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 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_polarization_angle(self, show=True, degree=False, **kwargs): """Plot the polarization angle as a function of energy. """ if self.fit_results == []: self.fit() _x = self.emean _dx = [self.emean - self.emin, self.emax - self.emean] if degree: _y = [numpy.degrees(r.phase) for r in self.fit_results] _dy = [numpy.degrees(r.phase_error) for r in self.fit_results] else: _y = [(r.phase) for r in self.fit_results] _dy = [(r.phase_error) for r in self.fit_results] # If there's more than one energy binning we also fit the entire # energy interval, but we don't want the corresponding data point to # appear in the plot, se we brutally get rid of it. if len(self.fit_results) > 1: _x = _x[:-1] _dx = [_x - self.emin[:-1], self.emax[:-1] - _x] _y = _y[:-1] _dy = _dy[:-1] plt.errorbar(_x, _y, _dy, _dx, fmt='o', **kwargs) plt.xlabel('Energy [keV]') if degree: plt.ylabel('Polarization angle [$^\circ$]') else: plt.ylabel('Polarization angle [rad]') 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_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(self, show=True): """Overloaded plot method. """ 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 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()
def plot(self, show=True, **kwargs): """Overloaded plot method. """ if not kwargs.has_key('fmt'): kwargs['fmt'] = 'o' plt.errorbar(self.phase, self.counts, yerr=self.error, xerr=0.5*self.phase_delta, **kwargs) plt.xlabel('Phase') plt.ylabel('Counts/bin') if show: 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 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 plot_polarization_degree(self, show=True, **kwargs): """Plot the polarization degree as a function of energy. """ if self.fit_results == []: self.fit() _x = self.emean _dx = [self.emean - self.emin, self.emax - self.emean] _y = [r.polarization_degree for r in self.fit_results] _dy = [r.polarization_degree_error for r in self.fit_results] plt.errorbar(_x, _y, _dy, _dx, fmt='o', **kwargs) plt.xlabel('Energy [keV]') plt.ylabel('Polarization degree') if show: plt.show()
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 plot_polarization_angle(self, show=True, degree=True, **kwargs): """Plot the polarization angle as a function of energy. """ if self.fit_results == []: self.fit() _x = self.emean _dx = [self.emean - self.emin, self.emax - self.emean] if degree: _y = [numpy.degrees(r.phase) for r in self.fit_results] _dy = [numpy.degrees(r.phase_error) for r in self.fit_results] else: _y = [(r.phase) for r in self.fit_results] _dy = [(r.phase_error) for r in self.fit_results] plt.errorbar(_x, _y, _dy, _dx, fmt='o', **kwargs) plt.xlabel('Energy [keV]') plt.ylabel('Polarization angle [$^\circ$]') 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 plot(self, num_pointsx=100, num_pointsy=100, num_contours=75, logz=False, show=True): """Plot the spline. Args ---- num_pointsx : int The number of x sampling points to be used to draw the spline. num_pointsy : int The number of y sampling points to be used to draw the spline. num_contours : int The number of contours for the color plot. show : bool, optional If True, `plt.show()` is called at the end, interrupting the flow. """ from ximpol.utils.matplotlib_ import pyplot as plt _x = numpy.linspace(self.xmin(), self.xmax(), num_pointsx) _y = numpy.linspace(self.ymin(), self.ymax(), num_pointsy) _x, _y = numpy.meshgrid(_x, _y) _z = self(_x, _y, grid=False) if logz: from matplotlib.colors import LogNorm _levels = numpy.logspace(-4, numpy.log10(_z.max()), num_contours) contour = plt.contourf(_x, _y, _z, levels=_levels, norm=LogNorm()) else: contour = plt.contourf(_x, _y, _z, num_contours) bar = plt.colorbar() if self.xname is not None: plt.xlabel(self.xlabel()) if self.yname is not None: plt.ylabel(self.ylabel()) if self.zname is not None: bar.set_label(self.zlabel()) 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_bin(self, i, show=True, fit=True): """Plot the azimuthal distribution for the i-th energy slice. """ _emin = self.emin[i] _emax = self.emax[i] _emean = self.emean[i] label = '%.2f-%.2f $<$%.2f$>$ keV' % (_emin, _emax, _emean) plt.errorbar(self.phi_x, self.phi_y[i], yerr=numpy.sqrt(self.phi_y[i]), fmt='o') if fit: fit_results = self.fit_bin(i) fit_results.plot(label=label) plt.axis([0., 2*numpy.pi, 0.0, 1.2*self.phi_y[i].max()]) plt.xlabel('Azimuthal angle [rad]') plt.ylabel('Counts/bin') plt.text(0.02, 0.92, label, transform=plt.gca().transAxes, fontsize=15) if show: plt.show()
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 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 plot(self, num_pointsx=100, num_pointsy=100, num_contours=75, logz=False, show=True): """Plot the spline. Args ---- num_pointsx : int The number of x sampling points to be used to draw the spline. num_pointsy : int The number of y sampling points to be used to draw the spline. num_contours : int The number of contours for the color plot. show : bool, optional If True, `plt.show()` is called at the end, interrupting the flow. """ from ximpol.utils.matplotlib_ import pyplot as plt _x = numpy.linspace(self.xmin(), self.xmax(), num_pointsx) _y = numpy.linspace(self.ymin(), self.ymax(), num_pointsy) _x, _y = numpy.meshgrid(_x, _y) _z = self(_x, _y, grid=False) if logz: from matplotlib.colors import LogNorm _levels = numpy.logspace(-4, numpy.log10(_z.max()), num_contours) contour = plt.contourf(_x, _y, _z, levels=_levels, norm = LogNorm()) else: contour = plt.contourf(_x, _y, _z, num_contours) bar = plt.colorbar() if self.xname is not None: plt.xlabel(self.xlabel()) if self.yname is not None: plt.ylabel(self.ylabel()) if self.zname is not None: bar.set_label(self.zlabel()) if show: plt.show()
def makeMDP_fE_ComparisonPlot(file_path): scale_factor = 10. (_phase_ave, _phase_err, _energy_mean, pulsar_e_err, pulsar_e_err, mdp) =\ numpy.loadtxt(file_path, unpack=True) print "Phase ave:",_phase_ave print print "Energy mean", _energy_mean #phase_values = [0.025, 0.15, 0.35, 0.675, 0.95] phase_values = [0.35,0.675] on, on_phase_color = (0.35,'r') off, off_phase_color = (0.675,'gray') #for phase in phase_values: plt.errorbar(_energy_mean[_phase_ave==on], 100*mdp[_phase_ave==on]*(1/numpy.sqrt(scale_factor)),xerr=pulsar_e_err[_phase_ave==on], label='On Phase',fmt='o',markersize=6,ls='--',color=on_phase_color) plt.errorbar(_energy_mean[_phase_ave==off], 100*mdp[_phase_ave==off]*(1/numpy.sqrt(scale_factor)),xerr=pulsar_e_err[_phase_ave==off], label='Off Phase',fmt='o',markersize=6,ls='--',color=off_phase_color) plt.legend() plt.ylabel('MPD 99\%') plt.xlabel('Energy (keV)') plt.savefig('crab_complex_mdp_imaging_fE_%i.png'%(SIM_DURATION*scale_factor/1000.)) plt.show()
def plot_bin(self, i, show=True, fit=True): """Plot the azimuthal distribution for the i-th energy slice. """ _emin = self.emin[i] _emax = self.emax[i] _emean = self.emean[i] label = '%.2f-%.2f $<$%.2f$>$ keV' % (_emin, _emax, _emean) plt.errorbar(self.phi_x, self.phi_y[i], yerr=numpy.sqrt(self.phi_y[i]), fmt='o') if fit: fit_results = self.fit_bin(i) fit_results.plot(label=label) view_range = 1.5 * (self.phi_y[i].max() - self.phi_y[i].min()) view_ymin = self.phi_y[i].min() - view_range view_ymax = self.phi_y[i].max() + view_range plt.axis([0., 2 * numpy.pi, view_ymin, view_ymax]) plt.xlabel('Azimuthal angle [rad]') plt.ylabel('Counts/bin') plt.text(0.02, 0.92, label, transform=plt.gca().transAxes, fontsize=15) 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 %s corona'%model_type, show=False) plt.figtext(0.2, 0.85,'XIPE %s ks'%(SIM_DURATION/1000.),size=18) #plt.errorbar(_energy_mean, _pol_deg, yerr=_pol_deg_err, color='blue',marker='o') plt.legend() plt.figure('Polarization angle') _mcube.plot_polarization_angle(show=False, color='blue', degree=False) pol_angle_spline.plot(color='lightgray',label='Model %s corona'%model_type, show=False) plt.figtext(0.2, 0.85,'XIPE %s ks'%(SIM_DURATION/1000.),size=18) #plt.errorbar(_energy_mean,_pol_angle, yerr= _pol_angle_err,color='blue',marker='o') plt.legend() plt.figure('MDP %s'%base_name) mdp = _mcube.mdp99 emean = _mcube.emean emin = _mcube.emin emax = _mcube.emax width = (emax-emin)/2. plt.errorbar(emean,mdp,xerr=width, label='MDP99',marker='o',linestyle='--') plt.figtext(0.2, 0.85,'XIPE %s ks'%(SIM_DURATION/1000.),size=18) plt.xlim([1,10]) plt.ylabel('MPD 99 %') plt.xlabel('Energy (keV)') #plt.legend() plt.show()
def plot(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()
# _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") plt.axis([1e-13, 1e-8, 0.5, 50])
r in mod_cube.fit_results]) for i in range(0, len(mod_cube.emax)): cnts = mod_cube.counts[i] logger.info('%.2f--%.2f keV: %d counts in %d s, mu %.3f, MDP %.2f%%' %\ (mod_cube.emin[i], mod_cube.emax[i], mod_cube.counts[i], TIME, mod_cube.effective_mu[i], 100*mod_cube.mdp99[i])) logger.info('Done.') pol_deg = numpy.mean(pol_degree_array, axis=0) pol_deg_err = numpy.mean(pol_degree_error_array, axis=0) pol_ang = numpy.mean(pol_angle_array, axis=0) pol_ang_err = numpy.mean(pol_angle_error_array, axis=0) fig = plt.figure('Polarization degree') plt.xlabel('Energy [keV]') plt.ylabel('Polarization degree') bad = pol_deg < 3*pol_deg_err good = numpy.invert(bad) bad[len(E_BINNING)-1] = False good[len(E_BINNING)-1] = False _dx = numpy.array([mod_cube.emean - mod_cube.emin, mod_cube.emax - mod_cube.emean]) if bad.sum() > 0: plt.errorbar(mod_cube.emean[bad], pol_deg[bad], pol_deg_err[bad], _dx.T[bad].T, fmt='o', label='Data', color='gray') if good.sum() > 0: plt.errorbar(mod_cube.emean[good], pol_deg[good], pol_deg_err[good], _dx.T[good].T, fmt='o', label='Data', color='blue') pol_degree.plot(show=False, label='Model', linestyle='dashed', color='green') plt.legend(bbox_to_anchor=(0.30, 0.95)) plt.axis([1, 10, 0, 0.1])
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()