/
psf_3d.py
428 lines (356 loc) · 13.1 KB
/
psf_3d.py
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
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from astropy.table import Table
from astropy.io import fits
from astropy import units as u
from astropy.coordinates import Angle
from astropy.utils import lazyproperty
from ..utils.array import array_stats_str
from ..utils.energy import Energy
from ..utils.scripts import make_path
from ..utils.interpolation import ScaledRegularGridInterpolator
from .psf_table import TablePSF, EnergyDependentTablePSF
__all__ = ["PSF3D"]
class PSF3D:
"""PSF with axes: energy, offset, rad.
Data format specification: :ref:`gadf:psf_table`
Parameters
----------
energy_lo : `~astropy.units.Quantity`
Energy bins lower edges (1-dim)
energy_hi : `~astropy.units.Quantity`
Energy bins upper edges (1-dim)
offset : `~astropy.coordinates.Angle`
Offset angle (1-dim)
rad_lo : `~astropy.coordinates.Angle`
Offset angle bins lower edges
rad_hi : `~astropy.coordinates.Angle`
Offset angle bins upper edges
psf_value : `~astropy.units.Quantity`
PSF (3-dim with axes: psf[rad_index, offset_index, energy_index]
energy_thresh_lo : `~astropy.units.Quantity`
Lower energy threshold.
energy_thresh_hi : `~astropy.units.Quantity`
Upper energy threshold.
"""
def __init__(
self,
energy_lo,
energy_hi,
offset,
rad_lo,
rad_hi,
psf_value,
energy_thresh_lo=u.Quantity(0.1, "TeV"),
energy_thresh_hi=u.Quantity(100, "TeV"),
interp_kwargs=None,
):
self.energy_lo = energy_lo.to("TeV")
self.energy_hi = energy_hi.to("TeV")
self.offset = Angle(offset)
self.rad_lo = Angle(rad_lo)
self.rad_hi = Angle(rad_hi)
self.psf_value = psf_value.to("sr^-1")
self.energy_thresh_lo = energy_thresh_lo.to("TeV")
self.energy_thresh_hi = energy_thresh_hi.to("TeV")
self._interp_kwargs = interp_kwargs or {}
@lazyproperty
def _interpolate(self):
energy = self._energy_logcenter()
offset = self.offset.to("deg")
rad = self._rad_center()
return ScaledRegularGridInterpolator(
points=(rad, offset, energy), values=self.psf_value, **self._interp_kwargs
)
def info(self):
"""Print some basic info.
"""
ss = "\nSummary PSF3D info\n"
ss += "---------------------\n"
ss += array_stats_str(self.energy_lo, "energy_lo")
ss += array_stats_str(self.energy_hi, "energy_hi")
ss += array_stats_str(self.offset, "offset")
ss += array_stats_str(self.rad_lo, "rad_lo")
ss += array_stats_str(self.rad_hi, "rad_hi")
ss += array_stats_str(self.psf_value, "psf_value")
# TODO: should quote containment values also
return ss
def _energy_logcenter(self):
"""Get logcenters of energy bins.
Returns
-------
energies : `~astropy.units.Quantity`
Logcenters of energy bins
"""
return np.sqrt(self.energy_lo * self.energy_hi)
def _rad_center(self):
"""Get centers of rad bins (`~astropy.coordinates.Angle` in deg).
"""
return ((self.rad_hi + self.rad_lo) / 2).to("deg")
@classmethod
def read(cls, filename, hdu="PSF_2D_TABLE"):
"""Create `PSF3D` from FITS file.
Parameters
----------
filename : str
File name
hdu : str
HDU name
"""
filename = str(make_path(filename))
table = Table.read(filename, hdu=hdu)
return cls.from_table(table)
@classmethod
def from_table(cls, table):
"""Create `PSF3D` from `~astropy.table.Table`.
Parameters
----------
table : `~astropy.table.Table`
Table Table-PSF info.
"""
theta_lo = table["THETA_LO"].quantity[0]
theta_hi = table["THETA_HI"].quantity[0]
offset = (theta_hi + theta_lo) / 2
offset = Angle(offset, unit=table["THETA_LO"].unit)
energy_lo = table["ENERG_LO"].quantity[0]
energy_hi = table["ENERG_HI"].quantity[0]
rad_lo = table["RAD_LO"].quantity[0]
rad_hi = table["RAD_HI"].quantity[0]
psf_value = table["RPSF"].quantity[0]
opts = {}
try:
opts["energy_thresh_lo"] = u.Quantity(table.meta["LO_THRES"], "TeV")
opts["energy_thresh_hi"] = u.Quantity(table.meta["HI_THRES"], "TeV")
except KeyError:
pass
return cls(energy_lo, energy_hi, offset, rad_lo, rad_hi, psf_value, **opts)
def to_fits(self):
"""
Convert PSF table data to FITS HDU list.
Returns
-------
hdu_list : `~astropy.io.fits.HDUList`
PSF in HDU list format.
"""
# Set up data
names = [
"ENERG_LO",
"ENERG_HI",
"THETA_LO",
"THETA_HI",
"RAD_LO",
"RAD_HI",
"RPSF",
]
units = ["TeV", "TeV", "deg", "deg", "deg", "deg", "sr^-1"]
data = [
self.energy_lo,
self.energy_hi,
self.offset,
self.offset,
self.rad_lo,
self.rad_hi,
self.psf_value,
]
table = Table()
for name_, data_, unit_ in zip(names, data, units):
table[name_] = [data_]
table[name_].unit = unit_
hdu = fits.BinTableHDU(table)
hdu.header["LO_THRES"] = self.energy_thresh_lo.value
hdu.header["HI_THRES"] = self.energy_thresh_hi.value
return fits.HDUList([fits.PrimaryHDU(), hdu])
def write(self, filename, *args, **kwargs):
"""Write PSF to FITS file.
Calls `~astropy.io.fits.HDUList.writeto`, forwarding all arguments.
"""
self.to_fits().writeto(filename, *args, **kwargs)
def evaluate(self, energy=None, offset=None, rad=None):
"""Interpolate PSF value at a given offset and energy.
Parameters
----------
energy : `~astropy.units.Quantity`
energy value
offset : `~astropy.coordinates.Angle`
Offset in the field of view
rad : `~astropy.coordinates.Angle`
Offset wrt source position
Returns
-------
values : `~astropy.units.Quantity`
Interpolated value
"""
if energy is None:
energy = self._energy_logcenter()
if offset is None:
offset = self.offset
if rad is None:
rad = self._rad_center()
rad = np.atleast_1d(u.Quantity(rad))
offset = np.atleast_1d(u.Quantity(offset))
energy = np.atleast_1d(u.Quantity(energy))
return self._interpolate(
(
rad[:, np.newaxis, np.newaxis],
offset[np.newaxis, :, np.newaxis],
energy[np.newaxis, np.newaxis, :],
)
)
def to_energy_dependent_table_psf(self, theta="0 deg", rad=None, exposure=None):
"""
Convert PSF3D in EnergyDependentTablePSF.
Parameters
----------
theta : `~astropy.coordinates.Angle`
Offset in the field of view
rad : `~astropy.coordinates.Angle`
Offset from PSF center used for evaluating the PSF on a grid.
Default is the ``rad`` from this PSF.
exposure : `~astropy.units.Quantity`
Energy dependent exposure. Should be in units equivalent to 'cm^2 s'.
Default exposure = 1.
Returns
-------
table_psf : `~gammapy.irf.EnergyDependentTablePSF`
Energy-dependent PSF
"""
theta = Angle(theta)
energies = self._energy_logcenter()
if rad is None:
rad = self._rad_center()
else:
rad = Angle(rad)
psf_value = self.evaluate(offset=theta, rad=rad).squeeze()
return EnergyDependentTablePSF(
energy=energies, rad=rad, exposure=exposure, psf_value=psf_value.T
)
def to_table_psf(self, energy, theta="0 deg", **kwargs):
"""Create `~gammapy.irf.TablePSF` at one given energy.
Parameters
----------
energy : `~astropy.units.Quantity`
Energy
theta : `~astropy.coordinates.Angle`
Offset in the field of view. Default theta = 0 deg
Returns
-------
psf : `~gammapy.irf.TablePSF`
Table PSF
"""
energy = u.Quantity(energy)
theta = Angle(theta)
psf_value = self.evaluate(energy, theta).squeeze()
rad = self._rad_center()
return TablePSF(rad, psf_value, **kwargs)
def containment_radius(
self, energy, theta="0 deg", fraction=0.68, interp_kwargs=None
):
"""Containment radius.
Parameters
----------
energy : `~astropy.units.Quantity`
Energy
theta : `~astropy.coordinates.Angle`
Offset in the field of view. Default theta = 0 deg
fraction : float
Containment fraction. Default fraction = 0.68
Returns
-------
radius : `~astropy.units.Quantity`
Containment radius in deg
"""
energy = np.atleast_1d(u.Quantity(energy))
theta = np.atleast_1d(u.Quantity(theta))
radii = []
for t in theta:
psf = self.to_energy_dependent_table_psf(theta=t)
radii.append(psf.containment_radius(energy, fraction=fraction))
return u.Quantity(radii).T.squeeze()
def plot_containment_vs_energy(
self, fractions=[0.68, 0.95], thetas=Angle([0, 1], "deg"), ax=None
):
"""Plot containment fraction as a function of energy.
"""
import matplotlib.pyplot as plt
ax = plt.gca() if ax is None else ax
energy = Energy.equal_log_spacing(self.energy_lo[0], self.energy_hi[-1], 100)
for theta in thetas:
for fraction in fractions:
radius = self.containment_radius(energy, theta, fraction)
label = "{} deg, {:.1f}%".format(theta.deg, 100 * fraction)
ax.plot(energy.value, radius.value, label=label)
ax.semilogx()
ax.legend(loc="best")
ax.set_xlabel("Energy (TeV)")
ax.set_ylabel("Containment radius (deg)")
def plot_psf_vs_rad(self, theta="0 deg", energy=u.Quantity(1, "TeV")):
"""Plot PSF vs rad.
Parameters
----------
energy : `~astropy.units.Quantity`
Energy. Default energy = 1 TeV
theta : `~astropy.coordinates.Angle`
Offset in the field of view. Default theta = 0 deg
"""
theta = Angle(theta)
table = self.to_table_psf(energy=energy, theta=theta)
return table.plot_psf_vs_rad()
def plot_containment(
self, fraction=0.68, ax=None, show_safe_energy=False, add_cbar=True, **kwargs
):
"""
Plot containment image with energy and theta axes.
Parameters
----------
fraction : float
Containment fraction between 0 and 1.
add_cbar : bool
Add a colorbar
"""
import matplotlib.pyplot as plt
ax = plt.gca() if ax is None else ax
energy = self._energy_logcenter()
offset = self.offset
# Set up and compute data
containment = self.containment_radius(energy, offset, fraction)
# plotting defaults
kwargs.setdefault("cmap", "GnBu")
kwargs.setdefault("vmin", np.nanmin(containment.value))
kwargs.setdefault("vmax", np.nanmax(containment.value))
# Plotting
x = energy.value
y = offset.value
caxes = ax.pcolormesh(x, y, containment.value.T, **kwargs)
# Axes labels and ticks, colobar
ax.semilogx()
ax.set_ylabel("Offset ({unit})".format(unit=offset.unit))
ax.set_xlabel("Energy ({unit})".format(unit=energy.unit))
ax.set_xlim(x.min(), x.max())
ax.set_ylim(y.min(), y.max())
if show_safe_energy:
self._plot_safe_energy_range(ax)
if add_cbar:
label = "Containment radius R{:.0f} ({})" "".format(
100 * fraction, containment.unit
)
ax.figure.colorbar(caxes, ax=ax, label=label)
return ax
def _plot_safe_energy_range(self, ax):
"""add safe energy range lines to the plot"""
esafe = self.energy_thresh_lo
omin = self.offset.value.min()
omax = self.offset.value.max()
ax.hlines(y=esafe.value, xmin=omin, xmax=omax)
label = "Safe energy threshold: {:3.2f}".format(esafe)
ax.text(x=0.1, y=0.9 * esafe.value, s=label, va="top")
def peek(self, figsize=(15, 5)):
"""Quick-look summary plots."""
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=figsize)
self.plot_containment(fraction=0.68, ax=axes[0])
self.plot_containment(fraction=0.95, ax=axes[1])
self.plot_containment_vs_energy(ax=axes[2])
# TODO: implement this plot
# psf = self.psf_at_energy_and_theta(energy='1 TeV', theta='1 deg')
# psf.plot_components(ax=axes[2])
plt.tight_layout()