Exemplo n.º 1
0
def test_make_extinguished_sed_grid():

    # download the needed files
    priors_fname = download_rename("beast_example_phat_spec_w_priors.grid.hd5")
    filter_fname = download_rename("filters.hd5")

    # download cached version of sed grid
    seds_fname_cache = download_rename("beast_example_phat_seds.grid.hd5")

    ################
    # generate the same extinguished SED grid from the code

    # Add in the filters
    filters = [
        "HST_WFC3_F275W",
        "HST_WFC3_F336W",
        "HST_ACS_WFC_F475W",
        "HST_ACS_WFC_F814W",
        "HST_WFC3_F110W",
        "HST_WFC3_F160W",
    ]
    add_spectral_properties_kwargs = dict(filternames=filters)

    g_pspec = grid.FileSpectralGrid(priors_fname, backend="memory")

    # generate the SED grid by integrating the filter response functions
    #   effect of dust extinction applied before filter integration
    #   also computes the dust priors as weights
    seds_fname = "/tmp/beast_example_phat_sed.grid.hd5"
    seds_fname, g_seds = make_extinguished_sed_grid(
        "test",
        g_pspec,
        filters,
        seds_fname=seds_fname,
        filterLib=filter_fname,
        extLaw=extinction.Gordon16_RvFALaw(),
        av=[0.0, 10.055, 1.0],
        rv=[2.0, 6.0, 1.0],
        fA=[0.0, 1.0, 0.25],
        av_prior_model={"name": "flat"},
        rv_prior_model={"name": "flat"},
        fA_prior_model={"name": "flat"},
        add_spectral_properties_kwargs=add_spectral_properties_kwargs,
    )

    # compare the new to the cached version
    compare_hdf5(seds_fname_cache, seds_fname)
Exemplo n.º 2
0
def test_add_stellar_priors_to_spectral_grid():

    # download the needed files
    gspec_fname = download_rename("beast_example_phat_spec_grid.hd5")

    # download cached version of spectral grid with priors
    priors_fname_cache = download_rename("beast_example_phat_spec_w_priors.grid.hd5")

    ###############
    # generate the spectral grid with stellar priors from the code

    gspec_fname = "/tmp/beast_example_phat_spec_grid.hd5"
    specgrid = grid.FileSpectralGrid(gspec_fname, backend="memory")

    priors_fname = "/tmp/beast_example_phat_spec_w_priors.grid.hd5"
    priors_fname, g = add_stellar_priors("test", specgrid, priors_fname=priors_fname)

    # compare the new to the cached version
    compare_hdf5(priors_fname_cache, priors_fname)
Exemplo n.º 3
0
def make_spectral_grid(
    project,
    oiso,
    osl=None,
    bounds={},
    verbose=True,
    spec_fname=None,
    distance=10,
    distance_unit=units.pc,
    redshift=0.0,
    filterLib=None,
    add_spectral_properties_kwargs=None,
    extLaw=None,
    **kwargs
):
    """
    The spectral grid is generated using the stellar parameters by
    interpolation of the isochrones and the generation of spectra into the
    physical units

    Parameters
    ----------
    project: str
        project name

    oiso: isochrone.Isochrone object
        set of isochrones to use

    osl: stellib.Stellib object
        Spectral library to use (default stellib.Kurucz)

    distance: float or list of float
        distances at which models should be shifted, specified as a
        single number or as [min, max, step]

        0 means absolute magnitude.

    distance_unit: astropy length unit or mag
        distances will be evenly spaced in this unit
        therefore, specifying a distance grid in mag units will lead to
        a log grid

    redshift: float
        Redshift to which wavelengths should be shifted
        Default is 0 (rest frame)

    spec_fname: str
        full filename to save the spectral grid into

    filterLib:  str
        full filename to the filter library hd5 file

    extLaw: extinction.ExtLaw (default=None)
        if set, only save the spectrum for the wavelengths over which the
        extinction law is valid

    add_spectral_properties_kwargs: dict
        keyword arguments to call :func:`add_spectral_properties`
        to add model properties from the spectra into the grid property table

    Returns
    -------
    fname: str
       name of saved file

    g: grid.SpectralGrid object
        spectral grid to transform
    """
    if spec_fname is None:
        spec_fname = "%s/%s_spec_grid.hd5" % (project, project)

    if not os.path.isfile(spec_fname):
        osl = osl or stellib.Kurucz()

        # filter extrapolations of the grid with given sensitivities in
        # logg and logT
        if "dlogT" not in bounds:
            bounds["dlogT"] = 0.1
        if "dlogg" not in bounds:
            bounds["dlogg"] = 0.3

        # make the spectral grid
        if verbose:
            print("Make spectra")
        g = creategrid.gen_spectral_grid_from_stellib_given_points(
            osl, oiso.data, bounds=bounds
        )

        # Construct the distances array. Turn single value into
        # 1-element list if single distance is given.
        _distance = np.atleast_1d(distance)
        if len(_distance) == 3:
            mindist, maxdist, stepdist = _distance
            distances = np.arange(mindist, maxdist + stepdist, stepdist)
        elif len(_distance) == 1:
            distances = np.array(_distance)
        else:
            raise ValueError("distance needs to be (min, max, step) or single number")

        # calculate the distances in pc
        if distance_unit == units.mag:
            distances = np.power(10, distances / 5.0 + 1) * units.pc
        else:
            distances = (distances * distance_unit).to(units.pc)

        print("applying {} distances".format(len(distances)))

        if verbose:
            print(
                "Adding spectral properties:",
                add_spectral_properties_kwargs is not None,
            )
        if add_spectral_properties_kwargs is not None:
            nameformat = (
                add_spectral_properties_kwargs.pop("nameformat", "{0:s}") + "_nd"
            )

        # Apply the distances to the stars. Seds already at 10 pc, need
        # multiplication by the square of the ratio to this distance.
        # TODO: Applying the distances might have to happen in chunks
        # for larger grids.
        def apply_distance_and_spectral_props(g):
            # distance
            g = creategrid.apply_distance_grid(g, distances, redshift=redshift)

            # spectral props
            if add_spectral_properties_kwargs is not None:
                g = creategrid.add_spectral_properties(
                    g,
                    nameformat=nameformat,
                    filterLib=filterLib,
                    **add_spectral_properties_kwargs
                )

            # extinction
            if extLaw is not None:

                ext_law_range_A = 1e4 / np.array(extLaw.x_range)
                valid_lambda = np.where(
                    (g.lamb > np.min(ext_law_range_A))
                    & (g.lamb < np.max(ext_law_range_A))
                )[0]

                g.lamb = g.lamb[valid_lambda]
                g.seds = g.seds[:, valid_lambda]

            return g

        # if extLaw is set, remove wavelengths where the extinction curve
        # isn't valid
        # Perform the extensions defined above and Write to disk
        if hasattr(g, "writeHDF"):
            g = apply_distance_and_spectral_props(g)
            g.writeHDF(spec_fname)
        else:
            for gk in g:
                gk = apply_distance_and_spectral_props(gk)
                gk.writeHDF(spec_fname, append=True)

    g = grid.FileSpectralGrid(spec_fname, backend="memory")

    return (spec_fname, g)
Exemplo n.º 4
0
def add_stellar_priors(project, specgrid,
                       age_prior_model={'name': 'flat'},
                       mass_prior_model={'name': 'kroupa'},
                       met_prior_model={'name': 'flat'},
                       verbose=True,
                       priors_fname=None,
                       **kwargs):
    """
    make_priors -- compute the weights for the stellar priors

    Parameters
    ----------
    project: str
        project name

    specgrid: grid.SpectralGrid object
        spectral grid to transform

    age_prior_model: dict
        dict including prior model name and parameters

    mass_prior_model: dict
        dict including prior model name and parameters

    met_prior_model: dict
        dict including prior model name and parameters

    priors_fname: str
        full filename to which to save the spectral grid with priors

    Returns
    -------
    fname: str
       name of saved file

    g: grid.SpectralGrid object
        spectral grid to transform
    """
    if priors_fname is None:
        priors_fname = "%s/%s_spec_w_priors.grid.hd5" % (project, project)
    if not os.path.isfile(priors_fname):

        if verbose:
            print("Make Prior Weights")

        compute_age_mass_metallicity_weights(
            specgrid.grid,
            age_prior_model=age_prior_model,
            mass_prior_model=mass_prior_model,
            met_prior_model=met_prior_model,
            **kwargs)

        # write to disk
        if hasattr(specgrid, "writeHDF"):
            specgrid.writeHDF(priors_fname)
        else:
            for gk in specgrid:
                gk.writeHDF(priors_fname, append=True)

    g = grid.FileSpectralGrid(priors_fname, backend="memory")

    return (priors_fname, g)