comsrcdetect.py
9.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
#! /usr/bin/env python
# ==========================================================================
# Detect source in TS map
#
# Copyright (C) 2021-2022 Juergen Knoedlseder
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ==========================================================================
import sys
import glob
import os
import gammalib
import ctools
from cscripts import modutils
# ================== #
# comsrcdetect class #
# ================== #
class comsrcdetect(ctools.cscript):
"""
Perform SRCLIX model fitting of COMPTEL observations
"""
# Constructor
def __init__(self, *argv):
"""
Constructor
"""
# Initialise application by calling the base class constructor
self._init_cscript(self.__class__.__name__, ctools.__version__, argv)
# Initialise members
self._models = gammalib.GModels()
self._fits = gammalib.GFits()
# Return
return
# Private methods
def _get_parameters(self):
"""
Get parameters from parfile
"""
# Query parameters
self['inmap'].filename()
self['threshold'].real()
self['maxsrcs'].integer()
self['prefix'].string()
# Query ahead output model filename
if self._read_ahead():
self['outmodel'].filename()
self['outmap'].filename()
self['outds9file'].filename()
# Write input parameters into logger
self._log_parameters(gammalib.TERSE)
# Return
return
def _add_source(self, dir):
"""
Add point source to model container
Parameters
----------
dir : `~gammalib.GSkyDir`
Source position
"""
# Set spatial component
spatial = gammalib.GModelSpatialPointSource(dir)
spatial['RA'].free()
spatial['DEC'].free()
# Set spectral component
spectral = gammalib.GModelSpectralPlaw(2.0e-3, -2.0, gammalib.GEnergy(1.0,'MeV'))
spectral['Prefactor'].min(1.0e-25)
# Set source name
name = '%s%3.3d' % (self['prefix'].string(), self._models.size()+1)
# Set source model
source = gammalib.GModelSky(spatial, spectral)
source.name(name)
source.tscalc(True)
# Append source to model
self._models.append(source)
# Return
return
def _remove_pixel(self, tsmap, premap, index, threshold):
"""
Remove pixel and all neighboring pixels above threshold from TS map
Parameters
----------
tsmap : `~gammalib.GSkyMap`
TS map
premap : `~gammalib.GSkyMap`
Prefactor map
index : int
Pixel to be removed
threshold : float
TS threshold above which pixels are to be removed
"""
# Set size of TS map
nx = tsmap.nx()
ny = tsmap.ny()
# Set pixel of interest to zero
tsmap[index] = 0.0
# Get X and Y index of pixel
ix0 = int(index % nx)
iy0 = int(index / nx)
# Remove all neighbouring pixels
for iy in range(iy0,-1,-1):
yoffset = iy * nx
n = 0
for ix in range(ix0,-1,-1):
if ix == ix0 and iy == iy0:
continue
i = ix + yoffset
if tsmap[i] > threshold and premap[i] > 0.0:
tsmap[i] = 0.0
n += 1
else:
break
for ix in range(ix0+1,nx):
if ix == ix0 and iy == iy0:
continue
i = ix + yoffset
if tsmap[i] > threshold and premap[i] > 0.0:
tsmap[i] = 0.0
n += 1
else:
break
if n == 0:
break
for iy in range(iy0+1,ny):
yoffset = iy * nx
n = 0
for ix in range(ix0,-1,-1):
if ix == ix0 and iy == iy0:
continue
i = ix + yoffset
if tsmap[i] > threshold and premap[i] > 0.0:
tsmap[i] = 0.0
n += 1
else:
break
for ix in range(ix0+1,nx):
if ix == ix0 and iy == iy0:
continue
i = ix + yoffset
if tsmap[i] > threshold and premap[i] > 0.0:
tsmap[i] = 0.0
n += 1
else:
break
if n == 0:
break
# Return
return
def _search_sources(self, tsmap, premap):
"""
Search for sources
Parameters
----------
tsmap : `~gammalib.GSkyMap`
TS map
premap : `~gammalib.GSkyMap`
Prefactor map
"""
# Write header
self._log_header1(gammalib.NORMAL, 'Search for sources')
# Initialise model container and diagnostics FITS file
self._models = gammalib.GModels()
self._fits = gammalib.GFits()
# Get threshold and maximum number of sources
threshold = self['threshold'].real()
maxsrcs = self['maxsrcs'].integer()
# Iterate over source finding
while True:
# Find pixel with largest TS value and positive Prefactor
tsmax = 0.0
imax = -1
for i in range(tsmap.npix()):
if tsmap[i] > tsmax and premap[i] > 0.0:
tsmax = tsmap[i]
imax = i
# If pixel is above threshold then add point source at pixel
if tsmax > threshold:
# Add point source to model
dir = tsmap.inx2dir(imax)
self._add_source(dir)
# Log point source
source = 'Source %d' % (self._models.size())
value = '%s (TS=%.3f)' % (str(dir), tsmax)
self._log_value(gammalib.NORMAL, source, value)
# If maximum number of source is reached then break
if self._models.size() >= maxsrcs:
break
# Reset map pixel and all its neighbours
self._remove_pixel(tsmap, premap, imax, threshold)
# Save TS map after removing pixels for diagnostics
extname = 'TS map %3.3d' % (self._models.size())
tsmap.write(self._fits, extname)
# ... otherwise break iterative loop
else:
break
# Return
return
# Public methods
def process(self):
"""
Process the script
"""
# Get parameters
self._get_parameters()
# Log header
self._log_header1(gammalib.NORMAL, 'Input TS map')
# Load TS and Prefactor maps
fits = gammalib.GFits(self['inmap'].filename())
tsmap = gammalib.GSkyMap(fits[0])
premap = gammalib.GSkyMap(fits[1])
# Search for sources
self._search_sources(tsmap, premap)
# Return
return
def save(self):
"""
Save observation definition file
"""
# Write header
self._log_header1(gammalib.TERSE, 'Save source model')
# Get output filenames
outmodel = self['outmodel'].filename()
outmap = self['outmap'].filename()
outds9file = self['outds9file'].filename()
# If file exists and clobber flag is false then raise an exception
if outmodel.exists() and not self['clobber'].boolean():
msg = ('Cannot save "'+outmodel.url()+'": File already exists. '
'Use parameter clobber=yes to allow overwriting of files.')
raise RuntimeError(msg)
elif outmap.exists() and not self['clobber'].boolean():
msg = ('Cannot save "'+outmap.url()+'": File already exists. '
'Use parameter clobber=yes to allow overwriting of files.')
raise RuntimeError(msg)
elif outds9file.exists() and not self['clobber'].boolean():
msg = ('Cannot save "'+outds9file.url()+'": File already exists. '
'Use parameter clobber=yes to allow overwriting of files.')
raise RuntimeError(msg)
# Otherwise log filename and save file
else:
# Log model definition filename
self._log_value(gammalib.NORMAL, 'Model definition XML file', outmodel.url())
# Save models
self._models.save(outmodel)
# Log model definition filename
self._log_value(gammalib.NORMAL, 'TS map FITS file', outmap.url())
# Save FITS file
self._fits.saveto(outmap, self['clobber'].boolean())
# Log DS9 region filename
self._log_value(gammalib.NORMAL, 'DS9 region file', outds9file.url())
# Save DS9 region file
modutils.models2ds9file(self._models, outds9file.url())
# Return
return
# ======================== #
# Main routine entry point #
# ======================== #
if __name__ == '__main__':
# Create instance of application
app = comsrcdetect(sys.argv)
# Execute application
app.execute()