Esempio n. 1
0
        massFracPlotFile = objFolder / f'{obj}_{ext}_SSP_MasFrac_Papaderos_{cycle}.png'
        LightFracPlotFile = objFolder / f'{obj}_{ext}_SSP_LightFrac_Papaderos_{cycle}.png'
        stellarPlotFile = objFolder / f'{obj}_{ext}_stellarFit_Papaderos_{cycle}.png'
        maskPlotFile = objFolder / f'{obj}_{ext}_maskAndFlags_Papaderos_{cycle}.png'
        stellarFluxFile = objFolder / f'{obj}_{ext}_stellarFlux_Papaderos_{cycle}.txt'

        # Load the data
        wave, flux_array, header = sr.import_fits_data(fits_file, instrument='OSIRIS')
        flux = flux_array[idx_band][0] if ext in ('_B', '_R') else flux_array
        lm = sr.LineMesurer(wave, flux, redshift=z_array[i], crop_waves=(wmin_array[i], wmax_array[i]))

        # Starlight wrapper
        sw = SSPsynthesizer()

        # Read output data
        stellar_Wave, obj_input_flux, stellar_flux, fit_output = sw.load_starlight_output(starlight2012_folder/outputFile)
        z_gp = obsData['sample_data']['z_array'][i]
        Mcor, Mint = fit_output['Mcor_tot'], fit_output['Mini_tot']
        mass_galaxy = computeSSP_galaxy_mass(Mcor, 1, z_gp)
        massProcess_galaxy = computeSSP_galaxy_mass(Mint, 1, z_gp)
        idcs_below_20Myr = fit_output['DF'].age_j < 2*10**7
        mass_galaxy_20Myr_percent = np.sum(fit_output['DF'].loc[idcs_below_20Myr, 'Mcor_j'].values)

        # Store starlight configuration values for linux runy
        rc = pn.RedCorr(R_V=RV, E_BV=fit_output['Av_min'] / RV, law=red_law)
        cHbeta_star = rc.cHbetaFromEbv(fit_output['Av_min']/RV)
        starlight_cfg = {'gridFileName': outputFile,
                         'outputFile': outputFile,
                         'saveFolder': starlight2012_folder.as_posix(),
                         'Galaxy_mass_Current': mass_galaxy,
                         'Galaxy_mass_Prosessed': massProcess_galaxy,
        specCompPlot = outputFolder / f'{obj}{ext}_specComponents.png'

        # Set wavelength and flux
        print(f'\n-- Treating {counter} :{obj}{ext}.fits')
        wave, flux_array, header = sr.import_fits_data(fits_file,
                                                       instrument='OSIRIS')
        wave_rest = wave / (1 + z)
        idx_wave = (wave_rest >= wmin_array[i]) & (wave_rest <= wmax_array[i])
        flux = flux_array[idx_band][0] if ext in ('_B', '_R') else flux_array

        obsWave, obsFlux = wave_rest[idx_wave], flux[idx_wave]
        nebWave, nebFlux = np.loadtxt(nebCompFile, unpack=True)
        obsNoNebWave, obsNoNebFlux = np.loadtxt(nebFluxNoNebCompFile,
                                                unpack=True)
        sw = SSPsynthesizer()
        stellarWave, inFlux, stellarFlux, fit_output = sw.load_starlight_output(
            starlightOutput)
        tsl = atpy.TableSet(str(starlightOutput), type='starlightv4')
        psfh = plot_fits_and_SFH(tsl)
        psfh.plot_fig_starlight()

        # collapse = False
        # cumsum = False
        # zcolor = [item['color'] for item in matplotlib.rcParams['axes.prop_cycle']]
        # fig = plt.figure(figsize=(10, 8))
        # gs = gridspec.GridSpec(2, 1)
        # gs.update(left=0.05, bottom=0.05, right=0.98, hspace=0.0)
        # ageBase = np.unique(tsl.population['popage_base'])
        # zBase = np.unique(tsl.population['popZ_base'])
        # lageBase = np.log10(ageBase)
        # log_age = np.log10(tsl.population['popage_base'])
        # # Bin width
            # Generate starlight files
            idcs_lines = ~lm.linesDF.index.str.contains('_b')
            gridFileName, outputFile, saveFolder, waveResample, fluxResample = sw.generate_starlight_files(starlightFolder,
                                                                                                             f'{obj}{ext}',
                                                                                                             specWave,
                                                                                                             specFlux,
                                                                                                             lm.linesDF.loc[idcs_lines])

            # # Launch starlight
            # print(f'\n-Initiating starlight: {obj}')
            # sw.starlight_launcher(gridFileName, starlightFolder)
            # print('\n-Starlight finished succesfully ended')

            # Read output data
            Input_Wavelength, Input_Flux, Output_Flux, fit_output = sw.load_starlight_output(starlightFolder/'Output'/outputFile)
            z_gp = obsData['sample_data']['z_array'][i]
            Mcor, Mint = fit_output['Mcor_tot'], fit_output['Mini_tot']
            mass_galaxy = computeSSP_galaxy_mass(Mcor, 1, z_gp)
            massProcess_galaxy = computeSSP_galaxy_mass(Mint, 1, z_gp)

            if ext == ('_BR'):
                objPlotLabel = f'{obj} full spectrum'
            else:
                objPlotLabel = f'{obj} blue spectrum'


            # Plot the results
            sw.population_fraction_plots(fit_output, objPlotLabel, 'Mass_fraction', massFracPlotFile, mass_galaxy=mass_galaxy)
            sw.population_fraction_plots(fit_output, objPlotLabel, 'Light_fraction', LightFracPlotFile)
            sw.stellar_fit_comparison_plot(objPlotLabel, Input_Wavelength, Input_Flux, Output_Flux, stellarPlotFile)
#     for i, HeI_HI in enumerate(HeI_range):
#         neb_gamma[j, i, :] = nebCalc.gamma_spectrum(wave_bases, temp, HeI_HI, HeII_HI)
# np.save(storing_folder/'neb_gamma', neb_gamma)

bases_df = pd.read_csv(bases_df_file, index_col=0)
wave_bases = np.load(storing_folder / 'waves_bases.npy')
flux_bases = np.load(storing_folder / 'flux_bases.npy')
nebular_bases = np.load(storing_folder / 'neb_gamma.npy')

# gamma_nebularfb_HI = nebCalc.freebound_gamma(wave, Te, self.HI_fb_dict)
# neb_int = nebCalc.flux_spectrum(lm.wave, Te_low, Halpha_int, HeII_HII, HeIII_HeII)

starlight_output_file = Path(
    'D:\Dropbox\Astrophysics\Papers\gtc_greenpeas\data\starlight\Output\gp121903_BR.slOutput'
)
Input_Wavelength, Input_Flux, Output_Flux, fit_output = starCalc.load_starlight_output(
    starlight_output_file)
# #
# # Region 1 templates:
# idcs_1 = (bases_df.age_yr < 1.5e7) & (bases_df.z_star > 0.005)
# z_range_1, age_range_1, flux_matrix_1 = generate_region_templates(bases_df, idcs_1, wave_bases, flux_bases)
# logAge_range_1 = np.log10(age_range_1)
# spy_RGridInterp = spy.interpolate.RegularGridInterpolator((z_range_1, logAge_range_1), flux_matrix_1)
# exop_interpAxis = xo.interp.RegularGridInterpolator([z_range_1, logAge_range_1], flux_matrix_1)
# neb_interpAxis = xo.interp.RegularGridInterpolator([temp_range, HeI_range], nebular_bases)
#
# # Compute nebular component
# Temp_true, HeI_II_true, Halpha_True = 12350.0, 0.1055, 500.0
# coordB = np.stack(([Temp_true], [HeI_II_true]), axis=-1)
# gamma_neb_inter = neb_interpAxis.evaluate(coordB).eval()[0]
# flux_neb_inter = nebCalc.zanstra_calibration(wave_bases, Temp_true, Halpha_True, gamma_neb_inter)
#
    fits_file = dataFolder / f'{obj}{ext}.fits'
    objFolder = resultsFolder / f'{obj}'
    lineLog_file = objFolder / f'{obj}{ext}_linesLog_c2.txt'
    results_file = objFolder / f'{obj}{ext}_measurements.txt'
    objMask = objFolder / f'{obj}{ext}_mask.txt'
    nebCompFile = objFolder / f'{obj}{ext}_NebFlux_{cycle}.txt'
    run_ref = f'{obj}{ext}_{cycle}'
    objSSP_outputFile = starlight_folder / 'Output' / f'{obj}{ext}_it2.slOutput'

    # Starlight wrapper
    sw = SSPsynthesizer()

    # Data output
    results_dict = sr.loadConfData(results_file, group_variables=False)
    stellar_fit_dict = results_dict[f'Starlight_run_it2']
    stellar_Wave, obj_input_flux, stellar_flux, fit_output = sw.load_starlight_output(
        objSSP_outputFile)

    if stellar_fit_dict['A_V_stellarr'] == 0:
        stellar_fit_dict['A_V_stellarr'] = 0.0

    row_data = [
        objRefNames[i],
        np.round(stellar_fit_dict['Galaxy_mass_Current'], 2),
        np.round(stellar_fit_dict['Galaxy_mass_Percentbelow20Myr'], 2),
        np.round(stellar_fit_dict['A_V_stellarr'], 2),
        np.round(stellar_fit_dict['cHbeta_stellar'], 2),
        np.round(stellar_fit_dict['SN'], 2),
        np.round(stellar_fit_dict['Chi2'], 2)
    ]

    pdf.addTableRow(row_data, last_row=False, rounddig=2)
Esempio n. 6
0
    wave, flux, header = sr.import_fits_data(file_address, instrument='OSIRIS')
    z_mean = obsData['sample_data']['z_array'][i]
    wmin_array, wmax_array = obsData['sample_data']['wmin_array'], obsData[
        'sample_data']['wmax_array']

    # Define wave and flux ranges
    wave_rest = wave / (1 + z_mean)
    idx_wave = (wave_rest >= wmin_array[i]) & (wave_rest <= wmax_array[i])

    # Load the data
    obsWave, obsFlux = wave_rest[idx_wave], flux[idx_wave]
    nebWave, nebFlux = np.loadtxt(lineLogFolder / nebCompFile, unpack=True)
    obsNoNebWave, obsNoNebFlux = np.loadtxt(lineLogFolder /
                                            nebFluxNoNebCompFile,
                                            unpack=True)
    stellarWave, inFlux, stellarFlux, fit_output = sw.load_starlight_output(
        outputFileAddress)

    #Increase the range of Wave_S so it is greater than the observational range
    Wave_StellarExtension = np.linspace(3000.0, 3399.0, 200)
    Int_StellarExtension = np.zeros(len(Wave_StellarExtension))

    #Increase the range of Wave_S so it is greater than the observational range
    Wave_S = np.hstack((Wave_StellarExtension, stellarWave))
    Int_S = np.hstack((Int_StellarExtension, stellarFlux))

    #Resampling stellar spectra
    Interpolation = interp1d(Wave_S, Int_S, kind='slinear')
    Int_Stellar_Resampled = Interpolation(obsWave)

    # Save the non object spectrum without stellar component
    obsFluxNoStellar = obsFlux - Int_Stellar_Resampled