configuration.py 13.8 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
3
# Copyright (C) 2012, 2013 Centre de données Astrophysiques de Marseille
# Licensed under the CeCILL-v2 licence - see Licence_CeCILL_V2-en.txt
Yannick Roehlly's avatar
Yannick Roehlly committed
4
# Author: Yannick Roehlly
5
6

import pkgutil
7
from collections import Iterable, OrderedDict
8
import multiprocessing as mp
9
from textwrap import wrap
10
11
12
13
14
15

import configobj
from glob import glob  # To allow the use of glob() in "eval..."
import pkg_resources
import numpy as np

16
from ..data import Database
17
from ..utils import read_table
18
19
from .. import creation_modules
from .. import analysis_modules
20

21
22
23
# Limit the redshift to this number of decimals
REDSHIFT_DECIMALS = 2

24
25
26
27

def list_modules(package_name):
    """Lists the modules available in a package

Yannick Roehlly's avatar
Yannick Roehlly committed
28
    Parameters
29
    ----------
30
    package_name: string
31
        Name of the package (e.g. pcigale.creation_modules).
32
33
34

    Returns
    -------
35
    module_name: array of strings
36
37
38
39
40
41
42
43
44
        List of the available modules.

    """
    directory = pkg_resources.resource_filename(package_name, '')
    module_names = [name for _, name, _ in pkgutil.iter_modules([directory])]

    return module_names


Yannick Roehlly's avatar
Yannick Roehlly committed
45
46
47
48
49
50
def evaluate_description(description):
    """Evaluate a description from the config file as a list.

    The description is read from the config file by configobj that transforms
    coma separated value in a list. From this description, this function try
    to evaluate the desired list of values:
51
52
53
    - If the description is a string beginning with 'eval ', then its content
      (without 'eval ') is evaluated as Python code and its result returned.
      An array is expected.
54
55
56
    - If the description is a string beginning by 'range', the start, step and
      stop values are then expected and the range is evaluated (stop included
      if reached.
Yannick Roehlly's avatar
Yannick Roehlly committed
57
58
    - Then the function tries to evaluate the description as a Numpy array of
      float and returns the mere list if this fails.
59

Yannick Roehlly's avatar
Yannick Roehlly committed
60
    Parameters
61
    ----------
62
    description: string or list
63
64
65
66
        The description to be evaluated.

    Returns
    -------
67
     results: list
Yannick Roehlly's avatar
Yannick Roehlly committed
68
        The evaluated list of values.
69
70

    """
71
72
73
74
75
    results = description
    if type(description) == str:
        if description.startswith('eval '):
            results = eval(description[4:])
            # If the evaluation lead to a single value, we put it in a list.
76
            if not isinstance(results, Iterable):
77
78
79
80
81
82
83
84
                results = [results]
        elif description.startswith('range '):
            start, stop, step = [float(item) for item
                                 in description[5:].split()]
            results = np.arange(start, stop+step, step)
        else:
            # We need to return a list to combine the list of possible values
            # for each parameter.
85
            results = [results]
86
87
88
89
90
91
92

    # We prefer to evaluate the parameter as a numpy array of floats if
    # possible.
    try:
        results = np.array(results, float)
    except ValueError:
        pass
93

Yannick Roehlly's avatar
Yannick Roehlly committed
94
    return results
95
96
97
98
99
100
101
102
103


class Configuration(object):
    """This class manages the configuration of pcigale.
    """

    def __init__(self, filename="pcigale.ini"):
        """Initialise a pcigale configuration.

Yannick Roehlly's avatar
Yannick Roehlly committed
104
        Parameters
105
        ----------
106
        filename: string
107
108
109
110
111
            Name of the configuration file (pcigale.conf by default).

        """
        self.config = configobj.ConfigObj(filename,
                                          write_empty_values=True,
112
113
                                          indent_type='  ',
                                          encoding='UTF8')
114
115
116
117
118
119
120
121
122
123
124
125

    def create_blank_conf(self):
        """Create the initial configuration file

        Write the initial pcigale configuration file where the user can state
        which data file to use, which modules to use for the SED creation, as
        well as the method selected for statistical analysis.

        """

        self.config['data_file'] = ""
        self.config.comments['data_file'] = wrap(
126
127
128
129
130
131
            "File containing the input data. The columns are 'id' (name of the"
            " object), 'redshift' (if 0 the distance is assumed to be 10 pc), "
            "the filter names for the fluxes, and the filter names with the "
            "'_err' suffix for the uncertainties. The fluxes and the "
            "uncertainties must be in mJy. This file is optional to generate "
            "the configuration file, in particular for the savefluxes module.")
132

133
        self.config['creation_modules'] = []
134
135
136
137
138
139
140
141
142
143
        self.config.comments['creation_modules'] = ([""] +
            ["Order of the modules use for SED creation. Available modules:"] +
            ["SFH: sfh2exp, sfhdelayed, sfhfromfile, sfhperiodic"] +
            ["SSP: bc03, m2005"] +
            ["Nebular emission: nebular"] +
            ["Dust attenuation: dustatt_calzleit, dustatt_powerlaw"] +
            ["Dust emission: casey2012, dale2014, dl2007, dl2014"] +
            ["AGN: dale2014, fritz2006"] +
            ["Radio: radio"] +
            ["Redshift: redshifting (mandatory!)"])
144
145
146
147

        self.config['analysis_method'] = ""
        self.config.comments['analysis_method'] = [""] + wrap(
            "Method used for statistical analysis. Available methods: "
148
            "pdf_analysis, savefluxes.")
149

150
151
152
153
154
        self.config['cores'] = ""
        self.config.comments['cores'] = [""] + wrap(
            "Number of CPU cores available. This computer has {} cores."
            .format(mp.cpu_count()))

155
156
157
158
159
160
161
162
163
164
165
166
        self.config.write()

    def generate_conf(self):
        """Generate the full configuration file

        Reads the user entries in the initial configuration file and add the
        configuration options of all selected modules as well as the filter
        selection based on the filters identified in the data table file.

        """

        # Getting the list of the filters available in pcigale database
167
        with Database() as base:
168
            filter_list = base.get_filter_names()
169

170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
        if self.config['data_file'] != '':
            obs_table = read_table(self.config['data_file'])

            # Check that the id and redshift columns are present in the input
            # file
            if 'id' not in obs_table.columns:
                raise Exception("Column id not present in input file")
            if 'redshift' not in obs_table.columns:
                raise Exception("Column redshift not present in input file")

            # Finding the known filters in the data table
            column_list = []
            for column in obs_table.columns:
                filter_name = column[:-4] if column.endswith('_err') else column
                if filter_name in filter_list:
                    column_list.append(column)

            # Check that we don't have an error column without the associated
            # flux
            for column in column_list:
Médéric Boquien's avatar
Médéric Boquien committed
190
191
                if column.endswith('_err') and (column[:-4]
                                                not in column_list):
192
193
                    raise Exception("The observation table as a {} column "
                                    "but no {} column.".format(column,
Médéric Boquien's avatar
Médéric Boquien committed
194
                                                               column[:-4]))
195
196
197
198

            self.config['column_list'] = column_list
        else:
            self.config['column_list'] = ''
199
200
201
202
203
        self.config.comments['column_list'] = [""] + wrap(
            "List of the columns in the observation data file to use for "
            "the fitting.")

        # SED creation modules configurations. For each module, we generate
Yannick Roehlly's avatar
Yannick Roehlly committed
204
        # the configuration section from its parameter list.
205
206
207
208
        self.config['sed_creation_modules'] = {}
        self.config.comments['sed_creation_modules'] = ["", ""] + wrap(
            "Configuration of the SED creation modules.")

209
        for module_name in self.config['creation_modules']:
210
211
212
            self.config["sed_creation_modules"][module_name] = {}
            sub_config = self.config["sed_creation_modules"][module_name]

213
            for name, (typ, description, default) in \
214
215
216
                    creation_modules.get_module(
                        module_name,
                        blank=True).parameter_list.items():
217
218
219
220
221
222
                if default is None:
                    default = ''
                sub_config[name] = default
                sub_config.comments[name] = wrap(description)

            self.config['sed_creation_modules'].comments[module_name] = [
223
                creation_modules.get_module(module_name, blank=True).comments]
224

225
226
        self.check_modules()

227
228
229
230
231
        # Configuration for the analysis method
        self.config['analysis_configuration'] = {}
        self.config.comments['analysis_configuration'] = ["", ""] + wrap(
            "Configuration of the statistical analysis method.")
        module_name = self.config['analysis_method']
232
        for name, (typ, desc, default) in \
233
                analysis_modules.get_module(module_name).parameter_list.items():
234
235
236
237
238
239
            if default is None:
                default = ''
            self.config['analysis_configuration'][name] = default
            self.config['analysis_configuration'].comments[name] = wrap(desc)

        self.config.write()
Yannick Roehlly's avatar
Yannick Roehlly committed
240

241
242
    @property
    def configuration(self):
Yannick Roehlly's avatar
Yannick Roehlly committed
243
        """Returns a dictionary for the session configuration.
Yannick Roehlly's avatar
Yannick Roehlly committed
244
245
246

        Returns
        -------
247
        configuration['data_file']: string
Yannick Roehlly's avatar
Yannick Roehlly committed
248
            File containing the observations to fit.
249
        configuration['column_list']: list of strings
Yannick Roehlly's avatar
Yannick Roehlly committed
250
            List of the columns of data_file to use in the fitting.
251
        configuration['creation_modules']: list of strings
Yannick Roehlly's avatar
Yannick Roehlly committed
252
            List of the modules (in the right order) used to create the SEDs.
253
        configuration['creation_modules_params']: list of dictionaries
Yannick Roehlly's avatar
Yannick Roehlly committed
254
255
            Configuration parameters for each module. To each parameter, the
            dictionary associates a list of possible values (possibly only
Yannick Roehlly's avatar
Yannick Roehlly committed
256
            one).
257
        configuration['analysis_method']: string
Yannick Roehlly's avatar
Yannick Roehlly committed
258
            Statistical analysis module used to fit the data.
259
        configuration['analysis_method_params']: dictionary
Yannick Roehlly's avatar
Yannick Roehlly committed
260
            Parameters for the statistical analysis module. To each parameter
Yannick Roehlly's avatar
Yannick Roehlly committed
261
262
263
264
            is associated a list of possible values.
        """
        configuration = {}

265
266
267
268
        # Before building the configuration dictionary, we ensure that all the
        # fields are filled
        self.complete_conf()

269
        for section in ['data_file', 'column_list', 'creation_modules',
270
                        'analysis_method']:
Yannick Roehlly's avatar
Yannick Roehlly committed
271
            configuration[section] = self.config[section]
272
        configuration['cores'] = int(self.config['cores'])
Yannick Roehlly's avatar
Yannick Roehlly committed
273

Yannick Roehlly's avatar
Yannick Roehlly committed
274
        # Parsing the SED modules parameters
275
276
        configuration['creation_modules_params'] = []
        for module in self.config['creation_modules']:
277
            module_params = {}
Yannick Roehlly's avatar
Yannick Roehlly committed
278
279
            for key, value in \
                    self.config['sed_creation_modules'][module].items():
Yannick Roehlly's avatar
Yannick Roehlly committed
280
                module_params[key] = evaluate_description(value)
281
            configuration['creation_modules_params'].append(module_params)
282
283

        # Analysis method parameters
284
285
        configuration['analysis_method_params'] = \
            self.config['analysis_configuration']
Yannick Roehlly's avatar
Yannick Roehlly committed
286
287

        return configuration
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307

    def check_modules(self):
        """Make a basic check to ensure that some required modules are present.
        Otherwise we emit a warning so the user knows their list of modules is
        suspicious. We do not emit an exception as they may be using an
        unofficial module that is not in our list
        """

        modules = OrderedDict((('SFH', ['sfh2exp', 'sfhdelayed', 'sfhfromfile',
                                        'sfhperiodic']),
                               ('SSP', ['bc03', 'm2005']),
                               ('nebular', ['nebular']),
                               ('dust attenuation', ['dustatt_calzleit',
                                                     'dustatt_powerlaw']),
                               ('dust emission', ['casey2012', 'dale2014',
                                                  'dl2007', 'dl2014']),
                               ('AGN', ['dale2014', 'fritz2006']),
                               ('radio', ['radio']),
                               ('redshift', ['redshifting'])))

Médéric Boquien's avatar
Médéric Boquien committed
308
309
        comments = {'SFH': "ERROR! Choosing one SFH module is mandatory.",
                    'SSP': "ERROR! Choosing one SSP module is mandatory.",
310
311
312
313
                    'nebular': "WARNING! Choosing the nebular module is "
                               "recommended. Without it the Lyman continuum "
                               "is left untouched.",
                    'dust attenuation': "No dust attenuation module found.",
314
                    'dust emission': "No dust emission module found.",
315
316
                    'AGN': "No AGN module found.",
                    'radio': "No radio module found.",
Médéric Boquien's avatar
Médéric Boquien committed
317
                    'redshift': "ERROR! No redshifting module found."}
318
319
320
321
322
323

        for module in modules:
            if all([user_module not in modules[module] for user_module in
                    self.config['creation_modules']]):
                print("{} Options are: {}.".
                      format(comments[module], ', '.join(modules[module])))
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340

    def complete_conf(self):
        """Complete the configuration when there is missing information that is
        to be extracted from other sources such as the input file (redshifts)
        or the output parameters (single run)
        """

        z_mod = self.config['sed_creation_modules']['redshifting']['redshift']
        if type(z_mod) is str and not z_mod:
            if self.config['data_file']:
                obs_table = read_table(self.config['data_file'])
                z = np.unique(np.around(obs_table['redshift'],
                                        decimals=REDSHIFT_DECIMALS))
                self.config['sed_creation_modules']['redshifting']['redshift'] = z
            else:
                raise Exception("No flux file and no redshift indicated. "
                                "The spectra cannot be computed. Aborting.")