SpectrumDatasetOnOff

class gammapy.datasets.SpectrumDatasetOnOff(models=None, counts=None, counts_off=None, acceptance=None, acceptance_off=None, exposure=None, mask_fit=None, psf=None, edisp=None, name=None, mask_safe=None, gti=None, meta_table=None)[source]

Bases: gammapy.datasets.spectrum.PlotMixin, gammapy.datasets.MapDatasetOnOff

Attributes Summary

alpha

Exposure ratio between signal and background regions

background

Computed as alpha * n_off

background_model

counts

A lazy FITS data descriptor.

data_shape

Shape of the counts or background data (tuple)

edisp

A lazy FITS data descriptor.

energy_range

Energy range defined by the safe mask

evaluators

Model evaluators

excess

Excess

exposure

A lazy FITS data descriptor.

geoms

Map geometries

mask

Combined fit and safe mask

mask_fit

A lazy FITS data descriptor.

mask_image

Reduced mask

mask_safe

A lazy FITS data descriptor.

mask_safe_edisp

Mask safe for edisp maps

mask_safe_image

Reduced mask safe

mask_safe_psf

Mask safe for psf maps

models

Models (Models).

name

psf

A lazy FITS data descriptor.

stat_type

tag

Methods Summary

copy([name])

A deep copy.

create(geom[, energy_axis_true, migra_axis, …])

Create a MapDataset object with zero filled maps.

cutout(*args, **kwargs)

Cutout map dataset.

downsample(factor[, axis_name, name])

Downsample map dataset.

fake(npred_background[, random_state])

Simulate fake counts (on and off) for the current model and reduced IRFs.

from_dict(data, **kwargs)

Create flux point dataset from dict.

from_geoms(geom, geom_exposure[, geom_psf, …])

Create a MapDatasetOnOff object swith zero filled maps according to the specified geometries

from_hdulist(*args, **kwargs)

Create map dataset from list of HDUs.

from_map_dataset(dataset, acceptance, …[, …])

Create on off dataset from a map dataset.

from_spectrum_dataset(**kwargs)

Create spectrum dataseton off from another dataset.

info_dict([in_safe_data_range])

Basic info dict with summary statistics

npred()

Predicted source and background counts

npred_background()

Prediced background counts estimated from the marginalized likelihood estimate.

npred_off()

Predicted counts in the off region

npred_signal([model])

“Model predicted signal counts.

pad()

Pad the spatial dimensions of the dataset.

peek([fig])

Quick-look summary plots.

plot_counts([ax, kwargs_counts, …])

Plot counts and background.

plot_excess([ax, kwargs_excess, …])

Plot excess and predicted signal.

plot_fit([ax_spectrum, ax_residuals, …])

Plot spectrum and residuals in two panels.

plot_residuals([ax_spatial, ax_spectral, …])

Plot spatial and spectral residuals in two panels.

plot_residuals_spatial(*args, **kwargs)

Plot spatial residuals.

plot_residuals_spectral([ax, method, region])

Plot spectral residuals.

read(filename)

Read from file

resample_energy_axis(energy_axis[, name])

Resample MapDatasetOnOff over reconstructed energy edges.

reset_data_cache()

Reset data cache to free memory space

residuals([method])

Compute residuals map.

slice_by_energy(energy_min, energy_max[, name])

Select and slice datasets in energy range

slice_by_idx(slices[, name])

Slice sub dataset.

stack(other)

Stack another dataset in place.

stat_array()

Likelihood per bin given the current model parameters

stat_sum()

Total likelihood given the current model parameters.

to_dict()

Convert to dict for YAML serialization.

to_hdulist(*args, **kwargs)

Convert map dataset to list of HDUs.

to_image([name])

Create images by summing over the reconstructed energy axis.

to_map_dataset([name])

Convert a MapDatasetOnOff to MapDataset The background model template is taken as alpha*counts_off

to_masked([name])

Return masked dataset

to_spectrum_dataset([name])

Convert a SpectrumDatasetOnOff to a SpectrumDataset The background model template is taken as alpha*counts_off

write(filename[, overwrite, format])

Write spectrum dataset on off to file.

Attributes Documentation

alpha

Exposure ratio between signal and background regions

See WStat : Poisson data with background measurement

Returns
alphaMap

Alpha map

background

Computed as alpha * n_off

See WStat : Poisson data with background measurement

Returns
backgroundMap

Background map

background_model
counts

A lazy FITS data descriptor.

Parameters
cachebool

Whether to cache the data.

data_shape

Shape of the counts or background data (tuple)

edisp

A lazy FITS data descriptor.

Parameters
cachebool

Whether to cache the data.

energy_range

Energy range defined by the safe mask

evaluators

Model evaluators

excess

Excess

exposure

A lazy FITS data descriptor.

Parameters
cachebool

Whether to cache the data.

geoms

Map geometries

Returns
geomsdict

Dict of map geometries involved in the dataset.

mask

Combined fit and safe mask

mask_fit

A lazy FITS data descriptor.

Parameters
cachebool

Whether to cache the data.

mask_image

Reduced mask

mask_safe

A lazy FITS data descriptor.

Parameters
cachebool

Whether to cache the data.

mask_safe_edisp

Mask safe for edisp maps

mask_safe_image

Reduced mask safe

mask_safe_psf

Mask safe for psf maps

models

Models (Models).

name
psf

A lazy FITS data descriptor.

Parameters
cachebool

Whether to cache the data.

stat_type = 'wstat'
tag = 'SpectrumDatasetOnOff'

Methods Documentation

copy(name=None)

A deep copy.

Parameters
namestr

Name of the copied dataset

Returns
datasetDataset

Copied datasets.

classmethod create(geom, energy_axis_true=None, migra_axis=None, rad_axis=None, binsz_irf=None, reference_time='2000-01-01', name=None, meta_table=None, **kwargs)

Create a MapDataset object with zero filled maps.

Parameters
geomWcsGeom

Reference target geometry in reco energy, used for counts and background maps

energy_axis_trueMapAxis

True energy axis used for IRF maps

migra_axisMapAxis

If set, this provides the migration axis for the energy dispersion map. If not set, an EDispKernelMap is produced instead. Default is None

rad_axisMapAxis

Rad axis for the psf map

binsz_irffloat

IRF Map pixel size in degrees.

reference_timeTime

the reference time to use in GTI definition

namestr

Name of the returned dataset.

meta_tableTable

Table listing informations on observations used to create the dataset. One line per observation for stacked datasets.

Returns
empty_mapsMapDataset

A MapDataset containing zero filled maps

cutout(*args, **kwargs)[source]

Cutout map dataset.

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’}

Mode option for Cutout2D, for details see Cutout2D.

namestr

Name of the new dataset.

Returns
cutoutMapDatasetOnOff

Cutout map dataset.

downsample(factor, axis_name=None, name=None)

Downsample map dataset.

The PSFMap and EDispKernelMap are not downsampled, except if a corresponding axis is given.

Parameters
factorint

Downsampling factor.

axis_namestr

Which non-spatial axis to downsample. By default only spatial axes are downsampled.

namestr

Name of the downsampled dataset.

Returns
datasetMapDatasetOnOff

Downsampled map dataset.

fake(npred_background, random_state='random-seed')

Simulate fake counts (on and off) for the current model and reduced IRFs.

This method overwrites the counts defined on the dataset object.

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

Defines random number generator initialisation. Passed to get_random_state.

classmethod from_dict(data, **kwargs)[source]

Create flux point dataset from dict.

Parameters
datadict

Dict containing data to create dataset from.

Returns
datasetSpectrumDatasetOnOff

Spectrum dataset on off.

classmethod from_geoms(geom, geom_exposure, geom_psf=None, geom_edisp=None, reference_time='2000-01-01', name=None, **kwargs)

Create a MapDatasetOnOff object swith zero filled maps according to the specified geometries

Parameters
geomgammapy.maps.WcsGeom

geometry for the counts, counts_off, acceptance and acceptance_off maps

geom_exposuregammapy.maps.WcsGeom

geometry for the exposure map

geom_psfgammapy.maps.WcsGeom

geometry for the psf map

geom_edispgammapy.maps.WcsGeom

geometry for the energy dispersion kernel map. If geom_edisp has a migra axis, this wil create an EDispMap instead.

reference_timeTime

the reference time to use in GTI definition

namestr

Name of the returned dataset.

Returns
empty_mapsMapDatasetOnOff

A MapDatasetOnOff containing zero filled maps

from_hdulist(*args, **kwargs)[source]

Create map dataset from list of HDUs.

Parameters
hdulistHDUList

List of HDUs.

namestr

Name of the new dataset.

format{“gadf”}

Format the hdulist is given in.

Returns
datasetMapDataset

Map dataset.

classmethod from_map_dataset(dataset, acceptance, acceptance_off, counts_off=None, name=None)

Create on off dataset from a map dataset.

Parameters
datasetMapDataset

Spectrum dataset defining counts, edisp, aeff, livetime etc.

acceptanceMap

Relative background efficiency in the on region.

acceptance_offMap

Relative background efficiency in the off region.

counts_offMap

Off counts map . If the dataset provides a background model, and no off counts are defined. The off counts are deferred from counts_off / alpha.

namestr

Name of the returned dataset.

Returns
datasetMapDatasetOnOff

Map dataset on off.

classmethod from_spectrum_dataset(**kwargs)[source]

Create spectrum dataseton off from another dataset.

Parameters
datasetSpectrumDataset

Spectrum dataset defining counts, edisp, exposure etc.

acceptancearray or float

Relative background efficiency in the on region.

acceptance_offarray or float

Relative background efficiency in the off region.

counts_offRegionNDMap

Off counts spectrum . If the dataset provides a background model, and no off counts are defined. The off counts are deferred from counts_off / alpha.

Returns
datasetSpectrumDatasetOnOff

Spectrum dataset on off.

info_dict(in_safe_data_range=True)

Basic info dict with summary statistics

If a region is passed, then a spectrum dataset is extracted, and the corresponding info returned.

Parameters
in_safe_data_rangebool

Whether to sum only in the safe energy range

Returns
info_dictdict

Dictionary with summary info.

npred()

Predicted source and background counts

Returns
npredMap

Total predicted counts

npred_background()

Prediced background counts estimated from the marginalized likelihood estimate.

See WStat : Poisson data with background measurement

Returns
npred_backgroundMap

Predicted background counts

npred_off()

Predicted counts in the off region

See WStat : Poisson data with background measurement

Returns
npred_offMap

Predicted off counts

npred_signal(model=None)

“Model predicted signal counts.

If a model is passed, predicted counts from that component is returned. Else, the total signal counts are returned.

Parameters
model: `~gammapy.modeling.models.SkyModel`, optional

Sky model to compute the npred for. If none, the sum of all components (minus the background model) is returned

Returns
npred_sig: gammapy.maps.Map

Map of the predicted signal counts

pad()

Pad the spatial dimensions of the dataset.

The padding only applies to counts, masks, background and exposure.

Counts, background and masks are padded with zeros, exposure is padded with edge value.

Parameters
pad_width{sequence, array_like, int}

Number of pixels padded to the edges of each axis.

namestr

Name of the padded dataset.

Returns
datasetMapDataset

Padded map dataset.

peek(fig=None)

Quick-look summary plots.

Parameters
figFigure

Figure to add AxesSubplot on.

Returns
ax1, ax2, ax3AxesSubplot

Counts, effective area and energy dispersion subplots.

plot_counts(ax=None, kwargs_counts=None, kwargs_background=None, **kwargs)

Plot counts and background.

Parameters
axAxes

Axes to plot on.

kwargs_counts: dict

Keyword arguments passed to hist for the counts.

kwargs_background: dict

Keyword arguments passed to hist for the background.

**kwargs: dict

Keyword arguments passed to both hist.

Returns
axAxes

Axes object.

plot_excess(ax=None, kwargs_excess=None, kwargs_npred_signal=None, **kwargs)

Plot excess and predicted signal.

Parameters
axAxes

Axes to plot on.

kwargs_excess: dict

Keyword arguments passed to errorbar for the excess.

kwargs_npred_signaldict

Keyword arguments passed to hist for the predicted signal.

**kwargs: dict

Keyword arguments passed to both plot methods.

Returns
axAxes

Axes object.

plot_fit(ax_spectrum=None, ax_residuals=None, kwargs_spectrum=None, kwargs_residuals=None)

Plot spectrum and residuals in two panels.

Calls plot_excess and plot_residuals.

Parameters
ax_spectrumAxes

Axes to plot spectrum on.

ax_residualsAxes

Axes to plot residuals on.

kwargs_spectrumdict

Keyword arguments passed to plot_excess.

kwargs_residualsdict

Keyword arguments passed to plot_residuals.

Returns
ax_spectrum, ax_residualsAxes

Spectrum and residuals plots.

plot_residuals(ax_spatial=None, ax_spectral=None, kwargs_spatial=None, kwargs_spectral=None)

Plot spatial and spectral residuals in two panels.

Calls plot_residuals_spatial and plot_residuals_spectral. The spectral residuals are extracted from the provided region, and the normalization used for its computation can be controlled using the method parameter. The region outline is overlaid on the residuals map.

Parameters
ax_spatialWCSAxes

Axes to plot spatial residuals on.

ax_spectralAxes

Axes to plot spectral residuals on.

kwargs_spatialdict

Keyword arguments passed to plot_residuals_spatial.

kwargs_spectraldict (region required)

Keyword arguments passed to plot_residuals_spectral.

Returns
ax_spatial, ax_spectralWCSAxes, Axes

Spatial and spectral residuals plots.

plot_residuals_spatial(*args, **kwargs)[source]

Plot spatial residuals.

The normalization used for the residuals computation can be controlled using the method parameter.

Parameters
axWCSAxes

Axes to plot on.

method{“diff”, “diff/model”, “diff/sqrt(model)”}

Normalization used to compute the residuals, see MapDataset.residuals.

smooth_kernel{“gauss”, “box”}

Kernel shape.

smooth_radius: `~astropy.units.Quantity`, str or float

Smoothing width given as quantity or float. If a float is given, it is interpreted as smoothing width in pixels.

**kwargsdict

Keyword arguments passed to imshow.

Returns
axWCSAxes

WCSAxes object.

plot_residuals_spectral(ax=None, method='diff', region=None, **kwargs)

Plot spectral residuals.

The residuals are extracted from the provided region, and the normalization used for its computation can be controlled using the method parameter.

Parameters
axAxes

Axes to plot on.

method{“diff”, “diff/model”, “diff/sqrt(model)”}

Normalization used to compute the residuals, see SpectrumDataset.residuals.

region: `~regions.SkyRegion` (required)

Target sky region.

**kwargsdict

Keyword arguments passed to errorbar.

Returns
axAxes

Axes object.

classmethod read(filename)[source]

Read from file

For now, filename is assumed to the name of a PHA file where BKG file, ARF, and RMF names must be set in the PHA header and be present in the same folder.

For formats specs see OGIPDatasetReader.read

Parameters
filenamePath or str

OGIP PHA file to read

resample_energy_axis(energy_axis, name=None)

Resample MapDatasetOnOff over reconstructed energy edges.

Counts are summed taking into account safe mask.

Parameters
energy_axisMapAxis

New reco energy axis.

name: str

Name of the new dataset.

Returns
dataset: SpectrumDataset

Resampled spectrum dataset .

reset_data_cache()

Reset data cache to free memory space

residuals(method='diff', **kwargs)

Compute residuals map.

Parameters
method: {“diff”, “diff/model”, “diff/sqrt(model)”}
Method used to compute the residuals. Available options are:
  • “diff” (default): data - model

  • “diff/model”: (data - model) / model

  • “diff/sqrt(model)”: (data - model) / sqrt(model)

**kwargsdict

Keyword arguments forwarded to Map.smooth()

Returns
residualsgammapy.maps.Map

Residual map.

slice_by_energy(energy_min, energy_max, name=None)

Select and slice datasets in energy range

Parameters
energy_min, energy_maxQuantity

Energy bounds to compute the flux point for.

namestr

Name of the sliced dataset.

Returns
datasetMapDataset

Sliced Dataset

slice_by_idx(slices, name=None)

Slice sub dataset.

The slicing only applies to the maps that define the corresponding axes.

Parameters
slicesdict

Dict of axes names and integers or slice object pairs. Contains one element for each non-spatial dimension. For integer indexing the corresponding axes is dropped from the map. Axes not specified in the dict are kept unchanged.

namestr

Name of the sliced dataset.

Returns
map_outMap

Sliced map object.

stack(other)

Stack another dataset in place.

The acceptance of the stacked dataset is normalized to 1, and the stacked acceptance_off is scaled so that:

\[\alpha_\text{stacked} = \frac{1}{a_\text{off}} = \frac{\alpha_1\text{OFF}_1 + \alpha_2\text{OFF}_2}{\text{OFF}_1 + OFF_2}\]
Parameters
otherMapDatasetOnOff

Other dataset

stat_array()

Likelihood per bin given the current model parameters

stat_sum()

Total likelihood given the current model parameters.

to_dict()[source]

Convert to dict for YAML serialization.

to_hdulist(*args, **kwargs)[source]

Convert map dataset to list of HDUs.

Returns
hdulistHDUList

Map dataset list of HDUs.

to_image(name=None)

Create images by summing over the reconstructed energy axis.

Parameters
namestr

Name of the new dataset.

Returns
datasetMapDataset or SpectrumDataset

Dataset integrated over non-spatial axes.

to_map_dataset(name=None)

Convert a MapDatasetOnOff to MapDataset The background model template is taken as alpha*counts_off

Parameters
name: str

Name of the new dataset

Returns
dataset: MapDataset

Map dataset with cash statistics

to_masked(name=None)

Return masked dataset

Parameters
namestr

Name of the masked dataset.

Returns
datasetMapDataset or SpectrumDataset

Masked dataset

to_spectrum_dataset(name=None)[source]

Convert a SpectrumDatasetOnOff to a SpectrumDataset The background model template is taken as alpha*counts_off

Parameters
name: str

Name of the new dataset

Returns
dataset: SpectrumDataset

SpectrumDatset with cash statistics

write(filename, overwrite=False, format='ogip')[source]

Write spectrum dataset on off to file.

Currently only the OGIP format is supported

For formats specs see OGIPDatasetWriter

Parameters
filenamePath or str

Filename to write to.

overwritebool

Overwrite existing file.

format{“ogip”, “ogip-sherpa”}

Format to use.