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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
gem/oq-engine | openquake/calculators/base.py | get_idxs | def get_idxs(data, eid2idx):
"""
Convert from event IDs to event indices.
:param data: an array with a field eid
:param eid2idx: a dictionary eid -> idx
:returns: the array of event indices
"""
uniq, inv = numpy.unique(data['eid'], return_inverse=True)
idxs = numpy.array([eid2idx[eid] for eid in uniq])[inv]
return idxs | python | def get_idxs(data, eid2idx):
"""
Convert from event IDs to event indices.
:param data: an array with a field eid
:param eid2idx: a dictionary eid -> idx
:returns: the array of event indices
"""
uniq, inv = numpy.unique(data['eid'], return_inverse=True)
idxs = numpy.array([eid2idx[eid] for eid in uniq])[inv]
return idxs | [
"def",
"get_idxs",
"(",
"data",
",",
"eid2idx",
")",
":",
"uniq",
",",
"inv",
"=",
"numpy",
".",
"unique",
"(",
"data",
"[",
"'eid'",
"]",
",",
"return_inverse",
"=",
"True",
")",
"idxs",
"=",
"numpy",
".",
"array",
"(",
"[",
"eid2idx",
"[",
"eid",
"]",
"for",
"eid",
"in",
"uniq",
"]",
")",
"[",
"inv",
"]",
"return",
"idxs"
] | Convert from event IDs to event indices.
:param data: an array with a field eid
:param eid2idx: a dictionary eid -> idx
:returns: the array of event indices | [
"Convert",
"from",
"event",
"IDs",
"to",
"event",
"indices",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L959-L969 | train | 232,900 |
gem/oq-engine | openquake/calculators/base.py | import_gmfs | def import_gmfs(dstore, fname, sids):
"""
Import in the datastore a ground motion field CSV file.
:param dstore: the datastore
:param fname: the CSV file
:param sids: the site IDs (complete)
:returns: event_ids, num_rlzs
"""
array = writers.read_composite_array(fname).array
# has header rlzi, sid, eid, gmv_PGA, ...
imts = [name[4:] for name in array.dtype.names[3:]]
n_imts = len(imts)
gmf_data_dt = numpy.dtype(
[('rlzi', U16), ('sid', U32), ('eid', U64), ('gmv', (F32, (n_imts,)))])
# store the events
eids = numpy.unique(array['eid'])
eids.sort()
E = len(eids)
eid2idx = dict(zip(eids, range(E)))
events = numpy.zeros(E, rupture.events_dt)
events['eid'] = eids
dstore['events'] = events
# store the GMFs
dic = general.group_array(array.view(gmf_data_dt), 'sid')
lst = []
offset = 0
for sid in sids:
n = len(dic.get(sid, []))
lst.append((offset, offset + n))
if n:
offset += n
gmvs = dic[sid]
gmvs['eid'] = get_idxs(gmvs, eid2idx)
gmvs['rlzi'] = 0 # effectively there is only 1 realization
dstore.extend('gmf_data/data', gmvs)
dstore['gmf_data/indices'] = numpy.array(lst, U32)
dstore['gmf_data/imts'] = ' '.join(imts)
sig_eps_dt = [('eid', U64), ('sig', (F32, n_imts)), ('eps', (F32, n_imts))]
dstore['gmf_data/sigma_epsilon'] = numpy.zeros(0, sig_eps_dt)
dstore['weights'] = numpy.ones((1, n_imts))
return eids | python | def import_gmfs(dstore, fname, sids):
"""
Import in the datastore a ground motion field CSV file.
:param dstore: the datastore
:param fname: the CSV file
:param sids: the site IDs (complete)
:returns: event_ids, num_rlzs
"""
array = writers.read_composite_array(fname).array
# has header rlzi, sid, eid, gmv_PGA, ...
imts = [name[4:] for name in array.dtype.names[3:]]
n_imts = len(imts)
gmf_data_dt = numpy.dtype(
[('rlzi', U16), ('sid', U32), ('eid', U64), ('gmv', (F32, (n_imts,)))])
# store the events
eids = numpy.unique(array['eid'])
eids.sort()
E = len(eids)
eid2idx = dict(zip(eids, range(E)))
events = numpy.zeros(E, rupture.events_dt)
events['eid'] = eids
dstore['events'] = events
# store the GMFs
dic = general.group_array(array.view(gmf_data_dt), 'sid')
lst = []
offset = 0
for sid in sids:
n = len(dic.get(sid, []))
lst.append((offset, offset + n))
if n:
offset += n
gmvs = dic[sid]
gmvs['eid'] = get_idxs(gmvs, eid2idx)
gmvs['rlzi'] = 0 # effectively there is only 1 realization
dstore.extend('gmf_data/data', gmvs)
dstore['gmf_data/indices'] = numpy.array(lst, U32)
dstore['gmf_data/imts'] = ' '.join(imts)
sig_eps_dt = [('eid', U64), ('sig', (F32, n_imts)), ('eps', (F32, n_imts))]
dstore['gmf_data/sigma_epsilon'] = numpy.zeros(0, sig_eps_dt)
dstore['weights'] = numpy.ones((1, n_imts))
return eids | [
"def",
"import_gmfs",
"(",
"dstore",
",",
"fname",
",",
"sids",
")",
":",
"array",
"=",
"writers",
".",
"read_composite_array",
"(",
"fname",
")",
".",
"array",
"# has header rlzi, sid, eid, gmv_PGA, ...",
"imts",
"=",
"[",
"name",
"[",
"4",
":",
"]",
"for",
"name",
"in",
"array",
".",
"dtype",
".",
"names",
"[",
"3",
":",
"]",
"]",
"n_imts",
"=",
"len",
"(",
"imts",
")",
"gmf_data_dt",
"=",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"'rlzi'",
",",
"U16",
")",
",",
"(",
"'sid'",
",",
"U32",
")",
",",
"(",
"'eid'",
",",
"U64",
")",
",",
"(",
"'gmv'",
",",
"(",
"F32",
",",
"(",
"n_imts",
",",
")",
")",
")",
"]",
")",
"# store the events",
"eids",
"=",
"numpy",
".",
"unique",
"(",
"array",
"[",
"'eid'",
"]",
")",
"eids",
".",
"sort",
"(",
")",
"E",
"=",
"len",
"(",
"eids",
")",
"eid2idx",
"=",
"dict",
"(",
"zip",
"(",
"eids",
",",
"range",
"(",
"E",
")",
")",
")",
"events",
"=",
"numpy",
".",
"zeros",
"(",
"E",
",",
"rupture",
".",
"events_dt",
")",
"events",
"[",
"'eid'",
"]",
"=",
"eids",
"dstore",
"[",
"'events'",
"]",
"=",
"events",
"# store the GMFs",
"dic",
"=",
"general",
".",
"group_array",
"(",
"array",
".",
"view",
"(",
"gmf_data_dt",
")",
",",
"'sid'",
")",
"lst",
"=",
"[",
"]",
"offset",
"=",
"0",
"for",
"sid",
"in",
"sids",
":",
"n",
"=",
"len",
"(",
"dic",
".",
"get",
"(",
"sid",
",",
"[",
"]",
")",
")",
"lst",
".",
"append",
"(",
"(",
"offset",
",",
"offset",
"+",
"n",
")",
")",
"if",
"n",
":",
"offset",
"+=",
"n",
"gmvs",
"=",
"dic",
"[",
"sid",
"]",
"gmvs",
"[",
"'eid'",
"]",
"=",
"get_idxs",
"(",
"gmvs",
",",
"eid2idx",
")",
"gmvs",
"[",
"'rlzi'",
"]",
"=",
"0",
"# effectively there is only 1 realization",
"dstore",
".",
"extend",
"(",
"'gmf_data/data'",
",",
"gmvs",
")",
"dstore",
"[",
"'gmf_data/indices'",
"]",
"=",
"numpy",
".",
"array",
"(",
"lst",
",",
"U32",
")",
"dstore",
"[",
"'gmf_data/imts'",
"]",
"=",
"' '",
".",
"join",
"(",
"imts",
")",
"sig_eps_dt",
"=",
"[",
"(",
"'eid'",
",",
"U64",
")",
",",
"(",
"'sig'",
",",
"(",
"F32",
",",
"n_imts",
")",
")",
",",
"(",
"'eps'",
",",
"(",
"F32",
",",
"n_imts",
")",
")",
"]",
"dstore",
"[",
"'gmf_data/sigma_epsilon'",
"]",
"=",
"numpy",
".",
"zeros",
"(",
"0",
",",
"sig_eps_dt",
")",
"dstore",
"[",
"'weights'",
"]",
"=",
"numpy",
".",
"ones",
"(",
"(",
"1",
",",
"n_imts",
")",
")",
"return",
"eids"
] | Import in the datastore a ground motion field CSV file.
:param dstore: the datastore
:param fname: the CSV file
:param sids: the site IDs (complete)
:returns: event_ids, num_rlzs | [
"Import",
"in",
"the",
"datastore",
"a",
"ground",
"motion",
"field",
"CSV",
"file",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L972-L1013 | train | 232,901 |
gem/oq-engine | openquake/calculators/base.py | BaseCalculator.save_params | def save_params(self, **kw):
"""
Update the current calculation parameters and save engine_version
"""
if ('hazard_calculation_id' in kw and
kw['hazard_calculation_id'] is None):
del kw['hazard_calculation_id']
vars(self.oqparam).update(**kw)
self.datastore['oqparam'] = self.oqparam # save the updated oqparam
attrs = self.datastore['/'].attrs
attrs['engine_version'] = engine_version
attrs['date'] = datetime.now().isoformat()[:19]
if 'checksum32' not in attrs:
attrs['checksum32'] = readinput.get_checksum32(self.oqparam)
self.datastore.flush() | python | def save_params(self, **kw):
"""
Update the current calculation parameters and save engine_version
"""
if ('hazard_calculation_id' in kw and
kw['hazard_calculation_id'] is None):
del kw['hazard_calculation_id']
vars(self.oqparam).update(**kw)
self.datastore['oqparam'] = self.oqparam # save the updated oqparam
attrs = self.datastore['/'].attrs
attrs['engine_version'] = engine_version
attrs['date'] = datetime.now().isoformat()[:19]
if 'checksum32' not in attrs:
attrs['checksum32'] = readinput.get_checksum32(self.oqparam)
self.datastore.flush() | [
"def",
"save_params",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"if",
"(",
"'hazard_calculation_id'",
"in",
"kw",
"and",
"kw",
"[",
"'hazard_calculation_id'",
"]",
"is",
"None",
")",
":",
"del",
"kw",
"[",
"'hazard_calculation_id'",
"]",
"vars",
"(",
"self",
".",
"oqparam",
")",
".",
"update",
"(",
"*",
"*",
"kw",
")",
"self",
".",
"datastore",
"[",
"'oqparam'",
"]",
"=",
"self",
".",
"oqparam",
"# save the updated oqparam",
"attrs",
"=",
"self",
".",
"datastore",
"[",
"'/'",
"]",
".",
"attrs",
"attrs",
"[",
"'engine_version'",
"]",
"=",
"engine_version",
"attrs",
"[",
"'date'",
"]",
"=",
"datetime",
".",
"now",
"(",
")",
".",
"isoformat",
"(",
")",
"[",
":",
"19",
"]",
"if",
"'checksum32'",
"not",
"in",
"attrs",
":",
"attrs",
"[",
"'checksum32'",
"]",
"=",
"readinput",
".",
"get_checksum32",
"(",
"self",
".",
"oqparam",
")",
"self",
".",
"datastore",
".",
"flush",
"(",
")"
] | Update the current calculation parameters and save engine_version | [
"Update",
"the",
"current",
"calculation",
"parameters",
"and",
"save",
"engine_version"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L142-L156 | train | 232,902 |
gem/oq-engine | openquake/calculators/base.py | BaseCalculator.run | def run(self, pre_execute=True, concurrent_tasks=None, close=True, **kw):
"""
Run the calculation and return the exported outputs.
"""
with self._monitor:
self._monitor.username = kw.get('username', '')
self._monitor.hdf5 = self.datastore.hdf5
if concurrent_tasks is None: # use the job.ini parameter
ct = self.oqparam.concurrent_tasks
else: # used the parameter passed in the command-line
ct = concurrent_tasks
if ct == 0: # disable distribution temporarily
oq_distribute = os.environ.get('OQ_DISTRIBUTE')
os.environ['OQ_DISTRIBUTE'] = 'no'
if ct != self.oqparam.concurrent_tasks:
# save the used concurrent_tasks
self.oqparam.concurrent_tasks = ct
self.save_params(**kw)
try:
if pre_execute:
self.pre_execute()
self.result = self.execute()
if self.result is not None:
self.post_execute(self.result)
self.before_export()
self.export(kw.get('exports', ''))
except Exception:
if kw.get('pdb'): # post-mortem debug
tb = sys.exc_info()[2]
traceback.print_tb(tb)
pdb.post_mortem(tb)
else:
logging.critical('', exc_info=True)
raise
finally:
# cleanup globals
if ct == 0: # restore OQ_DISTRIBUTE
if oq_distribute is None: # was not set
del os.environ['OQ_DISTRIBUTE']
else:
os.environ['OQ_DISTRIBUTE'] = oq_distribute
readinput.pmap = None
readinput.exposure = None
readinput.gmfs = None
readinput.eids = None
self._monitor.flush()
if close: # in the engine we close later
self.result = None
try:
self.datastore.close()
except (RuntimeError, ValueError):
# sometimes produces errors but they are difficult to
# reproduce
logging.warning('', exc_info=True)
return getattr(self, 'exported', {}) | python | def run(self, pre_execute=True, concurrent_tasks=None, close=True, **kw):
"""
Run the calculation and return the exported outputs.
"""
with self._monitor:
self._monitor.username = kw.get('username', '')
self._monitor.hdf5 = self.datastore.hdf5
if concurrent_tasks is None: # use the job.ini parameter
ct = self.oqparam.concurrent_tasks
else: # used the parameter passed in the command-line
ct = concurrent_tasks
if ct == 0: # disable distribution temporarily
oq_distribute = os.environ.get('OQ_DISTRIBUTE')
os.environ['OQ_DISTRIBUTE'] = 'no'
if ct != self.oqparam.concurrent_tasks:
# save the used concurrent_tasks
self.oqparam.concurrent_tasks = ct
self.save_params(**kw)
try:
if pre_execute:
self.pre_execute()
self.result = self.execute()
if self.result is not None:
self.post_execute(self.result)
self.before_export()
self.export(kw.get('exports', ''))
except Exception:
if kw.get('pdb'): # post-mortem debug
tb = sys.exc_info()[2]
traceback.print_tb(tb)
pdb.post_mortem(tb)
else:
logging.critical('', exc_info=True)
raise
finally:
# cleanup globals
if ct == 0: # restore OQ_DISTRIBUTE
if oq_distribute is None: # was not set
del os.environ['OQ_DISTRIBUTE']
else:
os.environ['OQ_DISTRIBUTE'] = oq_distribute
readinput.pmap = None
readinput.exposure = None
readinput.gmfs = None
readinput.eids = None
self._monitor.flush()
if close: # in the engine we close later
self.result = None
try:
self.datastore.close()
except (RuntimeError, ValueError):
# sometimes produces errors but they are difficult to
# reproduce
logging.warning('', exc_info=True)
return getattr(self, 'exported', {}) | [
"def",
"run",
"(",
"self",
",",
"pre_execute",
"=",
"True",
",",
"concurrent_tasks",
"=",
"None",
",",
"close",
"=",
"True",
",",
"*",
"*",
"kw",
")",
":",
"with",
"self",
".",
"_monitor",
":",
"self",
".",
"_monitor",
".",
"username",
"=",
"kw",
".",
"get",
"(",
"'username'",
",",
"''",
")",
"self",
".",
"_monitor",
".",
"hdf5",
"=",
"self",
".",
"datastore",
".",
"hdf5",
"if",
"concurrent_tasks",
"is",
"None",
":",
"# use the job.ini parameter",
"ct",
"=",
"self",
".",
"oqparam",
".",
"concurrent_tasks",
"else",
":",
"# used the parameter passed in the command-line",
"ct",
"=",
"concurrent_tasks",
"if",
"ct",
"==",
"0",
":",
"# disable distribution temporarily",
"oq_distribute",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'OQ_DISTRIBUTE'",
")",
"os",
".",
"environ",
"[",
"'OQ_DISTRIBUTE'",
"]",
"=",
"'no'",
"if",
"ct",
"!=",
"self",
".",
"oqparam",
".",
"concurrent_tasks",
":",
"# save the used concurrent_tasks",
"self",
".",
"oqparam",
".",
"concurrent_tasks",
"=",
"ct",
"self",
".",
"save_params",
"(",
"*",
"*",
"kw",
")",
"try",
":",
"if",
"pre_execute",
":",
"self",
".",
"pre_execute",
"(",
")",
"self",
".",
"result",
"=",
"self",
".",
"execute",
"(",
")",
"if",
"self",
".",
"result",
"is",
"not",
"None",
":",
"self",
".",
"post_execute",
"(",
"self",
".",
"result",
")",
"self",
".",
"before_export",
"(",
")",
"self",
".",
"export",
"(",
"kw",
".",
"get",
"(",
"'exports'",
",",
"''",
")",
")",
"except",
"Exception",
":",
"if",
"kw",
".",
"get",
"(",
"'pdb'",
")",
":",
"# post-mortem debug",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
"traceback",
".",
"print_tb",
"(",
"tb",
")",
"pdb",
".",
"post_mortem",
"(",
"tb",
")",
"else",
":",
"logging",
".",
"critical",
"(",
"''",
",",
"exc_info",
"=",
"True",
")",
"raise",
"finally",
":",
"# cleanup globals",
"if",
"ct",
"==",
"0",
":",
"# restore OQ_DISTRIBUTE",
"if",
"oq_distribute",
"is",
"None",
":",
"# was not set",
"del",
"os",
".",
"environ",
"[",
"'OQ_DISTRIBUTE'",
"]",
"else",
":",
"os",
".",
"environ",
"[",
"'OQ_DISTRIBUTE'",
"]",
"=",
"oq_distribute",
"readinput",
".",
"pmap",
"=",
"None",
"readinput",
".",
"exposure",
"=",
"None",
"readinput",
".",
"gmfs",
"=",
"None",
"readinput",
".",
"eids",
"=",
"None",
"self",
".",
"_monitor",
".",
"flush",
"(",
")",
"if",
"close",
":",
"# in the engine we close later",
"self",
".",
"result",
"=",
"None",
"try",
":",
"self",
".",
"datastore",
".",
"close",
"(",
")",
"except",
"(",
"RuntimeError",
",",
"ValueError",
")",
":",
"# sometimes produces errors but they are difficult to",
"# reproduce",
"logging",
".",
"warning",
"(",
"''",
",",
"exc_info",
"=",
"True",
")",
"return",
"getattr",
"(",
"self",
",",
"'exported'",
",",
"{",
"}",
")"
] | Run the calculation and return the exported outputs. | [
"Run",
"the",
"calculation",
"and",
"return",
"the",
"exported",
"outputs",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L175-L231 | train | 232,903 |
gem/oq-engine | openquake/calculators/base.py | BaseCalculator.export | def export(self, exports=None):
"""
Export all the outputs in the datastore in the given export formats.
Individual outputs are not exported if there are multiple realizations.
"""
self.exported = getattr(self.precalc, 'exported', {})
if isinstance(exports, tuple):
fmts = exports
elif exports: # is a string
fmts = exports.split(',')
elif isinstance(self.oqparam.exports, tuple):
fmts = self.oqparam.exports
else: # is a string
fmts = self.oqparam.exports.split(',')
keys = set(self.datastore)
has_hcurves = ('hcurves-stats' in self.datastore or
'hcurves-rlzs' in self.datastore)
if has_hcurves:
keys.add('hcurves')
for fmt in fmts:
if not fmt:
continue
for key in sorted(keys): # top level keys
if 'rlzs' in key and self.R > 1:
continue # skip individual curves
self._export((key, fmt))
if has_hcurves and self.oqparam.hazard_maps:
self._export(('hmaps', fmt))
if has_hcurves and self.oqparam.uniform_hazard_spectra:
self._export(('uhs', fmt)) | python | def export(self, exports=None):
"""
Export all the outputs in the datastore in the given export formats.
Individual outputs are not exported if there are multiple realizations.
"""
self.exported = getattr(self.precalc, 'exported', {})
if isinstance(exports, tuple):
fmts = exports
elif exports: # is a string
fmts = exports.split(',')
elif isinstance(self.oqparam.exports, tuple):
fmts = self.oqparam.exports
else: # is a string
fmts = self.oqparam.exports.split(',')
keys = set(self.datastore)
has_hcurves = ('hcurves-stats' in self.datastore or
'hcurves-rlzs' in self.datastore)
if has_hcurves:
keys.add('hcurves')
for fmt in fmts:
if not fmt:
continue
for key in sorted(keys): # top level keys
if 'rlzs' in key and self.R > 1:
continue # skip individual curves
self._export((key, fmt))
if has_hcurves and self.oqparam.hazard_maps:
self._export(('hmaps', fmt))
if has_hcurves and self.oqparam.uniform_hazard_spectra:
self._export(('uhs', fmt)) | [
"def",
"export",
"(",
"self",
",",
"exports",
"=",
"None",
")",
":",
"self",
".",
"exported",
"=",
"getattr",
"(",
"self",
".",
"precalc",
",",
"'exported'",
",",
"{",
"}",
")",
"if",
"isinstance",
"(",
"exports",
",",
"tuple",
")",
":",
"fmts",
"=",
"exports",
"elif",
"exports",
":",
"# is a string",
"fmts",
"=",
"exports",
".",
"split",
"(",
"','",
")",
"elif",
"isinstance",
"(",
"self",
".",
"oqparam",
".",
"exports",
",",
"tuple",
")",
":",
"fmts",
"=",
"self",
".",
"oqparam",
".",
"exports",
"else",
":",
"# is a string",
"fmts",
"=",
"self",
".",
"oqparam",
".",
"exports",
".",
"split",
"(",
"','",
")",
"keys",
"=",
"set",
"(",
"self",
".",
"datastore",
")",
"has_hcurves",
"=",
"(",
"'hcurves-stats'",
"in",
"self",
".",
"datastore",
"or",
"'hcurves-rlzs'",
"in",
"self",
".",
"datastore",
")",
"if",
"has_hcurves",
":",
"keys",
".",
"add",
"(",
"'hcurves'",
")",
"for",
"fmt",
"in",
"fmts",
":",
"if",
"not",
"fmt",
":",
"continue",
"for",
"key",
"in",
"sorted",
"(",
"keys",
")",
":",
"# top level keys",
"if",
"'rlzs'",
"in",
"key",
"and",
"self",
".",
"R",
">",
"1",
":",
"continue",
"# skip individual curves",
"self",
".",
"_export",
"(",
"(",
"key",
",",
"fmt",
")",
")",
"if",
"has_hcurves",
"and",
"self",
".",
"oqparam",
".",
"hazard_maps",
":",
"self",
".",
"_export",
"(",
"(",
"'hmaps'",
",",
"fmt",
")",
")",
"if",
"has_hcurves",
"and",
"self",
".",
"oqparam",
".",
"uniform_hazard_spectra",
":",
"self",
".",
"_export",
"(",
"(",
"'uhs'",
",",
"fmt",
")",
")"
] | Export all the outputs in the datastore in the given export formats.
Individual outputs are not exported if there are multiple realizations. | [
"Export",
"all",
"the",
"outputs",
"in",
"the",
"datastore",
"in",
"the",
"given",
"export",
"formats",
".",
"Individual",
"outputs",
"are",
"not",
"exported",
"if",
"there",
"are",
"multiple",
"realizations",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L260-L289 | train | 232,904 |
gem/oq-engine | openquake/calculators/base.py | BaseCalculator.before_export | def before_export(self):
"""
Set the attributes nbytes
"""
# sanity check that eff_ruptures have been set, i.e. are not -1
try:
csm_info = self.datastore['csm_info']
except KeyError:
csm_info = self.datastore['csm_info'] = self.csm.info
for sm in csm_info.source_models:
for sg in sm.src_groups:
assert sg.eff_ruptures != -1, sg
for key in self.datastore:
self.datastore.set_nbytes(key)
self.datastore.flush() | python | def before_export(self):
"""
Set the attributes nbytes
"""
# sanity check that eff_ruptures have been set, i.e. are not -1
try:
csm_info = self.datastore['csm_info']
except KeyError:
csm_info = self.datastore['csm_info'] = self.csm.info
for sm in csm_info.source_models:
for sg in sm.src_groups:
assert sg.eff_ruptures != -1, sg
for key in self.datastore:
self.datastore.set_nbytes(key)
self.datastore.flush() | [
"def",
"before_export",
"(",
"self",
")",
":",
"# sanity check that eff_ruptures have been set, i.e. are not -1",
"try",
":",
"csm_info",
"=",
"self",
".",
"datastore",
"[",
"'csm_info'",
"]",
"except",
"KeyError",
":",
"csm_info",
"=",
"self",
".",
"datastore",
"[",
"'csm_info'",
"]",
"=",
"self",
".",
"csm",
".",
"info",
"for",
"sm",
"in",
"csm_info",
".",
"source_models",
":",
"for",
"sg",
"in",
"sm",
".",
"src_groups",
":",
"assert",
"sg",
".",
"eff_ruptures",
"!=",
"-",
"1",
",",
"sg",
"for",
"key",
"in",
"self",
".",
"datastore",
":",
"self",
".",
"datastore",
".",
"set_nbytes",
"(",
"key",
")",
"self",
".",
"datastore",
".",
"flush",
"(",
")"
] | Set the attributes nbytes | [
"Set",
"the",
"attributes",
"nbytes"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L303-L318 | train | 232,905 |
gem/oq-engine | openquake/calculators/base.py | HazardCalculator.read_inputs | def read_inputs(self):
"""
Read risk data and sources if any
"""
oq = self.oqparam
self._read_risk_data()
self.check_overflow() # check if self.sitecol is too large
if ('source_model_logic_tree' in oq.inputs and
oq.hazard_calculation_id is None):
self.csm = readinput.get_composite_source_model(
oq, self.monitor(), srcfilter=self.src_filter)
self.init() | python | def read_inputs(self):
"""
Read risk data and sources if any
"""
oq = self.oqparam
self._read_risk_data()
self.check_overflow() # check if self.sitecol is too large
if ('source_model_logic_tree' in oq.inputs and
oq.hazard_calculation_id is None):
self.csm = readinput.get_composite_source_model(
oq, self.monitor(), srcfilter=self.src_filter)
self.init() | [
"def",
"read_inputs",
"(",
"self",
")",
":",
"oq",
"=",
"self",
".",
"oqparam",
"self",
".",
"_read_risk_data",
"(",
")",
"self",
".",
"check_overflow",
"(",
")",
"# check if self.sitecol is too large",
"if",
"(",
"'source_model_logic_tree'",
"in",
"oq",
".",
"inputs",
"and",
"oq",
".",
"hazard_calculation_id",
"is",
"None",
")",
":",
"self",
".",
"csm",
"=",
"readinput",
".",
"get_composite_source_model",
"(",
"oq",
",",
"self",
".",
"monitor",
"(",
")",
",",
"srcfilter",
"=",
"self",
".",
"src_filter",
")",
"self",
".",
"init",
"(",
")"
] | Read risk data and sources if any | [
"Read",
"risk",
"data",
"and",
"sources",
"if",
"any"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L406-L417 | train | 232,906 |
gem/oq-engine | openquake/calculators/base.py | HazardCalculator.pre_execute | def pre_execute(self):
"""
Check if there is a previous calculation ID.
If yes, read the inputs by retrieving the previous calculation;
if not, read the inputs directly.
"""
oq = self.oqparam
if 'gmfs' in oq.inputs or 'multi_peril' in oq.inputs:
# read hazard from files
assert not oq.hazard_calculation_id, (
'You cannot use --hc together with gmfs_file')
self.read_inputs()
if 'gmfs' in oq.inputs:
save_gmfs(self)
else:
self.save_multi_peril()
elif 'hazard_curves' in oq.inputs: # read hazard from file
assert not oq.hazard_calculation_id, (
'You cannot use --hc together with hazard_curves')
haz_sitecol = readinput.get_site_collection(oq)
# NB: horrible: get_site_collection calls get_pmap_from_nrml
# that sets oq.investigation_time, so it must be called first
self.load_riskmodel() # must be after get_site_collection
self.read_exposure(haz_sitecol) # define .assets_by_site
self.datastore['poes/grp-00'] = fix_ones(readinput.pmap)
self.datastore['sitecol'] = self.sitecol
self.datastore['assetcol'] = self.assetcol
self.datastore['csm_info'] = fake = source.CompositionInfo.fake()
self.rlzs_assoc = fake.get_rlzs_assoc()
elif oq.hazard_calculation_id:
parent = util.read(oq.hazard_calculation_id)
self.check_precalc(parent['oqparam'].calculation_mode)
self.datastore.parent = parent
# copy missing parameters from the parent
params = {name: value for name, value in
vars(parent['oqparam']).items()
if name not in vars(self.oqparam)}
self.save_params(**params)
self.read_inputs()
oqp = parent['oqparam']
if oqp.investigation_time != oq.investigation_time:
raise ValueError(
'The parent calculation was using investigation_time=%s'
' != %s' % (oqp.investigation_time, oq.investigation_time))
if oqp.minimum_intensity != oq.minimum_intensity:
raise ValueError(
'The parent calculation was using minimum_intensity=%s'
' != %s' % (oqp.minimum_intensity, oq.minimum_intensity))
missing_imts = set(oq.risk_imtls) - set(oqp.imtls)
if missing_imts:
raise ValueError(
'The parent calculation is missing the IMT(s) %s' %
', '.join(missing_imts))
elif self.__class__.precalc:
calc = calculators[self.__class__.precalc](
self.oqparam, self.datastore.calc_id)
calc.run()
self.param = calc.param
self.sitecol = calc.sitecol
self.assetcol = calc.assetcol
self.riskmodel = calc.riskmodel
if hasattr(calc, 'rlzs_assoc'):
self.rlzs_assoc = calc.rlzs_assoc
else:
# this happens for instance for a scenario_damage without
# rupture, gmfs, multi_peril
raise InvalidFile(
'%(job_ini)s: missing gmfs_csv, multi_peril_csv' %
oq.inputs)
if hasattr(calc, 'csm'): # no scenario
self.csm = calc.csm
else:
self.read_inputs()
if self.riskmodel:
self.save_riskmodel() | python | def pre_execute(self):
"""
Check if there is a previous calculation ID.
If yes, read the inputs by retrieving the previous calculation;
if not, read the inputs directly.
"""
oq = self.oqparam
if 'gmfs' in oq.inputs or 'multi_peril' in oq.inputs:
# read hazard from files
assert not oq.hazard_calculation_id, (
'You cannot use --hc together with gmfs_file')
self.read_inputs()
if 'gmfs' in oq.inputs:
save_gmfs(self)
else:
self.save_multi_peril()
elif 'hazard_curves' in oq.inputs: # read hazard from file
assert not oq.hazard_calculation_id, (
'You cannot use --hc together with hazard_curves')
haz_sitecol = readinput.get_site_collection(oq)
# NB: horrible: get_site_collection calls get_pmap_from_nrml
# that sets oq.investigation_time, so it must be called first
self.load_riskmodel() # must be after get_site_collection
self.read_exposure(haz_sitecol) # define .assets_by_site
self.datastore['poes/grp-00'] = fix_ones(readinput.pmap)
self.datastore['sitecol'] = self.sitecol
self.datastore['assetcol'] = self.assetcol
self.datastore['csm_info'] = fake = source.CompositionInfo.fake()
self.rlzs_assoc = fake.get_rlzs_assoc()
elif oq.hazard_calculation_id:
parent = util.read(oq.hazard_calculation_id)
self.check_precalc(parent['oqparam'].calculation_mode)
self.datastore.parent = parent
# copy missing parameters from the parent
params = {name: value for name, value in
vars(parent['oqparam']).items()
if name not in vars(self.oqparam)}
self.save_params(**params)
self.read_inputs()
oqp = parent['oqparam']
if oqp.investigation_time != oq.investigation_time:
raise ValueError(
'The parent calculation was using investigation_time=%s'
' != %s' % (oqp.investigation_time, oq.investigation_time))
if oqp.minimum_intensity != oq.minimum_intensity:
raise ValueError(
'The parent calculation was using minimum_intensity=%s'
' != %s' % (oqp.minimum_intensity, oq.minimum_intensity))
missing_imts = set(oq.risk_imtls) - set(oqp.imtls)
if missing_imts:
raise ValueError(
'The parent calculation is missing the IMT(s) %s' %
', '.join(missing_imts))
elif self.__class__.precalc:
calc = calculators[self.__class__.precalc](
self.oqparam, self.datastore.calc_id)
calc.run()
self.param = calc.param
self.sitecol = calc.sitecol
self.assetcol = calc.assetcol
self.riskmodel = calc.riskmodel
if hasattr(calc, 'rlzs_assoc'):
self.rlzs_assoc = calc.rlzs_assoc
else:
# this happens for instance for a scenario_damage without
# rupture, gmfs, multi_peril
raise InvalidFile(
'%(job_ini)s: missing gmfs_csv, multi_peril_csv' %
oq.inputs)
if hasattr(calc, 'csm'): # no scenario
self.csm = calc.csm
else:
self.read_inputs()
if self.riskmodel:
self.save_riskmodel() | [
"def",
"pre_execute",
"(",
"self",
")",
":",
"oq",
"=",
"self",
".",
"oqparam",
"if",
"'gmfs'",
"in",
"oq",
".",
"inputs",
"or",
"'multi_peril'",
"in",
"oq",
".",
"inputs",
":",
"# read hazard from files",
"assert",
"not",
"oq",
".",
"hazard_calculation_id",
",",
"(",
"'You cannot use --hc together with gmfs_file'",
")",
"self",
".",
"read_inputs",
"(",
")",
"if",
"'gmfs'",
"in",
"oq",
".",
"inputs",
":",
"save_gmfs",
"(",
"self",
")",
"else",
":",
"self",
".",
"save_multi_peril",
"(",
")",
"elif",
"'hazard_curves'",
"in",
"oq",
".",
"inputs",
":",
"# read hazard from file",
"assert",
"not",
"oq",
".",
"hazard_calculation_id",
",",
"(",
"'You cannot use --hc together with hazard_curves'",
")",
"haz_sitecol",
"=",
"readinput",
".",
"get_site_collection",
"(",
"oq",
")",
"# NB: horrible: get_site_collection calls get_pmap_from_nrml",
"# that sets oq.investigation_time, so it must be called first",
"self",
".",
"load_riskmodel",
"(",
")",
"# must be after get_site_collection",
"self",
".",
"read_exposure",
"(",
"haz_sitecol",
")",
"# define .assets_by_site",
"self",
".",
"datastore",
"[",
"'poes/grp-00'",
"]",
"=",
"fix_ones",
"(",
"readinput",
".",
"pmap",
")",
"self",
".",
"datastore",
"[",
"'sitecol'",
"]",
"=",
"self",
".",
"sitecol",
"self",
".",
"datastore",
"[",
"'assetcol'",
"]",
"=",
"self",
".",
"assetcol",
"self",
".",
"datastore",
"[",
"'csm_info'",
"]",
"=",
"fake",
"=",
"source",
".",
"CompositionInfo",
".",
"fake",
"(",
")",
"self",
".",
"rlzs_assoc",
"=",
"fake",
".",
"get_rlzs_assoc",
"(",
")",
"elif",
"oq",
".",
"hazard_calculation_id",
":",
"parent",
"=",
"util",
".",
"read",
"(",
"oq",
".",
"hazard_calculation_id",
")",
"self",
".",
"check_precalc",
"(",
"parent",
"[",
"'oqparam'",
"]",
".",
"calculation_mode",
")",
"self",
".",
"datastore",
".",
"parent",
"=",
"parent",
"# copy missing parameters from the parent",
"params",
"=",
"{",
"name",
":",
"value",
"for",
"name",
",",
"value",
"in",
"vars",
"(",
"parent",
"[",
"'oqparam'",
"]",
")",
".",
"items",
"(",
")",
"if",
"name",
"not",
"in",
"vars",
"(",
"self",
".",
"oqparam",
")",
"}",
"self",
".",
"save_params",
"(",
"*",
"*",
"params",
")",
"self",
".",
"read_inputs",
"(",
")",
"oqp",
"=",
"parent",
"[",
"'oqparam'",
"]",
"if",
"oqp",
".",
"investigation_time",
"!=",
"oq",
".",
"investigation_time",
":",
"raise",
"ValueError",
"(",
"'The parent calculation was using investigation_time=%s'",
"' != %s'",
"%",
"(",
"oqp",
".",
"investigation_time",
",",
"oq",
".",
"investigation_time",
")",
")",
"if",
"oqp",
".",
"minimum_intensity",
"!=",
"oq",
".",
"minimum_intensity",
":",
"raise",
"ValueError",
"(",
"'The parent calculation was using minimum_intensity=%s'",
"' != %s'",
"%",
"(",
"oqp",
".",
"minimum_intensity",
",",
"oq",
".",
"minimum_intensity",
")",
")",
"missing_imts",
"=",
"set",
"(",
"oq",
".",
"risk_imtls",
")",
"-",
"set",
"(",
"oqp",
".",
"imtls",
")",
"if",
"missing_imts",
":",
"raise",
"ValueError",
"(",
"'The parent calculation is missing the IMT(s) %s'",
"%",
"', '",
".",
"join",
"(",
"missing_imts",
")",
")",
"elif",
"self",
".",
"__class__",
".",
"precalc",
":",
"calc",
"=",
"calculators",
"[",
"self",
".",
"__class__",
".",
"precalc",
"]",
"(",
"self",
".",
"oqparam",
",",
"self",
".",
"datastore",
".",
"calc_id",
")",
"calc",
".",
"run",
"(",
")",
"self",
".",
"param",
"=",
"calc",
".",
"param",
"self",
".",
"sitecol",
"=",
"calc",
".",
"sitecol",
"self",
".",
"assetcol",
"=",
"calc",
".",
"assetcol",
"self",
".",
"riskmodel",
"=",
"calc",
".",
"riskmodel",
"if",
"hasattr",
"(",
"calc",
",",
"'rlzs_assoc'",
")",
":",
"self",
".",
"rlzs_assoc",
"=",
"calc",
".",
"rlzs_assoc",
"else",
":",
"# this happens for instance for a scenario_damage without",
"# rupture, gmfs, multi_peril",
"raise",
"InvalidFile",
"(",
"'%(job_ini)s: missing gmfs_csv, multi_peril_csv'",
"%",
"oq",
".",
"inputs",
")",
"if",
"hasattr",
"(",
"calc",
",",
"'csm'",
")",
":",
"# no scenario",
"self",
".",
"csm",
"=",
"calc",
".",
"csm",
"else",
":",
"self",
".",
"read_inputs",
"(",
")",
"if",
"self",
".",
"riskmodel",
":",
"self",
".",
"save_riskmodel",
"(",
")"
] | Check if there is a previous calculation ID.
If yes, read the inputs by retrieving the previous calculation;
if not, read the inputs directly. | [
"Check",
"if",
"there",
"is",
"a",
"previous",
"calculation",
"ID",
".",
"If",
"yes",
"read",
"the",
"inputs",
"by",
"retrieving",
"the",
"previous",
"calculation",
";",
"if",
"not",
"read",
"the",
"inputs",
"directly",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L422-L496 | train | 232,907 |
gem/oq-engine | openquake/calculators/base.py | HazardCalculator.init | def init(self):
"""
To be overridden to initialize the datasets needed by the calculation
"""
oq = self.oqparam
if not oq.risk_imtls:
if self.datastore.parent:
oq.risk_imtls = (
self.datastore.parent['oqparam'].risk_imtls)
if 'precalc' in vars(self):
self.rlzs_assoc = self.precalc.rlzs_assoc
elif 'csm_info' in self.datastore:
csm_info = self.datastore['csm_info']
if oq.hazard_calculation_id and 'gsim_logic_tree' in oq.inputs:
# redefine the realizations by reading the weights from the
# gsim_logic_tree_file that could be different from the parent
csm_info.gsim_lt = logictree.GsimLogicTree(
oq.inputs['gsim_logic_tree'], set(csm_info.trts))
self.rlzs_assoc = csm_info.get_rlzs_assoc()
elif hasattr(self, 'csm'):
self.check_floating_spinning()
self.rlzs_assoc = self.csm.info.get_rlzs_assoc()
else: # build a fake; used by risk-from-file calculators
self.datastore['csm_info'] = fake = source.CompositionInfo.fake()
self.rlzs_assoc = fake.get_rlzs_assoc() | python | def init(self):
"""
To be overridden to initialize the datasets needed by the calculation
"""
oq = self.oqparam
if not oq.risk_imtls:
if self.datastore.parent:
oq.risk_imtls = (
self.datastore.parent['oqparam'].risk_imtls)
if 'precalc' in vars(self):
self.rlzs_assoc = self.precalc.rlzs_assoc
elif 'csm_info' in self.datastore:
csm_info = self.datastore['csm_info']
if oq.hazard_calculation_id and 'gsim_logic_tree' in oq.inputs:
# redefine the realizations by reading the weights from the
# gsim_logic_tree_file that could be different from the parent
csm_info.gsim_lt = logictree.GsimLogicTree(
oq.inputs['gsim_logic_tree'], set(csm_info.trts))
self.rlzs_assoc = csm_info.get_rlzs_assoc()
elif hasattr(self, 'csm'):
self.check_floating_spinning()
self.rlzs_assoc = self.csm.info.get_rlzs_assoc()
else: # build a fake; used by risk-from-file calculators
self.datastore['csm_info'] = fake = source.CompositionInfo.fake()
self.rlzs_assoc = fake.get_rlzs_assoc() | [
"def",
"init",
"(",
"self",
")",
":",
"oq",
"=",
"self",
".",
"oqparam",
"if",
"not",
"oq",
".",
"risk_imtls",
":",
"if",
"self",
".",
"datastore",
".",
"parent",
":",
"oq",
".",
"risk_imtls",
"=",
"(",
"self",
".",
"datastore",
".",
"parent",
"[",
"'oqparam'",
"]",
".",
"risk_imtls",
")",
"if",
"'precalc'",
"in",
"vars",
"(",
"self",
")",
":",
"self",
".",
"rlzs_assoc",
"=",
"self",
".",
"precalc",
".",
"rlzs_assoc",
"elif",
"'csm_info'",
"in",
"self",
".",
"datastore",
":",
"csm_info",
"=",
"self",
".",
"datastore",
"[",
"'csm_info'",
"]",
"if",
"oq",
".",
"hazard_calculation_id",
"and",
"'gsim_logic_tree'",
"in",
"oq",
".",
"inputs",
":",
"# redefine the realizations by reading the weights from the",
"# gsim_logic_tree_file that could be different from the parent",
"csm_info",
".",
"gsim_lt",
"=",
"logictree",
".",
"GsimLogicTree",
"(",
"oq",
".",
"inputs",
"[",
"'gsim_logic_tree'",
"]",
",",
"set",
"(",
"csm_info",
".",
"trts",
")",
")",
"self",
".",
"rlzs_assoc",
"=",
"csm_info",
".",
"get_rlzs_assoc",
"(",
")",
"elif",
"hasattr",
"(",
"self",
",",
"'csm'",
")",
":",
"self",
".",
"check_floating_spinning",
"(",
")",
"self",
".",
"rlzs_assoc",
"=",
"self",
".",
"csm",
".",
"info",
".",
"get_rlzs_assoc",
"(",
")",
"else",
":",
"# build a fake; used by risk-from-file calculators",
"self",
".",
"datastore",
"[",
"'csm_info'",
"]",
"=",
"fake",
"=",
"source",
".",
"CompositionInfo",
".",
"fake",
"(",
")",
"self",
".",
"rlzs_assoc",
"=",
"fake",
".",
"get_rlzs_assoc",
"(",
")"
] | To be overridden to initialize the datasets needed by the calculation | [
"To",
"be",
"overridden",
"to",
"initialize",
"the",
"datasets",
"needed",
"by",
"the",
"calculation"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L498-L522 | train | 232,908 |
gem/oq-engine | openquake/calculators/base.py | HazardCalculator.read_exposure | def read_exposure(self, haz_sitecol=None): # after load_risk_model
"""
Read the exposure, the riskmodel and update the attributes
.sitecol, .assetcol
"""
with self.monitor('reading exposure', autoflush=True):
self.sitecol, self.assetcol, discarded = (
readinput.get_sitecol_assetcol(
self.oqparam, haz_sitecol, self.riskmodel.loss_types))
if len(discarded):
self.datastore['discarded'] = discarded
if hasattr(self, 'rup'):
# this is normal for the case of scenario from rupture
logging.info('%d assets were discarded because too far '
'from the rupture; use `oq show discarded` '
'to show them and `oq plot_assets` to plot '
'them' % len(discarded))
elif not self.oqparam.discard_assets: # raise an error
self.datastore['sitecol'] = self.sitecol
self.datastore['assetcol'] = self.assetcol
raise RuntimeError(
'%d assets were discarded; use `oq show discarded` to'
' show them and `oq plot_assets` to plot them' %
len(discarded))
# reduce the riskmodel to the relevant taxonomies
taxonomies = set(taxo for taxo in self.assetcol.tagcol.taxonomy
if taxo != '?')
if len(self.riskmodel.taxonomies) > len(taxonomies):
logging.info('Reducing risk model from %d to %d taxonomies',
len(self.riskmodel.taxonomies), len(taxonomies))
self.riskmodel = self.riskmodel.reduce(taxonomies)
return readinput.exposure | python | def read_exposure(self, haz_sitecol=None): # after load_risk_model
"""
Read the exposure, the riskmodel and update the attributes
.sitecol, .assetcol
"""
with self.monitor('reading exposure', autoflush=True):
self.sitecol, self.assetcol, discarded = (
readinput.get_sitecol_assetcol(
self.oqparam, haz_sitecol, self.riskmodel.loss_types))
if len(discarded):
self.datastore['discarded'] = discarded
if hasattr(self, 'rup'):
# this is normal for the case of scenario from rupture
logging.info('%d assets were discarded because too far '
'from the rupture; use `oq show discarded` '
'to show them and `oq plot_assets` to plot '
'them' % len(discarded))
elif not self.oqparam.discard_assets: # raise an error
self.datastore['sitecol'] = self.sitecol
self.datastore['assetcol'] = self.assetcol
raise RuntimeError(
'%d assets were discarded; use `oq show discarded` to'
' show them and `oq plot_assets` to plot them' %
len(discarded))
# reduce the riskmodel to the relevant taxonomies
taxonomies = set(taxo for taxo in self.assetcol.tagcol.taxonomy
if taxo != '?')
if len(self.riskmodel.taxonomies) > len(taxonomies):
logging.info('Reducing risk model from %d to %d taxonomies',
len(self.riskmodel.taxonomies), len(taxonomies))
self.riskmodel = self.riskmodel.reduce(taxonomies)
return readinput.exposure | [
"def",
"read_exposure",
"(",
"self",
",",
"haz_sitecol",
"=",
"None",
")",
":",
"# after load_risk_model",
"with",
"self",
".",
"monitor",
"(",
"'reading exposure'",
",",
"autoflush",
"=",
"True",
")",
":",
"self",
".",
"sitecol",
",",
"self",
".",
"assetcol",
",",
"discarded",
"=",
"(",
"readinput",
".",
"get_sitecol_assetcol",
"(",
"self",
".",
"oqparam",
",",
"haz_sitecol",
",",
"self",
".",
"riskmodel",
".",
"loss_types",
")",
")",
"if",
"len",
"(",
"discarded",
")",
":",
"self",
".",
"datastore",
"[",
"'discarded'",
"]",
"=",
"discarded",
"if",
"hasattr",
"(",
"self",
",",
"'rup'",
")",
":",
"# this is normal for the case of scenario from rupture",
"logging",
".",
"info",
"(",
"'%d assets were discarded because too far '",
"'from the rupture; use `oq show discarded` '",
"'to show them and `oq plot_assets` to plot '",
"'them'",
"%",
"len",
"(",
"discarded",
")",
")",
"elif",
"not",
"self",
".",
"oqparam",
".",
"discard_assets",
":",
"# raise an error",
"self",
".",
"datastore",
"[",
"'sitecol'",
"]",
"=",
"self",
".",
"sitecol",
"self",
".",
"datastore",
"[",
"'assetcol'",
"]",
"=",
"self",
".",
"assetcol",
"raise",
"RuntimeError",
"(",
"'%d assets were discarded; use `oq show discarded` to'",
"' show them and `oq plot_assets` to plot them'",
"%",
"len",
"(",
"discarded",
")",
")",
"# reduce the riskmodel to the relevant taxonomies",
"taxonomies",
"=",
"set",
"(",
"taxo",
"for",
"taxo",
"in",
"self",
".",
"assetcol",
".",
"tagcol",
".",
"taxonomy",
"if",
"taxo",
"!=",
"'?'",
")",
"if",
"len",
"(",
"self",
".",
"riskmodel",
".",
"taxonomies",
")",
">",
"len",
"(",
"taxonomies",
")",
":",
"logging",
".",
"info",
"(",
"'Reducing risk model from %d to %d taxonomies'",
",",
"len",
"(",
"self",
".",
"riskmodel",
".",
"taxonomies",
")",
",",
"len",
"(",
"taxonomies",
")",
")",
"self",
".",
"riskmodel",
"=",
"self",
".",
"riskmodel",
".",
"reduce",
"(",
"taxonomies",
")",
"return",
"readinput",
".",
"exposure"
] | Read the exposure, the riskmodel and update the attributes
.sitecol, .assetcol | [
"Read",
"the",
"exposure",
"the",
"riskmodel",
"and",
"update",
"the",
"attributes",
".",
"sitecol",
".",
"assetcol"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L534-L566 | train | 232,909 |
gem/oq-engine | openquake/calculators/base.py | HazardCalculator.save_riskmodel | def save_riskmodel(self):
"""
Save the risk models in the datastore
"""
self.datastore['risk_model'] = rm = self.riskmodel
self.datastore['taxonomy_mapping'] = self.riskmodel.tmap
attrs = self.datastore.getitem('risk_model').attrs
attrs['min_iml'] = hdf5.array_of_vstr(sorted(rm.min_iml.items()))
self.datastore.set_nbytes('risk_model') | python | def save_riskmodel(self):
"""
Save the risk models in the datastore
"""
self.datastore['risk_model'] = rm = self.riskmodel
self.datastore['taxonomy_mapping'] = self.riskmodel.tmap
attrs = self.datastore.getitem('risk_model').attrs
attrs['min_iml'] = hdf5.array_of_vstr(sorted(rm.min_iml.items()))
self.datastore.set_nbytes('risk_model') | [
"def",
"save_riskmodel",
"(",
"self",
")",
":",
"self",
".",
"datastore",
"[",
"'risk_model'",
"]",
"=",
"rm",
"=",
"self",
".",
"riskmodel",
"self",
".",
"datastore",
"[",
"'taxonomy_mapping'",
"]",
"=",
"self",
".",
"riskmodel",
".",
"tmap",
"attrs",
"=",
"self",
".",
"datastore",
".",
"getitem",
"(",
"'risk_model'",
")",
".",
"attrs",
"attrs",
"[",
"'min_iml'",
"]",
"=",
"hdf5",
".",
"array_of_vstr",
"(",
"sorted",
"(",
"rm",
".",
"min_iml",
".",
"items",
"(",
")",
")",
")",
"self",
".",
"datastore",
".",
"set_nbytes",
"(",
"'risk_model'",
")"
] | Save the risk models in the datastore | [
"Save",
"the",
"risk",
"models",
"in",
"the",
"datastore"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L588-L596 | train | 232,910 |
gem/oq-engine | openquake/calculators/base.py | HazardCalculator.store_rlz_info | def store_rlz_info(self, eff_ruptures=None):
"""
Save info about the composite source model inside the csm_info dataset
"""
if hasattr(self, 'csm'): # no scenario
self.csm.info.update_eff_ruptures(eff_ruptures)
self.rlzs_assoc = self.csm.info.get_rlzs_assoc(
self.oqparam.sm_lt_path)
if not self.rlzs_assoc:
raise RuntimeError('Empty logic tree: too much filtering?')
self.datastore['csm_info'] = self.csm.info
R = len(self.rlzs_assoc.realizations)
logging.info('There are %d realization(s)', R)
if self.oqparam.imtls:
self.datastore['weights'] = arr = build_weights(
self.rlzs_assoc.realizations, self.oqparam.imt_dt())
self.datastore.set_attrs('weights', nbytes=arr.nbytes)
if hasattr(self, 'hdf5cache'): # no scenario
with hdf5.File(self.hdf5cache, 'r+') as cache:
cache['weights'] = arr
if 'event_based' in self.oqparam.calculation_mode and R >= TWO16:
# rlzi is 16 bit integer in the GMFs, so there is hard limit or R
raise ValueError(
'The logic tree has %d realizations, the maximum '
'is %d' % (R, TWO16))
elif R > 10000:
logging.warning(
'The logic tree has %d realizations(!), please consider '
'sampling it', R)
self.datastore.flush() | python | def store_rlz_info(self, eff_ruptures=None):
"""
Save info about the composite source model inside the csm_info dataset
"""
if hasattr(self, 'csm'): # no scenario
self.csm.info.update_eff_ruptures(eff_ruptures)
self.rlzs_assoc = self.csm.info.get_rlzs_assoc(
self.oqparam.sm_lt_path)
if not self.rlzs_assoc:
raise RuntimeError('Empty logic tree: too much filtering?')
self.datastore['csm_info'] = self.csm.info
R = len(self.rlzs_assoc.realizations)
logging.info('There are %d realization(s)', R)
if self.oqparam.imtls:
self.datastore['weights'] = arr = build_weights(
self.rlzs_assoc.realizations, self.oqparam.imt_dt())
self.datastore.set_attrs('weights', nbytes=arr.nbytes)
if hasattr(self, 'hdf5cache'): # no scenario
with hdf5.File(self.hdf5cache, 'r+') as cache:
cache['weights'] = arr
if 'event_based' in self.oqparam.calculation_mode and R >= TWO16:
# rlzi is 16 bit integer in the GMFs, so there is hard limit or R
raise ValueError(
'The logic tree has %d realizations, the maximum '
'is %d' % (R, TWO16))
elif R > 10000:
logging.warning(
'The logic tree has %d realizations(!), please consider '
'sampling it', R)
self.datastore.flush() | [
"def",
"store_rlz_info",
"(",
"self",
",",
"eff_ruptures",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'csm'",
")",
":",
"# no scenario",
"self",
".",
"csm",
".",
"info",
".",
"update_eff_ruptures",
"(",
"eff_ruptures",
")",
"self",
".",
"rlzs_assoc",
"=",
"self",
".",
"csm",
".",
"info",
".",
"get_rlzs_assoc",
"(",
"self",
".",
"oqparam",
".",
"sm_lt_path",
")",
"if",
"not",
"self",
".",
"rlzs_assoc",
":",
"raise",
"RuntimeError",
"(",
"'Empty logic tree: too much filtering?'",
")",
"self",
".",
"datastore",
"[",
"'csm_info'",
"]",
"=",
"self",
".",
"csm",
".",
"info",
"R",
"=",
"len",
"(",
"self",
".",
"rlzs_assoc",
".",
"realizations",
")",
"logging",
".",
"info",
"(",
"'There are %d realization(s)'",
",",
"R",
")",
"if",
"self",
".",
"oqparam",
".",
"imtls",
":",
"self",
".",
"datastore",
"[",
"'weights'",
"]",
"=",
"arr",
"=",
"build_weights",
"(",
"self",
".",
"rlzs_assoc",
".",
"realizations",
",",
"self",
".",
"oqparam",
".",
"imt_dt",
"(",
")",
")",
"self",
".",
"datastore",
".",
"set_attrs",
"(",
"'weights'",
",",
"nbytes",
"=",
"arr",
".",
"nbytes",
")",
"if",
"hasattr",
"(",
"self",
",",
"'hdf5cache'",
")",
":",
"# no scenario",
"with",
"hdf5",
".",
"File",
"(",
"self",
".",
"hdf5cache",
",",
"'r+'",
")",
"as",
"cache",
":",
"cache",
"[",
"'weights'",
"]",
"=",
"arr",
"if",
"'event_based'",
"in",
"self",
".",
"oqparam",
".",
"calculation_mode",
"and",
"R",
">=",
"TWO16",
":",
"# rlzi is 16 bit integer in the GMFs, so there is hard limit or R",
"raise",
"ValueError",
"(",
"'The logic tree has %d realizations, the maximum '",
"'is %d'",
"%",
"(",
"R",
",",
"TWO16",
")",
")",
"elif",
"R",
">",
"10000",
":",
"logging",
".",
"warning",
"(",
"'The logic tree has %d realizations(!), please consider '",
"'sampling it'",
",",
"R",
")",
"self",
".",
"datastore",
".",
"flush",
"(",
")"
] | Save info about the composite source model inside the csm_info dataset | [
"Save",
"info",
"about",
"the",
"composite",
"source",
"model",
"inside",
"the",
"csm_info",
"dataset"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L701-L730 | train | 232,911 |
gem/oq-engine | openquake/calculators/base.py | RiskCalculator.read_shakemap | def read_shakemap(self, haz_sitecol, assetcol):
"""
Enabled only if there is a shakemap_id parameter in the job.ini.
Download, unzip, parse USGS shakemap files and build a corresponding
set of GMFs which are then filtered with the hazard site collection
and stored in the datastore.
"""
oq = self.oqparam
E = oq.number_of_ground_motion_fields
oq.risk_imtls = oq.imtls or self.datastore.parent['oqparam'].imtls
extra = self.riskmodel.get_extra_imts(oq.risk_imtls)
if extra:
logging.warning('There are risk functions for not available IMTs '
'which will be ignored: %s' % extra)
logging.info('Getting/reducing shakemap')
with self.monitor('getting/reducing shakemap'):
smap = oq.shakemap_id if oq.shakemap_id else numpy.load(
oq.inputs['shakemap'])
sitecol, shakemap, discarded = get_sitecol_shakemap(
smap, oq.imtls, haz_sitecol,
oq.asset_hazard_distance['default'],
oq.discard_assets)
if len(discarded):
self.datastore['discarded'] = discarded
assetcol = assetcol.reduce_also(sitecol)
logging.info('Building GMFs')
with self.monitor('building/saving GMFs'):
imts, gmfs = to_gmfs(
shakemap, oq.spatial_correlation, oq.cross_correlation,
oq.site_effects, oq.truncation_level, E, oq.random_seed,
oq.imtls)
save_gmf_data(self.datastore, sitecol, gmfs, imts)
return sitecol, assetcol | python | def read_shakemap(self, haz_sitecol, assetcol):
"""
Enabled only if there is a shakemap_id parameter in the job.ini.
Download, unzip, parse USGS shakemap files and build a corresponding
set of GMFs which are then filtered with the hazard site collection
and stored in the datastore.
"""
oq = self.oqparam
E = oq.number_of_ground_motion_fields
oq.risk_imtls = oq.imtls or self.datastore.parent['oqparam'].imtls
extra = self.riskmodel.get_extra_imts(oq.risk_imtls)
if extra:
logging.warning('There are risk functions for not available IMTs '
'which will be ignored: %s' % extra)
logging.info('Getting/reducing shakemap')
with self.monitor('getting/reducing shakemap'):
smap = oq.shakemap_id if oq.shakemap_id else numpy.load(
oq.inputs['shakemap'])
sitecol, shakemap, discarded = get_sitecol_shakemap(
smap, oq.imtls, haz_sitecol,
oq.asset_hazard_distance['default'],
oq.discard_assets)
if len(discarded):
self.datastore['discarded'] = discarded
assetcol = assetcol.reduce_also(sitecol)
logging.info('Building GMFs')
with self.monitor('building/saving GMFs'):
imts, gmfs = to_gmfs(
shakemap, oq.spatial_correlation, oq.cross_correlation,
oq.site_effects, oq.truncation_level, E, oq.random_seed,
oq.imtls)
save_gmf_data(self.datastore, sitecol, gmfs, imts)
return sitecol, assetcol | [
"def",
"read_shakemap",
"(",
"self",
",",
"haz_sitecol",
",",
"assetcol",
")",
":",
"oq",
"=",
"self",
".",
"oqparam",
"E",
"=",
"oq",
".",
"number_of_ground_motion_fields",
"oq",
".",
"risk_imtls",
"=",
"oq",
".",
"imtls",
"or",
"self",
".",
"datastore",
".",
"parent",
"[",
"'oqparam'",
"]",
".",
"imtls",
"extra",
"=",
"self",
".",
"riskmodel",
".",
"get_extra_imts",
"(",
"oq",
".",
"risk_imtls",
")",
"if",
"extra",
":",
"logging",
".",
"warning",
"(",
"'There are risk functions for not available IMTs '",
"'which will be ignored: %s'",
"%",
"extra",
")",
"logging",
".",
"info",
"(",
"'Getting/reducing shakemap'",
")",
"with",
"self",
".",
"monitor",
"(",
"'getting/reducing shakemap'",
")",
":",
"smap",
"=",
"oq",
".",
"shakemap_id",
"if",
"oq",
".",
"shakemap_id",
"else",
"numpy",
".",
"load",
"(",
"oq",
".",
"inputs",
"[",
"'shakemap'",
"]",
")",
"sitecol",
",",
"shakemap",
",",
"discarded",
"=",
"get_sitecol_shakemap",
"(",
"smap",
",",
"oq",
".",
"imtls",
",",
"haz_sitecol",
",",
"oq",
".",
"asset_hazard_distance",
"[",
"'default'",
"]",
",",
"oq",
".",
"discard_assets",
")",
"if",
"len",
"(",
"discarded",
")",
":",
"self",
".",
"datastore",
"[",
"'discarded'",
"]",
"=",
"discarded",
"assetcol",
"=",
"assetcol",
".",
"reduce_also",
"(",
"sitecol",
")",
"logging",
".",
"info",
"(",
"'Building GMFs'",
")",
"with",
"self",
".",
"monitor",
"(",
"'building/saving GMFs'",
")",
":",
"imts",
",",
"gmfs",
"=",
"to_gmfs",
"(",
"shakemap",
",",
"oq",
".",
"spatial_correlation",
",",
"oq",
".",
"cross_correlation",
",",
"oq",
".",
"site_effects",
",",
"oq",
".",
"truncation_level",
",",
"E",
",",
"oq",
".",
"random_seed",
",",
"oq",
".",
"imtls",
")",
"save_gmf_data",
"(",
"self",
".",
"datastore",
",",
"sitecol",
",",
"gmfs",
",",
"imts",
")",
"return",
"sitecol",
",",
"assetcol"
] | Enabled only if there is a shakemap_id parameter in the job.ini.
Download, unzip, parse USGS shakemap files and build a corresponding
set of GMFs which are then filtered with the hazard site collection
and stored in the datastore. | [
"Enabled",
"only",
"if",
"there",
"is",
"a",
"shakemap_id",
"parameter",
"in",
"the",
"job",
".",
"ini",
".",
"Download",
"unzip",
"parse",
"USGS",
"shakemap",
"files",
"and",
"build",
"a",
"corresponding",
"set",
"of",
"GMFs",
"which",
"are",
"then",
"filtered",
"with",
"the",
"hazard",
"site",
"collection",
"and",
"stored",
"in",
"the",
"datastore",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L766-L800 | train | 232,912 |
gem/oq-engine | openquake/baselib/zeromq.py | bind | def bind(end_point, socket_type):
"""
Bind to a zmq URL; raise a proper error if the URL is invalid; return
a zmq socket.
"""
sock = context.socket(socket_type)
try:
sock.bind(end_point)
except zmq.error.ZMQError as exc:
sock.close()
raise exc.__class__('%s: %s' % (exc, end_point))
return sock | python | def bind(end_point, socket_type):
"""
Bind to a zmq URL; raise a proper error if the URL is invalid; return
a zmq socket.
"""
sock = context.socket(socket_type)
try:
sock.bind(end_point)
except zmq.error.ZMQError as exc:
sock.close()
raise exc.__class__('%s: %s' % (exc, end_point))
return sock | [
"def",
"bind",
"(",
"end_point",
",",
"socket_type",
")",
":",
"sock",
"=",
"context",
".",
"socket",
"(",
"socket_type",
")",
"try",
":",
"sock",
".",
"bind",
"(",
"end_point",
")",
"except",
"zmq",
".",
"error",
".",
"ZMQError",
"as",
"exc",
":",
"sock",
".",
"close",
"(",
")",
"raise",
"exc",
".",
"__class__",
"(",
"'%s: %s'",
"%",
"(",
"exc",
",",
"end_point",
")",
")",
"return",
"sock"
] | Bind to a zmq URL; raise a proper error if the URL is invalid; return
a zmq socket. | [
"Bind",
"to",
"a",
"zmq",
"URL",
";",
"raise",
"a",
"proper",
"error",
"if",
"the",
"URL",
"is",
"invalid",
";",
"return",
"a",
"zmq",
"socket",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/zeromq.py#L30-L41 | train | 232,913 |
gem/oq-engine | openquake/baselib/zeromq.py | Socket.send | def send(self, obj):
"""
Send an object to the remote server; block and return the reply
if the socket type is REQ.
:param obj:
the Python object to send
"""
self.zsocket.send_pyobj(obj)
self.num_sent += 1
if self.socket_type == zmq.REQ:
return self.zsocket.recv_pyobj() | python | def send(self, obj):
"""
Send an object to the remote server; block and return the reply
if the socket type is REQ.
:param obj:
the Python object to send
"""
self.zsocket.send_pyobj(obj)
self.num_sent += 1
if self.socket_type == zmq.REQ:
return self.zsocket.recv_pyobj() | [
"def",
"send",
"(",
"self",
",",
"obj",
")",
":",
"self",
".",
"zsocket",
".",
"send_pyobj",
"(",
"obj",
")",
"self",
".",
"num_sent",
"+=",
"1",
"if",
"self",
".",
"socket_type",
"==",
"zmq",
".",
"REQ",
":",
"return",
"self",
".",
"zsocket",
".",
"recv_pyobj",
"(",
")"
] | Send an object to the remote server; block and return the reply
if the socket type is REQ.
:param obj:
the Python object to send | [
"Send",
"an",
"object",
"to",
"the",
"remote",
"server",
";",
"block",
"and",
"return",
"the",
"reply",
"if",
"the",
"socket",
"type",
"is",
"REQ",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/zeromq.py#L139-L150 | train | 232,914 |
gem/oq-engine | openquake/hazardlib/geo/utils.py | angular_distance | def angular_distance(km, lat, lat2=None):
"""
Return the angular distance of two points at the given latitude.
>>> '%.3f' % angular_distance(100, lat=40)
'1.174'
>>> '%.3f' % angular_distance(100, lat=80)
'5.179'
"""
if lat2 is not None:
# use the largest latitude to compute the angular distance
lat = max(abs(lat), abs(lat2))
return km * KM_TO_DEGREES / math.cos(lat * DEGREES_TO_RAD) | python | def angular_distance(km, lat, lat2=None):
"""
Return the angular distance of two points at the given latitude.
>>> '%.3f' % angular_distance(100, lat=40)
'1.174'
>>> '%.3f' % angular_distance(100, lat=80)
'5.179'
"""
if lat2 is not None:
# use the largest latitude to compute the angular distance
lat = max(abs(lat), abs(lat2))
return km * KM_TO_DEGREES / math.cos(lat * DEGREES_TO_RAD) | [
"def",
"angular_distance",
"(",
"km",
",",
"lat",
",",
"lat2",
"=",
"None",
")",
":",
"if",
"lat2",
"is",
"not",
"None",
":",
"# use the largest latitude to compute the angular distance",
"lat",
"=",
"max",
"(",
"abs",
"(",
"lat",
")",
",",
"abs",
"(",
"lat2",
")",
")",
"return",
"km",
"*",
"KM_TO_DEGREES",
"/",
"math",
".",
"cos",
"(",
"lat",
"*",
"DEGREES_TO_RAD",
")"
] | Return the angular distance of two points at the given latitude.
>>> '%.3f' % angular_distance(100, lat=40)
'1.174'
>>> '%.3f' % angular_distance(100, lat=80)
'5.179' | [
"Return",
"the",
"angular",
"distance",
"of",
"two",
"points",
"at",
"the",
"given",
"latitude",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L45-L57 | train | 232,915 |
gem/oq-engine | openquake/hazardlib/geo/utils.py | assoc | def assoc(objects, sitecol, assoc_dist, mode, asset_refs=()):
"""
Associate geographic objects to a site collection.
:param objects:
something with .lons, .lats or ['lon'] ['lat'], or a list of lists
of objects with a .location attribute (i.e. assets_by_site)
:param assoc_dist:
the maximum distance for association
:param mode:
if 'strict' fail if at least one site is not associated
if 'error' fail if all sites are not associated
:returns: (filtered site collection, filtered objects)
"""
if isinstance(objects, numpy.ndarray) or hasattr(objects, 'lons'):
# objects is a geo array with lon, lat fields or a mesh-like instance
return _GeographicObjects(objects).assoc(sitecol, assoc_dist, mode)
else: # objects is the list assets_by_site
return _GeographicObjects(sitecol).assoc2(
objects, assoc_dist, mode, asset_refs) | python | def assoc(objects, sitecol, assoc_dist, mode, asset_refs=()):
"""
Associate geographic objects to a site collection.
:param objects:
something with .lons, .lats or ['lon'] ['lat'], or a list of lists
of objects with a .location attribute (i.e. assets_by_site)
:param assoc_dist:
the maximum distance for association
:param mode:
if 'strict' fail if at least one site is not associated
if 'error' fail if all sites are not associated
:returns: (filtered site collection, filtered objects)
"""
if isinstance(objects, numpy.ndarray) or hasattr(objects, 'lons'):
# objects is a geo array with lon, lat fields or a mesh-like instance
return _GeographicObjects(objects).assoc(sitecol, assoc_dist, mode)
else: # objects is the list assets_by_site
return _GeographicObjects(sitecol).assoc2(
objects, assoc_dist, mode, asset_refs) | [
"def",
"assoc",
"(",
"objects",
",",
"sitecol",
",",
"assoc_dist",
",",
"mode",
",",
"asset_refs",
"=",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"objects",
",",
"numpy",
".",
"ndarray",
")",
"or",
"hasattr",
"(",
"objects",
",",
"'lons'",
")",
":",
"# objects is a geo array with lon, lat fields or a mesh-like instance",
"return",
"_GeographicObjects",
"(",
"objects",
")",
".",
"assoc",
"(",
"sitecol",
",",
"assoc_dist",
",",
"mode",
")",
"else",
":",
"# objects is the list assets_by_site",
"return",
"_GeographicObjects",
"(",
"sitecol",
")",
".",
"assoc2",
"(",
"objects",
",",
"assoc_dist",
",",
"mode",
",",
"asset_refs",
")"
] | Associate geographic objects to a site collection.
:param objects:
something with .lons, .lats or ['lon'] ['lat'], or a list of lists
of objects with a .location attribute (i.e. assets_by_site)
:param assoc_dist:
the maximum distance for association
:param mode:
if 'strict' fail if at least one site is not associated
if 'error' fail if all sites are not associated
:returns: (filtered site collection, filtered objects) | [
"Associate",
"geographic",
"objects",
"to",
"a",
"site",
"collection",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L177-L196 | train | 232,916 |
gem/oq-engine | openquake/hazardlib/geo/utils.py | line_intersects_itself | def line_intersects_itself(lons, lats, closed_shape=False):
"""
Return ``True`` if line of points intersects itself.
Line with the last point repeating the first one considered
intersecting itself.
The line is defined by lists (or numpy arrays) of points'
longitudes and latitudes (depth is not taken into account).
:param closed_shape:
If ``True`` the line will be checked twice: first time with
its original shape and second time with the points sequence
being shifted by one point (the last point becomes first,
the first turns second and so on). This is useful for
checking that the sequence of points defines a valid
:class:`~openquake.hazardlib.geo.polygon.Polygon`.
"""
assert len(lons) == len(lats)
if len(lons) <= 3:
# line can not intersect itself unless there are
# at least four points
return False
west, east, north, south = get_spherical_bounding_box(lons, lats)
proj = OrthographicProjection(west, east, north, south)
xx, yy = proj(lons, lats)
if not shapely.geometry.LineString(list(zip(xx, yy))).is_simple:
return True
if closed_shape:
xx, yy = proj(numpy.roll(lons, 1), numpy.roll(lats, 1))
if not shapely.geometry.LineString(list(zip(xx, yy))).is_simple:
return True
return False | python | def line_intersects_itself(lons, lats, closed_shape=False):
"""
Return ``True`` if line of points intersects itself.
Line with the last point repeating the first one considered
intersecting itself.
The line is defined by lists (or numpy arrays) of points'
longitudes and latitudes (depth is not taken into account).
:param closed_shape:
If ``True`` the line will be checked twice: first time with
its original shape and second time with the points sequence
being shifted by one point (the last point becomes first,
the first turns second and so on). This is useful for
checking that the sequence of points defines a valid
:class:`~openquake.hazardlib.geo.polygon.Polygon`.
"""
assert len(lons) == len(lats)
if len(lons) <= 3:
# line can not intersect itself unless there are
# at least four points
return False
west, east, north, south = get_spherical_bounding_box(lons, lats)
proj = OrthographicProjection(west, east, north, south)
xx, yy = proj(lons, lats)
if not shapely.geometry.LineString(list(zip(xx, yy))).is_simple:
return True
if closed_shape:
xx, yy = proj(numpy.roll(lons, 1), numpy.roll(lats, 1))
if not shapely.geometry.LineString(list(zip(xx, yy))).is_simple:
return True
return False | [
"def",
"line_intersects_itself",
"(",
"lons",
",",
"lats",
",",
"closed_shape",
"=",
"False",
")",
":",
"assert",
"len",
"(",
"lons",
")",
"==",
"len",
"(",
"lats",
")",
"if",
"len",
"(",
"lons",
")",
"<=",
"3",
":",
"# line can not intersect itself unless there are",
"# at least four points",
"return",
"False",
"west",
",",
"east",
",",
"north",
",",
"south",
"=",
"get_spherical_bounding_box",
"(",
"lons",
",",
"lats",
")",
"proj",
"=",
"OrthographicProjection",
"(",
"west",
",",
"east",
",",
"north",
",",
"south",
")",
"xx",
",",
"yy",
"=",
"proj",
"(",
"lons",
",",
"lats",
")",
"if",
"not",
"shapely",
".",
"geometry",
".",
"LineString",
"(",
"list",
"(",
"zip",
"(",
"xx",
",",
"yy",
")",
")",
")",
".",
"is_simple",
":",
"return",
"True",
"if",
"closed_shape",
":",
"xx",
",",
"yy",
"=",
"proj",
"(",
"numpy",
".",
"roll",
"(",
"lons",
",",
"1",
")",
",",
"numpy",
".",
"roll",
"(",
"lats",
",",
"1",
")",
")",
"if",
"not",
"shapely",
".",
"geometry",
".",
"LineString",
"(",
"list",
"(",
"zip",
"(",
"xx",
",",
"yy",
")",
")",
")",
".",
"is_simple",
":",
"return",
"True",
"return",
"False"
] | Return ``True`` if line of points intersects itself.
Line with the last point repeating the first one considered
intersecting itself.
The line is defined by lists (or numpy arrays) of points'
longitudes and latitudes (depth is not taken into account).
:param closed_shape:
If ``True`` the line will be checked twice: first time with
its original shape and second time with the points sequence
being shifted by one point (the last point becomes first,
the first turns second and so on). This is useful for
checking that the sequence of points defines a valid
:class:`~openquake.hazardlib.geo.polygon.Polygon`. | [
"Return",
"True",
"if",
"line",
"of",
"points",
"intersects",
"itself",
".",
"Line",
"with",
"the",
"last",
"point",
"repeating",
"the",
"first",
"one",
"considered",
"intersecting",
"itself",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L214-L250 | train | 232,917 |
gem/oq-engine | openquake/hazardlib/geo/utils.py | get_bounding_box | def get_bounding_box(obj, maxdist):
"""
Return the dilated bounding box of a geometric object.
:param obj:
an object with method .get_bounding_box, or with an attribute .polygon
or a list of locations
:param maxdist: maximum distance in km
"""
if hasattr(obj, 'get_bounding_box'):
return obj.get_bounding_box(maxdist)
elif hasattr(obj, 'polygon'):
bbox = obj.polygon.get_bbox()
else:
if isinstance(obj, list): # a list of locations
lons = numpy.array([loc.longitude for loc in obj])
lats = numpy.array([loc.latitude for loc in obj])
else: # assume an array with fields lon, lat
lons, lats = obj['lon'], obj['lat']
min_lon, max_lon = lons.min(), lons.max()
if cross_idl(min_lon, max_lon):
lons %= 360
bbox = lons.min(), lats.min(), lons.max(), lats.max()
a1 = min(maxdist * KM_TO_DEGREES, 90)
a2 = min(angular_distance(maxdist, bbox[1], bbox[3]), 180)
return bbox[0] - a2, bbox[1] - a1, bbox[2] + a2, bbox[3] + a1 | python | def get_bounding_box(obj, maxdist):
"""
Return the dilated bounding box of a geometric object.
:param obj:
an object with method .get_bounding_box, or with an attribute .polygon
or a list of locations
:param maxdist: maximum distance in km
"""
if hasattr(obj, 'get_bounding_box'):
return obj.get_bounding_box(maxdist)
elif hasattr(obj, 'polygon'):
bbox = obj.polygon.get_bbox()
else:
if isinstance(obj, list): # a list of locations
lons = numpy.array([loc.longitude for loc in obj])
lats = numpy.array([loc.latitude for loc in obj])
else: # assume an array with fields lon, lat
lons, lats = obj['lon'], obj['lat']
min_lon, max_lon = lons.min(), lons.max()
if cross_idl(min_lon, max_lon):
lons %= 360
bbox = lons.min(), lats.min(), lons.max(), lats.max()
a1 = min(maxdist * KM_TO_DEGREES, 90)
a2 = min(angular_distance(maxdist, bbox[1], bbox[3]), 180)
return bbox[0] - a2, bbox[1] - a1, bbox[2] + a2, bbox[3] + a1 | [
"def",
"get_bounding_box",
"(",
"obj",
",",
"maxdist",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'get_bounding_box'",
")",
":",
"return",
"obj",
".",
"get_bounding_box",
"(",
"maxdist",
")",
"elif",
"hasattr",
"(",
"obj",
",",
"'polygon'",
")",
":",
"bbox",
"=",
"obj",
".",
"polygon",
".",
"get_bbox",
"(",
")",
"else",
":",
"if",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"# a list of locations",
"lons",
"=",
"numpy",
".",
"array",
"(",
"[",
"loc",
".",
"longitude",
"for",
"loc",
"in",
"obj",
"]",
")",
"lats",
"=",
"numpy",
".",
"array",
"(",
"[",
"loc",
".",
"latitude",
"for",
"loc",
"in",
"obj",
"]",
")",
"else",
":",
"# assume an array with fields lon, lat",
"lons",
",",
"lats",
"=",
"obj",
"[",
"'lon'",
"]",
",",
"obj",
"[",
"'lat'",
"]",
"min_lon",
",",
"max_lon",
"=",
"lons",
".",
"min",
"(",
")",
",",
"lons",
".",
"max",
"(",
")",
"if",
"cross_idl",
"(",
"min_lon",
",",
"max_lon",
")",
":",
"lons",
"%=",
"360",
"bbox",
"=",
"lons",
".",
"min",
"(",
")",
",",
"lats",
".",
"min",
"(",
")",
",",
"lons",
".",
"max",
"(",
")",
",",
"lats",
".",
"max",
"(",
")",
"a1",
"=",
"min",
"(",
"maxdist",
"*",
"KM_TO_DEGREES",
",",
"90",
")",
"a2",
"=",
"min",
"(",
"angular_distance",
"(",
"maxdist",
",",
"bbox",
"[",
"1",
"]",
",",
"bbox",
"[",
"3",
"]",
")",
",",
"180",
")",
"return",
"bbox",
"[",
"0",
"]",
"-",
"a2",
",",
"bbox",
"[",
"1",
"]",
"-",
"a1",
",",
"bbox",
"[",
"2",
"]",
"+",
"a2",
",",
"bbox",
"[",
"3",
"]",
"+",
"a1"
] | Return the dilated bounding box of a geometric object.
:param obj:
an object with method .get_bounding_box, or with an attribute .polygon
or a list of locations
:param maxdist: maximum distance in km | [
"Return",
"the",
"dilated",
"bounding",
"box",
"of",
"a",
"geometric",
"object",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L267-L292 | train | 232,918 |
gem/oq-engine | openquake/hazardlib/geo/utils.py | get_spherical_bounding_box | def get_spherical_bounding_box(lons, lats):
"""
Given a collection of points find and return the bounding box,
as a pair of longitudes and a pair of latitudes.
Parameters define longitudes and latitudes of a point collection
respectively in a form of lists or numpy arrays.
:return:
A tuple of four items. These items represent western, eastern,
northern and southern borders of the bounding box respectively.
Values are floats in decimal degrees.
:raises ValueError:
If points collection has the longitudinal extent of more than
180 degrees (it is impossible to define a single hemisphere
bound to poles that would contain the whole collection).
"""
north, south = numpy.max(lats), numpy.min(lats)
west, east = numpy.min(lons), numpy.max(lons)
assert (-180 <= west <= 180) and (-180 <= east <= 180), (west, east)
if get_longitudinal_extent(west, east) < 0:
# points are lying on both sides of the international date line
# (meridian 180). the actual west longitude is the lowest positive
# longitude and east one is the highest negative.
if hasattr(lons, 'flatten'):
# fixes test_surface_crossing_international_date_line
lons = lons.flatten()
west = min(lon for lon in lons if lon > 0)
east = max(lon for lon in lons if lon < 0)
if not all((get_longitudinal_extent(west, lon) >= 0
and get_longitudinal_extent(lon, east) >= 0)
for lon in lons):
raise ValueError('points collection has longitudinal extent '
'wider than 180 deg')
return SphericalBB(west, east, north, south) | python | def get_spherical_bounding_box(lons, lats):
"""
Given a collection of points find and return the bounding box,
as a pair of longitudes and a pair of latitudes.
Parameters define longitudes and latitudes of a point collection
respectively in a form of lists or numpy arrays.
:return:
A tuple of four items. These items represent western, eastern,
northern and southern borders of the bounding box respectively.
Values are floats in decimal degrees.
:raises ValueError:
If points collection has the longitudinal extent of more than
180 degrees (it is impossible to define a single hemisphere
bound to poles that would contain the whole collection).
"""
north, south = numpy.max(lats), numpy.min(lats)
west, east = numpy.min(lons), numpy.max(lons)
assert (-180 <= west <= 180) and (-180 <= east <= 180), (west, east)
if get_longitudinal_extent(west, east) < 0:
# points are lying on both sides of the international date line
# (meridian 180). the actual west longitude is the lowest positive
# longitude and east one is the highest negative.
if hasattr(lons, 'flatten'):
# fixes test_surface_crossing_international_date_line
lons = lons.flatten()
west = min(lon for lon in lons if lon > 0)
east = max(lon for lon in lons if lon < 0)
if not all((get_longitudinal_extent(west, lon) >= 0
and get_longitudinal_extent(lon, east) >= 0)
for lon in lons):
raise ValueError('points collection has longitudinal extent '
'wider than 180 deg')
return SphericalBB(west, east, north, south) | [
"def",
"get_spherical_bounding_box",
"(",
"lons",
",",
"lats",
")",
":",
"north",
",",
"south",
"=",
"numpy",
".",
"max",
"(",
"lats",
")",
",",
"numpy",
".",
"min",
"(",
"lats",
")",
"west",
",",
"east",
"=",
"numpy",
".",
"min",
"(",
"lons",
")",
",",
"numpy",
".",
"max",
"(",
"lons",
")",
"assert",
"(",
"-",
"180",
"<=",
"west",
"<=",
"180",
")",
"and",
"(",
"-",
"180",
"<=",
"east",
"<=",
"180",
")",
",",
"(",
"west",
",",
"east",
")",
"if",
"get_longitudinal_extent",
"(",
"west",
",",
"east",
")",
"<",
"0",
":",
"# points are lying on both sides of the international date line",
"# (meridian 180). the actual west longitude is the lowest positive",
"# longitude and east one is the highest negative.",
"if",
"hasattr",
"(",
"lons",
",",
"'flatten'",
")",
":",
"# fixes test_surface_crossing_international_date_line",
"lons",
"=",
"lons",
".",
"flatten",
"(",
")",
"west",
"=",
"min",
"(",
"lon",
"for",
"lon",
"in",
"lons",
"if",
"lon",
">",
"0",
")",
"east",
"=",
"max",
"(",
"lon",
"for",
"lon",
"in",
"lons",
"if",
"lon",
"<",
"0",
")",
"if",
"not",
"all",
"(",
"(",
"get_longitudinal_extent",
"(",
"west",
",",
"lon",
")",
">=",
"0",
"and",
"get_longitudinal_extent",
"(",
"lon",
",",
"east",
")",
">=",
"0",
")",
"for",
"lon",
"in",
"lons",
")",
":",
"raise",
"ValueError",
"(",
"'points collection has longitudinal extent '",
"'wider than 180 deg'",
")",
"return",
"SphericalBB",
"(",
"west",
",",
"east",
",",
"north",
",",
"south",
")"
] | Given a collection of points find and return the bounding box,
as a pair of longitudes and a pair of latitudes.
Parameters define longitudes and latitudes of a point collection
respectively in a form of lists or numpy arrays.
:return:
A tuple of four items. These items represent western, eastern,
northern and southern borders of the bounding box respectively.
Values are floats in decimal degrees.
:raises ValueError:
If points collection has the longitudinal extent of more than
180 degrees (it is impossible to define a single hemisphere
bound to poles that would contain the whole collection). | [
"Given",
"a",
"collection",
"of",
"points",
"find",
"and",
"return",
"the",
"bounding",
"box",
"as",
"a",
"pair",
"of",
"longitudes",
"and",
"a",
"pair",
"of",
"latitudes",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L295-L329 | train | 232,919 |
gem/oq-engine | openquake/hazardlib/geo/utils.py | get_middle_point | def get_middle_point(lon1, lat1, lon2, lat2):
"""
Given two points return the point exactly in the middle lying on the same
great circle arc.
Parameters are point coordinates in degrees.
:returns:
Tuple of longitude and latitude of the point in the middle.
"""
if lon1 == lon2 and lat1 == lat2:
return lon1, lat1
dist = geodetic.geodetic_distance(lon1, lat1, lon2, lat2)
azimuth = geodetic.azimuth(lon1, lat1, lon2, lat2)
return geodetic.point_at(lon1, lat1, azimuth, dist / 2.0) | python | def get_middle_point(lon1, lat1, lon2, lat2):
"""
Given two points return the point exactly in the middle lying on the same
great circle arc.
Parameters are point coordinates in degrees.
:returns:
Tuple of longitude and latitude of the point in the middle.
"""
if lon1 == lon2 and lat1 == lat2:
return lon1, lat1
dist = geodetic.geodetic_distance(lon1, lat1, lon2, lat2)
azimuth = geodetic.azimuth(lon1, lat1, lon2, lat2)
return geodetic.point_at(lon1, lat1, azimuth, dist / 2.0) | [
"def",
"get_middle_point",
"(",
"lon1",
",",
"lat1",
",",
"lon2",
",",
"lat2",
")",
":",
"if",
"lon1",
"==",
"lon2",
"and",
"lat1",
"==",
"lat2",
":",
"return",
"lon1",
",",
"lat1",
"dist",
"=",
"geodetic",
".",
"geodetic_distance",
"(",
"lon1",
",",
"lat1",
",",
"lon2",
",",
"lat2",
")",
"azimuth",
"=",
"geodetic",
".",
"azimuth",
"(",
"lon1",
",",
"lat1",
",",
"lon2",
",",
"lat2",
")",
"return",
"geodetic",
".",
"point_at",
"(",
"lon1",
",",
"lat1",
",",
"azimuth",
",",
"dist",
"/",
"2.0",
")"
] | Given two points return the point exactly in the middle lying on the same
great circle arc.
Parameters are point coordinates in degrees.
:returns:
Tuple of longitude and latitude of the point in the middle. | [
"Given",
"two",
"points",
"return",
"the",
"point",
"exactly",
"in",
"the",
"middle",
"lying",
"on",
"the",
"same",
"great",
"circle",
"arc",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L428-L442 | train | 232,920 |
gem/oq-engine | openquake/hazardlib/geo/utils.py | cartesian_to_spherical | def cartesian_to_spherical(vectors):
"""
Return the spherical coordinates for coordinates in Cartesian space.
This function does an opposite to :func:`spherical_to_cartesian`.
:param vectors:
Array of 3d vectors in Cartesian space of shape (..., 3)
:returns:
Tuple of three arrays of the same shape as ``vectors`` representing
longitude (decimal degrees), latitude (decimal degrees) and depth (km)
in specified order.
"""
rr = numpy.sqrt(numpy.sum(vectors * vectors, axis=-1))
xx, yy, zz = vectors.T
lats = numpy.degrees(numpy.arcsin((zz / rr).clip(-1., 1.)))
lons = numpy.degrees(numpy.arctan2(yy, xx))
depths = EARTH_RADIUS - rr
return lons.T, lats.T, depths | python | def cartesian_to_spherical(vectors):
"""
Return the spherical coordinates for coordinates in Cartesian space.
This function does an opposite to :func:`spherical_to_cartesian`.
:param vectors:
Array of 3d vectors in Cartesian space of shape (..., 3)
:returns:
Tuple of three arrays of the same shape as ``vectors`` representing
longitude (decimal degrees), latitude (decimal degrees) and depth (km)
in specified order.
"""
rr = numpy.sqrt(numpy.sum(vectors * vectors, axis=-1))
xx, yy, zz = vectors.T
lats = numpy.degrees(numpy.arcsin((zz / rr).clip(-1., 1.)))
lons = numpy.degrees(numpy.arctan2(yy, xx))
depths = EARTH_RADIUS - rr
return lons.T, lats.T, depths | [
"def",
"cartesian_to_spherical",
"(",
"vectors",
")",
":",
"rr",
"=",
"numpy",
".",
"sqrt",
"(",
"numpy",
".",
"sum",
"(",
"vectors",
"*",
"vectors",
",",
"axis",
"=",
"-",
"1",
")",
")",
"xx",
",",
"yy",
",",
"zz",
"=",
"vectors",
".",
"T",
"lats",
"=",
"numpy",
".",
"degrees",
"(",
"numpy",
".",
"arcsin",
"(",
"(",
"zz",
"/",
"rr",
")",
".",
"clip",
"(",
"-",
"1.",
",",
"1.",
")",
")",
")",
"lons",
"=",
"numpy",
".",
"degrees",
"(",
"numpy",
".",
"arctan2",
"(",
"yy",
",",
"xx",
")",
")",
"depths",
"=",
"EARTH_RADIUS",
"-",
"rr",
"return",
"lons",
".",
"T",
",",
"lats",
".",
"T",
",",
"depths"
] | Return the spherical coordinates for coordinates in Cartesian space.
This function does an opposite to :func:`spherical_to_cartesian`.
:param vectors:
Array of 3d vectors in Cartesian space of shape (..., 3)
:returns:
Tuple of three arrays of the same shape as ``vectors`` representing
longitude (decimal degrees), latitude (decimal degrees) and depth (km)
in specified order. | [
"Return",
"the",
"spherical",
"coordinates",
"for",
"coordinates",
"in",
"Cartesian",
"space",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L445-L463 | train | 232,921 |
gem/oq-engine | openquake/hazardlib/geo/utils.py | triangle_area | def triangle_area(e1, e2, e3):
"""
Get the area of triangle formed by three vectors.
Parameters are three three-dimensional numpy arrays representing
vectors of triangle's edges in Cartesian space.
:returns:
Float number, the area of the triangle in squared units of coordinates,
or numpy array of shape of edges with one dimension less.
Uses Heron formula, see http://mathworld.wolfram.com/HeronsFormula.html.
"""
# calculating edges length
e1_length = numpy.sqrt(numpy.sum(e1 * e1, axis=-1))
e2_length = numpy.sqrt(numpy.sum(e2 * e2, axis=-1))
e3_length = numpy.sqrt(numpy.sum(e3 * e3, axis=-1))
# calculating half perimeter
s = (e1_length + e2_length + e3_length) / 2.0
# applying Heron's formula
return numpy.sqrt(s * (s - e1_length) * (s - e2_length) * (s - e3_length)) | python | def triangle_area(e1, e2, e3):
"""
Get the area of triangle formed by three vectors.
Parameters are three three-dimensional numpy arrays representing
vectors of triangle's edges in Cartesian space.
:returns:
Float number, the area of the triangle in squared units of coordinates,
or numpy array of shape of edges with one dimension less.
Uses Heron formula, see http://mathworld.wolfram.com/HeronsFormula.html.
"""
# calculating edges length
e1_length = numpy.sqrt(numpy.sum(e1 * e1, axis=-1))
e2_length = numpy.sqrt(numpy.sum(e2 * e2, axis=-1))
e3_length = numpy.sqrt(numpy.sum(e3 * e3, axis=-1))
# calculating half perimeter
s = (e1_length + e2_length + e3_length) / 2.0
# applying Heron's formula
return numpy.sqrt(s * (s - e1_length) * (s - e2_length) * (s - e3_length)) | [
"def",
"triangle_area",
"(",
"e1",
",",
"e2",
",",
"e3",
")",
":",
"# calculating edges length",
"e1_length",
"=",
"numpy",
".",
"sqrt",
"(",
"numpy",
".",
"sum",
"(",
"e1",
"*",
"e1",
",",
"axis",
"=",
"-",
"1",
")",
")",
"e2_length",
"=",
"numpy",
".",
"sqrt",
"(",
"numpy",
".",
"sum",
"(",
"e2",
"*",
"e2",
",",
"axis",
"=",
"-",
"1",
")",
")",
"e3_length",
"=",
"numpy",
".",
"sqrt",
"(",
"numpy",
".",
"sum",
"(",
"e3",
"*",
"e3",
",",
"axis",
"=",
"-",
"1",
")",
")",
"# calculating half perimeter",
"s",
"=",
"(",
"e1_length",
"+",
"e2_length",
"+",
"e3_length",
")",
"/",
"2.0",
"# applying Heron's formula",
"return",
"numpy",
".",
"sqrt",
"(",
"s",
"*",
"(",
"s",
"-",
"e1_length",
")",
"*",
"(",
"s",
"-",
"e2_length",
")",
"*",
"(",
"s",
"-",
"e3_length",
")",
")"
] | Get the area of triangle formed by three vectors.
Parameters are three three-dimensional numpy arrays representing
vectors of triangle's edges in Cartesian space.
:returns:
Float number, the area of the triangle in squared units of coordinates,
or numpy array of shape of edges with one dimension less.
Uses Heron formula, see http://mathworld.wolfram.com/HeronsFormula.html. | [
"Get",
"the",
"area",
"of",
"triangle",
"formed",
"by",
"three",
"vectors",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L466-L486 | train | 232,922 |
gem/oq-engine | openquake/hazardlib/geo/utils.py | normalized | def normalized(vector):
"""
Get unit vector for a given one.
:param vector:
Numpy vector as coordinates in Cartesian space, or an array of such.
:returns:
Numpy array of the same shape and structure where all vectors are
normalized. That is, each coordinate component is divided by its
vector's length.
"""
length = numpy.sum(vector * vector, axis=-1)
length = numpy.sqrt(length.reshape(length.shape + (1, )))
return vector / length | python | def normalized(vector):
"""
Get unit vector for a given one.
:param vector:
Numpy vector as coordinates in Cartesian space, or an array of such.
:returns:
Numpy array of the same shape and structure where all vectors are
normalized. That is, each coordinate component is divided by its
vector's length.
"""
length = numpy.sum(vector * vector, axis=-1)
length = numpy.sqrt(length.reshape(length.shape + (1, )))
return vector / length | [
"def",
"normalized",
"(",
"vector",
")",
":",
"length",
"=",
"numpy",
".",
"sum",
"(",
"vector",
"*",
"vector",
",",
"axis",
"=",
"-",
"1",
")",
"length",
"=",
"numpy",
".",
"sqrt",
"(",
"length",
".",
"reshape",
"(",
"length",
".",
"shape",
"+",
"(",
"1",
",",
")",
")",
")",
"return",
"vector",
"/",
"length"
] | Get unit vector for a given one.
:param vector:
Numpy vector as coordinates in Cartesian space, or an array of such.
:returns:
Numpy array of the same shape and structure where all vectors are
normalized. That is, each coordinate component is divided by its
vector's length. | [
"Get",
"unit",
"vector",
"for",
"a",
"given",
"one",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L489-L502 | train | 232,923 |
gem/oq-engine | openquake/hazardlib/geo/utils.py | point_to_polygon_distance | def point_to_polygon_distance(polygon, pxx, pyy):
"""
Calculate the distance to polygon for each point of the collection
on the 2d Cartesian plane.
:param polygon:
Shapely "Polygon" geometry object.
:param pxx:
List or numpy array of abscissae values of points to calculate
the distance from.
:param pyy:
Same structure as ``pxx``, but with ordinate values.
:returns:
Numpy array of distances in units of coordinate system. Points
that lie inside the polygon have zero distance.
"""
pxx = numpy.array(pxx)
pyy = numpy.array(pyy)
assert pxx.shape == pyy.shape
if pxx.ndim == 0:
pxx = pxx.reshape((1, ))
pyy = pyy.reshape((1, ))
result = numpy.array([
polygon.distance(shapely.geometry.Point(pxx.item(i), pyy.item(i)))
for i in range(pxx.size)
])
return result.reshape(pxx.shape) | python | def point_to_polygon_distance(polygon, pxx, pyy):
"""
Calculate the distance to polygon for each point of the collection
on the 2d Cartesian plane.
:param polygon:
Shapely "Polygon" geometry object.
:param pxx:
List or numpy array of abscissae values of points to calculate
the distance from.
:param pyy:
Same structure as ``pxx``, but with ordinate values.
:returns:
Numpy array of distances in units of coordinate system. Points
that lie inside the polygon have zero distance.
"""
pxx = numpy.array(pxx)
pyy = numpy.array(pyy)
assert pxx.shape == pyy.shape
if pxx.ndim == 0:
pxx = pxx.reshape((1, ))
pyy = pyy.reshape((1, ))
result = numpy.array([
polygon.distance(shapely.geometry.Point(pxx.item(i), pyy.item(i)))
for i in range(pxx.size)
])
return result.reshape(pxx.shape) | [
"def",
"point_to_polygon_distance",
"(",
"polygon",
",",
"pxx",
",",
"pyy",
")",
":",
"pxx",
"=",
"numpy",
".",
"array",
"(",
"pxx",
")",
"pyy",
"=",
"numpy",
".",
"array",
"(",
"pyy",
")",
"assert",
"pxx",
".",
"shape",
"==",
"pyy",
".",
"shape",
"if",
"pxx",
".",
"ndim",
"==",
"0",
":",
"pxx",
"=",
"pxx",
".",
"reshape",
"(",
"(",
"1",
",",
")",
")",
"pyy",
"=",
"pyy",
".",
"reshape",
"(",
"(",
"1",
",",
")",
")",
"result",
"=",
"numpy",
".",
"array",
"(",
"[",
"polygon",
".",
"distance",
"(",
"shapely",
".",
"geometry",
".",
"Point",
"(",
"pxx",
".",
"item",
"(",
"i",
")",
",",
"pyy",
".",
"item",
"(",
"i",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"pxx",
".",
"size",
")",
"]",
")",
"return",
"result",
".",
"reshape",
"(",
"pxx",
".",
"shape",
")"
] | Calculate the distance to polygon for each point of the collection
on the 2d Cartesian plane.
:param polygon:
Shapely "Polygon" geometry object.
:param pxx:
List or numpy array of abscissae values of points to calculate
the distance from.
:param pyy:
Same structure as ``pxx``, but with ordinate values.
:returns:
Numpy array of distances in units of coordinate system. Points
that lie inside the polygon have zero distance. | [
"Calculate",
"the",
"distance",
"to",
"polygon",
"for",
"each",
"point",
"of",
"the",
"collection",
"on",
"the",
"2d",
"Cartesian",
"plane",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L505-L531 | train | 232,924 |
gem/oq-engine | openquake/hazardlib/geo/utils.py | cross_idl | def cross_idl(lon1, lon2, *lons):
"""
Return True if two longitude values define line crossing international date
line.
>>> cross_idl(-45, 45)
False
>>> cross_idl(-180, -179)
False
>>> cross_idl(180, 179)
False
>>> cross_idl(45, -45)
False
>>> cross_idl(0, 0)
False
>>> cross_idl(-170, 170)
True
>>> cross_idl(170, -170)
True
>>> cross_idl(-180, 180)
True
"""
lons = (lon1, lon2) + lons
l1, l2 = min(lons), max(lons)
# a line crosses the international date line if the end positions
# have different sign and they are more than 180 degrees longitude apart
return l1 * l2 < 0 and abs(l1 - l2) > 180 | python | def cross_idl(lon1, lon2, *lons):
"""
Return True if two longitude values define line crossing international date
line.
>>> cross_idl(-45, 45)
False
>>> cross_idl(-180, -179)
False
>>> cross_idl(180, 179)
False
>>> cross_idl(45, -45)
False
>>> cross_idl(0, 0)
False
>>> cross_idl(-170, 170)
True
>>> cross_idl(170, -170)
True
>>> cross_idl(-180, 180)
True
"""
lons = (lon1, lon2) + lons
l1, l2 = min(lons), max(lons)
# a line crosses the international date line if the end positions
# have different sign and they are more than 180 degrees longitude apart
return l1 * l2 < 0 and abs(l1 - l2) > 180 | [
"def",
"cross_idl",
"(",
"lon1",
",",
"lon2",
",",
"*",
"lons",
")",
":",
"lons",
"=",
"(",
"lon1",
",",
"lon2",
")",
"+",
"lons",
"l1",
",",
"l2",
"=",
"min",
"(",
"lons",
")",
",",
"max",
"(",
"lons",
")",
"# a line crosses the international date line if the end positions",
"# have different sign and they are more than 180 degrees longitude apart",
"return",
"l1",
"*",
"l2",
"<",
"0",
"and",
"abs",
"(",
"l1",
"-",
"l2",
")",
">",
"180"
] | Return True if two longitude values define line crossing international date
line.
>>> cross_idl(-45, 45)
False
>>> cross_idl(-180, -179)
False
>>> cross_idl(180, 179)
False
>>> cross_idl(45, -45)
False
>>> cross_idl(0, 0)
False
>>> cross_idl(-170, 170)
True
>>> cross_idl(170, -170)
True
>>> cross_idl(-180, 180)
True | [
"Return",
"True",
"if",
"two",
"longitude",
"values",
"define",
"line",
"crossing",
"international",
"date",
"line",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L548-L574 | train | 232,925 |
gem/oq-engine | openquake/hazardlib/geo/utils.py | normalize_lons | def normalize_lons(l1, l2):
"""
An international date line safe way of returning a range of longitudes.
>>> normalize_lons(20, 30) # no IDL within the range
[(20, 30)]
>>> normalize_lons(-17, +17) # no IDL within the range
[(-17, 17)]
>>> normalize_lons(-178, +179)
[(-180, -178), (179, 180)]
>>> normalize_lons(178, -179)
[(-180, -179), (178, 180)]
>>> normalize_lons(179, -179)
[(-180, -179), (179, 180)]
>>> normalize_lons(177, -176)
[(-180, -176), (177, 180)]
"""
if l1 > l2: # exchange lons
l1, l2 = l2, l1
delta = l2 - l1
if l1 < 0 and l2 > 0 and delta > 180:
return [(-180, l1), (l2, 180)]
elif l1 > 0 and l2 > 180 and delta < 180:
return [(l1, 180), (-180, l2 - 360)]
elif l1 < -180 and l2 < 0 and delta < 180:
return [(l1 + 360, 180), (l2, -180)]
return [(l1, l2)] | python | def normalize_lons(l1, l2):
"""
An international date line safe way of returning a range of longitudes.
>>> normalize_lons(20, 30) # no IDL within the range
[(20, 30)]
>>> normalize_lons(-17, +17) # no IDL within the range
[(-17, 17)]
>>> normalize_lons(-178, +179)
[(-180, -178), (179, 180)]
>>> normalize_lons(178, -179)
[(-180, -179), (178, 180)]
>>> normalize_lons(179, -179)
[(-180, -179), (179, 180)]
>>> normalize_lons(177, -176)
[(-180, -176), (177, 180)]
"""
if l1 > l2: # exchange lons
l1, l2 = l2, l1
delta = l2 - l1
if l1 < 0 and l2 > 0 and delta > 180:
return [(-180, l1), (l2, 180)]
elif l1 > 0 and l2 > 180 and delta < 180:
return [(l1, 180), (-180, l2 - 360)]
elif l1 < -180 and l2 < 0 and delta < 180:
return [(l1 + 360, 180), (l2, -180)]
return [(l1, l2)] | [
"def",
"normalize_lons",
"(",
"l1",
",",
"l2",
")",
":",
"if",
"l1",
">",
"l2",
":",
"# exchange lons",
"l1",
",",
"l2",
"=",
"l2",
",",
"l1",
"delta",
"=",
"l2",
"-",
"l1",
"if",
"l1",
"<",
"0",
"and",
"l2",
">",
"0",
"and",
"delta",
">",
"180",
":",
"return",
"[",
"(",
"-",
"180",
",",
"l1",
")",
",",
"(",
"l2",
",",
"180",
")",
"]",
"elif",
"l1",
">",
"0",
"and",
"l2",
">",
"180",
"and",
"delta",
"<",
"180",
":",
"return",
"[",
"(",
"l1",
",",
"180",
")",
",",
"(",
"-",
"180",
",",
"l2",
"-",
"360",
")",
"]",
"elif",
"l1",
"<",
"-",
"180",
"and",
"l2",
"<",
"0",
"and",
"delta",
"<",
"180",
":",
"return",
"[",
"(",
"l1",
"+",
"360",
",",
"180",
")",
",",
"(",
"l2",
",",
"-",
"180",
")",
"]",
"return",
"[",
"(",
"l1",
",",
"l2",
")",
"]"
] | An international date line safe way of returning a range of longitudes.
>>> normalize_lons(20, 30) # no IDL within the range
[(20, 30)]
>>> normalize_lons(-17, +17) # no IDL within the range
[(-17, 17)]
>>> normalize_lons(-178, +179)
[(-180, -178), (179, 180)]
>>> normalize_lons(178, -179)
[(-180, -179), (178, 180)]
>>> normalize_lons(179, -179)
[(-180, -179), (179, 180)]
>>> normalize_lons(177, -176)
[(-180, -176), (177, 180)] | [
"An",
"international",
"date",
"line",
"safe",
"way",
"of",
"returning",
"a",
"range",
"of",
"longitudes",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L577-L603 | train | 232,926 |
gem/oq-engine | openquake/hazardlib/geo/utils.py | _GeographicObjects.get_closest | def get_closest(self, lon, lat, depth=0):
"""
Get the closest object to the given longitude and latitude
and its distance.
:param lon: longitude in degrees
:param lat: latitude in degrees
:param depth: depth in km (default 0)
:returns: (object, distance)
"""
xyz = spherical_to_cartesian(lon, lat, depth)
min_dist, idx = self.kdtree.query(xyz)
return self.objects[idx], min_dist | python | def get_closest(self, lon, lat, depth=0):
"""
Get the closest object to the given longitude and latitude
and its distance.
:param lon: longitude in degrees
:param lat: latitude in degrees
:param depth: depth in km (default 0)
:returns: (object, distance)
"""
xyz = spherical_to_cartesian(lon, lat, depth)
min_dist, idx = self.kdtree.query(xyz)
return self.objects[idx], min_dist | [
"def",
"get_closest",
"(",
"self",
",",
"lon",
",",
"lat",
",",
"depth",
"=",
"0",
")",
":",
"xyz",
"=",
"spherical_to_cartesian",
"(",
"lon",
",",
"lat",
",",
"depth",
")",
"min_dist",
",",
"idx",
"=",
"self",
".",
"kdtree",
".",
"query",
"(",
"xyz",
")",
"return",
"self",
".",
"objects",
"[",
"idx",
"]",
",",
"min_dist"
] | Get the closest object to the given longitude and latitude
and its distance.
:param lon: longitude in degrees
:param lat: latitude in degrees
:param depth: depth in km (default 0)
:returns: (object, distance) | [
"Get",
"the",
"closest",
"object",
"to",
"the",
"given",
"longitude",
"and",
"latitude",
"and",
"its",
"distance",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L85-L97 | train | 232,927 |
gem/oq-engine | openquake/hazardlib/geo/utils.py | _GeographicObjects.assoc2 | def assoc2(self, assets_by_site, assoc_dist, mode, asset_refs):
"""
Associated a list of assets by site to the site collection used
to instantiate GeographicObjects.
:param assets_by_sites: a list of lists of assets
:param assoc_dist: the maximum distance for association
:param mode: 'strict', 'warn' or 'filter'
:param asset_ref: ID of the assets are a list of strings
:returns: filtered site collection, filtered assets by site, discarded
"""
assert mode in 'strict filter', mode
self.objects.filtered # self.objects must be a SiteCollection
asset_dt = numpy.dtype(
[('asset_ref', vstr), ('lon', F32), ('lat', F32)])
assets_by_sid = collections.defaultdict(list)
discarded = []
for assets in assets_by_site:
lon, lat = assets[0].location
obj, distance = self.get_closest(lon, lat)
if distance <= assoc_dist:
# keep the assets, otherwise discard them
assets_by_sid[obj['sids']].extend(assets)
elif mode == 'strict':
raise SiteAssociationError(
'There is nothing closer than %s km '
'to site (%s %s)' % (assoc_dist, lon, lat))
else:
discarded.extend(assets)
sids = sorted(assets_by_sid)
if not sids:
raise SiteAssociationError(
'Could not associate any site to any assets within the '
'asset_hazard_distance of %s km' % assoc_dist)
assets_by_site = [
sorted(assets_by_sid[sid], key=operator.attrgetter('ordinal'))
for sid in sids]
data = [(asset_refs[asset.ordinal],) + asset.location
for asset in discarded]
discarded = numpy.array(data, asset_dt)
return self.objects.filtered(sids), assets_by_site, discarded | python | def assoc2(self, assets_by_site, assoc_dist, mode, asset_refs):
"""
Associated a list of assets by site to the site collection used
to instantiate GeographicObjects.
:param assets_by_sites: a list of lists of assets
:param assoc_dist: the maximum distance for association
:param mode: 'strict', 'warn' or 'filter'
:param asset_ref: ID of the assets are a list of strings
:returns: filtered site collection, filtered assets by site, discarded
"""
assert mode in 'strict filter', mode
self.objects.filtered # self.objects must be a SiteCollection
asset_dt = numpy.dtype(
[('asset_ref', vstr), ('lon', F32), ('lat', F32)])
assets_by_sid = collections.defaultdict(list)
discarded = []
for assets in assets_by_site:
lon, lat = assets[0].location
obj, distance = self.get_closest(lon, lat)
if distance <= assoc_dist:
# keep the assets, otherwise discard them
assets_by_sid[obj['sids']].extend(assets)
elif mode == 'strict':
raise SiteAssociationError(
'There is nothing closer than %s km '
'to site (%s %s)' % (assoc_dist, lon, lat))
else:
discarded.extend(assets)
sids = sorted(assets_by_sid)
if not sids:
raise SiteAssociationError(
'Could not associate any site to any assets within the '
'asset_hazard_distance of %s km' % assoc_dist)
assets_by_site = [
sorted(assets_by_sid[sid], key=operator.attrgetter('ordinal'))
for sid in sids]
data = [(asset_refs[asset.ordinal],) + asset.location
for asset in discarded]
discarded = numpy.array(data, asset_dt)
return self.objects.filtered(sids), assets_by_site, discarded | [
"def",
"assoc2",
"(",
"self",
",",
"assets_by_site",
",",
"assoc_dist",
",",
"mode",
",",
"asset_refs",
")",
":",
"assert",
"mode",
"in",
"'strict filter'",
",",
"mode",
"self",
".",
"objects",
".",
"filtered",
"# self.objects must be a SiteCollection",
"asset_dt",
"=",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"'asset_ref'",
",",
"vstr",
")",
",",
"(",
"'lon'",
",",
"F32",
")",
",",
"(",
"'lat'",
",",
"F32",
")",
"]",
")",
"assets_by_sid",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"discarded",
"=",
"[",
"]",
"for",
"assets",
"in",
"assets_by_site",
":",
"lon",
",",
"lat",
"=",
"assets",
"[",
"0",
"]",
".",
"location",
"obj",
",",
"distance",
"=",
"self",
".",
"get_closest",
"(",
"lon",
",",
"lat",
")",
"if",
"distance",
"<=",
"assoc_dist",
":",
"# keep the assets, otherwise discard them",
"assets_by_sid",
"[",
"obj",
"[",
"'sids'",
"]",
"]",
".",
"extend",
"(",
"assets",
")",
"elif",
"mode",
"==",
"'strict'",
":",
"raise",
"SiteAssociationError",
"(",
"'There is nothing closer than %s km '",
"'to site (%s %s)'",
"%",
"(",
"assoc_dist",
",",
"lon",
",",
"lat",
")",
")",
"else",
":",
"discarded",
".",
"extend",
"(",
"assets",
")",
"sids",
"=",
"sorted",
"(",
"assets_by_sid",
")",
"if",
"not",
"sids",
":",
"raise",
"SiteAssociationError",
"(",
"'Could not associate any site to any assets within the '",
"'asset_hazard_distance of %s km'",
"%",
"assoc_dist",
")",
"assets_by_site",
"=",
"[",
"sorted",
"(",
"assets_by_sid",
"[",
"sid",
"]",
",",
"key",
"=",
"operator",
".",
"attrgetter",
"(",
"'ordinal'",
")",
")",
"for",
"sid",
"in",
"sids",
"]",
"data",
"=",
"[",
"(",
"asset_refs",
"[",
"asset",
".",
"ordinal",
"]",
",",
")",
"+",
"asset",
".",
"location",
"for",
"asset",
"in",
"discarded",
"]",
"discarded",
"=",
"numpy",
".",
"array",
"(",
"data",
",",
"asset_dt",
")",
"return",
"self",
".",
"objects",
".",
"filtered",
"(",
"sids",
")",
",",
"assets_by_site",
",",
"discarded"
] | Associated a list of assets by site to the site collection used
to instantiate GeographicObjects.
:param assets_by_sites: a list of lists of assets
:param assoc_dist: the maximum distance for association
:param mode: 'strict', 'warn' or 'filter'
:param asset_ref: ID of the assets are a list of strings
:returns: filtered site collection, filtered assets by site, discarded | [
"Associated",
"a",
"list",
"of",
"assets",
"by",
"site",
"to",
"the",
"site",
"collection",
"used",
"to",
"instantiate",
"GeographicObjects",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L134-L174 | train | 232,928 |
gem/oq-engine | openquake/risklib/read_nrml.py | ffconvert | def ffconvert(fname, limit_states, ff, min_iml=1E-10):
"""
Convert a fragility function into a numpy array plus a bunch
of attributes.
:param fname: path to the fragility model file
:param limit_states: expected limit states
:param ff: fragility function node
:returns: a pair (array, dictionary)
"""
with context(fname, ff):
ffs = ff[1:]
imls = ff.imls
nodamage = imls.attrib.get('noDamageLimit')
if nodamage == 0:
# use a cutoff to avoid log(0) in GMPE.to_distribution_values
logging.warning('Found a noDamageLimit=0 in %s, line %s, '
'using %g instead', fname, ff.lineno, min_iml)
nodamage = min_iml
with context(fname, imls):
attrs = dict(format=ff['format'],
imt=imls['imt'],
id=ff['id'],
nodamage=nodamage)
LS = len(limit_states)
if LS != len(ffs):
with context(fname, ff):
raise InvalidFile('expected %d limit states, found %d' %
(LS, len(ffs)))
if ff['format'] == 'continuous':
minIML = float(imls['minIML'])
if minIML == 0:
# use a cutoff to avoid log(0) in GMPE.to_distribution_values
logging.warning('Found minIML=0 in %s, line %s, using %g instead',
fname, imls.lineno, min_iml)
minIML = min_iml
attrs['minIML'] = minIML
attrs['maxIML'] = float(imls['maxIML'])
array = numpy.zeros(LS, [('mean', F64), ('stddev', F64)])
for i, ls, node in zip(range(LS), limit_states, ff[1:]):
if ls != node['ls']:
with context(fname, node):
raise InvalidFile('expected %s, found' %
(ls, node['ls']))
array['mean'][i] = node['mean']
array['stddev'][i] = node['stddev']
elif ff['format'] == 'discrete':
attrs['imls'] = ~imls
valid.check_levels(attrs['imls'], attrs['imt'], min_iml)
num_poes = len(attrs['imls'])
array = numpy.zeros((LS, num_poes))
for i, ls, node in zip(range(LS), limit_states, ff[1:]):
with context(fname, node):
if ls != node['ls']:
raise InvalidFile('expected %s, found' %
(ls, node['ls']))
poes = (~node if isinstance(~node, list)
else valid.probabilities(~node))
if len(poes) != num_poes:
raise InvalidFile('expected %s, found' %
(num_poes, len(poes)))
array[i, :] = poes
# NB: the format is constrained in nrml.FragilityNode to be either
# discrete or continuous, there is no third option
return array, attrs | python | def ffconvert(fname, limit_states, ff, min_iml=1E-10):
"""
Convert a fragility function into a numpy array plus a bunch
of attributes.
:param fname: path to the fragility model file
:param limit_states: expected limit states
:param ff: fragility function node
:returns: a pair (array, dictionary)
"""
with context(fname, ff):
ffs = ff[1:]
imls = ff.imls
nodamage = imls.attrib.get('noDamageLimit')
if nodamage == 0:
# use a cutoff to avoid log(0) in GMPE.to_distribution_values
logging.warning('Found a noDamageLimit=0 in %s, line %s, '
'using %g instead', fname, ff.lineno, min_iml)
nodamage = min_iml
with context(fname, imls):
attrs = dict(format=ff['format'],
imt=imls['imt'],
id=ff['id'],
nodamage=nodamage)
LS = len(limit_states)
if LS != len(ffs):
with context(fname, ff):
raise InvalidFile('expected %d limit states, found %d' %
(LS, len(ffs)))
if ff['format'] == 'continuous':
minIML = float(imls['minIML'])
if minIML == 0:
# use a cutoff to avoid log(0) in GMPE.to_distribution_values
logging.warning('Found minIML=0 in %s, line %s, using %g instead',
fname, imls.lineno, min_iml)
minIML = min_iml
attrs['minIML'] = minIML
attrs['maxIML'] = float(imls['maxIML'])
array = numpy.zeros(LS, [('mean', F64), ('stddev', F64)])
for i, ls, node in zip(range(LS), limit_states, ff[1:]):
if ls != node['ls']:
with context(fname, node):
raise InvalidFile('expected %s, found' %
(ls, node['ls']))
array['mean'][i] = node['mean']
array['stddev'][i] = node['stddev']
elif ff['format'] == 'discrete':
attrs['imls'] = ~imls
valid.check_levels(attrs['imls'], attrs['imt'], min_iml)
num_poes = len(attrs['imls'])
array = numpy.zeros((LS, num_poes))
for i, ls, node in zip(range(LS), limit_states, ff[1:]):
with context(fname, node):
if ls != node['ls']:
raise InvalidFile('expected %s, found' %
(ls, node['ls']))
poes = (~node if isinstance(~node, list)
else valid.probabilities(~node))
if len(poes) != num_poes:
raise InvalidFile('expected %s, found' %
(num_poes, len(poes)))
array[i, :] = poes
# NB: the format is constrained in nrml.FragilityNode to be either
# discrete or continuous, there is no third option
return array, attrs | [
"def",
"ffconvert",
"(",
"fname",
",",
"limit_states",
",",
"ff",
",",
"min_iml",
"=",
"1E-10",
")",
":",
"with",
"context",
"(",
"fname",
",",
"ff",
")",
":",
"ffs",
"=",
"ff",
"[",
"1",
":",
"]",
"imls",
"=",
"ff",
".",
"imls",
"nodamage",
"=",
"imls",
".",
"attrib",
".",
"get",
"(",
"'noDamageLimit'",
")",
"if",
"nodamage",
"==",
"0",
":",
"# use a cutoff to avoid log(0) in GMPE.to_distribution_values",
"logging",
".",
"warning",
"(",
"'Found a noDamageLimit=0 in %s, line %s, '",
"'using %g instead'",
",",
"fname",
",",
"ff",
".",
"lineno",
",",
"min_iml",
")",
"nodamage",
"=",
"min_iml",
"with",
"context",
"(",
"fname",
",",
"imls",
")",
":",
"attrs",
"=",
"dict",
"(",
"format",
"=",
"ff",
"[",
"'format'",
"]",
",",
"imt",
"=",
"imls",
"[",
"'imt'",
"]",
",",
"id",
"=",
"ff",
"[",
"'id'",
"]",
",",
"nodamage",
"=",
"nodamage",
")",
"LS",
"=",
"len",
"(",
"limit_states",
")",
"if",
"LS",
"!=",
"len",
"(",
"ffs",
")",
":",
"with",
"context",
"(",
"fname",
",",
"ff",
")",
":",
"raise",
"InvalidFile",
"(",
"'expected %d limit states, found %d'",
"%",
"(",
"LS",
",",
"len",
"(",
"ffs",
")",
")",
")",
"if",
"ff",
"[",
"'format'",
"]",
"==",
"'continuous'",
":",
"minIML",
"=",
"float",
"(",
"imls",
"[",
"'minIML'",
"]",
")",
"if",
"minIML",
"==",
"0",
":",
"# use a cutoff to avoid log(0) in GMPE.to_distribution_values",
"logging",
".",
"warning",
"(",
"'Found minIML=0 in %s, line %s, using %g instead'",
",",
"fname",
",",
"imls",
".",
"lineno",
",",
"min_iml",
")",
"minIML",
"=",
"min_iml",
"attrs",
"[",
"'minIML'",
"]",
"=",
"minIML",
"attrs",
"[",
"'maxIML'",
"]",
"=",
"float",
"(",
"imls",
"[",
"'maxIML'",
"]",
")",
"array",
"=",
"numpy",
".",
"zeros",
"(",
"LS",
",",
"[",
"(",
"'mean'",
",",
"F64",
")",
",",
"(",
"'stddev'",
",",
"F64",
")",
"]",
")",
"for",
"i",
",",
"ls",
",",
"node",
"in",
"zip",
"(",
"range",
"(",
"LS",
")",
",",
"limit_states",
",",
"ff",
"[",
"1",
":",
"]",
")",
":",
"if",
"ls",
"!=",
"node",
"[",
"'ls'",
"]",
":",
"with",
"context",
"(",
"fname",
",",
"node",
")",
":",
"raise",
"InvalidFile",
"(",
"'expected %s, found'",
"%",
"(",
"ls",
",",
"node",
"[",
"'ls'",
"]",
")",
")",
"array",
"[",
"'mean'",
"]",
"[",
"i",
"]",
"=",
"node",
"[",
"'mean'",
"]",
"array",
"[",
"'stddev'",
"]",
"[",
"i",
"]",
"=",
"node",
"[",
"'stddev'",
"]",
"elif",
"ff",
"[",
"'format'",
"]",
"==",
"'discrete'",
":",
"attrs",
"[",
"'imls'",
"]",
"=",
"~",
"imls",
"valid",
".",
"check_levels",
"(",
"attrs",
"[",
"'imls'",
"]",
",",
"attrs",
"[",
"'imt'",
"]",
",",
"min_iml",
")",
"num_poes",
"=",
"len",
"(",
"attrs",
"[",
"'imls'",
"]",
")",
"array",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"LS",
",",
"num_poes",
")",
")",
"for",
"i",
",",
"ls",
",",
"node",
"in",
"zip",
"(",
"range",
"(",
"LS",
")",
",",
"limit_states",
",",
"ff",
"[",
"1",
":",
"]",
")",
":",
"with",
"context",
"(",
"fname",
",",
"node",
")",
":",
"if",
"ls",
"!=",
"node",
"[",
"'ls'",
"]",
":",
"raise",
"InvalidFile",
"(",
"'expected %s, found'",
"%",
"(",
"ls",
",",
"node",
"[",
"'ls'",
"]",
")",
")",
"poes",
"=",
"(",
"~",
"node",
"if",
"isinstance",
"(",
"~",
"node",
",",
"list",
")",
"else",
"valid",
".",
"probabilities",
"(",
"~",
"node",
")",
")",
"if",
"len",
"(",
"poes",
")",
"!=",
"num_poes",
":",
"raise",
"InvalidFile",
"(",
"'expected %s, found'",
"%",
"(",
"num_poes",
",",
"len",
"(",
"poes",
")",
")",
")",
"array",
"[",
"i",
",",
":",
"]",
"=",
"poes",
"# NB: the format is constrained in nrml.FragilityNode to be either",
"# discrete or continuous, there is no third option",
"return",
"array",
",",
"attrs"
] | Convert a fragility function into a numpy array plus a bunch
of attributes.
:param fname: path to the fragility model file
:param limit_states: expected limit states
:param ff: fragility function node
:returns: a pair (array, dictionary) | [
"Convert",
"a",
"fragility",
"function",
"into",
"a",
"numpy",
"array",
"plus",
"a",
"bunch",
"of",
"attributes",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/read_nrml.py#L152-L217 | train | 232,929 |
gem/oq-engine | openquake/risklib/read_nrml.py | taxonomy | def taxonomy(value):
"""
Any ASCII character goes into a taxonomy, except spaces.
"""
try:
value.encode('ascii')
except UnicodeEncodeError:
raise ValueError('tag %r is not ASCII' % value)
if re.search(r'\s', value):
raise ValueError('The taxonomy %r contains whitespace chars' % value)
return value | python | def taxonomy(value):
"""
Any ASCII character goes into a taxonomy, except spaces.
"""
try:
value.encode('ascii')
except UnicodeEncodeError:
raise ValueError('tag %r is not ASCII' % value)
if re.search(r'\s', value):
raise ValueError('The taxonomy %r contains whitespace chars' % value)
return value | [
"def",
"taxonomy",
"(",
"value",
")",
":",
"try",
":",
"value",
".",
"encode",
"(",
"'ascii'",
")",
"except",
"UnicodeEncodeError",
":",
"raise",
"ValueError",
"(",
"'tag %r is not ASCII'",
"%",
"value",
")",
"if",
"re",
".",
"search",
"(",
"r'\\s'",
",",
"value",
")",
":",
"raise",
"ValueError",
"(",
"'The taxonomy %r contains whitespace chars'",
"%",
"value",
")",
"return",
"value"
] | Any ASCII character goes into a taxonomy, except spaces. | [
"Any",
"ASCII",
"character",
"goes",
"into",
"a",
"taxonomy",
"except",
"spaces",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/read_nrml.py#L371-L381 | train | 232,930 |
gem/oq-engine | openquake/risklib/read_nrml.py | update_validators | def update_validators():
"""
Call this to updade the global nrml.validators
"""
validators.update({
'fragilityFunction.id': valid.utf8, # taxonomy
'vulnerabilityFunction.id': valid.utf8, # taxonomy
'consequenceFunction.id': valid.utf8, # taxonomy
'asset.id': valid.asset_id,
'costType.name': valid.cost_type,
'costType.type': valid.cost_type_type,
'cost.type': valid.cost_type,
'area.type': valid.name,
'isAbsolute': valid.boolean,
'insuranceLimit': valid.positivefloat,
'deductible': valid.positivefloat,
'occupants': valid.positivefloat,
'value': valid.positivefloat,
'retrofitted': valid.positivefloat,
'number': valid.compose(valid.positivefloat, valid.nonzero),
'vulnerabilitySetID': str, # any ASCII string is fine
'vulnerabilityFunctionID': str, # any ASCII string is fine
'lossCategory': valid.utf8, # a description field
'lr': valid.probability,
'lossRatio': valid.positivefloats,
'coefficientsVariation': valid.positivefloats,
'probabilisticDistribution': valid.Choice('LN', 'BT'),
'dist': valid.Choice('LN', 'BT', 'PM'),
'meanLRs': valid.positivefloats,
'covLRs': valid.positivefloats,
'format': valid.ChoiceCI('discrete', 'continuous'),
'mean': valid.positivefloat,
'stddev': valid.positivefloat,
'minIML': valid.positivefloat,
'maxIML': valid.positivefloat,
'limitStates': valid.namelist,
'noDamageLimit': valid.NoneOr(valid.positivefloat),
'loss_type': valid_loss_types,
'losses': valid.positivefloats,
'averageLoss': valid.positivefloat,
'stdDevLoss': valid.positivefloat,
'ffs.type': valid.ChoiceCI('lognormal'),
'assetLifeExpectancy': valid.positivefloat,
'interestRate': valid.positivefloat,
'lossType': valid_loss_types,
'aalOrig': valid.positivefloat,
'aalRetr': valid.positivefloat,
'ratio': valid.positivefloat,
'cf': asset_mean_stddev,
'damage': damage_triple,
'damageStates': valid.namelist,
'taxonomy': taxonomy,
'tagNames': valid.namelist,
}) | python | def update_validators():
"""
Call this to updade the global nrml.validators
"""
validators.update({
'fragilityFunction.id': valid.utf8, # taxonomy
'vulnerabilityFunction.id': valid.utf8, # taxonomy
'consequenceFunction.id': valid.utf8, # taxonomy
'asset.id': valid.asset_id,
'costType.name': valid.cost_type,
'costType.type': valid.cost_type_type,
'cost.type': valid.cost_type,
'area.type': valid.name,
'isAbsolute': valid.boolean,
'insuranceLimit': valid.positivefloat,
'deductible': valid.positivefloat,
'occupants': valid.positivefloat,
'value': valid.positivefloat,
'retrofitted': valid.positivefloat,
'number': valid.compose(valid.positivefloat, valid.nonzero),
'vulnerabilitySetID': str, # any ASCII string is fine
'vulnerabilityFunctionID': str, # any ASCII string is fine
'lossCategory': valid.utf8, # a description field
'lr': valid.probability,
'lossRatio': valid.positivefloats,
'coefficientsVariation': valid.positivefloats,
'probabilisticDistribution': valid.Choice('LN', 'BT'),
'dist': valid.Choice('LN', 'BT', 'PM'),
'meanLRs': valid.positivefloats,
'covLRs': valid.positivefloats,
'format': valid.ChoiceCI('discrete', 'continuous'),
'mean': valid.positivefloat,
'stddev': valid.positivefloat,
'minIML': valid.positivefloat,
'maxIML': valid.positivefloat,
'limitStates': valid.namelist,
'noDamageLimit': valid.NoneOr(valid.positivefloat),
'loss_type': valid_loss_types,
'losses': valid.positivefloats,
'averageLoss': valid.positivefloat,
'stdDevLoss': valid.positivefloat,
'ffs.type': valid.ChoiceCI('lognormal'),
'assetLifeExpectancy': valid.positivefloat,
'interestRate': valid.positivefloat,
'lossType': valid_loss_types,
'aalOrig': valid.positivefloat,
'aalRetr': valid.positivefloat,
'ratio': valid.positivefloat,
'cf': asset_mean_stddev,
'damage': damage_triple,
'damageStates': valid.namelist,
'taxonomy': taxonomy,
'tagNames': valid.namelist,
}) | [
"def",
"update_validators",
"(",
")",
":",
"validators",
".",
"update",
"(",
"{",
"'fragilityFunction.id'",
":",
"valid",
".",
"utf8",
",",
"# taxonomy",
"'vulnerabilityFunction.id'",
":",
"valid",
".",
"utf8",
",",
"# taxonomy",
"'consequenceFunction.id'",
":",
"valid",
".",
"utf8",
",",
"# taxonomy",
"'asset.id'",
":",
"valid",
".",
"asset_id",
",",
"'costType.name'",
":",
"valid",
".",
"cost_type",
",",
"'costType.type'",
":",
"valid",
".",
"cost_type_type",
",",
"'cost.type'",
":",
"valid",
".",
"cost_type",
",",
"'area.type'",
":",
"valid",
".",
"name",
",",
"'isAbsolute'",
":",
"valid",
".",
"boolean",
",",
"'insuranceLimit'",
":",
"valid",
".",
"positivefloat",
",",
"'deductible'",
":",
"valid",
".",
"positivefloat",
",",
"'occupants'",
":",
"valid",
".",
"positivefloat",
",",
"'value'",
":",
"valid",
".",
"positivefloat",
",",
"'retrofitted'",
":",
"valid",
".",
"positivefloat",
",",
"'number'",
":",
"valid",
".",
"compose",
"(",
"valid",
".",
"positivefloat",
",",
"valid",
".",
"nonzero",
")",
",",
"'vulnerabilitySetID'",
":",
"str",
",",
"# any ASCII string is fine",
"'vulnerabilityFunctionID'",
":",
"str",
",",
"# any ASCII string is fine",
"'lossCategory'",
":",
"valid",
".",
"utf8",
",",
"# a description field",
"'lr'",
":",
"valid",
".",
"probability",
",",
"'lossRatio'",
":",
"valid",
".",
"positivefloats",
",",
"'coefficientsVariation'",
":",
"valid",
".",
"positivefloats",
",",
"'probabilisticDistribution'",
":",
"valid",
".",
"Choice",
"(",
"'LN'",
",",
"'BT'",
")",
",",
"'dist'",
":",
"valid",
".",
"Choice",
"(",
"'LN'",
",",
"'BT'",
",",
"'PM'",
")",
",",
"'meanLRs'",
":",
"valid",
".",
"positivefloats",
",",
"'covLRs'",
":",
"valid",
".",
"positivefloats",
",",
"'format'",
":",
"valid",
".",
"ChoiceCI",
"(",
"'discrete'",
",",
"'continuous'",
")",
",",
"'mean'",
":",
"valid",
".",
"positivefloat",
",",
"'stddev'",
":",
"valid",
".",
"positivefloat",
",",
"'minIML'",
":",
"valid",
".",
"positivefloat",
",",
"'maxIML'",
":",
"valid",
".",
"positivefloat",
",",
"'limitStates'",
":",
"valid",
".",
"namelist",
",",
"'noDamageLimit'",
":",
"valid",
".",
"NoneOr",
"(",
"valid",
".",
"positivefloat",
")",
",",
"'loss_type'",
":",
"valid_loss_types",
",",
"'losses'",
":",
"valid",
".",
"positivefloats",
",",
"'averageLoss'",
":",
"valid",
".",
"positivefloat",
",",
"'stdDevLoss'",
":",
"valid",
".",
"positivefloat",
",",
"'ffs.type'",
":",
"valid",
".",
"ChoiceCI",
"(",
"'lognormal'",
")",
",",
"'assetLifeExpectancy'",
":",
"valid",
".",
"positivefloat",
",",
"'interestRate'",
":",
"valid",
".",
"positivefloat",
",",
"'lossType'",
":",
"valid_loss_types",
",",
"'aalOrig'",
":",
"valid",
".",
"positivefloat",
",",
"'aalRetr'",
":",
"valid",
".",
"positivefloat",
",",
"'ratio'",
":",
"valid",
".",
"positivefloat",
",",
"'cf'",
":",
"asset_mean_stddev",
",",
"'damage'",
":",
"damage_triple",
",",
"'damageStates'",
":",
"valid",
".",
"namelist",
",",
"'taxonomy'",
":",
"taxonomy",
",",
"'tagNames'",
":",
"valid",
".",
"namelist",
",",
"}",
")"
] | Call this to updade the global nrml.validators | [
"Call",
"this",
"to",
"updade",
"the",
"global",
"nrml",
".",
"validators"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/read_nrml.py#L384-L437 | train | 232,931 |
gem/oq-engine | openquake/calculators/extract.py | barray | def barray(iterlines):
"""
Array of bytes
"""
lst = [line.encode('utf-8') for line in iterlines]
arr = numpy.array(lst)
return arr | python | def barray(iterlines):
"""
Array of bytes
"""
lst = [line.encode('utf-8') for line in iterlines]
arr = numpy.array(lst)
return arr | [
"def",
"barray",
"(",
"iterlines",
")",
":",
"lst",
"=",
"[",
"line",
".",
"encode",
"(",
"'utf-8'",
")",
"for",
"line",
"in",
"iterlines",
"]",
"arr",
"=",
"numpy",
".",
"array",
"(",
"lst",
")",
"return",
"arr"
] | Array of bytes | [
"Array",
"of",
"bytes"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L130-L136 | train | 232,932 |
gem/oq-engine | openquake/calculators/extract.py | losses_by_tag | def losses_by_tag(dstore, tag):
"""
Statistical average losses by tag. For instance call
$ oq extract losses_by_tag/occupancy
"""
dt = [(tag, vstr)] + dstore['oqparam'].loss_dt_list()
aids = dstore['assetcol/array'][tag]
dset, stats = _get(dstore, 'avg_losses')
arr = dset.value
tagvalues = dstore['assetcol/tagcol/' + tag][1:] # except tagvalue="?"
for s, stat in enumerate(stats):
out = numpy.zeros(len(tagvalues), dt)
for li, (lt, lt_dt) in enumerate(dt[1:]):
for i, tagvalue in enumerate(tagvalues):
out[i][tag] = tagvalue
counts = arr[aids == i + 1, s, li].sum()
if counts:
out[i][lt] = counts
yield stat, out | python | def losses_by_tag(dstore, tag):
"""
Statistical average losses by tag. For instance call
$ oq extract losses_by_tag/occupancy
"""
dt = [(tag, vstr)] + dstore['oqparam'].loss_dt_list()
aids = dstore['assetcol/array'][tag]
dset, stats = _get(dstore, 'avg_losses')
arr = dset.value
tagvalues = dstore['assetcol/tagcol/' + tag][1:] # except tagvalue="?"
for s, stat in enumerate(stats):
out = numpy.zeros(len(tagvalues), dt)
for li, (lt, lt_dt) in enumerate(dt[1:]):
for i, tagvalue in enumerate(tagvalues):
out[i][tag] = tagvalue
counts = arr[aids == i + 1, s, li].sum()
if counts:
out[i][lt] = counts
yield stat, out | [
"def",
"losses_by_tag",
"(",
"dstore",
",",
"tag",
")",
":",
"dt",
"=",
"[",
"(",
"tag",
",",
"vstr",
")",
"]",
"+",
"dstore",
"[",
"'oqparam'",
"]",
".",
"loss_dt_list",
"(",
")",
"aids",
"=",
"dstore",
"[",
"'assetcol/array'",
"]",
"[",
"tag",
"]",
"dset",
",",
"stats",
"=",
"_get",
"(",
"dstore",
",",
"'avg_losses'",
")",
"arr",
"=",
"dset",
".",
"value",
"tagvalues",
"=",
"dstore",
"[",
"'assetcol/tagcol/'",
"+",
"tag",
"]",
"[",
"1",
":",
"]",
"# except tagvalue=\"?\"",
"for",
"s",
",",
"stat",
"in",
"enumerate",
"(",
"stats",
")",
":",
"out",
"=",
"numpy",
".",
"zeros",
"(",
"len",
"(",
"tagvalues",
")",
",",
"dt",
")",
"for",
"li",
",",
"(",
"lt",
",",
"lt_dt",
")",
"in",
"enumerate",
"(",
"dt",
"[",
"1",
":",
"]",
")",
":",
"for",
"i",
",",
"tagvalue",
"in",
"enumerate",
"(",
"tagvalues",
")",
":",
"out",
"[",
"i",
"]",
"[",
"tag",
"]",
"=",
"tagvalue",
"counts",
"=",
"arr",
"[",
"aids",
"==",
"i",
"+",
"1",
",",
"s",
",",
"li",
"]",
".",
"sum",
"(",
")",
"if",
"counts",
":",
"out",
"[",
"i",
"]",
"[",
"lt",
"]",
"=",
"counts",
"yield",
"stat",
",",
"out"
] | Statistical average losses by tag. For instance call
$ oq extract losses_by_tag/occupancy | [
"Statistical",
"average",
"losses",
"by",
"tag",
".",
"For",
"instance",
"call"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L808-L827 | train | 232,933 |
gem/oq-engine | openquake/calculators/extract.py | WebExtractor.dump | def dump(self, fname):
"""
Dump the remote datastore on a local path.
"""
url = '%s/v1/calc/%d/datastore' % (self.server, self.calc_id)
resp = self.sess.get(url, stream=True)
down = 0
with open(fname, 'wb') as f:
logging.info('Saving %s', fname)
for chunk in resp.iter_content(CHUNKSIZE):
f.write(chunk)
down += len(chunk)
println('Downloaded {:,} bytes'.format(down))
print() | python | def dump(self, fname):
"""
Dump the remote datastore on a local path.
"""
url = '%s/v1/calc/%d/datastore' % (self.server, self.calc_id)
resp = self.sess.get(url, stream=True)
down = 0
with open(fname, 'wb') as f:
logging.info('Saving %s', fname)
for chunk in resp.iter_content(CHUNKSIZE):
f.write(chunk)
down += len(chunk)
println('Downloaded {:,} bytes'.format(down))
print() | [
"def",
"dump",
"(",
"self",
",",
"fname",
")",
":",
"url",
"=",
"'%s/v1/calc/%d/datastore'",
"%",
"(",
"self",
".",
"server",
",",
"self",
".",
"calc_id",
")",
"resp",
"=",
"self",
".",
"sess",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"down",
"=",
"0",
"with",
"open",
"(",
"fname",
",",
"'wb'",
")",
"as",
"f",
":",
"logging",
".",
"info",
"(",
"'Saving %s'",
",",
"fname",
")",
"for",
"chunk",
"in",
"resp",
".",
"iter_content",
"(",
"CHUNKSIZE",
")",
":",
"f",
".",
"write",
"(",
"chunk",
")",
"down",
"+=",
"len",
"(",
"chunk",
")",
"println",
"(",
"'Downloaded {:,} bytes'",
".",
"format",
"(",
"down",
")",
")",
"print",
"(",
")"
] | Dump the remote datastore on a local path. | [
"Dump",
"the",
"remote",
"datastore",
"on",
"a",
"local",
"path",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L988-L1001 | train | 232,934 |
gem/oq-engine | openquake/hazardlib/gsim/utils_swiss_gmpe.py | _compute_small_mag_correction_term | def _compute_small_mag_correction_term(C, mag, rhypo):
"""
small magnitude correction applied to the median values
"""
if mag >= 3.00 and mag < 5.5:
min_term = np.minimum(rhypo, C['Rm'])
max_term = np.maximum(min_term, 10)
term_ln = np.log(max_term / 20)
term_ratio = ((5.50 - mag) / C['a1'])
temp = (term_ratio) ** C['a2'] * (C['b1'] + C['b2'] * term_ln)
return 1 / np.exp(temp)
else:
return 1 | python | def _compute_small_mag_correction_term(C, mag, rhypo):
"""
small magnitude correction applied to the median values
"""
if mag >= 3.00 and mag < 5.5:
min_term = np.minimum(rhypo, C['Rm'])
max_term = np.maximum(min_term, 10)
term_ln = np.log(max_term / 20)
term_ratio = ((5.50 - mag) / C['a1'])
temp = (term_ratio) ** C['a2'] * (C['b1'] + C['b2'] * term_ln)
return 1 / np.exp(temp)
else:
return 1 | [
"def",
"_compute_small_mag_correction_term",
"(",
"C",
",",
"mag",
",",
"rhypo",
")",
":",
"if",
"mag",
">=",
"3.00",
"and",
"mag",
"<",
"5.5",
":",
"min_term",
"=",
"np",
".",
"minimum",
"(",
"rhypo",
",",
"C",
"[",
"'Rm'",
"]",
")",
"max_term",
"=",
"np",
".",
"maximum",
"(",
"min_term",
",",
"10",
")",
"term_ln",
"=",
"np",
".",
"log",
"(",
"max_term",
"/",
"20",
")",
"term_ratio",
"=",
"(",
"(",
"5.50",
"-",
"mag",
")",
"/",
"C",
"[",
"'a1'",
"]",
")",
"temp",
"=",
"(",
"term_ratio",
")",
"**",
"C",
"[",
"'a2'",
"]",
"*",
"(",
"C",
"[",
"'b1'",
"]",
"+",
"C",
"[",
"'b2'",
"]",
"*",
"term_ln",
")",
"return",
"1",
"/",
"np",
".",
"exp",
"(",
"temp",
")",
"else",
":",
"return",
"1"
] | small magnitude correction applied to the median values | [
"small",
"magnitude",
"correction",
"applied",
"to",
"the",
"median",
"values"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/utils_swiss_gmpe.py#L40-L52 | train | 232,935 |
gem/oq-engine | openquake/hazardlib/gsim/utils_swiss_gmpe.py | _apply_adjustments | def _apply_adjustments(COEFFS, C_ADJ, tau_ss, mean, stddevs, sites, rup, dists,
imt, stddev_types, log_phi_ss, NL=None, tau_value=None):
"""
This method applies adjustments to the mean and standard deviation.
The small-magnitude adjustments are applied to mean, whereas the
embeded single station sigma logic tree is applied to the
total standard deviation.
"""
c1_dists = _compute_C1_term(C_ADJ, dists)
phi_ss = _compute_phi_ss(
C_ADJ, rup.mag, c1_dists, log_phi_ss, C_ADJ['mean_phi_ss']
)
mean_corr = np.exp(mean) * C_ADJ['k_adj'] * \
_compute_small_mag_correction_term(C_ADJ, rup.mag, dists)
mean_corr = np.log(mean_corr)
std_corr = _get_corr_stddevs(COEFFS[imt], tau_ss, stddev_types,
len(sites.vs30), phi_ss, NL, tau_value)
stddevs = np.array(std_corr)
return mean_corr, stddevs | python | def _apply_adjustments(COEFFS, C_ADJ, tau_ss, mean, stddevs, sites, rup, dists,
imt, stddev_types, log_phi_ss, NL=None, tau_value=None):
"""
This method applies adjustments to the mean and standard deviation.
The small-magnitude adjustments are applied to mean, whereas the
embeded single station sigma logic tree is applied to the
total standard deviation.
"""
c1_dists = _compute_C1_term(C_ADJ, dists)
phi_ss = _compute_phi_ss(
C_ADJ, rup.mag, c1_dists, log_phi_ss, C_ADJ['mean_phi_ss']
)
mean_corr = np.exp(mean) * C_ADJ['k_adj'] * \
_compute_small_mag_correction_term(C_ADJ, rup.mag, dists)
mean_corr = np.log(mean_corr)
std_corr = _get_corr_stddevs(COEFFS[imt], tau_ss, stddev_types,
len(sites.vs30), phi_ss, NL, tau_value)
stddevs = np.array(std_corr)
return mean_corr, stddevs | [
"def",
"_apply_adjustments",
"(",
"COEFFS",
",",
"C_ADJ",
",",
"tau_ss",
",",
"mean",
",",
"stddevs",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
",",
"log_phi_ss",
",",
"NL",
"=",
"None",
",",
"tau_value",
"=",
"None",
")",
":",
"c1_dists",
"=",
"_compute_C1_term",
"(",
"C_ADJ",
",",
"dists",
")",
"phi_ss",
"=",
"_compute_phi_ss",
"(",
"C_ADJ",
",",
"rup",
".",
"mag",
",",
"c1_dists",
",",
"log_phi_ss",
",",
"C_ADJ",
"[",
"'mean_phi_ss'",
"]",
")",
"mean_corr",
"=",
"np",
".",
"exp",
"(",
"mean",
")",
"*",
"C_ADJ",
"[",
"'k_adj'",
"]",
"*",
"_compute_small_mag_correction_term",
"(",
"C_ADJ",
",",
"rup",
".",
"mag",
",",
"dists",
")",
"mean_corr",
"=",
"np",
".",
"log",
"(",
"mean_corr",
")",
"std_corr",
"=",
"_get_corr_stddevs",
"(",
"COEFFS",
"[",
"imt",
"]",
",",
"tau_ss",
",",
"stddev_types",
",",
"len",
"(",
"sites",
".",
"vs30",
")",
",",
"phi_ss",
",",
"NL",
",",
"tau_value",
")",
"stddevs",
"=",
"np",
".",
"array",
"(",
"std_corr",
")",
"return",
"mean_corr",
",",
"stddevs"
] | This method applies adjustments to the mean and standard deviation.
The small-magnitude adjustments are applied to mean, whereas the
embeded single station sigma logic tree is applied to the
total standard deviation. | [
"This",
"method",
"applies",
"adjustments",
"to",
"the",
"mean",
"and",
"standard",
"deviation",
".",
"The",
"small",
"-",
"magnitude",
"adjustments",
"are",
"applied",
"to",
"mean",
"whereas",
"the",
"embeded",
"single",
"station",
"sigma",
"logic",
"tree",
"is",
"applied",
"to",
"the",
"total",
"standard",
"deviation",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/utils_swiss_gmpe.py#L102-L125 | train | 232,936 |
gem/oq-engine | openquake/commonlib/source.py | CompositionInfo.get_info | def get_info(self, sm_id):
"""
Extract a CompositionInfo instance containing the single
model of index `sm_id`.
"""
sm = self.source_models[sm_id]
num_samples = sm.samples if self.num_samples else 0
return self.__class__(
self.gsim_lt, self.seed, num_samples, [sm], self.tot_weight) | python | def get_info(self, sm_id):
"""
Extract a CompositionInfo instance containing the single
model of index `sm_id`.
"""
sm = self.source_models[sm_id]
num_samples = sm.samples if self.num_samples else 0
return self.__class__(
self.gsim_lt, self.seed, num_samples, [sm], self.tot_weight) | [
"def",
"get_info",
"(",
"self",
",",
"sm_id",
")",
":",
"sm",
"=",
"self",
".",
"source_models",
"[",
"sm_id",
"]",
"num_samples",
"=",
"sm",
".",
"samples",
"if",
"self",
".",
"num_samples",
"else",
"0",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"gsim_lt",
",",
"self",
".",
"seed",
",",
"num_samples",
",",
"[",
"sm",
"]",
",",
"self",
".",
"tot_weight",
")"
] | Extract a CompositionInfo instance containing the single
model of index `sm_id`. | [
"Extract",
"a",
"CompositionInfo",
"instance",
"containing",
"the",
"single",
"model",
"of",
"index",
"sm_id",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L142-L150 | train | 232,937 |
gem/oq-engine | openquake/commonlib/source.py | CompositionInfo.get_source_model | def get_source_model(self, src_group_id):
"""
Return the source model for the given src_group_id
"""
for smodel in self.source_models:
for src_group in smodel.src_groups:
if src_group.id == src_group_id:
return smodel | python | def get_source_model(self, src_group_id):
"""
Return the source model for the given src_group_id
"""
for smodel in self.source_models:
for src_group in smodel.src_groups:
if src_group.id == src_group_id:
return smodel | [
"def",
"get_source_model",
"(",
"self",
",",
"src_group_id",
")",
":",
"for",
"smodel",
"in",
"self",
".",
"source_models",
":",
"for",
"src_group",
"in",
"smodel",
".",
"src_groups",
":",
"if",
"src_group",
".",
"id",
"==",
"src_group_id",
":",
"return",
"smodel"
] | Return the source model for the given src_group_id | [
"Return",
"the",
"source",
"model",
"for",
"the",
"given",
"src_group_id"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L275-L282 | train | 232,938 |
gem/oq-engine | openquake/commonlib/source.py | CompositeSourceModel.get_model | def get_model(self, sm_id):
"""
Extract a CompositeSourceModel instance containing the single
model of index `sm_id`.
"""
sm = self.source_models[sm_id]
if self.source_model_lt.num_samples:
self.source_model_lt.num_samples = sm.samples
new = self.__class__(self.gsim_lt, self.source_model_lt, [sm],
self.optimize_same_id)
new.sm_id = sm_id
return new | python | def get_model(self, sm_id):
"""
Extract a CompositeSourceModel instance containing the single
model of index `sm_id`.
"""
sm = self.source_models[sm_id]
if self.source_model_lt.num_samples:
self.source_model_lt.num_samples = sm.samples
new = self.__class__(self.gsim_lt, self.source_model_lt, [sm],
self.optimize_same_id)
new.sm_id = sm_id
return new | [
"def",
"get_model",
"(",
"self",
",",
"sm_id",
")",
":",
"sm",
"=",
"self",
".",
"source_models",
"[",
"sm_id",
"]",
"if",
"self",
".",
"source_model_lt",
".",
"num_samples",
":",
"self",
".",
"source_model_lt",
".",
"num_samples",
"=",
"sm",
".",
"samples",
"new",
"=",
"self",
".",
"__class__",
"(",
"self",
".",
"gsim_lt",
",",
"self",
".",
"source_model_lt",
",",
"[",
"sm",
"]",
",",
"self",
".",
"optimize_same_id",
")",
"new",
".",
"sm_id",
"=",
"sm_id",
"return",
"new"
] | Extract a CompositeSourceModel instance containing the single
model of index `sm_id`. | [
"Extract",
"a",
"CompositeSourceModel",
"instance",
"containing",
"the",
"single",
"model",
"of",
"index",
"sm_id",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L381-L392 | train | 232,939 |
gem/oq-engine | openquake/commonlib/source.py | CompositeSourceModel.new | def new(self, sources_by_grp):
"""
Generate a new CompositeSourceModel from the given dictionary.
:param sources_by_group: a dictionary grp_id -> sources
:returns: a new CompositeSourceModel instance
"""
source_models = []
for sm in self.source_models:
src_groups = []
for src_group in sm.src_groups:
sg = copy.copy(src_group)
sg.sources = sorted(sources_by_grp.get(sg.id, []),
key=operator.attrgetter('id'))
src_groups.append(sg)
newsm = logictree.LtSourceModel(
sm.names, sm.weight, sm.path, src_groups,
sm.num_gsim_paths, sm.ordinal, sm.samples)
source_models.append(newsm)
new = self.__class__(self.gsim_lt, self.source_model_lt, source_models,
self.optimize_same_id)
new.info.update_eff_ruptures(new.get_num_ruptures())
new.info.tot_weight = new.get_weight()
return new | python | def new(self, sources_by_grp):
"""
Generate a new CompositeSourceModel from the given dictionary.
:param sources_by_group: a dictionary grp_id -> sources
:returns: a new CompositeSourceModel instance
"""
source_models = []
for sm in self.source_models:
src_groups = []
for src_group in sm.src_groups:
sg = copy.copy(src_group)
sg.sources = sorted(sources_by_grp.get(sg.id, []),
key=operator.attrgetter('id'))
src_groups.append(sg)
newsm = logictree.LtSourceModel(
sm.names, sm.weight, sm.path, src_groups,
sm.num_gsim_paths, sm.ordinal, sm.samples)
source_models.append(newsm)
new = self.__class__(self.gsim_lt, self.source_model_lt, source_models,
self.optimize_same_id)
new.info.update_eff_ruptures(new.get_num_ruptures())
new.info.tot_weight = new.get_weight()
return new | [
"def",
"new",
"(",
"self",
",",
"sources_by_grp",
")",
":",
"source_models",
"=",
"[",
"]",
"for",
"sm",
"in",
"self",
".",
"source_models",
":",
"src_groups",
"=",
"[",
"]",
"for",
"src_group",
"in",
"sm",
".",
"src_groups",
":",
"sg",
"=",
"copy",
".",
"copy",
"(",
"src_group",
")",
"sg",
".",
"sources",
"=",
"sorted",
"(",
"sources_by_grp",
".",
"get",
"(",
"sg",
".",
"id",
",",
"[",
"]",
")",
",",
"key",
"=",
"operator",
".",
"attrgetter",
"(",
"'id'",
")",
")",
"src_groups",
".",
"append",
"(",
"sg",
")",
"newsm",
"=",
"logictree",
".",
"LtSourceModel",
"(",
"sm",
".",
"names",
",",
"sm",
".",
"weight",
",",
"sm",
".",
"path",
",",
"src_groups",
",",
"sm",
".",
"num_gsim_paths",
",",
"sm",
".",
"ordinal",
",",
"sm",
".",
"samples",
")",
"source_models",
".",
"append",
"(",
"newsm",
")",
"new",
"=",
"self",
".",
"__class__",
"(",
"self",
".",
"gsim_lt",
",",
"self",
".",
"source_model_lt",
",",
"source_models",
",",
"self",
".",
"optimize_same_id",
")",
"new",
".",
"info",
".",
"update_eff_ruptures",
"(",
"new",
".",
"get_num_ruptures",
"(",
")",
")",
"new",
".",
"info",
".",
"tot_weight",
"=",
"new",
".",
"get_weight",
"(",
")",
"return",
"new"
] | Generate a new CompositeSourceModel from the given dictionary.
:param sources_by_group: a dictionary grp_id -> sources
:returns: a new CompositeSourceModel instance | [
"Generate",
"a",
"new",
"CompositeSourceModel",
"from",
"the",
"given",
"dictionary",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L394-L417 | train | 232,940 |
gem/oq-engine | openquake/commonlib/source.py | CompositeSourceModel.check_dupl_sources | def check_dupl_sources(self): # used in print_csm_info
"""
Extracts duplicated sources, i.e. sources with the same source_id in
different source groups. Raise an exception if there are sources with
the same ID which are not duplicated.
:returns: a list of list of sources, ordered by source_id
"""
dd = collections.defaultdict(list)
for src_group in self.src_groups:
for src in src_group:
try:
srcid = src.source_id
except AttributeError: # src is a Node object
srcid = src['id']
dd[srcid].append(src)
dupl = []
for srcid, srcs in sorted(dd.items()):
if len(srcs) > 1:
_assert_equal_sources(srcs)
dupl.append(srcs)
return dupl | python | def check_dupl_sources(self): # used in print_csm_info
"""
Extracts duplicated sources, i.e. sources with the same source_id in
different source groups. Raise an exception if there are sources with
the same ID which are not duplicated.
:returns: a list of list of sources, ordered by source_id
"""
dd = collections.defaultdict(list)
for src_group in self.src_groups:
for src in src_group:
try:
srcid = src.source_id
except AttributeError: # src is a Node object
srcid = src['id']
dd[srcid].append(src)
dupl = []
for srcid, srcs in sorted(dd.items()):
if len(srcs) > 1:
_assert_equal_sources(srcs)
dupl.append(srcs)
return dupl | [
"def",
"check_dupl_sources",
"(",
"self",
")",
":",
"# used in print_csm_info",
"dd",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"src_group",
"in",
"self",
".",
"src_groups",
":",
"for",
"src",
"in",
"src_group",
":",
"try",
":",
"srcid",
"=",
"src",
".",
"source_id",
"except",
"AttributeError",
":",
"# src is a Node object",
"srcid",
"=",
"src",
"[",
"'id'",
"]",
"dd",
"[",
"srcid",
"]",
".",
"append",
"(",
"src",
")",
"dupl",
"=",
"[",
"]",
"for",
"srcid",
",",
"srcs",
"in",
"sorted",
"(",
"dd",
".",
"items",
"(",
")",
")",
":",
"if",
"len",
"(",
"srcs",
")",
">",
"1",
":",
"_assert_equal_sources",
"(",
"srcs",
")",
"dupl",
".",
"append",
"(",
"srcs",
")",
"return",
"dupl"
] | Extracts duplicated sources, i.e. sources with the same source_id in
different source groups. Raise an exception if there are sources with
the same ID which are not duplicated.
:returns: a list of list of sources, ordered by source_id | [
"Extracts",
"duplicated",
"sources",
"i",
".",
"e",
".",
"sources",
"with",
"the",
"same",
"source_id",
"in",
"different",
"source",
"groups",
".",
"Raise",
"an",
"exception",
"if",
"there",
"are",
"sources",
"with",
"the",
"same",
"ID",
"which",
"are",
"not",
"duplicated",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L443-L464 | train | 232,941 |
gem/oq-engine | openquake/commonlib/source.py | CompositeSourceModel.get_sources | def get_sources(self, kind='all'):
"""
Extract the sources contained in the source models by optionally
filtering and splitting them, depending on the passed parameter.
"""
assert kind in ('all', 'indep', 'mutex'), kind
sources = []
for sm in self.source_models:
for src_group in sm.src_groups:
if kind in ('all', src_group.src_interdep):
for src in src_group:
if sm.samples > 1:
src.samples = sm.samples
sources.append(src)
return sources | python | def get_sources(self, kind='all'):
"""
Extract the sources contained in the source models by optionally
filtering and splitting them, depending on the passed parameter.
"""
assert kind in ('all', 'indep', 'mutex'), kind
sources = []
for sm in self.source_models:
for src_group in sm.src_groups:
if kind in ('all', src_group.src_interdep):
for src in src_group:
if sm.samples > 1:
src.samples = sm.samples
sources.append(src)
return sources | [
"def",
"get_sources",
"(",
"self",
",",
"kind",
"=",
"'all'",
")",
":",
"assert",
"kind",
"in",
"(",
"'all'",
",",
"'indep'",
",",
"'mutex'",
")",
",",
"kind",
"sources",
"=",
"[",
"]",
"for",
"sm",
"in",
"self",
".",
"source_models",
":",
"for",
"src_group",
"in",
"sm",
".",
"src_groups",
":",
"if",
"kind",
"in",
"(",
"'all'",
",",
"src_group",
".",
"src_interdep",
")",
":",
"for",
"src",
"in",
"src_group",
":",
"if",
"sm",
".",
"samples",
">",
"1",
":",
"src",
".",
"samples",
"=",
"sm",
".",
"samples",
"sources",
".",
"append",
"(",
"src",
")",
"return",
"sources"
] | Extract the sources contained in the source models by optionally
filtering and splitting them, depending on the passed parameter. | [
"Extract",
"the",
"sources",
"contained",
"in",
"the",
"source",
"models",
"by",
"optionally",
"filtering",
"and",
"splitting",
"them",
"depending",
"on",
"the",
"passed",
"parameter",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L466-L480 | train | 232,942 |
gem/oq-engine | openquake/commonlib/source.py | CompositeSourceModel.init_serials | def init_serials(self, ses_seed):
"""
Generate unique seeds for each rupture with numpy.arange.
This should be called only in event based calculators
"""
sources = self.get_sources()
serial = ses_seed
for src in sources:
nr = src.num_ruptures
src.serial = serial
serial += nr | python | def init_serials(self, ses_seed):
"""
Generate unique seeds for each rupture with numpy.arange.
This should be called only in event based calculators
"""
sources = self.get_sources()
serial = ses_seed
for src in sources:
nr = src.num_ruptures
src.serial = serial
serial += nr | [
"def",
"init_serials",
"(",
"self",
",",
"ses_seed",
")",
":",
"sources",
"=",
"self",
".",
"get_sources",
"(",
")",
"serial",
"=",
"ses_seed",
"for",
"src",
"in",
"sources",
":",
"nr",
"=",
"src",
".",
"num_ruptures",
"src",
".",
"serial",
"=",
"serial",
"serial",
"+=",
"nr"
] | Generate unique seeds for each rupture with numpy.arange.
This should be called only in event based calculators | [
"Generate",
"unique",
"seeds",
"for",
"each",
"rupture",
"with",
"numpy",
".",
"arange",
".",
"This",
"should",
"be",
"called",
"only",
"in",
"event",
"based",
"calculators"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L525-L535 | train | 232,943 |
gem/oq-engine | openquake/commonlib/source.py | CompositeSourceModel.get_maxweight | def get_maxweight(self, weight, concurrent_tasks, minweight=MINWEIGHT):
"""
Return an appropriate maxweight for use in the block_splitter
"""
totweight = self.get_weight(weight)
ct = concurrent_tasks or 1
mw = math.ceil(totweight / ct)
return max(mw, minweight) | python | def get_maxweight(self, weight, concurrent_tasks, minweight=MINWEIGHT):
"""
Return an appropriate maxweight for use in the block_splitter
"""
totweight = self.get_weight(weight)
ct = concurrent_tasks or 1
mw = math.ceil(totweight / ct)
return max(mw, minweight) | [
"def",
"get_maxweight",
"(",
"self",
",",
"weight",
",",
"concurrent_tasks",
",",
"minweight",
"=",
"MINWEIGHT",
")",
":",
"totweight",
"=",
"self",
".",
"get_weight",
"(",
"weight",
")",
"ct",
"=",
"concurrent_tasks",
"or",
"1",
"mw",
"=",
"math",
".",
"ceil",
"(",
"totweight",
"/",
"ct",
")",
"return",
"max",
"(",
"mw",
",",
"minweight",
")"
] | Return an appropriate maxweight for use in the block_splitter | [
"Return",
"an",
"appropriate",
"maxweight",
"for",
"use",
"in",
"the",
"block_splitter"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L537-L544 | train | 232,944 |
gem/oq-engine | openquake/hmtk/parsers/faults/fault_yaml_parser.py | weight_list_to_tuple | def weight_list_to_tuple(data, attr_name):
'''
Converts a list of values and corresponding weights to a tuple of values
'''
if len(data['Value']) != len(data['Weight']):
raise ValueError('Number of weights do not correspond to number of '
'attributes in %s' % attr_name)
weight = np.array(data['Weight'])
if fabs(np.sum(weight) - 1.) > 1E-7:
raise ValueError('Weights do not sum to 1.0 in %s' % attr_name)
data_tuple = []
for iloc, value in enumerate(data['Value']):
data_tuple.append((value, weight[iloc]))
return data_tuple | python | def weight_list_to_tuple(data, attr_name):
'''
Converts a list of values and corresponding weights to a tuple of values
'''
if len(data['Value']) != len(data['Weight']):
raise ValueError('Number of weights do not correspond to number of '
'attributes in %s' % attr_name)
weight = np.array(data['Weight'])
if fabs(np.sum(weight) - 1.) > 1E-7:
raise ValueError('Weights do not sum to 1.0 in %s' % attr_name)
data_tuple = []
for iloc, value in enumerate(data['Value']):
data_tuple.append((value, weight[iloc]))
return data_tuple | [
"def",
"weight_list_to_tuple",
"(",
"data",
",",
"attr_name",
")",
":",
"if",
"len",
"(",
"data",
"[",
"'Value'",
"]",
")",
"!=",
"len",
"(",
"data",
"[",
"'Weight'",
"]",
")",
":",
"raise",
"ValueError",
"(",
"'Number of weights do not correspond to number of '",
"'attributes in %s'",
"%",
"attr_name",
")",
"weight",
"=",
"np",
".",
"array",
"(",
"data",
"[",
"'Weight'",
"]",
")",
"if",
"fabs",
"(",
"np",
".",
"sum",
"(",
"weight",
")",
"-",
"1.",
")",
">",
"1E-7",
":",
"raise",
"ValueError",
"(",
"'Weights do not sum to 1.0 in %s'",
"%",
"attr_name",
")",
"data_tuple",
"=",
"[",
"]",
"for",
"iloc",
",",
"value",
"in",
"enumerate",
"(",
"data",
"[",
"'Value'",
"]",
")",
":",
"data_tuple",
".",
"append",
"(",
"(",
"value",
",",
"weight",
"[",
"iloc",
"]",
")",
")",
"return",
"data_tuple"
] | Converts a list of values and corresponding weights to a tuple of values | [
"Converts",
"a",
"list",
"of",
"values",
"and",
"corresponding",
"weights",
"to",
"a",
"tuple",
"of",
"values"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L71-L86 | train | 232,945 |
gem/oq-engine | openquake/hmtk/parsers/faults/fault_yaml_parser.py | parse_tect_region_dict_to_tuples | def parse_tect_region_dict_to_tuples(region_dict):
'''
Parses the tectonic regionalisation dictionary attributes to tuples
'''
output_region_dict = []
tuple_keys = ['Displacement_Length_Ratio', 'Shear_Modulus']
# Convert MSR string name to openquake.hazardlib.scalerel object
for region in region_dict:
for val_name in tuple_keys:
region[val_name] = weight_list_to_tuple(region[val_name],
val_name)
# MSR works differently - so call get_scaling_relation_tuple
region['Magnitude_Scaling_Relation'] = weight_list_to_tuple(
region['Magnitude_Scaling_Relation'],
'Magnitude Scaling Relation')
output_region_dict.append(region)
return output_region_dict | python | def parse_tect_region_dict_to_tuples(region_dict):
'''
Parses the tectonic regionalisation dictionary attributes to tuples
'''
output_region_dict = []
tuple_keys = ['Displacement_Length_Ratio', 'Shear_Modulus']
# Convert MSR string name to openquake.hazardlib.scalerel object
for region in region_dict:
for val_name in tuple_keys:
region[val_name] = weight_list_to_tuple(region[val_name],
val_name)
# MSR works differently - so call get_scaling_relation_tuple
region['Magnitude_Scaling_Relation'] = weight_list_to_tuple(
region['Magnitude_Scaling_Relation'],
'Magnitude Scaling Relation')
output_region_dict.append(region)
return output_region_dict | [
"def",
"parse_tect_region_dict_to_tuples",
"(",
"region_dict",
")",
":",
"output_region_dict",
"=",
"[",
"]",
"tuple_keys",
"=",
"[",
"'Displacement_Length_Ratio'",
",",
"'Shear_Modulus'",
"]",
"# Convert MSR string name to openquake.hazardlib.scalerel object",
"for",
"region",
"in",
"region_dict",
":",
"for",
"val_name",
"in",
"tuple_keys",
":",
"region",
"[",
"val_name",
"]",
"=",
"weight_list_to_tuple",
"(",
"region",
"[",
"val_name",
"]",
",",
"val_name",
")",
"# MSR works differently - so call get_scaling_relation_tuple",
"region",
"[",
"'Magnitude_Scaling_Relation'",
"]",
"=",
"weight_list_to_tuple",
"(",
"region",
"[",
"'Magnitude_Scaling_Relation'",
"]",
",",
"'Magnitude Scaling Relation'",
")",
"output_region_dict",
".",
"append",
"(",
"region",
")",
"return",
"output_region_dict"
] | Parses the tectonic regionalisation dictionary attributes to tuples | [
"Parses",
"the",
"tectonic",
"regionalisation",
"dictionary",
"attributes",
"to",
"tuples"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L89-L105 | train | 232,946 |
gem/oq-engine | openquake/hmtk/parsers/faults/fault_yaml_parser.py | get_scaling_relation_tuple | def get_scaling_relation_tuple(msr_dict):
'''
For a dictionary of scaling relation values convert string list to
object list and then to tuple
'''
# Convert MSR string name to openquake.hazardlib.scalerel object
for iloc, value in enumerate(msr_dict['Value']):
if not value in SCALE_REL_MAP.keys():
raise ValueError('Scaling relation %s not supported!' % value)
msr_dict['Value'][iloc] = SCALE_REL_MAP[value]()
return weight_list_to_tuple(msr_dict,
'Magnitude Scaling Relation') | python | def get_scaling_relation_tuple(msr_dict):
'''
For a dictionary of scaling relation values convert string list to
object list and then to tuple
'''
# Convert MSR string name to openquake.hazardlib.scalerel object
for iloc, value in enumerate(msr_dict['Value']):
if not value in SCALE_REL_MAP.keys():
raise ValueError('Scaling relation %s not supported!' % value)
msr_dict['Value'][iloc] = SCALE_REL_MAP[value]()
return weight_list_to_tuple(msr_dict,
'Magnitude Scaling Relation') | [
"def",
"get_scaling_relation_tuple",
"(",
"msr_dict",
")",
":",
"# Convert MSR string name to openquake.hazardlib.scalerel object",
"for",
"iloc",
",",
"value",
"in",
"enumerate",
"(",
"msr_dict",
"[",
"'Value'",
"]",
")",
":",
"if",
"not",
"value",
"in",
"SCALE_REL_MAP",
".",
"keys",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Scaling relation %s not supported!'",
"%",
"value",
")",
"msr_dict",
"[",
"'Value'",
"]",
"[",
"iloc",
"]",
"=",
"SCALE_REL_MAP",
"[",
"value",
"]",
"(",
")",
"return",
"weight_list_to_tuple",
"(",
"msr_dict",
",",
"'Magnitude Scaling Relation'",
")"
] | For a dictionary of scaling relation values convert string list to
object list and then to tuple | [
"For",
"a",
"dictionary",
"of",
"scaling",
"relation",
"values",
"convert",
"string",
"list",
"to",
"object",
"list",
"and",
"then",
"to",
"tuple"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L108-L120 | train | 232,947 |
gem/oq-engine | openquake/hmtk/parsers/faults/fault_yaml_parser.py | FaultYmltoSource.read_file | def read_file(self, mesh_spacing=1.0):
'''
Reads the file and returns an instance of the FaultSource class.
:param float mesh_spacing:
Fault mesh spacing (km)
'''
# Process the tectonic regionalisation
tectonic_reg = self.process_tectonic_regionalisation()
model = mtkActiveFaultModel(self.data['Fault_Model_ID'],
self.data['Fault_Model_Name'])
for fault in self.data['Fault_Model']:
fault_geometry = self.read_fault_geometry(fault['Fault_Geometry'],
mesh_spacing)
if fault['Shear_Modulus']:
fault['Shear_Modulus'] = weight_list_to_tuple(
fault['Shear_Modulus'], '%s Shear Modulus' % fault['ID'])
if fault['Displacement_Length_Ratio']:
fault['Displacement_Length_Ratio'] = weight_list_to_tuple(
fault['Displacement_Length_Ratio'],
'%s Displacement to Length Ratio' % fault['ID'])
fault_source = mtkActiveFault(
fault['ID'],
fault['Fault_Name'],
fault_geometry,
weight_list_to_tuple(fault['Slip'], '%s - Slip' % fault['ID']),
float(fault['Rake']),
fault['Tectonic_Region'],
float(fault['Aseismic']),
weight_list_to_tuple(
fault['Scaling_Relation_Sigma'],
'%s Scaling_Relation_Sigma' % fault['ID']),
neotectonic_fault=None,
scale_rel=get_scaling_relation_tuple(
fault['Magnitude_Scaling_Relation']),
aspect_ratio=fault['Aspect_Ratio'],
shear_modulus=fault['Shear_Modulus'],
disp_length_ratio=fault['Displacement_Length_Ratio'])
if tectonic_reg:
fault_source.get_tectonic_regionalisation(
tectonic_reg,
fault['Tectonic_Region'])
assert isinstance(fault['MFD_Model'], list)
fault_source.generate_config_set(fault['MFD_Model'])
model.faults.append(fault_source)
return model, tectonic_reg | python | def read_file(self, mesh_spacing=1.0):
'''
Reads the file and returns an instance of the FaultSource class.
:param float mesh_spacing:
Fault mesh spacing (km)
'''
# Process the tectonic regionalisation
tectonic_reg = self.process_tectonic_regionalisation()
model = mtkActiveFaultModel(self.data['Fault_Model_ID'],
self.data['Fault_Model_Name'])
for fault in self.data['Fault_Model']:
fault_geometry = self.read_fault_geometry(fault['Fault_Geometry'],
mesh_spacing)
if fault['Shear_Modulus']:
fault['Shear_Modulus'] = weight_list_to_tuple(
fault['Shear_Modulus'], '%s Shear Modulus' % fault['ID'])
if fault['Displacement_Length_Ratio']:
fault['Displacement_Length_Ratio'] = weight_list_to_tuple(
fault['Displacement_Length_Ratio'],
'%s Displacement to Length Ratio' % fault['ID'])
fault_source = mtkActiveFault(
fault['ID'],
fault['Fault_Name'],
fault_geometry,
weight_list_to_tuple(fault['Slip'], '%s - Slip' % fault['ID']),
float(fault['Rake']),
fault['Tectonic_Region'],
float(fault['Aseismic']),
weight_list_to_tuple(
fault['Scaling_Relation_Sigma'],
'%s Scaling_Relation_Sigma' % fault['ID']),
neotectonic_fault=None,
scale_rel=get_scaling_relation_tuple(
fault['Magnitude_Scaling_Relation']),
aspect_ratio=fault['Aspect_Ratio'],
shear_modulus=fault['Shear_Modulus'],
disp_length_ratio=fault['Displacement_Length_Ratio'])
if tectonic_reg:
fault_source.get_tectonic_regionalisation(
tectonic_reg,
fault['Tectonic_Region'])
assert isinstance(fault['MFD_Model'], list)
fault_source.generate_config_set(fault['MFD_Model'])
model.faults.append(fault_source)
return model, tectonic_reg | [
"def",
"read_file",
"(",
"self",
",",
"mesh_spacing",
"=",
"1.0",
")",
":",
"# Process the tectonic regionalisation",
"tectonic_reg",
"=",
"self",
".",
"process_tectonic_regionalisation",
"(",
")",
"model",
"=",
"mtkActiveFaultModel",
"(",
"self",
".",
"data",
"[",
"'Fault_Model_ID'",
"]",
",",
"self",
".",
"data",
"[",
"'Fault_Model_Name'",
"]",
")",
"for",
"fault",
"in",
"self",
".",
"data",
"[",
"'Fault_Model'",
"]",
":",
"fault_geometry",
"=",
"self",
".",
"read_fault_geometry",
"(",
"fault",
"[",
"'Fault_Geometry'",
"]",
",",
"mesh_spacing",
")",
"if",
"fault",
"[",
"'Shear_Modulus'",
"]",
":",
"fault",
"[",
"'Shear_Modulus'",
"]",
"=",
"weight_list_to_tuple",
"(",
"fault",
"[",
"'Shear_Modulus'",
"]",
",",
"'%s Shear Modulus'",
"%",
"fault",
"[",
"'ID'",
"]",
")",
"if",
"fault",
"[",
"'Displacement_Length_Ratio'",
"]",
":",
"fault",
"[",
"'Displacement_Length_Ratio'",
"]",
"=",
"weight_list_to_tuple",
"(",
"fault",
"[",
"'Displacement_Length_Ratio'",
"]",
",",
"'%s Displacement to Length Ratio'",
"%",
"fault",
"[",
"'ID'",
"]",
")",
"fault_source",
"=",
"mtkActiveFault",
"(",
"fault",
"[",
"'ID'",
"]",
",",
"fault",
"[",
"'Fault_Name'",
"]",
",",
"fault_geometry",
",",
"weight_list_to_tuple",
"(",
"fault",
"[",
"'Slip'",
"]",
",",
"'%s - Slip'",
"%",
"fault",
"[",
"'ID'",
"]",
")",
",",
"float",
"(",
"fault",
"[",
"'Rake'",
"]",
")",
",",
"fault",
"[",
"'Tectonic_Region'",
"]",
",",
"float",
"(",
"fault",
"[",
"'Aseismic'",
"]",
")",
",",
"weight_list_to_tuple",
"(",
"fault",
"[",
"'Scaling_Relation_Sigma'",
"]",
",",
"'%s Scaling_Relation_Sigma'",
"%",
"fault",
"[",
"'ID'",
"]",
")",
",",
"neotectonic_fault",
"=",
"None",
",",
"scale_rel",
"=",
"get_scaling_relation_tuple",
"(",
"fault",
"[",
"'Magnitude_Scaling_Relation'",
"]",
")",
",",
"aspect_ratio",
"=",
"fault",
"[",
"'Aspect_Ratio'",
"]",
",",
"shear_modulus",
"=",
"fault",
"[",
"'Shear_Modulus'",
"]",
",",
"disp_length_ratio",
"=",
"fault",
"[",
"'Displacement_Length_Ratio'",
"]",
")",
"if",
"tectonic_reg",
":",
"fault_source",
".",
"get_tectonic_regionalisation",
"(",
"tectonic_reg",
",",
"fault",
"[",
"'Tectonic_Region'",
"]",
")",
"assert",
"isinstance",
"(",
"fault",
"[",
"'MFD_Model'",
"]",
",",
"list",
")",
"fault_source",
".",
"generate_config_set",
"(",
"fault",
"[",
"'MFD_Model'",
"]",
")",
"model",
".",
"faults",
".",
"append",
"(",
"fault_source",
")",
"return",
"model",
",",
"tectonic_reg"
] | Reads the file and returns an instance of the FaultSource class.
:param float mesh_spacing:
Fault mesh spacing (km) | [
"Reads",
"the",
"file",
"and",
"returns",
"an",
"instance",
"of",
"the",
"FaultSource",
"class",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L138-L189 | train | 232,948 |
gem/oq-engine | openquake/hmtk/parsers/faults/fault_yaml_parser.py | FaultYmltoSource.process_tectonic_regionalisation | def process_tectonic_regionalisation(self):
'''
Processes the tectonic regionalisation from the yaml file
'''
if 'tectonic_regionalisation' in self.data.keys():
tectonic_reg = TectonicRegionalisation()
tectonic_reg.populate_regions(
parse_tect_region_dict_to_tuples(
self.data['tectonic_regionalisation']))
else:
tectonic_reg = None
return tectonic_reg | python | def process_tectonic_regionalisation(self):
'''
Processes the tectonic regionalisation from the yaml file
'''
if 'tectonic_regionalisation' in self.data.keys():
tectonic_reg = TectonicRegionalisation()
tectonic_reg.populate_regions(
parse_tect_region_dict_to_tuples(
self.data['tectonic_regionalisation']))
else:
tectonic_reg = None
return tectonic_reg | [
"def",
"process_tectonic_regionalisation",
"(",
"self",
")",
":",
"if",
"'tectonic_regionalisation'",
"in",
"self",
".",
"data",
".",
"keys",
"(",
")",
":",
"tectonic_reg",
"=",
"TectonicRegionalisation",
"(",
")",
"tectonic_reg",
".",
"populate_regions",
"(",
"parse_tect_region_dict_to_tuples",
"(",
"self",
".",
"data",
"[",
"'tectonic_regionalisation'",
"]",
")",
")",
"else",
":",
"tectonic_reg",
"=",
"None",
"return",
"tectonic_reg"
] | Processes the tectonic regionalisation from the yaml file | [
"Processes",
"the",
"tectonic",
"regionalisation",
"from",
"the",
"yaml",
"file"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L191-L203 | train | 232,949 |
gem/oq-engine | openquake/hmtk/parsers/faults/fault_yaml_parser.py | FaultYmltoSource.read_fault_geometry | def read_fault_geometry(self, geo_dict, mesh_spacing=1.0):
'''
Creates the fault geometry from the parameters specified in the
dictionary.
:param dict geo_dict:
Sub-dictionary of main fault dictionary containing only
the geometry attributes
:param float mesh_spacing:
Fault mesh spacing (km)
:returns:
Instance of SimpleFaultGeometry or ComplexFaultGeometry, depending
on typology
'''
if geo_dict['Fault_Typology'] == 'Simple':
# Simple fault geometry
raw_trace = geo_dict['Fault_Trace']
trace = Line([Point(raw_trace[ival], raw_trace[ival + 1])
for ival in range(0, len(raw_trace), 2)])
geometry = SimpleFaultGeometry(trace,
geo_dict['Dip'],
geo_dict['Upper_Depth'],
geo_dict['Lower_Depth'],
mesh_spacing)
elif geo_dict['Fault_Typology'] == 'Complex':
# Complex Fault Typology
trace = []
for raw_trace in geo_dict['Fault_Trace']:
fault_edge = Line(
[Point(raw_trace[ival], raw_trace[ival + 1],
raw_trace[ival + 2]) for ival in range(0, len(raw_trace),
3)])
trace.append(fault_edge)
geometry = ComplexFaultGeometry(trace, mesh_spacing)
else:
raise ValueError('Unrecognised or unsupported fault geometry!')
return geometry | python | def read_fault_geometry(self, geo_dict, mesh_spacing=1.0):
'''
Creates the fault geometry from the parameters specified in the
dictionary.
:param dict geo_dict:
Sub-dictionary of main fault dictionary containing only
the geometry attributes
:param float mesh_spacing:
Fault mesh spacing (km)
:returns:
Instance of SimpleFaultGeometry or ComplexFaultGeometry, depending
on typology
'''
if geo_dict['Fault_Typology'] == 'Simple':
# Simple fault geometry
raw_trace = geo_dict['Fault_Trace']
trace = Line([Point(raw_trace[ival], raw_trace[ival + 1])
for ival in range(0, len(raw_trace), 2)])
geometry = SimpleFaultGeometry(trace,
geo_dict['Dip'],
geo_dict['Upper_Depth'],
geo_dict['Lower_Depth'],
mesh_spacing)
elif geo_dict['Fault_Typology'] == 'Complex':
# Complex Fault Typology
trace = []
for raw_trace in geo_dict['Fault_Trace']:
fault_edge = Line(
[Point(raw_trace[ival], raw_trace[ival + 1],
raw_trace[ival + 2]) for ival in range(0, len(raw_trace),
3)])
trace.append(fault_edge)
geometry = ComplexFaultGeometry(trace, mesh_spacing)
else:
raise ValueError('Unrecognised or unsupported fault geometry!')
return geometry | [
"def",
"read_fault_geometry",
"(",
"self",
",",
"geo_dict",
",",
"mesh_spacing",
"=",
"1.0",
")",
":",
"if",
"geo_dict",
"[",
"'Fault_Typology'",
"]",
"==",
"'Simple'",
":",
"# Simple fault geometry",
"raw_trace",
"=",
"geo_dict",
"[",
"'Fault_Trace'",
"]",
"trace",
"=",
"Line",
"(",
"[",
"Point",
"(",
"raw_trace",
"[",
"ival",
"]",
",",
"raw_trace",
"[",
"ival",
"+",
"1",
"]",
")",
"for",
"ival",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"raw_trace",
")",
",",
"2",
")",
"]",
")",
"geometry",
"=",
"SimpleFaultGeometry",
"(",
"trace",
",",
"geo_dict",
"[",
"'Dip'",
"]",
",",
"geo_dict",
"[",
"'Upper_Depth'",
"]",
",",
"geo_dict",
"[",
"'Lower_Depth'",
"]",
",",
"mesh_spacing",
")",
"elif",
"geo_dict",
"[",
"'Fault_Typology'",
"]",
"==",
"'Complex'",
":",
"# Complex Fault Typology",
"trace",
"=",
"[",
"]",
"for",
"raw_trace",
"in",
"geo_dict",
"[",
"'Fault_Trace'",
"]",
":",
"fault_edge",
"=",
"Line",
"(",
"[",
"Point",
"(",
"raw_trace",
"[",
"ival",
"]",
",",
"raw_trace",
"[",
"ival",
"+",
"1",
"]",
",",
"raw_trace",
"[",
"ival",
"+",
"2",
"]",
")",
"for",
"ival",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"raw_trace",
")",
",",
"3",
")",
"]",
")",
"trace",
".",
"append",
"(",
"fault_edge",
")",
"geometry",
"=",
"ComplexFaultGeometry",
"(",
"trace",
",",
"mesh_spacing",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unrecognised or unsupported fault geometry!'",
")",
"return",
"geometry"
] | Creates the fault geometry from the parameters specified in the
dictionary.
:param dict geo_dict:
Sub-dictionary of main fault dictionary containing only
the geometry attributes
:param float mesh_spacing:
Fault mesh spacing (km)
:returns:
Instance of SimpleFaultGeometry or ComplexFaultGeometry, depending
on typology | [
"Creates",
"the",
"fault",
"geometry",
"from",
"the",
"parameters",
"specified",
"in",
"the",
"dictionary",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L205-L242 | train | 232,950 |
gem/oq-engine | openquake/hazardlib/gsim/cauzzi_2014.py | CauzziEtAl2014._get_distance_scaling_term | def _get_distance_scaling_term(self, C, mag, rrup):
"""
Returns the distance scaling parameter
"""
return (C["r1"] + C["r2"] * mag) * np.log10(rrup + C["r3"]) | python | def _get_distance_scaling_term(self, C, mag, rrup):
"""
Returns the distance scaling parameter
"""
return (C["r1"] + C["r2"] * mag) * np.log10(rrup + C["r3"]) | [
"def",
"_get_distance_scaling_term",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rrup",
")",
":",
"return",
"(",
"C",
"[",
"\"r1\"",
"]",
"+",
"C",
"[",
"\"r2\"",
"]",
"*",
"mag",
")",
"*",
"np",
".",
"log10",
"(",
"rrup",
"+",
"C",
"[",
"\"r3\"",
"]",
")"
] | Returns the distance scaling parameter | [
"Returns",
"the",
"distance",
"scaling",
"parameter"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L132-L136 | train | 232,951 |
gem/oq-engine | openquake/hazardlib/gsim/cauzzi_2014.py | CauzziEtAl2014._get_style_of_faulting_term | def _get_style_of_faulting_term(self, C, rake):
"""
Returns the style of faulting term. Cauzzi et al. determind SOF from
the plunge of the B-, T- and P-axes. For consistency with existing
GMPEs the Wells & Coppersmith model is preferred
"""
if rake > -150.0 and rake <= -30.0:
return C['fN']
elif rake > 30.0 and rake <= 150.0:
return C['fR']
else:
return C['fSS'] | python | def _get_style_of_faulting_term(self, C, rake):
"""
Returns the style of faulting term. Cauzzi et al. determind SOF from
the plunge of the B-, T- and P-axes. For consistency with existing
GMPEs the Wells & Coppersmith model is preferred
"""
if rake > -150.0 and rake <= -30.0:
return C['fN']
elif rake > 30.0 and rake <= 150.0:
return C['fR']
else:
return C['fSS'] | [
"def",
"_get_style_of_faulting_term",
"(",
"self",
",",
"C",
",",
"rake",
")",
":",
"if",
"rake",
">",
"-",
"150.0",
"and",
"rake",
"<=",
"-",
"30.0",
":",
"return",
"C",
"[",
"'fN'",
"]",
"elif",
"rake",
">",
"30.0",
"and",
"rake",
"<=",
"150.0",
":",
"return",
"C",
"[",
"'fR'",
"]",
"else",
":",
"return",
"C",
"[",
"'fSS'",
"]"
] | Returns the style of faulting term. Cauzzi et al. determind SOF from
the plunge of the B-, T- and P-axes. For consistency with existing
GMPEs the Wells & Coppersmith model is preferred | [
"Returns",
"the",
"style",
"of",
"faulting",
"term",
".",
"Cauzzi",
"et",
"al",
".",
"determind",
"SOF",
"from",
"the",
"plunge",
"of",
"the",
"B",
"-",
"T",
"-",
"and",
"P",
"-",
"axes",
".",
"For",
"consistency",
"with",
"existing",
"GMPEs",
"the",
"Wells",
"&",
"Coppersmith",
"model",
"is",
"preferred"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L138-L149 | train | 232,952 |
gem/oq-engine | openquake/hazardlib/gsim/cauzzi_2014.py | CauzziEtAl2014Eurocode8._get_site_amplification_term | def _get_site_amplification_term(self, C, vs30):
"""
Returns the site amplification term on the basis of Eurocode 8
site class
"""
s_b, s_c, s_d = self._get_site_dummy_variables(vs30)
return (C["sB"] * s_b) + (C["sC"] * s_c) + (C["sD"] * s_d) | python | def _get_site_amplification_term(self, C, vs30):
"""
Returns the site amplification term on the basis of Eurocode 8
site class
"""
s_b, s_c, s_d = self._get_site_dummy_variables(vs30)
return (C["sB"] * s_b) + (C["sC"] * s_c) + (C["sD"] * s_d) | [
"def",
"_get_site_amplification_term",
"(",
"self",
",",
"C",
",",
"vs30",
")",
":",
"s_b",
",",
"s_c",
",",
"s_d",
"=",
"self",
".",
"_get_site_dummy_variables",
"(",
"vs30",
")",
"return",
"(",
"C",
"[",
"\"sB\"",
"]",
"*",
"s_b",
")",
"+",
"(",
"C",
"[",
"\"sC\"",
"]",
"*",
"s_c",
")",
"+",
"(",
"C",
"[",
"\"sD\"",
"]",
"*",
"s_d",
")"
] | Returns the site amplification term on the basis of Eurocode 8
site class | [
"Returns",
"the",
"site",
"amplification",
"term",
"on",
"the",
"basis",
"of",
"Eurocode",
"8",
"site",
"class"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L471-L477 | train | 232,953 |
gem/oq-engine | openquake/hazardlib/gsim/cauzzi_2014.py | CauzziEtAl2014Eurocode8._get_site_dummy_variables | def _get_site_dummy_variables(self, vs30):
"""
Returns the Eurocode 8 site class dummy variable
"""
s_b = np.zeros_like(vs30)
s_c = np.zeros_like(vs30)
s_d = np.zeros_like(vs30)
s_b[np.logical_and(vs30 >= 360., vs30 < 800.)] = 1.0
s_c[np.logical_and(vs30 >= 180., vs30 < 360.)] = 1.0
s_d[vs30 < 180] = 1.0
return s_b, s_c, s_d | python | def _get_site_dummy_variables(self, vs30):
"""
Returns the Eurocode 8 site class dummy variable
"""
s_b = np.zeros_like(vs30)
s_c = np.zeros_like(vs30)
s_d = np.zeros_like(vs30)
s_b[np.logical_and(vs30 >= 360., vs30 < 800.)] = 1.0
s_c[np.logical_and(vs30 >= 180., vs30 < 360.)] = 1.0
s_d[vs30 < 180] = 1.0
return s_b, s_c, s_d | [
"def",
"_get_site_dummy_variables",
"(",
"self",
",",
"vs30",
")",
":",
"s_b",
"=",
"np",
".",
"zeros_like",
"(",
"vs30",
")",
"s_c",
"=",
"np",
".",
"zeros_like",
"(",
"vs30",
")",
"s_d",
"=",
"np",
".",
"zeros_like",
"(",
"vs30",
")",
"s_b",
"[",
"np",
".",
"logical_and",
"(",
"vs30",
">=",
"360.",
",",
"vs30",
"<",
"800.",
")",
"]",
"=",
"1.0",
"s_c",
"[",
"np",
".",
"logical_and",
"(",
"vs30",
">=",
"180.",
",",
"vs30",
"<",
"360.",
")",
"]",
"=",
"1.0",
"s_d",
"[",
"vs30",
"<",
"180",
"]",
"=",
"1.0",
"return",
"s_b",
",",
"s_c",
",",
"s_d"
] | Returns the Eurocode 8 site class dummy variable | [
"Returns",
"the",
"Eurocode",
"8",
"site",
"class",
"dummy",
"variable"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L479-L489 | train | 232,954 |
gem/oq-engine | openquake/hmtk/faults/fault_models.py | RecurrenceBranch.get_recurrence | def get_recurrence(self, config):
'''
Calculates the recurrence model for the given settings as
an instance of the openquake.hmtk.models.IncrementalMFD
:param dict config:
Configuration settings of the magnitude frequency distribution.
'''
model = MFD_MAP[config['Model_Name']]()
model.setUp(config)
model.get_mmax(config, self.msr, self.rake, self.area)
model.mmax = model.mmax + (self.msr_sigma * model.mmax_sigma)
# As the Anderson & Luco arbitrary model requires the input of the
# displacement to length ratio
if 'AndersonLucoAreaMmax' in config['Model_Name']:
if not self.disp_length_ratio:
# If not defined then default to 1.25E-5
self.disp_length_ratio = 1.25E-5
min_mag, bin_width, occur_rates = model.get_mfd(
self.slip,
self.area, self.shear_modulus, self.disp_length_ratio)
else:
min_mag, bin_width, occur_rates = model.get_mfd(self.slip,
self.area,
self.shear_modulus)
self.recurrence = IncrementalMFD(min_mag, bin_width, occur_rates)
self.magnitudes = min_mag + np.cumsum(
bin_width *
np.ones(len(occur_rates), dtype=float)) - bin_width
self.max_mag = np.max(self.magnitudes) | python | def get_recurrence(self, config):
'''
Calculates the recurrence model for the given settings as
an instance of the openquake.hmtk.models.IncrementalMFD
:param dict config:
Configuration settings of the magnitude frequency distribution.
'''
model = MFD_MAP[config['Model_Name']]()
model.setUp(config)
model.get_mmax(config, self.msr, self.rake, self.area)
model.mmax = model.mmax + (self.msr_sigma * model.mmax_sigma)
# As the Anderson & Luco arbitrary model requires the input of the
# displacement to length ratio
if 'AndersonLucoAreaMmax' in config['Model_Name']:
if not self.disp_length_ratio:
# If not defined then default to 1.25E-5
self.disp_length_ratio = 1.25E-5
min_mag, bin_width, occur_rates = model.get_mfd(
self.slip,
self.area, self.shear_modulus, self.disp_length_ratio)
else:
min_mag, bin_width, occur_rates = model.get_mfd(self.slip,
self.area,
self.shear_modulus)
self.recurrence = IncrementalMFD(min_mag, bin_width, occur_rates)
self.magnitudes = min_mag + np.cumsum(
bin_width *
np.ones(len(occur_rates), dtype=float)) - bin_width
self.max_mag = np.max(self.magnitudes) | [
"def",
"get_recurrence",
"(",
"self",
",",
"config",
")",
":",
"model",
"=",
"MFD_MAP",
"[",
"config",
"[",
"'Model_Name'",
"]",
"]",
"(",
")",
"model",
".",
"setUp",
"(",
"config",
")",
"model",
".",
"get_mmax",
"(",
"config",
",",
"self",
".",
"msr",
",",
"self",
".",
"rake",
",",
"self",
".",
"area",
")",
"model",
".",
"mmax",
"=",
"model",
".",
"mmax",
"+",
"(",
"self",
".",
"msr_sigma",
"*",
"model",
".",
"mmax_sigma",
")",
"# As the Anderson & Luco arbitrary model requires the input of the",
"# displacement to length ratio",
"if",
"'AndersonLucoAreaMmax'",
"in",
"config",
"[",
"'Model_Name'",
"]",
":",
"if",
"not",
"self",
".",
"disp_length_ratio",
":",
"# If not defined then default to 1.25E-5",
"self",
".",
"disp_length_ratio",
"=",
"1.25E-5",
"min_mag",
",",
"bin_width",
",",
"occur_rates",
"=",
"model",
".",
"get_mfd",
"(",
"self",
".",
"slip",
",",
"self",
".",
"area",
",",
"self",
".",
"shear_modulus",
",",
"self",
".",
"disp_length_ratio",
")",
"else",
":",
"min_mag",
",",
"bin_width",
",",
"occur_rates",
"=",
"model",
".",
"get_mfd",
"(",
"self",
".",
"slip",
",",
"self",
".",
"area",
",",
"self",
".",
"shear_modulus",
")",
"self",
".",
"recurrence",
"=",
"IncrementalMFD",
"(",
"min_mag",
",",
"bin_width",
",",
"occur_rates",
")",
"self",
".",
"magnitudes",
"=",
"min_mag",
"+",
"np",
".",
"cumsum",
"(",
"bin_width",
"*",
"np",
".",
"ones",
"(",
"len",
"(",
"occur_rates",
")",
",",
"dtype",
"=",
"float",
")",
")",
"-",
"bin_width",
"self",
".",
"max_mag",
"=",
"np",
".",
"max",
"(",
"self",
".",
"magnitudes",
")"
] | Calculates the recurrence model for the given settings as
an instance of the openquake.hmtk.models.IncrementalMFD
:param dict config:
Configuration settings of the magnitude frequency distribution. | [
"Calculates",
"the",
"recurrence",
"model",
"for",
"the",
"given",
"settings",
"as",
"an",
"instance",
"of",
"the",
"openquake",
".",
"hmtk",
".",
"models",
".",
"IncrementalMFD"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L145-L177 | train | 232,955 |
gem/oq-engine | openquake/hmtk/faults/fault_models.py | mtkActiveFault.get_tectonic_regionalisation | def get_tectonic_regionalisation(self, regionalisation, region_type=None):
'''
Defines the tectonic region and updates the shear modulus,
magnitude scaling relation and displacement to length ratio using
the regional values, if not previously defined for the fault
:param regionalistion:
Instance of the :class:
openquake.hmtk.faults.tectonic_regionalisaion.TectonicRegionalisation
:param str region_type:
Name of the region type - if not in regionalisation an error will
be raised
'''
if region_type:
self.trt = region_type
if not self.trt in regionalisation.key_list:
raise ValueError('Tectonic region classification missing or '
'not defined in regionalisation')
for iloc, key_val in enumerate(regionalisation.key_list):
if self.trt in key_val:
self.regionalisation = regionalisation.regionalisation[iloc]
# Update undefined shear modulus from tectonic regionalisation
if not self.shear_modulus:
self.shear_modulus = self.regionalisation.shear_modulus
# Update undefined scaling relation from tectonic
# regionalisation
if not self.msr:
self.msr = self.regionalisation.scaling_rel
# Update undefined displacement to length ratio from tectonic
# regionalisation
if not self.disp_length_ratio:
self.disp_length_ratio = \
self.regionalisation.disp_length_ratio
break
return | python | def get_tectonic_regionalisation(self, regionalisation, region_type=None):
'''
Defines the tectonic region and updates the shear modulus,
magnitude scaling relation and displacement to length ratio using
the regional values, if not previously defined for the fault
:param regionalistion:
Instance of the :class:
openquake.hmtk.faults.tectonic_regionalisaion.TectonicRegionalisation
:param str region_type:
Name of the region type - if not in regionalisation an error will
be raised
'''
if region_type:
self.trt = region_type
if not self.trt in regionalisation.key_list:
raise ValueError('Tectonic region classification missing or '
'not defined in regionalisation')
for iloc, key_val in enumerate(regionalisation.key_list):
if self.trt in key_val:
self.regionalisation = regionalisation.regionalisation[iloc]
# Update undefined shear modulus from tectonic regionalisation
if not self.shear_modulus:
self.shear_modulus = self.regionalisation.shear_modulus
# Update undefined scaling relation from tectonic
# regionalisation
if not self.msr:
self.msr = self.regionalisation.scaling_rel
# Update undefined displacement to length ratio from tectonic
# regionalisation
if not self.disp_length_ratio:
self.disp_length_ratio = \
self.regionalisation.disp_length_ratio
break
return | [
"def",
"get_tectonic_regionalisation",
"(",
"self",
",",
"regionalisation",
",",
"region_type",
"=",
"None",
")",
":",
"if",
"region_type",
":",
"self",
".",
"trt",
"=",
"region_type",
"if",
"not",
"self",
".",
"trt",
"in",
"regionalisation",
".",
"key_list",
":",
"raise",
"ValueError",
"(",
"'Tectonic region classification missing or '",
"'not defined in regionalisation'",
")",
"for",
"iloc",
",",
"key_val",
"in",
"enumerate",
"(",
"regionalisation",
".",
"key_list",
")",
":",
"if",
"self",
".",
"trt",
"in",
"key_val",
":",
"self",
".",
"regionalisation",
"=",
"regionalisation",
".",
"regionalisation",
"[",
"iloc",
"]",
"# Update undefined shear modulus from tectonic regionalisation",
"if",
"not",
"self",
".",
"shear_modulus",
":",
"self",
".",
"shear_modulus",
"=",
"self",
".",
"regionalisation",
".",
"shear_modulus",
"# Update undefined scaling relation from tectonic",
"# regionalisation",
"if",
"not",
"self",
".",
"msr",
":",
"self",
".",
"msr",
"=",
"self",
".",
"regionalisation",
".",
"scaling_rel",
"# Update undefined displacement to length ratio from tectonic",
"# regionalisation",
"if",
"not",
"self",
".",
"disp_length_ratio",
":",
"self",
".",
"disp_length_ratio",
"=",
"self",
".",
"regionalisation",
".",
"disp_length_ratio",
"break",
"return"
] | Defines the tectonic region and updates the shear modulus,
magnitude scaling relation and displacement to length ratio using
the regional values, if not previously defined for the fault
:param regionalistion:
Instance of the :class:
openquake.hmtk.faults.tectonic_regionalisaion.TectonicRegionalisation
:param str region_type:
Name of the region type - if not in regionalisation an error will
be raised | [
"Defines",
"the",
"tectonic",
"region",
"and",
"updates",
"the",
"shear",
"modulus",
"magnitude",
"scaling",
"relation",
"and",
"displacement",
"to",
"length",
"ratio",
"using",
"the",
"regional",
"values",
"if",
"not",
"previously",
"defined",
"for",
"the",
"fault"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L265-L301 | train | 232,956 |
gem/oq-engine | openquake/hmtk/faults/fault_models.py | mtkActiveFault.select_catalogue | def select_catalogue(self, selector, distance, distance_metric="rupture",
upper_eq_depth=None, lower_eq_depth=None):
"""
Select earthquakes within a specied distance of the fault
"""
if selector.catalogue.get_number_events() < 1:
raise ValueError('No events found in catalogue!')
# rupture metric is selected
if ('rupture' in distance_metric):
# Use rupture distance
self.catalogue = selector.within_rupture_distance(
self.geometry.surface,
distance,
upper_depth=upper_eq_depth,
lower_depth=lower_eq_depth)
else:
# Use Joyner-Boore distance
self.catalogue = selector.within_joyner_boore_distance(
self.geometry.surface,
distance,
upper_depth=upper_eq_depth,
lower_depth=lower_eq_depth) | python | def select_catalogue(self, selector, distance, distance_metric="rupture",
upper_eq_depth=None, lower_eq_depth=None):
"""
Select earthquakes within a specied distance of the fault
"""
if selector.catalogue.get_number_events() < 1:
raise ValueError('No events found in catalogue!')
# rupture metric is selected
if ('rupture' in distance_metric):
# Use rupture distance
self.catalogue = selector.within_rupture_distance(
self.geometry.surface,
distance,
upper_depth=upper_eq_depth,
lower_depth=lower_eq_depth)
else:
# Use Joyner-Boore distance
self.catalogue = selector.within_joyner_boore_distance(
self.geometry.surface,
distance,
upper_depth=upper_eq_depth,
lower_depth=lower_eq_depth) | [
"def",
"select_catalogue",
"(",
"self",
",",
"selector",
",",
"distance",
",",
"distance_metric",
"=",
"\"rupture\"",
",",
"upper_eq_depth",
"=",
"None",
",",
"lower_eq_depth",
"=",
"None",
")",
":",
"if",
"selector",
".",
"catalogue",
".",
"get_number_events",
"(",
")",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"'No events found in catalogue!'",
")",
"# rupture metric is selected",
"if",
"(",
"'rupture'",
"in",
"distance_metric",
")",
":",
"# Use rupture distance",
"self",
".",
"catalogue",
"=",
"selector",
".",
"within_rupture_distance",
"(",
"self",
".",
"geometry",
".",
"surface",
",",
"distance",
",",
"upper_depth",
"=",
"upper_eq_depth",
",",
"lower_depth",
"=",
"lower_eq_depth",
")",
"else",
":",
"# Use Joyner-Boore distance",
"self",
".",
"catalogue",
"=",
"selector",
".",
"within_joyner_boore_distance",
"(",
"self",
".",
"geometry",
".",
"surface",
",",
"distance",
",",
"upper_depth",
"=",
"upper_eq_depth",
",",
"lower_depth",
"=",
"lower_eq_depth",
")"
] | Select earthquakes within a specied distance of the fault | [
"Select",
"earthquakes",
"within",
"a",
"specied",
"distance",
"of",
"the",
"fault"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L303-L325 | train | 232,957 |
gem/oq-engine | openquake/hmtk/faults/fault_models.py | mtkActiveFault.generate_config_set | def generate_config_set(self, config):
'''
Generates a list of magnitude frequency distributions and renders as
a tuple
:param dict/list config:
Configuration paramters of magnitude frequency distribution
'''
if isinstance(config, dict):
# Configuration list contains only one element
self.config = [(config, 1.0)]
elif isinstance(config, list):
# Multiple configurations with correscponding weights
total_weight = 0.
self.config = []
for params in config:
weight = params['Model_Weight']
total_weight += params['Model_Weight']
self.config.append((params, weight))
if fabs(total_weight - 1.0) > 1E-7:
raise ValueError('MFD config weights do not sum to 1.0 for '
'fault %s' % self.id)
else:
raise ValueError('MFD config must be input as dictionary or list!') | python | def generate_config_set(self, config):
'''
Generates a list of magnitude frequency distributions and renders as
a tuple
:param dict/list config:
Configuration paramters of magnitude frequency distribution
'''
if isinstance(config, dict):
# Configuration list contains only one element
self.config = [(config, 1.0)]
elif isinstance(config, list):
# Multiple configurations with correscponding weights
total_weight = 0.
self.config = []
for params in config:
weight = params['Model_Weight']
total_weight += params['Model_Weight']
self.config.append((params, weight))
if fabs(total_weight - 1.0) > 1E-7:
raise ValueError('MFD config weights do not sum to 1.0 for '
'fault %s' % self.id)
else:
raise ValueError('MFD config must be input as dictionary or list!') | [
"def",
"generate_config_set",
"(",
"self",
",",
"config",
")",
":",
"if",
"isinstance",
"(",
"config",
",",
"dict",
")",
":",
"# Configuration list contains only one element",
"self",
".",
"config",
"=",
"[",
"(",
"config",
",",
"1.0",
")",
"]",
"elif",
"isinstance",
"(",
"config",
",",
"list",
")",
":",
"# Multiple configurations with correscponding weights",
"total_weight",
"=",
"0.",
"self",
".",
"config",
"=",
"[",
"]",
"for",
"params",
"in",
"config",
":",
"weight",
"=",
"params",
"[",
"'Model_Weight'",
"]",
"total_weight",
"+=",
"params",
"[",
"'Model_Weight'",
"]",
"self",
".",
"config",
".",
"append",
"(",
"(",
"params",
",",
"weight",
")",
")",
"if",
"fabs",
"(",
"total_weight",
"-",
"1.0",
")",
">",
"1E-7",
":",
"raise",
"ValueError",
"(",
"'MFD config weights do not sum to 1.0 for '",
"'fault %s'",
"%",
"self",
".",
"id",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'MFD config must be input as dictionary or list!'",
")"
] | Generates a list of magnitude frequency distributions and renders as
a tuple
:param dict/list config:
Configuration paramters of magnitude frequency distribution | [
"Generates",
"a",
"list",
"of",
"magnitude",
"frequency",
"distributions",
"and",
"renders",
"as",
"a",
"tuple"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L365-L388 | train | 232,958 |
gem/oq-engine | openquake/hmtk/faults/fault_models.py | mtkActiveFault.collapse_branches | def collapse_branches(self, mmin, bin_width, mmax):
'''
Collapse the logic tree branches into a single IncrementalMFD
:param float mmin:
Minimum magnitude of reference mfd
:param float bin_width:
Bin width of reference mfd
:param float mmax:
Maximum magnitude of reference mfd
:returns:
:class: openquake.hmtk.models.IncrementalMFD
'''
master_mags = np.arange(mmin, mmax + (bin_width / 2.), bin_width)
master_rates = np.zeros(len(master_mags), dtype=float)
for model in self.mfd_models:
id0 = np.logical_and(
master_mags >= np.min(model.magnitudes) - 1E-9,
master_mags <= np.max(model.magnitudes) + 1E-9)
# Use interpolation in log10-y values
yvals = np.log10(model.recurrence.occur_rates)
interp_y = np.interp(master_mags[id0],
model.magnitudes,
yvals)
master_rates[id0] = master_rates[id0] + (model.weight *
10. ** interp_y)
return IncrementalMFD(mmin, bin_width, master_rates) | python | def collapse_branches(self, mmin, bin_width, mmax):
'''
Collapse the logic tree branches into a single IncrementalMFD
:param float mmin:
Minimum magnitude of reference mfd
:param float bin_width:
Bin width of reference mfd
:param float mmax:
Maximum magnitude of reference mfd
:returns:
:class: openquake.hmtk.models.IncrementalMFD
'''
master_mags = np.arange(mmin, mmax + (bin_width / 2.), bin_width)
master_rates = np.zeros(len(master_mags), dtype=float)
for model in self.mfd_models:
id0 = np.logical_and(
master_mags >= np.min(model.magnitudes) - 1E-9,
master_mags <= np.max(model.magnitudes) + 1E-9)
# Use interpolation in log10-y values
yvals = np.log10(model.recurrence.occur_rates)
interp_y = np.interp(master_mags[id0],
model.magnitudes,
yvals)
master_rates[id0] = master_rates[id0] + (model.weight *
10. ** interp_y)
return IncrementalMFD(mmin, bin_width, master_rates) | [
"def",
"collapse_branches",
"(",
"self",
",",
"mmin",
",",
"bin_width",
",",
"mmax",
")",
":",
"master_mags",
"=",
"np",
".",
"arange",
"(",
"mmin",
",",
"mmax",
"+",
"(",
"bin_width",
"/",
"2.",
")",
",",
"bin_width",
")",
"master_rates",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"master_mags",
")",
",",
"dtype",
"=",
"float",
")",
"for",
"model",
"in",
"self",
".",
"mfd_models",
":",
"id0",
"=",
"np",
".",
"logical_and",
"(",
"master_mags",
">=",
"np",
".",
"min",
"(",
"model",
".",
"magnitudes",
")",
"-",
"1E-9",
",",
"master_mags",
"<=",
"np",
".",
"max",
"(",
"model",
".",
"magnitudes",
")",
"+",
"1E-9",
")",
"# Use interpolation in log10-y values",
"yvals",
"=",
"np",
".",
"log10",
"(",
"model",
".",
"recurrence",
".",
"occur_rates",
")",
"interp_y",
"=",
"np",
".",
"interp",
"(",
"master_mags",
"[",
"id0",
"]",
",",
"model",
".",
"magnitudes",
",",
"yvals",
")",
"master_rates",
"[",
"id0",
"]",
"=",
"master_rates",
"[",
"id0",
"]",
"+",
"(",
"model",
".",
"weight",
"*",
"10.",
"**",
"interp_y",
")",
"return",
"IncrementalMFD",
"(",
"mmin",
",",
"bin_width",
",",
"master_rates",
")"
] | Collapse the logic tree branches into a single IncrementalMFD
:param float mmin:
Minimum magnitude of reference mfd
:param float bin_width:
Bin width of reference mfd
:param float mmax:
Maximum magnitude of reference mfd
:returns:
:class: openquake.hmtk.models.IncrementalMFD | [
"Collapse",
"the",
"logic",
"tree",
"branches",
"into",
"a",
"single",
"IncrementalMFD"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L479-L507 | train | 232,959 |
gem/oq-engine | openquake/hmtk/faults/fault_models.py | mtkActiveFault.generate_fault_source_model | def generate_fault_source_model(self):
'''
Creates a resulting `openquake.hmtk` fault source set.
:returns:
source_model - list of instances of either the :class:
`openquake.hmtk.sources.simple_fault_source.mtkSimpleFaultSource`
or :class:
`openquake.hmtk.sources.complex_fault_source.mtkComplexFaultSource`
model_weight - Corresponding weights for each source model
'''
source_model = []
model_weight = []
for iloc in range(0, self.get_number_mfd_models()):
model_mfd = EvenlyDiscretizedMFD(
self.mfd[0][iloc].min_mag,
self.mfd[0][iloc].bin_width,
self.mfd[0][iloc].occur_rates.tolist())
if isinstance(self.geometry, ComplexFaultGeometry):
# Complex fault class
source = mtkComplexFaultSource(
self.id,
self.name,
self.trt,
self.geometry.surface,
self.mfd[2][iloc],
self.rupt_aspect_ratio,
model_mfd,
self.rake)
source.fault_edges = self.geometry.trace
else:
# Simple Fault source
source = mtkSimpleFaultSource(
self.id,
self.name,
self.trt,
self.geometry.surface,
self.geometry.dip,
self.geometry.upper_depth,
self.geometry.lower_depth,
self.mfd[2][iloc],
self.rupt_aspect_ratio,
model_mfd,
self.rake)
source.fault_trace = self.geometry.trace
source_model.append(source)
model_weight.append(self.mfd[1][iloc])
return source_model, model_weight | python | def generate_fault_source_model(self):
'''
Creates a resulting `openquake.hmtk` fault source set.
:returns:
source_model - list of instances of either the :class:
`openquake.hmtk.sources.simple_fault_source.mtkSimpleFaultSource`
or :class:
`openquake.hmtk.sources.complex_fault_source.mtkComplexFaultSource`
model_weight - Corresponding weights for each source model
'''
source_model = []
model_weight = []
for iloc in range(0, self.get_number_mfd_models()):
model_mfd = EvenlyDiscretizedMFD(
self.mfd[0][iloc].min_mag,
self.mfd[0][iloc].bin_width,
self.mfd[0][iloc].occur_rates.tolist())
if isinstance(self.geometry, ComplexFaultGeometry):
# Complex fault class
source = mtkComplexFaultSource(
self.id,
self.name,
self.trt,
self.geometry.surface,
self.mfd[2][iloc],
self.rupt_aspect_ratio,
model_mfd,
self.rake)
source.fault_edges = self.geometry.trace
else:
# Simple Fault source
source = mtkSimpleFaultSource(
self.id,
self.name,
self.trt,
self.geometry.surface,
self.geometry.dip,
self.geometry.upper_depth,
self.geometry.lower_depth,
self.mfd[2][iloc],
self.rupt_aspect_ratio,
model_mfd,
self.rake)
source.fault_trace = self.geometry.trace
source_model.append(source)
model_weight.append(self.mfd[1][iloc])
return source_model, model_weight | [
"def",
"generate_fault_source_model",
"(",
"self",
")",
":",
"source_model",
"=",
"[",
"]",
"model_weight",
"=",
"[",
"]",
"for",
"iloc",
"in",
"range",
"(",
"0",
",",
"self",
".",
"get_number_mfd_models",
"(",
")",
")",
":",
"model_mfd",
"=",
"EvenlyDiscretizedMFD",
"(",
"self",
".",
"mfd",
"[",
"0",
"]",
"[",
"iloc",
"]",
".",
"min_mag",
",",
"self",
".",
"mfd",
"[",
"0",
"]",
"[",
"iloc",
"]",
".",
"bin_width",
",",
"self",
".",
"mfd",
"[",
"0",
"]",
"[",
"iloc",
"]",
".",
"occur_rates",
".",
"tolist",
"(",
")",
")",
"if",
"isinstance",
"(",
"self",
".",
"geometry",
",",
"ComplexFaultGeometry",
")",
":",
"# Complex fault class",
"source",
"=",
"mtkComplexFaultSource",
"(",
"self",
".",
"id",
",",
"self",
".",
"name",
",",
"self",
".",
"trt",
",",
"self",
".",
"geometry",
".",
"surface",
",",
"self",
".",
"mfd",
"[",
"2",
"]",
"[",
"iloc",
"]",
",",
"self",
".",
"rupt_aspect_ratio",
",",
"model_mfd",
",",
"self",
".",
"rake",
")",
"source",
".",
"fault_edges",
"=",
"self",
".",
"geometry",
".",
"trace",
"else",
":",
"# Simple Fault source",
"source",
"=",
"mtkSimpleFaultSource",
"(",
"self",
".",
"id",
",",
"self",
".",
"name",
",",
"self",
".",
"trt",
",",
"self",
".",
"geometry",
".",
"surface",
",",
"self",
".",
"geometry",
".",
"dip",
",",
"self",
".",
"geometry",
".",
"upper_depth",
",",
"self",
".",
"geometry",
".",
"lower_depth",
",",
"self",
".",
"mfd",
"[",
"2",
"]",
"[",
"iloc",
"]",
",",
"self",
".",
"rupt_aspect_ratio",
",",
"model_mfd",
",",
"self",
".",
"rake",
")",
"source",
".",
"fault_trace",
"=",
"self",
".",
"geometry",
".",
"trace",
"source_model",
".",
"append",
"(",
"source",
")",
"model_weight",
".",
"append",
"(",
"self",
".",
"mfd",
"[",
"1",
"]",
"[",
"iloc",
"]",
")",
"return",
"source_model",
",",
"model_weight"
] | Creates a resulting `openquake.hmtk` fault source set.
:returns:
source_model - list of instances of either the :class:
`openquake.hmtk.sources.simple_fault_source.mtkSimpleFaultSource`
or :class:
`openquake.hmtk.sources.complex_fault_source.mtkComplexFaultSource`
model_weight - Corresponding weights for each source model | [
"Creates",
"a",
"resulting",
"openquake",
".",
"hmtk",
"fault",
"source",
"set",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L509-L557 | train | 232,960 |
gem/oq-engine | openquake/hmtk/models.py | SeismicSource.attrib | def attrib(self):
"""
General XML element attributes for a seismic source, as a dict.
"""
return dict([
('id', str(self.id)),
('name', str(self.name)),
('tectonicRegion', str(self.trt)),
]) | python | def attrib(self):
"""
General XML element attributes for a seismic source, as a dict.
"""
return dict([
('id', str(self.id)),
('name', str(self.name)),
('tectonicRegion', str(self.trt)),
]) | [
"def",
"attrib",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"'id'",
",",
"str",
"(",
"self",
".",
"id",
")",
")",
",",
"(",
"'name'",
",",
"str",
"(",
"self",
".",
"name",
")",
")",
",",
"(",
"'tectonicRegion'",
",",
"str",
"(",
"self",
".",
"trt",
")",
")",
",",
"]",
")"
] | General XML element attributes for a seismic source, as a dict. | [
"General",
"XML",
"element",
"attributes",
"for",
"a",
"seismic",
"source",
"as",
"a",
"dict",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/models.py#L53-L61 | train | 232,961 |
gem/oq-engine | openquake/hmtk/models.py | TGRMFD.attrib | def attrib(self):
"""
An dict of XML element attributes for this MFD.
"""
return dict([
('aValue', str(self.a_val)),
('bValue', str(self.b_val)),
('minMag', str(self.min_mag)),
('maxMag', str(self.max_mag)),
]) | python | def attrib(self):
"""
An dict of XML element attributes for this MFD.
"""
return dict([
('aValue', str(self.a_val)),
('bValue', str(self.b_val)),
('minMag', str(self.min_mag)),
('maxMag', str(self.max_mag)),
]) | [
"def",
"attrib",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"'aValue'",
",",
"str",
"(",
"self",
".",
"a_val",
")",
")",
",",
"(",
"'bValue'",
",",
"str",
"(",
"self",
".",
"b_val",
")",
")",
",",
"(",
"'minMag'",
",",
"str",
"(",
"self",
".",
"min_mag",
")",
")",
",",
"(",
"'maxMag'",
",",
"str",
"(",
"self",
".",
"max_mag",
")",
")",
",",
"]",
")"
] | An dict of XML element attributes for this MFD. | [
"An",
"dict",
"of",
"XML",
"element",
"attributes",
"for",
"this",
"MFD",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/models.py#L325-L334 | train | 232,962 |
gem/oq-engine | openquake/hmtk/models.py | NodalPlane.attrib | def attrib(self):
"""
A dict of XML element attributes for this NodalPlane.
"""
return dict([
('probability', str(self.probability)),
('strike', str(self.strike)),
('dip', str(self.dip)),
('rake', str(self.rake)),
]) | python | def attrib(self):
"""
A dict of XML element attributes for this NodalPlane.
"""
return dict([
('probability', str(self.probability)),
('strike', str(self.strike)),
('dip', str(self.dip)),
('rake', str(self.rake)),
]) | [
"def",
"attrib",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"'probability'",
",",
"str",
"(",
"self",
".",
"probability",
")",
")",
",",
"(",
"'strike'",
",",
"str",
"(",
"self",
".",
"strike",
")",
")",
",",
"(",
"'dip'",
",",
"str",
"(",
"self",
".",
"dip",
")",
")",
",",
"(",
"'rake'",
",",
"str",
"(",
"self",
".",
"rake",
")",
")",
",",
"]",
")"
] | A dict of XML element attributes for this NodalPlane. | [
"A",
"dict",
"of",
"XML",
"element",
"attributes",
"for",
"this",
"NodalPlane",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/models.py#L359-L368 | train | 232,963 |
gem/oq-engine | openquake/hazardlib/correlation.py | jbcorrelation | def jbcorrelation(sites_or_distances, imt, vs30_clustering=False):
"""
Returns the Jayaram-Baker correlation model.
:param sites_or_distances:
SiteCollection instance o ristance matrix
:param imt:
Intensity Measure Type (PGA or SA)
:param vs30_clustering:
flag, defalt false
"""
if hasattr(sites_or_distances, 'mesh'):
distances = sites_or_distances.mesh.get_distance_matrix()
else:
distances = sites_or_distances
# formulae are from page 1700
if imt.period < 1:
if not vs30_clustering:
# case 1, eq. (17)
b = 8.5 + 17.2 * imt.period
else:
# case 2, eq. (18)
b = 40.7 - 15.0 * imt.period
else:
# both cases, eq. (19)
b = 22.0 + 3.7 * imt.period
# eq. (20)
return numpy.exp((- 3.0 / b) * distances) | python | def jbcorrelation(sites_or_distances, imt, vs30_clustering=False):
"""
Returns the Jayaram-Baker correlation model.
:param sites_or_distances:
SiteCollection instance o ristance matrix
:param imt:
Intensity Measure Type (PGA or SA)
:param vs30_clustering:
flag, defalt false
"""
if hasattr(sites_or_distances, 'mesh'):
distances = sites_or_distances.mesh.get_distance_matrix()
else:
distances = sites_or_distances
# formulae are from page 1700
if imt.period < 1:
if not vs30_clustering:
# case 1, eq. (17)
b = 8.5 + 17.2 * imt.period
else:
# case 2, eq. (18)
b = 40.7 - 15.0 * imt.period
else:
# both cases, eq. (19)
b = 22.0 + 3.7 * imt.period
# eq. (20)
return numpy.exp((- 3.0 / b) * distances) | [
"def",
"jbcorrelation",
"(",
"sites_or_distances",
",",
"imt",
",",
"vs30_clustering",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"sites_or_distances",
",",
"'mesh'",
")",
":",
"distances",
"=",
"sites_or_distances",
".",
"mesh",
".",
"get_distance_matrix",
"(",
")",
"else",
":",
"distances",
"=",
"sites_or_distances",
"# formulae are from page 1700",
"if",
"imt",
".",
"period",
"<",
"1",
":",
"if",
"not",
"vs30_clustering",
":",
"# case 1, eq. (17)",
"b",
"=",
"8.5",
"+",
"17.2",
"*",
"imt",
".",
"period",
"else",
":",
"# case 2, eq. (18)",
"b",
"=",
"40.7",
"-",
"15.0",
"*",
"imt",
".",
"period",
"else",
":",
"# both cases, eq. (19)",
"b",
"=",
"22.0",
"+",
"3.7",
"*",
"imt",
".",
"period",
"# eq. (20)",
"return",
"numpy",
".",
"exp",
"(",
"(",
"-",
"3.0",
"/",
"b",
")",
"*",
"distances",
")"
] | Returns the Jayaram-Baker correlation model.
:param sites_or_distances:
SiteCollection instance o ristance matrix
:param imt:
Intensity Measure Type (PGA or SA)
:param vs30_clustering:
flag, defalt false | [
"Returns",
"the",
"Jayaram",
"-",
"Baker",
"correlation",
"model",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/correlation.py#L116-L145 | train | 232,964 |
gem/oq-engine | openquake/hazardlib/correlation.py | hmcorrelation | def hmcorrelation(sites_or_distances, imt, uncertainty_multiplier=0):
"""
Returns the Heresi-Miranda correlation model.
:param sites_or_distances:
SiteCollection instance o distance matrix
:param imt:
Intensity Measure Type (PGA or SA)
:param uncertainty_multiplier:
Value to be multiplied by the uncertainty in the correlation parameter
beta. If uncertainty_multiplier = 0 (default), the median value is
used as a constant value.
"""
if hasattr(sites_or_distances, 'mesh'):
distances = sites_or_distances.mesh.get_distance_matrix()
else:
distances = sites_or_distances
period = imt.period
# Eq. (9)
if period < 1.37:
Med_b = 4.231 * period * period - 5.180 * period + 13.392
else:
Med_b = 0.140 * period * period - 2.249 * period + 17.050
# Eq. (10)
Std_b = (4.63e-3 * period*period + 0.028 * period + 0.713)
# Obtain realization of b
if uncertainty_multiplier == 0:
beta = Med_b
else:
beta = numpy.random.lognormal(
numpy.log(Med_b), Std_b * uncertainty_multiplier)
# Eq. (8)
return numpy.exp(-numpy.power((distances / beta), 0.55)) | python | def hmcorrelation(sites_or_distances, imt, uncertainty_multiplier=0):
"""
Returns the Heresi-Miranda correlation model.
:param sites_or_distances:
SiteCollection instance o distance matrix
:param imt:
Intensity Measure Type (PGA or SA)
:param uncertainty_multiplier:
Value to be multiplied by the uncertainty in the correlation parameter
beta. If uncertainty_multiplier = 0 (default), the median value is
used as a constant value.
"""
if hasattr(sites_or_distances, 'mesh'):
distances = sites_or_distances.mesh.get_distance_matrix()
else:
distances = sites_or_distances
period = imt.period
# Eq. (9)
if period < 1.37:
Med_b = 4.231 * period * period - 5.180 * period + 13.392
else:
Med_b = 0.140 * period * period - 2.249 * period + 17.050
# Eq. (10)
Std_b = (4.63e-3 * period*period + 0.028 * period + 0.713)
# Obtain realization of b
if uncertainty_multiplier == 0:
beta = Med_b
else:
beta = numpy.random.lognormal(
numpy.log(Med_b), Std_b * uncertainty_multiplier)
# Eq. (8)
return numpy.exp(-numpy.power((distances / beta), 0.55)) | [
"def",
"hmcorrelation",
"(",
"sites_or_distances",
",",
"imt",
",",
"uncertainty_multiplier",
"=",
"0",
")",
":",
"if",
"hasattr",
"(",
"sites_or_distances",
",",
"'mesh'",
")",
":",
"distances",
"=",
"sites_or_distances",
".",
"mesh",
".",
"get_distance_matrix",
"(",
")",
"else",
":",
"distances",
"=",
"sites_or_distances",
"period",
"=",
"imt",
".",
"period",
"# Eq. (9)",
"if",
"period",
"<",
"1.37",
":",
"Med_b",
"=",
"4.231",
"*",
"period",
"*",
"period",
"-",
"5.180",
"*",
"period",
"+",
"13.392",
"else",
":",
"Med_b",
"=",
"0.140",
"*",
"period",
"*",
"period",
"-",
"2.249",
"*",
"period",
"+",
"17.050",
"# Eq. (10)",
"Std_b",
"=",
"(",
"4.63e-3",
"*",
"period",
"*",
"period",
"+",
"0.028",
"*",
"period",
"+",
"0.713",
")",
"# Obtain realization of b",
"if",
"uncertainty_multiplier",
"==",
"0",
":",
"beta",
"=",
"Med_b",
"else",
":",
"beta",
"=",
"numpy",
".",
"random",
".",
"lognormal",
"(",
"numpy",
".",
"log",
"(",
"Med_b",
")",
",",
"Std_b",
"*",
"uncertainty_multiplier",
")",
"# Eq. (8)",
"return",
"numpy",
".",
"exp",
"(",
"-",
"numpy",
".",
"power",
"(",
"(",
"distances",
"/",
"beta",
")",
",",
"0.55",
")",
")"
] | Returns the Heresi-Miranda correlation model.
:param sites_or_distances:
SiteCollection instance o distance matrix
:param imt:
Intensity Measure Type (PGA or SA)
:param uncertainty_multiplier:
Value to be multiplied by the uncertainty in the correlation parameter
beta. If uncertainty_multiplier = 0 (default), the median value is
used as a constant value. | [
"Returns",
"the",
"Heresi",
"-",
"Miranda",
"correlation",
"model",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/correlation.py#L225-L262 | train | 232,965 |
gem/oq-engine | openquake/hazardlib/correlation.py | JB2009CorrelationModel.get_lower_triangle_correlation_matrix | def get_lower_triangle_correlation_matrix(self, sites, imt):
"""
Get lower-triangle matrix as a result of Cholesky-decomposition
of correlation matrix.
The resulting matrix should have zeros on values above
the main diagonal.
The actual implementations of :class:`BaseCorrelationModel` interface
might calculate the matrix considering site collection and IMT (like
:class:`JB2009CorrelationModel` does) or might have it pre-constructed
for a specific site collection and IMT, in which case they will need
to make sure that parameters to this function match parameters that
were used to pre-calculate decomposed correlation matrix.
:param sites:
:class:`~openquake.hazardlib.site.SiteCollection` to create
correlation matrix for.
:param imt:
Intensity measure type object, see :mod:`openquake.hazardlib.imt`.
"""
return numpy.linalg.cholesky(self._get_correlation_matrix(sites, imt)) | python | def get_lower_triangle_correlation_matrix(self, sites, imt):
"""
Get lower-triangle matrix as a result of Cholesky-decomposition
of correlation matrix.
The resulting matrix should have zeros on values above
the main diagonal.
The actual implementations of :class:`BaseCorrelationModel` interface
might calculate the matrix considering site collection and IMT (like
:class:`JB2009CorrelationModel` does) or might have it pre-constructed
for a specific site collection and IMT, in which case they will need
to make sure that parameters to this function match parameters that
were used to pre-calculate decomposed correlation matrix.
:param sites:
:class:`~openquake.hazardlib.site.SiteCollection` to create
correlation matrix for.
:param imt:
Intensity measure type object, see :mod:`openquake.hazardlib.imt`.
"""
return numpy.linalg.cholesky(self._get_correlation_matrix(sites, imt)) | [
"def",
"get_lower_triangle_correlation_matrix",
"(",
"self",
",",
"sites",
",",
"imt",
")",
":",
"return",
"numpy",
".",
"linalg",
".",
"cholesky",
"(",
"self",
".",
"_get_correlation_matrix",
"(",
"sites",
",",
"imt",
")",
")"
] | Get lower-triangle matrix as a result of Cholesky-decomposition
of correlation matrix.
The resulting matrix should have zeros on values above
the main diagonal.
The actual implementations of :class:`BaseCorrelationModel` interface
might calculate the matrix considering site collection and IMT (like
:class:`JB2009CorrelationModel` does) or might have it pre-constructed
for a specific site collection and IMT, in which case they will need
to make sure that parameters to this function match parameters that
were used to pre-calculate decomposed correlation matrix.
:param sites:
:class:`~openquake.hazardlib.site.SiteCollection` to create
correlation matrix for.
:param imt:
Intensity measure type object, see :mod:`openquake.hazardlib.imt`. | [
"Get",
"lower",
"-",
"triangle",
"matrix",
"as",
"a",
"result",
"of",
"Cholesky",
"-",
"decomposition",
"of",
"correlation",
"matrix",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/correlation.py#L92-L113 | train | 232,966 |
gem/oq-engine | openquake/calculators/ebrisk.py | start_ebrisk | def start_ebrisk(rupgetter, srcfilter, param, monitor):
"""
Launcher for ebrisk tasks
"""
with monitor('weighting ruptures'):
rupgetter.set_weights(srcfilter, param['num_taxonomies'])
if rupgetter.weights.sum() <= param['maxweight']:
yield ebrisk(rupgetter, srcfilter, param, monitor)
else:
for rgetter in rupgetter.split(param['maxweight']):
yield ebrisk, rgetter, srcfilter, param | python | def start_ebrisk(rupgetter, srcfilter, param, monitor):
"""
Launcher for ebrisk tasks
"""
with monitor('weighting ruptures'):
rupgetter.set_weights(srcfilter, param['num_taxonomies'])
if rupgetter.weights.sum() <= param['maxweight']:
yield ebrisk(rupgetter, srcfilter, param, monitor)
else:
for rgetter in rupgetter.split(param['maxweight']):
yield ebrisk, rgetter, srcfilter, param | [
"def",
"start_ebrisk",
"(",
"rupgetter",
",",
"srcfilter",
",",
"param",
",",
"monitor",
")",
":",
"with",
"monitor",
"(",
"'weighting ruptures'",
")",
":",
"rupgetter",
".",
"set_weights",
"(",
"srcfilter",
",",
"param",
"[",
"'num_taxonomies'",
"]",
")",
"if",
"rupgetter",
".",
"weights",
".",
"sum",
"(",
")",
"<=",
"param",
"[",
"'maxweight'",
"]",
":",
"yield",
"ebrisk",
"(",
"rupgetter",
",",
"srcfilter",
",",
"param",
",",
"monitor",
")",
"else",
":",
"for",
"rgetter",
"in",
"rupgetter",
".",
"split",
"(",
"param",
"[",
"'maxweight'",
"]",
")",
":",
"yield",
"ebrisk",
",",
"rgetter",
",",
"srcfilter",
",",
"param"
] | Launcher for ebrisk tasks | [
"Launcher",
"for",
"ebrisk",
"tasks"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ebrisk.py#L38-L48 | train | 232,967 |
gem/oq-engine | openquake/hazardlib/mfd/youngs_coppersmith_1985.py | YoungsCoppersmith1985MFD.get_min_max_mag | def get_min_max_mag(self):
"Return the minimum and maximum magnitudes"
mag, num_bins = self._get_min_mag_and_num_bins()
return mag, mag + self. bin_width * (num_bins - 1) | python | def get_min_max_mag(self):
"Return the minimum and maximum magnitudes"
mag, num_bins = self._get_min_mag_and_num_bins()
return mag, mag + self. bin_width * (num_bins - 1) | [
"def",
"get_min_max_mag",
"(",
"self",
")",
":",
"mag",
",",
"num_bins",
"=",
"self",
".",
"_get_min_mag_and_num_bins",
"(",
")",
"return",
"mag",
",",
"mag",
"+",
"self",
".",
"bin_width",
"*",
"(",
"num_bins",
"-",
"1",
")"
] | Return the minimum and maximum magnitudes | [
"Return",
"the",
"minimum",
"and",
"maximum",
"magnitudes"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L91-L94 | train | 232,968 |
gem/oq-engine | openquake/hazardlib/mfd/youngs_coppersmith_1985.py | YoungsCoppersmith1985MFD._get_rate | def _get_rate(self, mag):
"""
Calculate and return the annual occurrence rate for a specific bin.
:param mag:
Magnitude value corresponding to the center of the bin of interest.
:returns:
Float number, the annual occurrence rate for the :param mag value.
"""
mag_lo = mag - self.bin_width / 2.0
mag_hi = mag + self.bin_width / 2.0
if mag >= self.min_mag and mag < self.char_mag - DELTA_CHAR / 2:
# return rate according to exponential distribution
return (10 ** (self.a_val - self.b_val * mag_lo)
- 10 ** (self.a_val - self.b_val * mag_hi))
else:
# return characteristic rate (distributed over the characteristic
# range) for the given bin width
return (self.char_rate / DELTA_CHAR) * self.bin_width | python | def _get_rate(self, mag):
"""
Calculate and return the annual occurrence rate for a specific bin.
:param mag:
Magnitude value corresponding to the center of the bin of interest.
:returns:
Float number, the annual occurrence rate for the :param mag value.
"""
mag_lo = mag - self.bin_width / 2.0
mag_hi = mag + self.bin_width / 2.0
if mag >= self.min_mag and mag < self.char_mag - DELTA_CHAR / 2:
# return rate according to exponential distribution
return (10 ** (self.a_val - self.b_val * mag_lo)
- 10 ** (self.a_val - self.b_val * mag_hi))
else:
# return characteristic rate (distributed over the characteristic
# range) for the given bin width
return (self.char_rate / DELTA_CHAR) * self.bin_width | [
"def",
"_get_rate",
"(",
"self",
",",
"mag",
")",
":",
"mag_lo",
"=",
"mag",
"-",
"self",
".",
"bin_width",
"/",
"2.0",
"mag_hi",
"=",
"mag",
"+",
"self",
".",
"bin_width",
"/",
"2.0",
"if",
"mag",
">=",
"self",
".",
"min_mag",
"and",
"mag",
"<",
"self",
".",
"char_mag",
"-",
"DELTA_CHAR",
"/",
"2",
":",
"# return rate according to exponential distribution",
"return",
"(",
"10",
"**",
"(",
"self",
".",
"a_val",
"-",
"self",
".",
"b_val",
"*",
"mag_lo",
")",
"-",
"10",
"**",
"(",
"self",
".",
"a_val",
"-",
"self",
".",
"b_val",
"*",
"mag_hi",
")",
")",
"else",
":",
"# return characteristic rate (distributed over the characteristic",
"# range) for the given bin width",
"return",
"(",
"self",
".",
"char_rate",
"/",
"DELTA_CHAR",
")",
"*",
"self",
".",
"bin_width"
] | Calculate and return the annual occurrence rate for a specific bin.
:param mag:
Magnitude value corresponding to the center of the bin of interest.
:returns:
Float number, the annual occurrence rate for the :param mag value. | [
"Calculate",
"and",
"return",
"the",
"annual",
"occurrence",
"rate",
"for",
"a",
"specific",
"bin",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L289-L308 | train | 232,969 |
gem/oq-engine | openquake/hazardlib/mfd/youngs_coppersmith_1985.py | YoungsCoppersmith1985MFD._get_min_mag_and_num_bins | def _get_min_mag_and_num_bins(self):
"""
Estimate the number of bins in the histogram and return it along with
the first bin center value.
Rounds ``min_mag`` and ``max_mag`` with respect to ``bin_width`` to
make the distance between them include integer number of bins.
:returns:
A tuple of 2 items: first bin center, and total number of bins.
"""
min_mag = round(self.min_mag / self.bin_width) * self.bin_width
max_mag = (round((self.char_mag + DELTA_CHAR / 2) /
self.bin_width) * self.bin_width)
min_mag += self.bin_width / 2.0
max_mag -= self.bin_width / 2.0
# here we use math round on the result of division and not just
# cast it to integer because for some magnitude values that can't
# be represented as an IEEE 754 double precisely the result can
# look like 7.999999999999 which would become 7 instead of 8
# being naively casted to int so we would lose the last bin.
num_bins = int(round((max_mag - min_mag) / self.bin_width)) + 1
return min_mag, num_bins | python | def _get_min_mag_and_num_bins(self):
"""
Estimate the number of bins in the histogram and return it along with
the first bin center value.
Rounds ``min_mag`` and ``max_mag`` with respect to ``bin_width`` to
make the distance between them include integer number of bins.
:returns:
A tuple of 2 items: first bin center, and total number of bins.
"""
min_mag = round(self.min_mag / self.bin_width) * self.bin_width
max_mag = (round((self.char_mag + DELTA_CHAR / 2) /
self.bin_width) * self.bin_width)
min_mag += self.bin_width / 2.0
max_mag -= self.bin_width / 2.0
# here we use math round on the result of division and not just
# cast it to integer because for some magnitude values that can't
# be represented as an IEEE 754 double precisely the result can
# look like 7.999999999999 which would become 7 instead of 8
# being naively casted to int so we would lose the last bin.
num_bins = int(round((max_mag - min_mag) / self.bin_width)) + 1
return min_mag, num_bins | [
"def",
"_get_min_mag_and_num_bins",
"(",
"self",
")",
":",
"min_mag",
"=",
"round",
"(",
"self",
".",
"min_mag",
"/",
"self",
".",
"bin_width",
")",
"*",
"self",
".",
"bin_width",
"max_mag",
"=",
"(",
"round",
"(",
"(",
"self",
".",
"char_mag",
"+",
"DELTA_CHAR",
"/",
"2",
")",
"/",
"self",
".",
"bin_width",
")",
"*",
"self",
".",
"bin_width",
")",
"min_mag",
"+=",
"self",
".",
"bin_width",
"/",
"2.0",
"max_mag",
"-=",
"self",
".",
"bin_width",
"/",
"2.0",
"# here we use math round on the result of division and not just",
"# cast it to integer because for some magnitude values that can't",
"# be represented as an IEEE 754 double precisely the result can",
"# look like 7.999999999999 which would become 7 instead of 8",
"# being naively casted to int so we would lose the last bin.",
"num_bins",
"=",
"int",
"(",
"round",
"(",
"(",
"max_mag",
"-",
"min_mag",
")",
"/",
"self",
".",
"bin_width",
")",
")",
"+",
"1",
"return",
"min_mag",
",",
"num_bins"
] | Estimate the number of bins in the histogram and return it along with
the first bin center value.
Rounds ``min_mag`` and ``max_mag`` with respect to ``bin_width`` to
make the distance between them include integer number of bins.
:returns:
A tuple of 2 items: first bin center, and total number of bins. | [
"Estimate",
"the",
"number",
"of",
"bins",
"in",
"the",
"histogram",
"and",
"return",
"it",
"along",
"with",
"the",
"first",
"bin",
"center",
"value",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L310-L332 | train | 232,970 |
gem/oq-engine | openquake/hazardlib/mfd/youngs_coppersmith_1985.py | YoungsCoppersmith1985MFD.get_annual_occurrence_rates | def get_annual_occurrence_rates(self):
"""
Calculate and return the annual occurrence rates histogram.
:returns:
See :meth:
`openquake.hazardlib.mfd.base.BaseMFD.get_annual_occurrence_rates`.
"""
mag, num_bins = self._get_min_mag_and_num_bins()
rates = []
for i in range(num_bins):
rate = self._get_rate(mag)
rates.append((mag, rate))
mag += self.bin_width
return rates | python | def get_annual_occurrence_rates(self):
"""
Calculate and return the annual occurrence rates histogram.
:returns:
See :meth:
`openquake.hazardlib.mfd.base.BaseMFD.get_annual_occurrence_rates`.
"""
mag, num_bins = self._get_min_mag_and_num_bins()
rates = []
for i in range(num_bins):
rate = self._get_rate(mag)
rates.append((mag, rate))
mag += self.bin_width
return rates | [
"def",
"get_annual_occurrence_rates",
"(",
"self",
")",
":",
"mag",
",",
"num_bins",
"=",
"self",
".",
"_get_min_mag_and_num_bins",
"(",
")",
"rates",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"num_bins",
")",
":",
"rate",
"=",
"self",
".",
"_get_rate",
"(",
"mag",
")",
"rates",
".",
"append",
"(",
"(",
"mag",
",",
"rate",
")",
")",
"mag",
"+=",
"self",
".",
"bin_width",
"return",
"rates"
] | Calculate and return the annual occurrence rates histogram.
:returns:
See :meth:
`openquake.hazardlib.mfd.base.BaseMFD.get_annual_occurrence_rates`. | [
"Calculate",
"and",
"return",
"the",
"annual",
"occurrence",
"rates",
"histogram",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L334-L348 | train | 232,971 |
gem/oq-engine | openquake/hmtk/sources/area_source.py | mtkAreaSource.create_geometry | def create_geometry(self, input_geometry, upper_depth, lower_depth):
'''
If geometry is defined as a numpy array then create instance of
nhlib.geo.polygon.Polygon class, otherwise if already instance of class
accept class
:param input_geometry:
Input geometry (polygon) as either
i) instance of nhlib.geo.polygon.Polygon class
ii) numpy.ndarray [Longitude, Latitude]
:param float upper_depth:
Upper seismogenic depth (km)
:param float lower_depth:
Lower seismogenic depth (km)
'''
self._check_seismogenic_depths(upper_depth, lower_depth)
# Check/create the geometry class
if not isinstance(input_geometry, Polygon):
if not isinstance(input_geometry, np.ndarray):
raise ValueError('Unrecognised or unsupported geometry '
'definition')
if np.shape(input_geometry)[0] < 3:
raise ValueError('Incorrectly formatted polygon geometry -'
' needs three or more vertices')
geometry = []
for row in input_geometry:
geometry.append(Point(row[0], row[1], self.upper_depth))
self.geometry = Polygon(geometry)
else:
self.geometry = input_geometry | python | def create_geometry(self, input_geometry, upper_depth, lower_depth):
'''
If geometry is defined as a numpy array then create instance of
nhlib.geo.polygon.Polygon class, otherwise if already instance of class
accept class
:param input_geometry:
Input geometry (polygon) as either
i) instance of nhlib.geo.polygon.Polygon class
ii) numpy.ndarray [Longitude, Latitude]
:param float upper_depth:
Upper seismogenic depth (km)
:param float lower_depth:
Lower seismogenic depth (km)
'''
self._check_seismogenic_depths(upper_depth, lower_depth)
# Check/create the geometry class
if not isinstance(input_geometry, Polygon):
if not isinstance(input_geometry, np.ndarray):
raise ValueError('Unrecognised or unsupported geometry '
'definition')
if np.shape(input_geometry)[0] < 3:
raise ValueError('Incorrectly formatted polygon geometry -'
' needs three or more vertices')
geometry = []
for row in input_geometry:
geometry.append(Point(row[0], row[1], self.upper_depth))
self.geometry = Polygon(geometry)
else:
self.geometry = input_geometry | [
"def",
"create_geometry",
"(",
"self",
",",
"input_geometry",
",",
"upper_depth",
",",
"lower_depth",
")",
":",
"self",
".",
"_check_seismogenic_depths",
"(",
"upper_depth",
",",
"lower_depth",
")",
"# Check/create the geometry class",
"if",
"not",
"isinstance",
"(",
"input_geometry",
",",
"Polygon",
")",
":",
"if",
"not",
"isinstance",
"(",
"input_geometry",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"ValueError",
"(",
"'Unrecognised or unsupported geometry '",
"'definition'",
")",
"if",
"np",
".",
"shape",
"(",
"input_geometry",
")",
"[",
"0",
"]",
"<",
"3",
":",
"raise",
"ValueError",
"(",
"'Incorrectly formatted polygon geometry -'",
"' needs three or more vertices'",
")",
"geometry",
"=",
"[",
"]",
"for",
"row",
"in",
"input_geometry",
":",
"geometry",
".",
"append",
"(",
"Point",
"(",
"row",
"[",
"0",
"]",
",",
"row",
"[",
"1",
"]",
",",
"self",
".",
"upper_depth",
")",
")",
"self",
".",
"geometry",
"=",
"Polygon",
"(",
"geometry",
")",
"else",
":",
"self",
".",
"geometry",
"=",
"input_geometry"
] | If geometry is defined as a numpy array then create instance of
nhlib.geo.polygon.Polygon class, otherwise if already instance of class
accept class
:param input_geometry:
Input geometry (polygon) as either
i) instance of nhlib.geo.polygon.Polygon class
ii) numpy.ndarray [Longitude, Latitude]
:param float upper_depth:
Upper seismogenic depth (km)
:param float lower_depth:
Lower seismogenic depth (km) | [
"If",
"geometry",
"is",
"defined",
"as",
"a",
"numpy",
"array",
"then",
"create",
"instance",
"of",
"nhlib",
".",
"geo",
".",
"polygon",
".",
"Polygon",
"class",
"otherwise",
"if",
"already",
"instance",
"of",
"class",
"accept",
"class"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/area_source.py#L118-L151 | train | 232,972 |
gem/oq-engine | openquake/hmtk/sources/area_source.py | mtkAreaSource.select_catalogue | def select_catalogue(self, selector, distance=None):
'''
Selects the catalogue of earthquakes attributable to the source
:param selector:
Populated instance of openquake.hmtk.seismicity.selector.CatalogueSelector
class
:param float distance:
Distance (in km) to extend or contract (if negative) the zone for
selecting events
'''
if selector.catalogue.get_number_events() < 1:
raise ValueError('No events found in catalogue!')
self.catalogue = selector.within_polygon(self.geometry,
distance,
upper_depth=self.upper_depth,
lower_depth=self.lower_depth)
if self.catalogue.get_number_events() < 5:
# Throw a warning regarding the small number of earthquakes in
# the source!
warnings.warn('Source %s (%s) has fewer than 5 events'
% (self.id, self.name)) | python | def select_catalogue(self, selector, distance=None):
'''
Selects the catalogue of earthquakes attributable to the source
:param selector:
Populated instance of openquake.hmtk.seismicity.selector.CatalogueSelector
class
:param float distance:
Distance (in km) to extend or contract (if negative) the zone for
selecting events
'''
if selector.catalogue.get_number_events() < 1:
raise ValueError('No events found in catalogue!')
self.catalogue = selector.within_polygon(self.geometry,
distance,
upper_depth=self.upper_depth,
lower_depth=self.lower_depth)
if self.catalogue.get_number_events() < 5:
# Throw a warning regarding the small number of earthquakes in
# the source!
warnings.warn('Source %s (%s) has fewer than 5 events'
% (self.id, self.name)) | [
"def",
"select_catalogue",
"(",
"self",
",",
"selector",
",",
"distance",
"=",
"None",
")",
":",
"if",
"selector",
".",
"catalogue",
".",
"get_number_events",
"(",
")",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"'No events found in catalogue!'",
")",
"self",
".",
"catalogue",
"=",
"selector",
".",
"within_polygon",
"(",
"self",
".",
"geometry",
",",
"distance",
",",
"upper_depth",
"=",
"self",
".",
"upper_depth",
",",
"lower_depth",
"=",
"self",
".",
"lower_depth",
")",
"if",
"self",
".",
"catalogue",
".",
"get_number_events",
"(",
")",
"<",
"5",
":",
"# Throw a warning regarding the small number of earthquakes in",
"# the source!",
"warnings",
".",
"warn",
"(",
"'Source %s (%s) has fewer than 5 events'",
"%",
"(",
"self",
".",
"id",
",",
"self",
".",
"name",
")",
")"
] | Selects the catalogue of earthquakes attributable to the source
:param selector:
Populated instance of openquake.hmtk.seismicity.selector.CatalogueSelector
class
:param float distance:
Distance (in km) to extend or contract (if negative) the zone for
selecting events | [
"Selects",
"the",
"catalogue",
"of",
"earthquakes",
"attributable",
"to",
"the",
"source"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/area_source.py#L180-L202 | train | 232,973 |
gem/oq-engine | openquake/baselib/performance.py | Monitor.new | def new(self, operation='no operation', **kw):
"""
Return a copy of the monitor usable for a different operation.
"""
self_vars = vars(self).copy()
del self_vars['operation']
del self_vars['children']
del self_vars['counts']
del self_vars['_flush']
new = self.__class__(operation)
vars(new).update(self_vars)
vars(new).update(kw)
return new | python | def new(self, operation='no operation', **kw):
"""
Return a copy of the monitor usable for a different operation.
"""
self_vars = vars(self).copy()
del self_vars['operation']
del self_vars['children']
del self_vars['counts']
del self_vars['_flush']
new = self.__class__(operation)
vars(new).update(self_vars)
vars(new).update(kw)
return new | [
"def",
"new",
"(",
"self",
",",
"operation",
"=",
"'no operation'",
",",
"*",
"*",
"kw",
")",
":",
"self_vars",
"=",
"vars",
"(",
"self",
")",
".",
"copy",
"(",
")",
"del",
"self_vars",
"[",
"'operation'",
"]",
"del",
"self_vars",
"[",
"'children'",
"]",
"del",
"self_vars",
"[",
"'counts'",
"]",
"del",
"self_vars",
"[",
"'_flush'",
"]",
"new",
"=",
"self",
".",
"__class__",
"(",
"operation",
")",
"vars",
"(",
"new",
")",
".",
"update",
"(",
"self_vars",
")",
"vars",
"(",
"new",
")",
".",
"update",
"(",
"kw",
")",
"return",
"new"
] | Return a copy of the monitor usable for a different operation. | [
"Return",
"a",
"copy",
"of",
"the",
"monitor",
"usable",
"for",
"a",
"different",
"operation",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/performance.py#L185-L197 | train | 232,974 |
gem/oq-engine | openquake/hazardlib/site.py | SiteCollection.from_shakemap | def from_shakemap(cls, shakemap_array):
"""
Build a site collection from a shakemap array
"""
self = object.__new__(cls)
self.complete = self
n = len(shakemap_array)
dtype = numpy.dtype([(p, site_param_dt[p])
for p in 'sids lon lat depth vs30'.split()])
self.array = arr = numpy.zeros(n, dtype)
arr['sids'] = numpy.arange(n, dtype=numpy.uint32)
arr['lon'] = shakemap_array['lon']
arr['lat'] = shakemap_array['lat']
arr['depth'] = numpy.zeros(n)
arr['vs30'] = shakemap_array['vs30']
arr.flags.writeable = False
return self | python | def from_shakemap(cls, shakemap_array):
"""
Build a site collection from a shakemap array
"""
self = object.__new__(cls)
self.complete = self
n = len(shakemap_array)
dtype = numpy.dtype([(p, site_param_dt[p])
for p in 'sids lon lat depth vs30'.split()])
self.array = arr = numpy.zeros(n, dtype)
arr['sids'] = numpy.arange(n, dtype=numpy.uint32)
arr['lon'] = shakemap_array['lon']
arr['lat'] = shakemap_array['lat']
arr['depth'] = numpy.zeros(n)
arr['vs30'] = shakemap_array['vs30']
arr.flags.writeable = False
return self | [
"def",
"from_shakemap",
"(",
"cls",
",",
"shakemap_array",
")",
":",
"self",
"=",
"object",
".",
"__new__",
"(",
"cls",
")",
"self",
".",
"complete",
"=",
"self",
"n",
"=",
"len",
"(",
"shakemap_array",
")",
"dtype",
"=",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"p",
",",
"site_param_dt",
"[",
"p",
"]",
")",
"for",
"p",
"in",
"'sids lon lat depth vs30'",
".",
"split",
"(",
")",
"]",
")",
"self",
".",
"array",
"=",
"arr",
"=",
"numpy",
".",
"zeros",
"(",
"n",
",",
"dtype",
")",
"arr",
"[",
"'sids'",
"]",
"=",
"numpy",
".",
"arange",
"(",
"n",
",",
"dtype",
"=",
"numpy",
".",
"uint32",
")",
"arr",
"[",
"'lon'",
"]",
"=",
"shakemap_array",
"[",
"'lon'",
"]",
"arr",
"[",
"'lat'",
"]",
"=",
"shakemap_array",
"[",
"'lat'",
"]",
"arr",
"[",
"'depth'",
"]",
"=",
"numpy",
".",
"zeros",
"(",
"n",
")",
"arr",
"[",
"'vs30'",
"]",
"=",
"shakemap_array",
"[",
"'vs30'",
"]",
"arr",
".",
"flags",
".",
"writeable",
"=",
"False",
"return",
"self"
] | Build a site collection from a shakemap array | [
"Build",
"a",
"site",
"collection",
"from",
"a",
"shakemap",
"array"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L164-L180 | train | 232,975 |
gem/oq-engine | openquake/hazardlib/site.py | SiteCollection.from_points | def from_points(cls, lons, lats, depths=None, sitemodel=None,
req_site_params=()):
"""
Build the site collection from
:param lons:
a sequence of longitudes
:param lats:
a sequence of latitudes
:param depths:
a sequence of depths (or None)
:param sitemodel:
None or an object containing site parameters as attributes
:param req_site_params:
a sequence of required site parameters, possibly empty
"""
assert len(lons) < U32LIMIT, len(lons)
if depths is None:
depths = numpy.zeros(len(lons))
assert len(lons) == len(lats) == len(depths), (len(lons), len(lats),
len(depths))
self = object.__new__(cls)
self.complete = self
req = ['sids', 'lon', 'lat', 'depth'] + sorted(
par for par in req_site_params if par not in ('lon', 'lat'))
if 'vs30' in req and 'vs30measured' not in req:
req.append('vs30measured')
self.dtype = numpy.dtype([(p, site_param_dt[p]) for p in req])
self.array = arr = numpy.zeros(len(lons), self.dtype)
arr['sids'] = numpy.arange(len(lons), dtype=numpy.uint32)
arr['lon'] = fix_lon(numpy.array(lons))
arr['lat'] = numpy.array(lats)
arr['depth'] = numpy.array(depths)
if sitemodel is None:
pass
elif hasattr(sitemodel, 'reference_vs30_value'):
# sitemodel is actually an OqParam instance
self._set('vs30', sitemodel.reference_vs30_value)
self._set('vs30measured',
sitemodel.reference_vs30_type == 'measured')
self._set('z1pt0', sitemodel.reference_depth_to_1pt0km_per_sec)
self._set('z2pt5', sitemodel.reference_depth_to_2pt5km_per_sec)
self._set('siteclass', sitemodel.reference_siteclass)
else:
for name in sitemodel.dtype.names:
if name not in ('lon', 'lat'):
self._set(name, sitemodel[name])
return self | python | def from_points(cls, lons, lats, depths=None, sitemodel=None,
req_site_params=()):
"""
Build the site collection from
:param lons:
a sequence of longitudes
:param lats:
a sequence of latitudes
:param depths:
a sequence of depths (or None)
:param sitemodel:
None or an object containing site parameters as attributes
:param req_site_params:
a sequence of required site parameters, possibly empty
"""
assert len(lons) < U32LIMIT, len(lons)
if depths is None:
depths = numpy.zeros(len(lons))
assert len(lons) == len(lats) == len(depths), (len(lons), len(lats),
len(depths))
self = object.__new__(cls)
self.complete = self
req = ['sids', 'lon', 'lat', 'depth'] + sorted(
par for par in req_site_params if par not in ('lon', 'lat'))
if 'vs30' in req and 'vs30measured' not in req:
req.append('vs30measured')
self.dtype = numpy.dtype([(p, site_param_dt[p]) for p in req])
self.array = arr = numpy.zeros(len(lons), self.dtype)
arr['sids'] = numpy.arange(len(lons), dtype=numpy.uint32)
arr['lon'] = fix_lon(numpy.array(lons))
arr['lat'] = numpy.array(lats)
arr['depth'] = numpy.array(depths)
if sitemodel is None:
pass
elif hasattr(sitemodel, 'reference_vs30_value'):
# sitemodel is actually an OqParam instance
self._set('vs30', sitemodel.reference_vs30_value)
self._set('vs30measured',
sitemodel.reference_vs30_type == 'measured')
self._set('z1pt0', sitemodel.reference_depth_to_1pt0km_per_sec)
self._set('z2pt5', sitemodel.reference_depth_to_2pt5km_per_sec)
self._set('siteclass', sitemodel.reference_siteclass)
else:
for name in sitemodel.dtype.names:
if name not in ('lon', 'lat'):
self._set(name, sitemodel[name])
return self | [
"def",
"from_points",
"(",
"cls",
",",
"lons",
",",
"lats",
",",
"depths",
"=",
"None",
",",
"sitemodel",
"=",
"None",
",",
"req_site_params",
"=",
"(",
")",
")",
":",
"assert",
"len",
"(",
"lons",
")",
"<",
"U32LIMIT",
",",
"len",
"(",
"lons",
")",
"if",
"depths",
"is",
"None",
":",
"depths",
"=",
"numpy",
".",
"zeros",
"(",
"len",
"(",
"lons",
")",
")",
"assert",
"len",
"(",
"lons",
")",
"==",
"len",
"(",
"lats",
")",
"==",
"len",
"(",
"depths",
")",
",",
"(",
"len",
"(",
"lons",
")",
",",
"len",
"(",
"lats",
")",
",",
"len",
"(",
"depths",
")",
")",
"self",
"=",
"object",
".",
"__new__",
"(",
"cls",
")",
"self",
".",
"complete",
"=",
"self",
"req",
"=",
"[",
"'sids'",
",",
"'lon'",
",",
"'lat'",
",",
"'depth'",
"]",
"+",
"sorted",
"(",
"par",
"for",
"par",
"in",
"req_site_params",
"if",
"par",
"not",
"in",
"(",
"'lon'",
",",
"'lat'",
")",
")",
"if",
"'vs30'",
"in",
"req",
"and",
"'vs30measured'",
"not",
"in",
"req",
":",
"req",
".",
"append",
"(",
"'vs30measured'",
")",
"self",
".",
"dtype",
"=",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"p",
",",
"site_param_dt",
"[",
"p",
"]",
")",
"for",
"p",
"in",
"req",
"]",
")",
"self",
".",
"array",
"=",
"arr",
"=",
"numpy",
".",
"zeros",
"(",
"len",
"(",
"lons",
")",
",",
"self",
".",
"dtype",
")",
"arr",
"[",
"'sids'",
"]",
"=",
"numpy",
".",
"arange",
"(",
"len",
"(",
"lons",
")",
",",
"dtype",
"=",
"numpy",
".",
"uint32",
")",
"arr",
"[",
"'lon'",
"]",
"=",
"fix_lon",
"(",
"numpy",
".",
"array",
"(",
"lons",
")",
")",
"arr",
"[",
"'lat'",
"]",
"=",
"numpy",
".",
"array",
"(",
"lats",
")",
"arr",
"[",
"'depth'",
"]",
"=",
"numpy",
".",
"array",
"(",
"depths",
")",
"if",
"sitemodel",
"is",
"None",
":",
"pass",
"elif",
"hasattr",
"(",
"sitemodel",
",",
"'reference_vs30_value'",
")",
":",
"# sitemodel is actually an OqParam instance",
"self",
".",
"_set",
"(",
"'vs30'",
",",
"sitemodel",
".",
"reference_vs30_value",
")",
"self",
".",
"_set",
"(",
"'vs30measured'",
",",
"sitemodel",
".",
"reference_vs30_type",
"==",
"'measured'",
")",
"self",
".",
"_set",
"(",
"'z1pt0'",
",",
"sitemodel",
".",
"reference_depth_to_1pt0km_per_sec",
")",
"self",
".",
"_set",
"(",
"'z2pt5'",
",",
"sitemodel",
".",
"reference_depth_to_2pt5km_per_sec",
")",
"self",
".",
"_set",
"(",
"'siteclass'",
",",
"sitemodel",
".",
"reference_siteclass",
")",
"else",
":",
"for",
"name",
"in",
"sitemodel",
".",
"dtype",
".",
"names",
":",
"if",
"name",
"not",
"in",
"(",
"'lon'",
",",
"'lat'",
")",
":",
"self",
".",
"_set",
"(",
"name",
",",
"sitemodel",
"[",
"name",
"]",
")",
"return",
"self"
] | Build the site collection from
:param lons:
a sequence of longitudes
:param lats:
a sequence of latitudes
:param depths:
a sequence of depths (or None)
:param sitemodel:
None or an object containing site parameters as attributes
:param req_site_params:
a sequence of required site parameters, possibly empty | [
"Build",
"the",
"site",
"collection",
"from"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L183-L230 | train | 232,976 |
gem/oq-engine | openquake/hazardlib/site.py | SiteCollection.make_complete | def make_complete(self):
"""
Turns the site collection into a complete one, if needed
"""
# reset the site indices from 0 to N-1 and set self.complete to self
self.array['sids'] = numpy.arange(len(self), dtype=numpy.uint32)
self.complete = self | python | def make_complete(self):
"""
Turns the site collection into a complete one, if needed
"""
# reset the site indices from 0 to N-1 and set self.complete to self
self.array['sids'] = numpy.arange(len(self), dtype=numpy.uint32)
self.complete = self | [
"def",
"make_complete",
"(",
"self",
")",
":",
"# reset the site indices from 0 to N-1 and set self.complete to self",
"self",
".",
"array",
"[",
"'sids'",
"]",
"=",
"numpy",
".",
"arange",
"(",
"len",
"(",
"self",
")",
",",
"dtype",
"=",
"numpy",
".",
"uint32",
")",
"self",
".",
"complete",
"=",
"self"
] | Turns the site collection into a complete one, if needed | [
"Turns",
"the",
"site",
"collection",
"into",
"a",
"complete",
"one",
"if",
"needed"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L256-L262 | train | 232,977 |
gem/oq-engine | openquake/hazardlib/site.py | SiteCollection.filter | def filter(self, mask):
"""
Create a SiteCollection with only a subset of sites.
:param mask:
Numpy array of boolean values of the same length as the site
collection. ``True`` values should indicate that site with that
index should be included into the filtered collection.
:returns:
A new :class:`SiteCollection` instance, unless all the
values in ``mask`` are ``True``, in which case this site collection
is returned, or if all the values in ``mask`` are ``False``,
in which case method returns ``None``. New collection has data
of only those sites that were marked for inclusion in the mask.
"""
assert len(mask) == len(self), (len(mask), len(self))
if mask.all():
# all sites satisfy the filter, return
# this collection unchanged
return self
if not mask.any():
# no sites pass the filter, return None
return None
# extract indices of Trues from the mask
indices, = mask.nonzero()
return self.filtered(indices) | python | def filter(self, mask):
"""
Create a SiteCollection with only a subset of sites.
:param mask:
Numpy array of boolean values of the same length as the site
collection. ``True`` values should indicate that site with that
index should be included into the filtered collection.
:returns:
A new :class:`SiteCollection` instance, unless all the
values in ``mask`` are ``True``, in which case this site collection
is returned, or if all the values in ``mask`` are ``False``,
in which case method returns ``None``. New collection has data
of only those sites that were marked for inclusion in the mask.
"""
assert len(mask) == len(self), (len(mask), len(self))
if mask.all():
# all sites satisfy the filter, return
# this collection unchanged
return self
if not mask.any():
# no sites pass the filter, return None
return None
# extract indices of Trues from the mask
indices, = mask.nonzero()
return self.filtered(indices) | [
"def",
"filter",
"(",
"self",
",",
"mask",
")",
":",
"assert",
"len",
"(",
"mask",
")",
"==",
"len",
"(",
"self",
")",
",",
"(",
"len",
"(",
"mask",
")",
",",
"len",
"(",
"self",
")",
")",
"if",
"mask",
".",
"all",
"(",
")",
":",
"# all sites satisfy the filter, return",
"# this collection unchanged",
"return",
"self",
"if",
"not",
"mask",
".",
"any",
"(",
")",
":",
"# no sites pass the filter, return None",
"return",
"None",
"# extract indices of Trues from the mask",
"indices",
",",
"=",
"mask",
".",
"nonzero",
"(",
")",
"return",
"self",
".",
"filtered",
"(",
"indices",
")"
] | Create a SiteCollection with only a subset of sites.
:param mask:
Numpy array of boolean values of the same length as the site
collection. ``True`` values should indicate that site with that
index should be included into the filtered collection.
:returns:
A new :class:`SiteCollection` instance, unless all the
values in ``mask`` are ``True``, in which case this site collection
is returned, or if all the values in ``mask`` are ``False``,
in which case method returns ``None``. New collection has data
of only those sites that were marked for inclusion in the mask. | [
"Create",
"a",
"SiteCollection",
"with",
"only",
"a",
"subset",
"of",
"sites",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L345-L370 | train | 232,978 |
gem/oq-engine | openquake/hazardlib/geo/point.py | Point.point_at | def point_at(self, horizontal_distance, vertical_increment, azimuth):
"""
Compute the point with given horizontal, vertical distances
and azimuth from this point.
:param horizontal_distance:
Horizontal distance, in km.
:type horizontal_distance:
float
:param vertical_increment:
Vertical increment, in km. When positive, the new point
has a greater depth. When negative, the new point
has a smaller depth.
:type vertical_increment:
float
:type azimuth:
Azimuth, in decimal degrees.
:type azimuth:
float
:returns:
The point at the given distances.
:rtype:
Instance of :class:`Point`
"""
lon, lat = geodetic.point_at(self.longitude, self.latitude,
azimuth, horizontal_distance)
return Point(lon, lat, self.depth + vertical_increment) | python | def point_at(self, horizontal_distance, vertical_increment, azimuth):
"""
Compute the point with given horizontal, vertical distances
and azimuth from this point.
:param horizontal_distance:
Horizontal distance, in km.
:type horizontal_distance:
float
:param vertical_increment:
Vertical increment, in km. When positive, the new point
has a greater depth. When negative, the new point
has a smaller depth.
:type vertical_increment:
float
:type azimuth:
Azimuth, in decimal degrees.
:type azimuth:
float
:returns:
The point at the given distances.
:rtype:
Instance of :class:`Point`
"""
lon, lat = geodetic.point_at(self.longitude, self.latitude,
azimuth, horizontal_distance)
return Point(lon, lat, self.depth + vertical_increment) | [
"def",
"point_at",
"(",
"self",
",",
"horizontal_distance",
",",
"vertical_increment",
",",
"azimuth",
")",
":",
"lon",
",",
"lat",
"=",
"geodetic",
".",
"point_at",
"(",
"self",
".",
"longitude",
",",
"self",
".",
"latitude",
",",
"azimuth",
",",
"horizontal_distance",
")",
"return",
"Point",
"(",
"lon",
",",
"lat",
",",
"self",
".",
"depth",
"+",
"vertical_increment",
")"
] | Compute the point with given horizontal, vertical distances
and azimuth from this point.
:param horizontal_distance:
Horizontal distance, in km.
:type horizontal_distance:
float
:param vertical_increment:
Vertical increment, in km. When positive, the new point
has a greater depth. When negative, the new point
has a smaller depth.
:type vertical_increment:
float
:type azimuth:
Azimuth, in decimal degrees.
:type azimuth:
float
:returns:
The point at the given distances.
:rtype:
Instance of :class:`Point` | [
"Compute",
"the",
"point",
"with",
"given",
"horizontal",
"vertical",
"distances",
"and",
"azimuth",
"from",
"this",
"point",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/point.py#L94-L120 | train | 232,979 |
gem/oq-engine | openquake/hazardlib/geo/point.py | Point.equally_spaced_points | def equally_spaced_points(self, point, distance):
"""
Compute the set of points equally spaced between this point
and the given point.
:param point:
Destination point.
:type point:
Instance of :class:`Point`
:param distance:
Distance between points (in km).
:type distance:
float
:returns:
The list of equally spaced points.
:rtype:
list of :class:`Point` instances
"""
lons, lats, depths = geodetic.intervals_between(
self.longitude, self.latitude, self.depth,
point.longitude, point.latitude, point.depth,
distance)
return [Point(lons[i], lats[i], depths[i]) for i in range(len(lons))] | python | def equally_spaced_points(self, point, distance):
"""
Compute the set of points equally spaced between this point
and the given point.
:param point:
Destination point.
:type point:
Instance of :class:`Point`
:param distance:
Distance between points (in km).
:type distance:
float
:returns:
The list of equally spaced points.
:rtype:
list of :class:`Point` instances
"""
lons, lats, depths = geodetic.intervals_between(
self.longitude, self.latitude, self.depth,
point.longitude, point.latitude, point.depth,
distance)
return [Point(lons[i], lats[i], depths[i]) for i in range(len(lons))] | [
"def",
"equally_spaced_points",
"(",
"self",
",",
"point",
",",
"distance",
")",
":",
"lons",
",",
"lats",
",",
"depths",
"=",
"geodetic",
".",
"intervals_between",
"(",
"self",
".",
"longitude",
",",
"self",
".",
"latitude",
",",
"self",
".",
"depth",
",",
"point",
".",
"longitude",
",",
"point",
".",
"latitude",
",",
"point",
".",
"depth",
",",
"distance",
")",
"return",
"[",
"Point",
"(",
"lons",
"[",
"i",
"]",
",",
"lats",
"[",
"i",
"]",
",",
"depths",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"lons",
")",
")",
"]"
] | Compute the set of points equally spaced between this point
and the given point.
:param point:
Destination point.
:type point:
Instance of :class:`Point`
:param distance:
Distance between points (in km).
:type distance:
float
:returns:
The list of equally spaced points.
:rtype:
list of :class:`Point` instances | [
"Compute",
"the",
"set",
"of",
"points",
"equally",
"spaced",
"between",
"this",
"point",
"and",
"the",
"given",
"point",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/point.py#L235-L257 | train | 232,980 |
gem/oq-engine | openquake/hazardlib/geo/point.py | Point.to_polygon | def to_polygon(self, radius):
"""
Create a circular polygon with specified radius centered in the point.
:param radius:
Required radius of a new polygon, in km.
:returns:
Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon` that
approximates a circle around the point with specified radius.
"""
assert radius > 0
# avoid circular imports
from openquake.hazardlib.geo.polygon import Polygon
# get a projection that is centered in the point
proj = geo_utils.OrthographicProjection(
self.longitude, self.longitude, self.latitude, self.latitude)
# create a shapely object from a projected point coordinates,
# which are supposedly (0, 0)
point = shapely.geometry.Point(*proj(self.longitude, self.latitude))
# extend the point to a shapely polygon using buffer()
# and create openquake.hazardlib.geo.polygon.Polygon object from it
return Polygon._from_2d(point.buffer(radius), proj) | python | def to_polygon(self, radius):
"""
Create a circular polygon with specified radius centered in the point.
:param radius:
Required radius of a new polygon, in km.
:returns:
Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon` that
approximates a circle around the point with specified radius.
"""
assert radius > 0
# avoid circular imports
from openquake.hazardlib.geo.polygon import Polygon
# get a projection that is centered in the point
proj = geo_utils.OrthographicProjection(
self.longitude, self.longitude, self.latitude, self.latitude)
# create a shapely object from a projected point coordinates,
# which are supposedly (0, 0)
point = shapely.geometry.Point(*proj(self.longitude, self.latitude))
# extend the point to a shapely polygon using buffer()
# and create openquake.hazardlib.geo.polygon.Polygon object from it
return Polygon._from_2d(point.buffer(radius), proj) | [
"def",
"to_polygon",
"(",
"self",
",",
"radius",
")",
":",
"assert",
"radius",
">",
"0",
"# avoid circular imports",
"from",
"openquake",
".",
"hazardlib",
".",
"geo",
".",
"polygon",
"import",
"Polygon",
"# get a projection that is centered in the point",
"proj",
"=",
"geo_utils",
".",
"OrthographicProjection",
"(",
"self",
".",
"longitude",
",",
"self",
".",
"longitude",
",",
"self",
".",
"latitude",
",",
"self",
".",
"latitude",
")",
"# create a shapely object from a projected point coordinates,",
"# which are supposedly (0, 0)",
"point",
"=",
"shapely",
".",
"geometry",
".",
"Point",
"(",
"*",
"proj",
"(",
"self",
".",
"longitude",
",",
"self",
".",
"latitude",
")",
")",
"# extend the point to a shapely polygon using buffer()",
"# and create openquake.hazardlib.geo.polygon.Polygon object from it",
"return",
"Polygon",
".",
"_from_2d",
"(",
"point",
".",
"buffer",
"(",
"radius",
")",
",",
"proj",
")"
] | Create a circular polygon with specified radius centered in the point.
:param radius:
Required radius of a new polygon, in km.
:returns:
Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon` that
approximates a circle around the point with specified radius. | [
"Create",
"a",
"circular",
"polygon",
"with",
"specified",
"radius",
"centered",
"in",
"the",
"point",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/point.py#L259-L283 | train | 232,981 |
gem/oq-engine | openquake/hazardlib/geo/point.py | Point.closer_than | def closer_than(self, mesh, radius):
"""
Check for proximity of points in the ``mesh``.
:param mesh:
:class:`openquake.hazardlib.geo.mesh.Mesh` instance.
:param radius:
Proximity measure in km.
:returns:
Numpy array of boolean values in the same shape as the mesh
coordinate arrays with ``True`` on indexes of points that
are not further than ``radius`` km from this point. Function
:func:`~openquake.hazardlib.geo.geodetic.distance` is used to
calculate distances to points of the mesh. Points of the mesh that
lie exactly ``radius`` km away from this point also have
``True`` in their indices.
"""
dists = geodetic.distance(self.longitude, self.latitude, self.depth,
mesh.lons, mesh.lats,
0 if mesh.depths is None else mesh.depths)
return dists <= radius | python | def closer_than(self, mesh, radius):
"""
Check for proximity of points in the ``mesh``.
:param mesh:
:class:`openquake.hazardlib.geo.mesh.Mesh` instance.
:param radius:
Proximity measure in km.
:returns:
Numpy array of boolean values in the same shape as the mesh
coordinate arrays with ``True`` on indexes of points that
are not further than ``radius`` km from this point. Function
:func:`~openquake.hazardlib.geo.geodetic.distance` is used to
calculate distances to points of the mesh. Points of the mesh that
lie exactly ``radius`` km away from this point also have
``True`` in their indices.
"""
dists = geodetic.distance(self.longitude, self.latitude, self.depth,
mesh.lons, mesh.lats,
0 if mesh.depths is None else mesh.depths)
return dists <= radius | [
"def",
"closer_than",
"(",
"self",
",",
"mesh",
",",
"radius",
")",
":",
"dists",
"=",
"geodetic",
".",
"distance",
"(",
"self",
".",
"longitude",
",",
"self",
".",
"latitude",
",",
"self",
".",
"depth",
",",
"mesh",
".",
"lons",
",",
"mesh",
".",
"lats",
",",
"0",
"if",
"mesh",
".",
"depths",
"is",
"None",
"else",
"mesh",
".",
"depths",
")",
"return",
"dists",
"<=",
"radius"
] | Check for proximity of points in the ``mesh``.
:param mesh:
:class:`openquake.hazardlib.geo.mesh.Mesh` instance.
:param radius:
Proximity measure in km.
:returns:
Numpy array of boolean values in the same shape as the mesh
coordinate arrays with ``True`` on indexes of points that
are not further than ``radius`` km from this point. Function
:func:`~openquake.hazardlib.geo.geodetic.distance` is used to
calculate distances to points of the mesh. Points of the mesh that
lie exactly ``radius`` km away from this point also have
``True`` in their indices. | [
"Check",
"for",
"proximity",
"of",
"points",
"in",
"the",
"mesh",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/point.py#L285-L305 | train | 232,982 |
gem/oq-engine | openquake/commands/info.py | print_csm_info | def print_csm_info(fname):
"""
Parse the composite source model without instantiating the sources and
prints information about its composition and the full logic tree
"""
oqparam = readinput.get_oqparam(fname)
csm = readinput.get_composite_source_model(oqparam, in_memory=False)
print(csm.info)
print('See http://docs.openquake.org/oq-engine/stable/'
'effective-realizations.html for an explanation')
rlzs_assoc = csm.info.get_rlzs_assoc()
print(rlzs_assoc)
dupl = [(srcs[0]['id'], len(srcs)) for srcs in csm.check_dupl_sources()]
if dupl:
print(rst_table(dupl, ['source_id', 'multiplicity']))
tot, pairs = get_pickled_sizes(rlzs_assoc)
print(rst_table(pairs, ['attribute', 'nbytes'])) | python | def print_csm_info(fname):
"""
Parse the composite source model without instantiating the sources and
prints information about its composition and the full logic tree
"""
oqparam = readinput.get_oqparam(fname)
csm = readinput.get_composite_source_model(oqparam, in_memory=False)
print(csm.info)
print('See http://docs.openquake.org/oq-engine/stable/'
'effective-realizations.html for an explanation')
rlzs_assoc = csm.info.get_rlzs_assoc()
print(rlzs_assoc)
dupl = [(srcs[0]['id'], len(srcs)) for srcs in csm.check_dupl_sources()]
if dupl:
print(rst_table(dupl, ['source_id', 'multiplicity']))
tot, pairs = get_pickled_sizes(rlzs_assoc)
print(rst_table(pairs, ['attribute', 'nbytes'])) | [
"def",
"print_csm_info",
"(",
"fname",
")",
":",
"oqparam",
"=",
"readinput",
".",
"get_oqparam",
"(",
"fname",
")",
"csm",
"=",
"readinput",
".",
"get_composite_source_model",
"(",
"oqparam",
",",
"in_memory",
"=",
"False",
")",
"print",
"(",
"csm",
".",
"info",
")",
"print",
"(",
"'See http://docs.openquake.org/oq-engine/stable/'",
"'effective-realizations.html for an explanation'",
")",
"rlzs_assoc",
"=",
"csm",
".",
"info",
".",
"get_rlzs_assoc",
"(",
")",
"print",
"(",
"rlzs_assoc",
")",
"dupl",
"=",
"[",
"(",
"srcs",
"[",
"0",
"]",
"[",
"'id'",
"]",
",",
"len",
"(",
"srcs",
")",
")",
"for",
"srcs",
"in",
"csm",
".",
"check_dupl_sources",
"(",
")",
"]",
"if",
"dupl",
":",
"print",
"(",
"rst_table",
"(",
"dupl",
",",
"[",
"'source_id'",
",",
"'multiplicity'",
"]",
")",
")",
"tot",
",",
"pairs",
"=",
"get_pickled_sizes",
"(",
"rlzs_assoc",
")",
"print",
"(",
"rst_table",
"(",
"pairs",
",",
"[",
"'attribute'",
",",
"'nbytes'",
"]",
")",
")"
] | Parse the composite source model without instantiating the sources and
prints information about its composition and the full logic tree | [
"Parse",
"the",
"composite",
"source",
"model",
"without",
"instantiating",
"the",
"sources",
"and",
"prints",
"information",
"about",
"its",
"composition",
"and",
"the",
"full",
"logic",
"tree"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/info.py#L65-L81 | train | 232,983 |
gem/oq-engine | openquake/commands/info.py | do_build_reports | def do_build_reports(directory):
"""
Walk the directory and builds pre-calculation reports for all the
job.ini files found.
"""
for cwd, dirs, files in os.walk(directory):
for f in sorted(files):
if f in ('job.ini', 'job_h.ini', 'job_haz.ini', 'job_hazard.ini'):
job_ini = os.path.join(cwd, f)
logging.info(job_ini)
try:
reportwriter.build_report(job_ini, cwd)
except Exception as e:
logging.error(str(e)) | python | def do_build_reports(directory):
"""
Walk the directory and builds pre-calculation reports for all the
job.ini files found.
"""
for cwd, dirs, files in os.walk(directory):
for f in sorted(files):
if f in ('job.ini', 'job_h.ini', 'job_haz.ini', 'job_hazard.ini'):
job_ini = os.path.join(cwd, f)
logging.info(job_ini)
try:
reportwriter.build_report(job_ini, cwd)
except Exception as e:
logging.error(str(e)) | [
"def",
"do_build_reports",
"(",
"directory",
")",
":",
"for",
"cwd",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory",
")",
":",
"for",
"f",
"in",
"sorted",
"(",
"files",
")",
":",
"if",
"f",
"in",
"(",
"'job.ini'",
",",
"'job_h.ini'",
",",
"'job_haz.ini'",
",",
"'job_hazard.ini'",
")",
":",
"job_ini",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"f",
")",
"logging",
".",
"info",
"(",
"job_ini",
")",
"try",
":",
"reportwriter",
".",
"build_report",
"(",
"job_ini",
",",
"cwd",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"str",
"(",
"e",
")",
")"
] | Walk the directory and builds pre-calculation reports for all the
job.ini files found. | [
"Walk",
"the",
"directory",
"and",
"builds",
"pre",
"-",
"calculation",
"reports",
"for",
"all",
"the",
"job",
".",
"ini",
"files",
"found",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/info.py#L84-L97 | train | 232,984 |
gem/oq-engine | openquake/commands/info.py | info | def info(calculators, gsims, views, exports, extracts, parameters,
report, input_file=''):
"""
Give information. You can pass the name of an available calculator,
a job.ini file, or a zip archive with the input files.
"""
if calculators:
for calc in sorted(base.calculators):
print(calc)
if gsims:
for gs in gsim.get_available_gsims():
print(gs)
if views:
for name in sorted(view):
print(name)
if exports:
dic = groupby(export, operator.itemgetter(0),
lambda group: [r[1] for r in group])
n = 0
for exporter, formats in dic.items():
print(exporter, formats)
n += len(formats)
print('There are %d exporters defined.' % n)
if extracts:
for key in extract:
func = extract[key]
if hasattr(func, '__wrapped__'):
fm = FunctionMaker(func.__wrapped__)
else:
fm = FunctionMaker(func)
print('%s(%s)%s' % (fm.name, fm.signature, fm.doc))
if parameters:
params = []
for val in vars(OqParam).values():
if hasattr(val, 'name'):
params.append(val)
params.sort(key=lambda x: x.name)
for param in params:
print(param.name)
if os.path.isdir(input_file) and report:
with Monitor('info', measuremem=True) as mon:
with mock.patch.object(logging.root, 'info'): # reduce logging
do_build_reports(input_file)
print(mon)
elif input_file.endswith('.xml'):
node = nrml.read(input_file)
if node[0].tag.endswith('sourceModel'):
if node['xmlns'].endswith('nrml/0.4'):
raise InvalidFile(
'%s is in NRML 0.4 format, please run the following '
'command:\noq upgrade_nrml %s' % (
input_file, os.path.dirname(input_file) or '.'))
print(source_model_info([node[0]]))
elif node[0].tag.endswith('logicTree'):
nodes = [nrml.read(sm_path)[0]
for sm_path in logictree.collect_info(input_file).smpaths]
print(source_model_info(nodes))
else:
print(node.to_str())
elif input_file.endswith(('.ini', '.zip')):
with Monitor('info', measuremem=True) as mon:
if report:
print('Generated', reportwriter.build_report(input_file))
else:
print_csm_info(input_file)
if mon.duration > 1:
print(mon)
elif input_file:
print("No info for '%s'" % input_file) | python | def info(calculators, gsims, views, exports, extracts, parameters,
report, input_file=''):
"""
Give information. You can pass the name of an available calculator,
a job.ini file, or a zip archive with the input files.
"""
if calculators:
for calc in sorted(base.calculators):
print(calc)
if gsims:
for gs in gsim.get_available_gsims():
print(gs)
if views:
for name in sorted(view):
print(name)
if exports:
dic = groupby(export, operator.itemgetter(0),
lambda group: [r[1] for r in group])
n = 0
for exporter, formats in dic.items():
print(exporter, formats)
n += len(formats)
print('There are %d exporters defined.' % n)
if extracts:
for key in extract:
func = extract[key]
if hasattr(func, '__wrapped__'):
fm = FunctionMaker(func.__wrapped__)
else:
fm = FunctionMaker(func)
print('%s(%s)%s' % (fm.name, fm.signature, fm.doc))
if parameters:
params = []
for val in vars(OqParam).values():
if hasattr(val, 'name'):
params.append(val)
params.sort(key=lambda x: x.name)
for param in params:
print(param.name)
if os.path.isdir(input_file) and report:
with Monitor('info', measuremem=True) as mon:
with mock.patch.object(logging.root, 'info'): # reduce logging
do_build_reports(input_file)
print(mon)
elif input_file.endswith('.xml'):
node = nrml.read(input_file)
if node[0].tag.endswith('sourceModel'):
if node['xmlns'].endswith('nrml/0.4'):
raise InvalidFile(
'%s is in NRML 0.4 format, please run the following '
'command:\noq upgrade_nrml %s' % (
input_file, os.path.dirname(input_file) or '.'))
print(source_model_info([node[0]]))
elif node[0].tag.endswith('logicTree'):
nodes = [nrml.read(sm_path)[0]
for sm_path in logictree.collect_info(input_file).smpaths]
print(source_model_info(nodes))
else:
print(node.to_str())
elif input_file.endswith(('.ini', '.zip')):
with Monitor('info', measuremem=True) as mon:
if report:
print('Generated', reportwriter.build_report(input_file))
else:
print_csm_info(input_file)
if mon.duration > 1:
print(mon)
elif input_file:
print("No info for '%s'" % input_file) | [
"def",
"info",
"(",
"calculators",
",",
"gsims",
",",
"views",
",",
"exports",
",",
"extracts",
",",
"parameters",
",",
"report",
",",
"input_file",
"=",
"''",
")",
":",
"if",
"calculators",
":",
"for",
"calc",
"in",
"sorted",
"(",
"base",
".",
"calculators",
")",
":",
"print",
"(",
"calc",
")",
"if",
"gsims",
":",
"for",
"gs",
"in",
"gsim",
".",
"get_available_gsims",
"(",
")",
":",
"print",
"(",
"gs",
")",
"if",
"views",
":",
"for",
"name",
"in",
"sorted",
"(",
"view",
")",
":",
"print",
"(",
"name",
")",
"if",
"exports",
":",
"dic",
"=",
"groupby",
"(",
"export",
",",
"operator",
".",
"itemgetter",
"(",
"0",
")",
",",
"lambda",
"group",
":",
"[",
"r",
"[",
"1",
"]",
"for",
"r",
"in",
"group",
"]",
")",
"n",
"=",
"0",
"for",
"exporter",
",",
"formats",
"in",
"dic",
".",
"items",
"(",
")",
":",
"print",
"(",
"exporter",
",",
"formats",
")",
"n",
"+=",
"len",
"(",
"formats",
")",
"print",
"(",
"'There are %d exporters defined.'",
"%",
"n",
")",
"if",
"extracts",
":",
"for",
"key",
"in",
"extract",
":",
"func",
"=",
"extract",
"[",
"key",
"]",
"if",
"hasattr",
"(",
"func",
",",
"'__wrapped__'",
")",
":",
"fm",
"=",
"FunctionMaker",
"(",
"func",
".",
"__wrapped__",
")",
"else",
":",
"fm",
"=",
"FunctionMaker",
"(",
"func",
")",
"print",
"(",
"'%s(%s)%s'",
"%",
"(",
"fm",
".",
"name",
",",
"fm",
".",
"signature",
",",
"fm",
".",
"doc",
")",
")",
"if",
"parameters",
":",
"params",
"=",
"[",
"]",
"for",
"val",
"in",
"vars",
"(",
"OqParam",
")",
".",
"values",
"(",
")",
":",
"if",
"hasattr",
"(",
"val",
",",
"'name'",
")",
":",
"params",
".",
"append",
"(",
"val",
")",
"params",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"name",
")",
"for",
"param",
"in",
"params",
":",
"print",
"(",
"param",
".",
"name",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"input_file",
")",
"and",
"report",
":",
"with",
"Monitor",
"(",
"'info'",
",",
"measuremem",
"=",
"True",
")",
"as",
"mon",
":",
"with",
"mock",
".",
"patch",
".",
"object",
"(",
"logging",
".",
"root",
",",
"'info'",
")",
":",
"# reduce logging",
"do_build_reports",
"(",
"input_file",
")",
"print",
"(",
"mon",
")",
"elif",
"input_file",
".",
"endswith",
"(",
"'.xml'",
")",
":",
"node",
"=",
"nrml",
".",
"read",
"(",
"input_file",
")",
"if",
"node",
"[",
"0",
"]",
".",
"tag",
".",
"endswith",
"(",
"'sourceModel'",
")",
":",
"if",
"node",
"[",
"'xmlns'",
"]",
".",
"endswith",
"(",
"'nrml/0.4'",
")",
":",
"raise",
"InvalidFile",
"(",
"'%s is in NRML 0.4 format, please run the following '",
"'command:\\noq upgrade_nrml %s'",
"%",
"(",
"input_file",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"input_file",
")",
"or",
"'.'",
")",
")",
"print",
"(",
"source_model_info",
"(",
"[",
"node",
"[",
"0",
"]",
"]",
")",
")",
"elif",
"node",
"[",
"0",
"]",
".",
"tag",
".",
"endswith",
"(",
"'logicTree'",
")",
":",
"nodes",
"=",
"[",
"nrml",
".",
"read",
"(",
"sm_path",
")",
"[",
"0",
"]",
"for",
"sm_path",
"in",
"logictree",
".",
"collect_info",
"(",
"input_file",
")",
".",
"smpaths",
"]",
"print",
"(",
"source_model_info",
"(",
"nodes",
")",
")",
"else",
":",
"print",
"(",
"node",
".",
"to_str",
"(",
")",
")",
"elif",
"input_file",
".",
"endswith",
"(",
"(",
"'.ini'",
",",
"'.zip'",
")",
")",
":",
"with",
"Monitor",
"(",
"'info'",
",",
"measuremem",
"=",
"True",
")",
"as",
"mon",
":",
"if",
"report",
":",
"print",
"(",
"'Generated'",
",",
"reportwriter",
".",
"build_report",
"(",
"input_file",
")",
")",
"else",
":",
"print_csm_info",
"(",
"input_file",
")",
"if",
"mon",
".",
"duration",
">",
"1",
":",
"print",
"(",
"mon",
")",
"elif",
"input_file",
":",
"print",
"(",
"\"No info for '%s'\"",
"%",
"input_file",
")"
] | Give information. You can pass the name of an available calculator,
a job.ini file, or a zip archive with the input files. | [
"Give",
"information",
".",
"You",
"can",
"pass",
"the",
"name",
"of",
"an",
"available",
"calculator",
"a",
"job",
".",
"ini",
"file",
"or",
"a",
"zip",
"archive",
"with",
"the",
"input",
"files",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/info.py#L103-L171 | train | 232,985 |
gem/oq-engine | openquake/calculators/classical.py | classical_split_filter | def classical_split_filter(srcs, srcfilter, gsims, params, monitor):
"""
Split the given sources, filter the subsources and the compute the
PoEs. Yield back subtasks if the split sources contain more than
maxweight ruptures.
"""
# first check if we are sampling the sources
ss = int(os.environ.get('OQ_SAMPLE_SOURCES', 0))
if ss:
splits, stime = split_sources(srcs)
srcs = readinput.random_filtered_sources(splits, srcfilter, ss)
yield classical(srcs, srcfilter, gsims, params, monitor)
return
sources = []
with monitor("filtering/splitting sources"):
for src, _sites in srcfilter(srcs):
if src.num_ruptures >= params['maxweight']:
splits, stime = split_sources([src])
sources.extend(srcfilter.filter(splits))
else:
sources.append(src)
blocks = list(block_splitter(sources, params['maxweight'],
operator.attrgetter('num_ruptures')))
if blocks:
# yield the first blocks (if any) and compute the last block in core
# NB: the last block is usually the smallest one
for block in blocks[:-1]:
yield classical, block, srcfilter, gsims, params
yield classical(blocks[-1], srcfilter, gsims, params, monitor) | python | def classical_split_filter(srcs, srcfilter, gsims, params, monitor):
"""
Split the given sources, filter the subsources and the compute the
PoEs. Yield back subtasks if the split sources contain more than
maxweight ruptures.
"""
# first check if we are sampling the sources
ss = int(os.environ.get('OQ_SAMPLE_SOURCES', 0))
if ss:
splits, stime = split_sources(srcs)
srcs = readinput.random_filtered_sources(splits, srcfilter, ss)
yield classical(srcs, srcfilter, gsims, params, monitor)
return
sources = []
with monitor("filtering/splitting sources"):
for src, _sites in srcfilter(srcs):
if src.num_ruptures >= params['maxweight']:
splits, stime = split_sources([src])
sources.extend(srcfilter.filter(splits))
else:
sources.append(src)
blocks = list(block_splitter(sources, params['maxweight'],
operator.attrgetter('num_ruptures')))
if blocks:
# yield the first blocks (if any) and compute the last block in core
# NB: the last block is usually the smallest one
for block in blocks[:-1]:
yield classical, block, srcfilter, gsims, params
yield classical(blocks[-1], srcfilter, gsims, params, monitor) | [
"def",
"classical_split_filter",
"(",
"srcs",
",",
"srcfilter",
",",
"gsims",
",",
"params",
",",
"monitor",
")",
":",
"# first check if we are sampling the sources",
"ss",
"=",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'OQ_SAMPLE_SOURCES'",
",",
"0",
")",
")",
"if",
"ss",
":",
"splits",
",",
"stime",
"=",
"split_sources",
"(",
"srcs",
")",
"srcs",
"=",
"readinput",
".",
"random_filtered_sources",
"(",
"splits",
",",
"srcfilter",
",",
"ss",
")",
"yield",
"classical",
"(",
"srcs",
",",
"srcfilter",
",",
"gsims",
",",
"params",
",",
"monitor",
")",
"return",
"sources",
"=",
"[",
"]",
"with",
"monitor",
"(",
"\"filtering/splitting sources\"",
")",
":",
"for",
"src",
",",
"_sites",
"in",
"srcfilter",
"(",
"srcs",
")",
":",
"if",
"src",
".",
"num_ruptures",
">=",
"params",
"[",
"'maxweight'",
"]",
":",
"splits",
",",
"stime",
"=",
"split_sources",
"(",
"[",
"src",
"]",
")",
"sources",
".",
"extend",
"(",
"srcfilter",
".",
"filter",
"(",
"splits",
")",
")",
"else",
":",
"sources",
".",
"append",
"(",
"src",
")",
"blocks",
"=",
"list",
"(",
"block_splitter",
"(",
"sources",
",",
"params",
"[",
"'maxweight'",
"]",
",",
"operator",
".",
"attrgetter",
"(",
"'num_ruptures'",
")",
")",
")",
"if",
"blocks",
":",
"# yield the first blocks (if any) and compute the last block in core",
"# NB: the last block is usually the smallest one",
"for",
"block",
"in",
"blocks",
"[",
":",
"-",
"1",
"]",
":",
"yield",
"classical",
",",
"block",
",",
"srcfilter",
",",
"gsims",
",",
"params",
"yield",
"classical",
"(",
"blocks",
"[",
"-",
"1",
"]",
",",
"srcfilter",
",",
"gsims",
",",
"params",
",",
"monitor",
")"
] | Split the given sources, filter the subsources and the compute the
PoEs. Yield back subtasks if the split sources contain more than
maxweight ruptures. | [
"Split",
"the",
"given",
"sources",
"filter",
"the",
"subsources",
"and",
"the",
"compute",
"the",
"PoEs",
".",
"Yield",
"back",
"subtasks",
"if",
"the",
"split",
"sources",
"contain",
"more",
"than",
"maxweight",
"ruptures",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/classical.py#L72-L100 | train | 232,986 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_utils.py | get_azimuth_plunge | def get_azimuth_plunge(vect, degrees=True):
'''
For a given vector in USE format, retrieve the azimuth and plunge
'''
if vect[0] > 0:
vect = -1. * np.copy(vect)
vect_hor = sqrt(vect[1] ** 2. + vect[2] ** 2.)
plunge = atan2(-vect[0], vect_hor)
azimuth = atan2(vect[2], -vect[1])
if degrees:
icr = 180. / pi
return icr * azimuth % 360., icr * plunge
else:
return azimuth % (2. * pi), plunge | python | def get_azimuth_plunge(vect, degrees=True):
'''
For a given vector in USE format, retrieve the azimuth and plunge
'''
if vect[0] > 0:
vect = -1. * np.copy(vect)
vect_hor = sqrt(vect[1] ** 2. + vect[2] ** 2.)
plunge = atan2(-vect[0], vect_hor)
azimuth = atan2(vect[2], -vect[1])
if degrees:
icr = 180. / pi
return icr * azimuth % 360., icr * plunge
else:
return azimuth % (2. * pi), plunge | [
"def",
"get_azimuth_plunge",
"(",
"vect",
",",
"degrees",
"=",
"True",
")",
":",
"if",
"vect",
"[",
"0",
"]",
">",
"0",
":",
"vect",
"=",
"-",
"1.",
"*",
"np",
".",
"copy",
"(",
"vect",
")",
"vect_hor",
"=",
"sqrt",
"(",
"vect",
"[",
"1",
"]",
"**",
"2.",
"+",
"vect",
"[",
"2",
"]",
"**",
"2.",
")",
"plunge",
"=",
"atan2",
"(",
"-",
"vect",
"[",
"0",
"]",
",",
"vect_hor",
")",
"azimuth",
"=",
"atan2",
"(",
"vect",
"[",
"2",
"]",
",",
"-",
"vect",
"[",
"1",
"]",
")",
"if",
"degrees",
":",
"icr",
"=",
"180.",
"/",
"pi",
"return",
"icr",
"*",
"azimuth",
"%",
"360.",
",",
"icr",
"*",
"plunge",
"else",
":",
"return",
"azimuth",
"%",
"(",
"2.",
"*",
"pi",
")",
",",
"plunge"
] | For a given vector in USE format, retrieve the azimuth and plunge | [
"For",
"a",
"given",
"vector",
"in",
"USE",
"format",
"retrieve",
"the",
"azimuth",
"and",
"plunge"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L77-L90 | train | 232,987 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_utils.py | use_to_ned | def use_to_ned(tensor):
'''
Converts a tensor in USE coordinate sytem to NED
'''
return np.array(ROT_NED_USE.T * np.matrix(tensor) * ROT_NED_USE) | python | def use_to_ned(tensor):
'''
Converts a tensor in USE coordinate sytem to NED
'''
return np.array(ROT_NED_USE.T * np.matrix(tensor) * ROT_NED_USE) | [
"def",
"use_to_ned",
"(",
"tensor",
")",
":",
"return",
"np",
".",
"array",
"(",
"ROT_NED_USE",
".",
"T",
"*",
"np",
".",
"matrix",
"(",
"tensor",
")",
"*",
"ROT_NED_USE",
")"
] | Converts a tensor in USE coordinate sytem to NED | [
"Converts",
"a",
"tensor",
"in",
"USE",
"coordinate",
"sytem",
"to",
"NED"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L101-L105 | train | 232,988 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_utils.py | ned_to_use | def ned_to_use(tensor):
'''
Converts a tensor in NED coordinate sytem to USE
'''
return np.array(ROT_NED_USE * np.matrix(tensor) * ROT_NED_USE.T) | python | def ned_to_use(tensor):
'''
Converts a tensor in NED coordinate sytem to USE
'''
return np.array(ROT_NED_USE * np.matrix(tensor) * ROT_NED_USE.T) | [
"def",
"ned_to_use",
"(",
"tensor",
")",
":",
"return",
"np",
".",
"array",
"(",
"ROT_NED_USE",
"*",
"np",
".",
"matrix",
"(",
"tensor",
")",
"*",
"ROT_NED_USE",
".",
"T",
")"
] | Converts a tensor in NED coordinate sytem to USE | [
"Converts",
"a",
"tensor",
"in",
"NED",
"coordinate",
"sytem",
"to",
"USE"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L108-L112 | train | 232,989 |
gem/oq-engine | openquake/hazardlib/gsim/boore_atkinson_2008.py | Atkinson2010Hawaii.get_mean_and_stddevs | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
Using a frequency dependent correction for the mean ground motion.
Standard deviation is fixed.
"""
mean, stddevs = super().get_mean_and_stddevs(sites, rup, dists,
imt, stddev_types)
# Defining frequency
if imt == PGA():
freq = 50.0
elif imt == PGV():
freq = 2.0
else:
freq = 1./imt.period
# Equation 3 of Atkinson (2010)
x1 = np.min([-0.18+0.17*np.log10(freq), 0])
# Equation 4 a-b-c of Atkinson (2010)
if rup.hypo_depth < 20.0:
x0 = np.max([0.217-0.321*np.log10(freq), 0])
elif rup.hypo_depth > 35.0:
x0 = np.min([0.263+0.0924*np.log10(freq), 0.35])
else:
x0 = 0.2
# Limiting calculation distance to 1km
# (as suggested by C. Bruce Worden)
rjb = [d if d > 1 else 1 for d in dists.rjb]
# Equation 2 and 5 of Atkinson (2010)
mean += (x0 + x1*np.log10(rjb))/np.log10(np.e)
return mean, stddevs | python | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
Using a frequency dependent correction for the mean ground motion.
Standard deviation is fixed.
"""
mean, stddevs = super().get_mean_and_stddevs(sites, rup, dists,
imt, stddev_types)
# Defining frequency
if imt == PGA():
freq = 50.0
elif imt == PGV():
freq = 2.0
else:
freq = 1./imt.period
# Equation 3 of Atkinson (2010)
x1 = np.min([-0.18+0.17*np.log10(freq), 0])
# Equation 4 a-b-c of Atkinson (2010)
if rup.hypo_depth < 20.0:
x0 = np.max([0.217-0.321*np.log10(freq), 0])
elif rup.hypo_depth > 35.0:
x0 = np.min([0.263+0.0924*np.log10(freq), 0.35])
else:
x0 = 0.2
# Limiting calculation distance to 1km
# (as suggested by C. Bruce Worden)
rjb = [d if d > 1 else 1 for d in dists.rjb]
# Equation 2 and 5 of Atkinson (2010)
mean += (x0 + x1*np.log10(rjb))/np.log10(np.e)
return mean, stddevs | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"mean",
",",
"stddevs",
"=",
"super",
"(",
")",
".",
"get_mean_and_stddevs",
"(",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
"# Defining frequency",
"if",
"imt",
"==",
"PGA",
"(",
")",
":",
"freq",
"=",
"50.0",
"elif",
"imt",
"==",
"PGV",
"(",
")",
":",
"freq",
"=",
"2.0",
"else",
":",
"freq",
"=",
"1.",
"/",
"imt",
".",
"period",
"# Equation 3 of Atkinson (2010)",
"x1",
"=",
"np",
".",
"min",
"(",
"[",
"-",
"0.18",
"+",
"0.17",
"*",
"np",
".",
"log10",
"(",
"freq",
")",
",",
"0",
"]",
")",
"# Equation 4 a-b-c of Atkinson (2010)",
"if",
"rup",
".",
"hypo_depth",
"<",
"20.0",
":",
"x0",
"=",
"np",
".",
"max",
"(",
"[",
"0.217",
"-",
"0.321",
"*",
"np",
".",
"log10",
"(",
"freq",
")",
",",
"0",
"]",
")",
"elif",
"rup",
".",
"hypo_depth",
">",
"35.0",
":",
"x0",
"=",
"np",
".",
"min",
"(",
"[",
"0.263",
"+",
"0.0924",
"*",
"np",
".",
"log10",
"(",
"freq",
")",
",",
"0.35",
"]",
")",
"else",
":",
"x0",
"=",
"0.2",
"# Limiting calculation distance to 1km",
"# (as suggested by C. Bruce Worden)",
"rjb",
"=",
"[",
"d",
"if",
"d",
">",
"1",
"else",
"1",
"for",
"d",
"in",
"dists",
".",
"rjb",
"]",
"# Equation 2 and 5 of Atkinson (2010)",
"mean",
"+=",
"(",
"x0",
"+",
"x1",
"*",
"np",
".",
"log10",
"(",
"rjb",
")",
")",
"/",
"np",
".",
"log10",
"(",
"np",
".",
"e",
")",
"return",
"mean",
",",
"stddevs"
] | Using a frequency dependent correction for the mean ground motion.
Standard deviation is fixed. | [
"Using",
"a",
"frequency",
"dependent",
"correction",
"for",
"the",
"mean",
"ground",
"motion",
".",
"Standard",
"deviation",
"is",
"fixed",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_atkinson_2008.py#L383-L416 | train | 232,990 |
gem/oq-engine | openquake/commonlib/rlzs_assoc.py | RlzsAssoc.get_rlz | def get_rlz(self, rlzstr):
r"""
Get a Realization instance for a string of the form 'rlz-\d+'
"""
mo = re.match(r'rlz-(\d+)', rlzstr)
if not mo:
return
return self.realizations[int(mo.group(1))] | python | def get_rlz(self, rlzstr):
r"""
Get a Realization instance for a string of the form 'rlz-\d+'
"""
mo = re.match(r'rlz-(\d+)', rlzstr)
if not mo:
return
return self.realizations[int(mo.group(1))] | [
"def",
"get_rlz",
"(",
"self",
",",
"rlzstr",
")",
":",
"mo",
"=",
"re",
".",
"match",
"(",
"r'rlz-(\\d+)'",
",",
"rlzstr",
")",
"if",
"not",
"mo",
":",
"return",
"return",
"self",
".",
"realizations",
"[",
"int",
"(",
"mo",
".",
"group",
"(",
"1",
")",
")",
"]"
] | r"""
Get a Realization instance for a string of the form 'rlz-\d+' | [
"r",
"Get",
"a",
"Realization",
"instance",
"for",
"a",
"string",
"of",
"the",
"form",
"rlz",
"-",
"\\",
"d",
"+"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/rlzs_assoc.py#L190-L197 | train | 232,991 |
gem/oq-engine | openquake/commands/export.py | export | def export(datastore_key, calc_id=-1, exports='csv', export_dir='.'):
"""
Export an output from the datastore.
"""
dstore = util.read(calc_id)
parent_id = dstore['oqparam'].hazard_calculation_id
if parent_id:
dstore.parent = util.read(parent_id)
dstore.export_dir = export_dir
with performance.Monitor('export', measuremem=True) as mon:
for fmt in exports.split(','):
fnames = export_((datastore_key, fmt), dstore)
nbytes = sum(os.path.getsize(f) for f in fnames)
print('Exported %s in %s' % (general.humansize(nbytes), fnames))
if mon.duration > 1:
print(mon)
dstore.close() | python | def export(datastore_key, calc_id=-1, exports='csv', export_dir='.'):
"""
Export an output from the datastore.
"""
dstore = util.read(calc_id)
parent_id = dstore['oqparam'].hazard_calculation_id
if parent_id:
dstore.parent = util.read(parent_id)
dstore.export_dir = export_dir
with performance.Monitor('export', measuremem=True) as mon:
for fmt in exports.split(','):
fnames = export_((datastore_key, fmt), dstore)
nbytes = sum(os.path.getsize(f) for f in fnames)
print('Exported %s in %s' % (general.humansize(nbytes), fnames))
if mon.duration > 1:
print(mon)
dstore.close() | [
"def",
"export",
"(",
"datastore_key",
",",
"calc_id",
"=",
"-",
"1",
",",
"exports",
"=",
"'csv'",
",",
"export_dir",
"=",
"'.'",
")",
":",
"dstore",
"=",
"util",
".",
"read",
"(",
"calc_id",
")",
"parent_id",
"=",
"dstore",
"[",
"'oqparam'",
"]",
".",
"hazard_calculation_id",
"if",
"parent_id",
":",
"dstore",
".",
"parent",
"=",
"util",
".",
"read",
"(",
"parent_id",
")",
"dstore",
".",
"export_dir",
"=",
"export_dir",
"with",
"performance",
".",
"Monitor",
"(",
"'export'",
",",
"measuremem",
"=",
"True",
")",
"as",
"mon",
":",
"for",
"fmt",
"in",
"exports",
".",
"split",
"(",
"','",
")",
":",
"fnames",
"=",
"export_",
"(",
"(",
"datastore_key",
",",
"fmt",
")",
",",
"dstore",
")",
"nbytes",
"=",
"sum",
"(",
"os",
".",
"path",
".",
"getsize",
"(",
"f",
")",
"for",
"f",
"in",
"fnames",
")",
"print",
"(",
"'Exported %s in %s'",
"%",
"(",
"general",
".",
"humansize",
"(",
"nbytes",
")",
",",
"fnames",
")",
")",
"if",
"mon",
".",
"duration",
">",
"1",
":",
"print",
"(",
"mon",
")",
"dstore",
".",
"close",
"(",
")"
] | Export an output from the datastore. | [
"Export",
"an",
"output",
"from",
"the",
"datastore",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/export.py#L27-L43 | train | 232,992 |
gem/oq-engine | openquake/calculators/ucerf_base.py | convert_UCERFSource | def convert_UCERFSource(self, node):
"""
Converts the Ucerf Source node into an SES Control object
"""
dirname = os.path.dirname(self.fname) # where the source_model_file is
source_file = os.path.join(dirname, node["filename"])
if "startDate" in node.attrib and "investigationTime" in node.attrib:
# Is a time-dependent model - even if rates were originally
# poissonian
# Verify that the source time span is the same as the TOM time span
inv_time = float(node["investigationTime"])
if inv_time != self.investigation_time:
raise ValueError("Source investigation time (%s) is not "
"equal to configuration investigation time "
"(%s)" % (inv_time, self.investigation_time))
start_date = datetime.strptime(node["startDate"], "%d/%m/%Y")
else:
start_date = None
return UCERFSource(
source_file,
self.investigation_time,
start_date,
float(node["minMag"]),
npd=self.convert_npdist(node),
hdd=self.convert_hpdist(node),
aspect=~node.ruptAspectRatio,
upper_seismogenic_depth=~node.pointGeometry.upperSeismoDepth,
lower_seismogenic_depth=~node.pointGeometry.lowerSeismoDepth,
msr=valid.SCALEREL[~node.magScaleRel](),
mesh_spacing=self.rupture_mesh_spacing,
trt=node["tectonicRegion"]) | python | def convert_UCERFSource(self, node):
"""
Converts the Ucerf Source node into an SES Control object
"""
dirname = os.path.dirname(self.fname) # where the source_model_file is
source_file = os.path.join(dirname, node["filename"])
if "startDate" in node.attrib and "investigationTime" in node.attrib:
# Is a time-dependent model - even if rates were originally
# poissonian
# Verify that the source time span is the same as the TOM time span
inv_time = float(node["investigationTime"])
if inv_time != self.investigation_time:
raise ValueError("Source investigation time (%s) is not "
"equal to configuration investigation time "
"(%s)" % (inv_time, self.investigation_time))
start_date = datetime.strptime(node["startDate"], "%d/%m/%Y")
else:
start_date = None
return UCERFSource(
source_file,
self.investigation_time,
start_date,
float(node["minMag"]),
npd=self.convert_npdist(node),
hdd=self.convert_hpdist(node),
aspect=~node.ruptAspectRatio,
upper_seismogenic_depth=~node.pointGeometry.upperSeismoDepth,
lower_seismogenic_depth=~node.pointGeometry.lowerSeismoDepth,
msr=valid.SCALEREL[~node.magScaleRel](),
mesh_spacing=self.rupture_mesh_spacing,
trt=node["tectonicRegion"]) | [
"def",
"convert_UCERFSource",
"(",
"self",
",",
"node",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"fname",
")",
"# where the source_model_file is",
"source_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"node",
"[",
"\"filename\"",
"]",
")",
"if",
"\"startDate\"",
"in",
"node",
".",
"attrib",
"and",
"\"investigationTime\"",
"in",
"node",
".",
"attrib",
":",
"# Is a time-dependent model - even if rates were originally",
"# poissonian",
"# Verify that the source time span is the same as the TOM time span",
"inv_time",
"=",
"float",
"(",
"node",
"[",
"\"investigationTime\"",
"]",
")",
"if",
"inv_time",
"!=",
"self",
".",
"investigation_time",
":",
"raise",
"ValueError",
"(",
"\"Source investigation time (%s) is not \"",
"\"equal to configuration investigation time \"",
"\"(%s)\"",
"%",
"(",
"inv_time",
",",
"self",
".",
"investigation_time",
")",
")",
"start_date",
"=",
"datetime",
".",
"strptime",
"(",
"node",
"[",
"\"startDate\"",
"]",
",",
"\"%d/%m/%Y\"",
")",
"else",
":",
"start_date",
"=",
"None",
"return",
"UCERFSource",
"(",
"source_file",
",",
"self",
".",
"investigation_time",
",",
"start_date",
",",
"float",
"(",
"node",
"[",
"\"minMag\"",
"]",
")",
",",
"npd",
"=",
"self",
".",
"convert_npdist",
"(",
"node",
")",
",",
"hdd",
"=",
"self",
".",
"convert_hpdist",
"(",
"node",
")",
",",
"aspect",
"=",
"~",
"node",
".",
"ruptAspectRatio",
",",
"upper_seismogenic_depth",
"=",
"~",
"node",
".",
"pointGeometry",
".",
"upperSeismoDepth",
",",
"lower_seismogenic_depth",
"=",
"~",
"node",
".",
"pointGeometry",
".",
"lowerSeismoDepth",
",",
"msr",
"=",
"valid",
".",
"SCALEREL",
"[",
"~",
"node",
".",
"magScaleRel",
"]",
"(",
")",
",",
"mesh_spacing",
"=",
"self",
".",
"rupture_mesh_spacing",
",",
"trt",
"=",
"node",
"[",
"\"tectonicRegion\"",
"]",
")"
] | Converts the Ucerf Source node into an SES Control object | [
"Converts",
"the",
"Ucerf",
"Source",
"node",
"into",
"an",
"SES",
"Control",
"object"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L58-L88 | train | 232,993 |
gem/oq-engine | openquake/calculators/ucerf_base.py | build_idx_set | def build_idx_set(branch_id, start_date):
"""
Builds a dictionary of keys based on the branch code
"""
code_set = branch_id.split("/")
code_set.insert(3, "Rates")
idx_set = {
"sec": "/".join([code_set[0], code_set[1], "Sections"]),
"mag": "/".join([code_set[0], code_set[1], code_set[2], "Magnitude"])}
idx_set["rate"] = "/".join(code_set)
idx_set["rake"] = "/".join([code_set[0], code_set[1], "Rake"])
idx_set["msr"] = "-".join(code_set[:3])
idx_set["geol"] = code_set[0]
if start_date: # time-dependent source
idx_set["grid_key"] = "_".join(
branch_id.replace("/", "_").split("_")[:-1])
else: # time-independent source
idx_set["grid_key"] = branch_id.replace("/", "_")
idx_set["total_key"] = branch_id.replace("/", "|")
return idx_set | python | def build_idx_set(branch_id, start_date):
"""
Builds a dictionary of keys based on the branch code
"""
code_set = branch_id.split("/")
code_set.insert(3, "Rates")
idx_set = {
"sec": "/".join([code_set[0], code_set[1], "Sections"]),
"mag": "/".join([code_set[0], code_set[1], code_set[2], "Magnitude"])}
idx_set["rate"] = "/".join(code_set)
idx_set["rake"] = "/".join([code_set[0], code_set[1], "Rake"])
idx_set["msr"] = "-".join(code_set[:3])
idx_set["geol"] = code_set[0]
if start_date: # time-dependent source
idx_set["grid_key"] = "_".join(
branch_id.replace("/", "_").split("_")[:-1])
else: # time-independent source
idx_set["grid_key"] = branch_id.replace("/", "_")
idx_set["total_key"] = branch_id.replace("/", "|")
return idx_set | [
"def",
"build_idx_set",
"(",
"branch_id",
",",
"start_date",
")",
":",
"code_set",
"=",
"branch_id",
".",
"split",
"(",
"\"/\"",
")",
"code_set",
".",
"insert",
"(",
"3",
",",
"\"Rates\"",
")",
"idx_set",
"=",
"{",
"\"sec\"",
":",
"\"/\"",
".",
"join",
"(",
"[",
"code_set",
"[",
"0",
"]",
",",
"code_set",
"[",
"1",
"]",
",",
"\"Sections\"",
"]",
")",
",",
"\"mag\"",
":",
"\"/\"",
".",
"join",
"(",
"[",
"code_set",
"[",
"0",
"]",
",",
"code_set",
"[",
"1",
"]",
",",
"code_set",
"[",
"2",
"]",
",",
"\"Magnitude\"",
"]",
")",
"}",
"idx_set",
"[",
"\"rate\"",
"]",
"=",
"\"/\"",
".",
"join",
"(",
"code_set",
")",
"idx_set",
"[",
"\"rake\"",
"]",
"=",
"\"/\"",
".",
"join",
"(",
"[",
"code_set",
"[",
"0",
"]",
",",
"code_set",
"[",
"1",
"]",
",",
"\"Rake\"",
"]",
")",
"idx_set",
"[",
"\"msr\"",
"]",
"=",
"\"-\"",
".",
"join",
"(",
"code_set",
"[",
":",
"3",
"]",
")",
"idx_set",
"[",
"\"geol\"",
"]",
"=",
"code_set",
"[",
"0",
"]",
"if",
"start_date",
":",
"# time-dependent source",
"idx_set",
"[",
"\"grid_key\"",
"]",
"=",
"\"_\"",
".",
"join",
"(",
"branch_id",
".",
"replace",
"(",
"\"/\"",
",",
"\"_\"",
")",
".",
"split",
"(",
"\"_\"",
")",
"[",
":",
"-",
"1",
"]",
")",
"else",
":",
"# time-independent source",
"idx_set",
"[",
"\"grid_key\"",
"]",
"=",
"branch_id",
".",
"replace",
"(",
"\"/\"",
",",
"\"_\"",
")",
"idx_set",
"[",
"\"total_key\"",
"]",
"=",
"branch_id",
".",
"replace",
"(",
"\"/\"",
",",
"\"|\"",
")",
"return",
"idx_set"
] | Builds a dictionary of keys based on the branch code | [
"Builds",
"a",
"dictionary",
"of",
"keys",
"based",
"on",
"the",
"branch",
"code"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L433-L452 | train | 232,994 |
gem/oq-engine | openquake/calculators/ucerf_base.py | get_rupture_surface | def get_rupture_surface(mag, nodal_plane, hypocenter, msr,
rupture_aspect_ratio, upper_seismogenic_depth,
lower_seismogenic_depth, mesh_spacing=1.0):
"""
Create and return rupture surface object with given properties.
:param mag:
Magnitude value, used to calculate rupture dimensions,
see :meth:`_get_rupture_dimensions`.
:param nodal_plane:
Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane`
describing the rupture orientation.
:param hypocenter:
Point representing rupture's hypocenter.
:returns:
Instance of
:class:`~openquake.hazardlib.geo.surface.planar.PlanarSurface`.
"""
assert (upper_seismogenic_depth <= hypocenter.depth
and lower_seismogenic_depth >= hypocenter.depth)
rdip = math.radians(nodal_plane.dip)
# precalculated azimuth values for horizontal-only and vertical-only
# moves from one point to another on the plane defined by strike
# and dip:
azimuth_right = nodal_plane.strike
azimuth_down = (azimuth_right + 90) % 360
azimuth_left = (azimuth_down + 90) % 360
azimuth_up = (azimuth_left + 90) % 360
rup_length, rup_width = get_rupture_dimensions(
mag, nodal_plane, msr, rupture_aspect_ratio, upper_seismogenic_depth,
lower_seismogenic_depth)
# calculate the height of the rupture being projected
# on the vertical plane:
rup_proj_height = rup_width * math.sin(rdip)
# and it's width being projected on the horizontal one:
rup_proj_width = rup_width * math.cos(rdip)
# half height of the vertical component of rupture width
# is the vertical distance between the rupture geometrical
# center and it's upper and lower borders:
hheight = rup_proj_height / 2
# calculate how much shallower the upper border of the rupture
# is than the upper seismogenic depth:
vshift = upper_seismogenic_depth - hypocenter.depth + hheight
# if it is shallower (vshift > 0) than we need to move the rupture
# by that value vertically.
if vshift < 0:
# the top edge is below upper seismogenic depth. now we need
# to check that we do not cross the lower border.
vshift = lower_seismogenic_depth - hypocenter.depth - hheight
if vshift > 0:
# the bottom edge of the rupture is above the lower sesmogenic
# depth. that means that we don't need to move the rupture
# as it fits inside seismogenic layer.
vshift = 0
# if vshift < 0 than we need to move the rupture up by that value.
# now we need to find the position of rupture's geometrical center.
# in any case the hypocenter point must lie on the surface, however
# the rupture center might be off (below or above) along the dip.
rupture_center = hypocenter
if vshift != 0:
# we need to move the rupture center to make the rupture fit
# inside the seismogenic layer.
hshift = abs(vshift / math.tan(rdip))
rupture_center = rupture_center.point_at(
horizontal_distance=hshift, vertical_increment=vshift,
azimuth=(azimuth_up if vshift < 0 else azimuth_down))
# from the rupture center we can now compute the coordinates of the
# four coorners by moving along the diagonals of the plane. This seems
# to be better then moving along the perimeter, because in this case
# errors are accumulated that induce distorsions in the shape with
# consequent raise of exceptions when creating PlanarSurface objects
# theta is the angle between the diagonal of the surface projection
# and the line passing through the rupture center and parallel to the
# top and bottom edges. Theta is zero for vertical ruptures (because
# rup_proj_width is zero)
theta = math.degrees(
math.atan((rup_proj_width / 2.) / (rup_length / 2.)))
hor_dist = math.sqrt(
(rup_length / 2.) ** 2 + (rup_proj_width / 2.) ** 2)
left_top = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=-rup_proj_height / 2,
azimuth=(nodal_plane.strike + 180 + theta) % 360)
right_top = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=-rup_proj_height / 2,
azimuth=(nodal_plane.strike - theta) % 360)
left_bottom = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=rup_proj_height / 2,
azimuth=(nodal_plane.strike + 180 - theta) % 360)
right_bottom = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=rup_proj_height / 2,
azimuth=(nodal_plane.strike + theta) % 360)
return PlanarSurface(nodal_plane.strike, nodal_plane.dip,
left_top, right_top, right_bottom, left_bottom) | python | def get_rupture_surface(mag, nodal_plane, hypocenter, msr,
rupture_aspect_ratio, upper_seismogenic_depth,
lower_seismogenic_depth, mesh_spacing=1.0):
"""
Create and return rupture surface object with given properties.
:param mag:
Magnitude value, used to calculate rupture dimensions,
see :meth:`_get_rupture_dimensions`.
:param nodal_plane:
Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane`
describing the rupture orientation.
:param hypocenter:
Point representing rupture's hypocenter.
:returns:
Instance of
:class:`~openquake.hazardlib.geo.surface.planar.PlanarSurface`.
"""
assert (upper_seismogenic_depth <= hypocenter.depth
and lower_seismogenic_depth >= hypocenter.depth)
rdip = math.radians(nodal_plane.dip)
# precalculated azimuth values for horizontal-only and vertical-only
# moves from one point to another on the plane defined by strike
# and dip:
azimuth_right = nodal_plane.strike
azimuth_down = (azimuth_right + 90) % 360
azimuth_left = (azimuth_down + 90) % 360
azimuth_up = (azimuth_left + 90) % 360
rup_length, rup_width = get_rupture_dimensions(
mag, nodal_plane, msr, rupture_aspect_ratio, upper_seismogenic_depth,
lower_seismogenic_depth)
# calculate the height of the rupture being projected
# on the vertical plane:
rup_proj_height = rup_width * math.sin(rdip)
# and it's width being projected on the horizontal one:
rup_proj_width = rup_width * math.cos(rdip)
# half height of the vertical component of rupture width
# is the vertical distance between the rupture geometrical
# center and it's upper and lower borders:
hheight = rup_proj_height / 2
# calculate how much shallower the upper border of the rupture
# is than the upper seismogenic depth:
vshift = upper_seismogenic_depth - hypocenter.depth + hheight
# if it is shallower (vshift > 0) than we need to move the rupture
# by that value vertically.
if vshift < 0:
# the top edge is below upper seismogenic depth. now we need
# to check that we do not cross the lower border.
vshift = lower_seismogenic_depth - hypocenter.depth - hheight
if vshift > 0:
# the bottom edge of the rupture is above the lower sesmogenic
# depth. that means that we don't need to move the rupture
# as it fits inside seismogenic layer.
vshift = 0
# if vshift < 0 than we need to move the rupture up by that value.
# now we need to find the position of rupture's geometrical center.
# in any case the hypocenter point must lie on the surface, however
# the rupture center might be off (below or above) along the dip.
rupture_center = hypocenter
if vshift != 0:
# we need to move the rupture center to make the rupture fit
# inside the seismogenic layer.
hshift = abs(vshift / math.tan(rdip))
rupture_center = rupture_center.point_at(
horizontal_distance=hshift, vertical_increment=vshift,
azimuth=(azimuth_up if vshift < 0 else azimuth_down))
# from the rupture center we can now compute the coordinates of the
# four coorners by moving along the diagonals of the plane. This seems
# to be better then moving along the perimeter, because in this case
# errors are accumulated that induce distorsions in the shape with
# consequent raise of exceptions when creating PlanarSurface objects
# theta is the angle between the diagonal of the surface projection
# and the line passing through the rupture center and parallel to the
# top and bottom edges. Theta is zero for vertical ruptures (because
# rup_proj_width is zero)
theta = math.degrees(
math.atan((rup_proj_width / 2.) / (rup_length / 2.)))
hor_dist = math.sqrt(
(rup_length / 2.) ** 2 + (rup_proj_width / 2.) ** 2)
left_top = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=-rup_proj_height / 2,
azimuth=(nodal_plane.strike + 180 + theta) % 360)
right_top = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=-rup_proj_height / 2,
azimuth=(nodal_plane.strike - theta) % 360)
left_bottom = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=rup_proj_height / 2,
azimuth=(nodal_plane.strike + 180 - theta) % 360)
right_bottom = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=rup_proj_height / 2,
azimuth=(nodal_plane.strike + theta) % 360)
return PlanarSurface(nodal_plane.strike, nodal_plane.dip,
left_top, right_top, right_bottom, left_bottom) | [
"def",
"get_rupture_surface",
"(",
"mag",
",",
"nodal_plane",
",",
"hypocenter",
",",
"msr",
",",
"rupture_aspect_ratio",
",",
"upper_seismogenic_depth",
",",
"lower_seismogenic_depth",
",",
"mesh_spacing",
"=",
"1.0",
")",
":",
"assert",
"(",
"upper_seismogenic_depth",
"<=",
"hypocenter",
".",
"depth",
"and",
"lower_seismogenic_depth",
">=",
"hypocenter",
".",
"depth",
")",
"rdip",
"=",
"math",
".",
"radians",
"(",
"nodal_plane",
".",
"dip",
")",
"# precalculated azimuth values for horizontal-only and vertical-only",
"# moves from one point to another on the plane defined by strike",
"# and dip:",
"azimuth_right",
"=",
"nodal_plane",
".",
"strike",
"azimuth_down",
"=",
"(",
"azimuth_right",
"+",
"90",
")",
"%",
"360",
"azimuth_left",
"=",
"(",
"azimuth_down",
"+",
"90",
")",
"%",
"360",
"azimuth_up",
"=",
"(",
"azimuth_left",
"+",
"90",
")",
"%",
"360",
"rup_length",
",",
"rup_width",
"=",
"get_rupture_dimensions",
"(",
"mag",
",",
"nodal_plane",
",",
"msr",
",",
"rupture_aspect_ratio",
",",
"upper_seismogenic_depth",
",",
"lower_seismogenic_depth",
")",
"# calculate the height of the rupture being projected",
"# on the vertical plane:",
"rup_proj_height",
"=",
"rup_width",
"*",
"math",
".",
"sin",
"(",
"rdip",
")",
"# and it's width being projected on the horizontal one:",
"rup_proj_width",
"=",
"rup_width",
"*",
"math",
".",
"cos",
"(",
"rdip",
")",
"# half height of the vertical component of rupture width",
"# is the vertical distance between the rupture geometrical",
"# center and it's upper and lower borders:",
"hheight",
"=",
"rup_proj_height",
"/",
"2",
"# calculate how much shallower the upper border of the rupture",
"# is than the upper seismogenic depth:",
"vshift",
"=",
"upper_seismogenic_depth",
"-",
"hypocenter",
".",
"depth",
"+",
"hheight",
"# if it is shallower (vshift > 0) than we need to move the rupture",
"# by that value vertically.",
"if",
"vshift",
"<",
"0",
":",
"# the top edge is below upper seismogenic depth. now we need",
"# to check that we do not cross the lower border.",
"vshift",
"=",
"lower_seismogenic_depth",
"-",
"hypocenter",
".",
"depth",
"-",
"hheight",
"if",
"vshift",
">",
"0",
":",
"# the bottom edge of the rupture is above the lower sesmogenic",
"# depth. that means that we don't need to move the rupture",
"# as it fits inside seismogenic layer.",
"vshift",
"=",
"0",
"# if vshift < 0 than we need to move the rupture up by that value.",
"# now we need to find the position of rupture's geometrical center.",
"# in any case the hypocenter point must lie on the surface, however",
"# the rupture center might be off (below or above) along the dip.",
"rupture_center",
"=",
"hypocenter",
"if",
"vshift",
"!=",
"0",
":",
"# we need to move the rupture center to make the rupture fit",
"# inside the seismogenic layer.",
"hshift",
"=",
"abs",
"(",
"vshift",
"/",
"math",
".",
"tan",
"(",
"rdip",
")",
")",
"rupture_center",
"=",
"rupture_center",
".",
"point_at",
"(",
"horizontal_distance",
"=",
"hshift",
",",
"vertical_increment",
"=",
"vshift",
",",
"azimuth",
"=",
"(",
"azimuth_up",
"if",
"vshift",
"<",
"0",
"else",
"azimuth_down",
")",
")",
"# from the rupture center we can now compute the coordinates of the",
"# four coorners by moving along the diagonals of the plane. This seems",
"# to be better then moving along the perimeter, because in this case",
"# errors are accumulated that induce distorsions in the shape with",
"# consequent raise of exceptions when creating PlanarSurface objects",
"# theta is the angle between the diagonal of the surface projection",
"# and the line passing through the rupture center and parallel to the",
"# top and bottom edges. Theta is zero for vertical ruptures (because",
"# rup_proj_width is zero)",
"theta",
"=",
"math",
".",
"degrees",
"(",
"math",
".",
"atan",
"(",
"(",
"rup_proj_width",
"/",
"2.",
")",
"/",
"(",
"rup_length",
"/",
"2.",
")",
")",
")",
"hor_dist",
"=",
"math",
".",
"sqrt",
"(",
"(",
"rup_length",
"/",
"2.",
")",
"**",
"2",
"+",
"(",
"rup_proj_width",
"/",
"2.",
")",
"**",
"2",
")",
"left_top",
"=",
"rupture_center",
".",
"point_at",
"(",
"horizontal_distance",
"=",
"hor_dist",
",",
"vertical_increment",
"=",
"-",
"rup_proj_height",
"/",
"2",
",",
"azimuth",
"=",
"(",
"nodal_plane",
".",
"strike",
"+",
"180",
"+",
"theta",
")",
"%",
"360",
")",
"right_top",
"=",
"rupture_center",
".",
"point_at",
"(",
"horizontal_distance",
"=",
"hor_dist",
",",
"vertical_increment",
"=",
"-",
"rup_proj_height",
"/",
"2",
",",
"azimuth",
"=",
"(",
"nodal_plane",
".",
"strike",
"-",
"theta",
")",
"%",
"360",
")",
"left_bottom",
"=",
"rupture_center",
".",
"point_at",
"(",
"horizontal_distance",
"=",
"hor_dist",
",",
"vertical_increment",
"=",
"rup_proj_height",
"/",
"2",
",",
"azimuth",
"=",
"(",
"nodal_plane",
".",
"strike",
"+",
"180",
"-",
"theta",
")",
"%",
"360",
")",
"right_bottom",
"=",
"rupture_center",
".",
"point_at",
"(",
"horizontal_distance",
"=",
"hor_dist",
",",
"vertical_increment",
"=",
"rup_proj_height",
"/",
"2",
",",
"azimuth",
"=",
"(",
"nodal_plane",
".",
"strike",
"+",
"theta",
")",
"%",
"360",
")",
"return",
"PlanarSurface",
"(",
"nodal_plane",
".",
"strike",
",",
"nodal_plane",
".",
"dip",
",",
"left_top",
",",
"right_top",
",",
"right_bottom",
",",
"left_bottom",
")"
] | Create and return rupture surface object with given properties.
:param mag:
Magnitude value, used to calculate rupture dimensions,
see :meth:`_get_rupture_dimensions`.
:param nodal_plane:
Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane`
describing the rupture orientation.
:param hypocenter:
Point representing rupture's hypocenter.
:returns:
Instance of
:class:`~openquake.hazardlib.geo.surface.planar.PlanarSurface`. | [
"Create",
"and",
"return",
"rupture",
"surface",
"object",
"with",
"given",
"properties",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L492-L593 | train | 232,995 |
gem/oq-engine | openquake/calculators/ucerf_base.py | UCERFSource.get_ridx | def get_ridx(self, iloc):
"""List of rupture indices for the given iloc"""
with h5py.File(self.source_file, "r") as hdf5:
return hdf5[self.idx_set["geol"] + "/RuptureIndex"][iloc] | python | def get_ridx(self, iloc):
"""List of rupture indices for the given iloc"""
with h5py.File(self.source_file, "r") as hdf5:
return hdf5[self.idx_set["geol"] + "/RuptureIndex"][iloc] | [
"def",
"get_ridx",
"(",
"self",
",",
"iloc",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"self",
".",
"source_file",
",",
"\"r\"",
")",
"as",
"hdf5",
":",
"return",
"hdf5",
"[",
"self",
".",
"idx_set",
"[",
"\"geol\"",
"]",
"+",
"\"/RuptureIndex\"",
"]",
"[",
"iloc",
"]"
] | List of rupture indices for the given iloc | [
"List",
"of",
"rupture",
"indices",
"for",
"the",
"given",
"iloc"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L271-L274 | train | 232,996 |
gem/oq-engine | openquake/calculators/ucerf_base.py | UCERFSource.get_background_sids | def get_background_sids(self, src_filter):
"""
We can apply the filtering of the background sites as a pre-processing
step - this is done here rather than in the sampling of the ruptures
themselves
"""
branch_key = self.idx_set["grid_key"]
idist = src_filter.integration_distance(DEFAULT_TRT)
with h5py.File(self.source_file, 'r') as hdf5:
bg_locations = hdf5["Grid/Locations"].value
distances = min_geodetic_distance(
src_filter.sitecol.xyz,
(bg_locations[:, 0], bg_locations[:, 1]))
# Add buffer equal to half of length of median area from Mmax
mmax_areas = self.msr.get_median_area(
hdf5["/".join(["Grid", branch_key, "MMax"])].value, 0.0)
# for instance hdf5['Grid/FM0_0_MEANFS_MEANMSR/MMax']
mmax_lengths = numpy.sqrt(mmax_areas / self.aspect)
ok = distances <= (0.5 * mmax_lengths + idist)
# get list of indices from array of booleans
return numpy.where(ok)[0].tolist() | python | def get_background_sids(self, src_filter):
"""
We can apply the filtering of the background sites as a pre-processing
step - this is done here rather than in the sampling of the ruptures
themselves
"""
branch_key = self.idx_set["grid_key"]
idist = src_filter.integration_distance(DEFAULT_TRT)
with h5py.File(self.source_file, 'r') as hdf5:
bg_locations = hdf5["Grid/Locations"].value
distances = min_geodetic_distance(
src_filter.sitecol.xyz,
(bg_locations[:, 0], bg_locations[:, 1]))
# Add buffer equal to half of length of median area from Mmax
mmax_areas = self.msr.get_median_area(
hdf5["/".join(["Grid", branch_key, "MMax"])].value, 0.0)
# for instance hdf5['Grid/FM0_0_MEANFS_MEANMSR/MMax']
mmax_lengths = numpy.sqrt(mmax_areas / self.aspect)
ok = distances <= (0.5 * mmax_lengths + idist)
# get list of indices from array of booleans
return numpy.where(ok)[0].tolist() | [
"def",
"get_background_sids",
"(",
"self",
",",
"src_filter",
")",
":",
"branch_key",
"=",
"self",
".",
"idx_set",
"[",
"\"grid_key\"",
"]",
"idist",
"=",
"src_filter",
".",
"integration_distance",
"(",
"DEFAULT_TRT",
")",
"with",
"h5py",
".",
"File",
"(",
"self",
".",
"source_file",
",",
"'r'",
")",
"as",
"hdf5",
":",
"bg_locations",
"=",
"hdf5",
"[",
"\"Grid/Locations\"",
"]",
".",
"value",
"distances",
"=",
"min_geodetic_distance",
"(",
"src_filter",
".",
"sitecol",
".",
"xyz",
",",
"(",
"bg_locations",
"[",
":",
",",
"0",
"]",
",",
"bg_locations",
"[",
":",
",",
"1",
"]",
")",
")",
"# Add buffer equal to half of length of median area from Mmax",
"mmax_areas",
"=",
"self",
".",
"msr",
".",
"get_median_area",
"(",
"hdf5",
"[",
"\"/\"",
".",
"join",
"(",
"[",
"\"Grid\"",
",",
"branch_key",
",",
"\"MMax\"",
"]",
")",
"]",
".",
"value",
",",
"0.0",
")",
"# for instance hdf5['Grid/FM0_0_MEANFS_MEANMSR/MMax']",
"mmax_lengths",
"=",
"numpy",
".",
"sqrt",
"(",
"mmax_areas",
"/",
"self",
".",
"aspect",
")",
"ok",
"=",
"distances",
"<=",
"(",
"0.5",
"*",
"mmax_lengths",
"+",
"idist",
")",
"# get list of indices from array of booleans",
"return",
"numpy",
".",
"where",
"(",
"ok",
")",
"[",
"0",
"]",
".",
"tolist",
"(",
")"
] | We can apply the filtering of the background sites as a pre-processing
step - this is done here rather than in the sampling of the ruptures
themselves | [
"We",
"can",
"apply",
"the",
"filtering",
"of",
"the",
"background",
"sites",
"as",
"a",
"pre",
"-",
"processing",
"step",
"-",
"this",
"is",
"done",
"here",
"rather",
"than",
"in",
"the",
"sampling",
"of",
"the",
"ruptures",
"themselves"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L297-L317 | train | 232,997 |
gem/oq-engine | openquake/calculators/ucerf_base.py | UCERFSource.iter_ruptures | def iter_ruptures(self):
"""
Yield ruptures for the current set of indices
"""
assert self.orig, '%s is not fully initialized' % self
for ridx in range(self.start, self.stop):
if self.orig.rate[ridx]: # ruptures may have have zero rate
rup = self.get_ucerf_rupture(ridx, self.src_filter)
if rup:
yield rup | python | def iter_ruptures(self):
"""
Yield ruptures for the current set of indices
"""
assert self.orig, '%s is not fully initialized' % self
for ridx in range(self.start, self.stop):
if self.orig.rate[ridx]: # ruptures may have have zero rate
rup = self.get_ucerf_rupture(ridx, self.src_filter)
if rup:
yield rup | [
"def",
"iter_ruptures",
"(",
"self",
")",
":",
"assert",
"self",
".",
"orig",
",",
"'%s is not fully initialized'",
"%",
"self",
"for",
"ridx",
"in",
"range",
"(",
"self",
".",
"start",
",",
"self",
".",
"stop",
")",
":",
"if",
"self",
".",
"orig",
".",
"rate",
"[",
"ridx",
"]",
":",
"# ruptures may have have zero rate",
"rup",
"=",
"self",
".",
"get_ucerf_rupture",
"(",
"ridx",
",",
"self",
".",
"src_filter",
")",
"if",
"rup",
":",
"yield",
"rup"
] | Yield ruptures for the current set of indices | [
"Yield",
"ruptures",
"for",
"the",
"current",
"set",
"of",
"indices"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L359-L368 | train | 232,998 |
gem/oq-engine | openquake/calculators/ucerf_base.py | UCERFSource.get_background_sources | def get_background_sources(self, src_filter, sample_factor=None):
"""
Turn the background model of a given branch into a set of point sources
:param src_filter:
SourceFilter instance
:param sample_factor:
Used to reduce the sources if OQ_SAMPLE_SOURCES is set
"""
background_sids = self.get_background_sids(src_filter)
if sample_factor is not None: # hack for use in the mosaic
background_sids = random_filter(
background_sids, sample_factor, seed=42)
with h5py.File(self.source_file, "r") as hdf5:
grid_loc = "/".join(["Grid", self.idx_set["grid_key"]])
# for instance Grid/FM0_0_MEANFS_MEANMSR_MeanRates
mags = hdf5[grid_loc + "/Magnitude"].value
mmax = hdf5[grid_loc + "/MMax"][background_sids]
rates = hdf5[grid_loc + "/RateArray"][background_sids, :]
locations = hdf5["Grid/Locations"][background_sids, :]
sources = []
for i, bg_idx in enumerate(background_sids):
src_id = "_".join([self.idx_set["grid_key"], str(bg_idx)])
src_name = "|".join([self.idx_set["total_key"], str(bg_idx)])
mag_idx = (self.min_mag <= mags) & (mags < mmax[i])
src_mags = mags[mag_idx]
src_mfd = EvenlyDiscretizedMFD(
src_mags[0],
src_mags[1] - src_mags[0],
rates[i, mag_idx].tolist())
ps = PointSource(
src_id, src_name, self.tectonic_region_type, src_mfd,
self.mesh_spacing, self.msr, self.aspect, self.tom,
self.usd, self.lsd,
Point(locations[i, 0], locations[i, 1]),
self.npd, self.hdd)
ps.id = self.id
ps.src_group_id = self.src_group_id
ps.num_ruptures = ps.count_ruptures()
sources.append(ps)
return sources | python | def get_background_sources(self, src_filter, sample_factor=None):
"""
Turn the background model of a given branch into a set of point sources
:param src_filter:
SourceFilter instance
:param sample_factor:
Used to reduce the sources if OQ_SAMPLE_SOURCES is set
"""
background_sids = self.get_background_sids(src_filter)
if sample_factor is not None: # hack for use in the mosaic
background_sids = random_filter(
background_sids, sample_factor, seed=42)
with h5py.File(self.source_file, "r") as hdf5:
grid_loc = "/".join(["Grid", self.idx_set["grid_key"]])
# for instance Grid/FM0_0_MEANFS_MEANMSR_MeanRates
mags = hdf5[grid_loc + "/Magnitude"].value
mmax = hdf5[grid_loc + "/MMax"][background_sids]
rates = hdf5[grid_loc + "/RateArray"][background_sids, :]
locations = hdf5["Grid/Locations"][background_sids, :]
sources = []
for i, bg_idx in enumerate(background_sids):
src_id = "_".join([self.idx_set["grid_key"], str(bg_idx)])
src_name = "|".join([self.idx_set["total_key"], str(bg_idx)])
mag_idx = (self.min_mag <= mags) & (mags < mmax[i])
src_mags = mags[mag_idx]
src_mfd = EvenlyDiscretizedMFD(
src_mags[0],
src_mags[1] - src_mags[0],
rates[i, mag_idx].tolist())
ps = PointSource(
src_id, src_name, self.tectonic_region_type, src_mfd,
self.mesh_spacing, self.msr, self.aspect, self.tom,
self.usd, self.lsd,
Point(locations[i, 0], locations[i, 1]),
self.npd, self.hdd)
ps.id = self.id
ps.src_group_id = self.src_group_id
ps.num_ruptures = ps.count_ruptures()
sources.append(ps)
return sources | [
"def",
"get_background_sources",
"(",
"self",
",",
"src_filter",
",",
"sample_factor",
"=",
"None",
")",
":",
"background_sids",
"=",
"self",
".",
"get_background_sids",
"(",
"src_filter",
")",
"if",
"sample_factor",
"is",
"not",
"None",
":",
"# hack for use in the mosaic",
"background_sids",
"=",
"random_filter",
"(",
"background_sids",
",",
"sample_factor",
",",
"seed",
"=",
"42",
")",
"with",
"h5py",
".",
"File",
"(",
"self",
".",
"source_file",
",",
"\"r\"",
")",
"as",
"hdf5",
":",
"grid_loc",
"=",
"\"/\"",
".",
"join",
"(",
"[",
"\"Grid\"",
",",
"self",
".",
"idx_set",
"[",
"\"grid_key\"",
"]",
"]",
")",
"# for instance Grid/FM0_0_MEANFS_MEANMSR_MeanRates",
"mags",
"=",
"hdf5",
"[",
"grid_loc",
"+",
"\"/Magnitude\"",
"]",
".",
"value",
"mmax",
"=",
"hdf5",
"[",
"grid_loc",
"+",
"\"/MMax\"",
"]",
"[",
"background_sids",
"]",
"rates",
"=",
"hdf5",
"[",
"grid_loc",
"+",
"\"/RateArray\"",
"]",
"[",
"background_sids",
",",
":",
"]",
"locations",
"=",
"hdf5",
"[",
"\"Grid/Locations\"",
"]",
"[",
"background_sids",
",",
":",
"]",
"sources",
"=",
"[",
"]",
"for",
"i",
",",
"bg_idx",
"in",
"enumerate",
"(",
"background_sids",
")",
":",
"src_id",
"=",
"\"_\"",
".",
"join",
"(",
"[",
"self",
".",
"idx_set",
"[",
"\"grid_key\"",
"]",
",",
"str",
"(",
"bg_idx",
")",
"]",
")",
"src_name",
"=",
"\"|\"",
".",
"join",
"(",
"[",
"self",
".",
"idx_set",
"[",
"\"total_key\"",
"]",
",",
"str",
"(",
"bg_idx",
")",
"]",
")",
"mag_idx",
"=",
"(",
"self",
".",
"min_mag",
"<=",
"mags",
")",
"&",
"(",
"mags",
"<",
"mmax",
"[",
"i",
"]",
")",
"src_mags",
"=",
"mags",
"[",
"mag_idx",
"]",
"src_mfd",
"=",
"EvenlyDiscretizedMFD",
"(",
"src_mags",
"[",
"0",
"]",
",",
"src_mags",
"[",
"1",
"]",
"-",
"src_mags",
"[",
"0",
"]",
",",
"rates",
"[",
"i",
",",
"mag_idx",
"]",
".",
"tolist",
"(",
")",
")",
"ps",
"=",
"PointSource",
"(",
"src_id",
",",
"src_name",
",",
"self",
".",
"tectonic_region_type",
",",
"src_mfd",
",",
"self",
".",
"mesh_spacing",
",",
"self",
".",
"msr",
",",
"self",
".",
"aspect",
",",
"self",
".",
"tom",
",",
"self",
".",
"usd",
",",
"self",
".",
"lsd",
",",
"Point",
"(",
"locations",
"[",
"i",
",",
"0",
"]",
",",
"locations",
"[",
"i",
",",
"1",
"]",
")",
",",
"self",
".",
"npd",
",",
"self",
".",
"hdd",
")",
"ps",
".",
"id",
"=",
"self",
".",
"id",
"ps",
".",
"src_group_id",
"=",
"self",
".",
"src_group_id",
"ps",
".",
"num_ruptures",
"=",
"ps",
".",
"count_ruptures",
"(",
")",
"sources",
".",
"append",
"(",
"ps",
")",
"return",
"sources"
] | Turn the background model of a given branch into a set of point sources
:param src_filter:
SourceFilter instance
:param sample_factor:
Used to reduce the sources if OQ_SAMPLE_SOURCES is set | [
"Turn",
"the",
"background",
"model",
"of",
"a",
"given",
"branch",
"into",
"a",
"set",
"of",
"point",
"sources"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L387-L427 | train | 232,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.