code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
profile_path = os.path.join(basedir, "profile_%s.yaml" % profile_name) profile_config = load_yaml(profile_path) src_name = profile_config['name'] profile_dict = profile_config['source_model'] return profile_name, src_name, profile_dict
def build_profile_dict(basedir, profile_name)
Get the name and source dictionary for the test source. Parameters ---------- basedir : str Path to the analysis directory profile_name : str Key for the spatial from of the target Returns ------- profile_name : str Name of for this particular...
3.044314
2.874646
1.059022
if DEFAULT_JOB_TYPE == 'slac': from fermipy.jobs.slac_impl import get_slac_default_args return get_slac_default_args(job_time) elif DEFAULT_JOB_TYPE == 'native': from fermipy.jobs.native_impl import get_native_default_args return get_native_default_args() return None
def get_batch_job_args(job_time=1500)
Get the correct set of batch jobs arguments. Parameters ---------- job_time : int Expected max length of the job, in seconds. This is used to select the batch queue and set the job_check_sleep parameter that sets how often we check for job completion. Returns -----...
2.993553
3.465114
0.863912
batch_job_args = get_batch_job_args(job_time) if DEFAULT_JOB_TYPE == 'slac': from fermipy.jobs.slac_impl import SlacInterface return SlacInterface(**batch_job_args) elif DEFAULT_JOB_TYPE == 'native': from fermipy.jobs.native_impl import NativeInterface return NativeInte...
def get_batch_job_interface(job_time=1500)
Create a batch job interface object. Parameters ---------- job_time : int Expected max length of the job, in seconds. This is used to select the batch queue and set the job_check_sleep parameter that sets how often we check for job completion. Returns ------- j...
2.987807
3.669775
0.814166
import sys import argparse # Argument defintion usage = "usage: %(prog)s [options]" description = "Collect all the new source" parser = argparse.ArgumentParser(usage, description=__abstract__) parser.add_argument("-i", "--input", type=argparse.FileType('r'), required=True, ...
def main()
if args.ebin == "ALL": wcsproj = hpxmap.geom.make_wcs( naxis=2, proj='MOL', energies=None, oversample=2) mapping = HpxToWcsMapping(hpxmap.hpx, wcsproj) for i, data in enumerate(hpxmap.counts): ip = ImagePlotter(data=data, proj=hpxmap.hpx, mapping=mapping) fig...
2.602846
2.308156
1.127673
CopyBaseROI.register_class() CopyBaseROI_SG.register_class() SimulateROI.register_class() SimulateROI_SG.register_class() RandomDirGen.register_class() RandomDirGen_SG.register_class()
def register_classes()
Register these classes with the `LinkFactory`
4.99781
5.197032
0.961666
for pattern in copyfiles: glob_path = os.path.join(orig_dir, pattern) files = glob.glob(glob_path) for ff in files: f = os.path.basename(ff) orig_path = os.path.join(orig_dir, f) dest_path = os.path.join(dest_dir, f) ...
def copy_analysis_files(cls, orig_dir, dest_dir, copyfiles)
Copy a list of files from orig_dir to dest_dir
1.903398
1.924474
0.989049
try: os.makedirs(dest_dir) except OSError: pass copyfiles = ['%s.fits' % roi_baseline, '%s.npy' % roi_baseline, '%s_*.xml' % roi_baseline] + cls.copyfiles if isinstance(extracopy, list): copyfiles += ...
def copy_target_dir(cls, orig_dir, dest_dir, roi_baseline, extracopy)
Create and populate directoris for target analysis
3.188967
3.308626
0.963834
args = self._parser.parse_args(argv) name_keys = dict(target_type=args.ttype, target_name=args.target, sim_name=args.sim, fullpath=True) orig_dir = NAME_FACTORY.targetdir(**name_keys) dest_dir = NAME_FA...
def run_analysis(self, argv)
Run this analysis
6.321289
6.328536
0.998855
job_configs = {} ttype = args['ttype'] (sim_targets_yaml, sim) = NAME_FACTORY.resolve_targetfile(args) targets = load_yaml(sim_targets_yaml) base_config = dict(ttype=ttype, roi_baseline=args['roi_baseline'], extraco...
def build_job_configs(self, args)
Hook to build job configurations
4.278306
4.268262
1.002353
binning = config['binning'] binsz = binning['binsz'] coordsys = binning.get('coordsys', 'GAL') roiwidth = binning['roiwidth'] proj = binning.get('proj', 'AIT') ra = config['selection']['ra'] dec = config['selection']['dec'] npix = int(np.round(ro...
def _make_wcsgeom_from_config(config)
Build a `WCS.Geom` object from a fermipy coniguration file
2.728108
2.67766
1.01884
step_x = rand_config['step_x'] step_y = rand_config['step_y'] max_x = rand_config['max_x'] max_y = rand_config['max_y'] seed = rand_config['seed'] nsims = rand_config['nsims'] cdelt = wcsgeom.wcs.wcs.cdelt pixstep_x = step_x / cdelt[0] pi...
def _build_skydir_dict(wcsgeom, rand_config)
Build a dictionary of random directions
2.149304
2.112373
1.017483
args = self._parser.parse_args(argv) if is_null(args.config): raise ValueError("Config yaml file must be specified") if is_null(args.rand_config): raise ValueError( "Random direction config yaml file must be specified") config = load_yaml...
def run_analysis(self, argv)
Run this analysis
3.752805
3.740568
1.003272
workdir = os.path.dirname(config_path) new_config_path = config_path.replace('.yaml', '_%06i.yaml' % seed) config = load_yaml(config_path) comps = config.get('components', [config]) for i, comp in enumerate(comps): comp_name = "%02i" % i if 'gtlik...
def _clone_config_and_srcmaps(config_path, seed)
Clone the configuration
2.200399
2.20903
0.996093
gta.load_roi('sim_baseline_%06i.npy' % current_seed) gta.set_random_seed(seed) gta.simulate_roi() if injected_name: gta.zero_source(injected_name) gta.optimize() gta.find_sources(sqrt_ts_threshold=5.0, search_skydir=gta.roi.skydir, ...
def _run_simulation(gta, roi_baseline, injected_name, test_sources, current_seed, seed, non_null_src)
Simulate a realization of this analysis
4.171017
4.195541
0.994155
args = self._parser.parse_args(argv) if not HAVE_ST: raise RuntimeError( "Trying to run fermipy analysis, but don't have ST") workdir = os.path.dirname(args.config) _config_file = self._clone_config_and_srcmaps(args.config, args.seed) gta =...
def run_analysis(self, argv)
Run this analysis
4.035884
4.036464
0.999856
job_configs = {} ttype = args['ttype'] (targets_yaml, sim) = NAME_FACTORY.resolve_targetfile(args) if targets_yaml is None: return job_configs config_yaml = 'config.yaml' config_override = args.get('config') if is_not_null(config_override): ...
def build_job_configs(self, args)
Hook to build job configurations
3.756018
3.742922
1.003499
job_configs = {} ttype = args['ttype'] (targets_yaml, sim) = NAME_FACTORY.resolve_targetfile(args) if targets_yaml is None: return job_configs config_yaml = 'config.yaml' config_override = args.get('config') if is_not_null(config_override): ...
def build_job_configs(self, args)
Hook to build job configurations
3.120001
3.123372
0.998921
ignore = ['pow', 'log10', 'sqrt', 'max'] branches = [] for k, v in aliases.items(): tokens = re.sub('[\(\)\+\*\/\,\=\<\>\&\!\-\|]', ' ', v).split() for t in tokens: if bool(re.search(r'^\d', t)) or len(t) <= 3: continue if bool(re.search(r'[a...
def get_branches(aliases)
Get unique branch names from an alias dictionary.
3.976238
3.7925
1.048448
if re.search('.root?', txt) is not None: c = ROOT.TChain(chain.GetName()) c.SetDirectory(0) c.Add(txt) friend_chains.append(c) chain.AddFriend(c, rand_str()) return files = np.loadtxt(txt, unpack=True, dtype='str') if files.ndim == 0: files = np...
def load_friend_chains(chain, friend_chains, txt, nfiles=None)
Load a list of trees from a file and add them as friends to the chain.
2.626627
2.574609
1.020204
from fermipy import utils ebins = None if 'ENERGIES' in hdulist: hdu = hdulist['ENERGIES'] ectr = hdu.data.field(hdu.columns[0].name) ebins = np.exp(utils.center_to_edge(np.log(ectr))) elif 'EBOUNDS' in hdulist: hdu = hdulist['EBOUNDS'] emin = hdu.data.field(...
def find_and_read_ebins(hdulist)
Reads and returns the energy bin edges. This works for both the CASE where the energies are in the ENERGIES HDU and the case where they are in the EBOUND HDU
2.408362
2.411111
0.99886
nebins = len(hdu.data) ebin_edges = np.ndarray((nebins + 1)) try: ebin_edges[0:-1] = np.log10(hdu.data.field("E_MIN")) - 3. ebin_edges[-1] = np.log10(hdu.data.field("E_MAX")[-1]) - 3. except KeyError: ebin_edges[0:-1] = np.log10(hdu.data.field("energy_MIN")) ebin_edg...
def read_energy_bounds(hdu)
Reads and returns the energy bin edges from a FITs HDU
2.071126
2.022384
1.024101
ebins = read_energy_bounds(hdu) fluxes = np.ndarray((len(ebins))) try: fluxes[0:-1] = hdu.data.field("E_MIN_FL") fluxes[-1] = hdu.data.field("E_MAX_FL")[-1] npreds = hdu.data.field("NPRED") except: fluxes = np.ones((len(ebins))) npreds = np.ones((len(ebins)))...
def read_spectral_data(hdu)
Reads and returns the energy bin edges, fluxes and npreds from a FITs HDU
2.929882
2.494006
1.174769
cols = [fits.Column("Energy", "D", unit='MeV', array=energy_vals)] hdu = fits.BinTableHDU.from_columns(cols, name=extname) return hdu
def make_energies_hdu(energy_vals, extname="ENERGIES")
Builds and returns a FITs HDU with the energy values extname : The HDU extension name
2.598012
3.251746
0.798959
f = fits.open(fitsfile) nhdu = len(f) # Try and get the energy bounds try: ebins = find_and_read_ebins(f) except: ebins = None if extname is None: # If there is an image in the Primary HDU we can return a WCS-based # projection if f[0].header['NAXIS'...
def read_projection_from_fits(fitsfile, extname=None)
Load a WCS or HPX projection.
2.204365
2.12091
1.039348
outhdulist = [fits.PrimaryHDU()] rmlist = [] for i, table in enumerate(tablelist): ft_name = "%s._%i" % (filepath, i) rmlist.append(ft_name) try: os.unlink(ft_name) except: pass table.write(ft_name, format="fits") ft_in = fits.open...
def write_tables_to_fits(filepath, tablelist, clobber=False, namelist=None, cardslist=None, hdu_list=None)
Write some astropy.table.Table objects to a single fits file
2.163943
2.189069
0.988522
options_str = [] for i, (k, v) in enumerate(sorted(options_dict.items())): option_str = '' if i == 0: option_str += '%s : %s\n' % (k, v[2].__name__) else: option_str += ' ' * 8 + '%s : %s\n' % (k, v[2].__name__) option_doc = v[1] option_doc...
def update_docstring(docstring, options_dict)
Update a method docstring by inserting option docstrings defined in the options dictionary. The input docstring should define `{options}` at the location where the options docstring block should be inserted. Parameters ---------- docstring : str Existing method docstring. options_dict...
2.240639
2.236698
1.001762
islice = slice(imin, imax) o = np.zeros(m[islice, ...].shape) ix = int(cpix[0]) iy = int(cpix[1]) # Loop over energy for i in range(m[islice, ...].shape[0]): ks = k[islice, ...][i, ...] ms = m[islice, ...][i, ...] mx = ks[ix, :] > ks[ix, iy] * threshold m...
def convolve_map(m, k, cpix, threshold=0.001, imin=0, imax=None, wmap=None)
Perform an energy-dependent convolution on a sequence of 2-D spatial maps. Parameters ---------- m : `~numpy.ndarray` 3-D map containing a sequence of 2-D spatial maps. First dimension should be energy. k : `~numpy.ndarray` 3-D map containing a sequence of convolution kernels (P...
2.457592
2.389348
1.028562
islice = slice(imin, imax) o = np.zeros(m.data.shape) nside = m.geom.nside nest = m.geom.nest # Loop over energy for i, ms in enumerate(m.data[islice, ...]): sigma = sigmas[islice][i] # Need to be in RING scheme if nest: ms = hp.pixelfunc.reorder(ms, n...
def convolve_map_hpx_gauss(m, sigmas, imin=0, imax=None, wmap=None)
Perform an energy-dependent convolution on a sequence of 2-D spatial maps. Parameters ---------- m : `HpxMap` 2-D map containing a sequence of 1-D HEALPix maps. First dimension should be energy. sigmas : `~numpy.ndarray` 1-D map containing a sequence gaussian widths for smoothin...
2.889936
2.938101
0.983607
sm = [] zs = 0 for c in gta.components: z = c.model_counts_map(name).data.astype('float') if kernel is not None: shape = (z.shape[0],) + kernel.shape z = np.apply_over_axes(np.sum, z, axes=[1, 2]) * np.ones( shape) * kernel[np.newaxis, :, :] ...
def get_source_kernel(gta, name, kernel=None)
Get the PDF for the given source.
3.271206
3.233515
1.011656
timer = Timer.create(start=True) self.logger.info('Generating residual maps') schema = ConfigSchema(self.defaults['residmap']) config = schema.create_config(self.config['residmap'], **kwargs) # Defining default properties of test source model config['model'].s...
def residmap(self, prefix='', **kwargs)
Generate 2-D spatial residual maps using the current ROI model and the convolution kernel defined with the `model` argument. Parameters ---------- prefix : str String that will be prefixed to the output residual map files. {options} Returns ...
4.726853
4.637395
1.019291
if appname in LinkFactory._class_dict: return LinkFactory._class_dict[appname].create(**kwargs) else: raise KeyError( "Could not create object associated to app %s" % appname)
def create(appname, **kwargs)
Create a `Link` of a particular class, using the kwargs as options
5.646931
4.785776
1.179941
comp_file = args.get('comp', None) datafile = args.get('data', None) if is_null(comp_file): return if is_null(datafile): return NAME_FACTORY.update_base_dict(datafile) outdir = args.get('outdir', None) outkey = args.get('outkey',...
def _map_arguments(self, args)
Map from the top-level arguments to the arguments provided to the indiviudal links
2.785696
2.73806
1.017398
data = args.get('data') comp = args.get('comp') ft1file = args.get('ft1file') scratch = args.get('scratch', None) dry_run = args.get('dry_run', None) self._set_link('split-and-bin', SplitAndBin_SG, comp=comp, data=data, ...
def _map_arguments(self, args)
Map from the top-level arguments to the arguments provided to the indiviudal links
4.044626
3.979566
1.016348
for k, v in aDict.items(): if v is None: aDict[k] = 'none'
def _replace_none(self, aDict)
Replace all None values in a dict with 'none'
2.684974
2.081424
1.28997
dsval = kwargs.get('dataset', self.dataset(**kwargs)) tokens = dsval.split('_') irf_name = "%s_%s_%s" % (DATASET_DICTIONARY['%s_%s' % (tokens[0], tokens[1])], EVCLASS_NAME_DICTIONARY[tokens[3]], kwargs.get('irf_ver')) ...
def irfs(self, **kwargs)
Get the name of IFRs associted with a particular dataset
6.592806
6.014093
1.096226
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) try: return NameFactory.dataset_format.format(**kwargs_copy) except KeyError: return None
def dataset(self, **kwargs)
Return a key that specifies the data selection
5.83026
5.452371
1.069307
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) try: return NameFactory.component_format.format(**kwargs_copy) except KeyError: return None
def component(self, **kwargs)
Return a key that specifies data the sub-selection
6.21059
6.074118
1.022468
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) try: return NameFactory.sourcekey_format.format(**kwargs_copy) except KeyError: return None
def sourcekey(self, **kwargs)
Return a key that specifies the name and version of a source or component
5.680584
5.583528
1.017383
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) try: return NameFactory.galprop_ringkey_format.format(**kwargs_copy) except KeyError: return None
def galprop_ringkey(self, **kwargs)
return the sourcekey for galprop input maps : specifies the component and ring
5.410459
5.295857
1.02164
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) try: return NameFactory.galprop_sourcekey_format.format(**kwargs_copy) except KeyError: return None
def galprop_sourcekey(self, **kwargs)
return the sourcekey for merged galprop maps : specifies the merged component and merging scheme
5.273317
5.309855
0.993119
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) try: return NameFactory.merged_sourcekey_format.format(**kwargs_copy) except KeyError: return None
def merged_sourcekey(self, **kwargs)
return the sourcekey for merged sets of point sources : specifies the catalog and merging rule
5.319647
5.487777
0.969363
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) localpath = NameFactory.galprop_gasmap_format.format(**kwargs_copy) if kwargs.get('fullpath', False): return self.fullpath(localpath=localpath) re...
def galprop_gasmap(self, **kwargs)
return the file name for Galprop input gasmaps
5.438329
5.165104
1.052898
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) localpath = NameFactory.merged_gasmap_format.format(**kwargs_copy) if kwargs.get('fullpath', False): return self.fullpath(localpath=localpath) ret...
def merged_gasmap(self, **kwargs)
return the file name for Galprop merged gasmaps
5.56413
5.225203
1.064864
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) localpath = NameFactory.diffuse_template_format.format(**kwargs_copy) if kwargs.get('fullpath', False): return self.fullpath(localpath=localpath) ...
def diffuse_template(self, **kwargs)
return the file name for other diffuse map templates
5.58671
5.334046
1.047368
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) localpath = NameFactory.spectral_template_format.format(**kwargs_copy) if kwargs.get('fullpath', False): return self.fullpath(localpath=localpath) return localpath
def spectral_template(self, **kwargs)
return the file name for spectral templates
5.428024
4.853129
1.118459
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) localpath = NameFactory.srcmdl_xml_format.format(**kwargs_copy) if kwargs.get('fullpath', False): return self.fullpath(localpath=localpath) return localpath
def srcmdl_xml(self, **kwargs)
return the file name for source model xml files
5.015269
4.749602
1.055935
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) localpath = NameFactory.nested_srcmdl_xml_format.format(**kwargs_copy) if kwargs.get('fullpath', False): return self.fullpath(localpath=localpath) ...
def nested_srcmdl_xml(self, **kwargs)
return the file name for source model xml files of nested sources
5.12751
4.868155
1.053276
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) self._replace_none(kwargs_copy) localpath = NameFactory.ft1file_format.format(**kwargs_copy) if kwargs.get('fullpath', ...
def ft1file(self, **kwargs)
return the name of the input ft1 file list
4.99646
4.904219
1.018809
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['data_time'] = kwargs.get( 'data_time', self.dataset(**kwargs)) self._replace_none(kwargs_copy) localpath = NameFactory.ft2file_format.format(**kwargs_copy) if kwargs...
def ft2file(self, **kwargs)
return the name of the input ft2 file list
5.649732
5.558366
1.016437
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) localpath = NameFactory.ltcube_format.format(**kwargs_copy) if kwargs.get('fullpath', False): return self.fullpath(localpat...
def ltcube(self, **kwargs)
return the name of a livetime cube file
5.217741
4.778446
1.091932
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) kwargs_copy['component'] = kwargs.get( 'component', self.component(**kwargs)) self._replace_none(kwargs_copy) ...
def select(self, **kwargs)
return the name of a selected events ft1file
4.629521
4.539134
1.019913
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) kwargs_copy['component'] = kwargs.get( 'component', self.component(**kwargs)) self._replace_none(kwargs_copy) ...
def mktime(self, **kwargs)
return the name of a selected events ft1file
4.643551
4.502839
1.03125
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) kwargs_copy['component'] = kwargs.get( 'component', self.component(**kwargs)) localpath = NameFactory.ccube_format.format(*...
def ccube(self, **kwargs)
return the name of a counts cube file
4.166788
3.936048
1.058622
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) kwargs_copy['component'] = kwargs.get( 'component', self.component(**kwargs)) self._replace_none(kwargs_copy) ...
def bexpcube(self, **kwargs)
return the name of a binned exposure cube file
4.479274
4.284448
1.045473
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) kwargs_copy['component'] = kwargs.get( 'component', self.component(**kwargs)) self._replace_none(kwargs_copy) ...
def srcmaps(self, **kwargs)
return the name of a source map file
4.433913
4.416672
1.003904
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) kwargs_copy['component'] = kwargs.get( 'component', self.component(**kwargs)) self._replace_none(kwargs_copy) ...
def mcube(self, **kwargs)
return the name of a model cube file
4.437266
4.305578
1.030585
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) self._replace_none(kwargs_copy) localpath = NameFactory.ltcubesun_format.format(**kwargs_copy) if kwargs.get('fullpath'...
def ltcube_sun(self, **kwargs)
return the name of a livetime cube file
6.012344
5.574208
1.078601
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) self._replace_none(kwargs_copy) localpath = NameFactory.ltcubemoon_format.format(**kwargs_copy) if kwargs.get('fullpath...
def ltcube_moon(self, **kwargs)
return the name of a livetime cube file
6.091589
5.725101
1.064014
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) kwargs_copy['component'] = kwargs.get( 'component', self.component(**kwargs)) self._replace_none(kwargs_copy) ...
def bexpcube_sun(self, **kwargs)
return the name of a binned exposure cube file
4.884633
4.645716
1.051427
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) kwargs_copy['component'] = kwargs.get( 'component', self.component(**kwargs)) self._replace_none(kwargs_copy) ...
def bexpcube_moon(self, **kwargs)
return the name of a binned exposure cube file
5.045954
4.878186
1.034391
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) localpath = NameFactory.angprofile_format.format(**kwargs_copy) if kwargs.get('fullpath', False): return self.fullpath(localpath=localpath) return...
def angprofile(self, **kwargs)
return the file name for sun or moon angular profiles
5.778082
5.373333
1.075326
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) kwargs_copy['component'] = kwargs.get( 'component', self.component(**kwargs)) self._replace_none(kwargs_copy) ...
def template_sunmoon(self, **kwargs)
return the file name for sun or moon template files
4.807616
4.735126
1.015309
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) kwargs_copy['component'] = kwargs.get( 'component', self.component(**kwargs)) localpath = NameFactory.residual_cr_format.fo...
def residual_cr(self, **kwargs)
Return the name of the residual CR analysis output files
4.449659
4.090839
1.087713
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) localpath = NameFactory.galprop_rings_yaml_format.format(**kwargs_copy) if kwargs.get('fullpath', False): return self.fullpath(localpath=localpath) ...
def galprop_rings_yaml(self, **kwargs)
return the name of a galprop rings merging yaml file
5.171557
5.029419
1.028261
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) localpath = NameFactory.catalog_split_yaml_format.format(**kwargs_copy) if kwargs.get('fullpath', False): return self.fullpath(localpath=localpath) ...
def catalog_split_yaml(self, **kwargs)
return the name of a catalog split yaml file
5.189786
4.87978
1.063529
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) localpath = NameFactory.model_yaml_format.format(**kwargs_copy) if kwargs.get('fullpath', False): return self.fullpath(localpath=localpath) return...
def model_yaml(self, **kwargs)
return the name of a model yaml file
5.518291
5.156744
1.070111
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) kwargs_copy['component'] = kwargs.get( 'component', self.component(**kwargs)) self._replace_none(kwargs_copy) ...
def merged_srcmaps(self, **kwargs)
return the name of a source map file
4.501946
4.446039
1.012575
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) localpath = NameFactory.master_srcmdl_xml_format.format(**kwargs_copy) if kwargs.get('fullpath', False): return self.fullpath(localpath=localpath) ...
def master_srcmdl_xml(self, **kwargs)
return the name of a source model file
5.091492
5.12796
0.992888
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) kwargs_copy['component'] = kwargs.get( 'component', self.component(**kwargs)) self._replace_none(kwargs_copy) ...
def comp_srcmdl_xml(self, **kwargs)
return the name of a source model file
4.257224
4.194346
1.014991
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) return NameFactory.fullpath_format.format(**kwargs_copy)
def fullpath(self, **kwargs)
Return a full path name for a given file
6.481748
6.190708
1.047012
kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) kwargs_copy['dataset'] = kwargs.get('dataset', self.dataset(**kwargs)) kwargs_copy['component'] = kwargs.get( 'component', self.component(**kwargs)) self._replace_none(kwargs_copy) ...
def generic(self, input_string, **kwargs)
return a generic filename for a given dataset and component
3.833001
3.298757
1.161953
out_dict = dict(ft1file=self.ft1file(**kwargs), ltcube=self.ltcube(**kwargs), ccube=self.ccube(**kwargs), bexpcube=self.bexpcube(**kwargs), srcmaps=self.srcmaps(**kwargs), mcube=self....
def make_filenames(self, **kwargs)
Make a dictionary of filenames for various types
4.153132
4.191762
0.990784
data = args.get('data') comp = args.get('comp') library = args.get('library') dry_run = args.get('dry_run', False) self._set_link('sum-rings', SumRings_SG, library=library, outdir=args['outdir'], dry_r...
def _map_arguments(self, args)
Map from the top-level arguments to the arguments provided to the indiviudal links
4.146354
3.976834
1.042627
data = args.get('data') comp = args.get('comp') library = args.get('library') dry_run = args.get('dry_run', False) self._set_link('srcmaps-catalog', SrcmapsCatalog_SG, comp=comp, data=data, library=library, ...
def _map_arguments(self, args)
Map from the top-level arguments to the arguments provided to the indiviudal links
3.333812
3.259785
1.022709
config_yaml = args['config'] config_dict = load_yaml(config_yaml) dry_run = args.get('dry_run', False) data = config_dict.get('data') comp = config_dict.get('comp') library = config_dict.get('library') models = config_dict.get('models') scratch ...
def _map_arguments(self, args)
Map from the top-level arguments to the arguments provided to the indiviudal links
3.064277
3.05764
1.002171
if fn is None: fn = pyLike.SourceFactory_funcFactory().create(str(spectrum_type)) if spectrum_type == 'PiecewisePowerLaw': build_piecewise_powerlaw(fn, spectral_pars) for k, v in spectral_pars.items(): v.setdefault('scale', 1.0) v.setdefault('min', v['value']...
def create_spectrum_from_dict(spectrum_type, spectral_pars, fn=None)
Create a Function object from a parameter dictionary. Parameters ---------- spectrum_type : str String identifying the spectrum type (e.g. PowerLaw). spectral_pars : dict Dictionary of spectral parameters.
3.191875
3.170016
1.006895
parameters = pyLike.ParameterVector() spectrum.getParams(parameters) d = dict(spectrum_type=spectrum.genericName()) for p in parameters: pname = p.getName() pval = p.getTrueValue() perr = abs(p.error() * p.getScale()) if p.isFree() else np.nan d[pname] = np.array([p...
def gtlike_spectrum_to_dict(spectrum)
Convert a pyLikelihood object to a python dictionary which can be easily saved to a file.
5.139487
5.065882
1.01453
parameters = pyLike.ParameterVector() spectrum.getParams(parameters) npar = max(parameters.size(), 10) o = {'param_names': np.zeros(npar, dtype='S32'), 'param_values': np.empty(npar, dtype=float) * np.nan, 'param_errors': np.empty(npar, dtype=float) * np.nan, } fo...
def gtlike_spectrum_to_vectors(spectrum)
Convert a pyLikelihood object to a python dictionary which can be easily saved to a file.
2.981294
2.837317
1.050744
pars = [] par_names = pyLike.StringVector() fn.getParamNames(par_names) for pname in par_names: par = fn.getParam(pname) bounds = par.getBounds() perr = par.error() if par.isFree() else np.nan pars += [dict(name=pname, value=par.getValue(), ...
def get_function_pars(fn)
Extract the parameters of a pyLikelihood function object (value, scale, bounds). Parameters ---------- fn : pyLikelihood.Function Returns ------- pars : list
3.319301
3.377923
0.982646
npar = len(like.params()) vals = np.ones(npar) errs = np.ones(npar) has_prior = np.array([False] * npar) for i, p in enumerate(like.params()): prior = like[i].log_prior() if prior is None: continue par_names = pyLike.StringVector() prior.getPara...
def get_priors(like)
Extract priors from a likelihood object.
2.907206
2.841166
1.023244
fnmap = src.getSrcFuncs() keys = fnmap.keys() if 'Position' in keys: ppars = get_function_pars(src.getSrcFuncs()[str('Position')]) elif 'SpatialDist' in keys: ppars = get_function_pars(src.getSrcFuncs()[str('SpatialDist')]) else: raise Exception('Failed to extract spa...
def get_source_pars(src)
Extract the parameters associated with a pyLikelihood Source object.
3.393913
3.211129
1.056922
nF = 0 pars = self.params() for par in pars: if par.isFree(): nF += 1 return nF
def nFreeParams(self)
Count the number of free parameters in the active model.
3.343074
3.015517
1.108624
saved_state = LikelihoodState(self) if verbosity > 0: print("*** Start Ts_dl ***") source_attributes = self.getExtraSourceAttributes() self.logLike.syncParams() src = self.logLike.getSource(srcName) self._ts_src = src freeParams = pyLike.Doub...
def Ts2(self, srcName, reoptimize=False, approx=True, tol=None, MaxIterations=10, verbosity=0)
Computes the TS value for a source indicated by "srcName." If "reoptimize=True" is selected this function will reoptimize the model up to "MaxIterations" given the tolerance "tol" (default is the tolerance selected for the overall fit). If "appox=True" is selected (the default) it will...
4.009394
3.96013
1.01244
logfile = job_config.get('logfile', "%s_%s_%s.log" % (cls.default_prefix_logfile, linkname, key)) job_config['logfile'] = logfile
def _make_scatter_logfile_name(cls, key, linkname, job_config)
Hook to inster the name of a logfile into the input config
4.577169
3.998481
1.144727
linkname = kwargs.setdefault('linkname', cls.clientclass.linkname_default) # Don't use setdefault b/c we don't want to build a JobArchive # Unless it is needed job_archive = kwargs.get('job_archive', None) if job_archive is None: job_archive = JobArchive.buil...
def create(cls, **kwargs)
Build and return a `ScatterGather` object
4.899405
4.768774
1.027393
self.files.file_dict.clear() self.sub_files.file_dict.clear() self.files.latch_file_info(self.args) self._scatter_link._update_sub_file_dict(self.sub_files)
def _latch_file_info(self)
Internal function to update the dictionaries keeping track of input and output files
7.666488
6.252975
1.226054
status_vect = JobStatusVector() for job_key, job_details in link.jobs.items(): # if job_details.status == JobStatus.failed: # failed = True # continue # elif job_details.status == JobStatus.done: # continue if job...
def _check_link_completion(self, link, fail_pending=False, fail_running=False)
Internal function to check the completion of all the dispatched jobs Returns ------- status_vect : `JobStatusVector` Vector that summarize the number of jobs in various states.
3.027832
2.704639
1.119496
if self.args['dry_run']: status = JobStatus.unknown else: status = JobStatus.not_ready base_config = self.scatter_link.args for jobkey, job_config in sorted(self._job_configs.items()): full_job_config = base_config.copy() full_jo...
def _build_job_dict(self)
Build a dictionary of `JobDetails` objects for the internal `Link`
5.328337
5.134775
1.037696
if resubmit_failed: self.args['action'] = 'resubmit' argv = self._make_argv() if dry_run: argv.append('--dry_run') self._invoke(argv, stream, resubmit_failed=resubmit_failed)
def _run_link(self, stream=sys.stdout, dry_run=False, stage_files=True, resubmit_failed=False)
Internal function that actually runs this link. This checks if input and output files are present. If input files are missing this will raise `OSError` if dry_run is False If all output files are present this will skip execution. Parameters ----------- stream : `file` ...
3.653907
4.546087
0.803748
args = self._run_argparser(argv) if args.action not in ACTIONS: sys.stderr.write( "Unrecognized action %s, options are %s\n" % (args.action, ACTIONS)) if args.action == 'skip': return JobStatus.no_job elif args.action in ['run', 'resubmi...
def _invoke(self, argv, stream=sys.stdout, resubmit_failed=False)
Invoke this object to preform a particular action Parameters ---------- argv : list List of command line arguments, passed to helper classes stream : `file` Stream that this function will print to, must have 'write' function. resubmit_faile...
3.162926
2.92626
1.080876
self.args = extract_arguments(override_args, self.args) self._job_configs = self.build_job_configs(self.args) if not self._scatter_link.jobs: self._build_job_dict() self._latch_file_info()
def update_args(self, override_args)
Update the arguments used to invoke the application Note that this will also update the dictionary of input and output files Parameters ---------- override_args : dict dictionary of arguments to override the current values
9.182618
10.194831
0.900713
if recursive: self._scatter_link.clear_jobs(recursive) self.jobs.clear()
def clear_jobs(self, recursive=True)
Clear the self.jobs dictionary that contains information about jobs associated with this `ScatterGather` If recursive is True this will include jobs from all internal `Link`
11.184148
9.5645
1.16934
if recursive: ret_dict = self.jobs.copy() ret_dict.update(self._scatter_link.get_jobs(recursive)) return ret_dict return self.jobs
def get_jobs(self, recursive=True)
Return a dictionary with all the jobs If recursive is True this will include jobs from all internal `Link`
5.430427
5.18699
1.046932
running = True first = True if not check_once: if stream != sys.stdout: sys.stdout.write('Checking status (%is): ' % self.args['job_check_sleep']) sys.stdout.flush() status_vect = JobStatusVector() ...
def check_status(self, stream=sys.stdout, check_once=False, fail_pending=False, fail_running=False, no_wait=False, do_print=True, write_status=False)
Loop to check on the status of all the jobs in job dict. Parameters ----------- stream : `file` Stream that this function will print to, Must have 'write' function. check_once : bool Check status once and exit loop. fail_pending : `bool` ...
2.901278
2.835777
1.023098
self._build_job_dict() self._interface._dry_run = self.args['dry_run'] scatter_status = self._interface.submit_jobs(self.scatter_link, job_archive=self._job_archive, stream=stream)...
def run_jobs(self, stream=sys.stdout, resubmit_failed=False)
Function to dipatch jobs and collect results Parameters ----------- stream : `file` Stream that this function will print to, Must have 'write' function. resubmit_failed : bool Resubmit failed jobs. Returns ------- status_vect...
4.76973
4.660319
1.023477
self._build_job_dict() status_vect = self.check_status(stream, check_once=True, fail_pending=True, fail_running=fail_running) status = status_vect.get_status() if status == JobStatus.done: return status failed_jobs = s...
def resubmit(self, stream=sys.stdout, fail_running=False, resubmit_failed=False)
Function to resubmit failed jobs and collect results Parameters ----------- stream : `file` Stream that this function will print to, Must have 'write' function. fail_running : `bool` If True, consider running jobs as failed resubmit_failed :...
3.536144
3.559484
0.993443
self._interface.clean_jobs(self.scatter_link, clean_all=recursive)
def clean_jobs(self, recursive=False)
Clean up all the jobs associated with this object. If recursive is True this also clean jobs dispatch by this object.
28.784554
28.237968
1.019356
Link.print_summary(self, stream, indent, recurse_level) if recurse_level > 0: recurse_level -= 1 indent += " " stream.write("\n") self._scatter_link.print_summary(stream, indent, recurse_level)
def print_summary(self, stream=sys.stdout, indent="", recurse_level=2)
Print a summary of the activity done by this `Link`. Parameters ---------- stream : `file` Stream to print to indent : str Indentation at start of line recurse_level : int Number of recursion levels to print
3.39113
3.460793
0.979871
if job_stats is None: job_stats = JobStatusVector() job_det_list = [] job_det_list += self._scatter_link.jobs.values() for job_dets in job_det_list: if job_dets.status == JobStatus.no_job: continue job_...
def print_update(self, stream=sys.stdout, job_stats=None)
Print an update about the current number of jobs running
2.506565
2.480028
1.0107
for job_key, job_details in sorted(self.scatter_link.jobs.items()): if job_details.status == JobStatus.failed: stream.write("Failed job %s\n log = %s\n" % (job_key, job_details.logfile))
def print_failed(self, stream=sys.stderr)
Print list of the failed jobs
5.89813
5.21576
1.130829