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.
@@ -0,0 +1,1005 @@
1
+ # -*- coding: utf-8 -*-
2
+ # -------------------------------------------------------------------
3
+ # Filename: base_acceptance_map_creator.py
4
+ # Purpose: Base class for common functionalities in background model creation
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 copy
12
+ import logging
13
+ from abc import ABC, abstractmethod
14
+ from typing import Tuple, List, Optional, Union
15
+
16
+ import astropy.units as u
17
+ import numpy as np
18
+ from astropy.coordinates import SkyCoord, AltAz, SkyOffsetFrame
19
+ from astropy.coordinates.erfa_astrom import erfa_astrom, ErfaAstromInterpolator
20
+ from astropy.time import Time
21
+ from gammapy.data import Observations, Observation
22
+ from gammapy.datasets import MapDataset
23
+ from gammapy.irf import FoVAlignment, Background2D, Background3D
24
+ from gammapy.irf.background import BackgroundIRF
25
+ from gammapy.makers import MapDatasetMaker, SafeMaskMaker, FoVBackgroundMaker
26
+ from gammapy.maps import WcsNDMap, WcsGeom, Map, MapAxis
27
+ from regions import CircleSkyRegion, EllipseSkyRegion, SkyRegion
28
+ from scipy.integrate import cumulative_trapezoid
29
+ from scipy.interpolate import interp1d
30
+
31
+ from .bkg_collection import BackgroundCollectionZenith
32
+ from .exception import BackgroundModelFormatException
33
+ from .toolbox import (compute_rotation_speed_fov,
34
+ get_unique_wobble_pointings,
35
+ get_time_mini_irf,
36
+ generate_irf_from_mini_irf,
37
+ compute_neighbour_condition_validation)
38
+
39
+ logger = logging.getLogger(__name__)
40
+
41
+
42
+ class BaseAcceptanceMapCreator(ABC):
43
+
44
+ def __init__(self,
45
+ energy_axis: MapAxis,
46
+ max_offset: u.Quantity,
47
+ spatial_resolution: u.Quantity,
48
+ exclude_regions: Optional[List[SkyRegion]] = None,
49
+ cos_zenith_binning_method: str = 'min_livetime',
50
+ cos_zenith_binning_parameter_value: int = 3600,
51
+ initial_cos_zenith_binning: float = 0.01,
52
+ max_angular_separation_wobble: u.Quantity = 0.4 * u.deg,
53
+ zenith_binning_run_splitting: bool = False,
54
+ max_fraction_pixel_rotation_fov: float = 0.5,
55
+ time_resolution: u.Quantity = 0.1 * u.s,
56
+ use_mini_irf_computation: bool = False,
57
+ mini_irf_time_resolution: u.Quantity = 1. * u.min,
58
+ interpolation_type: str = 'linear',
59
+ activate_interpolation_cleaning: bool = False,
60
+ interpolation_cleaning_energy_relative_threshold: float = 1e-4,
61
+ interpolation_cleaning_spatial_relative_threshold: float = 1e-2) -> None:
62
+ """
63
+ Create the class for calculating radial acceptance model.
64
+
65
+ Parameters
66
+ ----------
67
+ energy_axis : gammapy.maps.geom.MapAxis
68
+ The energy axis for the acceptance model
69
+ max_offset : astropy.units.Quantity
70
+ The offset corresponding to the edge of the model
71
+ spatial_resolution : astropy.units.Quantity
72
+ The spatial resolution
73
+ exclude_regions : list of regions.SkyRegion, optional
74
+ Regions with known or putative gamma-ray emission, will be excluded from the calculation of the acceptance map
75
+ cos_zenith_binning_method : str, optional
76
+ The method used for cos zenith binning: 'min_livetime', 'min_livetime_per_wobble', 'min_n_observation', 'min_n_observation_per_wobble'
77
+ cos_zenith_binning_parameter_value : int, optional
78
+ Minimum livetime (in seconds) or number of observations per zenith bins
79
+ initial_cos_zenith_binning : float, optional
80
+ Initial bin size for cos zenith binning
81
+ max_angular_separation_wobble : u.Quantity, optional
82
+ The maximum angular separation between identified wobbles, in degrees
83
+ zenith_binning_run_splitting : bool, optional
84
+ If true, will split each run to match zenith binning for the base model computation
85
+ Could be computationally expensive, especially at high zenith with a high resolution zenith binning
86
+ max_fraction_pixel_rotation_fov : float, optional
87
+ For camera frame transformation the maximum size relative to a pixel a rotation is allowed
88
+ time_resolution : astropy.units.Quantity, optional
89
+ Time resolution to use for the computation of the rotation of the FoV and cut as function of the zenith bins
90
+ use_mini_irf_computation : bool, optional
91
+ 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).
92
+ A model will be computed for each sub run before averaging them to obtain the final model for the run.
93
+ Should improve the accuracy of the model, especially at high zenith angle.
94
+ mini_irf_time_resolution : astropy.units.Quantity, optional
95
+ Time resolution to use for mini irf used for computation of the final background model
96
+ interpolation_type: str, optional
97
+ 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
98
+ activate_interpolation_cleaning: bool, optional
99
+ If true, will activate the cleaning step after interpolation, it should help to eliminate artefact caused by interpolation
100
+ interpolation_cleaning_energy_relative_threshold: float, optional
101
+ To be considered value, the bin in energy need at least one adjacent bin with a relative difference within this range
102
+ interpolation_cleaning_spatial_relative_threshold: float, optional
103
+ To be considered value, the bin in space need at least one adjacent bin with a relative difference within this range
104
+ """
105
+
106
+ # If no exclusion region, default it as an empty list
107
+ if exclude_regions is None:
108
+ exclude_regions = []
109
+
110
+ # Store base parameter
111
+ self.energy_axis = energy_axis
112
+ self.max_offset = max_offset
113
+ self.exclude_regions = exclude_regions
114
+
115
+ # Calculate map parameter
116
+ self.n_bins_map = 2 * int(np.rint((self.max_offset / spatial_resolution).to(u.dimensionless_unscaled)))
117
+ self.spatial_bin_size = self.max_offset / (self.n_bins_map / 2)
118
+ self.center_map = SkyCoord(ra=0. * u.deg, dec=0. * u.deg, frame='icrs')
119
+ self.geom = WcsGeom.create(skydir=self.center_map, npix=(self.n_bins_map, self.n_bins_map),
120
+ binsz=self.spatial_bin_size, frame="icrs", axes=[self.energy_axis])
121
+ logger.info(
122
+ 'Computation will be made with a bin size of {:.3f} arcmin'.format(
123
+ self.spatial_bin_size.to_value(u.arcmin)))
124
+
125
+ # Store computation parameters for run splitting
126
+ self.max_fraction_pixel_rotation_fov = max_fraction_pixel_rotation_fov
127
+ self.time_resolution = time_resolution
128
+ self.zenith_binning_run_splitting = zenith_binning_run_splitting
129
+
130
+ # Store zenith binning parameters
131
+ self.cos_zenith_binning_method = cos_zenith_binning_method
132
+ self.cos_zenith_binning_parameter_value = cos_zenith_binning_parameter_value
133
+ self.initial_cos_zenith_binning = initial_cos_zenith_binning
134
+ self.max_angular_separation_wobble = max_angular_separation_wobble
135
+
136
+ # Store interpolation parameters
137
+ self.threshold_value_log_interpolation = np.finfo(np.float64).tiny
138
+ self.interpolation_type = interpolation_type
139
+
140
+ # Store cleaning parameters for models created from interpolation
141
+ self.activate_interpolation_cleaning = activate_interpolation_cleaning
142
+ self.interpolation_cleaning_energy_relative_threshold = interpolation_cleaning_energy_relative_threshold
143
+ self.interpolation_cleaning_spatial_relative_threshold = interpolation_cleaning_spatial_relative_threshold
144
+ self.max_cleaning_iteration = 50
145
+
146
+ # Store mini irf computation parameters
147
+ self.use_mini_irf_computation = use_mini_irf_computation
148
+ self.mini_irf_time_resolution = mini_irf_time_resolution
149
+
150
+ @staticmethod
151
+ def _get_events_in_camera_frame(obs: Observation) -> SkyCoord:
152
+ """
153
+ Transform events and pointing of an obs from a sky frame to camera frame
154
+
155
+ Parameters
156
+ ----------
157
+ obs : gammapy.data.observations.Observation
158
+ The observation to transform
159
+
160
+ Returns
161
+ -------
162
+ events_camera_frame : astropy.coordinates.SkyCoord
163
+ The events coordinates for reference in camera frame
164
+ """
165
+
166
+ # Transform to altaz frame
167
+ altaz_frame = AltAz(obstime=obs.events.time,
168
+ location=obs.observatory_earth_location)
169
+ events_altaz = obs.events.radec.transform_to(altaz_frame)
170
+ pointing_altaz = obs.get_pointing_icrs(obs.events.time).transform_to(altaz_frame)
171
+
172
+ # Rotation to transform to camera frame
173
+ camera_frame = SkyOffsetFrame(origin=AltAz(alt=pointing_altaz.alt,
174
+ az=pointing_altaz.az,
175
+ obstime=obs.events.time,
176
+ location=obs.observatory_earth_location),
177
+ rotation=[0., ] * len(obs.events.time) * u.deg)
178
+
179
+ return events_altaz.transform_to(camera_frame)
180
+
181
+ @staticmethod
182
+ def _transform_obs_to_camera_frame(obs: Observation) -> Observation:
183
+ """
184
+ Transform events and pointing of an obs from a sky frame to camera frame
185
+
186
+ Parameters
187
+ ----------
188
+ obs : gammapy.data.observations.Observation
189
+ The observation to transform
190
+
191
+ Returns
192
+ -------
193
+ obs_camera_frame : gammapy.data.observations.Observation
194
+ The observation transformed for reference in camera frame
195
+ """
196
+
197
+ # Transform to altaz frame
198
+ altaz_frame = AltAz(obstime=obs.events.time,
199
+ location=obs.observatory_earth_location)
200
+ events_altaz = obs.events.radec.transform_to(altaz_frame)
201
+ pointing_altaz = obs.get_pointing_icrs(obs.events.time).transform_to(altaz_frame)
202
+
203
+ # Rotation to transform to camera frame
204
+ camera_frame = SkyOffsetFrame(origin=AltAz(alt=pointing_altaz.alt,
205
+ az=pointing_altaz.az,
206
+ obstime=obs.events.time,
207
+ location=obs.observatory_earth_location),
208
+ rotation=[0., ] * len(obs.events.time) * u.deg)
209
+ events_camera_frame = events_altaz.transform_to(camera_frame)
210
+
211
+ # Formatting data for the output
212
+ camera_frame_events = obs.events.copy()
213
+ camera_frame_events.table['RA'] = events_camera_frame.lon
214
+ camera_frame_events.table['DEC'] = events_camera_frame.lat
215
+ camera_frame_obs_info = copy.deepcopy(obs.obs_info)
216
+ camera_frame_obs_info['RA_PNT'] = 0.
217
+ camera_frame_obs_info['DEC_PNT'] = 0.
218
+ obs_camera_frame = Observation(obs_id=obs.obs_id,
219
+ obs_info=camera_frame_obs_info,
220
+ events=camera_frame_events,
221
+ gti=obs.gti,
222
+ aeff=obs.aeff)
223
+ obs_camera_frame._location = obs.observatory_earth_location
224
+
225
+ return obs_camera_frame
226
+
227
+ def _transform_exclusion_region_to_camera_frame(self, pointing_altaz: AltAz) -> List[SkyRegion]:
228
+ """
229
+ Transform the list of exclusion regions in sky frame into a list in camera frame.
230
+
231
+ Parameters
232
+ ----------
233
+ pointing_altaz : astropy.coordinates.AltAz
234
+ The pointing position of the telescope.
235
+
236
+ Returns
237
+ -------
238
+ exclusion_region_camera_frame : list of regions.SkyRegion
239
+ The list of exclusion regions in camera frame.
240
+
241
+ Raises
242
+ ------
243
+ Exception
244
+ If the region type is not supported.
245
+ """
246
+
247
+ camera_frame = SkyOffsetFrame(origin=pointing_altaz,
248
+ rotation=[0., ] * u.deg)
249
+ exclude_region_camera_frame = []
250
+ for region in self.exclude_regions:
251
+ if isinstance(region, CircleSkyRegion):
252
+ center_coordinate = region.center
253
+ center_coordinate_altaz = center_coordinate.transform_to(pointing_altaz)
254
+ center_coordinate_camera_frame = center_coordinate_altaz.transform_to(camera_frame)
255
+ center_coordinate_camera_frame_arb = SkyCoord(ra=-center_coordinate_camera_frame.lat[0],
256
+ dec=-center_coordinate_camera_frame.lon[0])
257
+ exclude_region_camera_frame.append(CircleSkyRegion(center=center_coordinate_camera_frame_arb,
258
+ radius=region.radius))
259
+ elif isinstance(region, EllipseSkyRegion):
260
+ center_coordinate = region.center
261
+ center_coordinate_altaz = center_coordinate.transform_to(pointing_altaz)
262
+ center_coordinate_camera_frame = center_coordinate_altaz.transform_to(camera_frame)
263
+ width_coordinate = center_coordinate.directional_offset_by(region.angle, region.width)
264
+ width_coordinate_altaz = width_coordinate.transform_to(pointing_altaz)
265
+ width_coordinate_camera_frame = width_coordinate_altaz.transform_to(camera_frame)
266
+ center_coordinate_camera_frame_arb = SkyCoord(ra=-center_coordinate_camera_frame.lat[0],
267
+ dec=-center_coordinate_camera_frame.lon[0])
268
+ width_coordinate_camera_frame_arb = SkyCoord(ra=-width_coordinate_camera_frame.lat,
269
+ dec=-width_coordinate_camera_frame.lon)
270
+ angle_camera_frame_arb = center_coordinate_camera_frame_arb.position_angle(width_coordinate_camera_frame_arb).to(u.deg)[0]
271
+ exclude_region_camera_frame.append(EllipseSkyRegion(center=center_coordinate_camera_frame_arb,
272
+ width=region.width, height=region.height,
273
+ angle=angle_camera_frame_arb))
274
+ else:
275
+ raise Exception(f'{type(region)} region type not supported')
276
+
277
+ return exclude_region_camera_frame
278
+
279
+ def _create_map(self,
280
+ obs: Observation,
281
+ geom: WcsGeom,
282
+ exclude_regions: List[SkyRegion],
283
+ add_bkg: bool = False
284
+ ) -> Tuple[MapDataset, WcsNDMap]:
285
+ """
286
+ Create a map and the associated exclusion mask based on the given geometry and exclusion region.
287
+
288
+ Parameters
289
+ ----------
290
+ obs : gammapy.data.observations.Observation
291
+ The observation used to make the sky map.
292
+ geom : gammapy.maps.WcsGeom
293
+ The geometry for the maps.
294
+ exclude_regions : list of regions.SkyRegion
295
+ The list of exclusion regions.
296
+ add_bkg : bool, optional
297
+ If true, will also add the background model to the map. Default is False.
298
+
299
+ Returns
300
+ -------
301
+ map_dataset : gammapy.datasets.MapDataset
302
+ The map dataset.
303
+ exclusion_mask : gammapy.maps.WcsNDMap
304
+ The exclusion mask.
305
+ """
306
+
307
+ maker = MapDatasetMaker(selection=["counts"])
308
+ if add_bkg:
309
+ maker = MapDatasetMaker(selection=["counts", "background"])
310
+
311
+ maker_safe_mask = SafeMaskMaker(methods=["offset-max"], offset_max=self.max_offset)
312
+
313
+ geom_image = geom.to_image()
314
+ exclusion_mask = ~geom_image.region_mask(exclude_regions) if len(exclude_regions) > 0 else ~Map.from_geom(
315
+ geom_image)
316
+
317
+ map_obs = maker.run(MapDataset.create(geom=geom), obs)
318
+ map_obs = maker_safe_mask.run(map_obs, obs)
319
+
320
+ return map_obs, exclusion_mask
321
+
322
+ def _create_sky_map(self,
323
+ obs: Observation,
324
+ add_bkg: bool = False
325
+ ) -> Tuple[MapDataset, WcsNDMap]:
326
+ """
327
+ Create the sky map and the associated exclusion mask based on the observation and the exclusion regions.
328
+
329
+ Parameters
330
+ ----------
331
+ obs : gammapy.data.observations.Observation
332
+ The observation used to make the sky map.
333
+ add_bkg : bool, optional
334
+ If true, will also add the background model to the map. Default is False.
335
+
336
+ Returns
337
+ -------
338
+ map_dataset : gammapy.datasets.MapDataset
339
+ The map dataset.
340
+ exclusion_mask : gammapy.maps.WcsNDMap
341
+ The exclusion mask.
342
+ """
343
+
344
+ geom_obs = WcsGeom.create(skydir=obs.get_pointing_icrs(obs.tmid),
345
+ npix=(self.n_bins_map, self.n_bins_map),
346
+ binsz=self.spatial_bin_size,
347
+ frame="icrs",
348
+ axes=[self.energy_axis])
349
+ map_obs, exclusion_mask = self._create_map(obs, geom_obs, self.exclude_regions, add_bkg=add_bkg)
350
+
351
+ return map_obs, exclusion_mask
352
+
353
+ def _compute_time_intervals_based_on_fov_rotation(self, obs: Observation) -> Time:
354
+ """
355
+ Calculate time intervals based on the rotation of the Field of View (FoV).
356
+
357
+ Parameters
358
+ ----------
359
+ obs : gammapy.data.observations.Observation
360
+ The observation used to calculate time intervals.
361
+
362
+ Returns
363
+ -------
364
+ time_intervals : astropy.time.Time
365
+ The time intervals for cutting the observation into time bins.
366
+ """
367
+
368
+ # Determine time interval for cutting the obs as function of the rotation of the Fov
369
+ n_bin = max(2, int(np.rint(
370
+ ((obs.tstop - obs.tstart) / self.time_resolution).to_value(u.dimensionless_unscaled))))
371
+ time_axis = np.linspace(obs.tstart, obs.tstop, num=n_bin)
372
+ rotation_speed_fov = compute_rotation_speed_fov(time_axis, obs.get_pointing_icrs(obs.tmid),
373
+ obs.observatory_earth_location)
374
+ rotation_fov = cumulative_trapezoid(x=time_axis.unix_tai,
375
+ y=rotation_speed_fov.to_value(u.rad / u.s),
376
+ initial=0.) * u.rad
377
+ distance_rotation_fov = rotation_fov.to_value(u.rad) * np.pi * self.max_offset
378
+ node_obs = distance_rotation_fov // (self.spatial_bin_size * self.max_fraction_pixel_rotation_fov)
379
+ change_node = node_obs[2:] != node_obs[1:-1]
380
+ time_interval = Time([obs.tstart, ] + [time_axis[1:-1][change_node], ] + [obs.tstop, ])
381
+
382
+ return time_interval
383
+
384
+ @abstractmethod
385
+ def create_acceptance_map(self, observations: Observations) -> BackgroundIRF:
386
+ """
387
+ Abstract method to calculate an acceptance map from a list of observations.
388
+
389
+ Subclasses must implement this method to provide the specific algorithm for calculating the acceptance map.
390
+
391
+ Parameters
392
+ ----------
393
+ observations : gammapy.data.observations.Observations
394
+ The collection of observations used to create the acceptance map.
395
+
396
+ Returns
397
+ -------
398
+ acceptance_map : gammapy.irf.background.Background2D or gammapy.irf.background.Background3D
399
+ The acceptance map calculated using the specific algorithm implemented by the subclass.
400
+ """
401
+ pass
402
+
403
+ def _create_base_computation_map(self, observations: Observation) -> Tuple:
404
+ """
405
+ Abstract method to calculate maps used in acceptance computation from a list of observations.
406
+
407
+ Subclasses must implement this method to provide the data used for calculating the acceptance map.
408
+
409
+ Parameters
410
+ ----------
411
+ observations : gammapy.data.observations.Observations
412
+ The collection of observations used to create the acceptance map.
413
+
414
+ Returns
415
+ -------
416
+ count_map_background : gammapy.map.WcsNDMap
417
+ The count map
418
+ exp_map_background : gammapy.map.WcsNDMap
419
+ The exposure map corrected for exclusion regions
420
+ exp_map_background_total : gammapy.map.WcsNDMap
421
+ The exposure map without correction for exclusion regions
422
+ livetime : astropy.unit.Quantity
423
+ The total exposure time for the model
424
+ """
425
+ pass
426
+
427
+ def _normalised_model_per_run(self,
428
+ observations: Observations,
429
+ acceptance_map: dict[int, BackgroundIRF]) -> dict[int, BackgroundIRF]:
430
+ """
431
+ Normalised the acceptance model associated to each run to the events associated with the run
432
+
433
+ Parameters
434
+ ----------
435
+ observations : gammapy.data.observations.Observations
436
+ The collection of observations used to make the acceptance map
437
+ acceptance_map :dict of gammapy.irf.background.Background2D or gammapy.irf.background.Background3D
438
+ A dict with observation number as key and a background model that could be used as an acceptance model associated at each key
439
+ This is the models that will be normalised
440
+ Returns
441
+ -------
442
+ background : dict of gammapy.irf.background.Background2D or gammapy.irf.background.Background3D
443
+ A dict with observation number as key and a background model that could be used as an acceptance model associated at each key
444
+ """
445
+
446
+ normalised_acceptance_map = {}
447
+ # Fit norm of the model to the observations
448
+ for obs in observations:
449
+ id_observation = obs.obs_id
450
+
451
+ # replace the background model
452
+ modified_observation = copy.deepcopy(obs)
453
+ modified_observation.bkg = acceptance_map[id_observation]
454
+
455
+ # Fit the background model
456
+ logger.info('Fit to model to run ' + str(id_observation))
457
+ map_obs, exclusion_mask = self._create_sky_map(modified_observation, add_bkg=True)
458
+ maker_FoV_background = FoVBackgroundMaker(method='fit', exclusion_mask=exclusion_mask)
459
+ map_obs = maker_FoV_background.run(map_obs)
460
+
461
+ # Extract the normalisation
462
+ parameters = map_obs.models.to_parameters_table()
463
+ norm_background = parameters[parameters['name'] == 'norm']['value'][0]
464
+
465
+ if norm_background < 0.:
466
+ logger.error(
467
+ 'Invalid normalisation value for run ' + str(id_observation) + ' : ' + str(
468
+ norm_background) + ', normalisation set back to 1')
469
+ norm_background = 1.
470
+ elif norm_background > 1.5 or norm_background < 0.5:
471
+ logger.warning(
472
+ 'High correction of the background normalisation for run ' + str(id_observation) + ' : ' + str(
473
+ norm_background))
474
+
475
+ # Apply normalisation to the background model
476
+ normalised_acceptance_map[id_observation] = copy.deepcopy(acceptance_map[id_observation])
477
+ normalised_acceptance_map[id_observation].data = normalised_acceptance_map[
478
+ id_observation].data * norm_background
479
+
480
+ return normalised_acceptance_map
481
+
482
+ def _compute_time_intervals_based_on_zenith_bin(self, obs: Observation, edge_zenith_bin: u.Quantity) -> Time:
483
+ """
484
+ Calculate time intervals based on an input zenith binning
485
+
486
+ Parameters
487
+ ----------
488
+ obs : gammapy.data.observations.Observation
489
+ The observation used to calculate time intervals.
490
+ edge_zenith_bin : astropy.units.Quantity
491
+ The edge of the bins used for zenith binning
492
+
493
+ Returns
494
+ -------
495
+ time_intervals : astropy.time.Time
496
+ The time intervals for cutting the observation into time bins.
497
+ """
498
+
499
+ # Create the time axis
500
+ n_bin = max(2, int(np.rint(
501
+ ((obs.tstop - obs.tstart) / self.time_resolution).to_value(u.dimensionless_unscaled))))
502
+ time_axis = np.linspace(obs.tstart, obs.tstop, num=n_bin)
503
+
504
+ # Compute the zenith for each evaluation time
505
+ with erfa_astrom.set(ErfaAstromInterpolator(1000 * u.s)):
506
+ altaz_coordinates = obs.get_pointing_altaz(time_axis)
507
+ zenith_values = altaz_coordinates.zen
508
+ if np.any(zenith_values < np.min(edge_zenith_bin)) or np.any(zenith_values > np.max(edge_zenith_bin)):
509
+ logger.error('Run with zenith value outside of the considered range for zenith binning')
510
+
511
+ # Split the time interval to transition between zenith bin
512
+ id_bin = np.digitize(zenith_values, edge_zenith_bin)
513
+ bin_transition = id_bin[2:] != id_bin[1:-1]
514
+ time_interval = Time([obs.tstart, ] + [time_axis[1:-1][bin_transition], ] + [obs.tstop, ])
515
+
516
+ return time_interval
517
+
518
+ def create_model_cos_zenith_binned(self,
519
+ observations: Observations
520
+ ) -> BackgroundCollectionZenith:
521
+ """
522
+ Calculate a model for each cos zenith bin
523
+
524
+ Parameters
525
+ ----------
526
+ observations : gammapy.data.observations.Observations
527
+ The collection of observations used to make the acceptance map
528
+
529
+ Returns
530
+ -------
531
+ background : BackgroundCollectionZenith
532
+ The collection of background model with the zenith associated to each model
533
+
534
+ """
535
+
536
+ # Determine binning method. Convention : per_wobble methods have negative values
537
+ methods = {'min_livetime': 1, 'min_livetime_per_wobble': -1, 'min_n_observation': 2,
538
+ 'min_n_observation_per_wobble': -2}
539
+ try:
540
+ i_method = methods[self.cos_zenith_binning_method]
541
+ except KeyError:
542
+ logger.error(f" KeyError : {self.cos_zenith_binning_method} not a valid zenith binning method.\nValid "
543
+ f"methods are {[*methods]}")
544
+ raise
545
+ per_wobble = i_method < 0
546
+
547
+ # Initial bins edges
548
+ cos_zenith_bin = np.sort(np.arange(1.0, 0. - self.initial_cos_zenith_binning, -self.initial_cos_zenith_binning))
549
+ zenith_bin = np.rad2deg(np.arccos(cos_zenith_bin)) * u.deg
550
+
551
+ # Cut observations if requested
552
+ if self.zenith_binning_run_splitting:
553
+ if abs(i_method) == 2:
554
+ logger.warning('Using a zenith binning requirement based on n_observation while using run splitting '
555
+ 'is not recommended and could lead to poor models. We recommend switching to a binning '
556
+ 'requirement based on livetime.')
557
+ compute_observations = Observations()
558
+ for obs in observations:
559
+ time_interval = self._compute_time_intervals_based_on_zenith_bin(obs, zenith_bin)
560
+ for i in range(len(time_interval) - 1):
561
+ compute_observations.append(obs.select_time(Time([time_interval[i], time_interval[i + 1]])))
562
+ else:
563
+ compute_observations = observations
564
+
565
+ # Determine initial bins values
566
+ cos_zenith_observations = np.array(
567
+ [np.cos(obs.get_pointing_altaz(obs.tmid).zen) for obs in compute_observations])
568
+ livetime_observations = np.array(
569
+ [obs.observation_live_time_duration.to_value(u.s) for obs in compute_observations])
570
+
571
+ # Select the quantity used to count observations
572
+ if i_method in [-1, 1]:
573
+ cut_variable_weights = livetime_observations
574
+ elif i_method in [-2, 2]:
575
+ cut_variable_weights = np.ones(len(cos_zenith_observations), dtype=int)
576
+
577
+ # Gather runs per separation angle or all together. Define the minimum multiplicity (-1) to create a zenith bin.
578
+ if per_wobble:
579
+ wobble_observations = np.array(
580
+ get_unique_wobble_pointings(compute_observations, self.max_angular_separation_wobble))
581
+ multiplicity_wob = 1
582
+ else:
583
+ wobble_observations = np.full(len(cos_zenith_observations), 'any', dtype=np.object_)
584
+ multiplicity_wob = 0
585
+
586
+ cumsum_variable = {}
587
+ for wobble in np.unique(wobble_observations):
588
+ # Create an array of cumulative weight of the selected variable vs cos(zenith)
589
+ cumsum_variable[wobble] = np.cumsum(np.histogram(cos_zenith_observations[wobble_observations == wobble],
590
+ bins=cos_zenith_bin,
591
+ weights=cut_variable_weights[
592
+ wobble_observations == wobble])[0])
593
+ # Initiate the list of index of selected zenith bin edges
594
+ zenith_selected = [0]
595
+
596
+ i = 0
597
+ n = len(cos_zenith_bin) - 2
598
+
599
+ while i < n:
600
+ # For each wobble, find the index of the first zenith which fulfills the zd binning criteria if any
601
+ # Then concatenate and sort the results for all wobbles
602
+ candidate_i_per_wobble = [np.nonzero(cum_cut_variable >= self.cos_zenith_binning_parameter_value)[0][:1]
603
+ for cum_cut_variable in cumsum_variable.values()] # nonzero is assumed sorted
604
+ candidate_i = np.sort(np.concatenate(candidate_i_per_wobble))
605
+
606
+ if len(candidate_i) > multiplicity_wob:
607
+ # If the criteria is fulfilled save the correct index.
608
+ # The first and only candidate_i in the non-per_wobble case and the second in the per_wobble case.
609
+ i = candidate_i[multiplicity_wob]
610
+ zenith_selected.append(i + 1)
611
+ for wobble in np.unique(wobble_observations):
612
+ # Reduce the cumulative sum by the value at the selected index for the next iteration
613
+ cumsum_variable[wobble] -= cumsum_variable[wobble][i]
614
+ else:
615
+ # The zenith bin creation criteria is not fulfilled, the last bin edge is set to the end of the
616
+ # cos(zenith) array
617
+ if i == 0:
618
+ zenith_selected.append(n + 1)
619
+ else:
620
+ zenith_selected[-1] = n + 1
621
+ i = n
622
+ cos_zenith_bin = cos_zenith_bin[zenith_selected]
623
+
624
+ # Associate each observation to the correct bin
625
+ binned_observations = []
626
+ for i in range((len(cos_zenith_bin) - 1)):
627
+ binned_observations.append(Observations())
628
+ for obs in compute_observations:
629
+ binned_observations[np.digitize(np.cos(obs.get_pointing_altaz(obs.tmid).zen), cos_zenith_bin) - 1].append(
630
+ obs)
631
+
632
+ # Compute the model for each bin
633
+ binned_model = [self.create_acceptance_map(binned_obs) for binned_obs in binned_observations]
634
+
635
+ # Determine the center of the bin (weighted as function of the livetime of each observation)
636
+ bin_center = []
637
+ for i in range(len(binned_observations)):
638
+ weighted_cos_zenith_bin_per_obs = []
639
+ livetime_per_obs = []
640
+ for obs in binned_observations[i]:
641
+ weighted_cos_zenith_bin_per_obs.append(
642
+ obs.observation_live_time_duration * np.cos(obs.get_pointing_altaz(obs.tmid).zen))
643
+ livetime_per_obs.append(obs.observation_live_time_duration)
644
+ bin_center.append(np.sum([wcos.value for wcos in weighted_cos_zenith_bin_per_obs]) / np.sum(
645
+ [livet.value for livet in livetime_per_obs]))
646
+
647
+ logger.info(f"cos zenith bin edges: {list(np.round(cos_zenith_bin, 2))}")
648
+ logger.info(f"cos zenith bin centers: {list(np.round(bin_center, 2))}")
649
+ logger.info(f"observation per bin: {list(np.histogram(cos_zenith_observations, bins=cos_zenith_bin)[0])}")
650
+ logger.info(f"livetime per bin [s]: " +
651
+ f"{list(np.histogram(cos_zenith_observations, bins=cos_zenith_bin, weights=livetime_observations)[0].astype(int))}")
652
+ if per_wobble:
653
+ wobble_observations_bool_arr = [(np.array(wobble_observations.tolist()) == wobble) for wobble in
654
+ np.unique(np.array(wobble_observations))]
655
+ livetime_observations_and_wobble = [np.array(livetime_observations) * wobble_bool for wobble_bool in
656
+ wobble_observations_bool_arr]
657
+ for i, wobble in enumerate(np.unique(np.array(wobble_observations))):
658
+ logger.info(
659
+ f"{wobble} observation per bin: {list(np.histogram(cos_zenith_observations, bins=cos_zenith_bin, weights=1 * wobble_observations_bool_arr[i])[0])}")
660
+ logger.info(
661
+ f"{wobble} livetime per bin: {list(np.histogram(cos_zenith_observations, bins=cos_zenith_bin, weights=livetime_observations_and_wobble[i])[0].astype(int))}")
662
+
663
+ # Create the dict for output of the function
664
+ collection_binned_model = BackgroundCollectionZenith()
665
+ for i in range(len(binned_model)):
666
+ collection_binned_model[np.rad2deg(np.arccos(bin_center[i]))] = binned_model[i]
667
+
668
+ return collection_binned_model
669
+
670
+ def create_acceptance_map_cos_zenith_binned(self,
671
+ observations: Observations,
672
+ off_observations: Observations = None,
673
+ base_model: BackgroundCollectionZenith = None
674
+ ) -> dict[int, BackgroundIRF]:
675
+ """
676
+ Calculate an acceptance map per run using cos zenith binning
677
+
678
+ Parameters
679
+ ----------
680
+ observations : gammapy.data.observations.Observations
681
+ The collection of observations to which the acceptance model will be applied
682
+ off_observations : gammapy.data.observations.Observations
683
+ The collection of observations used to generate the acceptance map, if None will be the observations provided as target
684
+ Will be ignored if a base_model parameter is provided
685
+ base_model : BackgroundCollectionZenith
686
+ If you have already a precomputed model, the method will use this model as base for the acceptance map instead of computing it from the data
687
+
688
+ Returns
689
+ -------
690
+ background : dict of gammapy.irf.background.Background2D or gammapy.irf.background.Background3D
691
+ A dict with observation number as key and a background model that could be used as an acceptance model associated at each key
692
+
693
+ """
694
+
695
+ if off_observations is None:
696
+ off_observations = observations
697
+ elif base_model is not None:
698
+ logger.warning('The off observations provided will be ignored as a base model has been provided.')
699
+
700
+ # If needed produce the zenith binned model
701
+ if base_model is not None and not isinstance(base_model, BackgroundCollectionZenith):
702
+ error_message = 'The models should be provided as a BackgroundCollectionZenith object'
703
+ logger.error(error_message)
704
+ raise BackgroundModelFormatException(error_message)
705
+ dict_binned_model = base_model or self.create_model_cos_zenith_binned(off_observations)
706
+
707
+ cos_zenith_model = []
708
+ key_model = []
709
+ for k in np.sort(list(dict_binned_model.keys())):
710
+ cos_zenith_model.append(np.cos(np.deg2rad(k)))
711
+ key_model.append(k)
712
+ cos_zenith_model = np.array(cos_zenith_model)
713
+
714
+ # Determine model type and axes
715
+ type_model = type(dict_binned_model[key_model[0]])
716
+ axes_model = dict_binned_model[key_model[0]].axes
717
+
718
+ # Find the closest model for each observation and associate it to each observation
719
+ acceptance_map = {}
720
+ if len(cos_zenith_model) <= 1:
721
+ logger.warning('Only one zenith bin, zenith binning deactivated')
722
+ for obs in observations:
723
+ if self.use_mini_irf_computation:
724
+ evaluation_time, observation_time = get_time_mini_irf(obs, self.mini_irf_time_resolution)
725
+
726
+ data_obs_all = np.zeros(
727
+ tuple([len(evaluation_time), ] + list(dict_binned_model[key_model[0]].data.shape))) * \
728
+ dict_binned_model[key_model[0]].unit
729
+ for i in range(len(evaluation_time)):
730
+ cos_zenith_observation = np.cos(obs.get_pointing_altaz(evaluation_time[i]).zen)
731
+ key_closest_model = key_model[(np.abs(cos_zenith_model - cos_zenith_observation)).argmin()]
732
+ selected_model_bin = dict_binned_model[key_closest_model]
733
+ data_obs_all[i] = selected_model_bin.data * selected_model_bin.unit
734
+
735
+ data_obs = generate_irf_from_mini_irf(data_obs_all, observation_time)
736
+
737
+ if type_model is Background2D:
738
+ acceptance_map[obs.obs_id] = Background2D(axes=axes_model,
739
+ data=data_obs)
740
+ elif type_model is Background3D:
741
+ acceptance_map[obs.obs_id] = Background3D(axes=axes_model,
742
+ data=data_obs,
743
+ fov_alignment=FoVAlignment.ALTAZ)
744
+ else:
745
+ raise Exception('Unknown background format')
746
+
747
+ else:
748
+ cos_zenith_observation = np.cos(obs.get_pointing_altaz(obs.tmid).zen)
749
+ key_closest_model = key_model[(np.abs(cos_zenith_model - cos_zenith_observation)).argmin()]
750
+ acceptance_map[obs.obs_id] = dict_binned_model[key_closest_model]
751
+
752
+ return acceptance_map
753
+
754
+ def _create_interpolation_function(self, base_model: BackgroundCollectionZenith) -> interp1d:
755
+ """
756
+ Create the function that will perform the interpolation
757
+
758
+ Parameters
759
+ ----------
760
+ base_model : dict of gammapy.irf.background.BackgroundIRF
761
+ The binned base model
762
+ Each key of the dictionary should correspond to the zenith in degree of the model
763
+
764
+ Returns
765
+ -------
766
+ interp_func : scipy.interpolate.interp1d
767
+ The object that could be call directly for performing the interpolation
768
+ """
769
+
770
+ # Reshape the base model
771
+ binned_model = []
772
+ cos_zenith_model = []
773
+ for k in np.sort(list(base_model.keys())):
774
+ binned_model.append(base_model[k])
775
+ cos_zenith_model.append(np.cos(np.deg2rad(k)))
776
+ cos_zenith_model = np.array(cos_zenith_model)
777
+
778
+ data_cube = np.zeros(tuple([len(binned_model), ] + list(binned_model[0].data.shape))) * binned_model[0].unit
779
+ for i in range(len(binned_model)):
780
+ data_cube[i] = binned_model[i].data * binned_model[i].unit
781
+ if self.interpolation_type == 'log':
782
+ interp_func = interp1d(x=cos_zenith_model,
783
+ y=np.log10(data_cube.to_value(
784
+ binned_model[0].unit) + self.threshold_value_log_interpolation),
785
+ axis=0,
786
+ fill_value='extrapolate')
787
+ elif self.interpolation_type == 'linear':
788
+ interp_func = interp1d(x=cos_zenith_model,
789
+ y=data_cube.to_value(binned_model[0].unit),
790
+ axis=0,
791
+ fill_value='extrapolate')
792
+ else:
793
+ raise Exception("Unknown interpolation type")
794
+
795
+ return interp_func
796
+
797
+ def _background_cleaning(self, background_model):
798
+ """
799
+ Is cleaning the background model from suspicious values not compatible with neighbour pixels.
800
+
801
+ Parameters
802
+ ----------
803
+ background_model : numpy.array
804
+ The background model to be cleaned
805
+
806
+ Returns
807
+ -------
808
+ background_model : numpy.array
809
+ The background model cleaned
810
+ """
811
+
812
+ base_model = background_model.copy()
813
+ final_model = background_model.copy()
814
+ i = 0
815
+ while (i < 1 or not np.allclose(base_model, final_model)) and (i < self.max_cleaning_iteration):
816
+ base_model = final_model.copy()
817
+ i += 1
818
+
819
+ count_valid_neighbour_condition_energy = compute_neighbour_condition_validation(base_model, axis=0,
820
+ relative_threshold=self.interpolation_cleaning_energy_relative_threshold)
821
+ count_valid_neighbour_condition_spatial = compute_neighbour_condition_validation(base_model, axis=1,
822
+ relative_threshold=self.interpolation_cleaning_spatial_relative_threshold)
823
+ if base_model.ndim == 3:
824
+ count_valid_neighbour_condition_spatial += compute_neighbour_condition_validation(base_model, axis=2,
825
+ relative_threshold=self.interpolation_cleaning_spatial_relative_threshold)
826
+
827
+ mask_energy = count_valid_neighbour_condition_energy > 0
828
+ mask_spatial = count_valid_neighbour_condition_spatial > (1 if base_model.ndim == 3 else 0)
829
+ mask_valid = np.logical_and(mask_energy, mask_spatial)
830
+ final_model[~mask_valid] = 0.
831
+
832
+ return final_model
833
+
834
+ def _get_interpolated_background(self, interp_func: interp1d, zenith: u.Quantity) -> np.array:
835
+ """
836
+ Create the function that will perform the interpolation
837
+
838
+ Parameters
839
+ ----------
840
+ interp_func : scipy.interpolate.interp1d
841
+ The interpolation function
842
+ zenith : u.Quantity
843
+ The zenith for which the interpolated background should be created
844
+
845
+ Returns
846
+ -------
847
+ interp_bkg : numpy.array
848
+ The object that could be call directly for performing the interpolation
849
+ """
850
+
851
+ if self.interpolation_type == 'log':
852
+ interp_bkg = (10. ** interp_func(np.cos(zenith)))
853
+ interp_bkg[interp_bkg < 100 * self.threshold_value_log_interpolation] = 0.
854
+ elif self.interpolation_type == 'linear':
855
+ interp_bkg = interp_func(np.cos(zenith))
856
+ else:
857
+ raise Exception("Unknown interpolation type")
858
+
859
+ if self.activate_interpolation_cleaning:
860
+ interp_bkg = self._background_cleaning(interp_bkg)
861
+
862
+ return interp_bkg
863
+
864
+ def create_acceptance_map_cos_zenith_interpolated(self,
865
+ observations: Observations,
866
+ off_observations: Observations = None,
867
+ base_model: BackgroundCollectionZenith = None
868
+ ) -> dict[int, BackgroundIRF]:
869
+ """
870
+ Calculate an acceptance map per run using cos zenith binning and interpolation
871
+
872
+ Parameters
873
+ ----------
874
+ observations : gammapy.data.observations.Observations
875
+ The collection of observations to which the acceptance model will be applied
876
+ off_observations : gammapy.data.observations.Observations
877
+ The collection of observations used to generate the acceptance map, if None will be the observations provided as target
878
+ Will be ignored if a base_model parameter is provideds
879
+ base_model : BackgroundCollectionZenith
880
+ If you have already a precomputed model, the method will use this model as base for the acceptance map instead of computing it from the data
881
+
882
+ Returns
883
+ -------
884
+ background : dict of gammapy.irf.background.Background2D or gammapy.irf.background.Background3D
885
+ A dict with observation number as key and a background model that could be used as an acceptance model associated at each key
886
+
887
+ """
888
+
889
+ if off_observations is None:
890
+ off_observations = observations
891
+ elif base_model is not None:
892
+ logger.warning('The off observations provided will be ignored as a base model has been provided.')
893
+
894
+ # If needed produce the zenith binned model
895
+ if base_model is not None and not isinstance(base_model, BackgroundCollectionZenith):
896
+ error_message = 'The models should be provided as a BackgroundCollectionZenith object'
897
+ logger.error(error_message)
898
+ raise BackgroundModelFormatException(error_message)
899
+ dict_binned_model = base_model or self.create_model_cos_zenith_binned(off_observations)
900
+
901
+ acceptance_map = {}
902
+ if len(dict_binned_model) <= 1:
903
+ logger.warning('Only one zenith bin, zenith interpolation deactivated')
904
+ for obs in observations:
905
+ acceptance_map[obs.obs_id] = dict_binned_model[dict_binned_model.zenith[0]]
906
+ else:
907
+ # Determine model properties
908
+ type_model = type(dict_binned_model[dict_binned_model.zenith[0]])
909
+ axes_model = dict_binned_model[dict_binned_model.zenith[0]].axes
910
+ shape_model = dict_binned_model[dict_binned_model.zenith[0]].data.shape
911
+ unit_model = dict_binned_model[dict_binned_model.zenith[0]].unit
912
+
913
+ # Perform the interpolation
914
+ interp_func = self._create_interpolation_function(dict_binned_model)
915
+ for obs in observations:
916
+ if self.use_mini_irf_computation:
917
+ evaluation_time, observation_time = get_time_mini_irf(obs, self.mini_irf_time_resolution)
918
+
919
+ data_obs_all = np.zeros(tuple([len(evaluation_time), ] + list(shape_model)))
920
+ for i in range(len(evaluation_time)):
921
+ data_obs_bin = self._get_interpolated_background(interp_func,
922
+ obs.get_pointing_altaz(evaluation_time[i]).zen)
923
+ data_obs_all[i, :, :] = data_obs_bin
924
+
925
+ data_obs = generate_irf_from_mini_irf(data_obs_all, observation_time)
926
+
927
+ else:
928
+ data_obs = self._get_interpolated_background(interp_func, obs.get_pointing_altaz(obs.tmid).zen)
929
+
930
+ if type_model is Background2D:
931
+ acceptance_map[obs.obs_id] = Background2D(axes=axes_model,
932
+ data=data_obs * unit_model)
933
+ elif type_model is Background3D:
934
+ acceptance_map[obs.obs_id] = Background3D(axes=axes_model,
935
+ data=data_obs * unit_model,
936
+ fov_alignment=FoVAlignment.ALTAZ)
937
+ else:
938
+ raise Exception('Unknown background format')
939
+
940
+ return acceptance_map
941
+
942
+ def create_acceptance_map_per_observation(self,
943
+ observations: Observations,
944
+ zenith_binning: bool = False,
945
+ zenith_interpolation: bool = False,
946
+ runwise_normalisation: bool = True,
947
+ off_observations: Observations = None,
948
+ base_model: Union[BackgroundCollectionZenith, BackgroundIRF] = None,
949
+ ) -> dict[int, BackgroundIRF]:
950
+ """
951
+ Calculate an acceptance map with the norm adjusted for each run
952
+
953
+ Parameters
954
+ ----------
955
+ observations : gammapy.data.observations.Observations
956
+ The collection of observations to which the acceptance model will be applied
957
+ zenith_binning : bool, optional
958
+ If true the acceptance maps will be generated using zenith binning
959
+ zenith_interpolation : bool, optional
960
+ If true the acceptance maps will be generated using zenith binning and interpolation
961
+ runwise_normalisation : bool, optional
962
+ If true the acceptance maps will be normalised runwise to the observations
963
+ off_observations : gammapy.data.observations.Observations
964
+ The collection of observations used to generate the acceptance map, if None will be the observations provided as target
965
+ Will be ignored if a base_model parameter is provided
966
+ base_model : gammapy.irf.background.BackgroundIRF or BackgroundCollectionZenith
967
+ If you have already a precomputed model, the method will use this model as base for the acceptance map instead of computing it from the data
968
+ In the case of a zenith dependant model, you should provide a BackgroundCollectionZenith object
969
+
970
+ Returns
971
+ -------
972
+ background : dict of gammapy.irf.background.Background2D or gammapy.irf.background.Background3D
973
+ A dict with observation number as key and a background model that could be used as an acceptance model associated at each key
974
+ """
975
+
976
+ acceptance_map = {}
977
+ if zenith_interpolation:
978
+ acceptance_map = self.create_acceptance_map_cos_zenith_interpolated(observations=observations,
979
+ off_observations=off_observations,
980
+ base_model=base_model)
981
+ elif zenith_binning:
982
+ acceptance_map = self.create_acceptance_map_cos_zenith_binned(observations=observations,
983
+ off_observations=off_observations,
984
+ base_model=base_model)
985
+ else:
986
+ if off_observations is None:
987
+ off_observations = observations
988
+ elif base_model is not None:
989
+ logger.warning('The off observations provided will be ignored as a base model has been provided.')
990
+
991
+ if base_model is not None:
992
+ if not isinstance(base_model, BackgroundIRF):
993
+ error_message = 'The model provided should be a gammapy BackgroundIRF object'
994
+ logger.error(error_message)
995
+ raise BackgroundModelFormatException(error_message)
996
+ unique_base_acceptance_map = base_model
997
+ else:
998
+ unique_base_acceptance_map = self.create_acceptance_map(off_observations)
999
+ for obs in observations:
1000
+ acceptance_map[obs.obs_id] = unique_base_acceptance_map
1001
+
1002
+ if runwise_normalisation:
1003
+ acceptance_map = self._normalised_model_per_run(observations, acceptance_map)
1004
+
1005
+ return acceptance_map