crabextent.py

Buehler Rolf, 03/18/2015 03:39 PM

Download (6.41 KB)

 
1
#! /usr/bin/env python 
2
# ==========================================================================
3
# This script simulates CTA observations of the Crab nebula and assesses
4
# to which extend a nebula extension can be detected. Several spatial and
5
# spectral models are tested
6
# 
7
# Author: Rolf Buehler (rolf.buehler@desy.de)
8
# Date: 20.3.2014
9
# ==========================================================================
10
import gammalib as gl
11
from ctools import obsutils
12
import time
13
import os
14
import shutil
15
import ctools as ct
16
#import spectrum
17
#import numpy as np
18
#import json
19
#import dicdata
20

    
21
def printandlog(text,tlastlog,logfile,spatial_type,toscreen=True):
22
    """Helper function to print to screen and log
23
    @param  [char]     Text text to print
24
    @param  [time]     Time last log entry was written
25
    @param  [file]     Log file to write to
26
    @param  [char]     Spatial model
27
    @param  [toscreen] Print also to screen
28
    @return [time]     Time log entry was written out
29
    """
30
    currenttime= time.time()
31
    fulltext=spatial_type+": "+text+"\n"+spatial_type+": (elapsed: "+str(currenttime-tlastlog)+" s)\n"
32
    if toscreen:
33
        print fulltext
34
    logfile.write(fulltext)
35
    return currenttime
36

    
37
def simcrab(obstime=0.5*3600,write=True,spatial_type="gauss",dospec=False):
38
    """"Simulates and fits crab & background for one run
39
    @param [float] obstime  Observation duration in seconds
40
    @param [bool]  write    Write out simulated observations adn fit results
41
    """
42
    #-----------------------------------------------------
43
    #create sub-folder and setup log to write profiling
44
    #-----------------------------------------------------
45
    if os.path.isdir(spatial_type):
46
        print "Deleting directory:",spatial_type
47
        shutil.rmtree(spatial_type)
48
    os.mkdir(spatial_type)
49
    os.chdir(spatial_type)
50
    logfile = open("log_"+spatial_type+".log","w")
51
    lastlogtime=printandlog("Starting. Obstime is "+str(obstime)+" s",time.time(),logfile,spatial_type)
52
    
53
    #-----------------------------------------------------
54
    #Create one observation (run)
55
    #-----------------------------------------------------
56
    ra_degree=83.633212         #Crab position from NED
57
    dec_degree=22.014460 
58
    radius=8
59
    offset_degree=-1            #Observing offset in dec from Crab in deg
60
    pntdir = gl.GSkyDir()
61
    pntdir.radec_deg(ra_degree, dec_degree+offset_degree) 
62
    ob = obsutils.set_obs(pntdir,tstart=0.0,duration=obstime,deadc=0.95, \
63
                  emin=0.1, emax=100.0, rad=radius, irf="DESY20140105_50h", caldb="aar")
64
    ob.id("run_1")
65
    
66
    #----------------------------------------------------
67
    # Create background model
68
    #----------------------------------------------------
69
    spec = gl.GModelSpectralPlaw(1,0,gl.GEnergy(1.0,"TeV"))
70
    bck = gl.GCTAModelIrfBackground(spec)
71
    bck.name("Background_run_1")
72
    bck.instruments("CTA")
73

    
74
    #----------------------------------------------------
75
    # Create Crab nebula model
76
    # Extension of the Crab in optical is approximatelly an
77
    # ellipse of: 0.12deg*0.08deg
78
    #----------------------------------------------------
79
    fixallpars=False
80
    crabdir = gl.GSkyDir()
81
    crabdir.radec_deg(ra_degree, dec_degree)
82
    if spatial_type=="point":
83
        crab_spatial = gl.GModelSpatialPointSource(crabdir)
84
    elif spatial_type=="ellipdisk":
85
        crab_spatial = gl.GModelSpatialEllipticalDisk(crabdir,0.025,0.015,90.)
86
    elif spatial_type=="raddisk":
87
        crab_spatial = gl.GModelSpatialRadialDisk(crabdir,0.02)
88
    elif spatial_type=="gauss":
89
        crab_spatial = gl.GModelSpatialRadialGauss(crabdir, 0.02)
90
    if fixallpars:
91
        for par in range(0,crab_spatial.size()):
92
            crab_spatial[par].fix()
93
    #crab_spectrum = gl.GModelSpectralPlaw(3.45e-17, -2.63,gl.GEnergy(1,"TeV") ) #from HESS 2006
94
    #crab_spectrum = gl.GModelSpectralPlaw2(2.26e-11,-2.63,gl.GEnergy(1,"TeV"),gl.GEnergy(100,"TeV"))
95
    crab_spectrum = gl.GModelSpectralLogParabola(3.2e-17,-2.47,gl.GEnergy(1,"TeV"),-0.24) # From MAGIC 2014c
96
    
97
    crab = gl.GModelSky(crab_spatial, crab_spectrum)
98
    crab.name("CrabNebula")
99
    crab.ids("")
100

    
101
    #----------------------------------------------------
102
    # Create GObservations and add models
103
    #----------------------------------------------------
104
    obs = gl.GObservations()
105
    obs.append(ob)
106
    obs.models().append(bck)
107
    obs.models().append(crab)
108
    
109
    #----------------------------------------------------
110
    # Simulate, fit and write out
111
    #----------------------------------------------------
112
    obssim = obsutils.sim(obs, log=write, debug=False, edisp=False, seed=0)
113
    lastlogtime=printandlog("Simulated..",lastlogtime,logfile,spatial_type)
114
    if write:
115
        degperpix=0.05
116
        npix=200
117
        obssim.save("crabextsim.xml")
118
        obssim.models().save("crabextsim_models.xml")
119
        obsutils.cntmap(obssim, proj="TAN", coord="EQU", xval=ra_degree, yval=dec_degree+offset_degree, \
120
                    binsz=degperpix, nxpix=npix, nypix=npix, outname="crabextsim_cntmap.fits")
121
        lastlogtime=printandlog("Created counts map..",lastlogtime,logfile,spatial_type)
122
        obsutils.modmap(obssim, eref=0.1, proj="TAN", coord="EQU", xval=ra_degree, yval=dec_degree+offset_degree, \
123
                    binsz=degperpix, nxpix=npix, nypix=npix, outname="crabextsim_modmap.fits")
124
        lastlogtime=printandlog("Created model map..",lastlogtime,logfile,spatial_type)
125
        for ob in obssim:
126
            events = ob.events()
127
            events.save("crabextsim_events_run_1.fits")
128
    like=obsutils.fit(obssim,log=True, debug=False, edisp=False)
129
    lastlogtime=printandlog("Fitted..",lastlogtime,logfile,spatial_type)
130
    print "TS is",like.obs().models()["CrabNebula"].ts()
131
    
132
    if dospec:
133
        spec = obsutils.specpoints(obssim,"CrabNebula",obsutils.getlogbins())
134
        json.dump(spec,open("spectrum.json","w"),indent=4)
135
        lastlogtime=printandlog("Done Spectrum..",lastlogtime,logfile,spatial_type)
136
    
137
    #----------------------------------------------------
138
    # Close file and change back directory
139
    #----------------------------------------------------
140
    logfile.close()
141
    os.chdir("..")
142

    
143
if __name__ == '__main__':
144
    #----------------------------------------------------
145
    # Run either in multiprocesing or single core
146
    #----------------------------------------------------
147
    simcrab(spatial_type="point")
148
    simcrab(spatial_type="raddisk")
149
    simcrab(spatial_type="gauss")
150
    simcrab(spatial_type="ellipdisk")
151