csphasecrv.py
17 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
#! /usr/bin/env python
# ==========================================================================
# Generates spectra as a function of phase
#
# Copyright (C) 2017-2018 Rolf Buehler
#
# 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 gammalib
import ctools
from cscripts import obsutils
from cscripts import ioutils
from cscripts import mputils
# ================ #
# csphasecrv class #
# ================ #
class csphasecrv(ctools.csobservation):
"""
Generates spectra in phase bins
This script computes spectra by performing a maximum likelihood fit
using :doc:`ctlike` in a series of phase bins for pulsars. The phase bins
can be either specified in an ASCII file or as an interval divided into
equally sized phase bins.
Examples:
>>> phcrv = csphasecrv()
>>> phcrv.run()
>>> ... (querying for parameters) ...
>>> phcrv = phrv.phasecrv()
Generates phase fits and retrieves dictionary with best fit models.
>>> phcrv = csphasecrv(obs)
>>> phcrv.execute()
>>> ... (querying for parameters) ...
Generates phase fits from the observations
and saves results in XML files.
"""
# Constructor
def __init__(self, *argv):
"""
Constructor
"""
# Initialise application by calling the appropriate class constructor
self._init_csobservation(self.__class__.__name__, ctools.__version__, argv)
# Initialise some members. Phases are stored in a nested list
# [[ph1min,ph1max], [ph2min,ph2max],..]
self._srcname = ''
self._phbins = [[0.0,1.0]]
self._onoff = False
self._stacked = False
self._fits = gammalib.GFits()
self._fitmodels = {}
self._nthreads = 0
# Return
return
# State methods por pickling
def __getstate__(self):
"""
Extend ctools.csobservation getstate method to include some members
Returns
-------
state : dict
Pickled instance
"""
# Set pickled dictionary
state = {'base' : ctools.csobservation.__getstate__(self),
'srcname' : self._srcname,
'phbins' : self._phbins,
'stacked' : self._stacked,
'onoff' : self._onoff,
'fits' : self._fits,
'fitmodels': self._fitmodels,
'nthreads' : self._nthreads}
# Return pickled dictionary
return state
def __setstate__(self, state):
"""
Extend ctools.csobservation setstate method to include some members
Parameters
----------
state : dict
Pickled instance
"""
ctools.csobservation.__setstate__(self, state['base'])
self._srcname = state['srcname']
self._phbins = state['phbins']
self._onoff = state['onoff']
self._stacked = state['stacked']
self._fits = state['fits']
self._fitmodels= state['fitmodels']
self._nthreads = state['nthreads']
# Return
return
# Private methods
def _get_parameters(self):
"""
Get parameters from parfile
"""
# Setup observations (require response and allow event list, don't
# allow counts cube)
self._setup_observations(self.obs(), True, True, False)
# Set observation statistic
self._set_obs_statistic(gammalib.toupper(self['statistic'].string()))
# Set models if there are none in the container
if self.obs().models().size() == 0:
self.obs().models(self['inmodel'].filename())
# Get source name
self._srcname = self['srcname'].string()
# Get phase boundaries
self._phbins = self._create_tbounds()
# Set On/Off analysis flag and query relevant user parameters
self._onoff = self._is_onoff()
# If cube analysis is selected
# Set stacked analysis flag and query relevant user parameters
if not self._onoff:
self._stacked = self._is_stacked()
# Query the hidden parameters, just in case
self['edisp'].boolean()
# Read ahead output parameters
if self._read_ahead():
self['outfile'].filename()
# Write input parameters into logger
self._log_parameters(gammalib.TERSE)
# Set number of processes for multiprocessing
self._nthreads = mputils.nthreads(self)
# Return
return
def _create_tbounds(self):
"""
Creates phase bins
Returns
-------
phbins : `[]`
List of phase bins
"""
# Initialise Good Time Intervals
phbins = []
# Get algorithm to use for defining the time intervals. Possible
# values are "FILE" or "LIN". This is enforced at
# parameter file level, hence no checking is needed.
algorithm = self['phbinalg'].string()
# If the algorithm is "FILE" then handle a FITS or an ASCII file for
# the time bin definition
if algorithm == 'FILE':
# Get the filename
filename = self['phbinfile'].filename()
# Load ASCII file as CSV file and construct
# the GTIs from the rows of the CSV file. It is expected that the
# CSV file has two columns containing the "START" and "STOP"
# values of the phase bins. No header row is expected.
csv = gammalib.GCsv(filename)
for i in range(csv.nrows()):
phmin = csv.real(i,0)
phmax = csv.real(i,1)
phbins.append([phmin,phmax])
# If the algorithm is "LIN" then use a linear time binning, defined by
# the "phbins" user parameters
elif algorithm == 'LIN':
# Get start and stop time and number of time bins
nbins = self['phbins'].integer()
# Compute time step and setup the GTIs
ph_step = 1.0 / float(nbins)
for i in range(nbins):
phmin = i * ph_step
phmax = (i+1) * ph_step
phbins.append([phmin,phmax])
# Return Good Time Intervals
return phbins
def _get_free_par_names(self):
"""
Return list of free parameter names
Returns
-------
names : list of str
List of free parameter names.
"""
# Initialise empty list of free parameter names
names = []
# Collect list of free parameter names
for par in self.obs().models()[self._srcname]:
if par.is_free():
names.append(par.name())
# Return names
return names
def _create_fits_table(self, results):
"""
Creates FITS binary table containing phase curve results
Parameters
----------
results : list of dict
List of result dictionaries
Returns
-------
table : `~gammalib.GFitsBinTable`
FITS binary table containing phase curve
"""
# Determine number of rows in FITS table
nrows = len(results)
# Create FITS Table with extension "PHASECURVE"
table = gammalib.GFitsBinTable(nrows)
table.extname('PHASECURVE')
# Append phase columns
ioutils.append_result_column(table, results, 'PHASE_MIN', '', 'phmin')
ioutils.append_result_column(table, results, 'PHASE_MAX', '', 'phmax')
# Append parameter columns
ioutils.append_model_par_column(table, self.obs().models()[self._srcname],
results)
# Return table
return table
def _create_fits(self):
"""
Create FITS file object from fit results
"""
# Initialise list of result dictionaries
results = []
# Get source parameters
pars = self._get_free_par_names()
# Loop over time bins
for i in range(len(self._phbins)):
# Get time boundaries
phmin = self._phbins[i][0]
phmax = self._phbins[i][1]
# Initialise result dictionary
result = {'phmin': phmin,
'phmax': phmax,
'pars': pars,
'values': {}}
# Store fit results
phname = str(phmin)+'-'+str(phmax)
# If the model contains the source of interest fill results
try:
source = self._fitmodels[phname][self._srcname]
for par in pars:
result['values'][par] = source[par].value()
result['values']['e_'+par] = source[par].error()
# ... otherwise fills with zeros
except:
for par in pars:
result['values'][par] = 0.
result['values']['e_'+par] = 0.
# Append result to list of dictionaries
results.append(result)
# Create FITS table from results
table = self._create_fits_table(results)
# Create FITS file and append FITS table to FITS file
self._fits = gammalib.GFits()
self._fits.append(table)
# Return
return
def _save_fits(self):
"""
Saved phase fit results into a fits file
"""
# Write header
self._log_header1(gammalib.TERSE, 'Save phase FITS file')
# Create FITS file
self._create_fits()
# Get file name
outfile = self['outfile'].filename()
# Log file name
self._log_value(gammalib.NORMAL, 'Phase curve file', outfile.url())
# Save to fits
self._fits.saveto(outfile, self._clobber())
# Return
return
def _save_xml(self):
"""
Save phase fit results into one XML model each bin
"""
# Write header
self._log_header1(gammalib.TERSE, 'Save phase XML files')
# Get file name
outname = self['outfile'].filename()
# Loop over all phase bins
for phbin in self._phbins:
# Set file name for phase bin
phname = str(phbin[0])+'-'+str(phbin[1])
replace_name = '_phase_'+phname+'.xml'
outname_phase = (outname.file()).replace('.fits', replace_name)
outfile = outname.path() + outname_phase
# Save XML file
self._fitmodels[phname].save(outfile)
# Log file name
name = 'Phase [%s] file' % phname
self._log_value(gammalib.NORMAL, name, outfile)
# Return
return
def _phase_bin(self,phbin):
# Write time bin into header
self._log_header2(gammalib.TERSE, 'PHASE %f - %f' %
(phbin[0], phbin[1]))
# Select events
select = ctools.ctselect(self.obs().copy())
select['emin'] = self['emin'].real()
select['emax'] = self['emax'].real()
select['tmin'] = 'UNDEFINED'
select['tmax'] = 'UNDEFINED'
select['rad'] = 'UNDEFINED'
select['ra'] = 'UNDEFINED'
select['dec'] = 'UNDEFINED'
select['expr'] = 'PHASE>' + str(phbin[0]) + ' && PHASE<' + str(phbin[1])
select.run()
# Set phase string
phstr = str(phbin[0]) + '-' + str(phbin[1])
# Add phase to observation id
for i in range(0, select.obs().size()):
oldid = select.obs()[i].id()
select.obs()[i].id(oldid + '_' + phstr)
obs = select.obs()
# If an On/Off analysis is requested generate the On/Off observations
if self._onoff:
obs = obsutils.get_onoff_obs(self, select.obs(), nthreads=1)
# ... otherwise, if stacked analysis is requested then bin the
# events and compute the stacked response functions and setup
# an observation container with a single stacked observation.
elif self._stacked:
obs = obsutils.get_stacked_obs(self, select.obs())
# Header
self._log_header3(gammalib.EXPLICIT, 'Fitting the data')
# The On/Off analysis can produce empty observation containers,
# e.g., when on-axis observations are used. To avoid ctlike asking
# for a new observation container (or hang, if in interactive mode)
# we'll run ctlike only if the size is >0
if obs.size() > 0:
# Do maximum likelihood model fitting
like = ctools.ctlike(obs)
like['edisp'] = self['edisp'].boolean()
like['nthreads'] = 1 # Avoids OpenMP conflict
like.run()
# Renormalize models to phase selection
# TODO move the scaling from the temporal to the spectral component
for model in like.obs().models():
scaled_norm = model['Normalization'].value() / (phbin[1] - phbin[0])
model['Normalization'].value(scaled_norm)
# Store fit model
fitmodels = like.obs().models().copy()
# ... otherwise we set an empty model container
else:
self._log_string(gammalib.TERSE,
'PHASE %f - %f: no observations available'
' for fitting' % (phbin[0], phbin[1]))
# Set empty models container
fitmodels = gammalib.GModels()
# Set results
result = {'phstr': phstr, 'fitmodels': fitmodels}
# Return results
return result
# Public methods
def run(self):
"""
Run the script
"""
# Switch screen logging on in debug mode
if self._logDebug():
self._log.cout(True)
# Get parameters
self._get_parameters()
# Write observation into logger
self._log_observations(gammalib.NORMAL, self.obs(), 'Observation')
# Dictionary to save phase fitted models
self._fitmodels = {}
# Write header
self._log_header1(gammalib.TERSE, 'Generate phase curve')
# If more than a single thread is requested then use multiprocessing
if self._nthreads > 1:
# Compute phase bins
args = [(self, '_phase_bin', phbin) for phbin in self._phbins]
poolresults = mputils.process(self._nthreads, mputils.mpfunc, args)
# Construct results
for i in range(len(self._phbins)):
self._fitmodels[poolresults[i][0]['phstr']] = poolresults[i][0]['fitmodels']
self._log_string(gammalib.TERSE, poolresults[i][1]['log'], False)
# Otherwise, loop over all phases
else:
for phbin in self._phbins:
result = self._phase_bin(phbin)
self._fitmodels[result['phstr']] = result['fitmodels']
# Create FITS file
self._create_fits()
# Optionally publish phase curve
if self['publish'].boolean():
self.publish()
# Return
return
def save(self):
"""
Saves results to fits and XML
"""
# Save results to FITS
self._save_fits()
# Save results to XML files (one per phase bin)
self._save_xml()
# Return
return
def publish(self, name=''):
"""
Publish phase curve
Parameters
----------
name : str, optional
Name of phase curve
"""
# Write header
self._log_header1(gammalib.TERSE, 'Publish phase curve')
# Continue only if phase curve is valid
if self._fits.contains('PHASECURVE'):
# Set default name is user name is empty
if not name:
user_name = self._name()
else:
user_name = name
# Log file name
self._log_value(gammalib.NORMAL, 'Phase curve name', user_name)
# Publish phase curve
self._fits.publish('PHASECURVE', user_name)
# Return
return
def phasecurve(self):
"""
Return dictionary with best fit models
"""
# Return
return self._fitmodels
# ======================== #
# Main routine entry point #
# ======================== #
if __name__ == '__main__':
# Create instance of application
app = csphasecrv(sys.argv)
# Execute application
app.execute()