crabextent.py

Buehler Rolf, 07/25/2014 10:01 AM

Download (6.43 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="ellipdisk",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="irf_file.fits",\
64
                  caldb="$PWD/caldb/data/cta/aar/bcf/DESY20140105_50h/")
65
    ob.id("run_1")
66
    
67
    #----------------------------------------------------
68
    # Create background model
69
    #----------------------------------------------------
70
    spec = gl.GModelSpectralPlaw(1,0,gl.GEnergy(1.0,"TeV"))
71
    filename="$PWD/caldb/data/cta/aar/bcf/DESY20140105_50h/irf_file.fits"
72
    bck = gl.GCTAModelIrfBackground(spec)
73
    bck.name("Background_run_1")
74
    bck.instruments("CTA")
75

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

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

    
145
if __name__ == '__main__':
146
    #----------------------------------------------------
147
    # Run either in multiprocesing or single core
148
    #----------------------------------------------------
149
    simcrab()
150