repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 39 1.84M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
gem/oq-engine | openquake/hazardlib/gsim/berge_thierry_2003.py | BergeThierryEtAl2003Ms._get_stddevs | def _get_stddevs(self, C, stddev_types, num_sites, mag_conversion_sigma):
"""
Return total standard deviation.
"""
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
for stddev_type in stddev_types)
sigma = np.zeros(num_sites) + C['sigma'] * n... | python | def _get_stddevs(self, C, stddev_types, num_sites, mag_conversion_sigma):
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
for stddev_type in stddev_types)
sigma = np.zeros(num_sites) + C['sigma'] * np.log(10)
sigma = np.sqrt(sigma ** 2 + (C['a'] *... | [
"def",
"_get_stddevs",
"(",
"self",
",",
"C",
",",
"stddev_types",
",",
"num_sites",
",",
"mag_conversion_sigma",
")",
":",
"assert",
"all",
"(",
"stddev_type",
"in",
"self",
".",
"DEFINED_FOR_STANDARD_DEVIATION_TYPES",
"for",
"stddev_type",
"in",
"stddev_types",
... | Return total standard deviation. | [
"Return",
"total",
"standard",
"deviation",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/berge_thierry_2003.py#L77-L88 |
gem/oq-engine | openquake/hazardlib/gsim/berge_thierry_2003.py | BergeThierryEtAl2003Ms._get_mean_and_stddevs | def _get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types,
mag_conversion_sigma=0.0):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extract dictionaries of coeffici... | python | def _get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types,
mag_conversion_sigma=0.0):
C = self.COEFFS[imt]
rhypo = dists.rhypo
rhypo[rhypo < 4.] = 4.
mean = C['a'] * rup.mag + C['b'] * rhypo - np.log10(rhypo)
... | [
"def",
"_get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
",",
"mag_conversion_sigma",
"=",
"0.0",
")",
":",
"# extract dictionaries of coefficients specific to required",
"# intensity measure type",
"C",
"=",
... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. | [
"See",
":",
"meth",
":",
"superclass",
"method",
"<",
".",
"base",
".",
"GroundShakingIntensityModel",
".",
"get_mean_and_stddevs",
">",
"for",
"spec",
"of",
"input",
"and",
"result",
"values",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/berge_thierry_2003.py#L90-L118 |
gem/oq-engine | openquake/hazardlib/gsim/can15/sslab.py | SSlabCan15Mid.get_mean_and_stddevs | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# get original values
hslab = 50 # See info in GMPEt_Inslab_... | python | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
hslab = 50
rjb, rrup = utils.get_equivalent_distance_inslab(rup.mag, dists.repi,
hslab)
dists.rjb = rjb
dists.rrup = rrup
mean, stdd... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"# get original values",
"hslab",
"=",
"50",
"# See info in GMPEt_Inslab_med.dat",
"rjb",
",",
"rrup",
"=",
"utils",
".",
"get_equivale... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. | [
"See",
":",
"meth",
":",
"superclass",
"method",
"<",
".",
"base",
".",
"GroundShakingIntensityModel",
".",
"get_mean_and_stddevs",
">",
"for",
"spec",
"of",
"input",
"and",
"result",
"values",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/can15/sslab.py#L45-L63 |
gem/oq-engine | openquake/calculators/classical.py | get_src_ids | def get_src_ids(sources):
"""
:returns:
a string with the source IDs of the given sources, stripping the
extension after the colon, if any
"""
src_ids = []
for src in sources:
long_src_id = src.source_id
try:
src_id, ext = long_src_id.rsplit(':', 1)
... | python | def get_src_ids(sources):
src_ids = []
for src in sources:
long_src_id = src.source_id
try:
src_id, ext = long_src_id.rsplit(':', 1)
except ValueError:
src_id = long_src_id
src_ids.append(src_id)
return ' '.join(set(src_ids)) | [
"def",
"get_src_ids",
"(",
"sources",
")",
":",
"src_ids",
"=",
"[",
"]",
"for",
"src",
"in",
"sources",
":",
"long_src_id",
"=",
"src",
".",
"source_id",
"try",
":",
"src_id",
",",
"ext",
"=",
"long_src_id",
".",
"rsplit",
"(",
"':'",
",",
"1",
")",... | :returns:
a string with the source IDs of the given sources, stripping the
extension after the colon, if any | [
":",
"returns",
":",
"a",
"string",
"with",
"the",
"source",
"IDs",
"of",
"the",
"given",
"sources",
"stripping",
"the",
"extension",
"after",
"the",
"colon",
"if",
"any"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/classical.py#L45-L59 |
gem/oq-engine | openquake/calculators/classical.py | get_extreme_poe | def get_extreme_poe(array, imtls):
"""
:param array: array of shape (L, G) with L=num_levels, G=num_gsims
:param imtls: DictArray imt -> levels
:returns:
the maximum PoE corresponding to the maximum level for IMTs and GSIMs
"""
return max(array[imtls(imt).stop - 1].max() for imt in imtls... | python | def get_extreme_poe(array, imtls):
return max(array[imtls(imt).stop - 1].max() for imt in imtls) | [
"def",
"get_extreme_poe",
"(",
"array",
",",
"imtls",
")",
":",
"return",
"max",
"(",
"array",
"[",
"imtls",
"(",
"imt",
")",
".",
"stop",
"-",
"1",
"]",
".",
"max",
"(",
")",
"for",
"imt",
"in",
"imtls",
")"
] | :param array: array of shape (L, G) with L=num_levels, G=num_gsims
:param imtls: DictArray imt -> levels
:returns:
the maximum PoE corresponding to the maximum level for IMTs and GSIMs | [
":",
"param",
"array",
":",
"array",
"of",
"shape",
"(",
"L",
"G",
")",
"with",
"L",
"=",
"num_levels",
"G",
"=",
"num_gsims",
":",
"param",
"imtls",
":",
"DictArray",
"imt",
"-",
">",
"levels",
":",
"returns",
":",
"the",
"maximum",
"PoE",
"correspo... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/classical.py#L62-L69 |
gem/oq-engine | openquake/calculators/classical.py | classical_split_filter | def classical_split_filter(srcs, srcfilter, gsims, params, monitor):
"""
Split the given sources, filter the subsources and the compute the
PoEs. Yield back subtasks if the split sources contain more than
maxweight ruptures.
"""
# first check if we are sampling the sources
ss = int(os.enviro... | python | def classical_split_filter(srcs, srcfilter, gsims, params, monitor):
ss = int(os.environ.get('OQ_SAMPLE_SOURCES', 0))
if ss:
splits, stime = split_sources(srcs)
srcs = readinput.random_filtered_sources(splits, srcfilter, ss)
yield classical(srcs, srcfilter, gsims, params, monit... | [
"def",
"classical_split_filter",
"(",
"srcs",
",",
"srcfilter",
",",
"gsims",
",",
"params",
",",
"monitor",
")",
":",
"# first check if we are sampling the sources",
"ss",
"=",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'OQ_SAMPLE_SOURCES'",
",",
"0",
... | Split the given sources, filter the subsources and the compute the
PoEs. Yield back subtasks if the split sources contain more than
maxweight ruptures. | [
"Split",
"the",
"given",
"sources",
"filter",
"the",
"subsources",
"and",
"the",
"compute",
"the",
"PoEs",
".",
"Yield",
"back",
"subtasks",
"if",
"the",
"split",
"sources",
"contain",
"more",
"than",
"maxweight",
"ruptures",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/classical.py#L72-L100 |
gem/oq-engine | openquake/calculators/classical.py | build_hazard_stats | def build_hazard_stats(pgetter, N, hstats, individual_curves, monitor):
"""
:param pgetter: an :class:`openquake.commonlib.getters.PmapGetter`
:param N: the total number of sites
:param hstats: a list of pairs (statname, statfunc)
:param individual_curves: if True, also build the individual curves
... | python | def build_hazard_stats(pgetter, N, hstats, individual_curves, monitor):
with monitor('combine pmaps'):
pgetter.init()
try:
pmaps = pgetter.get_pmaps()
except IndexError:
return {}
if sum(len(pmap) for pmap in pmaps) == 0:
return {}
R... | [
"def",
"build_hazard_stats",
"(",
"pgetter",
",",
"N",
",",
"hstats",
",",
"individual_curves",
",",
"monitor",
")",
":",
"with",
"monitor",
"(",
"'combine pmaps'",
")",
":",
"pgetter",
".",
"init",
"(",
")",
"# if not already initialized",
"try",
":",
"pmaps"... | :param pgetter: an :class:`openquake.commonlib.getters.PmapGetter`
:param N: the total number of sites
:param hstats: a list of pairs (statname, statfunc)
:param individual_curves: if True, also build the individual curves
:param monitor: instance of Monitor
:returns: a dictionary kind -> Probabilit... | [
":",
"param",
"pgetter",
":",
"an",
":",
"class",
":",
"openquake",
".",
"commonlib",
".",
"getters",
".",
"PmapGetter",
":",
"param",
"N",
":",
"the",
"total",
"number",
"of",
"sites",
":",
"param",
"hstats",
":",
"a",
"list",
"of",
"pairs",
"(",
"s... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/classical.py#L336-L384 |
gem/oq-engine | openquake/hazardlib/gsim/cauzzi_faccioli_2008_swiss.py | CauzziFaccioli2008SWISS01.get_mean_and_stddevs | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
sites.vs30 = 700 * np.ones(len(sites.vs30))
mean, stddevs = ... | python | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
sites.vs30 = 700 * np.ones(len(sites.vs30))
mean, stddevs = super().get_mean_and_stddevs(
sites, rup, dists, imt, stddev_types)
C = CauzziFaccioli2008SWISS01.COEFFS
tau_ss = 'tau'
log_p... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"sites",
".",
"vs30",
"=",
"700",
"*",
"np",
".",
"ones",
"(",
"len",
"(",
"sites",
".",
"vs30",
")",
")",
"mean",
",",
... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. | [
"See",
":",
"meth",
":",
"superclass",
"method",
"<",
".",
"base",
".",
"GroundShakingIntensityModel",
".",
"get_mean_and_stddevs",
">",
"for",
"spec",
"of",
"input",
"and",
"result",
"values",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_faccioli_2008_swiss.py#L73-L94 |
gem/oq-engine | openquake/hazardlib/source/point.py | _get_rupture_dimensions | def _get_rupture_dimensions(src, mag, nodal_plane):
"""
Calculate and return the rupture length and width
for given magnitude ``mag`` and nodal plane.
:param src:
a PointSource, AreaSource or MultiPointSource
:param mag:
a magnitude
:param nodal_plane:
Instance of :class... | python | def _get_rupture_dimensions(src, mag, nodal_plane):
area = src.magnitude_scaling_relationship.get_median_area(
mag, nodal_plane.rake)
rup_length = math.sqrt(area * src.rupture_aspect_ratio)
rup_width = area / rup_length
seismogenic_layer_width = (src.lower_seismogenic_depth
... | [
"def",
"_get_rupture_dimensions",
"(",
"src",
",",
"mag",
",",
"nodal_plane",
")",
":",
"area",
"=",
"src",
".",
"magnitude_scaling_relationship",
".",
"get_median_area",
"(",
"mag",
",",
"nodal_plane",
".",
"rake",
")",
"rup_length",
"=",
"math",
".",
"sqrt",... | Calculate and return the rupture length and width
for given magnitude ``mag`` and nodal plane.
:param src:
a PointSource, AreaSource or MultiPointSource
:param mag:
a magnitude
:param nodal_plane:
Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane`.
:returns:
... | [
"Calculate",
"and",
"return",
"the",
"rupture",
"length",
"and",
"width",
"for",
"given",
"magnitude",
"mag",
"and",
"nodal",
"plane",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/source/point.py#L29-L67 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_utils.py | tensor_components_to_use | def tensor_components_to_use(mrr, mtt, mpp, mrt, mrp, mtp):
'''
Converts components to Up, South, East definition::
USE = [[mrr, mrt, mrp],
[mtt, mtt, mtp],
[mrp, mtp, mpp]]
'''
return np.array([[mrr, mrt, mrp], [mrt, mtt, mtp], [mrp, mtp, mpp]]) | python | def tensor_components_to_use(mrr, mtt, mpp, mrt, mrp, mtp):
return np.array([[mrr, mrt, mrp], [mrt, mtt, mtp], [mrp, mtp, mpp]]) | [
"def",
"tensor_components_to_use",
"(",
"mrr",
",",
"mtt",
",",
"mpp",
",",
"mrt",
",",
"mrp",
",",
"mtp",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"mrr",
",",
"mrt",
",",
"mrp",
"]",
",",
"[",
"mrt",
",",
"mtt",
",",
"mtp",
"]",
... | Converts components to Up, South, East definition::
USE = [[mrr, mrt, mrp],
[mtt, mtt, mtp],
[mrp, mtp, mpp]] | [
"Converts",
"components",
"to",
"Up",
"South",
"East",
"definition",
"::"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L55-L63 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_utils.py | get_azimuth_plunge | def get_azimuth_plunge(vect, degrees=True):
'''
For a given vector in USE format, retrieve the azimuth and plunge
'''
if vect[0] > 0:
vect = -1. * np.copy(vect)
vect_hor = sqrt(vect[1] ** 2. + vect[2] ** 2.)
plunge = atan2(-vect[0], vect_hor)
azimuth = atan2(vect[2], -vect[1])
if... | python | def get_azimuth_plunge(vect, degrees=True):
if vect[0] > 0:
vect = -1. * np.copy(vect)
vect_hor = sqrt(vect[1] ** 2. + vect[2] ** 2.)
plunge = atan2(-vect[0], vect_hor)
azimuth = atan2(vect[2], -vect[1])
if degrees:
icr = 180. / pi
return icr * azimuth % 360., icr * plun... | [
"def",
"get_azimuth_plunge",
"(",
"vect",
",",
"degrees",
"=",
"True",
")",
":",
"if",
"vect",
"[",
"0",
"]",
">",
"0",
":",
"vect",
"=",
"-",
"1.",
"*",
"np",
".",
"copy",
"(",
"vect",
")",
"vect_hor",
"=",
"sqrt",
"(",
"vect",
"[",
"1",
"]",
... | For a given vector in USE format, retrieve the azimuth and plunge | [
"For",
"a",
"given",
"vector",
"in",
"USE",
"format",
"retrieve",
"the",
"azimuth",
"and",
"plunge"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L77-L90 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_utils.py | use_to_ned | def use_to_ned(tensor):
'''
Converts a tensor in USE coordinate sytem to NED
'''
return np.array(ROT_NED_USE.T * np.matrix(tensor) * ROT_NED_USE) | python | def use_to_ned(tensor):
return np.array(ROT_NED_USE.T * np.matrix(tensor) * ROT_NED_USE) | [
"def",
"use_to_ned",
"(",
"tensor",
")",
":",
"return",
"np",
".",
"array",
"(",
"ROT_NED_USE",
".",
"T",
"*",
"np",
".",
"matrix",
"(",
"tensor",
")",
"*",
"ROT_NED_USE",
")"
] | Converts a tensor in USE coordinate sytem to NED | [
"Converts",
"a",
"tensor",
"in",
"USE",
"coordinate",
"sytem",
"to",
"NED"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L101-L105 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_utils.py | ned_to_use | def ned_to_use(tensor):
'''
Converts a tensor in NED coordinate sytem to USE
'''
return np.array(ROT_NED_USE * np.matrix(tensor) * ROT_NED_USE.T) | python | def ned_to_use(tensor):
return np.array(ROT_NED_USE * np.matrix(tensor) * ROT_NED_USE.T) | [
"def",
"ned_to_use",
"(",
"tensor",
")",
":",
"return",
"np",
".",
"array",
"(",
"ROT_NED_USE",
"*",
"np",
".",
"matrix",
"(",
"tensor",
")",
"*",
"ROT_NED_USE",
".",
"T",
")"
] | Converts a tensor in NED coordinate sytem to USE | [
"Converts",
"a",
"tensor",
"in",
"NED",
"coordinate",
"sytem",
"to",
"USE"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L108-L112 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_utils.py | tensor_to_6component | def tensor_to_6component(tensor, frame='USE'):
'''
Returns a tensor to six component vector [Mrr, Mtt, Mpp, Mrt, Mrp, Mtp]
'''
if 'NED' in frame:
tensor = ned_to_use(tensor)
return [tensor[0, 0], tensor[1, 1], tensor[2, 2], tensor[0, 1],
tensor[0, 2], tensor[1, 2]] | python | def tensor_to_6component(tensor, frame='USE'):
if 'NED' in frame:
tensor = ned_to_use(tensor)
return [tensor[0, 0], tensor[1, 1], tensor[2, 2], tensor[0, 1],
tensor[0, 2], tensor[1, 2]] | [
"def",
"tensor_to_6component",
"(",
"tensor",
",",
"frame",
"=",
"'USE'",
")",
":",
"if",
"'NED'",
"in",
"frame",
":",
"tensor",
"=",
"ned_to_use",
"(",
"tensor",
")",
"return",
"[",
"tensor",
"[",
"0",
",",
"0",
"]",
",",
"tensor",
"[",
"1",
",",
... | Returns a tensor to six component vector [Mrr, Mtt, Mpp, Mrt, Mrp, Mtp] | [
"Returns",
"a",
"tensor",
"to",
"six",
"component",
"vector",
"[",
"Mrr",
"Mtt",
"Mpp",
"Mrt",
"Mrp",
"Mtp",
"]"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L115-L123 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_utils.py | normalise_tensor | def normalise_tensor(tensor):
'''
Normalise the tensor by dividing it by its norm, defined such that
np.sqrt(X:X)
'''
tensor_norm = np.linalg.norm(tensor)
return tensor / tensor_norm, tensor_norm | python | def normalise_tensor(tensor):
tensor_norm = np.linalg.norm(tensor)
return tensor / tensor_norm, tensor_norm | [
"def",
"normalise_tensor",
"(",
"tensor",
")",
":",
"tensor_norm",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"tensor",
")",
"return",
"tensor",
"/",
"tensor_norm",
",",
"tensor_norm"
] | Normalise the tensor by dividing it by its norm, defined such that
np.sqrt(X:X) | [
"Normalise",
"the",
"tensor",
"by",
"dividing",
"it",
"by",
"its",
"norm",
"defined",
"such",
"that",
"np",
".",
"sqrt",
"(",
"X",
":",
"X",
")"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L126-L132 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_utils.py | eigendecompose | def eigendecompose(tensor, normalise=False):
'''
Performs and eigendecomposition of the tensor and orders into
descending eigenvalues
'''
if normalise:
tensor, tensor_norm = normalise_tensor(tensor)
else:
tensor_norm = 1.
eigvals, eigvects = np.linalg.eigh(tensor, UPLO='U')
... | python | def eigendecompose(tensor, normalise=False):
if normalise:
tensor, tensor_norm = normalise_tensor(tensor)
else:
tensor_norm = 1.
eigvals, eigvects = np.linalg.eigh(tensor, UPLO='U')
isrt = np.argsort(eigvals)
eigenvalues = eigvals[isrt] * tensor_norm
eigenvectors = eigvect... | [
"def",
"eigendecompose",
"(",
"tensor",
",",
"normalise",
"=",
"False",
")",
":",
"if",
"normalise",
":",
"tensor",
",",
"tensor_norm",
"=",
"normalise_tensor",
"(",
"tensor",
")",
"else",
":",
"tensor_norm",
"=",
"1.",
"eigvals",
",",
"eigvects",
"=",
"np... | Performs and eigendecomposition of the tensor and orders into
descending eigenvalues | [
"Performs",
"and",
"eigendecomposition",
"of",
"the",
"tensor",
"and",
"orders",
"into",
"descending",
"eigenvalues"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L135-L150 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_utils.py | matrix_to_euler | def matrix_to_euler(rotmat):
'''Inverse of euler_to_matrix().'''
if not isinstance(rotmat, np.matrixlib.defmatrix.matrix):
# As this calculation relies on np.matrix algebra - convert array to
# matrix
rotmat = np.matrix(rotmat)
def cvec(x, y, z):
return np.matrix([[x, y, z]]... | python | def matrix_to_euler(rotmat):
if not isinstance(rotmat, np.matrixlib.defmatrix.matrix):
rotmat = np.matrix(rotmat)
def cvec(x, y, z):
return np.matrix([[x, y, z]]).T
ex = cvec(1., 0., 0.)
ez = cvec(0., 0., 1.)
exs = rotmat.T * ex
ezs = rotmat.T * ez
eno... | [
"def",
"matrix_to_euler",
"(",
"rotmat",
")",
":",
"if",
"not",
"isinstance",
"(",
"rotmat",
",",
"np",
".",
"matrixlib",
".",
"defmatrix",
".",
"matrix",
")",
":",
"# As this calculation relies on np.matrix algebra - convert array to",
"# matrix",
"rotmat",
"=",
"n... | Inverse of euler_to_matrix(). | [
"Inverse",
"of",
"euler_to_matrix",
"()",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L153-L178 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_utils.py | unique_euler | def unique_euler(alpha, beta, gamma):
'''
Uniquify euler angle triplet.
Put euler angles into ranges compatible with (dip,strike,-rake)
in seismology:
alpha (dip) : [0, pi/2]
beta (strike) : [0, 2*pi)
gamma (-rake) : [-pi, pi)
If alpha is near to zero, beta is replaced by beta+gamma and ... | python | def unique_euler(alpha, beta, gamma):
alpha = np.mod(alpha, 2.0 * pi)
if 0.5 * pi < alpha and alpha <= pi:
alpha = pi - alpha
beta = beta + pi
gamma = 2.0 * pi - gamma
elif pi < alpha and alpha <= 1.5 * pi:
alpha = alpha - pi
gamma = pi - gamma
elif 1.5 * p... | [
"def",
"unique_euler",
"(",
"alpha",
",",
"beta",
",",
"gamma",
")",
":",
"alpha",
"=",
"np",
".",
"mod",
"(",
"alpha",
",",
"2.0",
"*",
"pi",
")",
"if",
"0.5",
"*",
"pi",
"<",
"alpha",
"and",
"alpha",
"<=",
"pi",
":",
"alpha",
"=",
"pi",
"-",
... | Uniquify euler angle triplet.
Put euler angles into ranges compatible with (dip,strike,-rake)
in seismology:
alpha (dip) : [0, pi/2]
beta (strike) : [0, 2*pi)
gamma (-rake) : [-pi, pi)
If alpha is near to zero, beta is replaced by beta+gamma and gamma is set
to zero, to prevent that addition... | [
"Uniquify",
"euler",
"angle",
"triplet",
".",
"Put",
"euler",
"angles",
"into",
"ranges",
"compatible",
"with",
"(",
"dip",
"strike",
"-",
"rake",
")",
"in",
"seismology",
":",
"alpha",
"(",
"dip",
")",
":",
"[",
"0",
"pi",
"/",
"2",
"]",
"beta",
"("... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L181-L238 |
gem/oq-engine | openquake/hmtk/seismicity/gcmt_utils.py | moment_magnitude_scalar | def moment_magnitude_scalar(moment):
'''
Uses Hanks & Kanamori formula for calculating moment magnitude from
a scalar moment (Nm)
'''
if isinstance(moment, np.ndarray):
return (2. / 3.) * (np.log10(moment) - 9.05)
else:
return (2. / 3.) * (log10(moment) - 9.05) | python | def moment_magnitude_scalar(moment):
if isinstance(moment, np.ndarray):
return (2. / 3.) * (np.log10(moment) - 9.05)
else:
return (2. / 3.) * (log10(moment) - 9.05) | [
"def",
"moment_magnitude_scalar",
"(",
"moment",
")",
":",
"if",
"isinstance",
"(",
"moment",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"(",
"2.",
"/",
"3.",
")",
"*",
"(",
"np",
".",
"log10",
"(",
"moment",
")",
"-",
"9.05",
")",
"else",
":",... | Uses Hanks & Kanamori formula for calculating moment magnitude from
a scalar moment (Nm) | [
"Uses",
"Hanks",
"&",
"Kanamori",
"formula",
"for",
"calculating",
"moment",
"magnitude",
"from",
"a",
"scalar",
"moment",
"(",
"Nm",
")"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L241-L249 |
gem/oq-engine | openquake/hazardlib/gsim/boore_atkinson_2008.py | BooreAtkinson2008.get_mean_and_stddevs | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
#... | python | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
C = self.COEFFS[imt]
C_SR = self.COEFFS_SOIL_RESPONSE[imt]
pga4nl = self._get_pga_on_rock(rup, dists, C)
if imt == PGA():
... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"# extracting dictionary of coefficients specific to required",
"# intensity measure type.",
"C",
"=",
"self",
".",
"COEFFS",
"[",
"imt",
"... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. | [
"See",
":",
"meth",
":",
"superclass",
"method",
"<",
".",
"base",
".",
"GroundShakingIntensityModel",
".",
"get_mean_and_stddevs",
">",
"for",
"spec",
"of",
"input",
"and",
"result",
"values",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_atkinson_2008.py#L78-L113 |
gem/oq-engine | openquake/hazardlib/gsim/boore_atkinson_2008.py | BooreAtkinson2008._compute_distance_scaling | def _compute_distance_scaling(self, rup, dists, C):
"""
Compute distance-scaling term, equations (3) and (4), pag 107.
"""
Mref = 4.5
Rref = 1.0
R = np.sqrt(dists.rjb ** 2 + C['h'] ** 2)
return (C['c1'] + C['c2'] * (rup.mag - Mref)) * np.log(R / Rref) + \
... | python | def _compute_distance_scaling(self, rup, dists, C):
Mref = 4.5
Rref = 1.0
R = np.sqrt(dists.rjb ** 2 + C['h'] ** 2)
return (C['c1'] + C['c2'] * (rup.mag - Mref)) * np.log(R / Rref) + \
C['c3'] * (R - Rref) | [
"def",
"_compute_distance_scaling",
"(",
"self",
",",
"rup",
",",
"dists",
",",
"C",
")",
":",
"Mref",
"=",
"4.5",
"Rref",
"=",
"1.0",
"R",
"=",
"np",
".",
"sqrt",
"(",
"dists",
".",
"rjb",
"**",
"2",
"+",
"C",
"[",
"'h'",
"]",
"**",
"2",
")",
... | Compute distance-scaling term, equations (3) and (4), pag 107. | [
"Compute",
"distance",
"-",
"scaling",
"term",
"equations",
"(",
"3",
")",
"and",
"(",
"4",
")",
"pag",
"107",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_atkinson_2008.py#L130-L138 |
gem/oq-engine | openquake/hazardlib/gsim/boore_atkinson_2008.py | BooreAtkinson2008._compute_magnitude_scaling | def _compute_magnitude_scaling(self, rup, C):
"""
Compute magnitude-scaling term, equations (5a) and (5b), pag 107.
"""
U, SS, NS, RS = self._get_fault_type_dummy_variables(rup)
if rup.mag <= C['Mh']:
return C['e1'] * U + C['e2'] * SS + C['e3'] * NS + C['e4'] * RS + \... | python | def _compute_magnitude_scaling(self, rup, C):
U, SS, NS, RS = self._get_fault_type_dummy_variables(rup)
if rup.mag <= C['Mh']:
return C['e1'] * U + C['e2'] * SS + C['e3'] * NS + C['e4'] * RS + \
C['e5'] * (rup.mag - C['Mh']) + \
C['e6'] * (rup.mag - C... | [
"def",
"_compute_magnitude_scaling",
"(",
"self",
",",
"rup",
",",
"C",
")",
":",
"U",
",",
"SS",
",",
"NS",
",",
"RS",
"=",
"self",
".",
"_get_fault_type_dummy_variables",
"(",
"rup",
")",
"if",
"rup",
".",
"mag",
"<=",
"C",
"[",
"'Mh'",
"]",
":",
... | Compute magnitude-scaling term, equations (5a) and (5b), pag 107. | [
"Compute",
"magnitude",
"-",
"scaling",
"term",
"equations",
"(",
"5a",
")",
"and",
"(",
"5b",
")",
"pag",
"107",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_atkinson_2008.py#L140-L151 |
gem/oq-engine | openquake/hazardlib/gsim/boore_atkinson_2008.py | BooreAtkinson2008._get_pga_on_rock | def _get_pga_on_rock(self, rup, dists, _C):
"""
Compute and return PGA on rock conditions (that is vs30 = 760.0 m/s).
This is needed to compute non-linear site amplification term
"""
# Median PGA in g for Vref = 760.0, without site amplification,
# that is equation (1) pa... | python | def _get_pga_on_rock(self, rup, dists, _C):
C_pga = self.COEFFS[PGA()]
pga4nl = np.exp(self._compute_magnitude_scaling(rup, C_pga) +
self._compute_distance_scaling(rup, dists, C_pga... | [
"def",
"_get_pga_on_rock",
"(",
"self",
",",
"rup",
",",
"dists",
",",
"_C",
")",
":",
"# Median PGA in g for Vref = 760.0, without site amplification,",
"# that is equation (1) pag 106, without the third and fourth terms",
"# Mref and Rref values are given in the caption to table 6, pag... | Compute and return PGA on rock conditions (that is vs30 = 760.0 m/s).
This is needed to compute non-linear site amplification term | [
"Compute",
"and",
"return",
"PGA",
"on",
"rock",
"conditions",
"(",
"that",
"is",
"vs30",
"=",
"760",
".",
"0",
"m",
"/",
"s",
")",
".",
"This",
"is",
"needed",
"to",
"compute",
"non",
"-",
"linear",
"site",
"amplification",
"term"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_atkinson_2008.py#L187-L206 |
gem/oq-engine | openquake/hazardlib/gsim/boore_atkinson_2008.py | BooreAtkinson2008._get_site_amplification_non_linear | def _get_site_amplification_non_linear(self, vs30, pga4nl, C):
"""
Compute site amplification non-linear term,
equations (8a) to (13d), pag 108-109.
"""
# non linear slope
bnl = self._compute_non_linear_slope(vs30, C)
# compute the actual non-linear term
r... | python | def _get_site_amplification_non_linear(self, vs30, pga4nl, C):
bnl = self._compute_non_linear_slope(vs30, C)
return self._compute_non_linear_term(pga4nl, bnl) | [
"def",
"_get_site_amplification_non_linear",
"(",
"self",
",",
"vs30",
",",
"pga4nl",
",",
"C",
")",
":",
"# non linear slope",
"bnl",
"=",
"self",
".",
"_compute_non_linear_slope",
"(",
"vs30",
",",
"C",
")",
"# compute the actual non-linear term",
"return",
"self"... | Compute site amplification non-linear term,
equations (8a) to (13d), pag 108-109. | [
"Compute",
"site",
"amplification",
"non",
"-",
"linear",
"term",
"equations",
"(",
"8a",
")",
"to",
"(",
"13d",
")",
"pag",
"108",
"-",
"109",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_atkinson_2008.py#L208-L216 |
gem/oq-engine | openquake/hazardlib/gsim/boore_atkinson_2008.py | BooreAtkinson2008._compute_non_linear_slope | def _compute_non_linear_slope(self, vs30, C):
"""
Compute non-linear slope factor,
equations (13a) to (13d), pag 108-109.
"""
V1 = 180.0
V2 = 300.0
Vref = 760.0
# equation (13d), values are zero for vs30 >= Vref = 760.0
bnl = np.zeros(vs30.shape)
... | python | def _compute_non_linear_slope(self, vs30, C):
V1 = 180.0
V2 = 300.0
Vref = 760.0
bnl = np.zeros(vs30.shape)
idx = vs30 <= V1
bnl[idx] = C['b1']
idx = np.where((vs30 > V1) & (vs30 <= V2))
bnl[idx] = (C['b1'] - C['b2'])... | [
"def",
"_compute_non_linear_slope",
"(",
"self",
",",
"vs30",
",",
"C",
")",
":",
"V1",
"=",
"180.0",
"V2",
"=",
"300.0",
"Vref",
"=",
"760.0",
"# equation (13d), values are zero for vs30 >= Vref = 760.0",
"bnl",
"=",
"np",
".",
"zeros",
"(",
"vs30",
".",
"sha... | Compute non-linear slope factor,
equations (13a) to (13d), pag 108-109. | [
"Compute",
"non",
"-",
"linear",
"slope",
"factor",
"equations",
"(",
"13a",
")",
"to",
"(",
"13d",
")",
"pag",
"108",
"-",
"109",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_atkinson_2008.py#L218-L242 |
gem/oq-engine | openquake/hazardlib/gsim/boore_atkinson_2008.py | BooreAtkinson2008._compute_non_linear_term | def _compute_non_linear_term(self, pga4nl, bnl):
"""
Compute non-linear term,
equation (8a) to (8c), pag 108.
"""
fnl = np.zeros(pga4nl.shape)
a1 = 0.03
a2 = 0.09
pga_low = 0.06
# equation (8a)
idx = pga4nl <= a1
fnl[idx] = bnl[id... | python | def _compute_non_linear_term(self, pga4nl, bnl):
fnl = np.zeros(pga4nl.shape)
a1 = 0.03
a2 = 0.09
pga_low = 0.06
idx = pga4nl <= a1
fnl[idx] = bnl[idx] * np.log(pga_low / 0.1)
idx = np.where((pga4nl > a1) & (pga4nl <= a2))
del... | [
"def",
"_compute_non_linear_term",
"(",
"self",
",",
"pga4nl",
",",
"bnl",
")",
":",
"fnl",
"=",
"np",
".",
"zeros",
"(",
"pga4nl",
".",
"shape",
")",
"a1",
"=",
"0.03",
"a2",
"=",
"0.09",
"pga_low",
"=",
"0.06",
"# equation (8a)",
"idx",
"=",
"pga4nl"... | Compute non-linear term,
equation (8a) to (8c), pag 108. | [
"Compute",
"non",
"-",
"linear",
"term",
"equation",
"(",
"8a",
")",
"to",
"(",
"8c",
")",
"pag",
"108",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_atkinson_2008.py#L244-L273 |
gem/oq-engine | openquake/hazardlib/gsim/boore_atkinson_2008.py | Atkinson2010Hawaii.get_mean_and_stddevs | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
Using a frequency dependent correction for the mean ground motion.
Standard deviation is fixed.
"""
mean, stddevs = super().get_mean_and_stddevs(sites, rup, dists,
... | python | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
mean, stddevs = super().get_mean_and_stddevs(sites, rup, dists,
imt, stddev_types)
if imt == PGA():
freq = 50.0
elif imt == PGV():
... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"mean",
",",
"stddevs",
"=",
"super",
"(",
")",
".",
"get_mean_and_stddevs",
"(",
"sites",
",",
"rup",
",",
"dists",
",",
"im... | Using a frequency dependent correction for the mean ground motion.
Standard deviation is fixed. | [
"Using",
"a",
"frequency",
"dependent",
"correction",
"for",
"the",
"mean",
"ground",
"motion",
".",
"Standard",
"deviation",
"is",
"fixed",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_atkinson_2008.py#L383-L416 |
gem/oq-engine | openquake/hazardlib/gsim/boore_atkinson_2008.py | Atkinson2010Hawaii._get_stddevs | def _get_stddevs(self, C, stddev_types, num_sites):
"""
Return total standard deviation.
"""
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
for stddev_type in stddev_types)
# Using a frequency independent value of sigma as recommended
... | python | def _get_stddevs(self, C, stddev_types, num_sites):
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
for stddev_type in stddev_types)
stddevs = [0.26/np.log10(np.e) + np.zeros(num_sites)]
return stddevs | [
"def",
"_get_stddevs",
"(",
"self",
",",
"C",
",",
"stddev_types",
",",
"num_sites",
")",
":",
"assert",
"all",
"(",
"stddev_type",
"in",
"self",
".",
"DEFINED_FOR_STANDARD_DEVIATION_TYPES",
"for",
"stddev_type",
"in",
"stddev_types",
")",
"# Using a frequency indep... | Return total standard deviation. | [
"Return",
"total",
"standard",
"deviation",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_atkinson_2008.py#L418-L429 |
gem/oq-engine | openquake/commonlib/rlzs_assoc.py | accept_path | def accept_path(path, ref_path):
"""
:param path: a logic tree path (list or tuple of strings)
:param ref_path: reference logic tree path
:returns: True if `path` is consistent with `ref_path`, False otherwise
>>> accept_path(['SM2'], ('SM2', 'a3b1'))
False
>>> accept_path(['SM2', '@'], ('S... | python | def accept_path(path, ref_path):
if len(path) != len(ref_path):
return False
for a, b in zip(path, ref_path):
if a != '@' and a != b:
return False
return True | [
"def",
"accept_path",
"(",
"path",
",",
"ref_path",
")",
":",
"if",
"len",
"(",
"path",
")",
"!=",
"len",
"(",
"ref_path",
")",
":",
"return",
"False",
"for",
"a",
",",
"b",
"in",
"zip",
"(",
"path",
",",
"ref_path",
")",
":",
"if",
"a",
"!=",
... | :param path: a logic tree path (list or tuple of strings)
:param ref_path: reference logic tree path
:returns: True if `path` is consistent with `ref_path`, False otherwise
>>> accept_path(['SM2'], ('SM2', 'a3b1'))
False
>>> accept_path(['SM2', '@'], ('SM2', 'a3b1'))
True
>>> accept_path(['... | [
":",
"param",
"path",
":",
"a",
"logic",
"tree",
"path",
"(",
"list",
"or",
"tuple",
"of",
"strings",
")",
":",
"param",
"ref_path",
":",
"reference",
"logic",
"tree",
"path",
":",
"returns",
":",
"True",
"if",
"path",
"is",
"consistent",
"with",
"ref_... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/rlzs_assoc.py#L226-L246 |
gem/oq-engine | openquake/commonlib/rlzs_assoc.py | get_rlzs_assoc | def get_rlzs_assoc(cinfo, sm_lt_path=None, trts=None):
"""
:param cinfo: a :class:`openquake.commonlib.source.CompositionInfo`
:param sm_lt_path: logic tree path tuple used to select a source model
:param trts: tectonic region types to accept
"""
assoc = RlzsAssoc(cinfo)
offset = 0
trtse... | python | def get_rlzs_assoc(cinfo, sm_lt_path=None, trts=None):
assoc = RlzsAssoc(cinfo)
offset = 0
trtset = set(cinfo.gsim_lt.values)
for smodel in cinfo.source_models:
if sm_lt_path and not accept_path(smodel.path, sm_lt_path):
continue
trts_ = set()
... | [
"def",
"get_rlzs_assoc",
"(",
"cinfo",
",",
"sm_lt_path",
"=",
"None",
",",
"trts",
"=",
"None",
")",
":",
"assoc",
"=",
"RlzsAssoc",
"(",
"cinfo",
")",
"offset",
"=",
"0",
"trtset",
"=",
"set",
"(",
"cinfo",
".",
"gsim_lt",
".",
"values",
")",
"for"... | :param cinfo: a :class:`openquake.commonlib.source.CompositionInfo`
:param sm_lt_path: logic tree path tuple used to select a source model
:param trts: tectonic region types to accept | [
":",
"param",
"cinfo",
":",
"a",
":",
"class",
":",
"openquake",
".",
"commonlib",
".",
"source",
".",
"CompositionInfo",
":",
"param",
"sm_lt_path",
":",
"logic",
"tree",
"path",
"tuple",
"used",
"to",
"select",
"a",
"source",
"model",
":",
"param",
"tr... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/rlzs_assoc.py#L249-L292 |
gem/oq-engine | openquake/commonlib/rlzs_assoc.py | RlzsAssoc.get_rlzs_by_gsim | def get_rlzs_by_gsim(self, trt_or_grp_id, sm_id=None):
"""
:param trt_or_grp_id: a tectonic region type or a source group ID
:param sm_id: source model ordinal (or None)
:returns: a dictionary gsim -> rlzs
"""
if isinstance(trt_or_grp_id, (int, U16, U32)): # grp_id
... | python | def get_rlzs_by_gsim(self, trt_or_grp_id, sm_id=None):
if isinstance(trt_or_grp_id, (int, U16, U32)):
trt = self.csm_info.trt_by_grp[trt_or_grp_id]
sm_id = self.csm_info.get_sm_by_grp()[trt_or_grp_id]
else:
trt = trt_or_grp_id
acc = collections.de... | [
"def",
"get_rlzs_by_gsim",
"(",
"self",
",",
"trt_or_grp_id",
",",
"sm_id",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"trt_or_grp_id",
",",
"(",
"int",
",",
"U16",
",",
"U32",
")",
")",
":",
"# grp_id",
"trt",
"=",
"self",
".",
"csm_info",
".",
... | :param trt_or_grp_id: a tectonic region type or a source group ID
:param sm_id: source model ordinal (or None)
:returns: a dictionary gsim -> rlzs | [
":",
"param",
"trt_or_grp_id",
":",
"a",
"tectonic",
"region",
"type",
"or",
"a",
"source",
"group",
"ID",
":",
"param",
"sm_id",
":",
"source",
"model",
"ordinal",
"(",
"or",
"None",
")",
":",
"returns",
":",
"a",
"dictionary",
"gsim",
"-",
">",
"rlzs... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/rlzs_assoc.py#L102-L126 |
gem/oq-engine | openquake/commonlib/rlzs_assoc.py | RlzsAssoc.by_grp | def by_grp(self):
"""
:returns: a dictionary grp -> rlzis
"""
dic = {} # grp -> [(gsim_idx, rlzis), ...]
for sm in self.csm_info.source_models:
for sg in sm.src_groups:
if not sg.eff_ruptures:
continue
rlzs_by_gsim ... | python | def by_grp(self):
dic = {}
for sm in self.csm_info.source_models:
for sg in sm.src_groups:
if not sg.eff_ruptures:
continue
rlzs_by_gsim = self.get_rlzs_by_gsim(sg.trt, sm.ordinal)
if not rlzs_by_gsim:
... | [
"def",
"by_grp",
"(",
"self",
")",
":",
"dic",
"=",
"{",
"}",
"# grp -> [(gsim_idx, rlzis), ...]",
"for",
"sm",
"in",
"self",
".",
"csm_info",
".",
"source_models",
":",
"for",
"sg",
"in",
"sm",
".",
"src_groups",
":",
"if",
"not",
"sg",
".",
"eff_ruptur... | :returns: a dictionary grp -> rlzis | [
":",
"returns",
":",
"a",
"dictionary",
"grp",
"-",
">",
"rlzis"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/rlzs_assoc.py#L128-L142 |
gem/oq-engine | openquake/commonlib/rlzs_assoc.py | RlzsAssoc._init | def _init(self):
"""
Finalize the initialization of the RlzsAssoc object by setting
the (reduced) weights of the realizations.
"""
if self.num_samples:
assert len(self.realizations) == self.num_samples, (
len(self.realizations), self.num_samples)
... | python | def _init(self):
if self.num_samples:
assert len(self.realizations) == self.num_samples, (
len(self.realizations), self.num_samples)
for rlz in self.realizations:
for k in rlz.weight.dic:
rlz.weight.dic[k] = 1. / self.num_sampl... | [
"def",
"_init",
"(",
"self",
")",
":",
"if",
"self",
".",
"num_samples",
":",
"assert",
"len",
"(",
"self",
".",
"realizations",
")",
"==",
"self",
".",
"num_samples",
",",
"(",
"len",
"(",
"self",
".",
"realizations",
")",
",",
"self",
".",
"num_sam... | Finalize the initialization of the RlzsAssoc object by setting
the (reduced) weights of the realizations. | [
"Finalize",
"the",
"initialization",
"of",
"the",
"RlzsAssoc",
"object",
"by",
"setting",
"the",
"(",
"reduced",
")",
"weights",
"of",
"the",
"realizations",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/rlzs_assoc.py#L144-L161 |
gem/oq-engine | openquake/commonlib/rlzs_assoc.py | RlzsAssoc.combine_pmaps | def combine_pmaps(self, pmap_by_grp):
"""
:param pmap_by_grp: dictionary group string -> probability map
:returns: a list of probability maps, one per realization
"""
grp = list(pmap_by_grp)[0] # pmap_by_grp must be non-empty
num_levels = pmap_by_grp[grp].shape_y
... | python | def combine_pmaps(self, pmap_by_grp):
grp = list(pmap_by_grp)[0]
num_levels = pmap_by_grp[grp].shape_y
pmaps = [probability_map.ProbabilityMap(num_levels, 1)
for _ in self.realizations]
array = self.by_grp()
for grp in pmap_by_grp:
for gsim... | [
"def",
"combine_pmaps",
"(",
"self",
",",
"pmap_by_grp",
")",
":",
"grp",
"=",
"list",
"(",
"pmap_by_grp",
")",
"[",
"0",
"]",
"# pmap_by_grp must be non-empty",
"num_levels",
"=",
"pmap_by_grp",
"[",
"grp",
"]",
".",
"shape_y",
"pmaps",
"=",
"[",
"probabili... | :param pmap_by_grp: dictionary group string -> probability map
:returns: a list of probability maps, one per realization | [
":",
"param",
"pmap_by_grp",
":",
"dictionary",
"group",
"string",
"-",
">",
"probability",
"map",
":",
"returns",
":",
"a",
"list",
"of",
"probability",
"maps",
"one",
"per",
"realization"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/rlzs_assoc.py#L173-L188 |
gem/oq-engine | openquake/commonlib/rlzs_assoc.py | RlzsAssoc.get_rlz | def get_rlz(self, rlzstr):
r"""
Get a Realization instance for a string of the form 'rlz-\d+'
"""
mo = re.match(r'rlz-(\d+)', rlzstr)
if not mo:
return
return self.realizations[int(mo.group(1))] | python | def get_rlz(self, rlzstr):
r
mo = re.match(r'rlz-(\d+)', rlzstr)
if not mo:
return
return self.realizations[int(mo.group(1))] | [
"def",
"get_rlz",
"(",
"self",
",",
"rlzstr",
")",
":",
"mo",
"=",
"re",
".",
"match",
"(",
"r'rlz-(\\d+)'",
",",
"rlzstr",
")",
"if",
"not",
"mo",
":",
"return",
"return",
"self",
".",
"realizations",
"[",
"int",
"(",
"mo",
".",
"group",
"(",
"1",... | r"""
Get a Realization instance for a string of the form 'rlz-\d+' | [
"r",
"Get",
"a",
"Realization",
"instance",
"for",
"a",
"string",
"of",
"the",
"form",
"rlz",
"-",
"\\",
"d",
"+"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/rlzs_assoc.py#L190-L197 |
gem/oq-engine | openquake/commands/export.py | export | def export(datastore_key, calc_id=-1, exports='csv', export_dir='.'):
"""
Export an output from the datastore.
"""
dstore = util.read(calc_id)
parent_id = dstore['oqparam'].hazard_calculation_id
if parent_id:
dstore.parent = util.read(parent_id)
dstore.export_dir = export_dir
... | python | def export(datastore_key, calc_id=-1, exports='csv', export_dir='.'):
dstore = util.read(calc_id)
parent_id = dstore['oqparam'].hazard_calculation_id
if parent_id:
dstore.parent = util.read(parent_id)
dstore.export_dir = export_dir
with performance.Monitor('export', measuremem=True)... | [
"def",
"export",
"(",
"datastore_key",
",",
"calc_id",
"=",
"-",
"1",
",",
"exports",
"=",
"'csv'",
",",
"export_dir",
"=",
"'.'",
")",
":",
"dstore",
"=",
"util",
".",
"read",
"(",
"calc_id",
")",
"parent_id",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"... | Export an output from the datastore. | [
"Export",
"an",
"output",
"from",
"the",
"datastore",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/export.py#L27-L43 |
gem/oq-engine | openquake/calculators/ucerf_base.py | convert_UCERFSource | def convert_UCERFSource(self, node):
"""
Converts the Ucerf Source node into an SES Control object
"""
dirname = os.path.dirname(self.fname) # where the source_model_file is
source_file = os.path.join(dirname, node["filename"])
if "startDate" in node.attrib and "investigationTime" in node.attri... | python | def convert_UCERFSource(self, node):
dirname = os.path.dirname(self.fname)
source_file = os.path.join(dirname, node["filename"])
if "startDate" in node.attrib and "investigationTime" in node.attrib:
inv_time = float(node["investigationTime"])
if inv_time != ... | [
"def",
"convert_UCERFSource",
"(",
"self",
",",
"node",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"fname",
")",
"# where the source_model_file is",
"source_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
","... | Converts the Ucerf Source node into an SES Control object | [
"Converts",
"the",
"Ucerf",
"Source",
"node",
"into",
"an",
"SES",
"Control",
"object"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L58-L88 |
gem/oq-engine | openquake/calculators/ucerf_base.py | build_idx_set | def build_idx_set(branch_id, start_date):
"""
Builds a dictionary of keys based on the branch code
"""
code_set = branch_id.split("/")
code_set.insert(3, "Rates")
idx_set = {
"sec": "/".join([code_set[0], code_set[1], "Sections"]),
"mag": "/".join([code_set[0], code_set[1], code_... | python | def build_idx_set(branch_id, start_date):
code_set = branch_id.split("/")
code_set.insert(3, "Rates")
idx_set = {
"sec": "/".join([code_set[0], code_set[1], "Sections"]),
"mag": "/".join([code_set[0], code_set[1], code_set[2], "Magnitude"])}
idx_set["rate"] = "/".join(code_set)
... | [
"def",
"build_idx_set",
"(",
"branch_id",
",",
"start_date",
")",
":",
"code_set",
"=",
"branch_id",
".",
"split",
"(",
"\"/\"",
")",
"code_set",
".",
"insert",
"(",
"3",
",",
"\"Rates\"",
")",
"idx_set",
"=",
"{",
"\"sec\"",
":",
"\"/\"",
".",
"join",
... | Builds a dictionary of keys based on the branch code | [
"Builds",
"a",
"dictionary",
"of",
"keys",
"based",
"on",
"the",
"branch",
"code"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L433-L452 |
gem/oq-engine | openquake/calculators/ucerf_base.py | get_rupture_dimensions | def get_rupture_dimensions(mag, nodal_plane, msr, rupture_aspect_ratio,
upper_seismogenic_depth, lower_seismogenic_depth):
"""
Calculate and return the rupture length and width
for given magnitude ``mag`` and nodal plane.
:param nodal_plane:
Instance of :class:`openqu... | python | def get_rupture_dimensions(mag, nodal_plane, msr, rupture_aspect_ratio,
upper_seismogenic_depth, lower_seismogenic_depth):
area = msr.get_median_area(mag, nodal_plane.rake)
rup_length = math.sqrt(area * rupture_aspect_ratio)
rup_width = area / rup_length
seismogenic_layer... | [
"def",
"get_rupture_dimensions",
"(",
"mag",
",",
"nodal_plane",
",",
"msr",
",",
"rupture_aspect_ratio",
",",
"upper_seismogenic_depth",
",",
"lower_seismogenic_depth",
")",
":",
"area",
"=",
"msr",
".",
"get_median_area",
"(",
"mag",
",",
"nodal_plane",
".",
"ra... | Calculate and return the rupture length and width
for given magnitude ``mag`` and nodal plane.
:param nodal_plane:
Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane`.
:returns:
Tuple of two items: rupture length in width in km.
The rupture area is calculated using metho... | [
"Calculate",
"and",
"return",
"the",
"rupture",
"length",
"and",
"width",
"for",
"given",
"magnitude",
"mag",
"and",
"nodal",
"plane",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L455-L489 |
gem/oq-engine | openquake/calculators/ucerf_base.py | get_rupture_surface | def get_rupture_surface(mag, nodal_plane, hypocenter, msr,
rupture_aspect_ratio, upper_seismogenic_depth,
lower_seismogenic_depth, mesh_spacing=1.0):
"""
Create and return rupture surface object with given properties.
:param mag:
Magnitude value, used... | python | def get_rupture_surface(mag, nodal_plane, hypocenter, msr,
rupture_aspect_ratio, upper_seismogenic_depth,
lower_seismogenic_depth, mesh_spacing=1.0):
assert (upper_seismogenic_depth <= hypocenter.depth
and lower_seismogenic_depth >= hypocenter.depth)
... | [
"def",
"get_rupture_surface",
"(",
"mag",
",",
"nodal_plane",
",",
"hypocenter",
",",
"msr",
",",
"rupture_aspect_ratio",
",",
"upper_seismogenic_depth",
",",
"lower_seismogenic_depth",
",",
"mesh_spacing",
"=",
"1.0",
")",
":",
"assert",
"(",
"upper_seismogenic_depth... | Create and return rupture surface object with given properties.
:param mag:
Magnitude value, used to calculate rupture dimensions,
see :meth:`_get_rupture_dimensions`.
:param nodal_plane:
Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane`
describing the rupture o... | [
"Create",
"and",
"return",
"rupture",
"surface",
"object",
"with",
"given",
"properties",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L492-L593 |
gem/oq-engine | openquake/calculators/ucerf_base.py | generate_background_ruptures | def generate_background_ruptures(tom, locations, occurrence, mag, npd,
hdd, upper_seismogenic_depth,
lower_seismogenic_depth, msr=WC1994(),
aspect=1.5, trt=DEFAULT_TRT):
"""
:param tom:
Temporal occurrence... | python | def generate_background_ruptures(tom, locations, occurrence, mag, npd,
hdd, upper_seismogenic_depth,
lower_seismogenic_depth, msr=WC1994(),
aspect=1.5, trt=DEFAULT_TRT):
ruptures = []
n_vals = len(locations)
... | [
"def",
"generate_background_ruptures",
"(",
"tom",
",",
"locations",
",",
"occurrence",
",",
"mag",
",",
"npd",
",",
"hdd",
",",
"upper_seismogenic_depth",
",",
"lower_seismogenic_depth",
",",
"msr",
"=",
"WC1994",
"(",
")",
",",
"aspect",
"=",
"1.5",
",",
"... | :param tom:
Temporal occurrence model as instance of :class:
openquake.hazardlib.tom.TOM
:param numpy.ndarray locations:
Array of locations [Longitude, Latitude] of the point sources
:param numpy.ndarray occurrence:
Annual rates of occurrence
:param float mag:
Magnitu... | [
":",
"param",
"tom",
":",
"Temporal",
"occurrence",
"model",
"as",
"instance",
"of",
":",
"class",
":",
"openquake",
".",
"hazardlib",
".",
"tom",
".",
"TOM",
":",
"param",
"numpy",
".",
"ndarray",
"locations",
":",
"Array",
"of",
"locations",
"[",
"Long... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L596-L644 |
gem/oq-engine | openquake/calculators/ucerf_base.py | UcerfFilter.get_indices | def get_indices(self, src, ridx, mag):
"""
:param src: an UCERF source
:param ridx: a set of rupture indices
:param mag: magnitude to use to compute the integration distance
:returns: array with the IDs of the sites close to the ruptures
"""
centroids = src.get_ce... | python | def get_indices(self, src, ridx, mag):
centroids = src.get_centroids(ridx)
mindistance = min_geodetic_distance(
(centroids[:, 0], centroids[:, 1]), self.sitecol.xyz)
idist = self.integration_distance(DEFAULT_TRT, mag)
indices, = (mindistance <= idist).nonzero()
... | [
"def",
"get_indices",
"(",
"self",
",",
"src",
",",
"ridx",
",",
"mag",
")",
":",
"centroids",
"=",
"src",
".",
"get_centroids",
"(",
"ridx",
")",
"mindistance",
"=",
"min_geodetic_distance",
"(",
"(",
"centroids",
"[",
":",
",",
"0",
"]",
",",
"centro... | :param src: an UCERF source
:param ridx: a set of rupture indices
:param mag: magnitude to use to compute the integration distance
:returns: array with the IDs of the sites close to the ruptures | [
":",
"param",
"src",
":",
"an",
"UCERF",
"source",
":",
"param",
"ridx",
":",
"a",
"set",
"of",
"rupture",
"indices",
":",
"param",
"mag",
":",
"magnitude",
"to",
"use",
"to",
"compute",
"the",
"integration",
"distance",
":",
"returns",
":",
"array",
"... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L126-L138 |
gem/oq-engine | openquake/calculators/ucerf_base.py | UCERFSource.new | def new(self, grp_id, branch_id):
"""
:param grp_id: ordinal of the source group
:param branch_name: name of the UCERF branch
:param branch_id: string associated to the branch
:returns: a new UCERFSource associated to the branch_id
"""
new = copy.copy(self)
... | python | def new(self, grp_id, branch_id):
new = copy.copy(self)
new.orig = new
new.src_group_id = grp_id
new.source_id = branch_id
new.idx_set = build_idx_set(branch_id, self.start_date)
with h5py.File(self.source_file, "r") as hdf5:
new.start = 0
... | [
"def",
"new",
"(",
"self",
",",
"grp_id",
",",
"branch_id",
")",
":",
"new",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"new",
".",
"orig",
"=",
"new",
"new",
".",
"src_group_id",
"=",
"grp_id",
"new",
".",
"source_id",
"=",
"branch_id",
"new",
".... | :param grp_id: ordinal of the source group
:param branch_name: name of the UCERF branch
:param branch_id: string associated to the branch
:returns: a new UCERFSource associated to the branch_id | [
":",
"param",
"grp_id",
":",
"ordinal",
"of",
"the",
"source",
"group",
":",
"param",
"branch_name",
":",
"name",
"of",
"the",
"UCERF",
"branch",
":",
"param",
"branch_id",
":",
"string",
"associated",
"to",
"the",
"branch",
":",
"returns",
":",
"a",
"ne... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L242-L257 |
gem/oq-engine | openquake/calculators/ucerf_base.py | UCERFSource.get_ridx | def get_ridx(self, iloc):
"""List of rupture indices for the given iloc"""
with h5py.File(self.source_file, "r") as hdf5:
return hdf5[self.idx_set["geol"] + "/RuptureIndex"][iloc] | python | def get_ridx(self, iloc):
with h5py.File(self.source_file, "r") as hdf5:
return hdf5[self.idx_set["geol"] + "/RuptureIndex"][iloc] | [
"def",
"get_ridx",
"(",
"self",
",",
"iloc",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"self",
".",
"source_file",
",",
"\"r\"",
")",
"as",
"hdf5",
":",
"return",
"hdf5",
"[",
"self",
".",
"idx_set",
"[",
"\"geol\"",
"]",
"+",
"\"/RuptureIndex\"",
... | List of rupture indices for the given iloc | [
"List",
"of",
"rupture",
"indices",
"for",
"the",
"given",
"iloc"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L271-L274 |
gem/oq-engine | openquake/calculators/ucerf_base.py | UCERFSource.get_centroids | def get_centroids(self, ridx):
"""
:returns: array of centroids for the given rupture index
"""
centroids = []
with h5py.File(self.source_file, "r") as hdf5:
for idx in ridx:
trace = "{:s}/{:s}".format(self.idx_set["sec"], str(idx))
cen... | python | def get_centroids(self, ridx):
centroids = []
with h5py.File(self.source_file, "r") as hdf5:
for idx in ridx:
trace = "{:s}/{:s}".format(self.idx_set["sec"], str(idx))
centroids.append(hdf5[trace + "/Centroids"].value)
return numpy.concatenate... | [
"def",
"get_centroids",
"(",
"self",
",",
"ridx",
")",
":",
"centroids",
"=",
"[",
"]",
"with",
"h5py",
".",
"File",
"(",
"self",
".",
"source_file",
",",
"\"r\"",
")",
"as",
"hdf5",
":",
"for",
"idx",
"in",
"ridx",
":",
"trace",
"=",
"\"{:s}/{:s}\""... | :returns: array of centroids for the given rupture index | [
":",
"returns",
":",
"array",
"of",
"centroids",
"for",
"the",
"given",
"rupture",
"index"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L276-L285 |
gem/oq-engine | openquake/calculators/ucerf_base.py | UCERFSource.gen_trace_planes | def gen_trace_planes(self, ridx):
"""
:yields: trace and rupture planes for the given rupture index
"""
with h5py.File(self.source_file, "r") as hdf5:
for idx in ridx:
trace = "{:s}/{:s}".format(self.idx_set["sec"], str(idx))
plane = hdf5[trace... | python | def gen_trace_planes(self, ridx):
with h5py.File(self.source_file, "r") as hdf5:
for idx in ridx:
trace = "{:s}/{:s}".format(self.idx_set["sec"], str(idx))
plane = hdf5[trace + "/RupturePlanes"][:].astype("float64")
yield trace, plane | [
"def",
"gen_trace_planes",
"(",
"self",
",",
"ridx",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"self",
".",
"source_file",
",",
"\"r\"",
")",
"as",
"hdf5",
":",
"for",
"idx",
"in",
"ridx",
":",
"trace",
"=",
"\"{:s}/{:s}\"",
".",
"format",
"(",
"se... | :yields: trace and rupture planes for the given rupture index | [
":",
"yields",
":",
"trace",
"and",
"rupture",
"planes",
"for",
"the",
"given",
"rupture",
"index"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L287-L295 |
gem/oq-engine | openquake/calculators/ucerf_base.py | UCERFSource.get_background_sids | def get_background_sids(self, src_filter):
"""
We can apply the filtering of the background sites as a pre-processing
step - this is done here rather than in the sampling of the ruptures
themselves
"""
branch_key = self.idx_set["grid_key"]
idist = src_filter.integ... | python | def get_background_sids(self, src_filter):
branch_key = self.idx_set["grid_key"]
idist = src_filter.integration_distance(DEFAULT_TRT)
with h5py.File(self.source_file, 'r') as hdf5:
bg_locations = hdf5["Grid/Locations"].value
distances = min_geodetic_distance(
... | [
"def",
"get_background_sids",
"(",
"self",
",",
"src_filter",
")",
":",
"branch_key",
"=",
"self",
".",
"idx_set",
"[",
"\"grid_key\"",
"]",
"idist",
"=",
"src_filter",
".",
"integration_distance",
"(",
"DEFAULT_TRT",
")",
"with",
"h5py",
".",
"File",
"(",
"... | We can apply the filtering of the background sites as a pre-processing
step - this is done here rather than in the sampling of the ruptures
themselves | [
"We",
"can",
"apply",
"the",
"filtering",
"of",
"the",
"background",
"sites",
"as",
"a",
"pre",
"-",
"processing",
"step",
"-",
"this",
"is",
"done",
"here",
"rather",
"than",
"in",
"the",
"sampling",
"of",
"the",
"ruptures",
"themselves"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L297-L317 |
gem/oq-engine | openquake/calculators/ucerf_base.py | UCERFSource.get_ucerf_rupture | def get_ucerf_rupture(self, iloc, src_filter):
"""
:param iloc:
Location of the rupture plane in the hdf5 file
:param src_filter:
Sites for consideration and maximum distance
"""
trt = self.tectonic_region_type
ridx = self.get_ridx(iloc)
ma... | python | def get_ucerf_rupture(self, iloc, src_filter):
trt = self.tectonic_region_type
ridx = self.get_ridx(iloc)
mag = self.orig.mags[iloc]
surface_set = []
indices = src_filter.get_indices(self, ridx, mag)
if len(indices) == 0:
return None
for trace... | [
"def",
"get_ucerf_rupture",
"(",
"self",
",",
"iloc",
",",
"src_filter",
")",
":",
"trt",
"=",
"self",
".",
"tectonic_region_type",
"ridx",
"=",
"self",
".",
"get_ridx",
"(",
"iloc",
")",
"mag",
"=",
"self",
".",
"orig",
".",
"mags",
"[",
"iloc",
"]",
... | :param iloc:
Location of the rupture plane in the hdf5 file
:param src_filter:
Sites for consideration and maximum distance | [
":",
"param",
"iloc",
":",
"Location",
"of",
"the",
"rupture",
"plane",
"in",
"the",
"hdf5",
"file",
":",
"param",
"src_filter",
":",
"Sites",
"for",
"consideration",
"and",
"maximum",
"distance"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L319-L357 |
gem/oq-engine | openquake/calculators/ucerf_base.py | UCERFSource.iter_ruptures | def iter_ruptures(self):
"""
Yield ruptures for the current set of indices
"""
assert self.orig, '%s is not fully initialized' % self
for ridx in range(self.start, self.stop):
if self.orig.rate[ridx]: # ruptures may have have zero rate
rup = self.get_... | python | def iter_ruptures(self):
assert self.orig, '%s is not fully initialized' % self
for ridx in range(self.start, self.stop):
if self.orig.rate[ridx]:
rup = self.get_ucerf_rupture(ridx, self.src_filter)
if rup:
yield rup | [
"def",
"iter_ruptures",
"(",
"self",
")",
":",
"assert",
"self",
".",
"orig",
",",
"'%s is not fully initialized'",
"%",
"self",
"for",
"ridx",
"in",
"range",
"(",
"self",
".",
"start",
",",
"self",
".",
"stop",
")",
":",
"if",
"self",
".",
"orig",
"."... | Yield ruptures for the current set of indices | [
"Yield",
"ruptures",
"for",
"the",
"current",
"set",
"of",
"indices"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L359-L368 |
gem/oq-engine | openquake/calculators/ucerf_base.py | UCERFSource.get_background_sources | def get_background_sources(self, src_filter, sample_factor=None):
"""
Turn the background model of a given branch into a set of point sources
:param src_filter:
SourceFilter instance
:param sample_factor:
Used to reduce the sources if OQ_SAMPLE_SOURCES is set
... | python | def get_background_sources(self, src_filter, sample_factor=None):
background_sids = self.get_background_sids(src_filter)
if sample_factor is not None:
background_sids = random_filter(
background_sids, sample_factor, seed=42)
with h5py.File(self.source_file,... | [
"def",
"get_background_sources",
"(",
"self",
",",
"src_filter",
",",
"sample_factor",
"=",
"None",
")",
":",
"background_sids",
"=",
"self",
".",
"get_background_sids",
"(",
"src_filter",
")",
"if",
"sample_factor",
"is",
"not",
"None",
":",
"# hack for use in th... | Turn the background model of a given branch into a set of point sources
:param src_filter:
SourceFilter instance
:param sample_factor:
Used to reduce the sources if OQ_SAMPLE_SOURCES is set | [
"Turn",
"the",
"background",
"model",
"of",
"a",
"given",
"branch",
"into",
"a",
"set",
"of",
"point",
"sources"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L387-L427 |
gem/oq-engine | openquake/hazardlib/source/rupture_collection.py | split | def split(src, chunksize=MINWEIGHT):
"""
Split a complex fault source in chunks
"""
for i, block in enumerate(block_splitter(src.iter_ruptures(), chunksize,
key=operator.attrgetter('mag'))):
rup = block[0]
source_id = '%s:%d' % (src.source_id,... | python | def split(src, chunksize=MINWEIGHT):
for i, block in enumerate(block_splitter(src.iter_ruptures(), chunksize,
key=operator.attrgetter('mag'))):
rup = block[0]
source_id = '%s:%d' % (src.source_id, i)
amfd = mfd.ArbitraryMFD([rup.mag], [rup.ma... | [
"def",
"split",
"(",
"src",
",",
"chunksize",
"=",
"MINWEIGHT",
")",
":",
"for",
"i",
",",
"block",
"in",
"enumerate",
"(",
"block_splitter",
"(",
"src",
".",
"iter_ruptures",
"(",
")",
",",
"chunksize",
",",
"key",
"=",
"operator",
".",
"attrgetter",
... | Split a complex fault source in chunks | [
"Split",
"a",
"complex",
"fault",
"source",
"in",
"chunks"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/source/rupture_collection.py#L61-L72 |
gem/oq-engine | openquake/hazardlib/source/rupture_collection.py | RuptureCollectionSource.get_bounding_box | def get_bounding_box(self, maxdist):
"""
Bounding box containing all the hypocenters, enlarged by the
maximum distance
"""
locations = [rup.hypocenter for rup in self.ruptures]
return get_bounding_box(locations, maxdist) | python | def get_bounding_box(self, maxdist):
locations = [rup.hypocenter for rup in self.ruptures]
return get_bounding_box(locations, maxdist) | [
"def",
"get_bounding_box",
"(",
"self",
",",
"maxdist",
")",
":",
"locations",
"=",
"[",
"rup",
".",
"hypocenter",
"for",
"rup",
"in",
"self",
".",
"ruptures",
"]",
"return",
"get_bounding_box",
"(",
"locations",
",",
"maxdist",
")"
] | Bounding box containing all the hypocenters, enlarged by the
maximum distance | [
"Bounding",
"box",
"containing",
"all",
"the",
"hypocenters",
"enlarged",
"by",
"the",
"maximum",
"distance"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/source/rupture_collection.py#L52-L58 |
gem/oq-engine | openquake/commands/show_attrs.py | show_attrs | def show_attrs(key, calc_id=-1):
"""
Show the attributes of a HDF5 dataset in the datastore.
"""
ds = util.read(calc_id)
try:
attrs = h5py.File.__getitem__(ds.hdf5, key).attrs
except KeyError:
print('%r is not in %s' % (key, ds))
else:
if len(attrs) == 0:
... | python | def show_attrs(key, calc_id=-1):
ds = util.read(calc_id)
try:
attrs = h5py.File.__getitem__(ds.hdf5, key).attrs
except KeyError:
print('%r is not in %s' % (key, ds))
else:
if len(attrs) == 0:
print('%s has no attributes' % key)
for name, value in attrs.it... | [
"def",
"show_attrs",
"(",
"key",
",",
"calc_id",
"=",
"-",
"1",
")",
":",
"ds",
"=",
"util",
".",
"read",
"(",
"calc_id",
")",
"try",
":",
"attrs",
"=",
"h5py",
".",
"File",
".",
"__getitem__",
"(",
"ds",
".",
"hdf5",
",",
"key",
")",
".",
"att... | Show the attributes of a HDF5 dataset in the datastore. | [
"Show",
"the",
"attributes",
"of",
"a",
"HDF5",
"dataset",
"in",
"the",
"datastore",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/show_attrs.py#L24-L39 |
gem/oq-engine | utils/compare_mean_curves.py | compare_mean_curves | def compare_mean_curves(calc_ref, calc, nsigma=3):
"""
Compare the hazard curves coming from two different calculations.
"""
dstore_ref = datastore.read(calc_ref)
dstore = datastore.read(calc)
imtls = dstore_ref['oqparam'].imtls
if dstore['oqparam'].imtls != imtls:
raise RuntimeError... | python | def compare_mean_curves(calc_ref, calc, nsigma=3):
dstore_ref = datastore.read(calc_ref)
dstore = datastore.read(calc)
imtls = dstore_ref['oqparam'].imtls
if dstore['oqparam'].imtls != imtls:
raise RuntimeError('The IMTs and levels are different between '
'calcula... | [
"def",
"compare_mean_curves",
"(",
"calc_ref",
",",
"calc",
",",
"nsigma",
"=",
"3",
")",
":",
"dstore_ref",
"=",
"datastore",
".",
"read",
"(",
"calc_ref",
")",
"dstore",
"=",
"datastore",
".",
"read",
"(",
"calc",
")",
"imtls",
"=",
"dstore_ref",
"[",
... | Compare the hazard curves coming from two different calculations. | [
"Compare",
"the",
"hazard",
"curves",
"coming",
"from",
"two",
"different",
"calculations",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/utils/compare_mean_curves.py#L27-L69 |
gem/oq-engine | openquake/hazardlib/gsim/chiou_youngs_2014.py | ChiouYoungs2014._get_mean | def _get_mean(self, sites, C, ln_y_ref, exp1, exp2):
"""
Add site effects to an intensity.
Implements eq. 13b.
"""
# we do not support estimating of basin depth and instead
# rely on it being available (since we require it).
# centered_z1pt0
centered_z1pt... | python | def _get_mean(self, sites, C, ln_y_ref, exp1, exp2):
centered_z1pt0 = self._get_centered_z1pt0(sites)
eta = epsilon = 0.
ln_y = (
ln_y_ref + eta
+ C['phi1'] * np.log(sites.vs30 / 1130).clip(-... | [
"def",
"_get_mean",
"(",
"self",
",",
"sites",
",",
"C",
",",
"ln_y_ref",
",",
"exp1",
",",
"exp2",
")",
":",
"# we do not support estimating of basin depth and instead",
"# rely on it being available (since we require it).",
"# centered_z1pt0",
"centered_z1pt0",
"=",
"self... | Add site effects to an intensity.
Implements eq. 13b. | [
"Add",
"site",
"effects",
"to",
"an",
"intensity",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/chiou_youngs_2014.py#L93-L122 |
gem/oq-engine | openquake/hazardlib/gsim/chiou_youngs_2014.py | ChiouYoungs2014._get_ln_y_ref | def _get_ln_y_ref(self, rup, dists, C):
"""
Get an intensity on a reference soil.
Implements eq. 13a.
"""
# reverse faulting flag
Frv = 1. if 30 <= rup.rake <= 150 else 0.
# normal faulting flag
Fnm = 1. if -120 <= rup.rake <= -60 else 0.
# hangin... | python | def _get_ln_y_ref(self, rup, dists, C):
Frv = 1. if 30 <= rup.rake <= 150 else 0.
Fnm = 1. if -120 <= rup.rake <= -60 else 0.
Fhw = np.zeros_like(dists.rx)
idx = np.nonzero(dists.rx >= 0.)
Fhw[idx] = 1.
mag_test1 = np.cosh(2.... | [
"def",
"_get_ln_y_ref",
"(",
"self",
",",
"rup",
",",
"dists",
",",
"C",
")",
":",
"# reverse faulting flag",
"Frv",
"=",
"1.",
"if",
"30",
"<=",
"rup",
".",
"rake",
"<=",
"150",
"else",
"0.",
"# normal faulting flag",
"Fnm",
"=",
"1.",
"if",
"-",
"120... | Get an intensity on a reference soil.
Implements eq. 13a. | [
"Get",
"an",
"intensity",
"on",
"a",
"reference",
"soil",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/chiou_youngs_2014.py#L162-L222 |
gem/oq-engine | openquake/hazardlib/gsim/chiou_youngs_2014.py | ChiouYoungs2014._get_centered_z1pt0 | def _get_centered_z1pt0(self, sites):
"""
Get z1pt0 centered on the Vs30- dependent avarage z1pt0(m)
California and non-Japan regions
"""
#: California and non-Japan regions
mean_z1pt0 = (-7.15 / 4.) * np.log(((sites.vs30) ** 4. + 570.94 ** 4.)
... | python | def _get_centered_z1pt0(self, sites):
mean_z1pt0 = (-7.15 / 4.) * np.log(((sites.vs30) ** 4. + 570.94 ** 4.)
/ (1360 ** 4. + 570.94 ** 4.))
centered_z1pt0 = sites.z1pt0 - np.exp(mean_z1pt0)
return centered_z1pt0 | [
"def",
"_get_centered_z1pt0",
"(",
"self",
",",
"sites",
")",
":",
"#: California and non-Japan regions",
"mean_z1pt0",
"=",
"(",
"-",
"7.15",
"/",
"4.",
")",
"*",
"np",
".",
"log",
"(",
"(",
"(",
"sites",
".",
"vs30",
")",
"**",
"4.",
"+",
"570.94",
"... | Get z1pt0 centered on the Vs30- dependent avarage z1pt0(m)
California and non-Japan regions | [
"Get",
"z1pt0",
"centered",
"on",
"the",
"Vs30",
"-",
"dependent",
"avarage",
"z1pt0",
"(",
"m",
")",
"California",
"and",
"non",
"-",
"Japan",
"regions"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/chiou_youngs_2014.py#L224-L236 |
gem/oq-engine | openquake/hazardlib/gsim/chiou_youngs_2014.py | ChiouYoungs2014._get_centered_ztor | def _get_centered_ztor(self, rup, Frv):
"""
Get ztor centered on the M- dependent avarage ztor(km)
by different fault types.
"""
if Frv == 1:
mean_ztor = max(2.704 - 1.226 * max(rup.mag - 5.849, 0.0), 0.) ** 2
centered_ztor = rup.ztor - mean_ztor
... | python | def _get_centered_ztor(self, rup, Frv):
if Frv == 1:
mean_ztor = max(2.704 - 1.226 * max(rup.mag - 5.849, 0.0), 0.) ** 2
centered_ztor = rup.ztor - mean_ztor
else:
mean_ztor = max(2.673 - 1.136 * max(rup.mag - 4.970, 0.0), 0.) ** 2
centered_ztor... | [
"def",
"_get_centered_ztor",
"(",
"self",
",",
"rup",
",",
"Frv",
")",
":",
"if",
"Frv",
"==",
"1",
":",
"mean_ztor",
"=",
"max",
"(",
"2.704",
"-",
"1.226",
"*",
"max",
"(",
"rup",
".",
"mag",
"-",
"5.849",
",",
"0.0",
")",
",",
"0.",
")",
"**... | Get ztor centered on the M- dependent avarage ztor(km)
by different fault types. | [
"Get",
"ztor",
"centered",
"on",
"the",
"M",
"-",
"dependent",
"avarage",
"ztor",
"(",
"km",
")",
"by",
"different",
"fault",
"types",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/chiou_youngs_2014.py#L238-L252 |
gem/oq-engine | openquake/hazardlib/gsim/chiou_youngs_2014.py | ChiouYoungs2014PEER._get_stddevs | def _get_stddevs(self, sites, rup, C, stddev_types, ln_y_ref, exp1, exp2):
"""
Returns the standard deviation, which is fixed at 0.65 for every site
"""
ret = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
... | python | def _get_stddevs(self, sites, rup, C, stddev_types, ln_y_ref, exp1, exp2):
ret = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
ret.append(0.65 * n... | [
"def",
"_get_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"C",
",",
"stddev_types",
",",
"ln_y_ref",
",",
"exp1",
",",
"exp2",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"stddev_type",
"in",
"stddev_types",
":",
"assert",
"stddev_type",
"in",
"sel... | Returns the standard deviation, which is fixed at 0.65 for every site | [
"Returns",
"the",
"standard",
"deviation",
"which",
"is",
"fixed",
"at",
"0",
".",
"65",
"for",
"every",
"site"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/chiou_youngs_2014.py#L313-L323 |
gem/oq-engine | openquake/risklib/scientific.py | fine_graining | def fine_graining(points, steps):
"""
:param points: a list of floats
:param int steps: expansion steps (>= 2)
>>> fine_graining([0, 1], steps=0)
[0, 1]
>>> fine_graining([0, 1], steps=1)
[0, 1]
>>> fine_graining([0, 1], steps=2)
array([0. , 0.5, 1. ])
>>> fine_graining([0, 1], ... | python | def fine_graining(points, steps):
if steps < 2:
return points
ls = numpy.concatenate([numpy.linspace(x, y, num=steps + 1)[:-1]
for x, y in pairwise(points)])
return numpy.concatenate([ls, [points[-1]]]) | [
"def",
"fine_graining",
"(",
"points",
",",
"steps",
")",
":",
"if",
"steps",
"<",
"2",
":",
"return",
"points",
"ls",
"=",
"numpy",
".",
"concatenate",
"(",
"[",
"numpy",
".",
"linspace",
"(",
"x",
",",
"y",
",",
"num",
"=",
"steps",
"+",
"1",
"... | :param points: a list of floats
:param int steps: expansion steps (>= 2)
>>> fine_graining([0, 1], steps=0)
[0, 1]
>>> fine_graining([0, 1], steps=1)
[0, 1]
>>> fine_graining([0, 1], steps=2)
array([0. , 0.5, 1. ])
>>> fine_graining([0, 1], steps=3)
array([0. , 0.33333333, 0.... | [
":",
"param",
"points",
":",
"a",
"list",
"of",
"floats",
":",
"param",
"int",
"steps",
":",
"expansion",
"steps",
"(",
">",
"=",
"2",
")"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L49-L71 |
gem/oq-engine | openquake/risklib/scientific.py | build_imls | def build_imls(ff, continuous_fragility_discretization,
steps_per_interval=0):
"""
Build intensity measure levels from a fragility function. If the function
is continuous, they are produced simply as a linear space between minIML
and maxIML. If the function is discrete, they are generated... | python | def build_imls(ff, continuous_fragility_discretization,
steps_per_interval=0):
if ff.format == 'discrete':
imls = ff.imls
if ff.nodamage and ff.nodamage < imls[0]:
imls = [ff.nodamage] + imls
if steps_per_interval > 1:
gen_imls = fine_graining(imls... | [
"def",
"build_imls",
"(",
"ff",
",",
"continuous_fragility_discretization",
",",
"steps_per_interval",
"=",
"0",
")",
":",
"if",
"ff",
".",
"format",
"==",
"'discrete'",
":",
"imls",
"=",
"ff",
".",
"imls",
"if",
"ff",
".",
"nodamage",
"and",
"ff",
".",
... | Build intensity measure levels from a fragility function. If the function
is continuous, they are produced simply as a linear space between minIML
and maxIML. If the function is discrete, they are generated with a
complex logic depending on the noDamageLimit and the parameter
steps per interval.
:p... | [
"Build",
"intensity",
"measure",
"levels",
"from",
"a",
"fragility",
"function",
".",
"If",
"the",
"function",
"is",
"continuous",
"they",
"are",
"produced",
"simply",
"as",
"a",
"linear",
"space",
"between",
"minIML",
"and",
"maxIML",
".",
"If",
"the",
"fun... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L665-L690 |
gem/oq-engine | openquake/risklib/scientific.py | make_epsilons | def make_epsilons(matrix, seed, correlation):
"""
Given a matrix N * R returns a matrix of the same shape N * R
obtained by applying the multivariate_normal distribution to
N points and R samples, by starting from the given seed and
correlation.
"""
if seed is not None:
numpy.random.... | python | def make_epsilons(matrix, seed, correlation):
if seed is not None:
numpy.random.seed(seed)
asset_count = len(matrix)
samples = len(matrix[0])
if not correlation:
return numpy.random.normal(size=(samples, asset_count)).transpose()
means_vector = numpy.zeros(asset_count)
cov... | [
"def",
"make_epsilons",
"(",
"matrix",
",",
"seed",
",",
"correlation",
")",
":",
"if",
"seed",
"is",
"not",
"None",
":",
"numpy",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"asset_count",
"=",
"len",
"(",
"matrix",
")",
"samples",
"=",
"len",
"("... | Given a matrix N * R returns a matrix of the same shape N * R
obtained by applying the multivariate_normal distribution to
N points and R samples, by starting from the given seed and
correlation. | [
"Given",
"a",
"matrix",
"N",
"*",
"R",
"returns",
"a",
"matrix",
"of",
"the",
"same",
"shape",
"N",
"*",
"R",
"obtained",
"by",
"applying",
"the",
"multivariate_normal",
"distribution",
"to",
"N",
"points",
"and",
"R",
"samples",
"by",
"starting",
"from",
... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L784-L802 |
gem/oq-engine | openquake/risklib/scientific.py | scenario_damage | def scenario_damage(fragility_functions, gmvs):
"""
:param fragility_functions: a list of D - 1 fragility functions
:param gmvs: an array of E ground motion values
:returns: an array of (D, E) damage fractions
"""
lst = [numpy.ones_like(gmvs)]
for f, ff in enumerate(fragility_functions): # ... | python | def scenario_damage(fragility_functions, gmvs):
lst = [numpy.ones_like(gmvs)]
for f, ff in enumerate(fragility_functions):
lst.append(ff(gmvs))
lst.append(numpy.zeros_like(gmvs))
arr = pairwise_diff(numpy.array(lst))
arr[arr < 1E-7] = 0
return arr | [
"def",
"scenario_damage",
"(",
"fragility_functions",
",",
"gmvs",
")",
":",
"lst",
"=",
"[",
"numpy",
".",
"ones_like",
"(",
"gmvs",
")",
"]",
"for",
"f",
",",
"ff",
"in",
"enumerate",
"(",
"fragility_functions",
")",
":",
"# D - 1 functions",
"lst",
".",... | :param fragility_functions: a list of D - 1 fragility functions
:param gmvs: an array of E ground motion values
:returns: an array of (D, E) damage fractions | [
":",
"param",
"fragility_functions",
":",
"a",
"list",
"of",
"D",
"-",
"1",
"fragility",
"functions",
":",
"param",
"gmvs",
":",
"an",
"array",
"of",
"E",
"ground",
"motion",
"values",
":",
"returns",
":",
"an",
"array",
"of",
"(",
"D",
"E",
")",
"da... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L903-L916 |
gem/oq-engine | openquake/risklib/scientific.py | annual_frequency_of_exceedence | def annual_frequency_of_exceedence(poe, t_haz):
"""
:param poe: array of probabilities of exceedence
:param t_haz: hazard investigation time
:returns: array of frequencies (with +inf values where poe=1)
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# avoid R... | python | def annual_frequency_of_exceedence(poe, t_haz):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return - numpy.log(1. - poe) / t_haz | [
"def",
"annual_frequency_of_exceedence",
"(",
"poe",
",",
"t_haz",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
")",
"# avoid RuntimeWarning: divide by zero encountered in log",
"return",
"-",
... | :param poe: array of probabilities of exceedence
:param t_haz: hazard investigation time
:returns: array of frequencies (with +inf values where poe=1) | [
":",
"param",
"poe",
":",
"array",
"of",
"probabilities",
"of",
"exceedence",
":",
"param",
"t_haz",
":",
"hazard",
"investigation",
"time",
":",
"returns",
":",
"array",
"of",
"frequencies",
"(",
"with",
"+",
"inf",
"values",
"where",
"poe",
"=",
"1",
"... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L923-L932 |
gem/oq-engine | openquake/risklib/scientific.py | classical_damage | def classical_damage(
fragility_functions, hazard_imls, hazard_poes,
investigation_time, risk_investigation_time):
"""
:param fragility_functions:
a list of fragility functions for each damage state
:param hazard_imls:
Intensity Measure Levels
:param hazard_poes:
... | python | def classical_damage(
fragility_functions, hazard_imls, hazard_poes,
investigation_time, risk_investigation_time):
spi = fragility_functions.steps_per_interval
if spi and spi > 1:
imls = numpy.array(fragility_functions.interp_imls)
min_val, max_val = hazard_imls[0], hazard... | [
"def",
"classical_damage",
"(",
"fragility_functions",
",",
"hazard_imls",
",",
"hazard_poes",
",",
"investigation_time",
",",
"risk_investigation_time",
")",
":",
"spi",
"=",
"fragility_functions",
".",
"steps_per_interval",
"if",
"spi",
"and",
"spi",
">",
"1",
":"... | :param fragility_functions:
a list of fragility functions for each damage state
:param hazard_imls:
Intensity Measure Levels
:param hazard_poes:
hazard curve
:param investigation_time:
hazard investigation time
:param risk_investigation_time:
risk investigation ti... | [
":",
"param",
"fragility_functions",
":",
"a",
"list",
"of",
"fragility",
"functions",
"for",
"each",
"damage",
"state",
":",
"param",
"hazard_imls",
":",
"Intensity",
"Measure",
"Levels",
":",
"param",
"hazard_poes",
":",
"hazard",
"curve",
":",
"param",
"inv... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L935-L977 |
gem/oq-engine | openquake/risklib/scientific.py | classical | def classical(vulnerability_function, hazard_imls, hazard_poes, loss_ratios):
"""
:param vulnerability_function:
an instance of
:py:class:`openquake.risklib.scientific.VulnerabilityFunction`
representing the vulnerability function used to compute the curve.
:param hazard_imls:
... | python | def classical(vulnerability_function, hazard_imls, hazard_poes, loss_ratios):
assert len(hazard_imls) == len(hazard_poes), (
len(hazard_imls), len(hazard_poes))
vf = vulnerability_function
imls = vf.mean_imls()
lrem = vf.loss_ratio_exceedance_matrix(loss_ratios)
min_val, max_val =... | [
"def",
"classical",
"(",
"vulnerability_function",
",",
"hazard_imls",
",",
"hazard_poes",
",",
"loss_ratios",
")",
":",
"assert",
"len",
"(",
"hazard_imls",
")",
"==",
"len",
"(",
"hazard_poes",
")",
",",
"(",
"len",
"(",
"hazard_imls",
")",
",",
"len",
"... | :param vulnerability_function:
an instance of
:py:class:`openquake.risklib.scientific.VulnerabilityFunction`
representing the vulnerability function used to compute the curve.
:param hazard_imls:
the hazard intensity measure type and levels
:type hazard_poes:
the hazard c... | [
":",
"param",
"vulnerability_function",
":",
"an",
"instance",
"of",
":",
"py",
":",
"class",
":",
"openquake",
".",
"risklib",
".",
"scientific",
".",
"VulnerabilityFunction",
"representing",
"the",
"vulnerability",
"function",
"used",
"to",
"compute",
"the",
"... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L984-L1018 |
gem/oq-engine | openquake/risklib/scientific.py | conditional_loss_ratio | def conditional_loss_ratio(loss_ratios, poes, probability):
"""
Return the loss ratio corresponding to the given PoE (Probability
of Exceendance). We can have four cases:
1. If `probability` is in `poes` it takes the bigger
corresponding loss_ratios.
2. If it is in `(poe1, poe2)` wher... | python | def conditional_loss_ratio(loss_ratios, poes, probability):
assert len(loss_ratios) >= 3, loss_ratios
rpoes = poes[::-1]
if probability > poes[0]:
return 0.0
elif probability < poes[-1]:
return loss_ratios[-1]
if probability in poes:
return max([loss
... | [
"def",
"conditional_loss_ratio",
"(",
"loss_ratios",
",",
"poes",
",",
"probability",
")",
":",
"assert",
"len",
"(",
"loss_ratios",
")",
">=",
"3",
",",
"loss_ratios",
"rpoes",
"=",
"poes",
"[",
":",
":",
"-",
"1",
"]",
"if",
"probability",
">",
"poes",... | Return the loss ratio corresponding to the given PoE (Probability
of Exceendance). We can have four cases:
1. If `probability` is in `poes` it takes the bigger
corresponding loss_ratios.
2. If it is in `(poe1, poe2)` where both `poe1` and `poe2` are
in `poes`, then we perform a linea... | [
"Return",
"the",
"loss",
"ratio",
"corresponding",
"to",
"the",
"given",
"PoE",
"(",
"Probability",
"of",
"Exceendance",
")",
".",
"We",
"can",
"have",
"four",
"cases",
":"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1021-L1068 |
gem/oq-engine | openquake/risklib/scientific.py | insured_losses | def insured_losses(losses, deductible, insured_limit):
"""
:param losses: an array of ground-up loss ratios
:param float deductible: the deductible limit in fraction form
:param float insured_limit: the insured limit in fraction form
Compute insured losses for the given asset and losses, from the p... | python | def insured_losses(losses, deductible, insured_limit):
return numpy.piecewise(
losses,
[losses < deductible, losses > insured_limit],
[0, insured_limit - deductible, lambda x: x - deductible]) | [
"def",
"insured_losses",
"(",
"losses",
",",
"deductible",
",",
"insured_limit",
")",
":",
"return",
"numpy",
".",
"piecewise",
"(",
"losses",
",",
"[",
"losses",
"<",
"deductible",
",",
"losses",
">",
"insured_limit",
"]",
",",
"[",
"0",
",",
"insured_lim... | :param losses: an array of ground-up loss ratios
:param float deductible: the deductible limit in fraction form
:param float insured_limit: the insured limit in fraction form
Compute insured losses for the given asset and losses, from the point
of view of the insurance company. For instance:
>>> i... | [
":",
"param",
"losses",
":",
"an",
"array",
"of",
"ground",
"-",
"up",
"loss",
"ratios",
":",
"param",
"float",
"deductible",
":",
"the",
"deductible",
"limit",
"in",
"fraction",
"form",
":",
"param",
"float",
"insured_limit",
":",
"the",
"insured",
"limit... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1075-L1094 |
gem/oq-engine | openquake/risklib/scientific.py | insured_loss_curve | def insured_loss_curve(curve, deductible, insured_limit):
"""
Compute an insured loss ratio curve given a loss ratio curve
:param curve: an array 2 x R (where R is the curve resolution)
:param float deductible: the deductible limit in fraction form
:param float insured_limit: the insured limit in f... | python | def insured_loss_curve(curve, deductible, insured_limit):
losses, poes = curve[:, curve[0] <= insured_limit]
limit_poe = interpolate.interp1d(
*curve, bounds_error=False, fill_value=1)(deductible)
return numpy.array([
losses,
numpy.piecewise(poes, [poes > limit_poe], [limit_poe,... | [
"def",
"insured_loss_curve",
"(",
"curve",
",",
"deductible",
",",
"insured_limit",
")",
":",
"losses",
",",
"poes",
"=",
"curve",
"[",
":",
",",
"curve",
"[",
"0",
"]",
"<=",
"insured_limit",
"]",
"limit_poe",
"=",
"interpolate",
".",
"interp1d",
"(",
"... | Compute an insured loss ratio curve given a loss ratio curve
:param curve: an array 2 x R (where R is the curve resolution)
:param float deductible: the deductible limit in fraction form
:param float insured_limit: the insured limit in fraction form
>>> losses = numpy.array([3, 20, 101])
>>> poes ... | [
"Compute",
"an",
"insured",
"loss",
"ratio",
"curve",
"given",
"a",
"loss",
"ratio",
"curve"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1097-L1116 |
gem/oq-engine | openquake/risklib/scientific.py | bcr | def bcr(eal_original, eal_retrofitted, interest_rate,
asset_life_expectancy, asset_value, retrofitting_cost):
"""
Compute the Benefit-Cost Ratio.
BCR = (EALo - EALr)(1-exp(-r*t))/(r*C)
Where:
* BCR -- Benefit cost ratio
* EALo -- Expected annual loss for original asset
* EALr -- E... | python | def bcr(eal_original, eal_retrofitted, interest_rate,
asset_life_expectancy, asset_value, retrofitting_cost):
return ((eal_original - eal_retrofitted) * asset_value *
(1 - numpy.exp(- interest_rate * asset_life_expectancy)) /
(interest_rate * retrofitting_cost)) | [
"def",
"bcr",
"(",
"eal_original",
",",
"eal_retrofitted",
",",
"interest_rate",
",",
"asset_life_expectancy",
",",
"asset_value",
",",
"retrofitting_cost",
")",
":",
"return",
"(",
"(",
"eal_original",
"-",
"eal_retrofitted",
")",
"*",
"asset_value",
"*",
"(",
... | Compute the Benefit-Cost Ratio.
BCR = (EALo - EALr)(1-exp(-r*t))/(r*C)
Where:
* BCR -- Benefit cost ratio
* EALo -- Expected annual loss for original asset
* EALr -- Expected annual loss for retrofitted asset
* r -- Interest rate
* t -- Life expectancy of the asset
* C -- Retrofitting... | [
"Compute",
"the",
"Benefit",
"-",
"Cost",
"Ratio",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1124-L1142 |
gem/oq-engine | openquake/risklib/scientific.py | pairwise_mean | def pairwise_mean(values):
"Averages between a value and the next value in a sequence"
return numpy.array([numpy.mean(pair) for pair in pairwise(values)]) | python | def pairwise_mean(values):
"Averages between a value and the next value in a sequence"
return numpy.array([numpy.mean(pair) for pair in pairwise(values)]) | [
"def",
"pairwise_mean",
"(",
"values",
")",
":",
"return",
"numpy",
".",
"array",
"(",
"[",
"numpy",
".",
"mean",
"(",
"pair",
")",
"for",
"pair",
"in",
"pairwise",
"(",
"values",
")",
"]",
")"
] | Averages between a value and the next value in a sequence | [
"Averages",
"between",
"a",
"value",
"and",
"the",
"next",
"value",
"in",
"a",
"sequence"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1147-L1149 |
gem/oq-engine | openquake/risklib/scientific.py | pairwise_diff | def pairwise_diff(values):
"Differences between a value and the next value in a sequence"
return numpy.array([x - y for x, y in pairwise(values)]) | python | def pairwise_diff(values):
"Differences between a value and the next value in a sequence"
return numpy.array([x - y for x, y in pairwise(values)]) | [
"def",
"pairwise_diff",
"(",
"values",
")",
":",
"return",
"numpy",
".",
"array",
"(",
"[",
"x",
"-",
"y",
"for",
"x",
",",
"y",
"in",
"pairwise",
"(",
"values",
")",
"]",
")"
] | Differences between a value and the next value in a sequence | [
"Differences",
"between",
"a",
"value",
"and",
"the",
"next",
"value",
"in",
"a",
"sequence"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1152-L1154 |
gem/oq-engine | openquake/risklib/scientific.py | mean_std | def mean_std(fractions):
"""
Given an N x M matrix, returns mean and std computed on the rows,
i.e. two M-dimensional vectors.
"""
n = fractions.shape[0]
if n == 1: # avoid warnings when computing the stddev
return fractions[0], numpy.ones_like(fractions[0]) * numpy.nan
return numpy... | python | def mean_std(fractions):
n = fractions.shape[0]
if n == 1:
return fractions[0], numpy.ones_like(fractions[0]) * numpy.nan
return numpy.mean(fractions, axis=0), numpy.std(fractions, axis=0, ddof=1) | [
"def",
"mean_std",
"(",
"fractions",
")",
":",
"n",
"=",
"fractions",
".",
"shape",
"[",
"0",
"]",
"if",
"n",
"==",
"1",
":",
"# avoid warnings when computing the stddev",
"return",
"fractions",
"[",
"0",
"]",
",",
"numpy",
".",
"ones_like",
"(",
"fraction... | Given an N x M matrix, returns mean and std computed on the rows,
i.e. two M-dimensional vectors. | [
"Given",
"an",
"N",
"x",
"M",
"matrix",
"returns",
"mean",
"and",
"std",
"computed",
"on",
"the",
"rows",
"i",
".",
"e",
".",
"two",
"M",
"-",
"dimensional",
"vectors",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1157-L1165 |
gem/oq-engine | openquake/risklib/scientific.py | loss_maps | def loss_maps(curves, conditional_loss_poes):
"""
:param curves: an array of loss curves
:param conditional_loss_poes: a list of conditional loss poes
:returns: a composite array of loss maps with the same shape
"""
loss_maps_dt = numpy.dtype([('poe-%s' % poe, F32)
... | python | def loss_maps(curves, conditional_loss_poes):
loss_maps_dt = numpy.dtype([('poe-%s' % poe, F32)
for poe in conditional_loss_poes])
loss_maps = numpy.zeros(curves.shape, loss_maps_dt)
for idx, curve in numpy.ndenumerate(curves):
for poe in conditional_loss_poes:
... | [
"def",
"loss_maps",
"(",
"curves",
",",
"conditional_loss_poes",
")",
":",
"loss_maps_dt",
"=",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"'poe-%s'",
"%",
"poe",
",",
"F32",
")",
"for",
"poe",
"in",
"conditional_loss_poes",
"]",
")",
"loss_maps",
"=",
"numpy",... | :param curves: an array of loss curves
:param conditional_loss_poes: a list of conditional loss poes
:returns: a composite array of loss maps with the same shape | [
":",
"param",
"curves",
":",
"an",
"array",
"of",
"loss",
"curves",
":",
"param",
"conditional_loss_poes",
":",
"a",
"list",
"of",
"conditional",
"loss",
"poes",
":",
"returns",
":",
"a",
"composite",
"array",
"of",
"loss",
"maps",
"with",
"the",
"same",
... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1168-L1181 |
gem/oq-engine | openquake/risklib/scientific.py | broadcast | def broadcast(func, composite_array, *args):
"""
Broadcast an array function over a composite array
"""
dic = {}
dtypes = []
for name in composite_array.dtype.names:
dic[name] = func(composite_array[name], *args)
dtypes.append((name, dic[name].dtype))
res = numpy.zeros(dic[na... | python | def broadcast(func, composite_array, *args):
dic = {}
dtypes = []
for name in composite_array.dtype.names:
dic[name] = func(composite_array[name], *args)
dtypes.append((name, dic[name].dtype))
res = numpy.zeros(dic[name].shape, numpy.dtype(dtypes))
for name in dic:
res[n... | [
"def",
"broadcast",
"(",
"func",
",",
"composite_array",
",",
"*",
"args",
")",
":",
"dic",
"=",
"{",
"}",
"dtypes",
"=",
"[",
"]",
"for",
"name",
"in",
"composite_array",
".",
"dtype",
".",
"names",
":",
"dic",
"[",
"name",
"]",
"=",
"func",
"(",
... | Broadcast an array function over a composite array | [
"Broadcast",
"an",
"array",
"function",
"over",
"a",
"composite",
"array"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1184-L1196 |
gem/oq-engine | openquake/risklib/scientific.py | average_loss | def average_loss(lc):
"""
Given a loss curve array with `poe` and `loss` fields,
computes the average loss on a period of time.
:note: As the loss curve is supposed to be piecewise linear as it
is a result of a linear interpolation, we compute an exact
integral by using the trapei... | python | def average_loss(lc):
losses, poes = (lc['loss'], lc['poe']) if lc.dtype.names else lc
return -pairwise_diff(losses) @ pairwise_mean(poes) | [
"def",
"average_loss",
"(",
"lc",
")",
":",
"losses",
",",
"poes",
"=",
"(",
"lc",
"[",
"'loss'",
"]",
",",
"lc",
"[",
"'poe'",
"]",
")",
"if",
"lc",
".",
"dtype",
".",
"names",
"else",
"lc",
"return",
"-",
"pairwise_diff",
"(",
"losses",
")",
"@... | Given a loss curve array with `poe` and `loss` fields,
computes the average loss on a period of time.
:note: As the loss curve is supposed to be piecewise linear as it
is a result of a linear interpolation, we compute an exact
integral by using the trapeizodal rule with the width given by... | [
"Given",
"a",
"loss",
"curve",
"array",
"with",
"poe",
"and",
"loss",
"fields",
"computes",
"the",
"average",
"loss",
"on",
"a",
"period",
"of",
"time",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1200-L1211 |
gem/oq-engine | openquake/risklib/scientific.py | normalize_curves_eb | def normalize_curves_eb(curves):
"""
A more sophisticated version of normalize_curves, used in the event
based calculator.
:param curves: a list of pairs (losses, poes)
:returns: first losses, all_poes
"""
# we assume non-decreasing losses, so losses[-1] is the maximum loss
non_zero_cur... | python | def normalize_curves_eb(curves):
non_zero_curves = [(losses, poes)
for losses, poes in curves if losses[-1] > 0]
if not non_zero_curves:
return curves[0][0], numpy.array([poes for _losses, poes in curves])
else:
max_losses = [losses[-1] for losses, _poes ... | [
"def",
"normalize_curves_eb",
"(",
"curves",
")",
":",
"# we assume non-decreasing losses, so losses[-1] is the maximum loss",
"non_zero_curves",
"=",
"[",
"(",
"losses",
",",
"poes",
")",
"for",
"losses",
",",
"poes",
"in",
"curves",
"if",
"losses",
"[",
"-",
"1",
... | A more sophisticated version of normalize_curves, used in the event
based calculator.
:param curves: a list of pairs (losses, poes)
:returns: first losses, all_poes | [
"A",
"more",
"sophisticated",
"version",
"of",
"normalize_curves",
"used",
"in",
"the",
"event",
"based",
"calculator",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1214-L1238 |
gem/oq-engine | openquake/risklib/scientific.py | build_loss_curve_dt | def build_loss_curve_dt(curve_resolution, insured_losses=False):
"""
:param curve_resolution:
dictionary loss_type -> curve_resolution
:param insured_losses:
configuration parameter
:returns:
loss_curve_dt
"""
lc_list = []
for lt in sorted(curve_resolution):
C ... | python | def build_loss_curve_dt(curve_resolution, insured_losses=False):
lc_list = []
for lt in sorted(curve_resolution):
C = curve_resolution[lt]
pairs = [('losses', (F32, C)), ('poes', (F32, C))]
lc_dt = numpy.dtype(pairs)
lc_list.append((str(lt), lc_dt))
if insured_losses:
... | [
"def",
"build_loss_curve_dt",
"(",
"curve_resolution",
",",
"insured_losses",
"=",
"False",
")",
":",
"lc_list",
"=",
"[",
"]",
"for",
"lt",
"in",
"sorted",
"(",
"curve_resolution",
")",
":",
"C",
"=",
"curve_resolution",
"[",
"lt",
"]",
"pairs",
"=",
"[",... | :param curve_resolution:
dictionary loss_type -> curve_resolution
:param insured_losses:
configuration parameter
:returns:
loss_curve_dt | [
":",
"param",
"curve_resolution",
":",
"dictionary",
"loss_type",
"-",
">",
"curve_resolution",
":",
"param",
"insured_losses",
":",
"configuration",
"parameter",
":",
"returns",
":",
"loss_curve_dt"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1241-L1263 |
gem/oq-engine | openquake/risklib/scientific.py | return_periods | def return_periods(eff_time, num_losses):
"""
:param eff_time: ses_per_logic_tree_path * investigation_time
:param num_losses: used to determine the minimum period
:returns: an array of 32 bit periods
Here are a few examples:
>>> return_periods(1, 1)
Traceback (most recent call last):
... | python | def return_periods(eff_time, num_losses):
assert eff_time >= 2, 'eff_time too small: %s' % eff_time
assert num_losses >= 2, 'num_losses too small: %s' % num_losses
min_time = eff_time / num_losses
period = 1
periods = []
loop = True
while loop:
for val in [1, 2, 5]:
... | [
"def",
"return_periods",
"(",
"eff_time",
",",
"num_losses",
")",
":",
"assert",
"eff_time",
">=",
"2",
",",
"'eff_time too small: %s'",
"%",
"eff_time",
"assert",
"num_losses",
">=",
"2",
",",
"'num_losses too small: %s'",
"%",
"num_losses",
"min_time",
"=",
"eff... | :param eff_time: ses_per_logic_tree_path * investigation_time
:param num_losses: used to determine the minimum period
:returns: an array of 32 bit periods
Here are a few examples:
>>> return_periods(1, 1)
Traceback (most recent call last):
...
AssertionError: eff_time too small: 1
>... | [
":",
"param",
"eff_time",
":",
"ses_per_logic_tree_path",
"*",
"investigation_time",
":",
"param",
"num_losses",
":",
"used",
"to",
"determine",
"the",
"minimum",
"period",
":",
"returns",
":",
"an",
"array",
"of",
"32",
"bit",
"periods"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1266-L1303 |
gem/oq-engine | openquake/risklib/scientific.py | losses_by_period | def losses_by_period(losses, return_periods, num_events=None, eff_time=None):
"""
:param losses: array of simulated losses
:param return_periods: return periods of interest
:param num_events: the number of events (>= to the number of losses)
:param eff_time: investigation_time * ses_per_logic_tree_p... | python | def losses_by_period(losses, return_periods, num_events=None, eff_time=None):
if len(losses) == 0:
return numpy.zeros(len(return_periods))
if num_events is None:
num_events = len(losses)
elif num_events < len(losses):
raise ValueError(
'There are not enough events ... | [
"def",
"losses_by_period",
"(",
"losses",
",",
"return_periods",
",",
"num_events",
"=",
"None",
",",
"eff_time",
"=",
"None",
")",
":",
"if",
"len",
"(",
"losses",
")",
"==",
"0",
":",
"# zero-curve",
"return",
"numpy",
".",
"zeros",
"(",
"len",
"(",
... | :param losses: array of simulated losses
:param return_periods: return periods of interest
:param num_events: the number of events (>= to the number of losses)
:param eff_time: investigation_time * ses_per_logic_tree_path
:returns: interpolated losses for the return periods, possibly with NaN
NB: t... | [
":",
"param",
"losses",
":",
"array",
"of",
"simulated",
"losses",
":",
"param",
"return_periods",
":",
"return",
"periods",
"of",
"interest",
":",
"param",
"num_events",
":",
"the",
"number",
"of",
"events",
"(",
">",
"=",
"to",
"the",
"number",
"of",
"... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1306-L1345 |
gem/oq-engine | openquake/risklib/scientific.py | VulnerabilityFunction.interpolate | def interpolate(self, gmvs):
"""
:param gmvs:
array of intensity measure levels
:returns:
(interpolated loss ratios, interpolated covs, indices > min)
"""
# gmvs are clipped to max(iml)
gmvs_curve = numpy.piecewise(
gmvs, [gmvs > self.iml... | python | def interpolate(self, gmvs):
gmvs_curve = numpy.piecewise(
gmvs, [gmvs > self.imls[-1]], [self.imls[-1], lambda x: x])
idxs = gmvs_curve >= self.imls[0]
gmvs_curve = gmvs_curve[idxs]
return self._mlr_i1d(gmvs_curve), self._cov_for(gmvs_curve), idxs | [
"def",
"interpolate",
"(",
"self",
",",
"gmvs",
")",
":",
"# gmvs are clipped to max(iml)",
"gmvs_curve",
"=",
"numpy",
".",
"piecewise",
"(",
"gmvs",
",",
"[",
"gmvs",
">",
"self",
".",
"imls",
"[",
"-",
"1",
"]",
"]",
",",
"[",
"self",
".",
"imls",
... | :param gmvs:
array of intensity measure levels
:returns:
(interpolated loss ratios, interpolated covs, indices > min) | [
":",
"param",
"gmvs",
":",
"array",
"of",
"intensity",
"measure",
"levels",
":",
"returns",
":",
"(",
"interpolated",
"loss",
"ratios",
"interpolated",
"covs",
"indices",
">",
"min",
")"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L147-L159 |
gem/oq-engine | openquake/risklib/scientific.py | VulnerabilityFunction.sample | def sample(self, means, covs, idxs, epsilons=None):
"""
Sample the epsilons and apply the corrections to the means.
This method is called only if there are nonzero covs.
:param means:
array of E' loss ratios
:param covs:
array of E' floats
:param id... | python | def sample(self, means, covs, idxs, epsilons=None):
if epsilons is None:
return means
self.set_distribution(epsilons)
res = self.distribution.sample(means, covs, means * covs, idxs)
return res | [
"def",
"sample",
"(",
"self",
",",
"means",
",",
"covs",
",",
"idxs",
",",
"epsilons",
"=",
"None",
")",
":",
"if",
"epsilons",
"is",
"None",
":",
"return",
"means",
"self",
".",
"set_distribution",
"(",
"epsilons",
")",
"res",
"=",
"self",
".",
"dis... | Sample the epsilons and apply the corrections to the means.
This method is called only if there are nonzero covs.
:param means:
array of E' loss ratios
:param covs:
array of E' floats
:param idxs:
array of E booleans with E >= E'
:param epsilons:... | [
"Sample",
"the",
"epsilons",
"and",
"apply",
"the",
"corrections",
"to",
"the",
"means",
".",
"This",
"method",
"is",
"called",
"only",
"if",
"there",
"are",
"nonzero",
"covs",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L161-L181 |
gem/oq-engine | openquake/risklib/scientific.py | VulnerabilityFunction.strictly_increasing | def strictly_increasing(self):
"""
:returns:
a new vulnerability function that is strictly increasing.
It is built by removing piece of the function where the mean
loss ratio is constant.
"""
imls, mlrs, covs = [], [], []
previous_mlr = None
... | python | def strictly_increasing(self):
imls, mlrs, covs = [], [], []
previous_mlr = None
for i, mlr in enumerate(self.mean_loss_ratios):
if previous_mlr == mlr:
continue
else:
mlrs.append(mlr)
imls.append(self.imls[i])
... | [
"def",
"strictly_increasing",
"(",
"self",
")",
":",
"imls",
",",
"mlrs",
",",
"covs",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"previous_mlr",
"=",
"None",
"for",
"i",
",",
"mlr",
"in",
"enumerate",
"(",
"self",
".",
"mean_loss_ratios",
")",
"... | :returns:
a new vulnerability function that is strictly increasing.
It is built by removing piece of the function where the mean
loss ratio is constant. | [
":",
"returns",
":",
"a",
"new",
"vulnerability",
"function",
"that",
"is",
"strictly",
"increasing",
".",
"It",
"is",
"built",
"by",
"removing",
"piece",
"of",
"the",
"function",
"where",
"the",
"mean",
"loss",
"ratio",
"is",
"constant",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L194-L214 |
gem/oq-engine | openquake/risklib/scientific.py | VulnerabilityFunction.mean_loss_ratios_with_steps | def mean_loss_ratios_with_steps(self, steps):
"""
Split the mean loss ratios, producing a new set of loss ratios. The new
set of loss ratios always includes 0.0 and 1.0
:param int steps:
the number of steps we make to go from one loss
ratio to the next. For examp... | python | def mean_loss_ratios_with_steps(self, steps):
loss_ratios = self.mean_loss_ratios
if min(loss_ratios) > 0.0:
loss_ratios = numpy.concatenate([[0.0], loss_ratios])
if max(loss_ratios) < 1.0:
loss_ratios = numpy.concatenate([loss_ratios,... | [
"def",
"mean_loss_ratios_with_steps",
"(",
"self",
",",
"steps",
")",
":",
"loss_ratios",
"=",
"self",
".",
"mean_loss_ratios",
"if",
"min",
"(",
"loss_ratios",
")",
">",
"0.0",
":",
"# prepend with a zero",
"loss_ratios",
"=",
"numpy",
".",
"concatenate",
"(",
... | Split the mean loss ratios, producing a new set of loss ratios. The new
set of loss ratios always includes 0.0 and 1.0
:param int steps:
the number of steps we make to go from one loss
ratio to the next. For example, if we have [0.5, 0.7]::
steps = 1 produces [0.0,... | [
"Split",
"the",
"mean",
"loss",
"ratios",
"producing",
"a",
"new",
"set",
"of",
"loss",
"ratios",
".",
"The",
"new",
"set",
"of",
"loss",
"ratios",
"always",
"includes",
"0",
".",
"0",
"and",
"1",
".",
"0"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L216-L240 |
gem/oq-engine | openquake/risklib/scientific.py | VulnerabilityFunction._cov_for | def _cov_for(self, imls):
"""
Clip `imls` to the range associated with the support of the
vulnerability function and returns the corresponding
covariance values by linear interpolation. For instance
if the range is [0.005, 0.0269] and the imls are
[0.0049, 0.006, 0.027], ... | python | def _cov_for(self, imls):
return self._covs_i1d(
numpy.piecewise(
imls,
[imls > self.imls[-1], imls < self.imls[0]],
[self.imls[-1], self.imls[0], lambda x: x])) | [
"def",
"_cov_for",
"(",
"self",
",",
"imls",
")",
":",
"return",
"self",
".",
"_covs_i1d",
"(",
"numpy",
".",
"piecewise",
"(",
"imls",
",",
"[",
"imls",
">",
"self",
".",
"imls",
"[",
"-",
"1",
"]",
",",
"imls",
"<",
"self",
".",
"imls",
"[",
... | Clip `imls` to the range associated with the support of the
vulnerability function and returns the corresponding
covariance values by linear interpolation. For instance
if the range is [0.005, 0.0269] and the imls are
[0.0049, 0.006, 0.027], the clipped imls are
[0.005, 0.006, 0... | [
"Clip",
"imls",
"to",
"the",
"range",
"associated",
"with",
"the",
"support",
"of",
"the",
"vulnerability",
"function",
"and",
"returns",
"the",
"corresponding",
"covariance",
"values",
"by",
"linear",
"interpolation",
".",
"For",
"instance",
"if",
"the",
"range... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L242-L255 |
gem/oq-engine | openquake/risklib/scientific.py | VulnerabilityFunction.loss_ratio_exceedance_matrix | def loss_ratio_exceedance_matrix(self, loss_ratios):
"""
Compute the LREM (Loss Ratio Exceedance Matrix).
"""
# LREM has number of rows equal to the number of loss ratios
# and number of columns equal to the number of imls
lrem = numpy.empty((len(loss_ratios), len(self.im... | python | def loss_ratio_exceedance_matrix(self, loss_ratios):
lrem = numpy.empty((len(loss_ratios), len(self.imls)))
for row, loss_ratio in enumerate(loss_ratios):
for col, (mean_loss_ratio, stddev) in enumerate(
zip(self.mean_loss_ratios, self.stddevs))... | [
"def",
"loss_ratio_exceedance_matrix",
"(",
"self",
",",
"loss_ratios",
")",
":",
"# LREM has number of rows equal to the number of loss ratios",
"# and number of columns equal to the number of imls",
"lrem",
"=",
"numpy",
".",
"empty",
"(",
"(",
"len",
"(",
"loss_ratios",
")... | Compute the LREM (Loss Ratio Exceedance Matrix). | [
"Compute",
"the",
"LREM",
"(",
"Loss",
"Ratio",
"Exceedance",
"Matrix",
")",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L280-L292 |
gem/oq-engine | openquake/risklib/scientific.py | VulnerabilityFunction.mean_imls | def mean_imls(self):
"""
Compute the mean IMLs (Intensity Measure Level)
for the given vulnerability function.
:param vulnerability_function: the vulnerability function where
the IMLs (Intensity Measure Level) are taken from.
:type vuln_function:
:py:class... | python | def mean_imls(self):
return numpy.array(
[max(0, self.imls[0] - (self.imls[1] - self.imls[0]) / 2.)] +
[numpy.mean(pair) for pair in pairwise(self.imls)] +
[self.imls[-1] + (self.imls[-1] - self.imls[-2]) / 2.]) | [
"def",
"mean_imls",
"(",
"self",
")",
":",
"return",
"numpy",
".",
"array",
"(",
"[",
"max",
"(",
"0",
",",
"self",
".",
"imls",
"[",
"0",
"]",
"-",
"(",
"self",
".",
"imls",
"[",
"1",
"]",
"-",
"self",
".",
"imls",
"[",
"0",
"]",
")",
"/",... | Compute the mean IMLs (Intensity Measure Level)
for the given vulnerability function.
:param vulnerability_function: the vulnerability function where
the IMLs (Intensity Measure Level) are taken from.
:type vuln_function:
:py:class:`openquake.risklib.vulnerability_functio... | [
"Compute",
"the",
"mean",
"IMLs",
"(",
"Intensity",
"Measure",
"Level",
")",
"for",
"the",
"given",
"vulnerability",
"function",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L295-L309 |
gem/oq-engine | openquake/risklib/scientific.py | VulnerabilityFunctionWithPMF.interpolate | def interpolate(self, gmvs):
"""
:param gmvs:
array of intensity measure levels
:returns:
(interpolated probabilities, zeros, indices > min)
"""
# gmvs are clipped to max(iml)
gmvs_curve = numpy.piecewise(
gmvs, [gmvs > self.imls[-1]], [s... | python | def interpolate(self, gmvs):
gmvs_curve = numpy.piecewise(
gmvs, [gmvs > self.imls[-1]], [self.imls[-1], lambda x: x])
idxs = gmvs_curve >= self.imls[0]
gmvs_curve = gmvs_curve[idxs]
return self._probs_i1d(gmvs_curve), numpy.zeros_like(gmvs_curve), idxs | [
"def",
"interpolate",
"(",
"self",
",",
"gmvs",
")",
":",
"# gmvs are clipped to max(iml)",
"gmvs_curve",
"=",
"numpy",
".",
"piecewise",
"(",
"gmvs",
",",
"[",
"gmvs",
">",
"self",
".",
"imls",
"[",
"-",
"1",
"]",
"]",
",",
"[",
"self",
".",
"imls",
... | :param gmvs:
array of intensity measure levels
:returns:
(interpolated probabilities, zeros, indices > min) | [
":",
"param",
"gmvs",
":",
"array",
"of",
"intensity",
"measure",
"levels",
":",
"returns",
":",
"(",
"interpolated",
"probabilities",
"zeros",
"indices",
">",
"min",
")"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L392-L404 |
gem/oq-engine | openquake/risklib/scientific.py | VulnerabilityFunctionWithPMF.sample | def sample(self, probs, _covs, idxs, epsilons):
"""
Sample the .loss_ratios with the given probabilities.
:param probs:
array of E' floats
:param _covs:
ignored, it is there only for API consistency
:param idxs:
array of E booleans with E >= E'
... | python | def sample(self, probs, _covs, idxs, epsilons):
self.set_distribution(epsilons)
return self.distribution.sample(self.loss_ratios, probs) | [
"def",
"sample",
"(",
"self",
",",
"probs",
",",
"_covs",
",",
"idxs",
",",
"epsilons",
")",
":",
"self",
".",
"set_distribution",
"(",
"epsilons",
")",
"return",
"self",
".",
"distribution",
".",
"sample",
"(",
"self",
".",
"loss_ratios",
",",
"probs",
... | Sample the .loss_ratios with the given probabilities.
:param probs:
array of E' floats
:param _covs:
ignored, it is there only for API consistency
:param idxs:
array of E booleans with E >= E'
:param epsilons:
array of E floats
:return... | [
"Sample",
"the",
".",
"loss_ratios",
"with",
"the",
"given",
"probabilities",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L406-L422 |
gem/oq-engine | openquake/risklib/scientific.py | FragilityFunctionList.build | def build(self, limit_states, discretization, steps_per_interval):
"""
:param limit_states: a sequence of limit states
:param discretization: continouos fragility discretization parameter
:param steps_per_interval: steps_per_interval parameter
:returns: a populated FragilityFunct... | python | def build(self, limit_states, discretization, steps_per_interval):
new = copy.copy(self)
add_zero = (self.format == 'discrete' and
self.nodamage and self.nodamage <= self.imls[0])
new.imls = build_imls(new, discretization)
if steps_per_interval > 1:
... | [
"def",
"build",
"(",
"self",
",",
"limit_states",
",",
"discretization",
",",
"steps_per_interval",
")",
":",
"new",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"add_zero",
"=",
"(",
"self",
".",
"format",
"==",
"'discrete'",
"and",
"self",
".",
"nodamag... | :param limit_states: a sequence of limit states
:param discretization: continouos fragility discretization parameter
:param steps_per_interval: steps_per_interval parameter
:returns: a populated FragilityFunctionList instance | [
":",
"param",
"limit_states",
":",
"a",
"sequence",
"of",
"limit",
"states",
":",
"param",
"discretization",
":",
"continouos",
"fragility",
"discretization",
"parameter",
":",
"param",
"steps_per_interval",
":",
"steps_per_interval",
"parameter",
":",
"returns",
":... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L582-L610 |
gem/oq-engine | openquake/risklib/scientific.py | FragilityModel.build | def build(self, continuous_fragility_discretization, steps_per_interval):
"""
Return a new FragilityModel instance, in which the values have been
replaced with FragilityFunctionList instances.
:param continuous_fragility_discretization:
configuration parameter
:param... | python | def build(self, continuous_fragility_discretization, steps_per_interval):
newfm = copy.copy(self)
for key, ffl in self.items():
newfm[key] = ffl.build(self.limitStates,
continuous_fragility_discretization,
steps_p... | [
"def",
"build",
"(",
"self",
",",
"continuous_fragility_discretization",
",",
"steps_per_interval",
")",
":",
"newfm",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"for",
"key",
",",
"ffl",
"in",
"self",
".",
"items",
"(",
")",
":",
"newfm",
"[",
"key",
... | Return a new FragilityModel instance, in which the values have been
replaced with FragilityFunctionList instances.
:param continuous_fragility_discretization:
configuration parameter
:param steps_per_interval:
configuration parameter | [
"Return",
"a",
"new",
"FragilityModel",
"instance",
"in",
"which",
"the",
"values",
"have",
"been",
"replaced",
"with",
"FragilityFunctionList",
"instances",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L719-L734 |
gem/oq-engine | openquake/risklib/scientific.py | LossCurvesMapsBuilder.pair | def pair(self, array, stats):
"""
:return (array, array_stats) if stats, else (array, None)
"""
if len(self.weights) > 1 and stats:
statnames, statfuncs = zip(*stats)
array_stats = compute_stats2(array, statfuncs, self.weights)
else:
array_stat... | python | def pair(self, array, stats):
if len(self.weights) > 1 and stats:
statnames, statfuncs = zip(*stats)
array_stats = compute_stats2(array, statfuncs, self.weights)
else:
array_stats = None
return array, array_stats | [
"def",
"pair",
"(",
"self",
",",
"array",
",",
"stats",
")",
":",
"if",
"len",
"(",
"self",
".",
"weights",
")",
">",
"1",
"and",
"stats",
":",
"statnames",
",",
"statfuncs",
"=",
"zip",
"(",
"*",
"stats",
")",
"array_stats",
"=",
"compute_stats2",
... | :return (array, array_stats) if stats, else (array, None) | [
":",
"return",
"(",
"array",
"array_stats",
")",
"if",
"stats",
"else",
"(",
"array",
"None",
")"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1369-L1378 |
gem/oq-engine | openquake/risklib/scientific.py | LossCurvesMapsBuilder.build | def build(self, losses_by_event, stats=()):
"""
:param losses_by_event:
the aggregate loss table with shape R -> (E, L)
:param stats:
list of pairs [(statname, statfunc), ...]
:returns:
two arrays with shape (P, R, L) and (P, S, L)
"""
... | python | def build(self, losses_by_event, stats=()):
P, R = len(self.return_periods), len(self.weights)
L = len(self.loss_dt.names)
array = numpy.zeros((P, R, L), F32)
for r in losses_by_event:
num_events = self.num_events[r]
losses = losses_by_event[r]
... | [
"def",
"build",
"(",
"self",
",",
"losses_by_event",
",",
"stats",
"=",
"(",
")",
")",
":",
"P",
",",
"R",
"=",
"len",
"(",
"self",
".",
"return_periods",
")",
",",
"len",
"(",
"self",
".",
"weights",
")",
"L",
"=",
"len",
"(",
"self",
".",
"lo... | :param losses_by_event:
the aggregate loss table with shape R -> (E, L)
:param stats:
list of pairs [(statname, statfunc), ...]
:returns:
two arrays with shape (P, R, L) and (P, S, L) | [
":",
"param",
"losses_by_event",
":",
"the",
"aggregate",
"loss",
"table",
"with",
"shape",
"R",
"-",
">",
"(",
"E",
"L",
")",
":",
"param",
"stats",
":",
"list",
"of",
"pairs",
"[",
"(",
"statname",
"statfunc",
")",
"...",
"]",
":",
"returns",
":",
... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1381-L1402 |
gem/oq-engine | openquake/risklib/scientific.py | LossCurvesMapsBuilder.build_pair | def build_pair(self, losses, stats):
"""
:param losses: a list of lists with R elements
:returns: two arrays of shape (P, R) and (P, S) respectively
"""
P, R = len(self.return_periods), len(self.weights)
assert len(losses) == R, len(losses)
array = numpy.zeros((P,... | python | def build_pair(self, losses, stats):
P, R = len(self.return_periods), len(self.weights)
assert len(losses) == R, len(losses)
array = numpy.zeros((P, R), F32)
for r, ls in enumerate(losses):
ne = self.num_events.get(r, 0)
if ne:
array[:, r]... | [
"def",
"build_pair",
"(",
"self",
",",
"losses",
",",
"stats",
")",
":",
"P",
",",
"R",
"=",
"len",
"(",
"self",
".",
"return_periods",
")",
",",
"len",
"(",
"self",
".",
"weights",
")",
"assert",
"len",
"(",
"losses",
")",
"==",
"R",
",",
"len",... | :param losses: a list of lists with R elements
:returns: two arrays of shape (P, R) and (P, S) respectively | [
":",
"param",
"losses",
":",
"a",
"list",
"of",
"lists",
"with",
"R",
"elements",
":",
"returns",
":",
"two",
"arrays",
"of",
"shape",
"(",
"P",
"R",
")",
"and",
"(",
"P",
"S",
")",
"respectively"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1404-L1417 |
gem/oq-engine | openquake/risklib/scientific.py | LossCurvesMapsBuilder.build_maps | def build_maps(self, losses, clp, stats=()):
"""
:param losses: an array of shape (A, R, P)
:param clp: a list of C conditional loss poes
:param stats: list of pairs [(statname, statfunc), ...]
:returns: an array of loss_maps of shape (A, R, C, LI)
"""
shp = losse... | python | def build_maps(self, losses, clp, stats=()):
shp = losses.shape[:2] + (len(clp), len(losses.dtype))
array = numpy.zeros(shp, F32)
for lti, lt in enumerate(losses.dtype.names):
for a, losses_ in enumerate(losses[lt]):
for r, ls in enumerate(losses_):
... | [
"def",
"build_maps",
"(",
"self",
",",
"losses",
",",
"clp",
",",
"stats",
"=",
"(",
")",
")",
":",
"shp",
"=",
"losses",
".",
"shape",
"[",
":",
"2",
"]",
"+",
"(",
"len",
"(",
"clp",
")",
",",
"len",
"(",
"losses",
".",
"dtype",
")",
")",
... | :param losses: an array of shape (A, R, P)
:param clp: a list of C conditional loss poes
:param stats: list of pairs [(statname, statfunc), ...]
:returns: an array of loss_maps of shape (A, R, C, LI) | [
":",
"param",
"losses",
":",
"an",
"array",
"of",
"shape",
"(",
"A",
"R",
"P",
")",
":",
"param",
"clp",
":",
"a",
"list",
"of",
"C",
"conditional",
"loss",
"poes",
":",
"param",
"stats",
":",
"list",
"of",
"pairs",
"[",
"(",
"statname",
"statfunc"... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1426-L1441 |
gem/oq-engine | openquake/risklib/scientific.py | LossCurvesMapsBuilder.build_loss_maps | def build_loss_maps(self, losses, clp, stats=()):
"""
:param losses: an array of shape R, E
:param clp: a list of C conditional loss poes
:param stats: list of pairs [(statname, statfunc), ...]
:returns: two arrays of shape (C, R) and (C, S)
"""
array = numpy.zero... | python | def build_loss_maps(self, losses, clp, stats=()):
array = numpy.zeros((len(clp), len(losses)), F32)
for r, ls in enumerate(losses):
if len(ls) < 2:
continue
for c, poe in enumerate(clp):
array[c, r] = conditional_loss_ratio(ls, self.poes, ... | [
"def",
"build_loss_maps",
"(",
"self",
",",
"losses",
",",
"clp",
",",
"stats",
"=",
"(",
")",
")",
":",
"array",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"len",
"(",
"clp",
")",
",",
"len",
"(",
"losses",
")",
")",
",",
"F32",
")",
"for",
"r",
... | :param losses: an array of shape R, E
:param clp: a list of C conditional loss poes
:param stats: list of pairs [(statname, statfunc), ...]
:returns: two arrays of shape (C, R) and (C, S) | [
":",
"param",
"losses",
":",
"an",
"array",
"of",
"shape",
"R",
"E",
":",
"param",
"clp",
":",
"a",
"list",
"of",
"C",
"conditional",
"loss",
"poes",
":",
"param",
"stats",
":",
"list",
"of",
"pairs",
"[",
"(",
"statname",
"statfunc",
")",
"...",
"... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1444-L1457 |
gem/oq-engine | openquake/calculators/event_based.py | store_rlzs_by_grp | def store_rlzs_by_grp(dstore):
"""
Save in the datastore a composite array with fields (grp_id, gsim_id, rlzs)
"""
lst = []
assoc = dstore['csm_info'].get_rlzs_assoc()
for grp, arr in assoc.by_grp().items():
for gsim_id, rlzs in enumerate(arr):
lst.append((int(grp[4:]), gsim_... | python | def store_rlzs_by_grp(dstore):
lst = []
assoc = dstore['csm_info'].get_rlzs_assoc()
for grp, arr in assoc.by_grp().items():
for gsim_id, rlzs in enumerate(arr):
lst.append((int(grp[4:]), gsim_id, rlzs))
dstore['csm_info/rlzs_by_grp'] = numpy.array(lst, rlzs_by_grp_dt) | [
"def",
"store_rlzs_by_grp",
"(",
"dstore",
")",
":",
"lst",
"=",
"[",
"]",
"assoc",
"=",
"dstore",
"[",
"'csm_info'",
"]",
".",
"get_rlzs_assoc",
"(",
")",
"for",
"grp",
",",
"arr",
"in",
"assoc",
".",
"by_grp",
"(",
")",
".",
"items",
"(",
")",
":... | Save in the datastore a composite array with fields (grp_id, gsim_id, rlzs) | [
"Save",
"in",
"the",
"datastore",
"a",
"composite",
"array",
"with",
"fields",
"(",
"grp_id",
"gsim_id",
"rlzs",
")"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/event_based.py#L53-L62 |
gem/oq-engine | openquake/calculators/event_based.py | compute_gmfs | def compute_gmfs(rupgetter, srcfilter, param, monitor):
"""
Compute GMFs and optionally hazard curves
"""
getter = GmfGetter(rupgetter, srcfilter, param['oqparam'])
with monitor('getting ruptures'):
getter.init()
return getter.compute_gmfs_curves(monitor) | python | def compute_gmfs(rupgetter, srcfilter, param, monitor):
getter = GmfGetter(rupgetter, srcfilter, param['oqparam'])
with monitor('getting ruptures'):
getter.init()
return getter.compute_gmfs_curves(monitor) | [
"def",
"compute_gmfs",
"(",
"rupgetter",
",",
"srcfilter",
",",
"param",
",",
"monitor",
")",
":",
"getter",
"=",
"GmfGetter",
"(",
"rupgetter",
",",
"srcfilter",
",",
"param",
"[",
"'oqparam'",
"]",
")",
"with",
"monitor",
"(",
"'getting ruptures'",
")",
... | Compute GMFs and optionally hazard curves | [
"Compute",
"GMFs",
"and",
"optionally",
"hazard",
"curves"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/event_based.py#L82-L89 |
gem/oq-engine | utils/combine_mean_curves.py | combine_mean_curves | def combine_mean_curves(calc_big, calc_small):
"""
Combine the hazard curves coming from two different calculations.
The result will be the hazard curves of calc_big, updated on the sites
in common with calc_small with the PoEs of calc_small. For instance:
calc_big = USA, calc_small = California
... | python | def combine_mean_curves(calc_big, calc_small):
dstore_big = datastore.read(calc_big)
dstore_small = datastore.read(calc_small)
sitecol_big = dstore_big['sitecol']
sitecol_small = dstore_small['sitecol']
site_id_big = {(lon, lat): sid for sid, lon, lat in zip(
sitecol_big.sids, sitecol_b... | [
"def",
"combine_mean_curves",
"(",
"calc_big",
",",
"calc_small",
")",
":",
"dstore_big",
"=",
"datastore",
".",
"read",
"(",
"calc_big",
")",
"dstore_small",
"=",
"datastore",
".",
"read",
"(",
"calc_small",
")",
"sitecol_big",
"=",
"dstore_big",
"[",
"'sitec... | Combine the hazard curves coming from two different calculations.
The result will be the hazard curves of calc_big, updated on the sites
in common with calc_small with the PoEs of calc_small. For instance:
calc_big = USA, calc_small = California | [
"Combine",
"the",
"hazard",
"curves",
"coming",
"from",
"two",
"different",
"calculations",
".",
"The",
"result",
"will",
"be",
"the",
"hazard",
"curves",
"of",
"calc_big",
"updated",
"on",
"the",
"sites",
"in",
"common",
"with",
"calc_small",
"with",
"the",
... | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/utils/combine_mean_curves.py#L25-L55 |
gem/oq-engine | openquake/hmtk/sources/complex_fault_source.py | mtkComplexFaultSource.create_geometry | def create_geometry(self, input_geometry, mesh_spacing=1.0):
'''
If geometry is defined as a numpy array then create instance of
nhlib.geo.line.Line class, otherwise if already instance of class
accept class
:param input_geometry:
List of at least two fault edges of... | python | def create_geometry(self, input_geometry, mesh_spacing=1.0):
if not isinstance(input_geometry, list) or len(input_geometry) < 2:
raise ValueError('Complex fault geometry incorrectly defined')
self.fault_edges = []
for edge in input_geometry:
if not isinstance(e... | [
"def",
"create_geometry",
"(",
"self",
",",
"input_geometry",
",",
"mesh_spacing",
"=",
"1.0",
")",
":",
"if",
"not",
"isinstance",
"(",
"input_geometry",
",",
"list",
")",
"or",
"len",
"(",
"input_geometry",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",... | If geometry is defined as a numpy array then create instance of
nhlib.geo.line.Line class, otherwise if already instance of class
accept class
:param input_geometry:
List of at least two fault edges of the fault source from
shallowest to deepest. Each edge can be represe... | [
"If",
"geometry",
"is",
"defined",
"as",
"a",
"numpy",
"array",
"then",
"create",
"instance",
"of",
"nhlib",
".",
"geo",
".",
"line",
".",
"Line",
"class",
"otherwise",
"if",
"already",
"instance",
"of",
"class",
"accept",
"class"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/complex_fault_source.py#L115-L151 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.