__init__.py 12.7 KB
Newer Older
Yannick Roehlly's avatar
Yannick Roehlly committed
1 2
# -*- coding: utf-8 -*-
"""
3
Copyright (C) 2012, 2013 Centre de données Astrophysiques de Marseille
Yannick Roehlly's avatar
Yannick Roehlly committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17
Licensed under the CeCILL-v2 licence - see Licence_CeCILL_V2-en.txt

@author: Yannick Roehlly <yannick.roehlly@oamp.fr>

This script is used the build pcigale internal database containing:
- The various filter transmission tables;
- The Maraston 2005 single stellar population (SSP) data;
- The Dale and Helou 2002 infra-red templates.

"""
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
import glob
18
import itertools
Yannick Roehlly's avatar
Yannick Roehlly committed
19 20
import numpy as np
from scipy import interpolate
21
from pcigale.data import Database, Filter, SspM2005, SspBC03
Yannick Roehlly's avatar
Yannick Roehlly committed
22 23 24 25


filters_dir = os.path.join(os.path.dirname(__file__), 'filters/')
m2005_dir = os.path.join(os.path.dirname(__file__), 'maraston2005/')
26
bc03_dir = os.path.join(os.path.dirname(__file__), 'bc03//')
Yannick Roehlly's avatar
Yannick Roehlly committed
27 28 29
dh2002_dir = os.path.join(os.path.dirname(__file__), 'dh2002/')


30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 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 131 132 133 134 135 136 137 138 139 140 141
def read_bc03_ssp(filename):
    """Read a Bruzual and Charlot 2003 ASCII SSP file

    The ASCII SSP files of Bruzual and Charlot 2003 have se special structure.
    A vector is stored with the number of values followed by the values
    sepateded by a space (or a carriage return). There are the time vector, 5
    (for Chabrier IMF) or 6 lines (for Salpeter IMF) that we don't care of,
    then the wavelength vector, then the luminosity vectors, each followed by
    a 52 value table, then a bunch of other table of information that are also
    in the *colors files.

    Parameters
    ----------
    filename : string

    Returns
    -------
    time_grid: numpy 1D array of floats
              Vector of the time grid of the SSP in Gyr.
    wavelength: numpy 1D array of floats
                Vector of the wavelength grid of the SSP in nm.
    spectra: numpy 2D array of floats
             Array containing the SSP spectra, first axis is the wavelength,
             second one is the time.

    """

    def file_structure_generator():
        """Generator used to identify table lines in the SSP file

        In the SSP file, the vectors are store one next to the other, but
        there are 5 informational lines after the time vector. We use this
        generator to the if we are on lines to read or not.
        """
        if "chab" in filename:
            bad_line_number = 5
        else:
            bad_line_number = 6
        yield("data")
        for i in range(bad_line_number):
            yield("bad")
        while True:
            yield("data")

    file_structure = file_structure_generator()
    # Are we in a data line or a bad one.
    what_line = file_structure.next()
    # Variable conting, in reverse order, the number of value still to
    # read for the read vector.
    counter = 0

    time_grid = []
    full_table = []
    tmp_table = []

    with open(filename) as file_:
        # We read the file line by line.
        for line in file_:
            if what_line == "data":
                # If we are in a "data" line, we analyse each number.
                for item in line.split():
                    if counter == 0:
                        # If counter is 0, then we are not reading a vector
                        # and the first number is the length of the next
                        # vector.
                        counter = int(item)
                    else:
                        # If counter > 0, we are currently reading a vector.
                        tmp_table.append(float(item))
                        counter -= 1
                        if counter == 0:
                            # We reached the end of the vector. If we have not
                            # yet store the time grid (the first table) we are
                            # currently reading it.
                            if time_grid == []:
                                time_grid = tmp_table[:]
                            # Else, we store the vector in the full table,
                            # only if its length is superior to 250 to get rid
                            # of the 52 item unknown vector and the 221 (time
                            # grid length) item vectors at the end of the
                            # file.
                            elif len(tmp_table) > 250:
                                full_table.append(tmp_table[:])

                            tmp_table = []

            # If at the end of a line, we have finished reading a vector, it's
            # time to change to the next structure context.
            if counter == 0:
                what_line = file_structure.next()

    # The time grid is in year, we want Gyr.
    time_grid = np.array(time_grid, dtype=float)
    time_grid = time_grid * 1.e-9

    # The first "long" vector encountered is the wavelength grid. The value
    # are in Ångström, we convert it to nano-meter.
    wavelength = np.array(full_table.pop(0), dtype=float)
    wavelength = wavelength * 0.1

    # The luminosities are in Solar luminosity (3.826.10^33 ergs.s-1) per
    # Ångström, we convert it to W/nm.
    luminosity = np.array(full_table, dtype=float)
    luminosity = luminosity * 3.826e27
    # Transposition to have the time in the second axis.
    luminosity = luminosity.transpose()

    # In the SSP, the time grid begins at 0, but not in the *colors file, so
    # we remove t=0 from the SSP.
    return time_grid[1:], wavelength, luminosity[:, 1:]


Yannick Roehlly's avatar
Yannick Roehlly committed
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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
def build_base():
    base = Database(writable=True)
    base.upgrade_base()

    print('#' * 78)
    ########################################################################
    # Filter transmission tables insertion                                 #
    ########################################################################
    print("1- Importing filters...\n")
    for filter_file in glob.glob(filters_dir + '*.dat'):
        with open(filter_file, 'r') as filter_file_read:
            filter_name = filter_file_read.readline().strip('# \n\t')
            filter_type = filter_file_read.readline().strip('# \n\t')
            filter_description = filter_file_read.readline().strip('# \n\t')
        filter_table = np.genfromtxt(filter_file)
        # The table is transposed to have table[0] containing the wavelength
        # and table[1] containing the transmission.
        filter_table = filter_table.transpose()
        # We convert the wavelength from Å to nm.
        filter_table[0] *= 0.1

        print("Importing %s... (%s points)" % (filter_name,
                                               filter_table.shape[1]))

        new_filter = Filter(filter_name, filter_description,
                            filter_type, filter_table)

        # We normalise the filter and compute the effective wavelength.
        new_filter.normalise()

        base.add_filter(new_filter)
    print("\nDONE\n")
    print('#' * 78)

    ########################################################################
    # Maraston 2005 SSP insertion                                          #
    ########################################################################
    print("2- Importing Maraston 2005 SSP\n")

    # Age grid (1My to 13.7Gy with 1My step)
    age_grid = np.arange(1e-3, 13.701, 1e-3)

    # Transpose the table to have access to each value vector on the first
    # axis
    kroupa_mass = np.genfromtxt(m2005_dir + 'stellarmass.kroupa').transpose()
    salpeter_mass = \
        np.genfromtxt(m2005_dir + '/stellarmass.salpeter').transpose()

    for spec_file in glob.glob(m2005_dir + '*.rhb'):

        print("Importing %s..." % spec_file)

        spec_table = np.genfromtxt(spec_file).transpose()
        metallicity = spec_table[1, 0]

        if 'krz' in spec_file:
            imf = 'kr'
            mass_table = np.copy(kroupa_mass)
        elif 'ssz' in spec_file:
            imf = 'ss'
            mass_table = np.copy(salpeter_mass)
        else:
            raise ValueError('Unknown IMF!!!')

        # Keep only the actual metallicity values in the mass table
        # we don't take the first column which contains metallicity
        mass_table = mass_table[1:, mass_table[0] == metallicity]

        # Interpolate the mass table over the new age grid
        mass_table = interpolate.interp1d(mass_table[0], mass_table)(age_grid)

        # Remove the age column from the mass table
        mass_table = np.delete(mass_table, 0, 0)

        # Remove the metallicity column from the spec table
        spec_table = np.delete(spec_table, 1, 0)

        # Convert the wavelength from Å to nm
        spec_table[1] = spec_table[1] * 0.1

        # For all ages, the lambda grid is the same.
        lambda_grid = np.unique(spec_table[1])

        # Creation of the age vs lambda flux table
        tmpList = []
        for wavelength in lambda_grid:
            [age_grid_orig, lambda_grid_orig, flux_orig] = \
                spec_table[:, spec_table[1, :] == wavelength]
            flux_orig = flux_orig * 10 * 1.e-7  # From erg/s^-1/Å to W/nm
            flux_regrid = interpolate.interp1d(age_grid_orig,
                                               flux_orig)(age_grid)

            tmpList.append(flux_regrid)
        flux_age = np.array(tmpList)

        base.add_ssp_m2005(SspM2005(imf, metallicity, age_grid,
                                    lambda_grid, mass_table, flux_age))

    print("\nDONE\n")
    print('#' * 78)

243 244 245 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
    ########################################################################
    # Bruzual and Charlot SSP insertion                                    #
    ########################################################################
    print("3- Importing Bruzual and Charlot 2003 SSP\n")

    # Time grid (1My to 20Gy with 1My step)
    time_grid = np.arange(1e-3, 20., 1e-3)

    # Metallicities associated to each key
    metallicity = {
        "m22": 0.0001,
        "m32": 0.0004,
        "m42": 0.004,
        "m52": 0.008,
        "m62": 0.02,
        "m72": 0.05
    }

    for key, imf in itertools.product(metallicity, ["salp", "chab"]):
        base_filename = bc03_dir + "bc2003_lr_" + key + "_" + imf + "_ssp"
        ssp_filename = base_filename + ".ised_ASCII"
        color3_filename = base_filename + ".3color"
        color4_filename = base_filename + ".4color"

        print("Importing %s..." % base_filename)

        # Read the desired information from the color files
        color_table = []
        color3_table = np.genfromtxt(color3_filename).transpose()
        color4_table = np.genfromtxt(color4_filename).transpose()
        color_table.append(color4_table[6])  # Mstar
        color_table.append(color4_table[7])  # Mgas
        color_table.append(color3_table[5])  # NLy
        color_table.append(color3_table[1])  # B4000
        color_table.append(color3_table[2])  # B4_VN
        color_table.append(color3_table[3])  # B4_SDSS
        color_table.append(color3_table[4])  # B(912)

        color_table = np.array(color_table)

        ssp_time, ssp_wave, ssp_lumin = read_bc03_ssp(ssp_filename)

        # Regrid the SSP data to the evenly spaced time grid.
        color_table = interpolate.interp1d(ssp_time, color_table)(time_grid)
        ssp_lumin = interpolate.interp1d(ssp_time,
                                         ssp_lumin)(time_grid)

        base.add_ssp_bc03(SspBC03(
            imf,
            metallicity[key],
            time_grid,
            ssp_wave,
            color_table,
            ssp_lumin
        ))

Yannick Roehlly's avatar
Yannick Roehlly committed
299 300 301
    ########################################################################
    # Dale and Helou 2002 templates insertion                              #
    ########################################################################
302
    print("4- Importing Dale and Helou 2002 templates\n")
Yannick Roehlly's avatar
Yannick Roehlly committed
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

    # Getting the alpha grid for the templates
    dhcal = np.genfromtxt(dh2002_dir + 'dhcal.dat')
    alpha_grid = dhcal[:, 1]

    # Getting the lambda grid for the templates (we checked that all share the
    # same grid).
    first_template = np.genfromtxt(dh2002_dir + 'irdh01.spec', skip_header=1)
    lambda_grid = first_template[:, 0] * 0.1  # Convert Å to nm

    templates = []

    for i in range(len(alpha_grid)):
        filename = dh2002_dir + 'irdh' + ("%02d" % (i + 1)) + '.spec'
        print("Importing %s..." % filename)
        table = np.genfromtxt(filename, skip_header=1)[:, 1]  # Luminosity
                                                              # column
        # The table give the luminosity density in Lsun/Å normalised to 1 Lsun
        # over the full spectrum. As we converted the wavelengths to nm, we
        # must multiply the density per 10 to keep the normalisation.
        table = table * 10
        templates.append(table)

    templates = np.array(templates)

    data = (alpha_grid, lambda_grid, templates)

    base.add_dh2002_infrared_templates(data)

    print("\nDONE\n")
    print('#' * 78)

    base.session.close_all()

if __name__ == '__main__':
    build_base()