Пример #1
0
def plot_orig_data(datafile=None, micron=True, alpha=0.8):
    # plot the original text files
    if datafile is None:
        #datafile = os.path.join(os.path.dirname(__file__),'data/ab4475.')
        datafile = os.path.join(os.path.dirname(__file__), 'data/ab10900.')
    wave_num, obs_s, tel_s, rat_s, obs_w, tel_w, rat_w = np.loadtxt(
        datafile, unpack=True)

    summer_wave = wave_num * 1.0000478

    winter_wave = wave_num * .9999129
    if micron:
        # convert from wavenumber (1/cm) into microns
        summer_wave = (1.0 / summer_wave) * 1e4
        winter_wave = (1.0 / winter_wave) * 1e4

    #plt.plot(summer_wave,rat_s)
    plt.plot(winter_wave, rat_w, label='Arcturus')
    atomic_file = os.path.join(os.path.dirname(__file__),
                               'data/arcturus_atomic_lines.txt')
    molecular_file = os.path.join(os.path.dirname(__file__),
                                  'data/arcturus_molecular_lines.txt')
    atomic_lines, atomic_line_names = np.loadtxt(atomic_file,
                                                 delimiter=',',
                                                 unpack=True,
                                                 dtype=str)
    molecular_lines, molecular_line_names = np.loadtxt(molecular_file,
                                                       delimiter=',',
                                                       unpack=True,
                                                       dtype=str)
    atomic_lines = np.array(atomic_lines, dtype=float) - .00001
    molecular_lines = np.array(molecular_lines, dtype=float) - 0.00001
    molecular_lines = np.array(molecular_lines, dtype=float)
    molecular_line_names = ['$' + lamb + '$' for lamb in molecular_line_names]
    atomic_line_names = ['$' + lamb + '$' for lamb in atomic_line_names]
    plt.ylim(0, 1.1)
    plt.xlim(np.min(winter_wave), np.max(winter_wave))
    #plotlines.oplotlines(spec_wave=winter_wave,spec_flux=rat_w,lines=atomic_lines,line_names=atomic_line_names)
    plotlines.oplotlines(lines=atomic_lines,
                         line_names=atomic_line_names,
                         label=True,
                         color='r',
                         linestyle=':')
    plotlines.oplotlines(lines=molecular_lines,
                         line_names=molecular_line_names,
                         label=True,
                         alpha=alpha)
Пример #2
0
def plot_spectrum(wave_range=[2.15, 2.2]):
    # plot the Arcturus spectrum

    datadir = os.path.join(os.path.dirname(__file__), 'data')
    # plot all the data into a PDF form

    # get the line list
    atomic_file = os.path.join(datadir, 'arcturus_atomic_lines.txt')
    molecular_file = os.path.join(datadir, 'arcturus_molecular_lines.txt')
    atomic_lines, atomic_line_names = np.loadtxt(atomic_file,
                                                 delimiter=',',
                                                 unpack=True,
                                                 dtype=str)
    molecular_lines, molecular_line_names = np.loadtxt(molecular_file,
                                                       delimiter=',',
                                                       unpack=True,
                                                       dtype=str)
    atomic_lines = np.array(atomic_lines, dtype=float) - .00001
    molecular_lines = np.array(molecular_lines, dtype=float) - 0.00001
    molecular_line_names = ['$' + lamb + '$' for lamb in molecular_line_names]
    atomic_line_names = ['$' + lamb + '$' for lamb in atomic_line_names]

    sns.set_context('paper', font_scale=1.0, rc={"lines.linewidth": 0.8})
    sns.set_style('white')
    sns.set_style('ticks')

    fontscale = 0.75
    wave, flux = spectrum(wave_range=wave_range)
    plt.clf()
    plt.plot(wave, flux)
    plt.ylim(0.2, 1.1)
    plt.xlim(np.min(wave), np.max(wave))
    plotlines.oplotlines(label=True,
                         lines=molecular_lines,
                         line_names=molecular_line_names,
                         size=12 * fontscale,
                         alpha=0.6)
    plotlines.oplotlines(label=True,
                         lines=atomic_lines,
                         line_names=atomic_line_names,
                         size=12 * fontscale,
                         color='r',
                         alpha=0.9,
                         linestyle=':')
Пример #3
0
def plot_orders(star='NE_1_002',
                orders=[37, 36, 35, 34],
                ylim=[0, 1.5],
                noclear=False,
                vel=0):
    # plot all the orders for a star
    if not noclear:
        plt.clf()
    for i in xrange(len(orders)):
        file1 = os.path.join(spectra_dir,
                             star + '_order' + str(orders[i]) + '_nod1.dat')
        tab1 = pd.read_csv(
            file1,
            delim_whitespace=True,
            skiprows=3,
            names=['pixel', 'wave', 'flux', 'nod1', 'nod2', 'diff'])

        plt.subplot(len(orders), 1, i + 1)
        plt.plot(tab1['wave'],
                 tab1['flux'],
                 label=star + ' order ' + str(orders[i]))
        plt.ylim(ylim[0], ylim[1])
        plotlines.oplotlines(vel=vel)
        plt.legend(loc=3)
Пример #4
0
        label="Data")

ax.plot(w / (unmasked_median_fits['vrad_2'] / 3e5 + 1.0),
        f,
        label="Unmasked model with best fit unmasked values")

sl_ax.plot(w / (unmasked_median_fits['vrad_2'] / 3e5 + 1.0),
           logsl,
           label="Log($S_{\lambda}$)",
           color="green")

ax.plot(w / (unmasked_median_fits['vrad_2'] / 3e5 + 1.0),
        logsl + 100.,
        label="Log($S_{\lambda}$)",
        color="green")

ax.set_xlabel("Wavelength (angstroms)", size=12)
ax.set_ylabel("Flux")
sl_ax.set_ylabel("Log($S_{\lambda}$)", size=12)
ax.set_ylim(-0.3, 1.3)

sl_ax.set_ylim(-4, 6.)
ax.set_title("Order 35 Observed and Model fluxes, with sensitivity function",
             size=15)
ax.legend(loc='upper right', fontsize=11)

plt.tick_params(axis='both', which='major', labelsize=11)

plotlines.oplotlines(angstrom=True, arcturus=True, alpha=0.25, size=12)
plt.show()
Пример #5
0
def plot_data_pdf(filename='Arcturus_IR_spectrum.pdf',
                  per_page=2,
                  micron=True,
                  plot_both=False,
                  label_file=False):
    datadir = os.path.join(os.path.dirname(__file__), 'data')
    # plot all the data into a PDF form
    pdf_pages = PdfPages(filename)

    # get the line list
    atomic_file = os.path.join(datadir, 'arcturus_atomic_lines.txt')
    molecular_file = os.path.join(datadir, 'arcturus_molecular_lines.txt')
    atomic_lines, atomic_line_names = np.loadtxt(atomic_file,
                                                 delimiter=',',
                                                 unpack=True,
                                                 dtype=str)
    molecular_lines, molecular_line_names = np.loadtxt(molecular_file,
                                                       delimiter=',',
                                                       unpack=True,
                                                       dtype=str)
    atomic_lines = np.array(atomic_lines, dtype=float) - .00001
    molecular_lines = np.array(molecular_lines, dtype=float) - 0.00001
    molecular_line_names = ['$' + lamb + '$' for lamb in molecular_line_names]
    atomic_line_names = ['$' + lamb + '$' for lamb in atomic_line_names]

    sns.set_context('paper', font_scale=1.0, rc={"lines.linewidth": 0.8})
    sns.set_style('white')
    sns.set_style('ticks')
    fontscale = 0.75

    # spectra files
    specfiles = os.path.join(datadir, 'filenames.txt')
    specnames = np.loadtxt(specfiles, dtype=str, unpack=True)

    for i in xrange(len(specnames)):
        datafile = os.path.join(datadir, specnames[i])
        wave_num, obs_s, tel_s, rat_s, obs_w, tel_w, rat_w = np.loadtxt(
            datafile, unpack=True)

        summer_wave = wave_num * 1.0000478

        winter_wave = wave_num * .9999129
        if micron:
            # convert from wavenumber (1/cm) into microns
            summer_wave = (1.0 / summer_wave) * 1e4
            winter_wave = (1.0 / winter_wave) * 1e4

        if ((i % per_page) == 0):
            fig = plt.figure(figsize=(11, 8.5), dpi=100)
            plt.clf()
        plt.subplot(per_page, 1, (i % per_page) + 1)
        plt.ylim(0, 1.1)
        plt.xlim(np.min(winter_wave), np.max(winter_wave))

        plotlines.oplotlines(label=True,
                             lines=molecular_lines,
                             line_names=molecular_line_names,
                             size=12 * fontscale,
                             alpha=0.6)
        plotlines.oplotlines(label=True,
                             lines=atomic_lines,
                             line_names=atomic_line_names,
                             size=12 * fontscale,
                             color='r',
                             alpha=0.9,
                             linestyle=':')

        if plot_both:
            plt.plot(summer_wave, rat_s)
            plt.plot(winter_wave, rat_w)
        else:
            plt.plot(winter_wave, rat_w, 'k')
        #plotlines.oplotlines(spec_wave=summer_wave,spec_flux=rat_s,lines=atomic_lines,line_names=atomic_line_names,size=12*fontscale)
        #plotlines.oplotlines(spec_wave=summer_wave,spec_flux=rat_s,lines=molecular_lines,line_names=molecular_line_names,size=12*fontscale)
        plt.xlabel(r'$Wavelength (\mu m)$')
        plt.ylabel(r'$Flux$')
        if label_file:
            plt.text(winter_wave[-2], 1.05, specnames[i], size=9)
        if ((i != 0) and (((i + 1) % per_page) == 0)):
            pdf_pages.savefig(fig, orientation='landscape')
            plt.close(fig)

    pdf_pages.close()
    plt.close('all')
axpresent.plot(starspectrum35.wavelength.value /
               (unmasked_median_fits['vrad_2'] / 3e5 + 1.0),
               starspectrum35.flux.value + 1.5,
               label="Data")

axpresent.plot(slope_w / (gc_result_masked_slope.median['vrad_2'] / 3e5 + 1.0),
               slope_f,
               label="Masked model with best fit masked values")

axpresent.plot(slope_w / (gc_result_masked_slope.median['vrad_2'] / 3e5 + 1.0),
               masked_data_slope.flux.value - slope_f + 0.5,
               label='Masked Model-Masked Data Residuals')

plotlines.oplotlines(angstrom=True,
                     arcturus=True,
                     alpha=0.5,
                     size=6,
                     highlight=['Sc'])
#plt.plot(sl_w,unmasked_mod_masked_data_removed_flux-sl_f,label="Umasked model-masked model residuals")

axpresent.set_xlabel("Wavelength (angstroms)", size=12)
axpresent.set_ylabel("Flux", size=12)
axpresent.set_ylim(-0.3, 1.2)
axpresent.set_title("Order 35 Observed and Model fluxes (unmasked)", size=15)
axpresent.legend(loc='upper right', fontsize=11)

fit_results_file = open(
    "/u/ghezgroup/data/metallicity/nirspec/spectra_fits/pdfs/slope_masked_fit_results_output.lis",
    "a+")
fit_results_file.write("Fitting results with slopes with slope < " +
                       cutoff_str + " removed\n")
m71_021 = 'M71_J19534827+1848021'

tyc_3544 = 'TYC 3544'

sl_vals_ngc6791_282, specs_ngc6791_282 = slp.sl_response_plot_four(
    ngc6791_282, mod, specdir=spec_path)

star_data = specs_ngc6791_282['1.0']

plt.plot(star_data[0][0], star_data[0][1], 'g')
plt.plot(star_data[1][0], star_data[1][1], 'g')
plt.plot(star_data[2][0], star_data[2][1], 'g')
plt.plot(star_data[3][0], star_data[3][1], 'g')

plt.plot(star_data[4][0], star_data[4][1], 'b')
plt.plot(star_data[5][0], star_data[5][1], 'b')
plt.plot(star_data[6][0], star_data[6][1], 'b')
plt.plot(star_data[7][0], star_data[7][1], 'b')

plt.plot(star_data[8][0], star_data[8][1], 'r.')

plotlines.oplotlines(
    angstrom=True,
    arcturus=True,
    molecules=False,
    alpha=0.5,
    size=6,
    highlight=['O', 'Ne', 'Mg', 'Si', 'S', 'Ar', 'Ca', 'Ti', 'Cr', 'Fe', 'Ni'])

plt.show()
fitted_params = [str(round(gc_result.median[a],4))+"$\pm$"+str(round((gc_sigmas[a][1]*0.5-gc_sigmas[a][0]*0.5),4)) for a in ["teff_0","logg_0","mh_0","alpha_0"]]

apogee_params = ["4026.56$\pm$46.36","1.653$\pm$0.042","0.4470$\pm$0.0158","0.0201$\pm$0.0086"]

unmasked_params = ["3891.37$\pm$8.85","0.104$\pm$0.005","0.003$\pm$0.043","0.306$\pm$0.020"]


table = tableax.table(cellText=[fitted_params,unmasked_params,apogee_params],rowLabels=rows,colLabels=columns, loc='upper center',fontsize=24)
table.scale(1,1.5)

f.legend([l1, l1b, l2, l3, l3b],["Data","Masked Data Points",'Masked Model','$S_{\lambda}$', '$S_{\lambda}$ = '+cutoff_str], loc=(0.4,0.02))

plt.sca(sl_ax)

plotlines.oplotlines(angstrom=True,arcturus=True,alpha=0.25,molecules=False,size=8)





modelax2.set_xticks([])

l5 = dataresidualax.plot(sl_wavelength/(gc_result.median['vrad_2']/3e5+1.0), data_unmasked_residual, color='0.5')[0]

l5b = dataresidualax.axhline(0.05, color='black',ls='--')
l5c = dataresidualax.axhline(-0.05, color='black',ls='--')

dataresidualax.set_xticks([])

dataresidualax.set_ylabel("Flux",size=14)
Пример #9
0
def plot_multi_order_fit(starname,
                         g=None,
                         savefile=None,
                         specdir='/group/data/nirspec/spectra/',
                         savedir='../nirspec_fits/',
                         snr=30.0,
                         nnorm=2,
                         save_model=False,
                         plot_maximum=False):
    # plot the results of a multiple order fit on observed spectrum.

    file1 = glob.glob(specdir + starname + '_order34*.dat')
    file2 = glob.glob(specdir + starname + '_order35*.dat')
    file3 = glob.glob(specdir + starname + '_order36*.dat')

    if savefile is None:
        savefile = os.path.join(
            savedir, 'unmasked_' + starname + '_order34-36' + like_str + '.h5')
    # restore MultiNest savefile
    result = MultiNestResult.from_hdf5(savefile)

    starspectrum34 = read_fits_file.read_nirspec_dat(
        file1, desired_wavelength_units='Angstrom', wave_range=[2.245, 2.275])
    starspectrum34.uncertainty = (
        np.zeros(len(starspectrum34.flux.value)) +
        1.0 / np.float(snr)) * starspectrum34.flux.unit

    starspectrum35 = read_fits_file.read_nirspec_dat(
        file2, desired_wavelength_units='Angstrom', wave_range=[2.181, 2.2103])
    starspectrum35.uncertainty = (
        np.zeros(len(starspectrum35.flux.value)) +
        1.0 / np.float(snr)) * starspectrum35.flux.unit

    starspectrum36 = read_fits_file.read_nirspec_dat(
        file3, desired_wavelength_units='Angstrom', wave_range=[2.1168, 2.145])
    starspectrum36.uncertainty = (
        np.zeros(len(starspectrum36.flux.value)) +
        1.0 / np.float(snr)) * starspectrum36.flux.unit

    if g is not None:
        interp1 = Interpolate(starspectrum34)
        convolve1 = InstrumentConvolveGrating.from_grid(g, R=24000)
        rot1 = RotationalBroadening.from_grid(g, vrot=np.array([10.0]))
        norm1 = Normalize(starspectrum34, nnorm)

        interp2 = Interpolate(starspectrum35)
        convolve2 = InstrumentConvolveGrating.from_grid(g, R=24000)
        #rot2 = RotationalBroadening.from_grid(g,vrot=np.array([10.0]))
        norm2 = Normalize(starspectrum35, nnorm)

        interp3 = Interpolate(starspectrum36)
        convolve3 = InstrumentConvolveGrating.from_grid(g, R=24000)
        #rot3 = RotationalBroadening.from_grid(g,vrot=np.array([10.0]))
        norm3 = Normalize(starspectrum36, nnorm)


        model = g | rot1 | Splitter3() | DopplerShift(vrad=0) & DopplerShift(vrad=0) & DopplerShift(vrad=0) | \
             convolve1 & convolve2 & convolve3 | interp1 & interp2 & interp3 | \
             norm1 & norm2 & norm3

        if plot_maximum:
            model.teff_0 = result.maximum['teff_0']
            model.logg_0 = result.maximum['logg_0']
            model.mh_0 = result.maximum['mh_0']
            model.alpha_0 = result.maximum['alpha_0']
            model.vrot_1 = result.maximum['vrot_1']
            model.vrad_3 = result.maximum['vrad_3']
            model.vrad_4 = result.maximum['vrad_4']
            model.vrad_5 = result.maximum['vrad_5']
            model.R_6 = result.maximum['R_6']
            model.R_7 = result.maximum['R_7']
            model.R_8 = result.maximum['R_8']
            #model.R_9 = result.median['R_9']

        else:
            model.teff_0 = result.median['teff_0']
            model.logg_0 = result.median['logg_0']
            model.mh_0 = result.median['mh_0']
            model.alpha_0 = result.median['alpha_0']
            model.vrot_1 = result.median['vrot_1']
            model.vrad_3 = result.median['vrad_3']
            model.vrad_4 = result.median['vrad_4']
            model.vrad_5 = result.median['vrad_5']
            model.R_6 = result.median['R_6']
            model.R_7 = result.median['R_7']
            model.R_8 = result.median['R_8']
            #model.R_9 = result.median['R_9']

        w1, f1, w2, f2, w3, f3 = model()

    else:

        file1 = os.path.join(savedir, starname + '_order34_model.txt')
        file2 = os.path.join(savedir, starname + '_order35_model.txt')
        file3 = os.path.join(savedir, starname + '_order36_model.txt')

        w1, f1 = np.loadtxt(file1, usecols=(0, 1), unpack=True)
        w2, f2 = np.loadtxt(file2, usecols=(0, 1), unpack=True)
        w3, f3 = np.loadtxt(file3, usecols=(0, 1), unpack=True)

    # teff_0      3363.211996
    # logg_0         1.691725
    # mh_0           0.936003
    # alpha_0       -0.027917
    # vrot_1         1.378488
    # vrad_3      -538.550269
    # vrad_4      -239.851862
    # vrad_5      -541.044943
    # vrad_6      -540.432821
    # R_7        20000.000000
    # R_8        20000.000000
    # R_9        20000.000000
    # R_10       20000.000000

    plt.clf()
    observed_wave = (starspectrum36.wavelength, starspectrum35.wavelength,
                     starspectrum34.wavelength)
    observed_flux = (starspectrum36.flux, starspectrum35.flux,
                     starspectrum34.flux)
    model_wave = (w3, w2, w1)
    model_flux = (f3, f2, f1)
    max_result = result.maximum
    vels = (max_result['vrad_5'], max_result['vrad_4'], max_result['vrad_3'])

    print 'maximum likelihood:'
    print max_result

    print 'median:'
    print result.median

    print '1 sigma:'
    print result.calculate_sigmas(1)

    for i in xrange(len(observed_wave)):
        plt.subplot(4, 1, i + 1)
        velfac = 1.0 / (vels[i] / 3e5 + 1.0)
        xwave = observed_wave[i] * velfac
        plt.plot(xwave, observed_flux[i])
        plt.plot(model_wave[i] * velfac, model_flux[i])
        plt.ylim(0.2, 1.2)
        plt.xlabel('Wavelength (Angstrom)')
        plt.ylabel('Flux')
        plt.xlim(np.min(xwave.value), np.max(xwave.value))
        plotlines.oplotlines(angstrom=True,
                             arcturus=True,
                             alpha=0.5,
                             molecules=False,
                             size=12)

    plt.tight_layout()
    plt.show()
    if save_model:
        comment1 = 'teff %f,logg %f,mh %f,alpha %f,vrot %f,vrad %f,R %f' % \
                   (model.teff_0.value,model.logg_0.value,model.mh_0.value,model.alpha_0.value,
                   model.vrot_1.value,model.vrad_3.value,model.R_6.value)
        comment2 = 'teff %f,logg %f,mh %f,alpha %f,vrot %f,vrad %f,R %f' % \
                   (model.teff_0.value,model.logg_0.value,model.mh_0.value,model.alpha_0.value,
                   model.vrot_1.value,model.vrad_4.value,model.R_7.value)
        comment3 = 'teff %f,logg %f,mh %f,alpha %f,vrot %f,vrad %f,R %f' % \
                   (model.teff_0.value,model.logg_0.value,model.mh_0.value,model.alpha_0.value,
                   model.vrot_1.value,model.vrad_5.value,model.R_8.value)

        file1 = os.path.join(savedir, starname + '_order34_model.txt')
        file2 = os.path.join(savedir, starname + '_order35_model.txt')
        file3 = os.path.join(savedir, starname + '_order36_model.txt')

        write_spectrum.write_txt(w1, f1, file1, comments=comment1)
        write_spectrum.write_txt(w2, f2, file2, comments=comment2)
        write_spectrum.write_txt(w3, f3, file3, comments=comment3)
gc_result = mt.run_multinest_fit_rv_constrained(fit_model,
                                                apogee_vals['vrad_2'], 0.11)

gc_result.to_hdf(
    "/u/rbentley/metallicity/spectra_fits/masked_fit_results/unmasked_rv_constrained_"
    + starname + "_orders34-36.h5")

print "chi squared val ", like1

sigmas = gc_result.calculate_sigmas(1)

#Makes plots of S_lambda masked model

#print gc_result
print gc_result
for a in gc_result.median.keys():
    setattr(model, a, gc_result.median[a])

w, f = model()
gc_result.plot_triangle(
    parameters=['teff_0', 'logg_0', 'mh_0', 'alpha_0', 'vrot_1', 'vrad_2'])
plt.figure(figsize=(15, 7))
plt.plot(
    starspectrum.wavelength.value / (gc_result.median['vrad_2'] / 3e5 + 1.0),
    starspectrum.flux)
plt.plot(w / (gc_result.median['vrad_2'] / 3e5 + 1.0), f)
plotlines.oplotlines(angstrom=True)
plt.xlabel('Wavelength (Angstrom)')
plt.ylabel('Flux')
plt.show()