Dataset Viewer (First 5GB)
Auto-converted to Parquet Duplicate
repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
39
1.84M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
gem/oq-engine
openquake/calculators/export/hazard.py
export_ruptures_csv
def export_ruptures_csv(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ oq = dstore['oqparam'] if 'scenario' in oq.calculation_mode: return [] dest = dstore.export_path('ruptures.csv') header = ('rupid multiplicity ...
python
def export_ruptures_csv(ekey, dstore): oq = dstore['oqparam'] if 'scenario' in oq.calculation_mode: return [] dest = dstore.export_path('ruptures.csv') header = ('rupid multiplicity mag centroid_lon centroid_lat ' 'centroid_depth trt strike dip rake boundary').split() rows...
[ "def", "export_ruptures_csv", "(", "ekey", ",", "dstore", ")", ":", "oq", "=", "dstore", "[", "'oqparam'", "]", "if", "'scenario'", "in", "oq", ".", "calculation_mode", ":", "return", "[", "]", "dest", "=", "dstore", ".", "export_path", "(", "'ruptures.csv...
:param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object
[ ":", "param", "ekey", ":", "export", "key", "i", ".", "e", ".", "a", "pair", "(", "datastore", "key", "fmt", ")", ":", "param", "dstore", ":", "datastore", "object" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L81-L106
gem/oq-engine
openquake/calculators/export/hazard.py
export_hmaps_csv
def export_hmaps_csv(key, dest, sitemesh, array, comment): """ Export the hazard maps of the given realization into CSV. :param key: output_type and export_type :param dest: name of the exported file :param sitemesh: site collection :param array: a composite array of dtype hmap_dt :param co...
python
def export_hmaps_csv(key, dest, sitemesh, array, comment): curves = util.compose_arrays(sitemesh, array) writers.write_csv(dest, curves, comment=comment) return [dest]
[ "def", "export_hmaps_csv", "(", "key", ",", "dest", ",", "sitemesh", ",", "array", ",", "comment", ")", ":", "curves", "=", "util", ".", "compose_arrays", "(", "sitemesh", ",", "array", ")", "writers", ".", "write_csv", "(", "dest", ",", "curves", ",", ...
Export the hazard maps of the given realization into CSV. :param key: output_type and export_type :param dest: name of the exported file :param sitemesh: site collection :param array: a composite array of dtype hmap_dt :param comment: comment to use as header of the exported CSV file
[ "Export", "the", "hazard", "maps", "of", "the", "given", "realization", "into", "CSV", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L223-L235
gem/oq-engine
openquake/calculators/export/hazard.py
add_imt
def add_imt(fname, imt): """ >>> add_imt('/path/to/hcurve_23.csv', 'SA(0.1)') '/path/to/hcurve-SA(0.1)_23.csv' """ name = os.path.basename(fname) newname = re.sub(r'(_\d+\.)', '-%s\\1' % imt, name) return os.path.join(os.path.dirname(fname), newname)
python
def add_imt(fname, imt): name = os.path.basename(fname) newname = re.sub(r'(_\d+\.)', '-%s\\1' % imt, name) return os.path.join(os.path.dirname(fname), newname)
[ "def", "add_imt", "(", "fname", ",", "imt", ")", ":", "name", "=", "os", ".", "path", ".", "basename", "(", "fname", ")", "newname", "=", "re", ".", "sub", "(", "r'(_\\d+\\.)'", ",", "'-%s\\\\1'", "%", "imt", ",", "name", ")", "return", "os", ".", ...
>>> add_imt('/path/to/hcurve_23.csv', 'SA(0.1)') '/path/to/hcurve-SA(0.1)_23.csv'
[ ">>>", "add_imt", "(", "/", "path", "/", "to", "/", "hcurve_23", ".", "csv", "SA", "(", "0", ".", "1", ")", ")", "/", "path", "/", "to", "/", "hcurve", "-", "SA", "(", "0", ".", "1", ")", "_23", ".", "csv" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L238-L245
gem/oq-engine
openquake/calculators/export/hazard.py
export_hcurves_by_imt_csv
def export_hcurves_by_imt_csv( key, kind, rlzs_assoc, fname, sitecol, array, oq, checksum): """ Export the curves of the given realization into CSV. :param key: output_type and export_type :param kind: a string with the kind of output (realization or statistics) :param rlzs_assoc: a :class:...
python
def export_hcurves_by_imt_csv( key, kind, rlzs_assoc, fname, sitecol, array, oq, checksum): nsites = len(sitecol) fnames = [] for imt, imls in oq.imtls.items(): slc = oq.imtls(imt) dest = add_imt(fname, imt) lst = [('lon', F32), ('lat', F32), ('depth', F32)] for ...
[ "def", "export_hcurves_by_imt_csv", "(", "key", ",", "kind", ",", "rlzs_assoc", ",", "fname", ",", "sitecol", ",", "array", ",", "oq", ",", "checksum", ")", ":", "nsites", "=", "len", "(", "sitecol", ")", "fnames", "=", "[", "]", "for", "imt", ",", "...
Export the curves of the given realization into CSV. :param key: output_type and export_type :param kind: a string with the kind of output (realization or statistics) :param rlzs_assoc: a :class:`openquake.commonlib.source.RlzsAssoc` instance :param fname: name of the exported file :param sitecol: ...
[ "Export", "the", "curves", "of", "the", "given", "realization", "into", "CSV", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L248-L277
gem/oq-engine
openquake/calculators/export/hazard.py
hazard_curve_name
def hazard_curve_name(dstore, ekey, kind, rlzs_assoc): """ :param calc_id: the calculation ID :param ekey: the export key :param kind: the kind of key :param rlzs_assoc: a RlzsAssoc instance """ key, fmt = ekey prefix = {'hcurves': 'hazard_curve', 'hmaps': 'hazard_map', 'uh...
python
def hazard_curve_name(dstore, ekey, kind, rlzs_assoc): key, fmt = ekey prefix = {'hcurves': 'hazard_curve', 'hmaps': 'hazard_map', 'uhs': 'hazard_uhs'}[key] if kind.startswith('quantile-'): fname = dstore.build_fname('quantile_' + prefix[7:], kind[9:], fmt) else: fna...
[ "def", "hazard_curve_name", "(", "dstore", ",", "ekey", ",", "kind", ",", "rlzs_assoc", ")", ":", "key", ",", "fmt", "=", "ekey", "prefix", "=", "{", "'hcurves'", ":", "'hazard_curve'", ",", "'hmaps'", ":", "'hazard_map'", ",", "'uhs'", ":", "'hazard_uhs'"...
:param calc_id: the calculation ID :param ekey: the export key :param kind: the kind of key :param rlzs_assoc: a RlzsAssoc instance
[ ":", "param", "calc_id", ":", "the", "calculation", "ID", ":", "param", "ekey", ":", "the", "export", "key", ":", "param", "kind", ":", "the", "kind", "of", "key", ":", "param", "rlzs_assoc", ":", "a", "RlzsAssoc", "instance" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L280-L294
gem/oq-engine
openquake/calculators/export/hazard.py
get_kkf
def get_kkf(ekey): """ :param ekey: export key, for instance ('uhs/rlz-1', 'xml') :returns: key, kind and fmt from the export key, i.e. 'uhs', 'rlz-1', 'xml' """ key, fmt = ekey if '/' in key: key, kind = key.split('/', 1) else: kind = '' return key, kind, fmt
python
def get_kkf(ekey): key, fmt = ekey if '/' in key: key, kind = key.split('/', 1) else: kind = '' return key, kind, fmt
[ "def", "get_kkf", "(", "ekey", ")", ":", "key", ",", "fmt", "=", "ekey", "if", "'/'", "in", "key", ":", "key", ",", "kind", "=", "key", ".", "split", "(", "'/'", ",", "1", ")", "else", ":", "kind", "=", "''", "return", "key", ",", "kind", ","...
:param ekey: export key, for instance ('uhs/rlz-1', 'xml') :returns: key, kind and fmt from the export key, i.e. 'uhs', 'rlz-1', 'xml'
[ ":", "param", "ekey", ":", "export", "key", "for", "instance", "(", "uhs", "/", "rlz", "-", "1", "xml", ")", ":", "returns", ":", "key", "kind", "and", "fmt", "from", "the", "export", "key", "i", ".", "e", ".", "uhs", "rlz", "-", "1", "xml" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L319-L329
gem/oq-engine
openquake/calculators/export/hazard.py
export_hcurves_csv
def export_hcurves_csv(ekey, dstore): """ Exports the hazard curves into several .csv files :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ oq = dstore['oqparam'] info = get_info(dstore) rlzs_assoc = dstore['csm_info'].get_rlzs_assoc() R...
python
def export_hcurves_csv(ekey, dstore): oq = dstore['oqparam'] info = get_info(dstore) rlzs_assoc = dstore['csm_info'].get_rlzs_assoc() R = len(rlzs_assoc.realizations) sitecol = dstore['sitecol'] sitemesh = get_mesh(sitecol) key, kind, fmt = get_kkf(ekey) fnames = [] checksum = d...
[ "def", "export_hcurves_csv", "(", "ekey", ",", "dstore", ")", ":", "oq", "=", "dstore", "[", "'oqparam'", "]", "info", "=", "get_info", "(", "dstore", ")", "rlzs_assoc", "=", "dstore", "[", "'csm_info'", "]", ".", "get_rlzs_assoc", "(", ")", "R", "=", ...
Exports the hazard curves into several .csv files :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object
[ "Exports", "the", "hazard", "curves", "into", "several", ".", "csv", "files" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L333-L373
gem/oq-engine
openquake/calculators/export/hazard.py
get_metadata
def get_metadata(realizations, kind): """ :param list realizations: realization objects :param str kind: kind of data, i.e. a key in the datastore :returns: a dictionary with smlt_path, gsimlt_path, statistics, quantile_value """ metadata = {} if kind.startswith('rlz-...
python
def get_metadata(realizations, kind): metadata = {} if kind.startswith('rlz-'): rlz = realizations[int(kind[4:])] metadata['smlt_path'] = '_'.join(rlz.sm_lt_path) metadata['gsimlt_path'] = rlz.gsim_rlz.uid elif kind.startswith('quantile-'): metadata['statistics'] = 'quan...
[ "def", "get_metadata", "(", "realizations", ",", "kind", ")", ":", "metadata", "=", "{", "}", "if", "kind", ".", "startswith", "(", "'rlz-'", ")", ":", "rlz", "=", "realizations", "[", "int", "(", "kind", "[", "4", ":", "]", ")", "]", "metadata", "...
:param list realizations: realization objects :param str kind: kind of data, i.e. a key in the datastore :returns: a dictionary with smlt_path, gsimlt_path, statistics, quantile_value
[ ":", "param", "list", "realizations", ":", "realization", "objects", ":", "param", "str", "kind", ":", "kind", "of", "data", "i", ".", "e", ".", "a", "key", "in", "the", "datastore", ":", "returns", ":", "a", "dictionary", "with", "smlt_path", "gsimlt_pa...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L379-L402
gem/oq-engine
openquake/calculators/export/hazard.py
export_gmf
def export_gmf(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ oq = dstore['oqparam'] if not oq.calculation_mode.startswith('scenario'): return [] sitecol = dstore['sitecol'] investigation_time = (None if oq.calcula...
python
def export_gmf(ekey, dstore): oq = dstore['oqparam'] if not oq.calculation_mode.startswith('scenario'): return [] sitecol = dstore['sitecol'] investigation_time = (None if oq.calculation_mode == 'scenario' else oq.investigation_time) fmt = ekey[-1] gmf_data...
[ "def", "export_gmf", "(", "ekey", ",", "dstore", ")", ":", "oq", "=", "dstore", "[", "'oqparam'", "]", "if", "not", "oq", ".", "calculation_mode", ".", "startswith", "(", "'scenario'", ")", ":", "return", "[", "]", "sitecol", "=", "dstore", "[", "'site...
:param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object
[ ":", "param", "ekey", ":", "export", "key", "i", ".", "e", ".", "a", "pair", "(", "datastore", "key", "fmt", ")", ":", "param", "dstore", ":", "datastore", "object" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L535-L563
gem/oq-engine
openquake/calculators/export/hazard.py
save_disagg_to_csv
def save_disagg_to_csv(metadata, matrices): """ Save disaggregation matrices to multiple .csv files. """ skip_keys = ('Mag', 'Dist', 'Lon', 'Lat', 'Eps', 'TRT') base_header = ','.join( '%s=%s' % (key, value) for key, value in metadata.items() if value is not None and key not in skip_...
python
def save_disagg_to_csv(metadata, matrices): skip_keys = ('Mag', 'Dist', 'Lon', 'Lat', 'Eps', 'TRT') base_header = ','.join( '%s=%s' % (key, value) for key, value in metadata.items() if value is not None and key not in skip_keys) for disag_tup, (poe, iml, matrix, fname) in matrices.items...
[ "def", "save_disagg_to_csv", "(", "metadata", ",", "matrices", ")", ":", "skip_keys", "=", "(", "'Mag'", ",", "'Dist'", ",", "'Lon'", ",", "'Lat'", ",", "'Eps'", ",", "'TRT'", ")", "base_header", "=", "','", ".", "join", "(", "'%s=%s'", "%", "(", "key"...
Save disaggregation matrices to multiple .csv files.
[ "Save", "disaggregation", "matrices", "to", "multiple", ".", "csv", "files", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L743-L776
gem/oq-engine
openquake/hazardlib/gsim/bradley_2013b.py
Bradley2013bChchCBD.get_mean_and_stddevs
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required #...
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): C = self.COEFFS[imt] if isinstance(imt, PGA): imt_per = 0.0 else: imt_per = imt.period sites.vs30 = np.array([250]) sites.z1pt0 = np.array([330]) ...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "# extracting dictionary of coefficients specific to required", "# intensity measure type.", "C", "=", "self", ".", "COEFFS", "[", "imt", "...
See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
[ "See", ":", "meth", ":", "superclass", "method", "<", ".", "base", ".", "GroundShakingIntensityModel", ".", "get_mean_and_stddevs", ">", "for", "spec", "of", "input", "and", "result", "values", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L63-L96
gem/oq-engine
openquake/hazardlib/gsim/bradley_2013b.py
Bradley2013bChchCBD._interp_function
def _interp_function(self, y_ip1, y_i, t_ip1, t_i, imt_per): """ Generic interpolation function used in equation 19 of 2013 report. """ return y_i + (y_ip1 - y_i) / (t_ip1 - t_i) * (imt_per - t_i)
python
def _interp_function(self, y_ip1, y_i, t_ip1, t_i, imt_per): return y_i + (y_ip1 - y_i) / (t_ip1 - t_i) * (imt_per - t_i)
[ "def", "_interp_function", "(", "self", ",", "y_ip1", ",", "y_i", ",", "t_ip1", ",", "t_i", ",", "imt_per", ")", ":", "return", "y_i", "+", "(", "y_ip1", "-", "y_i", ")", "/", "(", "t_ip1", "-", "t_i", ")", "*", "(", "imt_per", "-", "t_i", ")" ]
Generic interpolation function used in equation 19 of 2013 report.
[ "Generic", "interpolation", "function", "used", "in", "equation", "19", "of", "2013", "report", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L154-L158
gem/oq-engine
openquake/hazardlib/gsim/bradley_2013b.py
Bradley2013bChchCBD._get_SRF_tau
def _get_SRF_tau(self, imt_per): """ Table 6 and equation 19 of 2013 report. """ if imt_per < 1: srf = 0.87 elif 1 <= imt_per < 5: srf = self._interp_function(0.58, 0.87, 5, 1, imt_per) elif 5 <= imt_per <= 10: srf = 0.58 else: ...
python
def _get_SRF_tau(self, imt_per): if imt_per < 1: srf = 0.87 elif 1 <= imt_per < 5: srf = self._interp_function(0.58, 0.87, 5, 1, imt_per) elif 5 <= imt_per <= 10: srf = 0.58 else: srf = 1 return srf
[ "def", "_get_SRF_tau", "(", "self", ",", "imt_per", ")", ":", "if", "imt_per", "<", "1", ":", "srf", "=", "0.87", "elif", "1", "<=", "imt_per", "<", "5", ":", "srf", "=", "self", ".", "_interp_function", "(", "0.58", ",", "0.87", ",", "5", ",", "...
Table 6 and equation 19 of 2013 report.
[ "Table", "6", "and", "equation", "19", "of", "2013", "report", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L160-L173
gem/oq-engine
openquake/hazardlib/gsim/bradley_2013b.py
Bradley2013bChchCBD._get_SRF_phi
def _get_SRF_phi(self, imt_per): """ Table 7 and equation 19 of 2013 report. NB change in notation, 2013 report calls this term 'sigma' but it is referred to here as phi. """ if imt_per < 0.6: srf = 0.8 elif 0.6 <= imt_per < 1: srf = self._...
python
def _get_SRF_phi(self, imt_per): if imt_per < 0.6: srf = 0.8 elif 0.6 <= imt_per < 1: srf = self._interp_function(0.7, 0.8, 1, 0.6, imt_per) elif 1 <= imt_per <= 10: srf = self._interp_function(0.6, 0.7, 10, 1, imt_per) else: srf =...
[ "def", "_get_SRF_phi", "(", "self", ",", "imt_per", ")", ":", "if", "imt_per", "<", "0.6", ":", "srf", "=", "0.8", "elif", "0.6", "<=", "imt_per", "<", "1", ":", "srf", "=", "self", ".", "_interp_function", "(", "0.7", ",", "0.8", ",", "1", ",", ...
Table 7 and equation 19 of 2013 report. NB change in notation, 2013 report calls this term 'sigma' but it is referred to here as phi.
[ "Table", "7", "and", "equation", "19", "of", "2013", "report", ".", "NB", "change", "in", "notation", "2013", "report", "calls", "this", "term", "sigma", "but", "it", "is", "referred", "to", "here", "as", "phi", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L175-L190
gem/oq-engine
openquake/hazardlib/gsim/bradley_2013b.py
Bradley2013bChchCBD._get_SRF_sigma
def _get_SRF_sigma(self, imt_per): """ Table 8 and equation 19 of 2013 report. NB change in notation, 2013 report calls this term 'sigma_t' but it is referred to here as sigma. Note that Table 8 is identical to Table 7 in the 2013 report. """ if imt_per < 0.6: ...
python
def _get_SRF_sigma(self, imt_per): if imt_per < 0.6: srf = 0.8 elif 0.6 <= imt_per < 1: srf = self._interp_function(0.7, 0.8, 1, 0.6, imt_per) elif 1 <= imt_per <= 10: srf = self._interp_function(0.6, 0.7, 10, 1, imt_per) else: srf...
[ "def", "_get_SRF_sigma", "(", "self", ",", "imt_per", ")", ":", "if", "imt_per", "<", "0.6", ":", "srf", "=", "0.8", "elif", "0.6", "<=", "imt_per", "<", "1", ":", "srf", "=", "self", ".", "_interp_function", "(", "0.7", ",", "0.8", ",", "1", ",", ...
Table 8 and equation 19 of 2013 report. NB change in notation, 2013 report calls this term 'sigma_t' but it is referred to here as sigma. Note that Table 8 is identical to Table 7 in the 2013 report.
[ "Table", "8", "and", "equation", "19", "of", "2013", "report", ".", "NB", "change", "in", "notation", "2013", "report", "calls", "this", "term", "sigma_t", "but", "it", "is", "referred", "to", "here", "as", "sigma", ".", "Note", "that", "Table", "8", "...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L192-L208
gem/oq-engine
openquake/hazardlib/gsim/bradley_2013b.py
Bradley2013bChchCBD._get_dL2L
def _get_dL2L(self, imt_per): """ Table 3 and equation 19 of 2013 report. """ if imt_per < 0.18: dL2L = -0.06 elif 0.18 <= imt_per < 0.35: dL2L = self._interp_function(0.12, -0.06, 0.35, 0.18, imt_per) elif 0.35 <= imt_per <= 10: dL2L =...
python
def _get_dL2L(self, imt_per): if imt_per < 0.18: dL2L = -0.06 elif 0.18 <= imt_per < 0.35: dL2L = self._interp_function(0.12, -0.06, 0.35, 0.18, imt_per) elif 0.35 <= imt_per <= 10: dL2L = self._interp_function(0.65, 0.12, 10, 0.35, imt_per) e...
[ "def", "_get_dL2L", "(", "self", ",", "imt_per", ")", ":", "if", "imt_per", "<", "0.18", ":", "dL2L", "=", "-", "0.06", "elif", "0.18", "<=", "imt_per", "<", "0.35", ":", "dL2L", "=", "self", ".", "_interp_function", "(", "0.12", ",", "-", "0.06", ...
Table 3 and equation 19 of 2013 report.
[ "Table", "3", "and", "equation", "19", "of", "2013", "report", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L210-L223
gem/oq-engine
openquake/hazardlib/gsim/bradley_2013b.py
Bradley2013bChchCBD._get_dS2S
def _get_dS2S(self, imt_per): """ Table 4 of 2013 report """ if imt_per == 0: dS2S = 0.05 elif 0 < imt_per < 0.15: dS2S = self._interp_function(-0.15, 0.05, 0.15, 0, imt_per) elif 0.15 <= imt_per < 0.45: dS2S = self._interp_function(0.4...
python
def _get_dS2S(self, imt_per): if imt_per == 0: dS2S = 0.05 elif 0 < imt_per < 0.15: dS2S = self._interp_function(-0.15, 0.05, 0.15, 0, imt_per) elif 0.15 <= imt_per < 0.45: dS2S = self._interp_function(0.4, -0.15, 0.45, 0.15, imt_per) elif 0.4...
[ "def", "_get_dS2S", "(", "self", ",", "imt_per", ")", ":", "if", "imt_per", "==", "0", ":", "dS2S", "=", "0.05", "elif", "0", "<", "imt_per", "<", "0.15", ":", "dS2S", "=", "self", ".", "_interp_function", "(", "-", "0.15", ",", "0.05", ",", "0.15"...
Table 4 of 2013 report
[ "Table", "4", "of", "2013", "report" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L225-L244
gem/oq-engine
openquake/hazardlib/calc/filters.py
context
def context(src): """ Used to add the source_id to the error message. To be used as with context(src): operation_with(src) Typically the operation is filtering a source, that can fail for tricky geometries. """ try: yield except Exception: etype, err, tb = sys.e...
python
def context(src): try: yield except Exception: etype, err, tb = sys.exc_info() msg = 'An error occurred with source id=%s. Error: %s' msg %= (src.source_id, err) raise_(etype, msg, tb)
[ "def", "context", "(", "src", ")", ":", "try", ":", "yield", "except", "Exception", ":", "etype", ",", "err", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "msg", "=", "'An error occurred with source id=%s. Error: %s'", "msg", "%=", "(", "src", ".", ...
Used to add the source_id to the error message. To be used as with context(src): operation_with(src) Typically the operation is filtering a source, that can fail for tricky geometries.
[ "Used", "to", "add", "the", "source_id", "to", "the", "error", "message", ".", "To", "be", "used", "as" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L39-L55
gem/oq-engine
openquake/hazardlib/calc/filters.py
split_sources
def split_sources(srcs): """ :param srcs: sources :returns: a pair (split sources, split time) or just the split_sources """ from openquake.hazardlib.source import splittable sources = [] split_time = {} # src.id -> time for src in srcs: t0 = time.time() mag_a, mag_b = s...
python
def split_sources(srcs): from openquake.hazardlib.source import splittable sources = [] split_time = {} for src in srcs: t0 = time.time() mag_a, mag_b = src.get_min_max_mag() min_mag = src.min_mag if mag_b < min_mag: continue has_serial = hasa...
[ "def", "split_sources", "(", "srcs", ")", ":", "from", "openquake", ".", "hazardlib", ".", "source", "import", "splittable", "sources", "=", "[", "]", "split_time", "=", "{", "}", "# src.id -> time", "for", "src", "in", "srcs", ":", "t0", "=", "time", "....
:param srcs: sources :returns: a pair (split sources, split time) or just the split_sources
[ ":", "param", "srcs", ":", "sources", ":", "returns", ":", "a", "pair", "(", "split", "sources", "split", "time", ")", "or", "just", "the", "split_sources" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L186-L241
gem/oq-engine
openquake/hazardlib/calc/filters.py
IntegrationDistance.get_bounding_box
def get_bounding_box(self, lon, lat, trt=None, mag=None): """ Build a bounding box around the given lon, lat by computing the maximum_distance at the given tectonic region type and magnitude. :param lon: longitude :param lat: latitude :param trt: tectonic region type, po...
python
def get_bounding_box(self, lon, lat, trt=None, mag=None): if trt is None: maxdist = max(self(trt, mag) for trt in self.dic) else: maxdist = self(trt, mag) a1 = min(maxdist * KM_TO_DEGREES, 90) a2 = min(angular_distance(maxdist, lat), 180) retu...
[ "def", "get_bounding_box", "(", "self", ",", "lon", ",", "lat", ",", "trt", "=", "None", ",", "mag", "=", "None", ")", ":", "if", "trt", "is", "None", ":", "# take the greatest integration distance", "maxdist", "=", "max", "(", "self", "(", "trt", ",", ...
Build a bounding box around the given lon, lat by computing the maximum_distance at the given tectonic region type and magnitude. :param lon: longitude :param lat: latitude :param trt: tectonic region type, possibly None :param mag: magnitude, possibly None :returns: min...
[ "Build", "a", "bounding", "box", "around", "the", "given", "lon", "lat", "by", "computing", "the", "maximum_distance", "at", "the", "given", "tectonic", "region", "type", "and", "magnitude", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L138-L155
gem/oq-engine
openquake/hazardlib/calc/filters.py
IntegrationDistance.get_affected_box
def get_affected_box(self, src): """ Get the enlarged bounding box of a source. :param src: a source object :returns: a bounding box (min_lon, min_lat, max_lon, max_lat) """ mag = src.get_min_max_mag()[1] maxdist = self(src.tectonic_region_type, mag) bbox...
python
def get_affected_box(self, src): mag = src.get_min_max_mag()[1] maxdist = self(src.tectonic_region_type, mag) bbox = get_bounding_box(src, maxdist) return (fix_lon(bbox[0]), bbox[1], fix_lon(bbox[2]), bbox[3])
[ "def", "get_affected_box", "(", "self", ",", "src", ")", ":", "mag", "=", "src", ".", "get_min_max_mag", "(", ")", "[", "1", "]", "maxdist", "=", "self", "(", "src", ".", "tectonic_region_type", ",", "mag", ")", "bbox", "=", "get_bounding_box", "(", "s...
Get the enlarged bounding box of a source. :param src: a source object :returns: a bounding box (min_lon, min_lat, max_lon, max_lat)
[ "Get", "the", "enlarged", "bounding", "box", "of", "a", "source", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L157-L167
gem/oq-engine
openquake/hazardlib/calc/filters.py
SourceFilter.sitecol
def sitecol(self): """ Read the site collection from .filename and cache it """ if 'sitecol' in vars(self): return self.__dict__['sitecol'] if self.filename is None or not os.path.exists(self.filename): # case of nofilter/None sitecol return ...
python
def sitecol(self): if 'sitecol' in vars(self): return self.__dict__['sitecol'] if self.filename is None or not os.path.exists(self.filename): return with hdf5.File(self.filename, 'r') as h5: self.__dict__['sitecol'] = sc = h5.get('sitecol...
[ "def", "sitecol", "(", "self", ")", ":", "if", "'sitecol'", "in", "vars", "(", "self", ")", ":", "return", "self", ".", "__dict__", "[", "'sitecol'", "]", "if", "self", ".", "filename", "is", "None", "or", "not", "os", ".", "path", ".", "exists", "...
Read the site collection from .filename and cache it
[ "Read", "the", "site", "collection", "from", ".", "filename", "and", "cache", "it" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L276-L287
gem/oq-engine
openquake/hazardlib/calc/filters.py
SourceFilter.get_rectangle
def get_rectangle(self, src): """ :param src: a source object :returns: ((min_lon, min_lat), width, height), useful for plotting """ min_lon, min_lat, max_lon, max_lat = ( self.integration_distance.get_affected_box(src)) return (min_lon, min_lat), (max_lon - m...
python
def get_rectangle(self, src): min_lon, min_lat, max_lon, max_lat = ( self.integration_distance.get_affected_box(src)) return (min_lon, min_lat), (max_lon - min_lon) % 360, max_lat - min_lat
[ "def", "get_rectangle", "(", "self", ",", "src", ")", ":", "min_lon", ",", "min_lat", ",", "max_lon", ",", "max_lat", "=", "(", "self", ".", "integration_distance", ".", "get_affected_box", "(", "src", ")", ")", "return", "(", "min_lon", ",", "min_lat", ...
:param src: a source object :returns: ((min_lon, min_lat), width, height), useful for plotting
[ ":", "param", "src", ":", "a", "source", "object", ":", "returns", ":", "((", "min_lon", "min_lat", ")", "width", "height", ")", "useful", "for", "plotting" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L289-L296
gem/oq-engine
openquake/hazardlib/calc/filters.py
SourceFilter.get_bounding_boxes
def get_bounding_boxes(self, trt=None, mag=None): """ :param trt: a tectonic region type (used for the integration distance) :param mag: a magnitude (used for the integration distance) :returns: a list of bounding boxes, one per site """ bbs = [] for site in self....
python
def get_bounding_boxes(self, trt=None, mag=None): bbs = [] for site in self.sitecol: bb = self.integration_distance.get_bounding_box( site.location.longitude, site.location.latitude, trt, mag) bbs.append(bb) return bbs
[ "def", "get_bounding_boxes", "(", "self", ",", "trt", "=", "None", ",", "mag", "=", "None", ")", ":", "bbs", "=", "[", "]", "for", "site", "in", "self", ".", "sitecol", ":", "bb", "=", "self", ".", "integration_distance", ".", "get_bounding_box", "(", ...
:param trt: a tectonic region type (used for the integration distance) :param mag: a magnitude (used for the integration distance) :returns: a list of bounding boxes, one per site
[ ":", "param", "trt", ":", "a", "tectonic", "region", "type", "(", "used", "for", "the", "integration", "distance", ")", ":", "param", "mag", ":", "a", "magnitude", "(", "used", "for", "the", "integration", "distance", ")", ":", "returns", ":", "a", "li...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L319-L330
gem/oq-engine
openquake/hazardlib/calc/filters.py
SourceFilter.close_sids
def close_sids(self, rec, trt, mag): """ :param rec: a record with fields minlon, minlat, maxlon, maxlat :param trt: tectonic region type string :param mag: magnitude :returns: the site indices within the bounding box enlarged by the in...
python
def close_sids(self, rec, trt, mag): if self.sitecol is None: return [] elif not self.integration_distance: return self.sitecol.sids if hasattr(rec, 'dtype'): bbox = rec['minlon'], rec['minlat'], rec['maxlon'], rec['maxlat'] else: ...
[ "def", "close_sids", "(", "self", ",", "rec", ",", "trt", ",", "mag", ")", ":", "if", "self", ".", "sitecol", "is", "None", ":", "return", "[", "]", "elif", "not", "self", ".", "integration_distance", ":", "# do not filter", "return", "self", ".", "sit...
:param rec: a record with fields minlon, minlat, maxlon, maxlat :param trt: tectonic region type string :param mag: magnitude :returns: the site indices within the bounding box enlarged by the integration distance for the given TRT and magni...
[ ":", "param", "rec", ":", "a", "record", "with", "fields", "minlon", "minlat", "maxlon", "maxlat", ":", "param", "trt", ":", "tectonic", "region", "type", "string", ":", "param", "mag", ":", "magnitude", ":", "returns", ":", "the", "site", "indices", "wi...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L332-L358
gem/oq-engine
openquake/hazardlib/calc/filters.py
SourceFilter.filter
def filter(self, sources): """ :param sources: a sequence of sources :yields: sources with .indices """ for src in sources: if hasattr(src, 'indices'): # already filtered yield src continue box = self.integration_distance....
python
def filter(self, sources): for src in sources: if hasattr(src, 'indices'): yield src continue box = self.integration_distance.get_affected_box(src) indices = self.sitecol.within_bbox(box) if len(indices): ...
[ "def", "filter", "(", "self", ",", "sources", ")", ":", "for", "src", "in", "sources", ":", "if", "hasattr", "(", "src", ",", "'indices'", ")", ":", "# already filtered", "yield", "src", "continue", "box", "=", "self", ".", "integration_distance", ".", "...
:param sources: a sequence of sources :yields: sources with .indices
[ ":", "param", "sources", ":", "a", "sequence", "of", "sources", ":", "yields", ":", "sources", "with", ".", "indices" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L360-L373
gem/oq-engine
openquake/hazardlib/calc/filters.py
RtreeFilter.filter
def filter(self, sources): """ :param sources: a sequence of sources :yields: rtree-filtered sources """ if self.sitecol is None: # do not filter yield from sources return for src in sources: box = self.integration_distance.get_affecte...
python
def filter(self, sources): if self.sitecol is None: yield from sources return for src in sources: box = self.integration_distance.get_affected_box(src) indices = within(box, self.index) if len(indices): src.indices = ...
[ "def", "filter", "(", "self", ",", "sources", ")", ":", "if", "self", ".", "sitecol", "is", "None", ":", "# do not filter", "yield", "from", "sources", "return", "for", "src", "in", "sources", ":", "box", "=", "self", ".", "integration_distance", ".", "g...
:param sources: a sequence of sources :yields: rtree-filtered sources
[ ":", "param", "sources", ":", "a", "sequence", "of", "sources", ":", "yields", ":", "rtree", "-", "filtered", "sources" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/filters.py#L419-L432
gem/oq-engine
openquake/commands/to_shapefile.py
to_shapefile
def to_shapefile(output, input_nrml_file, validate): """ Convert a NRML source model file to ESRI Shapefile(s). For each type of source geometry defined in the NRML file (point, area, simple fault, complex fault, planar) a separate shapefile is created. Each shapefile is differentiated by a specifi...
python
def to_shapefile(output, input_nrml_file, validate): input_parser = shapefileparser.SourceModelParser() source_model = input_parser.read(input_nrml_file, validate) if not output: output = os.path.splitext(input_nrml_file)[0] print('Extracting %s_ files' % output) shapefileparser.Shapefi...
[ "def", "to_shapefile", "(", "output", ",", "input_nrml_file", ",", "validate", ")", ":", "input_parser", "=", "shapefileparser", ".", "SourceModelParser", "(", ")", "source_model", "=", "input_parser", ".", "read", "(", "input_nrml_file", ",", "validate", ")", "...
Convert a NRML source model file to ESRI Shapefile(s). For each type of source geometry defined in the NRML file (point, area, simple fault, complex fault, planar) a separate shapefile is created. Each shapefile is differentiated by a specific ending('_point', '_area', '_simple', '_complex', '_planar')...
[ "Convert", "a", "NRML", "source", "model", "file", "to", "ESRI", "Shapefile", "(", "s", ")", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/to_shapefile.py#L24-L40
gem/oq-engine
openquake/hazardlib/geo/surface/simple_fault.py
simple_fault_node
def simple_fault_node(fault_trace, dip, upper_depth, lower_depth): """ :param fault_trace: an object with an attribute .points :param dip: dip parameter :param upper_depth: upper seismogenic depth :param lower_depth: lower seismogenic depth :returns: a Node of kind simpleFaultGeometry """ ...
python
def simple_fault_node(fault_trace, dip, upper_depth, lower_depth): node = Node('simpleFaultGeometry') line = [] for p in fault_trace.points: line.append(p.longitude) line.append(p.latitude) node.append(Node('gml:LineString', nodes=[Node('gml:posList', {}, line)])) node.append(No...
[ "def", "simple_fault_node", "(", "fault_trace", ",", "dip", ",", "upper_depth", ",", "lower_depth", ")", ":", "node", "=", "Node", "(", "'simpleFaultGeometry'", ")", "line", "=", "[", "]", "for", "p", "in", "fault_trace", ".", "points", ":", "line", ".", ...
:param fault_trace: an object with an attribute .points :param dip: dip parameter :param upper_depth: upper seismogenic depth :param lower_depth: lower seismogenic depth :returns: a Node of kind simpleFaultGeometry
[ ":", "param", "fault_trace", ":", "an", "object", "with", "an", "attribute", ".", "points", ":", "param", "dip", ":", "dip", "parameter", ":", "param", "upper_depth", ":", "upper", "seismogenic", "depth", ":", "param", "lower_depth", ":", "lower", "seismogen...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L35-L52
gem/oq-engine
openquake/hazardlib/geo/surface/simple_fault.py
SimpleFaultSurface.check_fault_data
def check_fault_data(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip, mesh_spacing): """ Verify the fault data and raise ``ValueError`` if anything is wrong. This method doesn't have to be called by hands before creating the surface objec...
python
def check_fault_data(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip, mesh_spacing): if not len(fault_trace) >= 2: raise ValueError("the fault trace must have at least two points") if not fault_trace.horizontal(): raise Va...
[ "def", "check_fault_data", "(", "cls", ",", "fault_trace", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "dip", ",", "mesh_spacing", ")", ":", "if", "not", "len", "(", "fault_trace", ")", ">=", "2", ":", "raise", "ValueError", "(", "\"th...
Verify the fault data and raise ``ValueError`` if anything is wrong. This method doesn't have to be called by hands before creating the surface object, because it is called from :meth:`from_fault_data`.
[ "Verify", "the", "fault", "data", "and", "raise", "ValueError", "if", "anything", "is", "wrong", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L107-L132
gem/oq-engine
openquake/hazardlib/geo/surface/simple_fault.py
SimpleFaultSurface.from_fault_data
def from_fault_data(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip, mesh_spacing): """ Create and return a fault surface using fault source data. :param openquake.hazardlib.geo.line.Line fault_trace: Geographical line representing the...
python
def from_fault_data(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip, mesh_spacing): cls.check_fault_data(fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip, mesh_spacing) vdi...
[ "def", "from_fault_data", "(", "cls", ",", "fault_trace", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "dip", ",", "mesh_spacing", ")", ":", "cls", ".", "check_fault_data", "(", "fault_trace", ",", "upper_seismogenic_depth", ",", "lower_seismog...
Create and return a fault surface using fault source data. :param openquake.hazardlib.geo.line.Line fault_trace: Geographical line representing the intersection between the fault surface and the earth surface. The line must be horizontal (i.e. all depth values must be equal)...
[ "Create", "and", "return", "a", "fault", "surface", "using", "fault", "source", "data", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L135-L196
gem/oq-engine
openquake/hazardlib/geo/surface/simple_fault.py
SimpleFaultSurface.get_fault_patch_vertices
def get_fault_patch_vertices(cls, rupture_top_edge, upper_seismogenic_depth, lower_seismogenic_depth, dip, index_patch=1): """ Get surface main vertices. Parameters are the same as for :meth:`from_fault_data`, excluding fa...
python
def get_fault_patch_vertices(cls, rupture_top_edge, upper_seismogenic_depth, lower_seismogenic_depth, dip, index_patch=1): dip_tan = math.tan(math.radians(dip)) hdist_bottom = ( lower_seismogenic_depth - uppe...
[ "def", "get_fault_patch_vertices", "(", "cls", ",", "rupture_top_edge", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "dip", ",", "index_patch", "=", "1", ")", ":", "# Similar to :meth:`from_fault_data`, we just don't resample edges", "dip_tan", "=", ...
Get surface main vertices. Parameters are the same as for :meth:`from_fault_data`, excluding fault_trace, and mesh spacing. :param rupture_top_edge: A instances of :class:`openquake.hazardlib.geo.line.Line` representing the rupture surface's top edge. :param inde...
[ "Get", "surface", "main", "vertices", ".", "Parameters", "are", "the", "same", "as", "for", ":", "meth", ":", "from_fault_data", "excluding", "fault_trace", "and", "mesh", "spacing", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L199-L253
gem/oq-engine
openquake/hazardlib/geo/surface/simple_fault.py
SimpleFaultSurface.hypocentre_patch_index
def hypocentre_patch_index(cls, hypocentre, rupture_top_edge, upper_seismogenic_depth, lower_seismogenic_depth, dip): """ This methods finds the index of the fault patch including the hypocentre. :param hypocentre: ...
python
def hypocentre_patch_index(cls, hypocentre, rupture_top_edge, upper_seismogenic_depth, lower_seismogenic_depth, dip): totaln_patch = len(rupture_top_edge) indexlist = [] dist_list = [] for i, index in enumerate(range(...
[ "def", "hypocentre_patch_index", "(", "cls", ",", "hypocentre", ",", "rupture_top_edge", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "dip", ")", ":", "totaln_patch", "=", "len", "(", "rupture_top_edge", ")", "indexlist", "=", "[", "]", "di...
This methods finds the index of the fault patch including the hypocentre. :param hypocentre: :class:`~openquake.hazardlib.geo.point.Point` object representing the location of hypocentre. :param rupture_top_edge: A instances of :class:`openquake.hazardlib.geo....
[ "This", "methods", "finds", "the", "index", "of", "the", "fault", "patch", "including", "the", "hypocentre", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L256-L298
gem/oq-engine
openquake/hazardlib/geo/surface/simple_fault.py
SimpleFaultSurface.get_surface_vertexes
def get_surface_vertexes(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip): """ Get surface main vertexes. Parameters are the same as for :meth:`from_fault_data`, excluding mesh spacing. :returns: ...
python
def get_surface_vertexes(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip): dip_tan = math.tan(math.radians(dip)) hdist_top = upper_seismogenic_depth / dip_tan hdist_bottom = lower_seismogenic_dept...
[ "def", "get_surface_vertexes", "(", "cls", ",", "fault_trace", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "dip", ")", ":", "# Similar to :meth:`from_fault_data`, we just don't resample edges", "dip_tan", "=", "math", ".", "tan", "(", "math", ".",...
Get surface main vertexes. Parameters are the same as for :meth:`from_fault_data`, excluding mesh spacing. :returns: Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon` describing the surface projection of the simple fault with specified parameters...
[ "Get", "surface", "main", "vertexes", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L301-L336
gem/oq-engine
openquake/hazardlib/geo/surface/simple_fault.py
SimpleFaultSurface.surface_projection_from_fault_data
def surface_projection_from_fault_data(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip): """ Get a surface projection of the simple fault surface. Parameters are the same as for :meth:`...
python
def surface_projection_from_fault_data(cls, fault_trace, upper_seismogenic_depth, lower_seismogenic_depth, dip): lons, lats = cls.get_surface_vertexes(fault_trace, upper_s...
[ "def", "surface_projection_from_fault_data", "(", "cls", ",", "fault_trace", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "dip", ")", ":", "lons", ",", "lats", "=", "cls", ".", "get_surface_vertexes", "(", "fault_trace", ",", "upper_seismogenic...
Get a surface projection of the simple fault surface. Parameters are the same as for :meth:`from_fault_data`, excluding mesh spacing. :returns: Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon` describing the surface projection of the simple fault with ...
[ "Get", "a", "surface", "projection", "of", "the", "simple", "fault", "surface", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/surface/simple_fault.py#L339-L356
gem/oq-engine
openquake/hazardlib/gsim/zhao_2006.py
ZhaoEtAl2006Asc.get_mean_and_stddevs
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extracting dictionary of coefficients specific to required #...
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): C = self.COEFFS_ASC[imt] mean = self._compute_magnitude_term(C, rup.mag) +\ self._compute_distance_term(C, rup.mag, dists.rrup) +\ self._compute_f...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "# extracting dictionary of coefficients specific to required", "# intensity measure type.", "C", "=", "self", ".", "COEFFS_ASC", "[", "imt",...
See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
[ "See", ":", "meth", ":", "superclass", "method", "<", ".", "base", ".", "GroundShakingIntensityModel", ".", "get_mean_and_stddevs", ">", "for", "spec", "of", "input", "and", "result", "values", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L81-L109
gem/oq-engine
openquake/hazardlib/gsim/zhao_2006.py
ZhaoEtAl2006Asc._compute_distance_term
def _compute_distance_term(self, C, mag, rrup): """ Compute second and third terms in equation 1, p. 901. """ term1 = C['b'] * rrup term2 = - np.log(rrup + C['c'] * np.exp(C['d'] * mag)) return term1 + term2
python
def _compute_distance_term(self, C, mag, rrup): term1 = C['b'] * rrup term2 = - np.log(rrup + C['c'] * np.exp(C['d'] * mag)) return term1 + term2
[ "def", "_compute_distance_term", "(", "self", ",", "C", ",", "mag", ",", "rrup", ")", ":", "term1", "=", "C", "[", "'b'", "]", "*", "rrup", "term2", "=", "-", "np", ".", "log", "(", "rrup", "+", "C", "[", "'c'", "]", "*", "np", ".", "exp", "(...
Compute second and third terms in equation 1, p. 901.
[ "Compute", "second", "and", "third", "terms", "in", "equation", "1", "p", ".", "901", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L133-L140
gem/oq-engine
openquake/hazardlib/gsim/zhao_2006.py
ZhaoEtAl2006Asc._compute_focal_depth_term
def _compute_focal_depth_term(self, C, hypo_depth): """ Compute fourth term in equation 1, p. 901. """ # p. 901. "(i.e, depth is capped at 125 km)". focal_depth = hypo_depth if focal_depth > 125.0: focal_depth = 125.0 # p. 902. "We used the value of 1...
python
def _compute_focal_depth_term(self, C, hypo_depth): focal_depth = hypo_depth if focal_depth > 125.0: focal_depth = 125.0 hc = 15.0 return float(focal_depth >= hc) * C['e'] * (focal_depth - hc)
[ "def", "_compute_focal_depth_term", "(", "self", ",", "C", ",", "hypo_depth", ")", ":", "# p. 901. \"(i.e, depth is capped at 125 km)\".", "focal_depth", "=", "hypo_depth", "if", "focal_depth", ">", "125.0", ":", "focal_depth", "=", "125.0", "# p. 902. \"We used the value...
Compute fourth term in equation 1, p. 901.
[ "Compute", "fourth", "term", "in", "equation", "1", "p", ".", "901", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L142-L157
gem/oq-engine
openquake/hazardlib/gsim/zhao_2006.py
ZhaoEtAl2006Asc._compute_site_class_term
def _compute_site_class_term(self, C, vs30): """ Compute nine-th term in equation 1, p. 901. """ # map vs30 value to site class, see table 2, p. 901. site_term = np.zeros(len(vs30)) # hard rock site_term[vs30 > 1100.0] = C['CH'] # rock site_term[...
python
def _compute_site_class_term(self, C, vs30): site_term = np.zeros(len(vs30)) site_term[vs30 > 1100.0] = C['CH'] site_term[(vs30 > 600) & (vs30 <= 1100)] = C['C1'] site_term[(vs30 > 300) & (vs30 <= 600)] = C['C2'] site_term...
[ "def", "_compute_site_class_term", "(", "self", ",", "C", ",", "vs30", ")", ":", "# map vs30 value to site class, see table 2, p. 901.", "site_term", "=", "np", ".", "zeros", "(", "len", "(", "vs30", ")", ")", "# hard rock", "site_term", "[", "vs30", ">", "1100....
Compute nine-th term in equation 1, p. 901.
[ "Compute", "nine", "-", "th", "term", "in", "equation", "1", "p", ".", "901", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L168-L190
gem/oq-engine
openquake/hazardlib/gsim/zhao_2006.py
ZhaoEtAl2006Asc._compute_magnitude_squared_term
def _compute_magnitude_squared_term(self, P, M, Q, W, mag): """ Compute magnitude squared term, equation 5, p. 909. """ return P * (mag - M) + Q * (mag - M) ** 2 + W
python
def _compute_magnitude_squared_term(self, P, M, Q, W, mag): return P * (mag - M) + Q * (mag - M) ** 2 + W
[ "def", "_compute_magnitude_squared_term", "(", "self", ",", "P", ",", "M", ",", "Q", ",", "W", ",", "mag", ")", ":", "return", "P", "*", "(", "mag", "-", "M", ")", "+", "Q", "*", "(", "mag", "-", "M", ")", "**", "2", "+", "W" ]
Compute magnitude squared term, equation 5, p. 909.
[ "Compute", "magnitude", "squared", "term", "equation", "5", "p", ".", "909", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L192-L196
gem/oq-engine
openquake/hazardlib/gsim/zhao_2006.py
ZhaoEtAl2006SSlab._compute_slab_correction_term
def _compute_slab_correction_term(self, C, rrup): """ Compute path modification term for slab events, that is the 8-th term in equation 1, p. 901. """ slab_term = C['SSL'] * np.log(rrup) return slab_term
python
def _compute_slab_correction_term(self, C, rrup): slab_term = C['SSL'] * np.log(rrup) return slab_term
[ "def", "_compute_slab_correction_term", "(", "self", ",", "C", ",", "rrup", ")", ":", "slab_term", "=", "C", "[", "'SSL'", "]", "*", "np", ".", "log", "(", "rrup", ")", "return", "slab_term" ]
Compute path modification term for slab events, that is the 8-th term in equation 1, p. 901.
[ "Compute", "path", "modification", "term", "for", "slab", "events", "that", "is", "the", "8", "-", "th", "term", "in", "equation", "1", "p", ".", "901", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L369-L376
gem/oq-engine
openquake/hazardlib/gsim/zhao_2006.py
ZhaoEtAl2006AscSGS.get_mean_and_stddevs
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ Using a minimum distance of 5km for the calculation. """ dists_mod = copy.deepcopy(dists) dists_mod.rrup[dists.rrup <= 5.] = 5. return super().get_mean_and_stddevs( sites, rup, dists_m...
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): dists_mod = copy.deepcopy(dists) dists_mod.rrup[dists.rrup <= 5.] = 5. return super().get_mean_and_stddevs( sites, rup, dists_mod, imt, stddev_types)
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "dists_mod", "=", "copy", ".", "deepcopy", "(", "dists", ")", "dists_mod", ".", "rrup", "[", "dists", ".", "rrup", "<=", "5."...
Using a minimum distance of 5km for the calculation.
[ "Using", "a", "minimum", "distance", "of", "5km", "for", "the", "calculation", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/zhao_2006.py#L654-L663
gem/oq-engine
openquake/engine/utils/__init__.py
confirm
def confirm(prompt): """ Ask for confirmation, given a ``prompt`` and return a boolean value. """ while True: try: answer = input(prompt) except KeyboardInterrupt: # the user presses ctrl+c, just say 'no' return False answer = answer.strip().lo...
python
def confirm(prompt): while True: try: answer = input(prompt) except KeyboardInterrupt: return False answer = answer.strip().lower() if answer not in ('y', 'n'): print('Please enter y or n') continue return answ...
[ "def", "confirm", "(", "prompt", ")", ":", "while", "True", ":", "try", ":", "answer", "=", "input", "(", "prompt", ")", "except", "KeyboardInterrupt", ":", "# the user presses ctrl+c, just say 'no'", "return", "False", "answer", "=", "answer", ".", "strip", "...
Ask for confirmation, given a ``prompt`` and return a boolean value.
[ "Ask", "for", "confirmation", "given", "a", "prompt", "and", "return", "a", "boolean", "value", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/utils/__init__.py#L20-L34
gem/oq-engine
openquake/risklib/asset.py
build_asset_array
def build_asset_array(assets_by_site, tagnames=(), time_event=None): """ :param assets_by_site: a list of lists of assets :param tagnames: a list of tag names :returns: an array `assetcol` """ for assets in assets_by_site: if len(assets): first_asset = assets[0] b...
python
def build_asset_array(assets_by_site, tagnames=(), time_event=None): for assets in assets_by_site: if len(assets): first_asset = assets[0] break else: raise ValueError('There are no assets!') loss_types = [] occupancy_periods = [] for name in sorted(fir...
[ "def", "build_asset_array", "(", "assets_by_site", ",", "tagnames", "=", "(", ")", ",", "time_event", "=", "None", ")", ":", "for", "assets", "in", "assets_by_site", ":", "if", "len", "(", "assets", ")", ":", "first_asset", "=", "assets", "[", "0", "]", ...
:param assets_by_site: a list of lists of assets :param tagnames: a list of tag names :returns: an array `assetcol`
[ ":", "param", "assets_by_site", ":", "a", "list", "of", "lists", "of", "assets", ":", "param", "tagnames", ":", "a", "list", "of", "tag", "names", ":", "returns", ":", "an", "array", "assetcol" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L583-L655
gem/oq-engine
openquake/risklib/asset.py
_get_exposure
def _get_exposure(fname, stop=None): """ :param fname: path of the XML file containing the exposure :param stop: node at which to stop parsing (or None) :returns: a pair (Exposure instance, list of asset nodes) """ [exposure] = nrml.read(fname, stop=stop) if not expos...
python
def _get_exposure(fname, stop=None): [exposure] = nrml.read(fname, stop=stop) if not exposure.tag.endswith('exposureModel'): raise InvalidFile('%s: expected exposureModel, got %s' % (fname, exposure.tag)) description = exposure.description try: conversions ...
[ "def", "_get_exposure", "(", "fname", ",", "stop", "=", "None", ")", ":", "[", "exposure", "]", "=", "nrml", ".", "read", "(", "fname", ",", "stop", "=", "stop", ")", "if", "not", "exposure", ".", "tag", ".", "endswith", "(", "'exposureModel'", ")", ...
:param fname: path of the XML file containing the exposure :param stop: node at which to stop parsing (or None) :returns: a pair (Exposure instance, list of asset nodes)
[ ":", "param", "fname", ":", "path", "of", "the", "XML", "file", "containing", "the", "exposure", ":", "param", "stop", ":", "node", "at", "which", "to", "stop", "parsing", "(", "or", "None", ")", ":", "returns", ":", "a", "pair", "(", "Exposure", "in...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L665-L762
gem/oq-engine
openquake/risklib/asset.py
CostCalculator.get_units
def get_units(self, loss_types): """ :param: a list of loss types :returns: an array of units as byte strings, suitable for HDF5 """ lst = [] for lt in loss_types: if lt.endswith('_ins'): lt = lt[:-4] if lt == 'occupants': ...
python
def get_units(self, loss_types): lst = [] for lt in loss_types: if lt.endswith('_ins'): lt = lt[:-4] if lt == 'occupants': unit = 'people' else: unit = self.units[lt] lst.append(encode(unit)) ...
[ "def", "get_units", "(", "self", ",", "loss_types", ")", ":", "lst", "=", "[", "]", "for", "lt", "in", "loss_types", ":", "if", "lt", ".", "endswith", "(", "'_ins'", ")", ":", "lt", "=", "lt", "[", ":", "-", "4", "]", "if", "lt", "==", "'occupa...
:param: a list of loss types :returns: an array of units as byte strings, suitable for HDF5
[ ":", "param", ":", "a", "list", "of", "loss", "types", ":", "returns", ":", "an", "array", "of", "units", "as", "byte", "strings", "suitable", "for", "HDF5" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L82-L96
gem/oq-engine
openquake/risklib/asset.py
Asset.value
def value(self, loss_type, time_event=None): """ :returns: the total asset value for `loss_type` """ if loss_type == 'occupants': return self.values['occupants_' + str(time_event)] try: # extract from the cache val = self._cost[loss_type] except K...
python
def value(self, loss_type, time_event=None): if loss_type == 'occupants': return self.values['occupants_' + str(time_event)] try: val = self._cost[loss_type] except KeyError: val = self.calc(loss_type, self.values, self.area, self.number) ...
[ "def", "value", "(", "self", ",", "loss_type", ",", "time_event", "=", "None", ")", ":", "if", "loss_type", "==", "'occupants'", ":", "return", "self", ".", "values", "[", "'occupants_'", "+", "str", "(", "time_event", ")", "]", "try", ":", "# extract fr...
:returns: the total asset value for `loss_type`
[ ":", "returns", ":", "the", "total", "asset", "value", "for", "loss_type" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L195-L206
gem/oq-engine
openquake/risklib/asset.py
Asset.deductible
def deductible(self, loss_type, dummy=None): """ :returns: the deductible fraction of the asset cost for `loss_type` """ val = self.calc(loss_type, self.deductibles, self.area, self.number) if self.calc.deduct_abs: # convert to relative value return val / self.calc(l...
python
def deductible(self, loss_type, dummy=None): val = self.calc(loss_type, self.deductibles, self.area, self.number) if self.calc.deduct_abs: return val / self.calc(loss_type, self.values, self.area, self.number) else: return val
[ "def", "deductible", "(", "self", ",", "loss_type", ",", "dummy", "=", "None", ")", ":", "val", "=", "self", ".", "calc", "(", "loss_type", ",", "self", ".", "deductibles", ",", "self", ".", "area", ",", "self", ".", "number", ")", "if", "self", "....
:returns: the deductible fraction of the asset cost for `loss_type`
[ ":", "returns", ":", "the", "deductible", "fraction", "of", "the", "asset", "cost", "for", "loss_type" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L208-L217
gem/oq-engine
openquake/risklib/asset.py
Asset.insurance_limit
def insurance_limit(self, loss_type, dummy=None): """ :returns: the limit fraction of the asset cost for `loss_type` """ val = self.calc(loss_type, self.insurance_limits, self.area, self.number) if self.calc.limit_abs: # convert to relative value ...
python
def insurance_limit(self, loss_type, dummy=None): val = self.calc(loss_type, self.insurance_limits, self.area, self.number) if self.calc.limit_abs: return val / self.calc(loss_type, self.values, self.area, self.number) ...
[ "def", "insurance_limit", "(", "self", ",", "loss_type", ",", "dummy", "=", "None", ")", ":", "val", "=", "self", ".", "calc", "(", "loss_type", ",", "self", ".", "insurance_limits", ",", "self", ".", "area", ",", "self", ".", "number", ")", "if", "s...
:returns: the limit fraction of the asset cost for `loss_type`
[ ":", "returns", ":", "the", "limit", "fraction", "of", "the", "asset", "cost", "for", "loss_type" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L219-L229
gem/oq-engine
openquake/risklib/asset.py
Asset.retrofitted
def retrofitted(self): """ :returns: the asset retrofitted value """ return self.calc('structural', {'structural': self._retrofitted}, self.area, self.number)
python
def retrofitted(self): return self.calc('structural', {'structural': self._retrofitted}, self.area, self.number)
[ "def", "retrofitted", "(", "self", ")", ":", "return", "self", ".", "calc", "(", "'structural'", ",", "{", "'structural'", ":", "self", ".", "_retrofitted", "}", ",", "self", ".", "area", ",", "self", ".", "number", ")" ]
:returns: the asset retrofitted value
[ ":", "returns", ":", "the", "asset", "retrofitted", "value" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L231-L236
gem/oq-engine
openquake/risklib/asset.py
Asset.tagmask
def tagmask(self, tags): """ :returns: a boolean array with True where the assets has tags """ mask = numpy.zeros(len(tags), bool) for t, tag in enumerate(tags): tagname, tagvalue = tag.split('=') mask[t] = self.tagvalue(tagname) == tagvalue return...
python
def tagmask(self, tags): mask = numpy.zeros(len(tags), bool) for t, tag in enumerate(tags): tagname, tagvalue = tag.split('=') mask[t] = self.tagvalue(tagname) == tagvalue return mask
[ "def", "tagmask", "(", "self", ",", "tags", ")", ":", "mask", "=", "numpy", ".", "zeros", "(", "len", "(", "tags", ")", ",", "bool", ")", "for", "t", ",", "tag", "in", "enumerate", "(", "tags", ")", ":", "tagname", ",", "tagvalue", "=", "tag", ...
:returns: a boolean array with True where the assets has tags
[ ":", "returns", ":", "a", "boolean", "array", "with", "True", "where", "the", "assets", "has", "tags" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L238-L246
gem/oq-engine
openquake/risklib/asset.py
TagCollection.add
def add(self, tagname, tagvalue): """ :returns: numeric index associated to the tag """ dic = getattr(self, tagname + '_idx') try: return dic[tagvalue] except KeyError: dic[tagvalue] = idx = len(dic) getattr(self, tagname).append(tagval...
python
def add(self, tagname, tagvalue): dic = getattr(self, tagname + '_idx') try: return dic[tagvalue] except KeyError: dic[tagvalue] = idx = len(dic) getattr(self, tagname).append(tagvalue) if idx > TWO16: raise InvalidFile('co...
[ "def", "add", "(", "self", ",", "tagname", ",", "tagvalue", ")", ":", "dic", "=", "getattr", "(", "self", ",", "tagname", "+", "'_idx'", ")", "try", ":", "return", "dic", "[", "tagvalue", "]", "except", "KeyError", ":", "dic", "[", "tagvalue", "]", ...
:returns: numeric index associated to the tag
[ ":", "returns", ":", "numeric", "index", "associated", "to", "the", "tag" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L287-L299
gem/oq-engine
openquake/risklib/asset.py
TagCollection.add_tags
def add_tags(self, dic, prefix): """ :param dic: a dictionary tagname -> tagvalue :returns: a list of tag indices, one per tagname """ # fill missing tagvalues with "?", raise an error for unknown tagnames idxs = [] for tagname in self.tagnames: if tag...
python
def add_tags(self, dic, prefix): idxs = [] for tagname in self.tagnames: if tagname in ('exposure', 'country'): idxs.append(self.add(tagname, prefix)) continue try: tagvalue = dic.pop(tagname) except Ke...
[ "def", "add_tags", "(", "self", ",", "dic", ",", "prefix", ")", ":", "# fill missing tagvalues with \"?\", raise an error for unknown tagnames", "idxs", "=", "[", "]", "for", "tagname", "in", "self", ".", "tagnames", ":", "if", "tagname", "in", "(", "'exposure'", ...
:param dic: a dictionary tagname -> tagvalue :returns: a list of tag indices, one per tagname
[ ":", "param", "dic", ":", "a", "dictionary", "tagname", "-", ">", "tagvalue", ":", "returns", ":", "a", "list", "of", "tag", "indices", "one", "per", "tagname" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L301-L325
gem/oq-engine
openquake/risklib/asset.py
TagCollection.get_tag
def get_tag(self, tagname, tagidx): """ :returns: the tag associated to the given tagname and tag index """ return '%s=%s' % (tagname, decode(getattr(self, tagname)[tagidx]))
python
def get_tag(self, tagname, tagidx): return '%s=%s' % (tagname, decode(getattr(self, tagname)[tagidx]))
[ "def", "get_tag", "(", "self", ",", "tagname", ",", "tagidx", ")", ":", "return", "'%s=%s'", "%", "(", "tagname", ",", "decode", "(", "getattr", "(", "self", ",", "tagname", ")", "[", "tagidx", "]", ")", ")" ]
:returns: the tag associated to the given tagname and tag index
[ ":", "returns", ":", "the", "tag", "associated", "to", "the", "given", "tagname", "and", "tag", "index" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L332-L336
gem/oq-engine
openquake/risklib/asset.py
TagCollection.get_tagvalues
def get_tagvalues(self, tagnames, tagidxs): """ :returns: the tag associated to the given tagname and tag index """ values = tuple(getattr(self, tagname)[tagidx + 1] for tagidx, tagname in zip(tagidxs, tagnames)) return values
python
def get_tagvalues(self, tagnames, tagidxs): values = tuple(getattr(self, tagname)[tagidx + 1] for tagidx, tagname in zip(tagidxs, tagnames)) return values
[ "def", "get_tagvalues", "(", "self", ",", "tagnames", ",", "tagidxs", ")", ":", "values", "=", "tuple", "(", "getattr", "(", "self", ",", "tagname", ")", "[", "tagidx", "+", "1", "]", "for", "tagidx", ",", "tagname", "in", "zip", "(", "tagidxs", ",",...
:returns: the tag associated to the given tagname and tag index
[ ":", "returns", ":", "the", "tag", "associated", "to", "the", "given", "tagname", "and", "tag", "index" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L338-L344
gem/oq-engine
openquake/risklib/asset.py
TagCollection.gen_tags
def gen_tags(self, tagname): """ :yields: the tags associated to the given tagname """ for tagvalue in getattr(self, tagname): yield '%s=%s' % (tagname, decode(tagvalue))
python
def gen_tags(self, tagname): for tagvalue in getattr(self, tagname): yield '%s=%s' % (tagname, decode(tagvalue))
[ "def", "gen_tags", "(", "self", ",", "tagname", ")", ":", "for", "tagvalue", "in", "getattr", "(", "self", ",", "tagname", ")", ":", "yield", "'%s=%s'", "%", "(", "tagname", ",", "decode", "(", "tagvalue", ")", ")" ]
:yields: the tags associated to the given tagname
[ ":", "yields", ":", "the", "tags", "associated", "to", "the", "given", "tagname" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L346-L351
gem/oq-engine
openquake/risklib/asset.py
TagCollection.agg_shape
def agg_shape(self, shp, aggregate_by): """ :returns: a shape shp + (T, ...) depending on the tagnames """ return shp + tuple( len(getattr(self, tagname)) - 1 for tagname in aggregate_by)
python
def agg_shape(self, shp, aggregate_by): return shp + tuple( len(getattr(self, tagname)) - 1 for tagname in aggregate_by)
[ "def", "agg_shape", "(", "self", ",", "shp", ",", "aggregate_by", ")", ":", "return", "shp", "+", "tuple", "(", "len", "(", "getattr", "(", "self", ",", "tagname", ")", ")", "-", "1", "for", "tagname", "in", "aggregate_by", ")" ]
:returns: a shape shp + (T, ...) depending on the tagnames
[ ":", "returns", ":", "a", "shape", "shp", "+", "(", "T", "...", ")", "depending", "on", "the", "tagnames" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L353-L358
gem/oq-engine
openquake/risklib/asset.py
AssetCollection.num_taxonomies_by_site
def num_taxonomies_by_site(self): """ :returns: an array with the number of assets per each site """ dic = general.group_array(self.array, 'site_id') num_taxonomies = numpy.zeros(self.tot_sites, U32) for sid, arr in dic.items(): num_taxonomies[sid] = len(numpy...
python
def num_taxonomies_by_site(self): dic = general.group_array(self.array, 'site_id') num_taxonomies = numpy.zeros(self.tot_sites, U32) for sid, arr in dic.items(): num_taxonomies[sid] = len(numpy.unique(arr['taxonomy'])) return num_taxonomies
[ "def", "num_taxonomies_by_site", "(", "self", ")", ":", "dic", "=", "general", ".", "group_array", "(", "self", ".", "array", ",", "'site_id'", ")", "num_taxonomies", "=", "numpy", ".", "zeros", "(", "self", ".", "tot_sites", ",", "U32", ")", "for", "sid...
:returns: an array with the number of assets per each site
[ ":", "returns", ":", "an", "array", "with", "the", "number", "of", "assets", "per", "each", "site" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L426-L434
gem/oq-engine
openquake/risklib/asset.py
AssetCollection.get_aids_by_tag
def get_aids_by_tag(self): """ :returns: dict tag -> asset ordinals """ aids_by_tag = general.AccumDict(accum=set()) for aid, ass in enumerate(self): for tagname in self.tagnames: tag = self.tagcol.get_tag(tagname, ass[tagname]) aids_by...
python
def get_aids_by_tag(self): aids_by_tag = general.AccumDict(accum=set()) for aid, ass in enumerate(self): for tagname in self.tagnames: tag = self.tagcol.get_tag(tagname, ass[tagname]) aids_by_tag[tag].add(aid) return aids_by_tag
[ "def", "get_aids_by_tag", "(", "self", ")", ":", "aids_by_tag", "=", "general", ".", "AccumDict", "(", "accum", "=", "set", "(", ")", ")", "for", "aid", ",", "ass", "in", "enumerate", "(", "self", ")", ":", "for", "tagname", "in", "self", ".", "tagna...
:returns: dict tag -> asset ordinals
[ ":", "returns", ":", "dict", "tag", "-", ">", "asset", "ordinals" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L436-L445
gem/oq-engine
openquake/risklib/asset.py
AssetCollection.assets_by_site
def assets_by_site(self): """ :returns: numpy array of lists with the assets by each site """ assets_by_site = [[] for sid in range(self.tot_sites)] for i, ass in enumerate(self.array): assets_by_site[ass['site_id']].append(self[i]) return numpy.array(assets_b...
python
def assets_by_site(self): assets_by_site = [[] for sid in range(self.tot_sites)] for i, ass in enumerate(self.array): assets_by_site[ass['site_id']].append(self[i]) return numpy.array(assets_by_site)
[ "def", "assets_by_site", "(", "self", ")", ":", "assets_by_site", "=", "[", "[", "]", "for", "sid", "in", "range", "(", "self", ".", "tot_sites", ")", "]", "for", "i", ",", "ass", "in", "enumerate", "(", "self", ".", "array", ")", ":", "assets_by_sit...
:returns: numpy array of lists with the assets by each site
[ ":", "returns", ":", "numpy", "array", "of", "lists", "with", "the", "assets", "by", "each", "site" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L454-L461
gem/oq-engine
openquake/risklib/asset.py
AssetCollection.aggregate_by
def aggregate_by(self, tagnames, array): """ :param tagnames: a list of valid tag names :param array: an array with the same length as the asset collection :returns: an array of aggregate values with the proper shape """ missing = set(tagnames) - set(self.tagcol.tagnames)...
python
def aggregate_by(self, tagnames, array): missing = set(tagnames) - set(self.tagcol.tagnames) if missing: raise ValueError('Unknown tagname(s) %s' % missing) A, *shp = array.shape if A != len(self): raise ValueError('The array must have length %d, got %d' ...
[ "def", "aggregate_by", "(", "self", ",", "tagnames", ",", "array", ")", ":", "missing", "=", "set", "(", "tagnames", ")", "-", "set", "(", "self", ".", "tagcol", ".", "tagnames", ")", "if", "missing", ":", "raise", "ValueError", "(", "'Unknown tagname(s)...
:param tagnames: a list of valid tag names :param array: an array with the same length as the asset collection :returns: an array of aggregate values with the proper shape
[ ":", "param", "tagnames", ":", "a", "list", "of", "valid", "tag", "names", ":", "param", "array", ":", "an", "array", "with", "the", "same", "length", "as", "the", "asset", "collection", ":", "returns", ":", "an", "array", "of", "aggregate", "values", ...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L463-L482
gem/oq-engine
openquake/risklib/asset.py
AssetCollection.agg_value
def agg_value(self, *tagnames): """ :param tagnames: tagnames of lengths T1, T2, ... respectively :returns: the values of the exposure aggregated by tagnames as an array of shape (T1, T2, ..., L) """ aval = numpy.zeros((len(self), len(self.loss...
python
def agg_value(self, *tagnames): aval = numpy.zeros((len(self), len(self.loss_types)), F32) for asset in self: for lti, lt in enumerate(self.loss_types): if lt == 'occupants': aval[asset['ordinal'], lti] = asset[lt + '_None'] else...
[ "def", "agg_value", "(", "self", ",", "*", "tagnames", ")", ":", "aval", "=", "numpy", ".", "zeros", "(", "(", "len", "(", "self", ")", ",", "len", "(", "self", ".", "loss_types", ")", ")", ",", "F32", ")", "# (A, L)", "for", "asset", "in", "self...
:param tagnames: tagnames of lengths T1, T2, ... respectively :returns: the values of the exposure aggregated by tagnames as an array of shape (T1, T2, ..., L)
[ ":", "param", "tagnames", ":", "tagnames", "of", "lengths", "T1", "T2", "...", "respectively", ":", "returns", ":", "the", "values", "of", "the", "exposure", "aggregated", "by", "tagnames", "as", "an", "array", "of", "shape", "(", "T1", "T2", "...", "L",...
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L484-L499
gem/oq-engine
openquake/risklib/asset.py
AssetCollection.reduce
def reduce(self, sitecol): """ :returns: a reduced AssetCollection on the given sitecol """ ok_indices = numpy.sum( [self.array['site_id'] == sid for sid in sitecol.sids], axis=0, dtype=bool) new = object.__new__(self.__class__) vars(new).update(va...
python
def reduce(self, sitecol): ok_indices = numpy.sum( [self.array['site_id'] == sid for sid in sitecol.sids], axis=0, dtype=bool) new = object.__new__(self.__class__) vars(new).update(vars(self)) new.array = self.array[ok_indices] new.array['ordinal'...
[ "def", "reduce", "(", "self", ",", "sitecol", ")", ":", "ok_indices", "=", "numpy", ".", "sum", "(", "[", "self", ".", "array", "[", "'site_id'", "]", "==", "sid", "for", "sid", "in", "sitecol", ".", "sids", "]", ",", "axis", "=", "0", ",", "dtyp...
:returns: a reduced AssetCollection on the given sitecol
[ ":", "returns", ":", "a", "reduced", "AssetCollection", "on", "the", "given", "sitecol" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L501-L513
gem/oq-engine
openquake/risklib/asset.py
AssetCollection.reduce_also
def reduce_also(self, sitecol): """ :returns: a reduced AssetCollection on the given sitecol NB: diffently from .reduce, also the SiteCollection is reduced and turned into a complete site collection. """ array = [] asset_refs = [] for idx, sid in enumerate...
python
def reduce_also(self, sitecol): array = [] asset_refs = [] for idx, sid in enumerate(sitecol.sids): mask = self.array['site_id'] == sid arr = self.array[mask] arr['site_id'] = idx array.append(arr) asset_refs.append(self.asset_...
[ "def", "reduce_also", "(", "self", ",", "sitecol", ")", ":", "array", "=", "[", "]", "asset_refs", "=", "[", "]", "for", "idx", ",", "sid", "in", "enumerate", "(", "sitecol", ".", "sids", ")", ":", "mask", "=", "self", ".", "array", "[", "'site_id'...
:returns: a reduced AssetCollection on the given sitecol NB: diffently from .reduce, also the SiteCollection is reduced and turned into a complete site collection.
[ ":", "returns", ":", "a", "reduced", "AssetCollection", "on", "the", "given", "sitecol", "NB", ":", "diffently", "from", ".", "reduce", "also", "the", "SiteCollection", "is", "reduced", "and", "turned", "into", "a", "complete", "site", "collection", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/asset.py#L515-L536
End of preview. Expand in Data Studio

YAML Metadata Warning:empty or missing yaml metadata in repo card

Check out the documentation for more information.

Cleaning

Unlike the original dataset, the func_code_string column was updated to remove any comments and keep just the code. The original version can still be found in the whole_func_string.

import re

def remove_comments_docstrings(code, language):
    if language == 'python':
        # Remove docstrings
        code = re.sub(r'"""(.*?)"""', '', code, flags=re.DOTALL)
        code = re.sub(r"'''(.*?)'''", '', code, flags=re.DOTALL)
        # Remove comments
        code = re.sub(r'#.*', '', code)
    elif language == 'java' or language == 'javascript':
        # Remove multiline comments
        code = re.sub(r'/\*.*?\*/', '', code, flags=re.DOTALL)
        # Remove single line comments
        code = re.sub(r'//.*', '', code)
    elif language == 'go':
        # Similar to Java/Javascript
        code = re.sub(r'/\*.*?\*/', '', code, flags=re.DOTALL)
        code = re.sub(r'//.*', '', code)
    elif language == 'ruby':
        # Remove multiline comments
        code = re.sub(r'=begin.*?=end', '', code, flags=re.DOTALL)
        # Remove single line comments
        code = re.sub(r'#.*', '', code)
    elif language == 'php':
        # Remove multiline comments
        code = re.sub(r'/\*.*?\*/', '', code, flags=re.DOTALL)
        # Remove single line and hash comments
        code = re.sub(r'//.*', '', code)
        code = re.sub(r'#.*', '', code)
    return code.strip()

The validity of that snippet can be tested with the following example:

# Example DataFrame
import pandas as pd
example = {
  'language': ['python', 'java', 'javascript', 'go', 'ruby', 'php'],
  'func_code_string': [
    '"""Example docstring""" def foo(): # This is a comment\n    return 1',
    '/** Java doc */ public class Test { // Comment\n public void method() {} }',
    '/* JS doc */ function test() { // Comment\n return true; }',
    '/* Go doc */ package main // Import comment\nimport "fmt"',
    '=begin Ruby doc =end def foo # Comment\n 1 + 1 end',
    '<?php /* PHP doc */ // Comment\necho "Hello"; # Another comment ?>'
]}
example_df = pd.DataFrame(example)

example_df['cleaned_code'] = example_df.apply(lambda x: remove_comments_docstrings(x['func_code_string'], x['language']), axis=1)
print(example_df[['language', 'cleaned_code']])
Downloads last month
45