def display(): """Display the source model. """ from ximpol.utils.matplotlib_ import pyplot as plt print(ROI_MODEL) fig = plt.figure('Energy spectrum') total_spectral_model.plot(logy=True, show=False, label='Total') nonthermal_spectral_model.plot(logy=True, show=False, label='Non-thermal') thermal_spectral_model.plot(logy=True, show=False, label='Thermal') plt.legend(bbox_to_anchor=(0.95, 0.95)) fig = thermal_component.image.plot(show=False) fig.add_label(0.1, 0.92, '1.5-3 keV', relative=True, size='xx-large', color='white', horizontalalignment='left') fig = nonthermal_component.image.plot(show=False) fig.add_label(0.1, 0.92, '4-6 keV', relative=True, size='xx-large', color='white', horizontalalignment='left') plt.show()
def view(): _mcube = xBinnedModulationCube(MCUBE_FILE_PATH) _mcube.fit() _fit_results = _mcube.fit_results[0] plt.figure('Polarization degree') _mcube.plot_polarization_degree(show=False, color='blue') pol_degree_spline.plot(color='lightgray',label='Spin %s'%spindegree, show=False) plt.figtext(0.2, 0.85,'XIPE %s ks'%(SIM_DURATION/1000.),size=18) #plt.errorbar(_energy_mean, _pol_deg, yerr=_pol_deg_err, color='blue',marker='o') plt.legend() plt.figure('Polarization angle') _mcube.plot_polarization_angle(show=False, color='blue', degree=False) pol_angle_spline.plot(color='lightgray',label='Spin %s'%spindegree, show=False) plt.figtext(0.2, 0.85,'XIPE %s ks'%(SIM_DURATION/1000.),size=18) #plt.errorbar(_energy_mean,_pol_angle, yerr= _pol_angle_err,color='blue',marker='o') plt.xlim([1,10]) plt.legend() plt.figure('MDP %s'%base_name) mdp = _mcube.mdp99[:-1] emean = _mcube.emean[:-1] emin = _mcube.emin[:-1] emax = _mcube.emax[:-1] width = (emax-emin)/2. plt.errorbar(emean,mdp,xerr=width, label='MDP99',marker='o',linestyle='--') plt.figtext(0.2, 0.85,'XIPE %s ks'%(SIM_DURATION/1000.),size=18) plt.xlim([1,10]) plt.ylabel('MPD 99\%') plt.xlabel('Energy (keV)') #plt.legend() plt.show()
def makeMDPComparisonPlot(imaging_file_path): non_imaging_file_path = imaging_file_path.replace('_imaging.txt','_non_imaging.txt') print "Using %s for non imaging file path"%non_imaging_file_path _phase_ave, _phase_err, mdp_imaging = numpy.loadtxt(imaging_file_path, unpack=True) _phase_ave, _phase_err, mdp_nonimaging = numpy.loadtxt(non_imaging_file_path, unpack=True) scale_factor = 10. print "Improvement with imaging" for i, phase in enumerate(_phase_ave): imaging = 100*mdp_imaging[i]*(1/numpy.sqrt(scale_factor)) non_imaging = 100*mdp_nonimaging[i]*(1/numpy.sqrt(scale_factor)) print "%s\t Imaging (non):%s (%s) %s"%(phase,imaging,non_imaging,non_imaging/imaging) sim_label_imaging = 'XIPE %s ks\n Imaging 15"' % (SIM_DURATION*scale_factor/1000.) sim_label_nonimaging = 'Non imaging' lc_label = 'Light curve' plt.errorbar(_phase_ave, 100*mdp_imaging*(1/numpy.sqrt(scale_factor)),xerr=_phase_err, label=sim_label_imaging,fmt='o',markersize=6) plt.errorbar(_phase_ave, 100*mdp_nonimaging*(1/numpy.sqrt(scale_factor)),xerr=_phase_err, label=sim_label_nonimaging,fmt='v',markersize=6) pl_normalization_spline.plot(scale=10., show=False, color='darkgray',label=lc_label) #on_phase = 0.25, 0.45 #off_phase = 0.45,0.9 plt.axvspan(0.25, 0.45, color='r', alpha=0.45, lw=0) plt.axvspan(0.45, 0.9, color='gray', alpha=0.25, lw=0) plt.ylabel('MDP 99\%') plt.legend() plt.savefig('crab_complex_mdp_imaging_vs_nonimaging_%i_shaded.png'%(SIM_DURATION*scale_factor/1000.)) plt.show()
def plotmdp(): spin00_pol_degree_spline = buildspline(0.5) spin00_mcube = xBinnedModulationCube(fetch_mcubepath(0.5)) spin998_pol_degree_spline = buildspline(0.998) spin998_mcube = xBinnedModulationCube(fetch_mcubepath(0.998)) spin00_mcube.fit() spin998_mcube.fit() spin00_fit_results = spin00_mcube.fit_results[0] spin998_fit_results = spin998_mcube.fit_results[0] plt.figure('MDP') spin00_mdp = spin00_mcube.mdp99[:-1] spin998_mdp = spin998_mcube.mdp99[:-1] emean = spin00_mcube.emean[:-1] emin = spin00_mcube.emin[:-1] emax = spin00_mcube.emax[:-1] width = (emax-emin)/2. plt.errorbar(emean,spin00_mdp,xerr=width, label='Spin 0.5',marker='o',linestyle='--') plt.errorbar(emean,spin998_mdp,xerr=width, label='Spin 0.998',marker='o',linestyle='--') plt.figtext(0.2, 0.85,'XIPE %s ks'%((SIM_DURATION*NUM_RUNS)/1000.),size=18) plt.xlim([1,10]) plt.ylabel('MPD 99\%') plt.xlabel('Energy (keV)') plt.legend() plt.show()
def test_plots(self): """ """ model = xpeInterstellarAbsorptionModel() plt.figure() model.xsection.plot(logx=True, logy=True, show=False) save_current_figure('gabs_xsection.png', clear=False) plt.figure() model.xsection_ecube().plot(logx=True, show=False) save_current_figure('gabs_xsection_ecube.png', clear=False) plt.figure() ra, dec = 10.684, 41.269 column_density = mapped_column_density_HI(ra, dec, 'LAB') trans = model.transmission_factor(column_density) trans.plot(logx=True, show=False, label='$n_H = $%.3e' % column_density) plt.legend(loc='upper left') save_current_figure('gabs_trans_lab.png', clear=False) plt.figure() for column_density in [1.e20, 1.e21, 1.e22, 1.e23]: trans = model.transmission_factor(column_density) trans.plot(logx=True, show=False, label='$n_H = $%.1e' %\ column_density) plt.legend(loc='upper left') save_current_figure('gabs_trans_samples.png', clear=False) if sys.flags.interactive: plt.show()
def view(self, off_axis_angle = 10., show=True): """Plot the effective area. """ from ximpol.utils.matplotlib_ import pyplot as plt plt.figure('Effective area') xInterpolatedUnivariateSplineLinear.plot(self, show=False, label='On axis') plt.plot(self.x, self.eval_(self.x, off_axis_angle), label='%s arcmin off-axis' % off_axis_angle) plt.legend(bbox_to_anchor=(0.85, 0.75)) plt.figure('Vignetting') self.vignetting.plot(show=False) if show: plt.show()
def plot(self, off_axis_angle=10., show=True): """Plot the effective area. """ from ximpol.utils.matplotlib_ import pyplot as plt plt.figure('Effective area') xInterpolatedUnivariateSplineLinear.plot(self, show=False, label='On axis') plt.plot(self.x, self.eval_(self.x, off_axis_angle), label='%s arcmin off-axis' % off_axis_angle) plt.legend(bbox_to_anchor=(0.85, 0.75)) plt.figure('Vignetting') self.vignetting.plot(show=False) if show: plt.show()
def test_cdf(self): """Test the one-dimensional azimuthal response underlying pdf. """ phi = numpy.linspace(0., 2*numpy.pi, 100) for visibility in numpy.linspace(1, 0, 5): cdf = self.generator.cdf(phi, visibility) plt.plot(phi, cdf, label='$\\xi = %.2f$' % visibility) spline = xInterpolatedUnivariateSplineLinear(phi, cdf) self.assertTrue(abs(spline(0.)) < 1e-5, 'cdf(0) = %.3e' % spline(0)) self.assertTrue(abs(spline(2*numpy.pi) - 1) < 1e-5, 'cdf(2pi) = %.3e' % spline(2*numpy.pi)) plt.axis([0., 2*numpy.pi, None, None]) plt.xlabel('$\\phi$ [rad]') plt.ylabel('cdf($\\phi$)') plt.legend(bbox_to_anchor=(0.4, 0.92)) overlay_tag() save_current_figure('test_azimuthal_resp_cdf.png', show=self.interactive)
def plot(save=False): """Plot the stuff in the analysis file. """ sim_label = 'XIPE %s ks' % (SIM_DURATION/1000.) sim_label = 'OBS: %s ks' % (SIM_DURATION/1000.) mod_label = 'Input model' lc_label = 'Light curve' _phase, _phase_err, _pol_deg, _pol_deg_err, _pol_angle,\ _pol_angle_err, _index, _index_err, _norm,\ _norm_err = numpy.loadtxt(ANALYSIS_FILE_PATH, unpack=True) plt.figure('Polarization degree') pl_normalization_spline.plot(scale=0.12, show=False, color='lightgray', label=lc_label) _pol_deg_err_p=numpy.where((_pol_deg+_pol_deg_err)<1.0,_pol_deg_err,1.0-_pol_deg) _pol_deg_err_m=numpy.where((_pol_deg-_pol_deg_err)>0.0,_pol_deg_err,_pol_deg) #if (_pol_deg+_pol_deg_err)>1.0: _pol_deg_err=1.0-yerr_p plt.errorbar(_phase, _pol_deg, xerr=_phase_err, yerr=[_pol_deg_err_m,_pol_deg_err_p], fmt='o', label=sim_label) pol_degree_spline.plot(show=False, label=mod_label) plt.axis([0., 1., 0., 0.5]) plt.legend(bbox_to_anchor=(0.45, 0.95)) if save: save_current_figure('crab_polarization_degree', OUTPUT_FOLDER, False) plt.figure('Polarization angle') pl_normalization_spline.plot(scale=0.4, offset=1.25, show=False, color='lightgray', label=lc_label) plt.errorbar(_phase, _pol_angle, xerr=_phase_err, yerr=_pol_angle_err, fmt='o', label=sim_label) pol_angle_spline.plot(show=False, label=mod_label) plt.axis([0., 1., 1.25, 3.]) plt.legend(bbox_to_anchor=(0.45, 0.95)) if save: save_current_figure('crab_polarization_angle', OUTPUT_FOLDER, False) plt.figure('PL normalization') plt.errorbar(_phase, _norm, xerr=_phase_err, yerr=_norm_err, fmt='o', label=sim_label) pl_normalization_spline.plot(show=False, label=mod_label) plt.axis([0., 1., None, None]) plt.legend(bbox_to_anchor=(0.45, 0.95)) if save: save_current_figure('crab_pl_norm', OUTPUT_FOLDER, False) plt.figure('PL index') pl_normalization_spline.plot(scale=0.18, offset=1.3, show=False, color='lightgray', label=lc_label) plt.errorbar(_phase, _index, xerr=_phase_err, yerr=_index_err, fmt='o', label=sim_label) pl_index_spline.plot(show=False, label=mod_label) plt.axis([0., 1., 1.3, 2.1]) plt.legend(bbox_to_anchor=(0.45, 0.95)) if save: save_current_figure('crab_pl_index', OUTPUT_FOLDER, False) plt.show()
def view(): #_energy_mean,_emin, _emax, _pol_deg, _pol_deg_err, _pol_angle, \ # _pol_angle_err = \ # numpy.loadtxt(ANALYSIS_FILE_PATH, unpack=True) _mcube = xBinnedModulationCube(MCUBE_FILE_PATH) _mcube.fit() _fit_results = _mcube.fit_results[0] plt.figure('Polarization degree') _mcube.plot_polarization_degree(show=False, color='blue') pol_degree_spline.plot(color='lightgray', label='Model', show=False) #plt.errorbar(_energy_mean, _pol_deg, yerr=_pol_deg_err, color='blue',marker='o') plt.figure('Polarization angle') _mcube.plot_polarization_angle(show=False, color='blue', degree=False) pol_angle_spline.plot(color='lightgray', label='Model', show=False) #plt.errorbar(_energy_mean,_pol_angle, yerr= _pol_angle_err,color='blue',marker='o') plt.legend() plt.show()
def test_cdf(self): """Test the one-dimensional azimuthal response underlying pdf. """ phi = numpy.linspace(0., 2 * numpy.pi, 100) for visibility in numpy.linspace(1, 0, 5): cdf = self.generator.cdf(phi, visibility) plt.plot(phi, cdf, label='$\\xi = %.2f$' % visibility) spline = xInterpolatedUnivariateSplineLinear(phi, cdf) self.assertTrue( abs(spline(0.)) < 1e-5, 'cdf(0) = %.3e' % spline(0)) self.assertTrue( abs(spline(2 * numpy.pi) - 1) < 1e-5, 'cdf(2pi) = %.3e' % spline(2 * numpy.pi)) plt.axis([0., 2 * numpy.pi, None, None]) plt.xlabel('$\\phi$ [rad]') plt.ylabel('cdf($\\phi$)') plt.legend(bbox_to_anchor=(0.4, 0.92)) overlay_tag() save_current_figure('test_azimuthal_resp_cdf.png', show=self.interactive)
def display(): """Display the source model. """ from ximpol.utils.matplotlib_ import pyplot as plt from ximpol.srcmodel.img import xFITSImage print(ROI_MODEL) fig = plt.figure('Energy spectrum') total_spectral_model.plot(logy=True, show=False, label='Total') nonthermal_spectral_model.plot(logy=True, show=False, label='Non-thermal') thermal_spectral_model.plot(logy=True, show=False, label='Thermal') plt.legend(bbox_to_anchor=(0.95, 0.95)) fig = thermal_component.image.plot(show=False) xFITSImage.add_label(fig, 'Chandra 1.5-3.0 keV') fig = nonthermal_component.image.plot(show=False) xFITSImage.add_label(fig, 'Chandra 4.0-6.0 keV') img = xFITSImage(he_img_file_path) fig = img.plot(show=False) polarization_map.build_grid_sample(ROI_MODEL.ra, ROI_MODEL.dec) polarization_map.overlay_arrows(fig) plt.show()
def test_pdf(self): """Test the one-dimensional azimuthal response underlying pdf. """ self.generator.plot(show=self.interactive) overlay_tag(color='white') save_current_figure('test_azimuthal_resp_generator.png', show=self.interactive) phi = numpy.linspace(0., 2*numpy.pi, 100) for visibility in numpy.linspace(1, 0, 5): pdf = self.generator.pdf(phi, visibility) plt.plot(phi, pdf, label='$\\xi = %.2f$' % visibility) spline = xInterpolatedUnivariateSplineLinear(phi, pdf) norm = spline.norm() self.assertTrue(abs(norm - 1.) < 1e-5, 'Normalization is %.3e' % norm) plt.axis([0., 2*numpy.pi, None, None]) plt.xlabel('$\\phi$ [rad]') plt.ylabel('pdf($\\phi$) [1/rad]') plt.legend(bbox_to_anchor=(0.88, 0.92)) overlay_tag() save_current_figure('test_azimuthal_resp_pdf.png', show=self.interactive)
def test_pdf(self): """Test the one-dimensional azimuthal response underlying pdf. """ self.generator.plot(show=self.interactive) overlay_tag(color='white') save_current_figure('test_azimuthal_resp_generator.png', show=self.interactive) phi = numpy.linspace(0., 2 * numpy.pi, 100) for visibility in numpy.linspace(1, 0, 5): pdf = self.generator.pdf(phi, visibility) plt.plot(phi, pdf, label='$\\xi = %.2f$' % visibility) spline = xInterpolatedUnivariateSplineLinear(phi, pdf) norm = spline.norm() self.assertTrue( abs(norm - 1.) < 1e-5, 'Normalization is %.3e' % norm) plt.axis([0., 2 * numpy.pi, None, None]) plt.xlabel('$\\phi$ [rad]') plt.ylabel('pdf($\\phi$) [1/rad]') plt.legend(bbox_to_anchor=(0.88, 0.92)) overlay_tag() save_current_figure('test_azimuthal_resp_pdf.png', show=self.interactive)
def makeMDP_fE_ComparisonPlot(file_path): scale_factor = 10. (_phase_ave, _phase_err, _energy_mean, pulsar_e_err, pulsar_e_err, mdp) =\ numpy.loadtxt(file_path, unpack=True) print "Phase ave:",_phase_ave print print "Energy mean", _energy_mean #phase_values = [0.025, 0.15, 0.35, 0.675, 0.95] phase_values = [0.35,0.675] on, on_phase_color = (0.35,'r') off, off_phase_color = (0.675,'gray') #for phase in phase_values: plt.errorbar(_energy_mean[_phase_ave==on], 100*mdp[_phase_ave==on]*(1/numpy.sqrt(scale_factor)),xerr=pulsar_e_err[_phase_ave==on], label='On Phase',fmt='o',markersize=6,ls='--',color=on_phase_color) plt.errorbar(_energy_mean[_phase_ave==off], 100*mdp[_phase_ave==off]*(1/numpy.sqrt(scale_factor)),xerr=pulsar_e_err[_phase_ave==off], label='Off Phase',fmt='o',markersize=6,ls='--',color=off_phase_color) plt.legend() plt.ylabel('MPD 99\%') plt.xlabel('Energy (keV)') plt.savefig('crab_complex_mdp_imaging_fE_%i.png'%(SIM_DURATION*scale_factor/1000.)) plt.show()
def plot(save_plots=False): """ """ sim_label = 'XIPE %s ks' % (SIM_DURATION/1000.) mod_label = 'Input model' _phase, _phase_err, _pol_deg, _pol_deg_err, _pol_angle,\ _pol_angle_err = numpy.loadtxt(ANALYSIS_FILE_PATH, unpack=True) _colors = ['blue']*len(_pol_deg) plt.figure('Polarization degree') _good_fit = _pol_deg > 2*_pol_deg_err _bad_fit = numpy.logical_not(_good_fit) plt.errorbar(_phase[_good_fit], _pol_deg[_good_fit], xerr=_phase_err[_good_fit], yerr=_pol_deg_err[_good_fit], fmt='o', label=sim_label, color='blue') plt.errorbar(_phase[_bad_fit], _pol_deg[_bad_fit], xerr=_phase_err[_bad_fit], yerr=_pol_deg_err[_bad_fit], fmt='o', color='gray') pol_degree_spline.plot(show=False, label=mod_label, color='green') plt.axis([0., 1., 0., 0.1]) plt.legend(bbox_to_anchor=(0.37, 0.95)) plt.figtext(0.6, 0.8, '%.2f--%.2f keV' %\ (E_BINNING[0], E_BINNING[-1]), size=16) if save_plots: plt.savefig('gk_per_polarization_degree.png') plt.figure('Polarization angle') plt.errorbar(_phase[_good_fit], _pol_angle[_good_fit], xerr=_phase_err[_good_fit], yerr=_pol_angle_err[_good_fit], fmt='o', label=sim_label, color='blue') plt.errorbar(_phase[_bad_fit], _pol_angle[_bad_fit], xerr=_phase_err[_bad_fit], yerr=_pol_angle_err[_bad_fit], fmt='o', color='gray') pol_angle_spline.plot(show=False, label=mod_label, color='green', scale=numpy.radians(1.)) plt.axis([0., 1., -0.1, 1.5]) plt.xlabel('Rotational phase') plt.ylabel('Polarization angle [rad]') plt.legend(bbox_to_anchor=(0.37, 0.95)) plt.figtext(0.6, 0.8, '%.2f--%.2f keV' %\ (E_BINNING[0], E_BINNING[-1]), size=16) if save_plots: plt.savefig('gk_per_polarization_angle.png') _ebinning = zip(E_BINNING[:-1], E_BINNING[1:]) if len(_ebinning) > 1: _ebinning.append((E_BINNING[0], E_BINNING[-1])) for i, (_emin, _emax) in enumerate(_ebinning): plt.figure('Phasogram %d' % i) phasogram = xBinnedPhasogram(_phasg_file_path(i)) _scale = phasogram.counts.sum()/phasogram_spline.norm()/\ len(phasogram.counts) phasogram_spline.plot(show=False, label=mod_label, scale=_scale, color='green') phasogram.plot(show=False, color='blue', label=sim_label ) plt.legend(bbox_to_anchor=(0.37, 0.95)) plt.figtext(0.65, 0.8, '%.2f--%.2f keV' % (_emin, _emax), size=16) if save_plots: plt.savefig('gk_per_phasogram_%d.png' % i) plt.show()
def view(): #_energy_mean,_emin, _emax, _pol_deg, _pol_deg_err, _pol_angle, \ # _pol_angle_err = \ # # numpy.loadtxt(ANALYSIS_FILE_PATH, unpack=True) _mcube = xBinnedModulationCube(MCUBE_FILE_PATH) _mcube.fit() _fit_results = _mcube.fit_results[0] plt.figure('Polarization degree') _mcube.plot_polarization_degree(show=False, color='blue') pol_degree_spline.plot(color='lightgray',label='Model %s corona'%model_type, show=False) plt.figtext(0.2, 0.85,'XIPE %s ks'%(SIM_DURATION/1000.),size=18) #plt.errorbar(_energy_mean, _pol_deg, yerr=_pol_deg_err, color='blue',marker='o') plt.legend() plt.figure('Polarization angle') _mcube.plot_polarization_angle(show=False, color='blue', degree=False) pol_angle_spline.plot(color='lightgray',label='Model %s corona'%model_type, show=False) plt.figtext(0.2, 0.85,'XIPE %s ks'%(SIM_DURATION/1000.),size=18) #plt.errorbar(_energy_mean,_pol_angle, yerr= _pol_angle_err,color='blue',marker='o') plt.legend() plt.figure('MDP %s'%base_name) mdp = _mcube.mdp99 emean = _mcube.emean emin = _mcube.emin emax = _mcube.emax width = (emax-emin)/2. plt.errorbar(emean,mdp,xerr=width, label='MDP99',marker='o',linestyle='--') plt.figtext(0.2, 0.85,'XIPE %s ks'%(SIM_DURATION/1000.),size=18) plt.xlim([1,10]) plt.ylabel('MPD 99 %') plt.xlabel('Energy (keV)') #plt.legend() plt.show()
def plot(): spherical_mcube = xBinnedModulationCube(SPHERICAL_MCUBE_PATH) wedge_mcube = xBinnedModulationCube(WEDGE_MCUBE_PATH) spherical_mcube.fit() wedge_mcube.fit() spherical_fit_results = spherical_mcube.fit_results[0] wedge_fit_results = wedge_mcube.fit_results[0] plt.figure('Polarization degree') spherical_mcube.plot_polarization_degree(show=False, color='blue') pol_degree_spline_spherical.plot(color='lightblue',label='Spherical corona model (40 degree inclination)', show=False) wedge_mcube.plot_polarization_degree(show=False, color='red') pol_degree_spline_wedge.plot(color='lightsalmon',label='Wedge corona model (40 degree inclination)', show=False) plt.figtext(0.2, 0.85,'XIPE %s ks'%((SIM_DURATION*NUM_RUNS)/1000.),size=18) plt.xlim([1,10]) plt.legend() plt.show()
def plot(save=False): """Plot the stuff in the analysis file. """ for j in range(len(E_BINNING)): if (j==len(E_BINNING)-1): analysis_file = ANALYSIS_FILE_PATH emin=E_BINNING[0] emax=E_BINNING[-1] else: analysis_file = '%s_%d' % (ANALYSIS_FILE_PATH,j) emin=E_BINNING[j] emax=E_BINNING[j+1] sim_label = 'XIPE %s ks' % (SIM_DURATION/1000.) mod_label = 'Input model' lc_label = 'Light curve' _phase, _phase_err, _pol_deg, _pol_deg_err, _pol_angle,\ _pol_angle_err, _index, _index_err, _norm,\ _norm_err = numpy.loadtxt(ANALYSIS_FILE_PATH, unpack=True) plt.figure('Polarization degree (%g-%g keV)' % (emin,emax)) plt.title('Her X-1 (%g-%g keV)' % (emin,emax)) pl_normalization_spline.plot(scale=20, show=False, color='lightgray', label=lc_label) plt.errorbar(_phase, _pol_deg, xerr=_phase_err, yerr=_pol_deg_err, fmt='o', label=sim_label) pol_degree_spline.plot(show=False, label=mod_label) # pol_degree_spline_noqed.plot(show=False, label='No QED') plt.axis([0., 1., 0., 1.1]) plt.legend(bbox_to_anchor=(0.4, 0.5)) if save: save_current_figure('herx1_polarization_degree_%d' % j, OUTPUT_FOLDER, False) plt.figure('Polarization angle (%g-%g keV)' % (emin,emax)) plt.title('Her X-1 (%g-%g keV)' % (emin,emax)) pl_normalization_spline.plot(scale=60, offset=0, show=False, color='lightgray', label=lc_label) plt.errorbar(_phase, _pol_angle, xerr=_phase_err, yerr=_pol_angle_err, fmt='o', label=sim_label) pol_angle_spline.plot(show=False, label=mod_label) plt.axis([0., 1., 0, 3.15]) plt.legend(bbox_to_anchor=(0.4, 0.3)) if save: save_current_figure('herx1_polarization_angle_%d' %j, OUTPUT_FOLDER, False) plt.figure('Flux (%g-%g keV)' % (emin,emax)) plt.title('Her X-1 (%g-%g keV)' % (emin,emax)) plt.errorbar(_phase, 0.21*_norm/(2-_index)*(10.**(2.0-_index)-2.**(2.-_index)), xerr=_phase_err, yerr=0.21*_norm_err/(2-_index)*(10.**(2-_index)-2.**(2.-_index)), fmt='o', label=sim_label) pl_normalization_spline.plot(scale=1,show=False, label=mod_label) plt.axis([0., 1., None, None]) plt.legend(bbox_to_anchor=(0.75, 0.95)) if save: save_current_figure('herx1_flux_%d' % j, OUTPUT_FOLDER, False) plt.show()
def plot(save=False): """Plot the stuff in the analysis file. """ sim_label = 'XIPE %s ks' % (SIM_DURATION/1000.) mod_label = 'Input model' lc_label = 'Light curve' _phase, _phase_err, _pol_deg, _pol_deg_err, _pol_angle,\ _pol_angle_err, _index, _index_err, _norm,\ _norm_err = numpy.loadtxt(ANALYSIS_FILE_PATH, unpack=True) plt.figure('Polarization degree') pl_normalization_spline.plot(scale=20, show=False, color='lightgray', label=lc_label) plt.errorbar(_phase, _pol_deg, xerr=_phase_err, yerr=_pol_deg_err, fmt='o', label=sim_label) pol_degree_spline.plot(show=False, label='QED-On') pol_degree_spline_noqed.plot(show=False, offset=0.03, scale=1.06, label='QED-Off') plt.axis([0., 1., 0., 1.1]) plt.legend(bbox_to_anchor=(0.4, 0.6)) if save: save_current_figure('4u_polarization_degree', OUTPUT_FOLDER, False) plt.figure('Polarization angle') pl_normalization_spline.plot(scale=60, offset=0, show=False, color='lightgray', label=lc_label) plt.errorbar(_phase, _pol_angle, xerr=_phase_err, yerr=_pol_angle_err, fmt='o', label=sim_label) pol_angle_spline.plot(show=False, label=mod_label) plt.axis([0., 1., 0, 3.15]) plt.legend(bbox_to_anchor=(0.4, 0.3)) if save: save_current_figure('4u_polarization_angle', OUTPUT_FOLDER, False) plt.figure('Flux (2-10 keV)') plt.errorbar(_phase, 0.21*_norm/(2-_index)*(10.**(2.0-_index)-2.**(2.-_index)), xerr=_phase_err, yerr=0.21*_norm_err/(2-_index)*(10.**(2-_index)-2.**(2.-_index)), fmt='o', label=sim_label) pl_normalization_spline.plot(scale=1,show=False, label=mod_label) plt.axis([0., 1., None, None]) plt.legend(bbox_to_anchor=(0.75, 0.95)) if save: save_current_figure('4u_flux', OUTPUT_FOLDER, False) plt.show()
def plot(save=False): """Plot the stuff in the analysis file. """ def draw_time_grid(color='blue'): """ """ times = [3600., 3600.*24., 3600.*24.*7.] labels = ['1 hour', '1 day', '1 week'] for t, l in zip(times, labels): plt.axvline(t, linestyle='dashed', color=color) ymin, ymax = plt.gca().get_ylim() y = ymin + 1.05*(ymax - ymin) plt.text(t, y, l, ha='center', color=color) sim_label = 'XIPE' mod_label = 'Input model' lc_label = 'Light curve' _time, _time_errp, _time_errm, _pol_deg, _pol_deg_err, _pol_angle,\ _pol_angle_err, _index, _index_err, _norm,\ _norm_err = numpy.loadtxt(ANALYSIS_FILE_PATH, unpack=True) logger.info(_time) logger.info((_time_errp + _time_errm)/3600.) _pol_angle = numpy.degrees(_pol_angle) _pol_angle_err = numpy.degrees(_pol_angle_err) plt.figure('Polarization degree') pol_degree_spline.plot(show=False, label=mod_label, logx=True) plt.errorbar(_time, _pol_deg, xerr=[_time_errm, _time_errp], yerr=_pol_deg_err, fmt='o', label=sim_label) plt.axis([100., 1e6, 0., 0.6]) plt.legend(bbox_to_anchor=(0.4, 0.95)) draw_time_grid() if save: save_current_figure('grb130427_swift_polarization_degree', OUTPUT_FOLDER, False) plt.figure('Polarization angle') _x = pol_degree_spline.x _y = numpy.full(len(_x), polarization_angle(_x, None, None, None)) _y = numpy.degrees(_y) fmt = dict(xname='Time', xunits='s', yname='Polarization angle', yunits=r'$^\circ$') _s = xInterpolatedUnivariateSpline(_x, _y, **fmt) _s.plot(logx=True, show=False, label=mod_label) plt.errorbar(_time, _pol_angle, xerr=[_time_errm, _time_errp], yerr=_pol_angle_err, fmt='o', label=sim_label) plt.axis([100., 1e6, None, None]) plt.legend(bbox_to_anchor=(0.4, 0.95)) draw_time_grid() if save: save_current_figure('grb130427_swift_polarization_angle', OUTPUT_FOLDER, False) plt.figure('PL index') _y = numpy.full(len(_x), PL_INDEX) fmt = dict(xname='Time', xunits='s', yname='PL index') _s = xInterpolatedUnivariateSpline(_x, _y, **fmt) _s.plot(logx=True, show=False, label=mod_label) plt.errorbar(_time, _index, xerr=[_time_errm, _time_errp], yerr=_index_err, fmt='o', label=sim_label) plt.axis([100., 1e6, None, None]) plt.legend(bbox_to_anchor=(0.4, 0.95)) draw_time_grid() if save: save_current_figure('grb130427_swift_pl_index', OUTPUT_FOLDER, False) #plt.figure('PL normalization') #plt.errorbar(_time, _norm, xerr=[_time_errm, _time_errp], yerr=_norm_err, # fmt='o', label=sim_label) #pl_normalization_spline.plot(show=False, label=mod_label) #plt.axis([100., 1e6, None, None]) #plt.legend(bbox_to_anchor=(0.4, 0.95)) #draw_time_grid() #if save: # save_current_figure('grb130427_swift_pl_norm', OUTPUT_FOLDER, False) plt.figure('Light curve') lc = xBinnedLightCurve(_lc_file_path()) lc.plot(show=False) # This should be implemented in the binned LC class. plt.xscale('log') plt.yscale('log') plt.axis([100., 1e6, None, None]) draw_time_grid() if save: save_current_figure('grb130427_swift_lc', OUTPUT_FOLDER, False) plt.show()
sgrb1 = xUniformDisk('Sgr B1', 266.75833, -28.5325, angular_radius(6.), energy_spectrum_b1, polarization_degree_b1, polarization_angle_b1) spectrum_spline_b2 = parse_spectral_model('spec_model_SgrB2.txt') def energy_spectrum_b2(E, t): """ """ return spectrum_spline_b2(E) polarization_degree_b2 = constant(0.455) polarization_angle_b2 = constant(numpy.radians(84.4)) sgrb2 = xUniformDisk('Sgr B2', 266.835, -28.38528, angular_radius(5.), energy_spectrum_b2, polarization_degree_b2, polarization_angle_b2) ROI_MODEL.add_sources(sgrb1, sgrb2) if __name__ == '__main__': print(ROI_MODEL) from ximpol.utils.matplotlib_ import pyplot as plt plt.figure('Sgr complex') spectrum_spline_b1.plot(show=False, label='Sgr B1') spectrum_spline_b2.plot(show=False, label='Sgr B2') plt.yscale('log') plt.axis([1, 10, 1e-7, 1e-3]) plt.legend(bbox_to_anchor=(0.35, 0.85)) plt.show()
spectrum = power_law(C, Gamma) plt.figure('Source spectrum') _t = numpy.linspace(T_MIN, T_MAX, 100) _e = aeff.x fmt = dict(xname='Time', xunits='s', yname='Energy', yunits='keV', zname='dN/dE', zunits='cm$^{-2}$ s$^{-1}$ keV$^{-1}$') spectrum_spline = xInterpolatedBivariateSplineLinear(_t, _e, spectrum, **fmt) spectrum_spline.plot(show=False, logz=True) save_current_figure('source_spectrum.png', OUTPUT_FOLDER, clear=False) plt.figure('Source spectrum slices') for t in [T_MIN, 0.5*(T_MIN + T_MAX), T_MAX]: spectrum_spline.vslice(t).plot(show=False, logx=True, logy=True, label='t = %d s' % t) plt.legend(bbox_to_anchor=(0.75, 0.95)) plt.axis([1, 10, None, None]) save_current_figure('source_spectrum_slices.png', OUTPUT_FOLDER, clear=False) plt.figure('Count spectrum') count_spectrum = xCountSpectrum(spectrum, aeff, _t) count_spectrum.plot(show=False, logz=True) save_current_figure('count_spectrum.png', OUTPUT_FOLDER, clear=False) plt.figure('Count spectrum slices') for t in [T_MIN, 0.5*(T_MIN + T_MAX), T_MAX]: count_spectrum.vslice(t).plot(show=False, logx=True, logy=True, label='t = %d s' % t) plt.legend(bbox_to_anchor=(0.9, 0.95)) plt.axis([1, 10, None, None]) save_current_figure('count_spectrum_slices.png', OUTPUT_FOLDER, clear=False)
def plot(save=False): """Plot the stuff in the analysis file. """ def draw_time_grid(color='blue'): """ """ times = [3600., 3600. * 24., 3600. * 24. * 7.] labels = ['1 hour', '1 day', '1 week'] for t, l in zip(times, labels): plt.axvline(t, linestyle='dashed', color=color) ymin, ymax = plt.gca().get_ylim() y = ymin + 1.05 * (ymax - ymin) plt.text(t, y, l, ha='center', color=color) sim_label = 'XIPE' mod_label = 'Input model' lc_label = 'Light curve' _time, _time_errp, _time_errm, _pol_deg, _pol_deg_err, _pol_angle,\ _pol_angle_err, _index, _index_err, _norm,\ _norm_err = numpy.loadtxt(ANALYSIS_FILE_PATH, unpack=True) logger.info(_time) logger.info((_time_errp + _time_errm) / 3600.) _pol_angle = numpy.degrees(_pol_angle) _pol_angle_err = numpy.degrees(_pol_angle_err) plt.figure('Polarization degree') pol_degree_spline.plot(show=False, label=mod_label, logx=True) plt.errorbar(_time, _pol_deg, xerr=[_time_errm, _time_errp], yerr=_pol_deg_err, fmt='o', label=sim_label) plt.axis([100., 1e6, 0., 0.6]) plt.legend(bbox_to_anchor=(0.4, 0.95)) draw_time_grid() if save: save_current_figure('grb130427_swift_polarization_degree', OUTPUT_FOLDER, False) plt.figure('Polarization angle') _x = pol_degree_spline.x _y = numpy.full(len(_x), polarization_angle(_x, None, None, None)) _y = numpy.degrees(_y) fmt = dict(xname='Time', xunits='s', yname='Polarization angle', yunits=r'$^\circ$') _s = xInterpolatedUnivariateSpline(_x, _y, **fmt) _s.plot(logx=True, show=False, label=mod_label) plt.errorbar(_time, _pol_angle, xerr=[_time_errm, _time_errp], yerr=_pol_angle_err, fmt='o', label=sim_label) plt.axis([100., 1e6, None, None]) plt.legend(bbox_to_anchor=(0.4, 0.95)) draw_time_grid() if save: save_current_figure('grb130427_swift_polarization_angle', OUTPUT_FOLDER, False) plt.figure('PL index') _y = numpy.full(len(_x), PL_INDEX) fmt = dict(xname='Time', xunits='s', yname='PL index') _s = xInterpolatedUnivariateSpline(_x, _y, **fmt) _s.plot(logx=True, show=False, label=mod_label) plt.errorbar(_time, _index, xerr=[_time_errm, _time_errp], yerr=_index_err, fmt='o', label=sim_label) plt.axis([100., 1e6, None, None]) plt.legend(bbox_to_anchor=(0.4, 0.95)) draw_time_grid() if save: save_current_figure('grb130427_swift_pl_index', OUTPUT_FOLDER, False) #plt.figure('PL normalization') #plt.errorbar(_time, _norm, xerr=[_time_errm, _time_errp], yerr=_norm_err, # fmt='o', label=sim_label) #pl_normalization_spline.plot(show=False, label=mod_label) #plt.axis([100., 1e6, None, None]) #plt.legend(bbox_to_anchor=(0.4, 0.95)) #draw_time_grid() #if save: # save_current_figure('grb130427_swift_pl_norm', OUTPUT_FOLDER, False) plt.figure('Light curve') lc = xBinnedLightCurve(_lc_file_path()) lc.plot(show=False) # This should be implemented in the binned LC class. plt.xscale('log') plt.yscale('log') plt.axis([100., 1e6, None, None]) draw_time_grid() if save: save_current_figure('grb130427_swift_lc', OUTPUT_FOLDER, False) plt.show()
def test_power_law_stationary(self): """Test a time-independent power law. This creates a count spectrum with no time dependence, i.e., with only two (identical) interpolating time points on the auxiliary (time) axis. The power-law parameters (C and gamma) are constant >>> tmin = 0. >>> tmax = 100. >>> C = 1. >>> Gamma = 2. >>> >>> def powerlaw(E, t): >>> return C*numpy.power(E, -Gamma) >>> >>> _t = numpy.linspace(tmin, tmax, 2) >>> count_spectrum = xCountSpectrum(powerlaw, self.aeff, _t) and the underlying xUnivariateAuxGenerator looks like. .. image:: ../figures/test_power_law_stationary_2d.png Then a vertical slice (i.e., an interpolated linear spline) is taken in the middle of the auxiliary axis >>> tref = 0.5*(tmin + tmax) >>> ref_slice = count_spectrum.slice(tref) and the y-values of the spline are compared with the direct product of the effective area and the input spectrum: >>> _x = self.aeff.x >>> _y = C*numpy.power(_x, -Gamma)*self.aeff.y (Note that in general the two are technically not the same thing, as going from the count spectrum to the slice we do interpolate in time, although in this particular case the interpolation is trivial). If everything goes well, they should be on top of each other. The figure below is also showing the original power-law spectrum multiplied by the peak effective area. .. image:: ../figures/test_power_law_stationary_slice.png """ tmin = 0. tmax = 100. tref = 0.5*(tmin + tmax) C = 1. Gamma = 2. def powerlaw(E, t): """Function defining a time-dependent energy spectrum. """ return C*numpy.power(E, -Gamma) _t = numpy.linspace(tmin, tmax, 2) count_spectrum = xCountSpectrum(powerlaw, self.aeff, _t) count_spectrum.plot(show=False) overlay_tag(color='white') save_current_figure('test_power_law_stationary_2d.png', show=self.interactive) ref_slice = count_spectrum.slice(tref) _x = self.aeff.x _y = C*numpy.power(_x, -Gamma)*self.aeff.y.max() plt.plot(_x, _y, '-', label='Original power-law spectrum') _y = C*numpy.power(_x, -Gamma)*self.aeff.y _mask = _y > 0. _x = _x[_mask] _y = _y[_mask] delta = abs((_y - ref_slice(_x))/_y).max() self.assertTrue(delta < 1e-3, 'max deviation %.9f' % delta) plt.plot(_x, _y, 'o', label='Direct convolution with aeff') ref_slice.plot(logx=True, logy=True, show=False, label='xCountSpectrum output') overlay_tag() plt.text(0.1, 0.1, 'Max. difference = %.3e' % delta, transform=plt.gca().transAxes) plt.legend(bbox_to_anchor=(0.75, 0.5)) plt.axis([0.6, 10, None, None]) save_current_figure('test_power_law_stationary_slice.png', show=self.interactive)
def test_power_law_rvs(self, num_events=1000000): """Test the generation of event energies from a count power-law spectrum convoluted with the effective area. This turned out to be more tricky than we anticipated. Since the convolution of the source spectrum with the effective area falls pretty quickly at high energy, there's typically very few events above a few keV and, as a consequence, the slope of the corresponding ppf is fairly steep close to one. .. image:: ../figures/test_power_law_rvs_vppf.png This implies that the ppf in each slice must be properly sampled close to 1 (initial tests showed, e.g., that a uniform grid with 100 points between 0 and 1 was not enough to throw meaningful random numbers for a typical power-law source spectrum). This is particularly true for soft spectral indices---which is why we picked `Gamma = 3.` for this test. .. image:: ../figures/test_power_law_rvs_counts.png """ tmin = 0. tmax = 100. tref = 0.5*(tmin + tmax) C = 1. Gamma = 3. def powerlaw(E, t): """Function defining a time-dependent energy spectrum. """ return C*numpy.power(E, -Gamma) _t = numpy.linspace(tmin, tmax, 2) count_spectrum = xCountSpectrum(powerlaw, self.aeff, _t) count_spectrum.vppf.vslice(tref).plot(show=False, overlay=True) overlay_tag() save_current_figure('test_power_law_rvs_vppf.png', show=self.interactive) ref_slice = count_spectrum.slice(tref) _time = numpy.full(num_events, tref) _energy = count_spectrum.rvs(_time) _binning = numpy.linspace(self.aeff.xmin(), self.aeff.xmax(), 100) obs, bins, patches = plt.hist(_energy, bins=_binning, histtype='step', label='Random energies') plt.yscale('log') # We want to overlay the reference count-spectrum slice, normalized # to the total number of events simulated. bin_width = (bins[1] - bins[0]) scale = num_events*bin_width/ref_slice.norm() _x = 0.5*(bins[:-1] + bins[1:]) _y = scale*ref_slice(_x) plt.plot(_x, _y, label='Underlying pdf') # And, for the chisquare, we do correctly integrate the slice in each # energy bin, rather than evaluating it at the bin center. exp = [] scale = num_events/ref_slice.norm() for _emin, _emax in zip(bins[:-1], bins[1:]): exp.append(scale*ref_slice.integral(_emin, _emax)) exp = numpy.array(exp) _mask = exp > 0. exp = exp[_mask] obs = obs[_mask] chi2 = ((exp - obs)**2/exp).sum() ndof = len(obs) chi2_min = ndof - 3*numpy.sqrt(2*ndof) chi2_max = ndof + 3*numpy.sqrt(2*ndof) self.assertTrue(chi2 > chi2_min, 'chisquare too low (%.2f/%d)' %\ (chi2, ndof)) self.assertTrue(chi2 < chi2_max, 'chisquare too high (%.2f/%d)' %\ (chi2, ndof)) plt.text(0.5, 0.1, '$\chi^2$/ndof = %.2f/%d' % (chi2, ndof), transform=plt.gca().transAxes) plt.legend(bbox_to_anchor=(0.85, 0.75)) overlay_tag() save_current_figure('test_power_law_rvs_counts.png', show=self.interactive)
def test_power_law_variable(self): """Test a time-dependent power law. This creates a time-dependent count spectrum, where the two parameters of the underlying power law (C and Gamma) vary linearly with time, in opposite direction, between 1 and 2. >>> def C(t): >>> return 1. + (t - tmin)/(tmax - tmin) >>> >>> def Gamma(t): >>> return 2. - (t - tmin)/(tmax - tmin) >>> >>> def powerlaw(E, t): >>> return C(t)*numpy.power(E, -Gamma(t)) (Beware: this does not mean that you can interpolate linearly between the two time extremes, as both parameters vary at the same time and the spectral shape does not evolve linearly with time---we're sampling the time axis with 100 points). The underlying xUnivariateAuxGenerator looks like. .. image:: ../figures/test_power_law_variable_2d.png Then a vertical slice (i.e., an interpolated linear spline) is taken in the middle of the auxiliary axis and the y-values of the spline are compared with the direct product of the effective area and the count spectrum (evaluated at the same time). If everything goes well, they should be on top of each other. The figure below is also showing the orignal power-law spectrum multiplied by the peak effective area. .. image:: ../figures/test_power_law_variable_slice.png Finally, we do test the light-curve building by comparing it with the values from a direct intergration of the vertical slices on a fixed-spacing grid. Note that, since the normalization increases with time and the spectral index becomes harder, the light-curve increases more than linearly. .. image:: ../figures/test_power_law_variable_lc.png """ tmin = 0. tmax = 100. tref = 0.5*(tmin + tmax) def C(t): """Time-dependent C---equals to 1 @ tmin and 2 @ tmax. """ return 1. + (t - tmin)/(tmax - tmin) def Gamma(t): """Time-dependent C---equals to 2 @ tmin and 1 @ tmax. """ return 2. - (t - tmin)/(tmax - tmin) def powerlaw(E, t): """Function defining a time-dependent energy spectrum. """ return C(t)*numpy.power(E, -Gamma(t)) _t = numpy.linspace(tmin, tmax, 100) count_spectrum = xCountSpectrum(powerlaw, self.aeff, _t) count_spectrum.plot(show=False) overlay_tag(color='white') save_current_figure('test_power_law_variable_2d.png', show=self.interactive) ref_slice = count_spectrum.slice(tref) _x = self.aeff.x _y = self.aeff.y.max()*C(tref)*numpy.power(_x, -Gamma(tref)) plt.plot(_x, _y, '-', label='Original power-law spectrum') _y = C(tref)*numpy.power(_x, -Gamma(tref))*self.aeff.y _mask = _y > 0. _x = _x[_mask] _y = _y[_mask] delta = abs((_y - ref_slice(_x))/_y).max() self.assertTrue(delta < 1e-3, 'max deviation %.9f' % delta) plt.plot(_x, _y, 'o', label='Direct convolution with aeff') ref_slice.plot(logx=True, logy=True, show=False, label='xCountSpectrum output') overlay_tag() plt.text(0.1, 0.1, 'Max. difference = %.3e' % delta, transform=plt.gca().transAxes) plt.legend(bbox_to_anchor=(0.75, 0.5)) plt.axis([0.6, 10, None, None]) save_current_figure('test_power_law_variable_slice.png', show=self.interactive) _x = numpy.linspace(tmin, tmax, 33) _y = [] for _xp in _x: _y.append(count_spectrum.slice(_xp).norm()) _y = numpy.array(_y) plt.plot(_x, _y, 'o', label='Direct integral flux values') delta = abs((_y - count_spectrum.light_curve(_x))/_y).max() self.assertTrue(delta < 1e-3, 'max deviation %.9f' % delta) count_spectrum.light_curve.plot(show=False, label='xCountSpectrum light-curve') overlay_tag() plt.legend(bbox_to_anchor=(0.65, 0.75)) plt.text(0.5, 0.1, 'Max. difference = %.3e' % delta, transform=plt.gca().transAxes) save_current_figure('test_power_law_variable_lc.png', show=self.interactive)
def plot(angle=False): spin05_pol_degree_spline, spin05_pol_angle_spline = buildspline(0.5) spin05_mcube = xBinnedModulationCube(fetch_mcubepath(0.5)) spin09_pol_degree_spline, spin09_pol_angle_spline = buildspline(0.9) spin09_mcube = xBinnedModulationCube(fetch_mcubepath(0.9)) spin998_pol_degree_spline, spin998_pol_angle_spline = buildspline(0.998) spin998_mcube = xBinnedModulationCube(fetch_mcubepath(0.998)) spin05_mcube.fit() spin09_mcube.fit() spin998_mcube.fit() spin05_fit_results = spin05_mcube.fit_results[0] spin09_fit_results = spin09_mcube.fit_results[0] spin998_fit_results = spin998_mcube.fit_results[0] plt.figure('Polarization degree') spin05_mcube.plot_polarization_degree(show=False, color='blue') spin05_pol_degree_spline.plot(color='lightblue',label='Spin 0.5', show=False) spin998_mcube.plot_polarization_degree(show=False, color='red') spin998_pol_degree_spline.plot(color='lightsalmon',label='Spin 0.998', show=False) plt.figtext(0.2, 0.85,'XIPE %s ks'%((SIM_DURATION*NUM_RUNS)/1000.),size=18) plt.ylim([0.00,0.045]) plt.xlim([1,10]) plt.legend() plt.show() if angle: plt.figure('Polarization angle') spin05_mcube.plot_polarization_angle(show=False, degree=True, color='blue') #Converting to degrees spin05_y = numpy.degrees(spin05_pol_angle_spline.y) energy = spin05_pol_angle_spline.x plt.plot(energy, spin05_y, color='lightblue',label='Spin 0.5') spin09_mcube.plot_polarization_angle(show=False, degree=True, color='gray') #Converting to degrees spin09_y = numpy.degrees(spin09_pol_angle_spline.y) energy = spin09_pol_angle_spline.x plt.plot(energy, spin09_y, color='lightgray',label='Spin 0.9') spin998_mcube.plot_polarization_angle(show=False, degree=True, color='red') spin998_y = numpy.degrees(spin998_pol_angle_spline.y) energy = spin998_pol_angle_spline.x plt.plot(energy, spin998_y, color='lightsalmon',label='Spin 0.998') #spin998_pol_angle_spline.plot(color='lightsalmon',label='Spin 0.998', show=False) plt.figtext(0.2, 0.85,'XIPE %s ks'%((SIM_DURATION*NUM_RUNS)/1000.),size=18) plt.xlim([1,10]) plt.ylim([40,200]) plt.legend() plt.show()
aeff, psf, modf, edisp = load_irfs(IRF_NAME) plt.figure('On axis effective area') xInterpolatedUnivariateSplineLinear.plot(aeff, show=False) save_current_figure('aeff_on_axis.png', OUTPUT_FOLDER, clear=False) plt.figure('Vignetting') aeff.vignetting.plot(show=False) save_current_figure('aeff_vignetting.png', OUTPUT_FOLDER, clear=False) plt.figure('Edisp matrix') edisp.matrix.plot(show=False) save_current_figure('edisp_matrix.png', OUTPUT_FOLDER, clear=False) plt.figure('Edisp slice') _e = 6. edisp.matrix.vslice(_e).plot(show=False, label='E = %.2f keV' % _e) plt.axis([0, 256, None, None]) plt.legend(bbox_to_anchor=(0.45, 0.75)) save_current_figure('edisp_slice.png', OUTPUT_FOLDER, clear=False) plt.figure('PSF') psf.plot(show=False) save_current_figure('psf.png', OUTPUT_FOLDER, clear=False) plt.figure('Modulation factor') modf.plot(show=False) save_current_figure('modf.png', OUTPUT_FOLDER, clear=False) plt.show()
def calcMDP(plot=False): mdp_file = open(MDP_OUTPUT_FILE,'w') mdp_file.write('#Simulation time %s sec \n'%SIM_DURATION) mdp_file.write('#Phase Ave delta phase Mean energy delta energy mdp99\n') nebula_mcube_file = xBinnedModulationCube(NEBULA_MCUBE_FILE_PATH) nebula_counts = nebula_mcube_file.counts nebula_mdp = nebula_mcube_file.mdp99 txt = "Pulsar phase\t Emin - Emax\t Pulsar counts\t Nebula counts\t MDP\n" MDP99_PULSAR = [] phase = [] phase_err = [] for i, (_min, _max) in enumerate(PHASE_BINS): #zip(PHASE_BINS[:-1],PHASE_BINS[1:])): pulse_diff = numpy.fabs(_max -_min) _phase_ave = 0.5*(_min + _max) phase.append(_phase_ave) _phase_err = 0.5*(_max - _min) phase_err.append(_phase_err) pulsar_phase_mcube_file = xBinnedModulationCube(_mcube_file_path(i)) pulsar_emean = pulsar_phase_mcube_file.emean for j, _energy_mean in enumerate(pulsar_emean): pulsar_emin = pulsar_phase_mcube_file.emin[j] pulsar_emax = pulsar_phase_mcube_file.emax[j] pulsar_e_err = 0.5*(pulsar_emax-pulsar_emin) pulsar_phase_counts = pulsar_phase_mcube_file.counts[j] pulsar_mdp = pulsar_phase_mcube_file.mdp99[j] #scale the nebula counts for the time used for the pulsar phase scaled_nebula_counts = pulse_diff*nebula_counts[j] count_sqrt = numpy.sqrt(pulsar_phase_counts + scaled_nebula_counts) eff_mu_pulsar = pulsar_phase_mcube_file.effective_mu[j] mdp = 4.292/eff_mu_pulsar*count_sqrt/pulsar_phase_counts MDP99_PULSAR.append(100*mdp) _data = (_phase_ave, _phase_err, _energy_mean, pulsar_e_err, pulsar_e_err, mdp) _fmt = ('%.4e ' * len(_data)).strip() _fmt = '%s\n' % _fmt _line = _fmt % _data mdp_file.write(_line) #txt += "%s\t %s - %s\t %s\t %s\t %.3f\n"%(PHASE_BINS[i], pulsar_emin[0], pulsar_emax[0], pulsar_phase_counts[0], scaled_nebula_counts[0], 100*mdp) MDP99_PULSAR = numpy.array(MDP99_PULSAR) PHASE = numpy.array(phase) mdp_file.close() if plot: scale_factor = 10 sim_label = 'XIPE %s ks' % (SIM_DURATION*scale_factor/1000.) lc_label = 'Light curve' plt.errorbar(PHASE, MDP99_PULSAR*(1/numpy.sqrt(10)),xerr=phase_err, label=sim_label,fmt='o') pl_normalization_spline.plot(scale=10., show=False, color='lightgray',label=lc_label) plt.ylabel('MDP 99\%') plt.legend() plt.savefig('crab_complex_mdp_nonimaging_%i.png'%(SIM_DURATION*scale_factor/1000.)) #plt.show() print txt
from ximpol.evt.binning import xBinnedModulationCube from ximpol.utils.matplotlib_ import pyplot as plt from ximpol.config.lamp_post_accreting_bh_XTE import pol_degree, pol_angle CFG_FILE = os.path.join(XIMPOL_CONFIG, 'lamp_post_accreting_bh_XTE.py') DURATION = 100000. E_BINNING = [1., 2., 3., 4., 5., 7., 10.] SEED = 0 pipeline = xPipeline(clobber=False) evt_file_path = pipeline.xpobssim(configfile=CFG_FILE, duration=DURATION, seed=SEED) pipeline.xpbin(evt_file_path, algorithm='CMAP') mcube_file_path = pipeline.xpbin(evt_file_path, algorithm='MCUBE', ebinalg='LIST', ebinning=E_BINNING) mcube = xBinnedModulationCube(mcube_file_path) mcube.fit() fig = plt.figure('Polarization degree') mcube.plot_polarization_degree(show=False, label='Data') pol_degree.plot(show=False, label='Model', linestyle='dashed') plt.legend(bbox_to_anchor=(0.30, 0.95)) plt.axis([1, 10, None, None]) fig = plt.figure('Polarization angle') mcube.plot_polarization_angle(show=False, label='Data') pol_angle.plot(show=False, label='Model', linestyle='dashed') plt.legend(bbox_to_anchor=(0.95, 0.95)) plt.axis([1, 10, None, None]) plt.show()
fig = plt.figure('Polarization degree') plt.xlabel('Energy [keV]') plt.ylabel('Polarization degree') bad = pol_deg < 3*pol_deg_err good = numpy.invert(bad) bad[len(E_BINNING)-1] = False good[len(E_BINNING)-1] = False _dx = numpy.array([mod_cube.emean - mod_cube.emin, mod_cube.emax - mod_cube.emean]) if bad.sum() > 0: plt.errorbar(mod_cube.emean[bad], pol_deg[bad], pol_deg_err[bad], _dx.T[bad].T, fmt='o', label='Data', color='gray') if good.sum() > 0: plt.errorbar(mod_cube.emean[good], pol_deg[good], pol_deg_err[good], _dx.T[good].T, fmt='o', label='Data', color='blue') pol_degree.plot(show=False, label='Model', linestyle='dashed', color='green') plt.legend(bbox_to_anchor=(0.30, 0.95)) plt.axis([1, 10, 0, 0.1]) #plt.savefig('/home/nicco/%s_0_0_10x%dMs_polarization_degree.png' %\ # (NAME_LIST[0:3], TIME/100000)) fig = plt.figure('Polarization angle') plt.xlabel('Energy [keV]') plt.ylabel('Polarization angle [$^\circ$]') if bad.sum() > 0: plt.errorbar(mod_cube.emean[bad], pol_ang[bad], pol_ang_err[bad], _dx.T[bad].T, fmt='o', label='Data', color='gray') if good.sum() > 0: plt.errorbar(mod_cube.emean[good], pol_ang[good], pol_ang_err[good], _dx.T[good].T, fmt='o', label='Data', color='blue') pol_angle.plot(show=False, label='Model', linestyle='dashed', color='green') plt.legend(bbox_to_anchor=(0.95, 0.95))
polarization_degree_spline.plot(show=False) plt.figure() polarization_angle_spline.plot(show=False) plt.figure() _x = numpy.linspace(0, 1, 100) _y = energy_spectrum(2., _x) plt.plot(_x, _y) plt.figure() _x = numpy.linspace(1, 10, 100) for ph in numpy.linspace(0, 0.1, 2): _y = polarization_degree(_x, ph, 0, 0) plt.plot(_x, _y, label='Phase = %.2f' % ph) plt.legend(loc='upper right') plt.figure() _x = numpy.linspace(1, 10, 100) for ph in numpy.linspace(0, 0.1, 2): _y = polarization_angle(_x, ph, 0, 0) plt.plot(_x, _y, label='Phase = %.2f' % ph) plt.legend(loc='upper right') plt.figure() _x = numpy.linspace(0, 1, 100) for e in numpy.linspace(1, 10, 10): _y = polarization_degree(e, _x, 0, 0) plt.plot(_x, _y, label='Energy = %.2f keV' % e) plt.legend(loc='upper right')