code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
o = '' spatial_type = src['SpatialModel'].lower() o += spatial_type if spatial_type == 'gaussian': o += '_s%04.2f' % src['SpatialWidth'] if src['SpectrumType'] == 'PowerLaw': o += '_powerlaw_%04.2f' % float(src.spectral_pars['Index']['value']) else: o += '_%s' % (s...
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.
4.809521
4.23781
1.134907
err = np.sqrt(np.diag(cov)) errinv = np.ones_like(err) * np.nan m = np.isfinite(err) & (err != 0) errinv[m] = 1. / err[m] corr = np.array(cov) return corr * np.outer(errinv, errinv)
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.
3.18985
3.601751
0.885639
cth = np.cos(theta) sth = np.sin(theta) covxx = cth**2 * sigma_maj**2 + sth**2 * sigma_min**2 covyy = sth**2 * sigma_maj**2 + cth**2 * sigma_min**2 covxy = cth * sth * sigma_maj**2 - cth * sth * sigma_min**2 return np.array([[covxx, covxy], [covxy, covyy]])
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 axis of error ellipse. sigma_min : float Std....
1.718092
1.856347
0.925523
alpha = 1.0 - cl return 0.5 * np.power(np.sqrt(2.) * special.erfinv(1 - 2 * alpha), 2.)
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 of the likelihood function.
5.400274
6.598449
0.818416
if x0 == xb: return np.nan for i in range(10): if np.sign(fn(xb) + delta) != np.sign(fn(x0) + delta): break if bounds is not None and (xb < bounds[0] or xb > bounds[1]): break if xb < x0: xb *= 0.5 else: xb *= 2.0 ...
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 the lower or upper bound depending on the relative value of xb. ...
2.216246
2.301679
0.962882
x = xy[0] y = xy[1] cth = np.cos(theta) sth = np.sin(theta) a = (cth ** 2) / (2 * sx ** 2) + (sth ** 2) / (2 * sy ** 2) b = -(np.sin(2 * theta)) / (4 * sx ** 2) + (np.sin(2 * theta)) / ( 4 * sy ** 2) c = (sth ** 2) / (2 * sx ** 2) + (cth ** 2) / (2 * sy ** 2) vals = amplit...
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 = [[1/\sigma_x^2, 0 ], [0 , ...
1.797893
1.818805
0.988503
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
def get_region_mask(z, delta, xy=None)
Get mask of connected region within delta of max(z).
3.320457
3.000436
1.106658
offset = make_pixel_distance(z.shape, iy, ix) x, y = np.meshgrid(np.arange(z.shape[0]), np.arange(z.shape[1]), indexing='ij') m = (offset <= dpix) if np.sum(m) < 9: m = (offset <= dpix + 0.5) if zmin is not None: m |= get_region_mask(z, np.abs(zmin), (ix...
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 coordinate (iz,iy) OR that have a value relative to the peak ...
2.380927
2.418287
0.984551
if npts < 2: return edges x = (edges[:-1, None] + (edges[1:, None] - edges[:-1, None]) * np.linspace(0.0, 1.0, npts + 1)[None, :]) return np.unique(np.ravel(x))
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 ------- edges : `~numpy.ndarray` Subdivide...
2.957887
3.324103
0.88983
ibin = np.digitize(np.array(x, ndmin=1), edges) - 1 return ibin
def val_to_bin(edges, x)
Convert axis coordinate to bin index.
4.254906
3.926342
1.083682
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
def val_to_edge(edges, x)
Convert axis coordinate to bin index.
3.06163
2.48573
1.231682
nbins = len(edges) - 1 ibin = val_to_bin(edges, x) ibin[ibin < 0] = 0 ibin[ibin > nbins - 1] = nbins - 1 return ibin
def val_to_bin_bounded(edges, x)
Convert axis coordinate to bin index.
2.245377
2.146888
1.045875
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], numlo + 1) edges = np.concatenate((edges_lo[:-1], edges)) if numhi > 0: e...
def extend_array(edges, binsz, lo, hi)
Extend an array to encompass lo and hi values.
1.756665
1.710618
1.026918
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_data[0]) == np.float64: cols[col] = np.array(col_data, dtype=float) e...
def fits_recarray_to_dict(table)
Convert a FITS recarray to a python dictionary.
1.672449
1.649201
1.014097
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=" ")
def prettify_xml(elem)
Return a pretty-printed XML string for the Element.
1.771091
1.56248
1.133513
if d1 is None: return d0 elif d0 is None: return d1 elif d0 is None and d1 is None: return {} od = {} for k, v in d0.items(): t0 = None t1 = None if k in d0: t0 = type(d0[k]) if k in d1: t1 = type(d1[k]) ...
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 dictionary. add_new_keys : str Do not skip keys that only exis...
1.891718
1.915677
0.987493
if isinstance(x, list): return map(tolist, x) elif isinstance(x, dict): return dict((tolist(k), tolist(v)) for k, v in x.items()) elif isinstance(x, np.ndarray) or isinstance(x, np.number): # note, call tolist again to convert strings of numbers to numbers return tolist(...
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 True >...
2.505594
2.432299
1.030134
r = np.array(r, ndmin=1) sig = np.array(sig, ndmin=1) rmin = r - sig rmax = r + sig rmin[rmin < 0] = 0 delta = (rmax - rmin) / nstep redge = rmin[..., np.newaxis] + \ delta[..., np.newaxis] * np.linspace(0, nstep, nstep + 1) rp = 0.5 * (redge[..., 1:] + redge[..., :-1]) ...
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 coordinate parameter. r : `~numpy.ndarray` ...
3.424618
3.508934
0.975971
r = np.array(r, ndmin=1) sig = np.array(sig, ndmin=1) rmin = r - 10 * sig rmax = r + 10 * sig rmin[rmin < 0] = 0 delta = (rmax - rmin) / nstep redge = (rmin[..., np.newaxis] + delta[..., np.newaxis] * np.linspace(0, nstep, nstep + 1)) rp = 0.5 * (redge[....
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 Input function that takes a single radial coor...
3.370394
3.480503
0.968364
if np.isscalar(shape): shape = [shape, shape] if xpix is None: xpix = (shape[1] - 1.0) / 2. if ypix is None: ypix = (shape[0] - 1.0) / 2. dx = np.linspace(0, shape[1] - 1, shape[1]) - xpix dy = np.linspace(0, shape[0] - 1, shape[0]) - ypix dxy = np.zeros(shape) ...
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.
1.73662
1.798236
0.965736
sigma /= cdelt def fn(t, s): return 1. / (2 * np.pi * s ** 2) * np.exp( -t ** 2 / (s ** 2 * 2.0)) dxy = make_pixel_distance(npix, xpix, ypix) k = fn(dxy, sigma) k /= (np.sum(k) * np.radians(cdelt) ** 2) return k
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.
4.180968
4.584194
0.91204
radius /= cdelt def fn(t, s): return 0.5 * (np.sign(s - t) + 1.0) dxy = make_pixel_distance(npix, xpix, ypix) k = fn(dxy, radius) k /= (np.sum(k) * np.radians(cdelt) ** 2) return k
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.
5.004377
5.860939
0.853852
sigma /= 0.8246211251235321 dtheta = psf.dtheta egy = psf.energies x = make_pixel_distance(npix, xpix, ypix) x *= cdelt k = np.zeros((len(egy), npix, npix)) for i in range(len(egy)): def fn(t): return psf.eval(i, t, scale_fn=psf_scale_fn) psfc = convolve2d_disk(fn, d...
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.
4.657747
4.826658
0.965005
if klims is None: egy = psf.energies else: egy = psf.energies[klims[0]:klims[1] + 1] ang_dist = make_pixel_distance(npix, xpix, ypix) * cdelt max_ang_dist = np.max(ang_dist) + cdelt #dtheta = np.linspace(0.0, (np.max(ang_dist) * 1.05)**0.5, 200)**2.0 # z = create_kernel_fun...
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 that evaluates the kernel at a radial coordinate r. sigma : float 68% containment radius in degrees.
2.819422
2.89229
0.974806
egy = psf.energies x = make_pixel_distance(npix, xpix, ypix) x *= cdelt k = np.zeros((len(egy), npix, npix)) for i in range(len(egy)): k[i] = psf.eval(i, x, scale_fn=psf_scale_fn) if normalize: k /= (np.sum(k, axis=0)[np.newaxis, ...] * np.radians(cdelt) ** 2) return...
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.
3.386749
3.681175
0.920019
# Get edge coordinates edges_min = [int(pos - small_shape // 2) for (pos, small_shape) in zip(position, small_array_shape)] edges_max = [int(pos + (small_shape - small_shape // 2)) for (pos, small_shape) in zip(position, small_array_shape)] # Set ...
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 of slices are returned which can be used to extract, add or subtract the smal...
1.904689
1.958423
0.972563
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 = kwargs.get('ModelManager', ModelManager(basedir=basedir)) model_comp_dict = model_man.make_library(library_yaml, ...
def make_library(**kwargs)
Build and return a ModelManager object and fill the associated model library
4.601835
4.151198
1.108556
l = [] for model_comp in self.model_components.values(): if model_comp.edisp_disable: l += [model_comp.info.source_name] return l
def edisp_disable_list(self)
Return the list of source for which energy dispersion should be turned off
5.416791
4.847607
1.117416
ret_dict = {} for comp in components: compkey = comp.make_key('{ebin_name}_{evtype_name}') zcut = "zmax%i" % comp.zmax name_keys = dict(modelkey=self.model_name, zcut=zcut, ebin=comp.ebin_name, ...
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` Object that handles naming conventions Returns a dictio...
3.908972
3.696867
1.057374
ret_dict = {} # Figure out which sources need to be split by components master_roi_source_info = {} sub_comp_sources = {} for comp_name, model_comp in self.model_components.items(): comp_info = model_comp.info if comp_info.components is None: ...
def make_model_rois(self, components, name_factory)
Make the fermipy roi_model objects for each of a set of binning components
3.225348
3.136672
1.028271
model_yaml = self._name_factory.model_yaml(modelkey=modelkey, fullpath=True) model = yaml.safe_load(open(model_yaml)) return model
def read_model_yaml(self, modelkey)
Read the yaml file for the diffuse components
5.054893
4.918532
1.027724
ret_dict = {} #catalog_dict = yaml.safe_load(open(catalog_yaml)) components_dict = Component.build_from_yamlfile(binning_yaml) diffuse_ret_dict = make_diffuse_comp_info_dict(GalpropMapManager=self._gmm, DiffuseModelManager=s...
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 the yaml file width the library of catalog split definitions binning_ya...
4.197453
4.33255
0.968818
model = self.read_model_yaml(modelkey) sources = model['sources'] components = OrderedDict() spec_model_yaml = self._name_factory.fullpath(localpath=model['spectral_models']) self._spec_lib.update(yaml.safe_load(open(spec_model_yaml))) for source, source_info in ...
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`
2.680213
2.728831
0.982184
try: model_info = self._models[modelkey] except KeyError: model_info = self.make_model_info(modelkey) self._name_factory.update_base_dict(data) outfile = os.path.join('analysis', 'model_%s' % modelkey, 'srcmap_manifest_%s.ya...
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 binning components used in this analysis data : str Path...
3.522955
3.447175
1.021983
sub_comps = source_info.get('components', None) if sub_comps is None: return source_info.copy() moving = source_info.get('moving', False) selection_dependent = source_info.get('selection_dependent', False) if selection_dependent: key = comp.make_k...
def get_sub_comp_info(source_info, comp)
Build and return information about a sub-component for a particular selection
4.623013
4.511195
1.024787
for k, v in cut_dict.items(): for k0, v0 in aliases.items(): cut_dict[k] = cut_dict[k].replace(k0, '(%s)' % v0)
def replace_aliases(cut_dict, aliases)
Substitute aliases in a cut dictionary.
2.595843
2.496626
1.03974
files_out = [] for f in files: mime = mimetypes.guess_type(f) if os.path.splitext(f)[1] in extnames: files_out += [f] elif mime[0] == 'text/plain': files_out += list(np.loadtxt(f, unpack=True, dtype='str')) else: raise Exception('Unrecog...
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.
2.836427
3.070277
0.923834
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 in event_maps: if m.attrib['altName'] == 'EVENT_CLASS': for c in m.f...
def get_cuts_from_xml(xmlfile)
Extract event selection strings from the XML file.
2.337386
2.243411
1.041889
import ROOT elist = rand_str() if selection is None: cuts = '' else: cuts = selection if fraction is None or fraction >= 1.0: n = tree.Draw(">>%s" % elist, cuts, "goff") tree.SetEventList(ROOT.gDirectory.Get(elist)) elif start_fraction is None: nen...
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 the total file to include in the event list starting from the *end* of the file.
2.639175
2.646841
0.997104
timer = Timer.create(start=True) self.logger.info('Starting.') schema = ConfigSchema(self.defaults['sourcefind'], tsmap=self.defaults['tsmap'], tscube=self.defaults['tscube']) schema.add_option('search_skydir', None, ...
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 stops when the number of iterations exceeds ``max_it...
4.431355
3.850648
1.150808
timer = Timer.create(start=True) name = self.roi.get_source_by_name(name).name schema = ConfigSchema(self.defaults['localize'], optimizer=self.defaults['optimizer']) schema.add_option('use_cache', True) schema.add_option('prefix', '') ...
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 position is then further refined by scanning...
4.890171
4.746072
1.030362
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': kwargs.get('write_fits', False), 'write_npy': kwargs.get('write_npy', False), ...
def _fit_position_tsmap(self, name, **kwargs)
Localize a source from its TS map.
3.81603
3.756214
1.015924
if os.path.isabs(path): fullpath = path else: fullpath = os.path.abspath(path) if len(fullpath) < 6: return fullpath if fullpath[0:6] == '/gpfs/': fullpath = fullpath.replace('/gpfs/', '/nfs/') return fullpath
def make_nfs_path(path)
Make a nfs version of a file path. This just puts /nfs at the beginning instead of /gpfs
2.716217
2.310839
1.175425
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] == '/nfs/': fullpath = fullpath.replace('/nfs/', '/gpfs/') return fullpath
def make_gpfs_path(path)
Make a gpfs version of a file path. This just puts /gpfs at the beginning instead of /nfs
2.430146
2.356755
1.031141
status_count = {'RUN': 0, 'PEND': 0, 'SUSP': 0, 'USUSP': 0, 'NJOB': 0, 'UNKNWN': 0} try: subproc = subprocess.Popen(['bjobs'], stdout=subprocess.PIPE, ...
def get_lsf_status()
Count and print the number of jobs in various LSF states
3.075469
2.936309
1.047393
if command_template is None: return "" full_command = 'bsub -o {logfile}' for key, value in lsf_args.items(): full_command += ' -%s' % key if value is not None: full_command += ' %s' % value full_command += ' %s' % command_template return full_command
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
2.413138
2.555508
0.944289
slac_default_args = dict(lsf_args={'W': job_time, 'R': '\"select[rhel60&&!fell]\"'}, max_jobs=500, time_per_cycle=15, jobs_per_cycle=20, max_job_age=90, ...
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 for job completion.
7.818889
9.023581
0.866495
full_sub_dict = job_config.copy() if self._no_batch: full_command = "%s >& %s" % ( link.command_template().format(**full_sub_dict), logfile) else: full_sub_dict['logfile'] = logfile full_command_template = build_bsub_command( ...
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 identifies this particular instance of the job job_config : dict A dictionr...
3.232384
3.403957
0.949596
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()) # copy & reverse the keys b/c we will be popping item off the back of # the list unsubmitted_jo...
def submit_jobs(self, link, job_dict=None, job_archive=None, stream=sys.stdout)
Submit all the jobs in job_dict
2.985765
2.958289
1.009288
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 line in open(scfile, 'r')] tables = [create_table_from_fits(f, 'SC_DATA', colnames) ...
def create_sc_table(scfile, colnames=None)
Load an FT2 file from a file or list of files.
2.643172
2.590257
1.020429
if colnames is None: return Table.read(fitsfile, hduname) cols = [] with fits.open(fitsfile, memmap=True) as h: for k in colnames: data = h[hduname].data.field(k) cols += [Column(name=k, data=data)] return Table(cols)
def create_table_from_fits(fitsfile, hduname, colnames=None)
Memory efficient function for loading a table from a FITS file.
2.309031
2.347261
0.983713
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)) else: gamma = np.nan return gamma
def get_spectral_index(src, egy)
Compute the local spectral index of a source.
4.014561
3.901788
1.028903
infile = os.path.abspath(infile) roi_file, roi_data = utils.load_data(infile) if config is None: config = roi_data['config'] validate = False else: validate = True gta = cls(config, validate=validate) gta.setup(init_sources=...
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 may be overriden by passing a configuration file path with the `...
3.905287
3.87193
1.008615
gta = GTAnalysis(config, **kwargs) gta._roi = copy.deepcopy(self.roi) return gta
def clone(self, config, **kwargs)
Make a clone of this analysis instance.
9.473588
7.238648
1.308751
self.config['mc']['seed'] = seed np.random.seed(seed)
def set_random_seed(self, seed)
Set the seed for the random number generator
6.79608
6.383778
1.064586
for c in self.components: c.reload_source(name) if init_source: self._init_source(name) self.like.model = self.like.components[0].model
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.
4.538498
4.54478
0.998618
name = self.roi.get_source_by_name(name).name src = self.roi[name] spatial_model = kwargs.get('spatial_model', src['SpatialModel']) spatial_pars = kwargs.get('spatial_pars', {}) use_pylike = kwargs.get('use_pylike', True) psf_scale_fn = kwargs.get('psf_scale_fn...
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 Dictionary of spatial parameters (optional). use_cache : b...
3.589439
3.104352
1.15626
name = self.roi.get_source_by_name(name).name src = self.roi[name] spectrum_pars = {} if spectrum_pars is None else spectrum_pars if (self.roi[name]['SpectrumType'] == 'PowerLaw' and spectrum_type == 'LogParabola'): spectrum_pars.setdefault('beta', {...
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 spectrum_type='FileFunction' and spectrum_pars=None, the source spectrum will be replaced with a FileFunction with the same di...
2.964775
2.915719
1.016825
name = self.roi.get_source_by_name(name).name if self.roi[name]['SpectrumType'] != 'FileFunction': msg = 'Wrong spectral type: %s' % self.roi[name]['SpectrumType'] self.logger.error(msg) raise Exception(msg) xy = self.get_source_dnde(name) ...
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 values (cm^{-2} s^{-1} MeV^{-1}).
4.26827
4.055813
1.052383
name = self.roi.get_source_by_name(name).name if self.roi[name]['SpectrumType'] != 'FileFunction': src = self.components[0].like.logLike.getSource(str(name)) spectrum = src.spectrum() file_function = pyLike.FileFunction_cast(spectrum) loge = fil...
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 differential flux is evaluated (log10(E...
5.839879
5.382655
1.084944
spectrum_pars = {} if spectrum_pars is None else spectrum_pars if 'loge' in spectrum_pars: loge = spectrum_pars.get('loge') else: ebinsz = (self.log_energies[-1] - self.log_energies[0]) / self.enumbins loge = utils.extend_array...
def _create_filefunction(self, name, spectrum_pars)
Replace the spectrum of an existing source with a FileFunction.
5.432248
5.228904
1.038889
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']['outdir_regex'] savefits = self.config['fileio']['savefits'] fil...
def stage_output(self)
Copy data products to final output directory.
3.189904
3.111845
1.025085
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', self.workdir) files = [os.path.join(self.outdir, f) ...
def stage_input(self)
Copy input files to working directory.
2.480138
2.388581
1.038331
loglevel = kwargs.get('loglevel', self.loglevel) self.logger.log(loglevel, 'Running setup.') # Make spatial maps for extended sources for s in self.roi.sources: if s.diffuse: continue if not s.extended: continue ...
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 (gtexpcube2,gtsrcmaps). Parameters ---------- init_source...
3.314774
3.258032
1.017416
self._like = SummedLikelihood() for c in self.components: c._create_binned_analysis(srcmdl) self._like.addComponent(c.like) self.like.model = self.like.components[0].model self._fitcache = None self._init_roi_model()
def _create_likelihood(self, srcmdl=None)
Instantiate the likelihood object for each component and create a SummedLikelihood.
7.570062
5.697943
1.328561
for i, c in enumerate(self._components): c.generate_model(model_name=model_name)
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.
4.533455
3.484682
1.300967
if logemin is None: logemin = self.log_energies[0] else: imin = int(utils.val_to_edge(self.log_energies, logemin)[0]) logemin = self.log_energies[imin] if logemax is None: logemax = self.log_energies[-1] else: imax = ...
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 bound of the analysis instance will be used. ...
2.198544
2.173612
1.01147
maps = [c.model_counts_map(name, exclude, use_mask=use_mask) for c in self.components] return skymap.coadd_maps(self.geom, maps)
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. Parameters ---------- name : str or list of str P...
5.258041
7.918869
0.663989
if logemin is None: logemin = self.log_energies[0] if logemax is None: logemax = self.log_energies[-1] if summed: cs = np.zeros(self.enumbins) imin = utils.val_to_bin_bounded(self.log_energies, ...
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 otherwise return a list of model spectra. If weighted=True return the weighted version of the counts spectrum
2.331965
2.287924
1.01925
coordsys = self.config['binning']['coordsys'] return self.roi.get_sources(skydir, distance, cuts, minmax_ts, minmax_npred, exclude, square, coordsys=coordsys)
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 list of `~fermipy.roi_model.Model` objects.
4.000685
5.04704
0.792679
if self.roi.has_source(name): msg = 'Source %s already exists.' % name self.logger.error(msg) raise Exception(msg) loglevel = kwargs.pop('loglevel', self.loglevel) self.logger.log(loglevel, 'Adding source ' + name) src = self.roi.create_so...
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`. Parameters ---------- name : str Source name. src_dict : dict or `~fermipy.roi_model.Source` object Dictionary or source object def...
3.559771
3.381714
1.052653
for name in names: self.add_source(name, roi[name].data, free=free, **kwargs)
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 The roi model from which to add sources. free : bool ...
3.460089
4.254112
0.813352
if not self.roi.has_source(name): self.logger.error('No source with name: %s', name) return loglevel = kwargs.pop('loglevel', self.loglevel) self.logger.log(loglevel, 'Deleting source %s', name) # STs require a source to be freed before deletion ...
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 SpatialMap FITS template associated with this source. delete_source_map : bool Delete the source map associated with ...
3.391676
3.23907
1.047114
srcs = self.roi.get_sources(skydir=skydir, distance=distance, cuts=cuts, minmax_ts=minmax_ts, minmax_npred=minmax_npred, exclude=exclude, square=square, coordsys=self.config[ ...
def delete_sources(self, cuts=None, distance=None, skydir=None, minmax_ts=None, minmax_npred=None, exclude=None, square=False, names=None)
Delete sources in the ROI model satisfying the given selection criteria. Parameters ---------- cuts : dict Dictionary of [min,max] selections on source properties. distance : float Cut on angular distance from ``skydir``. If None then no sel...
4.550054
4.959594
0.917425
if names is None: return names = [names] if not isinstance(names, list) else names names = [self.roi.get_source_by_name(t).name for t in names] srcs = [s for s in self.roi.sources if s.name in names] for s in srcs: self.free_source(s.name, free=...
def free_sources_by_name(self, names, free=True, pars=None, **kwargs)
Free all sources with names matching ``names``. Parameters ---------- names : list List of source names. free : bool Choose whether to free (free=True) or fix (free=False) source parameters. pars : list Set a list of parameters t...
2.616518
2.794681
0.936249
srcs = self.roi.get_sources(skydir=skydir, distance=distance, cuts=cuts, minmax_ts=minmax_ts, minmax_npred=minmax_npred, exclude=exclude, square=square, coord...
def free_sources(self, free=True, pars=None, cuts=None, distance=None, skydir=None, minmax_ts=None, minmax_npred=None, exclude=None, square=False, **kwargs)
Free or fix sources in the ROI model satisfying the given selection. When multiple selections are defined, the selected sources will be those satisfying the logical AND of all selections (e.g. distance < X && minmax_ts[0] < ts < minmax_ts[1] && ...). Parameters --------...
2.489959
3.125455
0.796671
name = self.roi.get_source_by_name(name).name idx = self.like.par_index(name, par) current_bounds = list(self.like.model[idx].getBounds()) if scale is not None: self.like[idx].setScale(scale) else: scale = self.like.model[idx].getScale() ...
def set_parameter(self, name, par, value, true_value=True, scale=None, bounds=None, error=None, update_source=True)
Update the value of a parameter. Parameter bounds will automatically be adjusted to encompass the new parameter value. Parameters ---------- name : str Source name. par : str Parameter name. value : float Parameter value. ...
2.606494
2.608965
0.999053
name = self.roi.get_source_by_name(name).name idx = self.like.par_index(name, par) current_bounds = list(self.like.model[idx].getBounds()) current_scale = self.like.model[idx].getScale() current_value = self.like[idx].getValue() self.like[idx].setScale(scale) ...
def set_parameter_scale(self, name, par, scale)
Update the scale of a parameter while keeping its value constant.
3.248414
3.163765
1.026756
idx = self.like.par_index(name, par) self.like[idx].setBounds(*bounds) self._sync_params(name)
def set_parameter_bounds(self, name, par, bounds)
Set the bounds on the scaled value of a parameter. Parameters ---------- name : str Source name. par : str Parameter name. bounds : list Upper and lower bound.
9.571791
13.085155
0.7315
idx = self.like.par_index(name, par) self.like[idx].setError(error) self._sync_params(name)
def set_parameter_error(self, name, par, error)
Set the error on the value of a parameter. Parameters ---------- name : str Source name. par : str Parameter name. error : float The value for the parameter error
9.275969
14.994158
0.618639
name = self.roi.get_source_by_name(name).name lck_params = self._lck_params.setdefault(name, []) if lock: self.free_parameter(name, par, False) if not par in lck_params: lck_params += [par] else: if par in lck_params: ...
def lock_parameter(self, name, par, lock=True)
Set parameter to locked/unlocked state. A locked parameter will be ignored when running methods that free/fix sources or parameters. Parameters ---------- name : str Source name. par : str Parameter name. lock : bool ...
3.551946
3.560699
0.997542
name = self.get_source_name(name) if par in self._lck_params.get(name, []): return idx = self.like.par_index(name, par) self.like[idx].setFree(free) self._sync_params(name)
def free_parameter(self, name, par, free=True)
Free/Fix a parameter of a source by name. Parameters ---------- name : str Source name. par : str Parameter name.
6.201579
7.502326
0.826621
name = self.get_source_name(name) if lock: par_names = self.get_source_params(name) self.free_source(name, False, pars=par_names) self._lck_params[name] = par_names else: self._lck_params[name] = []
def lock_source(self, name, lock=True)
Set all parameters of a source to a locked/unlocked state. Locked parameters will be ignored when running methods that free/fix sources or parameters. Parameters ---------- name : str Source name. lock : bool Set source parameters to lock...
3.799324
3.881001
0.978955
free_pars = self.get_free_param_vector() loglevel = kwargs.pop('loglevel', self.loglevel) # Find the source src = self.roi.get_source_by_name(name) name = src.name if pars is None or (isinstance(pars, list) and not pars): pars = [] par...
def free_source(self, name, free=True, pars=None, **kwargs)
Free/Fix parameters of a source. Parameters ---------- name : str Source name. free : bool Choose whether to free (free=True) or fix (free=False) source parameters. pars : list Set a list of parameters to be freed/fixed for this...
2.967726
3.028254
0.980012
name = self.get_source_name(name) normPar = self.like.normPar(name).getName() self.free_source(name, pars=[normPar], free=free, **kwargs)
def free_norm(self, name, free=True, **kwargs)
Free/Fix normalization of a source. Parameters ---------- name : str Source name. free : bool Choose whether to free (free=True) or fix (free=False).
7.557634
7.946286
0.95109
src = self.roi.get_source_by_name(name) self.free_source(name, free=free, pars=index_parameters.get(src['SpectrumType'], []), **kwargs)
def free_index(self, name, free=True, **kwargs)
Free/Fix index of a source. Parameters ---------- name : str Source name. free : bool Choose whether to free (free=True) or fix (free=False).
9.6516
10.299415
0.937102
src = self.roi.get_source_by_name(name) self.free_source(name, free=free, pars=shape_parameters[src['SpectrumType']], **kwargs)
def free_shape(self, name, free=True, **kwargs)
Free/Fix shape parameters of a source. Parameters ---------- name : str Source name. free : bool Choose whether to free (free=True) or fix (free=False).
9.75115
10.177446
0.958114
if name not in self.like.sourceNames(): name = self.roi.get_source_by_name(name).name return name
def get_source_name(self, name)
Return the name of a source as it is defined in the pyLikelihood model object.
9.41761
6.919186
1.361087
self.logger.debug('Profiling %s', name) if savestate: saved_state = LikelihoodState(self.like) if fix_shape: self.free_sources(False, pars='shape', loglevel=logging.DEBUG) if npts is None: npts = self.config['gtlike']['llscan_npts'] ...
def profile_norm(self, name, logemin=None, logemax=None, reoptimize=False, xvals=None, npts=None, fix_shape=True, savestate=True, **kwargs)
Profile the normalization of a source. Parameters ---------- name : str Source name. reoptimize : bool Re-optimize free parameters in the model at each point in the profile likelihood scan.
2.957926
2.894189
1.022022
# Get the covariance matrix for name in srcNames: par = self.like.normPar(name) err = par.error() val = par.getValue() if par.error() == 0.0 or not par.isFree(): continue self.add_gauss_prior(name, par.getName(), ...
def constrain_norms(self, srcNames, cov_scale=1.0)
Constrain the normalizations of one or more sources by adding gaussian priors with sigma equal to the parameter error times a scaling factor.
6.244141
5.859744
1.0656
for src in self.roi.sources: for par in self.like[src.name].funcs["Spectrum"].params.values(): par.removePrior()
def remove_priors(self)
Clear all priors.
21.539072
18.104424
1.189713
optimizer = kwargs.get('optimizer', self.config['optimizer']['optimizer']) if optimizer.upper() == 'MINUIT': optObject = pyLike.Minuit(self.like.logLike) elif optimizer.upper() == 'NEWMINUIT': optObject = pyLike.NewMinuit(self.lik...
def _create_optObject(self, **kwargs)
Make MINUIT or NewMinuit type optimizer object
3.820785
3.223979
1.185114
loglevel = kwargs.pop('loglevel', self.loglevel) self.logger.log(loglevel, "Starting fit.") # Extract options from kwargs config = copy.deepcopy(self.config['optimizer']) config.setdefault('covar', True) config.setdefault('reoptimize', False) config = u...
def fit(self, update=True, **kwargs)
Run the likelihood optimization. This will execute a fit of all parameters that are currently free in the model and update the charateristics of the corresponding model components (TS, npred, etc.). The fit will be repeated N times (set with the `retries` parameter) until a fit quality...
3.639282
3.429083
1.061299
self.logger.info('Loading XML') for c in self.components: c.load_xml(xmlfile) for name in self.like.sourceNames(): self.update_source(name) self._fitcache = None self.logger.info('Finished Loading XML')
def load_xml(self, xmlfile)
Load model definition from XML. Parameters ---------- xmlfile : str Name of the input XML file.
6.539829
6.542411
0.999605
d = utils.load_yaml(yamlfile) for src, src_pars in d.items(): for par_name, par_dict in src_pars.items(): if par_name in ['SpectrumType']: continue par_value = par_dict.get('value', None) par_error = par_dict.get('e...
def load_parameters_from_yaml(self, yamlfile, update_sources=False)
Load model parameters from yaml Parameters ---------- yamlfile : str Name of the input yaml file.
2.177343
2.293349
0.949416
for c in self.components: c.restore_counts_maps() if hasattr(self.like.components[0].logLike, 'setCountsMap'): self._init_roi_model() else: self.write_xml('tmp') self._like = SummedLikelihood() for i, c in enumerate(self._com...
def _restore_counts_maps(self)
Revert counts maps to their state prior to injecting any simulated components.
6.555533
6.169822
1.062516
self._fitcache = None if src_dict is None: src_dict = {} else: src_dict = copy.deepcopy(src_dict) skydir = wcs_utils.get_target_skydir(src_dict, self.roi.skydir) src_dict.setdefault('ra', skydir.ra.deg) src_dict.setdefault('dec', skydi...
def simulate_source(self, src_dict=None)
Inject simulated source counts into the data. Parameters ---------- src_dict : dict Dictionary defining the spatial and spectral properties of the source that will be injected.
4.429684
4.5396
0.975787
self.logger.info('Simulating ROI') self._fitcache = None if restore: self.logger.info('Restoring') self._restore_counts_maps() self.logger.info('Finished') return for c in self.components: c.simulate_roi(name=name, ...
def simulate_roi(self, name=None, randomize=True, restore=False)
Generate a simulation of the ROI using the current best-fit model and replace the data counts cube with this simulation. The simulation is created by generating an array of Poisson random numbers with expectation values drawn from the model cube of the binned analysis instance. This fu...
5.128649
4.563069
1.123947
maps = [c.write_model_map(model_name, name) for c in self.components] outfile = os.path.join(self.workdir, 'mcube_%s.fits' % (model_name)) mmap = Map.from_geom(self.geom) for m in maps: mmap.coadd(m) mmap.write(outfile, overwr...
def write_model_map(self, model_name, name=None)
Save the counts model map to a FITS file. Parameters ---------- model_name : str String that will be append to the name of the output file. name : str Name of the component. Returns -------
5.31489
5.638204
0.942657
maps = [c.write_weight_map(model_name) for c in self.components] outfile = os.path.join(self.workdir, 'wcube_%s.fits' % (model_name)) wmap = Map.from_geom(self.geom) # FIXME: Should we average weights maps rather than coadding? for m in m...
def write_weight_map(self, model_name)
Save the counts model map to a FITS file. Parameters ---------- model_name : str String that will be append to the name of the output file. Returns -------
6.405684
6.690164
0.957478