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 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_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 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=False, stat=True, text_size=15, **options): """Plot the fit results. """ from ximpol.utils.matplotlib_ import pyplot as plt _x = numpy.linspace(0., 2*numpy.pi, 100) _y = xAzimuthalResponseGenerator.fit_function(_x, *self.popt) plt.plot(_x, _y, **options) if stat: posh = 0.02 posv = 0.25 delv = 0.07 for text in self.latex().split(','): text = text.strip() plt.text(posh, posv, text, transform=plt.gca().transAxes, fontsize=text_size) posv -= delv 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(self, num_points=1000, overlay=False, logx=False, logy=False, scale=1., offset=0., show=True, **kwargs): """Plot the spline. Args ---- num_points : int, optional The number of sampling points to be used to draw the spline. overlay : bool, optional If True, the original arrays passed to the spline are overlaid. show : bool, optional If True, `plt.show()` is called at the end, interrupting the flow. """ from ximpol.utils.matplotlib_ import pyplot as plt if not logx: _x = numpy.linspace(self.xmin(), self.xmax(), num_points) else: _x = numpy.logspace(numpy.log10(self.xmin()), numpy.log10(self.xmax()), num_points) _y = scale * self(_x) + offset if overlay: plt.plot(_x, _y, '-', self.x, self.y, 'o', **kwargs) else: plt.plot(_x, _y, '-', **kwargs) if self.xname is not None: plt.xlabel(self.xlabel()) if self.yname is not None: plt.ylabel(self.ylabel()) if logx: plt.gca().set_xscale('log') if logy: plt.gca().set_yscale('log') if show: plt.show()
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_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_grb_mdp_vs_obstime(grb_name, _t_obs, t_repoint=21600, \ color='black', show=True): """Plot all the MDP (changing the repointing elapsed time defined in *arg) for a given GRB. """ mdp_list = [] for obs in _t_obs: mdp = get_grb_mdp(grb_name,repointing=t_repoint,obs_time=obs) if mdp is not None: mdp_list.append(mdp) else: mdp_list.append(0.) _mdp = numpy.array(mdp_list)*100 plt.plot(_t_obs,_mdp, marker='.',linestyle='-', lw=0.5, color=color,\ label=grb_name) plt.xlabel('$\Delta t_{obs}$ [s]') plt.ylabel('2.-10. keV MDP (%)') plt.title('MDP vs $\Delta t_{obs}$, $ t_{repoint} =$ %i s'\ %(t_repoint)) if show: plt.show() return _mdp, _t_obs
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 plot_grb_mdp_vs_repoint(grb_name, _t_repoint, t_obs=50000, \ color='black', show=True): """Plot all the MDP (changing the repointing elapsed time defined in *arg) for a given GRB. """ mdp_list = [] for repoint in _t_repoint: mdp = process_grb(grb_name,tstart=repoint,duration=t_obs)[-1] if mdp is not None: mdp_list.append(mdp) else: mdp_list.append(0.) _mdp = numpy.array(mdp_list)*100 plt.plot(_t_repoint, _mdp, marker='.',linestyle='-', lw=0.5, color=color,\ label=grb_name) plt.xlabel('$t_{repoint}$ [s]') plt.ylabel('2.-10. keV MDP (%)') plt.title('MDP vs $t_{repoint}$, $\Delta t_{obs} =$ %i s'\ %(t_obs)) if show: plt.show() return _mdp, _t_repoint
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 plot(self, num_points=1000, overlay=False, logx=False, logy=False, scale=1., offset=0., show=True, **kwargs): """Plot the spline. Args ---- num_points : int, optional The number of sampling points to be used to draw the spline. overlay : bool, optional If True, the original arrays passed to the spline are overlaid. show : bool, optional If True, `plt.show()` is called at the end, interrupting the flow. """ from ximpol.utils.matplotlib_ import pyplot as plt if not logx: _x = numpy.linspace(self.xmin(), self.xmax(), num_points) else: _x = numpy.logspace(numpy.log10(self.xmin()), numpy.log10(self.xmax()), num_points) _y = scale*self(_x) + offset if overlay: plt.plot(_x, _y, '-', self.x, self.y, 'o', **kwargs) else: plt.plot(_x, _y, '-', **kwargs) if self.xname is not None: plt.xlabel(self.xlabel()) if self.yname is not None: plt.ylabel(self.ylabel()) if logx: plt.gca().set_xscale('log') if logy: plt.gca().set_yscale('log') if show: plt.show()
mdp_ref = mdp_table.mdp_values()[-1] logger.info('Reference MDP for %s s: %.3f' % (OBS_TIME_REF, mdp_ref)) obs_plan_list = parse_obs_plan_list(PRIORITY_ONLY) mirror_list = [5, 6, 7, 8] 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 '':
if __name__ == '__main__': plt.figure() energy_spectrum_spline.plot(show=False) plt.figure() 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')
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 [%]") for j, blazar in enumerate(blazar_list): _x_max = blazar["flux_max"] _x_min = blazar["flux_min"] _y_max = blazar["p_opt_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) plt.figure('Light curve') count_spectrum.light_curve.plot(show=False) save_current_figure('light_curve.png', OUTPUT_FOLDER, clear=False) plt.figure('Light curve times') count_spectrum.light_curve.plot(show=False) for t in count_spectrum.light_curve.rvs(100): plt.plot([t, t], [0, 20], color='gray', linestyle='-', linewidth=2) save_current_figure('light_curve_random.png', OUTPUT_FOLDER, clear=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 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()
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 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) _pol_angle = numpy.degrees(_pol_angle) _pol_angle_err = numpy.degrees(_pol_angle_err) _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') _x = numpy.linspace(0, 1, 100) _y = polarization_degree(2.38, _x, 0, 0) plt.plot(_x, _y) plt.axis([0., 1., 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('J1708_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.)) _x = numpy.linspace(0, 1, 100) _y = numpy.degrees(polarization_angle(2.56, _x, 0, 0)) plt.plot(_x, _y) plt.axis([0., 1., 0, 180]) plt.xlabel('Rotational phase') plt.ylabel('Polarization angle [$^\\circ$]') 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('J1708_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') #print phasogram.counts 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('J1708_per_phasogram_%d.png' % i) plt.show()
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()