def main(): """ """ import os from ximpol import XIMPOL_IRF from ximpol.utils.matplotlib_ import pyplot as plt file_path = os.path.join(XIMPOL_IRF,'fits','xipe_baseline.psf') psf = xPointSpreadFunction(file_path) print(psf.rvs(10)) ra, dec = 1., 1. print(psf.smear_single(ra, dec, 10)) rmax = 50 plt.hist(psf.rvs(100000), rmax, (0, rmax), rwidth=1, histtype='step', lw=2, normed=True) _r = numpy.linspace(0, rmax, rmax) _psf = psf(_r)/psf.norm() plt.plot(_r, _psf) plt.show()
def test_rvs(self, num_events=100000): """ """ mc_energy = 10. _ppf = self.edisp.matrix.vppf.vslice(mc_energy) _e = numpy.full(num_events, mc_energy) _slice = self.edisp.matrix.slice(mc_energy) _ch = self.edisp.matrix.rvs(_e) n, bins, patches = plt.hist(_ch, bins=numpy.linspace(0, 255, 256), histtype='step') bin_width = (bins[1] - bins[0]) scale = n.sum()*bin_width/_slice.norm() plt.plot(_slice.x, scale*_slice.y)
def test_rvs(self): """Test the random number generation. """ visibility = numpy.full(1000000, 0.5) phi = self.generator.rvs_phi(visibility, 0.25*numpy.pi) hist = plt.hist(phi, bins=numpy.linspace(0, 2*numpy.pi, 100), histtype='step', label='Random angles') fit_results = self.generator.fit_histogram(hist) fit_results.plot() plt.xlabel('$\\phi$ [rad]') plt.axis([0, 2*numpy.pi, 0, None]) overlay_tag() save_current_figure('test_azimuthal_resp_rvs.png', show=self.interactive)
def main(): """ """ import os from ximpol import XIMPOL_IRF from ximpol.utils.matplotlib_ import pyplot as plt file_path = os.path.join(XIMPOL_IRF, 'fits', 'xipe_baseline.psf') psf = xPointSpreadFunction(file_path) print(psf.rvs(10)) ra, dec = 1., 1. print(psf.smear_single(ra, dec, 10)) rmax = 50 plt.hist(psf.rvs(100000), rmax, (0, rmax), rwidth=1, histtype='step', lw=2, normed=True) _r = numpy.linspace(0, rmax, rmax) _psf = psf(_r) / psf.norm() plt.plot(_r, _psf) plt.show()
def test_rvs(self, num_events=100000): """ """ mc_energy = 10. _ppf = self.edisp.matrix.vppf.vslice(mc_energy) _e = numpy.full(num_events, mc_energy) _slice = self.edisp.matrix.slice(mc_energy) _ch = self.edisp.matrix.rvs(_e) n, bins, patches = plt.hist(_ch, bins=numpy.linspace(0, 255, 256), histtype='step') bin_width = (bins[1] - bins[0]) scale = n.sum() * bin_width / _slice.norm() plt.plot(_slice.x, scale * _slice.y)
def test_constant(self, num_events=1000000, polarization_degree=1., polarization_angle=numpy.radians(20.)): """Test the modulation factor as a random number generator when both the polarization angle and degrees are energy- and time-independent. """ poldegree = numpy.full(num_events, polarization_degree) polangle = numpy.full(num_events, polarization_angle) self.modf.generator.plot(show=False) save_current_figure('test_modulation_constant_generator.png', show=self.interactive) emin = self.modf.xmin() emax = self.modf.xmax() energy = numpy.random.uniform(emin, emax, num_events) phi = self.modf.rvs_phi(energy, poldegree, polangle) ebinning = numpy.linspace(emin, emax, 10) phi_binning = numpy.linspace(0, 2*numpy.pi, 100) fit_results = [] for i, (_emin, _emax) in enumerate(zip(ebinning[:-1], ebinning[1:])): _emean = 0.5*(_emin + _emax) _mask = (energy > _emin)*(energy < _emax) _phi = phi[_mask] _hist = plt.hist(_phi, bins=phi_binning, histtype='step') _fr = xAzimuthalResponseGenerator.fit_histogram(_hist) _fr.emean = _emean fit_results.append(_fr) _fr.plot(label='Energy: %.2f--%.2f keV' % (_emin, _emax)) plt.axis([0., 2*numpy.pi, 0., 1.2*_hist[0].max()]) overlay_tag() save_current_figure('test_modulation_constant_fit_slice%d.png' % i, show=self.interactive) _x = [_fr.emean for _fr in fit_results] _y = [_fr.phase for _fr in fit_results] _dy = [_fr.phase_error for _fr in fit_results] plt.errorbar(_x, _y, yerr=_dy, fmt='o') plt.plot(_x, numpy.array([polarization_angle]*len(_x))) plt.xlabel('Energy [keV]') plt.ylabel('Modulation angle [$^\circ$]') save_current_figure('test_modulation_constant_angle.png', show=self.interactive) _y = [_fr.visibility for _fr in fit_results] _dy = [_fr.visibility_error for _fr in fit_results] plt.errorbar(_x, _y, yerr=_dy, fmt='o') plt.axis([emin, emax, 0, 1]) self.modf.plot(show=False) plt.xlabel('Energy [keV]') plt.ylabel('Modulation visibility') save_current_figure('test_modulation_constant_visibility.png', show=self.interactive)
def test_rvs(self): """Test the random number generation. """ visibility = numpy.full(1000000, 0.5) phi = self.generator.rvs_phi(visibility, 0.25 * numpy.pi) hist = plt.hist(phi, bins=numpy.linspace(0, 2 * numpy.pi, 100), histtype='step', label='Random angles') fit_results = self.generator.fit_histogram(hist) fit_results.plot() plt.xlabel('$\\phi$ [rad]') plt.axis([0, 2 * numpy.pi, 0, None]) overlay_tag() save_current_figure('test_azimuthal_resp_rvs.png', show=self.interactive)
def test_simplest(self, size=100000, phase=0.): """ """ modf = 1. energy = numpy.random.uniform(self.emin, self.emax, size) visibility = modf*self.polarization_degree(energy) phi = self.generator.rvs_phi(visibility, phase) binning = numpy.linspace(0, 2*numpy.pi, 100) hist = plt.hist(phi, bins=binning) fit_results = self.generator.fit_histogram(hist) fit_results.set_polarization(modf) fit_degree = fit_results.polarization_degree mean_energy = numpy.mean(energy) exp_degree = self.polarization_degree(mean_energy) delta = abs(fit_degree - exp_degree)/exp_degree msg = 'delta = %.3f' % delta self.assertTrue(delta < 0.05, msg)
def test_uniform(self, size=100000, phase=0.): """ """ energy = numpy.random.uniform(self.emin, self.emax, size) visibility = self.modf(energy)*self.polarization_degree(energy) phi = self.generator.rvs_phi(visibility, phase) binning = numpy.linspace(0, 2*numpy.pi, 100) hist = plt.hist(phi, bins=binning) fit_results = self.generator.fit_histogram(hist) mean_energy = numpy.mean(energy) mu_effective = self.modf.weighted_average(energy) fit_results.set_polarization(mu_effective) fit_degree = fit_results.polarization_degree exp_degree = (self.polarization_degree(energy)*self.modf(energy))\ .sum()/self.modf(energy).sum() delta = abs(fit_degree - exp_degree)/exp_degree msg = 'delta = %.3f' % delta self.assertTrue(delta < 0.05, msg)
def test_power_law(self, size=1000000, phase=0., index=2.): """ """ _x = numpy.linspace(self.emin, self.emax, 100) _y = _x**(-index) generator = xUnivariateGenerator(_x, _y) energy = generator.rvs(size) visibility = self.modf(energy)*self.polarization_degree(energy) phi = self.generator.rvs_phi(visibility, phase) binning = numpy.linspace(0, 2*numpy.pi, 100) hist = plt.hist(phi, bins=binning) fit_results = self.generator.fit_histogram(hist) mean_energy = numpy.mean(energy) mu_effective = self.modf.weighted_average(energy) fit_results.set_polarization(mu_effective) fit_degree = fit_results.polarization_degree exp_degree = (self.polarization_degree(energy)*self.modf(energy))\ .sum()/self.modf(energy).sum() delta = abs(fit_degree - exp_degree)/exp_degree msg = 'delta = %.3f' % delta self.assertTrue(delta < 0.05, msg)
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 main(): """Produce some plots """ # If all_mdp = True, produces: # 1) the plot of the MDP for all the Swift GRBs # and a given repointing time # 2) the plot of the correlation between MDP for all the Swift # GRBs and a given repointing time and the integral prompt # (first 10 min) flux all_mdp = True if all_mdp == True: grb_list = get_all_swift_grb_names() t_rep = 21600 t_obs = 100000 promt_time = 600 mdp_list1,mdp_list2, flux_list, t0_list = [], [], [], [] c, good_grb = [], [] for grb in grb_list: mdp = get_grb_mdp(grb,repointing=t_rep,obs_time=t_obs) flux, t0 = get_integral_flux(grb,delta_t=promt_time) if mdp is not None and flux is not None: mdp_list1.append(mdp*100) if t0 < 350: if mdp*100 <= 15: c.append('red') else: c.append('blue') mdp_list2.append(mdp*100) flux_list.append(flux) t0_list.append(t0) else: continue _mdp1 = numpy.array(mdp_list1) _mdp2 = numpy.array(mdp_list2) _flux = numpy.array(flux_list) _t0 = numpy.array(t0_list) # 1)------------------------------------------------------ histo = plt.figure(figsize=(10, 6), dpi=80) bins = numpy.linspace(0, 100, 100) plt.title('%i GRBs, $\Delta t_{obs}=%i s,$ $t_{repoint}=%i s$'\ %(len(_mdp1),t_obs,t_rep)) plt.hist(_mdp1, bins, alpha=0.5) plt.xlabel('2.-10. keV MDP (%)') plt.ylabel('Number of GRBs') overlay_tag() save_current_figure('all_grbs_MDP_histo', clear=False) plt.show() # 1.1)---------------------------------------------------- histo = plt.figure(figsize=(10, 6), dpi=80) bins = numpy.linspace(0, 100, 100) plt.title('%i GRBs, $\Delta t_{obs}=%i s,$ $t_{repoint}=%i s$'\ %(len(_mdp1),t_obs,t_rep)) (n, bins, patches) = plt.hist(_mdp1, bins, histtype='step', cumulative=True) plt.xlabel('2.-10. keV MDP (%)') plt.ylabel('Cumulative number of GRBs') for i in range(0,len(bins)): print 'MDP %.2f%%: %i GRBs'%(i,n[i]) overlay_tag() save_current_figure('all_grbs_MDP_cumulative', clear=False) plt.show() # 2)------------------------------------------------------ plt.figure(figsize=(10, 6), dpi=80) ax = plt.gca() plt.scatter(_mdp2, _flux, s=30, marker='.', color=c) plt.xlabel('2.-10. keV MDP (%)') plt.ylabel('[keV$^{-1}$ cm$^{-2}$]') plt.title('$\Delta t_{obs}=%i s,$ $t_{repoint}=%i s$'%(t_obs,t_rep)) plt.xlim(1, 100) ax.set_yscale('log') ax.set_xscale('log') overlay_tag() save_current_figure('grb_MDP_prompt',clear=False) plt.show() # If mdp_vs_time = True Produces: # 1) the plot of the MDP for a given GRB # as a function of the repointing time # 2) the plot of the MDP for a given GRB # as a function of the observation duration mdp_vs_time = False color_list = [] if mdp_vs_time == True: grb_list = ['GRB 060729', 'GRB 080411', 'GRB 091127', 'GRB 111209A',\ 'GRB 120711A', 'GRB 130427A', 'GRB 130505A', 'GRB 130907A',\ 'GRB 150403A'] #1)------------------------------------------------------ plt.figure(figsize=(10, 6), dpi=80) ax = plt.gca() for grb in grb_list: c = [random.uniform(0,1),random.uniform(0,1),random.uniform(0,1)] color_list.append(c) repointing_time = numpy.logspace(2,4.8,30) plot_grb_mdp_vs_repoint(grb,repointing_time,show=False,color=c) ax.legend(loc='upper left', shadow=False, fontsize='small') plt.plot([21600, 21600], [0, 30], 'k--', lw=1, color='green') plt.plot([43200, 43200], [0, 30], 'k--', lw=1,color='green') ax.set_yscale('log') ax.set_xscale('log') overlay_tag() save_current_figure('grb_MDP_vs_repoint',clear=False) plt.show() #2)------------------------------------------------------ plt.figure(figsize=(10, 6), dpi=80) ax = plt.gca() for i,grb in enumerate(grb_list): obs_time = numpy.logspace(3,5,30) plot_grb_mdp_vs_obstime(grb,obs_time,show=False,color=color_list[i]) ax.legend(loc='upper right', shadow=False, fontsize='small') plt.plot([50000, 50000], [0, 50], 'k--', lw=1, color='green') ax.set_yscale('log') ax.set_xscale('log') overlay_tag(x=0.5) save_current_figure('grb_MDP_vs_obstime',clear=False) plt.show()
def main(): """Produce some plots """ # If process_grb_mdp = True, produces a fits file with all the # main infos on each grb if process_grb_mdp == True: data = process_grb_list(duration=50000.) build_grb_fits_file(data,OUTFILE) # 1) the plot of the MDP for all the Swift GRBs # and a given repointing time # 2) the cumulative of the previous histogram # 3) the plot of the correlation between MDP for all the Swift # GRBs and a given repointing time and the integral prompt # (first 10 min) flux # 1)------------------------------------------------------ plt.figure(figsize=(10, 6), dpi=80) bins = numpy.linspace(0, 100, 100) hdulist = fits.open(OUTFILE) grbdata = hdulist[1].data _mdp = grbdata['MDP 99%'] t_obs = '50000' t_rep = '21600' plt.title('%i GRBs, $\Delta t_{obs}=%s s,$ $t_{repoint}=%s s$'\ %(len(_mdp),t_obs,t_rep)) plt.hist(_mdp*100, bins, alpha=0.5) plt.xlabel('2.-10. keV MDP (%)') plt.ylabel('Number of GRBs') overlay_tag() save_current_figure('all_grbs_MDP_histo', clear=False) # 2)---------------------------------------------------- plt.figure(figsize=(10, 6), dpi=80) plt.title('%i GRBs, $\Delta t_{obs}=%s s,$ $t_{repoint}=%s s$'\ %(len(_mdp),t_obs,t_rep)) (n, bins, patches) = plt.hist(_mdp*100, bins, histtype='step', \ cumulative=True) plt.xlabel('2.-10. keV MDP (%)') plt.ylabel('Cumulative number of GRBs') for i in range(0,30): print 'MDP %.2f%%: %i GRBs'%(i,n[i]) overlay_tag() save_current_figure('all_grbs_MDP_cumulative', clear=False) # 3)------------------------------------------------------ plt.figure(figsize=(10, 6), dpi=80) ax = plt.gca() _prompt_tstart = grbdata['PROMPT_START'] _flux = grbdata['PROMPT_FLUX'] _good_indexes = numpy.where(_prompt_tstart>350) _flux = numpy.delete(_flux,_good_indexes) _mdp = numpy.delete(_mdp,_good_indexes) plt.scatter(_mdp*100, _flux, s=30, marker='.', color='blue') plt.xlabel('2.-10. keV MDP (%)') plt.ylabel('[erg $\cdot$ cm$^{-2}$]') plt.title('%i GRBs, $\Delta t_{obs}=%s s,$ $t_{repoint}=%s s$'%(len(_flux),\ t_obs,t_rep)) plt.xlim(1, 100) plt.ylim(1e-9,1e-4) plt.plot([20, 20], [1e-9,1e-4], 'k--', lw=1, color='green') ax.set_yscale('log') ax.set_xscale('log') overlay_tag() save_current_figure('grb_MDP_prompt',clear=False) plt.show() # If mdp_vs_time = True Produces: # 1) the plot of the MDP for a given GRB # as a function of the repointing time # 2) the plot of the MDP for a given GRB # as a function of the observation duration color_list = ['red','salmon','goldenrod','darkgreen','limegreen',\ 'royalblue','mediumpurple','darkviolet','deeppink']\ #'yellow','darkcyan'] if mdp_vs_time == True: grb_list = ['GRB 060729', 'GRB 080411', 'GRB 091127', 'GRB 111209A',\ 'GRB 120711A', 'GRB 130427A', 'GRB 130505A', 'GRB 130907A',\ 'GRB 150403A'] #1)------------------------------------------------------ plt.figure(figsize=(10, 6), dpi=80) ax = plt.gca() for i,grb in enumerate(grb_list): repointing_time = numpy.logspace(2,4.8,20) plot_grb_mdp_vs_repoint(grb,repointing_time,show=False,\ color=color_list[i]) ax.legend(loc='upper left', shadow=False, fontsize='small') #plt.ylim(0,100) plt.plot([21600, 21600], [0, 100], 'k--', lw=1, color='green') plt.plot([43200, 43200], [0, 100], 'k--', lw=1,color='green') ax.set_yscale('log') ax.set_xscale('log') overlay_tag() save_current_figure('grb_MDP_vs_repoint',clear=False) #2)------------------------------------------------------ plt.figure(figsize=(10, 6), dpi=80) ax = plt.gca() for i,grb in enumerate(grb_list): obs_time = numpy.logspace(3,5,30) plot_grb_mdp_vs_obstime(grb,obs_time,show=False,color=color_list[i]) ax.legend(loc='upper right', shadow=False, fontsize='small') ax.set_yscale('log') ax.set_xscale('log') overlay_tag(x=0.5) save_current_figure('grb_MDP_vs_obstime',clear=False) plt.show()