def fitspec(): s=read_fits.read_fits_spectrum1d('E5_1_004.fits',dispersion_unit='Angstrom') wave_range = [21000,24000] good = np.where((s.wavelength.value > wave_range[0]) & (s.wavelength.value < wave_range[1]))[0] s = Spectrum1D.from_array(s.wavelength[good],s.flux[good]/np.median(s.flux[good]), dispersion_unit = s.wavelength.unit) snr = 40 s.uncertainty = (np.zeros(len(s.flux.value))+1.0/snr)*s.flux.unit #g=load_grid('phoenix_20000_k.h5') g = load_grid('phoenix_r20000_1.9-2.5_k.h5') my_model = assemble_model(g, vrad=0, vrot=0,R=20000,spectrum=s,normalize_npol=4) wave,flux = my_model() plt.clf() plt.plot(s.wavelength,s.flux) plt.plot(wave,flux) teff_prior = priors.UniformPrior(3000,8000) logg_prior = priors.UniformPrior(0.0,4.4) mh_prior = priors.UniformPrior(-1.5,1.0) alpha_prior = priors.UniformPrior(-0.2,1.2) vrot_prior = priors.UniformPrior(0,20) vrad_prior = priors.UniformPrior(-300,300) R_prior = priors.GaussianPrior(5400,600) ll = Chi2Likelihood(s) my_model = my_model | ll fitobj = MultiNest(my_model, [teff_prior, logg_prior, mh_prior, alpha_prior, vrot_prior, vrad_prior, R_prior]) result = fitobj.run() return result
def run_multinest_fit_rv_constrained(fit_model, vrad, vrad_err): teff_prior = priors.UniformPrior(1000, 6000) logg_prior = priors.UniformPrior(0.1, 4.0) mh_prior = priors.UniformPrior(-2.0, 1.0) alpha_prior = priors.UniformPrior(-0.25, 0.5) vrot_prior = priors.UniformPrior(0, 350.0) #vrad_prior1 = priors.FixedPrior(vrad) vrad_prior1 = priors.UniformPrior(vrad - 3. * vrad_err, vrad + 3. * vrad_err) #R_prior1 = priors.UniformPrior(1500,5000) R_prior1 = priors.FixedPrior(24000) # 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() # 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) return gc_result
def fit_star_multi_order(starname, g, specdir='/group/data/nirspec/spectra/', savedir='../nirspec_fits/', snr=30.0, nnorm=2, teff_range=[2500, 6000], vrad_range=[-600, 600], logg_range=[0., 4.5], mh_range=[-2., 1.0], vrot_range=[0, 20], R=40000, verbose=True, alpha_range=[-1., 1.], r_range=[15000.0, 40000.0], R_fixed=None, logg_fixed=None, l1norm=False): # fit a spectrum of a star with multiple orders that can have different velocities 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 w1, f1, w2, f2, w3, f3 = model() plt.clf() plt.plot(w1, f1) plt.plot(starspectrum34.wavelength, starspectrum34.flux) plt.plot(w2, f2) plt.plot(starspectrum35.wavelength, starspectrum35.flux) plt.plot(w3, f3) plt.plot(starspectrum36.wavelength, starspectrum36.flux) # likelihoods if l1norm: like1 = L1Likelihood(starspectrum34) like2 = L1Likelihood(starspectrum35) like3 = L1Likelihood(starspectrum36) else: like1 = Chi2Likelihood(starspectrum34) like2 = Chi2Likelihood(starspectrum35) like3 = Chi2Likelihood(starspectrum36) fit_model = model | like1 & like2 & like3 | Combiner3() print fit_model.__class__ print fit_model() teff_prior = priors.UniformPrior(*teff_range) if logg_fixed is not None: logg_prior = priors.FixedPrior(logg_fixed) else: logg_prior = priors.UniformPrior(*logg_range) mh_prior = priors.UniformPrior(*mh_range) alpha_prior = priors.UniformPrior(*alpha_range) vrot_prior = priors.UniformPrior(*vrot_range) vrad_prior1 = priors.UniformPrior(*vrad_range) vrad_prior2 = priors.UniformPrior(*vrad_range) vrad_prior3 = priors.UniformPrior(*vrad_range) # R_prior1 = priors.FixedPrior(R) # R_prior2 = priors.FixedPrior(R) # R_prior3 = priors.FixedPrior(R) # R_prior4 = priors.FixedPrior(R) if R_fixed is not None: R_prior1 = priors.FixedPrior(R_fixed) R_prior2 = priors.FixedPrior(R_fixed) R_prior3 = priors.FixedPrior(R_fixed) else: R_prior1 = priors.UniformPrior(*r_range) R_prior2 = priors.UniformPrior(*r_range) R_prior3 = priors.UniformPrior(*r_range) fitobj = MultiNest(fit_model, [teff_prior, logg_prior, mh_prior, alpha_prior, vrot_prior, \ vrad_prior1,vrad_prior2,vrad_prior3,R_prior1,R_prior2,\ R_prior3]) fitobj.run(verbose=verbose, importance_nested_sampling=False, n_live_points=400) result = fitobj.result if l1norm: like_str = '_l1norm' else: like_str = '' result.to_hdf( os.path.join(savedir, 'unmasked_' + starname + '_order34-36' + like_str + '.h5')) print result.calculate_sigmas(1) print result.median # save the individual model spectra with the max posterior value 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_7 = result.maximum['R_6'] model.R_8 = result.maximum['R_7'] model.R_9 = result.maximum['R_8'] w1, f1, w2, f2, w3, f3 = 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_7.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_8.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_9.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)
teff_prior = priors.UniformPrior(1000,6000) logg_prior = priors.UniformPrior(0.1,4.0) mh_prior = priors.UniformPrior(-2.0,1.0) alpha_prior = priors.UniformPrior(-0.25,0.5) vrot_prior = priors.UniformPrior(0,350.0) vrad_prior1 = priors.UniformPrior(-1000,1000) #R_prior1 = priors.UniformPrior(1500,5000) R_prior1 = priors.FixedPrior(24000) # 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)
def fit(input_file, spectrum=None, teff_prior=[10000.0, 35000.0], logg_prior=[2.0, 5.0], mh_prior=[-1.0, 0.8], alpha_prior=[-0.25, 0.5], vrot_prior=[0, 350.0], vrad_prior=[-5000, 5000], R_prior=4000.0, wave_range=None, outdir='./', snr=30.0, norm_order=2, g=None, molecfit=False, wavelength_units='micron', debug=False, **kwargs): ''' Given a fits file, read in and fit the spectrum using a grid Passes keyword arguements into read_fits_file using **kwargs ''' if g is None: print('need to input grid in g keyword') return 0 teff_prior1 = priors.UniformPrior(teff_prior[0], teff_prior[1]) logg_prior1 = priors.UniformPrior(logg_prior[0], logg_prior[1]) mh_prior1 = priors.UniformPrior(-1.0, 0.8) alpha_prior1 = priors.UniformPrior(-0.25, 0.5) vrot_prior1 = priors.UniformPrior(0, 350.0) vrad_prior1 = priors.UniformPrior(-5000, 5000) #R_prior1 = priors.UniformPrior(1500,10000) R_prior1 = priors.FixedPrior(R_prior) # wavelength range for the fit #wave_range = None file_part = os.path.splitext(os.path.split(input_file)[-1])[0] file_part = os.path.join(outdir, file_part) extension = os.path.splitext(input_file)[-1] spectrum_file = file_part + extension fit_file = file_part + '.h5' plot_file = file_part + '.pdf' corner_file = file_part + '_corner.pdf' model_file = file_part + '_model.txt' # best fit model print('copying file from %s to %s' % (input_file, spectrum_file)) shutil.copyfile(input_file, spectrum_file) # read in the spectrum and set the uncertainty as 1/SNR if spectrum is None: if molecfit: spectrum = read_fits_file.read_txt_file( spectrum_file, desired_wavelength_units=wavelength_units, wave_range=wave_range, molecfit=True) else: if (extension == '.csv') or (extension == '.txt'): if extension == '.csv': delimiter = ',' else: delimiter = None spectrum = read_fits_file.read_txt_file( spectrum_file, desired_wavelength_units='angstrom', delimiter=delimiter, wave_range=wave_range, wavelength_units=wavelength_units, **kwargs) else: spectrum = read_fits_file.read_fits_file( spectrum_file, desired_wavelength_units='angstrom', wavelength_units=wavelength_units, wave_range=wave_range) spectrum.uncertainty = np.zeros(len(spectrum.flux)) + 1.0 / snr # setup the model interp1 = Interpolate(spectrum) convolve1 = InstrumentConvolveGrating.from_grid(g, R=R_prior) rot1 = RotationalBroadening.from_grid(g, vrot=np.array([10.0])) norm1 = Normalize(spectrum, norm_order) model = g | rot1 | DopplerShift(vrad=0) | convolve1 | interp1 | norm1 # add likelihood parts like1 = Chi2Likelihood(spectrum) #like1_l1 = SpectralL1Likelihood(spectrum) fit_model = model | like1 fitobj = MultiNest(fit_model, [ teff_prior1, logg_prior1, mh_prior1, alpha_prior1, vrot_prior1, vrad_prior1, R_prior1 ]) fitobj.run(verbose=debug) result = fitobj.result logging.info('saving results to: ' + fit_file) result.to_hdf(fit_file) # print some of the results into the log m = result.maximum sig = result.calculate_sigmas(1) for k in sig.keys(): print('%s\t %f\t %f\t %f\t %f' % (k, m[k], sig[k][0], sig[k][1], (sig[k][1] - sig[k][0]) / 2.0)) # evaluating the model model.teff_0 = result.maximum.teff_0 model.logg_0 = result.maximum.logg_0 model.mh_0 = result.maximum.mh_0 model.vrot_1 = result.maximum.vrot_1 model.vrad_2 = result.maximum.vrad_2 model.R_3 = result.maximum.R_3 model_wave, model_flux = model() logging.info('saving model spectrum to: ' + model_file) save_spectrum(model_wave, model_flux, model_file) plt.figure(figsize=(12, 6)) plt.plot(model_wave, model_flux, label='Best Fit Model') plt.plot(spectrum.wavelength, spectrum.flux, label='Data') plt.ylim( np.nanmin(spectrum.flux.value) - 0.2, np.nanmax(spectrum.flux.value) + 0.2) plt.xlabel('Wavelength (Angstrom)') plt.ylabel('Flux') plt.title(spectrum_file) plt.legend() plt.savefig(plot_file) result.plot_triangle( parameters=['teff_0', 'logg_0', 'mh_0', 'alpha_0', 'vrot_1', 'vrad_2']) logging.info('saving corner plot to: ' + corner_file) plt.savefig(corner_file) # try to free up memory fitobj = 0 fit_model = 0 return result
def run_fit(self, spectral_grid): likelihood = spectral_grid | self.model mn = MultiNest(likelihood, self.priors) return mn.run(**self.multinest_kwargs)