__init__.py 21.1 KB
Newer Older
1 2 3 4
# -*- coding: utf-8 -*-
# Copyright (C) 2013 Centre de données Astrophysiques de Marseille
# Copyright (C) 2013-2014 Yannick Roehlly
# Copyright (C) 2013 Institute of Astronomy
5
# Copyright (C) 2014 Laboratoire d'Astrophysique de Marseille
6
# Licensed under the CeCILL-v2 licence - see Licence_CeCILL_V2-en.txt
7
# Author: Yannick Roehlly, Médéric Boquien & Denis Burgarella
8 9

import argparse
10
import glob
11 12
from itertools import product, repeat
from collections import OrderedDict
13
import sys
14 15

from astropy.table import Table
16
import matplotlib
17

18
matplotlib.use('Agg')
19 20 21 22
import matplotlib.pyplot as plt
import multiprocessing as mp
import numpy as np
import os
23
import pkg_resources
24
from scipy.constants import c
25
from scipy import stats
26 27 28
from pcigale.data import Database
from pcigale.utils import read_table
from pcigale.session.configuration import Configuration
29
import matplotlib.gridspec as gridspec
30

Médéric Boquien's avatar
Médéric Boquien committed
31 32 33
__version__ = "0.1-alpha"


34
# Name of the file containing the best models information
35 36
BEST_RESULTS = "results.fits"
MOCK_RESULTS = "results_mock.fits"
37
# Wavelength limits (restframe) when plotting the best SED.
38
PLOT_L_MIN = 0.1
39
PLOT_L_MAX = 5e5
40 41 42 43 44 45 46 47 48 49 50 51 52


def _chi2_worker(obj_name, var_name):
    """Plot the reduced χ² associated with a given analysed variable

    Parameters
    ----------
    obj_name: string
        Name of the object.
    var_name: string
        Name of the analysed variable..

    """
53 54 55
    figure = plt.figure()
    ax = figure.add_subplot(111)

56
    var_name = var_name.replace('/', '_')
57 58
    fnames = glob.glob("out/{}_{}_chi2-block-*.npy".format(obj_name, var_name))
    for fname in fnames:
59 60 61
        data = np.memmap(fname, dtype=np.float64)
        data = np.memmap(fname, dtype=np.float64, shape=(2, data.size // 2))
        ax.scatter(data[1, :], data[0, :], color='k', s=.1)
62 63 64 65 66 67 68 69
    ax.set_xlabel(var_name)
    ax.set_ylabel("Reduced $\chi^2$")
    ax.set_ylim(0., )
    ax.minorticks_on()
    figure.suptitle("Reduced $\chi^2$ distribution of {} for {}."
                    .format(var_name, obj_name))
    figure.savefig("out/{}_{}_chi2.pdf".format(obj_name, var_name))
    plt.close(figure)
70 71 72 73 74 75 76 77 78 79 80 81 82


def _pdf_worker(obj_name, var_name):
    """Plot the PDF associated with a given analysed variable

    Parameters
    ----------
    obj_name: string
        Name of the object.
    var_name: string
        Name of the analysed variable..

    """
83
    var_name = var_name.replace('/', '_')
84 85 86 87 88 89 90 91
    if var_name.endswith('_log'):
        fnames = glob.glob("out/{}_{}_chi2-block-*.npy".format(obj_name,
                                                               var_name[:-4]))
        log = True
    else:
        fnames = glob.glob("out/{}_{}_chi2-block-*.npy".format(obj_name,
                                                               var_name))
        log = False
92 93 94
    likelihood = []
    model_variable = []
    for fname in fnames:
95 96 97
        data = np.memmap(fname, dtype=np.float64)
        data = np.memmap(fname, dtype=np.float64, shape=(2, data.size // 2))

98 99 100 101
        likelihood.append(np.exp(-data[0, :] / 2.))
        model_variable.append(data[1, :])
    likelihood = np.concatenate(likelihood)
    model_variable = np.concatenate(model_variable)
102 103
    if log is True:
        model_variable = np.log10(model_variable)
104 105 106
    w = np.where(np.isfinite(likelihood) & np.isfinite(model_variable))
    likelihood = likelihood[w]
    model_variable = model_variable[w]
107 108

    Npdf = 100
109 110
    min_hist = np.min(model_variable)
    max_hist = np.max(model_variable)
111 112 113 114 115
    Nhist = min(Npdf, len(np.unique(model_variable)))

    if min_hist == max_hist:
        pdf_grid = np.array([min_hist, max_hist])
        pdf_prob = np.array([1., 1.])
116
    else:
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
        pdf_prob, pdf_grid = np.histogram(model_variable, Nhist,
                                          (min_hist, max_hist),
                                          weights=likelihood, density=True)
        pdf_x = (pdf_grid[1:]+pdf_grid[:-1]) / 2.

        pdf_grid = np.linspace(min_hist, max_hist, Npdf)
        pdf_prob = np.interp(pdf_grid, pdf_x, pdf_prob)

    figure = plt.figure()
    ax = figure.add_subplot(111)
    ax.plot(pdf_grid, pdf_prob, color='k')
    ax.set_xlabel(var_name)
    ax.set_ylabel("Probability density")
    ax.minorticks_on()
    figure.suptitle("Probability distribution function of {} for {}"
                    .format(var_name, obj_name))
    figure.savefig("out/{}_{}_pdf.pdf".format(obj_name, var_name))
    plt.close(figure)
135 136


137
def _sed_worker(obs, mod, filters, sed_type, nologo):
138 139 140 141 142 143 144 145 146 147
    """Plot the best SED with the associated fluxes in bands

    Parameters
    ----------
    obs: Table row
        Data from the input file regarding one object.
    mod: Table row
        Data from the best model of one object.
    filters: ordered dictionary of Filter objects
        The observed fluxes in each filter.
148 149 150 151 152
    sed_type: string
        Type of SED to plot. It can either be "mJy" (flux in mJy and observed
        frame) or "lum" (luminosity in W and rest frame)
    nologo: boolean
        Do not add the logo when set to true.
153 154

    """
155

156
    if os.path.isfile("out/{}_best_model.fits".format(obs['id'])):
157

158
        sed = Table.read("out/{}_best_model.fits".format(obs['id']))
159

160
        filters_wl = np.array([filt.pivot_wavelength
161
                               for filt in filters.values()])
162
        wavelength_spec = sed['wavelength']
163
        obs_fluxes = np.array([obs[filt] for filt in filters.keys()])
164 165
        obs_fluxes_err = np.array([obs[filt+'_err']
                                   for filt in filters.keys()])
166
        mod_fluxes = np.array([mod["best."+filt] for filt in filters.keys()])
167 168 169 170
        if obs['redshift'] >= 0:
            z = obs['redshift']
        else:  # Redshift mode
            z = mod['best.universe.redshift']
171
        DL = mod['best.universe.luminosity_distance']
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189

        if sed_type == 'lum':
            xmin = PLOT_L_MIN
            xmax = PLOT_L_MAX

            k_corr_SED = 1e-29 * (4.*np.pi*DL*DL) * c / (filters_wl*1e-9)
            obs_fluxes *= k_corr_SED
            obs_fluxes_err *= k_corr_SED
            mod_fluxes *= k_corr_SED

            for cname in sed.colnames[1:]:
                sed[cname] *= wavelength_spec

            filters_wl /= 1. + z
            wavelength_spec /= 1. + z
        elif sed_type == 'mJy':
            xmin = PLOT_L_MIN * (1. + z)
            xmax = PLOT_L_MAX * (1. + z)
190
            k_corr_SED = 1.
191 192 193 194 195 196 197 198 199 200 201 202

            for cname in sed.colnames[1:]:
                sed[cname] *= (wavelength_spec * 1e29 /
                               (c / (wavelength_spec * 1e-9)) /
                               (4. * np.pi * DL * DL))
        else:
            print("Unknown plot type")

        filters_wl /= 1000.
        wavelength_spec /= 1000.

        wsed = np.where((wavelength_spec > xmin) & (wavelength_spec < xmax))
203
        figure = plt.figure()
204
        gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])
205 206 207 208 209
        if (sed.columns[1][wsed] > 0.).any():
            ax1 = plt.subplot(gs[0])
            ax2 = plt.subplot(gs[1])

            # Stellar emission
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
            if 'nebular.absorption_young' in sed.columns:
                ax1.loglog(wavelength_spec[wsed],
                           (sed['stellar.young'][wsed] +
                            sed['attenuation.stellar.young'][wsed] +
                            sed['nebular.absorption_young'][wsed] +
                            sed['stellar.old'][wsed] +
                            sed['attenuation.stellar.old'][wsed] +
                            sed['nebular.absorption_old'][wsed]),
                           label="Stellar attenuated ", color='orange',
                           marker=None, nonposy='clip', linestyle='-',
                           linewidth=0.5)
            else:
                ax1.loglog(wavelength_spec[wsed],
                           (sed['stellar.young'][wsed] +
                            sed['attenuation.stellar.young'][wsed] +
                            sed['stellar.old'][wsed] +
                            sed['attenuation.stellar.old'][wsed]),
                           label="Stellar attenuated ", color='orange',
                           marker=None, nonposy='clip', linestyle='-',
                           linewidth=0.5)
230 231 232 233 234
            ax1.loglog(wavelength_spec[wsed],
                       (sed['stellar.old'][wsed] +
                        sed['stellar.young'][wsed]),
                       label="Stellar unattenuated", color='b', marker=None,
                       nonposy='clip', linestyle='--', linewidth=0.5)
235
            # Nebular emission
236 237
            if 'nebular.lines_young' in sed.columns:
                ax1.loglog(wavelength_spec[wsed],
Médéric Boquien's avatar
Médéric Boquien committed
238 239 240 241 242 243 244 245 246 247
                           (sed['nebular.lines_young'][wsed] +
                            sed['nebular.lines_old'][wsed] +
                            sed['nebular.continuum_young'][wsed] +
                            sed['nebular.continuum_old'][wsed] +
                            sed['attenuation.nebular.lines_young'][wsed] +
                            sed['attenuation.nebular.lines_old'][wsed] +
                            sed['attenuation.nebular.continuum_young'][wsed] +
                            sed['attenuation.nebular.continuum_old'][wsed]),
                           label="Nebular emission", color='y', marker=None,
                           nonposy='clip', linewidth=.5)
248 249 250 251 252 253 254 255 256 257 258 259 260
            # Dust emission Draine & Li
            if 'dust.Umin_Umin' in sed.columns:
                ax1.loglog(wavelength_spec[wsed],
                           (sed['dust.Umin_Umin'][wsed] +
                            sed['dust.Umin_Umax'][wsed]),
                           label="Dust emission", color='r', marker=None,
                           nonposy='clip', linestyle='-', linewidth=0.5)
            # Dust emission Dale
            if 'dust' in sed.columns:
                ax1.loglog(wavelength_spec[wsed], sed['dust'][wsed],
                           label="Dust emission", color='r', marker=None,
                           nonposy='clip', linestyle='-', linewidth=0.5)
            # AGN emission Fritz
261
            if 'agn.fritz2006_therm' in sed.columns:
262
                ax1.loglog(wavelength_spec[wsed],
263 264 265
                           (sed['agn.fritz2006_therm'][wsed] +
                            sed['agn.fritz2006_scatt'][wsed] +
                            sed['agn.fritz2006_agn'][wsed]),
266 267 268 269 270 271 272 273 274 275
                           label="AGN emission", color='g', marker=None,
                           nonposy='clip', linestyle='-', linewidth=0.5)
            # Radio emission
            if 'radio_nonthermal' in sed.columns:
                ax1.loglog(wavelength_spec[wsed],
                           sed['radio_nonthermal'][wsed],
                           label="Radio nonthermal", color='brown',
                           marker=None, nonposy='clip', linestyle='-',
                           linewidth=0.5)

276
            ax1.loglog(wavelength_spec[wsed], sed['L_lambda_total'][wsed],
277
                       label="Model spectrum", color='k', nonposy='clip',
278
                       linestyle='-', linewidth=1.5)
279 280

            ax1.set_autoscale_on(False)
281 282 283 284 285
            s = np.argsort(filters_wl)
            filters_wl = filters_wl[s]
            mod_fluxes = mod_fluxes[s]
            obs_fluxes = obs_fluxes[s]
            obs_fluxes_err = obs_fluxes_err[s]
286
            ax1.scatter(filters_wl, mod_fluxes, marker='o', color='r', s=8,
287
                        zorder=3, label="Model fluxes")
288 289 290 291 292 293 294
            mask_ok = np.logical_and(obs_fluxes > 0., obs_fluxes_err > 0.)
            ax1.errorbar(filters_wl[mask_ok], obs_fluxes[mask_ok],
                         yerr=obs_fluxes_err[mask_ok]*3, ls='', marker='s',
                         label='Observed fluxes', markerfacecolor='None',
                         markersize=6, markeredgecolor='b', capsize=0.)
            mask_uplim = np.logical_and(np.logical_and(obs_fluxes > 0.,
                                                       obs_fluxes_err < 0.),
295
                                        obs_fluxes_err > -9990. * k_corr_SED)
296 297
            if not mask_uplim.any() == False:
                ax1.errorbar(filters_wl[mask_uplim], obs_fluxes[mask_uplim],
298
                             yerr=obs_fluxes_err[mask_uplim]*3, ls='',
299 300
                             marker='v', label='Observed upper limits',
                             markerfacecolor='None', markersize=6,
301
                             markeredgecolor='g', capsize=0.)
302
            mask_noerr = np.logical_and(obs_fluxes > 0.,
303
                                        obs_fluxes_err < -9990. * k_corr_SED)
304 305 306
            if not mask_noerr.any() == False:
                ax1.errorbar(filters_wl[mask_noerr], obs_fluxes[mask_noerr],
                             ls='', marker='s', markerfacecolor='None',
307
                             markersize=6, markeredgecolor='r',
308 309 310 311 312 313 314 315 316 317 318 319 320
                             label='Observed fluxes, no errors', capsize=0.)
            mask = np.where(obs_fluxes > 0.)
            ax2.errorbar(filters_wl[mask],
                         (obs_fluxes[mask]-mod_fluxes[mask])/obs_fluxes[mask],
                         yerr=obs_fluxes_err[mask]/obs_fluxes[mask]*3,
                         marker='_', label="(Obs-Mod)/Obs", color='k',
                         capsize=0.)
            ax2.plot([xmin, xmax], [0., 0.], ls='--', color='k')
            ax2.set_xscale('log')
            ax2.minorticks_on()

            figure.subplots_adjust(hspace=0., wspace=0.)

321
            ax1.set_xlim(xmin, xmax)
322 323
            ymin = min(np.min(obs_fluxes[mask_ok]),
                       np.min(mod_fluxes[mask_ok]))
324
            if not mask_uplim.any() == False:
Médéric Boquien's avatar
Médéric Boquien committed
325 326 327 328
                ymax = max(max(np.max(obs_fluxes[mask_ok]),
                               np.max(obs_fluxes[mask_uplim])),
                           max(np.max(mod_fluxes[mask_ok]),
                               np.max(mod_fluxes[mask_uplim])))
329
            else:
Médéric Boquien's avatar
Médéric Boquien committed
330 331
                ymax = max(np.max(obs_fluxes[mask_ok]),
                           np.max(mod_fluxes[mask_ok]))
332
            ax1.set_ylim(1e-1*ymin, 1e1*ymax)
333
            ax2.set_xlim(xmin, xmax)
334 335 336 337 338 339 340 341 342 343 344 345 346 347
            ax2.set_ylim(-1.0, 1.0)
            if sed_type == 'lum':
                ax2.set_xlabel("Rest-frame wavelength [$\mu$m]")
                ax1.set_ylabel("Luminosity [W]")
                ax2.set_ylabel("Relative residual luminosity")
            else:
                ax2.set_xlabel("Observed wavelength [$\mu$m]")
                ax1.set_ylabel("Flux [mJy]")
                ax2.set_ylabel("Relative residual flux")
            ax1.legend(fontsize=6, loc='best', fancybox=True, framealpha=0.5)
            ax2.legend(fontsize=6, loc='best', fancybox=True, framealpha=0.5)
            plt.setp(ax1.get_xticklabels(), visible=False)
            plt.setp(ax1.get_yticklabels()[1], visible=False)
            figure.suptitle("Best model for {} at z = {}. Reduced $\chi^2$={}".
348
                            format(obs['id'], np.round(z, decimals=3),
349
                                   np.round(mod['best.reduced_chi_square'],
350 351 352 353 354 355
                                            decimals=2)))
            if nologo is False:
                image = plt.imread(pkg_resources.resource_filename(__name__,
                                   "data/CIGALE.png"))
                figure.figimage(image, 75, 330, origin='upper', zorder=10,
                                alpha=1)
356
            figure.savefig("out/{}_best_model.pdf".format(obs['id']))
357
            plt.close(figure)
358
        else:
359 360
            print("No valid best SED found for {}. No plot created.".
                  format(obs['id']))
361
    else:
362 363 364
        print("No SED found for {}. No plot created.".format(obs['id']))


365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
def _mock_worker(exact, estimated, param, nologo):
    """Plot the exact and estimated values of a parameter for the mock analysis

    Parameters
    ----------
    exact: Table column
        Exact values of the parameter.
    estimated: Table column
        Estimated values of the parameter.
    param: string
        Name of the parameter
    nologo: boolean
        Do not add the logo when set to true.

    """

    range_exact = np.linspace(np.min(exact), np.max(exact), 100)

    # We compute the linear regression
    if (np.min(exact) < np.max(exact)):
        slope, intercept, r_value, p_value, std_err = stats.linregress(exact,
                                                                       estimated)
    else:
        slope = 0.0
        intercept = 1.0
        r_value = 0.0

    plt.errorbar(exact, estimated, marker='.', label=param, color='k',
                 linestyle='None', capsize=0.)
    plt.plot(range_exact, range_exact, color='r', label='1-to-1')
    plt.plot(range_exact, slope * range_exact + intercept, color='b',
             label='exact-fit $r^2$ = {:.2f}'.format(r_value**2))
    plt.xlabel('Exact')
    plt.ylabel('Estimated')
    plt.title(param)
    plt.legend(loc='best', fancybox=True, framealpha=0.5, numpoints=1)
    plt.minorticks_on()
    if nologo is False:
        image = plt.imread(pkg_resources.resource_filename(__name__,
                                                           "data/CIGALE.png"))
        plt.figimage(image, 510, 55, origin='upper', zorder=10, alpha=1)

    plt.tight_layout()
Médéric Boquien's avatar
Médéric Boquien committed
408
    plt.savefig('out/mock_{}.pdf'.format(param.replace('/', '_')))
409 410 411 412

    plt.close()


413 414 415 416
def chi2(config):
    """Plot the χ² values of analysed variables.
    """
    input_data = read_table(config.configuration['data_file'])
417
    chi2_vars = config.configuration['analysis_params']['variables']
418 419
    chi2_vars += [band for band in config.configuration['bands']
                  if band.endswith('_err') is False]
420 421 422 423 424 425

    with mp.Pool(processes=config.configuration['cores']) as pool:
        items = product(input_data['id'], chi2_vars)
        pool.starmap(_chi2_worker, items)
        pool.close()
        pool.join()
426 427 428 429 430 431


def pdf(config):
    """Plot the PDF of analysed variables.
    """
    input_data = read_table(config.configuration['data_file'])
432
    pdf_vars = config.configuration['analysis_params']['variables']
433 434
    pdf_vars += [band for band in config.configuration['bands']
                 if band.endswith('_err') is False]
435

436
    with mp.Pool(processes=config.configuration['cores']) as pool:
437 438 439 440 441 442
        items = product(input_data['id'], pdf_vars)
        pool.starmap(_pdf_worker, items)
        pool.close()
        pool.join()


443
def sed(config, sed_type, nologo):
444 445 446
    """Plot the best SED with associated observed and modelled fluxes.
    """
    obs = read_table(config.configuration['data_file'])
447
    mod = Table.read('out/' + BEST_RESULTS)
448

449 450
    with Database() as base:
        filters = OrderedDict([(name, base.get_filter(name))
451
                               for name in config.configuration['bands']
452
                               if not (name.endswith('_err') or name.startswith('line')) ])
453

454
    with mp.Pool(processes=config.configuration['cores']) as pool:
455 456
        pool.starmap(_sed_worker, zip(obs, mod, repeat(filters),
                                      repeat(sed_type), repeat(nologo)))
457 458 459 460
        pool.close()
        pool.join()


461 462 463 464 465
def mock(config, nologo):
    """Plot the comparison of input/output values of analysed variables.
    """

    try:
466
        exact = Table.read('out/' + BEST_RESULTS)
467
    except FileNotFoundError:
468
        print("Best models file {} not found.".format('out/' + BEST_RESULTS))
469 470 471
        sys.exit(1)

    try:
472
        estimated = Table.read('out/' + MOCK_RESULTS)
473
    except FileNotFoundError:
474
        print("Mock models file {} not found.".format('out/' + MOCK_RESULTS))
475 476
        sys.exit(1)

477
    params = config.configuration['analysis_params']['variables']
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492

    for param in params:
        if param.endswith('_log'):
            param = "best."+param
            exact[param] = np.log10(exact[param[:-4]])

    arguments = ((exact["best."+param], estimated["bayes."+param], param, nologo)
                 for param in params)

    with mp.Pool(processes=config.configuration['cores']) as pool:
        pool.starmap(_mock_worker, arguments)
        pool.close()
        pool.join()


493 494
def main():

495 496 497 498 499 500
    if sys.version_info[:2] >= (3, 4):
        mp.set_start_method('spawn')
    else:
        print("Could not set the multiprocessing start method to spawn. If "
              "you encounter a deadlock, please upgrade to Python≥3.4.")

501 502 503 504 505 506 507 508 509 510 511 512 513 514
    parser = argparse.ArgumentParser()

    parser.add_argument('-c', '--conf-file', dest='config_file',
                        help="Alternative configuration file to use.")

    subparsers = parser.add_subparsers(help="List of commands")

    pdf_parser = subparsers.add_parser('pdf', help=pdf.__doc__)
    pdf_parser.set_defaults(parser='pdf')

    chi2_parser = subparsers.add_parser('chi2', help=chi2.__doc__)
    chi2_parser.set_defaults(parser='chi2')

    sed_parser = subparsers.add_parser('sed', help=sed.__doc__)
515 516
    sed_parser.add_argument('--type', default='mJy')
    sed_parser.add_argument('--nologo', action="store_true")
517 518
    sed_parser.set_defaults(parser='sed')

519 520 521 522
    sed_parser = subparsers.add_parser('mock', help=mock.__doc__)
    sed_parser.add_argument('--nologo', action="store_true")
    sed_parser.set_defaults(parser='mock')

523 524 525 526 527 528 529
    args = parser.parse_args()

    if args.config_file:
        config = Configuration(args.config_file)
    else:
        config = Configuration()

530 531 532 533 534 535 536 537 538 539 540
    if len(sys.argv) == 1:
        parser.print_usage()
    else:
        if args.parser == 'chi2':
            chi2(config)
        elif args.parser == 'pdf':
            pdf(config)
        elif args.parser == 'sed':
            sed(config, args.type, args.nologo)
        elif args.parser == 'mock':
            mock(config, args.nologo)