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/jobs/chain.py | Chain.run | def run(self, stream=sys.stdout, dry_run=False,
stage_files=True, resubmit_failed=False):
"""Runs this `Chain`.
Parameters
-----------
stream : `file`
Stream that this `Link` will print to,
Must have 'write' function
dry_run : bool
Print command but do not run it.
stage_files : bool
Copy files to and from scratch staging area.
resubmit_failed : bool
Flag for sub-classes to resubmit failed jobs.
"""
self._run_chain(stream, dry_run, stage_files,
resubmit_failed=resubmit_failed) | python | def run(self, stream=sys.stdout, dry_run=False,
stage_files=True, resubmit_failed=False):
"""Runs this `Chain`.
Parameters
-----------
stream : `file`
Stream that this `Link` will print to,
Must have 'write' function
dry_run : bool
Print command but do not run it.
stage_files : bool
Copy files to and from scratch staging area.
resubmit_failed : bool
Flag for sub-classes to resubmit failed jobs.
"""
self._run_chain(stream, dry_run, stage_files,
resubmit_failed=resubmit_failed) | [
"def",
"run",
"(",
"self",
",",
"stream",
"=",
"sys",
".",
"stdout",
",",
"dry_run",
"=",
"False",
",",
"stage_files",
"=",
"True",
",",
"resubmit_failed",
"=",
"False",
")",
":",
"self",
".",
"_run_chain",
"(",
"stream",
",",
"dry_run",
",",
"stage_fi... | Runs this `Chain`.
Parameters
-----------
stream : `file`
Stream that this `Link` will print to,
Must have 'write' function
dry_run : bool
Print command but do not run it.
stage_files : bool
Copy files to and from scratch staging area.
resubmit_failed : bool
Flag for sub-classes to resubmit failed jobs. | [
"Runs",
"this",
"Chain",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/chain.py#L322-L343 | train | 36,100 |
fermiPy/fermipy | fermipy/jobs/chain.py | Chain.print_status | def print_status(self, indent="", recurse=False):
"""Print a summary of the job status for each `Link` in this `Chain`"""
print ("%s%30s : %15s : %20s" %
(indent, "Linkname", "Link Status", "Jobs Status"))
for link in self._links.values():
if hasattr(link, 'check_status'):
status_vect = link.check_status(
stream=sys.stdout, no_wait=True, do_print=False)
else:
status_vect = None
key = JobDetails.make_fullkey(link.full_linkname)
link_status = JOB_STATUS_STRINGS[link.check_job_status(key)]
if status_vect is None:
jobs_status = JOB_STATUS_STRINGS[link.check_jobs_status()]
else:
jobs_status = status_vect
print ("%s%30s : %15s : %20s" %
(indent, link.linkname, link_status, jobs_status))
if hasattr(link, 'print_status') and recurse:
print ("---------- %30s -----------" % link.linkname)
link.print_status(indent + " ", recurse=True)
print ("------------------------------------------------") | python | def print_status(self, indent="", recurse=False):
"""Print a summary of the job status for each `Link` in this `Chain`"""
print ("%s%30s : %15s : %20s" %
(indent, "Linkname", "Link Status", "Jobs Status"))
for link in self._links.values():
if hasattr(link, 'check_status'):
status_vect = link.check_status(
stream=sys.stdout, no_wait=True, do_print=False)
else:
status_vect = None
key = JobDetails.make_fullkey(link.full_linkname)
link_status = JOB_STATUS_STRINGS[link.check_job_status(key)]
if status_vect is None:
jobs_status = JOB_STATUS_STRINGS[link.check_jobs_status()]
else:
jobs_status = status_vect
print ("%s%30s : %15s : %20s" %
(indent, link.linkname, link_status, jobs_status))
if hasattr(link, 'print_status') and recurse:
print ("---------- %30s -----------" % link.linkname)
link.print_status(indent + " ", recurse=True)
print ("------------------------------------------------") | [
"def",
"print_status",
"(",
"self",
",",
"indent",
"=",
"\"\"",
",",
"recurse",
"=",
"False",
")",
":",
"print",
"(",
"\"%s%30s : %15s : %20s\"",
"%",
"(",
"indent",
",",
"\"Linkname\"",
",",
"\"Link Status\"",
",",
"\"Jobs Status\"",
")",
")",
"for",
"link"... | Print a summary of the job status for each `Link` in this `Chain` | [
"Print",
"a",
"summary",
"of",
"the",
"job",
"status",
"for",
"each",
"Link",
"in",
"this",
"Chain"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/chain.py#L367-L388 | train | 36,101 |
fermiPy/fermipy | fermipy/jobs/chain.py | Chain.print_summary | def print_summary(self, stream=sys.stdout, indent="", recurse_level=2):
"""Print a summary of the activity done by this `Chain`.
Parameters
-----------
stream : `file`
Stream to print to, must have 'write' method.
indent : str
Indentation at start of line
recurse_level : int
Number of recursion levels to print
"""
Link.print_summary(self, stream, indent, recurse_level)
if recurse_level > 0:
recurse_level -= 1
indent += " "
for link in self._links.values():
stream.write("\n")
link.print_summary(stream, indent, recurse_level) | python | def print_summary(self, stream=sys.stdout, indent="", recurse_level=2):
"""Print a summary of the activity done by this `Chain`.
Parameters
-----------
stream : `file`
Stream to print to, must have 'write' method.
indent : str
Indentation at start of line
recurse_level : int
Number of recursion levels to print
"""
Link.print_summary(self, stream, indent, recurse_level)
if recurse_level > 0:
recurse_level -= 1
indent += " "
for link in self._links.values():
stream.write("\n")
link.print_summary(stream, indent, recurse_level) | [
"def",
"print_summary",
"(",
"self",
",",
"stream",
"=",
"sys",
".",
"stdout",
",",
"indent",
"=",
"\"\"",
",",
"recurse_level",
"=",
"2",
")",
":",
"Link",
".",
"print_summary",
"(",
"self",
",",
"stream",
",",
"indent",
",",
"recurse_level",
")",
"if... | Print a summary of the activity done by this `Chain`.
Parameters
-----------
stream : `file`
Stream to print to, must have 'write' method.
indent : str
Indentation at start of line
recurse_level : int
Number of recursion levels to print | [
"Print",
"a",
"summary",
"of",
"the",
"activity",
"done",
"by",
"this",
"Chain",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/chain.py#L390-L412 | train | 36,102 |
fermiPy/fermipy | fermipy/diffuse/model_component.py | ModelComponentInfo.get_component_info | def get_component_info(self, comp):
"""Return the information about sub-component specific to a particular data selection
Parameters
----------
comp : `binning.Component` object
Specifies the sub-component
Returns `ModelComponentInfo` object
"""
if self.components is None:
raise ValueError(
'Model component %s does not have sub-components' % self.sourcekey)
if self.moving:
comp_key = "zmax%i" % (comp.zmax)
elif self.selection_dependent:
comp_key = comp.make_key('{ebin_name}_{evtype_name}')
else:
raise ValueError(
'Model component %s is not moving or selection dependent' % self.sourcekey)
return self.components[comp_key] | python | def get_component_info(self, comp):
"""Return the information about sub-component specific to a particular data selection
Parameters
----------
comp : `binning.Component` object
Specifies the sub-component
Returns `ModelComponentInfo` object
"""
if self.components is None:
raise ValueError(
'Model component %s does not have sub-components' % self.sourcekey)
if self.moving:
comp_key = "zmax%i" % (comp.zmax)
elif self.selection_dependent:
comp_key = comp.make_key('{ebin_name}_{evtype_name}')
else:
raise ValueError(
'Model component %s is not moving or selection dependent' % self.sourcekey)
return self.components[comp_key] | [
"def",
"get_component_info",
"(",
"self",
",",
"comp",
")",
":",
"if",
"self",
".",
"components",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Model component %s does not have sub-components'",
"%",
"self",
".",
"sourcekey",
")",
"if",
"self",
".",
"moving",... | Return the information about sub-component specific to a particular data selection
Parameters
----------
comp : `binning.Component` object
Specifies the sub-component
Returns `ModelComponentInfo` object | [
"Return",
"the",
"information",
"about",
"sub",
"-",
"component",
"specific",
"to",
"a",
"particular",
"data",
"selection"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/model_component.py#L138-L159 | train | 36,103 |
fermiPy/fermipy | fermipy/diffuse/model_component.py | ModelComponentInfo.add_component_info | def add_component_info(self, compinfo):
"""Add sub-component specific information to a particular data selection
Parameters
----------
compinfo : `ModelComponentInfo` object
Sub-component being added
"""
if self.components is None:
self.components = {}
self.components[compinfo.comp_key] = compinfo | python | def add_component_info(self, compinfo):
"""Add sub-component specific information to a particular data selection
Parameters
----------
compinfo : `ModelComponentInfo` object
Sub-component being added
"""
if self.components is None:
self.components = {}
self.components[compinfo.comp_key] = compinfo | [
"def",
"add_component_info",
"(",
"self",
",",
"compinfo",
")",
":",
"if",
"self",
".",
"components",
"is",
"None",
":",
"self",
".",
"components",
"=",
"{",
"}",
"self",
".",
"components",
"[",
"compinfo",
".",
"comp_key",
"]",
"=",
"compinfo"
] | Add sub-component specific information to a particular data selection
Parameters
----------
compinfo : `ModelComponentInfo` object
Sub-component being added | [
"Add",
"sub",
"-",
"component",
"specific",
"information",
"to",
"a",
"particular",
"data",
"selection"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/model_component.py#L161-L172 | train | 36,104 |
fermiPy/fermipy | fermipy/diffuse/model_component.py | ModelComponentInfo.clone_and_merge_sub | def clone_and_merge_sub(self, key):
"""Clones self and merges clone with sub-component specific information
Parameters
----------
key : str
Key specifying which sub-component
Returns `ModelComponentInfo` object
"""
new_comp = copy.deepcopy(self)
#sub_com = self.components[key]
new_comp.components = None
new_comp.comp_key = key
return new_comp | python | def clone_and_merge_sub(self, key):
"""Clones self and merges clone with sub-component specific information
Parameters
----------
key : str
Key specifying which sub-component
Returns `ModelComponentInfo` object
"""
new_comp = copy.deepcopy(self)
#sub_com = self.components[key]
new_comp.components = None
new_comp.comp_key = key
return new_comp | [
"def",
"clone_and_merge_sub",
"(",
"self",
",",
"key",
")",
":",
"new_comp",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"#sub_com = self.components[key]",
"new_comp",
".",
"components",
"=",
"None",
"new_comp",
".",
"comp_key",
"=",
"key",
"return",
"new_... | Clones self and merges clone with sub-component specific information
Parameters
----------
key : str
Key specifying which sub-component
Returns `ModelComponentInfo` object | [
"Clones",
"self",
"and",
"merges",
"clone",
"with",
"sub",
"-",
"component",
"specific",
"information"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/model_component.py#L174-L189 | train | 36,105 |
fermiPy/fermipy | fermipy/catalog.py | add_columns | def add_columns(t0, t1):
"""Add columns of table t1 to table t0."""
for colname in t1.colnames:
col = t1.columns[colname]
if colname in t0.columns:
continue
new_col = Column(name=col.name, length=len(t0), dtype=col.dtype) # ,
# shape=col.shape)
t0.add_column(new_col) | python | def add_columns(t0, t1):
"""Add columns of table t1 to table t0."""
for colname in t1.colnames:
col = t1.columns[colname]
if colname in t0.columns:
continue
new_col = Column(name=col.name, length=len(t0), dtype=col.dtype) # ,
# shape=col.shape)
t0.add_column(new_col) | [
"def",
"add_columns",
"(",
"t0",
",",
"t1",
")",
":",
"for",
"colname",
"in",
"t1",
".",
"colnames",
":",
"col",
"=",
"t1",
".",
"columns",
"[",
"colname",
"]",
"if",
"colname",
"in",
"t0",
".",
"columns",
":",
"continue",
"new_col",
"=",
"Column",
... | Add columns of table t1 to table t0. | [
"Add",
"columns",
"of",
"table",
"t1",
"to",
"table",
"t0",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/catalog.py#L14-L23 | train | 36,106 |
fermiPy/fermipy | fermipy/catalog.py | join_tables | def join_tables(left, right, key_left, key_right,
cols_right=None):
"""Perform a join of two tables.
Parameters
----------
left : `~astropy.Table`
Left table for join.
right : `~astropy.Table`
Right table for join.
key_left : str
Key used to match elements from ``left`` table.
key_right : str
Key used to match elements from ``right`` table.
cols_right : list
Subset of columns from ``right`` table that will be appended
to joined table.
"""
right = right.copy()
if cols_right is None:
cols_right = right.colnames
else:
cols_right = [c for c in cols_right if c in right.colnames]
if key_left != key_right:
right[key_right].name = key_left
if key_left not in cols_right:
cols_right += [key_left]
out = join(left, right[cols_right], keys=key_left,
join_type='left')
for col in out.colnames:
if out[col].dtype.kind in ['S', 'U']:
out[col].fill_value = ''
elif out[col].dtype.kind in ['i']:
out[col].fill_value = 0
else:
out[col].fill_value = np.nan
return out.filled() | python | def join_tables(left, right, key_left, key_right,
cols_right=None):
"""Perform a join of two tables.
Parameters
----------
left : `~astropy.Table`
Left table for join.
right : `~astropy.Table`
Right table for join.
key_left : str
Key used to match elements from ``left`` table.
key_right : str
Key used to match elements from ``right`` table.
cols_right : list
Subset of columns from ``right`` table that will be appended
to joined table.
"""
right = right.copy()
if cols_right is None:
cols_right = right.colnames
else:
cols_right = [c for c in cols_right if c in right.colnames]
if key_left != key_right:
right[key_right].name = key_left
if key_left not in cols_right:
cols_right += [key_left]
out = join(left, right[cols_right], keys=key_left,
join_type='left')
for col in out.colnames:
if out[col].dtype.kind in ['S', 'U']:
out[col].fill_value = ''
elif out[col].dtype.kind in ['i']:
out[col].fill_value = 0
else:
out[col].fill_value = np.nan
return out.filled() | [
"def",
"join_tables",
"(",
"left",
",",
"right",
",",
"key_left",
",",
"key_right",
",",
"cols_right",
"=",
"None",
")",
":",
"right",
"=",
"right",
".",
"copy",
"(",
")",
"if",
"cols_right",
"is",
"None",
":",
"cols_right",
"=",
"right",
".",
"colname... | Perform a join of two tables.
Parameters
----------
left : `~astropy.Table`
Left table for join.
right : `~astropy.Table`
Right table for join.
key_left : str
Key used to match elements from ``left`` table.
key_right : str
Key used to match elements from ``right`` table.
cols_right : list
Subset of columns from ``right`` table that will be appended
to joined table. | [
"Perform",
"a",
"join",
"of",
"two",
"tables",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/catalog.py#L26-L73 | train | 36,107 |
fermiPy/fermipy | fermipy/catalog.py | strip_columns | def strip_columns(tab):
"""Strip whitespace from string columns."""
for colname in tab.colnames:
if tab[colname].dtype.kind in ['S', 'U']:
tab[colname] = np.core.defchararray.strip(tab[colname]) | python | def strip_columns(tab):
"""Strip whitespace from string columns."""
for colname in tab.colnames:
if tab[colname].dtype.kind in ['S', 'U']:
tab[colname] = np.core.defchararray.strip(tab[colname]) | [
"def",
"strip_columns",
"(",
"tab",
")",
":",
"for",
"colname",
"in",
"tab",
".",
"colnames",
":",
"if",
"tab",
"[",
"colname",
"]",
".",
"dtype",
".",
"kind",
"in",
"[",
"'S'",
",",
"'U'",
"]",
":",
"tab",
"[",
"colname",
"]",
"=",
"np",
".",
... | Strip whitespace from string columns. | [
"Strip",
"whitespace",
"from",
"string",
"columns",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/catalog.py#L76-L80 | train | 36,108 |
fermiPy/fermipy | fermipy/catalog.py | row_to_dict | def row_to_dict(row):
"""Convert a table row to a dictionary."""
o = {}
for colname in row.colnames:
if isinstance(row[colname], np.string_) and row[colname].dtype.kind in ['S', 'U']:
o[colname] = str(row[colname])
else:
o[colname] = row[colname]
return o | python | def row_to_dict(row):
"""Convert a table row to a dictionary."""
o = {}
for colname in row.colnames:
if isinstance(row[colname], np.string_) and row[colname].dtype.kind in ['S', 'U']:
o[colname] = str(row[colname])
else:
o[colname] = row[colname]
return o | [
"def",
"row_to_dict",
"(",
"row",
")",
":",
"o",
"=",
"{",
"}",
"for",
"colname",
"in",
"row",
".",
"colnames",
":",
"if",
"isinstance",
"(",
"row",
"[",
"colname",
"]",
",",
"np",
".",
"string_",
")",
"and",
"row",
"[",
"colname",
"]",
".",
"dty... | Convert a table row to a dictionary. | [
"Convert",
"a",
"table",
"row",
"to",
"a",
"dictionary",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/catalog.py#L83-L93 | train | 36,109 |
fermiPy/fermipy | fermipy/batch.py | check_log | def check_log(logfile, exited='Exited with exit code',
successful='Successfully completed', exists=True):
""" 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
exists : bool
Is the logfile required to exist
exited : str
String in logfile used to determine if a job exited.
successful : str
String in logfile used to determine if a job succeeded.
"""
if not os.path.exists(logfile):
return not exists
if exited in open(logfile).read():
return 'Exited'
elif successful in open(logfile).read():
return 'Successful'
else:
return 'None' | python | def check_log(logfile, exited='Exited with exit code',
successful='Successfully completed', exists=True):
""" 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
exists : bool
Is the logfile required to exist
exited : str
String in logfile used to determine if a job exited.
successful : str
String in logfile used to determine if a job succeeded.
"""
if not os.path.exists(logfile):
return not exists
if exited in open(logfile).read():
return 'Exited'
elif successful in open(logfile).read():
return 'Successful'
else:
return 'None' | [
"def",
"check_log",
"(",
"logfile",
",",
"exited",
"=",
"'Exited with exit code'",
",",
"successful",
"=",
"'Successfully completed'",
",",
"exists",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"logfile",
")",
":",
"return",
... | 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
exists : bool
Is the logfile required to exist
exited : str
String in logfile used to determine if a job exited.
successful : str
String in logfile used to determine if a job succeeded. | [
"Often",
"logfile",
"doesn",
"t",
"exist",
"because",
"the",
"job",
"hasn",
"t",
"begun",
"to",
"run",
".",
"It",
"is",
"unclear",
"what",
"you",
"want",
"to",
"do",
"in",
"that",
"case",
"..."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/batch.py#L50-L75 | train | 36,110 |
fermiPy/fermipy | fermipy/batch.py | dispatch_job | def dispatch_job(jobname, exe, args, opts, batch_opts, dry_run=True):
"""Dispatch an LSF job.
Parameters
----------
exe : str
Execution string.
args : list
Positional arguments.
opts : dict
Dictionary of command-line options.
"""
batch_opts.setdefault('W', 300)
batch_opts.setdefault('R', 'rhel60 && scratch > 10')
cmd_opts = ''
for k, v in opts.items():
if isinstance(v, list):
cmd_opts += ' '.join(['--%s=%s' % (k, t) for t in v])
elif isinstance(v, bool) and v:
cmd_opts += ' --%s ' % (k)
elif isinstance(v, bool):
continue
elif v is not None:
cmd_opts += ' --%s=\"%s\" ' % (k, v)
bash_script = "{exe} {args} {opts}"
scriptexe = jobname + '.sh'
with open(os.path.join(scriptexe), 'wt') as f:
f.write(bash_script.format(exe=exe, args=' '.join(args),
opts=cmd_opts))
batch_optstr = parse_lsf_opts(**batch_opts)
batch_cmd = 'bsub %s ' % (batch_optstr)
batch_cmd += ' bash %s' % scriptexe
print(batch_cmd)
if not dry_run:
os.system(batch_cmd) | python | def dispatch_job(jobname, exe, args, opts, batch_opts, dry_run=True):
"""Dispatch an LSF job.
Parameters
----------
exe : str
Execution string.
args : list
Positional arguments.
opts : dict
Dictionary of command-line options.
"""
batch_opts.setdefault('W', 300)
batch_opts.setdefault('R', 'rhel60 && scratch > 10')
cmd_opts = ''
for k, v in opts.items():
if isinstance(v, list):
cmd_opts += ' '.join(['--%s=%s' % (k, t) for t in v])
elif isinstance(v, bool) and v:
cmd_opts += ' --%s ' % (k)
elif isinstance(v, bool):
continue
elif v is not None:
cmd_opts += ' --%s=\"%s\" ' % (k, v)
bash_script = "{exe} {args} {opts}"
scriptexe = jobname + '.sh'
with open(os.path.join(scriptexe), 'wt') as f:
f.write(bash_script.format(exe=exe, args=' '.join(args),
opts=cmd_opts))
batch_optstr = parse_lsf_opts(**batch_opts)
batch_cmd = 'bsub %s ' % (batch_optstr)
batch_cmd += ' bash %s' % scriptexe
print(batch_cmd)
if not dry_run:
os.system(batch_cmd) | [
"def",
"dispatch_job",
"(",
"jobname",
",",
"exe",
",",
"args",
",",
"opts",
",",
"batch_opts",
",",
"dry_run",
"=",
"True",
")",
":",
"batch_opts",
".",
"setdefault",
"(",
"'W'",
",",
"300",
")",
"batch_opts",
".",
"setdefault",
"(",
"'R'",
",",
"'rhe... | Dispatch an LSF job.
Parameters
----------
exe : str
Execution string.
args : list
Positional arguments.
opts : dict
Dictionary of command-line options. | [
"Dispatch",
"an",
"LSF",
"job",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/batch.py#L119-L160 | train | 36,111 |
fermiPy/fermipy | fermipy/spectrum.py | SpectralFunction.create_from_flux | def create_from_flux(cls, params, emin, emax, flux, scale=1.0):
"""Create a spectral function instance given its flux."""
params = params.copy()
params[0] = 1.0
params[0] = flux / cls.eval_flux(emin, emax, params, scale=scale)
return cls(params, scale) | python | def create_from_flux(cls, params, emin, emax, flux, scale=1.0):
"""Create a spectral function instance given its flux."""
params = params.copy()
params[0] = 1.0
params[0] = flux / cls.eval_flux(emin, emax, params, scale=scale)
return cls(params, scale) | [
"def",
"create_from_flux",
"(",
"cls",
",",
"params",
",",
"emin",
",",
"emax",
",",
"flux",
",",
"scale",
"=",
"1.0",
")",
":",
"params",
"=",
"params",
".",
"copy",
"(",
")",
"params",
"[",
"0",
"]",
"=",
"1.0",
"params",
"[",
"0",
"]",
"=",
... | Create a spectral function instance given its flux. | [
"Create",
"a",
"spectral",
"function",
"instance",
"given",
"its",
"flux",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/spectrum.py#L146-L151 | train | 36,112 |
fermiPy/fermipy | fermipy/spectrum.py | SpectralFunction.create_from_eflux | def create_from_eflux(cls, params, emin, emax, eflux, scale=1.0):
"""Create a spectral function instance given its energy flux."""
params = params.copy()
params[0] = 1.0
params[0] = eflux / cls.eval_eflux(emin, emax, params, scale=scale)
return cls(params, scale) | python | def create_from_eflux(cls, params, emin, emax, eflux, scale=1.0):
"""Create a spectral function instance given its energy flux."""
params = params.copy()
params[0] = 1.0
params[0] = eflux / cls.eval_eflux(emin, emax, params, scale=scale)
return cls(params, scale) | [
"def",
"create_from_eflux",
"(",
"cls",
",",
"params",
",",
"emin",
",",
"emax",
",",
"eflux",
",",
"scale",
"=",
"1.0",
")",
":",
"params",
"=",
"params",
".",
"copy",
"(",
")",
"params",
"[",
"0",
"]",
"=",
"1.0",
"params",
"[",
"0",
"]",
"=",
... | Create a spectral function instance given its energy flux. | [
"Create",
"a",
"spectral",
"function",
"instance",
"given",
"its",
"energy",
"flux",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/spectrum.py#L154-L159 | train | 36,113 |
fermiPy/fermipy | fermipy/spectrum.py | SpectralFunction._integrate | def _integrate(cls, fn, emin, emax, params, scale=1.0, extra_params=None,
npt=20):
"""Fast numerical integration method using mid-point rule."""
emin = np.expand_dims(emin, -1)
emax = np.expand_dims(emax, -1)
params = copy.deepcopy(params)
for i, p in enumerate(params):
params[i] = np.expand_dims(params[i], -1)
xedges = np.linspace(0.0, 1.0, npt + 1)
logx_edge = np.log(emin) + xedges * (np.log(emax) - np.log(emin))
logx = 0.5 * (logx_edge[..., 1:] + logx_edge[..., :-1])
xw = np.exp(logx_edge[..., 1:]) - np.exp(logx_edge[..., :-1])
dnde = fn(np.exp(logx), params, scale, extra_params)
return np.sum(dnde * xw, axis=-1) | python | def _integrate(cls, fn, emin, emax, params, scale=1.0, extra_params=None,
npt=20):
"""Fast numerical integration method using mid-point rule."""
emin = np.expand_dims(emin, -1)
emax = np.expand_dims(emax, -1)
params = copy.deepcopy(params)
for i, p in enumerate(params):
params[i] = np.expand_dims(params[i], -1)
xedges = np.linspace(0.0, 1.0, npt + 1)
logx_edge = np.log(emin) + xedges * (np.log(emax) - np.log(emin))
logx = 0.5 * (logx_edge[..., 1:] + logx_edge[..., :-1])
xw = np.exp(logx_edge[..., 1:]) - np.exp(logx_edge[..., :-1])
dnde = fn(np.exp(logx), params, scale, extra_params)
return np.sum(dnde * xw, axis=-1) | [
"def",
"_integrate",
"(",
"cls",
",",
"fn",
",",
"emin",
",",
"emax",
",",
"params",
",",
"scale",
"=",
"1.0",
",",
"extra_params",
"=",
"None",
",",
"npt",
"=",
"20",
")",
":",
"emin",
"=",
"np",
".",
"expand_dims",
"(",
"emin",
",",
"-",
"1",
... | Fast numerical integration method using mid-point rule. | [
"Fast",
"numerical",
"integration",
"method",
"using",
"mid",
"-",
"point",
"rule",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/spectrum.py#L230-L246 | train | 36,114 |
fermiPy/fermipy | fermipy/spectrum.py | SpectralFunction.dnde | def dnde(self, x, params=None):
"""Evaluate differential flux."""
params = self.params if params is None else params
return np.squeeze(self.eval_dnde(x, params, self.scale,
self.extra_params)) | python | def dnde(self, x, params=None):
"""Evaluate differential flux."""
params = self.params if params is None else params
return np.squeeze(self.eval_dnde(x, params, self.scale,
self.extra_params)) | [
"def",
"dnde",
"(",
"self",
",",
"x",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"params",
"if",
"params",
"is",
"None",
"else",
"params",
"return",
"np",
".",
"squeeze",
"(",
"self",
".",
"eval_dnde",
"(",
"x",
",",
"params"... | Evaluate differential flux. | [
"Evaluate",
"differential",
"flux",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/spectrum.py#L270-L274 | train | 36,115 |
fermiPy/fermipy | fermipy/spectrum.py | SpectralFunction.ednde | def ednde(self, x, params=None):
"""Evaluate E times differential flux."""
params = self.params if params is None else params
return np.squeeze(self.eval_ednde(x, params, self.scale,
self.extra_params)) | python | def ednde(self, x, params=None):
"""Evaluate E times differential flux."""
params = self.params if params is None else params
return np.squeeze(self.eval_ednde(x, params, self.scale,
self.extra_params)) | [
"def",
"ednde",
"(",
"self",
",",
"x",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"params",
"if",
"params",
"is",
"None",
"else",
"params",
"return",
"np",
".",
"squeeze",
"(",
"self",
".",
"eval_ednde",
"(",
"x",
",",
"param... | Evaluate E times differential flux. | [
"Evaluate",
"E",
"times",
"differential",
"flux",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/spectrum.py#L276-L280 | train | 36,116 |
fermiPy/fermipy | fermipy/spectrum.py | SpectralFunction.e2dnde | def e2dnde(self, x, params=None):
"""Evaluate E^2 times differential flux."""
params = self.params if params is None else params
return np.squeeze(self.eval_e2dnde(x, params, self.scale,
self.extra_params)) | python | def e2dnde(self, x, params=None):
"""Evaluate E^2 times differential flux."""
params = self.params if params is None else params
return np.squeeze(self.eval_e2dnde(x, params, self.scale,
self.extra_params)) | [
"def",
"e2dnde",
"(",
"self",
",",
"x",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"params",
"if",
"params",
"is",
"None",
"else",
"params",
"return",
"np",
".",
"squeeze",
"(",
"self",
".",
"eval_e2dnde",
"(",
"x",
",",
"par... | Evaluate E^2 times differential flux. | [
"Evaluate",
"E^2",
"times",
"differential",
"flux",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/spectrum.py#L282-L286 | train | 36,117 |
fermiPy/fermipy | fermipy/spectrum.py | SpectralFunction.dnde_deriv | def dnde_deriv(self, x, params=None):
"""Evaluate derivative of the differential flux with respect to E."""
params = self.params if params is None else params
return np.squeeze(self.eval_dnde_deriv(x, params, self.scale,
self.extra_params)) | python | def dnde_deriv(self, x, params=None):
"""Evaluate derivative of the differential flux with respect to E."""
params = self.params if params is None else params
return np.squeeze(self.eval_dnde_deriv(x, params, self.scale,
self.extra_params)) | [
"def",
"dnde_deriv",
"(",
"self",
",",
"x",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"params",
"if",
"params",
"is",
"None",
"else",
"params",
"return",
"np",
".",
"squeeze",
"(",
"self",
".",
"eval_dnde_deriv",
"(",
"x",
","... | Evaluate derivative of the differential flux with respect to E. | [
"Evaluate",
"derivative",
"of",
"the",
"differential",
"flux",
"with",
"respect",
"to",
"E",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/spectrum.py#L288-L292 | train | 36,118 |
fermiPy/fermipy | fermipy/spectrum.py | SpectralFunction.ednde_deriv | def ednde_deriv(self, x, params=None):
"""Evaluate derivative of E times differential flux with respect to
E."""
params = self.params if params is None else params
return np.squeeze(self.eval_ednde_deriv(x, params, self.scale,
self.extra_params)) | python | def ednde_deriv(self, x, params=None):
"""Evaluate derivative of E times differential flux with respect to
E."""
params = self.params if params is None else params
return np.squeeze(self.eval_ednde_deriv(x, params, self.scale,
self.extra_params)) | [
"def",
"ednde_deriv",
"(",
"self",
",",
"x",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"params",
"if",
"params",
"is",
"None",
"else",
"params",
"return",
"np",
".",
"squeeze",
"(",
"self",
".",
"eval_ednde_deriv",
"(",
"x",
"... | Evaluate derivative of E times differential flux with respect to
E. | [
"Evaluate",
"derivative",
"of",
"E",
"times",
"differential",
"flux",
"with",
"respect",
"to",
"E",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/spectrum.py#L294-L299 | train | 36,119 |
fermiPy/fermipy | fermipy/spectrum.py | SpectralFunction.e2dnde_deriv | def e2dnde_deriv(self, x, params=None):
"""Evaluate derivative of E^2 times differential flux with
respect to E."""
params = self.params if params is None else params
return np.squeeze(self.eval_e2dnde_deriv(x, params, self.scale,
self.extra_params)) | python | def e2dnde_deriv(self, x, params=None):
"""Evaluate derivative of E^2 times differential flux with
respect to E."""
params = self.params if params is None else params
return np.squeeze(self.eval_e2dnde_deriv(x, params, self.scale,
self.extra_params)) | [
"def",
"e2dnde_deriv",
"(",
"self",
",",
"x",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"params",
"if",
"params",
"is",
"None",
"else",
"params",
"return",
"np",
".",
"squeeze",
"(",
"self",
".",
"eval_e2dnde_deriv",
"(",
"x",
... | Evaluate derivative of E^2 times differential flux with
respect to E. | [
"Evaluate",
"derivative",
"of",
"E^2",
"times",
"differential",
"flux",
"with",
"respect",
"to",
"E",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/spectrum.py#L301-L306 | train | 36,120 |
fermiPy/fermipy | fermipy/spectrum.py | SpectralFunction.flux | def flux(self, emin, emax, params=None):
"""Evaluate the integral flux."""
params = self.params if params is None else params
return np.squeeze(self.eval_flux(emin, emax, params, self.scale,
self.extra_params)) | python | def flux(self, emin, emax, params=None):
"""Evaluate the integral flux."""
params = self.params if params is None else params
return np.squeeze(self.eval_flux(emin, emax, params, self.scale,
self.extra_params)) | [
"def",
"flux",
"(",
"self",
",",
"emin",
",",
"emax",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"params",
"if",
"params",
"is",
"None",
"else",
"params",
"return",
"np",
".",
"squeeze",
"(",
"self",
".",
"eval_flux",
"(",
"e... | Evaluate the integral flux. | [
"Evaluate",
"the",
"integral",
"flux",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/spectrum.py#L308-L312 | train | 36,121 |
fermiPy/fermipy | fermipy/spectrum.py | SpectralFunction.eflux | def eflux(self, emin, emax, params=None):
"""Evaluate the integral energy flux."""
params = self.params if params is None else params
return np.squeeze(self.eval_eflux(emin, emax, params, self.scale,
self.extra_params)) | python | def eflux(self, emin, emax, params=None):
"""Evaluate the integral energy flux."""
params = self.params if params is None else params
return np.squeeze(self.eval_eflux(emin, emax, params, self.scale,
self.extra_params)) | [
"def",
"eflux",
"(",
"self",
",",
"emin",
",",
"emax",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"params",
"if",
"params",
"is",
"None",
"else",
"params",
"return",
"np",
".",
"squeeze",
"(",
"self",
".",
"eval_eflux",
"(",
... | Evaluate the integral energy flux. | [
"Evaluate",
"the",
"integral",
"energy",
"flux",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/spectrum.py#L314-L318 | train | 36,122 |
fermiPy/fermipy | fermipy/sed_plotting.py | compare_SED | def compare_SED(castroData1, castroData2, ylims, TS_thresh=4.0,
errSigma=1.0, specVals=[]):
""" Compare two SEDs
castroData1: A CastroData object, with the
log-likelihood v. normalization for each energy bin
castroData2: A CastroData object, with the
log-likelihood v. normalization for each energy bin
ylims : y-axis limits
TS_thresh : TS value above with to plot a point,
rather than an upper limit
errSigma : Number of sigma to use for error bars
specVals : List of spectra to add to plot
returns fig,ax which are matplotlib figure and axes objects
"""
import matplotlib.pyplot as plt
xmin = min(castroData1.refSpec.ebins[0], castroData2.refSpec.ebins[0])
xmax = max(castroData1.refSpec.ebins[-1], castroData2.refSpec.ebins[-1])
ymin = ylims[0]
ymax = ylims[1]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlim((xmin, xmax))
ax.set_ylim((ymin, ymax))
ax.set_xlabel("Energy [GeV]")
ax.set_ylabel(NORM_LABEL[castroData1.norm_type])
plotSED_OnAxis(ax, castroData1, TS_thresh, errSigma,
colorLim='blue', colorPoint='blue')
plotSED_OnAxis(ax, castroData2, TS_thresh, errSigma,
colorLim='red', colorPoint='red')
for spec in specVals:
ax.loglog(castroData1.refSpec.eref, spec)
return fig, ax | python | def compare_SED(castroData1, castroData2, ylims, TS_thresh=4.0,
errSigma=1.0, specVals=[]):
""" Compare two SEDs
castroData1: A CastroData object, with the
log-likelihood v. normalization for each energy bin
castroData2: A CastroData object, with the
log-likelihood v. normalization for each energy bin
ylims : y-axis limits
TS_thresh : TS value above with to plot a point,
rather than an upper limit
errSigma : Number of sigma to use for error bars
specVals : List of spectra to add to plot
returns fig,ax which are matplotlib figure and axes objects
"""
import matplotlib.pyplot as plt
xmin = min(castroData1.refSpec.ebins[0], castroData2.refSpec.ebins[0])
xmax = max(castroData1.refSpec.ebins[-1], castroData2.refSpec.ebins[-1])
ymin = ylims[0]
ymax = ylims[1]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlim((xmin, xmax))
ax.set_ylim((ymin, ymax))
ax.set_xlabel("Energy [GeV]")
ax.set_ylabel(NORM_LABEL[castroData1.norm_type])
plotSED_OnAxis(ax, castroData1, TS_thresh, errSigma,
colorLim='blue', colorPoint='blue')
plotSED_OnAxis(ax, castroData2, TS_thresh, errSigma,
colorLim='red', colorPoint='red')
for spec in specVals:
ax.loglog(castroData1.refSpec.eref, spec)
return fig, ax | [
"def",
"compare_SED",
"(",
"castroData1",
",",
"castroData2",
",",
"ylims",
",",
"TS_thresh",
"=",
"4.0",
",",
"errSigma",
"=",
"1.0",
",",
"specVals",
"=",
"[",
"]",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"xmin",
"=",
"min",
"("... | Compare two SEDs
castroData1: A CastroData object, with the
log-likelihood v. normalization for each energy bin
castroData2: A CastroData object, with the
log-likelihood v. normalization for each energy bin
ylims : y-axis limits
TS_thresh : TS value above with to plot a point,
rather than an upper limit
errSigma : Number of sigma to use for error bars
specVals : List of spectra to add to plot
returns fig,ax which are matplotlib figure and axes objects | [
"Compare",
"two",
"SEDs"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/sed_plotting.py#L260-L301 | train | 36,123 |
fermiPy/fermipy | fermipy/diffuse/diffuse_src_manager.py | make_ring_dicts | def make_ring_dicts(**kwargs):
"""Build and return the information about the Galprop rings
"""
library_yamlfile = kwargs.get('library', 'models/library.yaml')
gmm = kwargs.get('GalpropMapManager', GalpropMapManager(**kwargs))
if library_yamlfile is None or library_yamlfile == 'None':
return gmm
diffuse_comps = DiffuseModelManager.read_diffuse_component_yaml(library_yamlfile)
for diffuse_value in diffuse_comps.values():
if diffuse_value is None:
continue
if diffuse_value['model_type'] != 'galprop_rings':
continue
versions = diffuse_value['versions']
for version in versions:
gmm.make_ring_dict(version)
return gmm | python | def make_ring_dicts(**kwargs):
"""Build and return the information about the Galprop rings
"""
library_yamlfile = kwargs.get('library', 'models/library.yaml')
gmm = kwargs.get('GalpropMapManager', GalpropMapManager(**kwargs))
if library_yamlfile is None or library_yamlfile == 'None':
return gmm
diffuse_comps = DiffuseModelManager.read_diffuse_component_yaml(library_yamlfile)
for diffuse_value in diffuse_comps.values():
if diffuse_value is None:
continue
if diffuse_value['model_type'] != 'galprop_rings':
continue
versions = diffuse_value['versions']
for version in versions:
gmm.make_ring_dict(version)
return gmm | [
"def",
"make_ring_dicts",
"(",
"*",
"*",
"kwargs",
")",
":",
"library_yamlfile",
"=",
"kwargs",
".",
"get",
"(",
"'library'",
",",
"'models/library.yaml'",
")",
"gmm",
"=",
"kwargs",
".",
"get",
"(",
"'GalpropMapManager'",
",",
"GalpropMapManager",
"(",
"*",
... | Build and return the information about the Galprop rings | [
"Build",
"and",
"return",
"the",
"information",
"about",
"the",
"Galprop",
"rings"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/diffuse_src_manager.py#L437-L453 | train | 36,124 |
fermiPy/fermipy | fermipy/diffuse/diffuse_src_manager.py | make_diffuse_comp_info_dict | def make_diffuse_comp_info_dict(**kwargs):
"""Build and return the information about the diffuse components
"""
library_yamlfile = kwargs.pop('library', 'models/library.yaml')
components = kwargs.pop('components', None)
if components is None:
comp_yamlfile = kwargs.pop('comp', 'config/binning.yaml')
components = Component.build_from_yamlfile(comp_yamlfile)
gmm = kwargs.get('GalpropMapManager', GalpropMapManager(**kwargs))
dmm = kwargs.get('DiffuseModelManager', DiffuseModelManager(**kwargs))
if library_yamlfile is None or library_yamlfile == 'None':
diffuse_comps = {}
else:
diffuse_comps = DiffuseModelManager.read_diffuse_component_yaml(
library_yamlfile)
diffuse_comp_info_dict = dmm.make_diffuse_comp_info_dict(
diffuse_comps, components)
for diffuse_value in diffuse_comps.values():
if diffuse_value is None:
continue
if diffuse_value['model_type'] != 'galprop_rings':
continue
versions = diffuse_value['versions']
for version in versions:
galprop_dict = gmm.make_diffuse_comp_info_dict(version)
diffuse_comp_info_dict.update(galprop_dict)
return dict(comp_info_dict=diffuse_comp_info_dict,
GalpropMapManager=gmm,
DiffuseModelManager=dmm) | python | def make_diffuse_comp_info_dict(**kwargs):
"""Build and return the information about the diffuse components
"""
library_yamlfile = kwargs.pop('library', 'models/library.yaml')
components = kwargs.pop('components', None)
if components is None:
comp_yamlfile = kwargs.pop('comp', 'config/binning.yaml')
components = Component.build_from_yamlfile(comp_yamlfile)
gmm = kwargs.get('GalpropMapManager', GalpropMapManager(**kwargs))
dmm = kwargs.get('DiffuseModelManager', DiffuseModelManager(**kwargs))
if library_yamlfile is None or library_yamlfile == 'None':
diffuse_comps = {}
else:
diffuse_comps = DiffuseModelManager.read_diffuse_component_yaml(
library_yamlfile)
diffuse_comp_info_dict = dmm.make_diffuse_comp_info_dict(
diffuse_comps, components)
for diffuse_value in diffuse_comps.values():
if diffuse_value is None:
continue
if diffuse_value['model_type'] != 'galprop_rings':
continue
versions = diffuse_value['versions']
for version in versions:
galprop_dict = gmm.make_diffuse_comp_info_dict(version)
diffuse_comp_info_dict.update(galprop_dict)
return dict(comp_info_dict=diffuse_comp_info_dict,
GalpropMapManager=gmm,
DiffuseModelManager=dmm) | [
"def",
"make_diffuse_comp_info_dict",
"(",
"*",
"*",
"kwargs",
")",
":",
"library_yamlfile",
"=",
"kwargs",
".",
"pop",
"(",
"'library'",
",",
"'models/library.yaml'",
")",
"components",
"=",
"kwargs",
".",
"pop",
"(",
"'components'",
",",
"None",
")",
"if",
... | Build and return the information about the diffuse components | [
"Build",
"and",
"return",
"the",
"information",
"about",
"the",
"diffuse",
"components"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/diffuse_src_manager.py#L456-L485 | train | 36,125 |
fermiPy/fermipy | fermipy/diffuse/diffuse_src_manager.py | GalpropMapManager.read_galprop_rings_yaml | def read_galprop_rings_yaml(self, galkey):
""" Read the yaml file for a partiuclar galprop key
"""
galprop_rings_yaml = self._name_factory.galprop_rings_yaml(galkey=galkey,
fullpath=True)
galprop_rings = yaml.safe_load(open(galprop_rings_yaml))
return galprop_rings | python | def read_galprop_rings_yaml(self, galkey):
""" Read the yaml file for a partiuclar galprop key
"""
galprop_rings_yaml = self._name_factory.galprop_rings_yaml(galkey=galkey,
fullpath=True)
galprop_rings = yaml.safe_load(open(galprop_rings_yaml))
return galprop_rings | [
"def",
"read_galprop_rings_yaml",
"(",
"self",
",",
"galkey",
")",
":",
"galprop_rings_yaml",
"=",
"self",
".",
"_name_factory",
".",
"galprop_rings_yaml",
"(",
"galkey",
"=",
"galkey",
",",
"fullpath",
"=",
"True",
")",
"galprop_rings",
"=",
"yaml",
".",
"saf... | Read the yaml file for a partiuclar galprop key | [
"Read",
"the",
"yaml",
"file",
"for",
"a",
"partiuclar",
"galprop",
"key"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/diffuse_src_manager.py#L50-L56 | train | 36,126 |
fermiPy/fermipy | fermipy/diffuse/diffuse_src_manager.py | GalpropMapManager.make_ring_filename | def make_ring_filename(self, source_name, ring, galprop_run):
""" Make the name of a gasmap file for a single ring
Parameters
----------
source_name : str
The galprop component, used to define path to gasmap files
ring : int
The ring index
galprop_run : str
String identifying the galprop parameters
"""
format_dict = self.__dict__.copy()
format_dict['sourcekey'] = self._name_factory.galprop_ringkey(source_name=source_name,
ringkey="ring_%i" % ring)
format_dict['galprop_run'] = galprop_run
return self._name_factory.galprop_gasmap(**format_dict) | python | def make_ring_filename(self, source_name, ring, galprop_run):
""" Make the name of a gasmap file for a single ring
Parameters
----------
source_name : str
The galprop component, used to define path to gasmap files
ring : int
The ring index
galprop_run : str
String identifying the galprop parameters
"""
format_dict = self.__dict__.copy()
format_dict['sourcekey'] = self._name_factory.galprop_ringkey(source_name=source_name,
ringkey="ring_%i" % ring)
format_dict['galprop_run'] = galprop_run
return self._name_factory.galprop_gasmap(**format_dict) | [
"def",
"make_ring_filename",
"(",
"self",
",",
"source_name",
",",
"ring",
",",
"galprop_run",
")",
":",
"format_dict",
"=",
"self",
".",
"__dict__",
".",
"copy",
"(",
")",
"format_dict",
"[",
"'sourcekey'",
"]",
"=",
"self",
".",
"_name_factory",
".",
"ga... | Make the name of a gasmap file for a single ring
Parameters
----------
source_name : str
The galprop component, used to define path to gasmap files
ring : int
The ring index
galprop_run : str
String identifying the galprop parameters | [
"Make",
"the",
"name",
"of",
"a",
"gasmap",
"file",
"for",
"a",
"single",
"ring"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/diffuse_src_manager.py#L77-L94 | train | 36,127 |
fermiPy/fermipy | fermipy/diffuse/diffuse_src_manager.py | GalpropMapManager.make_merged_name | def make_merged_name(self, source_name, galkey, fullpath):
""" Make the name of a gasmap file for a set of merged rings
Parameters
----------
source_name : str
The galprop component, used to define path to gasmap files
galkey : str
A short key identifying the galprop parameters
fullpath : bool
Return the full path name
"""
format_dict = self.__dict__.copy()
format_dict['sourcekey'] = self._name_factory.galprop_sourcekey(source_name=source_name,
galpropkey=galkey)
format_dict['fullpath'] = fullpath
return self._name_factory.merged_gasmap(**format_dict) | python | def make_merged_name(self, source_name, galkey, fullpath):
""" Make the name of a gasmap file for a set of merged rings
Parameters
----------
source_name : str
The galprop component, used to define path to gasmap files
galkey : str
A short key identifying the galprop parameters
fullpath : bool
Return the full path name
"""
format_dict = self.__dict__.copy()
format_dict['sourcekey'] = self._name_factory.galprop_sourcekey(source_name=source_name,
galpropkey=galkey)
format_dict['fullpath'] = fullpath
return self._name_factory.merged_gasmap(**format_dict) | [
"def",
"make_merged_name",
"(",
"self",
",",
"source_name",
",",
"galkey",
",",
"fullpath",
")",
":",
"format_dict",
"=",
"self",
".",
"__dict__",
".",
"copy",
"(",
")",
"format_dict",
"[",
"'sourcekey'",
"]",
"=",
"self",
".",
"_name_factory",
".",
"galpr... | Make the name of a gasmap file for a set of merged rings
Parameters
----------
source_name : str
The galprop component, used to define path to gasmap files
galkey : str
A short key identifying the galprop parameters
fullpath : bool
Return the full path name | [
"Make",
"the",
"name",
"of",
"a",
"gasmap",
"file",
"for",
"a",
"set",
"of",
"merged",
"rings"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/diffuse_src_manager.py#L96-L113 | train | 36,128 |
fermiPy/fermipy | fermipy/diffuse/diffuse_src_manager.py | GalpropMapManager.make_xml_name | def make_xml_name(self, source_name, galkey, fullpath):
""" Make the name of an xml file for a model definition for a set of merged rings
Parameters
----------
source_name : str
The galprop component, used to define path to gasmap files
galkey : str
A short key identifying the galprop parameters
fullpath : bool
Return the full path name
"""
format_dict = self.__dict__.copy()
format_dict['sourcekey'] = self._name_factory.galprop_sourcekey(source_name=source_name,
galpropkey=galkey)
format_dict['fullpath'] = fullpath
return self._name_factory.srcmdl_xml(**format_dict) | python | def make_xml_name(self, source_name, galkey, fullpath):
""" Make the name of an xml file for a model definition for a set of merged rings
Parameters
----------
source_name : str
The galprop component, used to define path to gasmap files
galkey : str
A short key identifying the galprop parameters
fullpath : bool
Return the full path name
"""
format_dict = self.__dict__.copy()
format_dict['sourcekey'] = self._name_factory.galprop_sourcekey(source_name=source_name,
galpropkey=galkey)
format_dict['fullpath'] = fullpath
return self._name_factory.srcmdl_xml(**format_dict) | [
"def",
"make_xml_name",
"(",
"self",
",",
"source_name",
",",
"galkey",
",",
"fullpath",
")",
":",
"format_dict",
"=",
"self",
".",
"__dict__",
".",
"copy",
"(",
")",
"format_dict",
"[",
"'sourcekey'",
"]",
"=",
"self",
".",
"_name_factory",
".",
"galprop_... | Make the name of an xml file for a model definition for a set of merged rings
Parameters
----------
source_name : str
The galprop component, used to define path to gasmap files
galkey : str
A short key identifying the galprop parameters
fullpath : bool
Return the full path name | [
"Make",
"the",
"name",
"of",
"an",
"xml",
"file",
"for",
"a",
"model",
"definition",
"for",
"a",
"set",
"of",
"merged",
"rings"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/diffuse_src_manager.py#L115-L132 | train | 36,129 |
fermiPy/fermipy | fermipy/diffuse/diffuse_src_manager.py | GalpropMapManager.make_ring_filelist | def make_ring_filelist(self, sourcekeys, rings, galprop_run):
""" Make a list of all the template files for a merged component
Parameters
----------
sourcekeys : list-like of str
The names of the componenents to merge
rings : list-like of int
The indices of the rings to merge
galprop_run : str
String identifying the galprop parameters
"""
flist = []
for sourcekey in sourcekeys:
for ring in rings:
flist += [self.make_ring_filename(sourcekey,
ring, galprop_run)]
return flist | python | def make_ring_filelist(self, sourcekeys, rings, galprop_run):
""" Make a list of all the template files for a merged component
Parameters
----------
sourcekeys : list-like of str
The names of the componenents to merge
rings : list-like of int
The indices of the rings to merge
galprop_run : str
String identifying the galprop parameters
"""
flist = []
for sourcekey in sourcekeys:
for ring in rings:
flist += [self.make_ring_filename(sourcekey,
ring, galprop_run)]
return flist | [
"def",
"make_ring_filelist",
"(",
"self",
",",
"sourcekeys",
",",
"rings",
",",
"galprop_run",
")",
":",
"flist",
"=",
"[",
"]",
"for",
"sourcekey",
"in",
"sourcekeys",
":",
"for",
"ring",
"in",
"rings",
":",
"flist",
"+=",
"[",
"self",
".",
"make_ring_f... | Make a list of all the template files for a merged component
Parameters
----------
sourcekeys : list-like of str
The names of the componenents to merge
rings : list-like of int
The indices of the rings to merge
galprop_run : str
String identifying the galprop parameters | [
"Make",
"a",
"list",
"of",
"all",
"the",
"template",
"files",
"for",
"a",
"merged",
"component"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/diffuse_src_manager.py#L134-L152 | train | 36,130 |
fermiPy/fermipy | fermipy/diffuse/diffuse_src_manager.py | GalpropMapManager.make_diffuse_comp_info_dict | def make_diffuse_comp_info_dict(self, galkey):
""" Make a dictionary maping from merged component to information about that component
Parameters
----------
galkey : str
A short key identifying the galprop parameters
"""
galprop_rings = self.read_galprop_rings_yaml(galkey)
ring_limits = galprop_rings.get('ring_limits')
comp_dict = galprop_rings.get('diffuse_comp_dict')
remove_rings = galprop_rings.get('remove_rings', [])
diffuse_comp_info_dict = {}
nring = len(ring_limits) - 1
for source_key in sorted(comp_dict.keys()):
for iring in range(nring):
source_name = "%s_%i" % (source_key, iring)
if source_name in remove_rings:
continue
full_key = "%s_%s" % (source_name, galkey)
diffuse_comp_info_dict[full_key] =\
self.make_diffuse_comp_info(source_name, galkey)
self._diffuse_comp_info_dicts[galkey] = diffuse_comp_info_dict
return diffuse_comp_info_dict | python | def make_diffuse_comp_info_dict(self, galkey):
""" Make a dictionary maping from merged component to information about that component
Parameters
----------
galkey : str
A short key identifying the galprop parameters
"""
galprop_rings = self.read_galprop_rings_yaml(galkey)
ring_limits = galprop_rings.get('ring_limits')
comp_dict = galprop_rings.get('diffuse_comp_dict')
remove_rings = galprop_rings.get('remove_rings', [])
diffuse_comp_info_dict = {}
nring = len(ring_limits) - 1
for source_key in sorted(comp_dict.keys()):
for iring in range(nring):
source_name = "%s_%i" % (source_key, iring)
if source_name in remove_rings:
continue
full_key = "%s_%s" % (source_name, galkey)
diffuse_comp_info_dict[full_key] =\
self.make_diffuse_comp_info(source_name, galkey)
self._diffuse_comp_info_dicts[galkey] = diffuse_comp_info_dict
return diffuse_comp_info_dict | [
"def",
"make_diffuse_comp_info_dict",
"(",
"self",
",",
"galkey",
")",
":",
"galprop_rings",
"=",
"self",
".",
"read_galprop_rings_yaml",
"(",
"galkey",
")",
"ring_limits",
"=",
"galprop_rings",
".",
"get",
"(",
"'ring_limits'",
")",
"comp_dict",
"=",
"galprop_rin... | Make a dictionary maping from merged component to information about that component
Parameters
----------
galkey : str
A short key identifying the galprop parameters | [
"Make",
"a",
"dictionary",
"maping",
"from",
"merged",
"component",
"to",
"information",
"about",
"that",
"component"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/diffuse_src_manager.py#L213-L237 | train | 36,131 |
fermiPy/fermipy | fermipy/diffuse/diffuse_src_manager.py | DiffuseModelManager.make_template_name | def make_template_name(self, model_type, sourcekey):
""" Make the name of a template file for particular component
Parameters
----------
model_type : str
Type of model to use for this component
sourcekey : str
Key to identify this component
Returns filename or None if component does not require a template file
"""
format_dict = self.__dict__.copy()
format_dict['sourcekey'] = sourcekey
if model_type == 'IsoSource':
return self._name_factory.spectral_template(**format_dict)
elif model_type in ['MapCubeSource', 'SpatialMap']:
return self._name_factory.diffuse_template(**format_dict)
else:
raise ValueError("Unexpected model_type %s" % model_type) | python | def make_template_name(self, model_type, sourcekey):
""" Make the name of a template file for particular component
Parameters
----------
model_type : str
Type of model to use for this component
sourcekey : str
Key to identify this component
Returns filename or None if component does not require a template file
"""
format_dict = self.__dict__.copy()
format_dict['sourcekey'] = sourcekey
if model_type == 'IsoSource':
return self._name_factory.spectral_template(**format_dict)
elif model_type in ['MapCubeSource', 'SpatialMap']:
return self._name_factory.diffuse_template(**format_dict)
else:
raise ValueError("Unexpected model_type %s" % model_type) | [
"def",
"make_template_name",
"(",
"self",
",",
"model_type",
",",
"sourcekey",
")",
":",
"format_dict",
"=",
"self",
".",
"__dict__",
".",
"copy",
"(",
")",
"format_dict",
"[",
"'sourcekey'",
"]",
"=",
"sourcekey",
"if",
"model_type",
"==",
"'IsoSource'",
":... | Make the name of a template file for particular component
Parameters
----------
model_type : str
Type of model to use for this component
sourcekey : str
Key to identify this component
Returns filename or None if component does not require a template file | [
"Make",
"the",
"name",
"of",
"a",
"template",
"file",
"for",
"particular",
"component"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/diffuse_src_manager.py#L290-L310 | train | 36,132 |
fermiPy/fermipy | fermipy/diffuse/diffuse_src_manager.py | DiffuseModelManager.make_xml_name | def make_xml_name(self, sourcekey):
""" Make the name of an xml file for a model definition of a single component
Parameters
----------
sourcekey : str
Key to identify this component
"""
format_dict = self.__dict__.copy()
format_dict['sourcekey'] = sourcekey
return self._name_factory.srcmdl_xml(**format_dict) | python | def make_xml_name(self, sourcekey):
""" Make the name of an xml file for a model definition of a single component
Parameters
----------
sourcekey : str
Key to identify this component
"""
format_dict = self.__dict__.copy()
format_dict['sourcekey'] = sourcekey
return self._name_factory.srcmdl_xml(**format_dict) | [
"def",
"make_xml_name",
"(",
"self",
",",
"sourcekey",
")",
":",
"format_dict",
"=",
"self",
".",
"__dict__",
".",
"copy",
"(",
")",
"format_dict",
"[",
"'sourcekey'",
"]",
"=",
"sourcekey",
"return",
"self",
".",
"_name_factory",
".",
"srcmdl_xml",
"(",
"... | Make the name of an xml file for a model definition of a single component
Parameters
----------
sourcekey : str
Key to identify this component | [
"Make",
"the",
"name",
"of",
"an",
"xml",
"file",
"for",
"a",
"model",
"definition",
"of",
"a",
"single",
"component"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/diffuse_src_manager.py#L312-L323 | train | 36,133 |
fermiPy/fermipy | fermipy/diffuse/diffuse_src_manager.py | DiffuseModelManager.make_diffuse_comp_info_dict | def make_diffuse_comp_info_dict(self, diffuse_sources, components):
""" Make a dictionary maping from diffuse component to information about that component
Parameters
----------
diffuse_sources : dict
Dictionary with diffuse source defintions
components : dict
Dictionary with event selection defintions,
needed for selection depenedent diffuse components
Returns
-------
ret_dict : dict
Dictionary mapping sourcekey to `model_component.ModelComponentInfo`
"""
ret_dict = {}
for key, value in diffuse_sources.items():
if value is None:
continue
model_type = value.get('model_type', 'MapCubeSource')
if model_type in ['galprop_rings', 'catalog']:
continue
selection_dependent = value.get('selection_dependent', False)
moving = value.get('moving', False)
versions = value.get('versions', [])
for version in versions:
# sourcekey = self._name_factory.sourcekey(source_name=key,
# source_ver=version)
comp_dict = None
if selection_dependent:
# For selection dependent diffuse sources we need to split
# by binning component
comp_dict = {}
for comp in components:
comp_key = comp.make_key('{ebin_name}_{evtype_name}')
comp_dict[comp_key] = self.make_diffuse_comp_info(
key, version, value, None, comp_key)
elif moving:
# For moving diffuse sources we need to split by zmax cut
comp_dict = {}
zmax_dict = {}
for comp in components:
zmax_dict[int(comp.zmax)] = True
zmax_list = sorted(zmax_dict.keys())
for zmax in zmax_list:
comp_key = "zmax%i" % (zmax)
comp_dict[comp_key] = self.make_diffuse_comp_info(
key, version, value, None, comp_key)
comp_info = self.make_diffuse_comp_info(
key, version, value, comp_dict)
ret_dict[comp_info.sourcekey] = comp_info
self._diffuse_comp_info_dict.update(ret_dict)
return ret_dict | python | def make_diffuse_comp_info_dict(self, diffuse_sources, components):
""" Make a dictionary maping from diffuse component to information about that component
Parameters
----------
diffuse_sources : dict
Dictionary with diffuse source defintions
components : dict
Dictionary with event selection defintions,
needed for selection depenedent diffuse components
Returns
-------
ret_dict : dict
Dictionary mapping sourcekey to `model_component.ModelComponentInfo`
"""
ret_dict = {}
for key, value in diffuse_sources.items():
if value is None:
continue
model_type = value.get('model_type', 'MapCubeSource')
if model_type in ['galprop_rings', 'catalog']:
continue
selection_dependent = value.get('selection_dependent', False)
moving = value.get('moving', False)
versions = value.get('versions', [])
for version in versions:
# sourcekey = self._name_factory.sourcekey(source_name=key,
# source_ver=version)
comp_dict = None
if selection_dependent:
# For selection dependent diffuse sources we need to split
# by binning component
comp_dict = {}
for comp in components:
comp_key = comp.make_key('{ebin_name}_{evtype_name}')
comp_dict[comp_key] = self.make_diffuse_comp_info(
key, version, value, None, comp_key)
elif moving:
# For moving diffuse sources we need to split by zmax cut
comp_dict = {}
zmax_dict = {}
for comp in components:
zmax_dict[int(comp.zmax)] = True
zmax_list = sorted(zmax_dict.keys())
for zmax in zmax_list:
comp_key = "zmax%i" % (zmax)
comp_dict[comp_key] = self.make_diffuse_comp_info(
key, version, value, None, comp_key)
comp_info = self.make_diffuse_comp_info(
key, version, value, comp_dict)
ret_dict[comp_info.sourcekey] = comp_info
self._diffuse_comp_info_dict.update(ret_dict)
return ret_dict | [
"def",
"make_diffuse_comp_info_dict",
"(",
"self",
",",
"diffuse_sources",
",",
"components",
")",
":",
"ret_dict",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"diffuse_sources",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"continue... | Make a dictionary maping from diffuse component to information about that component
Parameters
----------
diffuse_sources : dict
Dictionary with diffuse source defintions
components : dict
Dictionary with event selection defintions,
needed for selection depenedent diffuse components
Returns
-------
ret_dict : dict
Dictionary mapping sourcekey to `model_component.ModelComponentInfo` | [
"Make",
"a",
"dictionary",
"maping",
"from",
"diffuse",
"component",
"to",
"information",
"about",
"that",
"component"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/diffuse_src_manager.py#L377-L434 | train | 36,134 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | get_unique_match | def get_unique_match(table, colname, value):
"""Get the row matching value for a particular column.
If exactly one row matchs, return index of that row,
Otherwise raise KeyError.
"""
# FIXME, This is here for python 3.5, where astropy is now returning bytes
# instead of str
if table[colname].dtype.kind in ['S', 'U']:
mask = table[colname].astype(str) == value
else:
mask = table[colname] == value
if mask.sum() != 1:
raise KeyError("%i rows in column %s match value %s" %
(mask.sum(), colname, value))
return np.argmax(mask) | python | def get_unique_match(table, colname, value):
"""Get the row matching value for a particular column.
If exactly one row matchs, return index of that row,
Otherwise raise KeyError.
"""
# FIXME, This is here for python 3.5, where astropy is now returning bytes
# instead of str
if table[colname].dtype.kind in ['S', 'U']:
mask = table[colname].astype(str) == value
else:
mask = table[colname] == value
if mask.sum() != 1:
raise KeyError("%i rows in column %s match value %s" %
(mask.sum(), colname, value))
return np.argmax(mask) | [
"def",
"get_unique_match",
"(",
"table",
",",
"colname",
",",
"value",
")",
":",
"# FIXME, This is here for python 3.5, where astropy is now returning bytes",
"# instead of str",
"if",
"table",
"[",
"colname",
"]",
".",
"dtype",
".",
"kind",
"in",
"[",
"'S'",
",",
"... | Get the row matching value for a particular column.
If exactly one row matchs, return index of that row,
Otherwise raise KeyError. | [
"Get",
"the",
"row",
"matching",
"value",
"for",
"a",
"particular",
"column",
".",
"If",
"exactly",
"one",
"row",
"matchs",
"return",
"index",
"of",
"that",
"row",
"Otherwise",
"raise",
"KeyError",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L31-L46 | train | 36,135 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | main_browse | def main_browse():
"""Entry point for command line use for browsing a FileArchive """
import argparse
parser = argparse.ArgumentParser(usage="file_archive.py [options]",
description="Browse a job archive")
parser.add_argument('--files', action='store', dest='file_archive_table',
type=str, default='file_archive_temp.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:])
FileArchive.build_archive(**args.__dict__) | python | def main_browse():
"""Entry point for command line use for browsing a FileArchive """
import argparse
parser = argparse.ArgumentParser(usage="file_archive.py [options]",
description="Browse a job archive")
parser.add_argument('--files', action='store', dest='file_archive_table',
type=str, default='file_archive_temp.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:])
FileArchive.build_archive(**args.__dict__) | [
"def",
"main_browse",
"(",
")",
":",
"import",
"argparse",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"usage",
"=",
"\"file_archive.py [options]\"",
",",
"description",
"=",
"\"Browse a job archive\"",
")",
"parser",
".",
"add_argument",
"(",
"'--files'"... | Entry point for command line use for browsing a FileArchive | [
"Entry",
"point",
"for",
"command",
"line",
"use",
"for",
"browsing",
"a",
"FileArchive"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L815-L829 | train | 36,136 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileDict.latch_file_info | def latch_file_info(self, args):
"""Extract the file paths from a set of arguments
"""
self.file_dict.clear()
for key, val in self.file_args.items():
try:
file_path = args[key]
if file_path is None:
continue
# 'args' is special
if key[0:4] == 'args':
if isinstance(file_path, list):
tokens = file_path
elif isinstance(file_path, str):
tokens = file_path.split()
else:
raise TypeError(
"Args has type %s, expect list or str" % type(file_path))
for token in tokens:
self.file_dict[token.replace('.gz', '')] = val
else:
self.file_dict[file_path.replace('.gz', '')] = val
except KeyError:
pass | python | def latch_file_info(self, args):
"""Extract the file paths from a set of arguments
"""
self.file_dict.clear()
for key, val in self.file_args.items():
try:
file_path = args[key]
if file_path is None:
continue
# 'args' is special
if key[0:4] == 'args':
if isinstance(file_path, list):
tokens = file_path
elif isinstance(file_path, str):
tokens = file_path.split()
else:
raise TypeError(
"Args has type %s, expect list or str" % type(file_path))
for token in tokens:
self.file_dict[token.replace('.gz', '')] = val
else:
self.file_dict[file_path.replace('.gz', '')] = val
except KeyError:
pass | [
"def",
"latch_file_info",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"file_dict",
".",
"clear",
"(",
")",
"for",
"key",
",",
"val",
"in",
"self",
".",
"file_args",
".",
"items",
"(",
")",
":",
"try",
":",
"file_path",
"=",
"args",
"[",
"key",... | Extract the file paths from a set of arguments | [
"Extract",
"the",
"file",
"paths",
"from",
"a",
"set",
"of",
"arguments"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L96-L119 | train | 36,137 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileDict.output_files | def output_files(self):
"""Return a list of the output files produced by this link.
For `Link` sub-classes this will return the union
of all the output files of each internal `Link`.
That is to say this will include files produced by one
`Link` in a `Chain` and used as input to another `Link` in the `Chain`
"""
ret_list = []
for key, val in self.file_dict.items():
# For output files we only want files that were marked as output
if val & FileFlags.output_mask:
ret_list.append(key)
return ret_list | python | def output_files(self):
"""Return a list of the output files produced by this link.
For `Link` sub-classes this will return the union
of all the output files of each internal `Link`.
That is to say this will include files produced by one
`Link` in a `Chain` and used as input to another `Link` in the `Chain`
"""
ret_list = []
for key, val in self.file_dict.items():
# For output files we only want files that were marked as output
if val & FileFlags.output_mask:
ret_list.append(key)
return ret_list | [
"def",
"output_files",
"(",
"self",
")",
":",
"ret_list",
"=",
"[",
"]",
"for",
"key",
",",
"val",
"in",
"self",
".",
"file_dict",
".",
"items",
"(",
")",
":",
"# For output files we only want files that were marked as output",
"if",
"val",
"&",
"FileFlags",
"... | Return a list of the output files produced by this link.
For `Link` sub-classes this will return the union
of all the output files of each internal `Link`.
That is to say this will include files produced by one
`Link` in a `Chain` and used as input to another `Link` in the `Chain` | [
"Return",
"a",
"list",
"of",
"the",
"output",
"files",
"produced",
"by",
"this",
"link",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L152-L166 | train | 36,138 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileDict.chain_input_files | def chain_input_files(self):
"""Return a list of the input files needed by this chain.
For `Link` sub-classes this will return only those files
that were not created by any internal `Link`
"""
ret_list = []
for key, val in self.file_dict.items():
# For chain input files we only want files that were not marked as output
# (I.e., not produced by some other step in the chain)
if val & FileFlags.in_ch_mask == FileFlags.input_mask:
ret_list.append(key)
return ret_list | python | def chain_input_files(self):
"""Return a list of the input files needed by this chain.
For `Link` sub-classes this will return only those files
that were not created by any internal `Link`
"""
ret_list = []
for key, val in self.file_dict.items():
# For chain input files we only want files that were not marked as output
# (I.e., not produced by some other step in the chain)
if val & FileFlags.in_ch_mask == FileFlags.input_mask:
ret_list.append(key)
return ret_list | [
"def",
"chain_input_files",
"(",
"self",
")",
":",
"ret_list",
"=",
"[",
"]",
"for",
"key",
",",
"val",
"in",
"self",
".",
"file_dict",
".",
"items",
"(",
")",
":",
"# For chain input files we only want files that were not marked as output",
"# (I.e., not produced by ... | Return a list of the input files needed by this chain.
For `Link` sub-classes this will return only those files
that were not created by any internal `Link` | [
"Return",
"a",
"list",
"of",
"the",
"input",
"files",
"needed",
"by",
"this",
"chain",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L169-L181 | train | 36,139 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileDict.chain_output_files | def chain_output_files(self):
"""Return a list of the all the output files produced by this link.
For `Link` sub-classes this will return only those files
that were not marked as internal files or marked for removal.
"""
ret_list = []
for key, val in self.file_dict.items():
# For pure input files we only want output files that were not
# marked as internal or temp
if val & FileFlags.out_ch_mask == FileFlags.output_mask:
ret_list.append(key)
return ret_list | python | def chain_output_files(self):
"""Return a list of the all the output files produced by this link.
For `Link` sub-classes this will return only those files
that were not marked as internal files or marked for removal.
"""
ret_list = []
for key, val in self.file_dict.items():
# For pure input files we only want output files that were not
# marked as internal or temp
if val & FileFlags.out_ch_mask == FileFlags.output_mask:
ret_list.append(key)
return ret_list | [
"def",
"chain_output_files",
"(",
"self",
")",
":",
"ret_list",
"=",
"[",
"]",
"for",
"key",
",",
"val",
"in",
"self",
".",
"file_dict",
".",
"items",
"(",
")",
":",
"# For pure input files we only want output files that were not",
"# marked as internal or temp",
"i... | Return a list of the all the output files produced by this link.
For `Link` sub-classes this will return only those files
that were not marked as internal files or marked for removal. | [
"Return",
"a",
"list",
"of",
"the",
"all",
"the",
"output",
"files",
"produced",
"by",
"this",
"link",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L184-L196 | train | 36,140 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileDict.internal_files | def internal_files(self):
"""Return a list of the intermediate files produced by this link.
This returns all files that were explicitly marked as internal files.
"""
ret_list = []
for key, val in self.file_dict.items():
# For internal files we only want files that were marked as
# internal
if val & FileFlags.internal_mask:
ret_list.append(key)
return ret_list | python | def internal_files(self):
"""Return a list of the intermediate files produced by this link.
This returns all files that were explicitly marked as internal files.
"""
ret_list = []
for key, val in self.file_dict.items():
# For internal files we only want files that were marked as
# internal
if val & FileFlags.internal_mask:
ret_list.append(key)
return ret_list | [
"def",
"internal_files",
"(",
"self",
")",
":",
"ret_list",
"=",
"[",
"]",
"for",
"key",
",",
"val",
"in",
"self",
".",
"file_dict",
".",
"items",
"(",
")",
":",
"# For internal files we only want files that were marked as",
"# internal",
"if",
"val",
"&",
"Fi... | Return a list of the intermediate files produced by this link.
This returns all files that were explicitly marked as internal files. | [
"Return",
"a",
"list",
"of",
"the",
"intermediate",
"files",
"produced",
"by",
"this",
"link",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L233-L244 | train | 36,141 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileDict.temp_files | def temp_files(self):
"""Return a list of the temporary files produced by this link.
This returns all files that were explicitly marked for removal.
"""
ret_list = []
for key, val in self.file_dict.items():
# For temp files we only want files that were marked for removal
if val & FileFlags.rm_mask:
ret_list.append(key)
return ret_list | python | def temp_files(self):
"""Return a list of the temporary files produced by this link.
This returns all files that were explicitly marked for removal.
"""
ret_list = []
for key, val in self.file_dict.items():
# For temp files we only want files that were marked for removal
if val & FileFlags.rm_mask:
ret_list.append(key)
return ret_list | [
"def",
"temp_files",
"(",
"self",
")",
":",
"ret_list",
"=",
"[",
"]",
"for",
"key",
",",
"val",
"in",
"self",
".",
"file_dict",
".",
"items",
"(",
")",
":",
"# For temp files we only want files that were marked for removal",
"if",
"val",
"&",
"FileFlags",
"."... | Return a list of the temporary files produced by this link.
This returns all files that were explicitly marked for removal. | [
"Return",
"a",
"list",
"of",
"the",
"temporary",
"files",
"produced",
"by",
"this",
"link",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L247-L257 | train | 36,142 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileDict.gzip_files | def gzip_files(self):
"""Return a list of the files compressed by this link.
This returns all files that were explicitly marked for compression.
"""
ret_list = []
for key, val in self.file_dict.items():
# For temp files we only want files that were marked for removal
if val & FileFlags.gz_mask:
ret_list.append(key)
return ret_list | python | def gzip_files(self):
"""Return a list of the files compressed by this link.
This returns all files that were explicitly marked for compression.
"""
ret_list = []
for key, val in self.file_dict.items():
# For temp files we only want files that were marked for removal
if val & FileFlags.gz_mask:
ret_list.append(key)
return ret_list | [
"def",
"gzip_files",
"(",
"self",
")",
":",
"ret_list",
"=",
"[",
"]",
"for",
"key",
",",
"val",
"in",
"self",
".",
"file_dict",
".",
"items",
"(",
")",
":",
"# For temp files we only want files that were marked for removal",
"if",
"val",
"&",
"FileFlags",
"."... | Return a list of the files compressed by this link.
This returns all files that were explicitly marked for compression. | [
"Return",
"a",
"list",
"of",
"the",
"files",
"compressed",
"by",
"this",
"link",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L260-L270 | train | 36,143 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileStageManager.split_local_path | def split_local_path(self, local_file):
"""Split the local path into a directory name and a file name
If local_file is in self.workdir or a subdirectory of it,
the directory will consist of the relative path from workdir.
If local_file is not in self.workdir, directory will be empty.
Returns (dirname, basename)
"""
abspath = os.path.abspath(local_file)
if abspath.find(self.workdir) >= 0:
relpath = abspath.replace(self.workdir, '')[1:]
basename = os.path.basename(relpath)
dirname = os.path.dirname(relpath)
else:
basename = os.path.basename(local_file)
dirname = ''
return (dirname, basename) | python | def split_local_path(self, local_file):
"""Split the local path into a directory name and a file name
If local_file is in self.workdir or a subdirectory of it,
the directory will consist of the relative path from workdir.
If local_file is not in self.workdir, directory will be empty.
Returns (dirname, basename)
"""
abspath = os.path.abspath(local_file)
if abspath.find(self.workdir) >= 0:
relpath = abspath.replace(self.workdir, '')[1:]
basename = os.path.basename(relpath)
dirname = os.path.dirname(relpath)
else:
basename = os.path.basename(local_file)
dirname = ''
return (dirname, basename) | [
"def",
"split_local_path",
"(",
"self",
",",
"local_file",
")",
":",
"abspath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"local_file",
")",
"if",
"abspath",
".",
"find",
"(",
"self",
".",
"workdir",
")",
">=",
"0",
":",
"relpath",
"=",
"abspath",
... | Split the local path into a directory name and a file name
If local_file is in self.workdir or a subdirectory of it,
the directory will consist of the relative path from workdir.
If local_file is not in self.workdir, directory will be empty.
Returns (dirname, basename) | [
"Split",
"the",
"local",
"path",
"into",
"a",
"directory",
"name",
"and",
"a",
"file",
"name"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L319-L337 | train | 36,144 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileStageManager.construct_scratch_path | def construct_scratch_path(self, dirname, basename):
"""Construct and return a path in the scratch area.
This will be <self.scratchdir>/<dirname>/<basename>
"""
return os.path.join(self.scratchdir, dirname, basename) | python | def construct_scratch_path(self, dirname, basename):
"""Construct and return a path in the scratch area.
This will be <self.scratchdir>/<dirname>/<basename>
"""
return os.path.join(self.scratchdir, dirname, basename) | [
"def",
"construct_scratch_path",
"(",
"self",
",",
"dirname",
",",
"basename",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"scratchdir",
",",
"dirname",
",",
"basename",
")"
] | Construct and return a path in the scratch area.
This will be <self.scratchdir>/<dirname>/<basename> | [
"Construct",
"and",
"return",
"a",
"path",
"in",
"the",
"scratch",
"area",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L339-L344 | train | 36,145 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileStageManager.get_scratch_path | def get_scratch_path(self, local_file):
"""Construct and return a path in the scratch area from a local file.
"""
(local_dirname, local_basename) = self.split_local_path(local_file)
return self.construct_scratch_path(local_dirname, local_basename) | python | def get_scratch_path(self, local_file):
"""Construct and return a path in the scratch area from a local file.
"""
(local_dirname, local_basename) = self.split_local_path(local_file)
return self.construct_scratch_path(local_dirname, local_basename) | [
"def",
"get_scratch_path",
"(",
"self",
",",
"local_file",
")",
":",
"(",
"local_dirname",
",",
"local_basename",
")",
"=",
"self",
".",
"split_local_path",
"(",
"local_file",
")",
"return",
"self",
".",
"construct_scratch_path",
"(",
"local_dirname",
",",
"loca... | Construct and return a path in the scratch area from a local file. | [
"Construct",
"and",
"return",
"a",
"path",
"in",
"the",
"scratch",
"area",
"from",
"a",
"local",
"file",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L346-L350 | train | 36,146 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileStageManager.map_files | def map_files(self, local_files):
"""Build a dictionary mapping local paths to scratch paths.
Parameters
----------
local_files : list
List of filenames to be mapped to scratch area
Returns dict
Mapping local_file : fullpath of scratch file
"""
ret_dict = {}
for local_file in local_files:
ret_dict[local_file] = self.get_scratch_path(local_file)
return ret_dict | python | def map_files(self, local_files):
"""Build a dictionary mapping local paths to scratch paths.
Parameters
----------
local_files : list
List of filenames to be mapped to scratch area
Returns dict
Mapping local_file : fullpath of scratch file
"""
ret_dict = {}
for local_file in local_files:
ret_dict[local_file] = self.get_scratch_path(local_file)
return ret_dict | [
"def",
"map_files",
"(",
"self",
",",
"local_files",
")",
":",
"ret_dict",
"=",
"{",
"}",
"for",
"local_file",
"in",
"local_files",
":",
"ret_dict",
"[",
"local_file",
"]",
"=",
"self",
".",
"get_scratch_path",
"(",
"local_file",
")",
"return",
"ret_dict"
] | Build a dictionary mapping local paths to scratch paths.
Parameters
----------
local_files : list
List of filenames to be mapped to scratch area
Returns dict
Mapping local_file : fullpath of scratch file | [
"Build",
"a",
"dictionary",
"mapping",
"local",
"paths",
"to",
"scratch",
"paths",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L352-L367 | train | 36,147 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileStageManager.make_scratch_dirs | def make_scratch_dirs(file_mapping, dry_run=True):
"""Make any directories need in the scratch area"""
scratch_dirs = {}
for value in file_mapping.values():
scratch_dirname = os.path.dirname(value)
scratch_dirs[scratch_dirname] = True
for scratch_dirname in scratch_dirs:
if dry_run:
print("mkdir -f %s" % (scratch_dirname))
else:
try:
os.makedirs(scratch_dirname)
except OSError:
pass | python | def make_scratch_dirs(file_mapping, dry_run=True):
"""Make any directories need in the scratch area"""
scratch_dirs = {}
for value in file_mapping.values():
scratch_dirname = os.path.dirname(value)
scratch_dirs[scratch_dirname] = True
for scratch_dirname in scratch_dirs:
if dry_run:
print("mkdir -f %s" % (scratch_dirname))
else:
try:
os.makedirs(scratch_dirname)
except OSError:
pass | [
"def",
"make_scratch_dirs",
"(",
"file_mapping",
",",
"dry_run",
"=",
"True",
")",
":",
"scratch_dirs",
"=",
"{",
"}",
"for",
"value",
"in",
"file_mapping",
".",
"values",
"(",
")",
":",
"scratch_dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"va... | Make any directories need in the scratch area | [
"Make",
"any",
"directories",
"need",
"in",
"the",
"scratch",
"area"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L370-L383 | train | 36,148 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileStageManager.copy_to_scratch | def copy_to_scratch(file_mapping, dry_run=True):
"""Copy input files to scratch area """
for key, value in file_mapping.items():
if not os.path.exists(key):
continue
if dry_run:
print ("copy %s %s" % (key, value))
else:
print ("copy %s %s" % (key, value))
copyfile(key, value)
return file_mapping | python | def copy_to_scratch(file_mapping, dry_run=True):
"""Copy input files to scratch area """
for key, value in file_mapping.items():
if not os.path.exists(key):
continue
if dry_run:
print ("copy %s %s" % (key, value))
else:
print ("copy %s %s" % (key, value))
copyfile(key, value)
return file_mapping | [
"def",
"copy_to_scratch",
"(",
"file_mapping",
",",
"dry_run",
"=",
"True",
")",
":",
"for",
"key",
",",
"value",
"in",
"file_mapping",
".",
"items",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"key",
")",
":",
"continue",
"if"... | Copy input files to scratch area | [
"Copy",
"input",
"files",
"to",
"scratch",
"area"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L386-L397 | train | 36,149 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileStageManager.copy_from_scratch | def copy_from_scratch(file_mapping, dry_run=True):
"""Copy output files from scratch area """
for key, value in file_mapping.items():
if dry_run:
print ("copy %s %s" % (value, key))
else:
try:
outdir = os.path.dirname(key)
os.makedirs(outdir)
except OSError:
pass
print ("copy %s %s" % (value, key))
copyfile(value, key)
return file_mapping | python | def copy_from_scratch(file_mapping, dry_run=True):
"""Copy output files from scratch area """
for key, value in file_mapping.items():
if dry_run:
print ("copy %s %s" % (value, key))
else:
try:
outdir = os.path.dirname(key)
os.makedirs(outdir)
except OSError:
pass
print ("copy %s %s" % (value, key))
copyfile(value, key)
return file_mapping | [
"def",
"copy_from_scratch",
"(",
"file_mapping",
",",
"dry_run",
"=",
"True",
")",
":",
"for",
"key",
",",
"value",
"in",
"file_mapping",
".",
"items",
"(",
")",
":",
"if",
"dry_run",
":",
"print",
"(",
"\"copy %s %s\"",
"%",
"(",
"value",
",",
"key",
... | Copy output files from scratch area | [
"Copy",
"output",
"files",
"from",
"scratch",
"area"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L400-L413 | train | 36,150 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileHandle.make_table | def make_table(file_dict):
"""Build and return an `astropy.table.Table` to store `FileHandle`"""
col_key = Column(name='key', dtype=int)
col_path = Column(name='path', dtype='S256')
col_creator = Column(name='creator', dtype=int)
col_timestamp = Column(name='timestamp', dtype=int)
col_status = Column(name='status', dtype=int)
col_flags = Column(name='flags', dtype=int)
columns = [col_key, col_path, col_creator,
col_timestamp, col_status, col_flags]
table = Table(data=columns)
for val in file_dict.values():
val.append_to_table(table)
return table | python | def make_table(file_dict):
"""Build and return an `astropy.table.Table` to store `FileHandle`"""
col_key = Column(name='key', dtype=int)
col_path = Column(name='path', dtype='S256')
col_creator = Column(name='creator', dtype=int)
col_timestamp = Column(name='timestamp', dtype=int)
col_status = Column(name='status', dtype=int)
col_flags = Column(name='flags', dtype=int)
columns = [col_key, col_path, col_creator,
col_timestamp, col_status, col_flags]
table = Table(data=columns)
for val in file_dict.values():
val.append_to_table(table)
return table | [
"def",
"make_table",
"(",
"file_dict",
")",
":",
"col_key",
"=",
"Column",
"(",
"name",
"=",
"'key'",
",",
"dtype",
"=",
"int",
")",
"col_path",
"=",
"Column",
"(",
"name",
"=",
"'path'",
",",
"dtype",
"=",
"'S256'",
")",
"col_creator",
"=",
"Column",
... | Build and return an `astropy.table.Table` to store `FileHandle` | [
"Build",
"and",
"return",
"an",
"astropy",
".",
"table",
".",
"Table",
"to",
"store",
"FileHandle"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L456-L469 | train | 36,151 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileHandle.make_dict | def make_dict(cls, table):
"""Build and return a dict of `FileHandle` from an `astropy.table.Table`
The dictionary is keyed by FileHandle.key, which is a unique integer for each file
"""
ret_dict = {}
for row in table:
file_handle = cls.create_from_row(row)
ret_dict[file_handle.key] = file_handle
return ret_dict | python | def make_dict(cls, table):
"""Build and return a dict of `FileHandle` from an `astropy.table.Table`
The dictionary is keyed by FileHandle.key, which is a unique integer for each file
"""
ret_dict = {}
for row in table:
file_handle = cls.create_from_row(row)
ret_dict[file_handle.key] = file_handle
return ret_dict | [
"def",
"make_dict",
"(",
"cls",
",",
"table",
")",
":",
"ret_dict",
"=",
"{",
"}",
"for",
"row",
"in",
"table",
":",
"file_handle",
"=",
"cls",
".",
"create_from_row",
"(",
"row",
")",
"ret_dict",
"[",
"file_handle",
".",
"key",
"]",
"=",
"file_handle"... | Build and return a dict of `FileHandle` from an `astropy.table.Table`
The dictionary is keyed by FileHandle.key, which is a unique integer for each file | [
"Build",
"and",
"return",
"a",
"dict",
"of",
"FileHandle",
"from",
"an",
"astropy",
".",
"table",
".",
"Table"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L472-L481 | train | 36,152 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileHandle.create_from_row | def create_from_row(cls, table_row):
"""Build and return a `FileHandle` from an `astropy.table.row.Row` """
kwargs = {}
for key in table_row.colnames:
kwargs[key] = table_row[key]
try:
return cls(**kwargs)
except KeyError:
print(kwargs) | python | def create_from_row(cls, table_row):
"""Build and return a `FileHandle` from an `astropy.table.row.Row` """
kwargs = {}
for key in table_row.colnames:
kwargs[key] = table_row[key]
try:
return cls(**kwargs)
except KeyError:
print(kwargs) | [
"def",
"create_from_row",
"(",
"cls",
",",
"table_row",
")",
":",
"kwargs",
"=",
"{",
"}",
"for",
"key",
"in",
"table_row",
".",
"colnames",
":",
"kwargs",
"[",
"key",
"]",
"=",
"table_row",
"[",
"key",
"]",
"try",
":",
"return",
"cls",
"(",
"*",
"... | Build and return a `FileHandle` from an `astropy.table.row.Row` | [
"Build",
"and",
"return",
"a",
"FileHandle",
"from",
"an",
"astropy",
".",
"table",
".",
"row",
".",
"Row"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L484-L492 | train | 36,153 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileHandle.check_status | def check_status(self, basepath=None):
"""Check on the status of this particular file"""
if basepath is None:
fullpath = self.path
else:
fullpath = os.path.join(basepath, self.path)
exists = os.path.exists(fullpath)
if not exists:
if self.flags & FileFlags.gz_mask != 0:
fullpath += '.gz'
exists = os.path.exists(fullpath)
if exists:
if self.status == FileStatus.superseded:
pass
else:
self.status = FileStatus.exists
else:
if self.status in [FileStatus.no_file,
FileStatus.expected,
FileStatus.missing,
FileStatus.temp_removed]:
if self.flags & FileFlags.rmint_mask != 0:
self.status = FileStatus.temp_removed
elif self.status == FileStatus.exists:
self.status = FileStatus.missing
elif self.status == FileStatus.exists:
self.status = FileStatus.temp_removed
return self.status | python | def check_status(self, basepath=None):
"""Check on the status of this particular file"""
if basepath is None:
fullpath = self.path
else:
fullpath = os.path.join(basepath, self.path)
exists = os.path.exists(fullpath)
if not exists:
if self.flags & FileFlags.gz_mask != 0:
fullpath += '.gz'
exists = os.path.exists(fullpath)
if exists:
if self.status == FileStatus.superseded:
pass
else:
self.status = FileStatus.exists
else:
if self.status in [FileStatus.no_file,
FileStatus.expected,
FileStatus.missing,
FileStatus.temp_removed]:
if self.flags & FileFlags.rmint_mask != 0:
self.status = FileStatus.temp_removed
elif self.status == FileStatus.exists:
self.status = FileStatus.missing
elif self.status == FileStatus.exists:
self.status = FileStatus.temp_removed
return self.status | [
"def",
"check_status",
"(",
"self",
",",
"basepath",
"=",
"None",
")",
":",
"if",
"basepath",
"is",
"None",
":",
"fullpath",
"=",
"self",
".",
"path",
"else",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"basepath",
",",
"self",
".",
... | Check on the status of this particular file | [
"Check",
"on",
"the",
"status",
"of",
"this",
"particular",
"file"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L494-L522 | train | 36,154 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileHandle.update_table_row | def update_table_row(self, table, row_idx):
"""Update the values in an `astropy.table.Table` for this instances"""
table[row_idx]['path'] = self.path
table[row_idx]['key'] = self.key
table[row_idx]['creator'] = self.creator
table[row_idx]['timestamp'] = self.timestamp
table[row_idx]['status'] = self.status
table[row_idx]['flags'] = self.flags | python | def update_table_row(self, table, row_idx):
"""Update the values in an `astropy.table.Table` for this instances"""
table[row_idx]['path'] = self.path
table[row_idx]['key'] = self.key
table[row_idx]['creator'] = self.creator
table[row_idx]['timestamp'] = self.timestamp
table[row_idx]['status'] = self.status
table[row_idx]['flags'] = self.flags | [
"def",
"update_table_row",
"(",
"self",
",",
"table",
",",
"row_idx",
")",
":",
"table",
"[",
"row_idx",
"]",
"[",
"'path'",
"]",
"=",
"self",
".",
"path",
"table",
"[",
"row_idx",
"]",
"[",
"'key'",
"]",
"=",
"self",
".",
"key",
"table",
"[",
"row... | Update the values in an `astropy.table.Table` for this instances | [
"Update",
"the",
"values",
"in",
"an",
"astropy",
".",
"table",
".",
"Table",
"for",
"this",
"instances"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L533-L540 | train | 36,155 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileArchive._get_fullpath | def _get_fullpath(self, filepath):
"""Return filepath with the base_path prefixed """
if filepath[0] == '/':
return filepath
return os.path.join(self._base_path, filepath) | python | def _get_fullpath(self, filepath):
"""Return filepath with the base_path prefixed """
if filepath[0] == '/':
return filepath
return os.path.join(self._base_path, filepath) | [
"def",
"_get_fullpath",
"(",
"self",
",",
"filepath",
")",
":",
"if",
"filepath",
"[",
"0",
"]",
"==",
"'/'",
":",
"return",
"filepath",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_base_path",
",",
"filepath",
")"
] | Return filepath with the base_path prefixed | [
"Return",
"filepath",
"with",
"the",
"base_path",
"prefixed"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L597-L601 | train | 36,156 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileArchive._read_table_file | def _read_table_file(self, table_file):
"""Read an `astropy.table.Table` to set up the archive"""
self._table_file = table_file
if os.path.exists(self._table_file):
self._table = Table.read(self._table_file)
else:
self._table = FileHandle.make_table({})
self._fill_cache() | python | def _read_table_file(self, table_file):
"""Read an `astropy.table.Table` to set up the archive"""
self._table_file = table_file
if os.path.exists(self._table_file):
self._table = Table.read(self._table_file)
else:
self._table = FileHandle.make_table({})
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` to set up the archive | [
"Read",
"an",
"astropy",
".",
"table",
".",
"Table",
"to",
"set",
"up",
"the",
"archive"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L613-L620 | train | 36,157 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileArchive._make_file_handle | def _make_file_handle(self, row_idx):
"""Build and return a `FileHandle` object from an `astropy.table.row.Row` """
row = self._table[row_idx]
return FileHandle.create_from_row(row) | python | def _make_file_handle(self, row_idx):
"""Build and return a `FileHandle` object from an `astropy.table.row.Row` """
row = self._table[row_idx]
return FileHandle.create_from_row(row) | [
"def",
"_make_file_handle",
"(",
"self",
",",
"row_idx",
")",
":",
"row",
"=",
"self",
".",
"_table",
"[",
"row_idx",
"]",
"return",
"FileHandle",
".",
"create_from_row",
"(",
"row",
")"
] | Build and return a `FileHandle` object from an `astropy.table.row.Row` | [
"Build",
"and",
"return",
"a",
"FileHandle",
"object",
"from",
"an",
"astropy",
".",
"table",
".",
"row",
".",
"Row"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L622-L625 | train | 36,158 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileArchive.get_handle | def get_handle(self, filepath):
"""Get the `FileHandle` object associated to a particular file """
localpath = self._get_localpath(filepath)
return self._cache[localpath] | python | def get_handle(self, filepath):
"""Get the `FileHandle` object associated to a particular file """
localpath = self._get_localpath(filepath)
return self._cache[localpath] | [
"def",
"get_handle",
"(",
"self",
",",
"filepath",
")",
":",
"localpath",
"=",
"self",
".",
"_get_localpath",
"(",
"filepath",
")",
"return",
"self",
".",
"_cache",
"[",
"localpath",
"]"
] | Get the `FileHandle` object associated to a particular file | [
"Get",
"the",
"FileHandle",
"object",
"associated",
"to",
"a",
"particular",
"file"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L627-L630 | train | 36,159 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileArchive.register_file | def register_file(self, filepath, creator, status=FileStatus.no_file, flags=FileFlags.no_flags):
"""Register a file in the archive.
If the file already exists, this raises a `KeyError`
Parameters
----------
filepath : str
The path to the file
creatror : int
A unique key for the job that created this file
status : `FileStatus`
Enumeration giving current status of file
flags : `FileFlags`
Enumeration giving flags set on this file
Returns `FileHandle`
"""
# check to see if the file already exists
try:
file_handle = self.get_handle(filepath)
raise KeyError("File %s already exists in archive" % filepath)
except KeyError:
pass
localpath = self._get_localpath(filepath)
if status == FileStatus.exists:
# Make sure the file really exists
fullpath = self._get_fullpath(filepath)
if not os.path.exists(fullpath):
print("register_file called on called on mising file %s" % fullpath)
status = FileStatus.missing
timestamp = 0
else:
timestamp = int(os.stat(fullpath).st_mtime)
else:
timestamp = 0
key = len(self._table) + 1
file_handle = FileHandle(path=localpath,
key=key,
creator=creator,
timestamp=timestamp,
status=status,
flags=flags)
file_handle.append_to_table(self._table)
self._cache[localpath] = file_handle
return file_handle | python | def register_file(self, filepath, creator, status=FileStatus.no_file, flags=FileFlags.no_flags):
"""Register a file in the archive.
If the file already exists, this raises a `KeyError`
Parameters
----------
filepath : str
The path to the file
creatror : int
A unique key for the job that created this file
status : `FileStatus`
Enumeration giving current status of file
flags : `FileFlags`
Enumeration giving flags set on this file
Returns `FileHandle`
"""
# check to see if the file already exists
try:
file_handle = self.get_handle(filepath)
raise KeyError("File %s already exists in archive" % filepath)
except KeyError:
pass
localpath = self._get_localpath(filepath)
if status == FileStatus.exists:
# Make sure the file really exists
fullpath = self._get_fullpath(filepath)
if not os.path.exists(fullpath):
print("register_file called on called on mising file %s" % fullpath)
status = FileStatus.missing
timestamp = 0
else:
timestamp = int(os.stat(fullpath).st_mtime)
else:
timestamp = 0
key = len(self._table) + 1
file_handle = FileHandle(path=localpath,
key=key,
creator=creator,
timestamp=timestamp,
status=status,
flags=flags)
file_handle.append_to_table(self._table)
self._cache[localpath] = file_handle
return file_handle | [
"def",
"register_file",
"(",
"self",
",",
"filepath",
",",
"creator",
",",
"status",
"=",
"FileStatus",
".",
"no_file",
",",
"flags",
"=",
"FileFlags",
".",
"no_flags",
")",
":",
"# check to see if the file already exists",
"try",
":",
"file_handle",
"=",
"self"... | Register a file in the archive.
If the file already exists, this raises a `KeyError`
Parameters
----------
filepath : str
The path to the file
creatror : int
A unique key for the job that created this file
status : `FileStatus`
Enumeration giving current status of file
flags : `FileFlags`
Enumeration giving flags set on this file
Returns `FileHandle` | [
"Register",
"a",
"file",
"in",
"the",
"archive",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L632-L678 | train | 36,160 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileArchive.update_file | def update_file(self, filepath, creator, status):
"""Update a file in the archive
If the file does not exists, this raises a `KeyError`
Parameters
----------
filepath : str
The path to the file
creatror : int
A unique key for the job that created this file
status : `FileStatus`
Enumeration giving current status of file
Returns `FileHandle`
"""
file_handle = self.get_handle(filepath)
if status in [FileStatus.exists, FileStatus.superseded]:
# Make sure the file really exists
fullpath = file_handle.fullpath
if not os.path.exists(fullpath):
raise ValueError("File %s does not exist" % fullpath)
timestamp = int(os.stat(fullpath).st_mtime)
else:
timestamp = 0
file_handle.creator = creator
file_handle.timestamp = timestamp
file_handle.status = status
file_handle.update_table_row(self._table, file_handle.key - 1)
return file_handle | python | def update_file(self, filepath, creator, status):
"""Update a file in the archive
If the file does not exists, this raises a `KeyError`
Parameters
----------
filepath : str
The path to the file
creatror : int
A unique key for the job that created this file
status : `FileStatus`
Enumeration giving current status of file
Returns `FileHandle`
"""
file_handle = self.get_handle(filepath)
if status in [FileStatus.exists, FileStatus.superseded]:
# Make sure the file really exists
fullpath = file_handle.fullpath
if not os.path.exists(fullpath):
raise ValueError("File %s does not exist" % fullpath)
timestamp = int(os.stat(fullpath).st_mtime)
else:
timestamp = 0
file_handle.creator = creator
file_handle.timestamp = timestamp
file_handle.status = status
file_handle.update_table_row(self._table, file_handle.key - 1)
return file_handle | [
"def",
"update_file",
"(",
"self",
",",
"filepath",
",",
"creator",
",",
"status",
")",
":",
"file_handle",
"=",
"self",
".",
"get_handle",
"(",
"filepath",
")",
"if",
"status",
"in",
"[",
"FileStatus",
".",
"exists",
",",
"FileStatus",
".",
"superseded",
... | Update a file in the archive
If the file does not exists, this raises a `KeyError`
Parameters
----------
filepath : str
The path to the file
creatror : int
A unique key for the job that created this file
status : `FileStatus`
Enumeration giving current status of file
Returns `FileHandle` | [
"Update",
"a",
"file",
"in",
"the",
"archive"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L680-L710 | train | 36,161 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileArchive.get_file_ids | def get_file_ids(self, file_list, creator=None,
status=FileStatus.no_file, file_dict=None):
"""Get or create a list of file ids based on file names
Parameters
----------
file_list : list
The paths to the file
creatror : int
A unique key for the job that created these files
status : `FileStatus`
Enumeration giving current status of files
file_dict : `FileDict`
Mask giving flags set on this file
Returns list of integers
"""
ret_list = []
for fname in file_list:
if file_dict is None:
flags = FileFlags.no_flags
else:
flags = file_dict.file_dict[fname]
try:
fhandle = self.get_handle(fname)
except KeyError:
if creator is None:
creator = -1
# raise KeyError("Can not register a file %s without a creator"%fname)
fhandle = self.register_file(fname, creator, status, flags)
ret_list.append(fhandle.key)
return ret_list | python | def get_file_ids(self, file_list, creator=None,
status=FileStatus.no_file, file_dict=None):
"""Get or create a list of file ids based on file names
Parameters
----------
file_list : list
The paths to the file
creatror : int
A unique key for the job that created these files
status : `FileStatus`
Enumeration giving current status of files
file_dict : `FileDict`
Mask giving flags set on this file
Returns list of integers
"""
ret_list = []
for fname in file_list:
if file_dict is None:
flags = FileFlags.no_flags
else:
flags = file_dict.file_dict[fname]
try:
fhandle = self.get_handle(fname)
except KeyError:
if creator is None:
creator = -1
# raise KeyError("Can not register a file %s without a creator"%fname)
fhandle = self.register_file(fname, creator, status, flags)
ret_list.append(fhandle.key)
return ret_list | [
"def",
"get_file_ids",
"(",
"self",
",",
"file_list",
",",
"creator",
"=",
"None",
",",
"status",
"=",
"FileStatus",
".",
"no_file",
",",
"file_dict",
"=",
"None",
")",
":",
"ret_list",
"=",
"[",
"]",
"for",
"fname",
"in",
"file_list",
":",
"if",
"file... | Get or create a list of file ids based on file names
Parameters
----------
file_list : list
The paths to the file
creatror : int
A unique key for the job that created these files
status : `FileStatus`
Enumeration giving current status of files
file_dict : `FileDict`
Mask giving flags set on this file
Returns list of integers | [
"Get",
"or",
"create",
"a",
"list",
"of",
"file",
"ids",
"based",
"on",
"file",
"names"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L712-L744 | train | 36,162 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileArchive.get_file_paths | def get_file_paths(self, id_list):
"""Get a list of file paths based of a set of ids
Parameters
----------
id_list : list
List of integer file keys
Returns list of file paths
"""
if id_list is None:
return []
try:
path_array = self._table[id_list - 1]['path']
except IndexError:
print("IndexError ", len(self._table), id_list)
path_array = []
return [path for path in path_array] | python | def get_file_paths(self, id_list):
"""Get a list of file paths based of a set of ids
Parameters
----------
id_list : list
List of integer file keys
Returns list of file paths
"""
if id_list is None:
return []
try:
path_array = self._table[id_list - 1]['path']
except IndexError:
print("IndexError ", len(self._table), id_list)
path_array = []
return [path for path in path_array] | [
"def",
"get_file_paths",
"(",
"self",
",",
"id_list",
")",
":",
"if",
"id_list",
"is",
"None",
":",
"return",
"[",
"]",
"try",
":",
"path_array",
"=",
"self",
".",
"_table",
"[",
"id_list",
"-",
"1",
"]",
"[",
"'path'",
"]",
"except",
"IndexError",
"... | Get a list of file paths based of a set of ids
Parameters
----------
id_list : list
List of integer file keys
Returns list of file paths | [
"Get",
"a",
"list",
"of",
"file",
"paths",
"based",
"of",
"a",
"set",
"of",
"ids"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L746-L764 | train | 36,163 |
fermiPy/fermipy | fermipy/jobs/file_archive.py | FileArchive.update_file_status | def update_file_status(self):
"""Update the status of all the files in the archive"""
nfiles = len(self.cache.keys())
status_vect = np.zeros((6), int)
sys.stdout.write("Updating status of %i files: " % nfiles)
sys.stdout.flush()
for i, key in enumerate(self.cache.keys()):
if i % 200 == 0:
sys.stdout.write('.')
sys.stdout.flush()
fhandle = self.cache[key]
fhandle.check_status(self._base_path)
fhandle.update_table_row(self._table, fhandle.key - 1)
status_vect[fhandle.status] += 1
sys.stdout.write("!\n")
sys.stdout.flush()
sys.stdout.write("Summary:\n")
sys.stdout.write(" no_file: %i\n" % status_vect[0])
sys.stdout.write(" expected: %i\n" % status_vect[1])
sys.stdout.write(" exists: %i\n" % status_vect[2])
sys.stdout.write(" missing: %i\n" % status_vect[3])
sys.stdout.write(" superseded: %i\n" % status_vect[4])
sys.stdout.write(" temp_removed: %i\n" % status_vect[5]) | python | def update_file_status(self):
"""Update the status of all the files in the archive"""
nfiles = len(self.cache.keys())
status_vect = np.zeros((6), int)
sys.stdout.write("Updating status of %i files: " % nfiles)
sys.stdout.flush()
for i, key in enumerate(self.cache.keys()):
if i % 200 == 0:
sys.stdout.write('.')
sys.stdout.flush()
fhandle = self.cache[key]
fhandle.check_status(self._base_path)
fhandle.update_table_row(self._table, fhandle.key - 1)
status_vect[fhandle.status] += 1
sys.stdout.write("!\n")
sys.stdout.flush()
sys.stdout.write("Summary:\n")
sys.stdout.write(" no_file: %i\n" % status_vect[0])
sys.stdout.write(" expected: %i\n" % status_vect[1])
sys.stdout.write(" exists: %i\n" % status_vect[2])
sys.stdout.write(" missing: %i\n" % status_vect[3])
sys.stdout.write(" superseded: %i\n" % status_vect[4])
sys.stdout.write(" temp_removed: %i\n" % status_vect[5]) | [
"def",
"update_file_status",
"(",
"self",
")",
":",
"nfiles",
"=",
"len",
"(",
"self",
".",
"cache",
".",
"keys",
"(",
")",
")",
"status_vect",
"=",
"np",
".",
"zeros",
"(",
"(",
"6",
")",
",",
"int",
")",
"sys",
".",
"stdout",
".",
"write",
"(",... | Update the status of all the files in the archive | [
"Update",
"the",
"status",
"of",
"all",
"the",
"files",
"in",
"the",
"archive"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/file_archive.py#L777-L800 | train | 36,164 |
fermiPy/fermipy | fermipy/stats_utils.py | norm | def norm(x, mu, sigma=1.0):
""" Scipy norm function """
return stats.norm(loc=mu, scale=sigma).pdf(x) | python | def norm(x, mu, sigma=1.0):
""" Scipy norm function """
return stats.norm(loc=mu, scale=sigma).pdf(x) | [
"def",
"norm",
"(",
"x",
",",
"mu",
",",
"sigma",
"=",
"1.0",
")",
":",
"return",
"stats",
".",
"norm",
"(",
"loc",
"=",
"mu",
",",
"scale",
"=",
"sigma",
")",
".",
"pdf",
"(",
"x",
")"
] | Scipy norm function | [
"Scipy",
"norm",
"function"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L14-L16 | train | 36,165 |
fermiPy/fermipy | fermipy/stats_utils.py | ln_norm | def ln_norm(x, mu, sigma=1.0):
""" Natural log of scipy norm function truncated at zero """
return np.log(stats.norm(loc=mu, scale=sigma).pdf(x)) | python | def ln_norm(x, mu, sigma=1.0):
""" Natural log of scipy norm function truncated at zero """
return np.log(stats.norm(loc=mu, scale=sigma).pdf(x)) | [
"def",
"ln_norm",
"(",
"x",
",",
"mu",
",",
"sigma",
"=",
"1.0",
")",
":",
"return",
"np",
".",
"log",
"(",
"stats",
".",
"norm",
"(",
"loc",
"=",
"mu",
",",
"scale",
"=",
"sigma",
")",
".",
"pdf",
"(",
"x",
")",
")"
] | Natural log of scipy norm function truncated at zero | [
"Natural",
"log",
"of",
"scipy",
"norm",
"function",
"truncated",
"at",
"zero"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L19-L21 | train | 36,166 |
fermiPy/fermipy | fermipy/stats_utils.py | lognorm | def lognorm(x, mu, sigma=1.0):
""" Log-normal function from scipy """
return stats.lognorm(sigma, scale=mu).pdf(x) | python | def lognorm(x, mu, sigma=1.0):
""" Log-normal function from scipy """
return stats.lognorm(sigma, scale=mu).pdf(x) | [
"def",
"lognorm",
"(",
"x",
",",
"mu",
",",
"sigma",
"=",
"1.0",
")",
":",
"return",
"stats",
".",
"lognorm",
"(",
"sigma",
",",
"scale",
"=",
"mu",
")",
".",
"pdf",
"(",
"x",
")"
] | Log-normal function from scipy | [
"Log",
"-",
"normal",
"function",
"from",
"scipy"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L24-L26 | train | 36,167 |
fermiPy/fermipy | fermipy/stats_utils.py | lgauss | def lgauss(x, mu, sigma=1.0, logpdf=False):
""" Log10 normal distribution...
x : Parameter of interest for scanning the pdf
mu : Peak of the lognormal distribution (mean of the underlying
normal distribution is log10(mu)
sigma : Standard deviation of the underlying normal distribution
"""
x = np.array(x, ndmin=1)
lmu = np.log10(mu)
s2 = sigma * sigma
lx = np.zeros(x.shape)
v = np.zeros(x.shape)
lx[x > 0] = np.log10(x[x > 0])
v = 1. / np.sqrt(2 * s2 * np.pi) * np.exp(-(lx - lmu)**2 / (2 * s2))
if not logpdf:
v /= (x * np.log(10.))
v[x <= 0] = -np.inf
return v | python | def lgauss(x, mu, sigma=1.0, logpdf=False):
""" Log10 normal distribution...
x : Parameter of interest for scanning the pdf
mu : Peak of the lognormal distribution (mean of the underlying
normal distribution is log10(mu)
sigma : Standard deviation of the underlying normal distribution
"""
x = np.array(x, ndmin=1)
lmu = np.log10(mu)
s2 = sigma * sigma
lx = np.zeros(x.shape)
v = np.zeros(x.shape)
lx[x > 0] = np.log10(x[x > 0])
v = 1. / np.sqrt(2 * s2 * np.pi) * np.exp(-(lx - lmu)**2 / (2 * s2))
if not logpdf:
v /= (x * np.log(10.))
v[x <= 0] = -np.inf
return v | [
"def",
"lgauss",
"(",
"x",
",",
"mu",
",",
"sigma",
"=",
"1.0",
",",
"logpdf",
"=",
"False",
")",
":",
"x",
"=",
"np",
".",
"array",
"(",
"x",
",",
"ndmin",
"=",
"1",
")",
"lmu",
"=",
"np",
".",
"log10",
"(",
"mu",
")",
"s2",
"=",
"sigma",
... | Log10 normal distribution...
x : Parameter of interest for scanning the pdf
mu : Peak of the lognormal distribution (mean of the underlying
normal distribution is log10(mu)
sigma : Standard deviation of the underlying normal distribution | [
"Log10",
"normal",
"distribution",
"..."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L53-L78 | train | 36,168 |
fermiPy/fermipy | fermipy/stats_utils.py | create_prior_functor | def create_prior_functor(d):
"""Build a prior from a dictionary.
Parameters
----------
d : A dictionary, it must contain:
d['functype'] : a recognized function type
and all of the required parameters for the
prior_functor of the desired type
Returns
----------
A sub-class of '~fermipy.stats_utils.prior_functor'
Recognized types are:
'lognorm' : Scipy lognormal distribution
'norm' : Scipy normal distribution
'gauss' : Gaussian truncated at zero
'lgauss' : Gaussian in log-space
'lgauss_like' : Gaussian in log-space, with arguments reversed.
'lgauss_logpdf' : ???
"""
functype = d.get('functype', 'lgauss_like')
j_ref = d.get('j_ref', 1.0)
if functype == 'norm':
return norm_prior(d['mu'], d['sigma'], j_ref)
elif functype == 'lognorm':
return lognorm_prior(d['mu'], d['sigma'], j_ref)
elif functype == 'gauss':
return function_prior(functype, d['mu'], d['sigma'], gauss, lngauss, j_ref)
elif functype == 'lgauss':
return function_prior(functype, d['mu'], d['sigma'], lgauss, lnlgauss, j_ref)
elif functype in ['lgauss_like', 'lgauss_lik']:
def fn(x, y, s): return lgauss(y, x, s)
def lnfn(x, y, s): return lnlgauss(y, x, s)
return function_prior(functype, d['mu'], d['sigma'], fn, lnfn, j_ref)
elif functype == 'lgauss_log':
def fn(x, y, s): return lgauss(x, y, s, logpdf=True)
def lnfn(x, y, s): return lnlgauss(x, y, s, logpdf=True)
return function_prior(functype, d['mu'], d['sigma'], fn, lnfn, j_ref)
else:
raise KeyError("Unrecognized prior_functor type %s" % functype) | python | def create_prior_functor(d):
"""Build a prior from a dictionary.
Parameters
----------
d : A dictionary, it must contain:
d['functype'] : a recognized function type
and all of the required parameters for the
prior_functor of the desired type
Returns
----------
A sub-class of '~fermipy.stats_utils.prior_functor'
Recognized types are:
'lognorm' : Scipy lognormal distribution
'norm' : Scipy normal distribution
'gauss' : Gaussian truncated at zero
'lgauss' : Gaussian in log-space
'lgauss_like' : Gaussian in log-space, with arguments reversed.
'lgauss_logpdf' : ???
"""
functype = d.get('functype', 'lgauss_like')
j_ref = d.get('j_ref', 1.0)
if functype == 'norm':
return norm_prior(d['mu'], d['sigma'], j_ref)
elif functype == 'lognorm':
return lognorm_prior(d['mu'], d['sigma'], j_ref)
elif functype == 'gauss':
return function_prior(functype, d['mu'], d['sigma'], gauss, lngauss, j_ref)
elif functype == 'lgauss':
return function_prior(functype, d['mu'], d['sigma'], lgauss, lnlgauss, j_ref)
elif functype in ['lgauss_like', 'lgauss_lik']:
def fn(x, y, s): return lgauss(y, x, s)
def lnfn(x, y, s): return lnlgauss(y, x, s)
return function_prior(functype, d['mu'], d['sigma'], fn, lnfn, j_ref)
elif functype == 'lgauss_log':
def fn(x, y, s): return lgauss(x, y, s, logpdf=True)
def lnfn(x, y, s): return lnlgauss(x, y, s, logpdf=True)
return function_prior(functype, d['mu'], d['sigma'], fn, lnfn, j_ref)
else:
raise KeyError("Unrecognized prior_functor type %s" % functype) | [
"def",
"create_prior_functor",
"(",
"d",
")",
":",
"functype",
"=",
"d",
".",
"get",
"(",
"'functype'",
",",
"'lgauss_like'",
")",
"j_ref",
"=",
"d",
".",
"get",
"(",
"'j_ref'",
",",
"1.0",
")",
"if",
"functype",
"==",
"'norm'",
":",
"return",
"norm_pr... | Build a prior from a dictionary.
Parameters
----------
d : A dictionary, it must contain:
d['functype'] : a recognized function type
and all of the required parameters for the
prior_functor of the desired type
Returns
----------
A sub-class of '~fermipy.stats_utils.prior_functor'
Recognized types are:
'lognorm' : Scipy lognormal distribution
'norm' : Scipy normal distribution
'gauss' : Gaussian truncated at zero
'lgauss' : Gaussian in log-space
'lgauss_like' : Gaussian in log-space, with arguments reversed.
'lgauss_logpdf' : ??? | [
"Build",
"a",
"prior",
"from",
"a",
"dictionary",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L314-L358 | train | 36,169 |
fermiPy/fermipy | fermipy/stats_utils.py | prior_functor.marginalization_bins | def marginalization_bins(self):
"""Binning to use to do the marginalization integrals
"""
log_mean = np.log10(self.mean())
# Default is to marginalize over two decades,
# centered on mean, using 1000 bins
return np.logspace(-1. + log_mean, 1. + log_mean, 1001)/self._j_ref | python | def marginalization_bins(self):
"""Binning to use to do the marginalization integrals
"""
log_mean = np.log10(self.mean())
# Default is to marginalize over two decades,
# centered on mean, using 1000 bins
return np.logspace(-1. + log_mean, 1. + log_mean, 1001)/self._j_ref | [
"def",
"marginalization_bins",
"(",
"self",
")",
":",
"log_mean",
"=",
"np",
".",
"log10",
"(",
"self",
".",
"mean",
"(",
")",
")",
"# Default is to marginalize over two decades,",
"# centered on mean, using 1000 bins",
"return",
"np",
".",
"logspace",
"(",
"-",
"... | Binning to use to do the marginalization integrals | [
"Binning",
"to",
"use",
"to",
"do",
"the",
"marginalization",
"integrals"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L148-L154 | train | 36,170 |
fermiPy/fermipy | fermipy/stats_utils.py | prior_functor.profile_bins | def profile_bins(self):
""" The binning to use to do the profile fitting
"""
log_mean = np.log10(self.mean())
log_half_width = max(5. * self.sigma(), 3.)
# Default is to profile over +-5 sigma,
# centered on mean, using 100 bins
return np.logspace(log_mean - log_half_width,
log_mean + log_half_width, 101)/self._j_ref | python | def profile_bins(self):
""" The binning to use to do the profile fitting
"""
log_mean = np.log10(self.mean())
log_half_width = max(5. * self.sigma(), 3.)
# Default is to profile over +-5 sigma,
# centered on mean, using 100 bins
return np.logspace(log_mean - log_half_width,
log_mean + log_half_width, 101)/self._j_ref | [
"def",
"profile_bins",
"(",
"self",
")",
":",
"log_mean",
"=",
"np",
".",
"log10",
"(",
"self",
".",
"mean",
"(",
")",
")",
"log_half_width",
"=",
"max",
"(",
"5.",
"*",
"self",
".",
"sigma",
"(",
")",
",",
"3.",
")",
"# Default is to profile over +-5 ... | The binning to use to do the profile fitting | [
"The",
"binning",
"to",
"use",
"to",
"do",
"the",
"profile",
"fitting"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L156-L164 | train | 36,171 |
fermiPy/fermipy | fermipy/stats_utils.py | function_prior.normalization | def normalization(self):
""" The normalization
i.e., the intergral of the function over the normalization_range
"""
norm_r = self.normalization_range()
return quad(self, norm_r[0]*self._j_ref, norm_r[1]*self._j_ref)[0] | python | def normalization(self):
""" The normalization
i.e., the intergral of the function over the normalization_range
"""
norm_r = self.normalization_range()
return quad(self, norm_r[0]*self._j_ref, norm_r[1]*self._j_ref)[0] | [
"def",
"normalization",
"(",
"self",
")",
":",
"norm_r",
"=",
"self",
".",
"normalization_range",
"(",
")",
"return",
"quad",
"(",
"self",
",",
"norm_r",
"[",
"0",
"]",
"*",
"self",
".",
"_j_ref",
",",
"norm_r",
"[",
"1",
"]",
"*",
"self",
".",
"_j... | The normalization
i.e., the intergral of the function over the normalization_range | [
"The",
"normalization",
"i",
".",
"e",
".",
"the",
"intergral",
"of",
"the",
"function",
"over",
"the",
"normalization_range"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L186-L191 | train | 36,172 |
fermiPy/fermipy | fermipy/stats_utils.py | LnLFn_norm_prior.init_return | def init_return(self, ret_type):
"""Specify the return type.
Note that this will also construct the
'~fermipy.castro.Interpolator' object
for the requested return type.
"""
if self._ret_type == ret_type:
return
if ret_type == "straight":
self._interp = self._lnlfn.interp
if ret_type == "profile":
self._profile_loglike_spline(self._lnlfn.interp.x)
#self._profile_loglike(self._lnlfn.interp.x)
self._interp = self._prof_interp
elif ret_type == "marginal":
self._marginal_loglike(self._lnlfn.interp.x)
self._interp = self._marg_interp
elif ret_type == "posterior":
self._posterior(self._lnlfn.interp.x)
self._interp = self._post_interp
else:
raise ValueError("Did not recognize return type %s" % ret_type)
self._ret_type = ret_type | python | def init_return(self, ret_type):
"""Specify the return type.
Note that this will also construct the
'~fermipy.castro.Interpolator' object
for the requested return type.
"""
if self._ret_type == ret_type:
return
if ret_type == "straight":
self._interp = self._lnlfn.interp
if ret_type == "profile":
self._profile_loglike_spline(self._lnlfn.interp.x)
#self._profile_loglike(self._lnlfn.interp.x)
self._interp = self._prof_interp
elif ret_type == "marginal":
self._marginal_loglike(self._lnlfn.interp.x)
self._interp = self._marg_interp
elif ret_type == "posterior":
self._posterior(self._lnlfn.interp.x)
self._interp = self._post_interp
else:
raise ValueError("Did not recognize return type %s" % ret_type)
self._ret_type = ret_type | [
"def",
"init_return",
"(",
"self",
",",
"ret_type",
")",
":",
"if",
"self",
".",
"_ret_type",
"==",
"ret_type",
":",
"return",
"if",
"ret_type",
"==",
"\"straight\"",
":",
"self",
".",
"_interp",
"=",
"self",
".",
"_lnlfn",
".",
"interp",
"if",
"ret_type... | Specify the return type.
Note that this will also construct the
'~fermipy.castro.Interpolator' object
for the requested return type. | [
"Specify",
"the",
"return",
"type",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L431-L455 | train | 36,173 |
fermiPy/fermipy | fermipy/stats_utils.py | LnLFn_norm_prior.clear_cached_values | def clear_cached_values(self):
"""Removes all of the cached values and interpolators
"""
self._prof_interp = None
self._prof_y = None
self._prof_z = None
self._marg_interp = None
self._marg_z = None
self._post = None
self._post_interp = None
self._interp = None
self._ret_type = None | python | def clear_cached_values(self):
"""Removes all of the cached values and interpolators
"""
self._prof_interp = None
self._prof_y = None
self._prof_z = None
self._marg_interp = None
self._marg_z = None
self._post = None
self._post_interp = None
self._interp = None
self._ret_type = None | [
"def",
"clear_cached_values",
"(",
"self",
")",
":",
"self",
".",
"_prof_interp",
"=",
"None",
"self",
".",
"_prof_y",
"=",
"None",
"self",
".",
"_prof_z",
"=",
"None",
"self",
".",
"_marg_interp",
"=",
"None",
"self",
".",
"_marg_z",
"=",
"None",
"self"... | Removes all of the cached values and interpolators | [
"Removes",
"all",
"of",
"the",
"cached",
"values",
"and",
"interpolators"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L457-L468 | train | 36,174 |
fermiPy/fermipy | fermipy/stats_utils.py | LnLFn_norm_prior.profile_loglike | def profile_loglike(self, x):
"""Profile log-likelihood.
Returns ``L_prof(x,y=y_min|z')`` : where y_min is the
value of y that minimizes
L for a given x.
This will used the cached '~fermipy.castro.Interpolator' object
if possible, and construct it if needed.
"""
if self._prof_interp is None:
# This calculates values and caches the spline
return self._profile_loglike(x)[1]
x = np.array(x, ndmin=1)
return self._prof_interp(x) | python | def profile_loglike(self, x):
"""Profile log-likelihood.
Returns ``L_prof(x,y=y_min|z')`` : where y_min is the
value of y that minimizes
L for a given x.
This will used the cached '~fermipy.castro.Interpolator' object
if possible, and construct it if needed.
"""
if self._prof_interp is None:
# This calculates values and caches the spline
return self._profile_loglike(x)[1]
x = np.array(x, ndmin=1)
return self._prof_interp(x) | [
"def",
"profile_loglike",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"_prof_interp",
"is",
"None",
":",
"# This calculates values and caches the spline",
"return",
"self",
".",
"_profile_loglike",
"(",
"x",
")",
"[",
"1",
"]",
"x",
"=",
"np",
".",
... | Profile log-likelihood.
Returns ``L_prof(x,y=y_min|z')`` : where y_min is the
value of y that minimizes
L for a given x.
This will used the cached '~fermipy.castro.Interpolator' object
if possible, and construct it if needed. | [
"Profile",
"log",
"-",
"likelihood",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L512-L527 | train | 36,175 |
fermiPy/fermipy | fermipy/stats_utils.py | LnLFn_norm_prior.marginal_loglike | def marginal_loglike(self, x):
"""Marginal log-likelihood.
Returns ``L_marg(x) = \int L(x,y|z') L(y) dy``
This will used the cached '~fermipy.castro.Interpolator'
object if possible, and construct it if needed.
"""
if self._marg_interp is None:
# This calculates values and caches the spline
return self._marginal_loglike(x)
x = np.array(x, ndmin=1)
return self._marg_interp(x) | python | def marginal_loglike(self, x):
"""Marginal log-likelihood.
Returns ``L_marg(x) = \int L(x,y|z') L(y) dy``
This will used the cached '~fermipy.castro.Interpolator'
object if possible, and construct it if needed.
"""
if self._marg_interp is None:
# This calculates values and caches the spline
return self._marginal_loglike(x)
x = np.array(x, ndmin=1)
return self._marg_interp(x) | [
"def",
"marginal_loglike",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"_marg_interp",
"is",
"None",
":",
"# This calculates values and caches the spline",
"return",
"self",
".",
"_marginal_loglike",
"(",
"x",
")",
"x",
"=",
"np",
".",
"array",
"(",
... | Marginal log-likelihood.
Returns ``L_marg(x) = \int L(x,y|z') L(y) dy``
This will used the cached '~fermipy.castro.Interpolator'
object if possible, and construct it if needed. | [
"Marginal",
"log",
"-",
"likelihood",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L529-L542 | train | 36,176 |
fermiPy/fermipy | fermipy/stats_utils.py | LnLFn_norm_prior.posterior | def posterior(self, x):
"""Posterior function.
Returns ``P(x) = \int L(x,y|z') L(y) dy / \int L(x,y|z') L(y) dx dy``
This will used the cached '~fermipy.castro.Interpolator'
object if possible, and construct it if needed.
"""
if self._post is None:
return self._posterior(x)
x = np.array(x, ndmin=1)
return self._post_interp(x) | python | def posterior(self, x):
"""Posterior function.
Returns ``P(x) = \int L(x,y|z') L(y) dy / \int L(x,y|z') L(y) dx dy``
This will used the cached '~fermipy.castro.Interpolator'
object if possible, and construct it if needed.
"""
if self._post is None:
return self._posterior(x)
x = np.array(x, ndmin=1)
return self._post_interp(x) | [
"def",
"posterior",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"_post",
"is",
"None",
":",
"return",
"self",
".",
"_posterior",
"(",
"x",
")",
"x",
"=",
"np",
".",
"array",
"(",
"x",
",",
"ndmin",
"=",
"1",
")",
"return",
"self",
".",
... | Posterior function.
Returns ``P(x) = \int L(x,y|z') L(y) dy / \int L(x,y|z') L(y) dx dy``
This will used the cached '~fermipy.castro.Interpolator'
object if possible, and construct it if needed. | [
"Posterior",
"function",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L544-L555 | train | 36,177 |
fermiPy/fermipy | fermipy/stats_utils.py | LnLFn_norm_prior._marginal_loglike | def _marginal_loglike(self, x):
"""Internal function to calculate and cache the marginal likelihood
"""
yedge = self._nuis_pdf.marginalization_bins()
yw = yedge[1:] - yedge[:-1]
yc = 0.5 * (yedge[1:] + yedge[:-1])
s = self.like(x[:, np.newaxis], yc[np.newaxis, :])
# This does the marginalization integral
z = 1. * np.sum(s * yw, axis=1)
self._marg_z = np.zeros(z.shape)
msk = z > 0
self._marg_z[msk] = -1 * np.log(z[msk])
# Extrapolate to unphysical values
# FIXME, why is this needed
dlogzdx = (np.log(z[msk][-1]) - np.log(z[msk][-2])
) / (x[msk][-1] - x[msk][-2])
self._marg_z[~msk] = self._marg_z[msk][-1] + \
(self._marg_z[~msk] - self._marg_z[msk][-1]) * dlogzdx
self._marg_interp = castro.Interpolator(x, self._marg_z)
return self._marg_z | python | def _marginal_loglike(self, x):
"""Internal function to calculate and cache the marginal likelihood
"""
yedge = self._nuis_pdf.marginalization_bins()
yw = yedge[1:] - yedge[:-1]
yc = 0.5 * (yedge[1:] + yedge[:-1])
s = self.like(x[:, np.newaxis], yc[np.newaxis, :])
# This does the marginalization integral
z = 1. * np.sum(s * yw, axis=1)
self._marg_z = np.zeros(z.shape)
msk = z > 0
self._marg_z[msk] = -1 * np.log(z[msk])
# Extrapolate to unphysical values
# FIXME, why is this needed
dlogzdx = (np.log(z[msk][-1]) - np.log(z[msk][-2])
) / (x[msk][-1] - x[msk][-2])
self._marg_z[~msk] = self._marg_z[msk][-1] + \
(self._marg_z[~msk] - self._marg_z[msk][-1]) * dlogzdx
self._marg_interp = castro.Interpolator(x, self._marg_z)
return self._marg_z | [
"def",
"_marginal_loglike",
"(",
"self",
",",
"x",
")",
":",
"yedge",
"=",
"self",
".",
"_nuis_pdf",
".",
"marginalization_bins",
"(",
")",
"yw",
"=",
"yedge",
"[",
"1",
":",
"]",
"-",
"yedge",
"[",
":",
"-",
"1",
"]",
"yc",
"=",
"0.5",
"*",
"(",... | Internal function to calculate and cache the marginal likelihood | [
"Internal",
"function",
"to",
"calculate",
"and",
"cache",
"the",
"marginal",
"likelihood"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L608-L630 | train | 36,178 |
fermiPy/fermipy | fermipy/stats_utils.py | LnLFn_norm_prior._posterior | def _posterior(self, x):
"""Internal function to calculate and cache the posterior
"""
yedge = self._nuis_pdf.marginalization_bins()
yc = 0.5 * (yedge[1:] + yedge[:-1])
yw = yedge[1:] - yedge[:-1]
like_array = self.like(x[:, np.newaxis], yc[np.newaxis, :]) * yw
like_array /= like_array.sum()
self._post = like_array.sum(1)
self._post_interp = castro.Interpolator(x, self._post)
return self._post | python | def _posterior(self, x):
"""Internal function to calculate and cache the posterior
"""
yedge = self._nuis_pdf.marginalization_bins()
yc = 0.5 * (yedge[1:] + yedge[:-1])
yw = yedge[1:] - yedge[:-1]
like_array = self.like(x[:, np.newaxis], yc[np.newaxis, :]) * yw
like_array /= like_array.sum()
self._post = like_array.sum(1)
self._post_interp = castro.Interpolator(x, self._post)
return self._post | [
"def",
"_posterior",
"(",
"self",
",",
"x",
")",
":",
"yedge",
"=",
"self",
".",
"_nuis_pdf",
".",
"marginalization_bins",
"(",
")",
"yc",
"=",
"0.5",
"*",
"(",
"yedge",
"[",
"1",
":",
"]",
"+",
"yedge",
"[",
":",
"-",
"1",
"]",
")",
"yw",
"=",... | Internal function to calculate and cache the posterior | [
"Internal",
"function",
"to",
"calculate",
"and",
"cache",
"the",
"posterior"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L632-L644 | train | 36,179 |
fermiPy/fermipy | fermipy/stats_utils.py | LnLFn_norm_prior._compute_mle | def _compute_mle(self):
"""Maximum likelihood estimator.
"""
xmax = self._lnlfn.interp.xmax
x0 = max(self._lnlfn.mle(), xmax * 1e-5)
ret = opt.fmin(lambda x: np.where(
xmax > x > 0, -self(x), np.inf), x0, disp=False)
mle = float(ret[0])
return mle | python | def _compute_mle(self):
"""Maximum likelihood estimator.
"""
xmax = self._lnlfn.interp.xmax
x0 = max(self._lnlfn.mle(), xmax * 1e-5)
ret = opt.fmin(lambda x: np.where(
xmax > x > 0, -self(x), np.inf), x0, disp=False)
mle = float(ret[0])
return mle | [
"def",
"_compute_mle",
"(",
"self",
")",
":",
"xmax",
"=",
"self",
".",
"_lnlfn",
".",
"interp",
".",
"xmax",
"x0",
"=",
"max",
"(",
"self",
".",
"_lnlfn",
".",
"mle",
"(",
")",
",",
"xmax",
"*",
"1e-5",
")",
"ret",
"=",
"opt",
".",
"fmin",
"("... | Maximum likelihood estimator. | [
"Maximum",
"likelihood",
"estimator",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/stats_utils.py#L656-L664 | train | 36,180 |
fermiPy/fermipy | fermipy/diffuse/binning.py | Component.build_from_energy_dict | def build_from_energy_dict(cls, ebin_name, input_dict):
""" Build a list of components from a dictionary for a single energy range
"""
psf_types = input_dict.pop('psf_types')
output_list = []
for psf_type, val_dict in sorted(psf_types.items()):
fulldict = input_dict.copy()
fulldict.update(val_dict)
fulldict['evtype_name'] = psf_type
fulldict['ebin_name'] = ebin_name
component = cls(**fulldict)
output_list += [component]
return output_list | python | def build_from_energy_dict(cls, ebin_name, input_dict):
""" Build a list of components from a dictionary for a single energy range
"""
psf_types = input_dict.pop('psf_types')
output_list = []
for psf_type, val_dict in sorted(psf_types.items()):
fulldict = input_dict.copy()
fulldict.update(val_dict)
fulldict['evtype_name'] = psf_type
fulldict['ebin_name'] = ebin_name
component = cls(**fulldict)
output_list += [component]
return output_list | [
"def",
"build_from_energy_dict",
"(",
"cls",
",",
"ebin_name",
",",
"input_dict",
")",
":",
"psf_types",
"=",
"input_dict",
".",
"pop",
"(",
"'psf_types'",
")",
"output_list",
"=",
"[",
"]",
"for",
"psf_type",
",",
"val_dict",
"in",
"sorted",
"(",
"psf_types... | Build a list of components from a dictionary for a single energy range | [
"Build",
"a",
"list",
"of",
"components",
"from",
"a",
"dictionary",
"for",
"a",
"single",
"energy",
"range"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/binning.py#L88-L100 | train | 36,181 |
fermiPy/fermipy | fermipy/diffuse/binning.py | Component.build_from_yamlstr | def build_from_yamlstr(cls, yamlstr):
""" Build a list of components from a yaml string
"""
top_dict = yaml.safe_load(yamlstr)
coordsys = top_dict.pop('coordsys')
output_list = []
for e_key, e_dict in sorted(top_dict.items()):
if e_key == 'coordsys':
continue
e_dict = top_dict[e_key]
e_dict['coordsys'] = coordsys
output_list += cls.build_from_energy_dict(e_key, e_dict)
return output_list | python | def build_from_yamlstr(cls, yamlstr):
""" Build a list of components from a yaml string
"""
top_dict = yaml.safe_load(yamlstr)
coordsys = top_dict.pop('coordsys')
output_list = []
for e_key, e_dict in sorted(top_dict.items()):
if e_key == 'coordsys':
continue
e_dict = top_dict[e_key]
e_dict['coordsys'] = coordsys
output_list += cls.build_from_energy_dict(e_key, e_dict)
return output_list | [
"def",
"build_from_yamlstr",
"(",
"cls",
",",
"yamlstr",
")",
":",
"top_dict",
"=",
"yaml",
".",
"safe_load",
"(",
"yamlstr",
")",
"coordsys",
"=",
"top_dict",
".",
"pop",
"(",
"'coordsys'",
")",
"output_list",
"=",
"[",
"]",
"for",
"e_key",
",",
"e_dict... | Build a list of components from a yaml string | [
"Build",
"a",
"list",
"of",
"components",
"from",
"a",
"yaml",
"string"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/binning.py#L103-L115 | train | 36,182 |
fermiPy/fermipy | fermipy/diffuse/residual_cr.py | ResidualCR._match_cubes | def _match_cubes(ccube_clean, ccube_dirty,
bexpcube_clean, bexpcube_dirty,
hpx_order):
""" Match the HEALPIX scheme and order of all the input cubes
return a dictionary of cubes with the same HEALPIX scheme and order
"""
if hpx_order == ccube_clean.hpx.order:
ccube_clean_at_order = ccube_clean
else:
ccube_clean_at_order = ccube_clean.ud_grade(hpx_order, preserve_counts=True)
if hpx_order == ccube_dirty.hpx.order:
ccube_dirty_at_order = ccube_dirty
else:
ccube_dirty_at_order = ccube_dirty.ud_grade(hpx_order, preserve_counts=True)
if hpx_order == bexpcube_clean.hpx.order:
bexpcube_clean_at_order = bexpcube_clean
else:
bexpcube_clean_at_order = bexpcube_clean.ud_grade(hpx_order, preserve_counts=True)
if hpx_order == bexpcube_dirty.hpx.order:
bexpcube_dirty_at_order = bexpcube_dirty
else:
bexpcube_dirty_at_order = bexpcube_dirty.ud_grade(hpx_order, preserve_counts=True)
if ccube_dirty_at_order.hpx.nest != ccube_clean.hpx.nest:
ccube_dirty_at_order = ccube_dirty_at_order.swap_scheme()
if bexpcube_clean_at_order.hpx.nest != ccube_clean.hpx.nest:
bexpcube_clean_at_order = bexpcube_clean_at_order.swap_scheme()
if bexpcube_dirty_at_order.hpx.nest != ccube_clean.hpx.nest:
bexpcube_dirty_at_order = bexpcube_dirty_at_order.swap_scheme()
ret_dict = dict(ccube_clean=ccube_clean_at_order,
ccube_dirty=ccube_dirty_at_order,
bexpcube_clean=bexpcube_clean_at_order,
bexpcube_dirty=bexpcube_dirty_at_order)
return ret_dict | python | def _match_cubes(ccube_clean, ccube_dirty,
bexpcube_clean, bexpcube_dirty,
hpx_order):
""" Match the HEALPIX scheme and order of all the input cubes
return a dictionary of cubes with the same HEALPIX scheme and order
"""
if hpx_order == ccube_clean.hpx.order:
ccube_clean_at_order = ccube_clean
else:
ccube_clean_at_order = ccube_clean.ud_grade(hpx_order, preserve_counts=True)
if hpx_order == ccube_dirty.hpx.order:
ccube_dirty_at_order = ccube_dirty
else:
ccube_dirty_at_order = ccube_dirty.ud_grade(hpx_order, preserve_counts=True)
if hpx_order == bexpcube_clean.hpx.order:
bexpcube_clean_at_order = bexpcube_clean
else:
bexpcube_clean_at_order = bexpcube_clean.ud_grade(hpx_order, preserve_counts=True)
if hpx_order == bexpcube_dirty.hpx.order:
bexpcube_dirty_at_order = bexpcube_dirty
else:
bexpcube_dirty_at_order = bexpcube_dirty.ud_grade(hpx_order, preserve_counts=True)
if ccube_dirty_at_order.hpx.nest != ccube_clean.hpx.nest:
ccube_dirty_at_order = ccube_dirty_at_order.swap_scheme()
if bexpcube_clean_at_order.hpx.nest != ccube_clean.hpx.nest:
bexpcube_clean_at_order = bexpcube_clean_at_order.swap_scheme()
if bexpcube_dirty_at_order.hpx.nest != ccube_clean.hpx.nest:
bexpcube_dirty_at_order = bexpcube_dirty_at_order.swap_scheme()
ret_dict = dict(ccube_clean=ccube_clean_at_order,
ccube_dirty=ccube_dirty_at_order,
bexpcube_clean=bexpcube_clean_at_order,
bexpcube_dirty=bexpcube_dirty_at_order)
return ret_dict | [
"def",
"_match_cubes",
"(",
"ccube_clean",
",",
"ccube_dirty",
",",
"bexpcube_clean",
",",
"bexpcube_dirty",
",",
"hpx_order",
")",
":",
"if",
"hpx_order",
"==",
"ccube_clean",
".",
"hpx",
".",
"order",
":",
"ccube_clean_at_order",
"=",
"ccube_clean",
"else",
":... | Match the HEALPIX scheme and order of all the input cubes
return a dictionary of cubes with the same HEALPIX scheme and order | [
"Match",
"the",
"HEALPIX",
"scheme",
"and",
"order",
"of",
"all",
"the",
"input",
"cubes"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L62-L102 | train | 36,183 |
fermiPy/fermipy | fermipy/diffuse/residual_cr.py | ResidualCR._compute_intensity | def _compute_intensity(ccube, bexpcube):
""" Compute the intensity map
"""
bexp_data = np.sqrt(bexpcube.data[0:-1, 0:] * bexpcube.data[1:, 0:])
intensity_data = ccube.data / bexp_data
intensity_map = HpxMap(intensity_data, ccube.hpx)
return intensity_map | python | def _compute_intensity(ccube, bexpcube):
""" Compute the intensity map
"""
bexp_data = np.sqrt(bexpcube.data[0:-1, 0:] * bexpcube.data[1:, 0:])
intensity_data = ccube.data / bexp_data
intensity_map = HpxMap(intensity_data, ccube.hpx)
return intensity_map | [
"def",
"_compute_intensity",
"(",
"ccube",
",",
"bexpcube",
")",
":",
"bexp_data",
"=",
"np",
".",
"sqrt",
"(",
"bexpcube",
".",
"data",
"[",
"0",
":",
"-",
"1",
",",
"0",
":",
"]",
"*",
"bexpcube",
".",
"data",
"[",
"1",
":",
",",
"0",
":",
"]... | Compute the intensity map | [
"Compute",
"the",
"intensity",
"map"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L105-L111 | train | 36,184 |
fermiPy/fermipy | fermipy/diffuse/residual_cr.py | ResidualCR._compute_mean | def _compute_mean(map1, map2):
""" Make a map that is the mean of two maps
"""
data = (map1.data + map2.data) / 2.
return HpxMap(data, map1.hpx) | python | def _compute_mean(map1, map2):
""" Make a map that is the mean of two maps
"""
data = (map1.data + map2.data) / 2.
return HpxMap(data, map1.hpx) | [
"def",
"_compute_mean",
"(",
"map1",
",",
"map2",
")",
":",
"data",
"=",
"(",
"map1",
".",
"data",
"+",
"map2",
".",
"data",
")",
"/",
"2.",
"return",
"HpxMap",
"(",
"data",
",",
"map1",
".",
"hpx",
")"
] | Make a map that is the mean of two maps | [
"Make",
"a",
"map",
"that",
"is",
"the",
"mean",
"of",
"two",
"maps"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L114-L118 | train | 36,185 |
fermiPy/fermipy | fermipy/diffuse/residual_cr.py | ResidualCR._compute_ratio | def _compute_ratio(top, bot):
""" Make a map that is the ratio of two maps
"""
data = np.where(bot.data > 0, top.data / bot.data, 0.)
return HpxMap(data, top.hpx) | python | def _compute_ratio(top, bot):
""" Make a map that is the ratio of two maps
"""
data = np.where(bot.data > 0, top.data / bot.data, 0.)
return HpxMap(data, top.hpx) | [
"def",
"_compute_ratio",
"(",
"top",
",",
"bot",
")",
":",
"data",
"=",
"np",
".",
"where",
"(",
"bot",
".",
"data",
">",
"0",
",",
"top",
".",
"data",
"/",
"bot",
".",
"data",
",",
"0.",
")",
"return",
"HpxMap",
"(",
"data",
",",
"top",
".",
... | Make a map that is the ratio of two maps | [
"Make",
"a",
"map",
"that",
"is",
"the",
"ratio",
"of",
"two",
"maps"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L121-L125 | train | 36,186 |
fermiPy/fermipy | fermipy/diffuse/residual_cr.py | ResidualCR._compute_diff | def _compute_diff(map1, map2):
""" Make a map that is the difference of two maps
"""
data = map1.data - map2.data
return HpxMap(data, map1.hpx) | python | def _compute_diff(map1, map2):
""" Make a map that is the difference of two maps
"""
data = map1.data - map2.data
return HpxMap(data, map1.hpx) | [
"def",
"_compute_diff",
"(",
"map1",
",",
"map2",
")",
":",
"data",
"=",
"map1",
".",
"data",
"-",
"map2",
".",
"data",
"return",
"HpxMap",
"(",
"data",
",",
"map1",
".",
"hpx",
")"
] | Make a map that is the difference of two maps | [
"Make",
"a",
"map",
"that",
"is",
"the",
"difference",
"of",
"two",
"maps"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L128-L132 | train | 36,187 |
fermiPy/fermipy | fermipy/diffuse/residual_cr.py | ResidualCR._compute_product | def _compute_product(map1, map2):
""" Make a map that is the product of two maps
"""
data = map1.data * map2.data
return HpxMap(data, map1.hpx) | python | def _compute_product(map1, map2):
""" Make a map that is the product of two maps
"""
data = map1.data * map2.data
return HpxMap(data, map1.hpx) | [
"def",
"_compute_product",
"(",
"map1",
",",
"map2",
")",
":",
"data",
"=",
"map1",
".",
"data",
"*",
"map2",
".",
"data",
"return",
"HpxMap",
"(",
"data",
",",
"map1",
".",
"hpx",
")"
] | Make a map that is the product of two maps | [
"Make",
"a",
"map",
"that",
"is",
"the",
"product",
"of",
"two",
"maps"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L135-L139 | train | 36,188 |
fermiPy/fermipy | fermipy/diffuse/residual_cr.py | ResidualCR._compute_counts_from_intensity | def _compute_counts_from_intensity(intensity, bexpcube):
""" Make the counts map from the intensity
"""
data = intensity.data * np.sqrt(bexpcube.data[1:] * bexpcube.data[0:-1])
return HpxMap(data, intensity.hpx) | python | def _compute_counts_from_intensity(intensity, bexpcube):
""" Make the counts map from the intensity
"""
data = intensity.data * np.sqrt(bexpcube.data[1:] * bexpcube.data[0:-1])
return HpxMap(data, intensity.hpx) | [
"def",
"_compute_counts_from_intensity",
"(",
"intensity",
",",
"bexpcube",
")",
":",
"data",
"=",
"intensity",
".",
"data",
"*",
"np",
".",
"sqrt",
"(",
"bexpcube",
".",
"data",
"[",
"1",
":",
"]",
"*",
"bexpcube",
".",
"data",
"[",
"0",
":",
"-",
"... | Make the counts map from the intensity | [
"Make",
"the",
"counts",
"map",
"from",
"the",
"intensity"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L142-L146 | train | 36,189 |
fermiPy/fermipy | fermipy/diffuse/residual_cr.py | ResidualCR._compute_counts_from_model | def _compute_counts_from_model(model, bexpcube):
""" Make the counts maps from teh mdoe
"""
data = model.data * bexpcube.data
ebins = model.hpx.ebins
ratio = ebins[1:] / ebins[0:-1]
half_log_ratio = np.log(ratio) / 2.
int_map = ((data[0:-1].T * ebins[0:-1]) + (data[1:].T * ebins[1:])) * half_log_ratio
return HpxMap(int_map.T, model.hpx) | python | def _compute_counts_from_model(model, bexpcube):
""" Make the counts maps from teh mdoe
"""
data = model.data * bexpcube.data
ebins = model.hpx.ebins
ratio = ebins[1:] / ebins[0:-1]
half_log_ratio = np.log(ratio) / 2.
int_map = ((data[0:-1].T * ebins[0:-1]) + (data[1:].T * ebins[1:])) * half_log_ratio
return HpxMap(int_map.T, model.hpx) | [
"def",
"_compute_counts_from_model",
"(",
"model",
",",
"bexpcube",
")",
":",
"data",
"=",
"model",
".",
"data",
"*",
"bexpcube",
".",
"data",
"ebins",
"=",
"model",
".",
"hpx",
".",
"ebins",
"ratio",
"=",
"ebins",
"[",
"1",
":",
"]",
"/",
"ebins",
"... | Make the counts maps from teh mdoe | [
"Make",
"the",
"counts",
"maps",
"from",
"teh",
"mdoe"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L149-L157 | train | 36,190 |
fermiPy/fermipy | fermipy/diffuse/residual_cr.py | ResidualCR._make_bright_pixel_mask | def _make_bright_pixel_mask(intensity_mean, mask_factor=5.0):
""" Make of mask of all the brightest pixels """
mask = np.zeros((intensity_mean.data.shape), bool)
nebins = len(intensity_mean.data)
sum_intensity = intensity_mean.data.sum(0)
mean_intensity = sum_intensity.mean()
for i in range(nebins):
mask[i, 0:] = sum_intensity > (mask_factor * mean_intensity)
return HpxMap(mask, intensity_mean.hpx) | python | def _make_bright_pixel_mask(intensity_mean, mask_factor=5.0):
""" Make of mask of all the brightest pixels """
mask = np.zeros((intensity_mean.data.shape), bool)
nebins = len(intensity_mean.data)
sum_intensity = intensity_mean.data.sum(0)
mean_intensity = sum_intensity.mean()
for i in range(nebins):
mask[i, 0:] = sum_intensity > (mask_factor * mean_intensity)
return HpxMap(mask, intensity_mean.hpx) | [
"def",
"_make_bright_pixel_mask",
"(",
"intensity_mean",
",",
"mask_factor",
"=",
"5.0",
")",
":",
"mask",
"=",
"np",
".",
"zeros",
"(",
"(",
"intensity_mean",
".",
"data",
".",
"shape",
")",
",",
"bool",
")",
"nebins",
"=",
"len",
"(",
"intensity_mean",
... | Make of mask of all the brightest pixels | [
"Make",
"of",
"mask",
"of",
"all",
"the",
"brightest",
"pixels"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L160-L168 | train | 36,191 |
fermiPy/fermipy | fermipy/diffuse/residual_cr.py | ResidualCR._get_aeff_corrections | def _get_aeff_corrections(intensity_ratio, mask):
""" Compute a correction for the effective area from the brighter pixesl
"""
nebins = len(intensity_ratio.data)
aeff_corrections = np.zeros((nebins))
for i in range(nebins):
bright_pixels_intensity = intensity_ratio.data[i][mask.data[i]]
mean_bright_pixel = bright_pixels_intensity.mean()
aeff_corrections[i] = 1. / mean_bright_pixel
print("Aeff correction: ", aeff_corrections)
return aeff_corrections | python | def _get_aeff_corrections(intensity_ratio, mask):
""" Compute a correction for the effective area from the brighter pixesl
"""
nebins = len(intensity_ratio.data)
aeff_corrections = np.zeros((nebins))
for i in range(nebins):
bright_pixels_intensity = intensity_ratio.data[i][mask.data[i]]
mean_bright_pixel = bright_pixels_intensity.mean()
aeff_corrections[i] = 1. / mean_bright_pixel
print("Aeff correction: ", aeff_corrections)
return aeff_corrections | [
"def",
"_get_aeff_corrections",
"(",
"intensity_ratio",
",",
"mask",
")",
":",
"nebins",
"=",
"len",
"(",
"intensity_ratio",
".",
"data",
")",
"aeff_corrections",
"=",
"np",
".",
"zeros",
"(",
"(",
"nebins",
")",
")",
"for",
"i",
"in",
"range",
"(",
"neb... | Compute a correction for the effective area from the brighter pixesl | [
"Compute",
"a",
"correction",
"for",
"the",
"effective",
"area",
"from",
"the",
"brighter",
"pixesl"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L171-L182 | train | 36,192 |
fermiPy/fermipy | fermipy/diffuse/residual_cr.py | ResidualCR._apply_aeff_corrections | def _apply_aeff_corrections(intensity_map, aeff_corrections):
""" Multipy a map by the effective area correction
"""
data = aeff_corrections * intensity_map.data.T
return HpxMap(data.T, intensity_map.hpx) | python | def _apply_aeff_corrections(intensity_map, aeff_corrections):
""" Multipy a map by the effective area correction
"""
data = aeff_corrections * intensity_map.data.T
return HpxMap(data.T, intensity_map.hpx) | [
"def",
"_apply_aeff_corrections",
"(",
"intensity_map",
",",
"aeff_corrections",
")",
":",
"data",
"=",
"aeff_corrections",
"*",
"intensity_map",
".",
"data",
".",
"T",
"return",
"HpxMap",
"(",
"data",
".",
"T",
",",
"intensity_map",
".",
"hpx",
")"
] | Multipy a map by the effective area correction | [
"Multipy",
"a",
"map",
"by",
"the",
"effective",
"area",
"correction"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L185-L189 | train | 36,193 |
fermiPy/fermipy | fermipy/diffuse/residual_cr.py | ResidualCR._fill_masked_intensity_resid | def _fill_masked_intensity_resid(intensity_resid, bright_pixel_mask):
""" Fill the pixels used to compute the effective area correction with the mean intensity
"""
filled_intensity = np.zeros((intensity_resid.data.shape))
nebins = len(intensity_resid.data)
for i in range(nebins):
masked = bright_pixel_mask.data[i]
unmasked = np.invert(masked)
mean_intensity = intensity_resid.data[i][unmasked].mean()
filled_intensity[i] = np.where(masked, mean_intensity, intensity_resid.data[i])
return HpxMap(filled_intensity, intensity_resid.hpx) | python | def _fill_masked_intensity_resid(intensity_resid, bright_pixel_mask):
""" Fill the pixels used to compute the effective area correction with the mean intensity
"""
filled_intensity = np.zeros((intensity_resid.data.shape))
nebins = len(intensity_resid.data)
for i in range(nebins):
masked = bright_pixel_mask.data[i]
unmasked = np.invert(masked)
mean_intensity = intensity_resid.data[i][unmasked].mean()
filled_intensity[i] = np.where(masked, mean_intensity, intensity_resid.data[i])
return HpxMap(filled_intensity, intensity_resid.hpx) | [
"def",
"_fill_masked_intensity_resid",
"(",
"intensity_resid",
",",
"bright_pixel_mask",
")",
":",
"filled_intensity",
"=",
"np",
".",
"zeros",
"(",
"(",
"intensity_resid",
".",
"data",
".",
"shape",
")",
")",
"nebins",
"=",
"len",
"(",
"intensity_resid",
".",
... | Fill the pixels used to compute the effective area correction with the mean intensity | [
"Fill",
"the",
"pixels",
"used",
"to",
"compute",
"the",
"effective",
"area",
"correction",
"with",
"the",
"mean",
"intensity"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L192-L202 | train | 36,194 |
fermiPy/fermipy | fermipy/diffuse/residual_cr.py | ResidualCR._smooth_hpx_map | def _smooth_hpx_map(hpx_map, sigma):
""" Smooth a healpix map using a Gaussian
"""
if hpx_map.hpx.ordering == "NESTED":
ring_map = hpx_map.swap_scheme()
else:
ring_map = hpx_map
ring_data = ring_map.data.copy()
nebins = len(hpx_map.data)
smoothed_data = np.zeros((hpx_map.data.shape))
for i in range(nebins):
smoothed_data[i] = healpy.sphtfunc.smoothing(
ring_data[i], sigma=np.radians(sigma), verbose=False)
smoothed_data.clip(0., 1e99)
smoothed_ring_map = HpxMap(smoothed_data, ring_map.hpx)
if hpx_map.hpx.ordering == "NESTED":
return smoothed_ring_map.swap_scheme()
return smoothed_ring_map | python | def _smooth_hpx_map(hpx_map, sigma):
""" Smooth a healpix map using a Gaussian
"""
if hpx_map.hpx.ordering == "NESTED":
ring_map = hpx_map.swap_scheme()
else:
ring_map = hpx_map
ring_data = ring_map.data.copy()
nebins = len(hpx_map.data)
smoothed_data = np.zeros((hpx_map.data.shape))
for i in range(nebins):
smoothed_data[i] = healpy.sphtfunc.smoothing(
ring_data[i], sigma=np.radians(sigma), verbose=False)
smoothed_data.clip(0., 1e99)
smoothed_ring_map = HpxMap(smoothed_data, ring_map.hpx)
if hpx_map.hpx.ordering == "NESTED":
return smoothed_ring_map.swap_scheme()
return smoothed_ring_map | [
"def",
"_smooth_hpx_map",
"(",
"hpx_map",
",",
"sigma",
")",
":",
"if",
"hpx_map",
".",
"hpx",
".",
"ordering",
"==",
"\"NESTED\"",
":",
"ring_map",
"=",
"hpx_map",
".",
"swap_scheme",
"(",
")",
"else",
":",
"ring_map",
"=",
"hpx_map",
"ring_data",
"=",
... | Smooth a healpix map using a Gaussian | [
"Smooth",
"a",
"healpix",
"map",
"using",
"a",
"Gaussian"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L205-L223 | train | 36,195 |
fermiPy/fermipy | fermipy/diffuse/residual_cr.py | ResidualCR._intergral_to_differential | def _intergral_to_differential(hpx_map, gamma=-2.0):
""" Convert integral quantity to differential quantity
Here we are assuming the spectrum is a powerlaw with index gamma and we
are using log-log-quadrature to compute the integral quantities.
"""
nebins = len(hpx_map.data)
diff_map = np.zeros((nebins + 1, hpx_map.hpx.npix))
ebins = hpx_map.hpx.ebins
ratio = ebins[1:] / ebins[0:-1]
half_log_ratio = np.log(ratio) / 2.
ratio_gamma = np.power(ratio, gamma)
#ratio_inv_gamma = np.power(ratio, -1. * gamma)
diff_map[0] = hpx_map.data[0] / ((ebins[0] + ratio_gamma[0] * ebins[1]) * half_log_ratio[0])
for i in range(nebins):
diff_map[i + 1] = (hpx_map.data[i] / (ebins[i + 1] *
half_log_ratio[i])) - (diff_map[i] / ratio[i])
return HpxMap(diff_map, hpx_map.hpx) | python | def _intergral_to_differential(hpx_map, gamma=-2.0):
""" Convert integral quantity to differential quantity
Here we are assuming the spectrum is a powerlaw with index gamma and we
are using log-log-quadrature to compute the integral quantities.
"""
nebins = len(hpx_map.data)
diff_map = np.zeros((nebins + 1, hpx_map.hpx.npix))
ebins = hpx_map.hpx.ebins
ratio = ebins[1:] / ebins[0:-1]
half_log_ratio = np.log(ratio) / 2.
ratio_gamma = np.power(ratio, gamma)
#ratio_inv_gamma = np.power(ratio, -1. * gamma)
diff_map[0] = hpx_map.data[0] / ((ebins[0] + ratio_gamma[0] * ebins[1]) * half_log_ratio[0])
for i in range(nebins):
diff_map[i + 1] = (hpx_map.data[i] / (ebins[i + 1] *
half_log_ratio[i])) - (diff_map[i] / ratio[i])
return HpxMap(diff_map, hpx_map.hpx) | [
"def",
"_intergral_to_differential",
"(",
"hpx_map",
",",
"gamma",
"=",
"-",
"2.0",
")",
":",
"nebins",
"=",
"len",
"(",
"hpx_map",
".",
"data",
")",
"diff_map",
"=",
"np",
".",
"zeros",
"(",
"(",
"nebins",
"+",
"1",
",",
"hpx_map",
".",
"hpx",
".",
... | Convert integral quantity to differential quantity
Here we are assuming the spectrum is a powerlaw with index gamma and we
are using log-log-quadrature to compute the integral quantities. | [
"Convert",
"integral",
"quantity",
"to",
"differential",
"quantity"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L226-L244 | train | 36,196 |
fermiPy/fermipy | fermipy/diffuse/residual_cr.py | ResidualCR._differential_to_integral | def _differential_to_integral(hpx_map):
""" Convert a differential map to an integral map
Here we are using log-log-quadrature to compute the integral quantities.
"""
ebins = hpx_map.hpx.ebins
ratio = ebins[1:] / ebins[0:-1]
half_log_ratio = np.log(ratio) / 2.
int_map = ((hpx_map.data[0:-1].T * ebins[0:-1]) +
(hpx_map.data[1:].T * ebins[1:])) * half_log_ratio
return HpxMap(int_map.T, hpx_map.hpx) | python | def _differential_to_integral(hpx_map):
""" Convert a differential map to an integral map
Here we are using log-log-quadrature to compute the integral quantities.
"""
ebins = hpx_map.hpx.ebins
ratio = ebins[1:] / ebins[0:-1]
half_log_ratio = np.log(ratio) / 2.
int_map = ((hpx_map.data[0:-1].T * ebins[0:-1]) +
(hpx_map.data[1:].T * ebins[1:])) * half_log_ratio
return HpxMap(int_map.T, hpx_map.hpx) | [
"def",
"_differential_to_integral",
"(",
"hpx_map",
")",
":",
"ebins",
"=",
"hpx_map",
".",
"hpx",
".",
"ebins",
"ratio",
"=",
"ebins",
"[",
"1",
":",
"]",
"/",
"ebins",
"[",
"0",
":",
"-",
"1",
"]",
"half_log_ratio",
"=",
"np",
".",
"log",
"(",
"r... | Convert a differential map to an integral map
Here we are using log-log-quadrature to compute the integral quantities. | [
"Convert",
"a",
"differential",
"map",
"to",
"an",
"integral",
"map"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L247-L257 | train | 36,197 |
fermiPy/fermipy | fermipy/skymap.py | coadd_maps | def coadd_maps(geom, maps, preserve_counts=True):
"""Coadd a sequence of `~gammapy.maps.Map` objects."""
# FIXME: This functionality should be built into the Map.coadd method
map_out = gammapy.maps.Map.from_geom(geom)
for m in maps:
m_tmp = m
if isinstance(m, gammapy.maps.HpxNDMap):
if m.geom.order < map_out.geom.order:
factor = map_out.geom.nside // m.geom.nside
m_tmp = m.upsample(factor, preserve_counts=preserve_counts)
map_out.coadd(m_tmp)
return map_out | python | def coadd_maps(geom, maps, preserve_counts=True):
"""Coadd a sequence of `~gammapy.maps.Map` objects."""
# FIXME: This functionality should be built into the Map.coadd method
map_out = gammapy.maps.Map.from_geom(geom)
for m in maps:
m_tmp = m
if isinstance(m, gammapy.maps.HpxNDMap):
if m.geom.order < map_out.geom.order:
factor = map_out.geom.nside // m.geom.nside
m_tmp = m.upsample(factor, preserve_counts=preserve_counts)
map_out.coadd(m_tmp)
return map_out | [
"def",
"coadd_maps",
"(",
"geom",
",",
"maps",
",",
"preserve_counts",
"=",
"True",
")",
":",
"# FIXME: This functionality should be built into the Map.coadd method",
"map_out",
"=",
"gammapy",
".",
"maps",
".",
"Map",
".",
"from_geom",
"(",
"geom",
")",
"for",
"m... | Coadd a sequence of `~gammapy.maps.Map` objects. | [
"Coadd",
"a",
"sequence",
"of",
"~gammapy",
".",
"maps",
".",
"Map",
"objects",
"."
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/skymap.py#L21-L34 | train | 36,198 |
fermiPy/fermipy | fermipy/skymap.py | Map.sum_over_energy | def sum_over_energy(self):
""" Reduce a 3D counts cube to a 2D counts map
"""
# Note that the array is using the opposite convention from WCS
# so we sum over axis 0 in the array, but drop axis 2 in the WCS object
return Map(np.sum(self.counts, axis=0), self.wcs.dropaxis(2)) | python | def sum_over_energy(self):
""" Reduce a 3D counts cube to a 2D counts map
"""
# Note that the array is using the opposite convention from WCS
# so we sum over axis 0 in the array, but drop axis 2 in the WCS object
return Map(np.sum(self.counts, axis=0), self.wcs.dropaxis(2)) | [
"def",
"sum_over_energy",
"(",
"self",
")",
":",
"# Note that the array is using the opposite convention from WCS",
"# so we sum over axis 0 in the array, but drop axis 2 in the WCS object",
"return",
"Map",
"(",
"np",
".",
"sum",
"(",
"self",
".",
"counts",
",",
"axis",
"=",... | Reduce a 3D counts cube to a 2D counts map | [
"Reduce",
"a",
"3D",
"counts",
"cube",
"to",
"a",
"2D",
"counts",
"map"
] | 9df5e7e3728307fd58c5bba36fd86783c39fbad4 | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/skymap.py#L252-L257 | train | 36,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.