sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def _register_self(self, logfile, key=JobDetails.topkey, status=JobStatus.unknown):
"""Runs this link, captures output to logfile,
and records the job in self.jobs"""
fullkey = JobDetails.make_fullkey(self.full_linkname, key)
if fullkey in self.jobs:
job_details = self.jobs[f... | Runs this link, captures output to logfile,
and records the job in self.jobs | entailment |
def _archive_self(self, logfile, key=JobDetails.topkey, status=JobStatus.unknown):
"""Write info about a job run by this `Link` to the job archive"""
self._register_self(logfile, key, status)
if self._job_archive is None:
return
self._job_archive.register_jobs(self.get_jobs()... | Write info about a job run by this `Link` to the job archive | entailment |
def _set_status_self(self, key=JobDetails.topkey, status=JobStatus.unknown):
"""Set the status of this job, both in self.jobs and
in the `JobArchive` if it is present. """
fullkey = JobDetails.make_fullkey(self.full_linkname, key)
if fullkey in self.jobs:
self.jobs[fullkey].s... | Set the status of this job, both in self.jobs and
in the `JobArchive` if it is present. | entailment |
def _write_status_to_log(self, return_code, stream=sys.stdout):
"""Write the status of this job to a log stream.
This is used to check on job completion."""
stream.write("Timestamp: %i\n" % get_timestamp())
if return_code == 0:
stream.write("%s\n" % self._interface.string_suc... | Write the status of this job to a log stream.
This is used to check on job completion. | entailment |
def _finalize(self, dry_run=False):
"""Remove / compress files as requested """
for rmfile in self.files.temp_files:
if dry_run:
print("remove %s" % rmfile)
else:
os.remove(rmfile)
for gzfile in self.files.gzip_files:
if dry_run... | Remove / compress files as requested | 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 of arguments to override the current values
... | 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 of arguments to override the current values | entailment |
def get_failed_jobs(self, fail_running=False, fail_pending=False):
"""Return a dictionary with the subset of jobs that are marked as failed
Parameters
----------
fail_running : `bool`
If True, consider running jobs as failed
fail_pending : `bool`
If True... | Return a dictionary with the subset of jobs that are marked as failed
Parameters
----------
fail_running : `bool`
If True, consider running jobs as failed
fail_pending : `bool`
If True, consider pending jobs as failed
Returns
-------
fai... | entailment |
def check_job_status(self, key=JobDetails.topkey,
fail_running=False,
fail_pending=False,
force_check=False):
"""Check the status of a particular job
By default this checks the status of the top-level job, but
can by mad... | Check the status of a particular job
By default this checks the status of the top-level job, but
can by made to drill into the sub-jobs.
Parameters
----------
key : str
Key associated to the job in question
fail_running : `bool`
If True, conside... | entailment |
def check_jobs_status(self,
fail_running=False,
fail_pending=False):
"""Check the status of all the jobs run from this link
and return a status flag that summarizes that.
Parameters
----------
fail_running : `bool`
... | Check the status of all the jobs run from this link
and return a status flag that summarizes that.
Parameters
----------
fail_running : `bool`
If True, consider running jobs as failed
fail_pending : `bool`
If True, consider pending jobs as failed
... | entailment |
def get_jobs(self, recursive=True):
"""Return a dictionary with all the jobs
For sub-classes, if recursive is True this will include jobs
from any internal `Link`
"""
if recursive:
ret_dict = self.jobs.copy()
return ret_dict
return self.jobs | Return a dictionary with all the jobs
For sub-classes, if recursive is True this will include jobs
from any internal `Link` | entailment |
def check_input_files(self,
return_found=True,
return_missing=True):
"""Check if input files exist.
Parameters
----------
return_found : list
A list with the paths of the files that were found.
return_missing : lis... | Check if input files exist.
Parameters
----------
return_found : list
A list with the paths of the files that were found.
return_missing : list
A list with the paths of the files that were missing.
Returns
-------
found : list
... | entailment |
def check_output_files(self,
return_found=True,
return_missing=True):
"""Check if output files exist.
Parameters
----------
return_found : list
A list with the paths of the files that were found.
return_missing :... | Check if output files exist.
Parameters
----------
return_found : list
A list with the paths of the files that were found.
return_missing : list
A list with the paths of the files that were missing.
Returns
-------
found : list
... | 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.
"""
missing = self.check_input_files(return_found=False)
ret_dict = {}
for miss_fil... | 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 missing_output_files(self):
"""Make and return a dictionary of the missing output files.
This returns a dictionary mapping
filepath to list of links that produce the file as output.
"""
missing = self.check_output_files(return_found=False)
ret_dict = {}
for m... | Make and return a dictionary of the missing output files.
This returns a dictionary mapping
filepath to list of links that produce the file as output. | entailment |
def formatted_command(self):
"""Build and return the formatted command for this `Link`.
This is exactly the command as called from the Unix command line.
"""
# FIXME, this isn't really great as it force you to have all the arguments
command_template = self.command_template()
... | Build and return the formatted command for this `Link`.
This is exactly the command as called from the Unix command line. | 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`
Stream that this `Link` will print to,
Must have ... | Runs the command for this link. This method can be overridden by
sub-classes to invoke a different command
Parameters
----------
stream : `file`
Stream that this `Link` will print to,
Must have 'write' function
dry_run : bool
Print command b... | entailment |
def run_with_log(self, dry_run=False, stage_files=True, resubmit_failed=False):
"""Runs this link with output sent to a pre-defined logfile
Parameters
-----------
dry_run : bool
Print command but do not run it.
stage_files : bool
Copy files to and from s... | Runs this link with output sent to a pre-defined logfile
Parameters
-----------
dry_run : bool
Print command but do not run it.
stage_files : bool
Copy files to and from scratch staging area.
resubmit_failed : bool
Flag for sub-classes to re... | 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
arg_string = "... | 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 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, must have 'write' method.
indent : str
Indentation at start of line... | Print a summary of the activity done by this `Link`.
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 distance_to_edge(geom, skydir):
"""Return the angular distance from the given direction and
the edge of the projection."""
# FIXME: We should add a pixel_size property in gammapy.maps
# FIXME: We should make this into a MapGeom method
xpix, ypix = skydir.to_pixel(geom.wcs, origin=0)
d... | Return the angular distance from the given direction and
the edge of the projection. | entailment |
def create_wcs(skydir, coordsys='CEL', projection='AIT',
cdelt=1.0, crpix=1., naxis=2, energies=None):
"""Create a WCS object.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Sky coordinate of the WCS reference point.
coordsys : str
projection : str
c... | Create a WCS object.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Sky coordinate of the WCS reference point.
coordsys : str
projection : str
cdelt : float or (float,float)
In the first case the same value is used for x and y axes
crpix : float or (float,f... | entailment |
def wcs_add_energy_axis(wcs, energies):
"""Copy a WCS object, and add on the energy axis.
Parameters
----------
wcs : `~astropy.wcs.WCS`
WCS
energies : array-like
Array of energies.
"""
if wcs.naxis != 2:
raise Exception(
'wcs_add_energy_axis, input WCS na... | Copy a WCS object, and add on the energy axis.
Parameters
----------
wcs : `~astropy.wcs.WCS`
WCS
energies : array-like
Array of energies. | entailment |
def offset_to_sky(skydir, offset_lon, offset_lat,
coordsys='CEL', projection='AIT'):
"""Convert a cartesian offset (X,Y) in the given projection into
a pair of spherical coordinates."""
offset_lon = np.array(offset_lon, ndmin=1)
offset_lat = np.array(offset_lat, ndmin=1)
w = crea... | Convert a cartesian offset (X,Y) in the given projection into
a pair of spherical coordinates. | entailment |
def sky_to_offset(skydir, lon, lat, coordsys='CEL', projection='AIT'):
"""Convert sky coordinates to a projected offset. This function
is the inverse of offset_to_sky."""
w = create_wcs(skydir, coordsys, projection)
skycrd = np.vstack((lon, lat)).T
if len(skycrd) == 0:
return skycrd
... | Convert sky coordinates to a projected offset. This function
is the inverse of offset_to_sky. | entailment |
def offset_to_skydir(skydir, offset_lon, offset_lat,
coordsys='CEL', projection='AIT'):
"""Convert a cartesian offset (X,Y) in the given projection into
a SkyCoord."""
offset_lon = np.array(offset_lon, ndmin=1)
offset_lat = np.array(offset_lat, ndmin=1)
w = create_wcs(skydir, ... | Convert a cartesian offset (X,Y) in the given projection into
a SkyCoord. | entailment |
def skydir_to_pix(skydir, wcs):
"""Convert skydir object to pixel coordinates.
Gracefully handles 0-d coordinate arrays.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
wcs : `~astropy.wcs.WCS`
Returns
-------
xp, yp : `numpy.ndarray`
The pixel coordinates
... | Convert skydir object to pixel coordinates.
Gracefully handles 0-d coordinate arrays.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
wcs : `~astropy.wcs.WCS`
Returns
-------
xp, yp : `numpy.ndarray`
The pixel coordinates | entailment |
def pix_to_skydir(xpix, ypix, wcs):
"""Convert pixel coordinates to a skydir object.
Gracefully handles 0-d coordinate arrays.
Always returns a celestial coordinate.
Parameters
----------
xpix : `numpy.ndarray`
ypix : `numpy.ndarray`
wcs : `~astropy.wcs.WCS`
"""
xpix = np.ar... | Convert pixel coordinates to a skydir object.
Gracefully handles 0-d coordinate arrays.
Always returns a celestial coordinate.
Parameters
----------
xpix : `numpy.ndarray`
ypix : `numpy.ndarray`
wcs : `~astropy.wcs.WCS` | entailment |
def wcs_to_axes(w, npix):
"""Generate a sequence of bin edge vectors corresponding to the
axes of a WCS object."""
npix = npix[::-1]
x = np.linspace(-(npix[0]) / 2., (npix[0]) / 2.,
npix[0] + 1) * np.abs(w.wcs.cdelt[0])
y = np.linspace(-(npix[1]) / 2., (npix[1]) / 2.,
... | Generate a sequence of bin edge vectors corresponding to the
axes of a WCS object. | entailment |
def wcs_to_coords(w, shape):
"""Generate an N x D list of pixel center coordinates where N is
the number of pixels and D is the dimensionality of the map."""
if w.naxis == 2:
y, x = wcs_to_axes(w, shape)
elif w.naxis == 3:
z, y, x = wcs_to_axes(w, shape)
else:
raise Exception... | Generate an N x D list of pixel center coordinates where N is
the number of pixels and D is the dimensionality of the map. | entailment |
def get_cel_to_gal_angle(skydir):
"""Calculate the rotation angle in radians between the longitude
axes of a local projection in celestial and galactic coordinates.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Direction of projection center.
Returns
-------
an... | Calculate the rotation angle in radians between the longitude
axes of a local projection in celestial and galactic coordinates.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Direction of projection center.
Returns
-------
angle : float
Rotation angle in rad... | entailment |
def extract_mapcube_region(infile, skydir, outfile, maphdu=0):
"""Extract a region out of an all-sky mapcube file.
Parameters
----------
infile : str
Path to mapcube file.
skydir : `~astropy.coordinates.SkyCoord`
"""
h = fits.open(os.path.expandvars(infile))
npix = 200
... | Extract a region out of an all-sky mapcube file.
Parameters
----------
infile : str
Path to mapcube file.
skydir : `~astropy.coordinates.SkyCoord` | entailment |
def distance_to_edge(self, skydir):
"""Return the angular distance from the given direction and
the edge of the projection."""
xpix, ypix = skydir.to_pixel(self.wcs, origin=0)
deltax = np.array((xpix - self._pix_center[0]) * self._pix_size[0],
ndmin=1)
... | Return the angular distance from the given direction and
the edge of the projection. | entailment |
def readlines(arg):
"""Read lines from a file into a list.
Removes whitespace and lines that start with '#'
"""
fin = open(arg)
lines_in = fin.readlines()
fin.close()
lines_out = []
for line in lines_in:
line = line.strip()
if not line or line[0] == '#':
cont... | Read lines from a file into a list.
Removes whitespace and lines that start with '#' | entailment |
def create_inputlist(arglist):
"""Read lines from a file and makes a list of file names.
Removes whitespace and lines that start with '#'
Recursively read all files with the extension '.lst'
"""
lines = []
if isinstance(arglist, list):
for arg in arglist:
if os.path.splitext... | Read lines from a file and makes a list of file names.
Removes whitespace and lines that start with '#'
Recursively read all files with the extension '.lst' | entailment |
def init(self):
"""Initialize histograms."""
evclass_shape = [16, 40, 10]
evtype_shape = [16, 16, 40, 10]
evclass_psf_shape = [16, 40, 10, 100]
evtype_psf_shape = [16, 16, 40, 10, 100]
self._hists_eff = dict()
self._hists = dict(evclass_on=np.zeros(evclass_shape... | Initialize histograms. | entailment |
def create_hist(self, evclass, evtype, xsep, energy, ctheta,
fill_sep=False, fill_evtype=False):
"""Load into a histogram."""
nevt = len(evclass)
ebin = utils.val_to_bin(self._energy_bins, energy)
scale = self._psf_scale[ebin]
vals = [energy, ctheta]
... | Load into a histogram. | entailment |
def calc_eff(self):
"""Calculate the efficiency."""
hists = self.hists
hists_out = self._hists_eff
cth_axis_idx = dict(evclass=2, evtype=3)
for k in ['evclass', 'evtype']:
if k == 'evclass':
ns0 = hists['evclass_on'][4][None, ...]
nb... | Calculate the efficiency. | entailment |
def calc_containment(self):
"""Calculate PSF containment."""
hists = self.hists
hists_out = self._hists_eff
quantiles = [0.34, 0.68, 0.90, 0.95]
cth_axis_idx = dict(evclass=2, evtype=3)
for k in ['evclass']: # ,'evtype']:
print(k)
non = hists['... | Calculate PSF containment. | entailment |
def create_default_config(schema):
"""Create a configuration dictionary from a schema dictionary.
The schema defines the valid configuration keys and their default
values. Each element of ``schema`` should be a tuple/list
containing (default value,docstring,type) or a dict containing a
nested schem... | Create a configuration dictionary from a schema dictionary.
The schema defines the valid configuration keys and their default
values. Each element of ``schema`` should be a tuple/list
containing (default value,docstring,type) or a dict containing a
nested schema. | entailment |
def update_from_schema(cfg, cfgin, schema):
"""Update configuration dictionary ``cfg`` with the contents of
``cfgin`` using the ``schema`` dictionary to determine the valid
input keys.
Parameters
----------
cfg : dict
Configuration dictionary to be updated.
cfgin : dict
New... | Update configuration dictionary ``cfg`` with the contents of
``cfgin`` using the ``schema`` dictionary to determine the valid
input keys.
Parameters
----------
cfg : dict
Configuration dictionary to be updated.
cfgin : dict
New configuration dictionary that will be merged with ... | entailment |
def write_config(self, outfile):
"""Write the configuration dictionary to an output file."""
utils.write_yaml(self.config, outfile, default_flow_style=False) | Write the configuration dictionary to an output file. | entailment |
def create(cls, configfile):
"""Create a configuration dictionary from a yaml config file.
This function will first populate the dictionary with defaults
taken from pre-defined configuration files. The configuration
dictionary is then updated with the user-defined configuration
... | Create a configuration dictionary from a yaml config file.
This function will first populate the dictionary with defaults
taken from pre-defined configuration files. The configuration
dictionary is then updated with the user-defined configuration
file. Any settings defined by the user ... | entailment |
def update_null_primary(hdu_in, hdu=None):
""" 'Update' a null primary HDU
This actually just checks hdu exists and creates it from hdu_in if it does not.
"""
if hdu is None:
hdu = fits.PrimaryHDU(header=hdu_in.header)
else:
hdu = hdu_in
hdu.header.remove('FILENAME')
ret... | 'Update' a null primary HDU
This actually just checks hdu exists and creates it from hdu_in if it does not. | entailment |
def update_primary(hdu_in, hdu=None):
""" 'Update' a primary HDU
This checks hdu exists and creates it from hdu_in if it does not.
If hdu does exist, this adds the data in hdu_in to hdu
"""
if hdu is None:
hdu = fits.PrimaryHDU(data=hdu_in.data, header=hdu_in.header)
else:
hdu.d... | 'Update' a primary HDU
This checks hdu exists and creates it from hdu_in if it does not.
If hdu does exist, this adds the data in hdu_in to hdu | entailment |
def update_image(hdu_in, hdu=None):
""" 'Update' an image HDU
This checks hdu exists and creates it from hdu_in if it does not.
If hdu does exist, this adds the data in hdu_in to hdu
"""
if hdu is None:
hdu = fits.ImageHDU(
data=hdu_in.data, header=hdu_in.header, name=hdu_in.nam... | 'Update' an image HDU
This checks hdu exists and creates it from hdu_in if it does not.
If hdu does exist, this adds the data in hdu_in to hdu | entailment |
def update_ebounds(hdu_in, hdu=None):
""" 'Update' the EBOUNDS HDU
This checks hdu exists and creates it from hdu_in if it does not.
If hdu does exist, this raises an exception if it doesn not match hdu_in
"""
if hdu is None:
hdu = fits.BinTableHDU(
data=hdu_in.data, header=hdu_... | 'Update' the EBOUNDS HDU
This checks hdu exists and creates it from hdu_in if it does not.
If hdu does exist, this raises an exception if it doesn not match hdu_in | entailment |
def merge_all_gti_data(datalist_in, nrows, first):
""" Merge together all the GTI data
Parameters
-------
datalist_in : list of `astropy.io.fits.BinTableHDU` data
The GTI data that is being merged
nrows : `~numpy.ndarray` of ints
Array with the number of nrows for each object in da... | Merge together all the GTI data
Parameters
-------
datalist_in : list of `astropy.io.fits.BinTableHDU` data
The GTI data that is being merged
nrows : `~numpy.ndarray` of ints
Array with the number of nrows for each object in datalist_in
first : `astropy.io.fits.BinTableHDU`
... | entailment |
def extract_gti_data(hdu_in):
""" Extract some GTI related data
Parameters
-------
hdu_in : `astropy.io.fits.BinTableHDU`
The GTI data
Returns
-------
data : `astropy.io.fits.BinTableHDU` data
exposure : float
Exposure value taken from FITS header
tstop : float
... | Extract some GTI related data
Parameters
-------
hdu_in : `astropy.io.fits.BinTableHDU`
The GTI data
Returns
-------
data : `astropy.io.fits.BinTableHDU` data
exposure : float
Exposure value taken from FITS header
tstop : float
TSTOP value taken from FITS head... | entailment |
def update_hpx_skymap_allsky(map_in, map_out):
""" 'Update' a HEALPix skymap
This checks map_out exists and creates it from map_in if it does not.
If map_out does exist, this adds the data in map_in to map_out
"""
if map_out is None:
in_hpx = map_in.hpx
out_hpx = HPX.create_hpx(in_h... | 'Update' a HEALPix skymap
This checks map_out exists and creates it from map_in if it does not.
If map_out does exist, this adds the data in map_in to map_out | entailment |
def merge_wcs_counts_cubes(filelist):
""" Merge all the files in filelist, assuming that they WCS counts cubes
"""
out_prim = None
out_ebounds = None
datalist_gti = []
exposure_sum = 0.
nfiles = len(filelist)
ngti = np.zeros(nfiles, int)
for i, filename in enumerate(filelist):
... | Merge all the files in filelist, assuming that they WCS counts cubes | entailment |
def merge_hpx_counts_cubes(filelist):
""" Merge all the files in filelist, assuming that they HEALPix counts cubes
"""
out_prim = None
out_skymap = None
out_ebounds = None
datalist_gti = []
exposure_sum = 0.
nfiles = len(filelist)
ngti = np.zeros(nfiles, int)
out_name = None
... | Merge all the files in filelist, assuming that they HEALPix counts cubes | 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.cmap,
... | Run this analysis | entailment |
def _make_xml_files(catalog_info_dict, comp_info_dict):
"""Make all the xml file for individual components
"""
for val in catalog_info_dict.values():
val.roi_model.write_xml(val.srcmdl_name)
for val in comp_info_dict.values():
for val2 in val.values():
... | Make all the xml file for individual components | 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'])
if self._comp_dict is None or self._comp_dict_file != args['library']:
... | Hook to build job configurations | entailment |
def run_analysis(self, argv):
"""Run this analysis"""
args = self._parser.parse_args(argv)
exttype = splitext(args.infile)[-1]
if exttype in ['.fits', '.npy']:
castro_data = CastroData.create_from_sedfile(args.infile)
elif exttype in ['.yaml']:
castro_dat... | 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 targets_yaml is None:
return job_configs
targets = load_yaml(targets_yaml... | Hook to build job configurations | entailment |
def sed(self, name, **kwargs):
"""Generate a spectral energy distribution (SED) for a source. This
function will fit the normalization of the source in each
energy bin. By default the SED will be generated with the
analysis energy bins but a custom binning can be defined with
t... | Generate a spectral energy distribution (SED) for a source. This
function will fit the normalization of the source in each
energy bin. By default the SED will be generated with the
analysis energy bins but a custom binning can be defined with
the ``loge_bins`` parameter.
Param... | 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.cmap,
... | Run this analysis | entailment |
def _write_xml(xmlfile, srcs):
"""Save the ROI model as an XML """
root = ElementTree.Element('source_library')
root.set('title', 'source_library')
for src in srcs:
src.write_xml(root)
output_file = open(xmlfile, 'w')
output_file.write(utils.prettify_xml(roo... | Save the ROI model as an XML | entailment |
def _handle_component(sourcekey, comp_dict):
"""Make the source objects and write the xml for a component
"""
if comp_dict.comp_key is None:
fullkey = sourcekey
else:
fullkey = "%s_%s" % (sourcekey, comp_dict.comp_key)
srcdict = make_sources(fullkey, comp_... | Make the source objects and write the xml for a component | entailment |
def _make_xml_files(diffuse_comp_info_dict):
"""Make all the xml file for individual components
"""
try:
os.makedirs('srcmdls')
except OSError:
pass
for sourcekey in sorted(diffuse_comp_info_dict.keys()):
comp_info = diffuse_comp_info_dict[sou... | Make all the xml file for individual components | 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_diffuse_comp_info_dict(components=components,
... | Hook to build job configurations | entailment |
def fit_error_ellipse(tsmap, xy=None, dpix=3, zmin=None):
"""Fit a positional uncertainty ellipse from a TS map. The fit
will be performed over pixels in the vicinity of the peak pixel
with D < dpix OR z > zmin where D is the distance from the peak
pixel in pixel coordinates and z is the difference in ... | Fit a positional uncertainty ellipse from a TS map. The fit
will be performed over pixels in the vicinity of the peak pixel
with D < dpix OR z > zmin where D is the distance from the peak
pixel in pixel coordinates and z is the difference in amplitude
from the peak pixel.
Parameters
----------... | entailment |
def find_peaks(input_map, threshold, min_separation=0.5):
"""Find peaks in a 2-D map object that have amplitude larger than
`threshold` and lie a distance at least `min_separation` from another
peak of larger amplitude. The implementation of this method uses
`~scipy.ndimage.filters.maximum_filter`.
... | Find peaks in a 2-D map object that have amplitude larger than
`threshold` and lie a distance at least `min_separation` from another
peak of larger amplitude. The implementation of this method uses
`~scipy.ndimage.filters.maximum_filter`.
Parameters
----------
input_map : `~gammapy.maps.WcsMap... | entailment |
def estimate_pos_and_err_parabolic(tsvals):
"""Solve for the position and uncertainty of source in one dimension
assuming that you are near the maximum and the errors are parabolic
Parameters
----------
tsvals : `~numpy.ndarray`
The TS values at the maximum TS, and for each pixel on e... | Solve for the position and uncertainty of source in one dimension
assuming that you are near the maximum and the errors are parabolic
Parameters
----------
tsvals : `~numpy.ndarray`
The TS values at the maximum TS, and for each pixel on either side
Returns
-------
The positio... | entailment |
def refine_peak(tsmap, pix):
"""Solve for the position and uncertainty of source assuming that you
are near the maximum and the errors are parabolic
Parameters
----------
tsmap : `~numpy.ndarray`
Array with the TS data.
Returns
-------
The position and uncertainty of the source,... | Solve for the position and uncertainty of source assuming that you
are near the maximum and the errors are parabolic
Parameters
----------
tsmap : `~numpy.ndarray`
Array with the TS data.
Returns
-------
The position and uncertainty of the source, in pixel units
w.r.t. the cente... | entailment |
def create_source_table(scan_shape):
"""Create an empty source table.
Returns
-------
tab : `~astropy.table.Table`
"""
cols_dict = collections.OrderedDict()
cols_dict['Source_Name'] = dict(dtype='S48', format='%s')
cols_dict['name'] = dict(dtype='S48', format='%s')
cols_dict['class... | Create an empty source table.
Returns
-------
tab : `~astropy.table.Table` | entailment |
def get_skydir_distance_mask(src_skydir, skydir, dist, min_dist=None,
square=False, coordsys='CEL'):
"""Retrieve sources within a certain angular distance of an
(ra,dec) coordinate. This function supports two types of
geometric selections: circular (square=False) and square
... | Retrieve sources within a certain angular distance of an
(ra,dec) coordinate. This function supports two types of
geometric selections: circular (square=False) and square
(square=True). The circular selection finds all sources with a given
angular distance of the target position. The square selection... | entailment |
def spectral_pars_from_catalog(cat):
"""Create spectral parameters from 3FGL catalog columns."""
spectrum_type = cat['SpectrumType']
pars = get_function_defaults(cat['SpectrumType'])
par_idxs = {k: i for i, k in
enumerate(get_function_par_names(cat['SpectrumType']))}
for k in pars:... | Create spectral parameters from 3FGL catalog columns. | entailment |
def is_free(self):
""" returns True if any of the spectral model parameters is set to free, else False
"""
return bool(np.array([int(value.get("free", False)) for key, value in self.spectral_pars.items()]).sum()) | returns True if any of the spectral model parameters is set to free, else False | entailment |
def set_position(self, skydir):
"""
Set the position of the source.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
"""
if not isinstance(skydir, SkyCoord):
skydir = SkyCoord(ra=skydir[0], dec=skydir[1], unit=u.deg)
if not s... | Set the position of the source.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord` | entailment |
def skydir(self):
"""Return a SkyCoord representation of the source position.
Returns
-------
skydir : `~astropy.coordinates.SkyCoord`
"""
return SkyCoord(self.radec[0] * u.deg, self.radec[1] * u.deg) | Return a SkyCoord representation of the source position.
Returns
-------
skydir : `~astropy.coordinates.SkyCoord` | entailment |
def create_from_dict(cls, src_dict, roi_skydir=None, rescale=False):
"""Create a source object from a python dictionary.
Parameters
----------
src_dict : dict
Dictionary defining the properties of the source.
"""
src_dict = copy.deepcopy(src_dict)
src... | Create a source object from a python dictionary.
Parameters
----------
src_dict : dict
Dictionary defining the properties of the source. | entailment |
def create_from_xmlfile(cls, xmlfile, extdir=None):
"""Create a Source object from an XML file.
Parameters
----------
xmlfile : str
Path to XML file.
extdir : str
Path to the extended source archive.
"""
root = ElementTree.ElementTree(fil... | Create a Source object from an XML file.
Parameters
----------
xmlfile : str
Path to XML file.
extdir : str
Path to the extended source archive. | entailment |
def create_from_xml(root, extdir=None):
"""Create a Source object from an XML node.
Parameters
----------
root : `~xml.etree.ElementTree.Element`
XML node containing the source.
extdir : str
Path to the extended source archive.
"""
src_t... | Create a Source object from an XML node.
Parameters
----------
root : `~xml.etree.ElementTree.Element`
XML node containing the source.
extdir : str
Path to the extended source archive. | entailment |
def write_xml(self, root):
"""Write this source to an XML node."""
if not self.extended:
try:
source_element = utils.create_xml_element(root, 'source',
dict(name=self['Source_Name'],
... | Write this source to an XML node. | entailment |
def clear(self):
"""Clear the contents of the ROI."""
self._srcs = []
self._diffuse_srcs = []
self._src_dict = collections.defaultdict(list)
self._src_radius = [] | Clear the contents of the ROI. | entailment |
def _create_diffuse_src_from_xml(self, config, src_type='FileFunction'):
"""Load sources from an XML file.
"""
diffuse_xmls = config.get('diffuse_xml')
srcs_out = []
for diffuse_xml in diffuse_xmls:
srcs_out += self.load_xml(diffuse_xml, coordsys=config.get('coordsys'... | Load sources from an XML file. | entailment |
def create_source(self, name, src_dict, build_index=True,
merge_sources=True, rescale=True):
"""Add a new source to the ROI model from a dictionary or an
existing source object.
Parameters
----------
name : str
src_dict : dict or `~fermipy.roi_mod... | Add a new source to the ROI model from a dictionary or an
existing source object.
Parameters
----------
name : str
src_dict : dict or `~fermipy.roi_model.Source`
Returns
-------
src : `~fermipy.roi_model.Source` | entailment |
def load_sources(self, sources):
"""Delete all sources in the ROI and load the input source list."""
self.clear()
for s in sources:
if isinstance(s, dict):
s = Model.create_from_dict(s)
self.load_source(s, build_index=False)
self._build_src_inde... | Delete all sources in the ROI and load the input source list. | entailment |
def load_source(self, src, build_index=True, merge_sources=True,
**kwargs):
"""
Load a single source.
Parameters
----------
src : `~fermipy.roi_model.Source`
Source object that will be added to the ROI.
merge_sources : bool
... | Load a single source.
Parameters
----------
src : `~fermipy.roi_model.Source`
Source object that will be added to the ROI.
merge_sources : bool
When a source matches an existing source in the model
update that source with the properties of the ... | entailment |
def match_source(self, src):
"""Look for source or sources in the model that match the
given source. Sources are matched by name and any association
columns defined in the assoc_xmatch_columns parameter.
"""
srcs = []
names = [src.name]
for col in self.config['... | Look for source or sources in the model that match the
given source. Sources are matched by name and any association
columns defined in the assoc_xmatch_columns parameter. | entailment |
def load(self, **kwargs):
"""Load both point source and diffuse components."""
coordsys = kwargs.get('coordsys', 'CEL')
extdir = kwargs.get('extdir', self.extdir)
srcname = kwargs.get('srcname', None)
self.clear()
self.load_diffuse_srcs()
for c in self.config['... | Load both point source and diffuse components. | entailment |
def create_from_roi_data(cls, datafile):
"""Create an ROI model."""
data = np.load(datafile).flat[0]
roi = cls()
roi.load_sources(data['sources'].values())
return roi | Create an ROI model. | entailment |
def create(cls, selection, config, **kwargs):
"""Create an ROIModel instance."""
if selection['target'] is not None:
return cls.create_from_source(selection['target'],
config, **kwargs)
else:
target_skydir = wcs_utils.get_target_... | Create an ROIModel instance. | entailment |
def create_from_position(cls, skydir, config, **kwargs):
"""Create an ROIModel instance centered on a sky direction.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Sky direction on which the ROI will be centered.
config : dict
Model con... | Create an ROIModel instance centered on a sky direction.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Sky direction on which the ROI will be centered.
config : dict
Model configuration dictionary. | entailment |
def create_from_source(cls, name, config, **kwargs):
"""Create an ROI centered on the given source."""
coordsys = kwargs.pop('coordsys', 'CEL')
roi = cls(config, src_radius=None, src_roiwidth=None,
srcname=name, **kwargs)
src = roi.get_source_by_name(name)
re... | Create an ROI centered on the given source. | entailment |
def get_source_by_name(self, name):
"""Return a single source in the ROI with the given name. The
input name string can match any of the strings in the names
property of the source object. Case and whitespace are
ignored when matching name strings. If no sources are found
or m... | Return a single source in the ROI with the given name. The
input name string can match any of the strings in the names
property of the source object. Case and whitespace are
ignored when matching name strings. If no sources are found
or multiple sources then an exception is thrown.
... | entailment |
def get_sources_by_name(self, name):
"""Return a list of sources in the ROI matching the given
name. The input name string can match any of the strings in
the names property of the source object. Case and whitespace
are ignored when matching name strings.
Parameters
--... | Return a list of sources in the ROI matching the given
name. The input name string can match any of the strings in
the names property of the source object. Case and whitespace
are ignored when matching name strings.
Parameters
----------
name : str
Returns
... | entailment |
def get_sources(self, skydir=None, distance=None, cuts=None,
minmax_ts=None, minmax_npred=None,
exclude=None, square=False, coordsys='CEL',
names=None):
"""Retrieve list of source objects satisfying the following
selections:
* Angular ... | Retrieve list of source objects satisfying the following
selections:
* Angular separation from ``skydir`` or ROI center (if
``skydir`` is None) less than ``distance``.
* Cuts on source properties defined in ``cuts`` list.
* TS and Npred in range specified by ``... | entailment |
def get_sources_by_position(self, skydir, dist, min_dist=None,
square=False, coordsys='CEL'):
"""Retrieve sources within a certain angular distance of a sky
coordinate. This function supports two types of geometric
selections: circular (square=False) and square (... | Retrieve sources within a certain angular distance of a sky
coordinate. This function supports two types of geometric
selections: circular (square=False) and square (square=True).
The circular selection finds all sources with a given angular
distance of the target position. The square ... | entailment |
def load_fits_catalog(self, name, **kwargs):
"""Load sources from a FITS catalog file.
Parameters
----------
name : str
Catalog name or path to a catalog FITS file.
"""
# EAC split this function to make it easier to load an existing catalog
cat = cat... | Load sources from a FITS catalog file.
Parameters
----------
name : str
Catalog name or path to a catalog FITS file. | entailment |
def load_existing_catalog(self, cat, **kwargs):
"""Load sources from an existing catalog object.
Parameters
----------
cat : `~fermipy.catalog.Catalog`
Catalog object.
"""
coordsys = kwargs.get('coordsys', 'CEL')
extdir = kwargs.get('extdir', self.ex... | Load sources from an existing catalog object.
Parameters
----------
cat : `~fermipy.catalog.Catalog`
Catalog object. | entailment |
def load_xml(self, xmlfile, **kwargs):
"""Load sources from an XML file."""
extdir = kwargs.get('extdir', self.extdir)
coordsys = kwargs.get('coordsys', 'CEL')
if not os.path.isfile(xmlfile):
xmlfile = os.path.join(fermipy.PACKAGE_DATA, 'catalogs', xmlfile)
root = E... | Load sources from an XML file. | entailment |
def _build_src_index(self):
"""Build an indices for fast lookup of a source given its name
or coordinates."""
self._srcs = sorted(self._srcs, key=lambda t: t['offset'])
nsrc = len(self._srcs)
radec = np.zeros((2, nsrc))
for i, src in enumerate(self._srcs):
r... | Build an indices for fast lookup of a source given its name
or coordinates. | entailment |
def write_xml(self, xmlfile, config=None):
"""Save the ROI model as an XML file."""
root = ElementTree.Element('source_library')
root.set('title', 'source_library')
for s in self._srcs:
s.write_xml(root)
if config is not None:
srcs = self.create_diffuse... | Save the ROI model as an XML file. | entailment |
def create_table(self, names=None):
"""Create an astropy Table object with the contents of the ROI model.
"""
scan_shape = (1,)
for src in self._srcs:
scan_shape = max(scan_shape, src['dloglike_scan'].shape)
tab = create_source_table(scan_shape)
for s in sel... | Create an astropy Table object with the contents of the ROI model. | entailment |
def write_fits(self, fitsfile):
"""Write the ROI model to a FITS file."""
tab = self.create_table()
hdu_data = fits.table_to_hdu(tab)
hdus = [fits.PrimaryHDU(), hdu_data]
fits_utils.write_hdus(hdus, fitsfile) | Write the ROI model to a FITS file. | entailment |
def to_ds9(self, free='box',fixed='cross',frame='fk5',color='green',header=True):
"""Returns a list of ds9 region definitions
Parameters
----------
free: bool
one of the supported ds9 point symbols, used for free sources, see here: http://ds9.si.edu/doc/ref/region.html
... | Returns a list of ds9 region definitions
Parameters
----------
free: bool
one of the supported ds9 point symbols, used for free sources, see here: http://ds9.si.edu/doc/ref/region.html
fixed: bool
as free but for fixed sources
frame: str
... | entailment |
def write_ds9region(self, region, *args, **kwargs):
"""Create a ds9 compatible region file from the ROI.
It calls the `to_ds9` method and write the result to the region file. Only the file name is required.
All other parameters will be forwarded to the `to_ds9` method, see the documentation of... | Create a ds9 compatible region file from the ROI.
It calls the `to_ds9` method and write the result to the region file. Only the file name is required.
All other parameters will be forwarded to the `to_ds9` method, see the documentation of that method
for all accepted parameters and options.
... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.