simulation.py

Complete script - Tiziani Domenico, 03/26/2019 10:54 AM

Download (4.61 KB)

 
1
import gammalib
2
import ctools
3
import cscripts
4
import matplotlib.pyplot as plt
5
import numpy as np
6
from astropy.wcs import WCS
7

    
8
# Init observation
9
runlist = [20136]
10

    
11
cobs = cscripts.csiactobs()
12
cobs["prodname"] = "hess_dl3_dr1"
13
cobs["bkgpars"] = 2
14
cobs["psf_hiera"] = "psf_table"
15
cobs["debug"] = True
16
cobs["bkg_mod_hiera"] = "aeff"
17

    
18
cobs.runlist(runlist)
19
cobs.run()
20

    
21
observation = cobs.obs().copy()
22

    
23
# Select events
24
select = ctools.ctselect(observation)
25
select["usepnt"] = True
26
select["usethres"] = "DEFAULT"
27
select["rad"] = 2.5
28
select["emin"] = 0.2
29
select["emax"] = 92
30
select.run()
31

    
32
sel_observation = select.obs().copy()
33

    
34

    
35
# Build radial disk model
36
spec = gammalib.GModelSpectralPlaw(1e-14, -2.0, gammalib.GEnergy(1.0, 'TeV'))
37
spec['Prefactor'].fix()
38
spec['Index'].fix()
39

    
40
ra = 228.53
41
dec = -59.16
42

    
43
direction = gammalib.GSkyDir()
44
direction.radec_deg(ra,dec)
45
spat = gammalib.GModelSpatialRadialDisk(direction, 1.0)
46
spat["RA"].fix()
47
spat["DEC"].fix()
48
spat["Radius"].fix()
49

    
50
sourceModel = gammalib.GModelSky(spat, spec)
51

    
52
models = gammalib.GModels()
53
models.append(sourceModel)
54

    
55
sel_observation.models(models)
56

    
57
# Simulate observation
58
sim = ctools.ctobssim(sel_observation)
59
sim['debug'] = True
60
sim['nthreads'] = 40
61
sim['emin'] = 0.2
62
sim['emax'] = 91
63
sim['seed'] = 0
64
sim['tmin'] = "UNDEF"
65
sim.run()
66
sim_obs = sim.obs().copy()
67

    
68
# Bin observation
69
binpars = {'ebinalg': 'LOG', 'emin': 0.1, 'emax': 100,
70
           'enumbins': 24, 'nxpix': 150, 'nypix': 150,
71
           'binsz': 0.02, 'coordsys': "CEL", 'xref': 228.53,
72
           'yref': -59.16, 'proj': "CAR"}
73

    
74
cbin = ctools.ctbin(sim_obs.copy())
75
cbin.pardict(binpars)
76
cbin['debug'] = True
77
cbin.run()
78

    
79
cntcube = cbin.cube().copy()
80

    
81
# Model observation
82
mcube = ctools.ctmodel(sim_obs)
83
mcube.pardict(binpars)
84
mcube['incube'] = "NONE"
85
mcube['debug'] = True
86
mcube['nthreads'] = 30
87
mcube.run()
88

    
89
modcube = mcube.cube().copy()
90

    
91
# Compare counts and model cubes (note the difference in number of events)
92
print "Counts cube:"
93
print cntcube
94
print "\n Model cube:"
95
print modcube
96

    
97
# Generate resmap
98
cres = cscripts.csresmap(sim_obs)
99
cres.pardict(binpars)
100
cres['algorithm'] = "SUB"
101
cres.run()
102

    
103
# Define some helper functions for plotting
104
def get_wcs_from_skymap(skymap):
105
    from astropy.wcs import WCS
106
    import numpy as np
107
    pro = skymap.projection()
108

    
109
    wcs = WCS(naxis=2)
110
    wcs.wcs.crpix = [pro.crpix(0), pro.crpix(1)]
111
    wcs.wcs.cdelt = np.array([pro.cdelt(0), pro.cdelt(1)])
112
    wcs.wcs.crval = [pro.crval(0), pro.crval(1)]
113
    ctype_1 = "RA--" if pro.coordsys() == "EQU" else "GLON"
114
    ctype_1 += "-" + pro.code()
115
    ctype_2 = "DEC-" if pro.coordsys() == "EQU" else "GLAT"
116
    ctype_2 += "-" + pro.code()
117
    wcs.wcs.ctype = [ctype_1, ctype_2]
118
    return wcs
119

    
120
def plot_skymap(skymap, ax=None, label="Counts", cmap='afmhot', title="", correlate=False):
121

    
122
    skymap = skymap.copy()
123
    skymap.stack_maps()
124

    
125

    
126
    wcs = get_wcs_from_skymap(skymap)
127

    
128
    array = skymap.array()
129

    
130
    if correlate:
131
        array = tophat_correlate(array, pixelsize=wcs.wcs.cdelt[1], normalize_kernel=True)
132

    
133
    plot_array(array, wcs, ax, cmap=cmap, title=title, label=label)
134

    
135
def plot_array(array, wcs, ax=None, cmap='afmhot', title="", vmin=None, vmax=None, label=""):
136
    import matplotlib.pyplot as plt
137
    if ax== None:
138
        fig = plt.figure()
139
        ax = fig.add_subplot(1, 1, 1, projection=wcs)
140

    
141
    if wcs.wcs.ctype[0][:3] == "RA-":
142
        ax.set_xlabel('Right Ascension [deg]')
143
        ax.set_ylabel('Declination [deg]')
144
    else:
145
        ax.set_xlabel('Galactic logitude [deg]')
146
        ax.set_ylabel('Galactic latitude [deg]')
147

    
148
    ax.set_title(title)
149
    image = ax.imshow(array, origin='lower', interpolation='None', cmap=cmap, vmin=vmin, vmax=vmax)
150
    bar = ax.figure.colorbar(image, label=label)
151
    
152
def tophat_correlate( inarray, size=0.07, pixelsize=0.02, normalize_kernel=False ):
153
    """                                                                                         
154
    Correlates numpy array with tophat kernel                                                   
155
    :param inarray: Input array                                                                 
156
    :param size: size for kernel in degrees                                                     
157
    :param pixelsize: size of the pixels in input array in degrees                              
158
    """
159

    
160
    from astropy.convolution import Tophat2DKernel
161
    from astropy.convolution import convolve
162
    kernel = Tophat2DKernel(size/pixelsize)
163

    
164
    if not normalize_kernel:
165

    
166
        kernel = kernel.array/kernel.array[kernel.array.shape[0]/2,kernel.array.shape[0]/2]
167

    
168
    return convolve(inarray, kernel, normalize_kernel=normalize_kernel)
169

    
170

    
171
# Plot resmap
172
plot_skymap(cres._resmap, correlate=True)
173
plt.show()