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,108 @@
1
+ Metadata-Version: 2.1
2
+ Name: BAccMod
3
+ Version: 0.1.0.dev0
4
+ Summary: Calculate 2D acceptance model for creating maps with gammapy (IACT analysis)
5
+ Author: Mathieu de Bony de Lavergne
6
+ Author-email: lavergne@lapp.in2p3.fr
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: gammapy<0.20,>=0.19
9
+ Requires-Dist: numpy
10
+ Requires-Dist: astropy>=4.0
11
+ Requires-Dist: regions<0.6,>=0.5
12
+
13
+ # Description
14
+
15
+ This package create radial acceptance model to be used for IACT analysis with gammapy
16
+
17
+ # Installation
18
+
19
+
20
+ ```bash
21
+ git clone https://github.com/mdebony/acceptance_modelisation.git
22
+ cd baccmod
23
+ python setup.py install
24
+ ```
25
+
26
+ Dependencies :
27
+ - numpy
28
+ - gammapy 0.19
29
+ - regions 0.5
30
+ - astropy
31
+
32
+ # Example of use
33
+
34
+ You could first create the acceptance model
35
+
36
+ ```python
37
+ from gammapy.maps import MapAxis
38
+ from gammapy.data import DataStore
39
+ from regions import CircleSkyRegion
40
+ import astropy.units as u
41
+ import numpy as np
42
+ from astropy.coordinates import SkyCoord
43
+ from baccmod import RadialAcceptanceMapCreator
44
+
45
+ # The observations to use for creating the acceptance model
46
+ data_store = DataStore.from_dir("$GAMMAPY_DATA/hess-dl3-dr1")
47
+ obs_collection = data_store.get_observations([23523, 23526, 23559, 23592])
48
+
49
+ # The exclusion regions to apply during acceptance model calculation
50
+ exclude_regions = [CircleSkyRegion(center=SkyCoord.from_name('Crab'),
51
+ radius=0.2 * u.deg), ]
52
+
53
+ # Define the binning of the model
54
+ e_min, e_max = 0.1 * u.TeV, 10. * u.TeV
55
+ size_fov = 2.5 * u.deg
56
+ offset_axis_acceptance = MapAxis.from_bounds(0. * u.deg, size_fov, nbin=6, name='offset')
57
+ energy_axis_acceptance = MapAxis.from_energy_bounds(e_min, e_max, nbin=6, name='energy')
58
+
59
+ acceptance_model_creator = RadialAcceptanceMapCreator(energy_axis_acceptance,
60
+ offset_axis_acceptance,
61
+ exclude_regions=exclude_regions,
62
+ oversample_map=100)
63
+ acceptance_model = acceptance_model_creator.create_radial_acceptance_map(obs_collection)
64
+
65
+ ```
66
+
67
+ You can then check the acceptance model by plotting it using
68
+
69
+ ```python
70
+ acceptance_model.peek()
71
+ ```
72
+
73
+ To use it with gammapy, you could first save it on a FITS file
74
+
75
+ ```python
76
+ hdu_acceptance = acceptance_model.to_table_hdu()
77
+ hdu_acceptance.writeto('acceptance.fits', overwrite=True)
78
+ ```
79
+
80
+ It's then possible to load the acceptance model in the current gammapy DataStore with this code.
81
+ You would need then to recreate you gammapy Observations object in order than the acceptance model is taken into account for the analysis.
82
+
83
+ ```python
84
+ data_store.hdu_table.remove_rows(data_store.hdu_table['HDU_TYPE']=='bkg')
85
+ for obs_id in np.unique(data_store.hdu_table['OBS_ID']):
86
+ data_store.hdu_table.add_row({'OBS_ID': obs_id,
87
+ 'HDU_TYPE': 'bkg',
88
+ "HDU_CLASS": "bkg_2d",
89
+ "FILE_DIR": "",
90
+ "FILE_NAME": 'acceptance.fits',
91
+ "HDU_NAME": "BACKGROUND",
92
+ "SIZE": hdu_acceptance.size})
93
+ data_store.hdu_table = data_store.hdu_table.copy()
94
+
95
+ obs_collection = data_store.get_observations([23523, 23526, 23559, 23592])
96
+
97
+ data_store.hdu_table
98
+ ```
99
+
100
+ It's also possible to fit the normalisation of the model per run. For this use the method create_radial_acceptance_map_per_observation .
101
+ In that case the output is a dictionary containing the acceptance model of each observations (with the observation Id as index).
102
+ ```python
103
+ acceptance_model_creator = RadialAcceptanceMapCreator(energy_axis_acceptance,
104
+ offset_axis_acceptance,
105
+ exclude_regions=exclude_regions,
106
+ oversample_map=100)
107
+ acceptance_models = acceptance_model_creator.create_radial_acceptance_map_per_observation(obs_collection)
108
+ ```
@@ -0,0 +1,13 @@
1
+ baccmod/__init__.py,sha256=hMvI8ZwVjTyPC3ZLLNyz0X0Qg1Roua8QIvisErsj6zU,23
2
+ baccmod/baccmod.py,sha256=Zyw2ZbTc8J5H2E_kBjj5WBiuOnDTKC2Ni7MXbarzUW8,7720
3
+ baccmod/base_acceptance_map_creator.py,sha256=vDo5Yn3Qwb0n6EUqYVlqCCGwx_nHfawUqG6fYh_b7xg,52019
4
+ baccmod/bkg_collection.py,sha256=xnqwOL3zUesCXg2iGsItZI4Y9Lj4_4w3jVgKf-1Xxuo,3269
5
+ baccmod/exception.py,sha256=sMw0RRLkoqXs0lNr-Dhcq3vUYixHfbob9uFjGz4wkoM,864
6
+ baccmod/grid3d_acceptance_map_creator.py,sha256=S7gcS8Bbnq1aqlG2utmipaguLMAFgRjWFpeqDChcn5M,19589
7
+ baccmod/modeling.py,sha256=yogM6Pe9AP29WhAhMmWQQDE2bq2nvdB4lc3IS5jz7Yo,3890
8
+ baccmod/radial_acceptance_map_creator.py,sha256=NZ07aS-NXaxjfI_lIHMI82uDQ8BDw06_-obS2LCAbt8,11770
9
+ baccmod/toolbox.py,sha256=ZwDtekDY8TR-gEMfHFVho5Pe221old301Ht-zf98CYE,8701
10
+ BAccMod-0.1.0.dev0.dist-info/METADATA,sha256=60rAo-fFRJL3Ryk6ej0zEnFg7Wj0YlvE-U6PIxoU9Ag,3983
11
+ BAccMod-0.1.0.dev0.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
12
+ BAccMod-0.1.0.dev0.dist-info/top_level.txt,sha256=UigQ_V6MZPlcaEtx8CGAJwVpCe4Ul4gzNGkkSKez6IA,8
13
+ BAccMod-0.1.0.dev0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.6.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ baccmod
baccmod/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from .baccmod import *
baccmod/baccmod.py ADDED
@@ -0,0 +1,174 @@
1
+ import copy
2
+ import numpy as np
3
+ import astropy.units as u
4
+ from astropy.coordinates import SkyCoord
5
+ from gammapy.datasets import MapDataset
6
+ from gammapy.irf import Background2D
7
+ from gammapy.makers import MapDatasetMaker, SafeMaskMaker, FoVBackgroundMaker
8
+ from gammapy.maps import WcsNDMap, WcsGeom
9
+ from regions import CircleAnnulusSkyRegion
10
+
11
+
12
+ class RadialAcceptanceMapCreator:
13
+
14
+ def __init__(self, energy_axis, offset_axis, oversample_map=10, exclude_regions=[]):
15
+ """
16
+ Create the class for calculating radial acceptance model
17
+
18
+ Parameters
19
+ ----------
20
+ energy_axis : gammapy.maps.geom.MapAxis
21
+ The energy axis for the acceptance model
22
+ offset_axis : gammapy.maps.geom.MapAxis
23
+ The offset axis for the acceptance model
24
+ oversample_map : int
25
+ Oversample in number of pixel of the spatial axis used for the calculation
26
+ exclude_regions : list of 'regions.SkyRegion'
27
+ Region with known or putative gamma-ray emission, will be excluded of the calculation of the acceptance map
28
+ """
29
+
30
+ # Store base parameter
31
+ self.energy_axis = energy_axis
32
+ self.offset_axis = offset_axis
33
+ self.oversample_map = oversample_map
34
+ self.exclude_regions = exclude_regions
35
+
36
+ # Calculate map parameter
37
+ self.n_bins_map = self.offset_axis.nbin * self.oversample_map * 2
38
+ self.binsz = self.offset_axis.edges[-1] / (self.n_bins_map / 2)
39
+
40
+ def __create_sky_map(self, obs, add_bkg=False):
41
+ """
42
+ Create the sky map used for computation
43
+
44
+ Parameters
45
+ ----------
46
+ obs : gammapy.data.observations.Observation
47
+ The observation used to make the sky map
48
+ add_bkg : bool
49
+ If true will also add the background model to the map
50
+
51
+ Returns
52
+ -------
53
+ map_obs : gammapy.datasets.MapDataset
54
+ exclusion_mask : gammapy.maps.WcsNDMap
55
+ """
56
+
57
+ geom_obs = WcsGeom.create(skydir=obs.pointing_radec, npix=(self.n_bins_map, self.n_bins_map),
58
+ binsz=self.binsz, frame="icrs", axes=[self.energy_axis])
59
+ maker = MapDatasetMaker(selection=["counts"])
60
+ if add_bkg:
61
+ maker = MapDatasetMaker(selection=["counts", "background"])
62
+
63
+ maker_safe_mask = SafeMaskMaker(methods=["offset-max"], offset_max=np.max(self.offset_axis.edges))
64
+
65
+ geom_image = geom_obs.to_image()
66
+ exclusion_mask = ~geom_image.region_mask(self.exclude_regions)
67
+
68
+ map_obs = maker.run(MapDataset.create(geom=geom_obs), obs)
69
+ map_obs = maker_safe_mask.run(map_obs, obs)
70
+
71
+ return map_obs, exclusion_mask
72
+
73
+ def create_radial_acceptance_map(self, observations):
74
+ """
75
+ Calculate a radial acceptance map
76
+
77
+ Parameters
78
+ ----------
79
+ observations : gammapy.data.observations.Observations
80
+ The collection of observations used to make the acceptance map
81
+
82
+ Returns
83
+ -------
84
+ background : gammapy.irf.background.Background2D
85
+ """
86
+
87
+ center_map = SkyCoord(ra=0. * u.deg, dec=0. * u.deg, frame='icrs')
88
+
89
+ geom = WcsGeom.create(skydir=center_map, npix=(self.n_bins_map, self.n_bins_map), binsz=self.binsz,
90
+ frame="icrs", axes=[self.energy_axis])
91
+
92
+ count_map_background = WcsNDMap(geom=geom)
93
+ exp_map_background = WcsNDMap(geom=geom, unit=u.s)
94
+ exp_map_background_total = WcsNDMap(geom=geom, unit=u.s)
95
+ livetime = 0. * u.s
96
+
97
+ for obs in observations:
98
+ count_map_obs, exclusion_mask = self.__create_sky_map(obs)
99
+
100
+ exp_map_obs = MapDataset.create(geom=count_map_obs.geoms['geom'])
101
+ exp_map_obs_total = MapDataset.create(geom=count_map_obs.geoms['geom'])
102
+ exp_map_obs.counts.data = obs.observation_live_time_duration.value
103
+ exp_map_obs_total.counts.data = obs.observation_live_time_duration.value
104
+
105
+ for i in range(count_map_obs.counts.data.shape[0]):
106
+ count_map_obs.counts.data[i, :, :] = count_map_obs.counts.data[i, :, :] * exclusion_mask
107
+ exp_map_obs.counts.data[i, :, :] = exp_map_obs.counts.data[i, :, :] * exclusion_mask
108
+
109
+ count_map_background.data += count_map_obs.counts.data
110
+ exp_map_background.data += exp_map_obs.counts.data
111
+ exp_map_background_total.data += exp_map_obs_total.counts.data
112
+ livetime += obs.observation_live_time_duration
113
+
114
+ data_background = np.zeros((self.energy_axis.nbin, self.offset_axis.nbin)) * u.Unit('s-1 MeV-1 sr-1')
115
+ for i in range(self.offset_axis.nbin):
116
+ selection_region = CircleAnnulusSkyRegion(center=center_map, inner_radius=self.offset_axis.edges[i],
117
+ outer_radius=self.offset_axis.edges[i + 1])
118
+ selection_map = geom.to_image().region_mask([selection_region])
119
+ for j in range(self.energy_axis.nbin):
120
+ value = u.dimensionless_unscaled * np.sum(count_map_background.data[j, :, :] * selection_map)
121
+ value *= np.sum(exp_map_background_total.data[j, :, :] * selection_map) / np.sum(
122
+ exp_map_background.data[j, :, :] * selection_map)
123
+
124
+ value /= (self.energy_axis.edges[j + 1] - self.energy_axis.edges[j])
125
+ value /= 2. * np.pi * (
126
+ self.offset_axis.edges[i + 1].to('radian') - self.offset_axis.edges[i].to('radian')) * \
127
+ self.offset_axis.center[i].to('radian')
128
+ value /= livetime
129
+ data_background[j, i] = value
130
+
131
+ background = Background2D(axes=[self.energy_axis, self.offset_axis], data=data_background)
132
+
133
+ return background
134
+
135
+ def create_radial_acceptance_map_per_observation(self, observations):
136
+ """
137
+ Calculate a radial acceptance map with the norm adjusted for each run
138
+
139
+ Parameters
140
+ ----------
141
+ observations : gammapy.data.observations.Observations
142
+ The collection of observations used to make the acceptance map
143
+
144
+ Returns
145
+ -------
146
+ background : dict of gammapy.irf.background.Background2D
147
+ A dict with observation number as keu and a bakground model that could be used as an acceptance model associated at each key
148
+ """
149
+
150
+ base_radial_acceptance_map = self.create_radial_acceptance_map(observations)
151
+
152
+ radial_acceptance_map = {}
153
+ # Fit norm of the model to the observations
154
+ for obs in observations:
155
+ id_observation = obs.obs_id
156
+
157
+ # replace the background model
158
+ modified_observation = copy.deepcopy(obs)
159
+ modified_observation.bkg = base_radial_acceptance_map
160
+
161
+ # Fit the background model
162
+ map_obs, exclusion_mask = self.__create_sky_map(modified_observation, add_bkg=True)
163
+ maker_FoV_background = FoVBackgroundMaker(method='fit', exclusion_mask=exclusion_mask)
164
+ map_obs = maker_FoV_background.run(map_obs)
165
+
166
+ # Extract the normalisation
167
+ parameters = map_obs.models.to_parameters_table()
168
+ norm_background = parameters[parameters['name'] == 'norm']['value'][0]
169
+
170
+ # Apply normalisation to the background model
171
+ radial_acceptance_map[id_observation] = copy.deepcopy(base_radial_acceptance_map)
172
+ radial_acceptance_map[id_observation].data = radial_acceptance_map[id_observation].data * norm_background
173
+
174
+ return radial_acceptance_map