MapAxis#

class gammapy.maps.MapAxis(nodes, interp='lin', name='', node_type='edges', unit='', boundary_type='monotonic')[source]#

Bases: object

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:
nodesndarray or 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’.

namestr, optional

Axis name. Default is “”.

node_typestr, 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”.

unitstr, optional

String specifying the data units. Default is “”.

boundary_typestr, 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”.

Attributes Summary

as_plot_center

Plot center.

as_plot_edges

Plot edges.

as_plot_labels

Return a list of axis plot labels.

as_plot_scale

Plot axis scale.

as_plot_xerr

Return a tuple of x-error to be passed to errorbar.

bin_width

Array of bin widths.

bounds

Bounds of the axis as a Quantity.

center

Return an array of bin centers.

edges

Return an array of bin edges.

edges_max

Return an array of bin edges minimum values.

edges_min

Return an array of bin edges maximum values.

interp

Interpolation scale of the axis.

is_energy_axis

Whether this is an energy axis.

iter_by_edges

Iterate by intervals defined by the edges.

name

Name of the axis.

nbin

Return the number of bins.

nbin_per_decade

Return the number of bins per decade.

node_type

Return node type, either 'center' or 'edges'.

unit

Return the coordinate axis unit.

use_center_as_plot_labels

Use center as plot labels.

Methods Summary

assert_name(required_name)

Assert axis name if a specific one is required.

concatenate(axis)

Concatenate another MapAxis to this MapAxis into a new MapAxis object.

coord_to_idx(coord[, clip])

Transform axis coordinate to bin index.

coord_to_pix(coord)

Transform axis to pixel coordinates.

copy(**kwargs)

Copy MapAxis instance and overwrite given attributes.

downsample(factor[, strict])

Downsample map axis by a given factor.

format_plot_xaxis(ax)

Format the x-axis.

format_plot_yaxis(ax)

Format plot y-axis.

from_bounds(lo_bnd, hi_bnd, nbin, **kwargs)

Generate an axis object from a lower/upper bound and number of bins.

from_edges(edges, **kwargs)

Generate an axis object from a sequence of bin edges.

from_energy_bounds(energy_min, energy_max, nbin)

Make an energy axis from energy bounds.

from_energy_edges(energy_edges[, unit, ...])

Make an energy axis from adjacent edges.

from_nodes(nodes, **kwargs)

Generate an axis object from a sequence of nodes (bin centers).

from_stack(axes)

Create a map axis by merging a list of other map axes.

from_table(table[, format, idx, column_prefix])

Instantiate MapAxis from a table HDU.

from_table_hdu(hdu[, format, idx])

Instantiate MapAxis from table HDU.

group_table(edges)

Compute bin groups table for the map axis, given coarser bin edges.

is_aligned(other[, atol])

Check if the other map axis is aligned.

is_allclose(other, **kwargs)

Check if the other map axis is all close.

pad(pad_width)

Pad the axis by a given number of pixels.

pix_to_coord(pix)

Transform pixel to axis coordinates.

pix_to_idx(pix[, clip])

Convert pixel to index.

rename(new_name)

Rename the axis.

round(coord[, clip])

Round coordinate to the nearest axis edge.

slice(idx)

Create a new axis object by extracting a slice from this axis.

squash()

Create a new axis object by squashing the axis into one bin.

to_header([format, idx])

Create FITS header.

to_node_type(node_type)

Return a copy of the MapAxis instance with a node type set to node_type.

to_table([format])

Convert Quantity to OGIP EBOUNDS extension.

to_table_hdu([format])

Convert Quantity to OGIP EBOUNDS extension.

upsample(factor)

Upsample map axis by a given factor.

wrap_coord(coord)

Wrap coords between axis edges for a periodic boundary condition

Attributes Documentation

as_plot_center#

Plot center.

as_plot_edges#

Plot edges.

as_plot_labels#

Return a list of axis plot labels.

as_plot_scale#

Plot axis scale.

as_plot_xerr#

Return a tuple of x-error to be passed to errorbar.

bin_width#

Array of bin widths.

bounds#

Bounds of the axis as a Quantity.

center#

Return an array of bin centers.

edges#

Return an array of bin edges.

edges_max#

Return an array of bin edges minimum values.

edges_min#

Return an array of bin edges maximum values.

interp#

Interpolation scale of the axis.

is_energy_axis#

Whether this is an energy axis.

iter_by_edges#

Iterate by intervals defined by the edges.

name#

Name of the axis.

nbin#

Return the number of bins.

nbin_per_decade#

Return the number of bins per decade.

node_type#

Return node type, either ‘center’ or ‘edges’.

unit#

Return the coordinate axis unit.

use_center_as_plot_labels#

Use center as plot labels.

Methods Documentation

assert_name(required_name)[source]#

Assert axis name if a specific one is required.

Parameters:
required_namestr

Required name.

concatenate(axis)[source]#

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:
axisMapAxis

Axis to concatenate with.

Returns:
axisMapAxis

Concatenation of the two axis.

coord_to_idx(coord, clip=False)[source]#

Transform axis coordinate to bin index.

Parameters:
coordndarray

Array of axis coordinate values.

clipbool, 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:
idxndarray

Array of bin indices.

coord_to_pix(coord)[source]#

Transform axis to pixel coordinates.

Parameters:
coordndarray

Array of axis coordinate values.

Returns:
pixndarray

Array of pixel coordinate values.

copy(**kwargs)[source]#

Copy MapAxis instance and overwrite given attributes.

Parameters:
**kwargsdict, optional

Keyword arguments to overwrite in the map axis constructor.

Returns:
copyMapAxis

Copied map axis.

downsample(factor, strict=True)[source]#

Downsample map axis by a given factor.

When downsampling, each n-th (given by the factor) bin is selected from the axis while preserving the axis limits. For node type “edges” this requires nbin to be dividable by the factor, for node type “center” this requires nbin - 1 to be dividable by the factor.

Parameters:
factorint

Downsampling factor.

strictbool

Whether the number of bins is strictly divisible by the factor. If True, nbin must be divisible by the factor. If False, the reminder bins are put into the last bin of the new axis. Default is True.

Returns:
axisMapAxis

Downsampled map axis.

format_plot_xaxis(ax)[source]#

Format the x-axis.

Parameters:
axAxis

Plot axis to format.

Returns:
axAxis

Formatted plot axis.

format_plot_yaxis(ax)[source]#

Format plot y-axis.

Parameters:
axAxis

Plot axis to format.

Returns:
axAxis

Formatted plot axis.

classmethod from_bounds(lo_bnd, hi_bnd, nbin, **kwargs)[source]#

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_bndfloat

Lower bound of first axis bin.

hi_bndfloat

Upper bound of last axis bin.

nbinint

Number of bins.

interp{‘lin’, ‘log’, ‘sqrt’}

Interpolation method used to transform between axis and pixel coordinates. Default: ‘lin’.

***kwargsdict, optional

Keyword arguments passed to MapAxis.

classmethod from_edges(edges, **kwargs)[source]#

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:
edgesndarray

Axis bin edges.

interp{‘lin’, ‘log’, ‘sqrt’}

Interpolation method used to transform between axis and pixel coordinates. Default: ‘lin’.

**kwargsdict, optional

Keyword arguments passed to MapAxis.

classmethod from_energy_bounds(energy_min, energy_max, nbin, unit=None, per_decade=False, name=None, node_type='edges', strict_bounds=True)[source]#

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_maxQuantity, float

Energy range.

nbinint

Number of bins.

unitUnit, optional

Energy unit. Default is None.

per_decadebool, optional

Whether nbin is given per decade. Default is False.

namestr, optional

Name of the energy axis, either ‘energy’ or ‘energy_true’. Default is None.

node_typestr, optional

Node type, either ‘edges’ or ‘center’. Default is ‘edges’.

strict_boundsbool, 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:
axisMapAxis

Create MapAxis from the given input parameters.

classmethod from_energy_edges(energy_edges, unit=None, name=None, interp='log')[source]#

Make an energy axis from adjacent edges.

Parameters:
energy_edgesQuantity or float

Energy edges.

unitUnit, optional

Energy unit. Default is None.

namestr, optional

Name of the energy axis, either ‘energy’ or ‘energy_true’. Default is None.

interp: str, optional

interpolation mode. Default is ‘log’.

Returns:
axisMapAxis

Axis with name “energy” and interp “log”.

classmethod from_nodes(nodes, **kwargs)[source]#

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:
nodesndarray

Axis nodes (bin center).

interp{‘lin’, ‘log’, ‘sqrt’}

Interpolation method used to transform between axis and pixel coordinates. Default is ‘lin’.

**kwargsdict, optional

Keyword arguments passed to MapAxis.

classmethod from_stack(axes)[source]#

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:
axeslist of MapAxis

List of map axis to merge.

Returns:
axisMapAxis

Merged axis.

classmethod from_table(table, format='ogip', idx=0, column_prefix='')[source]#

Instantiate MapAxis from a table HDU.

Parameters:
tableTable

Table.

format{“ogip”, “ogip-arf”, “fgst-ccube”, “fgst-template”, “gadf”, “gadf-dl3”}

Format specification. Default is “ogip”.

idxint, optional

Column index of the axis. Default is 0.

column_prefixstr, optional

Column name prefix of the axis, used for creating the axis. Default is “”.

Returns:
axisMapAxis

Map Axis.

classmethod from_table_hdu(hdu, format='ogip', idx=0)[source]#

Instantiate MapAxis from table HDU.

Parameters:
hduBinTableHDU

Table HDU.

format{“ogip”, “ogip-arf”, “fgst-ccube”, “fgst-template”}

Format specification. Default is “ogip”.

idxint, optional

Column index of the axis. Default is 0.

Returns:
axisMapAxis

Map Axis.

group_table(edges)[source]#

Compute bin groups table for the map axis, given coarser bin edges.

Parameters:
edgesQuantity

Group bin edges.

Returns:
groupsTable

Map axis group table.

is_aligned(other, atol=0.02)[source]#

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:
otherMapAxis

Other map axis.

atolfloat, optional

Absolute numerical tolerance for the comparison measured in bins. Default is 2e-2.

Returns:
alignedbool

Whether the axes are aligned.

is_allclose(other, **kwargs)[source]#

Check if the other map axis is all close.

Parameters:
otherMapAxis

Other map axis.

**kwargsdict, optional

Keyword arguments passed to allclose.

Returns:
is_allclosebool

Whether the other axis is allclose.

pad(pad_width)[source]#

Pad the axis by a given number of pixels.

Parameters:
pad_widthint 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:
axisMapAxis

Padded axis.

pix_to_coord(pix)[source]#

Transform pixel to axis coordinates.

Parameters:
pixndarray

Array of pixel coordinate values.

Returns:
coordndarray

Array of axis coordinate values.

pix_to_idx(pix, clip=False)[source]#

Convert pixel to index.

Parameters:
pixndarray

Pixel coordinates.

clipbool, 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:
idxndarray

Pixel indices.

rename(new_name)[source]#

Rename the axis. Return a copy of the MapAxis instance with name set to new_name.

Parameters:
new_namestr

The new name for the axis.

Returns:
axisMapAxis

The new MapAxis.

round(coord, clip=False)[source]#

Round coordinate to the nearest axis edge.

Parameters:
coordQuantity

Coordinates to be rounded.

clipbool, 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:
coordQuantity

Rounded coordinates.

slice(idx)[source]#

Create a new axis object by extracting a slice from this axis.

Parameters:
idxslice

Slice object selecting a sub-selection of the axis.

Returns:
axisMapAxis

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)
squash()[source]#

Create a new axis object by squashing the axis into one bin.

Returns:
axisMapAxis

Squashed axis object.

to_header(format='ogip', idx=0)[source]#

Create FITS header.

Parameters:
format{“ogip”}, optional

Format specification. Default is “ogip”.

idxint, optional

Column index of the axis. Default is 0.

Returns:
headerHeader

Header to extend.

to_node_type(node_type)[source]#

Return a copy of the MapAxis instance with a node type set to node_type.

Parameters:
node_typestr

The target node type. It can be either ‘center’ or ‘edges’.

Returns:
axisMapAxis

The new MapAxis.

to_table(format='ogip')[source]#

Convert Quantity to OGIP EBOUNDS extension.

See https://heasarc.gsfc.nasa.gov/docs/heasarc/caldb/docs/memos/cal_gen_92_002/cal_gen_92_002.html#tth_sEc3.2 # noqa: E501

The ‘ogip-sherpa’ format is equivalent to ‘ogip’ but uses keV energy units.

Parameters:
format{“ogip”, “ogip-sherpa”, “gadf-dl3”, “gtpsf”}

Format specification. Default is “ogip”.

Returns:
tableTable

Table HDU.

to_table_hdu(format='ogip')[source]#

Convert Quantity to OGIP EBOUNDS extension.

See https://heasarc.gsfc.nasa.gov/docs/heasarc/caldb/docs/memos/cal_gen_92_002/cal_gen_92_002.html#tth_sEc3.2 # noqa: E501

The ‘ogip-sherpa’ format is equivalent to ‘ogip’ but uses keV energy units.

Parameters:
format{“ogip”, “ogip-sherpa”, “gtpsf”}

Format specification. Default is “ogip”.

Returns:
hduBinTableHDU

Table HDU.

upsample(factor)[source]#

Upsample map axis by a given factor.

When upsampling for each node specified in the axis, the corresponding number of sub-nodes are introduced and preserving the initial nodes. For node type “edges” this results in nbin * factor new bins. For node type “center” this results in (nbin - 1) * factor + 1 new bins.

Parameters:
factorint

Upsampling factor.

Returns:
axisMapAxis

Upsampled map axis.

wrap_coord(coord)[source]#

Wrap coords between axis edges for a periodic boundary condition

Parameters:
coordndarray

Array of axis coordinate values.

Returns:
coordndarray

Wrapped array of axis coordinate values.