crabextent.py

Knödlseder Jürgen, 10/30/2014 11:27 AM

Download (6.4 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="DESY20140105_50h",\
64
                  caldb="aar")
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
    crab.tscalc(True)
103

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

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