def addSrcsFITS(sL,GD,GDn,ISO,ISOn,oldNames):
	model=open(sL.out,'w') #open file in write mode, overwrites other files of same name
	file=pyfits.open(sL.srcs) #open source list file and access necessary fields, requires LAT source catalog definitions and names
	mask=file[1].data.field('Signif_Avg')>=self.sig
	data=file[1].data[mask]
	extendedinfo=file['ExtendedSources'].data
	extName=extendedinfo.field('Source_Name')	
	extFile=extendedinfo.field('Spatial_Filename')
	name=data.field('Source_Name')
	Sigvals=data.field('Signif_Avg')
	VarIdx=data.field('Variability_Index')
	EName=data.field('Extended_Source_Name')
	ra=data.field('RAJ2000')
	dec=data.field('DEJ2000')
	flux=data.field('Flux_Density')
	pivot=data.field('Pivot_Energy')
	index=data.field('Spectral_Index')
	cutoff=data.field('Cutoff')
	expIndex=data.field('Exp_Index')
	spectype=data.field('SpectrumType')
	beta=data.field('Beta')
	model.write('<?xml version="1.0" ?>\n')
	model.write('<source_library title="source library">\n')
	model.write('\n<!-- Point Sources -->\n')
	step=(sL.roi[2]+sL.ER)/5. #divide ROI radius plus ExtraRadius degrees into 5 steps for ordering of sources
	i=1
	radii=[]
	ptSrcNum=0
	extSrcNum=0
	Sources={}#dictionary for sources, useful for creating region file later.
	while i<6:
		if i*step<=sL.roi[2]+sL.ER:
			radii+=[step*i]
		else:
			radii+=[sL.roi[2]+sL.ER] #just in case of rounding errors
		i+=1
	for x in radii:
		if x==sL.roi[2]+sL.ER:
			model.write('\n<!-- Sources between [%s,%s] degrees of ROI center -->\n' %(x-step,x))
		else:
			model.write('\n<!-- Sources between [%s,%s) degrees of ROI center -->\n' %(x-step,x))
		for n,f,i,r,d,p,c,t,b,TS,ei,vi,En in zip(name,flux,index,ra,dec,pivot,cutoff,spectype,beta,Sigvals,expIndex,VarIdx,EName):
			E=(True if n[-1]=='e' else False)
			dist=angsep(sL.roi[0],sL.roi[1],r,d) #check that source is within ROI radius + 10 degress of ROI center
			if r==sL.roi[0] and d==sL.roi[1]:
				dist=0.0
			if (dist<x and dist>=x-step) or (x==sL.roi[2]+10. and dist==x):
				if E and not sL.psF:
					Sources[En]={'ra':r,'dec':d,'stype':t,'E':E}
					extSrcNum+=1
					Name='<source ROI_Center_Distance="%.3f" name="%s" type="DiffuseSource">\n' %(dist,En)
				else:
					if E:#even if forcing all to point sources, use extended name
						Sources[En]={'ra':r,'dec':d,'stype':t,'E':E}
						Name='<source ROI_Center_Distance="%.3f" name="%s" type="PointSource">\n' %(dist,En)
					else:
						Sources[n]={'ra':r,'dec':d,'stype':t,'E':E}
						if oldNames:
							srcname='_'
							for N in n.split(' '):
								srcname+=N
							Name='<source ROI_Center_Distance="%.3f" name="%s" type="PointSource">\n' %(dist,srcname)
						else:
							Name='<source ROI_Center_Distance="%.3f" name="%s" type="PointSource">\n' %(dist,n)
					ptSrcNum+=1
				if t=='PowerLaw':
					fixAll=(True if n=='3FGL J0534.5+2201i' or En in ['Cygnus Cocoon','Vela X','MSH 15-52','gamma Cygni'] else False)
					spec,free=PLspec(sL,f,i,p,dist,TS,vi,fixAll)
				elif t=='PowerLaw2':#no value for flux from 100 MeV to 100 GeV in fits file
					if i!=1.:#so calculate it by integrating PowerLaw spectral model
						F=f*p**i/(-i+1.)*(1.e5**(-i+1.)-1.e2**(-i+1.))
					else:
						F=f*p*log(1.e3)
					spec,free=PL2spec(sL,F,i,dist,TS,vi)
					#spec,free=PL2spec(sL,f100,i,dist,TS,vi)
				elif t=='LogParabola':
					spec,free=LPspec(sL,f,i,p,b,dist,TS,vi)
				else:
					spec,free=COspec(sL,f,i,p,c,ei,dist,TS,vi)
				if E:
					Sources[En]['free']=free
				else:
					Sources[n]['free']=free
				if E and not sL.psF:
					#need to fix this
					efile=None
					for EXTNAME,EXTFILE in zip(extName,extFile):
						if En==EXTNAME:
							efile=sL.extD+EXTFILE
					if efile==None:
						print 'could not find a match for',En,'in the list:'
						print extName
						efile=''
					skydir='\t<spatialModel file="%s" map_based_integral="true" type="SpatialMap">\n'%(efile)
					print 'Extended source %s in ROI, make sure %s is the correct path to the extended template.'%(En,efile)
					skydir+='\t\t<parameter free="0" max="1000" min="0.001" name="Prefactor" scale="1" value="1"/>\n'
					skydir+='\t</spatialModel>\n'
				else:
					skydir='\t<spatialModel type="SkyDirFunction">\n'
					skydir+='\t\t<parameter free="0" max="360.0" min="-360.0" name="RA" scale="1.0" value="%s"/>\n' %r
					skydir+='\t\t<parameter free="0" max="90" min="-90" name="DEC" scale="1.0" value="%s"/>\n' %d
					skydir+='\t</spatialModel>\n'
				skydir+='</source>'
				(src,)=(Name+spec+skydir,)
				ptsrc=pS(src).getElementsByTagName('source')[0]
				ptsrc.writexml(model)
				model.write('\n')
	file.close() #close file
	if not sL.psF:
		print 'Added %i point sources and %i extended sources'%(ptSrcNum,extSrcNum)
		if extSrcNum>0:
			print 'If using unbinned likelihood you will need to rerun gtdiffrsp for the extended sources or rerun the makeModel function with optional argument psForce=True'
	else:
		print 'Added %i point sources, note that any extended sources in ROI were modeled as point sources becaue psForce option was set to True'%ptSrcNum
	#add galactic diffuse with PL spectrum, fix index to zero for general use, those who want it to be free can unfreeze parameter manually
	model.write('\n<!-- Diffuse Sources -->\n')
	Name='\n<source name="%s" type="DiffuseSource">\n' %GDn
	spec='\t<spectrum type="PowerLaw" apply_edisp="false">\n'
	spec+='\t\t<parameter free="1" max="10" min="0" name="Prefactor" scale="1" value="1"/>\n'
	if sL.GIF:
		spec+='\t\t<parameter free="1" max="1" min="-1" name="Index" scale="1.0" value="0"/>\n'
	else:
		spec+='\t\t<parameter free="0" max="1" min="-1" name="Index" scale="1.0" value="0"/>\n'
	spec+='\t\t<parameter free="0" max="2e2" min="5e1" name="Scale" scale="1.0" value="1e2"/>\n'
	spec+='\t</spectrum>\n'
	skydir='\t<spatialModel file="%s" type="MapCubeFunction">\n' %GD
	skydir+='\t\t<parameter free="0" max="1e3" min="1e-3" name="Normalization" scale="1.0" value="1.0"/>\n'
	skydir+='\t</spatialModel>\n'
	skydir+='</source>'
	(src,)=(Name+spec+skydir,)
	galdiff=pS(src).getElementsByTagName('source')[0]
	galdiff.writexml(model)
	model.write('\n')
	Name='<source name="%s" type="DiffuseSource">\n' %ISOn
	spec='\t<spectrum type="FileFunction" file="%s"  apply_edisp="false">\n' %ISO
	spec+='\t\t<parameter free="1" max="10" min="1e-2" name="Normalization" scale="1" value="1"/>\n'
	spec+='\t</spectrum>\n'
	skydir='\t<spatialModel type="ConstantValue">\n'
	skydir+='\t\t<parameter free="0" max="10.0" min="0.0" name="Value" scale="1.0" value="1.0"/>\n'
	skydir+='\t</spatialModel>\n'
	skydir+='</source>'
	(src,)=(Name+spec+skydir,)
	iso=pS(src).getElementsByTagName('source')[0]
	iso.writexml(model)	
	model.write('\n</source_library>')
	model.close()
	if sL.reg:
		BuildRegion(sL,Sources)
	return
Exemplo n.º 2
0
def addSrcs2(sL, GD, GDn, ISO, ISOn, signif):
    model = open(
        sL.out,
        'w')  #open file in write mode, overwrites other files of same name
    file = pyfits.open(
        sL.srcs
    )  #open source list file and access necessary fields, requires LAT source catalog definitions and names
    data = file[1].data
    extendedinfo = file[4].data
    extName = extendedinfo.field('Source_Name')
    extFile = extendedinfo.field('Spatial_Filename')
    name = data.field('Source_Name')
    ExtName = data.field('Extended_Source_Name')
    ra = data.field('RAJ2000')
    dec = data.field('DEJ2000')
    flux = data.field('Flux_Density')
    pivot = data.field('Pivot_Energy')
    index = data.field('Spectral_Index')
    cutoff = data.field('Cutoff')
    spectype = data.field('SpectrumType')
    beta = data.field('beta')
    #extended=data.field('Extended')
    sigma = data.field('Signif_Avg')
    model.write('<?xml version="1.0" ?>\n')
    model.write('<source_library title="source library">\n')
    model.write('\n<!-- Point Sources -->\n')
    step = (
        sL.roi[2] + 5
    ) / 5  #divide ROI radius plus 5 degrees into 5 steps for ordering of sources, get next highest int for ease
    i = 1
    radii = []
    ptSrcNum = 0
    extSrcNum = 0
    while i < 6:
        if i * step <= sL.roi[2] + 5:
            radii += [step * i]
        else:
            radii += [sL.roi[2] + 5]  #just in case of rounding errors
        i += 1
    for x in radii:
        if x == sL.roi[2] + 5.:
            model.write(
                '\n<!-- Sources between [%s,%s] degrees of ROI center -->\n' %
                (x - step, x))
        else:
            model.write(
                '\n<!-- Sources between [%s,%s) degrees of ROI center -->\n' %
                (x - step, x))
        for n, f, i, r, d, p, c, t, b, S, EN in zip(name, flux, index, ra, dec,
                                                    pivot, cutoff, spectype,
                                                    beta, sigma, ExtName):
            dist = angsep(
                sL.roi[0], sL.roi[1], r, d
            )  #check that source is within ROI radius + 5 degress of ROI center
            if r == sL.roi[0] and d == sL.roi[1]:
                dist = 0.0
            if (dist < x and dist >= x - step) or (x == sL.roi[2] + 5.
                                                   and dist == x):
                sn = ''
                for N in n.split(' '):
                    sn += N
                if EN != '' and not sL.psF:
                    extSrcNum += 1
                    if EN[0].isdigit(
                    ):  #use the extended source name to set these apart even further
                        Name = '<source name="_%s" type="DiffuseSource">\n' % EN
                    else:
                        Name = '<source name="%s" type="DiffuseSource">\n' % EN
                else:
                    ptSrcNum += 1
                    if sn[0].isdigit():
                        Name = '<source name="_%s" type="PointSource">\n' % sn
                    else:
                        Name = '<source name="%s" type="PointSource">\n' % sn
                if EN != 'Vela X' and EN != 'MSH 15-52':
                    if t == 'PowerLaw':
                        spec = PLspec(sL, f, i, p, dist, S, signif)
                    elif t == 'PowerLaw2':  #no value for flux from 100 MeV to 100 GeV in fits file0
                        if i != 1.:  #so calculate it by integrating PowerLaw spectral model
                            F = f * p**i / (-i + 1) * (1.e5**(-i + 1) -
                                                       1.e2**(-1 + 1))
                        else:
                            F = f * p * log(1.e3)
                        spec = PL2spec(sL, F, i, dist, S, signif)
                    elif t == 'LogParabola':
                        spec = LPspec(sL, f, i, p, b, dist, S, signif)
                    else:
                        spec = COspec(sL, f, i, p, c, dist, S, signif)
                else:
                    if EN == 'Vela X':
                        spec = VXspec(sL, i, dist)
                    else:
                        spec = MSHspec(sL, i, dist)
                if EN != '' and not sL.psF:
                    eFile = None
                    for exN, exf in zip(extName, extFile):
                        if exN == EN:
                            if len(sL.extD) > 0:
                                if sL.extD[-1] == '/':
                                    eFile = sL.extD + exf
                                else:
                                    eFile = sL.extD + '/' + exf
                            else:
                                eFile = exf
                            break
                    if eFile == None:
                        skydir = '\t<spatialModel file="%s" type="SpatialMap">\n' % sL.extD
                        print 'Extended source %s (%s) in ROI, could not find name of matching template file.' % (
                            EN, sn)
                    else:
                        skydir = '\t<spatialModel file="%s" type="SpatialMap">\n' % eFile
                        print 'Extended source %s (%s) in ROI, verify that %s is the correct path.' % (
                            EN, sn, eFile)
                    skydir += '\t\t<parameter free="0" max="1000" min="0.001" name="Prefactor" scale="1" value="1"/>\n'
                    skydir += '\t</spatialModel>\n'
                else:
                    skydir = '\t<spatialModel type="SkyDirFunction">\n'
                    skydir += '\t\t<parameter free="0" max="360.0" min="-360.0" name="RA" scale="1.0" value="%s"/>\n' % r
                    skydir += '\t\t<parameter free="0" max="90" min="-90" name="DEC" scale="1.0" value="%s"/>\n' % d
                    skydir += '\t</spatialModel>\n'
                skydir += '</source>'
                (src, ) = (Name + spec + skydir, )
                ptsrc = pS(src).getElementsByTagName('source')[0]
                ptsrc.writexml(model)
                model.write('\n')
    file.close()  #close file
    if not sL.psF:
        print 'Added %i point sources and %i extended sources' % (ptSrcNum,
                                                                  extSrcNum)
        if extSrcNum > 0:
            print 'If using unbinned likelihood you will need to rerun gtdiffrsp for the extended sources or rerun the makeModel function with optional argument psForce=True'
    else:
        print 'Added %i point sources, note that any extended sources in ROI were modeled as point sources becaue psForce option was set to True' % ptSrcNum
    #add galactic diffuse with PL spectrum, fix index to zero for general use, those who want it to be free can unfreeze parameter manually
    model.write('\n<!-- Diffuse Sources -->\n')
    Name = '\n<source name="%s" type="DiffuseSource">\n' % GDn
    spec = '\t<spectrum type="PowerLaw">\n'
    spec += '\t\t<parameter free="1" max="10" min="0" name="Prefactor" scale="1" value="1"/>\n'
    spec += '\t\t<parameter free="0" max="1" min="-1" name="Index" scale="1.0" value="0"/>\n'
    spec += '\t\t<parameter free="0" max="2e2" min="5e1" name="Scale" scale="1.0" value="1e2"/>\n'
    spec += '\t</spectrum>\n'
    skydir = '\t<spatialModel file="%s" type="MapCubeFunction">\n' % GD
    skydir += '\t\t<parameter free="0" max="1e3" min="1e-3" name="Normalization" scale="1.0" value="1.0"/>\n'
    skydir += '\t</spatialModel>\n'
    skydir += '</source>'
    (src, ) = (Name + spec + skydir, )
    galdiff = pS(src).getElementsByTagName('source')[0]
    galdiff.writexml(model)
    model.write('\n')
    if ISO == None:  #null means no file so assume user wants an isotropic power law component
        Name = '<source name="%s" type="DiffuseSource">\n' % ISOn
        spec = '\t<spectrum type="PowerLaw">\n'
        spec += '\t\t<parameter free="1" max="1e3" min="1e-3" name="Prefactor" scale="1e-7" value="1"/>\n'
        spec += '\t\t<parameter free="1" max="-1.0" min="-3.5" name="Index" scale="1.0" value="-2.1"/>\n'
        spec += '\t\t<parameter free="0" max="2e2" min="5e1" name="Scale" scale="1.0" value="1e2"/>\n'
        spec += '\t</spectrum>\n'
    else:  #if a file is given assume it is an isotropic template
        Name = '<source name="%s" type="DiffuseSource">\n' % ISOn
        spec = '\t<spectrum type="FileFunction" file="%s">\n' % ISO
        spec += '\t\t<parameter free="1" max="10" min="1e-2" name="Normalization" scale="1" value="1"/>\n'
        spec += '\t</spectrum>\n'
    #both of the above options use the same spatial model
    skydir = '\t<spatialModel type="ConstantValue">\n'
    skydir += '\t\t<parameter free="0" max="10.0" min="0.0" name="Value" scale="1.0" value="1.0"/>\n'
    skydir += '\t</spatialModel>\n'
    skydir += '</source>'
    (src, ) = (Name + spec + skydir, )
    iso = pS(src).getElementsByTagName('source')[0]
    iso.writexml(model)
    model.write('\n</source_library>')
    model.close()
    return
Exemplo n.º 3
0
def addSrcs2(sL,GD,GDn,ISO,ISOn,signif):
	model=open(sL.out,'w') #open file in write mode, overwrites other files of same name
	file=pyfits.open(sL.srcs) #open source list file and access necessary fields, requires LAT source catalog definitions and names
	data=file[1].data
	extendedinfo=file[4].data
	extName=extendedinfo.field('Source_Name')	
	extFile=extendedinfo.field('Spatial_Filename')
	name=data.field('Source_Name')
	ExtName=data.field('Extended_Source_Name')
	ra=data.field('RAJ2000')
	dec=data.field('DEJ2000')
	flux=data.field('Flux_Density')
	pivot=data.field('Pivot_Energy')
	index=data.field('Spectral_Index')
	cutoff=data.field('Cutoff')
	spectype=data.field('SpectrumType')
	beta=data.field('beta')
	#extended=data.field('Extended')
	sigma=data.field('Signif_Avg')
	model.write('<?xml version="1.0" ?>\n')
	model.write('<source_library title="source library">\n')
	model.write('\n<!-- Point Sources -->\n')
	step=(sL.roi[2]+5)/5 #divide ROI radius plus 5 degrees into 5 steps for ordering of sources, get next highest int for ease
	i=1
	radii=[]
	ptSrcNum=0
	extSrcNum=0
	while i<6:
		if i*step<=sL.roi[2]+5:
			radii+=[step*i]
		else:
			radii+=[sL.roi[2]+5] #just in case of rounding errors
		i+=1
	for x in radii:
		if x==sL.roi[2]+5.:
			model.write('\n<!-- Sources between [%s,%s] degrees of ROI center -->\n' %(x-step,x))
		else:
			model.write('\n<!-- Sources between [%s,%s) degrees of ROI center -->\n' %(x-step,x))
		for n,f,i,r,d,p,c,t,b,S,EN in zip(name,flux,index,ra,dec,pivot,cutoff,spectype,beta,sigma,ExtName):
			dist=angsep(sL.roi[0],sL.roi[1],r,d) #check that source is within ROI radius + 5 degress of ROI center
			if r==sL.roi[0] and d==sL.roi[1]:
				dist=0.0
			if (dist<x and dist>=x-step) or (x==sL.roi[2]+5. and dist==x):
				sn=''
				for N in n.split(' '):
					sn+=N
				if EN!='' and not sL.psF:
					extSrcNum+=1
					if EN[0].isdigit():#use the extended source name to set these apart even further
						Name='<source name="_%s" type="DiffuseSource">\n' %EN
					else:
						Name='<source name="%s" type="DiffuseSource">\n' %EN
				else:
					ptSrcNum+=1
					if sn[0].isdigit():
						Name='<source name="_%s" type="PointSource">\n' %sn
					else:
						Name='<source name="%s" type="PointSource">\n' %sn
				if EN!='VelaX' and EN!='MSH15-52':
					if t=='PowerLaw':
						spec=PLspec(sL,f,i,p,dist,S,signif)
					elif t=='PowerLaw2':#no value for flux from 100 MeV to 100 GeV in fits file0
						if i!=1.:#so calculate it by integrating PowerLaw spectral model
							F=f*p**i/(-i+1)*(1.e5**(-i+1)-1.e2**(-1+1))
						else:
							F=f*p*log(1.e3)
						spec=PL2spec(sL,F,i,dist,S,signif)
					elif t=='LogParabola':
						spec=LPspec(sL,f,i,p,b,dist,S,signif)
					else:
						spec=COspec(sL,f,i,p,c,dist,S,signif)
				else:
					if EN=='VelaX':
						spec=VXspec(sL,i,dist)
					else:
						spec=MSHspec(sL,i,dist)
				if EN!='' and not sL.psF:
					eFile=None
					for exN,exf in zip(extName,extFile):
						if exN.replace(' ','')==EN:
							if len(sL.extD)>0:
								if sL.extD[-1]=='/':
									eFile=sL.extD+exf
								else:
									eFile=sL.extD+'/'+exf
							else:
								eFile=exf
							break
					if eFile==None:
						skydir='\t<spatialModel file="%s" type="SpatialMap">\n'%sL.extD
						print 'Extended source %s (%s) in ROI, could not find name of matching template file.'%(EN,sn)
					else:
						skydir='\t<spatialModel file="%s" type="SpatialMap">\n'%eFile
						print 'Extended source %s (%s) in ROI, verify that %s is the correct path.'%(EN,sn,eFile)
					skydir+='\t\t<parameter free="0" max="1000" min="0.001" name="Prefactor" scale="1" value="1"/>\n'
					skydir+='\t</spatialModel>\n'
				else:
					skydir='\t<spatialModel type="SkyDirFunction">\n'
					skydir+='\t\t<parameter free="0" max="360.0" min="-360.0" name="RA" scale="1.0" value="%s"/>\n' %r
					skydir+='\t\t<parameter free="0" max="90" min="-90" name="DEC" scale="1.0" value="%s"/>\n' %d
					skydir+='\t</spatialModel>\n'
				skydir+='</source>'
				(src,)=(Name+spec+skydir,)
				ptsrc=pS(src).getElementsByTagName('source')[0]
				ptsrc.writexml(model)
				model.write('\n')
	file.close() #close file
	if not sL.psF:
		print 'Added %i point sources and %i extended sources'%(ptSrcNum,extSrcNum)
		if extSrcNum>0:
			print 'If using unbinned likelihood you will need to rerun gtdiffrsp for the extended sources or rerun the makeModel function with optional argument psForce=True'
	else:
		print 'Added %i point sources, note that any extended sources in ROI were modeled as point sources becaue psForce option was set to True'%ptSrcNum
	#add galactic diffuse with PL spectrum, fix index to zero for general use, those who want it to be free can unfreeze parameter manually
	model.write('\n<!-- Diffuse Sources -->\n')
	Name='\n<source name="%s" type="DiffuseSource">\n' %GDn
	spec='\t<spectrum type="PowerLaw">\n'
	spec+='\t\t<parameter free="1" max="10" min="0" name="Prefactor" scale="1" value="1"/>\n'
	spec+='\t\t<parameter free="0" max="1" min="-1" name="Index" scale="1.0" value="0"/>\n'
	spec+='\t\t<parameter free="0" max="2e2" min="5e1" name="Scale" scale="1.0" value="1e2"/>\n'
	spec+='\t</spectrum>\n'
	skydir='\t<spatialModel file="%s" type="MapCubeFunction">\n' %GD
	skydir+='\t\t<parameter free="0" max="1e3" min="1e-3" name="Normalization" scale="1.0" value="1.0"/>\n'
	skydir+='\t</spatialModel>\n'
	skydir+='</source>'
	(src,)=(Name+spec+skydir,)
	galdiff=pS(src).getElementsByTagName('source')[0]
	galdiff.writexml(model)
	model.write('\n')
	if ISO==None: #null means no file so assume user wants an isotropic power law component
		Name='<source name="%s" type="DiffuseSource">\n' %ISOn
		spec='\t<spectrum type="PowerLaw">\n'
		spec+='\t\t<parameter free="1" max="1e3" min="1e-3" name="Prefactor" scale="1e-7" value="1"/>\n'
		spec+='\t\t<parameter free="1" max="-1.0" min="-3.5" name="Index" scale="1.0" value="-2.1"/>\n'
		spec+='\t\t<parameter free="0" max="2e2" min="5e1" name="Scale" scale="1.0" value="1e2"/>\n'
		spec+='\t</spectrum>\n'
	else: #if a file is given assume it is an isotropic template
		Name='<source name="%s" type="DiffuseSource">\n' %ISOn
		spec='\t<spectrum type="FileFunction" file="%s">\n' %ISO
		spec+='\t\t<parameter free="1" max="10" min="1e-2" name="Normalization" scale="1" value="1"/>\n'
		spec+='\t</spectrum>\n'
	#both of the above options use the same spatial model
	skydir='\t<spatialModel type="ConstantValue">\n'
	skydir+='\t\t<parameter free="0" max="10.0" min="0.0" name="Value" scale="1.0" value="1.0"/>\n'
	skydir+='\t</spatialModel>\n'
	skydir+='</source>'
	(src,)=(Name+spec+skydir,)
	iso=pS(src).getElementsByTagName('source')[0]
	iso.writexml(model)	
	model.write('\n</source_library>')
	model.close()
	return
Exemplo n.º 4
0
def addSrcs1(sL, GD, GDn, ISO, ISOn, signif):
    model = open(
        sL.out,
        'w')  #open file in write mode, overwrites other files of same name
    file = pyfits.open(
        sL.srcs
    )  #open source list file and access necessary fields, requires LAT source catalog definitions and names
    data = file[1].data
    try:
        name = data.field('Source_Name')
    except:
        name = data.field('NickName')
    ra = data.field('RA')
    dec = data.field('DEC')
    flux = data.field('Flux_Density')
    pivot = data.field('Pivot_Energy')
    index = data.field('Spectral_Index')
    sigma = data.field('Signif_Avg')
    model.write('<?xml version="1.0" ?>\n')
    model.write('<source_library title="source library">\n')
    model.write('\n<!-- Point Sources -->\n')
    step = (
        sL.roi[2] + 5
    ) / 5  #divide ROI radius plus 5 degrees into 5 steps for ordering of sources, get next highest int for ease
    i = 1
    radii = []
    while i < 6:
        if i * step <= sL.roi[2] + 5:
            radii += [step * i]
        else:
            radii += [sL.roi[2] + 5]  #just in case of rounding errors
        i += 1
    for x in radii:
        if x == sL.roi[2] + 5.:
            model.write(
                '\n<!-- Sources between [%s,%s] degrees of ROI center -->\n' %
                (x - step, x))
        else:
            model.write(
                '\n<!-- Sources between [%s,%s) degrees of ROI center -->\n' %
                (x - step, x))
        for n, f, i, r, d, p, s in zip(name, flux, index, ra, dec, pivot,
                                       sigma):
            dist = angsep(
                sL.roi[0], sL.roi[1], r, d
            )  #check that source is within ROI radius + 5 degress of ROI center
            if (dist < x and dist >= x - step) or (x == sL.roi[2] + 5.
                                                   and dist == x):
                fscale = int(floor(log10(f)))
                sn = ''
                for N in n.split(' '):
                    sn += N
                if sn[0].isdigit():
                    Name = '<source name="_%s" type="PointSource">\n' % sn
                else:
                    Name = '<source name="%s" type="PointSource">\n' % sn
                spec = '\t<spectrum type="PowerLaw">\n'
                spec += '\t<!-- Source is %s degrees away from ROI center -->\n' % dist
                if (dist > sL.roi[2]
                    ):  #if beyond ROI, shouldn't attempt to fit parameters
                    spec += '\t<!-- Source is outside ROI, all parameters should remain fixed -->\n'
                    spec += '\t\t<parameter free="0" max="1e4" min="1e-4" name="Prefactor" scale="1e%i" value="%s"/>\n' % (
                        fscale, f / 10**fscale)
                    spec += '\t\t<parameter free="0" max="5.0" min="0.0" name="Index" scale="-1.0" value="%s"/>\n' % i
                elif (dist > sL.radLim):
                    spec += '\t<!-- Source is outside specified radius limit of %s -->\n' % sL.radLim
                    spec += '\t\t<parameter free="0" max="1e4" min="1e-4" name="Prefactor" scale="1e%i" value="%s"/>\n' % (
                        fscale, f / 10**fscale)
                    spec += '\t\t<parameter free="0" max="5.0" min="0.0" name="Index" scale="-1.0" value="%s"/>\n' % i
                elif s < signif:
                    spec += '\t<!-- Source significance %s is less than specified limit of %s -->\n' % (
                        s, signif)
                    spec += '\t\t<parameter free="0" max="1e4" min="1e-4" name="Prefactor" scale="1e%i" value="%s"/>\n' % (
                        fscale, f / 10**fscale)
                    spec += '\t\t<parameter free="0" max="5.0" min="0.0" name="Index" scale="-1.0" value="%s"/>\n' % i
                else:
                    spec += '\t\t<parameter free="1" max="1e4" min="1e-4" name="Prefactor" scale="1e%i" value="%s"/>\n' % (
                        fscale, f / 10**fscale)
                    spec += '\t\t<parameter free="1" max="5.0" min="0.0" name="Index" scale="-1.0" value="%s"/>\n' % i
                spec += '\t\t<parameter free="0" max="5e5" min="30" name="Scale" scale="1.0" value="%f"/>\n' % p
                spec += '\t</spectrum>\n'
                skydir = '\t<spatialModel type="SkyDirFunction">\n'
                skydir += '\t\t<parameter free="0" max="360.0" min="-360.0" name="RA" scale="1.0" value="%s"/>\n' % r
                skydir += '\t\t<parameter free="0" max="90" min="-90" name="DEC" scale="1.0" value="%s"/>\n' % d
                skydir += '\t</spatialModel>\n'
                skydir += '</source>'
                (src, ) = (Name + spec + skydir, )
                ptsrc = pS(src).getElementsByTagName('source')[0]
                ptsrc.writexml(model)
                model.write('\n')
    file.close()  #close file
    #add galactic diffuse with PL spectrum, fix index to zero for general use, those who want it to be free can unfreeze parameter manually
    model.write('\n<!-- Diffuse Sources -->\n')
    Name = '\n<source name="CO" type="DiffuseSource">\n'
    spec = '\t<spectrum type="PowerLaw2">\n'
    spec += '\t\t<parameter free="1" max="1e4" min="1e-4" name="Integral" scale="1e-8" value="1.8"/>\n'
    spec += '\t\t<parameter free="0" max="1" min="-4" name="Index" scale="1.0" value="-2"/>\n'
    spec += '\t\t<parameter free="0" max="200000.0" min="20.0" name="LowerLimit" scale="1.0" value="%s" />\n' % Inputs[
        'emin'][1]
    spec += '\t\t<parameter free="0" max="200000.0" min="20.0" name="UpperLimit" scale="1.0" value="%s"/>\n' % Inputs[
        'emax'][1]
    spec += '\t</spectrum>\n'
    skydir = '\t<spatialModel file="%s" type="SpatialMap">\n' % fl['COmp']
    skydir += '\t\t<parameter free="0" max="1e3" min="1e-3" name="Prefactor" scale="1.0" value="1.0"/>\n'
    skydir += '\t</spatialModel>\n'
    skydir += '</source>'
    (src, ) = (Name + spec + skydir, )
    galdiff = pS(src).getElementsByTagName('source')[0]
    galdiff.writexml(model)
    model.write('\n')

    Name = '\n<source name="HI" type="DiffuseSource">\n'
    spec = '\t<spectrum type="PowerLaw2">\n'
    spec += '\t\t<parameter free="1" max="1e4" min="1e-4" name="Integral" scale="1e-6" value="1.8"/>\n'
    spec += '\t\t<parameter free="0" max="1" min="-4" name="Index" scale="1.0" value="-2"/>\n'
    spec += '\t\t<parameter free="0" max="200000.0" min="20.0" name="LowerLimit" scale="1.0" value="%s" />\n' % Inputs[
        'emin'][1]
    spec += '\t\t<parameter free="0" max="200000.0" min="20.0" name="UpperLimit" scale="1.0" value="%s"/>\n' % Inputs[
        'emax'][1]
    spec += '\t</spectrum>\n'
    skydir = '\t<spatialModel file="%s" type="SpatialMap">\n' % fl['HImp']
    skydir += '\t\t<parameter free="0" max="1e3" min="1e-3" name="Prefactor" scale="1.0" value="1.0"/>\n'
    skydir += '\t</spatialModel>\n'
    skydir += '</source>'
    (src, ) = (Name + spec + skydir, )
    galdiff = pS(src).getElementsByTagName('source')[0]
    galdiff.writexml(model)
    model.write('\n')
    if ISO == None:  #null means no file so assume user wants an isotropic power law component
        Name = '<source name="%s" type="DiffuseSource">\n' % ISOn
        spec = '\t<spectrum type="PowerLaw">\n'
        spec += '\t\t<parameter free="1" max="1e3" min="1e-3" name="Prefactor" scale="1e-7" value="1"/>\n'
        spec += '\t\t<parameter free="1" max="-1.0" min="-3.5" name="Index" scale="1.0" value="-2.1"/>\n'
        spec += '\t\t<parameter free="0" max="2e2" min="5e1" name="Scale" scale="1.0" value="1e2"/>\n'
        spec += '\t</spectrum>\n'
    else:  #if a file is given assume it is an isotropic template
        Name = '<source name="%s" type="DiffuseSource">\n' % ISOn
        spec = '\t<spectrum type="FileFunction" file="%s">\n' % ISO
        spec += '\t\t<parameter free="1" max="10" min="1e-2" name="Normalization" scale="1" value="1"/>\n'
        spec += '\t</spectrum>\n'
    #both of the above options use the same spatial model
    skydir = '\t<spatialModel type="ConstantValue">\n'
    skydir += '\t\t<parameter free="0" max="10.0" min="0.0" name="Value" scale="1.0" value="1.0"/>\n'
    skydir += '\t</spatialModel>\n'
    skydir += '</source>'
    (src, ) = (Name + spec + skydir, )
    iso = pS(src).getElementsByTagName('source')[0]
    iso.writexml(model)
    model.write('\n</source_library>')
    model.close()
    return
Exemplo n.º 5
0
def addSrcs1(sL,GD,GDn,ISO,ISOn,signif):
	model=open(sL.out,'w') #open file in write mode, overwrites other files of same name
	file=pyfits.open(sL.srcs) #open source list file and access necessary fields, requires LAT source catalog definitions and names
	data=file[1].data
	try:
		name=data.field('Source_Name')
	except:
		name=data.field('NickName')
	ra=data.field('RA')
	dec=data.field('DEC')
	flux=data.field('Flux_Density')
	pivot=data.field('Pivot_Energy')
	index=data.field('Spectral_Index')
	sigma=data.field('Signif_Avg')
	model.write('<?xml version="1.0" ?>\n')
	model.write('<source_library title="source library">\n')
	model.write('\n<!-- Point Sources -->\n')
	step=(sL.roi[2]+5)/5 #divide ROI radius plus 5 degrees into 5 steps for ordering of sources, get next highest int for ease
	i=1
	radii=[]
	while i<6:
		if i*step<=sL.roi[2]+5:
			radii+=[step*i]
		else:
			radii+=[sL.roi[2]+5] #just in case of rounding errors
		i+=1
	for x in radii:
		if x==sL.roi[2]+5.:
			model.write('\n<!-- Sources between [%s,%s] degrees of ROI center -->\n' %(x-step,x))
		else:
			model.write('\n<!-- Sources between [%s,%s) degrees of ROI center -->\n' %(x-step,x))
		for n,f,i,r,d,p,s in zip(name,flux,index,ra,dec,pivot,sigma):
			dist=angsep(sL.roi[0],sL.roi[1],r,d) #check that source is within ROI radius + 5 degress of ROI center
			if (dist<x and dist>=x-step) or (x==sL.roi[2]+5. and dist==x):
				fscale=int(floor(log10(f)))
				sn=''
				for N in n.split(' '):
					sn+=N
				if sn[0].isdigit():
						Name='<source name="_%s" type="PointSource">\n' %sn
				else:
					Name='<source name="%s" type="PointSource">\n' %sn
				spec='\t<spectrum type="PowerLaw">\n'
				spec+='\t<!-- Source is %s degrees away from ROI center -->\n' %dist
				if(dist>sL.roi[2]): #if beyond ROI, shouldn't attempt to fit parameters
					spec+='\t<!-- Source is outside ROI, all parameters should remain fixed -->\n'
					spec+='\t\t<parameter free="0" max="1e4" min="1e-4" name="Prefactor" scale="1e%i" value="%s"/>\n' %(fscale,f/10**fscale)
					spec+='\t\t<parameter free="0" max="5.0" min="0.0" name="Index" scale="-1.0" value="%s"/>\n' %i
				elif(dist>sL.radLim):
					spec+='\t<!-- Source is outside specified radius limit of %s -->\n'%sL.radLim
					spec+='\t\t<parameter free="0" max="1e4" min="1e-4" name="Prefactor" scale="1e%i" value="%s"/>\n' %(fscale,f/10**fscale)
					spec+='\t\t<parameter free="0" max="5.0" min="0.0" name="Index" scale="-1.0" value="%s"/>\n' %i
				elif s<signif:
					spec+='\t<!-- Source significance %s is less than specified limit of %s -->\n' %(s,signif)
					spec+='\t\t<parameter free="0" max="1e4" min="1e-4" name="Prefactor" scale="1e%i" value="%s"/>\n' %(fscale,f/10**fscale)
					spec+='\t\t<parameter free="0" max="5.0" min="0.0" name="Index" scale="-1.0" value="%s"/>\n' %i
				else:
					spec+='\t\t<parameter free="1" max="1e4" min="1e-4" name="Prefactor" scale="1e%i" value="%s"/>\n' %(fscale,f/10**fscale)
					spec+='\t\t<parameter free="1" max="5.0" min="0.0" name="Index" scale="-1.0" value="%s"/>\n' %i
				spec+='\t\t<parameter free="0" max="5e5" min="30" name="Scale" scale="1.0" value="%f"/>\n' %p
				spec+='\t</spectrum>\n'
				skydir='\t<spatialModel type="SkyDirFunction">\n'
				skydir+='\t\t<parameter free="0" max="360.0" min="-360.0" name="RA" scale="1.0" value="%s"/>\n' %r
				skydir+='\t\t<parameter free="0" max="90" min="-90" name="DEC" scale="1.0" value="%s"/>\n' %d
				skydir+='\t</spatialModel>\n'
				skydir+='</source>'
				(src,)=(Name+spec+skydir,)
				ptsrc=pS(src).getElementsByTagName('source')[0]
				ptsrc.writexml(model)
				model.write('\n')
	file.close() #close file
	#add galactic diffuse with PL spectrum, fix index to zero for general use, those who want it to be free can unfreeze parameter manually
	model.write('\n<!-- Diffuse Sources -->\n')
	Name='\n<source name="%s" type="DiffuseSource">\n' %GDn
	spec='\t<spectrum type="PowerLaw">\n'
	spec+='\t\t<parameter free="1" max="10" min="0" name="Prefactor" scale="1" value="1"/>\n'
	spec+='\t\t<parameter free="0" max="1" min="-1" name="Index" scale="1.0" value="0"/>\n'
	spec+='\t\t<parameter free="0" max="2e2" min="5e1" name="Scale" scale="1.0" value="1e2"/>\n'
	spec+='\t</spectrum>\n'
	skydir='\t<spatialModel file="%s" type="MapCubeFunction">\n' %GD
	skydir+='\t\t<parameter free="0" max="1e3" min="1e-3" name="Normalization" scale="1.0" value="1.0"/>\n'
	skydir+='\t</spatialModel>\n'
	skydir+='</source>'
	(src,)=(Name+spec+skydir,)
	galdiff=pS(src).getElementsByTagName('source')[0]
	galdiff.writexml(model)
	model.write('\n')
	if ISO==None: #null means no file so assume user wants an isotropic power law component
		Name='<source name="%s" type="DiffuseSource">\n' %ISOn
		spec='\t<spectrum type="PowerLaw">\n'
		spec+='\t\t<parameter free="1" max="1e3" min="1e-3" name="Prefactor" scale="1e-7" value="1"/>\n'
		spec+='\t\t<parameter free="1" max="-1.0" min="-3.5" name="Index" scale="1.0" value="-2.1"/>\n'
		spec+='\t\t<parameter free="0" max="2e2" min="5e1" name="Scale" scale="1.0" value="1e2"/>\n'
		spec+='\t</spectrum>\n'
	else: #if a file is given assume it is an isotropic template
		Name='<source name="%s" type="DiffuseSource">\n' %ISOn
		spec='\t<spectrum type="FileFunction" file="%s">\n' %ISO
		spec+='\t\t<parameter free="1" max="10" min="1e-2" name="Normalization" scale="1" value="1"/>\n'
		spec+='\t</spectrum>\n'
	#both of the above options use the same spatial model
	skydir='\t<spatialModel type="ConstantValue">\n'
	skydir+='\t\t<parameter free="0" max="10.0" min="0.0" name="Value" scale="1.0" value="1.0"/>\n'
	skydir+='\t</spatialModel>\n'
	skydir+='</source>'
	(src,)=(Name+spec+skydir,)
	iso=pS(src).getElementsByTagName('source')[0]
	iso.writexml(model)	
	model.write('\n</source_library>')
	model.close()
	return