HpxGeom#

class gammapy.maps.HpxGeom(nside, nest=True, frame='icrs', region=None, axes=None)[source]#

Bases: gammapy.maps.geom.Geom

Geometry class for HEALPix maps.

This class performs mapping between partial-sky indices (pixel number within a HEALPix region) and all-sky indices (pixel number within an all-sky HEALPix map). Multi-band HEALPix geometries use a global indexing scheme that assigns a unique pixel number based on the all-sky index and band index. In the single-band case the global index is the same as the HEALPix index.

By default, the constructor will return an all-sky map. Partial-sky maps can be defined with the region argument.

Parameters
nsidendarray

HEALPix NSIDE parameter, the total number of pixels is 12*nside*nside. For multi-dimensional maps one can pass either a single nside value or a vector of nside values defining the pixel size for each image plane. If nside is not a scalar then its dimensionality should match that of the non-spatial axes. If nest is True, nside must be a power of 2, less than 2**30.

nestbool

Indexing scheme. If True, “NESTED” scheme. If False, “RING” scheme.

frame{“icrs”, “galactic”}

Coordinate system. Default is “icrs”.

regionstr or tuple

Spatial geometry for partial-sky maps. If None, the map will encompass the whole sky. String input will be parsed according to HPX_REG header keyword conventions. Tuple input can be used to define an explicit list of pixels encompassed by the geometry.

axeslist

Axes for non-spatial dimensions.

Attributes Summary

as_energy_true

If the geom contains an axis named 'energy' rename it to 'energy_true'.

axes

List of non-spatial axes.

axes_names

All axes names.

center_coord

Map coordinates of the center of the geometry as a tuple.

center_pix

Pixel coordinates of the center of the geometry as a tuple.

center_skydir

Sky coordinate of the center of the geometry.

data_shape

Shape of the ndarray matching this geometry.

data_shape_axes

Shape of data of the non-spatial axes and unit spatial axes.

frame

has_energy_axis

Whether geom has an energy axis (either 'energy' or 'energy_true').

ipix

HEALPix pixel and band indices for every pixel in the map.

is_allsky

Flag for all-sky maps.

is_flat

Whether the geom non-spatial axes have length 1, equivalent to an image.

is_hpx

is_image

Whether the geom is an image without extra dimensions.

is_region

is_regular

Flag identifying whether this geometry is regular in non-spatial dimensions.

ndim

Number of dimensions as an integer.

nest

Whether HEALPix order is nested as a boolean.

npix

Number of pixels in each band.

npix_max

Maximum number of pixels.

nside

NSIDE in each band.

order

The order in each band (NSIDE = 2 ** ORDER).

ordering

HEALPix ordering ('NESTED' or 'RING').

pixel_scales

projection

Map projection.

region

Region string.

shape_axes

Shape of non-spatial axes.

width

Width of the map.

Methods Summary

contains(coords)

Check if a given map coordinate is contained in the geometry.

contains_pix(pix)

Check if a given pixel coordinate is contained in the geometry.

coord_to_idx(coords[, clip])

Convert map coordinates to pixel indices.

coord_to_pix(coords)

Convert map coordinates to pixel coordinates.

copy(**kwargs)

Copy and overwrite given attributes.

create([nside, binsz, nest, frame, region, ...])

Create an HpxGeom object.

crop(crop_width)

Crop the geometry at the edges.

cutout(position, width, **kwargs)

Create a cutout around a given position.

data_nbytes([dtype])

Estimate memory usage in megabytes of the Numpy data array matching this geometry depending on the given type.

downsample(factor[, axis_name])

Downsample the spatial dimension of the geometry by a given factor.

drop(axis_name)

Drop an axis from the geom.

energy_mask([energy_min, energy_max, ...])

Create a mask for a given energy range.

from_hdu(hdu[, hdu_bands])

Create an HPX object from a BinTable HDU.

from_hdulist(hdulist[, hdu, hdu_bands])

Load a geometry object from a FITS HDUList.

from_header(header[, hdu_bands, format])

Create an HPX object from a FITS header.

get_coord([idx, flat, sparse, mode, axis_name])

Get the coordinate array for this geometry.

get_idx([idx, local, flat, sparse, mode, ...])

Get tuple of pixel indices for this geometry.

get_index_list(nside, nest, region)

Get list of pixels indices for all the pixels in a region.

global_to_local(idx_global[, ravel])

Compute global (all-sky) index from a local (partial-sky) index.

interp_weights(coords[, idxs])

Get interpolation weights for given coordinates.

is_aligned(other)

Check if HEALPix geoms and extra axes are aligned.

is_allclose(other[, rtol_axes, atol_axes])

Compare two data IRFs for equivalency.

local_to_global(idx_local)

Compute a global index (all-sky) from a local (partial-sky) index.

pad(pad_width, axis_name)

Pad the geometry at the edges.

pix_to_coord(pix)

Convert pixel coordinates to map coordinates.

pix_to_idx(pix[, clip])

Convert pixel coordinates to pixel indices.

region_mask(regions)

Create a mask from a given list of regions.

rename_axes(names, new_names)

Rename axes contained in the geometry.

replace_axis(axis)

Replace axis with a new one.

resample_axis(axis)

Resample geom to a new axis binning.

separation(center)

Compute sky separation with respect to a given center.

slice_by_idx(slices)

Create a new geometry by slicing the non-spatial axes.

solid_angle()

Solid angle array as a Quantity in sr.

squash(axis_name)

Squash geom axis.

to_bands_hdu([hdu_bands, format])

to_binsz(binsz)

Change pixel size of the geometry.

to_cube(axes)

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

to_header([format])

Build and return FITS header for this HEALPix map.

to_image()

Create a 2D image geometry (drop non-spatial dimensions).

to_nside(nside)

Upgrade or downgrade the resolution to a given NSIDE.

to_swapped()

Geometry copy with swapped ORDERING (NEST->RING or vice versa).

to_wcs_geom([proj, oversample, width_pix])

Make a WCS projection appropriate for this HEALPix pixelization.

to_wcs_tiles([nside_tiles, margin])

Create WCS tiles geometries from HPX geometry with given nside.

upsample(factor)

Upsample the spatial dimension of the geometry by a given factor.

Attributes Documentation

as_energy_true#

If the geom contains an axis named ‘energy’ rename it to ‘energy_true’.

axes#

List of non-spatial axes.

axes_names#

All axes names.

center_coord#

Map coordinates of the center of the geometry as a tuple.

center_pix#

Pixel coordinates of the center of the geometry as a tuple.

center_skydir#

Sky coordinate of the center of the geometry.

Returns
centerSkyCoord

Center position.

data_shape#

Shape of the ndarray matching this geometry.

data_shape_axes#

Shape of data of the non-spatial axes and unit spatial axes.

frame#
has_energy_axis#

Whether geom has an energy axis (either ‘energy’ or ‘energy_true’).

ipix#

HEALPix pixel and band indices for every pixel in the map.

is_allsky#

Flag for all-sky maps.

is_flat#

Whether the geom non-spatial axes have length 1, equivalent to an image.

is_hpx = True#
is_image#

Whether the geom is an image without extra dimensions.

is_region = False#
is_regular#

Flag identifying whether this geometry is regular in non-spatial dimensions.

False for multi-resolution or irregular geometries. If True, all image planes have the same pixel geometry.

ndim#

Number of dimensions as an integer.

nest#

Whether HEALPix order is nested as a boolean.

npix#

Number of pixels in each band.

For partial-sky geometries this can be less than the number of pixels for the band NSIDE.

npix_max#

Maximum number of pixels.

nside#

NSIDE in each band.

order#

The order in each band (NSIDE = 2 ** ORDER).

Set to -1 for bands with NSIDE that is not a power of 2.

ordering#

HEALPix ordering (‘NESTED’ or ‘RING’).

pixel_scales#
projection#

Map projection.

region#

Region string.

shape_axes#

Shape of non-spatial axes.

width#

Width of the map.

Methods Documentation

contains(coords)[source]#

Check if a given map coordinate is contained in the geometry.

Parameters
coordstuple or MapCoord

Tuple of map coordinates.

Returns
containmentndarray

Bool array.

contains_pix(pix)#

Check if a given pixel coordinate is contained in the geometry.

Parameters
pixtuple

Tuple of pixel coordinates.

Returns
containmentndarray

Bool array.

coord_to_idx(coords, clip=False)#

Convert map coordinates to pixel indices.

Parameters
coordstuple or MapCoord

Coordinate values in each dimension of the map. This can either be a tuple of numpy arrays or a MapCoord object. If passed as a tuple then the ordering should be (longitude, latitude, c_0, …, c_N) where c_i is the coordinate vector for axis i.

clipbool

Choose whether to clip indices to the valid range of the geometry. If False then indices for coordinates outside the geometry range will be set -1. Default is False.

Returns
pixtuple

Tuple of pixel indices in image and band dimensions. Elements set to -1 correspond to coordinates outside the map.

coord_to_pix(coords)[source]#

Convert map coordinates to pixel coordinates.

Parameters
coordstuple

Coordinate values in each dimension of the map. This can either be a tuple of numpy arrays or a MapCoord object. If passed as a tuple then the ordering should be (longitude, latitude, c_0, …, c_N) where c_i is the coordinate vector for axis i.

Returns
pixtuple

Tuple of pixel coordinates in image and band dimensions.

copy(**kwargs)#

Copy and overwrite given attributes.

Parameters
**kwargsdict

Keyword arguments to overwrite in the map geometry constructor.

Returns
copyGeom

Copied map geometry.

classmethod create(nside=None, binsz=None, nest=True, frame='icrs', region=None, axes=None, skydir=None, width=None)[source]#

Create an HpxGeom object.

Parameters
nsideint or ndarray, optional

HEALPix NSIDE parameter. This parameter sets the size of the spatial pixels in the map. If nest is True, nside must be a power of 2, less than 2**30. Default is None.

binszfloat or ndarray, optional

Approximate pixel size in degrees. An nside will be chosen that corresponds to a pixel size closest to this value. This option is superseded by nside. Default is None.

nestbool, optional

Indexing scheme. If True, “NESTED” scheme. If False, “RING” scheme. Default is True.

frame{“icrs”, “galactic”}

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

regionstr, optional

HEALPix region string. Allows for partial-sky maps. Default is None.

axeslist, optional

List of axes for non-spatial dimensions. 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 deg in the coordinate system of the map. Default is None.

widthfloat, optional

Diameter of the map in degrees. If set the map will encompass all pixels within a circular region centered on skydir. Default is None.

Returns
geomHpxGeom

A HEALPix geometry object.

Examples

>>> from gammapy.maps import HpxGeom, MapAxis
>>> axis = MapAxis.from_bounds(0,1,2)
>>> geom = HpxGeom.create(nside=16) 
>>> geom = HpxGeom.create(binsz=0.1, width=10.0) 
>>> geom = HpxGeom.create(nside=64, width=10.0, axes=[axis]) 
>>> geom = HpxGeom.create(nside=[32,64], width=10.0, axes=[axis]) 
crop(crop_width)[source]#

Crop the geometry at the edges.

Parameters
crop_width{sequence, array_like, int}

Number of values cropped from the edges of each axis.

Returns
geomGeom

Cropped geometry.

cutout(position, width, **kwargs)[source]#

Create a cutout around a given position.

Parameters
positionSkyCoord

Center position of the cutout region.

widthAngle or Quantity

Diameter of the circular cutout region.

Returns
cutoutWcsNDMap

Cutout map.

data_nbytes(dtype='float32')#

Estimate memory usage in megabytes of the Numpy data array matching this geometry depending on the given type.

Parameters
dtypestr, optional

The desired data-type for the array. Default is “float32”.

Returns
memoryQuantity

Estimated memory usage in megabytes (MB).

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

Downsample the spatial dimension of the geometry by a given factor.

Parameters
factorint

Downsampling factor.

axis_namestr

Axis to downsample.

Returns
geomGeom

Downsampled geometry.

drop(axis_name)#

Drop an axis from the geom.

Parameters
axis_namestr

Name of the axis to remove.

Returns
geomGeom

New geom with the axis removed.

energy_mask(energy_min=None, energy_max=None, round_to_edge=False)#

Create a mask for a given energy range.

The energy bin must be fully contained to be included in the mask.

Parameters
energy_min, energy_maxQuantity

Energy range.

Returns
maskMap

Map containing the energy mask. The geometry of the map is the same as the geometry of the instance which called this method.

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

Create an HPX object from a BinTable HDU.

Parameters
hduBinTableHDU

The FITS HDU.

hdu_bandsBinTableHDU, optional

The BANDS table HDU. Default is None.

Returns
hpxHpxGeom

HEALPix geometry.

classmethod from_hdulist(hdulist, hdu=None, hdu_bands=None)#

Load a geometry object from a FITS HDUList.

Parameters
hdulistHDUList

HDU list containing HDUs for map data and bands.

hdustr or int, 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.

Returns
geomGeom

Geometry object.

classmethod from_header(header, hdu_bands=None, format=None)[source]#

Create an HPX object from a FITS header.

Parameters
headerHeader

The FITS header.

hdu_bandsBinTableHDU, optional

The BANDS table HDU. Default is None.

formatstr, optional

FITS convention. Default is None. If None the format is guessed. The following formats are supported:

  • “gadf”

  • “fgst-ccube”

  • “fgst-ltcube”

  • “fgst-bexpcube”

  • “fgst-srcmap”

  • “fgst-template”

  • “fgst-srcmap-sparse”

  • “galprop”

  • “galprop2”

  • “healpy”

Returns
hpxHpxGeom

HEALPix geometry.

get_coord(idx=None, flat=False, sparse=False, mode='center', axis_name=None)[source]#

Get the coordinate array for this geometry.

Returns a coordinate array with the same shape as the data array. Pixels outside the geometry are set to NaN. Coordinates for a single image plane can be accessed by setting idx to the index tuple of a plane.

Parameters
idxtuple, optional

A tuple of indices with one index for each non-spatial dimension. If defined only coordinates for the image plane with this index will be returned. If none then coordinates for all pixels will be returned. Default is None.

flatbool, optional

Return a flattened array containing only coordinates for pixels contained in the geometry. Default is False.

Returns
coordstuple

Tuple of coordinate vectors with one vector for each dimension.

get_idx(idx=None, local=False, flat=False, sparse=False, mode='center', axis_name=None)[source]#

Get tuple of pixel indices for this geometry.

Returns all pixels in the geometry by default. Pixel indices for a single image plane can be accessed by setting idx to the index tuple of a plane.

Parameters
idxtuple, optional

A tuple of indices with one index for each non-spatial dimension. If defined only pixels for the image plane with this index will be returned. If none then all pixels will be returned. Default is None.

localbool, optional

Flag to return local or global pixel indices. Local indices run from 0 to the number of pixels in a given image plane. Default is False.

flatbool, optional

Return a flattened array containing only indices for pixels contained in the geometry. Default is False.

Returns
idxtuple

Tuple of pixel index vectors with one vector for each dimension.

static get_index_list(nside, nest, region)[source]#

Get list of pixels indices for all the pixels in a region.

Parameters
nsideint

HEALPix NSIDE parameter.

nestbool

Indexing scheme. If True, “NESTED” scheme. If False, “RING” scheme.

regionstr

HEALPix region string.

Returns
ilistndarray

List of pixel indices.

global_to_local(idx_global, ravel=False)[source]#

Compute global (all-sky) index from a local (partial-sky) index.

Parameters
idx_globaltuple

A tuple of pixel indices with global HEALPix pixel indices.

ravelbool, optional

Return a raveled index. Default is False.

Returns
idx_localtuple

A tuple of pixel indices with local HEALPix pixel indices.

interp_weights(coords, idxs=None)[source]#

Get interpolation weights for given coordinates.

Parameters
coordsMapCoord or dict

Input coordinates.

idxsndarray, optional

Indices for non-spatial axes. Default is None.

Returns
weightsndarray

Interpolation weights.

is_aligned(other)[source]#

Check if HEALPix geoms and extra axes are aligned.

Parameters
otherHpxGeom

Other geometry.

Returns
alignedbool

Whether geometries are aligned.

is_allclose(other, rtol_axes=1e-06, atol_axes=1e-06)[source]#

Compare two data IRFs for equivalency.

Parameters
otherHpxGeom

Geometry to compare against.

rtol_axesfloat, optional

Relative tolerance for axes comparison. Default is 1e-6.

atol_axesfloat, optional

Relative tolerance for axes comparison. Default is 1e-6.

Returns
is_allclosebool

Whether the geometry is all close.

local_to_global(idx_local)[source]#

Compute a global index (all-sky) from a local (partial-sky) index.

Parameters
idx_localtuple

A tuple of pixel indices with local HEALPix pixel indices.

Returns
idx_globaltuple

A tuple of pixel index vectors with global HEALPix pixel indices.

pad(pad_width, axis_name)#

Pad the geometry at the edges.

Parameters
pad_width{sequence, array_like, int}

Number of values padded to the edges of each axis.

axis_namestr

Name of the axis to pad.

Returns
geomGeom

Padded geometry.

pix_to_coord(pix)[source]#

Convert pixel coordinates to map coordinates.

Parameters
pixtuple

Tuple of pixel coordinates.

Returns
coordstuple

Tuple of map coordinates.

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

Convert pixel coordinates to pixel indices.

Returns -1 for pixel coordinates that lie outside the map.

Parameters
pixtuple

Tuple of pixel coordinates.

clipbool

Choose whether to clip indices to the valid range of the geometry. If False then indices for coordinates outside the geometry range will be set -1. Default is False.

Returns
idxtuple

Tuple of pixel indices.

region_mask(regions)[source]#

Create a mask from a given list of regions.

The mask is filled such that a pixel inside the region is filled with “True”. To invert the mask, e.g. to create a mask with exclusion regions the tilde (~) operator can be used (see example below).

Parameters
regionsstr, Region or list of Region

Region or list of regions (pixel or sky regions accepted). A region can be defined as a string ind DS9 format as well. See http://ds9.si.edu/doc/ref/region.html for details.

Returns
mask_mapWcsNDMap of boolean type

Boolean region mask.

rename_axes(names, new_names)#

Rename axes contained in the geometry.

Parameters
nameslist or str

Names of the axes.

new_nameslist or str

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

Returns
geomGeom

Renamed geometry.

replace_axis(axis)#

Replace axis with a new one.

Parameters
axisMapAxis

New map axis.

Returns
mapGeom

Geom with replaced axis.

resample_axis(axis)#

Resample geom to a new axis binning.

This method groups the existing bins into a new binning.

Parameters
axisMapAxis

New map axis.

Returns
mapGeom

Geom with resampled axis.

separation(center)[source]#

Compute sky separation with respect to a given center.

Parameters
centerSkyCoord

Center position.

Returns
separationAngle

Separation angle array (1D).

slice_by_idx(slices)#

Create a new geometry by slicing the non-spatial axes.

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

Returns
geomGeom

Sliced geometry.

solid_angle()[source]#

Solid angle array as a Quantity in sr.

The array has the same dimensionality as map.nside as all pixels have the same solid angle.

squash(axis_name)#

Squash geom axis.

Parameters
axis_namestr

Axis to squash.

Returns
geomGeom

Geom with squashed axis.

to_bands_hdu(hdu_bands=None, format='gadf')#
to_binsz(binsz)[source]#

Change pixel size of the geometry.

Parameters
binszfloat or Quantity

New pixel size. A float is assumed to be in degree.

Returns
geomWcsGeom

Geometry with new pixel size.

to_cube(axes)[source]#

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

This will result in 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.

Parameters
axeslist

Axes that will be appended to this geometry.

Returns
geomGeom

Map geometry.

to_header(format='gadf', **kwargs)[source]#

Build and return FITS header for this HEALPix map.

to_image()[source]#

Create a 2D image geometry (drop non-spatial dimensions).

Returns
geomGeom

Image geometry.

to_nside(nside)[source]#

Upgrade or downgrade the resolution to a given NSIDE.

Parameters
nsideint

HEALPix NSIDE parameter.

Returns
geomHpxGeom

A HEALPix geometry object.

to_swapped()[source]#

Geometry copy with swapped ORDERING (NEST->RING or vice versa).

Returns
geomHpxGeom

A HEALPix geometry object.

to_wcs_geom(proj='AIT', oversample=2, width_pix=None)[source]#

Make a WCS projection appropriate for this HEALPix pixelization.

Parameters
projstr, optional

Projection type of WCS geometry. Default is “AIT”.

oversamplefloat, optional

Oversampling factor for WCS map. This will be the approximate ratio of the width of a HEALPix pixel to a WCS pixel. If this parameter is None then the width will be set from width_pix. Default is 2.

width_pixint, optional

Width of the WCS geometry in pixels. The pixel size will be set to the number of pixels satisfying oversample or width_pix whichever is smaller. If this parameter is None then the width will be set from oversample. Default is None.

Returns
wcsWcsGeom

WCS geometry.

to_wcs_tiles(nside_tiles=4, margin='0 deg')[source]#

Create WCS tiles geometries from HPX geometry with given nside.

The HEALPix geom is divide into superpixels defined by nside_tiles, which are then represented by a WCS geometry using a tangential projection. The number of WCS tiles is given by the number of pixels for the given nside_tiles.

Parameters
nside_tilesint, optional

HEALPix NSIDE parameter for super pixel tiles. Default is 4.

marginQuantity, optional

Width margin of the WCS tile. Default is “0 deg”.

Returns
wcs_tileslist

List of WCS tile geometries.

upsample(factor)[source]#

Upsample the spatial dimension of the geometry by a given factor.

Parameters
factorint

Upsampling factor.

axis_namestr

Axis to upsample.

Returns
geomGeom

Upsampled geometry.