def fillLivetime(self, ltc, src_type): self._tau = Histogram(self._cth_axis) if src_type == 'iso': self._tau += self._cth_axis.width elif src_type == 'isodec': sinlat = np.linspace(-1, 1, 48) m = ltc._ltmap[:, i] self._tau[i] = 0 for s in sinlat: lat = np.arcsin(s) th = np.pi / 2. - lat ipix = healpy.ang2pix(64, th, 0, nest=True) self._tau[i] += m[ipix] else: if not isinstance(src_type, list): src_type = [src_type] for s in src_type: cat = Catalog.get() src = cat.get_source_by_name(s) lonlat = (src['RAJ2000'], src['DEJ2000']) self._tau += ltc.get_src_lthist(lonlat[0], lonlat[1], cth_axis=self._cth_axis)
def loadsrclist(self, fname): self.srcs = [] self.src_names = [] self.src_redshifts = [] self.src_ra_deg = [] self.src_dec_deg = [] self.src_radec = [] # if not fname is None: # src_names = np.genfromtxt(fname,unpack=True,dtype=None) # else: # src_names = np.array(srcs.split(',')) if isinstance(fname, list): src_names = np.array(fname) if src_names.ndim == 0: src_names = src_names.reshape(1) cat = Catalog.get() for name in src_names: src = cat.get_source_by_name(name) name = src['Source_Name'] ra = src['RAJ2000'] dec = src['DEJ2000'] # self._photon_data._srcs.append(src) self.src_names.append(name) self.src_ra_deg.append(ra) self.src_dec_deg.append(dec) self.src_radec.append((np.radians(ra), np.radians(dec)))
def fillLivetime(self,ltc,src_type): self._tau = Histogram(self._cth_axis) if src_type == 'iso': self._tau += self._cth_axis.width elif src_type == 'isodec': sinlat = np.linspace(-1,1,48) m = ltc._ltmap[:,i] self._tau[i] = 0 for s in sinlat: lat = np.arcsin(s) th = np.pi/2. - lat ipix = healpy.ang2pix(64,th,0,nest=True) self._tau[i] += m[ipix] else: if not isinstance(src_type,list): src_type = [src_type] for s in src_type: cat = Catalog.get() src = cat.get_source_by_name(s) lonlat = (src['RAJ2000'], src['DEJ2000']) self._tau += ltc.get_src_lthist(lonlat[0], lonlat[1], cth_axis=self._cth_axis)
def loadsrclist(self,fname): self.srcs = [] self.src_names = [] self.src_redshifts = [] self.src_ra_deg = [] self.src_dec_deg = [] self.src_radec = [] # if not fname is None: # src_names = np.genfromtxt(fname,unpack=True,dtype=None) # else: # src_names = np.array(srcs.split(',')) if isinstance(fname,list): src_names = np.array(fname) if src_names.ndim == 0: src_names = src_names.reshape(1) cat = Catalog.get() for name in src_names: src = cat.get_source_by_name(name) name = src['Source_Name'] ra = src['RAJ2000'] dec = src['DEJ2000'] # self._photon_data._srcs.append(src) self.src_names.append(name) self.src_ra_deg.append(ra) self.src_dec_deg.append(dec) self.src_radec.append((np.radians(ra),np.radians(dec)))
def update_image(self): self.scf() bin_range = [self.slice,self.slice+self.nbin] self._cm = [] for im in self._im: if isinstance(im,SkyCube): self._cm.append(im.marginalize(2,bin_range=bin_range)) else: self._cm.append(im) for i in range(len(self._cm)): if self.smooth: self._cm[i] = self._cm[i].smooth(0.1) if len(self._cm) == 0: return cm = self._cm cat = Catalog.get('3fgl') if len(self._axim) == 0: axim = cm[0].plot(**self._style[0]) cat.plot(cm[0],src_color='w') self._axim.append(axim) self._ax = plt.gca() plt.colorbar(axim,orientation='horizontal',shrink=0.7,pad=0.15, fraction=0.05) return self._axim[0].set_data(cm[0].counts.T) self._axim[0].autoscale() if self._style[0]['logz']: self._axim[0].set_norm(LogNorm()) else: self._axim[0].set_norm(Normalize()) self.canvas.draw()
def __init__(self, irf, nbin=600, ebins_per_decade=16, src_type='iso', spectrum='powerlaw', spectrum_pars=[2.0], build_model=True, ltfile=None, edisp_table=None): PSFModel.__init__(self, model=spectrum, sp_param=spectrum_pars) self._src_type = src_type self._nbin_dtheta = nbin self._irf = irf self._edisp_table = edisp_table self._lonlat = (0, 0) if src_type != 'iso' and src_type != 'isodec': cat = Catalog.get() src = cat.get_source_by_name(src_type) self._lonlat = (src['RAJ2000'], src['DEJ2000']) loge_step = 1. / float(ebins_per_decade) emin = 1.0 + loge_step / 2. emax = 6.0 - loge_step / 2. nbin = int((emax - emin) / loge_step) + 1 self._loge_axis = Axis.create(emin, emax, nbin) self._energy = np.power(10, self._loge_axis.center) self._exps = np.zeros(self._loge_axis.nbins) self._psf = np.zeros((self._loge_axis.nbins, self._nbin_dtheta)) self._dtheta = np.array([ self._dtheta_max_deg * (float(i) / float(self._nbin_dtheta))**2 for i in range(self._nbin_dtheta) ]) self._dtheta_axis = Axis(self._dtheta) self._ctheta_axis = Axis.create(0.2, 1.0, 40) self._tau = np.zeros(self._ctheta_axis.nbins) self.loadLTCube(ltfile) self.fillLivetime() if build_model: self.buildModel()
def __init__(self,irf,nbin=600, ebins_per_decade=16, src_type='iso', spectrum='powerlaw', spectrum_pars=[2.0], build_model=True, ltfile=None, edisp_table=None): PSFModel.__init__(self,model=spectrum,sp_param=spectrum_pars) self._src_type = src_type self._nbin_dtheta = nbin self._irf = irf self._edisp_table = edisp_table self._lonlat = (0, 0) if src_type != 'iso' and src_type != 'isodec': cat = Catalog.get() src = cat.get_source_by_name(src_type) self._lonlat = (src['RAJ2000'], src['DEJ2000']) loge_step = 1./float(ebins_per_decade) emin = 1.0+loge_step/2. emax = 6.0-loge_step/2. nbin = int((emax-emin)/loge_step)+1 self._loge_axis = Axis.create(emin,emax,nbin) self._energy = np.power(10,self._loge_axis.center) self._exps = np.zeros(self._loge_axis.nbins) self._psf = np.zeros((self._loge_axis.nbins,self._nbin_dtheta)) self._dtheta = np.array([self._dtheta_max_deg* (float(i)/float(self._nbin_dtheta))**2 for i in range(self._nbin_dtheta)]) self._dtheta_axis = Axis(self._dtheta) self._ctheta_axis = Axis.create(0.2,1.0,40) self._tau = np.zeros(self._ctheta_axis.nbins) self.loadLTCube(ltfile) self.fillLivetime() if build_model: self.buildModel()
def loadsrclist(self,fname,srcs): self.srcs = [] self.src_names = [] self.src_redshifts = [] self.src_ra_deg = [] self.src_dec_deg = [] self.src_radec = [] if not fname is None: src_names = np.genfromtxt(fname,unpack=True,dtype=None) else: src_names = np.array(srcs.split(',')) if src_names.ndim == 0: src_names = src_names.reshape(1) cat = Catalog.get() for name in src_names: src = cat.get_source_by_name(name) name = src['Source_Name'] ra = src['RAJ2000'] dec = src['DEJ2000'] print 'Loading ', name self._photon_data._srcs.append(src) sd = skymaps.SkyDir(ra,dec) self.srcs.append(sd) self.src_names.append(name) self.src_ra_deg.append(ra) self.src_dec_deg.append(dec) self.src_radec.append((np.radians(ra),np.radians(dec))) self.src_redshifts.append(0.)
# Integrate over 3rd (energy) dimension im = im.marginalize(2) plt.figure() im.plot(cmap='ds9_b') plt.figure() # Smooth by 0.2 deg im.smooth(0.2).plot(cmap='ds9_b') # Draw an arbitrary contour in Galactic Coordinates phi = np.linspace(0, 2 * np.pi, 10000) r = np.sqrt(2 * np.cos(2 * phi)) x = im.lon + r * np.cos(phi) y = im.lat + r * np.sin(phi) im.ax()['gal'].plot(x, y, color='w') cat = Catalog.get('2fgl') cat.plot(im, ax=plt.gca(), label_threshold=5, src_color='w') # Make 1D projection on LON axis plt.figure() pim = im.project(0, offset_coord=True) pim.plot() plt.gca().grid(True) plt.show()
def make_image_plot(self,subplot,h,fig,fig2,title,rpsf68,rpsf95, smooth=False, resid_type=None,mc_resid=None,**kwargs): plt.figure(fig.get_label()) cb_label='Counts' if resid_type == 'significance': kwargs['vmin'] = -5 kwargs['vmax'] = 5 kwargs['levels'] = [-5.0,-3.0,3.0,5.0] cb_label = 'Significance [$\sigma$]' elif resid_type == 'fractional': kwargs['vmin'] = -1.0 kwargs['vmax'] = 1.0 kwargs['levels'] = [-1.0,-0.5,0.5,1.0] cb_label = 'Fractional Residual' if smooth: kwargs['beam_size'] = [self._rsmooth,self._rsmooth,0.0,4] axim = h.plot(subplot=subplot,cmap='ds9_b',**kwargs) h.plot_circle(rpsf68,color='w',lw=1.5) h.plot_circle(rpsf95,color='w',linestyle='--',lw=1.5) h.plot_marker(marker='+',color='w',linestyle='--') ax = h.ax() ax.set_title(title) cb = plt.colorbar(axim,orientation='horizontal', shrink=0.9,pad=0.15, fraction=0.05) cb.set_label(cb_label) cat = Catalog.get('3fgl') cat.plot(h,ax=ax,src_color='w',label_threshold=5.0) if resid_type is None: return plt.figure(fig2.get_label()) ax2 = fig2.add_subplot(subplot) z = h.counts[10:-10,10:-10] if resid_type == 'significance': zproj_axis = Axis.create(-6,6,120) elif resid_type == 'fractional': zproj_axis = Axis.create(-1.0,1.0,120) else: zproj_axis = Axis.create(-10,10,120) hz = Histogram(zproj_axis) hz.fill(np.ravel(z)) nbin = np.prod(z.shape) hz_mc = Histogram(zproj_axis) if mc_resid: for mch in mc_resid: z = mch.counts[10:-10,10:-10] hz_mc.fill(np.ravel(z)) hz_mc /= float(len(mc_resid)) fn = lambda t : 1./np.sqrt(2*np.pi)*np.exp(-t**2/2.) hz.plot(label='Data',linestyle='None') if resid_type == 'significance': plt.plot(hz.axis().center, fn(hz.axis().center)*hz.axis().width*nbin, color='k',label='Gaussian ($\sigma = 1$)') hz_mc.plot(label='MC',hist_style='line') plt.gca().grid(True) plt.gca().set_yscale('log') plt.gca().set_ylim(0.5) ax2.legend(loc='upper right',prop= {'size' : 10 }) data_stats = 'Mean = %.2f\nRMS = %.2f'%(hz.mean(),hz.stddev()) mc_stats = 'MC Mean = %.2f\nMC RMS = %.2f'%(hz_mc.mean(), hz_mc.stddev()) ax2.set_xlabel(cb_label) ax2.set_title(title) ax2.text(0.05,0.95, '%s\n%s'%(data_stats,mc_stats), verticalalignment='top', transform=ax2.transAxes,fontsize=10)
def make_image_plot(self, subplot, h, fig, fig2, title, rpsf68, rpsf95, smooth=False, resid_type=None, mc_resid=None, **kwargs): plt.figure(fig.get_label()) cb_label = 'Counts' if resid_type == 'significance': kwargs['vmin'] = -5 kwargs['vmax'] = 5 kwargs['levels'] = [-5.0, -3.0, 3.0, 5.0] cb_label = 'Significance [$\sigma$]' elif resid_type == 'fractional': kwargs['vmin'] = -1.0 kwargs['vmax'] = 1.0 kwargs['levels'] = [-1.0, -0.5, 0.5, 1.0] cb_label = 'Fractional Residual' if smooth: kwargs['beam_size'] = [self._rsmooth, self._rsmooth, 0.0, 4] axim = h.plot(subplot=subplot, cmap='ds9_b', **kwargs) h.plot_circle(rpsf68, color='w', lw=1.5) h.plot_circle(rpsf95, color='w', linestyle='--', lw=1.5) h.plot_marker(marker='x', color='w', linestyle='--') ax = h.ax() ax.set_title(title) cb = plt.colorbar(axim, orientation='horizontal', shrink=0.9, pad=0.15, fraction=0.05) if kwargs.get('zscale', None) is not None: import matplotlib.ticker cb.locator = matplotlib.ticker.MaxNLocator(nbins=5) cb.update_ticks() cb.set_label(cb_label) cat = Catalog.get('3fgl') cat.plot(h, ax=ax, src_color='w', label_threshold=self._srclabels_thresh) if resid_type is None: return plt.figure(fig2.get_label()) ax2 = fig2.add_subplot(subplot) z = h.counts[10:-10, 10:-10] if resid_type == 'significance': zproj_axis = Axis.create(-6, 6, 120) elif resid_type == 'fractional': zproj_axis = Axis.create(-1.0, 1.0, 120) else: zproj_axis = Axis.create(-10, 10, 120) hz = Histogram(zproj_axis) hz.fill(np.ravel(z)) nbin = np.prod(z.shape) hz_mc = Histogram(zproj_axis) if mc_resid: for mch in mc_resid: z = mch.counts[10:-10, 10:-10] hz_mc.fill(np.ravel(z)) hz_mc /= float(len(mc_resid)) fn = lambda t: 1. / np.sqrt(2 * np.pi) * np.exp(-t**2 / 2.) hz.plot(label='Data', linestyle='None') if resid_type == 'significance': plt.plot(hz.axis().center, fn(hz.axis().center) * hz.axis().width * nbin, color='k', label='Gaussian ($\sigma = 1$)') hz_mc.plot(label='MC', hist_style='line') plt.gca().grid(True) plt.gca().set_yscale('log') plt.gca().set_ylim(0.5) ax2.legend(loc='upper right', prop={'size': 10}) data_stats = 'Mean = %.2f\nRMS = %.2f' % (hz.mean(), hz.stddev()) mc_stats = 'MC Mean = %.2f\nMC RMS = %.2f' % (hz_mc.mean(), hz_mc.stddev()) ax2.set_xlabel(cb_label) ax2.set_title(title) ax2.text(0.05, 0.95, '%s\n%s' % (data_stats, mc_stats), verticalalignment='top', transform=ax2.transAxes, fontsize=10)
def main(self, *argv): usage = "usage: %(prog)s [options]" description = """Generates PSF model.""" parser = argparse.ArgumentParser(usage=usage, description=description) IRFManager.configure(parser) parser.add_argument('--ltfile', default=None, help='Set the livetime cube which will be used ' 'to generate the exposure-weighted PSF model.') parser.add_argument('--src', default='Vela', help='') parser.add_argument('--irf', default=None, help='Set the names of one or more IRF models.') parser.add_argument('--output_dir', default=None, help='Set the output directory name.') parser.add_argument('--cth_bin_edge', default='0.4,1.0', help='Edges of cos(theta) bins ' '(e.g. 0.2,0.5,1.0).') parser.add_argument('--egy_bin_edge', default=None, help='Edges of energy bins.') parser.add_argument('--egy_bin', default='1.25/5.0/0.25', help='Set min/max energy.') parser.add_argument('--quantiles', default='0.34,0.68,0.90,0.95', help='Define the set of quantiles to compute.') parser.add_argument('--conversion_type', default='front', help='Draw plots.') parser.add_argument('--spectrum', default='powerlaw/2', help='Draw plots.') parser.add_argument('--edisp', default=None, help='Set the energy dispersion lookup table.') parser.add_argument('-o', '--output', default=None, help='Set the output file.') parser.add_argument('--load_from_file', default=False, action='store_true', help='Load IRFs from FITS.') opts = parser.parse_args(list(argv)) irfs = opts.irf.split(',') [elo, ehi, ebin] = [float(t) for t in opts.egy_bin.split('/')] egy_bin_edge = np.linspace(elo, ehi, 1 + int((ehi - elo) / ebin)) cth_bin_edge = [float(t) for t in opts.cth_bin_edge.split(',')] quantiles = [float(t) for t in opts.quantiles.split(',')] for irf in irfs: if opts.output is None: output_file = re.sub('\:\:', r'_', irf) output_file += '_%03.f%03.f' % (100 * cth_bin_edge[0], 100 * cth_bin_edge[1]) output_file += '_psfdata.P' else: output_file = opts.output irfm = IRFManager.create(irf, opts.load_from_file, opts.irf_dir) lonlat = (0, 0) if opts.src != 'iso' and opts.src != 'iso2': cat = Catalog() src = cat.get_source_by_name(opts.src) lonlat = (src['RAJ2000'], src['DEJ2000']) m = PSFModelLT(opts.ltfile, irfm, nbin=400, cth_range=cth_bin_edge, psf_type=opts.src, lonlat=lonlat, edisp_table=opts.edisp) spectrum = opts.spectrum.split('/') pars = [float(t) for t in spectrum[1].split(',')] m.set_spectrum(spectrum[0], pars) # m.set_spectrum('powerlaw_exp',(1.607,3508.6)) psf_data = PSFData(egy_bin_edge, cth_bin_edge, 'model') # f = open(opts.o,'w') for i in range(len(psf_data.quantiles)): ql = psf_data.quantile_labels[i] q = psf_data.quantiles[i] for iegy in range(len(egy_bin_edge) - 1): elo = egy_bin_edge[iegy] ehi = egy_bin_edge[iegy + 1] radius = m.quantile(10**elo, 10**ehi, q) # print elo, ehi, radius psf_data.qdata[i].set(iegy, 0, radius) # line = '%6.3f '%(q) # line += '%6.3f %6.3f '%(cth_range[0],cth_range[1]) # line += '%6.3f %6.3f %8.4f %8.4f'%(elo,ehi,radius,0.0) # f.write(line + '\n') # m.set_spectrum('powerlaw_exp',(1.607,3508.6)) # m.set_spectrum('powerlaw',(2.0)) # psf_data.print_quantiles('test') psf_data.save(output_file)
def main(self,*argv): usage = "usage: %(prog)s [options]" description = """Generates PSF model.""" parser = argparse.ArgumentParser(usage=usage,description=description) IRFManager.configure(parser) parser.add_argument('--ltfile', default = None, help = 'Set the livetime cube which will be used ' 'to generate the exposure-weighted PSF model.') parser.add_argument('--src', default = 'Vela', help = '') parser.add_argument('--irf', default = None, help = 'Set the names of one or more IRF models.') parser.add_argument('--output_dir', default = None, help = 'Set the output directory name.') parser.add_argument('--cth_bin_edge', default = '0.4,1.0', help = 'Edges of cos(theta) bins ' '(e.g. 0.2,0.5,1.0).') parser.add_argument('--egy_bin_edge', default = None, help = 'Edges of energy bins.') parser.add_argument('--egy_bin', default = '1.25/5.0/0.25', help = 'Set min/max energy.') parser.add_argument('--quantiles', default = '0.34,0.68,0.90,0.95', help = 'Define the set of quantiles to compute.') parser.add_argument('--conversion_type', default = 'front', help = 'Draw plots.') parser.add_argument('--spectrum', default = 'powerlaw/2', help = 'Draw plots.') parser.add_argument('--edisp', default = None, help = 'Set the energy dispersion lookup table.') parser.add_argument('-o', '--output', default = None, help = 'Set the output file.') parser.add_argument('--load_from_file', default = False, action='store_true', help = 'Load IRFs from FITS.') opts = parser.parse_args(list(argv)) irfs = opts.irf.split(',') [elo, ehi, ebin] = [float(t) for t in opts.egy_bin.split('/')] egy_bin_edge = np.linspace(elo, ehi, 1 + int((ehi - elo) / ebin)) cth_bin_edge = [float(t) for t in opts.cth_bin_edge.split(',')] quantiles = [float(t) for t in opts.quantiles.split(',')] for irf in irfs: if opts.output is None: output_file = re.sub('\:\:',r'_',irf) output_file += '_%03.f%03.f'%(100*cth_bin_edge[0], 100*cth_bin_edge[1]) output_file += '_psfdata.P' else: output_file = opts.output irfm = IRFManager.create(irf,opts.load_from_file,opts.irf_dir) lonlat = (0,0) if opts.src != 'iso' and opts.src != 'iso2': cat = Catalog() src = cat.get_source_by_name(opts.src) lonlat = (src['RAJ2000'], src['DEJ2000']) m = PSFModelLT(opts.ltfile, irfm, nbin=400, cth_range=cth_bin_edge, psf_type=opts.src, lonlat=lonlat, edisp_table=opts.edisp) spectrum = opts.spectrum.split('/') pars = [ float(t) for t in spectrum[1].split(',')] m.set_spectrum(spectrum[0],pars) # m.set_spectrum('powerlaw_exp',(1.607,3508.6)) psf_data = PSFData(egy_bin_edge,cth_bin_edge,'model') # f = open(opts.o,'w') for i in range(len(psf_data.quantiles)): ql = psf_data.quantile_labels[i] q = psf_data.quantiles[i] for iegy in range(len(egy_bin_edge)-1): elo = egy_bin_edge[iegy] ehi = egy_bin_edge[iegy+1] radius = m.quantile(10**elo,10**ehi,q) # print elo, ehi, radius psf_data.qdata[i].set(iegy,0,radius) # line = '%6.3f '%(q) # line += '%6.3f %6.3f '%(cth_range[0],cth_range[1]) # line += '%6.3f %6.3f %8.4f %8.4f'%(elo,ehi,radius,0.0) # f.write(line + '\n') # m.set_spectrum('powerlaw_exp',(1.607,3508.6)) # m.set_spectrum('powerlaw',(2.0)) # psf_data.print_quantiles('test') psf_data.save(output_file)
# Integrate over 3rd (energy) dimension im = im.marginalize(2) plt.figure() im.plot(cmap='ds9_b') plt.figure() # Smooth by 0.2 deg im.smooth(0.2).plot(cmap='ds9_b') # Draw an arbitrary contour in Galactic Coordinates phi = np.linspace(0,2*np.pi,10000) r = np.sqrt(2*np.cos(2*phi)) x = im.lon + r*np.cos(phi) y = im.lat + r*np.sin(phi) im.ax()['gal'].plot(x,y,color='w') cat = Catalog.get('2fgl') cat.plot(im,ax=plt.gca(),label_threshold=5,src_color='w') # Make 1D projection on LON axis plt.figure() pim = im.project(0,offset_coord=True) pim.plot() plt.gca().grid(True) plt.show()