sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def merged_srcmaps(self, **kwargs):
""" return the name of a source map file
"""
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs))
kwargs_copy['component'] = kwargs.get(
'com... | return the name of a source map file | entailment |
def master_srcmdl_xml(self, **kwargs):
""" return the name of a source model file
"""
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
self._replace_none(kwargs_copy)
localpath = NameFactory.master_srcmdl_xml_format.format(**kwargs_copy)
if... | return the name of a source model file | entailment |
def comp_srcmdl_xml(self, **kwargs):
""" return the name of a source model file
"""
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs))
kwargs_copy['component'] = kwargs.get(
'... | return the name of a source model file | entailment |
def fullpath(self, **kwargs):
"""Return a full path name for a given file
"""
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
self._replace_none(kwargs_copy)
return NameFactory.fullpath_format.format(**kwargs_copy) | Return a full path name for a given file | entailment |
def generic(self, input_string, **kwargs):
""" return a generic filename for a given dataset and component
"""
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs))
kwargs_copy['component'] ... | return a generic filename for a given dataset and component | entailment |
def make_filenames(self, **kwargs):
""" Make a dictionary of filenames for various types
"""
out_dict = dict(ft1file=self.ft1file(**kwargs),
ltcube=self.ltcube(**kwargs),
ccube=self.ccube(**kwargs),
bexpcube=self.bexpcube(**... | Make a dictionary of filenames for various types | entailment |
def _map_arguments(self, args):
"""Map from the top-level arguments to the arguments provided to
the indiviudal links """
data = args.get('data')
comp = args.get('comp')
library = args.get('library')
dry_run = args.get('dry_run', False)
self._set_link('sum-rings'... | Map from the top-level arguments to the arguments provided to
the indiviudal links | entailment |
def _map_arguments(self, args):
"""Map from the top-level arguments to the arguments provided to
the indiviudal links """
data = args.get('data')
comp = args.get('comp')
library = args.get('library')
dry_run = args.get('dry_run', False)
self._set_link('srcmaps-ca... | Map from the top-level arguments to the arguments provided to
the indiviudal links | entailment |
def _map_arguments(self, args):
"""Map from the top-level arguments to the arguments provided to
the indiviudal links """
config_yaml = args['config']
config_dict = load_yaml(config_yaml)
dry_run = args.get('dry_run', False)
data = config_dict.get('data')
comp =... | Map from the top-level arguments to the arguments provided to
the indiviudal links | entailment |
def create_spectrum_from_dict(spectrum_type, spectral_pars, fn=None):
"""Create a Function object from a parameter dictionary.
Parameters
----------
spectrum_type : str
String identifying the spectrum type (e.g. PowerLaw).
spectral_pars : dict
Dictionary of spectral parameters.
... | Create a Function object from a parameter dictionary.
Parameters
----------
spectrum_type : str
String identifying the spectrum type (e.g. PowerLaw).
spectral_pars : dict
Dictionary of spectral parameters. | entailment |
def gtlike_spectrum_to_dict(spectrum):
""" Convert a pyLikelihood object to a python dictionary which can
be easily saved to a file."""
parameters = pyLike.ParameterVector()
spectrum.getParams(parameters)
d = dict(spectrum_type=spectrum.genericName())
for p in parameters:
pname = p.... | Convert a pyLikelihood object to a python dictionary which can
be easily saved to a file. | entailment |
def gtlike_spectrum_to_vectors(spectrum):
""" Convert a pyLikelihood object to a python dictionary which can
be easily saved to a file."""
parameters = pyLike.ParameterVector()
spectrum.getParams(parameters)
npar = max(parameters.size(), 10)
o = {'param_names': np.zeros(npar, dtype='S32')... | Convert a pyLikelihood object to a python dictionary which can
be easily saved to a file. | entailment |
def get_function_pars(fn):
"""Extract the parameters of a pyLikelihood function object
(value, scale, bounds).
Parameters
----------
fn : pyLikelihood.Function
Returns
-------
pars : list
"""
pars = []
par_names = pyLike.StringVector()
fn.getParamNames(par_names)
... | Extract the parameters of a pyLikelihood function object
(value, scale, bounds).
Parameters
----------
fn : pyLikelihood.Function
Returns
-------
pars : list | entailment |
def get_priors(like):
"""Extract priors from a likelihood object."""
npar = len(like.params())
vals = np.ones(npar)
errs = np.ones(npar)
has_prior = np.array([False] * npar)
for i, p in enumerate(like.params()):
prior = like[i].log_prior()
if prior is None:
conti... | Extract priors from a likelihood object. | entailment |
def get_source_pars(src):
"""Extract the parameters associated with a pyLikelihood Source object.
"""
fnmap = src.getSrcFuncs()
keys = fnmap.keys()
if 'Position' in keys:
ppars = get_function_pars(src.getSrcFuncs()[str('Position')])
elif 'SpatialDist' in keys:
ppars = get_fun... | Extract the parameters associated with a pyLikelihood Source object. | entailment |
def nFreeParams(self):
"""Count the number of free parameters in the active model."""
nF = 0
pars = self.params()
for par in pars:
if par.isFree():
nF += 1
return nF | Count the number of free parameters in the active model. | entailment |
def Ts2(self, srcName, reoptimize=False, approx=True,
tol=None, MaxIterations=10, verbosity=0):
"""Computes the TS value for a source indicated by "srcName."
If "reoptimize=True" is selected this function will reoptimize
the model up to "MaxIterations" given the tolerance "tol"
... | Computes the TS value for a source indicated by "srcName."
If "reoptimize=True" is selected this function will reoptimize
the model up to "MaxIterations" given the tolerance "tol"
(default is the tolerance selected for the overall fit). If
"appox=True" is selected (the default) it will... | entailment |
def _make_scatter_logfile_name(cls, key, linkname, job_config):
"""Hook to inster the name of a logfile into the input config """
logfile = job_config.get('logfile', "%s_%s_%s.log" %
(cls.default_prefix_logfile, linkname, key))
job_config['logfile'] = logfile | Hook to inster the name of a logfile into the input config | entailment |
def create(cls, **kwargs):
"""Build and return a `ScatterGather` object """
linkname = kwargs.setdefault('linkname', cls.clientclass.linkname_default)
# Don't use setdefault b/c we don't want to build a JobArchive
# Unless it is needed
job_archive = kwargs.get('job_archive', None... | Build and return a `ScatterGather` object | entailment |
def _latch_file_info(self):
"""Internal function to update the dictionaries
keeping track of input and output files
"""
self.files.file_dict.clear()
self.sub_files.file_dict.clear()
self.files.latch_file_info(self.args)
self._scatter_link._update_sub_file_dict(sel... | Internal function to update the dictionaries
keeping track of input and output files | entailment |
def _check_link_completion(self, link, fail_pending=False, fail_running=False):
"""Internal function to check the completion of all the dispatched jobs
Returns
-------
status_vect : `JobStatusVector`
Vector that summarize the number of jobs in various states.
"""
... | Internal function to check the completion of all the dispatched jobs
Returns
-------
status_vect : `JobStatusVector`
Vector that summarize the number of jobs in various states. | entailment |
def _build_job_dict(self):
"""Build a dictionary of `JobDetails` objects for the internal `Link`"""
if self.args['dry_run']:
status = JobStatus.unknown
else:
status = JobStatus.not_ready
base_config = self.scatter_link.args
for jobkey, job_config in sort... | Build a dictionary of `JobDetails` objects for the internal `Link` | entailment |
def _run_link(self, stream=sys.stdout, dry_run=False,
stage_files=True, resubmit_failed=False):
"""Internal function that actually runs this link.
This checks if input and output files are present.
If input files are missing this will raise `OSError` if dry_run is False
... | Internal function that actually runs this link.
This checks if input and output files are present.
If input files are missing this will raise `OSError` if dry_run is False
If all output files are present this will skip execution.
Parameters
-----------
stream : `file`
... | entailment |
def _invoke(self, argv, stream=sys.stdout, resubmit_failed=False):
"""Invoke this object to preform a particular action
Parameters
----------
argv : list
List of command line arguments, passed to helper classes
stream : `file`
Stream that this function ... | Invoke this object to preform a particular action
Parameters
----------
argv : list
List of command line arguments, passed to helper classes
stream : `file`
Stream that this function will print to,
must have 'write' function.
resubmit_faile... | entailment |
def update_args(self, override_args):
"""Update the arguments used to invoke the application
Note that this will also update the dictionary of input and output files
Parameters
----------
override_args : dict
dictionary of arguments to override the current values
... | Update the arguments used to invoke the application
Note that this will also update the dictionary of input and output files
Parameters
----------
override_args : dict
dictionary of arguments to override the current values | entailment |
def clear_jobs(self, recursive=True):
"""Clear the self.jobs dictionary that contains information
about jobs associated with this `ScatterGather`
If recursive is True this will include jobs from all internal `Link`
"""
if recursive:
self._scatter_link.clear_jobs(recu... | Clear the self.jobs dictionary that contains information
about jobs associated with this `ScatterGather`
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()
ret_dict.update(self._scatter_link.get_jobs(recursive))
ret... | Return a dictionary with all the jobs
If recursive is True this will include jobs from all internal `Link` | entailment |
def check_status(self, stream=sys.stdout,
check_once=False,
fail_pending=False, fail_running=False,
no_wait=False, do_print=True,
write_status=False):
"""Loop to check on the status of all the jobs in job dict.
Paramete... | Loop to check on the status of all the jobs in job dict.
Parameters
-----------
stream : `file`
Stream that this function will print to,
Must have 'write' function.
check_once : bool
Check status once and exit loop.
fail_pending : `bool`
... | entailment |
def run_jobs(self, stream=sys.stdout, resubmit_failed=False):
"""Function to dipatch jobs and collect results
Parameters
-----------
stream : `file`
Stream that this function will print to,
Must have 'write' function.
resubmit_failed : bool
R... | Function to dipatch jobs and collect results
Parameters
-----------
stream : `file`
Stream that this function will print to,
Must have 'write' function.
resubmit_failed : bool
Resubmit failed jobs.
Returns
-------
status_vect... | entailment |
def resubmit(self, stream=sys.stdout, fail_running=False, resubmit_failed=False):
"""Function to resubmit failed jobs and collect results
Parameters
-----------
stream : `file`
Stream that this function will print to,
Must have 'write' function.
fail_run... | Function to resubmit failed jobs and collect results
Parameters
-----------
stream : `file`
Stream that this function will print to,
Must have 'write' function.
fail_running : `bool`
If True, consider running jobs as failed
resubmit_failed :... | entailment |
def clean_jobs(self, recursive=False):
"""Clean up all the jobs associated with this object.
If recursive is True this also clean jobs dispatch by this
object."""
self._interface.clean_jobs(self.scatter_link,
clean_all=recursive) | Clean up all the jobs associated with this object.
If recursive is True this also clean jobs dispatch by this
object. | entailment |
def print_summary(self, stream=sys.stdout, indent="", recurse_level=2):
"""Print a summary of the activity done by this `Link`.
Parameters
----------
stream : `file`
Stream to print to
indent : str
Indentation at start of line
recurse_level : i... | Print a summary of the activity done by this `Link`.
Parameters
----------
stream : `file`
Stream to print to
indent : str
Indentation at start of line
recurse_level : int
Number of recursion levels to print | entailment |
def print_update(self, stream=sys.stdout, job_stats=None):
"""Print an update about the current number of jobs running """
if job_stats is None:
job_stats = JobStatusVector()
job_det_list = []
job_det_list += self._scatter_link.jobs.values()
for job_dets ... | Print an update about the current number of jobs running | entailment |
def print_failed(self, stream=sys.stderr):
"""Print list of the failed jobs """
for job_key, job_details in sorted(self.scatter_link.jobs.items()):
if job_details.status == JobStatus.failed:
stream.write("Failed job %s\n log = %s\n" %
(job_key, j... | Print list of the failed jobs | entailment |
def read_sources_from_numpy_file(npfile):
""" Open a numpy pickle file and read all the new sources into a dictionary
Parameters
----------
npfile : file name
The input numpy pickle file
Returns
-------
tab : `~astropy.table.Table`
"""
srcs = np.load(npfile).flat[0]['sources... | Open a numpy pickle file and read all the new sources into a dictionary
Parameters
----------
npfile : file name
The input numpy pickle file
Returns
-------
tab : `~astropy.table.Table` | entailment |
def read_sources_from_yaml_file(yamlfile):
""" Open a yaml file and read all the new sources into a dictionary
Parameters
----------
yaml : file name
The input yaml file
Returns
-------
tab : `~astropy.table.Table`
"""
f = open(yamlfile)
dd = yaml.load(f)
srcs = dd['... | Open a yaml file and read all the new sources into a dictionary
Parameters
----------
yaml : file name
The input yaml file
Returns
-------
tab : `~astropy.table.Table` | entailment |
def merge_source_tables(src_tab, tab, all_sources=False, prefix="", suffix="",
roi_idx=None):
"""Append the sources in a table into another table.
Parameters
----------
src_tab : `~astropy.table.Table`
Master source table that will be appended with the sources in
... | Append the sources in a table into another table.
Parameters
----------
src_tab : `~astropy.table.Table`
Master source table that will be appended with the sources in
``tab``.
tab : `~astropy.table.Table`
Table to be merged into ``src_tab``.
all_sources : bool
If ... | entailment |
def lightcurve(self, 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
... | 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 c... | entailment |
def main():
""" Main function for command line usage """
usage = "usage: %(prog)s [options] "
description = "Merge a set of 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 fill_livetime_hist(skydir, tab_sc, tab_gti, zmax, costh_edges):
"""Generate a sequence of livetime distributions at the sky
positions given by ``skydir``. The output of the method are two
NxM arrays containing a sequence of histograms for N sky positions
and M incidence angle bins where the bin edg... | Generate a sequence of livetime distributions at the sky
positions given by ``skydir``. The output of the method are two
NxM arrays containing a sequence of histograms for N sky positions
and M incidence angle bins where the bin edges are defined by
``costh_edges``. This method uses the same algorithm... | entailment |
def create(cls, ltfile):
"""Create a livetime cube from a single file or list of
files."""
if not re.search('\.txt?', ltfile) is None:
files = np.loadtxt(ltfile, unpack=True, dtype='str')
elif not isinstance(ltfile, list):
files = glob.glob(ltfile)
ltc =... | Create a livetime cube from a single file or list of
files. | entailment |
def create_empty(cls, tstart, tstop, fill=0.0, nside=64):
"""Create an empty livetime cube."""
cth_edges = np.linspace(0, 1.0, 41)
domega = utils.edge_to_width(cth_edges) * 2.0 * np.pi
hpx = HPX(nside, True, 'CEL', ebins=cth_edges)
data = np.ones((len(cth_edges) - 1, hpx.npix)) *... | Create an empty livetime cube. | entailment |
def get_skydir_lthist(self, skydir, cth_bins):
"""Get the livetime distribution (observing profile) for a given sky
direction with binning in incidence angle defined by
``cth_bins``.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Sky coordinat... | Get the livetime distribution (observing profile) for a given sky
direction with binning in incidence angle defined by
``cth_bins``.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Sky coordinate for which the observing profile will be
comp... | entailment |
def create_skydir_ltcube(self, skydir, tab_sc, tab_gti, zmax):
"""Create a new livetime cube by scaling this one by the
observing profile ratio in the direction ``skydir``. This
method can be used to generate an approximate livetime cube
that is accurate in the vicinity of ``skydir``.
... | Create a new livetime cube by scaling this one by the
observing profile ratio in the direction ``skydir``. This
method can be used to generate an approximate livetime cube
that is accurate in the vicinity of ``skydir``.
Parameters
----------
skydir : `~astropy.coordina... | entailment |
def write(self, outfile):
"""Write the livetime cube to a FITS file."""
hdu_pri = fits.PrimaryHDU()
hdu_exp = self._create_exp_hdu(self.data)
hdu_exp.name = 'EXPOSURE'
hdu_exp_wt = self._create_exp_hdu(self._data_wt)
hdu_exp_wt.name = 'WEIGHTED_EXPOSURE'
cols =... | Write the livetime cube to a FITS file. | entailment |
def main():
""" Main function for command line usage """
usage = "usage: %(prog)s [options] "
description = "Merge a set of 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 make_cube_slice(map_in, loge_bounds):
"""Extract a slice from a map cube object.
"""
# FIXME: This functionality should be moved into a slice method of
# gammapy.maps
axis = map_in.geom.axes[0]
i0 = utils.val_to_edge(axis.edges, 10**loge_bounds[0])[0]
i1 = utils.val_to_edge(axis.edges, 1... | Extract a slice from a map cube object. | entailment |
def plot_sed(sed, showlnl=False, **kwargs):
"""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
Color... | 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
... | entailment |
def run(self, gta, mcube_map, **kwargs):
"""Make all plots."""
prefix = kwargs.get('prefix', 'test')
format = kwargs.get('format', self.config['format'])
loge_bounds = [None] + self.config['loge_bounds']
for x in loge_bounds:
self.make_roi_plots(gta, mcube_map, loge... | Make all plots. | entailment |
def make_residmap_plots(self, maps, roi=None, **kwargs):
"""Make plots from the output of
`~fermipy.gtanalysis.GTAnalysis.residmap`.
Parameters
----------
maps : dict
Output dictionary of
`~fermipy.gtanalysis.GTAnalysis.residmap`.
roi : `~fermipy... | Make plots from the output of
`~fermipy.gtanalysis.GTAnalysis.residmap`.
Parameters
----------
maps : dict
Output dictionary of
`~fermipy.gtanalysis.GTAnalysis.residmap`.
roi : `~fermipy.roi_model.ROIModel`
ROI Model object. Generate markers... | entailment |
def make_tsmap_plots(self, maps, roi=None, **kwargs):
"""Make plots from the output of
`~fermipy.gtanalysis.GTAnalysis.tsmap` or
`~fermipy.gtanalysis.GTAnalysis.tscube`. This method
generates a 2D sky map for the best-fit test source in
sqrt(TS) and Npred.
Parameters
... | Make plots from the output of
`~fermipy.gtanalysis.GTAnalysis.tsmap` or
`~fermipy.gtanalysis.GTAnalysis.tscube`. This method
generates a 2D sky map for the best-fit test source in
sqrt(TS) and Npred.
Parameters
----------
maps : dict
Output dictionar... | entailment |
def make_roi_plots(self, gta, mcube_tot, **kwargs):
"""Make various diagnostic plots for the 1D and 2D
counts/model distributions.
Parameters
----------
prefix : str
Prefix that will be appended to all filenames.
"""
fmt = kwargs.get('format', self... | Make various diagnostic plots for the 1D and 2D
counts/model distributions.
Parameters
----------
prefix : str
Prefix that will be appended to all filenames. | entailment |
def _plot_extension(self, gta, prefix, src, loge_bounds=None, **kwargs):
"""Utility function for generating diagnostic plots for the
extension analysis."""
# format = kwargs.get('format', self.config['plotting']['format'])
if loge_bounds is None:
loge_bounds = (self.energie... | Utility function for generating diagnostic plots for the
extension analysis. | entailment |
def extract_parameters(pil, keys=None):
"""Extract and return parameter names and values from a pil object
Parameters
----------
pil : `Pil` object
keys : list
List of parameter names, if None, extact all parameters
Returns
-------
out_dict : dict
Dictionary with par... | Extract and return parameter names and values from a pil object
Parameters
----------
pil : `Pil` object
keys : list
List of parameter names, if None, extact all parameters
Returns
-------
out_dict : dict
Dictionary with parameter name, value pairs | entailment |
def update_gtapp(gtapp, **kwargs):
"""Update the parameters of the object that can run ScienceTools applications
Parameters
----------
gtapp : `GtApp.GtApp`
Object that will run the application in question
kwargs : arguments used to invoke the application
"""
for key, val in kwar... | Update the parameters of the object that can run ScienceTools applications
Parameters
----------
gtapp : `GtApp.GtApp`
Object that will run the application in question
kwargs : arguments used to invoke the application | entailment |
def _set_pfiles(dry_run, **kwargs):
"""Set the PFILES env var
Parameters
----------
dry_run : bool
Don't actually run
Keyword arguments
-----------------
pfiles : str
Value to set PFILES
Returns
-------
pfiles_orig : str
Current value of PFILES e... | Set the PFILES env var
Parameters
----------
dry_run : bool
Don't actually run
Keyword arguments
-----------------
pfiles : str
Value to set PFILES
Returns
-------
pfiles_orig : str
Current value of PFILES envar | entailment |
def build_gtapp(appname, dry_run, **kwargs):
"""Build an object that can run ScienceTools application
Parameters
----------
appname : str
Name of the application (e.g., gtbin)
dry_run : bool
Print command but do not run it
kwargs : arguments used to invoke the application
... | Build an object that can run ScienceTools application
Parameters
----------
appname : str
Name of the application (e.g., gtbin)
dry_run : bool
Print command but do not run it
kwargs : arguments used to invoke the application
Returns `GtApp.GtApp` object that will run the appl... | entailment |
def run_gtapp(gtapp, stream, dry_run, **kwargs):
"""Runs one on the ScienceTools apps
Taken from fermipy.gtanalysis.run_gtapp by Matt Wood
Parameters
----------
gtapp : `GtApp.GtApp` object
The application (e.g., gtbin)
stream : stream object
Must have 'write' function
d... | Runs one on the ScienceTools apps
Taken from fermipy.gtanalysis.run_gtapp by Matt Wood
Parameters
----------
gtapp : `GtApp.GtApp` object
The application (e.g., gtbin)
stream : stream object
Must have 'write' function
dry_run : bool
Print command but do not run it
... | entailment |
def update_args(self, override_args):
"""Update the argument used to invoke the application
See help for `chain.Link` for details
This calls the base class function then fills the parameters of the GtApp object
"""
Link.update_args(self, override_args)
dry_run = overrid... | Update the argument used to invoke the application
See help for `chain.Link` for details
This calls the base class function then fills the parameters of the GtApp object | entailment |
def run_command(self, stream=sys.stdout, dry_run=False):
"""Runs the command for this link. This method can be overridden by
sub-classes to invoke a different command
Parameters
-----------
stream : `file`
Must have 'write' function
dry_run : bool
... | Runs the command for this link. This method can be overridden by
sub-classes to invoke a different command
Parameters
-----------
stream : `file`
Must have 'write' function
dry_run : bool
Print command but do not run it | entailment |
def command_template(self):
"""Build and return a string that can be used as a template invoking
this chain from the command line.
The actual command can be obtainted by using
`self.command_template().format(**self.args)`
"""
com_out = self.appname
for key, val i... | Build and return a string that can be used as a template invoking
this chain from the command line.
The actual command can be obtainted by using
`self.command_template().format(**self.args)` | entailment |
def run_analysis(self, argv):
""" Build the manifest for all the models
"""
args = self._parser.parse_args(argv)
components = Component.build_from_yamlfile(args.comp)
NAME_FACTORY.update_base_dict(args.data)
model_dict = make_library(**args.__dict__)
model_manager... | Build the manifest for all the models | entailment |
def copy_ccube(ccube, outsrcmap, hpx_order):
"""Copy a counts cube into outsrcmap file
reducing the HEALPix order to hpx_order if needed.
"""
sys.stdout.write(" Copying counts cube from %s to %s\n" % (ccube, outsrcmap))
try:
hdulist_in = fits.open(ccube)
exce... | Copy a counts cube into outsrcmap file
reducing the HEALPix order to hpx_order if needed. | entailment |
def append_hdus(hdulist, srcmap_file, source_names, hpx_order):
"""Append HEALPix maps to a list
Parameters
----------
hdulist : list
The list being appended to
srcmap_file : str
Path to the file containing the HDUs
source_names : list of str
... | Append HEALPix maps to a list
Parameters
----------
hdulist : list
The list being appended to
srcmap_file : str
Path to the file containing the HDUs
source_names : list of str
Names of the sources to extract from srcmap_file
hpx_order... | entailment |
def assemble_component(compname, compinfo, hpx_order):
"""Assemble the source map file for one binning component
Parameters
----------
compname : str
The key for this component (e.g., E0_PSF3)
compinfo : dict
Information about this component
hpx_... | Assemble the source map file for one binning component
Parameters
----------
compname : str
The key for this component (e.g., E0_PSF3)
compinfo : dict
Information about this component
hpx_order : int
Maximum order for maps | entailment |
def run_analysis(self, argv):
"""Assemble the source map file for one binning component
FIXME
"""
args = self._parser.parse_args(argv)
manifest = yaml.safe_load(open(args.input))
compname = args.compname
value = manifest[compname]
self.assemble_component(... | Assemble the source map file for one binning component
FIXME | 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'])
models = load_yaml(args['models'])
for modelkey in models:
... | 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 """
data = input_dict.get('data')
comp = input_dict.get('comp')
library = input_dict.get('library')
models = input_dict.get('models')
hpx_or... | Map from the top-level arguments to the arguments provided to
the indiviudal links | entailment |
def run_analysis(self, argv):
"""Run this analysis"""
args = self._parser.parse_args(argv)
if not HAVE_ST:
raise RuntimeError(
"Trying to run fermipy analysis, but don't have ST")
gta = GTAnalysis(args.config, logging={'verbosity': 3},
... | Run this analysis | entailment |
def run_analysis(self, argv):
"""Run this analysis"""
args = self._parser.parse_args(argv)
if not HAVE_ST:
raise RuntimeError(
"Trying to run fermipy analysis, but don't have ST")
if is_null(args.skydirs):
skydir_dict = None
else:
... | Run this analysis | entailment |
def build_job_configs(self, args):
"""Hook to build job configurations
"""
job_configs = {}
ttype = args['ttype']
(targets_yaml, sim) = NAME_FACTORY.resolve_targetfile(args)
if sim is not None:
raise ValueError("Found 'sim' argument on AnalyzeROI_SG config.")... | Hook to build job configurations | entailment |
def read_data(self, size):
"""Receive data from the device.
If the read fails for any reason, an :obj:`IOError` exception
is raised.
:param size: the number of bytes to read.
:type size: int
:return: the data received.
:rtype: list(int)
"""
r... | Receive data from the device.
If the read fails for any reason, an :obj:`IOError` exception
is raised.
:param size: the number of bytes to read.
:type size: int
:return: the data received.
:rtype: list(int) | entailment |
def write_data(self, buf):
"""Send data to the device.
:param buf: the data to send.
:type buf: list(int)
:return: success status.
:rtype: bool
"""
data = ''.join(map(chr, buf))
size = len(data)
if hidapi.hid_write(self.device, ctypes.c_char_p... | Send data to the device.
:param buf: the data to send.
:type buf: list(int)
:return: success status.
:rtype: bool | entailment |
def zambretti_code(params, hourly_data):
"""Simple implementation of Zambretti forecaster algorithm.
Inspired by beteljuice.com Java algorithm, as converted to Python by
honeysucklecottage.me.uk, and further information
from http://www.meteormetrics.com/zambretti.htm"""
north = literal_eval(params.g... | Simple implementation of Zambretti forecaster algorithm.
Inspired by beteljuice.com Java algorithm, as converted to Python by
honeysucklecottage.me.uk, and further information
from http://www.meteormetrics.com/zambretti.htm | entailment |
def read_block(self, address):
"""Read 32 bytes from the weather station.
If the read fails for any reason, :obj:`None` is returned.
:param address: address to read from.
:type address: int
:return: the data from the weather station.
:rtype: list(int)
"""
... | Read 32 bytes from the weather station.
If the read fails for any reason, :obj:`None` is returned.
:param address: address to read from.
:type address: int
:return: the data from the weather station.
:rtype: list(int) | entailment |
def write_byte(self, address, data):
"""Write a single byte to the weather station.
:param address: address to write to.
:type address: int
:param data: the value to write.
:type data: int
:return: success status.
:rtype: bool
"""
buf = [
... | Write a single byte to the weather station.
:param address: address to write to.
:type address: int
:param data: the value to write.
:type data: int
:return: success status.
:rtype: bool | entailment |
def inc_ptr(self, ptr):
"""Get next circular buffer data pointer."""
result = ptr + self.reading_len[self.ws_type]
if result >= 0x10000:
result = self.data_start
return result | Get next circular buffer data pointer. | entailment |
def dec_ptr(self, ptr):
"""Get previous circular buffer data pointer."""
result = ptr - self.reading_len[self.ws_type]
if result < self.data_start:
result = 0x10000 - self.reading_len[self.ws_type]
return result | Get previous circular buffer data pointer. | entailment |
def get_raw_data(self, ptr, unbuffered=False):
"""Get raw data from circular buffer.
If unbuffered is false then a cached value that was obtained
earlier may be returned."""
if unbuffered:
self._data_pos = None
# round down ptr to a 'block boundary'
idx = ptr... | Get raw data from circular buffer.
If unbuffered is false then a cached value that was obtained
earlier may be returned. | entailment |
def get_data(self, ptr, unbuffered=False):
"""Get decoded data from circular buffer.
If unbuffered is false then a cached value that was obtained
earlier may be returned."""
result = _decode(self.get_raw_data(ptr, unbuffered),
self._reading_format[self.ws_type])... | Get decoded data from circular buffer.
If unbuffered is false then a cached value that was obtained
earlier may be returned. | entailment |
def current_pos(self):
"""Get circular buffer location where current data is being written."""
new_ptr = _decode(
self._read_fixed_block(0x0020), self.lo_fix_format['current_pos'])
if new_ptr == self._current_ptr:
return self._current_ptr
if self._current_ptr and ... | Get circular buffer location where current data is being written. | entailment |
def get_raw_fixed_block(self, unbuffered=False):
"""Get the raw "fixed block" of settings and min/max data."""
if unbuffered or not self._fixed_block:
self._fixed_block = self._read_fixed_block()
return self._fixed_block | Get the raw "fixed block" of settings and min/max data. | entailment |
def get_fixed_block(self, keys=[], unbuffered=False):
"""Get the decoded "fixed block" of settings and min/max data.
A subset of the entire block can be selected by keys."""
if unbuffered or not self._fixed_block:
self._fixed_block = self._read_fixed_block()
format = self.fi... | Get the decoded "fixed block" of settings and min/max data.
A subset of the entire block can be selected by keys. | entailment |
def write_data(self, data):
"""Write a set of single bytes to the weather station. Data must be an
array of (ptr, value) pairs."""
# send data
for ptr, value in data:
self._write_byte(ptr, value)
# set 'data changed'
self._write_byte(self.fixed_format['data_ch... | Write a set of single bytes to the weather station. Data must be an
array of (ptr, value) pairs. | entailment |
def _find_device(self, idVendor, idProduct):
"""Find a USB device by product and vendor id."""
for bus in usb.busses():
for device in bus.devices:
if (device.idVendor == idVendor and
device.idProduct == idProduct):
return device
... | Find a USB device by product and vendor id. | entailment |
def read_data(self, size):
"""Receive data from the device.
If the read fails for any reason, an :obj:`IOError` exception
is raised.
:param size: the number of bytes to read.
:type size: int
:return: the data received.
:rtype: list(int)
"""
r... | Receive data from the device.
If the read fails for any reason, an :obj:`IOError` exception
is raised.
:param size: the number of bytes to read.
:type size: int
:return: the data received.
:rtype: list(int) | entailment |
def write_data(self, buf):
"""Send data to the device.
If the write fails for any reason, an :obj:`IOError` exception
is raised.
:param buf: the data to send.
:type buf: list(int)
:return: success status.
:rtype: bool
"""
result = self.devh.c... | Send data to the device.
If the write fails for any reason, an :obj:`IOError` exception
is raised.
:param buf: the data to send.
:type buf: list(int)
:return: success status.
:rtype: bool | entailment |
def _adapt_WSDateTime(dt):
"""Return unix timestamp of the datetime like input.
If conversion overflows high, return sint64_max ,
if underflows, return 0
"""
try:
ts = int(
(dt.replace(tzinfo=pytz.utc)
- datetime(1970,1,1,tzinfo=pytz.utc)
).total_seconds()... | Return unix timestamp of the datetime like input.
If conversion overflows high, return sint64_max ,
if underflows, return 0 | entailment |
def _predicate(self, i):
"""Given a valid datetime or slace, return the predicate portion
of the SQL query, a boolean indicating whether multiple items are
expected from the result, and a dictionary of parameters for the query
"""
if isinstance(i, slice):
if i.step is... | Given a valid datetime or slace, return the predicate portion
of the SQL query, a boolean indicating whether multiple items are
expected from the result, and a dictionary of parameters for the query | entailment |
def update(self, i):
"""D.update(E) -> None. Update D from iterable E with pre-existing
items being overwritten.
Elements in E are assumed to be dicts containing the primary key to
allow the equivelent of:
for k in E: D[k.primary_key] = k
"""
key_list = ... | D.update(E) -> None. Update D from iterable E with pre-existing
items being overwritten.
Elements in E are assumed to be dicts containing the primary key to
allow the equivelent of:
for k in E: D[k.primary_key] = k | entailment |
def before(self, i):
"""Return datetime of newest existing data record whose datetime
is < idx. If no such record exists, return None.
"""
if not isinstance(i, datetime):
raise TypeError("'{}' is not a datetime object".format(i))
else:
result = self._conne... | Return datetime of newest existing data record whose datetime
is < idx. If no such record exists, return None. | entailment |
def keys(self):
"""D.keys() -> a set-like object providing a view on D's keys"""
return set(
row[self._keycol] for row in self._connection.execute(
"""SELECT DISTINCT {} FROM {} ORDER BY {} ASC;""".format(
self.selkeycol,
self.table,
... | D.keys() -> a set-like object providing a view on D's keys | entailment |
def items(self):
"""D.items() -> a set-like object providing a view on D's items"""
keycol = self._keycol
for row in self.__iter__():
yield (row[keycol], dict(row)) | D.items() -> a set-like object providing a view on D's items | entailment |
def clear(self):
"""S.clear() -> None -- remove all items from S"""
with self._connection as con:
con.execute("DELETE FROM {};".format(self.table)) | S.clear() -> None -- remove all items from S | entailment |
def popitem(self):
"""D.popitem() -> (k, v)
Remove and return some (key, value) pair
as a 2-tuple; but raise KeyError if D is empty.
"""
try:
value = next(iter(self))
key = value[self._keycol]
except StopIteration:
raise KeyErr... | D.popitem() -> (k, v)
Remove and return some (key, value) pair
as a 2-tuple; but raise KeyError if D is empty. | entailment |
def set_locale(lang):
"""Set the 'locale' used by a program.
This affects the entire application, changing the way dates,
currencies and numbers are represented. It should not be called
from a library routine that may be used in another program.
The ``lang`` parameter can be any string that is rec... | Set the 'locale' used by a program.
This affects the entire application, changing the way dates,
currencies and numbers are represented. It should not be called
from a library routine that may be used in another program.
The ``lang`` parameter can be any string that is recognised by
``locale.setlo... | entailment |
def set_translation(lang):
"""Set the translation used by (some) pywws modules.
This sets the translation object ``pywws.localisation.translation``
to use a particular language.
The ``lang`` parameter can be any string of the form ``en``,
``en_GB`` or ``en_GB.UTF-8``. Anything after a ``.`` charac... | Set the translation used by (some) pywws modules.
This sets the translation object ``pywws.localisation.translation``
to use a particular language.
The ``lang`` parameter can be any string of the form ``en``,
``en_GB`` or ``en_GB.UTF-8``. Anything after a ``.`` character is
ignored. In the case of... | entailment |
def set_application_language(params):
"""Set the locale and translation for a pywws program.
This function reads the language from the configuration file, then
calls :func:`set_locale` and :func:`set_translation`.
:param params: a :class:`pywws.storage.params` object.
:type params: object
""... | Set the locale and translation for a pywws program.
This function reads the language from the configuration file, then
calls :func:`set_locale` and :func:`set_translation`.
:param params: a :class:`pywws.storage.params` object.
:type params: object | entailment |
def read_data(self, size):
"""Receive data from the device.
If the read fails for any reason, an :obj:`IOError` exception
is raised.
:param size: the number of bytes to read.
:type size: int
:return: the data received.
:rtype: list(int)
"""
r... | Receive data from the device.
If the read fails for any reason, an :obj:`IOError` exception
is raised.
:param size: the number of bytes to read.
:type size: int
:return: the data received.
:rtype: list(int) | entailment |
def write_data(self, buf):
"""Send data to the device.
:param buf: the data to send.
:type buf: list(int)
:return: success status.
:rtype: bool
"""
if self.hid.write(buf) != len(buf):
raise IOError(
'pywws.device_cython_hidapi.USBD... | Send data to the device.
:param buf: the data to send.
:type buf: list(int)
:return: success status.
:rtype: bool | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.