BAccMod 0.1.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- BAccMod-0.1.0.dev0.dist-info/METADATA +108 -0
- BAccMod-0.1.0.dev0.dist-info/RECORD +13 -0
- BAccMod-0.1.0.dev0.dist-info/WHEEL +5 -0
- BAccMod-0.1.0.dev0.dist-info/top_level.txt +1 -0
- baccmod/__init__.py +1 -0
- baccmod/baccmod.py +174 -0
- baccmod/base_acceptance_map_creator.py +1005 -0
- baccmod/bkg_collection.py +91 -0
- baccmod/exception.py +13 -0
- baccmod/grid3d_acceptance_map_creator.py +349 -0
- baccmod/modeling.py +101 -0
- baccmod/radial_acceptance_map_creator.py +204 -0
- baccmod/toolbox.py +202 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# -------------------------------------------------------------------
|
|
3
|
+
# Filename: bkg_collection.py
|
|
4
|
+
# Purpose: Class for storing model with background zenith binning
|
|
5
|
+
#
|
|
6
|
+
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
|
7
|
+
# 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 Lesser General Public License for more details.
|
|
8
|
+
# ---------------------------------------------------------------------
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
import numpy as np
|
|
13
|
+
from gammapy.irf.background import BackgroundIRF
|
|
14
|
+
from .exception import BackgroundModelFormatException
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class BackgroundCollectionZenith:
|
|
20
|
+
|
|
21
|
+
def __init__(self, bkg_dict: dict[float, BackgroundIRF] = None):
|
|
22
|
+
"""
|
|
23
|
+
Create the class for storing a collection of model for different zenith angle
|
|
24
|
+
|
|
25
|
+
Parameters
|
|
26
|
+
----------
|
|
27
|
+
bkg_dict : dict of gammapy.irf.BackgroundIRF
|
|
28
|
+
The collection of model in a dictionary with as key the zenith angle (in degree) associated to the model
|
|
29
|
+
"""
|
|
30
|
+
bkg_dict = bkg_dict or {}
|
|
31
|
+
self.bkg_dict = {}
|
|
32
|
+
for k, v in bkg_dict.items():
|
|
33
|
+
key = float(k)
|
|
34
|
+
self._check_entry(key, v)
|
|
35
|
+
self.bkg_dict[key] = v
|
|
36
|
+
|
|
37
|
+
@staticmethod
|
|
38
|
+
def _check_entry(key, v):
|
|
39
|
+
error_message = ''
|
|
40
|
+
if key > 90.0 or key < 0.0:
|
|
41
|
+
error_message += ('Invalid key : The zenith associated with the model should be between 0 and 90 in degree,'
|
|
42
|
+
' ') + str(key) + ' provided.\n'
|
|
43
|
+
if not isinstance(v, BackgroundIRF):
|
|
44
|
+
error_message += 'Invalid type : model should be a BackgroundIRF.'
|
|
45
|
+
if error_message != '':
|
|
46
|
+
raise BackgroundModelFormatException(error_message)
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def zenith(self):
|
|
50
|
+
"""
|
|
51
|
+
Return the zenith available
|
|
52
|
+
|
|
53
|
+
Returns
|
|
54
|
+
----------
|
|
55
|
+
keys : np.array
|
|
56
|
+
The zenith angle available in degree
|
|
57
|
+
"""
|
|
58
|
+
return np.sort(np.array(list(self.bkg_dict.keys())))
|
|
59
|
+
|
|
60
|
+
def keys(self):
|
|
61
|
+
"""
|
|
62
|
+
Return the keys available
|
|
63
|
+
|
|
64
|
+
Returns
|
|
65
|
+
----------
|
|
66
|
+
keys : dict_keys
|
|
67
|
+
The keys (zenith angle) to available
|
|
68
|
+
"""
|
|
69
|
+
return self.bkg_dict.keys()
|
|
70
|
+
|
|
71
|
+
def __getitem__(self, key: float):
|
|
72
|
+
return self.bkg_dict[key]
|
|
73
|
+
|
|
74
|
+
def __setitem__(self, key: float, value: BackgroundIRF):
|
|
75
|
+
"""
|
|
76
|
+
Assign a new pair of zenith and background model
|
|
77
|
+
Check the format is compatible
|
|
78
|
+
|
|
79
|
+
Parameters
|
|
80
|
+
----------
|
|
81
|
+
key : float
|
|
82
|
+
The zenith angle in degree
|
|
83
|
+
value: gammapy.irf.BackgroundIRF
|
|
84
|
+
The model associated to the zenith angle provided
|
|
85
|
+
"""
|
|
86
|
+
key = float(key)
|
|
87
|
+
self._check_entry(key, value)
|
|
88
|
+
self.bkg_dict[key] = value
|
|
89
|
+
|
|
90
|
+
def __len__(self):
|
|
91
|
+
return len(self.bkg_dict)
|
baccmod/exception.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# -------------------------------------------------------------------
|
|
3
|
+
# Filename: toolbox.py
|
|
4
|
+
# Purpose: Definition of the Exception specific to the BAccMod code
|
|
5
|
+
#
|
|
6
|
+
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
|
7
|
+
# 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 Lesser General Public License for more details.
|
|
8
|
+
# ---------------------------------------------------------------------
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class BackgroundModelFormatException(Exception):
|
|
12
|
+
def __init__(self, *args):
|
|
13
|
+
super().__init__(*args)
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# -------------------------------------------------------------------
|
|
3
|
+
# Filename: grid3d_acceptance_map_creator.py
|
|
4
|
+
# Purpose: Class for creation of model based on a 3D grid (spatial and energy)
|
|
5
|
+
#
|
|
6
|
+
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
|
7
|
+
# 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 Lesser General Public License for more details.
|
|
8
|
+
# ---------------------------------------------------------------------
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
from typing import Tuple, List, Optional
|
|
13
|
+
|
|
14
|
+
from astropy.coordinates import AltAz
|
|
15
|
+
from astropy.coordinates.erfa_astrom import erfa_astrom, ErfaAstromInterpolator
|
|
16
|
+
import astropy.units as u
|
|
17
|
+
import numpy as np
|
|
18
|
+
from gammapy.data import Observations
|
|
19
|
+
from gammapy.datasets import MapDataset
|
|
20
|
+
from gammapy.irf import FoVAlignment, Background3D
|
|
21
|
+
from gammapy.maps import WcsNDMap, Map, MapAxis, RegionGeom
|
|
22
|
+
from iminuit import Minuit
|
|
23
|
+
from regions import SkyRegion
|
|
24
|
+
|
|
25
|
+
from .base_acceptance_map_creator import BaseAcceptanceMapCreator
|
|
26
|
+
from .modeling import FIT_FUNCTION, log_factorial, log_poisson
|
|
27
|
+
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Grid3DAcceptanceMapCreator(BaseAcceptanceMapCreator):
|
|
32
|
+
|
|
33
|
+
def __init__(self,
|
|
34
|
+
energy_axis: MapAxis,
|
|
35
|
+
offset_axis: MapAxis,
|
|
36
|
+
oversample_map: int = 10,
|
|
37
|
+
exclude_regions: Optional[List[SkyRegion]] = None,
|
|
38
|
+
cos_zenith_binning_method: str = 'min_livetime',
|
|
39
|
+
cos_zenith_binning_parameter_value: int = 3600,
|
|
40
|
+
initial_cos_zenith_binning: float = 0.01,
|
|
41
|
+
max_angular_separation_wobble: u.Quantity = 0.4 * u.deg,
|
|
42
|
+
zenith_binning_run_splitting: bool = False,
|
|
43
|
+
max_fraction_pixel_rotation_fov: float = 0.5,
|
|
44
|
+
time_resolution: u.Quantity = 0.1 * u.s,
|
|
45
|
+
use_mini_irf_computation: bool = False,
|
|
46
|
+
mini_irf_time_resolution: u.Quantity = 1. * u.min,
|
|
47
|
+
method='stack',
|
|
48
|
+
fit_fnc='gaussian2d',
|
|
49
|
+
fit_seeds=None,
|
|
50
|
+
fit_bounds=None,
|
|
51
|
+
interpolation_type: str = 'linear',
|
|
52
|
+
activate_interpolation_cleaning: bool = False,
|
|
53
|
+
interpolation_cleaning_energy_relative_threshold: float = 1e-4,
|
|
54
|
+
interpolation_cleaning_spatial_relative_threshold: float = 1e-2) -> None:
|
|
55
|
+
"""
|
|
56
|
+
Create the class for calculating 3D grid acceptance model
|
|
57
|
+
|
|
58
|
+
Parameters
|
|
59
|
+
----------
|
|
60
|
+
energy_axis : MapAxis
|
|
61
|
+
The energy axis for the acceptance model
|
|
62
|
+
offset_axis : MapAxis
|
|
63
|
+
The offset axis for the acceptance model
|
|
64
|
+
oversample_map : int, optional
|
|
65
|
+
Oversample in number of pixel of the spatial axis used for the calculation
|
|
66
|
+
exclude_regions : list of regions.SkyRegion, optional
|
|
67
|
+
Region with known or putative gamma-ray emission, will be excluded of the calculation of the acceptance map
|
|
68
|
+
cos_zenith_binning_method : str, optional
|
|
69
|
+
The method used for cos zenith binning: 'min_livetime','min_n_observation'
|
|
70
|
+
cos_zenith_binning_parameter_value : int, optional
|
|
71
|
+
Minimum livetime (in seconds) or number of observations per zenith bins
|
|
72
|
+
initial_cos_zenith_binning : float, optional
|
|
73
|
+
Initial bin size for cos zenith binning
|
|
74
|
+
max_angular_separation_wobble : u.Quantity, optional
|
|
75
|
+
The maximum angular separation between identified wobbles, in degrees
|
|
76
|
+
zenith_binning_run_splitting : float, optional
|
|
77
|
+
If true, will split each run to match zenith binning for the base model computation
|
|
78
|
+
Could be computationally expensive, especially at high zenith with a high resolution zenith binning
|
|
79
|
+
max_fraction_pixel_rotation_fov : bool, optional
|
|
80
|
+
For camera frame transformation the maximum size relative to a pixel a rotation is allowed
|
|
81
|
+
time_resolution : astropy.units.Quantity, optional
|
|
82
|
+
Time resolution to use for the computation of the rotation of the FoV and cut as function of the zenith bins
|
|
83
|
+
method : str, optional
|
|
84
|
+
Decide if the acceptance is a direct event stacking or a fitted model. 'stack' or 'fit'
|
|
85
|
+
fit_fnc: str or function
|
|
86
|
+
Two dimensional function to be fitted. Some built-in functions are provided and selected by passing a string
|
|
87
|
+
The function needs to have a size parameter (integral charge) as first parameter.
|
|
88
|
+
fit_seeds: dict, can optionally be None if using a built-in function
|
|
89
|
+
Seeds of the parameters of the function to fit. Normalisation parameter is ignored if given.
|
|
90
|
+
fit_bounds: dict, can optionally be None if using a built-in function
|
|
91
|
+
Bounds of the parameters of the function to fit. Normalisation parameter is ignored if given.
|
|
92
|
+
use_mini_irf_computation : bool, optional
|
|
93
|
+
If true, in case the case of zenith interpolation or binning, each run will be divided in small subrun (the slicing is based on time).
|
|
94
|
+
A model will be computed for each sub run before averaging them to obtain the final model for the run.
|
|
95
|
+
Should improve the accuracy of the model, especially at high zenith angle.
|
|
96
|
+
mini_irf_time_resolution : astropy.units.Quantity, optional
|
|
97
|
+
Time resolution to use for mini irf used for computation of the final background model
|
|
98
|
+
interpolation_type: str, optional
|
|
99
|
+
Select the type of interpolation to be used, could be either "log" or "linear", log tend to provided better results be could more easily create artefact that will cause issue
|
|
100
|
+
activate_interpolation_cleaning: bool, optional
|
|
101
|
+
If true, will activate the cleaning step after interpolation, it should help to eliminate artefact caused by interpolation
|
|
102
|
+
interpolation_cleaning_energy_relative_threshold: float, optional
|
|
103
|
+
To be considered value, the bin in energy need at least one adjacent bin with a relative difference within this range
|
|
104
|
+
interpolation_cleaning_spatial_relative_threshold: float, optional
|
|
105
|
+
To be considered value, the bin in space need at least one adjacent bin with a relative difference within this range
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
# If no exclusion region, default it as an empty list
|
|
109
|
+
if exclude_regions is None:
|
|
110
|
+
exclude_regions = []
|
|
111
|
+
|
|
112
|
+
# Compute parameters for internal map
|
|
113
|
+
self.offset_axis = offset_axis
|
|
114
|
+
if not np.allclose(self.offset_axis.bin_width, self.offset_axis.bin_width[0]):
|
|
115
|
+
raise Exception('Support only regular linear bin for offset axis')
|
|
116
|
+
if not np.isclose(self.offset_axis.edges[0], 0. * u.deg):
|
|
117
|
+
raise Exception('Offset axis need to start at 0')
|
|
118
|
+
self.oversample_map = oversample_map
|
|
119
|
+
spatial_resolution = np.min(
|
|
120
|
+
np.abs(self.offset_axis.edges[1:] - self.offset_axis.edges[:-1])) / self.oversample_map
|
|
121
|
+
max_offset = np.max(self.offset_axis.edges)
|
|
122
|
+
|
|
123
|
+
self.method = method
|
|
124
|
+
self.fit_fnc = fit_fnc
|
|
125
|
+
self.fit_seeds = fit_seeds
|
|
126
|
+
self.fit_bounds = fit_bounds
|
|
127
|
+
|
|
128
|
+
offset_edges = offset_axis.edges
|
|
129
|
+
offset_bins = np.round(np.concatenate((-np.flip(offset_edges), offset_edges[1:]), axis=None), 3)
|
|
130
|
+
self.map_bins = (energy_axis.edges, offset_bins, offset_bins)
|
|
131
|
+
|
|
132
|
+
# Initiate upper instance
|
|
133
|
+
super().__init__(energy_axis=energy_axis,
|
|
134
|
+
max_offset=max_offset,
|
|
135
|
+
spatial_resolution=spatial_resolution,
|
|
136
|
+
exclude_regions=exclude_regions,
|
|
137
|
+
cos_zenith_binning_method=cos_zenith_binning_method,
|
|
138
|
+
cos_zenith_binning_parameter_value=cos_zenith_binning_parameter_value,
|
|
139
|
+
initial_cos_zenith_binning=initial_cos_zenith_binning,
|
|
140
|
+
max_angular_separation_wobble=max_angular_separation_wobble,
|
|
141
|
+
zenith_binning_run_splitting=zenith_binning_run_splitting,
|
|
142
|
+
max_fraction_pixel_rotation_fov=max_fraction_pixel_rotation_fov,
|
|
143
|
+
time_resolution=time_resolution,
|
|
144
|
+
use_mini_irf_computation=use_mini_irf_computation,
|
|
145
|
+
mini_irf_time_resolution=mini_irf_time_resolution,
|
|
146
|
+
interpolation_type=interpolation_type,
|
|
147
|
+
activate_interpolation_cleaning=activate_interpolation_cleaning,
|
|
148
|
+
interpolation_cleaning_energy_relative_threshold=interpolation_cleaning_energy_relative_threshold,
|
|
149
|
+
interpolation_cleaning_spatial_relative_threshold=interpolation_cleaning_spatial_relative_threshold)
|
|
150
|
+
|
|
151
|
+
def fit_background(self, count_map, exp_map_total, exp_map):
|
|
152
|
+
centers = self.offset_axis.center.to_value(u.deg)
|
|
153
|
+
centers = np.concatenate((-np.flip(centers), centers), axis=None)
|
|
154
|
+
raw_seeds = {}
|
|
155
|
+
bounds = {}
|
|
156
|
+
if type(self.fit_fnc) == str:
|
|
157
|
+
try:
|
|
158
|
+
fnc = FIT_FUNCTION[self.fit_fnc]
|
|
159
|
+
except KeyError:
|
|
160
|
+
logger.error(f"Invalid built-in fit_fnc. Use {FIT_FUNCTION.keys()} or a custom function.")
|
|
161
|
+
raise
|
|
162
|
+
raw_seeds = fnc.default_seeds.copy()
|
|
163
|
+
bounds = fnc.default_bounds.copy()
|
|
164
|
+
else:
|
|
165
|
+
fnc = self.fit_fnc
|
|
166
|
+
if self.fit_seeds is not None:
|
|
167
|
+
raw_seeds.update(self.fit_seeds)
|
|
168
|
+
if self.fit_bounds is not None:
|
|
169
|
+
bounds.update(self.fit_bounds)
|
|
170
|
+
|
|
171
|
+
mask = exp_map > 0 # Handles fully overlapping exclusion regions in the 'size' seed computation
|
|
172
|
+
# Seeds the charge normalisation to the observed counts corrected for exclusion region reduction to exposure
|
|
173
|
+
raw_seeds['size'] = np.sum(count_map[mask] * exp_map_total[mask] / exp_map[mask]) / np.mean(mask)
|
|
174
|
+
bounds['size'] = (raw_seeds['size'] * 0.1, raw_seeds['size'] * 10)
|
|
175
|
+
|
|
176
|
+
# reorder seeds to fnc parameter order
|
|
177
|
+
param_fnc = list(fnc.__code__.co_varnames[:fnc.__code__.co_argcount])
|
|
178
|
+
param_fnc.remove('x')
|
|
179
|
+
param_fnc.remove('y')
|
|
180
|
+
seeds = {key: raw_seeds[key] for key in param_fnc}
|
|
181
|
+
|
|
182
|
+
x, y = np.meshgrid(centers, centers)
|
|
183
|
+
|
|
184
|
+
log_factorial_count_map = log_factorial(count_map)
|
|
185
|
+
|
|
186
|
+
def f(*args):
|
|
187
|
+
return -np.sum(
|
|
188
|
+
log_poisson(count_map, fnc(x, y, *args) * exp_map / exp_map_total, log_factorial_count_map))
|
|
189
|
+
|
|
190
|
+
logger.info(f"seeds :\n{seeds}")
|
|
191
|
+
m = Minuit(f,
|
|
192
|
+
name=seeds.keys(),
|
|
193
|
+
*seeds.values())
|
|
194
|
+
for key, bound in bounds.items():
|
|
195
|
+
if bound is None:
|
|
196
|
+
m.fixed[key] = True
|
|
197
|
+
else:
|
|
198
|
+
m.limits[key] = bound
|
|
199
|
+
m.errordef = Minuit.LIKELIHOOD
|
|
200
|
+
m.simplex().migrad()
|
|
201
|
+
if logger.level <= logging.INFO:
|
|
202
|
+
func = fnc(x, y, **m.values.to_dict()) * exp_map / exp_map_total
|
|
203
|
+
func[exp_map == 0] = 1
|
|
204
|
+
rel_residuals = 100 * (count_map - func) / func
|
|
205
|
+
logger.info(f"Fit valid : {m.valid}\n"
|
|
206
|
+
f"Results ({fnc.__name__}) :\n{m.values.to_dict()}")
|
|
207
|
+
logger.info("Average relative residuals : %.1f %%," % (np.mean(rel_residuals)) +
|
|
208
|
+
"Std = %.2f %%" % (np.std(rel_residuals)) + "\n")
|
|
209
|
+
|
|
210
|
+
return fnc(x, y, **m.values.to_dict())
|
|
211
|
+
|
|
212
|
+
def create_acceptance_map(self, observations: Observations) -> Background3D:
|
|
213
|
+
"""
|
|
214
|
+
Calculate a 3D grid acceptance map
|
|
215
|
+
|
|
216
|
+
Parameters
|
|
217
|
+
----------
|
|
218
|
+
observations : gammapy.data.observations.Observations
|
|
219
|
+
The collection of observations used to make the acceptance map
|
|
220
|
+
|
|
221
|
+
Returns
|
|
222
|
+
-------
|
|
223
|
+
acceptance_map : gammapy.irf.background.Background3D
|
|
224
|
+
"""
|
|
225
|
+
|
|
226
|
+
# Compute base data
|
|
227
|
+
count_background, exp_map_background, exp_map_background_total, livetime = self._create_base_computation_map(
|
|
228
|
+
observations)
|
|
229
|
+
|
|
230
|
+
# Downsample map to bkg model resolution
|
|
231
|
+
exp_map_background_downsample = exp_map_background.downsample(self.oversample_map, preserve_counts=True)
|
|
232
|
+
exp_map_background_total_downsample = exp_map_background_total.downsample(self.oversample_map,
|
|
233
|
+
preserve_counts=True)
|
|
234
|
+
|
|
235
|
+
# Create axis for bkg model
|
|
236
|
+
edges = self.offset_axis.edges
|
|
237
|
+
extended_edges = np.concatenate((-np.flip(edges), edges[1:]), axis=None)
|
|
238
|
+
extended_offset_axis_x = MapAxis.from_edges(extended_edges, name='fov_lon')
|
|
239
|
+
bin_width_x = np.repeat(extended_offset_axis_x.bin_width[:, np.newaxis], extended_offset_axis_x.nbin, axis=1)
|
|
240
|
+
extended_offset_axis_y = MapAxis.from_edges(extended_edges, name='fov_lat')
|
|
241
|
+
bin_width_y = np.repeat(extended_offset_axis_y.bin_width[np.newaxis, :], extended_offset_axis_y.nbin, axis=0)
|
|
242
|
+
|
|
243
|
+
# Compute acceptance_map
|
|
244
|
+
|
|
245
|
+
if self.method == 'stack':
|
|
246
|
+
corrected_counts = count_background * (exp_map_background_total_downsample.data /
|
|
247
|
+
exp_map_background_downsample.data)
|
|
248
|
+
elif self.method == 'fit':
|
|
249
|
+
logger.info(f"Performing the background fit using {self.fit_fnc}.")
|
|
250
|
+
corrected_counts = np.empty(count_background.shape)
|
|
251
|
+
for e in range(count_background.shape[0]):
|
|
252
|
+
logger.info(f"Energy bin : [{self.energy_axis.edges[e]:.2f},{self.energy_axis.edges[e + 1]:.2f}]")
|
|
253
|
+
corrected_counts[e] = self.fit_background(count_background[e].astype(int),
|
|
254
|
+
exp_map_background_total_downsample.data[e],
|
|
255
|
+
exp_map_background_downsample.data[e],
|
|
256
|
+
)
|
|
257
|
+
else:
|
|
258
|
+
raise NotImplementedError(f"Requested method '{self.method}' is not valid.")
|
|
259
|
+
solid_angle = 4. * (np.sin(bin_width_x / 2.) * np.sin(bin_width_y / 2.)) * u.steradian
|
|
260
|
+
data_background = corrected_counts / solid_angle[np.newaxis, :, :] / self.energy_axis.bin_width[:, np.newaxis,
|
|
261
|
+
np.newaxis] / livetime
|
|
262
|
+
|
|
263
|
+
acceptance_map = Background3D(axes=[self.energy_axis, extended_offset_axis_x, extended_offset_axis_y],
|
|
264
|
+
data=data_background.to(u.Unit('s-1 MeV-1 sr-1')),
|
|
265
|
+
fov_alignment=FoVAlignment.ALTAZ)
|
|
266
|
+
|
|
267
|
+
return acceptance_map
|
|
268
|
+
|
|
269
|
+
def _create_base_computation_map(self, observations: Observations) -> Tuple[
|
|
270
|
+
np.ndarray, WcsNDMap, WcsNDMap, u.Quantity]:
|
|
271
|
+
"""
|
|
272
|
+
From a list of observations return a stacked finely binned counts and exposure map in camera frame to compute a
|
|
273
|
+
model
|
|
274
|
+
|
|
275
|
+
Parameters
|
|
276
|
+
----------
|
|
277
|
+
observations : gammapy.data.observations.Observations
|
|
278
|
+
The list of observations
|
|
279
|
+
|
|
280
|
+
Returns
|
|
281
|
+
-------
|
|
282
|
+
count_background : numpy.ndarray
|
|
283
|
+
The background counts
|
|
284
|
+
exp_map_background : gammapy.map.WcsNDMap
|
|
285
|
+
The exposure map corrected for exclusion regions
|
|
286
|
+
exp_map_background_total : gammapy.map.WcsNDMap
|
|
287
|
+
The exposure map without correction for exclusion regions
|
|
288
|
+
livetime : astropy.unit.Quantity
|
|
289
|
+
The total exposure time for the model
|
|
290
|
+
"""
|
|
291
|
+
count_background = np.zeros((len(self.map_bins[0]) - 1,
|
|
292
|
+
len(self.map_bins[1]) - 1,
|
|
293
|
+
len(self.map_bins[2]) - 1))
|
|
294
|
+
exp_map_background = WcsNDMap(geom=self.geom, unit=u.s)
|
|
295
|
+
exp_map_background_total = WcsNDMap(geom=self.geom, unit=u.s)
|
|
296
|
+
livetime = 0. * u.s
|
|
297
|
+
|
|
298
|
+
with erfa_astrom.set(ErfaAstromInterpolator(1000 * u.s)):
|
|
299
|
+
for obs in observations:
|
|
300
|
+
# Filter events in exclusion regions
|
|
301
|
+
geom = RegionGeom.from_regions(self.exclude_regions)
|
|
302
|
+
mask = geom.contains(obs.events.radec)
|
|
303
|
+
obs._events = obs.events.select_row_subset(~mask)
|
|
304
|
+
# Create a count map in camera frame
|
|
305
|
+
events_camera_frame = self._get_events_in_camera_frame(obs)
|
|
306
|
+
count_obs, _ = np.histogramdd((obs.events.energy,
|
|
307
|
+
-events_camera_frame.lon,
|
|
308
|
+
events_camera_frame.lat
|
|
309
|
+
),
|
|
310
|
+
bins=self.map_bins)
|
|
311
|
+
# Create exposure maps and fill them with the obs livetime
|
|
312
|
+
exp_map_obs = MapDataset.create(geom=self.geom)
|
|
313
|
+
exp_map_obs_total = MapDataset.create(geom=self.geom)
|
|
314
|
+
exp_map_obs.counts.data = obs.observation_live_time_duration.value
|
|
315
|
+
exp_map_obs_total.counts.data = obs.observation_live_time_duration.value
|
|
316
|
+
|
|
317
|
+
# Evaluate the average exclusion mask in camera frame
|
|
318
|
+
# by evaluating it on time intervals short compared to the field of view rotation
|
|
319
|
+
exclusion_mask = np.zeros(exp_map_obs.counts.data.shape[1:])
|
|
320
|
+
time_interval = self._compute_time_intervals_based_on_fov_rotation(obs)
|
|
321
|
+
for i in range(len(time_interval) - 1):
|
|
322
|
+
# Compute the exclusion region in camera frame for the average time
|
|
323
|
+
dtime = time_interval[i + 1] - time_interval[i]
|
|
324
|
+
time = time_interval[i] + dtime / 2
|
|
325
|
+
average_alt_az_frame = AltAz(obstime=time,
|
|
326
|
+
location=obs.observatory_earth_location)
|
|
327
|
+
average_alt_az_pointing = obs.get_pointing_icrs(time).transform_to(average_alt_az_frame)
|
|
328
|
+
exclusion_region_camera_frame = self._transform_exclusion_region_to_camera_frame(
|
|
329
|
+
average_alt_az_pointing)
|
|
330
|
+
geom_image = self.geom.to_image()
|
|
331
|
+
|
|
332
|
+
exclusion_mask_t = ~geom_image.region_mask(exclusion_region_camera_frame) if len(
|
|
333
|
+
exclusion_region_camera_frame) > 0 else ~Map.from_geom(geom_image)
|
|
334
|
+
# Add the exclusion mask in camera frame weighted by the time interval duration
|
|
335
|
+
exclusion_mask += exclusion_mask_t * (dtime).value
|
|
336
|
+
# Normalise the exclusion mask by the full observation duration
|
|
337
|
+
exclusion_mask *= 1 / (time_interval[-1] - time_interval[0]).value
|
|
338
|
+
|
|
339
|
+
# Correct the exposure map by the exclusion region
|
|
340
|
+
for j in range(exp_map_obs.counts.data.shape[0]):
|
|
341
|
+
exp_map_obs.counts.data[j, :, :] = exp_map_obs.counts.data[j, :, :] * exclusion_mask
|
|
342
|
+
|
|
343
|
+
# Stack counts and exposure maps and livetime of all observations
|
|
344
|
+
count_background += count_obs
|
|
345
|
+
exp_map_background.data += exp_map_obs.counts.data
|
|
346
|
+
exp_map_background_total.data += exp_map_obs_total.counts.data
|
|
347
|
+
livetime += obs.observation_live_time_duration
|
|
348
|
+
|
|
349
|
+
return count_background, exp_map_background, exp_map_background_total, livetime
|
baccmod/modeling.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# -------------------------------------------------------------------
|
|
3
|
+
# Filename: modeling.py
|
|
4
|
+
# Purpose: Collection of function for fitting analytic model of background
|
|
5
|
+
#
|
|
6
|
+
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
|
7
|
+
# 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 Lesser General Public License for more details.
|
|
8
|
+
# ---------------------------------------------------------------------
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
"""
|
|
12
|
+
Define the background model functions for fits and associated seeds and bounds.
|
|
13
|
+
"""
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
__all__ = ['bilinear_gaussian2d',
|
|
17
|
+
'FIT_FUNCTION',
|
|
18
|
+
'gaussian2d',
|
|
19
|
+
'log_factorial',
|
|
20
|
+
'log_poisson']
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def log_factorial(count_map):
|
|
24
|
+
"""
|
|
25
|
+
Returns the log of the factorial of elements of `count_map` while computing each value only once.
|
|
26
|
+
Parameters
|
|
27
|
+
----------
|
|
28
|
+
count_map: Array-like of integers
|
|
29
|
+
Input for which we want the factorial of all elements
|
|
30
|
+
Returns
|
|
31
|
+
-------
|
|
32
|
+
The factorial of count_map in log scale
|
|
33
|
+
"""
|
|
34
|
+
max_input = np.max(count_map)
|
|
35
|
+
all_int = np.arange(0, max_input + 1)
|
|
36
|
+
all_int[0] = 1
|
|
37
|
+
log_int = np.log(all_int)
|
|
38
|
+
log_int_factorials = np.cumsum(log_int)
|
|
39
|
+
log_factorial_count_map = log_int_factorials[count_map]
|
|
40
|
+
return log_factorial_count_map
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def log_poisson(x, mu, log_factorial_x):
|
|
44
|
+
return -mu + x * np.log(mu) - log_factorial_x
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def gaussian2d(x, y, size, x_cm, y_cm, width, length, psi):
|
|
48
|
+
"""
|
|
49
|
+
Evaluate the bi-dimensional gaussian law.
|
|
50
|
+
Parameters
|
|
51
|
+
----------
|
|
52
|
+
x, y: float 1D array
|
|
53
|
+
Position at which the log gaussian is evaluated
|
|
54
|
+
size: float
|
|
55
|
+
Integral of the 2D Gaussian at the provided coordinates
|
|
56
|
+
x_cm, y_cm: float
|
|
57
|
+
Center of the 2D Gaussian
|
|
58
|
+
width, length: float
|
|
59
|
+
Standard deviations of the 2 dimensions of the 2D Gaussian law
|
|
60
|
+
psi: float
|
|
61
|
+
Orientation of the 2D Gaussian
|
|
62
|
+
Returns
|
|
63
|
+
-------
|
|
64
|
+
gauss2d: float 1D array
|
|
65
|
+
Evaluation of the 2D gaussian law at (x,y)
|
|
66
|
+
"""
|
|
67
|
+
# Compute the x and y coordinates projection in the 2D gaussian length and width coordinates
|
|
68
|
+
le = (x - x_cm) * np.cos(psi) + (y - y_cm) * np.sin(psi)
|
|
69
|
+
wi = -(x - x_cm) * np.sin(psi) + (y - y_cm) * np.cos(psi)
|
|
70
|
+
a = 2 * length ** 2
|
|
71
|
+
b = 2 * width ** 2
|
|
72
|
+
# Evaluate the 2D gaussian term
|
|
73
|
+
gauss2d = np.exp(-(le ** 2 / a + wi ** 2 / b))
|
|
74
|
+
gauss2d = size / np.sum(gauss2d) * gauss2d
|
|
75
|
+
return gauss2d
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
gaussian2d.default_seeds = {'x_cm': 0, 'y_cm': 0, 'width': 1, 'length': 1, 'psi': 0}
|
|
79
|
+
gaussian2d.default_bounds = {'x_cm': (-5, 5), 'y_cm': (-5, 5), 'width': (-5, 5), 'length': (-5, 5),
|
|
80
|
+
'psi': (0, 2 * np.pi)}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def bilinear_gaussian2d(x, y, size, x_cm, y_cm, width, length, psi, x_gradient, y_gradient):
|
|
84
|
+
"""
|
|
85
|
+
Adds linear gradients to `gaussian2d`
|
|
86
|
+
Parameters
|
|
87
|
+
----------
|
|
88
|
+
x, y, size, x_cm, y_cm, width, length, psi: see `gaussian2d`
|
|
89
|
+
x_gradient: float
|
|
90
|
+
y_gradient: float
|
|
91
|
+
"""
|
|
92
|
+
return (1 + x * x_gradient) * (1 + y * y_gradient) * gaussian2d(x, y, size, x_cm, y_cm, width, length, psi)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
bilinear_gaussian2d.default_seeds = {'x_cm': 0, 'y_cm': 0, 'width': 1, 'length': 1, 'psi': 0, 'x_gradient': 0,
|
|
96
|
+
'y_gradient': 0}
|
|
97
|
+
bilinear_gaussian2d.default_bounds = {'x_cm': (-5, 5), 'y_cm': (-5, 5), 'width': (-5, 5), 'length': (-5, 5),
|
|
98
|
+
'psi': (0, 2 * np.pi), 'x_gradient': (-5, 5), 'y_gradient': (-5, 5)}
|
|
99
|
+
|
|
100
|
+
FIT_FUNCTION = {'gaussian2d': gaussian2d,
|
|
101
|
+
'bilinear_gaussian2d': bilinear_gaussian2d}
|