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

class fermipy.gtanalysis.GTAnalysis(config, roi=None, **kwargs)[source]

Bases: fermipy.config.Configurable, fermipy.sed.SEDGenerator, fermipy.residmap.ResidMapGenerator, fermipy.tsmap.TSMapGenerator, fermipy.tsmap.TSCubeGenerator, fermipy.sourcefind.SourceFind, fermipy.extension.ExtensionFit, fermipy.lightcurve.LightCurve

High-level analysis interface that manages a set of analysis component objects. Most of the functionality of the Fermipy package is provided through the methods of this class. The class constructor accepts a dictionary that defines the configuration for the analysis. Keyword arguments to the constructor can be used to override parameters in the configuration dictionary.

add_gauss_prior(name, parName, mean, sigma)[source]
add_source(name, src_dict, free=None, init_source=True, save_source_maps=True, use_pylike=True, use_single_psf=False, **kwargs)[source]

Add a source to the ROI model. This function may be called either before or after setup.

Parameters:
  • name (str) – Source name.
  • src_dict (dict or Source object) – Dictionary or source object defining the source properties (coordinates, spectral parameters, etc.).
  • free (bool) – Initialize the source with a free normalization parameter.
  • use_pylike (bool) – Create source maps with pyLikelihood.
  • use_single_psf (bool) – Use the PSF model calculated for the ROI center. If false then a new model will be generated using the position of the source.
add_sources_from_roi(names, roi, free=False, **kwargs)[source]

Add multiple sources to the current ROI model copied from another ROI model.

Parameters:
  • names (list) – List of str source names to add.
  • roi (ROIModel object) – The roi model from which to add sources.
  • free (bool) – Initialize the source with a free normalization paramter.
bowtie(name, fd=None, loge=None)[source]

Generate a spectral uncertainty band (bowtie) for the given source. This will create an uncertainty band on the differential flux as a function of energy by propagating the errors on the global fit parameters. Note that this band only reflects the uncertainty for parameters that are currently free in the model.

Parameters:
  • name (str) – Source name.
  • fd (FluxDensity) – Flux density object. If this parameter is None then one will be created.
  • loge (array-like) – Sequence of energies in log10(E/MeV) at which the flux band will be evaluated.
cleanup()[source]
clone(config, **kwargs)[source]

Make a clone of this analysis instance.

components

Return the list of analysis components.

config

Return the configuration dictionary of this class.

configdir
configure(config, **kwargs)
constrain_norms(srcNames, cov_scale=1.0)[source]

Constrain the normalizations of one or more sources by adding gaussian priors with sigma equal to the parameter error times a scaling factor.

counts_map()[source]

Return a Map representation of the counts map.

Returns:map
Return type:Map
classmethod create(infile, config=None)[source]

Create a new instance of GTAnalysis from an analysis output file generated with write_roi. By default the new instance will inherit the configuration of the saved analysis instance. The configuration may be overriden by passing a configuration file path with the config argument.

Parameters:
  • infile (str) – Path to the ROI results file.
  • config (str) – Path to a configuration file. This will override the configuration in the ROI results file.
create_roi_table()[source]
curvature(name, **kwargs)[source]

Test whether a source shows spectral curvature by comparing the likelihood ratio of PowerLaw and LogParabola spectral models.

Parameters:name (str) – Source name.
defaults = {'binning': {'projtype': ('WCS', 'Projection mode (WCS or HPX).', <type 'str'>), 'binsperdec': (8, 'Number of energy bins per decade.', <type 'float'>), 'enumbins': (None, 'Number of energy bins. If none this will be inferred from energy range and ``binsperdec`` parameter.', <type 'int'>), 'roiwidth': (10.0, 'Width of the ROI in degrees. The number of pixels in each spatial dimension will be set from ``roiwidth`` / ``binsz`` (rounded up).', <type 'float'>), 'hpx_ebin': (True, 'Include energy binning', <type 'bool'>), 'binsz': (0.1, 'Spatial bin size in degrees.', <type 'float'>), 'npix': (None, 'Number of pixels. If none then this will be set from ``roiwidth`` and ``binsz``.', <type 'int'>), 'hpx_order': (10, 'Order of the map (int between 0 and 12, included)', <type 'int'>), 'proj': ('AIT', 'Spatial projection for WCS mode.', <type 'str'>), 'coordsys': ('CEL', 'Coordinate system of the spatial projection (CEL or GAL).', <type 'str'>), 'hpx_ordering_scheme': ('RING', 'HEALPix Ordering Scheme', <type 'str'>)}, 'components': (None, '', <type 'list'>), 'data': {'evfile': (None, 'Path to FT1 file or list of FT1 files.', <type 'str'>), 'cacheft1': (True, 'Cache FT1 files when performing binned analysis. If false then only the counts cube is retained.', <type 'bool'>), 'scfile': (None, 'Path to FT2 (spacecraft) file.', <type 'str'>), 'ltcube': (None, 'Path to livetime cube. If none a livetime cube will be generated with ``gtmktime``.', <type 'str'>)}, 'extension': {'free_radius': (None, 'Free normalizations of background sources within this angular distance in degrees from the source of interest. If None then no sources will be freed.', <type 'float'>), 'save_model_map': (False, 'Save model counts cubes for the best-fit model of extension.', <type 'bool'>), 'write_fits': (True, 'Write the output to a FITS file.', <type 'bool'>), 'psf_scale_fn': (None, "Tuple of two vectors (logE,f) defining an energy-dependent PSF scaling function that will be applied when building spatial models for the source of interest. The tuple (logE,f) defines the fractional corrections f at the sequence of energies logE = log10(E/MeV) where f=0 corresponds to no correction. The correction function f(E) is evaluated by linearly interpolating the fractional correction factors f in log(E). The corrected PSF is given by P'(x;E) = P(x/(1+f(E));E) where x is the angular separation.", <type 'tuple'>), 'width_min': (0.01, 'Minimum value in degrees for the likelihood scan over spatial extent.', <type 'float'>), 'make_plots': (False, 'Generate diagnostic plots.', <type 'bool'>), 'free_background': (False, 'Leave background parameters free when performing the fit. If True then any parameters that are currently free in the model will be fit simultaneously with the source of interest.', <type 'bool'>), 'fit_position': (False, 'Perform a simultaneous fit to the source position and extension.', <type 'bool'>), 'update': (False, 'Update this source with the best-fit model for spatial extension if TS_ext > ``tsext_threshold``.', <type 'bool'>), 'width': (None, 'Sequence of values in degrees for the likelihood scan over spatial extension (68% containment radius). If this argument is None then the scan points will be determined from width_min/width_max/width_nstep.', <type 'list'>), 'fix_shape': (False, 'Fix spectral shape parameters of the source of interest. If True then only the normalization parameter will be fit.', <type 'bool'>), 'write_npy': (True, 'Write the output dictionary to a numpy file.', <type 'bool'>), 'width_max': (1.0, 'Maximum value in degrees for the likelihood scan over spatial extent.', <type 'float'>), 'sqrt_ts_threshold': (None, 'Threshold on sqrt(TS_ext) that will be applied when ``update`` is True. If None then nothreshold is applied.', <type 'float'>), 'spatial_model': ('RadialGaussian', 'Spatial model that will be used to test the sourceextension. The spatial scale parameter of the model will be set such that the 68% containment radius of the model is equal to the width parameter.', <type 'str'>), 'fit_ebin': (False, 'Perform a fit for the angular extension in each analysis energy bin.', <type 'bool'>), 'make_tsmap': (True, 'Make a TS map for the source of interest.', <type 'bool'>), 'width_nstep': (21, 'Number of scan points between width_min and width_max. Scan points will be spaced evenly on a logarithmic scale between `width_min` and `width_max`.', <type 'int'>)}, 'fileio': {'usescratch': (False, 'Run analysis in a temporary working directory under ``scratchdir``.', <type 'bool'>), 'scratchdir': ('/scratch', 'Path to the scratch directory. If ``usescratch`` is True then a temporary working directory will be created under this directory.', <type 'str'>), 'savefits': (True, 'Save intermediate FITS files.', <type 'bool'>), 'workdir': (None, 'Path to the working directory.', <type '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.', <type 'list'>), '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.', <type 'list'>), 'logfile': (None, 'Path to log file. If None then log will be written to fermipy.log.', <type 'str'>), 'outdir': (None, 'Path of the output directory. If none this will default to the directory containing the configuration file.', <type 'str'>)}, 'gtlike': {'irfs': (None, 'Set the IRF string.', <type 'str'>), 'minbinsz': (0.05, 'Set the minimum bin size used for resampling diffuse maps.', <type 'float'>), 'use_scaled_srcmap': (False, 'Generate source map by scaling an external srcmap file.', <type 'bool'>), 'use_external_srcmap': (False, 'Use an external precomputed source map file.', <type 'bool'>), 'resample': (True, '', <type 'bool'>), 'srcmap_base': (None, 'Set the baseline source maps file. This will be used to generate a scaled source map.', <type 'str'>), 'edisp_disable': (None, 'Provide a list of sources for which the edisp correction should be disabled.', <type 'list'>), 'expscale': (None, 'Exposure correction that is applied to all sources in the analysis component. This correction is superseded by `src_expscale` if it is defined for a source.', <type 'float'>), 'bexpmap': (None, '', <type 'str'>), 'llscan_npts': (20, 'Number of evaluation points to use when performing a likelihood scan.', <type 'int'>), 'bexpmap_roi': (None, '', <type 'str'>), 'edisp': (True, 'Enable the correction for energy dispersion.', <type 'bool'>), 'srcmap': (None, 'Set the source maps file. When defined this file will be used instead of the local source maps file.', <type 'str'>), 'src_expscale': (None, 'Dictionary of exposure corrections for individual sources keyed to source name. The exposure for a given source will be scaled by this value. A value of 1.0 corresponds to the nominal exposure.', <type 'dict'>), 'bexpmap_roi_base': (None, 'Set the basline ROI expoure map file. This will be used to generate a scaled source map.', <type 'str'>), 'convolve': (True, '', <type 'bool'>), 'rfactor': (2, '', <type 'int'>), 'bexpmap_base': (None, 'Set the basline all-sky expoure map file. This will be used to generate a scaled source map.', <type 'str'>), 'wmap': (None, 'Likelihood weights map.', <type 'str'>)}, 'lightcurve': {'free_radius': (None, 'Free normalizations of background sources within this angular distance in degrees from the source of interest. If None then no sources will be freed.', <type 'float'>), 'nbins': (None, 'Set the number of lightcurve bins. The total time range will be evenly split into this number of time bins.', <type 'int'>), 'use_scaled_srcmap': (False, 'Generate approximate source maps for each time bin by scaling the current source maps by the exposure ratio with respect to that time bin.', <type 'bool'>), 'systematic': (0.02, 'Systematic correction factor for TS:subscript:`var`. See Sect. 3.6 in 2FGL for details.', <type 'float'>), 'free_sources': (None, 'List of sources to be freed. These sources will be added to the list of sources satisfying the free_radius selection.', <type 'list'>), 'free_background': (False, 'Leave background parameters free when performing the fit. If True then any parameters that are currently free in the model will be fit simultaneously with the source of interest.', <type 'bool'>), 'max_free_sources': (5, 'Maximum number of sources that will be fit simultaneously with the source of interest.', <type 'int'>), 'make_plots': (False, 'Generate diagnostic plots.', <type 'bool'>), 'nthread': (None, 'Number of processes to create when multithread is True. If None then one process will be created for each available core.', <type 'int'>), 'multithread': (False, 'Split the calculation across number of processes set by nthread option.', <type 'bool'>), 'binsz': (86400.0, 'Set the lightcurve bin size in seconds.', <type 'float'>), 'time_bins': (None, 'Set the lightcurve bin edge sequence in MET. This option takes precedence over binsz and nbins.', <type 'list'>), 'write_fits': (True, 'Write the output to a FITS file.', <type 'bool'>), 'use_local_ltcube': (True, 'Generate a fast LT cube.', <type 'bool'>), 'free_params': (None, 'Set the parameters of the source of interest that will be re-fit in each time bin. If this list is empty then all parameters will be freed.', <type 'list'>), 'save_bin_data': (True, 'Save analysis directories for individual time bins. If False then only the analysis results table will be saved.', <type 'bool'>), 'shape_ts_threshold': (16.0, 'Set the TS threshold at which shape parameters of sources will be freed. If a source is detected with TS less than this value then its shape parameters will be fixed to values derived from the analysis of the full time range.', <type 'float'>), 'write_npy': (True, 'Write the output dictionary to a numpy file.', <type 'bool'>), 'outdir': (None, 'Store all data in this directory (e.g. "30days"). If None then use current directory.', <type 'str'>)}, 'localize': {'free_radius': (None, 'Free normalizations of background sources within this angular distance in degrees from the source of interest. If None then no sources will be freed.', <type 'float'>), 'dtheta_max': (0.5, 'Half-width of the search region in degrees used for the first pass of the localization search.', <type 'float'>), 'fix_shape': (False, 'Fix spectral shape parameters of the source of interest. If True then only the normalization parameter will be fit.', <type 'bool'>), 'write_fits': (True, 'Write the output to a FITS file.', <type 'bool'>), 'make_plots': (False, 'Generate diagnostic plots.', <type 'bool'>), 'free_background': (False, 'Leave background parameters free when performing the fit. If True then any parameters that are currently free in the model will be fit simultaneously with the source of interest.', <type 'bool'>), 'nstep': (5, 'Number of steps in longitude/latitude that will be taken when refining the source position. The bounds of the scan range are set to the 99% positional uncertainty as determined from the TS map peak fit. The total number of sampling points will be nstep**2.', <type 'int'>), 'write_npy': (True, 'Write the output dictionary to a numpy file.', <type 'bool'>), 'update': (True, 'Update the source model with the best-fit position.', <type 'bool'>)}, 'logging': {'prefix': ('', 'Prefix that will be appended to the logger name.', <type 'str'>), 'chatter': (3, 'Set the chatter parameter of the STs.', <type 'int'>), 'verbosity': (3, '', <type 'int'>)}, 'ltcube': {'binsz': (1.0, 'Set the angular bin size for generating livetime cubes.', <type 'float'>), 'dcostheta': (0.025, 'Set the inclination angle binning represented as the cosine of the off-axis angle.', <type 'float'>), 'phibins': (0, 'Set the number of phi bins for generating livetime cubes.', <type 'int'>), 'use_local_ltcube': (False, 'Generate a livetime cube in the vicinity of the ROI using interpolation. This option disables LT cube generation with gtltcube.', <type 'bool'>)}, 'mc': {'seed': (None, '', <type 'int'>)}, 'model': {'catalogs': (None, '', <type 'list'>), 'limbdiff': (None, '', <type 'list'>), 'src_radius_roi': (None, 'Half-width of ``src_roiwidth`` selection. This parameter can be used in lieu of ``src_roiwidth``.', <type 'float'>), '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.', <type 'str'>), 'sources': (None, '', <type '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.', <type 'bool'>), 'assoc_xmatch_columns': (['3FGL_Name'], 'Choose a set of association columns on which to cross-match catalogs.', <type 'list'>), 'diffuse': (None, '', <type 'list'>), '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.', <type 'float'>), 'isodiff': (None, 'Set the path to one or more isotropic templates. A separate component will be generated for each item in this list.', <type '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.', <type 'list'>), 'extract_diffuse': (False, 'Extract a copy of all mapcube components centered on the ROI.', <type 'bool'>), '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.', <type 'float'>), 'diffuse_dir': (None, '', <type 'list'>)}, 'optimizer': {'retries': (3, 'Set the number of times to retry the fit when the fit quality is less than ``min_fit_quality``.', <type 'int'>), 'optimizer': ('MINUIT', 'Set the optimization algorithm to use when maximizing the likelihood function.', <type 'str'>), 'verbosity': (0, '', <type 'int'>), 'max_iter': (100, 'Maximum number of iterations for the Newtons method fitter.', <type 'int'>), 'min_fit_quality': (2, 'Set the minimum fit quality.', <type 'int'>), 'tol': (0.001, 'Set the optimizer tolerance.', <type 'float'>), 'init_lambda': (0.0001, 'Initial value of damping parameter for step size calculation when using the NEWTON fitter. A value of zero disables damping.', <type 'float'>)}, 'plotting': {'graticule_radii': (None, 'Define a list of radii at which circular graticules will be drawn.', <type 'list'>), 'cmap': ('magma', 'Set the colormap for 2D plots.', <type 'str'>), 'catalogs': (None, '', <type 'list'>), 'cmap_resid': ('RdBu_r', 'Set the colormap for 2D residual plots.', <type 'str'>), 'format': ('png', '', <type 'str'>), 'figsize': ([8.0, 6.0], 'Set the default figure size.', <type 'list'>), 'label_ts_threshold': (0.0, 'TS threshold for labeling sources in sky maps. If None then no sources will be labeled.', <type 'float'>), 'loge_bounds': (None, '', <type 'list'>), 'interactive': (False, 'Enable interactive mode. If True then plots will be drawn after each plotting command.', <type 'bool'>)}, 'residmap': {'make_plots': (False, 'Generate diagnostic plots.', <type 'bool'>), 'loge_bounds': (None, 'Restrict the analysis to an energy range (emin,emax) in log10(E/MeV) that is a subset of the analysis energy range. By default the full analysis energy range will be used. If either emin/emax are None then only an upper/lower bound on the energy range wil be applied.', <type 'list'>), 'write_fits': (True, 'Write the output to a FITS file.', <type 'bool'>), 'exclude': (None, 'List of sources that will be removed from the model when computing the residual map.', <type 'list'>), 'model': (None, 'Dictionary defining the spatial/spectral properties of the test source. If model is None the test source will be a PointSource with an Index 2 power-law spectrum.', <type 'dict'>), 'use_weights': (False, 'Used weighted version of maps in making plots.', <type 'bool'>), 'write_npy': (True, 'Write the output dictionary to a numpy file.', <type 'bool'>)}, 'roiopt': {'npred_frac': (0.95, '', <type 'float'>), 'shape_ts_threshold': (25.0, 'Threshold on source TS used for determining the sources that will be fit in the third optimization step.', <type 'float'>), 'npred_threshold': (1.0, '', <type 'float'>), 'skip': (None, 'List of str source names to skip while optimizing.', <type 'list'>), 'max_free_sources': (5, 'Maximum number of sources that will be fit simultaneously in the first optimization step.', <type 'int'>)}, 'sed': {'free_radius': (None, 'Free normalizations of background sources within this angular distance in degrees from the source of interest. If None then no sources will be freed.', <type 'float'>), 'use_local_index': (False, 'Use a power-law approximation to the shape of the global spectrum in each bin. If this is false then a constant index set to `bin_index` will be used.', <type 'bool'>), 'free_pars': (None, 'Set the parameters of the source of interest that will be freed when performing the global fit. By default all parameters will be freed.', <type 'list'>), 'write_fits': (True, 'Write the output to a FITS file.', <type 'bool'>), 'cov_scale': (3.0, 'Scale factor that sets the strength of the prior on nuisance parameters that are free. Setting this to None disables the prior.', <type 'float'>), 'ul_confidence': (0.95, 'Confidence level for flux upper limit.', <type 'float'>), 'make_plots': (False, 'Generate diagnostic plots.', <type 'bool'>), 'free_background': (False, 'Leave background parameters free when performing the fit. If True then any parameters that are currently free in the model will be fit simultaneously with the source of interest.', <type 'bool'>), 'bin_index': (2.0, 'Spectral index that will be use when fitting the energy distribution within an energy bin.', <type 'float'>), 'write_npy': (True, 'Write the output dictionary to a numpy file.', <type 'bool'>)}, 'selection': {'radius': (None, 'Radius of data selection. If none this will be automatically set from the ROI size.', <type 'float'>), 'tmin': (None, 'Minimum time (MET).', <type 'int'>), 'target': (None, 'Choose an object on which to center the ROI. This option takes precendence over ra/dec or glon/glat.', <type 'str'>), 'glon': (None, '', <type 'float'>), 'emin': (None, 'Minimum Energy (MeV)', <type 'float'>), 'emax': (None, 'Maximum Energy (MeV)', <type 'float'>), 'tmax': (None, 'Maximum time (MET).', <type 'int'>), 'glat': (None, '', <type 'float'>), 'phasemax': (None, 'Maximum pulsar phase', <type 'float'>), 'filter': (None, 'Filter string for ``gtmktime`` selection.', <type 'str'>), 'phasemin': (None, 'Minimum pulsar phase', <type 'float'>), 'logemax': (None, 'Maximum Energy (log10(MeV))', <type 'float'>), 'ra': (None, '', <type 'float'>), 'evtype': (None, 'Event type selection.', <type 'int'>), 'evclass': (None, 'Event class selection.', <type 'int'>), 'zmax': (None, 'Maximum zenith angle.', <type 'float'>), 'logemin': (None, 'Minimum Energy (log10(MeV))', <type 'float'>), 'dec': (None, '', <type 'float'>), 'roicut': ('no', '', <type 'str'>), 'convtype': (None, 'Conversion type selection.', <type 'int'>)}, 'sourcefind': {'tsmap_fitter': ('tsmap', 'Set the method for generating the TS map. Valid options are tsmap or tscube.', <type 'str'>), 'multithread': (False, 'Split the calculation across number of processes set by nthread option.', <type 'bool'>), 'sources_per_iter': (4, 'Maximum number of sources that will be added in each iteration. If the number of detected peaks in a given iteration is larger than this number, only the N peaks with the largest TS will be used as seeds for the current iteration.', <type 'int'>), 'sqrt_ts_threshold': (5.0, 'Source threshold in sqrt(TS). Only peaks with sqrt(TS) exceeding this threshold will be used as seeds for new sources.', <type 'float'>), 'free_params': (None, '', <type 'list'>), 'model': (None, 'Dictionary defining the spatial/spectral properties of the test source. If model is None the test source will be a PointSource with an Index 2 power-law spectrum.', <type 'dict'>), 'max_iter': (5, 'Maximum number of source finding iterations. The source finder will continue adding sources until no additional peaks are found or the number of iterations exceeds this number.', <type 'int'>), 'min_separation': (1.0, 'Minimum separation in degrees between sources detected in each iteration. The source finder will look for the maximum peak in the TS map within a circular region of this radius.', <type 'float'>), 'nthread': (None, 'Number of processes to create when multithread is True. If None then one process will be created for each available core.', <type 'int'>)}, 'tscube': {'do_sed': (True, 'Compute the energy bin-by-bin fits', <type 'bool'>), 'remake_test_source': (False, 'If true, recomputes the test source image (otherwise just shifts it)', <type 'bool'>), 'st_scan_level': (0, 'Level to which to do ST-based fitting (for testing)', <type 'int'>), 'cov_scale': (-1.0, 'Scale factor to apply to broadband fitting cov. matrix in bin-by-bin fits ( < 0 -> fixed ) ', <type 'float'>), 'max_iter': (30, 'Maximum number of iterations for the Newtons method fitter.', <type 'int'>), 'nnorm': (10, 'Number of points in the likelihood v. normalization scan', <type 'int'>), 'norm_sigma': (5.0, 'Number of sigma to use for the scan range ', <type 'float'>), 'tol_type': (0, 'Absoulte (0) or relative (1) criteria for convergence.', <type 'int'>), 'cov_scale_bb': (-1.0, 'Scale factor to apply to global fitting cov. matrix in broadband fits. ( < 0 -> no prior ) ', <type 'float'>), 'tol': (0.001, 'Critetia for fit convergence (estimated vertical distance to min < tol )', <type 'float'>), 'model': (None, 'Dictionary defining the spatial/spectral properties of the test source. If model is None the test source will be a PointSource with an Index 2 power-law spectrum.', <type 'dict'>), 'init_lambda': (0, 'Initial value of damping parameter for newton step size calculation. A value of zero disables damping.', <type 'float'>)}, 'tsmap': {'multithread': (False, 'Split the calculation across number of processes set by nthread option.', <type 'bool'>), 'loge_bounds': (None, 'Restrict the analysis to an energy range (emin,emax) in log10(E/MeV) that is a subset of the analysis energy range. By default the full analysis energy range will be used. If either emin/emax are None then only an upper/lower bound on the energy range wil be applied.', <type 'list'>), 'write_fits': (True, 'Write the output to a FITS file.', <type 'bool'>), 'make_plots': (False, 'Generate diagnostic plots.', <type 'bool'>), 'exclude': (None, 'List of sources that will be removed from the model when computing the TS map.', <type 'list'>), 'model': (None, 'Dictionary defining the spatial/spectral properties of the test source. If model is None the test source will be a PointSource with an Index 2 power-law spectrum.', <type 'dict'>), 'write_npy': (True, 'Write the output dictionary to a numpy file.', <type 'bool'>), 'nthread': (None, 'Number of processes to create when multithread is True. If None then one process will be created for each available core.', <type 'int'>), 'max_kernel_radius': (3.0, 'Set the maximum radius of the test source kernel. Using a smaller value will speed up the TS calculation at the loss of accuracy.', <type 'float'>)}}
delete_source(name, save_template=True, delete_source_map=False, build_fixed_wts=True, **kwargs)[source]

Delete a source from the ROI model.

Parameters:
  • name (str) – Source name.
  • save_template (bool) – Keep the SpatialMap FITS template associated with this source.
  • delete_source_map (bool) – Delete the source map associated with this source from the source maps file.
Returns:

src – The deleted source object.

Return type:

Model

delete_sources(cuts=None, distance=None, skydir=None, minmax_ts=None, minmax_npred=None, exclude=None, square=False, names=None)[source]

Delete sources in the ROI model satisfying the given selection criteria.

Parameters:
  • cuts (dict) – Dictionary of [min,max] selections on source properties.
  • distance (float) – Cut on angular distance from skydir. If None then no selection will be applied.
  • skydir (SkyCoord) – Reference sky coordinate for distance selection. If None then the distance selection will be applied with respect to the ROI center.
  • minmax_ts (list) – Select sources that have TS in the range [min,max]. If either min or max are None then only a lower (upper) bound will be applied. If this parameter is none no selection will be applied.
  • minmax_npred (list) – Select sources that have npred in the range [min,max]. If either min or max are None then only a lower (upper) bound will be applied. If this parameter is none no selection will be applied.
  • square (bool) – Switch between applying a circular or square (ROI-like) selection on the maximum projected distance from the ROI center.
  • names (list) – Select sources matching a name in this list.
Returns:

srcs – A list of Model objects.

Return type:

list

delete_workdir()[source]
energies

Return the energy bin edges in MeV.

enumbins

Return the number of energy bins.

extension(name, **kwargs)

Test this source for spatial extension with the likelihood ratio method (TS_ext). This method will substitute an extended spatial model for the given source and perform a one-dimensional scan of the spatial extension parameter over the range specified with the width parameters. The 1-D profile likelihood is then used to compute the best-fit value, upper limit, and TS for extension. The nuisance parameters that will be simultaneously fit when performing the spatial scan can be controlled with the fix_shape, free_background, and free_radius options. By default the position of the source will be fixed to its current position. A simultaneous fit to position and extension can be performed by setting fit_position to True.

Parameters:
  • name (str) – Source name.
  • fit_ebin (bool) – Perform a fit for the angular extension in each analysis energy bin. (default : False)
  • fit_position (bool) – Perform a simultaneous fit to the source position and extension. (default : False)
  • fix_shape (bool) – Fix spectral shape parameters of the source of interest. If True then only the normalization parameter will be fit. (default : False)
  • free_background (bool) – Leave background parameters free when performing the fit. If True then any parameters that are currently free in the model will be fit simultaneously with the source of interest. (default : False)
  • free_radius (float) – Free normalizations of background sources within this angular distance in degrees from the source of interest. If None then no sources will be freed. (default : None)
  • make_plots (bool) – Generate diagnostic plots. (default : False)
  • make_tsmap (bool) – Make a TS map for the source of interest. (default : True)
  • psf_scale_fn (tuple) – Tuple of two vectors (logE,f) defining an energy-dependent PSF scaling function that will be applied when building spatial models for the source of interest. The tuple (logE,f) defines the fractional corrections f at the sequence of energies logE = log10(E/MeV) where f=0 corresponds to no correction. The correction function f(E) is evaluated by linearly interpolating the fractional correction factors f in log(E). The corrected PSF is given by P’(x;E) = P(x/(1+f(E));E) where x is the angular separation. (default : None)
  • save_model_map (bool) – Save model counts cubes for the best-fit model of extension. (default : False)
  • spatial_model (str) – Spatial model that will be used to test the sourceextension. The spatial scale parameter of the model will be set such that the 68% containment radius of the model is equal to the width parameter. (default : RadialGaussian)
  • sqrt_ts_threshold (float) – Threshold on sqrt(TS_ext) that will be applied when update is True. If None then nothreshold is applied. (default : None)
  • update (bool) – Update this source with the best-fit model for spatial extension if TS_ext > tsext_threshold. (default : False)
  • width (list) – Sequence of values in degrees for the likelihood scan over spatial extension (68% containment radius). If this argument is None then the scan points will be determined from width_min/width_max/width_nstep. (default : None)
  • width_max (float) – Maximum value in degrees for the likelihood scan over spatial extent. (default : 1.0)
  • width_min (float) – Minimum value in degrees for the likelihood scan over spatial extent. (default : 0.01)
  • width_nstep (int) – Number of scan points between width_min and width_max. Scan points will be spaced evenly on a logarithmic scale between width_min and width_max. (default : 21)
  • write_fits (bool) – Write the output to a FITS file. (default : True)
  • write_npy (bool) – Write the output dictionary to a numpy file. (default : True)
  • optimizer (dict) – Dictionary that overrides the default optimizer settings.
Returns:

extension – Dictionary containing results of the extension analysis. The same dictionary is also saved to the dictionary of this source under ‘extension’.

Return type:

dict

files
find_sources(prefix='', **kwargs)

An iterative source-finding algorithm that uses likelihood ratio (TS) maps of the region of interest to find new sources. After each iteration a new TS map is generated incorporating sources found in the previous iteration. The method stops when the number of iterations exceeds max_iter or no sources exceeding sqrt_ts_threshold are found.

Parameters:
  • free_params (list) – (default : None)
  • max_iter (int) – Maximum number of source finding iterations. The source finder will continue adding sources until no additional peaks are found or the number of iterations exceeds this number. (default : 5)
  • min_separation (float) – Minimum separation in degrees between sources detected in each iteration. The source finder will look for the maximum peak in the TS map within a circular region of this radius. (default : 1.0)
  • model (dict) – Dictionary defining the spatial/spectral properties of the test source. If model is None the test source will be a PointSource with an Index 2 power-law spectrum. (default : None)
  • multithread (bool) – Split the calculation across number of processes set by nthread option. (default : False)
  • nthread (int) – Number of processes to create when multithread is True. If None then one process will be created for each available core. (default : None)
  • sources_per_iter (int) – Maximum number of sources that will be added in each iteration. If the number of detected peaks in a given iteration is larger than this number, only the N peaks with the largest TS will be used as seeds for the current iteration. (default : 4)
  • sqrt_ts_threshold (float) – Source threshold in sqrt(TS). Only peaks with sqrt(TS) exceeding this threshold will be used as seeds for new sources. (default : 5.0)
  • tsmap_fitter (str) – Set the method for generating the TS map. Valid options are tsmap or tscube. (default : tsmap)
  • tsmap (dict) – Keyword arguments dictionary for tsmap method.
  • tscube (dict) – Keyword arguments dictionary for tscube method.
Returns:

  • peaks (list) – List of peak objects.
  • sources (list) – List of source objects.

fit(update=True, **kwargs)[source]

Run the likelihood optimization. This will execute a fit of all parameters that are currently free in the model and update the charateristics of the corresponding model components (TS, npred, etc.). The fit will be repeated N times (set with the retries parameter) until a fit quality greater than or equal to min_fit_quality and a fit status code of 0 is obtained. If the fit does not succeed after N retries then all parameter values will be reverted to their state prior to the execution of the fit.

Parameters:
  • update (bool) – Update the model dictionary for all sources with free parameters.
  • tol (float) – Set the optimizer tolerance.
  • verbosity (int) – Set the optimizer output level.
  • optimizer (str) – Set the likelihood optimizer (e.g. MINUIT or NEWMINUIT).
  • retries (int) – Set the number of times to rerun the fit when the fit quality is < 3.
  • min_fit_quality (int) – Set the minimum fit quality. If the fit quality is smaller than this value then all model parameters will be restored to their values prior to the fit.
  • reoptimize (bool) – Refit background sources when updating source properties (TS and likelihood profiles).
Returns:

fit – Dictionary containing diagnostic information from the fit (fit quality, parameter covariances, etc.).

Return type:

dict

fit_correlation()[source]
free_index(name, free=True, **kwargs)[source]

Free/Fix index of a source.

Parameters:
  • name (str) – Source name.
  • free (bool) – Choose whether to free (free=True) or fix (free=False).
free_norm(name, free=True, **kwargs)[source]

Free/Fix normalization of a source.

Parameters:
  • name (str) – Source name.
  • free (bool) – Choose whether to free (free=True) or fix (free=False).
free_parameter(name, par, free=True)[source]

Free/Fix a parameter of a source by name.

Parameters:
  • name (str) – Source name.
  • par (str) – Parameter name.
free_shape(name, free=True, **kwargs)[source]

Free/Fix shape parameters of a source.

Parameters:
  • name (str) – Source name.
  • free (bool) – Choose whether to free (free=True) or fix (free=False).
free_source(name, free=True, pars=None, **kwargs)[source]

Free/Fix parameters of a source.

Parameters:
  • name (str) – Source name.
  • free (bool) – Choose whether to free (free=True) or fix (free=False) source parameters.
  • pars (list) – Set a list of parameters to be freed/fixed for this source. If none then all source parameters will be freed/fixed with the exception of those defined in the skip_pars list.
free_sources(free=True, pars=None, cuts=None, distance=None, skydir=None, minmax_ts=None, minmax_npred=None, exclude=None, square=False, **kwargs)[source]

Free or fix sources in the ROI model satisfying the given selection. When multiple selections are defined, the selected sources will be those satisfying the logical AND of all selections (e.g. distance < X && minmax_ts[0] < ts < minmax_ts[1] && …).

Parameters:
  • free (bool) – Choose whether to free (free=True) or fix (free=False) source parameters.
  • pars (list) – Set a list of parameters to be freed/fixed for each source. If none then all source parameters will be freed/fixed. If pars=’norm’ then only normalization parameters will be freed.
  • cuts (dict) – Dictionary of [min,max] selections on source properties.
  • distance (float) – Cut on angular distance from skydir. If None then no selection will be applied.
  • skydir (SkyCoord) – Reference sky coordinate for distance selection. If None then the distance selection will be applied with respect to the ROI center.
  • minmax_ts (list) – Free sources that have TS in the range [min,max]. If either min or max are None then only a lower (upper) bound will be applied. If this parameter is none no selection will be applied.
  • minmax_npred (list) – Free sources that have npred in the range [min,max]. If either min or max are None then only a lower (upper) bound will be applied. If this parameter is none no selection will be applied.
  • exclude (list) – Names of sources that will be excluded from the selection.
  • square (bool) – Switch between applying a circular or square (ROI-like) selection on the maximum projected distance from the ROI center.
Returns:

srcs – A list of Model objects.

Return type:

list

free_sources_by_name(names, free=True, pars=None, **kwargs)[source]

Free all sources with names matching names.

Parameters:
  • names (list) – List of source names.
  • free (bool) – Choose whether to free (free=True) or fix (free=False) source parameters.
  • pars (list) – Set a list of parameters to be freed/fixed for each source. If none then all source parameters will be freed/fixed. If pars=’norm’ then only normalization parameters will be freed.
Returns:

srcs – A list of Model objects.

Return type:

list

generate_model(model_name=None)[source]

Generate model maps for all components. model_name should be a unique identifier for the model. If model_name is None then the model maps will be generated using the current parameters of the ROI.

geom

ROI geometry.

classmethod get_config()

Return a default configuration dictionary for this class.

get_free_param_vector()[source]
get_free_source_params(name)[source]
get_norm(name)[source]
get_params(freeonly=False)[source]
get_source_dnde(name)[source]

Return differential flux distribution of a source. For sources with FileFunction spectral type this returns the internal differential flux array.

Returns:
  • loge (ndarray) – Array of energies at which the differential flux is evaluated (log10(E/MeV)).
  • dnde (ndarray) – Array of differential flux values (cm^{-2} s^{-1} MeV^{-1}) evaluated at energies in loge.
get_source_name(name)[source]

Return the name of a source as it is defined in the pyLikelihood model object.

get_source_params(name)[source]
get_sources(cuts=None, distance=None, skydir=None, minmax_ts=None, minmax_npred=None, exclude=None, square=False)[source]

Retrieve list of sources in the ROI satisfying the given selections.

Returns:srcs – A list of Model objects.
Return type:list
get_src_model(name, paramsonly=False, reoptimize=False, npts=None, **kwargs)[source]

Compose a dictionary for a source with the current best-fit parameters.

Parameters:
  • name (str) –
  • paramsonly (bool) – Skip computing TS and likelihood profile.
  • reoptimize (bool) – Re-fit background parameters in likelihood scan.
  • npts (int) – Number of points for likelihood scan.
Returns:

src_dict

Return type:

dict

lightcurve(name, **kwargs)

Generate a lightcurve for the named source. The function will complete the basic analysis steps for each bin and perform a likelihood fit for each bin. Extracted values (along with errors) are Integral Flux, spectral model, Spectral index, TS value, pred. # of photons. Note: successful calculation of TS:subscript:var requires at least one free background parameter and a previously optimized ROI model.

Parameters:
  • name (str) – source name
  • binsz (float) – Set the lightcurve bin size in seconds. (default : 86400.0)
  • free_background (bool) – Leave background parameters free when performing the fit. If True then any parameters that are currently free in the model will be fit simultaneously with the source of interest. (default : False)
  • free_params (list) – Set the parameters of the source of interest that will be re-fit in each time bin. If this list is empty then all parameters will be freed. (default : None)
  • free_radius (float) – Free normalizations of background sources within this angular distance in degrees from the source of interest. If None then no sources will be freed. (default : None)
  • free_sources (list) – List of sources to be freed. These sources will be added to the list of sources satisfying the free_radius selection. (default : None)
  • make_plots (bool) – Generate diagnostic plots. (default : False)
  • max_free_sources (int) – Maximum number of sources that will be fit simultaneously with the source of interest. (default : 5)
  • multithread (bool) – Split the calculation across number of processes set by nthread option. (default : False)
  • nbins (int) – Set the number of lightcurve bins. The total time range will be evenly split into this number of time bins. (default : None)
  • nthread (int) – Number of processes to create when multithread is True. If None then one process will be created for each available core. (default : None)
  • outdir (str) – Store all data in this directory (e.g. “30days”). If None then use current directory. (default : None)
  • save_bin_data (bool) – Save analysis directories for individual time bins. If False then only the analysis results table will be saved. (default : True)
  • shape_ts_threshold (float) – Set the TS threshold at which shape parameters of sources will be freed. If a source is detected with TS less than this value then its shape parameters will be fixed to values derived from the analysis of the full time range. (default : 16.0)
  • systematic (float) – Systematic correction factor for TS:subscript:var. See Sect. 3.6 in 2FGL for details. (default : 0.02)
  • time_bins (list) – Set the lightcurve bin edge sequence in MET. This option takes precedence over binsz and nbins. (default : None)
  • use_local_ltcube (bool) – Generate a fast LT cube. (default : True)
  • use_scaled_srcmap (bool) – Generate approximate source maps for each time bin by scaling the current source maps by the exposure ratio with respect to that time bin. (default : False)
  • write_fits (bool) – Write the output to a FITS file. (default : True)
  • write_npy (bool) – Write the output dictionary to a numpy file. (default : True)
Returns:

LightCurve – Dictionary containing output of the LC analysis

Return type:

dict

like

Return the global likelihood object.

load_parameters_from_yaml(yamlfile, update_sources=False)[source]

Load model parameters from yaml

Parameters:yamlfile (str) – Name of the input yaml file.
load_roi(infile, reload_sources=False)[source]

This function reloads the analysis state from a previously saved instance generated with write_roi.

Parameters:
  • infile (str) –
  • reload_sources (bool) – Regenerate source maps for non-diffuse sources.
load_xml(xmlfile)[source]

Load model definition from XML.

Parameters:xmlfile (str) – Name of the input XML file.
localize(name, **kwargs)

Find the best-fit position of a source. Localization is performed in two steps. First a TS map is computed centered on the source with half-width set by dtheta_max. A fit is then performed to the maximum TS peak in this map. The source position is then further refined by scanning the likelihood in the vicinity of the peak found in the first step. The size of the scan region is set to encompass the 99% positional uncertainty contour as determined from the peak fit.

Parameters:
  • name (str) – Source name.
  • dtheta_max (float) – Half-width of the search region in degrees used for the first pass of the localization search. (default : 0.5)
  • fix_shape (bool) – Fix spectral shape parameters of the source of interest. If True then only the normalization parameter will be fit. (default : False)
  • free_background (bool) – Leave background parameters free when performing the fit. If True then any parameters that are currently free in the model will be fit simultaneously with the source of interest. (default : False)
  • free_radius (float) – Free normalizations of background sources within this angular distance in degrees from the source of interest. If None then no sources will be freed. (default : None)
  • make_plots (bool) – Generate diagnostic plots. (default : False)
  • nstep (int) – Number of steps in longitude/latitude that will be taken when refining the source position. The bounds of the scan range are set to the 99% positional uncertainty as determined from the TS map peak fit. The total number of sampling points will be nstep**2. (default : 5)
  • update (bool) – Update the source model with the best-fit position. (default : True)
  • write_fits (bool) – Write the output to a FITS file. (default : True)
  • write_npy (bool) – Write the output dictionary to a numpy file. (default : True)
  • optimizer (dict) – Dictionary that overrides the default optimizer settings.
Returns:

localize – Dictionary containing results of the localization analysis.

Return type:

dict

lock_parameter(name, par, lock=True)[source]

Set parameter to locked/unlocked state. A locked parameter will be ignored when running methods that free/fix sources or parameters.

Parameters:
  • name (str) – Source name.
  • par (str) – Parameter name.
  • lock (bool) – Set parameter to locked (True) or unlocked (False) state.
lock_source(name, lock=True)[source]

Set all parameters of a source to a locked/unlocked state. Locked parameters will be ignored when running methods that free/fix sources or parameters.

Parameters:
  • name (str) – Source name.
  • lock (bool) – Set source parameters to locked (True) or unlocked (False) state.
log_energies

Return the energy bin edges in log10(E/MeV).

loge_bounds

Current analysis energy bounds in log10(E/MeV).

logger

Return the default loglevel.

loglevel

Return the default loglevel.

make_plots(prefix, mcube_map=None, **kwargs)[source]

Make diagnostic plots using the current ROI model.

make_template(src)[source]
model_counts_map(name=None, exclude=None, use_mask=False)[source]

Return the model counts map for a single source, a list of sources, or for the sum of all sources in the ROI. The exclude parameter can be used to exclude one or more components when generating the model map.

Parameters:
  • name (str or list of str) – Parameter controlling the set of sources for which the model counts map will be calculated. If name=None the model map will be generated for all sources in the ROI.
  • exclude (str or list of str) – List of sources that will be excluded when calculating the model map.
  • use_mask (bool) – Parameter that specifies in the model counts map should include mask pixels (i.e., ones whose weights are <= 0)
Returns:

map

Return type:

Map

model_counts_spectrum(name, logemin=None, logemax=None, summed=False, weighted=False)[source]

Return the predicted number of model counts versus energy for a given source and energy range. If summed=True return the counts spectrum summed over all components otherwise return a list of model spectra. If weighted=True return the weighted version of the counts spectrum

npix

Return the number of energy bins.

optimize(**kwargs)[source]

Iteratively optimize the ROI model. The optimization is performed in three sequential steps:

  • Free the normalization of the N largest components (as determined from NPred) that contain a fraction npred_frac of the total predicted counts in the model and perform a simultaneous fit of the normalization parameters of these components.
  • Individually fit the normalizations of all sources that were not included in the first step in order of their npred values. Skip any sources that have NPred < npred_threshold.
  • Individually fit the shape and normalization parameters of all sources with TS > shape_ts_threshold where TS is determined from the first two steps of the ROI optimization.

To ensure that the model is fully optimized this method can be run multiple times.

Parameters:
  • npred_frac (float) – Threshold on the fractional number of counts in the N largest components in the ROI. This parameter determines the set of sources that are fit in the first optimization step.
  • npred_threshold (float) – Threshold on the minimum number of counts of individual sources. This parameter determines the sources that are fit in the second optimization step.
  • shape_ts_threshold (float) – Threshold on source TS used for determining the sources that will be fit in the third optimization step.
  • max_free_sources (int) – Maximum number of sources that will be fit simultaneously in the first optimization step.
  • skip (list) – List of str source names to skip while optimizing.
  • optimizer (dict) – Dictionary that overrides the default optimizer settings.
outdir

Return the analysis output directory.

plotter

Return the plotter instance.

print_config(logger, loglevel=None)
print_model(loglevel=20)[source]
print_params(allpars=False, loglevel=20)[source]

Print information about the model parameters (values, errors, bounds, scale).

print_roi(loglevel=20)[source]

Print information about the spectral and spatial properties of the ROI (sources, diffuse components).

profile(name, parName, logemin=None, logemax=None, reoptimize=False, xvals=None, npts=None, savestate=True, **kwargs)[source]

Profile the likelihood for the given source and parameter.

Parameters:
  • name (str) – Source name.
  • parName (str) – Parameter name.
  • reoptimize (bool) – Re-fit nuisance parameters at each step in the scan. Note that enabling this option will only re-fit parameters that were free when the method was executed.
Returns:

lnlprofile – Dictionary containing results of likelihood scan.

Return type:

dict

profile_norm(name, logemin=None, logemax=None, reoptimize=False, xvals=None, npts=None, fix_shape=True, savestate=True, **kwargs)[source]

Profile the normalization of a source.

Parameters:
  • name (str) – Source name.
  • reoptimize (bool) – Re-optimize free parameters in the model at each point in the profile likelihood scan.
projtype

Return the type of projection to use

reload_source(name, init_source=True)[source]

Delete and reload a source in the model. This will update the spatial model of this source to the one defined in the XML model.

reload_sources(names, init_source=True)[source]
remove_prior(name, parName)[source]
remove_priors()[source]

Clear all priors.

residmap(prefix='', **kwargs)

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.
  • exclude (list) – List of sources that will be removed from the model when computing the residual map. (default : None)
  • loge_bounds (list) – Restrict the analysis to an energy range (emin,emax) in log10(E/MeV) that is a subset of the analysis energy range. By default the full analysis energy range will be used. If either emin/emax are None then only an upper/lower bound on the energy range wil be applied. (default : None)
  • make_plots (bool) – Generate diagnostic plots. (default : False)
  • model (dict) – Dictionary defining the spatial/spectral properties of the test source. If model is None the test source will be a PointSource with an Index 2 power-law spectrum. (default : None)
  • use_weights (bool) – Used weighted version of maps in making plots. (default : False)
  • write_fits (bool) – Write the output to a FITS file. (default : True)
  • write_npy (bool) – Write the output dictionary to a numpy file. (default : True)
Returns:

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

Return type:

dict

roi

Return the ROI object.

scale_parameter(name, par, scale)[source]
schema

Return the configuration schema of this class.

sed(name, **kwargs)

Generate a spectral energy distribution (SED) for a source. This function will fit the normalization of the source in each energy bin. By default the SED will be generated with the analysis energy bins but a custom binning can be defined with the loge_bins parameter.

Parameters:
  • name (str) – Source name.
  • prefix (str) – Optional string that will be prepended to all output files (FITS and rendered images).
  • loge_bins (ndarray) – Sequence of energies in log10(E/MeV) defining the edges of the energy bins. If this argument is None then the analysis energy bins will be used. The energies in this sequence must align with the bin edges of the underyling analysis instance.
  • bin_index (float) – Spectral index that will be use when fitting the energy distribution within an energy bin. (default : 2.0)
  • cov_scale (float) – Scale factor that sets the strength of the prior on nuisance parameters that are free. Setting this to None disables the prior. (default : 3.0)
  • free_background (bool) – Leave background parameters free when performing the fit. If True then any parameters that are currently free in the model will be fit simultaneously with the source of interest. (default : False)
  • free_pars (list) – Set the parameters of the source of interest that will be freed when performing the global fit. By default all parameters will be freed. (default : None)
  • free_radius (float) – Free normalizations of background sources within this angular distance in degrees from the source of interest. If None then no sources will be freed. (default : None)
  • make_plots (bool) – Generate diagnostic plots. (default : False)
  • ul_confidence (float) – Confidence level for flux upper limit. (default : 0.95)
  • use_local_index (bool) – Use a power-law approximation to the shape of the global spectrum in each bin. If this is false then a constant index set to bin_index will be used. (default : False)
  • write_fits (bool) – Write the output to a FITS file. (default : True)
  • write_npy (bool) – Write the output dictionary to a numpy file. (default : True)
  • optimizer (dict) – Dictionary that overrides the default optimizer settings.
Returns:

sed – Dictionary containing output of the SED analysis.

Return type:

dict

set_edisp_flag(name, flag=True)[source]

Enable or disable the energy dispersion correction for the given source.

set_energy_range(logemin, logemax)[source]

Set the energy bounds of the analysis. This restricts the evaluation of the likelihood to the data that falls in this range. Input values will be rounded to the closest bin edge value. If either argument is None then the lower or upper bound of the analysis instance will be used.

Parameters:
  • logemin (float) – Lower energy bound in log10(E/MeV).
  • logemax (float) – Upper energy bound in log10(E/MeV).
Returns:

eminmax – Minimum and maximum energy in log10(E/MeV).

Return type:

array

set_free_param_vector(free)[source]
set_log_level(level)[source]
set_norm(name, value, update_source=True)[source]
set_norm_bounds(name, bounds)[source]
set_norm_scale(name, value)[source]
set_parameter(name, par, value, true_value=True, scale=None, bounds=None, error=None, update_source=True)[source]

Update the value of a parameter. Parameter bounds will automatically be adjusted to encompass the new parameter value.

Parameters:
  • name (str) – Source name.
  • par (str) – Parameter name.
  • value (float) – Parameter value. By default this argument should be the unscaled (True) parameter value.
  • scale (float) – Parameter scale (optional). Value argument is interpreted with respect to the scale parameter if it is provided.
  • error (float) – Parameter error (optional). By default this argument should be the unscaled (True) parameter value.
  • update_source (bool) – Update the source dictionary for the object.
set_parameter_bounds(name, par, bounds)[source]

Set the bounds on the scaled value of a parameter.

Parameters:
  • name (str) – Source name.
  • par (str) – Parameter name.
  • bounds (list) – Upper and lower bound.
set_parameter_error(name, par, error)[source]

Set the error on the value of a parameter.

Parameters:
  • name (str) – Source name.
  • par (str) – Parameter name.
  • error (float) – The value for the parameter error
set_parameter_scale(name, par, scale)[source]

Update the scale of a parameter while keeping its value constant.

set_random_seed(seed)[source]

Set the seed for the random number generator

set_source_dnde(name, dnde, update_source=True)[source]

Set the differential flux distribution of a source with the FileFunction spectral type.

Parameters:
  • name (str) – Source name.
  • dnde (ndarray) – Array of differential flux values (cm^{-2} s^{-1} MeV^{-1}).
set_source_morphology(name, **kwargs)[source]

Set the spatial model of a source.

Parameters:
  • name (str) – Source name.
  • spatial_model (str) – Spatial model name (PointSource, RadialGaussian, etc.).
  • spatial_pars (dict) – Dictionary of spatial parameters (optional).
  • use_cache (bool) – Generate the spatial model by interpolating the cached source map.
  • use_pylike (bool) –
set_source_spectrum(name, spectrum_type='PowerLaw', spectrum_pars=None, update_source=True)[source]

Set the spectral model of a source. This function can be used to change the spectral type of a source or modify its spectral parameters. If called with spectrum_type=’FileFunction’ and spectrum_pars=None, the source spectrum will be replaced with a FileFunction with the same differential flux distribution as the original spectrum.

Parameters:
  • name (str) – Source name.
  • spectrum_type (str) – Spectrum type (PowerLaw, etc.).
  • spectrum_pars (dict) – Dictionary of spectral parameters (optional).
  • update_source (bool) – Recompute all source characteristics (flux, TS, NPred) using the new spectral model of the source.
set_weights_map(wmap, update_roi=True)[source]
setup(init_sources=True, overwrite=False, **kwargs)[source]

Run pre-processing for each analysis component and construct a joint likelihood object. This function performs the following tasks: data selection (gtselect, gtmktime), data binning (gtbin), and model generation (gtexpcube2,gtsrcmaps).

Parameters:
  • init_sources (bool) – Choose whether to compute properties (flux, TS, etc.) for individual sources.
  • overwrite (bool) – Run all pre-processing steps even if the output file of that step is present in the working directory. By default this function will skip any steps for which the output file already exists.
simulate_roi(name=None, randomize=True, restore=False)[source]

Generate a simulation of the ROI using the current best-fit model and replace the data counts cube with this simulation. The simulation is created by generating an array of Poisson random numbers with expectation values drawn from the model cube of the binned analysis instance. This function will update the counts cube both in memory and in the source map file. The counts cube can be restored to its original state by calling this method with restore = True.

Parameters:
  • name (str) – Name of the model component to be simulated. If None then the whole ROI will be simulated.
  • restore (bool) – Restore the data counts cube to its original state.
simulate_source(src_dict=None)[source]

Inject simulated source counts into the data.

Parameters:src_dict (dict) – Dictionary defining the spatial and spectral properties of the source that will be injected.
stage_input()[source]

Copy input files to working directory.

stage_output()[source]

Copy data products to final output directory.

tmax

Return the MET time for the end of the observation.

tmin

Return the MET time for the start of the observation.

tscube(prefix='', **kwargs)

Generate a spatial TS map for a source component with properties defined by the model argument. This method uses the gttscube ST application for source fitting and will simultaneously fit the test source normalization as well as the normalizations of any background components that are currently free. The output of this method is a dictionary containing Map objects with the TS and amplitude of the best-fit test source. By default this method will also save maps to FITS files and render them as image files.

Parameters:
  • prefix (str) – Optional string that will be prepended to all output files (FITS and rendered images).
  • model (dict) – Dictionary defining the properties of the test source.
  • do_sed (bool) – Compute the energy bin-by-bin fits.
  • nnorm (int) – Number of points in the likelihood v. normalization scan.
  • norm_sigma (float) – Number of sigma to use for the scan range.
  • tol (float) – Critetia for fit convergence (estimated vertical distance to min < tol ).
  • tol_type (int) – Absoulte (0) or relative (1) criteria for convergence.
  • max_iter (int) – Maximum number of iterations for the Newton’s method fitter
  • remake_test_source (bool) – If true, recomputes the test source image (otherwise just shifts it)
  • st_scan_level (int) –
  • make_plots (bool) – Write image files.
  • write_fits (bool) – Write a FITS file with the results of the analysis.
Returns:

maps – A dictionary containing the Map objects for TS and source amplitude.

Return type:

dict

tsmap(prefix='', **kwargs)

Generate a spatial TS map for a source component with properties defined by the model argument. The TS map will have the same geometry as the ROI. The output of this method is a dictionary containing Map objects with the TS and amplitude of the best-fit test source. By default this method will also save maps to FITS files and render them as image files.

This method uses a simplified likelihood fitting implementation that only fits for the normalization of the test source. Before running this method it is recommended to first optimize the ROI model (e.g. by running optimize()).

Parameters:
  • prefix (str) – Optional string that will be prepended to all output files.
  • exclude (list) – List of sources that will be removed from the model when computing the TS map. (default : None)
  • loge_bounds (list) – Restrict the analysis to an energy range (emin,emax) in log10(E/MeV) that is a subset of the analysis energy range. By default the full analysis energy range will be used. If either emin/emax are None then only an upper/lower bound on the energy range wil be applied. (default : None)
  • make_plots (bool) – Generate diagnostic plots. (default : False)
  • max_kernel_radius (float) – Set the maximum radius of the test source kernel. Using a smaller value will speed up the TS calculation at the loss of accuracy. (default : 3.0)
  • model (dict) – Dictionary defining the spatial/spectral properties of the test source. If model is None the test source will be a PointSource with an Index 2 power-law spectrum. (default : None)
  • multithread (bool) – Split the calculation across number of processes set by nthread option. (default : False)
  • nthread (int) – Number of processes to create when multithread is True. If None then one process will be created for each available core. (default : None)
  • write_fits (bool) – Write the output to a FITS file. (default : True)
  • write_npy (bool) – Write the output dictionary to a numpy file. (default : True)
Returns:

tsmap – A dictionary containing the Map objects for TS and source amplitude.

Return type:

dict

unzero_source(name, **kwargs)[source]
update_source(name, paramsonly=False, reoptimize=False, **kwargs)[source]

Update the dictionary for this source.

Parameters:
  • name (str) –
  • paramsonly (bool) –
  • reoptimize (bool) – Re-fit background parameters in likelihood scan.
weight_map()[source]

Return a Map representation of the weights map.

Returns:map
Return type:Map
workdir

Return the analysis working directory.

write_config(outfile)

Write the configuration dictionary to an output file.

write_fits(fitsfile)[source]
write_model_map(model_name, name=None)[source]

Save the counts model map to a FITS file.

Parameters:
  • model_name (str) – String that will be append to the name of the output file.
  • name (str) – Name of the component.
write_roi(outfile=None, save_model_map=False, **kwargs)[source]

Write current state of the analysis to a file. This method writes an XML model definition, a ROI dictionary, and a FITS source catalog file. A previously saved analysis state can be reloaded from the ROI dictionary file with the load_roi method.

Parameters:
  • outfile (str) – String prefix of the output files. The extension of this string will be stripped when generating the XML, YAML and npy filenames.
  • make_plots (bool) – Generate diagnostic plots.
  • save_model_map (bool) – Save the current counts model to a FITS file.
write_weight_map(model_name)[source]

Save the counts model map to a FITS file.

Parameters:model_name (str) – String that will be append to the name of the output file.
write_xml(xmlfile)[source]

Save current model definition as XML file.

Parameters:xmlfile (str) – Name of the output XML file.
zero_source(name, **kwargs)[source]

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.', <type 'list'>), 'catalogs': (None, '', <type 'list'>), 'diffuse': (None, '', <type 'list'>), 'diffuse_dir': (None, '', <type '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.', <type 'str'>), 'extract_diffuse': (False, 'Extract a copy of all mapcube components centered on the ROI.', <type 'bool'>), 'fileio': {'usescratch': (False, 'Run analysis in a temporary working directory under ``scratchdir``.', <type 'bool'>), 'scratchdir': ('/scratch', 'Path to the scratch directory. If ``usescratch`` is True then a temporary working directory will be created under this directory.', <type 'str'>), 'savefits': (True, 'Save intermediate FITS files.', <type 'bool'>), 'workdir': (None, 'Path to the working directory.', <type '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.', <type 'list'>), '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.', <type 'list'>), 'logfile': (None, 'Path to log file. If None then log will be written to fermipy.log.', <type 'str'>), 'outdir': (None, 'Path of the output directory. If none this will default to the directory containing the configuration file.', <type 'str'>)}, 'galdiff': (None, 'Set the path to one or more galactic IEM mapcubes. A separate component will be generated for each item in this list.', <type 'list'>), 'isodiff': (None, 'Set the path to one or more isotropic templates. A separate component will be generated for each item in this list.', <type 'list'>), 'limbdiff': (None, '', <type '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.', <type 'bool'>), 'sources': (None, '', <type '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.', <type 'float'>), 'src_radius_roi': (None, 'Half-width of ``src_roiwidth`` selection. This parameter can be used in lieu of ``src_roiwidth``.', <type '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.', <type '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.

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.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, '', <type 'list'>), 'cmap': ('magma', 'Set the colormap for 2D plots.', <type 'str'>), 'cmap_resid': ('RdBu_r', 'Set the colormap for 2D residual plots.', <type 'str'>), 'figsize': ([8.0, 6.0], 'Set the default figure size.', <type 'list'>), 'fileio': {'usescratch': (False, 'Run analysis in a temporary working directory under ``scratchdir``.', <type 'bool'>), 'scratchdir': ('/scratch', 'Path to the scratch directory. If ``usescratch`` is True then a temporary working directory will be created under this directory.', <type 'str'>), 'savefits': (True, 'Save intermediate FITS files.', <type 'bool'>), 'workdir': (None, 'Path to the working directory.', <type '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.', <type 'list'>), '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.', <type 'list'>), 'logfile': (None, 'Path to log file. If None then log will be written to fermipy.log.', <type 'str'>), 'outdir': (None, 'Path of the output directory. If none this will default to the directory containing the configuration file.', <type 'str'>)}, 'format': ('png', '', <type 'str'>), 'graticule_radii': (None, 'Define a list of radii at which circular graticules will be drawn.', <type 'list'>), 'interactive': (False, 'Enable interactive mode. If True then plots will be drawn after each plotting command.', <type 'bool'>), 'label_ts_threshold': (0.0, 'TS threshold for labeling sources in sky maps. If None then no sources will be labeled.', <type 'float'>), 'loge_bounds': (None, '', <type 'list'>), 'logging': {'prefix': ('', 'Prefix that will be appended to the logger name.', <type 'str'>), 'chatter': (3, 'Set the chatter parameter of the STs.', <type 'int'>), 'verbosity': (3, '', <type '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, '', <type 'list'>), 'cmap': ('ds9_b', '', <type 'str'>), 'graticule_radii': (None, '', <type 'list'>), 'label_ts_threshold': (0.0, '', <type 'float'>), 'loge_bounds': (None, '', <type '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

Utilities for dealing with SEDs

Many parts of this code are taken from dsphs/like/lnlfn.py by
Matthew Wood <mdwood@slac.stanford.edu> Alex Drlica-Wagner <kadrlica@slac.stanford.edu>
class fermipy.sed.SEDGenerator[source]

Bases: object

Mixin class that provides SED functionality to GTAnalysis.

sed(name, **kwargs)[source]

Generate a spectral energy distribution (SED) for a source. This function will fit the normalization of the source in each energy bin. By default the SED will be generated with the analysis energy bins but a custom binning can be defined with the loge_bins parameter.

Parameters:
  • name (str) – Source name.
  • prefix (str) – Optional string that will be prepended to all output files (FITS and rendered images).
  • loge_bins (ndarray) – Sequence of energies in log10(E/MeV) defining the edges of the energy bins. If this argument is None then the analysis energy bins will be used. The energies in this sequence must align with the bin edges of the underyling analysis instance.
  • {options}
  • optimizer (dict) – Dictionary that overrides the default optimizer settings.
Returns:

sed – Dictionary containing output of the SED analysis.

Return type:

dict

fermipy.sourcefind module

class fermipy.sourcefind.SourceFind[source]

Bases: object

Mixin class which provides source-finding functionality to GTAnalysis.

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

An iterative source-finding algorithm that uses likelihood ratio (TS) maps of the region of interest to find new sources. After each iteration a new TS map is generated incorporating sources found in the previous iteration. The method stops when the number of iterations exceeds max_iter or no sources exceeding sqrt_ts_threshold are found.

Parameters:
  • {options}
  • tsmap (dict) – Keyword arguments dictionary for tsmap method.
  • tscube (dict) – Keyword arguments dictionary for tscube method.
Returns:

  • peaks (list) – List of peak objects.
  • sources (list) – List of source objects.

localize(name, **kwargs)[source]

Find the best-fit position of a source. Localization is performed in two steps. First a TS map is computed centered on the source with half-width set by dtheta_max. A fit is then performed to the maximum TS peak in this map. The source position is then further refined by scanning the likelihood in the vicinity of the peak found in the first step. The size of the scan region is set to encompass the 99% positional uncertainty contour as determined from the peak fit.

Parameters:
  • name (str) – Source name.
  • {options}
  • optimizer (dict) – Dictionary that overrides the default optimizer settings.
Returns:

localize – Dictionary containing results of the localization analysis.

Return type:

dict

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.
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

Parameters:spec_types ([str,..]) – List of spectral types to try
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

class fermipy.tsmap.TSCubeGenerator[source]

Bases: object

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

Generate a spatial TS map for a source component with properties defined by the model argument. This method uses the gttscube ST application for source fitting and will simultaneously fit the test source normalization as well as the normalizations of any background components that are currently free. The output of this method is a dictionary containing Map objects with the TS and amplitude of the best-fit test source. By default this method will also save maps to FITS files and render them as image files.

Parameters:
  • prefix (str) – Optional string that will be prepended to all output files (FITS and rendered images).
  • model (dict) – Dictionary defining the properties of the test source.
  • do_sed (bool) – Compute the energy bin-by-bin fits.
  • nnorm (int) – Number of points in the likelihood v. normalization scan.
  • norm_sigma (float) – Number of sigma to use for the scan range.
  • tol (float) – Critetia for fit convergence (estimated vertical distance to min < tol ).
  • tol_type (int) – Absoulte (0) or relative (1) criteria for convergence.
  • max_iter (int) – Maximum number of iterations for the Newton’s method fitter
  • remake_test_source (bool) – If true, recomputes the test source image (otherwise just shifts it)
  • st_scan_level (int) –
  • make_plots (bool) – Write image files.
  • write_fits (bool) – Write a FITS file with the results of the analysis.
Returns:

maps – A dictionary containing the Map objects for TS and source amplitude.

Return type:

dict

class fermipy.tsmap.TSMapGenerator[source]

Bases: object

Mixin class for GTAnalysis that generates TS maps.

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

Generate a spatial TS map for a source component with properties defined by the model argument. The TS map will have the same geometry as the ROI. The output of this method is a dictionary containing Map objects with the TS and amplitude of the best-fit test source. By default this method will also save maps to FITS files and render them as image files.

This method uses a simplified likelihood fitting implementation that only fits for the normalization of the test source. Before running this method it is recommended to first optimize the ROI model (e.g. by running optimize()).

Parameters:
  • prefix (str) – Optional string that will be prepended to all output files.
  • {options}
Returns:

tsmap – A dictionary containing the Map objects for TS and source amplitude.

Return type:

dict

fermipy.tsmap.cash(counts, model)[source]

Compute the Poisson log-likelihood function.

fermipy.tsmap.convert_tscube(infile, outfile)[source]
fermipy.tsmap.convert_tscube_old(infile, outfile)[source]

Convert between old and new TSCube formats.

fermipy.tsmap.extract_array(array_large, array_small, position)[source]
fermipy.tsmap.extract_images_from_tscube(infile, outfile)[source]

Extract data from table HDUs in TSCube file and convert them to FITS images

fermipy.tsmap.extract_large_array(array_large, array_small, position)[source]
fermipy.tsmap.extract_small_array(array_small, array_large, position)[source]
fermipy.tsmap.f_cash(x, counts, bkg, model)[source]

Wrapper for cash statistics, that defines the model function.

Parameters:
  • x (float) – Model amplitude.
  • counts (ndarray) – Count map slice, where model is defined.
  • bkg (ndarray) – Background map slice, where model is defined.
  • model (ndarray) – Source template (multiplied with exposure).
fermipy.tsmap.f_cash_sum(x, counts, bkg, model, bkg_sum=0, model_sum=0)[source]
fermipy.tsmap.poisson_log_like(counts, model)[source]

Compute the Poisson log-likelihood function for the given counts and model arrays.

fermipy.tsmap.truncate_array(array1, array2, position)[source]

Truncate array1 by finding the overlap with array2 when the array1 center is located at the given position in array2.

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

class fermipy.lightcurve.LightCurve[source]

Bases: object

lightcurve(name, **kwargs)[source]

Generate a lightcurve for the named source. The function will complete the basic analysis steps for each bin and perform a likelihood fit for each bin. Extracted values (along with errors) are Integral Flux, spectral model, Spectral index, TS value, pred. # of photons. Note: successful calculation of TS:subscript:var requires at least one free background parameter and a previously optimized ROI model.

Parameters:
  • name (str) – source name
  • {options}
Returns:

LightCurve – Dictionary containing output of the LC analysis

Return type:

dict

fermipy.lightcurve.calcTS_var(loglike, loglike_const, flux_err, flux_const, systematic, fit_success)[source]

Module contents

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.