id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
0
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 comment: comment to use as header of the exported CSV file """ curves = util.compose_arrays(sitemesh, array) writers.write_csv(dest, curves, comment=comment) return [dest]
python
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 comment: comment to use as header of the exported CSV file """ 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", ",", "comment", "=", "comment", ")", "return", "[", "dest", "]" ]
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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L223-L235
1
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:`openquake.commonlib.source.RlzsAssoc` instance :param fname: name of the exported file :param sitecol: site collection :param array: an array of shape (N, L) and dtype numpy.float32 :param oq: job.ini parameters """ 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 iml in imls: lst.append(('poe-%s' % iml, F32)) hcurves = numpy.zeros(nsites, lst) for sid, lon, lat, dep in zip( range(nsites), sitecol.lons, sitecol.lats, sitecol.depths): hcurves[sid] = (lon, lat, dep) + tuple(array[sid, slc]) fnames.append(writers.write_csv(dest, hcurves, comment=_comment( rlzs_assoc, kind, oq.investigation_time) + ( ', imt="%s", checksum=%d' % (imt, checksum) ), header=[name for (name, dt) in lst])) return fnames
python
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:`openquake.commonlib.source.RlzsAssoc` instance :param fname: name of the exported file :param sitecol: site collection :param array: an array of shape (N, L) and dtype numpy.float32 :param oq: job.ini parameters """ 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 iml in imls: lst.append(('poe-%s' % iml, F32)) hcurves = numpy.zeros(nsites, lst) for sid, lon, lat, dep in zip( range(nsites), sitecol.lons, sitecol.lats, sitecol.depths): hcurves[sid] = (lon, lat, dep) + tuple(array[sid, slc]) fnames.append(writers.write_csv(dest, hcurves, comment=_comment( rlzs_assoc, kind, oq.investigation_time) + ( ', imt="%s", checksum=%d' % (imt, checksum) ), header=[name for (name, dt) in lst])) return fnames
[ "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", "iml", "in", "imls", ":", "lst", ".", "append", "(", "(", "'poe-%s'", "%", "iml", ",", "F32", ")", ")", "hcurves", "=", "numpy", ".", "zeros", "(", "nsites", ",", "lst", ")", "for", "sid", ",", "lon", ",", "lat", ",", "dep", "in", "zip", "(", "range", "(", "nsites", ")", ",", "sitecol", ".", "lons", ",", "sitecol", ".", "lats", ",", "sitecol", ".", "depths", ")", ":", "hcurves", "[", "sid", "]", "=", "(", "lon", ",", "lat", ",", "dep", ")", "+", "tuple", "(", "array", "[", "sid", ",", "slc", "]", ")", "fnames", ".", "append", "(", "writers", ".", "write_csv", "(", "dest", ",", "hcurves", ",", "comment", "=", "_comment", "(", "rlzs_assoc", ",", "kind", ",", "oq", ".", "investigation_time", ")", "+", "(", "', imt=\"%s\", checksum=%d'", "%", "(", "imt", ",", "checksum", ")", ")", ",", "header", "=", "[", "name", "for", "(", "name", ",", "dt", ")", "in", "lst", "]", ")", ")", "return", "fnames" ]
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: site collection :param array: an array of shape (N, L) and dtype numpy.float32 :param oq: job.ini parameters
[ "Export", "the", "curves", "of", "the", "given", "realization", "into", "CSV", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L248-L277
2
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 = len(rlzs_assoc.realizations) sitecol = dstore['sitecol'] sitemesh = get_mesh(sitecol) key, kind, fmt = get_kkf(ekey) fnames = [] checksum = dstore.get_attr('/', 'checksum32') hmap_dt = oq.hmap_dt() for kind in oq.get_kinds(kind, R): fname = hazard_curve_name(dstore, (key, fmt), kind, rlzs_assoc) comment = _comment(rlzs_assoc, kind, oq.investigation_time) if (key in ('hmaps', 'uhs') and oq.uniform_hazard_spectra or oq.hazard_maps): hmap = extract(dstore, 'hmaps?kind=' + kind)[kind] if key == 'uhs' and oq.poes and oq.uniform_hazard_spectra: uhs_curves = calc.make_uhs(hmap, info) writers.write_csv( fname, util.compose_arrays(sitemesh, uhs_curves), comment=comment + ', checksum=%d' % checksum) fnames.append(fname) elif key == 'hmaps' and oq.poes and oq.hazard_maps: fnames.extend( export_hmaps_csv(ekey, fname, sitemesh, hmap.flatten().view(hmap_dt), comment + ', checksum=%d' % checksum)) elif key == 'hcurves': hcurves = extract(dstore, 'hcurves?kind=' + kind)[kind] fnames.extend( export_hcurves_by_imt_csv( ekey, kind, rlzs_assoc, fname, sitecol, hcurves, oq, checksum)) return sorted(fnames)
python
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 = len(rlzs_assoc.realizations) sitecol = dstore['sitecol'] sitemesh = get_mesh(sitecol) key, kind, fmt = get_kkf(ekey) fnames = [] checksum = dstore.get_attr('/', 'checksum32') hmap_dt = oq.hmap_dt() for kind in oq.get_kinds(kind, R): fname = hazard_curve_name(dstore, (key, fmt), kind, rlzs_assoc) comment = _comment(rlzs_assoc, kind, oq.investigation_time) if (key in ('hmaps', 'uhs') and oq.uniform_hazard_spectra or oq.hazard_maps): hmap = extract(dstore, 'hmaps?kind=' + kind)[kind] if key == 'uhs' and oq.poes and oq.uniform_hazard_spectra: uhs_curves = calc.make_uhs(hmap, info) writers.write_csv( fname, util.compose_arrays(sitemesh, uhs_curves), comment=comment + ', checksum=%d' % checksum) fnames.append(fname) elif key == 'hmaps' and oq.poes and oq.hazard_maps: fnames.extend( export_hmaps_csv(ekey, fname, sitemesh, hmap.flatten().view(hmap_dt), comment + ', checksum=%d' % checksum)) elif key == 'hcurves': hcurves = extract(dstore, 'hcurves?kind=' + kind)[kind] fnames.extend( export_hcurves_by_imt_csv( ekey, kind, rlzs_assoc, fname, sitecol, hcurves, oq, checksum)) return sorted(fnames)
[ "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", "=", "dstore", ".", "get_attr", "(", "'/'", ",", "'checksum32'", ")", "hmap_dt", "=", "oq", ".", "hmap_dt", "(", ")", "for", "kind", "in", "oq", ".", "get_kinds", "(", "kind", ",", "R", ")", ":", "fname", "=", "hazard_curve_name", "(", "dstore", ",", "(", "key", ",", "fmt", ")", ",", "kind", ",", "rlzs_assoc", ")", "comment", "=", "_comment", "(", "rlzs_assoc", ",", "kind", ",", "oq", ".", "investigation_time", ")", "if", "(", "key", "in", "(", "'hmaps'", ",", "'uhs'", ")", "and", "oq", ".", "uniform_hazard_spectra", "or", "oq", ".", "hazard_maps", ")", ":", "hmap", "=", "extract", "(", "dstore", ",", "'hmaps?kind='", "+", "kind", ")", "[", "kind", "]", "if", "key", "==", "'uhs'", "and", "oq", ".", "poes", "and", "oq", ".", "uniform_hazard_spectra", ":", "uhs_curves", "=", "calc", ".", "make_uhs", "(", "hmap", ",", "info", ")", "writers", ".", "write_csv", "(", "fname", ",", "util", ".", "compose_arrays", "(", "sitemesh", ",", "uhs_curves", ")", ",", "comment", "=", "comment", "+", "', checksum=%d'", "%", "checksum", ")", "fnames", ".", "append", "(", "fname", ")", "elif", "key", "==", "'hmaps'", "and", "oq", ".", "poes", "and", "oq", ".", "hazard_maps", ":", "fnames", ".", "extend", "(", "export_hmaps_csv", "(", "ekey", ",", "fname", ",", "sitemesh", ",", "hmap", ".", "flatten", "(", ")", ".", "view", "(", "hmap_dt", ")", ",", "comment", "+", "', checksum=%d'", "%", "checksum", ")", ")", "elif", "key", "==", "'hcurves'", ":", "hcurves", "=", "extract", "(", "dstore", ",", "'hcurves?kind='", "+", "kind", ")", "[", "kind", "]", "fnames", ".", "extend", "(", "export_hcurves_by_imt_csv", "(", "ekey", ",", "kind", ",", "rlzs_assoc", ",", "fname", ",", "sitecol", ",", "hcurves", ",", "oq", ",", "checksum", ")", ")", "return", "sorted", "(", "fnames", ")" ]
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" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L333-L373
3
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_keys) for disag_tup, (poe, iml, matrix, fname) in matrices.items(): header = '%s,poe=%.7f,iml=%.7e\n' % (base_header, poe, iml) if disag_tup == ('Mag', 'Lon', 'Lat'): matrix = numpy.swapaxes(matrix, 0, 1) matrix = numpy.swapaxes(matrix, 1, 2) disag_tup = ('Lon', 'Lat', 'Mag') axis = [metadata[v] for v in disag_tup] header += ','.join(v for v in disag_tup) header += ',poe' # compute axis mid points axis = [(ax[: -1] + ax[1:]) / 2. if ax.dtype == float else ax for ax in axis] values = None if len(axis) == 1: values = numpy.array([axis[0], matrix.flatten()]).T else: grids = numpy.meshgrid(*axis, indexing='ij') values = [g.flatten() for g in grids] values.append(matrix.flatten()) values = numpy.array(values).T writers.write_csv(fname, values, comment=header, fmt='%.5E')
python
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_keys) for disag_tup, (poe, iml, matrix, fname) in matrices.items(): header = '%s,poe=%.7f,iml=%.7e\n' % (base_header, poe, iml) if disag_tup == ('Mag', 'Lon', 'Lat'): matrix = numpy.swapaxes(matrix, 0, 1) matrix = numpy.swapaxes(matrix, 1, 2) disag_tup = ('Lon', 'Lat', 'Mag') axis = [metadata[v] for v in disag_tup] header += ','.join(v for v in disag_tup) header += ',poe' # compute axis mid points axis = [(ax[: -1] + ax[1:]) / 2. if ax.dtype == float else ax for ax in axis] values = None if len(axis) == 1: values = numpy.array([axis[0], matrix.flatten()]).T else: grids = numpy.meshgrid(*axis, indexing='ij') values = [g.flatten() for g in grids] values.append(matrix.flatten()) values = numpy.array(values).T writers.write_csv(fname, values, comment=header, fmt='%.5E')
[ "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", "(", ")", ":", "header", "=", "'%s,poe=%.7f,iml=%.7e\\n'", "%", "(", "base_header", ",", "poe", ",", "iml", ")", "if", "disag_tup", "==", "(", "'Mag'", ",", "'Lon'", ",", "'Lat'", ")", ":", "matrix", "=", "numpy", ".", "swapaxes", "(", "matrix", ",", "0", ",", "1", ")", "matrix", "=", "numpy", ".", "swapaxes", "(", "matrix", ",", "1", ",", "2", ")", "disag_tup", "=", "(", "'Lon'", ",", "'Lat'", ",", "'Mag'", ")", "axis", "=", "[", "metadata", "[", "v", "]", "for", "v", "in", "disag_tup", "]", "header", "+=", "','", ".", "join", "(", "v", "for", "v", "in", "disag_tup", ")", "header", "+=", "',poe'", "# compute axis mid points", "axis", "=", "[", "(", "ax", "[", ":", "-", "1", "]", "+", "ax", "[", "1", ":", "]", ")", "/", "2.", "if", "ax", ".", "dtype", "==", "float", "else", "ax", "for", "ax", "in", "axis", "]", "values", "=", "None", "if", "len", "(", "axis", ")", "==", "1", ":", "values", "=", "numpy", ".", "array", "(", "[", "axis", "[", "0", "]", ",", "matrix", ".", "flatten", "(", ")", "]", ")", ".", "T", "else", ":", "grids", "=", "numpy", ".", "meshgrid", "(", "*", "axis", ",", "indexing", "=", "'ij'", ")", "values", "=", "[", "g", ".", "flatten", "(", ")", "for", "g", "in", "grids", "]", "values", ".", "append", "(", "matrix", ".", "flatten", "(", ")", ")", "values", "=", "numpy", ".", "array", "(", "values", ")", ".", "T", "writers", ".", "write_csv", "(", "fname", ",", "values", ",", "comment", "=", "header", ",", "fmt", "=", "'%.5E'", ")" ]
Save disaggregation matrices to multiple .csv files.
[ "Save", "disaggregation", "matrices", "to", "multiple", ".", "csv", "files", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L743-L776
4
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): """ 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)
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L154-L158
5
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: srf = 1 return srf
python
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: 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", ",", "1", ",", "imt_per", ")", "elif", "5", "<=", "imt_per", "<=", "10", ":", "srf", "=", "0.58", "else", ":", "srf", "=", "1", "return", "srf" ]
Table 6 and equation 19 of 2013 report.
[ "Table", "6", "and", "equation", "19", "of", "2013", "report", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L160-L173
6
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._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 = 1 return srf
python
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._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 = 1 return 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", ",", "0.6", ",", "imt_per", ")", "elif", "1", "<=", "imt_per", "<=", "10", ":", "srf", "=", "self", ".", "_interp_function", "(", "0.6", ",", "0.7", ",", "10", ",", "1", ",", "imt_per", ")", "else", ":", "srf", "=", "1", "return", "srf" ]
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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L175-L190
7
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: 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 = 1 return srf
python
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: 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 = 1 return 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", ",", "0.6", ",", "imt_per", ")", "elif", "1", "<=", "imt_per", "<=", "10", ":", "srf", "=", "self", ".", "_interp_function", "(", "0.6", ",", "0.7", ",", "10", ",", "1", ",", "imt_per", ")", "else", ":", "srf", "=", "1", "return", "srf" ]
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", "is", "identical", "to", "Table", "7", "in", "the", "2013", "report", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L192-L208
8
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 = self._interp_function(0.65, 0.12, 10, 0.35, imt_per) else: dL2L = 0 return dL2L
python
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 = self._interp_function(0.65, 0.12, 10, 0.35, imt_per) else: dL2L = 0 return dL2L
[ "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", ")", "else", ":", "dL2L", "=", "0", "return", "dL2L" ]
Table 3 and equation 19 of 2013 report.
[ "Table", "3", "and", "equation", "19", "of", "2013", "report", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L210-L223
9
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, -0.15, 0.45, 0.15, imt_per) elif 0.45 <= imt_per < 3.2: dS2S = 0.4 elif 3.2 <= imt_per < 5: dS2S = self._interp_function(0.08, 0.4, 5, 3.2, imt_per) elif 5 <= imt_per <= 10: dS2S = 0.08 else: dS2S = 0 return dS2S
python
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, -0.15, 0.45, 0.15, imt_per) elif 0.45 <= imt_per < 3.2: dS2S = 0.4 elif 3.2 <= imt_per < 5: dS2S = self._interp_function(0.08, 0.4, 5, 3.2, imt_per) elif 5 <= imt_per <= 10: dS2S = 0.08 else: dS2S = 0 return dS2S
[ "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.45", "<=", "imt_per", "<", "3.2", ":", "dS2S", "=", "0.4", "elif", "3.2", "<=", "imt_per", "<", "5", ":", "dS2S", "=", "self", ".", "_interp_function", "(", "0.08", ",", "0.4", ",", "5", ",", "3.2", ",", "imt_per", ")", "elif", "5", "<=", "imt_per", "<=", "10", ":", "dS2S", "=", "0.08", "else", ":", "dS2S", "=", "0", "return", "dS2S" ]
Table 4 of 2013 report
[ "Table", "4", "of", "2013", "report" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L225-L244
10
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.exc_info() msg = 'An error occurred with source id=%s. Error: %s' msg %= (src.source_id, err) raise_(etype, msg, tb)
python
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.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", ".", "source_id", ",", "err", ")", "raise_", "(", "etype", ",", "msg", ",", "tb", ")" ]
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" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L39-L55
11
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, possibly None :param mag: magnitude, possibly None :returns: min_lon, min_lat, max_lon, max_lat """ if trt is None: # take the greatest integration distance maxdist = max(self(trt, mag) for trt in self.dic) else: # get the integration distance for the given TRT maxdist = self(trt, mag) a1 = min(maxdist * KM_TO_DEGREES, 90) a2 = min(angular_distance(maxdist, lat), 180) return lon - a2, lat - a1, lon + a2, lat + a1
python
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, possibly None :param mag: magnitude, possibly None :returns: min_lon, min_lat, max_lon, max_lat """ if trt is None: # take the greatest integration distance maxdist = max(self(trt, mag) for trt in self.dic) else: # get the integration distance for the given TRT maxdist = self(trt, mag) a1 = min(maxdist * KM_TO_DEGREES, 90) a2 = min(angular_distance(maxdist, lat), 180) return lon - a2, lat - a1, lon + a2, lat + a1
[ "def", "get_bounding_box", "(", "self", ",", "lon", ",", "lat", ",", "trt", "=", "None", ",", "mag", "=", "None", ")", ":", "if", "trt", "is", "None", ":", "# take the greatest integration distance", "maxdist", "=", "max", "(", "self", "(", "trt", ",", "mag", ")", "for", "trt", "in", "self", ".", "dic", ")", "else", ":", "# get the integration distance for the given TRT", "maxdist", "=", "self", "(", "trt", ",", "mag", ")", "a1", "=", "min", "(", "maxdist", "*", "KM_TO_DEGREES", ",", "90", ")", "a2", "=", "min", "(", "angular_distance", "(", "maxdist", ",", "lat", ")", ",", "180", ")", "return", "lon", "-", "a2", ",", "lat", "-", "a1", ",", "lon", "+", "a2", ",", "lat", "+", "a1" ]
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_lon, min_lat, max_lon, max_lat
[ "Build", "a", "bounding", "box", "around", "the", "given", "lon", "lat", "by", "computing", "the", "maximum_distance", "at", "the", "given", "tectonic", "region", "type", "and", "magnitude", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L138-L155
12
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 = get_bounding_box(src, maxdist) return (fix_lon(bbox[0]), bbox[1], fix_lon(bbox[2]), bbox[3])
python
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 = 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", "(", "src", ",", "maxdist", ")", "return", "(", "fix_lon", "(", "bbox", "[", "0", "]", ")", ",", "bbox", "[", "1", "]", ",", "fix_lon", "(", "bbox", "[", "2", "]", ")", ",", "bbox", "[", "3", "]", ")" ]
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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L157-L167
13
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 with hdf5.File(self.filename, 'r') as h5: self.__dict__['sitecol'] = sc = h5.get('sitecol') return sc
python
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 with hdf5.File(self.filename, 'r') as h5: self.__dict__['sitecol'] = sc = h5.get('sitecol') return sc
[ "def", "sitecol", "(", "self", ")", ":", "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", "with", "hdf5", ".", "File", "(", "self", ".", "filename", ",", "'r'", ")", "as", "h5", ":", "self", ".", "__dict__", "[", "'sitecol'", "]", "=", "sc", "=", "h5", ".", "get", "(", "'sitecol'", ")", "return", "sc" ]
Read the site collection from .filename and cache it
[ "Read", "the", "site", "collection", "from", ".", "filename", "and", "cache", "it" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L276-L287
14
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: :class:`~openquake.hazardlib.geo.point.Point` object representing the location of hypocentre. :param rupture_top_edge: A instances of :class:`openquake.hazardlib.geo.line.Line` representing the rupture surface's top edge. :param upper_seismo_depth: Minimum depth ruptures can reach, in km (i.e. depth to fault's top edge). :param lower_seismo_depth: Maximum depth ruptures can reach, in km (i.e. depth to fault's bottom edge). :param dip: Dip angle (i.e. angle between fault surface and earth surface), in degrees. :return: An integer corresponding to the index of the fault patch which contains the hypocentre. """ totaln_patch = len(rupture_top_edge) indexlist = [] dist_list = [] for i, index in enumerate(range(1, totaln_patch)): p0, p1, p2, p3 = cls.get_fault_patch_vertices( rupture_top_edge, upper_seismogenic_depth, lower_seismogenic_depth, dip, index_patch=index) [normal, dist_to_plane] = get_plane_equation(p0, p1, p2, hypocentre) indexlist.append(index) dist_list.append(dist_to_plane) if numpy.allclose(dist_to_plane, 0., atol=25., rtol=0.): return index break index = indexlist[numpy.argmin(dist_list)] return index
python
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: :class:`~openquake.hazardlib.geo.point.Point` object representing the location of hypocentre. :param rupture_top_edge: A instances of :class:`openquake.hazardlib.geo.line.Line` representing the rupture surface's top edge. :param upper_seismo_depth: Minimum depth ruptures can reach, in km (i.e. depth to fault's top edge). :param lower_seismo_depth: Maximum depth ruptures can reach, in km (i.e. depth to fault's bottom edge). :param dip: Dip angle (i.e. angle between fault surface and earth surface), in degrees. :return: An integer corresponding to the index of the fault patch which contains the hypocentre. """ totaln_patch = len(rupture_top_edge) indexlist = [] dist_list = [] for i, index in enumerate(range(1, totaln_patch)): p0, p1, p2, p3 = cls.get_fault_patch_vertices( rupture_top_edge, upper_seismogenic_depth, lower_seismogenic_depth, dip, index_patch=index) [normal, dist_to_plane] = get_plane_equation(p0, p1, p2, hypocentre) indexlist.append(index) dist_list.append(dist_to_plane) if numpy.allclose(dist_to_plane, 0., atol=25., rtol=0.): return index break index = indexlist[numpy.argmin(dist_list)] return index
[ "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", "(", "1", ",", "totaln_patch", ")", ")", ":", "p0", ",", "p1", ",", "p2", ",", "p3", "=", "cls", ".", "get_fault_patch_vertices", "(", "rupture_top_edge", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "dip", ",", "index_patch", "=", "index", ")", "[", "normal", ",", "dist_to_plane", "]", "=", "get_plane_equation", "(", "p0", ",", "p1", ",", "p2", ",", "hypocentre", ")", "indexlist", ".", "append", "(", "index", ")", "dist_list", ".", "append", "(", "dist_to_plane", ")", "if", "numpy", ".", "allclose", "(", "dist_to_plane", ",", "0.", ",", "atol", "=", "25.", ",", "rtol", "=", "0.", ")", ":", "return", "index", "break", "index", "=", "indexlist", "[", "numpy", ".", "argmin", "(", "dist_list", ")", "]", "return", "index" ]
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.line.Line` representing the rupture surface's top edge. :param upper_seismo_depth: Minimum depth ruptures can reach, in km (i.e. depth to fault's top edge). :param lower_seismo_depth: Maximum depth ruptures can reach, in km (i.e. depth to fault's bottom edge). :param dip: Dip angle (i.e. angle between fault surface and earth surface), in degrees. :return: An integer corresponding to the index of the fault patch which contains the hypocentre.
[ "This", "methods", "finds", "the", "index", "of", "the", "fault", "patch", "including", "the", "hypocentre", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L256-L298
15
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: Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon` describing the surface projection of the simple fault with specified parameters. """ # Similar to :meth:`from_fault_data`, we just don't resample edges dip_tan = math.tan(math.radians(dip)) hdist_top = upper_seismogenic_depth / dip_tan hdist_bottom = lower_seismogenic_depth / dip_tan strike = fault_trace[0].azimuth(fault_trace[-1]) azimuth = (strike + 90.0) % 360 # Collect coordinates of vertices on the top and bottom edge lons = [] lats = [] for point in fault_trace.points: top_edge_point = point.point_at(hdist_top, 0, azimuth) bottom_edge_point = point.point_at(hdist_bottom, 0, azimuth) lons.append(top_edge_point.longitude) lats.append(top_edge_point.latitude) lons.append(bottom_edge_point.longitude) lats.append(bottom_edge_point.latitude) lons = numpy.array(lons, float) lats = numpy.array(lats, float) return lons, lats
python
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: Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon` describing the surface projection of the simple fault with specified parameters. """ # Similar to :meth:`from_fault_data`, we just don't resample edges dip_tan = math.tan(math.radians(dip)) hdist_top = upper_seismogenic_depth / dip_tan hdist_bottom = lower_seismogenic_depth / dip_tan strike = fault_trace[0].azimuth(fault_trace[-1]) azimuth = (strike + 90.0) % 360 # Collect coordinates of vertices on the top and bottom edge lons = [] lats = [] for point in fault_trace.points: top_edge_point = point.point_at(hdist_top, 0, azimuth) bottom_edge_point = point.point_at(hdist_bottom, 0, azimuth) lons.append(top_edge_point.longitude) lats.append(top_edge_point.latitude) lons.append(bottom_edge_point.longitude) lats.append(bottom_edge_point.latitude) lons = numpy.array(lons, float) lats = numpy.array(lats, float) return lons, lats
[ "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", ".", "radians", "(", "dip", ")", ")", "hdist_top", "=", "upper_seismogenic_depth", "/", "dip_tan", "hdist_bottom", "=", "lower_seismogenic_depth", "/", "dip_tan", "strike", "=", "fault_trace", "[", "0", "]", ".", "azimuth", "(", "fault_trace", "[", "-", "1", "]", ")", "azimuth", "=", "(", "strike", "+", "90.0", ")", "%", "360", "# Collect coordinates of vertices on the top and bottom edge", "lons", "=", "[", "]", "lats", "=", "[", "]", "for", "point", "in", "fault_trace", ".", "points", ":", "top_edge_point", "=", "point", ".", "point_at", "(", "hdist_top", ",", "0", ",", "azimuth", ")", "bottom_edge_point", "=", "point", ".", "point_at", "(", "hdist_bottom", ",", "0", ",", "azimuth", ")", "lons", ".", "append", "(", "top_edge_point", ".", "longitude", ")", "lats", ".", "append", "(", "top_edge_point", ".", "latitude", ")", "lons", ".", "append", "(", "bottom_edge_point", ".", "longitude", ")", "lats", ".", "append", "(", "bottom_edge_point", ".", "latitude", ")", "lons", "=", "numpy", ".", "array", "(", "lons", ",", "float", ")", "lats", "=", "numpy", ".", "array", "(", "lats", ",", "float", ")", "return", "lons", ",", "lats" ]
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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L301-L336
16
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:`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. """ lons, lats = cls.get_surface_vertexes(fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip) return Mesh(lons, lats, depths=None).get_convex_hull()
python
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:`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. """ lons, lats = cls.get_surface_vertexes(fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip) return Mesh(lons, lats, depths=None).get_convex_hull()
[ "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_depth", ",", "lower_seismogenic_depth", ",", "dip", ")", "return", "Mesh", "(", "lons", ",", "lats", ",", "depths", "=", "None", ")", ".", "get_convex_hull", "(", ")" ]
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 specified parameters.
[ "Get", "a", "surface", "projection", "of", "the", "simple", "fault", "surface", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L339-L356
17
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): """ 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
[ "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" ]
Compute second and third terms in equation 1, p. 901.
[ "Compute", "second", "and", "third", "terms", "in", "equation", "1", "p", ".", "901", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L133-L140
18
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 15 km for the # depth coefficient hc ...". hc = 15.0 # p. 901. "When h is larger than hc, the depth terms takes # effect ...". The next sentence specifies h>=hc. return float(focal_depth >= hc) * C['e'] * (focal_depth - hc)
python
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 15 km for the # depth coefficient hc ...". hc = 15.0 # p. 901. "When h is larger than hc, the depth terms takes # effect ...". The next sentence specifies h>=hc. 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 of 15 km for the", "# depth coefficient hc ...\".", "hc", "=", "15.0", "# p. 901. \"When h is larger than hc, the depth terms takes", "# effect ...\". The next sentence specifies h>=hc.", "return", "float", "(", "focal_depth", ">=", "hc", ")", "*", "C", "[", "'e'", "]", "*", "(", "focal_depth", "-", "hc", ")" ]
Compute fourth term in equation 1, p. 901.
[ "Compute", "fourth", "term", "in", "equation", "1", "p", ".", "901", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L142-L157
19
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[(vs30 > 600) & (vs30 <= 1100)] = C['C1'] # hard soil site_term[(vs30 > 300) & (vs30 <= 600)] = C['C2'] # medium soil site_term[(vs30 > 200) & (vs30 <= 300)] = C['C3'] # soft soil site_term[vs30 <= 200] = C['C4'] return site_term
python
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[(vs30 > 600) & (vs30 <= 1100)] = C['C1'] # hard soil site_term[(vs30 > 300) & (vs30 <= 600)] = C['C2'] # medium soil site_term[(vs30 > 200) & (vs30 <= 300)] = C['C3'] # soft soil site_term[vs30 <= 200] = C['C4'] return 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.0", "]", "=", "C", "[", "'CH'", "]", "# rock", "site_term", "[", "(", "vs30", ">", "600", ")", "&", "(", "vs30", "<=", "1100", ")", "]", "=", "C", "[", "'C1'", "]", "# hard soil", "site_term", "[", "(", "vs30", ">", "300", ")", "&", "(", "vs30", "<=", "600", ")", "]", "=", "C", "[", "'C2'", "]", "# medium soil", "site_term", "[", "(", "vs30", ">", "200", ")", "&", "(", "vs30", "<=", "300", ")", "]", "=", "C", "[", "'C3'", "]", "# soft soil", "site_term", "[", "vs30", "<=", "200", "]", "=", "C", "[", "'C4'", "]", "return", "site_term" ]
Compute nine-th term in equation 1, p. 901.
[ "Compute", "nine", "-", "th", "term", "in", "equation", "1", "p", ".", "901", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L168-L190
20
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): """ Compute magnitude squared term, equation 5, p. 909. """ 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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L192-L196
21
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): """ 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
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L369-L376
22
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_mod, imt, stddev_types)
python
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_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.", "]", "=", "5.", "return", "super", "(", ")", ".", "get_mean_and_stddevs", "(", "sites", ",", "rup", ",", "dists_mod", ",", "imt", ",", "stddev_types", ")" ]
Using a minimum distance of 5km for the calculation.
[ "Using", "a", "minimum", "distance", "of", "5km", "for", "the", "calculation", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L654-L663
23
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().lower() if answer not in ('y', 'n'): print('Please enter y or n') continue return answer == 'y'
python
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().lower() if answer not in ('y', 'n'): print('Please enter y or n') continue return answer == 'y'
[ "def", "confirm", "(", "prompt", ")", ":", "while", "True", ":", "try", ":", "answer", "=", "input", "(", "prompt", ")", "except", "KeyboardInterrupt", ":", "# the user presses ctrl+c, just say 'no'", "return", "False", "answer", "=", "answer", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "answer", "not", "in", "(", "'y'", ",", "'n'", ")", ":", "print", "(", "'Please enter y or n'", ")", "continue", "return", "answer", "==", "'y'" ]
Ask for confirmation, given a ``prompt`` and return a boolean value.
[ "Ask", "for", "confirmation", "given", "a", "prompt", "and", "return", "a", "boolean", "value", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/utils/__init__.py#L20-L34
24
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.append('area') if self.occupancy_periods: fields.extend(self.occupancy_periods.split()) fields.extend(self.tagcol.tagnames) return set(fields)
python
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.append('area') if self.occupancy_periods: fields.extend(self.occupancy_periods.split()) fields.extend(self.tagcol.tagnames) return set(fields)
[ "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", ".", "occupancy_periods", ".", "split", "(", ")", ")", "fields", ".", "extend", "(", "self", ".", "tagcol", ".", "tagnames", ")", "return", "set", "(", "fields", ")" ]
Extract the expected CSV header from the exposure metadata
[ "Extract", "the", "expected", "CSV", "header", "from", "the", "exposure", "metadata" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L885-L897
25
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( 'vulnerabilityFunction', {'id': vf.id, 'dist': vf.distribution_name}, nodes=nodes)
python
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( '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", ")", ",", "Node", "(", "'covLRs'", ",", "{", "}", ",", "vf", ".", "covs", ")", "]", "return", "Node", "(", "'vulnerabilityFunction'", ",", "{", "'id'", ":", "vf", ".", "id", ",", "'dist'", ":", "vf", ".", "distribution_name", "}", ",", "nodes", "=", "nodes", ")" ]
Convert a VulnerabilityFunction object into a Node suitable for XML conversion.
[ "Convert", "a", "VulnerabilityFunction", "object", "into", "a", "Node", "suitable", "for", "XML", "conversion", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/riskmodels.py#L69-L79
26
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 class :param extra: extra parameters to pass to the riskmodel class """ riskmodel_class = registry[oqparam.calculation_mode] # arguments needed to instantiate the riskmodel class argnames = inspect.getfullargspec(riskmodel_class.__init__).args[3:] # arguments extracted from oqparam known_args = set(name for name, value in inspect.getmembers(oqparam.__class__) if isinstance(value, valid.Param)) all_args = {} for argname in argnames: if argname in known_args: all_args[argname] = getattr(oqparam, argname) if 'hazard_imtls' in argnames: # special case all_args['hazard_imtls'] = oqparam.imtls all_args.update(extra) missing = set(argnames) - set(all_args) if missing: raise TypeError('Missing parameter: %s' % ', '.join(missing)) return riskmodel_class(taxonomy, **all_args)
python
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 class :param extra: extra parameters to pass to the riskmodel class """ riskmodel_class = registry[oqparam.calculation_mode] # arguments needed to instantiate the riskmodel class argnames = inspect.getfullargspec(riskmodel_class.__init__).args[3:] # arguments extracted from oqparam known_args = set(name for name, value in inspect.getmembers(oqparam.__class__) if isinstance(value, valid.Param)) all_args = {} for argname in argnames: if argname in known_args: all_args[argname] = getattr(oqparam, argname) if 'hazard_imtls' in argnames: # special case all_args['hazard_imtls'] = oqparam.imtls all_args.update(extra) missing = set(argnames) - set(all_args) if missing: raise TypeError('Missing parameter: %s' % ', '.join(missing)) return riskmodel_class(taxonomy, **all_args)
[ "def", "get_riskmodel", "(", "taxonomy", ",", "oqparam", ",", "*", "*", "extra", ")", ":", "riskmodel_class", "=", "registry", "[", "oqparam", ".", "calculation_mode", "]", "# arguments needed to instantiate the riskmodel class", "argnames", "=", "inspect", ".", "getfullargspec", "(", "riskmodel_class", ".", "__init__", ")", ".", "args", "[", "3", ":", "]", "# arguments extracted from oqparam", "known_args", "=", "set", "(", "name", "for", "name", ",", "value", "in", "inspect", ".", "getmembers", "(", "oqparam", ".", "__class__", ")", "if", "isinstance", "(", "value", ",", "valid", ".", "Param", ")", ")", "all_args", "=", "{", "}", "for", "argname", "in", "argnames", ":", "if", "argname", "in", "known_args", ":", "all_args", "[", "argname", "]", "=", "getattr", "(", "oqparam", ",", "argname", ")", "if", "'hazard_imtls'", "in", "argnames", ":", "# special case", "all_args", "[", "'hazard_imtls'", "]", "=", "oqparam", ".", "imtls", "all_args", ".", "update", "(", "extra", ")", "missing", "=", "set", "(", "argnames", ")", "-", "set", "(", "all_args", ")", "if", "missing", ":", "raise", "TypeError", "(", "'Missing parameter: %s'", "%", "', '", ".", "join", "(", "missing", ")", ")", "return", "riskmodel_class", "(", "taxonomy", ",", "*", "*", "all_args", ")" ]
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 to the riskmodel class
[ "Return", "an", "instance", "of", "the", "correct", "riskmodel", "class", "depending", "on", "the", "attribute", "calculation_mode", "of", "the", "object", "oqparam", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/riskmodels.py#L548-L580
27
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 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, M12, M13, M23 - the six independent components of the moment tensor, where the coordinate system is 1,2,3 = Up,South,East which equals r,theta,phi). The strike is of the first plane, clockwise relative to north. The dip is of the first plane, defined clockwise and perpendicular to strike, relative to horizontal such that 0 is horizontal and 90 is vertical. The rake is of the first focal plane solution. 90 moves the hanging wall up-dip (thrust), 0 moves it in the strike direction (left-lateral), -90 moves it down-dip (normal), and 180 moves it opposite to strike (right-lateral). :param facecolor: Color to use for quadrants of tension; can be a string, e.g. ``'r'``, ``'b'`` or three component color vector, [R G B]. Defaults to ``'b'`` (blue). :param bgcolor: The background color. Defaults to ``'w'`` (white). :param edgecolor: Color of the edges. Defaults to ``'k'`` (black). :param alpha: The alpha level of the beach ball. Defaults to ``1.0`` (opaque). :param xy: Origin position of the beach ball as tuple. Defaults to ``(0, 0)``. :type width: int :param width: Symbol size of beach ball. Defaults to ``200``. :param size: Controls the number of interpolation points for the curves. Minimum is automatically set to ``100``. :param nofill: Do not fill the beach ball, but only plot the planes. :param zorder: Set zorder. Artists with lower zorder values are drawn first. :param outfile: Output file string. Also used to automatically determine the output format. Supported file formats depend on your matplotlib backend. Most backends support png, pdf, ps, eps and svg. Defaults to ``None``. :param format: Format of the graph picture. If no format is given the outfile parameter will be used to try to automatically determine the output format. If no format is found it defaults to png output. If no outfile is specified but a format is, than a binary imagestring will be returned. Defaults to ``None``. :param fig: Give an existing figure instance to plot into. New Figure if set to ``None``. """ plot_width = width * 0.95 # plot the figure if not fig: fig = plt.figure(figsize=(3, 3), dpi=100) fig.subplots_adjust(left=0, bottom=0, right=1, top=1) fig.set_figheight(width // 100) fig.set_figwidth(width // 100) ax = fig.add_subplot(111, aspect='equal') # hide axes + ticks ax.axison = False # plot the collection collection = Beach(fm, linewidth=linewidth, facecolor=facecolor, edgecolor=edgecolor, bgcolor=bgcolor, alpha=alpha, nofill=nofill, xy=xy, width=plot_width, size=size, zorder=zorder) ax.add_collection(collection) ax.autoscale_view(tight=False, scalex=True, scaley=True) # export if outfile: if format: fig.savefig(outfile, dpi=100, transparent=True, format=format) else: fig.savefig(outfile, dpi=100, transparent=True) elif format and not outfile: imgdata = compatibility.BytesIO() fig.savefig(imgdata, format=format, dpi=100, transparent=True) imgdata.seek(0) return imgdata.read() else: plt.show() return fig
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): """ 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, M12, M13, M23 - the six independent components of the moment tensor, where the coordinate system is 1,2,3 = Up,South,East which equals r,theta,phi). The strike is of the first plane, clockwise relative to north. The dip is of the first plane, defined clockwise and perpendicular to strike, relative to horizontal such that 0 is horizontal and 90 is vertical. The rake is of the first focal plane solution. 90 moves the hanging wall up-dip (thrust), 0 moves it in the strike direction (left-lateral), -90 moves it down-dip (normal), and 180 moves it opposite to strike (right-lateral). :param facecolor: Color to use for quadrants of tension; can be a string, e.g. ``'r'``, ``'b'`` or three component color vector, [R G B]. Defaults to ``'b'`` (blue). :param bgcolor: The background color. Defaults to ``'w'`` (white). :param edgecolor: Color of the edges. Defaults to ``'k'`` (black). :param alpha: The alpha level of the beach ball. Defaults to ``1.0`` (opaque). :param xy: Origin position of the beach ball as tuple. Defaults to ``(0, 0)``. :type width: int :param width: Symbol size of beach ball. Defaults to ``200``. :param size: Controls the number of interpolation points for the curves. Minimum is automatically set to ``100``. :param nofill: Do not fill the beach ball, but only plot the planes. :param zorder: Set zorder. Artists with lower zorder values are drawn first. :param outfile: Output file string. Also used to automatically determine the output format. Supported file formats depend on your matplotlib backend. Most backends support png, pdf, ps, eps and svg. Defaults to ``None``. :param format: Format of the graph picture. If no format is given the outfile parameter will be used to try to automatically determine the output format. If no format is found it defaults to png output. If no outfile is specified but a format is, than a binary imagestring will be returned. Defaults to ``None``. :param fig: Give an existing figure instance to plot into. New Figure if set to ``None``. """ plot_width = width * 0.95 # plot the figure if not fig: fig = plt.figure(figsize=(3, 3), dpi=100) fig.subplots_adjust(left=0, bottom=0, right=1, top=1) fig.set_figheight(width // 100) fig.set_figwidth(width // 100) ax = fig.add_subplot(111, aspect='equal') # hide axes + ticks ax.axison = False # plot the collection collection = Beach(fm, linewidth=linewidth, facecolor=facecolor, edgecolor=edgecolor, bgcolor=bgcolor, alpha=alpha, nofill=nofill, xy=xy, width=plot_width, size=size, zorder=zorder) ax.add_collection(collection) ax.autoscale_view(tight=False, scalex=True, scaley=True) # export if outfile: if format: fig.savefig(outfile, dpi=100, transparent=True, format=format) else: fig.savefig(outfile, dpi=100, transparent=True) elif format and not outfile: imgdata = compatibility.BytesIO() fig.savefig(imgdata, format=format, dpi=100, transparent=True) imgdata.seek(0) return imgdata.read() else: plt.show() return fig
[ "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", "# plot the figure", "if", "not", "fig", ":", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "3", ",", "3", ")", ",", "dpi", "=", "100", ")", "fig", ".", "subplots_adjust", "(", "left", "=", "0", ",", "bottom", "=", "0", ",", "right", "=", "1", ",", "top", "=", "1", ")", "fig", ".", "set_figheight", "(", "width", "//", "100", ")", "fig", ".", "set_figwidth", "(", "width", "//", "100", ")", "ax", "=", "fig", ".", "add_subplot", "(", "111", ",", "aspect", "=", "'equal'", ")", "# hide axes + ticks", "ax", ".", "axison", "=", "False", "# plot the collection", "collection", "=", "Beach", "(", "fm", ",", "linewidth", "=", "linewidth", ",", "facecolor", "=", "facecolor", ",", "edgecolor", "=", "edgecolor", ",", "bgcolor", "=", "bgcolor", ",", "alpha", "=", "alpha", ",", "nofill", "=", "nofill", ",", "xy", "=", "xy", ",", "width", "=", "plot_width", ",", "size", "=", "size", ",", "zorder", "=", "zorder", ")", "ax", ".", "add_collection", "(", "collection", ")", "ax", ".", "autoscale_view", "(", "tight", "=", "False", ",", "scalex", "=", "True", ",", "scaley", "=", "True", ")", "# export", "if", "outfile", ":", "if", "format", ":", "fig", ".", "savefig", "(", "outfile", ",", "dpi", "=", "100", ",", "transparent", "=", "True", ",", "format", "=", "format", ")", "else", ":", "fig", ".", "savefig", "(", "outfile", ",", "dpi", "=", "100", ",", "transparent", "=", "True", ")", "elif", "format", "and", "not", "outfile", ":", "imgdata", "=", "compatibility", ".", "BytesIO", "(", ")", "fig", ".", "savefig", "(", "imgdata", ",", "format", "=", "format", ",", "dpi", "=", "100", ",", "transparent", "=", "True", ")", "imgdata", ".", "seek", "(", "0", ")", "return", "imgdata", ".", "read", "(", ")", "else", ":", "plt", ".", "show", "(", ")", "return", "fig" ]
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, M12, M13, M23 - the six independent components of the moment tensor, where the coordinate system is 1,2,3 = Up,South,East which equals r,theta,phi). The strike is of the first plane, clockwise relative to north. The dip is of the first plane, defined clockwise and perpendicular to strike, relative to horizontal such that 0 is horizontal and 90 is vertical. The rake is of the first focal plane solution. 90 moves the hanging wall up-dip (thrust), 0 moves it in the strike direction (left-lateral), -90 moves it down-dip (normal), and 180 moves it opposite to strike (right-lateral). :param facecolor: Color to use for quadrants of tension; can be a string, e.g. ``'r'``, ``'b'`` or three component color vector, [R G B]. Defaults to ``'b'`` (blue). :param bgcolor: The background color. Defaults to ``'w'`` (white). :param edgecolor: Color of the edges. Defaults to ``'k'`` (black). :param alpha: The alpha level of the beach ball. Defaults to ``1.0`` (opaque). :param xy: Origin position of the beach ball as tuple. Defaults to ``(0, 0)``. :type width: int :param width: Symbol size of beach ball. Defaults to ``200``. :param size: Controls the number of interpolation points for the curves. Minimum is automatically set to ``100``. :param nofill: Do not fill the beach ball, but only plot the planes. :param zorder: Set zorder. Artists with lower zorder values are drawn first. :param outfile: Output file string. Also used to automatically determine the output format. Supported file formats depend on your matplotlib backend. Most backends support png, pdf, ps, eps and svg. Defaults to ``None``. :param format: Format of the graph picture. If no format is given the outfile parameter will be used to try to automatically determine the output format. If no format is found it defaults to png output. If no outfile is specified but a format is, than a binary imagestring will be returned. Defaults to ``None``. :param fig: Give an existing figure instance to plot into. New Figure if set to ``None``.
[ "Draws", "a", "beach", "ball", "diagram", "of", "an", "earthquake", "focal", "mechanism", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L147-L230
28
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: 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(e, 2)) dip = np.arctan2(x, u) * r2d return (strike, dip)
python
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: 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(e, 2)) dip = np.arctan2(x, u) * r2d return (strike, dip)
[ "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", "(", "e", ",", "2", ")", ")", "dip", "=", "np", ".", "arctan2", "(", "x", ",", "u", ")", "*", "r2d", "return", "(", "strike", ",", "dip", ")" ]
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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L669-L692
29
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 # slick vector in plane 1 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) = StrikeDip(sl2, sl1, sl3) n1 = np.sin(z) * np.sin(z2) # normal vector to plane 1 n2 = np.cos(z) * np.sin(z2) h1 = -sl2 # strike vector of plane 2 h2 = sl1 # note h3=0 always so we leave it out # n3 = np.cos(z2) z = h1 * n1 + h2 * n2 z = z / np.sqrt(h1 * h1 + h2 * h2) z = np.arccos(z) rake = 0 if sl3 > 0: rake = z * r2d if sl3 <= 0: rake = -z * r2d return (strike, dip, rake)
python
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 # slick vector in plane 1 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) = StrikeDip(sl2, sl1, sl3) n1 = np.sin(z) * np.sin(z2) # normal vector to plane 1 n2 = np.cos(z) * np.sin(z2) h1 = -sl2 # strike vector of plane 2 h2 = sl1 # note h3=0 always so we leave it out # n3 = np.cos(z2) z = h1 * n1 + h2 * n2 z = z / np.sqrt(h1 * h1 + h2 * h2) z = np.arccos(z) rake = 0 if sl3 > 0: rake = z * r2d if sl3 <= 0: rake = -z * r2d return (strike, dip, rake)
[ "def", "AuxPlane", "(", "s1", ",", "d1", ",", "r1", ")", ":", "r2d", "=", "180", "/", "np", ".", "pi", "z", "=", "(", "s1", "+", "90", ")", "/", "r2d", "z2", "=", "d1", "/", "r2d", "z3", "=", "r1", "/", "r2d", "# slick vector in plane 1", "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", ")", "=", "StrikeDip", "(", "sl2", ",", "sl1", ",", "sl3", ")", "n1", "=", "np", ".", "sin", "(", "z", ")", "*", "np", ".", "sin", "(", "z2", ")", "# normal vector to plane 1", "n2", "=", "np", ".", "cos", "(", "z", ")", "*", "np", ".", "sin", "(", "z2", ")", "h1", "=", "-", "sl2", "# strike vector of plane 2", "h2", "=", "sl1", "# note h3=0 always so we leave it out", "# n3 = np.cos(z2)", "z", "=", "h1", "*", "n1", "+", "h2", "*", "n2", "z", "=", "z", "/", "np", ".", "sqrt", "(", "h1", "*", "h1", "+", "h2", "*", "h2", ")", "z", "=", "np", ".", "arccos", "(", "z", ")", "rake", "=", "0", "if", "sl3", ">", "0", ":", "rake", "=", "z", "*", "r2d", "if", "sl3", "<=", "0", ":", "rake", "=", "-", "z", "*", "r2d", "return", "(", "strike", ",", "dip", ",", "rake", ")" ]
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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L695-L729
30
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. """ (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]) / np.sqrt(2.0) AN = (V[:, IMAX] - V[:, IMIN]) / np.sqrt(2.0) AER = np.sqrt(np.power(AE[0], 2) + np.power(AE[1], 2) + np.power(AE[2], 2)) ANR = np.sqrt(np.power(AN[0], 2) + np.power(AN[1], 2) + np.power(AN[2], 2)) AE = AE / AER if not ANR: AN = np.array([np.nan, np.nan, np.nan]) else: AN = AN / ANR if AN[2] <= 0.: AN1 = AN AE1 = AE else: AN1 = -AN AE1 = -AE (ft, fd, fl) = TDL(AN1, AE1) return NodalPlane(360 - ft, fd, 180 - fl)
python
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. """ (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]) / np.sqrt(2.0) AN = (V[:, IMAX] - V[:, IMIN]) / np.sqrt(2.0) AER = np.sqrt(np.power(AE[0], 2) + np.power(AE[1], 2) + np.power(AE[2], 2)) ANR = np.sqrt(np.power(AN[0], 2) + np.power(AN[1], 2) + np.power(AN[2], 2)) AE = AE / AER if not ANR: AN = np.array([np.nan, np.nan, np.nan]) else: AN = AN / ANR if AN[2] <= 0.: AN1 = AN AE1 = AE else: AN1 = -AN AE1 = -AE (ft, fd, fl) = TDL(AN1, AE1) return NodalPlane(360 - ft, fd, 180 - fl)
[ "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", "]", ")", "/", "np", ".", "sqrt", "(", "2.0", ")", "AN", "=", "(", "V", "[", ":", ",", "IMAX", "]", "-", "V", "[", ":", ",", "IMIN", "]", ")", "/", "np", ".", "sqrt", "(", "2.0", ")", "AER", "=", "np", ".", "sqrt", "(", "np", ".", "power", "(", "AE", "[", "0", "]", ",", "2", ")", "+", "np", ".", "power", "(", "AE", "[", "1", "]", ",", "2", ")", "+", "np", ".", "power", "(", "AE", "[", "2", "]", ",", "2", ")", ")", "ANR", "=", "np", ".", "sqrt", "(", "np", ".", "power", "(", "AN", "[", "0", "]", ",", "2", ")", "+", "np", ".", "power", "(", "AN", "[", "1", "]", ",", "2", ")", "+", "np", ".", "power", "(", "AN", "[", "2", "]", ",", "2", ")", ")", "AE", "=", "AE", "/", "AER", "if", "not", "ANR", ":", "AN", "=", "np", ".", "array", "(", "[", "np", ".", "nan", ",", "np", ".", "nan", ",", "np", ".", "nan", "]", ")", "else", ":", "AN", "=", "AN", "/", "ANR", "if", "AN", "[", "2", "]", "<=", "0.", ":", "AN1", "=", "AN", "AE1", "=", "AE", "else", ":", "AN1", "=", "-", "AN", "AE1", "=", "-", "AE", "(", "ft", ",", "fd", ",", "fl", ")", "=", "TDL", "(", "AN1", ",", "AE1", ")", "return", "NodalPlane", "(", "360", "-", "ft", ",", "fd", ",", "180", "-", "fl", ")" ]
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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L732-L766
31
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 = 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 = -XN CT = YN if ST >= 0. and CT < 0: FT = 180. - FT if ST < 0. and CT <= 0: FT = 180. + FT if ST < 0. and CT > 0: FT = 360. - FT FL = np.arcsin(abs(ZE)) * CON SL = -ZE if np.fabs(XN) < AAA: CL = XE / YN else: CL = -YE / XN if SL >= 0. and CL < 0: FL = 180. - FL if SL < 0. and CL <= 0: FL = FL - 180. if SL < 0. and CL > 0: FL = -FL else: if - ZN > 1.0: ZN = -1.0 FDH = np.arccos(-ZN) FD = FDH * CON SD = np.sin(FDH) if SD == 0: return ST = -XN / SD CT = YN / SD SX = np.fabs(ST) if SX > 1.0: SX = 1.0 FT = np.arcsin(SX) * CON if ST >= 0. and CT < 0: FT = 180. - FT if ST < 0. and CT <= 0: FT = 180. + FT if ST < 0. and CT > 0: FT = 360. - FT SL = -ZE / SD SX = np.fabs(SL) if SX > 1.0: SX = 1.0 FL = np.arcsin(SX) * CON if ST == 0: CL = XE / CT else: XXX = YN * ZN * ZE / SD / SD + YE CL = -SD * XXX / XN if CT == 0: CL = YE / ST if SL >= 0. and CL < 0: FL = 180. - FL if SL < 0. and CL <= 0: FL = FL - 180. if SL < 0. and CL > 0: FL = -FL return (FT, FD, FL)
python
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 = 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 = -XN CT = YN if ST >= 0. and CT < 0: FT = 180. - FT if ST < 0. and CT <= 0: FT = 180. + FT if ST < 0. and CT > 0: FT = 360. - FT FL = np.arcsin(abs(ZE)) * CON SL = -ZE if np.fabs(XN) < AAA: CL = XE / YN else: CL = -YE / XN if SL >= 0. and CL < 0: FL = 180. - FL if SL < 0. and CL <= 0: FL = FL - 180. if SL < 0. and CL > 0: FL = -FL else: if - ZN > 1.0: ZN = -1.0 FDH = np.arccos(-ZN) FD = FDH * CON SD = np.sin(FDH) if SD == 0: return ST = -XN / SD CT = YN / SD SX = np.fabs(ST) if SX > 1.0: SX = 1.0 FT = np.arcsin(SX) * CON if ST >= 0. and CT < 0: FT = 180. - FT if ST < 0. and CT <= 0: FT = 180. + FT if ST < 0. and CT > 0: FT = 360. - FT SL = -ZE / SD SX = np.fabs(SL) if SX > 1.0: SX = 1.0 FL = np.arcsin(SX) * CON if ST == 0: CL = XE / CT else: XXX = YN * ZN * ZE / SD / SD + YE CL = -SD * XXX / XN if CT == 0: CL = YE / ST if SL >= 0. and CL < 0: FL = 180. - FL if SL < 0. and CL <= 0: FL = FL - 180. if SL < 0. and CL > 0: FL = -FL return (FT, FD, FL)
[ "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", "=", "-", "XN", "CT", "=", "YN", "if", "ST", ">=", "0.", "and", "CT", "<", "0", ":", "FT", "=", "180.", "-", "FT", "if", "ST", "<", "0.", "and", "CT", "<=", "0", ":", "FT", "=", "180.", "+", "FT", "if", "ST", "<", "0.", "and", "CT", ">", "0", ":", "FT", "=", "360.", "-", "FT", "FL", "=", "np", ".", "arcsin", "(", "abs", "(", "ZE", ")", ")", "*", "CON", "SL", "=", "-", "ZE", "if", "np", ".", "fabs", "(", "XN", ")", "<", "AAA", ":", "CL", "=", "XE", "/", "YN", "else", ":", "CL", "=", "-", "YE", "/", "XN", "if", "SL", ">=", "0.", "and", "CL", "<", "0", ":", "FL", "=", "180.", "-", "FL", "if", "SL", "<", "0.", "and", "CL", "<=", "0", ":", "FL", "=", "FL", "-", "180.", "if", "SL", "<", "0.", "and", "CL", ">", "0", ":", "FL", "=", "-", "FL", "else", ":", "if", "-", "ZN", ">", "1.0", ":", "ZN", "=", "-", "1.0", "FDH", "=", "np", ".", "arccos", "(", "-", "ZN", ")", "FD", "=", "FDH", "*", "CON", "SD", "=", "np", ".", "sin", "(", "FDH", ")", "if", "SD", "==", "0", ":", "return", "ST", "=", "-", "XN", "/", "SD", "CT", "=", "YN", "/", "SD", "SX", "=", "np", ".", "fabs", "(", "ST", ")", "if", "SX", ">", "1.0", ":", "SX", "=", "1.0", "FT", "=", "np", ".", "arcsin", "(", "SX", ")", "*", "CON", "if", "ST", ">=", "0.", "and", "CT", "<", "0", ":", "FT", "=", "180.", "-", "FT", "if", "ST", "<", "0.", "and", "CT", "<=", "0", ":", "FT", "=", "180.", "+", "FT", "if", "ST", "<", "0.", "and", "CT", ">", "0", ":", "FT", "=", "360.", "-", "FT", "SL", "=", "-", "ZE", "/", "SD", "SX", "=", "np", ".", "fabs", "(", "SL", ")", "if", "SX", ">", "1.0", ":", "SX", "=", "1.0", "FL", "=", "np", ".", "arcsin", "(", "SX", ")", "*", "CON", "if", "ST", "==", "0", ":", "CL", "=", "XE", "/", "CT", "else", ":", "XXX", "=", "YN", "*", "ZN", "*", "ZE", "/", "SD", "/", "SD", "+", "YE", "CL", "=", "-", "SD", "*", "XXX", "/", "XN", "if", "CT", "==", "0", ":", "CL", "=", "YE", "/", "ST", "if", "SL", ">=", "0.", "and", "CL", "<", "0", ":", "FL", "=", "180.", "-", "FL", "if", "SL", "<", "0.", "and", "CL", "<=", "0", ":", "FL", "=", "FL", "-", "180.", "if", "SL", "<", "0.", "and", "CL", ">", "0", ":", "FL", "=", "-", "FL", "return", "(", "FT", ",", "FD", ",", "FL", ")" ]
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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L769-L849
32
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.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] -= 2 * np.pi pl *= R2D az *= R2D T = PrincipalAxis(D[2], az[2], pl[2]) N = PrincipalAxis(D[1], az[1], pl[1]) P = PrincipalAxis(D[0], az[0], pl[0]) return (T, N, P)
python
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.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] -= 2 * np.pi pl *= R2D az *= R2D T = PrincipalAxis(D[2], az[2], pl[2]) N = PrincipalAxis(D[1], az[1], pl[1]) P = PrincipalAxis(D[0], az[0], pl[0]) return (T, N, P)
[ "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", "]", "-=", "2", "*", "np", ".", "pi", "pl", "*=", "R2D", "az", "*=", "R2D", "T", "=", "PrincipalAxis", "(", "D", "[", "2", "]", ",", "az", "[", "2", "]", ",", "pl", "[", "2", "]", ")", "N", "=", "PrincipalAxis", "(", "D", "[", "1", "]", ",", "az", "[", "1", "]", ",", "pl", "[", "1", "]", ")", "P", "=", "PrincipalAxis", "(", "D", "[", "0", "]", ",", "az", "[", "0", "]", ",", "pl", "[", "0", "]", ")", "return", "(", "T", ",", "N", ",", "P", ")" ]
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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/beachball.py#L852-L879
33
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: Threshold Moment of the distribution (moment rate essentially!) :param float beta: Beta value (b * ln(10.)) of the Tapered Gutenberg-Richter Function :param float corner_momnet: Corner moment of the Tapered Gutenberg-Richter Function :returns: Cumulative probability of moment release > moment ''' cdf = np.exp((moment_threshold - moment) / corner_moment) return ((moment / moment_threshold) ** (-beta)) * cdf
python
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: Threshold Moment of the distribution (moment rate essentially!) :param float beta: Beta value (b * ln(10.)) of the Tapered Gutenberg-Richter Function :param float corner_momnet: Corner moment of the Tapered Gutenberg-Richter Function :returns: Cumulative probability of moment release > 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", "(", "(", "moment", "/", "moment_threshold", ")", "**", "(", "-", "beta", ")", ")", "*", "cdf" ]
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 the Tapered Gutenberg-Richter Function :param float corner_momnet: Corner moment of the Tapered Gutenberg-Richter Function :returns: Cumulative probability of moment release > moment
[ "Tapered", "Gutenberg", "Richter", "Cumulative", "Density", "Function" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/strain/strain_utils.py#L111-L134
34
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: Threshold Moment of the distribution (moment rate essentially!) :param float beta: Beta value (b * ln(10.)) of the Tapered Gutenberg-Richter Function :param float corner_momnet: Corner moment of the Tapered Gutenberg-Richter Function :returns: Absolute probability of moment release > moment ''' return ((beta / moment + 1. / corner_moment) * tapered_gutenberg_richter_cdf(moment, moment_threshold, beta, corner_moment))
python
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: Threshold Moment of the distribution (moment rate essentially!) :param float beta: Beta value (b * ln(10.)) of the Tapered Gutenberg-Richter Function :param float corner_momnet: Corner moment of the Tapered Gutenberg-Richter Function :returns: Absolute probability of moment release > 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", ",", "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: Threshold Moment of the distribution (moment rate essentially!) :param float beta: Beta value (b * ln(10.)) of the Tapered Gutenberg-Richter Function :param float corner_momnet: Corner moment of the Tapered Gutenberg-Richter Function :returns: Absolute probability of moment release > moment
[ "Tapered", "Gutenberg", "-", "Richter", "Probability", "Density", "Function" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/strain/strain_utils.py#L137-L159
35
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 not a directory.' % path) else: os.makedirs(path)
python
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 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", "RuntimeError", "(", "'%s already exists and is not a directory.'", "%", "path", ")", "else", ":", "os", ".", "makedirs", "(", "path", ")" ]
Make all of the directories in the ``path`` using `os.makedirs`.
[ "Make", "all", "of", "the", "directories", "in", "the", "path", "using", "os", ".", "makedirs", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/export/core.py#L80-L91
36
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_uncertainty'] else: raise ValueError('Input mmax uncertainty must be specified!') max_location = np.argmax(catalogue['magnitude']) obsmax = catalogue['magnitude'][max_location] cond = isinstance(catalogue['sigmaMagnitude'], np.ndarray) and \ len(catalogue['sigmaMagnitude']) > 0 and not \ np.all(np.isnan(catalogue['sigmaMagnitude'])) if cond: if not np.isnan(catalogue['sigmaMagnitude'][max_location]): return obsmax, catalogue['sigmaMagnitude'][max_location] else: print('Uncertainty not given on observed Mmax\n' 'Taking largest magnitude uncertainty found in catalogue') return obsmax, np.nanmax(catalogue['sigmaMagnitude']) elif config['input_mmax_uncertainty']: return obsmax, config['input_mmax_uncertainty'] else: raise ValueError('Input mmax uncertainty must be specified!')
python
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_uncertainty'] else: raise ValueError('Input mmax uncertainty must be specified!') max_location = np.argmax(catalogue['magnitude']) obsmax = catalogue['magnitude'][max_location] cond = isinstance(catalogue['sigmaMagnitude'], np.ndarray) and \ len(catalogue['sigmaMagnitude']) > 0 and not \ np.all(np.isnan(catalogue['sigmaMagnitude'])) if cond: if not np.isnan(catalogue['sigmaMagnitude'][max_location]): return obsmax, catalogue['sigmaMagnitude'][max_location] else: print('Uncertainty not given on observed Mmax\n' 'Taking largest magnitude uncertainty found in catalogue') return obsmax, np.nanmax(catalogue['sigmaMagnitude']) elif config['input_mmax_uncertainty']: return obsmax, 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", "[", "'input_mmax'", "]", ",", "config", "[", "'input_mmax_uncertainty'", "]", "else", ":", "raise", "ValueError", "(", "'Input mmax uncertainty must be specified!'", ")", "max_location", "=", "np", ".", "argmax", "(", "catalogue", "[", "'magnitude'", "]", ")", "obsmax", "=", "catalogue", "[", "'magnitude'", "]", "[", "max_location", "]", "cond", "=", "isinstance", "(", "catalogue", "[", "'sigmaMagnitude'", "]", ",", "np", ".", "ndarray", ")", "and", "len", "(", "catalogue", "[", "'sigmaMagnitude'", "]", ")", ">", "0", "and", "not", "np", ".", "all", "(", "np", ".", "isnan", "(", "catalogue", "[", "'sigmaMagnitude'", "]", ")", ")", "if", "cond", ":", "if", "not", "np", ".", "isnan", "(", "catalogue", "[", "'sigmaMagnitude'", "]", "[", "max_location", "]", ")", ":", "return", "obsmax", ",", "catalogue", "[", "'sigmaMagnitude'", "]", "[", "max_location", "]", "else", ":", "print", "(", "'Uncertainty not given on observed Mmax\\n'", "'Taking largest magnitude uncertainty found in catalogue'", ")", "return", "obsmax", ",", "np", ".", "nanmax", "(", "catalogue", "[", "'sigmaMagnitude'", "]", ")", "elif", "config", "[", "'input_mmax_uncertainty'", "]", ":", "return", "obsmax", ",", "config", "[", "'input_mmax_uncertainty'", "]", "else", ":", "raise", "ValueError", "(", "'Input mmax uncertainty must be specified!'", ")" ]
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" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/max_magnitude/base.py#L57-L83
37
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'] >= mmin - 1.E-7)) return neq, mmin
python
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'] >= 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", "(", "np", ".", "sum", "(", "catalogue", "[", "'magnitude'", "]", ">=", "mmin", "-", "1.E-7", ")", ")", "return", "neq", ",", "mmin" ]
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" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/max_magnitude/base.py#L104-L110
38
gem/oq-engine
openquake/hazardlib/geo/surface/complex_fault.py
ComplexFaultSurface.get_dip
def get_dip(self): """ Return the fault dip as the average dip over the mesh. The average dip is defined as the weighted mean inclination of all the mesh cells. See :meth:`openquake.hazardlib.geo.mesh.RectangularMesh.get_mean_inclination_and_azimuth` :returns: The average dip, in decimal degrees. """ # uses the same approach as in simple fault surface if self.dip is None: mesh = self.mesh self.dip, self.strike = mesh.get_mean_inclination_and_azimuth() return self.dip
python
def get_dip(self): """ Return the fault dip as the average dip over the mesh. The average dip is defined as the weighted mean inclination of all the mesh cells. See :meth:`openquake.hazardlib.geo.mesh.RectangularMesh.get_mean_inclination_and_azimuth` :returns: The average dip, in decimal degrees. """ # uses the same approach as in simple fault surface if self.dip is None: mesh = self.mesh self.dip, self.strike = mesh.get_mean_inclination_and_azimuth() return self.dip
[ "def", "get_dip", "(", "self", ")", ":", "# uses the same approach as in simple fault surface", "if", "self", ".", "dip", "is", "None", ":", "mesh", "=", "self", ".", "mesh", "self", ".", "dip", ",", "self", ".", "strike", "=", "mesh", ".", "get_mean_inclination_and_azimuth", "(", ")", "return", "self", ".", "dip" ]
Return the fault dip as the average dip over the mesh. The average dip is defined as the weighted mean inclination of all the mesh cells. See :meth:`openquake.hazardlib.geo.mesh.RectangularMesh.get_mean_inclination_and_azimuth` :returns: The average dip, in decimal degrees.
[ "Return", "the", "fault", "dip", "as", "the", "average", "dip", "over", "the", "mesh", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/complex_fault.py#L96-L111
39
gem/oq-engine
openquake/hazardlib/geo/surface/complex_fault.py
ComplexFaultSurface.check_surface_validity
def check_surface_validity(cls, edges): """ Check validity of the surface. Project edge points to vertical plane anchored to surface upper left edge and with strike equal to top edge strike. Check that resulting polygon is valid. This method doesn't have to be called by hands before creating the surface object, because it is called from :meth:`from_fault_data`. """ # extract coordinates of surface boundary (as defined from edges) full_boundary = [] left_boundary = [] right_boundary = [] for i in range(1, len(edges) - 1): left_boundary.append(edges[i].points[0]) right_boundary.append(edges[i].points[-1]) full_boundary.extend(edges[0].points) full_boundary.extend(right_boundary) full_boundary.extend(edges[-1].points[::-1]) full_boundary.extend(left_boundary[::-1]) lons = [p.longitude for p in full_boundary] lats = [p.latitude for p in full_boundary] depths = [p.depth for p in full_boundary] # define reference plane. Corner points are separated by an arbitrary # distance of 10 km. The mesh spacing is set to 2 km. Both corner # distance and mesh spacing values do not affect the algorithm results. ul = edges[0].points[0] strike = ul.azimuth(edges[0].points[-1]) dist = 10. ur = ul.point_at(dist, 0, strike) bl = Point(ul.longitude, ul.latitude, ul.depth + dist) br = bl.point_at(dist, 0, strike) # project surface boundary to reference plane and check for # validity. ref_plane = PlanarSurface.from_corner_points(ul, ur, br, bl) _, xx, yy = ref_plane._project( spherical_to_cartesian(lons, lats, depths)) coords = [(x, y) for x, y in zip(xx, yy)] p = shapely.geometry.Polygon(coords) if not p.is_valid: raise ValueError('Edges points are not in the right order')
python
def check_surface_validity(cls, edges): """ Check validity of the surface. Project edge points to vertical plane anchored to surface upper left edge and with strike equal to top edge strike. Check that resulting polygon is valid. This method doesn't have to be called by hands before creating the surface object, because it is called from :meth:`from_fault_data`. """ # extract coordinates of surface boundary (as defined from edges) full_boundary = [] left_boundary = [] right_boundary = [] for i in range(1, len(edges) - 1): left_boundary.append(edges[i].points[0]) right_boundary.append(edges[i].points[-1]) full_boundary.extend(edges[0].points) full_boundary.extend(right_boundary) full_boundary.extend(edges[-1].points[::-1]) full_boundary.extend(left_boundary[::-1]) lons = [p.longitude for p in full_boundary] lats = [p.latitude for p in full_boundary] depths = [p.depth for p in full_boundary] # define reference plane. Corner points are separated by an arbitrary # distance of 10 km. The mesh spacing is set to 2 km. Both corner # distance and mesh spacing values do not affect the algorithm results. ul = edges[0].points[0] strike = ul.azimuth(edges[0].points[-1]) dist = 10. ur = ul.point_at(dist, 0, strike) bl = Point(ul.longitude, ul.latitude, ul.depth + dist) br = bl.point_at(dist, 0, strike) # project surface boundary to reference plane and check for # validity. ref_plane = PlanarSurface.from_corner_points(ul, ur, br, bl) _, xx, yy = ref_plane._project( spherical_to_cartesian(lons, lats, depths)) coords = [(x, y) for x, y in zip(xx, yy)] p = shapely.geometry.Polygon(coords) if not p.is_valid: raise ValueError('Edges points are not in the right order')
[ "def", "check_surface_validity", "(", "cls", ",", "edges", ")", ":", "# extract coordinates of surface boundary (as defined from edges)", "full_boundary", "=", "[", "]", "left_boundary", "=", "[", "]", "right_boundary", "=", "[", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "edges", ")", "-", "1", ")", ":", "left_boundary", ".", "append", "(", "edges", "[", "i", "]", ".", "points", "[", "0", "]", ")", "right_boundary", ".", "append", "(", "edges", "[", "i", "]", ".", "points", "[", "-", "1", "]", ")", "full_boundary", ".", "extend", "(", "edges", "[", "0", "]", ".", "points", ")", "full_boundary", ".", "extend", "(", "right_boundary", ")", "full_boundary", ".", "extend", "(", "edges", "[", "-", "1", "]", ".", "points", "[", ":", ":", "-", "1", "]", ")", "full_boundary", ".", "extend", "(", "left_boundary", "[", ":", ":", "-", "1", "]", ")", "lons", "=", "[", "p", ".", "longitude", "for", "p", "in", "full_boundary", "]", "lats", "=", "[", "p", ".", "latitude", "for", "p", "in", "full_boundary", "]", "depths", "=", "[", "p", ".", "depth", "for", "p", "in", "full_boundary", "]", "# define reference plane. Corner points are separated by an arbitrary", "# distance of 10 km. The mesh spacing is set to 2 km. Both corner", "# distance and mesh spacing values do not affect the algorithm results.", "ul", "=", "edges", "[", "0", "]", ".", "points", "[", "0", "]", "strike", "=", "ul", ".", "azimuth", "(", "edges", "[", "0", "]", ".", "points", "[", "-", "1", "]", ")", "dist", "=", "10.", "ur", "=", "ul", ".", "point_at", "(", "dist", ",", "0", ",", "strike", ")", "bl", "=", "Point", "(", "ul", ".", "longitude", ",", "ul", ".", "latitude", ",", "ul", ".", "depth", "+", "dist", ")", "br", "=", "bl", ".", "point_at", "(", "dist", ",", "0", ",", "strike", ")", "# project surface boundary to reference plane and check for", "# validity.", "ref_plane", "=", "PlanarSurface", ".", "from_corner_points", "(", "ul", ",", "ur", ",", "br", ",", "bl", ")", "_", ",", "xx", ",", "yy", "=", "ref_plane", ".", "_project", "(", "spherical_to_cartesian", "(", "lons", ",", "lats", ",", "depths", ")", ")", "coords", "=", "[", "(", "x", ",", "y", ")", "for", "x", ",", "y", "in", "zip", "(", "xx", ",", "yy", ")", "]", "p", "=", "shapely", ".", "geometry", ".", "Polygon", "(", "coords", ")", "if", "not", "p", ".", "is_valid", ":", "raise", "ValueError", "(", "'Edges points are not in the right order'", ")" ]
Check validity of the surface. Project edge points to vertical plane anchored to surface upper left edge and with strike equal to top edge strike. Check that resulting polygon is valid. This method doesn't have to be called by hands before creating the surface object, because it is called from :meth:`from_fault_data`.
[ "Check", "validity", "of", "the", "surface", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/complex_fault.py#L182-L230
40
gem/oq-engine
openquake/hazardlib/geo/surface/complex_fault.py
ComplexFaultSurface.surface_projection_from_fault_data
def surface_projection_from_fault_data(cls, edges): """ Get a surface projection of the complex fault surface. :param edges: A list of horizontal edges of the surface as instances of :class:`openquake.hazardlib.geo.line.Line`. :returns: Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon` describing the surface projection of the complex fault. """ # collect lons and lats of all the vertices of all the edges lons = [] lats = [] for edge in edges: for point in edge: lons.append(point.longitude) lats.append(point.latitude) lons = numpy.array(lons, dtype=float) lats = numpy.array(lats, dtype=float) return Mesh(lons, lats, depths=None).get_convex_hull()
python
def surface_projection_from_fault_data(cls, edges): """ Get a surface projection of the complex fault surface. :param edges: A list of horizontal edges of the surface as instances of :class:`openquake.hazardlib.geo.line.Line`. :returns: Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon` describing the surface projection of the complex fault. """ # collect lons and lats of all the vertices of all the edges lons = [] lats = [] for edge in edges: for point in edge: lons.append(point.longitude) lats.append(point.latitude) lons = numpy.array(lons, dtype=float) lats = numpy.array(lats, dtype=float) return Mesh(lons, lats, depths=None).get_convex_hull()
[ "def", "surface_projection_from_fault_data", "(", "cls", ",", "edges", ")", ":", "# collect lons and lats of all the vertices of all the edges", "lons", "=", "[", "]", "lats", "=", "[", "]", "for", "edge", "in", "edges", ":", "for", "point", "in", "edge", ":", "lons", ".", "append", "(", "point", ".", "longitude", ")", "lats", ".", "append", "(", "point", ".", "latitude", ")", "lons", "=", "numpy", ".", "array", "(", "lons", ",", "dtype", "=", "float", ")", "lats", "=", "numpy", ".", "array", "(", "lats", ",", "dtype", "=", "float", ")", "return", "Mesh", "(", "lons", ",", "lats", ",", "depths", "=", "None", ")", ".", "get_convex_hull", "(", ")" ]
Get a surface projection of the complex fault surface. :param edges: A list of horizontal edges of the surface as instances of :class:`openquake.hazardlib.geo.line.Line`. :returns: Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon` describing the surface projection of the complex fault.
[ "Get", "a", "surface", "projection", "of", "the", "complex", "fault", "surface", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/complex_fault.py#L302-L323
41
gem/oq-engine
openquake/calculators/base.py
check_time_event
def check_time_event(oqparam, occupancy_periods): """ Check the `time_event` parameter in the datastore, by comparing with the periods found in the exposure. """ time_event = oqparam.time_event if time_event and time_event not in occupancy_periods: raise ValueError( 'time_event is %s in %s, but the exposure contains %s' % (time_event, oqparam.inputs['job_ini'], ', '.join(occupancy_periods)))
python
def check_time_event(oqparam, occupancy_periods): """ Check the `time_event` parameter in the datastore, by comparing with the periods found in the exposure. """ time_event = oqparam.time_event if time_event and time_event not in occupancy_periods: raise ValueError( 'time_event is %s in %s, but the exposure contains %s' % (time_event, oqparam.inputs['job_ini'], ', '.join(occupancy_periods)))
[ "def", "check_time_event", "(", "oqparam", ",", "occupancy_periods", ")", ":", "time_event", "=", "oqparam", ".", "time_event", "if", "time_event", "and", "time_event", "not", "in", "occupancy_periods", ":", "raise", "ValueError", "(", "'time_event is %s in %s, but the exposure contains %s'", "%", "(", "time_event", ",", "oqparam", ".", "inputs", "[", "'job_ini'", "]", ",", "', '", ".", "join", "(", "occupancy_periods", ")", ")", ")" ]
Check the `time_event` parameter in the datastore, by comparing with the periods found in the exposure.
[ "Check", "the", "time_event", "parameter", "in", "the", "datastore", "by", "comparing", "with", "the", "periods", "found", "in", "the", "exposure", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L321-L331
42
gem/oq-engine
openquake/calculators/base.py
get_idxs
def get_idxs(data, eid2idx): """ Convert from event IDs to event indices. :param data: an array with a field eid :param eid2idx: a dictionary eid -> idx :returns: the array of event indices """ uniq, inv = numpy.unique(data['eid'], return_inverse=True) idxs = numpy.array([eid2idx[eid] for eid in uniq])[inv] return idxs
python
def get_idxs(data, eid2idx): """ Convert from event IDs to event indices. :param data: an array with a field eid :param eid2idx: a dictionary eid -> idx :returns: the array of event indices """ uniq, inv = numpy.unique(data['eid'], return_inverse=True) idxs = numpy.array([eid2idx[eid] for eid in uniq])[inv] return idxs
[ "def", "get_idxs", "(", "data", ",", "eid2idx", ")", ":", "uniq", ",", "inv", "=", "numpy", ".", "unique", "(", "data", "[", "'eid'", "]", ",", "return_inverse", "=", "True", ")", "idxs", "=", "numpy", ".", "array", "(", "[", "eid2idx", "[", "eid", "]", "for", "eid", "in", "uniq", "]", ")", "[", "inv", "]", "return", "idxs" ]
Convert from event IDs to event indices. :param data: an array with a field eid :param eid2idx: a dictionary eid -> idx :returns: the array of event indices
[ "Convert", "from", "event", "IDs", "to", "event", "indices", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L959-L969
43
gem/oq-engine
openquake/calculators/base.py
import_gmfs
def import_gmfs(dstore, fname, sids): """ Import in the datastore a ground motion field CSV file. :param dstore: the datastore :param fname: the CSV file :param sids: the site IDs (complete) :returns: event_ids, num_rlzs """ array = writers.read_composite_array(fname).array # has header rlzi, sid, eid, gmv_PGA, ... imts = [name[4:] for name in array.dtype.names[3:]] n_imts = len(imts) gmf_data_dt = numpy.dtype( [('rlzi', U16), ('sid', U32), ('eid', U64), ('gmv', (F32, (n_imts,)))]) # store the events eids = numpy.unique(array['eid']) eids.sort() E = len(eids) eid2idx = dict(zip(eids, range(E))) events = numpy.zeros(E, rupture.events_dt) events['eid'] = eids dstore['events'] = events # store the GMFs dic = general.group_array(array.view(gmf_data_dt), 'sid') lst = [] offset = 0 for sid in sids: n = len(dic.get(sid, [])) lst.append((offset, offset + n)) if n: offset += n gmvs = dic[sid] gmvs['eid'] = get_idxs(gmvs, eid2idx) gmvs['rlzi'] = 0 # effectively there is only 1 realization dstore.extend('gmf_data/data', gmvs) dstore['gmf_data/indices'] = numpy.array(lst, U32) dstore['gmf_data/imts'] = ' '.join(imts) sig_eps_dt = [('eid', U64), ('sig', (F32, n_imts)), ('eps', (F32, n_imts))] dstore['gmf_data/sigma_epsilon'] = numpy.zeros(0, sig_eps_dt) dstore['weights'] = numpy.ones((1, n_imts)) return eids
python
def import_gmfs(dstore, fname, sids): """ Import in the datastore a ground motion field CSV file. :param dstore: the datastore :param fname: the CSV file :param sids: the site IDs (complete) :returns: event_ids, num_rlzs """ array = writers.read_composite_array(fname).array # has header rlzi, sid, eid, gmv_PGA, ... imts = [name[4:] for name in array.dtype.names[3:]] n_imts = len(imts) gmf_data_dt = numpy.dtype( [('rlzi', U16), ('sid', U32), ('eid', U64), ('gmv', (F32, (n_imts,)))]) # store the events eids = numpy.unique(array['eid']) eids.sort() E = len(eids) eid2idx = dict(zip(eids, range(E))) events = numpy.zeros(E, rupture.events_dt) events['eid'] = eids dstore['events'] = events # store the GMFs dic = general.group_array(array.view(gmf_data_dt), 'sid') lst = [] offset = 0 for sid in sids: n = len(dic.get(sid, [])) lst.append((offset, offset + n)) if n: offset += n gmvs = dic[sid] gmvs['eid'] = get_idxs(gmvs, eid2idx) gmvs['rlzi'] = 0 # effectively there is only 1 realization dstore.extend('gmf_data/data', gmvs) dstore['gmf_data/indices'] = numpy.array(lst, U32) dstore['gmf_data/imts'] = ' '.join(imts) sig_eps_dt = [('eid', U64), ('sig', (F32, n_imts)), ('eps', (F32, n_imts))] dstore['gmf_data/sigma_epsilon'] = numpy.zeros(0, sig_eps_dt) dstore['weights'] = numpy.ones((1, n_imts)) return eids
[ "def", "import_gmfs", "(", "dstore", ",", "fname", ",", "sids", ")", ":", "array", "=", "writers", ".", "read_composite_array", "(", "fname", ")", ".", "array", "# has header rlzi, sid, eid, gmv_PGA, ...", "imts", "=", "[", "name", "[", "4", ":", "]", "for", "name", "in", "array", ".", "dtype", ".", "names", "[", "3", ":", "]", "]", "n_imts", "=", "len", "(", "imts", ")", "gmf_data_dt", "=", "numpy", ".", "dtype", "(", "[", "(", "'rlzi'", ",", "U16", ")", ",", "(", "'sid'", ",", "U32", ")", ",", "(", "'eid'", ",", "U64", ")", ",", "(", "'gmv'", ",", "(", "F32", ",", "(", "n_imts", ",", ")", ")", ")", "]", ")", "# store the events", "eids", "=", "numpy", ".", "unique", "(", "array", "[", "'eid'", "]", ")", "eids", ".", "sort", "(", ")", "E", "=", "len", "(", "eids", ")", "eid2idx", "=", "dict", "(", "zip", "(", "eids", ",", "range", "(", "E", ")", ")", ")", "events", "=", "numpy", ".", "zeros", "(", "E", ",", "rupture", ".", "events_dt", ")", "events", "[", "'eid'", "]", "=", "eids", "dstore", "[", "'events'", "]", "=", "events", "# store the GMFs", "dic", "=", "general", ".", "group_array", "(", "array", ".", "view", "(", "gmf_data_dt", ")", ",", "'sid'", ")", "lst", "=", "[", "]", "offset", "=", "0", "for", "sid", "in", "sids", ":", "n", "=", "len", "(", "dic", ".", "get", "(", "sid", ",", "[", "]", ")", ")", "lst", ".", "append", "(", "(", "offset", ",", "offset", "+", "n", ")", ")", "if", "n", ":", "offset", "+=", "n", "gmvs", "=", "dic", "[", "sid", "]", "gmvs", "[", "'eid'", "]", "=", "get_idxs", "(", "gmvs", ",", "eid2idx", ")", "gmvs", "[", "'rlzi'", "]", "=", "0", "# effectively there is only 1 realization", "dstore", ".", "extend", "(", "'gmf_data/data'", ",", "gmvs", ")", "dstore", "[", "'gmf_data/indices'", "]", "=", "numpy", ".", "array", "(", "lst", ",", "U32", ")", "dstore", "[", "'gmf_data/imts'", "]", "=", "' '", ".", "join", "(", "imts", ")", "sig_eps_dt", "=", "[", "(", "'eid'", ",", "U64", ")", ",", "(", "'sig'", ",", "(", "F32", ",", "n_imts", ")", ")", ",", "(", "'eps'", ",", "(", "F32", ",", "n_imts", ")", ")", "]", "dstore", "[", "'gmf_data/sigma_epsilon'", "]", "=", "numpy", ".", "zeros", "(", "0", ",", "sig_eps_dt", ")", "dstore", "[", "'weights'", "]", "=", "numpy", ".", "ones", "(", "(", "1", ",", "n_imts", ")", ")", "return", "eids" ]
Import in the datastore a ground motion field CSV file. :param dstore: the datastore :param fname: the CSV file :param sids: the site IDs (complete) :returns: event_ids, num_rlzs
[ "Import", "in", "the", "datastore", "a", "ground", "motion", "field", "CSV", "file", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L972-L1013
44
gem/oq-engine
openquake/calculators/base.py
BaseCalculator.save_params
def save_params(self, **kw): """ Update the current calculation parameters and save engine_version """ if ('hazard_calculation_id' in kw and kw['hazard_calculation_id'] is None): del kw['hazard_calculation_id'] vars(self.oqparam).update(**kw) self.datastore['oqparam'] = self.oqparam # save the updated oqparam attrs = self.datastore['/'].attrs attrs['engine_version'] = engine_version attrs['date'] = datetime.now().isoformat()[:19] if 'checksum32' not in attrs: attrs['checksum32'] = readinput.get_checksum32(self.oqparam) self.datastore.flush()
python
def save_params(self, **kw): """ Update the current calculation parameters and save engine_version """ if ('hazard_calculation_id' in kw and kw['hazard_calculation_id'] is None): del kw['hazard_calculation_id'] vars(self.oqparam).update(**kw) self.datastore['oqparam'] = self.oqparam # save the updated oqparam attrs = self.datastore['/'].attrs attrs['engine_version'] = engine_version attrs['date'] = datetime.now().isoformat()[:19] if 'checksum32' not in attrs: attrs['checksum32'] = readinput.get_checksum32(self.oqparam) self.datastore.flush()
[ "def", "save_params", "(", "self", ",", "*", "*", "kw", ")", ":", "if", "(", "'hazard_calculation_id'", "in", "kw", "and", "kw", "[", "'hazard_calculation_id'", "]", "is", "None", ")", ":", "del", "kw", "[", "'hazard_calculation_id'", "]", "vars", "(", "self", ".", "oqparam", ")", ".", "update", "(", "*", "*", "kw", ")", "self", ".", "datastore", "[", "'oqparam'", "]", "=", "self", ".", "oqparam", "# save the updated oqparam", "attrs", "=", "self", ".", "datastore", "[", "'/'", "]", ".", "attrs", "attrs", "[", "'engine_version'", "]", "=", "engine_version", "attrs", "[", "'date'", "]", "=", "datetime", ".", "now", "(", ")", ".", "isoformat", "(", ")", "[", ":", "19", "]", "if", "'checksum32'", "not", "in", "attrs", ":", "attrs", "[", "'checksum32'", "]", "=", "readinput", ".", "get_checksum32", "(", "self", ".", "oqparam", ")", "self", ".", "datastore", ".", "flush", "(", ")" ]
Update the current calculation parameters and save engine_version
[ "Update", "the", "current", "calculation", "parameters", "and", "save", "engine_version" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L142-L156
45
gem/oq-engine
openquake/calculators/base.py
BaseCalculator.run
def run(self, pre_execute=True, concurrent_tasks=None, close=True, **kw): """ Run the calculation and return the exported outputs. """ with self._monitor: self._monitor.username = kw.get('username', '') self._monitor.hdf5 = self.datastore.hdf5 if concurrent_tasks is None: # use the job.ini parameter ct = self.oqparam.concurrent_tasks else: # used the parameter passed in the command-line ct = concurrent_tasks if ct == 0: # disable distribution temporarily oq_distribute = os.environ.get('OQ_DISTRIBUTE') os.environ['OQ_DISTRIBUTE'] = 'no' if ct != self.oqparam.concurrent_tasks: # save the used concurrent_tasks self.oqparam.concurrent_tasks = ct self.save_params(**kw) try: if pre_execute: self.pre_execute() self.result = self.execute() if self.result is not None: self.post_execute(self.result) self.before_export() self.export(kw.get('exports', '')) except Exception: if kw.get('pdb'): # post-mortem debug tb = sys.exc_info()[2] traceback.print_tb(tb) pdb.post_mortem(tb) else: logging.critical('', exc_info=True) raise finally: # cleanup globals if ct == 0: # restore OQ_DISTRIBUTE if oq_distribute is None: # was not set del os.environ['OQ_DISTRIBUTE'] else: os.environ['OQ_DISTRIBUTE'] = oq_distribute readinput.pmap = None readinput.exposure = None readinput.gmfs = None readinput.eids = None self._monitor.flush() if close: # in the engine we close later self.result = None try: self.datastore.close() except (RuntimeError, ValueError): # sometimes produces errors but they are difficult to # reproduce logging.warning('', exc_info=True) return getattr(self, 'exported', {})
python
def run(self, pre_execute=True, concurrent_tasks=None, close=True, **kw): """ Run the calculation and return the exported outputs. """ with self._monitor: self._monitor.username = kw.get('username', '') self._monitor.hdf5 = self.datastore.hdf5 if concurrent_tasks is None: # use the job.ini parameter ct = self.oqparam.concurrent_tasks else: # used the parameter passed in the command-line ct = concurrent_tasks if ct == 0: # disable distribution temporarily oq_distribute = os.environ.get('OQ_DISTRIBUTE') os.environ['OQ_DISTRIBUTE'] = 'no' if ct != self.oqparam.concurrent_tasks: # save the used concurrent_tasks self.oqparam.concurrent_tasks = ct self.save_params(**kw) try: if pre_execute: self.pre_execute() self.result = self.execute() if self.result is not None: self.post_execute(self.result) self.before_export() self.export(kw.get('exports', '')) except Exception: if kw.get('pdb'): # post-mortem debug tb = sys.exc_info()[2] traceback.print_tb(tb) pdb.post_mortem(tb) else: logging.critical('', exc_info=True) raise finally: # cleanup globals if ct == 0: # restore OQ_DISTRIBUTE if oq_distribute is None: # was not set del os.environ['OQ_DISTRIBUTE'] else: os.environ['OQ_DISTRIBUTE'] = oq_distribute readinput.pmap = None readinput.exposure = None readinput.gmfs = None readinput.eids = None self._monitor.flush() if close: # in the engine we close later self.result = None try: self.datastore.close() except (RuntimeError, ValueError): # sometimes produces errors but they are difficult to # reproduce logging.warning('', exc_info=True) return getattr(self, 'exported', {})
[ "def", "run", "(", "self", ",", "pre_execute", "=", "True", ",", "concurrent_tasks", "=", "None", ",", "close", "=", "True", ",", "*", "*", "kw", ")", ":", "with", "self", ".", "_monitor", ":", "self", ".", "_monitor", ".", "username", "=", "kw", ".", "get", "(", "'username'", ",", "''", ")", "self", ".", "_monitor", ".", "hdf5", "=", "self", ".", "datastore", ".", "hdf5", "if", "concurrent_tasks", "is", "None", ":", "# use the job.ini parameter", "ct", "=", "self", ".", "oqparam", ".", "concurrent_tasks", "else", ":", "# used the parameter passed in the command-line", "ct", "=", "concurrent_tasks", "if", "ct", "==", "0", ":", "# disable distribution temporarily", "oq_distribute", "=", "os", ".", "environ", ".", "get", "(", "'OQ_DISTRIBUTE'", ")", "os", ".", "environ", "[", "'OQ_DISTRIBUTE'", "]", "=", "'no'", "if", "ct", "!=", "self", ".", "oqparam", ".", "concurrent_tasks", ":", "# save the used concurrent_tasks", "self", ".", "oqparam", ".", "concurrent_tasks", "=", "ct", "self", ".", "save_params", "(", "*", "*", "kw", ")", "try", ":", "if", "pre_execute", ":", "self", ".", "pre_execute", "(", ")", "self", ".", "result", "=", "self", ".", "execute", "(", ")", "if", "self", ".", "result", "is", "not", "None", ":", "self", ".", "post_execute", "(", "self", ".", "result", ")", "self", ".", "before_export", "(", ")", "self", ".", "export", "(", "kw", ".", "get", "(", "'exports'", ",", "''", ")", ")", "except", "Exception", ":", "if", "kw", ".", "get", "(", "'pdb'", ")", ":", "# post-mortem debug", "tb", "=", "sys", ".", "exc_info", "(", ")", "[", "2", "]", "traceback", ".", "print_tb", "(", "tb", ")", "pdb", ".", "post_mortem", "(", "tb", ")", "else", ":", "logging", ".", "critical", "(", "''", ",", "exc_info", "=", "True", ")", "raise", "finally", ":", "# cleanup globals", "if", "ct", "==", "0", ":", "# restore OQ_DISTRIBUTE", "if", "oq_distribute", "is", "None", ":", "# was not set", "del", "os", ".", "environ", "[", "'OQ_DISTRIBUTE'", "]", "else", ":", "os", ".", "environ", "[", "'OQ_DISTRIBUTE'", "]", "=", "oq_distribute", "readinput", ".", "pmap", "=", "None", "readinput", ".", "exposure", "=", "None", "readinput", ".", "gmfs", "=", "None", "readinput", ".", "eids", "=", "None", "self", ".", "_monitor", ".", "flush", "(", ")", "if", "close", ":", "# in the engine we close later", "self", ".", "result", "=", "None", "try", ":", "self", ".", "datastore", ".", "close", "(", ")", "except", "(", "RuntimeError", ",", "ValueError", ")", ":", "# sometimes produces errors but they are difficult to", "# reproduce", "logging", ".", "warning", "(", "''", ",", "exc_info", "=", "True", ")", "return", "getattr", "(", "self", ",", "'exported'", ",", "{", "}", ")" ]
Run the calculation and return the exported outputs.
[ "Run", "the", "calculation", "and", "return", "the", "exported", "outputs", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L175-L231
46
gem/oq-engine
openquake/calculators/base.py
BaseCalculator.export
def export(self, exports=None): """ Export all the outputs in the datastore in the given export formats. Individual outputs are not exported if there are multiple realizations. """ self.exported = getattr(self.precalc, 'exported', {}) if isinstance(exports, tuple): fmts = exports elif exports: # is a string fmts = exports.split(',') elif isinstance(self.oqparam.exports, tuple): fmts = self.oqparam.exports else: # is a string fmts = self.oqparam.exports.split(',') keys = set(self.datastore) has_hcurves = ('hcurves-stats' in self.datastore or 'hcurves-rlzs' in self.datastore) if has_hcurves: keys.add('hcurves') for fmt in fmts: if not fmt: continue for key in sorted(keys): # top level keys if 'rlzs' in key and self.R > 1: continue # skip individual curves self._export((key, fmt)) if has_hcurves and self.oqparam.hazard_maps: self._export(('hmaps', fmt)) if has_hcurves and self.oqparam.uniform_hazard_spectra: self._export(('uhs', fmt))
python
def export(self, exports=None): """ Export all the outputs in the datastore in the given export formats. Individual outputs are not exported if there are multiple realizations. """ self.exported = getattr(self.precalc, 'exported', {}) if isinstance(exports, tuple): fmts = exports elif exports: # is a string fmts = exports.split(',') elif isinstance(self.oqparam.exports, tuple): fmts = self.oqparam.exports else: # is a string fmts = self.oqparam.exports.split(',') keys = set(self.datastore) has_hcurves = ('hcurves-stats' in self.datastore or 'hcurves-rlzs' in self.datastore) if has_hcurves: keys.add('hcurves') for fmt in fmts: if not fmt: continue for key in sorted(keys): # top level keys if 'rlzs' in key and self.R > 1: continue # skip individual curves self._export((key, fmt)) if has_hcurves and self.oqparam.hazard_maps: self._export(('hmaps', fmt)) if has_hcurves and self.oqparam.uniform_hazard_spectra: self._export(('uhs', fmt))
[ "def", "export", "(", "self", ",", "exports", "=", "None", ")", ":", "self", ".", "exported", "=", "getattr", "(", "self", ".", "precalc", ",", "'exported'", ",", "{", "}", ")", "if", "isinstance", "(", "exports", ",", "tuple", ")", ":", "fmts", "=", "exports", "elif", "exports", ":", "# is a string", "fmts", "=", "exports", ".", "split", "(", "','", ")", "elif", "isinstance", "(", "self", ".", "oqparam", ".", "exports", ",", "tuple", ")", ":", "fmts", "=", "self", ".", "oqparam", ".", "exports", "else", ":", "# is a string", "fmts", "=", "self", ".", "oqparam", ".", "exports", ".", "split", "(", "','", ")", "keys", "=", "set", "(", "self", ".", "datastore", ")", "has_hcurves", "=", "(", "'hcurves-stats'", "in", "self", ".", "datastore", "or", "'hcurves-rlzs'", "in", "self", ".", "datastore", ")", "if", "has_hcurves", ":", "keys", ".", "add", "(", "'hcurves'", ")", "for", "fmt", "in", "fmts", ":", "if", "not", "fmt", ":", "continue", "for", "key", "in", "sorted", "(", "keys", ")", ":", "# top level keys", "if", "'rlzs'", "in", "key", "and", "self", ".", "R", ">", "1", ":", "continue", "# skip individual curves", "self", ".", "_export", "(", "(", "key", ",", "fmt", ")", ")", "if", "has_hcurves", "and", "self", ".", "oqparam", ".", "hazard_maps", ":", "self", ".", "_export", "(", "(", "'hmaps'", ",", "fmt", ")", ")", "if", "has_hcurves", "and", "self", ".", "oqparam", ".", "uniform_hazard_spectra", ":", "self", ".", "_export", "(", "(", "'uhs'", ",", "fmt", ")", ")" ]
Export all the outputs in the datastore in the given export formats. Individual outputs are not exported if there are multiple realizations.
[ "Export", "all", "the", "outputs", "in", "the", "datastore", "in", "the", "given", "export", "formats", ".", "Individual", "outputs", "are", "not", "exported", "if", "there", "are", "multiple", "realizations", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L260-L289
47
gem/oq-engine
openquake/calculators/base.py
BaseCalculator.before_export
def before_export(self): """ Set the attributes nbytes """ # sanity check that eff_ruptures have been set, i.e. are not -1 try: csm_info = self.datastore['csm_info'] except KeyError: csm_info = self.datastore['csm_info'] = self.csm.info for sm in csm_info.source_models: for sg in sm.src_groups: assert sg.eff_ruptures != -1, sg for key in self.datastore: self.datastore.set_nbytes(key) self.datastore.flush()
python
def before_export(self): """ Set the attributes nbytes """ # sanity check that eff_ruptures have been set, i.e. are not -1 try: csm_info = self.datastore['csm_info'] except KeyError: csm_info = self.datastore['csm_info'] = self.csm.info for sm in csm_info.source_models: for sg in sm.src_groups: assert sg.eff_ruptures != -1, sg for key in self.datastore: self.datastore.set_nbytes(key) self.datastore.flush()
[ "def", "before_export", "(", "self", ")", ":", "# sanity check that eff_ruptures have been set, i.e. are not -1", "try", ":", "csm_info", "=", "self", ".", "datastore", "[", "'csm_info'", "]", "except", "KeyError", ":", "csm_info", "=", "self", ".", "datastore", "[", "'csm_info'", "]", "=", "self", ".", "csm", ".", "info", "for", "sm", "in", "csm_info", ".", "source_models", ":", "for", "sg", "in", "sm", ".", "src_groups", ":", "assert", "sg", ".", "eff_ruptures", "!=", "-", "1", ",", "sg", "for", "key", "in", "self", ".", "datastore", ":", "self", ".", "datastore", ".", "set_nbytes", "(", "key", ")", "self", ".", "datastore", ".", "flush", "(", ")" ]
Set the attributes nbytes
[ "Set", "the", "attributes", "nbytes" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L303-L318
48
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.read_inputs
def read_inputs(self): """ Read risk data and sources if any """ oq = self.oqparam self._read_risk_data() self.check_overflow() # check if self.sitecol is too large if ('source_model_logic_tree' in oq.inputs and oq.hazard_calculation_id is None): self.csm = readinput.get_composite_source_model( oq, self.monitor(), srcfilter=self.src_filter) self.init()
python
def read_inputs(self): """ Read risk data and sources if any """ oq = self.oqparam self._read_risk_data() self.check_overflow() # check if self.sitecol is too large if ('source_model_logic_tree' in oq.inputs and oq.hazard_calculation_id is None): self.csm = readinput.get_composite_source_model( oq, self.monitor(), srcfilter=self.src_filter) self.init()
[ "def", "read_inputs", "(", "self", ")", ":", "oq", "=", "self", ".", "oqparam", "self", ".", "_read_risk_data", "(", ")", "self", ".", "check_overflow", "(", ")", "# check if self.sitecol is too large", "if", "(", "'source_model_logic_tree'", "in", "oq", ".", "inputs", "and", "oq", ".", "hazard_calculation_id", "is", "None", ")", ":", "self", ".", "csm", "=", "readinput", ".", "get_composite_source_model", "(", "oq", ",", "self", ".", "monitor", "(", ")", ",", "srcfilter", "=", "self", ".", "src_filter", ")", "self", ".", "init", "(", ")" ]
Read risk data and sources if any
[ "Read", "risk", "data", "and", "sources", "if", "any" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L406-L417
49
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.pre_execute
def pre_execute(self): """ Check if there is a previous calculation ID. If yes, read the inputs by retrieving the previous calculation; if not, read the inputs directly. """ oq = self.oqparam if 'gmfs' in oq.inputs or 'multi_peril' in oq.inputs: # read hazard from files assert not oq.hazard_calculation_id, ( 'You cannot use --hc together with gmfs_file') self.read_inputs() if 'gmfs' in oq.inputs: save_gmfs(self) else: self.save_multi_peril() elif 'hazard_curves' in oq.inputs: # read hazard from file assert not oq.hazard_calculation_id, ( 'You cannot use --hc together with hazard_curves') haz_sitecol = readinput.get_site_collection(oq) # NB: horrible: get_site_collection calls get_pmap_from_nrml # that sets oq.investigation_time, so it must be called first self.load_riskmodel() # must be after get_site_collection self.read_exposure(haz_sitecol) # define .assets_by_site self.datastore['poes/grp-00'] = fix_ones(readinput.pmap) self.datastore['sitecol'] = self.sitecol self.datastore['assetcol'] = self.assetcol self.datastore['csm_info'] = fake = source.CompositionInfo.fake() self.rlzs_assoc = fake.get_rlzs_assoc() elif oq.hazard_calculation_id: parent = util.read(oq.hazard_calculation_id) self.check_precalc(parent['oqparam'].calculation_mode) self.datastore.parent = parent # copy missing parameters from the parent params = {name: value for name, value in vars(parent['oqparam']).items() if name not in vars(self.oqparam)} self.save_params(**params) self.read_inputs() oqp = parent['oqparam'] if oqp.investigation_time != oq.investigation_time: raise ValueError( 'The parent calculation was using investigation_time=%s' ' != %s' % (oqp.investigation_time, oq.investigation_time)) if oqp.minimum_intensity != oq.minimum_intensity: raise ValueError( 'The parent calculation was using minimum_intensity=%s' ' != %s' % (oqp.minimum_intensity, oq.minimum_intensity)) missing_imts = set(oq.risk_imtls) - set(oqp.imtls) if missing_imts: raise ValueError( 'The parent calculation is missing the IMT(s) %s' % ', '.join(missing_imts)) elif self.__class__.precalc: calc = calculators[self.__class__.precalc]( self.oqparam, self.datastore.calc_id) calc.run() self.param = calc.param self.sitecol = calc.sitecol self.assetcol = calc.assetcol self.riskmodel = calc.riskmodel if hasattr(calc, 'rlzs_assoc'): self.rlzs_assoc = calc.rlzs_assoc else: # this happens for instance for a scenario_damage without # rupture, gmfs, multi_peril raise InvalidFile( '%(job_ini)s: missing gmfs_csv, multi_peril_csv' % oq.inputs) if hasattr(calc, 'csm'): # no scenario self.csm = calc.csm else: self.read_inputs() if self.riskmodel: self.save_riskmodel()
python
def pre_execute(self): """ Check if there is a previous calculation ID. If yes, read the inputs by retrieving the previous calculation; if not, read the inputs directly. """ oq = self.oqparam if 'gmfs' in oq.inputs or 'multi_peril' in oq.inputs: # read hazard from files assert not oq.hazard_calculation_id, ( 'You cannot use --hc together with gmfs_file') self.read_inputs() if 'gmfs' in oq.inputs: save_gmfs(self) else: self.save_multi_peril() elif 'hazard_curves' in oq.inputs: # read hazard from file assert not oq.hazard_calculation_id, ( 'You cannot use --hc together with hazard_curves') haz_sitecol = readinput.get_site_collection(oq) # NB: horrible: get_site_collection calls get_pmap_from_nrml # that sets oq.investigation_time, so it must be called first self.load_riskmodel() # must be after get_site_collection self.read_exposure(haz_sitecol) # define .assets_by_site self.datastore['poes/grp-00'] = fix_ones(readinput.pmap) self.datastore['sitecol'] = self.sitecol self.datastore['assetcol'] = self.assetcol self.datastore['csm_info'] = fake = source.CompositionInfo.fake() self.rlzs_assoc = fake.get_rlzs_assoc() elif oq.hazard_calculation_id: parent = util.read(oq.hazard_calculation_id) self.check_precalc(parent['oqparam'].calculation_mode) self.datastore.parent = parent # copy missing parameters from the parent params = {name: value for name, value in vars(parent['oqparam']).items() if name not in vars(self.oqparam)} self.save_params(**params) self.read_inputs() oqp = parent['oqparam'] if oqp.investigation_time != oq.investigation_time: raise ValueError( 'The parent calculation was using investigation_time=%s' ' != %s' % (oqp.investigation_time, oq.investigation_time)) if oqp.minimum_intensity != oq.minimum_intensity: raise ValueError( 'The parent calculation was using minimum_intensity=%s' ' != %s' % (oqp.minimum_intensity, oq.minimum_intensity)) missing_imts = set(oq.risk_imtls) - set(oqp.imtls) if missing_imts: raise ValueError( 'The parent calculation is missing the IMT(s) %s' % ', '.join(missing_imts)) elif self.__class__.precalc: calc = calculators[self.__class__.precalc]( self.oqparam, self.datastore.calc_id) calc.run() self.param = calc.param self.sitecol = calc.sitecol self.assetcol = calc.assetcol self.riskmodel = calc.riskmodel if hasattr(calc, 'rlzs_assoc'): self.rlzs_assoc = calc.rlzs_assoc else: # this happens for instance for a scenario_damage without # rupture, gmfs, multi_peril raise InvalidFile( '%(job_ini)s: missing gmfs_csv, multi_peril_csv' % oq.inputs) if hasattr(calc, 'csm'): # no scenario self.csm = calc.csm else: self.read_inputs() if self.riskmodel: self.save_riskmodel()
[ "def", "pre_execute", "(", "self", ")", ":", "oq", "=", "self", ".", "oqparam", "if", "'gmfs'", "in", "oq", ".", "inputs", "or", "'multi_peril'", "in", "oq", ".", "inputs", ":", "# read hazard from files", "assert", "not", "oq", ".", "hazard_calculation_id", ",", "(", "'You cannot use --hc together with gmfs_file'", ")", "self", ".", "read_inputs", "(", ")", "if", "'gmfs'", "in", "oq", ".", "inputs", ":", "save_gmfs", "(", "self", ")", "else", ":", "self", ".", "save_multi_peril", "(", ")", "elif", "'hazard_curves'", "in", "oq", ".", "inputs", ":", "# read hazard from file", "assert", "not", "oq", ".", "hazard_calculation_id", ",", "(", "'You cannot use --hc together with hazard_curves'", ")", "haz_sitecol", "=", "readinput", ".", "get_site_collection", "(", "oq", ")", "# NB: horrible: get_site_collection calls get_pmap_from_nrml", "# that sets oq.investigation_time, so it must be called first", "self", ".", "load_riskmodel", "(", ")", "# must be after get_site_collection", "self", ".", "read_exposure", "(", "haz_sitecol", ")", "# define .assets_by_site", "self", ".", "datastore", "[", "'poes/grp-00'", "]", "=", "fix_ones", "(", "readinput", ".", "pmap", ")", "self", ".", "datastore", "[", "'sitecol'", "]", "=", "self", ".", "sitecol", "self", ".", "datastore", "[", "'assetcol'", "]", "=", "self", ".", "assetcol", "self", ".", "datastore", "[", "'csm_info'", "]", "=", "fake", "=", "source", ".", "CompositionInfo", ".", "fake", "(", ")", "self", ".", "rlzs_assoc", "=", "fake", ".", "get_rlzs_assoc", "(", ")", "elif", "oq", ".", "hazard_calculation_id", ":", "parent", "=", "util", ".", "read", "(", "oq", ".", "hazard_calculation_id", ")", "self", ".", "check_precalc", "(", "parent", "[", "'oqparam'", "]", ".", "calculation_mode", ")", "self", ".", "datastore", ".", "parent", "=", "parent", "# copy missing parameters from the parent", "params", "=", "{", "name", ":", "value", "for", "name", ",", "value", "in", "vars", "(", "parent", "[", "'oqparam'", "]", ")", ".", "items", "(", ")", "if", "name", "not", "in", "vars", "(", "self", ".", "oqparam", ")", "}", "self", ".", "save_params", "(", "*", "*", "params", ")", "self", ".", "read_inputs", "(", ")", "oqp", "=", "parent", "[", "'oqparam'", "]", "if", "oqp", ".", "investigation_time", "!=", "oq", ".", "investigation_time", ":", "raise", "ValueError", "(", "'The parent calculation was using investigation_time=%s'", "' != %s'", "%", "(", "oqp", ".", "investigation_time", ",", "oq", ".", "investigation_time", ")", ")", "if", "oqp", ".", "minimum_intensity", "!=", "oq", ".", "minimum_intensity", ":", "raise", "ValueError", "(", "'The parent calculation was using minimum_intensity=%s'", "' != %s'", "%", "(", "oqp", ".", "minimum_intensity", ",", "oq", ".", "minimum_intensity", ")", ")", "missing_imts", "=", "set", "(", "oq", ".", "risk_imtls", ")", "-", "set", "(", "oqp", ".", "imtls", ")", "if", "missing_imts", ":", "raise", "ValueError", "(", "'The parent calculation is missing the IMT(s) %s'", "%", "', '", ".", "join", "(", "missing_imts", ")", ")", "elif", "self", ".", "__class__", ".", "precalc", ":", "calc", "=", "calculators", "[", "self", ".", "__class__", ".", "precalc", "]", "(", "self", ".", "oqparam", ",", "self", ".", "datastore", ".", "calc_id", ")", "calc", ".", "run", "(", ")", "self", ".", "param", "=", "calc", ".", "param", "self", ".", "sitecol", "=", "calc", ".", "sitecol", "self", ".", "assetcol", "=", "calc", ".", "assetcol", "self", ".", "riskmodel", "=", "calc", ".", "riskmodel", "if", "hasattr", "(", "calc", ",", "'rlzs_assoc'", ")", ":", "self", ".", "rlzs_assoc", "=", "calc", ".", "rlzs_assoc", "else", ":", "# this happens for instance for a scenario_damage without", "# rupture, gmfs, multi_peril", "raise", "InvalidFile", "(", "'%(job_ini)s: missing gmfs_csv, multi_peril_csv'", "%", "oq", ".", "inputs", ")", "if", "hasattr", "(", "calc", ",", "'csm'", ")", ":", "# no scenario", "self", ".", "csm", "=", "calc", ".", "csm", "else", ":", "self", ".", "read_inputs", "(", ")", "if", "self", ".", "riskmodel", ":", "self", ".", "save_riskmodel", "(", ")" ]
Check if there is a previous calculation ID. If yes, read the inputs by retrieving the previous calculation; if not, read the inputs directly.
[ "Check", "if", "there", "is", "a", "previous", "calculation", "ID", ".", "If", "yes", "read", "the", "inputs", "by", "retrieving", "the", "previous", "calculation", ";", "if", "not", "read", "the", "inputs", "directly", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L422-L496
50
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.init
def init(self): """ To be overridden to initialize the datasets needed by the calculation """ oq = self.oqparam if not oq.risk_imtls: if self.datastore.parent: oq.risk_imtls = ( self.datastore.parent['oqparam'].risk_imtls) if 'precalc' in vars(self): self.rlzs_assoc = self.precalc.rlzs_assoc elif 'csm_info' in self.datastore: csm_info = self.datastore['csm_info'] if oq.hazard_calculation_id and 'gsim_logic_tree' in oq.inputs: # redefine the realizations by reading the weights from the # gsim_logic_tree_file that could be different from the parent csm_info.gsim_lt = logictree.GsimLogicTree( oq.inputs['gsim_logic_tree'], set(csm_info.trts)) self.rlzs_assoc = csm_info.get_rlzs_assoc() elif hasattr(self, 'csm'): self.check_floating_spinning() self.rlzs_assoc = self.csm.info.get_rlzs_assoc() else: # build a fake; used by risk-from-file calculators self.datastore['csm_info'] = fake = source.CompositionInfo.fake() self.rlzs_assoc = fake.get_rlzs_assoc()
python
def init(self): """ To be overridden to initialize the datasets needed by the calculation """ oq = self.oqparam if not oq.risk_imtls: if self.datastore.parent: oq.risk_imtls = ( self.datastore.parent['oqparam'].risk_imtls) if 'precalc' in vars(self): self.rlzs_assoc = self.precalc.rlzs_assoc elif 'csm_info' in self.datastore: csm_info = self.datastore['csm_info'] if oq.hazard_calculation_id and 'gsim_logic_tree' in oq.inputs: # redefine the realizations by reading the weights from the # gsim_logic_tree_file that could be different from the parent csm_info.gsim_lt = logictree.GsimLogicTree( oq.inputs['gsim_logic_tree'], set(csm_info.trts)) self.rlzs_assoc = csm_info.get_rlzs_assoc() elif hasattr(self, 'csm'): self.check_floating_spinning() self.rlzs_assoc = self.csm.info.get_rlzs_assoc() else: # build a fake; used by risk-from-file calculators self.datastore['csm_info'] = fake = source.CompositionInfo.fake() self.rlzs_assoc = fake.get_rlzs_assoc()
[ "def", "init", "(", "self", ")", ":", "oq", "=", "self", ".", "oqparam", "if", "not", "oq", ".", "risk_imtls", ":", "if", "self", ".", "datastore", ".", "parent", ":", "oq", ".", "risk_imtls", "=", "(", "self", ".", "datastore", ".", "parent", "[", "'oqparam'", "]", ".", "risk_imtls", ")", "if", "'precalc'", "in", "vars", "(", "self", ")", ":", "self", ".", "rlzs_assoc", "=", "self", ".", "precalc", ".", "rlzs_assoc", "elif", "'csm_info'", "in", "self", ".", "datastore", ":", "csm_info", "=", "self", ".", "datastore", "[", "'csm_info'", "]", "if", "oq", ".", "hazard_calculation_id", "and", "'gsim_logic_tree'", "in", "oq", ".", "inputs", ":", "# redefine the realizations by reading the weights from the", "# gsim_logic_tree_file that could be different from the parent", "csm_info", ".", "gsim_lt", "=", "logictree", ".", "GsimLogicTree", "(", "oq", ".", "inputs", "[", "'gsim_logic_tree'", "]", ",", "set", "(", "csm_info", ".", "trts", ")", ")", "self", ".", "rlzs_assoc", "=", "csm_info", ".", "get_rlzs_assoc", "(", ")", "elif", "hasattr", "(", "self", ",", "'csm'", ")", ":", "self", ".", "check_floating_spinning", "(", ")", "self", ".", "rlzs_assoc", "=", "self", ".", "csm", ".", "info", ".", "get_rlzs_assoc", "(", ")", "else", ":", "# build a fake; used by risk-from-file calculators", "self", ".", "datastore", "[", "'csm_info'", "]", "=", "fake", "=", "source", ".", "CompositionInfo", ".", "fake", "(", ")", "self", ".", "rlzs_assoc", "=", "fake", ".", "get_rlzs_assoc", "(", ")" ]
To be overridden to initialize the datasets needed by the calculation
[ "To", "be", "overridden", "to", "initialize", "the", "datasets", "needed", "by", "the", "calculation" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L498-L522
51
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.read_exposure
def read_exposure(self, haz_sitecol=None): # after load_risk_model """ Read the exposure, the riskmodel and update the attributes .sitecol, .assetcol """ with self.monitor('reading exposure', autoflush=True): self.sitecol, self.assetcol, discarded = ( readinput.get_sitecol_assetcol( self.oqparam, haz_sitecol, self.riskmodel.loss_types)) if len(discarded): self.datastore['discarded'] = discarded if hasattr(self, 'rup'): # this is normal for the case of scenario from rupture logging.info('%d assets were discarded because too far ' 'from the rupture; use `oq show discarded` ' 'to show them and `oq plot_assets` to plot ' 'them' % len(discarded)) elif not self.oqparam.discard_assets: # raise an error self.datastore['sitecol'] = self.sitecol self.datastore['assetcol'] = self.assetcol raise RuntimeError( '%d assets were discarded; use `oq show discarded` to' ' show them and `oq plot_assets` to plot them' % len(discarded)) # reduce the riskmodel to the relevant taxonomies taxonomies = set(taxo for taxo in self.assetcol.tagcol.taxonomy if taxo != '?') if len(self.riskmodel.taxonomies) > len(taxonomies): logging.info('Reducing risk model from %d to %d taxonomies', len(self.riskmodel.taxonomies), len(taxonomies)) self.riskmodel = self.riskmodel.reduce(taxonomies) return readinput.exposure
python
def read_exposure(self, haz_sitecol=None): # after load_risk_model """ Read the exposure, the riskmodel and update the attributes .sitecol, .assetcol """ with self.monitor('reading exposure', autoflush=True): self.sitecol, self.assetcol, discarded = ( readinput.get_sitecol_assetcol( self.oqparam, haz_sitecol, self.riskmodel.loss_types)) if len(discarded): self.datastore['discarded'] = discarded if hasattr(self, 'rup'): # this is normal for the case of scenario from rupture logging.info('%d assets were discarded because too far ' 'from the rupture; use `oq show discarded` ' 'to show them and `oq plot_assets` to plot ' 'them' % len(discarded)) elif not self.oqparam.discard_assets: # raise an error self.datastore['sitecol'] = self.sitecol self.datastore['assetcol'] = self.assetcol raise RuntimeError( '%d assets were discarded; use `oq show discarded` to' ' show them and `oq plot_assets` to plot them' % len(discarded)) # reduce the riskmodel to the relevant taxonomies taxonomies = set(taxo for taxo in self.assetcol.tagcol.taxonomy if taxo != '?') if len(self.riskmodel.taxonomies) > len(taxonomies): logging.info('Reducing risk model from %d to %d taxonomies', len(self.riskmodel.taxonomies), len(taxonomies)) self.riskmodel = self.riskmodel.reduce(taxonomies) return readinput.exposure
[ "def", "read_exposure", "(", "self", ",", "haz_sitecol", "=", "None", ")", ":", "# after load_risk_model", "with", "self", ".", "monitor", "(", "'reading exposure'", ",", "autoflush", "=", "True", ")", ":", "self", ".", "sitecol", ",", "self", ".", "assetcol", ",", "discarded", "=", "(", "readinput", ".", "get_sitecol_assetcol", "(", "self", ".", "oqparam", ",", "haz_sitecol", ",", "self", ".", "riskmodel", ".", "loss_types", ")", ")", "if", "len", "(", "discarded", ")", ":", "self", ".", "datastore", "[", "'discarded'", "]", "=", "discarded", "if", "hasattr", "(", "self", ",", "'rup'", ")", ":", "# this is normal for the case of scenario from rupture", "logging", ".", "info", "(", "'%d assets were discarded because too far '", "'from the rupture; use `oq show discarded` '", "'to show them and `oq plot_assets` to plot '", "'them'", "%", "len", "(", "discarded", ")", ")", "elif", "not", "self", ".", "oqparam", ".", "discard_assets", ":", "# raise an error", "self", ".", "datastore", "[", "'sitecol'", "]", "=", "self", ".", "sitecol", "self", ".", "datastore", "[", "'assetcol'", "]", "=", "self", ".", "assetcol", "raise", "RuntimeError", "(", "'%d assets were discarded; use `oq show discarded` to'", "' show them and `oq plot_assets` to plot them'", "%", "len", "(", "discarded", ")", ")", "# reduce the riskmodel to the relevant taxonomies", "taxonomies", "=", "set", "(", "taxo", "for", "taxo", "in", "self", ".", "assetcol", ".", "tagcol", ".", "taxonomy", "if", "taxo", "!=", "'?'", ")", "if", "len", "(", "self", ".", "riskmodel", ".", "taxonomies", ")", ">", "len", "(", "taxonomies", ")", ":", "logging", ".", "info", "(", "'Reducing risk model from %d to %d taxonomies'", ",", "len", "(", "self", ".", "riskmodel", ".", "taxonomies", ")", ",", "len", "(", "taxonomies", ")", ")", "self", ".", "riskmodel", "=", "self", ".", "riskmodel", ".", "reduce", "(", "taxonomies", ")", "return", "readinput", ".", "exposure" ]
Read the exposure, the riskmodel and update the attributes .sitecol, .assetcol
[ "Read", "the", "exposure", "the", "riskmodel", "and", "update", "the", "attributes", ".", "sitecol", ".", "assetcol" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L534-L566
52
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.save_riskmodel
def save_riskmodel(self): """ Save the risk models in the datastore """ self.datastore['risk_model'] = rm = self.riskmodel self.datastore['taxonomy_mapping'] = self.riskmodel.tmap attrs = self.datastore.getitem('risk_model').attrs attrs['min_iml'] = hdf5.array_of_vstr(sorted(rm.min_iml.items())) self.datastore.set_nbytes('risk_model')
python
def save_riskmodel(self): """ Save the risk models in the datastore """ self.datastore['risk_model'] = rm = self.riskmodel self.datastore['taxonomy_mapping'] = self.riskmodel.tmap attrs = self.datastore.getitem('risk_model').attrs attrs['min_iml'] = hdf5.array_of_vstr(sorted(rm.min_iml.items())) self.datastore.set_nbytes('risk_model')
[ "def", "save_riskmodel", "(", "self", ")", ":", "self", ".", "datastore", "[", "'risk_model'", "]", "=", "rm", "=", "self", ".", "riskmodel", "self", ".", "datastore", "[", "'taxonomy_mapping'", "]", "=", "self", ".", "riskmodel", ".", "tmap", "attrs", "=", "self", ".", "datastore", ".", "getitem", "(", "'risk_model'", ")", ".", "attrs", "attrs", "[", "'min_iml'", "]", "=", "hdf5", ".", "array_of_vstr", "(", "sorted", "(", "rm", ".", "min_iml", ".", "items", "(", ")", ")", ")", "self", ".", "datastore", ".", "set_nbytes", "(", "'risk_model'", ")" ]
Save the risk models in the datastore
[ "Save", "the", "risk", "models", "in", "the", "datastore" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L588-L596
53
gem/oq-engine
openquake/calculators/base.py
HazardCalculator.store_rlz_info
def store_rlz_info(self, eff_ruptures=None): """ Save info about the composite source model inside the csm_info dataset """ if hasattr(self, 'csm'): # no scenario self.csm.info.update_eff_ruptures(eff_ruptures) self.rlzs_assoc = self.csm.info.get_rlzs_assoc( self.oqparam.sm_lt_path) if not self.rlzs_assoc: raise RuntimeError('Empty logic tree: too much filtering?') self.datastore['csm_info'] = self.csm.info R = len(self.rlzs_assoc.realizations) logging.info('There are %d realization(s)', R) if self.oqparam.imtls: self.datastore['weights'] = arr = build_weights( self.rlzs_assoc.realizations, self.oqparam.imt_dt()) self.datastore.set_attrs('weights', nbytes=arr.nbytes) if hasattr(self, 'hdf5cache'): # no scenario with hdf5.File(self.hdf5cache, 'r+') as cache: cache['weights'] = arr if 'event_based' in self.oqparam.calculation_mode and R >= TWO16: # rlzi is 16 bit integer in the GMFs, so there is hard limit or R raise ValueError( 'The logic tree has %d realizations, the maximum ' 'is %d' % (R, TWO16)) elif R > 10000: logging.warning( 'The logic tree has %d realizations(!), please consider ' 'sampling it', R) self.datastore.flush()
python
def store_rlz_info(self, eff_ruptures=None): """ Save info about the composite source model inside the csm_info dataset """ if hasattr(self, 'csm'): # no scenario self.csm.info.update_eff_ruptures(eff_ruptures) self.rlzs_assoc = self.csm.info.get_rlzs_assoc( self.oqparam.sm_lt_path) if not self.rlzs_assoc: raise RuntimeError('Empty logic tree: too much filtering?') self.datastore['csm_info'] = self.csm.info R = len(self.rlzs_assoc.realizations) logging.info('There are %d realization(s)', R) if self.oqparam.imtls: self.datastore['weights'] = arr = build_weights( self.rlzs_assoc.realizations, self.oqparam.imt_dt()) self.datastore.set_attrs('weights', nbytes=arr.nbytes) if hasattr(self, 'hdf5cache'): # no scenario with hdf5.File(self.hdf5cache, 'r+') as cache: cache['weights'] = arr if 'event_based' in self.oqparam.calculation_mode and R >= TWO16: # rlzi is 16 bit integer in the GMFs, so there is hard limit or R raise ValueError( 'The logic tree has %d realizations, the maximum ' 'is %d' % (R, TWO16)) elif R > 10000: logging.warning( 'The logic tree has %d realizations(!), please consider ' 'sampling it', R) self.datastore.flush()
[ "def", "store_rlz_info", "(", "self", ",", "eff_ruptures", "=", "None", ")", ":", "if", "hasattr", "(", "self", ",", "'csm'", ")", ":", "# no scenario", "self", ".", "csm", ".", "info", ".", "update_eff_ruptures", "(", "eff_ruptures", ")", "self", ".", "rlzs_assoc", "=", "self", ".", "csm", ".", "info", ".", "get_rlzs_assoc", "(", "self", ".", "oqparam", ".", "sm_lt_path", ")", "if", "not", "self", ".", "rlzs_assoc", ":", "raise", "RuntimeError", "(", "'Empty logic tree: too much filtering?'", ")", "self", ".", "datastore", "[", "'csm_info'", "]", "=", "self", ".", "csm", ".", "info", "R", "=", "len", "(", "self", ".", "rlzs_assoc", ".", "realizations", ")", "logging", ".", "info", "(", "'There are %d realization(s)'", ",", "R", ")", "if", "self", ".", "oqparam", ".", "imtls", ":", "self", ".", "datastore", "[", "'weights'", "]", "=", "arr", "=", "build_weights", "(", "self", ".", "rlzs_assoc", ".", "realizations", ",", "self", ".", "oqparam", ".", "imt_dt", "(", ")", ")", "self", ".", "datastore", ".", "set_attrs", "(", "'weights'", ",", "nbytes", "=", "arr", ".", "nbytes", ")", "if", "hasattr", "(", "self", ",", "'hdf5cache'", ")", ":", "# no scenario", "with", "hdf5", ".", "File", "(", "self", ".", "hdf5cache", ",", "'r+'", ")", "as", "cache", ":", "cache", "[", "'weights'", "]", "=", "arr", "if", "'event_based'", "in", "self", ".", "oqparam", ".", "calculation_mode", "and", "R", ">=", "TWO16", ":", "# rlzi is 16 bit integer in the GMFs, so there is hard limit or R", "raise", "ValueError", "(", "'The logic tree has %d realizations, the maximum '", "'is %d'", "%", "(", "R", ",", "TWO16", ")", ")", "elif", "R", ">", "10000", ":", "logging", ".", "warning", "(", "'The logic tree has %d realizations(!), please consider '", "'sampling it'", ",", "R", ")", "self", ".", "datastore", ".", "flush", "(", ")" ]
Save info about the composite source model inside the csm_info dataset
[ "Save", "info", "about", "the", "composite", "source", "model", "inside", "the", "csm_info", "dataset" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L701-L730
54
gem/oq-engine
openquake/calculators/base.py
RiskCalculator.read_shakemap
def read_shakemap(self, haz_sitecol, assetcol): """ Enabled only if there is a shakemap_id parameter in the job.ini. Download, unzip, parse USGS shakemap files and build a corresponding set of GMFs which are then filtered with the hazard site collection and stored in the datastore. """ oq = self.oqparam E = oq.number_of_ground_motion_fields oq.risk_imtls = oq.imtls or self.datastore.parent['oqparam'].imtls extra = self.riskmodel.get_extra_imts(oq.risk_imtls) if extra: logging.warning('There are risk functions for not available IMTs ' 'which will be ignored: %s' % extra) logging.info('Getting/reducing shakemap') with self.monitor('getting/reducing shakemap'): smap = oq.shakemap_id if oq.shakemap_id else numpy.load( oq.inputs['shakemap']) sitecol, shakemap, discarded = get_sitecol_shakemap( smap, oq.imtls, haz_sitecol, oq.asset_hazard_distance['default'], oq.discard_assets) if len(discarded): self.datastore['discarded'] = discarded assetcol = assetcol.reduce_also(sitecol) logging.info('Building GMFs') with self.monitor('building/saving GMFs'): imts, gmfs = to_gmfs( shakemap, oq.spatial_correlation, oq.cross_correlation, oq.site_effects, oq.truncation_level, E, oq.random_seed, oq.imtls) save_gmf_data(self.datastore, sitecol, gmfs, imts) return sitecol, assetcol
python
def read_shakemap(self, haz_sitecol, assetcol): """ Enabled only if there is a shakemap_id parameter in the job.ini. Download, unzip, parse USGS shakemap files and build a corresponding set of GMFs which are then filtered with the hazard site collection and stored in the datastore. """ oq = self.oqparam E = oq.number_of_ground_motion_fields oq.risk_imtls = oq.imtls or self.datastore.parent['oqparam'].imtls extra = self.riskmodel.get_extra_imts(oq.risk_imtls) if extra: logging.warning('There are risk functions for not available IMTs ' 'which will be ignored: %s' % extra) logging.info('Getting/reducing shakemap') with self.monitor('getting/reducing shakemap'): smap = oq.shakemap_id if oq.shakemap_id else numpy.load( oq.inputs['shakemap']) sitecol, shakemap, discarded = get_sitecol_shakemap( smap, oq.imtls, haz_sitecol, oq.asset_hazard_distance['default'], oq.discard_assets) if len(discarded): self.datastore['discarded'] = discarded assetcol = assetcol.reduce_also(sitecol) logging.info('Building GMFs') with self.monitor('building/saving GMFs'): imts, gmfs = to_gmfs( shakemap, oq.spatial_correlation, oq.cross_correlation, oq.site_effects, oq.truncation_level, E, oq.random_seed, oq.imtls) save_gmf_data(self.datastore, sitecol, gmfs, imts) return sitecol, assetcol
[ "def", "read_shakemap", "(", "self", ",", "haz_sitecol", ",", "assetcol", ")", ":", "oq", "=", "self", ".", "oqparam", "E", "=", "oq", ".", "number_of_ground_motion_fields", "oq", ".", "risk_imtls", "=", "oq", ".", "imtls", "or", "self", ".", "datastore", ".", "parent", "[", "'oqparam'", "]", ".", "imtls", "extra", "=", "self", ".", "riskmodel", ".", "get_extra_imts", "(", "oq", ".", "risk_imtls", ")", "if", "extra", ":", "logging", ".", "warning", "(", "'There are risk functions for not available IMTs '", "'which will be ignored: %s'", "%", "extra", ")", "logging", ".", "info", "(", "'Getting/reducing shakemap'", ")", "with", "self", ".", "monitor", "(", "'getting/reducing shakemap'", ")", ":", "smap", "=", "oq", ".", "shakemap_id", "if", "oq", ".", "shakemap_id", "else", "numpy", ".", "load", "(", "oq", ".", "inputs", "[", "'shakemap'", "]", ")", "sitecol", ",", "shakemap", ",", "discarded", "=", "get_sitecol_shakemap", "(", "smap", ",", "oq", ".", "imtls", ",", "haz_sitecol", ",", "oq", ".", "asset_hazard_distance", "[", "'default'", "]", ",", "oq", ".", "discard_assets", ")", "if", "len", "(", "discarded", ")", ":", "self", ".", "datastore", "[", "'discarded'", "]", "=", "discarded", "assetcol", "=", "assetcol", ".", "reduce_also", "(", "sitecol", ")", "logging", ".", "info", "(", "'Building GMFs'", ")", "with", "self", ".", "monitor", "(", "'building/saving GMFs'", ")", ":", "imts", ",", "gmfs", "=", "to_gmfs", "(", "shakemap", ",", "oq", ".", "spatial_correlation", ",", "oq", ".", "cross_correlation", ",", "oq", ".", "site_effects", ",", "oq", ".", "truncation_level", ",", "E", ",", "oq", ".", "random_seed", ",", "oq", ".", "imtls", ")", "save_gmf_data", "(", "self", ".", "datastore", ",", "sitecol", ",", "gmfs", ",", "imts", ")", "return", "sitecol", ",", "assetcol" ]
Enabled only if there is a shakemap_id parameter in the job.ini. Download, unzip, parse USGS shakemap files and build a corresponding set of GMFs which are then filtered with the hazard site collection and stored in the datastore.
[ "Enabled", "only", "if", "there", "is", "a", "shakemap_id", "parameter", "in", "the", "job", ".", "ini", ".", "Download", "unzip", "parse", "USGS", "shakemap", "files", "and", "build", "a", "corresponding", "set", "of", "GMFs", "which", "are", "then", "filtered", "with", "the", "hazard", "site", "collection", "and", "stored", "in", "the", "datastore", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/base.py#L766-L800
55
gem/oq-engine
openquake/baselib/zeromq.py
bind
def bind(end_point, socket_type): """ Bind to a zmq URL; raise a proper error if the URL is invalid; return a zmq socket. """ sock = context.socket(socket_type) try: sock.bind(end_point) except zmq.error.ZMQError as exc: sock.close() raise exc.__class__('%s: %s' % (exc, end_point)) return sock
python
def bind(end_point, socket_type): """ Bind to a zmq URL; raise a proper error if the URL is invalid; return a zmq socket. """ sock = context.socket(socket_type) try: sock.bind(end_point) except zmq.error.ZMQError as exc: sock.close() raise exc.__class__('%s: %s' % (exc, end_point)) return sock
[ "def", "bind", "(", "end_point", ",", "socket_type", ")", ":", "sock", "=", "context", ".", "socket", "(", "socket_type", ")", "try", ":", "sock", ".", "bind", "(", "end_point", ")", "except", "zmq", ".", "error", ".", "ZMQError", "as", "exc", ":", "sock", ".", "close", "(", ")", "raise", "exc", ".", "__class__", "(", "'%s: %s'", "%", "(", "exc", ",", "end_point", ")", ")", "return", "sock" ]
Bind to a zmq URL; raise a proper error if the URL is invalid; return a zmq socket.
[ "Bind", "to", "a", "zmq", "URL", ";", "raise", "a", "proper", "error", "if", "the", "URL", "is", "invalid", ";", "return", "a", "zmq", "socket", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/zeromq.py#L30-L41
56
gem/oq-engine
openquake/baselib/zeromq.py
Socket.send
def send(self, obj): """ Send an object to the remote server; block and return the reply if the socket type is REQ. :param obj: the Python object to send """ self.zsocket.send_pyobj(obj) self.num_sent += 1 if self.socket_type == zmq.REQ: return self.zsocket.recv_pyobj()
python
def send(self, obj): """ Send an object to the remote server; block and return the reply if the socket type is REQ. :param obj: the Python object to send """ self.zsocket.send_pyobj(obj) self.num_sent += 1 if self.socket_type == zmq.REQ: return self.zsocket.recv_pyobj()
[ "def", "send", "(", "self", ",", "obj", ")", ":", "self", ".", "zsocket", ".", "send_pyobj", "(", "obj", ")", "self", ".", "num_sent", "+=", "1", "if", "self", ".", "socket_type", "==", "zmq", ".", "REQ", ":", "return", "self", ".", "zsocket", ".", "recv_pyobj", "(", ")" ]
Send an object to the remote server; block and return the reply if the socket type is REQ. :param obj: the Python object to send
[ "Send", "an", "object", "to", "the", "remote", "server", ";", "block", "and", "return", "the", "reply", "if", "the", "socket", "type", "is", "REQ", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/zeromq.py#L139-L150
57
gem/oq-engine
openquake/hazardlib/geo/utils.py
angular_distance
def angular_distance(km, lat, lat2=None): """ Return the angular distance of two points at the given latitude. >>> '%.3f' % angular_distance(100, lat=40) '1.174' >>> '%.3f' % angular_distance(100, lat=80) '5.179' """ if lat2 is not None: # use the largest latitude to compute the angular distance lat = max(abs(lat), abs(lat2)) return km * KM_TO_DEGREES / math.cos(lat * DEGREES_TO_RAD)
python
def angular_distance(km, lat, lat2=None): """ Return the angular distance of two points at the given latitude. >>> '%.3f' % angular_distance(100, lat=40) '1.174' >>> '%.3f' % angular_distance(100, lat=80) '5.179' """ if lat2 is not None: # use the largest latitude to compute the angular distance lat = max(abs(lat), abs(lat2)) return km * KM_TO_DEGREES / math.cos(lat * DEGREES_TO_RAD)
[ "def", "angular_distance", "(", "km", ",", "lat", ",", "lat2", "=", "None", ")", ":", "if", "lat2", "is", "not", "None", ":", "# use the largest latitude to compute the angular distance", "lat", "=", "max", "(", "abs", "(", "lat", ")", ",", "abs", "(", "lat2", ")", ")", "return", "km", "*", "KM_TO_DEGREES", "/", "math", ".", "cos", "(", "lat", "*", "DEGREES_TO_RAD", ")" ]
Return the angular distance of two points at the given latitude. >>> '%.3f' % angular_distance(100, lat=40) '1.174' >>> '%.3f' % angular_distance(100, lat=80) '5.179'
[ "Return", "the", "angular", "distance", "of", "two", "points", "at", "the", "given", "latitude", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L45-L57
58
gem/oq-engine
openquake/hazardlib/geo/utils.py
assoc
def assoc(objects, sitecol, assoc_dist, mode, asset_refs=()): """ Associate geographic objects to a site collection. :param objects: something with .lons, .lats or ['lon'] ['lat'], or a list of lists of objects with a .location attribute (i.e. assets_by_site) :param assoc_dist: the maximum distance for association :param mode: if 'strict' fail if at least one site is not associated if 'error' fail if all sites are not associated :returns: (filtered site collection, filtered objects) """ if isinstance(objects, numpy.ndarray) or hasattr(objects, 'lons'): # objects is a geo array with lon, lat fields or a mesh-like instance return _GeographicObjects(objects).assoc(sitecol, assoc_dist, mode) else: # objects is the list assets_by_site return _GeographicObjects(sitecol).assoc2( objects, assoc_dist, mode, asset_refs)
python
def assoc(objects, sitecol, assoc_dist, mode, asset_refs=()): """ Associate geographic objects to a site collection. :param objects: something with .lons, .lats or ['lon'] ['lat'], or a list of lists of objects with a .location attribute (i.e. assets_by_site) :param assoc_dist: the maximum distance for association :param mode: if 'strict' fail if at least one site is not associated if 'error' fail if all sites are not associated :returns: (filtered site collection, filtered objects) """ if isinstance(objects, numpy.ndarray) or hasattr(objects, 'lons'): # objects is a geo array with lon, lat fields or a mesh-like instance return _GeographicObjects(objects).assoc(sitecol, assoc_dist, mode) else: # objects is the list assets_by_site return _GeographicObjects(sitecol).assoc2( objects, assoc_dist, mode, asset_refs)
[ "def", "assoc", "(", "objects", ",", "sitecol", ",", "assoc_dist", ",", "mode", ",", "asset_refs", "=", "(", ")", ")", ":", "if", "isinstance", "(", "objects", ",", "numpy", ".", "ndarray", ")", "or", "hasattr", "(", "objects", ",", "'lons'", ")", ":", "# objects is a geo array with lon, lat fields or a mesh-like instance", "return", "_GeographicObjects", "(", "objects", ")", ".", "assoc", "(", "sitecol", ",", "assoc_dist", ",", "mode", ")", "else", ":", "# objects is the list assets_by_site", "return", "_GeographicObjects", "(", "sitecol", ")", ".", "assoc2", "(", "objects", ",", "assoc_dist", ",", "mode", ",", "asset_refs", ")" ]
Associate geographic objects to a site collection. :param objects: something with .lons, .lats or ['lon'] ['lat'], or a list of lists of objects with a .location attribute (i.e. assets_by_site) :param assoc_dist: the maximum distance for association :param mode: if 'strict' fail if at least one site is not associated if 'error' fail if all sites are not associated :returns: (filtered site collection, filtered objects)
[ "Associate", "geographic", "objects", "to", "a", "site", "collection", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L177-L196
59
gem/oq-engine
openquake/hazardlib/geo/utils.py
line_intersects_itself
def line_intersects_itself(lons, lats, closed_shape=False): """ Return ``True`` if line of points intersects itself. Line with the last point repeating the first one considered intersecting itself. The line is defined by lists (or numpy arrays) of points' longitudes and latitudes (depth is not taken into account). :param closed_shape: If ``True`` the line will be checked twice: first time with its original shape and second time with the points sequence being shifted by one point (the last point becomes first, the first turns second and so on). This is useful for checking that the sequence of points defines a valid :class:`~openquake.hazardlib.geo.polygon.Polygon`. """ assert len(lons) == len(lats) if len(lons) <= 3: # line can not intersect itself unless there are # at least four points return False west, east, north, south = get_spherical_bounding_box(lons, lats) proj = OrthographicProjection(west, east, north, south) xx, yy = proj(lons, lats) if not shapely.geometry.LineString(list(zip(xx, yy))).is_simple: return True if closed_shape: xx, yy = proj(numpy.roll(lons, 1), numpy.roll(lats, 1)) if not shapely.geometry.LineString(list(zip(xx, yy))).is_simple: return True return False
python
def line_intersects_itself(lons, lats, closed_shape=False): """ Return ``True`` if line of points intersects itself. Line with the last point repeating the first one considered intersecting itself. The line is defined by lists (or numpy arrays) of points' longitudes and latitudes (depth is not taken into account). :param closed_shape: If ``True`` the line will be checked twice: first time with its original shape and second time with the points sequence being shifted by one point (the last point becomes first, the first turns second and so on). This is useful for checking that the sequence of points defines a valid :class:`~openquake.hazardlib.geo.polygon.Polygon`. """ assert len(lons) == len(lats) if len(lons) <= 3: # line can not intersect itself unless there are # at least four points return False west, east, north, south = get_spherical_bounding_box(lons, lats) proj = OrthographicProjection(west, east, north, south) xx, yy = proj(lons, lats) if not shapely.geometry.LineString(list(zip(xx, yy))).is_simple: return True if closed_shape: xx, yy = proj(numpy.roll(lons, 1), numpy.roll(lats, 1)) if not shapely.geometry.LineString(list(zip(xx, yy))).is_simple: return True return False
[ "def", "line_intersects_itself", "(", "lons", ",", "lats", ",", "closed_shape", "=", "False", ")", ":", "assert", "len", "(", "lons", ")", "==", "len", "(", "lats", ")", "if", "len", "(", "lons", ")", "<=", "3", ":", "# line can not intersect itself unless there are", "# at least four points", "return", "False", "west", ",", "east", ",", "north", ",", "south", "=", "get_spherical_bounding_box", "(", "lons", ",", "lats", ")", "proj", "=", "OrthographicProjection", "(", "west", ",", "east", ",", "north", ",", "south", ")", "xx", ",", "yy", "=", "proj", "(", "lons", ",", "lats", ")", "if", "not", "shapely", ".", "geometry", ".", "LineString", "(", "list", "(", "zip", "(", "xx", ",", "yy", ")", ")", ")", ".", "is_simple", ":", "return", "True", "if", "closed_shape", ":", "xx", ",", "yy", "=", "proj", "(", "numpy", ".", "roll", "(", "lons", ",", "1", ")", ",", "numpy", ".", "roll", "(", "lats", ",", "1", ")", ")", "if", "not", "shapely", ".", "geometry", ".", "LineString", "(", "list", "(", "zip", "(", "xx", ",", "yy", ")", ")", ")", ".", "is_simple", ":", "return", "True", "return", "False" ]
Return ``True`` if line of points intersects itself. Line with the last point repeating the first one considered intersecting itself. The line is defined by lists (or numpy arrays) of points' longitudes and latitudes (depth is not taken into account). :param closed_shape: If ``True`` the line will be checked twice: first time with its original shape and second time with the points sequence being shifted by one point (the last point becomes first, the first turns second and so on). This is useful for checking that the sequence of points defines a valid :class:`~openquake.hazardlib.geo.polygon.Polygon`.
[ "Return", "True", "if", "line", "of", "points", "intersects", "itself", ".", "Line", "with", "the", "last", "point", "repeating", "the", "first", "one", "considered", "intersecting", "itself", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L214-L250
60
gem/oq-engine
openquake/hazardlib/geo/utils.py
get_bounding_box
def get_bounding_box(obj, maxdist): """ Return the dilated bounding box of a geometric object. :param obj: an object with method .get_bounding_box, or with an attribute .polygon or a list of locations :param maxdist: maximum distance in km """ if hasattr(obj, 'get_bounding_box'): return obj.get_bounding_box(maxdist) elif hasattr(obj, 'polygon'): bbox = obj.polygon.get_bbox() else: if isinstance(obj, list): # a list of locations lons = numpy.array([loc.longitude for loc in obj]) lats = numpy.array([loc.latitude for loc in obj]) else: # assume an array with fields lon, lat lons, lats = obj['lon'], obj['lat'] min_lon, max_lon = lons.min(), lons.max() if cross_idl(min_lon, max_lon): lons %= 360 bbox = lons.min(), lats.min(), lons.max(), lats.max() a1 = min(maxdist * KM_TO_DEGREES, 90) a2 = min(angular_distance(maxdist, bbox[1], bbox[3]), 180) return bbox[0] - a2, bbox[1] - a1, bbox[2] + a2, bbox[3] + a1
python
def get_bounding_box(obj, maxdist): """ Return the dilated bounding box of a geometric object. :param obj: an object with method .get_bounding_box, or with an attribute .polygon or a list of locations :param maxdist: maximum distance in km """ if hasattr(obj, 'get_bounding_box'): return obj.get_bounding_box(maxdist) elif hasattr(obj, 'polygon'): bbox = obj.polygon.get_bbox() else: if isinstance(obj, list): # a list of locations lons = numpy.array([loc.longitude for loc in obj]) lats = numpy.array([loc.latitude for loc in obj]) else: # assume an array with fields lon, lat lons, lats = obj['lon'], obj['lat'] min_lon, max_lon = lons.min(), lons.max() if cross_idl(min_lon, max_lon): lons %= 360 bbox = lons.min(), lats.min(), lons.max(), lats.max() a1 = min(maxdist * KM_TO_DEGREES, 90) a2 = min(angular_distance(maxdist, bbox[1], bbox[3]), 180) return bbox[0] - a2, bbox[1] - a1, bbox[2] + a2, bbox[3] + a1
[ "def", "get_bounding_box", "(", "obj", ",", "maxdist", ")", ":", "if", "hasattr", "(", "obj", ",", "'get_bounding_box'", ")", ":", "return", "obj", ".", "get_bounding_box", "(", "maxdist", ")", "elif", "hasattr", "(", "obj", ",", "'polygon'", ")", ":", "bbox", "=", "obj", ".", "polygon", ".", "get_bbox", "(", ")", "else", ":", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "# a list of locations", "lons", "=", "numpy", ".", "array", "(", "[", "loc", ".", "longitude", "for", "loc", "in", "obj", "]", ")", "lats", "=", "numpy", ".", "array", "(", "[", "loc", ".", "latitude", "for", "loc", "in", "obj", "]", ")", "else", ":", "# assume an array with fields lon, lat", "lons", ",", "lats", "=", "obj", "[", "'lon'", "]", ",", "obj", "[", "'lat'", "]", "min_lon", ",", "max_lon", "=", "lons", ".", "min", "(", ")", ",", "lons", ".", "max", "(", ")", "if", "cross_idl", "(", "min_lon", ",", "max_lon", ")", ":", "lons", "%=", "360", "bbox", "=", "lons", ".", "min", "(", ")", ",", "lats", ".", "min", "(", ")", ",", "lons", ".", "max", "(", ")", ",", "lats", ".", "max", "(", ")", "a1", "=", "min", "(", "maxdist", "*", "KM_TO_DEGREES", ",", "90", ")", "a2", "=", "min", "(", "angular_distance", "(", "maxdist", ",", "bbox", "[", "1", "]", ",", "bbox", "[", "3", "]", ")", ",", "180", ")", "return", "bbox", "[", "0", "]", "-", "a2", ",", "bbox", "[", "1", "]", "-", "a1", ",", "bbox", "[", "2", "]", "+", "a2", ",", "bbox", "[", "3", "]", "+", "a1" ]
Return the dilated bounding box of a geometric object. :param obj: an object with method .get_bounding_box, or with an attribute .polygon or a list of locations :param maxdist: maximum distance in km
[ "Return", "the", "dilated", "bounding", "box", "of", "a", "geometric", "object", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L267-L292
61
gem/oq-engine
openquake/hazardlib/geo/utils.py
get_spherical_bounding_box
def get_spherical_bounding_box(lons, lats): """ Given a collection of points find and return the bounding box, as a pair of longitudes and a pair of latitudes. Parameters define longitudes and latitudes of a point collection respectively in a form of lists or numpy arrays. :return: A tuple of four items. These items represent western, eastern, northern and southern borders of the bounding box respectively. Values are floats in decimal degrees. :raises ValueError: If points collection has the longitudinal extent of more than 180 degrees (it is impossible to define a single hemisphere bound to poles that would contain the whole collection). """ north, south = numpy.max(lats), numpy.min(lats) west, east = numpy.min(lons), numpy.max(lons) assert (-180 <= west <= 180) and (-180 <= east <= 180), (west, east) if get_longitudinal_extent(west, east) < 0: # points are lying on both sides of the international date line # (meridian 180). the actual west longitude is the lowest positive # longitude and east one is the highest negative. if hasattr(lons, 'flatten'): # fixes test_surface_crossing_international_date_line lons = lons.flatten() west = min(lon for lon in lons if lon > 0) east = max(lon for lon in lons if lon < 0) if not all((get_longitudinal_extent(west, lon) >= 0 and get_longitudinal_extent(lon, east) >= 0) for lon in lons): raise ValueError('points collection has longitudinal extent ' 'wider than 180 deg') return SphericalBB(west, east, north, south)
python
def get_spherical_bounding_box(lons, lats): """ Given a collection of points find and return the bounding box, as a pair of longitudes and a pair of latitudes. Parameters define longitudes and latitudes of a point collection respectively in a form of lists or numpy arrays. :return: A tuple of four items. These items represent western, eastern, northern and southern borders of the bounding box respectively. Values are floats in decimal degrees. :raises ValueError: If points collection has the longitudinal extent of more than 180 degrees (it is impossible to define a single hemisphere bound to poles that would contain the whole collection). """ north, south = numpy.max(lats), numpy.min(lats) west, east = numpy.min(lons), numpy.max(lons) assert (-180 <= west <= 180) and (-180 <= east <= 180), (west, east) if get_longitudinal_extent(west, east) < 0: # points are lying on both sides of the international date line # (meridian 180). the actual west longitude is the lowest positive # longitude and east one is the highest negative. if hasattr(lons, 'flatten'): # fixes test_surface_crossing_international_date_line lons = lons.flatten() west = min(lon for lon in lons if lon > 0) east = max(lon for lon in lons if lon < 0) if not all((get_longitudinal_extent(west, lon) >= 0 and get_longitudinal_extent(lon, east) >= 0) for lon in lons): raise ValueError('points collection has longitudinal extent ' 'wider than 180 deg') return SphericalBB(west, east, north, south)
[ "def", "get_spherical_bounding_box", "(", "lons", ",", "lats", ")", ":", "north", ",", "south", "=", "numpy", ".", "max", "(", "lats", ")", ",", "numpy", ".", "min", "(", "lats", ")", "west", ",", "east", "=", "numpy", ".", "min", "(", "lons", ")", ",", "numpy", ".", "max", "(", "lons", ")", "assert", "(", "-", "180", "<=", "west", "<=", "180", ")", "and", "(", "-", "180", "<=", "east", "<=", "180", ")", ",", "(", "west", ",", "east", ")", "if", "get_longitudinal_extent", "(", "west", ",", "east", ")", "<", "0", ":", "# points are lying on both sides of the international date line", "# (meridian 180). the actual west longitude is the lowest positive", "# longitude and east one is the highest negative.", "if", "hasattr", "(", "lons", ",", "'flatten'", ")", ":", "# fixes test_surface_crossing_international_date_line", "lons", "=", "lons", ".", "flatten", "(", ")", "west", "=", "min", "(", "lon", "for", "lon", "in", "lons", "if", "lon", ">", "0", ")", "east", "=", "max", "(", "lon", "for", "lon", "in", "lons", "if", "lon", "<", "0", ")", "if", "not", "all", "(", "(", "get_longitudinal_extent", "(", "west", ",", "lon", ")", ">=", "0", "and", "get_longitudinal_extent", "(", "lon", ",", "east", ")", ">=", "0", ")", "for", "lon", "in", "lons", ")", ":", "raise", "ValueError", "(", "'points collection has longitudinal extent '", "'wider than 180 deg'", ")", "return", "SphericalBB", "(", "west", ",", "east", ",", "north", ",", "south", ")" ]
Given a collection of points find and return the bounding box, as a pair of longitudes and a pair of latitudes. Parameters define longitudes and latitudes of a point collection respectively in a form of lists or numpy arrays. :return: A tuple of four items. These items represent western, eastern, northern and southern borders of the bounding box respectively. Values are floats in decimal degrees. :raises ValueError: If points collection has the longitudinal extent of more than 180 degrees (it is impossible to define a single hemisphere bound to poles that would contain the whole collection).
[ "Given", "a", "collection", "of", "points", "find", "and", "return", "the", "bounding", "box", "as", "a", "pair", "of", "longitudes", "and", "a", "pair", "of", "latitudes", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L295-L329
62
gem/oq-engine
openquake/hazardlib/geo/utils.py
get_middle_point
def get_middle_point(lon1, lat1, lon2, lat2): """ Given two points return the point exactly in the middle lying on the same great circle arc. Parameters are point coordinates in degrees. :returns: Tuple of longitude and latitude of the point in the middle. """ if lon1 == lon2 and lat1 == lat2: return lon1, lat1 dist = geodetic.geodetic_distance(lon1, lat1, lon2, lat2) azimuth = geodetic.azimuth(lon1, lat1, lon2, lat2) return geodetic.point_at(lon1, lat1, azimuth, dist / 2.0)
python
def get_middle_point(lon1, lat1, lon2, lat2): """ Given two points return the point exactly in the middle lying on the same great circle arc. Parameters are point coordinates in degrees. :returns: Tuple of longitude and latitude of the point in the middle. """ if lon1 == lon2 and lat1 == lat2: return lon1, lat1 dist = geodetic.geodetic_distance(lon1, lat1, lon2, lat2) azimuth = geodetic.azimuth(lon1, lat1, lon2, lat2) return geodetic.point_at(lon1, lat1, azimuth, dist / 2.0)
[ "def", "get_middle_point", "(", "lon1", ",", "lat1", ",", "lon2", ",", "lat2", ")", ":", "if", "lon1", "==", "lon2", "and", "lat1", "==", "lat2", ":", "return", "lon1", ",", "lat1", "dist", "=", "geodetic", ".", "geodetic_distance", "(", "lon1", ",", "lat1", ",", "lon2", ",", "lat2", ")", "azimuth", "=", "geodetic", ".", "azimuth", "(", "lon1", ",", "lat1", ",", "lon2", ",", "lat2", ")", "return", "geodetic", ".", "point_at", "(", "lon1", ",", "lat1", ",", "azimuth", ",", "dist", "/", "2.0", ")" ]
Given two points return the point exactly in the middle lying on the same great circle arc. Parameters are point coordinates in degrees. :returns: Tuple of longitude and latitude of the point in the middle.
[ "Given", "two", "points", "return", "the", "point", "exactly", "in", "the", "middle", "lying", "on", "the", "same", "great", "circle", "arc", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L428-L442
63
gem/oq-engine
openquake/hazardlib/geo/utils.py
cartesian_to_spherical
def cartesian_to_spherical(vectors): """ Return the spherical coordinates for coordinates in Cartesian space. This function does an opposite to :func:`spherical_to_cartesian`. :param vectors: Array of 3d vectors in Cartesian space of shape (..., 3) :returns: Tuple of three arrays of the same shape as ``vectors`` representing longitude (decimal degrees), latitude (decimal degrees) and depth (km) in specified order. """ rr = numpy.sqrt(numpy.sum(vectors * vectors, axis=-1)) xx, yy, zz = vectors.T lats = numpy.degrees(numpy.arcsin((zz / rr).clip(-1., 1.))) lons = numpy.degrees(numpy.arctan2(yy, xx)) depths = EARTH_RADIUS - rr return lons.T, lats.T, depths
python
def cartesian_to_spherical(vectors): """ Return the spherical coordinates for coordinates in Cartesian space. This function does an opposite to :func:`spherical_to_cartesian`. :param vectors: Array of 3d vectors in Cartesian space of shape (..., 3) :returns: Tuple of three arrays of the same shape as ``vectors`` representing longitude (decimal degrees), latitude (decimal degrees) and depth (km) in specified order. """ rr = numpy.sqrt(numpy.sum(vectors * vectors, axis=-1)) xx, yy, zz = vectors.T lats = numpy.degrees(numpy.arcsin((zz / rr).clip(-1., 1.))) lons = numpy.degrees(numpy.arctan2(yy, xx)) depths = EARTH_RADIUS - rr return lons.T, lats.T, depths
[ "def", "cartesian_to_spherical", "(", "vectors", ")", ":", "rr", "=", "numpy", ".", "sqrt", "(", "numpy", ".", "sum", "(", "vectors", "*", "vectors", ",", "axis", "=", "-", "1", ")", ")", "xx", ",", "yy", ",", "zz", "=", "vectors", ".", "T", "lats", "=", "numpy", ".", "degrees", "(", "numpy", ".", "arcsin", "(", "(", "zz", "/", "rr", ")", ".", "clip", "(", "-", "1.", ",", "1.", ")", ")", ")", "lons", "=", "numpy", ".", "degrees", "(", "numpy", ".", "arctan2", "(", "yy", ",", "xx", ")", ")", "depths", "=", "EARTH_RADIUS", "-", "rr", "return", "lons", ".", "T", ",", "lats", ".", "T", ",", "depths" ]
Return the spherical coordinates for coordinates in Cartesian space. This function does an opposite to :func:`spherical_to_cartesian`. :param vectors: Array of 3d vectors in Cartesian space of shape (..., 3) :returns: Tuple of three arrays of the same shape as ``vectors`` representing longitude (decimal degrees), latitude (decimal degrees) and depth (km) in specified order.
[ "Return", "the", "spherical", "coordinates", "for", "coordinates", "in", "Cartesian", "space", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L445-L463
64
gem/oq-engine
openquake/hazardlib/geo/utils.py
triangle_area
def triangle_area(e1, e2, e3): """ Get the area of triangle formed by three vectors. Parameters are three three-dimensional numpy arrays representing vectors of triangle's edges in Cartesian space. :returns: Float number, the area of the triangle in squared units of coordinates, or numpy array of shape of edges with one dimension less. Uses Heron formula, see http://mathworld.wolfram.com/HeronsFormula.html. """ # calculating edges length e1_length = numpy.sqrt(numpy.sum(e1 * e1, axis=-1)) e2_length = numpy.sqrt(numpy.sum(e2 * e2, axis=-1)) e3_length = numpy.sqrt(numpy.sum(e3 * e3, axis=-1)) # calculating half perimeter s = (e1_length + e2_length + e3_length) / 2.0 # applying Heron's formula return numpy.sqrt(s * (s - e1_length) * (s - e2_length) * (s - e3_length))
python
def triangle_area(e1, e2, e3): """ Get the area of triangle formed by three vectors. Parameters are three three-dimensional numpy arrays representing vectors of triangle's edges in Cartesian space. :returns: Float number, the area of the triangle in squared units of coordinates, or numpy array of shape of edges with one dimension less. Uses Heron formula, see http://mathworld.wolfram.com/HeronsFormula.html. """ # calculating edges length e1_length = numpy.sqrt(numpy.sum(e1 * e1, axis=-1)) e2_length = numpy.sqrt(numpy.sum(e2 * e2, axis=-1)) e3_length = numpy.sqrt(numpy.sum(e3 * e3, axis=-1)) # calculating half perimeter s = (e1_length + e2_length + e3_length) / 2.0 # applying Heron's formula return numpy.sqrt(s * (s - e1_length) * (s - e2_length) * (s - e3_length))
[ "def", "triangle_area", "(", "e1", ",", "e2", ",", "e3", ")", ":", "# calculating edges length", "e1_length", "=", "numpy", ".", "sqrt", "(", "numpy", ".", "sum", "(", "e1", "*", "e1", ",", "axis", "=", "-", "1", ")", ")", "e2_length", "=", "numpy", ".", "sqrt", "(", "numpy", ".", "sum", "(", "e2", "*", "e2", ",", "axis", "=", "-", "1", ")", ")", "e3_length", "=", "numpy", ".", "sqrt", "(", "numpy", ".", "sum", "(", "e3", "*", "e3", ",", "axis", "=", "-", "1", ")", ")", "# calculating half perimeter", "s", "=", "(", "e1_length", "+", "e2_length", "+", "e3_length", ")", "/", "2.0", "# applying Heron's formula", "return", "numpy", ".", "sqrt", "(", "s", "*", "(", "s", "-", "e1_length", ")", "*", "(", "s", "-", "e2_length", ")", "*", "(", "s", "-", "e3_length", ")", ")" ]
Get the area of triangle formed by three vectors. Parameters are three three-dimensional numpy arrays representing vectors of triangle's edges in Cartesian space. :returns: Float number, the area of the triangle in squared units of coordinates, or numpy array of shape of edges with one dimension less. Uses Heron formula, see http://mathworld.wolfram.com/HeronsFormula.html.
[ "Get", "the", "area", "of", "triangle", "formed", "by", "three", "vectors", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L466-L486
65
gem/oq-engine
openquake/hazardlib/geo/utils.py
normalized
def normalized(vector): """ Get unit vector for a given one. :param vector: Numpy vector as coordinates in Cartesian space, or an array of such. :returns: Numpy array of the same shape and structure where all vectors are normalized. That is, each coordinate component is divided by its vector's length. """ length = numpy.sum(vector * vector, axis=-1) length = numpy.sqrt(length.reshape(length.shape + (1, ))) return vector / length
python
def normalized(vector): """ Get unit vector for a given one. :param vector: Numpy vector as coordinates in Cartesian space, or an array of such. :returns: Numpy array of the same shape and structure where all vectors are normalized. That is, each coordinate component is divided by its vector's length. """ length = numpy.sum(vector * vector, axis=-1) length = numpy.sqrt(length.reshape(length.shape + (1, ))) return vector / length
[ "def", "normalized", "(", "vector", ")", ":", "length", "=", "numpy", ".", "sum", "(", "vector", "*", "vector", ",", "axis", "=", "-", "1", ")", "length", "=", "numpy", ".", "sqrt", "(", "length", ".", "reshape", "(", "length", ".", "shape", "+", "(", "1", ",", ")", ")", ")", "return", "vector", "/", "length" ]
Get unit vector for a given one. :param vector: Numpy vector as coordinates in Cartesian space, or an array of such. :returns: Numpy array of the same shape and structure where all vectors are normalized. That is, each coordinate component is divided by its vector's length.
[ "Get", "unit", "vector", "for", "a", "given", "one", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L489-L502
66
gem/oq-engine
openquake/hazardlib/geo/utils.py
point_to_polygon_distance
def point_to_polygon_distance(polygon, pxx, pyy): """ Calculate the distance to polygon for each point of the collection on the 2d Cartesian plane. :param polygon: Shapely "Polygon" geometry object. :param pxx: List or numpy array of abscissae values of points to calculate the distance from. :param pyy: Same structure as ``pxx``, but with ordinate values. :returns: Numpy array of distances in units of coordinate system. Points that lie inside the polygon have zero distance. """ pxx = numpy.array(pxx) pyy = numpy.array(pyy) assert pxx.shape == pyy.shape if pxx.ndim == 0: pxx = pxx.reshape((1, )) pyy = pyy.reshape((1, )) result = numpy.array([ polygon.distance(shapely.geometry.Point(pxx.item(i), pyy.item(i))) for i in range(pxx.size) ]) return result.reshape(pxx.shape)
python
def point_to_polygon_distance(polygon, pxx, pyy): """ Calculate the distance to polygon for each point of the collection on the 2d Cartesian plane. :param polygon: Shapely "Polygon" geometry object. :param pxx: List or numpy array of abscissae values of points to calculate the distance from. :param pyy: Same structure as ``pxx``, but with ordinate values. :returns: Numpy array of distances in units of coordinate system. Points that lie inside the polygon have zero distance. """ pxx = numpy.array(pxx) pyy = numpy.array(pyy) assert pxx.shape == pyy.shape if pxx.ndim == 0: pxx = pxx.reshape((1, )) pyy = pyy.reshape((1, )) result = numpy.array([ polygon.distance(shapely.geometry.Point(pxx.item(i), pyy.item(i))) for i in range(pxx.size) ]) return result.reshape(pxx.shape)
[ "def", "point_to_polygon_distance", "(", "polygon", ",", "pxx", ",", "pyy", ")", ":", "pxx", "=", "numpy", ".", "array", "(", "pxx", ")", "pyy", "=", "numpy", ".", "array", "(", "pyy", ")", "assert", "pxx", ".", "shape", "==", "pyy", ".", "shape", "if", "pxx", ".", "ndim", "==", "0", ":", "pxx", "=", "pxx", ".", "reshape", "(", "(", "1", ",", ")", ")", "pyy", "=", "pyy", ".", "reshape", "(", "(", "1", ",", ")", ")", "result", "=", "numpy", ".", "array", "(", "[", "polygon", ".", "distance", "(", "shapely", ".", "geometry", ".", "Point", "(", "pxx", ".", "item", "(", "i", ")", ",", "pyy", ".", "item", "(", "i", ")", ")", ")", "for", "i", "in", "range", "(", "pxx", ".", "size", ")", "]", ")", "return", "result", ".", "reshape", "(", "pxx", ".", "shape", ")" ]
Calculate the distance to polygon for each point of the collection on the 2d Cartesian plane. :param polygon: Shapely "Polygon" geometry object. :param pxx: List or numpy array of abscissae values of points to calculate the distance from. :param pyy: Same structure as ``pxx``, but with ordinate values. :returns: Numpy array of distances in units of coordinate system. Points that lie inside the polygon have zero distance.
[ "Calculate", "the", "distance", "to", "polygon", "for", "each", "point", "of", "the", "collection", "on", "the", "2d", "Cartesian", "plane", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L505-L531
67
gem/oq-engine
openquake/hazardlib/geo/utils.py
cross_idl
def cross_idl(lon1, lon2, *lons): """ Return True if two longitude values define line crossing international date line. >>> cross_idl(-45, 45) False >>> cross_idl(-180, -179) False >>> cross_idl(180, 179) False >>> cross_idl(45, -45) False >>> cross_idl(0, 0) False >>> cross_idl(-170, 170) True >>> cross_idl(170, -170) True >>> cross_idl(-180, 180) True """ lons = (lon1, lon2) + lons l1, l2 = min(lons), max(lons) # a line crosses the international date line if the end positions # have different sign and they are more than 180 degrees longitude apart return l1 * l2 < 0 and abs(l1 - l2) > 180
python
def cross_idl(lon1, lon2, *lons): """ Return True if two longitude values define line crossing international date line. >>> cross_idl(-45, 45) False >>> cross_idl(-180, -179) False >>> cross_idl(180, 179) False >>> cross_idl(45, -45) False >>> cross_idl(0, 0) False >>> cross_idl(-170, 170) True >>> cross_idl(170, -170) True >>> cross_idl(-180, 180) True """ lons = (lon1, lon2) + lons l1, l2 = min(lons), max(lons) # a line crosses the international date line if the end positions # have different sign and they are more than 180 degrees longitude apart return l1 * l2 < 0 and abs(l1 - l2) > 180
[ "def", "cross_idl", "(", "lon1", ",", "lon2", ",", "*", "lons", ")", ":", "lons", "=", "(", "lon1", ",", "lon2", ")", "+", "lons", "l1", ",", "l2", "=", "min", "(", "lons", ")", ",", "max", "(", "lons", ")", "# a line crosses the international date line if the end positions", "# have different sign and they are more than 180 degrees longitude apart", "return", "l1", "*", "l2", "<", "0", "and", "abs", "(", "l1", "-", "l2", ")", ">", "180" ]
Return True if two longitude values define line crossing international date line. >>> cross_idl(-45, 45) False >>> cross_idl(-180, -179) False >>> cross_idl(180, 179) False >>> cross_idl(45, -45) False >>> cross_idl(0, 0) False >>> cross_idl(-170, 170) True >>> cross_idl(170, -170) True >>> cross_idl(-180, 180) True
[ "Return", "True", "if", "two", "longitude", "values", "define", "line", "crossing", "international", "date", "line", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L548-L574
68
gem/oq-engine
openquake/hazardlib/geo/utils.py
normalize_lons
def normalize_lons(l1, l2): """ An international date line safe way of returning a range of longitudes. >>> normalize_lons(20, 30) # no IDL within the range [(20, 30)] >>> normalize_lons(-17, +17) # no IDL within the range [(-17, 17)] >>> normalize_lons(-178, +179) [(-180, -178), (179, 180)] >>> normalize_lons(178, -179) [(-180, -179), (178, 180)] >>> normalize_lons(179, -179) [(-180, -179), (179, 180)] >>> normalize_lons(177, -176) [(-180, -176), (177, 180)] """ if l1 > l2: # exchange lons l1, l2 = l2, l1 delta = l2 - l1 if l1 < 0 and l2 > 0 and delta > 180: return [(-180, l1), (l2, 180)] elif l1 > 0 and l2 > 180 and delta < 180: return [(l1, 180), (-180, l2 - 360)] elif l1 < -180 and l2 < 0 and delta < 180: return [(l1 + 360, 180), (l2, -180)] return [(l1, l2)]
python
def normalize_lons(l1, l2): """ An international date line safe way of returning a range of longitudes. >>> normalize_lons(20, 30) # no IDL within the range [(20, 30)] >>> normalize_lons(-17, +17) # no IDL within the range [(-17, 17)] >>> normalize_lons(-178, +179) [(-180, -178), (179, 180)] >>> normalize_lons(178, -179) [(-180, -179), (178, 180)] >>> normalize_lons(179, -179) [(-180, -179), (179, 180)] >>> normalize_lons(177, -176) [(-180, -176), (177, 180)] """ if l1 > l2: # exchange lons l1, l2 = l2, l1 delta = l2 - l1 if l1 < 0 and l2 > 0 and delta > 180: return [(-180, l1), (l2, 180)] elif l1 > 0 and l2 > 180 and delta < 180: return [(l1, 180), (-180, l2 - 360)] elif l1 < -180 and l2 < 0 and delta < 180: return [(l1 + 360, 180), (l2, -180)] return [(l1, l2)]
[ "def", "normalize_lons", "(", "l1", ",", "l2", ")", ":", "if", "l1", ">", "l2", ":", "# exchange lons", "l1", ",", "l2", "=", "l2", ",", "l1", "delta", "=", "l2", "-", "l1", "if", "l1", "<", "0", "and", "l2", ">", "0", "and", "delta", ">", "180", ":", "return", "[", "(", "-", "180", ",", "l1", ")", ",", "(", "l2", ",", "180", ")", "]", "elif", "l1", ">", "0", "and", "l2", ">", "180", "and", "delta", "<", "180", ":", "return", "[", "(", "l1", ",", "180", ")", ",", "(", "-", "180", ",", "l2", "-", "360", ")", "]", "elif", "l1", "<", "-", "180", "and", "l2", "<", "0", "and", "delta", "<", "180", ":", "return", "[", "(", "l1", "+", "360", ",", "180", ")", ",", "(", "l2", ",", "-", "180", ")", "]", "return", "[", "(", "l1", ",", "l2", ")", "]" ]
An international date line safe way of returning a range of longitudes. >>> normalize_lons(20, 30) # no IDL within the range [(20, 30)] >>> normalize_lons(-17, +17) # no IDL within the range [(-17, 17)] >>> normalize_lons(-178, +179) [(-180, -178), (179, 180)] >>> normalize_lons(178, -179) [(-180, -179), (178, 180)] >>> normalize_lons(179, -179) [(-180, -179), (179, 180)] >>> normalize_lons(177, -176) [(-180, -176), (177, 180)]
[ "An", "international", "date", "line", "safe", "way", "of", "returning", "a", "range", "of", "longitudes", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L577-L603
69
gem/oq-engine
openquake/hazardlib/geo/utils.py
_GeographicObjects.get_closest
def get_closest(self, lon, lat, depth=0): """ Get the closest object to the given longitude and latitude and its distance. :param lon: longitude in degrees :param lat: latitude in degrees :param depth: depth in km (default 0) :returns: (object, distance) """ xyz = spherical_to_cartesian(lon, lat, depth) min_dist, idx = self.kdtree.query(xyz) return self.objects[idx], min_dist
python
def get_closest(self, lon, lat, depth=0): """ Get the closest object to the given longitude and latitude and its distance. :param lon: longitude in degrees :param lat: latitude in degrees :param depth: depth in km (default 0) :returns: (object, distance) """ xyz = spherical_to_cartesian(lon, lat, depth) min_dist, idx = self.kdtree.query(xyz) return self.objects[idx], min_dist
[ "def", "get_closest", "(", "self", ",", "lon", ",", "lat", ",", "depth", "=", "0", ")", ":", "xyz", "=", "spherical_to_cartesian", "(", "lon", ",", "lat", ",", "depth", ")", "min_dist", ",", "idx", "=", "self", ".", "kdtree", ".", "query", "(", "xyz", ")", "return", "self", ".", "objects", "[", "idx", "]", ",", "min_dist" ]
Get the closest object to the given longitude and latitude and its distance. :param lon: longitude in degrees :param lat: latitude in degrees :param depth: depth in km (default 0) :returns: (object, distance)
[ "Get", "the", "closest", "object", "to", "the", "given", "longitude", "and", "latitude", "and", "its", "distance", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L85-L97
70
gem/oq-engine
openquake/hazardlib/geo/utils.py
_GeographicObjects.assoc2
def assoc2(self, assets_by_site, assoc_dist, mode, asset_refs): """ Associated a list of assets by site to the site collection used to instantiate GeographicObjects. :param assets_by_sites: a list of lists of assets :param assoc_dist: the maximum distance for association :param mode: 'strict', 'warn' or 'filter' :param asset_ref: ID of the assets are a list of strings :returns: filtered site collection, filtered assets by site, discarded """ assert mode in 'strict filter', mode self.objects.filtered # self.objects must be a SiteCollection asset_dt = numpy.dtype( [('asset_ref', vstr), ('lon', F32), ('lat', F32)]) assets_by_sid = collections.defaultdict(list) discarded = [] for assets in assets_by_site: lon, lat = assets[0].location obj, distance = self.get_closest(lon, lat) if distance <= assoc_dist: # keep the assets, otherwise discard them assets_by_sid[obj['sids']].extend(assets) elif mode == 'strict': raise SiteAssociationError( 'There is nothing closer than %s km ' 'to site (%s %s)' % (assoc_dist, lon, lat)) else: discarded.extend(assets) sids = sorted(assets_by_sid) if not sids: raise SiteAssociationError( 'Could not associate any site to any assets within the ' 'asset_hazard_distance of %s km' % assoc_dist) assets_by_site = [ sorted(assets_by_sid[sid], key=operator.attrgetter('ordinal')) for sid in sids] data = [(asset_refs[asset.ordinal],) + asset.location for asset in discarded] discarded = numpy.array(data, asset_dt) return self.objects.filtered(sids), assets_by_site, discarded
python
def assoc2(self, assets_by_site, assoc_dist, mode, asset_refs): """ Associated a list of assets by site to the site collection used to instantiate GeographicObjects. :param assets_by_sites: a list of lists of assets :param assoc_dist: the maximum distance for association :param mode: 'strict', 'warn' or 'filter' :param asset_ref: ID of the assets are a list of strings :returns: filtered site collection, filtered assets by site, discarded """ assert mode in 'strict filter', mode self.objects.filtered # self.objects must be a SiteCollection asset_dt = numpy.dtype( [('asset_ref', vstr), ('lon', F32), ('lat', F32)]) assets_by_sid = collections.defaultdict(list) discarded = [] for assets in assets_by_site: lon, lat = assets[0].location obj, distance = self.get_closest(lon, lat) if distance <= assoc_dist: # keep the assets, otherwise discard them assets_by_sid[obj['sids']].extend(assets) elif mode == 'strict': raise SiteAssociationError( 'There is nothing closer than %s km ' 'to site (%s %s)' % (assoc_dist, lon, lat)) else: discarded.extend(assets) sids = sorted(assets_by_sid) if not sids: raise SiteAssociationError( 'Could not associate any site to any assets within the ' 'asset_hazard_distance of %s km' % assoc_dist) assets_by_site = [ sorted(assets_by_sid[sid], key=operator.attrgetter('ordinal')) for sid in sids] data = [(asset_refs[asset.ordinal],) + asset.location for asset in discarded] discarded = numpy.array(data, asset_dt) return self.objects.filtered(sids), assets_by_site, discarded
[ "def", "assoc2", "(", "self", ",", "assets_by_site", ",", "assoc_dist", ",", "mode", ",", "asset_refs", ")", ":", "assert", "mode", "in", "'strict filter'", ",", "mode", "self", ".", "objects", ".", "filtered", "# self.objects must be a SiteCollection", "asset_dt", "=", "numpy", ".", "dtype", "(", "[", "(", "'asset_ref'", ",", "vstr", ")", ",", "(", "'lon'", ",", "F32", ")", ",", "(", "'lat'", ",", "F32", ")", "]", ")", "assets_by_sid", "=", "collections", ".", "defaultdict", "(", "list", ")", "discarded", "=", "[", "]", "for", "assets", "in", "assets_by_site", ":", "lon", ",", "lat", "=", "assets", "[", "0", "]", ".", "location", "obj", ",", "distance", "=", "self", ".", "get_closest", "(", "lon", ",", "lat", ")", "if", "distance", "<=", "assoc_dist", ":", "# keep the assets, otherwise discard them", "assets_by_sid", "[", "obj", "[", "'sids'", "]", "]", ".", "extend", "(", "assets", ")", "elif", "mode", "==", "'strict'", ":", "raise", "SiteAssociationError", "(", "'There is nothing closer than %s km '", "'to site (%s %s)'", "%", "(", "assoc_dist", ",", "lon", ",", "lat", ")", ")", "else", ":", "discarded", ".", "extend", "(", "assets", ")", "sids", "=", "sorted", "(", "assets_by_sid", ")", "if", "not", "sids", ":", "raise", "SiteAssociationError", "(", "'Could not associate any site to any assets within the '", "'asset_hazard_distance of %s km'", "%", "assoc_dist", ")", "assets_by_site", "=", "[", "sorted", "(", "assets_by_sid", "[", "sid", "]", ",", "key", "=", "operator", ".", "attrgetter", "(", "'ordinal'", ")", ")", "for", "sid", "in", "sids", "]", "data", "=", "[", "(", "asset_refs", "[", "asset", ".", "ordinal", "]", ",", ")", "+", "asset", ".", "location", "for", "asset", "in", "discarded", "]", "discarded", "=", "numpy", ".", "array", "(", "data", ",", "asset_dt", ")", "return", "self", ".", "objects", ".", "filtered", "(", "sids", ")", ",", "assets_by_site", ",", "discarded" ]
Associated a list of assets by site to the site collection used to instantiate GeographicObjects. :param assets_by_sites: a list of lists of assets :param assoc_dist: the maximum distance for association :param mode: 'strict', 'warn' or 'filter' :param asset_ref: ID of the assets are a list of strings :returns: filtered site collection, filtered assets by site, discarded
[ "Associated", "a", "list", "of", "assets", "by", "site", "to", "the", "site", "collection", "used", "to", "instantiate", "GeographicObjects", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/utils.py#L134-L174
71
gem/oq-engine
openquake/risklib/read_nrml.py
ffconvert
def ffconvert(fname, limit_states, ff, min_iml=1E-10): """ Convert a fragility function into a numpy array plus a bunch of attributes. :param fname: path to the fragility model file :param limit_states: expected limit states :param ff: fragility function node :returns: a pair (array, dictionary) """ with context(fname, ff): ffs = ff[1:] imls = ff.imls nodamage = imls.attrib.get('noDamageLimit') if nodamage == 0: # use a cutoff to avoid log(0) in GMPE.to_distribution_values logging.warning('Found a noDamageLimit=0 in %s, line %s, ' 'using %g instead', fname, ff.lineno, min_iml) nodamage = min_iml with context(fname, imls): attrs = dict(format=ff['format'], imt=imls['imt'], id=ff['id'], nodamage=nodamage) LS = len(limit_states) if LS != len(ffs): with context(fname, ff): raise InvalidFile('expected %d limit states, found %d' % (LS, len(ffs))) if ff['format'] == 'continuous': minIML = float(imls['minIML']) if minIML == 0: # use a cutoff to avoid log(0) in GMPE.to_distribution_values logging.warning('Found minIML=0 in %s, line %s, using %g instead', fname, imls.lineno, min_iml) minIML = min_iml attrs['minIML'] = minIML attrs['maxIML'] = float(imls['maxIML']) array = numpy.zeros(LS, [('mean', F64), ('stddev', F64)]) for i, ls, node in zip(range(LS), limit_states, ff[1:]): if ls != node['ls']: with context(fname, node): raise InvalidFile('expected %s, found' % (ls, node['ls'])) array['mean'][i] = node['mean'] array['stddev'][i] = node['stddev'] elif ff['format'] == 'discrete': attrs['imls'] = ~imls valid.check_levels(attrs['imls'], attrs['imt'], min_iml) num_poes = len(attrs['imls']) array = numpy.zeros((LS, num_poes)) for i, ls, node in zip(range(LS), limit_states, ff[1:]): with context(fname, node): if ls != node['ls']: raise InvalidFile('expected %s, found' % (ls, node['ls'])) poes = (~node if isinstance(~node, list) else valid.probabilities(~node)) if len(poes) != num_poes: raise InvalidFile('expected %s, found' % (num_poes, len(poes))) array[i, :] = poes # NB: the format is constrained in nrml.FragilityNode to be either # discrete or continuous, there is no third option return array, attrs
python
def ffconvert(fname, limit_states, ff, min_iml=1E-10): """ Convert a fragility function into a numpy array plus a bunch of attributes. :param fname: path to the fragility model file :param limit_states: expected limit states :param ff: fragility function node :returns: a pair (array, dictionary) """ with context(fname, ff): ffs = ff[1:] imls = ff.imls nodamage = imls.attrib.get('noDamageLimit') if nodamage == 0: # use a cutoff to avoid log(0) in GMPE.to_distribution_values logging.warning('Found a noDamageLimit=0 in %s, line %s, ' 'using %g instead', fname, ff.lineno, min_iml) nodamage = min_iml with context(fname, imls): attrs = dict(format=ff['format'], imt=imls['imt'], id=ff['id'], nodamage=nodamage) LS = len(limit_states) if LS != len(ffs): with context(fname, ff): raise InvalidFile('expected %d limit states, found %d' % (LS, len(ffs))) if ff['format'] == 'continuous': minIML = float(imls['minIML']) if minIML == 0: # use a cutoff to avoid log(0) in GMPE.to_distribution_values logging.warning('Found minIML=0 in %s, line %s, using %g instead', fname, imls.lineno, min_iml) minIML = min_iml attrs['minIML'] = minIML attrs['maxIML'] = float(imls['maxIML']) array = numpy.zeros(LS, [('mean', F64), ('stddev', F64)]) for i, ls, node in zip(range(LS), limit_states, ff[1:]): if ls != node['ls']: with context(fname, node): raise InvalidFile('expected %s, found' % (ls, node['ls'])) array['mean'][i] = node['mean'] array['stddev'][i] = node['stddev'] elif ff['format'] == 'discrete': attrs['imls'] = ~imls valid.check_levels(attrs['imls'], attrs['imt'], min_iml) num_poes = len(attrs['imls']) array = numpy.zeros((LS, num_poes)) for i, ls, node in zip(range(LS), limit_states, ff[1:]): with context(fname, node): if ls != node['ls']: raise InvalidFile('expected %s, found' % (ls, node['ls'])) poes = (~node if isinstance(~node, list) else valid.probabilities(~node)) if len(poes) != num_poes: raise InvalidFile('expected %s, found' % (num_poes, len(poes))) array[i, :] = poes # NB: the format is constrained in nrml.FragilityNode to be either # discrete or continuous, there is no third option return array, attrs
[ "def", "ffconvert", "(", "fname", ",", "limit_states", ",", "ff", ",", "min_iml", "=", "1E-10", ")", ":", "with", "context", "(", "fname", ",", "ff", ")", ":", "ffs", "=", "ff", "[", "1", ":", "]", "imls", "=", "ff", ".", "imls", "nodamage", "=", "imls", ".", "attrib", ".", "get", "(", "'noDamageLimit'", ")", "if", "nodamage", "==", "0", ":", "# use a cutoff to avoid log(0) in GMPE.to_distribution_values", "logging", ".", "warning", "(", "'Found a noDamageLimit=0 in %s, line %s, '", "'using %g instead'", ",", "fname", ",", "ff", ".", "lineno", ",", "min_iml", ")", "nodamage", "=", "min_iml", "with", "context", "(", "fname", ",", "imls", ")", ":", "attrs", "=", "dict", "(", "format", "=", "ff", "[", "'format'", "]", ",", "imt", "=", "imls", "[", "'imt'", "]", ",", "id", "=", "ff", "[", "'id'", "]", ",", "nodamage", "=", "nodamage", ")", "LS", "=", "len", "(", "limit_states", ")", "if", "LS", "!=", "len", "(", "ffs", ")", ":", "with", "context", "(", "fname", ",", "ff", ")", ":", "raise", "InvalidFile", "(", "'expected %d limit states, found %d'", "%", "(", "LS", ",", "len", "(", "ffs", ")", ")", ")", "if", "ff", "[", "'format'", "]", "==", "'continuous'", ":", "minIML", "=", "float", "(", "imls", "[", "'minIML'", "]", ")", "if", "minIML", "==", "0", ":", "# use a cutoff to avoid log(0) in GMPE.to_distribution_values", "logging", ".", "warning", "(", "'Found minIML=0 in %s, line %s, using %g instead'", ",", "fname", ",", "imls", ".", "lineno", ",", "min_iml", ")", "minIML", "=", "min_iml", "attrs", "[", "'minIML'", "]", "=", "minIML", "attrs", "[", "'maxIML'", "]", "=", "float", "(", "imls", "[", "'maxIML'", "]", ")", "array", "=", "numpy", ".", "zeros", "(", "LS", ",", "[", "(", "'mean'", ",", "F64", ")", ",", "(", "'stddev'", ",", "F64", ")", "]", ")", "for", "i", ",", "ls", ",", "node", "in", "zip", "(", "range", "(", "LS", ")", ",", "limit_states", ",", "ff", "[", "1", ":", "]", ")", ":", "if", "ls", "!=", "node", "[", "'ls'", "]", ":", "with", "context", "(", "fname", ",", "node", ")", ":", "raise", "InvalidFile", "(", "'expected %s, found'", "%", "(", "ls", ",", "node", "[", "'ls'", "]", ")", ")", "array", "[", "'mean'", "]", "[", "i", "]", "=", "node", "[", "'mean'", "]", "array", "[", "'stddev'", "]", "[", "i", "]", "=", "node", "[", "'stddev'", "]", "elif", "ff", "[", "'format'", "]", "==", "'discrete'", ":", "attrs", "[", "'imls'", "]", "=", "~", "imls", "valid", ".", "check_levels", "(", "attrs", "[", "'imls'", "]", ",", "attrs", "[", "'imt'", "]", ",", "min_iml", ")", "num_poes", "=", "len", "(", "attrs", "[", "'imls'", "]", ")", "array", "=", "numpy", ".", "zeros", "(", "(", "LS", ",", "num_poes", ")", ")", "for", "i", ",", "ls", ",", "node", "in", "zip", "(", "range", "(", "LS", ")", ",", "limit_states", ",", "ff", "[", "1", ":", "]", ")", ":", "with", "context", "(", "fname", ",", "node", ")", ":", "if", "ls", "!=", "node", "[", "'ls'", "]", ":", "raise", "InvalidFile", "(", "'expected %s, found'", "%", "(", "ls", ",", "node", "[", "'ls'", "]", ")", ")", "poes", "=", "(", "~", "node", "if", "isinstance", "(", "~", "node", ",", "list", ")", "else", "valid", ".", "probabilities", "(", "~", "node", ")", ")", "if", "len", "(", "poes", ")", "!=", "num_poes", ":", "raise", "InvalidFile", "(", "'expected %s, found'", "%", "(", "num_poes", ",", "len", "(", "poes", ")", ")", ")", "array", "[", "i", ",", ":", "]", "=", "poes", "# NB: the format is constrained in nrml.FragilityNode to be either", "# discrete or continuous, there is no third option", "return", "array", ",", "attrs" ]
Convert a fragility function into a numpy array plus a bunch of attributes. :param fname: path to the fragility model file :param limit_states: expected limit states :param ff: fragility function node :returns: a pair (array, dictionary)
[ "Convert", "a", "fragility", "function", "into", "a", "numpy", "array", "plus", "a", "bunch", "of", "attributes", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/read_nrml.py#L152-L217
72
gem/oq-engine
openquake/risklib/read_nrml.py
taxonomy
def taxonomy(value): """ Any ASCII character goes into a taxonomy, except spaces. """ try: value.encode('ascii') except UnicodeEncodeError: raise ValueError('tag %r is not ASCII' % value) if re.search(r'\s', value): raise ValueError('The taxonomy %r contains whitespace chars' % value) return value
python
def taxonomy(value): """ Any ASCII character goes into a taxonomy, except spaces. """ try: value.encode('ascii') except UnicodeEncodeError: raise ValueError('tag %r is not ASCII' % value) if re.search(r'\s', value): raise ValueError('The taxonomy %r contains whitespace chars' % value) return value
[ "def", "taxonomy", "(", "value", ")", ":", "try", ":", "value", ".", "encode", "(", "'ascii'", ")", "except", "UnicodeEncodeError", ":", "raise", "ValueError", "(", "'tag %r is not ASCII'", "%", "value", ")", "if", "re", ".", "search", "(", "r'\\s'", ",", "value", ")", ":", "raise", "ValueError", "(", "'The taxonomy %r contains whitespace chars'", "%", "value", ")", "return", "value" ]
Any ASCII character goes into a taxonomy, except spaces.
[ "Any", "ASCII", "character", "goes", "into", "a", "taxonomy", "except", "spaces", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/read_nrml.py#L371-L381
73
gem/oq-engine
openquake/risklib/read_nrml.py
update_validators
def update_validators(): """ Call this to updade the global nrml.validators """ validators.update({ 'fragilityFunction.id': valid.utf8, # taxonomy 'vulnerabilityFunction.id': valid.utf8, # taxonomy 'consequenceFunction.id': valid.utf8, # taxonomy 'asset.id': valid.asset_id, 'costType.name': valid.cost_type, 'costType.type': valid.cost_type_type, 'cost.type': valid.cost_type, 'area.type': valid.name, 'isAbsolute': valid.boolean, 'insuranceLimit': valid.positivefloat, 'deductible': valid.positivefloat, 'occupants': valid.positivefloat, 'value': valid.positivefloat, 'retrofitted': valid.positivefloat, 'number': valid.compose(valid.positivefloat, valid.nonzero), 'vulnerabilitySetID': str, # any ASCII string is fine 'vulnerabilityFunctionID': str, # any ASCII string is fine 'lossCategory': valid.utf8, # a description field 'lr': valid.probability, 'lossRatio': valid.positivefloats, 'coefficientsVariation': valid.positivefloats, 'probabilisticDistribution': valid.Choice('LN', 'BT'), 'dist': valid.Choice('LN', 'BT', 'PM'), 'meanLRs': valid.positivefloats, 'covLRs': valid.positivefloats, 'format': valid.ChoiceCI('discrete', 'continuous'), 'mean': valid.positivefloat, 'stddev': valid.positivefloat, 'minIML': valid.positivefloat, 'maxIML': valid.positivefloat, 'limitStates': valid.namelist, 'noDamageLimit': valid.NoneOr(valid.positivefloat), 'loss_type': valid_loss_types, 'losses': valid.positivefloats, 'averageLoss': valid.positivefloat, 'stdDevLoss': valid.positivefloat, 'ffs.type': valid.ChoiceCI('lognormal'), 'assetLifeExpectancy': valid.positivefloat, 'interestRate': valid.positivefloat, 'lossType': valid_loss_types, 'aalOrig': valid.positivefloat, 'aalRetr': valid.positivefloat, 'ratio': valid.positivefloat, 'cf': asset_mean_stddev, 'damage': damage_triple, 'damageStates': valid.namelist, 'taxonomy': taxonomy, 'tagNames': valid.namelist, })
python
def update_validators(): """ Call this to updade the global nrml.validators """ validators.update({ 'fragilityFunction.id': valid.utf8, # taxonomy 'vulnerabilityFunction.id': valid.utf8, # taxonomy 'consequenceFunction.id': valid.utf8, # taxonomy 'asset.id': valid.asset_id, 'costType.name': valid.cost_type, 'costType.type': valid.cost_type_type, 'cost.type': valid.cost_type, 'area.type': valid.name, 'isAbsolute': valid.boolean, 'insuranceLimit': valid.positivefloat, 'deductible': valid.positivefloat, 'occupants': valid.positivefloat, 'value': valid.positivefloat, 'retrofitted': valid.positivefloat, 'number': valid.compose(valid.positivefloat, valid.nonzero), 'vulnerabilitySetID': str, # any ASCII string is fine 'vulnerabilityFunctionID': str, # any ASCII string is fine 'lossCategory': valid.utf8, # a description field 'lr': valid.probability, 'lossRatio': valid.positivefloats, 'coefficientsVariation': valid.positivefloats, 'probabilisticDistribution': valid.Choice('LN', 'BT'), 'dist': valid.Choice('LN', 'BT', 'PM'), 'meanLRs': valid.positivefloats, 'covLRs': valid.positivefloats, 'format': valid.ChoiceCI('discrete', 'continuous'), 'mean': valid.positivefloat, 'stddev': valid.positivefloat, 'minIML': valid.positivefloat, 'maxIML': valid.positivefloat, 'limitStates': valid.namelist, 'noDamageLimit': valid.NoneOr(valid.positivefloat), 'loss_type': valid_loss_types, 'losses': valid.positivefloats, 'averageLoss': valid.positivefloat, 'stdDevLoss': valid.positivefloat, 'ffs.type': valid.ChoiceCI('lognormal'), 'assetLifeExpectancy': valid.positivefloat, 'interestRate': valid.positivefloat, 'lossType': valid_loss_types, 'aalOrig': valid.positivefloat, 'aalRetr': valid.positivefloat, 'ratio': valid.positivefloat, 'cf': asset_mean_stddev, 'damage': damage_triple, 'damageStates': valid.namelist, 'taxonomy': taxonomy, 'tagNames': valid.namelist, })
[ "def", "update_validators", "(", ")", ":", "validators", ".", "update", "(", "{", "'fragilityFunction.id'", ":", "valid", ".", "utf8", ",", "# taxonomy", "'vulnerabilityFunction.id'", ":", "valid", ".", "utf8", ",", "# taxonomy", "'consequenceFunction.id'", ":", "valid", ".", "utf8", ",", "# taxonomy", "'asset.id'", ":", "valid", ".", "asset_id", ",", "'costType.name'", ":", "valid", ".", "cost_type", ",", "'costType.type'", ":", "valid", ".", "cost_type_type", ",", "'cost.type'", ":", "valid", ".", "cost_type", ",", "'area.type'", ":", "valid", ".", "name", ",", "'isAbsolute'", ":", "valid", ".", "boolean", ",", "'insuranceLimit'", ":", "valid", ".", "positivefloat", ",", "'deductible'", ":", "valid", ".", "positivefloat", ",", "'occupants'", ":", "valid", ".", "positivefloat", ",", "'value'", ":", "valid", ".", "positivefloat", ",", "'retrofitted'", ":", "valid", ".", "positivefloat", ",", "'number'", ":", "valid", ".", "compose", "(", "valid", ".", "positivefloat", ",", "valid", ".", "nonzero", ")", ",", "'vulnerabilitySetID'", ":", "str", ",", "# any ASCII string is fine", "'vulnerabilityFunctionID'", ":", "str", ",", "# any ASCII string is fine", "'lossCategory'", ":", "valid", ".", "utf8", ",", "# a description field", "'lr'", ":", "valid", ".", "probability", ",", "'lossRatio'", ":", "valid", ".", "positivefloats", ",", "'coefficientsVariation'", ":", "valid", ".", "positivefloats", ",", "'probabilisticDistribution'", ":", "valid", ".", "Choice", "(", "'LN'", ",", "'BT'", ")", ",", "'dist'", ":", "valid", ".", "Choice", "(", "'LN'", ",", "'BT'", ",", "'PM'", ")", ",", "'meanLRs'", ":", "valid", ".", "positivefloats", ",", "'covLRs'", ":", "valid", ".", "positivefloats", ",", "'format'", ":", "valid", ".", "ChoiceCI", "(", "'discrete'", ",", "'continuous'", ")", ",", "'mean'", ":", "valid", ".", "positivefloat", ",", "'stddev'", ":", "valid", ".", "positivefloat", ",", "'minIML'", ":", "valid", ".", "positivefloat", ",", "'maxIML'", ":", "valid", ".", "positivefloat", ",", "'limitStates'", ":", "valid", ".", "namelist", ",", "'noDamageLimit'", ":", "valid", ".", "NoneOr", "(", "valid", ".", "positivefloat", ")", ",", "'loss_type'", ":", "valid_loss_types", ",", "'losses'", ":", "valid", ".", "positivefloats", ",", "'averageLoss'", ":", "valid", ".", "positivefloat", ",", "'stdDevLoss'", ":", "valid", ".", "positivefloat", ",", "'ffs.type'", ":", "valid", ".", "ChoiceCI", "(", "'lognormal'", ")", ",", "'assetLifeExpectancy'", ":", "valid", ".", "positivefloat", ",", "'interestRate'", ":", "valid", ".", "positivefloat", ",", "'lossType'", ":", "valid_loss_types", ",", "'aalOrig'", ":", "valid", ".", "positivefloat", ",", "'aalRetr'", ":", "valid", ".", "positivefloat", ",", "'ratio'", ":", "valid", ".", "positivefloat", ",", "'cf'", ":", "asset_mean_stddev", ",", "'damage'", ":", "damage_triple", ",", "'damageStates'", ":", "valid", ".", "namelist", ",", "'taxonomy'", ":", "taxonomy", ",", "'tagNames'", ":", "valid", ".", "namelist", ",", "}", ")" ]
Call this to updade the global nrml.validators
[ "Call", "this", "to", "updade", "the", "global", "nrml", ".", "validators" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/read_nrml.py#L384-L437
74
gem/oq-engine
openquake/calculators/extract.py
barray
def barray(iterlines): """ Array of bytes """ lst = [line.encode('utf-8') for line in iterlines] arr = numpy.array(lst) return arr
python
def barray(iterlines): """ Array of bytes """ lst = [line.encode('utf-8') for line in iterlines] arr = numpy.array(lst) return arr
[ "def", "barray", "(", "iterlines", ")", ":", "lst", "=", "[", "line", ".", "encode", "(", "'utf-8'", ")", "for", "line", "in", "iterlines", "]", "arr", "=", "numpy", ".", "array", "(", "lst", ")", "return", "arr" ]
Array of bytes
[ "Array", "of", "bytes" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L130-L136
75
gem/oq-engine
openquake/calculators/extract.py
losses_by_tag
def losses_by_tag(dstore, tag): """ Statistical average losses by tag. For instance call $ oq extract losses_by_tag/occupancy """ dt = [(tag, vstr)] + dstore['oqparam'].loss_dt_list() aids = dstore['assetcol/array'][tag] dset, stats = _get(dstore, 'avg_losses') arr = dset.value tagvalues = dstore['assetcol/tagcol/' + tag][1:] # except tagvalue="?" for s, stat in enumerate(stats): out = numpy.zeros(len(tagvalues), dt) for li, (lt, lt_dt) in enumerate(dt[1:]): for i, tagvalue in enumerate(tagvalues): out[i][tag] = tagvalue counts = arr[aids == i + 1, s, li].sum() if counts: out[i][lt] = counts yield stat, out
python
def losses_by_tag(dstore, tag): """ Statistical average losses by tag. For instance call $ oq extract losses_by_tag/occupancy """ dt = [(tag, vstr)] + dstore['oqparam'].loss_dt_list() aids = dstore['assetcol/array'][tag] dset, stats = _get(dstore, 'avg_losses') arr = dset.value tagvalues = dstore['assetcol/tagcol/' + tag][1:] # except tagvalue="?" for s, stat in enumerate(stats): out = numpy.zeros(len(tagvalues), dt) for li, (lt, lt_dt) in enumerate(dt[1:]): for i, tagvalue in enumerate(tagvalues): out[i][tag] = tagvalue counts = arr[aids == i + 1, s, li].sum() if counts: out[i][lt] = counts yield stat, out
[ "def", "losses_by_tag", "(", "dstore", ",", "tag", ")", ":", "dt", "=", "[", "(", "tag", ",", "vstr", ")", "]", "+", "dstore", "[", "'oqparam'", "]", ".", "loss_dt_list", "(", ")", "aids", "=", "dstore", "[", "'assetcol/array'", "]", "[", "tag", "]", "dset", ",", "stats", "=", "_get", "(", "dstore", ",", "'avg_losses'", ")", "arr", "=", "dset", ".", "value", "tagvalues", "=", "dstore", "[", "'assetcol/tagcol/'", "+", "tag", "]", "[", "1", ":", "]", "# except tagvalue=\"?\"", "for", "s", ",", "stat", "in", "enumerate", "(", "stats", ")", ":", "out", "=", "numpy", ".", "zeros", "(", "len", "(", "tagvalues", ")", ",", "dt", ")", "for", "li", ",", "(", "lt", ",", "lt_dt", ")", "in", "enumerate", "(", "dt", "[", "1", ":", "]", ")", ":", "for", "i", ",", "tagvalue", "in", "enumerate", "(", "tagvalues", ")", ":", "out", "[", "i", "]", "[", "tag", "]", "=", "tagvalue", "counts", "=", "arr", "[", "aids", "==", "i", "+", "1", ",", "s", ",", "li", "]", ".", "sum", "(", ")", "if", "counts", ":", "out", "[", "i", "]", "[", "lt", "]", "=", "counts", "yield", "stat", ",", "out" ]
Statistical average losses by tag. For instance call $ oq extract losses_by_tag/occupancy
[ "Statistical", "average", "losses", "by", "tag", ".", "For", "instance", "call" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L808-L827
76
gem/oq-engine
openquake/calculators/extract.py
WebExtractor.dump
def dump(self, fname): """ Dump the remote datastore on a local path. """ url = '%s/v1/calc/%d/datastore' % (self.server, self.calc_id) resp = self.sess.get(url, stream=True) down = 0 with open(fname, 'wb') as f: logging.info('Saving %s', fname) for chunk in resp.iter_content(CHUNKSIZE): f.write(chunk) down += len(chunk) println('Downloaded {:,} bytes'.format(down)) print()
python
def dump(self, fname): """ Dump the remote datastore on a local path. """ url = '%s/v1/calc/%d/datastore' % (self.server, self.calc_id) resp = self.sess.get(url, stream=True) down = 0 with open(fname, 'wb') as f: logging.info('Saving %s', fname) for chunk in resp.iter_content(CHUNKSIZE): f.write(chunk) down += len(chunk) println('Downloaded {:,} bytes'.format(down)) print()
[ "def", "dump", "(", "self", ",", "fname", ")", ":", "url", "=", "'%s/v1/calc/%d/datastore'", "%", "(", "self", ".", "server", ",", "self", ".", "calc_id", ")", "resp", "=", "self", ".", "sess", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "down", "=", "0", "with", "open", "(", "fname", ",", "'wb'", ")", "as", "f", ":", "logging", ".", "info", "(", "'Saving %s'", ",", "fname", ")", "for", "chunk", "in", "resp", ".", "iter_content", "(", "CHUNKSIZE", ")", ":", "f", ".", "write", "(", "chunk", ")", "down", "+=", "len", "(", "chunk", ")", "println", "(", "'Downloaded {:,} bytes'", ".", "format", "(", "down", ")", ")", "print", "(", ")" ]
Dump the remote datastore on a local path.
[ "Dump", "the", "remote", "datastore", "on", "a", "local", "path", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/extract.py#L988-L1001
77
gem/oq-engine
openquake/hazardlib/gsim/utils_swiss_gmpe.py
_compute_small_mag_correction_term
def _compute_small_mag_correction_term(C, mag, rhypo): """ small magnitude correction applied to the median values """ if mag >= 3.00 and mag < 5.5: min_term = np.minimum(rhypo, C['Rm']) max_term = np.maximum(min_term, 10) term_ln = np.log(max_term / 20) term_ratio = ((5.50 - mag) / C['a1']) temp = (term_ratio) ** C['a2'] * (C['b1'] + C['b2'] * term_ln) return 1 / np.exp(temp) else: return 1
python
def _compute_small_mag_correction_term(C, mag, rhypo): """ small magnitude correction applied to the median values """ if mag >= 3.00 and mag < 5.5: min_term = np.minimum(rhypo, C['Rm']) max_term = np.maximum(min_term, 10) term_ln = np.log(max_term / 20) term_ratio = ((5.50 - mag) / C['a1']) temp = (term_ratio) ** C['a2'] * (C['b1'] + C['b2'] * term_ln) return 1 / np.exp(temp) else: return 1
[ "def", "_compute_small_mag_correction_term", "(", "C", ",", "mag", ",", "rhypo", ")", ":", "if", "mag", ">=", "3.00", "and", "mag", "<", "5.5", ":", "min_term", "=", "np", ".", "minimum", "(", "rhypo", ",", "C", "[", "'Rm'", "]", ")", "max_term", "=", "np", ".", "maximum", "(", "min_term", ",", "10", ")", "term_ln", "=", "np", ".", "log", "(", "max_term", "/", "20", ")", "term_ratio", "=", "(", "(", "5.50", "-", "mag", ")", "/", "C", "[", "'a1'", "]", ")", "temp", "=", "(", "term_ratio", ")", "**", "C", "[", "'a2'", "]", "*", "(", "C", "[", "'b1'", "]", "+", "C", "[", "'b2'", "]", "*", "term_ln", ")", "return", "1", "/", "np", ".", "exp", "(", "temp", ")", "else", ":", "return", "1" ]
small magnitude correction applied to the median values
[ "small", "magnitude", "correction", "applied", "to", "the", "median", "values" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/utils_swiss_gmpe.py#L40-L52
78
gem/oq-engine
openquake/hazardlib/gsim/utils_swiss_gmpe.py
_apply_adjustments
def _apply_adjustments(COEFFS, C_ADJ, tau_ss, mean, stddevs, sites, rup, dists, imt, stddev_types, log_phi_ss, NL=None, tau_value=None): """ This method applies adjustments to the mean and standard deviation. The small-magnitude adjustments are applied to mean, whereas the embeded single station sigma logic tree is applied to the total standard deviation. """ c1_dists = _compute_C1_term(C_ADJ, dists) phi_ss = _compute_phi_ss( C_ADJ, rup.mag, c1_dists, log_phi_ss, C_ADJ['mean_phi_ss'] ) mean_corr = np.exp(mean) * C_ADJ['k_adj'] * \ _compute_small_mag_correction_term(C_ADJ, rup.mag, dists) mean_corr = np.log(mean_corr) std_corr = _get_corr_stddevs(COEFFS[imt], tau_ss, stddev_types, len(sites.vs30), phi_ss, NL, tau_value) stddevs = np.array(std_corr) return mean_corr, stddevs
python
def _apply_adjustments(COEFFS, C_ADJ, tau_ss, mean, stddevs, sites, rup, dists, imt, stddev_types, log_phi_ss, NL=None, tau_value=None): """ This method applies adjustments to the mean and standard deviation. The small-magnitude adjustments are applied to mean, whereas the embeded single station sigma logic tree is applied to the total standard deviation. """ c1_dists = _compute_C1_term(C_ADJ, dists) phi_ss = _compute_phi_ss( C_ADJ, rup.mag, c1_dists, log_phi_ss, C_ADJ['mean_phi_ss'] ) mean_corr = np.exp(mean) * C_ADJ['k_adj'] * \ _compute_small_mag_correction_term(C_ADJ, rup.mag, dists) mean_corr = np.log(mean_corr) std_corr = _get_corr_stddevs(COEFFS[imt], tau_ss, stddev_types, len(sites.vs30), phi_ss, NL, tau_value) stddevs = np.array(std_corr) return mean_corr, stddevs
[ "def", "_apply_adjustments", "(", "COEFFS", ",", "C_ADJ", ",", "tau_ss", ",", "mean", ",", "stddevs", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ",", "log_phi_ss", ",", "NL", "=", "None", ",", "tau_value", "=", "None", ")", ":", "c1_dists", "=", "_compute_C1_term", "(", "C_ADJ", ",", "dists", ")", "phi_ss", "=", "_compute_phi_ss", "(", "C_ADJ", ",", "rup", ".", "mag", ",", "c1_dists", ",", "log_phi_ss", ",", "C_ADJ", "[", "'mean_phi_ss'", "]", ")", "mean_corr", "=", "np", ".", "exp", "(", "mean", ")", "*", "C_ADJ", "[", "'k_adj'", "]", "*", "_compute_small_mag_correction_term", "(", "C_ADJ", ",", "rup", ".", "mag", ",", "dists", ")", "mean_corr", "=", "np", ".", "log", "(", "mean_corr", ")", "std_corr", "=", "_get_corr_stddevs", "(", "COEFFS", "[", "imt", "]", ",", "tau_ss", ",", "stddev_types", ",", "len", "(", "sites", ".", "vs30", ")", ",", "phi_ss", ",", "NL", ",", "tau_value", ")", "stddevs", "=", "np", ".", "array", "(", "std_corr", ")", "return", "mean_corr", ",", "stddevs" ]
This method applies adjustments to the mean and standard deviation. The small-magnitude adjustments are applied to mean, whereas the embeded single station sigma logic tree is applied to the total standard deviation.
[ "This", "method", "applies", "adjustments", "to", "the", "mean", "and", "standard", "deviation", ".", "The", "small", "-", "magnitude", "adjustments", "are", "applied", "to", "mean", "whereas", "the", "embeded", "single", "station", "sigma", "logic", "tree", "is", "applied", "to", "the", "total", "standard", "deviation", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/utils_swiss_gmpe.py#L102-L125
79
gem/oq-engine
openquake/commonlib/source.py
CompositionInfo.get_info
def get_info(self, sm_id): """ Extract a CompositionInfo instance containing the single model of index `sm_id`. """ sm = self.source_models[sm_id] num_samples = sm.samples if self.num_samples else 0 return self.__class__( self.gsim_lt, self.seed, num_samples, [sm], self.tot_weight)
python
def get_info(self, sm_id): """ Extract a CompositionInfo instance containing the single model of index `sm_id`. """ sm = self.source_models[sm_id] num_samples = sm.samples if self.num_samples else 0 return self.__class__( self.gsim_lt, self.seed, num_samples, [sm], self.tot_weight)
[ "def", "get_info", "(", "self", ",", "sm_id", ")", ":", "sm", "=", "self", ".", "source_models", "[", "sm_id", "]", "num_samples", "=", "sm", ".", "samples", "if", "self", ".", "num_samples", "else", "0", "return", "self", ".", "__class__", "(", "self", ".", "gsim_lt", ",", "self", ".", "seed", ",", "num_samples", ",", "[", "sm", "]", ",", "self", ".", "tot_weight", ")" ]
Extract a CompositionInfo instance containing the single model of index `sm_id`.
[ "Extract", "a", "CompositionInfo", "instance", "containing", "the", "single", "model", "of", "index", "sm_id", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L142-L150
80
gem/oq-engine
openquake/commonlib/source.py
CompositionInfo.get_source_model
def get_source_model(self, src_group_id): """ Return the source model for the given src_group_id """ for smodel in self.source_models: for src_group in smodel.src_groups: if src_group.id == src_group_id: return smodel
python
def get_source_model(self, src_group_id): """ Return the source model for the given src_group_id """ for smodel in self.source_models: for src_group in smodel.src_groups: if src_group.id == src_group_id: return smodel
[ "def", "get_source_model", "(", "self", ",", "src_group_id", ")", ":", "for", "smodel", "in", "self", ".", "source_models", ":", "for", "src_group", "in", "smodel", ".", "src_groups", ":", "if", "src_group", ".", "id", "==", "src_group_id", ":", "return", "smodel" ]
Return the source model for the given src_group_id
[ "Return", "the", "source", "model", "for", "the", "given", "src_group_id" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L275-L282
81
gem/oq-engine
openquake/commonlib/source.py
CompositeSourceModel.get_model
def get_model(self, sm_id): """ Extract a CompositeSourceModel instance containing the single model of index `sm_id`. """ sm = self.source_models[sm_id] if self.source_model_lt.num_samples: self.source_model_lt.num_samples = sm.samples new = self.__class__(self.gsim_lt, self.source_model_lt, [sm], self.optimize_same_id) new.sm_id = sm_id return new
python
def get_model(self, sm_id): """ Extract a CompositeSourceModel instance containing the single model of index `sm_id`. """ sm = self.source_models[sm_id] if self.source_model_lt.num_samples: self.source_model_lt.num_samples = sm.samples new = self.__class__(self.gsim_lt, self.source_model_lt, [sm], self.optimize_same_id) new.sm_id = sm_id return new
[ "def", "get_model", "(", "self", ",", "sm_id", ")", ":", "sm", "=", "self", ".", "source_models", "[", "sm_id", "]", "if", "self", ".", "source_model_lt", ".", "num_samples", ":", "self", ".", "source_model_lt", ".", "num_samples", "=", "sm", ".", "samples", "new", "=", "self", ".", "__class__", "(", "self", ".", "gsim_lt", ",", "self", ".", "source_model_lt", ",", "[", "sm", "]", ",", "self", ".", "optimize_same_id", ")", "new", ".", "sm_id", "=", "sm_id", "return", "new" ]
Extract a CompositeSourceModel instance containing the single model of index `sm_id`.
[ "Extract", "a", "CompositeSourceModel", "instance", "containing", "the", "single", "model", "of", "index", "sm_id", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L381-L392
82
gem/oq-engine
openquake/commonlib/source.py
CompositeSourceModel.new
def new(self, sources_by_grp): """ Generate a new CompositeSourceModel from the given dictionary. :param sources_by_group: a dictionary grp_id -> sources :returns: a new CompositeSourceModel instance """ source_models = [] for sm in self.source_models: src_groups = [] for src_group in sm.src_groups: sg = copy.copy(src_group) sg.sources = sorted(sources_by_grp.get(sg.id, []), key=operator.attrgetter('id')) src_groups.append(sg) newsm = logictree.LtSourceModel( sm.names, sm.weight, sm.path, src_groups, sm.num_gsim_paths, sm.ordinal, sm.samples) source_models.append(newsm) new = self.__class__(self.gsim_lt, self.source_model_lt, source_models, self.optimize_same_id) new.info.update_eff_ruptures(new.get_num_ruptures()) new.info.tot_weight = new.get_weight() return new
python
def new(self, sources_by_grp): """ Generate a new CompositeSourceModel from the given dictionary. :param sources_by_group: a dictionary grp_id -> sources :returns: a new CompositeSourceModel instance """ source_models = [] for sm in self.source_models: src_groups = [] for src_group in sm.src_groups: sg = copy.copy(src_group) sg.sources = sorted(sources_by_grp.get(sg.id, []), key=operator.attrgetter('id')) src_groups.append(sg) newsm = logictree.LtSourceModel( sm.names, sm.weight, sm.path, src_groups, sm.num_gsim_paths, sm.ordinal, sm.samples) source_models.append(newsm) new = self.__class__(self.gsim_lt, self.source_model_lt, source_models, self.optimize_same_id) new.info.update_eff_ruptures(new.get_num_ruptures()) new.info.tot_weight = new.get_weight() return new
[ "def", "new", "(", "self", ",", "sources_by_grp", ")", ":", "source_models", "=", "[", "]", "for", "sm", "in", "self", ".", "source_models", ":", "src_groups", "=", "[", "]", "for", "src_group", "in", "sm", ".", "src_groups", ":", "sg", "=", "copy", ".", "copy", "(", "src_group", ")", "sg", ".", "sources", "=", "sorted", "(", "sources_by_grp", ".", "get", "(", "sg", ".", "id", ",", "[", "]", ")", ",", "key", "=", "operator", ".", "attrgetter", "(", "'id'", ")", ")", "src_groups", ".", "append", "(", "sg", ")", "newsm", "=", "logictree", ".", "LtSourceModel", "(", "sm", ".", "names", ",", "sm", ".", "weight", ",", "sm", ".", "path", ",", "src_groups", ",", "sm", ".", "num_gsim_paths", ",", "sm", ".", "ordinal", ",", "sm", ".", "samples", ")", "source_models", ".", "append", "(", "newsm", ")", "new", "=", "self", ".", "__class__", "(", "self", ".", "gsim_lt", ",", "self", ".", "source_model_lt", ",", "source_models", ",", "self", ".", "optimize_same_id", ")", "new", ".", "info", ".", "update_eff_ruptures", "(", "new", ".", "get_num_ruptures", "(", ")", ")", "new", ".", "info", ".", "tot_weight", "=", "new", ".", "get_weight", "(", ")", "return", "new" ]
Generate a new CompositeSourceModel from the given dictionary. :param sources_by_group: a dictionary grp_id -> sources :returns: a new CompositeSourceModel instance
[ "Generate", "a", "new", "CompositeSourceModel", "from", "the", "given", "dictionary", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L394-L417
83
gem/oq-engine
openquake/commonlib/source.py
CompositeSourceModel.check_dupl_sources
def check_dupl_sources(self): # used in print_csm_info """ Extracts duplicated sources, i.e. sources with the same source_id in different source groups. Raise an exception if there are sources with the same ID which are not duplicated. :returns: a list of list of sources, ordered by source_id """ dd = collections.defaultdict(list) for src_group in self.src_groups: for src in src_group: try: srcid = src.source_id except AttributeError: # src is a Node object srcid = src['id'] dd[srcid].append(src) dupl = [] for srcid, srcs in sorted(dd.items()): if len(srcs) > 1: _assert_equal_sources(srcs) dupl.append(srcs) return dupl
python
def check_dupl_sources(self): # used in print_csm_info """ Extracts duplicated sources, i.e. sources with the same source_id in different source groups. Raise an exception if there are sources with the same ID which are not duplicated. :returns: a list of list of sources, ordered by source_id """ dd = collections.defaultdict(list) for src_group in self.src_groups: for src in src_group: try: srcid = src.source_id except AttributeError: # src is a Node object srcid = src['id'] dd[srcid].append(src) dupl = [] for srcid, srcs in sorted(dd.items()): if len(srcs) > 1: _assert_equal_sources(srcs) dupl.append(srcs) return dupl
[ "def", "check_dupl_sources", "(", "self", ")", ":", "# used in print_csm_info", "dd", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "src_group", "in", "self", ".", "src_groups", ":", "for", "src", "in", "src_group", ":", "try", ":", "srcid", "=", "src", ".", "source_id", "except", "AttributeError", ":", "# src is a Node object", "srcid", "=", "src", "[", "'id'", "]", "dd", "[", "srcid", "]", ".", "append", "(", "src", ")", "dupl", "=", "[", "]", "for", "srcid", ",", "srcs", "in", "sorted", "(", "dd", ".", "items", "(", ")", ")", ":", "if", "len", "(", "srcs", ")", ">", "1", ":", "_assert_equal_sources", "(", "srcs", ")", "dupl", ".", "append", "(", "srcs", ")", "return", "dupl" ]
Extracts duplicated sources, i.e. sources with the same source_id in different source groups. Raise an exception if there are sources with the same ID which are not duplicated. :returns: a list of list of sources, ordered by source_id
[ "Extracts", "duplicated", "sources", "i", ".", "e", ".", "sources", "with", "the", "same", "source_id", "in", "different", "source", "groups", ".", "Raise", "an", "exception", "if", "there", "are", "sources", "with", "the", "same", "ID", "which", "are", "not", "duplicated", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L443-L464
84
gem/oq-engine
openquake/commonlib/source.py
CompositeSourceModel.get_sources
def get_sources(self, kind='all'): """ Extract the sources contained in the source models by optionally filtering and splitting them, depending on the passed parameter. """ assert kind in ('all', 'indep', 'mutex'), kind sources = [] for sm in self.source_models: for src_group in sm.src_groups: if kind in ('all', src_group.src_interdep): for src in src_group: if sm.samples > 1: src.samples = sm.samples sources.append(src) return sources
python
def get_sources(self, kind='all'): """ Extract the sources contained in the source models by optionally filtering and splitting them, depending on the passed parameter. """ assert kind in ('all', 'indep', 'mutex'), kind sources = [] for sm in self.source_models: for src_group in sm.src_groups: if kind in ('all', src_group.src_interdep): for src in src_group: if sm.samples > 1: src.samples = sm.samples sources.append(src) return sources
[ "def", "get_sources", "(", "self", ",", "kind", "=", "'all'", ")", ":", "assert", "kind", "in", "(", "'all'", ",", "'indep'", ",", "'mutex'", ")", ",", "kind", "sources", "=", "[", "]", "for", "sm", "in", "self", ".", "source_models", ":", "for", "src_group", "in", "sm", ".", "src_groups", ":", "if", "kind", "in", "(", "'all'", ",", "src_group", ".", "src_interdep", ")", ":", "for", "src", "in", "src_group", ":", "if", "sm", ".", "samples", ">", "1", ":", "src", ".", "samples", "=", "sm", ".", "samples", "sources", ".", "append", "(", "src", ")", "return", "sources" ]
Extract the sources contained in the source models by optionally filtering and splitting them, depending on the passed parameter.
[ "Extract", "the", "sources", "contained", "in", "the", "source", "models", "by", "optionally", "filtering", "and", "splitting", "them", "depending", "on", "the", "passed", "parameter", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L466-L480
85
gem/oq-engine
openquake/commonlib/source.py
CompositeSourceModel.init_serials
def init_serials(self, ses_seed): """ Generate unique seeds for each rupture with numpy.arange. This should be called only in event based calculators """ sources = self.get_sources() serial = ses_seed for src in sources: nr = src.num_ruptures src.serial = serial serial += nr
python
def init_serials(self, ses_seed): """ Generate unique seeds for each rupture with numpy.arange. This should be called only in event based calculators """ sources = self.get_sources() serial = ses_seed for src in sources: nr = src.num_ruptures src.serial = serial serial += nr
[ "def", "init_serials", "(", "self", ",", "ses_seed", ")", ":", "sources", "=", "self", ".", "get_sources", "(", ")", "serial", "=", "ses_seed", "for", "src", "in", "sources", ":", "nr", "=", "src", ".", "num_ruptures", "src", ".", "serial", "=", "serial", "serial", "+=", "nr" ]
Generate unique seeds for each rupture with numpy.arange. This should be called only in event based calculators
[ "Generate", "unique", "seeds", "for", "each", "rupture", "with", "numpy", ".", "arange", ".", "This", "should", "be", "called", "only", "in", "event", "based", "calculators" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L525-L535
86
gem/oq-engine
openquake/commonlib/source.py
CompositeSourceModel.get_maxweight
def get_maxweight(self, weight, concurrent_tasks, minweight=MINWEIGHT): """ Return an appropriate maxweight for use in the block_splitter """ totweight = self.get_weight(weight) ct = concurrent_tasks or 1 mw = math.ceil(totweight / ct) return max(mw, minweight)
python
def get_maxweight(self, weight, concurrent_tasks, minweight=MINWEIGHT): """ Return an appropriate maxweight for use in the block_splitter """ totweight = self.get_weight(weight) ct = concurrent_tasks or 1 mw = math.ceil(totweight / ct) return max(mw, minweight)
[ "def", "get_maxweight", "(", "self", ",", "weight", ",", "concurrent_tasks", ",", "minweight", "=", "MINWEIGHT", ")", ":", "totweight", "=", "self", ".", "get_weight", "(", "weight", ")", "ct", "=", "concurrent_tasks", "or", "1", "mw", "=", "math", ".", "ceil", "(", "totweight", "/", "ct", ")", "return", "max", "(", "mw", ",", "minweight", ")" ]
Return an appropriate maxweight for use in the block_splitter
[ "Return", "an", "appropriate", "maxweight", "for", "use", "in", "the", "block_splitter" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L537-L544
87
gem/oq-engine
openquake/hmtk/parsers/faults/fault_yaml_parser.py
weight_list_to_tuple
def weight_list_to_tuple(data, attr_name): ''' Converts a list of values and corresponding weights to a tuple of values ''' if len(data['Value']) != len(data['Weight']): raise ValueError('Number of weights do not correspond to number of ' 'attributes in %s' % attr_name) weight = np.array(data['Weight']) if fabs(np.sum(weight) - 1.) > 1E-7: raise ValueError('Weights do not sum to 1.0 in %s' % attr_name) data_tuple = [] for iloc, value in enumerate(data['Value']): data_tuple.append((value, weight[iloc])) return data_tuple
python
def weight_list_to_tuple(data, attr_name): ''' Converts a list of values and corresponding weights to a tuple of values ''' if len(data['Value']) != len(data['Weight']): raise ValueError('Number of weights do not correspond to number of ' 'attributes in %s' % attr_name) weight = np.array(data['Weight']) if fabs(np.sum(weight) - 1.) > 1E-7: raise ValueError('Weights do not sum to 1.0 in %s' % attr_name) data_tuple = [] for iloc, value in enumerate(data['Value']): data_tuple.append((value, weight[iloc])) return data_tuple
[ "def", "weight_list_to_tuple", "(", "data", ",", "attr_name", ")", ":", "if", "len", "(", "data", "[", "'Value'", "]", ")", "!=", "len", "(", "data", "[", "'Weight'", "]", ")", ":", "raise", "ValueError", "(", "'Number of weights do not correspond to number of '", "'attributes in %s'", "%", "attr_name", ")", "weight", "=", "np", ".", "array", "(", "data", "[", "'Weight'", "]", ")", "if", "fabs", "(", "np", ".", "sum", "(", "weight", ")", "-", "1.", ")", ">", "1E-7", ":", "raise", "ValueError", "(", "'Weights do not sum to 1.0 in %s'", "%", "attr_name", ")", "data_tuple", "=", "[", "]", "for", "iloc", ",", "value", "in", "enumerate", "(", "data", "[", "'Value'", "]", ")", ":", "data_tuple", ".", "append", "(", "(", "value", ",", "weight", "[", "iloc", "]", ")", ")", "return", "data_tuple" ]
Converts a list of values and corresponding weights to a tuple of values
[ "Converts", "a", "list", "of", "values", "and", "corresponding", "weights", "to", "a", "tuple", "of", "values" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L71-L86
88
gem/oq-engine
openquake/hmtk/parsers/faults/fault_yaml_parser.py
parse_tect_region_dict_to_tuples
def parse_tect_region_dict_to_tuples(region_dict): ''' Parses the tectonic regionalisation dictionary attributes to tuples ''' output_region_dict = [] tuple_keys = ['Displacement_Length_Ratio', 'Shear_Modulus'] # Convert MSR string name to openquake.hazardlib.scalerel object for region in region_dict: for val_name in tuple_keys: region[val_name] = weight_list_to_tuple(region[val_name], val_name) # MSR works differently - so call get_scaling_relation_tuple region['Magnitude_Scaling_Relation'] = weight_list_to_tuple( region['Magnitude_Scaling_Relation'], 'Magnitude Scaling Relation') output_region_dict.append(region) return output_region_dict
python
def parse_tect_region_dict_to_tuples(region_dict): ''' Parses the tectonic regionalisation dictionary attributes to tuples ''' output_region_dict = [] tuple_keys = ['Displacement_Length_Ratio', 'Shear_Modulus'] # Convert MSR string name to openquake.hazardlib.scalerel object for region in region_dict: for val_name in tuple_keys: region[val_name] = weight_list_to_tuple(region[val_name], val_name) # MSR works differently - so call get_scaling_relation_tuple region['Magnitude_Scaling_Relation'] = weight_list_to_tuple( region['Magnitude_Scaling_Relation'], 'Magnitude Scaling Relation') output_region_dict.append(region) return output_region_dict
[ "def", "parse_tect_region_dict_to_tuples", "(", "region_dict", ")", ":", "output_region_dict", "=", "[", "]", "tuple_keys", "=", "[", "'Displacement_Length_Ratio'", ",", "'Shear_Modulus'", "]", "# Convert MSR string name to openquake.hazardlib.scalerel object", "for", "region", "in", "region_dict", ":", "for", "val_name", "in", "tuple_keys", ":", "region", "[", "val_name", "]", "=", "weight_list_to_tuple", "(", "region", "[", "val_name", "]", ",", "val_name", ")", "# MSR works differently - so call get_scaling_relation_tuple", "region", "[", "'Magnitude_Scaling_Relation'", "]", "=", "weight_list_to_tuple", "(", "region", "[", "'Magnitude_Scaling_Relation'", "]", ",", "'Magnitude Scaling Relation'", ")", "output_region_dict", ".", "append", "(", "region", ")", "return", "output_region_dict" ]
Parses the tectonic regionalisation dictionary attributes to tuples
[ "Parses", "the", "tectonic", "regionalisation", "dictionary", "attributes", "to", "tuples" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L89-L105
89
gem/oq-engine
openquake/hmtk/parsers/faults/fault_yaml_parser.py
get_scaling_relation_tuple
def get_scaling_relation_tuple(msr_dict): ''' For a dictionary of scaling relation values convert string list to object list and then to tuple ''' # Convert MSR string name to openquake.hazardlib.scalerel object for iloc, value in enumerate(msr_dict['Value']): if not value in SCALE_REL_MAP.keys(): raise ValueError('Scaling relation %s not supported!' % value) msr_dict['Value'][iloc] = SCALE_REL_MAP[value]() return weight_list_to_tuple(msr_dict, 'Magnitude Scaling Relation')
python
def get_scaling_relation_tuple(msr_dict): ''' For a dictionary of scaling relation values convert string list to object list and then to tuple ''' # Convert MSR string name to openquake.hazardlib.scalerel object for iloc, value in enumerate(msr_dict['Value']): if not value in SCALE_REL_MAP.keys(): raise ValueError('Scaling relation %s not supported!' % value) msr_dict['Value'][iloc] = SCALE_REL_MAP[value]() return weight_list_to_tuple(msr_dict, 'Magnitude Scaling Relation')
[ "def", "get_scaling_relation_tuple", "(", "msr_dict", ")", ":", "# Convert MSR string name to openquake.hazardlib.scalerel object", "for", "iloc", ",", "value", "in", "enumerate", "(", "msr_dict", "[", "'Value'", "]", ")", ":", "if", "not", "value", "in", "SCALE_REL_MAP", ".", "keys", "(", ")", ":", "raise", "ValueError", "(", "'Scaling relation %s not supported!'", "%", "value", ")", "msr_dict", "[", "'Value'", "]", "[", "iloc", "]", "=", "SCALE_REL_MAP", "[", "value", "]", "(", ")", "return", "weight_list_to_tuple", "(", "msr_dict", ",", "'Magnitude Scaling Relation'", ")" ]
For a dictionary of scaling relation values convert string list to object list and then to tuple
[ "For", "a", "dictionary", "of", "scaling", "relation", "values", "convert", "string", "list", "to", "object", "list", "and", "then", "to", "tuple" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L108-L120
90
gem/oq-engine
openquake/hmtk/parsers/faults/fault_yaml_parser.py
FaultYmltoSource.read_file
def read_file(self, mesh_spacing=1.0): ''' Reads the file and returns an instance of the FaultSource class. :param float mesh_spacing: Fault mesh spacing (km) ''' # Process the tectonic regionalisation tectonic_reg = self.process_tectonic_regionalisation() model = mtkActiveFaultModel(self.data['Fault_Model_ID'], self.data['Fault_Model_Name']) for fault in self.data['Fault_Model']: fault_geometry = self.read_fault_geometry(fault['Fault_Geometry'], mesh_spacing) if fault['Shear_Modulus']: fault['Shear_Modulus'] = weight_list_to_tuple( fault['Shear_Modulus'], '%s Shear Modulus' % fault['ID']) if fault['Displacement_Length_Ratio']: fault['Displacement_Length_Ratio'] = weight_list_to_tuple( fault['Displacement_Length_Ratio'], '%s Displacement to Length Ratio' % fault['ID']) fault_source = mtkActiveFault( fault['ID'], fault['Fault_Name'], fault_geometry, weight_list_to_tuple(fault['Slip'], '%s - Slip' % fault['ID']), float(fault['Rake']), fault['Tectonic_Region'], float(fault['Aseismic']), weight_list_to_tuple( fault['Scaling_Relation_Sigma'], '%s Scaling_Relation_Sigma' % fault['ID']), neotectonic_fault=None, scale_rel=get_scaling_relation_tuple( fault['Magnitude_Scaling_Relation']), aspect_ratio=fault['Aspect_Ratio'], shear_modulus=fault['Shear_Modulus'], disp_length_ratio=fault['Displacement_Length_Ratio']) if tectonic_reg: fault_source.get_tectonic_regionalisation( tectonic_reg, fault['Tectonic_Region']) assert isinstance(fault['MFD_Model'], list) fault_source.generate_config_set(fault['MFD_Model']) model.faults.append(fault_source) return model, tectonic_reg
python
def read_file(self, mesh_spacing=1.0): ''' Reads the file and returns an instance of the FaultSource class. :param float mesh_spacing: Fault mesh spacing (km) ''' # Process the tectonic regionalisation tectonic_reg = self.process_tectonic_regionalisation() model = mtkActiveFaultModel(self.data['Fault_Model_ID'], self.data['Fault_Model_Name']) for fault in self.data['Fault_Model']: fault_geometry = self.read_fault_geometry(fault['Fault_Geometry'], mesh_spacing) if fault['Shear_Modulus']: fault['Shear_Modulus'] = weight_list_to_tuple( fault['Shear_Modulus'], '%s Shear Modulus' % fault['ID']) if fault['Displacement_Length_Ratio']: fault['Displacement_Length_Ratio'] = weight_list_to_tuple( fault['Displacement_Length_Ratio'], '%s Displacement to Length Ratio' % fault['ID']) fault_source = mtkActiveFault( fault['ID'], fault['Fault_Name'], fault_geometry, weight_list_to_tuple(fault['Slip'], '%s - Slip' % fault['ID']), float(fault['Rake']), fault['Tectonic_Region'], float(fault['Aseismic']), weight_list_to_tuple( fault['Scaling_Relation_Sigma'], '%s Scaling_Relation_Sigma' % fault['ID']), neotectonic_fault=None, scale_rel=get_scaling_relation_tuple( fault['Magnitude_Scaling_Relation']), aspect_ratio=fault['Aspect_Ratio'], shear_modulus=fault['Shear_Modulus'], disp_length_ratio=fault['Displacement_Length_Ratio']) if tectonic_reg: fault_source.get_tectonic_regionalisation( tectonic_reg, fault['Tectonic_Region']) assert isinstance(fault['MFD_Model'], list) fault_source.generate_config_set(fault['MFD_Model']) model.faults.append(fault_source) return model, tectonic_reg
[ "def", "read_file", "(", "self", ",", "mesh_spacing", "=", "1.0", ")", ":", "# Process the tectonic regionalisation", "tectonic_reg", "=", "self", ".", "process_tectonic_regionalisation", "(", ")", "model", "=", "mtkActiveFaultModel", "(", "self", ".", "data", "[", "'Fault_Model_ID'", "]", ",", "self", ".", "data", "[", "'Fault_Model_Name'", "]", ")", "for", "fault", "in", "self", ".", "data", "[", "'Fault_Model'", "]", ":", "fault_geometry", "=", "self", ".", "read_fault_geometry", "(", "fault", "[", "'Fault_Geometry'", "]", ",", "mesh_spacing", ")", "if", "fault", "[", "'Shear_Modulus'", "]", ":", "fault", "[", "'Shear_Modulus'", "]", "=", "weight_list_to_tuple", "(", "fault", "[", "'Shear_Modulus'", "]", ",", "'%s Shear Modulus'", "%", "fault", "[", "'ID'", "]", ")", "if", "fault", "[", "'Displacement_Length_Ratio'", "]", ":", "fault", "[", "'Displacement_Length_Ratio'", "]", "=", "weight_list_to_tuple", "(", "fault", "[", "'Displacement_Length_Ratio'", "]", ",", "'%s Displacement to Length Ratio'", "%", "fault", "[", "'ID'", "]", ")", "fault_source", "=", "mtkActiveFault", "(", "fault", "[", "'ID'", "]", ",", "fault", "[", "'Fault_Name'", "]", ",", "fault_geometry", ",", "weight_list_to_tuple", "(", "fault", "[", "'Slip'", "]", ",", "'%s - Slip'", "%", "fault", "[", "'ID'", "]", ")", ",", "float", "(", "fault", "[", "'Rake'", "]", ")", ",", "fault", "[", "'Tectonic_Region'", "]", ",", "float", "(", "fault", "[", "'Aseismic'", "]", ")", ",", "weight_list_to_tuple", "(", "fault", "[", "'Scaling_Relation_Sigma'", "]", ",", "'%s Scaling_Relation_Sigma'", "%", "fault", "[", "'ID'", "]", ")", ",", "neotectonic_fault", "=", "None", ",", "scale_rel", "=", "get_scaling_relation_tuple", "(", "fault", "[", "'Magnitude_Scaling_Relation'", "]", ")", ",", "aspect_ratio", "=", "fault", "[", "'Aspect_Ratio'", "]", ",", "shear_modulus", "=", "fault", "[", "'Shear_Modulus'", "]", ",", "disp_length_ratio", "=", "fault", "[", "'Displacement_Length_Ratio'", "]", ")", "if", "tectonic_reg", ":", "fault_source", ".", "get_tectonic_regionalisation", "(", "tectonic_reg", ",", "fault", "[", "'Tectonic_Region'", "]", ")", "assert", "isinstance", "(", "fault", "[", "'MFD_Model'", "]", ",", "list", ")", "fault_source", ".", "generate_config_set", "(", "fault", "[", "'MFD_Model'", "]", ")", "model", ".", "faults", ".", "append", "(", "fault_source", ")", "return", "model", ",", "tectonic_reg" ]
Reads the file and returns an instance of the FaultSource class. :param float mesh_spacing: Fault mesh spacing (km)
[ "Reads", "the", "file", "and", "returns", "an", "instance", "of", "the", "FaultSource", "class", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L138-L189
91
gem/oq-engine
openquake/hmtk/parsers/faults/fault_yaml_parser.py
FaultYmltoSource.process_tectonic_regionalisation
def process_tectonic_regionalisation(self): ''' Processes the tectonic regionalisation from the yaml file ''' if 'tectonic_regionalisation' in self.data.keys(): tectonic_reg = TectonicRegionalisation() tectonic_reg.populate_regions( parse_tect_region_dict_to_tuples( self.data['tectonic_regionalisation'])) else: tectonic_reg = None return tectonic_reg
python
def process_tectonic_regionalisation(self): ''' Processes the tectonic regionalisation from the yaml file ''' if 'tectonic_regionalisation' in self.data.keys(): tectonic_reg = TectonicRegionalisation() tectonic_reg.populate_regions( parse_tect_region_dict_to_tuples( self.data['tectonic_regionalisation'])) else: tectonic_reg = None return tectonic_reg
[ "def", "process_tectonic_regionalisation", "(", "self", ")", ":", "if", "'tectonic_regionalisation'", "in", "self", ".", "data", ".", "keys", "(", ")", ":", "tectonic_reg", "=", "TectonicRegionalisation", "(", ")", "tectonic_reg", ".", "populate_regions", "(", "parse_tect_region_dict_to_tuples", "(", "self", ".", "data", "[", "'tectonic_regionalisation'", "]", ")", ")", "else", ":", "tectonic_reg", "=", "None", "return", "tectonic_reg" ]
Processes the tectonic regionalisation from the yaml file
[ "Processes", "the", "tectonic", "regionalisation", "from", "the", "yaml", "file" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L191-L203
92
gem/oq-engine
openquake/hmtk/parsers/faults/fault_yaml_parser.py
FaultYmltoSource.read_fault_geometry
def read_fault_geometry(self, geo_dict, mesh_spacing=1.0): ''' Creates the fault geometry from the parameters specified in the dictionary. :param dict geo_dict: Sub-dictionary of main fault dictionary containing only the geometry attributes :param float mesh_spacing: Fault mesh spacing (km) :returns: Instance of SimpleFaultGeometry or ComplexFaultGeometry, depending on typology ''' if geo_dict['Fault_Typology'] == 'Simple': # Simple fault geometry raw_trace = geo_dict['Fault_Trace'] trace = Line([Point(raw_trace[ival], raw_trace[ival + 1]) for ival in range(0, len(raw_trace), 2)]) geometry = SimpleFaultGeometry(trace, geo_dict['Dip'], geo_dict['Upper_Depth'], geo_dict['Lower_Depth'], mesh_spacing) elif geo_dict['Fault_Typology'] == 'Complex': # Complex Fault Typology trace = [] for raw_trace in geo_dict['Fault_Trace']: fault_edge = Line( [Point(raw_trace[ival], raw_trace[ival + 1], raw_trace[ival + 2]) for ival in range(0, len(raw_trace), 3)]) trace.append(fault_edge) geometry = ComplexFaultGeometry(trace, mesh_spacing) else: raise ValueError('Unrecognised or unsupported fault geometry!') return geometry
python
def read_fault_geometry(self, geo_dict, mesh_spacing=1.0): ''' Creates the fault geometry from the parameters specified in the dictionary. :param dict geo_dict: Sub-dictionary of main fault dictionary containing only the geometry attributes :param float mesh_spacing: Fault mesh spacing (km) :returns: Instance of SimpleFaultGeometry or ComplexFaultGeometry, depending on typology ''' if geo_dict['Fault_Typology'] == 'Simple': # Simple fault geometry raw_trace = geo_dict['Fault_Trace'] trace = Line([Point(raw_trace[ival], raw_trace[ival + 1]) for ival in range(0, len(raw_trace), 2)]) geometry = SimpleFaultGeometry(trace, geo_dict['Dip'], geo_dict['Upper_Depth'], geo_dict['Lower_Depth'], mesh_spacing) elif geo_dict['Fault_Typology'] == 'Complex': # Complex Fault Typology trace = [] for raw_trace in geo_dict['Fault_Trace']: fault_edge = Line( [Point(raw_trace[ival], raw_trace[ival + 1], raw_trace[ival + 2]) for ival in range(0, len(raw_trace), 3)]) trace.append(fault_edge) geometry = ComplexFaultGeometry(trace, mesh_spacing) else: raise ValueError('Unrecognised or unsupported fault geometry!') return geometry
[ "def", "read_fault_geometry", "(", "self", ",", "geo_dict", ",", "mesh_spacing", "=", "1.0", ")", ":", "if", "geo_dict", "[", "'Fault_Typology'", "]", "==", "'Simple'", ":", "# Simple fault geometry", "raw_trace", "=", "geo_dict", "[", "'Fault_Trace'", "]", "trace", "=", "Line", "(", "[", "Point", "(", "raw_trace", "[", "ival", "]", ",", "raw_trace", "[", "ival", "+", "1", "]", ")", "for", "ival", "in", "range", "(", "0", ",", "len", "(", "raw_trace", ")", ",", "2", ")", "]", ")", "geometry", "=", "SimpleFaultGeometry", "(", "trace", ",", "geo_dict", "[", "'Dip'", "]", ",", "geo_dict", "[", "'Upper_Depth'", "]", ",", "geo_dict", "[", "'Lower_Depth'", "]", ",", "mesh_spacing", ")", "elif", "geo_dict", "[", "'Fault_Typology'", "]", "==", "'Complex'", ":", "# Complex Fault Typology", "trace", "=", "[", "]", "for", "raw_trace", "in", "geo_dict", "[", "'Fault_Trace'", "]", ":", "fault_edge", "=", "Line", "(", "[", "Point", "(", "raw_trace", "[", "ival", "]", ",", "raw_trace", "[", "ival", "+", "1", "]", ",", "raw_trace", "[", "ival", "+", "2", "]", ")", "for", "ival", "in", "range", "(", "0", ",", "len", "(", "raw_trace", ")", ",", "3", ")", "]", ")", "trace", ".", "append", "(", "fault_edge", ")", "geometry", "=", "ComplexFaultGeometry", "(", "trace", ",", "mesh_spacing", ")", "else", ":", "raise", "ValueError", "(", "'Unrecognised or unsupported fault geometry!'", ")", "return", "geometry" ]
Creates the fault geometry from the parameters specified in the dictionary. :param dict geo_dict: Sub-dictionary of main fault dictionary containing only the geometry attributes :param float mesh_spacing: Fault mesh spacing (km) :returns: Instance of SimpleFaultGeometry or ComplexFaultGeometry, depending on typology
[ "Creates", "the", "fault", "geometry", "from", "the", "parameters", "specified", "in", "the", "dictionary", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L205-L242
93
gem/oq-engine
openquake/hazardlib/gsim/cauzzi_2014.py
CauzziEtAl2014._get_distance_scaling_term
def _get_distance_scaling_term(self, C, mag, rrup): """ Returns the distance scaling parameter """ return (C["r1"] + C["r2"] * mag) * np.log10(rrup + C["r3"])
python
def _get_distance_scaling_term(self, C, mag, rrup): """ Returns the distance scaling parameter """ return (C["r1"] + C["r2"] * mag) * np.log10(rrup + C["r3"])
[ "def", "_get_distance_scaling_term", "(", "self", ",", "C", ",", "mag", ",", "rrup", ")", ":", "return", "(", "C", "[", "\"r1\"", "]", "+", "C", "[", "\"r2\"", "]", "*", "mag", ")", "*", "np", ".", "log10", "(", "rrup", "+", "C", "[", "\"r3\"", "]", ")" ]
Returns the distance scaling parameter
[ "Returns", "the", "distance", "scaling", "parameter" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L132-L136
94
gem/oq-engine
openquake/hazardlib/gsim/cauzzi_2014.py
CauzziEtAl2014._get_style_of_faulting_term
def _get_style_of_faulting_term(self, C, rake): """ Returns the style of faulting term. Cauzzi et al. determind SOF from the plunge of the B-, T- and P-axes. For consistency with existing GMPEs the Wells & Coppersmith model is preferred """ if rake > -150.0 and rake <= -30.0: return C['fN'] elif rake > 30.0 and rake <= 150.0: return C['fR'] else: return C['fSS']
python
def _get_style_of_faulting_term(self, C, rake): """ Returns the style of faulting term. Cauzzi et al. determind SOF from the plunge of the B-, T- and P-axes. For consistency with existing GMPEs the Wells & Coppersmith model is preferred """ if rake > -150.0 and rake <= -30.0: return C['fN'] elif rake > 30.0 and rake <= 150.0: return C['fR'] else: return C['fSS']
[ "def", "_get_style_of_faulting_term", "(", "self", ",", "C", ",", "rake", ")", ":", "if", "rake", ">", "-", "150.0", "and", "rake", "<=", "-", "30.0", ":", "return", "C", "[", "'fN'", "]", "elif", "rake", ">", "30.0", "and", "rake", "<=", "150.0", ":", "return", "C", "[", "'fR'", "]", "else", ":", "return", "C", "[", "'fSS'", "]" ]
Returns the style of faulting term. Cauzzi et al. determind SOF from the plunge of the B-, T- and P-axes. For consistency with existing GMPEs the Wells & Coppersmith model is preferred
[ "Returns", "the", "style", "of", "faulting", "term", ".", "Cauzzi", "et", "al", ".", "determind", "SOF", "from", "the", "plunge", "of", "the", "B", "-", "T", "-", "and", "P", "-", "axes", ".", "For", "consistency", "with", "existing", "GMPEs", "the", "Wells", "&", "Coppersmith", "model", "is", "preferred" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L138-L149
95
gem/oq-engine
openquake/hazardlib/gsim/cauzzi_2014.py
CauzziEtAl2014Eurocode8._get_site_amplification_term
def _get_site_amplification_term(self, C, vs30): """ Returns the site amplification term on the basis of Eurocode 8 site class """ s_b, s_c, s_d = self._get_site_dummy_variables(vs30) return (C["sB"] * s_b) + (C["sC"] * s_c) + (C["sD"] * s_d)
python
def _get_site_amplification_term(self, C, vs30): """ Returns the site amplification term on the basis of Eurocode 8 site class """ s_b, s_c, s_d = self._get_site_dummy_variables(vs30) return (C["sB"] * s_b) + (C["sC"] * s_c) + (C["sD"] * s_d)
[ "def", "_get_site_amplification_term", "(", "self", ",", "C", ",", "vs30", ")", ":", "s_b", ",", "s_c", ",", "s_d", "=", "self", ".", "_get_site_dummy_variables", "(", "vs30", ")", "return", "(", "C", "[", "\"sB\"", "]", "*", "s_b", ")", "+", "(", "C", "[", "\"sC\"", "]", "*", "s_c", ")", "+", "(", "C", "[", "\"sD\"", "]", "*", "s_d", ")" ]
Returns the site amplification term on the basis of Eurocode 8 site class
[ "Returns", "the", "site", "amplification", "term", "on", "the", "basis", "of", "Eurocode", "8", "site", "class" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L471-L477
96
gem/oq-engine
openquake/hazardlib/gsim/cauzzi_2014.py
CauzziEtAl2014Eurocode8._get_site_dummy_variables
def _get_site_dummy_variables(self, vs30): """ Returns the Eurocode 8 site class dummy variable """ s_b = np.zeros_like(vs30) s_c = np.zeros_like(vs30) s_d = np.zeros_like(vs30) s_b[np.logical_and(vs30 >= 360., vs30 < 800.)] = 1.0 s_c[np.logical_and(vs30 >= 180., vs30 < 360.)] = 1.0 s_d[vs30 < 180] = 1.0 return s_b, s_c, s_d
python
def _get_site_dummy_variables(self, vs30): """ Returns the Eurocode 8 site class dummy variable """ s_b = np.zeros_like(vs30) s_c = np.zeros_like(vs30) s_d = np.zeros_like(vs30) s_b[np.logical_and(vs30 >= 360., vs30 < 800.)] = 1.0 s_c[np.logical_and(vs30 >= 180., vs30 < 360.)] = 1.0 s_d[vs30 < 180] = 1.0 return s_b, s_c, s_d
[ "def", "_get_site_dummy_variables", "(", "self", ",", "vs30", ")", ":", "s_b", "=", "np", ".", "zeros_like", "(", "vs30", ")", "s_c", "=", "np", ".", "zeros_like", "(", "vs30", ")", "s_d", "=", "np", ".", "zeros_like", "(", "vs30", ")", "s_b", "[", "np", ".", "logical_and", "(", "vs30", ">=", "360.", ",", "vs30", "<", "800.", ")", "]", "=", "1.0", "s_c", "[", "np", ".", "logical_and", "(", "vs30", ">=", "180.", ",", "vs30", "<", "360.", ")", "]", "=", "1.0", "s_d", "[", "vs30", "<", "180", "]", "=", "1.0", "return", "s_b", ",", "s_c", ",", "s_d" ]
Returns the Eurocode 8 site class dummy variable
[ "Returns", "the", "Eurocode", "8", "site", "class", "dummy", "variable" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L479-L489
97
gem/oq-engine
openquake/hmtk/faults/fault_models.py
RecurrenceBranch.get_recurrence
def get_recurrence(self, config): ''' Calculates the recurrence model for the given settings as an instance of the openquake.hmtk.models.IncrementalMFD :param dict config: Configuration settings of the magnitude frequency distribution. ''' model = MFD_MAP[config['Model_Name']]() model.setUp(config) model.get_mmax(config, self.msr, self.rake, self.area) model.mmax = model.mmax + (self.msr_sigma * model.mmax_sigma) # As the Anderson & Luco arbitrary model requires the input of the # displacement to length ratio if 'AndersonLucoAreaMmax' in config['Model_Name']: if not self.disp_length_ratio: # If not defined then default to 1.25E-5 self.disp_length_ratio = 1.25E-5 min_mag, bin_width, occur_rates = model.get_mfd( self.slip, self.area, self.shear_modulus, self.disp_length_ratio) else: min_mag, bin_width, occur_rates = model.get_mfd(self.slip, self.area, self.shear_modulus) self.recurrence = IncrementalMFD(min_mag, bin_width, occur_rates) self.magnitudes = min_mag + np.cumsum( bin_width * np.ones(len(occur_rates), dtype=float)) - bin_width self.max_mag = np.max(self.magnitudes)
python
def get_recurrence(self, config): ''' Calculates the recurrence model for the given settings as an instance of the openquake.hmtk.models.IncrementalMFD :param dict config: Configuration settings of the magnitude frequency distribution. ''' model = MFD_MAP[config['Model_Name']]() model.setUp(config) model.get_mmax(config, self.msr, self.rake, self.area) model.mmax = model.mmax + (self.msr_sigma * model.mmax_sigma) # As the Anderson & Luco arbitrary model requires the input of the # displacement to length ratio if 'AndersonLucoAreaMmax' in config['Model_Name']: if not self.disp_length_ratio: # If not defined then default to 1.25E-5 self.disp_length_ratio = 1.25E-5 min_mag, bin_width, occur_rates = model.get_mfd( self.slip, self.area, self.shear_modulus, self.disp_length_ratio) else: min_mag, bin_width, occur_rates = model.get_mfd(self.slip, self.area, self.shear_modulus) self.recurrence = IncrementalMFD(min_mag, bin_width, occur_rates) self.magnitudes = min_mag + np.cumsum( bin_width * np.ones(len(occur_rates), dtype=float)) - bin_width self.max_mag = np.max(self.magnitudes)
[ "def", "get_recurrence", "(", "self", ",", "config", ")", ":", "model", "=", "MFD_MAP", "[", "config", "[", "'Model_Name'", "]", "]", "(", ")", "model", ".", "setUp", "(", "config", ")", "model", ".", "get_mmax", "(", "config", ",", "self", ".", "msr", ",", "self", ".", "rake", ",", "self", ".", "area", ")", "model", ".", "mmax", "=", "model", ".", "mmax", "+", "(", "self", ".", "msr_sigma", "*", "model", ".", "mmax_sigma", ")", "# As the Anderson & Luco arbitrary model requires the input of the", "# displacement to length ratio", "if", "'AndersonLucoAreaMmax'", "in", "config", "[", "'Model_Name'", "]", ":", "if", "not", "self", ".", "disp_length_ratio", ":", "# If not defined then default to 1.25E-5", "self", ".", "disp_length_ratio", "=", "1.25E-5", "min_mag", ",", "bin_width", ",", "occur_rates", "=", "model", ".", "get_mfd", "(", "self", ".", "slip", ",", "self", ".", "area", ",", "self", ".", "shear_modulus", ",", "self", ".", "disp_length_ratio", ")", "else", ":", "min_mag", ",", "bin_width", ",", "occur_rates", "=", "model", ".", "get_mfd", "(", "self", ".", "slip", ",", "self", ".", "area", ",", "self", ".", "shear_modulus", ")", "self", ".", "recurrence", "=", "IncrementalMFD", "(", "min_mag", ",", "bin_width", ",", "occur_rates", ")", "self", ".", "magnitudes", "=", "min_mag", "+", "np", ".", "cumsum", "(", "bin_width", "*", "np", ".", "ones", "(", "len", "(", "occur_rates", ")", ",", "dtype", "=", "float", ")", ")", "-", "bin_width", "self", ".", "max_mag", "=", "np", ".", "max", "(", "self", ".", "magnitudes", ")" ]
Calculates the recurrence model for the given settings as an instance of the openquake.hmtk.models.IncrementalMFD :param dict config: Configuration settings of the magnitude frequency distribution.
[ "Calculates", "the", "recurrence", "model", "for", "the", "given", "settings", "as", "an", "instance", "of", "the", "openquake", ".", "hmtk", ".", "models", ".", "IncrementalMFD" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L145-L177
98
gem/oq-engine
openquake/hmtk/faults/fault_models.py
mtkActiveFault.get_tectonic_regionalisation
def get_tectonic_regionalisation(self, regionalisation, region_type=None): ''' Defines the tectonic region and updates the shear modulus, magnitude scaling relation and displacement to length ratio using the regional values, if not previously defined for the fault :param regionalistion: Instance of the :class: openquake.hmtk.faults.tectonic_regionalisaion.TectonicRegionalisation :param str region_type: Name of the region type - if not in regionalisation an error will be raised ''' if region_type: self.trt = region_type if not self.trt in regionalisation.key_list: raise ValueError('Tectonic region classification missing or ' 'not defined in regionalisation') for iloc, key_val in enumerate(regionalisation.key_list): if self.trt in key_val: self.regionalisation = regionalisation.regionalisation[iloc] # Update undefined shear modulus from tectonic regionalisation if not self.shear_modulus: self.shear_modulus = self.regionalisation.shear_modulus # Update undefined scaling relation from tectonic # regionalisation if not self.msr: self.msr = self.regionalisation.scaling_rel # Update undefined displacement to length ratio from tectonic # regionalisation if not self.disp_length_ratio: self.disp_length_ratio = \ self.regionalisation.disp_length_ratio break return
python
def get_tectonic_regionalisation(self, regionalisation, region_type=None): ''' Defines the tectonic region and updates the shear modulus, magnitude scaling relation and displacement to length ratio using the regional values, if not previously defined for the fault :param regionalistion: Instance of the :class: openquake.hmtk.faults.tectonic_regionalisaion.TectonicRegionalisation :param str region_type: Name of the region type - if not in regionalisation an error will be raised ''' if region_type: self.trt = region_type if not self.trt in regionalisation.key_list: raise ValueError('Tectonic region classification missing or ' 'not defined in regionalisation') for iloc, key_val in enumerate(regionalisation.key_list): if self.trt in key_val: self.regionalisation = regionalisation.regionalisation[iloc] # Update undefined shear modulus from tectonic regionalisation if not self.shear_modulus: self.shear_modulus = self.regionalisation.shear_modulus # Update undefined scaling relation from tectonic # regionalisation if not self.msr: self.msr = self.regionalisation.scaling_rel # Update undefined displacement to length ratio from tectonic # regionalisation if not self.disp_length_ratio: self.disp_length_ratio = \ self.regionalisation.disp_length_ratio break return
[ "def", "get_tectonic_regionalisation", "(", "self", ",", "regionalisation", ",", "region_type", "=", "None", ")", ":", "if", "region_type", ":", "self", ".", "trt", "=", "region_type", "if", "not", "self", ".", "trt", "in", "regionalisation", ".", "key_list", ":", "raise", "ValueError", "(", "'Tectonic region classification missing or '", "'not defined in regionalisation'", ")", "for", "iloc", ",", "key_val", "in", "enumerate", "(", "regionalisation", ".", "key_list", ")", ":", "if", "self", ".", "trt", "in", "key_val", ":", "self", ".", "regionalisation", "=", "regionalisation", ".", "regionalisation", "[", "iloc", "]", "# Update undefined shear modulus from tectonic regionalisation", "if", "not", "self", ".", "shear_modulus", ":", "self", ".", "shear_modulus", "=", "self", ".", "regionalisation", ".", "shear_modulus", "# Update undefined scaling relation from tectonic", "# regionalisation", "if", "not", "self", ".", "msr", ":", "self", ".", "msr", "=", "self", ".", "regionalisation", ".", "scaling_rel", "# Update undefined displacement to length ratio from tectonic", "# regionalisation", "if", "not", "self", ".", "disp_length_ratio", ":", "self", ".", "disp_length_ratio", "=", "self", ".", "regionalisation", ".", "disp_length_ratio", "break", "return" ]
Defines the tectonic region and updates the shear modulus, magnitude scaling relation and displacement to length ratio using the regional values, if not previously defined for the fault :param regionalistion: Instance of the :class: openquake.hmtk.faults.tectonic_regionalisaion.TectonicRegionalisation :param str region_type: Name of the region type - if not in regionalisation an error will be raised
[ "Defines", "the", "tectonic", "region", "and", "updates", "the", "shear", "modulus", "magnitude", "scaling", "relation", "and", "displacement", "to", "length", "ratio", "using", "the", "regional", "values", "if", "not", "previously", "defined", "for", "the", "fault" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L265-L301
99
gem/oq-engine
openquake/hmtk/faults/fault_models.py
mtkActiveFault.select_catalogue
def select_catalogue(self, selector, distance, distance_metric="rupture", upper_eq_depth=None, lower_eq_depth=None): """ Select earthquakes within a specied distance of the fault """ if selector.catalogue.get_number_events() < 1: raise ValueError('No events found in catalogue!') # rupture metric is selected if ('rupture' in distance_metric): # Use rupture distance self.catalogue = selector.within_rupture_distance( self.geometry.surface, distance, upper_depth=upper_eq_depth, lower_depth=lower_eq_depth) else: # Use Joyner-Boore distance self.catalogue = selector.within_joyner_boore_distance( self.geometry.surface, distance, upper_depth=upper_eq_depth, lower_depth=lower_eq_depth)
python
def select_catalogue(self, selector, distance, distance_metric="rupture", upper_eq_depth=None, lower_eq_depth=None): """ Select earthquakes within a specied distance of the fault """ if selector.catalogue.get_number_events() < 1: raise ValueError('No events found in catalogue!') # rupture metric is selected if ('rupture' in distance_metric): # Use rupture distance self.catalogue = selector.within_rupture_distance( self.geometry.surface, distance, upper_depth=upper_eq_depth, lower_depth=lower_eq_depth) else: # Use Joyner-Boore distance self.catalogue = selector.within_joyner_boore_distance( self.geometry.surface, distance, upper_depth=upper_eq_depth, lower_depth=lower_eq_depth)
[ "def", "select_catalogue", "(", "self", ",", "selector", ",", "distance", ",", "distance_metric", "=", "\"rupture\"", ",", "upper_eq_depth", "=", "None", ",", "lower_eq_depth", "=", "None", ")", ":", "if", "selector", ".", "catalogue", ".", "get_number_events", "(", ")", "<", "1", ":", "raise", "ValueError", "(", "'No events found in catalogue!'", ")", "# rupture metric is selected", "if", "(", "'rupture'", "in", "distance_metric", ")", ":", "# Use rupture distance", "self", ".", "catalogue", "=", "selector", ".", "within_rupture_distance", "(", "self", ".", "geometry", ".", "surface", ",", "distance", ",", "upper_depth", "=", "upper_eq_depth", ",", "lower_depth", "=", "lower_eq_depth", ")", "else", ":", "# Use Joyner-Boore distance", "self", ".", "catalogue", "=", "selector", ".", "within_joyner_boore_distance", "(", "self", ".", "geometry", ".", "surface", ",", "distance", ",", "upper_depth", "=", "upper_eq_depth", ",", "lower_depth", "=", "lower_eq_depth", ")" ]
Select earthquakes within a specied distance of the fault
[ "Select", "earthquakes", "within", "a", "specied", "distance", "of", "the", "fault" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L303-L325