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
sequencelengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
sequencelengths 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'] * np.log(10)
sigma = np.sqrt(sigma ** 2 + (C['a'] ** 2) * (mag_conversion_sigma ** 2))
stddevs = [sigma for _ in stddev_types]
return stddevs | 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'] ** 2) * (mag_conversion_sigma ** 2))
stddevs = [sigma for _ in stddev_types]
return stddevs | [
"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'",
"]",
"**",
"2",
")",
"*",
"(",
"mag_conversion_sigma",
"**",
"2",
")",
")",
"stddevs",
"=",
"[",
"sigma",
"for",
"_",
"in",
"stddev_types",
"]",
"return",
"stddevs"
] | 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 coefficients specific to required
# intensity measure type
C = self.COEFFS[imt]
# clip distance at 4 km, minimum distance for which the equation is
# valid (see section 2.2.4, page 201). This also avoids singularity
# in the equation
rhypo = dists.rhypo
rhypo[rhypo < 4.] = 4.
mean = C['a'] * rup.mag + C['b'] * rhypo - np.log10(rhypo)
mean[sites.vs30 >= 800] += C['c1']
mean[sites.vs30 < 800] += C['c2']
# convert from log10 to ln, and from cm/s2 to g
mean = mean * np.log(10) - 2 * np.log(10) - np.log(g)
stddevs = self._get_stddevs(C, stddev_types, rhypo.shape[0],
mag_conversion_sigma=mag_conversion_sigma)
return mean, stddevs | 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)
mean[sites.vs30 >= 800] += C['c1']
mean[sites.vs30 < 800] += C['c2']
mean = mean * np.log(10) - 2 * np.log(10) - np.log(g)
stddevs = self._get_stddevs(C, stddev_types, rhypo.shape[0],
mag_conversion_sigma=mag_conversion_sigma)
return mean, stddevs | [
"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",
"=",
"self",
".",
"COEFFS",
"[",
"imt",
"]",
"# clip distance at 4 km, minimum distance for which the equation is",
"# valid (see section 2.2.4, page 201). This also avoids singularity",
"# in the equation",
"rhypo",
"=",
"dists",
".",
"rhypo",
"rhypo",
"[",
"rhypo",
"<",
"4.",
"]",
"=",
"4.",
"mean",
"=",
"C",
"[",
"'a'",
"]",
"*",
"rup",
".",
"mag",
"+",
"C",
"[",
"'b'",
"]",
"*",
"rhypo",
"-",
"np",
".",
"log10",
"(",
"rhypo",
")",
"mean",
"[",
"sites",
".",
"vs30",
">=",
"800",
"]",
"+=",
"C",
"[",
"'c1'",
"]",
"mean",
"[",
"sites",
".",
"vs30",
"<",
"800",
"]",
"+=",
"C",
"[",
"'c2'",
"]",
"# convert from log10 to ln, and from cm/s2 to g",
"mean",
"=",
"mean",
"*",
"np",
".",
"log",
"(",
"10",
")",
"-",
"2",
"*",
"np",
".",
"log",
"(",
"10",
")",
"-",
"np",
".",
"log",
"(",
"g",
")",
"stddevs",
"=",
"self",
".",
"_get_stddevs",
"(",
"C",
",",
"stddev_types",
",",
"rhypo",
".",
"shape",
"[",
"0",
"]",
",",
"mag_conversion_sigma",
"=",
"mag_conversion_sigma",
")",
"return",
"mean",
",",
"stddevs"
] | 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_med.dat
rjb, rrup = utils.get_equivalent_distance_inslab(rup.mag, dists.repi,
hslab)
dists.rjb = rjb
dists.rrup = rrup
mean, stddevs = super().get_mean_and_stddevs(sites, rup, dists, imt,
stddev_types)
cff = self.SITE_COEFFS[imt]
mean_adj = np.log(np.exp(mean) * 10**cff['mf'])
stddevs = [np.ones(len(dists.rrup))*get_sigma(imt)]
return mean_adj, stddevs | 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, stddevs = super().get_mean_and_stddevs(sites, rup, dists, imt,
stddev_types)
cff = self.SITE_COEFFS[imt]
mean_adj = np.log(np.exp(mean) * 10**cff['mf'])
stddevs = [np.ones(len(dists.rrup))*get_sigma(imt)]
return mean_adj, stddevs | [
"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_equivalent_distance_inslab",
"(",
"rup",
".",
"mag",
",",
"dists",
".",
"repi",
",",
"hslab",
")",
"dists",
".",
"rjb",
"=",
"rjb",
"dists",
".",
"rrup",
"=",
"rrup",
"mean",
",",
"stddevs",
"=",
"super",
"(",
")",
".",
"get_mean_and_stddevs",
"(",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
"cff",
"=",
"self",
".",
"SITE_COEFFS",
"[",
"imt",
"]",
"mean_adj",
"=",
"np",
".",
"log",
"(",
"np",
".",
"exp",
"(",
"mean",
")",
"*",
"10",
"**",
"cff",
"[",
"'mf'",
"]",
")",
"stddevs",
"=",
"[",
"np",
".",
"ones",
"(",
"len",
"(",
"dists",
".",
"rrup",
")",
")",
"*",
"get_sigma",
"(",
"imt",
")",
"]",
"return",
"mean_adj",
",",
"stddevs"
] | 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)
except ValueError:
src_id = long_src_id
src_ids.append(src_id)
return ' '.join(set(src_ids)) | 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",
")",
"except",
"ValueError",
":",
"src_id",
"=",
"long_src_id",
"src_ids",
".",
"append",
"(",
"src_id",
")",
"return",
"' '",
".",
"join",
"(",
"set",
"(",
"src_ids",
")",
")"
] | :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",
"corresponding",
"to",
"the",
"maximum",
"level",
"for",
"IMTs",
"and",
"GSIMs"
] | 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.environ.get('OQ_SAMPLE_SOURCES', 0))
if ss:
splits, stime = split_sources(srcs)
srcs = readinput.random_filtered_sources(splits, srcfilter, ss)
yield classical(srcs, srcfilter, gsims, params, monitor)
return
sources = []
with monitor("filtering/splitting sources"):
for src, _sites in srcfilter(srcs):
if src.num_ruptures >= params['maxweight']:
splits, stime = split_sources([src])
sources.extend(srcfilter.filter(splits))
else:
sources.append(src)
blocks = list(block_splitter(sources, params['maxweight'],
operator.attrgetter('num_ruptures')))
if blocks:
# yield the first blocks (if any) and compute the last block in core
# NB: the last block is usually the smallest one
for block in blocks[:-1]:
yield classical, block, srcfilter, gsims, params
yield classical(blocks[-1], srcfilter, gsims, params, monitor) | python | def classical_split_filter(srcs, srcfilter, gsims, params, monitor):
ss = int(os.environ.get('OQ_SAMPLE_SOURCES', 0))
if ss:
splits, stime = split_sources(srcs)
srcs = readinput.random_filtered_sources(splits, srcfilter, ss)
yield classical(srcs, srcfilter, gsims, params, monitor)
return
sources = []
with monitor("filtering/splitting sources"):
for src, _sites in srcfilter(srcs):
if src.num_ruptures >= params['maxweight']:
splits, stime = split_sources([src])
sources.extend(srcfilter.filter(splits))
else:
sources.append(src)
blocks = list(block_splitter(sources, params['maxweight'],
operator.attrgetter('num_ruptures')))
if blocks:
for block in blocks[:-1]:
yield classical, block, srcfilter, gsims, params
yield classical(blocks[-1], srcfilter, gsims, params, monitor) | [
"def",
"classical_split_filter",
"(",
"srcs",
",",
"srcfilter",
",",
"gsims",
",",
"params",
",",
"monitor",
")",
":",
"# first check if we are sampling the sources",
"ss",
"=",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'OQ_SAMPLE_SOURCES'",
",",
"0",
")",
")",
"if",
"ss",
":",
"splits",
",",
"stime",
"=",
"split_sources",
"(",
"srcs",
")",
"srcs",
"=",
"readinput",
".",
"random_filtered_sources",
"(",
"splits",
",",
"srcfilter",
",",
"ss",
")",
"yield",
"classical",
"(",
"srcs",
",",
"srcfilter",
",",
"gsims",
",",
"params",
",",
"monitor",
")",
"return",
"sources",
"=",
"[",
"]",
"with",
"monitor",
"(",
"\"filtering/splitting sources\"",
")",
":",
"for",
"src",
",",
"_sites",
"in",
"srcfilter",
"(",
"srcs",
")",
":",
"if",
"src",
".",
"num_ruptures",
">=",
"params",
"[",
"'maxweight'",
"]",
":",
"splits",
",",
"stime",
"=",
"split_sources",
"(",
"[",
"src",
"]",
")",
"sources",
".",
"extend",
"(",
"srcfilter",
".",
"filter",
"(",
"splits",
")",
")",
"else",
":",
"sources",
".",
"append",
"(",
"src",
")",
"blocks",
"=",
"list",
"(",
"block_splitter",
"(",
"sources",
",",
"params",
"[",
"'maxweight'",
"]",
",",
"operator",
".",
"attrgetter",
"(",
"'num_ruptures'",
")",
")",
")",
"if",
"blocks",
":",
"# yield the first blocks (if any) and compute the last block in core",
"# NB: the last block is usually the smallest one",
"for",
"block",
"in",
"blocks",
"[",
":",
"-",
"1",
"]",
":",
"yield",
"classical",
",",
"block",
",",
"srcfilter",
",",
"gsims",
",",
"params",
"yield",
"classical",
"(",
"blocks",
"[",
"-",
"1",
"]",
",",
"srcfilter",
",",
"gsims",
",",
"params",
",",
"monitor",
")"
] | Split the given sources, filter the subsources and the compute the
PoEs. Yield back subtasks if the split sources contain more than
maxweight ruptures. | [
"Split",
"the",
"given",
"sources",
"filter",
"the",
"subsources",
"and",
"the",
"compute",
"the",
"PoEs",
".",
"Yield",
"back",
"subtasks",
"if",
"the",
"split",
"sources",
"contain",
"more",
"than",
"maxweight",
"ruptures",
"."
] | 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
:param monitor: instance of Monitor
:returns: a dictionary kind -> ProbabilityMap
The "kind" is a string of the form 'rlz-XXX' or 'mean' of 'quantile-XXX'
used to specify the kind of output.
"""
with monitor('combine pmaps'):
pgetter.init() # if not already initialized
try:
pmaps = pgetter.get_pmaps()
except IndexError: # no data
return {}
if sum(len(pmap) for pmap in pmaps) == 0: # no data
return {}
R = len(pmaps)
imtls, poes, weights = pgetter.imtls, pgetter.poes, pgetter.weights
pmap_by_kind = {}
hmaps_stats = []
hcurves_stats = []
with monitor('compute stats'):
for statname, stat in hstats.items():
pmap = compute_pmap_stats(pmaps, [stat], weights, imtls)
hcurves_stats.append(pmap)
if pgetter.poes:
hmaps_stats.append(
calc.make_hmap(pmap, pgetter.imtls, pgetter.poes))
if statname == 'mean' and R > 1 and N <= FEWSITES:
pmap_by_kind['rlz_by_sid'] = rlz = {}
for sid, pcurve in pmap.items():
rlz[sid] = util.closest_to_ref(
[pm.setdefault(sid, 0).array for pm in pmaps],
pcurve.array)['rlz']
if hcurves_stats:
pmap_by_kind['hcurves-stats'] = hcurves_stats
if hmaps_stats:
pmap_by_kind['hmaps-stats'] = hmaps_stats
if R > 1 and individual_curves or not hstats:
pmap_by_kind['hcurves-rlzs'] = pmaps
if pgetter.poes:
with monitor('build individual hmaps'):
pmap_by_kind['hmaps-rlzs'] = [
calc.make_hmap(pmap, imtls, poes) for pmap in pmaps]
return pmap_by_kind | 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 = len(pmaps)
imtls, poes, weights = pgetter.imtls, pgetter.poes, pgetter.weights
pmap_by_kind = {}
hmaps_stats = []
hcurves_stats = []
with monitor('compute stats'):
for statname, stat in hstats.items():
pmap = compute_pmap_stats(pmaps, [stat], weights, imtls)
hcurves_stats.append(pmap)
if pgetter.poes:
hmaps_stats.append(
calc.make_hmap(pmap, pgetter.imtls, pgetter.poes))
if statname == 'mean' and R > 1 and N <= FEWSITES:
pmap_by_kind['rlz_by_sid'] = rlz = {}
for sid, pcurve in pmap.items():
rlz[sid] = util.closest_to_ref(
[pm.setdefault(sid, 0).array for pm in pmaps],
pcurve.array)['rlz']
if hcurves_stats:
pmap_by_kind['hcurves-stats'] = hcurves_stats
if hmaps_stats:
pmap_by_kind['hmaps-stats'] = hmaps_stats
if R > 1 and individual_curves or not hstats:
pmap_by_kind['hcurves-rlzs'] = pmaps
if pgetter.poes:
with monitor('build individual hmaps'):
pmap_by_kind['hmaps-rlzs'] = [
calc.make_hmap(pmap, imtls, poes) for pmap in pmaps]
return pmap_by_kind | [
"def",
"build_hazard_stats",
"(",
"pgetter",
",",
"N",
",",
"hstats",
",",
"individual_curves",
",",
"monitor",
")",
":",
"with",
"monitor",
"(",
"'combine pmaps'",
")",
":",
"pgetter",
".",
"init",
"(",
")",
"# if not already initialized",
"try",
":",
"pmaps",
"=",
"pgetter",
".",
"get_pmaps",
"(",
")",
"except",
"IndexError",
":",
"# no data",
"return",
"{",
"}",
"if",
"sum",
"(",
"len",
"(",
"pmap",
")",
"for",
"pmap",
"in",
"pmaps",
")",
"==",
"0",
":",
"# no data",
"return",
"{",
"}",
"R",
"=",
"len",
"(",
"pmaps",
")",
"imtls",
",",
"poes",
",",
"weights",
"=",
"pgetter",
".",
"imtls",
",",
"pgetter",
".",
"poes",
",",
"pgetter",
".",
"weights",
"pmap_by_kind",
"=",
"{",
"}",
"hmaps_stats",
"=",
"[",
"]",
"hcurves_stats",
"=",
"[",
"]",
"with",
"monitor",
"(",
"'compute stats'",
")",
":",
"for",
"statname",
",",
"stat",
"in",
"hstats",
".",
"items",
"(",
")",
":",
"pmap",
"=",
"compute_pmap_stats",
"(",
"pmaps",
",",
"[",
"stat",
"]",
",",
"weights",
",",
"imtls",
")",
"hcurves_stats",
".",
"append",
"(",
"pmap",
")",
"if",
"pgetter",
".",
"poes",
":",
"hmaps_stats",
".",
"append",
"(",
"calc",
".",
"make_hmap",
"(",
"pmap",
",",
"pgetter",
".",
"imtls",
",",
"pgetter",
".",
"poes",
")",
")",
"if",
"statname",
"==",
"'mean'",
"and",
"R",
">",
"1",
"and",
"N",
"<=",
"FEWSITES",
":",
"pmap_by_kind",
"[",
"'rlz_by_sid'",
"]",
"=",
"rlz",
"=",
"{",
"}",
"for",
"sid",
",",
"pcurve",
"in",
"pmap",
".",
"items",
"(",
")",
":",
"rlz",
"[",
"sid",
"]",
"=",
"util",
".",
"closest_to_ref",
"(",
"[",
"pm",
".",
"setdefault",
"(",
"sid",
",",
"0",
")",
".",
"array",
"for",
"pm",
"in",
"pmaps",
"]",
",",
"pcurve",
".",
"array",
")",
"[",
"'rlz'",
"]",
"if",
"hcurves_stats",
":",
"pmap_by_kind",
"[",
"'hcurves-stats'",
"]",
"=",
"hcurves_stats",
"if",
"hmaps_stats",
":",
"pmap_by_kind",
"[",
"'hmaps-stats'",
"]",
"=",
"hmaps_stats",
"if",
"R",
">",
"1",
"and",
"individual_curves",
"or",
"not",
"hstats",
":",
"pmap_by_kind",
"[",
"'hcurves-rlzs'",
"]",
"=",
"pmaps",
"if",
"pgetter",
".",
"poes",
":",
"with",
"monitor",
"(",
"'build individual hmaps'",
")",
":",
"pmap_by_kind",
"[",
"'hmaps-rlzs'",
"]",
"=",
"[",
"calc",
".",
"make_hmap",
"(",
"pmap",
",",
"imtls",
",",
"poes",
")",
"for",
"pmap",
"in",
"pmaps",
"]",
"return",
"pmap_by_kind"
] | :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 -> ProbabilityMap
The "kind" is a string of the form 'rlz-XXX' or 'mean' of 'quantile-XXX'
used to specify the kind of output. | [
":",
"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",
"-",
">",
"ProbabilityMap"
] | 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 = super().get_mean_and_stddevs(
sites, rup, dists, imt, stddev_types)
C = CauzziFaccioli2008SWISS01.COEFFS
tau_ss = 'tau'
log_phi_ss = np.log(10)
mean, stddevs = _apply_adjustments(
C, self.COEFFS_FS_ROCK[imt], tau_ss,
mean, stddevs, sites, rup, dists.rhypo, imt, stddev_types,
log_phi_ss)
return mean, np.log(10 ** np.array(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_phi_ss = np.log(10)
mean, stddevs = _apply_adjustments(
C, self.COEFFS_FS_ROCK[imt], tau_ss,
mean, stddevs, sites, rup, dists.rhypo, imt, stddev_types,
log_phi_ss)
return mean, np.log(10 ** np.array(stddevs)) | [
"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_phi_ss",
"=",
"np",
".",
"log",
"(",
"10",
")",
"mean",
",",
"stddevs",
"=",
"_apply_adjustments",
"(",
"C",
",",
"self",
".",
"COEFFS_FS_ROCK",
"[",
"imt",
"]",
",",
"tau_ss",
",",
"mean",
",",
"stddevs",
",",
"sites",
",",
"rup",
",",
"dists",
".",
"rhypo",
",",
"imt",
",",
"stddev_types",
",",
"log_phi_ss",
")",
"return",
"mean",
",",
"np",
".",
"log",
"(",
"10",
"**",
"np",
".",
"array",
"(",
"stddevs",
")",
")"
] | 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:`openquake.hazardlib.geo.nodalplane.NodalPlane`.
:returns:
Tuple of two items: rupture length in width in km.
The rupture area is calculated using method
:meth:`~openquake.hazardlib.scalerel.base.BaseMSR.get_median_area`
of source's
magnitude-scaling relationship. In any case the returned
dimensions multiplication is equal to that value. Than
the area is decomposed to length and width with respect
to source's rupture aspect ratio.
If calculated rupture width being inclined by nodal plane's
dip angle would not fit in between upper and lower seismogenic
depth, the rupture width is shrunken to a maximum possible
and rupture length is extended to preserve the same area.
"""
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
- src.upper_seismogenic_depth)
max_width = (seismogenic_layer_width
/ math.sin(math.radians(nodal_plane.dip)))
if rup_width > max_width:
rup_width = max_width
rup_length = area / rup_width
return rup_length, rup_width | 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
- src.upper_seismogenic_depth)
max_width = (seismogenic_layer_width
/ math.sin(math.radians(nodal_plane.dip)))
if rup_width > max_width:
rup_width = max_width
rup_length = area / rup_width
return rup_length, rup_width | [
"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",
"-",
"src",
".",
"upper_seismogenic_depth",
")",
"max_width",
"=",
"(",
"seismogenic_layer_width",
"/",
"math",
".",
"sin",
"(",
"math",
".",
"radians",
"(",
"nodal_plane",
".",
"dip",
")",
")",
")",
"if",
"rup_width",
">",
"max_width",
":",
"rup_width",
"=",
"max_width",
"rup_length",
"=",
"area",
"/",
"rup_width",
"return",
"rup_length",
",",
"rup_width"
] | 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:
Tuple of two items: rupture length in width in km.
The rupture area is calculated using method
:meth:`~openquake.hazardlib.scalerel.base.BaseMSR.get_median_area`
of source's
magnitude-scaling relationship. In any case the returned
dimensions multiplication is equal to that value. Than
the area is decomposed to length and width with respect
to source's rupture aspect ratio.
If calculated rupture width being inclined by nodal plane's
dip angle would not fit in between upper and lower seismogenic
depth, the rupture width is shrunken to a maximum possible
and rupture length is extended to preserve the same area. | [
"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",
"]",
",",
"[",
"mrp",
",",
"mtp",
",",
"mpp",
"]",
"]",
")"
] | 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 degrees:
icr = 180. / pi
return icr * azimuth % 360., icr * plunge
else:
return azimuth % (2. * pi), plunge | 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 * plunge
else:
return azimuth % (2. * pi), plunge | [
"def",
"get_azimuth_plunge",
"(",
"vect",
",",
"degrees",
"=",
"True",
")",
":",
"if",
"vect",
"[",
"0",
"]",
">",
"0",
":",
"vect",
"=",
"-",
"1.",
"*",
"np",
".",
"copy",
"(",
"vect",
")",
"vect_hor",
"=",
"sqrt",
"(",
"vect",
"[",
"1",
"]",
"**",
"2.",
"+",
"vect",
"[",
"2",
"]",
"**",
"2.",
")",
"plunge",
"=",
"atan2",
"(",
"-",
"vect",
"[",
"0",
"]",
",",
"vect_hor",
")",
"azimuth",
"=",
"atan2",
"(",
"vect",
"[",
"2",
"]",
",",
"-",
"vect",
"[",
"1",
"]",
")",
"if",
"degrees",
":",
"icr",
"=",
"180.",
"/",
"pi",
"return",
"icr",
"*",
"azimuth",
"%",
"360.",
",",
"icr",
"*",
"plunge",
"else",
":",
"return",
"azimuth",
"%",
"(",
"2.",
"*",
"pi",
")",
",",
"plunge"
] | For a given vector in USE format, retrieve the azimuth and plunge | [
"For",
"a",
"given",
"vector",
"in",
"USE",
"format",
"retrieve",
"the",
"azimuth",
"and",
"plunge"
] | 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",
",",
"1",
"]",
",",
"tensor",
"[",
"2",
",",
"2",
"]",
",",
"tensor",
"[",
"0",
",",
"1",
"]",
",",
"tensor",
"[",
"0",
",",
"2",
"]",
",",
"tensor",
"[",
"1",
",",
"2",
"]",
"]"
] | 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')
isrt = np.argsort(eigvals)
eigenvalues = eigvals[isrt] * tensor_norm
eigenvectors = eigvects[:, isrt]
return eigenvalues, eigenvectors | 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 = eigvects[:, isrt]
return eigenvalues, eigenvectors | [
"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",
"=",
"eigvects",
"[",
":",
",",
"isrt",
"]",
"return",
"eigenvalues",
",",
"eigenvectors"
] | 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]]).T
ex = cvec(1., 0., 0.)
ez = cvec(0., 0., 1.)
exs = rotmat.T * ex
ezs = rotmat.T * ez
enodes = np.cross(ez.T, ezs.T).T
if np.linalg.norm(enodes) < 1e-10:
enodes = exs
enodess = rotmat * enodes
cos_alpha = float((ez.T * ezs))
if cos_alpha > 1.:
cos_alpha = 1.
if cos_alpha < -1.:
cos_alpha = -1.
alpha = acos(cos_alpha)
beta = np.mod(atan2(enodes[1, 0], enodes[0, 0]), pi * 2.)
gamma = np.mod(-atan2(enodess[1, 0], enodess[0, 0]), pi * 2.)
return unique_euler(alpha, beta, gamma) | 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
enodes = np.cross(ez.T, ezs.T).T
if np.linalg.norm(enodes) < 1e-10:
enodes = exs
enodess = rotmat * enodes
cos_alpha = float((ez.T * ezs))
if cos_alpha > 1.:
cos_alpha = 1.
if cos_alpha < -1.:
cos_alpha = -1.
alpha = acos(cos_alpha)
beta = np.mod(atan2(enodes[1, 0], enodes[0, 0]), pi * 2.)
gamma = np.mod(-atan2(enodess[1, 0], enodess[0, 0]), pi * 2.)
return unique_euler(alpha, beta, gamma) | [
"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",
"=",
"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",
"enodes",
"=",
"np",
".",
"cross",
"(",
"ez",
".",
"T",
",",
"ezs",
".",
"T",
")",
".",
"T",
"if",
"np",
".",
"linalg",
".",
"norm",
"(",
"enodes",
")",
"<",
"1e-10",
":",
"enodes",
"=",
"exs",
"enodess",
"=",
"rotmat",
"*",
"enodes",
"cos_alpha",
"=",
"float",
"(",
"(",
"ez",
".",
"T",
"*",
"ezs",
")",
")",
"if",
"cos_alpha",
">",
"1.",
":",
"cos_alpha",
"=",
"1.",
"if",
"cos_alpha",
"<",
"-",
"1.",
":",
"cos_alpha",
"=",
"-",
"1.",
"alpha",
"=",
"acos",
"(",
"cos_alpha",
")",
"beta",
"=",
"np",
".",
"mod",
"(",
"atan2",
"(",
"enodes",
"[",
"1",
",",
"0",
"]",
",",
"enodes",
"[",
"0",
",",
"0",
"]",
")",
",",
"pi",
"*",
"2.",
")",
"gamma",
"=",
"np",
".",
"mod",
"(",
"-",
"atan2",
"(",
"enodess",
"[",
"1",
",",
"0",
"]",
",",
"enodess",
"[",
"0",
",",
"0",
"]",
")",
",",
"pi",
"*",
"2.",
")",
"return",
"unique_euler",
"(",
"alpha",
",",
"beta",
",",
"gamma",
")"
] | 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 gamma is set
to zero, to prevent that additional ambiguity.
If alpha is near to pi/2, beta is put into the range [0,pi).
'''
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 * pi < alpha and alpha <= 2.0 * pi:
alpha = 2.0 * pi - alpha
beta = beta + pi
gamma = pi + gamma
alpha = np.mod(alpha, 2.0 * pi)
beta = np.mod(beta, 2.0 * pi)
gamma = np.mod(gamma + pi, 2.0 * pi) - pi
# If dip is exactly 90 degrees, one is still
# free to choose between looking at the plane from either side.
# Choose to look at such that beta is in the range [0,180)
# This should prevent some problems, when dip is close to 90 degrees:
if fabs(alpha - 0.5 * pi) < 1e-10:
alpha = 0.5 * pi
if fabs(beta - pi) < 1e-10:
beta = pi
if fabs(beta - 2. * pi) < 1e-10:
beta = 0.
if fabs(beta) < 1e-10:
beta = 0.
if alpha == 0.5 * pi and beta >= pi:
gamma = - gamma
beta = np.mod(beta - pi, 2.0 * pi)
gamma = np.mod(gamma + pi, 2.0 * pi) - pi
assert 0. <= beta < pi
assert -pi <= gamma < pi
if alpha < 1e-7:
beta = np.mod(beta + gamma, 2.0 * pi)
gamma = 0.
return (alpha, beta, gamma) | 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 * pi < alpha and alpha <= 2.0 * pi:
alpha = 2.0 * pi - alpha
beta = beta + pi
gamma = pi + gamma
alpha = np.mod(alpha, 2.0 * pi)
beta = np.mod(beta, 2.0 * pi)
gamma = np.mod(gamma + pi, 2.0 * pi) - pi
if fabs(alpha - 0.5 * pi) < 1e-10:
alpha = 0.5 * pi
if fabs(beta - pi) < 1e-10:
beta = pi
if fabs(beta - 2. * pi) < 1e-10:
beta = 0.
if fabs(beta) < 1e-10:
beta = 0.
if alpha == 0.5 * pi and beta >= pi:
gamma = - gamma
beta = np.mod(beta - pi, 2.0 * pi)
gamma = np.mod(gamma + pi, 2.0 * pi) - pi
assert 0. <= beta < pi
assert -pi <= gamma < pi
if alpha < 1e-7:
beta = np.mod(beta + gamma, 2.0 * pi)
gamma = 0.
return (alpha, beta, gamma) | [
"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",
"*",
"pi",
"<",
"alpha",
"and",
"alpha",
"<=",
"2.0",
"*",
"pi",
":",
"alpha",
"=",
"2.0",
"*",
"pi",
"-",
"alpha",
"beta",
"=",
"beta",
"+",
"pi",
"gamma",
"=",
"pi",
"+",
"gamma",
"alpha",
"=",
"np",
".",
"mod",
"(",
"alpha",
",",
"2.0",
"*",
"pi",
")",
"beta",
"=",
"np",
".",
"mod",
"(",
"beta",
",",
"2.0",
"*",
"pi",
")",
"gamma",
"=",
"np",
".",
"mod",
"(",
"gamma",
"+",
"pi",
",",
"2.0",
"*",
"pi",
")",
"-",
"pi",
"# If dip is exactly 90 degrees, one is still",
"# free to choose between looking at the plane from either side.",
"# Choose to look at such that beta is in the range [0,180)",
"# This should prevent some problems, when dip is close to 90 degrees:",
"if",
"fabs",
"(",
"alpha",
"-",
"0.5",
"*",
"pi",
")",
"<",
"1e-10",
":",
"alpha",
"=",
"0.5",
"*",
"pi",
"if",
"fabs",
"(",
"beta",
"-",
"pi",
")",
"<",
"1e-10",
":",
"beta",
"=",
"pi",
"if",
"fabs",
"(",
"beta",
"-",
"2.",
"*",
"pi",
")",
"<",
"1e-10",
":",
"beta",
"=",
"0.",
"if",
"fabs",
"(",
"beta",
")",
"<",
"1e-10",
":",
"beta",
"=",
"0.",
"if",
"alpha",
"==",
"0.5",
"*",
"pi",
"and",
"beta",
">=",
"pi",
":",
"gamma",
"=",
"-",
"gamma",
"beta",
"=",
"np",
".",
"mod",
"(",
"beta",
"-",
"pi",
",",
"2.0",
"*",
"pi",
")",
"gamma",
"=",
"np",
".",
"mod",
"(",
"gamma",
"+",
"pi",
",",
"2.0",
"*",
"pi",
")",
"-",
"pi",
"assert",
"0.",
"<=",
"beta",
"<",
"pi",
"assert",
"-",
"pi",
"<=",
"gamma",
"<",
"pi",
"if",
"alpha",
"<",
"1e-7",
":",
"beta",
"=",
"np",
".",
"mod",
"(",
"beta",
"+",
"gamma",
",",
"2.0",
"*",
"pi",
")",
"gamma",
"=",
"0.",
"return",
"(",
"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 gamma is set
to zero, to prevent that additional ambiguity.
If alpha is near to pi/2, beta is put into the range [0,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",
"additional",
"ambiguity",
"."
] | 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",
":",
"return",
"(",
"2.",
"/",
"3.",
")",
"*",
"(",
"log10",
"(",
"moment",
")",
"-",
"9.05",
")"
] | 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
# intensity measure type.
C = self.COEFFS[imt]
C_SR = self.COEFFS_SOIL_RESPONSE[imt]
# compute PGA on rock conditions - needed to compute non-linear
# site amplification term
pga4nl = self._get_pga_on_rock(rup, dists, C)
# equation 1, pag 106, without sigma term, that is only the first 3
# terms. The third term (site amplification) is computed as given in
# equation (6), that is the sum of a linear term - equation (7) - and
# a non-linear one - equations (8a) to (8c).
# Mref, Rref values are given in the caption to table 6, pag 119.
if imt == PGA():
# avoid recomputing PGA on rock, just add site terms
mean = np.log(pga4nl) + \
self._get_site_amplification_linear(sites.vs30, C_SR) + \
self._get_site_amplification_non_linear(sites.vs30, pga4nl,
C_SR)
else:
mean = self._compute_magnitude_scaling(rup, C) + \
self._compute_distance_scaling(rup, dists, C) + \
self._get_site_amplification_linear(sites.vs30, C_SR) + \
self._get_site_amplification_non_linear(sites.vs30, pga4nl,
C_SR)
stddevs = self._get_stddevs(C, stddev_types, num_sites=len(sites.vs30))
return mean, stddevs | 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():
mean = np.log(pga4nl) + \
self._get_site_amplification_linear(sites.vs30, C_SR) + \
self._get_site_amplification_non_linear(sites.vs30, pga4nl,
C_SR)
else:
mean = self._compute_magnitude_scaling(rup, C) + \
self._compute_distance_scaling(rup, dists, C) + \
self._get_site_amplification_linear(sites.vs30, C_SR) + \
self._get_site_amplification_non_linear(sites.vs30, pga4nl,
C_SR)
stddevs = self._get_stddevs(C, stddev_types, num_sites=len(sites.vs30))
return mean, stddevs | [
"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",
"]",
"C_SR",
"=",
"self",
".",
"COEFFS_SOIL_RESPONSE",
"[",
"imt",
"]",
"# compute PGA on rock conditions - needed to compute non-linear",
"# site amplification term",
"pga4nl",
"=",
"self",
".",
"_get_pga_on_rock",
"(",
"rup",
",",
"dists",
",",
"C",
")",
"# equation 1, pag 106, without sigma term, that is only the first 3",
"# terms. The third term (site amplification) is computed as given in",
"# equation (6), that is the sum of a linear term - equation (7) - and",
"# a non-linear one - equations (8a) to (8c).",
"# Mref, Rref values are given in the caption to table 6, pag 119.",
"if",
"imt",
"==",
"PGA",
"(",
")",
":",
"# avoid recomputing PGA on rock, just add site terms",
"mean",
"=",
"np",
".",
"log",
"(",
"pga4nl",
")",
"+",
"self",
".",
"_get_site_amplification_linear",
"(",
"sites",
".",
"vs30",
",",
"C_SR",
")",
"+",
"self",
".",
"_get_site_amplification_non_linear",
"(",
"sites",
".",
"vs30",
",",
"pga4nl",
",",
"C_SR",
")",
"else",
":",
"mean",
"=",
"self",
".",
"_compute_magnitude_scaling",
"(",
"rup",
",",
"C",
")",
"+",
"self",
".",
"_compute_distance_scaling",
"(",
"rup",
",",
"dists",
",",
"C",
")",
"+",
"self",
".",
"_get_site_amplification_linear",
"(",
"sites",
".",
"vs30",
",",
"C_SR",
")",
"+",
"self",
".",
"_get_site_amplification_non_linear",
"(",
"sites",
".",
"vs30",
",",
"pga4nl",
",",
"C_SR",
")",
"stddevs",
"=",
"self",
".",
"_get_stddevs",
"(",
"C",
",",
"stddev_types",
",",
"num_sites",
"=",
"len",
"(",
"sites",
".",
"vs30",
")",
")",
"return",
"mean",
",",
"stddevs"
] | 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) + \
C['c3'] * (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",
")",
"return",
"(",
"C",
"[",
"'c1'",
"]",
"+",
"C",
"[",
"'c2'",
"]",
"*",
"(",
"rup",
".",
"mag",
"-",
"Mref",
")",
")",
"*",
"np",
".",
"log",
"(",
"R",
"/",
"Rref",
")",
"+",
"C",
"[",
"'c3'",
"]",
"*",
"(",
"R",
"-",
"Rref",
")"
] | 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 + \
C['e5'] * (rup.mag - C['Mh']) + \
C['e6'] * (rup.mag - C['Mh']) ** 2
else:
return C['e1'] * U + C['e2'] * SS + C['e3'] * NS + C['e4'] * RS + \
C['e7'] * (rup.mag - C['Mh']) | 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['Mh']) ** 2
else:
return C['e1'] * U + C['e2'] * SS + C['e3'] * NS + C['e4'] * RS + \
C['e7'] * (rup.mag - C['Mh']) | [
"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",
"[",
"'Mh'",
"]",
")",
"**",
"2",
"else",
":",
"return",
"C",
"[",
"'e1'",
"]",
"*",
"U",
"+",
"C",
"[",
"'e2'",
"]",
"*",
"SS",
"+",
"C",
"[",
"'e3'",
"]",
"*",
"NS",
"+",
"C",
"[",
"'e4'",
"]",
"*",
"RS",
"+",
"C",
"[",
"'e7'",
"]",
"*",
"(",
"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) pag 106, without the third and fourth terms
# Mref and Rref values are given in the caption to table 6, pag 119
# Note that in the original paper, the caption reads:
# "Distance-scaling coefficients (Mref=4.5 and Rref=1.0 km for all
# periods, except Rref=5.0 km for pga4nl)". However this is a mistake
# as reported in http://www.daveboore.com/pubs_online.php:
# ERRATUM: 27 August 2008. Tom Blake pointed out that the caption to
# Table 6 should read "Distance-scaling coefficients (Mref=4.5 and
# Rref=1.0 km for all periods)".
C_pga = self.COEFFS[PGA()]
pga4nl = np.exp(self._compute_magnitude_scaling(rup, C_pga) +
self._compute_distance_scaling(rup, dists, C_pga))
return pga4nl | 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))
return pga4nl | [
"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 119",
"# Note that in the original paper, the caption reads:",
"# \"Distance-scaling coefficients (Mref=4.5 and Rref=1.0 km for all",
"# periods, except Rref=5.0 km for pga4nl)\". However this is a mistake",
"# as reported in http://www.daveboore.com/pubs_online.php:",
"# ERRATUM: 27 August 2008. Tom Blake pointed out that the caption to",
"# Table 6 should read \"Distance-scaling coefficients (Mref=4.5 and",
"# Rref=1.0 km for all periods)\".",
"C_pga",
"=",
"self",
".",
"COEFFS",
"[",
"PGA",
"(",
")",
"]",
"pga4nl",
"=",
"np",
".",
"exp",
"(",
"self",
".",
"_compute_magnitude_scaling",
"(",
"rup",
",",
"C_pga",
")",
"+",
"self",
".",
"_compute_distance_scaling",
"(",
"rup",
",",
"dists",
",",
"C_pga",
")",
")",
"return",
"pga4nl"
] | 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
return self._compute_non_linear_term(pga4nl, bnl) | 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_non_linear_term",
"(",
"pga4nl",
",",
"bnl",
")"
] | 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)
# equation (13a)
idx = vs30 <= V1
bnl[idx] = C['b1']
# equation (13b)
idx = np.where((vs30 > V1) & (vs30 <= V2))
bnl[idx] = (C['b1'] - C['b2']) * \
np.log(vs30[idx] / V2) / np.log(V1 / V2) + C['b2']
# equation (13c)
idx = np.where((vs30 > V2) & (vs30 < Vref))
bnl[idx] = C['b2'] * np.log(vs30[idx] / Vref) / np.log(V2 / Vref)
return bnl | 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']) * \
np.log(vs30[idx] / V2) / np.log(V1 / V2) + C['b2']
idx = np.where((vs30 > V2) & (vs30 < Vref))
bnl[idx] = C['b2'] * np.log(vs30[idx] / Vref) / np.log(V2 / Vref)
return bnl | [
"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",
".",
"shape",
")",
"# equation (13a)",
"idx",
"=",
"vs30",
"<=",
"V1",
"bnl",
"[",
"idx",
"]",
"=",
"C",
"[",
"'b1'",
"]",
"# equation (13b)",
"idx",
"=",
"np",
".",
"where",
"(",
"(",
"vs30",
">",
"V1",
")",
"&",
"(",
"vs30",
"<=",
"V2",
")",
")",
"bnl",
"[",
"idx",
"]",
"=",
"(",
"C",
"[",
"'b1'",
"]",
"-",
"C",
"[",
"'b2'",
"]",
")",
"*",
"np",
".",
"log",
"(",
"vs30",
"[",
"idx",
"]",
"/",
"V2",
")",
"/",
"np",
".",
"log",
"(",
"V1",
"/",
"V2",
")",
"+",
"C",
"[",
"'b2'",
"]",
"# equation (13c)",
"idx",
"=",
"np",
".",
"where",
"(",
"(",
"vs30",
">",
"V2",
")",
"&",
"(",
"vs30",
"<",
"Vref",
")",
")",
"bnl",
"[",
"idx",
"]",
"=",
"C",
"[",
"'b2'",
"]",
"*",
"np",
".",
"log",
"(",
"vs30",
"[",
"idx",
"]",
"/",
"Vref",
")",
"/",
"np",
".",
"log",
"(",
"V2",
"/",
"Vref",
")",
"return",
"bnl"
] | 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[idx] * np.log(pga_low / 0.1)
# equation (8b)
idx = np.where((pga4nl > a1) & (pga4nl <= a2))
delta_x = np.log(a2 / a1)
delta_y = bnl[idx] * np.log(a2 / pga_low)
c = (3 * delta_y - bnl[idx] * delta_x) / delta_x ** 2
d = -(2 * delta_y - bnl[idx] * delta_x) / delta_x ** 3
fnl[idx] = bnl[idx] * np.log(pga_low / 0.1) +\
c * (np.log(pga4nl[idx] / a1) ** 2) + \
d * (np.log(pga4nl[idx] / a1) ** 3)
# equation (8c)
idx = pga4nl > a2
fnl[idx] = np.squeeze(bnl[idx]) * np.log(pga4nl[idx] / 0.1)
return fnl | 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))
delta_x = np.log(a2 / a1)
delta_y = bnl[idx] * np.log(a2 / pga_low)
c = (3 * delta_y - bnl[idx] * delta_x) / delta_x ** 2
d = -(2 * delta_y - bnl[idx] * delta_x) / delta_x ** 3
fnl[idx] = bnl[idx] * np.log(pga_low / 0.1) +\
c * (np.log(pga4nl[idx] / a1) ** 2) + \
d * (np.log(pga4nl[idx] / a1) ** 3)
idx = pga4nl > a2
fnl[idx] = np.squeeze(bnl[idx]) * np.log(pga4nl[idx] / 0.1)
return fnl | [
"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",
"<=",
"a1",
"fnl",
"[",
"idx",
"]",
"=",
"bnl",
"[",
"idx",
"]",
"*",
"np",
".",
"log",
"(",
"pga_low",
"/",
"0.1",
")",
"# equation (8b)",
"idx",
"=",
"np",
".",
"where",
"(",
"(",
"pga4nl",
">",
"a1",
")",
"&",
"(",
"pga4nl",
"<=",
"a2",
")",
")",
"delta_x",
"=",
"np",
".",
"log",
"(",
"a2",
"/",
"a1",
")",
"delta_y",
"=",
"bnl",
"[",
"idx",
"]",
"*",
"np",
".",
"log",
"(",
"a2",
"/",
"pga_low",
")",
"c",
"=",
"(",
"3",
"*",
"delta_y",
"-",
"bnl",
"[",
"idx",
"]",
"*",
"delta_x",
")",
"/",
"delta_x",
"**",
"2",
"d",
"=",
"-",
"(",
"2",
"*",
"delta_y",
"-",
"bnl",
"[",
"idx",
"]",
"*",
"delta_x",
")",
"/",
"delta_x",
"**",
"3",
"fnl",
"[",
"idx",
"]",
"=",
"bnl",
"[",
"idx",
"]",
"*",
"np",
".",
"log",
"(",
"pga_low",
"/",
"0.1",
")",
"+",
"c",
"*",
"(",
"np",
".",
"log",
"(",
"pga4nl",
"[",
"idx",
"]",
"/",
"a1",
")",
"**",
"2",
")",
"+",
"d",
"*",
"(",
"np",
".",
"log",
"(",
"pga4nl",
"[",
"idx",
"]",
"/",
"a1",
")",
"**",
"3",
")",
"# equation (8c)",
"idx",
"=",
"pga4nl",
">",
"a2",
"fnl",
"[",
"idx",
"]",
"=",
"np",
".",
"squeeze",
"(",
"bnl",
"[",
"idx",
"]",
")",
"*",
"np",
".",
"log",
"(",
"pga4nl",
"[",
"idx",
"]",
"/",
"0.1",
")",
"return",
"fnl"
] | 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,
imt, stddev_types)
# Defining frequency
if imt == PGA():
freq = 50.0
elif imt == PGV():
freq = 2.0
else:
freq = 1./imt.period
# Equation 3 of Atkinson (2010)
x1 = np.min([-0.18+0.17*np.log10(freq), 0])
# Equation 4 a-b-c of Atkinson (2010)
if rup.hypo_depth < 20.0:
x0 = np.max([0.217-0.321*np.log10(freq), 0])
elif rup.hypo_depth > 35.0:
x0 = np.min([0.263+0.0924*np.log10(freq), 0.35])
else:
x0 = 0.2
# Limiting calculation distance to 1km
# (as suggested by C. Bruce Worden)
rjb = [d if d > 1 else 1 for d in dists.rjb]
# Equation 2 and 5 of Atkinson (2010)
mean += (x0 + x1*np.log10(rjb))/np.log10(np.e)
return mean, stddevs | python | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
mean, stddevs = super().get_mean_and_stddevs(sites, rup, dists,
imt, stddev_types)
if imt == PGA():
freq = 50.0
elif imt == PGV():
freq = 2.0
else:
freq = 1./imt.period
x1 = np.min([-0.18+0.17*np.log10(freq), 0])
if rup.hypo_depth < 20.0:
x0 = np.max([0.217-0.321*np.log10(freq), 0])
elif rup.hypo_depth > 35.0:
x0 = np.min([0.263+0.0924*np.log10(freq), 0.35])
else:
x0 = 0.2
rjb = [d if d > 1 else 1 for d in dists.rjb]
mean += (x0 + x1*np.log10(rjb))/np.log10(np.e)
return mean, stddevs | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"mean",
",",
"stddevs",
"=",
"super",
"(",
")",
".",
"get_mean_and_stddevs",
"(",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
"# Defining frequency",
"if",
"imt",
"==",
"PGA",
"(",
")",
":",
"freq",
"=",
"50.0",
"elif",
"imt",
"==",
"PGV",
"(",
")",
":",
"freq",
"=",
"2.0",
"else",
":",
"freq",
"=",
"1.",
"/",
"imt",
".",
"period",
"# Equation 3 of Atkinson (2010)",
"x1",
"=",
"np",
".",
"min",
"(",
"[",
"-",
"0.18",
"+",
"0.17",
"*",
"np",
".",
"log10",
"(",
"freq",
")",
",",
"0",
"]",
")",
"# Equation 4 a-b-c of Atkinson (2010)",
"if",
"rup",
".",
"hypo_depth",
"<",
"20.0",
":",
"x0",
"=",
"np",
".",
"max",
"(",
"[",
"0.217",
"-",
"0.321",
"*",
"np",
".",
"log10",
"(",
"freq",
")",
",",
"0",
"]",
")",
"elif",
"rup",
".",
"hypo_depth",
">",
"35.0",
":",
"x0",
"=",
"np",
".",
"min",
"(",
"[",
"0.263",
"+",
"0.0924",
"*",
"np",
".",
"log10",
"(",
"freq",
")",
",",
"0.35",
"]",
")",
"else",
":",
"x0",
"=",
"0.2",
"# Limiting calculation distance to 1km",
"# (as suggested by C. Bruce Worden)",
"rjb",
"=",
"[",
"d",
"if",
"d",
">",
"1",
"else",
"1",
"for",
"d",
"in",
"dists",
".",
"rjb",
"]",
"# Equation 2 and 5 of Atkinson (2010)",
"mean",
"+=",
"(",
"x0",
"+",
"x1",
"*",
"np",
".",
"log10",
"(",
"rjb",
")",
")",
"/",
"np",
".",
"log10",
"(",
"np",
".",
"e",
")",
"return",
"mean",
",",
"stddevs"
] | Using a frequency dependent correction for the mean ground motion.
Standard deviation is fixed. | [
"Using",
"a",
"frequency",
"dependent",
"correction",
"for",
"the",
"mean",
"ground",
"motion",
".",
"Standard",
"deviation",
"is",
"fixed",
"."
] | 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
# in the caption of Table 2 of Atkinson (2010)
stddevs = [0.26/np.log10(np.e) + np.zeros(num_sites)]
return stddevs | 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 independent value of sigma as recommended",
"# in the caption of Table 2 of Atkinson (2010)",
"stddevs",
"=",
"[",
"0.26",
"/",
"np",
".",
"log10",
"(",
"np",
".",
"e",
")",
"+",
"np",
".",
"zeros",
"(",
"num_sites",
")",
"]",
"return",
"stddevs"
] | 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', '@'], ('SM2', 'a3b1'))
True
>>> accept_path(['@', 'a3b1'], ('SM2', 'a3b1'))
True
>>> accept_path('@@', ('SM2', 'a3b1'))
True
"""
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 | 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",
"!=",
"'@'",
"and",
"a",
"!=",
"b",
":",
"return",
"False",
"return",
"True"
] | :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(['@', 'a3b1'], ('SM2', 'a3b1'))
True
>>> accept_path('@@', ('SM2', 'a3b1'))
True | [
":",
"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"
] | 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
trtset = set(cinfo.gsim_lt.values)
for smodel in cinfo.source_models:
# discard source models with non-acceptable lt_path
if sm_lt_path and not accept_path(smodel.path, sm_lt_path):
continue
# collect the effective tectonic region types and ruptures
trts_ = set()
for sg in smodel.src_groups:
if sg.eff_ruptures:
if (trts and sg.trt in trts) or not trts:
trts_.add(sg.trt)
# recompute the GSIM logic tree if needed
if trts_ != {'*'} and trtset != trts_:
before = cinfo.gsim_lt.get_num_paths()
gsim_lt = cinfo.gsim_lt.reduce(trts_)
after = gsim_lt.get_num_paths()
if sm_lt_path and before > after:
# print the warning only when saving the logic tree,
# i.e. when called with sm_lt_path in store_rlz_info
logging.warning('Reducing the logic tree of %s from %d to %d '
'realizations', smodel.name, before, after)
gsim_rlzs = list(gsim_lt)
all_trts = list(gsim_lt.values)
else:
gsim_rlzs = list(cinfo.gsim_lt)
all_trts = list(cinfo.gsim_lt.values)
rlzs = cinfo._get_rlzs(smodel, gsim_rlzs, cinfo.seed + offset)
assoc._add_realizations(offset, smodel, all_trts, rlzs)
offset += len(rlzs)
if assoc.realizations:
assoc._init()
return assoc | 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()
for sg in smodel.src_groups:
if sg.eff_ruptures:
if (trts and sg.trt in trts) or not trts:
trts_.add(sg.trt)
if trts_ != {'*'} and trtset != trts_:
before = cinfo.gsim_lt.get_num_paths()
gsim_lt = cinfo.gsim_lt.reduce(trts_)
after = gsim_lt.get_num_paths()
if sm_lt_path and before > after:
logging.warning('Reducing the logic tree of %s from %d to %d '
'realizations', smodel.name, before, after)
gsim_rlzs = list(gsim_lt)
all_trts = list(gsim_lt.values)
else:
gsim_rlzs = list(cinfo.gsim_lt)
all_trts = list(cinfo.gsim_lt.values)
rlzs = cinfo._get_rlzs(smodel, gsim_rlzs, cinfo.seed + offset)
assoc._add_realizations(offset, smodel, all_trts, rlzs)
offset += len(rlzs)
if assoc.realizations:
assoc._init()
return assoc | [
"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",
":",
"# discard source models with non-acceptable lt_path",
"if",
"sm_lt_path",
"and",
"not",
"accept_path",
"(",
"smodel",
".",
"path",
",",
"sm_lt_path",
")",
":",
"continue",
"# collect the effective tectonic region types and ruptures",
"trts_",
"=",
"set",
"(",
")",
"for",
"sg",
"in",
"smodel",
".",
"src_groups",
":",
"if",
"sg",
".",
"eff_ruptures",
":",
"if",
"(",
"trts",
"and",
"sg",
".",
"trt",
"in",
"trts",
")",
"or",
"not",
"trts",
":",
"trts_",
".",
"add",
"(",
"sg",
".",
"trt",
")",
"# recompute the GSIM logic tree if needed",
"if",
"trts_",
"!=",
"{",
"'*'",
"}",
"and",
"trtset",
"!=",
"trts_",
":",
"before",
"=",
"cinfo",
".",
"gsim_lt",
".",
"get_num_paths",
"(",
")",
"gsim_lt",
"=",
"cinfo",
".",
"gsim_lt",
".",
"reduce",
"(",
"trts_",
")",
"after",
"=",
"gsim_lt",
".",
"get_num_paths",
"(",
")",
"if",
"sm_lt_path",
"and",
"before",
">",
"after",
":",
"# print the warning only when saving the logic tree,",
"# i.e. when called with sm_lt_path in store_rlz_info",
"logging",
".",
"warning",
"(",
"'Reducing the logic tree of %s from %d to %d '",
"'realizations'",
",",
"smodel",
".",
"name",
",",
"before",
",",
"after",
")",
"gsim_rlzs",
"=",
"list",
"(",
"gsim_lt",
")",
"all_trts",
"=",
"list",
"(",
"gsim_lt",
".",
"values",
")",
"else",
":",
"gsim_rlzs",
"=",
"list",
"(",
"cinfo",
".",
"gsim_lt",
")",
"all_trts",
"=",
"list",
"(",
"cinfo",
".",
"gsim_lt",
".",
"values",
")",
"rlzs",
"=",
"cinfo",
".",
"_get_rlzs",
"(",
"smodel",
",",
"gsim_rlzs",
",",
"cinfo",
".",
"seed",
"+",
"offset",
")",
"assoc",
".",
"_add_realizations",
"(",
"offset",
",",
"smodel",
",",
"all_trts",
",",
"rlzs",
")",
"offset",
"+=",
"len",
"(",
"rlzs",
")",
"if",
"assoc",
".",
"realizations",
":",
"assoc",
".",
"_init",
"(",
")",
"return",
"assoc"
] | :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",
"trts",
":",
"tectonic",
"region",
"types",
"to",
"accept"
] | 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
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: # assume TRT string
trt = trt_or_grp_id
acc = collections.defaultdict(list)
if sm_id is None: # full dictionary
for rlz, gsim_by_trt in zip(self.realizations, self.gsim_by_trt):
acc[gsim_by_trt[trt]].append(rlz.ordinal)
else: # dictionary for the selected source model
for rlz in self.rlzs_by_smodel[sm_id]:
gsim_by_trt = self.gsim_by_trt[rlz.ordinal]
try: # if there is a single TRT
[gsim] = gsim_by_trt.values()
except ValueError: # there is more than 1 TRT
gsim = gsim_by_trt[trt]
acc[gsim].append(rlz.ordinal)
return {gsim: numpy.array(acc[gsim], dtype=U16)
for gsim in sorted(acc)} | 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.defaultdict(list)
if sm_id is None:
for rlz, gsim_by_trt in zip(self.realizations, self.gsim_by_trt):
acc[gsim_by_trt[trt]].append(rlz.ordinal)
else:
for rlz in self.rlzs_by_smodel[sm_id]:
gsim_by_trt = self.gsim_by_trt[rlz.ordinal]
try:
[gsim] = gsim_by_trt.values()
except ValueError:
gsim = gsim_by_trt[trt]
acc[gsim].append(rlz.ordinal)
return {gsim: numpy.array(acc[gsim], dtype=U16)
for gsim in sorted(acc)} | [
"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",
".",
"trt_by_grp",
"[",
"trt_or_grp_id",
"]",
"sm_id",
"=",
"self",
".",
"csm_info",
".",
"get_sm_by_grp",
"(",
")",
"[",
"trt_or_grp_id",
"]",
"else",
":",
"# assume TRT string",
"trt",
"=",
"trt_or_grp_id",
"acc",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"if",
"sm_id",
"is",
"None",
":",
"# full dictionary",
"for",
"rlz",
",",
"gsim_by_trt",
"in",
"zip",
"(",
"self",
".",
"realizations",
",",
"self",
".",
"gsim_by_trt",
")",
":",
"acc",
"[",
"gsim_by_trt",
"[",
"trt",
"]",
"]",
".",
"append",
"(",
"rlz",
".",
"ordinal",
")",
"else",
":",
"# dictionary for the selected source model",
"for",
"rlz",
"in",
"self",
".",
"rlzs_by_smodel",
"[",
"sm_id",
"]",
":",
"gsim_by_trt",
"=",
"self",
".",
"gsim_by_trt",
"[",
"rlz",
".",
"ordinal",
"]",
"try",
":",
"# if there is a single TRT",
"[",
"gsim",
"]",
"=",
"gsim_by_trt",
".",
"values",
"(",
")",
"except",
"ValueError",
":",
"# there is more than 1 TRT",
"gsim",
"=",
"gsim_by_trt",
"[",
"trt",
"]",
"acc",
"[",
"gsim",
"]",
".",
"append",
"(",
"rlz",
".",
"ordinal",
")",
"return",
"{",
"gsim",
":",
"numpy",
".",
"array",
"(",
"acc",
"[",
"gsim",
"]",
",",
"dtype",
"=",
"U16",
")",
"for",
"gsim",
"in",
"sorted",
"(",
"acc",
")",
"}"
] | :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 = self.get_rlzs_by_gsim(sg.trt, sm.ordinal)
if not rlzs_by_gsim:
continue
dic['grp-%02d' % sg.id] = numpy.array(
list(rlzs_by_gsim.values()))
return dic | 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:
continue
dic['grp-%02d' % sg.id] = numpy.array(
list(rlzs_by_gsim.values()))
return dic | [
"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_ruptures",
":",
"continue",
"rlzs_by_gsim",
"=",
"self",
".",
"get_rlzs_by_gsim",
"(",
"sg",
".",
"trt",
",",
"sm",
".",
"ordinal",
")",
"if",
"not",
"rlzs_by_gsim",
":",
"continue",
"dic",
"[",
"'grp-%02d'",
"%",
"sg",
".",
"id",
"]",
"=",
"numpy",
".",
"array",
"(",
"list",
"(",
"rlzs_by_gsim",
".",
"values",
"(",
")",
")",
")",
"return",
"dic"
] | :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)
for rlz in self.realizations:
for k in rlz.weight.dic:
rlz.weight.dic[k] = 1. / self.num_samples
else:
tot_weight = sum(rlz.weight for rlz in self.realizations)
if not tot_weight.is_one():
# this may happen for rounding errors or because of the
# logic tree reduction; we ensure the sum of the weights is 1
for rlz in self.realizations:
rlz.weight = rlz.weight / tot_weight | 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_samples
else:
tot_weight = sum(rlz.weight for rlz in self.realizations)
if not tot_weight.is_one():
for rlz in self.realizations:
rlz.weight = rlz.weight / tot_weight | [
"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_samples",
"else",
":",
"tot_weight",
"=",
"sum",
"(",
"rlz",
".",
"weight",
"for",
"rlz",
"in",
"self",
".",
"realizations",
")",
"if",
"not",
"tot_weight",
".",
"is_one",
"(",
")",
":",
"# this may happen for rounding errors or because of the",
"# logic tree reduction; we ensure the sum of the weights is 1",
"for",
"rlz",
"in",
"self",
".",
"realizations",
":",
"rlz",
".",
"weight",
"=",
"rlz",
".",
"weight",
"/",
"tot_weight"
] | 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
pmaps = [probability_map.ProbabilityMap(num_levels, 1)
for _ in self.realizations]
array = self.by_grp()
for grp in pmap_by_grp:
for gsim_idx, rlzis in enumerate(array[grp]):
pmap = pmap_by_grp[grp].extract(gsim_idx)
for rlzi in rlzis:
pmaps[rlzi] |= pmap
return pmaps | 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_idx, rlzis in enumerate(array[grp]):
pmap = pmap_by_grp[grp].extract(gsim_idx)
for rlzi in rlzis:
pmaps[rlzi] |= pmap
return pmaps | [
"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",
"=",
"[",
"probability_map",
".",
"ProbabilityMap",
"(",
"num_levels",
",",
"1",
")",
"for",
"_",
"in",
"self",
".",
"realizations",
"]",
"array",
"=",
"self",
".",
"by_grp",
"(",
")",
"for",
"grp",
"in",
"pmap_by_grp",
":",
"for",
"gsim_idx",
",",
"rlzis",
"in",
"enumerate",
"(",
"array",
"[",
"grp",
"]",
")",
":",
"pmap",
"=",
"pmap_by_grp",
"[",
"grp",
"]",
".",
"extract",
"(",
"gsim_idx",
")",
"for",
"rlzi",
"in",
"rlzis",
":",
"pmaps",
"[",
"rlzi",
"]",
"|=",
"pmap",
"return",
"pmaps"
] | :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
with performance.Monitor('export', measuremem=True) as mon:
for fmt in exports.split(','):
fnames = export_((datastore_key, fmt), dstore)
nbytes = sum(os.path.getsize(f) for f in fnames)
print('Exported %s in %s' % (general.humansize(nbytes), fnames))
if mon.duration > 1:
print(mon)
dstore.close() | python | def export(datastore_key, calc_id=-1, exports='csv', export_dir='.'):
dstore = util.read(calc_id)
parent_id = dstore['oqparam'].hazard_calculation_id
if parent_id:
dstore.parent = util.read(parent_id)
dstore.export_dir = export_dir
with performance.Monitor('export', measuremem=True) as mon:
for fmt in exports.split(','):
fnames = export_((datastore_key, fmt), dstore)
nbytes = sum(os.path.getsize(f) for f in fnames)
print('Exported %s in %s' % (general.humansize(nbytes), fnames))
if mon.duration > 1:
print(mon)
dstore.close() | [
"def",
"export",
"(",
"datastore_key",
",",
"calc_id",
"=",
"-",
"1",
",",
"exports",
"=",
"'csv'",
",",
"export_dir",
"=",
"'.'",
")",
":",
"dstore",
"=",
"util",
".",
"read",
"(",
"calc_id",
")",
"parent_id",
"=",
"dstore",
"[",
"'oqparam'",
"]",
".",
"hazard_calculation_id",
"if",
"parent_id",
":",
"dstore",
".",
"parent",
"=",
"util",
".",
"read",
"(",
"parent_id",
")",
"dstore",
".",
"export_dir",
"=",
"export_dir",
"with",
"performance",
".",
"Monitor",
"(",
"'export'",
",",
"measuremem",
"=",
"True",
")",
"as",
"mon",
":",
"for",
"fmt",
"in",
"exports",
".",
"split",
"(",
"','",
")",
":",
"fnames",
"=",
"export_",
"(",
"(",
"datastore_key",
",",
"fmt",
")",
",",
"dstore",
")",
"nbytes",
"=",
"sum",
"(",
"os",
".",
"path",
".",
"getsize",
"(",
"f",
")",
"for",
"f",
"in",
"fnames",
")",
"print",
"(",
"'Exported %s in %s'",
"%",
"(",
"general",
".",
"humansize",
"(",
"nbytes",
")",
",",
"fnames",
")",
")",
"if",
"mon",
".",
"duration",
">",
"1",
":",
"print",
"(",
"mon",
")",
"dstore",
".",
"close",
"(",
")"
] | Export an output from the datastore. | [
"Export",
"an",
"output",
"from",
"the",
"datastore",
"."
] | 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.attrib:
# Is a time-dependent model - even if rates were originally
# poissonian
# Verify that the source time span is the same as the TOM time span
inv_time = float(node["investigationTime"])
if inv_time != self.investigation_time:
raise ValueError("Source investigation time (%s) is not "
"equal to configuration investigation time "
"(%s)" % (inv_time, self.investigation_time))
start_date = datetime.strptime(node["startDate"], "%d/%m/%Y")
else:
start_date = None
return UCERFSource(
source_file,
self.investigation_time,
start_date,
float(node["minMag"]),
npd=self.convert_npdist(node),
hdd=self.convert_hpdist(node),
aspect=~node.ruptAspectRatio,
upper_seismogenic_depth=~node.pointGeometry.upperSeismoDepth,
lower_seismogenic_depth=~node.pointGeometry.lowerSeismoDepth,
msr=valid.SCALEREL[~node.magScaleRel](),
mesh_spacing=self.rupture_mesh_spacing,
trt=node["tectonicRegion"]) | python | def convert_UCERFSource(self, node):
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 != self.investigation_time:
raise ValueError("Source investigation time (%s) is not "
"equal to configuration investigation time "
"(%s)" % (inv_time, self.investigation_time))
start_date = datetime.strptime(node["startDate"], "%d/%m/%Y")
else:
start_date = None
return UCERFSource(
source_file,
self.investigation_time,
start_date,
float(node["minMag"]),
npd=self.convert_npdist(node),
hdd=self.convert_hpdist(node),
aspect=~node.ruptAspectRatio,
upper_seismogenic_depth=~node.pointGeometry.upperSeismoDepth,
lower_seismogenic_depth=~node.pointGeometry.lowerSeismoDepth,
msr=valid.SCALEREL[~node.magScaleRel](),
mesh_spacing=self.rupture_mesh_spacing,
trt=node["tectonicRegion"]) | [
"def",
"convert_UCERFSource",
"(",
"self",
",",
"node",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"fname",
")",
"# where the source_model_file is",
"source_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"node",
"[",
"\"filename\"",
"]",
")",
"if",
"\"startDate\"",
"in",
"node",
".",
"attrib",
"and",
"\"investigationTime\"",
"in",
"node",
".",
"attrib",
":",
"# Is a time-dependent model - even if rates were originally",
"# poissonian",
"# Verify that the source time span is the same as the TOM time span",
"inv_time",
"=",
"float",
"(",
"node",
"[",
"\"investigationTime\"",
"]",
")",
"if",
"inv_time",
"!=",
"self",
".",
"investigation_time",
":",
"raise",
"ValueError",
"(",
"\"Source investigation time (%s) is not \"",
"\"equal to configuration investigation time \"",
"\"(%s)\"",
"%",
"(",
"inv_time",
",",
"self",
".",
"investigation_time",
")",
")",
"start_date",
"=",
"datetime",
".",
"strptime",
"(",
"node",
"[",
"\"startDate\"",
"]",
",",
"\"%d/%m/%Y\"",
")",
"else",
":",
"start_date",
"=",
"None",
"return",
"UCERFSource",
"(",
"source_file",
",",
"self",
".",
"investigation_time",
",",
"start_date",
",",
"float",
"(",
"node",
"[",
"\"minMag\"",
"]",
")",
",",
"npd",
"=",
"self",
".",
"convert_npdist",
"(",
"node",
")",
",",
"hdd",
"=",
"self",
".",
"convert_hpdist",
"(",
"node",
")",
",",
"aspect",
"=",
"~",
"node",
".",
"ruptAspectRatio",
",",
"upper_seismogenic_depth",
"=",
"~",
"node",
".",
"pointGeometry",
".",
"upperSeismoDepth",
",",
"lower_seismogenic_depth",
"=",
"~",
"node",
".",
"pointGeometry",
".",
"lowerSeismoDepth",
",",
"msr",
"=",
"valid",
".",
"SCALEREL",
"[",
"~",
"node",
".",
"magScaleRel",
"]",
"(",
")",
",",
"mesh_spacing",
"=",
"self",
".",
"rupture_mesh_spacing",
",",
"trt",
"=",
"node",
"[",
"\"tectonicRegion\"",
"]",
")"
] | Converts the Ucerf Source node into an SES Control object | [
"Converts",
"the",
"Ucerf",
"Source",
"node",
"into",
"an",
"SES",
"Control",
"object"
] | 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_set[2], "Magnitude"])}
idx_set["rate"] = "/".join(code_set)
idx_set["rake"] = "/".join([code_set[0], code_set[1], "Rake"])
idx_set["msr"] = "-".join(code_set[:3])
idx_set["geol"] = code_set[0]
if start_date: # time-dependent source
idx_set["grid_key"] = "_".join(
branch_id.replace("/", "_").split("_")[:-1])
else: # time-independent source
idx_set["grid_key"] = branch_id.replace("/", "_")
idx_set["total_key"] = branch_id.replace("/", "|")
return idx_set | python | def build_idx_set(branch_id, start_date):
code_set = branch_id.split("/")
code_set.insert(3, "Rates")
idx_set = {
"sec": "/".join([code_set[0], code_set[1], "Sections"]),
"mag": "/".join([code_set[0], code_set[1], code_set[2], "Magnitude"])}
idx_set["rate"] = "/".join(code_set)
idx_set["rake"] = "/".join([code_set[0], code_set[1], "Rake"])
idx_set["msr"] = "-".join(code_set[:3])
idx_set["geol"] = code_set[0]
if start_date:
idx_set["grid_key"] = "_".join(
branch_id.replace("/", "_").split("_")[:-1])
else:
idx_set["grid_key"] = branch_id.replace("/", "_")
idx_set["total_key"] = branch_id.replace("/", "|")
return idx_set | [
"def",
"build_idx_set",
"(",
"branch_id",
",",
"start_date",
")",
":",
"code_set",
"=",
"branch_id",
".",
"split",
"(",
"\"/\"",
")",
"code_set",
".",
"insert",
"(",
"3",
",",
"\"Rates\"",
")",
"idx_set",
"=",
"{",
"\"sec\"",
":",
"\"/\"",
".",
"join",
"(",
"[",
"code_set",
"[",
"0",
"]",
",",
"code_set",
"[",
"1",
"]",
",",
"\"Sections\"",
"]",
")",
",",
"\"mag\"",
":",
"\"/\"",
".",
"join",
"(",
"[",
"code_set",
"[",
"0",
"]",
",",
"code_set",
"[",
"1",
"]",
",",
"code_set",
"[",
"2",
"]",
",",
"\"Magnitude\"",
"]",
")",
"}",
"idx_set",
"[",
"\"rate\"",
"]",
"=",
"\"/\"",
".",
"join",
"(",
"code_set",
")",
"idx_set",
"[",
"\"rake\"",
"]",
"=",
"\"/\"",
".",
"join",
"(",
"[",
"code_set",
"[",
"0",
"]",
",",
"code_set",
"[",
"1",
"]",
",",
"\"Rake\"",
"]",
")",
"idx_set",
"[",
"\"msr\"",
"]",
"=",
"\"-\"",
".",
"join",
"(",
"code_set",
"[",
":",
"3",
"]",
")",
"idx_set",
"[",
"\"geol\"",
"]",
"=",
"code_set",
"[",
"0",
"]",
"if",
"start_date",
":",
"# time-dependent source",
"idx_set",
"[",
"\"grid_key\"",
"]",
"=",
"\"_\"",
".",
"join",
"(",
"branch_id",
".",
"replace",
"(",
"\"/\"",
",",
"\"_\"",
")",
".",
"split",
"(",
"\"_\"",
")",
"[",
":",
"-",
"1",
"]",
")",
"else",
":",
"# time-independent source",
"idx_set",
"[",
"\"grid_key\"",
"]",
"=",
"branch_id",
".",
"replace",
"(",
"\"/\"",
",",
"\"_\"",
")",
"idx_set",
"[",
"\"total_key\"",
"]",
"=",
"branch_id",
".",
"replace",
"(",
"\"/\"",
",",
"\"|\"",
")",
"return",
"idx_set"
] | Builds a dictionary of keys based on the branch code | [
"Builds",
"a",
"dictionary",
"of",
"keys",
"based",
"on",
"the",
"branch",
"code"
] | 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:`openquake.hazardlib.geo.nodalplane.NodalPlane`.
:returns:
Tuple of two items: rupture length in width in km.
The rupture area is calculated using method
:meth:`~openquake.hazardlib.scalerel.base.BaseMSR.get_median_area`
of source's
magnitude-scaling relationship. In any case the returned
dimensions multiplication is equal to that value. Than
the area is decomposed to length and width with respect
to source's rupture aspect ratio.
If calculated rupture width being inclined by nodal plane's
dip angle would not fit in between upper and lower seismogenic
depth, the rupture width is shrunken to a maximum possible
and rupture length is extended to preserve the same area.
"""
area = msr.get_median_area(mag, nodal_plane.rake)
rup_length = math.sqrt(area * rupture_aspect_ratio)
rup_width = area / rup_length
seismogenic_layer_width = (lower_seismogenic_depth -
upper_seismogenic_depth)
max_width = (seismogenic_layer_width /
math.sin(math.radians(nodal_plane.dip)))
if rup_width > max_width:
rup_width = max_width
rup_length = area / rup_width
return rup_length, rup_width | 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_width = (lower_seismogenic_depth -
upper_seismogenic_depth)
max_width = (seismogenic_layer_width /
math.sin(math.radians(nodal_plane.dip)))
if rup_width > max_width:
rup_width = max_width
rup_length = area / rup_width
return rup_length, rup_width | [
"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_width",
"=",
"(",
"lower_seismogenic_depth",
"-",
"upper_seismogenic_depth",
")",
"max_width",
"=",
"(",
"seismogenic_layer_width",
"/",
"math",
".",
"sin",
"(",
"math",
".",
"radians",
"(",
"nodal_plane",
".",
"dip",
")",
")",
")",
"if",
"rup_width",
">",
"max_width",
":",
"rup_width",
"=",
"max_width",
"rup_length",
"=",
"area",
"/",
"rup_width",
"return",
"rup_length",
",",
"rup_width"
] | 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 method
:meth:`~openquake.hazardlib.scalerel.base.BaseMSR.get_median_area`
of source's
magnitude-scaling relationship. In any case the returned
dimensions multiplication is equal to that value. Than
the area is decomposed to length and width with respect
to source's rupture aspect ratio.
If calculated rupture width being inclined by nodal plane's
dip angle would not fit in between upper and lower seismogenic
depth, the rupture width is shrunken to a maximum possible
and rupture length is extended to preserve the same area. | [
"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 to calculate rupture dimensions,
see :meth:`_get_rupture_dimensions`.
:param nodal_plane:
Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane`
describing the rupture orientation.
:param hypocenter:
Point representing rupture's hypocenter.
:returns:
Instance of
:class:`~openquake.hazardlib.geo.surface.planar.PlanarSurface`.
"""
assert (upper_seismogenic_depth <= hypocenter.depth
and lower_seismogenic_depth >= hypocenter.depth)
rdip = math.radians(nodal_plane.dip)
# precalculated azimuth values for horizontal-only and vertical-only
# moves from one point to another on the plane defined by strike
# and dip:
azimuth_right = nodal_plane.strike
azimuth_down = (azimuth_right + 90) % 360
azimuth_left = (azimuth_down + 90) % 360
azimuth_up = (azimuth_left + 90) % 360
rup_length, rup_width = get_rupture_dimensions(
mag, nodal_plane, msr, rupture_aspect_ratio, upper_seismogenic_depth,
lower_seismogenic_depth)
# calculate the height of the rupture being projected
# on the vertical plane:
rup_proj_height = rup_width * math.sin(rdip)
# and it's width being projected on the horizontal one:
rup_proj_width = rup_width * math.cos(rdip)
# half height of the vertical component of rupture width
# is the vertical distance between the rupture geometrical
# center and it's upper and lower borders:
hheight = rup_proj_height / 2
# calculate how much shallower the upper border of the rupture
# is than the upper seismogenic depth:
vshift = upper_seismogenic_depth - hypocenter.depth + hheight
# if it is shallower (vshift > 0) than we need to move the rupture
# by that value vertically.
if vshift < 0:
# the top edge is below upper seismogenic depth. now we need
# to check that we do not cross the lower border.
vshift = lower_seismogenic_depth - hypocenter.depth - hheight
if vshift > 0:
# the bottom edge of the rupture is above the lower sesmogenic
# depth. that means that we don't need to move the rupture
# as it fits inside seismogenic layer.
vshift = 0
# if vshift < 0 than we need to move the rupture up by that value.
# now we need to find the position of rupture's geometrical center.
# in any case the hypocenter point must lie on the surface, however
# the rupture center might be off (below or above) along the dip.
rupture_center = hypocenter
if vshift != 0:
# we need to move the rupture center to make the rupture fit
# inside the seismogenic layer.
hshift = abs(vshift / math.tan(rdip))
rupture_center = rupture_center.point_at(
horizontal_distance=hshift, vertical_increment=vshift,
azimuth=(azimuth_up if vshift < 0 else azimuth_down))
# from the rupture center we can now compute the coordinates of the
# four coorners by moving along the diagonals of the plane. This seems
# to be better then moving along the perimeter, because in this case
# errors are accumulated that induce distorsions in the shape with
# consequent raise of exceptions when creating PlanarSurface objects
# theta is the angle between the diagonal of the surface projection
# and the line passing through the rupture center and parallel to the
# top and bottom edges. Theta is zero for vertical ruptures (because
# rup_proj_width is zero)
theta = math.degrees(
math.atan((rup_proj_width / 2.) / (rup_length / 2.)))
hor_dist = math.sqrt(
(rup_length / 2.) ** 2 + (rup_proj_width / 2.) ** 2)
left_top = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=-rup_proj_height / 2,
azimuth=(nodal_plane.strike + 180 + theta) % 360)
right_top = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=-rup_proj_height / 2,
azimuth=(nodal_plane.strike - theta) % 360)
left_bottom = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=rup_proj_height / 2,
azimuth=(nodal_plane.strike + 180 - theta) % 360)
right_bottom = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=rup_proj_height / 2,
azimuth=(nodal_plane.strike + theta) % 360)
return PlanarSurface(nodal_plane.strike, nodal_plane.dip,
left_top, right_top, right_bottom, left_bottom) | python | def get_rupture_surface(mag, nodal_plane, hypocenter, msr,
rupture_aspect_ratio, upper_seismogenic_depth,
lower_seismogenic_depth, mesh_spacing=1.0):
assert (upper_seismogenic_depth <= hypocenter.depth
and lower_seismogenic_depth >= hypocenter.depth)
rdip = math.radians(nodal_plane.dip)
azimuth_right = nodal_plane.strike
azimuth_down = (azimuth_right + 90) % 360
azimuth_left = (azimuth_down + 90) % 360
azimuth_up = (azimuth_left + 90) % 360
rup_length, rup_width = get_rupture_dimensions(
mag, nodal_plane, msr, rupture_aspect_ratio, upper_seismogenic_depth,
lower_seismogenic_depth)
rup_proj_height = rup_width * math.sin(rdip)
rup_proj_width = rup_width * math.cos(rdip)
hheight = rup_proj_height / 2
vshift = upper_seismogenic_depth - hypocenter.depth + hheight
if vshift < 0:
vshift = lower_seismogenic_depth - hypocenter.depth - hheight
if vshift > 0:
vshift = 0
rupture_center = hypocenter
if vshift != 0:
hshift = abs(vshift / math.tan(rdip))
rupture_center = rupture_center.point_at(
horizontal_distance=hshift, vertical_increment=vshift,
azimuth=(azimuth_up if vshift < 0 else azimuth_down))
theta = math.degrees(
math.atan((rup_proj_width / 2.) / (rup_length / 2.)))
hor_dist = math.sqrt(
(rup_length / 2.) ** 2 + (rup_proj_width / 2.) ** 2)
left_top = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=-rup_proj_height / 2,
azimuth=(nodal_plane.strike + 180 + theta) % 360)
right_top = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=-rup_proj_height / 2,
azimuth=(nodal_plane.strike - theta) % 360)
left_bottom = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=rup_proj_height / 2,
azimuth=(nodal_plane.strike + 180 - theta) % 360)
right_bottom = rupture_center.point_at(
horizontal_distance=hor_dist,
vertical_increment=rup_proj_height / 2,
azimuth=(nodal_plane.strike + theta) % 360)
return PlanarSurface(nodal_plane.strike, nodal_plane.dip,
left_top, right_top, right_bottom, left_bottom) | [
"def",
"get_rupture_surface",
"(",
"mag",
",",
"nodal_plane",
",",
"hypocenter",
",",
"msr",
",",
"rupture_aspect_ratio",
",",
"upper_seismogenic_depth",
",",
"lower_seismogenic_depth",
",",
"mesh_spacing",
"=",
"1.0",
")",
":",
"assert",
"(",
"upper_seismogenic_depth",
"<=",
"hypocenter",
".",
"depth",
"and",
"lower_seismogenic_depth",
">=",
"hypocenter",
".",
"depth",
")",
"rdip",
"=",
"math",
".",
"radians",
"(",
"nodal_plane",
".",
"dip",
")",
"# precalculated azimuth values for horizontal-only and vertical-only",
"# moves from one point to another on the plane defined by strike",
"# and dip:",
"azimuth_right",
"=",
"nodal_plane",
".",
"strike",
"azimuth_down",
"=",
"(",
"azimuth_right",
"+",
"90",
")",
"%",
"360",
"azimuth_left",
"=",
"(",
"azimuth_down",
"+",
"90",
")",
"%",
"360",
"azimuth_up",
"=",
"(",
"azimuth_left",
"+",
"90",
")",
"%",
"360",
"rup_length",
",",
"rup_width",
"=",
"get_rupture_dimensions",
"(",
"mag",
",",
"nodal_plane",
",",
"msr",
",",
"rupture_aspect_ratio",
",",
"upper_seismogenic_depth",
",",
"lower_seismogenic_depth",
")",
"# calculate the height of the rupture being projected",
"# on the vertical plane:",
"rup_proj_height",
"=",
"rup_width",
"*",
"math",
".",
"sin",
"(",
"rdip",
")",
"# and it's width being projected on the horizontal one:",
"rup_proj_width",
"=",
"rup_width",
"*",
"math",
".",
"cos",
"(",
"rdip",
")",
"# half height of the vertical component of rupture width",
"# is the vertical distance between the rupture geometrical",
"# center and it's upper and lower borders:",
"hheight",
"=",
"rup_proj_height",
"/",
"2",
"# calculate how much shallower the upper border of the rupture",
"# is than the upper seismogenic depth:",
"vshift",
"=",
"upper_seismogenic_depth",
"-",
"hypocenter",
".",
"depth",
"+",
"hheight",
"# if it is shallower (vshift > 0) than we need to move the rupture",
"# by that value vertically.",
"if",
"vshift",
"<",
"0",
":",
"# the top edge is below upper seismogenic depth. now we need",
"# to check that we do not cross the lower border.",
"vshift",
"=",
"lower_seismogenic_depth",
"-",
"hypocenter",
".",
"depth",
"-",
"hheight",
"if",
"vshift",
">",
"0",
":",
"# the bottom edge of the rupture is above the lower sesmogenic",
"# depth. that means that we don't need to move the rupture",
"# as it fits inside seismogenic layer.",
"vshift",
"=",
"0",
"# if vshift < 0 than we need to move the rupture up by that value.",
"# now we need to find the position of rupture's geometrical center.",
"# in any case the hypocenter point must lie on the surface, however",
"# the rupture center might be off (below or above) along the dip.",
"rupture_center",
"=",
"hypocenter",
"if",
"vshift",
"!=",
"0",
":",
"# we need to move the rupture center to make the rupture fit",
"# inside the seismogenic layer.",
"hshift",
"=",
"abs",
"(",
"vshift",
"/",
"math",
".",
"tan",
"(",
"rdip",
")",
")",
"rupture_center",
"=",
"rupture_center",
".",
"point_at",
"(",
"horizontal_distance",
"=",
"hshift",
",",
"vertical_increment",
"=",
"vshift",
",",
"azimuth",
"=",
"(",
"azimuth_up",
"if",
"vshift",
"<",
"0",
"else",
"azimuth_down",
")",
")",
"# from the rupture center we can now compute the coordinates of the",
"# four coorners by moving along the diagonals of the plane. This seems",
"# to be better then moving along the perimeter, because in this case",
"# errors are accumulated that induce distorsions in the shape with",
"# consequent raise of exceptions when creating PlanarSurface objects",
"# theta is the angle between the diagonal of the surface projection",
"# and the line passing through the rupture center and parallel to the",
"# top and bottom edges. Theta is zero for vertical ruptures (because",
"# rup_proj_width is zero)",
"theta",
"=",
"math",
".",
"degrees",
"(",
"math",
".",
"atan",
"(",
"(",
"rup_proj_width",
"/",
"2.",
")",
"/",
"(",
"rup_length",
"/",
"2.",
")",
")",
")",
"hor_dist",
"=",
"math",
".",
"sqrt",
"(",
"(",
"rup_length",
"/",
"2.",
")",
"**",
"2",
"+",
"(",
"rup_proj_width",
"/",
"2.",
")",
"**",
"2",
")",
"left_top",
"=",
"rupture_center",
".",
"point_at",
"(",
"horizontal_distance",
"=",
"hor_dist",
",",
"vertical_increment",
"=",
"-",
"rup_proj_height",
"/",
"2",
",",
"azimuth",
"=",
"(",
"nodal_plane",
".",
"strike",
"+",
"180",
"+",
"theta",
")",
"%",
"360",
")",
"right_top",
"=",
"rupture_center",
".",
"point_at",
"(",
"horizontal_distance",
"=",
"hor_dist",
",",
"vertical_increment",
"=",
"-",
"rup_proj_height",
"/",
"2",
",",
"azimuth",
"=",
"(",
"nodal_plane",
".",
"strike",
"-",
"theta",
")",
"%",
"360",
")",
"left_bottom",
"=",
"rupture_center",
".",
"point_at",
"(",
"horizontal_distance",
"=",
"hor_dist",
",",
"vertical_increment",
"=",
"rup_proj_height",
"/",
"2",
",",
"azimuth",
"=",
"(",
"nodal_plane",
".",
"strike",
"+",
"180",
"-",
"theta",
")",
"%",
"360",
")",
"right_bottom",
"=",
"rupture_center",
".",
"point_at",
"(",
"horizontal_distance",
"=",
"hor_dist",
",",
"vertical_increment",
"=",
"rup_proj_height",
"/",
"2",
",",
"azimuth",
"=",
"(",
"nodal_plane",
".",
"strike",
"+",
"theta",
")",
"%",
"360",
")",
"return",
"PlanarSurface",
"(",
"nodal_plane",
".",
"strike",
",",
"nodal_plane",
".",
"dip",
",",
"left_top",
",",
"right_top",
",",
"right_bottom",
",",
"left_bottom",
")"
] | Create and return rupture surface object with given properties.
:param mag:
Magnitude value, used to calculate rupture dimensions,
see :meth:`_get_rupture_dimensions`.
:param nodal_plane:
Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane`
describing the rupture orientation.
:param hypocenter:
Point representing rupture's hypocenter.
:returns:
Instance of
:class:`~openquake.hazardlib.geo.surface.planar.PlanarSurface`. | [
"Create",
"and",
"return",
"rupture",
"surface",
"object",
"with",
"given",
"properties",
"."
] | 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 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:
Magnitude
:param npd:
Nodal plane distribution as instance of :class:
openquake.hazardlib.pmf.PMF
:param hdd:
Hypocentral depth distribution as instance of :class:
openquake.hazardlib.pmf.PMF
:param float upper_seismogenic_depth:
Upper seismogenic depth (km)
:param float lower_seismogenic_depth:
Lower seismogenic depth (km)
:param msr:
Magnitude scaling relation
:param float aspect:
Aspect ratio
:param str trt:
Tectonic region type
:returns:
List of ruptures
"""
ruptures = []
n_vals = len(locations)
depths = hdd.sample_pairs(n_vals)
nodal_planes = npd.sample_pairs(n_vals)
for i, (x, y) in enumerate(locations):
hypocentre = Point(x, y, depths[i][1])
surface = get_rupture_surface(mag, nodal_planes[i][1],
hypocentre, msr, aspect,
upper_seismogenic_depth,
lower_seismogenic_depth)
rupture_probability = (occurrence[i] * nodal_planes[i][0] *
depths[i][0])
ruptures.append(ParametricProbabilisticRupture(
mag, nodal_planes[i][1].rake, trt, hypocentre, surface,
rupture_probability, tom))
return ruptures | 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)
depths = hdd.sample_pairs(n_vals)
nodal_planes = npd.sample_pairs(n_vals)
for i, (x, y) in enumerate(locations):
hypocentre = Point(x, y, depths[i][1])
surface = get_rupture_surface(mag, nodal_planes[i][1],
hypocentre, msr, aspect,
upper_seismogenic_depth,
lower_seismogenic_depth)
rupture_probability = (occurrence[i] * nodal_planes[i][0] *
depths[i][0])
ruptures.append(ParametricProbabilisticRupture(
mag, nodal_planes[i][1].rake, trt, hypocentre, surface,
rupture_probability, tom))
return 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",
")",
":",
"ruptures",
"=",
"[",
"]",
"n_vals",
"=",
"len",
"(",
"locations",
")",
"depths",
"=",
"hdd",
".",
"sample_pairs",
"(",
"n_vals",
")",
"nodal_planes",
"=",
"npd",
".",
"sample_pairs",
"(",
"n_vals",
")",
"for",
"i",
",",
"(",
"x",
",",
"y",
")",
"in",
"enumerate",
"(",
"locations",
")",
":",
"hypocentre",
"=",
"Point",
"(",
"x",
",",
"y",
",",
"depths",
"[",
"i",
"]",
"[",
"1",
"]",
")",
"surface",
"=",
"get_rupture_surface",
"(",
"mag",
",",
"nodal_planes",
"[",
"i",
"]",
"[",
"1",
"]",
",",
"hypocentre",
",",
"msr",
",",
"aspect",
",",
"upper_seismogenic_depth",
",",
"lower_seismogenic_depth",
")",
"rupture_probability",
"=",
"(",
"occurrence",
"[",
"i",
"]",
"*",
"nodal_planes",
"[",
"i",
"]",
"[",
"0",
"]",
"*",
"depths",
"[",
"i",
"]",
"[",
"0",
"]",
")",
"ruptures",
".",
"append",
"(",
"ParametricProbabilisticRupture",
"(",
"mag",
",",
"nodal_planes",
"[",
"i",
"]",
"[",
"1",
"]",
".",
"rake",
",",
"trt",
",",
"hypocentre",
",",
"surface",
",",
"rupture_probability",
",",
"tom",
")",
")",
"return",
"ruptures"
] | :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:
Magnitude
:param npd:
Nodal plane distribution as instance of :class:
openquake.hazardlib.pmf.PMF
:param hdd:
Hypocentral depth distribution as instance of :class:
openquake.hazardlib.pmf.PMF
:param float upper_seismogenic_depth:
Upper seismogenic depth (km)
:param float lower_seismogenic_depth:
Lower seismogenic depth (km)
:param msr:
Magnitude scaling relation
:param float aspect:
Aspect ratio
:param str trt:
Tectonic region type
:returns:
List of ruptures | [
":",
"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",
":",
"Magnitude",
":",
"param",
"npd",
":",
"Nodal",
"plane",
"distribution",
"as",
"instance",
"of",
":",
"class",
":",
"openquake",
".",
"hazardlib",
".",
"pmf",
".",
"PMF",
":",
"param",
"hdd",
":",
"Hypocentral",
"depth",
"distribution",
"as",
"instance",
"of",
":",
"class",
":",
"openquake",
".",
"hazardlib",
".",
"pmf",
".",
"PMF",
":",
"param",
"float",
"upper_seismogenic_depth",
":",
"Upper",
"seismogenic",
"depth",
"(",
"km",
")",
":",
"param",
"float",
"lower_seismogenic_depth",
":",
"Lower",
"seismogenic",
"depth",
"(",
"km",
")",
":",
"param",
"msr",
":",
"Magnitude",
"scaling",
"relation",
":",
"param",
"float",
"aspect",
":",
"Aspect",
"ratio",
":",
"param",
"str",
"trt",
":",
"Tectonic",
"region",
"type",
":",
"returns",
":",
"List",
"of",
"ruptures"
] | 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_centroids(ridx)
mindistance = min_geodetic_distance(
(centroids[:, 0], centroids[:, 1]), self.sitecol.xyz)
idist = self.integration_distance(DEFAULT_TRT, mag)
indices, = (mindistance <= idist).nonzero()
return indices | 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()
return indices | [
"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",
"(",
")",
"return",
"indices"
] | :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",
"with",
"the",
"IDs",
"of",
"the",
"sites",
"close",
"to",
"the",
"ruptures"
] | 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)
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
new.stop = len(hdf5[new.idx_set["mag"]])
return new | 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
new.stop = len(hdf5[new.idx_set["mag"]])
return new | [
"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",
"new",
".",
"stop",
"=",
"len",
"(",
"hdf5",
"[",
"new",
".",
"idx_set",
"[",
"\"mag\"",
"]",
"]",
")",
"return",
"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",
"new",
"UCERFSource",
"associated",
"to",
"the",
"branch_id"
] | 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\"",
"]",
"[",
"iloc",
"]"
] | 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))
centroids.append(hdf5[trace + "/Centroids"].value)
return numpy.concatenate(centroids) | 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(centroids) | [
"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",
"(",
"centroids",
")"
] | :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 + "/RupturePlanes"][:].astype("float64")
yield trace, plane | 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",
"(",
"self",
".",
"idx_set",
"[",
"\"sec\"",
"]",
",",
"str",
"(",
"idx",
")",
")",
"plane",
"=",
"hdf5",
"[",
"trace",
"+",
"\"/RupturePlanes\"",
"]",
"[",
":",
"]",
".",
"astype",
"(",
"\"float64\"",
")",
"yield",
"trace",
",",
"plane"
] | :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.integration_distance(DEFAULT_TRT)
with h5py.File(self.source_file, 'r') as hdf5:
bg_locations = hdf5["Grid/Locations"].value
distances = min_geodetic_distance(
src_filter.sitecol.xyz,
(bg_locations[:, 0], bg_locations[:, 1]))
# Add buffer equal to half of length of median area from Mmax
mmax_areas = self.msr.get_median_area(
hdf5["/".join(["Grid", branch_key, "MMax"])].value, 0.0)
# for instance hdf5['Grid/FM0_0_MEANFS_MEANMSR/MMax']
mmax_lengths = numpy.sqrt(mmax_areas / self.aspect)
ok = distances <= (0.5 * mmax_lengths + idist)
# get list of indices from array of booleans
return numpy.where(ok)[0].tolist() | python | def get_background_sids(self, src_filter):
branch_key = self.idx_set["grid_key"]
idist = src_filter.integration_distance(DEFAULT_TRT)
with h5py.File(self.source_file, 'r') as hdf5:
bg_locations = hdf5["Grid/Locations"].value
distances = min_geodetic_distance(
src_filter.sitecol.xyz,
(bg_locations[:, 0], bg_locations[:, 1]))
mmax_areas = self.msr.get_median_area(
hdf5["/".join(["Grid", branch_key, "MMax"])].value, 0.0)
mmax_lengths = numpy.sqrt(mmax_areas / self.aspect)
ok = distances <= (0.5 * mmax_lengths + idist)
return numpy.where(ok)[0].tolist() | [
"def",
"get_background_sids",
"(",
"self",
",",
"src_filter",
")",
":",
"branch_key",
"=",
"self",
".",
"idx_set",
"[",
"\"grid_key\"",
"]",
"idist",
"=",
"src_filter",
".",
"integration_distance",
"(",
"DEFAULT_TRT",
")",
"with",
"h5py",
".",
"File",
"(",
"self",
".",
"source_file",
",",
"'r'",
")",
"as",
"hdf5",
":",
"bg_locations",
"=",
"hdf5",
"[",
"\"Grid/Locations\"",
"]",
".",
"value",
"distances",
"=",
"min_geodetic_distance",
"(",
"src_filter",
".",
"sitecol",
".",
"xyz",
",",
"(",
"bg_locations",
"[",
":",
",",
"0",
"]",
",",
"bg_locations",
"[",
":",
",",
"1",
"]",
")",
")",
"# Add buffer equal to half of length of median area from Mmax",
"mmax_areas",
"=",
"self",
".",
"msr",
".",
"get_median_area",
"(",
"hdf5",
"[",
"\"/\"",
".",
"join",
"(",
"[",
"\"Grid\"",
",",
"branch_key",
",",
"\"MMax\"",
"]",
")",
"]",
".",
"value",
",",
"0.0",
")",
"# for instance hdf5['Grid/FM0_0_MEANFS_MEANMSR/MMax']",
"mmax_lengths",
"=",
"numpy",
".",
"sqrt",
"(",
"mmax_areas",
"/",
"self",
".",
"aspect",
")",
"ok",
"=",
"distances",
"<=",
"(",
"0.5",
"*",
"mmax_lengths",
"+",
"idist",
")",
"# get list of indices from array of booleans",
"return",
"numpy",
".",
"where",
"(",
"ok",
")",
"[",
"0",
"]",
".",
"tolist",
"(",
")"
] | We can apply the filtering of the background sites as a pre-processing
step - this is done here rather than in the sampling of the ruptures
themselves | [
"We",
"can",
"apply",
"the",
"filtering",
"of",
"the",
"background",
"sites",
"as",
"a",
"pre",
"-",
"processing",
"step",
"-",
"this",
"is",
"done",
"here",
"rather",
"than",
"in",
"the",
"sampling",
"of",
"the",
"ruptures",
"themselves"
] | 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)
mag = self.orig.mags[iloc]
surface_set = []
indices = src_filter.get_indices(self, ridx, mag)
if len(indices) == 0:
return None
for trace, plane in self.gen_trace_planes(ridx):
# build simple fault surface
for jloc in range(0, plane.shape[2]):
top_left = Point(
plane[0, 0, jloc], plane[0, 1, jloc], plane[0, 2, jloc])
top_right = Point(
plane[1, 0, jloc], plane[1, 1, jloc], plane[1, 2, jloc])
bottom_right = Point(
plane[2, 0, jloc], plane[2, 1, jloc], plane[2, 2, jloc])
bottom_left = Point(
plane[3, 0, jloc], plane[3, 1, jloc], plane[3, 2, jloc])
try:
surface_set.append(
ImperfectPlanarSurface.from_corner_points(
top_left, top_right, bottom_right, bottom_left))
except ValueError as err:
raise ValueError(err, trace, top_left, top_right,
bottom_right, bottom_left)
rupture = ParametricProbabilisticRupture(
mag, self.orig.rake[iloc], trt,
surface_set[len(surface_set) // 2].get_middle_point(),
MultiSurface(surface_set), self.orig.rate[iloc], self.tom)
return rupture | 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, plane in self.gen_trace_planes(ridx):
for jloc in range(0, plane.shape[2]):
top_left = Point(
plane[0, 0, jloc], plane[0, 1, jloc], plane[0, 2, jloc])
top_right = Point(
plane[1, 0, jloc], plane[1, 1, jloc], plane[1, 2, jloc])
bottom_right = Point(
plane[2, 0, jloc], plane[2, 1, jloc], plane[2, 2, jloc])
bottom_left = Point(
plane[3, 0, jloc], plane[3, 1, jloc], plane[3, 2, jloc])
try:
surface_set.append(
ImperfectPlanarSurface.from_corner_points(
top_left, top_right, bottom_right, bottom_left))
except ValueError as err:
raise ValueError(err, trace, top_left, top_right,
bottom_right, bottom_left)
rupture = ParametricProbabilisticRupture(
mag, self.orig.rake[iloc], trt,
surface_set[len(surface_set) // 2].get_middle_point(),
MultiSurface(surface_set), self.orig.rate[iloc], self.tom)
return rupture | [
"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",
",",
"plane",
"in",
"self",
".",
"gen_trace_planes",
"(",
"ridx",
")",
":",
"# build simple fault surface",
"for",
"jloc",
"in",
"range",
"(",
"0",
",",
"plane",
".",
"shape",
"[",
"2",
"]",
")",
":",
"top_left",
"=",
"Point",
"(",
"plane",
"[",
"0",
",",
"0",
",",
"jloc",
"]",
",",
"plane",
"[",
"0",
",",
"1",
",",
"jloc",
"]",
",",
"plane",
"[",
"0",
",",
"2",
",",
"jloc",
"]",
")",
"top_right",
"=",
"Point",
"(",
"plane",
"[",
"1",
",",
"0",
",",
"jloc",
"]",
",",
"plane",
"[",
"1",
",",
"1",
",",
"jloc",
"]",
",",
"plane",
"[",
"1",
",",
"2",
",",
"jloc",
"]",
")",
"bottom_right",
"=",
"Point",
"(",
"plane",
"[",
"2",
",",
"0",
",",
"jloc",
"]",
",",
"plane",
"[",
"2",
",",
"1",
",",
"jloc",
"]",
",",
"plane",
"[",
"2",
",",
"2",
",",
"jloc",
"]",
")",
"bottom_left",
"=",
"Point",
"(",
"plane",
"[",
"3",
",",
"0",
",",
"jloc",
"]",
",",
"plane",
"[",
"3",
",",
"1",
",",
"jloc",
"]",
",",
"plane",
"[",
"3",
",",
"2",
",",
"jloc",
"]",
")",
"try",
":",
"surface_set",
".",
"append",
"(",
"ImperfectPlanarSurface",
".",
"from_corner_points",
"(",
"top_left",
",",
"top_right",
",",
"bottom_right",
",",
"bottom_left",
")",
")",
"except",
"ValueError",
"as",
"err",
":",
"raise",
"ValueError",
"(",
"err",
",",
"trace",
",",
"top_left",
",",
"top_right",
",",
"bottom_right",
",",
"bottom_left",
")",
"rupture",
"=",
"ParametricProbabilisticRupture",
"(",
"mag",
",",
"self",
".",
"orig",
".",
"rake",
"[",
"iloc",
"]",
",",
"trt",
",",
"surface_set",
"[",
"len",
"(",
"surface_set",
")",
"//",
"2",
"]",
".",
"get_middle_point",
"(",
")",
",",
"MultiSurface",
"(",
"surface_set",
")",
",",
"self",
".",
"orig",
".",
"rate",
"[",
"iloc",
"]",
",",
"self",
".",
"tom",
")",
"return",
"rupture"
] | :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_ucerf_rupture(ridx, self.src_filter)
if rup:
yield rup | 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",
".",
"rate",
"[",
"ridx",
"]",
":",
"# ruptures may have have zero rate",
"rup",
"=",
"self",
".",
"get_ucerf_rupture",
"(",
"ridx",
",",
"self",
".",
"src_filter",
")",
"if",
"rup",
":",
"yield",
"rup"
] | Yield ruptures for the current set of indices | [
"Yield",
"ruptures",
"for",
"the",
"current",
"set",
"of",
"indices"
] | 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
"""
background_sids = self.get_background_sids(src_filter)
if sample_factor is not None: # hack for use in the mosaic
background_sids = random_filter(
background_sids, sample_factor, seed=42)
with h5py.File(self.source_file, "r") as hdf5:
grid_loc = "/".join(["Grid", self.idx_set["grid_key"]])
# for instance Grid/FM0_0_MEANFS_MEANMSR_MeanRates
mags = hdf5[grid_loc + "/Magnitude"].value
mmax = hdf5[grid_loc + "/MMax"][background_sids]
rates = hdf5[grid_loc + "/RateArray"][background_sids, :]
locations = hdf5["Grid/Locations"][background_sids, :]
sources = []
for i, bg_idx in enumerate(background_sids):
src_id = "_".join([self.idx_set["grid_key"], str(bg_idx)])
src_name = "|".join([self.idx_set["total_key"], str(bg_idx)])
mag_idx = (self.min_mag <= mags) & (mags < mmax[i])
src_mags = mags[mag_idx]
src_mfd = EvenlyDiscretizedMFD(
src_mags[0],
src_mags[1] - src_mags[0],
rates[i, mag_idx].tolist())
ps = PointSource(
src_id, src_name, self.tectonic_region_type, src_mfd,
self.mesh_spacing, self.msr, self.aspect, self.tom,
self.usd, self.lsd,
Point(locations[i, 0], locations[i, 1]),
self.npd, self.hdd)
ps.id = self.id
ps.src_group_id = self.src_group_id
ps.num_ruptures = ps.count_ruptures()
sources.append(ps)
return sources | python | def get_background_sources(self, src_filter, sample_factor=None):
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, "r") as hdf5:
grid_loc = "/".join(["Grid", self.idx_set["grid_key"]])
mags = hdf5[grid_loc + "/Magnitude"].value
mmax = hdf5[grid_loc + "/MMax"][background_sids]
rates = hdf5[grid_loc + "/RateArray"][background_sids, :]
locations = hdf5["Grid/Locations"][background_sids, :]
sources = []
for i, bg_idx in enumerate(background_sids):
src_id = "_".join([self.idx_set["grid_key"], str(bg_idx)])
src_name = "|".join([self.idx_set["total_key"], str(bg_idx)])
mag_idx = (self.min_mag <= mags) & (mags < mmax[i])
src_mags = mags[mag_idx]
src_mfd = EvenlyDiscretizedMFD(
src_mags[0],
src_mags[1] - src_mags[0],
rates[i, mag_idx].tolist())
ps = PointSource(
src_id, src_name, self.tectonic_region_type, src_mfd,
self.mesh_spacing, self.msr, self.aspect, self.tom,
self.usd, self.lsd,
Point(locations[i, 0], locations[i, 1]),
self.npd, self.hdd)
ps.id = self.id
ps.src_group_id = self.src_group_id
ps.num_ruptures = ps.count_ruptures()
sources.append(ps)
return sources | [
"def",
"get_background_sources",
"(",
"self",
",",
"src_filter",
",",
"sample_factor",
"=",
"None",
")",
":",
"background_sids",
"=",
"self",
".",
"get_background_sids",
"(",
"src_filter",
")",
"if",
"sample_factor",
"is",
"not",
"None",
":",
"# hack for use in the mosaic",
"background_sids",
"=",
"random_filter",
"(",
"background_sids",
",",
"sample_factor",
",",
"seed",
"=",
"42",
")",
"with",
"h5py",
".",
"File",
"(",
"self",
".",
"source_file",
",",
"\"r\"",
")",
"as",
"hdf5",
":",
"grid_loc",
"=",
"\"/\"",
".",
"join",
"(",
"[",
"\"Grid\"",
",",
"self",
".",
"idx_set",
"[",
"\"grid_key\"",
"]",
"]",
")",
"# for instance Grid/FM0_0_MEANFS_MEANMSR_MeanRates",
"mags",
"=",
"hdf5",
"[",
"grid_loc",
"+",
"\"/Magnitude\"",
"]",
".",
"value",
"mmax",
"=",
"hdf5",
"[",
"grid_loc",
"+",
"\"/MMax\"",
"]",
"[",
"background_sids",
"]",
"rates",
"=",
"hdf5",
"[",
"grid_loc",
"+",
"\"/RateArray\"",
"]",
"[",
"background_sids",
",",
":",
"]",
"locations",
"=",
"hdf5",
"[",
"\"Grid/Locations\"",
"]",
"[",
"background_sids",
",",
":",
"]",
"sources",
"=",
"[",
"]",
"for",
"i",
",",
"bg_idx",
"in",
"enumerate",
"(",
"background_sids",
")",
":",
"src_id",
"=",
"\"_\"",
".",
"join",
"(",
"[",
"self",
".",
"idx_set",
"[",
"\"grid_key\"",
"]",
",",
"str",
"(",
"bg_idx",
")",
"]",
")",
"src_name",
"=",
"\"|\"",
".",
"join",
"(",
"[",
"self",
".",
"idx_set",
"[",
"\"total_key\"",
"]",
",",
"str",
"(",
"bg_idx",
")",
"]",
")",
"mag_idx",
"=",
"(",
"self",
".",
"min_mag",
"<=",
"mags",
")",
"&",
"(",
"mags",
"<",
"mmax",
"[",
"i",
"]",
")",
"src_mags",
"=",
"mags",
"[",
"mag_idx",
"]",
"src_mfd",
"=",
"EvenlyDiscretizedMFD",
"(",
"src_mags",
"[",
"0",
"]",
",",
"src_mags",
"[",
"1",
"]",
"-",
"src_mags",
"[",
"0",
"]",
",",
"rates",
"[",
"i",
",",
"mag_idx",
"]",
".",
"tolist",
"(",
")",
")",
"ps",
"=",
"PointSource",
"(",
"src_id",
",",
"src_name",
",",
"self",
".",
"tectonic_region_type",
",",
"src_mfd",
",",
"self",
".",
"mesh_spacing",
",",
"self",
".",
"msr",
",",
"self",
".",
"aspect",
",",
"self",
".",
"tom",
",",
"self",
".",
"usd",
",",
"self",
".",
"lsd",
",",
"Point",
"(",
"locations",
"[",
"i",
",",
"0",
"]",
",",
"locations",
"[",
"i",
",",
"1",
"]",
")",
",",
"self",
".",
"npd",
",",
"self",
".",
"hdd",
")",
"ps",
".",
"id",
"=",
"self",
".",
"id",
"ps",
".",
"src_group_id",
"=",
"self",
".",
"src_group_id",
"ps",
".",
"num_ruptures",
"=",
"ps",
".",
"count_ruptures",
"(",
")",
"sources",
".",
"append",
"(",
"ps",
")",
"return",
"sources"
] | Turn the background model of a given branch into a set of point sources
:param src_filter:
SourceFilter instance
:param sample_factor:
Used to reduce the sources if OQ_SAMPLE_SOURCES is set | [
"Turn",
"the",
"background",
"model",
"of",
"a",
"given",
"branch",
"into",
"a",
"set",
"of",
"point",
"sources"
] | 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, i)
amfd = mfd.ArbitraryMFD([rup.mag], [rup.mag_occ_rate])
rcs = RuptureCollectionSource(
source_id, src.name, src.tectonic_region_type, amfd, block)
yield rcs | 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.mag_occ_rate])
rcs = RuptureCollectionSource(
source_id, src.name, src.tectonic_region_type, amfd, block)
yield rcs | [
"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",
".",
"mag_occ_rate",
"]",
")",
"rcs",
"=",
"RuptureCollectionSource",
"(",
"source_id",
",",
"src",
".",
"name",
",",
"src",
".",
"tectonic_region_type",
",",
"amfd",
",",
"block",
")",
"yield",
"rcs"
] | 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:
print('%s has no attributes' % key)
for name, value in attrs.items():
print(name, value)
finally:
ds.close() | 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.items():
print(name, value)
finally:
ds.close() | [
"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",
".",
"items",
"(",
")",
":",
"print",
"(",
"name",
",",
"value",
")",
"finally",
":",
"ds",
".",
"close",
"(",
")"
] | 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('The IMTs and levels are different between '
'calculation %d and %d' % (calc_ref, calc))
sitecol_ref = dstore_ref['sitecol']
sitecol = dstore['sitecol']
site_id_ref = {(lon, lat): sid for sid, lon, lat in zip(
sitecol_ref.sids, sitecol_ref.lons, sitecol_ref.lats)}
site_id = {(lon, lat): sid for sid, lon, lat in zip(
sitecol.sids, sitecol.lons, sitecol.lats)}
common = set(site_id_ref) & set(site_id)
if not common:
raise RuntimeError('There are no common sites between calculation '
'%d and %d' % (calc_ref, calc))
pmap_ref = PmapGetter(dstore_ref, sids=[site_id_ref[lonlat]
for lonlat in common]).get_mean()
pmap = PmapGetter(dstore, sids=[site_id[lonlat]
for lonlat in common]).get_mean()
for lonlat in common:
mean, std = pmap[site_id[lonlat]].array.T # shape (2, N)
mean_ref, std_ref = pmap_ref[site_id_ref[lonlat]].array.T
err = numpy.sqrt(std**2 + std_ref**2)
for imt in imtls:
sl = imtls(imt)
ok = (numpy.abs(mean[sl] - mean_ref[sl]) < nsigma * err[sl]).all()
if not ok:
md = (numpy.abs(mean[sl] - mean_ref[sl])).max()
plt.title('point=%s, imt=%s, maxdiff=%.2e' % (lonlat, imt, md))
plt.loglog(imtls[imt], mean_ref[sl] + std_ref[sl],
label=str(calc_ref), color='black')
plt.loglog(imtls[imt], mean_ref[sl] - std_ref[sl],
color='black')
plt.loglog(imtls[imt], mean[sl] + std[sl], label=str(calc),
color='red')
plt.loglog(imtls[imt], mean[sl] - std[sl], color='red')
plt.legend()
plt.show() | 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 '
'calculation %d and %d' % (calc_ref, calc))
sitecol_ref = dstore_ref['sitecol']
sitecol = dstore['sitecol']
site_id_ref = {(lon, lat): sid for sid, lon, lat in zip(
sitecol_ref.sids, sitecol_ref.lons, sitecol_ref.lats)}
site_id = {(lon, lat): sid for sid, lon, lat in zip(
sitecol.sids, sitecol.lons, sitecol.lats)}
common = set(site_id_ref) & set(site_id)
if not common:
raise RuntimeError('There are no common sites between calculation '
'%d and %d' % (calc_ref, calc))
pmap_ref = PmapGetter(dstore_ref, sids=[site_id_ref[lonlat]
for lonlat in common]).get_mean()
pmap = PmapGetter(dstore, sids=[site_id[lonlat]
for lonlat in common]).get_mean()
for lonlat in common:
mean, std = pmap[site_id[lonlat]].array.T
mean_ref, std_ref = pmap_ref[site_id_ref[lonlat]].array.T
err = numpy.sqrt(std**2 + std_ref**2)
for imt in imtls:
sl = imtls(imt)
ok = (numpy.abs(mean[sl] - mean_ref[sl]) < nsigma * err[sl]).all()
if not ok:
md = (numpy.abs(mean[sl] - mean_ref[sl])).max()
plt.title('point=%s, imt=%s, maxdiff=%.2e' % (lonlat, imt, md))
plt.loglog(imtls[imt], mean_ref[sl] + std_ref[sl],
label=str(calc_ref), color='black')
plt.loglog(imtls[imt], mean_ref[sl] - std_ref[sl],
color='black')
plt.loglog(imtls[imt], mean[sl] + std[sl], label=str(calc),
color='red')
plt.loglog(imtls[imt], mean[sl] - std[sl], color='red')
plt.legend()
plt.show() | [
"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 '",
"'calculation %d and %d'",
"%",
"(",
"calc_ref",
",",
"calc",
")",
")",
"sitecol_ref",
"=",
"dstore_ref",
"[",
"'sitecol'",
"]",
"sitecol",
"=",
"dstore",
"[",
"'sitecol'",
"]",
"site_id_ref",
"=",
"{",
"(",
"lon",
",",
"lat",
")",
":",
"sid",
"for",
"sid",
",",
"lon",
",",
"lat",
"in",
"zip",
"(",
"sitecol_ref",
".",
"sids",
",",
"sitecol_ref",
".",
"lons",
",",
"sitecol_ref",
".",
"lats",
")",
"}",
"site_id",
"=",
"{",
"(",
"lon",
",",
"lat",
")",
":",
"sid",
"for",
"sid",
",",
"lon",
",",
"lat",
"in",
"zip",
"(",
"sitecol",
".",
"sids",
",",
"sitecol",
".",
"lons",
",",
"sitecol",
".",
"lats",
")",
"}",
"common",
"=",
"set",
"(",
"site_id_ref",
")",
"&",
"set",
"(",
"site_id",
")",
"if",
"not",
"common",
":",
"raise",
"RuntimeError",
"(",
"'There are no common sites between calculation '",
"'%d and %d'",
"%",
"(",
"calc_ref",
",",
"calc",
")",
")",
"pmap_ref",
"=",
"PmapGetter",
"(",
"dstore_ref",
",",
"sids",
"=",
"[",
"site_id_ref",
"[",
"lonlat",
"]",
"for",
"lonlat",
"in",
"common",
"]",
")",
".",
"get_mean",
"(",
")",
"pmap",
"=",
"PmapGetter",
"(",
"dstore",
",",
"sids",
"=",
"[",
"site_id",
"[",
"lonlat",
"]",
"for",
"lonlat",
"in",
"common",
"]",
")",
".",
"get_mean",
"(",
")",
"for",
"lonlat",
"in",
"common",
":",
"mean",
",",
"std",
"=",
"pmap",
"[",
"site_id",
"[",
"lonlat",
"]",
"]",
".",
"array",
".",
"T",
"# shape (2, N)",
"mean_ref",
",",
"std_ref",
"=",
"pmap_ref",
"[",
"site_id_ref",
"[",
"lonlat",
"]",
"]",
".",
"array",
".",
"T",
"err",
"=",
"numpy",
".",
"sqrt",
"(",
"std",
"**",
"2",
"+",
"std_ref",
"**",
"2",
")",
"for",
"imt",
"in",
"imtls",
":",
"sl",
"=",
"imtls",
"(",
"imt",
")",
"ok",
"=",
"(",
"numpy",
".",
"abs",
"(",
"mean",
"[",
"sl",
"]",
"-",
"mean_ref",
"[",
"sl",
"]",
")",
"<",
"nsigma",
"*",
"err",
"[",
"sl",
"]",
")",
".",
"all",
"(",
")",
"if",
"not",
"ok",
":",
"md",
"=",
"(",
"numpy",
".",
"abs",
"(",
"mean",
"[",
"sl",
"]",
"-",
"mean_ref",
"[",
"sl",
"]",
")",
")",
".",
"max",
"(",
")",
"plt",
".",
"title",
"(",
"'point=%s, imt=%s, maxdiff=%.2e'",
"%",
"(",
"lonlat",
",",
"imt",
",",
"md",
")",
")",
"plt",
".",
"loglog",
"(",
"imtls",
"[",
"imt",
"]",
",",
"mean_ref",
"[",
"sl",
"]",
"+",
"std_ref",
"[",
"sl",
"]",
",",
"label",
"=",
"str",
"(",
"calc_ref",
")",
",",
"color",
"=",
"'black'",
")",
"plt",
".",
"loglog",
"(",
"imtls",
"[",
"imt",
"]",
",",
"mean_ref",
"[",
"sl",
"]",
"-",
"std_ref",
"[",
"sl",
"]",
",",
"color",
"=",
"'black'",
")",
"plt",
".",
"loglog",
"(",
"imtls",
"[",
"imt",
"]",
",",
"mean",
"[",
"sl",
"]",
"+",
"std",
"[",
"sl",
"]",
",",
"label",
"=",
"str",
"(",
"calc",
")",
",",
"color",
"=",
"'red'",
")",
"plt",
".",
"loglog",
"(",
"imtls",
"[",
"imt",
"]",
",",
"mean",
"[",
"sl",
"]",
"-",
"std",
"[",
"sl",
"]",
",",
"color",
"=",
"'red'",
")",
"plt",
".",
"legend",
"(",
")",
"plt",
".",
"show",
"(",
")"
] | 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_z1pt0 = self._get_centered_z1pt0(sites)
# we consider random variables being zero since we want
# to find the exact mean value.
eta = epsilon = 0.
ln_y = (
# first line of eq. 12
ln_y_ref + eta
# second line
+ C['phi1'] * np.log(sites.vs30 / 1130).clip(-np.inf, 0)
# third line
+ C['phi2'] * (exp1 - exp2)
* np.log((np.exp(ln_y_ref) * np.exp(eta) + C['phi4']) / C['phi4'])
# fourth line
+ C['phi5']
* (1.0 - np.exp(-1. * centered_z1pt0 / C['phi6']))
# fifth line
+ epsilon
)
return ln_y | 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(-np.inf, 0)
+ C['phi2'] * (exp1 - exp2)
* np.log((np.exp(ln_y_ref) * np.exp(eta) + C['phi4']) / C['phi4'])
+ C['phi5']
* (1.0 - np.exp(-1. * centered_z1pt0 / C['phi6']))
+ epsilon
)
return ln_y | [
"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",
".",
"_get_centered_z1pt0",
"(",
"sites",
")",
"# we consider random variables being zero since we want",
"# to find the exact mean value.",
"eta",
"=",
"epsilon",
"=",
"0.",
"ln_y",
"=",
"(",
"# first line of eq. 12",
"ln_y_ref",
"+",
"eta",
"# second line",
"+",
"C",
"[",
"'phi1'",
"]",
"*",
"np",
".",
"log",
"(",
"sites",
".",
"vs30",
"/",
"1130",
")",
".",
"clip",
"(",
"-",
"np",
".",
"inf",
",",
"0",
")",
"# third line",
"+",
"C",
"[",
"'phi2'",
"]",
"*",
"(",
"exp1",
"-",
"exp2",
")",
"*",
"np",
".",
"log",
"(",
"(",
"np",
".",
"exp",
"(",
"ln_y_ref",
")",
"*",
"np",
".",
"exp",
"(",
"eta",
")",
"+",
"C",
"[",
"'phi4'",
"]",
")",
"/",
"C",
"[",
"'phi4'",
"]",
")",
"# fourth line",
"+",
"C",
"[",
"'phi5'",
"]",
"*",
"(",
"1.0",
"-",
"np",
".",
"exp",
"(",
"-",
"1.",
"*",
"centered_z1pt0",
"/",
"C",
"[",
"'phi6'",
"]",
")",
")",
"# fifth line",
"+",
"epsilon",
")",
"return",
"ln_y"
] | 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.
# hanging wall flag
Fhw = np.zeros_like(dists.rx)
idx = np.nonzero(dists.rx >= 0.)
Fhw[idx] = 1.
# a part in eq. 11
mag_test1 = np.cosh(2. * max(rup.mag - 4.5, 0))
# centered DPP
centered_dpp = self._get_centered_cdpp(dists)
# centered_ztor
centered_ztor = self._get_centered_ztor(rup, Frv)
#
dist_taper = np.fmax(1 - (np.fmax(dists.rrup - 40,
np.zeros_like(dists)) / 30.),
np.zeros_like(dists))
dist_taper = dist_taper.astype(np.float64)
ln_y_ref = (
# first part of eq. 11
C['c1']
+ (C['c1a'] + C['c1c'] / mag_test1) * Frv
+ (C['c1b'] + C['c1d'] / mag_test1) * Fnm
+ (C['c7'] + C['c7b'] / mag_test1) * centered_ztor
+ (C['c11'] + C['c11b'] / mag_test1) *
np.cos(math.radians(rup.dip)) ** 2
# second part
+ C['c2'] * (rup.mag - 6)
+ ((C['c2'] - C['c3']) / C['cn'])
* np.log(1 + np.exp(C['cn'] * (C['cm'] - rup.mag)))
# third part
+ C['c4']
* np.log(dists.rrup + C['c5']
* np.cosh(C['c6'] * max(rup.mag - C['chm'], 0)))
+ (C['c4a'] - C['c4'])
* np.log(np.sqrt(dists.rrup ** 2 + C['crb'] ** 2))
# forth part
+ (C['cg1'] + C['cg2'] / (np.cosh(max(rup.mag - C['cg3'], 0))))
* dists.rrup
# fifth part
+ C['c8'] * dist_taper
* min(max(rup.mag - 5.5, 0) / 0.8, 1.0)
* np.exp(-1 * C['c8a'] * (rup.mag - C['c8b']) ** 2) * centered_dpp
# sixth part
+ C['c9'] * Fhw * np.cos(math.radians(rup.dip)) *
(C['c9a'] + (1 - C['c9a']) * np.tanh(dists.rx / C['c9b']))
* (1 - np.sqrt(dists.rjb ** 2 + rup.ztor ** 2)
/ (dists.rrup + 1.0))
)
return ln_y_ref | 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. * max(rup.mag - 4.5, 0))
centered_dpp = self._get_centered_cdpp(dists)
centered_ztor = self._get_centered_ztor(rup, Frv)
dist_taper = np.fmax(1 - (np.fmax(dists.rrup - 40,
np.zeros_like(dists)) / 30.),
np.zeros_like(dists))
dist_taper = dist_taper.astype(np.float64)
ln_y_ref = (
C['c1']
+ (C['c1a'] + C['c1c'] / mag_test1) * Frv
+ (C['c1b'] + C['c1d'] / mag_test1) * Fnm
+ (C['c7'] + C['c7b'] / mag_test1) * centered_ztor
+ (C['c11'] + C['c11b'] / mag_test1) *
np.cos(math.radians(rup.dip)) ** 2
+ C['c2'] * (rup.mag - 6)
+ ((C['c2'] - C['c3']) / C['cn'])
* np.log(1 + np.exp(C['cn'] * (C['cm'] - rup.mag)))
+ C['c4']
* np.log(dists.rrup + C['c5']
* np.cosh(C['c6'] * max(rup.mag - C['chm'], 0)))
+ (C['c4a'] - C['c4'])
* np.log(np.sqrt(dists.rrup ** 2 + C['crb'] ** 2))
+ (C['cg1'] + C['cg2'] / (np.cosh(max(rup.mag - C['cg3'], 0))))
* dists.rrup
+ C['c8'] * dist_taper
* min(max(rup.mag - 5.5, 0) / 0.8, 1.0)
* np.exp(-1 * C['c8a'] * (rup.mag - C['c8b']) ** 2) * centered_dpp
+ C['c9'] * Fhw * np.cos(math.radians(rup.dip)) *
(C['c9a'] + (1 - C['c9a']) * np.tanh(dists.rx / C['c9b']))
* (1 - np.sqrt(dists.rjb ** 2 + rup.ztor ** 2)
/ (dists.rrup + 1.0))
)
return ln_y_ref | [
"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",
"<=",
"rup",
".",
"rake",
"<=",
"-",
"60",
"else",
"0.",
"# hanging wall flag",
"Fhw",
"=",
"np",
".",
"zeros_like",
"(",
"dists",
".",
"rx",
")",
"idx",
"=",
"np",
".",
"nonzero",
"(",
"dists",
".",
"rx",
">=",
"0.",
")",
"Fhw",
"[",
"idx",
"]",
"=",
"1.",
"# a part in eq. 11",
"mag_test1",
"=",
"np",
".",
"cosh",
"(",
"2.",
"*",
"max",
"(",
"rup",
".",
"mag",
"-",
"4.5",
",",
"0",
")",
")",
"# centered DPP",
"centered_dpp",
"=",
"self",
".",
"_get_centered_cdpp",
"(",
"dists",
")",
"# centered_ztor",
"centered_ztor",
"=",
"self",
".",
"_get_centered_ztor",
"(",
"rup",
",",
"Frv",
")",
"#",
"dist_taper",
"=",
"np",
".",
"fmax",
"(",
"1",
"-",
"(",
"np",
".",
"fmax",
"(",
"dists",
".",
"rrup",
"-",
"40",
",",
"np",
".",
"zeros_like",
"(",
"dists",
")",
")",
"/",
"30.",
")",
",",
"np",
".",
"zeros_like",
"(",
"dists",
")",
")",
"dist_taper",
"=",
"dist_taper",
".",
"astype",
"(",
"np",
".",
"float64",
")",
"ln_y_ref",
"=",
"(",
"# first part of eq. 11",
"C",
"[",
"'c1'",
"]",
"+",
"(",
"C",
"[",
"'c1a'",
"]",
"+",
"C",
"[",
"'c1c'",
"]",
"/",
"mag_test1",
")",
"*",
"Frv",
"+",
"(",
"C",
"[",
"'c1b'",
"]",
"+",
"C",
"[",
"'c1d'",
"]",
"/",
"mag_test1",
")",
"*",
"Fnm",
"+",
"(",
"C",
"[",
"'c7'",
"]",
"+",
"C",
"[",
"'c7b'",
"]",
"/",
"mag_test1",
")",
"*",
"centered_ztor",
"+",
"(",
"C",
"[",
"'c11'",
"]",
"+",
"C",
"[",
"'c11b'",
"]",
"/",
"mag_test1",
")",
"*",
"np",
".",
"cos",
"(",
"math",
".",
"radians",
"(",
"rup",
".",
"dip",
")",
")",
"**",
"2",
"# second part",
"+",
"C",
"[",
"'c2'",
"]",
"*",
"(",
"rup",
".",
"mag",
"-",
"6",
")",
"+",
"(",
"(",
"C",
"[",
"'c2'",
"]",
"-",
"C",
"[",
"'c3'",
"]",
")",
"/",
"C",
"[",
"'cn'",
"]",
")",
"*",
"np",
".",
"log",
"(",
"1",
"+",
"np",
".",
"exp",
"(",
"C",
"[",
"'cn'",
"]",
"*",
"(",
"C",
"[",
"'cm'",
"]",
"-",
"rup",
".",
"mag",
")",
")",
")",
"# third part",
"+",
"C",
"[",
"'c4'",
"]",
"*",
"np",
".",
"log",
"(",
"dists",
".",
"rrup",
"+",
"C",
"[",
"'c5'",
"]",
"*",
"np",
".",
"cosh",
"(",
"C",
"[",
"'c6'",
"]",
"*",
"max",
"(",
"rup",
".",
"mag",
"-",
"C",
"[",
"'chm'",
"]",
",",
"0",
")",
")",
")",
"+",
"(",
"C",
"[",
"'c4a'",
"]",
"-",
"C",
"[",
"'c4'",
"]",
")",
"*",
"np",
".",
"log",
"(",
"np",
".",
"sqrt",
"(",
"dists",
".",
"rrup",
"**",
"2",
"+",
"C",
"[",
"'crb'",
"]",
"**",
"2",
")",
")",
"# forth part",
"+",
"(",
"C",
"[",
"'cg1'",
"]",
"+",
"C",
"[",
"'cg2'",
"]",
"/",
"(",
"np",
".",
"cosh",
"(",
"max",
"(",
"rup",
".",
"mag",
"-",
"C",
"[",
"'cg3'",
"]",
",",
"0",
")",
")",
")",
")",
"*",
"dists",
".",
"rrup",
"# fifth part",
"+",
"C",
"[",
"'c8'",
"]",
"*",
"dist_taper",
"*",
"min",
"(",
"max",
"(",
"rup",
".",
"mag",
"-",
"5.5",
",",
"0",
")",
"/",
"0.8",
",",
"1.0",
")",
"*",
"np",
".",
"exp",
"(",
"-",
"1",
"*",
"C",
"[",
"'c8a'",
"]",
"*",
"(",
"rup",
".",
"mag",
"-",
"C",
"[",
"'c8b'",
"]",
")",
"**",
"2",
")",
"*",
"centered_dpp",
"# sixth part",
"+",
"C",
"[",
"'c9'",
"]",
"*",
"Fhw",
"*",
"np",
".",
"cos",
"(",
"math",
".",
"radians",
"(",
"rup",
".",
"dip",
")",
")",
"*",
"(",
"C",
"[",
"'c9a'",
"]",
"+",
"(",
"1",
"-",
"C",
"[",
"'c9a'",
"]",
")",
"*",
"np",
".",
"tanh",
"(",
"dists",
".",
"rx",
"/",
"C",
"[",
"'c9b'",
"]",
")",
")",
"*",
"(",
"1",
"-",
"np",
".",
"sqrt",
"(",
"dists",
".",
"rjb",
"**",
"2",
"+",
"rup",
".",
"ztor",
"**",
"2",
")",
"/",
"(",
"dists",
".",
"rrup",
"+",
"1.0",
")",
")",
")",
"return",
"ln_y_ref"
] | 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.)
/ (1360 ** 4. + 570.94 ** 4.))
centered_z1pt0 = sites.z1pt0 - np.exp(mean_z1pt0)
return centered_z1pt0 | 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",
"**",
"4.",
")",
"/",
"(",
"1360",
"**",
"4.",
"+",
"570.94",
"**",
"4.",
")",
")",
"centered_z1pt0",
"=",
"sites",
".",
"z1pt0",
"-",
"np",
".",
"exp",
"(",
"mean_z1pt0",
")",
"return",
"centered_z1pt0"
] | 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
else:
mean_ztor = max(2.673 - 1.136 * max(rup.mag - 4.970, 0.0), 0.) ** 2
centered_ztor = rup.ztor - mean_ztor
return centered_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 = rup.ztor - mean_ztor
return 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.",
")",
"**",
"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",
"=",
"rup",
".",
"ztor",
"-",
"mean_ztor",
"return",
"centered_ztor"
] | 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
if stddev_type == const.StdDev.TOTAL:
# eq. 13
ret.append(0.65 * np.ones_like(sites.vs30))
return ret | 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 * np.ones_like(sites.vs30))
return ret | [
"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",
":",
"# eq. 13",
"ret",
".",
"append",
"(",
"0.65",
"*",
"np",
".",
"ones_like",
"(",
"sites",
".",
"vs30",
")",
")",
"return",
"ret"
] | 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], steps=3)
array([0. , 0.33333333, 0.66666667, 1. ])
>>> fine_graining([0, 0.5, 0.7, 1], steps=2)
array([0. , 0.25, 0.5 , 0.6 , 0.7 , 0.85, 1. ])
N points become S * (N - 1) + 1 points with S > 0
"""
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]]]) | 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",
")",
"[",
":",
"-",
"1",
"]",
"for",
"x",
",",
"y",
"in",
"pairwise",
"(",
"points",
")",
"]",
")",
"return",
"numpy",
".",
"concatenate",
"(",
"[",
"ls",
",",
"[",
"points",
"[",
"-",
"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.66666667, 1. ])
>>> fine_graining([0, 0.5, 0.7, 1], steps=2)
array([0. , 0.25, 0.5 , 0.6 , 0.7 , 0.85, 1. ])
N points become S * (N - 1) + 1 points with S > 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 with a
complex logic depending on the noDamageLimit and the parameter
steps per interval.
:param ff: a fragility function object
:param continuous_fragility_discretization: .ini file parameter
:param steps_per_interval: .ini file parameter
:returns: generated imls
"""
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, steps_per_interval)
else:
gen_imls = imls
else: # continuous
gen_imls = numpy.linspace(ff.minIML, ff.maxIML,
continuous_fragility_discretization)
return gen_imls | 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, steps_per_interval)
else:
gen_imls = imls
else:
gen_imls = numpy.linspace(ff.minIML, ff.maxIML,
continuous_fragility_discretization)
return gen_imls | [
"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",
",",
"steps_per_interval",
")",
"else",
":",
"gen_imls",
"=",
"imls",
"else",
":",
"# continuous",
"gen_imls",
"=",
"numpy",
".",
"linspace",
"(",
"ff",
".",
"minIML",
",",
"ff",
".",
"maxIML",
",",
"continuous_fragility_discretization",
")",
"return",
"gen_imls"
] | 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.
:param ff: a fragility function object
:param continuous_fragility_discretization: .ini file parameter
:param steps_per_interval: .ini file parameter
:returns: generated imls | [
"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",
"."
] | 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.seed(seed)
asset_count = len(matrix)
samples = len(matrix[0])
if not correlation: # avoid building the covariance matrix
return numpy.random.normal(size=(samples, asset_count)).transpose()
means_vector = numpy.zeros(asset_count)
covariance_matrix = (
numpy.ones((asset_count, asset_count)) * correlation +
numpy.diag(numpy.ones(asset_count)) * (1 - correlation))
return numpy.random.multivariate_normal(
means_vector, covariance_matrix, samples).transpose() | 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)
covariance_matrix = (
numpy.ones((asset_count, asset_count)) * correlation +
numpy.diag(numpy.ones(asset_count)) * (1 - correlation))
return numpy.random.multivariate_normal(
means_vector, covariance_matrix, samples).transpose() | [
"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",
":",
"# avoid building the covariance matrix",
"return",
"numpy",
".",
"random",
".",
"normal",
"(",
"size",
"=",
"(",
"samples",
",",
"asset_count",
")",
")",
".",
"transpose",
"(",
")",
"means_vector",
"=",
"numpy",
".",
"zeros",
"(",
"asset_count",
")",
"covariance_matrix",
"=",
"(",
"numpy",
".",
"ones",
"(",
"(",
"asset_count",
",",
"asset_count",
")",
")",
"*",
"correlation",
"+",
"numpy",
".",
"diag",
"(",
"numpy",
".",
"ones",
"(",
"asset_count",
")",
")",
"*",
"(",
"1",
"-",
"correlation",
")",
")",
"return",
"numpy",
".",
"random",
".",
"multivariate_normal",
"(",
"means_vector",
",",
"covariance_matrix",
",",
"samples",
")",
".",
"transpose",
"(",
")"
] | 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",
"the",
"given",
"seed",
"and",
"correlation",
"."
] | 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): # D - 1 functions
lst.append(ff(gmvs))
lst.append(numpy.zeros_like(gmvs))
# convert a (D + 1, E) array into a (D, E) array
arr = pairwise_diff(numpy.array(lst))
arr[arr < 1E-7] = 0 # sanity check
return arr | 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",
".",
"append",
"(",
"ff",
"(",
"gmvs",
")",
")",
"lst",
".",
"append",
"(",
"numpy",
".",
"zeros_like",
"(",
"gmvs",
")",
")",
"# convert a (D + 1, E) array into a (D, E) array",
"arr",
"=",
"pairwise_diff",
"(",
"numpy",
".",
"array",
"(",
"lst",
")",
")",
"arr",
"[",
"arr",
"<",
"1E-7",
"]",
"=",
"0",
"# sanity check",
"return",
"arr"
] | :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",
")",
"damage",
"fractions"
] | 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 RuntimeWarning: divide by zero encountered in log
return - numpy.log(1. - poe) / t_haz | 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",
"-",
"numpy",
".",
"log",
"(",
"1.",
"-",
"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) | [
":",
"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:
hazard curve
:param investigation_time:
hazard investigation time
:param risk_investigation_time:
risk investigation time
:returns:
an array of M probabilities of occurrence where M is the numbers
of damage states.
"""
spi = fragility_functions.steps_per_interval
if spi and spi > 1: # interpolate
imls = numpy.array(fragility_functions.interp_imls)
min_val, max_val = hazard_imls[0], hazard_imls[-1]
assert min_val > 0, hazard_imls # sanity check
numpy.putmask(imls, imls < min_val, min_val)
numpy.putmask(imls, imls > max_val, max_val)
poes = interpolate.interp1d(hazard_imls, hazard_poes)(imls)
else:
imls = (hazard_imls if fragility_functions.format == 'continuous'
else fragility_functions.imls)
poes = numpy.array(hazard_poes)
afe = annual_frequency_of_exceedence(poes, investigation_time)
annual_frequency_of_occurrence = pairwise_diff(
pairwise_mean([afe[0]] + list(afe) + [afe[-1]]))
poes_per_damage_state = []
for ff in fragility_functions:
frequency_of_exceedence_per_damage_state = numpy.dot(
annual_frequency_of_occurrence, list(map(ff, imls)))
poe_per_damage_state = 1. - numpy.exp(
- frequency_of_exceedence_per_damage_state *
risk_investigation_time)
poes_per_damage_state.append(poe_per_damage_state)
poos = pairwise_diff([1] + poes_per_damage_state + [0])
return poos | 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_imls[-1]
assert min_val > 0, hazard_imls
numpy.putmask(imls, imls < min_val, min_val)
numpy.putmask(imls, imls > max_val, max_val)
poes = interpolate.interp1d(hazard_imls, hazard_poes)(imls)
else:
imls = (hazard_imls if fragility_functions.format == 'continuous'
else fragility_functions.imls)
poes = numpy.array(hazard_poes)
afe = annual_frequency_of_exceedence(poes, investigation_time)
annual_frequency_of_occurrence = pairwise_diff(
pairwise_mean([afe[0]] + list(afe) + [afe[-1]]))
poes_per_damage_state = []
for ff in fragility_functions:
frequency_of_exceedence_per_damage_state = numpy.dot(
annual_frequency_of_occurrence, list(map(ff, imls)))
poe_per_damage_state = 1. - numpy.exp(
- frequency_of_exceedence_per_damage_state *
risk_investigation_time)
poes_per_damage_state.append(poe_per_damage_state)
poos = pairwise_diff([1] + poes_per_damage_state + [0])
return poos | [
"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",
":",
"# interpolate",
"imls",
"=",
"numpy",
".",
"array",
"(",
"fragility_functions",
".",
"interp_imls",
")",
"min_val",
",",
"max_val",
"=",
"hazard_imls",
"[",
"0",
"]",
",",
"hazard_imls",
"[",
"-",
"1",
"]",
"assert",
"min_val",
">",
"0",
",",
"hazard_imls",
"# sanity check",
"numpy",
".",
"putmask",
"(",
"imls",
",",
"imls",
"<",
"min_val",
",",
"min_val",
")",
"numpy",
".",
"putmask",
"(",
"imls",
",",
"imls",
">",
"max_val",
",",
"max_val",
")",
"poes",
"=",
"interpolate",
".",
"interp1d",
"(",
"hazard_imls",
",",
"hazard_poes",
")",
"(",
"imls",
")",
"else",
":",
"imls",
"=",
"(",
"hazard_imls",
"if",
"fragility_functions",
".",
"format",
"==",
"'continuous'",
"else",
"fragility_functions",
".",
"imls",
")",
"poes",
"=",
"numpy",
".",
"array",
"(",
"hazard_poes",
")",
"afe",
"=",
"annual_frequency_of_exceedence",
"(",
"poes",
",",
"investigation_time",
")",
"annual_frequency_of_occurrence",
"=",
"pairwise_diff",
"(",
"pairwise_mean",
"(",
"[",
"afe",
"[",
"0",
"]",
"]",
"+",
"list",
"(",
"afe",
")",
"+",
"[",
"afe",
"[",
"-",
"1",
"]",
"]",
")",
")",
"poes_per_damage_state",
"=",
"[",
"]",
"for",
"ff",
"in",
"fragility_functions",
":",
"frequency_of_exceedence_per_damage_state",
"=",
"numpy",
".",
"dot",
"(",
"annual_frequency_of_occurrence",
",",
"list",
"(",
"map",
"(",
"ff",
",",
"imls",
")",
")",
")",
"poe_per_damage_state",
"=",
"1.",
"-",
"numpy",
".",
"exp",
"(",
"-",
"frequency_of_exceedence_per_damage_state",
"*",
"risk_investigation_time",
")",
"poes_per_damage_state",
".",
"append",
"(",
"poe_per_damage_state",
")",
"poos",
"=",
"pairwise_diff",
"(",
"[",
"1",
"]",
"+",
"poes_per_damage_state",
"+",
"[",
"0",
"]",
")",
"return",
"poos"
] | :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 time
:returns:
an array of M probabilities of occurrence where M is the numbers
of damage states. | [
":",
"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",
"time",
":",
"returns",
":",
"an",
"array",
"of",
"M",
"probabilities",
"of",
"occurrence",
"where",
"M",
"is",
"the",
"numbers",
"of",
"damage",
"states",
"."
] | 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:
the hazard intensity measure type and levels
:type hazard_poes:
the hazard curve
:param loss_ratios:
a tuple of C loss ratios
:returns:
an array of shape (2, C)
"""
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)
# saturate imls to hazard imls
min_val, max_val = hazard_imls[0], hazard_imls[-1]
numpy.putmask(imls, imls < min_val, min_val)
numpy.putmask(imls, imls > max_val, max_val)
# interpolate the hazard curve
poes = interpolate.interp1d(hazard_imls, hazard_poes)(imls)
# compute the poos
pos = pairwise_diff(poes)
lrem_po = numpy.empty(lrem.shape)
for idx, po in enumerate(pos):
lrem_po[:, idx] = lrem[:, idx] * po # column * po
return numpy.array([loss_ratios, lrem_po.sum(axis=1)]) | 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 = hazard_imls[0], hazard_imls[-1]
numpy.putmask(imls, imls < min_val, min_val)
numpy.putmask(imls, imls > max_val, max_val)
poes = interpolate.interp1d(hazard_imls, hazard_poes)(imls)
pos = pairwise_diff(poes)
lrem_po = numpy.empty(lrem.shape)
for idx, po in enumerate(pos):
lrem_po[:, idx] = lrem[:, idx] * po
return numpy.array([loss_ratios, lrem_po.sum(axis=1)]) | [
"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",
")",
"# saturate imls to hazard imls",
"min_val",
",",
"max_val",
"=",
"hazard_imls",
"[",
"0",
"]",
",",
"hazard_imls",
"[",
"-",
"1",
"]",
"numpy",
".",
"putmask",
"(",
"imls",
",",
"imls",
"<",
"min_val",
",",
"min_val",
")",
"numpy",
".",
"putmask",
"(",
"imls",
",",
"imls",
">",
"max_val",
",",
"max_val",
")",
"# interpolate the hazard curve",
"poes",
"=",
"interpolate",
".",
"interp1d",
"(",
"hazard_imls",
",",
"hazard_poes",
")",
"(",
"imls",
")",
"# compute the poos",
"pos",
"=",
"pairwise_diff",
"(",
"poes",
")",
"lrem_po",
"=",
"numpy",
".",
"empty",
"(",
"lrem",
".",
"shape",
")",
"for",
"idx",
",",
"po",
"in",
"enumerate",
"(",
"pos",
")",
":",
"lrem_po",
"[",
":",
",",
"idx",
"]",
"=",
"lrem",
"[",
":",
",",
"idx",
"]",
"*",
"po",
"# column * po",
"return",
"numpy",
".",
"array",
"(",
"[",
"loss_ratios",
",",
"lrem_po",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"]",
")"
] | :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 curve
:param loss_ratios:
a tuple of C loss ratios
:returns:
an array of shape (2, C) | [
":",
"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",
"curve",
":",
"param",
"loss_ratios",
":",
"a",
"tuple",
"of",
"C",
"loss",
"ratios",
":",
"returns",
":",
"an",
"array",
"of",
"shape",
"(",
"2",
"C",
")"
] | 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)` where both `poe1` and `poe2` are
in `poes`, then we perform a linear interpolation on the
corresponding losses
3. if the given probability is smaller than the
lowest PoE defined, it returns the max loss ratio .
4. if the given probability is greater than the highest PoE
defined it returns zero.
:param loss_ratios: an iterable over non-decreasing loss ratio
values (float)
:param poes: an iterable over non-increasing probability of
exceedance values (float)
:param float probability: the probability value used to
interpolate the loss curve
"""
assert len(loss_ratios) >= 3, loss_ratios
rpoes = poes[::-1]
if probability > poes[0]: # max poes
return 0.0
elif probability < poes[-1]: # min PoE
return loss_ratios[-1]
if probability in poes:
return max([loss
for i, loss in enumerate(loss_ratios)
if probability == poes[i]])
else:
interval_index = bisect.bisect_right(rpoes, probability)
if interval_index == len(poes): # poes are all nan
return float('nan')
elif interval_index == 1: # boundary case
x1, x2 = poes[-2:]
y1, y2 = loss_ratios[-2:]
else:
x1, x2 = poes[-interval_index-1:-interval_index + 1]
y1, y2 = loss_ratios[-interval_index-1:-interval_index + 1]
return (y2 - y1) / (x2 - x1) * (probability - x1) + y1 | 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
for i, loss in enumerate(loss_ratios)
if probability == poes[i]])
else:
interval_index = bisect.bisect_right(rpoes, probability)
if interval_index == len(poes):
return float('nan')
elif interval_index == 1:
x1, x2 = poes[-2:]
y1, y2 = loss_ratios[-2:]
else:
x1, x2 = poes[-interval_index-1:-interval_index + 1]
y1, y2 = loss_ratios[-interval_index-1:-interval_index + 1]
return (y2 - y1) / (x2 - x1) * (probability - x1) + y1 | [
"def",
"conditional_loss_ratio",
"(",
"loss_ratios",
",",
"poes",
",",
"probability",
")",
":",
"assert",
"len",
"(",
"loss_ratios",
")",
">=",
"3",
",",
"loss_ratios",
"rpoes",
"=",
"poes",
"[",
":",
":",
"-",
"1",
"]",
"if",
"probability",
">",
"poes",
"[",
"0",
"]",
":",
"# max poes",
"return",
"0.0",
"elif",
"probability",
"<",
"poes",
"[",
"-",
"1",
"]",
":",
"# min PoE",
"return",
"loss_ratios",
"[",
"-",
"1",
"]",
"if",
"probability",
"in",
"poes",
":",
"return",
"max",
"(",
"[",
"loss",
"for",
"i",
",",
"loss",
"in",
"enumerate",
"(",
"loss_ratios",
")",
"if",
"probability",
"==",
"poes",
"[",
"i",
"]",
"]",
")",
"else",
":",
"interval_index",
"=",
"bisect",
".",
"bisect_right",
"(",
"rpoes",
",",
"probability",
")",
"if",
"interval_index",
"==",
"len",
"(",
"poes",
")",
":",
"# poes are all nan",
"return",
"float",
"(",
"'nan'",
")",
"elif",
"interval_index",
"==",
"1",
":",
"# boundary case",
"x1",
",",
"x2",
"=",
"poes",
"[",
"-",
"2",
":",
"]",
"y1",
",",
"y2",
"=",
"loss_ratios",
"[",
"-",
"2",
":",
"]",
"else",
":",
"x1",
",",
"x2",
"=",
"poes",
"[",
"-",
"interval_index",
"-",
"1",
":",
"-",
"interval_index",
"+",
"1",
"]",
"y1",
",",
"y2",
"=",
"loss_ratios",
"[",
"-",
"interval_index",
"-",
"1",
":",
"-",
"interval_index",
"+",
"1",
"]",
"return",
"(",
"y2",
"-",
"y1",
")",
"/",
"(",
"x2",
"-",
"x1",
")",
"*",
"(",
"probability",
"-",
"x1",
")",
"+",
"y1"
] | 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 linear interpolation on the
corresponding losses
3. if the given probability is smaller than the
lowest PoE defined, it returns the max loss ratio .
4. if the given probability is greater than the highest PoE
defined it returns zero.
:param loss_ratios: an iterable over non-decreasing loss ratio
values (float)
:param poes: an iterable over non-increasing probability of
exceedance values (float)
:param float probability: the probability value used to
interpolate the loss curve | [
"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 point
of view of the insurance company. For instance:
>>> insured_losses(numpy.array([3, 20, 101]), 5, 100)
array([ 0, 15, 95])
- if the loss is 3 (< 5) the company does not pay anything
- if the loss is 20 the company pays 20 - 5 = 15
- if the loss is 101 the company pays 100 - 5 = 95
"""
return numpy.piecewise(
losses,
[losses < deductible, losses > insured_limit],
[0, insured_limit - deductible, lambda x: x - deductible]) | 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_limit",
"-",
"deductible",
",",
"lambda",
"x",
":",
"x",
"-",
"deductible",
"]",
")"
] | :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:
>>> insured_losses(numpy.array([3, 20, 101]), 5, 100)
array([ 0, 15, 95])
- if the loss is 3 (< 5) the company does not pay anything
- if the loss is 20 the company pays 20 - 5 = 15
- if the loss is 101 the company pays 100 - 5 = 95 | [
":",
"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"
] | 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 fraction form
>>> losses = numpy.array([3, 20, 101])
>>> poes = numpy.array([0.9, 0.5, 0.1])
>>> insured_loss_curve(numpy.array([losses, poes]), 5, 100)
array([[ 3. , 20. ],
[ 0.85294118, 0.5 ]])
"""
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, lambda x: x])]) | 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, lambda x: x])]) | [
"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",
",",
"lambda",
"x",
":",
"x",
"]",
")",
"]",
")"
] | 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 = numpy.array([0.9, 0.5, 0.1])
>>> insured_loss_curve(numpy.array([losses, poes]), 5, 100)
array([[ 3. , 20. ],
[ 0.85294118, 0.5 ]]) | [
"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 -- Expected annual loss for retrofitted asset
* r -- Interest rate
* t -- Life expectancy of the asset
* C -- Retrofitting cost
"""
return ((eal_original - eal_retrofitted) * asset_value *
(1 - numpy.exp(- interest_rate * asset_life_expectancy)) /
(interest_rate * retrofitting_cost)) | 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",
"*",
"(",
"1",
"-",
"numpy",
".",
"exp",
"(",
"-",
"interest_rate",
"*",
"asset_life_expectancy",
")",
")",
"/",
"(",
"interest_rate",
"*",
"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 -- Expected annual loss for retrofitted asset
* r -- Interest rate
* t -- Life expectancy of the asset
* C -- Retrofitting cost | [
"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.mean(fractions, axis=0), numpy.std(fractions, axis=0, ddof=1) | 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",
"(",
"fractions",
"[",
"0",
"]",
")",
"*",
"numpy",
".",
"nan",
"return",
"numpy",
".",
"mean",
"(",
"fractions",
",",
"axis",
"=",
"0",
")",
",",
"numpy",
".",
"std",
"(",
"fractions",
",",
"axis",
"=",
"0",
",",
"ddof",
"=",
"1",
")"
] | 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)
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:
loss_maps['poe-%s' % poe][idx] = conditional_loss_ratio(
curve['losses'], curve['poes'], poe)
return loss_maps | 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:
loss_maps['poe-%s' % poe][idx] = conditional_loss_ratio(
curve['losses'], curve['poes'], poe)
return loss_maps | [
"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",
":",
"loss_maps",
"[",
"'poe-%s'",
"%",
"poe",
"]",
"[",
"idx",
"]",
"=",
"conditional_loss_ratio",
"(",
"curve",
"[",
"'losses'",
"]",
",",
"curve",
"[",
"'poes'",
"]",
",",
"poe",
")",
"return",
"loss_maps"
] | :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",
"shape"
] | 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[name].shape, numpy.dtype(dtypes))
for name in dic:
res[name] = dic[name]
return res | 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[name] = dic[name]
return res | [
"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",
"[",
"name",
"]",
"=",
"dic",
"[",
"name",
"]",
"return",
"res"
] | 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 trapeizodal rule with the width given by the
loss bin width.
"""
losses, poes = (lc['loss'], lc['poe']) if lc.dtype.names else lc
return -pairwise_diff(losses) @ pairwise_mean(poes) | 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",
")",
"@",
"pairwise_mean",
"(",
"poes",
")"
] | 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 the
loss bin width. | [
"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_curves = [(losses, poes)
for losses, poes in curves if losses[-1] > 0]
if not non_zero_curves: # no damage. all zero curves
return curves[0][0], numpy.array([poes for _losses, poes in curves])
else: # standard case
max_losses = [losses[-1] for losses, _poes in non_zero_curves]
reference_curve = non_zero_curves[numpy.argmax(max_losses)]
loss_ratios = reference_curve[0]
curves_poes = [interpolate.interp1d(
losses, poes, bounds_error=False, fill_value=0)(loss_ratios)
for losses, poes in curves]
# fix degenerated case with flat curve
for cp in curves_poes:
if numpy.isnan(cp[0]):
cp[0] = 0
return loss_ratios, numpy.array(curves_poes) | 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 in non_zero_curves]
reference_curve = non_zero_curves[numpy.argmax(max_losses)]
loss_ratios = reference_curve[0]
curves_poes = [interpolate.interp1d(
losses, poes, bounds_error=False, fill_value=0)(loss_ratios)
for losses, poes in curves]
for cp in curves_poes:
if numpy.isnan(cp[0]):
cp[0] = 0
return loss_ratios, numpy.array(curves_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",
"]",
">",
"0",
"]",
"if",
"not",
"non_zero_curves",
":",
"# no damage. all zero curves",
"return",
"curves",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"numpy",
".",
"array",
"(",
"[",
"poes",
"for",
"_losses",
",",
"poes",
"in",
"curves",
"]",
")",
"else",
":",
"# standard case",
"max_losses",
"=",
"[",
"losses",
"[",
"-",
"1",
"]",
"for",
"losses",
",",
"_poes",
"in",
"non_zero_curves",
"]",
"reference_curve",
"=",
"non_zero_curves",
"[",
"numpy",
".",
"argmax",
"(",
"max_losses",
")",
"]",
"loss_ratios",
"=",
"reference_curve",
"[",
"0",
"]",
"curves_poes",
"=",
"[",
"interpolate",
".",
"interp1d",
"(",
"losses",
",",
"poes",
",",
"bounds_error",
"=",
"False",
",",
"fill_value",
"=",
"0",
")",
"(",
"loss_ratios",
")",
"for",
"losses",
",",
"poes",
"in",
"curves",
"]",
"# fix degenerated case with flat curve",
"for",
"cp",
"in",
"curves_poes",
":",
"if",
"numpy",
".",
"isnan",
"(",
"cp",
"[",
"0",
"]",
")",
":",
"cp",
"[",
"0",
"]",
"=",
"0",
"return",
"loss_ratios",
",",
"numpy",
".",
"array",
"(",
"curves_poes",
")"
] | 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 = 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:
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) + '_ins', lc_dt))
loss_curve_dt = numpy.dtype(lc_list) if lc_list else None
return loss_curve_dt | 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:
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) + '_ins', lc_dt))
loss_curve_dt = numpy.dtype(lc_list) if lc_list else None
return loss_curve_dt | [
"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",
":",
"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",
")",
"+",
"'_ins'",
",",
"lc_dt",
")",
")",
"loss_curve_dt",
"=",
"numpy",
".",
"dtype",
"(",
"lc_list",
")",
"if",
"lc_list",
"else",
"None",
"return",
"loss_curve_dt"
] | :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):
...
AssertionError: eff_time too small: 1
>>> return_periods(2, 2)
array([1, 2], dtype=uint32)
>>> return_periods(2, 10)
array([1, 2], dtype=uint32)
>>> return_periods(100, 2)
array([ 50, 100], dtype=uint32)
>>> return_periods(1000, 1000)
array([ 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000],
dtype=uint32)
"""
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]:
time = period * val
if time >= min_time:
if time > eff_time:
loop = False
break
periods.append(time)
period *= 10
return U32(periods) | 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]:
time = period * val
if time >= min_time:
if time > eff_time:
loop = False
break
periods.append(time)
period *= 10
return U32(periods) | [
"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",
"]",
":",
"time",
"=",
"period",
"*",
"val",
"if",
"time",
">=",
"min_time",
":",
"if",
"time",
">",
"eff_time",
":",
"loop",
"=",
"False",
"break",
"periods",
".",
"append",
"(",
"time",
")",
"period",
"*=",
"10",
"return",
"U32",
"(",
"periods",
")"
] | :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
>>> return_periods(2, 2)
array([1, 2], dtype=uint32)
>>> return_periods(2, 10)
array([1, 2], dtype=uint32)
>>> return_periods(100, 2)
array([ 50, 100], dtype=uint32)
>>> return_periods(1000, 1000)
array([ 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000],
dtype=uint32) | [
":",
"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_path
:returns: interpolated losses for the return periods, possibly with NaN
NB: the return periods must be ordered integers >= 1. The interpolated
losses are defined inside the interval min_time < time < eff_time
where min_time = eff_time /num_events. Outside the interval they
have NaN values. Here is an example:
>>> losses = [3, 2, 3.5, 4, 3, 23, 11, 2, 1, 4, 5, 7, 8, 9, 13]
>>> losses_by_period(losses, [1, 2, 5, 10, 20, 50, 100], 20)
array([ nan, nan, 0. , 3.5, 8. , 13. , 23. ])
If num_events is not passed, it is inferred from the number of losses;
if eff_time is not passed, it is inferred from the longest return period.
"""
if len(losses) == 0: # zero-curve
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 (%d) to compute the loss curve '
'from %d losses' % (num_events, len(losses)))
if eff_time is None:
eff_time = return_periods[-1]
losses = numpy.sort(losses)
num_zeros = num_events - len(losses)
if num_zeros:
losses = numpy.concatenate(
[numpy.zeros(num_zeros, losses.dtype), losses])
periods = eff_time / numpy.arange(num_events, 0., -1)
rperiods = [rp if periods[0] <= rp <= periods[-1] else numpy.nan
for rp in return_periods]
curve = numpy.interp(numpy.log(rperiods), numpy.log(periods), losses)
return curve | 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 (%d) to compute the loss curve '
'from %d losses' % (num_events, len(losses)))
if eff_time is None:
eff_time = return_periods[-1]
losses = numpy.sort(losses)
num_zeros = num_events - len(losses)
if num_zeros:
losses = numpy.concatenate(
[numpy.zeros(num_zeros, losses.dtype), losses])
periods = eff_time / numpy.arange(num_events, 0., -1)
rperiods = [rp if periods[0] <= rp <= periods[-1] else numpy.nan
for rp in return_periods]
curve = numpy.interp(numpy.log(rperiods), numpy.log(periods), losses)
return curve | [
"def",
"losses_by_period",
"(",
"losses",
",",
"return_periods",
",",
"num_events",
"=",
"None",
",",
"eff_time",
"=",
"None",
")",
":",
"if",
"len",
"(",
"losses",
")",
"==",
"0",
":",
"# zero-curve",
"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 (%d) to compute the loss curve '",
"'from %d losses'",
"%",
"(",
"num_events",
",",
"len",
"(",
"losses",
")",
")",
")",
"if",
"eff_time",
"is",
"None",
":",
"eff_time",
"=",
"return_periods",
"[",
"-",
"1",
"]",
"losses",
"=",
"numpy",
".",
"sort",
"(",
"losses",
")",
"num_zeros",
"=",
"num_events",
"-",
"len",
"(",
"losses",
")",
"if",
"num_zeros",
":",
"losses",
"=",
"numpy",
".",
"concatenate",
"(",
"[",
"numpy",
".",
"zeros",
"(",
"num_zeros",
",",
"losses",
".",
"dtype",
")",
",",
"losses",
"]",
")",
"periods",
"=",
"eff_time",
"/",
"numpy",
".",
"arange",
"(",
"num_events",
",",
"0.",
",",
"-",
"1",
")",
"rperiods",
"=",
"[",
"rp",
"if",
"periods",
"[",
"0",
"]",
"<=",
"rp",
"<=",
"periods",
"[",
"-",
"1",
"]",
"else",
"numpy",
".",
"nan",
"for",
"rp",
"in",
"return_periods",
"]",
"curve",
"=",
"numpy",
".",
"interp",
"(",
"numpy",
".",
"log",
"(",
"rperiods",
")",
",",
"numpy",
".",
"log",
"(",
"periods",
")",
",",
"losses",
")",
"return",
"curve"
] | :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: the return periods must be ordered integers >= 1. The interpolated
losses are defined inside the interval min_time < time < eff_time
where min_time = eff_time /num_events. Outside the interval they
have NaN values. Here is an example:
>>> losses = [3, 2, 3.5, 4, 3, 23, 11, 2, 1, 4, 5, 7, 8, 9, 13]
>>> losses_by_period(losses, [1, 2, 5, 10, 20, 50, 100], 20)
array([ nan, nan, 0. , 3.5, 8. , 13. , 23. ])
If num_events is not passed, it is inferred from the number of losses;
if eff_time is not passed, it is inferred from the longest return period. | [
":",
"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"
] | 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.imls[-1]], [self.imls[-1], lambda x: x])
idxs = gmvs_curve >= self.imls[0] # indices over the minimum
gmvs_curve = gmvs_curve[idxs]
return self._mlr_i1d(gmvs_curve), self._cov_for(gmvs_curve), idxs | 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",
"[",
"-",
"1",
"]",
",",
"lambda",
"x",
":",
"x",
"]",
")",
"idxs",
"=",
"gmvs_curve",
">=",
"self",
".",
"imls",
"[",
"0",
"]",
"# indices over the minimum",
"gmvs_curve",
"=",
"gmvs_curve",
"[",
"idxs",
"]",
"return",
"self",
".",
"_mlr_i1d",
"(",
"gmvs_curve",
")",
",",
"self",
".",
"_cov_for",
"(",
"gmvs_curve",
")",
",",
"idxs"
] | :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 idxs:
array of E booleans with E >= E'
:param epsilons:
array of E floats (or None)
:returns:
array of E' loss ratios
"""
if epsilons is None:
return means
self.set_distribution(epsilons)
res = self.distribution.sample(means, covs, means * covs, idxs)
return res | 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",
".",
"distribution",
".",
"sample",
"(",
"means",
",",
"covs",
",",
"means",
"*",
"covs",
",",
"idxs",
")",
"return",
"res"
] | 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:
array of E floats (or None)
:returns:
array of E' loss ratios | [
"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
for i, mlr in enumerate(self.mean_loss_ratios):
if previous_mlr == mlr:
continue
else:
mlrs.append(mlr)
imls.append(self.imls[i])
covs.append(self.covs[i])
previous_mlr = mlr
return self.__class__(
self.id, self.imt, imls, mlrs, covs, self.distribution_name) | 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])
covs.append(self.covs[i])
previous_mlr = mlr
return self.__class__(
self.id, self.imt, imls, mlrs, covs, self.distribution_name) | [
"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",
"]",
")",
"covs",
".",
"append",
"(",
"self",
".",
"covs",
"[",
"i",
"]",
")",
"previous_mlr",
"=",
"mlr",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"id",
",",
"self",
".",
"imt",
",",
"imls",
",",
"mlrs",
",",
"covs",
",",
"self",
".",
"distribution_name",
")"
] | :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 example, if we have [0.5, 0.7]::
steps = 1 produces [0.0, 0.5, 0.7, 1]
steps = 2 produces [0.0, 0.25, 0.5, 0.6, 0.7, 0.85, 1]
steps = 3 produces [0.0, 0.17, 0.33, 0.5, 0.57, 0.63,
0.7, 0.8, 0.9, 1]
"""
loss_ratios = self.mean_loss_ratios
if min(loss_ratios) > 0.0:
# prepend with a zero
loss_ratios = numpy.concatenate([[0.0], loss_ratios])
if max(loss_ratios) < 1.0:
# append a 1.0
loss_ratios = numpy.concatenate([loss_ratios, [1.0]])
return fine_graining(loss_ratios, steps) | 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, [1.0]])
return fine_graining(loss_ratios, steps) | [
"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",
"(",
"[",
"[",
"0.0",
"]",
",",
"loss_ratios",
"]",
")",
"if",
"max",
"(",
"loss_ratios",
")",
"<",
"1.0",
":",
"# append a 1.0",
"loss_ratios",
"=",
"numpy",
".",
"concatenate",
"(",
"[",
"loss_ratios",
",",
"[",
"1.0",
"]",
"]",
")",
"return",
"fine_graining",
"(",
"loss_ratios",
",",
"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 example, if we have [0.5, 0.7]::
steps = 1 produces [0.0, 0.5, 0.7, 1]
steps = 2 produces [0.0, 0.25, 0.5, 0.6, 0.7, 0.85, 1]
steps = 3 produces [0.0, 0.17, 0.33, 0.5, 0.57, 0.63,
0.7, 0.8, 0.9, 1] | [
"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], the clipped imls are
[0.005, 0.006, 0.0269].
"""
return self._covs_i1d(
numpy.piecewise(
imls,
[imls > self.imls[-1], imls < self.imls[0]],
[self.imls[-1], self.imls[0], lambda x: x])) | 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",
"[",
"0",
"]",
"]",
",",
"[",
"self",
".",
"imls",
"[",
"-",
"1",
"]",
",",
"self",
".",
"imls",
"[",
"0",
"]",
",",
"lambda",
"x",
":",
"x",
"]",
")",
")"
] | 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.0269]. | [
"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",
".",
"0269",
"]",
"."
] | 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.imls)))
for row, loss_ratio in enumerate(loss_ratios):
for col, (mean_loss_ratio, stddev) in enumerate(
zip(self.mean_loss_ratios, self.stddevs)):
lrem[row, col] = self.distribution.survival(
loss_ratio, mean_loss_ratio, stddev)
return lrem | 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)):
lrem[row, col] = self.distribution.survival(
loss_ratio, mean_loss_ratio, stddev)
return lrem | [
"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",
")",
",",
"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",
")",
")",
":",
"lrem",
"[",
"row",
",",
"col",
"]",
"=",
"self",
".",
"distribution",
".",
"survival",
"(",
"loss_ratio",
",",
"mean_loss_ratio",
",",
"stddev",
")",
"return",
"lrem"
] | 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:`openquake.risklib.vulnerability_function.\
VulnerabilityFunction`
"""
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.]) | 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",
"]",
")",
"/",
"2.",
")",
"]",
"+",
"[",
"numpy",
".",
"mean",
"(",
"pair",
")",
"for",
"pair",
"in",
"pairwise",
"(",
"self",
".",
"imls",
")",
"]",
"+",
"[",
"self",
".",
"imls",
"[",
"-",
"1",
"]",
"+",
"(",
"self",
".",
"imls",
"[",
"-",
"1",
"]",
"-",
"self",
".",
"imls",
"[",
"-",
"2",
"]",
")",
"/",
"2.",
"]",
")"
] | 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_function.\
VulnerabilityFunction` | [
"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]], [self.imls[-1], lambda x: x])
idxs = gmvs_curve >= self.imls[0] # indices over the minimum
gmvs_curve = gmvs_curve[idxs]
return self._probs_i1d(gmvs_curve), numpy.zeros_like(gmvs_curve), idxs | 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",
"[",
"-",
"1",
"]",
",",
"lambda",
"x",
":",
"x",
"]",
")",
"idxs",
"=",
"gmvs_curve",
">=",
"self",
".",
"imls",
"[",
"0",
"]",
"# indices over the minimum",
"gmvs_curve",
"=",
"gmvs_curve",
"[",
"idxs",
"]",
"return",
"self",
".",
"_probs_i1d",
"(",
"gmvs_curve",
")",
",",
"numpy",
".",
"zeros_like",
"(",
"gmvs_curve",
")",
",",
"idxs"
] | :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'
:param epsilons:
array of E floats
:returns:
array of E' probabilities
"""
self.set_distribution(epsilons)
return self.distribution.sample(self.loss_ratios, probs) | 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
:returns:
array of E' probabilities | [
"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 FragilityFunctionList instance
"""
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:
new.interp_imls = build_imls( # passed to classical_damage
new, discretization, steps_per_interval)
for i, ls in enumerate(limit_states):
data = self.array[i]
if self.format == 'discrete':
if add_zero:
new.append(FragilityFunctionDiscrete(
ls, [self.nodamage] + self.imls,
numpy.concatenate([[0.], data]),
self.nodamage))
else:
new.append(FragilityFunctionDiscrete(
ls, self.imls, data, self.nodamage))
else: # continuous
new.append(FragilityFunctionContinuous(
ls, data['mean'], data['stddev']))
return new | 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:
new.interp_imls = build_imls(
new, discretization, steps_per_interval)
for i, ls in enumerate(limit_states):
data = self.array[i]
if self.format == 'discrete':
if add_zero:
new.append(FragilityFunctionDiscrete(
ls, [self.nodamage] + self.imls,
numpy.concatenate([[0.], data]),
self.nodamage))
else:
new.append(FragilityFunctionDiscrete(
ls, self.imls, data, self.nodamage))
else:
new.append(FragilityFunctionContinuous(
ls, data['mean'], data['stddev']))
return new | [
"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",
":",
"new",
".",
"interp_imls",
"=",
"build_imls",
"(",
"# passed to classical_damage",
"new",
",",
"discretization",
",",
"steps_per_interval",
")",
"for",
"i",
",",
"ls",
"in",
"enumerate",
"(",
"limit_states",
")",
":",
"data",
"=",
"self",
".",
"array",
"[",
"i",
"]",
"if",
"self",
".",
"format",
"==",
"'discrete'",
":",
"if",
"add_zero",
":",
"new",
".",
"append",
"(",
"FragilityFunctionDiscrete",
"(",
"ls",
",",
"[",
"self",
".",
"nodamage",
"]",
"+",
"self",
".",
"imls",
",",
"numpy",
".",
"concatenate",
"(",
"[",
"[",
"0.",
"]",
",",
"data",
"]",
")",
",",
"self",
".",
"nodamage",
")",
")",
"else",
":",
"new",
".",
"append",
"(",
"FragilityFunctionDiscrete",
"(",
"ls",
",",
"self",
".",
"imls",
",",
"data",
",",
"self",
".",
"nodamage",
")",
")",
"else",
":",
"# continuous",
"new",
".",
"append",
"(",
"FragilityFunctionContinuous",
"(",
"ls",
",",
"data",
"[",
"'mean'",
"]",
",",
"data",
"[",
"'stddev'",
"]",
")",
")",
"return",
"new"
] | :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",
":",
"a",
"populated",
"FragilityFunctionList",
"instance"
] | 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 steps_per_interval:
configuration parameter
"""
newfm = copy.copy(self)
for key, ffl in self.items():
newfm[key] = ffl.build(self.limitStates,
continuous_fragility_discretization,
steps_per_interval)
return newfm | 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_per_interval)
return newfm | [
"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_per_interval",
")",
"return",
"newfm"
] | 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_stats = None
return array, array_stats | 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",
"(",
"array",
",",
"statfuncs",
",",
"self",
".",
"weights",
")",
"else",
":",
"array_stats",
"=",
"None",
"return",
"array",
",",
"array_stats"
] | :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)
"""
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]
for l, lt in enumerate(self.loss_dt.names):
ls = losses[:, l].flatten() # flatten only in ucerf
# NB: do not use squeeze or the gmf_ebrisk tests will break
lbp = losses_by_period(
ls, self.return_periods, num_events, self.eff_time)
array[:, r, l] = lbp
return self.pair(array, stats) | 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]
for l, lt in enumerate(self.loss_dt.names):
ls = losses[:, l].flatten()
lbp = losses_by_period(
ls, self.return_periods, num_events, self.eff_time)
array[:, r, l] = lbp
return self.pair(array, stats) | [
"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",
"]",
"for",
"l",
",",
"lt",
"in",
"enumerate",
"(",
"self",
".",
"loss_dt",
".",
"names",
")",
":",
"ls",
"=",
"losses",
"[",
":",
",",
"l",
"]",
".",
"flatten",
"(",
")",
"# flatten only in ucerf",
"# NB: do not use squeeze or the gmf_ebrisk tests will break",
"lbp",
"=",
"losses_by_period",
"(",
"ls",
",",
"self",
".",
"return_periods",
",",
"num_events",
",",
"self",
".",
"eff_time",
")",
"array",
"[",
":",
",",
"r",
",",
"l",
"]",
"=",
"lbp",
"return",
"self",
".",
"pair",
"(",
"array",
",",
"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) | [
":",
"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",
")"
] | 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, R), F32)
for r, ls in enumerate(losses):
ne = self.num_events.get(r, 0)
if ne:
array[:, r] = losses_by_period(
ls, self.return_periods, ne, self.eff_time)
return self.pair(array, stats) | 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] = losses_by_period(
ls, self.return_periods, ne, self.eff_time)
return self.pair(array, stats) | [
"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",
"]",
"=",
"losses_by_period",
"(",
"ls",
",",
"self",
".",
"return_periods",
",",
"ne",
",",
"self",
".",
"eff_time",
")",
"return",
"self",
".",
"pair",
"(",
"array",
",",
"stats",
")"
] | :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 = losses.shape[:2] + (len(clp), len(losses.dtype)) # (A, R, C, LI)
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_):
for c, poe in enumerate(clp):
clratio = conditional_loss_ratio(ls, self.poes, poe)
array[a, r, c, lti] = clratio
return self.pair(array, stats) | 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_):
for c, poe in enumerate(clp):
clratio = conditional_loss_ratio(ls, self.poes, poe)
array[a, r, c, lti] = clratio
return self.pair(array, stats) | [
"def",
"build_maps",
"(",
"self",
",",
"losses",
",",
"clp",
",",
"stats",
"=",
"(",
")",
")",
":",
"shp",
"=",
"losses",
".",
"shape",
"[",
":",
"2",
"]",
"+",
"(",
"len",
"(",
"clp",
")",
",",
"len",
"(",
"losses",
".",
"dtype",
")",
")",
"# (A, R, C, LI)",
"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_",
")",
":",
"for",
"c",
",",
"poe",
"in",
"enumerate",
"(",
"clp",
")",
":",
"clratio",
"=",
"conditional_loss_ratio",
"(",
"ls",
",",
"self",
".",
"poes",
",",
"poe",
")",
"array",
"[",
"a",
",",
"r",
",",
"c",
",",
"lti",
"]",
"=",
"clratio",
"return",
"self",
".",
"pair",
"(",
"array",
",",
"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) | [
":",
"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",
")"
] | 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.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, poe)
return self.pair(array, stats) | 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, poe)
return self.pair(array, stats) | [
"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",
",",
"poe",
")",
"return",
"self",
".",
"pair",
"(",
"array",
",",
"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) | [
":",
"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",
")"
] | 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_id, rlzs))
dstore['csm_info/rlzs_by_grp'] = numpy.array(lst, rlzs_by_grp_dt) | 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",
"(",
")",
":",
"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",
")"
] | 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'",
")",
":",
"getter",
".",
"init",
"(",
")",
"return",
"getter",
".",
"compute_gmfs_curves",
"(",
"monitor",
")"
] | 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
"""
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_big.lons, sitecol_big.lats)}
site_id_small = {(lon, lat): sid for sid, lon, lat in zip(
sitecol_small.sids, sitecol_small.lons, sitecol_small.lats)}
common = set(site_id_big) & set(site_id_small)
if not common:
raise RuntimeError('There are no common sites between calculation '
'%d and %d' % (calc_big, calc_small))
sids_small = [site_id_small[lonlat] for lonlat in common]
pmap_big = PmapGetter(dstore_big).get_mean() # USA
pmap_small = PmapGetter(dstore_big, sids=sids_small).get_mean() # Cal
for lonlat in common:
pmap_big[site_id_big[lonlat]] |= pmap_small.get(
site_id_small[lonlat], 0)
out = 'combine_%d_%d.hdf5' % (calc_big, calc_small)
with hdf5.File(out, 'w') as h5:
h5['hcurves/mean'] = pmap_big
h5['oqparam'] = dstore_big['oqparam']
h5['sitecol'] = dstore_big['sitecol']
print('Generated %s' % out) | 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_big.lons, sitecol_big.lats)}
site_id_small = {(lon, lat): sid for sid, lon, lat in zip(
sitecol_small.sids, sitecol_small.lons, sitecol_small.lats)}
common = set(site_id_big) & set(site_id_small)
if not common:
raise RuntimeError('There are no common sites between calculation '
'%d and %d' % (calc_big, calc_small))
sids_small = [site_id_small[lonlat] for lonlat in common]
pmap_big = PmapGetter(dstore_big).get_mean()
pmap_small = PmapGetter(dstore_big, sids=sids_small).get_mean()
for lonlat in common:
pmap_big[site_id_big[lonlat]] |= pmap_small.get(
site_id_small[lonlat], 0)
out = 'combine_%d_%d.hdf5' % (calc_big, calc_small)
with hdf5.File(out, 'w') as h5:
h5['hcurves/mean'] = pmap_big
h5['oqparam'] = dstore_big['oqparam']
h5['sitecol'] = dstore_big['sitecol']
print('Generated %s' % out) | [
"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_big",
".",
"lons",
",",
"sitecol_big",
".",
"lats",
")",
"}",
"site_id_small",
"=",
"{",
"(",
"lon",
",",
"lat",
")",
":",
"sid",
"for",
"sid",
",",
"lon",
",",
"lat",
"in",
"zip",
"(",
"sitecol_small",
".",
"sids",
",",
"sitecol_small",
".",
"lons",
",",
"sitecol_small",
".",
"lats",
")",
"}",
"common",
"=",
"set",
"(",
"site_id_big",
")",
"&",
"set",
"(",
"site_id_small",
")",
"if",
"not",
"common",
":",
"raise",
"RuntimeError",
"(",
"'There are no common sites between calculation '",
"'%d and %d'",
"%",
"(",
"calc_big",
",",
"calc_small",
")",
")",
"sids_small",
"=",
"[",
"site_id_small",
"[",
"lonlat",
"]",
"for",
"lonlat",
"in",
"common",
"]",
"pmap_big",
"=",
"PmapGetter",
"(",
"dstore_big",
")",
".",
"get_mean",
"(",
")",
"# USA",
"pmap_small",
"=",
"PmapGetter",
"(",
"dstore_big",
",",
"sids",
"=",
"sids_small",
")",
".",
"get_mean",
"(",
")",
"# Cal",
"for",
"lonlat",
"in",
"common",
":",
"pmap_big",
"[",
"site_id_big",
"[",
"lonlat",
"]",
"]",
"|=",
"pmap_small",
".",
"get",
"(",
"site_id_small",
"[",
"lonlat",
"]",
",",
"0",
")",
"out",
"=",
"'combine_%d_%d.hdf5'",
"%",
"(",
"calc_big",
",",
"calc_small",
")",
"with",
"hdf5",
".",
"File",
"(",
"out",
",",
"'w'",
")",
"as",
"h5",
":",
"h5",
"[",
"'hcurves/mean'",
"]",
"=",
"pmap_big",
"h5",
"[",
"'oqparam'",
"]",
"=",
"dstore_big",
"[",
"'oqparam'",
"]",
"h5",
"[",
"'sitecol'",
"]",
"=",
"dstore_big",
"[",
"'sitecol'",
"]",
"print",
"(",
"'Generated %s'",
"%",
"out",
")"
] | 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",
"PoEs",
"of",
"calc_small",
".",
"For",
"instance",
":",
"calc_big",
"=",
"USA",
"calc_small",
"=",
"California"
] | 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 the fault source from
shallowest to deepest. Each edge can be represented as as either
i) instance of nhlib.geo.polygon.Polygon class
ii) numpy.ndarray [Longitude, Latitude, Depth]
:param float mesh_spacing:
Spacing of the fault mesh (km) {default = 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(edge, Line):
if not isinstance(edge, np.ndarray):
raise ValueError('Unrecognised or unsupported geometry '
'definition')
else:
self.fault_edges.append(Line([Point(row[0], row[1], row[2])
for row in edge]))
else:
self.fault_edges.append(edge)
# Updates the upper and lower sesmogenic depths to reflect geometry
self._get_minmax_edges(edge)
# Build fault surface
self.geometry = ComplexFaultSurface.from_fault_data(self.fault_edges,
mesh_spacing)
# Get a mean dip
self.dip = self.geometry.get_dip() | 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(edge, Line):
if not isinstance(edge, np.ndarray):
raise ValueError('Unrecognised or unsupported geometry '
'definition')
else:
self.fault_edges.append(Line([Point(row[0], row[1], row[2])
for row in edge]))
else:
self.fault_edges.append(edge)
self._get_minmax_edges(edge)
self.geometry = ComplexFaultSurface.from_fault_data(self.fault_edges,
mesh_spacing)
self.dip = self.geometry.get_dip() | [
"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",
"(",
"edge",
",",
"Line",
")",
":",
"if",
"not",
"isinstance",
"(",
"edge",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"ValueError",
"(",
"'Unrecognised or unsupported geometry '",
"'definition'",
")",
"else",
":",
"self",
".",
"fault_edges",
".",
"append",
"(",
"Line",
"(",
"[",
"Point",
"(",
"row",
"[",
"0",
"]",
",",
"row",
"[",
"1",
"]",
",",
"row",
"[",
"2",
"]",
")",
"for",
"row",
"in",
"edge",
"]",
")",
")",
"else",
":",
"self",
".",
"fault_edges",
".",
"append",
"(",
"edge",
")",
"# Updates the upper and lower sesmogenic depths to reflect geometry",
"self",
".",
"_get_minmax_edges",
"(",
"edge",
")",
"# Build fault surface",
"self",
".",
"geometry",
"=",
"ComplexFaultSurface",
".",
"from_fault_data",
"(",
"self",
".",
"fault_edges",
",",
"mesh_spacing",
")",
"# Get a mean dip",
"self",
".",
"dip",
"=",
"self",
".",
"geometry",
".",
"get_dip",
"(",
")"
] | 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 represented as as either
i) instance of nhlib.geo.polygon.Polygon class
ii) numpy.ndarray [Longitude, Latitude, Depth]
:param float mesh_spacing:
Spacing of the fault mesh (km) {default = 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"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/complex_fault_source.py#L115-L151 |
Subsets and Splits