-
Notifications
You must be signed in to change notification settings - Fork 187
/
core.py
1910 lines (1579 loc) · 61.9 KB
/
core.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import abc
import copy
import inspect
import json
from collections import OrderedDict
import numpy as np
from astropy import units as u
from astropy.io import fits
import matplotlib.pyplot as plt
from gammapy.utils.random import InverseCDFSampler, get_random_state
from gammapy.utils.scripts import make_path
from gammapy.utils.units import energy_unit_format
from .axes import MapAxis
from .coord import MapCoord
from .geom import pix_tuple_to_idx
from .io import JsonQuantityDecoder
__all__ = ["Map"]
class Map(abc.ABC):
"""Abstract map class.
This can represent WCS- or HEALPIX-based maps
with 2 spatial dimensions and N non-spatial dimensions.
Parameters
----------
geom : `~gammapy.maps.Geom`
Geometry
data : `~numpy.ndarray` or `~astropy.units.Quantity`
Data array
meta : `dict`
Dictionary to store meta data
unit : str or `~astropy.units.Unit`
Data unit, ignored if data is a Quantity.
"""
tag = "map"
def __init__(self, geom, data, meta=None, unit=""):
self._geom = geom
if isinstance(data, u.Quantity):
self._unit = u.Unit(unit)
self.quantity = data
else:
self.data = data
self._unit = u.Unit(unit)
if meta is None:
self.meta = {}
else:
self.meta = meta
def _init_copy(self, **kwargs):
"""Init map instance by copying missing init arguments from self."""
argnames = inspect.getfullargspec(self.__init__).args
argnames.remove("self")
argnames.remove("dtype")
for arg in argnames:
value = getattr(self, "_" + arg)
if arg not in kwargs:
kwargs[arg] = copy.deepcopy(value)
return self.from_geom(**kwargs)
@property
def is_mask(self):
"""Whether map is mask with bool dtype"""
return self.data.dtype == bool
@property
def geom(self):
"""Map geometry (`~gammapy.maps.Geom`)"""
return self._geom
@property
def data(self):
"""Data array (`~numpy.ndarray`)"""
return self._data
@data.setter
def data(self, value):
"""Set data
Parameters
----------
value : array-like
Data array
"""
if np.isscalar(value):
value = value * np.ones(self.geom.data_shape, dtype=type(value))
if isinstance(value, u.Quantity):
raise TypeError("Map data must be a Numpy array. Set unit separately")
if not value.shape == self.geom.data_shape:
value = value.reshape(self.geom.data_shape)
self._data = value
@property
def unit(self):
"""Map unit (`~astropy.units.Unit`)"""
return self._unit
@property
def meta(self):
"""Map meta (`dict`)"""
return self._meta
@meta.setter
def meta(self, val):
self._meta = val
@property
def quantity(self):
"""Map data times unit (`~astropy.units.Quantity`)"""
return u.Quantity(self.data, self.unit, copy=False)
@quantity.setter
def quantity(self, val):
"""Set data and unit
Parameters
----------
value : `~astropy.units.Quantity`
Quantity
"""
val = u.Quantity(val, copy=False)
self.data = val.value
self._unit = val.unit
def rename_axes(self, names, new_names):
"""Rename the Map axes.
Parameters
----------
names : list or str
Names of the axes.
new_names : list or str
New names of the axes (list must be of same length than `names`).
Returns
-------
geom : `~Map`
Renamed Map.
"""
geom = self.geom.rename_axes(names=names, new_names=new_names)
return self._init_copy(geom=geom)
@staticmethod
def create(**kwargs):
"""Create an empty map object.
This method accepts generic options listed below, as well as options
for `HpxMap` and `WcsMap` objects. For WCS-specific options, see
`WcsMap.create` and for HPX-specific options, see `HpxMap.create`.
Parameters
----------
frame : str
Coordinate system, either Galactic ("galactic") or Equatorial
("icrs").
map_type : {'wcs', 'wcs-sparse', 'hpx', 'hpx-sparse', 'region'}
Map type. Selects the class that will be used to
instantiate the map.
binsz : float or `~numpy.ndarray`
Pixel size in degrees.
skydir : `~astropy.coordinates.SkyCoord`
Coordinate of map center.
axes : list
List of `~MapAxis` objects for each non-spatial dimension.
If None then the map will be a 2D image.
dtype : str
Data type, default is 'float32'
unit : str or `~astropy.units.Unit`
Data unit.
meta : `dict`
Dictionary to store meta data.
region : `~regions.SkyRegion`
Sky region used for the region map.
Returns
-------
map : `Map`
Empty map object.
"""
from .hpx import HpxMap
from .region import RegionNDMap
from .wcs import WcsMap
map_type = kwargs.setdefault("map_type", "wcs")
if "wcs" in map_type.lower():
return WcsMap.create(**kwargs)
elif "hpx" in map_type.lower():
return HpxMap.create(**kwargs)
elif map_type == "region":
_ = kwargs.pop("map_type")
return RegionNDMap.create(**kwargs)
else:
raise ValueError(f"Unrecognized map type: {map_type!r}")
@staticmethod
def read(
filename, hdu=None, hdu_bands=None, map_type="auto", format=None, colname=None
):
"""Read a map from a FITS file.
Parameters
----------
filename : str or `~pathlib.Path`
Name of the FITS file.
hdu : str
Name or index of the HDU with the map data.
hdu_bands : str
Name or index of the HDU with the BANDS table. If not
defined this will be inferred from the FITS header of the
map HDU.
map_type : {'wcs', 'wcs-sparse', 'hpx', 'hpx-sparse', 'auto', 'region'}
Map type. Selects the class that will be used to
instantiate the map. The map type should be consistent
with the format of the input file. If map_type is 'auto'
then an appropriate map type will be inferred from the
input file.
colname : str, optional
data column name to be used of healix map.
Returns
-------
map_out : `Map`
Map object
"""
with fits.open(str(make_path(filename)), memmap=False) as hdulist:
return Map.from_hdulist(
hdulist, hdu, hdu_bands, map_type, format=format, colname=colname
)
@staticmethod
def from_geom(geom, meta=None, data=None, unit="", dtype="float32"):
"""Generate an empty map from a `Geom` instance.
Parameters
----------
geom : `Geom`
Map geometry.
data : `numpy.ndarray`
data array
meta : `dict`
Dictionary to store meta data.
unit : str or `~astropy.units.Unit`
Data unit.
Returns
-------
map_out : `Map`
Map object
"""
from .hpx import HpxGeom
from .region import RegionGeom
from .wcs import WcsGeom
if isinstance(geom, HpxGeom):
map_type = "hpx"
elif isinstance(geom, WcsGeom):
map_type = "wcs"
elif isinstance(geom, RegionGeom):
map_type = "region"
else:
raise ValueError("Unrecognized geom type.")
cls_out = Map._get_map_cls(map_type)
return cls_out(geom, data=data, meta=meta, unit=unit, dtype=dtype)
@staticmethod
def from_hdulist(
hdulist, hdu=None, hdu_bands=None, map_type="auto", format=None, colname=None
):
"""Create from `astropy.io.fits.HDUList`.
Parameters
----------
hdulist : `~astropy.io.fits.HDUList`
HDU list containing HDUs for map data and bands.
hdu : str
Name or index of the HDU with the map data.
hdu_bands : str
Name or index of the HDU with the BANDS table.
map_type : {"auto", "wcs", "hpx", "region"}
Map type.
format : {'gadf', 'fgst-ccube', 'fgst-template'}
FITS format convention.
colname : str, optional
Data column name to be used for the HEALPix map.
Returns
-------
map_out : `Map`
Map object
"""
if map_type == "auto":
map_type = Map._get_map_type(hdulist, hdu)
cls_out = Map._get_map_cls(map_type)
if map_type == "hpx":
return cls_out.from_hdulist(
hdulist, hdu=hdu, hdu_bands=hdu_bands, format=format, colname=colname
)
else:
return cls_out.from_hdulist(
hdulist, hdu=hdu, hdu_bands=hdu_bands, format=format
)
@staticmethod
def _get_meta_from_header(header):
"""Load meta data from a FITS header."""
if "META" in header:
return json.loads(header["META"], cls=JsonQuantityDecoder)
else:
return {}
@staticmethod
def _get_map_type(hdu_list, hdu_name):
"""Infer map type from a FITS HDU.
Only read header, never data, to have good performance.
"""
if hdu_name is None:
# Find the header of the first non-empty HDU
header = hdu_list[0].header
if header["NAXIS"] == 0:
header = hdu_list[1].header
else:
header = hdu_list[hdu_name].header
if ("PIXTYPE" in header) and (header["PIXTYPE"] == "HEALPIX"):
return "hpx"
elif "CTYPE1" in header:
return "wcs"
else:
return "region"
@staticmethod
def _get_map_cls(map_type):
"""Get map class for given `map_type` string.
This should probably be a registry dict so that users
can add supported map types to the `gammapy.maps` I/O
(see e.g. the Astropy table format I/O registry),
but that's non-trivial to implement without avoiding circular imports.
"""
if map_type == "wcs":
from .wcs import WcsNDMap
return WcsNDMap
elif map_type == "wcs-sparse":
raise NotImplementedError()
elif map_type == "hpx":
from .hpx import HpxNDMap
return HpxNDMap
elif map_type == "hpx-sparse":
raise NotImplementedError()
elif map_type == "region":
from .region import RegionNDMap
return RegionNDMap
else:
raise ValueError(f"Unrecognized map type: {map_type!r}")
def write(self, filename, overwrite=False, **kwargs):
"""Write to a FITS file.
Parameters
----------
filename : str
Output file name.
overwrite : bool
Overwrite existing file?
hdu : str
Set the name of the image extension. By default this will
be set to SKYMAP (for BINTABLE HDU) or PRIMARY (for IMAGE
HDU).
hdu_bands : str
Set the name of the bands table extension. By default this will
be set to BANDS.
format : str, optional
FITS format convention. By default files will be written
to the gamma-astro-data-formats (GADF) format. This
option can be used to write files that are compliant with
format conventions required by specific software (e.g. the
Fermi Science Tools). The following formats are supported:
- "gadf" (default)
- "fgst-ccube"
- "fgst-ltcube"
- "fgst-bexpcube"
- "fgst-srcmap"
- "fgst-template"
- "fgst-srcmap-sparse"
- "galprop"
- "galprop2"
sparse : bool
Sparsify the map by dropping pixels with zero amplitude.
This option is only compatible with the 'gadf' format.
"""
hdulist = self.to_hdulist(**kwargs)
hdulist.writeto(str(make_path(filename)), overwrite=overwrite)
def iter_by_axis(self, axis_name, keepdims=False):
""" "Iterate over a given axis
Yields
------
map : `Map`
Map iteration.
See also
--------
iter_by_image : iterate by image returning a map
"""
axis = self.geom.axes[axis_name]
for idx in range(axis.nbin):
idx_axis = slice(idx, idx + 1) if keepdims else idx
slices = {axis_name: idx_axis}
yield self.slice_by_idx(slices=slices)
def iter_by_image(self, keepdims=False):
"""Iterate over image planes of a map.
Parameters
----------
keepdims : bool
Keep dimensions.
Yields
------
map : `Map`
Map iteration.
See also
--------
iter_by_image_data : iterate by image returning data and index
"""
for idx in np.ndindex(self.geom.shape_axes):
if keepdims:
names = self.geom.axes.names
slices = {name: slice(_, _ + 1) for name, _ in zip(names, idx)}
yield self.slice_by_idx(slices=slices)
else:
yield self.get_image_by_idx(idx=idx)
def iter_by_image_data(self):
"""Iterate over image planes of the map.
The image plane index is in data order, so that the data array can be
indexed directly.
Yields
------
(data, idx) : tuple
Where ``data`` is a `numpy.ndarray` view of the image plane data,
and ``idx`` is a tuple of int, the index of the image plane.
See also
--------
iter_by_image : iterate by image returning a map
"""
for idx in np.ndindex(self.geom.shape_axes):
yield self.data[idx[::-1]], idx[::-1]
def coadd(self, map_in, weights=None):
"""Add the contents of ``map_in`` to this map.
This method can be used to combine maps containing integral quantities (e.g. counts)
or differential quantities if the maps have the same binning.
Parameters
----------
map_in : `Map`
Input map.
weights: `Map` or `~numpy.ndarray`
The weight factors while adding
"""
if not self.unit.is_equivalent(map_in.unit):
raise ValueError("Incompatible units")
# TODO: Check whether geometries are aligned and if so sum the
# data vectors directly
if weights is not None:
map_in = map_in * weights
idx = map_in.geom.get_idx()
coords = map_in.geom.get_coord()
vals = u.Quantity(map_in.get_by_idx(idx), map_in.unit)
self.fill_by_coord(coords, vals)
def pad(self, pad_width, axis_name=None, mode="constant", cval=0, method="linear"):
"""Pad the spatial dimensions of the map.
Parameters
----------
pad_width : {sequence, array_like, int}
Number of pixels padded to the edges of each axis.
axis_name : str
Which axis to downsample. By default spatial axes are padded.
mode : {'edge', 'constant', 'interp'}
Padding mode. 'edge' pads with the closest edge value.
'constant' pads with a constant value. 'interp' pads with
an extrapolated value.
cval : float
Padding value when mode='consant'.
Returns
-------
map : `Map`
Padded map.
"""
if axis_name:
if np.isscalar(pad_width):
pad_width = (pad_width, pad_width)
geom = self.geom.pad(pad_width=pad_width, axis_name=axis_name)
idx = self.geom.axes.index_data(axis_name)
pad_width_np = [(0, 0)] * self.data.ndim
pad_width_np[idx] = pad_width
kwargs = {}
if mode == "constant":
kwargs["constant_values"] = cval
data = np.pad(self.data, pad_width=pad_width_np, mode=mode, **kwargs)
return self.__class__(
geom=geom, data=data, unit=self.unit, meta=self.meta.copy()
)
return self._pad_spatial(pad_width, mode="constant", cval=cval)
@abc.abstractmethod
def _pad_spatial(self, pad_width, mode="constant", cval=0, order=1):
pass
@abc.abstractmethod
def crop(self, crop_width):
"""Crop the spatial dimensions of the map.
Parameters
----------
crop_width : {sequence, array_like, int}
Number of pixels cropped from the edges of each axis.
Defined analogously to ``pad_with`` from `numpy.pad`.
Returns
-------
map : `Map`
Cropped map.
"""
pass
@abc.abstractmethod
def downsample(self, factor, preserve_counts=True, axis_name=None):
"""Downsample the spatial dimension by a given factor.
Parameters
----------
factor : int
Downsampling factor.
preserve_counts : bool
Preserve the integral over each bin. This should be true
if the map is an integral quantity (e.g. counts) and false if
the map is a differential quantity (e.g. intensity).
axis_name : str
Which axis to downsample. By default spatial axes are downsampled.
Returns
-------
map : `Map`
Downsampled map.
"""
pass
@abc.abstractmethod
def upsample(self, factor, order=0, preserve_counts=True, axis_name=None):
"""Upsample the spatial dimension by a given factor.
Parameters
----------
factor : int
Upsampling factor.
order : int
Order of the interpolation used for upsampling.
preserve_counts : bool
Preserve the integral over each bin. This should be true
if the map is an integral quantity (e.g. counts) and false if
the map is a differential quantity (e.g. intensity).
axis_name : str
Which axis to upsample. By default spatial axes are upsampled.
Returns
-------
map : `Map`
Upsampled map.
"""
pass
def resample(self, geom, weights=None, preserve_counts=True):
"""Resample pixels to ``geom`` with given ``weights``.
Parameters
----------
geom : `~gammapy.maps.Geom`
Target Map geometry
weights : `~numpy.ndarray`
Weights vector. Default is weight of one. Must have same shape as
the data of the map.
preserve_counts : bool
Preserve the integral over each bin. This should be true
if the map is an integral quantity (e.g. counts) and false if
the map is a differential quantity (e.g. intensity)
Returns
-------
resampled_map : `Map`
Resampled map
"""
coords = self.geom.get_coord()
idx = geom.coord_to_idx(coords)
weights = 1 if weights is None else weights
resampled = self._init_copy(data=None, geom=geom)
resampled._resample_by_idx(
idx, weights=self.data * weights, preserve_counts=preserve_counts
)
return resampled
@abc.abstractmethod
def _resample_by_idx(self, idx, weights=None, preserve_counts=False):
"""Resample pixels at ``idx`` with given ``weights``.
Parameters
----------
idx : tuple
Tuple of pixel index arrays for each dimension of the map.
Tuple should be ordered as (I_lon, I_lat, I_0, ..., I_n)
for WCS maps and (I_hpx, I_0, ..., I_n) for HEALPix maps.
weights : `~numpy.ndarray`
Weights vector. Default is weight of one.
preserve_counts : bool
Preserve the integral over each bin. This should be true
if the map is an integral quantity (e.g. counts) and false if
the map is a differential quantity (e.g. intensity)
"""
pass
def resample_axis(self, axis, weights=None, ufunc=np.add):
"""Resample map to a new axis by grouping and reducing smaller bins by a given ufunc
By default, the map content are summed over the smaller bins. Other numpy ufunc can be
used, e.g. `numpy.logical_and` or `numpy.logical_or`.
Parameters
----------
axis : `MapAxis`
New map axis.
weights : `Map`
Array to be used as weights. The spatial geometry must be equivalent
to `other` and additional axes must be broadcastable.
ufunc : `~numpy.ufunc`
ufunc to use to resample the axis. Default is numpy.add.
Returns
-------
map : `Map`
Map with resampled axis.
"""
from .hpx import HpxGeom
geom = self.geom.resample_axis(axis)
axis_self = self.geom.axes[axis.name]
axis_resampled = geom.axes[axis.name]
# We don't use MapAxis.coord_to_idx because is does not behave as needed with boundaries
coord = axis_resampled.edges.value
edges = axis_self.edges.value
indices = np.digitize(coord, edges) - 1
idx = self.geom.axes.index_data(axis.name)
weights = 1 if weights is None else weights.data
if not isinstance(self.geom, HpxGeom):
shape = self.geom._shape[:2]
else:
shape = (self.geom.data_shape[-1],)
shape += tuple([ax.nbin if ax != axis else 1 for ax in self.geom.axes])
padded_array = np.append(self.data * weights, np.zeros(shape[::-1]), axis=idx)
slices = tuple([slice(0, _) for _ in geom.data_shape])
data = ufunc.reduceat(padded_array, indices=indices, axis=idx)[slices]
return self._init_copy(data=data, geom=geom)
def slice_by_idx(
self,
slices,
):
"""Slice sub map from map object.
Parameters
----------
slices : dict
Dict of axes names and integers or `slice` object pairs. Contains one
element for each non-spatial dimension. For integer indexing the
corresponding axes is dropped from the map. Axes not specified in the
dict are kept unchanged.
Returns
-------
map_out : `Map`
Sliced map object.
"""
geom = self.geom.slice_by_idx(slices)
slices = tuple([slices.get(ax.name, slice(None)) for ax in self.geom.axes])
data = self.data[slices[::-1]]
return self.__class__(geom=geom, data=data, unit=self.unit, meta=self.meta)
def get_image_by_coord(self, coords):
"""Return spatial map at the given axis coordinates.
Parameters
----------
coords : tuple or dict
Tuple should be ordered as (x_0, ..., x_n) where x_i are coordinates
for non-spatial dimensions of the map. Dict should specify the axis
names of the non-spatial axes such as {'axes0': x_0, ..., 'axesn': x_n}.
Returns
-------
map_out : `Map`
Map with spatial dimensions only.
See Also
--------
get_image_by_idx, get_image_by_pix
Examples
--------
::
import numpy as np
from gammapy.maps import Map, MapAxis
from astropy.coordinates import SkyCoord
from astropy import units as u
# Define map axes
energy_axis = MapAxis.from_edges(
np.logspace(-1., 1., 4), unit='TeV', name='energy',
)
time_axis = MapAxis.from_edges(
np.linspace(0., 10, 20), unit='h', name='time',
)
# Define map center
skydir = SkyCoord(0, 0, frame='galactic', unit='deg')
# Create map
m_wcs = Map.create(
map_type='wcs',
binsz=0.02,
skydir=skydir,
width=10.0,
axes=[energy_axis, time_axis],
)
# Get image by coord tuple
image = m_wcs.get_image_by_coord(('500 GeV', '1 h'))
# Get image by coord dict with strings
image = m_wcs.get_image_by_coord({'energy': '500 GeV', 'time': '1 h'})
# Get image by coord dict with quantities
image = m_wcs.get_image_by_coord({'energy': 0.5 * u.TeV, 'time': 1 * u.h})
"""
if isinstance(coords, tuple):
coords = dict(zip(self.geom.axes.names, coords))
idx = self.geom.axes.coord_to_idx(coords)
return self.get_image_by_idx(idx)
def get_image_by_pix(self, pix):
"""Return spatial map at the given axis pixel coordinates
Parameters
----------
pix : tuple
Tuple of scalar pixel coordinates for each non-spatial dimension of
the map. Tuple should be ordered as (I_0, ..., I_n). Pixel coordinates
can be either float or integer type.
See Also
--------
get_image_by_coord, get_image_by_idx
Returns
-------
map_out : `Map`
Map with spatial dimensions only.
"""
idx = self.geom.pix_to_idx(pix)
return self.get_image_by_idx(idx)
def get_image_by_idx(self, idx):
"""Return spatial map at the given axis pixel indices.
Parameters
----------
idx : tuple
Tuple of scalar indices for each non spatial dimension of the map.
Tuple should be ordered as (I_0, ..., I_n).
See Also
--------
get_image_by_coord, get_image_by_pix
Returns
-------
map_out : `Map`
Map with spatial dimensions only.
"""
if len(idx) != len(self.geom.axes):
raise ValueError("Tuple length must equal number of non-spatial dimensions")
# Only support scalar indices per axis
idx = tuple([int(_) for _ in idx])
geom = self.geom.to_image()
data = self.data[idx[::-1]]
return self.__class__(geom=geom, data=data, unit=self.unit, meta=self.meta)
def get_by_coord(self, coords, fill_value=np.nan):
"""Return map values at the given map coordinates.
Parameters
----------
coords : tuple or `~gammapy.maps.MapCoord`
Coordinate arrays for each dimension of the map. Tuple
should be ordered as (lon, lat, x_0, ..., x_n) where x_i
are coordinates for non-spatial dimensions of the map.
fill_value : float
Value which is returned if the position is outside of the projection
footprint
Returns
-------
vals : `~numpy.ndarray`
Values of pixels in the map. np.nan used to flag coords
outside of map.
"""
pix = self.geom.coord_to_pix(coords=coords)
vals = self.get_by_pix(pix, fill_value=fill_value)
return vals
def get_by_pix(self, pix, fill_value=np.nan):
"""Return map values at the given pixel coordinates.
Parameters
----------
pix : tuple
Tuple of pixel index arrays for each dimension of the map.
Tuple should be ordered as (I_lon, I_lat, I_0, ..., I_n)
for WCS maps and (I_hpx, I_0, ..., I_n) for HEALPix maps.
Pixel indices can be either float or integer type.
fill_value : float
Value which is returned if the position is outside of the projection
footprint
Returns
-------
vals : `~numpy.ndarray`
Array of pixel values. np.nan used to flag coordinates
outside of map
"""
# FIXME: Support local indexing here?
# FIXME: Support slicing?
pix = np.broadcast_arrays(*pix)
idx = self.geom.pix_to_idx(pix)
vals = self.get_by_idx(idx)
mask = self.geom.contains_pix(pix)
if not mask.all():
vals = vals.astype(type(fill_value))
vals[~mask] = fill_value
return vals
@abc.abstractmethod
def get_by_idx(self, idx):
"""Return map values at the given pixel indices.
Parameters
----------
idx : tuple
Tuple of pixel index arrays for each dimension of the map.
Tuple should be ordered as (I_lon, I_lat, I_0, ..., I_n)
for WCS maps and (I_hpx, I_0, ..., I_n) for HEALPix maps.
Returns
-------
vals : `~numpy.ndarray`
Array of pixel values.
np.nan used to flag coordinate outside of map
"""
pass
@abc.abstractmethod
def interp_by_coord(self, coords, method="linear", fill_value=None):
"""Interpolate map values at the given map coordinates.
Parameters
----------
coords : tuple or `~gammapy.maps.MapCoord`
Coordinate arrays for each dimension of the map. Tuple
should be ordered as (lon, lat, x_0, ..., x_n) where x_i
are coordinates for non-spatial dimensions of the map.
method : {"linear", "nearest"}
Method to interpolate data values. By default linear
interpolation is performed.
fill_value : None or float value
The value to use for points outside of the interpolation domain.
If None, values outside the domain are extrapolated.
Returns
-------
vals : `~numpy.ndarray`
Interpolated pixel values.
"""
pass
@abc.abstractmethod
def interp_by_pix(self, pix, method="linear", fill_value=None):
"""Interpolate map values at the given pixel coordinates.
Parameters
----------
pix : tuple
Tuple of pixel coordinate arrays for each dimension of the
map. Tuple should be ordered as (p_lon, p_lat, p_0, ...,
p_n) where p_i are pixel coordinates for non-spatial
dimensions of the map.
method : {"linear", "nearest"}
Method to interpolate data values. By default linear
interpolation is performed.
fill_value : None or float value
The value to use for points outside of the interpolation domain.
If None, values outside the domain are extrapolated.
Returns
-------
vals : `~numpy.ndarray`
Interpolated pixel values.
"""
pass
def interp_to_geom(self, geom, preserve_counts=False, fill_value=0, **kwargs):
"""Interpolate map to input geometry.
Parameters
----------
geom : `~gammapy.maps.Geom`
Target Map geometry
preserve_counts : bool
Preserve the integral over each bin. This should be true
if the map is an integral quantity (e.g. counts) and false if
the map is a differential quantity (e.g. intensity)
**kwargs : dict
Keyword arguments passed to `Map.interp_by_coord`
Returns
-------
interp_map : `Map`
Interpolated Map
"""
coords = geom.get_coord()
map_copy = self.copy()
if preserve_counts:
if geom.ndim > 2 and geom.axes[0] != self.geom.axes[0]:
raise ValueError(
f"Energy axis do not match: expected {self.geom.axes[0]},"