p0=p0, labels=labels, model=ElectronIC, prior=lnprior, nwalkers=128, nburn=100, nrun=100, threads=4, prefit=True, interactive=True) # Save sampler naima.save_run('RXJ1713_IC_sampler.hdf5', sampler) # Diagnostic plots naima.save_results_table('RXJ1713_IC', sampler) from astropy.io import ascii results = ascii.read('RXJ1713_IC_results.ecsv') results.remove_row(-1) # remove blob2 for col in ['median', 'unc_lo', 'unc_hi']: results[col].format = '.3g' with open('RXJ1713_IC_results_table.txt', 'w') as f: info = [] for key in ['n_walkers', 'n_run', 'p0', 'ML_pars', 'MaxLogLikelihood']: info.append('{0:<18}: {1}\n'.format(key, str(results.meta[key]))) f.writelines(info) f.write('\n') f.write('------------- ------- ------- --------\n') results.write(f, format='ascii.fixed_width_two_line')
## Run sampler sampler, pos = naima.run_sampler( data_table=data, p0=p0, labels=labels, model=ElectronIC, prior=lnprior, nwalkers=32, nburn=100, nrun=20, threads=4, prefit=True, ) ## Save run results to HDF5 file (can be read later with naima.read_run) naima.save_run("RXJ1713_IC_run.hdf5", sampler) ## Diagnostic plots with labels for the metadata blobs naima.save_diagnostic_plots( "RXJ1713_IC", sampler, sed=True, last_step=False, blob_labels=[ "Spectrum", "Electron energy distribution", "$W_e (E_e>1\, \mathrm{TeV})$", ], ) naima.save_results_table("RXJ1713_IC", sampler)
def fitter(self, p0, labels, datatable): ''' This is the actual fitting function. Parameters: ------------ p0: list free parameters; 1st guess (compact using InteractiveModelFitter) labels: list names of the free parameters data_table: astropy Table list of data tables for fitting Results of the fit (an astropy table with best param estimate and uncertainties & the sed fit) are stored inside 'results_ssc_fit' ''' print("Executing the fit...") # An interactive window helps to adjust the starting point of sampling # before calling run_sampler. imf = naima.InteractiveModelFitter(self.model_func, p0, sed=True, e_range=[1e-3 * u.eV, 1e15 * u.eV], e_npoints = self.e_npoints, labels=labels) p0 = imf.pars nwalkers = 100 nparams = len(p0) if nparams > nwalkers: raise RandomWalkError("The number of walkers should be atleast" "greater than the number of parameters!!") # Numbers for nwalkers, nburn, nrun are only preliminary here # to achieve fast computation. sampler, pos = naima.run_sampler(data_table=datatable, p0=p0, labels=labels, model=self.model_func, prior=self.prior_func, nwalkers=nwalkers, nburn=50, nrun=100, threads=12, prefit=False, data_sed=True, interactive=False) naima.save_results_table('./results_ssc_fit/data_fit_table', sampler) fit_sed = naima.plot_fit(sampler, n_samples=50, e_range=[ 1e-3 * u.eV, 1e15 * u.eV], e_npoints=self.e_npoints) fit_sed.savefig("./results_ssc_fit/likelihoodfitresult_sed.png") labels = sampler.labels for index, name in enumerate(labels): chain = naima.plot_chain(sampler, p=index) chain.savefig("./results_ssc_fit/plot_chain/{}_chain.png".format(name)) corner_plt = naima.plot_corner(sampler, show_ML=True) corner_plt.savefig("./results_ssc_fit/corner_plots.png")
nwalkers=32, nburn=100, nrun=20, threads=4, prefit=True, interactive=False, ) #Try running with more walkers or increasing the number of runs. ## Save run results out_root = "RXJ1713_IC_minimal" naima.save_run(out_root, sampler) ## Save diagnostic plots and results table naima.save_diagnostic_plots(out_root, sampler, sed=True) naima.save_results_table(out_root, sampler) # In[51]: #Plot the fit results. #Try confs=None, or try e_range=None f = naima.plot_fit(sampler, modelidx=0, label=None, sed=True, last_step=False, n_samples=100, confs=[3, 2, 1], ML_info=True, figure=None,
p0=p0, labels=labels, model=ElectronIC, prior=lnprior, nwalkers=128, nburn=100, nrun=100, threads=4, prefit=True, interactive=True) # Save sampler naima.save_run('RXJ1713_IC_sampler.hdf5', sampler) # Diagnostic plots naima.save_results_table('RXJ1713_IC', sampler) from astropy.io import ascii results = ascii.read('RXJ1713_IC_results.ecsv') results.remove_row(-1) # remove blob2 for col in ['median', 'unc_lo', 'unc_hi']: results[col].format = '.3g' with open('RXJ1713_IC_results_table.txt', 'w') as f: info = [] for key in ['n_walkers', 'n_run', 'p0', 'ML_pars', 'MaxLogLikelihood']: info.append('{0:<18}: {1}\n'.format(key, str(results.meta[key]))) f.writelines(info) f.write('\n') f.write('------------- ------- ------- --------\n') results.write(f, format='ascii.fixed_width_two_line')
return logprob if __name__ == "__main__": ## Set initial parameters and labels p0 = np.array((1e30, 3.0, np.log10(30))) labels = ["norm", "index", "log10(cutoff)"] ## Run sampler sampler, pos = naima.run_sampler( data_table=data, p0=p0, labels=labels, model=ElectronIC, prior=lnprior, nwalkers=32, nburn=100, nrun=20, threads=4, prefit=True, interactive=False, ) ## Save run results out_root = "RXJ1713_IC_minimal" naima.save_run(out_root, sampler) ## Save diagnostic plots and results table naima.save_diagnostic_plots(out_root, sampler, sed=False) naima.save_results_table(out_root, sampler)
def fitter(self, p0, labels, datatable): ''' This is the actual fitting function. Parameters: ------------ p0: list free parameters; 1st guess (compact using InteractiveModelFitter) labels: list names of the free parameters data_table: astropy Table list of data tables for fitting Results of the fit (an astropy table with best param estimate and uncertainties & the sed fit) are stored inside 'results_ssc_fit' ''' print("Executing the fit...") # An interactive window helps to adjust the starting point of sampling # before calling run_sampler. imf = naima.InteractiveModelFitter(self.model_func, p0, sed=True, e_range=[1e-3 * u.eV, 1e15 * u.eV], e_npoints=self.e_npoints, labels=labels) p0 = imf.pars nwalkers = 100 nparams = len(p0) if nparams > nwalkers: raise RandomWalkError("The number of walkers should be atleast" "greater than the number of parameters!!") # Numbers for nwalkers, nburn, nrun are only preliminary here # to achieve fast computation. sampler, pos = naima.run_sampler(data_table=datatable, p0=p0, labels=labels, model=self.model_func, prior=self.prior_func, nwalkers=nwalkers, nburn=50, nrun=100, threads=12, prefit=False, data_sed=True, interactive=False) naima.save_results_table('./results_ssc_fit/data_fit_table', sampler) fit_sed = naima.plot_fit(sampler, n_samples=50, e_range=[1e-3 * u.eV, 1e15 * u.eV], e_npoints=self.e_npoints) fit_sed.savefig("./results_ssc_fit/likelihoodfitresult_sed.png") labels = sampler.labels for index, name in enumerate(labels): chain = naima.plot_chain(sampler, p=index) chain.savefig( "./results_ssc_fit/plot_chain/{}_chain.png".format(name)) corner_plt = naima.plot_corner(sampler, show_ML=True) corner_plt.savefig("./results_ssc_fit/corner_plots.png")
## Run sampler sampler, pos = naima.run_sampler( data_table=data, p0=p0, labels=labels, model=ElectronIC, prior=lnprior, nwalkers=32, nburn=100, nrun=20, threads=4, prefit=True, ) ## Save run results to HDF5 file (can be read later with naima.read_run) naima.save_run("RXJ1713_IC_run.hdf5", sampler) ## Diagnostic plots with labels for the metadata blobs naima.save_diagnostic_plots( "RXJ1713_IC", sampler, sed=True, last_step=False, blob_labels=[ "Spectrum", "Electron energy distribution", "$W_e (E_e>1\, \mathrm{TeV})$", ], ) naima.save_results_table("RXJ1713_IC", sampler)
def main(input_path, output_path, n_job, n_sample, n_burn, n_walker): if not os.path.exists(output_path): os.makedirs(output_path) # but kai?? why you doing global things? # because i have to. for the sake of speed. And for queen and country of course. # see https://emcee.readthedocs.io/en/latest/tutorials/parallel/#parallel global f global B global data global log_ampl global alpha global beta global log_e_min global log_e_max labels = [ "log_main_amplitude", "alpha", "beta", 'log10(E_max)', 'log10(E_min)', 'B' ] p0 = np.array([48, 3, 0.05, 15.6, 11, 100]) t = Table.read(input_path) energy = t['energy'].data.ravel() * u.TeV log_energy = np.log10(energy.to_value(u.TeV)) log_ampl = t['log_ampl'].data.ravel() alpha = t['alpha'].data.ravel() beta = t['beta'].data.ravel() log_e_max = t['log_e_max'].data.ravel() log_e_min = t['log_e_min'].data.ravel() B = t['B'].data.ravel() print('log ampl', log_ampl) print('alpha', alpha) print('beta', beta) print('e_max', log_e_max) print('e_min', log_e_min) print('B', B) data = np.log10(t['data'].data.squeeze()) f = RegularGridInterpolator( (log_energy, log_ampl, alpha, beta, log_e_max, log_e_min, B), data, bounds_error=False, fill_value=None) data = read_crab_mwl_data(e_min=40 * u.keV) sampler, pos = naima.run_sampler( data_table=data, p0=p0, labels=labels, model=lut_model, prior=lut_prior, nwalkers=n_walker, nburn=n_burn, nrun=n_sample, threads=n_job, prefit=True, ) mpl.use('Agg') mpl.rcParams['text.usetex'] = False mpl.rcParams['backend'] = 'agg' naima.save_run(f"{output_path}/crab_chain.h5", sampler, clobber=True) naima.save_results_table(f"{output_path}/crab_naima_fit", sampler) naima.save_diagnostic_plots(f"{output_path}/crab_naima", sampler)