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/calculators/export/hazard.py
export_ruptures_csv
def export_ruptures_csv(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ oq = dstore['oqparam'] if 'scenario' in oq.calculation_mode: return [] dest = dstore.export_path('ruptures.csv') header = ('rupid multiplicity ...
python
def export_ruptures_csv(ekey, dstore): oq = dstore['oqparam'] if 'scenario' in oq.calculation_mode: return [] dest = dstore.export_path('ruptures.csv') header = ('rupid multiplicity mag centroid_lon centroid_lat ' 'centroid_depth trt strike dip rake boundary').split() rows...
[ "def", "export_ruptures_csv", "(", "ekey", ",", "dstore", ")", ":", "oq", "=", "dstore", "[", "'oqparam'", "]", "if", "'scenario'", "in", "oq", ".", "calculation_mode", ":", "return", "[", "]", "dest", "=", "dstore", ".", "export_path", "(", "'ruptures.csv...
:param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object
[ ":", "param", "ekey", ":", "export", "key", "i", ".", "e", ".", "a", "pair", "(", "datastore", "key", "fmt", ")", ":", "param", "dstore", ":", "datastore", "object" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L81-L106
gem/oq-engine
openquake/calculators/export/hazard.py
export_hmaps_csv
def export_hmaps_csv(key, dest, sitemesh, array, comment): """ Export the hazard maps of the given realization into CSV. :param key: output_type and export_type :param dest: name of the exported file :param sitemesh: site collection :param array: a composite array of dtype hmap_dt :param co...
python
def export_hmaps_csv(key, dest, sitemesh, array, comment): curves = util.compose_arrays(sitemesh, array) writers.write_csv(dest, curves, comment=comment) return [dest]
[ "def", "export_hmaps_csv", "(", "key", ",", "dest", ",", "sitemesh", ",", "array", ",", "comment", ")", ":", "curves", "=", "util", ".", "compose_arrays", "(", "sitemesh", ",", "array", ")", "writers", ".", "write_csv", "(", "dest", ",", "curves", ",", ...
Export the hazard maps of the given realization into CSV. :param key: output_type and export_type :param dest: name of the exported file :param sitemesh: site collection :param array: a composite array of dtype hmap_dt :param comment: comment to use as header of the exported CSV file
[ "Export", "the", "hazard", "maps", "of", "the", "given", "realization", "into", "CSV", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L223-L235
gem/oq-engine
openquake/calculators/export/hazard.py
add_imt
def add_imt(fname, imt): """ >>> add_imt('/path/to/hcurve_23.csv', 'SA(0.1)') '/path/to/hcurve-SA(0.1)_23.csv' """ name = os.path.basename(fname) newname = re.sub(r'(_\d+\.)', '-%s\\1' % imt, name) return os.path.join(os.path.dirname(fname), newname)
python
def add_imt(fname, imt): name = os.path.basename(fname) newname = re.sub(r'(_\d+\.)', '-%s\\1' % imt, name) return os.path.join(os.path.dirname(fname), newname)
[ "def", "add_imt", "(", "fname", ",", "imt", ")", ":", "name", "=", "os", ".", "path", ".", "basename", "(", "fname", ")", "newname", "=", "re", ".", "sub", "(", "r'(_\\d+\\.)'", ",", "'-%s\\\\1'", "%", "imt", ",", "name", ")", "return", "os", ".", ...
>>> add_imt('/path/to/hcurve_23.csv', 'SA(0.1)') '/path/to/hcurve-SA(0.1)_23.csv'
[ ">>>", "add_imt", "(", "/", "path", "/", "to", "/", "hcurve_23", ".", "csv", "SA", "(", "0", ".", "1", ")", ")", "/", "path", "/", "to", "/", "hcurve", "-", "SA", "(", "0", ".", "1", ")", "_23", ".", "csv" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L238-L245
gem/oq-engine
openquake/calculators/export/hazard.py
export_hcurves_by_imt_csv
def export_hcurves_by_imt_csv( key, kind, rlzs_assoc, fname, sitecol, array, oq, checksum): """ Export the curves of the given realization into CSV. :param key: output_type and export_type :param kind: a string with the kind of output (realization or statistics) :param rlzs_assoc: a :class:...
python
def export_hcurves_by_imt_csv( key, kind, rlzs_assoc, fname, sitecol, array, oq, checksum): nsites = len(sitecol) fnames = [] for imt, imls in oq.imtls.items(): slc = oq.imtls(imt) dest = add_imt(fname, imt) lst = [('lon', F32), ('lat', F32), ('depth', F32)] for ...
[ "def", "export_hcurves_by_imt_csv", "(", "key", ",", "kind", ",", "rlzs_assoc", ",", "fname", ",", "sitecol", ",", "array", ",", "oq", ",", "checksum", ")", ":", "nsites", "=", "len", "(", "sitecol", ")", "fnames", "=", "[", "]", "for", "imt", ",", "...
Export the curves of the given realization into CSV. :param key: output_type and export_type :param kind: a string with the kind of output (realization or statistics) :param rlzs_assoc: a :class:`openquake.commonlib.source.RlzsAssoc` instance :param fname: name of the exported file :param sitecol: ...
[ "Export", "the", "curves", "of", "the", "given", "realization", "into", "CSV", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L248-L277
gem/oq-engine
openquake/calculators/export/hazard.py
hazard_curve_name
def hazard_curve_name(dstore, ekey, kind, rlzs_assoc): """ :param calc_id: the calculation ID :param ekey: the export key :param kind: the kind of key :param rlzs_assoc: a RlzsAssoc instance """ key, fmt = ekey prefix = {'hcurves': 'hazard_curve', 'hmaps': 'hazard_map', 'uh...
python
def hazard_curve_name(dstore, ekey, kind, rlzs_assoc): key, fmt = ekey prefix = {'hcurves': 'hazard_curve', 'hmaps': 'hazard_map', 'uhs': 'hazard_uhs'}[key] if kind.startswith('quantile-'): fname = dstore.build_fname('quantile_' + prefix[7:], kind[9:], fmt) else: fna...
[ "def", "hazard_curve_name", "(", "dstore", ",", "ekey", ",", "kind", ",", "rlzs_assoc", ")", ":", "key", ",", "fmt", "=", "ekey", "prefix", "=", "{", "'hcurves'", ":", "'hazard_curve'", ",", "'hmaps'", ":", "'hazard_map'", ",", "'uhs'", ":", "'hazard_uhs'"...
:param calc_id: the calculation ID :param ekey: the export key :param kind: the kind of key :param rlzs_assoc: a RlzsAssoc instance
[ ":", "param", "calc_id", ":", "the", "calculation", "ID", ":", "param", "ekey", ":", "the", "export", "key", ":", "param", "kind", ":", "the", "kind", "of", "key", ":", "param", "rlzs_assoc", ":", "a", "RlzsAssoc", "instance" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L280-L294
gem/oq-engine
openquake/calculators/export/hazard.py
get_kkf
def get_kkf(ekey): """ :param ekey: export key, for instance ('uhs/rlz-1', 'xml') :returns: key, kind and fmt from the export key, i.e. 'uhs', 'rlz-1', 'xml' """ key, fmt = ekey if '/' in key: key, kind = key.split('/', 1) else: kind = '' return key, kind, fmt
python
def get_kkf(ekey): key, fmt = ekey if '/' in key: key, kind = key.split('/', 1) else: kind = '' return key, kind, fmt
[ "def", "get_kkf", "(", "ekey", ")", ":", "key", ",", "fmt", "=", "ekey", "if", "'/'", "in", "key", ":", "key", ",", "kind", "=", "key", ".", "split", "(", "'/'", ",", "1", ")", "else", ":", "kind", "=", "''", "return", "key", ",", "kind", ","...
:param ekey: export key, for instance ('uhs/rlz-1', 'xml') :returns: key, kind and fmt from the export key, i.e. 'uhs', 'rlz-1', 'xml'
[ ":", "param", "ekey", ":", "export", "key", "for", "instance", "(", "uhs", "/", "rlz", "-", "1", "xml", ")", ":", "returns", ":", "key", "kind", "and", "fmt", "from", "the", "export", "key", "i", ".", "e", ".", "uhs", "rlz", "-", "1", "xml" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L319-L329
gem/oq-engine
openquake/calculators/export/hazard.py
export_hcurves_csv
def export_hcurves_csv(ekey, dstore): """ Exports the hazard curves into several .csv files :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ oq = dstore['oqparam'] info = get_info(dstore) rlzs_assoc = dstore['csm_info'].get_rlzs_assoc() R...
python
def export_hcurves_csv(ekey, dstore): oq = dstore['oqparam'] info = get_info(dstore) rlzs_assoc = dstore['csm_info'].get_rlzs_assoc() R = len(rlzs_assoc.realizations) sitecol = dstore['sitecol'] sitemesh = get_mesh(sitecol) key, kind, fmt = get_kkf(ekey) fnames = [] checksum = d...
[ "def", "export_hcurves_csv", "(", "ekey", ",", "dstore", ")", ":", "oq", "=", "dstore", "[", "'oqparam'", "]", "info", "=", "get_info", "(", "dstore", ")", "rlzs_assoc", "=", "dstore", "[", "'csm_info'", "]", ".", "get_rlzs_assoc", "(", ")", "R", "=", ...
Exports the hazard curves into several .csv files :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object
[ "Exports", "the", "hazard", "curves", "into", "several", ".", "csv", "files" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L333-L373
gem/oq-engine
openquake/calculators/export/hazard.py
get_metadata
def get_metadata(realizations, kind): """ :param list realizations: realization objects :param str kind: kind of data, i.e. a key in the datastore :returns: a dictionary with smlt_path, gsimlt_path, statistics, quantile_value """ metadata = {} if kind.startswith('rlz-...
python
def get_metadata(realizations, kind): metadata = {} if kind.startswith('rlz-'): rlz = realizations[int(kind[4:])] metadata['smlt_path'] = '_'.join(rlz.sm_lt_path) metadata['gsimlt_path'] = rlz.gsim_rlz.uid elif kind.startswith('quantile-'): metadata['statistics'] = 'quan...
[ "def", "get_metadata", "(", "realizations", ",", "kind", ")", ":", "metadata", "=", "{", "}", "if", "kind", ".", "startswith", "(", "'rlz-'", ")", ":", "rlz", "=", "realizations", "[", "int", "(", "kind", "[", "4", ":", "]", ")", "]", "metadata", "...
:param list realizations: realization objects :param str kind: kind of data, i.e. a key in the datastore :returns: a dictionary with smlt_path, gsimlt_path, statistics, quantile_value
[ ":", "param", "list", "realizations", ":", "realization", "objects", ":", "param", "str", "kind", ":", "kind", "of", "data", "i", ".", "e", ".", "a", "key", "in", "the", "datastore", ":", "returns", ":", "a", "dictionary", "with", "smlt_path", "gsimlt_pa...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L379-L402
gem/oq-engine
openquake/calculators/export/hazard.py
export_gmf
def export_gmf(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ oq = dstore['oqparam'] if not oq.calculation_mode.startswith('scenario'): return [] sitecol = dstore['sitecol'] investigation_time = (None if oq.calcula...
python
def export_gmf(ekey, dstore): oq = dstore['oqparam'] if not oq.calculation_mode.startswith('scenario'): return [] sitecol = dstore['sitecol'] investigation_time = (None if oq.calculation_mode == 'scenario' else oq.investigation_time) fmt = ekey[-1] gmf_data...
[ "def", "export_gmf", "(", "ekey", ",", "dstore", ")", ":", "oq", "=", "dstore", "[", "'oqparam'", "]", "if", "not", "oq", ".", "calculation_mode", ".", "startswith", "(", "'scenario'", ")", ":", "return", "[", "]", "sitecol", "=", "dstore", "[", "'site...
:param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object
[ ":", "param", "ekey", ":", "export", "key", "i", ".", "e", ".", "a", "pair", "(", "datastore", "key", "fmt", ")", ":", "param", "dstore", ":", "datastore", "object" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L535-L563
gem/oq-engine
openquake/calculators/export/hazard.py
save_disagg_to_csv
def save_disagg_to_csv(metadata, matrices): """ Save disaggregation matrices to multiple .csv files. """ skip_keys = ('Mag', 'Dist', 'Lon', 'Lat', 'Eps', 'TRT') base_header = ','.join( '%s=%s' % (key, value) for key, value in metadata.items() if value is not None and key not in skip_...
python
def save_disagg_to_csv(metadata, matrices): skip_keys = ('Mag', 'Dist', 'Lon', 'Lat', 'Eps', 'TRT') base_header = ','.join( '%s=%s' % (key, value) for key, value in metadata.items() if value is not None and key not in skip_keys) for disag_tup, (poe, iml, matrix, fname) in matrices.items...
[ "def", "save_disagg_to_csv", "(", "metadata", ",", "matrices", ")", ":", "skip_keys", "=", "(", "'Mag'", ",", "'Dist'", ",", "'Lon'", ",", "'Lat'", ",", "'Eps'", ",", "'TRT'", ")", "base_header", "=", "','", ".", "join", "(", "'%s=%s'", "%", "(", "key"...
Save disaggregation matrices to multiple .csv files.
[ "Save", "disaggregation", "matrices", "to", "multiple", ".", "csv", "files", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L743-L776
gem/oq-engine
openquake/hazardlib/gsim/bradley_2013b.py
Bradley2013bChchCBD.get_mean_and_stddevs
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required #...
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): C = self.COEFFS[imt] if isinstance(imt, PGA): imt_per = 0.0 else: imt_per = imt.period sites.vs30 = np.array([250]) sites.z1pt0 = np.array([330]) ...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "# extracting dictionary of coefficients specific to required", "# intensity measure type.", "C", "=", "self", ".", "COEFFS", "[", "imt", "...
See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
[ "See", ":", "meth", ":", "superclass", "method", "<", ".", "base", ".", "GroundShakingIntensityModel", ".", "get_mean_and_stddevs", ">", "for", "spec", "of", "input", "and", "result", "values", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L63-L96
gem/oq-engine
openquake/hazardlib/gsim/bradley_2013b.py
Bradley2013bChchCBD._interp_function
def _interp_function(self, y_ip1, y_i, t_ip1, t_i, imt_per): """ Generic interpolation function used in equation 19 of 2013 report. """ return y_i + (y_ip1 - y_i) / (t_ip1 - t_i) * (imt_per - t_i)
python
def _interp_function(self, y_ip1, y_i, t_ip1, t_i, imt_per): return y_i + (y_ip1 - y_i) / (t_ip1 - t_i) * (imt_per - t_i)
[ "def", "_interp_function", "(", "self", ",", "y_ip1", ",", "y_i", ",", "t_ip1", ",", "t_i", ",", "imt_per", ")", ":", "return", "y_i", "+", "(", "y_ip1", "-", "y_i", ")", "/", "(", "t_ip1", "-", "t_i", ")", "*", "(", "imt_per", "-", "t_i", ")" ]
Generic interpolation function used in equation 19 of 2013 report.
[ "Generic", "interpolation", "function", "used", "in", "equation", "19", "of", "2013", "report", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L154-L158
gem/oq-engine
openquake/hazardlib/gsim/bradley_2013b.py
Bradley2013bChchCBD._get_SRF_tau
def _get_SRF_tau(self, imt_per): """ Table 6 and equation 19 of 2013 report. """ if imt_per < 1: srf = 0.87 elif 1 <= imt_per < 5: srf = self._interp_function(0.58, 0.87, 5, 1, imt_per) elif 5 <= imt_per <= 10: srf = 0.58 else: ...
python
def _get_SRF_tau(self, imt_per): if imt_per < 1: srf = 0.87 elif 1 <= imt_per < 5: srf = self._interp_function(0.58, 0.87, 5, 1, imt_per) elif 5 <= imt_per <= 10: srf = 0.58 else: srf = 1 return srf
[ "def", "_get_SRF_tau", "(", "self", ",", "imt_per", ")", ":", "if", "imt_per", "<", "1", ":", "srf", "=", "0.87", "elif", "1", "<=", "imt_per", "<", "5", ":", "srf", "=", "self", ".", "_interp_function", "(", "0.58", ",", "0.87", ",", "5", ",", "...
Table 6 and equation 19 of 2013 report.
[ "Table", "6", "and", "equation", "19", "of", "2013", "report", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L160-L173
gem/oq-engine
openquake/hazardlib/gsim/bradley_2013b.py
Bradley2013bChchCBD._get_SRF_phi
def _get_SRF_phi(self, imt_per): """ Table 7 and equation 19 of 2013 report. NB change in notation, 2013 report calls this term 'sigma' but it is referred to here as phi. """ if imt_per < 0.6: srf = 0.8 elif 0.6 <= imt_per < 1: srf = self._...
python
def _get_SRF_phi(self, imt_per): if imt_per < 0.6: srf = 0.8 elif 0.6 <= imt_per < 1: srf = self._interp_function(0.7, 0.8, 1, 0.6, imt_per) elif 1 <= imt_per <= 10: srf = self._interp_function(0.6, 0.7, 10, 1, imt_per) else: srf =...
[ "def", "_get_SRF_phi", "(", "self", ",", "imt_per", ")", ":", "if", "imt_per", "<", "0.6", ":", "srf", "=", "0.8", "elif", "0.6", "<=", "imt_per", "<", "1", ":", "srf", "=", "self", ".", "_interp_function", "(", "0.7", ",", "0.8", ",", "1", ",", ...
Table 7 and equation 19 of 2013 report. NB change in notation, 2013 report calls this term 'sigma' but it is referred to here as phi.
[ "Table", "7", "and", "equation", "19", "of", "2013", "report", ".", "NB", "change", "in", "notation", "2013", "report", "calls", "this", "term", "sigma", "but", "it", "is", "referred", "to", "here", "as", "phi", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L175-L190
gem/oq-engine
openquake/hazardlib/gsim/bradley_2013b.py
Bradley2013bChchCBD._get_SRF_sigma
def _get_SRF_sigma(self, imt_per): """ Table 8 and equation 19 of 2013 report. NB change in notation, 2013 report calls this term 'sigma_t' but it is referred to here as sigma. Note that Table 8 is identical to Table 7 in the 2013 report. """ if imt_per < 0.6: ...
python
def _get_SRF_sigma(self, imt_per): if imt_per < 0.6: srf = 0.8 elif 0.6 <= imt_per < 1: srf = self._interp_function(0.7, 0.8, 1, 0.6, imt_per) elif 1 <= imt_per <= 10: srf = self._interp_function(0.6, 0.7, 10, 1, imt_per) else: srf...
[ "def", "_get_SRF_sigma", "(", "self", ",", "imt_per", ")", ":", "if", "imt_per", "<", "0.6", ":", "srf", "=", "0.8", "elif", "0.6", "<=", "imt_per", "<", "1", ":", "srf", "=", "self", ".", "_interp_function", "(", "0.7", ",", "0.8", ",", "1", ",", ...
Table 8 and equation 19 of 2013 report. NB change in notation, 2013 report calls this term 'sigma_t' but it is referred to here as sigma. Note that Table 8 is identical to Table 7 in the 2013 report.
[ "Table", "8", "and", "equation", "19", "of", "2013", "report", ".", "NB", "change", "in", "notation", "2013", "report", "calls", "this", "term", "sigma_t", "but", "it", "is", "referred", "to", "here", "as", "sigma", ".", "Note", "that", "Table", "8", "...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L192-L208
gem/oq-engine
openquake/hazardlib/gsim/bradley_2013b.py
Bradley2013bChchCBD._get_dL2L
def _get_dL2L(self, imt_per): """ Table 3 and equation 19 of 2013 report. """ if imt_per < 0.18: dL2L = -0.06 elif 0.18 <= imt_per < 0.35: dL2L = self._interp_function(0.12, -0.06, 0.35, 0.18, imt_per) elif 0.35 <= imt_per <= 10: dL2L =...
python
def _get_dL2L(self, imt_per): if imt_per < 0.18: dL2L = -0.06 elif 0.18 <= imt_per < 0.35: dL2L = self._interp_function(0.12, -0.06, 0.35, 0.18, imt_per) elif 0.35 <= imt_per <= 10: dL2L = self._interp_function(0.65, 0.12, 10, 0.35, imt_per) e...
[ "def", "_get_dL2L", "(", "self", ",", "imt_per", ")", ":", "if", "imt_per", "<", "0.18", ":", "dL2L", "=", "-", "0.06", "elif", "0.18", "<=", "imt_per", "<", "0.35", ":", "dL2L", "=", "self", ".", "_interp_function", "(", "0.12", ",", "-", "0.06", ...
Table 3 and equation 19 of 2013 report.
[ "Table", "3", "and", "equation", "19", "of", "2013", "report", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L210-L223
gem/oq-engine
openquake/hazardlib/gsim/bradley_2013b.py
Bradley2013bChchCBD._get_dS2S
def _get_dS2S(self, imt_per): """ Table 4 of 2013 report """ if imt_per == 0: dS2S = 0.05 elif 0 < imt_per < 0.15: dS2S = self._interp_function(-0.15, 0.05, 0.15, 0, imt_per) elif 0.15 <= imt_per < 0.45: dS2S = self._interp_function(0.4...
python
def _get_dS2S(self, imt_per): if imt_per == 0: dS2S = 0.05 elif 0 < imt_per < 0.15: dS2S = self._interp_function(-0.15, 0.05, 0.15, 0, imt_per) elif 0.15 <= imt_per < 0.45: dS2S = self._interp_function(0.4, -0.15, 0.45, 0.15, imt_per) elif 0.4...
[ "def", "_get_dS2S", "(", "self", ",", "imt_per", ")", ":", "if", "imt_per", "==", "0", ":", "dS2S", "=", "0.05", "elif", "0", "<", "imt_per", "<", "0.15", ":", "dS2S", "=", "self", ".", "_interp_function", "(", "-", "0.15", ",", "0.05", ",", "0.15"...
Table 4 of 2013 report
[ "Table", "4", "of", "2013", "report" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L225-L244
gem/oq-engine
openquake/hazardlib/calc/filters.py
context
def context(src): """ Used to add the source_id to the error message. To be used as with context(src): operation_with(src) Typically the operation is filtering a source, that can fail for tricky geometries. """ try: yield except Exception: etype, err, tb = sys.e...
python
def context(src): try: yield except Exception: etype, err, tb = sys.exc_info() msg = 'An error occurred with source id=%s. Error: %s' msg %= (src.source_id, err) raise_(etype, msg, tb)
[ "def", "context", "(", "src", ")", ":", "try", ":", "yield", "except", "Exception", ":", "etype", ",", "err", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "msg", "=", "'An error occurred with source id=%s. Error: %s'", "msg", "%=", "(", "src", ".", ...
Used to add the source_id to the error message. To be used as with context(src): operation_with(src) Typically the operation is filtering a source, that can fail for tricky geometries.
[ "Used", "to", "add", "the", "source_id", "to", "the", "error", "message", ".", "To", "be", "used", "as" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L39-L55
gem/oq-engine
openquake/hazardlib/calc/filters.py
split_sources
def split_sources(srcs): """ :param srcs: sources :returns: a pair (split sources, split time) or just the split_sources """ from openquake.hazardlib.source import splittable sources = [] split_time = {} # src.id -> time for src in srcs: t0 = time.time() mag_a, mag_b = s...
python
def split_sources(srcs): from openquake.hazardlib.source import splittable sources = [] split_time = {} for src in srcs: t0 = time.time() mag_a, mag_b = src.get_min_max_mag() min_mag = src.min_mag if mag_b < min_mag: continue has_serial = hasa...
[ "def", "split_sources", "(", "srcs", ")", ":", "from", "openquake", ".", "hazardlib", ".", "source", "import", "splittable", "sources", "=", "[", "]", "split_time", "=", "{", "}", "# src.id -> time", "for", "src", "in", "srcs", ":", "t0", "=", "time", "....
:param srcs: sources :returns: a pair (split sources, split time) or just the split_sources
[ ":", "param", "srcs", ":", "sources", ":", "returns", ":", "a", "pair", "(", "split", "sources", "split", "time", ")", "or", "just", "the", "split_sources" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L186-L241
gem/oq-engine
openquake/hazardlib/calc/filters.py
IntegrationDistance.get_bounding_box
def get_bounding_box(self, lon, lat, trt=None, mag=None): """ Build a bounding box around the given lon, lat by computing the maximum_distance at the given tectonic region type and magnitude. :param lon: longitude :param lat: latitude :param trt: tectonic region type, po...
python
def get_bounding_box(self, lon, lat, trt=None, mag=None): if trt is None: maxdist = max(self(trt, mag) for trt in self.dic) else: maxdist = self(trt, mag) a1 = min(maxdist * KM_TO_DEGREES, 90) a2 = min(angular_distance(maxdist, lat), 180) retu...
[ "def", "get_bounding_box", "(", "self", ",", "lon", ",", "lat", ",", "trt", "=", "None", ",", "mag", "=", "None", ")", ":", "if", "trt", "is", "None", ":", "# take the greatest integration distance", "maxdist", "=", "max", "(", "self", "(", "trt", ",", ...
Build a bounding box around the given lon, lat by computing the maximum_distance at the given tectonic region type and magnitude. :param lon: longitude :param lat: latitude :param trt: tectonic region type, possibly None :param mag: magnitude, possibly None :returns: min...
[ "Build", "a", "bounding", "box", "around", "the", "given", "lon", "lat", "by", "computing", "the", "maximum_distance", "at", "the", "given", "tectonic", "region", "type", "and", "magnitude", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L138-L155
gem/oq-engine
openquake/hazardlib/calc/filters.py
IntegrationDistance.get_affected_box
def get_affected_box(self, src): """ Get the enlarged bounding box of a source. :param src: a source object :returns: a bounding box (min_lon, min_lat, max_lon, max_lat) """ mag = src.get_min_max_mag()[1] maxdist = self(src.tectonic_region_type, mag) bbox...
python
def get_affected_box(self, src): mag = src.get_min_max_mag()[1] maxdist = self(src.tectonic_region_type, mag) bbox = get_bounding_box(src, maxdist) return (fix_lon(bbox[0]), bbox[1], fix_lon(bbox[2]), bbox[3])
[ "def", "get_affected_box", "(", "self", ",", "src", ")", ":", "mag", "=", "src", ".", "get_min_max_mag", "(", ")", "[", "1", "]", "maxdist", "=", "self", "(", "src", ".", "tectonic_region_type", ",", "mag", ")", "bbox", "=", "get_bounding_box", "(", "s...
Get the enlarged bounding box of a source. :param src: a source object :returns: a bounding box (min_lon, min_lat, max_lon, max_lat)
[ "Get", "the", "enlarged", "bounding", "box", "of", "a", "source", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L157-L167
gem/oq-engine
openquake/hazardlib/calc/filters.py
SourceFilter.sitecol
def sitecol(self): """ Read the site collection from .filename and cache it """ if 'sitecol' in vars(self): return self.__dict__['sitecol'] if self.filename is None or not os.path.exists(self.filename): # case of nofilter/None sitecol return ...
python
def sitecol(self): if 'sitecol' in vars(self): return self.__dict__['sitecol'] if self.filename is None or not os.path.exists(self.filename): return with hdf5.File(self.filename, 'r') as h5: self.__dict__['sitecol'] = sc = h5.get('sitecol...
[ "def", "sitecol", "(", "self", ")", ":", "if", "'sitecol'", "in", "vars", "(", "self", ")", ":", "return", "self", ".", "__dict__", "[", "'sitecol'", "]", "if", "self", ".", "filename", "is", "None", "or", "not", "os", ".", "path", ".", "exists", "...
Read the site collection from .filename and cache it
[ "Read", "the", "site", "collection", "from", ".", "filename", "and", "cache", "it" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L276-L287
gem/oq-engine
openquake/hazardlib/calc/filters.py
SourceFilter.get_rectangle
def get_rectangle(self, src): """ :param src: a source object :returns: ((min_lon, min_lat), width, height), useful for plotting """ min_lon, min_lat, max_lon, max_lat = ( self.integration_distance.get_affected_box(src)) return (min_lon, min_lat), (max_lon - m...
python
def get_rectangle(self, src): min_lon, min_lat, max_lon, max_lat = ( self.integration_distance.get_affected_box(src)) return (min_lon, min_lat), (max_lon - min_lon) % 360, max_lat - min_lat
[ "def", "get_rectangle", "(", "self", ",", "src", ")", ":", "min_lon", ",", "min_lat", ",", "max_lon", ",", "max_lat", "=", "(", "self", ".", "integration_distance", ".", "get_affected_box", "(", "src", ")", ")", "return", "(", "min_lon", ",", "min_lat", ...
:param src: a source object :returns: ((min_lon, min_lat), width, height), useful for plotting
[ ":", "param", "src", ":", "a", "source", "object", ":", "returns", ":", "((", "min_lon", "min_lat", ")", "width", "height", ")", "useful", "for", "plotting" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L289-L296
gem/oq-engine
openquake/hazardlib/calc/filters.py
SourceFilter.get_bounding_boxes
def get_bounding_boxes(self, trt=None, mag=None): """ :param trt: a tectonic region type (used for the integration distance) :param mag: a magnitude (used for the integration distance) :returns: a list of bounding boxes, one per site """ bbs = [] for site in self....
python
def get_bounding_boxes(self, trt=None, mag=None): bbs = [] for site in self.sitecol: bb = self.integration_distance.get_bounding_box( site.location.longitude, site.location.latitude, trt, mag) bbs.append(bb) return bbs
[ "def", "get_bounding_boxes", "(", "self", ",", "trt", "=", "None", ",", "mag", "=", "None", ")", ":", "bbs", "=", "[", "]", "for", "site", "in", "self", ".", "sitecol", ":", "bb", "=", "self", ".", "integration_distance", ".", "get_bounding_box", "(", ...
:param trt: a tectonic region type (used for the integration distance) :param mag: a magnitude (used for the integration distance) :returns: a list of bounding boxes, one per site
[ ":", "param", "trt", ":", "a", "tectonic", "region", "type", "(", "used", "for", "the", "integration", "distance", ")", ":", "param", "mag", ":", "a", "magnitude", "(", "used", "for", "the", "integration", "distance", ")", ":", "returns", ":", "a", "li...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L319-L330
gem/oq-engine
openquake/hazardlib/calc/filters.py
SourceFilter.close_sids
def close_sids(self, rec, trt, mag): """ :param rec: a record with fields minlon, minlat, maxlon, maxlat :param trt: tectonic region type string :param mag: magnitude :returns: the site indices within the bounding box enlarged by the in...
python
def close_sids(self, rec, trt, mag): if self.sitecol is None: return [] elif not self.integration_distance: return self.sitecol.sids if hasattr(rec, 'dtype'): bbox = rec['minlon'], rec['minlat'], rec['maxlon'], rec['maxlat'] else: ...
[ "def", "close_sids", "(", "self", ",", "rec", ",", "trt", ",", "mag", ")", ":", "if", "self", ".", "sitecol", "is", "None", ":", "return", "[", "]", "elif", "not", "self", ".", "integration_distance", ":", "# do not filter", "return", "self", ".", "sit...
:param rec: a record with fields minlon, minlat, maxlon, maxlat :param trt: tectonic region type string :param mag: magnitude :returns: the site indices within the bounding box enlarged by the integration distance for the given TRT and magni...
[ ":", "param", "rec", ":", "a", "record", "with", "fields", "minlon", "minlat", "maxlon", "maxlat", ":", "param", "trt", ":", "tectonic", "region", "type", "string", ":", "param", "mag", ":", "magnitude", ":", "returns", ":", "the", "site", "indices", "wi...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L332-L358
gem/oq-engine
openquake/hazardlib/calc/filters.py
SourceFilter.filter
def filter(self, sources): """ :param sources: a sequence of sources :yields: sources with .indices """ for src in sources: if hasattr(src, 'indices'): # already filtered yield src continue box = self.integration_distance....
python
def filter(self, sources): for src in sources: if hasattr(src, 'indices'): yield src continue box = self.integration_distance.get_affected_box(src) indices = self.sitecol.within_bbox(box) if len(indices): ...
[ "def", "filter", "(", "self", ",", "sources", ")", ":", "for", "src", "in", "sources", ":", "if", "hasattr", "(", "src", ",", "'indices'", ")", ":", "# already filtered", "yield", "src", "continue", "box", "=", "self", ".", "integration_distance", ".", "...
:param sources: a sequence of sources :yields: sources with .indices
[ ":", "param", "sources", ":", "a", "sequence", "of", "sources", ":", "yields", ":", "sources", "with", ".", "indices" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L360-L373
gem/oq-engine
openquake/hazardlib/calc/filters.py
RtreeFilter.filter
def filter(self, sources): """ :param sources: a sequence of sources :yields: rtree-filtered sources """ if self.sitecol is None: # do not filter yield from sources return for src in sources: box = self.integration_distance.get_affecte...
python
def filter(self, sources): if self.sitecol is None: yield from sources return for src in sources: box = self.integration_distance.get_affected_box(src) indices = within(box, self.index) if len(indices): src.indices = ...
[ "def", "filter", "(", "self", ",", "sources", ")", ":", "if", "self", ".", "sitecol", "is", "None", ":", "# do not filter", "yield", "from", "sources", "return", "for", "src", "in", "sources", ":", "box", "=", "self", ".", "integration_distance", ".", "g...
:param sources: a sequence of sources :yields: rtree-filtered sources
[ ":", "param", "sources", ":", "a", "sequence", "of", "sources", ":", "yields", ":", "rtree", "-", "filtered", "sources" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L419-L432
gem/oq-engine
openquake/commands/to_shapefile.py
to_shapefile
def to_shapefile(output, input_nrml_file, validate): """ Convert a NRML source model file to ESRI Shapefile(s). For each type of source geometry defined in the NRML file (point, area, simple fault, complex fault, planar) a separate shapefile is created. Each shapefile is differentiated by a specifi...
python
def to_shapefile(output, input_nrml_file, validate): input_parser = shapefileparser.SourceModelParser() source_model = input_parser.read(input_nrml_file, validate) if not output: output = os.path.splitext(input_nrml_file)[0] print('Extracting %s_ files' % output) shapefileparser.Shapefi...
[ "def", "to_shapefile", "(", "output", ",", "input_nrml_file", ",", "validate", ")", ":", "input_parser", "=", "shapefileparser", ".", "SourceModelParser", "(", ")", "source_model", "=", "input_parser", ".", "read", "(", "input_nrml_file", ",", "validate", ")", "...
Convert a NRML source model file to ESRI Shapefile(s). For each type of source geometry defined in the NRML file (point, area, simple fault, complex fault, planar) a separate shapefile is created. Each shapefile is differentiated by a specific ending('_point', '_area', '_simple', '_complex', '_planar')...
[ "Convert", "a", "NRML", "source", "model", "file", "to", "ESRI", "Shapefile", "(", "s", ")", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/to_shapefile.py#L24-L40
gem/oq-engine
openquake/hazardlib/geo/surface/simple_fault.py
simple_fault_node
def simple_fault_node(fault_trace, dip, upper_depth, lower_depth): """ :param fault_trace: an object with an attribute .points :param dip: dip parameter :param upper_depth: upper seismogenic depth :param lower_depth: lower seismogenic depth :returns: a Node of kind simpleFaultGeometry """ ...
python
def simple_fault_node(fault_trace, dip, upper_depth, lower_depth): node = Node('simpleFaultGeometry') line = [] for p in fault_trace.points: line.append(p.longitude) line.append(p.latitude) node.append(Node('gml:LineString', nodes=[Node('gml:posList', {}, line)])) node.append(No...
[ "def", "simple_fault_node", "(", "fault_trace", ",", "dip", ",", "upper_depth", ",", "lower_depth", ")", ":", "node", "=", "Node", "(", "'simpleFaultGeometry'", ")", "line", "=", "[", "]", "for", "p", "in", "fault_trace", ".", "points", ":", "line", ".", ...
:param fault_trace: an object with an attribute .points :param dip: dip parameter :param upper_depth: upper seismogenic depth :param lower_depth: lower seismogenic depth :returns: a Node of kind simpleFaultGeometry
[ ":", "param", "fault_trace", ":", "an", "object", "with", "an", "attribute", ".", "points", ":", "param", "dip", ":", "dip", "parameter", ":", "param", "upper_depth", ":", "upper", "seismogenic", "depth", ":", "param", "lower_depth", ":", "lower", "seismogen...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L35-L52
gem/oq-engine
openquake/hazardlib/geo/surface/simple_fault.py
SimpleFaultSurface.check_fault_data
def check_fault_data(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip, mesh_spacing): """ Verify the fault data and raise ``ValueError`` if anything is wrong. This method doesn't have to be called by hands before creating the surface objec...
python
def check_fault_data(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip, mesh_spacing): if not len(fault_trace) >= 2: raise ValueError("the fault trace must have at least two points") if not fault_trace.horizontal(): raise Va...
[ "def", "check_fault_data", "(", "cls", ",", "fault_trace", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "dip", ",", "mesh_spacing", ")", ":", "if", "not", "len", "(", "fault_trace", ")", ">=", "2", ":", "raise", "ValueError", "(", "\"th...
Verify the fault data and raise ``ValueError`` if anything is wrong. This method doesn't have to be called by hands before creating the surface object, because it is called from :meth:`from_fault_data`.
[ "Verify", "the", "fault", "data", "and", "raise", "ValueError", "if", "anything", "is", "wrong", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L107-L132
gem/oq-engine
openquake/hazardlib/geo/surface/simple_fault.py
SimpleFaultSurface.from_fault_data
def from_fault_data(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip, mesh_spacing): """ Create and return a fault surface using fault source data. :param openquake.hazardlib.geo.line.Line fault_trace: Geographical line representing the...
python
def from_fault_data(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip, mesh_spacing): cls.check_fault_data(fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip, mesh_spacing) vdi...
[ "def", "from_fault_data", "(", "cls", ",", "fault_trace", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "dip", ",", "mesh_spacing", ")", ":", "cls", ".", "check_fault_data", "(", "fault_trace", ",", "upper_seismogenic_depth", ",", "lower_seismog...
Create and return a fault surface using fault source data. :param openquake.hazardlib.geo.line.Line fault_trace: Geographical line representing the intersection between the fault surface and the earth surface. The line must be horizontal (i.e. all depth values must be equal)...
[ "Create", "and", "return", "a", "fault", "surface", "using", "fault", "source", "data", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L135-L196
gem/oq-engine
openquake/hazardlib/geo/surface/simple_fault.py
SimpleFaultSurface.get_fault_patch_vertices
def get_fault_patch_vertices(cls, rupture_top_edge, upper_seismogenic_depth, lower_seismogenic_depth, dip, index_patch=1): """ Get surface main vertices. Parameters are the same as for :meth:`from_fault_data`, excluding fa...
python
def get_fault_patch_vertices(cls, rupture_top_edge, upper_seismogenic_depth, lower_seismogenic_depth, dip, index_patch=1): dip_tan = math.tan(math.radians(dip)) hdist_bottom = ( lower_seismogenic_depth - uppe...
[ "def", "get_fault_patch_vertices", "(", "cls", ",", "rupture_top_edge", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "dip", ",", "index_patch", "=", "1", ")", ":", "# Similar to :meth:`from_fault_data`, we just don't resample edges", "dip_tan", "=", ...
Get surface main vertices. Parameters are the same as for :meth:`from_fault_data`, excluding fault_trace, and mesh spacing. :param rupture_top_edge: A instances of :class:`openquake.hazardlib.geo.line.Line` representing the rupture surface's top edge. :param inde...
[ "Get", "surface", "main", "vertices", ".", "Parameters", "are", "the", "same", "as", "for", ":", "meth", ":", "from_fault_data", "excluding", "fault_trace", "and", "mesh", "spacing", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L199-L253
gem/oq-engine
openquake/hazardlib/geo/surface/simple_fault.py
SimpleFaultSurface.hypocentre_patch_index
def hypocentre_patch_index(cls, hypocentre, rupture_top_edge, upper_seismogenic_depth, lower_seismogenic_depth, dip): """ This methods finds the index of the fault patch including the hypocentre. :param hypocentre: ...
python
def hypocentre_patch_index(cls, hypocentre, rupture_top_edge, upper_seismogenic_depth, lower_seismogenic_depth, dip): totaln_patch = len(rupture_top_edge) indexlist = [] dist_list = [] for i, index in enumerate(range(...
[ "def", "hypocentre_patch_index", "(", "cls", ",", "hypocentre", ",", "rupture_top_edge", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "dip", ")", ":", "totaln_patch", "=", "len", "(", "rupture_top_edge", ")", "indexlist", "=", "[", "]", "di...
This methods finds the index of the fault patch including the hypocentre. :param hypocentre: :class:`~openquake.hazardlib.geo.point.Point` object representing the location of hypocentre. :param rupture_top_edge: A instances of :class:`openquake.hazardlib.geo....
[ "This", "methods", "finds", "the", "index", "of", "the", "fault", "patch", "including", "the", "hypocentre", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L256-L298
gem/oq-engine
openquake/hazardlib/geo/surface/simple_fault.py
SimpleFaultSurface.get_surface_vertexes
def get_surface_vertexes(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip): """ Get surface main vertexes. Parameters are the same as for :meth:`from_fault_data`, excluding mesh spacing. :returns: ...
python
def get_surface_vertexes(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip): dip_tan = math.tan(math.radians(dip)) hdist_top = upper_seismogenic_depth / dip_tan hdist_bottom = lower_seismogenic_dept...
[ "def", "get_surface_vertexes", "(", "cls", ",", "fault_trace", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "dip", ")", ":", "# Similar to :meth:`from_fault_data`, we just don't resample edges", "dip_tan", "=", "math", ".", "tan", "(", "math", ".",...
Get surface main vertexes. Parameters are the same as for :meth:`from_fault_data`, excluding mesh spacing. :returns: Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon` describing the surface projection of the simple fault with specified parameters...
[ "Get", "surface", "main", "vertexes", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L301-L336
gem/oq-engine
openquake/hazardlib/geo/surface/simple_fault.py
SimpleFaultSurface.surface_projection_from_fault_data
def surface_projection_from_fault_data(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip): """ Get a surface projection of the simple fault surface. Parameters are the same as for :meth:`...
python
def surface_projection_from_fault_data(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip): lons, lats = cls.get_surface_vertexes(fault_trace, upper_s...
[ "def", "surface_projection_from_fault_data", "(", "cls", ",", "fault_trace", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "dip", ")", ":", "lons", ",", "lats", "=", "cls", ".", "get_surface_vertexes", "(", "fault_trace", ",", "upper_seismogenic...
Get a surface projection of the simple fault surface. Parameters are the same as for :meth:`from_fault_data`, excluding mesh spacing. :returns: Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon` describing the surface projection of the simple fault with ...
[ "Get", "a", "surface", "projection", "of", "the", "simple", "fault", "surface", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L339-L356
gem/oq-engine
openquake/hazardlib/gsim/zhao_2006.py
ZhaoEtAl2006Asc.get_mean_and_stddevs
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required #...
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): C = self.COEFFS_ASC[imt] mean = self._compute_magnitude_term(C, rup.mag) +\ self._compute_distance_term(C, rup.mag, dists.rrup) +\ self._compute_f...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "# extracting dictionary of coefficients specific to required", "# intensity measure type.", "C", "=", "self", ".", "COEFFS_ASC", "[", "imt",...
See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
[ "See", ":", "meth", ":", "superclass", "method", "<", ".", "base", ".", "GroundShakingIntensityModel", ".", "get_mean_and_stddevs", ">", "for", "spec", "of", "input", "and", "result", "values", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L81-L109
gem/oq-engine
openquake/hazardlib/gsim/zhao_2006.py
ZhaoEtAl2006Asc._compute_distance_term
def _compute_distance_term(self, C, mag, rrup): """ Compute second and third terms in equation 1, p. 901. """ term1 = C['b'] * rrup term2 = - np.log(rrup + C['c'] * np.exp(C['d'] * mag)) return term1 + term2
python
def _compute_distance_term(self, C, mag, rrup): term1 = C['b'] * rrup term2 = - np.log(rrup + C['c'] * np.exp(C['d'] * mag)) return term1 + term2
[ "def", "_compute_distance_term", "(", "self", ",", "C", ",", "mag", ",", "rrup", ")", ":", "term1", "=", "C", "[", "'b'", "]", "*", "rrup", "term2", "=", "-", "np", ".", "log", "(", "rrup", "+", "C", "[", "'c'", "]", "*", "np", ".", "exp", "(...
Compute second and third terms in equation 1, p. 901.
[ "Compute", "second", "and", "third", "terms", "in", "equation", "1", "p", ".", "901", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L133-L140
gem/oq-engine
openquake/hazardlib/gsim/zhao_2006.py
ZhaoEtAl2006Asc._compute_focal_depth_term
def _compute_focal_depth_term(self, C, hypo_depth): """ Compute fourth term in equation 1, p. 901. """ # p. 901. "(i.e, depth is capped at 125 km)". focal_depth = hypo_depth if focal_depth > 125.0: focal_depth = 125.0 # p. 902. "We used the value of 1...
python
def _compute_focal_depth_term(self, C, hypo_depth): focal_depth = hypo_depth if focal_depth > 125.0: focal_depth = 125.0 hc = 15.0 return float(focal_depth >= hc) * C['e'] * (focal_depth - hc)
[ "def", "_compute_focal_depth_term", "(", "self", ",", "C", ",", "hypo_depth", ")", ":", "# p. 901. \"(i.e, depth is capped at 125 km)\".", "focal_depth", "=", "hypo_depth", "if", "focal_depth", ">", "125.0", ":", "focal_depth", "=", "125.0", "# p. 902. \"We used the value...
Compute fourth term in equation 1, p. 901.
[ "Compute", "fourth", "term", "in", "equation", "1", "p", ".", "901", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L142-L157
gem/oq-engine
openquake/hazardlib/gsim/zhao_2006.py
ZhaoEtAl2006Asc._compute_site_class_term
def _compute_site_class_term(self, C, vs30): """ Compute nine-th term in equation 1, p. 901. """ # map vs30 value to site class, see table 2, p. 901. site_term = np.zeros(len(vs30)) # hard rock site_term[vs30 > 1100.0] = C['CH'] # rock site_term[...
python
def _compute_site_class_term(self, C, vs30): site_term = np.zeros(len(vs30)) site_term[vs30 > 1100.0] = C['CH'] site_term[(vs30 > 600) & (vs30 <= 1100)] = C['C1'] site_term[(vs30 > 300) & (vs30 <= 600)] = C['C2'] site_term...
[ "def", "_compute_site_class_term", "(", "self", ",", "C", ",", "vs30", ")", ":", "# map vs30 value to site class, see table 2, p. 901.", "site_term", "=", "np", ".", "zeros", "(", "len", "(", "vs30", ")", ")", "# hard rock", "site_term", "[", "vs30", ">", "1100....
Compute nine-th term in equation 1, p. 901.
[ "Compute", "nine", "-", "th", "term", "in", "equation", "1", "p", ".", "901", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L168-L190
gem/oq-engine
openquake/hazardlib/gsim/zhao_2006.py
ZhaoEtAl2006Asc._compute_magnitude_squared_term
def _compute_magnitude_squared_term(self, P, M, Q, W, mag): """ Compute magnitude squared term, equation 5, p. 909. """ return P * (mag - M) + Q * (mag - M) ** 2 + W
python
def _compute_magnitude_squared_term(self, P, M, Q, W, mag): return P * (mag - M) + Q * (mag - M) ** 2 + W
[ "def", "_compute_magnitude_squared_term", "(", "self", ",", "P", ",", "M", ",", "Q", ",", "W", ",", "mag", ")", ":", "return", "P", "*", "(", "mag", "-", "M", ")", "+", "Q", "*", "(", "mag", "-", "M", ")", "**", "2", "+", "W" ]
Compute magnitude squared term, equation 5, p. 909.
[ "Compute", "magnitude", "squared", "term", "equation", "5", "p", ".", "909", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L192-L196
gem/oq-engine
openquake/hazardlib/gsim/zhao_2006.py
ZhaoEtAl2006SSlab._compute_slab_correction_term
def _compute_slab_correction_term(self, C, rrup): """ Compute path modification term for slab events, that is the 8-th term in equation 1, p. 901. """ slab_term = C['SSL'] * np.log(rrup) return slab_term
python
def _compute_slab_correction_term(self, C, rrup): slab_term = C['SSL'] * np.log(rrup) return slab_term
[ "def", "_compute_slab_correction_term", "(", "self", ",", "C", ",", "rrup", ")", ":", "slab_term", "=", "C", "[", "'SSL'", "]", "*", "np", ".", "log", "(", "rrup", ")", "return", "slab_term" ]
Compute path modification term for slab events, that is the 8-th term in equation 1, p. 901.
[ "Compute", "path", "modification", "term", "for", "slab", "events", "that", "is", "the", "8", "-", "th", "term", "in", "equation", "1", "p", ".", "901", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L369-L376
gem/oq-engine
openquake/hazardlib/gsim/zhao_2006.py
ZhaoEtAl2006AscSGS.get_mean_and_stddevs
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ Using a minimum distance of 5km for the calculation. """ dists_mod = copy.deepcopy(dists) dists_mod.rrup[dists.rrup <= 5.] = 5. return super().get_mean_and_stddevs( sites, rup, dists_m...
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): dists_mod = copy.deepcopy(dists) dists_mod.rrup[dists.rrup <= 5.] = 5. return super().get_mean_and_stddevs( sites, rup, dists_mod, imt, stddev_types)
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "dists_mod", "=", "copy", ".", "deepcopy", "(", "dists", ")", "dists_mod", ".", "rrup", "[", "dists", ".", "rrup", "<=", "5."...
Using a minimum distance of 5km for the calculation.
[ "Using", "a", "minimum", "distance", "of", "5km", "for", "the", "calculation", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L654-L663
gem/oq-engine
openquake/engine/utils/__init__.py
confirm
def confirm(prompt): """ Ask for confirmation, given a ``prompt`` and return a boolean value. """ while True: try: answer = input(prompt) except KeyboardInterrupt: # the user presses ctrl+c, just say 'no' return False answer = answer.strip().lo...
python
def confirm(prompt): while True: try: answer = input(prompt) except KeyboardInterrupt: return False answer = answer.strip().lower() if answer not in ('y', 'n'): print('Please enter y or n') continue return answ...
[ "def", "confirm", "(", "prompt", ")", ":", "while", "True", ":", "try", ":", "answer", "=", "input", "(", "prompt", ")", "except", "KeyboardInterrupt", ":", "# the user presses ctrl+c, just say 'no'", "return", "False", "answer", "=", "answer", ".", "strip", "...
Ask for confirmation, given a ``prompt`` and return a boolean value.
[ "Ask", "for", "confirmation", "given", "a", "prompt", "and", "return", "a", "boolean", "value", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/utils/__init__.py#L20-L34
gem/oq-engine
openquake/risklib/asset.py
build_asset_array
def build_asset_array(assets_by_site, tagnames=(), time_event=None): """ :param assets_by_site: a list of lists of assets :param tagnames: a list of tag names :returns: an array `assetcol` """ for assets in assets_by_site: if len(assets): first_asset = assets[0] b...
python
def build_asset_array(assets_by_site, tagnames=(), time_event=None): for assets in assets_by_site: if len(assets): first_asset = assets[0] break else: raise ValueError('There are no assets!') loss_types = [] occupancy_periods = [] for name in sorted(fir...
[ "def", "build_asset_array", "(", "assets_by_site", ",", "tagnames", "=", "(", ")", ",", "time_event", "=", "None", ")", ":", "for", "assets", "in", "assets_by_site", ":", "if", "len", "(", "assets", ")", ":", "first_asset", "=", "assets", "[", "0", "]", ...
:param assets_by_site: a list of lists of assets :param tagnames: a list of tag names :returns: an array `assetcol`
[ ":", "param", "assets_by_site", ":", "a", "list", "of", "lists", "of", "assets", ":", "param", "tagnames", ":", "a", "list", "of", "tag", "names", ":", "returns", ":", "an", "array", "assetcol" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L583-L655
gem/oq-engine
openquake/risklib/asset.py
_get_exposure
def _get_exposure(fname, stop=None): """ :param fname: path of the XML file containing the exposure :param stop: node at which to stop parsing (or None) :returns: a pair (Exposure instance, list of asset nodes) """ [exposure] = nrml.read(fname, stop=stop) if not expos...
python
def _get_exposure(fname, stop=None): [exposure] = nrml.read(fname, stop=stop) if not exposure.tag.endswith('exposureModel'): raise InvalidFile('%s: expected exposureModel, got %s' % (fname, exposure.tag)) description = exposure.description try: conversions ...
[ "def", "_get_exposure", "(", "fname", ",", "stop", "=", "None", ")", ":", "[", "exposure", "]", "=", "nrml", ".", "read", "(", "fname", ",", "stop", "=", "stop", ")", "if", "not", "exposure", ".", "tag", ".", "endswith", "(", "'exposureModel'", ")", ...
:param fname: path of the XML file containing the exposure :param stop: node at which to stop parsing (or None) :returns: a pair (Exposure instance, list of asset nodes)
[ ":", "param", "fname", ":", "path", "of", "the", "XML", "file", "containing", "the", "exposure", ":", "param", "stop", ":", "node", "at", "which", "to", "stop", "parsing", "(", "or", "None", ")", ":", "returns", ":", "a", "pair", "(", "Exposure", "in...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L665-L762
gem/oq-engine
openquake/risklib/asset.py
CostCalculator.get_units
def get_units(self, loss_types): """ :param: a list of loss types :returns: an array of units as byte strings, suitable for HDF5 """ lst = [] for lt in loss_types: if lt.endswith('_ins'): lt = lt[:-4] if lt == 'occupants': ...
python
def get_units(self, loss_types): lst = [] for lt in loss_types: if lt.endswith('_ins'): lt = lt[:-4] if lt == 'occupants': unit = 'people' else: unit = self.units[lt] lst.append(encode(unit)) ...
[ "def", "get_units", "(", "self", ",", "loss_types", ")", ":", "lst", "=", "[", "]", "for", "lt", "in", "loss_types", ":", "if", "lt", ".", "endswith", "(", "'_ins'", ")", ":", "lt", "=", "lt", "[", ":", "-", "4", "]", "if", "lt", "==", "'occupa...
:param: a list of loss types :returns: an array of units as byte strings, suitable for HDF5
[ ":", "param", ":", "a", "list", "of", "loss", "types", ":", "returns", ":", "an", "array", "of", "units", "as", "byte", "strings", "suitable", "for", "HDF5" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L82-L96
gem/oq-engine
openquake/risklib/asset.py
Asset.value
def value(self, loss_type, time_event=None): """ :returns: the total asset value for `loss_type` """ if loss_type == 'occupants': return self.values['occupants_' + str(time_event)] try: # extract from the cache val = self._cost[loss_type] except K...
python
def value(self, loss_type, time_event=None): if loss_type == 'occupants': return self.values['occupants_' + str(time_event)] try: val = self._cost[loss_type] except KeyError: val = self.calc(loss_type, self.values, self.area, self.number) ...
[ "def", "value", "(", "self", ",", "loss_type", ",", "time_event", "=", "None", ")", ":", "if", "loss_type", "==", "'occupants'", ":", "return", "self", ".", "values", "[", "'occupants_'", "+", "str", "(", "time_event", ")", "]", "try", ":", "# extract fr...
:returns: the total asset value for `loss_type`
[ ":", "returns", ":", "the", "total", "asset", "value", "for", "loss_type" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L195-L206
gem/oq-engine
openquake/risklib/asset.py
Asset.deductible
def deductible(self, loss_type, dummy=None): """ :returns: the deductible fraction of the asset cost for `loss_type` """ val = self.calc(loss_type, self.deductibles, self.area, self.number) if self.calc.deduct_abs: # convert to relative value return val / self.calc(l...
python
def deductible(self, loss_type, dummy=None): val = self.calc(loss_type, self.deductibles, self.area, self.number) if self.calc.deduct_abs: return val / self.calc(loss_type, self.values, self.area, self.number) else: return val
[ "def", "deductible", "(", "self", ",", "loss_type", ",", "dummy", "=", "None", ")", ":", "val", "=", "self", ".", "calc", "(", "loss_type", ",", "self", ".", "deductibles", ",", "self", ".", "area", ",", "self", ".", "number", ")", "if", "self", "....
:returns: the deductible fraction of the asset cost for `loss_type`
[ ":", "returns", ":", "the", "deductible", "fraction", "of", "the", "asset", "cost", "for", "loss_type" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L208-L217
gem/oq-engine
openquake/risklib/asset.py
Asset.insurance_limit
def insurance_limit(self, loss_type, dummy=None): """ :returns: the limit fraction of the asset cost for `loss_type` """ val = self.calc(loss_type, self.insurance_limits, self.area, self.number) if self.calc.limit_abs: # convert to relative value ...
python
def insurance_limit(self, loss_type, dummy=None): val = self.calc(loss_type, self.insurance_limits, self.area, self.number) if self.calc.limit_abs: return val / self.calc(loss_type, self.values, self.area, self.number) ...
[ "def", "insurance_limit", "(", "self", ",", "loss_type", ",", "dummy", "=", "None", ")", ":", "val", "=", "self", ".", "calc", "(", "loss_type", ",", "self", ".", "insurance_limits", ",", "self", ".", "area", ",", "self", ".", "number", ")", "if", "s...
:returns: the limit fraction of the asset cost for `loss_type`
[ ":", "returns", ":", "the", "limit", "fraction", "of", "the", "asset", "cost", "for", "loss_type" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L219-L229
gem/oq-engine
openquake/risklib/asset.py
Asset.retrofitted
def retrofitted(self): """ :returns: the asset retrofitted value """ return self.calc('structural', {'structural': self._retrofitted}, self.area, self.number)
python
def retrofitted(self): return self.calc('structural', {'structural': self._retrofitted}, self.area, self.number)
[ "def", "retrofitted", "(", "self", ")", ":", "return", "self", ".", "calc", "(", "'structural'", ",", "{", "'structural'", ":", "self", ".", "_retrofitted", "}", ",", "self", ".", "area", ",", "self", ".", "number", ")" ]
:returns: the asset retrofitted value
[ ":", "returns", ":", "the", "asset", "retrofitted", "value" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L231-L236
gem/oq-engine
openquake/risklib/asset.py
Asset.tagmask
def tagmask(self, tags): """ :returns: a boolean array with True where the assets has tags """ mask = numpy.zeros(len(tags), bool) for t, tag in enumerate(tags): tagname, tagvalue = tag.split('=') mask[t] = self.tagvalue(tagname) == tagvalue return...
python
def tagmask(self, tags): mask = numpy.zeros(len(tags), bool) for t, tag in enumerate(tags): tagname, tagvalue = tag.split('=') mask[t] = self.tagvalue(tagname) == tagvalue return mask
[ "def", "tagmask", "(", "self", ",", "tags", ")", ":", "mask", "=", "numpy", ".", "zeros", "(", "len", "(", "tags", ")", ",", "bool", ")", "for", "t", ",", "tag", "in", "enumerate", "(", "tags", ")", ":", "tagname", ",", "tagvalue", "=", "tag", ...
:returns: a boolean array with True where the assets has tags
[ ":", "returns", ":", "a", "boolean", "array", "with", "True", "where", "the", "assets", "has", "tags" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L238-L246
gem/oq-engine
openquake/risklib/asset.py
TagCollection.add
def add(self, tagname, tagvalue): """ :returns: numeric index associated to the tag """ dic = getattr(self, tagname + '_idx') try: return dic[tagvalue] except KeyError: dic[tagvalue] = idx = len(dic) getattr(self, tagname).append(tagval...
python
def add(self, tagname, tagvalue): dic = getattr(self, tagname + '_idx') try: return dic[tagvalue] except KeyError: dic[tagvalue] = idx = len(dic) getattr(self, tagname).append(tagvalue) if idx > TWO16: raise InvalidFile('co...
[ "def", "add", "(", "self", ",", "tagname", ",", "tagvalue", ")", ":", "dic", "=", "getattr", "(", "self", ",", "tagname", "+", "'_idx'", ")", "try", ":", "return", "dic", "[", "tagvalue", "]", "except", "KeyError", ":", "dic", "[", "tagvalue", "]", ...
:returns: numeric index associated to the tag
[ ":", "returns", ":", "numeric", "index", "associated", "to", "the", "tag" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L287-L299
gem/oq-engine
openquake/risklib/asset.py
TagCollection.add_tags
def add_tags(self, dic, prefix): """ :param dic: a dictionary tagname -> tagvalue :returns: a list of tag indices, one per tagname """ # fill missing tagvalues with "?", raise an error for unknown tagnames idxs = [] for tagname in self.tagnames: if tag...
python
def add_tags(self, dic, prefix): idxs = [] for tagname in self.tagnames: if tagname in ('exposure', 'country'): idxs.append(self.add(tagname, prefix)) continue try: tagvalue = dic.pop(tagname) except Ke...
[ "def", "add_tags", "(", "self", ",", "dic", ",", "prefix", ")", ":", "# fill missing tagvalues with \"?\", raise an error for unknown tagnames", "idxs", "=", "[", "]", "for", "tagname", "in", "self", ".", "tagnames", ":", "if", "tagname", "in", "(", "'exposure'", ...
:param dic: a dictionary tagname -> tagvalue :returns: a list of tag indices, one per tagname
[ ":", "param", "dic", ":", "a", "dictionary", "tagname", "-", ">", "tagvalue", ":", "returns", ":", "a", "list", "of", "tag", "indices", "one", "per", "tagname" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L301-L325
gem/oq-engine
openquake/risklib/asset.py
TagCollection.get_tag
def get_tag(self, tagname, tagidx): """ :returns: the tag associated to the given tagname and tag index """ return '%s=%s' % (tagname, decode(getattr(self, tagname)[tagidx]))
python
def get_tag(self, tagname, tagidx): return '%s=%s' % (tagname, decode(getattr(self, tagname)[tagidx]))
[ "def", "get_tag", "(", "self", ",", "tagname", ",", "tagidx", ")", ":", "return", "'%s=%s'", "%", "(", "tagname", ",", "decode", "(", "getattr", "(", "self", ",", "tagname", ")", "[", "tagidx", "]", ")", ")" ]
:returns: the tag associated to the given tagname and tag index
[ ":", "returns", ":", "the", "tag", "associated", "to", "the", "given", "tagname", "and", "tag", "index" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L332-L336
gem/oq-engine
openquake/risklib/asset.py
TagCollection.get_tagvalues
def get_tagvalues(self, tagnames, tagidxs): """ :returns: the tag associated to the given tagname and tag index """ values = tuple(getattr(self, tagname)[tagidx + 1] for tagidx, tagname in zip(tagidxs, tagnames)) return values
python
def get_tagvalues(self, tagnames, tagidxs): values = tuple(getattr(self, tagname)[tagidx + 1] for tagidx, tagname in zip(tagidxs, tagnames)) return values
[ "def", "get_tagvalues", "(", "self", ",", "tagnames", ",", "tagidxs", ")", ":", "values", "=", "tuple", "(", "getattr", "(", "self", ",", "tagname", ")", "[", "tagidx", "+", "1", "]", "for", "tagidx", ",", "tagname", "in", "zip", "(", "tagidxs", ",",...
:returns: the tag associated to the given tagname and tag index
[ ":", "returns", ":", "the", "tag", "associated", "to", "the", "given", "tagname", "and", "tag", "index" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L338-L344
gem/oq-engine
openquake/risklib/asset.py
TagCollection.gen_tags
def gen_tags(self, tagname): """ :yields: the tags associated to the given tagname """ for tagvalue in getattr(self, tagname): yield '%s=%s' % (tagname, decode(tagvalue))
python
def gen_tags(self, tagname): for tagvalue in getattr(self, tagname): yield '%s=%s' % (tagname, decode(tagvalue))
[ "def", "gen_tags", "(", "self", ",", "tagname", ")", ":", "for", "tagvalue", "in", "getattr", "(", "self", ",", "tagname", ")", ":", "yield", "'%s=%s'", "%", "(", "tagname", ",", "decode", "(", "tagvalue", ")", ")" ]
:yields: the tags associated to the given tagname
[ ":", "yields", ":", "the", "tags", "associated", "to", "the", "given", "tagname" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L346-L351
gem/oq-engine
openquake/risklib/asset.py
TagCollection.agg_shape
def agg_shape(self, shp, aggregate_by): """ :returns: a shape shp + (T, ...) depending on the tagnames """ return shp + tuple( len(getattr(self, tagname)) - 1 for tagname in aggregate_by)
python
def agg_shape(self, shp, aggregate_by): return shp + tuple( len(getattr(self, tagname)) - 1 for tagname in aggregate_by)
[ "def", "agg_shape", "(", "self", ",", "shp", ",", "aggregate_by", ")", ":", "return", "shp", "+", "tuple", "(", "len", "(", "getattr", "(", "self", ",", "tagname", ")", ")", "-", "1", "for", "tagname", "in", "aggregate_by", ")" ]
:returns: a shape shp + (T, ...) depending on the tagnames
[ ":", "returns", ":", "a", "shape", "shp", "+", "(", "T", "...", ")", "depending", "on", "the", "tagnames" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L353-L358
gem/oq-engine
openquake/risklib/asset.py
AssetCollection.num_taxonomies_by_site
def num_taxonomies_by_site(self): """ :returns: an array with the number of assets per each site """ dic = general.group_array(self.array, 'site_id') num_taxonomies = numpy.zeros(self.tot_sites, U32) for sid, arr in dic.items(): num_taxonomies[sid] = len(numpy...
python
def num_taxonomies_by_site(self): dic = general.group_array(self.array, 'site_id') num_taxonomies = numpy.zeros(self.tot_sites, U32) for sid, arr in dic.items(): num_taxonomies[sid] = len(numpy.unique(arr['taxonomy'])) return num_taxonomies
[ "def", "num_taxonomies_by_site", "(", "self", ")", ":", "dic", "=", "general", ".", "group_array", "(", "self", ".", "array", ",", "'site_id'", ")", "num_taxonomies", "=", "numpy", ".", "zeros", "(", "self", ".", "tot_sites", ",", "U32", ")", "for", "sid...
:returns: an array with the number of assets per each site
[ ":", "returns", ":", "an", "array", "with", "the", "number", "of", "assets", "per", "each", "site" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L426-L434
gem/oq-engine
openquake/risklib/asset.py
AssetCollection.get_aids_by_tag
def get_aids_by_tag(self): """ :returns: dict tag -> asset ordinals """ aids_by_tag = general.AccumDict(accum=set()) for aid, ass in enumerate(self): for tagname in self.tagnames: tag = self.tagcol.get_tag(tagname, ass[tagname]) aids_by...
python
def get_aids_by_tag(self): aids_by_tag = general.AccumDict(accum=set()) for aid, ass in enumerate(self): for tagname in self.tagnames: tag = self.tagcol.get_tag(tagname, ass[tagname]) aids_by_tag[tag].add(aid) return aids_by_tag
[ "def", "get_aids_by_tag", "(", "self", ")", ":", "aids_by_tag", "=", "general", ".", "AccumDict", "(", "accum", "=", "set", "(", ")", ")", "for", "aid", ",", "ass", "in", "enumerate", "(", "self", ")", ":", "for", "tagname", "in", "self", ".", "tagna...
:returns: dict tag -> asset ordinals
[ ":", "returns", ":", "dict", "tag", "-", ">", "asset", "ordinals" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L436-L445
gem/oq-engine
openquake/risklib/asset.py
AssetCollection.assets_by_site
def assets_by_site(self): """ :returns: numpy array of lists with the assets by each site """ assets_by_site = [[] for sid in range(self.tot_sites)] for i, ass in enumerate(self.array): assets_by_site[ass['site_id']].append(self[i]) return numpy.array(assets_b...
python
def assets_by_site(self): assets_by_site = [[] for sid in range(self.tot_sites)] for i, ass in enumerate(self.array): assets_by_site[ass['site_id']].append(self[i]) return numpy.array(assets_by_site)
[ "def", "assets_by_site", "(", "self", ")", ":", "assets_by_site", "=", "[", "[", "]", "for", "sid", "in", "range", "(", "self", ".", "tot_sites", ")", "]", "for", "i", ",", "ass", "in", "enumerate", "(", "self", ".", "array", ")", ":", "assets_by_sit...
:returns: numpy array of lists with the assets by each site
[ ":", "returns", ":", "numpy", "array", "of", "lists", "with", "the", "assets", "by", "each", "site" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L454-L461
gem/oq-engine
openquake/risklib/asset.py
AssetCollection.aggregate_by
def aggregate_by(self, tagnames, array): """ :param tagnames: a list of valid tag names :param array: an array with the same length as the asset collection :returns: an array of aggregate values with the proper shape """ missing = set(tagnames) - set(self.tagcol.tagnames)...
python
def aggregate_by(self, tagnames, array): missing = set(tagnames) - set(self.tagcol.tagnames) if missing: raise ValueError('Unknown tagname(s) %s' % missing) A, *shp = array.shape if A != len(self): raise ValueError('The array must have length %d, got %d' ...
[ "def", "aggregate_by", "(", "self", ",", "tagnames", ",", "array", ")", ":", "missing", "=", "set", "(", "tagnames", ")", "-", "set", "(", "self", ".", "tagcol", ".", "tagnames", ")", "if", "missing", ":", "raise", "ValueError", "(", "'Unknown tagname(s)...
:param tagnames: a list of valid tag names :param array: an array with the same length as the asset collection :returns: an array of aggregate values with the proper shape
[ ":", "param", "tagnames", ":", "a", "list", "of", "valid", "tag", "names", ":", "param", "array", ":", "an", "array", "with", "the", "same", "length", "as", "the", "asset", "collection", ":", "returns", ":", "an", "array", "of", "aggregate", "values", ...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L463-L482
gem/oq-engine
openquake/risklib/asset.py
AssetCollection.agg_value
def agg_value(self, *tagnames): """ :param tagnames: tagnames of lengths T1, T2, ... respectively :returns: the values of the exposure aggregated by tagnames as an array of shape (T1, T2, ..., L) """ aval = numpy.zeros((len(self), len(self.loss...
python
def agg_value(self, *tagnames): aval = numpy.zeros((len(self), len(self.loss_types)), F32) for asset in self: for lti, lt in enumerate(self.loss_types): if lt == 'occupants': aval[asset['ordinal'], lti] = asset[lt + '_None'] else...
[ "def", "agg_value", "(", "self", ",", "*", "tagnames", ")", ":", "aval", "=", "numpy", ".", "zeros", "(", "(", "len", "(", "self", ")", ",", "len", "(", "self", ".", "loss_types", ")", ")", ",", "F32", ")", "# (A, L)", "for", "asset", "in", "self...
:param tagnames: tagnames of lengths T1, T2, ... respectively :returns: the values of the exposure aggregated by tagnames as an array of shape (T1, T2, ..., L)
[ ":", "param", "tagnames", ":", "tagnames", "of", "lengths", "T1", "T2", "...", "respectively", ":", "returns", ":", "the", "values", "of", "the", "exposure", "aggregated", "by", "tagnames", "as", "an", "array", "of", "shape", "(", "T1", "T2", "...", "L",...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L484-L499
gem/oq-engine
openquake/risklib/asset.py
AssetCollection.reduce
def reduce(self, sitecol): """ :returns: a reduced AssetCollection on the given sitecol """ ok_indices = numpy.sum( [self.array['site_id'] == sid for sid in sitecol.sids], axis=0, dtype=bool) new = object.__new__(self.__class__) vars(new).update(va...
python
def reduce(self, sitecol): ok_indices = numpy.sum( [self.array['site_id'] == sid for sid in sitecol.sids], axis=0, dtype=bool) new = object.__new__(self.__class__) vars(new).update(vars(self)) new.array = self.array[ok_indices] new.array['ordinal'...
[ "def", "reduce", "(", "self", ",", "sitecol", ")", ":", "ok_indices", "=", "numpy", ".", "sum", "(", "[", "self", ".", "array", "[", "'site_id'", "]", "==", "sid", "for", "sid", "in", "sitecol", ".", "sids", "]", ",", "axis", "=", "0", ",", "dtyp...
:returns: a reduced AssetCollection on the given sitecol
[ ":", "returns", ":", "a", "reduced", "AssetCollection", "on", "the", "given", "sitecol" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L501-L513
gem/oq-engine
openquake/risklib/asset.py
AssetCollection.reduce_also
def reduce_also(self, sitecol): """ :returns: a reduced AssetCollection on the given sitecol NB: diffently from .reduce, also the SiteCollection is reduced and turned into a complete site collection. """ array = [] asset_refs = [] for idx, sid in enumerate...
python
def reduce_also(self, sitecol): array = [] asset_refs = [] for idx, sid in enumerate(sitecol.sids): mask = self.array['site_id'] == sid arr = self.array[mask] arr['site_id'] = idx array.append(arr) asset_refs.append(self.asset_...
[ "def", "reduce_also", "(", "self", ",", "sitecol", ")", ":", "array", "=", "[", "]", "asset_refs", "=", "[", "]", "for", "idx", ",", "sid", "in", "enumerate", "(", "sitecol", ".", "sids", ")", ":", "mask", "=", "self", ".", "array", "[", "'site_id'...
:returns: a reduced AssetCollection on the given sitecol NB: diffently from .reduce, also the SiteCollection is reduced and turned into a complete site collection.
[ ":", "returns", ":", "a", "reduced", "AssetCollection", "on", "the", "given", "sitecol", "NB", ":", "diffently", "from", ".", "reduce", "also", "the", "SiteCollection", "is", "reduced", "and", "turned", "into", "a", "complete", "site", "collection", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L515-L536
gem/oq-engine
openquake/risklib/asset.py
Exposure.read
def read(fnames, calculation_mode='', region_constraint='', ignore_missing_costs=(), asset_nodes=False, check_dupl=True, tagcol=None, by_country=False): """ Call `Exposure.read(fname)` to get an :class:`Exposure` instance keeping all the assets in memory or `Exp...
python
def read(fnames, calculation_mode='', region_constraint='', ignore_missing_costs=(), asset_nodes=False, check_dupl=True, tagcol=None, by_country=False): if by_country: prefix2cc = countries.from_exposures( os.path.basename(f) for f in fnames) ...
[ "def", "read", "(", "fnames", ",", "calculation_mode", "=", "''", ",", "region_constraint", "=", "''", ",", "ignore_missing_costs", "=", "(", ")", ",", "asset_nodes", "=", "False", ",", "check_dupl", "=", "True", ",", "tagcol", "=", "None", ",", "by_countr...
Call `Exposure.read(fname)` to get an :class:`Exposure` instance keeping all the assets in memory or `Exposure.read(fname, asset_nodes=True)` to get an iterator over Node objects (one Node for each asset).
[ "Call", "Exposure", ".", "read", "(", "fname", ")", "to", "get", "an", ":", "class", ":", "Exposure", "instance", "keeping", "all", "the", "assets", "in", "memory", "or", "Exposure", ".", "read", "(", "fname", "asset_nodes", "=", "True", ")", "to", "ge...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L792-L836
gem/oq-engine
openquake/risklib/asset.py
Exposure._csv_header
def _csv_header(self): """ Extract the expected CSV header from the exposure metadata """ fields = ['id', 'number', 'taxonomy', 'lon', 'lat'] for name in self.cost_types['name']: fields.append(name) if 'per_area' in self.cost_types['type']: fields....
python
def _csv_header(self): fields = ['id', 'number', 'taxonomy', 'lon', 'lat'] for name in self.cost_types['name']: fields.append(name) if 'per_area' in self.cost_types['type']: fields.append('area') if self.occupancy_periods: fields.extend(self.o...
[ "def", "_csv_header", "(", "self", ")", ":", "fields", "=", "[", "'id'", ",", "'number'", ",", "'taxonomy'", ",", "'lon'", ",", "'lat'", "]", "for", "name", "in", "self", ".", "cost_types", "[", "'name'", "]", ":", "fields", ".", "append", "(", "name...
Extract the expected CSV header from the exposure metadata
[ "Extract", "the", "expected", "CSV", "header", "from", "the", "exposure", "metadata" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L885-L897
gem/oq-engine
openquake/risklib/asset.py
Exposure._read_csv
def _read_csv(self): """ :yields: asset nodes """ expected_header = self._csv_header() for fname in self.datafiles: with open(fname, encoding='utf-8') as f: fields = next(csv.reader(f)) header = set(fields) if len(header...
python
def _read_csv(self): expected_header = self._csv_header() for fname in self.datafiles: with open(fname, encoding='utf-8') as f: fields = next(csv.reader(f)) header = set(fields) if len(header) < len(fields): raise I...
[ "def", "_read_csv", "(", "self", ")", ":", "expected_header", "=", "self", ".", "_csv_header", "(", ")", "for", "fname", "in", "self", ".", "datafiles", ":", "with", "open", "(", "fname", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "fields", ...
:yields: asset nodes
[ ":", "yields", ":", "asset", "nodes" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L899-L947
gem/oq-engine
openquake/risklib/asset.py
Exposure.get_mesh_assets_by_site
def get_mesh_assets_by_site(self): """ :returns: (Mesh instance, assets_by_site list) """ assets_by_loc = general.groupby(self, key=lambda a: a.location) mesh = geo.Mesh.from_coords(list(assets_by_loc)) assets_by_site = [ assets_by_loc[lonlat] for lonlat in zi...
python
def get_mesh_assets_by_site(self): assets_by_loc = general.groupby(self, key=lambda a: a.location) mesh = geo.Mesh.from_coords(list(assets_by_loc)) assets_by_site = [ assets_by_loc[lonlat] for lonlat in zip(mesh.lons, mesh.lats)] return mesh, assets_by_site
[ "def", "get_mesh_assets_by_site", "(", "self", ")", ":", "assets_by_loc", "=", "general", ".", "groupby", "(", "self", ",", "key", "=", "lambda", "a", ":", "a", ".", "location", ")", "mesh", "=", "geo", ".", "Mesh", ".", "from_coords", "(", "list", "("...
:returns: (Mesh instance, assets_by_site list)
[ ":", "returns", ":", "(", "Mesh", "instance", "assets_by_site", "list", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L1049-L1057
gem/oq-engine
openquake/risklib/riskmodels.py
get_risk_files
def get_risk_files(inputs): """ :param inputs: a dictionary key -> path name :returns: a pair (file_type, {risk_type: path}) """ rfs = {} job_ini = inputs['job_ini'] for key in inputs: if key == 'fragility': # backward compatibily for .ini files with key fragility_file ...
python
def get_risk_files(inputs): rfs = {} job_ini = inputs['job_ini'] for key in inputs: if key == 'fragility': rfs['fragility/structural'] = inputs[ 'structural_fragility'] = inputs[key] del inputs['fragility'] elif key.endsw...
[ "def", "get_risk_files", "(", "inputs", ")", ":", "rfs", "=", "{", "}", "job_ini", "=", "inputs", "[", "'job_ini'", "]", "for", "key", "in", "inputs", ":", "if", "key", "==", "'fragility'", ":", "# backward compatibily for .ini files with key fragility_file", "#...
:param inputs: a dictionary key -> path name :returns: a pair (file_type, {risk_type: path})
[ ":", "param", "inputs", ":", "a", "dictionary", "key", "-", ">", "path", "name", ":", "returns", ":", "a", "pair", "(", "file_type", "{", "risk_type", ":", "path", "}", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/riskmodels.py#L39-L59
gem/oq-engine
openquake/risklib/riskmodels.py
build_vf_node
def build_vf_node(vf): """ Convert a VulnerabilityFunction object into a Node suitable for XML conversion. """ nodes = [Node('imls', {'imt': vf.imt}, vf.imls), Node('meanLRs', {}, vf.mean_loss_ratios), Node('covLRs', {}, vf.covs)] return Node( 'vulnerabilityFunc...
python
def build_vf_node(vf): nodes = [Node('imls', {'imt': vf.imt}, vf.imls), Node('meanLRs', {}, vf.mean_loss_ratios), Node('covLRs', {}, vf.covs)] return Node( 'vulnerabilityFunction', {'id': vf.id, 'dist': vf.distribution_name}, nodes=nodes)
[ "def", "build_vf_node", "(", "vf", ")", ":", "nodes", "=", "[", "Node", "(", "'imls'", ",", "{", "'imt'", ":", "vf", ".", "imt", "}", ",", "vf", ".", "imls", ")", ",", "Node", "(", "'meanLRs'", ",", "{", "}", ",", "vf", ".", "mean_loss_ratios", ...
Convert a VulnerabilityFunction object into a Node suitable for XML conversion.
[ "Convert", "a", "VulnerabilityFunction", "object", "into", "a", "Node", "suitable", "for", "XML", "conversion", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/riskmodels.py#L69-L79
gem/oq-engine
openquake/risklib/riskmodels.py
get_risk_models
def get_risk_models(oqparam, kind='vulnerability vulnerability_retrofitted ' 'fragility consequence'): """ :param oqparam: an OqParam instance :param kind: a space-separated string with the kinds of risk models to read :returns: a dictionary riskid -> loss_typ...
python
def get_risk_models(oqparam, kind='vulnerability vulnerability_retrofitted ' 'fragility consequence'): kinds = kind.split() rmodels = AccumDict() for kind in kinds: for key in sorted(oqparam.inputs): mo = re.match('(occupants|%s)_%s$' % (COST_TYPE_REGEX, kind), k...
[ "def", "get_risk_models", "(", "oqparam", ",", "kind", "=", "'vulnerability vulnerability_retrofitted '", "'fragility consequence'", ")", ":", "kinds", "=", "kind", ".", "split", "(", ")", "rmodels", "=", "AccumDict", "(", ")", "for", "kind", "in", "kinds", ":",...
:param oqparam: an OqParam instance :param kind: a space-separated string with the kinds of risk models to read :returns: a dictionary riskid -> loss_type, kind -> function
[ ":", "param", "oqparam", ":", "an", "OqParam", "instance", ":", "param", "kind", ":", "a", "space", "-", "separated", "string", "with", "the", "kinds", "of", "risk", "models", "to", "read", ":", "returns", ":", "a", "dictionary", "riskid", "-", ">", "l...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/riskmodels.py#L82-L150
gem/oq-engine
openquake/risklib/riskmodels.py
rescale
def rescale(curves, values): """ Multiply the losses in each curve of kind (losses, poes) by the corresponding value. :param curves: an array of shape (A, 2, C) :param values: an array of shape (A,) """ A, _, C = curves.shape assert A == len(values), (A, len(values)) array = numpy.z...
python
def rescale(curves, values): A, _, C = curves.shape assert A == len(values), (A, len(values)) array = numpy.zeros((A, C), loss_poe_dt) array['loss'] = [c * v for c, v in zip(curves[:, 0], values)] array['poe'] = curves[:, 1] return array
[ "def", "rescale", "(", "curves", ",", "values", ")", ":", "A", ",", "_", ",", "C", "=", "curves", ".", "shape", "assert", "A", "==", "len", "(", "values", ")", ",", "(", "A", ",", "len", "(", "values", ")", ")", "array", "=", "numpy", ".", "z...
Multiply the losses in each curve of kind (losses, poes) by the corresponding value. :param curves: an array of shape (A, 2, C) :param values: an array of shape (A,)
[ "Multiply", "the", "losses", "in", "each", "curve", "of", "kind", "(", "losses", "poes", ")", "by", "the", "corresponding", "value", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/riskmodels.py#L220-L233
gem/oq-engine
openquake/risklib/riskmodels.py
get_riskmodel
def get_riskmodel(taxonomy, oqparam, **extra): """ Return an instance of the correct riskmodel class, depending on the attribute `calculation_mode` of the object `oqparam`. :param taxonomy: a taxonomy string :param oqparam: an object containing the parameters needed by the riskmodel...
python
def get_riskmodel(taxonomy, oqparam, **extra): riskmodel_class = registry[oqparam.calculation_mode] argnames = inspect.getfullargspec(riskmodel_class.__init__).args[3:] known_args = set(name for name, value in inspect.getmembers(oqparam.__class__) if...
[ "def", "get_riskmodel", "(", "taxonomy", ",", "oqparam", ",", "*", "*", "extra", ")", ":", "riskmodel_class", "=", "registry", "[", "oqparam", ".", "calculation_mode", "]", "# arguments needed to instantiate the riskmodel class", "argnames", "=", "inspect", ".", "ge...
Return an instance of the correct riskmodel class, depending on the attribute `calculation_mode` of the object `oqparam`. :param taxonomy: a taxonomy string :param oqparam: an object containing the parameters needed by the riskmodel class :param extra: extra parameters to pass t...
[ "Return", "an", "instance", "of", "the", "correct", "riskmodel", "class", "depending", "on", "the", "attribute", "calculation_mode", "of", "the", "object", "oqparam", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/riskmodels.py#L548-L580
gem/oq-engine
openquake/risklib/riskmodels.py
RiskModel.get_loss_types
def get_loss_types(self, imt): """ :param imt: Intensity Measure Type string :returns: loss types with risk functions of the given imt """ return [lt for lt in self.loss_types if self.risk_functions[lt].imt == imt]
python
def get_loss_types(self, imt): return [lt for lt in self.loss_types if self.risk_functions[lt].imt == imt]
[ "def", "get_loss_types", "(", "self", ",", "imt", ")", ":", "return", "[", "lt", "for", "lt", "in", "self", ".", "loss_types", "if", "self", ".", "risk_functions", "[", "lt", "]", ".", "imt", "==", "imt", "]" ]
:param imt: Intensity Measure Type string :returns: loss types with risk functions of the given imt
[ ":", "param", "imt", ":", "Intensity", "Measure", "Type", "string", ":", "returns", ":", "loss", "types", "with", "risk", "functions", "of", "the", "given", "imt" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/riskmodels.py#L193-L199
gem/oq-engine
openquake/hmtk/plotting/beachball.py
Beach
def Beach(fm, linewidth=2, facecolor='b', bgcolor='w', edgecolor='k', alpha=1.0, xy=(0, 0), width=200, size=100, nofill=False, zorder=100, axes=None): """ Return a beach ball as a collection which can be connected to an current matplotlib axes instance (ax.add_collection). S1, D1, a...
python
def Beach(fm, linewidth=2, facecolor='b', bgcolor='w', edgecolor='k', alpha=1.0, xy=(0, 0), width=200, size=100, nofill=False, zorder=100, axes=None): try: assert(len(width) == 2) except TypeError: width = (width, width) mt = None np1 = None if isinstanc...
[ "def", "Beach", "(", "fm", ",", "linewidth", "=", "2", ",", "facecolor", "=", "'b'", ",", "bgcolor", "=", "'w'", ",", "edgecolor", "=", "'k'", ",", "alpha", "=", "1.0", ",", "xy", "=", "(", "0", ",", "0", ")", ",", "width", "=", "200", ",", "...
Return a beach ball as a collection which can be connected to an current matplotlib axes instance (ax.add_collection). S1, D1, and R1, the strike, dip and rake of one of the focal planes, can be vectors of multiple focal mechanisms. :param fm: Focal mechanism that is either number of mechanisms (NM) b...
[ "Return", "a", "beach", "ball", "as", "a", "collection", "which", "can", "be", "connected", "to", "an", "current", "matplotlib", "axes", "instance", "(", "ax", ".", "add_collection", ")", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L38-L144
gem/oq-engine
openquake/hmtk/plotting/beachball.py
Beachball
def Beachball(fm, linewidth=2, facecolor='b', bgcolor='w', edgecolor='k', alpha=1.0, xy=(0, 0), width=200, size=100, nofill=False, zorder=100, outfile=None, format=None, fig=None): """ Draws a beach ball diagram of an earthquake focal mechanism. S1, D1, and R1, the strike, dip a...
python
def Beachball(fm, linewidth=2, facecolor='b', bgcolor='w', edgecolor='k', alpha=1.0, xy=(0, 0), width=200, size=100, nofill=False, zorder=100, outfile=None, format=None, fig=None): plot_width = width * 0.95 if not fig: fig = plt.figure(figsize=(3, 3), dpi=100) ...
[ "def", "Beachball", "(", "fm", ",", "linewidth", "=", "2", ",", "facecolor", "=", "'b'", ",", "bgcolor", "=", "'w'", ",", "edgecolor", "=", "'k'", ",", "alpha", "=", "1.0", ",", "xy", "=", "(", "0", ",", "0", ")", ",", "width", "=", "200", ",",...
Draws a beach ball diagram of an earthquake focal mechanism. S1, D1, and R1, the strike, dip and rake of one of the focal planes, can be vectors of multiple focal mechanisms. :param fm: Focal mechanism that is either number of mechanisms (NM) by 3 (strike, dip, and rake) or NM x 6 (M11, M22, M33, ...
[ "Draws", "a", "beach", "ball", "diagram", "of", "an", "earthquake", "focal", "mechanism", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L147-L230
gem/oq-engine
openquake/hmtk/plotting/beachball.py
plotMT
def plotMT(T, N, P, size=200, plot_zerotrace=True, x0=0, y0=0, xy=(0, 0), width=200): """ Uses a principal axis T, N and P to draw a beach ball plot. :param ax: axis object of a matplotlib figure :param T: :class:`~PrincipalAxis` :param N: :class:`~PrincipalAxis` :param P: :class:`~P...
python
def plotMT(T, N, P, size=200, plot_zerotrace=True, x0=0, y0=0, xy=(0, 0), width=200): try: assert(len(width) == 2) except TypeError: width = (width, width) collect = [] colors = [] res = [value / float(size) for value in width] b = 1 big_iso = 0 j = 1...
[ "def", "plotMT", "(", "T", ",", "N", ",", "P", ",", "size", "=", "200", ",", "plot_zerotrace", "=", "True", ",", "x0", "=", "0", ",", "y0", "=", "0", ",", "xy", "=", "(", "0", ",", "0", ")", ",", "width", "=", "200", ")", ":", "# check if o...
Uses a principal axis T, N and P to draw a beach ball plot. :param ax: axis object of a matplotlib figure :param T: :class:`~PrincipalAxis` :param N: :class:`~PrincipalAxis` :param P: :class:`~PrincipalAxis` Adapted from ps_tensor / utilmeca.c / `Generic Mapping Tools (GMT)`_. .. _`Generic Ma...
[ "Uses", "a", "principal", "axis", "T", "N", "and", "P", "to", "draw", "a", "beach", "ball", "plot", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L233-L553
gem/oq-engine
openquake/hmtk/plotting/beachball.py
plotDC
def plotDC(np1, size=200, xy=(0, 0), width=200): """ Uses one nodal plane of a double couple to draw a beach ball plot. :param ax: axis object of a matplotlib figure :param np1: :class:`~NodalPlane` Adapted from MATLAB script `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.h...
python
def plotDC(np1, size=200, xy=(0, 0), width=200): try: assert(len(width) == 2) except TypeError: width = (width, width) S1 = np1.strike D1 = np1.dip R1 = np1.rake M = 0 if R1 > 180: R1 -= 180 M = 1 if R1 < 0: R1 += 180 M = 1 ...
[ "def", "plotDC", "(", "np1", ",", "size", "=", "200", ",", "xy", "=", "(", "0", ",", "0", ")", ",", "width", "=", "200", ")", ":", "# check if one or two widths are specified (Circle or Ellipse)", "try", ":", "assert", "(", "len", "(", "width", ")", "=="...
Uses one nodal plane of a double couple to draw a beach ball plot. :param ax: axis object of a matplotlib figure :param np1: :class:`~NodalPlane` Adapted from MATLAB script `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_ written by Andy Michael and Oliver Boyd.
[ "Uses", "one", "nodal", "plane", "of", "a", "double", "couple", "to", "draw", "a", "beach", "ball", "plot", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L556-L641
gem/oq-engine
openquake/hmtk/plotting/beachball.py
StrikeDip
def StrikeDip(n, e, u): """ Finds strike and dip of plane given normal vector having components n, e, and u. Adapted from MATLAB script `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_ written by Andy Michael and Oliver Boyd. """ r2d = 180 / np.pi if u < 0:...
python
def StrikeDip(n, e, u): r2d = 180 / np.pi if u < 0: n = -n e = -e u = -u strike = np.arctan2(e, n) * r2d strike = strike - 90 while strike >= 360: strike = strike - 360 while strike < 0: strike = strike + 360 x = np.sqrt(np.power(n, 2) + np.power...
[ "def", "StrikeDip", "(", "n", ",", "e", ",", "u", ")", ":", "r2d", "=", "180", "/", "np", ".", "pi", "if", "u", "<", "0", ":", "n", "=", "-", "n", "e", "=", "-", "e", "u", "=", "-", "u", "strike", "=", "np", ".", "arctan2", "(", "e", ...
Finds strike and dip of plane given normal vector having components n, e, and u. Adapted from MATLAB script `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_ written by Andy Michael and Oliver Boyd.
[ "Finds", "strike", "and", "dip", "of", "plane", "given", "normal", "vector", "having", "components", "n", "e", "and", "u", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L669-L692
gem/oq-engine
openquake/hmtk/plotting/beachball.py
AuxPlane
def AuxPlane(s1, d1, r1): """ Get Strike and dip of second plane. Adapted from MATLAB script `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_ written by Andy Michael and Oliver Boyd. """ r2d = 180 / np.pi z = (s1 + 90) / r2d z2 = d1 / r2d z3 = r1 / r2d...
python
def AuxPlane(s1, d1, r1): r2d = 180 / np.pi z = (s1 + 90) / r2d z2 = d1 / r2d z3 = r1 / r2d sl1 = -np.cos(z3) * np.cos(z) - np.sin(z3) * np.sin(z) * np.cos(z2) sl2 = np.cos(z3) * np.sin(z) - np.sin(z3) * np.cos(z) * np.cos(z2) sl3 = np.sin(z3) * np.sin(z2) (strike, dip) = Stri...
[ "def", "AuxPlane", "(", "s1", ",", "d1", ",", "r1", ")", ":", "r2d", "=", "180", "/", "np", ".", "pi", "z", "=", "(", "s1", "+", "90", ")", "/", "r2d", "z2", "=", "d1", "/", "r2d", "z3", "=", "r1", "/", "r2d", "# slick vector in plane 1", "sl...
Get Strike and dip of second plane. Adapted from MATLAB script `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_ written by Andy Michael and Oliver Boyd.
[ "Get", "Strike", "and", "dip", "of", "second", "plane", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L695-L729
gem/oq-engine
openquake/hmtk/plotting/beachball.py
MT2Plane
def MT2Plane(mt): """ Calculates a nodal plane of a given moment tensor. :param mt: :class:`~MomentTensor` :return: :class:`~NodalPlane` Adapted from MATLAB script `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_ written by Andy Michael and Oliver Boyd. """ ...
python
def MT2Plane(mt): (d, v) = np.linalg.eig(mt.mt) D = np.array([d[1], d[0], d[2]]) V = np.array([[v[1, 1], -v[1, 0], -v[1, 2]], [v[2, 1], -v[2, 0], -v[2, 2]], [-v[0, 1], v[0, 0], v[0, 2]]]) IMAX = D.argmax() IMIN = D.argmin() AE = (V[:, IMAX] + V[:, IMIN]) ...
[ "def", "MT2Plane", "(", "mt", ")", ":", "(", "d", ",", "v", ")", "=", "np", ".", "linalg", ".", "eig", "(", "mt", ".", "mt", ")", "D", "=", "np", ".", "array", "(", "[", "d", "[", "1", "]", ",", "d", "[", "0", "]", ",", "d", "[", "2",...
Calculates a nodal plane of a given moment tensor. :param mt: :class:`~MomentTensor` :return: :class:`~NodalPlane` Adapted from MATLAB script `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_ written by Andy Michael and Oliver Boyd.
[ "Calculates", "a", "nodal", "plane", "of", "a", "given", "moment", "tensor", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L732-L766
gem/oq-engine
openquake/hmtk/plotting/beachball.py
TDL
def TDL(AN, BN): """ Helper function for MT2Plane. Adapted from MATLAB script `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_ written by Andy Michael and Oliver Boyd. """ XN = AN[0] YN = AN[1] ZN = AN[2] XE = BN[0] YE = BN[1] ZE = BN[2] AAA...
python
def TDL(AN, BN): XN = AN[0] YN = AN[1] ZN = AN[2] XE = BN[0] YE = BN[1] ZE = BN[2] AAA = 1.0 / (1000000) CON = 57.2957795 if np.fabs(ZN) < AAA: FD = 90. AXN = np.fabs(XN) if AXN > 1.0: AXN = 1.0 FT = np.arcsin(AXN) * CON ST = -...
[ "def", "TDL", "(", "AN", ",", "BN", ")", ":", "XN", "=", "AN", "[", "0", "]", "YN", "=", "AN", "[", "1", "]", "ZN", "=", "AN", "[", "2", "]", "XE", "=", "BN", "[", "0", "]", "YE", "=", "BN", "[", "1", "]", "ZE", "=", "BN", "[", "2",...
Helper function for MT2Plane. Adapted from MATLAB script `bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_ written by Andy Michael and Oliver Boyd.
[ "Helper", "function", "for", "MT2Plane", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L769-L849
gem/oq-engine
openquake/hmtk/plotting/beachball.py
MT2Axes
def MT2Axes(mt): """ Calculates the principal axes of a given moment tensor. :param mt: :class:`~MomentTensor` :return: tuple of :class:`~PrincipalAxis` T, N and P Adapted from ps_tensor / utilmeca.c / `Generic Mapping Tools (GMT) <http://gmt.soest.hawaii.edu>`_. """ (D, V) = np.linalg...
python
def MT2Axes(mt): (D, V) = np.linalg.eigh(mt.mt) pl = np.arcsin(-V[0]) az = np.arctan2(V[2], -V[1]) for i in range(0, 3): if pl[i] <= 0: pl[i] = -pl[i] az[i] += np.pi if az[i] < 0: az[i] += 2 * np.pi if az[i] > 2 * np.pi: az[i] ...
[ "def", "MT2Axes", "(", "mt", ")", ":", "(", "D", ",", "V", ")", "=", "np", ".", "linalg", ".", "eigh", "(", "mt", ".", "mt", ")", "pl", "=", "np", ".", "arcsin", "(", "-", "V", "[", "0", "]", ")", "az", "=", "np", ".", "arctan2", "(", "...
Calculates the principal axes of a given moment tensor. :param mt: :class:`~MomentTensor` :return: tuple of :class:`~PrincipalAxis` T, N and P Adapted from ps_tensor / utilmeca.c / `Generic Mapping Tools (GMT) <http://gmt.soest.hawaii.edu>`_.
[ "Calculates", "the", "principal", "axes", "of", "a", "given", "moment", "tensor", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L852-L879
gem/oq-engine
openquake/hmtk/strain/strain_utils.py
calculate_taper_function
def calculate_taper_function(obs_threshold_moment, sel_threshold_moment, corner_moment, beta): ''' Calculates the tapering function of the tapered Gutenberg & Richter model: as described in Bird & Liu (2007):: taper_function = (M_0(M_T) / M_0(M_T^{CMT}))^-beta x exp((M_0(m...
python
def calculate_taper_function(obs_threshold_moment, sel_threshold_moment, corner_moment, beta): argument = (obs_threshold_moment - sel_threshold_moment) /\ corner_moment if argument < -100.0: g_function = 0.0 else: g_function = ((sel_threshold_moment ...
[ "def", "calculate_taper_function", "(", "obs_threshold_moment", ",", "sel_threshold_moment", ",", "corner_moment", ",", "beta", ")", ":", "argument", "=", "(", "obs_threshold_moment", "-", "sel_threshold_moment", ")", "/", "corner_moment", "if", "argument", "<", "-", ...
Calculates the tapering function of the tapered Gutenberg & Richter model: as described in Bird & Liu (2007):: taper_function = (M_0(M_T) / M_0(M_T^{CMT}))^-beta x exp((M_0(m_T^CMT) - M_0(m_T)) / M_0(m_c)) :param numpy.ndarray obs_threshold_moment: Moment of the threshold magnitude of th...
[ "Calculates", "the", "tapering", "function", "of", "the", "tapered", "Gutenberg", "&", "Richter", "model", ":", "as", "described", "in", "Bird", "&", "Liu", "(", "2007", ")", "::" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/strain/strain_utils.py#L81-L108
gem/oq-engine
openquake/hmtk/strain/strain_utils.py
tapered_gutenberg_richter_cdf
def tapered_gutenberg_richter_cdf(moment, moment_threshold, beta, corner_moment): ''' Tapered Gutenberg Richter Cumulative Density Function :param float or numpy.ndarray moment: Moment for calculation of rate :param float or numpy.ndarray moment_threshold: ...
python
def tapered_gutenberg_richter_cdf(moment, moment_threshold, beta, corner_moment): cdf = np.exp((moment_threshold - moment) / corner_moment) return ((moment / moment_threshold) ** (-beta)) * cdf
[ "def", "tapered_gutenberg_richter_cdf", "(", "moment", ",", "moment_threshold", ",", "beta", ",", "corner_moment", ")", ":", "cdf", "=", "np", ".", "exp", "(", "(", "moment_threshold", "-", "moment", ")", "/", "corner_moment", ")", "return", "(", "(", "momen...
Tapered Gutenberg Richter Cumulative Density Function :param float or numpy.ndarray moment: Moment for calculation of rate :param float or numpy.ndarray moment_threshold: Threshold Moment of the distribution (moment rate essentially!) :param float beta: Beta value (b * ln(10.)) of...
[ "Tapered", "Gutenberg", "Richter", "Cumulative", "Density", "Function" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/strain/strain_utils.py#L111-L134
gem/oq-engine
openquake/hmtk/strain/strain_utils.py
tapered_gutenberg_richter_pdf
def tapered_gutenberg_richter_pdf(moment, moment_threshold, beta, corner_moment): ''' Tapered Gutenberg-Richter Probability Density Function :param float or numpy.ndarray moment: Moment for calculation of rate :param float or numpy.ndarray moment_threshold: ...
python
def tapered_gutenberg_richter_pdf(moment, moment_threshold, beta, corner_moment): return ((beta / moment + 1. / corner_moment) * tapered_gutenberg_richter_cdf(moment, moment_threshold, beta, corner_moment))
[ "def", "tapered_gutenberg_richter_pdf", "(", "moment", ",", "moment_threshold", ",", "beta", ",", "corner_moment", ")", ":", "return", "(", "(", "beta", "/", "moment", "+", "1.", "/", "corner_moment", ")", "*", "tapered_gutenberg_richter_cdf", "(", "moment", ","...
Tapered Gutenberg-Richter Probability Density Function :param float or numpy.ndarray moment: Moment for calculation of rate :param float or numpy.ndarray moment_threshold: Threshold Moment of the distribution (moment rate essentially!) :param float beta: Beta value (b * ln(10.)) o...
[ "Tapered", "Gutenberg", "-", "Richter", "Probability", "Density", "Function" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/strain/strain_utils.py#L137-L159
gem/oq-engine
openquake/engine/export/core.py
check_version
def check_version(dstore): """ :param dstore: a DataStore instance :returns: a message if the stored version is different from the current version """ ds_version = dstore.hdf5.attrs['engine_version'] if ds_version != __version__: return (': the datastore is at version %s, but the...
python
def check_version(dstore): ds_version = dstore.hdf5.attrs['engine_version'] if ds_version != __version__: return (': the datastore is at version %s, but the exporter at ' 'version %s' % (ds_version, __version__)) else: return ''
[ "def", "check_version", "(", "dstore", ")", ":", "ds_version", "=", "dstore", ".", "hdf5", ".", "attrs", "[", "'engine_version'", "]", "if", "ds_version", "!=", "__version__", ":", "return", "(", "': the datastore is at version %s, but the exporter at '", "'version %s...
:param dstore: a DataStore instance :returns: a message if the stored version is different from the current version
[ ":", "param", "dstore", ":", "a", "DataStore", "instance", ":", "returns", ":", "a", "message", "if", "the", "stored", "version", "is", "different", "from", "the", "current", "version" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/export/core.py#L37-L48
gem/oq-engine
openquake/engine/export/core.py
export_from_db
def export_from_db(output_key, calc_id, datadir, target): """ :param output_key: a pair (ds_key, fmt) :param calc_id: calculation ID :param datadir: directory containing the datastore :param target: directory, temporary when called from the engine server :returns: the list of exported path names...
python
def export_from_db(output_key, calc_id, datadir, target): makedirs(target) export.from_db = True ds_key, fmt = output_key with datastore.read(calc_id, datadir=datadir) as dstore: dstore.export_dir = target try: exported = export(output_key, dstore) except Excepti...
[ "def", "export_from_db", "(", "output_key", ",", "calc_id", ",", "datadir", ",", "target", ")", ":", "makedirs", "(", "target", ")", "export", ".", "from_db", "=", "True", "ds_key", ",", "fmt", "=", "output_key", "with", "datastore", ".", "read", "(", "c...
:param output_key: a pair (ds_key, fmt) :param calc_id: calculation ID :param datadir: directory containing the datastore :param target: directory, temporary when called from the engine server :returns: the list of exported path names
[ ":", "param", "output_key", ":", "a", "pair", "(", "ds_key", "fmt", ")", ":", "param", "calc_id", ":", "calculation", "ID", ":", "param", "datadir", ":", "directory", "containing", "the", "datastore", ":", "param", "target", ":", "directory", "temporary", ...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/export/core.py#L51-L73
gem/oq-engine
openquake/engine/export/core.py
makedirs
def makedirs(path): """ Make all of the directories in the ``path`` using `os.makedirs`. """ if os.path.exists(path): if not os.path.isdir(path): # If it's not a directory, we can't do anything. # This is a problem raise RuntimeError('%s already exists and is ...
python
def makedirs(path): if os.path.exists(path): if not os.path.isdir(path): raise RuntimeError('%s already exists and is not a directory.' % path) else: os.makedirs(path)
[ "def", "makedirs", "(", "path", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "# If it's not a directory, we can't do anything.", "# This is a problem", "raise", ...
Make all of the directories in the ``path`` using `os.makedirs`.
[ "Make", "all", "of", "the", "directories", "in", "the", "path", "using", "os", ".", "makedirs", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/export/core.py#L80-L91
gem/oq-engine
openquake/engine/export/core.py
get_outkey
def get_outkey(dskey, export_types): """ Extract the first pair (dskey, exptype) found in export """ for exptype in export_types: if (dskey, exptype) in export: return (dskey, exptype)
python
def get_outkey(dskey, export_types): for exptype in export_types: if (dskey, exptype) in export: return (dskey, exptype)
[ "def", "get_outkey", "(", "dskey", ",", "export_types", ")", ":", "for", "exptype", "in", "export_types", ":", "if", "(", "dskey", ",", "exptype", ")", "in", "export", ":", "return", "(", "dskey", ",", "exptype", ")" ]
Extract the first pair (dskey, exptype) found in export
[ "Extract", "the", "first", "pair", "(", "dskey", "exptype", ")", "found", "in", "export" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/export/core.py#L106-L112
gem/oq-engine
openquake/engine/export/core.py
export_output
def export_output(dskey, calc_id, datadir, target_dir, export_types): """ Simple UI wrapper around :func:`openquake.engine.export.core.export_from_db` yielding a summary of files exported, if any. """ outkey = get_outkey(dskey, export_types.split(',')) if export_types and not outkey: ...
python
def export_output(dskey, calc_id, datadir, target_dir, export_types): outkey = get_outkey(dskey, export_types.split(',')) if export_types and not outkey: yield 'There is no exporter for %s, %s' % (dskey, export_types) return yield from export_from_db(outkey, calc_id, datadir, target_dir...
[ "def", "export_output", "(", "dskey", ",", "calc_id", ",", "datadir", ",", "target_dir", ",", "export_types", ")", ":", "outkey", "=", "get_outkey", "(", "dskey", ",", "export_types", ".", "split", "(", "','", ")", ")", "if", "export_types", "and", "not", ...
Simple UI wrapper around :func:`openquake.engine.export.core.export_from_db` yielding a summary of files exported, if any.
[ "Simple", "UI", "wrapper", "around", ":", "func", ":", "openquake", ".", "engine", ".", "export", ".", "core", ".", "export_from_db", "yielding", "a", "summary", "of", "files", "exported", "if", "any", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/export/core.py#L115-L125
gem/oq-engine
openquake/hmtk/seismicity/max_magnitude/base.py
_get_observed_mmax
def _get_observed_mmax(catalogue, config): '''Check see if observed mmax values are input, if not then take from the catalogue''' if config['input_mmax']: obsmax = config['input_mmax'] if config['input_mmax_uncertainty']: return config['input_mmax'], config['input_mmax_uncertaint...
python
def _get_observed_mmax(catalogue, config): if config['input_mmax']: obsmax = config['input_mmax'] if config['input_mmax_uncertainty']: return config['input_mmax'], config['input_mmax_uncertainty'] else: raise ValueError('Input mmax uncertainty must be specified!'...
[ "def", "_get_observed_mmax", "(", "catalogue", ",", "config", ")", ":", "if", "config", "[", "'input_mmax'", "]", ":", "obsmax", "=", "config", "[", "'input_mmax'", "]", "if", "config", "[", "'input_mmax_uncertainty'", "]", ":", "return", "config", "[", "'in...
Check see if observed mmax values are input, if not then take from the catalogue
[ "Check", "see", "if", "observed", "mmax", "values", "are", "input", "if", "not", "then", "take", "from", "the", "catalogue" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/max_magnitude/base.py#L57-L83
gem/oq-engine
openquake/hmtk/seismicity/max_magnitude/base.py
_get_magnitude_vector_properties
def _get_magnitude_vector_properties(catalogue, config): '''If an input minimum magnitude is given then consider catalogue only above the minimum magnitude - returns corresponding properties''' mmin = config.get('input_mmin', np.min(catalogue['magnitude'])) neq = np.float(np.sum(catalogue['magnitude'] ...
python
def _get_magnitude_vector_properties(catalogue, config): mmin = config.get('input_mmin', np.min(catalogue['magnitude'])) neq = np.float(np.sum(catalogue['magnitude'] >= mmin - 1.E-7)) return neq, mmin
[ "def", "_get_magnitude_vector_properties", "(", "catalogue", ",", "config", ")", ":", "mmin", "=", "config", ".", "get", "(", "'input_mmin'", ",", "np", ".", "min", "(", "catalogue", "[", "'magnitude'", "]", ")", ")", "neq", "=", "np", ".", "float", "(",...
If an input minimum magnitude is given then consider catalogue only above the minimum magnitude - returns corresponding properties
[ "If", "an", "input", "minimum", "magnitude", "is", "given", "then", "consider", "catalogue", "only", "above", "the", "minimum", "magnitude", "-", "returns", "corresponding", "properties" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/max_magnitude/base.py#L104-L110
gem/oq-engine
openquake/hazardlib/gsim/campbell_1997.py
Campbell1997.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. """ R = (dists.rrup) M = rup.mag # get constants S...
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): R = (dists.rrup) M = rup.mag Ssr = self.get_Ssr_term(sites.vs30) Shr = self.get_Shr_term(sites.vs30) rake = rup.rake F = self.get_fault_term(rake) mean = -3.512 + (0....
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "R", "=", "(", "dists", ".", "rrup", ")", "M", "=", "rup", ".", "mag", "# get constants", "Ssr", "=", "self", ".", "get_Ssr...
See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
[ "See", ":", "meth", ":", "superclass", "method", "<", ".", "base", ".", "GroundShakingIntensityModel", ".", "get_mean_and_stddevs", ">", "for", "spec", "of", "input", "and", "result", "values", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_1997.py#L71-L92
gem/oq-engine
openquake/hazardlib/gsim/campbell_1997.py
Campbell1997.get_fault_term
def get_fault_term(self, rake): """ Returns coefficient for faulting style (pg 156) """ rake = rake + 360 if rake < 0 else rake if (rake >= 45) & (rake <= 135): f = 1. elif (rake >= 225) & (rake <= 315): f = 0.5 else: f = 0. ...
python
def get_fault_term(self, rake): rake = rake + 360 if rake < 0 else rake if (rake >= 45) & (rake <= 135): f = 1. elif (rake >= 225) & (rake <= 315): f = 0.5 else: f = 0. return f
[ "def", "get_fault_term", "(", "self", ",", "rake", ")", ":", "rake", "=", "rake", "+", "360", "if", "rake", "<", "0", "else", "rake", "if", "(", "rake", ">=", "45", ")", "&", "(", "rake", "<=", "135", ")", ":", "f", "=", "1.", "elif", "(", "r...
Returns coefficient for faulting style (pg 156)
[ "Returns", "coefficient", "for", "faulting", "style", "(", "pg", "156", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_1997.py#L94-L106
gem/oq-engine
openquake/hazardlib/gsim/campbell_1997.py
Campbell1997.get_stddevs
def get_stddevs(self, mean, stddev_types): """ Returns the standard deviations from mean (pg 164; more robust than estimate using magnitude) """ mean = np.exp(mean) sigma = 0.39 + np.zeros(mean.shape) sigma[mean < 0.068] = 0.55 idx = np.logical_and(mean >=...
python
def get_stddevs(self, mean, stddev_types): mean = np.exp(mean) sigma = 0.39 + np.zeros(mean.shape) sigma[mean < 0.068] = 0.55 idx = np.logical_and(mean >= 0.068, mean <= 0.21) sigma[idx] = 0.173- 0.140 * np.log(mean[idx]) stddevs = [] for stddev in stddev...
[ "def", "get_stddevs", "(", "self", ",", "mean", ",", "stddev_types", ")", ":", "mean", "=", "np", ".", "exp", "(", "mean", ")", "sigma", "=", "0.39", "+", "np", ".", "zeros", "(", "mean", ".", "shape", ")", "sigma", "[", "mean", "<", "0.068", "]"...
Returns the standard deviations from mean (pg 164; more robust than estimate using magnitude)
[ "Returns", "the", "standard", "deviations", "from", "mean", "(", "pg", "164", ";", "more", "robust", "than", "estimate", "using", "magnitude", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_1997.py#L120-L134
gem/oq-engine
openquake/hazardlib/gsim/tavakoli_pezeshk_2005.py
TavakoliPezeshk2005.get_mean_and_stddevs
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients C = self.COEFFS[imt] ...
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): C = self.COEFFS[imt] mag = self._convert_magnitude(rup.mag) f1 = self._compute_magnitude_scaling_term(C, mag) f2 = self._compute_geometrical_spreading_term(C, dists.rrup) ...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "# extracting dictionary of coefficients", "C", "=", "self", ".", "COEFFS", "[", "imt", "]", "mag", "=", "self", ".", "_convert_mag...
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/tavakoli_pezeshk_2005.py#L73-L102
gem/oq-engine
openquake/hazardlib/gsim/tavakoli_pezeshk_2005.py
TavakoliPezeshk2005._get_stddevs
def _get_stddevs(self, C, stddev_types, num_sites, mag): """ Returns standard deviation as defined in equation 23, page 2291 (Tavakoli and Pezeshk, 2005) """ stddevs = [] sigma = (C['c14'] + C['c15'] * mag) if mag < 7.2 else C['c16'] vals = sigma * np.ones((num_si...
python
def _get_stddevs(self, C, stddev_types, num_sites, mag): stddevs = [] sigma = (C['c14'] + C['c15'] * mag) if mag < 7.2 else C['c16'] vals = sigma * np.ones((num_sites)) for _ in stddev_types: stddevs.append(vals) return stddevs
[ "def", "_get_stddevs", "(", "self", ",", "C", ",", "stddev_types", ",", "num_sites", ",", "mag", ")", ":", "stddevs", "=", "[", "]", "sigma", "=", "(", "C", "[", "'c14'", "]", "+", "C", "[", "'c15'", "]", "*", "mag", ")", "if", "mag", "<", "7.2...
Returns standard deviation as defined in equation 23, page 2291 (Tavakoli and Pezeshk, 2005)
[ "Returns", "standard", "deviation", "as", "defined", "in", "equation", "23", "page", "2291", "(", "Tavakoli", "and", "Pezeshk", "2005", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/tavakoli_pezeshk_2005.py#L104-L114
gem/oq-engine
openquake/hazardlib/gsim/tavakoli_pezeshk_2005.py
TavakoliPezeshk2005._compute_magnitude_scaling_term
def _compute_magnitude_scaling_term(self, C, mag): """ Compute magnitude scaling term as defined in equation 19, page 2291 (Tavakoli and Pezeshk, 2005) """ assert mag <= 8.5 return C['c1'] + C['c2'] * mag + C['c3'] * (8.5 - mag) ** 2.5
python
def _compute_magnitude_scaling_term(self, C, mag): assert mag <= 8.5 return C['c1'] + C['c2'] * mag + C['c3'] * (8.5 - mag) ** 2.5
[ "def", "_compute_magnitude_scaling_term", "(", "self", ",", "C", ",", "mag", ")", ":", "assert", "mag", "<=", "8.5", "return", "C", "[", "'c1'", "]", "+", "C", "[", "'c2'", "]", "*", "mag", "+", "C", "[", "'c3'", "]", "*", "(", "8.5", "-", "mag",...
Compute magnitude scaling term as defined in equation 19, page 2291 (Tavakoli and Pezeshk, 2005)
[ "Compute", "magnitude", "scaling", "term", "as", "defined", "in", "equation", "19", "page", "2291", "(", "Tavakoli", "and", "Pezeshk", "2005", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/tavakoli_pezeshk_2005.py#L131-L137
gem/oq-engine
openquake/hazardlib/gsim/tavakoli_pezeshk_2005.py
TavakoliPezeshk2005._compute_geometrical_spreading_term
def _compute_geometrical_spreading_term(self, C, rrup): """ Compute magnitude scaling term as defined in equation 19, page 2291 (Tavakoli and Pezeshk, 2005) """ f2 = np.ones_like(rrup) idx1 = np.nonzero(rrup <= 70.) idx2 = np.nonzero((rrup > 70.) & (rrup <= 130.))...
python
def _compute_geometrical_spreading_term(self, C, rrup): f2 = np.ones_like(rrup) idx1 = np.nonzero(rrup <= 70.) idx2 = np.nonzero((rrup > 70.) & (rrup <= 130.)) idx3 = np.nonzero(rrup > 130.) f2[idx1] = (C['c9'] * np.log(rrup[idx1] + 4.5)) f2[idx2] = (C['c10'] * ...
[ "def", "_compute_geometrical_spreading_term", "(", "self", ",", "C", ",", "rrup", ")", ":", "f2", "=", "np", ".", "ones_like", "(", "rrup", ")", "idx1", "=", "np", ".", "nonzero", "(", "rrup", "<=", "70.", ")", "idx2", "=", "np", ".", "nonzero", "(",...
Compute magnitude scaling term as defined in equation 19, page 2291 (Tavakoli and Pezeshk, 2005)
[ "Compute", "magnitude", "scaling", "term", "as", "defined", "in", "equation", "19", "page", "2291", "(", "Tavakoli", "and", "Pezeshk", "2005", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/tavakoli_pezeshk_2005.py#L139-L155