WcsNDMap#

class gammapy.maps.WcsNDMap(geom, data=None, dtype='float32', meta=None, unit='')[source]#

Bases: gammapy.maps.wcs.core.WcsMap

WCS map with any number of non-spatial dimensions.

This class uses an ND numpy array to store map values. For maps with non-spatial dimensions and variable pixel size it will allocate an array with dimensions commensurate with the largest image plane.

Parameters
geomWcsGeom

WCS geometry object.

datandarray

Data array. If none then an empty array will be allocated.

dtypestr, optional

Data type, default is float32

metadict

Dictionary to store meta data.

unitstr or Unit

The map unit

Attributes Summary

data

Data array as a ndarray object.

geom

Map geometry as a Geom object.

is_mask

Whether map is a mask with boolean data type.

meta

Map metadata as a dict.

quantity

Map data as a Quantity object.

tag

unit

Map unit as an Unit object.

Methods Summary

binary_dilate(width[, kernel, use_fft])

Binary dilation of boolean mask adding a given margin.

binary_erode(width[, kernel, use_fft])

Binary erosion of boolean mask removing a given margin.

coadd(map_in[, weights])

Add the contents of map_in to this map.

convolve(kernel[, method, mode])

Convolve map with a kernel.

copy(**kwargs)

Copy map instance and overwrite given attributes, except for geometry.

create([map_type, npix, binsz, width, proj, ...])

Factory method to create an empty WCS map.

crop(crop_width)

Crop the spatial dimensions of the map.

cumsum(axis_name)

Compute cumulative sum along a given axis.

cutout(position, width[, mode, odd_npix])

Create a cutout around a given position.

cutout_and_mask_region([region])

Compute cutout and mask for a given region of the map.

dot(other)

Apply dot product with the input map.

downsample(factor[, preserve_counts, ...])

Downsample the spatial dimension by a given factor.

fill_by_coord(coords[, weights])

Fill pixels at coords with given weights.

fill_by_idx(idx[, weights])

Fill pixels at idx with given weights.

fill_by_pix(pix[, weights])

Fill pixels at pix with given weights.

fill_events(events[, weights])

Fill the map from an EventList object.

from_geom(geom[, meta, data, unit, dtype])

Generate an empty map from a Geom instance.

from_hdu(hdu[, hdu_bands, format])

Make a WcsNDMap object from a FITS HDU.

from_hdulist(hdu_list[, hdu, hdu_bands, format])

Make a WcsMap object from a FITS HDUList.

from_stack(maps[, axis, axis_name])

Create Map from a list of images and a non-spatial axis.

get_by_coord(coords[, fill_value])

Return map values at the given map coordinates.

get_by_idx(idx)

Return map values at the given pixel indices.

get_by_pix(pix[, fill_value])

Return map values at the given pixel coordinates.

get_image_by_coord(coords)

Return spatial map at the given axis coordinates.

get_image_by_idx(idx)

Return spatial map at the given axis pixel indices.

get_image_by_pix(pix)

Return spatial map at the given axis pixel coordinates

get_spectrum([region, func, weights])

Extract spectrum in a given region.

integral(axis_name, coords, **kwargs)

Compute integral along a given axis.

interp_by_coord(coords[, method, ...])

Interpolate map values at the given map coordinates.

interp_by_pix(pix[, method, fill_value, ...])

Interpolate map values at the given pixel coordinates.

interp_to_geom(geom[, preserve_counts, ...])

Interpolate map to input geometry.

is_allclose(other[, rtol_axes, atol_axes])

Compare two Maps for close equivalency.

iter_by_axis(axis_name[, keepdims])

Iterate over a given axis.

iter_by_image([keepdims])

Iterate over image planes of a map.

iter_by_image_data()

Iterate over image planes of the map.

iter_by_image_index()

Iterate over image planes of the map.

mask_contains_region(region)

Check if input region is contained in a boolean mask map.

mask_nearest_position(position)

Given a sky coordinate return nearest valid position in the mask.

normalize([axis_name])

Normalise data in place along a given axis.

pad(pad_width[, axis_name, mode, cval, method])

Pad the spatial dimensions of the map.

plot([ax, fig, add_cbar, stretch, axes_loc, ...])

Plot image on matplotlib WCS axes.

plot_grid([figsize, ncols])

Plot map as a grid of subplots for non-spatial axes.

plot_interactive([rc_params])

Plot map with interactive widgets to explore the non-spatial axes.

plot_mask([ax])

Plot the mask as a shaded area.

read(filename[, hdu, hdu_bands, map_type, ...])

Read a map from a FITS file.

reduce(axis_name[, func, keepdims, weights])

Reduce map over a single non-spatial axis.

reduce_over_axes([func, keepdims, ...])

Reduce map over non-spatial axes.

rename_axes(names, new_names)

Rename the Map axes.

reorder_axes(axes_names)

Return a new map re-ordering the non-spatial axes.

reproject_by_image(geom[, preserve_counts, ...])

Reproject each image of a ND map to input 2d geometry.

reproject_to_geom(geom[, preserve_counts, ...])

Reproject map to input geometry.

resample(geom[, weights, preserve_counts])

Resample pixels to geom with given weights.

resample_axis(axis[, weights, ufunc])

Resample map to a new axis by grouping and reducing smaller bins by a given function ufunc.

sample_coord(n_events[, random_state])

Sample position and energy of events.

set_by_coord(coords, vals)

Set pixels at coords with given vals.

set_by_idx(idx, vals)

Set pixels at idx with given vals.

set_by_pix(pix, vals)

Set pixels at pix with given vals.

slice_by_idx(slices)

Slice sub map from map object.

smooth(width[, kernel])

Smooth the map.

split_by_axis(axis_name)

Split a Map along an axis into multiple maps.

stack(other[, weights, nan_to_num])

Stack cutout into map.

sum_over_axes([axes_names, keepdims, weights])

Sum map values over all non-spatial axes.

to_cube(axes)

Append non-spatial axes to create a higher-dimensional Map.

to_hdu([hdu, hdu_bands, sparse])

Make a FITS HDU from this map.

to_hdulist([hdu, hdu_bands, sparse, format])

Convert to HDUList.

to_region_nd_map([region, func, weights, method])

Get region ND map in a given region.

to_region_nd_map_histogram([region, ...])

Convert map into region map by histogramming.

to_unit(unit)

Convert map to a different unit.

upsample(factor[, order, preserve_counts, ...])

Upsample the spatial dimension by a given factor.

write(filename[, overwrite])

Write to a FITS file.

Attributes Documentation

data#

Data array as a ndarray object.

geom#

Map geometry as a Geom object.

is_mask#

Whether map is a mask with boolean data type.

meta#

Map metadata as a dict.

quantity#

Map data as a Quantity object.

tag = 'map'#
unit#

Map unit as an Unit object.

Methods Documentation

binary_dilate(width, kernel='disk', use_fft=True)[source]#

Binary dilation of boolean mask adding a given margin.

Parameters
widthtuple of Quantity

Angular sizes of the margin in (lon, lat) in that specific order. If only one value is passed, the same margin is applied in (lon, lat).

kernel{‘disk’, ‘box’}, optional

Kernel shape. Default is “disk”.

use_fftbool, optional

Use scipy.signal.fftconvolve if True. Otherwise, use scipy.ndimage.binary_dilation. Default is True.

Returns
mapWcsNDMap

Dilated mask map.

binary_erode(width, kernel='disk', use_fft=True)[source]#

Binary erosion of boolean mask removing a given margin.

Parameters
widthQuantity, str or float

If a float is given it interpreted as width in pixels. If an (angular) quantity is given it converted to pixels using geom.wcs.wcs.cdelt. The width corresponds to radius in case of a disk kernel, and the side length in case of a box kernel.

kernel{‘disk’, ‘box’}, optional

Kernel shape. Default is “disk”.

use_fftbool, optional

Use scipy.signal.fftconvolve if True. Otherwise, use scipy.ndimage.binary_erosion. Default is True.

Returns
mapWcsNDMap

Eroded mask map.

coadd(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_inMap

Map to add.

weights: `Map` or `~numpy.ndarray`

The weight factors while adding. Default is None.

convolve(kernel, method='fft', mode='same')[source]#

Convolve map with a kernel.

If the kernel is two-dimensional, it is applied to all image planes likewise. If the kernel is higher dimensional, it should either match the map in the number of dimensions or the map must be an image (no non-spatial axes). In that case, the corresponding kernel is selected and applied to every image plane or to the single input image respectively.

Parameters
kernelPSFKernel or numpy.ndarray

Convolution kernel.

methodstr, optional

The method used by convolve. Default is ‘fft’.

modestr, optional

The convolution mode used by convolve. Default is ‘same’.

Returns
mapWcsNDMap

Convolved map.

copy(**kwargs)#

Copy map instance and overwrite given attributes, except for geometry.

Parameters
**kwargsdict, optional

Keyword arguments to overwrite in the map constructor.

Returns
copyMap

Copied Map.

classmethod create(map_type='wcs', npix=None, binsz=0.1, width=None, proj='CAR', frame='icrs', refpix=None, axes=None, skydir=None, dtype='float32', meta=None, unit='')#

Factory method to create an empty WCS map.

Parameters
map_type{‘wcs’, ‘wcs-sparse’}, optional

Map type. Selects the class that will be used to instantiate the map. Default is “wcs”.

npixint or tuple or list, optional

Width of the map in pixels. A tuple will be interpreted as parameters for longitude and latitude axes. For maps with non-spatial dimensions, list input can be used to define a different map width in each image plane. This option supersedes width. Default is None.

binszfloat or tuple or list, optional

Map pixel size in degrees. A tuple will be interpreted as parameters for longitude and latitude axes. For maps with non-spatial dimensions, list input can be used to define a different bin size in each image plane. Default is 0.1.

widthfloat or tuple or list, optional

Width of the map in degrees. A tuple will be interpreted as parameters for longitude and latitude axes. For maps with non-spatial dimensions, list input can be used to define a different map width in each image plane. Default is None.

projstring, optional

Any valid WCS projection type. Default is ‘CAR’ (cartesian).

frame{“icrs”, “galactic”}, optional

Coordinate system, either Galactic (“galactic”) or Equatorial (“icrs”). Default is “icrs”.

refpixtuple, optional

Reference pixel of the projection. If None then this will be chosen to be center of the map. Default is None.

axeslist, optional

List of non-spatial axes. Default is None.

skydirtuple or SkyCoord, optional

Sky position of map center. Can be either a SkyCoord object or a tuple of longitude and latitude in degrees in the coordinate system of the map.

dtypestr, optional

Data type. Default is “float32”.

metadict, optional

Dictionary to store metadata. Default is None.

unitstr or Unit, optional

The unit of the map. Default is “”.

Returns
mapWcsMap

A WCS map object.

crop(crop_width)[source]#

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
mapMap

Cropped map.

cumsum(axis_name)#

Compute cumulative sum along a given axis.

Parameters
axis_namestr

Along which axis to sum.

Returns
cumsumMap

Map with cumulative sum.

cutout(position, width, mode='trim', odd_npix=False)[source]#

Create a cutout around a given position.

Parameters
positionSkyCoord

Center position of the cutout region.

widthtuple of Angle

Angular sizes of the region in (lon, lat) in that specific order. If only one value is passed, a square region is extracted.

mode{‘trim’, ‘partial’, ‘strict’}, optional

Mode option for Cutout2D, for details see Cutout2D. Default is “trim”.

odd_npixbool, optional

Force width to odd number of pixels. Default is False.

Returns
cutoutWcsNDMap

Cutout map.

cutout_and_mask_region(region=None)[source]#

Compute cutout and mask for a given region of the map.

The function will estimate the minimal size of the cutout, which encloses the region.

Parameters
region: `~regions.Region`, optional

Extended region. Default is None.

Returns
cutout, masktuple of WcsNDMap

Cutout and mask map.

dot(other)#

Apply dot product with the input map.

The input Map has to share a single MapAxis with the current Map. Because it has no spatial dimension, it must be a RegionNDMap.

Parameters
otherRegionNDMap

Map to apply the dot product to. It must share a unique non-spatial MapAxis with the current Map.

Returns
mapMap

Map with dot product applied.

downsample(factor, preserve_counts=True, axis_name=None, weights=None)[source]#

Downsample the spatial dimension by a given factor.

Parameters
factorint

Downsampling factor.

preserve_countsbool, optional

Preserve the integral over each bin. This should be set to True if the map is an integral quantity (e.g. counts) and False if the map is a differential quantity (e.g. intensity). Default is True.

axis_namestr, optional

Which axis to downsample. By default, spatial axes are downsampled. Default is None.

Returns
mapMap

Downsampled map.

fill_by_coord(coords, weights=None)#

Fill pixels at coords with given weights.

Parameters
coordstuple or 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.

weightsndarray, optional

Weights vector. If None, weights are set to 1. Default is None.

fill_by_idx(idx, weights=None)[source]#

Fill pixels at idx with given weights.

Parameters
idxtuple

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.

weightsndarray, optional

Weights vector. If None, weights are set to 1. Default is None.

fill_by_pix(pix, weights=None)#

Fill pixels at pix with given weights.

Parameters
pixtuple

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. Float indices will be rounded to the nearest integer.

weightsndarray, optional

Weights vector. If None, weights are set to 1. Default is None.

fill_events(events, weights=None)#

Fill the map from an EventList object.

Parameters
eventsEventList

Events to fill in the map with.

weightsndarray, optional

Weights vector. The weights vector must be of the same length as the events column length. If None, weights are set to 1. Default is None.

static from_geom(geom, meta=None, data=None, unit='', dtype='float32')#

Generate an empty map from a Geom instance.

Parameters
geomGeom

Map geometry.

metadict, optional

Dictionary to store metadata. Default is None.

datanumpy.ndarray, optional

Data array. Default is None.

unitstr or Unit

Data unit.

dtypestr, optional

Data type. Default is ‘float32’.

Returns
map_outMap

Map object.

classmethod from_hdu(hdu, hdu_bands=None, format=None)[source]#

Make a WcsNDMap object from a FITS HDU.

Parameters
hduBinTableHDU or ImageHDU

The map FITS HDU.

hdu_bandsBinTableHDU

The BANDS table HDU.

format{‘gadf’, ‘fgst-ccube’,’fgst-template’}

FITS format convention.

Returns
mapWcsNDMap

WCS map.

classmethod from_hdulist(hdu_list, hdu=None, hdu_bands=None, format='gadf')#

Make a WcsMap object from a FITS HDUList.

Parameters
hdu_listHDUList

HDU list containing HDUs for map data and bands.

hdustr, optional

Name or index of the HDU with the map data. Default is None.

hdu_bandsstr, optional

Name or index of the HDU with the BANDS table. Default is None.

format{‘gadf’, ‘fgst-ccube’, ‘fgst-template’}, optional

FITS format convention. Default is “gadf”.

Returns
wcs_mapWcsMap

Map object.

classmethod from_stack(maps, axis=None, axis_name=None)#

Create Map from a list of images and a non-spatial axis.

The image geometries must be aligned, except for the axis that is stacked.

Parameters
mapslist of Map objects

List of maps.

axisMapAxis, optional

If a MapAxis is provided the maps are stacked along the last data axis and the new axis is introduced. Default is None.

axis_namestr, optional

If an axis name is as string the given the maps are stacked along the given axis name.

Returns
mapMap

Map with additional non-spatial axis.

get_by_coord(coords, fill_value=nan)#

Return map values at the given map coordinates.

Parameters
coordstuple or 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_valuefloat

Value which is returned if the position is outside the projection footprint. Default is numpy.nan.

Returns
valsndarray

Values of pixels in the map. numpy.nan is used to flag coordinates outside the map.

get_by_idx(idx)[source]#

Return map values at the given pixel indices.

Parameters
idxtuple

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
valsndarray

Array of pixel values. numpy.nan is used to flag coordinates outside the map.

get_by_pix(pix, fill_value=nan)#

Return map values at the given pixel coordinates.

Parameters
pixtuple

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_valuefloat

Value which is returned if the position is outside the projection footprint. Default is numpy.nan.

Returns
valsndarray

Array of pixel values. numpy.nan is used to flag coordinates outside the map.

get_image_by_coord(coords)#

Return spatial map at the given axis coordinates.

Parameters
coordstuple or dict

Tuple should be ordered as (x_0, …, x_n) where x_i are coordinates for non-spatial dimensions of the map. Dictionary should specify the axis names of the non-spatial axes such as {‘axes0’: x_0, …, ‘axesn’: x_n}.

Returns
map_outMap

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})
get_image_by_idx(idx)#

Return spatial map at the given axis pixel indices.

Parameters
idxtuple

Tuple of scalar indices for each non-spatial dimension of the map. Tuple should be ordered as (I_0, …, I_n).

Returns
map_outMap

Map with spatial dimensions only.

See also

get_image_by_coord, get_image_by_pix.
get_image_by_pix(pix)#

Return spatial map at the given axis pixel coordinates

Parameters
pixtuple

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.

Returns
map_outMap

Map with spatial dimensions only.

See also

get_image_by_coord, get_image_by_idx.
get_spectrum(region=None, func=<function nansum>, weights=None)#

Extract spectrum in a given region.

The spectrum can be computed by summing (or, more generally, applying func) along the spatial axes in each energy bin. This occurs only inside the region, which by default is assumed to be the whole spatial extension of the map.

Parameters
region: `~regions.Region`, optional

Region to extract the spectrum from. Pixel or sky regions are accepted. Default is None.

funcnumpy.func, optional

Function to reduce the data. Default is nansum. For a boolean Map, use numpy.any or numpy.all. Default is numpy.nansum.

weightsWcsNDMap, optional

Array to be used as weights. The geometry must be equivalent. Default is None.

Returns
spectrumRegionNDMap

Spectrum in the given region.

integral(axis_name, coords, **kwargs)#

Compute integral along a given axis.

This method uses interpolation of the cumulative sum.

Parameters
axis_namestr

Along which axis to integrate.

coordsdict or MapCoord

Map coordinates.

**kwargsdict, optional

Keyword arguments passed to Map.interp_by_coord.

Returns
arrayQuantity

2D array with axes offset.

interp_by_coord(coords, method='linear', fill_value=None, values_scale='lin')[source]#

Interpolate map values at the given map coordinates.

Parameters
coordstuple, dict or 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. “lon” and “lat” are optional and will be taken at the center of the region by default.

method{“linear”, “nearest”}

Method to interpolate data values. By default linear interpolation is performed.

fill_valueNone or float value

The value to use for points outside of the interpolation domain. If None, values outside the domain are extrapolated.

values_scale{“lin”, “log”, “sqrt”}

Optional value scaling. Default is “lin”.

Returns
valsndarray

Interpolated pixel values.

interp_by_pix(pix, method='linear', fill_value=None, values_scale='lin')[source]#

Interpolate map values at the given pixel coordinates.

Parameters
pixtuple

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. Default is “linear”.

fill_valuefloat, optional

The value to use for points outside the interpolation domain. If None, values outside the domain are extrapolated. Default is None.

Returns
valsndarray

Interpolated pixel values.

interp_to_geom(geom, preserve_counts=False, fill_value=0, **kwargs)#

Interpolate map to input geometry.

Parameters
geomGeom

Target Map geometry.

preserve_countsbool, optional

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). Default is False.

fill_valuefloat, optional

The value to use for points outside the interpolation domain. Default is 0.

**kwargsdict, optional

Keyword arguments passed to Map.interp_by_coord.

Returns
interp_mapMap

Interpolated Map.

is_allclose(other, rtol_axes=0.001, atol_axes=1e-06, **kwargs)#

Compare two Maps for close equivalency.

Parameters
othergammapy.maps.Map

The Map to compare against.

rtol_axesfloat, optional

Relative tolerance for the axes’ comparison. Default is 1e-3.

atol_axesfloat, optional

Absolute tolerance for the axes’ comparison. Default is 1e-6.

**kwargsdict, optional

Keywords passed to allclose.

Returns
is_allclosebool

Whether the Map is all close.

iter_by_axis(axis_name, keepdims=False)#

Iterate over a given axis.

Yields
mapMap

Map iteration.

See also

iter_by_image

iterate by image returning a map.

iter_by_image(keepdims=False)#

Iterate over image planes of a map.

Parameters
keepdimsbool, optional

Keep dimensions. Default is False.

Yields
mapMap

Map iteration.

See also

iter_by_image_data

iterate by image returning data and index.

iter_by_image_data()#

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.

iter_by_image_index()#

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
idxtuple

idx is a tuple of int, the index of the image plane.

See also

iter_by_image

iterate by image returning a map.

mask_contains_region(region)[source]#

Check if input region is contained in a boolean mask map.

Parameters
region: `~regions.SkyRegion` or `~regions.PixRegion`

Region or list of Regions (pixel or sky regions accepted).

Returns
containedbool

Whether region is contained in the mask.

mask_nearest_position(position)#

Given a sky coordinate return nearest valid position in the mask.

If the mask contains additional axes, the mask is reduced over those axes.

Parameters
positionSkyCoord

Test position.

Returns
positionSkyCoord

The nearest position in the mask.

normalize(axis_name=None)#

Normalise data in place along a given axis.

Parameters
axis_namestr, optional

Along which axis to normalise.

pad(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_namestr, optional

Which axis to downsample. By default, spatial axes are padded. Default is None.

mode{‘constant’, ‘edge’, ‘interp’}

Padding mode. ‘edge’ pads with the closest edge value. ‘constant’ pads with a constant value. ‘interp’ pads with an extrapolated value. Default is ‘constant’.

cvalfloat, optional

Padding value when `mode`=’consant’. Default is 0.

Returns
mapMap

Padded map.

plot(ax=None, fig=None, add_cbar=False, stretch='linear', axes_loc=None, kwargs_colorbar=None, **kwargs)[source]#

Plot image on matplotlib WCS axes.

Parameters
axWCSAxes, optional

WCS axis object to plot on. Default is None.

figFigure, optional

Figure object. Default is None.

add_cbarbool, optional

Add color bar. Default is False.

stretchstr, optional
Passed to astropy.visualization.simple_norm.

Default is “linear”.

axes_locdict, optional

Keyword arguments passed to append_axes.

kwargs_colorbardict, optional

Keyword arguments passed to colorbar.

**kwargsdict

Keyword arguments passed to imshow.

Returns
axWCSAxes

WCS axes object.

plot_grid(figsize=None, ncols=3, **kwargs)#

Plot map as a grid of subplots for non-spatial axes.

Parameters
figsizetuple of int, optional

Figsize to plot on. Default is None.

ncolsint, optional

Number of columns to plot. Default is 3.

**kwargsdict, optional

Keyword arguments passed to WcsNDMap.plot.

Returns
axesndarray of Axes

Axes grid.

plot_interactive(rc_params=None, **kwargs)#

Plot map with interactive widgets to explore the non-spatial axes.

Parameters
rc_paramsdict, optional

Passed to matplotlib.rc_context(rc=rc_params) to style the plot. Default is None.

**kwargsdict, optional

Keyword arguments passed to WcsNDMap.plot.

Examples

You can try this out e.g. using a Fermi-LAT diffuse model cube with an energy axis:

from gammapy.maps import Map

m = Map.read("$GAMMAPY_DATA/fermi_3fhl/gll_iem_v06_cutout.fits")
m.plot_interactive(add_cbar=True, stretch="sqrt")

If you would like to adjust the figure size you can use the rc_params argument:

rc_params = {'figure.figsize': (12, 6), 'font.size': 12}
m.plot_interactive(rc_params=rc_params)
plot_mask(ax=None, **kwargs)[source]#

Plot the mask as a shaded area.

Parameters
axWCSAxes, optional

WCS axis object to plot on. Default is None.

**kwargsdict

Keyword arguments passed to contourf.

Returns
axWCSAxes, optional

WCS axis object to plot on.

static read(filename, hdu=None, hdu_bands=None, map_type='auto', format=None, colname=None, checksum=False)#

Read a map from a FITS file.

Parameters
filenamestr or Path

Name of the FITS file.

hdustr, optional

Name or index of the HDU with the map data. Default is None.

hdu_bandsstr, optional

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. Default is None.

map_type{‘auto’, ‘wcs’, ‘wcs-sparse’, ‘hpx’, ‘hpx-sparse’, ‘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. Default is ‘auto’.

colnamestr, optional

data column name to be used for HEALPix map.

checksumbool

If True checks both DATASUM and CHECKSUM cards in the file headers. Default is False.

Returns
map_outMap

Map object.

reduce(axis_name, func=<ufunc 'add'>, keepdims=False, weights=None)#

Reduce map over a single non-spatial axis.

Parameters
axis_name: str

The name of the axis to reduce over.

funcufunc, optional

Function to use for reducing the data. Default is numpy.add.

keepdimsbool, optional

If this is set to true, the axes which are summed over are left in the map with a single bin. Default is False.

weightsMap

Weights to be applied. The map should have the same geometry as this one. Default is None.

Returns
map_outMap

Map with the given non-spatial axes reduced.

reduce_over_axes(func=<ufunc 'add'>, keepdims=False, axes_names=None, weights=None)#

Reduce map over non-spatial axes.

Parameters
funcufunc, optional

Function to use for reducing the data. Default is numpy.add.

keepdimsbool, optional

If this is set to true, the axes which are summed over are left in the map with a single bin. Default is False.

axes_names: list, optional

Names of axis to reduce over. If None, all non-spatial axis will be reduced.

weightsMap, optional

Weights to be applied. The map should have the same geometry as this one. Default is None.

Returns
map_outMap

Map with non-spatial axes reduced.

rename_axes(names, new_names)#

Rename the Map axes.

Parameters
namesstr or list of str

Names of the axes.

new_namesstr or list of str

New names of the axes. The list must be of the same length as names).

Returns
geomMap

Map with renamed axes.

reorder_axes(axes_names)#

Return a new map re-ordering the non-spatial axes.

Parameters
axes_nameslist of str

The list of axes names in the required order.

Returns
mapMap

The map with axes re-ordered.

reproject_by_image(geom, preserve_counts=False, precision_factor=10)#

Reproject each image of a ND map to input 2d geometry.

For large maps this method is faster than reproject_to_geom.

Parameters
geomGeom

Target slice geometry in 2D.

preserve_countsbool, optional

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). Default is False.

precision_factorint, optional

Minimal factor between the bin size of the output map and the oversampled base map. Used only for the oversampling method. Default is 10.

Returns
output_mapMap

Reprojected Map.

reproject_to_geom(geom, preserve_counts=False, precision_factor=10)#

Reproject map to input geometry.

Parameters
geomGeom

Target Map geometry.

preserve_countsbool, optional

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). Default is False.

precision_factorint, optional

Minimal factor between the bin size of the output map and the oversampled base map. Used only for the oversampling method. Default is 10.

Returns
output_mapMap

Reprojected Map.

resample(geom, weights=None, preserve_counts=True)#

Resample pixels to geom with given weights.

Parameters
geomGeom

Target Map geometry.

weightsndarray, optional

Weights vector. It must have same shape as the data of the map. If set to None, weights will be set to 1. Default is None.

preserve_countsbool, optional

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). Default is True.

Returns
resampled_mapMap

Resampled map.

resample_axis(axis, weights=None, ufunc=<ufunc 'add'>)#

Resample map to a new axis by grouping and reducing smaller bins by a given function 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
axisMapAxis

New map axis.

weightsMap, optional

Array to be used as weights. The spatial geometry must be equivalent to other and additional axes must be broadcastable. If set to None, weights will be set to 1. Default is None.

ufuncufunc

Universal function to use to resample the axis. Default is numpy.add.

Returns
mapMap

Map with resampled axis.

sample_coord(n_events, random_state=0)#

Sample position and energy of events.

Parameters
n_eventsint

Number of events to sample.

random_state{int, ‘random-seed’, ‘global-rng’, RandomState}

Defines random number generator initialisation. Passed to get_random_state. Default is 0.

Returns
coordsMapCoord object.

Sequence of coordinates and energies of the sampled events.

set_by_coord(coords, vals)#

Set pixels at coords with given vals.

Parameters
coordstuple or 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.

valsndarray

Values vector.

set_by_idx(idx, vals)[source]#

Set pixels at idx with given vals.

Parameters
idxtuple

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.

valsndarray

Values vector.

set_by_pix(pix, vals)#

Set pixels at pix with given vals.

Parameters
pixtuple

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. Float indices will be rounded to the nearest integer.

valsndarray

Values vector.

slice_by_idx(slices)#

Slice sub map from map object.

Parameters
slicesdict

Dictionary 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 dictionary are kept unchanged.

Returns
map_outMap

Sliced map object.

smooth(width, kernel='gauss', **kwargs)[source]#

Smooth the map.

Iterates over 2D image planes, processing one at a time.

Parameters
widthQuantity, str or float

Smoothing width given as quantity or float. If a float is given it interpreted as smoothing width in pixels. If an (angular) quantity is given it converted to pixels using geom.wcs.wcs.cdelt. It corresponds to the standard deviation in case of a Gaussian kernel, the radius in case of a disk kernel, and the side length in case of a box kernel.

kernel{‘gauss’, ‘disk’, ‘box’}, optional

Kernel shape. Default is “gauss”.

kwargsdict

Keyword arguments passed to uniform_filter (‘box’), gaussian_filter (‘gauss’) or convolve (‘disk’).

Returns
imageWcsNDMap

Smoothed image (a copy, the original object is unchanged).

split_by_axis(axis_name)#

Split a Map along an axis into multiple maps.

Parameters
axis_namestr

Name of the axis to split.

Returns
mapslist

A list of Map.

stack(other, weights=None, nan_to_num=True)[source]#

Stack cutout into map.

Parameters
otherWcsNDMap

Other map to stack.

weightsWcsNDMap, optional

Array to be used as weights. The spatial geometry must be equivalent to other and additional axes must be broadcastable. Default is None.

nan_to_num: bool, optional

Non-finite values are replaced by zero if True. Default is True.

sum_over_axes(axes_names=None, keepdims=True, weights=None)#

Sum map values over all non-spatial axes.

Parameters
axes_names: list of str

Names of the axis to reduce over. If None, all non-spatial axis will be summed over. Default is None.

keepdimsbool, optional

If this is set to true, the axes which are summed over are left in the map with a single bin. Default is True.

weightsMap, optional

Weights to be applied. The map should have the same geometry as this one. Default is None.

Returns
map_outMap

Map with non-spatial axes summed over.

to_cube(axes)#

Append non-spatial axes to create a higher-dimensional Map.

This will result in a Map with a new geometry with N+M dimensions where N is the number of current dimensions and M is the number of axes in the list. The data is reshaped onto this new geometry.

Parameters
axeslist

Axes that will be appended to this Map. The axes should have only one bin.

Returns
mapWcsNDMap

New map.

to_hdu(hdu='SKYMAP', hdu_bands=None, sparse=False)#

Make a FITS HDU from this map.

Parameters
hdustr, optional

The HDU extension name. Default is “SKYMAP”.

hdu_bandsstr, optional

The HDU extension name for BANDS table. Default is None.

sparsebool, optional

Set INDXSCHM to SPARSE and sparsify the map by only writing pixels with non-zero amplitude. Default is False.

Returns
hduBinTableHDU or ImageHDU

HDU containing the map data.

to_hdulist(hdu=None, hdu_bands=None, sparse=False, format='gadf')#

Convert to HDUList.

Parameters
hdustr, optional

Name or index of the HDU with the map data. Default is None.

hdu_bandsstr, optional

Name or index of the HDU with the BANDS table. Default is None.

sparsebool, optional

Sparsify the map by only writing pixels with non-zero amplitude. Default is False.

format{‘gadf’, ‘fgst-ccube’,’fgst-template’}, optional

FITS format convention. Default is “gadf”.

Returns
hdu_listHDUList

HDU list.

to_region_nd_map(region=None, func=<function nansum>, weights=None, method='nearest')[source]#

Get region ND map in a given region.

By default, the whole map region is considered.

Parameters
region: `~regions.Region` or `~astropy.coordinates.SkyCoord`, optional

Region. Default is None.

funcnumpy.func, optional

Function to reduce the data. Default is np.nansum. For boolean Map, use np.any or np.all.

weightsWcsNDMap, optional

Array to be used as weights. The geometry must be equivalent. Default is None.

method{“nearest”, “linear”}, optional

How to interpolate if a position is given. Default is “nearest”.

Returns
spectrumRegionNDMap

Spectrum in the given region.

to_region_nd_map_histogram(region=None, bins_axis=None, nbin=100, density=False)[source]#

Convert map into region map by histogramming.

By default, it creates a linearly spaced axis with 100 bins between (-max(abs(data)), max(abs(data))) within the given region.

Parameters
region: `~regions.Region`, optional

Region to histogram over. Default is None.

bins_axisMapAxis, optional

Binning of the histogram. Default is None.

nbinint, optional

Number of bins to use if no bins_axis is given. Default is 100.

densitybool, optional

Normalize integral of the histogram to 1. Default is False.

Returns
region_mapRegionNDMap

Region map with histogram.

Examples

This is how to use the method to create energy dependent histograms:

from gammapy.maps import MapAxis, Map
import numpy as np

random_state = np.random.RandomState(seed=0)

energy_axis = MapAxis.from_energy_bounds("1 TeV", "10 TeV", nbin=3)

data = Map.create(axes=[energy_axis], width=10, unit="cm2 s-1", binsz=0.02)
data.data = random_state.normal(
    size=data.data.shape, loc=0, scale=np.array([1.0, 2.0, 3.0]).reshape((-1, 1, 1))
)

hist = data.to_region_nd_map_histogram()
hist.plot(axis_name="bins")
to_unit(unit)#

Convert map to a different unit.

Parameters
unitstr or Unit

New unit.

Returns
mapMap

Map with new unit and converted data.

upsample(factor, order=0, preserve_counts=True, axis_name=None)[source]#

Upsample the spatial dimension by a given factor.

Parameters
factorint

Upsampling factor.

orderint, optional

Order of the interpolation used for upsampling. Default is 0.

preserve_countsbool, optional

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). Default is True.

axis_namestr, optional

Which axis to upsample. By default, spatial axes are upsampled. Default is None.

Returns
mapMap

Upsampled map.

write(filename, overwrite=False, **kwargs)#

Write to a FITS file.

Parameters
filenamestr

Output file name.

overwritebool, optional

Overwrite existing file. Default is False.

hdustr, optional

Set the name of the image extension. By default, this will be set to ‘SKYMAP’ (for BINTABLE HDU) or ‘PRIMARY’ (for IMAGE HDU).

hdu_bandsstr, optional

Set the name of the bands table extension. Default is ‘BANDS’.

formatstr, 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”

sparsebool, optional

Sparsify the map by dropping pixels with zero amplitude. This option is only compatible with the ‘gadf’ format.

checksumbool, optional

When True adds both DATASUM and CHECKSUM cards to the headers written to the file. Default is False.