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/calculators/views.py | ebr_data_transfer | def ebr_data_transfer(token, dstore):
"""
Display the data transferred in an event based risk calculation
"""
attrs = dstore['losses_by_event'].attrs
sent = humansize(attrs['sent'])
received = humansize(attrs['tot_received'])
return 'Event Based Risk: sent %s, received %s' % (sent, received) | python | def ebr_data_transfer(token, dstore):
attrs = dstore['losses_by_event'].attrs
sent = humansize(attrs['sent'])
received = humansize(attrs['tot_received'])
return 'Event Based Risk: sent %s, received %s' % (sent, received) | [
"def",
"ebr_data_transfer",
"(",
"token",
",",
"dstore",
")",
":",
"attrs",
"=",
"dstore",
"[",
"'losses_by_event'",
"]",
".",
"attrs",
"sent",
"=",
"humansize",
"(",
"attrs",
"[",
"'sent'",
"]",
")",
"received",
"=",
"humansize",
"(",
"attrs",
"[",
"'tot_received'",
"]",
")",
"return",
"'Event Based Risk: sent %s, received %s'",
"%",
"(",
"sent",
",",
"received",
")"
] | Display the data transferred in an event based risk calculation | [
"Display",
"the",
"data",
"transferred",
"in",
"an",
"event",
"based",
"risk",
"calculation"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L345-L352 |
gem/oq-engine | openquake/calculators/views.py | view_totlosses | def view_totlosses(token, dstore):
"""
This is a debugging view. You can use it to check that the total
losses, i.e. the losses obtained by summing the average losses on
all assets are indeed equal to the aggregate losses. This is a
sanity check for the correctness of the implementation.
"""
oq = dstore['oqparam']
tot_losses = dstore['losses_by_asset']['mean'].sum(axis=0)
return rst_table(tot_losses.view(oq.loss_dt()), fmt='%.6E') | python | def view_totlosses(token, dstore):
oq = dstore['oqparam']
tot_losses = dstore['losses_by_asset']['mean'].sum(axis=0)
return rst_table(tot_losses.view(oq.loss_dt()), fmt='%.6E') | [
"def",
"view_totlosses",
"(",
"token",
",",
"dstore",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"tot_losses",
"=",
"dstore",
"[",
"'losses_by_asset'",
"]",
"[",
"'mean'",
"]",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
"return",
"rst_table",
"(",
"tot_losses",
".",
"view",
"(",
"oq",
".",
"loss_dt",
"(",
")",
")",
",",
"fmt",
"=",
"'%.6E'",
")"
] | This is a debugging view. You can use it to check that the total
losses, i.e. the losses obtained by summing the average losses on
all assets are indeed equal to the aggregate losses. This is a
sanity check for the correctness of the implementation. | [
"This",
"is",
"a",
"debugging",
"view",
".",
"You",
"can",
"use",
"it",
"to",
"check",
"that",
"the",
"total",
"losses",
"i",
".",
"e",
".",
"the",
"losses",
"obtained",
"by",
"summing",
"the",
"average",
"losses",
"on",
"all",
"assets",
"are",
"indeed",
"equal",
"to",
"the",
"aggregate",
"losses",
".",
"This",
"is",
"a",
"sanity",
"check",
"for",
"the",
"correctness",
"of",
"the",
"implementation",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L357-L366 |
gem/oq-engine | openquake/calculators/views.py | view_portfolio_losses | def view_portfolio_losses(token, dstore):
"""
The losses for the full portfolio, for each realization and loss type,
extracted from the event loss table.
"""
oq = dstore['oqparam']
loss_dt = oq.loss_dt()
data = portfolio_loss(dstore).view(loss_dt)[:, 0]
rlzids = [str(r) for r in range(len(data))]
array = util.compose_arrays(numpy.array(rlzids), data, 'rlz')
# this is very sensitive to rounding errors, so I am using a low precision
return rst_table(array, fmt='%.5E') | python | def view_portfolio_losses(token, dstore):
oq = dstore['oqparam']
loss_dt = oq.loss_dt()
data = portfolio_loss(dstore).view(loss_dt)[:, 0]
rlzids = [str(r) for r in range(len(data))]
array = util.compose_arrays(numpy.array(rlzids), data, 'rlz')
return rst_table(array, fmt='%.5E') | [
"def",
"view_portfolio_losses",
"(",
"token",
",",
"dstore",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"loss_dt",
"=",
"oq",
".",
"loss_dt",
"(",
")",
"data",
"=",
"portfolio_loss",
"(",
"dstore",
")",
".",
"view",
"(",
"loss_dt",
")",
"[",
":",
",",
"0",
"]",
"rlzids",
"=",
"[",
"str",
"(",
"r",
")",
"for",
"r",
"in",
"range",
"(",
"len",
"(",
"data",
")",
")",
"]",
"array",
"=",
"util",
".",
"compose_arrays",
"(",
"numpy",
".",
"array",
"(",
"rlzids",
")",
",",
"data",
",",
"'rlz'",
")",
"# this is very sensitive to rounding errors, so I am using a low precision",
"return",
"rst_table",
"(",
"array",
",",
"fmt",
"=",
"'%.5E'",
")"
] | The losses for the full portfolio, for each realization and loss type,
extracted from the event loss table. | [
"The",
"losses",
"for",
"the",
"full",
"portfolio",
"for",
"each",
"realization",
"and",
"loss",
"type",
"extracted",
"from",
"the",
"event",
"loss",
"table",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L382-L393 |
gem/oq-engine | openquake/calculators/views.py | view_portfolio_loss | def view_portfolio_loss(token, dstore):
"""
The mean and stddev loss for the full portfolio for each loss type,
extracted from the event loss table, averaged over the realizations
"""
data = portfolio_loss(dstore) # shape (R, L)
loss_types = list(dstore['oqparam'].loss_dt().names)
header = ['portfolio_loss'] + loss_types
mean = ['mean'] + [row.mean() for row in data.T]
stddev = ['stddev'] + [row.std(ddof=1) for row in data.T]
return rst_table([mean, stddev], header) | python | def view_portfolio_loss(token, dstore):
data = portfolio_loss(dstore)
loss_types = list(dstore['oqparam'].loss_dt().names)
header = ['portfolio_loss'] + loss_types
mean = ['mean'] + [row.mean() for row in data.T]
stddev = ['stddev'] + [row.std(ddof=1) for row in data.T]
return rst_table([mean, stddev], header) | [
"def",
"view_portfolio_loss",
"(",
"token",
",",
"dstore",
")",
":",
"data",
"=",
"portfolio_loss",
"(",
"dstore",
")",
"# shape (R, L)",
"loss_types",
"=",
"list",
"(",
"dstore",
"[",
"'oqparam'",
"]",
".",
"loss_dt",
"(",
")",
".",
"names",
")",
"header",
"=",
"[",
"'portfolio_loss'",
"]",
"+",
"loss_types",
"mean",
"=",
"[",
"'mean'",
"]",
"+",
"[",
"row",
".",
"mean",
"(",
")",
"for",
"row",
"in",
"data",
".",
"T",
"]",
"stddev",
"=",
"[",
"'stddev'",
"]",
"+",
"[",
"row",
".",
"std",
"(",
"ddof",
"=",
"1",
")",
"for",
"row",
"in",
"data",
".",
"T",
"]",
"return",
"rst_table",
"(",
"[",
"mean",
",",
"stddev",
"]",
",",
"header",
")"
] | The mean and stddev loss for the full portfolio for each loss type,
extracted from the event loss table, averaged over the realizations | [
"The",
"mean",
"and",
"stddev",
"loss",
"for",
"the",
"full",
"portfolio",
"for",
"each",
"loss",
"type",
"extracted",
"from",
"the",
"event",
"loss",
"table",
"averaged",
"over",
"the",
"realizations"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L397-L407 |
gem/oq-engine | openquake/calculators/views.py | sum_table | def sum_table(records):
"""
Used to compute summaries. The records are assumed to have numeric
fields, except the first field which is ignored, since it typically
contains a label. Here is an example:
>>> sum_table([('a', 1), ('b', 2)])
['total', 3]
"""
size = len(records[0])
result = [None] * size
firstrec = records[0]
for i in range(size):
if isinstance(firstrec[i], (numbers.Number, numpy.ndarray)):
result[i] = sum(rec[i] for rec in records)
else:
result[i] = 'total'
return result | python | def sum_table(records):
size = len(records[0])
result = [None] * size
firstrec = records[0]
for i in range(size):
if isinstance(firstrec[i], (numbers.Number, numpy.ndarray)):
result[i] = sum(rec[i] for rec in records)
else:
result[i] = 'total'
return result | [
"def",
"sum_table",
"(",
"records",
")",
":",
"size",
"=",
"len",
"(",
"records",
"[",
"0",
"]",
")",
"result",
"=",
"[",
"None",
"]",
"*",
"size",
"firstrec",
"=",
"records",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"size",
")",
":",
"if",
"isinstance",
"(",
"firstrec",
"[",
"i",
"]",
",",
"(",
"numbers",
".",
"Number",
",",
"numpy",
".",
"ndarray",
")",
")",
":",
"result",
"[",
"i",
"]",
"=",
"sum",
"(",
"rec",
"[",
"i",
"]",
"for",
"rec",
"in",
"records",
")",
"else",
":",
"result",
"[",
"i",
"]",
"=",
"'total'",
"return",
"result"
] | Used to compute summaries. The records are assumed to have numeric
fields, except the first field which is ignored, since it typically
contains a label. Here is an example:
>>> sum_table([('a', 1), ('b', 2)])
['total', 3] | [
"Used",
"to",
"compute",
"summaries",
".",
"The",
"records",
"are",
"assumed",
"to",
"have",
"numeric",
"fields",
"except",
"the",
"first",
"field",
"which",
"is",
"ignored",
"since",
"it",
"typically",
"contains",
"a",
"label",
".",
"Here",
"is",
"an",
"example",
":"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L410-L427 |
gem/oq-engine | openquake/calculators/views.py | view_exposure_info | def view_exposure_info(token, dstore):
"""
Display info about the exposure model
"""
assetcol = dstore['assetcol/array'][:]
taxonomies = sorted(set(dstore['assetcol'].taxonomies))
cc = dstore['assetcol/cost_calculator']
ra_flag = ['relative', 'absolute']
data = [('#assets', len(assetcol)),
('#taxonomies', len(taxonomies)),
('deductibile', ra_flag[int(cc.deduct_abs)]),
('insurance_limit', ra_flag[int(cc.limit_abs)]),
]
return rst_table(data) + '\n\n' + view_assets_by_site(token, dstore) | python | def view_exposure_info(token, dstore):
assetcol = dstore['assetcol/array'][:]
taxonomies = sorted(set(dstore['assetcol'].taxonomies))
cc = dstore['assetcol/cost_calculator']
ra_flag = ['relative', 'absolute']
data = [('
('
('deductibile', ra_flag[int(cc.deduct_abs)]),
('insurance_limit', ra_flag[int(cc.limit_abs)]),
]
return rst_table(data) + '\n\n' + view_assets_by_site(token, dstore) | [
"def",
"view_exposure_info",
"(",
"token",
",",
"dstore",
")",
":",
"assetcol",
"=",
"dstore",
"[",
"'assetcol/array'",
"]",
"[",
":",
"]",
"taxonomies",
"=",
"sorted",
"(",
"set",
"(",
"dstore",
"[",
"'assetcol'",
"]",
".",
"taxonomies",
")",
")",
"cc",
"=",
"dstore",
"[",
"'assetcol/cost_calculator'",
"]",
"ra_flag",
"=",
"[",
"'relative'",
",",
"'absolute'",
"]",
"data",
"=",
"[",
"(",
"'#assets'",
",",
"len",
"(",
"assetcol",
")",
")",
",",
"(",
"'#taxonomies'",
",",
"len",
"(",
"taxonomies",
")",
")",
",",
"(",
"'deductibile'",
",",
"ra_flag",
"[",
"int",
"(",
"cc",
".",
"deduct_abs",
")",
"]",
")",
",",
"(",
"'insurance_limit'",
",",
"ra_flag",
"[",
"int",
"(",
"cc",
".",
"limit_abs",
")",
"]",
")",
",",
"]",
"return",
"rst_table",
"(",
"data",
")",
"+",
"'\\n\\n'",
"+",
"view_assets_by_site",
"(",
"token",
",",
"dstore",
")"
] | Display info about the exposure model | [
"Display",
"info",
"about",
"the",
"exposure",
"model"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L431-L444 |
gem/oq-engine | openquake/calculators/views.py | view_fullreport | def view_fullreport(token, dstore):
"""
Display an .rst report about the computation
"""
# avoid circular imports
from openquake.calculators.reportwriter import ReportWriter
return ReportWriter(dstore).make_report() | python | def view_fullreport(token, dstore):
from openquake.calculators.reportwriter import ReportWriter
return ReportWriter(dstore).make_report() | [
"def",
"view_fullreport",
"(",
"token",
",",
"dstore",
")",
":",
"# avoid circular imports",
"from",
"openquake",
".",
"calculators",
".",
"reportwriter",
"import",
"ReportWriter",
"return",
"ReportWriter",
"(",
"dstore",
")",
".",
"make_report",
"(",
")"
] | Display an .rst report about the computation | [
"Display",
"an",
".",
"rst",
"report",
"about",
"the",
"computation"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L461-L467 |
gem/oq-engine | openquake/calculators/views.py | performance_view | def performance_view(dstore):
"""
Returns the performance view as a numpy array.
"""
data = sorted(dstore['performance_data'], key=operator.itemgetter(0))
out = []
for operation, group in itertools.groupby(data, operator.itemgetter(0)):
counts = 0
time = 0
mem = 0
for _operation, time_sec, memory_mb, counts_ in group:
counts += counts_
time += time_sec
mem = max(mem, memory_mb)
out.append((operation, time, mem, counts))
out.sort(key=operator.itemgetter(1), reverse=True) # sort by time
return numpy.array(out, perf_dt) | python | def performance_view(dstore):
data = sorted(dstore['performance_data'], key=operator.itemgetter(0))
out = []
for operation, group in itertools.groupby(data, operator.itemgetter(0)):
counts = 0
time = 0
mem = 0
for _operation, time_sec, memory_mb, counts_ in group:
counts += counts_
time += time_sec
mem = max(mem, memory_mb)
out.append((operation, time, mem, counts))
out.sort(key=operator.itemgetter(1), reverse=True)
return numpy.array(out, perf_dt) | [
"def",
"performance_view",
"(",
"dstore",
")",
":",
"data",
"=",
"sorted",
"(",
"dstore",
"[",
"'performance_data'",
"]",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"0",
")",
")",
"out",
"=",
"[",
"]",
"for",
"operation",
",",
"group",
"in",
"itertools",
".",
"groupby",
"(",
"data",
",",
"operator",
".",
"itemgetter",
"(",
"0",
")",
")",
":",
"counts",
"=",
"0",
"time",
"=",
"0",
"mem",
"=",
"0",
"for",
"_operation",
",",
"time_sec",
",",
"memory_mb",
",",
"counts_",
"in",
"group",
":",
"counts",
"+=",
"counts_",
"time",
"+=",
"time_sec",
"mem",
"=",
"max",
"(",
"mem",
",",
"memory_mb",
")",
"out",
".",
"append",
"(",
"(",
"operation",
",",
"time",
",",
"mem",
",",
"counts",
")",
")",
"out",
".",
"sort",
"(",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"1",
")",
",",
"reverse",
"=",
"True",
")",
"# sort by time",
"return",
"numpy",
".",
"array",
"(",
"out",
",",
"perf_dt",
")"
] | Returns the performance view as a numpy array. | [
"Returns",
"the",
"performance",
"view",
"as",
"a",
"numpy",
"array",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L470-L486 |
gem/oq-engine | openquake/calculators/views.py | stats | def stats(name, array, *extras):
"""
Returns statistics from an array of numbers.
:param name: a descriptive string
:returns: (name, mean, std, min, max, len)
"""
std = numpy.nan if len(array) == 1 else numpy.std(array, ddof=1)
return (name, numpy.mean(array), std,
numpy.min(array), numpy.max(array), len(array)) + extras | python | def stats(name, array, *extras):
std = numpy.nan if len(array) == 1 else numpy.std(array, ddof=1)
return (name, numpy.mean(array), std,
numpy.min(array), numpy.max(array), len(array)) + extras | [
"def",
"stats",
"(",
"name",
",",
"array",
",",
"*",
"extras",
")",
":",
"std",
"=",
"numpy",
".",
"nan",
"if",
"len",
"(",
"array",
")",
"==",
"1",
"else",
"numpy",
".",
"std",
"(",
"array",
",",
"ddof",
"=",
"1",
")",
"return",
"(",
"name",
",",
"numpy",
".",
"mean",
"(",
"array",
")",
",",
"std",
",",
"numpy",
".",
"min",
"(",
"array",
")",
",",
"numpy",
".",
"max",
"(",
"array",
")",
",",
"len",
"(",
"array",
")",
")",
"+",
"extras"
] | Returns statistics from an array of numbers.
:param name: a descriptive string
:returns: (name, mean, std, min, max, len) | [
"Returns",
"statistics",
"from",
"an",
"array",
"of",
"numbers",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L497-L506 |
gem/oq-engine | openquake/calculators/views.py | view_num_units | def view_num_units(token, dstore):
"""
Display the number of units by taxonomy
"""
taxo = dstore['assetcol/tagcol/taxonomy'].value
counts = collections.Counter()
for asset in dstore['assetcol']:
counts[taxo[asset['taxonomy']]] += asset['number']
data = sorted(counts.items())
data.append(('*ALL*', sum(d[1] for d in data)))
return rst_table(data, header=['taxonomy', 'num_units']) | python | def view_num_units(token, dstore):
taxo = dstore['assetcol/tagcol/taxonomy'].value
counts = collections.Counter()
for asset in dstore['assetcol']:
counts[taxo[asset['taxonomy']]] += asset['number']
data = sorted(counts.items())
data.append(('*ALL*', sum(d[1] for d in data)))
return rst_table(data, header=['taxonomy', 'num_units']) | [
"def",
"view_num_units",
"(",
"token",
",",
"dstore",
")",
":",
"taxo",
"=",
"dstore",
"[",
"'assetcol/tagcol/taxonomy'",
"]",
".",
"value",
"counts",
"=",
"collections",
".",
"Counter",
"(",
")",
"for",
"asset",
"in",
"dstore",
"[",
"'assetcol'",
"]",
":",
"counts",
"[",
"taxo",
"[",
"asset",
"[",
"'taxonomy'",
"]",
"]",
"]",
"+=",
"asset",
"[",
"'number'",
"]",
"data",
"=",
"sorted",
"(",
"counts",
".",
"items",
"(",
")",
")",
"data",
".",
"append",
"(",
"(",
"'*ALL*'",
",",
"sum",
"(",
"d",
"[",
"1",
"]",
"for",
"d",
"in",
"data",
")",
")",
")",
"return",
"rst_table",
"(",
"data",
",",
"header",
"=",
"[",
"'taxonomy'",
",",
"'num_units'",
"]",
")"
] | Display the number of units by taxonomy | [
"Display",
"the",
"number",
"of",
"units",
"by",
"taxonomy"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L510-L520 |
gem/oq-engine | openquake/calculators/views.py | view_assets_by_site | def view_assets_by_site(token, dstore):
"""
Display statistical information about the distribution of the assets
"""
taxonomies = dstore['assetcol/tagcol/taxonomy'].value
assets_by_site = dstore['assetcol'].assets_by_site()
data = ['taxonomy mean stddev min max num_sites num_assets'.split()]
num_assets = AccumDict()
for assets in assets_by_site:
num_assets += {k: [len(v)] for k, v in group_array(
assets, 'taxonomy').items()}
for taxo in sorted(num_assets):
val = numpy.array(num_assets[taxo])
data.append(stats(taxonomies[taxo], val, val.sum()))
if len(num_assets) > 1: # more than one taxonomy, add a summary
n_assets = numpy.array([len(assets) for assets in assets_by_site])
data.append(stats('*ALL*', n_assets, n_assets.sum()))
return rst_table(data) | python | def view_assets_by_site(token, dstore):
taxonomies = dstore['assetcol/tagcol/taxonomy'].value
assets_by_site = dstore['assetcol'].assets_by_site()
data = ['taxonomy mean stddev min max num_sites num_assets'.split()]
num_assets = AccumDict()
for assets in assets_by_site:
num_assets += {k: [len(v)] for k, v in group_array(
assets, 'taxonomy').items()}
for taxo in sorted(num_assets):
val = numpy.array(num_assets[taxo])
data.append(stats(taxonomies[taxo], val, val.sum()))
if len(num_assets) > 1:
n_assets = numpy.array([len(assets) for assets in assets_by_site])
data.append(stats('*ALL*', n_assets, n_assets.sum()))
return rst_table(data) | [
"def",
"view_assets_by_site",
"(",
"token",
",",
"dstore",
")",
":",
"taxonomies",
"=",
"dstore",
"[",
"'assetcol/tagcol/taxonomy'",
"]",
".",
"value",
"assets_by_site",
"=",
"dstore",
"[",
"'assetcol'",
"]",
".",
"assets_by_site",
"(",
")",
"data",
"=",
"[",
"'taxonomy mean stddev min max num_sites num_assets'",
".",
"split",
"(",
")",
"]",
"num_assets",
"=",
"AccumDict",
"(",
")",
"for",
"assets",
"in",
"assets_by_site",
":",
"num_assets",
"+=",
"{",
"k",
":",
"[",
"len",
"(",
"v",
")",
"]",
"for",
"k",
",",
"v",
"in",
"group_array",
"(",
"assets",
",",
"'taxonomy'",
")",
".",
"items",
"(",
")",
"}",
"for",
"taxo",
"in",
"sorted",
"(",
"num_assets",
")",
":",
"val",
"=",
"numpy",
".",
"array",
"(",
"num_assets",
"[",
"taxo",
"]",
")",
"data",
".",
"append",
"(",
"stats",
"(",
"taxonomies",
"[",
"taxo",
"]",
",",
"val",
",",
"val",
".",
"sum",
"(",
")",
")",
")",
"if",
"len",
"(",
"num_assets",
")",
">",
"1",
":",
"# more than one taxonomy, add a summary",
"n_assets",
"=",
"numpy",
".",
"array",
"(",
"[",
"len",
"(",
"assets",
")",
"for",
"assets",
"in",
"assets_by_site",
"]",
")",
"data",
".",
"append",
"(",
"stats",
"(",
"'*ALL*'",
",",
"n_assets",
",",
"n_assets",
".",
"sum",
"(",
")",
")",
")",
"return",
"rst_table",
"(",
"data",
")"
] | Display statistical information about the distribution of the assets | [
"Display",
"statistical",
"information",
"about",
"the",
"distribution",
"of",
"the",
"assets"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L524-L541 |
gem/oq-engine | openquake/calculators/views.py | view_required_params_per_trt | def view_required_params_per_trt(token, dstore):
"""
Display the parameters needed by each tectonic region type
"""
csm_info = dstore['csm_info']
tbl = []
for grp_id, trt in sorted(csm_info.grp_by("trt").items()):
gsims = csm_info.gsim_lt.get_gsims(trt)
maker = ContextMaker(trt, gsims)
distances = sorted(maker.REQUIRES_DISTANCES)
siteparams = sorted(maker.REQUIRES_SITES_PARAMETERS)
ruptparams = sorted(maker.REQUIRES_RUPTURE_PARAMETERS)
tbl.append((grp_id, ' '.join(map(repr, map(repr, gsims))),
distances, siteparams, ruptparams))
return rst_table(
tbl, header='grp_id gsims distances siteparams ruptparams'.split(),
fmt=scientificformat) | python | def view_required_params_per_trt(token, dstore):
csm_info = dstore['csm_info']
tbl = []
for grp_id, trt in sorted(csm_info.grp_by("trt").items()):
gsims = csm_info.gsim_lt.get_gsims(trt)
maker = ContextMaker(trt, gsims)
distances = sorted(maker.REQUIRES_DISTANCES)
siteparams = sorted(maker.REQUIRES_SITES_PARAMETERS)
ruptparams = sorted(maker.REQUIRES_RUPTURE_PARAMETERS)
tbl.append((grp_id, ' '.join(map(repr, map(repr, gsims))),
distances, siteparams, ruptparams))
return rst_table(
tbl, header='grp_id gsims distances siteparams ruptparams'.split(),
fmt=scientificformat) | [
"def",
"view_required_params_per_trt",
"(",
"token",
",",
"dstore",
")",
":",
"csm_info",
"=",
"dstore",
"[",
"'csm_info'",
"]",
"tbl",
"=",
"[",
"]",
"for",
"grp_id",
",",
"trt",
"in",
"sorted",
"(",
"csm_info",
".",
"grp_by",
"(",
"\"trt\"",
")",
".",
"items",
"(",
")",
")",
":",
"gsims",
"=",
"csm_info",
".",
"gsim_lt",
".",
"get_gsims",
"(",
"trt",
")",
"maker",
"=",
"ContextMaker",
"(",
"trt",
",",
"gsims",
")",
"distances",
"=",
"sorted",
"(",
"maker",
".",
"REQUIRES_DISTANCES",
")",
"siteparams",
"=",
"sorted",
"(",
"maker",
".",
"REQUIRES_SITES_PARAMETERS",
")",
"ruptparams",
"=",
"sorted",
"(",
"maker",
".",
"REQUIRES_RUPTURE_PARAMETERS",
")",
"tbl",
".",
"append",
"(",
"(",
"grp_id",
",",
"' '",
".",
"join",
"(",
"map",
"(",
"repr",
",",
"map",
"(",
"repr",
",",
"gsims",
")",
")",
")",
",",
"distances",
",",
"siteparams",
",",
"ruptparams",
")",
")",
"return",
"rst_table",
"(",
"tbl",
",",
"header",
"=",
"'grp_id gsims distances siteparams ruptparams'",
".",
"split",
"(",
")",
",",
"fmt",
"=",
"scientificformat",
")"
] | Display the parameters needed by each tectonic region type | [
"Display",
"the",
"parameters",
"needed",
"by",
"each",
"tectonic",
"region",
"type"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L545-L561 |
gem/oq-engine | openquake/calculators/views.py | view_task_info | def view_task_info(token, dstore):
"""
Display statistical information about the tasks performance.
It is possible to get full information about a specific task
with a command like this one, for a classical calculation::
$ oq show task_info:classical
"""
args = token.split(':')[1:] # called as task_info:task_name
if args:
[task] = args
array = dstore['task_info/' + task].value
rduration = array['duration'] / array['weight']
data = util.compose_arrays(rduration, array, 'rduration')
data.sort(order='duration')
return rst_table(data)
data = ['operation-duration mean stddev min max outputs'.split()]
for task in dstore['task_info']:
val = dstore['task_info/' + task]['duration']
if len(val):
data.append(stats(task, val))
if len(data) == 1:
return 'Not available'
return rst_table(data) | python | def view_task_info(token, dstore):
args = token.split(':')[1:]
if args:
[task] = args
array = dstore['task_info/' + task].value
rduration = array['duration'] / array['weight']
data = util.compose_arrays(rduration, array, 'rduration')
data.sort(order='duration')
return rst_table(data)
data = ['operation-duration mean stddev min max outputs'.split()]
for task in dstore['task_info']:
val = dstore['task_info/' + task]['duration']
if len(val):
data.append(stats(task, val))
if len(data) == 1:
return 'Not available'
return rst_table(data) | [
"def",
"view_task_info",
"(",
"token",
",",
"dstore",
")",
":",
"args",
"=",
"token",
".",
"split",
"(",
"':'",
")",
"[",
"1",
":",
"]",
"# called as task_info:task_name",
"if",
"args",
":",
"[",
"task",
"]",
"=",
"args",
"array",
"=",
"dstore",
"[",
"'task_info/'",
"+",
"task",
"]",
".",
"value",
"rduration",
"=",
"array",
"[",
"'duration'",
"]",
"/",
"array",
"[",
"'weight'",
"]",
"data",
"=",
"util",
".",
"compose_arrays",
"(",
"rduration",
",",
"array",
",",
"'rduration'",
")",
"data",
".",
"sort",
"(",
"order",
"=",
"'duration'",
")",
"return",
"rst_table",
"(",
"data",
")",
"data",
"=",
"[",
"'operation-duration mean stddev min max outputs'",
".",
"split",
"(",
")",
"]",
"for",
"task",
"in",
"dstore",
"[",
"'task_info'",
"]",
":",
"val",
"=",
"dstore",
"[",
"'task_info/'",
"+",
"task",
"]",
"[",
"'duration'",
"]",
"if",
"len",
"(",
"val",
")",
":",
"data",
".",
"append",
"(",
"stats",
"(",
"task",
",",
"val",
")",
")",
"if",
"len",
"(",
"data",
")",
"==",
"1",
":",
"return",
"'Not available'",
"return",
"rst_table",
"(",
"data",
")"
] | Display statistical information about the tasks performance.
It is possible to get full information about a specific task
with a command like this one, for a classical calculation::
$ oq show task_info:classical | [
"Display",
"statistical",
"information",
"about",
"the",
"tasks",
"performance",
".",
"It",
"is",
"possible",
"to",
"get",
"full",
"information",
"about",
"a",
"specific",
"task",
"with",
"a",
"command",
"like",
"this",
"one",
"for",
"a",
"classical",
"calculation",
"::"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L565-L589 |
gem/oq-engine | openquake/calculators/views.py | view_task_durations | def view_task_durations(token, dstore):
"""
Display the raw task durations. Here is an example of usage::
$ oq show task_durations:classical
"""
task = token.split(':')[1] # called as task_duration:task_name
array = dstore['task_info/' + task]['duration']
return '\n'.join(map(str, array)) | python | def view_task_durations(token, dstore):
task = token.split(':')[1]
array = dstore['task_info/' + task]['duration']
return '\n'.join(map(str, array)) | [
"def",
"view_task_durations",
"(",
"token",
",",
"dstore",
")",
":",
"task",
"=",
"token",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
"# called as task_duration:task_name",
"array",
"=",
"dstore",
"[",
"'task_info/'",
"+",
"task",
"]",
"[",
"'duration'",
"]",
"return",
"'\\n'",
".",
"join",
"(",
"map",
"(",
"str",
",",
"array",
")",
")"
] | Display the raw task durations. Here is an example of usage::
$ oq show task_durations:classical | [
"Display",
"the",
"raw",
"task",
"durations",
".",
"Here",
"is",
"an",
"example",
"of",
"usage",
"::"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L593-L601 |
gem/oq-engine | openquake/calculators/views.py | view_task_hazard | def view_task_hazard(token, dstore):
"""
Display info about a given task. Here are a few examples of usage::
$ oq show task_hazard:0 # the fastest task
$ oq show task_hazard:-1 # the slowest task
"""
tasks = set(dstore['task_info'])
if 'source_data' not in dstore:
return 'Missing source_data'
if 'classical_split_filter' in tasks:
data = dstore['task_info/classical_split_filter'].value
else:
data = dstore['task_info/compute_gmfs'].value
data.sort(order='duration')
rec = data[int(token.split(':')[1])]
taskno = rec['taskno']
arr = get_array(dstore['source_data'].value, taskno=taskno)
st = [stats('nsites', arr['nsites']), stats('weight', arr['weight'])]
sources = dstore['task_sources'][taskno - 1].split()
srcs = set(decode(s).split(':', 1)[0] for s in sources)
res = 'taskno=%d, weight=%d, duration=%d s, sources="%s"\n\n' % (
taskno, rec['weight'], rec['duration'], ' '.join(sorted(srcs)))
return res + rst_table(st, header='variable mean stddev min max n'.split()) | python | def view_task_hazard(token, dstore):
tasks = set(dstore['task_info'])
if 'source_data' not in dstore:
return 'Missing source_data'
if 'classical_split_filter' in tasks:
data = dstore['task_info/classical_split_filter'].value
else:
data = dstore['task_info/compute_gmfs'].value
data.sort(order='duration')
rec = data[int(token.split(':')[1])]
taskno = rec['taskno']
arr = get_array(dstore['source_data'].value, taskno=taskno)
st = [stats('nsites', arr['nsites']), stats('weight', arr['weight'])]
sources = dstore['task_sources'][taskno - 1].split()
srcs = set(decode(s).split(':', 1)[0] for s in sources)
res = 'taskno=%d, weight=%d, duration=%d s, sources="%s"\n\n' % (
taskno, rec['weight'], rec['duration'], ' '.join(sorted(srcs)))
return res + rst_table(st, header='variable mean stddev min max n'.split()) | [
"def",
"view_task_hazard",
"(",
"token",
",",
"dstore",
")",
":",
"tasks",
"=",
"set",
"(",
"dstore",
"[",
"'task_info'",
"]",
")",
"if",
"'source_data'",
"not",
"in",
"dstore",
":",
"return",
"'Missing source_data'",
"if",
"'classical_split_filter'",
"in",
"tasks",
":",
"data",
"=",
"dstore",
"[",
"'task_info/classical_split_filter'",
"]",
".",
"value",
"else",
":",
"data",
"=",
"dstore",
"[",
"'task_info/compute_gmfs'",
"]",
".",
"value",
"data",
".",
"sort",
"(",
"order",
"=",
"'duration'",
")",
"rec",
"=",
"data",
"[",
"int",
"(",
"token",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
")",
"]",
"taskno",
"=",
"rec",
"[",
"'taskno'",
"]",
"arr",
"=",
"get_array",
"(",
"dstore",
"[",
"'source_data'",
"]",
".",
"value",
",",
"taskno",
"=",
"taskno",
")",
"st",
"=",
"[",
"stats",
"(",
"'nsites'",
",",
"arr",
"[",
"'nsites'",
"]",
")",
",",
"stats",
"(",
"'weight'",
",",
"arr",
"[",
"'weight'",
"]",
")",
"]",
"sources",
"=",
"dstore",
"[",
"'task_sources'",
"]",
"[",
"taskno",
"-",
"1",
"]",
".",
"split",
"(",
")",
"srcs",
"=",
"set",
"(",
"decode",
"(",
"s",
")",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"0",
"]",
"for",
"s",
"in",
"sources",
")",
"res",
"=",
"'taskno=%d, weight=%d, duration=%d s, sources=\"%s\"\\n\\n'",
"%",
"(",
"taskno",
",",
"rec",
"[",
"'weight'",
"]",
",",
"rec",
"[",
"'duration'",
"]",
",",
"' '",
".",
"join",
"(",
"sorted",
"(",
"srcs",
")",
")",
")",
"return",
"res",
"+",
"rst_table",
"(",
"st",
",",
"header",
"=",
"'variable mean stddev min max n'",
".",
"split",
"(",
")",
")"
] | Display info about a given task. Here are a few examples of usage::
$ oq show task_hazard:0 # the fastest task
$ oq show task_hazard:-1 # the slowest task | [
"Display",
"info",
"about",
"a",
"given",
"task",
".",
"Here",
"are",
"a",
"few",
"examples",
"of",
"usage",
"::"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L605-L628 |
gem/oq-engine | openquake/calculators/views.py | view_task_risk | def view_task_risk(token, dstore):
"""
Display info about a given risk task. Here are a few examples of usage::
$ oq show task_risk:0 # the fastest task
$ oq show task_risk:-1 # the slowest task
"""
[key] = dstore['task_info']
data = dstore['task_info/' + key].value
data.sort(order='duration')
rec = data[int(token.split(':')[1])]
taskno = rec['taskno']
res = 'taskno=%d, weight=%d, duration=%d s' % (
taskno, rec['weight'], rec['duration'])
return res | python | def view_task_risk(token, dstore):
[key] = dstore['task_info']
data = dstore['task_info/' + key].value
data.sort(order='duration')
rec = data[int(token.split(':')[1])]
taskno = rec['taskno']
res = 'taskno=%d, weight=%d, duration=%d s' % (
taskno, rec['weight'], rec['duration'])
return res | [
"def",
"view_task_risk",
"(",
"token",
",",
"dstore",
")",
":",
"[",
"key",
"]",
"=",
"dstore",
"[",
"'task_info'",
"]",
"data",
"=",
"dstore",
"[",
"'task_info/'",
"+",
"key",
"]",
".",
"value",
"data",
".",
"sort",
"(",
"order",
"=",
"'duration'",
")",
"rec",
"=",
"data",
"[",
"int",
"(",
"token",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
")",
"]",
"taskno",
"=",
"rec",
"[",
"'taskno'",
"]",
"res",
"=",
"'taskno=%d, weight=%d, duration=%d s'",
"%",
"(",
"taskno",
",",
"rec",
"[",
"'weight'",
"]",
",",
"rec",
"[",
"'duration'",
"]",
")",
"return",
"res"
] | Display info about a given risk task. Here are a few examples of usage::
$ oq show task_risk:0 # the fastest task
$ oq show task_risk:-1 # the slowest task | [
"Display",
"info",
"about",
"a",
"given",
"risk",
"task",
".",
"Here",
"are",
"a",
"few",
"examples",
"of",
"usage",
"::"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L632-L646 |
gem/oq-engine | openquake/calculators/views.py | view_hmap | def view_hmap(token, dstore):
"""
Display the highest 20 points of the mean hazard map. Called as
$ oq show hmap:0.1 # 10% PoE
"""
try:
poe = valid.probability(token.split(':')[1])
except IndexError:
poe = 0.1
mean = dict(extract(dstore, 'hcurves?kind=mean'))['mean']
oq = dstore['oqparam']
hmap = calc.make_hmap_array(mean, oq.imtls, [poe], len(mean))
dt = numpy.dtype([('sid', U32)] + [(imt, F32) for imt in oq.imtls])
array = numpy.zeros(len(hmap), dt)
for i, vals in enumerate(hmap):
array[i] = (i, ) + tuple(vals)
array.sort(order=list(oq.imtls)[0])
return rst_table(array[:20]) | python | def view_hmap(token, dstore):
try:
poe = valid.probability(token.split(':')[1])
except IndexError:
poe = 0.1
mean = dict(extract(dstore, 'hcurves?kind=mean'))['mean']
oq = dstore['oqparam']
hmap = calc.make_hmap_array(mean, oq.imtls, [poe], len(mean))
dt = numpy.dtype([('sid', U32)] + [(imt, F32) for imt in oq.imtls])
array = numpy.zeros(len(hmap), dt)
for i, vals in enumerate(hmap):
array[i] = (i, ) + tuple(vals)
array.sort(order=list(oq.imtls)[0])
return rst_table(array[:20]) | [
"def",
"view_hmap",
"(",
"token",
",",
"dstore",
")",
":",
"try",
":",
"poe",
"=",
"valid",
".",
"probability",
"(",
"token",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
")",
"except",
"IndexError",
":",
"poe",
"=",
"0.1",
"mean",
"=",
"dict",
"(",
"extract",
"(",
"dstore",
",",
"'hcurves?kind=mean'",
")",
")",
"[",
"'mean'",
"]",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"hmap",
"=",
"calc",
".",
"make_hmap_array",
"(",
"mean",
",",
"oq",
".",
"imtls",
",",
"[",
"poe",
"]",
",",
"len",
"(",
"mean",
")",
")",
"dt",
"=",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"'sid'",
",",
"U32",
")",
"]",
"+",
"[",
"(",
"imt",
",",
"F32",
")",
"for",
"imt",
"in",
"oq",
".",
"imtls",
"]",
")",
"array",
"=",
"numpy",
".",
"zeros",
"(",
"len",
"(",
"hmap",
")",
",",
"dt",
")",
"for",
"i",
",",
"vals",
"in",
"enumerate",
"(",
"hmap",
")",
":",
"array",
"[",
"i",
"]",
"=",
"(",
"i",
",",
")",
"+",
"tuple",
"(",
"vals",
")",
"array",
".",
"sort",
"(",
"order",
"=",
"list",
"(",
"oq",
".",
"imtls",
")",
"[",
"0",
"]",
")",
"return",
"rst_table",
"(",
"array",
"[",
":",
"20",
"]",
")"
] | Display the highest 20 points of the mean hazard map. Called as
$ oq show hmap:0.1 # 10% PoE | [
"Display",
"the",
"highest",
"20",
"points",
"of",
"the",
"mean",
"hazard",
"map",
".",
"Called",
"as",
"$",
"oq",
"show",
"hmap",
":",
"0",
".",
"1",
"#",
"10%",
"PoE"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L650-L667 |
gem/oq-engine | openquake/calculators/views.py | view_global_hcurves | def view_global_hcurves(token, dstore):
"""
Display the global hazard curves for the calculation. They are
used for debugging purposes when comparing the results of two
calculations. They are the mean over the sites of the mean hazard
curves.
"""
oq = dstore['oqparam']
nsites = len(dstore['sitecol'])
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
mean = getters.PmapGetter(dstore, rlzs_assoc).get_mean()
array = calc.convert_to_array(mean, nsites, oq.imtls)
res = numpy.zeros(1, array.dtype)
for name in array.dtype.names:
res[name] = array[name].mean()
return rst_table(res) | python | def view_global_hcurves(token, dstore):
oq = dstore['oqparam']
nsites = len(dstore['sitecol'])
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
mean = getters.PmapGetter(dstore, rlzs_assoc).get_mean()
array = calc.convert_to_array(mean, nsites, oq.imtls)
res = numpy.zeros(1, array.dtype)
for name in array.dtype.names:
res[name] = array[name].mean()
return rst_table(res) | [
"def",
"view_global_hcurves",
"(",
"token",
",",
"dstore",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"nsites",
"=",
"len",
"(",
"dstore",
"[",
"'sitecol'",
"]",
")",
"rlzs_assoc",
"=",
"dstore",
"[",
"'csm_info'",
"]",
".",
"get_rlzs_assoc",
"(",
")",
"mean",
"=",
"getters",
".",
"PmapGetter",
"(",
"dstore",
",",
"rlzs_assoc",
")",
".",
"get_mean",
"(",
")",
"array",
"=",
"calc",
".",
"convert_to_array",
"(",
"mean",
",",
"nsites",
",",
"oq",
".",
"imtls",
")",
"res",
"=",
"numpy",
".",
"zeros",
"(",
"1",
",",
"array",
".",
"dtype",
")",
"for",
"name",
"in",
"array",
".",
"dtype",
".",
"names",
":",
"res",
"[",
"name",
"]",
"=",
"array",
"[",
"name",
"]",
".",
"mean",
"(",
")",
"return",
"rst_table",
"(",
"res",
")"
] | Display the global hazard curves for the calculation. They are
used for debugging purposes when comparing the results of two
calculations. They are the mean over the sites of the mean hazard
curves. | [
"Display",
"the",
"global",
"hazard",
"curves",
"for",
"the",
"calculation",
".",
"They",
"are",
"used",
"for",
"debugging",
"purposes",
"when",
"comparing",
"the",
"results",
"of",
"two",
"calculations",
".",
"They",
"are",
"the",
"mean",
"over",
"the",
"sites",
"of",
"the",
"mean",
"hazard",
"curves",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L671-L686 |
gem/oq-engine | openquake/calculators/views.py | view_dupl_sources_time | def view_dupl_sources_time(token, dstore):
"""
Display the time spent computing duplicated sources
"""
info = dstore['source_info']
items = sorted(group_array(info.value, 'source_id').items())
tbl = []
tot_time = 0
for source_id, records in items:
if len(records) > 1: # dupl
calc_time = records['calc_time'].sum()
tot_time += calc_time + records['split_time'].sum()
tbl.append((source_id, calc_time, len(records)))
if tbl and info.attrs.get('has_dupl_sources'):
tot = info['calc_time'].sum() + info['split_time'].sum()
percent = tot_time / tot * 100
m = '\nTotal time in duplicated sources: %d/%d (%d%%)' % (
tot_time, tot, percent)
return rst_table(tbl, ['source_id', 'calc_time', 'num_dupl']) + m
else:
return 'There are no duplicated sources' | python | def view_dupl_sources_time(token, dstore):
info = dstore['source_info']
items = sorted(group_array(info.value, 'source_id').items())
tbl = []
tot_time = 0
for source_id, records in items:
if len(records) > 1:
calc_time = records['calc_time'].sum()
tot_time += calc_time + records['split_time'].sum()
tbl.append((source_id, calc_time, len(records)))
if tbl and info.attrs.get('has_dupl_sources'):
tot = info['calc_time'].sum() + info['split_time'].sum()
percent = tot_time / tot * 100
m = '\nTotal time in duplicated sources: %d/%d (%d%%)' % (
tot_time, tot, percent)
return rst_table(tbl, ['source_id', 'calc_time', 'num_dupl']) + m
else:
return 'There are no duplicated sources' | [
"def",
"view_dupl_sources_time",
"(",
"token",
",",
"dstore",
")",
":",
"info",
"=",
"dstore",
"[",
"'source_info'",
"]",
"items",
"=",
"sorted",
"(",
"group_array",
"(",
"info",
".",
"value",
",",
"'source_id'",
")",
".",
"items",
"(",
")",
")",
"tbl",
"=",
"[",
"]",
"tot_time",
"=",
"0",
"for",
"source_id",
",",
"records",
"in",
"items",
":",
"if",
"len",
"(",
"records",
")",
">",
"1",
":",
"# dupl",
"calc_time",
"=",
"records",
"[",
"'calc_time'",
"]",
".",
"sum",
"(",
")",
"tot_time",
"+=",
"calc_time",
"+",
"records",
"[",
"'split_time'",
"]",
".",
"sum",
"(",
")",
"tbl",
".",
"append",
"(",
"(",
"source_id",
",",
"calc_time",
",",
"len",
"(",
"records",
")",
")",
")",
"if",
"tbl",
"and",
"info",
".",
"attrs",
".",
"get",
"(",
"'has_dupl_sources'",
")",
":",
"tot",
"=",
"info",
"[",
"'calc_time'",
"]",
".",
"sum",
"(",
")",
"+",
"info",
"[",
"'split_time'",
"]",
".",
"sum",
"(",
")",
"percent",
"=",
"tot_time",
"/",
"tot",
"*",
"100",
"m",
"=",
"'\\nTotal time in duplicated sources: %d/%d (%d%%)'",
"%",
"(",
"tot_time",
",",
"tot",
",",
"percent",
")",
"return",
"rst_table",
"(",
"tbl",
",",
"[",
"'source_id'",
",",
"'calc_time'",
",",
"'num_dupl'",
"]",
")",
"+",
"m",
"else",
":",
"return",
"'There are no duplicated sources'"
] | Display the time spent computing duplicated sources | [
"Display",
"the",
"time",
"spent",
"computing",
"duplicated",
"sources"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L690-L710 |
gem/oq-engine | openquake/calculators/views.py | view_global_poes | def view_global_poes(token, dstore):
"""
Display global probabilities averaged on all sites and all GMPEs
"""
tbl = []
imtls = dstore['oqparam'].imtls
header = ['grp_id'] + [str(poe) for poe in imtls.array]
for grp in sorted(dstore['poes']):
poes = dstore['poes/' + grp]
nsites = len(poes)
site_avg = sum(poes[sid].array for sid in poes) / nsites
gsim_avg = site_avg.sum(axis=1) / poes.shape_z
tbl.append([grp] + list(gsim_avg))
return rst_table(tbl, header=header) | python | def view_global_poes(token, dstore):
tbl = []
imtls = dstore['oqparam'].imtls
header = ['grp_id'] + [str(poe) for poe in imtls.array]
for grp in sorted(dstore['poes']):
poes = dstore['poes/' + grp]
nsites = len(poes)
site_avg = sum(poes[sid].array for sid in poes) / nsites
gsim_avg = site_avg.sum(axis=1) / poes.shape_z
tbl.append([grp] + list(gsim_avg))
return rst_table(tbl, header=header) | [
"def",
"view_global_poes",
"(",
"token",
",",
"dstore",
")",
":",
"tbl",
"=",
"[",
"]",
"imtls",
"=",
"dstore",
"[",
"'oqparam'",
"]",
".",
"imtls",
"header",
"=",
"[",
"'grp_id'",
"]",
"+",
"[",
"str",
"(",
"poe",
")",
"for",
"poe",
"in",
"imtls",
".",
"array",
"]",
"for",
"grp",
"in",
"sorted",
"(",
"dstore",
"[",
"'poes'",
"]",
")",
":",
"poes",
"=",
"dstore",
"[",
"'poes/'",
"+",
"grp",
"]",
"nsites",
"=",
"len",
"(",
"poes",
")",
"site_avg",
"=",
"sum",
"(",
"poes",
"[",
"sid",
"]",
".",
"array",
"for",
"sid",
"in",
"poes",
")",
"/",
"nsites",
"gsim_avg",
"=",
"site_avg",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"/",
"poes",
".",
"shape_z",
"tbl",
".",
"append",
"(",
"[",
"grp",
"]",
"+",
"list",
"(",
"gsim_avg",
")",
")",
"return",
"rst_table",
"(",
"tbl",
",",
"header",
"=",
"header",
")"
] | Display global probabilities averaged on all sites and all GMPEs | [
"Display",
"global",
"probabilities",
"averaged",
"on",
"all",
"sites",
"and",
"all",
"GMPEs"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L714-L727 |
gem/oq-engine | openquake/calculators/views.py | view_global_hmaps | def view_global_hmaps(token, dstore):
"""
Display the global hazard maps for the calculation. They are
used for debugging purposes when comparing the results of two
calculations. They are the mean over the sites of the mean hazard
maps.
"""
oq = dstore['oqparam']
dt = numpy.dtype([('%s-%s' % (imt, poe), F32)
for imt in oq.imtls for poe in oq.poes])
array = dstore['hmaps/mean'].value.view(dt)[:, 0]
res = numpy.zeros(1, array.dtype)
for name in array.dtype.names:
res[name] = array[name].mean()
return rst_table(res) | python | def view_global_hmaps(token, dstore):
oq = dstore['oqparam']
dt = numpy.dtype([('%s-%s' % (imt, poe), F32)
for imt in oq.imtls for poe in oq.poes])
array = dstore['hmaps/mean'].value.view(dt)[:, 0]
res = numpy.zeros(1, array.dtype)
for name in array.dtype.names:
res[name] = array[name].mean()
return rst_table(res) | [
"def",
"view_global_hmaps",
"(",
"token",
",",
"dstore",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"dt",
"=",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"'%s-%s'",
"%",
"(",
"imt",
",",
"poe",
")",
",",
"F32",
")",
"for",
"imt",
"in",
"oq",
".",
"imtls",
"for",
"poe",
"in",
"oq",
".",
"poes",
"]",
")",
"array",
"=",
"dstore",
"[",
"'hmaps/mean'",
"]",
".",
"value",
".",
"view",
"(",
"dt",
")",
"[",
":",
",",
"0",
"]",
"res",
"=",
"numpy",
".",
"zeros",
"(",
"1",
",",
"array",
".",
"dtype",
")",
"for",
"name",
"in",
"array",
".",
"dtype",
".",
"names",
":",
"res",
"[",
"name",
"]",
"=",
"array",
"[",
"name",
"]",
".",
"mean",
"(",
")",
"return",
"rst_table",
"(",
"res",
")"
] | Display the global hazard maps for the calculation. They are
used for debugging purposes when comparing the results of two
calculations. They are the mean over the sites of the mean hazard
maps. | [
"Display",
"the",
"global",
"hazard",
"maps",
"for",
"the",
"calculation",
".",
"They",
"are",
"used",
"for",
"debugging",
"purposes",
"when",
"comparing",
"the",
"results",
"of",
"two",
"calculations",
".",
"They",
"are",
"the",
"mean",
"over",
"the",
"sites",
"of",
"the",
"mean",
"hazard",
"maps",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L731-L745 |
gem/oq-engine | openquake/calculators/views.py | view_global_gmfs | def view_global_gmfs(token, dstore):
"""
Display GMFs averaged on everything for debugging purposes
"""
imtls = dstore['oqparam'].imtls
row = dstore['gmf_data/data']['gmv'].mean(axis=0)
return rst_table([row], header=imtls) | python | def view_global_gmfs(token, dstore):
imtls = dstore['oqparam'].imtls
row = dstore['gmf_data/data']['gmv'].mean(axis=0)
return rst_table([row], header=imtls) | [
"def",
"view_global_gmfs",
"(",
"token",
",",
"dstore",
")",
":",
"imtls",
"=",
"dstore",
"[",
"'oqparam'",
"]",
".",
"imtls",
"row",
"=",
"dstore",
"[",
"'gmf_data/data'",
"]",
"[",
"'gmv'",
"]",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
"return",
"rst_table",
"(",
"[",
"row",
"]",
",",
"header",
"=",
"imtls",
")"
] | Display GMFs averaged on everything for debugging purposes | [
"Display",
"GMFs",
"averaged",
"on",
"everything",
"for",
"debugging",
"purposes"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L749-L755 |
gem/oq-engine | openquake/calculators/views.py | view_mean_disagg | def view_mean_disagg(token, dstore):
"""
Display mean quantities for the disaggregation. Useful for checking
differences between two calculations.
"""
tbl = []
for key, dset in sorted(dstore['disagg'].items()):
vals = [ds.value.mean() for k, ds in sorted(dset.items())]
tbl.append([key] + vals)
header = ['key'] + sorted(dset)
return rst_table(sorted(tbl), header=header) | python | def view_mean_disagg(token, dstore):
tbl = []
for key, dset in sorted(dstore['disagg'].items()):
vals = [ds.value.mean() for k, ds in sorted(dset.items())]
tbl.append([key] + vals)
header = ['key'] + sorted(dset)
return rst_table(sorted(tbl), header=header) | [
"def",
"view_mean_disagg",
"(",
"token",
",",
"dstore",
")",
":",
"tbl",
"=",
"[",
"]",
"for",
"key",
",",
"dset",
"in",
"sorted",
"(",
"dstore",
"[",
"'disagg'",
"]",
".",
"items",
"(",
")",
")",
":",
"vals",
"=",
"[",
"ds",
".",
"value",
".",
"mean",
"(",
")",
"for",
"k",
",",
"ds",
"in",
"sorted",
"(",
"dset",
".",
"items",
"(",
")",
")",
"]",
"tbl",
".",
"append",
"(",
"[",
"key",
"]",
"+",
"vals",
")",
"header",
"=",
"[",
"'key'",
"]",
"+",
"sorted",
"(",
"dset",
")",
"return",
"rst_table",
"(",
"sorted",
"(",
"tbl",
")",
",",
"header",
"=",
"header",
")"
] | Display mean quantities for the disaggregation. Useful for checking
differences between two calculations. | [
"Display",
"mean",
"quantities",
"for",
"the",
"disaggregation",
".",
"Useful",
"for",
"checking",
"differences",
"between",
"two",
"calculations",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L759-L769 |
gem/oq-engine | openquake/calculators/views.py | view_elt | def view_elt(token, dstore):
"""
Display the event loss table averaged by event
"""
oq = dstore['oqparam']
R = len(dstore['csm_info'].rlzs)
dic = group_array(dstore['losses_by_event'].value, 'rlzi')
header = oq.loss_dt().names
tbl = []
for rlzi in range(R):
if rlzi in dic:
tbl.append(dic[rlzi]['loss'].mean(axis=0))
else:
tbl.append([0.] * len(header))
return rst_table(tbl, header) | python | def view_elt(token, dstore):
oq = dstore['oqparam']
R = len(dstore['csm_info'].rlzs)
dic = group_array(dstore['losses_by_event'].value, 'rlzi')
header = oq.loss_dt().names
tbl = []
for rlzi in range(R):
if rlzi in dic:
tbl.append(dic[rlzi]['loss'].mean(axis=0))
else:
tbl.append([0.] * len(header))
return rst_table(tbl, header) | [
"def",
"view_elt",
"(",
"token",
",",
"dstore",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"R",
"=",
"len",
"(",
"dstore",
"[",
"'csm_info'",
"]",
".",
"rlzs",
")",
"dic",
"=",
"group_array",
"(",
"dstore",
"[",
"'losses_by_event'",
"]",
".",
"value",
",",
"'rlzi'",
")",
"header",
"=",
"oq",
".",
"loss_dt",
"(",
")",
".",
"names",
"tbl",
"=",
"[",
"]",
"for",
"rlzi",
"in",
"range",
"(",
"R",
")",
":",
"if",
"rlzi",
"in",
"dic",
":",
"tbl",
".",
"append",
"(",
"dic",
"[",
"rlzi",
"]",
"[",
"'loss'",
"]",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
")",
"else",
":",
"tbl",
".",
"append",
"(",
"[",
"0.",
"]",
"*",
"len",
"(",
"header",
")",
")",
"return",
"rst_table",
"(",
"tbl",
",",
"header",
")"
] | Display the event loss table averaged by event | [
"Display",
"the",
"event",
"loss",
"table",
"averaged",
"by",
"event"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L773-L787 |
gem/oq-engine | openquake/calculators/views.py | view_pmap | def view_pmap(token, dstore):
"""
Display the mean ProbabilityMap associated to a given source group name
"""
grp = token.split(':')[1] # called as pmap:grp
pmap = {}
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
pgetter = getters.PmapGetter(dstore, rlzs_assoc)
pmap = pgetter.get_mean(grp)
return str(pmap) | python | def view_pmap(token, dstore):
grp = token.split(':')[1]
pmap = {}
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
pgetter = getters.PmapGetter(dstore, rlzs_assoc)
pmap = pgetter.get_mean(grp)
return str(pmap) | [
"def",
"view_pmap",
"(",
"token",
",",
"dstore",
")",
":",
"grp",
"=",
"token",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
"# called as pmap:grp",
"pmap",
"=",
"{",
"}",
"rlzs_assoc",
"=",
"dstore",
"[",
"'csm_info'",
"]",
".",
"get_rlzs_assoc",
"(",
")",
"pgetter",
"=",
"getters",
".",
"PmapGetter",
"(",
"dstore",
",",
"rlzs_assoc",
")",
"pmap",
"=",
"pgetter",
".",
"get_mean",
"(",
"grp",
")",
"return",
"str",
"(",
"pmap",
")"
] | Display the mean ProbabilityMap associated to a given source group name | [
"Display",
"the",
"mean",
"ProbabilityMap",
"associated",
"to",
"a",
"given",
"source",
"group",
"name"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L791-L800 |
gem/oq-engine | openquake/calculators/views.py | view_act_ruptures_by_src | def view_act_ruptures_by_src(token, dstore):
"""
Display the actual number of ruptures by source in event based calculations
"""
data = dstore['ruptures'].value[['srcidx', 'serial']]
counts = sorted(countby(data, 'srcidx').items(),
key=operator.itemgetter(1), reverse=True)
src_info = dstore['source_info'].value[['grp_id', 'source_id']]
table = [['src_id', 'grp_id', 'act_ruptures']]
for srcidx, act_ruptures in counts:
src = src_info[srcidx]
table.append([src['source_id'], src['grp_id'], act_ruptures])
return rst_table(table) | python | def view_act_ruptures_by_src(token, dstore):
data = dstore['ruptures'].value[['srcidx', 'serial']]
counts = sorted(countby(data, 'srcidx').items(),
key=operator.itemgetter(1), reverse=True)
src_info = dstore['source_info'].value[['grp_id', 'source_id']]
table = [['src_id', 'grp_id', 'act_ruptures']]
for srcidx, act_ruptures in counts:
src = src_info[srcidx]
table.append([src['source_id'], src['grp_id'], act_ruptures])
return rst_table(table) | [
"def",
"view_act_ruptures_by_src",
"(",
"token",
",",
"dstore",
")",
":",
"data",
"=",
"dstore",
"[",
"'ruptures'",
"]",
".",
"value",
"[",
"[",
"'srcidx'",
",",
"'serial'",
"]",
"]",
"counts",
"=",
"sorted",
"(",
"countby",
"(",
"data",
",",
"'srcidx'",
")",
".",
"items",
"(",
")",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"1",
")",
",",
"reverse",
"=",
"True",
")",
"src_info",
"=",
"dstore",
"[",
"'source_info'",
"]",
".",
"value",
"[",
"[",
"'grp_id'",
",",
"'source_id'",
"]",
"]",
"table",
"=",
"[",
"[",
"'src_id'",
",",
"'grp_id'",
",",
"'act_ruptures'",
"]",
"]",
"for",
"srcidx",
",",
"act_ruptures",
"in",
"counts",
":",
"src",
"=",
"src_info",
"[",
"srcidx",
"]",
"table",
".",
"append",
"(",
"[",
"src",
"[",
"'source_id'",
"]",
",",
"src",
"[",
"'grp_id'",
"]",
",",
"act_ruptures",
"]",
")",
"return",
"rst_table",
"(",
"table",
")"
] | Display the actual number of ruptures by source in event based calculations | [
"Display",
"the",
"actual",
"number",
"of",
"ruptures",
"by",
"source",
"in",
"event",
"based",
"calculations"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L804-L816 |
gem/oq-engine | openquake/calculators/views.py | view_dupl_sources | def view_dupl_sources(token, dstore):
"""
Show the sources with the same ID and the truly duplicated sources
"""
fields = ['source_id', 'code', 'gidx1', 'gidx2', 'num_ruptures']
dic = group_array(dstore['source_info'].value[fields], 'source_id')
sameid = []
dupl = []
for source_id, group in dic.items():
if len(group) > 1: # same ID sources
sources = []
for rec in group:
geom = dstore['source_geom'][rec['gidx1']:rec['gidx2']]
src = Source(source_id, rec['code'], geom, rec['num_ruptures'])
sources.append(src)
if all_equal(sources):
dupl.append(source_id)
sameid.append(source_id)
if not dupl:
return ''
msg = str(dupl) + '\n'
msg += ('Found %d source(s) with the same ID and %d true duplicate(s)'
% (len(sameid), len(dupl)))
fakedupl = set(sameid) - set(dupl)
if fakedupl:
msg += '\nHere is a fake duplicate: %s' % fakedupl.pop()
return msg | python | def view_dupl_sources(token, dstore):
fields = ['source_id', 'code', 'gidx1', 'gidx2', 'num_ruptures']
dic = group_array(dstore['source_info'].value[fields], 'source_id')
sameid = []
dupl = []
for source_id, group in dic.items():
if len(group) > 1:
sources = []
for rec in group:
geom = dstore['source_geom'][rec['gidx1']:rec['gidx2']]
src = Source(source_id, rec['code'], geom, rec['num_ruptures'])
sources.append(src)
if all_equal(sources):
dupl.append(source_id)
sameid.append(source_id)
if not dupl:
return ''
msg = str(dupl) + '\n'
msg += ('Found %d source(s) with the same ID and %d true duplicate(s)'
% (len(sameid), len(dupl)))
fakedupl = set(sameid) - set(dupl)
if fakedupl:
msg += '\nHere is a fake duplicate: %s' % fakedupl.pop()
return msg | [
"def",
"view_dupl_sources",
"(",
"token",
",",
"dstore",
")",
":",
"fields",
"=",
"[",
"'source_id'",
",",
"'code'",
",",
"'gidx1'",
",",
"'gidx2'",
",",
"'num_ruptures'",
"]",
"dic",
"=",
"group_array",
"(",
"dstore",
"[",
"'source_info'",
"]",
".",
"value",
"[",
"fields",
"]",
",",
"'source_id'",
")",
"sameid",
"=",
"[",
"]",
"dupl",
"=",
"[",
"]",
"for",
"source_id",
",",
"group",
"in",
"dic",
".",
"items",
"(",
")",
":",
"if",
"len",
"(",
"group",
")",
">",
"1",
":",
"# same ID sources",
"sources",
"=",
"[",
"]",
"for",
"rec",
"in",
"group",
":",
"geom",
"=",
"dstore",
"[",
"'source_geom'",
"]",
"[",
"rec",
"[",
"'gidx1'",
"]",
":",
"rec",
"[",
"'gidx2'",
"]",
"]",
"src",
"=",
"Source",
"(",
"source_id",
",",
"rec",
"[",
"'code'",
"]",
",",
"geom",
",",
"rec",
"[",
"'num_ruptures'",
"]",
")",
"sources",
".",
"append",
"(",
"src",
")",
"if",
"all_equal",
"(",
"sources",
")",
":",
"dupl",
".",
"append",
"(",
"source_id",
")",
"sameid",
".",
"append",
"(",
"source_id",
")",
"if",
"not",
"dupl",
":",
"return",
"''",
"msg",
"=",
"str",
"(",
"dupl",
")",
"+",
"'\\n'",
"msg",
"+=",
"(",
"'Found %d source(s) with the same ID and %d true duplicate(s)'",
"%",
"(",
"len",
"(",
"sameid",
")",
",",
"len",
"(",
"dupl",
")",
")",
")",
"fakedupl",
"=",
"set",
"(",
"sameid",
")",
"-",
"set",
"(",
"dupl",
")",
"if",
"fakedupl",
":",
"msg",
"+=",
"'\\nHere is a fake duplicate: %s'",
"%",
"fakedupl",
".",
"pop",
"(",
")",
"return",
"msg"
] | Show the sources with the same ID and the truly duplicated sources | [
"Show",
"the",
"sources",
"with",
"the",
"same",
"ID",
"and",
"the",
"truly",
"duplicated",
"sources"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L838-L864 |
gem/oq-engine | openquake/calculators/views.py | view_extreme_groups | def view_extreme_groups(token, dstore):
"""
Show the source groups contributing the most to the highest IML
"""
data = dstore['disagg_by_grp'].value
data.sort(order='extreme_poe')
return rst_table(data[::-1]) | python | def view_extreme_groups(token, dstore):
data = dstore['disagg_by_grp'].value
data.sort(order='extreme_poe')
return rst_table(data[::-1]) | [
"def",
"view_extreme_groups",
"(",
"token",
",",
"dstore",
")",
":",
"data",
"=",
"dstore",
"[",
"'disagg_by_grp'",
"]",
".",
"value",
"data",
".",
"sort",
"(",
"order",
"=",
"'extreme_poe'",
")",
"return",
"rst_table",
"(",
"data",
"[",
":",
":",
"-",
"1",
"]",
")"
] | Show the source groups contributing the most to the highest IML | [
"Show",
"the",
"source",
"groups",
"contributing",
"the",
"most",
"to",
"the",
"highest",
"IML"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L868-L874 |
gem/oq-engine | openquake/hazardlib/gsim/silva_2002.py | SilvaEtAl2002MblgAB1987NSHMP2008.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.
"""
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
for stddev_type in stddev_types)
C = self.COEFFS[imt]
mag = self._convert_magnitude(rup.mag)
mean = (
C['c1'] + C['c2'] * mag + C['c10'] * (mag - 6) ** 2 +
(C['c6'] + C['c7'] * mag) * np.log(dists.rjb + np.exp(C['c4']))
)
mean = clip_mean(imt, mean)
stddevs = self._compute_stddevs(C, dists.rjb.size, stddev_types)
return mean, stddevs | python | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
for stddev_type in stddev_types)
C = self.COEFFS[imt]
mag = self._convert_magnitude(rup.mag)
mean = (
C['c1'] + C['c2'] * mag + C['c10'] * (mag - 6) ** 2 +
(C['c6'] + C['c7'] * mag) * np.log(dists.rjb + np.exp(C['c4']))
)
mean = clip_mean(imt, mean)
stddevs = self._compute_stddevs(C, dists.rjb.size, stddev_types)
return mean, stddevs | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"assert",
"all",
"(",
"stddev_type",
"in",
"self",
".",
"DEFINED_FOR_STANDARD_DEVIATION_TYPES",
"for",
"stddev_type",
"in",
"stddev_types",
")",
"C",
"=",
"self",
".",
"COEFFS",
"[",
"imt",
"]",
"mag",
"=",
"self",
".",
"_convert_magnitude",
"(",
"rup",
".",
"mag",
")",
"mean",
"=",
"(",
"C",
"[",
"'c1'",
"]",
"+",
"C",
"[",
"'c2'",
"]",
"*",
"mag",
"+",
"C",
"[",
"'c10'",
"]",
"*",
"(",
"mag",
"-",
"6",
")",
"**",
"2",
"+",
"(",
"C",
"[",
"'c6'",
"]",
"+",
"C",
"[",
"'c7'",
"]",
"*",
"mag",
")",
"*",
"np",
".",
"log",
"(",
"dists",
".",
"rjb",
"+",
"np",
".",
"exp",
"(",
"C",
"[",
"'c4'",
"]",
")",
")",
")",
"mean",
"=",
"clip_mean",
"(",
"imt",
",",
"mean",
")",
"stddevs",
"=",
"self",
".",
"_compute_stddevs",
"(",
"C",
",",
"dists",
".",
"rjb",
".",
"size",
",",
"stddev_types",
")",
"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/silva_2002.py#L89-L109 |
gem/oq-engine | openquake/commonlib/oqzip.py | zip_all | def zip_all(directory):
"""
Zip source models and exposures recursively
"""
zips = []
for cwd, dirs, files in os.walk(directory):
if 'ssmLT.xml' in files:
zips.append(zip_source_model(os.path.join(cwd, 'ssmLT.xml')))
for f in files:
if f.endswith('.xml') and 'exposure' in f.lower():
zips.append(zip_exposure(os.path.join(cwd, f)))
total = sum(os.path.getsize(z) for z in zips)
logging.info('Generated %s of zipped data', general.humansize(total)) | python | def zip_all(directory):
zips = []
for cwd, dirs, files in os.walk(directory):
if 'ssmLT.xml' in files:
zips.append(zip_source_model(os.path.join(cwd, 'ssmLT.xml')))
for f in files:
if f.endswith('.xml') and 'exposure' in f.lower():
zips.append(zip_exposure(os.path.join(cwd, f)))
total = sum(os.path.getsize(z) for z in zips)
logging.info('Generated %s of zipped data', general.humansize(total)) | [
"def",
"zip_all",
"(",
"directory",
")",
":",
"zips",
"=",
"[",
"]",
"for",
"cwd",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory",
")",
":",
"if",
"'ssmLT.xml'",
"in",
"files",
":",
"zips",
".",
"append",
"(",
"zip_source_model",
"(",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"'ssmLT.xml'",
")",
")",
")",
"for",
"f",
"in",
"files",
":",
"if",
"f",
".",
"endswith",
"(",
"'.xml'",
")",
"and",
"'exposure'",
"in",
"f",
".",
"lower",
"(",
")",
":",
"zips",
".",
"append",
"(",
"zip_exposure",
"(",
"os",
".",
"path",
".",
"join",
"(",
"cwd",
",",
"f",
")",
")",
")",
"total",
"=",
"sum",
"(",
"os",
".",
"path",
".",
"getsize",
"(",
"z",
")",
"for",
"z",
"in",
"zips",
")",
"logging",
".",
"info",
"(",
"'Generated %s of zipped data'",
",",
"general",
".",
"humansize",
"(",
"total",
")",
")"
] | Zip source models and exposures recursively | [
"Zip",
"source",
"models",
"and",
"exposures",
"recursively"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqzip.py#L27-L39 |
gem/oq-engine | openquake/commonlib/oqzip.py | zip_source_model | def zip_source_model(ssmLT, archive_zip='', log=logging.info):
"""
Zip the source model files starting from the smmLT.xml file
"""
basedir = os.path.dirname(ssmLT)
if os.path.basename(ssmLT) != 'ssmLT.xml':
orig = ssmLT
ssmLT = os.path.join(basedir, 'ssmLT.xml')
with open(ssmLT, 'wb') as f:
f.write(open(orig, 'rb').read())
archive_zip = archive_zip or os.path.join(basedir, 'ssmLT.zip')
if os.path.exists(archive_zip):
sys.exit('%s exists already' % archive_zip)
oq = mock.Mock(inputs={'source_model_logic_tree': ssmLT})
checksum = readinput.get_checksum32(oq)
checkfile = os.path.join(os.path.dirname(ssmLT), 'CHECKSUM.txt')
with open(checkfile, 'w') as f:
f.write(str(checksum))
files = logictree.collect_info(ssmLT).smpaths + [
os.path.abspath(ssmLT), os.path.abspath(checkfile)]
general.zipfiles(files, archive_zip, log=log, cleanup=True)
return archive_zip | python | def zip_source_model(ssmLT, archive_zip='', log=logging.info):
basedir = os.path.dirname(ssmLT)
if os.path.basename(ssmLT) != 'ssmLT.xml':
orig = ssmLT
ssmLT = os.path.join(basedir, 'ssmLT.xml')
with open(ssmLT, 'wb') as f:
f.write(open(orig, 'rb').read())
archive_zip = archive_zip or os.path.join(basedir, 'ssmLT.zip')
if os.path.exists(archive_zip):
sys.exit('%s exists already' % archive_zip)
oq = mock.Mock(inputs={'source_model_logic_tree': ssmLT})
checksum = readinput.get_checksum32(oq)
checkfile = os.path.join(os.path.dirname(ssmLT), 'CHECKSUM.txt')
with open(checkfile, 'w') as f:
f.write(str(checksum))
files = logictree.collect_info(ssmLT).smpaths + [
os.path.abspath(ssmLT), os.path.abspath(checkfile)]
general.zipfiles(files, archive_zip, log=log, cleanup=True)
return archive_zip | [
"def",
"zip_source_model",
"(",
"ssmLT",
",",
"archive_zip",
"=",
"''",
",",
"log",
"=",
"logging",
".",
"info",
")",
":",
"basedir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"ssmLT",
")",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"ssmLT",
")",
"!=",
"'ssmLT.xml'",
":",
"orig",
"=",
"ssmLT",
"ssmLT",
"=",
"os",
".",
"path",
".",
"join",
"(",
"basedir",
",",
"'ssmLT.xml'",
")",
"with",
"open",
"(",
"ssmLT",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"open",
"(",
"orig",
",",
"'rb'",
")",
".",
"read",
"(",
")",
")",
"archive_zip",
"=",
"archive_zip",
"or",
"os",
".",
"path",
".",
"join",
"(",
"basedir",
",",
"'ssmLT.zip'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"archive_zip",
")",
":",
"sys",
".",
"exit",
"(",
"'%s exists already'",
"%",
"archive_zip",
")",
"oq",
"=",
"mock",
".",
"Mock",
"(",
"inputs",
"=",
"{",
"'source_model_logic_tree'",
":",
"ssmLT",
"}",
")",
"checksum",
"=",
"readinput",
".",
"get_checksum32",
"(",
"oq",
")",
"checkfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"ssmLT",
")",
",",
"'CHECKSUM.txt'",
")",
"with",
"open",
"(",
"checkfile",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"str",
"(",
"checksum",
")",
")",
"files",
"=",
"logictree",
".",
"collect_info",
"(",
"ssmLT",
")",
".",
"smpaths",
"+",
"[",
"os",
".",
"path",
".",
"abspath",
"(",
"ssmLT",
")",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"checkfile",
")",
"]",
"general",
".",
"zipfiles",
"(",
"files",
",",
"archive_zip",
",",
"log",
"=",
"log",
",",
"cleanup",
"=",
"True",
")",
"return",
"archive_zip"
] | Zip the source model files starting from the smmLT.xml file | [
"Zip",
"the",
"source",
"model",
"files",
"starting",
"from",
"the",
"smmLT",
".",
"xml",
"file"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqzip.py#L42-L64 |
gem/oq-engine | openquake/commonlib/oqzip.py | zip_exposure | def zip_exposure(exposure_xml, archive_zip='', log=logging.info):
"""
Zip an exposure.xml file with all its .csv subfiles (if any)
"""
archive_zip = archive_zip or exposure_xml[:-4] + '.zip'
if os.path.exists(archive_zip):
sys.exit('%s exists already' % archive_zip)
[exp] = Exposure.read_headers([exposure_xml])
files = [exposure_xml] + exp.datafiles
general.zipfiles(files, archive_zip, log=log, cleanup=True)
return archive_zip | python | def zip_exposure(exposure_xml, archive_zip='', log=logging.info):
archive_zip = archive_zip or exposure_xml[:-4] + '.zip'
if os.path.exists(archive_zip):
sys.exit('%s exists already' % archive_zip)
[exp] = Exposure.read_headers([exposure_xml])
files = [exposure_xml] + exp.datafiles
general.zipfiles(files, archive_zip, log=log, cleanup=True)
return archive_zip | [
"def",
"zip_exposure",
"(",
"exposure_xml",
",",
"archive_zip",
"=",
"''",
",",
"log",
"=",
"logging",
".",
"info",
")",
":",
"archive_zip",
"=",
"archive_zip",
"or",
"exposure_xml",
"[",
":",
"-",
"4",
"]",
"+",
"'.zip'",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"archive_zip",
")",
":",
"sys",
".",
"exit",
"(",
"'%s exists already'",
"%",
"archive_zip",
")",
"[",
"exp",
"]",
"=",
"Exposure",
".",
"read_headers",
"(",
"[",
"exposure_xml",
"]",
")",
"files",
"=",
"[",
"exposure_xml",
"]",
"+",
"exp",
".",
"datafiles",
"general",
".",
"zipfiles",
"(",
"files",
",",
"archive_zip",
",",
"log",
"=",
"log",
",",
"cleanup",
"=",
"True",
")",
"return",
"archive_zip"
] | Zip an exposure.xml file with all its .csv subfiles (if any) | [
"Zip",
"an",
"exposure",
".",
"xml",
"file",
"with",
"all",
"its",
".",
"csv",
"subfiles",
"(",
"if",
"any",
")"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqzip.py#L67-L77 |
gem/oq-engine | openquake/commonlib/oqzip.py | zip_job | def zip_job(job_ini, archive_zip='', risk_ini='', oq=None, log=logging.info):
"""
Zip the given job.ini file into the given archive, together with all
related files.
"""
if not os.path.exists(job_ini):
sys.exit('%s does not exist' % job_ini)
archive_zip = archive_zip or 'job.zip'
if isinstance(archive_zip, str): # actually it should be path-like
if not archive_zip.endswith('.zip'):
sys.exit('%s does not end with .zip' % archive_zip)
if os.path.exists(archive_zip):
sys.exit('%s exists already' % archive_zip)
# do not validate to avoid permissions error on the export_dir
oq = oq or readinput.get_oqparam(job_ini, validate=False)
if risk_ini:
risk_ini = os.path.normpath(os.path.abspath(risk_ini))
risk_inputs = readinput.get_params([risk_ini])['inputs']
del risk_inputs['job_ini']
oq.inputs.update(risk_inputs)
files = readinput.get_input_files(oq)
if risk_ini:
files = [risk_ini] + files
return general.zipfiles(files, archive_zip, log=log) | python | def zip_job(job_ini, archive_zip='', risk_ini='', oq=None, log=logging.info):
if not os.path.exists(job_ini):
sys.exit('%s does not exist' % job_ini)
archive_zip = archive_zip or 'job.zip'
if isinstance(archive_zip, str):
if not archive_zip.endswith('.zip'):
sys.exit('%s does not end with .zip' % archive_zip)
if os.path.exists(archive_zip):
sys.exit('%s exists already' % archive_zip)
oq = oq or readinput.get_oqparam(job_ini, validate=False)
if risk_ini:
risk_ini = os.path.normpath(os.path.abspath(risk_ini))
risk_inputs = readinput.get_params([risk_ini])['inputs']
del risk_inputs['job_ini']
oq.inputs.update(risk_inputs)
files = readinput.get_input_files(oq)
if risk_ini:
files = [risk_ini] + files
return general.zipfiles(files, archive_zip, log=log) | [
"def",
"zip_job",
"(",
"job_ini",
",",
"archive_zip",
"=",
"''",
",",
"risk_ini",
"=",
"''",
",",
"oq",
"=",
"None",
",",
"log",
"=",
"logging",
".",
"info",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"job_ini",
")",
":",
"sys",
".",
"exit",
"(",
"'%s does not exist'",
"%",
"job_ini",
")",
"archive_zip",
"=",
"archive_zip",
"or",
"'job.zip'",
"if",
"isinstance",
"(",
"archive_zip",
",",
"str",
")",
":",
"# actually it should be path-like",
"if",
"not",
"archive_zip",
".",
"endswith",
"(",
"'.zip'",
")",
":",
"sys",
".",
"exit",
"(",
"'%s does not end with .zip'",
"%",
"archive_zip",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"archive_zip",
")",
":",
"sys",
".",
"exit",
"(",
"'%s exists already'",
"%",
"archive_zip",
")",
"# do not validate to avoid permissions error on the export_dir",
"oq",
"=",
"oq",
"or",
"readinput",
".",
"get_oqparam",
"(",
"job_ini",
",",
"validate",
"=",
"False",
")",
"if",
"risk_ini",
":",
"risk_ini",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"risk_ini",
")",
")",
"risk_inputs",
"=",
"readinput",
".",
"get_params",
"(",
"[",
"risk_ini",
"]",
")",
"[",
"'inputs'",
"]",
"del",
"risk_inputs",
"[",
"'job_ini'",
"]",
"oq",
".",
"inputs",
".",
"update",
"(",
"risk_inputs",
")",
"files",
"=",
"readinput",
".",
"get_input_files",
"(",
"oq",
")",
"if",
"risk_ini",
":",
"files",
"=",
"[",
"risk_ini",
"]",
"+",
"files",
"return",
"general",
".",
"zipfiles",
"(",
"files",
",",
"archive_zip",
",",
"log",
"=",
"log",
")"
] | Zip the given job.ini file into the given archive, together with all
related files. | [
"Zip",
"the",
"given",
"job",
".",
"ini",
"file",
"into",
"the",
"given",
"archive",
"together",
"with",
"all",
"related",
"files",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqzip.py#L80-L103 |
gem/oq-engine | openquake/calculators/reportwriter.py | build_report | def build_report(job_ini, output_dir=None):
"""
Write a `report.csv` file with information about the calculation
without running it
:param job_ini:
full pathname of the job.ini file
:param output_dir:
the directory where the report is written (default the input directory)
"""
calc_id = logs.init()
oq = readinput.get_oqparam(job_ini)
if oq.calculation_mode == 'classical':
oq.calculation_mode = 'preclassical'
oq.ground_motion_fields = False
output_dir = output_dir or os.path.dirname(job_ini)
from openquake.calculators import base # ugly
calc = base.calculators(oq, calc_id)
calc.save_params() # needed to save oqparam
# some taken is care so that the real calculation is not run:
# the goal is to extract information about the source management only
calc.pre_execute()
if oq.calculation_mode == 'preclassical':
calc.execute()
rw = ReportWriter(calc.datastore)
rw.make_report()
report = (os.path.join(output_dir, 'report.rst') if output_dir
else calc.datastore.export_path('report.rst'))
try:
rw.save(report)
except IOError as exc: # permission error
sys.stderr.write(str(exc) + '\n')
readinput.exposure = None # ugly hack
return report | python | def build_report(job_ini, output_dir=None):
calc_id = logs.init()
oq = readinput.get_oqparam(job_ini)
if oq.calculation_mode == 'classical':
oq.calculation_mode = 'preclassical'
oq.ground_motion_fields = False
output_dir = output_dir or os.path.dirname(job_ini)
from openquake.calculators import base
calc = base.calculators(oq, calc_id)
calc.save_params()
calc.pre_execute()
if oq.calculation_mode == 'preclassical':
calc.execute()
rw = ReportWriter(calc.datastore)
rw.make_report()
report = (os.path.join(output_dir, 'report.rst') if output_dir
else calc.datastore.export_path('report.rst'))
try:
rw.save(report)
except IOError as exc:
sys.stderr.write(str(exc) + '\n')
readinput.exposure = None
return report | [
"def",
"build_report",
"(",
"job_ini",
",",
"output_dir",
"=",
"None",
")",
":",
"calc_id",
"=",
"logs",
".",
"init",
"(",
")",
"oq",
"=",
"readinput",
".",
"get_oqparam",
"(",
"job_ini",
")",
"if",
"oq",
".",
"calculation_mode",
"==",
"'classical'",
":",
"oq",
".",
"calculation_mode",
"=",
"'preclassical'",
"oq",
".",
"ground_motion_fields",
"=",
"False",
"output_dir",
"=",
"output_dir",
"or",
"os",
".",
"path",
".",
"dirname",
"(",
"job_ini",
")",
"from",
"openquake",
".",
"calculators",
"import",
"base",
"# ugly",
"calc",
"=",
"base",
".",
"calculators",
"(",
"oq",
",",
"calc_id",
")",
"calc",
".",
"save_params",
"(",
")",
"# needed to save oqparam",
"# some taken is care so that the real calculation is not run:",
"# the goal is to extract information about the source management only",
"calc",
".",
"pre_execute",
"(",
")",
"if",
"oq",
".",
"calculation_mode",
"==",
"'preclassical'",
":",
"calc",
".",
"execute",
"(",
")",
"rw",
"=",
"ReportWriter",
"(",
"calc",
".",
"datastore",
")",
"rw",
".",
"make_report",
"(",
")",
"report",
"=",
"(",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"'report.rst'",
")",
"if",
"output_dir",
"else",
"calc",
".",
"datastore",
".",
"export_path",
"(",
"'report.rst'",
")",
")",
"try",
":",
"rw",
".",
"save",
"(",
"report",
")",
"except",
"IOError",
"as",
"exc",
":",
"# permission error",
"sys",
".",
"stderr",
".",
"write",
"(",
"str",
"(",
"exc",
")",
"+",
"'\\n'",
")",
"readinput",
".",
"exposure",
"=",
"None",
"# ugly hack",
"return",
"report"
] | Write a `report.csv` file with information about the calculation
without running it
:param job_ini:
full pathname of the job.ini file
:param output_dir:
the directory where the report is written (default the input directory) | [
"Write",
"a",
"report",
".",
"csv",
"file",
"with",
"information",
"about",
"the",
"calculation",
"without",
"running",
"it"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/reportwriter.py#L125-L159 |
gem/oq-engine | openquake/calculators/reportwriter.py | ReportWriter.add | def add(self, name, obj=None):
"""Add the view named `name` to the report text"""
if obj:
text = '\n::\n\n' + indent(str(obj))
else:
text = views.view(name, self.dstore)
if text:
title = self.title[name]
line = '-' * len(title)
self.text += '\n'.join(['\n\n' + title, line, text]) | python | def add(self, name, obj=None):
if obj:
text = '\n::\n\n' + indent(str(obj))
else:
text = views.view(name, self.dstore)
if text:
title = self.title[name]
line = '-' * len(title)
self.text += '\n'.join(['\n\n' + title, line, text]) | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"obj",
"=",
"None",
")",
":",
"if",
"obj",
":",
"text",
"=",
"'\\n::\\n\\n'",
"+",
"indent",
"(",
"str",
"(",
"obj",
")",
")",
"else",
":",
"text",
"=",
"views",
".",
"view",
"(",
"name",
",",
"self",
".",
"dstore",
")",
"if",
"text",
":",
"title",
"=",
"self",
".",
"title",
"[",
"name",
"]",
"line",
"=",
"'-'",
"*",
"len",
"(",
"title",
")",
"self",
".",
"text",
"+=",
"'\\n'",
".",
"join",
"(",
"[",
"'\\n\\n'",
"+",
"title",
",",
"line",
",",
"text",
"]",
")"
] | Add the view named `name` to the report text | [
"Add",
"the",
"view",
"named",
"name",
"to",
"the",
"report",
"text"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/reportwriter.py#L74-L83 |
gem/oq-engine | openquake/calculators/reportwriter.py | ReportWriter.make_report | def make_report(self):
"""Build the report and return a restructed text string"""
oq, ds = self.oq, self.dstore
for name in ('params', 'inputs'):
self.add(name)
if 'csm_info' in ds:
self.add('csm_info')
if ds['csm_info'].source_models[0].name != 'scenario':
# required_params_per_trt makes no sense for GMFs from file
self.add('required_params_per_trt')
self.add('rlzs_assoc', ds['csm_info'].get_rlzs_assoc())
if 'csm_info' in ds:
self.add('ruptures_per_trt')
if 'rup_data' in ds:
self.add('ruptures_events')
if oq.calculation_mode in ('event_based_risk',):
self.add('avglosses_data_transfer')
if 'exposure' in oq.inputs:
self.add('exposure_info')
if 'source_info' in ds:
self.add('slow_sources')
self.add('times_by_source_class')
self.add('dupl_sources')
if 'task_info' in ds:
self.add('task_info')
tasks = set(ds['task_info'])
if 'classical' in tasks:
self.add('task_hazard:0')
self.add('task_hazard:-1')
self.add('job_info')
if 'performance_data' in ds:
self.add('performance')
return self.text | python | def make_report(self):
oq, ds = self.oq, self.dstore
for name in ('params', 'inputs'):
self.add(name)
if 'csm_info' in ds:
self.add('csm_info')
if ds['csm_info'].source_models[0].name != 'scenario':
self.add('required_params_per_trt')
self.add('rlzs_assoc', ds['csm_info'].get_rlzs_assoc())
if 'csm_info' in ds:
self.add('ruptures_per_trt')
if 'rup_data' in ds:
self.add('ruptures_events')
if oq.calculation_mode in ('event_based_risk',):
self.add('avglosses_data_transfer')
if 'exposure' in oq.inputs:
self.add('exposure_info')
if 'source_info' in ds:
self.add('slow_sources')
self.add('times_by_source_class')
self.add('dupl_sources')
if 'task_info' in ds:
self.add('task_info')
tasks = set(ds['task_info'])
if 'classical' in tasks:
self.add('task_hazard:0')
self.add('task_hazard:-1')
self.add('job_info')
if 'performance_data' in ds:
self.add('performance')
return self.text | [
"def",
"make_report",
"(",
"self",
")",
":",
"oq",
",",
"ds",
"=",
"self",
".",
"oq",
",",
"self",
".",
"dstore",
"for",
"name",
"in",
"(",
"'params'",
",",
"'inputs'",
")",
":",
"self",
".",
"add",
"(",
"name",
")",
"if",
"'csm_info'",
"in",
"ds",
":",
"self",
".",
"add",
"(",
"'csm_info'",
")",
"if",
"ds",
"[",
"'csm_info'",
"]",
".",
"source_models",
"[",
"0",
"]",
".",
"name",
"!=",
"'scenario'",
":",
"# required_params_per_trt makes no sense for GMFs from file",
"self",
".",
"add",
"(",
"'required_params_per_trt'",
")",
"self",
".",
"add",
"(",
"'rlzs_assoc'",
",",
"ds",
"[",
"'csm_info'",
"]",
".",
"get_rlzs_assoc",
"(",
")",
")",
"if",
"'csm_info'",
"in",
"ds",
":",
"self",
".",
"add",
"(",
"'ruptures_per_trt'",
")",
"if",
"'rup_data'",
"in",
"ds",
":",
"self",
".",
"add",
"(",
"'ruptures_events'",
")",
"if",
"oq",
".",
"calculation_mode",
"in",
"(",
"'event_based_risk'",
",",
")",
":",
"self",
".",
"add",
"(",
"'avglosses_data_transfer'",
")",
"if",
"'exposure'",
"in",
"oq",
".",
"inputs",
":",
"self",
".",
"add",
"(",
"'exposure_info'",
")",
"if",
"'source_info'",
"in",
"ds",
":",
"self",
".",
"add",
"(",
"'slow_sources'",
")",
"self",
".",
"add",
"(",
"'times_by_source_class'",
")",
"self",
".",
"add",
"(",
"'dupl_sources'",
")",
"if",
"'task_info'",
"in",
"ds",
":",
"self",
".",
"add",
"(",
"'task_info'",
")",
"tasks",
"=",
"set",
"(",
"ds",
"[",
"'task_info'",
"]",
")",
"if",
"'classical'",
"in",
"tasks",
":",
"self",
".",
"add",
"(",
"'task_hazard:0'",
")",
"self",
".",
"add",
"(",
"'task_hazard:-1'",
")",
"self",
".",
"add",
"(",
"'job_info'",
")",
"if",
"'performance_data'",
"in",
"ds",
":",
"self",
".",
"add",
"(",
"'performance'",
")",
"return",
"self",
".",
"text"
] | Build the report and return a restructed text string | [
"Build",
"the",
"report",
"and",
"return",
"a",
"restructed",
"text",
"string"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/reportwriter.py#L85-L117 |
gem/oq-engine | openquake/calculators/reportwriter.py | ReportWriter.save | def save(self, fname):
"""Save the report"""
with open(fname, 'wb') as f:
f.write(encode(self.text)) | python | def save(self, fname):
with open(fname, 'wb') as f:
f.write(encode(self.text)) | [
"def",
"save",
"(",
"self",
",",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"encode",
"(",
"self",
".",
"text",
")",
")"
] | Save the report | [
"Save",
"the",
"report"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/reportwriter.py#L119-L122 |
gem/oq-engine | openquake/hazardlib/gsim/bradley_2013.py | convert_to_LHC | def convert_to_LHC(imt):
"""
Converts from GMRotI50 to Larger of two horizontal components using
global equation of:
Boore, D and Kishida, T (2016). Relations between some horizontal-
component ground-motion intensity measures used in practice.
Bulletin of the Seismological Society of America, 107(1), 334-343.
doi:10.1785/0120160250
No standard deviation modification required.
"""
# get period t
if isinstance(imt, SA):
t = imt.period
else:
t = 0.01
T1 = 0.08
T2 = 0.56
T3 = 4.40
T4 = 8.70
R1 = 1.106
R2 = 1.158
R3 = 1.178
R4 = 1.241
R5 = 1.241
Ratio = max(R1,
max(min(R1+(R2-R1)/np.log(T2/T1)*np.log(t/T1),
R2+(R3-R2)/np.log(T3/T2)*np.log(t/T2)),
min(R3+(R4-R3)/np.log(T4/T3)*np.log(t/T3), R5)))
SF = np.log(Ratio)
return SF | python | def convert_to_LHC(imt):
if isinstance(imt, SA):
t = imt.period
else:
t = 0.01
T1 = 0.08
T2 = 0.56
T3 = 4.40
T4 = 8.70
R1 = 1.106
R2 = 1.158
R3 = 1.178
R4 = 1.241
R5 = 1.241
Ratio = max(R1,
max(min(R1+(R2-R1)/np.log(T2/T1)*np.log(t/T1),
R2+(R3-R2)/np.log(T3/T2)*np.log(t/T2)),
min(R3+(R4-R3)/np.log(T4/T3)*np.log(t/T3), R5)))
SF = np.log(Ratio)
return SF | [
"def",
"convert_to_LHC",
"(",
"imt",
")",
":",
"# get period t",
"if",
"isinstance",
"(",
"imt",
",",
"SA",
")",
":",
"t",
"=",
"imt",
".",
"period",
"else",
":",
"t",
"=",
"0.01",
"T1",
"=",
"0.08",
"T2",
"=",
"0.56",
"T3",
"=",
"4.40",
"T4",
"=",
"8.70",
"R1",
"=",
"1.106",
"R2",
"=",
"1.158",
"R3",
"=",
"1.178",
"R4",
"=",
"1.241",
"R5",
"=",
"1.241",
"Ratio",
"=",
"max",
"(",
"R1",
",",
"max",
"(",
"min",
"(",
"R1",
"+",
"(",
"R2",
"-",
"R1",
")",
"/",
"np",
".",
"log",
"(",
"T2",
"/",
"T1",
")",
"*",
"np",
".",
"log",
"(",
"t",
"/",
"T1",
")",
",",
"R2",
"+",
"(",
"R3",
"-",
"R2",
")",
"/",
"np",
".",
"log",
"(",
"T3",
"/",
"T2",
")",
"*",
"np",
".",
"log",
"(",
"t",
"/",
"T2",
")",
")",
",",
"min",
"(",
"R3",
"+",
"(",
"R4",
"-",
"R3",
")",
"/",
"np",
".",
"log",
"(",
"T4",
"/",
"T3",
")",
"*",
"np",
".",
"log",
"(",
"t",
"/",
"T3",
")",
",",
"R5",
")",
")",
")",
"SF",
"=",
"np",
".",
"log",
"(",
"Ratio",
")",
"return",
"SF"
] | Converts from GMRotI50 to Larger of two horizontal components using
global equation of:
Boore, D and Kishida, T (2016). Relations between some horizontal-
component ground-motion intensity measures used in practice.
Bulletin of the Seismological Society of America, 107(1), 334-343.
doi:10.1785/0120160250
No standard deviation modification required. | [
"Converts",
"from",
"GMRotI50",
"to",
"Larger",
"of",
"two",
"horizontal",
"components",
"using",
"global",
"equation",
"of",
":",
"Boore",
"D",
"and",
"Kishida",
"T",
"(",
"2016",
")",
".",
"Relations",
"between",
"some",
"horizontal",
"-",
"component",
"ground",
"-",
"motion",
"intensity",
"measures",
"used",
"in",
"practice",
".",
"Bulletin",
"of",
"the",
"Seismological",
"Society",
"of",
"America",
"107",
"(",
"1",
")",
"334",
"-",
"343",
".",
"doi",
":",
"10",
".",
"1785",
"/",
"0120160250",
"No",
"standard",
"deviation",
"modification",
"required",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013.py#L389-L421 |
gem/oq-engine | openquake/hazardlib/gsim/bradley_2013.py | Bradley2013._get_mean | def _get_mean(self, sites, C, ln_y_ref, exp1, exp2, v1):
"""
Add site effects to an intensity.
Implements eq. 5
"""
# we do not support estimating of basin depth and instead
# rely on it being available (since we require it).
z1pt0 = sites.z1pt0
# we consider random variables being zero since we want
# to find the exact mean value.
eta = epsilon = 0
ln_y = (
# first line of eq. 13b
ln_y_ref + C['phi1'] *
np.log(np.clip(sites.vs30, -np.inf, v1) / 1130)
# second line
+ C['phi2'] * (exp1 - exp2)
* np.log((np.exp(ln_y_ref) + C['phi4']) / C['phi4'])
# third line
+ C['phi5']
* (1.0 - 1.0 / np.cosh(
C['phi6'] * (z1pt0 - C['phi7']).clip(0, np.inf)))
+ C['phi8'] / np.cosh(0.15 * (z1pt0 - 15).clip(0, np.inf))
# fourth line
+ eta + epsilon
)
return ln_y | python | def _get_mean(self, sites, C, ln_y_ref, exp1, exp2, v1):
z1pt0 = sites.z1pt0
eta = epsilon = 0
ln_y = (
ln_y_ref + C['phi1'] *
np.log(np.clip(sites.vs30, -np.inf, v1) / 1130)
+ C['phi2'] * (exp1 - exp2)
* np.log((np.exp(ln_y_ref) + C['phi4']) / C['phi4'])
+ C['phi5']
* (1.0 - 1.0 / np.cosh(
C['phi6'] * (z1pt0 - C['phi7']).clip(0, np.inf)))
+ C['phi8'] / np.cosh(0.15 * (z1pt0 - 15).clip(0, np.inf))
+ eta + epsilon
)
return ln_y | [
"def",
"_get_mean",
"(",
"self",
",",
"sites",
",",
"C",
",",
"ln_y_ref",
",",
"exp1",
",",
"exp2",
",",
"v1",
")",
":",
"# we do not support estimating of basin depth and instead",
"# rely on it being available (since we require it).",
"z1pt0",
"=",
"sites",
".",
"z1pt0",
"# we consider random variables being zero since we want",
"# to find the exact mean value.",
"eta",
"=",
"epsilon",
"=",
"0",
"ln_y",
"=",
"(",
"# first line of eq. 13b",
"ln_y_ref",
"+",
"C",
"[",
"'phi1'",
"]",
"*",
"np",
".",
"log",
"(",
"np",
".",
"clip",
"(",
"sites",
".",
"vs30",
",",
"-",
"np",
".",
"inf",
",",
"v1",
")",
"/",
"1130",
")",
"# second line",
"+",
"C",
"[",
"'phi2'",
"]",
"*",
"(",
"exp1",
"-",
"exp2",
")",
"*",
"np",
".",
"log",
"(",
"(",
"np",
".",
"exp",
"(",
"ln_y_ref",
")",
"+",
"C",
"[",
"'phi4'",
"]",
")",
"/",
"C",
"[",
"'phi4'",
"]",
")",
"# third line",
"+",
"C",
"[",
"'phi5'",
"]",
"*",
"(",
"1.0",
"-",
"1.0",
"/",
"np",
".",
"cosh",
"(",
"C",
"[",
"'phi6'",
"]",
"*",
"(",
"z1pt0",
"-",
"C",
"[",
"'phi7'",
"]",
")",
".",
"clip",
"(",
"0",
",",
"np",
".",
"inf",
")",
")",
")",
"+",
"C",
"[",
"'phi8'",
"]",
"/",
"np",
".",
"cosh",
"(",
"0.15",
"*",
"(",
"z1pt0",
"-",
"15",
")",
".",
"clip",
"(",
"0",
",",
"np",
".",
"inf",
")",
")",
"# fourth line",
"+",
"eta",
"+",
"epsilon",
")",
"return",
"ln_y"
] | Add site effects to an intensity.
Implements eq. 5 | [
"Add",
"site",
"effects",
"to",
"an",
"intensity",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013.py#L107-L137 |
gem/oq-engine | openquake/hazardlib/gsim/bradley_2013.py | Bradley2013._get_v1 | def _get_v1(self, imt):
"""
Calculates Bradley's V1 term. Equation 2 (page 1814) and 6 (page 1816)
based on SA period
"""
if imt == PGA():
v1 = 1800.
else:
T = imt.period
v1a = np.clip((1130 * (T / 0.75)**-0.11), 1130, np.inf)
v1 = np.clip(v1a, -np.inf, 1800.)
return v1 | python | def _get_v1(self, imt):
if imt == PGA():
v1 = 1800.
else:
T = imt.period
v1a = np.clip((1130 * (T / 0.75)**-0.11), 1130, np.inf)
v1 = np.clip(v1a, -np.inf, 1800.)
return v1 | [
"def",
"_get_v1",
"(",
"self",
",",
"imt",
")",
":",
"if",
"imt",
"==",
"PGA",
"(",
")",
":",
"v1",
"=",
"1800.",
"else",
":",
"T",
"=",
"imt",
".",
"period",
"v1a",
"=",
"np",
".",
"clip",
"(",
"(",
"1130",
"*",
"(",
"T",
"/",
"0.75",
")",
"**",
"-",
"0.11",
")",
",",
"1130",
",",
"np",
".",
"inf",
")",
"v1",
"=",
"np",
".",
"clip",
"(",
"v1a",
",",
"-",
"np",
".",
"inf",
",",
"1800.",
")",
"return",
"v1"
] | Calculates Bradley's V1 term. Equation 2 (page 1814) and 6 (page 1816)
based on SA period | [
"Calculates",
"Bradley",
"s",
"V1",
"term",
".",
"Equation",
"2",
"(",
"page",
"1814",
")",
"and",
"6",
"(",
"page",
"1816",
")",
"based",
"on",
"SA",
"period"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013.py#L243-L257 |
gem/oq-engine | openquake/hazardlib/gsim/bradley_2013.py | Bradley2013LHC.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]
# intensity on a reference soil is used for both mean
# and stddev calculations.
ln_y_ref = self._get_ln_y_ref(rup, dists, C)
# exp1 and exp2 are parts of eq. 7
exp1 = np.exp(C['phi3'] * (sites.vs30.clip(-np.inf, 1130) - 360))
exp2 = np.exp(C['phi3'] * (1130 - 360))
# v1 is the period dependent site term. The Vs30 above which, the
# amplification is constant
v1 = self._get_v1(imt)
mean = self._get_mean(sites, C, ln_y_ref, exp1, exp2, v1)
mean += convert_to_LHC(imt)
stddevs = self._get_stddevs(sites, rup, C, stddev_types,
ln_y_ref, exp1, exp2)
return mean, stddevs | python | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
C = self.COEFFS[imt]
ln_y_ref = self._get_ln_y_ref(rup, dists, C)
exp1 = np.exp(C['phi3'] * (sites.vs30.clip(-np.inf, 1130) - 360))
exp2 = np.exp(C['phi3'] * (1130 - 360))
v1 = self._get_v1(imt)
mean = self._get_mean(sites, C, ln_y_ref, exp1, exp2, v1)
mean += convert_to_LHC(imt)
stddevs = self._get_stddevs(sites, rup, C, stddev_types,
ln_y_ref, exp1, exp2)
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",
"]",
"# intensity on a reference soil is used for both mean",
"# and stddev calculations.",
"ln_y_ref",
"=",
"self",
".",
"_get_ln_y_ref",
"(",
"rup",
",",
"dists",
",",
"C",
")",
"# exp1 and exp2 are parts of eq. 7",
"exp1",
"=",
"np",
".",
"exp",
"(",
"C",
"[",
"'phi3'",
"]",
"*",
"(",
"sites",
".",
"vs30",
".",
"clip",
"(",
"-",
"np",
".",
"inf",
",",
"1130",
")",
"-",
"360",
")",
")",
"exp2",
"=",
"np",
".",
"exp",
"(",
"C",
"[",
"'phi3'",
"]",
"*",
"(",
"1130",
"-",
"360",
")",
")",
"# v1 is the period dependent site term. The Vs30 above which, the",
"# amplification is constant",
"v1",
"=",
"self",
".",
"_get_v1",
"(",
"imt",
")",
"mean",
"=",
"self",
".",
"_get_mean",
"(",
"sites",
",",
"C",
",",
"ln_y_ref",
",",
"exp1",
",",
"exp2",
",",
"v1",
")",
"mean",
"+=",
"convert_to_LHC",
"(",
"imt",
")",
"stddevs",
"=",
"self",
".",
"_get_stddevs",
"(",
"sites",
",",
"rup",
",",
"C",
",",
"stddev_types",
",",
"ln_y_ref",
",",
"exp1",
",",
"exp2",
")",
"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/bradley_2013.py#L345-L369 |
gem/oq-engine | openquake/hazardlib/gsim/frankel_1996.py | FrankelEtAl1996MblgAB1987NSHMP2008.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.
:raises ValueError:
if imt is instance of :class:`openquake.hazardlib.imt.SA` with
unsupported period.
"""
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
for stddev_type in stddev_types)
if imt not in self.IMTS_TABLES:
raise ValueError(
'IMT %s not supported in FrankelEtAl1996NSHMP. ' % repr(imt) +
'FrankelEtAl1996NSHMP does not allow interpolation for ' +
'unsupported periods.'
)
mean = self._compute_mean(imt, rup.mag, dists.rhypo.copy())
mean = clip_mean(imt, mean)
stddevs = self._compute_stddevs(imt, dists.rhypo.shape, stddev_types)
return mean, stddevs | python | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
for stddev_type in stddev_types)
if imt not in self.IMTS_TABLES:
raise ValueError(
'IMT %s not supported in FrankelEtAl1996NSHMP. ' % repr(imt) +
'FrankelEtAl1996NSHMP does not allow interpolation for ' +
'unsupported periods.'
)
mean = self._compute_mean(imt, rup.mag, dists.rhypo.copy())
mean = clip_mean(imt, mean)
stddevs = self._compute_stddevs(imt, dists.rhypo.shape, stddev_types)
return mean, stddevs | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"assert",
"all",
"(",
"stddev_type",
"in",
"self",
".",
"DEFINED_FOR_STANDARD_DEVIATION_TYPES",
"for",
"stddev_type",
"in",
"stddev_types",
")",
"if",
"imt",
"not",
"in",
"self",
".",
"IMTS_TABLES",
":",
"raise",
"ValueError",
"(",
"'IMT %s not supported in FrankelEtAl1996NSHMP. '",
"%",
"repr",
"(",
"imt",
")",
"+",
"'FrankelEtAl1996NSHMP does not allow interpolation for '",
"+",
"'unsupported periods.'",
")",
"mean",
"=",
"self",
".",
"_compute_mean",
"(",
"imt",
",",
"rup",
".",
"mag",
",",
"dists",
".",
"rhypo",
".",
"copy",
"(",
")",
")",
"mean",
"=",
"clip_mean",
"(",
"imt",
",",
"mean",
")",
"stddevs",
"=",
"self",
".",
"_compute_stddevs",
"(",
"imt",
",",
"dists",
".",
"rhypo",
".",
"shape",
",",
"stddev_types",
")",
"return",
"mean",
",",
"stddevs"
] | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
:raises ValueError:
if imt is instance of :class:`openquake.hazardlib.imt.SA` with
unsupported period. | [
"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/frankel_1996.py#L102-L127 |
gem/oq-engine | openquake/hazardlib/gsim/frankel_1996.py | FrankelEtAl1996MblgAB1987NSHMP2008._compute_mean | def _compute_mean(self, imt, mag, rhypo):
"""
Compute mean value from lookup table.
Lookup table defines log10(IMT) (in g) for combinations of Mw and
log10(rhypo) values. ``mag`` is therefore converted from Mblg to Mw
using Atkinson and Boore 1987 conversion equation. Mean value is
finally converted from base 10 to base e.
"""
mag = np.zeros_like(rhypo) + self._convert_magnitude(mag)
# to avoid run time warning in case rhypo is zero set minimum distance
# to 10, which is anyhow the minimum distance allowed by the tables
rhypo[rhypo < 10] = 10
rhypo = np.log10(rhypo)
# create lookup table and interpolate it at magnitude/distance values
table = RectBivariateSpline(
self.MAGS, self.DISTS, self.IMTS_TABLES[imt].T
)
mean = table.ev(mag, rhypo)
# convert mean from base 10 to base e
return mean * np.log(10) | python | def _compute_mean(self, imt, mag, rhypo):
mag = np.zeros_like(rhypo) + self._convert_magnitude(mag)
rhypo[rhypo < 10] = 10
rhypo = np.log10(rhypo)
table = RectBivariateSpline(
self.MAGS, self.DISTS, self.IMTS_TABLES[imt].T
)
mean = table.ev(mag, rhypo)
return mean * np.log(10) | [
"def",
"_compute_mean",
"(",
"self",
",",
"imt",
",",
"mag",
",",
"rhypo",
")",
":",
"mag",
"=",
"np",
".",
"zeros_like",
"(",
"rhypo",
")",
"+",
"self",
".",
"_convert_magnitude",
"(",
"mag",
")",
"# to avoid run time warning in case rhypo is zero set minimum distance",
"# to 10, which is anyhow the minimum distance allowed by the tables",
"rhypo",
"[",
"rhypo",
"<",
"10",
"]",
"=",
"10",
"rhypo",
"=",
"np",
".",
"log10",
"(",
"rhypo",
")",
"# create lookup table and interpolate it at magnitude/distance values",
"table",
"=",
"RectBivariateSpline",
"(",
"self",
".",
"MAGS",
",",
"self",
".",
"DISTS",
",",
"self",
".",
"IMTS_TABLES",
"[",
"imt",
"]",
".",
"T",
")",
"mean",
"=",
"table",
".",
"ev",
"(",
"mag",
",",
"rhypo",
")",
"# convert mean from base 10 to base e",
"return",
"mean",
"*",
"np",
".",
"log",
"(",
"10",
")"
] | Compute mean value from lookup table.
Lookup table defines log10(IMT) (in g) for combinations of Mw and
log10(rhypo) values. ``mag`` is therefore converted from Mblg to Mw
using Atkinson and Boore 1987 conversion equation. Mean value is
finally converted from base 10 to base e. | [
"Compute",
"mean",
"value",
"from",
"lookup",
"table",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/frankel_1996.py#L129-L152 |
gem/oq-engine | openquake/hmtk/plotting/seismicity/occurrence/recurrence_plot.py | _get_recurrence_model | def _get_recurrence_model(input_model):
"""
Returns the annual and cumulative recurrence rates predicted by the
recurrence model
"""
if not isinstance(input_model, (TruncatedGRMFD,
EvenlyDiscretizedMFD,
YoungsCoppersmith1985MFD)):
raise ValueError('Recurrence model not recognised')
# Get model annual occurrence rates
annual_rates = input_model.get_annual_occurrence_rates()
annual_rates = np.array([[val[0], val[1]] for val in annual_rates])
# Get cumulative rates
cumulative_rates = np.array([np.sum(annual_rates[iloc:, 1])
for iloc in range(0, len(annual_rates), 1)])
return annual_rates, cumulative_rates | python | def _get_recurrence_model(input_model):
if not isinstance(input_model, (TruncatedGRMFD,
EvenlyDiscretizedMFD,
YoungsCoppersmith1985MFD)):
raise ValueError('Recurrence model not recognised')
annual_rates = input_model.get_annual_occurrence_rates()
annual_rates = np.array([[val[0], val[1]] for val in annual_rates])
cumulative_rates = np.array([np.sum(annual_rates[iloc:, 1])
for iloc in range(0, len(annual_rates), 1)])
return annual_rates, cumulative_rates | [
"def",
"_get_recurrence_model",
"(",
"input_model",
")",
":",
"if",
"not",
"isinstance",
"(",
"input_model",
",",
"(",
"TruncatedGRMFD",
",",
"EvenlyDiscretizedMFD",
",",
"YoungsCoppersmith1985MFD",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Recurrence model not recognised'",
")",
"# Get model annual occurrence rates",
"annual_rates",
"=",
"input_model",
".",
"get_annual_occurrence_rates",
"(",
")",
"annual_rates",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"val",
"[",
"0",
"]",
",",
"val",
"[",
"1",
"]",
"]",
"for",
"val",
"in",
"annual_rates",
"]",
")",
"# Get cumulative rates",
"cumulative_rates",
"=",
"np",
".",
"array",
"(",
"[",
"np",
".",
"sum",
"(",
"annual_rates",
"[",
"iloc",
":",
",",
"1",
"]",
")",
"for",
"iloc",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"annual_rates",
")",
",",
"1",
")",
"]",
")",
"return",
"annual_rates",
",",
"cumulative_rates"
] | Returns the annual and cumulative recurrence rates predicted by the
recurrence model | [
"Returns",
"the",
"annual",
"and",
"cumulative",
"recurrence",
"rates",
"predicted",
"by",
"the",
"recurrence",
"model"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/occurrence/recurrence_plot.py#L62-L77 |
gem/oq-engine | openquake/hmtk/plotting/seismicity/occurrence/recurrence_plot.py | _check_completeness_table | def _check_completeness_table(completeness, catalogue):
"""
Generates the completeness table according to different instances
"""
if isinstance(completeness, np.ndarray) and np.shape(completeness)[1] == 2:
return completeness
elif isinstance(completeness, float):
return np.array([[float(np.min(catalogue.data['year'])),
completeness]])
elif completeness is None:
return np.array([[float(np.min(catalogue.data['year'])),
np.min(catalogue.data['magnitude'])]])
else:
raise ValueError('Completeness representation not recognised') | python | def _check_completeness_table(completeness, catalogue):
if isinstance(completeness, np.ndarray) and np.shape(completeness)[1] == 2:
return completeness
elif isinstance(completeness, float):
return np.array([[float(np.min(catalogue.data['year'])),
completeness]])
elif completeness is None:
return np.array([[float(np.min(catalogue.data['year'])),
np.min(catalogue.data['magnitude'])]])
else:
raise ValueError('Completeness representation not recognised') | [
"def",
"_check_completeness_table",
"(",
"completeness",
",",
"catalogue",
")",
":",
"if",
"isinstance",
"(",
"completeness",
",",
"np",
".",
"ndarray",
")",
"and",
"np",
".",
"shape",
"(",
"completeness",
")",
"[",
"1",
"]",
"==",
"2",
":",
"return",
"completeness",
"elif",
"isinstance",
"(",
"completeness",
",",
"float",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"float",
"(",
"np",
".",
"min",
"(",
"catalogue",
".",
"data",
"[",
"'year'",
"]",
")",
")",
",",
"completeness",
"]",
"]",
")",
"elif",
"completeness",
"is",
"None",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"float",
"(",
"np",
".",
"min",
"(",
"catalogue",
".",
"data",
"[",
"'year'",
"]",
")",
")",
",",
"np",
".",
"min",
"(",
"catalogue",
".",
"data",
"[",
"'magnitude'",
"]",
")",
"]",
"]",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Completeness representation not recognised'",
")"
] | Generates the completeness table according to different instances | [
"Generates",
"the",
"completeness",
"table",
"according",
"to",
"different",
"instances"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/occurrence/recurrence_plot.py#L80-L93 |
gem/oq-engine | openquake/hmtk/plotting/seismicity/occurrence/recurrence_plot.py | plot_recurrence_model | def plot_recurrence_model(
input_model, catalogue, completeness, dmag=0.1, filename=None,
figure_size=(8, 6), filetype='png', dpi=300, ax=None):
"""
Plot a calculated recurrence model over an observed catalogue, adjusted for
time-varying completeness
"""
annual_rates, cumulative_rates = _get_recurrence_model(input_model)
# Get observed annual recurrence
if not catalogue.end_year:
catalogue.update_end_year()
cent_mag, t_per, n_obs = get_completeness_counts(catalogue,
completeness,
dmag)
obs_rates = n_obs / t_per
cum_obs_rates = np.array([np.sum(obs_rates[i:])
for i in range(len(obs_rates))])
if ax is None:
fig, ax = plt.subplots(figsize=figure_size)
else:
fig = ax.get_figure()
ax.semilogy(cent_mag, obs_rates, 'bo')
ax.semilogy(annual_rates[:, 0], annual_rates[:, 1], 'b-')
ax.semilogy(cent_mag, cum_obs_rates, 'rs')
ax.semilogy(annual_rates[:, 0], cumulative_rates, 'r-')
ax.grid(which='both')
ax.set_xlabel('Magnitude')
ax.set_ylabel('Annual Rate')
ax.legend(['Observed Incremental Rate',
'Model Incremental Rate',
'Observed Cumulative Rate',
'Model Cumulative Rate'])
ax.tick_params(labelsize=12)
_save_image(fig, filename, filetype, dpi) | python | def plot_recurrence_model(
input_model, catalogue, completeness, dmag=0.1, filename=None,
figure_size=(8, 6), filetype='png', dpi=300, ax=None):
annual_rates, cumulative_rates = _get_recurrence_model(input_model)
if not catalogue.end_year:
catalogue.update_end_year()
cent_mag, t_per, n_obs = get_completeness_counts(catalogue,
completeness,
dmag)
obs_rates = n_obs / t_per
cum_obs_rates = np.array([np.sum(obs_rates[i:])
for i in range(len(obs_rates))])
if ax is None:
fig, ax = plt.subplots(figsize=figure_size)
else:
fig = ax.get_figure()
ax.semilogy(cent_mag, obs_rates, 'bo')
ax.semilogy(annual_rates[:, 0], annual_rates[:, 1], 'b-')
ax.semilogy(cent_mag, cum_obs_rates, 'rs')
ax.semilogy(annual_rates[:, 0], cumulative_rates, 'r-')
ax.grid(which='both')
ax.set_xlabel('Magnitude')
ax.set_ylabel('Annual Rate')
ax.legend(['Observed Incremental Rate',
'Model Incremental Rate',
'Observed Cumulative Rate',
'Model Cumulative Rate'])
ax.tick_params(labelsize=12)
_save_image(fig, filename, filetype, dpi) | [
"def",
"plot_recurrence_model",
"(",
"input_model",
",",
"catalogue",
",",
"completeness",
",",
"dmag",
"=",
"0.1",
",",
"filename",
"=",
"None",
",",
"figure_size",
"=",
"(",
"8",
",",
"6",
")",
",",
"filetype",
"=",
"'png'",
",",
"dpi",
"=",
"300",
",",
"ax",
"=",
"None",
")",
":",
"annual_rates",
",",
"cumulative_rates",
"=",
"_get_recurrence_model",
"(",
"input_model",
")",
"# Get observed annual recurrence",
"if",
"not",
"catalogue",
".",
"end_year",
":",
"catalogue",
".",
"update_end_year",
"(",
")",
"cent_mag",
",",
"t_per",
",",
"n_obs",
"=",
"get_completeness_counts",
"(",
"catalogue",
",",
"completeness",
",",
"dmag",
")",
"obs_rates",
"=",
"n_obs",
"/",
"t_per",
"cum_obs_rates",
"=",
"np",
".",
"array",
"(",
"[",
"np",
".",
"sum",
"(",
"obs_rates",
"[",
"i",
":",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"obs_rates",
")",
")",
"]",
")",
"if",
"ax",
"is",
"None",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"figsize",
"=",
"figure_size",
")",
"else",
":",
"fig",
"=",
"ax",
".",
"get_figure",
"(",
")",
"ax",
".",
"semilogy",
"(",
"cent_mag",
",",
"obs_rates",
",",
"'bo'",
")",
"ax",
".",
"semilogy",
"(",
"annual_rates",
"[",
":",
",",
"0",
"]",
",",
"annual_rates",
"[",
":",
",",
"1",
"]",
",",
"'b-'",
")",
"ax",
".",
"semilogy",
"(",
"cent_mag",
",",
"cum_obs_rates",
",",
"'rs'",
")",
"ax",
".",
"semilogy",
"(",
"annual_rates",
"[",
":",
",",
"0",
"]",
",",
"cumulative_rates",
",",
"'r-'",
")",
"ax",
".",
"grid",
"(",
"which",
"=",
"'both'",
")",
"ax",
".",
"set_xlabel",
"(",
"'Magnitude'",
")",
"ax",
".",
"set_ylabel",
"(",
"'Annual Rate'",
")",
"ax",
".",
"legend",
"(",
"[",
"'Observed Incremental Rate'",
",",
"'Model Incremental Rate'",
",",
"'Observed Cumulative Rate'",
",",
"'Model Cumulative Rate'",
"]",
")",
"ax",
".",
"tick_params",
"(",
"labelsize",
"=",
"12",
")",
"_save_image",
"(",
"fig",
",",
"filename",
",",
"filetype",
",",
"dpi",
")"
] | Plot a calculated recurrence model over an observed catalogue, adjusted for
time-varying completeness | [
"Plot",
"a",
"calculated",
"recurrence",
"model",
"over",
"an",
"observed",
"catalogue",
"adjusted",
"for",
"time",
"-",
"varying",
"completeness"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/occurrence/recurrence_plot.py#L96-L132 |
gem/oq-engine | openquake/hmtk/plotting/seismicity/occurrence/recurrence_plot.py | plot_trunc_gr_model | def plot_trunc_gr_model(
aval, bval, min_mag, max_mag, dmag,
catalogue=None, completeness=None, filename=None,
figure_size=(8, 6), filetype='png', dpi=300, ax=None):
"""
Plots a Gutenberg-Richter model
"""
input_model = TruncatedGRMFD(min_mag, max_mag, dmag, aval, bval)
if not catalogue:
# Plot only the modelled recurrence
annual_rates, cumulative_rates = _get_recurrence_model(input_model)
if ax is None:
fig, ax = plt.subplots(figsize=figure_size)
else:
fig = ax.get_figure()
ax.semilogy(annual_rates[:, 0], annual_rates[:, 1], 'b-')
ax.semilogy(annual_rates[:, 0], cumulative_rates, 'r-')
ax.xlabel('Magnitude')
ax.set_ylabel('Annual Rate')
ax.set_legend(['Incremental Rate', 'Cumulative Rate'])
_save_image(fig, filename, filetype, dpi)
else:
completeness = _check_completeness_table(completeness, catalogue)
plot_recurrence_model(
input_model, catalogue, completeness, dmag, filename=filename,
figure_size=figure_size, filetype=filetype, dpi=dpi, ax=ax) | python | def plot_trunc_gr_model(
aval, bval, min_mag, max_mag, dmag,
catalogue=None, completeness=None, filename=None,
figure_size=(8, 6), filetype='png', dpi=300, ax=None):
input_model = TruncatedGRMFD(min_mag, max_mag, dmag, aval, bval)
if not catalogue:
annual_rates, cumulative_rates = _get_recurrence_model(input_model)
if ax is None:
fig, ax = plt.subplots(figsize=figure_size)
else:
fig = ax.get_figure()
ax.semilogy(annual_rates[:, 0], annual_rates[:, 1], 'b-')
ax.semilogy(annual_rates[:, 0], cumulative_rates, 'r-')
ax.xlabel('Magnitude')
ax.set_ylabel('Annual Rate')
ax.set_legend(['Incremental Rate', 'Cumulative Rate'])
_save_image(fig, filename, filetype, dpi)
else:
completeness = _check_completeness_table(completeness, catalogue)
plot_recurrence_model(
input_model, catalogue, completeness, dmag, filename=filename,
figure_size=figure_size, filetype=filetype, dpi=dpi, ax=ax) | [
"def",
"plot_trunc_gr_model",
"(",
"aval",
",",
"bval",
",",
"min_mag",
",",
"max_mag",
",",
"dmag",
",",
"catalogue",
"=",
"None",
",",
"completeness",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"figure_size",
"=",
"(",
"8",
",",
"6",
")",
",",
"filetype",
"=",
"'png'",
",",
"dpi",
"=",
"300",
",",
"ax",
"=",
"None",
")",
":",
"input_model",
"=",
"TruncatedGRMFD",
"(",
"min_mag",
",",
"max_mag",
",",
"dmag",
",",
"aval",
",",
"bval",
")",
"if",
"not",
"catalogue",
":",
"# Plot only the modelled recurrence",
"annual_rates",
",",
"cumulative_rates",
"=",
"_get_recurrence_model",
"(",
"input_model",
")",
"if",
"ax",
"is",
"None",
":",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"figsize",
"=",
"figure_size",
")",
"else",
":",
"fig",
"=",
"ax",
".",
"get_figure",
"(",
")",
"ax",
".",
"semilogy",
"(",
"annual_rates",
"[",
":",
",",
"0",
"]",
",",
"annual_rates",
"[",
":",
",",
"1",
"]",
",",
"'b-'",
")",
"ax",
".",
"semilogy",
"(",
"annual_rates",
"[",
":",
",",
"0",
"]",
",",
"cumulative_rates",
",",
"'r-'",
")",
"ax",
".",
"xlabel",
"(",
"'Magnitude'",
")",
"ax",
".",
"set_ylabel",
"(",
"'Annual Rate'",
")",
"ax",
".",
"set_legend",
"(",
"[",
"'Incremental Rate'",
",",
"'Cumulative Rate'",
"]",
")",
"_save_image",
"(",
"fig",
",",
"filename",
",",
"filetype",
",",
"dpi",
")",
"else",
":",
"completeness",
"=",
"_check_completeness_table",
"(",
"completeness",
",",
"catalogue",
")",
"plot_recurrence_model",
"(",
"input_model",
",",
"catalogue",
",",
"completeness",
",",
"dmag",
",",
"filename",
"=",
"filename",
",",
"figure_size",
"=",
"figure_size",
",",
"filetype",
"=",
"filetype",
",",
"dpi",
"=",
"dpi",
",",
"ax",
"=",
"ax",
")"
] | Plots a Gutenberg-Richter model | [
"Plots",
"a",
"Gutenberg",
"-",
"Richter",
"model"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/occurrence/recurrence_plot.py#L135-L163 |
gem/oq-engine | openquake/hazardlib/nrml.py | get_tag_version | def get_tag_version(nrml_node):
"""
Extract from a node of kind NRML the tag and the version. For instance
from '{http://openquake.org/xmlns/nrml/0.4}fragilityModel' one gets
the pair ('fragilityModel', 'nrml/0.4').
"""
version, tag = re.search(r'(nrml/[\d\.]+)\}(\w+)', nrml_node.tag).groups()
return tag, version | python | def get_tag_version(nrml_node):
version, tag = re.search(r'(nrml/[\d\.]+)\}(\w+)', nrml_node.tag).groups()
return tag, version | [
"def",
"get_tag_version",
"(",
"nrml_node",
")",
":",
"version",
",",
"tag",
"=",
"re",
".",
"search",
"(",
"r'(nrml/[\\d\\.]+)\\}(\\w+)'",
",",
"nrml_node",
".",
"tag",
")",
".",
"groups",
"(",
")",
"return",
"tag",
",",
"version"
] | Extract from a node of kind NRML the tag and the version. For instance
from '{http://openquake.org/xmlns/nrml/0.4}fragilityModel' one gets
the pair ('fragilityModel', 'nrml/0.4'). | [
"Extract",
"from",
"a",
"node",
"of",
"kind",
"NRML",
"the",
"tag",
"and",
"the",
"version",
".",
"For",
"instance",
"from",
"{",
"http",
":",
"//",
"openquake",
".",
"org",
"/",
"xmlns",
"/",
"nrml",
"/",
"0",
".",
"4",
"}",
"fragilityModel",
"one",
"gets",
"the",
"pair",
"(",
"fragilityModel",
"nrml",
"/",
"0",
".",
"4",
")",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/nrml.py#L151-L158 |
gem/oq-engine | openquake/hazardlib/nrml.py | to_python | def to_python(fname, *args):
"""
Parse a NRML file and return an associated Python object. It works by
calling nrml.read() and node_to_obj() in sequence.
"""
[node] = read(fname)
return node_to_obj(node, fname, *args) | python | def to_python(fname, *args):
[node] = read(fname)
return node_to_obj(node, fname, *args) | [
"def",
"to_python",
"(",
"fname",
",",
"*",
"args",
")",
":",
"[",
"node",
"]",
"=",
"read",
"(",
"fname",
")",
"return",
"node_to_obj",
"(",
"node",
",",
"fname",
",",
"*",
"args",
")"
] | Parse a NRML file and return an associated Python object. It works by
calling nrml.read() and node_to_obj() in sequence. | [
"Parse",
"a",
"NRML",
"file",
"and",
"return",
"an",
"associated",
"Python",
"object",
".",
"It",
"works",
"by",
"calling",
"nrml",
".",
"read",
"()",
"and",
"node_to_obj",
"()",
"in",
"sequence",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/nrml.py#L161-L167 |
gem/oq-engine | openquake/hazardlib/nrml.py | read_source_models | def read_source_models(fnames, converter, monitor):
"""
:param fnames:
list of source model files
:param converter:
a SourceConverter instance
:param monitor:
a :class:`openquake.performance.Monitor` instance
:yields:
SourceModel instances
"""
for fname in fnames:
if fname.endswith(('.xml', '.nrml')):
sm = to_python(fname, converter)
elif fname.endswith('.hdf5'):
sm = sourceconverter.to_python(fname, converter)
else:
raise ValueError('Unrecognized extension in %s' % fname)
sm.fname = fname
yield sm | python | def read_source_models(fnames, converter, monitor):
for fname in fnames:
if fname.endswith(('.xml', '.nrml')):
sm = to_python(fname, converter)
elif fname.endswith('.hdf5'):
sm = sourceconverter.to_python(fname, converter)
else:
raise ValueError('Unrecognized extension in %s' % fname)
sm.fname = fname
yield sm | [
"def",
"read_source_models",
"(",
"fnames",
",",
"converter",
",",
"monitor",
")",
":",
"for",
"fname",
"in",
"fnames",
":",
"if",
"fname",
".",
"endswith",
"(",
"(",
"'.xml'",
",",
"'.nrml'",
")",
")",
":",
"sm",
"=",
"to_python",
"(",
"fname",
",",
"converter",
")",
"elif",
"fname",
".",
"endswith",
"(",
"'.hdf5'",
")",
":",
"sm",
"=",
"sourceconverter",
".",
"to_python",
"(",
"fname",
",",
"converter",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unrecognized extension in %s'",
"%",
"fname",
")",
"sm",
".",
"fname",
"=",
"fname",
"yield",
"sm"
] | :param fnames:
list of source model files
:param converter:
a SourceConverter instance
:param monitor:
a :class:`openquake.performance.Monitor` instance
:yields:
SourceModel instances | [
":",
"param",
"fnames",
":",
"list",
"of",
"source",
"model",
"files",
":",
"param",
"converter",
":",
"a",
"SourceConverter",
"instance",
":",
"param",
"monitor",
":",
"a",
":",
"class",
":",
"openquake",
".",
"performance",
".",
"Monitor",
"instance",
":",
"yields",
":",
"SourceModel",
"instances"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/nrml.py#L307-L326 |
gem/oq-engine | openquake/hazardlib/nrml.py | read | def read(source, chatty=True, stop=None):
"""
Convert a NRML file into a validated Node object. Keeps
the entire tree in memory.
:param source:
a file name or file object open for reading
"""
vparser = ValidatingXmlParser(validators, stop)
nrml = vparser.parse_file(source)
if striptag(nrml.tag) != 'nrml':
raise ValueError('%s: expected a node of kind nrml, got %s' %
(source, nrml.tag))
# extract the XML namespace URL ('http://openquake.org/xmlns/nrml/0.5')
xmlns = nrml.tag.split('}')[0][1:]
if xmlns != NRML05 and chatty:
# for the moment NRML04 is still supported, so we hide the warning
logging.debug('%s is at an outdated version: %s', source, xmlns)
nrml['xmlns'] = xmlns
nrml['xmlns:gml'] = GML_NAMESPACE
return nrml | python | def read(source, chatty=True, stop=None):
vparser = ValidatingXmlParser(validators, stop)
nrml = vparser.parse_file(source)
if striptag(nrml.tag) != 'nrml':
raise ValueError('%s: expected a node of kind nrml, got %s' %
(source, nrml.tag))
xmlns = nrml.tag.split('}')[0][1:]
if xmlns != NRML05 and chatty:
logging.debug('%s is at an outdated version: %s', source, xmlns)
nrml['xmlns'] = xmlns
nrml['xmlns:gml'] = GML_NAMESPACE
return nrml | [
"def",
"read",
"(",
"source",
",",
"chatty",
"=",
"True",
",",
"stop",
"=",
"None",
")",
":",
"vparser",
"=",
"ValidatingXmlParser",
"(",
"validators",
",",
"stop",
")",
"nrml",
"=",
"vparser",
".",
"parse_file",
"(",
"source",
")",
"if",
"striptag",
"(",
"nrml",
".",
"tag",
")",
"!=",
"'nrml'",
":",
"raise",
"ValueError",
"(",
"'%s: expected a node of kind nrml, got %s'",
"%",
"(",
"source",
",",
"nrml",
".",
"tag",
")",
")",
"# extract the XML namespace URL ('http://openquake.org/xmlns/nrml/0.5')",
"xmlns",
"=",
"nrml",
".",
"tag",
".",
"split",
"(",
"'}'",
")",
"[",
"0",
"]",
"[",
"1",
":",
"]",
"if",
"xmlns",
"!=",
"NRML05",
"and",
"chatty",
":",
"# for the moment NRML04 is still supported, so we hide the warning",
"logging",
".",
"debug",
"(",
"'%s is at an outdated version: %s'",
",",
"source",
",",
"xmlns",
")",
"nrml",
"[",
"'xmlns'",
"]",
"=",
"xmlns",
"nrml",
"[",
"'xmlns:gml'",
"]",
"=",
"GML_NAMESPACE",
"return",
"nrml"
] | Convert a NRML file into a validated Node object. Keeps
the entire tree in memory.
:param source:
a file name or file object open for reading | [
"Convert",
"a",
"NRML",
"file",
"into",
"a",
"validated",
"Node",
"object",
".",
"Keeps",
"the",
"entire",
"tree",
"in",
"memory",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/nrml.py#L329-L349 |
gem/oq-engine | openquake/hazardlib/nrml.py | write | def write(nodes, output=sys.stdout, fmt='%.7E', gml=True, xmlns=None):
"""
Convert nodes into a NRML file. output must be a file
object open in write mode. If you want to perform a
consistency check, open it in read-write mode, then it will
be read after creation and validated.
:params nodes: an iterable over Node objects
:params output: a file-like object in write or read-write mode
:param fmt: format used for writing the floats (default '%.7E')
:param gml: add the http://www.opengis.net/gml namespace
:param xmlns: NRML namespace like http://openquake.org/xmlns/nrml/0.4
"""
root = Node('nrml', nodes=nodes)
namespaces = {xmlns or NRML05: ''}
if gml:
namespaces[GML_NAMESPACE] = 'gml:'
with floatformat(fmt):
node_to_xml(root, output, namespaces)
if hasattr(output, 'mode') and '+' in output.mode: # read-write mode
output.seek(0)
read(output) | python | def write(nodes, output=sys.stdout, fmt='%.7E', gml=True, xmlns=None):
root = Node('nrml', nodes=nodes)
namespaces = {xmlns or NRML05: ''}
if gml:
namespaces[GML_NAMESPACE] = 'gml:'
with floatformat(fmt):
node_to_xml(root, output, namespaces)
if hasattr(output, 'mode') and '+' in output.mode:
output.seek(0)
read(output) | [
"def",
"write",
"(",
"nodes",
",",
"output",
"=",
"sys",
".",
"stdout",
",",
"fmt",
"=",
"'%.7E'",
",",
"gml",
"=",
"True",
",",
"xmlns",
"=",
"None",
")",
":",
"root",
"=",
"Node",
"(",
"'nrml'",
",",
"nodes",
"=",
"nodes",
")",
"namespaces",
"=",
"{",
"xmlns",
"or",
"NRML05",
":",
"''",
"}",
"if",
"gml",
":",
"namespaces",
"[",
"GML_NAMESPACE",
"]",
"=",
"'gml:'",
"with",
"floatformat",
"(",
"fmt",
")",
":",
"node_to_xml",
"(",
"root",
",",
"output",
",",
"namespaces",
")",
"if",
"hasattr",
"(",
"output",
",",
"'mode'",
")",
"and",
"'+'",
"in",
"output",
".",
"mode",
":",
"# read-write mode",
"output",
".",
"seek",
"(",
"0",
")",
"read",
"(",
"output",
")"
] | Convert nodes into a NRML file. output must be a file
object open in write mode. If you want to perform a
consistency check, open it in read-write mode, then it will
be read after creation and validated.
:params nodes: an iterable over Node objects
:params output: a file-like object in write or read-write mode
:param fmt: format used for writing the floats (default '%.7E')
:param gml: add the http://www.opengis.net/gml namespace
:param xmlns: NRML namespace like http://openquake.org/xmlns/nrml/0.4 | [
"Convert",
"nodes",
"into",
"a",
"NRML",
"file",
".",
"output",
"must",
"be",
"a",
"file",
"object",
"open",
"in",
"write",
"mode",
".",
"If",
"you",
"want",
"to",
"perform",
"a",
"consistency",
"check",
"open",
"it",
"in",
"read",
"-",
"write",
"mode",
"then",
"it",
"will",
"be",
"read",
"after",
"creation",
"and",
"validated",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/nrml.py#L352-L373 |
gem/oq-engine | openquake/hazardlib/nrml.py | to_string | def to_string(node):
"""
Convert a node into a string in NRML format
"""
with io.BytesIO() as f:
write([node], f)
return f.getvalue().decode('utf-8') | python | def to_string(node):
with io.BytesIO() as f:
write([node], f)
return f.getvalue().decode('utf-8') | [
"def",
"to_string",
"(",
"node",
")",
":",
"with",
"io",
".",
"BytesIO",
"(",
")",
"as",
"f",
":",
"write",
"(",
"[",
"node",
"]",
",",
"f",
")",
"return",
"f",
".",
"getvalue",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")"
] | Convert a node into a string in NRML format | [
"Convert",
"a",
"node",
"into",
"a",
"string",
"in",
"NRML",
"format"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/nrml.py#L376-L382 |
gem/oq-engine | openquake/hazardlib/gsim/derras_2014.py | DerrasEtAl2014.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.
"""
C = self.COEFFS[imt]
# Get the mean
mean = self.get_mean(C, rup, sites, dists)
if imt.name == "PGV":
# Convert from log10 m/s to ln cm/s
mean = np.log((10.0 ** mean) * 100.)
else:
# convert from log10 m/s/s to ln g
mean = np.log((10.0 ** mean) / g)
# Get the standard deviations
stddevs = self.get_stddevs(C, mean.shape, stddev_types)
return mean, stddevs | python | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
C = self.COEFFS[imt]
mean = self.get_mean(C, rup, sites, dists)
if imt.name == "PGV":
mean = np.log((10.0 ** mean) * 100.)
else:
mean = np.log((10.0 ** mean) / g)
stddevs = self.get_stddevs(C, mean.shape, stddev_types)
return mean, stddevs | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"C",
"=",
"self",
".",
"COEFFS",
"[",
"imt",
"]",
"# Get the mean",
"mean",
"=",
"self",
".",
"get_mean",
"(",
"C",
",",
"rup",
",",
"sites",
",",
"dists",
")",
"if",
"imt",
".",
"name",
"==",
"\"PGV\"",
":",
"# Convert from log10 m/s to ln cm/s",
"mean",
"=",
"np",
".",
"log",
"(",
"(",
"10.0",
"**",
"mean",
")",
"*",
"100.",
")",
"else",
":",
"# convert from log10 m/s/s to ln g",
"mean",
"=",
"np",
".",
"log",
"(",
"(",
"10.0",
"**",
"mean",
")",
"/",
"g",
")",
"# Get the standard deviations",
"stddevs",
"=",
"self",
".",
"get_stddevs",
"(",
"C",
",",
"mean",
".",
"shape",
",",
"stddev_types",
")",
"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/derras_2014.py#L75-L93 |
gem/oq-engine | openquake/hazardlib/gsim/derras_2014.py | DerrasEtAl2014.get_mean | def get_mean(self, C, rup, sites, dists):
"""
Returns the mean ground motion in terms of log10 m/s/s, implementing
equation 2 (page 502)
"""
# W2 needs to be a 1 by 5 matrix (not a vector
w_2 = np.array([
[C["W_21"], C["W_22"], C["W_23"], C["W_24"], C["W_25"]]
])
# Gets the style of faulting dummy variable
sof = self._get_sof_dummy_variable(rup.rake)
# Get the normalised coefficients
p_n = self.get_pn(rup, sites, dists, sof)
mean = np.zeros_like(dists.rjb)
# Need to loop over sites - maybe this can be improved in future?
# ndenumerate is used to allow for application to 2-D arrays
for idx, rval in np.ndenumerate(p_n[0]):
# Place normalised coefficients into a single array
p_n_i = np.array([rval, p_n[1], p_n[2][idx], p_n[3], p_n[4]])
# Executes the main ANN model
mean_i = np.dot(w_2, np.tanh(np.dot(self.W_1, p_n_i) + self.B_1))
mean[idx] = (0.5 * (mean_i + C["B_2"] + 1.0) *
(C["tmax"] - C["tmin"])) + C["tmin"]
return mean | python | def get_mean(self, C, rup, sites, dists):
w_2 = np.array([
[C["W_21"], C["W_22"], C["W_23"], C["W_24"], C["W_25"]]
])
sof = self._get_sof_dummy_variable(rup.rake)
p_n = self.get_pn(rup, sites, dists, sof)
mean = np.zeros_like(dists.rjb)
for idx, rval in np.ndenumerate(p_n[0]):
p_n_i = np.array([rval, p_n[1], p_n[2][idx], p_n[3], p_n[4]])
mean_i = np.dot(w_2, np.tanh(np.dot(self.W_1, p_n_i) + self.B_1))
mean[idx] = (0.5 * (mean_i + C["B_2"] + 1.0) *
(C["tmax"] - C["tmin"])) + C["tmin"]
return mean | [
"def",
"get_mean",
"(",
"self",
",",
"C",
",",
"rup",
",",
"sites",
",",
"dists",
")",
":",
"# W2 needs to be a 1 by 5 matrix (not a vector",
"w_2",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"C",
"[",
"\"W_21\"",
"]",
",",
"C",
"[",
"\"W_22\"",
"]",
",",
"C",
"[",
"\"W_23\"",
"]",
",",
"C",
"[",
"\"W_24\"",
"]",
",",
"C",
"[",
"\"W_25\"",
"]",
"]",
"]",
")",
"# Gets the style of faulting dummy variable",
"sof",
"=",
"self",
".",
"_get_sof_dummy_variable",
"(",
"rup",
".",
"rake",
")",
"# Get the normalised coefficients",
"p_n",
"=",
"self",
".",
"get_pn",
"(",
"rup",
",",
"sites",
",",
"dists",
",",
"sof",
")",
"mean",
"=",
"np",
".",
"zeros_like",
"(",
"dists",
".",
"rjb",
")",
"# Need to loop over sites - maybe this can be improved in future?",
"# ndenumerate is used to allow for application to 2-D arrays",
"for",
"idx",
",",
"rval",
"in",
"np",
".",
"ndenumerate",
"(",
"p_n",
"[",
"0",
"]",
")",
":",
"# Place normalised coefficients into a single array",
"p_n_i",
"=",
"np",
".",
"array",
"(",
"[",
"rval",
",",
"p_n",
"[",
"1",
"]",
",",
"p_n",
"[",
"2",
"]",
"[",
"idx",
"]",
",",
"p_n",
"[",
"3",
"]",
",",
"p_n",
"[",
"4",
"]",
"]",
")",
"# Executes the main ANN model",
"mean_i",
"=",
"np",
".",
"dot",
"(",
"w_2",
",",
"np",
".",
"tanh",
"(",
"np",
".",
"dot",
"(",
"self",
".",
"W_1",
",",
"p_n_i",
")",
"+",
"self",
".",
"B_1",
")",
")",
"mean",
"[",
"idx",
"]",
"=",
"(",
"0.5",
"*",
"(",
"mean_i",
"+",
"C",
"[",
"\"B_2\"",
"]",
"+",
"1.0",
")",
"*",
"(",
"C",
"[",
"\"tmax\"",
"]",
"-",
"C",
"[",
"\"tmin\"",
"]",
")",
")",
"+",
"C",
"[",
"\"tmin\"",
"]",
"return",
"mean"
] | Returns the mean ground motion in terms of log10 m/s/s, implementing
equation 2 (page 502) | [
"Returns",
"the",
"mean",
"ground",
"motion",
"in",
"terms",
"of",
"log10",
"m",
"/",
"s",
"/",
"s",
"implementing",
"equation",
"2",
"(",
"page",
"502",
")"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/derras_2014.py#L95-L118 |
gem/oq-engine | openquake/hazardlib/gsim/boore_1997.py | BooreEtAl1997GeometricMean.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]
mean = (self._compute_style_of_faulting_term(rup, C) +
self._compute_magnitude_scaling(rup.mag, C) +
self._compute_distance_scaling(dists.rjb, C) +
self._compute_site_term(sites.vs30, C))
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]
mean = (self._compute_style_of_faulting_term(rup, C) +
self._compute_magnitude_scaling(rup.mag, C) +
self._compute_distance_scaling(dists.rjb, C) +
self._compute_site_term(sites.vs30, C))
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",
"]",
"mean",
"=",
"(",
"self",
".",
"_compute_style_of_faulting_term",
"(",
"rup",
",",
"C",
")",
"+",
"self",
".",
"_compute_magnitude_scaling",
"(",
"rup",
".",
"mag",
",",
"C",
")",
"+",
"self",
".",
"_compute_distance_scaling",
"(",
"dists",
".",
"rjb",
",",
"C",
")",
"+",
"self",
".",
"_compute_site_term",
"(",
"sites",
".",
"vs30",
",",
"C",
")",
")",
"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_1997.py#L71-L87 |
gem/oq-engine | openquake/hazardlib/gsim/boore_1997.py | BooreEtAl1997GeometricMean._compute_distance_scaling | def _compute_distance_scaling(self, rjb, C):
"""
Compute distance-scaling term (Page 141, Eq 1)
"""
# Calculate distance according to Page 141, Eq 2.
rdist = np.sqrt((rjb ** 2.) + (C['h'] ** 2.))
return C['B5'] * np.log(rdist) | python | def _compute_distance_scaling(self, rjb, C):
rdist = np.sqrt((rjb ** 2.) + (C['h'] ** 2.))
return C['B5'] * np.log(rdist) | [
"def",
"_compute_distance_scaling",
"(",
"self",
",",
"rjb",
",",
"C",
")",
":",
"# Calculate distance according to Page 141, Eq 2.",
"rdist",
"=",
"np",
".",
"sqrt",
"(",
"(",
"rjb",
"**",
"2.",
")",
"+",
"(",
"C",
"[",
"'h'",
"]",
"**",
"2.",
")",
")",
"return",
"C",
"[",
"'B5'",
"]",
"*",
"np",
".",
"log",
"(",
"rdist",
")"
] | Compute distance-scaling term (Page 141, Eq 1) | [
"Compute",
"distance",
"-",
"scaling",
"term",
"(",
"Page",
"141",
"Eq",
"1",
")"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_1997.py#L106-L112 |
gem/oq-engine | openquake/hazardlib/gsim/boore_1997.py | BooreEtAl1997GeometricMean._compute_magnitude_scaling | def _compute_magnitude_scaling(self, mag, C):
"""
Compute magnitude-scaling term (Page 141, Eq 1)
"""
dmag = mag - 6.
return (C['B2'] * dmag) + (C['B3'] * (dmag ** 2.)) | python | def _compute_magnitude_scaling(self, mag, C):
dmag = mag - 6.
return (C['B2'] * dmag) + (C['B3'] * (dmag ** 2.)) | [
"def",
"_compute_magnitude_scaling",
"(",
"self",
",",
"mag",
",",
"C",
")",
":",
"dmag",
"=",
"mag",
"-",
"6.",
"return",
"(",
"C",
"[",
"'B2'",
"]",
"*",
"dmag",
")",
"+",
"(",
"C",
"[",
"'B3'",
"]",
"*",
"(",
"dmag",
"**",
"2.",
")",
")"
] | Compute magnitude-scaling term (Page 141, Eq 1) | [
"Compute",
"magnitude",
"-",
"scaling",
"term",
"(",
"Page",
"141",
"Eq",
"1",
")"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_1997.py#L114-L119 |
gem/oq-engine | openquake/hazardlib/gsim/boore_1997.py | BooreEtAl1997GeometricMean._compute_style_of_faulting_term | def _compute_style_of_faulting_term(self, rup, C):
"""
Computes the coefficient to scale for reverse or strike-slip events
Fault type (Strike-slip, Normal, Thrust/reverse) is
derived from rake angle.
Rakes angles within 30 of horizontal are strike-slip,
angles from 30 to 150 are reverse, and angles from
-30 to -150 are normal. See paragraph 'Predictor Variables'
pag 103.
Note that 'Unspecified' case is used to refer to all other rake
angles.
"""
if np.abs(rup.rake) <= 30.0 or (180.0 - np.abs(rup.rake)) <= 30.0:
# strike-slip
return C['B1ss']
elif rup.rake > 30.0 and rup.rake < 150.0:
# reverse
return C['B1rv']
else:
# unspecified (also includes Normal faulting!)
return C['B1all'] | python | def _compute_style_of_faulting_term(self, rup, C):
if np.abs(rup.rake) <= 30.0 or (180.0 - np.abs(rup.rake)) <= 30.0:
return C['B1ss']
elif rup.rake > 30.0 and rup.rake < 150.0:
return C['B1rv']
else:
return C['B1all'] | [
"def",
"_compute_style_of_faulting_term",
"(",
"self",
",",
"rup",
",",
"C",
")",
":",
"if",
"np",
".",
"abs",
"(",
"rup",
".",
"rake",
")",
"<=",
"30.0",
"or",
"(",
"180.0",
"-",
"np",
".",
"abs",
"(",
"rup",
".",
"rake",
")",
")",
"<=",
"30.0",
":",
"# strike-slip",
"return",
"C",
"[",
"'B1ss'",
"]",
"elif",
"rup",
".",
"rake",
">",
"30.0",
"and",
"rup",
".",
"rake",
"<",
"150.0",
":",
"# reverse",
"return",
"C",
"[",
"'B1rv'",
"]",
"else",
":",
"# unspecified (also includes Normal faulting!)",
"return",
"C",
"[",
"'B1all'",
"]"
] | Computes the coefficient to scale for reverse or strike-slip events
Fault type (Strike-slip, Normal, Thrust/reverse) is
derived from rake angle.
Rakes angles within 30 of horizontal are strike-slip,
angles from 30 to 150 are reverse, and angles from
-30 to -150 are normal. See paragraph 'Predictor Variables'
pag 103.
Note that 'Unspecified' case is used to refer to all other rake
angles. | [
"Computes",
"the",
"coefficient",
"to",
"scale",
"for",
"reverse",
"or",
"strike",
"-",
"slip",
"events",
"Fault",
"type",
"(",
"Strike",
"-",
"slip",
"Normal",
"Thrust",
"/",
"reverse",
")",
"is",
"derived",
"from",
"rake",
"angle",
".",
"Rakes",
"angles",
"within",
"30",
"of",
"horizontal",
"are",
"strike",
"-",
"slip",
"angles",
"from",
"30",
"to",
"150",
"are",
"reverse",
"and",
"angles",
"from",
"-",
"30",
"to",
"-",
"150",
"are",
"normal",
".",
"See",
"paragraph",
"Predictor",
"Variables",
"pag",
"103",
".",
"Note",
"that",
"Unspecified",
"case",
"is",
"used",
"to",
"refer",
"to",
"all",
"other",
"rake",
"angles",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_1997.py#L121-L141 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014.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.
"""
# extract dictionaries of coefficients specific to required
# intensity measure type and for PGA
C = self.COEFFS[imt]
C_PGA = self.COEFFS[PGA()]
# Get mean and standard deviation of PGA on rock (Vs30 1100 m/s^2)
pga1100 = np.exp(self.get_mean_values(C_PGA, sites, rup, dists, None))
# Get mean and standard deviations for IMT
mean = self.get_mean_values(C, sites, rup, dists, pga1100)
if imt.name == "SA" and imt.period <= 0.25:
# According to Campbell & Bozorgnia (2013) [NGA West 2 Report]
# If Sa (T) < PGA for T < 0.25 then set mean Sa(T) to mean PGA
# Get PGA on soil
pga = self.get_mean_values(C_PGA, sites, rup, dists, pga1100)
idx = mean <= pga
mean[idx] = pga[idx]
# Get standard deviations
stddevs = self._get_stddevs(C,
C_PGA,
rup,
sites,
pga1100,
stddev_types)
return mean, stddevs | python | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
C = self.COEFFS[imt]
C_PGA = self.COEFFS[PGA()]
pga1100 = np.exp(self.get_mean_values(C_PGA, sites, rup, dists, None))
mean = self.get_mean_values(C, sites, rup, dists, pga1100)
if imt.name == "SA" and imt.period <= 0.25:
pga = self.get_mean_values(C_PGA, sites, rup, dists, pga1100)
idx = mean <= pga
mean[idx] = pga[idx]
stddevs = self._get_stddevs(C,
C_PGA,
rup,
sites,
pga1100,
stddev_types)
return mean, stddevs | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"# extract dictionaries of coefficients specific to required",
"# intensity measure type and for PGA",
"C",
"=",
"self",
".",
"COEFFS",
"[",
"imt",
"]",
"C_PGA",
"=",
"self",
".",
"COEFFS",
"[",
"PGA",
"(",
")",
"]",
"# Get mean and standard deviation of PGA on rock (Vs30 1100 m/s^2)",
"pga1100",
"=",
"np",
".",
"exp",
"(",
"self",
".",
"get_mean_values",
"(",
"C_PGA",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"None",
")",
")",
"# Get mean and standard deviations for IMT",
"mean",
"=",
"self",
".",
"get_mean_values",
"(",
"C",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"pga1100",
")",
"if",
"imt",
".",
"name",
"==",
"\"SA\"",
"and",
"imt",
".",
"period",
"<=",
"0.25",
":",
"# According to Campbell & Bozorgnia (2013) [NGA West 2 Report]",
"# If Sa (T) < PGA for T < 0.25 then set mean Sa(T) to mean PGA",
"# Get PGA on soil",
"pga",
"=",
"self",
".",
"get_mean_values",
"(",
"C_PGA",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"pga1100",
")",
"idx",
"=",
"mean",
"<=",
"pga",
"mean",
"[",
"idx",
"]",
"=",
"pga",
"[",
"idx",
"]",
"# Get standard deviations",
"stddevs",
"=",
"self",
".",
"_get_stddevs",
"(",
"C",
",",
"C_PGA",
",",
"rup",
",",
"sites",
",",
"pga1100",
",",
"stddev_types",
")",
"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/campbell_bozorgnia_2014.py#L91-L120 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014.get_mean_values | def get_mean_values(self, C, sites, rup, dists, a1100):
"""
Returns the mean values for a specific IMT
"""
if isinstance(a1100, np.ndarray):
# Site model defined
temp_vs30 = sites.vs30
temp_z2pt5 = sites.z2pt5
else:
# Default site and basin model
temp_vs30 = 1100.0 * np.ones(len(sites.vs30))
temp_z2pt5 = self._select_basin_model(1100.0) *\
np.ones_like(temp_vs30)
return (self._get_magnitude_term(C, rup.mag) +
self._get_geometric_attenuation_term(C, rup.mag, dists.rrup) +
self._get_style_of_faulting_term(C, rup) +
self._get_hanging_wall_term(C, rup, dists) +
self._get_shallow_site_response_term(C, temp_vs30, a1100) +
self._get_basin_response_term(C, temp_z2pt5) +
self._get_hypocentral_depth_term(C, rup) +
self._get_fault_dip_term(C, rup) +
self._get_anelastic_attenuation_term(C, dists.rrup)) | python | def get_mean_values(self, C, sites, rup, dists, a1100):
if isinstance(a1100, np.ndarray):
temp_vs30 = sites.vs30
temp_z2pt5 = sites.z2pt5
else:
temp_vs30 = 1100.0 * np.ones(len(sites.vs30))
temp_z2pt5 = self._select_basin_model(1100.0) *\
np.ones_like(temp_vs30)
return (self._get_magnitude_term(C, rup.mag) +
self._get_geometric_attenuation_term(C, rup.mag, dists.rrup) +
self._get_style_of_faulting_term(C, rup) +
self._get_hanging_wall_term(C, rup, dists) +
self._get_shallow_site_response_term(C, temp_vs30, a1100) +
self._get_basin_response_term(C, temp_z2pt5) +
self._get_hypocentral_depth_term(C, rup) +
self._get_fault_dip_term(C, rup) +
self._get_anelastic_attenuation_term(C, dists.rrup)) | [
"def",
"get_mean_values",
"(",
"self",
",",
"C",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"a1100",
")",
":",
"if",
"isinstance",
"(",
"a1100",
",",
"np",
".",
"ndarray",
")",
":",
"# Site model defined",
"temp_vs30",
"=",
"sites",
".",
"vs30",
"temp_z2pt5",
"=",
"sites",
".",
"z2pt5",
"else",
":",
"# Default site and basin model",
"temp_vs30",
"=",
"1100.0",
"*",
"np",
".",
"ones",
"(",
"len",
"(",
"sites",
".",
"vs30",
")",
")",
"temp_z2pt5",
"=",
"self",
".",
"_select_basin_model",
"(",
"1100.0",
")",
"*",
"np",
".",
"ones_like",
"(",
"temp_vs30",
")",
"return",
"(",
"self",
".",
"_get_magnitude_term",
"(",
"C",
",",
"rup",
".",
"mag",
")",
"+",
"self",
".",
"_get_geometric_attenuation_term",
"(",
"C",
",",
"rup",
".",
"mag",
",",
"dists",
".",
"rrup",
")",
"+",
"self",
".",
"_get_style_of_faulting_term",
"(",
"C",
",",
"rup",
")",
"+",
"self",
".",
"_get_hanging_wall_term",
"(",
"C",
",",
"rup",
",",
"dists",
")",
"+",
"self",
".",
"_get_shallow_site_response_term",
"(",
"C",
",",
"temp_vs30",
",",
"a1100",
")",
"+",
"self",
".",
"_get_basin_response_term",
"(",
"C",
",",
"temp_z2pt5",
")",
"+",
"self",
".",
"_get_hypocentral_depth_term",
"(",
"C",
",",
"rup",
")",
"+",
"self",
".",
"_get_fault_dip_term",
"(",
"C",
",",
"rup",
")",
"+",
"self",
".",
"_get_anelastic_attenuation_term",
"(",
"C",
",",
"dists",
".",
"rrup",
")",
")"
] | Returns the mean values for a specific IMT | [
"Returns",
"the",
"mean",
"values",
"for",
"a",
"specific",
"IMT"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L122-L144 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_magnitude_term | def _get_magnitude_term(self, C, mag):
"""
Returns the magnitude scaling term defined in equation 2
"""
f_mag = C["c0"] + C["c1"] * mag
if (mag > 4.5) and (mag <= 5.5):
return f_mag + (C["c2"] * (mag - 4.5))
elif (mag > 5.5) and (mag <= 6.5):
return f_mag + (C["c2"] * (mag - 4.5)) + (C["c3"] * (mag - 5.5))
elif mag > 6.5:
return f_mag + (C["c2"] * (mag - 4.5)) + (C["c3"] * (mag - 5.5)) +\
(C["c4"] * (mag - 6.5))
else:
return f_mag | python | def _get_magnitude_term(self, C, mag):
f_mag = C["c0"] + C["c1"] * mag
if (mag > 4.5) and (mag <= 5.5):
return f_mag + (C["c2"] * (mag - 4.5))
elif (mag > 5.5) and (mag <= 6.5):
return f_mag + (C["c2"] * (mag - 4.5)) + (C["c3"] * (mag - 5.5))
elif mag > 6.5:
return f_mag + (C["c2"] * (mag - 4.5)) + (C["c3"] * (mag - 5.5)) +\
(C["c4"] * (mag - 6.5))
else:
return f_mag | [
"def",
"_get_magnitude_term",
"(",
"self",
",",
"C",
",",
"mag",
")",
":",
"f_mag",
"=",
"C",
"[",
"\"c0\"",
"]",
"+",
"C",
"[",
"\"c1\"",
"]",
"*",
"mag",
"if",
"(",
"mag",
">",
"4.5",
")",
"and",
"(",
"mag",
"<=",
"5.5",
")",
":",
"return",
"f_mag",
"+",
"(",
"C",
"[",
"\"c2\"",
"]",
"*",
"(",
"mag",
"-",
"4.5",
")",
")",
"elif",
"(",
"mag",
">",
"5.5",
")",
"and",
"(",
"mag",
"<=",
"6.5",
")",
":",
"return",
"f_mag",
"+",
"(",
"C",
"[",
"\"c2\"",
"]",
"*",
"(",
"mag",
"-",
"4.5",
")",
")",
"+",
"(",
"C",
"[",
"\"c3\"",
"]",
"*",
"(",
"mag",
"-",
"5.5",
")",
")",
"elif",
"mag",
">",
"6.5",
":",
"return",
"f_mag",
"+",
"(",
"C",
"[",
"\"c2\"",
"]",
"*",
"(",
"mag",
"-",
"4.5",
")",
")",
"+",
"(",
"C",
"[",
"\"c3\"",
"]",
"*",
"(",
"mag",
"-",
"5.5",
")",
")",
"+",
"(",
"C",
"[",
"\"c4\"",
"]",
"*",
"(",
"mag",
"-",
"6.5",
")",
")",
"else",
":",
"return",
"f_mag"
] | Returns the magnitude scaling term defined in equation 2 | [
"Returns",
"the",
"magnitude",
"scaling",
"term",
"defined",
"in",
"equation",
"2"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L146-L159 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_geometric_attenuation_term | def _get_geometric_attenuation_term(self, C, mag, rrup):
"""
Returns the geometric attenuation term defined in equation 3
"""
return (C["c5"] + C["c6"] * mag) * np.log(np.sqrt((rrup ** 2.) +
(C["c7"] ** 2.))) | python | def _get_geometric_attenuation_term(self, C, mag, rrup):
return (C["c5"] + C["c6"] * mag) * np.log(np.sqrt((rrup ** 2.) +
(C["c7"] ** 2.))) | [
"def",
"_get_geometric_attenuation_term",
"(",
"self",
",",
"C",
",",
"mag",
",",
"rrup",
")",
":",
"return",
"(",
"C",
"[",
"\"c5\"",
"]",
"+",
"C",
"[",
"\"c6\"",
"]",
"*",
"mag",
")",
"*",
"np",
".",
"log",
"(",
"np",
".",
"sqrt",
"(",
"(",
"rrup",
"**",
"2.",
")",
"+",
"(",
"C",
"[",
"\"c7\"",
"]",
"**",
"2.",
")",
")",
")"
] | Returns the geometric attenuation term defined in equation 3 | [
"Returns",
"the",
"geometric",
"attenuation",
"term",
"defined",
"in",
"equation",
"3"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L161-L166 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_style_of_faulting_term | def _get_style_of_faulting_term(self, C, rup):
"""
Returns the style-of-faulting scaling term defined in equations 4 to 6
"""
if (rup.rake > 30.0) and (rup.rake < 150.):
frv = 1.0
fnm = 0.0
elif (rup.rake > -150.0) and (rup.rake < -30.0):
fnm = 1.0
frv = 0.0
else:
fnm = 0.0
frv = 0.0
fflt_f = (self.CONSTS["c8"] * frv) + (C["c9"] * fnm)
if rup.mag <= 4.5:
fflt_m = 0.0
elif rup.mag > 5.5:
fflt_m = 1.0
else:
fflt_m = rup.mag - 4.5
return fflt_f * fflt_m | python | def _get_style_of_faulting_term(self, C, rup):
if (rup.rake > 30.0) and (rup.rake < 150.):
frv = 1.0
fnm = 0.0
elif (rup.rake > -150.0) and (rup.rake < -30.0):
fnm = 1.0
frv = 0.0
else:
fnm = 0.0
frv = 0.0
fflt_f = (self.CONSTS["c8"] * frv) + (C["c9"] * fnm)
if rup.mag <= 4.5:
fflt_m = 0.0
elif rup.mag > 5.5:
fflt_m = 1.0
else:
fflt_m = rup.mag - 4.5
return fflt_f * fflt_m | [
"def",
"_get_style_of_faulting_term",
"(",
"self",
",",
"C",
",",
"rup",
")",
":",
"if",
"(",
"rup",
".",
"rake",
">",
"30.0",
")",
"and",
"(",
"rup",
".",
"rake",
"<",
"150.",
")",
":",
"frv",
"=",
"1.0",
"fnm",
"=",
"0.0",
"elif",
"(",
"rup",
".",
"rake",
">",
"-",
"150.0",
")",
"and",
"(",
"rup",
".",
"rake",
"<",
"-",
"30.0",
")",
":",
"fnm",
"=",
"1.0",
"frv",
"=",
"0.0",
"else",
":",
"fnm",
"=",
"0.0",
"frv",
"=",
"0.0",
"fflt_f",
"=",
"(",
"self",
".",
"CONSTS",
"[",
"\"c8\"",
"]",
"*",
"frv",
")",
"+",
"(",
"C",
"[",
"\"c9\"",
"]",
"*",
"fnm",
")",
"if",
"rup",
".",
"mag",
"<=",
"4.5",
":",
"fflt_m",
"=",
"0.0",
"elif",
"rup",
".",
"mag",
">",
"5.5",
":",
"fflt_m",
"=",
"1.0",
"else",
":",
"fflt_m",
"=",
"rup",
".",
"mag",
"-",
"4.5",
"return",
"fflt_f",
"*",
"fflt_m"
] | Returns the style-of-faulting scaling term defined in equations 4 to 6 | [
"Returns",
"the",
"style",
"-",
"of",
"-",
"faulting",
"scaling",
"term",
"defined",
"in",
"equations",
"4",
"to",
"6"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L168-L189 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_hanging_wall_term | def _get_hanging_wall_term(self, C, rup, dists):
"""
Returns the hanging wall scaling term defined in equations 7 to 16
"""
return (C["c10"] *
self._get_hanging_wall_coeffs_rx(C, rup, dists.rx) *
self._get_hanging_wall_coeffs_rrup(dists) *
self._get_hanging_wall_coeffs_mag(C, rup.mag) *
self._get_hanging_wall_coeffs_ztor(rup.ztor) *
self._get_hanging_wall_coeffs_dip(rup.dip)) | python | def _get_hanging_wall_term(self, C, rup, dists):
return (C["c10"] *
self._get_hanging_wall_coeffs_rx(C, rup, dists.rx) *
self._get_hanging_wall_coeffs_rrup(dists) *
self._get_hanging_wall_coeffs_mag(C, rup.mag) *
self._get_hanging_wall_coeffs_ztor(rup.ztor) *
self._get_hanging_wall_coeffs_dip(rup.dip)) | [
"def",
"_get_hanging_wall_term",
"(",
"self",
",",
"C",
",",
"rup",
",",
"dists",
")",
":",
"return",
"(",
"C",
"[",
"\"c10\"",
"]",
"*",
"self",
".",
"_get_hanging_wall_coeffs_rx",
"(",
"C",
",",
"rup",
",",
"dists",
".",
"rx",
")",
"*",
"self",
".",
"_get_hanging_wall_coeffs_rrup",
"(",
"dists",
")",
"*",
"self",
".",
"_get_hanging_wall_coeffs_mag",
"(",
"C",
",",
"rup",
".",
"mag",
")",
"*",
"self",
".",
"_get_hanging_wall_coeffs_ztor",
"(",
"rup",
".",
"ztor",
")",
"*",
"self",
".",
"_get_hanging_wall_coeffs_dip",
"(",
"rup",
".",
"dip",
")",
")"
] | Returns the hanging wall scaling term defined in equations 7 to 16 | [
"Returns",
"the",
"hanging",
"wall",
"scaling",
"term",
"defined",
"in",
"equations",
"7",
"to",
"16"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L191-L200 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_hanging_wall_coeffs_rx | def _get_hanging_wall_coeffs_rx(self, C, rup, r_x):
"""
Returns the hanging wall r-x caling term defined in equation 7 to 12
"""
# Define coefficients R1 and R2
r_1 = rup.width * cos(radians(rup.dip))
r_2 = 62.0 * rup.mag - 350.0
fhngrx = np.zeros(len(r_x))
# Case when 0 <= Rx <= R1
idx = np.logical_and(r_x >= 0., r_x < r_1)
fhngrx[idx] = self._get_f1rx(C, r_x[idx], r_1)
# Case when Rx > R1
idx = r_x >= r_1
f2rx = self._get_f2rx(C, r_x[idx], r_1, r_2)
f2rx[f2rx < 0.0] = 0.0
fhngrx[idx] = f2rx
return fhngrx | python | def _get_hanging_wall_coeffs_rx(self, C, rup, r_x):
r_1 = rup.width * cos(radians(rup.dip))
r_2 = 62.0 * rup.mag - 350.0
fhngrx = np.zeros(len(r_x))
idx = np.logical_and(r_x >= 0., r_x < r_1)
fhngrx[idx] = self._get_f1rx(C, r_x[idx], r_1)
idx = r_x >= r_1
f2rx = self._get_f2rx(C, r_x[idx], r_1, r_2)
f2rx[f2rx < 0.0] = 0.0
fhngrx[idx] = f2rx
return fhngrx | [
"def",
"_get_hanging_wall_coeffs_rx",
"(",
"self",
",",
"C",
",",
"rup",
",",
"r_x",
")",
":",
"# Define coefficients R1 and R2",
"r_1",
"=",
"rup",
".",
"width",
"*",
"cos",
"(",
"radians",
"(",
"rup",
".",
"dip",
")",
")",
"r_2",
"=",
"62.0",
"*",
"rup",
".",
"mag",
"-",
"350.0",
"fhngrx",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"r_x",
")",
")",
"# Case when 0 <= Rx <= R1",
"idx",
"=",
"np",
".",
"logical_and",
"(",
"r_x",
">=",
"0.",
",",
"r_x",
"<",
"r_1",
")",
"fhngrx",
"[",
"idx",
"]",
"=",
"self",
".",
"_get_f1rx",
"(",
"C",
",",
"r_x",
"[",
"idx",
"]",
",",
"r_1",
")",
"# Case when Rx > R1",
"idx",
"=",
"r_x",
">=",
"r_1",
"f2rx",
"=",
"self",
".",
"_get_f2rx",
"(",
"C",
",",
"r_x",
"[",
"idx",
"]",
",",
"r_1",
",",
"r_2",
")",
"f2rx",
"[",
"f2rx",
"<",
"0.0",
"]",
"=",
"0.0",
"fhngrx",
"[",
"idx",
"]",
"=",
"f2rx",
"return",
"fhngrx"
] | Returns the hanging wall r-x caling term defined in equation 7 to 12 | [
"Returns",
"the",
"hanging",
"wall",
"r",
"-",
"x",
"caling",
"term",
"defined",
"in",
"equation",
"7",
"to",
"12"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L202-L218 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_f1rx | def _get_f1rx(self, C, r_x, r_1):
"""
Defines the f1 scaling coefficient defined in equation 9
"""
rxr1 = r_x / r_1
return C["h1"] + (C["h2"] * rxr1) + (C["h3"] * (rxr1 ** 2.)) | python | def _get_f1rx(self, C, r_x, r_1):
rxr1 = r_x / r_1
return C["h1"] + (C["h2"] * rxr1) + (C["h3"] * (rxr1 ** 2.)) | [
"def",
"_get_f1rx",
"(",
"self",
",",
"C",
",",
"r_x",
",",
"r_1",
")",
":",
"rxr1",
"=",
"r_x",
"/",
"r_1",
"return",
"C",
"[",
"\"h1\"",
"]",
"+",
"(",
"C",
"[",
"\"h2\"",
"]",
"*",
"rxr1",
")",
"+",
"(",
"C",
"[",
"\"h3\"",
"]",
"*",
"(",
"rxr1",
"**",
"2.",
")",
")"
] | Defines the f1 scaling coefficient defined in equation 9 | [
"Defines",
"the",
"f1",
"scaling",
"coefficient",
"defined",
"in",
"equation",
"9"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L220-L225 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_f2rx | def _get_f2rx(self, C, r_x, r_1, r_2):
"""
Defines the f2 scaling coefficient defined in equation 10
"""
drx = (r_x - r_1) / (r_2 - r_1)
return self.CONSTS["h4"] + (C["h5"] * drx) + (C["h6"] * (drx ** 2.)) | python | def _get_f2rx(self, C, r_x, r_1, r_2):
drx = (r_x - r_1) / (r_2 - r_1)
return self.CONSTS["h4"] + (C["h5"] * drx) + (C["h6"] * (drx ** 2.)) | [
"def",
"_get_f2rx",
"(",
"self",
",",
"C",
",",
"r_x",
",",
"r_1",
",",
"r_2",
")",
":",
"drx",
"=",
"(",
"r_x",
"-",
"r_1",
")",
"/",
"(",
"r_2",
"-",
"r_1",
")",
"return",
"self",
".",
"CONSTS",
"[",
"\"h4\"",
"]",
"+",
"(",
"C",
"[",
"\"h5\"",
"]",
"*",
"drx",
")",
"+",
"(",
"C",
"[",
"\"h6\"",
"]",
"*",
"(",
"drx",
"**",
"2.",
")",
")"
] | Defines the f2 scaling coefficient defined in equation 10 | [
"Defines",
"the",
"f2",
"scaling",
"coefficient",
"defined",
"in",
"equation",
"10"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L227-L232 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_hanging_wall_coeffs_rrup | def _get_hanging_wall_coeffs_rrup(self, dists):
"""
Returns the hanging wall rrup term defined in equation 13
"""
fhngrrup = np.ones(len(dists.rrup))
idx = dists.rrup > 0.0
fhngrrup[idx] = (dists.rrup[idx] - dists.rjb[idx]) / dists.rrup[idx]
return fhngrrup | python | def _get_hanging_wall_coeffs_rrup(self, dists):
fhngrrup = np.ones(len(dists.rrup))
idx = dists.rrup > 0.0
fhngrrup[idx] = (dists.rrup[idx] - dists.rjb[idx]) / dists.rrup[idx]
return fhngrrup | [
"def",
"_get_hanging_wall_coeffs_rrup",
"(",
"self",
",",
"dists",
")",
":",
"fhngrrup",
"=",
"np",
".",
"ones",
"(",
"len",
"(",
"dists",
".",
"rrup",
")",
")",
"idx",
"=",
"dists",
".",
"rrup",
">",
"0.0",
"fhngrrup",
"[",
"idx",
"]",
"=",
"(",
"dists",
".",
"rrup",
"[",
"idx",
"]",
"-",
"dists",
".",
"rjb",
"[",
"idx",
"]",
")",
"/",
"dists",
".",
"rrup",
"[",
"idx",
"]",
"return",
"fhngrrup"
] | Returns the hanging wall rrup term defined in equation 13 | [
"Returns",
"the",
"hanging",
"wall",
"rrup",
"term",
"defined",
"in",
"equation",
"13"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L234-L241 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_hanging_wall_coeffs_mag | def _get_hanging_wall_coeffs_mag(self, C, mag):
"""
Returns the hanging wall magnitude term defined in equation 14
"""
if mag < 5.5:
return 0.0
elif mag > 6.5:
return 1.0 + C["a2"] * (mag - 6.5)
else:
return (mag - 5.5) * (1.0 + C["a2"] * (mag - 6.5)) | python | def _get_hanging_wall_coeffs_mag(self, C, mag):
if mag < 5.5:
return 0.0
elif mag > 6.5:
return 1.0 + C["a2"] * (mag - 6.5)
else:
return (mag - 5.5) * (1.0 + C["a2"] * (mag - 6.5)) | [
"def",
"_get_hanging_wall_coeffs_mag",
"(",
"self",
",",
"C",
",",
"mag",
")",
":",
"if",
"mag",
"<",
"5.5",
":",
"return",
"0.0",
"elif",
"mag",
">",
"6.5",
":",
"return",
"1.0",
"+",
"C",
"[",
"\"a2\"",
"]",
"*",
"(",
"mag",
"-",
"6.5",
")",
"else",
":",
"return",
"(",
"mag",
"-",
"5.5",
")",
"*",
"(",
"1.0",
"+",
"C",
"[",
"\"a2\"",
"]",
"*",
"(",
"mag",
"-",
"6.5",
")",
")"
] | Returns the hanging wall magnitude term defined in equation 14 | [
"Returns",
"the",
"hanging",
"wall",
"magnitude",
"term",
"defined",
"in",
"equation",
"14"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L243-L252 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_hypocentral_depth_term | def _get_hypocentral_depth_term(self, C, rup):
"""
Returns the hypocentral depth scaling term defined in equations 21 - 23
"""
if rup.hypo_depth <= 7.0:
fhyp_h = 0.0
elif rup.hypo_depth > 20.0:
fhyp_h = 13.0
else:
fhyp_h = rup.hypo_depth - 7.0
if rup.mag <= 5.5:
fhyp_m = C["c17"]
elif rup.mag > 6.5:
fhyp_m = C["c18"]
else:
fhyp_m = C["c17"] + ((C["c18"] - C["c17"]) * (rup.mag - 5.5))
return fhyp_h * fhyp_m | python | def _get_hypocentral_depth_term(self, C, rup):
if rup.hypo_depth <= 7.0:
fhyp_h = 0.0
elif rup.hypo_depth > 20.0:
fhyp_h = 13.0
else:
fhyp_h = rup.hypo_depth - 7.0
if rup.mag <= 5.5:
fhyp_m = C["c17"]
elif rup.mag > 6.5:
fhyp_m = C["c18"]
else:
fhyp_m = C["c17"] + ((C["c18"] - C["c17"]) * (rup.mag - 5.5))
return fhyp_h * fhyp_m | [
"def",
"_get_hypocentral_depth_term",
"(",
"self",
",",
"C",
",",
"rup",
")",
":",
"if",
"rup",
".",
"hypo_depth",
"<=",
"7.0",
":",
"fhyp_h",
"=",
"0.0",
"elif",
"rup",
".",
"hypo_depth",
">",
"20.0",
":",
"fhyp_h",
"=",
"13.0",
"else",
":",
"fhyp_h",
"=",
"rup",
".",
"hypo_depth",
"-",
"7.0",
"if",
"rup",
".",
"mag",
"<=",
"5.5",
":",
"fhyp_m",
"=",
"C",
"[",
"\"c17\"",
"]",
"elif",
"rup",
".",
"mag",
">",
"6.5",
":",
"fhyp_m",
"=",
"C",
"[",
"\"c18\"",
"]",
"else",
":",
"fhyp_m",
"=",
"C",
"[",
"\"c17\"",
"]",
"+",
"(",
"(",
"C",
"[",
"\"c18\"",
"]",
"-",
"C",
"[",
"\"c17\"",
"]",
")",
"*",
"(",
"rup",
".",
"mag",
"-",
"5.5",
")",
")",
"return",
"fhyp_h",
"*",
"fhyp_m"
] | Returns the hypocentral depth scaling term defined in equations 21 - 23 | [
"Returns",
"the",
"hypocentral",
"depth",
"scaling",
"term",
"defined",
"in",
"equations",
"21",
"-",
"23"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L269-L286 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_fault_dip_term | def _get_fault_dip_term(self, C, rup):
"""
Returns the fault dip term, defined in equation 24
"""
if rup.mag < 4.5:
return C["c19"] * rup.dip
elif rup.mag > 5.5:
return 0.0
else:
return C["c19"] * (5.5 - rup.mag) * rup.dip | python | def _get_fault_dip_term(self, C, rup):
if rup.mag < 4.5:
return C["c19"] * rup.dip
elif rup.mag > 5.5:
return 0.0
else:
return C["c19"] * (5.5 - rup.mag) * rup.dip | [
"def",
"_get_fault_dip_term",
"(",
"self",
",",
"C",
",",
"rup",
")",
":",
"if",
"rup",
".",
"mag",
"<",
"4.5",
":",
"return",
"C",
"[",
"\"c19\"",
"]",
"*",
"rup",
".",
"dip",
"elif",
"rup",
".",
"mag",
">",
"5.5",
":",
"return",
"0.0",
"else",
":",
"return",
"C",
"[",
"\"c19\"",
"]",
"*",
"(",
"5.5",
"-",
"rup",
".",
"mag",
")",
"*",
"rup",
".",
"dip"
] | Returns the fault dip term, defined in equation 24 | [
"Returns",
"the",
"fault",
"dip",
"term",
"defined",
"in",
"equation",
"24"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L288-L297 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_anelastic_attenuation_term | def _get_anelastic_attenuation_term(self, C, rrup):
"""
Returns the anelastic attenuation term defined in equation 25
"""
f_atn = np.zeros(len(rrup))
idx = rrup >= 80.0
f_atn[idx] = (C["c20"] + C["Dc20"]) * (rrup[idx] - 80.0)
return f_atn | python | def _get_anelastic_attenuation_term(self, C, rrup):
f_atn = np.zeros(len(rrup))
idx = rrup >= 80.0
f_atn[idx] = (C["c20"] + C["Dc20"]) * (rrup[idx] - 80.0)
return f_atn | [
"def",
"_get_anelastic_attenuation_term",
"(",
"self",
",",
"C",
",",
"rrup",
")",
":",
"f_atn",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"rrup",
")",
")",
"idx",
"=",
"rrup",
">=",
"80.0",
"f_atn",
"[",
"idx",
"]",
"=",
"(",
"C",
"[",
"\"c20\"",
"]",
"+",
"C",
"[",
"\"Dc20\"",
"]",
")",
"*",
"(",
"rrup",
"[",
"idx",
"]",
"-",
"80.0",
")",
"return",
"f_atn"
] | Returns the anelastic attenuation term defined in equation 25 | [
"Returns",
"the",
"anelastic",
"attenuation",
"term",
"defined",
"in",
"equation",
"25"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L299-L306 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._select_basin_model | def _select_basin_model(self, vs30):
"""
Select the preferred basin model (California or Japan) to scale
basin depth with respect to Vs30
"""
if self.CONSTS["SJ"]:
# Japan Basin Model - Equation 34 of Campbell & Bozorgnia (2014)
return np.exp(5.359 - 1.102 * np.log(vs30))
else:
# California Basin Model - Equation 33 of
# Campbell & Bozorgnia (2014)
return np.exp(7.089 - 1.144 * np.log(vs30)) | python | def _select_basin_model(self, vs30):
if self.CONSTS["SJ"]:
return np.exp(5.359 - 1.102 * np.log(vs30))
else:
return np.exp(7.089 - 1.144 * np.log(vs30)) | [
"def",
"_select_basin_model",
"(",
"self",
",",
"vs30",
")",
":",
"if",
"self",
".",
"CONSTS",
"[",
"\"SJ\"",
"]",
":",
"# Japan Basin Model - Equation 34 of Campbell & Bozorgnia (2014)",
"return",
"np",
".",
"exp",
"(",
"5.359",
"-",
"1.102",
"*",
"np",
".",
"log",
"(",
"vs30",
")",
")",
"else",
":",
"# California Basin Model - Equation 33 of",
"# Campbell & Bozorgnia (2014)",
"return",
"np",
".",
"exp",
"(",
"7.089",
"-",
"1.144",
"*",
"np",
".",
"log",
"(",
"vs30",
")",
")"
] | Select the preferred basin model (California or Japan) to scale
basin depth with respect to Vs30 | [
"Select",
"the",
"preferred",
"basin",
"model",
"(",
"California",
"or",
"Japan",
")",
"to",
"scale",
"basin",
"depth",
"with",
"respect",
"to",
"Vs30"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L308-L319 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_basin_response_term | def _get_basin_response_term(self, C, z2pt5):
"""
Returns the basin response term defined in equation 20
"""
f_sed = np.zeros(len(z2pt5))
idx = z2pt5 < 1.0
f_sed[idx] = (C["c14"] + C["c15"] * float(self.CONSTS["SJ"])) *\
(z2pt5[idx] - 1.0)
idx = z2pt5 > 3.0
f_sed[idx] = C["c16"] * C["k3"] * exp(-0.75) *\
(1.0 - np.exp(-0.25 * (z2pt5[idx] - 3.0)))
return f_sed | python | def _get_basin_response_term(self, C, z2pt5):
f_sed = np.zeros(len(z2pt5))
idx = z2pt5 < 1.0
f_sed[idx] = (C["c14"] + C["c15"] * float(self.CONSTS["SJ"])) *\
(z2pt5[idx] - 1.0)
idx = z2pt5 > 3.0
f_sed[idx] = C["c16"] * C["k3"] * exp(-0.75) *\
(1.0 - np.exp(-0.25 * (z2pt5[idx] - 3.0)))
return f_sed | [
"def",
"_get_basin_response_term",
"(",
"self",
",",
"C",
",",
"z2pt5",
")",
":",
"f_sed",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"z2pt5",
")",
")",
"idx",
"=",
"z2pt5",
"<",
"1.0",
"f_sed",
"[",
"idx",
"]",
"=",
"(",
"C",
"[",
"\"c14\"",
"]",
"+",
"C",
"[",
"\"c15\"",
"]",
"*",
"float",
"(",
"self",
".",
"CONSTS",
"[",
"\"SJ\"",
"]",
")",
")",
"*",
"(",
"z2pt5",
"[",
"idx",
"]",
"-",
"1.0",
")",
"idx",
"=",
"z2pt5",
">",
"3.0",
"f_sed",
"[",
"idx",
"]",
"=",
"C",
"[",
"\"c16\"",
"]",
"*",
"C",
"[",
"\"k3\"",
"]",
"*",
"exp",
"(",
"-",
"0.75",
")",
"*",
"(",
"1.0",
"-",
"np",
".",
"exp",
"(",
"-",
"0.25",
"*",
"(",
"z2pt5",
"[",
"idx",
"]",
"-",
"3.0",
")",
")",
")",
"return",
"f_sed"
] | Returns the basin response term defined in equation 20 | [
"Returns",
"the",
"basin",
"response",
"term",
"defined",
"in",
"equation",
"20"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L321-L332 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_shallow_site_response_term | def _get_shallow_site_response_term(self, C, vs30, pga_rock):
"""
Returns the shallow site response term defined in equations 17, 18 and
19
"""
vs_mod = vs30 / C["k1"]
# Get linear global site response term
f_site_g = C["c11"] * np.log(vs_mod)
idx = vs30 > C["k1"]
f_site_g[idx] = f_site_g[idx] + (C["k2"] * self.CONSTS["n"] *
np.log(vs_mod[idx]))
# Get nonlinear site response term
idx = np.logical_not(idx)
if np.any(idx):
f_site_g[idx] = f_site_g[idx] + C["k2"] * (
np.log(pga_rock[idx] +
self.CONSTS["c"] * (vs_mod[idx] ** self.CONSTS["n"])) -
np.log(pga_rock[idx] + self.CONSTS["c"])
)
# For Japan sites (SJ = 1) further scaling is needed (equation 19)
if self.CONSTS["SJ"]:
fsite_j = np.log(vs_mod)
idx = vs30 > 200.0
if np.any(idx):
fsite_j[idx] = (C["c13"] + C["k2"] * self.CONSTS["n"]) *\
fsite_j[idx]
idx = np.logical_not(idx)
if np.any(idx):
fsite_j[idx] = (C["c12"] + C["k2"] * self.CONSTS["n"]) *\
(fsite_j[idx] - np.log(200.0 / C["k1"]))
return f_site_g + fsite_j
else:
return f_site_g | python | def _get_shallow_site_response_term(self, C, vs30, pga_rock):
vs_mod = vs30 / C["k1"]
f_site_g = C["c11"] * np.log(vs_mod)
idx = vs30 > C["k1"]
f_site_g[idx] = f_site_g[idx] + (C["k2"] * self.CONSTS["n"] *
np.log(vs_mod[idx]))
idx = np.logical_not(idx)
if np.any(idx):
f_site_g[idx] = f_site_g[idx] + C["k2"] * (
np.log(pga_rock[idx] +
self.CONSTS["c"] * (vs_mod[idx] ** self.CONSTS["n"])) -
np.log(pga_rock[idx] + self.CONSTS["c"])
)
if self.CONSTS["SJ"]:
fsite_j = np.log(vs_mod)
idx = vs30 > 200.0
if np.any(idx):
fsite_j[idx] = (C["c13"] + C["k2"] * self.CONSTS["n"]) *\
fsite_j[idx]
idx = np.logical_not(idx)
if np.any(idx):
fsite_j[idx] = (C["c12"] + C["k2"] * self.CONSTS["n"]) *\
(fsite_j[idx] - np.log(200.0 / C["k1"]))
return f_site_g + fsite_j
else:
return f_site_g | [
"def",
"_get_shallow_site_response_term",
"(",
"self",
",",
"C",
",",
"vs30",
",",
"pga_rock",
")",
":",
"vs_mod",
"=",
"vs30",
"/",
"C",
"[",
"\"k1\"",
"]",
"# Get linear global site response term",
"f_site_g",
"=",
"C",
"[",
"\"c11\"",
"]",
"*",
"np",
".",
"log",
"(",
"vs_mod",
")",
"idx",
"=",
"vs30",
">",
"C",
"[",
"\"k1\"",
"]",
"f_site_g",
"[",
"idx",
"]",
"=",
"f_site_g",
"[",
"idx",
"]",
"+",
"(",
"C",
"[",
"\"k2\"",
"]",
"*",
"self",
".",
"CONSTS",
"[",
"\"n\"",
"]",
"*",
"np",
".",
"log",
"(",
"vs_mod",
"[",
"idx",
"]",
")",
")",
"# Get nonlinear site response term",
"idx",
"=",
"np",
".",
"logical_not",
"(",
"idx",
")",
"if",
"np",
".",
"any",
"(",
"idx",
")",
":",
"f_site_g",
"[",
"idx",
"]",
"=",
"f_site_g",
"[",
"idx",
"]",
"+",
"C",
"[",
"\"k2\"",
"]",
"*",
"(",
"np",
".",
"log",
"(",
"pga_rock",
"[",
"idx",
"]",
"+",
"self",
".",
"CONSTS",
"[",
"\"c\"",
"]",
"*",
"(",
"vs_mod",
"[",
"idx",
"]",
"**",
"self",
".",
"CONSTS",
"[",
"\"n\"",
"]",
")",
")",
"-",
"np",
".",
"log",
"(",
"pga_rock",
"[",
"idx",
"]",
"+",
"self",
".",
"CONSTS",
"[",
"\"c\"",
"]",
")",
")",
"# For Japan sites (SJ = 1) further scaling is needed (equation 19)",
"if",
"self",
".",
"CONSTS",
"[",
"\"SJ\"",
"]",
":",
"fsite_j",
"=",
"np",
".",
"log",
"(",
"vs_mod",
")",
"idx",
"=",
"vs30",
">",
"200.0",
"if",
"np",
".",
"any",
"(",
"idx",
")",
":",
"fsite_j",
"[",
"idx",
"]",
"=",
"(",
"C",
"[",
"\"c13\"",
"]",
"+",
"C",
"[",
"\"k2\"",
"]",
"*",
"self",
".",
"CONSTS",
"[",
"\"n\"",
"]",
")",
"*",
"fsite_j",
"[",
"idx",
"]",
"idx",
"=",
"np",
".",
"logical_not",
"(",
"idx",
")",
"if",
"np",
".",
"any",
"(",
"idx",
")",
":",
"fsite_j",
"[",
"idx",
"]",
"=",
"(",
"C",
"[",
"\"c12\"",
"]",
"+",
"C",
"[",
"\"k2\"",
"]",
"*",
"self",
".",
"CONSTS",
"[",
"\"n\"",
"]",
")",
"*",
"(",
"fsite_j",
"[",
"idx",
"]",
"-",
"np",
".",
"log",
"(",
"200.0",
"/",
"C",
"[",
"\"k1\"",
"]",
")",
")",
"return",
"f_site_g",
"+",
"fsite_j",
"else",
":",
"return",
"f_site_g"
] | Returns the shallow site response term defined in equations 17, 18 and
19 | [
"Returns",
"the",
"shallow",
"site",
"response",
"term",
"defined",
"in",
"equations",
"17",
"18",
"and",
"19"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L334-L369 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_stddevs | def _get_stddevs(self, C, C_PGA, rup, sites, pga1100, stddev_types):
"""
Returns the inter- and intra-event and total standard deviations
"""
# Get stddevs for PGA on basement rock
tau_lnpga_b, phi_lnpga_b = self._get_stddevs_pga(C_PGA, rup)
num_sites = len(sites.vs30)
# Get tau_lny on the basement rock
tau_lnyb = self._get_taulny(C, rup.mag)
# Get phi_lny on the basement rock
phi_lnyb = np.sqrt(self._get_philny(C, rup.mag) ** 2. -
self.CONSTS["philnAF"] ** 2.)
# Get site scaling term
alpha = self._get_alpha(C, sites.vs30, pga1100)
# Evaluate tau according to equation 29
tau = np.sqrt(
(tau_lnyb ** 2.) +
((alpha ** 2.) * (tau_lnpga_b ** 2.)) +
(2.0 * alpha * C["rholny"] * tau_lnyb * tau_lnpga_b))
# Evaluate phi according to equation 30
phi = np.sqrt(
(phi_lnyb ** 2.) +
(self.CONSTS["philnAF"] ** 2.) +
((alpha ** 2.) * (phi_lnpga_b ** 2.)) +
(2.0 * alpha * C["rholny"] * phi_lnyb * phi_lnpga_b))
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
stddevs.append(np.sqrt((tau ** 2.) + (phi ** 2.)) +
np.zeros(num_sites))
elif stddev_type == const.StdDev.INTRA_EVENT:
stddevs.append(phi + np.zeros(num_sites))
elif stddev_type == const.StdDev.INTER_EVENT:
stddevs.append(tau + np.zeros(num_sites))
return stddevs | python | def _get_stddevs(self, C, C_PGA, rup, sites, pga1100, stddev_types):
tau_lnpga_b, phi_lnpga_b = self._get_stddevs_pga(C_PGA, rup)
num_sites = len(sites.vs30)
tau_lnyb = self._get_taulny(C, rup.mag)
phi_lnyb = np.sqrt(self._get_philny(C, rup.mag) ** 2. -
self.CONSTS["philnAF"] ** 2.)
alpha = self._get_alpha(C, sites.vs30, pga1100)
tau = np.sqrt(
(tau_lnyb ** 2.) +
((alpha ** 2.) * (tau_lnpga_b ** 2.)) +
(2.0 * alpha * C["rholny"] * tau_lnyb * tau_lnpga_b))
phi = np.sqrt(
(phi_lnyb ** 2.) +
(self.CONSTS["philnAF"] ** 2.) +
((alpha ** 2.) * (phi_lnpga_b ** 2.)) +
(2.0 * alpha * C["rholny"] * phi_lnyb * phi_lnpga_b))
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.TOTAL:
stddevs.append(np.sqrt((tau ** 2.) + (phi ** 2.)) +
np.zeros(num_sites))
elif stddev_type == const.StdDev.INTRA_EVENT:
stddevs.append(phi + np.zeros(num_sites))
elif stddev_type == const.StdDev.INTER_EVENT:
stddevs.append(tau + np.zeros(num_sites))
return stddevs | [
"def",
"_get_stddevs",
"(",
"self",
",",
"C",
",",
"C_PGA",
",",
"rup",
",",
"sites",
",",
"pga1100",
",",
"stddev_types",
")",
":",
"# Get stddevs for PGA on basement rock",
"tau_lnpga_b",
",",
"phi_lnpga_b",
"=",
"self",
".",
"_get_stddevs_pga",
"(",
"C_PGA",
",",
"rup",
")",
"num_sites",
"=",
"len",
"(",
"sites",
".",
"vs30",
")",
"# Get tau_lny on the basement rock",
"tau_lnyb",
"=",
"self",
".",
"_get_taulny",
"(",
"C",
",",
"rup",
".",
"mag",
")",
"# Get phi_lny on the basement rock",
"phi_lnyb",
"=",
"np",
".",
"sqrt",
"(",
"self",
".",
"_get_philny",
"(",
"C",
",",
"rup",
".",
"mag",
")",
"**",
"2.",
"-",
"self",
".",
"CONSTS",
"[",
"\"philnAF\"",
"]",
"**",
"2.",
")",
"# Get site scaling term",
"alpha",
"=",
"self",
".",
"_get_alpha",
"(",
"C",
",",
"sites",
".",
"vs30",
",",
"pga1100",
")",
"# Evaluate tau according to equation 29",
"tau",
"=",
"np",
".",
"sqrt",
"(",
"(",
"tau_lnyb",
"**",
"2.",
")",
"+",
"(",
"(",
"alpha",
"**",
"2.",
")",
"*",
"(",
"tau_lnpga_b",
"**",
"2.",
")",
")",
"+",
"(",
"2.0",
"*",
"alpha",
"*",
"C",
"[",
"\"rholny\"",
"]",
"*",
"tau_lnyb",
"*",
"tau_lnpga_b",
")",
")",
"# Evaluate phi according to equation 30",
"phi",
"=",
"np",
".",
"sqrt",
"(",
"(",
"phi_lnyb",
"**",
"2.",
")",
"+",
"(",
"self",
".",
"CONSTS",
"[",
"\"philnAF\"",
"]",
"**",
"2.",
")",
"+",
"(",
"(",
"alpha",
"**",
"2.",
")",
"*",
"(",
"phi_lnpga_b",
"**",
"2.",
")",
")",
"+",
"(",
"2.0",
"*",
"alpha",
"*",
"C",
"[",
"\"rholny\"",
"]",
"*",
"phi_lnyb",
"*",
"phi_lnpga_b",
")",
")",
"stddevs",
"=",
"[",
"]",
"for",
"stddev_type",
"in",
"stddev_types",
":",
"assert",
"stddev_type",
"in",
"self",
".",
"DEFINED_FOR_STANDARD_DEVIATION_TYPES",
"if",
"stddev_type",
"==",
"const",
".",
"StdDev",
".",
"TOTAL",
":",
"stddevs",
".",
"append",
"(",
"np",
".",
"sqrt",
"(",
"(",
"tau",
"**",
"2.",
")",
"+",
"(",
"phi",
"**",
"2.",
")",
")",
"+",
"np",
".",
"zeros",
"(",
"num_sites",
")",
")",
"elif",
"stddev_type",
"==",
"const",
".",
"StdDev",
".",
"INTRA_EVENT",
":",
"stddevs",
".",
"append",
"(",
"phi",
"+",
"np",
".",
"zeros",
"(",
"num_sites",
")",
")",
"elif",
"stddev_type",
"==",
"const",
".",
"StdDev",
".",
"INTER_EVENT",
":",
"stddevs",
".",
"append",
"(",
"tau",
"+",
"np",
".",
"zeros",
"(",
"num_sites",
")",
")",
"return",
"stddevs"
] | Returns the inter- and intra-event and total standard deviations | [
"Returns",
"the",
"inter",
"-",
"and",
"intra",
"-",
"event",
"and",
"total",
"standard",
"deviations"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L371-L407 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_stddevs_pga | def _get_stddevs_pga(self, C, rup):
"""
Returns the inter- and intra-event coefficients for PGA
"""
tau_lnpga_b = self._get_taulny(C, rup.mag)
phi_lnpga_b = np.sqrt(self._get_philny(C, rup.mag) ** 2. -
self.CONSTS["philnAF"] ** 2.)
return tau_lnpga_b, phi_lnpga_b | python | def _get_stddevs_pga(self, C, rup):
tau_lnpga_b = self._get_taulny(C, rup.mag)
phi_lnpga_b = np.sqrt(self._get_philny(C, rup.mag) ** 2. -
self.CONSTS["philnAF"] ** 2.)
return tau_lnpga_b, phi_lnpga_b | [
"def",
"_get_stddevs_pga",
"(",
"self",
",",
"C",
",",
"rup",
")",
":",
"tau_lnpga_b",
"=",
"self",
".",
"_get_taulny",
"(",
"C",
",",
"rup",
".",
"mag",
")",
"phi_lnpga_b",
"=",
"np",
".",
"sqrt",
"(",
"self",
".",
"_get_philny",
"(",
"C",
",",
"rup",
".",
"mag",
")",
"**",
"2.",
"-",
"self",
".",
"CONSTS",
"[",
"\"philnAF\"",
"]",
"**",
"2.",
")",
"return",
"tau_lnpga_b",
",",
"phi_lnpga_b"
] | Returns the inter- and intra-event coefficients for PGA | [
"Returns",
"the",
"inter",
"-",
"and",
"intra",
"-",
"event",
"coefficients",
"for",
"PGA"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L409-L416 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_taulny | def _get_taulny(self, C, mag):
"""
Returns the inter-event random effects coefficient (tau)
Equation 28.
"""
if mag <= 4.5:
return C["tau1"]
elif mag >= 5.5:
return C["tau2"]
else:
return C["tau2"] + (C["tau1"] - C["tau2"]) * (5.5 - mag) | python | def _get_taulny(self, C, mag):
if mag <= 4.5:
return C["tau1"]
elif mag >= 5.5:
return C["tau2"]
else:
return C["tau2"] + (C["tau1"] - C["tau2"]) * (5.5 - mag) | [
"def",
"_get_taulny",
"(",
"self",
",",
"C",
",",
"mag",
")",
":",
"if",
"mag",
"<=",
"4.5",
":",
"return",
"C",
"[",
"\"tau1\"",
"]",
"elif",
"mag",
">=",
"5.5",
":",
"return",
"C",
"[",
"\"tau2\"",
"]",
"else",
":",
"return",
"C",
"[",
"\"tau2\"",
"]",
"+",
"(",
"C",
"[",
"\"tau1\"",
"]",
"-",
"C",
"[",
"\"tau2\"",
"]",
")",
"*",
"(",
"5.5",
"-",
"mag",
")"
] | Returns the inter-event random effects coefficient (tau)
Equation 28. | [
"Returns",
"the",
"inter",
"-",
"event",
"random",
"effects",
"coefficient",
"(",
"tau",
")",
"Equation",
"28",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L418-L428 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_philny | def _get_philny(self, C, mag):
"""
Returns the intra-event random effects coefficient (phi)
Equation 28.
"""
if mag <= 4.5:
return C["phi1"]
elif mag >= 5.5:
return C["phi2"]
else:
return C["phi2"] + (C["phi1"] - C["phi2"]) * (5.5 - mag) | python | def _get_philny(self, C, mag):
if mag <= 4.5:
return C["phi1"]
elif mag >= 5.5:
return C["phi2"]
else:
return C["phi2"] + (C["phi1"] - C["phi2"]) * (5.5 - mag) | [
"def",
"_get_philny",
"(",
"self",
",",
"C",
",",
"mag",
")",
":",
"if",
"mag",
"<=",
"4.5",
":",
"return",
"C",
"[",
"\"phi1\"",
"]",
"elif",
"mag",
">=",
"5.5",
":",
"return",
"C",
"[",
"\"phi2\"",
"]",
"else",
":",
"return",
"C",
"[",
"\"phi2\"",
"]",
"+",
"(",
"C",
"[",
"\"phi1\"",
"]",
"-",
"C",
"[",
"\"phi2\"",
"]",
")",
"*",
"(",
"5.5",
"-",
"mag",
")"
] | Returns the intra-event random effects coefficient (phi)
Equation 28. | [
"Returns",
"the",
"intra",
"-",
"event",
"random",
"effects",
"coefficient",
"(",
"phi",
")",
"Equation",
"28",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L430-L440 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2014.py | CampbellBozorgnia2014._get_alpha | def _get_alpha(self, C, vs30, pga_rock):
"""
Returns the alpha, the linearised functional relationship between the
site amplification and the PGA on rock. Equation 31.
"""
alpha = np.zeros(len(pga_rock))
idx = vs30 < C["k1"]
if np.any(idx):
af1 = pga_rock[idx] +\
self.CONSTS["c"] * ((vs30[idx] / C["k1"]) ** self.CONSTS["n"])
af2 = pga_rock[idx] + self.CONSTS["c"]
alpha[idx] = C["k2"] * pga_rock[idx] * ((1.0 / af1) - (1.0 / af2))
return alpha | python | def _get_alpha(self, C, vs30, pga_rock):
alpha = np.zeros(len(pga_rock))
idx = vs30 < C["k1"]
if np.any(idx):
af1 = pga_rock[idx] +\
self.CONSTS["c"] * ((vs30[idx] / C["k1"]) ** self.CONSTS["n"])
af2 = pga_rock[idx] + self.CONSTS["c"]
alpha[idx] = C["k2"] * pga_rock[idx] * ((1.0 / af1) - (1.0 / af2))
return alpha | [
"def",
"_get_alpha",
"(",
"self",
",",
"C",
",",
"vs30",
",",
"pga_rock",
")",
":",
"alpha",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"pga_rock",
")",
")",
"idx",
"=",
"vs30",
"<",
"C",
"[",
"\"k1\"",
"]",
"if",
"np",
".",
"any",
"(",
"idx",
")",
":",
"af1",
"=",
"pga_rock",
"[",
"idx",
"]",
"+",
"self",
".",
"CONSTS",
"[",
"\"c\"",
"]",
"*",
"(",
"(",
"vs30",
"[",
"idx",
"]",
"/",
"C",
"[",
"\"k1\"",
"]",
")",
"**",
"self",
".",
"CONSTS",
"[",
"\"n\"",
"]",
")",
"af2",
"=",
"pga_rock",
"[",
"idx",
"]",
"+",
"self",
".",
"CONSTS",
"[",
"\"c\"",
"]",
"alpha",
"[",
"idx",
"]",
"=",
"C",
"[",
"\"k2\"",
"]",
"*",
"pga_rock",
"[",
"idx",
"]",
"*",
"(",
"(",
"1.0",
"/",
"af1",
")",
"-",
"(",
"1.0",
"/",
"af2",
")",
")",
"return",
"alpha"
] | Returns the alpha, the linearised functional relationship between the
site amplification and the PGA on rock. Equation 31. | [
"Returns",
"the",
"alpha",
"the",
"linearised",
"functional",
"relationship",
"between",
"the",
"site",
"amplification",
"and",
"the",
"PGA",
"on",
"rock",
".",
"Equation",
"31",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2014.py#L442-L454 |
gem/oq-engine | openquake/hmtk/seismicity/utils.py | decimal_year | def decimal_year(year, month, day):
"""
Allows to calculate the decimal year for a vector of dates
(TODO this is legacy code kept to maintain comparability with previous
declustering algorithms!)
:param year: year column from catalogue matrix
:type year: numpy.ndarray
:param month: month column from catalogue matrix
:type month: numpy.ndarray
:param day: day column from catalogue matrix
:type day: numpy.ndarray
:returns: decimal year column
:rtype: numpy.ndarray
"""
marker = np.array([0., 31., 59., 90., 120., 151., 181.,
212., 243., 273., 304., 334.])
tmonth = (month - 1).astype(int)
day_count = marker[tmonth] + day - 1.
dec_year = year + (day_count / 365.)
return dec_year | python | def decimal_year(year, month, day):
marker = np.array([0., 31., 59., 90., 120., 151., 181.,
212., 243., 273., 304., 334.])
tmonth = (month - 1).astype(int)
day_count = marker[tmonth] + day - 1.
dec_year = year + (day_count / 365.)
return dec_year | [
"def",
"decimal_year",
"(",
"year",
",",
"month",
",",
"day",
")",
":",
"marker",
"=",
"np",
".",
"array",
"(",
"[",
"0.",
",",
"31.",
",",
"59.",
",",
"90.",
",",
"120.",
",",
"151.",
",",
"181.",
",",
"212.",
",",
"243.",
",",
"273.",
",",
"304.",
",",
"334.",
"]",
")",
"tmonth",
"=",
"(",
"month",
"-",
"1",
")",
".",
"astype",
"(",
"int",
")",
"day_count",
"=",
"marker",
"[",
"tmonth",
"]",
"+",
"day",
"-",
"1.",
"dec_year",
"=",
"year",
"+",
"(",
"day_count",
"/",
"365.",
")",
"return",
"dec_year"
] | Allows to calculate the decimal year for a vector of dates
(TODO this is legacy code kept to maintain comparability with previous
declustering algorithms!)
:param year: year column from catalogue matrix
:type year: numpy.ndarray
:param month: month column from catalogue matrix
:type month: numpy.ndarray
:param day: day column from catalogue matrix
:type day: numpy.ndarray
:returns: decimal year column
:rtype: numpy.ndarray | [
"Allows",
"to",
"calculate",
"the",
"decimal",
"year",
"for",
"a",
"vector",
"of",
"dates",
"(",
"TODO",
"this",
"is",
"legacy",
"code",
"kept",
"to",
"maintain",
"comparability",
"with",
"previous",
"declustering",
"algorithms!",
")"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/utils.py#L105-L126 |
gem/oq-engine | openquake/hmtk/seismicity/utils.py | decimal_time | def decimal_time(year, month, day, hour, minute, second):
"""
Returns the full time as a decimal value
:param year:
Year of events (integer numpy.ndarray)
:param month:
Month of events (integer numpy.ndarray)
:param day:
Days of event (integer numpy.ndarray)
:param hour:
Hour of event (integer numpy.ndarray)
:param minute:
Minute of event (integer numpy.ndarray)
:param second:
Second of event (float numpy.ndarray)
:returns decimal_time:
Decimal representation of the time (as numpy.ndarray)
"""
tmo = np.ones_like(year, dtype=int)
tda = np.ones_like(year, dtype=int)
tho = np.zeros_like(year, dtype=int)
tmi = np.zeros_like(year, dtype=int)
tse = np.zeros_like(year, dtype=float)
#
# Checking inputs
if any(month < 1) or any(month > 12):
raise ValueError('Month must be in [1, 12]')
if any(day < 1) or any(day > 31):
raise ValueError('Day must be in [1, 31]')
if any(hour < 0) or any(hour > 24):
raise ValueError('Hour must be in [0, 24]')
if any(minute < 0) or any(minute > 60):
raise ValueError('Minute must be in [0, 60]')
if any(second < 0) or any(second > 60):
raise ValueError('Second must be in [0, 60]')
#
# Initialising values
if any(month):
tmo = month
if any(day):
tda = day
if any(hour):
tho = hour
if any(minute):
tmi = minute
if any(second):
tse = second
#
# Computing decimal
tmonth = tmo - 1
day_count = MARKER_NORMAL[tmonth] + tda - 1
id_leap = leap_check(year)
leap_loc = np.where(id_leap)[0]
day_count[leap_loc] = MARKER_LEAP[tmonth[leap_loc]] + tda[leap_loc] - 1
year_secs = ((day_count.astype(float) * SECONDS_PER_DAY) + tse +
(60. * tmi.astype(float)) + (3600. * tho.astype(float)))
dtime = year.astype(float) + (year_secs / (365. * 24. * 3600.))
dtime[leap_loc] = year[leap_loc].astype(float) + \
(year_secs[leap_loc] / (366. * 24. * 3600.))
return dtime | python | def decimal_time(year, month, day, hour, minute, second):
tmo = np.ones_like(year, dtype=int)
tda = np.ones_like(year, dtype=int)
tho = np.zeros_like(year, dtype=int)
tmi = np.zeros_like(year, dtype=int)
tse = np.zeros_like(year, dtype=float)
if any(month < 1) or any(month > 12):
raise ValueError('Month must be in [1, 12]')
if any(day < 1) or any(day > 31):
raise ValueError('Day must be in [1, 31]')
if any(hour < 0) or any(hour > 24):
raise ValueError('Hour must be in [0, 24]')
if any(minute < 0) or any(minute > 60):
raise ValueError('Minute must be in [0, 60]')
if any(second < 0) or any(second > 60):
raise ValueError('Second must be in [0, 60]')
if any(month):
tmo = month
if any(day):
tda = day
if any(hour):
tho = hour
if any(minute):
tmi = minute
if any(second):
tse = second
tmonth = tmo - 1
day_count = MARKER_NORMAL[tmonth] + tda - 1
id_leap = leap_check(year)
leap_loc = np.where(id_leap)[0]
day_count[leap_loc] = MARKER_LEAP[tmonth[leap_loc]] + tda[leap_loc] - 1
year_secs = ((day_count.astype(float) * SECONDS_PER_DAY) + tse +
(60. * tmi.astype(float)) + (3600. * tho.astype(float)))
dtime = year.astype(float) + (year_secs / (365. * 24. * 3600.))
dtime[leap_loc] = year[leap_loc].astype(float) + \
(year_secs[leap_loc] / (366. * 24. * 3600.))
return dtime | [
"def",
"decimal_time",
"(",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"minute",
",",
"second",
")",
":",
"tmo",
"=",
"np",
".",
"ones_like",
"(",
"year",
",",
"dtype",
"=",
"int",
")",
"tda",
"=",
"np",
".",
"ones_like",
"(",
"year",
",",
"dtype",
"=",
"int",
")",
"tho",
"=",
"np",
".",
"zeros_like",
"(",
"year",
",",
"dtype",
"=",
"int",
")",
"tmi",
"=",
"np",
".",
"zeros_like",
"(",
"year",
",",
"dtype",
"=",
"int",
")",
"tse",
"=",
"np",
".",
"zeros_like",
"(",
"year",
",",
"dtype",
"=",
"float",
")",
"#",
"# Checking inputs",
"if",
"any",
"(",
"month",
"<",
"1",
")",
"or",
"any",
"(",
"month",
">",
"12",
")",
":",
"raise",
"ValueError",
"(",
"'Month must be in [1, 12]'",
")",
"if",
"any",
"(",
"day",
"<",
"1",
")",
"or",
"any",
"(",
"day",
">",
"31",
")",
":",
"raise",
"ValueError",
"(",
"'Day must be in [1, 31]'",
")",
"if",
"any",
"(",
"hour",
"<",
"0",
")",
"or",
"any",
"(",
"hour",
">",
"24",
")",
":",
"raise",
"ValueError",
"(",
"'Hour must be in [0, 24]'",
")",
"if",
"any",
"(",
"minute",
"<",
"0",
")",
"or",
"any",
"(",
"minute",
">",
"60",
")",
":",
"raise",
"ValueError",
"(",
"'Minute must be in [0, 60]'",
")",
"if",
"any",
"(",
"second",
"<",
"0",
")",
"or",
"any",
"(",
"second",
">",
"60",
")",
":",
"raise",
"ValueError",
"(",
"'Second must be in [0, 60]'",
")",
"#",
"# Initialising values",
"if",
"any",
"(",
"month",
")",
":",
"tmo",
"=",
"month",
"if",
"any",
"(",
"day",
")",
":",
"tda",
"=",
"day",
"if",
"any",
"(",
"hour",
")",
":",
"tho",
"=",
"hour",
"if",
"any",
"(",
"minute",
")",
":",
"tmi",
"=",
"minute",
"if",
"any",
"(",
"second",
")",
":",
"tse",
"=",
"second",
"#",
"# Computing decimal",
"tmonth",
"=",
"tmo",
"-",
"1",
"day_count",
"=",
"MARKER_NORMAL",
"[",
"tmonth",
"]",
"+",
"tda",
"-",
"1",
"id_leap",
"=",
"leap_check",
"(",
"year",
")",
"leap_loc",
"=",
"np",
".",
"where",
"(",
"id_leap",
")",
"[",
"0",
"]",
"day_count",
"[",
"leap_loc",
"]",
"=",
"MARKER_LEAP",
"[",
"tmonth",
"[",
"leap_loc",
"]",
"]",
"+",
"tda",
"[",
"leap_loc",
"]",
"-",
"1",
"year_secs",
"=",
"(",
"(",
"day_count",
".",
"astype",
"(",
"float",
")",
"*",
"SECONDS_PER_DAY",
")",
"+",
"tse",
"+",
"(",
"60.",
"*",
"tmi",
".",
"astype",
"(",
"float",
")",
")",
"+",
"(",
"3600.",
"*",
"tho",
".",
"astype",
"(",
"float",
")",
")",
")",
"dtime",
"=",
"year",
".",
"astype",
"(",
"float",
")",
"+",
"(",
"year_secs",
"/",
"(",
"365.",
"*",
"24.",
"*",
"3600.",
")",
")",
"dtime",
"[",
"leap_loc",
"]",
"=",
"year",
"[",
"leap_loc",
"]",
".",
"astype",
"(",
"float",
")",
"+",
"(",
"year_secs",
"[",
"leap_loc",
"]",
"/",
"(",
"366.",
"*",
"24.",
"*",
"3600.",
")",
")",
"return",
"dtime"
] | Returns the full time as a decimal value
:param year:
Year of events (integer numpy.ndarray)
:param month:
Month of events (integer numpy.ndarray)
:param day:
Days of event (integer numpy.ndarray)
:param hour:
Hour of event (integer numpy.ndarray)
:param minute:
Minute of event (integer numpy.ndarray)
:param second:
Second of event (float numpy.ndarray)
:returns decimal_time:
Decimal representation of the time (as numpy.ndarray) | [
"Returns",
"the",
"full",
"time",
"as",
"a",
"decimal",
"value"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/utils.py#L137-L197 |
gem/oq-engine | openquake/hmtk/seismicity/utils.py | haversine | def haversine(lon1, lat1, lon2, lat2, radians=False, earth_rad=6371.227):
"""
Allows to calculate geographical distance
using the haversine formula.
:param lon1: longitude of the first set of locations
:type lon1: numpy.ndarray
:param lat1: latitude of the frist set of locations
:type lat1: numpy.ndarray
:param lon2: longitude of the second set of locations
:type lon2: numpy.float64
:param lat2: latitude of the second set of locations
:type lat2: numpy.float64
:keyword radians: states if locations are given in terms of radians
:type radians: bool
:keyword earth_rad: radius of the earth in km
:type earth_rad: float
:returns: geographical distance in km
:rtype: numpy.ndarray
"""
if not radians:
cfact = np.pi / 180.
lon1 = cfact * lon1
lat1 = cfact * lat1
lon2 = cfact * lon2
lat2 = cfact * lat2
# Number of locations in each set of points
if not np.shape(lon1):
nlocs1 = 1
lon1 = np.array([lon1])
lat1 = np.array([lat1])
else:
nlocs1 = np.max(np.shape(lon1))
if not np.shape(lon2):
nlocs2 = 1
lon2 = np.array([lon2])
lat2 = np.array([lat2])
else:
nlocs2 = np.max(np.shape(lon2))
# Pre-allocate array
distance = np.zeros((nlocs1, nlocs2))
i = 0
while i < nlocs2:
# Perform distance calculation
dlat = lat1 - lat2[i]
dlon = lon1 - lon2[i]
aval = (np.sin(dlat / 2.) ** 2.) + (np.cos(lat1) * np.cos(lat2[i]) *
(np.sin(dlon / 2.) ** 2.))
distance[:, i] = (2. * earth_rad * np.arctan2(np.sqrt(aval),
np.sqrt(1 - aval))).T
i += 1
return distance | python | def haversine(lon1, lat1, lon2, lat2, radians=False, earth_rad=6371.227):
if not radians:
cfact = np.pi / 180.
lon1 = cfact * lon1
lat1 = cfact * lat1
lon2 = cfact * lon2
lat2 = cfact * lat2
if not np.shape(lon1):
nlocs1 = 1
lon1 = np.array([lon1])
lat1 = np.array([lat1])
else:
nlocs1 = np.max(np.shape(lon1))
if not np.shape(lon2):
nlocs2 = 1
lon2 = np.array([lon2])
lat2 = np.array([lat2])
else:
nlocs2 = np.max(np.shape(lon2))
distance = np.zeros((nlocs1, nlocs2))
i = 0
while i < nlocs2:
dlat = lat1 - lat2[i]
dlon = lon1 - lon2[i]
aval = (np.sin(dlat / 2.) ** 2.) + (np.cos(lat1) * np.cos(lat2[i]) *
(np.sin(dlon / 2.) ** 2.))
distance[:, i] = (2. * earth_rad * np.arctan2(np.sqrt(aval),
np.sqrt(1 - aval))).T
i += 1
return distance | [
"def",
"haversine",
"(",
"lon1",
",",
"lat1",
",",
"lon2",
",",
"lat2",
",",
"radians",
"=",
"False",
",",
"earth_rad",
"=",
"6371.227",
")",
":",
"if",
"not",
"radians",
":",
"cfact",
"=",
"np",
".",
"pi",
"/",
"180.",
"lon1",
"=",
"cfact",
"*",
"lon1",
"lat1",
"=",
"cfact",
"*",
"lat1",
"lon2",
"=",
"cfact",
"*",
"lon2",
"lat2",
"=",
"cfact",
"*",
"lat2",
"# Number of locations in each set of points",
"if",
"not",
"np",
".",
"shape",
"(",
"lon1",
")",
":",
"nlocs1",
"=",
"1",
"lon1",
"=",
"np",
".",
"array",
"(",
"[",
"lon1",
"]",
")",
"lat1",
"=",
"np",
".",
"array",
"(",
"[",
"lat1",
"]",
")",
"else",
":",
"nlocs1",
"=",
"np",
".",
"max",
"(",
"np",
".",
"shape",
"(",
"lon1",
")",
")",
"if",
"not",
"np",
".",
"shape",
"(",
"lon2",
")",
":",
"nlocs2",
"=",
"1",
"lon2",
"=",
"np",
".",
"array",
"(",
"[",
"lon2",
"]",
")",
"lat2",
"=",
"np",
".",
"array",
"(",
"[",
"lat2",
"]",
")",
"else",
":",
"nlocs2",
"=",
"np",
".",
"max",
"(",
"np",
".",
"shape",
"(",
"lon2",
")",
")",
"# Pre-allocate array",
"distance",
"=",
"np",
".",
"zeros",
"(",
"(",
"nlocs1",
",",
"nlocs2",
")",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"nlocs2",
":",
"# Perform distance calculation",
"dlat",
"=",
"lat1",
"-",
"lat2",
"[",
"i",
"]",
"dlon",
"=",
"lon1",
"-",
"lon2",
"[",
"i",
"]",
"aval",
"=",
"(",
"np",
".",
"sin",
"(",
"dlat",
"/",
"2.",
")",
"**",
"2.",
")",
"+",
"(",
"np",
".",
"cos",
"(",
"lat1",
")",
"*",
"np",
".",
"cos",
"(",
"lat2",
"[",
"i",
"]",
")",
"*",
"(",
"np",
".",
"sin",
"(",
"dlon",
"/",
"2.",
")",
"**",
"2.",
")",
")",
"distance",
"[",
":",
",",
"i",
"]",
"=",
"(",
"2.",
"*",
"earth_rad",
"*",
"np",
".",
"arctan2",
"(",
"np",
".",
"sqrt",
"(",
"aval",
")",
",",
"np",
".",
"sqrt",
"(",
"1",
"-",
"aval",
")",
")",
")",
".",
"T",
"i",
"+=",
"1",
"return",
"distance"
] | Allows to calculate geographical distance
using the haversine formula.
:param lon1: longitude of the first set of locations
:type lon1: numpy.ndarray
:param lat1: latitude of the frist set of locations
:type lat1: numpy.ndarray
:param lon2: longitude of the second set of locations
:type lon2: numpy.float64
:param lat2: latitude of the second set of locations
:type lat2: numpy.float64
:keyword radians: states if locations are given in terms of radians
:type radians: bool
:keyword earth_rad: radius of the earth in km
:type earth_rad: float
:returns: geographical distance in km
:rtype: numpy.ndarray | [
"Allows",
"to",
"calculate",
"geographical",
"distance",
"using",
"the",
"haversine",
"formula",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/utils.py#L200-L252 |
gem/oq-engine | openquake/hmtk/seismicity/utils.py | greg2julian | def greg2julian(year, month, day, hour, minute, second):
"""
Function to convert a date from Gregorian to Julian format
:param year:
Year of events (integer numpy.ndarray)
:param month:
Month of events (integer numpy.ndarray)
:param day:
Days of event (integer numpy.ndarray)
:param hour:
Hour of event (integer numpy.ndarray)
:param minute:
Minute of event (integer numpy.ndarray)
:param second:
Second of event (float numpy.ndarray)
:returns julian_time:
Julian representation of the time (as float numpy.ndarray)
"""
year = year.astype(float)
month = month.astype(float)
day = day.astype(float)
timeut = hour.astype(float) + (minute.astype(float) / 60.0) + \
(second / 3600.0)
julian_time = ((367.0 * year) -
np.floor(
7.0 * (year + np.floor((month + 9.0) / 12.0)) / 4.0) -
np.floor(3.0 *
(np.floor((year + (month - 9.0) / 7.0) / 100.0) +
1.0) / 4.0) +
np.floor((275.0 * month) / 9.0) +
day + 1721028.5 + (timeut / 24.0))
return julian_time | python | def greg2julian(year, month, day, hour, minute, second):
year = year.astype(float)
month = month.astype(float)
day = day.astype(float)
timeut = hour.astype(float) + (minute.astype(float) / 60.0) + \
(second / 3600.0)
julian_time = ((367.0 * year) -
np.floor(
7.0 * (year + np.floor((month + 9.0) / 12.0)) / 4.0) -
np.floor(3.0 *
(np.floor((year + (month - 9.0) / 7.0) / 100.0) +
1.0) / 4.0) +
np.floor((275.0 * month) / 9.0) +
day + 1721028.5 + (timeut / 24.0))
return julian_time | [
"def",
"greg2julian",
"(",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"minute",
",",
"second",
")",
":",
"year",
"=",
"year",
".",
"astype",
"(",
"float",
")",
"month",
"=",
"month",
".",
"astype",
"(",
"float",
")",
"day",
"=",
"day",
".",
"astype",
"(",
"float",
")",
"timeut",
"=",
"hour",
".",
"astype",
"(",
"float",
")",
"+",
"(",
"minute",
".",
"astype",
"(",
"float",
")",
"/",
"60.0",
")",
"+",
"(",
"second",
"/",
"3600.0",
")",
"julian_time",
"=",
"(",
"(",
"367.0",
"*",
"year",
")",
"-",
"np",
".",
"floor",
"(",
"7.0",
"*",
"(",
"year",
"+",
"np",
".",
"floor",
"(",
"(",
"month",
"+",
"9.0",
")",
"/",
"12.0",
")",
")",
"/",
"4.0",
")",
"-",
"np",
".",
"floor",
"(",
"3.0",
"*",
"(",
"np",
".",
"floor",
"(",
"(",
"year",
"+",
"(",
"month",
"-",
"9.0",
")",
"/",
"7.0",
")",
"/",
"100.0",
")",
"+",
"1.0",
")",
"/",
"4.0",
")",
"+",
"np",
".",
"floor",
"(",
"(",
"275.0",
"*",
"month",
")",
"/",
"9.0",
")",
"+",
"day",
"+",
"1721028.5",
"+",
"(",
"timeut",
"/",
"24.0",
")",
")",
"return",
"julian_time"
] | Function to convert a date from Gregorian to Julian format
:param year:
Year of events (integer numpy.ndarray)
:param month:
Month of events (integer numpy.ndarray)
:param day:
Days of event (integer numpy.ndarray)
:param hour:
Hour of event (integer numpy.ndarray)
:param minute:
Minute of event (integer numpy.ndarray)
:param second:
Second of event (float numpy.ndarray)
:returns julian_time:
Julian representation of the time (as float numpy.ndarray) | [
"Function",
"to",
"convert",
"a",
"date",
"from",
"Gregorian",
"to",
"Julian",
"format"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/utils.py#L255-L289 |
gem/oq-engine | openquake/hmtk/seismicity/utils.py | piecewise_linear_scalar | def piecewise_linear_scalar(params, xval):
'''Piecewise linear function for a scalar variable xval (float).
:param params:
Piecewise linear parameters (numpy.ndarray) in the following form:
[slope_i,... slope_n, turning_point_i, ..., turning_point_n, intercept]
Length params === 2 * number_segments, e.g.
[slope_1, slope_2, slope_3, turning_point1, turning_point_2, intercept]
:param xval:
Value for evaluation of function (float)
:returns:
Piecewise linear function evaluated at point xval (float)
'''
n_params = len(params)
n_seg, remainder = divmod(n_params, 2)
if remainder:
raise ValueError(
'Piecewise Function requires 2 * nsegments parameters')
if n_seg == 1:
return params[1] + params[0] * xval
gradients = params[0:n_seg]
turning_points = params[n_seg: -1]
c_val = np.array([params[-1]])
for iloc in range(1, n_seg):
c_val = np.hstack(
[c_val, (c_val[iloc - 1] + gradients[iloc - 1] *
turning_points[iloc - 1]) - (gradients[iloc] *
turning_points[iloc - 1])])
if xval <= turning_points[0]:
return gradients[0] * xval + c_val[0]
elif xval > turning_points[-1]:
return gradients[-1] * xval + c_val[-1]
else:
select = np.nonzero(turning_points <= xval)[0][-1] + 1
return gradients[select] * xval + c_val[select] | python | def piecewise_linear_scalar(params, xval):
n_params = len(params)
n_seg, remainder = divmod(n_params, 2)
if remainder:
raise ValueError(
'Piecewise Function requires 2 * nsegments parameters')
if n_seg == 1:
return params[1] + params[0] * xval
gradients = params[0:n_seg]
turning_points = params[n_seg: -1]
c_val = np.array([params[-1]])
for iloc in range(1, n_seg):
c_val = np.hstack(
[c_val, (c_val[iloc - 1] + gradients[iloc - 1] *
turning_points[iloc - 1]) - (gradients[iloc] *
turning_points[iloc - 1])])
if xval <= turning_points[0]:
return gradients[0] * xval + c_val[0]
elif xval > turning_points[-1]:
return gradients[-1] * xval + c_val[-1]
else:
select = np.nonzero(turning_points <= xval)[0][-1] + 1
return gradients[select] * xval + c_val[select] | [
"def",
"piecewise_linear_scalar",
"(",
"params",
",",
"xval",
")",
":",
"n_params",
"=",
"len",
"(",
"params",
")",
"n_seg",
",",
"remainder",
"=",
"divmod",
"(",
"n_params",
",",
"2",
")",
"if",
"remainder",
":",
"raise",
"ValueError",
"(",
"'Piecewise Function requires 2 * nsegments parameters'",
")",
"if",
"n_seg",
"==",
"1",
":",
"return",
"params",
"[",
"1",
"]",
"+",
"params",
"[",
"0",
"]",
"*",
"xval",
"gradients",
"=",
"params",
"[",
"0",
":",
"n_seg",
"]",
"turning_points",
"=",
"params",
"[",
"n_seg",
":",
"-",
"1",
"]",
"c_val",
"=",
"np",
".",
"array",
"(",
"[",
"params",
"[",
"-",
"1",
"]",
"]",
")",
"for",
"iloc",
"in",
"range",
"(",
"1",
",",
"n_seg",
")",
":",
"c_val",
"=",
"np",
".",
"hstack",
"(",
"[",
"c_val",
",",
"(",
"c_val",
"[",
"iloc",
"-",
"1",
"]",
"+",
"gradients",
"[",
"iloc",
"-",
"1",
"]",
"*",
"turning_points",
"[",
"iloc",
"-",
"1",
"]",
")",
"-",
"(",
"gradients",
"[",
"iloc",
"]",
"*",
"turning_points",
"[",
"iloc",
"-",
"1",
"]",
")",
"]",
")",
"if",
"xval",
"<=",
"turning_points",
"[",
"0",
"]",
":",
"return",
"gradients",
"[",
"0",
"]",
"*",
"xval",
"+",
"c_val",
"[",
"0",
"]",
"elif",
"xval",
">",
"turning_points",
"[",
"-",
"1",
"]",
":",
"return",
"gradients",
"[",
"-",
"1",
"]",
"*",
"xval",
"+",
"c_val",
"[",
"-",
"1",
"]",
"else",
":",
"select",
"=",
"np",
".",
"nonzero",
"(",
"turning_points",
"<=",
"xval",
")",
"[",
"0",
"]",
"[",
"-",
"1",
"]",
"+",
"1",
"return",
"gradients",
"[",
"select",
"]",
"*",
"xval",
"+",
"c_val",
"[",
"select",
"]"
] | Piecewise linear function for a scalar variable xval (float).
:param params:
Piecewise linear parameters (numpy.ndarray) in the following form:
[slope_i,... slope_n, turning_point_i, ..., turning_point_n, intercept]
Length params === 2 * number_segments, e.g.
[slope_1, slope_2, slope_3, turning_point1, turning_point_2, intercept]
:param xval:
Value for evaluation of function (float)
:returns:
Piecewise linear function evaluated at point xval (float) | [
"Piecewise",
"linear",
"function",
"for",
"a",
"scalar",
"variable",
"xval",
"(",
"float",
")",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/utils.py#L292-L330 |
gem/oq-engine | openquake/hmtk/seismicity/utils.py | sample_truncated_gaussian_vector | def sample_truncated_gaussian_vector(data, uncertainties, bounds=None):
'''
Samples a Gaussian distribution subject to boundaries on the data
:param numpy.ndarray data:
Vector of N data values
:param numpy.ndarray uncertainties:
Vector of N data uncertainties
:param int number_bootstraps:
Number of bootstrap samples
:param tuple bounds:
(Lower, Upper) bound of data space
'''
nvals = len(data)
if bounds:
# if bounds[0] or (fabs(bounds[0]) < PRECISION):
if bounds[0] is not None:
lower_bound = (bounds[0] - data) / uncertainties
else:
lower_bound = -np.inf * np.ones_like(data)
# if bounds[1] or (fabs(bounds[1]) < PRECISION):
if bounds[1] is not None:
upper_bound = (bounds[1] - data) / uncertainties
else:
upper_bound = np.inf * np.ones_like(data)
sample = hmtk_truncnorm.rvs(lower_bound, upper_bound, size=nvals)
else:
sample = np.random.normal(0., 1., nvals)
return data + uncertainties * sample | python | def sample_truncated_gaussian_vector(data, uncertainties, bounds=None):
nvals = len(data)
if bounds:
if bounds[0] is not None:
lower_bound = (bounds[0] - data) / uncertainties
else:
lower_bound = -np.inf * np.ones_like(data)
if bounds[1] is not None:
upper_bound = (bounds[1] - data) / uncertainties
else:
upper_bound = np.inf * np.ones_like(data)
sample = hmtk_truncnorm.rvs(lower_bound, upper_bound, size=nvals)
else:
sample = np.random.normal(0., 1., nvals)
return data + uncertainties * sample | [
"def",
"sample_truncated_gaussian_vector",
"(",
"data",
",",
"uncertainties",
",",
"bounds",
"=",
"None",
")",
":",
"nvals",
"=",
"len",
"(",
"data",
")",
"if",
"bounds",
":",
"# if bounds[0] or (fabs(bounds[0]) < PRECISION):",
"if",
"bounds",
"[",
"0",
"]",
"is",
"not",
"None",
":",
"lower_bound",
"=",
"(",
"bounds",
"[",
"0",
"]",
"-",
"data",
")",
"/",
"uncertainties",
"else",
":",
"lower_bound",
"=",
"-",
"np",
".",
"inf",
"*",
"np",
".",
"ones_like",
"(",
"data",
")",
"# if bounds[1] or (fabs(bounds[1]) < PRECISION):",
"if",
"bounds",
"[",
"1",
"]",
"is",
"not",
"None",
":",
"upper_bound",
"=",
"(",
"bounds",
"[",
"1",
"]",
"-",
"data",
")",
"/",
"uncertainties",
"else",
":",
"upper_bound",
"=",
"np",
".",
"inf",
"*",
"np",
".",
"ones_like",
"(",
"data",
")",
"sample",
"=",
"hmtk_truncnorm",
".",
"rvs",
"(",
"lower_bound",
",",
"upper_bound",
",",
"size",
"=",
"nvals",
")",
"else",
":",
"sample",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0.",
",",
"1.",
",",
"nvals",
")",
"return",
"data",
"+",
"uncertainties",
"*",
"sample"
] | Samples a Gaussian distribution subject to boundaries on the data
:param numpy.ndarray data:
Vector of N data values
:param numpy.ndarray uncertainties:
Vector of N data uncertainties
:param int number_bootstraps:
Number of bootstrap samples
:param tuple bounds:
(Lower, Upper) bound of data space | [
"Samples",
"a",
"Gaussian",
"distribution",
"subject",
"to",
"boundaries",
"on",
"the",
"data"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/utils.py#L333-L363 |
gem/oq-engine | openquake/hmtk/seismicity/utils.py | hmtk_histogram_1D | def hmtk_histogram_1D(values, intervals, offset=1.0E-10):
"""
So, here's the problem. We tend to refer to certain data (like magnitudes)
rounded to the nearest 0.1 (or similar, i.e. 4.1, 5.7, 8.3 etc.). We also
like our tables to fall on on the same interval, i.e. 3.1, 3.2, 3.3 etc.
We usually assume that the counter should correspond to the low edge,
i.e. 3.1 is in the group 3.1 to 3.2 (i.e. L <= M < U).
Floating point precision can be a bitch! Because when we read in magnitudes
from files 3.1 might be represented as 3.0999999999 or as 3.1000000000001
and this is seemingly random. Similarly, if np.arange() is used to generate
the bin intervals then we see similar floating point problems emerging. As
we are frequently encountering density plots with empty rows or columns
where data should be but isn't because it has been assigned to the wrong
group.
Instead of using numpy's own historgram function we use a slower numpy
version that allows us to offset the intervals by a smaller amount and
ensure that 3.0999999999, 3.0, and 3.10000000001 would fall in the group
3.1 - 3.2!
:param numpy.ndarray values:
Values of data
:param numpy.ndarray intervals:
Data bins
:param float offset:
Small amount to offset the bins for floating point precision
:returns:
Count in each bin (as float)
"""
nbins = len(intervals) - 1
counter = np.zeros(nbins, dtype=float)
x_ints = intervals - offset
for i in range(nbins):
idx = np.logical_and(values >= x_ints[i], values < x_ints[i + 1])
counter[i] += float(np.sum(idx))
return counter | python | def hmtk_histogram_1D(values, intervals, offset=1.0E-10):
nbins = len(intervals) - 1
counter = np.zeros(nbins, dtype=float)
x_ints = intervals - offset
for i in range(nbins):
idx = np.logical_and(values >= x_ints[i], values < x_ints[i + 1])
counter[i] += float(np.sum(idx))
return counter | [
"def",
"hmtk_histogram_1D",
"(",
"values",
",",
"intervals",
",",
"offset",
"=",
"1.0E-10",
")",
":",
"nbins",
"=",
"len",
"(",
"intervals",
")",
"-",
"1",
"counter",
"=",
"np",
".",
"zeros",
"(",
"nbins",
",",
"dtype",
"=",
"float",
")",
"x_ints",
"=",
"intervals",
"-",
"offset",
"for",
"i",
"in",
"range",
"(",
"nbins",
")",
":",
"idx",
"=",
"np",
".",
"logical_and",
"(",
"values",
">=",
"x_ints",
"[",
"i",
"]",
",",
"values",
"<",
"x_ints",
"[",
"i",
"+",
"1",
"]",
")",
"counter",
"[",
"i",
"]",
"+=",
"float",
"(",
"np",
".",
"sum",
"(",
"idx",
")",
")",
"return",
"counter"
] | So, here's the problem. We tend to refer to certain data (like magnitudes)
rounded to the nearest 0.1 (or similar, i.e. 4.1, 5.7, 8.3 etc.). We also
like our tables to fall on on the same interval, i.e. 3.1, 3.2, 3.3 etc.
We usually assume that the counter should correspond to the low edge,
i.e. 3.1 is in the group 3.1 to 3.2 (i.e. L <= M < U).
Floating point precision can be a bitch! Because when we read in magnitudes
from files 3.1 might be represented as 3.0999999999 or as 3.1000000000001
and this is seemingly random. Similarly, if np.arange() is used to generate
the bin intervals then we see similar floating point problems emerging. As
we are frequently encountering density plots with empty rows or columns
where data should be but isn't because it has been assigned to the wrong
group.
Instead of using numpy's own historgram function we use a slower numpy
version that allows us to offset the intervals by a smaller amount and
ensure that 3.0999999999, 3.0, and 3.10000000001 would fall in the group
3.1 - 3.2!
:param numpy.ndarray values:
Values of data
:param numpy.ndarray intervals:
Data bins
:param float offset:
Small amount to offset the bins for floating point precision
:returns:
Count in each bin (as float) | [
"So",
"here",
"s",
"the",
"problem",
".",
"We",
"tend",
"to",
"refer",
"to",
"certain",
"data",
"(",
"like",
"magnitudes",
")",
"rounded",
"to",
"the",
"nearest",
"0",
".",
"1",
"(",
"or",
"similar",
"i",
".",
"e",
".",
"4",
".",
"1",
"5",
".",
"7",
"8",
".",
"3",
"etc",
".",
")",
".",
"We",
"also",
"like",
"our",
"tables",
"to",
"fall",
"on",
"on",
"the",
"same",
"interval",
"i",
".",
"e",
".",
"3",
".",
"1",
"3",
".",
"2",
"3",
".",
"3",
"etc",
".",
"We",
"usually",
"assume",
"that",
"the",
"counter",
"should",
"correspond",
"to",
"the",
"low",
"edge",
"i",
".",
"e",
".",
"3",
".",
"1",
"is",
"in",
"the",
"group",
"3",
".",
"1",
"to",
"3",
".",
"2",
"(",
"i",
".",
"e",
".",
"L",
"<",
"=",
"M",
"<",
"U",
")",
".",
"Floating",
"point",
"precision",
"can",
"be",
"a",
"bitch!",
"Because",
"when",
"we",
"read",
"in",
"magnitudes",
"from",
"files",
"3",
".",
"1",
"might",
"be",
"represented",
"as",
"3",
".",
"0999999999",
"or",
"as",
"3",
".",
"1000000000001",
"and",
"this",
"is",
"seemingly",
"random",
".",
"Similarly",
"if",
"np",
".",
"arange",
"()",
"is",
"used",
"to",
"generate",
"the",
"bin",
"intervals",
"then",
"we",
"see",
"similar",
"floating",
"point",
"problems",
"emerging",
".",
"As",
"we",
"are",
"frequently",
"encountering",
"density",
"plots",
"with",
"empty",
"rows",
"or",
"columns",
"where",
"data",
"should",
"be",
"but",
"isn",
"t",
"because",
"it",
"has",
"been",
"assigned",
"to",
"the",
"wrong",
"group",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/utils.py#L366-L401 |
gem/oq-engine | openquake/hmtk/seismicity/utils.py | hmtk_histogram_2D | def hmtk_histogram_2D(xvalues, yvalues, bins, x_offset=1.0E-10,
y_offset=1.0E-10):
"""
See the explanation for the 1D case - now applied to 2D.
:param numpy.ndarray xvalues:
Values of x-data
:param numpy.ndarray yvalues:
Values of y-data
:param tuple bins:
Tuple containing bin intervals for x-data and y-data (as numpy arrays)
:param float x_offset:
Small amount to offset the x-bins for floating point precision
:param float y_offset:
Small amount to offset the y-bins for floating point precision
:returns:
Count in each bin (as float)
"""
xbins, ybins = (bins[0] - x_offset, bins[1] - y_offset)
n_x = len(xbins) - 1
n_y = len(ybins) - 1
counter = np.zeros([n_y, n_x], dtype=float)
for j in range(n_y):
y_idx = np.logical_and(yvalues >= ybins[j], yvalues < ybins[j + 1])
x_vals = xvalues[y_idx]
for i in range(n_x):
idx = np.logical_and(x_vals >= xbins[i], x_vals < xbins[i + 1])
counter[j, i] += float(np.sum(idx))
return counter.T | python | def hmtk_histogram_2D(xvalues, yvalues, bins, x_offset=1.0E-10,
y_offset=1.0E-10):
xbins, ybins = (bins[0] - x_offset, bins[1] - y_offset)
n_x = len(xbins) - 1
n_y = len(ybins) - 1
counter = np.zeros([n_y, n_x], dtype=float)
for j in range(n_y):
y_idx = np.logical_and(yvalues >= ybins[j], yvalues < ybins[j + 1])
x_vals = xvalues[y_idx]
for i in range(n_x):
idx = np.logical_and(x_vals >= xbins[i], x_vals < xbins[i + 1])
counter[j, i] += float(np.sum(idx))
return counter.T | [
"def",
"hmtk_histogram_2D",
"(",
"xvalues",
",",
"yvalues",
",",
"bins",
",",
"x_offset",
"=",
"1.0E-10",
",",
"y_offset",
"=",
"1.0E-10",
")",
":",
"xbins",
",",
"ybins",
"=",
"(",
"bins",
"[",
"0",
"]",
"-",
"x_offset",
",",
"bins",
"[",
"1",
"]",
"-",
"y_offset",
")",
"n_x",
"=",
"len",
"(",
"xbins",
")",
"-",
"1",
"n_y",
"=",
"len",
"(",
"ybins",
")",
"-",
"1",
"counter",
"=",
"np",
".",
"zeros",
"(",
"[",
"n_y",
",",
"n_x",
"]",
",",
"dtype",
"=",
"float",
")",
"for",
"j",
"in",
"range",
"(",
"n_y",
")",
":",
"y_idx",
"=",
"np",
".",
"logical_and",
"(",
"yvalues",
">=",
"ybins",
"[",
"j",
"]",
",",
"yvalues",
"<",
"ybins",
"[",
"j",
"+",
"1",
"]",
")",
"x_vals",
"=",
"xvalues",
"[",
"y_idx",
"]",
"for",
"i",
"in",
"range",
"(",
"n_x",
")",
":",
"idx",
"=",
"np",
".",
"logical_and",
"(",
"x_vals",
">=",
"xbins",
"[",
"i",
"]",
",",
"x_vals",
"<",
"xbins",
"[",
"i",
"+",
"1",
"]",
")",
"counter",
"[",
"j",
",",
"i",
"]",
"+=",
"float",
"(",
"np",
".",
"sum",
"(",
"idx",
")",
")",
"return",
"counter",
".",
"T"
] | See the explanation for the 1D case - now applied to 2D.
:param numpy.ndarray xvalues:
Values of x-data
:param numpy.ndarray yvalues:
Values of y-data
:param tuple bins:
Tuple containing bin intervals for x-data and y-data (as numpy arrays)
:param float x_offset:
Small amount to offset the x-bins for floating point precision
:param float y_offset:
Small amount to offset the y-bins for floating point precision
:returns:
Count in each bin (as float) | [
"See",
"the",
"explanation",
"for",
"the",
"1D",
"case",
"-",
"now",
"applied",
"to",
"2D",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/utils.py#L404-L432 |
gem/oq-engine | openquake/hmtk/seismicity/utils.py | bootstrap_histogram_1D | def bootstrap_histogram_1D(
values, intervals, uncertainties=None,
normalisation=False, number_bootstraps=None, boundaries=None):
'''
Bootstrap samples a set of vectors
:param numpy.ndarray values:
The data values
:param numpy.ndarray intervals:
The bin edges
:param numpy.ndarray uncertainties:
The standard deviations of each observation
:param bool normalisation:
If True then returns the histogram as a density function
:param int number_bootstraps:
Number of bootstraps
:param tuple boundaries:
(Lower, Upper) bounds on the data
:param returns:
1-D histogram of data
'''
if not number_bootstraps or np.all(np.fabs(uncertainties < PRECISION)):
# No bootstraps or all uncertaintes are zero - return ordinary
# histogram
#output = np.histogram(values, intervals)[0]
output = hmtk_histogram_1D(values, intervals)
if normalisation:
output = output / float(np.sum(output))
else:
output = output
return output
else:
temp_hist = np.zeros([len(intervals) - 1, number_bootstraps],
dtype=float)
for iloc in range(0, number_bootstraps):
sample = sample_truncated_gaussian_vector(values,
uncertainties,
boundaries)
#output = np.histogram(sample, intervals)[0]
output = hmtk_histogram_1D(sample, intervals)
temp_hist[:, iloc] = output
output = np.sum(temp_hist, axis=1)
if normalisation:
output = output / float(np.sum(output))
else:
output = output / float(number_bootstraps)
return output | python | def bootstrap_histogram_1D(
values, intervals, uncertainties=None,
normalisation=False, number_bootstraps=None, boundaries=None):
if not number_bootstraps or np.all(np.fabs(uncertainties < PRECISION)):
output = hmtk_histogram_1D(values, intervals)
if normalisation:
output = output / float(np.sum(output))
else:
output = output
return output
else:
temp_hist = np.zeros([len(intervals) - 1, number_bootstraps],
dtype=float)
for iloc in range(0, number_bootstraps):
sample = sample_truncated_gaussian_vector(values,
uncertainties,
boundaries)
output = hmtk_histogram_1D(sample, intervals)
temp_hist[:, iloc] = output
output = np.sum(temp_hist, axis=1)
if normalisation:
output = output / float(np.sum(output))
else:
output = output / float(number_bootstraps)
return output | [
"def",
"bootstrap_histogram_1D",
"(",
"values",
",",
"intervals",
",",
"uncertainties",
"=",
"None",
",",
"normalisation",
"=",
"False",
",",
"number_bootstraps",
"=",
"None",
",",
"boundaries",
"=",
"None",
")",
":",
"if",
"not",
"number_bootstraps",
"or",
"np",
".",
"all",
"(",
"np",
".",
"fabs",
"(",
"uncertainties",
"<",
"PRECISION",
")",
")",
":",
"# No bootstraps or all uncertaintes are zero - return ordinary",
"# histogram",
"#output = np.histogram(values, intervals)[0]",
"output",
"=",
"hmtk_histogram_1D",
"(",
"values",
",",
"intervals",
")",
"if",
"normalisation",
":",
"output",
"=",
"output",
"/",
"float",
"(",
"np",
".",
"sum",
"(",
"output",
")",
")",
"else",
":",
"output",
"=",
"output",
"return",
"output",
"else",
":",
"temp_hist",
"=",
"np",
".",
"zeros",
"(",
"[",
"len",
"(",
"intervals",
")",
"-",
"1",
",",
"number_bootstraps",
"]",
",",
"dtype",
"=",
"float",
")",
"for",
"iloc",
"in",
"range",
"(",
"0",
",",
"number_bootstraps",
")",
":",
"sample",
"=",
"sample_truncated_gaussian_vector",
"(",
"values",
",",
"uncertainties",
",",
"boundaries",
")",
"#output = np.histogram(sample, intervals)[0]",
"output",
"=",
"hmtk_histogram_1D",
"(",
"sample",
",",
"intervals",
")",
"temp_hist",
"[",
":",
",",
"iloc",
"]",
"=",
"output",
"output",
"=",
"np",
".",
"sum",
"(",
"temp_hist",
",",
"axis",
"=",
"1",
")",
"if",
"normalisation",
":",
"output",
"=",
"output",
"/",
"float",
"(",
"np",
".",
"sum",
"(",
"output",
")",
")",
"else",
":",
"output",
"=",
"output",
"/",
"float",
"(",
"number_bootstraps",
")",
"return",
"output"
] | Bootstrap samples a set of vectors
:param numpy.ndarray values:
The data values
:param numpy.ndarray intervals:
The bin edges
:param numpy.ndarray uncertainties:
The standard deviations of each observation
:param bool normalisation:
If True then returns the histogram as a density function
:param int number_bootstraps:
Number of bootstraps
:param tuple boundaries:
(Lower, Upper) bounds on the data
:param returns:
1-D histogram of data | [
"Bootstrap",
"samples",
"a",
"set",
"of",
"vectors"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/utils.py#L435-L483 |
gem/oq-engine | openquake/hmtk/seismicity/utils.py | bootstrap_histogram_2D | def bootstrap_histogram_2D(
xvalues, yvalues, xbins, ybins,
boundaries=[None, None], xsigma=None, ysigma=None,
normalisation=False, number_bootstraps=None):
'''
Calculates a 2D histogram of data, allowing for normalisation and
bootstrap sampling
:param numpy.ndarray xvalues:
Data values of the first variable
:param numpy.ndarray yvalues:
Data values of the second variable
:param numpy.ndarray xbins:
Bin edges for the first variable
:param numpy.ndarray ybins:
Bin edges for the second variable
:param list boundaries:
List of (Lower, Upper) tuples corresponding to the bounds of the
two data sets
:param numpy.ndarray xsigma:
Error values (standard deviatons) on first variable
:param numpy.ndarray ysigma:
Error values (standard deviatons) on second variable
:param bool normalisation:
If True then returns the histogram as a density function
:param int number_bootstraps:
Number of bootstraps
:param returns:
2-D histogram of data
'''
if (xsigma is None and ysigma is None) or not number_bootstraps:
# No sampling - return simple 2-D histrogram
#output = np.histogram2d(xvalues, yvalues, bins=[xbins, ybins])[0]
output = hmtk_histogram_2D(xvalues, yvalues, bins=(xbins, ybins))
if normalisation:
output = output / float(np.sum(output))
return output
else:
if xsigma is None:
xsigma = np.zeros(len(xvalues), dtype=float)
if ysigma is None:
ysigma = np.zeros(len(yvalues), dtype=float)
temp_hist = np.zeros(
[len(xbins) - 1, len(ybins) - 1, number_bootstraps],
dtype=float)
for iloc in range(0, number_bootstraps):
xsample = sample_truncated_gaussian_vector(xvalues, xsigma,
boundaries[0])
ysample = sample_truncated_gaussian_vector(yvalues, ysigma,
boundaries[0])
# temp_hist[:, :, iloc] = np.histogram2d(xsample,
# ysample,
# bins=[xbins, ybins])[0]
temp_hist[:, :, iloc] = hmtk_histogram_2D(xsample,
ysample,
bins=(xbins, ybins))
if normalisation:
output = np.sum(temp_hist, axis=2)
output = output / np.sum(output)
else:
output = np.sum(temp_hist, axis=2) / float(number_bootstraps)
return output | python | def bootstrap_histogram_2D(
xvalues, yvalues, xbins, ybins,
boundaries=[None, None], xsigma=None, ysigma=None,
normalisation=False, number_bootstraps=None):
if (xsigma is None and ysigma is None) or not number_bootstraps:
output = hmtk_histogram_2D(xvalues, yvalues, bins=(xbins, ybins))
if normalisation:
output = output / float(np.sum(output))
return output
else:
if xsigma is None:
xsigma = np.zeros(len(xvalues), dtype=float)
if ysigma is None:
ysigma = np.zeros(len(yvalues), dtype=float)
temp_hist = np.zeros(
[len(xbins) - 1, len(ybins) - 1, number_bootstraps],
dtype=float)
for iloc in range(0, number_bootstraps):
xsample = sample_truncated_gaussian_vector(xvalues, xsigma,
boundaries[0])
ysample = sample_truncated_gaussian_vector(yvalues, ysigma,
boundaries[0])
temp_hist[:, :, iloc] = hmtk_histogram_2D(xsample,
ysample,
bins=(xbins, ybins))
if normalisation:
output = np.sum(temp_hist, axis=2)
output = output / np.sum(output)
else:
output = np.sum(temp_hist, axis=2) / float(number_bootstraps)
return output | [
"def",
"bootstrap_histogram_2D",
"(",
"xvalues",
",",
"yvalues",
",",
"xbins",
",",
"ybins",
",",
"boundaries",
"=",
"[",
"None",
",",
"None",
"]",
",",
"xsigma",
"=",
"None",
",",
"ysigma",
"=",
"None",
",",
"normalisation",
"=",
"False",
",",
"number_bootstraps",
"=",
"None",
")",
":",
"if",
"(",
"xsigma",
"is",
"None",
"and",
"ysigma",
"is",
"None",
")",
"or",
"not",
"number_bootstraps",
":",
"# No sampling - return simple 2-D histrogram",
"#output = np.histogram2d(xvalues, yvalues, bins=[xbins, ybins])[0]",
"output",
"=",
"hmtk_histogram_2D",
"(",
"xvalues",
",",
"yvalues",
",",
"bins",
"=",
"(",
"xbins",
",",
"ybins",
")",
")",
"if",
"normalisation",
":",
"output",
"=",
"output",
"/",
"float",
"(",
"np",
".",
"sum",
"(",
"output",
")",
")",
"return",
"output",
"else",
":",
"if",
"xsigma",
"is",
"None",
":",
"xsigma",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"xvalues",
")",
",",
"dtype",
"=",
"float",
")",
"if",
"ysigma",
"is",
"None",
":",
"ysigma",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"yvalues",
")",
",",
"dtype",
"=",
"float",
")",
"temp_hist",
"=",
"np",
".",
"zeros",
"(",
"[",
"len",
"(",
"xbins",
")",
"-",
"1",
",",
"len",
"(",
"ybins",
")",
"-",
"1",
",",
"number_bootstraps",
"]",
",",
"dtype",
"=",
"float",
")",
"for",
"iloc",
"in",
"range",
"(",
"0",
",",
"number_bootstraps",
")",
":",
"xsample",
"=",
"sample_truncated_gaussian_vector",
"(",
"xvalues",
",",
"xsigma",
",",
"boundaries",
"[",
"0",
"]",
")",
"ysample",
"=",
"sample_truncated_gaussian_vector",
"(",
"yvalues",
",",
"ysigma",
",",
"boundaries",
"[",
"0",
"]",
")",
"# temp_hist[:, :, iloc] = np.histogram2d(xsample,",
"# ysample,",
"# bins=[xbins, ybins])[0]",
"temp_hist",
"[",
":",
",",
":",
",",
"iloc",
"]",
"=",
"hmtk_histogram_2D",
"(",
"xsample",
",",
"ysample",
",",
"bins",
"=",
"(",
"xbins",
",",
"ybins",
")",
")",
"if",
"normalisation",
":",
"output",
"=",
"np",
".",
"sum",
"(",
"temp_hist",
",",
"axis",
"=",
"2",
")",
"output",
"=",
"output",
"/",
"np",
".",
"sum",
"(",
"output",
")",
"else",
":",
"output",
"=",
"np",
".",
"sum",
"(",
"temp_hist",
",",
"axis",
"=",
"2",
")",
"/",
"float",
"(",
"number_bootstraps",
")",
"return",
"output"
] | Calculates a 2D histogram of data, allowing for normalisation and
bootstrap sampling
:param numpy.ndarray xvalues:
Data values of the first variable
:param numpy.ndarray yvalues:
Data values of the second variable
:param numpy.ndarray xbins:
Bin edges for the first variable
:param numpy.ndarray ybins:
Bin edges for the second variable
:param list boundaries:
List of (Lower, Upper) tuples corresponding to the bounds of the
two data sets
:param numpy.ndarray xsigma:
Error values (standard deviatons) on first variable
:param numpy.ndarray ysigma:
Error values (standard deviatons) on second variable
:param bool normalisation:
If True then returns the histogram as a density function
:param int number_bootstraps:
Number of bootstraps
:param returns:
2-D histogram of data | [
"Calculates",
"a",
"2D",
"histogram",
"of",
"data",
"allowing",
"for",
"normalisation",
"and",
"bootstrap",
"sampling"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/utils.py#L486-L558 |
gem/oq-engine | openquake/hmtk/seismicity/utils.py | lonlat_to_laea | def lonlat_to_laea(lon, lat, lon0, lat0, f_e=0.0, f_n=0.0):
"""
Converts vectors of longitude and latitude into Lambert Azimuthal
Equal Area projection (km), with respect to an origin point
:param numpy.ndarray lon:
Longitudes
:param numpy.ndarray lat:
Latitude
:param float lon0:
Central longitude
:param float lat0:
Central latitude
:param float f_e:
False easting (km)
:param float f_e:
False northing (km)
:returns:
* easting (km)
* northing (km)
"""
lon = np.radians(lon)
lat = np.radians(lat)
lon0 = np.radians(lon0)
lat0 = np.radians(lat0)
q_0 = TO_Q(lat0)
q_p = TO_Q(np.pi / 2.)
q_val = TO_Q(lat)
beta = np.arcsin(q_val / q_p)
beta0 = np.arcsin(q_0 / q_p)
r_q = WGS84["a"] * np.sqrt(q_p / 2.)
dval = WGS84["a"] * (
np.cos(lat0) / np.sqrt(1.0 - (WGS84["e2"] * (np.sin(lat0) ** 2.))) /
(r_q * np.cos(beta0)))
bval = r_q * np.sqrt(
2. / (1.0 + (np.sin(beta0) * np.sin(beta)) + (np.cos(beta) *
np.cos(beta0) * np.cos(lon - lon0))))
easting = f_e + ((bval * dval) * (np.cos(beta) * np.sin(lon - lon0)))
northing = f_n + (bval / dval) * ((np.cos(beta0) * np.sin(beta)) -
(np.sin(beta0) * np.cos(beta) * np.cos(lon - lon0)))
return easting, northing | python | def lonlat_to_laea(lon, lat, lon0, lat0, f_e=0.0, f_n=0.0):
lon = np.radians(lon)
lat = np.radians(lat)
lon0 = np.radians(lon0)
lat0 = np.radians(lat0)
q_0 = TO_Q(lat0)
q_p = TO_Q(np.pi / 2.)
q_val = TO_Q(lat)
beta = np.arcsin(q_val / q_p)
beta0 = np.arcsin(q_0 / q_p)
r_q = WGS84["a"] * np.sqrt(q_p / 2.)
dval = WGS84["a"] * (
np.cos(lat0) / np.sqrt(1.0 - (WGS84["e2"] * (np.sin(lat0) ** 2.))) /
(r_q * np.cos(beta0)))
bval = r_q * np.sqrt(
2. / (1.0 + (np.sin(beta0) * np.sin(beta)) + (np.cos(beta) *
np.cos(beta0) * np.cos(lon - lon0))))
easting = f_e + ((bval * dval) * (np.cos(beta) * np.sin(lon - lon0)))
northing = f_n + (bval / dval) * ((np.cos(beta0) * np.sin(beta)) -
(np.sin(beta0) * np.cos(beta) * np.cos(lon - lon0)))
return easting, northing | [
"def",
"lonlat_to_laea",
"(",
"lon",
",",
"lat",
",",
"lon0",
",",
"lat0",
",",
"f_e",
"=",
"0.0",
",",
"f_n",
"=",
"0.0",
")",
":",
"lon",
"=",
"np",
".",
"radians",
"(",
"lon",
")",
"lat",
"=",
"np",
".",
"radians",
"(",
"lat",
")",
"lon0",
"=",
"np",
".",
"radians",
"(",
"lon0",
")",
"lat0",
"=",
"np",
".",
"radians",
"(",
"lat0",
")",
"q_0",
"=",
"TO_Q",
"(",
"lat0",
")",
"q_p",
"=",
"TO_Q",
"(",
"np",
".",
"pi",
"/",
"2.",
")",
"q_val",
"=",
"TO_Q",
"(",
"lat",
")",
"beta",
"=",
"np",
".",
"arcsin",
"(",
"q_val",
"/",
"q_p",
")",
"beta0",
"=",
"np",
".",
"arcsin",
"(",
"q_0",
"/",
"q_p",
")",
"r_q",
"=",
"WGS84",
"[",
"\"a\"",
"]",
"*",
"np",
".",
"sqrt",
"(",
"q_p",
"/",
"2.",
")",
"dval",
"=",
"WGS84",
"[",
"\"a\"",
"]",
"*",
"(",
"np",
".",
"cos",
"(",
"lat0",
")",
"/",
"np",
".",
"sqrt",
"(",
"1.0",
"-",
"(",
"WGS84",
"[",
"\"e2\"",
"]",
"*",
"(",
"np",
".",
"sin",
"(",
"lat0",
")",
"**",
"2.",
")",
")",
")",
"/",
"(",
"r_q",
"*",
"np",
".",
"cos",
"(",
"beta0",
")",
")",
")",
"bval",
"=",
"r_q",
"*",
"np",
".",
"sqrt",
"(",
"2.",
"/",
"(",
"1.0",
"+",
"(",
"np",
".",
"sin",
"(",
"beta0",
")",
"*",
"np",
".",
"sin",
"(",
"beta",
")",
")",
"+",
"(",
"np",
".",
"cos",
"(",
"beta",
")",
"*",
"np",
".",
"cos",
"(",
"beta0",
")",
"*",
"np",
".",
"cos",
"(",
"lon",
"-",
"lon0",
")",
")",
")",
")",
"easting",
"=",
"f_e",
"+",
"(",
"(",
"bval",
"*",
"dval",
")",
"*",
"(",
"np",
".",
"cos",
"(",
"beta",
")",
"*",
"np",
".",
"sin",
"(",
"lon",
"-",
"lon0",
")",
")",
")",
"northing",
"=",
"f_n",
"+",
"(",
"bval",
"/",
"dval",
")",
"*",
"(",
"(",
"np",
".",
"cos",
"(",
"beta0",
")",
"*",
"np",
".",
"sin",
"(",
"beta",
")",
")",
"-",
"(",
"np",
".",
"sin",
"(",
"beta0",
")",
"*",
"np",
".",
"cos",
"(",
"beta",
")",
"*",
"np",
".",
"cos",
"(",
"lon",
"-",
"lon0",
")",
")",
")",
"return",
"easting",
",",
"northing"
] | Converts vectors of longitude and latitude into Lambert Azimuthal
Equal Area projection (km), with respect to an origin point
:param numpy.ndarray lon:
Longitudes
:param numpy.ndarray lat:
Latitude
:param float lon0:
Central longitude
:param float lat0:
Central latitude
:param float f_e:
False easting (km)
:param float f_e:
False northing (km)
:returns:
* easting (km)
* northing (km) | [
"Converts",
"vectors",
"of",
"longitude",
"and",
"latitude",
"into",
"Lambert",
"Azimuthal",
"Equal",
"Area",
"projection",
"(",
"km",
")",
"with",
"respect",
"to",
"an",
"origin",
"point"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/utils.py#L585-L625 |
gem/oq-engine | openquake/hmtk/seismicity/utils.py | area_of_polygon | def area_of_polygon(polygon):
"""
Returns the area of an OpenQuake polygon in square kilometres
"""
lon0 = np.mean(polygon.lons)
lat0 = np.mean(polygon.lats)
# Transform to lamber equal area projection
x, y = lonlat_to_laea(polygon.lons, polygon.lats, lon0, lat0)
# Build shapely polygons
poly = geometry.Polygon(zip(x, y))
return poly.area | python | def area_of_polygon(polygon):
lon0 = np.mean(polygon.lons)
lat0 = np.mean(polygon.lats)
x, y = lonlat_to_laea(polygon.lons, polygon.lats, lon0, lat0)
poly = geometry.Polygon(zip(x, y))
return poly.area | [
"def",
"area_of_polygon",
"(",
"polygon",
")",
":",
"lon0",
"=",
"np",
".",
"mean",
"(",
"polygon",
".",
"lons",
")",
"lat0",
"=",
"np",
".",
"mean",
"(",
"polygon",
".",
"lats",
")",
"# Transform to lamber equal area projection",
"x",
",",
"y",
"=",
"lonlat_to_laea",
"(",
"polygon",
".",
"lons",
",",
"polygon",
".",
"lats",
",",
"lon0",
",",
"lat0",
")",
"# Build shapely polygons",
"poly",
"=",
"geometry",
".",
"Polygon",
"(",
"zip",
"(",
"x",
",",
"y",
")",
")",
"return",
"poly",
".",
"area"
] | Returns the area of an OpenQuake polygon in square kilometres | [
"Returns",
"the",
"area",
"of",
"an",
"OpenQuake",
"polygon",
"in",
"square",
"kilometres"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/utils.py#L628-L638 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.input_dir | def input_dir(self):
"""
:returns: absolute path to where the job.ini is
"""
return os.path.abspath(os.path.dirname(self.inputs['job_ini'])) | python | def input_dir(self):
return os.path.abspath(os.path.dirname(self.inputs['job_ini'])) | [
"def",
"input_dir",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"inputs",
"[",
"'job_ini'",
"]",
")",
")"
] | :returns: absolute path to where the job.ini is | [
":",
"returns",
":",
"absolute",
"path",
"to",
"where",
"the",
"job",
".",
"ini",
"is"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L170-L174 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.get_reqv | def get_reqv(self):
"""
:returns: an instance of class:`RjbEquivalent` if reqv_hdf5 is set
"""
if 'reqv' not in self.inputs:
return
return {key: valid.RjbEquivalent(value)
for key, value in self.inputs['reqv'].items()} | python | def get_reqv(self):
if 'reqv' not in self.inputs:
return
return {key: valid.RjbEquivalent(value)
for key, value in self.inputs['reqv'].items()} | [
"def",
"get_reqv",
"(",
"self",
")",
":",
"if",
"'reqv'",
"not",
"in",
"self",
".",
"inputs",
":",
"return",
"return",
"{",
"key",
":",
"valid",
".",
"RjbEquivalent",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"inputs",
"[",
"'reqv'",
"]",
".",
"items",
"(",
")",
"}"
] | :returns: an instance of class:`RjbEquivalent` if reqv_hdf5 is set | [
":",
"returns",
":",
"an",
"instance",
"of",
"class",
":",
"RjbEquivalent",
"if",
"reqv_hdf5",
"is",
"set"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L176-L183 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.check_gsims | def check_gsims(self, gsims):
"""
:param gsims: a sequence of GSIM instances
"""
imts = set(from_string(imt).name for imt in self.imtls)
for gsim in gsims:
restrict_imts = gsim.DEFINED_FOR_INTENSITY_MEASURE_TYPES
if restrict_imts:
names = set(cls.__name__ for cls in restrict_imts)
invalid_imts = ', '.join(imts - names)
if invalid_imts:
raise ValueError(
'The IMT %s is not accepted by the GSIM %s' %
(invalid_imts, gsim))
if 'site_model' not in self.inputs:
# look at the required sites parameters: they must have
# a valid value; the other parameters can keep a NaN
# value since they are not used by the calculator
for param in gsim.REQUIRES_SITES_PARAMETERS:
if param in ('lon', 'lat'): # no check
continue
param_name = self.siteparam[param]
param_value = getattr(self, param_name)
if (isinstance(param_value, float) and
numpy.isnan(param_value)):
raise ValueError(
'Please set a value for %r, this is required by '
'the GSIM %s' % (param_name, gsim)) | python | def check_gsims(self, gsims):
imts = set(from_string(imt).name for imt in self.imtls)
for gsim in gsims:
restrict_imts = gsim.DEFINED_FOR_INTENSITY_MEASURE_TYPES
if restrict_imts:
names = set(cls.__name__ for cls in restrict_imts)
invalid_imts = ', '.join(imts - names)
if invalid_imts:
raise ValueError(
'The IMT %s is not accepted by the GSIM %s' %
(invalid_imts, gsim))
if 'site_model' not in self.inputs:
for param in gsim.REQUIRES_SITES_PARAMETERS:
if param in ('lon', 'lat'):
continue
param_name = self.siteparam[param]
param_value = getattr(self, param_name)
if (isinstance(param_value, float) and
numpy.isnan(param_value)):
raise ValueError(
'Please set a value for %r, this is required by '
'the GSIM %s' % (param_name, gsim)) | [
"def",
"check_gsims",
"(",
"self",
",",
"gsims",
")",
":",
"imts",
"=",
"set",
"(",
"from_string",
"(",
"imt",
")",
".",
"name",
"for",
"imt",
"in",
"self",
".",
"imtls",
")",
"for",
"gsim",
"in",
"gsims",
":",
"restrict_imts",
"=",
"gsim",
".",
"DEFINED_FOR_INTENSITY_MEASURE_TYPES",
"if",
"restrict_imts",
":",
"names",
"=",
"set",
"(",
"cls",
".",
"__name__",
"for",
"cls",
"in",
"restrict_imts",
")",
"invalid_imts",
"=",
"', '",
".",
"join",
"(",
"imts",
"-",
"names",
")",
"if",
"invalid_imts",
":",
"raise",
"ValueError",
"(",
"'The IMT %s is not accepted by the GSIM %s'",
"%",
"(",
"invalid_imts",
",",
"gsim",
")",
")",
"if",
"'site_model'",
"not",
"in",
"self",
".",
"inputs",
":",
"# look at the required sites parameters: they must have",
"# a valid value; the other parameters can keep a NaN",
"# value since they are not used by the calculator",
"for",
"param",
"in",
"gsim",
".",
"REQUIRES_SITES_PARAMETERS",
":",
"if",
"param",
"in",
"(",
"'lon'",
",",
"'lat'",
")",
":",
"# no check",
"continue",
"param_name",
"=",
"self",
".",
"siteparam",
"[",
"param",
"]",
"param_value",
"=",
"getattr",
"(",
"self",
",",
"param_name",
")",
"if",
"(",
"isinstance",
"(",
"param_value",
",",
"float",
")",
"and",
"numpy",
".",
"isnan",
"(",
"param_value",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Please set a value for %r, this is required by '",
"'the GSIM %s'",
"%",
"(",
"param_name",
",",
"gsim",
")",
")"
] | :param gsims: a sequence of GSIM instances | [
":",
"param",
"gsims",
":",
"a",
"sequence",
"of",
"GSIM",
"instances"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L316-L344 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.ses_ratio | def ses_ratio(self):
"""
The ratio
risk_investigation_time / investigation_time / ses_per_logic_tree_path
"""
if self.investigation_time is None:
raise ValueError('Missing investigation_time in the .ini file')
return (self.risk_investigation_time or self.investigation_time) / (
self.investigation_time * self.ses_per_logic_tree_path) | python | def ses_ratio(self):
if self.investigation_time is None:
raise ValueError('Missing investigation_time in the .ini file')
return (self.risk_investigation_time or self.investigation_time) / (
self.investigation_time * self.ses_per_logic_tree_path) | [
"def",
"ses_ratio",
"(",
"self",
")",
":",
"if",
"self",
".",
"investigation_time",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Missing investigation_time in the .ini file'",
")",
"return",
"(",
"self",
".",
"risk_investigation_time",
"or",
"self",
".",
"investigation_time",
")",
"/",
"(",
"self",
".",
"investigation_time",
"*",
"self",
".",
"ses_per_logic_tree_path",
")"
] | The ratio
risk_investigation_time / investigation_time / ses_per_logic_tree_path | [
"The",
"ratio"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L356-L365 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.all_cost_types | def all_cost_types(self):
"""
Return the cost types of the computation (including `occupants`
if it is there) in order.
"""
# rt has the form 'vulnerability/structural', 'fragility/...', ...
costtypes = sorted(rt.rsplit('/')[1] for rt in self.risk_files)
if not costtypes and self.hazard_calculation_id:
with util.read(self.hazard_calculation_id) as ds:
parent = ds['oqparam']
self._risk_files = get_risk_files(parent.inputs)
costtypes = sorted(rt.rsplit('/')[1] for rt in self.risk_files)
return costtypes | python | def all_cost_types(self):
costtypes = sorted(rt.rsplit('/')[1] for rt in self.risk_files)
if not costtypes and self.hazard_calculation_id:
with util.read(self.hazard_calculation_id) as ds:
parent = ds['oqparam']
self._risk_files = get_risk_files(parent.inputs)
costtypes = sorted(rt.rsplit('/')[1] for rt in self.risk_files)
return costtypes | [
"def",
"all_cost_types",
"(",
"self",
")",
":",
"# rt has the form 'vulnerability/structural', 'fragility/...', ...",
"costtypes",
"=",
"sorted",
"(",
"rt",
".",
"rsplit",
"(",
"'/'",
")",
"[",
"1",
"]",
"for",
"rt",
"in",
"self",
".",
"risk_files",
")",
"if",
"not",
"costtypes",
"and",
"self",
".",
"hazard_calculation_id",
":",
"with",
"util",
".",
"read",
"(",
"self",
".",
"hazard_calculation_id",
")",
"as",
"ds",
":",
"parent",
"=",
"ds",
"[",
"'oqparam'",
"]",
"self",
".",
"_risk_files",
"=",
"get_risk_files",
"(",
"parent",
".",
"inputs",
")",
"costtypes",
"=",
"sorted",
"(",
"rt",
".",
"rsplit",
"(",
"'/'",
")",
"[",
"1",
"]",
"for",
"rt",
"in",
"self",
".",
"risk_files",
")",
"return",
"costtypes"
] | Return the cost types of the computation (including `occupants`
if it is there) in order. | [
"Return",
"the",
"cost",
"types",
"of",
"the",
"computation",
"(",
"including",
"occupants",
"if",
"it",
"is",
"there",
")",
"in",
"order",
"."
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L377-L389 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.min_iml | def min_iml(self):
"""
:returns: a numpy array of intensities, one per IMT
"""
mini = self.minimum_intensity
if mini:
for imt in self.imtls:
try:
mini[imt] = calc.filters.getdefault(mini, imt)
except KeyError:
raise ValueError(
'The parameter `minimum_intensity` in the job.ini '
'file is missing the IMT %r' % imt)
if 'default' in mini:
del mini['default']
return F32([mini.get(imt, 0) for imt in self.imtls]) | python | def min_iml(self):
mini = self.minimum_intensity
if mini:
for imt in self.imtls:
try:
mini[imt] = calc.filters.getdefault(mini, imt)
except KeyError:
raise ValueError(
'The parameter `minimum_intensity` in the job.ini '
'file is missing the IMT %r' % imt)
if 'default' in mini:
del mini['default']
return F32([mini.get(imt, 0) for imt in self.imtls]) | [
"def",
"min_iml",
"(",
"self",
")",
":",
"mini",
"=",
"self",
".",
"minimum_intensity",
"if",
"mini",
":",
"for",
"imt",
"in",
"self",
".",
"imtls",
":",
"try",
":",
"mini",
"[",
"imt",
"]",
"=",
"calc",
".",
"filters",
".",
"getdefault",
"(",
"mini",
",",
"imt",
")",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"'The parameter `minimum_intensity` in the job.ini '",
"'file is missing the IMT %r'",
"%",
"imt",
")",
"if",
"'default'",
"in",
"mini",
":",
"del",
"mini",
"[",
"'default'",
"]",
"return",
"F32",
"(",
"[",
"mini",
".",
"get",
"(",
"imt",
",",
"0",
")",
"for",
"imt",
"in",
"self",
".",
"imtls",
"]",
")"
] | :returns: a numpy array of intensities, one per IMT | [
":",
"returns",
":",
"a",
"numpy",
"array",
"of",
"intensities",
"one",
"per",
"IMT"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L392-L407 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.set_risk_imtls | def set_risk_imtls(self, risk_models):
"""
:param risk_models:
a dictionary taxonomy -> loss_type -> risk_function
Set the attribute risk_imtls.
"""
# NB: different loss types may have different IMLs for the same IMT
# in that case we merge the IMLs
imtls = {}
for taxonomy, risk_functions in risk_models.items():
for risk_type, rf in risk_functions.items():
imt = rf.imt
from_string(imt) # make sure it is a valid IMT
imls = list(rf.imls)
if imt in imtls and imtls[imt] != imls:
logging.debug(
'Different levels for IMT %s: got %s, expected %s',
imt, imls, imtls[imt])
imtls[imt] = sorted(set(imls + imtls[imt]))
else:
imtls[imt] = imls
self.risk_imtls = imtls
if self.uniform_hazard_spectra:
self.check_uniform_hazard_spectra() | python | def set_risk_imtls(self, risk_models):
imtls = {}
for taxonomy, risk_functions in risk_models.items():
for risk_type, rf in risk_functions.items():
imt = rf.imt
from_string(imt)
imls = list(rf.imls)
if imt in imtls and imtls[imt] != imls:
logging.debug(
'Different levels for IMT %s: got %s, expected %s',
imt, imls, imtls[imt])
imtls[imt] = sorted(set(imls + imtls[imt]))
else:
imtls[imt] = imls
self.risk_imtls = imtls
if self.uniform_hazard_spectra:
self.check_uniform_hazard_spectra() | [
"def",
"set_risk_imtls",
"(",
"self",
",",
"risk_models",
")",
":",
"# NB: different loss types may have different IMLs for the same IMT",
"# in that case we merge the IMLs",
"imtls",
"=",
"{",
"}",
"for",
"taxonomy",
",",
"risk_functions",
"in",
"risk_models",
".",
"items",
"(",
")",
":",
"for",
"risk_type",
",",
"rf",
"in",
"risk_functions",
".",
"items",
"(",
")",
":",
"imt",
"=",
"rf",
".",
"imt",
"from_string",
"(",
"imt",
")",
"# make sure it is a valid IMT",
"imls",
"=",
"list",
"(",
"rf",
".",
"imls",
")",
"if",
"imt",
"in",
"imtls",
"and",
"imtls",
"[",
"imt",
"]",
"!=",
"imls",
":",
"logging",
".",
"debug",
"(",
"'Different levels for IMT %s: got %s, expected %s'",
",",
"imt",
",",
"imls",
",",
"imtls",
"[",
"imt",
"]",
")",
"imtls",
"[",
"imt",
"]",
"=",
"sorted",
"(",
"set",
"(",
"imls",
"+",
"imtls",
"[",
"imt",
"]",
")",
")",
"else",
":",
"imtls",
"[",
"imt",
"]",
"=",
"imls",
"self",
".",
"risk_imtls",
"=",
"imtls",
"if",
"self",
".",
"uniform_hazard_spectra",
":",
"self",
".",
"check_uniform_hazard_spectra",
"(",
")"
] | :param risk_models:
a dictionary taxonomy -> loss_type -> risk_function
Set the attribute risk_imtls. | [
":",
"param",
"risk_models",
":",
"a",
"dictionary",
"taxonomy",
"-",
">",
"loss_type",
"-",
">",
"risk_function"
] | train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L409-L433 |