def plot(self, show=True): """Overloaded plot method. """ 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 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()
# 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 [%]") for j, blazar in enumerate(blazar_list): _x_max = blazar["flux_max"] _x_min = blazar["flux_min"] _y_max = blazar["p_opt_max"] _y_min = blazar["p_opt_min"] plt.plot([_x_min, _x_max, _x_max], [_y_max, _y_max, _y_min], color=_color[:, j], lw=1.5) _x_text = numpy.sqrt((_x_max) * (_x_min)) if j in mirror_list: _y_text = 0.88 * _y_max else: _y_text = 1.02 * _y_max plt.text(_x_text, _y_text, blazar["name"], color=_color[:, j], horizontalalignment="center", size="large")
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 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_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)
numpy.random.seed(1) _color = numpy.random.random((3, len(obs_plan_list))) numpy.random.seed(17) _disp = numpy.random.uniform(0.9, 1.4, len(obs_plan_list)) plt.figure('Average polarization degree', (14, 10)) _x = numpy.logspace(-13, -7, 100) for obs_time in [1.e3, 10.e3, 100.e3, 1.e6]: _y = 100.* mdp_ref * numpy.sqrt(OBS_TIME_REF/obs_time * FLUX_REF/_x) plt.plot(_x, _y, color=GRID_COLOR, ls='dashed', lw=0.5) _i = 53 plt.text(_x[_i], _y[_i], '$T_{obs} =$ %d ks' % (obs_time/1000.), color=GRID_COLOR, rotation=-45.) 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 [%]') for j, source in enumerate(obs_plan_list): _x = source['flux'] _y = source['mdp']*_disp[j] plt.plot(_x, _y, 'o', color=_color[:,j]) _text = source['name'] if source['notes'] is not '': _text += '\n' + source['notes'] if j in mirror_list: _y *= 0.8 else: _y *= 1.05
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()