fermipy package

fermipy.config module

class fermipy.config.ConfigManager[source]

Bases: object

classmethod create(configfile)[source]

Create a configuration dictionary from a yaml config file. This function will first populate the dictionary with defaults taken from pre-defined configuration files. The configuration dictionary is then updated with the user-defined configuration file. Any settings defined by the user will take precedence over the default settings.

static load(path)[source]
class fermipy.config.ConfigSchema(options=None, **kwargs)[source]

Bases: object

Class encapsulating a configuration schema.

add_option(name, default_value, helpstr='', otype=None)[source]
add_section(name, section)[source]
create_config(config=None, validate=True, **kwargs)[source]
items()[source]
class fermipy.config.Configurable(config, **kwargs)[source]

Bases: object

The base class provides common facilities like loading and saving configuration state.

config

Return the configuration dictionary of this class.

configdir
configure(config, **kwargs)[source]
classmethod get_config()[source]

Return a default configuration dictionary for this class.

print_config(logger, loglevel=None)[source]
schema

Return the configuration schema of this class.

write_config(outfile)[source]

Write the configuration dictionary to an output file.

fermipy.config.cast_config(config, defaults)[source]
fermipy.config.create_default_config(schema)[source]

Create a configuration dictionary from a schema dictionary. The schema defines the valid configuration keys and their default values. Each element of schema should be a tuple/list containing (default value,docstring,type) or a dict containing a nested schema.

fermipy.config.update_from_schema(cfg, cfgin, schema)[source]

Update configuration dictionary cfg with the contents of cfgin using the schema dictionary to determine the valid input keys.

Parameters:
  • cfg (dict) – Configuration dictionary to be updated.
  • cfgin (dict) – New configuration dictionary that will be merged with cfg.
  • schema (dict) – Configuration schema defining the valid configuration keys and their types.
Returns:

cfgout

Return type:

dict

fermipy.config.validate_config(config, defaults, section=None)[source]
fermipy.config.validate_from_schema(cfg, schema, section=None)[source]
fermipy.config.validate_option(opt_name, opt_val, schema_type)[source]

fermipy.defaults module

fermipy.defaults.make_attrs_class(typename, d)[source]
fermipy.defaults.make_default_dict(d)[source]
fermipy.defaults.make_default_tuple(d)[source]

fermipy.gtanalysis module

fermipy.logger module

class fermipy.logger.Logger[source]

Bases: object

This class provides helper functions which facilitate creating instances of the built-in logger class.

static configure(name, logfile, loglevel=10)[source]

Create a python logger instance and configure it.

Parameters:
  • name (str) – Logger name.
  • logfile (str) – Path to the log file.
  • loglevel (int) – Default log level for STDOUT.
static setup(config=None, logfile=None)[source]

This method sets up the default configuration of the logger. Once this method is called all subsequent instances Logger instances will inherit this configuration.

class fermipy.logger.StreamLogger(name='stdout', logfile=None, quiet=True)[source]

Bases: object

File-like object to log stdout/stderr using the logging module.

close()[source]
flush()[source]
write(msg, level=10)[source]
fermipy.logger.log_level(level)[source]

This is a function that returns a python like level from a HEASOFT like level.

fermipy.roi_model module

class fermipy.roi_model.CompositeSource(name, data)[source]

Bases: fermipy.roi_model.Model

diffuse
nested_sources
write_xml(root)[source]
class fermipy.roi_model.IsoSource(name, data)[source]

Bases: fermipy.roi_model.Model

diffuse
filefunction
write_xml(root, **kwargs)[source]
class fermipy.roi_model.MapCubeSource(name, data)[source]

Bases: fermipy.roi_model.Model

diffuse
mapcube
write_xml(root, **kwargs)[source]
class fermipy.roi_model.Model(name, data)[source]

Bases: object

Base class for point-like and diffuse source components. This class is a container for spectral and spatial parameters as well as other source properties such as TS, Npred, and location within the ROI.

add_name(name)[source]
add_to_table(tab)[source]
assoc
check_cuts(cuts)[source]
static create_from_dict(src_dict, roi_skydir=None, rescale=False)[source]
data
get_catalog_dict()[source]
get_norm()[source]
is_free

returns True if any of the spectral model parameters is set to free, else False

items()[source]
name
names
params
psf_scale_fn
set_name(name, names=None)[source]
set_psf_scale_fn(fn)[source]
set_spectral_pars(spectral_pars)[source]
spatial_pars
spectral_pars
update_data(d)[source]
update_from_source(src)[source]
update_spectral_pars(spectral_pars)[source]
class fermipy.roi_model.ROIModel(config=None, **kwargs)[source]

Bases: fermipy.config.Configurable

This class is responsible for managing the ROI model (both sources and diffuse components). Source catalogs can be read from either FITS or XML files. Individual components are represented by instances of Model and can be accessed by name using the bracket operator.

  • Create an ROI with all 3FGL sources and print a summary of its contents:
>>> skydir = astropy.coordinates.SkyCoord(0.0,0.0,unit='deg')
>>> roi = ROIModel({'catalogs' : ['3FGL'],'src_roiwidth' : 10.0},skydir=skydir)
>>> print(roi)
name                SpatialModel   SpectrumType     offset        ts       npred
--------------------------------------------------------------------------------
3FGL J2357.3-0150   PointSource    PowerLaw          1.956       nan         0.0
3FGL J0006.2+0135   PointSource    PowerLaw          2.232       nan         0.0
3FGL J0016.3-0013   PointSource    PowerLaw          4.084       nan         0.0
3FGL J0014.3-0455   PointSource    PowerLaw          6.085       nan         0.0
  • Print a summary of an individual source
>>> print(roi['3FGL J0006.2+0135'])
Name           : 3FGL J0006.2+0135
Associations   : ['3FGL J0006.2+0135']
RA/DEC         :      1.572/     1.585
GLON/GLAT      :    100.400/   -59.297
TS             : nan
Npred          : nan
Flux           :       nan +/-      nan
EnergyFlux     :       nan +/-      nan
SpatialModel   : PointSource
SpectrumType   : PowerLaw
Spectral Parameters
Index          :         -2 +/-        nan
Scale          :       1000 +/-        nan
Prefactor      :      1e-12 +/-        nan
  • Get the SkyCoord for a source
>>> dir = roi['SourceA'].skydir
  • Loop over all sources and print their names
>>> for s in roi.sources: print(s.name)
3FGL J2357.3-0150
3FGL J0006.2+0135
3FGL J0016.3-0013
3FGL J0014.3-0455
clear()[source]

Clear the contents of the ROI.

copy_source(name)[source]
classmethod create(selection, config, **kwargs)[source]

Create an ROIModel instance.

create_diffuse_srcs(config)[source]
classmethod create_from_position(skydir, config, **kwargs)[source]

Create an ROIModel instance centered on a sky direction.

Parameters:
  • skydir (SkyCoord) – Sky direction on which the ROI will be centered.
  • config (dict) – Model configuration dictionary.
classmethod create_from_roi_data(datafile)[source]

Create an ROI model.

classmethod create_from_source(name, config, **kwargs)[source]

Create an ROI centered on the given source.

create_param_table()[source]
classmethod create_roi_from_ft1(ft1file, config)[source]

Create an ROI model by extracting the sources coordinates form an FT1 file.

create_source(name, src_dict, build_index=True, merge_sources=True, rescale=True)[source]

Add a new source to the ROI model from a dictionary or an existing source object.

Parameters:
  • name (str) –
  • src_dict (dict or Source) –
Returns:

src

Return type:

Source

create_source_table()[source]
create_table(names=None)[source]

Create an astropy Table object with the contents of the ROI model.

defaults = {'assoc_xmatch_columns': (['3FGL_Name'], 'Choose a set of association columns on which to cross-match catalogs.', <class 'list'>), 'catalogs': (None, '', <class 'list'>), 'diffuse': (None, '', <class 'list'>), 'diffuse_dir': (None, '', <class 'list'>), 'diffuse_xml': (None, '', <class 'list'>), 'extdir': (None, 'Set a directory that will be searched for extended source FITS templates. Template files in this directory will take precendence over catalog source templates with the same name.', <class 'str'>), 'extract_diffuse': (False, 'Extract a copy of all mapcube components centered on the ROI.', <class 'bool'>), 'fileio': {'logfile': (None, 'Path to log file. If None then log will be written to fermipy.log.', <class 'str'>), 'outdir': (None, 'Path of the output directory. If none this will default to the directory containing the configuration file.', <class 'str'>), 'outdir_regex': (['\\.fits$|\\.fit$|\\.xml$|\\.npy$|\\.png$|\\.pdf$|\\.yaml$'], 'Stage files to the output directory that match at least one of the regular expressions in this list. This option only takes effect when ``usescratch`` is True.', <class 'list'>), 'savefits': (True, 'Save intermediate FITS files.', <class 'bool'>), 'scratchdir': ('/scratch', 'Path to the scratch directory. If ``usescratch`` is True then a temporary working directory will be created under this directory.', <class 'str'>), 'usescratch': (False, 'Run analysis in a temporary working directory under ``scratchdir``.', <class 'bool'>), 'workdir': (None, 'Path to the working directory.', <class 'str'>), 'workdir_regex': (['\\.fits$|\\.fit$|\\.xml$|\\.npy$'], 'Stage files to the working directory that match at least one of the regular expressions in this list. This option only takes effect when ``usescratch`` is True.', <class 'list'>)}, 'galdiff': (None, 'Set the path to one or more galactic IEM mapcubes. A separate component will be generated for each item in this list.', <class 'list'>), 'isodiff': (None, 'Set the path to one or more isotropic templates. A separate component will be generated for each item in this list.', <class 'list'>), 'limbdiff': (None, '', <class 'list'>), 'merge_sources': (True, 'Merge properties of sources that appear in multiple source catalogs. If merge_sources=false then subsequent sources with the same name will be ignored.', <class 'bool'>), 'sources': (None, '', <class 'list'>), 'src_radius': (None, 'Radius of circular region in degrees centered on the ROI that selects sources for inclusion in the model. If this parameter is none then no selection is applied. This selection is ORed with the ``src_roiwidth`` selection.', <class 'float'>), 'src_radius_roi': (None, 'Half-width of ``src_roiwidth`` selection. This parameter can be used in lieu of ``src_roiwidth``.', <class 'float'>), 'src_roiwidth': (None, 'Width of square region in degrees centered on the ROI that selects sources for inclusion in the model. If this parameter is none then no selection is applied. This selection will be ORed with the ``src_radius`` selection.', <class 'float'>)}
delete_sources(srcs)[source]
diffuse_sources
extdir
geom
get_nearby_sources(name, distance, min_dist=None, square=False)[source]
get_source_by_name(name)[source]

Return a single source in the ROI with the given name. The input name string can match any of the strings in the names property of the source object. Case and whitespace are ignored when matching name strings. If no sources are found or multiple sources then an exception is thrown.

Parameters:name (str) – Name string.
Returns:srcs – A source object.
Return type:Model
get_sources(skydir=None, distance=None, cuts=None, minmax_ts=None, minmax_npred=None, exclude=None, square=False, coordsys='CEL', names=None)[source]

Retrieve list of source objects satisfying the following selections:

  • Angular separation from skydir or ROI center (if
    skydir is None) less than distance.
  • Cuts on source properties defined in cuts list.
  • TS and Npred in range specified by minmax_ts and minmax_npred.
  • Name matching a value in names

Sources can be excluded from the selection by adding their name to the exclude list. exclude can be a str or a list of str.

Returns:srcs – List of source objects.
Return type:list
get_sources_by_name(name)[source]

Return a list of sources in the ROI matching the given name. The input name string can match any of the strings in the names property of the source object. Case and whitespace are ignored when matching name strings.

Parameters:name (str) –
Returns:srcs – A list of Model objects.
Return type:list
get_sources_by_position(skydir, dist, min_dist=None, square=False, coordsys='CEL')[source]

Retrieve sources within a certain angular distance of a sky coordinate. This function supports two types of geometric selections: circular (square=False) and square (square=True). The circular selection finds all sources with a given angular distance of the target position. The square selection finds sources within an ROI-like region of size R x R where R = 2 x dist.

Parameters:
  • skydir (SkyCoord) – Sky direction with respect to which the selection will be applied.
  • dist (float) – Maximum distance in degrees from the sky coordinate.
  • square (bool) – Choose whether to apply a circular or square selection.
  • coordsys (str) – Coordinate system to use when applying a selection with square=True.
get_sources_by_property(pname, pmin, pmax=None)[source]
has_source(name)[source]
load(**kwargs)[source]

Load both point source and diffuse components.

load_diffuse_srcs()[source]
load_existing_catalog(cat, **kwargs)[source]

Load sources from an existing catalog object.

Parameters:cat (Catalog) – Catalog object.
load_fits_catalog(name, **kwargs)[source]

Load sources from a FITS catalog file.

Parameters:name (str) – Catalog name or path to a catalog FITS file.
load_source(src, build_index=True, merge_sources=True, **kwargs)[source]

Load a single source.

Parameters:
  • src (Source) – Source object that will be added to the ROI.
  • merge_sources (bool) – When a source matches an existing source in the model update that source with the properties of the new source.
  • build_index (bool) – Re-make the source index after loading this source.
load_sources(sources)[source]

Delete all sources in the ROI and load the input source list.

load_xml(xmlfile, **kwargs)[source]

Load sources from an XML file.

match_source(src)[source]

Look for source or sources in the model that match the given source. Sources are matched by name and any association columns defined in the assoc_xmatch_columns parameter.

point_sources
set_geom(geom)[source]
skydir

Return the sky direction corresponding to the center of the ROI.

sources
src_name_cols = ['Source_Name', 'ASSOC', 'ASSOC1', 'ASSOC2', 'ASSOC_GAM', '1FHL_Name', '2FGL_Name', '3FGL_Name', 'ASSOC_GAM1', 'ASSOC_GAM2', 'ASSOC_TEV']
to_ds9(free='box', fixed='cross', frame='fk5', color='green', header=True)[source]

Returns a list of ds9 region definitions :param free: one of the supported ds9 point symbols, used for free sources, see here: http://ds9.si.edu/doc/ref/region.html :type free: bool :param fixed: as free but for fixed sources :type fixed: bool :param frame: typically fk5, more to be implemented :type frame: str :param color: color used for symbols (only ds9 compatible colors) :type color: str :param header: if True, will prepend a global header line. :type header: bool

Returns:lines – list of regions (and header if requested)
Return type:list
write_ds9region(region, *args, **kwargs)[source]

Create a ds9 compatible region file from the ROI.

It calls the to_ds9 method and write the result to the region file. Only the file name is required. All other parameters will be forwarded to the to_ds9 method, see the documentation of that method for all accepted parameters and options. :param region: name of the region file (string) :type region: str

write_fits(fitsfile)[source]

Write the ROI model to a FITS file.

write_xml(xmlfile, config=None)[source]

Save the ROI model as an XML file.

class fermipy.roi_model.Source(name, data, radec=None)[source]

Bases: fermipy.roi_model.Model

Class representation of a source (non-diffuse) model component. A source object serves as a container for the properties of that source (position, spatial/spectral parameters, TS, etc.) as derived in the current analysis. Most properties of a source object can be accessed with the bracket operator:

# Return the TS of this source >>> src[‘ts’]

# Get a skycoord representation of the source position >>> src.skydir

associations
classmethod create_from_dict(src_dict, roi_skydir=None, rescale=False)[source]

Create a source object from a python dictionary.

Parameters:src_dict (dict) – Dictionary defining the properties of the source.
static create_from_xml(root, extdir=None)[source]

Create a Source object from an XML node.

Parameters:
  • root (Element) – XML node containing the source.
  • extdir (str) – Path to the extended source archive.
classmethod create_from_xmlfile(xmlfile, extdir=None)[source]

Create a Source object from an XML file.

Parameters:
  • xmlfile (str) – Path to XML file.
  • extdir (str) – Path to the extended source archive.
data
diffuse
extended
radec
separation(src)[source]
set_position(skydir)[source]

Set the position of the source.

Parameters:skydir (SkyCoord) –
set_radec(ra, dec)[source]
set_roi_direction(roidir)[source]
set_roi_geom(geom)[source]
set_spatial_model(spatial_model, spatial_pars)[source]
skydir

Return a SkyCoord representation of the source position.

Returns:skydir
Return type:SkyCoord
update_data(d)[source]
write_xml(root)[source]

Write this source to an XML node.

fermipy.roi_model.create_source_table(scan_shape)[source]

Create an empty source table.

Returns:tab
Return type:Table
fermipy.roi_model.get_dist_to_edge(skydir, lon, lat, width, coordsys='CEL')[source]
fermipy.roi_model.get_linear_dist(skydir, lon, lat, coordsys='CEL')[source]
fermipy.roi_model.get_skydir_distance_mask(src_skydir, skydir, dist, min_dist=None, square=False, coordsys='CEL')[source]

Retrieve sources within a certain angular distance of an (ra,dec) coordinate. This function supports two types of geometric selections: circular (square=False) and square (square=True). The circular selection finds all sources with a given angular distance of the target position. The square selection finds sources within an ROI-like region of size R x R where R = 2 x dist.

Parameters:
  • src_skydir (SkyCoord) – Array of sky directions.
  • skydir (SkyCoord) – Sky direction with respect to which the selection will be applied.
  • dist (float) – Maximum distance in degrees from the sky coordinate.
  • square (bool) – Choose whether to apply a circular or square selection.
  • coordsys (str) – Coordinate system to use when applying a selection with square=True.
fermipy.roi_model.get_true_params_dict(pars_dict)[source]
fermipy.roi_model.spatial_pars_from_catalog(cat)[source]
fermipy.roi_model.spectral_pars_from_catalog(cat)[source]

Create spectral parameters from 3FGL catalog columns.

fermipy.utils module

fermipy.utils.angle_to_cartesian(lon, lat)[source]

Convert spherical coordinates to cartesian unit vectors.

fermipy.utils.apply_minmax_selection(val, val_minmax)[source]
fermipy.utils.arg_to_list(arg)[source]
fermipy.utils.center_to_edge(center)[source]
fermipy.utils.collect_dirs(path, max_depth=1, followlinks=True)[source]

Recursively find directories under the given path.

fermipy.utils.convolve2d_disk(fn, r, sig, nstep=200)[source]

Evaluate the convolution f’(r) = f(r) * g(r) where f(r) is azimuthally symmetric function in two dimensions and g is a step function given by:

g(r) = H(1-r/s)

Parameters:
  • fn (function) – Input function that takes a single radial coordinate parameter.
  • r (ndarray) – Array of points at which the convolution is to be evaluated.
  • sig (float) – Radius parameter of the step function.
  • nstep (int) – Number of sampling point for numeric integration.
fermipy.utils.convolve2d_gauss(fn, r, sig, nstep=200)[source]

Evaluate the convolution f’(r) = f(r) * g(r) where f(r) is azimuthally symmetric function in two dimensions and g is a 2D gaussian with standard deviation s given by:

g(r) = 1/(2*pi*s^2) Exp[-r^2/(2*s^2)]

Parameters:
  • fn (function) – Input function that takes a single radial coordinate parameter.
  • r (ndarray) – Array of points at which the convolution is to be evaluated.
  • sig (float) – Width parameter of the gaussian.
  • nstep (int) – Number of sampling point for numeric integration.
fermipy.utils.cov_to_correlation(cov)[source]

Compute the correlation matrix given the covariance matrix.

Parameters:cov (ndarray) – N x N matrix of covariances among N parameters.
Returns:corr – N x N matrix of correlations among N parameters.
Return type:ndarray
fermipy.utils.create_dict(d0, **kwargs)[source]
fermipy.utils.create_hpx_disk_region_string(skyDir, coordsys, radius, inclusive=0)[source]
fermipy.utils.create_kernel_function_lookup(psf, fn, sigma, egy, dtheta, psf_scale_fn)[source]
fermipy.utils.create_model_name(src)[source]

Generate a name for a source object given its spatial/spectral properties.

Parameters:src (Source) – A source object.
Returns:name – A source name.
Return type:str
fermipy.utils.create_radial_spline(psf, fn, sigma, egy, dtheta, psf_scale_fn)[source]
fermipy.utils.create_source_name(skydir, floor=True, prefix='PS')[source]
fermipy.utils.create_xml_element(root, name, attrib)[source]
fermipy.utils.decode_list(input_list, key_map)[source]
fermipy.utils.dot_prod(xyz0, xyz1)[source]

Compute the dot product between two cartesian vectors where the second dimension contains the vector components.

fermipy.utils.edge_to_center(edges)[source]
fermipy.utils.edge_to_width(edges)[source]
fermipy.utils.ellipse_to_cov(sigma_maj, sigma_min, theta)[source]

Compute the covariance matrix in two variables x and y given the std. deviation along the semi-major and semi-minor axes and the rotation angle of the error ellipse.

Parameters:
  • sigma_maj (float) – Std. deviation along major axis of error ellipse.
  • sigma_min (float) – Std. deviation along minor axis of error ellipse.
  • theta (float) – Rotation angle in radians from x-axis to ellipse major axis.
fermipy.utils.eq2gal(ra, dec)[source]
fermipy.utils.eval_radial_kernel(psf, fn, sigma, idx, dtheta, psf_scale_fn)[source]
fermipy.utils.extend_array(edges, binsz, lo, hi)[source]

Extend an array to encompass lo and hi values.

fermipy.utils.find_function_root(fn, x0, xb, delta=0.0, bounds=None)[source]

Find the root of a function: f(x)+delta in the interval encompassed by x0 and xb.

Parameters:
  • fn (function) – Python function.
  • x0 (float) – Fixed bound for the root search. This will either be used as the lower or upper bound depending on the relative value of xb.
  • xb (float) – Upper or lower bound for the root search. If a root is not found in the interval [x0,xb]/[xb,x0] this value will be increased/decreased until a change in sign is found.
fermipy.utils.find_rows_by_string(tab, names, colnames=['assoc'])[source]

Find the rows in a table tab that match at least one of the strings in names. This method ignores whitespace and case when matching strings.

Parameters:
  • tab (astropy.table.Table) – Table that will be searched.
  • names (list) – List of strings.
  • colname (str) – Name of the table column that will be searched for matching string.
Returns:

mask – Boolean mask for rows with matching strings.

Return type:

ndarray

fermipy.utils.fit_parabola(z, ix, iy, dpix=3, zmin=None)[source]

Fit a parabola to a 2D numpy array. This function will fit a parabola with the functional form described in parabola to a 2D slice of the input array z. The fit region encompasses pixels that are within dpix of the pixel coordinate (iz,iy) OR that have a value relative to the peak value greater than zmin.

Parameters:
  • z (ndarray) –
  • ix (int) – X index of center pixel of fit region in array z.
  • iy (int) – Y index of center pixel of fit region in array z.
  • dpix (int) – Max distance from center pixel of fit region.
  • zmin (float) –
fermipy.utils.fits_recarray_to_dict(table)[source]

Convert a FITS recarray to a python dictionary.

fermipy.utils.format_filename(outdir, basename, prefix=None, extension=None)[source]
fermipy.utils.gal2eq(l, b)[source]
fermipy.utils.get_bounded_slice(idx, dpix, shape)[source]
fermipy.utils.get_parameter_limits(xval, loglike, cl_limit=0.95, cl_err=0.68269, tol=0.01, bounds=None)[source]

Compute upper/lower limits, peak position, and 1-sigma errors from a 1-D likelihood function. This function uses the delta-loglikelihood method to evaluate parameter limits by searching for the point at which the change in the log-likelihood value with respect to the maximum equals a specific value. A cubic spline fit to the log-likelihood values is used to improve the accuracy of the calculation.

Parameters:
  • xval (ndarray) – Array of parameter values.
  • loglike (ndarray) – Array of log-likelihood values.
  • cl_limit (float) – Confidence level to use for limit calculation.
  • cl_err (float) – Confidence level to use for two-sided confidence interval calculation.
  • tol (float) – Absolute precision of likelihood values.
Returns:

  • x0 (float) – Coordinate at maximum of likelihood function.
  • err_lo (float) – Lower error for two-sided confidence interval with CL cl_err. Corresponds to point (x < x0) at which the log-likelihood falls by a given value with respect to the maximum (0.5 for 1 sigma). Set to nan if the change in the log-likelihood function at the lower bound of the xval input array is less than than the value for the given CL.
  • err_hi (float) – Upper error for two-sided confidence interval with CL cl_err. Corresponds to point (x > x0) at which the log-likelihood falls by a given value with respect to the maximum (0.5 for 1 sigma). Set to nan if the change in the log-likelihood function at the upper bound of the xval input array is less than the value for the given CL.
  • err (float) – Symmetric 1-sigma error. Average of err_lo and err_hi if both are defined.
  • ll (float) – Lower limit evaluated at confidence level cl_limit.
  • ul (float) – Upper limit evaluated at confidence level cl_limit.
  • lnlmax (float) – Log-likelihood value at x0.

fermipy.utils.get_region_mask(z, delta, xy=None)[source]

Get mask of connected region within delta of max(z).

fermipy.utils.init_matplotlib_backend(backend=None)[source]

This function initializes the matplotlib backend. When no DISPLAY is available the backend is automatically set to ‘Agg’.

Parameters:backend (str) – matplotlib backend name.
fermipy.utils.interpolate_function_min(x, y)[source]
fermipy.utils.is_fits_file(path)[source]
fermipy.utils.isstr(s)[source]

String instance testing method that works under both Python 2.X and 3.X. Returns true if the input is a string.

fermipy.utils.join_strings(strings, sep='_')[source]
fermipy.utils.load_data(infile, workdir=None)[source]

Load python data structure from either a YAML or numpy file.

fermipy.utils.load_npy(infile)[source]
fermipy.utils.load_xml_elements(root, path)[source]
fermipy.utils.load_yaml(infile, **kwargs)[source]
fermipy.utils.lonlat_to_xyz(lon, lat)[source]
fermipy.utils.make_cdisk_kernel(psf, sigma, npix, cdelt, xpix, ypix, psf_scale_fn=None, normalize=False)[source]

Make a kernel for a PSF-convolved 2D disk.

Parameters:
  • psf (PSFModel) –
  • sigma (float) – 68% containment radius in degrees.
fermipy.utils.make_cgauss_kernel(psf, sigma, npix, cdelt, xpix, ypix, psf_scale_fn=None, normalize=False)[source]

Make a kernel for a PSF-convolved 2D gaussian.

Parameters:
  • psf (PSFModel) –
  • sigma (float) – 68% containment radius in degrees.
fermipy.utils.make_disk_kernel(radius, npix=501, cdelt=0.01, xpix=None, ypix=None)[source]

Make kernel for a 2D disk.

Parameters:radius (float) – Disk radius in deg.
fermipy.utils.make_gaussian_kernel(sigma, npix=501, cdelt=0.01, xpix=None, ypix=None)[source]

Make kernel for a 2D gaussian.

Parameters:sigma (float) – Standard deviation in degrees.
fermipy.utils.make_pixel_distance(shape, xpix=None, ypix=None)[source]

Fill a 2D array with dimensions shape with the distance of each pixel from a reference direction (xpix,ypix) in pixel coordinates. Pixel coordinates are defined such that (0,0) is located at the center of the corner pixel.

fermipy.utils.make_psf_kernel(psf, npix, cdelt, xpix, ypix, psf_scale_fn=None, normalize=False)[source]

Generate a kernel for a point-source.

Parameters:
  • psf (PSFModel) –
  • npix (int) – Number of pixels in X and Y dimensions.
  • cdelt (float) – Pixel size in degrees.
fermipy.utils.make_radial_kernel(psf, fn, sigma, npix, cdelt, xpix, ypix, psf_scale_fn=None, normalize=False, klims=None, sparse=False)[source]

Make a kernel for a general radially symmetric 2D function.

Parameters:
  • psf (PSFModel) –
  • fn (callable) – Function that evaluates the kernel at a radial coordinate r.
  • sigma (float) – 68% containment radius in degrees.
fermipy.utils.match_regex_list(patterns, string)[source]

Perform a regex match of a string against a list of patterns. Returns true if the string matches at least one pattern in the list.

fermipy.utils.memoize(obj)[source]
fermipy.utils.merge_dict(d0, d1, add_new_keys=False, append_arrays=False)[source]

Recursively merge the contents of python dictionary d0 with the contents of another python dictionary, d1.

Parameters:
  • d0 (dict) – The input dictionary.
  • d1 (dict) – Dictionary to be merged with the input dictionary.
  • add_new_keys (str) – Do not skip keys that only exist in d1.
  • append_arrays (bool) – If an element is a numpy array set the value of that element by concatenating the two arrays.
fermipy.utils.merge_list_of_dicts(listofdicts)[source]
fermipy.utils.met_to_mjd(time)[source]

“Convert mission elapsed time to mean julian date.

fermipy.utils.mkdir(dir)[source]
fermipy.utils.onesided_cl_to_dlnl(cl)[source]

Compute the delta-loglikehood values that corresponds to an upper limit of the given confidence level.

Parameters:cl (float) – Confidence level.
Returns:dlnl – Delta-loglikelihood value with respect to the maximum of the likelihood function.
Return type:float
fermipy.utils.onesided_dlnl_to_cl(dlnl)[source]

Compute the confidence level that corresponds to an upper limit with a given change in the loglikelihood value.

Parameters:dlnl (float) – Delta-loglikelihood value with respect to the maximum of the likelihood function.
Returns:cl – Confidence level.
Return type:float
fermipy.utils.overlap_slices(large_array_shape, small_array_shape, position)[source]

Modified version of overlap_slices.

Get slices for the overlapping part of a small and a large array.

Given a certain position of the center of the small array, with respect to the large array, tuples of slices are returned which can be used to extract, add or subtract the small array at the given position. This function takes care of the correct behavior at the boundaries, where the small array is cut of appropriately.

Parameters:
  • large_array_shape (tuple) – Shape of the large array.
  • small_array_shape (tuple) – Shape of the small array.
  • position (tuple) – Position of the small array’s center, with respect to the large array. Coordinates should be in the same order as the array shape.
Returns:

  • slices_large (tuple of slices) – Slices in all directions for the large array, such that large_array[slices_large] extracts the region of the large array that overlaps with the small array.
  • slices_small (slice) – Slices in all directions for the small array, such that small_array[slices_small] extracts the region that is inside the large array.

fermipy.utils.parabola(xy, amplitude, x0, y0, sx, sy, theta)[source]

Evaluate a 2D parabola given by:

f(x,y) = f_0 - (1/2) * delta^T * R * Sigma * R^T * delta

where

delta = [(x - x_0), (y - y_0)]

and R is the matrix for a 2D rotation by angle heta and Sigma is the covariance matrix:

Sigma = [[1/sigma_x^2, 0 ],
[0 , 1/sigma_y^2]]
Parameters:
  • xy (tuple) – Tuple containing x and y arrays for the values at which the parabola will be evaluated.
  • amplitude (float) – Constant offset value.
  • x0 (float) – Centroid in x coordinate.
  • y0 (float) – Centroid in y coordinate.
  • sx (float) – Standard deviation along first axis (x-axis when theta=0).
  • sy (float) – Standard deviation along second axis (y-axis when theta=0).
  • theta (float) – Rotation angle in radians.
Returns:

vals – Values of the parabola evaluated at the points defined in the xy input tuple.

Return type:

ndarray

fermipy.utils.path_to_xmlpath(path)[source]
fermipy.utils.poly_to_parabola(coeff)[source]
fermipy.utils.prettify_xml(elem)[source]

Return a pretty-printed XML string for the Element.

fermipy.utils.project(lon0, lat0, lon1, lat1)[source]

This function performs a stereographic projection on the unit vector (lon1,lat1) with the pole defined at the reference unit vector (lon0,lat0).

fermipy.utils.rebin_map(k, nebin, npix, rebin)[source]
fermipy.utils.resolve_file_path(path, **kwargs)[source]
fermipy.utils.resolve_file_path_list(pathlist, workdir, prefix='', randomize=False)[source]

Resolve the path of each file name in the file pathlist and write the updated paths to a new file.

fermipy.utils.resolve_path(path, workdir=None)[source]
fermipy.utils.scale_parameter(p)[source]
fermipy.utils.separation_cos_angle(lon0, lat0, lon1, lat1)[source]

Evaluate the cosine of the angular separation between two direction vectors.

fermipy.utils.split_bin_edges(edges, npts=2)[source]

Subdivide an array of bins by splitting each bin into npts subintervals.

Parameters:
  • edges (ndarray) – Bin edge array.
  • npts (int) – Number of intervals into which each bin will be subdivided.
Returns:

edges – Subdivided bin edge array.

Return type:

ndarray

fermipy.utils.strip_suffix(filename, suffix)[source]
fermipy.utils.sum_bins(x, dim, npts)[source]
fermipy.utils.tolist(x)[source]

convenience function that takes in a nested structure of lists and dictionaries and converts everything to its base objects. This is useful for dupming a file to yaml.

  1. numpy arrays into python lists

    >>> type(tolist(np.asarray(123))) == int
    True
    >>> tolist(np.asarray([1,2,3])) == [1,2,3]
    True
    
  2. numpy strings into python strings.

    >>> tolist([np.asarray('cat')])==['cat']
    True
    
  3. an ordered dict to a dict

    >>> ordered=OrderedDict(a=1, b=2)
    >>> type(tolist(ordered)) == dict
    True
    
  4. converts unicode to regular strings

    >>> type(u'a') == str
    False
    >>> type(tolist(u'a')) == str
    True
    
  5. converts numbers & bools in strings to real represntation, (i.e. ‘123’ -> 123)

    >>> type(tolist(np.asarray('123'))) == int
    True
    >>> type(tolist('123')) == int
    True
    >>> tolist('False') == False
    True
    
fermipy.utils.twosided_cl_to_dlnl(cl)[source]

Compute the delta-loglikehood value that corresponds to a two-sided interval of the given confidence level.

Parameters:cl (float) – Confidence level.
Returns:dlnl – Delta-loglikelihood value with respect to the maximum of the likelihood function.
Return type:float
fermipy.utils.twosided_dlnl_to_cl(dlnl)[source]

Compute the confidence level that corresponds to a two-sided interval with a given change in the loglikelihood value.

Parameters:dlnl (float) – Delta-loglikelihood value with respect to the maximum of the likelihood function.
Returns:cl – Confidence level.
Return type:float
fermipy.utils.unicode_representer(dumper, uni)[source]
fermipy.utils.unicode_to_str(args)[source]
fermipy.utils.update_bounds(val, bounds)[source]
fermipy.utils.update_keys(input_dict, key_map)[source]
fermipy.utils.val_to_bin(edges, x)[source]

Convert axis coordinate to bin index.

fermipy.utils.val_to_bin_bounded(edges, x)[source]

Convert axis coordinate to bin index.

fermipy.utils.val_to_edge(edges, x)[source]

Convert axis coordinate to bin index.

fermipy.utils.val_to_pix(center, x)[source]
fermipy.utils.write_yaml(o, outfile, **kwargs)[source]
fermipy.utils.xmlpath_to_path(path)[source]
fermipy.utils.xyz_to_lonlat(*args)[source]

fermipy.plotting module

class fermipy.plotting.AnalysisPlotter(config, **kwargs)[source]

Bases: fermipy.config.Configurable

defaults = {'catalogs': (None, '', <class 'list'>), 'cmap': ('magma', 'Set the colormap for 2D plots.', <class 'str'>), 'cmap_resid': ('RdBu_r', 'Set the colormap for 2D residual plots.', <class 'str'>), 'figsize': ([8.0, 6.0], 'Set the default figure size.', <class 'list'>), 'fileio': {'logfile': (None, 'Path to log file. If None then log will be written to fermipy.log.', <class 'str'>), 'outdir': (None, 'Path of the output directory. If none this will default to the directory containing the configuration file.', <class 'str'>), 'outdir_regex': (['\\.fits$|\\.fit$|\\.xml$|\\.npy$|\\.png$|\\.pdf$|\\.yaml$'], 'Stage files to the output directory that match at least one of the regular expressions in this list. This option only takes effect when ``usescratch`` is True.', <class 'list'>), 'savefits': (True, 'Save intermediate FITS files.', <class 'bool'>), 'scratchdir': ('/scratch', 'Path to the scratch directory. If ``usescratch`` is True then a temporary working directory will be created under this directory.', <class 'str'>), 'usescratch': (False, 'Run analysis in a temporary working directory under ``scratchdir``.', <class 'bool'>), 'workdir': (None, 'Path to the working directory.', <class 'str'>), 'workdir_regex': (['\\.fits$|\\.fit$|\\.xml$|\\.npy$'], 'Stage files to the working directory that match at least one of the regular expressions in this list. This option only takes effect when ``usescratch`` is True.', <class 'list'>)}, 'format': ('png', '', <class 'str'>), 'graticule_radii': (None, 'Define a list of radii at which circular graticules will be drawn.', <class 'list'>), 'interactive': (False, 'Enable interactive mode. If True then plots will be drawn after each plotting command.', <class 'bool'>), 'label_ts_threshold': (0.0, 'TS threshold for labeling sources in sky maps. If None then no sources will be labeled.', <class 'float'>), 'loge_bounds': (None, '', <class 'list'>), 'logging': {'chatter': (3, 'Set the chatter parameter of the STs.', <class 'int'>), 'prefix': ('', 'Prefix that will be appended to the logger name.', <class 'str'>), 'verbosity': (3, '', <class 'int'>)}}
make_extension_plots(ext, roi=None, **kwargs)[source]
make_localization_plots(loc, roi=None, **kwargs)[source]
make_residmap_plots(maps, roi=None, **kwargs)[source]

Make plots from the output of residmap.

Parameters:
  • maps (dict) – Output dictionary of residmap.
  • roi (ROIModel) – ROI Model object. Generate markers at the positions of the sources in this ROI.
  • zoom (float) – Crop the image by this factor. If None then no crop is applied.
make_roi_plots(gta, mcube_tot, **kwargs)[source]

Make various diagnostic plots for the 1D and 2D counts/model distributions.

Parameters:prefix (str) – Prefix that will be appended to all filenames.
make_sed_plots(sed, **kwargs)[source]
make_tsmap_plots(maps, roi=None, **kwargs)[source]

Make plots from the output of tsmap or tscube. This method generates a 2D sky map for the best-fit test source in sqrt(TS) and Npred.

Parameters:
  • maps (dict) – Output dictionary of tsmap or tscube.
  • roi (ROIModel) – ROI Model object. Generate markers at the positions of the sources in this ROI.
  • zoom (float) – Crop the image by this factor. If None then no crop is applied.
run(gta, mcube_map, **kwargs)[source]

Make all plots.

class fermipy.plotting.ExtensionPlotter(src, roi, suffix, workdir, loge_bounds=None)[source]

Bases: object

plot(iaxis)[source]
class fermipy.plotting.ImagePlotter(img, mapping=None)[source]

Bases: object

geom
plot(subplot=111, cmap='magma', **kwargs)[source]
projtype
class fermipy.plotting.ROIPlotter(data_map, hpx2wcs=None, **kwargs)[source]

Bases: fermipy.config.Configurable

classmethod create_from_fits(fitsfile, roi, **kwargs)[source]
data
defaults = {'catalogs': (None, '', <class 'list'>), 'cmap': ('ds9_b', '', <class 'str'>), 'graticule_radii': (None, '', <class 'list'>), 'label_ts_threshold': (0.0, '', <class 'float'>), 'loge_bounds': (None, '', <class 'list'>)}
draw_circle(radius, **kwargs)[source]
geom
static get_data_projection(data_map, axes, iaxis, xmin=-1, xmax=1, loge_bounds=None)[source]
map
plot(**kwargs)[source]
plot_catalog(catalog)[source]
plot_projection(iaxis, **kwargs)[source]
plot_roi(roi, **kwargs)[source]
plot_sources(skydir, labels, plot_kwargs, text_kwargs, **kwargs)[source]
proj
projtype
static setup_projection_axis(iaxis, loge_bounds=None)[source]
zoom(zoom)[source]
class fermipy.plotting.SEDPlotter(sed)[source]

Bases: object

static get_ylims(sed)[source]
plot(showlnl=False, **kwargs)[source]
static plot_flux_points(sed, **kwargs)[source]
static plot_lnlscan(sed, **kwargs)[source]
static plot_model(model_flux, **kwargs)[source]
static plot_resid(src, model_flux, **kwargs)[source]
static plot_sed(sed, showlnl=False, **kwargs)[source]

Render a plot of a spectral energy distribution.

Parameters:
  • showlnl (bool) – Overlay a map of the delta-loglikelihood values vs. flux in each energy bin.
  • cmap (str) – Colormap that will be used for the delta-loglikelihood map.
  • llhcut (float) – Minimum delta-loglikelihood value.
  • ul_ts_threshold (float) – TS threshold that determines whether the MLE or UL is plotted in each energy bin.
sed
fermipy.plotting.annotate(**kwargs)[source]
fermipy.plotting.annotate_name(data, xy=(0.05, 0.93), **kwargs)[source]
fermipy.plotting.get_xerr(sed)[source]
fermipy.plotting.load_bluered_cmap()[source]
fermipy.plotting.load_ds9_cmap()[source]
fermipy.plotting.make_counts_spectrum_plot(o, roi, energies, imfile, **kwargs)[source]
fermipy.plotting.make_cube_slice(map_in, loge_bounds)[source]

Extract a slice from a map cube object.

fermipy.plotting.plot_error_ellipse(fit, xy, cdelt, **kwargs)[source]
fermipy.plotting.plot_markers(lon, lat, **kwargs)[source]
fermipy.plotting.truncate_colormap(cmap, minval=0.0, maxval=1.0, n=256)[source]

Function that extracts a subset of a colormap.

fermipy.sed module

fermipy.sourcefind module

fermipy.spectrum module

class fermipy.spectrum.DMFitFunction(params, chan='bb', jfactor=1e+19, tablepath=None, dfactor=1e+17)[source]

Bases: fermipy.spectrum.SpectralFunction

Class that evaluates the spectrum for a DM particle of a given mass, channel, cross section, and J-factor. The parameterization is given by:

F(x) = 1 / (8 * pi) * (1/mass^2) * sigmav * J * dN/dE(E,mass,i)

where the params array should be defined with:

  • params[0] : sigmav (or tau for decay)
  • params[1] : mass

Note that this class assumes that mass and J-factor are provided in units of GeV and GeV^2 cm^-5 while energies are defined in MeV.

For decay the D-factor is in uits of GeV cm^-2 s

ann_channel_names
chan

Return the channel string.

chan_code

Return the channel code.

channel_index_mapping = {1: 8, 2: 6, 3: 3, 4: 1, 5: 2, 6: 7, 7: 4, 8: 5, 9: 0, 10: 10, 11: 11, 12: 9, 101: 8, 102: 6, 103: 3, 104: 1, 105: 2, 106: 7, 107: 4, 108: 5, 109: 0, 110: 10, 111: 11, 112: 9}
channel_name_mapping = {1: ['e+e-', 'ee'], 2: ['mu+mu-', 'mumu', 'musrc'], 3: ['tau+tau-', 'tautau', 'tausrc'], 4: ['bb-bar', 'bb', 'bbbar', 'bbsrc'], 5: ['tt-bar', 'tt'], 6: ['gluons', 'gg'], 7: ['W+W-', 'w+w-', 'ww', 'wwsrc'], 8: ['ZZ', 'zz'], 9: ['cc-bar', 'cc'], 10: ['uu-bar', 'uu'], 11: ['dd-bar', 'dd'], 12: ['ss-bar', 'ss'], 101: ['e+e-_decay', 'ee_decay'], 102: ['mu+mu-_decay', 'mumu_decay', 'musrc_decay'], 103: ['tau+tau-_decay', 'tautau_decay', 'tausrc_decay'], 104: ['bb-bar_decay', 'bb_decay', 'bbbar_decay', 'bbsrc_decay'], 105: ['tt-bar_decay', 'tt_decay'], 106: ['gluons_decay', 'gg_decay'], 107: ['W+W-_decay', 'w+w-_decay', 'ww_decay', 'wwsrc_decay'], 108: ['ZZ_decay', 'zz_decay'], 109: ['cc-bar_decay', 'cc_decay'], 110: ['uu-bar_decay', 'uu_decay'], 111: ['dd-bar_decay', 'dd_decay'], 112: ['ss-bar_decay', 'ss_decay']}
channel_rev_map = {'W+W-': 7, 'W+W-_decay': 107, 'ZZ': 8, 'ZZ_decay': 108, 'bb': 4, 'bb-bar': 4, 'bb-bar_decay': 104, 'bb_decay': 104, 'bbbar': 4, 'bbbar_decay': 104, 'bbsrc': 4, 'bbsrc_decay': 104, 'cc': 9, 'cc-bar': 9, 'cc-bar_decay': 109, 'cc_decay': 109, 'dd': 11, 'dd-bar': 11, 'dd-bar_decay': 111, 'dd_decay': 111, 'e+e-': 1, 'e+e-_decay': 101, 'ee': 1, 'ee_decay': 101, 'gg': 6, 'gg_decay': 106, 'gluons': 6, 'gluons_decay': 106, 'mu+mu-': 2, 'mu+mu-_decay': 102, 'mumu': 2, 'mumu_decay': 102, 'musrc': 2, 'musrc_decay': 102, 'ss': 12, 'ss-bar': 12, 'ss-bar_decay': 112, 'ss_decay': 112, 'tau+tau-': 3, 'tau+tau-_decay': 103, 'tausrc': 3, 'tausrc_decay': 103, 'tautau': 3, 'tautau_decay': 103, 'tt': 5, 'tt-bar': 5, 'tt-bar_decay': 105, 'tt_decay': 105, 'uu': 10, 'uu-bar': 10, 'uu-bar_decay': 110, 'uu_decay': 110, 'w+w-': 7, 'w+w-_decay': 107, 'ww': 7, 'ww_decay': 107, 'wwsrc': 7, 'wwsrc_decay': 107, 'zz': 8, 'zz_decay': 108}
channel_shortname_mapping = {1: 'ee', 2: 'mumu', 3: 'tautau', 4: 'bb', 5: 'tt', 6: 'gg', 7: 'ww', 8: 'zz', 9: 'cc', 10: 'uu', 11: 'dd', 12: 'ss', 101: 'ee', 102: 'mumu', 103: 'tautau', 104: 'bb', 105: 'tt', 106: 'gg', 107: 'ww', 108: 'zz', 109: 'cc', 110: 'uu', 111: 'dd', 112: 'ss'}
static channels()[source]

Return all available DMFit channel strings

decay

Return True if this is a decay spectrum

decay_channel_names
static nparam()[source]
set_channel(chan)[source]
class fermipy.spectrum.LogParabola(params=None, scale=1.0, extra_params=None)[source]

Bases: fermipy.spectrum.SpectralFunction

Class that evaluates a function with the parameterization:

F(x) = p_0 * (x/x_s)^(p_1 - p_2*log(x/x_s) )

where x_s is a scale parameter. The params array should be defined with:

  • params[0] : Prefactor (p_0)
  • params[1] : Index (p_1)
  • params[2] : Curvature (p_2)
static nparam()[source]
class fermipy.spectrum.PLExpCutoff(params=None, scale=1.0, extra_params=None)[source]

Bases: fermipy.spectrum.SpectralFunction

Class that evaluates a function with the parameterization:

F(x) = p_0 * (x/x_s)^(p_1) * exp(- x/p_2 )

where x_s is the scale parameter. The params array should be defined with:

  • params[0] : Prefactor (p_0)
  • params[1] : Index (p_1)
  • params[2] : Cutoff (p_2)
static log_to_params(params)[source]
static nparam()[source]
static params_to_log(params)[source]
class fermipy.spectrum.PLSuperExpCutoff(params=None, scale=1.0, extra_params=None)[source]

Bases: fermipy.spectrum.SpectralFunction

Class that evaluates a function with the parameterization:

F(x) = p_0 * (x/x_s)^(p_1) * exp(-(x/p2)**p3)

where x_s is the scale parameter. The params array should be defined with:

  • params[0] : Prefactor (p_0)
  • params[1] : Index1 (p_1)
  • params[2] : Curvature (p_2)
  • params[3] : Index2 (p3)
static log_to_params(params)[source]
static nparam()[source]
static params_to_log(params)[source]
class fermipy.spectrum.PowerLaw(params=None, scale=1.0, extra_params=None)[source]

Bases: fermipy.spectrum.SpectralFunction

Class that evaluates a power-law function with the parameterization:

F(x) = p_0 * (x/x_s)^p_1

where x_s is the scale parameter. The params array should be defined with:

  • params[0] : Prefactor (p_0)
  • params[1] : Index (p_1)
classmethod eval_eflux(emin, emax, params, scale=1.0, extra_params=None)[source]
static eval_flux(emin, emax, params, scale=1.0, extra_params=None)[source]
classmethod eval_norm(scale, index, emin, emax, flux)[source]
static nparam()[source]
class fermipy.spectrum.SEDEFluxFunctor(sfn, emin, emax)[source]

Bases: fermipy.spectrum.SEDFunctor

Functor that computes the energy flux of a source in a pre-defined sequence of energy bins.

class fermipy.spectrum.SEDFluxFunctor(sfn, emin, emax)[source]

Bases: fermipy.spectrum.SEDFunctor

Functor that computes the flux of a source in a pre-defined sequence of energy bins.

class fermipy.spectrum.SEDFunctor(sfn, emin, emax)[source]

Bases: object

Functor object that wraps a SpectralFunction and computes the normalization of the model in a sequence of SED energy bins. The evaluation method of this class accepts a single vector for the parameters of the model. This class serves as an object that can be passed to likelihood optimizers.

emax
emin
params
scale
spectral_fn
class fermipy.spectrum.SpectralFunction(params, scale=1.0, extra_params=None)[source]

Bases: object

Base class for spectral models. Spectral models inheriting from this class should implement at a minimum an _eval_dnde method which evaluates the differential flux at a given energy.

classmethod create_eflux_functor(emin, emax, params=None, scale=1.0, extra_params=None)[source]
classmethod create_flux_functor(emin, emax, params=None, scale=1.0, extra_params=None)[source]
classmethod create_from_eflux(params, emin, emax, eflux, scale=1.0)[source]

Create a spectral function instance given its energy flux.

classmethod create_from_flux(params, emin, emax, flux, scale=1.0)[source]

Create a spectral function instance given its flux.

classmethod create_functor(spec_type, func_type, emin, emax, params=None, scale=1.0, extra_params=None)[source]
dnde(x, params=None)[source]

Evaluate differential flux.

dnde_deriv(x, params=None)[source]

Evaluate derivative of the differential flux with respect to E.

e2dnde(x, params=None)[source]

Evaluate E^2 times differential flux.

e2dnde_deriv(x, params=None)[source]

Evaluate derivative of E^2 times differential flux with respect to E.

ednde(x, params=None)[source]

Evaluate E times differential flux.

ednde_deriv(x, params=None)[source]

Evaluate derivative of E times differential flux with respect to E.

eflux(emin, emax, params=None)[source]

Evaluate the integral energy flux.

classmethod eval_dnde(x, params, scale=1.0, extra_params=None)[source]
classmethod eval_dnde_deriv(x, params, scale=1.0, extra_params=None)[source]
classmethod eval_e2dnde(x, params, scale=1.0, extra_params=None)[source]
classmethod eval_e2dnde_deriv(x, params, scale=1.0, extra_params=None)[source]
classmethod eval_ednde(x, params, scale=1.0, extra_params=None)[source]
classmethod eval_ednde_deriv(x, params, scale=1.0, extra_params=None)[source]
classmethod eval_eflux(emin, emax, params, scale=1.0, extra_params=None)[source]
classmethod eval_flux(emin, emax, params, scale=1.0, extra_params=None)[source]
extra_params

Dictionary containing additional parameters needed for evaluation of the function.

flux(emin, emax, params=None)[source]

Evaluate the integral flux.

log_params

Return transformed parameter vector in which norm and scale parameters are converted to log10.

params

Return parameter vector of the function.

scale
fermipy.spectrum.cast_args(x)[source]
fermipy.spectrum.cast_params(params)[source]

fermipy.skymap module

class fermipy.skymap.HpxMap(counts, hpx)[source]

Bases: fermipy.skymap.Map_Base

Representation of a 2D or 3D counts map using HEALPix.

convert_to_cached_wcs(hpx_in, sum_ebins=False, normalize=True)[source]

Make a WCS object and convert HEALPix data into WCS projection

Parameters:
  • hpx_in (ndarray) – HEALPix input data
  • sum_ebins (bool) – sum energy bins over energy bins before reprojecting
  • normalize (bool) – True -> perserve integral by splitting HEALPix values between bins
  • (WCS object, np.ndarray() with reprojected data) (returns) –
classmethod create_from_fits(fitsfile, **kwargs)[source]
classmethod create_from_hdu(hdu, ebins)[source]

Creates and returns an HpxMap object from a FITS HDU.

hdu : The FITS ebins : Energy bin edges [optional]

classmethod create_from_hdulist(hdulist, **kwargs)[source]

Creates and returns an HpxMap object from a FITS HDUList

extname : The name of the HDU with the map data ebounds : The name of the HDU with the energy bin data

create_image_hdu(name=None, **kwargs)[source]
expanded_counts_map()[source]

return the full counts map

explicit_counts_map(pixels=None)[source]

return a counts map with explicit index scheme

Parameters:pixels (np.ndarray or None) – If set, grab only those pixels. If none, grab only non-zero pixels
get_map_values(lons, lats, ibin=None)[source]

Return the indices in the flat array corresponding to a set of coordinates

Parameters:
  • lons (array-like) – ‘Longitudes’ (RA or GLON)
  • lats (array-like) – ‘Latitidues’ (DEC or GLAT)
  • ibin (int or array-like) – Extract data only for a given energy bin. None -> extract data for all bins
Returns:

vals – Values of pixels in the flattened map, np.nan used to flag coords outside of map

Return type:

numpy.ndarray((n))

get_pixel_indices(lats, lons)[source]

Return the indices in the flat array corresponding to a set of coordinates

get_pixel_skydirs()[source]

Get a list of sky coordinates for the centers of every pixel.

hpx
interpolate(lon, lat, egy=None, interp_log=True)[source]

Interpolate map values.

Parameters:interp_log (bool) – Interpolate the z-coordinate in logspace.
make_wcs_from_hpx(sum_ebins=False, proj='CAR', oversample=2, normalize=True)[source]

Make a WCS object and convert HEALPix data into WCS projection

NOTE: this re-calculates the mapping, if you have already calculated the mapping it is much faster to use convert_to_cached_wcs() instead

Parameters:
  • sum_ebins (bool) – sum energy bins over energy bins before reprojecting
  • proj (str) – WCS-projection
  • oversample (int) – Oversampling factor for WCS map
  • normalize (bool) – True -> perserve integral by splitting HEALPix values between bins
  • (WCS object, np.ndarray() with reprojected data) (returns) –
sparse_counts_map()[source]

return a counts map with sparse index scheme

sum_over_energy()[source]

Reduce a counts cube to a counts map

swap_scheme()[source]
ud_grade(order, preserve_counts=False)[source]
class fermipy.skymap.Map(counts, wcs, ebins=None)[source]

Bases: fermipy.skymap.Map_Base

Representation of a 2D or 3D counts map using WCS.

classmethod create(skydir, cdelt, npix, coordsys='CEL', projection='AIT', ebins=None, differential=False)[source]
classmethod create_from_fits(fitsfile, **kwargs)[source]
classmethod create_from_hdu(hdu, wcs)[source]
create_image_hdu(name=None, **kwargs)[source]
create_primary_hdu()[source]
get_map_values(lons, lats, ibin=None)[source]

Return the map values corresponding to a set of coordinates.

Parameters:
  • lons (array-like) – ‘Longitudes’ (RA or GLON)
  • lats (array-like) – ‘Latitidues’ (DEC or GLAT)
  • ibin (int or array-like) – Extract data only for a given energy bin. None -> extract data for all bins
Returns:

vals – Values of pixels in the flattened map, np.nan used to flag coords outside of map

Return type:

numpy.ndarray((n))

get_pixel_indices(lons, lats, ibin=None)[source]

Return the indices in the flat array corresponding to a set of coordinates

Parameters:
  • lons (array-like) – ‘Longitudes’ (RA or GLON)
  • lats (array-like) – ‘Latitidues’ (DEC or GLAT)
  • ibin (int or array-like) – Extract data only for a given energy bin. None -> extract data for all energy bins.
Returns:

pixcrd – Pixel indices along each dimension of the map.

Return type:

list

get_pixel_skydirs()[source]

Get a list of sky coordinates for the centers of every pixel.

interpolate(lon, lat, egy=None)[source]

Return the interpolated map values corresponding to a set of coordinates.

interpolate_at_skydir(skydir)[source]
ipix_swap_axes(ipix, colwise=False)[source]

Return the transposed pixel index from the pixel xy coordinates

if colwise is True (False) this assumes the original index was in column wise scheme

ipix_to_xypix(ipix, colwise=False)[source]

Return array multi-dimensional pixel indices from flattened index.

Parameters:colwise (bool) – Use column-wise pixel indexing.
npix
pix_center

Return the ROI center in pixel coordinates.

pix_size

Return the pixel size along the two image dimensions.

skydir

Return the sky coordinate of the image center.

sum_over_energy()[source]

Reduce a 3D counts cube to a 2D counts map

wcs
width

Return the dimensions of the image.

xypix_to_ipix(xypix, colwise=False)[source]

Return the flattened pixel indices from an array multi-dimensional pixel indices.

Parameters:
  • xypix (list) – List of pixel indices in the order (LON,LAT,ENERGY).
  • colwise (bool) – Use column-wise pixel indexing.
class fermipy.skymap.Map_Base(counts)[source]

Bases: object

Abstract representation of a 2D or 3D counts map.

counts
data
get_map_values(lons, lats, ibin=None)[source]

Return the map values corresponding to a set of coordinates.

get_pixel_indices(lats, lons)[source]

Return the indices in the flat array corresponding to a set of coordinates

get_pixel_skydirs()[source]

Get a list of sky coordinates for the centers of every pixel.

interpolate(lon, lat, egy=None)[source]

Return the interpolated map values corresponding to a set of coordinates.

sum_over_energy()[source]

Reduce a counts cube to a counts map by summing over the energy planes

fermipy.skymap.coadd_maps(geom, maps, preserve_counts=True)[source]

Coadd a sequence of Map objects.

fermipy.skymap.make_coadd_hpx(maps, hpx, shape, preserve_counts=True)[source]
fermipy.skymap.make_coadd_map(maps, proj, shape, preserve_counts=True)[source]
fermipy.skymap.make_coadd_wcs(maps, wcs, shape)[source]
fermipy.skymap.read_map_from_fits(fitsfile, extname=None)[source]

fermipy.castro module

Utilities for dealing with ‘castro data’, i.e., 2D table of likelihood values.

Castro data can be tabluated in terms of a variety of variables. The most common example is probably a simple SED, where we have the likelihood as a function of Energy and Energy Flux.

However, we could easily convert to the likelihood as a function of other variables, such as the Flux normalization and the spectral index, or the mass and cross-section of a putative dark matter particle.

class fermipy.castro.CastroData(norm_vals, nll_vals, refSpec, norm_type)[source]

Bases: fermipy.castro.CastroData_Base

This class wraps the data needed to make a “Castro” plot, namely the log-likelihood as a function of normalization for a series of energy bins.

classmethod create_from_fits(fitsfile, norm_type='eflux', hdu_scan='SCANDATA', hdu_energies='EBOUNDS', irow=None)[source]

Create a CastroData object from a tscube FITS file.

Parameters:
  • fitsfile (str) – Name of the fits file
  • norm_type (str) –

    Type of normalization to use. Valid options are:

    • norm : Normalization w.r.t. to test source
    • flux : Flux of the test source ( ph cm^-2 s^-1 )
    • eflux: Energy Flux of the test source ( MeV cm^-2 s^-1 )
    • npred: Number of predicted photons (Not implemented)
    • dnde : Differential flux of the test source ( ph cm^-2 s^-1 MeV^-1 )
  • hdu_scan (str) – Name of the FITS HDU with the scan data
  • hdu_energies (str) – Name of the FITS HDU with the energy binning and normalization data
  • irow (int or None) – If none, then this assumes that there is a single row in the scan data table Otherwise, this specifies which row of the table to use
Returns:

castro

Return type:

CastroData

classmethod create_from_flux_points(txtfile)[source]

Create a Castro data object from a text file containing a sequence of differential flux points.

classmethod create_from_sedfile(fitsfile, norm_type='eflux')[source]

Create a CastroData object from an SED fits file

Parameters:
  • fitsfile (str) – Name of the fits file
  • norm_type (str) –

    Type of normalization to use, options are:

    • norm : Normalization w.r.t. to test source
    • flux : Flux of the test source ( ph cm^-2 s^-1 )
    • eflux: Energy Flux of the test source ( MeV cm^-2 s^-1 )
    • npred: Number of predicted photons (Not implemented)
    • dnde : Differential flux of the test source ( ph cm^-2 s^-1 MeV^-1 )
Returns:

castro

Return type:

CastroData

classmethod create_from_stack(shape, components, ylims, weights=None)[source]

Combine the log-likelihoods from a number of components.

Parameters:
  • shape (tuple) – The shape of the return array
  • components ([CastroData_Base]) – The components to be stacked
  • weights (array-like) –
Returns:

castro

Return type:

CastroData

classmethod create_from_tables(norm_type='eflux', tab_s='SCANDATA', tab_e='EBOUNDS')[source]

Create a CastroData object from two tables

Parameters:
  • norm_type (str) –

    Type of normalization to use. Valid options are:

    • norm : Normalization w.r.t. to test source
    • flux : Flux of the test source ( ph cm^-2 s^-1 )
    • eflux: Energy Flux of the test source ( MeV cm^-2 s^-1 )
    • npred: Number of predicted photons (Not implemented)
    • dnde : Differential flux of the test source ( ph cm^-2 s^-1 MeV^-1 )
  • tab_s (str) – table scan data
  • tab_e (str) – table energy binning and normalization data
Returns:

castro

Return type:

CastroData

classmethod create_from_yamlfile(yamlfile)[source]

Create a Castro data object from a yaml file contains the likelihood data.

create_functor(specType, initPars=None, scale=1000.0)[source]

Create a functor object that computes normalizations in a sequence of energy bins for a given spectral model.

Parameters:
  • specType (str) – The type of spectrum to use. This can be a string corresponding to the spectral model class name or a SpectralFunction object.
  • initPars (ndarray) – Arrays of parameter values with which the spectral function will be initialized.
  • scale (float) – The ‘pivot energy’ or energy scale to use for the spectrum
Returns:

fn – A functor object.

Return type:

SEDFunctor

nE

Return the number of energy bins. This is also the number of x-axis bins.

refSpec

Return a ReferenceSpec with the spectral data

spectrum_loglike(specType, params, scale=1000.0)[source]

return the log-likelihood for a particular spectrum

Parameters:
  • specTypes (str) – The type of spectrum to try
  • params (array-like) – The spectral parameters
  • scale (float) – The energy scale or ‘pivot’ energy
test_spectra(spec_types=None)[source]

Test different spectral types against the SED represented by this CastroData.

Parameters:spec_types ([str,..]) – List of spectral types to try
Returns:retDict – A dictionary of dictionaries. The top level dictionary is keyed by spec_type. The sub-dictionaries each contain:
  • ”Function” : SpectralFunction
  • ”Result” : tuple with the output of scipy.optimize.fmin
  • ”Spectrum” : ndarray with best-fit spectral values
  • ”ScaleEnergy” : float, the ‘pivot energy’ value
  • ”TS” : float, the TS for the best-fit spectrum
Return type:dict
x_edges()[source]
class fermipy.castro.CastroData_Base(norm_vals, nll_vals, nll_offsets, norm_type)[source]

Bases: object

This class wraps the data needed to make a “Castro” plot, namely the log-likelihood as a function of normalization.

In this case the x-axes and y-axes are generic Sub-classes can implement particul axes choices (e.g., EFlux v. Energy)

TS_spectrum(spec_vals)[source]

Calculate and the TS for a given set of spectral values.

build_lnl_fn(normv, nllv)[source]
build_scandata_table()[source]

Build an astropy.table.Table object from these data.

chi2_vals(x)[source]

Compute the difference in the log-likelihood between the MLE in each energy bin and the normalization predicted by a global best-fit model. This array can be summed to get a goodness-of-fit chi2 for the model.

Parameters:x (ndarray) – An array of normalizations derived from a global fit to all energy bins.
Returns:chi2_vals – An array of chi2 values for each energy bin.
Return type:ndarray
derivative(x, der=1)[source]

Return the derivate of the log-like summed over the energy bins

Parameters:
  • x (ndarray) – Array of N x M values
  • der (int) – Order of the derivate
Returns:

der_val – Array of negative log-likelihood values.

Return type:

ndarray

fitNorm_v2(specVals)[source]

Fit the normalization given a set of spectral values that define a spectral shape.

This version uses scipy.optimize.fmin.

Parameters:
  • specVals (an array of (nebin values that define a spectral shape) –
  • xlims (fit limits) –
Returns:

norm – Best-fit normalization value

Return type:

float

fitNormalization(specVals, xlims)[source]

Fit the normalization given a set of spectral values that define a spectral shape

This version is faster, and solves for the root of the derivatvie

Parameters:
  • specVals (an array of (nebin values that define a spectral shape) –
  • xlims (fit limits) –
  • the best-fit normalization value (returns) –
fit_spectrum(specFunc, initPars, freePars=None)[source]

Fit for the free parameters of a spectral function

Parameters:
  • specFunc (SpectralFunction) – The Spectral Function
  • initPars (ndarray) – The initial values of the parameters
  • freePars (ndarray) – Boolean array indicating which parameters should be free in the fit.
Returns:

  • params (ndarray) – Best-fit parameters.
  • spec_vals (ndarray) – The values of the best-fit spectral model in each energy bin.
  • ts_spec (float) – The TS of the best-fit spectrum
  • chi2_vals (ndarray) – Array of chi-squared values for each energy bin.
  • chi2_spec (float) – Global chi-squared value for the sum of all energy bins.
  • pval_spec (float) – p-value of chi-squared for the best-fit spectrum.

fn_mles()[source]

returns the summed likelihood at the maximum likelihood estimate

Note that simply sums the maximum likelihood values at each bin, and does not impose any sort of constrain between bins

getIntervals(alpha)[source]

Evaluate the two-sided intervals corresponding to a C.L. of (1-alpha)%.

Parameters:alpha (float) – limit confidence level.
Returns:
  • limit_vals_hi (ndarray) – An array of lower limit values.
  • limit_vals_lo (ndarray) – An array of upper limit values.
getLimits(alpha, upper=True)[source]

Evaluate the limits corresponding to a C.L. of (1-alpha)%.

Parameters:
  • alpha (float) – limit confidence level.
  • upper (bool) – upper or lower limits.
  • an array of values, one for each energy bin (returns) –
mles()[source]

return the maximum likelihood estimates for each of the energy bins

nll_null

Return the negative log-likelihood for the null-hypothesis

nll_offsets

Return the offsets in the negative log-likelihoods for each bin

norm_derivative(spec, norm)[source]
norm_type

Return the normalization type flag

nx

Return the number of profiles

ny

Return the number of profiles

static stack_nll(shape, components, ylims, weights=None)[source]

Combine the log-likelihoods from a number of components.

Parameters:
  • shape (tuple) – The shape of the return array
  • components (CastroData_Base) – The components to be stacked
  • weights (array-like) –
Returns:

  • norm_vals (numpy.ndarray) – N X M array of Normalization values
  • nll_vals (numpy.ndarray) – N X M array of log-likelihood values
  • nll_offsets (numpy.ndarray) – N array of maximum log-likelihood values in each bin

ts_vals()[source]

returns test statistic values for each energy bin

x_edges()[source]
class fermipy.castro.Interpolator(x, y)[source]

Bases: object

Helper class for interpolating a 1-D function from a set of tabulated values.

Safely deals with overflows and underflows

derivative(x, der=1)[source]

return the derivative a an array of input values

x : the inputs der : the order of derivative

x

return the x values used to construct the split

xmax

return the maximum value over which the spline is defined

xmin

return the minimum value over which the spline is defined

y

return the y values used to construct the split

class fermipy.castro.LnLFn(x, y, norm_type=0)[source]

Bases: object

Helper class for interpolating a 1-D log-likelihood function from a set of tabulated values.

TS()[source]

return the Test Statistic

fn_mle()[source]

return the function value at the maximum likelihood estimate

getDeltaLogLike(dlnl, upper=True)[source]

Find the point at which the log-likelihood changes by a given value with respect to its value at the MLE.

getInterval(alpha)[source]

Evaluate the interval corresponding to a C.L. of (1-alpha)%.

Parameters:alpha (limit confidence level.) –
getLimit(alpha, upper=True)[source]

Evaluate the limits corresponding to a C.L. of (1-alpha)%.

Parameters:
  • alpha (limit confidence level.) –
  • upper (upper or lower limits.) –
interp

return the underlying Interpolator object

mle()[source]

return the maximum likelihood estimate

This will return the cached value, if it exists

norm_type

Return a string specifying the quantity used for the normalization. This isn’t actually used in this class, but it is carried so that the class is self-describing. The possible values are open-ended.

class fermipy.castro.ReferenceSpec(emin, emax, ref_dnde, ref_flux, ref_eflux, ref_npred, eref=None)[source]

Bases: object

This class encapsulates data for a reference spectrum.

Parameters:
  • ne (int) – Number of energy bins
  • ebins (ndarray) – Array of bin edges.
  • emin (ndarray) – Array of lower bin edges.
  • emax (ndarray) – Array of upper bin edges.
  • bin_widths (ndarray) – Array of energy bin widths.
  • eref (ndarray) – Array of reference energies. Typically these are the geometric mean of the energy bins
  • ref_dnde (ndarray) – Array of differential photon flux values.
  • ref_flux (ndarray) – Array of integral photon flux values.
  • ref_eflux (ndarray) – Array of integral energy flux values.
  • ref_npred (ndarray) – Array of predicted number of photons in each energy bin.
bin_widths
build_ebound_table()[source]

Build and return an EBOUNDS table with the encapsulated data.

classmethod create_from_table(tab_e)[source]
Parameters:tab_e (Table) – EBOUNDS table.
create_functor(specType, normType, initPars=None, scale=1000.0)[source]

Create a functor object that computes normalizations in a sequence of energy bins for a given spectral model.

Parameters:
  • specType (str) – The type of spectrum to use. This can be a string corresponding to the spectral model class name or a SpectralFunction object.
  • normType (The type of normalization to use) –
  • initPars (ndarray) – Arrays of parameter values with which the spectral function will be initialized.
  • scale (float) – The ‘pivot energy’ or energy scale to use for the spectrum
Returns:

fn – A functor object.

Return type:

SEDFunctor

ebins
emax
emin
eref
log_ebins
nE
ref_dnde
ref_eflux

return the energy flux values

ref_flux

return the flux values

ref_npred

return the number of predicted events

class fermipy.castro.SpecData(ref_spec, norm, norm_err)[source]

Bases: fermipy.castro.ReferenceSpec

This class encapsulates spectral analysis results (best-fit normalizations, errors, etc.), energy binning, and reference spectrum definition.

Parameters:
  • norm (ndarray) –
  • norm_err (ndarray) –
  • flux (ndarray) – Array of integral photon flux values.
  • eflux (ndarray) – Array of integral energy flux values.
  • dnde (ndarray) – Differential flux values
  • dnde_err (ndarray) – Uncertainties on differential flux values
  • e2dnde (ndarray) – Differential flux values scaled by E^2
  • e2dnde_err (ndarray) – Uncertainties on differential flux values scaled by E^2
build_spec_table()[source]
classmethod create_from_table(tab)[source]
dnde
dnde_err
e2dnde
e2dnde_err
eflux
flux
norm
norm_err
class fermipy.castro.TSCube(tsmap, normmap, tscube, normcube, norm_vals, nll_vals, refSpec, norm_type)[source]

Bases: object

A class wrapping a TSCube, which is a collection of CastroData objects for a set of directions.

This class wraps a combination of:

  • Pixel data,
  • Pixel x Energy bin data,
  • Pixel x Energy Bin x Normalization scan point data
castroData_from_ipix(ipix, colwise=False)[source]

Build a CastroData object for a particular pixel

castroData_from_pix_xy(xy, colwise=False)[source]

Build a CastroData object for a particular pixel

classmethod create_from_fits(fitsfile, norm_type='flux')[source]

Build a TSCube object from a fits file created by gttscube :param fitsfile: Path to the tscube FITS file. :type fitsfile: str :param norm_type: String specifying the quantity used for the normalization :type norm_type: str

find_and_refine_peaks(threshold, min_separation=1.0, use_cumul=False)[source]

Run a simple peak-finding algorithm, and fit the peaks to paraboloids to extract their positions and error ellipses.

Parameters:
  • threshold (float) – Peak threshold in TS.
  • min_separation (float) – Radius of region size in degrees. Sets the minimum allowable separation between peaks.
  • use_cumul (bool) – If true, used the cumulative TS map (i.e., the TS summed over the energy bins) instead of the TS Map from the fit to and index=2 powerlaw.
Returns:

peaks – List of dictionaries containing the location and amplitude of each peak. Output of find_peaks

Return type:

list

find_sources(threshold, min_separation=1.0, use_cumul=False, output_peaks=False, output_castro=False, output_specInfo=False, output_src_dicts=False, output_srcs=False)[source]
nE

return the number of energy bins

nN

return the number of sample points in each energy bin

normcube

return the Cube of the normalization value per pixel / energy bin

normmap

return the Map of the Best-fit normalization value

nvals

Return the number of values in the tscube

refSpec

Return the Spectral Data object

test_spectra_of_peak(peak, spec_types=None)[source]

Test different spectral types against the SED represented by the CastroData corresponding to a single pixel in this TSCube :param spec_types: List of spectral types to try :type spec_types: [str,…]

Returns:
  • castro (CastroData) – The castro data object for the pixel corresponding to the peak
  • test_dict (dict) – The dictionary returned by test_spectra
ts_cumul

return the Map of the cumulative TestStatistic value per pixel (summed over energy bin)

tscube

return the Cube of the TestStatistic value per pixel / energy bin

tsmap

return the Map of the TestStatistic value

fermipy.castro.build_source_dict(src_name, peak_dict, spec_dict, spec_type)[source]
fermipy.castro.convert_sed_cols(tab)[source]

Cast SED column names to lowercase.

fermipy.tsmap module

fermipy.residmap module

class fermipy.residmap.ResidMapGenerator[source]

Bases: object

Mixin class for GTAnalysis that generates spatial residual maps from the difference of data and model maps smoothed with a user-defined spatial/spectral template. The map of residual significance can be interpreted in the same way as a TS map (the likelihood of a source at the given location).

residmap(prefix='', **kwargs)[source]

Generate 2-D spatial residual maps using the current ROI model and the convolution kernel defined with the model argument.

Parameters:
  • prefix (str) – String that will be prefixed to the output residual map files.
  • {options}
Returns:

maps – A dictionary containing the Map objects for the residual significance and amplitude.

Return type:

dict

fermipy.residmap.convolve_map(m, k, cpix, threshold=0.001, imin=0, imax=None, wmap=None)[source]

Perform an energy-dependent convolution on a sequence of 2-D spatial maps.

Parameters:
  • m (ndarray) – 3-D map containing a sequence of 2-D spatial maps. First dimension should be energy.
  • k (ndarray) – 3-D map containing a sequence of convolution kernels (PSF) for each slice in m. This map should have the same dimension as m.
  • cpix (list) – Indices of kernel reference pixel in the two spatial dimensions.
  • threshold (float) – Kernel amplitude
  • imin (int) – Minimum index in energy dimension.
  • imax (int) – Maximum index in energy dimension.
  • wmap (ndarray) – 3-D map containing a sequence of 2-D spatial maps of weights. First dimension should be energy. This map should have the same dimension as m.
fermipy.residmap.convolve_map_hpx(m, k, cpix, threshold=0.001, imin=0, imax=None, wmap=None)[source]

Perform an energy-dependent convolution on a sequence of 2-D spatial maps.

Parameters:
  • m (ndarray) – 2-D map containing a sequence of 1-D HEALPix maps. First dimension should be energy.
  • k (ndarray) – 2-D map containing a sequence of convolution kernels (PSF) for each slice in m. This map should have the same dimension as m.
  • threshold (float) – Kernel amplitude
  • imin (int) – Minimum index in energy dimension.
  • imax (int) – Maximum index in energy dimension.
  • wmap (ndarray) – 2-D map containing a sequence of 1-D HEALPix maps of weights. First dimension should be energy. This map should have the same dimension as m.
fermipy.residmap.convolve_map_hpx_gauss(m, sigmas, imin=0, imax=None, wmap=None)[source]

Perform an energy-dependent convolution on a sequence of 2-D spatial maps.

Parameters:
  • m (HpxMap) – 2-D map containing a sequence of 1-D HEALPix maps. First dimension should be energy.
  • sigmas (ndarray) – 1-D map containing a sequence gaussian widths for smoothing
  • imin (int) – Minimum index in energy dimension.
  • imax (int) – Maximum index in energy dimension.
  • wmap (ndarray) – 2-D map containing a sequence of 1-D HEALPix maps of weights. First dimension should be energy. This map should have the same dimension as m.
fermipy.residmap.get_source_kernel(gta, name, kernel=None)[source]

Get the PDF for the given source.

fermipy.residmap.poisson_lnl(nc, mu)[source]

fermipy.lightcurve module

Module contents

fermipy.get_ft_conda_version()[source]

Get the version string from conda

fermipy.get_git_version_fp()[source]

Get the version string of the ST release.

fermipy.get_st_version()[source]

Get the version string of the ST release.

fermipy.test(package=None, test_path=None, args=None, plugins=None, verbose=False, pastebin=None, remote_data=False, pep8=False, pdb=False, coverage=False, open_files=False, **kwargs)[source]

Run the tests using py.test. A proper set of arguments is constructed and passed to pytest.main.

Parameters:
  • package (str, optional) – The name of a specific package to test, e.g. ‘io.fits’ or ‘utils’. If nothing is specified all default tests are run.
  • test_path (str, optional) – Specify location to test by path. May be a single file or directory. Must be specified absolutely or relative to the calling directory.
  • args (str, optional) – Additional arguments to be passed to pytest.main in the args keyword argument.
  • plugins (list, optional) – Plugins to be passed to pytest.main in the plugins keyword argument.
  • verbose (bool, optional) –

    Convenience option to turn on verbose output from py.test. Passing True is the same as specifying '-v' in args.

  • pastebin ({'failed','all',None}, optional) – Convenience option for turning on py.test pastebin output. Set to 'failed' to upload info for failed tests, or 'all' to upload info for all tests.
  • remote_data (bool, optional) – Controls whether to run tests marked with @remote_data. These tests use online data and are not run by default. Set to True to run these tests.
  • pep8 (bool, optional) – Turn on PEP8 checking via the pytest-pep8 plugin and disable normal tests. Same as specifying '--pep8 -k pep8' in args.
  • pdb (bool, optional) – Turn on PDB post-mortem analysis for failing tests. Same as specifying '--pdb' in args.
  • coverage (bool, optional) – Generate a test coverage report. The result will be placed in the directory htmlcov.
  • open_files (bool, optional) – Fail when any tests leave files open. Off by default, because this adds extra run time to the test suite. Works only on platforms with a working lsof command.
  • parallel (int, optional) – When provided, run the tests in parallel on the specified number of CPUs. If parallel is negative, it will use the all the cores on the machine. Requires the pytest-xdist plugin installed. Only available when using Astropy 0.3 or later.
  • kwargs – Any additional keywords passed into this function will be passed on to the astropy test runner. This allows use of test-related functionality implemented in later versions of astropy without explicitly updating the package template.