repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 39
1.84M
| func_code_tokens
listlengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
listlengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.hmap_dt | def hmap_dt(self): # used for CSV export
"""
:returns: a composite dtype (imt, poe)
"""
return numpy.dtype([('%s-%s' % (imt, poe), F32)
for imt in self.imtls for poe in self.poes]) | python | def hmap_dt(self):
return numpy.dtype([('%s-%s' % (imt, poe), F32)
for imt in self.imtls for poe in self.poes]) | [
"def",
"hmap_dt",
"(",
"self",
")",
":",
"# used for CSV export",
"return",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"'%s-%s'",
"%",
"(",
"imt",
",",
"poe",
")",
",",
"F32",
")",
"for",
"imt",
"in",
"self",
".",
"imtls",
"for",
"poe",
"in",
"self",
".",
"poes",
"]",
")"
]
| :returns: a composite dtype (imt, poe) | [
":",
"returns",
":",
"a",
"composite",
"dtype",
"(",
"imt",
"poe",
")"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L435-L440 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.uhs_dt | def uhs_dt(self): # used for CSV and NPZ export
"""
:returns: a composity dtype (poe, imt)
"""
imts_dt = numpy.dtype([(imt, F32) for imt in self.imtls
if imt.startswith(('PGA', 'SA'))])
return numpy.dtype([(str(poe), imts_dt) for poe in self.poes]) | python | def uhs_dt(self):
imts_dt = numpy.dtype([(imt, F32) for imt in self.imtls
if imt.startswith(('PGA', 'SA'))])
return numpy.dtype([(str(poe), imts_dt) for poe in self.poes]) | [
"def",
"uhs_dt",
"(",
"self",
")",
":",
"# used for CSV and NPZ export",
"imts_dt",
"=",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"imt",
",",
"F32",
")",
"for",
"imt",
"in",
"self",
".",
"imtls",
"if",
"imt",
".",
"startswith",
"(",
"(",
"'PGA'",
",",
"'SA'",
")",
")",
"]",
")",
"return",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"str",
"(",
"poe",
")",
",",
"imts_dt",
")",
"for",
"poe",
"in",
"self",
".",
"poes",
"]",
")"
]
| :returns: a composity dtype (poe, imt) | [
":",
"returns",
":",
"a",
"composity",
"dtype",
"(",
"poe",
"imt",
")"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L442-L448 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.imt_periods | def imt_periods(self):
"""
:returns: the IMTs with a period, as objects
"""
imts = []
for im in self.imtls:
imt = from_string(im)
if hasattr(imt, 'period'):
imts.append(imt)
return imts | python | def imt_periods(self):
imts = []
for im in self.imtls:
imt = from_string(im)
if hasattr(imt, 'period'):
imts.append(imt)
return imts | [
"def",
"imt_periods",
"(",
"self",
")",
":",
"imts",
"=",
"[",
"]",
"for",
"im",
"in",
"self",
".",
"imtls",
":",
"imt",
"=",
"from_string",
"(",
"im",
")",
"if",
"hasattr",
"(",
"imt",
",",
"'period'",
")",
":",
"imts",
".",
"append",
"(",
"imt",
")",
"return",
"imts"
]
| :returns: the IMTs with a period, as objects | [
":",
"returns",
":",
"the",
"IMTs",
"with",
"a",
"period",
"as",
"objects"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L450-L459 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.imt_dt | def imt_dt(self, dtype=F64):
"""
:returns: a numpy dtype {imt: float}
"""
return numpy.dtype([(imt, dtype) for imt in self.imtls]) | python | def imt_dt(self, dtype=F64):
return numpy.dtype([(imt, dtype) for imt in self.imtls]) | [
"def",
"imt_dt",
"(",
"self",
",",
"dtype",
"=",
"F64",
")",
":",
"return",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"imt",
",",
"dtype",
")",
"for",
"imt",
"in",
"self",
".",
"imtls",
"]",
")"
]
| :returns: a numpy dtype {imt: float} | [
":",
"returns",
":",
"a",
"numpy",
"dtype",
"{",
"imt",
":",
"float",
"}"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L461-L465 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.lti | def lti(self):
"""
Dictionary extended_loss_type -> extended_loss_type index
"""
return {lt: i for i, (lt, dt) in enumerate(self.loss_dt_list())} | python | def lti(self):
return {lt: i for i, (lt, dt) in enumerate(self.loss_dt_list())} | [
"def",
"lti",
"(",
"self",
")",
":",
"return",
"{",
"lt",
":",
"i",
"for",
"i",
",",
"(",
"lt",
",",
"dt",
")",
"in",
"enumerate",
"(",
"self",
".",
"loss_dt_list",
"(",
")",
")",
"}"
]
| Dictionary extended_loss_type -> extended_loss_type index | [
"Dictionary",
"extended_loss_type",
"-",
">",
"extended_loss_type",
"index"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L468-L472 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.loss_dt_list | def loss_dt_list(self, dtype=F32):
"""
Return a data type list [(loss_name, dtype), ...]
"""
loss_types = self.all_cost_types
dts = [(str(lt), dtype) for lt in loss_types]
return dts | python | def loss_dt_list(self, dtype=F32):
loss_types = self.all_cost_types
dts = [(str(lt), dtype) for lt in loss_types]
return dts | [
"def",
"loss_dt_list",
"(",
"self",
",",
"dtype",
"=",
"F32",
")",
":",
"loss_types",
"=",
"self",
".",
"all_cost_types",
"dts",
"=",
"[",
"(",
"str",
"(",
"lt",
")",
",",
"dtype",
")",
"for",
"lt",
"in",
"loss_types",
"]",
"return",
"dts"
]
| Return a data type list [(loss_name, dtype), ...] | [
"Return",
"a",
"data",
"type",
"list",
"[",
"(",
"loss_name",
"dtype",
")",
"...",
"]"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L480-L486 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.loss_maps_dt | def loss_maps_dt(self, dtype=F32):
"""
Return a composite data type for loss maps
"""
ltypes = self.loss_dt(dtype).names
lst = [('poe-%s' % poe, dtype) for poe in self.conditional_loss_poes]
return numpy.dtype([(lt, lst) for lt in ltypes]) | python | def loss_maps_dt(self, dtype=F32):
ltypes = self.loss_dt(dtype).names
lst = [('poe-%s' % poe, dtype) for poe in self.conditional_loss_poes]
return numpy.dtype([(lt, lst) for lt in ltypes]) | [
"def",
"loss_maps_dt",
"(",
"self",
",",
"dtype",
"=",
"F32",
")",
":",
"ltypes",
"=",
"self",
".",
"loss_dt",
"(",
"dtype",
")",
".",
"names",
"lst",
"=",
"[",
"(",
"'poe-%s'",
"%",
"poe",
",",
"dtype",
")",
"for",
"poe",
"in",
"self",
".",
"conditional_loss_poes",
"]",
"return",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"lt",
",",
"lst",
")",
"for",
"lt",
"in",
"ltypes",
"]",
")"
]
| Return a composite data type for loss maps | [
"Return",
"a",
"composite",
"data",
"type",
"for",
"loss",
"maps"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L488-L494 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.gmf_data_dt | def gmf_data_dt(self):
"""
Return a composite data type for the GMFs
"""
return numpy.dtype(
[('rlzi', U16), ('sid', U32),
('eid', U64), ('gmv', (F32, (len(self.imtls),)))]) | python | def gmf_data_dt(self):
return numpy.dtype(
[('rlzi', U16), ('sid', U32),
('eid', U64), ('gmv', (F32, (len(self.imtls),)))]) | [
"def",
"gmf_data_dt",
"(",
"self",
")",
":",
"return",
"numpy",
".",
"dtype",
"(",
"[",
"(",
"'rlzi'",
",",
"U16",
")",
",",
"(",
"'sid'",
",",
"U32",
")",
",",
"(",
"'eid'",
",",
"U64",
")",
",",
"(",
"'gmv'",
",",
"(",
"F32",
",",
"(",
"len",
"(",
"self",
".",
"imtls",
")",
",",
")",
")",
")",
"]",
")"
]
| Return a composite data type for the GMFs | [
"Return",
"a",
"composite",
"data",
"type",
"for",
"the",
"GMFs"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L496-L502 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.no_imls | def no_imls(self):
"""
Return True if there are no intensity measure levels
"""
return all(numpy.isnan(ls).any() for ls in self.imtls.values()) | python | def no_imls(self):
return all(numpy.isnan(ls).any() for ls in self.imtls.values()) | [
"def",
"no_imls",
"(",
"self",
")",
":",
"return",
"all",
"(",
"numpy",
".",
"isnan",
"(",
"ls",
")",
".",
"any",
"(",
")",
"for",
"ls",
"in",
"self",
".",
"imtls",
".",
"values",
"(",
")",
")"
]
| Return True if there are no intensity measure levels | [
"Return",
"True",
"if",
"there",
"are",
"no",
"intensity",
"measure",
"levels"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L504-L508 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.correl_model | def correl_model(self):
"""
Return a correlation object. See :mod:`openquake.hazardlib.correlation`
for more info.
"""
correl_name = self.ground_motion_correlation_model
if correl_name is None: # no correlation model
return
correl_model_cls = getattr(
correlation, '%sCorrelationModel' % correl_name)
return correl_model_cls(**self.ground_motion_correlation_params) | python | def correl_model(self):
correl_name = self.ground_motion_correlation_model
if correl_name is None:
return
correl_model_cls = getattr(
correlation, '%sCorrelationModel' % correl_name)
return correl_model_cls(**self.ground_motion_correlation_params) | [
"def",
"correl_model",
"(",
"self",
")",
":",
"correl_name",
"=",
"self",
".",
"ground_motion_correlation_model",
"if",
"correl_name",
"is",
"None",
":",
"# no correlation model",
"return",
"correl_model_cls",
"=",
"getattr",
"(",
"correlation",
",",
"'%sCorrelationModel'",
"%",
"correl_name",
")",
"return",
"correl_model_cls",
"(",
"*",
"*",
"self",
".",
"ground_motion_correlation_params",
")"
]
| Return a correlation object. See :mod:`openquake.hazardlib.correlation`
for more info. | [
"Return",
"a",
"correlation",
"object",
".",
"See",
":",
"mod",
":",
"openquake",
".",
"hazardlib",
".",
"correlation",
"for",
"more",
"info",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L511-L521 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.get_kinds | def get_kinds(self, kind, R):
"""
Yield 'rlz-000', 'rlz-001', ...', 'mean', 'quantile-0.1', ...
"""
stats = self.hazard_stats()
if kind == 'stats':
yield from stats
return
elif kind == 'rlzs':
for r in range(R):
yield 'rlz-%d' % r
return
elif kind:
yield kind
return
# default: yield stats (and realizations if required)
if R > 1 and self.individual_curves or not stats:
for r in range(R):
yield 'rlz-%03d' % r
yield from stats | python | def get_kinds(self, kind, R):
stats = self.hazard_stats()
if kind == 'stats':
yield from stats
return
elif kind == 'rlzs':
for r in range(R):
yield 'rlz-%d' % r
return
elif kind:
yield kind
return
if R > 1 and self.individual_curves or not stats:
for r in range(R):
yield 'rlz-%03d' % r
yield from stats | [
"def",
"get_kinds",
"(",
"self",
",",
"kind",
",",
"R",
")",
":",
"stats",
"=",
"self",
".",
"hazard_stats",
"(",
")",
"if",
"kind",
"==",
"'stats'",
":",
"yield",
"from",
"stats",
"return",
"elif",
"kind",
"==",
"'rlzs'",
":",
"for",
"r",
"in",
"range",
"(",
"R",
")",
":",
"yield",
"'rlz-%d'",
"%",
"r",
"return",
"elif",
"kind",
":",
"yield",
"kind",
"return",
"# default: yield stats (and realizations if required)",
"if",
"R",
">",
"1",
"and",
"self",
".",
"individual_curves",
"or",
"not",
"stats",
":",
"for",
"r",
"in",
"range",
"(",
"R",
")",
":",
"yield",
"'rlz-%03d'",
"%",
"r",
"yield",
"from",
"stats"
]
| Yield 'rlz-000', 'rlz-001', ...', 'mean', 'quantile-0.1', ... | [
"Yield",
"rlz",
"-",
"000",
"rlz",
"-",
"001",
"...",
"mean",
"quantile",
"-",
"0",
".",
"1",
"..."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L523-L542 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.hazard_stats | def hazard_stats(self):
"""
Return a list of item with the statistical functions defined for the
hazard calculation
"""
names = [] # name of statistical functions
funcs = [] # statistical functions of kind func(values, weights)
if self.mean_hazard_curves:
names.append('mean')
funcs.append(stats.mean_curve)
if self.std_hazard_curves:
names.append('std')
funcs.append(stats.std_curve)
for q in self.quantiles:
names.append('quantile-%s' % q)
funcs.append(functools.partial(stats.quantile_curve, q))
if self.max_hazard_curves:
names.append('max')
funcs.append(stats.max_curve)
return dict(zip(names, funcs)) | python | def hazard_stats(self):
names = []
funcs = []
if self.mean_hazard_curves:
names.append('mean')
funcs.append(stats.mean_curve)
if self.std_hazard_curves:
names.append('std')
funcs.append(stats.std_curve)
for q in self.quantiles:
names.append('quantile-%s' % q)
funcs.append(functools.partial(stats.quantile_curve, q))
if self.max_hazard_curves:
names.append('max')
funcs.append(stats.max_curve)
return dict(zip(names, funcs)) | [
"def",
"hazard_stats",
"(",
"self",
")",
":",
"names",
"=",
"[",
"]",
"# name of statistical functions",
"funcs",
"=",
"[",
"]",
"# statistical functions of kind func(values, weights)",
"if",
"self",
".",
"mean_hazard_curves",
":",
"names",
".",
"append",
"(",
"'mean'",
")",
"funcs",
".",
"append",
"(",
"stats",
".",
"mean_curve",
")",
"if",
"self",
".",
"std_hazard_curves",
":",
"names",
".",
"append",
"(",
"'std'",
")",
"funcs",
".",
"append",
"(",
"stats",
".",
"std_curve",
")",
"for",
"q",
"in",
"self",
".",
"quantiles",
":",
"names",
".",
"append",
"(",
"'quantile-%s'",
"%",
"q",
")",
"funcs",
".",
"append",
"(",
"functools",
".",
"partial",
"(",
"stats",
".",
"quantile_curve",
",",
"q",
")",
")",
"if",
"self",
".",
"max_hazard_curves",
":",
"names",
".",
"append",
"(",
"'max'",
")",
"funcs",
".",
"append",
"(",
"stats",
".",
"max_curve",
")",
"return",
"dict",
"(",
"zip",
"(",
"names",
",",
"funcs",
")",
")"
]
| Return a list of item with the statistical functions defined for the
hazard calculation | [
"Return",
"a",
"list",
"of",
"item",
"with",
"the",
"statistical",
"functions",
"defined",
"for",
"the",
"hazard",
"calculation"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L544-L563 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.is_valid_geometry | def is_valid_geometry(self):
"""
It is possible to infer the geometry only if exactly
one of sites, sites_csv, hazard_curves_csv, gmfs_csv,
region is set. You did set more than one, or nothing.
"""
has_sites = (self.sites is not None or 'sites' in self.inputs
or 'site_model' in self.inputs)
if not has_sites and not self.ground_motion_fields:
# when generating only the ruptures you do not need the sites
return True
if ('gmfs' in self.inputs and not has_sites and
not self.inputs['gmfs'].endswith('.xml')):
raise ValueError('Missing sites or sites_csv in the .ini file')
elif ('risk' in self.calculation_mode or
'damage' in self.calculation_mode or
'bcr' in self.calculation_mode):
return True # no check on the sites for risk
flags = dict(
sites=bool(self.sites),
sites_csv=self.inputs.get('sites', 0),
hazard_curves_csv=self.inputs.get('hazard_curves', 0),
gmfs_csv=self.inputs.get('gmfs', 0),
region=bool(self.region and self.region_grid_spacing))
# NB: below we check that all the flags
# are mutually exclusive
return sum(bool(v) for v in flags.values()) == 1 or self.inputs.get(
'exposure') or self.inputs.get('site_model') | python | def is_valid_geometry(self):
has_sites = (self.sites is not None or 'sites' in self.inputs
or 'site_model' in self.inputs)
if not has_sites and not self.ground_motion_fields:
return True
if ('gmfs' in self.inputs and not has_sites and
not self.inputs['gmfs'].endswith('.xml')):
raise ValueError('Missing sites or sites_csv in the .ini file')
elif ('risk' in self.calculation_mode or
'damage' in self.calculation_mode or
'bcr' in self.calculation_mode):
return True
flags = dict(
sites=bool(self.sites),
sites_csv=self.inputs.get('sites', 0),
hazard_curves_csv=self.inputs.get('hazard_curves', 0),
gmfs_csv=self.inputs.get('gmfs', 0),
region=bool(self.region and self.region_grid_spacing))
return sum(bool(v) for v in flags.values()) == 1 or self.inputs.get(
'exposure') or self.inputs.get('site_model') | [
"def",
"is_valid_geometry",
"(",
"self",
")",
":",
"has_sites",
"=",
"(",
"self",
".",
"sites",
"is",
"not",
"None",
"or",
"'sites'",
"in",
"self",
".",
"inputs",
"or",
"'site_model'",
"in",
"self",
".",
"inputs",
")",
"if",
"not",
"has_sites",
"and",
"not",
"self",
".",
"ground_motion_fields",
":",
"# when generating only the ruptures you do not need the sites",
"return",
"True",
"if",
"(",
"'gmfs'",
"in",
"self",
".",
"inputs",
"and",
"not",
"has_sites",
"and",
"not",
"self",
".",
"inputs",
"[",
"'gmfs'",
"]",
".",
"endswith",
"(",
"'.xml'",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Missing sites or sites_csv in the .ini file'",
")",
"elif",
"(",
"'risk'",
"in",
"self",
".",
"calculation_mode",
"or",
"'damage'",
"in",
"self",
".",
"calculation_mode",
"or",
"'bcr'",
"in",
"self",
".",
"calculation_mode",
")",
":",
"return",
"True",
"# no check on the sites for risk",
"flags",
"=",
"dict",
"(",
"sites",
"=",
"bool",
"(",
"self",
".",
"sites",
")",
",",
"sites_csv",
"=",
"self",
".",
"inputs",
".",
"get",
"(",
"'sites'",
",",
"0",
")",
",",
"hazard_curves_csv",
"=",
"self",
".",
"inputs",
".",
"get",
"(",
"'hazard_curves'",
",",
"0",
")",
",",
"gmfs_csv",
"=",
"self",
".",
"inputs",
".",
"get",
"(",
"'gmfs'",
",",
"0",
")",
",",
"region",
"=",
"bool",
"(",
"self",
".",
"region",
"and",
"self",
".",
"region_grid_spacing",
")",
")",
"# NB: below we check that all the flags",
"# are mutually exclusive",
"return",
"sum",
"(",
"bool",
"(",
"v",
")",
"for",
"v",
"in",
"flags",
".",
"values",
"(",
")",
")",
"==",
"1",
"or",
"self",
".",
"inputs",
".",
"get",
"(",
"'exposure'",
")",
"or",
"self",
".",
"inputs",
".",
"get",
"(",
"'site_model'",
")"
]
| It is possible to infer the geometry only if exactly
one of sites, sites_csv, hazard_curves_csv, gmfs_csv,
region is set. You did set more than one, or nothing. | [
"It",
"is",
"possible",
"to",
"infer",
"the",
"geometry",
"only",
"if",
"exactly",
"one",
"of",
"sites",
"sites_csv",
"hazard_curves_csv",
"gmfs_csv",
"region",
"is",
"set",
".",
"You",
"did",
"set",
"more",
"than",
"one",
"or",
"nothing",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L595-L622 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.is_valid_poes | def is_valid_poes(self):
"""
When computing hazard maps and/or uniform hazard spectra,
the poes list must be non-empty.
"""
if self.hazard_maps or self.uniform_hazard_spectra:
return bool(self.poes)
else:
return True | python | def is_valid_poes(self):
if self.hazard_maps or self.uniform_hazard_spectra:
return bool(self.poes)
else:
return True | [
"def",
"is_valid_poes",
"(",
"self",
")",
":",
"if",
"self",
".",
"hazard_maps",
"or",
"self",
".",
"uniform_hazard_spectra",
":",
"return",
"bool",
"(",
"self",
".",
"poes",
")",
"else",
":",
"return",
"True"
]
| When computing hazard maps and/or uniform hazard spectra,
the poes list must be non-empty. | [
"When",
"computing",
"hazard",
"maps",
"and",
"/",
"or",
"uniform",
"hazard",
"spectra",
"the",
"poes",
"list",
"must",
"be",
"non",
"-",
"empty",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L624-L632 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.is_valid_maximum_distance | def is_valid_maximum_distance(self):
"""
Invalid maximum_distance={maximum_distance}: {error}
"""
if 'gsim_logic_tree' not in self.inputs:
return True # don't apply validation
gsim_lt = self.inputs['gsim_logic_tree']
trts = set(self.maximum_distance)
unknown = ', '.join(trts - set(self._gsims_by_trt) - set(['default']))
if unknown:
self.error = ('setting the maximum_distance for %s which is '
'not in %s' % (unknown, gsim_lt))
return False
for trt, val in self.maximum_distance.items():
if val <= 0:
self.error = '%s=%r < 0' % (trt, val)
return False
elif trt not in self._gsims_by_trt and trt != 'default':
self.error = 'tectonic region %r not in %s' % (trt, gsim_lt)
return False
if 'default' not in trts and trts < set(self._gsims_by_trt):
missing = ', '.join(set(self._gsims_by_trt) - trts)
self.error = 'missing distance for %s and no default' % missing
return False
return True | python | def is_valid_maximum_distance(self):
if 'gsim_logic_tree' not in self.inputs:
return True
gsim_lt = self.inputs['gsim_logic_tree']
trts = set(self.maximum_distance)
unknown = ', '.join(trts - set(self._gsims_by_trt) - set(['default']))
if unknown:
self.error = ('setting the maximum_distance for %s which is '
'not in %s' % (unknown, gsim_lt))
return False
for trt, val in self.maximum_distance.items():
if val <= 0:
self.error = '%s=%r < 0' % (trt, val)
return False
elif trt not in self._gsims_by_trt and trt != 'default':
self.error = 'tectonic region %r not in %s' % (trt, gsim_lt)
return False
if 'default' not in trts and trts < set(self._gsims_by_trt):
missing = ', '.join(set(self._gsims_by_trt) - trts)
self.error = 'missing distance for %s and no default' % missing
return False
return True | [
"def",
"is_valid_maximum_distance",
"(",
"self",
")",
":",
"if",
"'gsim_logic_tree'",
"not",
"in",
"self",
".",
"inputs",
":",
"return",
"True",
"# don't apply validation",
"gsim_lt",
"=",
"self",
".",
"inputs",
"[",
"'gsim_logic_tree'",
"]",
"trts",
"=",
"set",
"(",
"self",
".",
"maximum_distance",
")",
"unknown",
"=",
"', '",
".",
"join",
"(",
"trts",
"-",
"set",
"(",
"self",
".",
"_gsims_by_trt",
")",
"-",
"set",
"(",
"[",
"'default'",
"]",
")",
")",
"if",
"unknown",
":",
"self",
".",
"error",
"=",
"(",
"'setting the maximum_distance for %s which is '",
"'not in %s'",
"%",
"(",
"unknown",
",",
"gsim_lt",
")",
")",
"return",
"False",
"for",
"trt",
",",
"val",
"in",
"self",
".",
"maximum_distance",
".",
"items",
"(",
")",
":",
"if",
"val",
"<=",
"0",
":",
"self",
".",
"error",
"=",
"'%s=%r < 0'",
"%",
"(",
"trt",
",",
"val",
")",
"return",
"False",
"elif",
"trt",
"not",
"in",
"self",
".",
"_gsims_by_trt",
"and",
"trt",
"!=",
"'default'",
":",
"self",
".",
"error",
"=",
"'tectonic region %r not in %s'",
"%",
"(",
"trt",
",",
"gsim_lt",
")",
"return",
"False",
"if",
"'default'",
"not",
"in",
"trts",
"and",
"trts",
"<",
"set",
"(",
"self",
".",
"_gsims_by_trt",
")",
":",
"missing",
"=",
"', '",
".",
"join",
"(",
"set",
"(",
"self",
".",
"_gsims_by_trt",
")",
"-",
"trts",
")",
"self",
".",
"error",
"=",
"'missing distance for %s and no default'",
"%",
"missing",
"return",
"False",
"return",
"True"
]
| Invalid maximum_distance={maximum_distance}: {error} | [
"Invalid",
"maximum_distance",
"=",
"{",
"maximum_distance",
"}",
":",
"{",
"error",
"}"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L634-L658 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.is_valid_intensity_measure_types | def is_valid_intensity_measure_types(self):
"""
If the IMTs and levels are extracted from the risk models,
they must not be set directly. Moreover, if
`intensity_measure_types_and_levels` is set directly,
`intensity_measure_types` must not be set.
"""
if self.ground_motion_correlation_model:
for imt in self.imtls:
if not (imt.startswith('SA') or imt == 'PGA'):
raise ValueError(
'Correlation model %s does not accept IMT=%s' % (
self.ground_motion_correlation_model, imt))
if self.risk_files: # IMTLs extracted from the risk files
return (self.intensity_measure_types is None and
self.intensity_measure_types_and_levels is None)
elif not hasattr(self, 'hazard_imtls') and not hasattr(
self, 'risk_imtls'):
return False
return True | python | def is_valid_intensity_measure_types(self):
if self.ground_motion_correlation_model:
for imt in self.imtls:
if not (imt.startswith('SA') or imt == 'PGA'):
raise ValueError(
'Correlation model %s does not accept IMT=%s' % (
self.ground_motion_correlation_model, imt))
if self.risk_files:
return (self.intensity_measure_types is None and
self.intensity_measure_types_and_levels is None)
elif not hasattr(self, 'hazard_imtls') and not hasattr(
self, 'risk_imtls'):
return False
return True | [
"def",
"is_valid_intensity_measure_types",
"(",
"self",
")",
":",
"if",
"self",
".",
"ground_motion_correlation_model",
":",
"for",
"imt",
"in",
"self",
".",
"imtls",
":",
"if",
"not",
"(",
"imt",
".",
"startswith",
"(",
"'SA'",
")",
"or",
"imt",
"==",
"'PGA'",
")",
":",
"raise",
"ValueError",
"(",
"'Correlation model %s does not accept IMT=%s'",
"%",
"(",
"self",
".",
"ground_motion_correlation_model",
",",
"imt",
")",
")",
"if",
"self",
".",
"risk_files",
":",
"# IMTLs extracted from the risk files",
"return",
"(",
"self",
".",
"intensity_measure_types",
"is",
"None",
"and",
"self",
".",
"intensity_measure_types_and_levels",
"is",
"None",
")",
"elif",
"not",
"hasattr",
"(",
"self",
",",
"'hazard_imtls'",
")",
"and",
"not",
"hasattr",
"(",
"self",
",",
"'risk_imtls'",
")",
":",
"return",
"False",
"return",
"True"
]
| If the IMTs and levels are extracted from the risk models,
they must not be set directly. Moreover, if
`intensity_measure_types_and_levels` is set directly,
`intensity_measure_types` must not be set. | [
"If",
"the",
"IMTs",
"and",
"levels",
"are",
"extracted",
"from",
"the",
"risk",
"models",
"they",
"must",
"not",
"be",
"set",
"directly",
".",
"Moreover",
"if",
"intensity_measure_types_and_levels",
"is",
"set",
"directly",
"intensity_measure_types",
"must",
"not",
"be",
"set",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L660-L679 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.is_valid_intensity_measure_levels | def is_valid_intensity_measure_levels(self):
"""
In order to compute hazard curves, `intensity_measure_types_and_levels`
must be set or extracted from the risk models.
"""
invalid = self.no_imls() and not self.risk_files and (
self.hazard_curves_from_gmfs or self.calculation_mode in
('classical', 'disaggregation'))
return not invalid | python | def is_valid_intensity_measure_levels(self):
invalid = self.no_imls() and not self.risk_files and (
self.hazard_curves_from_gmfs or self.calculation_mode in
('classical', 'disaggregation'))
return not invalid | [
"def",
"is_valid_intensity_measure_levels",
"(",
"self",
")",
":",
"invalid",
"=",
"self",
".",
"no_imls",
"(",
")",
"and",
"not",
"self",
".",
"risk_files",
"and",
"(",
"self",
".",
"hazard_curves_from_gmfs",
"or",
"self",
".",
"calculation_mode",
"in",
"(",
"'classical'",
",",
"'disaggregation'",
")",
")",
"return",
"not",
"invalid"
]
| In order to compute hazard curves, `intensity_measure_types_and_levels`
must be set or extracted from the risk models. | [
"In",
"order",
"to",
"compute",
"hazard",
"curves",
"intensity_measure_types_and_levels",
"must",
"be",
"set",
"or",
"extracted",
"from",
"the",
"risk",
"models",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L681-L689 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.is_valid_export_dir | def is_valid_export_dir(self):
"""
export_dir={export_dir} must refer to a directory,
and the user must have the permission to write on it.
"""
if self.export_dir and not os.path.isabs(self.export_dir):
self.export_dir = os.path.normpath(
os.path.join(self.input_dir, self.export_dir))
if not self.export_dir:
self.export_dir = os.path.expanduser('~') # home directory
logging.warning('export_dir not specified. Using export_dir=%s'
% self.export_dir)
return True
elif not os.path.exists(self.export_dir):
try:
os.makedirs(self.export_dir)
except PermissionError:
return False
return True
return os.path.isdir(self.export_dir) and os.access(
self.export_dir, os.W_OK) | python | def is_valid_export_dir(self):
if self.export_dir and not os.path.isabs(self.export_dir):
self.export_dir = os.path.normpath(
os.path.join(self.input_dir, self.export_dir))
if not self.export_dir:
self.export_dir = os.path.expanduser('~')
logging.warning('export_dir not specified. Using export_dir=%s'
% self.export_dir)
return True
elif not os.path.exists(self.export_dir):
try:
os.makedirs(self.export_dir)
except PermissionError:
return False
return True
return os.path.isdir(self.export_dir) and os.access(
self.export_dir, os.W_OK) | [
"def",
"is_valid_export_dir",
"(",
"self",
")",
":",
"if",
"self",
".",
"export_dir",
"and",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"self",
".",
"export_dir",
")",
":",
"self",
".",
"export_dir",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"input_dir",
",",
"self",
".",
"export_dir",
")",
")",
"if",
"not",
"self",
".",
"export_dir",
":",
"self",
".",
"export_dir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"# home directory",
"logging",
".",
"warning",
"(",
"'export_dir not specified. Using export_dir=%s'",
"%",
"self",
".",
"export_dir",
")",
"return",
"True",
"elif",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"export_dir",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"export_dir",
")",
"except",
"PermissionError",
":",
"return",
"False",
"return",
"True",
"return",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"export_dir",
")",
"and",
"os",
".",
"access",
"(",
"self",
".",
"export_dir",
",",
"os",
".",
"W_OK",
")"
]
| export_dir={export_dir} must refer to a directory,
and the user must have the permission to write on it. | [
"export_dir",
"=",
"{",
"export_dir",
"}",
"must",
"refer",
"to",
"a",
"directory",
"and",
"the",
"user",
"must",
"have",
"the",
"permission",
"to",
"write",
"on",
"it",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L711-L731 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.is_valid_sites | def is_valid_sites(self):
"""
The sites are overdetermined
"""
if 'site_model' in self.inputs and 'sites' in self.inputs:
return False
elif 'site_model' in self.inputs and self.sites:
return False
elif 'sites' in self.inputs and self.sites:
return False
elif self.sites and self.region and self.region_grid_spacing:
return False
else:
return True | python | def is_valid_sites(self):
if 'site_model' in self.inputs and 'sites' in self.inputs:
return False
elif 'site_model' in self.inputs and self.sites:
return False
elif 'sites' in self.inputs and self.sites:
return False
elif self.sites and self.region and self.region_grid_spacing:
return False
else:
return True | [
"def",
"is_valid_sites",
"(",
"self",
")",
":",
"if",
"'site_model'",
"in",
"self",
".",
"inputs",
"and",
"'sites'",
"in",
"self",
".",
"inputs",
":",
"return",
"False",
"elif",
"'site_model'",
"in",
"self",
".",
"inputs",
"and",
"self",
".",
"sites",
":",
"return",
"False",
"elif",
"'sites'",
"in",
"self",
".",
"inputs",
"and",
"self",
".",
"sites",
":",
"return",
"False",
"elif",
"self",
".",
"sites",
"and",
"self",
".",
"region",
"and",
"self",
".",
"region_grid_spacing",
":",
"return",
"False",
"else",
":",
"return",
"True"
]
| The sites are overdetermined | [
"The",
"sites",
"are",
"overdetermined"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L733-L746 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.is_valid_complex_fault_mesh_spacing | def is_valid_complex_fault_mesh_spacing(self):
"""
The `complex_fault_mesh_spacing` parameter can be None only if
`rupture_mesh_spacing` is set. In that case it is identified with it.
"""
rms = getattr(self, 'rupture_mesh_spacing', None)
if rms and not getattr(self, 'complex_fault_mesh_spacing', None):
self.complex_fault_mesh_spacing = self.rupture_mesh_spacing
return True | python | def is_valid_complex_fault_mesh_spacing(self):
rms = getattr(self, 'rupture_mesh_spacing', None)
if rms and not getattr(self, 'complex_fault_mesh_spacing', None):
self.complex_fault_mesh_spacing = self.rupture_mesh_spacing
return True | [
"def",
"is_valid_complex_fault_mesh_spacing",
"(",
"self",
")",
":",
"rms",
"=",
"getattr",
"(",
"self",
",",
"'rupture_mesh_spacing'",
",",
"None",
")",
"if",
"rms",
"and",
"not",
"getattr",
"(",
"self",
",",
"'complex_fault_mesh_spacing'",
",",
"None",
")",
":",
"self",
".",
"complex_fault_mesh_spacing",
"=",
"self",
".",
"rupture_mesh_spacing",
"return",
"True"
]
| The `complex_fault_mesh_spacing` parameter can be None only if
`rupture_mesh_spacing` is set. In that case it is identified with it. | [
"The",
"complex_fault_mesh_spacing",
"parameter",
"can",
"be",
"None",
"only",
"if",
"rupture_mesh_spacing",
"is",
"set",
".",
"In",
"that",
"case",
"it",
"is",
"identified",
"with",
"it",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L748-L756 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.is_valid_optimize_same_id_sources | def is_valid_optimize_same_id_sources(self):
"""
The `optimize_same_id_sources` can be true only in the classical
calculators.
"""
if (self.optimize_same_id_sources and
'classical' in self.calculation_mode or
'disagg' in self.calculation_mode):
return True
elif self.optimize_same_id_sources:
return False
else:
return True | python | def is_valid_optimize_same_id_sources(self):
if (self.optimize_same_id_sources and
'classical' in self.calculation_mode or
'disagg' in self.calculation_mode):
return True
elif self.optimize_same_id_sources:
return False
else:
return True | [
"def",
"is_valid_optimize_same_id_sources",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"optimize_same_id_sources",
"and",
"'classical'",
"in",
"self",
".",
"calculation_mode",
"or",
"'disagg'",
"in",
"self",
".",
"calculation_mode",
")",
":",
"return",
"True",
"elif",
"self",
".",
"optimize_same_id_sources",
":",
"return",
"False",
"else",
":",
"return",
"True"
]
| The `optimize_same_id_sources` can be true only in the classical
calculators. | [
"The",
"optimize_same_id_sources",
"can",
"be",
"true",
"only",
"in",
"the",
"classical",
"calculators",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L758-L770 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.check_missing | def check_missing(self, param, action):
"""
Make sure the given parameter is missing in the job.ini file
"""
assert action in ('debug', 'info', 'warn', 'error'), action
if self.inputs.get(param):
msg = '%s_file in %s is ignored in %s' % (
param, self.inputs['job_ini'], self.calculation_mode)
if action == 'error':
raise InvalidFile(msg)
else:
getattr(logging, action)(msg) | python | def check_missing(self, param, action):
assert action in ('debug', 'info', 'warn', 'error'), action
if self.inputs.get(param):
msg = '%s_file in %s is ignored in %s' % (
param, self.inputs['job_ini'], self.calculation_mode)
if action == 'error':
raise InvalidFile(msg)
else:
getattr(logging, action)(msg) | [
"def",
"check_missing",
"(",
"self",
",",
"param",
",",
"action",
")",
":",
"assert",
"action",
"in",
"(",
"'debug'",
",",
"'info'",
",",
"'warn'",
",",
"'error'",
")",
",",
"action",
"if",
"self",
".",
"inputs",
".",
"get",
"(",
"param",
")",
":",
"msg",
"=",
"'%s_file in %s is ignored in %s'",
"%",
"(",
"param",
",",
"self",
".",
"inputs",
"[",
"'job_ini'",
"]",
",",
"self",
".",
"calculation_mode",
")",
"if",
"action",
"==",
"'error'",
":",
"raise",
"InvalidFile",
"(",
"msg",
")",
"else",
":",
"getattr",
"(",
"logging",
",",
"action",
")",
"(",
"msg",
")"
]
| Make sure the given parameter is missing in the job.ini file | [
"Make",
"sure",
"the",
"given",
"parameter",
"is",
"missing",
"in",
"the",
"job",
".",
"ini",
"file"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L795-L806 |
gem/oq-engine | openquake/commonlib/oqvalidation.py | OqParam.hazard_precomputed | def hazard_precomputed(self):
"""
:returns: True if the hazard is precomputed
"""
if 'gmfs' in self.inputs or 'hazard_curves' in self.inputs:
return True
elif self.hazard_calculation_id:
parent = list(util.read(self.hazard_calculation_id))
return 'gmf_data' in parent or 'poes' in parent | python | def hazard_precomputed(self):
if 'gmfs' in self.inputs or 'hazard_curves' in self.inputs:
return True
elif self.hazard_calculation_id:
parent = list(util.read(self.hazard_calculation_id))
return 'gmf_data' in parent or 'poes' in parent | [
"def",
"hazard_precomputed",
"(",
"self",
")",
":",
"if",
"'gmfs'",
"in",
"self",
".",
"inputs",
"or",
"'hazard_curves'",
"in",
"self",
".",
"inputs",
":",
"return",
"True",
"elif",
"self",
".",
"hazard_calculation_id",
":",
"parent",
"=",
"list",
"(",
"util",
".",
"read",
"(",
"self",
".",
"hazard_calculation_id",
")",
")",
"return",
"'gmf_data'",
"in",
"parent",
"or",
"'poes'",
"in",
"parent"
]
| :returns: True if the hazard is precomputed | [
":",
"returns",
":",
"True",
"if",
"the",
"hazard",
"is",
"precomputed"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/oqvalidation.py#L808-L816 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | get_set_num_ruptures | def get_set_num_ruptures(src):
"""
Extract the number of ruptures and set it
"""
if not src.num_ruptures:
t0 = time.time()
src.num_ruptures = src.count_ruptures()
dt = time.time() - t0
clsname = src.__class__.__name__
if dt > 10:
if 'Area' in clsname:
logging.warning(
'%s.count_ruptures took %d seconds, perhaps the '
'area discretization is too small', src, dt)
elif 'ComplexFault' in clsname:
logging.warning(
'%s.count_ruptures took %d seconds, perhaps the '
'complex_fault_mesh_spacing is too small', src, dt)
elif 'SimpleFault' in clsname:
logging.warning(
'%s.count_ruptures took %d seconds, perhaps the '
'rupture_mesh_spacing is too small', src, dt)
else:
# multiPointSource
logging.warning('count_ruptures %s took %d seconds', src, dt)
return src.num_ruptures | python | def get_set_num_ruptures(src):
if not src.num_ruptures:
t0 = time.time()
src.num_ruptures = src.count_ruptures()
dt = time.time() - t0
clsname = src.__class__.__name__
if dt > 10:
if 'Area' in clsname:
logging.warning(
'%s.count_ruptures took %d seconds, perhaps the '
'area discretization is too small', src, dt)
elif 'ComplexFault' in clsname:
logging.warning(
'%s.count_ruptures took %d seconds, perhaps the '
'complex_fault_mesh_spacing is too small', src, dt)
elif 'SimpleFault' in clsname:
logging.warning(
'%s.count_ruptures took %d seconds, perhaps the '
'rupture_mesh_spacing is too small', src, dt)
else:
logging.warning('count_ruptures %s took %d seconds', src, dt)
return src.num_ruptures | [
"def",
"get_set_num_ruptures",
"(",
"src",
")",
":",
"if",
"not",
"src",
".",
"num_ruptures",
":",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"src",
".",
"num_ruptures",
"=",
"src",
".",
"count_ruptures",
"(",
")",
"dt",
"=",
"time",
".",
"time",
"(",
")",
"-",
"t0",
"clsname",
"=",
"src",
".",
"__class__",
".",
"__name__",
"if",
"dt",
">",
"10",
":",
"if",
"'Area'",
"in",
"clsname",
":",
"logging",
".",
"warning",
"(",
"'%s.count_ruptures took %d seconds, perhaps the '",
"'area discretization is too small'",
",",
"src",
",",
"dt",
")",
"elif",
"'ComplexFault'",
"in",
"clsname",
":",
"logging",
".",
"warning",
"(",
"'%s.count_ruptures took %d seconds, perhaps the '",
"'complex_fault_mesh_spacing is too small'",
",",
"src",
",",
"dt",
")",
"elif",
"'SimpleFault'",
"in",
"clsname",
":",
"logging",
".",
"warning",
"(",
"'%s.count_ruptures took %d seconds, perhaps the '",
"'rupture_mesh_spacing is too small'",
",",
"src",
",",
"dt",
")",
"else",
":",
"# multiPointSource",
"logging",
".",
"warning",
"(",
"'count_ruptures %s took %d seconds'",
",",
"src",
",",
"dt",
")",
"return",
"src",
".",
"num_ruptures"
]
| Extract the number of ruptures and set it | [
"Extract",
"the",
"number",
"of",
"ruptures",
"and",
"set",
"it"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L238-L263 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | split_coords_2d | def split_coords_2d(seq):
"""
:param seq: a flat list with lons and lats
:returns: a validated list of pairs (lon, lat)
>>> split_coords_2d([1.1, 2.1, 2.2, 2.3])
[(1.1, 2.1), (2.2, 2.3)]
"""
lons, lats = [], []
for i, el in enumerate(seq):
if i % 2 == 0:
lons.append(valid.longitude(el))
elif i % 2 == 1:
lats.append(valid.latitude(el))
return list(zip(lons, lats)) | python | def split_coords_2d(seq):
lons, lats = [], []
for i, el in enumerate(seq):
if i % 2 == 0:
lons.append(valid.longitude(el))
elif i % 2 == 1:
lats.append(valid.latitude(el))
return list(zip(lons, lats)) | [
"def",
"split_coords_2d",
"(",
"seq",
")",
":",
"lons",
",",
"lats",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"i",
",",
"el",
"in",
"enumerate",
"(",
"seq",
")",
":",
"if",
"i",
"%",
"2",
"==",
"0",
":",
"lons",
".",
"append",
"(",
"valid",
".",
"longitude",
"(",
"el",
")",
")",
"elif",
"i",
"%",
"2",
"==",
"1",
":",
"lats",
".",
"append",
"(",
"valid",
".",
"latitude",
"(",
"el",
")",
")",
"return",
"list",
"(",
"zip",
"(",
"lons",
",",
"lats",
")",
")"
]
| :param seq: a flat list with lons and lats
:returns: a validated list of pairs (lon, lat)
>>> split_coords_2d([1.1, 2.1, 2.2, 2.3])
[(1.1, 2.1), (2.2, 2.3)] | [
":",
"param",
"seq",
":",
"a",
"flat",
"list",
"with",
"lons",
"and",
"lats",
":",
"returns",
":",
"a",
"validated",
"list",
"of",
"pairs",
"(",
"lon",
"lat",
")"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L266-L280 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | split_coords_3d | def split_coords_3d(seq):
"""
:param seq: a flat list with lons, lats and depths
:returns: a validated list of (lon, lat, depths) triplets
>>> split_coords_3d([1.1, 2.1, 0.1, 2.3, 2.4, 0.1])
[(1.1, 2.1, 0.1), (2.3, 2.4, 0.1)]
"""
lons, lats, depths = [], [], []
for i, el in enumerate(seq):
if i % 3 == 0:
lons.append(valid.longitude(el))
elif i % 3 == 1:
lats.append(valid.latitude(el))
elif i % 3 == 2:
depths.append(valid.depth(el))
return list(zip(lons, lats, depths)) | python | def split_coords_3d(seq):
lons, lats, depths = [], [], []
for i, el in enumerate(seq):
if i % 3 == 0:
lons.append(valid.longitude(el))
elif i % 3 == 1:
lats.append(valid.latitude(el))
elif i % 3 == 2:
depths.append(valid.depth(el))
return list(zip(lons, lats, depths)) | [
"def",
"split_coords_3d",
"(",
"seq",
")",
":",
"lons",
",",
"lats",
",",
"depths",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"for",
"i",
",",
"el",
"in",
"enumerate",
"(",
"seq",
")",
":",
"if",
"i",
"%",
"3",
"==",
"0",
":",
"lons",
".",
"append",
"(",
"valid",
".",
"longitude",
"(",
"el",
")",
")",
"elif",
"i",
"%",
"3",
"==",
"1",
":",
"lats",
".",
"append",
"(",
"valid",
".",
"latitude",
"(",
"el",
")",
")",
"elif",
"i",
"%",
"3",
"==",
"2",
":",
"depths",
".",
"append",
"(",
"valid",
".",
"depth",
"(",
"el",
")",
")",
"return",
"list",
"(",
"zip",
"(",
"lons",
",",
"lats",
",",
"depths",
")",
")"
]
| :param seq: a flat list with lons, lats and depths
:returns: a validated list of (lon, lat, depths) triplets
>>> split_coords_3d([1.1, 2.1, 0.1, 2.3, 2.4, 0.1])
[(1.1, 2.1, 0.1), (2.3, 2.4, 0.1)] | [
":",
"param",
"seq",
":",
"a",
"flat",
"list",
"with",
"lons",
"lats",
"and",
"depths",
":",
"returns",
":",
"a",
"validated",
"list",
"of",
"(",
"lon",
"lat",
"depths",
")",
"triplets"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L283-L299 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | dists | def dists(node):
"""
:returns: hpdist, npdist and magScaleRel from the given pointSource node
"""
hd = tuple((node['probability'], node['depth'])
for node in node.hypoDepthDist)
npd = tuple(
((node['probability'], node['rake'], node['strike'], node['dip']))
for node in node.nodalPlaneDist)
return hd, npd, ~node.magScaleRel | python | def dists(node):
hd = tuple((node['probability'], node['depth'])
for node in node.hypoDepthDist)
npd = tuple(
((node['probability'], node['rake'], node['strike'], node['dip']))
for node in node.nodalPlaneDist)
return hd, npd, ~node.magScaleRel | [
"def",
"dists",
"(",
"node",
")",
":",
"hd",
"=",
"tuple",
"(",
"(",
"node",
"[",
"'probability'",
"]",
",",
"node",
"[",
"'depth'",
"]",
")",
"for",
"node",
"in",
"node",
".",
"hypoDepthDist",
")",
"npd",
"=",
"tuple",
"(",
"(",
"(",
"node",
"[",
"'probability'",
"]",
",",
"node",
"[",
"'rake'",
"]",
",",
"node",
"[",
"'strike'",
"]",
",",
"node",
"[",
"'dip'",
"]",
")",
")",
"for",
"node",
"in",
"node",
".",
"nodalPlaneDist",
")",
"return",
"hd",
",",
"npd",
",",
"~",
"node",
".",
"magScaleRel"
]
| :returns: hpdist, npdist and magScaleRel from the given pointSource node | [
":",
"returns",
":",
"hpdist",
"npdist",
"and",
"magScaleRel",
"from",
"the",
"given",
"pointSource",
"node"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L896-L905 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | mfds2multimfd | def mfds2multimfd(mfds):
"""
Convert a list of MFD nodes into a single MultiMFD node
"""
_, kind = mfds[0].tag.split('}')
node = Node('multiMFD', dict(kind=kind, size=len(mfds)))
lengths = None
for field in mfd.multi_mfd.ASSOC[kind][1:]:
alias = mfd.multi_mfd.ALIAS.get(field, field)
if field in ('magnitudes', 'occurRates'):
data = [~getattr(m, field) for m in mfds]
lengths = [len(d) for d in data]
data = sum(data, []) # list of lists
else:
try:
data = [m[alias] for m in mfds]
except KeyError:
if alias == 'binWidth':
# missing bindWidth in GR MDFs is ok
continue
else:
raise
node.append(Node(field, text=collapse(data)))
if lengths: # this is the last field if present
node.append(Node('lengths', text=collapse(lengths)))
return node | python | def mfds2multimfd(mfds):
_, kind = mfds[0].tag.split('}')
node = Node('multiMFD', dict(kind=kind, size=len(mfds)))
lengths = None
for field in mfd.multi_mfd.ASSOC[kind][1:]:
alias = mfd.multi_mfd.ALIAS.get(field, field)
if field in ('magnitudes', 'occurRates'):
data = [~getattr(m, field) for m in mfds]
lengths = [len(d) for d in data]
data = sum(data, [])
else:
try:
data = [m[alias] for m in mfds]
except KeyError:
if alias == 'binWidth':
continue
else:
raise
node.append(Node(field, text=collapse(data)))
if lengths:
node.append(Node('lengths', text=collapse(lengths)))
return node | [
"def",
"mfds2multimfd",
"(",
"mfds",
")",
":",
"_",
",",
"kind",
"=",
"mfds",
"[",
"0",
"]",
".",
"tag",
".",
"split",
"(",
"'}'",
")",
"node",
"=",
"Node",
"(",
"'multiMFD'",
",",
"dict",
"(",
"kind",
"=",
"kind",
",",
"size",
"=",
"len",
"(",
"mfds",
")",
")",
")",
"lengths",
"=",
"None",
"for",
"field",
"in",
"mfd",
".",
"multi_mfd",
".",
"ASSOC",
"[",
"kind",
"]",
"[",
"1",
":",
"]",
":",
"alias",
"=",
"mfd",
".",
"multi_mfd",
".",
"ALIAS",
".",
"get",
"(",
"field",
",",
"field",
")",
"if",
"field",
"in",
"(",
"'magnitudes'",
",",
"'occurRates'",
")",
":",
"data",
"=",
"[",
"~",
"getattr",
"(",
"m",
",",
"field",
")",
"for",
"m",
"in",
"mfds",
"]",
"lengths",
"=",
"[",
"len",
"(",
"d",
")",
"for",
"d",
"in",
"data",
"]",
"data",
"=",
"sum",
"(",
"data",
",",
"[",
"]",
")",
"# list of lists",
"else",
":",
"try",
":",
"data",
"=",
"[",
"m",
"[",
"alias",
"]",
"for",
"m",
"in",
"mfds",
"]",
"except",
"KeyError",
":",
"if",
"alias",
"==",
"'binWidth'",
":",
"# missing bindWidth in GR MDFs is ok",
"continue",
"else",
":",
"raise",
"node",
".",
"append",
"(",
"Node",
"(",
"field",
",",
"text",
"=",
"collapse",
"(",
"data",
")",
")",
")",
"if",
"lengths",
":",
"# this is the last field if present",
"node",
".",
"append",
"(",
"Node",
"(",
"'lengths'",
",",
"text",
"=",
"collapse",
"(",
"lengths",
")",
")",
")",
"return",
"node"
]
| Convert a list of MFD nodes into a single MultiMFD node | [
"Convert",
"a",
"list",
"of",
"MFD",
"nodes",
"into",
"a",
"single",
"MultiMFD",
"node"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L918-L943 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | update_source_model | def update_source_model(sm_node, fname):
"""
:param sm_node: a sourceModel Node object containing sourceGroups
"""
i = 0
for group in sm_node:
if 'srcs_weights' in group.attrib:
raise InvalidFile('srcs_weights must be removed in %s' % fname)
if not group.tag.endswith('sourceGroup'):
raise InvalidFile('wrong NRML, got %s instead of '
'sourceGroup in %s' % (group.tag, fname))
psrcs = []
others = []
for src in group:
try:
del src.attrib['tectonicRegion'] # make the trt implicit
except KeyError:
pass # already missing
if src.tag.endswith('pointSource'):
psrcs.append(src)
else:
others.append(src)
others.sort(key=lambda src: (src.tag, src['id']))
i, sources = _pointsources2multipoints(psrcs, i)
group.nodes = sources + others | python | def update_source_model(sm_node, fname):
i = 0
for group in sm_node:
if 'srcs_weights' in group.attrib:
raise InvalidFile('srcs_weights must be removed in %s' % fname)
if not group.tag.endswith('sourceGroup'):
raise InvalidFile('wrong NRML, got %s instead of '
'sourceGroup in %s' % (group.tag, fname))
psrcs = []
others = []
for src in group:
try:
del src.attrib['tectonicRegion']
except KeyError:
pass
if src.tag.endswith('pointSource'):
psrcs.append(src)
else:
others.append(src)
others.sort(key=lambda src: (src.tag, src['id']))
i, sources = _pointsources2multipoints(psrcs, i)
group.nodes = sources + others | [
"def",
"update_source_model",
"(",
"sm_node",
",",
"fname",
")",
":",
"i",
"=",
"0",
"for",
"group",
"in",
"sm_node",
":",
"if",
"'srcs_weights'",
"in",
"group",
".",
"attrib",
":",
"raise",
"InvalidFile",
"(",
"'srcs_weights must be removed in %s'",
"%",
"fname",
")",
"if",
"not",
"group",
".",
"tag",
".",
"endswith",
"(",
"'sourceGroup'",
")",
":",
"raise",
"InvalidFile",
"(",
"'wrong NRML, got %s instead of '",
"'sourceGroup in %s'",
"%",
"(",
"group",
".",
"tag",
",",
"fname",
")",
")",
"psrcs",
"=",
"[",
"]",
"others",
"=",
"[",
"]",
"for",
"src",
"in",
"group",
":",
"try",
":",
"del",
"src",
".",
"attrib",
"[",
"'tectonicRegion'",
"]",
"# make the trt implicit",
"except",
"KeyError",
":",
"pass",
"# already missing",
"if",
"src",
".",
"tag",
".",
"endswith",
"(",
"'pointSource'",
")",
":",
"psrcs",
".",
"append",
"(",
"src",
")",
"else",
":",
"others",
".",
"append",
"(",
"src",
")",
"others",
".",
"sort",
"(",
"key",
"=",
"lambda",
"src",
":",
"(",
"src",
".",
"tag",
",",
"src",
"[",
"'id'",
"]",
")",
")",
"i",
",",
"sources",
"=",
"_pointsources2multipoints",
"(",
"psrcs",
",",
"i",
")",
"group",
".",
"nodes",
"=",
"sources",
"+",
"others"
]
| :param sm_node: a sourceModel Node object containing sourceGroups | [
":",
"param",
"sm_node",
":",
"a",
"sourceModel",
"Node",
"object",
"containing",
"sourceGroups"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L988-L1012 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | to_python | def to_python(fname, converter):
"""
Convert a source model .hdf5 file into a :class:`SourceModel` object
"""
with hdf5.File(fname, 'r') as f:
source_model = f['/']
for sg in source_model:
for src in sg:
if hasattr(src, 'mfd'):
# multipoint source
# src.tom = converter.tom
kwargs = getattr(src.mfd, 'kwargs', {})
if 'bin_width' not in kwargs:
kwargs['bin_width'] = [converter.width_of_mfd_bin]
return source_model | python | def to_python(fname, converter):
with hdf5.File(fname, 'r') as f:
source_model = f['/']
for sg in source_model:
for src in sg:
if hasattr(src, 'mfd'):
kwargs = getattr(src.mfd, 'kwargs', {})
if 'bin_width' not in kwargs:
kwargs['bin_width'] = [converter.width_of_mfd_bin]
return source_model | [
"def",
"to_python",
"(",
"fname",
",",
"converter",
")",
":",
"with",
"hdf5",
".",
"File",
"(",
"fname",
",",
"'r'",
")",
"as",
"f",
":",
"source_model",
"=",
"f",
"[",
"'/'",
"]",
"for",
"sg",
"in",
"source_model",
":",
"for",
"src",
"in",
"sg",
":",
"if",
"hasattr",
"(",
"src",
",",
"'mfd'",
")",
":",
"# multipoint source",
"# src.tom = converter.tom",
"kwargs",
"=",
"getattr",
"(",
"src",
".",
"mfd",
",",
"'kwargs'",
",",
"{",
"}",
")",
"if",
"'bin_width'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'bin_width'",
"]",
"=",
"[",
"converter",
".",
"width_of_mfd_bin",
"]",
"return",
"source_model"
]
| Convert a source model .hdf5 file into a :class:`SourceModel` object | [
"Convert",
"a",
"source",
"model",
".",
"hdf5",
"file",
"into",
"a",
":",
"class",
":",
"SourceModel",
"object"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L1015-L1029 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | SourceGroup.collect | def collect(cls, sources):
"""
:param sources: dictionaries with a key 'tectonicRegion'
:returns: an ordered list of SourceGroup instances
"""
source_stats_dict = {}
for src in sources:
trt = src['tectonicRegion']
if trt not in source_stats_dict:
source_stats_dict[trt] = SourceGroup(trt)
sg = source_stats_dict[trt]
if not sg.sources:
# we append just one source per SourceGroup, so that
# the memory occupation is insignificant
sg.sources.append(src)
# return SourceGroups, ordered by TRT string
return sorted(source_stats_dict.values()) | python | def collect(cls, sources):
source_stats_dict = {}
for src in sources:
trt = src['tectonicRegion']
if trt not in source_stats_dict:
source_stats_dict[trt] = SourceGroup(trt)
sg = source_stats_dict[trt]
if not sg.sources:
sg.sources.append(src)
return sorted(source_stats_dict.values()) | [
"def",
"collect",
"(",
"cls",
",",
"sources",
")",
":",
"source_stats_dict",
"=",
"{",
"}",
"for",
"src",
"in",
"sources",
":",
"trt",
"=",
"src",
"[",
"'tectonicRegion'",
"]",
"if",
"trt",
"not",
"in",
"source_stats_dict",
":",
"source_stats_dict",
"[",
"trt",
"]",
"=",
"SourceGroup",
"(",
"trt",
")",
"sg",
"=",
"source_stats_dict",
"[",
"trt",
"]",
"if",
"not",
"sg",
".",
"sources",
":",
"# we append just one source per SourceGroup, so that",
"# the memory occupation is insignificant",
"sg",
".",
"sources",
".",
"append",
"(",
"src",
")",
"# return SourceGroups, ordered by TRT string",
"return",
"sorted",
"(",
"source_stats_dict",
".",
"values",
"(",
")",
")"
]
| :param sources: dictionaries with a key 'tectonicRegion'
:returns: an ordered list of SourceGroup instances | [
":",
"param",
"sources",
":",
"dictionaries",
"with",
"a",
"key",
"tectonicRegion",
":",
"returns",
":",
"an",
"ordered",
"list",
"of",
"SourceGroup",
"instances"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L80-L97 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | SourceGroup.update | def update(self, src):
"""
Update the attributes sources, min_mag, max_mag
according to the given source.
:param src:
an instance of :class:
`openquake.hazardlib.source.base.BaseSeismicSource`
"""
assert src.tectonic_region_type == self.trt, (
src.tectonic_region_type, self.trt)
if not src.min_mag: # if not set already
src.min_mag = self.min_mag.get(self.trt) or self.min_mag['default']
# checking mutex ruptures
if (not isinstance(src, NonParametricSeismicSource) and
self.rup_interdep == 'mutex'):
msg = "Mutually exclusive ruptures can only be "
msg += "modelled using non-parametric sources"
raise ValueError(msg)
nr = get_set_num_ruptures(src)
if nr == 0: # the minimum_magnitude filters all ruptures
return
self.tot_ruptures += nr
self.sources.append(src)
_, max_mag = src.get_min_max_mag()
prev_max_mag = self.max_mag
if prev_max_mag is None or max_mag > prev_max_mag:
self.max_mag = max_mag | python | def update(self, src):
assert src.tectonic_region_type == self.trt, (
src.tectonic_region_type, self.trt)
if not src.min_mag:
src.min_mag = self.min_mag.get(self.trt) or self.min_mag['default']
if (not isinstance(src, NonParametricSeismicSource) and
self.rup_interdep == 'mutex'):
msg = "Mutually exclusive ruptures can only be "
msg += "modelled using non-parametric sources"
raise ValueError(msg)
nr = get_set_num_ruptures(src)
if nr == 0:
return
self.tot_ruptures += nr
self.sources.append(src)
_, max_mag = src.get_min_max_mag()
prev_max_mag = self.max_mag
if prev_max_mag is None or max_mag > prev_max_mag:
self.max_mag = max_mag | [
"def",
"update",
"(",
"self",
",",
"src",
")",
":",
"assert",
"src",
".",
"tectonic_region_type",
"==",
"self",
".",
"trt",
",",
"(",
"src",
".",
"tectonic_region_type",
",",
"self",
".",
"trt",
")",
"if",
"not",
"src",
".",
"min_mag",
":",
"# if not set already",
"src",
".",
"min_mag",
"=",
"self",
".",
"min_mag",
".",
"get",
"(",
"self",
".",
"trt",
")",
"or",
"self",
".",
"min_mag",
"[",
"'default'",
"]",
"# checking mutex ruptures",
"if",
"(",
"not",
"isinstance",
"(",
"src",
",",
"NonParametricSeismicSource",
")",
"and",
"self",
".",
"rup_interdep",
"==",
"'mutex'",
")",
":",
"msg",
"=",
"\"Mutually exclusive ruptures can only be \"",
"msg",
"+=",
"\"modelled using non-parametric sources\"",
"raise",
"ValueError",
"(",
"msg",
")",
"nr",
"=",
"get_set_num_ruptures",
"(",
"src",
")",
"if",
"nr",
"==",
"0",
":",
"# the minimum_magnitude filters all ruptures",
"return",
"self",
".",
"tot_ruptures",
"+=",
"nr",
"self",
".",
"sources",
".",
"append",
"(",
"src",
")",
"_",
",",
"max_mag",
"=",
"src",
".",
"get_min_max_mag",
"(",
")",
"prev_max_mag",
"=",
"self",
".",
"max_mag",
"if",
"prev_max_mag",
"is",
"None",
"or",
"max_mag",
">",
"prev_max_mag",
":",
"self",
".",
"max_mag",
"=",
"max_mag"
]
| Update the attributes sources, min_mag, max_mag
according to the given source.
:param src:
an instance of :class:
`openquake.hazardlib.source.base.BaseSeismicSource` | [
"Update",
"the",
"attributes",
"sources",
"min_mag",
"max_mag",
"according",
"to",
"the",
"given",
"source",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L159-L187 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | RuptureConverter.convert_node | def convert_node(self, node):
"""
Convert the given rupture node into a hazardlib rupture, depending
on the node tag.
:param node: a node representing a rupture
"""
convert = getattr(self, 'convert_' + striptag(node.tag))
return convert(node) | python | def convert_node(self, node):
convert = getattr(self, 'convert_' + striptag(node.tag))
return convert(node) | [
"def",
"convert_node",
"(",
"self",
",",
"node",
")",
":",
"convert",
"=",
"getattr",
"(",
"self",
",",
"'convert_'",
"+",
"striptag",
"(",
"node",
".",
"tag",
")",
")",
"return",
"convert",
"(",
"node",
")"
]
| Convert the given rupture node into a hazardlib rupture, depending
on the node tag.
:param node: a node representing a rupture | [
"Convert",
"the",
"given",
"rupture",
"node",
"into",
"a",
"hazardlib",
"rupture",
"depending",
"on",
"the",
"node",
"tag",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L321-L329 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | RuptureConverter.geo_line | def geo_line(self, edge):
"""
Utility function to convert a node of kind edge
into a :class:`openquake.hazardlib.geo.Line` instance.
:param edge: a node describing an edge
"""
with context(self.fname, edge.LineString.posList) as plist:
coords = split_coords_2d(~plist)
return geo.Line([geo.Point(*p) for p in coords]) | python | def geo_line(self, edge):
with context(self.fname, edge.LineString.posList) as plist:
coords = split_coords_2d(~plist)
return geo.Line([geo.Point(*p) for p in coords]) | [
"def",
"geo_line",
"(",
"self",
",",
"edge",
")",
":",
"with",
"context",
"(",
"self",
".",
"fname",
",",
"edge",
".",
"LineString",
".",
"posList",
")",
"as",
"plist",
":",
"coords",
"=",
"split_coords_2d",
"(",
"~",
"plist",
")",
"return",
"geo",
".",
"Line",
"(",
"[",
"geo",
".",
"Point",
"(",
"*",
"p",
")",
"for",
"p",
"in",
"coords",
"]",
")"
]
| Utility function to convert a node of kind edge
into a :class:`openquake.hazardlib.geo.Line` instance.
:param edge: a node describing an edge | [
"Utility",
"function",
"to",
"convert",
"a",
"node",
"of",
"kind",
"edge",
"into",
"a",
":",
"class",
":",
"openquake",
".",
"hazardlib",
".",
"geo",
".",
"Line",
"instance",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L331-L340 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | RuptureConverter.geo_lines | def geo_lines(self, edges):
"""
Utility function to convert a list of edges into a list of
:class:`openquake.hazardlib.geo.Line` instances.
:param edge: a node describing an edge
"""
lines = []
for edge in edges:
with context(self.fname, edge):
coords = split_coords_3d(~edge.LineString.posList)
lines.append(geo.Line([geo.Point(*p) for p in coords]))
return lines | python | def geo_lines(self, edges):
lines = []
for edge in edges:
with context(self.fname, edge):
coords = split_coords_3d(~edge.LineString.posList)
lines.append(geo.Line([geo.Point(*p) for p in coords]))
return lines | [
"def",
"geo_lines",
"(",
"self",
",",
"edges",
")",
":",
"lines",
"=",
"[",
"]",
"for",
"edge",
"in",
"edges",
":",
"with",
"context",
"(",
"self",
".",
"fname",
",",
"edge",
")",
":",
"coords",
"=",
"split_coords_3d",
"(",
"~",
"edge",
".",
"LineString",
".",
"posList",
")",
"lines",
".",
"append",
"(",
"geo",
".",
"Line",
"(",
"[",
"geo",
".",
"Point",
"(",
"*",
"p",
")",
"for",
"p",
"in",
"coords",
"]",
")",
")",
"return",
"lines"
]
| Utility function to convert a list of edges into a list of
:class:`openquake.hazardlib.geo.Line` instances.
:param edge: a node describing an edge | [
"Utility",
"function",
"to",
"convert",
"a",
"list",
"of",
"edges",
"into",
"a",
"list",
"of",
":",
"class",
":",
"openquake",
".",
"hazardlib",
".",
"geo",
".",
"Line",
"instances",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L342-L354 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | RuptureConverter.geo_planar | def geo_planar(self, surface):
"""
Utility to convert a PlanarSurface node with subnodes
topLeft, topRight, bottomLeft, bottomRight into a
:class:`openquake.hazardlib.geo.PlanarSurface` instance.
:param surface: PlanarSurface node
"""
with context(self.fname, surface):
tl = surface.topLeft
top_left = geo.Point(tl['lon'], tl['lat'], tl['depth'])
tr = surface.topRight
top_right = geo.Point(tr['lon'], tr['lat'], tr['depth'])
bl = surface.bottomLeft
bottom_left = geo.Point(bl['lon'], bl['lat'], bl['depth'])
br = surface.bottomRight
bottom_right = geo.Point(br['lon'], br['lat'], br['depth'])
return geo.PlanarSurface.from_corner_points(
top_left, top_right, bottom_right, bottom_left) | python | def geo_planar(self, surface):
with context(self.fname, surface):
tl = surface.topLeft
top_left = geo.Point(tl['lon'], tl['lat'], tl['depth'])
tr = surface.topRight
top_right = geo.Point(tr['lon'], tr['lat'], tr['depth'])
bl = surface.bottomLeft
bottom_left = geo.Point(bl['lon'], bl['lat'], bl['depth'])
br = surface.bottomRight
bottom_right = geo.Point(br['lon'], br['lat'], br['depth'])
return geo.PlanarSurface.from_corner_points(
top_left, top_right, bottom_right, bottom_left) | [
"def",
"geo_planar",
"(",
"self",
",",
"surface",
")",
":",
"with",
"context",
"(",
"self",
".",
"fname",
",",
"surface",
")",
":",
"tl",
"=",
"surface",
".",
"topLeft",
"top_left",
"=",
"geo",
".",
"Point",
"(",
"tl",
"[",
"'lon'",
"]",
",",
"tl",
"[",
"'lat'",
"]",
",",
"tl",
"[",
"'depth'",
"]",
")",
"tr",
"=",
"surface",
".",
"topRight",
"top_right",
"=",
"geo",
".",
"Point",
"(",
"tr",
"[",
"'lon'",
"]",
",",
"tr",
"[",
"'lat'",
"]",
",",
"tr",
"[",
"'depth'",
"]",
")",
"bl",
"=",
"surface",
".",
"bottomLeft",
"bottom_left",
"=",
"geo",
".",
"Point",
"(",
"bl",
"[",
"'lon'",
"]",
",",
"bl",
"[",
"'lat'",
"]",
",",
"bl",
"[",
"'depth'",
"]",
")",
"br",
"=",
"surface",
".",
"bottomRight",
"bottom_right",
"=",
"geo",
".",
"Point",
"(",
"br",
"[",
"'lon'",
"]",
",",
"br",
"[",
"'lat'",
"]",
",",
"br",
"[",
"'depth'",
"]",
")",
"return",
"geo",
".",
"PlanarSurface",
".",
"from_corner_points",
"(",
"top_left",
",",
"top_right",
",",
"bottom_right",
",",
"bottom_left",
")"
]
| Utility to convert a PlanarSurface node with subnodes
topLeft, topRight, bottomLeft, bottomRight into a
:class:`openquake.hazardlib.geo.PlanarSurface` instance.
:param surface: PlanarSurface node | [
"Utility",
"to",
"convert",
"a",
"PlanarSurface",
"node",
"with",
"subnodes",
"topLeft",
"topRight",
"bottomLeft",
"bottomRight",
"into",
"a",
":",
"class",
":",
"openquake",
".",
"hazardlib",
".",
"geo",
".",
"PlanarSurface",
"instance",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L356-L374 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | RuptureConverter.convert_surfaces | def convert_surfaces(self, surface_nodes):
"""
Utility to convert a list of surface nodes into a single hazardlib
surface. There are four possibilities:
1. there is a single simpleFaultGeometry node; returns a
:class:`openquake.hazardlib.geo.simpleFaultSurface` instance
2. there is a single complexFaultGeometry node; returns a
:class:`openquake.hazardlib.geo.complexFaultSurface` instance
3. there is a single griddedSurface node; returns a
:class:`openquake.hazardlib.geo.GriddedSurface` instance
4. there is a list of PlanarSurface nodes; returns a
:class:`openquake.hazardlib.geo.MultiSurface` instance
:param surface_nodes: surface nodes as just described
"""
surface_node = surface_nodes[0]
if surface_node.tag.endswith('simpleFaultGeometry'):
surface = geo.SimpleFaultSurface.from_fault_data(
self.geo_line(surface_node),
~surface_node.upperSeismoDepth,
~surface_node.lowerSeismoDepth,
~surface_node.dip,
self.rupture_mesh_spacing)
elif surface_node.tag.endswith('complexFaultGeometry'):
surface = geo.ComplexFaultSurface.from_fault_data(
self.geo_lines(surface_node),
self.complex_fault_mesh_spacing)
elif surface_node.tag.endswith('griddedSurface'):
with context(self.fname, surface_node):
coords = split_coords_3d(~surface_node.posList)
points = [geo.Point(*p) for p in coords]
surface = geo.GriddedSurface.from_points_list(points)
else: # a collection of planar surfaces
planar_surfaces = list(map(self.geo_planar, surface_nodes))
surface = geo.MultiSurface(planar_surfaces)
return surface | python | def convert_surfaces(self, surface_nodes):
surface_node = surface_nodes[0]
if surface_node.tag.endswith('simpleFaultGeometry'):
surface = geo.SimpleFaultSurface.from_fault_data(
self.geo_line(surface_node),
~surface_node.upperSeismoDepth,
~surface_node.lowerSeismoDepth,
~surface_node.dip,
self.rupture_mesh_spacing)
elif surface_node.tag.endswith('complexFaultGeometry'):
surface = geo.ComplexFaultSurface.from_fault_data(
self.geo_lines(surface_node),
self.complex_fault_mesh_spacing)
elif surface_node.tag.endswith('griddedSurface'):
with context(self.fname, surface_node):
coords = split_coords_3d(~surface_node.posList)
points = [geo.Point(*p) for p in coords]
surface = geo.GriddedSurface.from_points_list(points)
else:
planar_surfaces = list(map(self.geo_planar, surface_nodes))
surface = geo.MultiSurface(planar_surfaces)
return surface | [
"def",
"convert_surfaces",
"(",
"self",
",",
"surface_nodes",
")",
":",
"surface_node",
"=",
"surface_nodes",
"[",
"0",
"]",
"if",
"surface_node",
".",
"tag",
".",
"endswith",
"(",
"'simpleFaultGeometry'",
")",
":",
"surface",
"=",
"geo",
".",
"SimpleFaultSurface",
".",
"from_fault_data",
"(",
"self",
".",
"geo_line",
"(",
"surface_node",
")",
",",
"~",
"surface_node",
".",
"upperSeismoDepth",
",",
"~",
"surface_node",
".",
"lowerSeismoDepth",
",",
"~",
"surface_node",
".",
"dip",
",",
"self",
".",
"rupture_mesh_spacing",
")",
"elif",
"surface_node",
".",
"tag",
".",
"endswith",
"(",
"'complexFaultGeometry'",
")",
":",
"surface",
"=",
"geo",
".",
"ComplexFaultSurface",
".",
"from_fault_data",
"(",
"self",
".",
"geo_lines",
"(",
"surface_node",
")",
",",
"self",
".",
"complex_fault_mesh_spacing",
")",
"elif",
"surface_node",
".",
"tag",
".",
"endswith",
"(",
"'griddedSurface'",
")",
":",
"with",
"context",
"(",
"self",
".",
"fname",
",",
"surface_node",
")",
":",
"coords",
"=",
"split_coords_3d",
"(",
"~",
"surface_node",
".",
"posList",
")",
"points",
"=",
"[",
"geo",
".",
"Point",
"(",
"*",
"p",
")",
"for",
"p",
"in",
"coords",
"]",
"surface",
"=",
"geo",
".",
"GriddedSurface",
".",
"from_points_list",
"(",
"points",
")",
"else",
":",
"# a collection of planar surfaces",
"planar_surfaces",
"=",
"list",
"(",
"map",
"(",
"self",
".",
"geo_planar",
",",
"surface_nodes",
")",
")",
"surface",
"=",
"geo",
".",
"MultiSurface",
"(",
"planar_surfaces",
")",
"return",
"surface"
]
| Utility to convert a list of surface nodes into a single hazardlib
surface. There are four possibilities:
1. there is a single simpleFaultGeometry node; returns a
:class:`openquake.hazardlib.geo.simpleFaultSurface` instance
2. there is a single complexFaultGeometry node; returns a
:class:`openquake.hazardlib.geo.complexFaultSurface` instance
3. there is a single griddedSurface node; returns a
:class:`openquake.hazardlib.geo.GriddedSurface` instance
4. there is a list of PlanarSurface nodes; returns a
:class:`openquake.hazardlib.geo.MultiSurface` instance
:param surface_nodes: surface nodes as just described | [
"Utility",
"to",
"convert",
"a",
"list",
"of",
"surface",
"nodes",
"into",
"a",
"single",
"hazardlib",
"surface",
".",
"There",
"are",
"four",
"possibilities",
":"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L376-L412 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | RuptureConverter.convert_simpleFaultRupture | def convert_simpleFaultRupture(self, node):
"""
Convert a simpleFaultRupture node.
:param node: the rupture node
"""
mag, rake, hypocenter = self.get_mag_rake_hypo(node)
with context(self.fname, node):
surfaces = [node.simpleFaultGeometry]
rupt = source.rupture.BaseRupture(
mag=mag, rake=rake, tectonic_region_type=None,
hypocenter=hypocenter,
surface=self.convert_surfaces(surfaces))
return rupt | python | def convert_simpleFaultRupture(self, node):
mag, rake, hypocenter = self.get_mag_rake_hypo(node)
with context(self.fname, node):
surfaces = [node.simpleFaultGeometry]
rupt = source.rupture.BaseRupture(
mag=mag, rake=rake, tectonic_region_type=None,
hypocenter=hypocenter,
surface=self.convert_surfaces(surfaces))
return rupt | [
"def",
"convert_simpleFaultRupture",
"(",
"self",
",",
"node",
")",
":",
"mag",
",",
"rake",
",",
"hypocenter",
"=",
"self",
".",
"get_mag_rake_hypo",
"(",
"node",
")",
"with",
"context",
"(",
"self",
".",
"fname",
",",
"node",
")",
":",
"surfaces",
"=",
"[",
"node",
".",
"simpleFaultGeometry",
"]",
"rupt",
"=",
"source",
".",
"rupture",
".",
"BaseRupture",
"(",
"mag",
"=",
"mag",
",",
"rake",
"=",
"rake",
",",
"tectonic_region_type",
"=",
"None",
",",
"hypocenter",
"=",
"hypocenter",
",",
"surface",
"=",
"self",
".",
"convert_surfaces",
"(",
"surfaces",
")",
")",
"return",
"rupt"
]
| Convert a simpleFaultRupture node.
:param node: the rupture node | [
"Convert",
"a",
"simpleFaultRupture",
"node",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L414-L427 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | RuptureConverter.convert_multiPlanesRupture | def convert_multiPlanesRupture(self, node):
"""
Convert a multiPlanesRupture node.
:param node: the rupture node
"""
mag, rake, hypocenter = self.get_mag_rake_hypo(node)
with context(self.fname, node):
surfaces = list(node.getnodes('planarSurface'))
rupt = source.rupture.BaseRupture(
mag=mag, rake=rake,
tectonic_region_type=None,
hypocenter=hypocenter,
surface=self.convert_surfaces(surfaces))
return rupt | python | def convert_multiPlanesRupture(self, node):
mag, rake, hypocenter = self.get_mag_rake_hypo(node)
with context(self.fname, node):
surfaces = list(node.getnodes('planarSurface'))
rupt = source.rupture.BaseRupture(
mag=mag, rake=rake,
tectonic_region_type=None,
hypocenter=hypocenter,
surface=self.convert_surfaces(surfaces))
return rupt | [
"def",
"convert_multiPlanesRupture",
"(",
"self",
",",
"node",
")",
":",
"mag",
",",
"rake",
",",
"hypocenter",
"=",
"self",
".",
"get_mag_rake_hypo",
"(",
"node",
")",
"with",
"context",
"(",
"self",
".",
"fname",
",",
"node",
")",
":",
"surfaces",
"=",
"list",
"(",
"node",
".",
"getnodes",
"(",
"'planarSurface'",
")",
")",
"rupt",
"=",
"source",
".",
"rupture",
".",
"BaseRupture",
"(",
"mag",
"=",
"mag",
",",
"rake",
"=",
"rake",
",",
"tectonic_region_type",
"=",
"None",
",",
"hypocenter",
"=",
"hypocenter",
",",
"surface",
"=",
"self",
".",
"convert_surfaces",
"(",
"surfaces",
")",
")",
"return",
"rupt"
]
| Convert a multiPlanesRupture node.
:param node: the rupture node | [
"Convert",
"a",
"multiPlanesRupture",
"node",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L460-L474 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | RuptureConverter.convert_ruptureCollection | def convert_ruptureCollection(self, node):
"""
:param node: a ruptureCollection node
:returns: a dictionary grp_id -> EBRuptures
"""
coll = {}
for grpnode in node:
grp_id = int(grpnode['id'])
coll[grp_id] = ebrs = []
for node in grpnode:
rup = self.convert_node(node)
rup.serial = int(node['id'])
sesnodes = node.stochasticEventSets
n = 0 # number of events
for sesnode in sesnodes:
with context(self.fname, sesnode):
n += len(sesnode.text.split())
ebr = source.rupture.EBRupture(rup, 0, 0, numpy.array([n]))
ebrs.append(ebr)
return coll | python | def convert_ruptureCollection(self, node):
coll = {}
for grpnode in node:
grp_id = int(grpnode['id'])
coll[grp_id] = ebrs = []
for node in grpnode:
rup = self.convert_node(node)
rup.serial = int(node['id'])
sesnodes = node.stochasticEventSets
n = 0
for sesnode in sesnodes:
with context(self.fname, sesnode):
n += len(sesnode.text.split())
ebr = source.rupture.EBRupture(rup, 0, 0, numpy.array([n]))
ebrs.append(ebr)
return coll | [
"def",
"convert_ruptureCollection",
"(",
"self",
",",
"node",
")",
":",
"coll",
"=",
"{",
"}",
"for",
"grpnode",
"in",
"node",
":",
"grp_id",
"=",
"int",
"(",
"grpnode",
"[",
"'id'",
"]",
")",
"coll",
"[",
"grp_id",
"]",
"=",
"ebrs",
"=",
"[",
"]",
"for",
"node",
"in",
"grpnode",
":",
"rup",
"=",
"self",
".",
"convert_node",
"(",
"node",
")",
"rup",
".",
"serial",
"=",
"int",
"(",
"node",
"[",
"'id'",
"]",
")",
"sesnodes",
"=",
"node",
".",
"stochasticEventSets",
"n",
"=",
"0",
"# number of events",
"for",
"sesnode",
"in",
"sesnodes",
":",
"with",
"context",
"(",
"self",
".",
"fname",
",",
"sesnode",
")",
":",
"n",
"+=",
"len",
"(",
"sesnode",
".",
"text",
".",
"split",
"(",
")",
")",
"ebr",
"=",
"source",
".",
"rupture",
".",
"EBRupture",
"(",
"rup",
",",
"0",
",",
"0",
",",
"numpy",
".",
"array",
"(",
"[",
"n",
"]",
")",
")",
"ebrs",
".",
"append",
"(",
"ebr",
")",
"return",
"coll"
]
| :param node: a ruptureCollection node
:returns: a dictionary grp_id -> EBRuptures | [
":",
"param",
"node",
":",
"a",
"ruptureCollection",
"node",
":",
"returns",
":",
"a",
"dictionary",
"grp_id",
"-",
">",
"EBRuptures"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L492-L511 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | SourceConverter.get_tom | def get_tom(self, node):
"""
Convert the given node into a Temporal Occurrence Model object.
:param node: a node of kind poissonTOM or brownianTOM
:returns: a :class:`openquake.hazardlib.mfd.EvenlyDiscretizedMFD.` or
:class:`openquake.hazardlib.mfd.TruncatedGRMFD` instance
"""
if 'tom' in node.attrib:
tom_cls = tom.registry[node['tom']]
else:
tom_cls = tom.registry['PoissonTOM']
return tom_cls(time_span=self.investigation_time,
occurrence_rate=node.get('occurrence_rate')) | python | def get_tom(self, node):
if 'tom' in node.attrib:
tom_cls = tom.registry[node['tom']]
else:
tom_cls = tom.registry['PoissonTOM']
return tom_cls(time_span=self.investigation_time,
occurrence_rate=node.get('occurrence_rate')) | [
"def",
"get_tom",
"(",
"self",
",",
"node",
")",
":",
"if",
"'tom'",
"in",
"node",
".",
"attrib",
":",
"tom_cls",
"=",
"tom",
".",
"registry",
"[",
"node",
"[",
"'tom'",
"]",
"]",
"else",
":",
"tom_cls",
"=",
"tom",
".",
"registry",
"[",
"'PoissonTOM'",
"]",
"return",
"tom_cls",
"(",
"time_span",
"=",
"self",
".",
"investigation_time",
",",
"occurrence_rate",
"=",
"node",
".",
"get",
"(",
"'occurrence_rate'",
")",
")"
]
| Convert the given node into a Temporal Occurrence Model object.
:param node: a node of kind poissonTOM or brownianTOM
:returns: a :class:`openquake.hazardlib.mfd.EvenlyDiscretizedMFD.` or
:class:`openquake.hazardlib.mfd.TruncatedGRMFD` instance | [
"Convert",
"the",
"given",
"node",
"into",
"a",
"Temporal",
"Occurrence",
"Model",
"object",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L533-L546 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | SourceConverter.convert_mfdist | def convert_mfdist(self, node):
"""
Convert the given node into a Magnitude-Frequency Distribution
object.
:param node: a node of kind incrementalMFD or truncGutenbergRichterMFD
:returns: a :class:`openquake.hazardlib.mfd.EvenlyDiscretizedMFD.` or
:class:`openquake.hazardlib.mfd.TruncatedGRMFD` instance
"""
with context(self.fname, node):
[mfd_node] = [subnode for subnode in node
if subnode.tag.endswith(
('incrementalMFD', 'truncGutenbergRichterMFD',
'arbitraryMFD', 'YoungsCoppersmithMFD',
'multiMFD'))]
if mfd_node.tag.endswith('incrementalMFD'):
return mfd.EvenlyDiscretizedMFD(
min_mag=mfd_node['minMag'], bin_width=mfd_node['binWidth'],
occurrence_rates=~mfd_node.occurRates)
elif mfd_node.tag.endswith('truncGutenbergRichterMFD'):
return mfd.TruncatedGRMFD(
a_val=mfd_node['aValue'], b_val=mfd_node['bValue'],
min_mag=mfd_node['minMag'], max_mag=mfd_node['maxMag'],
bin_width=self.width_of_mfd_bin)
elif mfd_node.tag.endswith('arbitraryMFD'):
return mfd.ArbitraryMFD(
magnitudes=~mfd_node.magnitudes,
occurrence_rates=~mfd_node.occurRates)
elif mfd_node.tag.endswith('YoungsCoppersmithMFD'):
if "totalMomentRate" in mfd_node.attrib.keys():
# Return Youngs & Coppersmith from the total moment rate
return mfd.YoungsCoppersmith1985MFD.from_total_moment_rate(
min_mag=mfd_node["minMag"], b_val=mfd_node["bValue"],
char_mag=mfd_node["characteristicMag"],
total_moment_rate=mfd_node["totalMomentRate"],
bin_width=mfd_node["binWidth"])
elif "characteristicRate" in mfd_node.attrib.keys():
# Return Youngs & Coppersmith from the total moment rate
return mfd.YoungsCoppersmith1985MFD.\
from_characteristic_rate(
min_mag=mfd_node["minMag"],
b_val=mfd_node["bValue"],
char_mag=mfd_node["characteristicMag"],
char_rate=mfd_node["characteristicRate"],
bin_width=mfd_node["binWidth"])
elif mfd_node.tag.endswith('multiMFD'):
return mfd.multi_mfd.MultiMFD.from_node(
mfd_node, self.width_of_mfd_bin) | python | def convert_mfdist(self, node):
with context(self.fname, node):
[mfd_node] = [subnode for subnode in node
if subnode.tag.endswith(
('incrementalMFD', 'truncGutenbergRichterMFD',
'arbitraryMFD', 'YoungsCoppersmithMFD',
'multiMFD'))]
if mfd_node.tag.endswith('incrementalMFD'):
return mfd.EvenlyDiscretizedMFD(
min_mag=mfd_node['minMag'], bin_width=mfd_node['binWidth'],
occurrence_rates=~mfd_node.occurRates)
elif mfd_node.tag.endswith('truncGutenbergRichterMFD'):
return mfd.TruncatedGRMFD(
a_val=mfd_node['aValue'], b_val=mfd_node['bValue'],
min_mag=mfd_node['minMag'], max_mag=mfd_node['maxMag'],
bin_width=self.width_of_mfd_bin)
elif mfd_node.tag.endswith('arbitraryMFD'):
return mfd.ArbitraryMFD(
magnitudes=~mfd_node.magnitudes,
occurrence_rates=~mfd_node.occurRates)
elif mfd_node.tag.endswith('YoungsCoppersmithMFD'):
if "totalMomentRate" in mfd_node.attrib.keys():
return mfd.YoungsCoppersmith1985MFD.from_total_moment_rate(
min_mag=mfd_node["minMag"], b_val=mfd_node["bValue"],
char_mag=mfd_node["characteristicMag"],
total_moment_rate=mfd_node["totalMomentRate"],
bin_width=mfd_node["binWidth"])
elif "characteristicRate" in mfd_node.attrib.keys():
return mfd.YoungsCoppersmith1985MFD.\
from_characteristic_rate(
min_mag=mfd_node["minMag"],
b_val=mfd_node["bValue"],
char_mag=mfd_node["characteristicMag"],
char_rate=mfd_node["characteristicRate"],
bin_width=mfd_node["binWidth"])
elif mfd_node.tag.endswith('multiMFD'):
return mfd.multi_mfd.MultiMFD.from_node(
mfd_node, self.width_of_mfd_bin) | [
"def",
"convert_mfdist",
"(",
"self",
",",
"node",
")",
":",
"with",
"context",
"(",
"self",
".",
"fname",
",",
"node",
")",
":",
"[",
"mfd_node",
"]",
"=",
"[",
"subnode",
"for",
"subnode",
"in",
"node",
"if",
"subnode",
".",
"tag",
".",
"endswith",
"(",
"(",
"'incrementalMFD'",
",",
"'truncGutenbergRichterMFD'",
",",
"'arbitraryMFD'",
",",
"'YoungsCoppersmithMFD'",
",",
"'multiMFD'",
")",
")",
"]",
"if",
"mfd_node",
".",
"tag",
".",
"endswith",
"(",
"'incrementalMFD'",
")",
":",
"return",
"mfd",
".",
"EvenlyDiscretizedMFD",
"(",
"min_mag",
"=",
"mfd_node",
"[",
"'minMag'",
"]",
",",
"bin_width",
"=",
"mfd_node",
"[",
"'binWidth'",
"]",
",",
"occurrence_rates",
"=",
"~",
"mfd_node",
".",
"occurRates",
")",
"elif",
"mfd_node",
".",
"tag",
".",
"endswith",
"(",
"'truncGutenbergRichterMFD'",
")",
":",
"return",
"mfd",
".",
"TruncatedGRMFD",
"(",
"a_val",
"=",
"mfd_node",
"[",
"'aValue'",
"]",
",",
"b_val",
"=",
"mfd_node",
"[",
"'bValue'",
"]",
",",
"min_mag",
"=",
"mfd_node",
"[",
"'minMag'",
"]",
",",
"max_mag",
"=",
"mfd_node",
"[",
"'maxMag'",
"]",
",",
"bin_width",
"=",
"self",
".",
"width_of_mfd_bin",
")",
"elif",
"mfd_node",
".",
"tag",
".",
"endswith",
"(",
"'arbitraryMFD'",
")",
":",
"return",
"mfd",
".",
"ArbitraryMFD",
"(",
"magnitudes",
"=",
"~",
"mfd_node",
".",
"magnitudes",
",",
"occurrence_rates",
"=",
"~",
"mfd_node",
".",
"occurRates",
")",
"elif",
"mfd_node",
".",
"tag",
".",
"endswith",
"(",
"'YoungsCoppersmithMFD'",
")",
":",
"if",
"\"totalMomentRate\"",
"in",
"mfd_node",
".",
"attrib",
".",
"keys",
"(",
")",
":",
"# Return Youngs & Coppersmith from the total moment rate",
"return",
"mfd",
".",
"YoungsCoppersmith1985MFD",
".",
"from_total_moment_rate",
"(",
"min_mag",
"=",
"mfd_node",
"[",
"\"minMag\"",
"]",
",",
"b_val",
"=",
"mfd_node",
"[",
"\"bValue\"",
"]",
",",
"char_mag",
"=",
"mfd_node",
"[",
"\"characteristicMag\"",
"]",
",",
"total_moment_rate",
"=",
"mfd_node",
"[",
"\"totalMomentRate\"",
"]",
",",
"bin_width",
"=",
"mfd_node",
"[",
"\"binWidth\"",
"]",
")",
"elif",
"\"characteristicRate\"",
"in",
"mfd_node",
".",
"attrib",
".",
"keys",
"(",
")",
":",
"# Return Youngs & Coppersmith from the total moment rate",
"return",
"mfd",
".",
"YoungsCoppersmith1985MFD",
".",
"from_characteristic_rate",
"(",
"min_mag",
"=",
"mfd_node",
"[",
"\"minMag\"",
"]",
",",
"b_val",
"=",
"mfd_node",
"[",
"\"bValue\"",
"]",
",",
"char_mag",
"=",
"mfd_node",
"[",
"\"characteristicMag\"",
"]",
",",
"char_rate",
"=",
"mfd_node",
"[",
"\"characteristicRate\"",
"]",
",",
"bin_width",
"=",
"mfd_node",
"[",
"\"binWidth\"",
"]",
")",
"elif",
"mfd_node",
".",
"tag",
".",
"endswith",
"(",
"'multiMFD'",
")",
":",
"return",
"mfd",
".",
"multi_mfd",
".",
"MultiMFD",
".",
"from_node",
"(",
"mfd_node",
",",
"self",
".",
"width_of_mfd_bin",
")"
]
| Convert the given node into a Magnitude-Frequency Distribution
object.
:param node: a node of kind incrementalMFD or truncGutenbergRichterMFD
:returns: a :class:`openquake.hazardlib.mfd.EvenlyDiscretizedMFD.` or
:class:`openquake.hazardlib.mfd.TruncatedGRMFD` instance | [
"Convert",
"the",
"given",
"node",
"into",
"a",
"Magnitude",
"-",
"Frequency",
"Distribution",
"object",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L548-L595 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | SourceConverter.convert_npdist | def convert_npdist(self, node):
"""
Convert the given node into a Nodal Plane Distribution.
:param node: a nodalPlaneDist node
:returns: a :class:`openquake.hazardlib.geo.NodalPlane` instance
"""
with context(self.fname, node):
npdist = []
for np in node.nodalPlaneDist:
prob, strike, dip, rake = (
np['probability'], np['strike'], np['dip'], np['rake'])
npdist.append((prob, geo.NodalPlane(strike, dip, rake)))
if not self.spinning_floating:
npdist = [(1, npdist[0][1])] # consider the first nodal plane
return pmf.PMF(npdist) | python | def convert_npdist(self, node):
with context(self.fname, node):
npdist = []
for np in node.nodalPlaneDist:
prob, strike, dip, rake = (
np['probability'], np['strike'], np['dip'], np['rake'])
npdist.append((prob, geo.NodalPlane(strike, dip, rake)))
if not self.spinning_floating:
npdist = [(1, npdist[0][1])]
return pmf.PMF(npdist) | [
"def",
"convert_npdist",
"(",
"self",
",",
"node",
")",
":",
"with",
"context",
"(",
"self",
".",
"fname",
",",
"node",
")",
":",
"npdist",
"=",
"[",
"]",
"for",
"np",
"in",
"node",
".",
"nodalPlaneDist",
":",
"prob",
",",
"strike",
",",
"dip",
",",
"rake",
"=",
"(",
"np",
"[",
"'probability'",
"]",
",",
"np",
"[",
"'strike'",
"]",
",",
"np",
"[",
"'dip'",
"]",
",",
"np",
"[",
"'rake'",
"]",
")",
"npdist",
".",
"append",
"(",
"(",
"prob",
",",
"geo",
".",
"NodalPlane",
"(",
"strike",
",",
"dip",
",",
"rake",
")",
")",
")",
"if",
"not",
"self",
".",
"spinning_floating",
":",
"npdist",
"=",
"[",
"(",
"1",
",",
"npdist",
"[",
"0",
"]",
"[",
"1",
"]",
")",
"]",
"# consider the first nodal plane",
"return",
"pmf",
".",
"PMF",
"(",
"npdist",
")"
]
| Convert the given node into a Nodal Plane Distribution.
:param node: a nodalPlaneDist node
:returns: a :class:`openquake.hazardlib.geo.NodalPlane` instance | [
"Convert",
"the",
"given",
"node",
"into",
"a",
"Nodal",
"Plane",
"Distribution",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L597-L612 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | SourceConverter.convert_hpdist | def convert_hpdist(self, node):
"""
Convert the given node into a probability mass function for the
hypo depth distribution.
:param node: a hypoDepthDist node
:returns: a :class:`openquake.hazardlib.pmf.PMF` instance
"""
with context(self.fname, node):
hcdist = [(hd['probability'], hd['depth'])
for hd in node.hypoDepthDist]
if not self.spinning_floating: # consider the first hypocenter
hcdist = [(1, hcdist[0][1])]
return pmf.PMF(hcdist) | python | def convert_hpdist(self, node):
with context(self.fname, node):
hcdist = [(hd['probability'], hd['depth'])
for hd in node.hypoDepthDist]
if not self.spinning_floating:
hcdist = [(1, hcdist[0][1])]
return pmf.PMF(hcdist) | [
"def",
"convert_hpdist",
"(",
"self",
",",
"node",
")",
":",
"with",
"context",
"(",
"self",
".",
"fname",
",",
"node",
")",
":",
"hcdist",
"=",
"[",
"(",
"hd",
"[",
"'probability'",
"]",
",",
"hd",
"[",
"'depth'",
"]",
")",
"for",
"hd",
"in",
"node",
".",
"hypoDepthDist",
"]",
"if",
"not",
"self",
".",
"spinning_floating",
":",
"# consider the first hypocenter",
"hcdist",
"=",
"[",
"(",
"1",
",",
"hcdist",
"[",
"0",
"]",
"[",
"1",
"]",
")",
"]",
"return",
"pmf",
".",
"PMF",
"(",
"hcdist",
")"
]
| Convert the given node into a probability mass function for the
hypo depth distribution.
:param node: a hypoDepthDist node
:returns: a :class:`openquake.hazardlib.pmf.PMF` instance | [
"Convert",
"the",
"given",
"node",
"into",
"a",
"probability",
"mass",
"function",
"for",
"the",
"hypo",
"depth",
"distribution",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L614-L627 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | SourceConverter.convert_areaSource | def convert_areaSource(self, node):
"""
Convert the given node into an area source object.
:param node: a node with tag areaGeometry
:returns: a :class:`openquake.hazardlib.source.AreaSource` instance
"""
geom = node.areaGeometry
coords = split_coords_2d(~geom.Polygon.exterior.LinearRing.posList)
polygon = geo.Polygon([geo.Point(*xy) for xy in coords])
msr = valid.SCALEREL[~node.magScaleRel]()
area_discretization = geom.attrib.get(
'discretization', self.area_source_discretization)
if area_discretization is None:
raise ValueError(
'The source %r has no `discretization` parameter and the job.'
'ini file has no `area_source_discretization` parameter either'
% node['id'])
return source.AreaSource(
source_id=node['id'],
name=node['name'],
tectonic_region_type=node.attrib.get('tectonicRegion'),
mfd=self.convert_mfdist(node),
rupture_mesh_spacing=self.rupture_mesh_spacing,
magnitude_scaling_relationship=msr,
rupture_aspect_ratio=~node.ruptAspectRatio,
upper_seismogenic_depth=~geom.upperSeismoDepth,
lower_seismogenic_depth=~geom.lowerSeismoDepth,
nodal_plane_distribution=self.convert_npdist(node),
hypocenter_distribution=self.convert_hpdist(node),
polygon=polygon,
area_discretization=area_discretization,
temporal_occurrence_model=self.get_tom(node)) | python | def convert_areaSource(self, node):
geom = node.areaGeometry
coords = split_coords_2d(~geom.Polygon.exterior.LinearRing.posList)
polygon = geo.Polygon([geo.Point(*xy) for xy in coords])
msr = valid.SCALEREL[~node.magScaleRel]()
area_discretization = geom.attrib.get(
'discretization', self.area_source_discretization)
if area_discretization is None:
raise ValueError(
'The source %r has no `discretization` parameter and the job.'
'ini file has no `area_source_discretization` parameter either'
% node['id'])
return source.AreaSource(
source_id=node['id'],
name=node['name'],
tectonic_region_type=node.attrib.get('tectonicRegion'),
mfd=self.convert_mfdist(node),
rupture_mesh_spacing=self.rupture_mesh_spacing,
magnitude_scaling_relationship=msr,
rupture_aspect_ratio=~node.ruptAspectRatio,
upper_seismogenic_depth=~geom.upperSeismoDepth,
lower_seismogenic_depth=~geom.lowerSeismoDepth,
nodal_plane_distribution=self.convert_npdist(node),
hypocenter_distribution=self.convert_hpdist(node),
polygon=polygon,
area_discretization=area_discretization,
temporal_occurrence_model=self.get_tom(node)) | [
"def",
"convert_areaSource",
"(",
"self",
",",
"node",
")",
":",
"geom",
"=",
"node",
".",
"areaGeometry",
"coords",
"=",
"split_coords_2d",
"(",
"~",
"geom",
".",
"Polygon",
".",
"exterior",
".",
"LinearRing",
".",
"posList",
")",
"polygon",
"=",
"geo",
".",
"Polygon",
"(",
"[",
"geo",
".",
"Point",
"(",
"*",
"xy",
")",
"for",
"xy",
"in",
"coords",
"]",
")",
"msr",
"=",
"valid",
".",
"SCALEREL",
"[",
"~",
"node",
".",
"magScaleRel",
"]",
"(",
")",
"area_discretization",
"=",
"geom",
".",
"attrib",
".",
"get",
"(",
"'discretization'",
",",
"self",
".",
"area_source_discretization",
")",
"if",
"area_discretization",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'The source %r has no `discretization` parameter and the job.'",
"'ini file has no `area_source_discretization` parameter either'",
"%",
"node",
"[",
"'id'",
"]",
")",
"return",
"source",
".",
"AreaSource",
"(",
"source_id",
"=",
"node",
"[",
"'id'",
"]",
",",
"name",
"=",
"node",
"[",
"'name'",
"]",
",",
"tectonic_region_type",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'tectonicRegion'",
")",
",",
"mfd",
"=",
"self",
".",
"convert_mfdist",
"(",
"node",
")",
",",
"rupture_mesh_spacing",
"=",
"self",
".",
"rupture_mesh_spacing",
",",
"magnitude_scaling_relationship",
"=",
"msr",
",",
"rupture_aspect_ratio",
"=",
"~",
"node",
".",
"ruptAspectRatio",
",",
"upper_seismogenic_depth",
"=",
"~",
"geom",
".",
"upperSeismoDepth",
",",
"lower_seismogenic_depth",
"=",
"~",
"geom",
".",
"lowerSeismoDepth",
",",
"nodal_plane_distribution",
"=",
"self",
".",
"convert_npdist",
"(",
"node",
")",
",",
"hypocenter_distribution",
"=",
"self",
".",
"convert_hpdist",
"(",
"node",
")",
",",
"polygon",
"=",
"polygon",
",",
"area_discretization",
"=",
"area_discretization",
",",
"temporal_occurrence_model",
"=",
"self",
".",
"get_tom",
"(",
"node",
")",
")"
]
| Convert the given node into an area source object.
:param node: a node with tag areaGeometry
:returns: a :class:`openquake.hazardlib.source.AreaSource` instance | [
"Convert",
"the",
"given",
"node",
"into",
"an",
"area",
"source",
"object",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L629-L661 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | SourceConverter.convert_pointSource | def convert_pointSource(self, node):
"""
Convert the given node into a point source object.
:param node: a node with tag pointGeometry
:returns: a :class:`openquake.hazardlib.source.PointSource` instance
"""
geom = node.pointGeometry
lon_lat = ~geom.Point.pos
msr = valid.SCALEREL[~node.magScaleRel]()
return source.PointSource(
source_id=node['id'],
name=node['name'],
tectonic_region_type=node.attrib.get('tectonicRegion'),
mfd=self.convert_mfdist(node),
rupture_mesh_spacing=self.rupture_mesh_spacing,
magnitude_scaling_relationship=msr,
rupture_aspect_ratio=~node.ruptAspectRatio,
upper_seismogenic_depth=~geom.upperSeismoDepth,
lower_seismogenic_depth=~geom.lowerSeismoDepth,
location=geo.Point(*lon_lat),
nodal_plane_distribution=self.convert_npdist(node),
hypocenter_distribution=self.convert_hpdist(node),
temporal_occurrence_model=self.get_tom(node)) | python | def convert_pointSource(self, node):
geom = node.pointGeometry
lon_lat = ~geom.Point.pos
msr = valid.SCALEREL[~node.magScaleRel]()
return source.PointSource(
source_id=node['id'],
name=node['name'],
tectonic_region_type=node.attrib.get('tectonicRegion'),
mfd=self.convert_mfdist(node),
rupture_mesh_spacing=self.rupture_mesh_spacing,
magnitude_scaling_relationship=msr,
rupture_aspect_ratio=~node.ruptAspectRatio,
upper_seismogenic_depth=~geom.upperSeismoDepth,
lower_seismogenic_depth=~geom.lowerSeismoDepth,
location=geo.Point(*lon_lat),
nodal_plane_distribution=self.convert_npdist(node),
hypocenter_distribution=self.convert_hpdist(node),
temporal_occurrence_model=self.get_tom(node)) | [
"def",
"convert_pointSource",
"(",
"self",
",",
"node",
")",
":",
"geom",
"=",
"node",
".",
"pointGeometry",
"lon_lat",
"=",
"~",
"geom",
".",
"Point",
".",
"pos",
"msr",
"=",
"valid",
".",
"SCALEREL",
"[",
"~",
"node",
".",
"magScaleRel",
"]",
"(",
")",
"return",
"source",
".",
"PointSource",
"(",
"source_id",
"=",
"node",
"[",
"'id'",
"]",
",",
"name",
"=",
"node",
"[",
"'name'",
"]",
",",
"tectonic_region_type",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'tectonicRegion'",
")",
",",
"mfd",
"=",
"self",
".",
"convert_mfdist",
"(",
"node",
")",
",",
"rupture_mesh_spacing",
"=",
"self",
".",
"rupture_mesh_spacing",
",",
"magnitude_scaling_relationship",
"=",
"msr",
",",
"rupture_aspect_ratio",
"=",
"~",
"node",
".",
"ruptAspectRatio",
",",
"upper_seismogenic_depth",
"=",
"~",
"geom",
".",
"upperSeismoDepth",
",",
"lower_seismogenic_depth",
"=",
"~",
"geom",
".",
"lowerSeismoDepth",
",",
"location",
"=",
"geo",
".",
"Point",
"(",
"*",
"lon_lat",
")",
",",
"nodal_plane_distribution",
"=",
"self",
".",
"convert_npdist",
"(",
"node",
")",
",",
"hypocenter_distribution",
"=",
"self",
".",
"convert_hpdist",
"(",
"node",
")",
",",
"temporal_occurrence_model",
"=",
"self",
".",
"get_tom",
"(",
"node",
")",
")"
]
| Convert the given node into a point source object.
:param node: a node with tag pointGeometry
:returns: a :class:`openquake.hazardlib.source.PointSource` instance | [
"Convert",
"the",
"given",
"node",
"into",
"a",
"point",
"source",
"object",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L663-L686 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | SourceConverter.convert_multiPointSource | def convert_multiPointSource(self, node):
"""
Convert the given node into a MultiPointSource object.
:param node: a node with tag multiPointGeometry
:returns: a :class:`openquake.hazardlib.source.MultiPointSource`
"""
geom = node.multiPointGeometry
lons, lats = zip(*split_coords_2d(~geom.posList))
msr = valid.SCALEREL[~node.magScaleRel]()
return source.MultiPointSource(
source_id=node['id'],
name=node['name'],
tectonic_region_type=node.attrib.get('tectonicRegion'),
mfd=self.convert_mfdist(node),
magnitude_scaling_relationship=msr,
rupture_aspect_ratio=~node.ruptAspectRatio,
upper_seismogenic_depth=~geom.upperSeismoDepth,
lower_seismogenic_depth=~geom.lowerSeismoDepth,
nodal_plane_distribution=self.convert_npdist(node),
hypocenter_distribution=self.convert_hpdist(node),
mesh=geo.Mesh(F32(lons), F32(lats)),
temporal_occurrence_model=self.get_tom(node)) | python | def convert_multiPointSource(self, node):
geom = node.multiPointGeometry
lons, lats = zip(*split_coords_2d(~geom.posList))
msr = valid.SCALEREL[~node.magScaleRel]()
return source.MultiPointSource(
source_id=node['id'],
name=node['name'],
tectonic_region_type=node.attrib.get('tectonicRegion'),
mfd=self.convert_mfdist(node),
magnitude_scaling_relationship=msr,
rupture_aspect_ratio=~node.ruptAspectRatio,
upper_seismogenic_depth=~geom.upperSeismoDepth,
lower_seismogenic_depth=~geom.lowerSeismoDepth,
nodal_plane_distribution=self.convert_npdist(node),
hypocenter_distribution=self.convert_hpdist(node),
mesh=geo.Mesh(F32(lons), F32(lats)),
temporal_occurrence_model=self.get_tom(node)) | [
"def",
"convert_multiPointSource",
"(",
"self",
",",
"node",
")",
":",
"geom",
"=",
"node",
".",
"multiPointGeometry",
"lons",
",",
"lats",
"=",
"zip",
"(",
"*",
"split_coords_2d",
"(",
"~",
"geom",
".",
"posList",
")",
")",
"msr",
"=",
"valid",
".",
"SCALEREL",
"[",
"~",
"node",
".",
"magScaleRel",
"]",
"(",
")",
"return",
"source",
".",
"MultiPointSource",
"(",
"source_id",
"=",
"node",
"[",
"'id'",
"]",
",",
"name",
"=",
"node",
"[",
"'name'",
"]",
",",
"tectonic_region_type",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'tectonicRegion'",
")",
",",
"mfd",
"=",
"self",
".",
"convert_mfdist",
"(",
"node",
")",
",",
"magnitude_scaling_relationship",
"=",
"msr",
",",
"rupture_aspect_ratio",
"=",
"~",
"node",
".",
"ruptAspectRatio",
",",
"upper_seismogenic_depth",
"=",
"~",
"geom",
".",
"upperSeismoDepth",
",",
"lower_seismogenic_depth",
"=",
"~",
"geom",
".",
"lowerSeismoDepth",
",",
"nodal_plane_distribution",
"=",
"self",
".",
"convert_npdist",
"(",
"node",
")",
",",
"hypocenter_distribution",
"=",
"self",
".",
"convert_hpdist",
"(",
"node",
")",
",",
"mesh",
"=",
"geo",
".",
"Mesh",
"(",
"F32",
"(",
"lons",
")",
",",
"F32",
"(",
"lats",
")",
")",
",",
"temporal_occurrence_model",
"=",
"self",
".",
"get_tom",
"(",
"node",
")",
")"
]
| Convert the given node into a MultiPointSource object.
:param node: a node with tag multiPointGeometry
:returns: a :class:`openquake.hazardlib.source.MultiPointSource` | [
"Convert",
"the",
"given",
"node",
"into",
"a",
"MultiPointSource",
"object",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L688-L710 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | SourceConverter.convert_simpleFaultSource | def convert_simpleFaultSource(self, node):
"""
Convert the given node into a simple fault object.
:param node: a node with tag areaGeometry
:returns: a :class:`openquake.hazardlib.source.SimpleFaultSource`
instance
"""
geom = node.simpleFaultGeometry
msr = valid.SCALEREL[~node.magScaleRel]()
fault_trace = self.geo_line(geom)
mfd = self.convert_mfdist(node)
with context(self.fname, node):
try:
hypo_list = valid.hypo_list(node.hypoList)
except AttributeError:
hypo_list = ()
try:
slip_list = valid.slip_list(node.slipList)
except AttributeError:
slip_list = ()
simple = source.SimpleFaultSource(
source_id=node['id'],
name=node['name'],
tectonic_region_type=node.attrib.get('tectonicRegion'),
mfd=mfd,
rupture_mesh_spacing=self.rupture_mesh_spacing,
magnitude_scaling_relationship=msr,
rupture_aspect_ratio=~node.ruptAspectRatio,
upper_seismogenic_depth=~geom.upperSeismoDepth,
lower_seismogenic_depth=~geom.lowerSeismoDepth,
fault_trace=fault_trace,
dip=~geom.dip,
rake=~node.rake,
temporal_occurrence_model=self.get_tom(node),
hypo_list=hypo_list,
slip_list=slip_list)
return simple | python | def convert_simpleFaultSource(self, node):
geom = node.simpleFaultGeometry
msr = valid.SCALEREL[~node.magScaleRel]()
fault_trace = self.geo_line(geom)
mfd = self.convert_mfdist(node)
with context(self.fname, node):
try:
hypo_list = valid.hypo_list(node.hypoList)
except AttributeError:
hypo_list = ()
try:
slip_list = valid.slip_list(node.slipList)
except AttributeError:
slip_list = ()
simple = source.SimpleFaultSource(
source_id=node['id'],
name=node['name'],
tectonic_region_type=node.attrib.get('tectonicRegion'),
mfd=mfd,
rupture_mesh_spacing=self.rupture_mesh_spacing,
magnitude_scaling_relationship=msr,
rupture_aspect_ratio=~node.ruptAspectRatio,
upper_seismogenic_depth=~geom.upperSeismoDepth,
lower_seismogenic_depth=~geom.lowerSeismoDepth,
fault_trace=fault_trace,
dip=~geom.dip,
rake=~node.rake,
temporal_occurrence_model=self.get_tom(node),
hypo_list=hypo_list,
slip_list=slip_list)
return simple | [
"def",
"convert_simpleFaultSource",
"(",
"self",
",",
"node",
")",
":",
"geom",
"=",
"node",
".",
"simpleFaultGeometry",
"msr",
"=",
"valid",
".",
"SCALEREL",
"[",
"~",
"node",
".",
"magScaleRel",
"]",
"(",
")",
"fault_trace",
"=",
"self",
".",
"geo_line",
"(",
"geom",
")",
"mfd",
"=",
"self",
".",
"convert_mfdist",
"(",
"node",
")",
"with",
"context",
"(",
"self",
".",
"fname",
",",
"node",
")",
":",
"try",
":",
"hypo_list",
"=",
"valid",
".",
"hypo_list",
"(",
"node",
".",
"hypoList",
")",
"except",
"AttributeError",
":",
"hypo_list",
"=",
"(",
")",
"try",
":",
"slip_list",
"=",
"valid",
".",
"slip_list",
"(",
"node",
".",
"slipList",
")",
"except",
"AttributeError",
":",
"slip_list",
"=",
"(",
")",
"simple",
"=",
"source",
".",
"SimpleFaultSource",
"(",
"source_id",
"=",
"node",
"[",
"'id'",
"]",
",",
"name",
"=",
"node",
"[",
"'name'",
"]",
",",
"tectonic_region_type",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'tectonicRegion'",
")",
",",
"mfd",
"=",
"mfd",
",",
"rupture_mesh_spacing",
"=",
"self",
".",
"rupture_mesh_spacing",
",",
"magnitude_scaling_relationship",
"=",
"msr",
",",
"rupture_aspect_ratio",
"=",
"~",
"node",
".",
"ruptAspectRatio",
",",
"upper_seismogenic_depth",
"=",
"~",
"geom",
".",
"upperSeismoDepth",
",",
"lower_seismogenic_depth",
"=",
"~",
"geom",
".",
"lowerSeismoDepth",
",",
"fault_trace",
"=",
"fault_trace",
",",
"dip",
"=",
"~",
"geom",
".",
"dip",
",",
"rake",
"=",
"~",
"node",
".",
"rake",
",",
"temporal_occurrence_model",
"=",
"self",
".",
"get_tom",
"(",
"node",
")",
",",
"hypo_list",
"=",
"hypo_list",
",",
"slip_list",
"=",
"slip_list",
")",
"return",
"simple"
]
| Convert the given node into a simple fault object.
:param node: a node with tag areaGeometry
:returns: a :class:`openquake.hazardlib.source.SimpleFaultSource`
instance | [
"Convert",
"the",
"given",
"node",
"into",
"a",
"simple",
"fault",
"object",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L712-L749 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | SourceConverter.convert_complexFaultSource | def convert_complexFaultSource(self, node):
"""
Convert the given node into a complex fault object.
:param node: a node with tag areaGeometry
:returns: a :class:`openquake.hazardlib.source.ComplexFaultSource`
instance
"""
geom = node.complexFaultGeometry
edges = self.geo_lines(geom)
mfd = self.convert_mfdist(node)
msr = valid.SCALEREL[~node.magScaleRel]()
with context(self.fname, node):
cmplx = source.ComplexFaultSource(
source_id=node['id'],
name=node['name'],
tectonic_region_type=node.attrib.get('tectonicRegion'),
mfd=mfd,
rupture_mesh_spacing=self.complex_fault_mesh_spacing,
magnitude_scaling_relationship=msr,
rupture_aspect_ratio=~node.ruptAspectRatio,
edges=edges,
rake=~node.rake,
temporal_occurrence_model=self.get_tom(node))
return cmplx | python | def convert_complexFaultSource(self, node):
geom = node.complexFaultGeometry
edges = self.geo_lines(geom)
mfd = self.convert_mfdist(node)
msr = valid.SCALEREL[~node.magScaleRel]()
with context(self.fname, node):
cmplx = source.ComplexFaultSource(
source_id=node['id'],
name=node['name'],
tectonic_region_type=node.attrib.get('tectonicRegion'),
mfd=mfd,
rupture_mesh_spacing=self.complex_fault_mesh_spacing,
magnitude_scaling_relationship=msr,
rupture_aspect_ratio=~node.ruptAspectRatio,
edges=edges,
rake=~node.rake,
temporal_occurrence_model=self.get_tom(node))
return cmplx | [
"def",
"convert_complexFaultSource",
"(",
"self",
",",
"node",
")",
":",
"geom",
"=",
"node",
".",
"complexFaultGeometry",
"edges",
"=",
"self",
".",
"geo_lines",
"(",
"geom",
")",
"mfd",
"=",
"self",
".",
"convert_mfdist",
"(",
"node",
")",
"msr",
"=",
"valid",
".",
"SCALEREL",
"[",
"~",
"node",
".",
"magScaleRel",
"]",
"(",
")",
"with",
"context",
"(",
"self",
".",
"fname",
",",
"node",
")",
":",
"cmplx",
"=",
"source",
".",
"ComplexFaultSource",
"(",
"source_id",
"=",
"node",
"[",
"'id'",
"]",
",",
"name",
"=",
"node",
"[",
"'name'",
"]",
",",
"tectonic_region_type",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'tectonicRegion'",
")",
",",
"mfd",
"=",
"mfd",
",",
"rupture_mesh_spacing",
"=",
"self",
".",
"complex_fault_mesh_spacing",
",",
"magnitude_scaling_relationship",
"=",
"msr",
",",
"rupture_aspect_ratio",
"=",
"~",
"node",
".",
"ruptAspectRatio",
",",
"edges",
"=",
"edges",
",",
"rake",
"=",
"~",
"node",
".",
"rake",
",",
"temporal_occurrence_model",
"=",
"self",
".",
"get_tom",
"(",
"node",
")",
")",
"return",
"cmplx"
]
| Convert the given node into a complex fault object.
:param node: a node with tag areaGeometry
:returns: a :class:`openquake.hazardlib.source.ComplexFaultSource`
instance | [
"Convert",
"the",
"given",
"node",
"into",
"a",
"complex",
"fault",
"object",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L751-L775 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | SourceConverter.convert_characteristicFaultSource | def convert_characteristicFaultSource(self, node):
"""
Convert the given node into a characteristic fault object.
:param node:
a node with tag areaGeometry
:returns:
a :class:`openquake.hazardlib.source.CharacteristicFaultSource`
instance
"""
char = source.CharacteristicFaultSource(
source_id=node['id'],
name=node['name'],
tectonic_region_type=node.attrib.get('tectonicRegion'),
mfd=self.convert_mfdist(node),
surface=self.convert_surfaces(node.surface),
rake=~node.rake,
temporal_occurrence_model=self.get_tom(node))
return char | python | def convert_characteristicFaultSource(self, node):
char = source.CharacteristicFaultSource(
source_id=node['id'],
name=node['name'],
tectonic_region_type=node.attrib.get('tectonicRegion'),
mfd=self.convert_mfdist(node),
surface=self.convert_surfaces(node.surface),
rake=~node.rake,
temporal_occurrence_model=self.get_tom(node))
return char | [
"def",
"convert_characteristicFaultSource",
"(",
"self",
",",
"node",
")",
":",
"char",
"=",
"source",
".",
"CharacteristicFaultSource",
"(",
"source_id",
"=",
"node",
"[",
"'id'",
"]",
",",
"name",
"=",
"node",
"[",
"'name'",
"]",
",",
"tectonic_region_type",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'tectonicRegion'",
")",
",",
"mfd",
"=",
"self",
".",
"convert_mfdist",
"(",
"node",
")",
",",
"surface",
"=",
"self",
".",
"convert_surfaces",
"(",
"node",
".",
"surface",
")",
",",
"rake",
"=",
"~",
"node",
".",
"rake",
",",
"temporal_occurrence_model",
"=",
"self",
".",
"get_tom",
"(",
"node",
")",
")",
"return",
"char"
]
| Convert the given node into a characteristic fault object.
:param node:
a node with tag areaGeometry
:returns:
a :class:`openquake.hazardlib.source.CharacteristicFaultSource`
instance | [
"Convert",
"the",
"given",
"node",
"into",
"a",
"characteristic",
"fault",
"object",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L777-L795 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | SourceConverter.convert_nonParametricSeismicSource | def convert_nonParametricSeismicSource(self, node):
"""
Convert the given node into a non parametric source object.
:param node:
a node with tag areaGeometry
:returns:
a :class:`openquake.hazardlib.source.NonParametricSeismicSource`
instance
"""
trt = node.attrib.get('tectonicRegion')
rup_pmf_data = []
rups_weights = None
if 'rup_weights' in node.attrib:
tmp = node.attrib.get('rup_weights')
rups_weights = numpy.array([float(s) for s in tmp.split()])
for i, rupnode in enumerate(node):
probs = pmf.PMF(valid.pmf(rupnode['probs_occur']))
rup = RuptureConverter.convert_node(self, rupnode)
rup.tectonic_region_type = trt
rup.weight = None if rups_weights is None else rups_weights[i]
rup_pmf_data.append((rup, probs))
nps = source.NonParametricSeismicSource(
node['id'], node['name'], trt, rup_pmf_data)
nps.splittable = 'rup_weights' not in node.attrib
return nps | python | def convert_nonParametricSeismicSource(self, node):
trt = node.attrib.get('tectonicRegion')
rup_pmf_data = []
rups_weights = None
if 'rup_weights' in node.attrib:
tmp = node.attrib.get('rup_weights')
rups_weights = numpy.array([float(s) for s in tmp.split()])
for i, rupnode in enumerate(node):
probs = pmf.PMF(valid.pmf(rupnode['probs_occur']))
rup = RuptureConverter.convert_node(self, rupnode)
rup.tectonic_region_type = trt
rup.weight = None if rups_weights is None else rups_weights[i]
rup_pmf_data.append((rup, probs))
nps = source.NonParametricSeismicSource(
node['id'], node['name'], trt, rup_pmf_data)
nps.splittable = 'rup_weights' not in node.attrib
return nps | [
"def",
"convert_nonParametricSeismicSource",
"(",
"self",
",",
"node",
")",
":",
"trt",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'tectonicRegion'",
")",
"rup_pmf_data",
"=",
"[",
"]",
"rups_weights",
"=",
"None",
"if",
"'rup_weights'",
"in",
"node",
".",
"attrib",
":",
"tmp",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'rup_weights'",
")",
"rups_weights",
"=",
"numpy",
".",
"array",
"(",
"[",
"float",
"(",
"s",
")",
"for",
"s",
"in",
"tmp",
".",
"split",
"(",
")",
"]",
")",
"for",
"i",
",",
"rupnode",
"in",
"enumerate",
"(",
"node",
")",
":",
"probs",
"=",
"pmf",
".",
"PMF",
"(",
"valid",
".",
"pmf",
"(",
"rupnode",
"[",
"'probs_occur'",
"]",
")",
")",
"rup",
"=",
"RuptureConverter",
".",
"convert_node",
"(",
"self",
",",
"rupnode",
")",
"rup",
".",
"tectonic_region_type",
"=",
"trt",
"rup",
".",
"weight",
"=",
"None",
"if",
"rups_weights",
"is",
"None",
"else",
"rups_weights",
"[",
"i",
"]",
"rup_pmf_data",
".",
"append",
"(",
"(",
"rup",
",",
"probs",
")",
")",
"nps",
"=",
"source",
".",
"NonParametricSeismicSource",
"(",
"node",
"[",
"'id'",
"]",
",",
"node",
"[",
"'name'",
"]",
",",
"trt",
",",
"rup_pmf_data",
")",
"nps",
".",
"splittable",
"=",
"'rup_weights'",
"not",
"in",
"node",
".",
"attrib",
"return",
"nps"
]
| Convert the given node into a non parametric source object.
:param node:
a node with tag areaGeometry
:returns:
a :class:`openquake.hazardlib.source.NonParametricSeismicSource`
instance | [
"Convert",
"the",
"given",
"node",
"into",
"a",
"non",
"parametric",
"source",
"object",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L797-L822 |
gem/oq-engine | openquake/hazardlib/sourceconverter.py | SourceConverter.convert_sourceGroup | def convert_sourceGroup(self, node):
"""
Convert the given node into a SourceGroup object.
:param node:
a node with tag sourceGroup
:returns:
a :class:`SourceGroup` instance
"""
trt = node['tectonicRegion']
srcs_weights = node.attrib.get('srcs_weights')
grp_attrs = {k: v for k, v in node.attrib.items()
if k not in ('name', 'src_interdep', 'rup_interdep',
'srcs_weights')}
sg = SourceGroup(trt, min_mag=self.minimum_magnitude)
sg.temporal_occurrence_model = self.get_tom(node)
sg.name = node.attrib.get('name')
# Set attributes related to occurrence
sg.src_interdep = node.attrib.get('src_interdep', 'indep')
sg.rup_interdep = node.attrib.get('rup_interdep', 'indep')
sg.grp_probability = node.attrib.get('grp_probability')
# Set the cluster attribute
sg.cluster = node.attrib.get('cluster') == 'true'
# Filter admitted cases
# 1. The source group is a cluster. In this case the cluster must have
# the attributes required to define its occurrence in time.
if sg.cluster:
msg = 'A cluster group requires the definition of a temporal'
msg += ' occurrence model'
assert 'tom' in node.attrib, msg
if isinstance(tom, PoissonTOM):
assert hasattr(sg, 'occurrence_rate')
#
for src_node in node:
if self.source_id and self.source_id != src_node['id']:
continue # filter by source_id
src = self.convert_node(src_node)
# transmit the group attributes to the underlying source
for attr, value in grp_attrs.items():
if attr == 'tectonicRegion':
src_trt = src_node.get('tectonicRegion')
if src_trt and src_trt != trt:
with context(self.fname, src_node):
raise ValueError('Found %s, expected %s' %
(src_node['tectonicRegion'], trt))
src.tectonic_region_type = trt
elif attr == 'grp_probability':
pass # do not transmit
else: # transmit as it is
setattr(src, attr, node[attr])
sg.update(src)
if srcs_weights is not None:
if len(node) and len(srcs_weights) != len(node):
raise ValueError(
'There are %d srcs_weights but %d source(s) in %s'
% (len(srcs_weights), len(node), self.fname))
for src, sw in zip(sg, srcs_weights):
src.mutex_weight = sw
# check that, when the cluster option is set, the group has a temporal
# occurrence model properly defined
if sg.cluster and not hasattr(sg, 'temporal_occurrence_model'):
msg = 'The Source Group is a cluster but does not have a '
msg += 'temporal occurrence model'
raise ValueError(msg)
return sg | python | def convert_sourceGroup(self, node):
trt = node['tectonicRegion']
srcs_weights = node.attrib.get('srcs_weights')
grp_attrs = {k: v for k, v in node.attrib.items()
if k not in ('name', 'src_interdep', 'rup_interdep',
'srcs_weights')}
sg = SourceGroup(trt, min_mag=self.minimum_magnitude)
sg.temporal_occurrence_model = self.get_tom(node)
sg.name = node.attrib.get('name')
sg.src_interdep = node.attrib.get('src_interdep', 'indep')
sg.rup_interdep = node.attrib.get('rup_interdep', 'indep')
sg.grp_probability = node.attrib.get('grp_probability')
sg.cluster = node.attrib.get('cluster') == 'true'
if sg.cluster:
msg = 'A cluster group requires the definition of a temporal'
msg += ' occurrence model'
assert 'tom' in node.attrib, msg
if isinstance(tom, PoissonTOM):
assert hasattr(sg, 'occurrence_rate')
for src_node in node:
if self.source_id and self.source_id != src_node['id']:
continue
src = self.convert_node(src_node)
for attr, value in grp_attrs.items():
if attr == 'tectonicRegion':
src_trt = src_node.get('tectonicRegion')
if src_trt and src_trt != trt:
with context(self.fname, src_node):
raise ValueError('Found %s, expected %s' %
(src_node['tectonicRegion'], trt))
src.tectonic_region_type = trt
elif attr == 'grp_probability':
pass
else:
setattr(src, attr, node[attr])
sg.update(src)
if srcs_weights is not None:
if len(node) and len(srcs_weights) != len(node):
raise ValueError(
'There are %d srcs_weights but %d source(s) in %s'
% (len(srcs_weights), len(node), self.fname))
for src, sw in zip(sg, srcs_weights):
src.mutex_weight = sw
if sg.cluster and not hasattr(sg, 'temporal_occurrence_model'):
msg = 'The Source Group is a cluster but does not have a '
msg += 'temporal occurrence model'
raise ValueError(msg)
return sg | [
"def",
"convert_sourceGroup",
"(",
"self",
",",
"node",
")",
":",
"trt",
"=",
"node",
"[",
"'tectonicRegion'",
"]",
"srcs_weights",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'srcs_weights'",
")",
"grp_attrs",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"node",
".",
"attrib",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"(",
"'name'",
",",
"'src_interdep'",
",",
"'rup_interdep'",
",",
"'srcs_weights'",
")",
"}",
"sg",
"=",
"SourceGroup",
"(",
"trt",
",",
"min_mag",
"=",
"self",
".",
"minimum_magnitude",
")",
"sg",
".",
"temporal_occurrence_model",
"=",
"self",
".",
"get_tom",
"(",
"node",
")",
"sg",
".",
"name",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'name'",
")",
"# Set attributes related to occurrence",
"sg",
".",
"src_interdep",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'src_interdep'",
",",
"'indep'",
")",
"sg",
".",
"rup_interdep",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'rup_interdep'",
",",
"'indep'",
")",
"sg",
".",
"grp_probability",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'grp_probability'",
")",
"# Set the cluster attribute",
"sg",
".",
"cluster",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'cluster'",
")",
"==",
"'true'",
"# Filter admitted cases",
"# 1. The source group is a cluster. In this case the cluster must have",
"# the attributes required to define its occurrence in time.",
"if",
"sg",
".",
"cluster",
":",
"msg",
"=",
"'A cluster group requires the definition of a temporal'",
"msg",
"+=",
"' occurrence model'",
"assert",
"'tom'",
"in",
"node",
".",
"attrib",
",",
"msg",
"if",
"isinstance",
"(",
"tom",
",",
"PoissonTOM",
")",
":",
"assert",
"hasattr",
"(",
"sg",
",",
"'occurrence_rate'",
")",
"#",
"for",
"src_node",
"in",
"node",
":",
"if",
"self",
".",
"source_id",
"and",
"self",
".",
"source_id",
"!=",
"src_node",
"[",
"'id'",
"]",
":",
"continue",
"# filter by source_id",
"src",
"=",
"self",
".",
"convert_node",
"(",
"src_node",
")",
"# transmit the group attributes to the underlying source",
"for",
"attr",
",",
"value",
"in",
"grp_attrs",
".",
"items",
"(",
")",
":",
"if",
"attr",
"==",
"'tectonicRegion'",
":",
"src_trt",
"=",
"src_node",
".",
"get",
"(",
"'tectonicRegion'",
")",
"if",
"src_trt",
"and",
"src_trt",
"!=",
"trt",
":",
"with",
"context",
"(",
"self",
".",
"fname",
",",
"src_node",
")",
":",
"raise",
"ValueError",
"(",
"'Found %s, expected %s'",
"%",
"(",
"src_node",
"[",
"'tectonicRegion'",
"]",
",",
"trt",
")",
")",
"src",
".",
"tectonic_region_type",
"=",
"trt",
"elif",
"attr",
"==",
"'grp_probability'",
":",
"pass",
"# do not transmit",
"else",
":",
"# transmit as it is",
"setattr",
"(",
"src",
",",
"attr",
",",
"node",
"[",
"attr",
"]",
")",
"sg",
".",
"update",
"(",
"src",
")",
"if",
"srcs_weights",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"node",
")",
"and",
"len",
"(",
"srcs_weights",
")",
"!=",
"len",
"(",
"node",
")",
":",
"raise",
"ValueError",
"(",
"'There are %d srcs_weights but %d source(s) in %s'",
"%",
"(",
"len",
"(",
"srcs_weights",
")",
",",
"len",
"(",
"node",
")",
",",
"self",
".",
"fname",
")",
")",
"for",
"src",
",",
"sw",
"in",
"zip",
"(",
"sg",
",",
"srcs_weights",
")",
":",
"src",
".",
"mutex_weight",
"=",
"sw",
"# check that, when the cluster option is set, the group has a temporal",
"# occurrence model properly defined",
"if",
"sg",
".",
"cluster",
"and",
"not",
"hasattr",
"(",
"sg",
",",
"'temporal_occurrence_model'",
")",
":",
"msg",
"=",
"'The Source Group is a cluster but does not have a '",
"msg",
"+=",
"'temporal occurrence model'",
"raise",
"ValueError",
"(",
"msg",
")",
"return",
"sg"
]
| Convert the given node into a SourceGroup object.
:param node:
a node with tag sourceGroup
:returns:
a :class:`SourceGroup` instance | [
"Convert",
"the",
"given",
"node",
"into",
"a",
"SourceGroup",
"object",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L827-L891 |
gem/oq-engine | openquake/hmtk/faults/tectonic_regionalisation.py | _check_list_weights | def _check_list_weights(parameter, name):
'''
Checks that the weights in a list of tuples sums to 1.0
'''
if not isinstance(parameter, list):
raise ValueError('%s must be formatted with a list of tuples' % name)
weight = np.sum([val[1] for val in parameter])
if fabs(weight - 1.) > 1E-8:
raise ValueError('%s weights do not sum to 1.0!' % name)
return parameter | python | def _check_list_weights(parameter, name):
if not isinstance(parameter, list):
raise ValueError('%s must be formatted with a list of tuples' % name)
weight = np.sum([val[1] for val in parameter])
if fabs(weight - 1.) > 1E-8:
raise ValueError('%s weights do not sum to 1.0!' % name)
return parameter | [
"def",
"_check_list_weights",
"(",
"parameter",
",",
"name",
")",
":",
"if",
"not",
"isinstance",
"(",
"parameter",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"'%s must be formatted with a list of tuples'",
"%",
"name",
")",
"weight",
"=",
"np",
".",
"sum",
"(",
"[",
"val",
"[",
"1",
"]",
"for",
"val",
"in",
"parameter",
"]",
")",
"if",
"fabs",
"(",
"weight",
"-",
"1.",
")",
">",
"1E-8",
":",
"raise",
"ValueError",
"(",
"'%s weights do not sum to 1.0!'",
"%",
"name",
")",
"return",
"parameter"
]
| Checks that the weights in a list of tuples sums to 1.0 | [
"Checks",
"that",
"the",
"weights",
"in",
"a",
"list",
"of",
"tuples",
"sums",
"to",
"1",
".",
"0"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/tectonic_regionalisation.py#L63-L72 |
gem/oq-engine | openquake/hmtk/faults/tectonic_regionalisation.py | TectonicRegionalisation.populate_regions | def populate_regions(self, tectonic_region_dict):
'''
Populates the tectonic region from the list of dictionaries, where each
region is a dictionary of with the following format::
region = {'Shear_Modulus': [(val1, weight1), (val2, weight2), ...],
'Displacement_Length_Ratio': [(val1, weight1), ...],
'Magnitude_Scaling_Relation': [(val1, weight1), ...]}
'''
for tect_reg in tectonic_region_dict:
if 'Shear_Modulus' in tect_reg.keys():
shear_modulus = tect_reg['Shear_Modulus']
else:
shear_modulus = DEFAULT_SHEAR_MODULUS
if 'Displacement_Length_Ratio' in tect_reg.keys():
disp_length_ratio = tect_reg['Displacement_Length_Ratio']
else:
disp_length_ratio = DEFAULT_DLR
if 'Magnitude_Scaling_Relation' in tect_reg.keys():
scaling_relation = tect_reg['Magnitude_Scaling_Relation']
else:
scaling_relation = DEFAULT_MSR
self.regionalisation.append(
TectonicRegion(
tect_reg['Code'], tect_reg['Name'],
shear_modulus, disp_length_ratio, scaling_relation))
self.key_list.append(tect_reg['Name']) | python | def populate_regions(self, tectonic_region_dict):
for tect_reg in tectonic_region_dict:
if 'Shear_Modulus' in tect_reg.keys():
shear_modulus = tect_reg['Shear_Modulus']
else:
shear_modulus = DEFAULT_SHEAR_MODULUS
if 'Displacement_Length_Ratio' in tect_reg.keys():
disp_length_ratio = tect_reg['Displacement_Length_Ratio']
else:
disp_length_ratio = DEFAULT_DLR
if 'Magnitude_Scaling_Relation' in tect_reg.keys():
scaling_relation = tect_reg['Magnitude_Scaling_Relation']
else:
scaling_relation = DEFAULT_MSR
self.regionalisation.append(
TectonicRegion(
tect_reg['Code'], tect_reg['Name'],
shear_modulus, disp_length_ratio, scaling_relation))
self.key_list.append(tect_reg['Name']) | [
"def",
"populate_regions",
"(",
"self",
",",
"tectonic_region_dict",
")",
":",
"for",
"tect_reg",
"in",
"tectonic_region_dict",
":",
"if",
"'Shear_Modulus'",
"in",
"tect_reg",
".",
"keys",
"(",
")",
":",
"shear_modulus",
"=",
"tect_reg",
"[",
"'Shear_Modulus'",
"]",
"else",
":",
"shear_modulus",
"=",
"DEFAULT_SHEAR_MODULUS",
"if",
"'Displacement_Length_Ratio'",
"in",
"tect_reg",
".",
"keys",
"(",
")",
":",
"disp_length_ratio",
"=",
"tect_reg",
"[",
"'Displacement_Length_Ratio'",
"]",
"else",
":",
"disp_length_ratio",
"=",
"DEFAULT_DLR",
"if",
"'Magnitude_Scaling_Relation'",
"in",
"tect_reg",
".",
"keys",
"(",
")",
":",
"scaling_relation",
"=",
"tect_reg",
"[",
"'Magnitude_Scaling_Relation'",
"]",
"else",
":",
"scaling_relation",
"=",
"DEFAULT_MSR",
"self",
".",
"regionalisation",
".",
"append",
"(",
"TectonicRegion",
"(",
"tect_reg",
"[",
"'Code'",
"]",
",",
"tect_reg",
"[",
"'Name'",
"]",
",",
"shear_modulus",
",",
"disp_length_ratio",
",",
"scaling_relation",
")",
")",
"self",
".",
"key_list",
".",
"append",
"(",
"tect_reg",
"[",
"'Name'",
"]",
")"
]
| Populates the tectonic region from the list of dictionaries, where each
region is a dictionary of with the following format::
region = {'Shear_Modulus': [(val1, weight1), (val2, weight2), ...],
'Displacement_Length_Ratio': [(val1, weight1), ...],
'Magnitude_Scaling_Relation': [(val1, weight1), ...]} | [
"Populates",
"the",
"tectonic",
"region",
"from",
"the",
"list",
"of",
"dictionaries",
"where",
"each",
"region",
"is",
"a",
"dictionary",
"of",
"with",
"the",
"following",
"format",
"::"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/tectonic_regionalisation.py#L111-L140 |
gem/oq-engine | openquake/hmtk/faults/active_fault_model.py | mtkActiveFaultModel.build_fault_model | def build_fault_model(self, collapse=False, rendered_msr=WC1994(),
mfd_config=None):
'''
Constructs a full fault model with epistemic uncertainty by
enumerating all the possible recurrence models of each fault as
separate faults, with the recurrence rates multiplied by the
corresponding weights.
:param bool collapse:
Determines whether or not to collapse the branches
:param rendered_msr:
If the option is taken to collapse the branches then a recurrence
model for rendering must be defined
:param list/dict mfd_config:
Universal list or dictionay of configuration parameters for the
magnitude frequency distribution - will overwrite whatever is
previously defined for the fault!
'''
self.source_model = mtkSourceModel(self.id, self.name)
for fault in self.faults:
fault.generate_recurrence_models(collapse,
config=mfd_config,
rendered_msr=rendered_msr)
src_model, src_weight = fault.generate_fault_source_model()
for iloc, model in enumerate(src_model):
new_model = deepcopy(model)
new_model.id = str(model.id) + '_%g' % (iloc + 1)
new_model.mfd.occurrence_rates = \
(np.array(new_model.mfd.occurrence_rates) *
src_weight[iloc]).tolist()
self.source_model.sources.append(new_model) | python | def build_fault_model(self, collapse=False, rendered_msr=WC1994(),
mfd_config=None):
self.source_model = mtkSourceModel(self.id, self.name)
for fault in self.faults:
fault.generate_recurrence_models(collapse,
config=mfd_config,
rendered_msr=rendered_msr)
src_model, src_weight = fault.generate_fault_source_model()
for iloc, model in enumerate(src_model):
new_model = deepcopy(model)
new_model.id = str(model.id) + '_%g' % (iloc + 1)
new_model.mfd.occurrence_rates = \
(np.array(new_model.mfd.occurrence_rates) *
src_weight[iloc]).tolist()
self.source_model.sources.append(new_model) | [
"def",
"build_fault_model",
"(",
"self",
",",
"collapse",
"=",
"False",
",",
"rendered_msr",
"=",
"WC1994",
"(",
")",
",",
"mfd_config",
"=",
"None",
")",
":",
"self",
".",
"source_model",
"=",
"mtkSourceModel",
"(",
"self",
".",
"id",
",",
"self",
".",
"name",
")",
"for",
"fault",
"in",
"self",
".",
"faults",
":",
"fault",
".",
"generate_recurrence_models",
"(",
"collapse",
",",
"config",
"=",
"mfd_config",
",",
"rendered_msr",
"=",
"rendered_msr",
")",
"src_model",
",",
"src_weight",
"=",
"fault",
".",
"generate_fault_source_model",
"(",
")",
"for",
"iloc",
",",
"model",
"in",
"enumerate",
"(",
"src_model",
")",
":",
"new_model",
"=",
"deepcopy",
"(",
"model",
")",
"new_model",
".",
"id",
"=",
"str",
"(",
"model",
".",
"id",
")",
"+",
"'_%g'",
"%",
"(",
"iloc",
"+",
"1",
")",
"new_model",
".",
"mfd",
".",
"occurrence_rates",
"=",
"(",
"np",
".",
"array",
"(",
"new_model",
".",
"mfd",
".",
"occurrence_rates",
")",
"*",
"src_weight",
"[",
"iloc",
"]",
")",
".",
"tolist",
"(",
")",
"self",
".",
"source_model",
".",
"sources",
".",
"append",
"(",
"new_model",
")"
]
| Constructs a full fault model with epistemic uncertainty by
enumerating all the possible recurrence models of each fault as
separate faults, with the recurrence rates multiplied by the
corresponding weights.
:param bool collapse:
Determines whether or not to collapse the branches
:param rendered_msr:
If the option is taken to collapse the branches then a recurrence
model for rendering must be defined
:param list/dict mfd_config:
Universal list or dictionay of configuration parameters for the
magnitude frequency distribution - will overwrite whatever is
previously defined for the fault! | [
"Constructs",
"a",
"full",
"fault",
"model",
"with",
"epistemic",
"uncertainty",
"by",
"enumerating",
"all",
"the",
"possible",
"recurrence",
"models",
"of",
"each",
"fault",
"as",
"separate",
"faults",
"with",
"the",
"recurrence",
"rates",
"multiplied",
"by",
"the",
"corresponding",
"weights",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/active_fault_model.py#L94-L125 |
gem/oq-engine | openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py | _read_date_from_string | def _read_date_from_string(str1):
"""
Reads the date from a string in the format YYYY/MM/DD and returns
:class: datetime.date
"""
full_date = [int(x) for x in str1.split('/')]
return datetime.date(full_date[0], full_date[1], full_date[2]) | python | def _read_date_from_string(str1):
full_date = [int(x) for x in str1.split('/')]
return datetime.date(full_date[0], full_date[1], full_date[2]) | [
"def",
"_read_date_from_string",
"(",
"str1",
")",
":",
"full_date",
"=",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"str1",
".",
"split",
"(",
"'/'",
")",
"]",
"return",
"datetime",
".",
"date",
"(",
"full_date",
"[",
"0",
"]",
",",
"full_date",
"[",
"1",
"]",
",",
"full_date",
"[",
"2",
"]",
")"
]
| Reads the date from a string in the format YYYY/MM/DD and returns
:class: datetime.date | [
"Reads",
"the",
"date",
"from",
"a",
"string",
"in",
"the",
"format",
"YYYY",
"/",
"MM",
"/",
"DD",
"and",
"returns",
":",
"class",
":",
"datetime",
".",
"date"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L63-L69 |
gem/oq-engine | openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py | _read_time_from_string | def _read_time_from_string(str1):
"""
Reads the time from a string in the format HH:MM:SS.S and returns
:class: datetime.time
"""
full_time = [float(x) for x in str1.split(':')]
hour = int(full_time[0])
minute = int(full_time[1])
if full_time[2] > 59.99:
minute += 1
second = 0
else:
second = int(full_time[2])
microseconds = int((full_time[2] - floor(full_time[2])) * 1000000)
return datetime.time(hour, minute, second, microseconds) | python | def _read_time_from_string(str1):
full_time = [float(x) for x in str1.split(':')]
hour = int(full_time[0])
minute = int(full_time[1])
if full_time[2] > 59.99:
minute += 1
second = 0
else:
second = int(full_time[2])
microseconds = int((full_time[2] - floor(full_time[2])) * 1000000)
return datetime.time(hour, minute, second, microseconds) | [
"def",
"_read_time_from_string",
"(",
"str1",
")",
":",
"full_time",
"=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"str1",
".",
"split",
"(",
"':'",
")",
"]",
"hour",
"=",
"int",
"(",
"full_time",
"[",
"0",
"]",
")",
"minute",
"=",
"int",
"(",
"full_time",
"[",
"1",
"]",
")",
"if",
"full_time",
"[",
"2",
"]",
">",
"59.99",
":",
"minute",
"+=",
"1",
"second",
"=",
"0",
"else",
":",
"second",
"=",
"int",
"(",
"full_time",
"[",
"2",
"]",
")",
"microseconds",
"=",
"int",
"(",
"(",
"full_time",
"[",
"2",
"]",
"-",
"floor",
"(",
"full_time",
"[",
"2",
"]",
")",
")",
"*",
"1000000",
")",
"return",
"datetime",
".",
"time",
"(",
"hour",
",",
"minute",
",",
"second",
",",
"microseconds",
")"
]
| Reads the time from a string in the format HH:MM:SS.S and returns
:class: datetime.time | [
"Reads",
"the",
"time",
"from",
"a",
"string",
"in",
"the",
"format",
"HH",
":",
"MM",
":",
"SS",
".",
"S",
"and",
"returns",
":",
"class",
":",
"datetime",
".",
"time"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L72-L86 |
gem/oq-engine | openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py | _read_moment_tensor_from_ndk_string | def _read_moment_tensor_from_ndk_string(ndk_string, system='USE'):
"""
Reads the moment tensor from the ndk_string representation
ndk_string = [Mrr, sigMrr, Mtt, sigMtt, Mpp, sigMpp, Mrt, sigMrt, Mrp,
sigMrp, Mtp, sigMtp]
Output tensors should be of format:
expected = [[Mtt, Mtp, Mtr],
[Mtp, Mpp, Mpr],
[Mtr, Mpr, Mrr]]
sigma = [[sigMtt, sigMtp, sigMtr],
[sigMtp, sigMpp, sigMpr],
[sigMtr, sigMpr, sigMrr]]
Exponent returned in Nm
:param str ndk_string:
String of data in ndk format (line 4 of event)
:param str system:
Reference frame of tensor Up, South, East {USE} or North, East, Down
(NED)
"""
exponent = float(ndk_string[0:2]) - 7.
mkr = np.array([2, 9, 15], dtype=int)
vector = []
for i in range(0, 6):
vector.extend([
float(ndk_string[mkr[0]:mkr[1]]),
float(ndk_string[mkr[1]:mkr[2]])])
mkr = mkr + 13
vector = np.array(vector)
mrr, mtt, mpp, mrt, mrp, mtp = tuple(vector[np.arange(0, 12, 2)])
sig_mrr, sig_mtt, sig_mpp, sig_mrt, sig_mrp, sig_mtp = \
tuple(vector[np.arange(1, 13, 2)])
tensor = utils.COORD_SYSTEM[system](mrr, mtt, mpp, mrt, mrp, mtp)
tensor = (10. ** exponent) * tensor
sigma = utils.COORD_SYSTEM[system](sig_mrr, sig_mtt, sig_mpp,
sig_mrt, sig_mrp, sig_mtp)
sigma = (10. ** exponent) * sigma
return tensor, sigma, exponent | python | def _read_moment_tensor_from_ndk_string(ndk_string, system='USE'):
exponent = float(ndk_string[0:2]) - 7.
mkr = np.array([2, 9, 15], dtype=int)
vector = []
for i in range(0, 6):
vector.extend([
float(ndk_string[mkr[0]:mkr[1]]),
float(ndk_string[mkr[1]:mkr[2]])])
mkr = mkr + 13
vector = np.array(vector)
mrr, mtt, mpp, mrt, mrp, mtp = tuple(vector[np.arange(0, 12, 2)])
sig_mrr, sig_mtt, sig_mpp, sig_mrt, sig_mrp, sig_mtp = \
tuple(vector[np.arange(1, 13, 2)])
tensor = utils.COORD_SYSTEM[system](mrr, mtt, mpp, mrt, mrp, mtp)
tensor = (10. ** exponent) * tensor
sigma = utils.COORD_SYSTEM[system](sig_mrr, sig_mtt, sig_mpp,
sig_mrt, sig_mrp, sig_mtp)
sigma = (10. ** exponent) * sigma
return tensor, sigma, exponent | [
"def",
"_read_moment_tensor_from_ndk_string",
"(",
"ndk_string",
",",
"system",
"=",
"'USE'",
")",
":",
"exponent",
"=",
"float",
"(",
"ndk_string",
"[",
"0",
":",
"2",
"]",
")",
"-",
"7.",
"mkr",
"=",
"np",
".",
"array",
"(",
"[",
"2",
",",
"9",
",",
"15",
"]",
",",
"dtype",
"=",
"int",
")",
"vector",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"6",
")",
":",
"vector",
".",
"extend",
"(",
"[",
"float",
"(",
"ndk_string",
"[",
"mkr",
"[",
"0",
"]",
":",
"mkr",
"[",
"1",
"]",
"]",
")",
",",
"float",
"(",
"ndk_string",
"[",
"mkr",
"[",
"1",
"]",
":",
"mkr",
"[",
"2",
"]",
"]",
")",
"]",
")",
"mkr",
"=",
"mkr",
"+",
"13",
"vector",
"=",
"np",
".",
"array",
"(",
"vector",
")",
"mrr",
",",
"mtt",
",",
"mpp",
",",
"mrt",
",",
"mrp",
",",
"mtp",
"=",
"tuple",
"(",
"vector",
"[",
"np",
".",
"arange",
"(",
"0",
",",
"12",
",",
"2",
")",
"]",
")",
"sig_mrr",
",",
"sig_mtt",
",",
"sig_mpp",
",",
"sig_mrt",
",",
"sig_mrp",
",",
"sig_mtp",
"=",
"tuple",
"(",
"vector",
"[",
"np",
".",
"arange",
"(",
"1",
",",
"13",
",",
"2",
")",
"]",
")",
"tensor",
"=",
"utils",
".",
"COORD_SYSTEM",
"[",
"system",
"]",
"(",
"mrr",
",",
"mtt",
",",
"mpp",
",",
"mrt",
",",
"mrp",
",",
"mtp",
")",
"tensor",
"=",
"(",
"10.",
"**",
"exponent",
")",
"*",
"tensor",
"sigma",
"=",
"utils",
".",
"COORD_SYSTEM",
"[",
"system",
"]",
"(",
"sig_mrr",
",",
"sig_mtt",
",",
"sig_mpp",
",",
"sig_mrt",
",",
"sig_mrp",
",",
"sig_mtp",
")",
"sigma",
"=",
"(",
"10.",
"**",
"exponent",
")",
"*",
"sigma",
"return",
"tensor",
",",
"sigma",
",",
"exponent"
]
| Reads the moment tensor from the ndk_string representation
ndk_string = [Mrr, sigMrr, Mtt, sigMtt, Mpp, sigMpp, Mrt, sigMrt, Mrp,
sigMrp, Mtp, sigMtp]
Output tensors should be of format:
expected = [[Mtt, Mtp, Mtr],
[Mtp, Mpp, Mpr],
[Mtr, Mpr, Mrr]]
sigma = [[sigMtt, sigMtp, sigMtr],
[sigMtp, sigMpp, sigMpr],
[sigMtr, sigMpr, sigMrr]]
Exponent returned in Nm
:param str ndk_string:
String of data in ndk format (line 4 of event)
:param str system:
Reference frame of tensor Up, South, East {USE} or North, East, Down
(NED) | [
"Reads",
"the",
"moment",
"tensor",
"from",
"the",
"ndk_string",
"representation",
"ndk_string",
"=",
"[",
"Mrr",
"sigMrr",
"Mtt",
"sigMtt",
"Mpp",
"sigMpp",
"Mrt",
"sigMrt",
"Mrp",
"sigMrp",
"Mtp",
"sigMtp",
"]",
"Output",
"tensors",
"should",
"be",
"of",
"format",
":",
"expected",
"=",
"[[",
"Mtt",
"Mtp",
"Mtr",
"]",
"[",
"Mtp",
"Mpp",
"Mpr",
"]",
"[",
"Mtr",
"Mpr",
"Mrr",
"]]",
"sigma",
"=",
"[[",
"sigMtt",
"sigMtp",
"sigMtr",
"]",
"[",
"sigMtp",
"sigMpp",
"sigMpr",
"]",
"[",
"sigMtr",
"sigMpr",
"sigMrr",
"]]",
"Exponent",
"returned",
"in",
"Nm"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L89-L129 |
gem/oq-engine | openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py | ParseNDKtoGCMT.read_file | def read_file(self, start_year=None, end_year=None, use_centroid=None):
"""
Reads the file
"""
raw_data = getlines(self.filename)
num_lines = len(raw_data)
if ((float(num_lines) / 5.) - float(num_lines / 5)) > 1E-9:
raise IOError('GCMT represented by 5 lines - number in file not'
' a multiple of 5!')
self.catalogue.number_gcmts = num_lines // 5
self.catalogue.gcmts = [None] * self.catalogue.number_gcmts
# Pre-allocates list
id0 = 0
print('Parsing catalogue ...')
for iloc in range(0, self.catalogue.number_gcmts):
self.catalogue.gcmts[iloc] = self.read_ndk_event(raw_data, id0)
id0 += 5
print('complete. Contains %s moment tensors'
% self.catalogue.get_number_tensors())
if not start_year:
min_years = []
min_years = [cent.centroid.date.year
for cent in self.catalogue.gcmts]
self.catalogue.start_year = np.min(min_years)
if not end_year:
max_years = []
max_years = [cent.centroid.date.year
for cent in self.catalogue.gcmts]
self.catalogue.end_year = np.max(max_years)
self.to_hmtk(use_centroid)
return self.catalogue | python | def read_file(self, start_year=None, end_year=None, use_centroid=None):
raw_data = getlines(self.filename)
num_lines = len(raw_data)
if ((float(num_lines) / 5.) - float(num_lines / 5)) > 1E-9:
raise IOError('GCMT represented by 5 lines - number in file not'
' a multiple of 5!')
self.catalogue.number_gcmts = num_lines // 5
self.catalogue.gcmts = [None] * self.catalogue.number_gcmts
id0 = 0
print('Parsing catalogue ...')
for iloc in range(0, self.catalogue.number_gcmts):
self.catalogue.gcmts[iloc] = self.read_ndk_event(raw_data, id0)
id0 += 5
print('complete. Contains %s moment tensors'
% self.catalogue.get_number_tensors())
if not start_year:
min_years = []
min_years = [cent.centroid.date.year
for cent in self.catalogue.gcmts]
self.catalogue.start_year = np.min(min_years)
if not end_year:
max_years = []
max_years = [cent.centroid.date.year
for cent in self.catalogue.gcmts]
self.catalogue.end_year = np.max(max_years)
self.to_hmtk(use_centroid)
return self.catalogue | [
"def",
"read_file",
"(",
"self",
",",
"start_year",
"=",
"None",
",",
"end_year",
"=",
"None",
",",
"use_centroid",
"=",
"None",
")",
":",
"raw_data",
"=",
"getlines",
"(",
"self",
".",
"filename",
")",
"num_lines",
"=",
"len",
"(",
"raw_data",
")",
"if",
"(",
"(",
"float",
"(",
"num_lines",
")",
"/",
"5.",
")",
"-",
"float",
"(",
"num_lines",
"/",
"5",
")",
")",
">",
"1E-9",
":",
"raise",
"IOError",
"(",
"'GCMT represented by 5 lines - number in file not'",
"' a multiple of 5!'",
")",
"self",
".",
"catalogue",
".",
"number_gcmts",
"=",
"num_lines",
"//",
"5",
"self",
".",
"catalogue",
".",
"gcmts",
"=",
"[",
"None",
"]",
"*",
"self",
".",
"catalogue",
".",
"number_gcmts",
"# Pre-allocates list",
"id0",
"=",
"0",
"print",
"(",
"'Parsing catalogue ...'",
")",
"for",
"iloc",
"in",
"range",
"(",
"0",
",",
"self",
".",
"catalogue",
".",
"number_gcmts",
")",
":",
"self",
".",
"catalogue",
".",
"gcmts",
"[",
"iloc",
"]",
"=",
"self",
".",
"read_ndk_event",
"(",
"raw_data",
",",
"id0",
")",
"id0",
"+=",
"5",
"print",
"(",
"'complete. Contains %s moment tensors'",
"%",
"self",
".",
"catalogue",
".",
"get_number_tensors",
"(",
")",
")",
"if",
"not",
"start_year",
":",
"min_years",
"=",
"[",
"]",
"min_years",
"=",
"[",
"cent",
".",
"centroid",
".",
"date",
".",
"year",
"for",
"cent",
"in",
"self",
".",
"catalogue",
".",
"gcmts",
"]",
"self",
".",
"catalogue",
".",
"start_year",
"=",
"np",
".",
"min",
"(",
"min_years",
")",
"if",
"not",
"end_year",
":",
"max_years",
"=",
"[",
"]",
"max_years",
"=",
"[",
"cent",
".",
"centroid",
".",
"date",
".",
"year",
"for",
"cent",
"in",
"self",
".",
"catalogue",
".",
"gcmts",
"]",
"self",
".",
"catalogue",
".",
"end_year",
"=",
"np",
".",
"max",
"(",
"max_years",
")",
"self",
".",
"to_hmtk",
"(",
"use_centroid",
")",
"return",
"self",
".",
"catalogue"
]
| Reads the file | [
"Reads",
"the",
"file"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L145-L176 |
gem/oq-engine | openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py | ParseNDKtoGCMT.read_ndk_event | def read_ndk_event(self, raw_data, id0):
"""
Reads a 5-line batch of data into a set of GCMTs
"""
gcmt = GCMTEvent()
# Get hypocentre
ndkstring = raw_data[id0].rstrip('\n')
gcmt.hypocentre = self._read_hypocentre_from_ndk_string(ndkstring)
# GCMT metadata
ndkstring = raw_data[id0 + 1].rstrip('\n')
gcmt = self._get_metadata_from_ndk_string(gcmt, ndkstring)
# Get Centroid
ndkstring = raw_data[id0 + 2].rstrip('\n')
gcmt.centroid = self._read_centroid_from_ndk_string(ndkstring,
gcmt.hypocentre)
# Get Moment Tensor
ndkstring = raw_data[id0 + 3].rstrip('\n')
gcmt.moment_tensor = self._get_moment_tensor_from_ndk_string(ndkstring)
# Get principal axes
ndkstring = raw_data[id0 + 4].rstrip('\n')
gcmt.principal_axes = self._get_principal_axes_from_ndk_string(
ndkstring[3:48],
exponent=gcmt.moment_tensor.exponent)
# Get Nodal Planes
gcmt.nodal_planes = self._get_nodal_planes_from_ndk_string(
ndkstring[57:])
# Get Moment and Magnitude
gcmt.moment, gcmt.version, gcmt.magnitude = \
self._get_moment_from_ndk_string(
ndkstring, gcmt.moment_tensor.exponent)
return gcmt | python | def read_ndk_event(self, raw_data, id0):
gcmt = GCMTEvent()
ndkstring = raw_data[id0].rstrip('\n')
gcmt.hypocentre = self._read_hypocentre_from_ndk_string(ndkstring)
ndkstring = raw_data[id0 + 1].rstrip('\n')
gcmt = self._get_metadata_from_ndk_string(gcmt, ndkstring)
ndkstring = raw_data[id0 + 2].rstrip('\n')
gcmt.centroid = self._read_centroid_from_ndk_string(ndkstring,
gcmt.hypocentre)
ndkstring = raw_data[id0 + 3].rstrip('\n')
gcmt.moment_tensor = self._get_moment_tensor_from_ndk_string(ndkstring)
ndkstring = raw_data[id0 + 4].rstrip('\n')
gcmt.principal_axes = self._get_principal_axes_from_ndk_string(
ndkstring[3:48],
exponent=gcmt.moment_tensor.exponent)
gcmt.nodal_planes = self._get_nodal_planes_from_ndk_string(
ndkstring[57:])
gcmt.moment, gcmt.version, gcmt.magnitude = \
self._get_moment_from_ndk_string(
ndkstring, gcmt.moment_tensor.exponent)
return gcmt | [
"def",
"read_ndk_event",
"(",
"self",
",",
"raw_data",
",",
"id0",
")",
":",
"gcmt",
"=",
"GCMTEvent",
"(",
")",
"# Get hypocentre",
"ndkstring",
"=",
"raw_data",
"[",
"id0",
"]",
".",
"rstrip",
"(",
"'\\n'",
")",
"gcmt",
".",
"hypocentre",
"=",
"self",
".",
"_read_hypocentre_from_ndk_string",
"(",
"ndkstring",
")",
"# GCMT metadata",
"ndkstring",
"=",
"raw_data",
"[",
"id0",
"+",
"1",
"]",
".",
"rstrip",
"(",
"'\\n'",
")",
"gcmt",
"=",
"self",
".",
"_get_metadata_from_ndk_string",
"(",
"gcmt",
",",
"ndkstring",
")",
"# Get Centroid",
"ndkstring",
"=",
"raw_data",
"[",
"id0",
"+",
"2",
"]",
".",
"rstrip",
"(",
"'\\n'",
")",
"gcmt",
".",
"centroid",
"=",
"self",
".",
"_read_centroid_from_ndk_string",
"(",
"ndkstring",
",",
"gcmt",
".",
"hypocentre",
")",
"# Get Moment Tensor",
"ndkstring",
"=",
"raw_data",
"[",
"id0",
"+",
"3",
"]",
".",
"rstrip",
"(",
"'\\n'",
")",
"gcmt",
".",
"moment_tensor",
"=",
"self",
".",
"_get_moment_tensor_from_ndk_string",
"(",
"ndkstring",
")",
"# Get principal axes",
"ndkstring",
"=",
"raw_data",
"[",
"id0",
"+",
"4",
"]",
".",
"rstrip",
"(",
"'\\n'",
")",
"gcmt",
".",
"principal_axes",
"=",
"self",
".",
"_get_principal_axes_from_ndk_string",
"(",
"ndkstring",
"[",
"3",
":",
"48",
"]",
",",
"exponent",
"=",
"gcmt",
".",
"moment_tensor",
".",
"exponent",
")",
"# Get Nodal Planes",
"gcmt",
".",
"nodal_planes",
"=",
"self",
".",
"_get_nodal_planes_from_ndk_string",
"(",
"ndkstring",
"[",
"57",
":",
"]",
")",
"# Get Moment and Magnitude",
"gcmt",
".",
"moment",
",",
"gcmt",
".",
"version",
",",
"gcmt",
".",
"magnitude",
"=",
"self",
".",
"_get_moment_from_ndk_string",
"(",
"ndkstring",
",",
"gcmt",
".",
"moment_tensor",
".",
"exponent",
")",
"return",
"gcmt"
]
| Reads a 5-line batch of data into a set of GCMTs | [
"Reads",
"a",
"5",
"-",
"line",
"batch",
"of",
"data",
"into",
"a",
"set",
"of",
"GCMTs"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L178-L214 |
gem/oq-engine | openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py | ParseNDKtoGCMT.to_hmtk | def to_hmtk(self, use_centroid=True):
'''
Convert the content of the GCMT catalogue to a HMTK
catalogue.
'''
self._preallocate_data_dict()
for iloc, gcmt in enumerate(self.catalogue.gcmts):
self.catalogue.data['eventID'][iloc] = iloc
if use_centroid:
self.catalogue.data['year'][iloc] = \
gcmt.centroid.date.year
self.catalogue.data['month'][iloc] = \
gcmt.centroid.date.month
self.catalogue.data['day'][iloc] = \
gcmt.centroid.date.day
self.catalogue.data['hour'][iloc] = \
gcmt.centroid.time.hour
self.catalogue.data['minute'][iloc] = \
gcmt.centroid.time.minute
self.catalogue.data['second'][iloc] = \
gcmt.centroid.time.second
self.catalogue.data['longitude'][iloc] = \
gcmt.centroid.longitude
self.catalogue.data['latitude'][iloc] = \
gcmt.centroid.latitude
self.catalogue.data['depth'][iloc] = \
gcmt.centroid.depth
else:
self.catalogue.data['year'][iloc] = \
gcmt.hypocentre.date.year
self.catalogue.data['month'][iloc] = \
gcmt.hypocentre.date.month
self.catalogue.data['day'][iloc] = \
gcmt.hypocentre.date.day
self.catalogue.data['hour'][iloc] = \
gcmt.hypocentre.time.hour
self.catalogue.data['minute'][iloc] = \
gcmt.hypocentre.time.minute
self.catalogue.data['second'][iloc] = \
gcmt.hypocentre.time.second
self.catalogue.data['longitude'][iloc] = \
gcmt.hypocentre.longitude
self.catalogue.data['latitude'][iloc] = \
gcmt.hypocentre.latitude
self.catalogue.data['depth'][iloc] = \
gcmt.hypocentre.depth
# Moment, magnitude and relative errors
self.catalogue.data['moment'][iloc] = gcmt.moment
self.catalogue.data['magnitude'][iloc] = gcmt.magnitude
self.catalogue.data['f_clvd'][iloc] = gcmt.f_clvd
self.catalogue.data['e_rel'][iloc] = gcmt.e_rel
self.catalogue.data['centroidID'][iloc] = gcmt.identifier
# Nodal planes
self.catalogue.data['strike1'][iloc] = \
gcmt.nodal_planes.nodal_plane_1['strike']
self.catalogue.data['dip1'][iloc] = \
gcmt.nodal_planes.nodal_plane_1['dip']
self.catalogue.data['rake1'][iloc] = \
gcmt.nodal_planes.nodal_plane_1['rake']
self.catalogue.data['strike2'][iloc] = \
gcmt.nodal_planes.nodal_plane_2['strike']
self.catalogue.data['dip2'][iloc] = \
gcmt.nodal_planes.nodal_plane_2['dip']
self.catalogue.data['rake2'][iloc] = \
gcmt.nodal_planes.nodal_plane_2['rake']
# Principal axes
self.catalogue.data['eigenvalue_b'][iloc] = \
gcmt.principal_axes.b_axis['eigenvalue']
self.catalogue.data['azimuth_b'][iloc] = \
gcmt.principal_axes.b_axis['azimuth']
self.catalogue.data['plunge_b'][iloc] = \
gcmt.principal_axes.b_axis['plunge']
self.catalogue.data['eigenvalue_p'][iloc] = \
gcmt.principal_axes.p_axis['eigenvalue']
self.catalogue.data['azimuth_p'][iloc] = \
gcmt.principal_axes.p_axis['azimuth']
self.catalogue.data['plunge_p'][iloc] = \
gcmt.principal_axes.p_axis['plunge']
self.catalogue.data['eigenvalue_t'][iloc] = \
gcmt.principal_axes.t_axis['eigenvalue']
self.catalogue.data['azimuth_t'][iloc] = \
gcmt.principal_axes.t_axis['azimuth']
self.catalogue.data['plunge_t'][iloc] = \
gcmt.principal_axes.t_axis['plunge']
return self.catalogue | python | def to_hmtk(self, use_centroid=True):
self._preallocate_data_dict()
for iloc, gcmt in enumerate(self.catalogue.gcmts):
self.catalogue.data['eventID'][iloc] = iloc
if use_centroid:
self.catalogue.data['year'][iloc] = \
gcmt.centroid.date.year
self.catalogue.data['month'][iloc] = \
gcmt.centroid.date.month
self.catalogue.data['day'][iloc] = \
gcmt.centroid.date.day
self.catalogue.data['hour'][iloc] = \
gcmt.centroid.time.hour
self.catalogue.data['minute'][iloc] = \
gcmt.centroid.time.minute
self.catalogue.data['second'][iloc] = \
gcmt.centroid.time.second
self.catalogue.data['longitude'][iloc] = \
gcmt.centroid.longitude
self.catalogue.data['latitude'][iloc] = \
gcmt.centroid.latitude
self.catalogue.data['depth'][iloc] = \
gcmt.centroid.depth
else:
self.catalogue.data['year'][iloc] = \
gcmt.hypocentre.date.year
self.catalogue.data['month'][iloc] = \
gcmt.hypocentre.date.month
self.catalogue.data['day'][iloc] = \
gcmt.hypocentre.date.day
self.catalogue.data['hour'][iloc] = \
gcmt.hypocentre.time.hour
self.catalogue.data['minute'][iloc] = \
gcmt.hypocentre.time.minute
self.catalogue.data['second'][iloc] = \
gcmt.hypocentre.time.second
self.catalogue.data['longitude'][iloc] = \
gcmt.hypocentre.longitude
self.catalogue.data['latitude'][iloc] = \
gcmt.hypocentre.latitude
self.catalogue.data['depth'][iloc] = \
gcmt.hypocentre.depth
self.catalogue.data['moment'][iloc] = gcmt.moment
self.catalogue.data['magnitude'][iloc] = gcmt.magnitude
self.catalogue.data['f_clvd'][iloc] = gcmt.f_clvd
self.catalogue.data['e_rel'][iloc] = gcmt.e_rel
self.catalogue.data['centroidID'][iloc] = gcmt.identifier
self.catalogue.data['strike1'][iloc] = \
gcmt.nodal_planes.nodal_plane_1['strike']
self.catalogue.data['dip1'][iloc] = \
gcmt.nodal_planes.nodal_plane_1['dip']
self.catalogue.data['rake1'][iloc] = \
gcmt.nodal_planes.nodal_plane_1['rake']
self.catalogue.data['strike2'][iloc] = \
gcmt.nodal_planes.nodal_plane_2['strike']
self.catalogue.data['dip2'][iloc] = \
gcmt.nodal_planes.nodal_plane_2['dip']
self.catalogue.data['rake2'][iloc] = \
gcmt.nodal_planes.nodal_plane_2['rake']
self.catalogue.data['eigenvalue_b'][iloc] = \
gcmt.principal_axes.b_axis['eigenvalue']
self.catalogue.data['azimuth_b'][iloc] = \
gcmt.principal_axes.b_axis['azimuth']
self.catalogue.data['plunge_b'][iloc] = \
gcmt.principal_axes.b_axis['plunge']
self.catalogue.data['eigenvalue_p'][iloc] = \
gcmt.principal_axes.p_axis['eigenvalue']
self.catalogue.data['azimuth_p'][iloc] = \
gcmt.principal_axes.p_axis['azimuth']
self.catalogue.data['plunge_p'][iloc] = \
gcmt.principal_axes.p_axis['plunge']
self.catalogue.data['eigenvalue_t'][iloc] = \
gcmt.principal_axes.t_axis['eigenvalue']
self.catalogue.data['azimuth_t'][iloc] = \
gcmt.principal_axes.t_axis['azimuth']
self.catalogue.data['plunge_t'][iloc] = \
gcmt.principal_axes.t_axis['plunge']
return self.catalogue | [
"def",
"to_hmtk",
"(",
"self",
",",
"use_centroid",
"=",
"True",
")",
":",
"self",
".",
"_preallocate_data_dict",
"(",
")",
"for",
"iloc",
",",
"gcmt",
"in",
"enumerate",
"(",
"self",
".",
"catalogue",
".",
"gcmts",
")",
":",
"self",
".",
"catalogue",
".",
"data",
"[",
"'eventID'",
"]",
"[",
"iloc",
"]",
"=",
"iloc",
"if",
"use_centroid",
":",
"self",
".",
"catalogue",
".",
"data",
"[",
"'year'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"centroid",
".",
"date",
".",
"year",
"self",
".",
"catalogue",
".",
"data",
"[",
"'month'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"centroid",
".",
"date",
".",
"month",
"self",
".",
"catalogue",
".",
"data",
"[",
"'day'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"centroid",
".",
"date",
".",
"day",
"self",
".",
"catalogue",
".",
"data",
"[",
"'hour'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"centroid",
".",
"time",
".",
"hour",
"self",
".",
"catalogue",
".",
"data",
"[",
"'minute'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"centroid",
".",
"time",
".",
"minute",
"self",
".",
"catalogue",
".",
"data",
"[",
"'second'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"centroid",
".",
"time",
".",
"second",
"self",
".",
"catalogue",
".",
"data",
"[",
"'longitude'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"centroid",
".",
"longitude",
"self",
".",
"catalogue",
".",
"data",
"[",
"'latitude'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"centroid",
".",
"latitude",
"self",
".",
"catalogue",
".",
"data",
"[",
"'depth'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"centroid",
".",
"depth",
"else",
":",
"self",
".",
"catalogue",
".",
"data",
"[",
"'year'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"hypocentre",
".",
"date",
".",
"year",
"self",
".",
"catalogue",
".",
"data",
"[",
"'month'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"hypocentre",
".",
"date",
".",
"month",
"self",
".",
"catalogue",
".",
"data",
"[",
"'day'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"hypocentre",
".",
"date",
".",
"day",
"self",
".",
"catalogue",
".",
"data",
"[",
"'hour'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"hypocentre",
".",
"time",
".",
"hour",
"self",
".",
"catalogue",
".",
"data",
"[",
"'minute'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"hypocentre",
".",
"time",
".",
"minute",
"self",
".",
"catalogue",
".",
"data",
"[",
"'second'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"hypocentre",
".",
"time",
".",
"second",
"self",
".",
"catalogue",
".",
"data",
"[",
"'longitude'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"hypocentre",
".",
"longitude",
"self",
".",
"catalogue",
".",
"data",
"[",
"'latitude'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"hypocentre",
".",
"latitude",
"self",
".",
"catalogue",
".",
"data",
"[",
"'depth'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"hypocentre",
".",
"depth",
"# Moment, magnitude and relative errors",
"self",
".",
"catalogue",
".",
"data",
"[",
"'moment'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"moment",
"self",
".",
"catalogue",
".",
"data",
"[",
"'magnitude'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"magnitude",
"self",
".",
"catalogue",
".",
"data",
"[",
"'f_clvd'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"f_clvd",
"self",
".",
"catalogue",
".",
"data",
"[",
"'e_rel'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"e_rel",
"self",
".",
"catalogue",
".",
"data",
"[",
"'centroidID'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"identifier",
"# Nodal planes",
"self",
".",
"catalogue",
".",
"data",
"[",
"'strike1'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"nodal_planes",
".",
"nodal_plane_1",
"[",
"'strike'",
"]",
"self",
".",
"catalogue",
".",
"data",
"[",
"'dip1'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"nodal_planes",
".",
"nodal_plane_1",
"[",
"'dip'",
"]",
"self",
".",
"catalogue",
".",
"data",
"[",
"'rake1'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"nodal_planes",
".",
"nodal_plane_1",
"[",
"'rake'",
"]",
"self",
".",
"catalogue",
".",
"data",
"[",
"'strike2'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"nodal_planes",
".",
"nodal_plane_2",
"[",
"'strike'",
"]",
"self",
".",
"catalogue",
".",
"data",
"[",
"'dip2'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"nodal_planes",
".",
"nodal_plane_2",
"[",
"'dip'",
"]",
"self",
".",
"catalogue",
".",
"data",
"[",
"'rake2'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"nodal_planes",
".",
"nodal_plane_2",
"[",
"'rake'",
"]",
"# Principal axes",
"self",
".",
"catalogue",
".",
"data",
"[",
"'eigenvalue_b'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"principal_axes",
".",
"b_axis",
"[",
"'eigenvalue'",
"]",
"self",
".",
"catalogue",
".",
"data",
"[",
"'azimuth_b'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"principal_axes",
".",
"b_axis",
"[",
"'azimuth'",
"]",
"self",
".",
"catalogue",
".",
"data",
"[",
"'plunge_b'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"principal_axes",
".",
"b_axis",
"[",
"'plunge'",
"]",
"self",
".",
"catalogue",
".",
"data",
"[",
"'eigenvalue_p'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"principal_axes",
".",
"p_axis",
"[",
"'eigenvalue'",
"]",
"self",
".",
"catalogue",
".",
"data",
"[",
"'azimuth_p'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"principal_axes",
".",
"p_axis",
"[",
"'azimuth'",
"]",
"self",
".",
"catalogue",
".",
"data",
"[",
"'plunge_p'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"principal_axes",
".",
"p_axis",
"[",
"'plunge'",
"]",
"self",
".",
"catalogue",
".",
"data",
"[",
"'eigenvalue_t'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"principal_axes",
".",
"t_axis",
"[",
"'eigenvalue'",
"]",
"self",
".",
"catalogue",
".",
"data",
"[",
"'azimuth_t'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"principal_axes",
".",
"t_axis",
"[",
"'azimuth'",
"]",
"self",
".",
"catalogue",
".",
"data",
"[",
"'plunge_t'",
"]",
"[",
"iloc",
"]",
"=",
"gcmt",
".",
"principal_axes",
".",
"t_axis",
"[",
"'plunge'",
"]",
"return",
"self",
".",
"catalogue"
]
| Convert the content of the GCMT catalogue to a HMTK
catalogue. | [
"Convert",
"the",
"content",
"of",
"the",
"GCMT",
"catalogue",
"to",
"a",
"HMTK",
"catalogue",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L216-L301 |
gem/oq-engine | openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py | ParseNDKtoGCMT._read_hypocentre_from_ndk_string | def _read_hypocentre_from_ndk_string(self, linestring):
"""
Reads the hypocentre data from the ndk string to return an
instance of the GCMTHypocentre class
"""
hypo = GCMTHypocentre()
hypo.source = linestring[0:4]
hypo.date = _read_date_from_string(linestring[5:15])
hypo.time = _read_time_from_string(linestring[16:26])
hypo.latitude = float(linestring[27:33])
hypo.longitude = float(linestring[34:41])
hypo.depth = float(linestring[42:47])
magnitudes = [float(x) for x in linestring[48:55].split(' ')]
if magnitudes[0] > 0.:
hypo.m_b = magnitudes[0]
if magnitudes[1] > 0.:
hypo.m_s = magnitudes[1]
hypo.location = linestring[56:]
return hypo | python | def _read_hypocentre_from_ndk_string(self, linestring):
hypo = GCMTHypocentre()
hypo.source = linestring[0:4]
hypo.date = _read_date_from_string(linestring[5:15])
hypo.time = _read_time_from_string(linestring[16:26])
hypo.latitude = float(linestring[27:33])
hypo.longitude = float(linestring[34:41])
hypo.depth = float(linestring[42:47])
magnitudes = [float(x) for x in linestring[48:55].split(' ')]
if magnitudes[0] > 0.:
hypo.m_b = magnitudes[0]
if magnitudes[1] > 0.:
hypo.m_s = magnitudes[1]
hypo.location = linestring[56:]
return hypo | [
"def",
"_read_hypocentre_from_ndk_string",
"(",
"self",
",",
"linestring",
")",
":",
"hypo",
"=",
"GCMTHypocentre",
"(",
")",
"hypo",
".",
"source",
"=",
"linestring",
"[",
"0",
":",
"4",
"]",
"hypo",
".",
"date",
"=",
"_read_date_from_string",
"(",
"linestring",
"[",
"5",
":",
"15",
"]",
")",
"hypo",
".",
"time",
"=",
"_read_time_from_string",
"(",
"linestring",
"[",
"16",
":",
"26",
"]",
")",
"hypo",
".",
"latitude",
"=",
"float",
"(",
"linestring",
"[",
"27",
":",
"33",
"]",
")",
"hypo",
".",
"longitude",
"=",
"float",
"(",
"linestring",
"[",
"34",
":",
"41",
"]",
")",
"hypo",
".",
"depth",
"=",
"float",
"(",
"linestring",
"[",
"42",
":",
"47",
"]",
")",
"magnitudes",
"=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"linestring",
"[",
"48",
":",
"55",
"]",
".",
"split",
"(",
"' '",
")",
"]",
"if",
"magnitudes",
"[",
"0",
"]",
">",
"0.",
":",
"hypo",
".",
"m_b",
"=",
"magnitudes",
"[",
"0",
"]",
"if",
"magnitudes",
"[",
"1",
"]",
">",
"0.",
":",
"hypo",
".",
"m_s",
"=",
"magnitudes",
"[",
"1",
"]",
"hypo",
".",
"location",
"=",
"linestring",
"[",
"56",
":",
"]",
"return",
"hypo"
]
| Reads the hypocentre data from the ndk string to return an
instance of the GCMTHypocentre class | [
"Reads",
"the",
"hypocentre",
"data",
"from",
"the",
"ndk",
"string",
"to",
"return",
"an",
"instance",
"of",
"the",
"GCMTHypocentre",
"class"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L315-L333 |
gem/oq-engine | openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py | ParseNDKtoGCMT._get_metadata_from_ndk_string | def _get_metadata_from_ndk_string(self, gcmt, ndk_string):
"""
Reads the GCMT metadata from line 2 of the ndk batch
"""
gcmt.identifier = ndk_string[:16]
inversion_data = re.split('[A-Z:]+', ndk_string[17:61])
gcmt.metadata['BODY'] = [float(x) for x in inversion_data[1].split()]
gcmt.metadata['SURFACE'] = [
float(x) for x in inversion_data[2].split()]
gcmt.metadata['MANTLE'] = [float(x) for x in inversion_data[3].split()]
further_meta = re.split('[: ]+', ndk_string[62:])
gcmt.metadata['CMT'] = int(further_meta[1])
gcmt.metadata['FUNCTION'] = {'TYPE': further_meta[2],
'DURATION': float(further_meta[3])}
return gcmt | python | def _get_metadata_from_ndk_string(self, gcmt, ndk_string):
gcmt.identifier = ndk_string[:16]
inversion_data = re.split('[A-Z:]+', ndk_string[17:61])
gcmt.metadata['BODY'] = [float(x) for x in inversion_data[1].split()]
gcmt.metadata['SURFACE'] = [
float(x) for x in inversion_data[2].split()]
gcmt.metadata['MANTLE'] = [float(x) for x in inversion_data[3].split()]
further_meta = re.split('[: ]+', ndk_string[62:])
gcmt.metadata['CMT'] = int(further_meta[1])
gcmt.metadata['FUNCTION'] = {'TYPE': further_meta[2],
'DURATION': float(further_meta[3])}
return gcmt | [
"def",
"_get_metadata_from_ndk_string",
"(",
"self",
",",
"gcmt",
",",
"ndk_string",
")",
":",
"gcmt",
".",
"identifier",
"=",
"ndk_string",
"[",
":",
"16",
"]",
"inversion_data",
"=",
"re",
".",
"split",
"(",
"'[A-Z:]+'",
",",
"ndk_string",
"[",
"17",
":",
"61",
"]",
")",
"gcmt",
".",
"metadata",
"[",
"'BODY'",
"]",
"=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"inversion_data",
"[",
"1",
"]",
".",
"split",
"(",
")",
"]",
"gcmt",
".",
"metadata",
"[",
"'SURFACE'",
"]",
"=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"inversion_data",
"[",
"2",
"]",
".",
"split",
"(",
")",
"]",
"gcmt",
".",
"metadata",
"[",
"'MANTLE'",
"]",
"=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"inversion_data",
"[",
"3",
"]",
".",
"split",
"(",
")",
"]",
"further_meta",
"=",
"re",
".",
"split",
"(",
"'[: ]+'",
",",
"ndk_string",
"[",
"62",
":",
"]",
")",
"gcmt",
".",
"metadata",
"[",
"'CMT'",
"]",
"=",
"int",
"(",
"further_meta",
"[",
"1",
"]",
")",
"gcmt",
".",
"metadata",
"[",
"'FUNCTION'",
"]",
"=",
"{",
"'TYPE'",
":",
"further_meta",
"[",
"2",
"]",
",",
"'DURATION'",
":",
"float",
"(",
"further_meta",
"[",
"3",
"]",
")",
"}",
"return",
"gcmt"
]
| Reads the GCMT metadata from line 2 of the ndk batch | [
"Reads",
"the",
"GCMT",
"metadata",
"from",
"line",
"2",
"of",
"the",
"ndk",
"batch"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L335-L349 |
gem/oq-engine | openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py | ParseNDKtoGCMT._read_centroid_from_ndk_string | def _read_centroid_from_ndk_string(self, ndk_string, hypocentre):
"""
Reads the centroid data from the ndk string to return an
instance of the GCMTCentroid class
:param str ndk_string:
String of data (line 3 of ndk format)
:param hypocentre:
Instance of the GCMTHypocentre class
"""
centroid = GCMTCentroid(hypocentre.date,
hypocentre.time)
data = ndk_string[:58].split()
centroid.centroid_type = data[0].rstrip(':')
data = [float(x) for x in data[1:]]
time_diff = data[0]
if fabs(time_diff) > 1E-6:
centroid._get_centroid_time(time_diff)
centroid.time_error = data[1]
centroid.latitude = data[2]
centroid.latitude_error = data[3]
centroid.longitude = data[4]
centroid.longitude_error = data[5]
centroid.depth = data[6]
centroid.depth_error = data[7]
centroid.depth_type = ndk_string[59:63]
centroid.centroid_id = ndk_string[64:]
return centroid | python | def _read_centroid_from_ndk_string(self, ndk_string, hypocentre):
centroid = GCMTCentroid(hypocentre.date,
hypocentre.time)
data = ndk_string[:58].split()
centroid.centroid_type = data[0].rstrip(':')
data = [float(x) for x in data[1:]]
time_diff = data[0]
if fabs(time_diff) > 1E-6:
centroid._get_centroid_time(time_diff)
centroid.time_error = data[1]
centroid.latitude = data[2]
centroid.latitude_error = data[3]
centroid.longitude = data[4]
centroid.longitude_error = data[5]
centroid.depth = data[6]
centroid.depth_error = data[7]
centroid.depth_type = ndk_string[59:63]
centroid.centroid_id = ndk_string[64:]
return centroid | [
"def",
"_read_centroid_from_ndk_string",
"(",
"self",
",",
"ndk_string",
",",
"hypocentre",
")",
":",
"centroid",
"=",
"GCMTCentroid",
"(",
"hypocentre",
".",
"date",
",",
"hypocentre",
".",
"time",
")",
"data",
"=",
"ndk_string",
"[",
":",
"58",
"]",
".",
"split",
"(",
")",
"centroid",
".",
"centroid_type",
"=",
"data",
"[",
"0",
"]",
".",
"rstrip",
"(",
"':'",
")",
"data",
"=",
"[",
"float",
"(",
"x",
")",
"for",
"x",
"in",
"data",
"[",
"1",
":",
"]",
"]",
"time_diff",
"=",
"data",
"[",
"0",
"]",
"if",
"fabs",
"(",
"time_diff",
")",
">",
"1E-6",
":",
"centroid",
".",
"_get_centroid_time",
"(",
"time_diff",
")",
"centroid",
".",
"time_error",
"=",
"data",
"[",
"1",
"]",
"centroid",
".",
"latitude",
"=",
"data",
"[",
"2",
"]",
"centroid",
".",
"latitude_error",
"=",
"data",
"[",
"3",
"]",
"centroid",
".",
"longitude",
"=",
"data",
"[",
"4",
"]",
"centroid",
".",
"longitude_error",
"=",
"data",
"[",
"5",
"]",
"centroid",
".",
"depth",
"=",
"data",
"[",
"6",
"]",
"centroid",
".",
"depth_error",
"=",
"data",
"[",
"7",
"]",
"centroid",
".",
"depth_type",
"=",
"ndk_string",
"[",
"59",
":",
"63",
"]",
"centroid",
".",
"centroid_id",
"=",
"ndk_string",
"[",
"64",
":",
"]",
"return",
"centroid"
]
| Reads the centroid data from the ndk string to return an
instance of the GCMTCentroid class
:param str ndk_string:
String of data (line 3 of ndk format)
:param hypocentre:
Instance of the GCMTHypocentre class | [
"Reads",
"the",
"centroid",
"data",
"from",
"the",
"ndk",
"string",
"to",
"return",
"an",
"instance",
"of",
"the",
"GCMTCentroid",
"class",
":",
"param",
"str",
"ndk_string",
":",
"String",
"of",
"data",
"(",
"line",
"3",
"of",
"ndk",
"format",
")",
":",
"param",
"hypocentre",
":",
"Instance",
"of",
"the",
"GCMTHypocentre",
"class"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L351-L378 |
gem/oq-engine | openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py | ParseNDKtoGCMT._get_moment_tensor_from_ndk_string | def _get_moment_tensor_from_ndk_string(self, ndk_string):
"""
Reads the moment tensor from the ndk_string and returns an instance of
the GCMTMomentTensor class.
By default the ndk format uses the Up, South, East (USE) reference
system.
"""
moment_tensor = GCMTMomentTensor('USE')
tensor_data = _read_moment_tensor_from_ndk_string(ndk_string, 'USE')
moment_tensor.tensor = tensor_data[0]
moment_tensor.tensor_sigma = tensor_data[1]
moment_tensor.exponent = tensor_data[2]
return moment_tensor | python | def _get_moment_tensor_from_ndk_string(self, ndk_string):
moment_tensor = GCMTMomentTensor('USE')
tensor_data = _read_moment_tensor_from_ndk_string(ndk_string, 'USE')
moment_tensor.tensor = tensor_data[0]
moment_tensor.tensor_sigma = tensor_data[1]
moment_tensor.exponent = tensor_data[2]
return moment_tensor | [
"def",
"_get_moment_tensor_from_ndk_string",
"(",
"self",
",",
"ndk_string",
")",
":",
"moment_tensor",
"=",
"GCMTMomentTensor",
"(",
"'USE'",
")",
"tensor_data",
"=",
"_read_moment_tensor_from_ndk_string",
"(",
"ndk_string",
",",
"'USE'",
")",
"moment_tensor",
".",
"tensor",
"=",
"tensor_data",
"[",
"0",
"]",
"moment_tensor",
".",
"tensor_sigma",
"=",
"tensor_data",
"[",
"1",
"]",
"moment_tensor",
".",
"exponent",
"=",
"tensor_data",
"[",
"2",
"]",
"return",
"moment_tensor"
]
| Reads the moment tensor from the ndk_string and returns an instance of
the GCMTMomentTensor class.
By default the ndk format uses the Up, South, East (USE) reference
system. | [
"Reads",
"the",
"moment",
"tensor",
"from",
"the",
"ndk_string",
"and",
"returns",
"an",
"instance",
"of",
"the",
"GCMTMomentTensor",
"class",
".",
"By",
"default",
"the",
"ndk",
"format",
"uses",
"the",
"Up",
"South",
"East",
"(",
"USE",
")",
"reference",
"system",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L380-L392 |
gem/oq-engine | openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py | ParseNDKtoGCMT._get_principal_axes_from_ndk_string | def _get_principal_axes_from_ndk_string(self, ndk_string, exponent):
"""
Gets the principal axes from the ndk string and returns an instance
of the GCMTPrincipalAxes class
"""
axes = GCMTPrincipalAxes()
# The principal axes is defined in characters 3:48 of the 5th line
exponent = 10. ** exponent
axes.t_axis = {'eigenvalue': exponent * float(ndk_string[0:8]),
'plunge': float(ndk_string[8:11]),
'azimuth': float(ndk_string[11:15])}
axes.b_axis = {'eigenvalue': exponent * float(ndk_string[15:23]),
'plunge': float(ndk_string[23:26]),
'azimuth': float(ndk_string[26:30])}
axes.p_axis = {'eigenvalue': exponent * float(ndk_string[30:38]),
'plunge': float(ndk_string[38:41]),
'azimuth': float(ndk_string[41:])}
return axes | python | def _get_principal_axes_from_ndk_string(self, ndk_string, exponent):
axes = GCMTPrincipalAxes()
exponent = 10. ** exponent
axes.t_axis = {'eigenvalue': exponent * float(ndk_string[0:8]),
'plunge': float(ndk_string[8:11]),
'azimuth': float(ndk_string[11:15])}
axes.b_axis = {'eigenvalue': exponent * float(ndk_string[15:23]),
'plunge': float(ndk_string[23:26]),
'azimuth': float(ndk_string[26:30])}
axes.p_axis = {'eigenvalue': exponent * float(ndk_string[30:38]),
'plunge': float(ndk_string[38:41]),
'azimuth': float(ndk_string[41:])}
return axes | [
"def",
"_get_principal_axes_from_ndk_string",
"(",
"self",
",",
"ndk_string",
",",
"exponent",
")",
":",
"axes",
"=",
"GCMTPrincipalAxes",
"(",
")",
"# The principal axes is defined in characters 3:48 of the 5th line",
"exponent",
"=",
"10.",
"**",
"exponent",
"axes",
".",
"t_axis",
"=",
"{",
"'eigenvalue'",
":",
"exponent",
"*",
"float",
"(",
"ndk_string",
"[",
"0",
":",
"8",
"]",
")",
",",
"'plunge'",
":",
"float",
"(",
"ndk_string",
"[",
"8",
":",
"11",
"]",
")",
",",
"'azimuth'",
":",
"float",
"(",
"ndk_string",
"[",
"11",
":",
"15",
"]",
")",
"}",
"axes",
".",
"b_axis",
"=",
"{",
"'eigenvalue'",
":",
"exponent",
"*",
"float",
"(",
"ndk_string",
"[",
"15",
":",
"23",
"]",
")",
",",
"'plunge'",
":",
"float",
"(",
"ndk_string",
"[",
"23",
":",
"26",
"]",
")",
",",
"'azimuth'",
":",
"float",
"(",
"ndk_string",
"[",
"26",
":",
"30",
"]",
")",
"}",
"axes",
".",
"p_axis",
"=",
"{",
"'eigenvalue'",
":",
"exponent",
"*",
"float",
"(",
"ndk_string",
"[",
"30",
":",
"38",
"]",
")",
",",
"'plunge'",
":",
"float",
"(",
"ndk_string",
"[",
"38",
":",
"41",
"]",
")",
",",
"'azimuth'",
":",
"float",
"(",
"ndk_string",
"[",
"41",
":",
"]",
")",
"}",
"return",
"axes"
]
| Gets the principal axes from the ndk string and returns an instance
of the GCMTPrincipalAxes class | [
"Gets",
"the",
"principal",
"axes",
"from",
"the",
"ndk",
"string",
"and",
"returns",
"an",
"instance",
"of",
"the",
"GCMTPrincipalAxes",
"class"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L394-L413 |
gem/oq-engine | openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py | ParseNDKtoGCMT._get_nodal_planes_from_ndk_string | def _get_nodal_planes_from_ndk_string(self, ndk_string):
"""
Reads the nodal plane information (represented by 5th line [57:] of the
tensor representation) and returns an instance of the GCMTNodalPlanes
class
"""
planes = GCMTNodalPlanes()
planes.nodal_plane_1 = {'strike': float(ndk_string[0:3]),
'dip': float(ndk_string[3:6]),
'rake': float(ndk_string[6:11])}
planes.nodal_plane_2 = {'strike': float(ndk_string[11:15]),
'dip': float(ndk_string[15:18]),
'rake': float(ndk_string[18:])}
return planes | python | def _get_nodal_planes_from_ndk_string(self, ndk_string):
planes = GCMTNodalPlanes()
planes.nodal_plane_1 = {'strike': float(ndk_string[0:3]),
'dip': float(ndk_string[3:6]),
'rake': float(ndk_string[6:11])}
planes.nodal_plane_2 = {'strike': float(ndk_string[11:15]),
'dip': float(ndk_string[15:18]),
'rake': float(ndk_string[18:])}
return planes | [
"def",
"_get_nodal_planes_from_ndk_string",
"(",
"self",
",",
"ndk_string",
")",
":",
"planes",
"=",
"GCMTNodalPlanes",
"(",
")",
"planes",
".",
"nodal_plane_1",
"=",
"{",
"'strike'",
":",
"float",
"(",
"ndk_string",
"[",
"0",
":",
"3",
"]",
")",
",",
"'dip'",
":",
"float",
"(",
"ndk_string",
"[",
"3",
":",
"6",
"]",
")",
",",
"'rake'",
":",
"float",
"(",
"ndk_string",
"[",
"6",
":",
"11",
"]",
")",
"}",
"planes",
".",
"nodal_plane_2",
"=",
"{",
"'strike'",
":",
"float",
"(",
"ndk_string",
"[",
"11",
":",
"15",
"]",
")",
",",
"'dip'",
":",
"float",
"(",
"ndk_string",
"[",
"15",
":",
"18",
"]",
")",
",",
"'rake'",
":",
"float",
"(",
"ndk_string",
"[",
"18",
":",
"]",
")",
"}",
"return",
"planes"
]
| Reads the nodal plane information (represented by 5th line [57:] of the
tensor representation) and returns an instance of the GCMTNodalPlanes
class | [
"Reads",
"the",
"nodal",
"plane",
"information",
"(",
"represented",
"by",
"5th",
"line",
"[",
"57",
":",
"]",
"of",
"the",
"tensor",
"representation",
")",
"and",
"returns",
"an",
"instance",
"of",
"the",
"GCMTNodalPlanes",
"class"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L415-L428 |
gem/oq-engine | openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py | ParseNDKtoGCMT._get_moment_from_ndk_string | def _get_moment_from_ndk_string(self, ndk_string, exponent):
"""
Returns the moment and the moment magnitude
"""
moment = float(ndk_string[49:56]) * (10. ** exponent)
version = ndk_string[:3]
magnitude = utils.moment_magnitude_scalar(moment)
return moment, version, magnitude | python | def _get_moment_from_ndk_string(self, ndk_string, exponent):
moment = float(ndk_string[49:56]) * (10. ** exponent)
version = ndk_string[:3]
magnitude = utils.moment_magnitude_scalar(moment)
return moment, version, magnitude | [
"def",
"_get_moment_from_ndk_string",
"(",
"self",
",",
"ndk_string",
",",
"exponent",
")",
":",
"moment",
"=",
"float",
"(",
"ndk_string",
"[",
"49",
":",
"56",
"]",
")",
"*",
"(",
"10.",
"**",
"exponent",
")",
"version",
"=",
"ndk_string",
"[",
":",
"3",
"]",
"magnitude",
"=",
"utils",
".",
"moment_magnitude_scalar",
"(",
"moment",
")",
"return",
"moment",
",",
"version",
",",
"magnitude"
]
| Returns the moment and the moment magnitude | [
"Returns",
"the",
"moment",
"and",
"the",
"moment",
"magnitude"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/catalogue/gcmt_ndk_parser.py#L430-L437 |
gem/oq-engine | openquake/hmtk/sources/source_model.py | mtkSourceModel.serialise_to_nrml | def serialise_to_nrml(self, filename, use_defaults=False):
'''
Writes the source model to a nrml source model file given by the
filename
:param str filename:
Path to output file
:param bool use_defaults:
Boolean to indicate whether to use default values (True) or not.
If set to False, ValueErrors will be raised when an essential
attribute is missing.
'''
source_model = self.convert_to_oqhazardlib(
PoissonTOM(1.0), 2.0, 2.0, 10.0, use_defaults=use_defaults)
write_source_model(filename, source_model, name=self.name) | python | def serialise_to_nrml(self, filename, use_defaults=False):
source_model = self.convert_to_oqhazardlib(
PoissonTOM(1.0), 2.0, 2.0, 10.0, use_defaults=use_defaults)
write_source_model(filename, source_model, name=self.name) | [
"def",
"serialise_to_nrml",
"(",
"self",
",",
"filename",
",",
"use_defaults",
"=",
"False",
")",
":",
"source_model",
"=",
"self",
".",
"convert_to_oqhazardlib",
"(",
"PoissonTOM",
"(",
"1.0",
")",
",",
"2.0",
",",
"2.0",
",",
"10.0",
",",
"use_defaults",
"=",
"use_defaults",
")",
"write_source_model",
"(",
"filename",
",",
"source_model",
",",
"name",
"=",
"self",
".",
"name",
")"
]
| Writes the source model to a nrml source model file given by the
filename
:param str filename:
Path to output file
:param bool use_defaults:
Boolean to indicate whether to use default values (True) or not.
If set to False, ValueErrors will be raised when an essential
attribute is missing. | [
"Writes",
"the",
"source",
"model",
"to",
"a",
"nrml",
"source",
"model",
"file",
"given",
"by",
"the",
"filename"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/source_model.py#L95-L110 |
gem/oq-engine | openquake/hmtk/sources/source_model.py | mtkSourceModel.convert_to_oqhazardlib | def convert_to_oqhazardlib(
self, tom, simple_mesh_spacing=1.0,
complex_mesh_spacing=2.0, area_discretisation=10.0,
use_defaults=False):
"""
Converts the source model to an iterator of sources of :class:
openquake.hazardlib.source.base.BaseSeismicSource
"""
oq_source_model = []
for source in self.sources:
if isinstance(source, mtkAreaSource):
oq_source_model.append(source.create_oqhazardlib_source(
tom,
simple_mesh_spacing,
area_discretisation,
use_defaults))
elif isinstance(source, mtkPointSource):
oq_source_model.append(source.create_oqhazardlib_source(
tom,
simple_mesh_spacing,
use_defaults))
elif isinstance(source, mtkSimpleFaultSource):
oq_source_model.append(source.create_oqhazardlib_source(
tom,
simple_mesh_spacing,
use_defaults))
elif isinstance(source, mtkComplexFaultSource):
oq_source_model.append(source.create_oqhazardlib_source(
tom,
complex_mesh_spacing,
use_defaults))
else:
raise ValueError('Source type not recognised!')
return oq_source_model | python | def convert_to_oqhazardlib(
self, tom, simple_mesh_spacing=1.0,
complex_mesh_spacing=2.0, area_discretisation=10.0,
use_defaults=False):
oq_source_model = []
for source in self.sources:
if isinstance(source, mtkAreaSource):
oq_source_model.append(source.create_oqhazardlib_source(
tom,
simple_mesh_spacing,
area_discretisation,
use_defaults))
elif isinstance(source, mtkPointSource):
oq_source_model.append(source.create_oqhazardlib_source(
tom,
simple_mesh_spacing,
use_defaults))
elif isinstance(source, mtkSimpleFaultSource):
oq_source_model.append(source.create_oqhazardlib_source(
tom,
simple_mesh_spacing,
use_defaults))
elif isinstance(source, mtkComplexFaultSource):
oq_source_model.append(source.create_oqhazardlib_source(
tom,
complex_mesh_spacing,
use_defaults))
else:
raise ValueError('Source type not recognised!')
return oq_source_model | [
"def",
"convert_to_oqhazardlib",
"(",
"self",
",",
"tom",
",",
"simple_mesh_spacing",
"=",
"1.0",
",",
"complex_mesh_spacing",
"=",
"2.0",
",",
"area_discretisation",
"=",
"10.0",
",",
"use_defaults",
"=",
"False",
")",
":",
"oq_source_model",
"=",
"[",
"]",
"for",
"source",
"in",
"self",
".",
"sources",
":",
"if",
"isinstance",
"(",
"source",
",",
"mtkAreaSource",
")",
":",
"oq_source_model",
".",
"append",
"(",
"source",
".",
"create_oqhazardlib_source",
"(",
"tom",
",",
"simple_mesh_spacing",
",",
"area_discretisation",
",",
"use_defaults",
")",
")",
"elif",
"isinstance",
"(",
"source",
",",
"mtkPointSource",
")",
":",
"oq_source_model",
".",
"append",
"(",
"source",
".",
"create_oqhazardlib_source",
"(",
"tom",
",",
"simple_mesh_spacing",
",",
"use_defaults",
")",
")",
"elif",
"isinstance",
"(",
"source",
",",
"mtkSimpleFaultSource",
")",
":",
"oq_source_model",
".",
"append",
"(",
"source",
".",
"create_oqhazardlib_source",
"(",
"tom",
",",
"simple_mesh_spacing",
",",
"use_defaults",
")",
")",
"elif",
"isinstance",
"(",
"source",
",",
"mtkComplexFaultSource",
")",
":",
"oq_source_model",
".",
"append",
"(",
"source",
".",
"create_oqhazardlib_source",
"(",
"tom",
",",
"complex_mesh_spacing",
",",
"use_defaults",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Source type not recognised!'",
")",
"return",
"oq_source_model"
]
| Converts the source model to an iterator of sources of :class:
openquake.hazardlib.source.base.BaseSeismicSource | [
"Converts",
"the",
"source",
"model",
"to",
"an",
"iterator",
"of",
"sources",
"of",
":",
"class",
":",
"openquake",
".",
"hazardlib",
".",
"source",
".",
"base",
".",
"BaseSeismicSource"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/source_model.py#L112-L145 |
gem/oq-engine | openquake/hmtk/seismicity/occurrence/utils.py | recurrence_table | def recurrence_table(mag, dmag, year, time_interval=None):
"""
Table of recurrence statistics for each magnitude
[Magnitude, Number of Observations, Cumulative Number
of Observations >= M, Number of Observations
(normalised to annual value), Cumulative Number of
Observations (normalised to annual value)]
Counts number and cumulative number of occurrences of
each magnitude in catalogue
:param numpy.ndarray mag:
Catalog matrix magnitude column
:param numpy.ndarray dmag:
Magnitude interval
:param numpy.ndarray year:
Catalog matrix year column
:returns numpy.ndarray recurrence table:
Recurrence table
"""
# Define magnitude vectors
if time_interval is None:
num_year = np.max(year) - np.min(year) + 1.
else:
num_year = time_interval
upper_m = np.max(np.ceil(10.0 * mag) / 10.0)
lower_m = np.min(np.floor(10.0 * mag) / 10.0)
mag_range = np.arange(lower_m, upper_m + (1.5 * dmag), dmag)
mval = mag_range[:-1] + (dmag / 2.0)
# Find number of earthquakes inside range
number_obs = np.histogram(mag, mag_range)[0]
number_rows = np.shape(number_obs)[0]
# Cumulative number of events
n_c = np.zeros((number_rows, 1))
i = 0
while i < number_rows:
n_c[i] = np.sum(number_obs[i:], axis=0)
i += 1
# Normalise to Annual Rate
number_obs_annual = number_obs / num_year
n_c_annual = n_c / num_year
rec_table = np.column_stack([mval, number_obs, n_c, number_obs_annual,
n_c_annual])
return rec_table | python | def recurrence_table(mag, dmag, year, time_interval=None):
if time_interval is None:
num_year = np.max(year) - np.min(year) + 1.
else:
num_year = time_interval
upper_m = np.max(np.ceil(10.0 * mag) / 10.0)
lower_m = np.min(np.floor(10.0 * mag) / 10.0)
mag_range = np.arange(lower_m, upper_m + (1.5 * dmag), dmag)
mval = mag_range[:-1] + (dmag / 2.0)
number_obs = np.histogram(mag, mag_range)[0]
number_rows = np.shape(number_obs)[0]
n_c = np.zeros((number_rows, 1))
i = 0
while i < number_rows:
n_c[i] = np.sum(number_obs[i:], axis=0)
i += 1
number_obs_annual = number_obs / num_year
n_c_annual = n_c / num_year
rec_table = np.column_stack([mval, number_obs, n_c, number_obs_annual,
n_c_annual])
return rec_table | [
"def",
"recurrence_table",
"(",
"mag",
",",
"dmag",
",",
"year",
",",
"time_interval",
"=",
"None",
")",
":",
"# Define magnitude vectors",
"if",
"time_interval",
"is",
"None",
":",
"num_year",
"=",
"np",
".",
"max",
"(",
"year",
")",
"-",
"np",
".",
"min",
"(",
"year",
")",
"+",
"1.",
"else",
":",
"num_year",
"=",
"time_interval",
"upper_m",
"=",
"np",
".",
"max",
"(",
"np",
".",
"ceil",
"(",
"10.0",
"*",
"mag",
")",
"/",
"10.0",
")",
"lower_m",
"=",
"np",
".",
"min",
"(",
"np",
".",
"floor",
"(",
"10.0",
"*",
"mag",
")",
"/",
"10.0",
")",
"mag_range",
"=",
"np",
".",
"arange",
"(",
"lower_m",
",",
"upper_m",
"+",
"(",
"1.5",
"*",
"dmag",
")",
",",
"dmag",
")",
"mval",
"=",
"mag_range",
"[",
":",
"-",
"1",
"]",
"+",
"(",
"dmag",
"/",
"2.0",
")",
"# Find number of earthquakes inside range",
"number_obs",
"=",
"np",
".",
"histogram",
"(",
"mag",
",",
"mag_range",
")",
"[",
"0",
"]",
"number_rows",
"=",
"np",
".",
"shape",
"(",
"number_obs",
")",
"[",
"0",
"]",
"# Cumulative number of events",
"n_c",
"=",
"np",
".",
"zeros",
"(",
"(",
"number_rows",
",",
"1",
")",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"number_rows",
":",
"n_c",
"[",
"i",
"]",
"=",
"np",
".",
"sum",
"(",
"number_obs",
"[",
"i",
":",
"]",
",",
"axis",
"=",
"0",
")",
"i",
"+=",
"1",
"# Normalise to Annual Rate",
"number_obs_annual",
"=",
"number_obs",
"/",
"num_year",
"n_c_annual",
"=",
"n_c",
"/",
"num_year",
"rec_table",
"=",
"np",
".",
"column_stack",
"(",
"[",
"mval",
",",
"number_obs",
",",
"n_c",
",",
"number_obs_annual",
",",
"n_c_annual",
"]",
")",
"return",
"rec_table"
]
| Table of recurrence statistics for each magnitude
[Magnitude, Number of Observations, Cumulative Number
of Observations >= M, Number of Observations
(normalised to annual value), Cumulative Number of
Observations (normalised to annual value)]
Counts number and cumulative number of occurrences of
each magnitude in catalogue
:param numpy.ndarray mag:
Catalog matrix magnitude column
:param numpy.ndarray dmag:
Magnitude interval
:param numpy.ndarray year:
Catalog matrix year column
:returns numpy.ndarray recurrence table:
Recurrence table | [
"Table",
"of",
"recurrence",
"statistics",
"for",
"each",
"magnitude",
"[",
"Magnitude",
"Number",
"of",
"Observations",
"Cumulative",
"Number",
"of",
"Observations",
">",
"=",
"M",
"Number",
"of",
"Observations",
"(",
"normalised",
"to",
"annual",
"value",
")",
"Cumulative",
"Number",
"of",
"Observations",
"(",
"normalised",
"to",
"annual",
"value",
")",
"]",
"Counts",
"number",
"and",
"cumulative",
"number",
"of",
"occurrences",
"of",
"each",
"magnitude",
"in",
"catalogue"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/occurrence/utils.py#L54-L97 |
gem/oq-engine | openquake/hmtk/seismicity/occurrence/utils.py | input_checks | def input_checks(catalogue, config, completeness):
""" Performs a basic set of input checks on the data
"""
if isinstance(completeness, np.ndarray):
# completeness table is a numpy array (i.e. [year, magnitude])
if np.shape(completeness)[1] != 2:
raise ValueError('Completeness Table incorrectly configured')
else:
cmag = completeness[:, 1]
ctime = completeness[:, 0]
elif isinstance(completeness, float):
# Completeness corresponds to a single magnitude (i.e. applies to
# the entire catalogue)
cmag = np.array(completeness)
ctime = np.array(np.min(catalogue.data['year']))
else:
# Everything is valid - i.e. no completeness magnitude
cmag = np.array(np.min(catalogue.data['magnitude']))
ctime = np.array(np.min(catalogue.data['year']))
# Set reference magnitude - if not in config then default to M = 0.
if not config:
# use default reference magnitude of 0.0 and magnitude interval of 0.1
ref_mag = 0.0
dmag = 0.1
config = {'reference_magnitude': None,
'magnitude_interval': 0.1}
else:
if (not 'reference_magnitude' in config.keys()) or\
(config['reference_magnitude'] is None):
ref_mag = 0.
config['reference_magnitude'] = None
else:
ref_mag = config['reference_magnitude']
if (not 'magnitude_interval' in config.keys()) or \
not config['magnitude_interval']:
dmag = 0.1
else:
dmag = config['magnitude_interval']
return cmag, ctime, ref_mag, dmag, config | python | def input_checks(catalogue, config, completeness):
if isinstance(completeness, np.ndarray):
if np.shape(completeness)[1] != 2:
raise ValueError('Completeness Table incorrectly configured')
else:
cmag = completeness[:, 1]
ctime = completeness[:, 0]
elif isinstance(completeness, float):
cmag = np.array(completeness)
ctime = np.array(np.min(catalogue.data['year']))
else:
cmag = np.array(np.min(catalogue.data['magnitude']))
ctime = np.array(np.min(catalogue.data['year']))
if not config:
ref_mag = 0.0
dmag = 0.1
config = {'reference_magnitude': None,
'magnitude_interval': 0.1}
else:
if (not 'reference_magnitude' in config.keys()) or\
(config['reference_magnitude'] is None):
ref_mag = 0.
config['reference_magnitude'] = None
else:
ref_mag = config['reference_magnitude']
if (not 'magnitude_interval' in config.keys()) or \
not config['magnitude_interval']:
dmag = 0.1
else:
dmag = config['magnitude_interval']
return cmag, ctime, ref_mag, dmag, config | [
"def",
"input_checks",
"(",
"catalogue",
",",
"config",
",",
"completeness",
")",
":",
"if",
"isinstance",
"(",
"completeness",
",",
"np",
".",
"ndarray",
")",
":",
"# completeness table is a numpy array (i.e. [year, magnitude])",
"if",
"np",
".",
"shape",
"(",
"completeness",
")",
"[",
"1",
"]",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'Completeness Table incorrectly configured'",
")",
"else",
":",
"cmag",
"=",
"completeness",
"[",
":",
",",
"1",
"]",
"ctime",
"=",
"completeness",
"[",
":",
",",
"0",
"]",
"elif",
"isinstance",
"(",
"completeness",
",",
"float",
")",
":",
"# Completeness corresponds to a single magnitude (i.e. applies to",
"# the entire catalogue)",
"cmag",
"=",
"np",
".",
"array",
"(",
"completeness",
")",
"ctime",
"=",
"np",
".",
"array",
"(",
"np",
".",
"min",
"(",
"catalogue",
".",
"data",
"[",
"'year'",
"]",
")",
")",
"else",
":",
"# Everything is valid - i.e. no completeness magnitude",
"cmag",
"=",
"np",
".",
"array",
"(",
"np",
".",
"min",
"(",
"catalogue",
".",
"data",
"[",
"'magnitude'",
"]",
")",
")",
"ctime",
"=",
"np",
".",
"array",
"(",
"np",
".",
"min",
"(",
"catalogue",
".",
"data",
"[",
"'year'",
"]",
")",
")",
"# Set reference magnitude - if not in config then default to M = 0.",
"if",
"not",
"config",
":",
"# use default reference magnitude of 0.0 and magnitude interval of 0.1",
"ref_mag",
"=",
"0.0",
"dmag",
"=",
"0.1",
"config",
"=",
"{",
"'reference_magnitude'",
":",
"None",
",",
"'magnitude_interval'",
":",
"0.1",
"}",
"else",
":",
"if",
"(",
"not",
"'reference_magnitude'",
"in",
"config",
".",
"keys",
"(",
")",
")",
"or",
"(",
"config",
"[",
"'reference_magnitude'",
"]",
"is",
"None",
")",
":",
"ref_mag",
"=",
"0.",
"config",
"[",
"'reference_magnitude'",
"]",
"=",
"None",
"else",
":",
"ref_mag",
"=",
"config",
"[",
"'reference_magnitude'",
"]",
"if",
"(",
"not",
"'magnitude_interval'",
"in",
"config",
".",
"keys",
"(",
")",
")",
"or",
"not",
"config",
"[",
"'magnitude_interval'",
"]",
":",
"dmag",
"=",
"0.1",
"else",
":",
"dmag",
"=",
"config",
"[",
"'magnitude_interval'",
"]",
"return",
"cmag",
",",
"ctime",
",",
"ref_mag",
",",
"dmag",
",",
"config"
]
| Performs a basic set of input checks on the data | [
"Performs",
"a",
"basic",
"set",
"of",
"input",
"checks",
"on",
"the",
"data"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/occurrence/utils.py#L100-L142 |
gem/oq-engine | openquake/hmtk/seismicity/occurrence/utils.py | generate_trunc_gr_magnitudes | def generate_trunc_gr_magnitudes(bval, mmin, mmax, nsamples):
'''
Generate a random list of magnitudes distributed according to a
truncated Gutenberg-Richter model
:param float bval:
b-value
:param float mmin:
Minimum Magnitude
:param float mmax:
Maximum Magnitude
:param int nsamples:
Number of samples
:returns:
Vector of generated magnitudes
'''
sampler = np.random.uniform(0., 1., nsamples)
beta = bval * np.log(10.)
return (-1. / beta) * (
np.log(1. - sampler * (1 - np.exp(-beta * (mmax - mmin))))) + mmin | python | def generate_trunc_gr_magnitudes(bval, mmin, mmax, nsamples):
sampler = np.random.uniform(0., 1., nsamples)
beta = bval * np.log(10.)
return (-1. / beta) * (
np.log(1. - sampler * (1 - np.exp(-beta * (mmax - mmin))))) + mmin | [
"def",
"generate_trunc_gr_magnitudes",
"(",
"bval",
",",
"mmin",
",",
"mmax",
",",
"nsamples",
")",
":",
"sampler",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"0.",
",",
"1.",
",",
"nsamples",
")",
"beta",
"=",
"bval",
"*",
"np",
".",
"log",
"(",
"10.",
")",
"return",
"(",
"-",
"1.",
"/",
"beta",
")",
"*",
"(",
"np",
".",
"log",
"(",
"1.",
"-",
"sampler",
"*",
"(",
"1",
"-",
"np",
".",
"exp",
"(",
"-",
"beta",
"*",
"(",
"mmax",
"-",
"mmin",
")",
")",
")",
")",
")",
"+",
"mmin"
]
| Generate a random list of magnitudes distributed according to a
truncated Gutenberg-Richter model
:param float bval:
b-value
:param float mmin:
Minimum Magnitude
:param float mmax:
Maximum Magnitude
:param int nsamples:
Number of samples
:returns:
Vector of generated magnitudes | [
"Generate",
"a",
"random",
"list",
"of",
"magnitudes",
"distributed",
"according",
"to",
"a",
"truncated",
"Gutenberg",
"-",
"Richter",
"model"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/occurrence/utils.py#L145-L165 |
gem/oq-engine | openquake/hmtk/seismicity/occurrence/utils.py | generate_synthetic_magnitudes | def generate_synthetic_magnitudes(aval, bval, mmin, mmax, nyears):
'''
Generates a synthetic catalogue for a specified number of years, with
magnitudes distributed according to a truncated Gutenberg-Richter
distribution
:param float aval:
a-value
:param float bval:
b-value
:param float mmin:
Minimum Magnitude
:param float mmax:
Maximum Magnitude
:param int nyears:
Number of years
:returns:
Synthetic catalogue (dict) with year and magnitude attributes
'''
nsamples = int(np.round(nyears * (10. ** (aval - bval * mmin)), 0))
year = np.random.randint(0, nyears, nsamples)
# Get magnitudes
mags = generate_trunc_gr_magnitudes(bval, mmin, mmax, nsamples)
return {'magnitude': mags, 'year': np.sort(year)} | python | def generate_synthetic_magnitudes(aval, bval, mmin, mmax, nyears):
nsamples = int(np.round(nyears * (10. ** (aval - bval * mmin)), 0))
year = np.random.randint(0, nyears, nsamples)
mags = generate_trunc_gr_magnitudes(bval, mmin, mmax, nsamples)
return {'magnitude': mags, 'year': np.sort(year)} | [
"def",
"generate_synthetic_magnitudes",
"(",
"aval",
",",
"bval",
",",
"mmin",
",",
"mmax",
",",
"nyears",
")",
":",
"nsamples",
"=",
"int",
"(",
"np",
".",
"round",
"(",
"nyears",
"*",
"(",
"10.",
"**",
"(",
"aval",
"-",
"bval",
"*",
"mmin",
")",
")",
",",
"0",
")",
")",
"year",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"nyears",
",",
"nsamples",
")",
"# Get magnitudes",
"mags",
"=",
"generate_trunc_gr_magnitudes",
"(",
"bval",
",",
"mmin",
",",
"mmax",
",",
"nsamples",
")",
"return",
"{",
"'magnitude'",
":",
"mags",
",",
"'year'",
":",
"np",
".",
"sort",
"(",
"year",
")",
"}"
]
| Generates a synthetic catalogue for a specified number of years, with
magnitudes distributed according to a truncated Gutenberg-Richter
distribution
:param float aval:
a-value
:param float bval:
b-value
:param float mmin:
Minimum Magnitude
:param float mmax:
Maximum Magnitude
:param int nyears:
Number of years
:returns:
Synthetic catalogue (dict) with year and magnitude attributes | [
"Generates",
"a",
"synthetic",
"catalogue",
"for",
"a",
"specified",
"number",
"of",
"years",
"with",
"magnitudes",
"distributed",
"according",
"to",
"a",
"truncated",
"Gutenberg",
"-",
"Richter",
"distribution"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/occurrence/utils.py#L168-L191 |
gem/oq-engine | openquake/hmtk/seismicity/occurrence/utils.py | downsample_completeness_table | def downsample_completeness_table(comp_table, sample_width=0.1, mmax=None):
"""
Re-sample the completeness table to a specified sample_width
"""
new_comp_table = []
for i in range(comp_table.shape[0] - 1):
mvals = np.arange(comp_table[i, 1],
comp_table[i + 1, 1], d_m) # FIXME: d_m is undefined!
new_comp_table.extend([[comp_table[i, 0], mval] for mval in mvals])
# If mmax > last magnitude in completeness table
if mmax and (mmax > comp_table[-1, 1]):
new_comp_table.extend(
[[comp_table[-1, 0], mval]
for mval in np.arange(comp_table[-1, 1], mmax + d_m, d_m)])
return np.array(new_comp_table) | python | def downsample_completeness_table(comp_table, sample_width=0.1, mmax=None):
new_comp_table = []
for i in range(comp_table.shape[0] - 1):
mvals = np.arange(comp_table[i, 1],
comp_table[i + 1, 1], d_m)
new_comp_table.extend([[comp_table[i, 0], mval] for mval in mvals])
if mmax and (mmax > comp_table[-1, 1]):
new_comp_table.extend(
[[comp_table[-1, 0], mval]
for mval in np.arange(comp_table[-1, 1], mmax + d_m, d_m)])
return np.array(new_comp_table) | [
"def",
"downsample_completeness_table",
"(",
"comp_table",
",",
"sample_width",
"=",
"0.1",
",",
"mmax",
"=",
"None",
")",
":",
"new_comp_table",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"comp_table",
".",
"shape",
"[",
"0",
"]",
"-",
"1",
")",
":",
"mvals",
"=",
"np",
".",
"arange",
"(",
"comp_table",
"[",
"i",
",",
"1",
"]",
",",
"comp_table",
"[",
"i",
"+",
"1",
",",
"1",
"]",
",",
"d_m",
")",
"# FIXME: d_m is undefined!",
"new_comp_table",
".",
"extend",
"(",
"[",
"[",
"comp_table",
"[",
"i",
",",
"0",
"]",
",",
"mval",
"]",
"for",
"mval",
"in",
"mvals",
"]",
")",
"# If mmax > last magnitude in completeness table",
"if",
"mmax",
"and",
"(",
"mmax",
">",
"comp_table",
"[",
"-",
"1",
",",
"1",
"]",
")",
":",
"new_comp_table",
".",
"extend",
"(",
"[",
"[",
"comp_table",
"[",
"-",
"1",
",",
"0",
"]",
",",
"mval",
"]",
"for",
"mval",
"in",
"np",
".",
"arange",
"(",
"comp_table",
"[",
"-",
"1",
",",
"1",
"]",
",",
"mmax",
"+",
"d_m",
",",
"d_m",
")",
"]",
")",
"return",
"np",
".",
"array",
"(",
"new_comp_table",
")"
]
| Re-sample the completeness table to a specified sample_width | [
"Re",
"-",
"sample",
"the",
"completeness",
"table",
"to",
"a",
"specified",
"sample_width"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/occurrence/utils.py#L194-L208 |
gem/oq-engine | openquake/hmtk/seismicity/occurrence/utils.py | get_completeness_counts | def get_completeness_counts(catalogue, completeness, d_m):
"""
Returns the number of earthquakes in a set of magnitude bins of specified
with, along with the corresponding completeness duration (in years) of the
bin
:param catalogue:
Earthquake catalogue as instance of
:class: openquake.hmtk.seisimicity.catalogue.Catalogue
:param numpy.ndarray completeness:
Completeness table [year, magnitude]
:param float d_m:
Bin size
:returns:
* cent_mag - array indicating center of magnitude bins
* t_per - array indicating total duration (in years) of completeness
* n_obs - number of events in completeness period
"""
mmax_obs = np.max(catalogue.data["magnitude"])
# thw line below was added by Nick Ackerley but it breaks the tests
# catalogue.data["dtime"] = catalogue.get_decimal_time()
if mmax_obs > np.max(completeness[:, 1]):
cmag = np.hstack([completeness[:, 1], mmax_obs])
else:
cmag = completeness[:, 1]
cyear = np.hstack([catalogue.end_year + 1, completeness[:, 0]])
# When the magnitude value is on the bin edge numpy's histogram function
# may assign randomly to one side or the other based on the floating
# point value. As catalogues are rounded to the nearest 0.1 this occurs
# frequently! So we offset the bin edge by a very tiny amount to ensure
# that, for example, M = 4.099999999 is assigned to the bin M = 4.1 and
# not 4.0
master_bins = np.arange(np.min(cmag) - 1.0E-7,
np.max(cmag) + d_m,
d_m)
count_rates = np.zeros(len(master_bins) - 1)
count_years = np.zeros_like(count_rates)
for i in range(len(cyear) - 1):
time_idx = np.logical_and(catalogue.data["dtime"] < cyear[i],
catalogue.data["dtime"] >= cyear[i + 1])
nyrs = cyear[i] - cyear[i + 1]
sel_mags = catalogue.data["magnitude"][time_idx]
m_idx = np.where(master_bins >= (cmag[i] - (d_m / 2.)))[0]
m_bins = master_bins[m_idx]
count_rates[m_idx[:-1]] += np.histogram(
sel_mags,
bins=m_bins)[0].astype(float)
count_years[m_idx[:-1]] += float(nyrs)
# Removes any zero rates greater than
last_loc = np.where(count_rates > 0)[0][-1]
n_obs = count_rates[:(last_loc + 1)]
t_per = count_years[:(last_loc + 1)]
cent_mag = (master_bins[:-1] + master_bins[1:]) / 2.
cent_mag = np.around(cent_mag[:(last_loc + 1)], 3)
return cent_mag, t_per, n_obs | python | def get_completeness_counts(catalogue, completeness, d_m):
mmax_obs = np.max(catalogue.data["magnitude"])
if mmax_obs > np.max(completeness[:, 1]):
cmag = np.hstack([completeness[:, 1], mmax_obs])
else:
cmag = completeness[:, 1]
cyear = np.hstack([catalogue.end_year + 1, completeness[:, 0]])
master_bins = np.arange(np.min(cmag) - 1.0E-7,
np.max(cmag) + d_m,
d_m)
count_rates = np.zeros(len(master_bins) - 1)
count_years = np.zeros_like(count_rates)
for i in range(len(cyear) - 1):
time_idx = np.logical_and(catalogue.data["dtime"] < cyear[i],
catalogue.data["dtime"] >= cyear[i + 1])
nyrs = cyear[i] - cyear[i + 1]
sel_mags = catalogue.data["magnitude"][time_idx]
m_idx = np.where(master_bins >= (cmag[i] - (d_m / 2.)))[0]
m_bins = master_bins[m_idx]
count_rates[m_idx[:-1]] += np.histogram(
sel_mags,
bins=m_bins)[0].astype(float)
count_years[m_idx[:-1]] += float(nyrs)
last_loc = np.where(count_rates > 0)[0][-1]
n_obs = count_rates[:(last_loc + 1)]
t_per = count_years[:(last_loc + 1)]
cent_mag = (master_bins[:-1] + master_bins[1:]) / 2.
cent_mag = np.around(cent_mag[:(last_loc + 1)], 3)
return cent_mag, t_per, n_obs | [
"def",
"get_completeness_counts",
"(",
"catalogue",
",",
"completeness",
",",
"d_m",
")",
":",
"mmax_obs",
"=",
"np",
".",
"max",
"(",
"catalogue",
".",
"data",
"[",
"\"magnitude\"",
"]",
")",
"# thw line below was added by Nick Ackerley but it breaks the tests",
"# catalogue.data[\"dtime\"] = catalogue.get_decimal_time()",
"if",
"mmax_obs",
">",
"np",
".",
"max",
"(",
"completeness",
"[",
":",
",",
"1",
"]",
")",
":",
"cmag",
"=",
"np",
".",
"hstack",
"(",
"[",
"completeness",
"[",
":",
",",
"1",
"]",
",",
"mmax_obs",
"]",
")",
"else",
":",
"cmag",
"=",
"completeness",
"[",
":",
",",
"1",
"]",
"cyear",
"=",
"np",
".",
"hstack",
"(",
"[",
"catalogue",
".",
"end_year",
"+",
"1",
",",
"completeness",
"[",
":",
",",
"0",
"]",
"]",
")",
"# When the magnitude value is on the bin edge numpy's histogram function",
"# may assign randomly to one side or the other based on the floating",
"# point value. As catalogues are rounded to the nearest 0.1 this occurs",
"# frequently! So we offset the bin edge by a very tiny amount to ensure",
"# that, for example, M = 4.099999999 is assigned to the bin M = 4.1 and",
"# not 4.0",
"master_bins",
"=",
"np",
".",
"arange",
"(",
"np",
".",
"min",
"(",
"cmag",
")",
"-",
"1.0E-7",
",",
"np",
".",
"max",
"(",
"cmag",
")",
"+",
"d_m",
",",
"d_m",
")",
"count_rates",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"master_bins",
")",
"-",
"1",
")",
"count_years",
"=",
"np",
".",
"zeros_like",
"(",
"count_rates",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"cyear",
")",
"-",
"1",
")",
":",
"time_idx",
"=",
"np",
".",
"logical_and",
"(",
"catalogue",
".",
"data",
"[",
"\"dtime\"",
"]",
"<",
"cyear",
"[",
"i",
"]",
",",
"catalogue",
".",
"data",
"[",
"\"dtime\"",
"]",
">=",
"cyear",
"[",
"i",
"+",
"1",
"]",
")",
"nyrs",
"=",
"cyear",
"[",
"i",
"]",
"-",
"cyear",
"[",
"i",
"+",
"1",
"]",
"sel_mags",
"=",
"catalogue",
".",
"data",
"[",
"\"magnitude\"",
"]",
"[",
"time_idx",
"]",
"m_idx",
"=",
"np",
".",
"where",
"(",
"master_bins",
">=",
"(",
"cmag",
"[",
"i",
"]",
"-",
"(",
"d_m",
"/",
"2.",
")",
")",
")",
"[",
"0",
"]",
"m_bins",
"=",
"master_bins",
"[",
"m_idx",
"]",
"count_rates",
"[",
"m_idx",
"[",
":",
"-",
"1",
"]",
"]",
"+=",
"np",
".",
"histogram",
"(",
"sel_mags",
",",
"bins",
"=",
"m_bins",
")",
"[",
"0",
"]",
".",
"astype",
"(",
"float",
")",
"count_years",
"[",
"m_idx",
"[",
":",
"-",
"1",
"]",
"]",
"+=",
"float",
"(",
"nyrs",
")",
"# Removes any zero rates greater than",
"last_loc",
"=",
"np",
".",
"where",
"(",
"count_rates",
">",
"0",
")",
"[",
"0",
"]",
"[",
"-",
"1",
"]",
"n_obs",
"=",
"count_rates",
"[",
":",
"(",
"last_loc",
"+",
"1",
")",
"]",
"t_per",
"=",
"count_years",
"[",
":",
"(",
"last_loc",
"+",
"1",
")",
"]",
"cent_mag",
"=",
"(",
"master_bins",
"[",
":",
"-",
"1",
"]",
"+",
"master_bins",
"[",
"1",
":",
"]",
")",
"/",
"2.",
"cent_mag",
"=",
"np",
".",
"around",
"(",
"cent_mag",
"[",
":",
"(",
"last_loc",
"+",
"1",
")",
"]",
",",
"3",
")",
"return",
"cent_mag",
",",
"t_per",
",",
"n_obs"
]
| Returns the number of earthquakes in a set of magnitude bins of specified
with, along with the corresponding completeness duration (in years) of the
bin
:param catalogue:
Earthquake catalogue as instance of
:class: openquake.hmtk.seisimicity.catalogue.Catalogue
:param numpy.ndarray completeness:
Completeness table [year, magnitude]
:param float d_m:
Bin size
:returns:
* cent_mag - array indicating center of magnitude bins
* t_per - array indicating total duration (in years) of completeness
* n_obs - number of events in completeness period | [
"Returns",
"the",
"number",
"of",
"earthquakes",
"in",
"a",
"set",
"of",
"magnitude",
"bins",
"of",
"specified",
"with",
"along",
"with",
"the",
"corresponding",
"completeness",
"duration",
"(",
"in",
"years",
")",
"of",
"the",
"bin"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/occurrence/utils.py#L211-L266 |
gem/oq-engine | openquake/commands/reset.py | reset | def reset(yes):
"""
Remove all the datastores and the database of the current user
"""
ok = yes or confirm('Do you really want to destroy all your data? (y/n) ')
if not ok:
return
dbpath = os.path.realpath(os.path.expanduser(config.dbserver.file))
# user must be able to access and write the databse file to remove it
if os.path.isfile(dbpath) and os.access(dbpath, os.W_OK):
if dbserver.get_status() == 'running':
if config.dbserver.multi_user:
sys.exit('The oq dbserver must be stopped '
'before proceeding')
else:
pid = logs.dbcmd('getpid')
os.kill(pid, signal.SIGTERM)
time.sleep(.5) # give time to stop
assert dbserver.get_status() == 'not-running'
print('dbserver stopped')
try:
os.remove(dbpath)
print('Removed %s' % dbpath)
except OSError as exc:
print(exc, file=sys.stderr)
# fast way of removing everything
purge_all(fast=True) | python | def reset(yes):
ok = yes or confirm('Do you really want to destroy all your data? (y/n) ')
if not ok:
return
dbpath = os.path.realpath(os.path.expanduser(config.dbserver.file))
if os.path.isfile(dbpath) and os.access(dbpath, os.W_OK):
if dbserver.get_status() == 'running':
if config.dbserver.multi_user:
sys.exit('The oq dbserver must be stopped '
'before proceeding')
else:
pid = logs.dbcmd('getpid')
os.kill(pid, signal.SIGTERM)
time.sleep(.5)
assert dbserver.get_status() == 'not-running'
print('dbserver stopped')
try:
os.remove(dbpath)
print('Removed %s' % dbpath)
except OSError as exc:
print(exc, file=sys.stderr)
purge_all(fast=True) | [
"def",
"reset",
"(",
"yes",
")",
":",
"ok",
"=",
"yes",
"or",
"confirm",
"(",
"'Do you really want to destroy all your data? (y/n) '",
")",
"if",
"not",
"ok",
":",
"return",
"dbpath",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"config",
".",
"dbserver",
".",
"file",
")",
")",
"# user must be able to access and write the databse file to remove it",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"dbpath",
")",
"and",
"os",
".",
"access",
"(",
"dbpath",
",",
"os",
".",
"W_OK",
")",
":",
"if",
"dbserver",
".",
"get_status",
"(",
")",
"==",
"'running'",
":",
"if",
"config",
".",
"dbserver",
".",
"multi_user",
":",
"sys",
".",
"exit",
"(",
"'The oq dbserver must be stopped '",
"'before proceeding'",
")",
"else",
":",
"pid",
"=",
"logs",
".",
"dbcmd",
"(",
"'getpid'",
")",
"os",
".",
"kill",
"(",
"pid",
",",
"signal",
".",
"SIGTERM",
")",
"time",
".",
"sleep",
"(",
".5",
")",
"# give time to stop",
"assert",
"dbserver",
".",
"get_status",
"(",
")",
"==",
"'not-running'",
"print",
"(",
"'dbserver stopped'",
")",
"try",
":",
"os",
".",
"remove",
"(",
"dbpath",
")",
"print",
"(",
"'Removed %s'",
"%",
"dbpath",
")",
"except",
"OSError",
"as",
"exc",
":",
"print",
"(",
"exc",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"# fast way of removing everything",
"purge_all",
"(",
"fast",
"=",
"True",
")"
]
| Remove all the datastores and the database of the current user | [
"Remove",
"all",
"the",
"datastores",
"and",
"the",
"database",
"of",
"the",
"current",
"user"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/reset.py#L30-L59 |
gem/oq-engine | openquake/hazardlib/gsim/drouet_alpes_2015.py | DrouetAlpes2015Rjb._compute_mean | def _compute_mean(self, C, mag, r):
"""
Compute mean value according to equation 30, page 1021.
"""
mean = (C['c1'] +
self._compute_term1(C, mag) +
self._compute_term2(C, mag, r))
return mean | python | def _compute_mean(self, C, mag, r):
mean = (C['c1'] +
self._compute_term1(C, mag) +
self._compute_term2(C, mag, r))
return mean | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"mag",
",",
"r",
")",
":",
"mean",
"=",
"(",
"C",
"[",
"'c1'",
"]",
"+",
"self",
".",
"_compute_term1",
"(",
"C",
",",
"mag",
")",
"+",
"self",
".",
"_compute_term2",
"(",
"C",
",",
"mag",
",",
"r",
")",
")",
"return",
"mean"
]
| Compute mean value according to equation 30, page 1021. | [
"Compute",
"mean",
"value",
"according",
"to",
"equation",
"30",
"page",
"1021",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/drouet_alpes_2015.py#L119-L126 |
gem/oq-engine | openquake/hazardlib/gsim/drouet_alpes_2015.py | DrouetAlpes2015Rjb._compute_term2 | def _compute_term2(self, C, mag, r):
"""
This computes the term f2 equation 8 Drouet & Cotton (2015)
"""
return (C['c4'] + C['c5'] * mag) * \
np.log(np.sqrt(r**2 + C['c6']**2)) + C['c7'] * r | python | def _compute_term2(self, C, mag, r):
return (C['c4'] + C['c5'] * mag) * \
np.log(np.sqrt(r**2 + C['c6']**2)) + C['c7'] * r | [
"def",
"_compute_term2",
"(",
"self",
",",
"C",
",",
"mag",
",",
"r",
")",
":",
"return",
"(",
"C",
"[",
"'c4'",
"]",
"+",
"C",
"[",
"'c5'",
"]",
"*",
"mag",
")",
"*",
"np",
".",
"log",
"(",
"np",
".",
"sqrt",
"(",
"r",
"**",
"2",
"+",
"C",
"[",
"'c6'",
"]",
"**",
"2",
")",
")",
"+",
"C",
"[",
"'c7'",
"]",
"*",
"r"
]
| This computes the term f2 equation 8 Drouet & Cotton (2015) | [
"This",
"computes",
"the",
"term",
"f2",
"equation",
"8",
"Drouet",
"&",
"Cotton",
"(",
"2015",
")"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/drouet_alpes_2015.py#L150-L155 |
gem/oq-engine | openquake/hazardlib/gsim/drouet_alpes_2015.py | DrouetAlpes2015Rrup.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]
mean = self._compute_mean(C, rup.mag, dists.rrup)
if isinstance(imt, SA) or isinstance(imt, PGA):
# Convert from m/s**2 to g
mean = mean - np.log(g)
elif isinstance(imt, PGV): # Convert from m/s to cm/s
mean = mean + np.log(100.0)
stddevs = self._get_stddevs(C, stddev_types, rup.mag,
dists.rrup.shape[0])
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]
mean = self._compute_mean(C, rup.mag, dists.rrup)
if isinstance(imt, SA) or isinstance(imt, PGA):
mean = mean - np.log(g)
elif isinstance(imt, PGV):
mean = mean + np.log(100.0)
stddevs = self._get_stddevs(C, stddev_types, rup.mag,
dists.rrup.shape[0])
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",
"]",
"mean",
"=",
"self",
".",
"_compute_mean",
"(",
"C",
",",
"rup",
".",
"mag",
",",
"dists",
".",
"rrup",
")",
"if",
"isinstance",
"(",
"imt",
",",
"SA",
")",
"or",
"isinstance",
"(",
"imt",
",",
"PGA",
")",
":",
"# Convert from m/s**2 to g",
"mean",
"=",
"mean",
"-",
"np",
".",
"log",
"(",
"g",
")",
"elif",
"isinstance",
"(",
"imt",
",",
"PGV",
")",
":",
"# Convert from m/s to cm/s",
"mean",
"=",
"mean",
"+",
"np",
".",
"log",
"(",
"100.0",
")",
"stddevs",
"=",
"self",
".",
"_get_stddevs",
"(",
"C",
",",
"stddev_types",
",",
"rup",
".",
"mag",
",",
"dists",
".",
"rrup",
".",
"shape",
"[",
"0",
"]",
")",
"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/drouet_alpes_2015.py#L196-L215 |
gem/oq-engine | openquake/server/db/actions.py | set_status | def set_status(db, job_id, status):
"""
Set the status 'created', 'executing', 'complete', 'failed', 'aborted'
consistently with `is_running`.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: ID of the current job
:param status: status string
"""
assert status in (
'created', 'submitted', 'executing', 'complete', 'aborted', 'failed'
), status
if status in ('created', 'complete', 'failed', 'aborted'):
is_running = 0
else: # 'executing'
is_running = 1
if job_id < 0:
rows = db('SELECT id FROM job ORDER BY id DESC LIMIT ?x', -job_id)
if not rows:
return 0
job_id = rows[-1].id
cursor = db('UPDATE job SET status=?x, is_running=?x WHERE id=?x',
status, is_running, job_id)
return cursor.rowcount | python | def set_status(db, job_id, status):
assert status in (
'created', 'submitted', 'executing', 'complete', 'aborted', 'failed'
), status
if status in ('created', 'complete', 'failed', 'aborted'):
is_running = 0
else:
is_running = 1
if job_id < 0:
rows = db('SELECT id FROM job ORDER BY id DESC LIMIT ?x', -job_id)
if not rows:
return 0
job_id = rows[-1].id
cursor = db('UPDATE job SET status=?x, is_running=?x WHERE id=?x',
status, is_running, job_id)
return cursor.rowcount | [
"def",
"set_status",
"(",
"db",
",",
"job_id",
",",
"status",
")",
":",
"assert",
"status",
"in",
"(",
"'created'",
",",
"'submitted'",
",",
"'executing'",
",",
"'complete'",
",",
"'aborted'",
",",
"'failed'",
")",
",",
"status",
"if",
"status",
"in",
"(",
"'created'",
",",
"'complete'",
",",
"'failed'",
",",
"'aborted'",
")",
":",
"is_running",
"=",
"0",
"else",
":",
"# 'executing'",
"is_running",
"=",
"1",
"if",
"job_id",
"<",
"0",
":",
"rows",
"=",
"db",
"(",
"'SELECT id FROM job ORDER BY id DESC LIMIT ?x'",
",",
"-",
"job_id",
")",
"if",
"not",
"rows",
":",
"return",
"0",
"job_id",
"=",
"rows",
"[",
"-",
"1",
"]",
".",
"id",
"cursor",
"=",
"db",
"(",
"'UPDATE job SET status=?x, is_running=?x WHERE id=?x'",
",",
"status",
",",
"is_running",
",",
"job_id",
")",
"return",
"cursor",
".",
"rowcount"
]
| Set the status 'created', 'executing', 'complete', 'failed', 'aborted'
consistently with `is_running`.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: ID of the current job
:param status: status string | [
"Set",
"the",
"status",
"created",
"executing",
"complete",
"failed",
"aborted",
"consistently",
"with",
"is_running",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L62-L85 |
gem/oq-engine | openquake/server/db/actions.py | create_job | def create_job(db, datadir):
"""
Create job for the given user, return it.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param datadir:
Data directory of the user who owns/started this job.
:returns:
the job ID
"""
calc_id = get_calc_id(db, datadir) + 1
job = dict(id=calc_id, is_running=1, description='just created',
user_name='openquake', calculation_mode='to be set',
ds_calc_dir=os.path.join('%s/calc_%s' % (datadir, calc_id)))
return db('INSERT INTO job (?S) VALUES (?X)',
job.keys(), job.values()).lastrowid | python | def create_job(db, datadir):
calc_id = get_calc_id(db, datadir) + 1
job = dict(id=calc_id, is_running=1, description='just created',
user_name='openquake', calculation_mode='to be set',
ds_calc_dir=os.path.join('%s/calc_%s' % (datadir, calc_id)))
return db('INSERT INTO job (?S) VALUES (?X)',
job.keys(), job.values()).lastrowid | [
"def",
"create_job",
"(",
"db",
",",
"datadir",
")",
":",
"calc_id",
"=",
"get_calc_id",
"(",
"db",
",",
"datadir",
")",
"+",
"1",
"job",
"=",
"dict",
"(",
"id",
"=",
"calc_id",
",",
"is_running",
"=",
"1",
",",
"description",
"=",
"'just created'",
",",
"user_name",
"=",
"'openquake'",
",",
"calculation_mode",
"=",
"'to be set'",
",",
"ds_calc_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'%s/calc_%s'",
"%",
"(",
"datadir",
",",
"calc_id",
")",
")",
")",
"return",
"db",
"(",
"'INSERT INTO job (?S) VALUES (?X)'",
",",
"job",
".",
"keys",
"(",
")",
",",
"job",
".",
"values",
"(",
")",
")",
".",
"lastrowid"
]
| Create job for the given user, return it.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param datadir:
Data directory of the user who owns/started this job.
:returns:
the job ID | [
"Create",
"job",
"for",
"the",
"given",
"user",
"return",
"it",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L88-L104 |
gem/oq-engine | openquake/server/db/actions.py | import_job | def import_job(db, calc_id, calc_mode, description, user_name, status,
hc_id, datadir):
"""
Insert a calculation inside the database, if calc_id is not taken
"""
job = dict(id=calc_id,
calculation_mode=calc_mode,
description=description,
user_name=user_name,
hazard_calculation_id=hc_id,
is_running=0,
status=status,
ds_calc_dir=os.path.join('%s/calc_%s' % (datadir, calc_id)))
db('INSERT INTO job (?S) VALUES (?X)', job.keys(), job.values()) | python | def import_job(db, calc_id, calc_mode, description, user_name, status,
hc_id, datadir):
job = dict(id=calc_id,
calculation_mode=calc_mode,
description=description,
user_name=user_name,
hazard_calculation_id=hc_id,
is_running=0,
status=status,
ds_calc_dir=os.path.join('%s/calc_%s' % (datadir, calc_id)))
db('INSERT INTO job (?S) VALUES (?X)', job.keys(), job.values()) | [
"def",
"import_job",
"(",
"db",
",",
"calc_id",
",",
"calc_mode",
",",
"description",
",",
"user_name",
",",
"status",
",",
"hc_id",
",",
"datadir",
")",
":",
"job",
"=",
"dict",
"(",
"id",
"=",
"calc_id",
",",
"calculation_mode",
"=",
"calc_mode",
",",
"description",
"=",
"description",
",",
"user_name",
"=",
"user_name",
",",
"hazard_calculation_id",
"=",
"hc_id",
",",
"is_running",
"=",
"0",
",",
"status",
"=",
"status",
",",
"ds_calc_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'%s/calc_%s'",
"%",
"(",
"datadir",
",",
"calc_id",
")",
")",
")",
"db",
"(",
"'INSERT INTO job (?S) VALUES (?X)'",
",",
"job",
".",
"keys",
"(",
")",
",",
"job",
".",
"values",
"(",
")",
")"
]
| Insert a calculation inside the database, if calc_id is not taken | [
"Insert",
"a",
"calculation",
"inside",
"the",
"database",
"if",
"calc_id",
"is",
"not",
"taken"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L107-L120 |
gem/oq-engine | openquake/server/db/actions.py | get_job | def get_job(db, job_id, username=None):
"""
If job_id is negative, return the last calculation of the current
user, otherwise returns the job_id unchanged.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: a job ID (can be negative and can be nonexisting)
:param username: an user name (if None, ignore it)
:returns: a valid job or None if the original job ID was invalid
"""
job_id = int(job_id)
if job_id > 0:
dic = dict(id=job_id)
if username:
dic['user_name'] = username
try:
return db('SELECT * FROM job WHERE ?A', dic, one=True)
except NotFound:
return
# else negative job_id
if username:
joblist = db('SELECT * FROM job WHERE user_name=?x '
'ORDER BY id DESC LIMIT ?x', username, -job_id)
else:
joblist = db('SELECT * FROM job ORDER BY id DESC LIMIT ?x', -job_id)
if not joblist: # no jobs
return
else:
return joblist[-1] | python | def get_job(db, job_id, username=None):
job_id = int(job_id)
if job_id > 0:
dic = dict(id=job_id)
if username:
dic['user_name'] = username
try:
return db('SELECT * FROM job WHERE ?A', dic, one=True)
except NotFound:
return
if username:
joblist = db('SELECT * FROM job WHERE user_name=?x '
'ORDER BY id DESC LIMIT ?x', username, -job_id)
else:
joblist = db('SELECT * FROM job ORDER BY id DESC LIMIT ?x', -job_id)
if not joblist:
return
else:
return joblist[-1] | [
"def",
"get_job",
"(",
"db",
",",
"job_id",
",",
"username",
"=",
"None",
")",
":",
"job_id",
"=",
"int",
"(",
"job_id",
")",
"if",
"job_id",
">",
"0",
":",
"dic",
"=",
"dict",
"(",
"id",
"=",
"job_id",
")",
"if",
"username",
":",
"dic",
"[",
"'user_name'",
"]",
"=",
"username",
"try",
":",
"return",
"db",
"(",
"'SELECT * FROM job WHERE ?A'",
",",
"dic",
",",
"one",
"=",
"True",
")",
"except",
"NotFound",
":",
"return",
"# else negative job_id",
"if",
"username",
":",
"joblist",
"=",
"db",
"(",
"'SELECT * FROM job WHERE user_name=?x '",
"'ORDER BY id DESC LIMIT ?x'",
",",
"username",
",",
"-",
"job_id",
")",
"else",
":",
"joblist",
"=",
"db",
"(",
"'SELECT * FROM job ORDER BY id DESC LIMIT ?x'",
",",
"-",
"job_id",
")",
"if",
"not",
"joblist",
":",
"# no jobs",
"return",
"else",
":",
"return",
"joblist",
"[",
"-",
"1",
"]"
]
| If job_id is negative, return the last calculation of the current
user, otherwise returns the job_id unchanged.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: a job ID (can be negative and can be nonexisting)
:param username: an user name (if None, ignore it)
:returns: a valid job or None if the original job ID was invalid | [
"If",
"job_id",
"is",
"negative",
"return",
"the",
"last",
"calculation",
"of",
"the",
"current",
"user",
"otherwise",
"returns",
"the",
"job_id",
"unchanged",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L133-L163 |
gem/oq-engine | openquake/server/db/actions.py | get_calc_id | def get_calc_id(db, datadir, job_id=None):
"""
Return the latest calc_id by looking both at the datastore
and the database.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param datadir: the directory containing the datastores
:param job_id: a job ID; if None, returns the latest job ID
"""
calcs = datastore.get_calc_ids(datadir)
calc_id = 0 if not calcs else calcs[-1]
if job_id is None:
try:
job_id = db('SELECT seq FROM sqlite_sequence WHERE name="job"',
scalar=True)
except NotFound:
job_id = 0
return max(calc_id, job_id) | python | def get_calc_id(db, datadir, job_id=None):
calcs = datastore.get_calc_ids(datadir)
calc_id = 0 if not calcs else calcs[-1]
if job_id is None:
try:
job_id = db('SELECT seq FROM sqlite_sequence WHERE name="job"',
scalar=True)
except NotFound:
job_id = 0
return max(calc_id, job_id) | [
"def",
"get_calc_id",
"(",
"db",
",",
"datadir",
",",
"job_id",
"=",
"None",
")",
":",
"calcs",
"=",
"datastore",
".",
"get_calc_ids",
"(",
"datadir",
")",
"calc_id",
"=",
"0",
"if",
"not",
"calcs",
"else",
"calcs",
"[",
"-",
"1",
"]",
"if",
"job_id",
"is",
"None",
":",
"try",
":",
"job_id",
"=",
"db",
"(",
"'SELECT seq FROM sqlite_sequence WHERE name=\"job\"'",
",",
"scalar",
"=",
"True",
")",
"except",
"NotFound",
":",
"job_id",
"=",
"0",
"return",
"max",
"(",
"calc_id",
",",
"job_id",
")"
]
| Return the latest calc_id by looking both at the datastore
and the database.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param datadir: the directory containing the datastores
:param job_id: a job ID; if None, returns the latest job ID | [
"Return",
"the",
"latest",
"calc_id",
"by",
"looking",
"both",
"at",
"the",
"datastore",
"and",
"the",
"database",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L166-L183 |
gem/oq-engine | openquake/server/db/actions.py | list_calculations | def list_calculations(db, job_type, user_name):
"""
Yield a summary of past calculations.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_type: 'hazard' or 'risk'
:param user_name: an user name
"""
jobs = db('SELECT *, %s FROM job WHERE user_name=?x '
'AND job_type=?x ORDER BY start_time' % JOB_TYPE,
user_name, job_type)
out = []
if len(jobs) == 0:
out.append('None')
else:
out.append('job_id | status | start_time | '
' description')
for job in jobs:
descr = job.description
start_time = job.start_time
out.append('%6d | %10s | %s | %s' % (
job.id, job.status, start_time, descr))
return out | python | def list_calculations(db, job_type, user_name):
jobs = db('SELECT *, %s FROM job WHERE user_name=?x '
'AND job_type=?x ORDER BY start_time' % JOB_TYPE,
user_name, job_type)
out = []
if len(jobs) == 0:
out.append('None')
else:
out.append('job_id | status | start_time | '
' description')
for job in jobs:
descr = job.description
start_time = job.start_time
out.append('%6d | %10s | %s | %s' % (
job.id, job.status, start_time, descr))
return out | [
"def",
"list_calculations",
"(",
"db",
",",
"job_type",
",",
"user_name",
")",
":",
"jobs",
"=",
"db",
"(",
"'SELECT *, %s FROM job WHERE user_name=?x '",
"'AND job_type=?x ORDER BY start_time'",
"%",
"JOB_TYPE",
",",
"user_name",
",",
"job_type",
")",
"out",
"=",
"[",
"]",
"if",
"len",
"(",
"jobs",
")",
"==",
"0",
":",
"out",
".",
"append",
"(",
"'None'",
")",
"else",
":",
"out",
".",
"append",
"(",
"'job_id | status | start_time | '",
"' description'",
")",
"for",
"job",
"in",
"jobs",
":",
"descr",
"=",
"job",
".",
"description",
"start_time",
"=",
"job",
".",
"start_time",
"out",
".",
"append",
"(",
"'%6d | %10s | %s | %s'",
"%",
"(",
"job",
".",
"id",
",",
"job",
".",
"status",
",",
"start_time",
",",
"descr",
")",
")",
"return",
"out"
]
| Yield a summary of past calculations.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_type: 'hazard' or 'risk'
:param user_name: an user name | [
"Yield",
"a",
"summary",
"of",
"past",
"calculations",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L186-L208 |
gem/oq-engine | openquake/server/db/actions.py | list_outputs | def list_outputs(db, job_id, full=True):
"""
List the outputs for a given
:class:`~openquake.server.db.models.OqJob`.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
ID of a calculation.
:param bool full:
If True produce a full listing, otherwise a short version
"""
outputs = get_outputs(db, job_id)
out = []
if len(outputs) > 0:
truncated = False
out.append(' id | name')
outs = sorted(outputs, key=operator.attrgetter('display_name'))
for i, o in enumerate(outs):
if not full and i >= 10:
out.append(' ... | %d additional output(s)' % (len(outs) - 10))
truncated = True
break
out.append('%4d | %s' % (o.id, o.display_name))
if truncated:
out.append('Some outputs where not shown. You can see the full '
'list with the command\n`oq engine --list-outputs`')
return out | python | def list_outputs(db, job_id, full=True):
outputs = get_outputs(db, job_id)
out = []
if len(outputs) > 0:
truncated = False
out.append(' id | name')
outs = sorted(outputs, key=operator.attrgetter('display_name'))
for i, o in enumerate(outs):
if not full and i >= 10:
out.append(' ... | %d additional output(s)' % (len(outs) - 10))
truncated = True
break
out.append('%4d | %s' % (o.id, o.display_name))
if truncated:
out.append('Some outputs where not shown. You can see the full '
'list with the command\n`oq engine --list-outputs`')
return out | [
"def",
"list_outputs",
"(",
"db",
",",
"job_id",
",",
"full",
"=",
"True",
")",
":",
"outputs",
"=",
"get_outputs",
"(",
"db",
",",
"job_id",
")",
"out",
"=",
"[",
"]",
"if",
"len",
"(",
"outputs",
")",
">",
"0",
":",
"truncated",
"=",
"False",
"out",
".",
"append",
"(",
"' id | name'",
")",
"outs",
"=",
"sorted",
"(",
"outputs",
",",
"key",
"=",
"operator",
".",
"attrgetter",
"(",
"'display_name'",
")",
")",
"for",
"i",
",",
"o",
"in",
"enumerate",
"(",
"outs",
")",
":",
"if",
"not",
"full",
"and",
"i",
">=",
"10",
":",
"out",
".",
"append",
"(",
"' ... | %d additional output(s)'",
"%",
"(",
"len",
"(",
"outs",
")",
"-",
"10",
")",
")",
"truncated",
"=",
"True",
"break",
"out",
".",
"append",
"(",
"'%4d | %s'",
"%",
"(",
"o",
".",
"id",
",",
"o",
".",
"display_name",
")",
")",
"if",
"truncated",
":",
"out",
".",
"append",
"(",
"'Some outputs where not shown. You can see the full '",
"'list with the command\\n`oq engine --list-outputs`'",
")",
"return",
"out"
]
| List the outputs for a given
:class:`~openquake.server.db.models.OqJob`.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
ID of a calculation.
:param bool full:
If True produce a full listing, otherwise a short version | [
"List",
"the",
"outputs",
"for",
"a",
"given",
":",
"class",
":",
"~openquake",
".",
"server",
".",
"db",
".",
"models",
".",
"OqJob",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L211-L238 |
gem/oq-engine | openquake/server/db/actions.py | create_outputs | def create_outputs(db, job_id, keysize, ds_size):
"""
Build a correspondence between the outputs in the datastore and the
ones in the database. Also, update the datastore size in the job table.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: ID of the current job
:param keysize: a list of pairs (key, size_mb)
:param ds_size: total datastore size in MB
"""
rows = [(job_id, DISPLAY_NAME.get(key, key), key, size)
for key, size in keysize]
db('UPDATE job SET size_mb=?x WHERE id=?x', ds_size, job_id)
db.insert('output', 'oq_job_id display_name ds_key size_mb'.split(), rows) | python | def create_outputs(db, job_id, keysize, ds_size):
rows = [(job_id, DISPLAY_NAME.get(key, key), key, size)
for key, size in keysize]
db('UPDATE job SET size_mb=?x WHERE id=?x', ds_size, job_id)
db.insert('output', 'oq_job_id display_name ds_key size_mb'.split(), rows) | [
"def",
"create_outputs",
"(",
"db",
",",
"job_id",
",",
"keysize",
",",
"ds_size",
")",
":",
"rows",
"=",
"[",
"(",
"job_id",
",",
"DISPLAY_NAME",
".",
"get",
"(",
"key",
",",
"key",
")",
",",
"key",
",",
"size",
")",
"for",
"key",
",",
"size",
"in",
"keysize",
"]",
"db",
"(",
"'UPDATE job SET size_mb=?x WHERE id=?x'",
",",
"ds_size",
",",
"job_id",
")",
"db",
".",
"insert",
"(",
"'output'",
",",
"'oq_job_id display_name ds_key size_mb'",
".",
"split",
"(",
")",
",",
"rows",
")"
]
| Build a correspondence between the outputs in the datastore and the
ones in the database. Also, update the datastore size in the job table.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: ID of the current job
:param keysize: a list of pairs (key, size_mb)
:param ds_size: total datastore size in MB | [
"Build",
"a",
"correspondence",
"between",
"the",
"outputs",
"in",
"the",
"datastore",
"and",
"the",
"ones",
"in",
"the",
"database",
".",
"Also",
"update",
"the",
"datastore",
"size",
"in",
"the",
"job",
"table",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L299-L312 |
gem/oq-engine | openquake/server/db/actions.py | finish | def finish(db, job_id, status):
"""
Set the job columns `is_running`, `status`, and `stop_time`.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
ID of the current job
:param status:
a string such as 'successful' or 'failed'
"""
db('UPDATE job SET ?D WHERE id=?x',
dict(is_running=False, status=status, stop_time=datetime.utcnow()),
job_id) | python | def finish(db, job_id, status):
db('UPDATE job SET ?D WHERE id=?x',
dict(is_running=False, status=status, stop_time=datetime.utcnow()),
job_id) | [
"def",
"finish",
"(",
"db",
",",
"job_id",
",",
"status",
")",
":",
"db",
"(",
"'UPDATE job SET ?D WHERE id=?x'",
",",
"dict",
"(",
"is_running",
"=",
"False",
",",
"status",
"=",
"status",
",",
"stop_time",
"=",
"datetime",
".",
"utcnow",
"(",
")",
")",
",",
"job_id",
")"
]
| Set the job columns `is_running`, `status`, and `stop_time`.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
ID of the current job
:param status:
a string such as 'successful' or 'failed' | [
"Set",
"the",
"job",
"columns",
"is_running",
"status",
"and",
"stop_time",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L315-L328 |
gem/oq-engine | openquake/server/db/actions.py | del_calc | def del_calc(db, job_id, user):
"""
Delete a calculation and all associated outputs, if possible.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: job ID, can be an integer or a string
:param user: username
:returns: None if everything went fine or an error message
"""
job_id = int(job_id)
dependent = db(
'SELECT id FROM job WHERE hazard_calculation_id=?x', job_id)
if dependent:
return {"error": 'Cannot delete calculation %d: there '
'are calculations '
'dependent from it: %s' % (job_id, [j.id for j in dependent])}
try:
owner, path = db('SELECT user_name, ds_calc_dir FROM job WHERE id=?x',
job_id, one=True)
except NotFound:
return {"error": 'Cannot delete calculation %d:'
' ID does not exist' % job_id}
deleted = db('DELETE FROM job WHERE id=?x AND user_name=?x',
job_id, user).rowcount
if not deleted:
return {"error": 'Cannot delete calculation %d: it belongs to '
'%s and you are %s' % (job_id, owner, user)}
# try to delete datastore and associated file
# path has typically the form /home/user/oqdata/calc_XXX
fname = path + ".hdf5"
try:
os.remove(fname)
except OSError as exc: # permission error
return {"error": 'Could not remove %s: %s' % (fname, exc)}
return {"success": fname} | python | def del_calc(db, job_id, user):
job_id = int(job_id)
dependent = db(
'SELECT id FROM job WHERE hazard_calculation_id=?x', job_id)
if dependent:
return {"error": 'Cannot delete calculation %d: there '
'are calculations '
'dependent from it: %s' % (job_id, [j.id for j in dependent])}
try:
owner, path = db('SELECT user_name, ds_calc_dir FROM job WHERE id=?x',
job_id, one=True)
except NotFound:
return {"error": 'Cannot delete calculation %d:'
' ID does not exist' % job_id}
deleted = db('DELETE FROM job WHERE id=?x AND user_name=?x',
job_id, user).rowcount
if not deleted:
return {"error": 'Cannot delete calculation %d: it belongs to '
'%s and you are %s' % (job_id, owner, user)}
fname = path + ".hdf5"
try:
os.remove(fname)
except OSError as exc:
return {"error": 'Could not remove %s: %s' % (fname, exc)}
return {"success": fname} | [
"def",
"del_calc",
"(",
"db",
",",
"job_id",
",",
"user",
")",
":",
"job_id",
"=",
"int",
"(",
"job_id",
")",
"dependent",
"=",
"db",
"(",
"'SELECT id FROM job WHERE hazard_calculation_id=?x'",
",",
"job_id",
")",
"if",
"dependent",
":",
"return",
"{",
"\"error\"",
":",
"'Cannot delete calculation %d: there '",
"'are calculations '",
"'dependent from it: %s'",
"%",
"(",
"job_id",
",",
"[",
"j",
".",
"id",
"for",
"j",
"in",
"dependent",
"]",
")",
"}",
"try",
":",
"owner",
",",
"path",
"=",
"db",
"(",
"'SELECT user_name, ds_calc_dir FROM job WHERE id=?x'",
",",
"job_id",
",",
"one",
"=",
"True",
")",
"except",
"NotFound",
":",
"return",
"{",
"\"error\"",
":",
"'Cannot delete calculation %d:'",
"' ID does not exist'",
"%",
"job_id",
"}",
"deleted",
"=",
"db",
"(",
"'DELETE FROM job WHERE id=?x AND user_name=?x'",
",",
"job_id",
",",
"user",
")",
".",
"rowcount",
"if",
"not",
"deleted",
":",
"return",
"{",
"\"error\"",
":",
"'Cannot delete calculation %d: it belongs to '",
"'%s and you are %s'",
"%",
"(",
"job_id",
",",
"owner",
",",
"user",
")",
"}",
"# try to delete datastore and associated file",
"# path has typically the form /home/user/oqdata/calc_XXX",
"fname",
"=",
"path",
"+",
"\".hdf5\"",
"try",
":",
"os",
".",
"remove",
"(",
"fname",
")",
"except",
"OSError",
"as",
"exc",
":",
"# permission error",
"return",
"{",
"\"error\"",
":",
"'Could not remove %s: %s'",
"%",
"(",
"fname",
",",
"exc",
")",
"}",
"return",
"{",
"\"success\"",
":",
"fname",
"}"
]
| Delete a calculation and all associated outputs, if possible.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: job ID, can be an integer or a string
:param user: username
:returns: None if everything went fine or an error message | [
"Delete",
"a",
"calculation",
"and",
"all",
"associated",
"outputs",
"if",
"possible",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L331-L367 |
gem/oq-engine | openquake/server/db/actions.py | log | def log(db, job_id, timestamp, level, process, message):
"""
Write a log record in the database.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
a job ID
:param timestamp:
timestamp to store in the log record
:param level:
logging level to store in the log record
:param process:
process ID to store in the log record
:param message:
message to store in the log record
"""
db('INSERT INTO log (job_id, timestamp, level, process, message) '
'VALUES (?X)', (job_id, timestamp, level, process, message)) | python | def log(db, job_id, timestamp, level, process, message):
db('INSERT INTO log (job_id, timestamp, level, process, message) '
'VALUES (?X)', (job_id, timestamp, level, process, message)) | [
"def",
"log",
"(",
"db",
",",
"job_id",
",",
"timestamp",
",",
"level",
",",
"process",
",",
"message",
")",
":",
"db",
"(",
"'INSERT INTO log (job_id, timestamp, level, process, message) '",
"'VALUES (?X)'",
",",
"(",
"job_id",
",",
"timestamp",
",",
"level",
",",
"process",
",",
"message",
")",
")"
]
| Write a log record in the database.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
a job ID
:param timestamp:
timestamp to store in the log record
:param level:
logging level to store in the log record
:param process:
process ID to store in the log record
:param message:
message to store in the log record | [
"Write",
"a",
"log",
"record",
"in",
"the",
"database",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L370-L388 |
gem/oq-engine | openquake/server/db/actions.py | get_log | def get_log(db, job_id):
"""
Extract the logs as a big string
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: a job ID
"""
logs = db('SELECT * FROM log WHERE job_id=?x ORDER BY id', job_id)
out = []
for log in logs:
time = str(log.timestamp)[:-4] # strip decimals
out.append('[%s #%d %s] %s' % (time, job_id, log.level, log.message))
return out | python | def get_log(db, job_id):
logs = db('SELECT * FROM log WHERE job_id=?x ORDER BY id', job_id)
out = []
for log in logs:
time = str(log.timestamp)[:-4]
out.append('[%s
return out | [
"def",
"get_log",
"(",
"db",
",",
"job_id",
")",
":",
"logs",
"=",
"db",
"(",
"'SELECT * FROM log WHERE job_id=?x ORDER BY id'",
",",
"job_id",
")",
"out",
"=",
"[",
"]",
"for",
"log",
"in",
"logs",
":",
"time",
"=",
"str",
"(",
"log",
".",
"timestamp",
")",
"[",
":",
"-",
"4",
"]",
"# strip decimals",
"out",
".",
"append",
"(",
"'[%s #%d %s] %s'",
"%",
"(",
"time",
",",
"job_id",
",",
"log",
".",
"level",
",",
"log",
".",
"message",
")",
")",
"return",
"out"
]
| Extract the logs as a big string
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: a job ID | [
"Extract",
"the",
"logs",
"as",
"a",
"big",
"string"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L391-L403 |
gem/oq-engine | openquake/server/db/actions.py | get_output | def get_output(db, output_id):
"""
:param db: a :class:`openquake.server.dbapi.Db` instance
:param output_id: ID of an Output object
:returns: (ds_key, calc_id, dirname)
"""
out = db('SELECT output.*, ds_calc_dir FROM output, job '
'WHERE oq_job_id=job.id AND output.id=?x', output_id, one=True)
return out.ds_key, out.oq_job_id, os.path.dirname(out.ds_calc_dir) | python | def get_output(db, output_id):
out = db('SELECT output.*, ds_calc_dir FROM output, job '
'WHERE oq_job_id=job.id AND output.id=?x', output_id, one=True)
return out.ds_key, out.oq_job_id, os.path.dirname(out.ds_calc_dir) | [
"def",
"get_output",
"(",
"db",
",",
"output_id",
")",
":",
"out",
"=",
"db",
"(",
"'SELECT output.*, ds_calc_dir FROM output, job '",
"'WHERE oq_job_id=job.id AND output.id=?x'",
",",
"output_id",
",",
"one",
"=",
"True",
")",
"return",
"out",
".",
"ds_key",
",",
"out",
".",
"oq_job_id",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"out",
".",
"ds_calc_dir",
")"
]
| :param db: a :class:`openquake.server.dbapi.Db` instance
:param output_id: ID of an Output object
:returns: (ds_key, calc_id, dirname) | [
":",
"param",
"db",
":",
"a",
":",
"class",
":",
"openquake",
".",
"server",
".",
"dbapi",
".",
"Db",
"instance",
":",
"param",
"output_id",
":",
"ID",
"of",
"an",
"Output",
"object",
":",
"returns",
":",
"(",
"ds_key",
"calc_id",
"dirname",
")"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L406-L414 |
gem/oq-engine | openquake/server/db/actions.py | save_performance | def save_performance(db, job_id, records):
"""
Save in the database the performance information about the given job.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: a job ID
:param records: a list of performance records
"""
# NB: rec['counts'] is a numpy.uint64 which is not automatically converted
# into an int in Ubuntu 12.04, so we convert it manually below
rows = [(job_id, rec['operation'], rec['time_sec'], rec['memory_mb'],
int(rec['counts'])) for rec in records]
db.insert('performance',
'job_id operation time_sec memory_mb counts'.split(), rows) | python | def save_performance(db, job_id, records):
rows = [(job_id, rec['operation'], rec['time_sec'], rec['memory_mb'],
int(rec['counts'])) for rec in records]
db.insert('performance',
'job_id operation time_sec memory_mb counts'.split(), rows) | [
"def",
"save_performance",
"(",
"db",
",",
"job_id",
",",
"records",
")",
":",
"# NB: rec['counts'] is a numpy.uint64 which is not automatically converted",
"# into an int in Ubuntu 12.04, so we convert it manually below",
"rows",
"=",
"[",
"(",
"job_id",
",",
"rec",
"[",
"'operation'",
"]",
",",
"rec",
"[",
"'time_sec'",
"]",
",",
"rec",
"[",
"'memory_mb'",
"]",
",",
"int",
"(",
"rec",
"[",
"'counts'",
"]",
")",
")",
"for",
"rec",
"in",
"records",
"]",
"db",
".",
"insert",
"(",
"'performance'",
",",
"'job_id operation time_sec memory_mb counts'",
".",
"split",
"(",
")",
",",
"rows",
")"
]
| Save in the database the performance information about the given job.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: a job ID
:param records: a list of performance records | [
"Save",
"in",
"the",
"database",
"the",
"performance",
"information",
"about",
"the",
"given",
"job",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L417-L430 |
gem/oq-engine | openquake/server/db/actions.py | calc_info | def calc_info(db, calc_id):
"""
:param db: a :class:`openquake.server.dbapi.Db` instance
:param calc_id: calculation ID
:returns: dictionary of info about the given calculation
"""
job = db('SELECT * FROM job WHERE id=?x', calc_id, one=True)
response_data = {}
response_data['user_name'] = job.user_name
response_data['status'] = job.status
response_data['start_time'] = str(job.start_time)
response_data['stop_time'] = str(job.stop_time)
response_data['is_running'] = job.is_running
return response_data | python | def calc_info(db, calc_id):
job = db('SELECT * FROM job WHERE id=?x', calc_id, one=True)
response_data = {}
response_data['user_name'] = job.user_name
response_data['status'] = job.status
response_data['start_time'] = str(job.start_time)
response_data['stop_time'] = str(job.stop_time)
response_data['is_running'] = job.is_running
return response_data | [
"def",
"calc_info",
"(",
"db",
",",
"calc_id",
")",
":",
"job",
"=",
"db",
"(",
"'SELECT * FROM job WHERE id=?x'",
",",
"calc_id",
",",
"one",
"=",
"True",
")",
"response_data",
"=",
"{",
"}",
"response_data",
"[",
"'user_name'",
"]",
"=",
"job",
".",
"user_name",
"response_data",
"[",
"'status'",
"]",
"=",
"job",
".",
"status",
"response_data",
"[",
"'start_time'",
"]",
"=",
"str",
"(",
"job",
".",
"start_time",
")",
"response_data",
"[",
"'stop_time'",
"]",
"=",
"str",
"(",
"job",
".",
"stop_time",
")",
"response_data",
"[",
"'is_running'",
"]",
"=",
"job",
".",
"is_running",
"return",
"response_data"
]
| :param db: a :class:`openquake.server.dbapi.Db` instance
:param calc_id: calculation ID
:returns: dictionary of info about the given calculation | [
":",
"param",
"db",
":",
"a",
":",
"class",
":",
"openquake",
".",
"server",
".",
"dbapi",
".",
"Db",
"instance",
":",
"param",
"calc_id",
":",
"calculation",
"ID",
":",
"returns",
":",
"dictionary",
"of",
"info",
"about",
"the",
"given",
"calculation"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L492-L505 |
gem/oq-engine | openquake/server/db/actions.py | get_calcs | def get_calcs(db, request_get_dict, allowed_users, user_acl_on=False, id=None):
"""
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param request_get_dict:
a dictionary
:param allowed_users:
a list of users
:param user_acl_on:
if True, returns only the calculations owned by the user or the group
:param id:
if given, extract only the specified calculation
:returns:
list of tuples (job_id, user_name, job_status, calculation_mode,
job_is_running, job_description)
"""
# helper to get job+calculation data from the oq-engine database
filterdict = {}
if id is not None:
filterdict['id'] = id
if 'calculation_mode' in request_get_dict:
filterdict['calculation_mode'] = request_get_dict.get(
'calculation_mode')
if 'is_running' in request_get_dict:
is_running = request_get_dict.get('is_running')
filterdict['is_running'] = valid.boolean(is_running)
if 'relevant' in request_get_dict:
relevant = request_get_dict.get('relevant')
filterdict['relevant'] = valid.boolean(relevant)
if 'limit' in request_get_dict:
limit = int(request_get_dict.get('limit'))
else:
limit = 100
if 'start_time' in request_get_dict:
# assume an ISO date string
time_filter = "start_time >= '%s'" % request_get_dict.get('start_time')
else:
time_filter = 1
if user_acl_on:
users_filter = "user_name IN (?X)"
else:
users_filter = 1
jobs = db('SELECT * FROM job WHERE ?A AND %s AND %s'
' ORDER BY id DESC LIMIT %d'
% (users_filter, time_filter, limit), filterdict, allowed_users)
return [(job.id, job.user_name, job.status, job.calculation_mode,
job.is_running, job.description, job.pid,
job.hazard_calculation_id, job.size_mb) for job in jobs] | python | def get_calcs(db, request_get_dict, allowed_users, user_acl_on=False, id=None):
filterdict = {}
if id is not None:
filterdict['id'] = id
if 'calculation_mode' in request_get_dict:
filterdict['calculation_mode'] = request_get_dict.get(
'calculation_mode')
if 'is_running' in request_get_dict:
is_running = request_get_dict.get('is_running')
filterdict['is_running'] = valid.boolean(is_running)
if 'relevant' in request_get_dict:
relevant = request_get_dict.get('relevant')
filterdict['relevant'] = valid.boolean(relevant)
if 'limit' in request_get_dict:
limit = int(request_get_dict.get('limit'))
else:
limit = 100
if 'start_time' in request_get_dict:
time_filter = "start_time >= '%s'" % request_get_dict.get('start_time')
else:
time_filter = 1
if user_acl_on:
users_filter = "user_name IN (?X)"
else:
users_filter = 1
jobs = db('SELECT * FROM job WHERE ?A AND %s AND %s'
' ORDER BY id DESC LIMIT %d'
% (users_filter, time_filter, limit), filterdict, allowed_users)
return [(job.id, job.user_name, job.status, job.calculation_mode,
job.is_running, job.description, job.pid,
job.hazard_calculation_id, job.size_mb) for job in jobs] | [
"def",
"get_calcs",
"(",
"db",
",",
"request_get_dict",
",",
"allowed_users",
",",
"user_acl_on",
"=",
"False",
",",
"id",
"=",
"None",
")",
":",
"# helper to get job+calculation data from the oq-engine database",
"filterdict",
"=",
"{",
"}",
"if",
"id",
"is",
"not",
"None",
":",
"filterdict",
"[",
"'id'",
"]",
"=",
"id",
"if",
"'calculation_mode'",
"in",
"request_get_dict",
":",
"filterdict",
"[",
"'calculation_mode'",
"]",
"=",
"request_get_dict",
".",
"get",
"(",
"'calculation_mode'",
")",
"if",
"'is_running'",
"in",
"request_get_dict",
":",
"is_running",
"=",
"request_get_dict",
".",
"get",
"(",
"'is_running'",
")",
"filterdict",
"[",
"'is_running'",
"]",
"=",
"valid",
".",
"boolean",
"(",
"is_running",
")",
"if",
"'relevant'",
"in",
"request_get_dict",
":",
"relevant",
"=",
"request_get_dict",
".",
"get",
"(",
"'relevant'",
")",
"filterdict",
"[",
"'relevant'",
"]",
"=",
"valid",
".",
"boolean",
"(",
"relevant",
")",
"if",
"'limit'",
"in",
"request_get_dict",
":",
"limit",
"=",
"int",
"(",
"request_get_dict",
".",
"get",
"(",
"'limit'",
")",
")",
"else",
":",
"limit",
"=",
"100",
"if",
"'start_time'",
"in",
"request_get_dict",
":",
"# assume an ISO date string",
"time_filter",
"=",
"\"start_time >= '%s'\"",
"%",
"request_get_dict",
".",
"get",
"(",
"'start_time'",
")",
"else",
":",
"time_filter",
"=",
"1",
"if",
"user_acl_on",
":",
"users_filter",
"=",
"\"user_name IN (?X)\"",
"else",
":",
"users_filter",
"=",
"1",
"jobs",
"=",
"db",
"(",
"'SELECT * FROM job WHERE ?A AND %s AND %s'",
"' ORDER BY id DESC LIMIT %d'",
"%",
"(",
"users_filter",
",",
"time_filter",
",",
"limit",
")",
",",
"filterdict",
",",
"allowed_users",
")",
"return",
"[",
"(",
"job",
".",
"id",
",",
"job",
".",
"user_name",
",",
"job",
".",
"status",
",",
"job",
".",
"calculation_mode",
",",
"job",
".",
"is_running",
",",
"job",
".",
"description",
",",
"job",
".",
"pid",
",",
"job",
".",
"hazard_calculation_id",
",",
"job",
".",
"size_mb",
")",
"for",
"job",
"in",
"jobs",
"]"
]
| :param db:
a :class:`openquake.server.dbapi.Db` instance
:param request_get_dict:
a dictionary
:param allowed_users:
a list of users
:param user_acl_on:
if True, returns only the calculations owned by the user or the group
:param id:
if given, extract only the specified calculation
:returns:
list of tuples (job_id, user_name, job_status, calculation_mode,
job_is_running, job_description) | [
":",
"param",
"db",
":",
"a",
":",
"class",
":",
"openquake",
".",
"server",
".",
"dbapi",
".",
"Db",
"instance",
":",
"param",
"request_get_dict",
":",
"a",
"dictionary",
":",
"param",
"allowed_users",
":",
"a",
"list",
"of",
"users",
":",
"param",
"user_acl_on",
":",
"if",
"True",
"returns",
"only",
"the",
"calculations",
"owned",
"by",
"the",
"user",
"or",
"the",
"group",
":",
"param",
"id",
":",
"if",
"given",
"extract",
"only",
"the",
"specified",
"calculation",
":",
"returns",
":",
"list",
"of",
"tuples",
"(",
"job_id",
"user_name",
"job_status",
"calculation_mode",
"job_is_running",
"job_description",
")"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L508-L563 |
gem/oq-engine | openquake/server/db/actions.py | get_log_slice | def get_log_slice(db, job_id, start, stop):
"""
Get a slice of the calculation log as a JSON list of rows
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
a job ID
:param start:
start of the slice
:param stop:
end of the slice (the last element is excluded)
"""
start = int(start)
stop = int(stop)
limit = -1 if stop == 0 else stop - start
logs = db('SELECT * FROM log WHERE job_id=?x '
'ORDER BY id LIMIT ?s OFFSET ?s',
job_id, limit, start)
# NB: .isoformat() returns a string like '2016-08-29T15:42:34.984756'
# we consider only the first 22 characters, i.e. '2016-08-29T15:42:34.98'
return [[log.timestamp.isoformat()[:22], log.level,
log.process, log.message] for log in logs] | python | def get_log_slice(db, job_id, start, stop):
start = int(start)
stop = int(stop)
limit = -1 if stop == 0 else stop - start
logs = db('SELECT * FROM log WHERE job_id=?x '
'ORDER BY id LIMIT ?s OFFSET ?s',
job_id, limit, start)
return [[log.timestamp.isoformat()[:22], log.level,
log.process, log.message] for log in logs] | [
"def",
"get_log_slice",
"(",
"db",
",",
"job_id",
",",
"start",
",",
"stop",
")",
":",
"start",
"=",
"int",
"(",
"start",
")",
"stop",
"=",
"int",
"(",
"stop",
")",
"limit",
"=",
"-",
"1",
"if",
"stop",
"==",
"0",
"else",
"stop",
"-",
"start",
"logs",
"=",
"db",
"(",
"'SELECT * FROM log WHERE job_id=?x '",
"'ORDER BY id LIMIT ?s OFFSET ?s'",
",",
"job_id",
",",
"limit",
",",
"start",
")",
"# NB: .isoformat() returns a string like '2016-08-29T15:42:34.984756'",
"# we consider only the first 22 characters, i.e. '2016-08-29T15:42:34.98'",
"return",
"[",
"[",
"log",
".",
"timestamp",
".",
"isoformat",
"(",
")",
"[",
":",
"22",
"]",
",",
"log",
".",
"level",
",",
"log",
".",
"process",
",",
"log",
".",
"message",
"]",
"for",
"log",
"in",
"logs",
"]"
]
| Get a slice of the calculation log as a JSON list of rows
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
a job ID
:param start:
start of the slice
:param stop:
end of the slice (the last element is excluded) | [
"Get",
"a",
"slice",
"of",
"the",
"calculation",
"log",
"as",
"a",
"JSON",
"list",
"of",
"rows"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L588-L610 |
gem/oq-engine | openquake/server/db/actions.py | get_traceback | def get_traceback(db, job_id):
"""
Return the traceback of the given calculation as a list of lines.
The list is empty if the calculation was successful.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
a job ID
"""
# strange: understand why the filter returns two lines or zero lines
log = db("SELECT * FROM log WHERE job_id=?x AND level='CRITICAL'",
job_id)
if not log:
return []
response_data = log[-1].message.splitlines()
return response_data | python | def get_traceback(db, job_id):
log = db("SELECT * FROM log WHERE job_id=?x AND level='CRITICAL'",
job_id)
if not log:
return []
response_data = log[-1].message.splitlines()
return response_data | [
"def",
"get_traceback",
"(",
"db",
",",
"job_id",
")",
":",
"# strange: understand why the filter returns two lines or zero lines",
"log",
"=",
"db",
"(",
"\"SELECT * FROM log WHERE job_id=?x AND level='CRITICAL'\"",
",",
"job_id",
")",
"if",
"not",
"log",
":",
"return",
"[",
"]",
"response_data",
"=",
"log",
"[",
"-",
"1",
"]",
".",
"message",
".",
"splitlines",
"(",
")",
"return",
"response_data"
]
| Return the traceback of the given calculation as a list of lines.
The list is empty if the calculation was successful.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
a job ID | [
"Return",
"the",
"traceback",
"of",
"the",
"given",
"calculation",
"as",
"a",
"list",
"of",
"lines",
".",
"The",
"list",
"is",
"empty",
"if",
"the",
"calculation",
"was",
"successful",
"."
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L626-L642 |
gem/oq-engine | openquake/server/db/actions.py | get_result | def get_result(db, result_id):
"""
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param result_id:
a result ID
:returns: (job_id, job_status, datadir, datastore_key)
"""
job = db('SELECT job.*, ds_key FROM job, output WHERE '
'oq_job_id=job.id AND output.id=?x', result_id, one=True)
return (job.id, job.status, job.user_name,
os.path.dirname(job.ds_calc_dir), job.ds_key) | python | def get_result(db, result_id):
job = db('SELECT job.*, ds_key FROM job, output WHERE '
'oq_job_id=job.id AND output.id=?x', result_id, one=True)
return (job.id, job.status, job.user_name,
os.path.dirname(job.ds_calc_dir), job.ds_key) | [
"def",
"get_result",
"(",
"db",
",",
"result_id",
")",
":",
"job",
"=",
"db",
"(",
"'SELECT job.*, ds_key FROM job, output WHERE '",
"'oq_job_id=job.id AND output.id=?x'",
",",
"result_id",
",",
"one",
"=",
"True",
")",
"return",
"(",
"job",
".",
"id",
",",
"job",
".",
"status",
",",
"job",
".",
"user_name",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"job",
".",
"ds_calc_dir",
")",
",",
"job",
".",
"ds_key",
")"
]
| :param db:
a :class:`openquake.server.dbapi.Db` instance
:param result_id:
a result ID
:returns: (job_id, job_status, datadir, datastore_key) | [
":",
"param",
"db",
":",
"a",
":",
"class",
":",
"openquake",
".",
"server",
".",
"dbapi",
".",
"Db",
"instance",
":",
"param",
"result_id",
":",
"a",
"result",
"ID",
":",
"returns",
":",
"(",
"job_id",
"job_status",
"datadir",
"datastore_key",
")"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L645-L656 |
gem/oq-engine | openquake/server/db/actions.py | get_results | def get_results(db, job_id):
"""
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
a job ID
:returns: (datadir, datastore_keys)
"""
ds_calc_dir = db('SELECT ds_calc_dir FROM job WHERE id=?x', job_id,
scalar=True)
datadir = os.path.dirname(ds_calc_dir)
return datadir, [output.ds_key for output in get_outputs(db, job_id)] | python | def get_results(db, job_id):
ds_calc_dir = db('SELECT ds_calc_dir FROM job WHERE id=?x', job_id,
scalar=True)
datadir = os.path.dirname(ds_calc_dir)
return datadir, [output.ds_key for output in get_outputs(db, job_id)] | [
"def",
"get_results",
"(",
"db",
",",
"job_id",
")",
":",
"ds_calc_dir",
"=",
"db",
"(",
"'SELECT ds_calc_dir FROM job WHERE id=?x'",
",",
"job_id",
",",
"scalar",
"=",
"True",
")",
"datadir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"ds_calc_dir",
")",
"return",
"datadir",
",",
"[",
"output",
".",
"ds_key",
"for",
"output",
"in",
"get_outputs",
"(",
"db",
",",
"job_id",
")",
"]"
]
| :param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
a job ID
:returns: (datadir, datastore_keys) | [
":",
"param",
"db",
":",
"a",
":",
"class",
":",
"openquake",
".",
"server",
".",
"dbapi",
".",
"Db",
"instance",
":",
"param",
"job_id",
":",
"a",
"job",
"ID",
":",
"returns",
":",
"(",
"datadir",
"datastore_keys",
")"
]
| train | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/server/db/actions.py#L659-L670 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.