__init__.py 22.1 KB
 Yannick Roehlly committed Feb 18, 2014 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 ``````# -*- coding: utf-8 -*- # Copyright (C) 2013 Centre de données Astrophysiques de Marseille # Copyright (C) 2013-2014 Yannick Roehlly # Licensed under the CeCILL-v2 licence - see Licence_CeCILL_V2-en.txt # Author: Yannick Roehlly """ Probability Density Function analysis module ============================================ This module builds the probability density functions (PDF) of the SED parameters to compute their moments. The models corresponding to all possible combinations of parameters are computed and their fluxes in the same filters as the observations are integrated. These fluxes are compared to the observed ones to compute the χ² value of the fitting. This χ² give a probability that is associated with the model values for the parameters. At the end, for each parameter, the probability-weighted mean and standard deviation are computed and the best fitting model (the one with the least reduced χ²) is given for each observation. """ import os import numpy as np `````` Yannick Roehlly committed Feb 19, 2014 28 ``````import matplotlib `````` Yannick Roehlly committed Feb 18, 2014 29 30 31 32 ``````from numpy import newaxis from collections import OrderedDict from datetime import datetime from progressbar import ProgressBar `````` Yannick Roehlly committed Feb 19, 2014 33 ``````from matplotlib import pyplot as plt `````` Yannick Roehlly committed Feb 18, 2014 34 35 36 ``````from astropy.table import Table, Column from ...utils import read_table from .. import AnalysisModule, complete_obs_table `````` Médéric Boquien committed Mar 11, 2014 37 ``````from .utils import gen_pdf, gen_best_sed_fig `````` Yannick Roehlly committed Feb 18, 2014 38 39 40 41 ``````from ...warehouse import SedWarehouse from ...data import Database # Tolerance threshold under which any flux or error is considered as 0. `````` Médéric Boquien committed Mar 11, 2014 42 ``````TOLERANCE = 1e-12 `````` Yannick Roehlly committed Feb 18, 2014 43 44 ``````# Probability threshold: models with a lower probability are excluded from # the moments computation. `````` Médéric Boquien committed Mar 11, 2014 45 ``````MIN_PROBABILITY = 1e-20 `````` Yannick Roehlly committed Mar 06, 2014 46 ``````# Limit the redshift to this number of decimals `````` Médéric Boquien committed Mar 11, 2014 47 ``````REDSHIFT_DECIMALS = 2 `````` Yannick Roehlly committed Feb 18, 2014 48 49 50 51 52 53 54 55 56 ``````# Name of the file containing the analysis results RESULT_FILE = "analysis_results.fits" # Name of the file containing the best models information BEST_MODEL_FILE = "best_models.fits" # Directory where the output files are stored OUT_DIR = "out/" # Wavelength limits (restframe) when plotting the best SED. PLOT_L_MIN = 91 PLOT_L_MAX = 1e6 `````` Yannick Roehlly committed Feb 19, 2014 57 58 ``````# Number of points in the PDF PDF_NB_POINTS = 1000 `````` Yannick Roehlly committed Feb 18, 2014 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 `````` class PdfAnalysis(AnalysisModule): """PDF analysis module""" parameter_list = OrderedDict([ ("analysed_variables", ( "array of strings", "List of the variables (in the SEDs info dictionaries) for which " "the statistical analysis will be done.", ["sfr", "average_sfr"] )), ("save_best_sed", ( "boolean", "If true, save the best SED for each observation to a file.", False )), ("plot_best_sed", ( "boolean", "If true, for each observation save a plot of the best SED " "and the observed fluxes.", False )), ("plot_chi2_distribution", ( "boolean", "If true, for each observation and each analysed variable " "plot the value vs reduced chi-square distribution.", False )), ("save_pdf", ( "boolean", "If true, for each observation and each analysed variable " "save the probability density function.", False )), ("plot_pdf", ( "boolean", "If true, for each observation and each analysed variable " "plot the probability density function.", False )), ("storage_type", ( "string", "Type of storage used to cache the generate SED.", "memory" )) ]) def process(self, data_file, column_list, creation_modules, creation_modules_params, parameters): """Process with the psum analysis. The analysis is done in two nested loops: over each observation and over each theoretical SEDs. We first loop over the SEDs to limit the number of time the SEDs are created. Parameters ---------- data_file: string Name of the file containing the observations to fit. column_list: list of strings Name of the columns from the data file to use for the analysis. creation_modules: list of strings List of the module names (in the right order) to use for creating the SEDs. creation_modules_params: list of dictionaries List of the parameter dictionaries for each module. parameters: dictionary Dictionary containing the parameters. """ `````` Yannick Roehlly committed Feb 19, 2014 131 132 133 `````` # To be sure matplotlib will not display the interactive window. matplotlib.interactive(0) `````` Yannick Roehlly committed Feb 18, 2014 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 `````` # Rename the output directory if it exists if os.path.exists(OUT_DIR): new_name = datetime.now().strftime("%Y%m%d%H%M") + "_" + OUT_DIR os.rename(OUT_DIR, new_name) print("The existing {} directory was renamed to {}".format( OUT_DIR, new_name )) os.mkdir(OUT_DIR) # Get the parameters analysed_variables = parameters["analysed_variables"] save_best_sed = (parameters["save_best_sed"].lower() == "true") plot_best_sed = (parameters["plot_best_sed"].lower() == "true") plot_chi2_distribution = ( parameters["plot_chi2_distribution"].lower() == "true") save_pdf = (parameters["save_pdf"].lower() == "true") plot_pdf = (parameters["plot_pdf"].lower() == "true") # Get the needed filters in the pcigale database. We use an ordered # dictionary because we need the keys to always be returned in the # same order. with Database() as base: filters = OrderedDict([(name, base.get_filter(name)) for name in column_list if not name.endswith('_err')]) # Read the observation table and complete it by adding error where # none is provided and by adding the systematic deviation. obs_table = complete_obs_table( read_table(data_file), column_list, filters, TOLERANCE ) ################################################################## # Model computation # ################################################################## print("Computing the models fluxes...") # First, we compute for all the possible theoretical models (one for # each parameter set in sed_module_parameters) the fluxes in all the `````` Médéric Boquien committed Mar 11, 2014 178 `````` # filters. These fluxes are stored in: `````` Yannick Roehlly committed Feb 18, 2014 179 180 181 `````` # model_fluxes: # - axis 0: model index `````` Médéric Boquien committed Mar 11, 2014 182 `````` # - axis 1: filter index `````` Yannick Roehlly committed Feb 18, 2014 183 184 `````` # We use a numpy masked array to mask the fluxes of models that would `````` Médéric Boquien committed Mar 11, 2014 185 `````` # be older than the age of the Universe at the considered redshift. `````` Yannick Roehlly committed Feb 18, 2014 186 187 188 189 190 191 192 `````` # The values for the analysed variables are stored in: # model_variables: # - axis 0: the model index in sed_module_params # - axis 1: the variable index in analysed_variables `````` Médéric Boquien committed Mar 11, 2014 193 194 195 `````` # For convenience, the redshift of each model is stored in # model_redshift. `````` 196 `````` model_fluxes = np.ma.empty((len(creation_modules_params), `````` Yannick Roehlly committed Feb 18, 2014 197 `````` len(filters))) `````` 198 `````` model_variables = np.ma.empty((len(creation_modules_params), `````` Yannick Roehlly committed Feb 18, 2014 199 200 `````` len(analysed_variables))) `````` Médéric Boquien committed Mar 11, 2014 201 202 `````` model_redshift = np.empty(len(creation_modules_params)) `````` Yannick Roehlly committed Feb 18, 2014 203 204 205 206 207 208 209 210 211 212 213 `````` # We keep the information (i.e. the content of the sed.info # dictionary) for each model. model_info = [] progress_bar = ProgressBar(maxval=len(creation_modules_params)).start() # The SED warehouse is used to retrieve SED corresponding to some # modules and parameters. with SedWarehouse(cache_type=parameters["storage_type"]) as \ sed_warehouse: `````` Yannick Roehlly committed Feb 19, 2014 214 215 `````` for model_index, model_params in enumerate( creation_modules_params): `````` Yannick Roehlly committed Feb 18, 2014 216 `````` `````` Yannick Roehlly committed Feb 19, 2014 217 `````` sed = sed_warehouse.get_sed(creation_modules, model_params) `````` Yannick Roehlly committed Feb 18, 2014 218 `````` `````` Médéric Boquien committed Mar 11, 2014 219 220 221 222 223 `````` model_fluxes[model_index, :] = np.array( [sed.compute_fnu(filter_.trans_table, filter_.effective_wavelength) for filter_ in filters.values()]) model_variables[model_index, :] = np.array( `````` Yannick Roehlly committed Feb 18, 2014 224 225 226 `````` [sed.info[name] for name in analysed_variables] ) `````` Médéric Boquien committed Mar 11, 2014 227 228 `````` model_redshift[model_index] = sed.info['redshift'] `````` Yannick Roehlly committed Feb 18, 2014 229 230 231 232 `````` model_info.append(sed.info.values()) progress_bar.update(model_index + 1) `````` Médéric Boquien committed Mar 11, 2014 233 234 `````` unique_redshifts = np.unique(model_redshift) `````` Yannick Roehlly committed Feb 18, 2014 235 `````` # Mask the invalid fluxes `````` Yannick Roehlly committed Feb 19, 2014 236 `````` model_fluxes = np.ma.masked_less(model_fluxes, -90) `````` Yannick Roehlly committed Feb 18, 2014 237 238 239 240 241 242 243 244 245 `````` progress_bar.finish() ################################################################## # Observations to models comparison # ################################################################## print("Comparing the observations to the models...") `````` Médéric Boquien committed Mar 11, 2014 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 `````` # As we are looping over all the observations we store data for the # output tables in various arrays analysed_averages_all = np.empty((len(obs_table), len(analysed_variables))) analysed_std_all = np.empty_like(analysed_averages_all) best_idx_all = np.empty(len(obs_table)) best_chi2_all = np.empty_like(best_idx_all) best_chi2_red_all = np.empty_like(best_idx_all) normalisation_factors_all = np.empty_like(best_idx_all) best_variables_all = [None]*len(obs_table) for idx_obs, obs in enumerate(obs_table): obs_fluxes = np.array([obs[name] for name in filters]) obs_errors = np.array([obs[name + "_err"] for name in filters]) # Some observations may not have flux value in some filters, in # that case the user is asked to put -9999 as value. We mask these # values. Note, we must mask obs_fluxes after obs_errors. obs_errors = np.ma.masked_where(obs_fluxes < -9990., obs_errors) obs_fluxes = np.ma.masked_less(obs_fluxes, -9990.) # We compute the χ² only for models with the closest redshift. We # extract model fluxes and information into arrays dedicated to a # given observation. closest_redshift = unique_redshifts[np.abs(obs["redshift"] - unique_redshifts).argmin()] w_models = model_redshift == closest_redshift model_fluxes_obs = model_fluxes[w_models, :] model_info_obs = np.array(model_info)[w_models] model_variables_obs = model_variables[w_models] # Normalisation factor to be applied to a model fluxes to best fit # an observation fluxes. Normalised flux of the models. χ² and # likelihood of the fitting. Reduced χ² (divided by the number of # filters to do the fit). normalisation_factors = ( np.sum( model_fluxes_obs * obs_fluxes / ( obs_errors * obs_errors), axis=1 ) / np.sum( model_fluxes_obs * model_fluxes_obs / ( obs_errors * obs_errors), axis=1) ) norm_model_fluxes = (model_fluxes_obs * normalisation_factors[:, np.newaxis]) # χ² of the comparison of each model to each observation. chi_squares = np.sum( np.square((obs_fluxes - norm_model_fluxes) / obs_errors), axis=1) # We define the reduced χ² as the χ² divided by the number of # fluxes used for the fitting. reduced_chi_squares = chi_squares / obs_fluxes.count() # We use the exponential probability associated with the χ² as # likelihood function. likelihood = np.exp(-chi_squares/2) # For the analysis, we consider that the computed models explain # each observation. We normalise the likelihood function to have a # total likelihood of 1 for each observation. likelihood /= np.sum(likelihood) # We don't want to take into account the models with a probability # less that the threshold. likelihood = np.ma.masked_less(likelihood, MIN_PROBABILITY) # We re-normalise the likelihood. likelihood /= np.sum(likelihood) # We take the mass-dependent variable list from the last computed # sed. for index, variable in enumerate(analysed_variables): if variable in sed.mass_proportional_info: model_variables_obs[:, index] *= normalisation_factors # We also add the galaxy mass to the analysed variables if relevant if sed.sfh is not None: analysed_variables.insert(0, "galaxy_mass") model_variables_obs = np.dstack((normalisation_factors, model_variables_obs)) ################################################################## # Variable analysis # ################################################################## print("Analysing the variables...") # We compute the weighted average and standard deviation using the # likelihood as weight. We first build the weight array by # expanding the likelihood along a new axis corresponding to the # analysed variable. weights = likelihood[:, newaxis].repeat(len(analysed_variables), axis=1) # Analysed variables average and standard deviation arrays. analysed_averages = np.ma.average(model_variables_obs, axis=0, weights=weights) analysed_std = np.ma.sqrt(np.ma.average( (model_variables_obs - analysed_averages[newaxis, :])**2, axis=0, weights=weights)) # We record the estimated averages and standard deviations to # save in a table later on when this has been computed for all # objects. analysed_averages_all[idx_obs, :] = analysed_averages analysed_std_all[idx_obs, :] = analysed_std ################################################################## # Best models # ################################################################## print("Analysing the best models...") # We define the best fitting model for each observation as the one # with the least χ². best_index = chi_squares.argmin() # We save the relevant data related to the model with the lowest # χ² best_idx_all[idx_obs] = best_index normalisation_factors_all[idx_obs] = \ normalisation_factors[best_index] best_chi2_all[idx_obs] = chi_squares[best_index] best_chi2_red_all[idx_obs] = reduced_chi_squares[best_index] best_variables_all[idx_obs] = list(model_info_obs[best_index]) if plot_best_sed or save_best_sed: print("Plotting/saving the best models...") with SedWarehouse(cache_type=parameters["storage_type"]) as \ sed_warehouse: `````` Yannick Roehlly committed Feb 19, 2014 380 381 382 `````` sed = sed_warehouse.get_sed( creation_modules, `````` Médéric Boquien committed Mar 11, 2014 383 `````` np.array(creation_modules_params)[w_models][best_index] `````` Yannick Roehlly committed Feb 19, 2014 384 385 386 `````` ) best_lambda = sed.wavelength_grid `````` Médéric Boquien committed Mar 11, 2014 387 `````` best_fnu = sed.fnu * normalisation_factors[best_index] `````` Yannick Roehlly committed Feb 19, 2014 388 389 `````` if save_best_sed: `````` Yannick Roehlly committed Feb 20, 2014 390 `````` sed.to_votable( `````` Médéric Boquien committed Mar 11, 2014 391 392 `````` OUT_DIR + "{}_best_model.xml".format(obs['id']), mass=normalisation_factors[best_index] `````` Yannick Roehlly committed Feb 20, 2014 393 `````` ) `````` Yannick Roehlly committed Feb 19, 2014 394 395 396 397 `````` if plot_best_sed: plot_mask = ( `````` Médéric Boquien committed Mar 11, 2014 398 399 400 `````` (best_lambda >= PLOT_L_MIN * (1 + obs["redshift"])) & (best_lambda <= PLOT_L_MAX * (1 + obs["redshift"])) `````` Yannick Roehlly committed Feb 19, 2014 401 402 403 404 405 406 `````` ) figure = gen_best_sed_fig( best_lambda[plot_mask], best_fnu[plot_mask], [f.effective_wavelength for f in filters.values()], `````` Médéric Boquien committed Mar 11, 2014 407 408 `````` norm_model_fluxes[best_index, :], [obs[f] for f in filters] `````` Yannick Roehlly committed Feb 19, 2014 409 410 411 412 `````` ) if figure is None: print("Can not plot best model for observation " `````` Médéric Boquien committed Mar 11, 2014 413 `````` "{}!".format(obs['id'])) `````` Yannick Roehlly committed Feb 19, 2014 414 415 416 `````` else: figure.suptitle( u"Best model for {} - red-chi² = {}".format( `````` Médéric Boquien committed Mar 11, 2014 417 418 `````` obs['id'], reduced_chi_squares[best_index] `````` Yannick Roehlly committed Feb 19, 2014 419 420 `````` ) ) `````` Médéric Boquien committed Mar 11, 2014 421 422 `````` figure.savefig(OUT_DIR + "{}_best_model.pdf".format (obs['id'])) `````` Yannick Roehlly committed Feb 19, 2014 423 424 `````` plt.close(figure) `````` Médéric Boquien committed Mar 11, 2014 425 426 427 `````` ################################################################## # Probability Density Functions # ################################################################## `````` Yannick Roehlly committed Feb 18, 2014 428 `````` `````` Médéric Boquien committed Mar 11, 2014 429 430 431 432 `````` # We estimate the probability density functions (PDF) of the # parameters using a weighted kernel density estimation. This part # should definitely be improved as we simulate the weight by adding # as many value as their probability * 100. `````` Yannick Roehlly committed Feb 18, 2014 433 `````` `````` Médéric Boquien committed Mar 11, 2014 434 `````` if save_pdf or plot_pdf: `````` Yannick Roehlly committed Feb 18, 2014 435 `````` `````` Médéric Boquien committed Mar 11, 2014 436 `````` print("Computing the probability density functions...") `````` Yannick Roehlly committed Feb 18, 2014 437 `````` `````` Yannick Roehlly committed Feb 19, 2014 438 `````` for var_index, var_name in enumerate(analysed_variables): `````` Yannick Roehlly committed Feb 18, 2014 439 `````` `````` Médéric Boquien committed Mar 11, 2014 440 `````` values = model_variables_obs[:, var_index] `````` Yannick Roehlly committed Feb 18, 2014 441 `````` `````` Yannick Roehlly committed Feb 19, 2014 442 443 `````` pdf_grid = np.linspace(values.min(), values.max(), PDF_NB_POINTS) `````` Médéric Boquien committed Mar 11, 2014 444 `````` pdf_prob = gen_pdf(values, likelihood, pdf_grid) `````` Yannick Roehlly committed Feb 18, 2014 445 `````` `````` Yannick Roehlly committed Feb 19, 2014 446 447 448 `````` if pdf_prob is None: # TODO: use logging print("Can not compute PDF for observation <{}> and " `````` Médéric Boquien committed Mar 11, 2014 449 `````` "variable <{}>.".format(obs['id'], var_name)) `````` Yannick Roehlly committed Feb 18, 2014 450 `````` `````` Yannick Roehlly committed Feb 19, 2014 451 452 453 `````` if save_pdf and pdf_prob is not None: table = Table(( Column(pdf_grid, name=var_name), `````` Yannick Roehlly committed Feb 19, 2014 454 `````` Column(pdf_prob, name="probability density") `````` Yannick Roehlly committed Feb 19, 2014 455 456 `````` )) table.write(OUT_DIR + "{}_{}_pdf.fits".format( `````` Médéric Boquien committed Mar 11, 2014 457 `````` obs['id'], var_name)) `````` Yannick Roehlly committed Feb 18, 2014 458 `````` `````` Yannick Roehlly committed Feb 19, 2014 459 460 461 462 463 `````` if plot_pdf and pdf_prob is not None: figure = plt.figure() ax = figure.add_subplot(111) ax.plot(pdf_grid, pdf_prob) ax.set_xlabel(var_name) `````` Yannick Roehlly committed Feb 19, 2014 464 `````` ax.set_ylabel("Probability density") `````` Yannick Roehlly committed Feb 19, 2014 465 `````` figure.savefig(OUT_DIR + "{}_{}_pdf.pdf".format( `````` Médéric Boquien committed Mar 11, 2014 466 `````` obs['id'], var_name)) `````` Yannick Roehlly committed Feb 19, 2014 467 `````` plt.close(figure) `````` Yannick Roehlly committed Feb 18, 2014 468 `````` `````` Médéric Boquien committed Mar 11, 2014 469 470 471 472 `````` ################################################################## # Reduced-chisquares plots # ################################################################## if plot_chi2_distribution: `````` Yannick Roehlly committed Feb 19, 2014 473 `````` `````` Médéric Boquien committed Mar 11, 2014 474 `````` print("Plotting the reduced chi squares distributions...") `````` Yannick Roehlly committed Feb 19, 2014 475 476 477 `````` for var_index, var_name in enumerate(analysed_variables): `````` Médéric Boquien committed Mar 11, 2014 478 `````` values = model_variables_obs[:, var_index] `````` Yannick Roehlly committed Feb 19, 2014 479 480 481 `````` figure = plt.figure() ax = figure.add_subplot(111) `````` Médéric Boquien committed Mar 11, 2014 482 `````` ax.plot(values, reduced_chi_squares, "ob") `````` Yannick Roehlly committed Feb 19, 2014 483 484 485 `````` ax.set_xlabel(var_name) ax.set_ylabel("reduced chi-square") figure.suptitle("Reduced chi-square distribution of {} " `````` Médéric Boquien committed Mar 11, 2014 486 487 `````` "values for {}".format(obs['id'], var_name)) `````` Yannick Roehlly committed Feb 19, 2014 488 `````` figure.savefig(OUT_DIR + "{}_{}_chisquares.pdf".format( `````` Médéric Boquien committed Mar 11, 2014 489 `````` obs['id'], var_name)) `````` Yannick Roehlly committed Feb 19, 2014 490 491 `````` plt.close(figure) `````` Médéric Boquien committed Mar 11, 2014 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 `````` # Create and save the result table. result_table = Table() result_table.add_column(Column( obs_table["id"].data, name="observation_id" )) for index, variable in enumerate(analysed_variables): result_table.add_column(Column( analysed_averages_all[:, index], name=variable )) result_table.add_column(Column( analysed_std_all[:, index], name=variable+"_err" )) result_table.write(OUT_DIR + RESULT_FILE) best_model_table = Table() best_model_table.add_column(Column( obs_table["id"].data, name="observation_id" )) best_model_table.add_column(Column( best_chi2_all, name="chi_square" )) best_model_table.add_column(Column( best_chi2_red_all, name="reduced_chi_square" )) if sed.sfh is not None: best_model_table.add_column(Column( normalisation_factors_all, name="galaxy_mass", unit="Msun" )) for index, name in enumerate(sed.info.keys()): column = Column([best_variables[index] for best_variables in best_variables_all], name=name) if name in sed.mass_proportional_info: column *= normalisation_factors_all best_model_table.add_column(column) best_model_table.write(OUT_DIR + BEST_MODEL_FILE) `````` Yannick Roehlly committed Feb 19, 2014 539 `````` `````` Yannick Roehlly committed Feb 18, 2014 540 541 ``````# AnalysisModule to be returned by get_module Module = PdfAnalysis``````