def get_point_sources(names, catalog): """ Input is a list of the name of 1FGL sources. What is return is a list of point source found from the names. """ cat=FermiCatalog(catalog,free_radius=180) \ if not isinstance(catalog,SourceCatalog) else catalog point_sources = [] for name in names: index = np.where(cat.names == name)[0] if len(index) < 1: raise Exception("Cannot find source %s in the catalog %s" % (name, catalog)) if len(index) > 1: raise Exception( "%s has too many counterpats in the catalog %s" % (name, catalog)) index = int(index) point_sources.append( PointSource(cat.dirs[index], cat.names[index], cat.models[index], free_parameters=True)) if len(names) == 1: return point_sources[0] return point_sources
def background_fit(self): """Perform a fit over the full time range.""" kw = self.factory_kwargs.copy() kw['tstart'], kw['tstop'] = self.bg_interval f = ROIFactory(**kw) mapper = lambda x: FermiCatalog(x, **self.catalog_kwargs) roi = f(self.skydir, catalog_mapper=mapper, **self.roi_kwargs) roi.fit(**self.fit_kwargs) return roi
def fit(self, start, stop, return_likelihood=False): """Perform a fit over the specified interval.""" fact_kw = self.factory_kwargs.copy() fact_kw['tstart'], fact_kw['tstop'] = start, stop fit_kwargs = self.fit_kwargs.copy() fit_kwargs['fit_bg_first'] = False f = ROIFactory(**fact_kw) mapper = lambda x: FermiCatalog(x, **self.catalog_kwargs) roi = f(self.skydir, catalog_mapper=mapper, **self.roi_kwargs) #roi.set_parameters(self.bg_roi.parameters().copy()) ll_0 = roi.logLikelihood(self.bg_roi.parameters().copy()) for m in roi.bgm.models: m.free[:] = False for m in roi.psm.models: m.free[:] = False for ps in roi.psm.point_sources[self.free_mask]: ps.model.free[0] = True roi.psm.models[0].free[1] = self.index_free roi.fit(**fit_kwargs) if return_likelihood: return roi, ll_0, roi.logLikelihood(roi.parameters()) else: return roi
def get_catalog(catalog=None, **kwargs): if catalog is None or isinstance(catalog, SourceCatalog): pass elif catalog == 'PSC3Y': catalog = Catalog3Y( '/u/ki/kadrlica/fermi/catalogs/PSC3Y/gll_psc3yearclean_v1_assoc_v6r1p0.fit', latextdir='/u/ki/kadrlica/fermi/catalogs/PSC3Y/', prune_radius=0, **kwargs) elif catalog == '2FGL': catalog = Catalog2FGL( '/u/ki/kadrlica/fermi/catalogs/2FGL/gll_psc_v08.fit', latextdir='/u/ki/kadrlica/fermi/catalogs/2FGL/Templates/', prune_radius=0, **kwargs) elif catalog == "1FGL": catalog = FermiCatalog( '/u/ki/kadrlica/fermi/catalogs/gll_psc_v02.fit', prune_radius=0, **kwargs) else: raise Exception("Unknown catalog: %s" % catalog) return catalog
def setup_pwn(name,pwndata,phase, free_radius=5, tempdir=None, emin=1.0e2, emax=1.0e5,maxroi=10,model=None,**kwargs): """Name of the source pwndata Yaml file returns pointlike ROI. """ sources=yaml.load(open(pwndata)) catalog_name=sources[name]['catalog'] ltcube=sources[name]['ltcube'] pulsar_position=SkyDir(*sources[name]['dir']) ft2=sources[name]['ft2'] ft1=sources[name]['ft1'] # in case no list was passed if len(phase)==2 and isinstance(phase[0],numbers.Real) and \ isinstance(phase[1],numbers.Real): # write in case phase wraps around. if phase[0]>phase[1]: phase=[[phase[0],1.0],[0.0,phase[1]]] else: phase = [phase] phase_factor=get_phase_factor(phase) print "phase" print phase print "phase_factor=%.2f"%phase_factor catalog=FermiCatalog(e("$FERMI/catalogs/gll_psc_v02.fit"),free_radius=free_radius) catalog_source=[i for i in catalog.get_sources(SkyDir(),180) if i.name==catalog_name][0] center=catalog_source.skydir if tempdir is None: tempdir=mkdtemp(prefix='/scratch/') binfile=j(tempdir,'binned_phased.fits') # apply phase cut to ft1 file phased_ft1 = j(tempdir,'ft1_phased.fits') phasetools.phase_cut(ft1,phased_ft1,phaseranges=phase) # create a temporary ltcube scaled by the phase factor # phased_ltcube=j(tempdir,'phased_ltcube.fits') # phase_ltcube(ltcube,phased_ltcube, phase=phase) phased_ltcube=ltcube from uw.like.pointspec import DataSpecification data_specification = DataSpecification( ft1files = phased_ft1, ft2files = ft2, ltcube = phased_ltcube, binfile = binfile) spectral_analysis = SpectralAnalysis(data_specification, binsperdec = 4, emin = 100, emax = 100000, irf = "P6_V3_DIFFUSE", roi_dir = center, maxROI = maxroi, minROI = maxroi) if model == None : roi=spectral_analysis.roi( roi_dir=center, diffuse_sources=get_default_diffuse(diffdir=e("$FERMI/diffuse"), gfile="gll_iem_v02.fit", ifile="isotropic_iem_v02.txt"), catalogs = catalog, phase_factor = 1.0, fit_emin = [emin,emin], fit_emax = [emax,emax], **kwargs) else : roi=spectral_analysis.roi( roi_dir=center, xmlfile = model, phase_factor =1.0, fit_emin = [emin,emin], fit_emax = [emax,emax], **kwargs) print "---------------------Energy range--------------------" print "emin="+str(roi.bands[0].emin)+"\n" print "emax="+str(roi.bands[len(roi.bands)-1].emax)+"\n" # keep overall flux of catalog source, # but change the starting index to 2. roi.modify(which=catalog_name, name=name, index=2, keep_old_flux=True) return roi
def setup_pointlike(name,pwnlist,phasing=True): """Name of the source pwnlist Yaml file phasing=true : apply phase cut phasing=false : don't do it""" sources=yaml.load(open(pwnlist)) catalog_name=sources[name]['catalog'] phase=sources[name]['phase'] ltcube=sources[name]['ltcube'] pulsar_position=SkyDir(*sources[name]['dir']) if phasing==True: phase_factor=phase[1]-phase[0] if phase[1]>phase[0] else (1-phase[0]) + (phase[1]-0) ft1=sources[name]['ft1'] else : phase_factor=1.0 raise Exception("Unable to phase data") catalog=FermiCatalog(e("$FERMI/catalogs/gll_psc_v02.fit"),free_radius=5) catalog_source=[i for i in catalog.get_sources(SkyDir(),180) if i.name==catalog_name][0] center=catalog_source.skydir from uw.like.pointspec import DataSpecification data_specification = DataSpecification( ft1files = ft1, ltcube = ltcube, binfile = "binned_%s.fits" % name) spectral_analysis = SpectralAnalysis(data_specification, binsperdec = 8, emin = 100, emax = 100000, irf = "P6_V3_DIFFUSE", roi_dir = center, maxROI = 10, minROI = 10) roi=LandeROI(spectral_analysis.roi( roi_dir=center, diffuse_sources=get_default_diffuse(diffdir=e("$FERMI/diffuse"), gfile="gll_iem_v02.fit", ifile="isotropic_iem_v02.txt"), catalogs = catalog, fit_emin = 100, fit_emax = 100000, catalog_include_radius = 20, phase_factor = phase_factor) ) roi.del_source(catalog_name) # make residual TS map # add in PWN Candidate source=PointSource( name=name, model=PowerLaw(p=[1,2]), skydir=pulsar_position ) source.model.set_flux(1e-7,emin=100,emax=100000) roi.add_source(source) return roi
args = parser.parse_args() if args.num_points is not None: from uw.utilities.convolution import AnalyticConvolution AnalyticConvolution.set_points(args.num_points) name=args.name savename = name.replace(' ','_') datafiles=imp.load_source('datafiles',args.datafiles) start_spectral = None manager=FermiCatalog(datafiles.catalog) if not isinstance(datafiles.catalog,SourceCatalog) else datafiles.catalog source = manager.get_source(name) # only works with Catalog2FGL (oops) start_spectral = source.model skydir = source.skydir outfile={'start_cel':[skydir.ra(),skydir.dec()], 'start_gal':[skydir.l(),skydir.b()], 'name':name} ds = DataSpecification( binfile = datafiles.binfile, ltcube = datafiles.ltcube, ft1files = datafiles.ft1files, ft2files = datafiles.ft2file) sa = SpectralAnalysis(ds,
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 setup_pwn(name,pwndata,phase, free_radius=5, tempdir=None, **kwargs): """Name of the source pwndata Yaml file returns pointlike ROI. """ sources=yaml.load(open(pwndata)) catalog_name=sources[name]['catalog'] ltcube=sources[name]['ltcube'] pulsar_position=SkyDir(*sources[name]['dir']) ft2=sources[name]['ft2'] ft1=sources[name]['ft1'] # in case no list was passed if len(phase)==2 and isinstance(phase[0],numbers.Real) and \ isinstance(phase[1],numbers.Real): # write in case phase wraps around. if phase[0]>phase[1]: phase=[[phase[0],1.0],[0.0,phase[1]]] else: phase = [phase] phase_factor=get_phase_factor(phase) catalog=FermiCatalog(e("$FERMI/catalogs/gll_psc_v02.fit"),free_radius=free_radius) catalog_source=[i for i in catalog.get_sources(SkyDir(),180) if i.name==catalog_name][0] center=catalog_source.skydir if tempdir is None: tempdir=mkdtemp(prefix='/scratch/') binfile=j(tempdir,'binned_phased.fits') # apply phase cut to ft1 file phased_ft1 = j(tempdir,'ft1_phased.fits') phasetools.phase_cut(ft1,phased_ft1,phaseranges=phase) # create a temporary ltcube scaled by the phase factor # phased_ltcube=j(tempdir,'phased_ltcube.fits') # phase_ltcube(ltcube,phased_ltcube, phase=[0.0,1.0]) phased_ltcube=ltcube from uw.like.pointspec import DataSpecification data_specification = DataSpecification( ft1files = phased_ft1, ft2files = ft2, ltcube = phased_ltcube, binfile = binfile) spectral_analysis = SpectralAnalysis(data_specification, binsperdec = 4, emin = 100, emax = 100000, irf = "P6_V3_DIFFUSE", roi_dir = center, maxROI = 10, minROI = 10) roi=spectral_analysis.roi( roi_dir=center, diffuse_sources=get_default_diffuse(diffdir=e("$FERMI/diffuse"), gfile="gll_iem_v02.fit", ifile="isotropic_iem_v02.txt"), catalogs = catalog, phase_factor = phase_factor, **kwargs) # phaseing already done to the ltcube print "phase_factor=%.2f"%phase_factor # keep overall flux of catalog source, # but change the starting index to 2. roi.modify(which=catalog_name, name=name, index=2, keep_old_flux=True) roi.toXML(filename="essai") print roi roi.print_summary() for names in roi.get_names(): try : roi.modify(names,Norm=roi.get_model(names)[0]*roi.phase_factor) except : try : roi.modify(names,Int_flux=roi.get_model(names)[0]*roi.phase_factor) except : print names table=roi.get_names() print roi.modify(which=table[len(table)-2],model=PowerLaw(p=[1.0*phase_factor,0.1]),free=[True,False]) print roi.modify(which=table[len(table)-1],model=PowerLaw(p=[1.0*phase_factor,0.1]),free=[True,False]) # print roi.modify(which='eg_v02',free=[False]) print roi return roi