repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
fermiPy/fermipy
fermipy/diffuse/catalog_src_manager.py
make_catalog_comp_dict
def make_catalog_comp_dict(**kwargs): """Build and return the information about the catalog components """ library_yamlfile = kwargs.pop('library', 'models/library.yaml') csm = kwargs.pop('CatalogSourceManager', CatalogSourceManager(**kwargs)) if library_yamlfile is None or library_yamlfile == 'None': yamldict = {} else: yamldict = yaml.safe_load(open(library_yamlfile)) catalog_info_dict, comp_info_dict = csm.make_catalog_comp_info_dict(yamldict) return dict(catalog_info_dict=catalog_info_dict, comp_info_dict=comp_info_dict, CatalogSourceManager=csm)
python
def make_catalog_comp_dict(**kwargs): """Build and return the information about the catalog components """ library_yamlfile = kwargs.pop('library', 'models/library.yaml') csm = kwargs.pop('CatalogSourceManager', CatalogSourceManager(**kwargs)) if library_yamlfile is None or library_yamlfile == 'None': yamldict = {} else: yamldict = yaml.safe_load(open(library_yamlfile)) catalog_info_dict, comp_info_dict = csm.make_catalog_comp_info_dict(yamldict) return dict(catalog_info_dict=catalog_info_dict, comp_info_dict=comp_info_dict, CatalogSourceManager=csm)
[ "def", "make_catalog_comp_dict", "(", "*", "*", "kwargs", ")", ":", "library_yamlfile", "=", "kwargs", ".", "pop", "(", "'library'", ",", "'models/library.yaml'", ")", "csm", "=", "kwargs", ".", "pop", "(", "'CatalogSourceManager'", ",", "CatalogSourceManager", ...
Build and return the information about the catalog components
[ "Build", "and", "return", "the", "information", "about", "the", "catalog", "components" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/catalog_src_manager.py#L256-L268
train
35,900
fermiPy/fermipy
fermipy/diffuse/catalog_src_manager.py
CatalogSourceManager.read_catalog_info_yaml
def read_catalog_info_yaml(self, splitkey): """ Read the yaml file for a particular split key """ catalog_info_yaml = self._name_factory.catalog_split_yaml(sourcekey=splitkey, fullpath=True) yaml_dict = yaml.safe_load(open(catalog_info_yaml)) # resolve env vars yaml_dict['catalog_file'] = os.path.expandvars(yaml_dict['catalog_file']) yaml_dict['catalog_extdir'] = os.path.expandvars(yaml_dict['catalog_extdir']) return yaml_dict
python
def read_catalog_info_yaml(self, splitkey): """ Read the yaml file for a particular split key """ catalog_info_yaml = self._name_factory.catalog_split_yaml(sourcekey=splitkey, fullpath=True) yaml_dict = yaml.safe_load(open(catalog_info_yaml)) # resolve env vars yaml_dict['catalog_file'] = os.path.expandvars(yaml_dict['catalog_file']) yaml_dict['catalog_extdir'] = os.path.expandvars(yaml_dict['catalog_extdir']) return yaml_dict
[ "def", "read_catalog_info_yaml", "(", "self", ",", "splitkey", ")", ":", "catalog_info_yaml", "=", "self", ".", "_name_factory", ".", "catalog_split_yaml", "(", "sourcekey", "=", "splitkey", ",", "fullpath", "=", "True", ")", "yaml_dict", "=", "yaml", ".", "sa...
Read the yaml file for a particular split key
[ "Read", "the", "yaml", "file", "for", "a", "particular", "split", "key" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/catalog_src_manager.py#L101-L110
train
35,901
fermiPy/fermipy
fermipy/diffuse/catalog_src_manager.py
CatalogSourceManager.build_catalog_info
def build_catalog_info(self, catalog_info): """ Build a CatalogInfo object """ cat = SourceFactory.build_catalog(**catalog_info) catalog_info['catalog'] = cat # catalog_info['catalog_table'] = # Table.read(catalog_info['catalog_file']) catalog_info['catalog_table'] = cat.table catalog_info['roi_model'] =\ SourceFactory.make_fermipy_roi_model_from_catalogs([cat]) catalog_info['srcmdl_name'] =\ self._name_factory.srcmdl_xml(sourcekey=catalog_info['catalog_name']) return CatalogInfo(**catalog_info)
python
def build_catalog_info(self, catalog_info): """ Build a CatalogInfo object """ cat = SourceFactory.build_catalog(**catalog_info) catalog_info['catalog'] = cat # catalog_info['catalog_table'] = # Table.read(catalog_info['catalog_file']) catalog_info['catalog_table'] = cat.table catalog_info['roi_model'] =\ SourceFactory.make_fermipy_roi_model_from_catalogs([cat]) catalog_info['srcmdl_name'] =\ self._name_factory.srcmdl_xml(sourcekey=catalog_info['catalog_name']) return CatalogInfo(**catalog_info)
[ "def", "build_catalog_info", "(", "self", ",", "catalog_info", ")", ":", "cat", "=", "SourceFactory", ".", "build_catalog", "(", "*", "*", "catalog_info", ")", "catalog_info", "[", "'catalog'", "]", "=", "cat", "# catalog_info['catalog_table'] =", "# Table.read(c...
Build a CatalogInfo object
[ "Build", "a", "CatalogInfo", "object" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/catalog_src_manager.py#L112-L123
train
35,902
fermiPy/fermipy
fermipy/diffuse/catalog_src_manager.py
CatalogSourceManager.catalog_components
def catalog_components(self, catalog_name, split_ver): """ Return the set of merged components for a particular split key """ return sorted(self._split_comp_info_dicts["%s_%s" % (catalog_name, split_ver)].keys())
python
def catalog_components(self, catalog_name, split_ver): """ Return the set of merged components for a particular split key """ return sorted(self._split_comp_info_dicts["%s_%s" % (catalog_name, split_ver)].keys())
[ "def", "catalog_components", "(", "self", ",", "catalog_name", ",", "split_ver", ")", ":", "return", "sorted", "(", "self", ".", "_split_comp_info_dicts", "[", "\"%s_%s\"", "%", "(", "catalog_name", ",", "split_ver", ")", "]", ".", "keys", "(", ")", ")" ]
Return the set of merged components for a particular split key
[ "Return", "the", "set", "of", "merged", "components", "for", "a", "particular", "split", "key" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/catalog_src_manager.py#L141-L143
train
35,903
fermiPy/fermipy
fermipy/diffuse/catalog_src_manager.py
CatalogSourceManager.split_comp_info
def split_comp_info(self, catalog_name, split_ver, split_key): """ Return the info for a particular split key """ return self._split_comp_info_dicts["%s_%s" % (catalog_name, split_ver)][split_key]
python
def split_comp_info(self, catalog_name, split_ver, split_key): """ Return the info for a particular split key """ return self._split_comp_info_dicts["%s_%s" % (catalog_name, split_ver)][split_key]
[ "def", "split_comp_info", "(", "self", ",", "catalog_name", ",", "split_ver", ",", "split_key", ")", ":", "return", "self", ".", "_split_comp_info_dicts", "[", "\"%s_%s\"", "%", "(", "catalog_name", ",", "split_ver", ")", "]", "[", "split_key", "]" ]
Return the info for a particular split key
[ "Return", "the", "info", "for", "a", "particular", "split", "key" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/catalog_src_manager.py#L145-L147
train
35,904
fermiPy/fermipy
fermipy/diffuse/catalog_src_manager.py
CatalogSourceManager.make_catalog_comp_info_dict
def make_catalog_comp_info_dict(self, catalog_sources): """ Make the information about the catalog components Parameters ---------- catalog_sources : dict Dictionary with catalog source defintions Returns ------- catalog_ret_dict : dict Dictionary mapping catalog_name to `model_component.CatalogInfo` split_ret_dict : dict Dictionary mapping sourcekey to `model_component.ModelComponentInfo` """ catalog_ret_dict = {} split_ret_dict = {} for key, value in catalog_sources.items(): if value is None: continue if value['model_type'] != 'catalog': continue versions = value['versions'] for version in versions: ver_key = "%s_%s" % (key, version) source_dict = self.read_catalog_info_yaml(ver_key) try: full_cat_info = catalog_ret_dict[key] except KeyError: full_cat_info = self.build_catalog_info(source_dict) catalog_ret_dict[key] = full_cat_info try: all_sources = [x.strip() for x in full_cat_info.catalog_table[ 'Source_Name'].astype(str).tolist()] except KeyError: print(full_cat_info.catalog_table.colnames) used_sources = [] rules_dict = source_dict['rules_dict'] split_dict = {} for rule_key, rule_val in rules_dict.items(): # full_key =\ # self._name_factory.merged_sourcekey(catalog=ver_key, # rulekey=rule_key) sources = select_sources( full_cat_info.catalog_table, rule_val['cuts']) used_sources.extend(sources) split_dict[rule_key] = self.make_catalog_comp_info( full_cat_info, version, rule_key, rule_val, sources) # Now deal with the remainder for source in used_sources: try: all_sources.remove(source) except ValueError: continue rule_val = dict(cuts=[], merge=source_dict['remainder'].get('merge', False)) split_dict['remain'] = self.make_catalog_comp_info( full_cat_info, version, 'remain', rule_val, all_sources) # Merge in the info for this version of splits split_ret_dict[ver_key] = split_dict self._catalog_comp_info_dicts.update(catalog_ret_dict) self._split_comp_info_dicts.update(split_ret_dict) return (catalog_ret_dict, split_ret_dict)
python
def make_catalog_comp_info_dict(self, catalog_sources): """ Make the information about the catalog components Parameters ---------- catalog_sources : dict Dictionary with catalog source defintions Returns ------- catalog_ret_dict : dict Dictionary mapping catalog_name to `model_component.CatalogInfo` split_ret_dict : dict Dictionary mapping sourcekey to `model_component.ModelComponentInfo` """ catalog_ret_dict = {} split_ret_dict = {} for key, value in catalog_sources.items(): if value is None: continue if value['model_type'] != 'catalog': continue versions = value['versions'] for version in versions: ver_key = "%s_%s" % (key, version) source_dict = self.read_catalog_info_yaml(ver_key) try: full_cat_info = catalog_ret_dict[key] except KeyError: full_cat_info = self.build_catalog_info(source_dict) catalog_ret_dict[key] = full_cat_info try: all_sources = [x.strip() for x in full_cat_info.catalog_table[ 'Source_Name'].astype(str).tolist()] except KeyError: print(full_cat_info.catalog_table.colnames) used_sources = [] rules_dict = source_dict['rules_dict'] split_dict = {} for rule_key, rule_val in rules_dict.items(): # full_key =\ # self._name_factory.merged_sourcekey(catalog=ver_key, # rulekey=rule_key) sources = select_sources( full_cat_info.catalog_table, rule_val['cuts']) used_sources.extend(sources) split_dict[rule_key] = self.make_catalog_comp_info( full_cat_info, version, rule_key, rule_val, sources) # Now deal with the remainder for source in used_sources: try: all_sources.remove(source) except ValueError: continue rule_val = dict(cuts=[], merge=source_dict['remainder'].get('merge', False)) split_dict['remain'] = self.make_catalog_comp_info( full_cat_info, version, 'remain', rule_val, all_sources) # Merge in the info for this version of splits split_ret_dict[ver_key] = split_dict self._catalog_comp_info_dicts.update(catalog_ret_dict) self._split_comp_info_dicts.update(split_ret_dict) return (catalog_ret_dict, split_ret_dict)
[ "def", "make_catalog_comp_info_dict", "(", "self", ",", "catalog_sources", ")", ":", "catalog_ret_dict", "=", "{", "}", "split_ret_dict", "=", "{", "}", "for", "key", ",", "value", "in", "catalog_sources", ".", "items", "(", ")", ":", "if", "value", "is", ...
Make the information about the catalog components Parameters ---------- catalog_sources : dict Dictionary with catalog source defintions Returns ------- catalog_ret_dict : dict Dictionary mapping catalog_name to `model_component.CatalogInfo` split_ret_dict : dict Dictionary mapping sourcekey to `model_component.ModelComponentInfo`
[ "Make", "the", "information", "about", "the", "catalog", "components" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/catalog_src_manager.py#L185-L253
train
35,905
fermiPy/fermipy
fermipy/tsmap.py
extract_images_from_tscube
def extract_images_from_tscube(infile, outfile): """ Extract data from table HDUs in TSCube file and convert them to FITS images """ inhdulist = fits.open(infile) wcs = pywcs.WCS(inhdulist[0].header) map_shape = inhdulist[0].data.shape t_eng = Table.read(infile, "EBOUNDS") t_scan = Table.read(infile, "SCANDATA") t_fit = Table.read(infile, "FITDATA") n_ebin = len(t_eng) energies = np.ndarray((n_ebin + 1)) energies[0:-1] = t_eng["E_MIN"] energies[-1] = t_eng["E_MAX"][-1] cube_shape = (n_ebin, map_shape[1], map_shape[0]) wcs_cube = wcs_utils.wcs_add_energy_axis(wcs, energies) outhdulist = [inhdulist[0], inhdulist["EBOUNDS"]] FIT_COLNAMES = ['FIT_TS', 'FIT_STATUS', 'FIT_NORM', 'FIT_NORM_ERR', 'FIT_NORM_ERRP', 'FIT_NORM_ERRN'] SCAN_COLNAMES = ['TS', 'BIN_STATUS', 'NORM', 'NORM_UL', 'NORM_ERR', 'NORM_ERRP', 'NORM_ERRN', 'LOGLIKE'] for c in FIT_COLNAMES: data = t_fit[c].data.reshape(map_shape) hdu = fits.ImageHDU(data, wcs.to_header(), name=c) outhdulist.append(hdu) for c in SCAN_COLNAMES: data = t_scan[c].data.swapaxes(0, 1).reshape(cube_shape) hdu = fits.ImageHDU(data, wcs_cube.to_header(), name=c) outhdulist.append(hdu) hdulist = fits.HDUList(outhdulist) hdulist.writeto(outfile, clobber=True) return hdulist
python
def extract_images_from_tscube(infile, outfile): """ Extract data from table HDUs in TSCube file and convert them to FITS images """ inhdulist = fits.open(infile) wcs = pywcs.WCS(inhdulist[0].header) map_shape = inhdulist[0].data.shape t_eng = Table.read(infile, "EBOUNDS") t_scan = Table.read(infile, "SCANDATA") t_fit = Table.read(infile, "FITDATA") n_ebin = len(t_eng) energies = np.ndarray((n_ebin + 1)) energies[0:-1] = t_eng["E_MIN"] energies[-1] = t_eng["E_MAX"][-1] cube_shape = (n_ebin, map_shape[1], map_shape[0]) wcs_cube = wcs_utils.wcs_add_energy_axis(wcs, energies) outhdulist = [inhdulist[0], inhdulist["EBOUNDS"]] FIT_COLNAMES = ['FIT_TS', 'FIT_STATUS', 'FIT_NORM', 'FIT_NORM_ERR', 'FIT_NORM_ERRP', 'FIT_NORM_ERRN'] SCAN_COLNAMES = ['TS', 'BIN_STATUS', 'NORM', 'NORM_UL', 'NORM_ERR', 'NORM_ERRP', 'NORM_ERRN', 'LOGLIKE'] for c in FIT_COLNAMES: data = t_fit[c].data.reshape(map_shape) hdu = fits.ImageHDU(data, wcs.to_header(), name=c) outhdulist.append(hdu) for c in SCAN_COLNAMES: data = t_scan[c].data.swapaxes(0, 1).reshape(cube_shape) hdu = fits.ImageHDU(data, wcs_cube.to_header(), name=c) outhdulist.append(hdu) hdulist = fits.HDUList(outhdulist) hdulist.writeto(outfile, clobber=True) return hdulist
[ "def", "extract_images_from_tscube", "(", "infile", ",", "outfile", ")", ":", "inhdulist", "=", "fits", ".", "open", "(", "infile", ")", "wcs", "=", "pywcs", ".", "WCS", "(", "inhdulist", "[", "0", "]", ".", "header", ")", "map_shape", "=", "inhdulist", ...
Extract data from table HDUs in TSCube file and convert them to FITS images
[ "Extract", "data", "from", "table", "HDUs", "in", "TSCube", "file", "and", "convert", "them", "to", "FITS", "images" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/tsmap.py#L35-L74
train
35,906
fermiPy/fermipy
fermipy/tsmap.py
truncate_array
def truncate_array(array1, array2, position): """Truncate array1 by finding the overlap with array2 when the array1 center is located at the given position in array2.""" slices = [] for i in range(array1.ndim): xmin = 0 xmax = array1.shape[i] dxlo = array1.shape[i] // 2 dxhi = array1.shape[i] - dxlo if position[i] - dxlo < 0: xmin = max(dxlo - position[i], 0) if position[i] + dxhi > array2.shape[i]: xmax = array1.shape[i] - (position[i] + dxhi - array2.shape[i]) xmax = max(xmax, 0) slices += [slice(xmin, xmax)] return array1[slices]
python
def truncate_array(array1, array2, position): """Truncate array1 by finding the overlap with array2 when the array1 center is located at the given position in array2.""" slices = [] for i in range(array1.ndim): xmin = 0 xmax = array1.shape[i] dxlo = array1.shape[i] // 2 dxhi = array1.shape[i] - dxlo if position[i] - dxlo < 0: xmin = max(dxlo - position[i], 0) if position[i] + dxhi > array2.shape[i]: xmax = array1.shape[i] - (position[i] + dxhi - array2.shape[i]) xmax = max(xmax, 0) slices += [slice(xmin, xmax)] return array1[slices]
[ "def", "truncate_array", "(", "array1", ",", "array2", ",", "position", ")", ":", "slices", "=", "[", "]", "for", "i", "in", "range", "(", "array1", ".", "ndim", ")", ":", "xmin", "=", "0", "xmax", "=", "array1", ".", "shape", "[", "i", "]", "dxl...
Truncate array1 by finding the overlap with array2 when the array1 center is located at the given position in array2.
[ "Truncate", "array1", "by", "finding", "the", "overlap", "with", "array2", "when", "the", "array1", "center", "is", "located", "at", "the", "given", "position", "in", "array2", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/tsmap.py#L265-L283
train
35,907
fermiPy/fermipy
fermipy/tsmap.py
_sum_wrapper
def _sum_wrapper(fn): """ Wrapper to perform row-wise aggregation of list arguments and pass them to a function. The return value of the function is summed over the argument groups. Non-list arguments will be automatically cast to a list. """ def wrapper(*args, **kwargs): v = 0 new_args = _cast_args_to_list(args) for arg in zip(*new_args): v += fn(*arg, **kwargs) return v return wrapper
python
def _sum_wrapper(fn): """ Wrapper to perform row-wise aggregation of list arguments and pass them to a function. The return value of the function is summed over the argument groups. Non-list arguments will be automatically cast to a list. """ def wrapper(*args, **kwargs): v = 0 new_args = _cast_args_to_list(args) for arg in zip(*new_args): v += fn(*arg, **kwargs) return v return wrapper
[ "def", "_sum_wrapper", "(", "fn", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "v", "=", "0", "new_args", "=", "_cast_args_to_list", "(", "args", ")", "for", "arg", "in", "zip", "(", "*", "new_args", ")", ":", ...
Wrapper to perform row-wise aggregation of list arguments and pass them to a function. The return value of the function is summed over the argument groups. Non-list arguments will be automatically cast to a list.
[ "Wrapper", "to", "perform", "row", "-", "wise", "aggregation", "of", "list", "arguments", "and", "pass", "them", "to", "a", "function", ".", "The", "return", "value", "of", "the", "function", "is", "summed", "over", "the", "argument", "groups", ".", "Non",...
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/tsmap.py#L325-L340
train
35,908
fermiPy/fermipy
fermipy/tsmap.py
_amplitude_bounds
def _amplitude_bounds(counts, bkg, model): """ Compute bounds for the root of `_f_cash_root_cython`. Parameters ---------- counts : `~numpy.ndarray` Count map. bkg : `~numpy.ndarray` Background map. model : `~numpy.ndarray` Source template (multiplied with exposure). """ if isinstance(counts, list): counts = np.concatenate([t.flat for t in counts]) bkg = np.concatenate([t.flat for t in bkg]) model = np.concatenate([t.flat for t in model]) s_model = np.sum(model) s_counts = np.sum(counts) sn = bkg / model imin = np.argmin(sn) sn_min = sn[imin] c_min = counts[imin] b_min = c_min / s_model - sn_min b_max = s_counts / s_model - sn_min return max(b_min, 0), b_max
python
def _amplitude_bounds(counts, bkg, model): """ Compute bounds for the root of `_f_cash_root_cython`. Parameters ---------- counts : `~numpy.ndarray` Count map. bkg : `~numpy.ndarray` Background map. model : `~numpy.ndarray` Source template (multiplied with exposure). """ if isinstance(counts, list): counts = np.concatenate([t.flat for t in counts]) bkg = np.concatenate([t.flat for t in bkg]) model = np.concatenate([t.flat for t in model]) s_model = np.sum(model) s_counts = np.sum(counts) sn = bkg / model imin = np.argmin(sn) sn_min = sn[imin] c_min = counts[imin] b_min = c_min / s_model - sn_min b_max = s_counts / s_model - sn_min return max(b_min, 0), b_max
[ "def", "_amplitude_bounds", "(", "counts", ",", "bkg", ",", "model", ")", ":", "if", "isinstance", "(", "counts", ",", "list", ")", ":", "counts", "=", "np", ".", "concatenate", "(", "[", "t", ".", "flat", "for", "t", "in", "counts", "]", ")", "bkg...
Compute bounds for the root of `_f_cash_root_cython`. Parameters ---------- counts : `~numpy.ndarray` Count map. bkg : `~numpy.ndarray` Background map. model : `~numpy.ndarray` Source template (multiplied with exposure).
[ "Compute", "bounds", "for", "the", "root", "of", "_f_cash_root_cython", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/tsmap.py#L358-L387
train
35,909
fermiPy/fermipy
fermipy/tsmap.py
_root_amplitude_brentq
def _root_amplitude_brentq(counts, bkg, model, root_fn=_f_cash_root): """Fit amplitude by finding roots using Brent algorithm. See Appendix A Stewart (2009). Parameters ---------- counts : `~numpy.ndarray` Slice of count map. bkg : `~numpy.ndarray` Slice of background map. model : `~numpy.ndarray` Model template to fit. Returns ------- amplitude : float Fitted flux amplitude. niter : int Number of function evaluations needed for the fit. """ # Compute amplitude bounds and assert counts > 0 amplitude_min, amplitude_max = _amplitude_bounds(counts, bkg, model) if not np.sum(counts) > 0: return amplitude_min, 0 args = (counts, bkg, model) if root_fn(0.0, *args) < 0: return 0.0, 1 with warnings.catch_warnings(): warnings.simplefilter("ignore") try: result = brentq(root_fn, amplitude_min, amplitude_max, args=args, maxiter=MAX_NITER, full_output=True, rtol=1E-4) return result[0], result[1].iterations except (RuntimeError, ValueError): # Where the root finding fails NaN is set as amplitude return np.nan, MAX_NITER
python
def _root_amplitude_brentq(counts, bkg, model, root_fn=_f_cash_root): """Fit amplitude by finding roots using Brent algorithm. See Appendix A Stewart (2009). Parameters ---------- counts : `~numpy.ndarray` Slice of count map. bkg : `~numpy.ndarray` Slice of background map. model : `~numpy.ndarray` Model template to fit. Returns ------- amplitude : float Fitted flux amplitude. niter : int Number of function evaluations needed for the fit. """ # Compute amplitude bounds and assert counts > 0 amplitude_min, amplitude_max = _amplitude_bounds(counts, bkg, model) if not np.sum(counts) > 0: return amplitude_min, 0 args = (counts, bkg, model) if root_fn(0.0, *args) < 0: return 0.0, 1 with warnings.catch_warnings(): warnings.simplefilter("ignore") try: result = brentq(root_fn, amplitude_min, amplitude_max, args=args, maxiter=MAX_NITER, full_output=True, rtol=1E-4) return result[0], result[1].iterations except (RuntimeError, ValueError): # Where the root finding fails NaN is set as amplitude return np.nan, MAX_NITER
[ "def", "_root_amplitude_brentq", "(", "counts", ",", "bkg", ",", "model", ",", "root_fn", "=", "_f_cash_root", ")", ":", "# Compute amplitude bounds and assert counts > 0", "amplitude_min", ",", "amplitude_max", "=", "_amplitude_bounds", "(", "counts", ",", "bkg", ","...
Fit amplitude by finding roots using Brent algorithm. See Appendix A Stewart (2009). Parameters ---------- counts : `~numpy.ndarray` Slice of count map. bkg : `~numpy.ndarray` Slice of background map. model : `~numpy.ndarray` Model template to fit. Returns ------- amplitude : float Fitted flux amplitude. niter : int Number of function evaluations needed for the fit.
[ "Fit", "amplitude", "by", "finding", "roots", "using", "Brent", "algorithm", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/tsmap.py#L445-L486
train
35,910
fermiPy/fermipy
fermipy/tsmap.py
poisson_log_like
def poisson_log_like(counts, model): """Compute the Poisson log-likelihood function for the given counts and model arrays.""" loglike = np.array(model) m = counts > 0 loglike[m] -= counts[m] * np.log(model[m]) return loglike
python
def poisson_log_like(counts, model): """Compute the Poisson log-likelihood function for the given counts and model arrays.""" loglike = np.array(model) m = counts > 0 loglike[m] -= counts[m] * np.log(model[m]) return loglike
[ "def", "poisson_log_like", "(", "counts", ",", "model", ")", ":", "loglike", "=", "np", ".", "array", "(", "model", ")", "m", "=", "counts", ">", "0", "loglike", "[", "m", "]", "-=", "counts", "[", "m", "]", "*", "np", ".", "log", "(", "model", ...
Compute the Poisson log-likelihood function for the given counts and model arrays.
[ "Compute", "the", "Poisson", "log", "-", "likelihood", "function", "for", "the", "given", "counts", "and", "model", "arrays", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/tsmap.py#L489-L495
train
35,911
fermiPy/fermipy
fermipy/tsmap.py
f_cash
def f_cash(x, counts, bkg, model): """ Wrapper for cash statistics, that defines the model function. Parameters ---------- x : float Model amplitude. counts : `~numpy.ndarray` Count map slice, where model is defined. bkg : `~numpy.ndarray` Background map slice, where model is defined. model : `~numpy.ndarray` Source template (multiplied with exposure). """ return 2.0 * poisson_log_like(counts, bkg + x * model)
python
def f_cash(x, counts, bkg, model): """ Wrapper for cash statistics, that defines the model function. Parameters ---------- x : float Model amplitude. counts : `~numpy.ndarray` Count map slice, where model is defined. bkg : `~numpy.ndarray` Background map slice, where model is defined. model : `~numpy.ndarray` Source template (multiplied with exposure). """ return 2.0 * poisson_log_like(counts, bkg + x * model)
[ "def", "f_cash", "(", "x", ",", "counts", ",", "bkg", ",", "model", ")", ":", "return", "2.0", "*", "poisson_log_like", "(", "counts", ",", "bkg", "+", "x", "*", "model", ")" ]
Wrapper for cash statistics, that defines the model function. Parameters ---------- x : float Model amplitude. counts : `~numpy.ndarray` Count map slice, where model is defined. bkg : `~numpy.ndarray` Background map slice, where model is defined. model : `~numpy.ndarray` Source template (multiplied with exposure).
[ "Wrapper", "for", "cash", "statistics", "that", "defines", "the", "model", "function", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/tsmap.py#L507-L523
train
35,912
fermiPy/fermipy
fermipy/tsmap.py
_ts_value_newton
def _ts_value_newton(position, counts, bkg, model, C_0_map): """ Compute TS value at a given pixel position using the newton method. Parameters ---------- position : tuple Pixel position. counts : `~numpy.ndarray` Count map. bkg : `~numpy.ndarray` Background map. model : `~numpy.ndarray` Source model map. Returns ------- TS : float TS value at the given pixel position. amp : float Best-fit amplitude of the test source. niter : int Number of fit iterations. """ extract_fn = _collect_wrapper(extract_large_array) truncate_fn = _collect_wrapper(extract_small_array) # Get data slices counts_slice = extract_fn(counts, model, position) bkg_slice = extract_fn(bkg, model, position) C_0_map_slice = extract_fn(C_0_map, model, position) model_slice = truncate_fn(model, counts, position) # Mask of pixels with > 0 counts mask = [c > 0 for c in counts_slice] # Sum of background and model in empty pixels bkg_sum = np.sum(np.array([np.sum(t[~m]) for t, m in zip(bkg_slice, mask)])) model_sum = np.sum(np.array([np.sum(t[~m]) for t, m in zip(model_slice, mask)])) # Flattened Arrays counts_ = np.concatenate([t[m].flat for t, m in zip(counts_slice, mask)]) bkg_ = np.concatenate([t[m].flat for t, m in zip(bkg_slice, mask)]) model_ = np.concatenate([t[m].flat for t, m in zip(model_slice, mask)]) C_0 = np.sum(np.array([np.sum(t) for t in C_0_map_slice])) amplitude, niter = _fit_amplitude_newton(counts_, bkg_, model_, model_sum) if niter > MAX_NITER: print('Exceeded maximum number of function evaluations!') return np.nan, amplitude, niter with np.errstate(invalid='ignore', divide='ignore'): C_1 = f_cash_sum(amplitude, counts_, bkg_, model_, bkg_sum, model_sum) # Compute and return TS value return (C_0 - C_1) * np.sign(amplitude), amplitude, niter
python
def _ts_value_newton(position, counts, bkg, model, C_0_map): """ Compute TS value at a given pixel position using the newton method. Parameters ---------- position : tuple Pixel position. counts : `~numpy.ndarray` Count map. bkg : `~numpy.ndarray` Background map. model : `~numpy.ndarray` Source model map. Returns ------- TS : float TS value at the given pixel position. amp : float Best-fit amplitude of the test source. niter : int Number of fit iterations. """ extract_fn = _collect_wrapper(extract_large_array) truncate_fn = _collect_wrapper(extract_small_array) # Get data slices counts_slice = extract_fn(counts, model, position) bkg_slice = extract_fn(bkg, model, position) C_0_map_slice = extract_fn(C_0_map, model, position) model_slice = truncate_fn(model, counts, position) # Mask of pixels with > 0 counts mask = [c > 0 for c in counts_slice] # Sum of background and model in empty pixels bkg_sum = np.sum(np.array([np.sum(t[~m]) for t, m in zip(bkg_slice, mask)])) model_sum = np.sum(np.array([np.sum(t[~m]) for t, m in zip(model_slice, mask)])) # Flattened Arrays counts_ = np.concatenate([t[m].flat for t, m in zip(counts_slice, mask)]) bkg_ = np.concatenate([t[m].flat for t, m in zip(bkg_slice, mask)]) model_ = np.concatenate([t[m].flat for t, m in zip(model_slice, mask)]) C_0 = np.sum(np.array([np.sum(t) for t in C_0_map_slice])) amplitude, niter = _fit_amplitude_newton(counts_, bkg_, model_, model_sum) if niter > MAX_NITER: print('Exceeded maximum number of function evaluations!') return np.nan, amplitude, niter with np.errstate(invalid='ignore', divide='ignore'): C_1 = f_cash_sum(amplitude, counts_, bkg_, model_, bkg_sum, model_sum) # Compute and return TS value return (C_0 - C_1) * np.sign(amplitude), amplitude, niter
[ "def", "_ts_value_newton", "(", "position", ",", "counts", ",", "bkg", ",", "model", ",", "C_0_map", ")", ":", "extract_fn", "=", "_collect_wrapper", "(", "extract_large_array", ")", "truncate_fn", "=", "_collect_wrapper", "(", "extract_small_array", ")", "# Get d...
Compute TS value at a given pixel position using the newton method. Parameters ---------- position : tuple Pixel position. counts : `~numpy.ndarray` Count map. bkg : `~numpy.ndarray` Background map. model : `~numpy.ndarray` Source model map. Returns ------- TS : float TS value at the given pixel position. amp : float Best-fit amplitude of the test source. niter : int Number of fit iterations.
[ "Compute", "TS", "value", "at", "a", "given", "pixel", "position", "using", "the", "newton", "method", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/tsmap.py#L578-L643
train
35,913
fermiPy/fermipy
fermipy/tsmap.py
TSMapGenerator.tsmap
def tsmap(self, prefix='', **kwargs): """Generate a spatial TS map for a source component with properties defined by the `model` argument. The TS map will have the same geometry as the ROI. The output of this method is a dictionary containing `~fermipy.skymap.Map` objects with the TS and amplitude of the best-fit test source. By default this method will also save maps to FITS files and render them as image files. This method uses a simplified likelihood fitting implementation that only fits for the normalization of the test source. Before running this method it is recommended to first optimize the ROI model (e.g. by running :py:meth:`~fermipy.gtanalysis.GTAnalysis.optimize`). Parameters ---------- prefix : str Optional string that will be prepended to all output files. {options} Returns ------- tsmap : dict A dictionary containing the `~fermipy.skymap.Map` objects for TS and source amplitude. """ timer = Timer.create(start=True) schema = ConfigSchema(self.defaults['tsmap']) schema.add_option('loglevel', logging.INFO) schema.add_option('map_skydir', None, '', astropy.coordinates.SkyCoord) schema.add_option('map_size', 1.0) schema.add_option('threshold', 1E-2, '', float) schema.add_option('use_pylike', True, '', bool) schema.add_option('outfile', None, '', str) config = schema.create_config(self.config['tsmap'], **kwargs) # Defining default properties of test source model config['model'].setdefault('Index', 2.0) config['model'].setdefault('SpectrumType', 'PowerLaw') config['model'].setdefault('SpatialModel', 'PointSource') self.logger.log(config['loglevel'], 'Generating TS map') o = self._make_tsmap_fast(prefix, **config) if config['make_plots']: plotter = plotting.AnalysisPlotter(self.config['plotting'], fileio=self.config['fileio'], logging=self.config['logging']) plotter.make_tsmap_plots(o, self.roi) self.logger.log(config['loglevel'], 'Finished TS map') outfile = config.get('outfile', None) if outfile is None: outfile = utils.format_filename(self.workdir, 'tsmap', prefix=[o['name']]) else: outfile = os.path.join(self.workdir, os.path.splitext(outfile)[0]) if config['write_fits']: o['file'] = os.path.basename(outfile) + '.fits' self._make_tsmap_fits(o, outfile + '.fits') if config['write_npy']: np.save(outfile + '.npy', o) self.logger.log(config['loglevel'], 'Execution time: %.2f s', timer.elapsed_time) return o
python
def tsmap(self, prefix='', **kwargs): """Generate a spatial TS map for a source component with properties defined by the `model` argument. The TS map will have the same geometry as the ROI. The output of this method is a dictionary containing `~fermipy.skymap.Map` objects with the TS and amplitude of the best-fit test source. By default this method will also save maps to FITS files and render them as image files. This method uses a simplified likelihood fitting implementation that only fits for the normalization of the test source. Before running this method it is recommended to first optimize the ROI model (e.g. by running :py:meth:`~fermipy.gtanalysis.GTAnalysis.optimize`). Parameters ---------- prefix : str Optional string that will be prepended to all output files. {options} Returns ------- tsmap : dict A dictionary containing the `~fermipy.skymap.Map` objects for TS and source amplitude. """ timer = Timer.create(start=True) schema = ConfigSchema(self.defaults['tsmap']) schema.add_option('loglevel', logging.INFO) schema.add_option('map_skydir', None, '', astropy.coordinates.SkyCoord) schema.add_option('map_size', 1.0) schema.add_option('threshold', 1E-2, '', float) schema.add_option('use_pylike', True, '', bool) schema.add_option('outfile', None, '', str) config = schema.create_config(self.config['tsmap'], **kwargs) # Defining default properties of test source model config['model'].setdefault('Index', 2.0) config['model'].setdefault('SpectrumType', 'PowerLaw') config['model'].setdefault('SpatialModel', 'PointSource') self.logger.log(config['loglevel'], 'Generating TS map') o = self._make_tsmap_fast(prefix, **config) if config['make_plots']: plotter = plotting.AnalysisPlotter(self.config['plotting'], fileio=self.config['fileio'], logging=self.config['logging']) plotter.make_tsmap_plots(o, self.roi) self.logger.log(config['loglevel'], 'Finished TS map') outfile = config.get('outfile', None) if outfile is None: outfile = utils.format_filename(self.workdir, 'tsmap', prefix=[o['name']]) else: outfile = os.path.join(self.workdir, os.path.splitext(outfile)[0]) if config['write_fits']: o['file'] = os.path.basename(outfile) + '.fits' self._make_tsmap_fits(o, outfile + '.fits') if config['write_npy']: np.save(outfile + '.npy', o) self.logger.log(config['loglevel'], 'Execution time: %.2f s', timer.elapsed_time) return o
[ "def", "tsmap", "(", "self", ",", "prefix", "=", "''", ",", "*", "*", "kwargs", ")", ":", "timer", "=", "Timer", ".", "create", "(", "start", "=", "True", ")", "schema", "=", "ConfigSchema", "(", "self", ".", "defaults", "[", "'tsmap'", "]", ")", ...
Generate a spatial TS map for a source component with properties defined by the `model` argument. The TS map will have the same geometry as the ROI. The output of this method is a dictionary containing `~fermipy.skymap.Map` objects with the TS and amplitude of the best-fit test source. By default this method will also save maps to FITS files and render them as image files. This method uses a simplified likelihood fitting implementation that only fits for the normalization of the test source. Before running this method it is recommended to first optimize the ROI model (e.g. by running :py:meth:`~fermipy.gtanalysis.GTAnalysis.optimize`). Parameters ---------- prefix : str Optional string that will be prepended to all output files. {options} Returns ------- tsmap : dict A dictionary containing the `~fermipy.skymap.Map` objects for TS and source amplitude.
[ "Generate", "a", "spatial", "TS", "map", "for", "a", "source", "component", "with", "properties", "defined", "by", "the", "model", "argument", ".", "The", "TS", "map", "will", "have", "the", "same", "geometry", "as", "the", "ROI", ".", "The", "output", "...
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/tsmap.py#L650-L725
train
35,914
fermiPy/fermipy
fermipy/tsmap.py
TSCubeGenerator.tscube
def tscube(self, prefix='', **kwargs): """Generate a spatial TS map for a source component with properties defined by the `model` argument. This method uses the `gttscube` ST application for source fitting and will simultaneously fit the test source normalization as well as the normalizations of any background components that are currently free. The output of this method is a dictionary containing `~fermipy.skymap.Map` objects with the TS and amplitude of the best-fit test source. By default this method will also save maps to FITS files and render them as image files. Parameters ---------- prefix : str Optional string that will be prepended to all output files (FITS and rendered images). model : dict Dictionary defining the properties of the test source. do_sed : bool Compute the energy bin-by-bin fits. nnorm : int Number of points in the likelihood v. normalization scan. norm_sigma : float Number of sigma to use for the scan range. tol : float Critetia for fit convergence (estimated vertical distance to min < tol ). tol_type : int Absoulte (0) or relative (1) criteria for convergence. max_iter : int Maximum number of iterations for the Newton's method fitter remake_test_source : bool If true, recomputes the test source image (otherwise just shifts it) st_scan_level : int make_plots : bool Write image files. write_fits : bool Write a FITS file with the results of the analysis. Returns ------- maps : dict A dictionary containing the `~fermipy.skymap.Map` objects for TS and source amplitude. """ self.logger.info('Generating TS cube') schema = ConfigSchema(self.defaults['tscube']) schema.add_option('make_plots', True) schema.add_option('write_fits', True) schema.add_option('write_npy', True) config = schema.create_config(self.config['tscube'], **kwargs) maps = self._make_ts_cube(prefix, **config) if config['make_plots']: plotter = plotting.AnalysisPlotter(self.config['plotting'], fileio=self.config['fileio'], logging=self.config['logging']) plotter.make_tsmap_plots(maps, self.roi, suffix='tscube') self.logger.info("Finished TS cube") return maps
python
def tscube(self, prefix='', **kwargs): """Generate a spatial TS map for a source component with properties defined by the `model` argument. This method uses the `gttscube` ST application for source fitting and will simultaneously fit the test source normalization as well as the normalizations of any background components that are currently free. The output of this method is a dictionary containing `~fermipy.skymap.Map` objects with the TS and amplitude of the best-fit test source. By default this method will also save maps to FITS files and render them as image files. Parameters ---------- prefix : str Optional string that will be prepended to all output files (FITS and rendered images). model : dict Dictionary defining the properties of the test source. do_sed : bool Compute the energy bin-by-bin fits. nnorm : int Number of points in the likelihood v. normalization scan. norm_sigma : float Number of sigma to use for the scan range. tol : float Critetia for fit convergence (estimated vertical distance to min < tol ). tol_type : int Absoulte (0) or relative (1) criteria for convergence. max_iter : int Maximum number of iterations for the Newton's method fitter remake_test_source : bool If true, recomputes the test source image (otherwise just shifts it) st_scan_level : int make_plots : bool Write image files. write_fits : bool Write a FITS file with the results of the analysis. Returns ------- maps : dict A dictionary containing the `~fermipy.skymap.Map` objects for TS and source amplitude. """ self.logger.info('Generating TS cube') schema = ConfigSchema(self.defaults['tscube']) schema.add_option('make_plots', True) schema.add_option('write_fits', True) schema.add_option('write_npy', True) config = schema.create_config(self.config['tscube'], **kwargs) maps = self._make_ts_cube(prefix, **config) if config['make_plots']: plotter = plotting.AnalysisPlotter(self.config['plotting'], fileio=self.config['fileio'], logging=self.config['logging']) plotter.make_tsmap_plots(maps, self.roi, suffix='tscube') self.logger.info("Finished TS cube") return maps
[ "def", "tscube", "(", "self", ",", "prefix", "=", "''", ",", "*", "*", "kwargs", ")", ":", "self", ".", "logger", ".", "info", "(", "'Generating TS cube'", ")", "schema", "=", "ConfigSchema", "(", "self", ".", "defaults", "[", "'tscube'", "]", ")", "...
Generate a spatial TS map for a source component with properties defined by the `model` argument. This method uses the `gttscube` ST application for source fitting and will simultaneously fit the test source normalization as well as the normalizations of any background components that are currently free. The output of this method is a dictionary containing `~fermipy.skymap.Map` objects with the TS and amplitude of the best-fit test source. By default this method will also save maps to FITS files and render them as image files. Parameters ---------- prefix : str Optional string that will be prepended to all output files (FITS and rendered images). model : dict Dictionary defining the properties of the test source. do_sed : bool Compute the energy bin-by-bin fits. nnorm : int Number of points in the likelihood v. normalization scan. norm_sigma : float Number of sigma to use for the scan range. tol : float Critetia for fit convergence (estimated vertical distance to min < tol ). tol_type : int Absoulte (0) or relative (1) criteria for convergence. max_iter : int Maximum number of iterations for the Newton's method fitter remake_test_source : bool If true, recomputes the test source image (otherwise just shifts it) st_scan_level : int make_plots : bool Write image files. write_fits : bool Write a FITS file with the results of the analysis. Returns ------- maps : dict A dictionary containing the `~fermipy.skymap.Map` objects for TS and source amplitude.
[ "Generate", "a", "spatial", "TS", "map", "for", "a", "source", "component", "with", "properties", "defined", "by", "the", "model", "argument", ".", "This", "method", "uses", "the", "gttscube", "ST", "application", "for", "source", "fitting", "and", "will", "...
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/tsmap.py#L945-L1024
train
35,915
fermiPy/fermipy
fermipy/irfs.py
compute_ps_counts
def compute_ps_counts(ebins, exp, psf, bkg, fn, egy_dim=0, spatial_model='PointSource', spatial_size=1E-3): """Calculate the observed signal and background counts given models for the exposure, background intensity, PSF, and source flux. Parameters ---------- ebins : `~numpy.ndarray` Array of energy bin edges. exp : `~numpy.ndarray` Model for exposure. psf : `~fermipy.irfs.PSFModel` Model for average PSF. bkg : `~numpy.ndarray` Array of background intensities. fn : `~fermipy.spectrum.SpectralFunction` egy_dim : int Index of energy dimension in ``bkg`` and ``exp`` arrays. """ ewidth = utils.edge_to_width(ebins) ectr = np.exp(utils.edge_to_center(np.log(ebins))) r68 = psf.containment_angle(ectr, fraction=0.68) if spatial_model != 'PointSource': r68[r68 < spatial_size] = spatial_size # * np.ones((len(ectr), 31)) theta_edges = np.linspace(0.0, 3.0, 31)[np.newaxis, :] theta_edges = theta_edges * r68[:, np.newaxis] theta = 0.5 * (theta_edges[:, :-1] + theta_edges[:, 1:]) domega = np.pi * (theta_edges[:, 1:]**2 - theta_edges[:, :-1]**2) if spatial_model == 'PointSource': sig_pdf = domega * psf.interp(ectr[:, np.newaxis], theta) elif spatial_model == 'RadialGaussian': sig_pdf = domega * utils.convolve2d_gauss(lambda t: psf.interp(ectr[:, np.newaxis, np.newaxis], t), theta, spatial_size / 1.5095921854516636, nstep=2000) elif spatial_model == 'RadialDisk': sig_pdf = domega * utils.convolve2d_disk(lambda t: psf.interp(ectr[:, np.newaxis, np.newaxis], t), theta, spatial_size / 0.8246211251235321) else: raise ValueError('Invalid spatial model: {}'.format(spatial_model)) sig_pdf *= (np.pi / 180.)**2 sig_flux = fn.flux(ebins[:-1], ebins[1:]) # Background and signal counts bkgc = bkg[..., np.newaxis] * domega * exp[..., np.newaxis] * \ ewidth[..., np.newaxis] * (np.pi / 180.)**2 sigc = sig_pdf * sig_flux[..., np.newaxis] * exp[..., np.newaxis] return sigc, bkgc
python
def compute_ps_counts(ebins, exp, psf, bkg, fn, egy_dim=0, spatial_model='PointSource', spatial_size=1E-3): """Calculate the observed signal and background counts given models for the exposure, background intensity, PSF, and source flux. Parameters ---------- ebins : `~numpy.ndarray` Array of energy bin edges. exp : `~numpy.ndarray` Model for exposure. psf : `~fermipy.irfs.PSFModel` Model for average PSF. bkg : `~numpy.ndarray` Array of background intensities. fn : `~fermipy.spectrum.SpectralFunction` egy_dim : int Index of energy dimension in ``bkg`` and ``exp`` arrays. """ ewidth = utils.edge_to_width(ebins) ectr = np.exp(utils.edge_to_center(np.log(ebins))) r68 = psf.containment_angle(ectr, fraction=0.68) if spatial_model != 'PointSource': r68[r68 < spatial_size] = spatial_size # * np.ones((len(ectr), 31)) theta_edges = np.linspace(0.0, 3.0, 31)[np.newaxis, :] theta_edges = theta_edges * r68[:, np.newaxis] theta = 0.5 * (theta_edges[:, :-1] + theta_edges[:, 1:]) domega = np.pi * (theta_edges[:, 1:]**2 - theta_edges[:, :-1]**2) if spatial_model == 'PointSource': sig_pdf = domega * psf.interp(ectr[:, np.newaxis], theta) elif spatial_model == 'RadialGaussian': sig_pdf = domega * utils.convolve2d_gauss(lambda t: psf.interp(ectr[:, np.newaxis, np.newaxis], t), theta, spatial_size / 1.5095921854516636, nstep=2000) elif spatial_model == 'RadialDisk': sig_pdf = domega * utils.convolve2d_disk(lambda t: psf.interp(ectr[:, np.newaxis, np.newaxis], t), theta, spatial_size / 0.8246211251235321) else: raise ValueError('Invalid spatial model: {}'.format(spatial_model)) sig_pdf *= (np.pi / 180.)**2 sig_flux = fn.flux(ebins[:-1], ebins[1:]) # Background and signal counts bkgc = bkg[..., np.newaxis] * domega * exp[..., np.newaxis] * \ ewidth[..., np.newaxis] * (np.pi / 180.)**2 sigc = sig_pdf * sig_flux[..., np.newaxis] * exp[..., np.newaxis] return sigc, bkgc
[ "def", "compute_ps_counts", "(", "ebins", ",", "exp", ",", "psf", ",", "bkg", ",", "fn", ",", "egy_dim", "=", "0", ",", "spatial_model", "=", "'PointSource'", ",", "spatial_size", "=", "1E-3", ")", ":", "ewidth", "=", "utils", ".", "edge_to_width", "(", ...
Calculate the observed signal and background counts given models for the exposure, background intensity, PSF, and source flux. Parameters ---------- ebins : `~numpy.ndarray` Array of energy bin edges. exp : `~numpy.ndarray` Model for exposure. psf : `~fermipy.irfs.PSFModel` Model for average PSF. bkg : `~numpy.ndarray` Array of background intensities. fn : `~fermipy.spectrum.SpectralFunction` egy_dim : int Index of energy dimension in ``bkg`` and ``exp`` arrays.
[ "Calculate", "the", "observed", "signal", "and", "background", "counts", "given", "models", "for", "the", "exposure", "background", "intensity", "PSF", "and", "source", "flux", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L100-L157
train
35,916
fermiPy/fermipy
fermipy/irfs.py
create_psf
def create_psf(event_class, event_type, dtheta, egy, cth): """Create an array of PSF response values versus energy and inclination angle. Parameters ---------- egy : `~numpy.ndarray` Energy in MeV. cth : `~numpy.ndarray` Cosine of the incidence angle. """ irf = create_irf(event_class, event_type) theta = np.degrees(np.arccos(cth)) m = np.zeros((len(dtheta), len(egy), len(cth))) for i, x in enumerate(egy): for j, y in enumerate(theta): m[:, i, j] = irf.psf().value(dtheta, x, y, 0.0) return m
python
def create_psf(event_class, event_type, dtheta, egy, cth): """Create an array of PSF response values versus energy and inclination angle. Parameters ---------- egy : `~numpy.ndarray` Energy in MeV. cth : `~numpy.ndarray` Cosine of the incidence angle. """ irf = create_irf(event_class, event_type) theta = np.degrees(np.arccos(cth)) m = np.zeros((len(dtheta), len(egy), len(cth))) for i, x in enumerate(egy): for j, y in enumerate(theta): m[:, i, j] = irf.psf().value(dtheta, x, y, 0.0) return m
[ "def", "create_psf", "(", "event_class", ",", "event_type", ",", "dtheta", ",", "egy", ",", "cth", ")", ":", "irf", "=", "create_irf", "(", "event_class", ",", "event_type", ")", "theta", "=", "np", ".", "degrees", "(", "np", ".", "arccos", "(", "cth",...
Create an array of PSF response values versus energy and inclination angle. Parameters ---------- egy : `~numpy.ndarray` Energy in MeV. cth : `~numpy.ndarray` Cosine of the incidence angle.
[ "Create", "an", "array", "of", "PSF", "response", "values", "versus", "energy", "and", "inclination", "angle", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L583-L604
train
35,917
fermiPy/fermipy
fermipy/irfs.py
create_edisp
def create_edisp(event_class, event_type, erec, egy, cth): """Create an array of energy response values versus energy and inclination angle. Parameters ---------- egy : `~numpy.ndarray` Energy in MeV. cth : `~numpy.ndarray` Cosine of the incidence angle. """ irf = create_irf(event_class, event_type) theta = np.degrees(np.arccos(cth)) v = np.zeros((len(erec), len(egy), len(cth))) m = (erec[:,None] / egy[None,:] < 3.0) & (erec[:,None] / egy[None,:] > 0.33333) # m |= ((erec[:,None] / egy[None,:] < 3.0) & # (erec[:,None] / egy[None,:] > 0.5) & (egy[None,:] < 10**2.5)) m = np.broadcast_to(m[:,:,None], v.shape) try: x = np.ones(v.shape)*erec[:,None,None] y = np.ones(v.shape)*egy[None,:,None] z = np.ones(v.shape)*theta[None,None,:] v[m] = irf.edisp().value(np.ravel(x[m]), np.ravel(y[m]), np.ravel(z[m]), 0.0) except: for i, x in enumerate(egy): for j, y in enumerate(theta): m = (erec / x < 3.0) & (erec / x > 0.333) v[m, i, j] = irf.edisp().value(erec[m], x, y, 0.0) return v
python
def create_edisp(event_class, event_type, erec, egy, cth): """Create an array of energy response values versus energy and inclination angle. Parameters ---------- egy : `~numpy.ndarray` Energy in MeV. cth : `~numpy.ndarray` Cosine of the incidence angle. """ irf = create_irf(event_class, event_type) theta = np.degrees(np.arccos(cth)) v = np.zeros((len(erec), len(egy), len(cth))) m = (erec[:,None] / egy[None,:] < 3.0) & (erec[:,None] / egy[None,:] > 0.33333) # m |= ((erec[:,None] / egy[None,:] < 3.0) & # (erec[:,None] / egy[None,:] > 0.5) & (egy[None,:] < 10**2.5)) m = np.broadcast_to(m[:,:,None], v.shape) try: x = np.ones(v.shape)*erec[:,None,None] y = np.ones(v.shape)*egy[None,:,None] z = np.ones(v.shape)*theta[None,None,:] v[m] = irf.edisp().value(np.ravel(x[m]), np.ravel(y[m]), np.ravel(z[m]), 0.0) except: for i, x in enumerate(egy): for j, y in enumerate(theta): m = (erec / x < 3.0) & (erec / x > 0.333) v[m, i, j] = irf.edisp().value(erec[m], x, y, 0.0) return v
[ "def", "create_edisp", "(", "event_class", ",", "event_type", ",", "erec", ",", "egy", ",", "cth", ")", ":", "irf", "=", "create_irf", "(", "event_class", ",", "event_type", ")", "theta", "=", "np", ".", "degrees", "(", "np", ".", "arccos", "(", "cth",...
Create an array of energy response values versus energy and inclination angle. Parameters ---------- egy : `~numpy.ndarray` Energy in MeV. cth : `~numpy.ndarray` Cosine of the incidence angle.
[ "Create", "an", "array", "of", "energy", "response", "values", "versus", "energy", "and", "inclination", "angle", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L607-L639
train
35,918
fermiPy/fermipy
fermipy/irfs.py
create_aeff
def create_aeff(event_class, event_type, egy, cth): """Create an array of effective areas versus energy and incidence angle. Binning in energy and incidence angle is controlled with the egy and cth input parameters. Parameters ---------- event_class : str Event class string (e.g. P8R2_SOURCE_V6). event_type : list egy : array_like Evaluation points in energy (MeV). cth : array_like Evaluation points in cosine of the incidence angle. """ irf = create_irf(event_class, event_type) irf.aeff().setPhiDependence(False) theta = np.degrees(np.arccos(cth)) # Exposure Matrix # Dimensions are Etrue and incidence angle m = np.zeros((len(egy), len(cth))) for i, x in enumerate(egy): for j, y in enumerate(theta): m[i, j] = irf.aeff().value(x, y, 0.0) return m
python
def create_aeff(event_class, event_type, egy, cth): """Create an array of effective areas versus energy and incidence angle. Binning in energy and incidence angle is controlled with the egy and cth input parameters. Parameters ---------- event_class : str Event class string (e.g. P8R2_SOURCE_V6). event_type : list egy : array_like Evaluation points in energy (MeV). cth : array_like Evaluation points in cosine of the incidence angle. """ irf = create_irf(event_class, event_type) irf.aeff().setPhiDependence(False) theta = np.degrees(np.arccos(cth)) # Exposure Matrix # Dimensions are Etrue and incidence angle m = np.zeros((len(egy), len(cth))) for i, x in enumerate(egy): for j, y in enumerate(theta): m[i, j] = irf.aeff().value(x, y, 0.0) return m
[ "def", "create_aeff", "(", "event_class", ",", "event_type", ",", "egy", ",", "cth", ")", ":", "irf", "=", "create_irf", "(", "event_class", ",", "event_type", ")", "irf", ".", "aeff", "(", ")", ".", "setPhiDependence", "(", "False", ")", "theta", "=", ...
Create an array of effective areas versus energy and incidence angle. Binning in energy and incidence angle is controlled with the egy and cth input parameters. Parameters ---------- event_class : str Event class string (e.g. P8R2_SOURCE_V6). event_type : list egy : array_like Evaluation points in energy (MeV). cth : array_like Evaluation points in cosine of the incidence angle.
[ "Create", "an", "array", "of", "effective", "areas", "versus", "energy", "and", "incidence", "angle", ".", "Binning", "in", "energy", "and", "incidence", "angle", "is", "controlled", "with", "the", "egy", "and", "cth", "input", "parameters", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L642-L673
train
35,919
fermiPy/fermipy
fermipy/irfs.py
calc_exp
def calc_exp(skydir, ltc, event_class, event_types, egy, cth_bins, npts=None): """Calculate the exposure on a 2D grid of energy and incidence angle. Parameters ---------- npts : int Number of points by which to sample the response in each incidence angle bin. If None then npts will be automatically set such that incidence angle is sampled on intervals of < 0.05 in Cos(Theta). Returns ------- exp : `~numpy.ndarray` 2D Array of exposures vs. energy and incidence angle. """ if npts is None: npts = int(np.ceil(np.max(cth_bins[1:] - cth_bins[:-1]) / 0.025)) exp = np.zeros((len(egy), len(cth_bins) - 1)) cth_bins = utils.split_bin_edges(cth_bins, npts) cth = edge_to_center(cth_bins) ltw = ltc.get_skydir_lthist(skydir, cth_bins).reshape(-1, npts) for et in event_types: aeff = create_aeff(event_class, et, egy, cth) aeff = aeff.reshape(exp.shape + (npts,)) exp += np.sum(aeff * ltw[np.newaxis, :, :], axis=-1) return exp
python
def calc_exp(skydir, ltc, event_class, event_types, egy, cth_bins, npts=None): """Calculate the exposure on a 2D grid of energy and incidence angle. Parameters ---------- npts : int Number of points by which to sample the response in each incidence angle bin. If None then npts will be automatically set such that incidence angle is sampled on intervals of < 0.05 in Cos(Theta). Returns ------- exp : `~numpy.ndarray` 2D Array of exposures vs. energy and incidence angle. """ if npts is None: npts = int(np.ceil(np.max(cth_bins[1:] - cth_bins[:-1]) / 0.025)) exp = np.zeros((len(egy), len(cth_bins) - 1)) cth_bins = utils.split_bin_edges(cth_bins, npts) cth = edge_to_center(cth_bins) ltw = ltc.get_skydir_lthist(skydir, cth_bins).reshape(-1, npts) for et in event_types: aeff = create_aeff(event_class, et, egy, cth) aeff = aeff.reshape(exp.shape + (npts,)) exp += np.sum(aeff * ltw[np.newaxis, :, :], axis=-1) return exp
[ "def", "calc_exp", "(", "skydir", ",", "ltc", ",", "event_class", ",", "event_types", ",", "egy", ",", "cth_bins", ",", "npts", "=", "None", ")", ":", "if", "npts", "is", "None", ":", "npts", "=", "int", "(", "np", ".", "ceil", "(", "np", ".", "m...
Calculate the exposure on a 2D grid of energy and incidence angle. Parameters ---------- npts : int Number of points by which to sample the response in each incidence angle bin. If None then npts will be automatically set such that incidence angle is sampled on intervals of < 0.05 in Cos(Theta). Returns ------- exp : `~numpy.ndarray` 2D Array of exposures vs. energy and incidence angle.
[ "Calculate", "the", "exposure", "on", "a", "2D", "grid", "of", "energy", "and", "incidence", "angle", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L676-L707
train
35,920
fermiPy/fermipy
fermipy/irfs.py
create_avg_rsp
def create_avg_rsp(rsp_fn, skydir, ltc, event_class, event_types, x, egy, cth_bins, npts=None): """Calculate the weighted response function. """ if npts is None: npts = int(np.ceil(np.max(cth_bins[1:] - cth_bins[:-1]) / 0.05)) wrsp = np.zeros((len(x), len(egy), len(cth_bins) - 1)) exps = np.zeros((len(egy), len(cth_bins) - 1)) cth_bins = utils.split_bin_edges(cth_bins, npts) cth = edge_to_center(cth_bins) ltw = ltc.get_skydir_lthist(skydir, cth_bins) ltw = ltw.reshape(-1, npts) for et in event_types: rsp = rsp_fn(event_class, et, x, egy, cth) aeff = create_aeff(event_class, et, egy, cth) rsp = rsp.reshape(wrsp.shape + (npts,)) aeff = aeff.reshape(exps.shape + (npts,)) wrsp += np.sum(rsp * aeff[np.newaxis, :, :, :] * ltw[np.newaxis, np.newaxis, :, :], axis=-1) exps += np.sum(aeff * ltw[np.newaxis, :, :], axis=-1) exps_inv = np.zeros_like(exps) exps_inv[exps > 0] = 1./exps[exps>0] wrsp *= exps_inv[np.newaxis, :, :] return wrsp
python
def create_avg_rsp(rsp_fn, skydir, ltc, event_class, event_types, x, egy, cth_bins, npts=None): """Calculate the weighted response function. """ if npts is None: npts = int(np.ceil(np.max(cth_bins[1:] - cth_bins[:-1]) / 0.05)) wrsp = np.zeros((len(x), len(egy), len(cth_bins) - 1)) exps = np.zeros((len(egy), len(cth_bins) - 1)) cth_bins = utils.split_bin_edges(cth_bins, npts) cth = edge_to_center(cth_bins) ltw = ltc.get_skydir_lthist(skydir, cth_bins) ltw = ltw.reshape(-1, npts) for et in event_types: rsp = rsp_fn(event_class, et, x, egy, cth) aeff = create_aeff(event_class, et, egy, cth) rsp = rsp.reshape(wrsp.shape + (npts,)) aeff = aeff.reshape(exps.shape + (npts,)) wrsp += np.sum(rsp * aeff[np.newaxis, :, :, :] * ltw[np.newaxis, np.newaxis, :, :], axis=-1) exps += np.sum(aeff * ltw[np.newaxis, :, :], axis=-1) exps_inv = np.zeros_like(exps) exps_inv[exps > 0] = 1./exps[exps>0] wrsp *= exps_inv[np.newaxis, :, :] return wrsp
[ "def", "create_avg_rsp", "(", "rsp_fn", ",", "skydir", ",", "ltc", ",", "event_class", ",", "event_types", ",", "x", ",", "egy", ",", "cth_bins", ",", "npts", "=", "None", ")", ":", "if", "npts", "is", "None", ":", "npts", "=", "int", "(", "np", "....
Calculate the weighted response function.
[ "Calculate", "the", "weighted", "response", "function", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L710-L737
train
35,921
fermiPy/fermipy
fermipy/irfs.py
create_avg_psf
def create_avg_psf(skydir, ltc, event_class, event_types, dtheta, egy, cth_bins, npts=None): """Generate model for exposure-weighted PSF averaged over incidence angle. Parameters ---------- egy : `~numpy.ndarray` Energies in MeV. cth_bins : `~numpy.ndarray` Bin edges in cosine of the incidence angle. """ return create_avg_rsp(create_psf, skydir, ltc, event_class, event_types, dtheta, egy, cth_bins, npts)
python
def create_avg_psf(skydir, ltc, event_class, event_types, dtheta, egy, cth_bins, npts=None): """Generate model for exposure-weighted PSF averaged over incidence angle. Parameters ---------- egy : `~numpy.ndarray` Energies in MeV. cth_bins : `~numpy.ndarray` Bin edges in cosine of the incidence angle. """ return create_avg_rsp(create_psf, skydir, ltc, event_class, event_types, dtheta, egy, cth_bins, npts)
[ "def", "create_avg_psf", "(", "skydir", ",", "ltc", ",", "event_class", ",", "event_types", ",", "dtheta", ",", "egy", ",", "cth_bins", ",", "npts", "=", "None", ")", ":", "return", "create_avg_rsp", "(", "create_psf", ",", "skydir", ",", "ltc", ",", "ev...
Generate model for exposure-weighted PSF averaged over incidence angle. Parameters ---------- egy : `~numpy.ndarray` Energies in MeV. cth_bins : `~numpy.ndarray` Bin edges in cosine of the incidence angle.
[ "Generate", "model", "for", "exposure", "-", "weighted", "PSF", "averaged", "over", "incidence", "angle", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L740-L756
train
35,922
fermiPy/fermipy
fermipy/irfs.py
create_avg_edisp
def create_avg_edisp(skydir, ltc, event_class, event_types, erec, egy, cth_bins, npts=None): """Generate model for exposure-weighted DRM averaged over incidence angle. Parameters ---------- egy : `~numpy.ndarray` True energies in MeV. cth_bins : `~numpy.ndarray` Bin edges in cosine of the incidence angle. """ return create_avg_rsp(create_edisp, skydir, ltc, event_class, event_types, erec, egy, cth_bins, npts)
python
def create_avg_edisp(skydir, ltc, event_class, event_types, erec, egy, cth_bins, npts=None): """Generate model for exposure-weighted DRM averaged over incidence angle. Parameters ---------- egy : `~numpy.ndarray` True energies in MeV. cth_bins : `~numpy.ndarray` Bin edges in cosine of the incidence angle. """ return create_avg_rsp(create_edisp, skydir, ltc, event_class, event_types, erec, egy, cth_bins, npts)
[ "def", "create_avg_edisp", "(", "skydir", ",", "ltc", ",", "event_class", ",", "event_types", ",", "erec", ",", "egy", ",", "cth_bins", ",", "npts", "=", "None", ")", ":", "return", "create_avg_rsp", "(", "create_edisp", ",", "skydir", ",", "ltc", ",", "...
Generate model for exposure-weighted DRM averaged over incidence angle. Parameters ---------- egy : `~numpy.ndarray` True energies in MeV. cth_bins : `~numpy.ndarray` Bin edges in cosine of the incidence angle.
[ "Generate", "model", "for", "exposure", "-", "weighted", "DRM", "averaged", "over", "incidence", "angle", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L759-L774
train
35,923
fermiPy/fermipy
fermipy/irfs.py
create_wtd_psf
def create_wtd_psf(skydir, ltc, event_class, event_types, dtheta, egy_bins, cth_bins, fn, nbin=64, npts=1): """Create an exposure- and dispersion-weighted PSF model for a source with spectral parameterization ``fn``. The calculation performed by this method accounts for the influence of energy dispersion on the PSF. Parameters ---------- dtheta : `~numpy.ndarray` egy_bins : `~numpy.ndarray` Bin edges in observed energy. cth_bins : `~numpy.ndarray` Bin edges in cosine of the true incidence angle. nbin : int Number of bins per decade in true energy. npts : int Number of points by which to oversample each energy bin. """ #npts = int(np.ceil(32. / bins_per_dec(egy_bins))) egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts)) etrue_bins = 10**np.linspace(1.0, 6.5, nbin * 5.5 + 1) etrue = 10**utils.edge_to_center(np.log10(etrue_bins)) psf = create_avg_psf(skydir, ltc, event_class, event_types, dtheta, etrue, cth_bins) drm = calc_drm(skydir, ltc, event_class, event_types, egy_bins, cth_bins, nbin=nbin) cnts = calc_counts(skydir, ltc, event_class, event_types, etrue_bins, cth_bins, fn) wts = drm * cnts[None, :, :] wts_norm = np.sum(wts, axis=1) wts_norm[wts_norm == 0] = 1.0 wts = wts / wts_norm[:, None, :] wpsf = np.sum(wts[None, :, :, :] * psf[:, None, :, :], axis=2) wts = np.sum(wts[None, :, :, :], axis=2) if npts > 1: shape = (wpsf.shape[0], int(wpsf.shape[1] / npts), npts, wpsf.shape[2]) wpsf = np.sum((wpsf * wts).reshape(shape), axis=2) shape = (wts.shape[0], int(wts.shape[1] / npts), npts, wts.shape[2]) wpsf = wpsf / np.sum(wts.reshape(shape), axis=2) return wpsf
python
def create_wtd_psf(skydir, ltc, event_class, event_types, dtheta, egy_bins, cth_bins, fn, nbin=64, npts=1): """Create an exposure- and dispersion-weighted PSF model for a source with spectral parameterization ``fn``. The calculation performed by this method accounts for the influence of energy dispersion on the PSF. Parameters ---------- dtheta : `~numpy.ndarray` egy_bins : `~numpy.ndarray` Bin edges in observed energy. cth_bins : `~numpy.ndarray` Bin edges in cosine of the true incidence angle. nbin : int Number of bins per decade in true energy. npts : int Number of points by which to oversample each energy bin. """ #npts = int(np.ceil(32. / bins_per_dec(egy_bins))) egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts)) etrue_bins = 10**np.linspace(1.0, 6.5, nbin * 5.5 + 1) etrue = 10**utils.edge_to_center(np.log10(etrue_bins)) psf = create_avg_psf(skydir, ltc, event_class, event_types, dtheta, etrue, cth_bins) drm = calc_drm(skydir, ltc, event_class, event_types, egy_bins, cth_bins, nbin=nbin) cnts = calc_counts(skydir, ltc, event_class, event_types, etrue_bins, cth_bins, fn) wts = drm * cnts[None, :, :] wts_norm = np.sum(wts, axis=1) wts_norm[wts_norm == 0] = 1.0 wts = wts / wts_norm[:, None, :] wpsf = np.sum(wts[None, :, :, :] * psf[:, None, :, :], axis=2) wts = np.sum(wts[None, :, :, :], axis=2) if npts > 1: shape = (wpsf.shape[0], int(wpsf.shape[1] / npts), npts, wpsf.shape[2]) wpsf = np.sum((wpsf * wts).reshape(shape), axis=2) shape = (wts.shape[0], int(wts.shape[1] / npts), npts, wts.shape[2]) wpsf = wpsf / np.sum(wts.reshape(shape), axis=2) return wpsf
[ "def", "create_wtd_psf", "(", "skydir", ",", "ltc", ",", "event_class", ",", "event_types", ",", "dtheta", ",", "egy_bins", ",", "cth_bins", ",", "fn", ",", "nbin", "=", "64", ",", "npts", "=", "1", ")", ":", "#npts = int(np.ceil(32. / bins_per_dec(egy_bins)))...
Create an exposure- and dispersion-weighted PSF model for a source with spectral parameterization ``fn``. The calculation performed by this method accounts for the influence of energy dispersion on the PSF. Parameters ---------- dtheta : `~numpy.ndarray` egy_bins : `~numpy.ndarray` Bin edges in observed energy. cth_bins : `~numpy.ndarray` Bin edges in cosine of the true incidence angle. nbin : int Number of bins per decade in true energy. npts : int Number of points by which to oversample each energy bin.
[ "Create", "an", "exposure", "-", "and", "dispersion", "-", "weighted", "PSF", "model", "for", "a", "source", "with", "spectral", "parameterization", "fn", ".", "The", "calculation", "performed", "by", "this", "method", "accounts", "for", "the", "influence", "o...
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L777-L826
train
35,924
fermiPy/fermipy
fermipy/irfs.py
calc_drm
def calc_drm(skydir, ltc, event_class, event_types, egy_bins, cth_bins, nbin=64): """Calculate the detector response matrix.""" npts = int(np.ceil(128. / bins_per_dec(egy_bins))) egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts)) etrue_bins = 10**np.linspace(1.0, 6.5, nbin * 5.5 + 1) egy = 10**utils.edge_to_center(np.log10(egy_bins)) egy_width = utils.edge_to_width(egy_bins) etrue = 10**utils.edge_to_center(np.log10(etrue_bins)) edisp = create_avg_edisp(skydir, ltc, event_class, event_types, egy, etrue, cth_bins) edisp = edisp * egy_width[:, None, None] edisp = sum_bins(edisp, 0, npts) return edisp
python
def calc_drm(skydir, ltc, event_class, event_types, egy_bins, cth_bins, nbin=64): """Calculate the detector response matrix.""" npts = int(np.ceil(128. / bins_per_dec(egy_bins))) egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts)) etrue_bins = 10**np.linspace(1.0, 6.5, nbin * 5.5 + 1) egy = 10**utils.edge_to_center(np.log10(egy_bins)) egy_width = utils.edge_to_width(egy_bins) etrue = 10**utils.edge_to_center(np.log10(etrue_bins)) edisp = create_avg_edisp(skydir, ltc, event_class, event_types, egy, etrue, cth_bins) edisp = edisp * egy_width[:, None, None] edisp = sum_bins(edisp, 0, npts) return edisp
[ "def", "calc_drm", "(", "skydir", ",", "ltc", ",", "event_class", ",", "event_types", ",", "egy_bins", ",", "cth_bins", ",", "nbin", "=", "64", ")", ":", "npts", "=", "int", "(", "np", ".", "ceil", "(", "128.", "/", "bins_per_dec", "(", "egy_bins", "...
Calculate the detector response matrix.
[ "Calculate", "the", "detector", "response", "matrix", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L829-L843
train
35,925
fermiPy/fermipy
fermipy/irfs.py
calc_counts
def calc_counts(skydir, ltc, event_class, event_types, egy_bins, cth_bins, fn, npts=1): """Calculate the expected counts vs. true energy and incidence angle for a source with spectral parameterization ``fn``. Parameters ---------- skydir : `~astropy.coordinate.SkyCoord` ltc : `~fermipy.irfs.LTCube` egy_bins : `~numpy.ndarray` Bin edges in observed energy in MeV. cth_bins : `~numpy.ndarray` Bin edges in cosine of the true incidence angle. npts : int Number of points by which to oversample each energy bin. """ #npts = int(np.ceil(32. / bins_per_dec(egy_bins))) egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts)) exp = calc_exp(skydir, ltc, event_class, event_types, egy_bins, cth_bins) dnde = fn.dnde(egy_bins) cnts = loglog_quad(egy_bins, exp * dnde[:, None], 0) cnts = sum_bins(cnts, 0, npts) return cnts
python
def calc_counts(skydir, ltc, event_class, event_types, egy_bins, cth_bins, fn, npts=1): """Calculate the expected counts vs. true energy and incidence angle for a source with spectral parameterization ``fn``. Parameters ---------- skydir : `~astropy.coordinate.SkyCoord` ltc : `~fermipy.irfs.LTCube` egy_bins : `~numpy.ndarray` Bin edges in observed energy in MeV. cth_bins : `~numpy.ndarray` Bin edges in cosine of the true incidence angle. npts : int Number of points by which to oversample each energy bin. """ #npts = int(np.ceil(32. / bins_per_dec(egy_bins))) egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts)) exp = calc_exp(skydir, ltc, event_class, event_types, egy_bins, cth_bins) dnde = fn.dnde(egy_bins) cnts = loglog_quad(egy_bins, exp * dnde[:, None], 0) cnts = sum_bins(cnts, 0, npts) return cnts
[ "def", "calc_counts", "(", "skydir", ",", "ltc", ",", "event_class", ",", "event_types", ",", "egy_bins", ",", "cth_bins", ",", "fn", ",", "npts", "=", "1", ")", ":", "#npts = int(np.ceil(32. / bins_per_dec(egy_bins)))", "egy_bins", "=", "np", ".", "exp", "(",...
Calculate the expected counts vs. true energy and incidence angle for a source with spectral parameterization ``fn``. Parameters ---------- skydir : `~astropy.coordinate.SkyCoord` ltc : `~fermipy.irfs.LTCube` egy_bins : `~numpy.ndarray` Bin edges in observed energy in MeV. cth_bins : `~numpy.ndarray` Bin edges in cosine of the true incidence angle. npts : int Number of points by which to oversample each energy bin.
[ "Calculate", "the", "expected", "counts", "vs", ".", "true", "energy", "and", "incidence", "angle", "for", "a", "source", "with", "spectral", "parameterization", "fn", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L846-L873
train
35,926
fermiPy/fermipy
fermipy/irfs.py
calc_counts_edisp
def calc_counts_edisp(skydir, ltc, event_class, event_types, egy_bins, cth_bins, fn, nbin=16, npts=1): """Calculate the expected counts vs. observed energy and true incidence angle for a source with spectral parameterization ``fn``. Parameters ---------- skydir : `~astropy.coordinate.SkyCoord` ltc : `~fermipy.irfs.LTCube` egy_bins : `~numpy.ndarray` Bin edges in observed energy in MeV. cth_bins : `~numpy.ndarray` Bin edges in cosine of the true incidence angle. nbin : int Number of points per decade with which to sample true energy. npts : int Number of points by which to oversample each reconstructed energy bin. """ #npts = int(np.ceil(32. / bins_per_dec(egy_bins))) # Split energy bins egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts)) etrue_bins = 10**np.linspace(1.0, 6.5, nbin * 5.5 + 1) drm = calc_drm(skydir, ltc, event_class, event_types, egy_bins, cth_bins, nbin=nbin) cnts_etrue = calc_counts(skydir, ltc, event_class, event_types, etrue_bins, cth_bins, fn) cnts = np.sum(cnts_etrue[None, :, :] * drm[:, :, :], axis=1) cnts = sum_bins(cnts, 0, npts) return cnts
python
def calc_counts_edisp(skydir, ltc, event_class, event_types, egy_bins, cth_bins, fn, nbin=16, npts=1): """Calculate the expected counts vs. observed energy and true incidence angle for a source with spectral parameterization ``fn``. Parameters ---------- skydir : `~astropy.coordinate.SkyCoord` ltc : `~fermipy.irfs.LTCube` egy_bins : `~numpy.ndarray` Bin edges in observed energy in MeV. cth_bins : `~numpy.ndarray` Bin edges in cosine of the true incidence angle. nbin : int Number of points per decade with which to sample true energy. npts : int Number of points by which to oversample each reconstructed energy bin. """ #npts = int(np.ceil(32. / bins_per_dec(egy_bins))) # Split energy bins egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts)) etrue_bins = 10**np.linspace(1.0, 6.5, nbin * 5.5 + 1) drm = calc_drm(skydir, ltc, event_class, event_types, egy_bins, cth_bins, nbin=nbin) cnts_etrue = calc_counts(skydir, ltc, event_class, event_types, etrue_bins, cth_bins, fn) cnts = np.sum(cnts_etrue[None, :, :] * drm[:, :, :], axis=1) cnts = sum_bins(cnts, 0, npts) return cnts
[ "def", "calc_counts_edisp", "(", "skydir", ",", "ltc", ",", "event_class", ",", "event_types", ",", "egy_bins", ",", "cth_bins", ",", "fn", ",", "nbin", "=", "16", ",", "npts", "=", "1", ")", ":", "#npts = int(np.ceil(32. / bins_per_dec(egy_bins)))", "# Split en...
Calculate the expected counts vs. observed energy and true incidence angle for a source with spectral parameterization ``fn``. Parameters ---------- skydir : `~astropy.coordinate.SkyCoord` ltc : `~fermipy.irfs.LTCube` egy_bins : `~numpy.ndarray` Bin edges in observed energy in MeV. cth_bins : `~numpy.ndarray` Bin edges in cosine of the true incidence angle. nbin : int Number of points per decade with which to sample true energy. npts : int Number of points by which to oversample each reconstructed energy bin.
[ "Calculate", "the", "expected", "counts", "vs", ".", "observed", "energy", "and", "true", "incidence", "angle", "for", "a", "source", "with", "spectral", "parameterization", "fn", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L876-L912
train
35,927
fermiPy/fermipy
fermipy/irfs.py
calc_wtd_exp
def calc_wtd_exp(skydir, ltc, event_class, event_types, egy_bins, cth_bins, fn, nbin=16): """Calculate the effective exposure. Parameters ---------- skydir : `~astropy.coordinates.SkyCoord` ltc : `~fermipy.irfs.LTCube` nbin : int Number of points per decade with which to sample true energy. """ cnts = calc_counts_edisp(skydir, ltc, event_class, event_types, egy_bins, cth_bins, fn, nbin=nbin) flux = fn.flux(egy_bins[:-1], egy_bins[1:]) return cnts / flux[:, None]
python
def calc_wtd_exp(skydir, ltc, event_class, event_types, egy_bins, cth_bins, fn, nbin=16): """Calculate the effective exposure. Parameters ---------- skydir : `~astropy.coordinates.SkyCoord` ltc : `~fermipy.irfs.LTCube` nbin : int Number of points per decade with which to sample true energy. """ cnts = calc_counts_edisp(skydir, ltc, event_class, event_types, egy_bins, cth_bins, fn, nbin=nbin) flux = fn.flux(egy_bins[:-1], egy_bins[1:]) return cnts / flux[:, None]
[ "def", "calc_wtd_exp", "(", "skydir", ",", "ltc", ",", "event_class", ",", "event_types", ",", "egy_bins", ",", "cth_bins", ",", "fn", ",", "nbin", "=", "16", ")", ":", "cnts", "=", "calc_counts_edisp", "(", "skydir", ",", "ltc", ",", "event_class", ",",...
Calculate the effective exposure. Parameters ---------- skydir : `~astropy.coordinates.SkyCoord` ltc : `~fermipy.irfs.LTCube` nbin : int Number of points per decade with which to sample true energy.
[ "Calculate", "the", "effective", "exposure", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L915-L932
train
35,928
fermiPy/fermipy
fermipy/irfs.py
PSFModel.eval
def eval(self, ebin, dtheta, scale_fn=None): """Evaluate the PSF at the given energy bin index. Parameters ---------- ebin : int Index of energy bin. dtheta : array_like Array of angular separations in degrees. scale_fn : callable Function that evaluates the PSF scaling function. Argument is energy in MeV. """ if scale_fn is None and self.scale_fn is not None: scale_fn = self.scale_fn if scale_fn is None: scale_factor = 1.0 else: dtheta = dtheta / scale_fn(self.energies[ebin]) scale_factor = 1. / scale_fn(self.energies[ebin])**2 vals = 10**np.interp(dtheta, self.dtheta, np.log10(self.val[:, ebin])) return vals * scale_factor
python
def eval(self, ebin, dtheta, scale_fn=None): """Evaluate the PSF at the given energy bin index. Parameters ---------- ebin : int Index of energy bin. dtheta : array_like Array of angular separations in degrees. scale_fn : callable Function that evaluates the PSF scaling function. Argument is energy in MeV. """ if scale_fn is None and self.scale_fn is not None: scale_fn = self.scale_fn if scale_fn is None: scale_factor = 1.0 else: dtheta = dtheta / scale_fn(self.energies[ebin]) scale_factor = 1. / scale_fn(self.energies[ebin])**2 vals = 10**np.interp(dtheta, self.dtheta, np.log10(self.val[:, ebin])) return vals * scale_factor
[ "def", "eval", "(", "self", ",", "ebin", ",", "dtheta", ",", "scale_fn", "=", "None", ")", ":", "if", "scale_fn", "is", "None", "and", "self", ".", "scale_fn", "is", "not", "None", ":", "scale_fn", "=", "self", ".", "scale_fn", "if", "scale_fn", "is"...
Evaluate the PSF at the given energy bin index. Parameters ---------- ebin : int Index of energy bin. dtheta : array_like Array of angular separations in degrees. scale_fn : callable Function that evaluates the PSF scaling function. Argument is energy in MeV.
[ "Evaluate", "the", "PSF", "at", "the", "given", "energy", "bin", "index", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L359-L385
train
35,929
fermiPy/fermipy
fermipy/irfs.py
PSFModel.interp
def interp(self, energies, dtheta, scale_fn=None): """Evaluate the PSF model at an array of energies and angular separations. Parameters ---------- energies : array_like Array of energies in MeV. dtheta : array_like Array of angular separations in degrees. scale_fn : callable Function that evaluates the PSF scaling function. Argument is energy in MeV. """ if scale_fn is None and self.scale_fn: scale_fn = self.scale_fn log_energies = np.log10(energies) shape = (energies * dtheta).shape scale_factor = np.ones(shape) if scale_fn is not None: dtheta = dtheta / scale_fn(energies) scale_factor = 1. / scale_fn(energies)**2 vals = np.exp(self._psf_fn((dtheta, log_energies))) return vals * scale_factor
python
def interp(self, energies, dtheta, scale_fn=None): """Evaluate the PSF model at an array of energies and angular separations. Parameters ---------- energies : array_like Array of energies in MeV. dtheta : array_like Array of angular separations in degrees. scale_fn : callable Function that evaluates the PSF scaling function. Argument is energy in MeV. """ if scale_fn is None and self.scale_fn: scale_fn = self.scale_fn log_energies = np.log10(energies) shape = (energies * dtheta).shape scale_factor = np.ones(shape) if scale_fn is not None: dtheta = dtheta / scale_fn(energies) scale_factor = 1. / scale_fn(energies)**2 vals = np.exp(self._psf_fn((dtheta, log_energies))) return vals * scale_factor
[ "def", "interp", "(", "self", ",", "energies", ",", "dtheta", ",", "scale_fn", "=", "None", ")", ":", "if", "scale_fn", "is", "None", "and", "self", ".", "scale_fn", ":", "scale_fn", "=", "self", ".", "scale_fn", "log_energies", "=", "np", ".", "log10"...
Evaluate the PSF model at an array of energies and angular separations. Parameters ---------- energies : array_like Array of energies in MeV. dtheta : array_like Array of angular separations in degrees. scale_fn : callable Function that evaluates the PSF scaling function. Argument is energy in MeV.
[ "Evaluate", "the", "PSF", "model", "at", "an", "array", "of", "energies", "and", "angular", "separations", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L387-L417
train
35,930
fermiPy/fermipy
fermipy/irfs.py
PSFModel.interp_bin
def interp_bin(self, egy_bins, dtheta, scale_fn=None): """Evaluate the bin-averaged PSF model over the energy bins ``egy_bins``. Parameters ---------- egy_bins : array_like Energy bin edges in MeV. dtheta : array_like Array of angular separations in degrees. scale_fn : callable Function that evaluates the PSF scaling function. Argument is energy in MeV. """ npts = 4 egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts)) egy = np.exp(utils.edge_to_center(np.log(egy_bins))) log_energies = np.log10(egy) vals = self.interp(egy[None, :], dtheta[:, None], scale_fn=scale_fn) wts = np.exp(self._wts_fn((log_energies,))) wts = wts.reshape((1,) + wts.shape) vals = np.sum( (vals * wts).reshape((vals.shape[0], int(vals.shape[1] / npts), npts)), axis=2) vals /= np.sum(wts.reshape(wts.shape[0], int(wts.shape[1] / npts), npts), axis=2) return vals
python
def interp_bin(self, egy_bins, dtheta, scale_fn=None): """Evaluate the bin-averaged PSF model over the energy bins ``egy_bins``. Parameters ---------- egy_bins : array_like Energy bin edges in MeV. dtheta : array_like Array of angular separations in degrees. scale_fn : callable Function that evaluates the PSF scaling function. Argument is energy in MeV. """ npts = 4 egy_bins = np.exp(utils.split_bin_edges(np.log(egy_bins), npts)) egy = np.exp(utils.edge_to_center(np.log(egy_bins))) log_energies = np.log10(egy) vals = self.interp(egy[None, :], dtheta[:, None], scale_fn=scale_fn) wts = np.exp(self._wts_fn((log_energies,))) wts = wts.reshape((1,) + wts.shape) vals = np.sum( (vals * wts).reshape((vals.shape[0], int(vals.shape[1] / npts), npts)), axis=2) vals /= np.sum(wts.reshape(wts.shape[0], int(wts.shape[1] / npts), npts), axis=2) return vals
[ "def", "interp_bin", "(", "self", ",", "egy_bins", ",", "dtheta", ",", "scale_fn", "=", "None", ")", ":", "npts", "=", "4", "egy_bins", "=", "np", ".", "exp", "(", "utils", ".", "split_bin_edges", "(", "np", ".", "log", "(", "egy_bins", ")", ",", "...
Evaluate the bin-averaged PSF model over the energy bins ``egy_bins``. Parameters ---------- egy_bins : array_like Energy bin edges in MeV. dtheta : array_like Array of angular separations in degrees. scale_fn : callable Function that evaluates the PSF scaling function. Argument is energy in MeV.
[ "Evaluate", "the", "bin", "-", "averaged", "PSF", "model", "over", "the", "energy", "bins", "egy_bins", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L419-L448
train
35,931
fermiPy/fermipy
fermipy/irfs.py
PSFModel.containment_angle
def containment_angle(self, energies=None, fraction=0.68, scale_fn=None): """Evaluate the PSF containment angle at a sequence of energies.""" if energies is None: energies = self.energies vals = self.interp(energies[np.newaxis, :], self.dtheta[:, np.newaxis], scale_fn=scale_fn) dtheta = np.radians(self.dtheta[:, np.newaxis] * np.ones(vals.shape)) return self._calc_containment(dtheta, vals, fraction)
python
def containment_angle(self, energies=None, fraction=0.68, scale_fn=None): """Evaluate the PSF containment angle at a sequence of energies.""" if energies is None: energies = self.energies vals = self.interp(energies[np.newaxis, :], self.dtheta[:, np.newaxis], scale_fn=scale_fn) dtheta = np.radians(self.dtheta[:, np.newaxis] * np.ones(vals.shape)) return self._calc_containment(dtheta, vals, fraction)
[ "def", "containment_angle", "(", "self", ",", "energies", "=", "None", ",", "fraction", "=", "0.68", ",", "scale_fn", "=", "None", ")", ":", "if", "energies", "is", "None", ":", "energies", "=", "self", ".", "energies", "vals", "=", "self", ".", "inter...
Evaluate the PSF containment angle at a sequence of energies.
[ "Evaluate", "the", "PSF", "containment", "angle", "at", "a", "sequence", "of", "energies", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L450-L459
train
35,932
fermiPy/fermipy
fermipy/irfs.py
PSFModel.containment_angle_bin
def containment_angle_bin(self, egy_bins, fraction=0.68, scale_fn=None): """Evaluate the PSF containment angle averaged over energy bins.""" vals = self.interp_bin(egy_bins, self.dtheta, scale_fn=scale_fn) dtheta = np.radians(self.dtheta[:, np.newaxis] * np.ones(vals.shape)) return self._calc_containment(dtheta, vals, fraction)
python
def containment_angle_bin(self, egy_bins, fraction=0.68, scale_fn=None): """Evaluate the PSF containment angle averaged over energy bins.""" vals = self.interp_bin(egy_bins, self.dtheta, scale_fn=scale_fn) dtheta = np.radians(self.dtheta[:, np.newaxis] * np.ones(vals.shape)) return self._calc_containment(dtheta, vals, fraction)
[ "def", "containment_angle_bin", "(", "self", ",", "egy_bins", ",", "fraction", "=", "0.68", ",", "scale_fn", "=", "None", ")", ":", "vals", "=", "self", ".", "interp_bin", "(", "egy_bins", ",", "self", ".", "dtheta", ",", "scale_fn", "=", "scale_fn", ")"...
Evaluate the PSF containment angle averaged over energy bins.
[ "Evaluate", "the", "PSF", "containment", "angle", "averaged", "over", "energy", "bins", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L461-L466
train
35,933
fermiPy/fermipy
fermipy/irfs.py
PSFModel.create
def create(cls, skydir, ltc, event_class, event_types, energies, cth_bins=None, ndtheta=500, use_edisp=False, fn=None, nbin=64): """Create a PSFModel object. This class can be used to evaluate the exposure-weighted PSF for a source with a given observing profile and energy distribution. Parameters ---------- skydir : `~astropy.coordinates.SkyCoord` ltc : `~fermipy.irfs.LTCube` energies : `~numpy.ndarray` Grid of energies at which the PSF will be pre-computed. cth_bins : `~numpy.ndarray` Bin edges in cosine of the inclination angle. use_edisp : bool Generate the PSF model accounting for the influence of energy dispersion. fn : `~fermipy.spectrum.SpectralFunction` Model for the spectral energy distribution of the source. """ if isinstance(event_types, int): event_types = bitmask_to_bits(event_types) if fn is None: fn = spectrum.PowerLaw([1E-13, -2.0]) dtheta = np.logspace(-4, 1.75, ndtheta) dtheta = np.insert(dtheta, 0, [0]) log_energies = np.log10(energies) egy_bins = 10**utils.center_to_edge(log_energies) if cth_bins is None: cth_bins = np.array([0.2, 1.0]) if use_edisp: psf = create_wtd_psf(skydir, ltc, event_class, event_types, dtheta, egy_bins, cth_bins, fn, nbin=nbin) wts = calc_counts_edisp(skydir, ltc, event_class, event_types, egy_bins, cth_bins, fn, nbin=nbin) else: psf = create_avg_psf(skydir, ltc, event_class, event_types, dtheta, energies, cth_bins) wts = calc_counts(skydir, ltc, event_class, event_types, egy_bins, cth_bins, fn) exp = calc_exp(skydir, ltc, event_class, event_types, energies, cth_bins) return cls(dtheta, energies, cth_bins, np.squeeze(exp), np.squeeze(psf), np.squeeze(wts))
python
def create(cls, skydir, ltc, event_class, event_types, energies, cth_bins=None, ndtheta=500, use_edisp=False, fn=None, nbin=64): """Create a PSFModel object. This class can be used to evaluate the exposure-weighted PSF for a source with a given observing profile and energy distribution. Parameters ---------- skydir : `~astropy.coordinates.SkyCoord` ltc : `~fermipy.irfs.LTCube` energies : `~numpy.ndarray` Grid of energies at which the PSF will be pre-computed. cth_bins : `~numpy.ndarray` Bin edges in cosine of the inclination angle. use_edisp : bool Generate the PSF model accounting for the influence of energy dispersion. fn : `~fermipy.spectrum.SpectralFunction` Model for the spectral energy distribution of the source. """ if isinstance(event_types, int): event_types = bitmask_to_bits(event_types) if fn is None: fn = spectrum.PowerLaw([1E-13, -2.0]) dtheta = np.logspace(-4, 1.75, ndtheta) dtheta = np.insert(dtheta, 0, [0]) log_energies = np.log10(energies) egy_bins = 10**utils.center_to_edge(log_energies) if cth_bins is None: cth_bins = np.array([0.2, 1.0]) if use_edisp: psf = create_wtd_psf(skydir, ltc, event_class, event_types, dtheta, egy_bins, cth_bins, fn, nbin=nbin) wts = calc_counts_edisp(skydir, ltc, event_class, event_types, egy_bins, cth_bins, fn, nbin=nbin) else: psf = create_avg_psf(skydir, ltc, event_class, event_types, dtheta, energies, cth_bins) wts = calc_counts(skydir, ltc, event_class, event_types, egy_bins, cth_bins, fn) exp = calc_exp(skydir, ltc, event_class, event_types, energies, cth_bins) return cls(dtheta, energies, cth_bins, np.squeeze(exp), np.squeeze(psf), np.squeeze(wts))
[ "def", "create", "(", "cls", ",", "skydir", ",", "ltc", ",", "event_class", ",", "event_types", ",", "energies", ",", "cth_bins", "=", "None", ",", "ndtheta", "=", "500", ",", "use_edisp", "=", "False", ",", "fn", "=", "None", ",", "nbin", "=", "64",...
Create a PSFModel object. This class can be used to evaluate the exposure-weighted PSF for a source with a given observing profile and energy distribution. Parameters ---------- skydir : `~astropy.coordinates.SkyCoord` ltc : `~fermipy.irfs.LTCube` energies : `~numpy.ndarray` Grid of energies at which the PSF will be pre-computed. cth_bins : `~numpy.ndarray` Bin edges in cosine of the inclination angle. use_edisp : bool Generate the PSF model accounting for the influence of energy dispersion. fn : `~fermipy.spectrum.SpectralFunction` Model for the spectral energy distribution of the source.
[ "Create", "a", "PSFModel", "object", ".", "This", "class", "can", "be", "used", "to", "evaluate", "the", "exposure", "-", "weighted", "PSF", "for", "a", "source", "with", "a", "given", "observing", "profile", "and", "energy", "distribution", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/irfs.py#L514-L570
train
35,934
fermiPy/fermipy
fermipy/jobs/sys_interface.py
remove_file
def remove_file(filepath, dry_run=False): """Remove the file at filepath Catches exception if the file does not exist. If dry_run is True, print name of file to be removed, but do not remove it. """ if dry_run: sys.stdout.write("rm %s\n" % filepath) else: try: os.remove(filepath) except OSError: pass
python
def remove_file(filepath, dry_run=False): """Remove the file at filepath Catches exception if the file does not exist. If dry_run is True, print name of file to be removed, but do not remove it. """ if dry_run: sys.stdout.write("rm %s\n" % filepath) else: try: os.remove(filepath) except OSError: pass
[ "def", "remove_file", "(", "filepath", ",", "dry_run", "=", "False", ")", ":", "if", "dry_run", ":", "sys", ".", "stdout", ".", "write", "(", "\"rm %s\\n\"", "%", "filepath", ")", "else", ":", "try", ":", "os", ".", "remove", "(", "filepath", ")", "e...
Remove the file at filepath Catches exception if the file does not exist. If dry_run is True, print name of file to be removed, but do not remove it.
[ "Remove", "the", "file", "at", "filepath" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/sys_interface.py#L13-L26
train
35,935
fermiPy/fermipy
fermipy/jobs/sys_interface.py
clean_job
def clean_job(logfile, outfiles, dry_run=False): """Removes log file and files created by failed jobs. If dry_run is True, print name of files to be removed, but do not remove them. """ remove_file(logfile, dry_run) for outfile in outfiles.values(): remove_file(outfile, dry_run)
python
def clean_job(logfile, outfiles, dry_run=False): """Removes log file and files created by failed jobs. If dry_run is True, print name of files to be removed, but do not remove them. """ remove_file(logfile, dry_run) for outfile in outfiles.values(): remove_file(outfile, dry_run)
[ "def", "clean_job", "(", "logfile", ",", "outfiles", ",", "dry_run", "=", "False", ")", ":", "remove_file", "(", "logfile", ",", "dry_run", ")", "for", "outfile", "in", "outfiles", ".", "values", "(", ")", ":", "remove_file", "(", "outfile", ",", "dry_ru...
Removes log file and files created by failed jobs. If dry_run is True, print name of files to be removed, but do not remove them.
[ "Removes", "log", "file", "and", "files", "created", "by", "failed", "jobs", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/sys_interface.py#L29-L36
train
35,936
fermiPy/fermipy
fermipy/jobs/sys_interface.py
check_log
def check_log(logfile, exited='Exited with exit code', successful='Successfully completed'): """Check a log file to determine status of LSF job Often logfile doesn't exist because the job hasn't begun to run. It is unclear what you want to do in that case... Parameters ---------- logfile : str String with path to logfile exited : str Value to check for in existing logfile for exit with failure successful : str Value to check for in existing logfile for success Returns str, one of 'Pending', 'Running', 'Done', 'Failed' """ if not os.path.exists(logfile): return JobStatus.ready if exited in open(logfile).read(): return JobStatus.failed elif successful in open(logfile).read(): return JobStatus.done return JobStatus.running
python
def check_log(logfile, exited='Exited with exit code', successful='Successfully completed'): """Check a log file to determine status of LSF job Often logfile doesn't exist because the job hasn't begun to run. It is unclear what you want to do in that case... Parameters ---------- logfile : str String with path to logfile exited : str Value to check for in existing logfile for exit with failure successful : str Value to check for in existing logfile for success Returns str, one of 'Pending', 'Running', 'Done', 'Failed' """ if not os.path.exists(logfile): return JobStatus.ready if exited in open(logfile).read(): return JobStatus.failed elif successful in open(logfile).read(): return JobStatus.done return JobStatus.running
[ "def", "check_log", "(", "logfile", ",", "exited", "=", "'Exited with exit code'", ",", "successful", "=", "'Successfully completed'", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "logfile", ")", ":", "return", "JobStatus", ".", "ready", "if...
Check a log file to determine status of LSF job Often logfile doesn't exist because the job hasn't begun to run. It is unclear what you want to do in that case... Parameters ---------- logfile : str String with path to logfile exited : str Value to check for in existing logfile for exit with failure successful : str Value to check for in existing logfile for success Returns str, one of 'Pending', 'Running', 'Done', 'Failed'
[ "Check", "a", "log", "file", "to", "determine", "status", "of", "LSF", "job" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/sys_interface.py#L39-L66
train
35,937
fermiPy/fermipy
fermipy/jobs/sys_interface.py
SysInterface.check_job
def check_job(cls, job_details): """ Check the status of a specfic job """ return check_log(job_details.logfile, cls.string_exited, cls.string_successful)
python
def check_job(cls, job_details): """ Check the status of a specfic job """ return check_log(job_details.logfile, cls.string_exited, cls.string_successful)
[ "def", "check_job", "(", "cls", ",", "job_details", ")", ":", "return", "check_log", "(", "job_details", ".", "logfile", ",", "cls", ".", "string_exited", ",", "cls", ".", "string_successful", ")" ]
Check the status of a specfic job
[ "Check", "the", "status", "of", "a", "specfic", "job" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/sys_interface.py#L82-L84
train
35,938
fermiPy/fermipy
fermipy/jobs/sys_interface.py
SysInterface.dispatch_job_hook
def dispatch_job_hook(self, link, key, job_config, logfile, stream=sys.stdout): """Hook to dispatch a single job""" raise NotImplementedError("SysInterface.dispatch_job_hook")
python
def dispatch_job_hook(self, link, key, job_config, logfile, stream=sys.stdout): """Hook to dispatch a single job""" raise NotImplementedError("SysInterface.dispatch_job_hook")
[ "def", "dispatch_job_hook", "(", "self", ",", "link", ",", "key", ",", "job_config", ",", "logfile", ",", "stream", "=", "sys", ".", "stdout", ")", ":", "raise", "NotImplementedError", "(", "\"SysInterface.dispatch_job_hook\"", ")" ]
Hook to dispatch a single job
[ "Hook", "to", "dispatch", "a", "single", "job" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/sys_interface.py#L86-L88
train
35,939
fermiPy/fermipy
fermipy/jobs/sys_interface.py
SysInterface.dispatch_job
def dispatch_job(self, link, key, job_archive, stream=sys.stdout): """Function to dispatch a single job Parameters ---------- link : `Link` Link object that sendes the job key : str Key used to identify this particular job job_archive : `JobArchive` Archive used to keep track of jobs Returns `JobDetails` object """ try: job_details = link.jobs[key] except KeyError: print(key, link.jobs) job_config = job_details.job_config link.update_args(job_config) logfile = job_config['logfile'] try: self.dispatch_job_hook(link, key, job_config, logfile, stream) job_details.status = JobStatus.running except IOError: job_details.status = JobStatus.failed if job_archive is not None: job_archive.register_job(job_details) return job_details
python
def dispatch_job(self, link, key, job_archive, stream=sys.stdout): """Function to dispatch a single job Parameters ---------- link : `Link` Link object that sendes the job key : str Key used to identify this particular job job_archive : `JobArchive` Archive used to keep track of jobs Returns `JobDetails` object """ try: job_details = link.jobs[key] except KeyError: print(key, link.jobs) job_config = job_details.job_config link.update_args(job_config) logfile = job_config['logfile'] try: self.dispatch_job_hook(link, key, job_config, logfile, stream) job_details.status = JobStatus.running except IOError: job_details.status = JobStatus.failed if job_archive is not None: job_archive.register_job(job_details) return job_details
[ "def", "dispatch_job", "(", "self", ",", "link", ",", "key", ",", "job_archive", ",", "stream", "=", "sys", ".", "stdout", ")", ":", "try", ":", "job_details", "=", "link", ".", "jobs", "[", "key", "]", "except", "KeyError", ":", "print", "(", "key",...
Function to dispatch a single job Parameters ---------- link : `Link` Link object that sendes the job key : str Key used to identify this particular job job_archive : `JobArchive` Archive used to keep track of jobs Returns `JobDetails` object
[ "Function", "to", "dispatch", "a", "single", "job" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/sys_interface.py#L90-L122
train
35,940
fermiPy/fermipy
fermipy/jobs/sys_interface.py
SysInterface.submit_jobs
def submit_jobs(self, link, job_dict=None, job_archive=None, stream=sys.stdout): """Run the `Link` with all of the items job_dict as input. If job_dict is None, the job_dict will be take from link.jobs Returns a `JobStatus` enum """ failed = False if job_dict is None: job_dict = link.jobs for job_key, job_details in sorted(job_dict.items()): job_config = job_details.job_config # clean failed jobs if job_details.status == JobStatus.failed: clean_job(job_details.logfile, job_details.outfiles, self._dry_run) # clean_job(job_details.logfile, {}, self._dry_run) job_config['logfile'] = job_details.logfile new_job_details = self.dispatch_job( link, job_key, job_archive, stream) if new_job_details.status == JobStatus.failed: failed = True clean_job(new_job_details.logfile, new_job_details.outfiles, self._dry_run) link.jobs[job_key] = new_job_details if failed: return JobStatus.failed return JobStatus.done
python
def submit_jobs(self, link, job_dict=None, job_archive=None, stream=sys.stdout): """Run the `Link` with all of the items job_dict as input. If job_dict is None, the job_dict will be take from link.jobs Returns a `JobStatus` enum """ failed = False if job_dict is None: job_dict = link.jobs for job_key, job_details in sorted(job_dict.items()): job_config = job_details.job_config # clean failed jobs if job_details.status == JobStatus.failed: clean_job(job_details.logfile, job_details.outfiles, self._dry_run) # clean_job(job_details.logfile, {}, self._dry_run) job_config['logfile'] = job_details.logfile new_job_details = self.dispatch_job( link, job_key, job_archive, stream) if new_job_details.status == JobStatus.failed: failed = True clean_job(new_job_details.logfile, new_job_details.outfiles, self._dry_run) link.jobs[job_key] = new_job_details if failed: return JobStatus.failed return JobStatus.done
[ "def", "submit_jobs", "(", "self", ",", "link", ",", "job_dict", "=", "None", ",", "job_archive", "=", "None", ",", "stream", "=", "sys", ".", "stdout", ")", ":", "failed", "=", "False", "if", "job_dict", "is", "None", ":", "job_dict", "=", "link", "...
Run the `Link` with all of the items job_dict as input. If job_dict is None, the job_dict will be take from link.jobs Returns a `JobStatus` enum
[ "Run", "the", "Link", "with", "all", "of", "the", "items", "job_dict", "as", "input", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/sys_interface.py#L124-L152
train
35,941
fermiPy/fermipy
fermipy/jobs/sys_interface.py
SysInterface.clean_jobs
def clean_jobs(self, link, job_dict=None, clean_all=False): """ Clean up all the jobs associated with this link. Returns a `JobStatus` enum """ failed = False if job_dict is None: job_dict = link.jobs for job_details in job_dict.values(): # clean failed jobs if job_details.status == JobStatus.failed or clean_all: # clean_job(job_details.logfile, job_details.outfiles, self._dry_run) clean_job(job_details.logfile, {}, self._dry_run) job_details.status = JobStatus.ready if failed: return JobStatus.failed return JobStatus.done
python
def clean_jobs(self, link, job_dict=None, clean_all=False): """ Clean up all the jobs associated with this link. Returns a `JobStatus` enum """ failed = False if job_dict is None: job_dict = link.jobs for job_details in job_dict.values(): # clean failed jobs if job_details.status == JobStatus.failed or clean_all: # clean_job(job_details.logfile, job_details.outfiles, self._dry_run) clean_job(job_details.logfile, {}, self._dry_run) job_details.status = JobStatus.ready if failed: return JobStatus.failed return JobStatus.done
[ "def", "clean_jobs", "(", "self", ",", "link", ",", "job_dict", "=", "None", ",", "clean_all", "=", "False", ")", ":", "failed", "=", "False", "if", "job_dict", "is", "None", ":", "job_dict", "=", "link", ".", "jobs", "for", "job_details", "in", "job_d...
Clean up all the jobs associated with this link. Returns a `JobStatus` enum
[ "Clean", "up", "all", "the", "jobs", "associated", "with", "this", "link", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/sys_interface.py#L154-L171
train
35,942
fermiPy/fermipy
fermipy/model_utils.py
get_spatial_type
def get_spatial_type(spatial_model): """Translate a spatial model string to a spatial type.""" if spatial_model in ['SkyDirFunction', 'PointSource', 'Gaussian']: return 'SkyDirFunction' elif spatial_model in ['SpatialMap']: return 'SpatialMap' elif spatial_model in ['RadialGaussian', 'RadialDisk']: try: import pyLikelihood if hasattr(pyLikelihood, 'RadialGaussian'): return spatial_model else: return 'SpatialMap' except Exception: return spatial_model else: return spatial_model
python
def get_spatial_type(spatial_model): """Translate a spatial model string to a spatial type.""" if spatial_model in ['SkyDirFunction', 'PointSource', 'Gaussian']: return 'SkyDirFunction' elif spatial_model in ['SpatialMap']: return 'SpatialMap' elif spatial_model in ['RadialGaussian', 'RadialDisk']: try: import pyLikelihood if hasattr(pyLikelihood, 'RadialGaussian'): return spatial_model else: return 'SpatialMap' except Exception: return spatial_model else: return spatial_model
[ "def", "get_spatial_type", "(", "spatial_model", ")", ":", "if", "spatial_model", "in", "[", "'SkyDirFunction'", ",", "'PointSource'", ",", "'Gaussian'", "]", ":", "return", "'SkyDirFunction'", "elif", "spatial_model", "in", "[", "'SpatialMap'", "]", ":", "return"...
Translate a spatial model string to a spatial type.
[ "Translate", "a", "spatial", "model", "string", "to", "a", "spatial", "type", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/model_utils.py#L77-L95
train
35,943
fermiPy/fermipy
fermipy/model_utils.py
create_pars_from_dict
def create_pars_from_dict(name, pars_dict, rescale=True, update_bounds=False): """Create a dictionary for the parameters of a function. Parameters ---------- name : str Name of the function. pars_dict : dict Existing parameter dict that will be merged with the default dictionary created by this method. rescale : bool Rescale parameter values. """ o = get_function_defaults(name) pars_dict = pars_dict.copy() for k in o.keys(): if not k in pars_dict: continue v = pars_dict[k] if not isinstance(v, dict): v = {'name': k, 'value': v} o[k].update(v) kw = dict(update_bounds=update_bounds, rescale=rescale) if 'min' in v or 'max' in v: kw['update_bounds'] = False if 'scale' in v: kw['rescale'] = False o[k] = make_parameter_dict(o[k], **kw) return o
python
def create_pars_from_dict(name, pars_dict, rescale=True, update_bounds=False): """Create a dictionary for the parameters of a function. Parameters ---------- name : str Name of the function. pars_dict : dict Existing parameter dict that will be merged with the default dictionary created by this method. rescale : bool Rescale parameter values. """ o = get_function_defaults(name) pars_dict = pars_dict.copy() for k in o.keys(): if not k in pars_dict: continue v = pars_dict[k] if not isinstance(v, dict): v = {'name': k, 'value': v} o[k].update(v) kw = dict(update_bounds=update_bounds, rescale=rescale) if 'min' in v or 'max' in v: kw['update_bounds'] = False if 'scale' in v: kw['rescale'] = False o[k] = make_parameter_dict(o[k], **kw) return o
[ "def", "create_pars_from_dict", "(", "name", ",", "pars_dict", ",", "rescale", "=", "True", ",", "update_bounds", "=", "False", ")", ":", "o", "=", "get_function_defaults", "(", "name", ")", "pars_dict", "=", "pars_dict", ".", "copy", "(", ")", "for", "k",...
Create a dictionary for the parameters of a function. Parameters ---------- name : str Name of the function. pars_dict : dict Existing parameter dict that will be merged with the default dictionary created by this method. rescale : bool Rescale parameter values.
[ "Create", "a", "dictionary", "for", "the", "parameters", "of", "a", "function", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/model_utils.py#L120-L162
train
35,944
fermiPy/fermipy
fermipy/model_utils.py
make_parameter_dict
def make_parameter_dict(pdict, fixed_par=False, rescale=True, update_bounds=False): """ Update a parameter dictionary. This function will automatically set the parameter scale and bounds if they are not defined. Bounds are also adjusted to ensure that they encompass the parameter value. """ o = copy.deepcopy(pdict) o.setdefault('scale', 1.0) if rescale: value, scale = utils.scale_parameter(o['value'] * o['scale']) o['value'] = np.abs(value) * np.sign(o['value']) o['scale'] = np.abs(scale) * np.sign(o['scale']) if 'error' in o: o['error'] /= np.abs(scale) if update_bounds: o['min'] = o['value'] * 1E-3 o['max'] = o['value'] * 1E3 if fixed_par: o['min'] = o['value'] o['max'] = o['value'] if float(o['min']) > float(o['value']): o['min'] = o['value'] if float(o['max']) < float(o['value']): o['max'] = o['value'] return o
python
def make_parameter_dict(pdict, fixed_par=False, rescale=True, update_bounds=False): """ Update a parameter dictionary. This function will automatically set the parameter scale and bounds if they are not defined. Bounds are also adjusted to ensure that they encompass the parameter value. """ o = copy.deepcopy(pdict) o.setdefault('scale', 1.0) if rescale: value, scale = utils.scale_parameter(o['value'] * o['scale']) o['value'] = np.abs(value) * np.sign(o['value']) o['scale'] = np.abs(scale) * np.sign(o['scale']) if 'error' in o: o['error'] /= np.abs(scale) if update_bounds: o['min'] = o['value'] * 1E-3 o['max'] = o['value'] * 1E3 if fixed_par: o['min'] = o['value'] o['max'] = o['value'] if float(o['min']) > float(o['value']): o['min'] = o['value'] if float(o['max']) < float(o['value']): o['max'] = o['value'] return o
[ "def", "make_parameter_dict", "(", "pdict", ",", "fixed_par", "=", "False", ",", "rescale", "=", "True", ",", "update_bounds", "=", "False", ")", ":", "o", "=", "copy", ".", "deepcopy", "(", "pdict", ")", "o", ".", "setdefault", "(", "'scale'", ",", "1...
Update a parameter dictionary. This function will automatically set the parameter scale and bounds if they are not defined. Bounds are also adjusted to ensure that they encompass the parameter value.
[ "Update", "a", "parameter", "dictionary", ".", "This", "function", "will", "automatically", "set", "the", "parameter", "scale", "and", "bounds", "if", "they", "are", "not", "defined", ".", "Bounds", "are", "also", "adjusted", "to", "ensure", "that", "they", ...
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/model_utils.py#L165-L197
train
35,945
fermiPy/fermipy
fermipy/model_utils.py
cast_pars_dict
def cast_pars_dict(pars_dict): """Cast the bool and float elements of a parameters dict to the appropriate python types. """ o = {} for pname, pdict in pars_dict.items(): o[pname] = {} for k, v in pdict.items(): if k == 'free': o[pname][k] = bool(int(v)) elif k == 'name': o[pname][k] = v else: o[pname][k] = float(v) return o
python
def cast_pars_dict(pars_dict): """Cast the bool and float elements of a parameters dict to the appropriate python types. """ o = {} for pname, pdict in pars_dict.items(): o[pname] = {} for k, v in pdict.items(): if k == 'free': o[pname][k] = bool(int(v)) elif k == 'name': o[pname][k] = v else: o[pname][k] = float(v) return o
[ "def", "cast_pars_dict", "(", "pars_dict", ")", ":", "o", "=", "{", "}", "for", "pname", ",", "pdict", "in", "pars_dict", ".", "items", "(", ")", ":", "o", "[", "pname", "]", "=", "{", "}", "for", "k", ",", "v", "in", "pdict", ".", "items", "("...
Cast the bool and float elements of a parameters dict to the appropriate python types.
[ "Cast", "the", "bool", "and", "float", "elements", "of", "a", "parameters", "dict", "to", "the", "appropriate", "python", "types", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/model_utils.py#L200-L220
train
35,946
fermiPy/fermipy
fermipy/scripts/gather_srcmaps.py
do_gather
def do_gather(flist): """ Gather all the HDUs from a list of files""" hlist = [] nskip = 3 for fname in flist: fin = fits.open(fname) if len(hlist) == 0: if fin[1].name == 'SKYMAP': nskip = 4 start = 0 else: start = nskip for h in fin[start:]: hlist.append(h) hdulistout = fits.HDUList(hlist) return hdulistout
python
def do_gather(flist): """ Gather all the HDUs from a list of files""" hlist = [] nskip = 3 for fname in flist: fin = fits.open(fname) if len(hlist) == 0: if fin[1].name == 'SKYMAP': nskip = 4 start = 0 else: start = nskip for h in fin[start:]: hlist.append(h) hdulistout = fits.HDUList(hlist) return hdulistout
[ "def", "do_gather", "(", "flist", ")", ":", "hlist", "=", "[", "]", "nskip", "=", "3", "for", "fname", "in", "flist", ":", "fin", "=", "fits", ".", "open", "(", "fname", ")", "if", "len", "(", "hlist", ")", "==", "0", ":", "if", "fin", "[", "...
Gather all the HDUs from a list of files
[ "Gather", "all", "the", "HDUs", "from", "a", "list", "of", "files" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/scripts/gather_srcmaps.py#L10-L25
train
35,947
fermiPy/fermipy
fermipy/jobs/job_archive.py
main_browse
def main_browse(): """Entry point for command line use for browsing a JobArchive """ parser = argparse.ArgumentParser(usage="job_archive.py [options]", description="Browse a job archive") parser.add_argument('--jobs', action='store', dest='job_archive_table', type=str, default='job_archive_temp2.fits', help="Job archive file") parser.add_argument('--files', action='store', dest='file_archive_table', type=str, default='file_archive_temp2.fits', help="File archive file") parser.add_argument('--base', action='store', dest='base_path', type=str, default=os.path.abspath('.'), help="File archive base path") args = parser.parse_args(sys.argv[1:]) job_ar = JobArchive.build_archive(**args.__dict__) job_ar.table.pprint()
python
def main_browse(): """Entry point for command line use for browsing a JobArchive """ parser = argparse.ArgumentParser(usage="job_archive.py [options]", description="Browse a job archive") parser.add_argument('--jobs', action='store', dest='job_archive_table', type=str, default='job_archive_temp2.fits', help="Job archive file") parser.add_argument('--files', action='store', dest='file_archive_table', type=str, default='file_archive_temp2.fits', help="File archive file") parser.add_argument('--base', action='store', dest='base_path', type=str, default=os.path.abspath('.'), help="File archive base path") args = parser.parse_args(sys.argv[1:]) job_ar = JobArchive.build_archive(**args.__dict__) job_ar.table.pprint()
[ "def", "main_browse", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "usage", "=", "\"job_archive.py [options]\"", ",", "description", "=", "\"Browse a job archive\"", ")", "parser", ".", "add_argument", "(", "'--jobs'", ",", "action", "=", ...
Entry point for command line use for browsing a JobArchive
[ "Entry", "point", "for", "command", "line", "use", "for", "browsing", "a", "JobArchive" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L690-L705
train
35,948
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobStatusVector.n_waiting
def n_waiting(self): """Return the number of jobs in various waiting states""" return self._counters[JobStatus.no_job] +\ self._counters[JobStatus.unknown] +\ self._counters[JobStatus.not_ready] +\ self._counters[JobStatus.ready]
python
def n_waiting(self): """Return the number of jobs in various waiting states""" return self._counters[JobStatus.no_job] +\ self._counters[JobStatus.unknown] +\ self._counters[JobStatus.not_ready] +\ self._counters[JobStatus.ready]
[ "def", "n_waiting", "(", "self", ")", ":", "return", "self", ".", "_counters", "[", "JobStatus", ".", "no_job", "]", "+", "self", ".", "_counters", "[", "JobStatus", ".", "unknown", "]", "+", "self", ".", "_counters", "[", "JobStatus", ".", "not_ready", ...
Return the number of jobs in various waiting states
[ "Return", "the", "number", "of", "jobs", "in", "various", "waiting", "states" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L87-L92
train
35,949
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobStatusVector.n_failed
def n_failed(self): """Return the number of failed jobs""" return self._counters[JobStatus.failed] + self._counters[JobStatus.partial_failed]
python
def n_failed(self): """Return the number of failed jobs""" return self._counters[JobStatus.failed] + self._counters[JobStatus.partial_failed]
[ "def", "n_failed", "(", "self", ")", ":", "return", "self", ".", "_counters", "[", "JobStatus", ".", "failed", "]", "+", "self", ".", "_counters", "[", "JobStatus", ".", "partial_failed", "]" ]
Return the number of failed jobs
[ "Return", "the", "number", "of", "failed", "jobs" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L110-L112
train
35,950
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobStatusVector.get_status
def get_status(self): """Return an overall status based on the number of jobs in various states. """ if self.n_total == 0: return JobStatus.no_job elif self.n_done == self.n_total: return JobStatus.done elif self.n_failed > 0: # If more that a quater of the jobs fail, fail the whole thing if self.n_failed > self.n_total / 4.: return JobStatus.failed return JobStatus.partial_failed elif self.n_running > 0: return JobStatus.running elif self.n_pending > 0: return JobStatus.pending return JobStatus.ready
python
def get_status(self): """Return an overall status based on the number of jobs in various states. """ if self.n_total == 0: return JobStatus.no_job elif self.n_done == self.n_total: return JobStatus.done elif self.n_failed > 0: # If more that a quater of the jobs fail, fail the whole thing if self.n_failed > self.n_total / 4.: return JobStatus.failed return JobStatus.partial_failed elif self.n_running > 0: return JobStatus.running elif self.n_pending > 0: return JobStatus.pending return JobStatus.ready
[ "def", "get_status", "(", "self", ")", ":", "if", "self", ".", "n_total", "==", "0", ":", "return", "JobStatus", ".", "no_job", "elif", "self", ".", "n_done", "==", "self", ".", "n_total", ":", "return", "JobStatus", ".", "done", "elif", "self", ".", ...
Return an overall status based on the number of jobs in various states.
[ "Return", "an", "overall", "status", "based", "on", "the", "number", "of", "jobs", "in", "various", "states", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L123-L140
train
35,951
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobDetails.make_tables
def make_tables(job_dict): """Build and return an `astropy.table.Table' to store `JobDetails`""" col_dbkey = Column(name='dbkey', dtype=int) col_jobname = Column(name='jobname', dtype='S64') col_jobkey = Column(name='jobkey', dtype='S64') col_appname = Column(name='appname', dtype='S64') col_logfile = Column(name='logfile', dtype='S256') col_job_config = Column(name='job_config', dtype='S1024') col_timestamp = Column(name='timestamp', dtype=int) col_infile_refs = Column(name='infile_refs', dtype=int, shape=(2)) col_outfile_refs = Column(name='outfile_refs', dtype=int, shape=(2)) col_rmfile_refs = Column(name='rmfile_refs', dtype=int, shape=(2)) col_intfile_refs = Column(name='intfile_refs', dtype=int, shape=(2)) col_status = Column(name='status', dtype=int) columns = [col_dbkey, col_jobname, col_jobkey, col_appname, col_logfile, col_job_config, col_timestamp, col_infile_refs, col_outfile_refs, col_rmfile_refs, col_intfile_refs, col_status] table = Table(data=columns) col_file_ids = Column(name='file_id', dtype=int) table_ids = Table(data=[col_file_ids]) for val in job_dict.values(): val.append_to_tables(table, table_ids) return table, table_ids
python
def make_tables(job_dict): """Build and return an `astropy.table.Table' to store `JobDetails`""" col_dbkey = Column(name='dbkey', dtype=int) col_jobname = Column(name='jobname', dtype='S64') col_jobkey = Column(name='jobkey', dtype='S64') col_appname = Column(name='appname', dtype='S64') col_logfile = Column(name='logfile', dtype='S256') col_job_config = Column(name='job_config', dtype='S1024') col_timestamp = Column(name='timestamp', dtype=int) col_infile_refs = Column(name='infile_refs', dtype=int, shape=(2)) col_outfile_refs = Column(name='outfile_refs', dtype=int, shape=(2)) col_rmfile_refs = Column(name='rmfile_refs', dtype=int, shape=(2)) col_intfile_refs = Column(name='intfile_refs', dtype=int, shape=(2)) col_status = Column(name='status', dtype=int) columns = [col_dbkey, col_jobname, col_jobkey, col_appname, col_logfile, col_job_config, col_timestamp, col_infile_refs, col_outfile_refs, col_rmfile_refs, col_intfile_refs, col_status] table = Table(data=columns) col_file_ids = Column(name='file_id', dtype=int) table_ids = Table(data=[col_file_ids]) for val in job_dict.values(): val.append_to_tables(table, table_ids) return table, table_ids
[ "def", "make_tables", "(", "job_dict", ")", ":", "col_dbkey", "=", "Column", "(", "name", "=", "'dbkey'", ",", "dtype", "=", "int", ")", "col_jobname", "=", "Column", "(", "name", "=", "'jobname'", ",", "dtype", "=", "'S64'", ")", "col_jobkey", "=", "C...
Build and return an `astropy.table.Table' to store `JobDetails`
[ "Build", "and", "return", "an", "astropy", ".", "table", ".", "Table", "to", "store", "JobDetails" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L228-L255
train
35,952
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobDetails.get_file_ids
def get_file_ids(self, file_archive, creator=None, status=FileStatus.no_file): """Fill the file id arrays from the file lists Parameters ---------- file_archive : `FileArchive` Used to look up file ids creator : int A unique key for the job that created these file status : `FileStatus` Enumeration giving current status thse files """ file_dict = copy.deepcopy(self.file_dict) if self.sub_file_dict is not None: file_dict.update(self.sub_file_dict.file_dict) infiles = file_dict.input_files outfiles = file_dict.output_files rmfiles = file_dict.temp_files int_files = file_dict.internal_files if self.infile_ids is None: if infiles is not None: self.infile_ids = np.zeros((len(infiles)), int) filelist = file_archive.get_file_ids( infiles, creator, FileStatus.expected, file_dict) JobDetails._fill_array_from_list(filelist, self.infile_ids) else: self.infile_ids = np.zeros((0), int) if self.outfile_ids is None: if outfiles is not None: self.outfile_ids = np.zeros((len(outfiles)), int) filelist = file_archive.get_file_ids( outfiles, creator, status, file_dict) JobDetails._fill_array_from_list(filelist, self.outfile_ids) else: self.outfile_ids = np.zeros((0), int) if self.rmfile_ids is None: if rmfiles is not None: self.rmfile_ids = np.zeros((len(rmfiles)), int) filelist = file_archive.get_file_ids(rmfiles) JobDetails._fill_array_from_list(filelist, self.rmfile_ids) else: self.rmfile_ids = np.zeros((0), int) if self.intfile_ids is None: if int_files is not None: self.intfile_ids = np.zeros((len(int_files)), int) filelist = file_archive.get_file_ids( int_files, creator, status) JobDetails._fill_array_from_list(filelist, self.intfile_ids) else: self.intfile_ids = np.zeros((0), int)
python
def get_file_ids(self, file_archive, creator=None, status=FileStatus.no_file): """Fill the file id arrays from the file lists Parameters ---------- file_archive : `FileArchive` Used to look up file ids creator : int A unique key for the job that created these file status : `FileStatus` Enumeration giving current status thse files """ file_dict = copy.deepcopy(self.file_dict) if self.sub_file_dict is not None: file_dict.update(self.sub_file_dict.file_dict) infiles = file_dict.input_files outfiles = file_dict.output_files rmfiles = file_dict.temp_files int_files = file_dict.internal_files if self.infile_ids is None: if infiles is not None: self.infile_ids = np.zeros((len(infiles)), int) filelist = file_archive.get_file_ids( infiles, creator, FileStatus.expected, file_dict) JobDetails._fill_array_from_list(filelist, self.infile_ids) else: self.infile_ids = np.zeros((0), int) if self.outfile_ids is None: if outfiles is not None: self.outfile_ids = np.zeros((len(outfiles)), int) filelist = file_archive.get_file_ids( outfiles, creator, status, file_dict) JobDetails._fill_array_from_list(filelist, self.outfile_ids) else: self.outfile_ids = np.zeros((0), int) if self.rmfile_ids is None: if rmfiles is not None: self.rmfile_ids = np.zeros((len(rmfiles)), int) filelist = file_archive.get_file_ids(rmfiles) JobDetails._fill_array_from_list(filelist, self.rmfile_ids) else: self.rmfile_ids = np.zeros((0), int) if self.intfile_ids is None: if int_files is not None: self.intfile_ids = np.zeros((len(int_files)), int) filelist = file_archive.get_file_ids( int_files, creator, status) JobDetails._fill_array_from_list(filelist, self.intfile_ids) else: self.intfile_ids = np.zeros((0), int)
[ "def", "get_file_ids", "(", "self", ",", "file_archive", ",", "creator", "=", "None", ",", "status", "=", "FileStatus", ".", "no_file", ")", ":", "file_dict", "=", "copy", ".", "deepcopy", "(", "self", ".", "file_dict", ")", "if", "self", ".", "sub_file_...
Fill the file id arrays from the file lists Parameters ---------- file_archive : `FileArchive` Used to look up file ids creator : int A unique key for the job that created these file status : `FileStatus` Enumeration giving current status thse files
[ "Fill", "the", "file", "id", "arrays", "from", "the", "file", "lists" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L264-L318
train
35,953
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobDetails.get_file_paths
def get_file_paths(self, file_archive, file_id_array): """Get the full paths of the files used by this object from the the id arrays Parameters ---------- file_archive : `FileArchive` Used to look up file ids file_id_array : `numpy.array` Array that remaps the file indexes """ full_list = [] status_dict = {} full_list += file_archive.get_file_paths( file_id_array[self.infile_ids]) full_list += file_archive.get_file_paths( file_id_array[self.outfile_ids]) full_list += file_archive.get_file_paths( file_id_array[self.rmfile_ids]) full_list += file_archive.get_file_paths( file_id_array[self.intfile_ids]) for filepath in full_list: handle = file_archive.get_handle(filepath) status_dict[filepath] = handle.status if self.file_dict is None: self.file_dict = FileDict() self.file_dict.update(status_dict)
python
def get_file_paths(self, file_archive, file_id_array): """Get the full paths of the files used by this object from the the id arrays Parameters ---------- file_archive : `FileArchive` Used to look up file ids file_id_array : `numpy.array` Array that remaps the file indexes """ full_list = [] status_dict = {} full_list += file_archive.get_file_paths( file_id_array[self.infile_ids]) full_list += file_archive.get_file_paths( file_id_array[self.outfile_ids]) full_list += file_archive.get_file_paths( file_id_array[self.rmfile_ids]) full_list += file_archive.get_file_paths( file_id_array[self.intfile_ids]) for filepath in full_list: handle = file_archive.get_handle(filepath) status_dict[filepath] = handle.status if self.file_dict is None: self.file_dict = FileDict() self.file_dict.update(status_dict)
[ "def", "get_file_paths", "(", "self", ",", "file_archive", ",", "file_id_array", ")", ":", "full_list", "=", "[", "]", "status_dict", "=", "{", "}", "full_list", "+=", "file_archive", ".", "get_file_paths", "(", "file_id_array", "[", "self", ".", "infile_ids",...
Get the full paths of the files used by this object from the the id arrays Parameters ---------- file_archive : `FileArchive` Used to look up file ids file_id_array : `numpy.array` Array that remaps the file indexes
[ "Get", "the", "full", "paths", "of", "the", "files", "used", "by", "this", "object", "from", "the", "the", "id", "arrays" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L320-L347
train
35,954
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobDetails._fill_array_from_list
def _fill_array_from_list(the_list, the_array): """Fill an `array` from a `list`""" for i, val in enumerate(the_list): the_array[i] = val return the_array
python
def _fill_array_from_list(the_list, the_array): """Fill an `array` from a `list`""" for i, val in enumerate(the_list): the_array[i] = val return the_array
[ "def", "_fill_array_from_list", "(", "the_list", ",", "the_array", ")", ":", "for", "i", ",", "val", "in", "enumerate", "(", "the_list", ")", ":", "the_array", "[", "i", "]", "=", "val", "return", "the_array" ]
Fill an `array` from a `list`
[ "Fill", "an", "array", "from", "a", "list" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L350-L354
train
35,955
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobDetails.make_dict
def make_dict(cls, table): """Build a dictionary map int to `JobDetails` from an `astropy.table.Table`""" ret_dict = {} for row in table: job_details = cls.create_from_row(row) ret_dict[job_details.dbkey] = job_details return ret_dict
python
def make_dict(cls, table): """Build a dictionary map int to `JobDetails` from an `astropy.table.Table`""" ret_dict = {} for row in table: job_details = cls.create_from_row(row) ret_dict[job_details.dbkey] = job_details return ret_dict
[ "def", "make_dict", "(", "cls", ",", "table", ")", ":", "ret_dict", "=", "{", "}", "for", "row", "in", "table", ":", "job_details", "=", "cls", ".", "create_from_row", "(", "row", ")", "ret_dict", "[", "job_details", ".", "dbkey", "]", "=", "job_detail...
Build a dictionary map int to `JobDetails` from an `astropy.table.Table`
[ "Build", "a", "dictionary", "map", "int", "to", "JobDetails", "from", "an", "astropy", ".", "table", ".", "Table" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L362-L368
train
35,956
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobDetails.check_status_logfile
def check_status_logfile(self, checker_func): """Check on the status of this particular job using the logfile""" self.status = checker_func(self.logfile) return self.status
python
def check_status_logfile(self, checker_func): """Check on the status of this particular job using the logfile""" self.status = checker_func(self.logfile) return self.status
[ "def", "check_status_logfile", "(", "self", ",", "checker_func", ")", ":", "self", ".", "status", "=", "checker_func", "(", "self", ".", "logfile", ")", "return", "self", ".", "status" ]
Check on the status of this particular job using the logfile
[ "Check", "on", "the", "status", "of", "this", "particular", "job", "using", "the", "logfile" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L441-L444
train
35,957
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobArchive._read_table_file
def _read_table_file(self, table_file): """Read an `astropy.table.Table` from table_file to set up the `JobArchive`""" self._table_file = table_file if os.path.exists(self._table_file): self._table = Table.read(self._table_file, hdu='JOB_ARCHIVE') self._table_ids = Table.read(self._table_file, hdu='FILE_IDS') else: self._table, self._table_ids = JobDetails.make_tables({}) self._table_id_array = self._table_ids['file_id'].data self._fill_cache()
python
def _read_table_file(self, table_file): """Read an `astropy.table.Table` from table_file to set up the `JobArchive`""" self._table_file = table_file if os.path.exists(self._table_file): self._table = Table.read(self._table_file, hdu='JOB_ARCHIVE') self._table_ids = Table.read(self._table_file, hdu='FILE_IDS') else: self._table, self._table_ids = JobDetails.make_tables({}) self._table_id_array = self._table_ids['file_id'].data self._fill_cache()
[ "def", "_read_table_file", "(", "self", ",", "table_file", ")", ":", "self", ".", "_table_file", "=", "table_file", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "_table_file", ")", ":", "self", ".", "_table", "=", "Table", ".", "read", "("...
Read an `astropy.table.Table` from table_file to set up the `JobArchive`
[ "Read", "an", "astropy", ".", "table", ".", "Table", "from", "table_file", "to", "set", "up", "the", "JobArchive" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L525-L534
train
35,958
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobArchive.get_details
def get_details(self, jobname, jobkey): """Get the `JobDetails` associated to a particular job instance""" fullkey = JobDetails.make_fullkey(jobname, jobkey) return self._cache[fullkey]
python
def get_details(self, jobname, jobkey): """Get the `JobDetails` associated to a particular job instance""" fullkey = JobDetails.make_fullkey(jobname, jobkey) return self._cache[fullkey]
[ "def", "get_details", "(", "self", ",", "jobname", ",", "jobkey", ")", ":", "fullkey", "=", "JobDetails", ".", "make_fullkey", "(", "jobname", ",", "jobkey", ")", "return", "self", ".", "_cache", "[", "fullkey", "]" ]
Get the `JobDetails` associated to a particular job instance
[ "Get", "the", "JobDetails", "associated", "to", "a", "particular", "job", "instance" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L544-L547
train
35,959
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobArchive.register_job
def register_job(self, job_details): """Register a job in this `JobArchive` """ # check to see if the job already exists try: job_details_old = self.get_details(job_details.jobname, job_details.jobkey) if job_details_old.status <= JobStatus.running: job_details_old.status = job_details.status job_details_old.update_table_row( self._table, job_details_old.dbkey - 1) job_details = job_details_old except KeyError: job_details.dbkey = len(self._table) + 1 job_details.get_file_ids( self._file_archive, creator=job_details.dbkey) job_details.append_to_tables(self._table, self._table_ids) self._table_id_array = self._table_ids['file_id'].data self._cache[job_details.fullkey] = job_details return job_details
python
def register_job(self, job_details): """Register a job in this `JobArchive` """ # check to see if the job already exists try: job_details_old = self.get_details(job_details.jobname, job_details.jobkey) if job_details_old.status <= JobStatus.running: job_details_old.status = job_details.status job_details_old.update_table_row( self._table, job_details_old.dbkey - 1) job_details = job_details_old except KeyError: job_details.dbkey = len(self._table) + 1 job_details.get_file_ids( self._file_archive, creator=job_details.dbkey) job_details.append_to_tables(self._table, self._table_ids) self._table_id_array = self._table_ids['file_id'].data self._cache[job_details.fullkey] = job_details return job_details
[ "def", "register_job", "(", "self", ",", "job_details", ")", ":", "# check to see if the job already exists", "try", ":", "job_details_old", "=", "self", ".", "get_details", "(", "job_details", ".", "jobname", ",", "job_details", ".", "jobkey", ")", "if", "job_det...
Register a job in this `JobArchive`
[ "Register", "a", "job", "in", "this", "JobArchive" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L549-L567
train
35,960
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobArchive.register_jobs
def register_jobs(self, job_dict): """Register a bunch of jobs in this archive""" njobs = len(job_dict) sys.stdout.write("Registering %i total jobs: " % njobs) for i, job_details in enumerate(job_dict.values()): if i % 10 == 0: sys.stdout.write('.') sys.stdout.flush() self.register_job(job_details) sys.stdout.write('!\n')
python
def register_jobs(self, job_dict): """Register a bunch of jobs in this archive""" njobs = len(job_dict) sys.stdout.write("Registering %i total jobs: " % njobs) for i, job_details in enumerate(job_dict.values()): if i % 10 == 0: sys.stdout.write('.') sys.stdout.flush() self.register_job(job_details) sys.stdout.write('!\n')
[ "def", "register_jobs", "(", "self", ",", "job_dict", ")", ":", "njobs", "=", "len", "(", "job_dict", ")", "sys", ".", "stdout", ".", "write", "(", "\"Registering %i total jobs: \"", "%", "njobs", ")", "for", "i", ",", "job_details", "in", "enumerate", "("...
Register a bunch of jobs in this archive
[ "Register", "a", "bunch", "of", "jobs", "in", "this", "archive" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L569-L578
train
35,961
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobArchive.register_job_from_link
def register_job_from_link(self, link, key, **kwargs): """Register a job in the `JobArchive` from a `Link` object """ job_config = kwargs.get('job_config', None) if job_config is None: job_config = link.args status = kwargs.get('status', JobStatus.unknown) job_details = JobDetails(jobname=link.linkname, jobkey=key, appname=link.appname, logfile=kwargs.get('logfile'), jobconfig=job_config, timestamp=get_timestamp(), file_dict=copy.deepcopy(link.files), sub_file_dict=copy.deepcopy(link.sub_files), status=status) self.register_job(job_details) return job_details
python
def register_job_from_link(self, link, key, **kwargs): """Register a job in the `JobArchive` from a `Link` object """ job_config = kwargs.get('job_config', None) if job_config is None: job_config = link.args status = kwargs.get('status', JobStatus.unknown) job_details = JobDetails(jobname=link.linkname, jobkey=key, appname=link.appname, logfile=kwargs.get('logfile'), jobconfig=job_config, timestamp=get_timestamp(), file_dict=copy.deepcopy(link.files), sub_file_dict=copy.deepcopy(link.sub_files), status=status) self.register_job(job_details) return job_details
[ "def", "register_job_from_link", "(", "self", ",", "link", ",", "key", ",", "*", "*", "kwargs", ")", ":", "job_config", "=", "kwargs", ".", "get", "(", "'job_config'", ",", "None", ")", "if", "job_config", "is", "None", ":", "job_config", "=", "link", ...
Register a job in the `JobArchive` from a `Link` object
[ "Register", "a", "job", "in", "the", "JobArchive", "from", "a", "Link", "object" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L580-L596
train
35,962
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobArchive.update_job
def update_job(self, job_details): """Update a job in the `JobArchive` """ other = self.get_details(job_details.jobname, job_details.jobkey) other.timestamp = job_details.timestamp other.status = job_details.status other.update_table_row(self._table, other.dbkey - 1) return other
python
def update_job(self, job_details): """Update a job in the `JobArchive` """ other = self.get_details(job_details.jobname, job_details.jobkey) other.timestamp = job_details.timestamp other.status = job_details.status other.update_table_row(self._table, other.dbkey - 1) return other
[ "def", "update_job", "(", "self", ",", "job_details", ")", ":", "other", "=", "self", ".", "get_details", "(", "job_details", ".", "jobname", ",", "job_details", ".", "jobkey", ")", "other", ".", "timestamp", "=", "job_details", ".", "timestamp", "other", ...
Update a job in the `JobArchive`
[ "Update", "a", "job", "in", "the", "JobArchive" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L598-L605
train
35,963
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobArchive.remove_jobs
def remove_jobs(self, mask): """Mark all jobs that match a mask as 'removed' """ jobnames = self.table[mask]['jobname'] jobkey = self.table[mask]['jobkey'] self.table[mask]['status'] = JobStatus.removed for jobname, jobkey in zip(jobnames, jobkey): fullkey = JobDetails.make_fullkey(jobname, jobkey) self._cache.pop(fullkey).status = JobStatus.removed self.write_table_file()
python
def remove_jobs(self, mask): """Mark all jobs that match a mask as 'removed' """ jobnames = self.table[mask]['jobname'] jobkey = self.table[mask]['jobkey'] self.table[mask]['status'] = JobStatus.removed for jobname, jobkey in zip(jobnames, jobkey): fullkey = JobDetails.make_fullkey(jobname, jobkey) self._cache.pop(fullkey).status = JobStatus.removed self.write_table_file()
[ "def", "remove_jobs", "(", "self", ",", "mask", ")", ":", "jobnames", "=", "self", ".", "table", "[", "mask", "]", "[", "'jobname'", "]", "jobkey", "=", "self", ".", "table", "[", "mask", "]", "[", "'jobkey'", "]", "self", ".", "table", "[", "mask"...
Mark all jobs that match a mask as 'removed'
[ "Mark", "all", "jobs", "that", "match", "a", "mask", "as", "removed" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L607-L615
train
35,964
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobArchive.build_temp_job_archive
def build_temp_job_archive(cls): """Build and return a `JobArchive` using defualt locations of persistent files. """ try: os.unlink('job_archive_temp.fits') os.unlink('file_archive_temp.fits') except OSError: pass cls._archive = cls(job_archive_table='job_archive_temp.fits', file_archive_table='file_archive_temp.fits', base_path=os.path.abspath('.') + '/') return cls._archive
python
def build_temp_job_archive(cls): """Build and return a `JobArchive` using defualt locations of persistent files. """ try: os.unlink('job_archive_temp.fits') os.unlink('file_archive_temp.fits') except OSError: pass cls._archive = cls(job_archive_table='job_archive_temp.fits', file_archive_table='file_archive_temp.fits', base_path=os.path.abspath('.') + '/') return cls._archive
[ "def", "build_temp_job_archive", "(", "cls", ")", ":", "try", ":", "os", ".", "unlink", "(", "'job_archive_temp.fits'", ")", "os", ".", "unlink", "(", "'file_archive_temp.fits'", ")", "except", "OSError", ":", "pass", "cls", ".", "_archive", "=", "cls", "(",...
Build and return a `JobArchive` using defualt locations of persistent files.
[ "Build", "and", "return", "a", "JobArchive", "using", "defualt", "locations", "of", "persistent", "files", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L618-L630
train
35,965
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobArchive.update_job_status
def update_job_status(self, checker_func): """Update the status of all the jobs in the archive""" njobs = len(self.cache.keys()) status_vect = np.zeros((8), int) sys.stdout.write("Updating status of %i jobs: " % njobs) sys.stdout.flush() for i, key in enumerate(self.cache.keys()): if i % 200 == 0: sys.stdout.write('.') sys.stdout.flush() job_details = self.cache[key] if job_details.status in [JobStatus.pending, JobStatus.running]: if checker_func: job_details.check_status_logfile(checker_func) job_details.update_table_row(self._table, job_details.dbkey - 1) status_vect[job_details.status] += 1 sys.stdout.write("!\n") sys.stdout.flush() sys.stdout.write("Summary:\n") sys.stdout.write(" Unknown: %i\n" % status_vect[JobStatus.unknown]) sys.stdout.write(" Not Ready: %i\n" % status_vect[JobStatus.not_ready]) sys.stdout.write(" Ready: %i\n" % status_vect[JobStatus.ready]) sys.stdout.write(" Pending: %i\n" % status_vect[JobStatus.pending]) sys.stdout.write(" Running: %i\n" % status_vect[JobStatus.running]) sys.stdout.write(" Done: %i\n" % status_vect[JobStatus.done]) sys.stdout.write(" Failed: %i\n" % status_vect[JobStatus.failed]) sys.stdout.write(" Partial: %i\n" % status_vect[JobStatus.partial_failed])
python
def update_job_status(self, checker_func): """Update the status of all the jobs in the archive""" njobs = len(self.cache.keys()) status_vect = np.zeros((8), int) sys.stdout.write("Updating status of %i jobs: " % njobs) sys.stdout.flush() for i, key in enumerate(self.cache.keys()): if i % 200 == 0: sys.stdout.write('.') sys.stdout.flush() job_details = self.cache[key] if job_details.status in [JobStatus.pending, JobStatus.running]: if checker_func: job_details.check_status_logfile(checker_func) job_details.update_table_row(self._table, job_details.dbkey - 1) status_vect[job_details.status] += 1 sys.stdout.write("!\n") sys.stdout.flush() sys.stdout.write("Summary:\n") sys.stdout.write(" Unknown: %i\n" % status_vect[JobStatus.unknown]) sys.stdout.write(" Not Ready: %i\n" % status_vect[JobStatus.not_ready]) sys.stdout.write(" Ready: %i\n" % status_vect[JobStatus.ready]) sys.stdout.write(" Pending: %i\n" % status_vect[JobStatus.pending]) sys.stdout.write(" Running: %i\n" % status_vect[JobStatus.running]) sys.stdout.write(" Done: %i\n" % status_vect[JobStatus.done]) sys.stdout.write(" Failed: %i\n" % status_vect[JobStatus.failed]) sys.stdout.write(" Partial: %i\n" % status_vect[JobStatus.partial_failed])
[ "def", "update_job_status", "(", "self", ",", "checker_func", ")", ":", "njobs", "=", "len", "(", "self", ".", "cache", ".", "keys", "(", ")", ")", "status_vect", "=", "np", ".", "zeros", "(", "(", "8", ")", ",", "int", ")", "sys", ".", "stdout", ...
Update the status of all the jobs in the archive
[ "Update", "the", "status", "of", "all", "the", "jobs", "in", "the", "archive" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L646-L675
train
35,966
fermiPy/fermipy
fermipy/jobs/job_archive.py
JobArchive.build_archive
def build_archive(cls, **kwargs): """Return the singleton `JobArchive` instance, building it if needed """ if cls._archive is None: cls._archive = cls(**kwargs) return cls._archive
python
def build_archive(cls, **kwargs): """Return the singleton `JobArchive` instance, building it if needed """ if cls._archive is None: cls._archive = cls(**kwargs) return cls._archive
[ "def", "build_archive", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "if", "cls", ".", "_archive", "is", "None", ":", "cls", ".", "_archive", "=", "cls", "(", "*", "*", "kwargs", ")", "return", "cls", ".", "_archive" ]
Return the singleton `JobArchive` instance, building it if needed
[ "Return", "the", "singleton", "JobArchive", "instance", "building", "it", "if", "needed" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L683-L687
train
35,967
fermiPy/fermipy
fermipy/timing.py
Timer.elapsed_time
def elapsed_time(self): """Get the elapsed time.""" # Timer is running if self._t0 is not None: return self._time + self._get_time() else: return self._time
python
def elapsed_time(self): """Get the elapsed time.""" # Timer is running if self._t0 is not None: return self._time + self._get_time() else: return self._time
[ "def", "elapsed_time", "(", "self", ")", ":", "# Timer is running", "if", "self", ".", "_t0", "is", "not", "None", ":", "return", "self", ".", "_time", "+", "self", ".", "_get_time", "(", ")", "else", ":", "return", "self", ".", "_time" ]
Get the elapsed time.
[ "Get", "the", "elapsed", "time", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/timing.py#L14-L21
train
35,968
fermiPy/fermipy
fermipy/diffuse/source_factory.py
make_spatialmap_source
def make_spatialmap_source(name, Spatial_Filename, spectrum): """Construct and return a `fermipy.roi_model.Source` object """ data = dict(Spatial_Filename=Spatial_Filename, ra=0.0, dec=0.0, SpatialType='SpatialMap', Source_Name=name) if spectrum is not None: data.update(spectrum) return roi_model.Source(name, data)
python
def make_spatialmap_source(name, Spatial_Filename, spectrum): """Construct and return a `fermipy.roi_model.Source` object """ data = dict(Spatial_Filename=Spatial_Filename, ra=0.0, dec=0.0, SpatialType='SpatialMap', Source_Name=name) if spectrum is not None: data.update(spectrum) return roi_model.Source(name, data)
[ "def", "make_spatialmap_source", "(", "name", ",", "Spatial_Filename", ",", "spectrum", ")", ":", "data", "=", "dict", "(", "Spatial_Filename", "=", "Spatial_Filename", ",", "ra", "=", "0.0", ",", "dec", "=", "0.0", ",", "SpatialType", "=", "'SpatialMap'", "...
Construct and return a `fermipy.roi_model.Source` object
[ "Construct", "and", "return", "a", "fermipy", ".", "roi_model", ".", "Source", "object" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/source_factory.py#L21-L31
train
35,969
fermiPy/fermipy
fermipy/diffuse/source_factory.py
make_mapcube_source
def make_mapcube_source(name, Spatial_Filename, spectrum): """Construct and return a `fermipy.roi_model.MapCubeSource` object """ data = dict(Spatial_Filename=Spatial_Filename) if spectrum is not None: data.update(spectrum) return roi_model.MapCubeSource(name, data)
python
def make_mapcube_source(name, Spatial_Filename, spectrum): """Construct and return a `fermipy.roi_model.MapCubeSource` object """ data = dict(Spatial_Filename=Spatial_Filename) if spectrum is not None: data.update(spectrum) return roi_model.MapCubeSource(name, data)
[ "def", "make_mapcube_source", "(", "name", ",", "Spatial_Filename", ",", "spectrum", ")", ":", "data", "=", "dict", "(", "Spatial_Filename", "=", "Spatial_Filename", ")", "if", "spectrum", "is", "not", "None", ":", "data", ".", "update", "(", "spectrum", ")"...
Construct and return a `fermipy.roi_model.MapCubeSource` object
[ "Construct", "and", "return", "a", "fermipy", ".", "roi_model", ".", "MapCubeSource", "object" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/source_factory.py#L34-L41
train
35,970
fermiPy/fermipy
fermipy/diffuse/source_factory.py
make_isotropic_source
def make_isotropic_source(name, Spectrum_Filename, spectrum): """Construct and return a `fermipy.roi_model.IsoSource` object """ data = dict(Spectrum_Filename=Spectrum_Filename) if spectrum is not None: data.update(spectrum) return roi_model.IsoSource(name, data)
python
def make_isotropic_source(name, Spectrum_Filename, spectrum): """Construct and return a `fermipy.roi_model.IsoSource` object """ data = dict(Spectrum_Filename=Spectrum_Filename) if spectrum is not None: data.update(spectrum) return roi_model.IsoSource(name, data)
[ "def", "make_isotropic_source", "(", "name", ",", "Spectrum_Filename", ",", "spectrum", ")", ":", "data", "=", "dict", "(", "Spectrum_Filename", "=", "Spectrum_Filename", ")", "if", "spectrum", "is", "not", "None", ":", "data", ".", "update", "(", "spectrum", ...
Construct and return a `fermipy.roi_model.IsoSource` object
[ "Construct", "and", "return", "a", "fermipy", ".", "roi_model", ".", "IsoSource", "object" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/source_factory.py#L44-L51
train
35,971
fermiPy/fermipy
fermipy/diffuse/source_factory.py
make_composite_source
def make_composite_source(name, spectrum): """Construct and return a `fermipy.roi_model.CompositeSource` object """ data = dict(SpatialType='CompositeSource', SpatialModel='CompositeSource', SourceType='CompositeSource') if spectrum is not None: data.update(spectrum) return roi_model.CompositeSource(name, data)
python
def make_composite_source(name, spectrum): """Construct and return a `fermipy.roi_model.CompositeSource` object """ data = dict(SpatialType='CompositeSource', SpatialModel='CompositeSource', SourceType='CompositeSource') if spectrum is not None: data.update(spectrum) return roi_model.CompositeSource(name, data)
[ "def", "make_composite_source", "(", "name", ",", "spectrum", ")", ":", "data", "=", "dict", "(", "SpatialType", "=", "'CompositeSource'", ",", "SpatialModel", "=", "'CompositeSource'", ",", "SourceType", "=", "'CompositeSource'", ")", "if", "spectrum", "is", "n...
Construct and return a `fermipy.roi_model.CompositeSource` object
[ "Construct", "and", "return", "a", "fermipy", ".", "roi_model", ".", "CompositeSource", "object" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/source_factory.py#L54-L62
train
35,972
fermiPy/fermipy
fermipy/diffuse/source_factory.py
make_catalog_sources
def make_catalog_sources(catalog_roi_model, source_names): """Construct and return dictionary of sources that are a subset of sources in catalog_roi_model. Parameters ---------- catalog_roi_model : dict or `fermipy.roi_model.ROIModel` Input set of sources source_names : list Names of sourcs to extract Returns dict mapping source_name to `fermipy.roi_model.Source` object """ sources = {} for source_name in source_names: sources[source_name] = catalog_roi_model[source_name] return sources
python
def make_catalog_sources(catalog_roi_model, source_names): """Construct and return dictionary of sources that are a subset of sources in catalog_roi_model. Parameters ---------- catalog_roi_model : dict or `fermipy.roi_model.ROIModel` Input set of sources source_names : list Names of sourcs to extract Returns dict mapping source_name to `fermipy.roi_model.Source` object """ sources = {} for source_name in source_names: sources[source_name] = catalog_roi_model[source_name] return sources
[ "def", "make_catalog_sources", "(", "catalog_roi_model", ",", "source_names", ")", ":", "sources", "=", "{", "}", "for", "source_name", "in", "source_names", ":", "sources", "[", "source_name", "]", "=", "catalog_roi_model", "[", "source_name", "]", "return", "s...
Construct and return dictionary of sources that are a subset of sources in catalog_roi_model. Parameters ---------- catalog_roi_model : dict or `fermipy.roi_model.ROIModel` Input set of sources source_names : list Names of sourcs to extract Returns dict mapping source_name to `fermipy.roi_model.Source` object
[ "Construct", "and", "return", "dictionary", "of", "sources", "that", "are", "a", "subset", "of", "sources", "in", "catalog_roi_model", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/source_factory.py#L65-L83
train
35,973
fermiPy/fermipy
fermipy/diffuse/source_factory.py
make_sources
def make_sources(comp_key, comp_dict): """Make dictionary mapping component keys to a source or set of sources Parameters ---------- comp_key : str Key used to access sources comp_dict : dict Information used to build sources return `OrderedDict` maping comp_key to `fermipy.roi_model.Source` """ srcdict = OrderedDict() try: comp_info = comp_dict.info except AttributeError: comp_info = comp_dict try: spectrum = comp_dict.spectrum except AttributeError: spectrum = None model_type = comp_info.model_type if model_type == 'PointSource': srcdict[comp_key] = make_point_source(comp_info.source_name, comp_info.src_dict) elif model_type == 'SpatialMap': srcdict[comp_key] = make_spatialmap_source(comp_info.source_name, comp_info.Spatial_Filename, spectrum) elif model_type == 'MapCubeSource': srcdict[comp_key] = make_mapcube_source(comp_info.source_name, comp_info.Spatial_Filename, spectrum) elif model_type == 'IsoSource': srcdict[comp_key] = make_isotropic_source(comp_info.source_name, comp_info.Spectral_Filename, spectrum) elif model_type == 'CompositeSource': srcdict[comp_key] = make_composite_source(comp_info.source_name, spectrum) elif model_type == 'CatalogSources': srcdict.update(make_catalog_sources(comp_info.roi_model, comp_info.source_names)) else: raise ValueError("Unrecognized model_type %s" % model_type) return srcdict
python
def make_sources(comp_key, comp_dict): """Make dictionary mapping component keys to a source or set of sources Parameters ---------- comp_key : str Key used to access sources comp_dict : dict Information used to build sources return `OrderedDict` maping comp_key to `fermipy.roi_model.Source` """ srcdict = OrderedDict() try: comp_info = comp_dict.info except AttributeError: comp_info = comp_dict try: spectrum = comp_dict.spectrum except AttributeError: spectrum = None model_type = comp_info.model_type if model_type == 'PointSource': srcdict[comp_key] = make_point_source(comp_info.source_name, comp_info.src_dict) elif model_type == 'SpatialMap': srcdict[comp_key] = make_spatialmap_source(comp_info.source_name, comp_info.Spatial_Filename, spectrum) elif model_type == 'MapCubeSource': srcdict[comp_key] = make_mapcube_source(comp_info.source_name, comp_info.Spatial_Filename, spectrum) elif model_type == 'IsoSource': srcdict[comp_key] = make_isotropic_source(comp_info.source_name, comp_info.Spectral_Filename, spectrum) elif model_type == 'CompositeSource': srcdict[comp_key] = make_composite_source(comp_info.source_name, spectrum) elif model_type == 'CatalogSources': srcdict.update(make_catalog_sources(comp_info.roi_model, comp_info.source_names)) else: raise ValueError("Unrecognized model_type %s" % model_type) return srcdict
[ "def", "make_sources", "(", "comp_key", ",", "comp_dict", ")", ":", "srcdict", "=", "OrderedDict", "(", ")", "try", ":", "comp_info", "=", "comp_dict", ".", "info", "except", "AttributeError", ":", "comp_info", "=", "comp_dict", "try", ":", "spectrum", "=", ...
Make dictionary mapping component keys to a source or set of sources Parameters ---------- comp_key : str Key used to access sources comp_dict : dict Information used to build sources return `OrderedDict` maping comp_key to `fermipy.roi_model.Source`
[ "Make", "dictionary", "mapping", "component", "keys", "to", "a", "source", "or", "set", "of", "sources" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/source_factory.py#L86-L135
train
35,974
fermiPy/fermipy
fermipy/diffuse/source_factory.py
SourceFactory.add_sources
def add_sources(self, source_info_dict): """Add all of the sources in source_info_dict to this factory """ self._source_info_dict.update(source_info_dict) for key, value in source_info_dict.items(): self._sources.update(make_sources(key, value))
python
def add_sources(self, source_info_dict): """Add all of the sources in source_info_dict to this factory """ self._source_info_dict.update(source_info_dict) for key, value in source_info_dict.items(): self._sources.update(make_sources(key, value))
[ "def", "add_sources", "(", "self", ",", "source_info_dict", ")", ":", "self", ".", "_source_info_dict", ".", "update", "(", "source_info_dict", ")", "for", "key", ",", "value", "in", "source_info_dict", ".", "items", "(", ")", ":", "self", ".", "_sources", ...
Add all of the sources in source_info_dict to this factory
[ "Add", "all", "of", "the", "sources", "in", "source_info_dict", "to", "this", "factory" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/source_factory.py#L158-L163
train
35,975
fermiPy/fermipy
fermipy/diffuse/source_factory.py
SourceFactory.build_catalog
def build_catalog(**kwargs): """Build a `fermipy.catalog.Catalog` object Parameters ---------- catalog_type : str Specifies catalog type, options include 2FHL | 3FGL | 4FGLP catalog_file : str FITS file with catalog tables catalog_extdir : str Path to directory with extended source templates """ catalog_type = kwargs.get('catalog_type') catalog_file = kwargs.get('catalog_file') catalog_extdir = kwargs.get('catalog_extdir') if catalog_type == '2FHL': return catalog.Catalog2FHL(fitsfile=catalog_file, extdir=catalog_extdir) elif catalog_type == '3FGL': return catalog.Catalog3FGL(fitsfile=catalog_file, extdir=catalog_extdir) elif catalog_type == '4FGLP': return catalog.Catalog4FGLP(fitsfile=catalog_file, extdir=catalog_extdir) elif catalog_type == 'FL8Y': return catalog.CatalogFL8Y(fitsfile=catalog_file, extdir=catalog_extdir) else: table = Table.read(catalog_file) return catalog.Catalog(table, extdir=catalog_extdir)
python
def build_catalog(**kwargs): """Build a `fermipy.catalog.Catalog` object Parameters ---------- catalog_type : str Specifies catalog type, options include 2FHL | 3FGL | 4FGLP catalog_file : str FITS file with catalog tables catalog_extdir : str Path to directory with extended source templates """ catalog_type = kwargs.get('catalog_type') catalog_file = kwargs.get('catalog_file') catalog_extdir = kwargs.get('catalog_extdir') if catalog_type == '2FHL': return catalog.Catalog2FHL(fitsfile=catalog_file, extdir=catalog_extdir) elif catalog_type == '3FGL': return catalog.Catalog3FGL(fitsfile=catalog_file, extdir=catalog_extdir) elif catalog_type == '4FGLP': return catalog.Catalog4FGLP(fitsfile=catalog_file, extdir=catalog_extdir) elif catalog_type == 'FL8Y': return catalog.CatalogFL8Y(fitsfile=catalog_file, extdir=catalog_extdir) else: table = Table.read(catalog_file) return catalog.Catalog(table, extdir=catalog_extdir)
[ "def", "build_catalog", "(", "*", "*", "kwargs", ")", ":", "catalog_type", "=", "kwargs", ".", "get", "(", "'catalog_type'", ")", "catalog_file", "=", "kwargs", ".", "get", "(", "'catalog_file'", ")", "catalog_extdir", "=", "kwargs", ".", "get", "(", "'cat...
Build a `fermipy.catalog.Catalog` object Parameters ---------- catalog_type : str Specifies catalog type, options include 2FHL | 3FGL | 4FGLP catalog_file : str FITS file with catalog tables catalog_extdir : str Path to directory with extended source templates
[ "Build", "a", "fermipy", ".", "catalog", ".", "Catalog", "object" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/source_factory.py#L166-L192
train
35,976
fermiPy/fermipy
fermipy/diffuse/source_factory.py
SourceFactory.make_fermipy_roi_model_from_catalogs
def make_fermipy_roi_model_from_catalogs(cataloglist): """Build and return a `fermipy.roi_model.ROIModel object from a list of fermipy.catalog.Catalog` objects """ data = dict(catalogs=cataloglist, src_roiwidth=360.) return roi_model.ROIModel(data, skydir=SkyCoord(0.0, 0.0, unit='deg'))
python
def make_fermipy_roi_model_from_catalogs(cataloglist): """Build and return a `fermipy.roi_model.ROIModel object from a list of fermipy.catalog.Catalog` objects """ data = dict(catalogs=cataloglist, src_roiwidth=360.) return roi_model.ROIModel(data, skydir=SkyCoord(0.0, 0.0, unit='deg'))
[ "def", "make_fermipy_roi_model_from_catalogs", "(", "cataloglist", ")", ":", "data", "=", "dict", "(", "catalogs", "=", "cataloglist", ",", "src_roiwidth", "=", "360.", ")", "return", "roi_model", ".", "ROIModel", "(", "data", ",", "skydir", "=", "SkyCoord", "...
Build and return a `fermipy.roi_model.ROIModel object from a list of fermipy.catalog.Catalog` objects
[ "Build", "and", "return", "a", "fermipy", ".", "roi_model", ".", "ROIModel", "object", "from", "a", "list", "of", "fermipy", ".", "catalog", ".", "Catalog", "objects" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/source_factory.py#L195-L201
train
35,977
fermiPy/fermipy
fermipy/diffuse/source_factory.py
SourceFactory.make_roi
def make_roi(cls, sources=None): """Build and return a `fermipy.roi_model.ROIModel` object from a dict with information about the sources """ if sources is None: sources = {} src_fact = cls() src_fact.add_sources(sources) ret_model = roi_model.ROIModel( {}, skydir=SkyCoord(0.0, 0.0, unit='deg')) for source in src_fact.sources.values(): ret_model.load_source(source, build_index=False, merge_sources=False) return ret_model
python
def make_roi(cls, sources=None): """Build and return a `fermipy.roi_model.ROIModel` object from a dict with information about the sources """ if sources is None: sources = {} src_fact = cls() src_fact.add_sources(sources) ret_model = roi_model.ROIModel( {}, skydir=SkyCoord(0.0, 0.0, unit='deg')) for source in src_fact.sources.values(): ret_model.load_source(source, build_index=False, merge_sources=False) return ret_model
[ "def", "make_roi", "(", "cls", ",", "sources", "=", "None", ")", ":", "if", "sources", "is", "None", ":", "sources", "=", "{", "}", "src_fact", "=", "cls", "(", ")", "src_fact", ".", "add_sources", "(", "sources", ")", "ret_model", "=", "roi_model", ...
Build and return a `fermipy.roi_model.ROIModel` object from a dict with information about the sources
[ "Build", "and", "return", "a", "fermipy", ".", "roi_model", ".", "ROIModel", "object", "from", "a", "dict", "with", "information", "about", "the", "sources" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/source_factory.py#L204-L217
train
35,978
fermiPy/fermipy
fermipy/diffuse/source_factory.py
SourceFactory.copy_selected_sources
def copy_selected_sources(cls, roi, source_names): """Build and return a `fermipy.roi_model.ROIModel` object by copying selected sources from another such object """ roi_new = cls.make_roi() for source_name in source_names: try: src_cp = roi.copy_source(source_name) except Exception: continue roi_new.load_source(src_cp, build_index=False) return roi_new
python
def copy_selected_sources(cls, roi, source_names): """Build and return a `fermipy.roi_model.ROIModel` object by copying selected sources from another such object """ roi_new = cls.make_roi() for source_name in source_names: try: src_cp = roi.copy_source(source_name) except Exception: continue roi_new.load_source(src_cp, build_index=False) return roi_new
[ "def", "copy_selected_sources", "(", "cls", ",", "roi", ",", "source_names", ")", ":", "roi_new", "=", "cls", ".", "make_roi", "(", ")", "for", "source_name", "in", "source_names", ":", "try", ":", "src_cp", "=", "roi", ".", "copy_source", "(", "source_nam...
Build and return a `fermipy.roi_model.ROIModel` object by copying selected sources from another such object
[ "Build", "and", "return", "a", "fermipy", ".", "roi_model", ".", "ROIModel", "object", "by", "copying", "selected", "sources", "from", "another", "such", "object" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/source_factory.py#L220-L231
train
35,979
fermiPy/fermipy
fermipy/diffuse/timefilter.py
MktimeFilterDict.build_from_yamlfile
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'])
python
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'])
[ "def", "build_from_yamlfile", "(", "yamlfile", ")", ":", "d", "=", "yaml", ".", "load", "(", "open", "(", "yamlfile", ")", ")", "return", "MktimeFilterDict", "(", "d", "[", "'aliases'", "]", ",", "d", "[", "'selections'", "]", ")" ]
Build a list of components from a yaml file
[ "Build", "a", "list", "of", "components", "from", "a", "yaml", "file" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/timefilter.py#L39-L43
train
35,980
fermiPy/fermipy
fermipy/scripts/dispatch.py
collect_jobs
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(runscript)[0] + '.log'), runscript=os.path.join(dirname, runscript)) if not os.path.isfile(o['cfgfile']): continue if not os.path.isfile(o['runscript']): continue if not os.path.isfile(o['logfile']): jobs.append(o) continue age = file_age_in_seconds(o['logfile']) / 60. job_status = check_log(o['logfile']) print(dirname, job_status, age) if job_status is False or overwrite: jobs.append(o) elif job_status == 'Exited': print("Job Exited. Resending command.") jobs.append(o) elif job_status == 'None' and age > max_job_age: print( "Job did not exit, but no activity on log file for > %.2f min. Resending command." % max_job_age) jobs.append(o) # elif job_status is True: # print("Job Completed. Resending command.") # jobs.append(o) return jobs
python
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(runscript)[0] + '.log'), runscript=os.path.join(dirname, runscript)) if not os.path.isfile(o['cfgfile']): continue if not os.path.isfile(o['runscript']): continue if not os.path.isfile(o['logfile']): jobs.append(o) continue age = file_age_in_seconds(o['logfile']) / 60. job_status = check_log(o['logfile']) print(dirname, job_status, age) if job_status is False or overwrite: jobs.append(o) elif job_status == 'Exited': print("Job Exited. Resending command.") jobs.append(o) elif job_status == 'None' and age > max_job_age: print( "Job did not exit, but no activity on log file for > %.2f min. Resending command." % max_job_age) jobs.append(o) # elif job_status is True: # print("Job Completed. Resending command.") # jobs.append(o) return jobs
[ "def", "collect_jobs", "(", "dirs", ",", "runscript", ",", "overwrite", "=", "False", ",", "max_job_age", "=", "90", ")", ":", "jobs", "=", "[", "]", "for", "dirname", "in", "sorted", "(", "dirs", ")", ":", "o", "=", "dict", "(", "cfgfile", "=", "o...
Construct a list of job dictionaries.
[ "Construct", "a", "list", "of", "job", "dictionaries", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/scripts/dispatch.py#L18-L58
train
35,981
fermiPy/fermipy
fermipy/srcmap_utils.py
delete_source_map
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(srcmap_file) as hdulist: hdunames = [hdu.name.upper() for hdu in hdulist] if not isinstance(names, list): names = [names] for name in names: if not name.upper() in hdunames: continue del hdulist[name.upper()] hdulist.writeto(srcmap_file, overwrite=True)
python
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(srcmap_file) as hdulist: hdunames = [hdu.name.upper() for hdu in hdulist] if not isinstance(names, list): names = [names] for name in names: if not name.upper() in hdunames: continue del hdulist[name.upper()] hdulist.writeto(srcmap_file, overwrite=True)
[ "def", "delete_source_map", "(", "srcmap_file", ",", "names", ",", "logger", "=", "None", ")", ":", "with", "fits", ".", "open", "(", "srcmap_file", ")", "as", "hdulist", ":", "hdunames", "=", "[", "hdu", ".", "name", ".", "upper", "(", ")", "for", "...
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.
[ "Delete", "a", "map", "from", "a", "binned", "analysis", "source", "map", "file", "if", "it", "exists", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/srcmap_utils.py#L380-L403
train
35,982
fermiPy/fermipy
fermipy/srcmap_utils.py
MapInterpolator.get_offsets
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): if i == 0: idx += [0] else: npix1 = int(self.shape[i]) pix0 = int(pix[i - 1]) - npix1 // 2 idx += [pix0] return idx
python
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): if i == 0: idx += [0] else: npix1 = int(self.shape[i]) pix0 = int(pix[i - 1]) - npix1 // 2 idx += [pix0] return idx
[ "def", "get_offsets", "(", "self", ",", "pix", ")", ":", "idx", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "ndim", ")", ":", "if", "i", "==", "0", ":", "idx", "+=", "[", "0", "]", "else", ":", "npix1", "=", "int", "(", "sel...
Get offset of the first pixel in each dimension in the global coordinate system. Parameters ---------- pix : `~numpy.ndarray` Pixel coordinates in global coordinate system.
[ "Get", "offset", "of", "the", "first", "pixel", "in", "each", "dimension", "in", "the", "global", "coordinate", "system", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/srcmap_utils.py#L62-L82
train
35,983
fermiPy/fermipy
fermipy/srcmap_utils.py
MapInterpolator.shift_to_coords
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_offset[i + 1] ) + (self.rebin - 1.0) / 2. dpix[i] = x - self._pix_ref[i] pos = [pix_offset[i] + self.shape[i] // 2 for i in range(self.data.ndim)] s0, s1 = utils.overlap_slices(self.shape_out, self.shape, pos) k = np.zeros(self.data.shape) for i in range(k.shape[0]): k[i] = shift(self._data_spline[i], dpix, cval=np.nan, order=2, prefilter=False) for i in range(1, len(self.shape)): k = utils.sum_bins(k, i, self.rebin) k0 = np.ones(self.shape_out) * fill_value if k[s1].size == 0 or k0[s0].size == 0: return k0 k0[s0] = k[s1] return k0
python
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_offset[i + 1] ) + (self.rebin - 1.0) / 2. dpix[i] = x - self._pix_ref[i] pos = [pix_offset[i] + self.shape[i] // 2 for i in range(self.data.ndim)] s0, s1 = utils.overlap_slices(self.shape_out, self.shape, pos) k = np.zeros(self.data.shape) for i in range(k.shape[0]): k[i] = shift(self._data_spline[i], dpix, cval=np.nan, order=2, prefilter=False) for i in range(1, len(self.shape)): k = utils.sum_bins(k, i, self.rebin) k0 = np.ones(self.shape_out) * fill_value if k[s1].size == 0 or k0[s0].size == 0: return k0 k0[s0] = k[s1] return k0
[ "def", "shift_to_coords", "(", "self", ",", "pix", ",", "fill_value", "=", "np", ".", "nan", ")", ":", "pix_offset", "=", "self", ".", "get_offsets", "(", "pix", ")", "dpix", "=", "np", ".", "zeros", "(", "len", "(", "self", ".", "shape", ")", "-",...
Create a new map that is shifted to the pixel coordinates ``pix``.
[ "Create", "a", "new", "map", "that", "is", "shifted", "to", "the", "pixel", "coordinates", "pix", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/srcmap_utils.py#L84-L112
train
35,984
fermiPy/fermipy
fermipy/srcmap_utils.py
SourceMapCache.create_map
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` The shifted map. """ k0 = self._m0.shift_to_coords(pix) k1 = self._m1.shift_to_coords(pix) k0[np.isfinite(k1)] = k1[np.isfinite(k1)] k0[~np.isfinite(k0)] = 0 return k0
python
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` The shifted map. """ k0 = self._m0.shift_to_coords(pix) k1 = self._m1.shift_to_coords(pix) k0[np.isfinite(k1)] = k1[np.isfinite(k1)] k0[~np.isfinite(k0)] = 0 return k0
[ "def", "create_map", "(", "self", ",", "pix", ")", ":", "k0", "=", "self", ".", "_m0", ".", "shift_to_coords", "(", "pix", ")", "k1", "=", "self", ".", "_m1", ".", "shift_to_coords", "(", "pix", ")", "k0", "[", "np", ".", "isfinite", "(", "k1", "...
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.
[ "Create", "a", "new", "map", "with", "reference", "pixel", "coordinates", "shifted", "to", "the", "pixel", "coordinates", "pix", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/srcmap_utils.py#L123-L142
train
35,985
fermiPy/fermipy
fermipy/version.py
render_pep440
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:])
python
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:])
[ "def", "render_pep440", "(", "vcs", ")", ":", "if", "vcs", "is", "None", ":", "return", "None", "tags", "=", "vcs", ".", "split", "(", "'-'", ")", "# Bare version number", "if", "len", "(", "tags", ")", "==", "1", ":", "return", "tags", "[", "0", "...
Convert git release tag into a form that is PEP440 compliant.
[ "Convert", "git", "release", "tag", "into", "a", "form", "that", "is", "PEP440", "compliant", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/version.py#L62-L74
train
35,986
fermiPy/fermipy
fermipy/version.py
read_release_version
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) if m: ver = m.group(1) return ver except: return None return None
python
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) if m: ver = m.group(1) return ver except: return None return None
[ "def", "read_release_version", "(", ")", ":", "import", "re", "dirname", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "try", ":", "f", "=", "open", "(", "os", ".", "path", ".", "join", ...
Read the release version from ``_version.py``.
[ "Read", "the", "release", "version", "from", "_version", ".", "py", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/version.py#L114-L131
train
35,987
fermiPy/fermipy
fermipy/version.py
write_release_version
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()
python
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()
[ "def", "write_release_version", "(", "version", ")", ":", "dirname", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "f", "=", "open", "(", "os", ".", "path", ".", "join", "(", "dirname", "...
Write the release version to ``_version.py``.
[ "Write", "the", "release", "version", "to", "_version", ".", "py", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/version.py#L134-L139
train
35,988
fermiPy/fermipy
fermipy/diffuse/gt_split_and_mktime.py
make_full_path
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 Returns ------- outpath : str This will be <basedir>:<outkey>:<newname>.fits Where newname = origname.replace('.fits', '_<outkey>.fits') """ return os.path.join(basedir, outkey, os.path.basename(origname).replace('.fits', '_%s.fits' % outkey))
python
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 Returns ------- outpath : str This will be <basedir>:<outkey>:<newname>.fits Where newname = origname.replace('.fits', '_<outkey>.fits') """ return os.path.join(basedir, outkey, os.path.basename(origname).replace('.fits', '_%s.fits' % outkey))
[ "def", "make_full_path", "(", "basedir", ",", "outkey", ",", "origname", ")", ":", "return", "os", ".", "path", ".", "join", "(", "basedir", ",", "outkey", ",", "os", ".", "path", ".", "basename", "(", "origname", ")", ".", "replace", "(", "'.fits'", ...
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 This will be <basedir>:<outkey>:<newname>.fits Where newname = origname.replace('.fits', '_<outkey>.fits')
[ "Make", "a", "full", "file", "path", "by", "combining", "tokens" ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/gt_split_and_mktime.py#L38-L63
train
35,989
fermiPy/fermipy
fermipy/utils.py
init_matplotlib_backend
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['DISPLAY'] except KeyError: matplotlib.use('Agg') else: if backend is not None: matplotlib.use(backend)
python
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['DISPLAY'] except KeyError: matplotlib.use('Agg') else: if backend is not None: matplotlib.use(backend)
[ "def", "init_matplotlib_backend", "(", "backend", "=", "None", ")", ":", "import", "matplotlib", "try", ":", "os", ".", "environ", "[", "'DISPLAY'", "]", "except", "KeyError", ":", "matplotlib", ".", "use", "(", "'Agg'", ")", "else", ":", "if", "backend", ...
This function initializes the matplotlib backend. When no DISPLAY is available the backend is automatically set to 'Agg'. Parameters ---------- backend : str matplotlib backend name.
[ "This", "function", "initializes", "the", "matplotlib", "backend", ".", "When", "no", "DISPLAY", "is", "available", "the", "backend", "is", "automatically", "set", "to", "Agg", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/utils.py#L22-L40
train
35,990
fermiPy/fermipy
fermipy/utils.py
load_data
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'): infile += '.yaml' else: raise Exception('Input file does not exist.') ext = os.path.splitext(infile)[1] if ext == '.npy': return infile, load_npy(infile) elif ext == '.yaml': return infile, load_yaml(infile) else: raise Exception('Unrecognized extension.')
python
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'): infile += '.yaml' else: raise Exception('Input file does not exist.') ext = os.path.splitext(infile)[1] if ext == '.npy': return infile, load_npy(infile) elif ext == '.yaml': return infile, load_yaml(infile) else: raise Exception('Unrecognized extension.')
[ "def", "load_data", "(", "infile", ",", "workdir", "=", "None", ")", ":", "infile", "=", "resolve_path", "(", "infile", ",", "workdir", "=", "workdir", ")", "infile", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "infile", ")", "if", "os"...
Load python data structure from either a YAML or numpy file.
[ "Load", "python", "data", "structure", "from", "either", "a", "YAML", "or", "numpy", "file", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/utils.py#L63-L82
train
35,991
fermiPy/fermipy
fermipy/utils.py
resolve_file_path_list
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] newfiles = [] for f in files: f = os.path.expandvars(f) if os.path.isfile(f): newfiles += [f] else: newfiles += [os.path.join(workdir, f)] if randomize: _, tmppath = tempfile.mkstemp(prefix=prefix, dir=workdir) else: tmppath = os.path.join(workdir, prefix) tmppath += '.txt' with open(tmppath, 'w') as tmpfile: tmpfile.write("\n".join(newfiles)) return tmppath
python
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] newfiles = [] for f in files: f = os.path.expandvars(f) if os.path.isfile(f): newfiles += [f] else: newfiles += [os.path.join(workdir, f)] if randomize: _, tmppath = tempfile.mkstemp(prefix=prefix, dir=workdir) else: tmppath = os.path.join(workdir, prefix) tmppath += '.txt' with open(tmppath, 'w') as tmpfile: tmpfile.write("\n".join(newfiles)) return tmppath
[ "def", "resolve_file_path_list", "(", "pathlist", ",", "workdir", ",", "prefix", "=", "''", ",", "randomize", "=", "False", ")", ":", "files", "=", "[", "]", "with", "open", "(", "pathlist", ",", "'r'", ")", "as", "f", ":", "files", "=", "[", "line",...
Resolve the path of each file name in the file ``pathlist`` and write the updated paths to a new file.
[ "Resolve", "the", "path", "of", "each", "file", "name", "in", "the", "file", "pathlist", "and", "write", "the", "updated", "paths", "to", "a", "new", "file", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/utils.py#L123-L149
train
35,992
fermiPy/fermipy
fermipy/utils.py
collect_dirs
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 not os.path.isdir(subdir): continue o += [subdir] if os.path.islink(subdir) and not followlinks: continue if max_depth > 0: o += collect_dirs(subdir, max_depth=max_depth - 1) return list(set(o))
python
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 not os.path.isdir(subdir): continue o += [subdir] if os.path.islink(subdir) and not followlinks: continue if max_depth > 0: o += collect_dirs(subdir, max_depth=max_depth - 1) return list(set(o))
[ "def", "collect_dirs", "(", "path", ",", "max_depth", "=", "1", ",", "followlinks", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "return", "[", "]", "o", "=", "[", "path", "]", "if", "max_depth", "==...
Recursively find directories under the given path.
[ "Recursively", "find", "directories", "under", "the", "given", "path", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/utils.py#L161-L187
train
35,993
fermiPy/fermipy
fermipy/utils.py
match_regex_list
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
python
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
[ "def", "match_regex_list", "(", "patterns", ",", "string", ")", ":", "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.
[ "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", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/utils.py#L190-L200
train
35,994
fermiPy/fermipy
fermipy/utils.py
find_rows_by_string
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. names : list List of strings. colname : str Name of the table column that will be searched for matching string. Returns ------- mask : `~numpy.ndarray` Boolean mask for rows with matching strings. """ mask = np.empty(len(tab), dtype=bool) mask.fill(False) names = [name.lower().replace(' ', '') for name in names] for colname in colnames: if colname not in tab.columns: continue col = tab[[colname]].copy() col[colname] = defchararray.replace(defchararray.lower(col[colname]).astype(str), ' ', '') for name in names: mask |= col[colname] == name return mask
python
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. names : list List of strings. colname : str Name of the table column that will be searched for matching string. Returns ------- mask : `~numpy.ndarray` Boolean mask for rows with matching strings. """ mask = np.empty(len(tab), dtype=bool) mask.fill(False) names = [name.lower().replace(' ', '') for name in names] for colname in colnames: if colname not in tab.columns: continue col = tab[[colname]].copy() col[colname] = defchararray.replace(defchararray.lower(col[colname]).astype(str), ' ', '') for name in names: mask |= col[colname] == name return mask
[ "def", "find_rows_by_string", "(", "tab", ",", "names", ",", "colnames", "=", "[", "'assoc'", "]", ")", ":", "mask", "=", "np", ".", "empty", "(", "len", "(", "tab", ")", ",", "dtype", "=", "bool", ")", "mask", ".", "fill", "(", "False", ")", "na...
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 Name of the table column that will be searched for matching string. Returns ------- mask : `~numpy.ndarray` Boolean mask for rows with matching strings.
[ "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", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/utils.py#L203-L239
train
35,995
fermiPy/fermipy
fermipy/utils.py
separation_cos_angle
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))
python
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))
[ "def", "separation_cos_angle", "(", "lon0", ",", "lat0", ",", "lon1", ",", "lat1", ")", ":", "return", "(", "np", ".", "sin", "(", "lat1", ")", "*", "np", ".", "sin", "(", "lat0", ")", "+", "np", ".", "cos", "(", "lat1", ")", "*", "np", ".", ...
Evaluate the cosine of the angular separation between two direction vectors.
[ "Evaluate", "the", "cosine", "of", "the", "angular", "separation", "between", "two", "direction", "vectors", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/utils.py#L394-L398
train
35,996
fermiPy/fermipy
fermipy/utils.py
angle_to_cartesian
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
python
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
[ "def", "angle_to_cartesian", "(", "lon", ",", "lat", ")", ":", "theta", "=", "np", ".", "array", "(", "np", ".", "pi", "/", "2.", "-", "lat", ")", "return", "np", ".", "vstack", "(", "(", "np", ".", "sin", "(", "theta", ")", "*", "np", ".", "...
Convert spherical coordinates to cartesian unit vectors.
[ "Convert", "spherical", "coordinates", "to", "cartesian", "unit", "vectors", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/utils.py#L407-L412
train
35,997
fermiPy/fermipy
fermipy/utils.py
cov_to_correlation
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. """ 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)
python
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. """ 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", ")", ":", "err", "=", "np", ".", "sqrt", "(", "np", ".", "diag", "(", "cov", ")", ")", "errinv", "=", "np", ".", "ones_like", "(", "err", ")", "*", "np", ".", "nan", "m", "=", "np", ".", "isfinite", "(",...
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", "." ]
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/utils.py#L495-L513
train
35,998
fermiPy/fermipy
fermipy/utils.py
ellipse_to_cov
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. deviation along minor axis of error ellipse. theta : float Rotation angle in radians from x-axis to ellipse major axis. """ 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]])
python
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. deviation along minor axis of error ellipse. theta : float Rotation angle in radians from x-axis to ellipse major axis. """ 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", ")", ":", "cth", "=", "np", ".", "cos", "(", "theta", ")", "sth", "=", "np", ".", "sin", "(", "theta", ")", "covxx", "=", "cth", "**", "2", "*", "sigma_maj", "**", "2", "+...
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. deviation along minor axis of error ellipse. theta : float Rotation angle in radians from x-axis to ellipse major axis.
[ "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", "erro...
9df5e7e3728307fd58c5bba36fd86783c39fbad4
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/utils.py#L516-L537
train
35,999