def all_energy_table(pwnlist): data = yaml.load(open(expandvars('$pwncode/data/pwncat2_phase_lande.yaml'))) table = OrderedDefaultDict(list) psr_name='PSR' phase_name='Phase' optimal_emin_name='Optimal Emin' if confluence else r'Optimal $E_\text{min}$' optimal_radius_name='Optimal radius' for pwn in pwnlist: print pwn table[psr_name].append(format.pwn(pwn)) phase=PhaseRange(data[pwn]['phase']) optimal_emin=data[pwn]['optimal_emin'] optimal_radius=data[pwn]['optimal_radius'] table[phase_name].append(phase.pretty_format()) table[optimal_emin_name].append('%.2f' % optimal_emin) table[optimal_radius_name].append('%.2f' % optimal_radius) print yaml.dump(table) if confluence: write_confluence(table, filebase='phase_range') else: write_latex(table, filebase='phase_range')
def plot_phaseogram(ft1, nbins=100, filename=None, title=None, phase_range=None, data_kwargs=dict(), phase_range_kwargs=dict(), repeat_phase=False, axes=None, offset=None, **kwargs): """ Simple code to plot a phaseogram. """ phases = get_phases(ft1, **kwargs) if offset is not None: phases += offset phases = phases % 1 if axes is None: fig = P.figure(None, figsize=(5, 5)) axes = fig.add_subplot(111) bins = np.linspace(0, 1, nbins + 1) x, y = histpoints(phases, bins=bins) if repeat_phase: x, y = np.append(x, x + 1), np.append(y, y) k = dict(color='black') k.update(data_kwargs) P.plot(x, y, **k) axes.set_ylim(0) axes.set_xlim(0, 2 if repeat_phase else 1) if title is not None: axes.set_title(title) axes.set_xlabel('Phase') axes.set_ylabel('Counts') axes.grid = True if phase_range is not None: phase_range = PhaseRange(phase_range) if offset is not None: phase_range = phase_range.offset(offset) kwargs = dict(alpha=0.25, color='blue') kwargs.update(phase_range_kwargs) phase_range.axvspan(axes=axes, phase_offsets=[0, 1] if repeat_phase else 0, **kwargs) if filename is not None: P.savefig(filename) return axes, bins
def plot_phaseogram(ft1, nbins=100, filename=None, title=None, phase_range=None, data_kwargs=dict(), phase_range_kwargs=dict(), repeat_phase=False, axes=None, offset=None, **kwargs): """ Simple code to plot a phaseogram. """ phases = get_phases(ft1, **kwargs) if offset is not None: phases += offset phases = phases % 1 if axes is None: fig = P.figure(None, figsize=(5,5)) axes = fig.add_subplot(111) bins = np.linspace(0,1,nbins+1) x, y = histpoints(phases, bins=bins) if repeat_phase: x,y = np.append(x, x+1), np.append(y, y) k = dict(color='black') k.update(data_kwargs) P.plot(x,y, **k) axes.set_ylim(0) axes.set_xlim(0,2 if repeat_phase else 1) if title is not None: axes.set_title(title) axes.set_xlabel('Phase') axes.set_ylabel('Counts') axes.grid=True if phase_range is not None: phase_range = PhaseRange(phase_range) if offset is not None: phase_range = phase_range.offset(offset) kwargs=dict(alpha=0.25, color='blue') kwargs.update(phase_range_kwargs) phase_range.axvspan(axes=axes, phase_offsets=[0,1] if repeat_phase else 0, **kwargs) if filename is not None: P.savefig(filename) return axes, bins
def plot_phase_vs_time(ft1, filename=None, title=None, phase_range=None, phase_range_kwargs=dict(), axes=None, **kwargs): """ Simple code to plot phase vs time. """ phases, times = get_phases_and_times(ft1, **kwargs) if axes is None: # here, put a 2d histogram fig = P.figure(None, figsize=(5, 5)) fig.subplots_adjust(left=0.2) axes = fig.add_subplot(111) # Note about 2D histograms: # http://www.physics.ucdavis.edu/~dwittman/Matplotlib-examples/ hist, xedges, yedges = np.histogram2d(phases, times, bins=(50, 50), range=[[0, 1], [min(times), max(times)]]) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] axes.imshow(hist.T, extent=extent, interpolation='nearest', origin='lower', aspect='auto') if phase_range is not None: kwargs = dict(alpha=0.5, color='white') kwargs.update(phase_range_kwargs) PhaseRange(phase_range).axvspan(axes=axes, **kwargs) axes.set_xlabel('phase') axes.set_ylabel('MJD') if title is not None: axes.set_title(title) if filename is not None: P.savefig(filename) return axes
def load_pwn(filename, savedir=None, **kwargs): """ By default, pwn roi's are not loadable. """ d = cPickle.load(open(expandvars(filename), 'r')) extra = d['extra'] ft1 = extra['unphased_ft1'] ltcube = extra['unphased_ltcube'] phase = PhaseRange(extra['phase']) if exists(ft1) and exists(ltcube) and exists(phase): return load(filename, **kwargs) if savedir is None: save_data = False savedir = mkdtemp(prefix='/scratch/') else: if not os.path.exists(savedir): os.makedirs(savedir) save_data = True print 'new savedir is', savedir phased_ft1 = PWNRegion.phase_ft1(ft1, phase, savedir) phased_ltcube = PWNRegion.phase_ltcube(ltcube, phase, savedir) binfile = join(savedir, 'binned_phased.fits') roi = load(filename, ft1files=phased_ft1, ltcube=phased_ltcube, binfile=binfile, **kwargs) if not save_data: roi.__del__ = lambda x: shutil.rmtree(savedir) return roi
def get_results(self, pwn, require_all_exists=True, get_seds=True, get_variability=True, get_altdiff=True, verbosity=None): filename = join(self.fitdir, pwn, 'results_%s_general.yaml' % pwn) if verbosity or (verbosity is None and self.verbosity): print 'Getting results for %s' % pwn if not exists(filename): raise PWNResultsException("%s does not exist" % filename) results = loaddict(filename) for hypothesis in self.all_hypotheses: results[hypothesis] = dict() for code in ['gtlike', 'pointlike']: for hypothesis in self.all_hypotheses: filename = join( self.fitdir, pwn, 'results_%s_%s_%s.yaml' % (pwn, code, hypothesis)) if exists(filename): results[hypothesis][code] = loaddict(filename) else: if require_all_exists: raise PWNResultsException("%s does not exist" % filename) if get_variability: for hypothesis in ['at_pulsar', 'point']: filename = join( self.fitdir, pwn, 'results_%s_variability_%s.yaml' % (pwn, hypothesis)) if exists(filename): results[hypothesis]['variability'] = loaddict(filename) else: if require_all_exists: raise PWNResultsException('%s does not exist' % filename) if get_altdiff: for hypothesis in ['point']: results[hypothesis]['gtlike']['altdiff'] = dict() for dist in ['SNR', 'Lorimer']: for halo in [4, 10]: for TS in [150, 100000]: filename = join( self.fitdir, pwn, 'results_%s_altdiff_dist_%s_halo_%s_TS_%s_%s.yaml' % (pwn, dist, halo, TS, hypothesis)) if exists(filename): results[hypothesis]['gtlike']['altdiff'][ dist, halo, TS] = loaddict(filename) else: results[hypothesis]['gtlike']['altdiff'][ dist, halo, TS] = None if get_seds: for hypothesis in self.all_hypotheses: for code, all_binning in [['gtlike', ['1bpd', '2bpd', '4bpd']], ['pointlike', ['4bpd']]]: results[hypothesis][code]['seds'] = dict() for binning in all_binning: filename = join( self.fitdir, pwn, 'seds', 'sed_%s_%s_%s_%s.yaml' % (code, binning, hypothesis, pwn)) if exists(filename): results[hypothesis][code]['seds'][ binning] = loaddict(filename) else: if require_all_exists: raise PWNResultsException("%s does not exist" % filename) results['raw_phase'] = PhaseRange(results['phase']) del results['phase'] # to avoid ambiguity if self.phase_shift is not None: import pickle ps = pickle.load(open(self.phase_shift)) shift = float(ps[pwn.replace('PSRJ', 'J')]['shift']) """ Convention taken from private correspondence with Matthew Kerr: me: ok so i am trying to implement phase shifts in my analysis did you decide the right way to do it Matthew: it seems to be + me: so correct_phase = phase_in_file + shift Matthew: yes """ results['shifted_phase'] = results['raw_phase'].offset(shift) return results
def setup_region(name,pwndata,phase, free_radius=5, tempdir=None, maxroi=10, xml=None, **kwargs): """Name of the source pwndata Yaml file returns pointlike ROI. """ phase = PhaseRange(phase) sources=yaml.load(open(pwndata)) catalog_name=sources[name]['catalog']['2fgl'] ltcube=sources[name]['ltcube'] pulsar_position=SkyDir(*sources[name]['dir']) ft2=sources[name]['ft2'] ft1=sources[name]['ft1'] catalog=FermiCatalog(e("$FERMI/catalogs/gll_psc_v02.fit")) catalog=Catalog2FGL('$FERMI/catalogs/gll_psc_v05.fit', latextdir='$FERMI/extended_archives/gll_psc_v05_templates', free_radius=free_radius) catalog_source=catalog.get_source(catalog_name) center=catalog_source.skydir if tempdir is None: tempdir=mkdtemp(prefix='/scratch/') binfile=j(tempdir,'binned_phased.fits') if np.allclose(phase.phase_fraction,1): phased_ltcube = ltcube phased_ft1 = ft1 else: # create a temporary ltcube scaled by the phase factor phased_ltcube=j(tempdir,'phased_ltcube.fits') phase_ltcube(ltcube,phased_ltcube, phase=phase) # apply phase cut to ft1 file phased_ft1 = j(tempdir,'ft1_phased.fits') phasetools.phase_cut(ft1,phased_ft1,phaseranges=phase.tolist(dense=False)) from uw.like.pointspec import DataSpecification ds = DataSpecification( ft1files = phased_ft1, ft2files = ft2, ltcube = phased_ltcube, binfile = binfile) sa = SpectralAnalysis(ds, binsperdec = 8, emin = 100, emax = 100000, irf = "P6_V11_DIFFUSE", roi_dir = center, maxROI = maxroi, minROI = maxroi) if xml is None: roi=sa.roi( diffuse_sources=get_default_diffuse(diffdir="/afs/slac/g/glast/groups/diffuse/mapcubes", gfile="gll_iem_v02.fit", ifile="isotropic_iem_v02.txt"), catalogs = catalog, phase_factor =1, **kwargs) else: roi=sa.roi_from_xml( roi_dir=center, xmlfile = xml, phase_factor =1, **kwargs) print 'bins ',roi.bin_edges roi.del_source(catalog_name) return roi
def get_roi(self, name, phase, fit_emin, fit_emax, binsperdec, extended=False, roi_size=10, catalog_kwargs=dict(), **kwargs): """ Sets up the ROI for studying a LAT Pulsar in the off pulse. """ sourcedict = yaml.load(open(self.pwndata))[name] ltcube = sourcedict['ltcube'] pulsar_position = SkyDir(*sourcedict['cel']) ft1 = sourcedict['ft1'] ft2 = sourcedict['ft2'] source = PWNRegion.get_source(name, position=pulsar_position, fit_emin=fit_emin, fit_emax=fit_emax, sigma=0.1, extended=extended) sources = [source] roi_dir = pulsar_position phase = PhaseRange(phase) point_sources, diffuse_sources = [], [] for source in sources: if isinstance(source, PointSource): point_sources.append(source) else: diffuse_sources.append(source) diffuse_sources += PWNRegion.get_background() catalog = PWNRegion.get_catalog(**catalog_kwargs) binfile = join(self.savedir, 'binned_phased.fits') phased_ltcube = PWNRegion.phase_ltcube(ltcube, phase, self.savedir) phased_ft1 = PWNRegion.phase_ft1(ft1, phase, self.savedir) ds = DataSpecification(ft1files=phased_ft1, ft2files=ft2, ltcube=phased_ltcube, binfile=binfile) print 'For now, 4 bins per decade. Eventually, this will have to be better.' sa = SpectralAnalysis(ds, binsperdec=binsperdec, emin=100, emax=1000000, irf="P7SOURCE_V6", roi_dir=roi_dir, maxROI=roi_size, minROI=roi_size, event_class=0) roi = sa.roi(point_sources=point_sources, diffuse_sources=diffuse_sources, catalogs=catalog, phase_factor=1, fit_emin=fit_emin, fit_emax=fit_emax, **kwargs) print 'bins ', roi.bin_edges roi.extra = dict(unphased_ft1=ft1, unphased_ltcube=ltcube, phase=phase) self.roi = roi return roi