-
Notifications
You must be signed in to change notification settings - Fork 187
/
axes.py
3525 lines (2894 loc) · 108 KB
/
axes.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 copy
import html
import inspect
import logging
from collections.abc import Sequence
from enum import Enum
import numpy as np
import scipy
import astropy.units as u
from astropy.io import fits
from astropy.table import Column, Table, hstack
from astropy.time import Time
from astropy.utils import lazyproperty
import matplotlib.pyplot as plt
from gammapy.utils.compat import COPY_IF_NEEDED
from gammapy.utils.interpolation import interpolation_scale
from gammapy.utils.time import time_ref_from_dict, time_ref_to_dict
from .utils import INVALID_INDEX, INVALID_VALUE, edges_from_lo_hi
__all__ = ["MapAxes", "MapAxis", "TimeMapAxis", "LabelMapAxis"]
log = logging.getLogger(__name__)
def flat_if_equal(array):
if array.ndim == 2 and np.all(array == array[0]):
return array[0]
else:
return array
class BoundaryEnum(str, Enum):
monotonic = "monotonic"
periodic = "periodic"
class AxisCoordInterpolator:
"""Axis coordinate interpolator."""
def __init__(self, edges, interp="lin"):
self.scale = interpolation_scale(interp)
self.x = self.scale(edges)
self.y = np.arange(len(edges), dtype=float)
self.fill_value = "extrapolate"
if len(edges) == 1:
self.kind = 0
else:
self.kind = 1
def coord_to_pix(self, coord):
"""Transform coordinate to pixel."""
interp_fn = scipy.interpolate.interp1d(
x=self.x, y=self.y, kind=self.kind, fill_value=self.fill_value
)
return interp_fn(self.scale(coord))
def pix_to_coord(self, pix):
"""Transform pixel to coordinate."""
interp_fn = scipy.interpolate.interp1d(
x=self.y, y=self.x, kind=self.kind, fill_value=self.fill_value
)
return self.scale.inverse(interp_fn(pix))
PLOT_AXIS_LABEL = {
"energy": "Energy",
"energy_true": "True Energy",
"offset": "FoV Offset",
"rad": "Source Offset",
"migra": "Energy / True Energy",
"fov_lon": "FoV Lon.",
"fov_lat": "FoV Lat.",
"time": "Time",
}
DEFAULT_LABEL_TEMPLATE = "{quantity} [{unit}]"
UNIT_STRING_FORMAT = "latex_inline"
class MapAxis:
"""Class representing an axis of a map.
Provides methods for
transforming to/from axis and pixel coordinates. An axis is
defined by a sequence of node values that lie at the center of
each bin. The pixel coordinate at each node is equal to its index
in the node array (0, 1, ..). Bin edges are offset by 0.5 in
pixel coordinates from the nodes such that the lower/upper edge of
the first bin is (-0.5,0.5).
Parameters
----------
nodes : `~numpy.ndarray` or `~astropy.units.Quantity`
Array of node values. These will be interpreted as either bin
edges or centers according to ``node_type``.
interp : {'lin', 'log', 'sqrt'}
Interpolation method used to transform between axis and pixel
coordinates. Default is 'lin'.
name : str, optional
Axis name. Default is "".
node_type : str, optional
Flag indicating whether coordinate nodes correspond to pixel
edges (node_type = 'edges') or pixel centers (node_type =
'center'). 'center' should be used where the map values are
defined at a specific coordinate (e.g. differential
quantities). 'edges' should be used where map values are
defined by an integral over coordinate intervals (e.g. a
counts histogram). Default is "edges".
unit : str, optional
String specifying the data units. Default is "".
boundary_type : str, optional
Flag indicating boundary condition for the axis.
Available options are "monotonic" and "periodic".
"Periodic" boundary is only supported for interp = "lin".
Default is "monotonic".
"""
# TODO: Cache an interpolation object?
def __init__(
self,
nodes,
interp="lin",
name="",
node_type="edges",
unit="",
boundary_type="monotonic",
):
if not isinstance(name, str):
raise TypeError(f"Name must be a string, got: {type(name)!r}")
if len(nodes) != len(np.unique(nodes)):
raise ValueError("MapAxis: node values must be unique")
if ~(np.all(nodes == np.sort(nodes)) or np.all(nodes[::-1] == np.sort(nodes))):
raise ValueError("MapAxis: node values must be sorted")
if isinstance(nodes, u.Quantity):
unit = nodes.unit if nodes.unit is not None else ""
nodes = nodes.value
else:
nodes = np.array(nodes)
if boundary_type not in list(BoundaryEnum):
raise ValueError(f"Invalid boundary_type: {boundary_type}")
if boundary_type == BoundaryEnum.periodic and interp != "lin":
raise ValueError("Periodic Axis only supports linear interpolation")
self._name = name
self._unit = u.Unit(unit)
self._nodes = nodes.astype(float)
self._node_type = node_type
self._interp = interp
self._boundary_type = BoundaryEnum(boundary_type).value
if (self._nodes < 0).any() and interp != "lin":
raise ValueError(
f"Interpolation scaling {interp!r} only support for positive node values."
)
# Set pixel coordinate of first node
if node_type == "edges":
self._pix_offset = -0.5
nbin = len(nodes) - 1
elif node_type == "center":
self._pix_offset = 0.0
nbin = len(nodes)
else:
raise ValueError(f"Invalid node type: {node_type!r}")
self._nbin = nbin
self._use_center_as_plot_labels = None
def _repr_html_(self):
try:
return self.to_html()
except AttributeError:
return f"<pre>{html.escape(str(self))}</pre>"
def assert_name(self, required_name):
"""Assert axis name if a specific one is required.
Parameters
----------
required_name : str
Required name.
"""
if self.name != required_name:
raise ValueError(
"Unexpected axis name,"
f' expected "{required_name}", got: "{self.name}"'
)
def is_aligned(self, other, atol=2e-2):
"""Check if the other map axis is aligned.
Two axes are aligned if their center coordinate values map to integers
on the other axes as well and if the interpolation modes are equivalent.
Parameters
----------
other : `MapAxis`
Other map axis.
atol : float, optional
Absolute numerical tolerance for the comparison measured in bins. Default is 2e-2.
Returns
-------
aligned : bool
Whether the axes are aligned.
"""
pix = self.coord_to_pix(other.center)
pix_other = other.coord_to_pix(self.center)
pix_all = np.append(pix, pix_other)
aligned = np.allclose(np.round(pix_all) - pix_all, 0, atol=atol)
return aligned and self.interp == other.interp
def is_allclose(self, other, **kwargs):
"""Check if the other map axis is all close.
Parameters
----------
other : `MapAxis`
Other map axis.
**kwargs : dict, optional
Keyword arguments passed to `~numpy.allclose`.
Returns
-------
is_allclose : bool
Whether the other axis is allclose.
"""
if not isinstance(other, self.__class__):
return TypeError(f"Cannot compare {type(self)} and {type(other)}")
if self.edges.shape != other.edges.shape:
return False
if not self.unit.is_equivalent(other.unit):
return False
return (
np.allclose(self.edges, other.edges, **kwargs)
and self._node_type == other._node_type
and self._interp == other._interp
and self.name.upper() == other.name.upper()
and self._boundary_type == other._boundary_type
)
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.is_allclose(other, rtol=1e-6, atol=1e-6)
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return id(self)
@lazyproperty
def _transform(self):
"""Interpolate coordinates to pixel."""
return AxisCoordInterpolator(edges=self._nodes, interp=self.interp)
@property
def is_energy_axis(self):
"""Whether this is an energy axis."""
return self.name in ["energy", "energy_true"]
@property
def interp(self):
"""Interpolation scale of the axis."""
return self._interp
@property
def name(self):
"""Name of the axis."""
return self._name
@lazyproperty
def edges(self):
"""Return an array of bin edges."""
pix = np.arange(self.nbin + 1, dtype=float) - 0.5
return u.Quantity(self.pix_to_coord(pix), self._unit, copy=COPY_IF_NEEDED)
@property
def edges_min(self):
"""Return an array of bin edges maximum values."""
return self.edges[:-1]
@property
def edges_max(self):
"""Return an array of bin edges minimum values."""
return self.edges[1:]
@property
def bounds(self):
"""Bounds of the axis as a `~astropy.units.Quantity`."""
idx = [0, -1]
if self.node_type == "edges":
return self.edges[idx]
else:
return self.center[idx]
@property
def as_plot_xerr(self):
"""Return a tuple of x-error to be passed to `~matplotlib.pyplot.errorbar`."""
return (
self.center - self.edges_min,
self.edges_max - self.center,
)
@property
def use_center_as_plot_labels(self):
"""Use center as plot labels."""
if self._use_center_as_plot_labels is not None:
return self._use_center_as_plot_labels
return self.node_type == "center"
@use_center_as_plot_labels.setter
def use_center_as_plot_labels(self, value):
"""Use center as plot labels."""
self._use_center_as_plot_labels = bool(value)
@property
def as_plot_labels(self):
"""Return a list of axis plot labels."""
if self.use_center_as_plot_labels:
labels = [f"{val:.2e}" for val in self.center]
else:
labels = [
f"{val_min:.2e} - {val_max:.2e}"
for val_min, val_max in self.iter_by_edges
]
return labels
@property
def as_plot_edges(self):
"""Plot edges."""
return self.edges
@property
def as_plot_center(self):
"""Plot center."""
return self.center
@property
def as_plot_scale(self):
"""Plot axis scale."""
mpl_scale = {"lin": "linear", "sqrt": "linear", "log": "log"}
return mpl_scale[self.interp]
def to_node_type(self, node_type):
"""Return a copy of the `MapAxis` instance with a node type set to node_type.
Parameters
----------
node_type : str
The target node type. It can be either 'center' or 'edges'.
Returns
-------
axis : `~gammapy.maps.MapAxis`
The new MapAxis.
"""
if node_type == self.node_type:
return self
else:
if node_type == "center":
nodes = self.center
else:
nodes = self.edges
return self.__class__(
nodes=nodes,
interp=self.interp,
name=self.name,
node_type=node_type,
unit=self.unit,
)
def rename(self, new_name):
"""Rename the axis. Return a copy of the `MapAxis` instance with name set to new_name.
Parameters
----------
new_name : str
The new name for the axis.
Returns
-------
axis : `~gammapy.maps.MapAxis`
The new MapAxis.
"""
return self.copy(name=new_name)
def format_plot_xaxis(self, ax):
"""Format the x-axis.
Parameters
----------
ax : `~matplotlib.pyplot.Axis`
Plot axis to format.
Returns
-------
ax : `~matplotlib.pyplot.Axis`
Formatted plot axis.
"""
ax.set_xscale(self.as_plot_scale)
xlabel = DEFAULT_LABEL_TEMPLATE.format(
quantity=PLOT_AXIS_LABEL.get(self.name, self.name.capitalize()),
unit=ax.xaxis.units.to_string(UNIT_STRING_FORMAT),
)
ax.set_xlabel(xlabel)
xmin, xmax = self.bounds
if not xmin == xmax:
ax.set_xlim(self.bounds)
return ax
def format_plot_yaxis(self, ax):
"""Format plot y-axis.
Parameters
----------
ax : `~matplotlib.pyplot.Axis`
Plot axis to format.
Returns
-------
ax : `~matplotlib.pyplot.Axis`
Formatted plot axis.
"""
ax.set_yscale(self.as_plot_scale)
ylabel = DEFAULT_LABEL_TEMPLATE.format(
quantity=PLOT_AXIS_LABEL.get(self.name, self.name.capitalize()),
unit=ax.yaxis.units.to_string(UNIT_STRING_FORMAT),
)
ax.set_ylabel(ylabel)
ax.set_ylim(self.bounds)
return ax
@property
def iter_by_edges(self):
"""Iterate by intervals defined by the edges."""
for value_min, value_max in zip(self.edges[:-1], self.edges[1:]):
yield (value_min, value_max)
@lazyproperty
def center(self):
"""Return an array of bin centers."""
pix = np.arange(self.nbin, dtype=float)
return u.Quantity(self.pix_to_coord(pix), self._unit, copy=COPY_IF_NEEDED)
@lazyproperty
def bin_width(self):
"""Array of bin widths."""
return np.diff(self.edges)
@property
def nbin(self):
"""Return the number of bins."""
return self._nbin
@property
def nbin_per_decade(self):
"""Return the number of bins per decade."""
if self.interp != "log":
raise ValueError("Bins per decade can only be computed for log-spaced axes")
if self.node_type == "edges":
values = self.edges
else:
values = self.center
ndecades = np.log10(values.max() / values.min())
return (self._nbin / ndecades).value
@property
def node_type(self):
"""Return node type, either 'center' or 'edges'."""
return self._node_type
@property
def unit(self):
"""Return the coordinate axis unit."""
return self._unit
@classmethod
def from_bounds(cls, lo_bnd, hi_bnd, nbin, **kwargs):
"""Generate an axis object from a lower/upper bound and number of bins.
If node_type = 'edges' then bounds correspond to the
lower and upper bound of the first and last bin. If node_type
= 'center' then bounds correspond to the centers of the first
and last bin.
Parameters
----------
lo_bnd : float
Lower bound of first axis bin.
hi_bnd : float
Upper bound of last axis bin.
nbin : int
Number of bins.
interp : {'lin', 'log', 'sqrt'}
Interpolation method used to transform between axis and pixel
coordinates. Default: 'lin'.
***kwargs : dict, optional
Keyword arguments passed to `MapAxis`.
"""
nbin = int(nbin)
interp = kwargs.setdefault("interp", "lin")
node_type = kwargs.setdefault("node_type", "edges")
if node_type == "edges":
nnode = nbin + 1
elif node_type == "center":
nnode = nbin
else:
raise ValueError(f"Invalid node type: {node_type!r}")
if interp == "lin":
nodes = np.linspace(lo_bnd, hi_bnd, nnode)
elif interp == "log":
nodes = np.geomspace(lo_bnd, hi_bnd, nnode)
elif interp == "sqrt":
nodes = np.linspace(lo_bnd**0.5, hi_bnd**0.5, nnode) ** 2.0
else:
raise ValueError(f"Invalid interp: {interp}")
return cls(nodes, **kwargs)
@classmethod
def from_energy_edges(cls, energy_edges, unit=None, name=None, interp="log"):
"""Make an energy axis from adjacent edges.
Parameters
----------
energy_edges : `~astropy.units.Quantity` or float
Energy edges.
unit : `~astropy.units.Unit`, optional
Energy unit. Default is None.
name : str, optional
Name of the energy axis, either 'energy' or 'energy_true'. Default is None.
interp: str, optional
interpolation mode. Default is 'log'.
Returns
-------
axis : `MapAxis`
Axis with name "energy" and interp "log".
"""
energy_edges = u.Quantity(energy_edges, unit)
if not energy_edges.unit.is_equivalent("TeV"):
raise ValueError(
f"Please provide a valid energy unit, got {energy_edges.unit} instead."
)
if name is None:
name = "energy"
if name not in ["energy", "energy_true"]:
raise ValueError("Energy axis can only be named 'energy' or 'energy_true'")
return cls.from_edges(energy_edges, unit=unit, interp=interp, name=name)
@classmethod
def from_energy_bounds(
cls,
energy_min,
energy_max,
nbin,
unit=None,
per_decade=False,
name=None,
node_type="edges",
strict_bounds=True,
):
"""Make an energy axis from energy bounds. The interpolation is always 'log'.
Used frequently also to make energy grids, by making
the axis, and then using ``axis.center`` or ``axis.edges``.
Parameters
----------
energy_min, energy_max : `~astropy.units.Quantity`, float
Energy range.
nbin : int
Number of bins.
unit : `~astropy.units.Unit`, optional
Energy unit. Default is None.
per_decade : bool, optional
Whether `nbin` is given per decade. Default is False.
name : str, optional
Name of the energy axis, either 'energy' or 'energy_true'. Default is None.
node_type : str, optional
Node type, either 'edges' or 'center'. Default is 'edges'.
strict_bounds : bool, optional
Whether to strictly end the binning at 'energy_max' when
`per_decade=True`. If True, the number of bins per decade
might be slightly increased to match the bounds. If False,
'energy_max' might be reduced so the number of bins per
decade is exactly the given input. Default is True.
Returns
-------
axis : `MapAxis`
Create MapAxis from the given input parameters.
"""
energy_min = u.Quantity(energy_min, unit)
energy_max = u.Quantity(energy_max, unit)
if unit is None:
unit = energy_max.unit
energy_min = energy_min.to(unit)
if not energy_max.unit.is_equivalent("TeV"):
raise ValueError(
f"Please provide a valid energy unit, got {energy_max.unit} instead."
)
if per_decade:
if strict_bounds:
nbin = np.ceil(np.log10(energy_max / energy_min).value * nbin)
else:
bin_per_decade = nbin
nbin = np.floor(
np.log10(energy_max / energy_min).value * bin_per_decade
)
if np.log10(energy_max / energy_min).value % (1 / bin_per_decade) != 0:
energy_max = energy_min * 10 ** (nbin / bin_per_decade)
if name is None:
name = "energy"
if name not in ["energy", "energy_true"]:
raise ValueError("Energy axis can only be named 'energy' or 'energy_true'")
return cls.from_bounds(
energy_min.value,
energy_max.value,
nbin=nbin,
unit=unit,
interp="log",
name=name,
node_type=node_type,
)
@classmethod
def from_nodes(cls, nodes, **kwargs):
# TODO: What to do with interp in docstring but not in signature?
"""Generate an axis object from a sequence of nodes (bin centers).
This will create a sequence of bins with edges half-way
between the node values. This method should be used to
construct an axis where the bin center should lie at a
specific value (e.g. a map of a continuous function).
Parameters
----------
nodes : `~numpy.ndarray`
Axis nodes (bin center).
interp : {'lin', 'log', 'sqrt'}
Interpolation method used to transform between axis and pixel
coordinates. Default is 'lin'.
**kwargs : dict, optional
Keyword arguments passed to `MapAxis`.
"""
if len(nodes) < 1:
raise ValueError("Nodes array must have at least one element.")
return cls(nodes, node_type="center", **kwargs)
@classmethod
def from_edges(cls, edges, **kwargs):
"""Generate an axis object from a sequence of bin edges.
This method should be used to construct an axis where the bin
edges should lie at specific values (e.g. a histogram). The
number of bins will be one less than the number of edges.
Parameters
----------
edges : `~numpy.ndarray`
Axis bin edges.
interp : {'lin', 'log', 'sqrt'}
Interpolation method used to transform between axis and pixel
coordinates. Default: 'lin'.
**kwargs : dict, optional
Keyword arguments passed to `MapAxis`.
"""
if len(edges) < 2:
raise ValueError("Edges array must have at least two elements.")
return cls(edges, node_type="edges", **kwargs)
def concatenate(self, axis):
"""Concatenate another `MapAxis` to this `MapAxis` into a new `MapAxis` object.
Name, interp type and node type must agree between the axes. If the node
type is "edges", the edges must be contiguous and non-overlapping.
Parameters
----------
axis : `MapAxis`
Axis to concatenate with.
Returns
-------
axis : `MapAxis`
Concatenation of the two axis.
"""
if self.node_type != axis.node_type:
raise ValueError(
f"Node type must agree, got {self.node_type} and {axis.node_type}"
)
if self.name != axis.name:
raise ValueError(f"Names must agree, got {self.name} and {axis.name} ")
if self.interp != axis.interp:
raise ValueError(
f"Interp type must agree, got {self.interp} and {axis.interp}"
)
if self.node_type == "edges":
edges = np.append(self.edges, axis.edges[1:])
return self.from_edges(edges=edges, interp=self.interp, name=self.name)
else:
nodes = np.append(self.center, axis.center)
return self.from_nodes(nodes=nodes, interp=self.interp, name=self.name)
def pad(self, pad_width):
"""Pad the axis by a given number of pixels.
Parameters
----------
pad_width : int or tuple of int
A single integer pads in both direction of the axis, a tuple specifies
which number of bins to pad at the low and high edge of the axis.
Returns
-------
axis : `MapAxis`
Padded axis.
"""
if isinstance(pad_width, tuple):
pad_low, pad_high = pad_width
else:
pad_low, pad_high = pad_width, pad_width
if self.node_type == "edges":
pix = np.arange(-pad_low, self.nbin + pad_high + 1) - 0.5
edges = self.pix_to_coord(pix)
return self.from_edges(edges=edges, interp=self.interp, name=self.name)
else:
pix = np.arange(-pad_low, self.nbin + pad_high)
nodes = self.pix_to_coord(pix)
return self.from_nodes(nodes=nodes, interp=self.interp, name=self.name)
@classmethod
def from_stack(cls, axes):
"""Create a map axis by merging a list of other map axes.
If the node type is "edges" the bin edges in the provided axes must be
contiguous and non-overlapping.
Parameters
----------
axes : list of `MapAxis`
List of map axis to merge.
Returns
-------
axis : `MapAxis`
Merged axis.
"""
ax_stacked = axes[0]
for ax in axes[1:]:
ax_stacked = ax_stacked.concatenate(ax)
return ax_stacked
def pix_to_coord(self, pix):
"""Transform pixel to axis coordinates.
Parameters
----------
pix : `~numpy.ndarray`
Array of pixel coordinate values.
Returns
-------
coord : `~numpy.ndarray`
Array of axis coordinate values.
"""
pix = pix - self._pix_offset
values = self._transform.pix_to_coord(pix=pix)
return u.Quantity(values, unit=self.unit, copy=COPY_IF_NEEDED)
def wrap_coord(self, coord):
"""Wrap coords between axis edges for a periodic boundary condition
Parameters
----------
coord : `~numpy.ndarray`
Array of axis coordinate values.
Returns
-------
coord : `~numpy.ndarray`
Wrapped array of axis coordinate values.
"""
m1, m2 = self.edges_min[0], self.edges_max[-1]
out_of_range = (coord >= m2) | (coord < m1)
return np.where(out_of_range, (coord - m1) % (m2 - m1) + m1, coord)
def pix_to_idx(self, pix, clip=False):
"""Convert pixel to index.
Parameters
----------
pix : `~numpy.ndarray`
Pixel coordinates.
clip : bool, optional
Choose whether to clip indices to the valid range of the
axis. Default is False. If False, indices for coordinates outside
the axis range will be set to -1.
Returns
-------
idx : `~numpy.ndarray`
Pixel indices.
"""
if clip:
idx = np.clip(pix, 0, self.nbin - 1)
else:
condition = (pix < 0) | (pix >= self.nbin)
idx = np.where(condition, -1, pix)
return idx
def coord_to_pix(self, coord):
"""Transform axis to pixel coordinates.
Parameters
----------
coord : `~numpy.ndarray`
Array of axis coordinate values.
Returns
-------
pix : `~numpy.ndarray`
Array of pixel coordinate values.
"""
if self._boundary_type == BoundaryEnum.periodic:
coord = self.wrap_coord(coord)
coord = u.Quantity(coord, self.unit, copy=COPY_IF_NEEDED).value
pix = self._transform.coord_to_pix(coord=coord)
return np.array(pix + self._pix_offset, ndmin=1)
def coord_to_idx(self, coord, clip=False):
"""Transform axis coordinate to bin index.
Parameters
----------
coord : `~numpy.ndarray`
Array of axis coordinate values.
clip : bool, optional
Choose whether to clip the index to the valid range of the
axis. Default is False. If False, then indices for values outside the axis
range will be set to -1.
Returns
-------
idx : `~numpy.ndarray`
Array of bin indices.
"""
if self._boundary_type == BoundaryEnum.periodic:
coord = self.wrap_coord(coord)
coord = u.Quantity(coord, self.unit, copy=COPY_IF_NEEDED, ndmin=1).value
edges = self.edges.value
idx = np.digitize(coord, edges) - 1
if clip:
idx = np.clip(idx, 0, self.nbin - 1)
else:
with np.errstate(invalid="ignore"):
idx[coord > edges[-1]] = INVALID_INDEX.int
idx[~np.isfinite(coord)] = INVALID_INDEX.int
return idx
def slice(self, idx):
"""Create a new axis object by extracting a slice from this axis.
Parameters
----------
idx : slice
Slice object selecting a sub-selection of the axis.
Returns
-------
axis : `MapAxis`
Sliced axis object.
Examples
--------
>>> from gammapy.maps import MapAxis
>>> axis = MapAxis.from_bounds(
... 10.0, 2e3, 6, interp="log", name="energy_true", unit="GeV"
... )
>>> slices = slice(1, 3)
>>> sliced = axis.slice(slices)
"""
center = self.center[idx].value
idx = self.coord_to_idx(center)
# For edge nodes we need to keep N+1 nodes
if self._node_type == "edges":
idx = tuple(list(idx) + [1 + idx[-1]])
nodes = self._nodes[(idx,)]
return MapAxis(
nodes,
interp=self._interp,
name=self._name,
node_type=self._node_type,
unit=self._unit,
)
def squash(self):
"""Create a new axis object by squashing the axis into one bin.
Returns
-------
axis : `~MapAxis`
Squashed axis object.
"""
return MapAxis.from_bounds(
lo_bnd=self.edges[0].value,
hi_bnd=self.edges[-1].value,
nbin=1,
interp=self._interp,
name=self._name,
unit=self._unit,
)
def __repr__(self):
str_ = self.__class__.__name__
str_ += "\n\n"
fmt = "\t{:<10s} : {:<10s}\n"
str_ += fmt.format("name", self.name)
str_ += fmt.format("unit", "{!r}".format(str(self.unit)))
str_ += fmt.format("nbins", str(self.nbin))
str_ += fmt.format("node type", self.node_type)
vals = self.edges if self.node_type == "edges" else self.center
str_ += fmt.format(f"{self.node_type} min", "{:.1e}".format(vals.min()))
str_ += fmt.format(f"{self.node_type} max", "{:.1e}".format(vals.max()))
str_ += fmt.format("interp", self._interp)
return str_
def _init_copy(self, **kwargs):
"""Init map axis instance by copying missing init arguments from self."""
argnames = inspect.getfullargspec(self.__init__).args
argnames.remove("self")
for arg in argnames:
value = getattr(self, "_" + arg)
if arg not in kwargs:
kwargs[arg] = copy.deepcopy(value)
return self.__class__(**kwargs)
def copy(self, **kwargs):
"""Copy `MapAxis` instance and overwrite given attributes.
Parameters
----------
**kwargs : dict, optional
Keyword arguments to overwrite in the map axis constructor.
Returns
-------
copy : `MapAxis`
Copied map axis.
"""
return self._init_copy(**kwargs)
def round(self, coord, clip=False):
"""Round coordinate to the nearest axis edge.