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 plot_swift_lc(grb_list,show=True): """Plots Swift GRB light curves. """ plt.figure(figsize=(10, 8), dpi=80) plt.title('Swift XRT light curves') num_grb = 0 for grb_name in grb_list: flux_outfile = download_swift_grb_lc_file(grb_name, min_obs_time=21600) if flux_outfile is not None: integral_flux_spline = parse_light_curve(flux_outfile) if integral_flux_spline is not None: if grb_name == 'GRB 130427A': integral_flux_spline.plot(num_points=1000,logx=True,\ logy=True,show=False,\ color="red",linewidth=1.0) num_grb += 1 else: c = random.uniform(0.4,0.8) integral_flux_spline.plot(num_points=1000,logx=True,\ logy=True,show=False,\ color='%f'%c,linewidth=1.0) num_grb += 1 else: continue logger.info('%i GRBs included in the plot.'%num_grb) if show: plt.show()
def plot(self, show=True, zlabel='Counts/pixel', subplot=(1, 1, 1)): """Plot the image. This is using aplpy to render the image. Warning ------- We have to figure out the subplot issue, here. I put in a horrible hack to recover the previous behavior when there's only one subplot. """ import aplpy with context_no_grids(): if subplot == (1, 1, 1): fig = aplpy.FITSFigure(self.hdu_list[0], figure=plt.figure()) else: fig = aplpy.FITSFigure(self.hdu_list[0], figure=plt.figure( 0, figsize=(10 * subplot[1], 10 * subplot[0])), subplot=subplot) fig.add_grid() fig.show_colorscale(cmap='afmhot', vmin=self.vmin, vmax=self.vmax) fig.add_colorbar() fig.colorbar.set_axis_label_text(zlabel) if show: plt.show() return fig
def main(): """ """ plt.figure(figsize=(10, 6), dpi=80) plt.title('Swift XRT light curves of GRBs up to 130427A') #get_all_swift_grb_names = ['GRB 130427A','GRB 041223'] num_grb = 0 for i,grb_name in enumerate(get_all_swift_grb_names()): flux_outfile = download_swift_grb_lc_file(grb_name) if type(flux_outfile) is str: integral_flux_spline = parse_light_curve(flux_outfile) if integral_flux_spline != 0: if grb_name == 'GRB 130427A': integral_flux_spline.plot(num_points=1000,logx=True,\ logy=True,show=False,\ color="red",linewidth=1.0) num_grb += 1 break plt.title('Swift XRT light curves of GRBs up to now') else: c = random.uniform(0.4,0.8) integral_flux_spline.plot(num_points=1000,logx=True,\ logy=True,show=False,\ color='%f'%c,linewidth=1.0) num_grb += 1 print num_grb plt.show()
def plot(self, show=True): """Plot the energy dispersion. """ from ximpol.utils.matplotlib_ import pyplot as plt from ximpol.utils.matplotlib_ import context_two_by_two emin = self.matrix.xmin() emax = self.matrix.xmax() def _plot_vslice(energy, position): """Convenience function to plot a generic vertical slice of the energy dispersion. """ ax = plt.subplot(2, 2, position) vslice = self.matrix.vslice(energy) vslice.plot(overlay=False, show=False) plt.text(0.1, 0.9, '$E = %.2f\\ \\rm{keV}$' % energy, transform=ax.transAxes) ppf = vslice.build_ppf() eres = 0.5*(ppf(0.8413) - ppf(0.1586))/ppf(0.5) plt.text(0.1, 0.85, '$\sigma_E/E = %.3f$' % eres, transform=ax.transAxes) with context_two_by_two(): plt.figure(1) ax = plt.subplot(2, 2, 1) self.matrix.plot(show=False) ax = plt.subplot(2, 2, 2) self.ebounds.plot(overlay=False, show=False) _plot_vslice(emin + 0.333*(emax - emin), 3) _plot_vslice(emin + 0.666*(emax - emin), 4) if show: plt.show()
def display(): """Display the source model. """ print(ROI_MODEL) from ximpol.utils.matplotlib_ import pyplot as plt fig = plt.figure('Energy spectrum') spectral_model.plot(show=False, logy=True) fig = plt.figure('Polarization degree') pol_degree.plot(show=False) fig = plt.figure('Polarization angle') pol_angle.plot(show=False) plt.show()
def main(): """Simple test code. """ from ximpol.utils.matplotlib_ import pyplot as plt model = xpeInterstellarAbsorptionModel() trans = model.transmission_factor(1.e22) energy = numpy.linspace(1, 10, 10) print(trans(energy)) plt.figure() model.xsection.plot(logx=True, logy=True, show=False) plt.figure() trans.plot(logx=True)
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 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 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 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 plot(self, show=True): """Overloaded plot method. """ fig = plt.figure('Phasogram') plt.errorbar(self.phase, self.counts, yerr=self.error, fmt='o') plt.xlabel('Phase') plt.ylabel('Counts/bin') if show: plt.show()
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 plot(self, show=True): """Overloaded plot method. """ fig = plt.figure('Count spectrum') plt.errorbar(self.channel, self.rate, yerr=self.error, fmt='o') plt.xlabel('PHA') plt.ylabel('Rate [Hz]') plt.yscale('log') if show: plt.show()
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') spectral_model_spline.plot(logy=True, show=False, label='Total') plt.show()
def plot(self, show=True): """Overloaded plot method. """ fig = plt.figure('Light curve') plt.errorbar(self.time, self.counts/self.timedel, yerr=self.error/self.timedel, fmt='o') plt.xlabel('Time [s]') plt.ylabel('Rate [Hz]') if show: 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 plot(self, show=True): """Overloaded plot method. """ fig = plt.figure('Light curve') plt.errorbar(self.time, self.counts / self.timedel, yerr=self.error / self.timedel, fmt='o') plt.xlabel('Time [s]') plt.ylabel('Rate [Hz]') if show: 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 plot(self, show=True, fit=True, analyze=True, xsubplot=0): """Plot the azimuthal distributions for all the energy bins. """ if analyze: fit = True for i, _emean in enumerate(self.emean): if xsubplot == 0: plt.figure() else: plt.subplot(len(self.emean), xsubplot + 1, (xsubplot + 1) * (i + 1)) self.plot_bin(i, False, False) if fit: _res = self.fit_bin(i) _res.plot(color=xpColor(i)) if analyze: fig = plt.figure('Polarization degree vs. energy') self.plot_polarization_degree(show=False) fig = plt.figure('Polarization angle vs. energy') self.plot_polarization_angle(show=False) if show: plt.show()
def plot(self, show=True, fit=True, analyze=True, xsubplot=0): """Plot the azimuthal distributions for all the energy bins. """ if analyze: fit = True for i, _emean in enumerate(self.emean): if xsubplot == 0: plt.figure() else: plt.subplot(len(self.emean), xsubplot + 1, (xsubplot + 1)*(i + 1)) self.plot_bin(i, False, False) if fit: _res = self.fit_bin(i) _res.plot(color=xpColor(i)) if analyze: fig = plt.figure('Polarization degree vs. energy') self.plot_polarization_degree(show=False) fig = plt.figure('Polarization angle vs. energy') self.plot_polarization_angle(show=False) if show: plt.show()
def test_power_law(self): """ """ norm = 1. index = 2. emin = 1. emax = 10. num_points = 5 _x = numpy.logspace(numpy.log10(emin), numpy.log10(emax), num_points) _y = norm*_x**(-index) slin = xInterpolatedUnivariateSplineLinear(_x, _y) slog = xInterpolatedUnivariateLogSplineLinear(_x, _y) target_norm = self.power_law_integral(norm, index, emin, emax) lin_norm = slin.norm() log_norm = slog.norm() delta = abs(target_norm - log_norm)/target_norm msg = 'delta = %.3e' % delta self.assertTrue(delta < 0.01, msg) if self.interactive: plt.figure() slin.plot(logx=True, logy=True, overlay=True, show=False) slog.plot(logx=True, logy=True, overlay=True, show=False) 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 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(self, show=True): """Plot the energy dispersion. """ from ximpol.utils.matplotlib_ import pyplot as plt from ximpol.utils.matplotlib_ import context_two_by_two emin = self.matrix.xmin() emax = self.matrix.xmax() def _plot_vslice(energy, position): """Convenience function to plot a generic vertical slice of the energy dispersion. """ ax = plt.subplot(2, 2, position) vslice = self.matrix.vslice(energy) vslice.plot(overlay=False, show=False) plt.text(0.1, 0.9, '$E = %.2f\\ \\rm{keV}$' % energy, transform=ax.transAxes) ppf = vslice.build_ppf() eres = 0.5 * (ppf(0.8413) - ppf(0.1586)) / ppf(0.5) plt.text(0.1, 0.85, '$\sigma_E/E = %.3f$' % eres, transform=ax.transAxes) with context_two_by_two(): plt.figure(1) ax = plt.subplot(2, 2, 1) self.matrix.plot(show=False) ax = plt.subplot(2, 2, 2) self.ebounds.plot(overlay=False, show=False) _plot_vslice(emin + 0.333 * (emax - emin), 3) _plot_vslice(emin + 0.666 * (emax - emin), 4) if show: plt.show()
def plot(self, show=True, zlabel='Counts/pixel', subplot=(1, 1, 1)): """Plot the image. This is using aplpy to render the image. Warning ------- We have to figure out the subplot issue, here. I put in a horrible hack to recover the previous behavior when there's only one subplot. """ import aplpy with context_no_grids(): if subplot == (1, 1, 1): fig = aplpy.FITSFigure(self.hdu_list[0], figure=plt.figure()) else: fig = aplpy.FITSFigure(self.hdu_list[0], figure=plt.figure(0,figsize=(10*subplot[1], 10*subplot[0])), subplot=subplot) fig.add_grid() fig.show_colorscale(cmap = 'afmhot', vmin=self.vmin, vmax=self.vmax) fig.add_colorbar() fig.colorbar.set_axis_label_text(zlabel) if show: plt.show() return fig
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 view(self, show=True): """Overloaded plot method (with default log scale on the y-axis). """ from ximpol.utils.matplotlib_ import pyplot as plt plt.figure("PSF") xInterpolatedUnivariateSpline.plot(self, logy=True, show=False) plt.figure("Solid-angle convolution") self.generator.plot(logy=True, show=False) plt.figure("EEF") self.eef.plot(show=False) if show: plt.show()
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 plot_polarization_degree(self, show=True): """ """ import aplpy if self.x_img is None: self.x_img = xFITSImage(self.xmap_file_path, build_cdf=False) if self.y_img is None: self.y_img = xFITSImage(self.ymap_file_path, build_cdf=False) _data = numpy.sqrt(self.x_data ** 2 + self.y_data ** 2) hdu_list = [self.x_img.hdu_list[0].copy()] hdu_list[0].data = _data with context_no_grids(): fig = aplpy.FITSFigure(hdu_list[0], figure=plt.figure()) fig.add_grid() fig.show_colorscale(cmap="afmhot", vmin=None, vmax=None) fig.add_colorbar() fig.colorbar.set_axis_label_text("Polarization degree") if show: plt.show() return fig
def plot_pol_map_from_ascii(): output_file = get_output_file() logger.info('Opening file %s for plotting...' % output_file) emin,emax, degree, degree_error, angle, angle_error, counts = numpy.loadtxt(output_file, delimiter=',', unpack=True) _ra = numpy.linspace(ra_min, ra_max, num_points) _dec = numpy.linspace(dec_min, dec_max, num_points) _ra, _dec = numpy.meshgrid(_ra, _dec) fig = plt.figure() for i in range(len(E_BINNING) - 1): sigma_array = degree[emin==E_BINNING[i]]/degree_error[emin==E_BINNING[i]] pol_array = degree[emin==E_BINNING[i]].reshape((num_points,num_points)) sigma_array = sigma_array.reshape((num_points,num_points)) ax1 = fig.add_subplot() label = 'XIPE %.1d ks'%(DURATION/1000.) plt.contourf(_ra,_dec,pol_array) cbar = plt.colorbar() cbar.ax.set_ylabel('Polarization degree') plt.text(0.02, 0.92, label, transform=plt.gca().transAxes, fontsize=20,color='w') plt.xlabel('RA') plt.ylabel('DEC') # fig.gca().add_artist(psf) plt.show() ax2 = fig.add_subplot() plt.contourf(_ra,_dec,sigma_array) cbar2 = plt.colorbar() cbar2.ax.set_ylabel('Sigma') plt.text(0.02, 0.92, label, transform=plt.gca().transAxes, fontsize=20,color='w') plt.xlabel('RA') plt.ylabel('DEC') plt.show()
def view(self, show=True): """Plot the energy dispersion. """ from ximpol.utils.matplotlib_ import pyplot as plt plt.figure('Energy redistribution') self.matrix.plot(show=False) plt.figure('Energy bounds') self.ebounds.plot(overlay=False, show=False) energy = 0.5*(self.matrix.xmin() + self.matrix.xmax()) plt.figure('Energy dispersion @ %.2f keV' % energy) vslice = self.matrix.vslice(energy) vslice.plot(overlay=False, show=False) plt.text(0.1, 0.9, '$E = %.2f\\ \\rm{keV}$' % energy, transform=plt.gca().transAxes) ppf = vslice.build_ppf() eres = 0.5*(ppf(0.8413) - ppf(0.1586))/ppf(0.5) plt.text(0.1, 0.85, '$\sigma_E/E = %.3f$' % eres, transform=plt.gca().transAxes) if show: 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 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()
pol_degree_spline = xInterpolatedUnivariateSpline(_phi, _pol_degree, k=1, **fmt) # And, again, this needs to be wrapped into a function. def polarization_angle(E, t, ra, dec): return pol_angle_spline(t) ROI_MODEL = xROIModel(83.633083, 22.014500) crab_ephemeris = xEphemeris(0., 29.8003951530036, -3.73414e-10, 1.18e-20) crab_pulsar = xPeriodicPointSource('Crab pulsar', ROI_MODEL.ra, ROI_MODEL.dec, energy_spectrum, polarization_degree, polarization_angle, crab_ephemeris) ROI_MODEL.add_source(crab_pulsar) if __name__ == '__main__': print(ROI_MODEL) from ximpol.utils.matplotlib_ import pyplot as plt plt.figure() pl_index_spline.plot(show=False) plt.figure() pl_normalization_spline.plot(show=False) plt.figure() pol_angle_spline.plot(show=False) plt.figure() pol_degree_spline.plot(show=False) plt.show()
ebinning = numpy.array([E_MIN, E_MAX]) energy_spectrum = power_law(pl_norm_ref, PL_INDEX) count_spectrum = xCountSpectrum(energy_spectrum, aeff, tsamples) mdp_table = count_spectrum.build_mdp_table(ebinning, modf) mdp_ref = mdp_table.mdp_values()[-1] logger.info("Reference MDP for %s s: %.3f" % (OBS_TIME_REF, mdp_ref)) blazar_list = parse_blazar_list(PRIORITY_ONLY) mirror_list = [1, 3, 9, 17, 18] numpy.random.seed(10) _color = numpy.random.random((3, len(blazar_list))) # numpy.random.seed(1) # _disp = numpy.random.uniform(0.7, 2., len(blazar_list)) plt.figure("Average polarization degree", (11, 8)) _x = numpy.logspace(-13, -7, 100) for obs_time in [1.0e3, 10.0e3, 100.0e3, 1.0e6]: _y = 100.0 * mdp_ref * numpy.sqrt(OBS_TIME_REF / obs_time * FLUX_REF / _x) plt.plot(_x, _y, color=GRID_COLOR, ls="dashed", lw=0.6) _i = 51 if obs_time is 1.0e3: _x_text = _x[_i] _y_text = _y[_i] plt.text(_x_text, _y_text, "$T_{obs} =$ %d ks" % (obs_time / 1000.0), color=GRID_COLOR, rotation=-43.0, size=14) _x_text /= 10 plt.xscale("log") plt.yscale("log") plt.xlabel("Integral energy flux %.0f-%.0f keV [erg cm$^{-2}$ s$^{-1}$]" % (E_MIN, E_MAX)) plt.ylabel("MDP 99% CL [%]")
fmt = dict(xname='Pulsar phase', yname='Polarization angle [rad]') pol_angle_spline = xInterpolatedUnivariateSpline(_phi, _pol_angle, k=1, **fmt) # Build the polarization degree as a function of the phase. _pol_degree = polarization_degree(0,_phi,0,0) fmt = dict(xname='Pulsar phase', yname='Polarization degree') pol_degree_spline = xInterpolatedUnivariateSpline(_phi, _pol_degree, k=1, **fmt) ROI_MODEL = xROIModel(254.457625, 35.3423888889) herx1_ephemeris = xEphemeris(0., 0.8064516129, 0, 0) herx1_pulsar = xPeriodicPointSource('Her X-1', ROI_MODEL.ra, ROI_MODEL.dec, energy_spectrum, polarization_degree, polarization_angle, herx1_ephemeris) ROI_MODEL.add_source(herx1_pulsar) if __name__ == '__main__': print(ROI_MODEL) from ximpol.utils.matplotlib_ import pyplot as plt plt.figure() pl_index_spline.plot(show=False) plt.figure() pl_normalization_spline.plot(show=False) plt.figure() pol_angle_spline.plot(show=False) plt.figure() pol_degree_spline.plot(show=False) plt.show()
import os from ximpol import XIMPOL_DOC_FIGURES from ximpol.irf import load_irfs from ximpol.utils.matplotlib_ import save_current_figure from ximpol.utils.matplotlib_ import pyplot as plt from ximpol.core.spline import xInterpolatedUnivariateSplineLinear IRF_NAME = 'xipe_baseline' OUTPUT_FOLDER = XIMPOL_DOC_FIGURES 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])
energy_spectrum, polarization_degree, polarization_angle, min_validity_time=integral_flux_spline.xmin(), max_validity_time=integral_flux_spline.xmax()) def sampling_time(tstart, tstop): return numpy.logspace(numpy.log10(tstart), numpy.log10(tstop), 100) grb.sampling_time = sampling_time ROI_MODEL.add_source(grb) if __name__ == '__main__': from ximpol.utils.matplotlib_ import pyplot as plt from ximpol.utils.matplotlib_ import save_current_figure from ximpol import XIMPOL_DOC output_folder = os.path.join(XIMPOL_DOC, 'figures', 'showcase') fig = plt.figure() integral_flux_spline.plot(logx=True, logy=True, show=False) if True: save_current_figure('grb130427_swift_input_lc', output_folder, False) fig = plt.figure() pl_normalization_spline.plot(logx=True, logy=True, show=False) fig = plt.figure() pol_degree_spline.plot(logx=True, logy=False, show=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()
IRF_NAME = 'xipe_baseline' T_MIN = 0. T_MAX = 1000. OUTPUT_FOLDER = XIMPOL_DOC_FIGURES aeff, psf, modf, edisp = load_irfs(IRF_NAME) def C(t): return 1. - 0.9*t/(T_MAX - T_MIN) def Gamma(t): return 1.5 + t/(T_MAX - T_MIN) 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)
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()
#put together the flux for the source starting from the txt file _energy, _flux = numpy.loadtxt(FLUX_FILE_PATH, unpack=True) _mask = (_energy >= MIN_ENERGY) * (_energy <= MAX_ENERGY) _energy = _energy[_mask] _flux = _flux[_mask] fmt = dict(xname='Energy', xunits='keV', yname='Flux', yunits='cm$^{-2}$ s$^{-1}$ keV$^{-1}$') _energy_spectrum = xInterpolatedUnivariateSpline(_energy, _flux, **fmt) #""" ROI_MODEL = xROIModel(CYGX1_RA, CYGX1_DEC) src = xPointSource('Cyg-X1', ROI_MODEL.ra, ROI_MODEL.dec, energy_spectrum, polarization_degree, polarization_angle) ROI_MODEL.add_source(src) if __name__ == '__main__': print(ROI_MODEL) from ximpol.utils.matplotlib_ import pyplot as plt fig = plt.figure('Spectrum') _energy_spectrum.plot(show=False) fig = plt.figure('Polarization angle') pol_angle_spline.plot(show=False) fig = plt.figure('Polarization degree') pol_degree_spline.plot(show=False) plt.show()
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import os import numpy from ximpol import XIMPOL_DOC_FIGURES from ximpol.irf import load_irfs from ximpol.utils.matplotlib_ import save_current_figure from ximpol.utils.matplotlib_ import pyplot as plt from ximpol.core.rand import xUnivariateGenerator from ximpol.core.spline import xInterpolatedUnivariateSplineLinear from ximpol.core.spline import xInterpolatedBivariateSplineLinear from ximpol.srcmodel.spectrum import power_law, xCountSpectrum OUTPUT_FOLDER = XIMPOL_DOC_FIGURES _x = numpy.linspace(-5., 5., 100) _y = (1. / numpy.sqrt(2 * numpy.pi)) * numpy.exp(-_x**2 / 2.) pdf = xUnivariateGenerator(_x, _y) print pdf.norm() plt.figure('pdf') pdf.plot(show=False) plt.figure('ppf') pdf.ppf.plot(show=False) print numpy.random.sample(10) plt.show()