__init__.py 13.6 KB
Newer Older
Yannick Roehlly's avatar
Yannick Roehlly committed
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
Yannick Roehlly's avatar
Yannick Roehlly committed
5

6
"""
Yannick Roehlly's avatar
Yannick Roehlly committed
7
8
This class represents a Spectral Energy Distribution (SED) as used by pcigale.
Such SED is characterised by:
Yannick Roehlly's avatar
Yannick Roehlly committed
9

10
- sfh: the Star Formation History of the galaxy.
Yannick Roehlly's avatar
Yannick Roehlly committed
11

Yannick Roehlly's avatar
Yannick Roehlly committed
12
13
- modules: a list of tuples (module name, parameter dictionary) containing all
  the pcigale modules the SED 'went through'.
Yannick Roehlly's avatar
Yannick Roehlly committed
14

Yannick Roehlly's avatar
Yannick Roehlly committed
15
- wavelength_grid: the grid of wavelengths [nm] used for the luminosities.
Yannick Roehlly's avatar
Yannick Roehlly committed
16

Yannick Roehlly's avatar
Yannick Roehlly committed
17
18
- contribution_names: the list of the names of the luminosity contributions
  making part of the SED.
Yannick Roehlly's avatar
Yannick Roehlly committed
19

Yannick Roehlly's avatar
Yannick Roehlly committed
20
21
22
23
- luminosities: a two axis numpy array containing all the luminosity density
  [W/nm] contributions to the SED. The index in the first axis corresponds to
  the contribution (in the contribution_names list) and the index of the
  second axis corresponds to the wavelength in the wavelength grid.
Yannick Roehlly's avatar
Yannick Roehlly committed
24

Yannick Roehlly's avatar
Yannick Roehlly committed
25
- info: a dictionary containing various information about the SED.
Yannick Roehlly's avatar
Yannick Roehlly committed
26

27
- mass_proportional_info: the set of keys in the info dictionary whose value
Yannick Roehlly's avatar
Yannick Roehlly committed
28
  is proportional to the galaxy mass.
Yannick Roehlly's avatar
Yannick Roehlly committed
29

Yannick Roehlly's avatar
Yannick Roehlly committed
30
"""
Yannick Roehlly's avatar
Yannick Roehlly committed
31

Yannick Roehlly's avatar
Yannick Roehlly committed
32
import numpy as np
33
34
from scipy.constants import c, parsec

Yannick Roehlly's avatar
Yannick Roehlly committed
35
from . import utils
36
from .io.vo import save_sed_to_vo
37
from .io.fits import save_sed_to_fits
38
39
from ..data import Database

Yannick Roehlly's avatar
Yannick Roehlly committed
40

Yannick Roehlly's avatar
Yannick Roehlly committed
41
42
class SED(object):
    """Spectral Energy Distribution with associated information
Yannick Roehlly's avatar
Yannick Roehlly committed
43
44
    """

45
46
47
48
    # We declare the filters cache here as to be efficient it needs to be
    # shared between different objects.
    cache_filters = {}

Yannick Roehlly's avatar
Yannick Roehlly committed
49
50
51
52
53
    def __init__(self, sfh=None):
        """Create a new SED

        Parameters
        ----------
54
        sfh: (numpy.array, numpy.array)
Yannick Roehlly's avatar
Yannick Roehlly committed
55
56
57
58
59
60
            Star Formation History: tuple of two numpy array, the first is the
            time in Myr and the second is the Star Formation Rate in Msun/yr.
            If no SFH is given, it's set to None.

        """
        self.sfh = sfh
Yannick Roehlly's avatar
Yannick Roehlly committed
61
62
63
        self.modules = []
        self.wavelength_grid = None
        self.contribution_names = []
64
        self.luminosity = None
Yannick Roehlly's avatar
Yannick Roehlly committed
65
        self.luminosities = None
66
        self.info = dict()
67
        self.mass_proportional_info = set()
Yannick Roehlly's avatar
Yannick Roehlly committed
68

Yannick Roehlly's avatar
Yannick Roehlly committed
69
70
71
72
73
74
75
76
77
78
79
    @property
    def sfh(self):
        """Return a copy of the star formation history
        """
        if self._sfh is None:
            return None
        else:
            return np.copy(self._sfh)

    @sfh.setter
    def sfh(self, value):
Yannick Roehlly's avatar
Yannick Roehlly committed
80
81
82
83

        # The SFH can be set multiple times. Maybe it's better to make is
        # settable only once and then provide an update_sfh method for when
        # it's needed.
Yannick Roehlly's avatar
Yannick Roehlly committed
84
85
        self._sfh = value

86
87
        if value is not None:
            sfh_sfr = value
88
            self._sfh = value
Yannick Roehlly's avatar
Yannick Roehlly committed
89
90
91
92
93
            self.add_info("sfh.sfr", sfh_sfr[-1], True, force=True)
            self.add_info("sfh.sfr10Myrs", np.mean(sfh_sfr[-10:]), True,
                          force=True)
            self.add_info("sfh.sfr100Myrs", np.mean(sfh_sfr[-100:]), True,
                          force=True)
94
            self.add_info("sfh.age", sfh_sfr.size, False, force=True)
95

96
97
98
    @property
    def fnu(self):
        """Total Fν flux density of the SED
Yannick Roehlly's avatar
Yannick Roehlly committed
99

100
101
        Return the total Fν density vector, i.e the total luminosity converted
        to Fν flux in mJy.
Yannick Roehlly's avatar
Yannick Roehlly committed
102
103
        """

Yannick Roehlly's avatar
Yannick Roehlly committed
104
        # Fλ flux density in W/m²/nm
105
106
107
108
109
110
        if 'universe.luminosity_distance' in self.info:
            f_lambda = utils.luminosity_to_flux(self.luminosity,
                                                self.info
                                                ['universe.luminosity_distance'])
        else:
            f_lambda = utils.luminosity_to_flux(self.luminosity, 10. * parsec)
Yannick Roehlly's avatar
Yannick Roehlly committed
111

112
113
        # Fν flux density in mJy
        f_nu = utils.lambda_flambda_to_fnu(self.wavelength_grid, f_lambda)
Yannick Roehlly's avatar
Yannick Roehlly committed
114

115
        return f_nu
Yannick Roehlly's avatar
Yannick Roehlly committed
116

117
    def add_info(self, key, value, mass_proportional=False, force=False):
Yannick Roehlly's avatar
Yannick Roehlly committed
118
119
120
        """
        Add a key / value to the information dictionary

Yannick Roehlly's avatar
Yannick Roehlly committed
121
        If the key is present in the dictionary, it will raise an exception.
Yannick Roehlly's avatar
Yannick Roehlly committed
122
        Use this method (instead of direct value assignment ) to avoid
123
        overriding an already present information.
Yannick Roehlly's avatar
Yannick Roehlly committed
124

Yannick Roehlly's avatar
Yannick Roehlly committed
125
        Parameters
Yannick Roehlly's avatar
Yannick Roehlly committed
126
        ----------
127
        key: any immutable
Yannick Roehlly's avatar
Yannick Roehlly committed
128
           The key used to retrieve the information.
129
        value: anything
Yannick Roehlly's avatar
Yannick Roehlly committed
130
           The information.
131
        mass_proportional: boolean
132
133
           If True, the added variable is set as proportional to the
           mass.
134
        force: boolean
135
           If false (default), adding a key that already exists in the info
136
137
           dictionary will raise an error. If true, doing this will update
           the associated value.
Yannick Roehlly's avatar
Yannick Roehlly committed
138
139

        """
140
        if (key not in self.info) or force:
Yannick Roehlly's avatar
Yannick Roehlly committed
141
            self.info[key] = value
142
            if mass_proportional:
143
                self.mass_proportional_info.add(key)
Yannick Roehlly's avatar
Yannick Roehlly committed
144
        else:
145
            raise KeyError("The information %s is already present "
Yannick Roehlly's avatar
Yannick Roehlly committed
146
147
                           "in the SED. " % key)

148
149
150
    def add_module(self, module_name, module_conf):
        """Add a new module information to the SED.

Yannick Roehlly's avatar
Yannick Roehlly committed
151
        Parameters
152
        ----------
153
        module_name: string
154
155
            Name of the module. This name can be suffixed with anything
            using a dot.
156
        module_conf: dictionary
Yannick Roehlly's avatar
Yannick Roehlly committed
157
            Dictionary containing the module parameters.
158

Yannick Roehlly's avatar
Yannick Roehlly committed
159
        TODO: Complete the parameter dictionary with the default values from
160
161
              the module if they are not present.

Yannick Roehlly's avatar
Yannick Roehlly committed
162
        """
163
        self.modules.append((module_name, module_conf))
Yannick Roehlly's avatar
Yannick Roehlly committed
164

165
166
167
168
    def add_contribution(self, contribution_name, results_wavelengths,
                         results_lumin):
        """
        Add a new luminosity contribution to the SED.
Yannick Roehlly's avatar
Yannick Roehlly committed
169
170
171
172
173
174
175
176

        The luminosity contribution of the module is added to the contribution
        table doing an interpolation between the current wavelength grid and
        the grid of the module contribution. During the interpolation,
        everything that is outside of the concerned wavelength domain has its
        luminosity set to 0. Also, the name of the contribution is added to
        the contribution names array.

Yannick Roehlly's avatar
Yannick Roehlly committed
177
        Parameters
Yannick Roehlly's avatar
Yannick Roehlly committed
178
        ----------
179
        contribution_name: string
Yannick Roehlly's avatar
Yannick Roehlly committed
180
181
182
183
            Name of the contribution added. This name is used to retrieve the
            luminosity contribution and allows one module to add more than
            one contribution.

184
        results_wavelengths: array of floats
Yannick Roehlly's avatar
Yannick Roehlly committed
185
186
            The vector of the wavelengths of the module results (in nm).

187
        results_lumin: array of floats
Yannick Roehlly's avatar
Yannick Roehlly committed
188
189
190
191
192
193
194
            The vector of the Lλ luminosities (in W/nm) of the module results.

        """
        self.contribution_names.append(contribution_name)

        # If the SED luminosity table is empty, then there is nothing to
        # compute.
195
        if self.luminosity is None:
196
197
198
            self.wavelength_grid = results_wavelengths.copy()
            self.luminosity = results_lumin.copy()
            self.luminosities = results_lumin.copy()
Yannick Roehlly's avatar
Yannick Roehlly committed
199
        else:
200
201
            # If the added luminosity contribution changes the SED wavelength
            # grid, we interpolate everything on a common wavelength grid.
202
203
204
205
            if (results_wavelengths.size != self.wavelength_grid.size or
                    not np.all(results_wavelengths == self.wavelength_grid)):
                # Interpolate each luminosity component to the new wavelength
                # grid setting everything outside the wavelength domain to 0.
206
207
                self.wavelength_grid, self.luminosities = \
                    utils.interpolate_lumin(self.wavelength_grid,
208
                                            self.luminosities,
209
210
211
                                            results_wavelengths,
                                            results_lumin)

212
                self.luminosity = self.luminosities.sum(0)
213
214
215
            else:
                self.luminosities = np.vstack((self.luminosities,
                                               results_lumin))
216
                self.luminosity += results_lumin
Yannick Roehlly's avatar
Yannick Roehlly committed
217
218
219
220
221
222
223

    def get_lumin_contribution(self, name):
        """Get the luminosity vector of a given contribution

        If the name of the contribution is not unique in the SED, the flux of
        the last one is returned.

Yannick Roehlly's avatar
Yannick Roehlly committed
224
        Parameters
Yannick Roehlly's avatar
Yannick Roehlly committed
225
        ----------
226
        name: string
Yannick Roehlly's avatar
Yannick Roehlly committed
227
228
229
230
            Name of the contribution

        Returns
        -------
231
        luminosities: array of floats
Yannick Roehlly's avatar
Yannick Roehlly committed
232
233
234
235
236
            Vector of the luminosity density contribution based on the SED
            wavelength grid.

        """
        # Find the index of the _last_ name element
Médéric Boquien's avatar
Médéric Boquien committed
237
238
        idx = (len(self.contribution_names) - 1 -
               self.contribution_names[::-1].index(name))
Yannick Roehlly's avatar
Yannick Roehlly committed
239
        return self.luminosities[idx]
Yannick Roehlly's avatar
Yannick Roehlly committed
240

241
    def compute_fnu(self, filter_name):
Yannick Roehlly's avatar
Yannick Roehlly committed
242
        """
243
        Compute the Fν flux density in a given filter
Yannick Roehlly's avatar
Yannick Roehlly committed
244
245
246
247

        As the SED stores the Lλ luminosity density, we first compute the Fλ
        flux density. Fλ is the integration of the Lλ luminosity multiplied by
        the filter transmission, normalised to this transmission and corrected
248
        by the luminosity distance of the source.
Yannick Roehlly's avatar
Yannick Roehlly committed
249

Yannick Roehlly's avatar
Yannick Roehlly committed
250
        Fλ is in W/m²/nm. At redshift 0, the flux is computed at 10 pc. Then,
Yannick Roehlly's avatar
Yannick Roehlly committed
251
252
253
254
255
256
257
        to compute Fν, we make the approximation:

        Fν = λeff / c . λeff . Fλ

        Fν is computed in W/m²/Hz and then converted to mJy.

        If the SED spectrum does not cover all the filter response table,
258
        NaN is returned.
Yannick Roehlly's avatar
Yannick Roehlly committed
259

Yannick Roehlly's avatar
Yannick Roehlly committed
260
        Parameters
Yannick Roehlly's avatar
Yannick Roehlly committed
261
        ----------
262
263
264
        filter_name: string
            Name of the filter to integrate into. It must be presnt in the
            database.
Yannick Roehlly's avatar
Yannick Roehlly committed
265
266
267

        Return
        ------
268
        fnu: float
Yannick Roehlly's avatar
Yannick Roehlly committed
269
270
271
            The integrated Fν density in mJy.
        """

272
        wavelength = self.wavelength_grid
Yannick Roehlly's avatar
Yannick Roehlly committed
273

274
275
276
277
278
279
280
        # First we try to fetch the filter's wavelength, transmission and
        # effective wavelength from the cache. The two keys are the size of the
        # spectrum wavelength grid and the name of the filter. The first key is
        # necessary because different spectra may have different sampling. To
        # avoid having the resample the filter every time on the optimal grid
        # (spectrum+filter), we store the resampled filter. That way we only
        # have to resample to spectrum.
Médéric Boquien's avatar
Médéric Boquien committed
281
282
283
        if 'universe.redshift' in self.info:
            key = (wavelength.size, filter_name,
                   self.info['universe.redshift'])
284
            dist = self.info['universe.luminosity_distance']
285
286
        else:
            key = (wavelength.size, filter_name, 0.)
287
288
            dist = 10. * parsec

289
        if key in self.cache_filters:
290
            wavelength_r, transmission_r, lambda_eff = self.cache_filters[key]
Yannick Roehlly's avatar
Yannick Roehlly committed
291
        else:
292
293
294
295
296
297
298
299
300
301
            with Database() as db:
                filter_ = db.get_filter(filter_name)
            trans_table = filter_.trans_table
            lambda_eff = filter_.effective_wavelength
            lambda_min = filter_.trans_table[0][0]
            lambda_max = filter_.trans_table[0][-1]

            # Test if the filter covers all the spectrum extent. If not then
            # the flux is not defined
            if ((wavelength[0] > lambda_min) or (wavelength[-1] < lambda_max)):
302
                return np.nan
303

Yannick Roehlly's avatar
Yannick Roehlly committed
304
305
306
            # We regrid both spectrum and filter to the best wavelength grid
            # to avoid interpolating a high wavelength density curve to a low
            # density one. Also, we limit the work wavelength domain to the
307
            # filter one.
Médéric Boquien's avatar
Médéric Boquien committed
308
309
            w = np.where((wavelength >= lambda_min) &
                         (wavelength <= lambda_max))
310
            wavelength_r = utils.best_grid(wavelength[w], trans_table[0], key)
Médéric Boquien's avatar
Médéric Boquien committed
311
312
            transmission_r = np.interp(wavelength_r, trans_table[0],
                                       trans_table[1])
Yannick Roehlly's avatar
Yannick Roehlly committed
313

Médéric Boquien's avatar
Médéric Boquien committed
314
315
            self.cache_filters[key] = (wavelength_r, transmission_r,
                                       lambda_eff)
316

317
        l_lambda_r = np.interp(wavelength_r, wavelength, self.luminosity)
Yannick Roehlly's avatar
Yannick Roehlly committed
318

319
        f_lambda = utils.luminosity_to_flux(
320
            utils.flux_trapz(transmission_r * l_lambda_r, wavelength_r, key),
321
            dist)
Yannick Roehlly's avatar
Yannick Roehlly committed
322

323
324
        # Return Fν in mJy. The 1e-9 factor is because λ is in nm and 1e29 for
        # convert from W/m²/Hz to mJy.
325
        return 1e-9 / c * 1e29 * lambda_eff * lambda_eff * f_lambda
326
327
328
329
330
331
332

    def to_votable(self, filename, mass=1.):
        """
        Save the SED to a VO-table file

        Parameters
        ----------
333
        filename: string
334
            Name of the VO-table file
335
        mass: float
336
337
338
339
340
            Galaxy mass in solar mass. When need, the saved data will be
            multiplied by this mass.

        """
        save_sed_to_vo(self, filename, mass)
341

342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
    def to_fits(self, prefix, mass=1.):
        """
        Save the SED to FITS files.

        Parameters
        ----------
        prefix: string
            Prefix of the fits file containing the path and the id of the model
        mass: float
            Galaxy mass in solar masses. When needed, the data will be scaled
            to this mass

        """
        save_sed_to_fits(self, prefix, mass)

357
    def copy(self):
358
359
360
361
362
363
        """
        Create a new copy of the object. This is done manually rather than
        using copy.deepcopy() for speed reasons. As we know the structure of
        the object, we can do a better job.

        """
364
        sed = SED()
365
        if self._sfh is not None:
366
            sed._sfh = self._sfh
367
368
369
370
371
372
373
        sed.modules = self.modules[:]
        if self.wavelength_grid is not None:
            sed.wavelength_grid = self.wavelength_grid.copy()
            sed.luminosity = self.luminosity.copy()
            sed.luminosities = self.luminosities.copy()
        sed.contribution_names = self.contribution_names[:]
        sed.info = self.info.copy()
374
        sed.mass_proportional_info = self.mass_proportional_info.copy()
375
376

        return sed