sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def build_from_yamlfile(yamlfile):
""" Build a list of components from a yaml file
"""
d = yaml.load(open(yamlfile))
return MktimeFilterDict(d['aliases'], d['selections']) | Build a list of components from a yaml file | 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_not_null(args.roi_baseline):
gta = GTAnalysis.create(args.ro... | Run this analysis | entailment |
def collect_jobs(dirs, runscript, overwrite=False, max_job_age=90):
"""Construct a list of job dictionaries."""
jobs = []
for dirname in sorted(dirs):
o = dict(cfgfile=os.path.join(dirname, 'config.yaml'),
logfile=os.path.join(
dirname, os.path.splitext(runsc... | Construct a list of job dictionaries. | entailment |
def make_srcmap_old(psf, spatial_model, sigma, npix=500, xpix=0.0, ypix=0.0,
cdelt=0.01, rebin=1, psf_scale_fn=None):
"""Compute the source map for a given spatial model.
Parameters
----------
psf : `~fermipy.irfs.PSFModel`
spatial_model : str
Spatial model.
sigma : ... | Compute the source map for a given spatial model.
Parameters
----------
psf : `~fermipy.irfs.PSFModel`
spatial_model : str
Spatial model.
sigma : float
Spatial size parameter for extended models.
xpix : float
Source position in pixel coordinates in X dimension.
ypix ... | entailment |
def make_srcmap(psf, exp, spatial_model, sigma, npix=500, xpix=0.0, ypix=0.0,
cdelt=0.01, psf_scale_fn=None, klims=None, sparse=False):
"""Compute the source map for a given spatial model.
Parameters
----------
psf : `~fermipy.irfs.PSFModel`
exp : `~numpy.ndarray`
Array of ... | Compute the source map for a given spatial model.
Parameters
----------
psf : `~fermipy.irfs.PSFModel`
exp : `~numpy.ndarray`
Array of exposures.
spatial_model : str
Spatial model.
sigma : float
Spatial size parameter for extended models.
xpix : float
Sou... | entailment |
def delete_source_map(srcmap_file, names, logger=None):
"""Delete a map from a binned analysis source map file if it exists.
Parameters
----------
srcmap_file : str
Path to the source map file.
names : list
List of HDU keys of source maps to be deleted.
"""
with fits.open(sr... | Delete a map from a binned analysis source map file if it exists.
Parameters
----------
srcmap_file : str
Path to the source map file.
names : list
List of HDU keys of source maps to be deleted. | entailment |
def get_offsets(self, pix):
"""Get offset of the first pixel in each dimension in the
global coordinate system.
Parameters
----------
pix : `~numpy.ndarray`
Pixel coordinates in global coordinate system.
"""
idx = []
for i in range(self.ndim)... | Get offset of the first pixel in each dimension in the
global coordinate system.
Parameters
----------
pix : `~numpy.ndarray`
Pixel coordinates in global coordinate system. | entailment |
def shift_to_coords(self, pix, fill_value=np.nan):
"""Create a new map that is shifted to the pixel coordinates
``pix``."""
pix_offset = self.get_offsets(pix)
dpix = np.zeros(len(self.shape) - 1)
for i in range(len(self.shape) - 1):
x = self.rebin * (pix[i] - pix_off... | Create a new map that is shifted to the pixel coordinates
``pix``. | entailment |
def create_map(self, pix):
"""Create a new map with reference pixel coordinates shifted
to the pixel coordinates ``pix``.
Parameters
----------
pix : `~numpy.ndarray`
Reference pixel of new map.
Returns
-------
out_map : `~numpy.ndarray`
... | Create a new map with reference pixel coordinates shifted
to the pixel coordinates ``pix``.
Parameters
----------
pix : `~numpy.ndarray`
Reference pixel of new map.
Returns
-------
out_map : `~numpy.ndarray`
The shifted map. | entailment |
def render_pep440(vcs):
"""Convert git release tag into a form that is PEP440 compliant."""
if vcs is None:
return None
tags = vcs.split('-')
# Bare version number
if len(tags) == 1:
return tags[0]
else:
return tags[0] + '+' + '.'.join(tags[1:]) | Convert git release tag into a form that is PEP440 compliant. | entailment |
def read_release_version():
"""Read the release version from ``_version.py``."""
import re
dirname = os.path.abspath(os.path.dirname(__file__))
try:
f = open(os.path.join(dirname, "_version.py"), "rt")
for line in f.readlines():
m = re.match("__version__ = '([^']+)'", line)... | Read the release version from ``_version.py``. | entailment |
def write_release_version(version):
"""Write the release version to ``_version.py``."""
dirname = os.path.abspath(os.path.dirname(__file__))
f = open(os.path.join(dirname, "_version.py"), "wt")
f.write("__version__ = '%s'\n" % version)
f.close() | Write the release version to ``_version.py``. | entailment |
def make_full_path(basedir, outkey, origname):
"""Make a full file path by combining tokens
Parameters
-----------
basedir : str
The top level output area
outkey : str
The key for the particular instance of the analysis
origname : str
Template for the output file name... | Make a full file path by combining tokens
Parameters
-----------
basedir : str
The top level output area
outkey : str
The key for the particular instance of the analysis
origname : str
Template for the output file name
Returns
-------
outpath : str
T... | entailment |
def _map_arguments(self, args):
"""Map from the top-level arguments to the arguments provided to
the indiviudal links """
comp_file = args.get('comp', None)
datafile = args.get('data', None)
if is_null(comp_file):
return
if is_null(datafile):
retur... | Map from the top-level arguments to the arguments provided to
the indiviudal links | entailment |
def build_job_configs(self, args):
"""Hook to build job configurations
"""
job_configs = {}
comp_file = args.get('comp', None)
if comp_file is not None:
comp_dict = yaml.safe_load(open(comp_file))
coordsys = comp_dict.pop('coordsys')
for v in ... | Hook to build job configurations | 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')
ft1file = args.get('ft1file')
ft2file = args.get('ft2file')
scratch = args.get('scratch', None... | Map from the top-level arguments to the arguments provided to
the indiviudal links | entailment |
def init_matplotlib_backend(backend=None):
"""This function initializes the matplotlib backend. When no
DISPLAY is available the backend is automatically set to 'Agg'.
Parameters
----------
backend : str
matplotlib backend name.
"""
import matplotlib
try:
os.environ['D... | This function initializes the matplotlib backend. When no
DISPLAY is available the backend is automatically set to 'Agg'.
Parameters
----------
backend : str
matplotlib backend name. | entailment |
def load_data(infile, workdir=None):
"""Load python data structure from either a YAML or numpy file. """
infile = resolve_path(infile, workdir=workdir)
infile, ext = os.path.splitext(infile)
if os.path.isfile(infile + '.npy'):
infile += '.npy'
elif os.path.isfile(infile + '.yaml'):
... | Load python data structure from either a YAML or numpy file. | entailment |
def resolve_file_path_list(pathlist, workdir, prefix='',
randomize=False):
"""Resolve the path of each file name in the file ``pathlist`` and
write the updated paths to a new file.
"""
files = []
with open(pathlist, 'r') as f:
files = [line.strip() for line in f]
... | Resolve the path of each file name in the file ``pathlist`` and
write the updated paths to a new file. | entailment |
def collect_dirs(path, max_depth=1, followlinks=True):
"""Recursively find directories under the given path."""
if not os.path.isdir(path):
return []
o = [path]
if max_depth == 0:
return o
for subdir in os.listdir(path):
subdir = os.path.join(path, subdir)
if no... | Recursively find directories under the given path. | entailment |
def match_regex_list(patterns, string):
"""Perform a regex match of a string against a list of patterns.
Returns true if the string matches at least one pattern in the
list."""
for p in patterns:
if re.findall(p, string):
return True
return False | Perform a regex match of a string against a list of patterns.
Returns true if the string matches at least one pattern in the
list. | entailment |
def find_rows_by_string(tab, names, colnames=['assoc']):
"""Find the rows in a table ``tab`` that match at least one of the
strings in ``names``. This method ignores whitespace and case
when matching strings.
Parameters
----------
tab : `astropy.table.Table`
Table that will be searched.... | Find the rows in a table ``tab`` that match at least one of the
strings in ``names``. This method ignores whitespace and case
when matching strings.
Parameters
----------
tab : `astropy.table.Table`
Table that will be searched.
names : list
List of strings.
colname : str
... | entailment |
def project(lon0, lat0, lon1, lat1):
"""This function performs a stereographic projection on the unit
vector (lon1,lat1) with the pole defined at the reference unit
vector (lon0,lat0)."""
costh = np.cos(np.pi / 2. - lat0)
cosphi = np.cos(lon0)
sinth = np.sin(np.pi / 2. - lat0)
sinphi = np.... | This function performs a stereographic projection on the unit
vector (lon1,lat1) with the pole defined at the reference unit
vector (lon0,lat0). | entailment |
def separation_cos_angle(lon0, lat0, lon1, lat1):
"""Evaluate the cosine of the angular separation between two
direction vectors."""
return (np.sin(lat1) * np.sin(lat0) + np.cos(lat1) * np.cos(lat0) *
np.cos(lon1 - lon0)) | Evaluate the cosine of the angular separation between two
direction vectors. | entailment |
def angle_to_cartesian(lon, lat):
"""Convert spherical coordinates to cartesian unit vectors."""
theta = np.array(np.pi / 2. - lat)
return np.vstack((np.sin(theta) * np.cos(lon),
np.sin(theta) * np.sin(lon),
np.cos(theta))).T | Convert spherical coordinates to cartesian unit vectors. | entailment |
def create_model_name(src):
"""Generate a name for a source object given its spatial/spectral
properties.
Parameters
----------
src : `~fermipy.roi_model.Source`
A source object.
Returns
-------
name : str
A source name.
"""
o = ''
spatial_type = src['S... | Generate a name for a source object given its spatial/spectral
properties.
Parameters
----------
src : `~fermipy.roi_model.Source`
A source object.
Returns
-------
name : str
A source name. | entailment |
def cov_to_correlation(cov):
"""Compute the correlation matrix given the covariance matrix.
Parameters
----------
cov : `~numpy.ndarray`
N x N matrix of covariances among N parameters.
Returns
-------
corr : `~numpy.ndarray`
N x N matrix of correlations among N parameters.
... | Compute the correlation matrix given the covariance matrix.
Parameters
----------
cov : `~numpy.ndarray`
N x N matrix of covariances among N parameters.
Returns
-------
corr : `~numpy.ndarray`
N x N matrix of correlations among N parameters. | entailment |
def ellipse_to_cov(sigma_maj, sigma_min, theta):
"""Compute the covariance matrix in two variables x and y given
the std. deviation along the semi-major and semi-minor axes and
the rotation angle of the error ellipse.
Parameters
----------
sigma_maj : float
Std. deviation along major ax... | Compute the covariance matrix in two variables x and y given
the std. deviation along the semi-major and semi-minor axes and
the rotation angle of the error ellipse.
Parameters
----------
sigma_maj : float
Std. deviation along major axis of error ellipse.
sigma_min : float
Std.... | entailment |
def onesided_cl_to_dlnl(cl):
"""Compute the delta-loglikehood values that corresponds to an
upper limit of the given confidence level.
Parameters
----------
cl : float
Confidence level.
Returns
-------
dlnl : float
Delta-loglikelihood value with respect to the maximum o... | Compute the delta-loglikehood values that corresponds to an
upper limit of the given confidence level.
Parameters
----------
cl : float
Confidence level.
Returns
-------
dlnl : float
Delta-loglikelihood value with respect to the maximum of the
likelihood function. | entailment |
def find_function_root(fn, x0, xb, delta=0.0, bounds=None):
"""Find the root of a function: f(x)+delta in the interval encompassed
by x0 and xb.
Parameters
----------
fn : function
Python function.
x0 : float
Fixed bound for the root search. This will either be used as
t... | Find the root of a function: f(x)+delta in the interval encompassed
by x0 and xb.
Parameters
----------
fn : function
Python function.
x0 : float
Fixed bound for the root search. This will either be used as
the lower or upper bound depending on the relative value of xb.
... | entailment |
def get_parameter_limits(xval, loglike, cl_limit=0.95, cl_err=0.68269, tol=1E-2,
bounds=None):
"""Compute upper/lower limits, peak position, and 1-sigma errors
from a 1-D likelihood function. This function uses the
delta-loglikelihood method to evaluate parameter limits by
sear... | Compute upper/lower limits, peak position, and 1-sigma errors
from a 1-D likelihood function. This function uses the
delta-loglikelihood method to evaluate parameter limits by
searching for the point at which the change in the log-likelihood
value with respect to the maximum equals a specific value. A... | entailment |
def parabola(xy, amplitude, x0, y0, sx, sy, theta):
"""Evaluate a 2D parabola given by:
f(x,y) = f_0 - (1/2) * \delta^T * R * \Sigma * R^T * \delta
where
\delta = [(x - x_0), (y - y_0)]
and R is the matrix for a 2D rotation by angle \theta and \Sigma
is the covariance matrix:
\Sigma = [... | Evaluate a 2D parabola given by:
f(x,y) = f_0 - (1/2) * \delta^T * R * \Sigma * R^T * \delta
where
\delta = [(x - x_0), (y - y_0)]
and R is the matrix for a 2D rotation by angle \theta and \Sigma
is the covariance matrix:
\Sigma = [[1/\sigma_x^2, 0 ],
[0 , ... | entailment |
def get_region_mask(z, delta, xy=None):
"""Get mask of connected region within delta of max(z)."""
if xy is None:
ix, iy = np.unravel_index(np.argmax(z), z.shape)
else:
ix, iy = xy
mz = (z > z[ix, iy] - delta)
labels = label(mz)[0]
mz &= labels == labels[ix, iy]
return mz | Get mask of connected region within delta of max(z). | entailment |
def fit_parabola(z, ix, iy, dpix=3, zmin=None):
"""Fit a parabola to a 2D numpy array. This function will fit a
parabola with the functional form described in
`~fermipy.utils.parabola` to a 2D slice of the input array `z`.
The fit region encompasses pixels that are within `dpix` of the
pixel coordi... | Fit a parabola to a 2D numpy array. This function will fit a
parabola with the functional form described in
`~fermipy.utils.parabola` to a 2D slice of the input array `z`.
The fit region encompasses pixels that are within `dpix` of the
pixel coordinate (iz,iy) OR that have a value relative to the peak
... | entailment |
def split_bin_edges(edges, npts=2):
"""Subdivide an array of bins by splitting each bin into ``npts``
subintervals.
Parameters
----------
edges : `~numpy.ndarray`
Bin edge array.
npts : int
Number of intervals into which each bin will be subdivided.
Returns
-------
... | Subdivide an array of bins by splitting each bin into ``npts``
subintervals.
Parameters
----------
edges : `~numpy.ndarray`
Bin edge array.
npts : int
Number of intervals into which each bin will be subdivided.
Returns
-------
edges : `~numpy.ndarray`
Subdivide... | entailment |
def val_to_bin(edges, x):
"""Convert axis coordinate to bin index."""
ibin = np.digitize(np.array(x, ndmin=1), edges) - 1
return ibin | Convert axis coordinate to bin index. | entailment |
def val_to_edge(edges, x):
"""Convert axis coordinate to bin index."""
edges = np.array(edges)
w = edges[1:] - edges[:-1]
w = np.insert(w, 0, w[0])
ibin = np.digitize(np.array(x, ndmin=1), edges - 0.5 * w) - 1
ibin[ibin < 0] = 0
return ibin | Convert axis coordinate to bin index. | entailment |
def val_to_bin_bounded(edges, x):
"""Convert axis coordinate to bin index."""
nbins = len(edges) - 1
ibin = val_to_bin(edges, x)
ibin[ibin < 0] = 0
ibin[ibin > nbins - 1] = nbins - 1
return ibin | Convert axis coordinate to bin index. | entailment |
def extend_array(edges, binsz, lo, hi):
"""Extend an array to encompass lo and hi values."""
numlo = int(np.ceil((edges[0] - lo) / binsz))
numhi = int(np.ceil((hi - edges[-1]) / binsz))
edges = copy.deepcopy(edges)
if numlo > 0:
edges_lo = np.linspace(edges[0] - numlo * binsz, edges[0], nu... | Extend an array to encompass lo and hi values. | entailment |
def fits_recarray_to_dict(table):
"""Convert a FITS recarray to a python dictionary."""
cols = {}
for icol, col in enumerate(table.columns.names):
col_data = table.data[col]
if type(col_data[0]) == np.float32:
cols[col] = np.array(col_data, dtype=float)
elif type(col_da... | Convert a FITS recarray to a python dictionary. | entailment |
def prettify_xml(elem):
"""Return a pretty-printed XML string for the Element.
"""
from xml.dom import minidom
import xml.etree.cElementTree as et
rough_string = et.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ") | Return a pretty-printed XML string for the Element. | entailment |
def merge_dict(d0, d1, add_new_keys=False, append_arrays=False):
"""Recursively merge the contents of python dictionary d0 with
the contents of another python dictionary, d1.
Parameters
----------
d0 : dict
The input dictionary.
d1 : dict
Dictionary to be merged with the input di... | Recursively merge the contents of python dictionary d0 with
the contents of another python dictionary, d1.
Parameters
----------
d0 : dict
The input dictionary.
d1 : dict
Dictionary to be merged with the input dictionary.
add_new_keys : str
Do not skip keys that only exis... | entailment |
def tolist(x):
""" convenience function that takes in a
nested structure of lists and dictionaries
and converts everything to its base objects.
This is useful for dupming a file to yaml.
(a) numpy arrays into python lists
>>> type(tolist(np.asarray(123))) == int
... | convenience function that takes in a
nested structure of lists and dictionaries
and converts everything to its base objects.
This is useful for dupming a file to yaml.
(a) numpy arrays into python lists
>>> type(tolist(np.asarray(123))) == int
True
>... | entailment |
def convolve2d_disk(fn, r, sig, nstep=200):
"""Evaluate the convolution f'(r) = f(r) * g(r) where f(r) is
azimuthally symmetric function in two dimensions and g is a
step function given by:
g(r) = H(1-r/s)
Parameters
----------
fn : function
Input function that takes a single radial... | Evaluate the convolution f'(r) = f(r) * g(r) where f(r) is
azimuthally symmetric function in two dimensions and g is a
step function given by:
g(r) = H(1-r/s)
Parameters
----------
fn : function
Input function that takes a single radial coordinate parameter.
r : `~numpy.ndarray`
... | entailment |
def convolve2d_gauss(fn, r, sig, nstep=200):
"""Evaluate the convolution f'(r) = f(r) * g(r) where f(r) is
azimuthally symmetric function in two dimensions and g is a
2D gaussian with standard deviation s given by:
g(r) = 1/(2*pi*s^2) Exp[-r^2/(2*s^2)]
Parameters
----------
fn : function
... | Evaluate the convolution f'(r) = f(r) * g(r) where f(r) is
azimuthally symmetric function in two dimensions and g is a
2D gaussian with standard deviation s given by:
g(r) = 1/(2*pi*s^2) Exp[-r^2/(2*s^2)]
Parameters
----------
fn : function
Input function that takes a single radial coor... | entailment |
def make_pixel_distance(shape, xpix=None, ypix=None):
"""Fill a 2D array with dimensions `shape` with the distance of each
pixel from a reference direction (xpix,ypix) in pixel coordinates.
Pixel coordinates are defined such that (0,0) is located at the
center of the corner pixel.
"""
if np.iss... | Fill a 2D array with dimensions `shape` with the distance of each
pixel from a reference direction (xpix,ypix) in pixel coordinates.
Pixel coordinates are defined such that (0,0) is located at the
center of the corner pixel. | entailment |
def make_gaussian_kernel(sigma, npix=501, cdelt=0.01, xpix=None, ypix=None):
"""Make kernel for a 2D gaussian.
Parameters
----------
sigma : float
Standard deviation in degrees.
"""
sigma /= cdelt
def fn(t, s): return 1. / (2 * np.pi * s ** 2) * np.exp(
-t ** 2 / (s ** 2 * ... | Make kernel for a 2D gaussian.
Parameters
----------
sigma : float
Standard deviation in degrees. | entailment |
def make_disk_kernel(radius, npix=501, cdelt=0.01, xpix=None, ypix=None):
"""Make kernel for a 2D disk.
Parameters
----------
radius : float
Disk radius in deg.
"""
radius /= cdelt
def fn(t, s): return 0.5 * (np.sign(s - t) + 1.0)
dxy = make_pixel_distance(npix, xpix, ypix)
... | Make kernel for a 2D disk.
Parameters
----------
radius : float
Disk radius in deg. | entailment |
def make_cdisk_kernel(psf, sigma, npix, cdelt, xpix, ypix, psf_scale_fn=None,
normalize=False):
"""Make a kernel for a PSF-convolved 2D disk.
Parameters
----------
psf : `~fermipy.irfs.PSFModel`
sigma : float
68% containment radius in degrees.
"""
sigma /= 0.8... | Make a kernel for a PSF-convolved 2D disk.
Parameters
----------
psf : `~fermipy.irfs.PSFModel`
sigma : float
68% containment radius in degrees. | entailment |
def make_radial_kernel(psf, fn, sigma, npix, cdelt, xpix, ypix, psf_scale_fn=None,
normalize=False, klims=None, sparse=False):
"""Make a kernel for a general radially symmetric 2D function.
Parameters
----------
psf : `~fermipy.irfs.PSFModel`
fn : callable
Function ... | Make a kernel for a general radially symmetric 2D function.
Parameters
----------
psf : `~fermipy.irfs.PSFModel`
fn : callable
Function that evaluates the kernel at a radial coordinate r.
sigma : float
68% containment radius in degrees. | entailment |
def make_psf_kernel(psf, npix, cdelt, xpix, ypix, psf_scale_fn=None, normalize=False):
"""
Generate a kernel for a point-source.
Parameters
----------
psf : `~fermipy.irfs.PSFModel`
npix : int
Number of pixels in X and Y dimensions.
cdelt : float
Pixel size in degrees.
... | Generate a kernel for a point-source.
Parameters
----------
psf : `~fermipy.irfs.PSFModel`
npix : int
Number of pixels in X and Y dimensions.
cdelt : float
Pixel size in degrees. | entailment |
def overlap_slices(large_array_shape, small_array_shape, position):
"""
Modified version of `~astropy.nddata.utils.overlap_slices`.
Get slices for the overlapping part of a small and a large array.
Given a certain position of the center of the small array, with
respect to the large array, tuples o... | Modified version of `~astropy.nddata.utils.overlap_slices`.
Get slices for the overlapping part of a small and a large array.
Given a certain position of the center of the small array, with
respect to the large array, tuples of slices are returned which can be
used to extract, add or subtract the smal... | entailment |
def make_library(**kwargs):
"""Build and return a ModelManager object and fill the associated model library
"""
library_yaml = kwargs.pop('library', 'models/library.yaml')
comp_yaml = kwargs.pop('comp', 'config/binning.yaml')
basedir = kwargs.pop('basedir', os.path.abspath('.'))
model_man = kwa... | Build and return a ModelManager object and fill the associated model library | entailment |
def edisp_disable_list(self):
""" Return the list of source for which energy dispersion should be turned off """
l = []
for model_comp in self.model_components.values():
if model_comp.edisp_disable:
l += [model_comp.info.source_name]
return l | Return the list of source for which energy dispersion should be turned off | entailment |
def make_srcmap_manifest(self, components, name_factory):
""" Build a yaml file that specfies how to make the srcmap files for a particular model
Parameters
----------
components : list
The binning components used in this analysis
name_factory : `NameFactory`
... | Build a yaml file that specfies how to make the srcmap files for a particular model
Parameters
----------
components : list
The binning components used in this analysis
name_factory : `NameFactory`
Object that handles naming conventions
Returns a dictio... | entailment |
def make_model_rois(self, components, name_factory):
""" Make the fermipy roi_model objects for each of a set of binning components """
ret_dict = {}
# Figure out which sources need to be split by components
master_roi_source_info = {}
sub_comp_sources = {}
for comp_name... | Make the fermipy roi_model objects for each of a set of binning components | entailment |
def read_model_yaml(self, modelkey):
""" Read the yaml file for the diffuse components
"""
model_yaml = self._name_factory.model_yaml(modelkey=modelkey,
fullpath=True)
model = yaml.safe_load(open(model_yaml))
return model | Read the yaml file for the diffuse components | entailment |
def make_library(self, diffuse_yaml, catalog_yaml, binning_yaml):
""" Build up the library of all the components
Parameters
----------
diffuse_yaml : str
Name of the yaml file with the library of diffuse component definitions
catalog_yaml : str
Name of t... | Build up the library of all the components
Parameters
----------
diffuse_yaml : str
Name of the yaml file with the library of diffuse component definitions
catalog_yaml : str
Name of the yaml file width the library of catalog split definitions
binning_ya... | entailment |
def make_model_info(self, modelkey):
""" Build a dictionary with the information for a particular model.
Parameters
----------
modelkey : str
Key used to identify this particular model
Return `ModelInfo`
"""
model = self.read_model_yaml(modelkey)
... | Build a dictionary with the information for a particular model.
Parameters
----------
modelkey : str
Key used to identify this particular model
Return `ModelInfo` | entailment |
def make_srcmap_manifest(self, modelkey, components, data):
"""Build a yaml file that specfies how to make the srcmap files for a particular model
Parameters
----------
modelkey : str
Key used to identify this particular model
components : list
The binni... | Build a yaml file that specfies how to make the srcmap files for a particular model
Parameters
----------
modelkey : str
Key used to identify this particular model
components : list
The binning components used in this analysis
data : str
Path... | entailment |
def make_fermipy_config_yaml(self, modelkey, components, data, **kwargs):
"""Build a fermipy top-level yaml configuration file
Parameters
----------
modelkey : str
Key used to identify this particular model
components : list
The binning components used i... | Build a fermipy top-level yaml configuration file
Parameters
----------
modelkey : str
Key used to identify this particular model
components : list
The binning components used in this analysis
data : str
Path to file containing dataset defini... | entailment |
def get_sub_comp_info(source_info, comp):
"""Build and return information about a sub-component for a particular selection
"""
sub_comps = source_info.get('components', None)
if sub_comps is None:
return source_info.copy()
moving = source_info.get('moving', False)
... | Build and return information about a sub-component for a particular selection | entailment |
def replace_aliases(cut_dict, aliases):
"""Substitute aliases in a cut dictionary."""
for k, v in cut_dict.items():
for k0, v0 in aliases.items():
cut_dict[k] = cut_dict[k].replace(k0, '(%s)' % v0) | Substitute aliases in a cut dictionary. | entailment |
def get_files(files, extnames=['.root']):
"""Extract a list of file paths from a list containing both paths
and file lists with one path per line."""
files_out = []
for f in files:
mime = mimetypes.guess_type(f)
if os.path.splitext(f)[1] in extnames:
files_out += [f]
... | Extract a list of file paths from a list containing both paths
and file lists with one path per line. | entailment |
def get_cuts_from_xml(xmlfile):
"""Extract event selection strings from the XML file."""
root = ElementTree.ElementTree(file=xmlfile).getroot()
event_maps = root.findall('EventMap')
alias_maps = root.findall('AliasDict')[0]
event_classes = {}
event_types = {}
event_aliases = {}
for m ... | Extract event selection strings from the XML file. | entailment |
def set_event_list(tree, selection=None, fraction=None, start_fraction=None):
"""
Set the event list for a tree or chain.
Parameters
----------
tree : `ROOT.TTree`
Input tree/chain.
selection : str
Cut string defining the event list.
fraction : float
Fraction of ... | Set the event list for a tree or chain.
Parameters
----------
tree : `ROOT.TTree`
Input tree/chain.
selection : str
Cut string defining the event list.
fraction : float
Fraction of the total file to include in the event list
starting from the *end* of the file. | entailment |
def find_sources(self, prefix='', **kwargs):
"""An iterative source-finding algorithm that uses likelihood
ratio (TS) maps of the region of interest to find new sources.
After each iteration a new TS map is generated incorporating
sources found in the previous iteration. The method stop... | An iterative source-finding algorithm that uses likelihood
ratio (TS) maps of the region of interest to find new sources.
After each iteration a new TS map is generated incorporating
sources found in the previous iteration. The method stops
when the number of iterations exceeds ``max_it... | entailment |
def localize(self, name, **kwargs):
"""Find the best-fit position of a source. Localization is
performed in two steps. First a TS map is computed centered
on the source with half-width set by ``dtheta_max``. A fit is
then performed to the maximum TS peak in this map. The source
... | Find the best-fit position of a source. Localization is
performed in two steps. First a TS map is computed centered
on the source with half-width set by ``dtheta_max``. A fit is
then performed to the maximum TS peak in this map. The source
position is then further refined by scanning... | entailment |
def _fit_position_tsmap(self, name, **kwargs):
"""Localize a source from its TS map."""
prefix = kwargs.get('prefix', '')
dtheta_max = kwargs.get('dtheta_max', 0.5)
zmin = kwargs.get('zmin', -3.0)
kw = {
'map_size': 2.0 * dtheta_max,
'write_fits': kwarg... | Localize a source from its TS map. | entailment |
def make_nfs_path(path):
"""Make a nfs version of a file path.
This just puts /nfs at the beginning instead of /gpfs"""
if os.path.isabs(path):
fullpath = path
else:
fullpath = os.path.abspath(path)
if len(fullpath) < 6:
return fullpath
if fullpath[0:6] == '/gpfs/':
... | Make a nfs version of a file path.
This just puts /nfs at the beginning instead of /gpfs | entailment |
def make_gpfs_path(path):
"""Make a gpfs version of a file path.
This just puts /gpfs at the beginning instead of /nfs"""
if os.path.isabs(path):
fullpath = os.path.abspath(path)
else:
fullpath = os.path.abspath(path)
if len(fullpath) < 5:
return fullpath
if fullpath[0:5]... | Make a gpfs version of a file path.
This just puts /gpfs at the beginning instead of /nfs | entailment |
def get_lsf_status():
"""Count and print the number of jobs in various LSF states
"""
status_count = {'RUN': 0,
'PEND': 0,
'SUSP': 0,
'USUSP': 0,
'NJOB': 0,
'UNKNWN': 0}
try:
subproc = subprocess... | Count and print the number of jobs in various LSF states | entailment |
def build_bsub_command(command_template, lsf_args):
"""Build and return a lsf batch command template
The structure will be 'bsub -s <key> <value> <command_template>'
where <key> and <value> refer to items in lsf_args
"""
if command_template is None:
return ""
full_command = 'bsub -o... | Build and return a lsf batch command template
The structure will be 'bsub -s <key> <value> <command_template>'
where <key> and <value> refer to items in lsf_args | entailment |
def get_slac_default_args(job_time=1500):
""" Create a batch job interface object.
Parameters
----------
job_time : int
Expected max length of the job, in seconds.
This is used to select the batch queue and set the
job_check_sleep parameter that sets how often
we check ... | Create a batch job interface object.
Parameters
----------
job_time : int
Expected max length of the job, in seconds.
This is used to select the batch queue and set the
job_check_sleep parameter that sets how often
we check for job completion. | entailment |
def dispatch_job_hook(self, link, key, job_config, logfile, stream=sys.stdout):
"""Send a single job to the LSF batch
Parameters
----------
link : `fermipy.jobs.chain.Link`
The link used to invoke the command we are running
key : str
A string that ident... | Send a single job to the LSF batch
Parameters
----------
link : `fermipy.jobs.chain.Link`
The link used to invoke the command we are running
key : str
A string that identifies this particular instance of the job
job_config : dict
A dictionr... | entailment |
def submit_jobs(self, link, job_dict=None, job_archive=None, stream=sys.stdout):
"""Submit all the jobs in job_dict """
if link is None:
return JobStatus.no_job
if job_dict is None:
job_keys = link.jobs.keys()
else:
job_keys = sorted(job_dict.keys())
... | Submit all the jobs in job_dict | entailment |
def create_sc_table(scfile, colnames=None):
"""Load an FT2 file from a file or list of files."""
if utils.is_fits_file(scfile) and colnames is None:
return create_table_from_fits(scfile, 'SC_DATA')
if utils.is_fits_file(scfile):
files = [scfile]
else:
files = [line.strip() for ... | Load an FT2 file from a file or list of files. | entailment |
def create_table_from_fits(fitsfile, hduname, colnames=None):
"""Memory efficient function for loading a table from a FITS
file."""
if colnames is None:
return Table.read(fitsfile, hduname)
cols = []
with fits.open(fitsfile, memmap=True) as h:
for k in colnames:
data = ... | Memory efficient function for loading a table from a FITS
file. | entailment |
def get_spectral_index(src, egy):
"""Compute the local spectral index of a source."""
delta = 1E-5
f0 = src.spectrum()(pyLike.dArg(egy * (1 - delta)))
f1 = src.spectrum()(pyLike.dArg(egy * (1 + delta)))
if f0 > 0 and f1 > 0:
gamma = np.log10(f0 / f1) / np.log10((1 - delta) / (1 + delta))
... | Compute the local spectral index of a source. | entailment |
def create(cls, infile, config=None, params=None, mask=None):
"""Create a new instance of GTAnalysis from an analysis output file
generated with `~fermipy.GTAnalysis.write_roi`. By default
the new instance will inherit the configuration of the saved
analysis instance. The configuration... | Create a new instance of GTAnalysis from an analysis output file
generated with `~fermipy.GTAnalysis.write_roi`. By default
the new instance will inherit the configuration of the saved
analysis instance. The configuration may be overriden by
passing a configuration file path with the `... | entailment |
def clone(self, config, **kwargs):
"""Make a clone of this analysis instance."""
gta = GTAnalysis(config, **kwargs)
gta._roi = copy.deepcopy(self.roi)
return gta | Make a clone of this analysis instance. | entailment |
def set_random_seed(self, seed):
"""Set the seed for the random number generator"""
self.config['mc']['seed'] = seed
np.random.seed(seed) | Set the seed for the random number generator | entailment |
def reload_source(self, name, init_source=True):
"""Delete and reload a source in the model. This will update
the spatial model of this source to the one defined in the XML
model."""
for c in self.components:
c.reload_source(name)
if init_source:
self._... | Delete and reload a source in the model. This will update
the spatial model of this source to the one defined in the XML
model. | entailment |
def set_source_morphology(self, name, **kwargs):
"""Set the spatial model of a source.
Parameters
----------
name : str
Source name.
spatial_model : str
Spatial model name (PointSource, RadialGaussian, etc.).
spatial_pars : dict
Diction... | Set the spatial model of a source.
Parameters
----------
name : str
Source name.
spatial_model : str
Spatial model name (PointSource, RadialGaussian, etc.).
spatial_pars : dict
Dictionary of spatial parameters (optional).
use_cache : b... | entailment |
def set_source_spectrum(self, name, spectrum_type='PowerLaw',
spectrum_pars=None, update_source=True):
"""Set the spectral model of a source. This function can be
used to change the spectral type of a source or modify its
spectral parameters. If called with
... | Set the spectral model of a source. This function can be
used to change the spectral type of a source or modify its
spectral parameters. If called with
spectrum_type='FileFunction' and spectrum_pars=None, the
source spectrum will be replaced with a FileFunction with the
same di... | entailment |
def set_source_dnde(self, name, dnde, update_source=True):
"""Set the differential flux distribution of a source with the
FileFunction spectral type.
Parameters
----------
name : str
Source name.
dnde : `~numpy.ndarray`
Array of differential flux v... | Set the differential flux distribution of a source with the
FileFunction spectral type.
Parameters
----------
name : str
Source name.
dnde : `~numpy.ndarray`
Array of differential flux values (cm^{-2} s^{-1} MeV^{-1}). | entailment |
def get_source_dnde(self, name):
"""Return differential flux distribution of a source. For
sources with FileFunction spectral type this returns the
internal differential flux array.
Returns
-------
loge : `~numpy.ndarray`
Array of energies at which the differ... | Return differential flux distribution of a source. For
sources with FileFunction spectral type this returns the
internal differential flux array.
Returns
-------
loge : `~numpy.ndarray`
Array of energies at which the differential flux is
evaluated (log10(E... | entailment |
def _create_filefunction(self, name, spectrum_pars):
"""Replace the spectrum of an existing source with a
FileFunction."""
spectrum_pars = {} if spectrum_pars is None else spectrum_pars
if 'loge' in spectrum_pars:
loge = spectrum_pars.get('loge')
else:
e... | Replace the spectrum of an existing source with a
FileFunction. | entailment |
def stage_output(self):
"""Copy data products to final output directory."""
if self.workdir == self.outdir:
return
elif not os.path.isdir(self.workdir):
self.logger.error('Working directory does not exist.')
return
regex = self.config['fileio']['outd... | Copy data products to final output directory. | entailment |
def stage_input(self):
"""Copy input files to working directory."""
if self.workdir == self.outdir:
return
elif not os.path.isdir(self.workdir):
self.logger.error('Working directory does not exist.')
return
self.logger.info('Staging files to %s', sel... | Copy input files to working directory. | entailment |
def setup(self, init_sources=True, overwrite=False, **kwargs):
"""Run pre-processing for each analysis component and
construct a joint likelihood object. This function performs
the following tasks: data selection (gtselect, gtmktime),
data binning (gtbin), and model generation (gtexpcub... | Run pre-processing for each analysis component and
construct a joint likelihood object. This function performs
the following tasks: data selection (gtselect, gtmktime),
data binning (gtbin), and model generation (gtexpcube2,gtsrcmaps).
Parameters
----------
init_source... | entailment |
def _create_likelihood(self, srcmdl=None):
"""Instantiate the likelihood object for each component and
create a SummedLikelihood."""
self._like = SummedLikelihood()
for c in self.components:
c._create_binned_analysis(srcmdl)
self._like.addComponent(c.like)
... | Instantiate the likelihood object for each component and
create a SummedLikelihood. | entailment |
def generate_model(self, model_name=None):
"""Generate model maps for all components. model_name should
be a unique identifier for the model. If model_name is None
then the model maps will be generated using the current
parameters of the ROI."""
for i, c in enumerate(self._com... | Generate model maps for all components. model_name should
be a unique identifier for the model. If model_name is None
then the model maps will be generated using the current
parameters of the ROI. | entailment |
def set_energy_range(self, logemin, logemax):
"""Set the energy bounds of the analysis. This restricts the
evaluation of the likelihood to the data that falls in this
range. Input values will be rounded to the closest bin edge
value. If either argument is None then the lower or upper
... | Set the energy bounds of the analysis. This restricts the
evaluation of the likelihood to the data that falls in this
range. Input values will be rounded to the closest bin edge
value. If either argument is None then the lower or upper
bound of the analysis instance will be used.
... | entailment |
def model_counts_map(self, name=None, exclude=None, use_mask=False):
"""Return the model counts map for a single source, a list of
sources, or for the sum of all sources in the ROI. The
exclude parameter can be used to exclude one or more
components when generating the model map.
... | Return the model counts map for a single source, a list of
sources, or for the sum of all sources in the ROI. The
exclude parameter can be used to exclude one or more
components when generating the model map.
Parameters
----------
name : str or list of str
P... | entailment |
def model_counts_spectrum(self, name, logemin=None, logemax=None,
summed=False, weighted=False):
"""Return the predicted number of model counts versus energy
for a given source and energy range. If summed=True return
the counts spectrum summed over all components o... | Return the predicted number of model counts versus energy
for a given source and energy range. If summed=True return
the counts spectrum summed over all components otherwise
return a list of model spectra. If weighted=True return
the weighted version of the counts spectrum | entailment |
def get_sources(self, cuts=None, distance=None, skydir=None,
minmax_ts=None, minmax_npred=None, exclude=None,
square=False):
"""Retrieve list of sources in the ROI satisfying the given
selections.
Returns
-------
srcs : list
A ... | Retrieve list of sources in the ROI satisfying the given
selections.
Returns
-------
srcs : list
A list of `~fermipy.roi_model.Model` objects. | entailment |
def add_source(self, name, src_dict, free=None, init_source=True,
save_source_maps=True, use_pylike=True,
use_single_psf=False, **kwargs):
"""Add a source to the ROI model. This function may be called
either before or after `~fermipy.gtanalysis.GTAnalysis.setup`.
... | Add a source to the ROI model. This function may be called
either before or after `~fermipy.gtanalysis.GTAnalysis.setup`.
Parameters
----------
name : str
Source name.
src_dict : dict or `~fermipy.roi_model.Source` object
Dictionary or source object def... | entailment |
def add_sources_from_roi(self, names, roi, free=False, **kwargs):
"""Add multiple sources to the current ROI model copied from another ROI model.
Parameters
----------
names : list
List of str source names to add.
roi : `~fermipy.roi_model.ROIModel` object
... | Add multiple sources to the current ROI model copied from another ROI model.
Parameters
----------
names : list
List of str source names to add.
roi : `~fermipy.roi_model.ROIModel` object
The roi model from which to add sources.
free : bool
... | entailment |
def delete_source(self, name, save_template=True, delete_source_map=False,
build_fixed_wts=True, **kwargs):
"""Delete a source from the ROI model.
Parameters
----------
name : str
Source name.
save_template : bool
Keep the SpatialMa... | Delete a source from the ROI model.
Parameters
----------
name : str
Source name.
save_template : bool
Keep the SpatialMap FITS template associated with this
source.
delete_source_map : bool
Delete the source map associated with ... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.