cal_spec = []

for i in range(len(cal_stars_init)):
    for order in order_info:

        if order[0] == cal_stars_init[i][0] and order[
                1] == 'order35' and order[4] != 2:
            #print cal_stars_init[i]
            cal_spec += [[
                cal_stars_init[i][0], cal_stars_init[i][1], order[2]
            ]]

for i in range(len(cal_stars_init)):
    fitting_res = MultiNestResult.from_hdf5(
        '/u/rbentley/metallicity/spectra_fits/' + cal_stars_init[i][0] +
        'order35_test_results.h5')
    print fitting_res
    print fitting_res.median['vrad_2']
    cal_spec[i] += [fitting_res.median['vrad_2']]
'''
passwd=raw_input('Sql pwd: ')
con = mdb.connect(host='galaxy1.astro.ucla.edu',user='******',passwd=passwd,db='gcg')
cur = con.cursor()

sql_query = 'SELECT name, date, teff_peak, teff, teff_err,' +\
            'logg_peak,logg,logg_err,logg_err_upper,logg_err_lower,'+\
            'vz_peak,vz,vz_err,vz_err_upper,vz_err_lower,'+\
            'mh_peak,mh,mh_err,mh_err_upper,mh_err_lower,'+\
            'alpha_peak,alpha,alpha_err,alpha_err_upper,alpha_err_lower,'+\
            'order_ FROM metallicity'
예제 #2
0
def update_starkit_db(name,
                      date,
                      ddate,
                      mjd,
                      h5file,
                      snr=None,
                      original_location=None,
                      spectrum_file=None,
                      vlsr=None,
                      passwd=None,
                      vsys=0.0,
                      source=None,
                      vhelio=None,
                      order=None):
    # update the starkit database with the info from the hdf5 file and the star
    print h5file
    if os.path.exists(h5file):
        results = MultiNestResult.from_hdf5(h5file)

        m = results.maximum
        med = results.median
        sig = results.calculate_sigmas(1)
        if 'add_err_6' in m.keys():
            p = [
                'teff_0', 'logg_0', 'mh_0', 'alpha_0', 'vrot_1', 'vrad_2',
                'R_3', 'add_err_6'
            ]
        else:
            p = [
                'teff_0', 'logg_0', 'mh_0', 'alpha_0', 'vrot_1', 'vrad_2',
                'R_3'
            ]

        temp = []
        for k in p:
            temp.append([
                m[k], med[k], (sig[k][1] - sig[k][0]) / 2.0, sig[k][1],
                sig[k][0]
            ])

        values = [name,date,ddate,mjd]+ temp[0] + temp[1]+ temp[5] + temp[2] + temp[3] + temp[4] + temp[6] + \
                 [original_location,spectrum_file,h5file,str(datetime.datetime.today())]

        #        if 'add_err_6' in m.keys():
        #            values = [name,date,ddate,mjd]+ temp[0] + temp[1]+ temp[5] + temp[2] + temp[3] + temp[4] + temp[6] + \
        #                     temp[7] + [original_location,spectrum_file,h5file,str(datetime.datetime.today())]
        #        else:
        #            values = [name,date,ddate,mjd]+ temp[0] + temp[1]+ temp[5] + temp[2] + temp[3] + temp[4] + temp[6] + \
        #                     [None,None,None,None] + [original_location,spectrum_file,h5file,str(datetime.datetime.today())]

        if vlsr is None:
            values = values + [None, None]
        else:
            values = values + [temp[5][1] + vlsr, temp[5][0] + vlsr]

        if vhelio is None:
            values = values + [None, None]
        else:
            values = values + [temp[5][1] + vhelio, temp[5][0] + vhelio]

        inf = open('fitting_params_' + name + '.dat', 'r')
        lines = inf.readlines()
        for l in lines:
            lcont = l.split()
            if int(lcont[0]) == order:

                resmean = lcont[1]
                resmax = lcont[2]
                chi2 = lcont[3]
        inf.close()
        values = values + [vsys, snr, source]
        con = mdb.connect(host='galaxy1.astro.ucla.edu',
                          user='******',
                          passwd=passwd,
                          db='gcg')
        cur = con.cursor()
        values = values + [None, None, None, None, None, None, None, None]
        values = values + [resmean, resmax, chi2, order, 'PHOENIX']
        testval = values
        print(values), len(values)
        sql_query = 'REPLACE INTO metallicity (name,date,ddate,mjd,'+\
                    'teff_peak,teff,teff_err,teff_err_upper,teff_err_lower,'+\
                    'logg_peak,logg,logg_err,logg_err_upper,logg_err_lower,'+\
                    'vz_peak,vz,vz_err,vz_err_upper,vz_err_lower,'+\
                    'mh_peak,mh,mh_err,mh_err_upper,mh_err_lower,'+\
                    'alpha_peak,alpha,alpha_err,alpha_err_upper,alpha_err_lower,'+\
                    'vrot_peak,vrot,vrot_err,vrot_err_upper,vrot_err_lower,'+\
                    'r_peak,r,r_err,r_err_upper,r_err_lower,'+\
                    'original_location,file,chains,edit,vlsr,vlsr_peak,vhelio,vhelio_peak,vsys_err,snr,source,simbad,simbad_err,add_err,add_err_peak,early_type,simbad_rot,simbad_rot_err,vsys_offset,residual_mean,residual_max,reduce_chi2,order_,grid) '+\
                    'VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,'+\
                    '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,'+\
                    '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,'+\
                    '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,'+\
                    '%s,%s,%s)'

        for x in range(len(values)):
            if type(values[x]) is np.float64:
                values[x] = float(values[x])
            print type(values[x])

        print('adding into db', type(values))
        #print(sql_query)
        #print(values)
        #print testval
        cur.execute(sql_query, values)
        #cur.execute('DELETE FROM starkit_nirspec;')
        con.commit()
        cur.close()
        con.close()
예제 #3
0
                        "mh_0":0.447044,
                        "alpha_0":0.020058,
                        "vrot_1":0.928,
                        "vrad_2":-48.4008,
                        "R_3":24000.}

for a in apogee_vals.keys():
    setattr(model,a,apogee_vals[a])


cutoff = 0.05
cutoff_str = str(cutoff)

unmasked_wavelength, unmasked_flux = model()

gc_result = MultiNestResult.from_hdf5("/u/rbentley/metallicity/spectra_fits/masked_fit_results/residual_cut_005_NGC6791_J19205+3748282_order35.h5")

print gc_result

gc_sigmas = gc_result.calculate_sigmas(1)

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

sl_wavelength, sl_flux = model()

data_unmasked_residual = mt.calc_residuals(sl_flux,starspectrum35.flux.value)

masked_unmasked_residual = mt.calc_residuals(sl_flux,unmasked_flux)

residual_mask_flux = []
def sl_response_plot_three(starname,
                           g,
                           specdir='/group/data/nirspec/spectra/',
                           snr=30.,
                           nnorm=2):

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

    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

    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

    h5_files_us = glob.glob(
        '/u/rbentley/metallicity/spectra_fits/masked_fit_results/orders34-35-36-37/masked*.h5'
    )

    cut_lis = []

    for filename in h5_files_us:
        print filename.split('_')
        cut_lis += [(float(filename.split('_')[6]), filename)]

    cut_lis = sorted(cut_lis, key=getKey)

    h5_files = [i[1] for i in cut_lis]

    sl_val = []
    print h5_files
    for filename in h5_files:
        print filename.split('_')[6]
        gc_result = MultiNestResult.from_hdf5(filename)
        print gc_result

        for a in apogee_vals.keys():
            setattr(model, a, apogee_vals[a])

        sl_mh1, sl_mh2, sl_mh3 = mtf.s_lambda_three_order(
            model, 'mh', model.mh_0.value, 0.1)

        w1, f1, w2, f2, w3, f3 = model()
        #combine all sl_mh,w,f, lists

        sl_mh = np.concatenate((sl_mh1, sl_mh2, sl_mh3))

        w = np.concatenate((w1, w2, w3))

        f = np.concatenate((f1, f2, f3))

        starfluxall = np.concatenate(
            (starspectrum34.flux.value, starspectrum35.flux.value,
             starspectrum36.flux.value))

        starwaveall = np.concatenate(
            (starspectrum34.wavelength.value, starspectrum35.wavelength.value,
             starspectrum36.wavelength.value))

        sigma_bounds = gc_result.calculate_sigmas(1)

        sigmas = []

        for a in sigma_bounds.keys():
            print a
            sigmas += [(sigma_bounds[a][1] - sigma_bounds[a][0]) / 2.]

        print sigmas

        abs_sl_mh = []

        mask_sl_f = []
        mask_sl_w = []

        data_sl_f = []

        for i in range(len(sl_mh)):
            abs_sl_mh += [np.abs(sl_mh[i])]
            if abs(sl_mh[i]) < float(filename.split('_')[6]):
                mask_sl_f += [starfluxall[i]]
                mask_sl_w += [starwaveall[i]]
            else:
                data_sl_f += [starfluxall[i]]

        print sigmas
        sl_val += [(float(filename.split('_')[6]), len(mask_sl_f),
                    gc_result.median['vrad_3'], gc_result.median['vrad_4'],
                    gc_result.median['vrad_5'], gc_result.median['logg_0'],
                    gc_result.median['mh_0'], gc_result.median['alpha_0'],
                    gc_result.median['teff_0'], sigmas)]

    print len(starfluxall)
    return sl_val
                        "logg_0":1.653,
                        "mh_0":0.447044,
                        "alpha_0":0.020058,
                        "vrot_1":0.928,
                        "vrad_2":-48.4008,
                        "R_3":24000.}

for a in apogee_vals.keys():
    setattr(model,a,apogee_vals[a])

unmasked_wavelength, unmasked_flux = model()


sl_mh = mt.s_lambda(model,'mh',model.mh_0.value,0.1)

gc_result = MultiNestResult.from_hdf5("/u/rbentley/metallicity/spectra_fits/masked_fit_results/order34/sensitivity_cut_10.0_"+starname+"_order"+order+".h5")

gc_sigmas = gc_result.calculate_sigmas(1)

print gc_result

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

sl_wavelength, sl_flux = model()

data_unmasked_residual = mt.calc_residuals(sl_flux,starspectrum35.flux.value)

masked_unmasked_residual = mt.calc_residuals(sl_flux,unmasked_flux)

residual_mask_flux = []
def sl_response_plot_four(starname,
                          g,
                          specdir='/group/data/nirspec/spectra/',
                          snr=30.,
                          nnorm=2):

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

    starspectrum34 = read_fits_file.read_nirspec_dat(
        file1, desired_wavelength_units='micron')
    starspectrum35 = read_fits_file.read_nirspec_dat(
        file2, desired_wavelength_units='micron')
    starspectrum36 = read_fits_file.read_nirspec_dat(
        file3, desired_wavelength_units='micron')
    starspectrum37 = read_fits_file.read_nirspec_dat(
        file4, desired_wavelength_units='micron')

    waverange34 = [
        np.amin(starspectrum34.wavelength.value[:970]),
        np.amax(starspectrum34.wavelength.value[:970])
    ]
    waverange35 = [
        np.amin(starspectrum35.wavelength.value[:970]),
        np.amax(starspectrum35.wavelength.value[:970])
    ]
    waverange36 = [
        np.amin(starspectrum36.wavelength.value[:970]),
        np.amax(starspectrum36.wavelength.value[:970])
    ]
    waverange37 = [
        np.amin(starspectrum37.wavelength.value[:970]),
        np.amax(starspectrum37.wavelength.value[:970])
    ]

    starspectrum34 = read_fits_file.read_nirspec_dat(
        file1, desired_wavelength_units='Angstrom', wave_range=waverange34)
    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=waverange35)
    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=waverange36)
    starspectrum36.uncertainty = (
        np.zeros(len(starspectrum36.flux.value)) +
        1.0 / np.float(snr)) * starspectrum36.flux.unit

    starspectrum37 = read_fits_file.read_nirspec_dat(
        file4, desired_wavelength_units='Angstrom', wave_range=waverange37)
    starspectrum37.uncertainty = (
        np.zeros(len(starspectrum37.flux.value)) +
        1.0 / np.float(snr)) * starspectrum37.flux.unit

    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)

    interp4 = Interpolate(starspectrum37)
    convolve4 = InstrumentConvolveGrating.from_grid(g, R=24000)
    #rot3 = RotationalBroadening.from_grid(g,vrot=np.array([10.0]))
    norm4 = Normalize(starspectrum37, nnorm)



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

    h5_files_us = glob.glob(
        '/u/rbentley/metallicity/spectra_fits/masked_fit_results/orders34-35-36-37/masked*'
        + starname + '_order34-37.h5')

    cut_lis = []

    for filename in h5_files_us:
        print filename.split('_')
        cut_lis += [(float(filename.split('_')[6]), filename)]

    cut_lis = sorted(cut_lis, key=getKey)

    h5_files = [i[1] for i in cut_lis]

    sl_val = []

    combined_data_mask_model = {}

    for filename in h5_files:
        print filename
        print filename.split('_')[6]
        gc_result = MultiNestResult.from_hdf5(filename)
        print gc_result

        for a in apogee_vals.keys():
            setattr(model, a, apogee_vals[a])

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

        sl_mh1, sl_mh2, sl_mh3, sl_mh4 = mtf.s_lambda_four_order(
            model, 'mh', model.mh_0.value, 0.1)

        #combine all sl_mh,w,f, lists

        sl_mh = np.concatenate((sl_mh1, sl_mh2, sl_mh3, sl_mh4))

        w = np.concatenate((w1 / (gc_result.median['vrad_3'] / 3e5 + 1.0),
                            w2 / (gc_result.median['vrad_4'] / 3e5 + 1.0),
                            w3 / (gc_result.median['vrad_5'] / 3e5 + 1.0),
                            w4 / (gc_result.median['vrad_6'] / 3e5 + 1.0)))

        f = np.concatenate((f1, f2, f3, f4))

        starfluxall = np.concatenate(
            (starspectrum34.flux.value, starspectrum35.flux.value,
             starspectrum36.flux.value, starspectrum37.flux.value))

        starwaveall = np.concatenate(
            (starspectrum34.wavelength.value /
             (gc_result.median['vrad_3'] / 3e5 + 1.0),
             starspectrum35.wavelength.value /
             (gc_result.median['vrad_4'] / 3e5 + 1.0),
             starspectrum36.wavelength.value /
             (gc_result.median['vrad_5'] / 3e5 + 1.0),
             starspectrum37.wavelength.value /
             (gc_result.median['vrad_6'] / 3e5 + 1.0)))

        sigma_bounds = gc_result.calculate_sigmas(1)

        sigmas = []

        for a in sigma_bounds.keys():
            #print a
            sigmas += [(sigma_bounds[a][1] - sigma_bounds[a][0]) / 2.]

        #print sigmas

        abs_sl_mh = []

        mask_sl_f = []
        mask_sl_w = []

        data_sl_f = []

        for i in range(len(sl_mh)):
            abs_sl_mh += [np.abs(sl_mh[i])]
            if abs(sl_mh[i]) < float(filename.split('_')[6]):
                mask_sl_f += [starfluxall[i]]
                mask_sl_w += [starwaveall[i]]
            else:
                data_sl_f += [starfluxall[i]]

        print sigmas
        combined_data_mask_model.update({
            filename.split('_')[6]: [(starwaveall, starfluxall), (w, f),
                                     (mask_sl_w, mask_sl_f)]
        })
        sl_val += [
            (float(filename.split('_')[6]), len(mask_sl_f),
             gc_result.median['vrad_3'], gc_result.median['vrad_4'],
             gc_result.median['vrad_5'], gc_result.median['vrad_6'],
             gc_result.median['logg_0'], gc_result.median['mh_0'],
             gc_result.median['alpha_0'], gc_result.median['teff_0'], sigmas)
        ]

    print len(starfluxall)
    return sl_val, combined_data_mask_model
예제 #7
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)
예제 #8
0
# make a MultiNest fitting object with the model and the prior
gc_fitobj = MultiNest(fit_model, [teff_prior, logg_prior, mh_prior, alpha_prior,vrot_prior, vrad_prior1,R_prior1])





# Run the fit using the MultiNest sampler.
# Will take about 5-10 minutes to run for high resolution Phoenix grid
gc_result = gc_fitobj.run()

# after fitting, save the results to an HDF5 file
gc_result.to_hdf(savefile)
print "here"
# load from the HDF5 file in case the fit was not run
gc_result = MultiNestResult.from_hdf5(savefile)




# summary statistics like the mean and median can be accessed as dictionaries
print(gc_result.median)
print(gc_result.mean), "end"

# can also compute 1 sigma intervals (or arbitrary)
gc_result.calculate_sigmas(1)

# can also make corner plots
# be sure to specify parameters if one of them is fixed - if not, corner will crash
gc_result.plot_triangle(parameters=['teff_0','logg_0','mh_0','alpha_0','vrot_1','vrad_2'])
예제 #9
0
model = g | rot1 |DopplerShift(vrad=0.0)| convolve1 | interp1 | norm1

cut_lis = []
for filename in h5_files_us:
    cut_lis += [(float(filename.split('_')[5]),filename)]

cut_lis = sorted(cut_lis,key = getKey)
print cut_lis
h5_files = [i[1] for i in cut_lis]

    
for filename in h5_files:



    gc_result = MultiNestResult.from_hdf5(filename)


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

    sl_mh = mt.s_lambda(model,'mh',model.mh_0.value,0.1)

    mask_sl_f = []
    mask_sl_w = []

    
    data_sl_f = []

    abs_sl_mh = []
예제 #10
0
def gc_results_table():
    f = open(
        '/u/rbentley/localcompute/fitting_plots/plots_for_paper/gc_fit_table_logg.tex',
        'w')

    teff_offset = 140.
    teff_scatter = 157.

    logg_offset = 0.15
    logg_scatter = 0.14

    mh_offset = 0.15
    mh_scatter = 0.14

    alpha_offset = 0.18
    alpha_scatter = 0.16

    gc_stars = [
        'NE_1_001', 'NE_1_002', 'NE_1_003', 'E7_1_001', 'E7_2_001', 'E7_1_002',
        'E7_1_003', 'N2_1_001', 'E5_1_001', 'N2_1_002', 'N2_1_003', 'S1-23'
    ]

    for star in gc_stars:
        bosz_result = MultiNestResult.from_hdf5(
            '/u/rbentley/metallicity/spectra_fits/masked_fit_results/orders34-35-36/BOSZ_fits/unmasked/'
            + star + '_order34-36_bosz_logg1.2_adderr.h5')
        sigmas = bosz_result.calculate_sigmas(1)

        teff = [
            np.round_(bosz_result.median['teff_0'] + teff_offset),
            np.round_(
                np.sqrt(((sigmas['teff_0'][1] - sigmas['teff_0'][0]) / 2.)**2 +
                        teff_scatter**2))
        ]
        logg = [
            np.round_(bosz_result.median['logg_0'] + logg_offset, decimals=2),
            np.round_(
                np.sqrt(((sigmas['logg_0'][1] - sigmas['logg_0'][0]) / 2.)**2 +
                        logg_scatter**2),
                decimals=2)
        ]
        mh = [
            np.round_(bosz_result.median['mh_0'] + mh_offset, decimals=2),
            np.round_(
                np.sqrt(((sigmas['mh_0'][1] - sigmas['mh_0'][0]) / 2.)**2 +
                        mh_scatter**2),
                decimals=2)
        ]
        alpha = [
            np.round_(bosz_result.median['alpha_0'] + alpha_offset,
                      decimals=2),
            np.round_(np.sqrt((
                (sigmas['alpha_0'][1] - sigmas['alpha_0'][0]) / 2.)**2 +
                              alpha_scatter**2),
                      decimals=2)
        ]

        f.write(star + ' & #### & ' + str(teff[0]) + '$\pm$' + str(teff[1]) +
                ' & ' + str(logg[0]) + '$\pm$' + str(logg[1]) + ' & ' +
                str(mh[0]) + '$\pm$' + str(mh[1]) + ' & ' + str(alpha[0]) +
                '$\pm$' + str(alpha[1]) + ' \\\\\n')

    f.close()