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/hmtk/seismicity/smoothing/utils.py | get_weichert_factor | def get_weichert_factor(beta, cmag, cyear, end_year):
'''
Gets the Weichert adjustment factor for each the magnitude bins
:param float beta:
Beta value of Gutenberg & Richter parameter (b * log(10.))
:param np.ndarray cmag:
Magnitude values of the completeness table
:param np.ndarray cyear:
Year values of the completeness table
:param float end_year:
Last year for consideration in the catalogue
:returns:
Weichert adjustment factor (float)
'''
if len(cmag) > 1:
# cval corresponds to the mid-point of the completeness bins
# In the original code it requires that the magnitude bins be
# equal sizedclass IsotropicGaussian(BaseSmoothingKernel):
dmag = (cmag[1:] + cmag[:-1]) / 2.
cval = np.hstack([dmag, cmag[-1] + (dmag[-1] - cmag[-2])])
else:
# Single completeness value so Weichert factor is unity
return 1.0 / (end_year - cyear[0] + 1), None
t_f = sum(np.exp(-beta * cval)) / sum((end_year - cyear + 1) *
np.exp(-beta * cval))
return t_f, cval | python | def get_weichert_factor(beta, cmag, cyear, end_year):
'''
Gets the Weichert adjustment factor for each the magnitude bins
:param float beta:
Beta value of Gutenberg & Richter parameter (b * log(10.))
:param np.ndarray cmag:
Magnitude values of the completeness table
:param np.ndarray cyear:
Year values of the completeness table
:param float end_year:
Last year for consideration in the catalogue
:returns:
Weichert adjustment factor (float)
'''
if len(cmag) > 1:
# cval corresponds to the mid-point of the completeness bins
# In the original code it requires that the magnitude bins be
# equal sizedclass IsotropicGaussian(BaseSmoothingKernel):
dmag = (cmag[1:] + cmag[:-1]) / 2.
cval = np.hstack([dmag, cmag[-1] + (dmag[-1] - cmag[-2])])
else:
# Single completeness value so Weichert factor is unity
return 1.0 / (end_year - cyear[0] + 1), None
t_f = sum(np.exp(-beta * cval)) / sum((end_year - cyear + 1) *
np.exp(-beta * cval))
return t_f, cval | [
"def",
"get_weichert_factor",
"(",
"beta",
",",
"cmag",
",",
"cyear",
",",
"end_year",
")",
":",
"if",
"len",
"(",
"cmag",
")",
">",
"1",
":",
"# cval corresponds to the mid-point of the completeness bins",
"# In the original code it requires that the magnitude bins be",
... | Gets the Weichert adjustment factor for each the magnitude bins
:param float beta:
Beta value of Gutenberg & Richter parameter (b * log(10.))
:param np.ndarray cmag:
Magnitude values of the completeness table
:param np.ndarray cyear:
Year values of the completeness table
:param float end_year:
Last year for consideration in the catalogue
:returns:
Weichert adjustment factor (float) | [
"Gets",
"the",
"Weichert",
"adjustment",
"factor",
"for",
"each",
"the",
"magnitude",
"bins"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/smoothing/utils.py#L96-L127 | train | 214,000 |
gem/oq-engine | openquake/hmtk/seismicity/smoothing/utils.py | get_even_magnitude_completeness | def get_even_magnitude_completeness(completeness_table, catalogue=None):
'''
To make the magnitudes evenly spaced, render to a constant 0.1
magnitude unit
:param np.ndarray completeness_table:
Completeness table in format [[year, mag]]
:param catalogue:
Instance of openquake.hmtk.seismicity.catalogue.Catalogue class
:returns:
Correct completeness table
'''
mmax = np.floor(10. * np.max(catalogue.data['magnitude'])) / 10.
check_completeness_table(completeness_table, catalogue)
cmag = np.hstack([completeness_table[:, 1], mmax + 0.1])
cyear = np.hstack([completeness_table[:, 0], completeness_table[-1, 0]])
if np.shape(completeness_table)[0] == 1:
# Simple single-valued table
return completeness_table, 0.1
for iloc in range(0, len(cmag) - 1):
mrange = np.arange(np.floor(10. * cmag[iloc]) / 10.,
(np.ceil(10. * cmag[iloc + 1]) / 10.),
0.1)
temp_table = np.column_stack([
cyear[iloc] * np.ones(len(mrange), dtype=float),
mrange])
if iloc == 0:
completeness_table = np.copy(temp_table)
else:
completeness_table = np.vstack([completeness_table,
temp_table])
# completeness_table = np.vstack([completeness_table,
# np.array([[cyear[-1], cmag[-1]]])])
return completeness_table, 0.1 | python | def get_even_magnitude_completeness(completeness_table, catalogue=None):
'''
To make the magnitudes evenly spaced, render to a constant 0.1
magnitude unit
:param np.ndarray completeness_table:
Completeness table in format [[year, mag]]
:param catalogue:
Instance of openquake.hmtk.seismicity.catalogue.Catalogue class
:returns:
Correct completeness table
'''
mmax = np.floor(10. * np.max(catalogue.data['magnitude'])) / 10.
check_completeness_table(completeness_table, catalogue)
cmag = np.hstack([completeness_table[:, 1], mmax + 0.1])
cyear = np.hstack([completeness_table[:, 0], completeness_table[-1, 0]])
if np.shape(completeness_table)[0] == 1:
# Simple single-valued table
return completeness_table, 0.1
for iloc in range(0, len(cmag) - 1):
mrange = np.arange(np.floor(10. * cmag[iloc]) / 10.,
(np.ceil(10. * cmag[iloc + 1]) / 10.),
0.1)
temp_table = np.column_stack([
cyear[iloc] * np.ones(len(mrange), dtype=float),
mrange])
if iloc == 0:
completeness_table = np.copy(temp_table)
else:
completeness_table = np.vstack([completeness_table,
temp_table])
# completeness_table = np.vstack([completeness_table,
# np.array([[cyear[-1], cmag[-1]]])])
return completeness_table, 0.1 | [
"def",
"get_even_magnitude_completeness",
"(",
"completeness_table",
",",
"catalogue",
"=",
"None",
")",
":",
"mmax",
"=",
"np",
".",
"floor",
"(",
"10.",
"*",
"np",
".",
"max",
"(",
"catalogue",
".",
"data",
"[",
"'magnitude'",
"]",
")",
")",
"/",
"10."... | To make the magnitudes evenly spaced, render to a constant 0.1
magnitude unit
:param np.ndarray completeness_table:
Completeness table in format [[year, mag]]
:param catalogue:
Instance of openquake.hmtk.seismicity.catalogue.Catalogue class
:returns:
Correct completeness table | [
"To",
"make",
"the",
"magnitudes",
"evenly",
"spaced",
"render",
"to",
"a",
"constant",
"0",
".",
"1",
"magnitude",
"unit"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/smoothing/utils.py#L158-L195 | train | 214,001 |
gem/oq-engine | openquake/commonlib/logictree.py | unique | def unique(objects, key=None):
"""
Raise a ValueError if there is a duplicated object, otherwise
returns the objects as they are.
"""
dupl = []
for obj, group in itertools.groupby(sorted(objects), key):
if sum(1 for _ in group) > 1:
dupl.append(obj)
if dupl:
raise ValueError('Found duplicates %s' % dupl)
return objects | python | def unique(objects, key=None):
"""
Raise a ValueError if there is a duplicated object, otherwise
returns the objects as they are.
"""
dupl = []
for obj, group in itertools.groupby(sorted(objects), key):
if sum(1 for _ in group) > 1:
dupl.append(obj)
if dupl:
raise ValueError('Found duplicates %s' % dupl)
return objects | [
"def",
"unique",
"(",
"objects",
",",
"key",
"=",
"None",
")",
":",
"dupl",
"=",
"[",
"]",
"for",
"obj",
",",
"group",
"in",
"itertools",
".",
"groupby",
"(",
"sorted",
"(",
"objects",
")",
",",
"key",
")",
":",
"if",
"sum",
"(",
"1",
"for",
"_... | Raise a ValueError if there is a duplicated object, otherwise
returns the objects as they are. | [
"Raise",
"a",
"ValueError",
"if",
"there",
"is",
"a",
"duplicated",
"object",
"otherwise",
"returns",
"the",
"objects",
"as",
"they",
"are",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L60-L71 | train | 214,002 |
gem/oq-engine | openquake/commonlib/logictree.py | sample | def sample(weighted_objects, num_samples, seed):
"""
Take random samples of a sequence of weighted objects
:param weighted_objects:
A finite sequence of objects with a `.weight` attribute.
The weights must sum up to 1.
:param num_samples:
The number of samples to return
:param seed:
A random seed
:return:
A subsequence of the original sequence with `num_samples` elements
"""
weights = []
for obj in weighted_objects:
w = obj.weight
if isinstance(obj.weight, float):
weights.append(w)
else:
weights.append(w['weight'])
numpy.random.seed(seed)
idxs = numpy.random.choice(len(weights), num_samples, p=weights)
# NB: returning an array would break things
return [weighted_objects[idx] for idx in idxs] | python | def sample(weighted_objects, num_samples, seed):
"""
Take random samples of a sequence of weighted objects
:param weighted_objects:
A finite sequence of objects with a `.weight` attribute.
The weights must sum up to 1.
:param num_samples:
The number of samples to return
:param seed:
A random seed
:return:
A subsequence of the original sequence with `num_samples` elements
"""
weights = []
for obj in weighted_objects:
w = obj.weight
if isinstance(obj.weight, float):
weights.append(w)
else:
weights.append(w['weight'])
numpy.random.seed(seed)
idxs = numpy.random.choice(len(weights), num_samples, p=weights)
# NB: returning an array would break things
return [weighted_objects[idx] for idx in idxs] | [
"def",
"sample",
"(",
"weighted_objects",
",",
"num_samples",
",",
"seed",
")",
":",
"weights",
"=",
"[",
"]",
"for",
"obj",
"in",
"weighted_objects",
":",
"w",
"=",
"obj",
".",
"weight",
"if",
"isinstance",
"(",
"obj",
".",
"weight",
",",
"float",
")"... | Take random samples of a sequence of weighted objects
:param weighted_objects:
A finite sequence of objects with a `.weight` attribute.
The weights must sum up to 1.
:param num_samples:
The number of samples to return
:param seed:
A random seed
:return:
A subsequence of the original sequence with `num_samples` elements | [
"Take",
"random",
"samples",
"of",
"a",
"sequence",
"of",
"weighted",
"objects"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L170-L194 | train | 214,003 |
gem/oq-engine | openquake/commonlib/logictree.py | collect_info | def collect_info(smlt):
"""
Given a path to a source model logic tree, collect all of the
path names to the source models it contains and build
1. a dictionary source model branch ID -> paths
2. a dictionary source model branch ID -> source IDs in applyToSources
:param smlt: source model logic tree file
:returns: an Info namedtupled containing the two dictionaries
"""
n = nrml.read(smlt)
try:
blevels = n.logicTree
except Exception:
raise InvalidFile('%s is not a valid source_model_logic_tree_file'
% smlt)
paths = collections.defaultdict(set) # branchID -> paths
applytosources = collections.defaultdict(list) # branchID -> source IDs
for blevel in blevels:
for bset in blevel:
if 'applyToSources' in bset.attrib:
applytosources[bset['branchSetID']].extend(
bset['applyToSources'].split())
for br in bset:
with node.context(smlt, br):
fnames = unique(br.uncertaintyModel.text.split())
paths[br['branchID']].update(get_paths(smlt, fnames))
return Info({k: sorted(v) for k, v in paths.items()}, applytosources) | python | def collect_info(smlt):
"""
Given a path to a source model logic tree, collect all of the
path names to the source models it contains and build
1. a dictionary source model branch ID -> paths
2. a dictionary source model branch ID -> source IDs in applyToSources
:param smlt: source model logic tree file
:returns: an Info namedtupled containing the two dictionaries
"""
n = nrml.read(smlt)
try:
blevels = n.logicTree
except Exception:
raise InvalidFile('%s is not a valid source_model_logic_tree_file'
% smlt)
paths = collections.defaultdict(set) # branchID -> paths
applytosources = collections.defaultdict(list) # branchID -> source IDs
for blevel in blevels:
for bset in blevel:
if 'applyToSources' in bset.attrib:
applytosources[bset['branchSetID']].extend(
bset['applyToSources'].split())
for br in bset:
with node.context(smlt, br):
fnames = unique(br.uncertaintyModel.text.split())
paths[br['branchID']].update(get_paths(smlt, fnames))
return Info({k: sorted(v) for k, v in paths.items()}, applytosources) | [
"def",
"collect_info",
"(",
"smlt",
")",
":",
"n",
"=",
"nrml",
".",
"read",
"(",
"smlt",
")",
"try",
":",
"blevels",
"=",
"n",
".",
"logicTree",
"except",
"Exception",
":",
"raise",
"InvalidFile",
"(",
"'%s is not a valid source_model_logic_tree_file'",
"%",
... | Given a path to a source model logic tree, collect all of the
path names to the source models it contains and build
1. a dictionary source model branch ID -> paths
2. a dictionary source model branch ID -> source IDs in applyToSources
:param smlt: source model logic tree file
:returns: an Info namedtupled containing the two dictionaries | [
"Given",
"a",
"path",
"to",
"a",
"source",
"model",
"logic",
"tree",
"collect",
"all",
"of",
"the",
"path",
"names",
"to",
"the",
"source",
"models",
"it",
"contains",
"and",
"build",
"1",
".",
"a",
"dictionary",
"source",
"model",
"branch",
"ID",
"-",
... | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L499-L526 | train | 214,004 |
gem/oq-engine | openquake/commonlib/logictree.py | toml | def toml(uncertainty):
"""
Converts an uncertainty node into a TOML string
"""
text = uncertainty.text.strip()
if not text.startswith('['): # a bare GSIM name was passed
text = '[%s]' % text
for k, v in uncertainty.attrib.items():
try:
v = ast.literal_eval(v)
except ValueError:
v = repr(v)
text += '\n%s = %s' % (k, v)
return text | python | def toml(uncertainty):
"""
Converts an uncertainty node into a TOML string
"""
text = uncertainty.text.strip()
if not text.startswith('['): # a bare GSIM name was passed
text = '[%s]' % text
for k, v in uncertainty.attrib.items():
try:
v = ast.literal_eval(v)
except ValueError:
v = repr(v)
text += '\n%s = %s' % (k, v)
return text | [
"def",
"toml",
"(",
"uncertainty",
")",
":",
"text",
"=",
"uncertainty",
".",
"text",
".",
"strip",
"(",
")",
"if",
"not",
"text",
".",
"startswith",
"(",
"'['",
")",
":",
"# a bare GSIM name was passed",
"text",
"=",
"'[%s]'",
"%",
"text",
"for",
"k",
... | Converts an uncertainty node into a TOML string | [
"Converts",
"an",
"uncertainty",
"node",
"into",
"a",
"TOML",
"string"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L1294-L1307 | train | 214,005 |
gem/oq-engine | openquake/commonlib/logictree.py | LtSourceModel.name | def name(self):
"""
Compact representation for the names
"""
names = self.names.split()
if len(names) == 1:
return names[0]
elif len(names) == 2:
return ' '.join(names)
else:
return ' '.join([names[0], '...', names[-1]]) | python | def name(self):
"""
Compact representation for the names
"""
names = self.names.split()
if len(names) == 1:
return names[0]
elif len(names) == 2:
return ' '.join(names)
else:
return ' '.join([names[0], '...', names[-1]]) | [
"def",
"name",
"(",
"self",
")",
":",
"names",
"=",
"self",
".",
"names",
".",
"split",
"(",
")",
"if",
"len",
"(",
"names",
")",
"==",
"1",
":",
"return",
"names",
"[",
"0",
"]",
"elif",
"len",
"(",
"names",
")",
"==",
"2",
":",
"return",
"'... | Compact representation for the names | [
"Compact",
"representation",
"for",
"the",
"names"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L90-L100 | train | 214,006 |
gem/oq-engine | openquake/commonlib/logictree.py | LtSourceModel.get_skeleton | def get_skeleton(self):
"""
Return an empty copy of the source model, i.e. without sources,
but with the proper attributes for each SourceGroup contained within.
"""
src_groups = []
for grp in self.src_groups:
sg = copy.copy(grp)
sg.sources = []
src_groups.append(sg)
return self.__class__(self.names, self.weight, self.path, src_groups,
self.num_gsim_paths, self.ordinal, self.samples) | python | def get_skeleton(self):
"""
Return an empty copy of the source model, i.e. without sources,
but with the proper attributes for each SourceGroup contained within.
"""
src_groups = []
for grp in self.src_groups:
sg = copy.copy(grp)
sg.sources = []
src_groups.append(sg)
return self.__class__(self.names, self.weight, self.path, src_groups,
self.num_gsim_paths, self.ordinal, self.samples) | [
"def",
"get_skeleton",
"(",
"self",
")",
":",
"src_groups",
"=",
"[",
"]",
"for",
"grp",
"in",
"self",
".",
"src_groups",
":",
"sg",
"=",
"copy",
".",
"copy",
"(",
"grp",
")",
"sg",
".",
"sources",
"=",
"[",
"]",
"src_groups",
".",
"append",
"(",
... | Return an empty copy of the source model, i.e. without sources,
but with the proper attributes for each SourceGroup contained within. | [
"Return",
"an",
"empty",
"copy",
"of",
"the",
"source",
"model",
"i",
".",
"e",
".",
"without",
"sources",
"but",
"with",
"the",
"proper",
"attributes",
"for",
"each",
"SourceGroup",
"contained",
"within",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L109-L120 | train | 214,007 |
gem/oq-engine | openquake/commonlib/logictree.py | BranchSet.enumerate_paths | def enumerate_paths(self):
"""
Generate all possible paths starting from this branch set.
:returns:
Generator of two-item tuples. Each tuple contains weight
of the path (calculated as a product of the weights of all path's
branches) and list of path's :class:`Branch` objects. Total sum
of all paths' weights is 1.0
"""
for path in self._enumerate_paths([]):
flat_path = []
weight = 1.0
while path:
path, branch = path
weight *= branch.weight
flat_path.append(branch)
yield weight, flat_path[::-1] | python | def enumerate_paths(self):
"""
Generate all possible paths starting from this branch set.
:returns:
Generator of two-item tuples. Each tuple contains weight
of the path (calculated as a product of the weights of all path's
branches) and list of path's :class:`Branch` objects. Total sum
of all paths' weights is 1.0
"""
for path in self._enumerate_paths([]):
flat_path = []
weight = 1.0
while path:
path, branch = path
weight *= branch.weight
flat_path.append(branch)
yield weight, flat_path[::-1] | [
"def",
"enumerate_paths",
"(",
"self",
")",
":",
"for",
"path",
"in",
"self",
".",
"_enumerate_paths",
"(",
"[",
"]",
")",
":",
"flat_path",
"=",
"[",
"]",
"weight",
"=",
"1.0",
"while",
"path",
":",
"path",
",",
"branch",
"=",
"path",
"weight",
"*="... | Generate all possible paths starting from this branch set.
:returns:
Generator of two-item tuples. Each tuple contains weight
of the path (calculated as a product of the weights of all path's
branches) and list of path's :class:`Branch` objects. Total sum
of all paths' weights is 1.0 | [
"Generate",
"all",
"possible",
"paths",
"starting",
"from",
"this",
"branch",
"set",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L300-L317 | train | 214,008 |
gem/oq-engine | openquake/commonlib/logictree.py | BranchSet.filter_source | def filter_source(self, source):
# pylint: disable=R0911,R0912
"""
Apply filters to ``source`` and return ``True`` if uncertainty should
be applied to it.
"""
for key, value in self.filters.items():
if key == 'applyToTectonicRegionType':
if value != source.tectonic_region_type:
return False
elif key == 'applyToSourceType':
if value == 'area':
if not isinstance(source, ohs.AreaSource):
return False
elif value == 'point':
# area source extends point source
if (not isinstance(source, ohs.PointSource)
or isinstance(source, ohs.AreaSource)):
return False
elif value == 'simpleFault':
if not isinstance(source, ohs.SimpleFaultSource):
return False
elif value == 'complexFault':
if not isinstance(source, ohs.ComplexFaultSource):
return False
elif value == 'characteristicFault':
if not isinstance(source, ohs.CharacteristicFaultSource):
return False
else:
raise AssertionError("unknown source type '%s'" % value)
elif key == 'applyToSources':
if source and source.source_id not in value:
return False
else:
raise AssertionError("unknown filter '%s'" % key)
# All filters pass, return True.
return True | python | def filter_source(self, source):
# pylint: disable=R0911,R0912
"""
Apply filters to ``source`` and return ``True`` if uncertainty should
be applied to it.
"""
for key, value in self.filters.items():
if key == 'applyToTectonicRegionType':
if value != source.tectonic_region_type:
return False
elif key == 'applyToSourceType':
if value == 'area':
if not isinstance(source, ohs.AreaSource):
return False
elif value == 'point':
# area source extends point source
if (not isinstance(source, ohs.PointSource)
or isinstance(source, ohs.AreaSource)):
return False
elif value == 'simpleFault':
if not isinstance(source, ohs.SimpleFaultSource):
return False
elif value == 'complexFault':
if not isinstance(source, ohs.ComplexFaultSource):
return False
elif value == 'characteristicFault':
if not isinstance(source, ohs.CharacteristicFaultSource):
return False
else:
raise AssertionError("unknown source type '%s'" % value)
elif key == 'applyToSources':
if source and source.source_id not in value:
return False
else:
raise AssertionError("unknown filter '%s'" % key)
# All filters pass, return True.
return True | [
"def",
"filter_source",
"(",
"self",
",",
"source",
")",
":",
"# pylint: disable=R0911,R0912",
"for",
"key",
",",
"value",
"in",
"self",
".",
"filters",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"'applyToTectonicRegionType'",
":",
"if",
"value",
"!=",
... | Apply filters to ``source`` and return ``True`` if uncertainty should
be applied to it. | [
"Apply",
"filters",
"to",
"source",
"and",
"return",
"True",
"if",
"uncertainty",
"should",
"be",
"applied",
"to",
"it",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L343-L379 | train | 214,009 |
gem/oq-engine | openquake/commonlib/logictree.py | BranchSet._apply_uncertainty_to_geometry | def _apply_uncertainty_to_geometry(self, source, value):
"""
Modify ``source`` geometry with the uncertainty value ``value``
"""
if self.uncertainty_type == 'simpleFaultDipRelative':
source.modify('adjust_dip', dict(increment=value))
elif self.uncertainty_type == 'simpleFaultDipAbsolute':
source.modify('set_dip', dict(dip=value))
elif self.uncertainty_type == 'simpleFaultGeometryAbsolute':
trace, usd, lsd, dip, spacing = value
source.modify(
'set_geometry',
dict(fault_trace=trace, upper_seismogenic_depth=usd,
lower_seismogenic_depth=lsd, dip=dip, spacing=spacing))
elif self.uncertainty_type == 'complexFaultGeometryAbsolute':
edges, spacing = value
source.modify('set_geometry', dict(edges=edges, spacing=spacing))
elif self.uncertainty_type == 'characteristicFaultGeometryAbsolute':
source.modify('set_geometry', dict(surface=value)) | python | def _apply_uncertainty_to_geometry(self, source, value):
"""
Modify ``source`` geometry with the uncertainty value ``value``
"""
if self.uncertainty_type == 'simpleFaultDipRelative':
source.modify('adjust_dip', dict(increment=value))
elif self.uncertainty_type == 'simpleFaultDipAbsolute':
source.modify('set_dip', dict(dip=value))
elif self.uncertainty_type == 'simpleFaultGeometryAbsolute':
trace, usd, lsd, dip, spacing = value
source.modify(
'set_geometry',
dict(fault_trace=trace, upper_seismogenic_depth=usd,
lower_seismogenic_depth=lsd, dip=dip, spacing=spacing))
elif self.uncertainty_type == 'complexFaultGeometryAbsolute':
edges, spacing = value
source.modify('set_geometry', dict(edges=edges, spacing=spacing))
elif self.uncertainty_type == 'characteristicFaultGeometryAbsolute':
source.modify('set_geometry', dict(surface=value)) | [
"def",
"_apply_uncertainty_to_geometry",
"(",
"self",
",",
"source",
",",
"value",
")",
":",
"if",
"self",
".",
"uncertainty_type",
"==",
"'simpleFaultDipRelative'",
":",
"source",
".",
"modify",
"(",
"'adjust_dip'",
",",
"dict",
"(",
"increment",
"=",
"value",
... | Modify ``source`` geometry with the uncertainty value ``value`` | [
"Modify",
"source",
"geometry",
"with",
"the",
"uncertainty",
"value",
"value"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L409-L427 | train | 214,010 |
gem/oq-engine | openquake/commonlib/logictree.py | BranchSet._apply_uncertainty_to_mfd | def _apply_uncertainty_to_mfd(self, mfd, value):
"""
Modify ``mfd`` object with uncertainty value ``value``.
"""
if self.uncertainty_type == 'abGRAbsolute':
a, b = value
mfd.modify('set_ab', dict(a_val=a, b_val=b))
elif self.uncertainty_type == 'bGRRelative':
mfd.modify('increment_b', dict(value=value))
elif self.uncertainty_type == 'maxMagGRRelative':
mfd.modify('increment_max_mag', dict(value=value))
elif self.uncertainty_type == 'maxMagGRAbsolute':
mfd.modify('set_max_mag', dict(value=value))
elif self.uncertainty_type == 'incrementalMFDAbsolute':
min_mag, bin_width, occur_rates = value
mfd.modify('set_mfd', dict(min_mag=min_mag, bin_width=bin_width,
occurrence_rates=occur_rates)) | python | def _apply_uncertainty_to_mfd(self, mfd, value):
"""
Modify ``mfd`` object with uncertainty value ``value``.
"""
if self.uncertainty_type == 'abGRAbsolute':
a, b = value
mfd.modify('set_ab', dict(a_val=a, b_val=b))
elif self.uncertainty_type == 'bGRRelative':
mfd.modify('increment_b', dict(value=value))
elif self.uncertainty_type == 'maxMagGRRelative':
mfd.modify('increment_max_mag', dict(value=value))
elif self.uncertainty_type == 'maxMagGRAbsolute':
mfd.modify('set_max_mag', dict(value=value))
elif self.uncertainty_type == 'incrementalMFDAbsolute':
min_mag, bin_width, occur_rates = value
mfd.modify('set_mfd', dict(min_mag=min_mag, bin_width=bin_width,
occurrence_rates=occur_rates)) | [
"def",
"_apply_uncertainty_to_mfd",
"(",
"self",
",",
"mfd",
",",
"value",
")",
":",
"if",
"self",
".",
"uncertainty_type",
"==",
"'abGRAbsolute'",
":",
"a",
",",
"b",
"=",
"value",
"mfd",
".",
"modify",
"(",
"'set_ab'",
",",
"dict",
"(",
"a_val",
"=",
... | Modify ``mfd`` object with uncertainty value ``value``. | [
"Modify",
"mfd",
"object",
"with",
"uncertainty",
"value",
"value",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L429-L449 | train | 214,011 |
gem/oq-engine | openquake/commonlib/logictree.py | FakeSmlt.gen_source_models | def gen_source_models(self, gsim_lt):
"""
Yield the underlying LtSourceModel, multiple times if there is sampling
"""
num_gsim_paths = 1 if self.num_samples else gsim_lt.get_num_paths()
for i, rlz in enumerate(self):
yield LtSourceModel(
rlz.value, rlz.weight, ('b1',), [], num_gsim_paths, i, 1) | python | def gen_source_models(self, gsim_lt):
"""
Yield the underlying LtSourceModel, multiple times if there is sampling
"""
num_gsim_paths = 1 if self.num_samples else gsim_lt.get_num_paths()
for i, rlz in enumerate(self):
yield LtSourceModel(
rlz.value, rlz.weight, ('b1',), [], num_gsim_paths, i, 1) | [
"def",
"gen_source_models",
"(",
"self",
",",
"gsim_lt",
")",
":",
"num_gsim_paths",
"=",
"1",
"if",
"self",
".",
"num_samples",
"else",
"gsim_lt",
".",
"get_num_paths",
"(",
")",
"for",
"i",
",",
"rlz",
"in",
"enumerate",
"(",
"self",
")",
":",
"yield",... | Yield the underlying LtSourceModel, multiple times if there is sampling | [
"Yield",
"the",
"underlying",
"LtSourceModel",
"multiple",
"times",
"if",
"there",
"is",
"sampling"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L470-L477 | train | 214,012 |
gem/oq-engine | openquake/commonlib/logictree.py | SourceModelLogicTree.on_each_source | def on_each_source(self):
"""
True if there is an applyToSources for each source.
"""
return (self.info.applytosources and
self.info.applytosources == self.source_ids) | python | def on_each_source(self):
"""
True if there is an applyToSources for each source.
"""
return (self.info.applytosources and
self.info.applytosources == self.source_ids) | [
"def",
"on_each_source",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"info",
".",
"applytosources",
"and",
"self",
".",
"info",
".",
"applytosources",
"==",
"self",
".",
"source_ids",
")"
] | True if there is an applyToSources for each source. | [
"True",
"if",
"there",
"is",
"an",
"applyToSources",
"for",
"each",
"source",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L598-L603 | train | 214,013 |
gem/oq-engine | openquake/commonlib/logictree.py | SourceModelLogicTree.parse_tree | def parse_tree(self, tree_node, validate):
"""
Parse the whole tree and point ``root_branchset`` attribute
to the tree's root.
"""
self.info = collect_info(self.filename)
self.source_ids = collections.defaultdict(list)
t0 = time.time()
for depth, branchinglevel_node in enumerate(tree_node.nodes):
self.parse_branchinglevel(branchinglevel_node, depth, validate)
dt = time.time() - t0
if validate:
bname = os.path.basename(self.filename)
logging.info('Validated %s in %.2f seconds', bname, dt) | python | def parse_tree(self, tree_node, validate):
"""
Parse the whole tree and point ``root_branchset`` attribute
to the tree's root.
"""
self.info = collect_info(self.filename)
self.source_ids = collections.defaultdict(list)
t0 = time.time()
for depth, branchinglevel_node in enumerate(tree_node.nodes):
self.parse_branchinglevel(branchinglevel_node, depth, validate)
dt = time.time() - t0
if validate:
bname = os.path.basename(self.filename)
logging.info('Validated %s in %.2f seconds', bname, dt) | [
"def",
"parse_tree",
"(",
"self",
",",
"tree_node",
",",
"validate",
")",
":",
"self",
".",
"info",
"=",
"collect_info",
"(",
"self",
".",
"filename",
")",
"self",
".",
"source_ids",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"t0",
"=",
... | Parse the whole tree and point ``root_branchset`` attribute
to the tree's root. | [
"Parse",
"the",
"whole",
"tree",
"and",
"point",
"root_branchset",
"attribute",
"to",
"the",
"tree",
"s",
"root",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L605-L618 | train | 214,014 |
gem/oq-engine | openquake/commonlib/logictree.py | SourceModelLogicTree.parse_branchinglevel | def parse_branchinglevel(self, branchinglevel_node, depth, validate):
"""
Parse one branching level.
:param branchinglevel_node:
``etree.Element`` object with tag "logicTreeBranchingLevel".
:param depth:
The sequential number of this branching level, based on 0.
:param validate:
Whether or not the branching level, its branchsets and their
branches should be validated.
Enumerates children branchsets and call :meth:`parse_branchset`,
:meth:`validate_branchset`, :meth:`parse_branches` and finally
:meth:`apply_branchset` for each.
Keeps track of "open ends" -- the set of branches that don't have
any child branchset on this step of execution. After processing
of every branching level only those branches that are listed in it
can have child branchsets (if there is one on the next level).
"""
new_open_ends = set()
branchsets = branchinglevel_node.nodes
for number, branchset_node in enumerate(branchsets):
branchset = self.parse_branchset(branchset_node, depth, number,
validate)
self.parse_branches(branchset_node, branchset, validate)
if self.root_branchset is None: # not set yet
self.num_paths = 1
self.root_branchset = branchset
else:
self.apply_branchset(branchset_node, branchset)
for branch in branchset.branches:
new_open_ends.add(branch)
self.num_paths *= len(branchset.branches)
if number > 0:
logging.warning('There is a branching level with multiple '
'branchsets in %s', self.filename)
self.open_ends.clear()
self.open_ends.update(new_open_ends) | python | def parse_branchinglevel(self, branchinglevel_node, depth, validate):
"""
Parse one branching level.
:param branchinglevel_node:
``etree.Element`` object with tag "logicTreeBranchingLevel".
:param depth:
The sequential number of this branching level, based on 0.
:param validate:
Whether or not the branching level, its branchsets and their
branches should be validated.
Enumerates children branchsets and call :meth:`parse_branchset`,
:meth:`validate_branchset`, :meth:`parse_branches` and finally
:meth:`apply_branchset` for each.
Keeps track of "open ends" -- the set of branches that don't have
any child branchset on this step of execution. After processing
of every branching level only those branches that are listed in it
can have child branchsets (if there is one on the next level).
"""
new_open_ends = set()
branchsets = branchinglevel_node.nodes
for number, branchset_node in enumerate(branchsets):
branchset = self.parse_branchset(branchset_node, depth, number,
validate)
self.parse_branches(branchset_node, branchset, validate)
if self.root_branchset is None: # not set yet
self.num_paths = 1
self.root_branchset = branchset
else:
self.apply_branchset(branchset_node, branchset)
for branch in branchset.branches:
new_open_ends.add(branch)
self.num_paths *= len(branchset.branches)
if number > 0:
logging.warning('There is a branching level with multiple '
'branchsets in %s', self.filename)
self.open_ends.clear()
self.open_ends.update(new_open_ends) | [
"def",
"parse_branchinglevel",
"(",
"self",
",",
"branchinglevel_node",
",",
"depth",
",",
"validate",
")",
":",
"new_open_ends",
"=",
"set",
"(",
")",
"branchsets",
"=",
"branchinglevel_node",
".",
"nodes",
"for",
"number",
",",
"branchset_node",
"in",
"enumera... | Parse one branching level.
:param branchinglevel_node:
``etree.Element`` object with tag "logicTreeBranchingLevel".
:param depth:
The sequential number of this branching level, based on 0.
:param validate:
Whether or not the branching level, its branchsets and their
branches should be validated.
Enumerates children branchsets and call :meth:`parse_branchset`,
:meth:`validate_branchset`, :meth:`parse_branches` and finally
:meth:`apply_branchset` for each.
Keeps track of "open ends" -- the set of branches that don't have
any child branchset on this step of execution. After processing
of every branching level only those branches that are listed in it
can have child branchsets (if there is one on the next level). | [
"Parse",
"one",
"branching",
"level",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L620-L659 | train | 214,015 |
gem/oq-engine | openquake/commonlib/logictree.py | SourceModelLogicTree.parse_branches | def parse_branches(self, branchset_node, branchset, validate):
"""
Create and attach branches at ``branchset_node`` to ``branchset``.
:param branchset_node:
Same as for :meth:`parse_branchset`.
:param branchset:
An instance of :class:`BranchSet`.
:param validate:
Whether or not branches' uncertainty values should be validated.
Checks that each branch has :meth:`valid <validate_uncertainty_value>`
value, unique id and that all branches have total weight of 1.0.
:return:
``None``, all branches are attached to provided branchset.
"""
weight_sum = 0
branches = branchset_node.nodes
values = []
for branchnode in branches:
weight = ~branchnode.uncertaintyWeight
weight_sum += weight
value_node = node_from_elem(branchnode.uncertaintyModel)
if value_node.text is not None:
values.append(value_node.text.strip())
if validate:
self.validate_uncertainty_value(
value_node, branchnode, branchset)
value = self.parse_uncertainty_value(value_node, branchset)
branch_id = branchnode.attrib.get('branchID')
branch = Branch(branch_id, weight, value)
if branch_id in self.branches:
raise LogicTreeError(
branchnode, self.filename,
"branchID '%s' is not unique" % branch_id)
self.branches[branch_id] = branch
branchset.branches.append(branch)
if abs(weight_sum - 1.0) > pmf.PRECISION:
raise LogicTreeError(
branchset_node, self.filename,
"branchset weights don't sum up to 1.0")
if len(set(values)) < len(values):
# TODO: add a test for this case
# <logicTreeBranch branchID="b71">
# <uncertaintyModel> 7.7 </uncertaintyModel>
# <uncertaintyWeight>0.333</uncertaintyWeight>
# </logicTreeBranch>
# <logicTreeBranch branchID="b72">
# <uncertaintyModel> 7.695 </uncertaintyModel>
# <uncertaintyWeight>0.333</uncertaintyWeight>
# </logicTreeBranch>
# <logicTreeBranch branchID="b73">
# <uncertaintyModel> 7.7 </uncertaintyModel>
# <uncertaintyWeight>0.334</uncertaintyWeight>
# </logicTreeBranch>
raise LogicTreeError(
branchset_node, self.filename,
"there are duplicate values in uncertaintyModel: " +
' '.join(values)) | python | def parse_branches(self, branchset_node, branchset, validate):
"""
Create and attach branches at ``branchset_node`` to ``branchset``.
:param branchset_node:
Same as for :meth:`parse_branchset`.
:param branchset:
An instance of :class:`BranchSet`.
:param validate:
Whether or not branches' uncertainty values should be validated.
Checks that each branch has :meth:`valid <validate_uncertainty_value>`
value, unique id and that all branches have total weight of 1.0.
:return:
``None``, all branches are attached to provided branchset.
"""
weight_sum = 0
branches = branchset_node.nodes
values = []
for branchnode in branches:
weight = ~branchnode.uncertaintyWeight
weight_sum += weight
value_node = node_from_elem(branchnode.uncertaintyModel)
if value_node.text is not None:
values.append(value_node.text.strip())
if validate:
self.validate_uncertainty_value(
value_node, branchnode, branchset)
value = self.parse_uncertainty_value(value_node, branchset)
branch_id = branchnode.attrib.get('branchID')
branch = Branch(branch_id, weight, value)
if branch_id in self.branches:
raise LogicTreeError(
branchnode, self.filename,
"branchID '%s' is not unique" % branch_id)
self.branches[branch_id] = branch
branchset.branches.append(branch)
if abs(weight_sum - 1.0) > pmf.PRECISION:
raise LogicTreeError(
branchset_node, self.filename,
"branchset weights don't sum up to 1.0")
if len(set(values)) < len(values):
# TODO: add a test for this case
# <logicTreeBranch branchID="b71">
# <uncertaintyModel> 7.7 </uncertaintyModel>
# <uncertaintyWeight>0.333</uncertaintyWeight>
# </logicTreeBranch>
# <logicTreeBranch branchID="b72">
# <uncertaintyModel> 7.695 </uncertaintyModel>
# <uncertaintyWeight>0.333</uncertaintyWeight>
# </logicTreeBranch>
# <logicTreeBranch branchID="b73">
# <uncertaintyModel> 7.7 </uncertaintyModel>
# <uncertaintyWeight>0.334</uncertaintyWeight>
# </logicTreeBranch>
raise LogicTreeError(
branchset_node, self.filename,
"there are duplicate values in uncertaintyModel: " +
' '.join(values)) | [
"def",
"parse_branches",
"(",
"self",
",",
"branchset_node",
",",
"branchset",
",",
"validate",
")",
":",
"weight_sum",
"=",
"0",
"branches",
"=",
"branchset_node",
".",
"nodes",
"values",
"=",
"[",
"]",
"for",
"branchnode",
"in",
"branches",
":",
"weight",
... | Create and attach branches at ``branchset_node`` to ``branchset``.
:param branchset_node:
Same as for :meth:`parse_branchset`.
:param branchset:
An instance of :class:`BranchSet`.
:param validate:
Whether or not branches' uncertainty values should be validated.
Checks that each branch has :meth:`valid <validate_uncertainty_value>`
value, unique id and that all branches have total weight of 1.0.
:return:
``None``, all branches are attached to provided branchset. | [
"Create",
"and",
"attach",
"branches",
"at",
"branchset_node",
"to",
"branchset",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L690-L749 | train | 214,016 |
gem/oq-engine | openquake/commonlib/logictree.py | SourceModelLogicTree.sample_path | def sample_path(self, seed):
"""
Return the model name and a list of branch ids.
:param seed: the seed used for the sampling
"""
branchset = self.root_branchset
branch_ids = []
while branchset is not None:
[branch] = sample(branchset.branches, 1, seed)
branch_ids.append(branch.branch_id)
branchset = branch.child_branchset
modelname = self.root_branchset.get_branch_by_id(branch_ids[0]).value
return modelname, branch_ids | python | def sample_path(self, seed):
"""
Return the model name and a list of branch ids.
:param seed: the seed used for the sampling
"""
branchset = self.root_branchset
branch_ids = []
while branchset is not None:
[branch] = sample(branchset.branches, 1, seed)
branch_ids.append(branch.branch_id)
branchset = branch.child_branchset
modelname = self.root_branchset.get_branch_by_id(branch_ids[0]).value
return modelname, branch_ids | [
"def",
"sample_path",
"(",
"self",
",",
"seed",
")",
":",
"branchset",
"=",
"self",
".",
"root_branchset",
"branch_ids",
"=",
"[",
"]",
"while",
"branchset",
"is",
"not",
"None",
":",
"[",
"branch",
"]",
"=",
"sample",
"(",
"branchset",
".",
"branches",
... | Return the model name and a list of branch ids.
:param seed: the seed used for the sampling | [
"Return",
"the",
"model",
"name",
"and",
"a",
"list",
"of",
"branch",
"ids",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L765-L778 | train | 214,017 |
gem/oq-engine | openquake/commonlib/logictree.py | SourceModelLogicTree._parse_simple_fault_geometry_surface | def _parse_simple_fault_geometry_surface(self, node):
"""
Parses a simple fault geometry surface
"""
spacing = node["spacing"]
usd, lsd, dip = (~node.upperSeismoDepth, ~node.lowerSeismoDepth,
~node.dip)
# Parse the geometry
coords = split_coords_2d(~node.LineString.posList)
trace = geo.Line([geo.Point(*p) for p in coords])
return trace, usd, lsd, dip, spacing | python | def _parse_simple_fault_geometry_surface(self, node):
"""
Parses a simple fault geometry surface
"""
spacing = node["spacing"]
usd, lsd, dip = (~node.upperSeismoDepth, ~node.lowerSeismoDepth,
~node.dip)
# Parse the geometry
coords = split_coords_2d(~node.LineString.posList)
trace = geo.Line([geo.Point(*p) for p in coords])
return trace, usd, lsd, dip, spacing | [
"def",
"_parse_simple_fault_geometry_surface",
"(",
"self",
",",
"node",
")",
":",
"spacing",
"=",
"node",
"[",
"\"spacing\"",
"]",
"usd",
",",
"lsd",
",",
"dip",
"=",
"(",
"~",
"node",
".",
"upperSeismoDepth",
",",
"~",
"node",
".",
"lowerSeismoDepth",
",... | Parses a simple fault geometry surface | [
"Parses",
"a",
"simple",
"fault",
"geometry",
"surface"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L850-L860 | train | 214,018 |
gem/oq-engine | openquake/commonlib/logictree.py | SourceModelLogicTree._parse_complex_fault_geometry_surface | def _parse_complex_fault_geometry_surface(self, node):
"""
Parses a complex fault geometry surface
"""
spacing = node["spacing"]
edges = []
for edge_node in node.nodes:
coords = split_coords_3d(~edge_node.LineString.posList)
edges.append(geo.Line([geo.Point(*p) for p in coords]))
return edges, spacing | python | def _parse_complex_fault_geometry_surface(self, node):
"""
Parses a complex fault geometry surface
"""
spacing = node["spacing"]
edges = []
for edge_node in node.nodes:
coords = split_coords_3d(~edge_node.LineString.posList)
edges.append(geo.Line([geo.Point(*p) for p in coords]))
return edges, spacing | [
"def",
"_parse_complex_fault_geometry_surface",
"(",
"self",
",",
"node",
")",
":",
"spacing",
"=",
"node",
"[",
"\"spacing\"",
"]",
"edges",
"=",
"[",
"]",
"for",
"edge_node",
"in",
"node",
".",
"nodes",
":",
"coords",
"=",
"split_coords_3d",
"(",
"~",
"e... | Parses a complex fault geometry surface | [
"Parses",
"a",
"complex",
"fault",
"geometry",
"surface"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L862-L871 | train | 214,019 |
gem/oq-engine | openquake/commonlib/logictree.py | SourceModelLogicTree._parse_planar_geometry_surface | def _parse_planar_geometry_surface(self, node):
"""
Parses a planar geometry surface
"""
nodes = []
for key in ["topLeft", "topRight", "bottomRight", "bottomLeft"]:
nodes.append(geo.Point(getattr(node, key)["lon"],
getattr(node, key)["lat"],
getattr(node, key)["depth"]))
top_left, top_right, bottom_right, bottom_left = tuple(nodes)
return geo.PlanarSurface.from_corner_points(
top_left, top_right, bottom_right, bottom_left) | python | def _parse_planar_geometry_surface(self, node):
"""
Parses a planar geometry surface
"""
nodes = []
for key in ["topLeft", "topRight", "bottomRight", "bottomLeft"]:
nodes.append(geo.Point(getattr(node, key)["lon"],
getattr(node, key)["lat"],
getattr(node, key)["depth"]))
top_left, top_right, bottom_right, bottom_left = tuple(nodes)
return geo.PlanarSurface.from_corner_points(
top_left, top_right, bottom_right, bottom_left) | [
"def",
"_parse_planar_geometry_surface",
"(",
"self",
",",
"node",
")",
":",
"nodes",
"=",
"[",
"]",
"for",
"key",
"in",
"[",
"\"topLeft\"",
",",
"\"topRight\"",
",",
"\"bottomRight\"",
",",
"\"bottomLeft\"",
"]",
":",
"nodes",
".",
"append",
"(",
"geo",
"... | Parses a planar geometry surface | [
"Parses",
"a",
"planar",
"geometry",
"surface"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L873-L884 | train | 214,020 |
gem/oq-engine | openquake/commonlib/logictree.py | SourceModelLogicTree._validate_simple_fault_geometry | def _validate_simple_fault_geometry(self, node, _float_re):
"""
Validates a node representation of a simple fault geometry
"""
try:
# Parse the geometry
coords = split_coords_2d(~node.LineString.posList)
trace = geo.Line([geo.Point(*p) for p in coords])
except ValueError:
# If the geometry cannot be created then use the LogicTreeError
# to point the user to the incorrect node. Hence, if trace is
# compiled successfully then len(trace) is True, otherwise it is
# False
trace = []
if len(trace):
return
raise LogicTreeError(
node, self.filename,
"'simpleFaultGeometry' node is not valid") | python | def _validate_simple_fault_geometry(self, node, _float_re):
"""
Validates a node representation of a simple fault geometry
"""
try:
# Parse the geometry
coords = split_coords_2d(~node.LineString.posList)
trace = geo.Line([geo.Point(*p) for p in coords])
except ValueError:
# If the geometry cannot be created then use the LogicTreeError
# to point the user to the incorrect node. Hence, if trace is
# compiled successfully then len(trace) is True, otherwise it is
# False
trace = []
if len(trace):
return
raise LogicTreeError(
node, self.filename,
"'simpleFaultGeometry' node is not valid") | [
"def",
"_validate_simple_fault_geometry",
"(",
"self",
",",
"node",
",",
"_float_re",
")",
":",
"try",
":",
"# Parse the geometry",
"coords",
"=",
"split_coords_2d",
"(",
"~",
"node",
".",
"LineString",
".",
"posList",
")",
"trace",
"=",
"geo",
".",
"Line",
... | Validates a node representation of a simple fault geometry | [
"Validates",
"a",
"node",
"representation",
"of",
"a",
"simple",
"fault",
"geometry"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L948-L966 | train | 214,021 |
gem/oq-engine | openquake/commonlib/logictree.py | SourceModelLogicTree._validate_complex_fault_geometry | def _validate_complex_fault_geometry(self, node, _float_re):
"""
Validates a node representation of a complex fault geometry - this
check merely verifies that the format is correct. If the geometry
does not conform to the Aki & Richards convention this will not be
verified here, but will raise an error when the surface is created.
"""
valid_edges = []
for edge_node in node.nodes:
try:
coords = split_coords_3d(edge_node.LineString.posList.text)
edge = geo.Line([geo.Point(*p) for p in coords])
except ValueError:
# See use of validation error in simple geometry case
# The node is valid if all of the edges compile correctly
edge = []
if len(edge):
valid_edges.append(True)
else:
valid_edges.append(False)
if node["spacing"] and all(valid_edges):
return
raise LogicTreeError(
node, self.filename,
"'complexFaultGeometry' node is not valid") | python | def _validate_complex_fault_geometry(self, node, _float_re):
"""
Validates a node representation of a complex fault geometry - this
check merely verifies that the format is correct. If the geometry
does not conform to the Aki & Richards convention this will not be
verified here, but will raise an error when the surface is created.
"""
valid_edges = []
for edge_node in node.nodes:
try:
coords = split_coords_3d(edge_node.LineString.posList.text)
edge = geo.Line([geo.Point(*p) for p in coords])
except ValueError:
# See use of validation error in simple geometry case
# The node is valid if all of the edges compile correctly
edge = []
if len(edge):
valid_edges.append(True)
else:
valid_edges.append(False)
if node["spacing"] and all(valid_edges):
return
raise LogicTreeError(
node, self.filename,
"'complexFaultGeometry' node is not valid") | [
"def",
"_validate_complex_fault_geometry",
"(",
"self",
",",
"node",
",",
"_float_re",
")",
":",
"valid_edges",
"=",
"[",
"]",
"for",
"edge_node",
"in",
"node",
".",
"nodes",
":",
"try",
":",
"coords",
"=",
"split_coords_3d",
"(",
"edge_node",
".",
"LineStri... | Validates a node representation of a complex fault geometry - this
check merely verifies that the format is correct. If the geometry
does not conform to the Aki & Richards convention this will not be
verified here, but will raise an error when the surface is created. | [
"Validates",
"a",
"node",
"representation",
"of",
"a",
"complex",
"fault",
"geometry",
"-",
"this",
"check",
"merely",
"verifies",
"that",
"the",
"format",
"is",
"correct",
".",
"If",
"the",
"geometry",
"does",
"not",
"conform",
"to",
"the",
"Aki",
"&",
"R... | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L968-L992 | train | 214,022 |
gem/oq-engine | openquake/commonlib/logictree.py | SourceModelLogicTree._validate_planar_fault_geometry | def _validate_planar_fault_geometry(self, node, _float_re):
"""
Validares a node representation of a planar fault geometry
"""
valid_spacing = node["spacing"]
for key in ["topLeft", "topRight", "bottomLeft", "bottomRight"]:
lon = getattr(node, key)["lon"]
lat = getattr(node, key)["lat"]
depth = getattr(node, key)["depth"]
valid_lon = (lon >= -180.0) and (lon <= 180.0)
valid_lat = (lat >= -90.0) and (lat <= 90.0)
valid_depth = (depth >= 0.0)
is_valid = valid_lon and valid_lat and valid_depth
if not is_valid or not valid_spacing:
raise LogicTreeError(
node, self.filename,
"'planarFaultGeometry' node is not valid") | python | def _validate_planar_fault_geometry(self, node, _float_re):
"""
Validares a node representation of a planar fault geometry
"""
valid_spacing = node["spacing"]
for key in ["topLeft", "topRight", "bottomLeft", "bottomRight"]:
lon = getattr(node, key)["lon"]
lat = getattr(node, key)["lat"]
depth = getattr(node, key)["depth"]
valid_lon = (lon >= -180.0) and (lon <= 180.0)
valid_lat = (lat >= -90.0) and (lat <= 90.0)
valid_depth = (depth >= 0.0)
is_valid = valid_lon and valid_lat and valid_depth
if not is_valid or not valid_spacing:
raise LogicTreeError(
node, self.filename,
"'planarFaultGeometry' node is not valid") | [
"def",
"_validate_planar_fault_geometry",
"(",
"self",
",",
"node",
",",
"_float_re",
")",
":",
"valid_spacing",
"=",
"node",
"[",
"\"spacing\"",
"]",
"for",
"key",
"in",
"[",
"\"topLeft\"",
",",
"\"topRight\"",
",",
"\"bottomLeft\"",
",",
"\"bottomRight\"",
"]"... | Validares a node representation of a planar fault geometry | [
"Validares",
"a",
"node",
"representation",
"of",
"a",
"planar",
"fault",
"geometry"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L994-L1010 | train | 214,023 |
gem/oq-engine | openquake/commonlib/logictree.py | SourceModelLogicTree.apply_uncertainties | def apply_uncertainties(self, branch_ids, source_group):
"""
Parse the path through the source model logic tree and return
"apply uncertainties" function.
:param branch_ids:
List of string identifiers of branches, representing the path
through source model logic tree.
:param source_group:
A group of sources
:return:
A copy of the original group with modified sources
"""
branchset = self.root_branchset
branchsets_and_uncertainties = []
branch_ids = list(branch_ids[::-1])
while branchset is not None:
branch = branchset.get_branch_by_id(branch_ids.pop(-1))
if not branchset.uncertainty_type == 'sourceModel':
branchsets_and_uncertainties.append((branchset, branch.value))
branchset = branch.child_branchset
if not branchsets_and_uncertainties:
return source_group # nothing changed
sg = copy.deepcopy(source_group)
sg.applied_uncertainties = []
sg.changed = numpy.zeros(len(sg.sources), int)
for branchset, value in branchsets_and_uncertainties:
for s, source in enumerate(sg.sources):
changed = branchset.apply_uncertainty(value, source)
if changed:
sg.changed[s] += changed
sg.applied_uncertainties.append(
(branchset.uncertainty_type, value))
return sg | python | def apply_uncertainties(self, branch_ids, source_group):
"""
Parse the path through the source model logic tree and return
"apply uncertainties" function.
:param branch_ids:
List of string identifiers of branches, representing the path
through source model logic tree.
:param source_group:
A group of sources
:return:
A copy of the original group with modified sources
"""
branchset = self.root_branchset
branchsets_and_uncertainties = []
branch_ids = list(branch_ids[::-1])
while branchset is not None:
branch = branchset.get_branch_by_id(branch_ids.pop(-1))
if not branchset.uncertainty_type == 'sourceModel':
branchsets_and_uncertainties.append((branchset, branch.value))
branchset = branch.child_branchset
if not branchsets_and_uncertainties:
return source_group # nothing changed
sg = copy.deepcopy(source_group)
sg.applied_uncertainties = []
sg.changed = numpy.zeros(len(sg.sources), int)
for branchset, value in branchsets_and_uncertainties:
for s, source in enumerate(sg.sources):
changed = branchset.apply_uncertainty(value, source)
if changed:
sg.changed[s] += changed
sg.applied_uncertainties.append(
(branchset.uncertainty_type, value))
return sg | [
"def",
"apply_uncertainties",
"(",
"self",
",",
"branch_ids",
",",
"source_group",
")",
":",
"branchset",
"=",
"self",
".",
"root_branchset",
"branchsets_and_uncertainties",
"=",
"[",
"]",
"branch_ids",
"=",
"list",
"(",
"branch_ids",
"[",
":",
":",
"-",
"1",
... | Parse the path through the source model logic tree and return
"apply uncertainties" function.
:param branch_ids:
List of string identifiers of branches, representing the path
through source model logic tree.
:param source_group:
A group of sources
:return:
A copy of the original group with modified sources | [
"Parse",
"the",
"path",
"through",
"the",
"source",
"model",
"logic",
"tree",
"and",
"return",
"apply",
"uncertainties",
"function",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L1178-L1214 | train | 214,024 |
gem/oq-engine | openquake/commonlib/logictree.py | ImtWeight.is_one | def is_one(self):
"""
Check that all the inner weights are 1 up to the precision
"""
return all(abs(v - 1.) < pmf.PRECISION for v in self.dic.values()) | python | def is_one(self):
"""
Check that all the inner weights are 1 up to the precision
"""
return all(abs(v - 1.) < pmf.PRECISION for v in self.dic.values()) | [
"def",
"is_one",
"(",
"self",
")",
":",
"return",
"all",
"(",
"abs",
"(",
"v",
"-",
"1.",
")",
"<",
"pmf",
".",
"PRECISION",
"for",
"v",
"in",
"self",
".",
"dic",
".",
"values",
"(",
")",
")"
] | Check that all the inner weights are 1 up to the precision | [
"Check",
"that",
"all",
"the",
"inner",
"weights",
"are",
"1",
"up",
"to",
"the",
"precision"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L1278-L1282 | train | 214,025 |
gem/oq-engine | openquake/commonlib/logictree.py | GsimLogicTree.from_ | def from_(cls, gsim):
"""
Generate a trivial GsimLogicTree from a single GSIM instance.
"""
ltbranch = N('logicTreeBranch', {'branchID': 'b1'},
nodes=[N('uncertaintyModel', text=str(gsim)),
N('uncertaintyWeight', text='1.0')])
lt = N('logicTree', {'logicTreeID': 'lt1'},
nodes=[N('logicTreeBranchingLevel', {'branchingLevelID': 'bl1'},
nodes=[N('logicTreeBranchSet',
{'applyToTectonicRegionType': '*',
'branchSetID': 'bs1',
'uncertaintyType': 'gmpeModel'},
nodes=[ltbranch])])])
return cls(repr(gsim), ['*'], ltnode=lt) | python | def from_(cls, gsim):
"""
Generate a trivial GsimLogicTree from a single GSIM instance.
"""
ltbranch = N('logicTreeBranch', {'branchID': 'b1'},
nodes=[N('uncertaintyModel', text=str(gsim)),
N('uncertaintyWeight', text='1.0')])
lt = N('logicTree', {'logicTreeID': 'lt1'},
nodes=[N('logicTreeBranchingLevel', {'branchingLevelID': 'bl1'},
nodes=[N('logicTreeBranchSet',
{'applyToTectonicRegionType': '*',
'branchSetID': 'bs1',
'uncertaintyType': 'gmpeModel'},
nodes=[ltbranch])])])
return cls(repr(gsim), ['*'], ltnode=lt) | [
"def",
"from_",
"(",
"cls",
",",
"gsim",
")",
":",
"ltbranch",
"=",
"N",
"(",
"'logicTreeBranch'",
",",
"{",
"'branchID'",
":",
"'b1'",
"}",
",",
"nodes",
"=",
"[",
"N",
"(",
"'uncertaintyModel'",
",",
"text",
"=",
"str",
"(",
"gsim",
")",
")",
","... | Generate a trivial GsimLogicTree from a single GSIM instance. | [
"Generate",
"a",
"trivial",
"GsimLogicTree",
"from",
"a",
"single",
"GSIM",
"instance",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L1328-L1342 | train | 214,026 |
gem/oq-engine | openquake/commonlib/logictree.py | GsimLogicTree.check_imts | def check_imts(self, imts):
"""
Make sure the IMTs are recognized by all GSIMs in the logic tree
"""
for trt in self.values:
for gsim in self.values[trt]:
for attr in dir(gsim):
coeffs = getattr(gsim, attr)
if not isinstance(coeffs, CoeffsTable):
continue
for imt in imts:
if imt.startswith('SA'):
try:
coeffs[from_string(imt)]
except KeyError:
raise ValueError(
'%s is out of the period range defined '
'for %s' % (imt, gsim)) | python | def check_imts(self, imts):
"""
Make sure the IMTs are recognized by all GSIMs in the logic tree
"""
for trt in self.values:
for gsim in self.values[trt]:
for attr in dir(gsim):
coeffs = getattr(gsim, attr)
if not isinstance(coeffs, CoeffsTable):
continue
for imt in imts:
if imt.startswith('SA'):
try:
coeffs[from_string(imt)]
except KeyError:
raise ValueError(
'%s is out of the period range defined '
'for %s' % (imt, gsim)) | [
"def",
"check_imts",
"(",
"self",
",",
"imts",
")",
":",
"for",
"trt",
"in",
"self",
".",
"values",
":",
"for",
"gsim",
"in",
"self",
".",
"values",
"[",
"trt",
"]",
":",
"for",
"attr",
"in",
"dir",
"(",
"gsim",
")",
":",
"coeffs",
"=",
"getattr"... | Make sure the IMTs are recognized by all GSIMs in the logic tree | [
"Make",
"sure",
"the",
"IMTs",
"are",
"recognized",
"by",
"all",
"GSIMs",
"in",
"the",
"logic",
"tree"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L1365-L1382 | train | 214,027 |
gem/oq-engine | openquake/commonlib/logictree.py | GsimLogicTree.reduce | def reduce(self, trts):
"""
Reduce the GsimLogicTree.
:param trts: a subset of tectonic region types
:returns: a reduced GsimLogicTree instance
"""
new = object.__new__(self.__class__)
vars(new).update(vars(self))
if trts != {'*'}:
new.branches = []
for br in self.branches:
branch = BranchTuple(br.trt, br.id, br.gsim, br.weight,
br.trt in trts)
new.branches.append(branch)
return new | python | def reduce(self, trts):
"""
Reduce the GsimLogicTree.
:param trts: a subset of tectonic region types
:returns: a reduced GsimLogicTree instance
"""
new = object.__new__(self.__class__)
vars(new).update(vars(self))
if trts != {'*'}:
new.branches = []
for br in self.branches:
branch = BranchTuple(br.trt, br.id, br.gsim, br.weight,
br.trt in trts)
new.branches.append(branch)
return new | [
"def",
"reduce",
"(",
"self",
",",
"trts",
")",
":",
"new",
"=",
"object",
".",
"__new__",
"(",
"self",
".",
"__class__",
")",
"vars",
"(",
"new",
")",
".",
"update",
"(",
"vars",
"(",
"self",
")",
")",
"if",
"trts",
"!=",
"{",
"'*'",
"}",
":",... | Reduce the GsimLogicTree.
:param trts: a subset of tectonic region types
:returns: a reduced GsimLogicTree instance | [
"Reduce",
"the",
"GsimLogicTree",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L1432-L1447 | train | 214,028 |
gem/oq-engine | openquake/commonlib/logictree.py | GsimLogicTree.get_num_branches | def get_num_branches(self):
"""
Return the number of effective branches for tectonic region type,
as a dictionary.
"""
num = {}
for trt, branches in itertools.groupby(
self.branches, operator.attrgetter('trt')):
num[trt] = sum(1 for br in branches if br.effective)
return num | python | def get_num_branches(self):
"""
Return the number of effective branches for tectonic region type,
as a dictionary.
"""
num = {}
for trt, branches in itertools.groupby(
self.branches, operator.attrgetter('trt')):
num[trt] = sum(1 for br in branches if br.effective)
return num | [
"def",
"get_num_branches",
"(",
"self",
")",
":",
"num",
"=",
"{",
"}",
"for",
"trt",
",",
"branches",
"in",
"itertools",
".",
"groupby",
"(",
"self",
".",
"branches",
",",
"operator",
".",
"attrgetter",
"(",
"'trt'",
")",
")",
":",
"num",
"[",
"trt"... | Return the number of effective branches for tectonic region type,
as a dictionary. | [
"Return",
"the",
"number",
"of",
"effective",
"branches",
"for",
"tectonic",
"region",
"type",
"as",
"a",
"dictionary",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L1449-L1458 | train | 214,029 |
gem/oq-engine | openquake/commonlib/logictree.py | GsimLogicTree.get_num_paths | def get_num_paths(self):
"""
Return the effective number of paths in the tree.
"""
# NB: the algorithm assume a symmetric logic tree for the GSIMs;
# in the future we may relax such assumption
num_branches = self.get_num_branches()
if not sum(num_branches.values()):
return 0
num = 1
for val in num_branches.values():
if val: # the branch is effective
num *= val
return num | python | def get_num_paths(self):
"""
Return the effective number of paths in the tree.
"""
# NB: the algorithm assume a symmetric logic tree for the GSIMs;
# in the future we may relax such assumption
num_branches = self.get_num_branches()
if not sum(num_branches.values()):
return 0
num = 1
for val in num_branches.values():
if val: # the branch is effective
num *= val
return num | [
"def",
"get_num_paths",
"(",
"self",
")",
":",
"# NB: the algorithm assume a symmetric logic tree for the GSIMs;",
"# in the future we may relax such assumption",
"num_branches",
"=",
"self",
".",
"get_num_branches",
"(",
")",
"if",
"not",
"sum",
"(",
"num_branches",
".",
"... | Return the effective number of paths in the tree. | [
"Return",
"the",
"effective",
"number",
"of",
"paths",
"in",
"the",
"tree",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/logictree.py#L1460-L1473 | train | 214,030 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_2003.py | _compute_faulting_style_term | def _compute_faulting_style_term(Frss, pR, Fnss, pN, rake):
"""
Compute SHARE faulting style adjustment term.
"""
if rake > 30.0 and rake <= 150.0:
return np.power(Frss, 1 - pR) * np.power(Fnss, -pN)
elif rake > -120.0 and rake <= -60.0:
return np.power(Frss, - pR) * np.power(Fnss, 1 - pN)
else:
return np.power(Frss, - pR) * np.power(Fnss, - pN) | python | def _compute_faulting_style_term(Frss, pR, Fnss, pN, rake):
"""
Compute SHARE faulting style adjustment term.
"""
if rake > 30.0 and rake <= 150.0:
return np.power(Frss, 1 - pR) * np.power(Fnss, -pN)
elif rake > -120.0 and rake <= -60.0:
return np.power(Frss, - pR) * np.power(Fnss, 1 - pN)
else:
return np.power(Frss, - pR) * np.power(Fnss, - pN) | [
"def",
"_compute_faulting_style_term",
"(",
"Frss",
",",
"pR",
",",
"Fnss",
",",
"pN",
",",
"rake",
")",
":",
"if",
"rake",
">",
"30.0",
"and",
"rake",
"<=",
"150.0",
":",
"return",
"np",
".",
"power",
"(",
"Frss",
",",
"1",
"-",
"pR",
")",
"*",
... | Compute SHARE faulting style adjustment term. | [
"Compute",
"SHARE",
"faulting",
"style",
"adjustment",
"term",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_2003.py#L242-L251 | train | 214,031 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_2003.py | Campbell2003._get_stddevs | def _get_stddevs(self, C, stddev_types, mag, num_sites):
"""
Return total standard deviation as for equation 35, page 1021.
"""
stddevs = []
for _ in stddev_types:
if mag < 7.16:
sigma = C['c11'] + C['c12'] * mag
elif mag >= 7.16:
sigma = C['c13']
stddevs.append(np.zeros(num_sites) + sigma)
return stddevs | python | def _get_stddevs(self, C, stddev_types, mag, num_sites):
"""
Return total standard deviation as for equation 35, page 1021.
"""
stddevs = []
for _ in stddev_types:
if mag < 7.16:
sigma = C['c11'] + C['c12'] * mag
elif mag >= 7.16:
sigma = C['c13']
stddevs.append(np.zeros(num_sites) + sigma)
return stddevs | [
"def",
"_get_stddevs",
"(",
"self",
",",
"C",
",",
"stddev_types",
",",
"mag",
",",
"num_sites",
")",
":",
"stddevs",
"=",
"[",
"]",
"for",
"_",
"in",
"stddev_types",
":",
"if",
"mag",
"<",
"7.16",
":",
"sigma",
"=",
"C",
"[",
"'c11'",
"]",
"+",
... | Return total standard deviation as for equation 35, page 1021. | [
"Return",
"total",
"standard",
"deviation",
"as",
"for",
"equation",
"35",
"page",
"1021",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_2003.py#L106-L118 | train | 214,032 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_2003.py | Campbell2003._compute_term2 | def _compute_term2(self, C, mag, rrup):
"""
This computes the term f2 in equation 32, page 1021
"""
c78_factor = (C['c7'] * np.exp(C['c8'] * mag)) ** 2
R = np.sqrt(rrup ** 2 + c78_factor)
return C['c4'] * np.log(R) + (C['c5'] + C['c6'] * mag) * rrup | python | def _compute_term2(self, C, mag, rrup):
"""
This computes the term f2 in equation 32, page 1021
"""
c78_factor = (C['c7'] * np.exp(C['c8'] * mag)) ** 2
R = np.sqrt(rrup ** 2 + c78_factor)
return C['c4'] * np.log(R) + (C['c5'] + C['c6'] * mag) * rrup | [
"def",
"_compute_term2",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rrup",
")",
":",
"c78_factor",
"=",
"(",
"C",
"[",
"'c7'",
"]",
"*",
"np",
".",
"exp",
"(",
"C",
"[",
"'c8'",
"]",
"*",
"mag",
")",
")",
"**",
"2",
"R",
"=",
"np",
".",
"sqrt... | This computes the term f2 in equation 32, page 1021 | [
"This",
"computes",
"the",
"term",
"f2",
"in",
"equation",
"32",
"page",
"1021"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_2003.py#L126-L133 | train | 214,033 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_2003.py | Campbell2003._compute_term3 | def _compute_term3(self, C, rrup):
"""
This computes the term f3 in equation 34, page 1021 but corrected
according to the erratum.
"""
f3 = np.zeros_like(rrup)
idx_between_70_130 = (rrup > 70) & (rrup <= 130)
idx_greater_130 = rrup > 130
f3[idx_between_70_130] = (
C['c9'] * (np.log(rrup[idx_between_70_130]) - np.log(70))
)
f3[idx_greater_130] = (
C['c9'] * (np.log(rrup[idx_greater_130]) - np.log(70)) +
C['c10'] * (np.log(rrup[idx_greater_130]) - np.log(130))
)
return f3 | python | def _compute_term3(self, C, rrup):
"""
This computes the term f3 in equation 34, page 1021 but corrected
according to the erratum.
"""
f3 = np.zeros_like(rrup)
idx_between_70_130 = (rrup > 70) & (rrup <= 130)
idx_greater_130 = rrup > 130
f3[idx_between_70_130] = (
C['c9'] * (np.log(rrup[idx_between_70_130]) - np.log(70))
)
f3[idx_greater_130] = (
C['c9'] * (np.log(rrup[idx_greater_130]) - np.log(70)) +
C['c10'] * (np.log(rrup[idx_greater_130]) - np.log(130))
)
return f3 | [
"def",
"_compute_term3",
"(",
"self",
",",
"C",
",",
"rrup",
")",
":",
"f3",
"=",
"np",
".",
"zeros_like",
"(",
"rrup",
")",
"idx_between_70_130",
"=",
"(",
"rrup",
">",
"70",
")",
"&",
"(",
"rrup",
"<=",
"130",
")",
"idx_greater_130",
"=",
"rrup",
... | This computes the term f3 in equation 34, page 1021 but corrected
according to the erratum. | [
"This",
"computes",
"the",
"term",
"f3",
"in",
"equation",
"34",
"page",
"1021",
"but",
"corrected",
"according",
"to",
"the",
"erratum",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_2003.py#L135-L154 | train | 214,034 |
gem/oq-engine | openquake/hmtk/seismicity/declusterer/distance_time_windows.py | time_window_cutoff | def time_window_cutoff(sw_time, time_cutoff):
"""
Allows for cutting the declustering time window at a specific time, outside
of which an event of any magnitude is no longer identified as a cluster
"""
sw_time = np.array(
[(time_cutoff / DAYS) if x > (time_cutoff / DAYS)
else x for x in sw_time])
return(sw_time) | python | def time_window_cutoff(sw_time, time_cutoff):
"""
Allows for cutting the declustering time window at a specific time, outside
of which an event of any magnitude is no longer identified as a cluster
"""
sw_time = np.array(
[(time_cutoff / DAYS) if x > (time_cutoff / DAYS)
else x for x in sw_time])
return(sw_time) | [
"def",
"time_window_cutoff",
"(",
"sw_time",
",",
"time_cutoff",
")",
":",
"sw_time",
"=",
"np",
".",
"array",
"(",
"[",
"(",
"time_cutoff",
"/",
"DAYS",
")",
"if",
"x",
">",
"(",
"time_cutoff",
"/",
"DAYS",
")",
"else",
"x",
"for",
"x",
"in",
"sw_ti... | Allows for cutting the declustering time window at a specific time, outside
of which an event of any magnitude is no longer identified as a cluster | [
"Allows",
"for",
"cutting",
"the",
"declustering",
"time",
"window",
"at",
"a",
"specific",
"time",
"outside",
"of",
"which",
"an",
"event",
"of",
"any",
"magnitude",
"is",
"no",
"longer",
"identified",
"as",
"a",
"cluster"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/declusterer/distance_time_windows.py#L59-L67 | train | 214,035 |
gem/oq-engine | openquake/hmtk/sources/point_source.py | mtkPointSource.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.point.Point class, otherwise if already instance of class
accept class
:param input_geometry:
Input geometry (point) as either
i) instance of nhlib.geo.point.Point 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, Point):
if not isinstance(input_geometry, np.ndarray):
raise ValueError('Unrecognised or unsupported geometry '
'definition')
self.geometry = Point(input_geometry[0], input_geometry[1])
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.point.Point class, otherwise if already instance of class
accept class
:param input_geometry:
Input geometry (point) as either
i) instance of nhlib.geo.point.Point 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, Point):
if not isinstance(input_geometry, np.ndarray):
raise ValueError('Unrecognised or unsupported geometry '
'definition')
self.geometry = Point(input_geometry[0], input_geometry[1])
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",
"(",
... | If geometry is defined as a numpy array then create instance of
nhlib.geo.point.Point class, otherwise if already instance of class
accept class
:param input_geometry:
Input geometry (point) as either
i) instance of nhlib.geo.point.Point 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",
".",
"point",
".",
"Point",
"class",
"otherwise",
"if",
"already",
"instance",
"of",
"class",
"accept",
"class"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/point_source.py#L115-L141 | train | 214,036 |
gem/oq-engine | openquake/hmtk/sources/point_source.py | mtkPointSource.select_catalogue | def select_catalogue(self, selector, distance, selector_type='circle',
distance_metric='epicentral', point_depth=None,
upper_eq_depth=None, lower_eq_depth=None):
'''
Selects the catalogue associated to the point source.
Effectively a wrapper to the two functions select catalogue within
a distance of the point and select catalogue within cell centred on
point
:param selector:
Populated instance of :class:
`openquake.hmtk.seismicity.selector.CatalogueSelector`
:param float distance:
Distance from point (km) for selection
:param str selector_type:
Chooses whether to select within {'circle'} or within a {'square'}.
:param str distance_metric:
'epicentral' or 'hypocentral' (only for 'circle' selector type)
:param float point_depth:
Assumed hypocentral depth of the point (only applied to 'circle'
distance type)
:param float upper_depth:
Upper seismogenic depth (km) (only for 'square')
:param float lower_depth:
Lower seismogenic depth (km) (only for 'square')
'''
if selector.catalogue.get_number_events() < 1:
raise ValueError('No events found in catalogue!')
if 'square' in selector_type:
# Calls select catalogue within cell function
self.select_catalogue_within_cell(selector,
distance,
upper_depth=upper_eq_depth,
lower_depth=lower_eq_depth)
elif 'circle' in selector_type:
# Calls select catalogue within distance function
self.select_catalogue_within_distance(selector, distance,
distance_metric, point_depth)
else:
raise ValueError('Unrecognised selection type for point source!') | python | def select_catalogue(self, selector, distance, selector_type='circle',
distance_metric='epicentral', point_depth=None,
upper_eq_depth=None, lower_eq_depth=None):
'''
Selects the catalogue associated to the point source.
Effectively a wrapper to the two functions select catalogue within
a distance of the point and select catalogue within cell centred on
point
:param selector:
Populated instance of :class:
`openquake.hmtk.seismicity.selector.CatalogueSelector`
:param float distance:
Distance from point (km) for selection
:param str selector_type:
Chooses whether to select within {'circle'} or within a {'square'}.
:param str distance_metric:
'epicentral' or 'hypocentral' (only for 'circle' selector type)
:param float point_depth:
Assumed hypocentral depth of the point (only applied to 'circle'
distance type)
:param float upper_depth:
Upper seismogenic depth (km) (only for 'square')
:param float lower_depth:
Lower seismogenic depth (km) (only for 'square')
'''
if selector.catalogue.get_number_events() < 1:
raise ValueError('No events found in catalogue!')
if 'square' in selector_type:
# Calls select catalogue within cell function
self.select_catalogue_within_cell(selector,
distance,
upper_depth=upper_eq_depth,
lower_depth=lower_eq_depth)
elif 'circle' in selector_type:
# Calls select catalogue within distance function
self.select_catalogue_within_distance(selector, distance,
distance_metric, point_depth)
else:
raise ValueError('Unrecognised selection type for point source!') | [
"def",
"select_catalogue",
"(",
"self",
",",
"selector",
",",
"distance",
",",
"selector_type",
"=",
"'circle'",
",",
"distance_metric",
"=",
"'epicentral'",
",",
"point_depth",
"=",
"None",
",",
"upper_eq_depth",
"=",
"None",
",",
"lower_eq_depth",
"=",
"None",... | Selects the catalogue associated to the point source.
Effectively a wrapper to the two functions select catalogue within
a distance of the point and select catalogue within cell centred on
point
:param selector:
Populated instance of :class:
`openquake.hmtk.seismicity.selector.CatalogueSelector`
:param float distance:
Distance from point (km) for selection
:param str selector_type:
Chooses whether to select within {'circle'} or within a {'square'}.
:param str distance_metric:
'epicentral' or 'hypocentral' (only for 'circle' selector type)
:param float point_depth:
Assumed hypocentral depth of the point (only applied to 'circle'
distance type)
:param float upper_depth:
Upper seismogenic depth (km) (only for 'square')
:param float lower_depth:
Lower seismogenic depth (km) (only for 'square') | [
"Selects",
"the",
"catalogue",
"associated",
"to",
"the",
"point",
"source",
".",
"Effectively",
"a",
"wrapper",
"to",
"the",
"two",
"functions",
"select",
"catalogue",
"within",
"a",
"distance",
"of",
"the",
"point",
"and",
"select",
"catalogue",
"within",
"c... | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/point_source.py#L170-L213 | train | 214,037 |
gem/oq-engine | openquake/commands/plot.py | plot | def plot(what, calc_id=-1, other_id=None, webapi=False):
"""
Generic plotter for local and remote calculations.
"""
if '?' not in what:
raise SystemExit('Missing ? in %r' % what)
prefix, rest = what.split('?', 1)
assert prefix in 'source_geom hcurves hmaps uhs', prefix
if prefix in 'hcurves hmaps' and 'imt=' not in rest:
raise SystemExit('Missing imt= in %r' % what)
elif prefix == 'uhs' and 'imt=' in rest:
raise SystemExit('Invalid IMT in %r' % what)
elif prefix in 'hcurves uhs' and 'site_id=' not in rest:
what += '&site_id=0'
if webapi:
xs = [WebExtractor(calc_id)]
if other_id:
xs.append(WebExtractor(other_id))
else:
xs = [Extractor(calc_id)]
if other_id:
xs.append(Extractor(other_id))
make_figure = globals()['make_figure_' + prefix]
plt = make_figure(xs, what)
plt.show() | python | def plot(what, calc_id=-1, other_id=None, webapi=False):
"""
Generic plotter for local and remote calculations.
"""
if '?' not in what:
raise SystemExit('Missing ? in %r' % what)
prefix, rest = what.split('?', 1)
assert prefix in 'source_geom hcurves hmaps uhs', prefix
if prefix in 'hcurves hmaps' and 'imt=' not in rest:
raise SystemExit('Missing imt= in %r' % what)
elif prefix == 'uhs' and 'imt=' in rest:
raise SystemExit('Invalid IMT in %r' % what)
elif prefix in 'hcurves uhs' and 'site_id=' not in rest:
what += '&site_id=0'
if webapi:
xs = [WebExtractor(calc_id)]
if other_id:
xs.append(WebExtractor(other_id))
else:
xs = [Extractor(calc_id)]
if other_id:
xs.append(Extractor(other_id))
make_figure = globals()['make_figure_' + prefix]
plt = make_figure(xs, what)
plt.show() | [
"def",
"plot",
"(",
"what",
",",
"calc_id",
"=",
"-",
"1",
",",
"other_id",
"=",
"None",
",",
"webapi",
"=",
"False",
")",
":",
"if",
"'?'",
"not",
"in",
"what",
":",
"raise",
"SystemExit",
"(",
"'Missing ? in %r'",
"%",
"what",
")",
"prefix",
",",
... | Generic plotter for local and remote calculations. | [
"Generic",
"plotter",
"for",
"local",
"and",
"remote",
"calculations",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/plot.py#L144-L168 | train | 214,038 |
gem/oq-engine | openquake/hazardlib/gsim/multi.py | MultiGMPE.get_mean_and_stddevs | def get_mean_and_stddevs(self, sctx, rctx, dctx, imt, stddev_types):
"""
Call the get mean and stddevs of the GMPE for the respective IMT
"""
return self.kwargs[str(imt)].get_mean_and_stddevs(
sctx, rctx, dctx, imt, stddev_types) | python | def get_mean_and_stddevs(self, sctx, rctx, dctx, imt, stddev_types):
"""
Call the get mean and stddevs of the GMPE for the respective IMT
"""
return self.kwargs[str(imt)].get_mean_and_stddevs(
sctx, rctx, dctx, imt, stddev_types) | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sctx",
",",
"rctx",
",",
"dctx",
",",
"imt",
",",
"stddev_types",
")",
":",
"return",
"self",
".",
"kwargs",
"[",
"str",
"(",
"imt",
")",
"]",
".",
"get_mean_and_stddevs",
"(",
"sctx",
",",
"rctx",
",",... | Call the get mean and stddevs of the GMPE for the respective IMT | [
"Call",
"the",
"get",
"mean",
"and",
"stddevs",
"of",
"the",
"GMPE",
"for",
"the",
"respective",
"IMT"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/multi.py#L97-L102 | train | 214,039 |
gem/oq-engine | openquake/commands/plot_agg_curve.py | plot_ac | def plot_ac(calc_id):
"""
Aggregate loss curves plotter.
"""
# read the hazard data
dstore = util.read(calc_id)
agg_curve = dstore['agg_curve-rlzs']
plt = make_figure(agg_curve)
plt.show() | python | def plot_ac(calc_id):
"""
Aggregate loss curves plotter.
"""
# read the hazard data
dstore = util.read(calc_id)
agg_curve = dstore['agg_curve-rlzs']
plt = make_figure(agg_curve)
plt.show() | [
"def",
"plot_ac",
"(",
"calc_id",
")",
":",
"# read the hazard data",
"dstore",
"=",
"util",
".",
"read",
"(",
"calc_id",
")",
"agg_curve",
"=",
"dstore",
"[",
"'agg_curve-rlzs'",
"]",
"plt",
"=",
"make_figure",
"(",
"agg_curve",
")",
"plt",
".",
"show",
"... | Aggregate loss curves plotter. | [
"Aggregate",
"loss",
"curves",
"plotter",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/plot_agg_curve.py#L42-L50 | train | 214,040 |
gem/oq-engine | openquake/hazardlib/gsim/allen_2012_ipe.py | AllenEtAl2012._get_stddevs | def _get_stddevs(self, C, distance, stddev_types):
"""
Returns the total standard deviation, which is a function of distance
"""
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
sigma = C["s1"] + (C["s2"] / (1.0 +
((distance / C["s3"]) ** 2.)))
stddevs.append(sigma + np.zeros_like(distance))
return stddevs | python | def _get_stddevs(self, C, distance, stddev_types):
"""
Returns the total standard deviation, which is a function of distance
"""
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
sigma = C["s1"] + (C["s2"] / (1.0 +
((distance / C["s3"]) ** 2.)))
stddevs.append(sigma + np.zeros_like(distance))
return stddevs | [
"def",
"_get_stddevs",
"(",
"self",
",",
"C",
",",
"distance",
",",
"stddev_types",
")",
":",
"stddevs",
"=",
"[",
"]",
"for",
"stddev_type",
"in",
"stddev_types",
":",
"assert",
"stddev_type",
"in",
"self",
".",
"DEFINED_FOR_STANDARD_DEVIATION_TYPES",
"if",
"... | Returns the total standard deviation, which is a function of distance | [
"Returns",
"the",
"total",
"standard",
"deviation",
"which",
"is",
"a",
"function",
"of",
"distance"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/allen_2012_ipe.py#L92-L103 | train | 214,041 |
gem/oq-engine | openquake/hazardlib/gsim/allen_2012.py | Allen2012._compute_mean | def _compute_mean(self, C, mag, rrup):
"""
Compute mean value according to equation 18, page 32.
"""
# see table 3, page 14
R1 = 90.
R2 = 150.
# see equation 19, page 32
m_ref = mag - 4
r1 = R1 + C['c8'] * m_ref
r2 = R2 + C['c11'] * m_ref
assert r1 > 0
assert r2 > 0
g0 = np.log10(
np.sqrt(np.minimum(rrup, r1) ** 2 + (1 + C['c5'] * m_ref) ** 2)
)
g1 = np.maximum(np.log10(rrup / r1), 0)
g2 = np.maximum(np.log10(rrup / r2), 0)
mean = (C['c0'] + C['c1'] * m_ref + C['c2'] * m_ref ** 2 +
(C['c3'] + C['c4'] * m_ref) * g0 +
(C['c6'] + C['c7'] * m_ref) * g1 +
(C['c9'] + C['c10'] * m_ref) * g2)
# convert from log10 to ln and units from cm/s2 to g
mean = np.log((10 ** mean) * 1e-2 / g)
return mean | python | def _compute_mean(self, C, mag, rrup):
"""
Compute mean value according to equation 18, page 32.
"""
# see table 3, page 14
R1 = 90.
R2 = 150.
# see equation 19, page 32
m_ref = mag - 4
r1 = R1 + C['c8'] * m_ref
r2 = R2 + C['c11'] * m_ref
assert r1 > 0
assert r2 > 0
g0 = np.log10(
np.sqrt(np.minimum(rrup, r1) ** 2 + (1 + C['c5'] * m_ref) ** 2)
)
g1 = np.maximum(np.log10(rrup / r1), 0)
g2 = np.maximum(np.log10(rrup / r2), 0)
mean = (C['c0'] + C['c1'] * m_ref + C['c2'] * m_ref ** 2 +
(C['c3'] + C['c4'] * m_ref) * g0 +
(C['c6'] + C['c7'] * m_ref) * g1 +
(C['c9'] + C['c10'] * m_ref) * g2)
# convert from log10 to ln and units from cm/s2 to g
mean = np.log((10 ** mean) * 1e-2 / g)
return mean | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rrup",
")",
":",
"# see table 3, page 14",
"R1",
"=",
"90.",
"R2",
"=",
"150.",
"# see equation 19, page 32",
"m_ref",
"=",
"mag",
"-",
"4",
"r1",
"=",
"R1",
"+",
"C",
"[",
"'c8'",
"]",
... | Compute mean value according to equation 18, page 32. | [
"Compute",
"mean",
"value",
"according",
"to",
"equation",
"18",
"page",
"32",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/allen_2012.py#L93-L120 | train | 214,042 |
gem/oq-engine | openquake/commands/extract.py | extract | def extract(what, calc_id, webapi=True):
"""
Extract an output from the datastore and save it into an .hdf5 file.
By default uses the WebAPI, otherwise the extraction is done locally.
"""
with performance.Monitor('extract', measuremem=True) as mon:
if webapi:
obj = WebExtractor(calc_id).get(what)
else:
obj = Extractor(calc_id).get(what)
fname = '%s_%d.hdf5' % (what.replace('/', '-').replace('?', '-'),
calc_id)
obj.save(fname)
print('Saved', fname)
if mon.duration > 1:
print(mon) | python | def extract(what, calc_id, webapi=True):
"""
Extract an output from the datastore and save it into an .hdf5 file.
By default uses the WebAPI, otherwise the extraction is done locally.
"""
with performance.Monitor('extract', measuremem=True) as mon:
if webapi:
obj = WebExtractor(calc_id).get(what)
else:
obj = Extractor(calc_id).get(what)
fname = '%s_%d.hdf5' % (what.replace('/', '-').replace('?', '-'),
calc_id)
obj.save(fname)
print('Saved', fname)
if mon.duration > 1:
print(mon) | [
"def",
"extract",
"(",
"what",
",",
"calc_id",
",",
"webapi",
"=",
"True",
")",
":",
"with",
"performance",
".",
"Monitor",
"(",
"'extract'",
",",
"measuremem",
"=",
"True",
")",
"as",
"mon",
":",
"if",
"webapi",
":",
"obj",
"=",
"WebExtractor",
"(",
... | Extract an output from the datastore and save it into an .hdf5 file.
By default uses the WebAPI, otherwise the extraction is done locally. | [
"Extract",
"an",
"output",
"from",
"the",
"datastore",
"and",
"save",
"it",
"into",
"an",
".",
"hdf5",
"file",
".",
"By",
"default",
"uses",
"the",
"WebAPI",
"otherwise",
"the",
"extraction",
"is",
"done",
"locally",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/extract.py#L24-L39 | train | 214,043 |
gem/oq-engine | openquake/hmtk/strain/regionalisation/kreemer_regionalisation.py | KreemerRegionalisation.get_regionalisation | def get_regionalisation(self, strain_model):
'''
Gets the tectonic region type for every element inside the strain model
:paramm strain_model:
Input strain model as instance of
openquake.hmtk.strain.geodetic_strain.GeodeticStrain
:returns:
Strain model with complete regionalisation
'''
self.strain = strain_model
self.strain.data['region'] = np.array(
['IPL'
for _ in range(self.strain.get_number_observations())],
dtype='|S13')
self.strain.data['area'] = np.array(
[np.nan
for _ in range(self.strain.get_number_observations())])
regional_model = self.define_kreemer_regionalisation()
for polygon in regional_model:
self._point_in_tectonic_region(polygon)
return self.strain | python | def get_regionalisation(self, strain_model):
'''
Gets the tectonic region type for every element inside the strain model
:paramm strain_model:
Input strain model as instance of
openquake.hmtk.strain.geodetic_strain.GeodeticStrain
:returns:
Strain model with complete regionalisation
'''
self.strain = strain_model
self.strain.data['region'] = np.array(
['IPL'
for _ in range(self.strain.get_number_observations())],
dtype='|S13')
self.strain.data['area'] = np.array(
[np.nan
for _ in range(self.strain.get_number_observations())])
regional_model = self.define_kreemer_regionalisation()
for polygon in regional_model:
self._point_in_tectonic_region(polygon)
return self.strain | [
"def",
"get_regionalisation",
"(",
"self",
",",
"strain_model",
")",
":",
"self",
".",
"strain",
"=",
"strain_model",
"self",
".",
"strain",
".",
"data",
"[",
"'region'",
"]",
"=",
"np",
".",
"array",
"(",
"[",
"'IPL'",
"for",
"_",
"in",
"range",
"(",
... | Gets the tectonic region type for every element inside the strain model
:paramm strain_model:
Input strain model as instance of
openquake.hmtk.strain.geodetic_strain.GeodeticStrain
:returns:
Strain model with complete regionalisation | [
"Gets",
"the",
"tectonic",
"region",
"type",
"for",
"every",
"element",
"inside",
"the",
"strain",
"model"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/strain/regionalisation/kreemer_regionalisation.py#L100-L124 | train | 214,044 |
gem/oq-engine | openquake/hmtk/strain/regionalisation/kreemer_regionalisation.py | KreemerRegionalisation.define_kreemer_regionalisation | def define_kreemer_regionalisation(self, north=90., south=-90., east=180.,
west=-180.):
'''
Applies the regionalisation defined according to the regionalisation
typology of Corne Kreemer
'''
'''Applies the regionalisation of Kreemer (2003)
:param input_file:
Filename (str) of input file contraining Kreemer regionalisation
:param north:
Northern limit (decimal degrees)for consideration (float)
:param south:
Southern limit (decimal degrees)for consideration (float)
:param east:
Eastern limit (decimal degrees)for consideration (float)
:param west:
Western limit (decimal degrees)for consideration (float)
:returns: List of polygons corresonding to the Kreemer cells.
'''
input_data = getlines(self.filename)
kreemer_polygons = []
for line_loc, line in enumerate(input_data):
if '>' in line[0]:
polygon_dict = {}
# Get region type (char) and area (m ^ 2) from header
primary_data = line[2:].rstrip('\n')
primary_data = primary_data.split(' ', 1)
polygon_dict['region_type'] = primary_data[0].strip(' ')
polygon_dict['area'] = float(primary_data[1].strip(' '))
polygon_dict['cell'] = _build_kreemer_cell(input_data,
line_loc)
polygon_dict['long_lims'] = np.array([
np.min(polygon_dict['cell'][:, 0]),
np.max(polygon_dict['cell'][:, 0])])
polygon_dict['lat_lims'] = np.array([
np.min(polygon_dict['cell'][:, 1]),
np.max(polygon_dict['cell'][:, 1])])
polygon_dict['cell'] = None
if polygon_dict['long_lims'][0] >= 180.0:
polygon_dict['long_lims'] = \
polygon_dict['long_lims'] - 360.0
valid_check = [
polygon_dict['long_lims'][0] >= west,
polygon_dict['long_lims'][1] <= east,
polygon_dict['lat_lims'][0] >= south,
polygon_dict['lat_lims'][1] <= north]
if all(valid_check):
kreemer_polygons.append(polygon_dict)
return kreemer_polygons | python | def define_kreemer_regionalisation(self, north=90., south=-90., east=180.,
west=-180.):
'''
Applies the regionalisation defined according to the regionalisation
typology of Corne Kreemer
'''
'''Applies the regionalisation of Kreemer (2003)
:param input_file:
Filename (str) of input file contraining Kreemer regionalisation
:param north:
Northern limit (decimal degrees)for consideration (float)
:param south:
Southern limit (decimal degrees)for consideration (float)
:param east:
Eastern limit (decimal degrees)for consideration (float)
:param west:
Western limit (decimal degrees)for consideration (float)
:returns: List of polygons corresonding to the Kreemer cells.
'''
input_data = getlines(self.filename)
kreemer_polygons = []
for line_loc, line in enumerate(input_data):
if '>' in line[0]:
polygon_dict = {}
# Get region type (char) and area (m ^ 2) from header
primary_data = line[2:].rstrip('\n')
primary_data = primary_data.split(' ', 1)
polygon_dict['region_type'] = primary_data[0].strip(' ')
polygon_dict['area'] = float(primary_data[1].strip(' '))
polygon_dict['cell'] = _build_kreemer_cell(input_data,
line_loc)
polygon_dict['long_lims'] = np.array([
np.min(polygon_dict['cell'][:, 0]),
np.max(polygon_dict['cell'][:, 0])])
polygon_dict['lat_lims'] = np.array([
np.min(polygon_dict['cell'][:, 1]),
np.max(polygon_dict['cell'][:, 1])])
polygon_dict['cell'] = None
if polygon_dict['long_lims'][0] >= 180.0:
polygon_dict['long_lims'] = \
polygon_dict['long_lims'] - 360.0
valid_check = [
polygon_dict['long_lims'][0] >= west,
polygon_dict['long_lims'][1] <= east,
polygon_dict['lat_lims'][0] >= south,
polygon_dict['lat_lims'][1] <= north]
if all(valid_check):
kreemer_polygons.append(polygon_dict)
return kreemer_polygons | [
"def",
"define_kreemer_regionalisation",
"(",
"self",
",",
"north",
"=",
"90.",
",",
"south",
"=",
"-",
"90.",
",",
"east",
"=",
"180.",
",",
"west",
"=",
"-",
"180.",
")",
":",
"'''Applies the regionalisation of Kreemer (2003)\n :param input_file:\n ... | Applies the regionalisation defined according to the regionalisation
typology of Corne Kreemer | [
"Applies",
"the",
"regionalisation",
"defined",
"according",
"to",
"the",
"regionalisation",
"typology",
"of",
"Corne",
"Kreemer"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/strain/regionalisation/kreemer_regionalisation.py#L153-L204 | train | 214,045 |
gem/oq-engine | openquake/hazardlib/shakemap.py | urlextract | def urlextract(url, fname):
"""
Download and unzip an archive and extract the underlying fname
"""
with urlopen(url) as f:
data = io.BytesIO(f.read())
with zipfile.ZipFile(data) as z:
try:
return z.open(fname)
except KeyError:
# for instance the ShakeMap ci3031111 has inside a file
# data/verified_atlas2.0/reviewed/19920628115739/output/
# uncertainty.xml
# instead of just uncertainty.xml
zinfo = z.filelist[0]
if zinfo.filename.endswith(fname):
return z.open(zinfo)
else:
raise | python | def urlextract(url, fname):
"""
Download and unzip an archive and extract the underlying fname
"""
with urlopen(url) as f:
data = io.BytesIO(f.read())
with zipfile.ZipFile(data) as z:
try:
return z.open(fname)
except KeyError:
# for instance the ShakeMap ci3031111 has inside a file
# data/verified_atlas2.0/reviewed/19920628115739/output/
# uncertainty.xml
# instead of just uncertainty.xml
zinfo = z.filelist[0]
if zinfo.filename.endswith(fname):
return z.open(zinfo)
else:
raise | [
"def",
"urlextract",
"(",
"url",
",",
"fname",
")",
":",
"with",
"urlopen",
"(",
"url",
")",
"as",
"f",
":",
"data",
"=",
"io",
".",
"BytesIO",
"(",
"f",
".",
"read",
"(",
")",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"data",
")",
"as",
"z"... | Download and unzip an archive and extract the underlying fname | [
"Download",
"and",
"unzip",
"an",
"archive",
"and",
"extract",
"the",
"underlying",
"fname"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/shakemap.py#L46-L64 | train | 214,046 |
gem/oq-engine | openquake/hazardlib/shakemap.py | amplify_gmfs | def amplify_gmfs(imts, vs30s, gmfs):
"""
Amplify the ground shaking depending on the vs30s
"""
n = len(vs30s)
out = [amplify_ground_shaking(im.period, vs30s[i], gmfs[m * n + i])
for m, im in enumerate(imts) for i in range(n)]
return numpy.array(out) | python | def amplify_gmfs(imts, vs30s, gmfs):
"""
Amplify the ground shaking depending on the vs30s
"""
n = len(vs30s)
out = [amplify_ground_shaking(im.period, vs30s[i], gmfs[m * n + i])
for m, im in enumerate(imts) for i in range(n)]
return numpy.array(out) | [
"def",
"amplify_gmfs",
"(",
"imts",
",",
"vs30s",
",",
"gmfs",
")",
":",
"n",
"=",
"len",
"(",
"vs30s",
")",
"out",
"=",
"[",
"amplify_ground_shaking",
"(",
"im",
".",
"period",
",",
"vs30s",
"[",
"i",
"]",
",",
"gmfs",
"[",
"m",
"*",
"n",
"+",
... | Amplify the ground shaking depending on the vs30s | [
"Amplify",
"the",
"ground",
"shaking",
"depending",
"on",
"the",
"vs30s"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/shakemap.py#L220-L227 | train | 214,047 |
gem/oq-engine | openquake/hazardlib/shakemap.py | cholesky | def cholesky(spatial_cov, cross_corr):
"""
Decompose the spatial covariance and cross correlation matrices.
:param spatial_cov: array of shape (M, N, N)
:param cross_corr: array of shape (M, M)
:returns: a triangular matrix of shape (M * N, M * N)
"""
M, N = spatial_cov.shape[:2]
L = numpy.array([numpy.linalg.cholesky(spatial_cov[i]) for i in range(M)])
LLT = []
for i in range(M):
row = [numpy.dot(L[i], L[j].T) * cross_corr[i, j] for j in range(M)]
for j in range(N):
singlerow = numpy.zeros(M * N)
for i in range(M):
singlerow[i * N:(i + 1) * N] = row[i][j]
LLT.append(singlerow)
return numpy.linalg.cholesky(numpy.array(LLT)) | python | def cholesky(spatial_cov, cross_corr):
"""
Decompose the spatial covariance and cross correlation matrices.
:param spatial_cov: array of shape (M, N, N)
:param cross_corr: array of shape (M, M)
:returns: a triangular matrix of shape (M * N, M * N)
"""
M, N = spatial_cov.shape[:2]
L = numpy.array([numpy.linalg.cholesky(spatial_cov[i]) for i in range(M)])
LLT = []
for i in range(M):
row = [numpy.dot(L[i], L[j].T) * cross_corr[i, j] for j in range(M)]
for j in range(N):
singlerow = numpy.zeros(M * N)
for i in range(M):
singlerow[i * N:(i + 1) * N] = row[i][j]
LLT.append(singlerow)
return numpy.linalg.cholesky(numpy.array(LLT)) | [
"def",
"cholesky",
"(",
"spatial_cov",
",",
"cross_corr",
")",
":",
"M",
",",
"N",
"=",
"spatial_cov",
".",
"shape",
"[",
":",
"2",
"]",
"L",
"=",
"numpy",
".",
"array",
"(",
"[",
"numpy",
".",
"linalg",
".",
"cholesky",
"(",
"spatial_cov",
"[",
"i... | Decompose the spatial covariance and cross correlation matrices.
:param spatial_cov: array of shape (M, N, N)
:param cross_corr: array of shape (M, M)
:returns: a triangular matrix of shape (M * N, M * N) | [
"Decompose",
"the",
"spatial",
"covariance",
"and",
"cross",
"correlation",
"matrices",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/shakemap.py#L257-L275 | train | 214,048 |
gem/oq-engine | openquake/commonlib/writers.py | build_header | def build_header(dtype):
"""
Convert a numpy nested dtype into a list of strings suitable as header
of csv file.
>>> imt_dt = numpy.dtype([('PGA', numpy.float32, 3),
... ('PGV', numpy.float32, 4)])
>>> build_header(imt_dt)
['PGA:3', 'PGV:4']
>>> gmf_dt = numpy.dtype([('A', imt_dt), ('B', imt_dt),
... ('idx', numpy.uint32)])
>>> build_header(gmf_dt)
['A~PGA:3', 'A~PGV:4', 'B~PGA:3', 'B~PGV:4', 'idx:uint32']
"""
header = _build_header(dtype, ())
h = []
for col in header:
name = '~'.join(col[:-2])
numpytype = col[-2]
shape = col[-1]
coldescr = name
if numpytype != 'float32' and not numpytype.startswith('|S'):
coldescr += ':' + numpytype
if shape:
coldescr += ':' + ':'.join(map(str, shape))
h.append(coldescr)
return h | python | def build_header(dtype):
"""
Convert a numpy nested dtype into a list of strings suitable as header
of csv file.
>>> imt_dt = numpy.dtype([('PGA', numpy.float32, 3),
... ('PGV', numpy.float32, 4)])
>>> build_header(imt_dt)
['PGA:3', 'PGV:4']
>>> gmf_dt = numpy.dtype([('A', imt_dt), ('B', imt_dt),
... ('idx', numpy.uint32)])
>>> build_header(gmf_dt)
['A~PGA:3', 'A~PGV:4', 'B~PGA:3', 'B~PGV:4', 'idx:uint32']
"""
header = _build_header(dtype, ())
h = []
for col in header:
name = '~'.join(col[:-2])
numpytype = col[-2]
shape = col[-1]
coldescr = name
if numpytype != 'float32' and not numpytype.startswith('|S'):
coldescr += ':' + numpytype
if shape:
coldescr += ':' + ':'.join(map(str, shape))
h.append(coldescr)
return h | [
"def",
"build_header",
"(",
"dtype",
")",
":",
"header",
"=",
"_build_header",
"(",
"dtype",
",",
"(",
")",
")",
"h",
"=",
"[",
"]",
"for",
"col",
"in",
"header",
":",
"name",
"=",
"'~'",
".",
"join",
"(",
"col",
"[",
":",
"-",
"2",
"]",
")",
... | Convert a numpy nested dtype into a list of strings suitable as header
of csv file.
>>> imt_dt = numpy.dtype([('PGA', numpy.float32, 3),
... ('PGV', numpy.float32, 4)])
>>> build_header(imt_dt)
['PGA:3', 'PGV:4']
>>> gmf_dt = numpy.dtype([('A', imt_dt), ('B', imt_dt),
... ('idx', numpy.uint32)])
>>> build_header(gmf_dt)
['A~PGA:3', 'A~PGV:4', 'B~PGA:3', 'B~PGV:4', 'idx:uint32'] | [
"Convert",
"a",
"numpy",
"nested",
"dtype",
"into",
"a",
"list",
"of",
"strings",
"suitable",
"as",
"header",
"of",
"csv",
"file",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/writers.py#L143-L169 | train | 214,049 |
gem/oq-engine | openquake/commonlib/writers.py | read_composite_array | def read_composite_array(fname, sep=','):
r"""
Convert a CSV file with header into an ArrayWrapper object.
>>> from openquake.baselib.general import gettemp
>>> fname = gettemp('PGA:3,PGV:2,avg:1\n'
... '.1 .2 .3,.4 .5,.6\n')
>>> print(read_composite_array(fname).array) # array of shape (1,)
[([0.1, 0.2, 0.3], [0.4, 0.5], [0.6])]
"""
with open(fname) as f:
header = next(f)
if header.startswith('#'): # the first line is a comment, skip it
attrs = dict(parse_comment(header[1:]))
header = next(f)
else:
attrs = {}
transheader = htranslator.read(header.split(sep))
fields, dtype = parse_header(transheader)
ts_pairs = [] # [(type, shape), ...]
for name in fields:
dt = dtype.fields[name][0]
ts_pairs.append((dt.subdtype[0].type if dt.subdtype else dt.type,
dt.shape))
col_ids = list(range(1, len(ts_pairs) + 1))
num_columns = len(col_ids)
records = []
col, col_id = '', 0
for i, line in enumerate(f, 2):
row = line.split(sep)
if len(row) != num_columns:
raise InvalidFile(
'expected %d columns, found %d in file %s, line %d' %
(num_columns, len(row), fname, i))
try:
record = []
for (ntype, shape), col, col_id in zip(ts_pairs, row, col_ids):
record.append(_cast(col, ntype, shape, i, fname))
records.append(tuple(record))
except Exception as e:
raise InvalidFile(
'Could not cast %r in file %s, line %d, column %d '
'using %s: %s' % (col, fname, i, col_id,
(ntype.__name__,) + shape, e))
return ArrayWrapper(numpy.array(records, dtype), attrs) | python | def read_composite_array(fname, sep=','):
r"""
Convert a CSV file with header into an ArrayWrapper object.
>>> from openquake.baselib.general import gettemp
>>> fname = gettemp('PGA:3,PGV:2,avg:1\n'
... '.1 .2 .3,.4 .5,.6\n')
>>> print(read_composite_array(fname).array) # array of shape (1,)
[([0.1, 0.2, 0.3], [0.4, 0.5], [0.6])]
"""
with open(fname) as f:
header = next(f)
if header.startswith('#'): # the first line is a comment, skip it
attrs = dict(parse_comment(header[1:]))
header = next(f)
else:
attrs = {}
transheader = htranslator.read(header.split(sep))
fields, dtype = parse_header(transheader)
ts_pairs = [] # [(type, shape), ...]
for name in fields:
dt = dtype.fields[name][0]
ts_pairs.append((dt.subdtype[0].type if dt.subdtype else dt.type,
dt.shape))
col_ids = list(range(1, len(ts_pairs) + 1))
num_columns = len(col_ids)
records = []
col, col_id = '', 0
for i, line in enumerate(f, 2):
row = line.split(sep)
if len(row) != num_columns:
raise InvalidFile(
'expected %d columns, found %d in file %s, line %d' %
(num_columns, len(row), fname, i))
try:
record = []
for (ntype, shape), col, col_id in zip(ts_pairs, row, col_ids):
record.append(_cast(col, ntype, shape, i, fname))
records.append(tuple(record))
except Exception as e:
raise InvalidFile(
'Could not cast %r in file %s, line %d, column %d '
'using %s: %s' % (col, fname, i, col_id,
(ntype.__name__,) + shape, e))
return ArrayWrapper(numpy.array(records, dtype), attrs) | [
"def",
"read_composite_array",
"(",
"fname",
",",
"sep",
"=",
"','",
")",
":",
"with",
"open",
"(",
"fname",
")",
"as",
"f",
":",
"header",
"=",
"next",
"(",
"f",
")",
"if",
"header",
".",
"startswith",
"(",
"'#'",
")",
":",
"# the first line is a comm... | r"""
Convert a CSV file with header into an ArrayWrapper object.
>>> from openquake.baselib.general import gettemp
>>> fname = gettemp('PGA:3,PGV:2,avg:1\n'
... '.1 .2 .3,.4 .5,.6\n')
>>> print(read_composite_array(fname).array) # array of shape (1,)
[([0.1, 0.2, 0.3], [0.4, 0.5], [0.6])] | [
"r",
"Convert",
"a",
"CSV",
"file",
"with",
"header",
"into",
"an",
"ArrayWrapper",
"object",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/writers.py#L368-L412 | train | 214,050 |
gem/oq-engine | openquake/commonlib/writers.py | read_array | def read_array(fname, sep=','):
r"""
Convert a CSV file without header into a numpy array of floats.
>>> from openquake.baselib.general import gettemp
>>> print(read_array(gettemp('.1 .2, .3 .4, .5 .6\n')))
[[[0.1 0.2]
[0.3 0.4]
[0.5 0.6]]]
"""
with open(fname) as f:
records = []
for line in f:
row = line.split(sep)
record = [list(map(float, col.split())) for col in row]
records.append(record)
return numpy.array(records) | python | def read_array(fname, sep=','):
r"""
Convert a CSV file without header into a numpy array of floats.
>>> from openquake.baselib.general import gettemp
>>> print(read_array(gettemp('.1 .2, .3 .4, .5 .6\n')))
[[[0.1 0.2]
[0.3 0.4]
[0.5 0.6]]]
"""
with open(fname) as f:
records = []
for line in f:
row = line.split(sep)
record = [list(map(float, col.split())) for col in row]
records.append(record)
return numpy.array(records) | [
"def",
"read_array",
"(",
"fname",
",",
"sep",
"=",
"','",
")",
":",
"with",
"open",
"(",
"fname",
")",
"as",
"f",
":",
"records",
"=",
"[",
"]",
"for",
"line",
"in",
"f",
":",
"row",
"=",
"line",
".",
"split",
"(",
"sep",
")",
"record",
"=",
... | r"""
Convert a CSV file without header into a numpy array of floats.
>>> from openquake.baselib.general import gettemp
>>> print(read_array(gettemp('.1 .2, .3 .4, .5 .6\n')))
[[[0.1 0.2]
[0.3 0.4]
[0.5 0.6]]] | [
"r",
"Convert",
"a",
"CSV",
"file",
"without",
"header",
"into",
"a",
"numpy",
"array",
"of",
"floats",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/writers.py#L416-L432 | train | 214,051 |
gem/oq-engine | openquake/commonlib/writers.py | HeaderTranslator.read | def read(self, names):
"""
Convert names into descriptions
"""
descrs = []
for name in names:
mo = re.match(self.short_regex, name)
if mo:
idx = mo.lastindex # matching group index, starting from 1
suffix = self.suffix[idx - 1].replace(r':\|', ':|')
descrs.append(mo.group(mo.lastindex) + suffix +
name[mo.end():])
else:
descrs.append(name)
return descrs | python | def read(self, names):
"""
Convert names into descriptions
"""
descrs = []
for name in names:
mo = re.match(self.short_regex, name)
if mo:
idx = mo.lastindex # matching group index, starting from 1
suffix = self.suffix[idx - 1].replace(r':\|', ':|')
descrs.append(mo.group(mo.lastindex) + suffix +
name[mo.end():])
else:
descrs.append(name)
return descrs | [
"def",
"read",
"(",
"self",
",",
"names",
")",
":",
"descrs",
"=",
"[",
"]",
"for",
"name",
"in",
"names",
":",
"mo",
"=",
"re",
".",
"match",
"(",
"self",
".",
"short_regex",
",",
"name",
")",
"if",
"mo",
":",
"idx",
"=",
"mo",
".",
"lastindex... | Convert names into descriptions | [
"Convert",
"names",
"into",
"descriptions"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/writers.py#L58-L72 | train | 214,052 |
gem/oq-engine | openquake/commonlib/writers.py | HeaderTranslator.write | def write(self, descrs):
"""
Convert descriptions into names
"""
# example: '(poe-[\d\.]+):float32' -> 'poe-[\d\.]+'
names = []
for descr in descrs:
mo = re.match(self.long_regex, descr)
if mo:
names.append(mo.group(mo.lastindex) + descr[mo.end():])
else:
names.append(descr)
return names | python | def write(self, descrs):
"""
Convert descriptions into names
"""
# example: '(poe-[\d\.]+):float32' -> 'poe-[\d\.]+'
names = []
for descr in descrs:
mo = re.match(self.long_regex, descr)
if mo:
names.append(mo.group(mo.lastindex) + descr[mo.end():])
else:
names.append(descr)
return names | [
"def",
"write",
"(",
"self",
",",
"descrs",
")",
":",
"# example: '(poe-[\\d\\.]+):float32' -> 'poe-[\\d\\.]+'",
"names",
"=",
"[",
"]",
"for",
"descr",
"in",
"descrs",
":",
"mo",
"=",
"re",
".",
"match",
"(",
"self",
".",
"long_regex",
",",
"descr",
")",
... | Convert descriptions into names | [
"Convert",
"descriptions",
"into",
"names"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/writers.py#L74-L86 | train | 214,053 |
gem/oq-engine | openquake/commonlib/writers.py | CsvWriter.save | def save(self, data, fname, header=None):
"""
Save data on fname.
:param data: numpy array or list of lists
:param fname: path name
:param header: header to use
"""
write_csv(fname, data, self.sep, self.fmt, header)
self.fnames.add(getattr(fname, 'name', fname)) | python | def save(self, data, fname, header=None):
"""
Save data on fname.
:param data: numpy array or list of lists
:param fname: path name
:param header: header to use
"""
write_csv(fname, data, self.sep, self.fmt, header)
self.fnames.add(getattr(fname, 'name', fname)) | [
"def",
"save",
"(",
"self",
",",
"data",
",",
"fname",
",",
"header",
"=",
"None",
")",
":",
"write_csv",
"(",
"fname",
",",
"data",
",",
"self",
".",
"sep",
",",
"self",
".",
"fmt",
",",
"header",
")",
"self",
".",
"fnames",
".",
"add",
"(",
"... | Save data on fname.
:param data: numpy array or list of lists
:param fname: path name
:param header: header to use | [
"Save",
"data",
"on",
"fname",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/writers.py#L265-L274 | train | 214,054 |
gem/oq-engine | openquake/commonlib/writers.py | CsvWriter.save_block | def save_block(self, data, dest):
"""
Save data on dest, which is file open in 'a' mode
"""
write_csv(dest, data, self.sep, self.fmt, 'no-header') | python | def save_block(self, data, dest):
"""
Save data on dest, which is file open in 'a' mode
"""
write_csv(dest, data, self.sep, self.fmt, 'no-header') | [
"def",
"save_block",
"(",
"self",
",",
"data",
",",
"dest",
")",
":",
"write_csv",
"(",
"dest",
",",
"data",
",",
"self",
".",
"sep",
",",
"self",
".",
"fmt",
",",
"'no-header'",
")"
] | Save data on dest, which is file open in 'a' mode | [
"Save",
"data",
"on",
"dest",
"which",
"is",
"file",
"open",
"in",
"a",
"mode"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/writers.py#L276-L280 | train | 214,055 |
gem/oq-engine | openquake/hazardlib/gsim/raghukanth_iyengar_2007.py | RaghukanthIyengar2007._get_site_coeffs | def _get_site_coeffs(self, sites, imt):
"""
Extracts correct coefficients for each site from Table 5 on p. 208
for each site.
:raises UserWarning:
If vs30 is below limit for site class D, since "E- and F-type
sites [...] are susceptible for liquefaction and failure." p. 205.
"""
site_classes = self.get_nehrp_classes(sites)
is_bedrock = self.is_bedrock(sites)
if 'E' in site_classes:
msg = ('Site class E and F not supported by %s'
% type(self).__name__)
warnings.warn(msg, UserWarning)
a_1 = np.nan*np.ones_like(sites.vs30)
a_2 = np.nan*np.ones_like(sites.vs30)
sigma = np.nan*np.ones_like(sites.vs30)
for key in self.COEFFS_NEHRP.keys():
indices = (site_classes == key) & ~is_bedrock
a_1[indices] = self.COEFFS_NEHRP[key][imt]['a1']
a_2[indices] = self.COEFFS_NEHRP[key][imt]['a2']
sigma[indices] = self.COEFFS_NEHRP[key][imt]['sigma']
a_1[is_bedrock] = 0.
a_2[is_bedrock] = 0.
sigma[is_bedrock] = 0.
return (a_1, a_2, sigma) | python | def _get_site_coeffs(self, sites, imt):
"""
Extracts correct coefficients for each site from Table 5 on p. 208
for each site.
:raises UserWarning:
If vs30 is below limit for site class D, since "E- and F-type
sites [...] are susceptible for liquefaction and failure." p. 205.
"""
site_classes = self.get_nehrp_classes(sites)
is_bedrock = self.is_bedrock(sites)
if 'E' in site_classes:
msg = ('Site class E and F not supported by %s'
% type(self).__name__)
warnings.warn(msg, UserWarning)
a_1 = np.nan*np.ones_like(sites.vs30)
a_2 = np.nan*np.ones_like(sites.vs30)
sigma = np.nan*np.ones_like(sites.vs30)
for key in self.COEFFS_NEHRP.keys():
indices = (site_classes == key) & ~is_bedrock
a_1[indices] = self.COEFFS_NEHRP[key][imt]['a1']
a_2[indices] = self.COEFFS_NEHRP[key][imt]['a2']
sigma[indices] = self.COEFFS_NEHRP[key][imt]['sigma']
a_1[is_bedrock] = 0.
a_2[is_bedrock] = 0.
sigma[is_bedrock] = 0.
return (a_1, a_2, sigma) | [
"def",
"_get_site_coeffs",
"(",
"self",
",",
"sites",
",",
"imt",
")",
":",
"site_classes",
"=",
"self",
".",
"get_nehrp_classes",
"(",
"sites",
")",
"is_bedrock",
"=",
"self",
".",
"is_bedrock",
"(",
"sites",
")",
"if",
"'E'",
"in",
"site_classes",
":",
... | Extracts correct coefficients for each site from Table 5 on p. 208
for each site.
:raises UserWarning:
If vs30 is below limit for site class D, since "E- and F-type
sites [...] are susceptible for liquefaction and failure." p. 205. | [
"Extracts",
"correct",
"coefficients",
"for",
"each",
"site",
"from",
"Table",
"5",
"on",
"p",
".",
"208",
"for",
"each",
"site",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/raghukanth_iyengar_2007.py#L204-L235 | train | 214,056 |
gem/oq-engine | openquake/hazardlib/gsim/raghukanth_iyengar_2007.py | RaghukanthIyengar2007.get_nehrp_classes | def get_nehrp_classes(self, sites):
"""
Site classification threshholds from Section 4 "Site correction
coefficients" p. 205. Note that site classes E and F are not
supported.
"""
classes = sorted(self.NEHRP_VS30_UPPER_BOUNDS.keys())
bounds = [self.NEHRP_VS30_UPPER_BOUNDS[item] for item in classes]
bounds = np.reshape(np.array(bounds), (-1, 1))
vs30s = np.reshape(sites.vs30, (1, -1))
site_classes = np.choose((vs30s < bounds).sum(axis=0) - 1, classes)
return site_classes.astype('object') | python | def get_nehrp_classes(self, sites):
"""
Site classification threshholds from Section 4 "Site correction
coefficients" p. 205. Note that site classes E and F are not
supported.
"""
classes = sorted(self.NEHRP_VS30_UPPER_BOUNDS.keys())
bounds = [self.NEHRP_VS30_UPPER_BOUNDS[item] for item in classes]
bounds = np.reshape(np.array(bounds), (-1, 1))
vs30s = np.reshape(sites.vs30, (1, -1))
site_classes = np.choose((vs30s < bounds).sum(axis=0) - 1, classes)
return site_classes.astype('object') | [
"def",
"get_nehrp_classes",
"(",
"self",
",",
"sites",
")",
":",
"classes",
"=",
"sorted",
"(",
"self",
".",
"NEHRP_VS30_UPPER_BOUNDS",
".",
"keys",
"(",
")",
")",
"bounds",
"=",
"[",
"self",
".",
"NEHRP_VS30_UPPER_BOUNDS",
"[",
"item",
"]",
"for",
"item",... | Site classification threshholds from Section 4 "Site correction
coefficients" p. 205. Note that site classes E and F are not
supported. | [
"Site",
"classification",
"threshholds",
"from",
"Section",
"4",
"Site",
"correction",
"coefficients",
"p",
".",
"205",
".",
"Note",
"that",
"site",
"classes",
"E",
"and",
"F",
"are",
"not",
"supported",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/raghukanth_iyengar_2007.py#L246-L259 | train | 214,057 |
gem/oq-engine | openquake/server/utils.py | get_valid_users | def get_valid_users(request):
""""
Returns a list of `users` based on groups membership.
Returns a list made of a single user when it is not member of any group.
"""
users = [get_user(request)]
if settings.LOCKDOWN and hasattr(request, 'user'):
if request.user.is_authenticated:
groups = request.user.groups.all()
if groups:
users = list(User.objects.filter(groups__in=groups)
.values_list('username', flat=True))
else:
# This may happen with crafted requests
users = []
return users | python | def get_valid_users(request):
""""
Returns a list of `users` based on groups membership.
Returns a list made of a single user when it is not member of any group.
"""
users = [get_user(request)]
if settings.LOCKDOWN and hasattr(request, 'user'):
if request.user.is_authenticated:
groups = request.user.groups.all()
if groups:
users = list(User.objects.filter(groups__in=groups)
.values_list('username', flat=True))
else:
# This may happen with crafted requests
users = []
return users | [
"def",
"get_valid_users",
"(",
"request",
")",
":",
"users",
"=",
"[",
"get_user",
"(",
"request",
")",
"]",
"if",
"settings",
".",
"LOCKDOWN",
"and",
"hasattr",
"(",
"request",
",",
"'user'",
")",
":",
"if",
"request",
".",
"user",
".",
"is_authenticate... | Returns a list of `users` based on groups membership.
Returns a list made of a single user when it is not member of any group. | [
"Returns",
"a",
"list",
"of",
"users",
"based",
"on",
"groups",
"membership",
".",
"Returns",
"a",
"list",
"made",
"of",
"a",
"single",
"user",
"when",
"it",
"is",
"not",
"member",
"of",
"any",
"group",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/utils.py#L50-L65 | train | 214,058 |
gem/oq-engine | openquake/server/utils.py | get_acl_on | def get_acl_on(request):
"""
Returns `True` if ACL should be honorated, returns otherwise `False`.
"""
acl_on = settings.ACL_ON
if settings.LOCKDOWN and hasattr(request, 'user'):
# ACL is always disabled for superusers
if request.user.is_superuser:
acl_on = False
return acl_on | python | def get_acl_on(request):
"""
Returns `True` if ACL should be honorated, returns otherwise `False`.
"""
acl_on = settings.ACL_ON
if settings.LOCKDOWN and hasattr(request, 'user'):
# ACL is always disabled for superusers
if request.user.is_superuser:
acl_on = False
return acl_on | [
"def",
"get_acl_on",
"(",
"request",
")",
":",
"acl_on",
"=",
"settings",
".",
"ACL_ON",
"if",
"settings",
".",
"LOCKDOWN",
"and",
"hasattr",
"(",
"request",
",",
"'user'",
")",
":",
"# ACL is always disabled for superusers",
"if",
"request",
".",
"user",
".",... | Returns `True` if ACL should be honorated, returns otherwise `False`. | [
"Returns",
"True",
"if",
"ACL",
"should",
"be",
"honorated",
"returns",
"otherwise",
"False",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/utils.py#L68-L77 | train | 214,059 |
gem/oq-engine | openquake/server/utils.py | oq_server_context_processor | def oq_server_context_processor(request):
"""
A custom context processor which allows injection of additional
context variables.
"""
context = {}
context['oq_engine_server_url'] = ('//' +
request.META.get('HTTP_HOST',
'localhost:8800'))
# this context var is also evaluated by the STANDALONE_APPS to identify
# the running environment. Keep it as it is
context['oq_engine_version'] = oqversion
context['server_name'] = settings.SERVER_NAME
return context | python | def oq_server_context_processor(request):
"""
A custom context processor which allows injection of additional
context variables.
"""
context = {}
context['oq_engine_server_url'] = ('//' +
request.META.get('HTTP_HOST',
'localhost:8800'))
# this context var is also evaluated by the STANDALONE_APPS to identify
# the running environment. Keep it as it is
context['oq_engine_version'] = oqversion
context['server_name'] = settings.SERVER_NAME
return context | [
"def",
"oq_server_context_processor",
"(",
"request",
")",
":",
"context",
"=",
"{",
"}",
"context",
"[",
"'oq_engine_server_url'",
"]",
"=",
"(",
"'//'",
"+",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_HOST'",
",",
"'localhost:8800'",
")",
")",
"# this... | A custom context processor which allows injection of additional
context variables. | [
"A",
"custom",
"context",
"processor",
"which",
"allows",
"injection",
"of",
"additional",
"context",
"variables",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/utils.py#L88-L103 | train | 214,060 |
gem/oq-engine | openquake/server/utils.py | check_webserver_running | def check_webserver_running(url="http://localhost:8800", max_retries=30):
"""
Returns True if a given URL is responding within a given timeout.
"""
retry = 0
response = ''
success = False
while response != requests.codes.ok and retry < max_retries:
try:
response = requests.head(url, allow_redirects=True).status_code
success = True
except:
sleep(1)
retry += 1
if not success:
logging.warning('Unable to connect to %s within %s retries'
% (url, max_retries))
return success | python | def check_webserver_running(url="http://localhost:8800", max_retries=30):
"""
Returns True if a given URL is responding within a given timeout.
"""
retry = 0
response = ''
success = False
while response != requests.codes.ok and retry < max_retries:
try:
response = requests.head(url, allow_redirects=True).status_code
success = True
except:
sleep(1)
retry += 1
if not success:
logging.warning('Unable to connect to %s within %s retries'
% (url, max_retries))
return success | [
"def",
"check_webserver_running",
"(",
"url",
"=",
"\"http://localhost:8800\"",
",",
"max_retries",
"=",
"30",
")",
":",
"retry",
"=",
"0",
"response",
"=",
"''",
"success",
"=",
"False",
"while",
"response",
"!=",
"requests",
".",
"codes",
".",
"ok",
"and",... | Returns True if a given URL is responding within a given timeout. | [
"Returns",
"True",
"if",
"a",
"given",
"URL",
"is",
"responding",
"within",
"a",
"given",
"timeout",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/utils.py#L106-L127 | train | 214,061 |
gem/oq-engine | openquake/calculators/export/__init__.py | export_csv | def export_csv(ekey, dstore):
"""
Default csv exporter for arrays stored in the output.hdf5 file
:param ekey: export key
:param dstore: datastore object
:returns: a list with the path of the exported file
"""
name = ekey[0] + '.csv'
try:
array = dstore[ekey[0]].value
except AttributeError:
# this happens if the key correspond to a HDF5 group
return [] # write a custom exporter in this case
if len(array.shape) == 1: # vector
array = array.reshape((len(array), 1))
return [write_csv(dstore.export_path(name), array)] | python | def export_csv(ekey, dstore):
"""
Default csv exporter for arrays stored in the output.hdf5 file
:param ekey: export key
:param dstore: datastore object
:returns: a list with the path of the exported file
"""
name = ekey[0] + '.csv'
try:
array = dstore[ekey[0]].value
except AttributeError:
# this happens if the key correspond to a HDF5 group
return [] # write a custom exporter in this case
if len(array.shape) == 1: # vector
array = array.reshape((len(array), 1))
return [write_csv(dstore.export_path(name), array)] | [
"def",
"export_csv",
"(",
"ekey",
",",
"dstore",
")",
":",
"name",
"=",
"ekey",
"[",
"0",
"]",
"+",
"'.csv'",
"try",
":",
"array",
"=",
"dstore",
"[",
"ekey",
"[",
"0",
"]",
"]",
".",
"value",
"except",
"AttributeError",
":",
"# this happens if the key... | Default csv exporter for arrays stored in the output.hdf5 file
:param ekey: export key
:param dstore: datastore object
:returns: a list with the path of the exported file | [
"Default",
"csv",
"exporter",
"for",
"arrays",
"stored",
"in",
"the",
"output",
".",
"hdf5",
"file"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/__init__.py#L28-L44 | train | 214,062 |
gem/oq-engine | openquake/calculators/export/__init__.py | export_input_zip | def export_input_zip(ekey, dstore):
"""
Export the data in the `input_zip` dataset as a .zip file
"""
dest = dstore.export_path('input.zip')
nbytes = dstore.get_attr('input/zip', 'nbytes')
zbytes = dstore['input/zip'].value
# when reading input_zip some terminating null bytes are truncated (for
# unknown reasons) therefore they must be restored
zbytes += b'\x00' * (nbytes - len(zbytes))
open(dest, 'wb').write(zbytes)
return [dest] | python | def export_input_zip(ekey, dstore):
"""
Export the data in the `input_zip` dataset as a .zip file
"""
dest = dstore.export_path('input.zip')
nbytes = dstore.get_attr('input/zip', 'nbytes')
zbytes = dstore['input/zip'].value
# when reading input_zip some terminating null bytes are truncated (for
# unknown reasons) therefore they must be restored
zbytes += b'\x00' * (nbytes - len(zbytes))
open(dest, 'wb').write(zbytes)
return [dest] | [
"def",
"export_input_zip",
"(",
"ekey",
",",
"dstore",
")",
":",
"dest",
"=",
"dstore",
".",
"export_path",
"(",
"'input.zip'",
")",
"nbytes",
"=",
"dstore",
".",
"get_attr",
"(",
"'input/zip'",
",",
"'nbytes'",
")",
"zbytes",
"=",
"dstore",
"[",
"'input/z... | Export the data in the `input_zip` dataset as a .zip file | [
"Export",
"the",
"data",
"in",
"the",
"input_zip",
"dataset",
"as",
"a",
".",
"zip",
"file"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/__init__.py#L68-L79 | train | 214,063 |
gem/oq-engine | openquake/hmtk/parsers/source_model/nrml04_parser.py | node_to_point_geometry | def node_to_point_geometry(node):
"""
Reads the node and returns the point geometry, upper depth and lower depth
"""
assert "pointGeometry" in node.tag
for subnode in node.nodes:
if "Point" in subnode.tag:
# Position
lon, lat = map(float, subnode.nodes[0].text.split())
point = Point(lon, lat)
elif "upperSeismoDepth" in subnode.tag:
upper_depth = float_(subnode.text)
elif "lowerSeismoDepth" in subnode.tag:
lower_depth = float_(subnode.text)
else:
# Redundent
pass
assert lower_depth > upper_depth
return point, upper_depth, lower_depth | python | def node_to_point_geometry(node):
"""
Reads the node and returns the point geometry, upper depth and lower depth
"""
assert "pointGeometry" in node.tag
for subnode in node.nodes:
if "Point" in subnode.tag:
# Position
lon, lat = map(float, subnode.nodes[0].text.split())
point = Point(lon, lat)
elif "upperSeismoDepth" in subnode.tag:
upper_depth = float_(subnode.text)
elif "lowerSeismoDepth" in subnode.tag:
lower_depth = float_(subnode.text)
else:
# Redundent
pass
assert lower_depth > upper_depth
return point, upper_depth, lower_depth | [
"def",
"node_to_point_geometry",
"(",
"node",
")",
":",
"assert",
"\"pointGeometry\"",
"in",
"node",
".",
"tag",
"for",
"subnode",
"in",
"node",
".",
"nodes",
":",
"if",
"\"Point\"",
"in",
"subnode",
".",
"tag",
":",
"# Position",
"lon",
",",
"lat",
"=",
... | Reads the node and returns the point geometry, upper depth and lower depth | [
"Reads",
"the",
"node",
"and",
"returns",
"the",
"point",
"geometry",
"upper",
"depth",
"and",
"lower",
"depth"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/source_model/nrml04_parser.py#L125-L143 | train | 214,064 |
gem/oq-engine | openquake/hmtk/parsers/source_model/nrml04_parser.py | node_to_area_geometry | def node_to_area_geometry(node):
"""
Reads an area geometry node and returns the polygon, upper depth and lower
depth
"""
assert "areaGeometry" in node.tag
for subnode in node.nodes:
if "Polygon" in subnode.tag:
crds = [float(x)
for x in subnode.nodes[0].nodes[0].nodes[0].text.split()]
polygon = Polygon([Point(crds[iloc], crds[iloc + 1])
for iloc in range(0, len(crds), 2)])
elif "upperSeismoDepth" in subnode.tag:
upper_depth = float_(subnode.text)
elif "lowerSeismoDepth" in subnode.tag:
lower_depth = float_(subnode.text)
else:
# Redundent
pass
assert lower_depth > upper_depth
return polygon, upper_depth, lower_depth | python | def node_to_area_geometry(node):
"""
Reads an area geometry node and returns the polygon, upper depth and lower
depth
"""
assert "areaGeometry" in node.tag
for subnode in node.nodes:
if "Polygon" in subnode.tag:
crds = [float(x)
for x in subnode.nodes[0].nodes[0].nodes[0].text.split()]
polygon = Polygon([Point(crds[iloc], crds[iloc + 1])
for iloc in range(0, len(crds), 2)])
elif "upperSeismoDepth" in subnode.tag:
upper_depth = float_(subnode.text)
elif "lowerSeismoDepth" in subnode.tag:
lower_depth = float_(subnode.text)
else:
# Redundent
pass
assert lower_depth > upper_depth
return polygon, upper_depth, lower_depth | [
"def",
"node_to_area_geometry",
"(",
"node",
")",
":",
"assert",
"\"areaGeometry\"",
"in",
"node",
".",
"tag",
"for",
"subnode",
"in",
"node",
".",
"nodes",
":",
"if",
"\"Polygon\"",
"in",
"subnode",
".",
"tag",
":",
"crds",
"=",
"[",
"float",
"(",
"x",
... | Reads an area geometry node and returns the polygon, upper depth and lower
depth | [
"Reads",
"an",
"area",
"geometry",
"node",
"and",
"returns",
"the",
"polygon",
"upper",
"depth",
"and",
"lower",
"depth"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/source_model/nrml04_parser.py#L146-L166 | train | 214,065 |
gem/oq-engine | openquake/hmtk/parsers/source_model/nrml04_parser.py | node_to_simple_fault_geometry | def node_to_simple_fault_geometry(node):
"""
Reads a simple fault geometry node and returns an OpenQuake representation
:returns:
trace - Trace of fault as instance
"""
assert "simpleFaultGeometry" in node.tag
for subnode in node.nodes:
if "LineString" in subnode.tag:
trace = linestring_node_to_line(subnode, with_depth=False)
elif "dip" in subnode.tag:
dip = float(subnode.text)
elif "upperSeismoDepth" in subnode.tag:
upper_depth = float(subnode.text)
elif "lowerSeismoDepth" in subnode.tag:
lower_depth = float(subnode.text)
else:
# Redundent
pass
assert lower_depth > upper_depth
return trace, dip, upper_depth, lower_depth | python | def node_to_simple_fault_geometry(node):
"""
Reads a simple fault geometry node and returns an OpenQuake representation
:returns:
trace - Trace of fault as instance
"""
assert "simpleFaultGeometry" in node.tag
for subnode in node.nodes:
if "LineString" in subnode.tag:
trace = linestring_node_to_line(subnode, with_depth=False)
elif "dip" in subnode.tag:
dip = float(subnode.text)
elif "upperSeismoDepth" in subnode.tag:
upper_depth = float(subnode.text)
elif "lowerSeismoDepth" in subnode.tag:
lower_depth = float(subnode.text)
else:
# Redundent
pass
assert lower_depth > upper_depth
return trace, dip, upper_depth, lower_depth | [
"def",
"node_to_simple_fault_geometry",
"(",
"node",
")",
":",
"assert",
"\"simpleFaultGeometry\"",
"in",
"node",
".",
"tag",
"for",
"subnode",
"in",
"node",
".",
"nodes",
":",
"if",
"\"LineString\"",
"in",
"subnode",
".",
"tag",
":",
"trace",
"=",
"linestring... | Reads a simple fault geometry node and returns an OpenQuake representation
:returns:
trace - Trace of fault as instance | [
"Reads",
"a",
"simple",
"fault",
"geometry",
"node",
"and",
"returns",
"an",
"OpenQuake",
"representation"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/source_model/nrml04_parser.py#L169-L190 | train | 214,066 |
gem/oq-engine | openquake/hmtk/parsers/source_model/nrml04_parser.py | node_to_complex_fault_geometry | def node_to_complex_fault_geometry(node):
"""
Reads a complex fault geometry node and returns an
"""
assert "complexFaultGeometry" in node.tag
intermediate_edges = []
for subnode in node.nodes:
if "faultTopEdge" in subnode.tag:
top_edge = linestring_node_to_line(subnode.nodes[0],
with_depth=True)
elif "intermediateEdge" in subnode.tag:
int_edge = linestring_node_to_line(subnode.nodes[0],
with_depth=True)
intermediate_edges.append(int_edge)
elif "faultBottomEdge" in subnode.tag:
bottom_edge = linestring_node_to_line(subnode.nodes[0],
with_depth=True)
else:
# Redundent
pass
return [top_edge] + intermediate_edges + [bottom_edge] | python | def node_to_complex_fault_geometry(node):
"""
Reads a complex fault geometry node and returns an
"""
assert "complexFaultGeometry" in node.tag
intermediate_edges = []
for subnode in node.nodes:
if "faultTopEdge" in subnode.tag:
top_edge = linestring_node_to_line(subnode.nodes[0],
with_depth=True)
elif "intermediateEdge" in subnode.tag:
int_edge = linestring_node_to_line(subnode.nodes[0],
with_depth=True)
intermediate_edges.append(int_edge)
elif "faultBottomEdge" in subnode.tag:
bottom_edge = linestring_node_to_line(subnode.nodes[0],
with_depth=True)
else:
# Redundent
pass
return [top_edge] + intermediate_edges + [bottom_edge] | [
"def",
"node_to_complex_fault_geometry",
"(",
"node",
")",
":",
"assert",
"\"complexFaultGeometry\"",
"in",
"node",
".",
"tag",
"intermediate_edges",
"=",
"[",
"]",
"for",
"subnode",
"in",
"node",
".",
"nodes",
":",
"if",
"\"faultTopEdge\"",
"in",
"subnode",
"."... | Reads a complex fault geometry node and returns an | [
"Reads",
"a",
"complex",
"fault",
"geometry",
"node",
"and",
"returns",
"an"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/source_model/nrml04_parser.py#L193-L213 | train | 214,067 |
gem/oq-engine | openquake/hmtk/parsers/source_model/nrml04_parser.py | node_to_mfd | def node_to_mfd(node, taglist):
"""
Reads the node to return a magnitude frequency distribution
"""
if "incrementalMFD" in taglist:
mfd = node_to_evenly_discretized(
node.nodes[taglist.index("incrementalMFD")])
elif "truncGutenbergRichterMFD" in taglist:
mfd = node_to_truncated_gr(
node.nodes[taglist.index("truncGutenbergRichterMFD")])
else:
mfd = None
return mfd | python | def node_to_mfd(node, taglist):
"""
Reads the node to return a magnitude frequency distribution
"""
if "incrementalMFD" in taglist:
mfd = node_to_evenly_discretized(
node.nodes[taglist.index("incrementalMFD")])
elif "truncGutenbergRichterMFD" in taglist:
mfd = node_to_truncated_gr(
node.nodes[taglist.index("truncGutenbergRichterMFD")])
else:
mfd = None
return mfd | [
"def",
"node_to_mfd",
"(",
"node",
",",
"taglist",
")",
":",
"if",
"\"incrementalMFD\"",
"in",
"taglist",
":",
"mfd",
"=",
"node_to_evenly_discretized",
"(",
"node",
".",
"nodes",
"[",
"taglist",
".",
"index",
"(",
"\"incrementalMFD\"",
")",
"]",
")",
"elif"... | Reads the node to return a magnitude frequency distribution | [
"Reads",
"the",
"node",
"to",
"return",
"a",
"magnitude",
"frequency",
"distribution"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/source_model/nrml04_parser.py#L259-L271 | train | 214,068 |
gem/oq-engine | openquake/hmtk/parsers/source_model/nrml04_parser.py | node_to_nodal_planes | def node_to_nodal_planes(node):
"""
Parses the nodal plane distribution to a PMF
"""
if not len(node):
return None
npd_pmf = []
for plane in node.nodes:
if not all(plane.attrib[key] for key in plane.attrib):
# One plane fails - return None
return None
npd = NodalPlane(float(plane.attrib["strike"]),
float(plane.attrib["dip"]),
float(plane.attrib["rake"]))
npd_pmf.append((float(plane.attrib["probability"]), npd))
return PMF(npd_pmf) | python | def node_to_nodal_planes(node):
"""
Parses the nodal plane distribution to a PMF
"""
if not len(node):
return None
npd_pmf = []
for plane in node.nodes:
if not all(plane.attrib[key] for key in plane.attrib):
# One plane fails - return None
return None
npd = NodalPlane(float(plane.attrib["strike"]),
float(plane.attrib["dip"]),
float(plane.attrib["rake"]))
npd_pmf.append((float(plane.attrib["probability"]), npd))
return PMF(npd_pmf) | [
"def",
"node_to_nodal_planes",
"(",
"node",
")",
":",
"if",
"not",
"len",
"(",
"node",
")",
":",
"return",
"None",
"npd_pmf",
"=",
"[",
"]",
"for",
"plane",
"in",
"node",
".",
"nodes",
":",
"if",
"not",
"all",
"(",
"plane",
".",
"attrib",
"[",
"key... | Parses the nodal plane distribution to a PMF | [
"Parses",
"the",
"nodal",
"plane",
"distribution",
"to",
"a",
"PMF"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/source_model/nrml04_parser.py#L274-L289 | train | 214,069 |
gem/oq-engine | openquake/hmtk/parsers/source_model/nrml04_parser.py | node_to_hdd | def node_to_hdd(node):
"""
Parses the node to a hpyocentral depth distribution PMF
"""
if not len(node):
return None
hdds = []
for subnode in node.nodes:
if not all([subnode.attrib[key] for key in ["depth", "probability"]]):
return None
hdds.append((float(subnode.attrib["probability"]),
float(subnode.attrib["depth"])))
return PMF(hdds) | python | def node_to_hdd(node):
"""
Parses the node to a hpyocentral depth distribution PMF
"""
if not len(node):
return None
hdds = []
for subnode in node.nodes:
if not all([subnode.attrib[key] for key in ["depth", "probability"]]):
return None
hdds.append((float(subnode.attrib["probability"]),
float(subnode.attrib["depth"])))
return PMF(hdds) | [
"def",
"node_to_hdd",
"(",
"node",
")",
":",
"if",
"not",
"len",
"(",
"node",
")",
":",
"return",
"None",
"hdds",
"=",
"[",
"]",
"for",
"subnode",
"in",
"node",
".",
"nodes",
":",
"if",
"not",
"all",
"(",
"[",
"subnode",
".",
"attrib",
"[",
"key"... | Parses the node to a hpyocentral depth distribution PMF | [
"Parses",
"the",
"node",
"to",
"a",
"hpyocentral",
"depth",
"distribution",
"PMF"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/source_model/nrml04_parser.py#L292-L304 | train | 214,070 |
gem/oq-engine | openquake/hazardlib/gsim/atkinson_boore_2003.py | AtkinsonBoore2003SInter._compute_mean | def _compute_mean(self, C, g, mag, hypo_depth, rrup, vs30, pga_rock, imt):
"""
Compute mean according to equation 1, page 1706.
"""
if hypo_depth > 100:
hypo_depth = 100
delta = 0.00724 * 10 ** (0.507 * mag)
R = np.sqrt(rrup ** 2 + delta ** 2)
s_amp = self._compute_soil_amplification(C, vs30, pga_rock, imt)
mean = (
# 1st term
C['c1'] + C['c2'] * mag +
# 2nd term
C['c3'] * hypo_depth +
# 3rd term
C['c4'] * R -
# 4th term
g * np.log10(R) +
# 5th, 6th and 7th terms
s_amp
)
return mean | python | def _compute_mean(self, C, g, mag, hypo_depth, rrup, vs30, pga_rock, imt):
"""
Compute mean according to equation 1, page 1706.
"""
if hypo_depth > 100:
hypo_depth = 100
delta = 0.00724 * 10 ** (0.507 * mag)
R = np.sqrt(rrup ** 2 + delta ** 2)
s_amp = self._compute_soil_amplification(C, vs30, pga_rock, imt)
mean = (
# 1st term
C['c1'] + C['c2'] * mag +
# 2nd term
C['c3'] * hypo_depth +
# 3rd term
C['c4'] * R -
# 4th term
g * np.log10(R) +
# 5th, 6th and 7th terms
s_amp
)
return mean | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"g",
",",
"mag",
",",
"hypo_depth",
",",
"rrup",
",",
"vs30",
",",
"pga_rock",
",",
"imt",
")",
":",
"if",
"hypo_depth",
">",
"100",
":",
"hypo_depth",
"=",
"100",
"delta",
"=",
"0.00724",
"*",
"1... | Compute mean according to equation 1, page 1706. | [
"Compute",
"mean",
"according",
"to",
"equation",
"1",
"page",
"1706",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/atkinson_boore_2003.py#L149-L173 | train | 214,071 |
gem/oq-engine | openquake/hazardlib/gsim/atkinson_boore_2003.py | AtkinsonBoore2003SInter._compute_soil_linear_factor | def _compute_soil_linear_factor(cls, pga_rock, imt):
"""
Compute soil linear factor as explained in paragraph 'Functional
Form', page 1706.
"""
if imt.period >= 1:
return np.ones_like(pga_rock)
else:
sl = np.zeros_like(pga_rock)
pga_between_100_500 = (pga_rock > 100) & (pga_rock < 500)
pga_greater_equal_500 = pga_rock >= 500
is_SA_between_05_1 = 0.5 < imt.period < 1
is_SA_less_equal_05 = imt.period <= 0.5
if is_SA_between_05_1:
sl[pga_between_100_500] = (1 - (1. / imt.period - 1) *
(pga_rock[pga_between_100_500] -
100) / 400)
sl[pga_greater_equal_500] = 1 - (1. / imt.period - 1)
if is_SA_less_equal_05 or imt.period == 0:
sl[pga_between_100_500] = (1 - (pga_rock[pga_between_100_500] -
100) / 400)
sl[pga_rock <= 100] = 1
return sl | python | def _compute_soil_linear_factor(cls, pga_rock, imt):
"""
Compute soil linear factor as explained in paragraph 'Functional
Form', page 1706.
"""
if imt.period >= 1:
return np.ones_like(pga_rock)
else:
sl = np.zeros_like(pga_rock)
pga_between_100_500 = (pga_rock > 100) & (pga_rock < 500)
pga_greater_equal_500 = pga_rock >= 500
is_SA_between_05_1 = 0.5 < imt.period < 1
is_SA_less_equal_05 = imt.period <= 0.5
if is_SA_between_05_1:
sl[pga_between_100_500] = (1 - (1. / imt.period - 1) *
(pga_rock[pga_between_100_500] -
100) / 400)
sl[pga_greater_equal_500] = 1 - (1. / imt.period - 1)
if is_SA_less_equal_05 or imt.period == 0:
sl[pga_between_100_500] = (1 - (pga_rock[pga_between_100_500] -
100) / 400)
sl[pga_rock <= 100] = 1
return sl | [
"def",
"_compute_soil_linear_factor",
"(",
"cls",
",",
"pga_rock",
",",
"imt",
")",
":",
"if",
"imt",
".",
"period",
">=",
"1",
":",
"return",
"np",
".",
"ones_like",
"(",
"pga_rock",
")",
"else",
":",
"sl",
"=",
"np",
".",
"zeros_like",
"(",
"pga_rock... | Compute soil linear factor as explained in paragraph 'Functional
Form', page 1706. | [
"Compute",
"soil",
"linear",
"factor",
"as",
"explained",
"in",
"paragraph",
"Functional",
"Form",
"page",
"1706",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/atkinson_boore_2003.py#L203-L232 | train | 214,072 |
gem/oq-engine | openquake/hazardlib/gsim/mcverry_2006.py | McVerry2006Asc._get_stddevs | def _get_stddevs(self, C, mag, stddev_types, sites):
"""
Return standard deviation as defined on page 29 in
equation 8a,b,c and 9.
"""
num_sites = sites.vs30.size
sigma_intra = np.zeros(num_sites)
# interevent stddev
tau = sigma_intra + C['tau']
# intraevent std (equations 8a-8c page 29)
if mag < 5.0:
sigma_intra += C['sigmaM6'] - C['sigSlope']
elif 5.0 <= mag < 7.0:
sigma_intra += C['sigmaM6'] + C['sigSlope'] * (mag - 6)
else:
sigma_intra += C['sigmaM6'] + C['sigSlope']
std = []
for stddev_type in stddev_types:
if stddev_type == const.StdDev.TOTAL:
# equation 9 page 29
std += [np.sqrt(sigma_intra**2 + tau**2)]
elif stddev_type == const.StdDev.INTRA_EVENT:
std.append(sigma_intra)
elif stddev_type == const.StdDev.INTER_EVENT:
std.append(tau)
return std | python | def _get_stddevs(self, C, mag, stddev_types, sites):
"""
Return standard deviation as defined on page 29 in
equation 8a,b,c and 9.
"""
num_sites = sites.vs30.size
sigma_intra = np.zeros(num_sites)
# interevent stddev
tau = sigma_intra + C['tau']
# intraevent std (equations 8a-8c page 29)
if mag < 5.0:
sigma_intra += C['sigmaM6'] - C['sigSlope']
elif 5.0 <= mag < 7.0:
sigma_intra += C['sigmaM6'] + C['sigSlope'] * (mag - 6)
else:
sigma_intra += C['sigmaM6'] + C['sigSlope']
std = []
for stddev_type in stddev_types:
if stddev_type == const.StdDev.TOTAL:
# equation 9 page 29
std += [np.sqrt(sigma_intra**2 + tau**2)]
elif stddev_type == const.StdDev.INTRA_EVENT:
std.append(sigma_intra)
elif stddev_type == const.StdDev.INTER_EVENT:
std.append(tau)
return std | [
"def",
"_get_stddevs",
"(",
"self",
",",
"C",
",",
"mag",
",",
"stddev_types",
",",
"sites",
")",
":",
"num_sites",
"=",
"sites",
".",
"vs30",
".",
"size",
"sigma_intra",
"=",
"np",
".",
"zeros",
"(",
"num_sites",
")",
"# interevent stddev",
"tau",
"=",
... | Return standard deviation as defined on page 29 in
equation 8a,b,c and 9. | [
"Return",
"standard",
"deviation",
"as",
"defined",
"on",
"page",
"29",
"in",
"equation",
"8a",
"b",
"c",
"and",
"9",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/mcverry_2006.py#L218-L248 | train | 214,073 |
gem/oq-engine | openquake/hazardlib/gsim/mcverry_2006.py | McVerry2006AscSC._get_deltas | def _get_deltas(self, sites):
"""
Return delta's for equation 4
delta_C = 1 for site class C, 0 otherwise
delta_D = 1 for site class D, 0 otherwise
"""
siteclass = sites.siteclass
delta_C = np.zeros_like(siteclass, dtype=np.float)
delta_C[siteclass == b'C'] = 1
delta_D = np.zeros_like(siteclass, dtype=np.float)
delta_D[siteclass == b'D'] = 1
return delta_C, delta_D | python | def _get_deltas(self, sites):
"""
Return delta's for equation 4
delta_C = 1 for site class C, 0 otherwise
delta_D = 1 for site class D, 0 otherwise
"""
siteclass = sites.siteclass
delta_C = np.zeros_like(siteclass, dtype=np.float)
delta_C[siteclass == b'C'] = 1
delta_D = np.zeros_like(siteclass, dtype=np.float)
delta_D[siteclass == b'D'] = 1
return delta_C, delta_D | [
"def",
"_get_deltas",
"(",
"self",
",",
"sites",
")",
":",
"siteclass",
"=",
"sites",
".",
"siteclass",
"delta_C",
"=",
"np",
".",
"zeros_like",
"(",
"siteclass",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"delta_C",
"[",
"siteclass",
"==",
"b'C'",
"]... | Return delta's for equation 4
delta_C = 1 for site class C, 0 otherwise
delta_D = 1 for site class D, 0 otherwise | [
"Return",
"delta",
"s",
"for",
"equation",
"4",
"delta_C",
"=",
"1",
"for",
"site",
"class",
"C",
"0",
"otherwise",
"delta_D",
"=",
"1",
"for",
"site",
"class",
"D",
"0",
"otherwise"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/mcverry_2006.py#L546-L559 | train | 214,074 |
gem/oq-engine | openquake/risklib/riskinput.py | CompositeRiskModel.gen_outputs | def gen_outputs(self, riskinput, monitor, epspath=None, hazard=None):
"""
Group the assets per taxonomy and compute the outputs by using the
underlying riskmodels. Yield one output per realization.
:param riskinput: a RiskInput instance
:param monitor: a monitor object used to measure the performance
"""
self.monitor = monitor
hazard_getter = riskinput.hazard_getter
if hazard is None:
with monitor('getting hazard'):
hazard_getter.init()
hazard = hazard_getter.get_hazard()
sids = hazard_getter.sids
assert len(sids) == 1
with monitor('computing risk', measuremem=False):
# this approach is slow for event_based_risk since a lot of
# small arrays are passed (one per realization) instead of
# a long array with all realizations; ebrisk does the right
# thing since it calls get_output directly
assets_by_taxo = get_assets_by_taxo(riskinput.assets, epspath)
for rlzi, haz in sorted(hazard[sids[0]].items()):
out = self.get_output(assets_by_taxo, haz, rlzi)
yield out | python | def gen_outputs(self, riskinput, monitor, epspath=None, hazard=None):
"""
Group the assets per taxonomy and compute the outputs by using the
underlying riskmodels. Yield one output per realization.
:param riskinput: a RiskInput instance
:param monitor: a monitor object used to measure the performance
"""
self.monitor = monitor
hazard_getter = riskinput.hazard_getter
if hazard is None:
with monitor('getting hazard'):
hazard_getter.init()
hazard = hazard_getter.get_hazard()
sids = hazard_getter.sids
assert len(sids) == 1
with monitor('computing risk', measuremem=False):
# this approach is slow for event_based_risk since a lot of
# small arrays are passed (one per realization) instead of
# a long array with all realizations; ebrisk does the right
# thing since it calls get_output directly
assets_by_taxo = get_assets_by_taxo(riskinput.assets, epspath)
for rlzi, haz in sorted(hazard[sids[0]].items()):
out = self.get_output(assets_by_taxo, haz, rlzi)
yield out | [
"def",
"gen_outputs",
"(",
"self",
",",
"riskinput",
",",
"monitor",
",",
"epspath",
"=",
"None",
",",
"hazard",
"=",
"None",
")",
":",
"self",
".",
"monitor",
"=",
"monitor",
"hazard_getter",
"=",
"riskinput",
".",
"hazard_getter",
"if",
"hazard",
"is",
... | Group the assets per taxonomy and compute the outputs by using the
underlying riskmodels. Yield one output per realization.
:param riskinput: a RiskInput instance
:param monitor: a monitor object used to measure the performance | [
"Group",
"the",
"assets",
"per",
"taxonomy",
"and",
"compute",
"the",
"outputs",
"by",
"using",
"the",
"underlying",
"riskmodels",
".",
"Yield",
"one",
"output",
"per",
"realization",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/riskinput.py#L347-L371 | train | 214,075 |
gem/oq-engine | openquake/hmtk/faults/mfd/__init__.py | get_available_mfds | def get_available_mfds():
'''
Returns an ordered dictionary with the available GSIM classes
keyed by class name
'''
mfds = {}
for fname in os.listdir(os.path.dirname(__file__)):
if fname.endswith('.py'):
modname, _ext = os.path.splitext(fname)
mod = importlib.import_module(
'openquake.hmtk.faults.mfd.' + modname)
for cls in mod.__dict__.values():
if inspect.isclass(cls) and issubclass(cls, BaseMFDfromSlip):
mfds[cls.__name__] = cls
return dict((k, mfds[k]) for k in sorted(mfds)) | python | def get_available_mfds():
'''
Returns an ordered dictionary with the available GSIM classes
keyed by class name
'''
mfds = {}
for fname in os.listdir(os.path.dirname(__file__)):
if fname.endswith('.py'):
modname, _ext = os.path.splitext(fname)
mod = importlib.import_module(
'openquake.hmtk.faults.mfd.' + modname)
for cls in mod.__dict__.values():
if inspect.isclass(cls) and issubclass(cls, BaseMFDfromSlip):
mfds[cls.__name__] = cls
return dict((k, mfds[k]) for k in sorted(mfds)) | [
"def",
"get_available_mfds",
"(",
")",
":",
"mfds",
"=",
"{",
"}",
"for",
"fname",
"in",
"os",
".",
"listdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
":",
"if",
"fname",
".",
"endswith",
"(",
"'.py'",
")",
":",
"modname"... | Returns an ordered dictionary with the available GSIM classes
keyed by class name | [
"Returns",
"an",
"ordered",
"dictionary",
"with",
"the",
"available",
"GSIM",
"classes",
"keyed",
"by",
"class",
"name"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/mfd/__init__.py#L25-L39 | train | 214,076 |
gem/oq-engine | openquake/hmtk/seismicity/max_magnitude/kijko_sellevol_fixed_b.py | check_config | def check_config(config, data):
'''Checks that the config file contains all required parameters
:param dict config:
Configuration file
:returns:
Configuration file with all correct parameters
'''
if 'tolerance' not in config.keys() or not config['tolerance']:
config['tolerance'] = 1E-5
if not config.get('maximum_iterations', None):
config['maximum_iterations'] = 1000
mmin_obs = np.min(data['magnitude'])
if config.get('input_mmin', 0) < mmin_obs:
config['input_mmin'] = mmin_obs
if fabs(config['b-value']) < 1E-7:
config['b-value'] = 1E-7
return config | python | def check_config(config, data):
'''Checks that the config file contains all required parameters
:param dict config:
Configuration file
:returns:
Configuration file with all correct parameters
'''
if 'tolerance' not in config.keys() or not config['tolerance']:
config['tolerance'] = 1E-5
if not config.get('maximum_iterations', None):
config['maximum_iterations'] = 1000
mmin_obs = np.min(data['magnitude'])
if config.get('input_mmin', 0) < mmin_obs:
config['input_mmin'] = mmin_obs
if fabs(config['b-value']) < 1E-7:
config['b-value'] = 1E-7
return config | [
"def",
"check_config",
"(",
"config",
",",
"data",
")",
":",
"if",
"'tolerance'",
"not",
"in",
"config",
".",
"keys",
"(",
")",
"or",
"not",
"config",
"[",
"'tolerance'",
"]",
":",
"config",
"[",
"'tolerance'",
"]",
"=",
"1E-5",
"if",
"not",
"config",
... | Checks that the config file contains all required parameters
:param dict config:
Configuration file
:returns:
Configuration file with all correct parameters | [
"Checks",
"that",
"the",
"config",
"file",
"contains",
"all",
"required",
"parameters"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/max_magnitude/kijko_sellevol_fixed_b.py#L61-L83 | train | 214,077 |
gem/oq-engine | openquake/hazardlib/valid.py | disagg_outputs | def disagg_outputs(value):
"""
Validate disaggregation outputs. For instance
>>> disagg_outputs('TRT Mag_Dist')
['TRT', 'Mag_Dist']
>>> disagg_outputs('TRT, Mag_Dist')
['TRT', 'Mag_Dist']
"""
values = value.replace(',', ' ').split()
for val in values:
if val not in disagg.pmf_map:
raise ValueError('Invalid disagg output: %s' % val)
return values | python | def disagg_outputs(value):
"""
Validate disaggregation outputs. For instance
>>> disagg_outputs('TRT Mag_Dist')
['TRT', 'Mag_Dist']
>>> disagg_outputs('TRT, Mag_Dist')
['TRT', 'Mag_Dist']
"""
values = value.replace(',', ' ').split()
for val in values:
if val not in disagg.pmf_map:
raise ValueError('Invalid disagg output: %s' % val)
return values | [
"def",
"disagg_outputs",
"(",
"value",
")",
":",
"values",
"=",
"value",
".",
"replace",
"(",
"','",
",",
"' '",
")",
".",
"split",
"(",
")",
"for",
"val",
"in",
"values",
":",
"if",
"val",
"not",
"in",
"disagg",
".",
"pmf_map",
":",
"raise",
"Valu... | Validate disaggregation outputs. For instance
>>> disagg_outputs('TRT Mag_Dist')
['TRT', 'Mag_Dist']
>>> disagg_outputs('TRT, Mag_Dist')
['TRT', 'Mag_Dist'] | [
"Validate",
"disaggregation",
"outputs",
".",
"For",
"instance"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/valid.py#L43-L56 | train | 214,078 |
gem/oq-engine | openquake/hazardlib/valid.py | gsim | def gsim(value):
"""
Convert a string in TOML format into a GSIM instance
>>> gsim('[BooreAtkinson2011]')
[BooreAtkinson2011]
"""
if not value.startswith('['): # assume the GSIM name
value = '[%s]' % value
[(gsim_name, kwargs)] = toml.loads(value).items()
minimum_distance = float(kwargs.pop('minimum_distance', 0))
if gsim_name == 'FromFile':
return FromFile()
try:
gsim_class = registry[gsim_name]
except KeyError:
raise ValueError('Unknown GSIM: %s' % gsim_name)
gs = gsim_class(**kwargs)
gs._toml = '\n'.join(line.strip() for line in value.splitlines())
gs.minimum_distance = minimum_distance
return gs | python | def gsim(value):
"""
Convert a string in TOML format into a GSIM instance
>>> gsim('[BooreAtkinson2011]')
[BooreAtkinson2011]
"""
if not value.startswith('['): # assume the GSIM name
value = '[%s]' % value
[(gsim_name, kwargs)] = toml.loads(value).items()
minimum_distance = float(kwargs.pop('minimum_distance', 0))
if gsim_name == 'FromFile':
return FromFile()
try:
gsim_class = registry[gsim_name]
except KeyError:
raise ValueError('Unknown GSIM: %s' % gsim_name)
gs = gsim_class(**kwargs)
gs._toml = '\n'.join(line.strip() for line in value.splitlines())
gs.minimum_distance = minimum_distance
return gs | [
"def",
"gsim",
"(",
"value",
")",
":",
"if",
"not",
"value",
".",
"startswith",
"(",
"'['",
")",
":",
"# assume the GSIM name",
"value",
"=",
"'[%s]'",
"%",
"value",
"[",
"(",
"gsim_name",
",",
"kwargs",
")",
"]",
"=",
"toml",
".",
"loads",
"(",
"val... | Convert a string in TOML format into a GSIM instance
>>> gsim('[BooreAtkinson2011]')
[BooreAtkinson2011] | [
"Convert",
"a",
"string",
"in",
"TOML",
"format",
"into",
"a",
"GSIM",
"instance"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/valid.py#L76-L96 | train | 214,079 |
gem/oq-engine | openquake/hazardlib/valid.py | compose | def compose(*validators):
"""
Implement composition of validators. For instance
>>> utf8_not_empty = compose(utf8, not_empty)
"""
def composed_validator(value):
out = value
for validator in reversed(validators):
out = validator(out)
return out
composed_validator.__name__ = 'compose(%s)' % ','.join(
val.__name__ for val in validators)
return composed_validator | python | def compose(*validators):
"""
Implement composition of validators. For instance
>>> utf8_not_empty = compose(utf8, not_empty)
"""
def composed_validator(value):
out = value
for validator in reversed(validators):
out = validator(out)
return out
composed_validator.__name__ = 'compose(%s)' % ','.join(
val.__name__ for val in validators)
return composed_validator | [
"def",
"compose",
"(",
"*",
"validators",
")",
":",
"def",
"composed_validator",
"(",
"value",
")",
":",
"out",
"=",
"value",
"for",
"validator",
"in",
"reversed",
"(",
"validators",
")",
":",
"out",
"=",
"validator",
"(",
"out",
")",
"return",
"out",
... | Implement composition of validators. For instance
>>> utf8_not_empty = compose(utf8, not_empty) | [
"Implement",
"composition",
"of",
"validators",
".",
"For",
"instance"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/valid.py#L107-L120 | train | 214,080 |
gem/oq-engine | openquake/hazardlib/valid.py | utf8 | def utf8(value):
r"""
Check that the string is UTF-8. Returns an encode bytestring.
>>> utf8(b'\xe0') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Not UTF-8: ...
"""
try:
if isinstance(value, bytes):
return value.decode('utf-8')
else:
return value
except Exception:
raise ValueError('Not UTF-8: %r' % value) | python | def utf8(value):
r"""
Check that the string is UTF-8. Returns an encode bytestring.
>>> utf8(b'\xe0') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Not UTF-8: ...
"""
try:
if isinstance(value, bytes):
return value.decode('utf-8')
else:
return value
except Exception:
raise ValueError('Not UTF-8: %r' % value) | [
"def",
"utf8",
"(",
"value",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"return",
"value",
".",
"decode",
"(",
"'utf-8'",
")",
"else",
":",
"return",
"value",
"except",
"Exception",
":",
"raise",
"ValueError",
"(",
... | r"""
Check that the string is UTF-8. Returns an encode bytestring.
>>> utf8(b'\xe0') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Not UTF-8: ... | [
"r",
"Check",
"that",
"the",
"string",
"is",
"UTF",
"-",
"8",
".",
"Returns",
"an",
"encode",
"bytestring",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/valid.py#L310-L325 | train | 214,081 |
gem/oq-engine | openquake/hazardlib/valid.py | coordinates | def coordinates(value):
"""
Convert a non-empty string into a list of lon-lat coordinates.
>>> coordinates('')
Traceback (most recent call last):
...
ValueError: Empty list of coordinates: ''
>>> coordinates('1.1 1.2')
[(1.1, 1.2, 0.0)]
>>> coordinates('1.1 1.2, 2.2 2.3')
[(1.1, 1.2, 0.0), (2.2, 2.3, 0.0)]
>>> coordinates('1.1 1.2 -0.4, 2.2 2.3 -0.5')
[(1.1, 1.2, -0.4), (2.2, 2.3, -0.5)]
>>> coordinates('0 0 0, 0 0 -1')
Traceback (most recent call last):
...
ValueError: Found overlapping site #2, 0 0 -1
"""
if not value.strip():
raise ValueError('Empty list of coordinates: %r' % value)
points = []
pointset = set()
for i, line in enumerate(value.split(','), 1):
pnt = point(line)
if pnt[:2] in pointset:
raise ValueError("Found overlapping site #%d, %s" % (i, line))
pointset.add(pnt[:2])
points.append(pnt)
return points | python | def coordinates(value):
"""
Convert a non-empty string into a list of lon-lat coordinates.
>>> coordinates('')
Traceback (most recent call last):
...
ValueError: Empty list of coordinates: ''
>>> coordinates('1.1 1.2')
[(1.1, 1.2, 0.0)]
>>> coordinates('1.1 1.2, 2.2 2.3')
[(1.1, 1.2, 0.0), (2.2, 2.3, 0.0)]
>>> coordinates('1.1 1.2 -0.4, 2.2 2.3 -0.5')
[(1.1, 1.2, -0.4), (2.2, 2.3, -0.5)]
>>> coordinates('0 0 0, 0 0 -1')
Traceback (most recent call last):
...
ValueError: Found overlapping site #2, 0 0 -1
"""
if not value.strip():
raise ValueError('Empty list of coordinates: %r' % value)
points = []
pointset = set()
for i, line in enumerate(value.split(','), 1):
pnt = point(line)
if pnt[:2] in pointset:
raise ValueError("Found overlapping site #%d, %s" % (i, line))
pointset.add(pnt[:2])
points.append(pnt)
return points | [
"def",
"coordinates",
"(",
"value",
")",
":",
"if",
"not",
"value",
".",
"strip",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Empty list of coordinates: %r'",
"%",
"value",
")",
"points",
"=",
"[",
"]",
"pointset",
"=",
"set",
"(",
")",
"for",
"i",
",... | Convert a non-empty string into a list of lon-lat coordinates.
>>> coordinates('')
Traceback (most recent call last):
...
ValueError: Empty list of coordinates: ''
>>> coordinates('1.1 1.2')
[(1.1, 1.2, 0.0)]
>>> coordinates('1.1 1.2, 2.2 2.3')
[(1.1, 1.2, 0.0), (2.2, 2.3, 0.0)]
>>> coordinates('1.1 1.2 -0.4, 2.2 2.3 -0.5')
[(1.1, 1.2, -0.4), (2.2, 2.3, -0.5)]
>>> coordinates('0 0 0, 0 0 -1')
Traceback (most recent call last):
...
ValueError: Found overlapping site #2, 0 0 -1 | [
"Convert",
"a",
"non",
"-",
"empty",
"string",
"into",
"a",
"list",
"of",
"lon",
"-",
"lat",
"coordinates",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/valid.py#L464-L493 | train | 214,082 |
gem/oq-engine | openquake/hazardlib/valid.py | wkt_polygon | def wkt_polygon(value):
"""
Convert a string with a comma separated list of coordinates into
a WKT polygon, by closing the ring.
"""
points = ['%s %s' % (lon, lat) for lon, lat, dep in coordinates(value)]
# close the linear polygon ring by appending the first coord to the end
points.append(points[0])
return 'POLYGON((%s))' % ', '.join(points) | python | def wkt_polygon(value):
"""
Convert a string with a comma separated list of coordinates into
a WKT polygon, by closing the ring.
"""
points = ['%s %s' % (lon, lat) for lon, lat, dep in coordinates(value)]
# close the linear polygon ring by appending the first coord to the end
points.append(points[0])
return 'POLYGON((%s))' % ', '.join(points) | [
"def",
"wkt_polygon",
"(",
"value",
")",
":",
"points",
"=",
"[",
"'%s %s'",
"%",
"(",
"lon",
",",
"lat",
")",
"for",
"lon",
",",
"lat",
",",
"dep",
"in",
"coordinates",
"(",
"value",
")",
"]",
"# close the linear polygon ring by appending the first coord to t... | Convert a string with a comma separated list of coordinates into
a WKT polygon, by closing the ring. | [
"Convert",
"a",
"string",
"with",
"a",
"comma",
"separated",
"list",
"of",
"coordinates",
"into",
"a",
"WKT",
"polygon",
"by",
"closing",
"the",
"ring",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/valid.py#L496-L504 | train | 214,083 |
gem/oq-engine | openquake/hazardlib/valid.py | check_levels | def check_levels(imls, imt, min_iml=1E-10):
"""
Raise a ValueError if the given levels are invalid.
:param imls: a list of intensity measure and levels
:param imt: the intensity measure type
:param min_iml: minimum intensity measure level (default 1E-10)
>>> check_levels([0.1, 0.2], 'PGA') # ok
>>> check_levels([], 'PGA')
Traceback (most recent call last):
...
ValueError: No imls for PGA: []
>>> check_levels([0.2, 0.1], 'PGA')
Traceback (most recent call last):
...
ValueError: The imls for PGA are not sorted: [0.2, 0.1]
>>> check_levels([0.2, 0.2], 'PGA')
Traceback (most recent call last):
...
ValueError: Found duplicated levels for PGA: [0.2, 0.2]
"""
if len(imls) < 1:
raise ValueError('No imls for %s: %s' % (imt, imls))
elif imls != sorted(imls):
raise ValueError('The imls for %s are not sorted: %s' % (imt, imls))
elif len(distinct(imls)) < len(imls):
raise ValueError("Found duplicated levels for %s: %s" % (imt, imls))
elif imls[0] == 0 and imls[1] <= min_iml: # apply the cutoff
raise ValueError("The min_iml %s=%s is larger than the second level "
"for %s" % (imt, min_iml, imls))
elif imls[0] == 0 and imls[1] > min_iml: # apply the cutoff
imls[0] = min_iml | python | def check_levels(imls, imt, min_iml=1E-10):
"""
Raise a ValueError if the given levels are invalid.
:param imls: a list of intensity measure and levels
:param imt: the intensity measure type
:param min_iml: minimum intensity measure level (default 1E-10)
>>> check_levels([0.1, 0.2], 'PGA') # ok
>>> check_levels([], 'PGA')
Traceback (most recent call last):
...
ValueError: No imls for PGA: []
>>> check_levels([0.2, 0.1], 'PGA')
Traceback (most recent call last):
...
ValueError: The imls for PGA are not sorted: [0.2, 0.1]
>>> check_levels([0.2, 0.2], 'PGA')
Traceback (most recent call last):
...
ValueError: Found duplicated levels for PGA: [0.2, 0.2]
"""
if len(imls) < 1:
raise ValueError('No imls for %s: %s' % (imt, imls))
elif imls != sorted(imls):
raise ValueError('The imls for %s are not sorted: %s' % (imt, imls))
elif len(distinct(imls)) < len(imls):
raise ValueError("Found duplicated levels for %s: %s" % (imt, imls))
elif imls[0] == 0 and imls[1] <= min_iml: # apply the cutoff
raise ValueError("The min_iml %s=%s is larger than the second level "
"for %s" % (imt, min_iml, imls))
elif imls[0] == 0 and imls[1] > min_iml: # apply the cutoff
imls[0] = min_iml | [
"def",
"check_levels",
"(",
"imls",
",",
"imt",
",",
"min_iml",
"=",
"1E-10",
")",
":",
"if",
"len",
"(",
"imls",
")",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"'No imls for %s: %s'",
"%",
"(",
"imt",
",",
"imls",
")",
")",
"elif",
"imls",
"!=",
... | Raise a ValueError if the given levels are invalid.
:param imls: a list of intensity measure and levels
:param imt: the intensity measure type
:param min_iml: minimum intensity measure level (default 1E-10)
>>> check_levels([0.1, 0.2], 'PGA') # ok
>>> check_levels([], 'PGA')
Traceback (most recent call last):
...
ValueError: No imls for PGA: []
>>> check_levels([0.2, 0.1], 'PGA')
Traceback (most recent call last):
...
ValueError: The imls for PGA are not sorted: [0.2, 0.1]
>>> check_levels([0.2, 0.2], 'PGA')
Traceback (most recent call last):
...
ValueError: Found duplicated levels for PGA: [0.2, 0.2] | [
"Raise",
"a",
"ValueError",
"if",
"the",
"given",
"levels",
"are",
"invalid",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/valid.py#L681-L713 | train | 214,084 |
gem/oq-engine | openquake/hazardlib/valid.py | pmf | def pmf(value):
"""
Comvert a string into a Probability Mass Function.
:param value:
a sequence of probabilities summing up to 1 (no commas)
:returns:
a list of pairs [(probability, index), ...] with index starting from 0
>>> pmf("0.157 0.843")
[(0.157, 0), (0.843, 1)]
"""
probs = probabilities(value)
if abs(1.-sum(map(float, value.split()))) > 1e-12:
raise ValueError('The probabilities %s do not sum up to 1!' % value)
return [(p, i) for i, p in enumerate(probs)] | python | def pmf(value):
"""
Comvert a string into a Probability Mass Function.
:param value:
a sequence of probabilities summing up to 1 (no commas)
:returns:
a list of pairs [(probability, index), ...] with index starting from 0
>>> pmf("0.157 0.843")
[(0.157, 0), (0.843, 1)]
"""
probs = probabilities(value)
if abs(1.-sum(map(float, value.split()))) > 1e-12:
raise ValueError('The probabilities %s do not sum up to 1!' % value)
return [(p, i) for i, p in enumerate(probs)] | [
"def",
"pmf",
"(",
"value",
")",
":",
"probs",
"=",
"probabilities",
"(",
"value",
")",
"if",
"abs",
"(",
"1.",
"-",
"sum",
"(",
"map",
"(",
"float",
",",
"value",
".",
"split",
"(",
")",
")",
")",
")",
">",
"1e-12",
":",
"raise",
"ValueError",
... | Comvert a string into a Probability Mass Function.
:param value:
a sequence of probabilities summing up to 1 (no commas)
:returns:
a list of pairs [(probability, index), ...] with index starting from 0
>>> pmf("0.157 0.843")
[(0.157, 0), (0.843, 1)] | [
"Comvert",
"a",
"string",
"into",
"a",
"Probability",
"Mass",
"Function",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/valid.py#L862-L877 | train | 214,085 |
gem/oq-engine | openquake/hazardlib/valid.py | check_weights | def check_weights(nodes_with_a_weight):
"""
Ensure that the sum of the values is 1
:param nodes_with_a_weight: a list of Node objects with a weight attribute
"""
weights = [n['weight'] for n in nodes_with_a_weight]
if abs(sum(weights) - 1.) > PRECISION:
raise ValueError('The weights do not sum up to 1: %s' % weights)
return nodes_with_a_weight | python | def check_weights(nodes_with_a_weight):
"""
Ensure that the sum of the values is 1
:param nodes_with_a_weight: a list of Node objects with a weight attribute
"""
weights = [n['weight'] for n in nodes_with_a_weight]
if abs(sum(weights) - 1.) > PRECISION:
raise ValueError('The weights do not sum up to 1: %s' % weights)
return nodes_with_a_weight | [
"def",
"check_weights",
"(",
"nodes_with_a_weight",
")",
":",
"weights",
"=",
"[",
"n",
"[",
"'weight'",
"]",
"for",
"n",
"in",
"nodes_with_a_weight",
"]",
"if",
"abs",
"(",
"sum",
"(",
"weights",
")",
"-",
"1.",
")",
">",
"PRECISION",
":",
"raise",
"V... | Ensure that the sum of the values is 1
:param nodes_with_a_weight: a list of Node objects with a weight attribute | [
"Ensure",
"that",
"the",
"sum",
"of",
"the",
"values",
"is",
"1"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/valid.py#L880-L889 | train | 214,086 |
gem/oq-engine | openquake/hazardlib/valid.py | ab_values | def ab_values(value):
"""
a and b values of the GR magniture-scaling relation.
a is a positive float, b is just a float.
"""
a, b = value.split()
return positivefloat(a), float_(b) | python | def ab_values(value):
"""
a and b values of the GR magniture-scaling relation.
a is a positive float, b is just a float.
"""
a, b = value.split()
return positivefloat(a), float_(b) | [
"def",
"ab_values",
"(",
"value",
")",
":",
"a",
",",
"b",
"=",
"value",
".",
"split",
"(",
")",
"return",
"positivefloat",
"(",
"a",
")",
",",
"float_",
"(",
"b",
")"
] | a and b values of the GR magniture-scaling relation.
a is a positive float, b is just a float. | [
"a",
"and",
"b",
"values",
"of",
"the",
"GR",
"magniture",
"-",
"scaling",
"relation",
".",
"a",
"is",
"a",
"positive",
"float",
"b",
"is",
"just",
"a",
"float",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/valid.py#L971-L977 | train | 214,087 |
gem/oq-engine | openquake/hazardlib/valid.py | site_param | def site_param(dic):
"""
Convert a dictionary site_model_param -> string into a dictionary
of valid casted site parameters.
"""
new = {}
for name, val in dic.items():
if name == 'vs30Type':
# avoid "Unrecognized parameter vs30Type"
new['vs30measured'] = val == 'measured'
elif name not in site.site_param_dt:
raise ValueError('Unrecognized parameter %s' % name)
else:
new[name] = val
return new | python | def site_param(dic):
"""
Convert a dictionary site_model_param -> string into a dictionary
of valid casted site parameters.
"""
new = {}
for name, val in dic.items():
if name == 'vs30Type':
# avoid "Unrecognized parameter vs30Type"
new['vs30measured'] = val == 'measured'
elif name not in site.site_param_dt:
raise ValueError('Unrecognized parameter %s' % name)
else:
new[name] = val
return new | [
"def",
"site_param",
"(",
"dic",
")",
":",
"new",
"=",
"{",
"}",
"for",
"name",
",",
"val",
"in",
"dic",
".",
"items",
"(",
")",
":",
"if",
"name",
"==",
"'vs30Type'",
":",
"# avoid \"Unrecognized parameter vs30Type\"",
"new",
"[",
"'vs30measured'",
"]",
... | Convert a dictionary site_model_param -> string into a dictionary
of valid casted site parameters. | [
"Convert",
"a",
"dictionary",
"site_model_param",
"-",
">",
"string",
"into",
"a",
"dictionary",
"of",
"valid",
"casted",
"site",
"parameters",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/valid.py#L1043-L1057 | train | 214,088 |
gem/oq-engine | openquake/hazardlib/valid.py | ParamSet.check | def check(cls, dic):
"""
Convert a dictionary name->string into a dictionary name->value
by converting the string. If the name does not correspond to a
known parameter, just ignore it and print a warning.
"""
res = {}
for name, text in dic.items():
try:
p = getattr(cls, name)
except AttributeError:
logging.warning('Ignored unknown parameter %s', name)
else:
res[name] = p.validator(text)
return res | python | def check(cls, dic):
"""
Convert a dictionary name->string into a dictionary name->value
by converting the string. If the name does not correspond to a
known parameter, just ignore it and print a warning.
"""
res = {}
for name, text in dic.items():
try:
p = getattr(cls, name)
except AttributeError:
logging.warning('Ignored unknown parameter %s', name)
else:
res[name] = p.validator(text)
return res | [
"def",
"check",
"(",
"cls",
",",
"dic",
")",
":",
"res",
"=",
"{",
"}",
"for",
"name",
",",
"text",
"in",
"dic",
".",
"items",
"(",
")",
":",
"try",
":",
"p",
"=",
"getattr",
"(",
"cls",
",",
"name",
")",
"except",
"AttributeError",
":",
"loggi... | Convert a dictionary name->string into a dictionary name->value
by converting the string. If the name does not correspond to a
known parameter, just ignore it and print a warning. | [
"Convert",
"a",
"dictionary",
"name",
"-",
">",
"string",
"into",
"a",
"dictionary",
"name",
"-",
">",
"value",
"by",
"converting",
"the",
"string",
".",
"If",
"the",
"name",
"does",
"not",
"correspond",
"to",
"a",
"known",
"parameter",
"just",
"ignore",
... | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/valid.py#L1149-L1163 | train | 214,089 |
gem/oq-engine | openquake/hazardlib/valid.py | ParamSet.from_ | def from_(cls, dic):
"""
Build a new ParamSet from a dictionary of string-valued parameters
which are assumed to be already valid.
"""
self = cls.__new__(cls)
for k, v in dic.items():
setattr(self, k, ast.literal_eval(v))
return self | python | def from_(cls, dic):
"""
Build a new ParamSet from a dictionary of string-valued parameters
which are assumed to be already valid.
"""
self = cls.__new__(cls)
for k, v in dic.items():
setattr(self, k, ast.literal_eval(v))
return self | [
"def",
"from_",
"(",
"cls",
",",
"dic",
")",
":",
"self",
"=",
"cls",
".",
"__new__",
"(",
"cls",
")",
"for",
"k",
",",
"v",
"in",
"dic",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"k",
",",
"ast",
".",
"literal_eval",
"(",
"v"... | Build a new ParamSet from a dictionary of string-valued parameters
which are assumed to be already valid. | [
"Build",
"a",
"new",
"ParamSet",
"from",
"a",
"dictionary",
"of",
"string",
"-",
"valued",
"parameters",
"which",
"are",
"assumed",
"to",
"be",
"already",
"valid",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/valid.py#L1166-L1174 | train | 214,090 |
gem/oq-engine | openquake/hazardlib/valid.py | ParamSet.validate | def validate(self):
"""
Apply the `is_valid` methods to self and possibly raise a ValueError.
"""
# it is important to have the validator applied in a fixed order
valids = [getattr(self, valid)
for valid in sorted(dir(self.__class__))
if valid.startswith('is_valid_')]
for is_valid in valids:
if not is_valid():
docstring = '\n'.join(
line.strip() for line in is_valid.__doc__.splitlines())
doc = docstring.format(**vars(self))
raise ValueError(doc) | python | def validate(self):
"""
Apply the `is_valid` methods to self and possibly raise a ValueError.
"""
# it is important to have the validator applied in a fixed order
valids = [getattr(self, valid)
for valid in sorted(dir(self.__class__))
if valid.startswith('is_valid_')]
for is_valid in valids:
if not is_valid():
docstring = '\n'.join(
line.strip() for line in is_valid.__doc__.splitlines())
doc = docstring.format(**vars(self))
raise ValueError(doc) | [
"def",
"validate",
"(",
"self",
")",
":",
"# it is important to have the validator applied in a fixed order",
"valids",
"=",
"[",
"getattr",
"(",
"self",
",",
"valid",
")",
"for",
"valid",
"in",
"sorted",
"(",
"dir",
"(",
"self",
".",
"__class__",
")",
")",
"i... | Apply the `is_valid` methods to self and possibly raise a ValueError. | [
"Apply",
"the",
"is_valid",
"methods",
"to",
"self",
"and",
"possibly",
"raise",
"a",
"ValueError",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/valid.py#L1203-L1216 | train | 214,091 |
gem/oq-engine | openquake/hazardlib/gsim/idriss_2014.py | Idriss2014._get_magnitude_scaling_term | def _get_magnitude_scaling_term(self, C, mag):
"""
Returns the magnitude scaling term defined in equation 3
"""
if mag < 6.75:
return C["a1_lo"] + C["a2_lo"] * mag + C["a3"] *\
((8.5 - mag) ** 2.0)
else:
return C["a1_hi"] + C["a2_hi"] * mag + C["a3"] *\
((8.5 - mag) ** 2.0) | python | def _get_magnitude_scaling_term(self, C, mag):
"""
Returns the magnitude scaling term defined in equation 3
"""
if mag < 6.75:
return C["a1_lo"] + C["a2_lo"] * mag + C["a3"] *\
((8.5 - mag) ** 2.0)
else:
return C["a1_hi"] + C["a2_hi"] * mag + C["a3"] *\
((8.5 - mag) ** 2.0) | [
"def",
"_get_magnitude_scaling_term",
"(",
"self",
",",
"C",
",",
"mag",
")",
":",
"if",
"mag",
"<",
"6.75",
":",
"return",
"C",
"[",
"\"a1_lo\"",
"]",
"+",
"C",
"[",
"\"a2_lo\"",
"]",
"*",
"mag",
"+",
"C",
"[",
"\"a3\"",
"]",
"*",
"(",
"(",
"8.5... | Returns the magnitude scaling term defined in equation 3 | [
"Returns",
"the",
"magnitude",
"scaling",
"term",
"defined",
"in",
"equation",
"3"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/idriss_2014.py#L89-L98 | train | 214,092 |
gem/oq-engine | openquake/hazardlib/gsim/idriss_2014.py | Idriss2014._get_distance_scaling_term | def _get_distance_scaling_term(self, C, mag, rrup):
"""
Returns the magnitude dependent distance scaling term
"""
if mag < 6.75:
mag_factor = -(C["b1_lo"] + C["b2_lo"] * mag)
else:
mag_factor = -(C["b1_hi"] + C["b2_hi"] * mag)
return mag_factor * np.log(rrup + 10.0) + (C["gamma"] * rrup) | python | def _get_distance_scaling_term(self, C, mag, rrup):
"""
Returns the magnitude dependent distance scaling term
"""
if mag < 6.75:
mag_factor = -(C["b1_lo"] + C["b2_lo"] * mag)
else:
mag_factor = -(C["b1_hi"] + C["b2_hi"] * mag)
return mag_factor * np.log(rrup + 10.0) + (C["gamma"] * rrup) | [
"def",
"_get_distance_scaling_term",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rrup",
")",
":",
"if",
"mag",
"<",
"6.75",
":",
"mag_factor",
"=",
"-",
"(",
"C",
"[",
"\"b1_lo\"",
"]",
"+",
"C",
"[",
"\"b2_lo\"",
"]",
"*",
"mag",
")",
"else",
":",
... | Returns the magnitude dependent distance scaling term | [
"Returns",
"the",
"magnitude",
"dependent",
"distance",
"scaling",
"term"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/idriss_2014.py#L100-L108 | train | 214,093 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_silva_2008.py | AbrahamsonSilva2008._compute_base_term | def _compute_base_term(self, C, rup, dists):
"""
Compute and return base model term, that is the first term in equation
1, page 74. The calculation of this term is explained in paragraph
'Base Model', page 75.
"""
c1 = self.CONSTS['c1']
R = np.sqrt(dists.rrup ** 2 + self.CONSTS['c4'] ** 2)
base_term = (C['a1'] +
C['a8'] * ((8.5 - rup.mag) ** 2) +
(C['a2'] + self.CONSTS['a3'] * (rup.mag - c1)) *
np.log(R))
if rup.mag <= c1:
return base_term + self.CONSTS['a4'] * (rup.mag - c1)
else:
return base_term + self.CONSTS['a5'] * (rup.mag - c1) | python | def _compute_base_term(self, C, rup, dists):
"""
Compute and return base model term, that is the first term in equation
1, page 74. The calculation of this term is explained in paragraph
'Base Model', page 75.
"""
c1 = self.CONSTS['c1']
R = np.sqrt(dists.rrup ** 2 + self.CONSTS['c4'] ** 2)
base_term = (C['a1'] +
C['a8'] * ((8.5 - rup.mag) ** 2) +
(C['a2'] + self.CONSTS['a3'] * (rup.mag - c1)) *
np.log(R))
if rup.mag <= c1:
return base_term + self.CONSTS['a4'] * (rup.mag - c1)
else:
return base_term + self.CONSTS['a5'] * (rup.mag - c1) | [
"def",
"_compute_base_term",
"(",
"self",
",",
"C",
",",
"rup",
",",
"dists",
")",
":",
"c1",
"=",
"self",
".",
"CONSTS",
"[",
"'c1'",
"]",
"R",
"=",
"np",
".",
"sqrt",
"(",
"dists",
".",
"rrup",
"**",
"2",
"+",
"self",
".",
"CONSTS",
"[",
"'c4... | Compute and return base model term, that is the first term in equation
1, page 74. The calculation of this term is explained in paragraph
'Base Model', page 75. | [
"Compute",
"and",
"return",
"base",
"model",
"term",
"that",
"is",
"the",
"first",
"term",
"in",
"equation",
"1",
"page",
"74",
".",
"The",
"calculation",
"of",
"this",
"term",
"is",
"explained",
"in",
"paragraph",
"Base",
"Model",
"page",
"75",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L110-L127 | train | 214,094 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_silva_2008.py | AbrahamsonSilva2008._compute_site_response_term | def _compute_site_response_term(self, C, imt, sites, pga1100):
"""
Compute and return site response model term, that is the fifth term
in equation 1, page 74.
"""
site_resp_term = np.zeros_like(sites.vs30)
vs30_star, _ = self._compute_vs30_star_factor(imt, sites.vs30)
vlin, c, n = C['VLIN'], self.CONSTS['c'], self.CONSTS['n']
a10, b = C['a10'], C['b']
idx = sites.vs30 < vlin
arg = vs30_star[idx] / vlin
site_resp_term[idx] = (a10 * np.log(arg) -
b * np.log(pga1100[idx] + c) +
b * np.log(pga1100[idx] + c * (arg ** n)))
idx = sites.vs30 >= vlin
site_resp_term[idx] = (a10 + b * n) * np.log(vs30_star[idx] / vlin)
return site_resp_term | python | def _compute_site_response_term(self, C, imt, sites, pga1100):
"""
Compute and return site response model term, that is the fifth term
in equation 1, page 74.
"""
site_resp_term = np.zeros_like(sites.vs30)
vs30_star, _ = self._compute_vs30_star_factor(imt, sites.vs30)
vlin, c, n = C['VLIN'], self.CONSTS['c'], self.CONSTS['n']
a10, b = C['a10'], C['b']
idx = sites.vs30 < vlin
arg = vs30_star[idx] / vlin
site_resp_term[idx] = (a10 * np.log(arg) -
b * np.log(pga1100[idx] + c) +
b * np.log(pga1100[idx] + c * (arg ** n)))
idx = sites.vs30 >= vlin
site_resp_term[idx] = (a10 + b * n) * np.log(vs30_star[idx] / vlin)
return site_resp_term | [
"def",
"_compute_site_response_term",
"(",
"self",
",",
"C",
",",
"imt",
",",
"sites",
",",
"pga1100",
")",
":",
"site_resp_term",
"=",
"np",
".",
"zeros_like",
"(",
"sites",
".",
"vs30",
")",
"vs30_star",
",",
"_",
"=",
"self",
".",
"_compute_vs30_star_fa... | Compute and return site response model term, that is the fifth term
in equation 1, page 74. | [
"Compute",
"and",
"return",
"site",
"response",
"model",
"term",
"that",
"is",
"the",
"fifth",
"term",
"in",
"equation",
"1",
"page",
"74",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L139-L159 | train | 214,095 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_silva_2008.py | AbrahamsonSilva2008._compute_hanging_wall_term | def _compute_hanging_wall_term(self, C, dists, rup):
"""
Compute and return hanging wall model term, that is the sixth term in
equation 1, page 74. The calculation of this term is explained in
paragraph 'Hanging-Wall Model', page 77.
"""
if rup.dip == 90.0:
return np.zeros_like(dists.rx)
else:
idx = dists.rx > 0
Fhw = np.zeros_like(dists.rx)
Fhw[idx] = 1
# equation 8, page 77
T1 = np.zeros_like(dists.rx)
idx1 = (dists.rjb < 30.0) & (idx)
T1[idx1] = 1.0 - dists.rjb[idx1] / 30.0
# equation 9, page 77
T2 = np.ones_like(dists.rx)
idx2 = ((dists.rx <= rup.width * np.cos(np.radians(rup.dip))) &
(idx))
T2[idx2] = (0.5 + dists.rx[idx2] /
(2 * rup.width * np.cos(np.radians(rup.dip))))
# equation 10, page 78
T3 = np.ones_like(dists.rx)
idx3 = (dists.rx < rup.ztor) & (idx)
T3[idx3] = dists.rx[idx3] / rup.ztor
# equation 11, page 78
if rup.mag <= 6.0:
T4 = 0.0
elif rup.mag > 6 and rup.mag < 7:
T4 = rup.mag - 6
else:
T4 = 1.0
# equation 5, in AS08_NGA_errata.pdf
if rup.dip >= 30:
T5 = 1.0 - (rup.dip - 30.0) / 60.0
else:
T5 = 1.0
return Fhw * C['a14'] * T1 * T2 * T3 * T4 * T5 | python | def _compute_hanging_wall_term(self, C, dists, rup):
"""
Compute and return hanging wall model term, that is the sixth term in
equation 1, page 74. The calculation of this term is explained in
paragraph 'Hanging-Wall Model', page 77.
"""
if rup.dip == 90.0:
return np.zeros_like(dists.rx)
else:
idx = dists.rx > 0
Fhw = np.zeros_like(dists.rx)
Fhw[idx] = 1
# equation 8, page 77
T1 = np.zeros_like(dists.rx)
idx1 = (dists.rjb < 30.0) & (idx)
T1[idx1] = 1.0 - dists.rjb[idx1] / 30.0
# equation 9, page 77
T2 = np.ones_like(dists.rx)
idx2 = ((dists.rx <= rup.width * np.cos(np.radians(rup.dip))) &
(idx))
T2[idx2] = (0.5 + dists.rx[idx2] /
(2 * rup.width * np.cos(np.radians(rup.dip))))
# equation 10, page 78
T3 = np.ones_like(dists.rx)
idx3 = (dists.rx < rup.ztor) & (idx)
T3[idx3] = dists.rx[idx3] / rup.ztor
# equation 11, page 78
if rup.mag <= 6.0:
T4 = 0.0
elif rup.mag > 6 and rup.mag < 7:
T4 = rup.mag - 6
else:
T4 = 1.0
# equation 5, in AS08_NGA_errata.pdf
if rup.dip >= 30:
T5 = 1.0 - (rup.dip - 30.0) / 60.0
else:
T5 = 1.0
return Fhw * C['a14'] * T1 * T2 * T3 * T4 * T5 | [
"def",
"_compute_hanging_wall_term",
"(",
"self",
",",
"C",
",",
"dists",
",",
"rup",
")",
":",
"if",
"rup",
".",
"dip",
"==",
"90.0",
":",
"return",
"np",
".",
"zeros_like",
"(",
"dists",
".",
"rx",
")",
"else",
":",
"idx",
"=",
"dists",
".",
"rx"... | Compute and return hanging wall model term, that is the sixth term in
equation 1, page 74. The calculation of this term is explained in
paragraph 'Hanging-Wall Model', page 77. | [
"Compute",
"and",
"return",
"hanging",
"wall",
"model",
"term",
"that",
"is",
"the",
"sixth",
"term",
"in",
"equation",
"1",
"page",
"74",
".",
"The",
"calculation",
"of",
"this",
"term",
"is",
"explained",
"in",
"paragraph",
"Hanging",
"-",
"Wall",
"Model... | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L161-L205 | train | 214,096 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_silva_2008.py | AbrahamsonSilva2008._compute_top_of_rupture_depth_term | def _compute_top_of_rupture_depth_term(self, C, rup):
"""
Compute and return top of rupture depth term, that is the seventh term
in equation 1, page 74. The calculation of this term is explained in
paragraph 'Depth-to-Top of Rupture Model', page 78.
"""
if rup.ztor >= 10.0:
return C['a16']
else:
return C['a16'] * rup.ztor / 10.0 | python | def _compute_top_of_rupture_depth_term(self, C, rup):
"""
Compute and return top of rupture depth term, that is the seventh term
in equation 1, page 74. The calculation of this term is explained in
paragraph 'Depth-to-Top of Rupture Model', page 78.
"""
if rup.ztor >= 10.0:
return C['a16']
else:
return C['a16'] * rup.ztor / 10.0 | [
"def",
"_compute_top_of_rupture_depth_term",
"(",
"self",
",",
"C",
",",
"rup",
")",
":",
"if",
"rup",
".",
"ztor",
">=",
"10.0",
":",
"return",
"C",
"[",
"'a16'",
"]",
"else",
":",
"return",
"C",
"[",
"'a16'",
"]",
"*",
"rup",
".",
"ztor",
"/",
"1... | Compute and return top of rupture depth term, that is the seventh term
in equation 1, page 74. The calculation of this term is explained in
paragraph 'Depth-to-Top of Rupture Model', page 78. | [
"Compute",
"and",
"return",
"top",
"of",
"rupture",
"depth",
"term",
"that",
"is",
"the",
"seventh",
"term",
"in",
"equation",
"1",
"page",
"74",
".",
"The",
"calculation",
"of",
"this",
"term",
"is",
"explained",
"in",
"paragraph",
"Depth",
"-",
"to",
"... | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L207-L216 | train | 214,097 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_silva_2008.py | AbrahamsonSilva2008._compute_large_distance_term | def _compute_large_distance_term(self, C, dists, rup):
"""
Compute and return large distance model term, that is the 8-th term
in equation 1, page 74. The calculation of this term is explained in
paragraph 'Large Distance Model', page 78.
"""
# equation 15, page 79
if rup.mag < 5.5:
T6 = 1.0
elif rup.mag >= 5.5 and rup.mag <= 6.5:
T6 = 0.5 * (6.5 - rup.mag) + 0.5
else:
T6 = 0.5
# equation 14, page 79
large_distance_term = np.zeros_like(dists.rrup)
idx = dists.rrup >= 100.0
large_distance_term[idx] = C['a18'] * (dists.rrup[idx] - 100.0) * T6
return large_distance_term | python | def _compute_large_distance_term(self, C, dists, rup):
"""
Compute and return large distance model term, that is the 8-th term
in equation 1, page 74. The calculation of this term is explained in
paragraph 'Large Distance Model', page 78.
"""
# equation 15, page 79
if rup.mag < 5.5:
T6 = 1.0
elif rup.mag >= 5.5 and rup.mag <= 6.5:
T6 = 0.5 * (6.5 - rup.mag) + 0.5
else:
T6 = 0.5
# equation 14, page 79
large_distance_term = np.zeros_like(dists.rrup)
idx = dists.rrup >= 100.0
large_distance_term[idx] = C['a18'] * (dists.rrup[idx] - 100.0) * T6
return large_distance_term | [
"def",
"_compute_large_distance_term",
"(",
"self",
",",
"C",
",",
"dists",
",",
"rup",
")",
":",
"# equation 15, page 79",
"if",
"rup",
".",
"mag",
"<",
"5.5",
":",
"T6",
"=",
"1.0",
"elif",
"rup",
".",
"mag",
">=",
"5.5",
"and",
"rup",
".",
"mag",
... | Compute and return large distance model term, that is the 8-th term
in equation 1, page 74. The calculation of this term is explained in
paragraph 'Large Distance Model', page 78. | [
"Compute",
"and",
"return",
"large",
"distance",
"model",
"term",
"that",
"is",
"the",
"8",
"-",
"th",
"term",
"in",
"equation",
"1",
"page",
"74",
".",
"The",
"calculation",
"of",
"this",
"term",
"is",
"explained",
"in",
"paragraph",
"Large",
"Distance",
... | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L218-L237 | train | 214,098 |
gem/oq-engine | openquake/hazardlib/gsim/abrahamson_silva_2008.py | AbrahamsonSilva2008._compute_soil_depth_term | def _compute_soil_depth_term(self, C, imt, z1pt0, vs30):
"""
Compute and return soil depth model term, that is the 9-th term in
equation 1, page 74. The calculation of this term is explained in
paragraph 'Soil Depth Model', page 79.
"""
a21 = self._compute_a21_factor(C, imt, z1pt0, vs30)
a22 = self._compute_a22_factor(imt)
median_z1pt0 = self._compute_median_z1pt0(vs30)
soil_depth_term = a21 * np.log((z1pt0 + self.CONSTS['c2']) /
(median_z1pt0 + self.CONSTS['c2']))
idx = z1pt0 >= 200
soil_depth_term[idx] += a22 * np.log(z1pt0[idx] / 200)
return soil_depth_term | python | def _compute_soil_depth_term(self, C, imt, z1pt0, vs30):
"""
Compute and return soil depth model term, that is the 9-th term in
equation 1, page 74. The calculation of this term is explained in
paragraph 'Soil Depth Model', page 79.
"""
a21 = self._compute_a21_factor(C, imt, z1pt0, vs30)
a22 = self._compute_a22_factor(imt)
median_z1pt0 = self._compute_median_z1pt0(vs30)
soil_depth_term = a21 * np.log((z1pt0 + self.CONSTS['c2']) /
(median_z1pt0 + self.CONSTS['c2']))
idx = z1pt0 >= 200
soil_depth_term[idx] += a22 * np.log(z1pt0[idx] / 200)
return soil_depth_term | [
"def",
"_compute_soil_depth_term",
"(",
"self",
",",
"C",
",",
"imt",
",",
"z1pt0",
",",
"vs30",
")",
":",
"a21",
"=",
"self",
".",
"_compute_a21_factor",
"(",
"C",
",",
"imt",
",",
"z1pt0",
",",
"vs30",
")",
"a22",
"=",
"self",
".",
"_compute_a22_fact... | Compute and return soil depth model term, that is the 9-th term in
equation 1, page 74. The calculation of this term is explained in
paragraph 'Soil Depth Model', page 79. | [
"Compute",
"and",
"return",
"soil",
"depth",
"model",
"term",
"that",
"is",
"the",
"9",
"-",
"th",
"term",
"in",
"equation",
"1",
"page",
"74",
".",
"The",
"calculation",
"of",
"this",
"term",
"is",
"explained",
"in",
"paragraph",
"Soil",
"Depth",
"Model... | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_silva_2008.py#L239-L255 | train | 214,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.