Пример #1
0
    def _synthesize_spectrum(self, code):
        #--- Synthesizing spectrum -----------------------------------------------------
        # Parameters
        teff = 5771.0
        logg = 4.44
        MH = 0.00
        alpha = ispec.determine_abundance_enchancements(MH)
        microturbulence_vel = ispec.estimate_vmic(teff, logg, MH)  # 1.07
        macroturbulence = ispec.estimate_vmac(teff, logg, MH)  # 4.21
        vsini = 1.60  # Sun
        limb_darkening_coeff = 0.6
        resolution = 300000
        wave_step = 0.001

        # Wavelengths to synthesis
        #regions = ispec.read_segment_regions(ispec_dir + "/input/regions/fe_lines_segments.txt")
        regions = None
        wave_base = 515.0  # Magnesium triplet region
        wave_top = 525.0

        # Selected model amtosphere, linelist and solar abundances
        #model = ispec_dir + "/input/atmospheres/MARCS/"
        model = ispec_dir + "/input/atmospheres/MARCS.GES/"
        #model = ispec_dir + "/input/atmospheres/MARCS.APOGEE/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.APOGEE/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.Castelli/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.Kurucz/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.Kirby/"

        #atomic_linelist_file = ispec_dir + "/input/linelists/transitions/VALD.300_1100nm/atomic_lines.tsv"
        #atomic_linelist_file = ispec_dir + "/input/linelists/transitions/VALD.1100_2400nm/atomic_lines.tsv"
        atomic_linelist_file = ispec_dir + "/input/linelists/transitions/GESv6_atom_hfs_iso.420_920nm/atomic_lines.tsv"
        #atomic_linelist_file = ispec_dir + "/input/linelists/transitions/GESv6_atom_nohfs_noiso.420_920nm/atomic_lines.tsv"

        isotope_file = ispec_dir + "/input/isotopes/SPECTRUM.lst"

        # Load chemical information and linelist
        atomic_linelist = ispec.read_atomic_linelist(atomic_linelist_file,
                                                     wave_base=wave_base,
                                                     wave_top=wave_top)
        atomic_linelist = atomic_linelist[
            atomic_linelist['theoretical_depth'] >=
            0.01]  # Select lines that have some minimal contribution in the sun

        isotopes = ispec.read_isotope_data(isotope_file)

        if "ATLAS" in model:
            solar_abundances_file = ispec_dir + "/input/abundances/Grevesse.1998/stdatom.dat"
        else:
            # MARCS
            solar_abundances_file = ispec_dir + "/input/abundances/Grevesse.2007/stdatom.dat"
        #solar_abundances_file = ispec_dir + "/input/abundances/Asplund.2005/stdatom.dat"
        #solar_abundances_file = ispec_dir + "/input/abundances/Asplund.2009/stdatom.dat"
        #solar_abundances_file = ispec_dir + "/input/abundances/Anders.1989/stdatom.dat"

        # Load model atmospheres
        modeled_layers_pack = ispec.load_modeled_layers_pack(model)
        # Load SPECTRUM abundances
        solar_abundances = ispec.read_solar_abundances(solar_abundances_file)

        ## Custom fixed abundances
        #fixed_abundances = ispec.create_free_abundances_structure(["C", "N", "O"], chemical_elements, solar_abundances)
        #fixed_abundances['Abund'] = [-3.49, -3.71, -3.54] # Abundances in SPECTRUM scale (i.e., x - 12.0 - 0.036) and in the same order ["C", "N", "O"]
        ## No fixed abundances
        fixed_abundances = None

        # Validate parameters
        if not ispec.valid_atmosphere_target(modeled_layers_pack, {
                'teff': teff,
                'logg': logg,
                'MH': MH,
                'alpha': alpha
        }):
            msg = "The specified effective temperature, gravity (log g) and metallicity [M/H] \
                    fall out of theatmospheric models."

            print(msg)

        # Prepare atmosphere model
        atmosphere_layers = ispec.interpolate_atmosphere_layers(
            modeled_layers_pack, {
                'teff': teff,
                'logg': logg,
                'MH': MH,
                'alpha': alpha
            },
            code=code)

        # Synthesis
        synth_spectrum = ispec.create_spectrum_structure(
            np.arange(wave_base, wave_top, wave_step))
        synth_spectrum['flux'] = ispec.generate_spectrum(synth_spectrum['waveobs'], \
                atmosphere_layers, teff, logg, MH, alpha, atomic_linelist, isotopes, solar_abundances, \
                fixed_abundances, microturbulence_vel = microturbulence_vel, \
                macroturbulence=macroturbulence, vsini=vsini, limb_darkening_coeff=limb_darkening_coeff, \
                R=resolution, regions=regions, verbose=1,
                code=code)
        return synth_spectrum
Пример #2
0
    def test_determine_loggf_line_by_line_using_synth_spectra(self):
        code = "spectrum"
        star_spectrum = ispec.read_spectrum(
            ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
        #--- Radial Velocity determination with template -------------------------------
        # - Read synthetic template
        #template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Arcturus.372_926nm/template.txt.gz")
        #template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Sun.372_926nm/template.txt.gz")
        template = ispec.read_spectrum(
            ispec_dir +
            "/input/spectra/templates/NARVAL.Sun.370_1048nm/template.txt.gz")
        #template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Synth.Sun.300_1100nm/template.txt.gz")

        models, ccf = ispec.cross_correlate_with_template(star_spectrum, template, \
                                lower_velocity_limit=-200, upper_velocity_limit=200, \
                                velocity_step=1.0, fourier=False)

        # Number of models represent the number of components
        components = len(models)
        # First component:
        rv = np.round(models[0].mu(), 2)  # km/s
        rv_err = np.round(models[0].emu(), 2)  # km/s
        #--- Radial Velocity correction ------------------------------------------------
        star_spectrum = ispec.correct_velocity(star_spectrum, rv)

        #--- Resolution degradation ----------------------------------------------------
        # NOTE: The line selection was built based on a solar spectrum with R ~ 47,000 and GES/VALD atomic linelist.
        from_resolution = 80000
        to_resolution = 47000
        star_spectrum = ispec.convolve_spectrum(star_spectrum, to_resolution,
                                                from_resolution)

        #--- Continuum fit -------------------------------------------------------------
        model = "Splines"  # "Polynomy"
        degree = 2
        nknots = None  # Automatic: 1 spline every 5 nm
        from_resolution = to_resolution

        # Strategy: Filter first median values and secondly MAXIMUMs in order to find the continuum
        order = 'median+max'
        median_wave_range = 0.05
        max_wave_range = 1.0

        star_continuum_model = ispec.fit_continuum(star_spectrum, from_resolution=from_resolution, \
                                    nknots=nknots, degree=degree, \
                                    median_wave_range=median_wave_range, \
                                    max_wave_range=max_wave_range, \
                                    model=model, order=order, \
                                    automatic_strong_line_detection=True, \
                                    strong_line_probability=0.5, \
                                    use_errors_for_fitting=True)
        #--- Normalize -------------------------------------------------------------
        normalized_star_spectrum = ispec.normalize_spectrum(
            star_spectrum,
            star_continuum_model,
            consider_continuum_errors=False)
        # Use a fixed value because the spectrum is already normalized
        star_continuum_model = ispec.fit_continuum(star_spectrum,
                                                   fixed_value=1.0,
                                                   model="Fixed value")
        #--- Model spectra ----------------------------------------------------------
        # Parameters
        initial_teff = 5771.0
        initial_logg = 4.44
        initial_MH = 0.00
        initial_alpha = 0.00
        initial_vmic = ispec.estimate_vmic(initial_teff, initial_logg,
                                           initial_MH)
        initial_vmac = ispec.estimate_vmac(initial_teff, initial_logg,
                                           initial_MH)
        initial_vsini = 1.60  # Sun
        initial_limb_darkening_coeff = 0.6
        initial_R = to_resolution
        initial_vrad = 0
        max_iterations = 6

        # Selected model amtosphere, linelist and solar abundances
        #model = ispec_dir + "/input/atmospheres/MARCS/"
        model = ispec_dir + "/input/atmospheres/MARCS.GES/"
        #model = ispec_dir + "/input/atmospheres/MARCS.APOGEE/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.APOGEE/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.Castelli/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.Kurucz/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.Kirby/"

        #atomic_linelist_file = ispec_dir + "/input/linelists/transitions/VALD.300_1100nm/atomic_lines.tsv"
        #atomic_linelist_file = ispec_dir + "/input/linelists/transitions/VALD.1100_2400nm/atomic_lines.tsv"
        atomic_linelist_file = ispec_dir + "/input/linelists/transitions/GESv6_atom_hfs_iso.420_920nm/atomic_lines.tsv"
        #atomic_linelist_file = ispec_dir + "/input/linelists/transitions/GESv6_atom_nohfs_noiso.420_920nm/atomic_lines.tsv"

        if "ATLAS" in model:
            solar_abundances_file = ispec_dir + "/input/abundances/Grevesse.1998/stdatom.dat"
        else:
            # MARCS
            solar_abundances_file = ispec_dir + "/input/abundances/Grevesse.2007/stdatom.dat"
        #solar_abundances_file = ispec_dir + "/input/abundances/Asplund.2005/stdatom.dat"
        #solar_abundances_file = ispec_dir + "/input/abundances/Asplund.2009/stdatom.dat"
        #solar_abundances_file = ispec_dir + "/input/abundances/Anders.1989/stdatom.dat"

        isotope_file = ispec_dir + "/input/isotopes/SPECTRUM.lst"

        # Load chemical information and linelist
        atomic_linelist = ispec.read_atomic_linelist(
            atomic_linelist_file,
            wave_base=np.min(star_spectrum['waveobs']),
            wave_top=np.max(star_spectrum['waveobs']))
        atomic_linelist = atomic_linelist[
            atomic_linelist['theoretical_depth'] >=
            0.01]  # Select lines that have some minimal contribution in the sun

        isotopes = ispec.read_isotope_data(isotope_file)

        # Load model atmospheres
        modeled_layers_pack = ispec.load_modeled_layers_pack(model)

        # Load SPECTRUM abundances
        solar_abundances = ispec.read_solar_abundances(solar_abundances_file)

        # Free parameters
        #free_params = ["teff", "logg", "MH", "vmic", "vmac", "vsini", "R", "vrad", "limb_darkening_coeff"]
        #free_params = ["vrad"]
        free_params = []

        # Free individual element abundance (WARNING: it should be coherent with the selected line regions!)
        chemical_elements_file = ispec_dir + "/input/abundances/chemical_elements_symbols.dat"
        chemical_elements = ispec.read_chemical_elements(
            chemical_elements_file)

        # Line regions
        line_regions_with_atomic_data = ispec.read_line_regions(
            ispec_dir +
            "/input/regions/47000_GES/{}_synth_good_for_params_all_extended.txt"
            .format(code))
        #line_regions_with_atomic_data = ispec.read_line_regions(ispec_dir + "/input/regions/47000_VALD/{}_synth_good_for_params_all_extended.txt".format(code))
        # Select only the lines to get abundances from
        line_regions_with_atomic_data = line_regions_with_atomic_data[:5]
        line_regions_with_atomic_data = ispec.adjust_linemasks(
            normalized_star_spectrum,
            line_regions_with_atomic_data,
            max_margin=0.5)

        output_dirname = "example_loggf_line_by_line_%s" % (code, )
        #ispec.mkdir_p(output_dirname)
        for i, line in enumerate(line_regions_with_atomic_data):
            # Directory and file names
            #element_name = "_".join(line['element'].split())
            element_name = "_".join(line['note'].split())
            common_filename = "example_" + code + "_individual_" + element_name + "_%.4f" % line[
                'wave_peak']

            # Free individual element abundance (WARNING: it should be coherent with the selected line regions!)
            free_abundances = None

            # Line by line
            individual_line_regions = line_regions_with_atomic_data[
                i:i + 1]  # Keep recarray structure
            linelist_free_loggf = line_regions_with_atomic_data[
                i:i + 1]  # Keep recarray structure

            # Filter the line that we want to determine the loggf from the global atomic linelist
            lfilter = atomic_linelist['element'] == linelist_free_loggf[
                'element'][0]
            for key in [
                    'wave_nm', 'lower_state_eV', 'loggf', 'stark', 'rad',
                    'waals'
            ]:
                lfilter = np.logical_and(
                    lfilter,
                    np.abs(atomic_linelist[key] - linelist_free_loggf[key][0])
                    < 1e-9)

            # Segment
            segments = ispec.create_segments_around_lines(
                individual_line_regions, margin=0.25)
            wfilter = ispec.create_wavelength_filter(
                normalized_star_spectrum,
                regions=segments)  # Only use the segment

            obs_spec, modeled_synth_spectrum, params, errors, abundances_found, loggf_found, status, stats_linemasks = \
                    ispec.model_spectrum(normalized_star_spectrum[wfilter], star_continuum_model, \
                    modeled_layers_pack, atomic_linelist[~lfilter], isotopes, solar_abundances, free_abundances, linelist_free_loggf, initial_teff, \
                    initial_logg, initial_MH, initial_alpha, initial_vmic, initial_vmac, initial_vsini, \
                    initial_limb_darkening_coeff, initial_R, initial_vrad, free_params, segments=segments, \
                    linemasks=individual_line_regions, \
                    enhance_abundances=True, \
                    use_errors = True, \
                    vmic_from_empirical_relation = False, \
                    vmac_from_empirical_relation = False, \
                    max_iterations=max_iterations, \
                    tmp_dir = None, \
                    code=code)

            self.assertAlmostEqual(loggf_found['loggf'][0],
                                   -1.0743873027191777)
            self.assertAlmostEqual(loggf_found['eloggf'][0],
                                   0.11414696354921147)
            self.assertEqual(len(loggf_found['loggf']), 1)
            self.assertEqual(individual_line_regions['lower_state_eV'][0],
                             loggf_found['linelist']['lower_state_eV'][0])
            break
Пример #3
0
    def test_interpolate_spectrum(self):
        #--- Synthesizing spectrum -----------------------------------------------------
        # Parameters
        #teff = 5771.0
        teff = 4025.0
        logg = 4.44
        MH = 0.00
        alpha = ispec.determine_abundance_enchancements(MH)
        microturbulence_vel = ispec.estimate_vmic(teff, logg, MH)  # 1.07
        macroturbulence = ispec.estimate_vmac(teff, logg, MH)  # 4.21
        vsini = 1.60  # Sun
        limb_darkening_coeff = 0.6
        resolution = 300000
        wave_step = 0.001

        # Wavelengths to synthesis
        wave_base = 515.0  # Magnesium triplet region
        wave_top = 525.0

        code = "grid"
        precomputed_grid_dir = ispec_dir + "/input/grid/SPECTRUM_MARCS.GES_GESv6_atom_hfs_iso.480_680nm_light/"
        grid = ispec.load_spectral_grid(precomputed_grid_dir)

        atomic_linelist = None
        isotopes = None
        modeled_layers_pack = None
        solar_abundances = None
        fixed_abundances = None
        abundances = None
        atmosphere_layers = None
        regions = None

        # Validate parameters
        if not ispec.valid_interpolated_spectrum_target(
                grid, {
                    'teff': teff,
                    'logg': logg,
                    'MH': MH,
                    'alpha': alpha,
                    'vmic': microturbulence_vel
                }):
            msg = "The specified effective temperature, gravity (log g) and metallicity [M/H] \
                    fall out of the spectral grid limits."

            print(msg)

        # Interpolation
        interpolated_spectrum = ispec.create_spectrum_structure(
            np.arange(wave_base, wave_top, wave_step))
        interpolated_spectrum['flux'] = ispec.generate_spectrum(interpolated_spectrum['waveobs'], \
                atmosphere_layers, teff, logg, MH, alpha, atomic_linelist, isotopes, abundances, \
                fixed_abundances, microturbulence_vel = microturbulence_vel, \
                macroturbulence=macroturbulence, vsini=vsini, limb_darkening_coeff=limb_darkening_coeff, \
                R=resolution, regions=regions, verbose=1,
                code=code, grid=grid)
        np.testing.assert_almost_equal(
            interpolated_spectrum['flux'][:10],
            np.array([
                1.0000000e-10, 9.3509103e-01, 9.2898036e-01, 9.2100053e-01,
                9.1271230e-01, 9.0331793e-01, 8.9166097e-01, 8.7667336e-01,
                8.5752275e-01, 8.3368807e-01
            ]))
        np.testing.assert_almost_equal(
            interpolated_spectrum['waveobs'][:10],
            np.array([
                515., 515.001, 515.002, 515.003, 515.004, 515.005, 515.006,
                515.007, 515.008, 515.009
            ]))
Пример #4
0
    def test_determine_astrophysical_parameters_using_synth_spectra(self):
        code = "spectrum"
        star_spectrum = ispec.read_spectrum(
            ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
        #--- Radial Velocity determination with template -------------------------------
        # - Read synthetic template
        #template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Arcturus.372_926nm/template.txt.gz")
        #template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Sun.372_926nm/template.txt.gz")
        template = ispec.read_spectrum(
            ispec_dir +
            "/input/spectra/templates/NARVAL.Sun.370_1048nm/template.txt.gz")
        #template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Synth.Sun.300_1100nm/template.txt.gz")

        models, ccf = ispec.cross_correlate_with_template(star_spectrum, template, \
                                lower_velocity_limit=-200, upper_velocity_limit=200, \
                                velocity_step=1.0, fourier=False)

        # Number of models represent the number of components
        components = len(models)
        # First component:
        rv = np.round(models[0].mu(), 2)  # km/s
        rv_err = np.round(models[0].emu(), 2)  # km/s
        #--- Radial Velocity correction ------------------------------------------------
        star_spectrum = ispec.correct_velocity(star_spectrum, rv)
        #--- Resolution degradation ----------------------------------------------------
        # NOTE: The line selection was built based on a solar spectrum with R ~ 47,000 and GES/VALD atomic linelist.
        from_resolution = 80000
        to_resolution = 47000
        star_spectrum = ispec.convolve_spectrum(star_spectrum, to_resolution,
                                                from_resolution)
        #--- Continuum fit -------------------------------------------------------------
        model = "Splines"  # "Polynomy"
        degree = 2
        nknots = None  # Automatic: 1 spline every 5 nm
        from_resolution = to_resolution

        # Strategy: Filter first median values and secondly MAXIMUMs in order to find the continuum
        order = 'median+max'
        median_wave_range = 0.05
        max_wave_range = 1.0

        star_continuum_model = ispec.fit_continuum(star_spectrum, from_resolution=from_resolution, \
                                    nknots=nknots, degree=degree, \
                                    median_wave_range=median_wave_range, \
                                    max_wave_range=max_wave_range, \
                                    model=model, order=order, \
                                    automatic_strong_line_detection=True, \
                                    strong_line_probability=0.5, \
                                    use_errors_for_fitting=True)
        #--- Normalize -------------------------------------------------------------
        normalized_star_spectrum = ispec.normalize_spectrum(
            star_spectrum,
            star_continuum_model,
            consider_continuum_errors=False)
        # Use a fixed value because the spectrum is already normalized
        star_continuum_model = ispec.fit_continuum(star_spectrum,
                                                   fixed_value=1.0,
                                                   model="Fixed value")
        #--- Model spectra ----------------------------------------------------------
        # Parameters
        initial_teff = 5750.0
        initial_logg = 4.5
        initial_MH = 0.00
        initial_alpha = ispec.determine_abundance_enchancements(initial_MH)
        initial_vmic = ispec.estimate_vmic(initial_teff, initial_logg,
                                           initial_MH)
        initial_vmac = ispec.estimate_vmac(initial_teff, initial_logg,
                                           initial_MH)
        initial_vsini = 2.0
        initial_limb_darkening_coeff = 0.6
        initial_R = to_resolution
        initial_vrad = 0
        max_iterations = 6

        # Selected model amtosphere, linelist and solar abundances
        #model = ispec_dir + "/input/atmospheres/MARCS/"
        model = ispec_dir + "/input/atmospheres/MARCS.GES/"
        #model = ispec_dir + "/input/atmospheres/MARCS.APOGEE/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.APOGEE/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.Castelli/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.Kurucz/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.Kirby/"

        #atomic_linelist_file = ispec_dir + "/input/linelists/transitions/VALD.300_1100nm/atomic_lines.tsv"
        #atomic_linelist_file = ispec_dir + "/input/linelists/transitions/VALD.1100_2400nm/atomic_lines.tsv"
        atomic_linelist_file = ispec_dir + "/input/linelists/transitions/GESv6_atom_hfs_iso.420_920nm/atomic_lines.tsv"
        #atomic_linelist_file = ispec_dir + "/input/linelists/transitions/GESv6_atom_nohfs_noiso.420_920nm/atomic_lines.tsv"

        if "ATLAS" in model:
            solar_abundances_file = ispec_dir + "/input/abundances/Grevesse.1998/stdatom.dat"
        else:
            # MARCS
            solar_abundances_file = ispec_dir + "/input/abundances/Grevesse.2007/stdatom.dat"
        #solar_abundances_file = ispec_dir + "/input/abundances/Asplund.2005/stdatom.dat"
        #solar_abundances_file = ispec_dir + "/input/abundances/Asplund.2009/stdatom.dat"
        #solar_abundances_file = ispec_dir + "/input/abundances/Anders.1989/stdatom.dat"

        isotope_file = ispec_dir + "/input/isotopes/SPECTRUM.lst"

        # Load chemical information and linelist
        atomic_linelist = ispec.read_atomic_linelist(
            atomic_linelist_file,
            wave_base=np.min(star_spectrum['waveobs']),
            wave_top=np.max(star_spectrum['waveobs']))
        atomic_linelist = atomic_linelist[
            atomic_linelist['theoretical_depth'] >=
            0.01]  # Select lines that have some minimal contribution in the sun

        isotopes = ispec.read_isotope_data(isotope_file)

        # Load model atmospheres
        modeled_layers_pack = ispec.load_modeled_layers_pack(model)

        # Load SPECTRUM abundances
        solar_abundances = ispec.read_solar_abundances(solar_abundances_file)

        # Free parameters
        #free_params = ["teff", "logg", "MH", "vmic", "vmac", "vsini", "R", "vrad", "limb_darkening_coeff"]
        free_params = ["teff", "logg", "MH", "vmic", "R"]

        # Free individual element abundance
        free_abundances = None
        linelist_free_loggf = None

        # Line regions
        line_regions = ispec.read_line_regions(
            ispec_dir +
            "/input/regions/47000_GES/{}_synth_good_for_params_all.txt".format(
                code))
        #line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_GES/{}_synth_good_for_params_all_extended.txt".format(code))
        #line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_VALD/{}_synth_good_for_params_all.txt".format(code))
        #line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_VALD/{}_synth_good_for_params_all_extended.txt".format(code))
        ## Select only some lines to speed up the execution (in a real analysis it is better not to do this)
        line_regions = line_regions[np.logical_or(
            line_regions['note'] == 'Ti 1', line_regions['note'] == 'Ti 2')]
        line_regions = ispec.adjust_linemasks(normalized_star_spectrum,
                                              line_regions,
                                              max_margin=0.5)
        # Read segments if we have them or...
        #segments = ispec.read_segment_regions(ispec_dir + "/input/regions/fe_lines_segments.txt")
        # ... or we can create the segments on the fly:
        segments = ispec.create_segments_around_lines(line_regions,
                                                      margin=0.25)

        ### Add also regions from the wings of strong lines:
        ## H beta
        #hbeta_lines = ispec.read_line_regions(ispec_dir + "input/regions/wings_Hbeta.txt")
        #hbeta_segments = ispec.read_segment_regions(ispec_dir + "input/regions/wings_Hbeta_segments.txt")
        #line_regions = np.hstack((line_regions, hbeta_lines))
        #segments = np.hstack((segments, hbeta_segments))
        ## H alpha
        #halpha_lines = ispec.read_line_regions(ispec_dir + "input/regions/wings_Halpha.txt")
        #halpha_segments = ispec.read_segment_regions(ispec_dir + "input/regions/wings_Halpha_segments.txt")
        #line_regions = np.hstack((line_regions, halpha_lines))
        #segments = np.hstack((segments, halpha_segments))
        ## Magnesium triplet
        #mgtriplet_lines = ispec.read_line_regions(ispec_dir + "input/regions/wings_MgTriplet.txt")
        #mgtriplet_segments = ispec.read_segment_regions(ispec_dir + "input/regions/wings_MgTriplet_segments.txt")
        #line_regions = np.hstack((line_regions, mgtriplet_lines))
        #segments = np.hstack((segments, mgtriplet_segments))

        obs_spec, modeled_synth_spectrum, params, errors, abundances_found, loggf_found, status, stats_linemasks = \
                ispec.model_spectrum(normalized_star_spectrum, star_continuum_model, \
                modeled_layers_pack, atomic_linelist, isotopes, solar_abundances, free_abundances, linelist_free_loggf, initial_teff, \
                initial_logg, initial_MH, initial_alpha, initial_vmic, initial_vmac, initial_vsini, \
                initial_limb_darkening_coeff, initial_R, initial_vrad, free_params, segments=segments, \
                linemasks=line_regions, \
                enhance_abundances=True, \
                use_errors = True, \
                vmic_from_empirical_relation = False, \
                vmac_from_empirical_relation = True, \
                max_iterations=max_iterations, \
                tmp_dir = None, \
                code=code)

        expected_params = {
            'teff': 5696.144535300913,
            'logg': 4.35386512625295,
            'MH': -0.117924251886487,
            'alpha': 0.047169700754594805,
            'vmic': 1.1383979614486783,
            'vmac': 4.04,
            'vsini': 2.0,
            'limb_darkening_coeff': 0.6,
            'R': 49936.32725781359
        }
        for k, v in list(expected_params.items()):
            self.assertAlmostEqual(params[k], v)
        expected_errors = {
            'teff': 66.38643184730074,
            'logg': 0.10101410057739481,
            'MH': 0.07728877921624414,
            'alpha': 0.0,
            'vmic': 0.10922339131594937,
            'vmac': 0.0,
            'vsini': 0.0,
            'limb_darkening_coeff': 0.0,
            'R': 3496.439438356713
        }
        for k, v in list(expected_errors.items()):
            self.assertAlmostEqual(errors[k], v)
        self.assertEqual(len(stats_linemasks), 30)
Пример #5
0
    def test_determine_astrophysical_parameters_using_grid(self):
        star_spectrum = ispec.read_spectrum(
            ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
        #star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_Arcturus.txt.gz")
        #star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_muCas.txt.gz")
        #star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/NARVAL_muLeo.txt.gz")
        #star_spectrum = ispec.read_spectrum(ispec_dir + "/input/spectra/examples/HARPS.GBOG_Procyon.txt.gz")
        #--- Radial Velocity determination with template -------------------------------
        # - Read synthetic template
        #template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Arcturus.372_926nm/template.txt.gz")
        #template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Sun.372_926nm/template.txt.gz")
        template = ispec.read_spectrum(
            ispec_dir +
            "/input/spectra/templates/NARVAL.Sun.370_1048nm/template.txt.gz")
        #template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Synth.Sun.300_1100nm/template.txt.gz")

        models, ccf = ispec.cross_correlate_with_template(star_spectrum, template, \
                                lower_velocity_limit=-200, upper_velocity_limit=200, \
                                velocity_step=1.0, fourier=False)

        # Number of models represent the number of components
        components = len(models)
        # First component:
        rv = np.round(models[0].mu(), 2)  # km/s
        rv_err = np.round(models[0].emu(), 2)  # km/s
        #--- Radial Velocity correction ------------------------------------------------
        star_spectrum = ispec.correct_velocity(star_spectrum, rv)
        #--- Resolution degradation ----------------------------------------------------
        # NOTE: The line selection was built based on a solar spectrum with R ~ 47,000 and GES/VALD atomic linelist.
        from_resolution = 80000
        to_resolution = 47000
        star_spectrum = ispec.convolve_spectrum(star_spectrum, to_resolution,
                                                from_resolution)
        #--- Continuum fit -------------------------------------------------------------
        model = "Splines"  # "Polynomy"
        degree = 2
        nknots = None  # Automatic: 1 spline every 5 nm
        from_resolution = to_resolution

        # Strategy: Filter first median values and secondly MAXIMUMs in order to find the continuum
        order = 'median+max'
        median_wave_range = 0.05
        max_wave_range = 1.0

        star_continuum_model = ispec.fit_continuum(star_spectrum, from_resolution=from_resolution, \
                                    nknots=nknots, degree=degree, \
                                    median_wave_range=median_wave_range, \
                                    max_wave_range=max_wave_range, \
                                    model=model, order=order, \
                                    automatic_strong_line_detection=True, \
                                    strong_line_probability=0.5, \
                                    use_errors_for_fitting=True)
        #--- Normalize -------------------------------------------------------------
        normalized_star_spectrum = ispec.normalize_spectrum(
            star_spectrum,
            star_continuum_model,
            consider_continuum_errors=False)
        # Use a fixed value because the spectrum is already normalized
        star_continuum_model = ispec.fit_continuum(star_spectrum,
                                                   fixed_value=1.0,
                                                   model="Fixed value")
        #--- Model spectra ----------------------------------------------------------
        # Parameters
        initial_teff = 5750.0
        initial_logg = 4.5
        initial_MH = 0.00
        initial_alpha = 0.00
        initial_vmic = ispec.estimate_vmic(initial_teff, initial_logg,
                                           initial_MH)
        initial_vmac = ispec.estimate_vmac(initial_teff, initial_logg,
                                           initial_MH)
        initial_vsini = 2.0
        initial_limb_darkening_coeff = 0.6
        initial_R = to_resolution
        initial_vrad = 0
        max_iterations = 20

        code = "grid"
        precomputed_grid_dir = ispec_dir + "/input/grid/SPECTRUM_MARCS.GES_GESv6_atom_hfs_iso.480_680nm_light/"

        atomic_linelist = None
        isotopes = None
        modeled_layers_pack = None
        solar_abundances = None
        free_abundances = None
        linelist_free_loggf = None

        # Free parameters (vmic cannot be used as a free parameter when using a spectral grid)
        #free_params = ["teff", "logg", "MH", "alpha", "vmic", "vmac", "vsini", "R", "vrad", "limb_darkening_coeff"]
        free_params = ["teff", "logg", "MH", "alpha", "vmic", "R"]

        # Line regions
        line_regions = ispec.read_line_regions(
            ispec_dir +
            "/input/regions/47000_GES/{}_synth_good_for_params_all.txt".format(
                code))
        #line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_GES/{}_synth_good_for_params_all_extended.txt".format(code))
        #line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_VALD/{}_synth_good_for_params_all.txt".format(code))
        #line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_VALD/{}_synth_good_for_params_all_extended.txt".format(code))
        ## Select only some lines to speed up the execution (in a real analysis it is better not to do this)
        #line_regions = line_regions[np.logical_or(line_regions['note'] == 'Ti 1', line_regions['note'] == 'Ti 2')]
        #line_regions = ispec.adjust_linemasks(normalized_star_spectrum, line_regions, max_margin=0.5)
        # Read segments if we have them or...
        #segments = ispec.read_segment_regions(ispec_dir + "/input/regions/fe_lines_segments.txt")
        # ... or we can create the segments on the fly:
        segments = ispec.create_segments_around_lines(line_regions,
                                                      margin=0.25)

        ## Add also regions from the wings of strong lines:
        # H beta
        hbeta_lines = ispec.read_line_regions(ispec_dir +
                                              "input/regions/wings_Hbeta.txt")
        hbeta_segments = ispec.read_segment_regions(
            ispec_dir + "input/regions/wings_Hbeta_segments.txt")
        line_regions = np.hstack((line_regions, hbeta_lines))
        segments = np.hstack((segments, hbeta_segments))
        # H alpha
        halpha_lines = ispec.read_line_regions(
            ispec_dir + "input/regions/wings_Halpha.txt")
        halpha_segments = ispec.read_segment_regions(
            ispec_dir + "input/regions/wings_Halpha_segments.txt")
        line_regions = np.hstack((line_regions, halpha_lines))
        segments = np.hstack((segments, halpha_segments))
        # Magnesium triplet
        mgtriplet_lines = ispec.read_line_regions(
            ispec_dir + "input/regions/wings_MgTriplet.txt")
        mgtriplet_segments = ispec.read_segment_regions(
            ispec_dir + "input/regions/wings_MgTriplet_segments.txt")
        line_regions = np.hstack((line_regions, mgtriplet_lines))
        segments = np.hstack((segments, mgtriplet_segments))

        obs_spec, modeled_synth_spectrum, params, errors, abundances_found, loggf_found, status, stats_linemasks = \
                ispec.model_spectrum(normalized_star_spectrum, star_continuum_model, \
                modeled_layers_pack, atomic_linelist, isotopes, solar_abundances, free_abundances, linelist_free_loggf, initial_teff, \
                initial_logg, initial_MH, initial_alpha, initial_vmic, initial_vmac, initial_vsini, \
                initial_limb_darkening_coeff, initial_R, initial_vrad, free_params, segments=segments, \
                linemasks=line_regions, \
                enhance_abundances=False, \
                use_errors = True, \
                vmic_from_empirical_relation = False, \
                vmac_from_empirical_relation = True, \
                max_iterations=max_iterations, \
                tmp_dir = None, \
                code=code, precomputed_grid_dir=precomputed_grid_dir)

        expected_params = {
            'teff': 5848.516352941799,
            'logg': 4.47140586507073,
            'MH': 0.021745200217247945,
            'alpha': 0.0,
            'vmic': 0.5617098008018283,
            'vmac': 4.5,
            'vsini': 2.0,
            'limb_darkening_coeff': 0.6,
            'R': 78395.52968455742
        }
        for k, v in list(expected_params.items()):
            self.assertAlmostEqual(params[k], v)
        expected_errors = {
            'teff': 16.061649602869444,
            'logg': 0.028408456932473077,
            'MH': 0.007324730574204324,
            'alpha': 0.007733907152934892,
            'vmic': 0.043996803165640905,
            'vmac': 0.0,
            'vsini': 0.0,
            'limb_darkening_coeff': 0.0,
            'R': 3898.724894322937
        }
        for k, v in list(expected_errors.items()):
            self.assertAlmostEqual(errors[k], v)
        self.assertEqual(len(stats_linemasks), 337)
Пример #6
0
def synthesize_spectrum(theta, code="moog"):
    teff, logg, MH, vsini = theta
    resolution = 48000

    microturbulence_vel = ispec.estimate_vmic(teff, logg, MH)
    macroturbulence = ispec.estimate_vmac(teff, logg, MH)

    limb_darkening_coeff = 0.6
    regions = None
    wave_base = 609.0
    wave_top = 620.0

    model = ispec_dir + "/input/atmospheres/ATLAS9.Castelli/"

    atomic_linelist_file = ispec_dir + "/input/linelists/transitions/VALD.300_1100nm/atomic_lines.tsv"
    #atomic_linelist_file = ispec_dir + "/input/linelists/transitions/GESv5_atom_hfs_iso.420_920nm/atomic_lines.tsv"

    isotope_file = ispec_dir + "/input/isotopes/SPECTRUM.lst"
    alpha = ispec.determine_abundance_enchancements(MH)

    atomic_linelist = ispec.read_atomic_linelist(atomic_linelist_file,
                                                 wave_base=wave_base,
                                                 wave_top=wave_top)
    atomic_linelist = atomic_linelist[
        atomic_linelist['theoretical_depth'] >= 0.01]

    isotopes = ispec.read_isotope_data(isotope_file)

    solar_abundances_file = ispec_dir + "/input/abundances/Asplund.2009/stdatom.dat"

    solar_abundances = ispec.read_solar_abundances(solar_abundances_file)
    fixed_abundances = None
    modeled_layers_pack = ispec.load_modeled_layers_pack(model)
    atmosphere_layers = ispec.interpolate_atmosphere_layers(
        modeled_layers_pack, {
            'teff': teff,
            'logg': logg,
            'MH': MH,
            'alpha': alpha
        },
        code=code)
    synth_spectrum = ispec.create_spectrum_structure(x)
    synth_spectrum['flux'] = ispec.generate_spectrum(
        synth_spectrum['waveobs'],
        atmosphere_layers,
        teff,
        logg,
        MH,
        alpha,
        atomic_linelist,
        isotopes,
        solar_abundances,
        fixed_abundances,
        microturbulence_vel=microturbulence_vel,
        macroturbulence=macroturbulence,
        vsini=vsini,
        limb_darkening_coeff=limb_darkening_coeff,
        R=resolution,
        regions=regions,
        verbose=0,
        code=code)

    return synth_spectrum
Пример #7
0
    def test_determine_abundances_using_synth_spectra(self):
        code = "spectrum"
        star_spectrum = ispec.read_spectrum(
            ispec_dir + "/input/spectra/examples/NARVAL_Sun_Vesta-1.txt.gz")
        #--- Radial Velocity determination with template -------------------------------
        # - Read synthetic template
        #template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Arcturus.372_926nm/template.txt.gz")
        #template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Atlas.Sun.372_926nm/template.txt.gz")
        template = ispec.read_spectrum(
            ispec_dir +
            "/input/spectra/templates/NARVAL.Sun.370_1048nm/template.txt.gz")
        #template = ispec.read_spectrum(ispec_dir + "/input/spectra/templates/Synth.Sun.300_1100nm/template.txt.gz")

        models, ccf = ispec.cross_correlate_with_template(star_spectrum, template, \
                                lower_velocity_limit=-200, upper_velocity_limit=200, \
                                velocity_step=1.0, fourier=False)

        # Number of models represent the number of components
        components = len(models)
        # First component:
        rv = np.round(models[0].mu(), 2)  # km/s
        rv_err = np.round(models[0].emu(), 2)  # km/s
        #--- Radial Velocity correction ------------------------------------------------
        star_spectrum = ispec.correct_velocity(star_spectrum, rv)

        #--- Resolution degradation ----------------------------------------------------
        # NOTE: The line selection was built based on a solar spectrum with R ~ 47,000 and GES/VALD atomic linelist.
        from_resolution = 80000
        to_resolution = 47000
        star_spectrum = ispec.convolve_spectrum(star_spectrum, to_resolution,
                                                from_resolution)

        #--- Continuum fit -------------------------------------------------------------
        model = "Splines"  # "Polynomy"
        degree = 2
        nknots = None  # Automatic: 1 spline every 5 nm
        from_resolution = to_resolution

        # Strategy: Filter first median values and secondly MAXIMUMs in order to find the continuum
        order = 'median+max'
        median_wave_range = 0.05
        max_wave_range = 1.0

        star_continuum_model = ispec.fit_continuum(star_spectrum, from_resolution=from_resolution, \
                                    nknots=nknots, degree=degree, \
                                    median_wave_range=median_wave_range, \
                                    max_wave_range=max_wave_range, \
                                    model=model, order=order, \
                                    automatic_strong_line_detection=True, \
                                    strong_line_probability=0.5, \
                                    use_errors_for_fitting=True)
        #--- Normalize -------------------------------------------------------------
        normalized_star_spectrum = ispec.normalize_spectrum(
            star_spectrum,
            star_continuum_model,
            consider_continuum_errors=False)
        # Use a fixed value because the spectrum is already normalized
        star_continuum_model = ispec.fit_continuum(star_spectrum,
                                                   fixed_value=1.0,
                                                   model="Fixed value")
        #--- Model spectra ----------------------------------------------------------
        # Parameters
        initial_teff = 5771.0
        initial_logg = 4.44
        initial_MH = 0.00
        initial_alpha = 0.00
        initial_vmic = ispec.estimate_vmic(initial_teff, initial_logg,
                                           initial_MH)
        initial_vmac = ispec.estimate_vmac(initial_teff, initial_logg,
                                           initial_MH)
        initial_vsini = 1.60  # Sun
        initial_limb_darkening_coeff = 0.6
        initial_R = to_resolution
        initial_vrad = 0
        max_iterations = 6

        # Selected model amtosphere, linelist and solar abundances
        #model = ispec_dir + "/input/atmospheres/MARCS/"
        model = ispec_dir + "/input/atmospheres/MARCS.GES/"
        #model = ispec_dir + "/input/atmospheres/MARCS.APOGEE/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.APOGEE/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.Castelli/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.Kurucz/"
        #model = ispec_dir + "/input/atmospheres/ATLAS9.Kirby/"

        #atomic_linelist_file = ispec_dir + "/input/linelists/transitions/VALD.300_1100nm/atomic_lines.tsv"
        #atomic_linelist_file = ispec_dir + "/input/linelists/transitions/VALD.1100_2400nm/atomic_lines.tsv"
        atomic_linelist_file = ispec_dir + "/input/linelists/transitions/GESv6_atom_hfs_iso.420_920nm/atomic_lines.tsv"
        #atomic_linelist_file = ispec_dir + "/input/linelists/transitions/GESv6_atom_nohfs_noiso.420_920nm/atomic_lines.tsv"

        if "ATLAS" in model:
            solar_abundances_file = ispec_dir + "/input/abundances/Grevesse.1998/stdatom.dat"
        else:
            # MARCS
            solar_abundances_file = ispec_dir + "/input/abundances/Grevesse.2007/stdatom.dat"
        #solar_abundances_file = ispec_dir + "/input/abundances/Asplund.2005/stdatom.dat"
        #solar_abundances_file = ispec_dir + "/input/abundances/Asplund.2009/stdatom.dat"
        #solar_abundances_file = ispec_dir + "/input/abundances/Anders.1989/stdatom.dat"

        isotope_file = ispec_dir + "/input/isotopes/SPECTRUM.lst"

        # Load chemical information and linelist
        atomic_linelist = ispec.read_atomic_linelist(
            atomic_linelist_file,
            wave_base=np.min(star_spectrum['waveobs']),
            wave_top=np.max(star_spectrum['waveobs']))
        atomic_linelist = atomic_linelist[
            atomic_linelist['theoretical_depth'] >=
            0.01]  # Select lines that have some minimal contribution in the sun

        isotopes = ispec.read_isotope_data(isotope_file)

        # Load model atmospheres
        modeled_layers_pack = ispec.load_modeled_layers_pack(model)

        # Load SPECTRUM abundances
        solar_abundances = ispec.read_solar_abundances(solar_abundances_file)

        # Free parameters
        #free_params = ["teff", "logg", "MH", "vmic", "vmac", "vsini", "R", "vrad", "limb_darkening_coeff"]
        free_params = ["vrad"]
        #free_params = []

        # Free individual element abundance (WARNING: it should be coherent with the selected line regions!)
        chemical_elements_file = ispec_dir + "/input/abundances/chemical_elements_symbols.dat"
        chemical_elements = ispec.read_chemical_elements(
            chemical_elements_file)

        element_name = "Ca"
        free_abundances = ispec.create_free_abundances_structure(
            [element_name], chemical_elements, solar_abundances)
        free_abundances['Abund'] += initial_MH  # Scale to metallicity

        linelist_free_loggf = None

        # Line regions
        line_regions = ispec.read_line_regions(
            ispec_dir +
            "/input/regions/47000_GES/{}_synth_good_for_params_all.txt".format(
                code))
        #line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_GES/{}_synth_good_for_params_all_extended.txt".format(code))
        #line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_VALD/{}_synth_good_for_params_all.txt".format(code))
        #line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_VALD/{}_synth_good_for_params_all_extended.txt".format(code))
        # Select only the lines to get abundances from
        line_regions = line_regions[np.logical_or(
            line_regions['note'] == element_name + ' 1',
            line_regions['note'] == element_name + ' 2')]
        line_regions = ispec.adjust_linemasks(normalized_star_spectrum,
                                              line_regions,
                                              max_margin=0.5)

        # Read segments if we have them or...
        #segments = ispec.read_segment_regions(ispec_dir + "/input/regions/fe_lines_segments.txt")
        # ... or we can create the segments on the fly:
        segments = ispec.create_segments_around_lines(line_regions,
                                                      margin=0.25)

        obs_spec, modeled_synth_spectrum, params, errors, abundances_found, loggf_found, status, stats_linemasks = \
                ispec.model_spectrum(normalized_star_spectrum, star_continuum_model, \
                modeled_layers_pack, atomic_linelist, isotopes, solar_abundances, free_abundances, linelist_free_loggf, initial_teff, \
                initial_logg, initial_MH, initial_alpha, initial_vmic, initial_vmac, initial_vsini, \
                initial_limb_darkening_coeff, initial_R, initial_vrad, free_params, segments=segments, \
                linemasks=line_regions, \
                enhance_abundances=True, \
                use_errors = True, \
                vmic_from_empirical_relation = False, \
                vmac_from_empirical_relation = False, \
                max_iterations=max_iterations, \
                tmp_dir = None, \
                code=code)

        expected_params = {
            'teff': 5771.0,
            'logg': 4.44,
            'MH': 0.0,
            'alpha': 0.0,
            'vmic': 1.07,
            'vmac': 4.19,
            'vsini': 1.6,
            'limb_darkening_coeff': 0.6,
            'R': 47000.0,
            'vrad0000': -0.009293697395991595,
            'vrad0001': -0.06018526081728252,
            'vrad0002': -0.015666491320596353,
            'vrad0003': -0.055193632795656256,
            'vrad0004': -0.1567689404172516,
            'vrad0005': -0.22508061064189286,
            'vrad0006': -0.20359311863771612,
            'vrad0007': -0.16078450322612126
        }
        for k, v in list(expected_params.items()):
            self.assertAlmostEqual(params[k], v)
        expected_errors = {
            'teff': 0.0,
            'logg': 0.0,
            'MH': 0.0,
            'alpha': 0.0,
            'vmic': 0.0,
            'vmac': 0.0,
            'vsini': 0.0,
            'limb_darkening_coeff': 0.0,
            'R': 0.0,
            'vrad0000': 2.2914331925224816,
            'vrad0001': 0.6770488621090028,
            'vrad0002': 0.2767472596825708,
            'vrad0003': 1.0820599330375968,
            'vrad0004': 0.47734411482243877,
            'vrad0005': 0.2585031799872256,
            'vrad0006': 0.46187116575854853,
            'vrad0007': 0.23921192411257394
        }
        for k, v in list(expected_errors.items()):
            self.assertAlmostEqual(errors[k], v)
        self.assertEqual(len(stats_linemasks), 8)
        self.assertEqual(abundances_found['element'][0], 'Ca')
        self.assertAlmostEqual(abundances_found['[X/H]'][0],
                               -0.0020078068382556324)
        self.assertAlmostEqual(abundances_found['[X/Fe]'][0],
                               -0.0020078068382556324)
        self.assertAlmostEqual(abundances_found['e[X/H]'][0],
                               0.027149612080779945)
        self.assertAlmostEqual(abundances_found['e[X/Fe]'][0],
                               0.027149612080779945)
Пример #8
0
def param_using_grid(normalized_star_spectrum, star_continuum_model, object_id,\
    resolution=80000, p0 = [5750.0, 4.5, 0, 0, 2, 0.6, 0], max_iter = 10):
    ''' Derive spectroscopic parameters using grid model 
    p0 are initial values list:
    teff, logg, MH, alpha, vsini, limb_darkening coef, vrad 
   
    Returns params, errors and ispec_pectrum object with spectra form best fit
    '''

    #--- Model spectra --------------------------------------------------------
    # Parameters initiall values
    initial_teff = p0[0]
    initial_logg = p0[1]
    initial_MH = p0[2]
    initial_alpha = p0[3]
    initial_vmic = ispec.estimate_vmic(initial_teff, initial_logg, initial_MH)
    initial_vmac = ispec.estimate_vmac(initial_teff, initial_logg, initial_MH)
    initial_vsini = p0[4]
    initial_limb_darkening_coeff = p0[5]
    initial_R = resolution
    initial_vrad = p0[6]
    max_iterations = max_iter

    #load grid
    code = "grid"
    precomputed_grid_dir = ispec_dir + "/input/grid/SPECTRUM_MARCS.GES_GESv5_atom_hfs_iso.480_680nm_light/"

    atomic_linelist = None
    isotopes = None
    modeled_layers_pack = None
    solar_abundances = None
    free_abundances = None
    linelist_free_loggf = None

    # Free parameters (vmic cannot be used as a free parameter when using a spectral grid)

    free_params = ["teff", "logg", "MH", "alpha", "R"]

    # Line regions
    line_regions = ispec.read_line_regions(
        ispec_dir +
        "/input/regions/47000_GES/{}_synth_good_for_params_all.txt".format(
            code))
    #line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_GES/{}_synth_good_for_params_all_extended.txt".format(code))
    #line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_VALD/{}_synth_good_for_params_all.txt".format(code))
    #line_regions = ispec.read_line_regions(ispec_dir + "/input/regions/47000_VALD/{}_synth_good_for_params_all_extended.txt".format(code))
    ## Select only some lines to speed up the execution (in a real analysis it is better not to do this)
    #line_regions = line_regions[np.logical_or(line_regions['note'] == 'Ti 1', line_regions['note'] == 'Ti 2')]
    #line_regions = ispec.adjust_linemasks(normalized_star_spectrum, line_regions, max_margin=0.5)

    # Read segments if we have them or...
    #segments = ispec.read_segment_regions(ispec_dir + "/input/regions/fe_lines_segments.txt")
    # ... or we can create the segments on the fly:
    segments = ispec.create_segments_around_lines(line_regions, margin=0.25)

    ## Add also regions from the wings of strong lines:
    # H beta
    hbeta_lines = ispec.read_line_regions(ispec_dir +
                                          "/input/regions/wings_Hbeta.txt")
    hbeta_segments = ispec.read_segment_regions(
        ispec_dir + "/input/regions/wings_Hbeta_segments.txt")
    line_regions = np.hstack((line_regions, hbeta_lines))
    segments = np.hstack((segments, hbeta_segments))
    # H alpha
    halpha_lines = ispec.read_line_regions(ispec_dir +
                                           "/input/regions/wings_Halpha.txt")
    halpha_segments = ispec.read_segment_regions(
        ispec_dir + "/input/regions/wings_Halpha_segments.txt")
    line_regions = np.hstack((line_regions, halpha_lines))
    segments = np.hstack((segments, halpha_segments))
    # Magnesium triplet
    mgtriplet_lines = ispec.read_line_regions(
        ispec_dir + "/input/regions/wings_MgTriplet.txt")
    mgtriplet_segments = ispec.read_segment_regions(
        ispec_dir + "/input/regions/wings_MgTriplet_segments.txt")
    line_regions = np.hstack((line_regions, mgtriplet_lines))
    segments = np.hstack((segments, mgtriplet_segments))

    # run model spectra from grid!
    obs_spec, modeled_synth_spectrum, params, errors, abundances_found,\
    loggf_found, status, stats_linemasks = \
    ispec.model_spectrum(normalized_star_spectrum, star_continuum_model,\
    modeled_layers_pack, atomic_linelist, isotopes, solar_abundances,\
    free_abundances, linelist_free_loggf, initial_teff, initial_logg,\
    initial_MH, initial_alpha, initial_vmic, initial_vmac, initial_vsini,\
    initial_limb_darkening_coeff, initial_R, initial_vrad, free_params,\
    segments=segments, linemasks=line_regions, enhance_abundances=False,\
    use_errors = True, vmic_from_empirical_relation = False,\
    vmac_from_empirical_relation = True, max_iterations=max_iterations,\
    tmp_dir = None, code=code, precomputed_grid_dir=precomputed_grid_dir)

    ##--- Save results ---------------------------------------------------------
    #logging.info("Saving results...")
    dump_file = "example_results_synth_grid_%s.dump" % (object_id)
    #logging.info("Saving results...")
    ispec.save_results(dump_file, (params, errors, abundances_found,
                                   loggf_found, status, stats_linemasks))
    # If we need to restore the results from another script:
    # params, errors, abundances_found, loggf_found, status, stats_linemasks = ispec.restore_results(dump_file)

    #logging.info("Saving synthetic spectrum...")
    synth_filename = "example_modeled_synth_grid_%s.fits" % (object_id)
    ispec.write_spectrum(modeled_synth_spectrum, synth_filename)
    return params, errors, modeled_synth_spectrum