sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def delete_sources(self, cuts=None, distance=None,
skydir=None, minmax_ts=None, minmax_npred=None,
exclude=None, square=False, names=None):
"""Delete sources in the ROI model satisfying the given
selection criteria.
Parameters
----------
... | 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
sel... | entailment |
def free_sources_by_name(self, names, free=True, pars=None,
**kwargs):
"""Free all sources with names matching ``names``.
Parameters
----------
names : list
List of source names.
free : bool
Choose whether to free (free=True)... | 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 t... | entailment |
def free_sources(self, free=True, pars=None, cuts=None,
distance=None, skydir=None, minmax_ts=None, minmax_npred=None,
exclude=None, square=False, **kwargs):
"""Free or fix sources in the ROI model satisfying the given
selection. When multiple selections are de... | 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
--------... | entailment |
def set_parameter(self, name, par, value, true_value=True, scale=None,
bounds=None, error=None, update_source=True):
"""
Update the value of a parameter. Parameter bounds will
automatically be adjusted to encompass the new parameter
value.
Parameters
... | 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. ... | entailment |
def set_parameter_scale(self, name, par, scale):
"""Update the scale of a parameter while keeping its value constant."""
name = self.roi.get_source_by_name(name).name
idx = self.like.par_index(name, par)
current_bounds = list(self.like.model[idx].getBounds())
current_scale = self... | Update the scale of a parameter while keeping its value constant. | entailment |
def set_parameter_bounds(self, name, par, bounds):
"""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 the bounds on the scaled value of a parameter.
Parameters
----------
name : str
Source name.
par : str
Parameter name.
bounds : list
Upper and lower bound. | entailment |
def set_parameter_error(self, name, par, error):
"""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 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 | entailment |
def lock_parameter(self, name, par, lock=True):
"""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
... | 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
... | entailment |
def free_parameter(self, name, par, free=True):
"""Free/Fix a parameter of a source by name.
Parameters
----------
name : str
Source name.
par : str
Parameter name.
"""
name = self.get_source_name(name)
if par in self._lck_params.... | Free/Fix a parameter of a source by name.
Parameters
----------
name : str
Source name.
par : str
Parameter name. | entailment |
def lock_source(self, name, lock=True):
"""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 : boo... | 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 lock... | entailment |
def free_source(self, name, free=True, pars=None, **kwargs):
"""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.
par... | 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... | entailment |
def free_norm(self, name, free=True, **kwargs):
"""Free/Fix normalization of a source.
Parameters
----------
name : str
Source name.
free : bool
Choose whether to free (free=True) or fix (free=False).
"""
name = self.get_source_name(nam... | Free/Fix normalization of a source.
Parameters
----------
name : str
Source name.
free : bool
Choose whether to free (free=True) or fix (free=False). | entailment |
def free_index(self, name, free=True, **kwargs):
"""Free/Fix index of a source.
Parameters
----------
name : str
Source name.
free : bool
Choose whether to free (free=True) or fix (free=False).
"""
src = self.roi.get_source_by_name(name... | Free/Fix index of a source.
Parameters
----------
name : str
Source name.
free : bool
Choose whether to free (free=True) or fix (free=False). | entailment |
def free_shape(self, name, free=True, **kwargs):
"""Free/Fix shape parameters of a source.
Parameters
----------
name : str
Source name.
free : bool
Choose whether to free (free=True) or fix (free=False).
"""
src = self.roi.get_source_by... | Free/Fix shape parameters of a source.
Parameters
----------
name : str
Source name.
free : bool
Choose whether to free (free=True) or fix (free=False). | entailment |
def get_source_name(self, name):
"""Return the name of a source as it is defined in the
pyLikelihood model object."""
if name not in self.like.sourceNames():
name = self.roi.get_source_by_name(name).name
return name | Return the name of a source as it is defined in the
pyLikelihood model object. | entailment |
def optimize(self, **kwargs):
"""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... | 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
sim... | entailment |
def profile_norm(self, name, logemin=None, logemax=None, reoptimize=False,
xvals=None, npts=None, fix_shape=True, savestate=True,
**kwargs):
"""Profile the normalization of a source.
Parameters
----------
name : str
Source name.
... | 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. | entailment |
def profile(self, name, parName, logemin=None, logemax=None,
reoptimize=False,
xvals=None, npts=None, savestate=True, **kwargs):
"""Profile the likelihood for the given source and parameter.
Parameters
----------
name : str
Source name.
... | 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 o... | entailment |
def constrain_norms(self, srcNames, cov_scale=1.0):
"""Constrain the normalizations of one or more sources by
adding gaussian priors with sigma equal to the parameter
error times a scaling factor."""
# Get the covariance matrix
for name in srcNames:
par = self.like.... | Constrain the normalizations of one or more sources by
adding gaussian priors with sigma equal to the parameter
error times a scaling factor. | entailment |
def remove_priors(self):
"""Clear all priors."""
for src in self.roi.sources:
for par in self.like[src.name].funcs["Spectrum"].params.values():
par.removePrior() | Clear all priors. | entailment |
def _create_optObject(self, **kwargs):
""" Make MINUIT or NewMinuit type optimizer object """
optimizer = kwargs.get('optimizer',
self.config['optimizer']['optimizer'])
if optimizer.upper() == 'MINUIT':
optObject = pyLike.Minuit(self.like.logLike)
... | Make MINUIT or NewMinuit type optimizer object | entailment |
def fit(self, update=True, **kwargs):
"""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... | 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... | entailment |
def _fit_newton(self, fitcache=None, ebin=None, **kwargs):
"""Fast fitting method using newton fitter."""
tol = kwargs.get('tol', self.config['optimizer']['tol'])
max_iter = kwargs.get('max_iter',
self.config['optimizer']['max_iter'])
init_lambda = kwargs.g... | Fast fitting method using newton fitter. | entailment |
def load_xml(self, xmlfile):
"""Load model definition from XML.
Parameters
----------
xmlfile : str
Name of the input XML file.
"""
self.logger.info('Loading XML')
for c in self.components:
c.load_xml(xmlfile)
for name in self.... | Load model definition from XML.
Parameters
----------
xmlfile : str
Name of the input XML file. | entailment |
def load_parameters_from_yaml(self, yamlfile, update_sources=False):
"""Load model parameters from yaml
Parameters
----------
yamlfile : str
Name of the input yaml file.
"""
d = utils.load_yaml(yamlfile)
for src, src_pars in d.items():
for... | Load model parameters from yaml
Parameters
----------
yamlfile : str
Name of the input yaml file. | entailment |
def _restore_counts_maps(self):
"""
Revert counts maps to their state prior to injecting any simulated
components.
"""
for c in self.components:
c.restore_counts_maps()
if hasattr(self.like.components[0].logLike, 'setCountsMap'):
self._init_roi_m... | Revert counts maps to their state prior to injecting any simulated
components. | entailment |
def simulate_source(self, src_dict=None):
"""
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.
"""
self._fitcac... | 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. | entailment |
def simulate_roi(self, name=None, randomize=True, restore=False):
"""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 value... | 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 fu... | entailment |
def write_model_map(self, model_name, name=None):
"""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.
Returns
---... | 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.
Returns
------- | entailment |
def write_weight_map(self, model_name):
"""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.
Returns
-------
"""
maps = [c.write_weight_map(model_name)... | 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.
Returns
------- | entailment |
def print_roi(self, loglevel=logging.INFO):
"""Print information about the spectral and spatial properties
of the ROI (sources, diffuse components)."""
self.logger.log(loglevel, '\n' + str(self.roi)) | Print information about the spectral and spatial properties
of the ROI (sources, diffuse components). | entailment |
def print_params(self, allpars=False, loglevel=logging.INFO):
"""Print information about the model parameters (values,
errors, bounds, scale)."""
pars = self.get_params()
o = '\n'
o += '%4s %-20s%10s%10s%10s%10s%10s%5s\n' % (
'idx', 'parname', 'value', 'error',
... | Print information about the model parameters (values,
errors, bounds, scale). | entailment |
def load_roi(self, infile, reload_sources=False, params=None, mask=None):
"""This function reloads the analysis state from a previously
saved instance generated with
`~fermipy.gtanalysis.GTAnalysis.write_roi`.
Parameters
----------
infile : str
reload_sources :... | This function reloads the analysis state from a previously
saved instance generated with
`~fermipy.gtanalysis.GTAnalysis.write_roi`.
Parameters
----------
infile : str
reload_sources : bool
Regenerate source maps for non-diffuse sources.
params : st... | entailment |
def write_roi(self, outfile=None,
save_model_map=False, **kwargs):
"""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 th... | 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
`~fermipy.gtanalysis.GTAnalysis.load_roi` method.
... | entailment |
def make_plots(self, prefix, mcube_map=None, **kwargs):
"""Make diagnostic plots using the current ROI model."""
#mcube_maps = kwargs.pop('mcube_maps', None)
if mcube_map is None:
mcube_map = self.model_counts_map()
plotter = plotting.AnalysisPlotter(self.config['plotting']... | Make diagnostic plots using the current ROI model. | entailment |
def curvature(self, name, **kwargs):
"""Test whether a source shows spectral curvature by comparing
the likelihood ratio of PowerLaw and LogParabola spectral
models.
Parameters
----------
name : str
Source name.
"""
name = self.roi.get_sourc... | Test whether a source shows spectral curvature by comparing
the likelihood ratio of PowerLaw and LogParabola spectral
models.
Parameters
----------
name : str
Source name. | entailment |
def bowtie(self, name, fd=None, loge=None):
"""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
... | 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 cu... | entailment |
def update_source(self, name, paramsonly=False, reoptimize=False, **kwargs):
"""Update the dictionary for this source.
Parameters
----------
name : str
paramsonly : bool
reoptimize : bool
Re-fit background parameters in likelihood scan.
"""
... | Update the dictionary for this source.
Parameters
----------
name : str
paramsonly : bool
reoptimize : bool
Re-fit background parameters in likelihood scan. | entailment |
def get_src_model(self, name, paramsonly=False, reoptimize=False,
npts=None, **kwargs):
"""Compose a dictionary for a source with the current best-fit
parameters.
Parameters
----------
name : str
paramsonly : bool
Skip computing TS and ... | 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 ... | entailment |
def compute_srcprob(self,xmlfile=None, overwrite=False):
"""Run the gtsrcprob app with the current model or a user provided xmlfile"""
for i,c in enumerate(self.components):
# compute diffuse response, necessary for srcprob
c._diffrsp_app(xmlfile=xmlfile)
# compute s... | Run the gtsrcprob app with the current model or a user provided xmlfile | entailment |
def reload_source(self, name):
"""Recompute the source map for a single source in the model.
"""
src = self.roi.get_source_by_name(name)
if hasattr(self.like.logLike, 'loadSourceMap'):
self.like.logLike.loadSourceMap(str(name), True, False)
srcmap_utils.delete_s... | Recompute the source map for a single source in the model. | entailment |
def reload_sources(self, names):
"""Recompute the source map for a list of sources in the model.
"""
try:
self.like.logLike.loadSourceMaps(names, True, True)
# loadSourceMaps doesn't overwrite the header so we need
# to ignore EXPSCALE by setting check_header... | Recompute the source map for a list of sources in the model. | entailment |
def add_source(self, name, src_dict, free=None, save_source_maps=True,
use_pylike=True, use_single_psf=False):
"""Add a new source to the model. Source properties
(spectrum, spatial model) are set with the src_dict argument.
Parameters
----------
name : str... | Add a new source to the model. Source properties
(spectrum, spatial model) are set with the src_dict argument.
Parameters
----------
name : str
Source name.
src_dict : dict or `~fermipy.roi_model.Source` object
Dictionary or Source object defining the... | entailment |
def _create_source(self, src):
"""Create a pyLikelihood Source object from a
`~fermipy.roi_model.Model` object."""
if src['SpatialType'] == 'SkyDirFunction':
pylike_src = pyLike.PointSource(self.like.logLike.observation())
pylike_src.setDir(src.skydir.ra.deg, src.skydir.... | Create a pyLikelihood Source object from a
`~fermipy.roi_model.Model` object. | entailment |
def set_exposure_scale(self, name, scale=None):
"""Set the exposure correction of a source.
Parameters
----------
name : str
Source name.
scale : factor
Exposure scale factor (1.0 = nominal exposure).
"""
name = self.roi.get_source_by_na... | Set the exposure correction of a source.
Parameters
----------
name : str
Source name.
scale : factor
Exposure scale factor (1.0 = nominal exposure). | entailment |
def set_edisp_flag(self, name, flag=True):
"""Enable/Disable the energy dispersion correction for a
source."""
src = self.roi.get_source_by_name(name)
name = src.name
self.like[name].src.set_edisp_flag(flag) | Enable/Disable the energy dispersion correction for a
source. | entailment |
def set_energy_range(self, logemin, logemax):
"""Set the energy range of the analysis.
Parameters
----------
logemin: float
Lower end of energy range in log10(E/MeV).
logemax : float
Upper end of energy range in log10(E/MeV).
"""
if logem... | Set the energy range of the analysis.
Parameters
----------
logemin: float
Lower end of energy range in log10(E/MeV).
logemax : float
Upper end of energy range in log10(E/MeV). | entailment |
def counts_map(self):
"""Return 3-D counts map for this component as a Map object.
Returns
-------
map : `~fermipy.skymap.MapBase`
"""
try:
if isinstance(self.like, gtutils.SummedLikelihood):
cmap = self.like.components[0].logLike.countsMap()... | Return 3-D counts map for this component as a Map object.
Returns
-------
map : `~fermipy.skymap.MapBase` | entailment |
def weight_map(self):
"""Return 3-D weights map for this component as a Map object.
Returns
-------
map : `~fermipy.skymap.MapBase`
"""
# EAC we need the try blocks b/c older versions of the ST don't have some of these functions
if isinstance(self.like, gtutils.... | Return 3-D weights map for this component as a Map object.
Returns
-------
map : `~fermipy.skymap.MapBase` | entailment |
def model_counts_map(self, name=None, exclude=None, use_mask=False):
"""Return the model expectation map for a single source, a set
of sources, or all sources in the ROI. The map will be
computed using the current model parameters.
Parameters
----------
name : str
... | Return the model expectation map for a single source, a set
of sources, or all sources in the ROI. The map will be
computed using the current model parameters.
Parameters
----------
name : str
Parameter that defines the sources for which the model map
wil... | entailment |
def model_counts_spectrum(self, name, logemin, logemax, weighted=False):
"""Return the model counts spectrum of a source.
Parameters
----------
name : str
Source name.
"""
# EAC, we need this b/c older version of the ST don't have the right signature
... | Return the model counts spectrum of a source.
Parameters
----------
name : str
Source name. | entailment |
def setup(self, overwrite=False, **kwargs):
"""Run pre-processing step for this component. This will
generate all of the auxiliary files needed to instantiate a
likelihood object. By default this function will skip any
steps for which the output file already exists.
Parameters... | Run pre-processing step for this component. This will
generate all of the auxiliary files needed to instantiate a
likelihood object. By default this function will skip any
steps for which the output file already exists.
Parameters
----------
overwrite : bool
... | entailment |
def _scale_srcmap(self, scale_map, check_header=True, names=None):
"""Apply exposure corrections to the source map file.
Parameters
----------
scale_map : dict
Dictionary of exposure corrections.
check_header : bool
Check EXPSCALE header keyword to see i... | Apply exposure corrections to the source map file.
Parameters
----------
scale_map : dict
Dictionary of exposure corrections.
check_header : bool
Check EXPSCALE header keyword to see if an exposure
correction has already been applied to this source.
... | entailment |
def _make_scaled_srcmap(self):
"""Make an exposure cube with the same binning as the counts map."""
self.logger.info('Computing scaled source map.')
bexp0 = fits.open(self.files['bexpmap_roi'])
bexp1 = fits.open(self.config['gtlike']['bexpmap'])
srcmap = fits.open(self.config['... | Make an exposure cube with the same binning as the counts map. | entailment |
def simulate_roi(self, name=None, clear=True, randomize=True):
"""Simulate the whole ROI or inject a simulation of one or
more model components into the data.
Parameters
----------
name : str
Name of the model component to be simulated. If None then
the wh... | Simulate the whole ROI or inject a simulation of one or
more model components into the data.
Parameters
----------
name : str
Name of the model component to be simulated. If None then
the whole ROI will be simulated.
clear : bool
Zero the curre... | entailment |
def write_model_map(self, model_name=None, name=None):
"""Save counts model map to a FITS file.
"""
if model_name is None:
suffix = self.config['file_suffix']
else:
suffix = '_%s%s' % (model_name, self.config['file_suffix'])
self.logger.info('Generating... | Save counts model map to a FITS file. | entailment |
def write_weight_map(self, model_name=None):
"""Save counts model map to a FITS file.
"""
if model_name is None:
suffix = self.config['file_suffix']
else:
suffix = '_%s%s' % (model_name, self.config['file_suffix'])
self.logger.info('Generating model map... | Save counts model map to a FITS file. | entailment |
def _update_srcmap_file(self, sources, overwrite=True):
"""Check the contents of the source map file and generate
source maps for any components that are not present."""
if not os.path.isfile(self.files['srcmap']):
return
hdulist = fits.open(self.files['srcmap'])
hd... | Check the contents of the source map file and generate
source maps for any components that are not present. | entailment |
def _create_srcmap(self, name, src, **kwargs):
"""Generate the source map for a source."""
psf_scale_fn = kwargs.get('psf_scale_fn', None)
skydir = src.skydir
spatial_model = src['SpatialModel']
spatial_width = src['SpatialWidth']
xpix, ypix = self.geom.to_image().coord_... | Generate the source map for a source. | entailment |
def _update_srcmap(self, name, src, **kwargs):
"""Update the source map for an existing source in memory."""
k = self._create_srcmap(name, src, **kwargs)
scale = self._src_expscale.get(name, 1.0)
k *= scale
# Force the source map to be cached
# FIXME: No longer necessar... | Update the source map for an existing source in memory. | entailment |
def generate_model(self, model_name=None, outfile=None):
"""Generate a counts model map from an XML model file using
gtmodel.
Parameters
----------
model_name : str
Name of the model. If no name is given it will use the
baseline model.
outfile :... | Generate a counts model map from an XML model file using
gtmodel.
Parameters
----------
model_name : str
Name of the model. If no name is given it will use the
baseline model.
outfile : str
Override the name of the output model file. | entailment |
def write_xml(self, xmlfile):
"""Write the XML model for this analysis component."""
xmlfile = self.get_model_path(xmlfile)
self.logger.info('Writing %s...', xmlfile)
self.like.writeXml(str(xmlfile)) | Write the XML model for this analysis component. | entailment |
def get_model_path(self, name):
"""Infer the path to the XML model name."""
name, ext = os.path.splitext(name)
ext = '.xml'
xmlfile = name + self.config['file_suffix'] + ext
xmlfile = utils.resolve_path(xmlfile,
workdir=self.config['fileio'][... | Infer the path to the XML model name. | entailment |
def _tscube_app(self, xmlfile):
"""Run gttscube as an application."""
xmlfile = self.get_model_path(xmlfile)
outfile = os.path.join(self.config['fileio']['workdir'],
'tscube%s.fits' % (self.config['file_suffix']))
kw = dict(cmap=self.files['ccube'],
... | Run gttscube as an application. | entailment |
def _diffrsp_app(self,xmlfile=None, **kwargs):
"""
Compute the diffuse response
"""
loglevel = kwargs.get('loglevel', self.loglevel)
self.logger.log(loglevel, 'Computing diffuse repsonce for component %s.',
self.name)
# set the srcmdl
sr... | Compute the diffuse response | entailment |
def _srcprob_app(self,xmlfile=None, overwrite=False, **kwargs):
"""
Run srcprob for an analysis component as an application
"""
loglevel = kwargs.get('loglevel', self.loglevel)
self.logger.log(loglevel, 'Computing src probability for component %s.',
self... | Run srcprob for an analysis component as an application | entailment |
def purge_dict(idict):
"""Remove null items from a dictionary """
odict = {}
for key, val in idict.items():
if is_null(val):
continue
odict[key] = val
return odict | Remove null items from a dictionary | entailment |
def main(cls):
"""Hook to run this `Chain` from the command line """
chain = cls.create()
args = chain._run_argparser(sys.argv[1:])
chain._run_chain(sys.stdout, args.dry_run)
chain._finalize(args.dry_run) | Hook to run this `Chain` from the command line | entailment |
def _latch_file_info(self):
"""Internal function to update the dictionaries
keeping track of input and output files
"""
self._map_arguments(self.args)
self.files.latch_file_info(self.args)
self.sub_files.file_dict.clear()
self.sub_files.update(self.files.file_dict... | Internal function to update the dictionaries
keeping track of input and output files | entailment |
def _set_link(self, linkname, cls, **kwargs):
"""Transfer options kwargs to a `Link` object,
optionally building the `Link if needed.
Parameters
----------
linkname : str
Unique name of this particular link
cls : type
Type of `Link` being create... | Transfer options kwargs to a `Link` object,
optionally building the `Link if needed.
Parameters
----------
linkname : str
Unique name of this particular link
cls : type
Type of `Link` being created or managed | entailment |
def _set_links_job_archive(self):
"""Pass self._job_archive along to links"""
for link in self._links.values():
link._job_archive = self._job_archive | Pass self._job_archive along to links | entailment |
def _run_chain(self,
stream=sys.stdout,
dry_run=False,
stage_files=True,
force_run=False,
resubmit_failed=False):
"""Run all the links in the chain
Parameters
-----------
stream : `file`
... | Run all the links in the chain
Parameters
-----------
stream : `file`
Stream to print to,
Must have 'write' function
dry_run : bool
Print commands but do not run them
stage_files : bool
Stage files to and from the scratch area
... | entailment |
def clear_jobs(self, recursive=True):
"""Clear a dictionary with all the jobs
If recursive is True this will include jobs from all internal `Link`
"""
if recursive:
for link in self._links.values():
link.clear_jobs(recursive)
self.jobs.clear() | Clear a dictionary with all the jobs
If recursive is True this will include jobs from all internal `Link` | entailment |
def get_jobs(self, recursive=True):
"""Return a dictionary with all the jobs
If recursive is True this will include jobs from all internal `Link`
"""
if recursive:
ret_dict = self.jobs.copy()
for link in self._links.values():
ret_dict.update(link.... | Return a dictionary with all the jobs
If recursive is True this will include jobs from all internal `Link` | entailment |
def missing_input_files(self):
"""Make and return a dictionary of the missing input files.
This returns a dictionary mapping
filepath to list of `Link` that use the file as input.
"""
ret_dict = OrderedDict()
for link in self._links.values():
link_dict = link... | Make and return a dictionary of the missing input files.
This returns a dictionary mapping
filepath to list of `Link` that use the file as input. | entailment |
def check_links_status(self,
fail_running=False,
fail_pending=False):
""""Check the status of all the jobs run from the
`Link` objects in this `Chain` and return a status
flag that summarizes that.
Parameters
----------
... | Check the status of all the jobs run from the
`Link` objects in this `Chain` and return a status
flag that summarizes that.
Parameters
----------
fail_running : `bool`
If True, consider running jobs as failed
fail_pending : `bool`
If True, consi... | entailment |
def run(self, stream=sys.stdout, dry_run=False,
stage_files=True, resubmit_failed=False):
"""Runs this `Chain`.
Parameters
-----------
stream : `file`
Stream that this `Link` will print to,
Must have 'write' function
dry_run : bool
... | Runs this `Chain`.
Parameters
-----------
stream : `file`
Stream that this `Link` will print to,
Must have 'write' function
dry_run : bool
Print command but do not run it.
stage_files : bool
Copy files to and from scratch staging... | entailment |
def update_args(self, override_args):
"""Update the argument used to invoke the application
Note that this will also update the dictionary of input
and output files.
Parameters
-----------
override_args : dict
dictionary passed to the links
"""
... | Update the argument used to invoke the application
Note that this will also update the dictionary of input
and output files.
Parameters
-----------
override_args : dict
dictionary passed to the links | entailment |
def print_status(self, indent="", recurse=False):
"""Print a summary of the job status for each `Link` in this `Chain`"""
print ("%s%30s : %15s : %20s" %
(indent, "Linkname", "Link Status", "Jobs Status"))
for link in self._links.values():
if hasattr(link, 'check_statu... | Print a summary of the job status for each `Link` in this `Chain` | entailment |
def print_summary(self, stream=sys.stdout, indent="", recurse_level=2):
"""Print a summary of the activity done by this `Chain`.
Parameters
-----------
stream : `file`
Stream to print to, must have 'write' method.
indent : str
Indentation at start of li... | Print a summary of the activity done by this `Chain`.
Parameters
-----------
stream : `file`
Stream to print to, must have 'write' method.
indent : str
Indentation at start of line
recurse_level : int
Number of recursion levels to print | entailment |
def register_classes():
"""Register these classes with the `LinkFactory` """
Gtlink_exphpsun.register_class()
Gtlink_suntemp.register_class()
Gtexphpsun_SG.register_class()
Gtsuntemp_SG.register_class()
SunMoonChain.register_class() | Register these classes with the `LinkFactory` | entailment |
def build_job_configs(self, args):
"""Hook to build job configurations
"""
job_configs = {}
components = Component.build_from_yamlfile(args['comp'])
NAME_FACTORY.update_base_dict(args['data'])
mktime = args['mktimefilter']
base_config = dict(nxpix=args['nxpix']... | Hook to build job configurations | entailment |
def build_job_configs(self, args):
"""Hook to build job configurations
"""
job_configs = {}
components = Component.build_from_yamlfile(args['comp'])
NAME_FACTORY.update_base_dict(args['data'])
mktime = args['mktimefilter']
for comp in components:
zc... | Hook to build job configurations | entailment |
def build_job_configs(self, args):
"""Hook to build job configurations
"""
job_configs = {}
components = Component.build_from_yamlfile(args['comp'])
NAME_FACTORY.update_base_dict(args['data'])
# FIXME
mktime = args['mktimefilter']
for comp in components... | Hook to build job configurations | entailment |
def _map_arguments(self, input_dict):
"""Map from the top-level arguments to the arguments provided to
the indiviudal links """
config_yaml = input_dict['config']
config_dict = load_yaml(config_yaml)
data = config_dict.get('data')
comp = config_dict.get('comp')
... | Map from the top-level arguments to the arguments provided to
the indiviudal links | entailment |
def get_component_info(self, comp):
"""Return the information about sub-component specific to a particular data selection
Parameters
----------
comp : `binning.Component` object
Specifies the sub-component
Returns `ModelComponentInfo` object
"""
if ... | Return the information about sub-component specific to a particular data selection
Parameters
----------
comp : `binning.Component` object
Specifies the sub-component
Returns `ModelComponentInfo` object | entailment |
def add_component_info(self, compinfo):
"""Add sub-component specific information to a particular data selection
Parameters
----------
compinfo : `ModelComponentInfo` object
Sub-component being added
"""
if self.components is None:
self.component... | Add sub-component specific information to a particular data selection
Parameters
----------
compinfo : `ModelComponentInfo` object
Sub-component being added | entailment |
def clone_and_merge_sub(self, key):
"""Clones self and merges clone with sub-component specific information
Parameters
----------
key : str
Key specifying which sub-component
Returns `ModelComponentInfo` object
"""
new_comp = copy.deepcopy(self)
... | Clones self and merges clone with sub-component specific information
Parameters
----------
key : str
Key specifying which sub-component
Returns `ModelComponentInfo` object | entailment |
def add_columns(t0, t1):
"""Add columns of table t1 to table t0."""
for colname in t1.colnames:
col = t1.columns[colname]
if colname in t0.columns:
continue
new_col = Column(name=col.name, length=len(t0), dtype=col.dtype) # ,
# shape=col.shape)
t0.add_column... | Add columns of table t1 to table t0. | entailment |
def join_tables(left, right, key_left, key_right,
cols_right=None):
"""Perform a join of two tables.
Parameters
----------
left : `~astropy.Table`
Left table for join.
right : `~astropy.Table`
Right table for join.
key_left : str
Key used to match eleme... | Perform a join of two tables.
Parameters
----------
left : `~astropy.Table`
Left table for join.
right : `~astropy.Table`
Right table for join.
key_left : str
Key used to match elements from ``left`` table.
key_right : str
Key used to match elements from ``rig... | entailment |
def strip_columns(tab):
"""Strip whitespace from string columns."""
for colname in tab.colnames:
if tab[colname].dtype.kind in ['S', 'U']:
tab[colname] = np.core.defchararray.strip(tab[colname]) | Strip whitespace from string columns. | entailment |
def row_to_dict(row):
"""Convert a table row to a dictionary."""
o = {}
for colname in row.colnames:
if isinstance(row[colname], np.string_) and row[colname].dtype.kind in ['S', 'U']:
o[colname] = str(row[colname])
else:
o[colname] = row[colname]
return o | Convert a table row to a dictionary. | entailment |
def run_analysis(self, argv):
"""Run this analysis"""
args = self._parser.parse_args(argv)
obs = BinnedAnalysis.BinnedObs(irfs=args.irfs,
expCube=args.expcube,
srcMaps=args.srcmaps,
... | Run this analysis | entailment |
def build_job_configs(self, args):
"""Hook to build job configurations
"""
job_configs = {}
components = Component.build_from_yamlfile(args['comp'])
NAME_FACTORY.update_base_dict(args['data'])
ret_dict = make_catalog_comp_dict(sources=args['library'], basedir='.')
... | Hook to build job configurations | entailment |
def check_log(logfile, exited='Exited with exit code',
successful='Successfully completed', exists=True):
""" Often logfile doesn't exist because the job hasn't begun
to run. It is unclear what you want to do in that case...
Parameters
----------
logfile : str
String with path... | Often logfile doesn't exist because the job hasn't begun
to run. It is unclear what you want to do in that case...
Parameters
----------
logfile : str
String with path to logfile
exists : bool
Is the logfile required to exist
exited : str
String in logfile used to dete... | entailment |
def dispatch_job(jobname, exe, args, opts, batch_opts, dry_run=True):
"""Dispatch an LSF job.
Parameters
----------
exe : str
Execution string.
args : list
Positional arguments.
opts : dict
Dictionary of command-line options.
"""
batch_opts.setdefault('W', 300... | Dispatch an LSF job.
Parameters
----------
exe : str
Execution string.
args : list
Positional arguments.
opts : dict
Dictionary of command-line options. | entailment |
def _make_input_file_list(binnedfile, num_files):
"""Make the list of input files for a particular energy bin X psf type """
outdir_base = os.path.abspath(os.path.dirname(binnedfile))
outbasename = os.path.basename(binnedfile)
filelist = ""
for i in range(num_files):
split_key = "%06i" % i
... | Make the list of input files for a particular energy bin X psf type | entailment |
def _map_arguments(self, args):
"""Map from the top-level arguments to the arguments provided to
the indiviudal links """
comp_file = args.get('comp', None)
datafile = args.get('data', None)
do_ltsum = args.get('do_ltsum', False)
NAME_FACTORY.update_base_dict(datafile)
... | Map from the top-level arguments to the arguments provided to
the indiviudal links | entailment |
def build_job_configs(self, args):
"""Hook to build job configurations
"""
job_configs = {}
components = Component.build_from_yamlfile(args['comp'])
datafile = args['data']
if datafile is None or datafile == 'None':
return job_configs
NAME_FACTORY.up... | Hook to build job configurations | entailment |
def create_from_flux(cls, params, emin, emax, flux, scale=1.0):
"""Create a spectral function instance given its flux."""
params = params.copy()
params[0] = 1.0
params[0] = flux / cls.eval_flux(emin, emax, params, scale=scale)
return cls(params, scale) | Create a spectral function instance given its flux. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.