sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def main():
gtselect_keys = ['tmin', 'tmax', 'emin', 'emax', 'zmax', 'evtype', 'evclass',
'phasemin', 'phasemax', 'convtype', 'rad', 'ra', 'dec']
gtmktime_keys = ['roicut', 'filter']
usage = "usage: %(prog)s [options] "
description = "Run gtselect and gtmktime on one or more FT1 ... | Note that gtmktime will be skipped if no FT2 file is provided. | entailment |
def select_extended(cat_table):
"""Select only rows representing extended sources from a catalog table
"""
try:
l = [len(row.strip()) > 0 for row in cat_table['Extended_Source_Name'].data]
return np.array(l, bool)
except KeyError:
return cat_table['Extended'] | Select only rows representing extended sources from a catalog table | entailment |
def make_mask(cat_table, cut):
"""Mask a bit mask selecting the rows that pass a selection
"""
cut_var = cut['cut_var']
min_val = cut.get('min_val', None)
max_val = cut.get('max_val', None)
nsrc = len(cat_table)
if min_val is None:
min_mask = np.ones((nsrc), bool)
else:
... | Mask a bit mask selecting the rows that pass a selection | entailment |
def select_sources(cat_table, cuts):
"""Select only rows passing a set of cuts from catalog table
"""
nsrc = len(cat_table)
full_mask = np.ones((nsrc), bool)
for cut in cuts:
if cut == 'mask_extended':
full_mask *= mask_extended(cat_table)
elif cut == 'select_extended':
... | Select only rows passing a set of cuts from catalog table | entailment |
def make_catalog_comp_dict(**kwargs):
"""Build and return the information about the catalog components
"""
library_yamlfile = kwargs.pop('library', 'models/library.yaml')
csm = kwargs.pop('CatalogSourceManager', CatalogSourceManager(**kwargs))
if library_yamlfile is None or library_yamlfile == 'None... | Build and return the information about the catalog components | entailment |
def read_catalog_info_yaml(self, splitkey):
""" Read the yaml file for a particular split key
"""
catalog_info_yaml = self._name_factory.catalog_split_yaml(sourcekey=splitkey,
fullpath=True)
yaml_dict = yaml.safe_load(open... | Read the yaml file for a particular split key | entailment |
def build_catalog_info(self, catalog_info):
""" Build a CatalogInfo object """
cat = SourceFactory.build_catalog(**catalog_info)
catalog_info['catalog'] = cat
# catalog_info['catalog_table'] =
# Table.read(catalog_info['catalog_file'])
catalog_info['catalog_table'] = c... | Build a CatalogInfo object | entailment |
def catalog_components(self, catalog_name, split_ver):
""" Return the set of merged components for a particular split key """
return sorted(self._split_comp_info_dicts["%s_%s" % (catalog_name, split_ver)].keys()) | Return the set of merged components for a particular split key | entailment |
def split_comp_info(self, catalog_name, split_ver, split_key):
""" Return the info for a particular split key """
return self._split_comp_info_dicts["%s_%s" % (catalog_name, split_ver)][split_key] | Return the info for a particular split key | entailment |
def make_catalog_comp_info(self, full_cat_info, split_key, rule_key, rule_val, sources):
""" Make the information about a single merged component
Parameters
----------
full_cat_info : `_model_component.CatalogInfo`
Information about the full catalog
split_key : str
... | Make the information about a single merged component
Parameters
----------
full_cat_info : `_model_component.CatalogInfo`
Information about the full catalog
split_key : str
Key identifying the version of the spliting used
rule_key : str
Key i... | entailment |
def make_catalog_comp_info_dict(self, catalog_sources):
""" Make the information about the catalog components
Parameters
----------
catalog_sources : dict
Dictionary with catalog source defintions
Returns
-------
catalog_ret_dict : dict
... | Make the information about the catalog components
Parameters
----------
catalog_sources : dict
Dictionary with catalog source defintions
Returns
-------
catalog_ret_dict : dict
Dictionary mapping catalog_name to `model_component.CatalogInfo`
... | entailment |
def extract_images_from_tscube(infile, outfile):
""" Extract data from table HDUs in TSCube file and convert them to FITS images
"""
inhdulist = fits.open(infile)
wcs = pywcs.WCS(inhdulist[0].header)
map_shape = inhdulist[0].data.shape
t_eng = Table.read(infile, "EBOUNDS")
t_scan = Table.re... | Extract data from table HDUs in TSCube file and convert them to FITS images | entailment |
def convert_tscube_old(infile, outfile):
"""Convert between old and new TSCube formats."""
inhdulist = fits.open(infile)
# If already in the new-style format just write and exit
if 'DLOGLIKE_SCAN' in inhdulist['SCANDATA'].columns.names:
if infile != outfile:
inhdulist.writeto(outfil... | Convert between old and new TSCube formats. | entailment |
def truncate_array(array1, array2, position):
"""Truncate array1 by finding the overlap with array2 when the
array1 center is located at the given position in array2."""
slices = []
for i in range(array1.ndim):
xmin = 0
xmax = array1.shape[i]
dxlo = array1.shape[i] // 2
... | Truncate array1 by finding the overlap with array2 when the
array1 center is located at the given position in array2. | entailment |
def _sum_wrapper(fn):
"""
Wrapper to perform row-wise aggregation of list arguments and pass
them to a function. The return value of the function is summed
over the argument groups. Non-list arguments will be
automatically cast to a list.
"""
def wrapper(*args, **kwargs):
v = 0
... | Wrapper to perform row-wise aggregation of list arguments and pass
them to a function. The return value of the function is summed
over the argument groups. Non-list arguments will be
automatically cast to a list. | entailment |
def _amplitude_bounds(counts, bkg, model):
"""
Compute bounds for the root of `_f_cash_root_cython`.
Parameters
----------
counts : `~numpy.ndarray`
Count map.
bkg : `~numpy.ndarray`
Background map.
model : `~numpy.ndarray`
Source template (multiplied with exposure).... | Compute bounds for the root of `_f_cash_root_cython`.
Parameters
----------
counts : `~numpy.ndarray`
Count map.
bkg : `~numpy.ndarray`
Background map.
model : `~numpy.ndarray`
Source template (multiplied with exposure). | entailment |
def _f_cash_root(x, counts, bkg, model):
"""
Function to find root of. Described in Appendix A, Stewart (2009).
Parameters
----------
x : float
Model amplitude.
counts : `~numpy.ndarray`
Count map slice, where model is defined.
bkg : `~numpy.ndarray`
Background map s... | Function to find root of. Described in Appendix A, Stewart (2009).
Parameters
----------
x : float
Model amplitude.
counts : `~numpy.ndarray`
Count map slice, where model is defined.
bkg : `~numpy.ndarray`
Background map slice, where model is defined.
model : `~numpy.nda... | entailment |
def _root_amplitude_brentq(counts, bkg, model, root_fn=_f_cash_root):
"""Fit amplitude by finding roots using Brent algorithm.
See Appendix A Stewart (2009).
Parameters
----------
counts : `~numpy.ndarray`
Slice of count map.
bkg : `~numpy.ndarray`
Slice of background map.
... | Fit amplitude by finding roots using Brent algorithm.
See Appendix A Stewart (2009).
Parameters
----------
counts : `~numpy.ndarray`
Slice of count map.
bkg : `~numpy.ndarray`
Slice of background map.
model : `~numpy.ndarray`
Model template to fit.
Returns
----... | entailment |
def poisson_log_like(counts, model):
"""Compute the Poisson log-likelihood function for the given
counts and model arrays."""
loglike = np.array(model)
m = counts > 0
loglike[m] -= counts[m] * np.log(model[m])
return loglike | Compute the Poisson log-likelihood function for the given
counts and model arrays. | entailment |
def f_cash(x, counts, bkg, model):
"""
Wrapper for cash statistics, that defines the model function.
Parameters
----------
x : float
Model amplitude.
counts : `~numpy.ndarray`
Count map slice, where model is defined.
bkg : `~numpy.ndarray`
Background map slice, where... | Wrapper for cash statistics, that defines the model function.
Parameters
----------
x : float
Model amplitude.
counts : `~numpy.ndarray`
Count map slice, where model is defined.
bkg : `~numpy.ndarray`
Background map slice, where model is defined.
model : `~numpy.ndarray`... | entailment |
def _ts_value(position, counts, bkg, model, C_0_map):
"""
Compute TS value at a given pixel position using the approach described
in Stewart (2009).
Parameters
----------
position : tuple
Pixel position.
counts : `~numpy.ndarray`
Count map.
bkg : `~numpy.ndarray`
... | Compute TS value at a given pixel position using the approach described
in Stewart (2009).
Parameters
----------
position : tuple
Pixel position.
counts : `~numpy.ndarray`
Count map.
bkg : `~numpy.ndarray`
Background map.
model : `~numpy.ndarray`
Source model... | entailment |
def _ts_value_newton(position, counts, bkg, model, C_0_map):
"""
Compute TS value at a given pixel position using the newton
method.
Parameters
----------
position : tuple
Pixel position.
counts : `~numpy.ndarray`
Count map.
bkg : `~numpy.ndarray`
Background ma... | Compute TS value at a given pixel position using the newton
method.
Parameters
----------
position : tuple
Pixel position.
counts : `~numpy.ndarray`
Count map.
bkg : `~numpy.ndarray`
Background map.
model : `~numpy.ndarray`
Source model map.
Returns
... | entailment |
def tsmap(self, 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 `~fermipy.skymap.Map` objects with
... | 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 `~fermipy.skymap.Map` objects with
the TS and amplitude of the best-fit test source.... | entailment |
def _make_tsmap_fast(self, prefix, **kwargs):
"""
Make a TS map from a GTAnalysis instance. This is a
simplified implementation optimized for speed that only fits
for the source normalization (all background components are
kept fixed). The spectral/spatial characteristics of the... | Make a TS map from a GTAnalysis instance. This is a
simplified implementation optimized for speed that only fits
for the source normalization (all background components are
kept fixed). The spectral/spatial characteristics of the test
source can be defined with the src_dict argument. B... | entailment |
def tscube(self, 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... | 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 a... | entailment |
def compute_ps_counts(ebins, exp, psf, bkg, fn, egy_dim=0, spatial_model='PointSource',
spatial_size=1E-3):
"""Calculate the observed signal and background counts given models
for the exposure, background intensity, PSF, and source flux.
Parameters
----------
ebins : `~numpy.n... | Calculate the observed signal and background counts given models
for the exposure, background intensity, PSF, and source flux.
Parameters
----------
ebins : `~numpy.ndarray`
Array of energy bin edges.
exp : `~numpy.ndarray`
Model for exposure.
psf : `~fermipy.irfs.PSFModel`
... | entailment |
def compute_norm(sig, bkg, ts_thresh, min_counts, sum_axes=None, bkg_fit=None,
rebin_axes=None):
"""Solve for the normalization of the signal distribution at which the
detection test statistic (twice delta-loglikelihood ratio) is >=
``ts_thresh`` AND the number of signal counts >= ``min_cou... | Solve for the normalization of the signal distribution at which the
detection test statistic (twice delta-loglikelihood ratio) is >=
``ts_thresh`` AND the number of signal counts >= ``min_counts``.
This function uses the Asimov method to calculate the median
expected TS when the model for the background... | entailment |
def create_psf(event_class, event_type, dtheta, egy, cth):
"""Create an array of PSF response values versus energy and
inclination angle.
Parameters
----------
egy : `~numpy.ndarray`
Energy in MeV.
cth : `~numpy.ndarray`
Cosine of the incidence angle.
"""
irf = create_... | Create an array of PSF response values versus energy and
inclination angle.
Parameters
----------
egy : `~numpy.ndarray`
Energy in MeV.
cth : `~numpy.ndarray`
Cosine of the incidence angle. | entailment |
def create_edisp(event_class, event_type, erec, egy, cth):
"""Create an array of energy response values versus energy and
inclination angle.
Parameters
----------
egy : `~numpy.ndarray`
Energy in MeV.
cth : `~numpy.ndarray`
Cosine of the incidence angle.
"""
irf = crea... | Create an array of energy response values versus energy and
inclination angle.
Parameters
----------
egy : `~numpy.ndarray`
Energy in MeV.
cth : `~numpy.ndarray`
Cosine of the incidence angle. | entailment |
def create_aeff(event_class, event_type, egy, cth):
"""Create an array of effective areas versus energy and incidence
angle. Binning in energy and incidence angle is controlled with
the egy and cth input parameters.
Parameters
----------
event_class : str
Event class string (e.g. P8R2_... | Create an array of effective areas versus energy and incidence
angle. Binning in energy and incidence angle is controlled with
the egy and cth input parameters.
Parameters
----------
event_class : str
Event class string (e.g. P8R2_SOURCE_V6).
event_type : list
egy : array_like
... | entailment |
def calc_exp(skydir, ltc, event_class, event_types,
egy, cth_bins, npts=None):
"""Calculate the exposure on a 2D grid of energy and incidence angle.
Parameters
----------
npts : int
Number of points by which to sample the response in each
incidence angle bin. If None t... | Calculate the exposure on a 2D grid of energy and incidence angle.
Parameters
----------
npts : int
Number of points by which to sample the response in each
incidence angle bin. If None then npts will be automatically
set such that incidence angle is sampled on intervals of <
... | entailment |
def create_avg_rsp(rsp_fn, skydir, ltc, event_class, event_types, x,
egy, cth_bins, npts=None):
"""Calculate the weighted response function.
"""
if npts is None:
npts = int(np.ceil(np.max(cth_bins[1:] - cth_bins[:-1]) / 0.05))
wrsp = np.zeros((len(x), len(egy), len(cth_bins) ... | Calculate the weighted response function. | entailment |
def create_avg_psf(skydir, ltc, event_class, event_types, dtheta,
egy, cth_bins, npts=None):
"""Generate model for exposure-weighted PSF averaged over incidence
angle.
Parameters
----------
egy : `~numpy.ndarray`
Energies in MeV.
cth_bins : `~numpy.ndarray`
B... | Generate model for exposure-weighted PSF averaged over incidence
angle.
Parameters
----------
egy : `~numpy.ndarray`
Energies in MeV.
cth_bins : `~numpy.ndarray`
Bin edges in cosine of the incidence angle. | entailment |
def create_avg_edisp(skydir, ltc, event_class, event_types, erec,
egy, cth_bins, npts=None):
"""Generate model for exposure-weighted DRM averaged over incidence
angle.
Parameters
----------
egy : `~numpy.ndarray`
True energies in MeV.
cth_bins : `~numpy.ndarray`
... | Generate model for exposure-weighted DRM averaged over incidence
angle.
Parameters
----------
egy : `~numpy.ndarray`
True energies in MeV.
cth_bins : `~numpy.ndarray`
Bin edges in cosine of the incidence angle. | entailment |
def create_wtd_psf(skydir, ltc, event_class, event_types, dtheta,
egy_bins, cth_bins, fn, nbin=64, npts=1):
"""Create an exposure- and dispersion-weighted PSF model for a source
with spectral parameterization ``fn``. The calculation performed
by this method accounts for the influence of ... | Create an exposure- and dispersion-weighted PSF model for a source
with spectral parameterization ``fn``. The calculation performed
by this method accounts for the influence of energy dispersion on
the PSF.
Parameters
----------
dtheta : `~numpy.ndarray`
egy_bins : `~numpy.ndarray`
... | entailment |
def calc_drm(skydir, ltc, event_class, event_types,
egy_bins, cth_bins, nbin=64):
"""Calculate the detector response matrix."""
npts = int(np.ceil(128. / bins_per_dec(egy_bins)))
egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts))
etrue_bins = 10**np.linspace(1.0, 6.5, nbin * ... | Calculate the detector response matrix. | entailment |
def calc_counts(skydir, ltc, event_class, event_types,
egy_bins, cth_bins, fn, npts=1):
"""Calculate the expected counts vs. true energy and incidence angle
for a source with spectral parameterization ``fn``.
Parameters
----------
skydir : `~astropy.coordinate.SkyCoord`
ltc : `... | Calculate the expected counts vs. true energy and incidence angle
for a source with spectral parameterization ``fn``.
Parameters
----------
skydir : `~astropy.coordinate.SkyCoord`
ltc : `~fermipy.irfs.LTCube`
egy_bins : `~numpy.ndarray`
Bin edges in observed energy in MeV.
cth_bi... | entailment |
def calc_counts_edisp(skydir, ltc, event_class, event_types,
egy_bins, cth_bins, fn, nbin=16, npts=1):
"""Calculate the expected counts vs. observed energy and true
incidence angle for a source with spectral parameterization ``fn``.
Parameters
----------
skydir : `~astropy.coo... | Calculate the expected counts vs. observed energy and true
incidence angle for a source with spectral parameterization ``fn``.
Parameters
----------
skydir : `~astropy.coordinate.SkyCoord`
ltc : `~fermipy.irfs.LTCube`
egy_bins : `~numpy.ndarray`
Bin edges in observed energy in MeV.
... | entailment |
def calc_wtd_exp(skydir, ltc, event_class, event_types,
egy_bins, cth_bins, fn, nbin=16):
"""Calculate the effective exposure.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
ltc : `~fermipy.irfs.LTCube`
nbin : int
Number of points per decade with w... | Calculate the effective exposure.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
ltc : `~fermipy.irfs.LTCube`
nbin : int
Number of points per decade with which to sample true energy. | entailment |
def create(cls, ltc, event_class, event_types, ebins):
"""Create an exposure map from a livetime cube. This method will
generate an exposure map with the same geometry as the
livetime cube (nside, etc.).
Parameters
----------
ltc : `~fermipy.irfs.LTCube`
Liv... | Create an exposure map from a livetime cube. This method will
generate an exposure map with the same geometry as the
livetime cube (nside, etc.).
Parameters
----------
ltc : `~fermipy.irfs.LTCube`
Livetime cube object.
event_class : str
Event cl... | entailment |
def eval(self, ebin, dtheta, scale_fn=None):
"""Evaluate the PSF at the given energy bin index.
Parameters
----------
ebin : int
Index of energy bin.
dtheta : array_like
Array of angular separations in degrees.
scale_fn : callable
... | Evaluate the PSF at the given energy bin index.
Parameters
----------
ebin : int
Index of energy bin.
dtheta : array_like
Array of angular separations in degrees.
scale_fn : callable
Function that evaluates the PSF scaling function.
... | entailment |
def interp(self, energies, dtheta, scale_fn=None):
"""Evaluate the PSF model at an array of energies and angular
separations.
Parameters
----------
energies : array_like
Array of energies in MeV.
dtheta : array_like
Array of angular separations i... | Evaluate the PSF model at an array of energies and angular
separations.
Parameters
----------
energies : array_like
Array of energies in MeV.
dtheta : array_like
Array of angular separations in degrees.
scale_fn : callable
Fu... | entailment |
def interp_bin(self, egy_bins, dtheta, scale_fn=None):
"""Evaluate the bin-averaged PSF model over the energy bins ``egy_bins``.
Parameters
----------
egy_bins : array_like
Energy bin edges in MeV.
dtheta : array_like
Array of angular separations in degr... | Evaluate the bin-averaged PSF model over the energy bins ``egy_bins``.
Parameters
----------
egy_bins : array_like
Energy bin edges in MeV.
dtheta : array_like
Array of angular separations in degrees.
scale_fn : callable
Function tha... | entailment |
def containment_angle(self, energies=None, fraction=0.68, scale_fn=None):
"""Evaluate the PSF containment angle at a sequence of energies."""
if energies is None:
energies = self.energies
vals = self.interp(energies[np.newaxis, :], self.dtheta[:, np.newaxis],
... | Evaluate the PSF containment angle at a sequence of energies. | entailment |
def containment_angle_bin(self, egy_bins, fraction=0.68, scale_fn=None):
"""Evaluate the PSF containment angle averaged over energy bins."""
vals = self.interp_bin(egy_bins, self.dtheta, scale_fn=scale_fn)
dtheta = np.radians(self.dtheta[:, np.newaxis] * np.ones(vals.shape))
return self... | Evaluate the PSF containment angle averaged over energy bins. | entailment |
def create(cls, skydir, ltc, event_class, event_types, energies, cth_bins=None,
ndtheta=500, use_edisp=False, fn=None, nbin=64):
"""Create a PSFModel object. This class can be used to evaluate the
exposure-weighted PSF for a source with a given observing
profile and energy distri... | Create a PSFModel object. This class can be used to evaluate the
exposure-weighted PSF for a source with a given observing
profile and energy distribution.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
ltc : `~fermipy.irfs.LTCube`
energies : `... | entailment |
def remove_file(filepath, dry_run=False):
"""Remove the file at filepath
Catches exception if the file does not exist.
If dry_run is True, print name of file to be removed, but do not remove it.
"""
if dry_run:
sys.stdout.write("rm %s\n" % filepath)
else:
try:
os.re... | Remove the file at filepath
Catches exception if the file does not exist.
If dry_run is True, print name of file to be removed, but do not remove it. | entailment |
def clean_job(logfile, outfiles, dry_run=False):
"""Removes log file and files created by failed jobs.
If dry_run is True, print name of files to be removed, but do not remove them.
"""
remove_file(logfile, dry_run)
for outfile in outfiles.values():
remove_file(outfile, dry_run) | Removes log file and files created by failed jobs.
If dry_run is True, print name of files to be removed, but do not remove them. | entailment |
def check_log(logfile, exited='Exited with exit code',
successful='Successfully completed'):
"""Check a log file to determine status of LSF job
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
----------
... | Check a log file to determine status of LSF job
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
exited : str
Value to check for in existing logf... | entailment |
def check_job(cls, job_details):
""" Check the status of a specfic job """
return check_log(job_details.logfile, cls.string_exited, cls.string_successful) | Check the status of a specfic job | entailment |
def dispatch_job_hook(self, link, key, job_config, logfile, stream=sys.stdout):
"""Hook to dispatch a single job"""
raise NotImplementedError("SysInterface.dispatch_job_hook") | Hook to dispatch a single job | entailment |
def dispatch_job(self, link, key, job_archive, stream=sys.stdout):
"""Function to dispatch a single job
Parameters
----------
link : `Link`
Link object that sendes the job
key : str
Key used to identify this particular job
job_archive : `JobArc... | Function to dispatch a single job
Parameters
----------
link : `Link`
Link object that sendes the job
key : str
Key used to identify this particular job
job_archive : `JobArchive`
Archive used to keep track of jobs
Returns `JobDeta... | entailment |
def submit_jobs(self, link, job_dict=None, job_archive=None, stream=sys.stdout):
"""Run the `Link` with all of the items job_dict as input.
If job_dict is None, the job_dict will be take from link.jobs
Returns a `JobStatus` enum
"""
failed = False
if job_dict is None:
... | Run the `Link` with all of the items job_dict as input.
If job_dict is None, the job_dict will be take from link.jobs
Returns a `JobStatus` enum | entailment |
def clean_jobs(self, link, job_dict=None, clean_all=False):
""" Clean up all the jobs associated with this link.
Returns a `JobStatus` enum
"""
failed = False
if job_dict is None:
job_dict = link.jobs
for job_details in job_dict.values():
# clean... | Clean up all the jobs associated with this link.
Returns a `JobStatus` enum | entailment |
def get_function_spec(name):
"""Return a dictionary with the specification of a function:
parameter names and defaults (value, bounds, scale, etc.).
Returns
-------
par_names : list
List of parameter names for this function.
norm_par : str
Name of normalization parameter.
... | Return a dictionary with the specification of a function:
parameter names and defaults (value, bounds, scale, etc.).
Returns
-------
par_names : list
List of parameter names for this function.
norm_par : str
Name of normalization parameter.
default : dict
Parameter def... | entailment |
def get_spatial_type(spatial_model):
"""Translate a spatial model string to a spatial type."""
if spatial_model in ['SkyDirFunction', 'PointSource',
'Gaussian']:
return 'SkyDirFunction'
elif spatial_model in ['SpatialMap']:
return 'SpatialMap'
elif spatial_model... | Translate a spatial model string to a spatial type. | entailment |
def create_pars_from_dict(name, pars_dict, rescale=True, update_bounds=False):
"""Create a dictionary for the parameters of a function.
Parameters
----------
name : str
Name of the function.
pars_dict : dict
Existing parameter dict that will be merged with the
default d... | Create a dictionary for the parameters of a function.
Parameters
----------
name : str
Name of the function.
pars_dict : dict
Existing parameter dict that will be merged with the
default dictionary created by this method.
rescale : bool
Rescale parameter values... | entailment |
def make_parameter_dict(pdict, fixed_par=False, rescale=True,
update_bounds=False):
"""
Update a parameter dictionary. This function will automatically
set the parameter scale and bounds if they are not defined.
Bounds are also adjusted to ensure that they encompass the
para... | Update a parameter dictionary. This function will automatically
set the parameter scale and bounds if they are not defined.
Bounds are also adjusted to ensure that they encompass the
parameter value. | entailment |
def cast_pars_dict(pars_dict):
"""Cast the bool and float elements of a parameters dict to
the appropriate python types.
"""
o = {}
for pname, pdict in pars_dict.items():
o[pname] = {}
for k, v in pdict.items():
if k == 'free':
o[pname][k] = bool(int(... | Cast the bool and float elements of a parameters dict to
the appropriate python types. | entailment |
def do_gather(flist):
""" Gather all the HDUs from a list of files"""
hlist = []
nskip = 3
for fname in flist:
fin = fits.open(fname)
if len(hlist) == 0:
if fin[1].name == 'SKYMAP':
nskip = 4
start = 0
else:
start = nskip
... | Gather all the HDUs from a list of files | entailment |
def main():
""" Main function for command line usage """
usage = "usage: %(prog)s [options] "
description = "Gather source maps from Fermi-LAT files."
parser = argparse.ArgumentParser(usage=usage, description=description)
parser.add_argument('-o', '--output', default=None, type=str,
... | Main function for command line usage | entailment |
def main_browse():
"""Entry point for command line use for browsing a JobArchive """
parser = argparse.ArgumentParser(usage="job_archive.py [options]",
description="Browse a job archive")
parser.add_argument('--jobs', action='store', dest='job_archive_table',
... | Entry point for command line use for browsing a JobArchive | entailment |
def n_waiting(self):
"""Return the number of jobs in various waiting states"""
return self._counters[JobStatus.no_job] +\
self._counters[JobStatus.unknown] +\
self._counters[JobStatus.not_ready] +\
self._counters[JobStatus.ready] | Return the number of jobs in various waiting states | entailment |
def n_failed(self):
"""Return the number of failed jobs"""
return self._counters[JobStatus.failed] + self._counters[JobStatus.partial_failed] | Return the number of failed jobs | entailment |
def get_status(self):
"""Return an overall status based
on the number of jobs in various states.
"""
if self.n_total == 0:
return JobStatus.no_job
elif self.n_done == self.n_total:
return JobStatus.done
elif self.n_failed > 0:
# If more... | Return an overall status based
on the number of jobs in various states. | entailment |
def make_tables(job_dict):
"""Build and return an `astropy.table.Table' to store `JobDetails`"""
col_dbkey = Column(name='dbkey', dtype=int)
col_jobname = Column(name='jobname', dtype='S64')
col_jobkey = Column(name='jobkey', dtype='S64')
col_appname = Column(name='appname', dtyp... | Build and return an `astropy.table.Table' to store `JobDetails` | entailment |
def get_file_ids(self, file_archive, creator=None, status=FileStatus.no_file):
"""Fill the file id arrays from the file lists
Parameters
----------
file_archive : `FileArchive`
Used to look up file ids
creator : int
A unique key for the job that created... | Fill the file id arrays from the file lists
Parameters
----------
file_archive : `FileArchive`
Used to look up file ids
creator : int
A unique key for the job that created these file
status : `FileStatus`
Enumeration giving current status... | entailment |
def get_file_paths(self, file_archive, file_id_array):
"""Get the full paths of the files used by this object from the the id arrays
Parameters
----------
file_archive : `FileArchive`
Used to look up file ids
file_id_array : `numpy.array`
Array that rema... | Get the full paths of the files used by this object from the the id arrays
Parameters
----------
file_archive : `FileArchive`
Used to look up file ids
file_id_array : `numpy.array`
Array that remaps the file indexes | entailment |
def _fill_array_from_list(the_list, the_array):
"""Fill an `array` from a `list`"""
for i, val in enumerate(the_list):
the_array[i] = val
return the_array | Fill an `array` from a `list` | entailment |
def make_dict(cls, table):
"""Build a dictionary map int to `JobDetails` from an `astropy.table.Table`"""
ret_dict = {}
for row in table:
job_details = cls.create_from_row(row)
ret_dict[job_details.dbkey] = job_details
return ret_dict | Build a dictionary map int to `JobDetails` from an `astropy.table.Table` | entailment |
def create_from_row(cls, table_row):
"""Create a `JobDetails` from an `astropy.table.row.Row` """
kwargs = {}
for key in table_row.colnames:
kwargs[key] = table_row[key]
infile_refs = kwargs.pop('infile_refs')
outfile_refs = kwargs.pop('outfile_refs')
rmfile_... | Create a `JobDetails` from an `astropy.table.row.Row` | entailment |
def append_to_tables(self, table, table_ids):
"""Add this instance as a row on a `astropy.table.Table` """
infile_refs = np.zeros((2), int)
outfile_refs = np.zeros((2), int)
rmfile_refs = np.zeros((2), int)
intfile_refs = np.zeros((2), int)
f_ptr = len(table_ids['file_id'... | Add this instance as a row on a `astropy.table.Table` | entailment |
def update_table_row(self, table, row_idx):
"""Add this instance as a row on a `astropy.table.Table` """
try:
table[row_idx]['timestamp'] = self.timestamp
table[row_idx]['status'] = self.status
except IndexError:
print("Index error", len(table), row_idx) | Add this instance as a row on a `astropy.table.Table` | entailment |
def check_status_logfile(self, checker_func):
"""Check on the status of this particular job using the logfile"""
self.status = checker_func(self.logfile)
return self.status | Check on the status of this particular job using the logfile | entailment |
def _fill_cache(self):
"""Fill the cache from the `astropy.table.Table`"""
for irow in range(len(self._table)):
job_details = self.make_job_details(irow)
self._cache[job_details.fullkey] = job_details | Fill the cache from the `astropy.table.Table` | entailment |
def _read_table_file(self, table_file):
"""Read an `astropy.table.Table` from table_file to set up the `JobArchive`"""
self._table_file = table_file
if os.path.exists(self._table_file):
self._table = Table.read(self._table_file, hdu='JOB_ARCHIVE')
self._table_ids = Table.... | Read an `astropy.table.Table` from table_file to set up the `JobArchive` | entailment |
def make_job_details(self, row_idx):
"""Create a `JobDetails` from an `astropy.table.row.Row` """
row = self._table[row_idx]
job_details = JobDetails.create_from_row(row)
job_details.get_file_paths(self._file_archive, self._table_id_array)
self._cache[job_details.fullkey] = job_d... | Create a `JobDetails` from an `astropy.table.row.Row` | entailment |
def get_details(self, jobname, jobkey):
"""Get the `JobDetails` associated to a particular job instance"""
fullkey = JobDetails.make_fullkey(jobname, jobkey)
return self._cache[fullkey] | Get the `JobDetails` associated to a particular job instance | entailment |
def register_job(self, job_details):
"""Register a job in this `JobArchive` """
# check to see if the job already exists
try:
job_details_old = self.get_details(job_details.jobname,
job_details.jobkey)
if job_details_old.stat... | Register a job in this `JobArchive` | entailment |
def register_jobs(self, job_dict):
"""Register a bunch of jobs in this archive"""
njobs = len(job_dict)
sys.stdout.write("Registering %i total jobs: " % njobs)
for i, job_details in enumerate(job_dict.values()):
if i % 10 == 0:
sys.stdout.write('.')
... | Register a bunch of jobs in this archive | entailment |
def register_job_from_link(self, link, key, **kwargs):
"""Register a job in the `JobArchive` from a `Link` object """
job_config = kwargs.get('job_config', None)
if job_config is None:
job_config = link.args
status = kwargs.get('status', JobStatus.unknown)
job_details... | Register a job in the `JobArchive` from a `Link` object | entailment |
def update_job(self, job_details):
"""Update a job in the `JobArchive` """
other = self.get_details(job_details.jobname,
job_details.jobkey)
other.timestamp = job_details.timestamp
other.status = job_details.status
other.update_table_row(self._tab... | Update a job in the `JobArchive` | entailment |
def remove_jobs(self, mask):
"""Mark all jobs that match a mask as 'removed' """
jobnames = self.table[mask]['jobname']
jobkey = self.table[mask]['jobkey']
self.table[mask]['status'] = JobStatus.removed
for jobname, jobkey in zip(jobnames, jobkey):
fullkey = JobDetail... | Mark all jobs that match a mask as 'removed' | entailment |
def build_temp_job_archive(cls):
"""Build and return a `JobArchive` using defualt locations of
persistent files. """
try:
os.unlink('job_archive_temp.fits')
os.unlink('file_archive_temp.fits')
except OSError:
pass
cls._archive = cls(job_archiv... | Build and return a `JobArchive` using defualt locations of
persistent files. | entailment |
def write_table_file(self, job_table_file=None, file_table_file=None):
"""Write the table to self._table_file"""
if self._table is None:
raise RuntimeError("No table to write")
if self._table_ids is None:
raise RuntimeError("No ID table to write")
if job_table_fil... | Write the table to self._table_file | entailment |
def update_job_status(self, checker_func):
"""Update the status of all the jobs in the archive"""
njobs = len(self.cache.keys())
status_vect = np.zeros((8), int)
sys.stdout.write("Updating status of %i jobs: " % njobs)
sys.stdout.flush()
for i, key in enumerate(self.cache... | Update the status of all the jobs in the archive | entailment |
def build_archive(cls, **kwargs):
"""Return the singleton `JobArchive` instance, building it if needed """
if cls._archive is None:
cls._archive = cls(**kwargs)
return cls._archive | Return the singleton `JobArchive` instance, building it if needed | entailment |
def elapsed_time(self):
"""Get the elapsed time."""
# Timer is running
if self._t0 is not None:
return self._time + self._get_time()
else:
return self._time | Get the elapsed time. | entailment |
def stop(self):
"""Stop the timer."""
if self._t0 is None:
raise RuntimeError('Timer not started.')
self._time += self._get_time()
self._t0 = None | Stop the timer. | entailment |
def make_spatialmap_source(name, Spatial_Filename, spectrum):
"""Construct and return a `fermipy.roi_model.Source` object
"""
data = dict(Spatial_Filename=Spatial_Filename,
ra=0.0, dec=0.0,
SpatialType='SpatialMap',
Source_Name=name)
if spectrum is not No... | Construct and return a `fermipy.roi_model.Source` object | entailment |
def make_mapcube_source(name, Spatial_Filename, spectrum):
"""Construct and return a `fermipy.roi_model.MapCubeSource` object
"""
data = dict(Spatial_Filename=Spatial_Filename)
if spectrum is not None:
data.update(spectrum)
return roi_model.MapCubeSource(name, data) | Construct and return a `fermipy.roi_model.MapCubeSource` object | entailment |
def make_isotropic_source(name, Spectrum_Filename, spectrum):
"""Construct and return a `fermipy.roi_model.IsoSource` object
"""
data = dict(Spectrum_Filename=Spectrum_Filename)
if spectrum is not None:
data.update(spectrum)
return roi_model.IsoSource(name, data) | Construct and return a `fermipy.roi_model.IsoSource` object | entailment |
def make_composite_source(name, spectrum):
"""Construct and return a `fermipy.roi_model.CompositeSource` object
"""
data = dict(SpatialType='CompositeSource',
SpatialModel='CompositeSource',
SourceType='CompositeSource')
if spectrum is not None:
data.update(spectr... | Construct and return a `fermipy.roi_model.CompositeSource` object | entailment |
def make_catalog_sources(catalog_roi_model, source_names):
"""Construct and return dictionary of sources that are a subset of sources
in catalog_roi_model.
Parameters
----------
catalog_roi_model : dict or `fermipy.roi_model.ROIModel`
Input set of sources
source_names : list
N... | Construct and return dictionary of sources that are a subset of sources
in catalog_roi_model.
Parameters
----------
catalog_roi_model : dict or `fermipy.roi_model.ROIModel`
Input set of sources
source_names : list
Names of sourcs to extract
Returns dict mapping source_name to... | entailment |
def make_sources(comp_key, comp_dict):
"""Make dictionary mapping component keys to a source
or set of sources
Parameters
----------
comp_key : str
Key used to access sources
comp_dict : dict
Information used to build sources
return `OrderedDict` maping comp_key to `fermi... | Make dictionary mapping component keys to a source
or set of sources
Parameters
----------
comp_key : str
Key used to access sources
comp_dict : dict
Information used to build sources
return `OrderedDict` maping comp_key to `fermipy.roi_model.Source` | entailment |
def add_sources(self, source_info_dict):
"""Add all of the sources in source_info_dict to this factory
"""
self._source_info_dict.update(source_info_dict)
for key, value in source_info_dict.items():
self._sources.update(make_sources(key, value)) | Add all of the sources in source_info_dict to this factory | entailment |
def build_catalog(**kwargs):
"""Build a `fermipy.catalog.Catalog` object
Parameters
----------
catalog_type : str
Specifies catalog type, options include 2FHL | 3FGL | 4FGLP
catalog_file : str
FITS file with catalog tables
catalog_extdir : str
... | Build a `fermipy.catalog.Catalog` object
Parameters
----------
catalog_type : str
Specifies catalog type, options include 2FHL | 3FGL | 4FGLP
catalog_file : str
FITS file with catalog tables
catalog_extdir : str
Path to directory with extende... | entailment |
def make_fermipy_roi_model_from_catalogs(cataloglist):
"""Build and return a `fermipy.roi_model.ROIModel object from
a list of fermipy.catalog.Catalog` objects
"""
data = dict(catalogs=cataloglist,
src_roiwidth=360.)
return roi_model.ROIModel(data, skydir=SkyC... | Build and return a `fermipy.roi_model.ROIModel object from
a list of fermipy.catalog.Catalog` objects | entailment |
def make_roi(cls, sources=None):
"""Build and return a `fermipy.roi_model.ROIModel` object from
a dict with information about the sources
"""
if sources is None:
sources = {}
src_fact = cls()
src_fact.add_sources(sources)
ret_model = roi_model.ROIModel... | Build and return a `fermipy.roi_model.ROIModel` object from
a dict with information about the sources | entailment |
def copy_selected_sources(cls, roi, source_names):
"""Build and return a `fermipy.roi_model.ROIModel` object
by copying selected sources from another such object
"""
roi_new = cls.make_roi()
for source_name in source_names:
try:
src_cp = roi.copy_sourc... | Build and return a `fermipy.roi_model.ROIModel` object
by copying selected sources from another such object | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.