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/hazardlib/gsim/utils_swiss_gmpe.py
_compute_C1_term
def _compute_C1_term(C, dists): """ Return C1 coeffs as function of Rrup as proposed by Rodriguez-Marek et al (2013) The C1 coeff are used to compute the single station sigma """ c1_dists = np.zeros_like(dists) idx = dists < C['Rc11'] c1_dists[idx] = C['phi_11'] idx = (dists >= C['Rc11']) & (dists <= C['Rc21']) c1_dists[idx] = C['phi_11'] + (C['phi_21'] - C['phi_11']) * \ ((dists[idx] - C['Rc11']) / (C['Rc21'] - C['Rc11'])) idx = dists > C['Rc21'] c1_dists[idx] = C['phi_21'] return c1_dists
python
def _compute_C1_term(C, dists): c1_dists = np.zeros_like(dists) idx = dists < C['Rc11'] c1_dists[idx] = C['phi_11'] idx = (dists >= C['Rc11']) & (dists <= C['Rc21']) c1_dists[idx] = C['phi_11'] + (C['phi_21'] - C['phi_11']) * \ ((dists[idx] - C['Rc11']) / (C['Rc21'] - C['Rc11'])) idx = dists > C['Rc21'] c1_dists[idx] = C['phi_21'] return c1_dists
[ "def", "_compute_C1_term", "(", "C", ",", "dists", ")", ":", "c1_dists", "=", "np", ".", "zeros_like", "(", "dists", ")", "idx", "=", "dists", "<", "C", "[", "'Rc11'", "]", "c1_dists", "[", "idx", "]", "=", "C", "[", "'phi_11'", "]", "idx", "=", "(", "dists", ">=", "C", "[", "'Rc11'", "]", ")", "&", "(", "dists", "<=", "C", "[", "'Rc21'", "]", ")", "c1_dists", "[", "idx", "]", "=", "C", "[", "'phi_11'", "]", "+", "(", "C", "[", "'phi_21'", "]", "-", "C", "[", "'phi_11'", "]", ")", "*", "(", "(", "dists", "[", "idx", "]", "-", "C", "[", "'Rc11'", "]", ")", "/", "(", "C", "[", "'Rc21'", "]", "-", "C", "[", "'Rc11'", "]", ")", ")", "idx", "=", "dists", ">", "C", "[", "'Rc21'", "]", "c1_dists", "[", "idx", "]", "=", "C", "[", "'phi_21'", "]", "return", "c1_dists" ]
Return C1 coeffs as function of Rrup as proposed by Rodriguez-Marek et al (2013) The C1 coeff are used to compute the single station sigma
[ "Return", "C1", "coeffs", "as", "function", "of", "Rrup", "as", "proposed", "by", "Rodriguez", "-", "Marek", "et", "al", "(", "2013", ")", "The", "C1", "coeff", "are", "used", "to", "compute", "the", "single", "station", "sigma" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/utils_swiss_gmpe.py#L22-L37
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): 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" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/utils_swiss_gmpe.py#L40-L52
gem/oq-engine
openquake/hazardlib/gsim/utils_swiss_gmpe.py
_compute_phi_ss
def _compute_phi_ss(C, mag, c1_dists, log_phi_ss, mean_phi_ss): """ Returns the embeded logic tree for single station sigma as defined to be used in the Swiss Hazard Model 2014: the single station sigma branching levels combines with equal weights: the phi_ss reported as function of magnitude as proposed by Rodriguez-Marek et al (2013) with the mean (mean_phi_ss) single station value; the resulted phi_ss is in natural logarithm units """ phi_ss = 0 if mag < C['Mc1']: phi_ss = c1_dists elif mag >= C['Mc1'] and mag <= C['Mc2']: phi_ss = c1_dists + \ (C['C2'] - c1_dists) * \ ((mag - C['Mc1']) / (C['Mc2'] - C['Mc1'])) elif mag > C['Mc2']: phi_ss = C['C2'] return (phi_ss * 0.50 + mean_phi_ss * 0.50) / log_phi_ss
python
def _compute_phi_ss(C, mag, c1_dists, log_phi_ss, mean_phi_ss): phi_ss = 0 if mag < C['Mc1']: phi_ss = c1_dists elif mag >= C['Mc1'] and mag <= C['Mc2']: phi_ss = c1_dists + \ (C['C2'] - c1_dists) * \ ((mag - C['Mc1']) / (C['Mc2'] - C['Mc1'])) elif mag > C['Mc2']: phi_ss = C['C2'] return (phi_ss * 0.50 + mean_phi_ss * 0.50) / log_phi_ss
[ "def", "_compute_phi_ss", "(", "C", ",", "mag", ",", "c1_dists", ",", "log_phi_ss", ",", "mean_phi_ss", ")", ":", "phi_ss", "=", "0", "if", "mag", "<", "C", "[", "'Mc1'", "]", ":", "phi_ss", "=", "c1_dists", "elif", "mag", ">=", "C", "[", "'Mc1'", "]", "and", "mag", "<=", "C", "[", "'Mc2'", "]", ":", "phi_ss", "=", "c1_dists", "+", "(", "C", "[", "'C2'", "]", "-", "c1_dists", ")", "*", "(", "(", "mag", "-", "C", "[", "'Mc1'", "]", ")", "/", "(", "C", "[", "'Mc2'", "]", "-", "C", "[", "'Mc1'", "]", ")", ")", "elif", "mag", ">", "C", "[", "'Mc2'", "]", ":", "phi_ss", "=", "C", "[", "'C2'", "]", "return", "(", "phi_ss", "*", "0.50", "+", "mean_phi_ss", "*", "0.50", ")", "/", "log_phi_ss" ]
Returns the embeded logic tree for single station sigma as defined to be used in the Swiss Hazard Model 2014: the single station sigma branching levels combines with equal weights: the phi_ss reported as function of magnitude as proposed by Rodriguez-Marek et al (2013) with the mean (mean_phi_ss) single station value; the resulted phi_ss is in natural logarithm units
[ "Returns", "the", "embeded", "logic", "tree", "for", "single", "station", "sigma", "as", "defined", "to", "be", "used", "in", "the", "Swiss", "Hazard", "Model", "2014", ":", "the", "single", "station", "sigma", "branching", "levels", "combines", "with", "equal", "weights", ":", "the", "phi_ss", "reported", "as", "function", "of", "magnitude", "as", "proposed", "by", "Rodriguez", "-", "Marek", "et", "al", "(", "2013", ")", "with", "the", "mean", "(", "mean_phi_ss", ")", "single", "station", "value", ";", "the", "resulted", "phi_ss", "is", "in", "natural", "logarithm", "units" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/utils_swiss_gmpe.py#L55-L78
gem/oq-engine
openquake/hazardlib/gsim/utils_swiss_gmpe.py
_get_corr_stddevs
def _get_corr_stddevs(C, tau_ss, stddev_types, num_sites, phi_ss, NL=None, tau_value=None): """ Return standard deviations adjusted for single station sigma as the total standard deviation - as proposed to be used in the Swiss Hazard Model [2014]. """ stddevs = [] temp_stddev = phi_ss * phi_ss if tau_value is not None and NL is not None: temp_stddev = temp_stddev + tau_value * tau_value * ((1 + NL) ** 2) else: temp_stddev = temp_stddev + C[tau_ss] * C[tau_ss] for stddev_type in stddev_types: if stddev_type == const.StdDev.TOTAL: stddevs.append(np.sqrt(temp_stddev) + np.zeros(num_sites)) return stddevs
python
def _get_corr_stddevs(C, tau_ss, stddev_types, num_sites, phi_ss, NL=None, tau_value=None): stddevs = [] temp_stddev = phi_ss * phi_ss if tau_value is not None and NL is not None: temp_stddev = temp_stddev + tau_value * tau_value * ((1 + NL) ** 2) else: temp_stddev = temp_stddev + C[tau_ss] * C[tau_ss] for stddev_type in stddev_types: if stddev_type == const.StdDev.TOTAL: stddevs.append(np.sqrt(temp_stddev) + np.zeros(num_sites)) return stddevs
[ "def", "_get_corr_stddevs", "(", "C", ",", "tau_ss", ",", "stddev_types", ",", "num_sites", ",", "phi_ss", ",", "NL", "=", "None", ",", "tau_value", "=", "None", ")", ":", "stddevs", "=", "[", "]", "temp_stddev", "=", "phi_ss", "*", "phi_ss", "if", "tau_value", "is", "not", "None", "and", "NL", "is", "not", "None", ":", "temp_stddev", "=", "temp_stddev", "+", "tau_value", "*", "tau_value", "*", "(", "(", "1", "+", "NL", ")", "**", "2", ")", "else", ":", "temp_stddev", "=", "temp_stddev", "+", "C", "[", "tau_ss", "]", "*", "C", "[", "tau_ss", "]", "for", "stddev_type", "in", "stddev_types", ":", "if", "stddev_type", "==", "const", ".", "StdDev", ".", "TOTAL", ":", "stddevs", ".", "append", "(", "np", ".", "sqrt", "(", "temp_stddev", ")", "+", "np", ".", "zeros", "(", "num_sites", ")", ")", "return", "stddevs" ]
Return standard deviations adjusted for single station sigma as the total standard deviation - as proposed to be used in the Swiss Hazard Model [2014].
[ "Return", "standard", "deviations", "adjusted", "for", "single", "station", "sigma", "as", "the", "total", "standard", "deviation", "-", "as", "proposed", "to", "be", "used", "in", "the", "Swiss", "Hazard", "Model", "[", "2014", "]", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/utils_swiss_gmpe.py#L81-L99
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): 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", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/utils_swiss_gmpe.py#L102-L125
gem/oq-engine
openquake/commonlib/source.py
CompositionInfo.fake
def fake(cls, gsimlt=None): """ :returns: a fake `CompositionInfo` instance with the given gsim logic tree object; if None, builds automatically a fake gsim logic tree """ weight = 1 gsim_lt = gsimlt or logictree.GsimLogicTree.from_('[FromFile]') fakeSM = logictree.LtSourceModel( 'scenario', weight, 'b1', [sourceconverter.SourceGroup('*', eff_ruptures=1)], gsim_lt.get_num_paths(), ordinal=0, samples=1) return cls(gsim_lt, seed=0, num_samples=0, source_models=[fakeSM], totweight=0)
python
def fake(cls, gsimlt=None): weight = 1 gsim_lt = gsimlt or logictree.GsimLogicTree.from_('[FromFile]') fakeSM = logictree.LtSourceModel( 'scenario', weight, 'b1', [sourceconverter.SourceGroup('*', eff_ruptures=1)], gsim_lt.get_num_paths(), ordinal=0, samples=1) return cls(gsim_lt, seed=0, num_samples=0, source_models=[fakeSM], totweight=0)
[ "def", "fake", "(", "cls", ",", "gsimlt", "=", "None", ")", ":", "weight", "=", "1", "gsim_lt", "=", "gsimlt", "or", "logictree", ".", "GsimLogicTree", ".", "from_", "(", "'[FromFile]'", ")", "fakeSM", "=", "logictree", ".", "LtSourceModel", "(", "'scenario'", ",", "weight", ",", "'b1'", ",", "[", "sourceconverter", ".", "SourceGroup", "(", "'*'", ",", "eff_ruptures", "=", "1", ")", "]", ",", "gsim_lt", ".", "get_num_paths", "(", ")", ",", "ordinal", "=", "0", ",", "samples", "=", "1", ")", "return", "cls", "(", "gsim_lt", ",", "seed", "=", "0", ",", "num_samples", "=", "0", ",", "source_models", "=", "[", "fakeSM", "]", ",", "totweight", "=", "0", ")" ]
:returns: a fake `CompositionInfo` instance with the given gsim logic tree object; if None, builds automatically a fake gsim logic tree
[ ":", "returns", ":", "a", "fake", "CompositionInfo", "instance", "with", "the", "given", "gsim", "logic", "tree", "object", ";", "if", "None", "builds", "automatically", "a", "fake", "gsim", "logic", "tree" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L107-L120
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): 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", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L142-L150
gem/oq-engine
openquake/commonlib/source.py
CompositionInfo.classify_gsim_lt
def classify_gsim_lt(self, source_model): """ :returns: (kind, num_paths), where kind is trivial, simple, complex """ trts = set(sg.trt for sg in source_model.src_groups if sg.eff_ruptures) gsim_lt = self.gsim_lt.reduce(trts) num_branches = list(gsim_lt.get_num_branches().values()) num_paths = gsim_lt.get_num_paths() num_gsims = '(%s)' % ','.join(map(str, num_branches)) multi_gsim_trts = sum(1 for num_gsim in num_branches if num_gsim > 1) if multi_gsim_trts == 0: return "trivial" + num_gsims, num_paths elif multi_gsim_trts == 1: return "simple" + num_gsims, num_paths else: return "complex" + num_gsims, num_paths
python
def classify_gsim_lt(self, source_model): trts = set(sg.trt for sg in source_model.src_groups if sg.eff_ruptures) gsim_lt = self.gsim_lt.reduce(trts) num_branches = list(gsim_lt.get_num_branches().values()) num_paths = gsim_lt.get_num_paths() num_gsims = '(%s)' % ','.join(map(str, num_branches)) multi_gsim_trts = sum(1 for num_gsim in num_branches if num_gsim > 1) if multi_gsim_trts == 0: return "trivial" + num_gsims, num_paths elif multi_gsim_trts == 1: return "simple" + num_gsims, num_paths else: return "complex" + num_gsims, num_paths
[ "def", "classify_gsim_lt", "(", "self", ",", "source_model", ")", ":", "trts", "=", "set", "(", "sg", ".", "trt", "for", "sg", "in", "source_model", ".", "src_groups", "if", "sg", ".", "eff_ruptures", ")", "gsim_lt", "=", "self", ".", "gsim_lt", ".", "reduce", "(", "trts", ")", "num_branches", "=", "list", "(", "gsim_lt", ".", "get_num_branches", "(", ")", ".", "values", "(", ")", ")", "num_paths", "=", "gsim_lt", ".", "get_num_paths", "(", ")", "num_gsims", "=", "'(%s)'", "%", "','", ".", "join", "(", "map", "(", "str", ",", "num_branches", ")", ")", "multi_gsim_trts", "=", "sum", "(", "1", "for", "num_gsim", "in", "num_branches", "if", "num_gsim", ">", "1", ")", "if", "multi_gsim_trts", "==", "0", ":", "return", "\"trivial\"", "+", "num_gsims", ",", "num_paths", "elif", "multi_gsim_trts", "==", "1", ":", "return", "\"simple\"", "+", "num_gsims", ",", "num_paths", "else", ":", "return", "\"complex\"", "+", "num_gsims", ",", "num_paths" ]
:returns: (kind, num_paths), where kind is trivial, simple, complex
[ ":", "returns", ":", "(", "kind", "num_paths", ")", "where", "kind", "is", "trivial", "simple", "complex" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L152-L167
gem/oq-engine
openquake/commonlib/source.py
CompositionInfo.get_samples_by_grp
def get_samples_by_grp(self): """ :returns: a dictionary src_group_id -> source_model.samples """ return {grp.id: sm.samples for sm in self.source_models for grp in sm.src_groups}
python
def get_samples_by_grp(self): return {grp.id: sm.samples for sm in self.source_models for grp in sm.src_groups}
[ "def", "get_samples_by_grp", "(", "self", ")", ":", "return", "{", "grp", ".", "id", ":", "sm", ".", "samples", "for", "sm", "in", "self", ".", "source_models", "for", "grp", "in", "sm", ".", "src_groups", "}" ]
:returns: a dictionary src_group_id -> source_model.samples
[ ":", "returns", ":", "a", "dictionary", "src_group_id", "-", ">", "source_model", ".", "samples" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L169-L174
gem/oq-engine
openquake/commonlib/source.py
CompositionInfo.get_rlzs_by_gsim_grp
def get_rlzs_by_gsim_grp(self, sm_lt_path=None, trts=None): """ :returns: a dictionary src_group_id -> gsim -> rlzs """ self.rlzs_assoc = self.get_rlzs_assoc(sm_lt_path, trts) dic = {grp.id: self.rlzs_assoc.get_rlzs_by_gsim(grp.id) for sm in self.source_models for grp in sm.src_groups} return dic
python
def get_rlzs_by_gsim_grp(self, sm_lt_path=None, trts=None): self.rlzs_assoc = self.get_rlzs_assoc(sm_lt_path, trts) dic = {grp.id: self.rlzs_assoc.get_rlzs_by_gsim(grp.id) for sm in self.source_models for grp in sm.src_groups} return dic
[ "def", "get_rlzs_by_gsim_grp", "(", "self", ",", "sm_lt_path", "=", "None", ",", "trts", "=", "None", ")", ":", "self", ".", "rlzs_assoc", "=", "self", ".", "get_rlzs_assoc", "(", "sm_lt_path", ",", "trts", ")", "dic", "=", "{", "grp", ".", "id", ":", "self", ".", "rlzs_assoc", ".", "get_rlzs_by_gsim", "(", "grp", ".", "id", ")", "for", "sm", "in", "self", ".", "source_models", "for", "grp", "in", "sm", ".", "src_groups", "}", "return", "dic" ]
:returns: a dictionary src_group_id -> gsim -> rlzs
[ ":", "returns", ":", "a", "dictionary", "src_group_id", "-", ">", "gsim", "-", ">", "rlzs" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L176-L183
gem/oq-engine
openquake/commonlib/source.py
CompositionInfo.trt2i
def trt2i(self): """ :returns: trt -> trti """ trts = sorted(set(src_group.trt for sm in self.source_models for src_group in sm.src_groups)) return {trt: i for i, trt in enumerate(trts)}
python
def trt2i(self): trts = sorted(set(src_group.trt for sm in self.source_models for src_group in sm.src_groups)) return {trt: i for i, trt in enumerate(trts)}
[ "def", "trt2i", "(", "self", ")", ":", "trts", "=", "sorted", "(", "set", "(", "src_group", ".", "trt", "for", "sm", "in", "self", ".", "source_models", "for", "src_group", "in", "sm", ".", "src_groups", ")", ")", "return", "{", "trt", ":", "i", "for", "i", ",", "trt", "in", "enumerate", "(", "trts", ")", "}" ]
:returns: trt -> trti
[ ":", "returns", ":", "trt", "-", ">", "trti" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L189-L195
gem/oq-engine
openquake/commonlib/source.py
CompositionInfo.get_num_rlzs
def get_num_rlzs(self, source_model=None): """ :param source_model: a LtSourceModel instance (or None) :returns: the number of realizations per source model (or all) """ if source_model is None: return sum(self.get_num_rlzs(sm) for sm in self.source_models) if self.num_samples: return source_model.samples trts = set(sg.trt for sg in source_model.src_groups if sg.eff_ruptures) if sum(sg.eff_ruptures for sg in source_model.src_groups) == 0: return 0 return self.gsim_lt.reduce(trts).get_num_paths()
python
def get_num_rlzs(self, source_model=None): if source_model is None: return sum(self.get_num_rlzs(sm) for sm in self.source_models) if self.num_samples: return source_model.samples trts = set(sg.trt for sg in source_model.src_groups if sg.eff_ruptures) if sum(sg.eff_ruptures for sg in source_model.src_groups) == 0: return 0 return self.gsim_lt.reduce(trts).get_num_paths()
[ "def", "get_num_rlzs", "(", "self", ",", "source_model", "=", "None", ")", ":", "if", "source_model", "is", "None", ":", "return", "sum", "(", "self", ".", "get_num_rlzs", "(", "sm", ")", "for", "sm", "in", "self", ".", "source_models", ")", "if", "self", ".", "num_samples", ":", "return", "source_model", ".", "samples", "trts", "=", "set", "(", "sg", ".", "trt", "for", "sg", "in", "source_model", ".", "src_groups", "if", "sg", ".", "eff_ruptures", ")", "if", "sum", "(", "sg", ".", "eff_ruptures", "for", "sg", "in", "source_model", ".", "src_groups", ")", "==", "0", ":", "return", "0", "return", "self", ".", "gsim_lt", ".", "reduce", "(", "trts", ")", ".", "get_num_paths", "(", ")" ]
:param source_model: a LtSourceModel instance (or None) :returns: the number of realizations per source model (or all)
[ ":", "param", "source_model", ":", "a", "LtSourceModel", "instance", "(", "or", "None", ")", ":", "returns", ":", "the", "number", "of", "realizations", "per", "source", "model", "(", "or", "all", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L242-L254
gem/oq-engine
openquake/commonlib/source.py
CompositionInfo.rlzs
def rlzs(self): """ :returns: an array of realizations """ tups = [(r.ordinal, r.uid, r.weight['weight']) for r in self.get_rlzs_assoc().realizations] return numpy.array(tups, rlz_dt)
python
def rlzs(self): tups = [(r.ordinal, r.uid, r.weight['weight']) for r in self.get_rlzs_assoc().realizations] return numpy.array(tups, rlz_dt)
[ "def", "rlzs", "(", "self", ")", ":", "tups", "=", "[", "(", "r", ".", "ordinal", ",", "r", ".", "uid", ",", "r", ".", "weight", "[", "'weight'", "]", ")", "for", "r", "in", "self", ".", "get_rlzs_assoc", "(", ")", ".", "realizations", "]", "return", "numpy", ".", "array", "(", "tups", ",", "rlz_dt", ")" ]
:returns: an array of realizations
[ ":", "returns", ":", "an", "array", "of", "realizations" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L257-L263
gem/oq-engine
openquake/commonlib/source.py
CompositionInfo.update_eff_ruptures
def update_eff_ruptures(self, count_ruptures): """ :param count_ruptures: function or dict src_group_id -> num_ruptures """ for smodel in self.source_models: for sg in smodel.src_groups: sg.eff_ruptures = (count_ruptures(sg.id) if callable(count_ruptures) else count_ruptures.get(sg.id, 0))
python
def update_eff_ruptures(self, count_ruptures): for smodel in self.source_models: for sg in smodel.src_groups: sg.eff_ruptures = (count_ruptures(sg.id) if callable(count_ruptures) else count_ruptures.get(sg.id, 0))
[ "def", "update_eff_ruptures", "(", "self", ",", "count_ruptures", ")", ":", "for", "smodel", "in", "self", ".", "source_models", ":", "for", "sg", "in", "smodel", ".", "src_groups", ":", "sg", ".", "eff_ruptures", "=", "(", "count_ruptures", "(", "sg", ".", "id", ")", "if", "callable", "(", "count_ruptures", ")", "else", "count_ruptures", ".", "get", "(", "sg", ".", "id", ",", "0", ")", ")" ]
:param count_ruptures: function or dict src_group_id -> num_ruptures
[ ":", "param", "count_ruptures", ":", "function", "or", "dict", "src_group_id", "-", ">", "num_ruptures" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L265-L273
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): 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" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L275-L282
gem/oq-engine
openquake/commonlib/source.py
CompositionInfo.get_grp_ids
def get_grp_ids(self, sm_id): """ :returns: a list of source group IDs for the given source model ID """ return [sg.id for sg in self.source_models[sm_id].src_groups]
python
def get_grp_ids(self, sm_id): return [sg.id for sg in self.source_models[sm_id].src_groups]
[ "def", "get_grp_ids", "(", "self", ",", "sm_id", ")", ":", "return", "[", "sg", ".", "id", "for", "sg", "in", "self", ".", "source_models", "[", "sm_id", "]", ".", "src_groups", "]" ]
:returns: a list of source group IDs for the given source model ID
[ ":", "returns", ":", "a", "list", "of", "source", "group", "IDs", "for", "the", "given", "source", "model", "ID" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L284-L288
gem/oq-engine
openquake/commonlib/source.py
CompositionInfo.get_sm_by_grp
def get_sm_by_grp(self): """ :returns: a dictionary grp_id -> sm_id """ return {grp.id: sm.ordinal for sm in self.source_models for grp in sm.src_groups}
python
def get_sm_by_grp(self): return {grp.id: sm.ordinal for sm in self.source_models for grp in sm.src_groups}
[ "def", "get_sm_by_grp", "(", "self", ")", ":", "return", "{", "grp", ".", "id", ":", "sm", ".", "ordinal", "for", "sm", "in", "self", ".", "source_models", "for", "grp", "in", "sm", ".", "src_groups", "}" ]
:returns: a dictionary grp_id -> sm_id
[ ":", "returns", ":", "a", "dictionary", "grp_id", "-", ">", "sm_id" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L290-L295
gem/oq-engine
openquake/commonlib/source.py
CompositionInfo.grp_by
def grp_by(self, name): """ :returns: a dictionary grp_id -> TRT string """ dic = {} for smodel in self.source_models: for src_group in smodel.src_groups: dic[src_group.id] = getattr(src_group, name) return dic
python
def grp_by(self, name): dic = {} for smodel in self.source_models: for src_group in smodel.src_groups: dic[src_group.id] = getattr(src_group, name) return dic
[ "def", "grp_by", "(", "self", ",", "name", ")", ":", "dic", "=", "{", "}", "for", "smodel", "in", "self", ".", "source_models", ":", "for", "src_group", "in", "smodel", ".", "src_groups", ":", "dic", "[", "src_group", ".", "id", "]", "=", "getattr", "(", "src_group", ",", "name", ")", "return", "dic" ]
:returns: a dictionary grp_id -> TRT string
[ ":", "returns", ":", "a", "dictionary", "grp_id", "-", ">", "TRT", "string" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L297-L305
gem/oq-engine
openquake/commonlib/source.py
CompositeSourceModel.grp_by_src
def grp_by_src(self): """ :returns: a new CompositeSourceModel with one group per source """ smodels = [] grp_id = 0 for sm in self.source_models: src_groups = [] smodel = sm.__class__(sm.names, sm.weight, sm.path, src_groups, sm.num_gsim_paths, sm.ordinal, sm.samples) for sg in sm.src_groups: for src in sg.sources: src.src_group_id = grp_id src_groups.append( sourceconverter.SourceGroup( sg.trt, [src], name=src.source_id, id=grp_id)) grp_id += 1 smodels.append(smodel) return self.__class__(self.gsim_lt, self.source_model_lt, smodels, self.optimize_same_id)
python
def grp_by_src(self): smodels = [] grp_id = 0 for sm in self.source_models: src_groups = [] smodel = sm.__class__(sm.names, sm.weight, sm.path, src_groups, sm.num_gsim_paths, sm.ordinal, sm.samples) for sg in sm.src_groups: for src in sg.sources: src.src_group_id = grp_id src_groups.append( sourceconverter.SourceGroup( sg.trt, [src], name=src.source_id, id=grp_id)) grp_id += 1 smodels.append(smodel) return self.__class__(self.gsim_lt, self.source_model_lt, smodels, self.optimize_same_id)
[ "def", "grp_by_src", "(", "self", ")", ":", "smodels", "=", "[", "]", "grp_id", "=", "0", "for", "sm", "in", "self", ".", "source_models", ":", "src_groups", "=", "[", "]", "smodel", "=", "sm", ".", "__class__", "(", "sm", ".", "names", ",", "sm", ".", "weight", ",", "sm", ".", "path", ",", "src_groups", ",", "sm", ".", "num_gsim_paths", ",", "sm", ".", "ordinal", ",", "sm", ".", "samples", ")", "for", "sg", "in", "sm", ".", "src_groups", ":", "for", "src", "in", "sg", ".", "sources", ":", "src", ".", "src_group_id", "=", "grp_id", "src_groups", ".", "append", "(", "sourceconverter", ".", "SourceGroup", "(", "sg", ".", "trt", ",", "[", "src", "]", ",", "name", "=", "src", ".", "source_id", ",", "id", "=", "grp_id", ")", ")", "grp_id", "+=", "1", "smodels", ".", "append", "(", "smodel", ")", "return", "self", ".", "__class__", "(", "self", ".", "gsim_lt", ",", "self", ".", "source_model_lt", ",", "smodels", ",", "self", ".", "optimize_same_id", ")" ]
:returns: a new CompositeSourceModel with one group per source
[ ":", "returns", ":", "a", "new", "CompositeSourceModel", "with", "one", "group", "per", "source" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L360-L379
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): 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", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L381-L392
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): 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", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L394-L417
gem/oq-engine
openquake/commonlib/source.py
CompositeSourceModel.get_weight
def get_weight(self, weight=operator.attrgetter('weight')): """ :param weight: source weight function :returns: total weight of the source model """ return sum(weight(src) for src in self.get_sources())
python
def get_weight(self, weight=operator.attrgetter('weight')): return sum(weight(src) for src in self.get_sources())
[ "def", "get_weight", "(", "self", ",", "weight", "=", "operator", ".", "attrgetter", "(", "'weight'", ")", ")", ":", "return", "sum", "(", "weight", "(", "src", ")", "for", "src", "in", "self", ".", "get_sources", "(", ")", ")" ]
:param weight: source weight function :returns: total weight of the source model
[ ":", "param", "weight", ":", "source", "weight", "function", ":", "returns", ":", "total", "weight", "of", "the", "source", "model" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L419-L424
gem/oq-engine
openquake/commonlib/source.py
CompositeSourceModel.get_nonparametric_sources
def get_nonparametric_sources(self): """ :returns: list of non parametric sources in the composite source model """ return [src for sm in self.source_models for src_group in sm.src_groups for src in src_group if hasattr(src, 'data')]
python
def get_nonparametric_sources(self): return [src for sm in self.source_models for src_group in sm.src_groups for src in src_group if hasattr(src, 'data')]
[ "def", "get_nonparametric_sources", "(", "self", ")", ":", "return", "[", "src", "for", "sm", "in", "self", ".", "source_models", "for", "src_group", "in", "sm", ".", "src_groups", "for", "src", "in", "src_group", "if", "hasattr", "(", "src", ",", "'data'", ")", "]" ]
:returns: list of non parametric sources in the composite source model
[ ":", "returns", ":", "list", "of", "non", "parametric", "sources", "in", "the", "composite", "source", "model" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L435-L441
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): dd = collections.defaultdict(list) for src_group in self.src_groups: for src in src_group: try: srcid = src.source_id except AttributeError: 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", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L443-L464
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'): 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", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L466-L480
gem/oq-engine
openquake/commonlib/source.py
CompositeSourceModel.get_trt_sources
def get_trt_sources(self, optimize_same_id=None): """ :returns: a list of pairs [(trt, group of sources)] """ atomic = [] acc = AccumDict(accum=[]) for sm in self.source_models: for grp in sm.src_groups: if grp and grp.atomic: atomic.append((grp.trt, grp)) elif grp: acc[grp.trt].extend(grp) if optimize_same_id is None: optimize_same_id = self.optimize_same_id if optimize_same_id is False: return atomic + list(acc.items()) # extract a single source from multiple sources with the same ID n = 0 tot = 0 dic = {} for trt in acc: dic[trt] = [] for grp in groupby(acc[trt], lambda x: x.source_id).values(): src = grp[0] n += 1 tot += len(grp) # src.src_group_id can be a list if get_sources_by_trt was # called before if len(grp) > 1 and not isinstance(src.src_group_id, list): src.src_group_id = [s.src_group_id for s in grp] dic[trt].append(src) if n < tot: logging.info('Reduced %d sources to %d sources with unique IDs', tot, n) return atomic + list(dic.items())
python
def get_trt_sources(self, optimize_same_id=None): atomic = [] acc = AccumDict(accum=[]) for sm in self.source_models: for grp in sm.src_groups: if grp and grp.atomic: atomic.append((grp.trt, grp)) elif grp: acc[grp.trt].extend(grp) if optimize_same_id is None: optimize_same_id = self.optimize_same_id if optimize_same_id is False: return atomic + list(acc.items()) n = 0 tot = 0 dic = {} for trt in acc: dic[trt] = [] for grp in groupby(acc[trt], lambda x: x.source_id).values(): src = grp[0] n += 1 tot += len(grp) if len(grp) > 1 and not isinstance(src.src_group_id, list): src.src_group_id = [s.src_group_id for s in grp] dic[trt].append(src) if n < tot: logging.info('Reduced %d sources to %d sources with unique IDs', tot, n) return atomic + list(dic.items())
[ "def", "get_trt_sources", "(", "self", ",", "optimize_same_id", "=", "None", ")", ":", "atomic", "=", "[", "]", "acc", "=", "AccumDict", "(", "accum", "=", "[", "]", ")", "for", "sm", "in", "self", ".", "source_models", ":", "for", "grp", "in", "sm", ".", "src_groups", ":", "if", "grp", "and", "grp", ".", "atomic", ":", "atomic", ".", "append", "(", "(", "grp", ".", "trt", ",", "grp", ")", ")", "elif", "grp", ":", "acc", "[", "grp", ".", "trt", "]", ".", "extend", "(", "grp", ")", "if", "optimize_same_id", "is", "None", ":", "optimize_same_id", "=", "self", ".", "optimize_same_id", "if", "optimize_same_id", "is", "False", ":", "return", "atomic", "+", "list", "(", "acc", ".", "items", "(", ")", ")", "# extract a single source from multiple sources with the same ID", "n", "=", "0", "tot", "=", "0", "dic", "=", "{", "}", "for", "trt", "in", "acc", ":", "dic", "[", "trt", "]", "=", "[", "]", "for", "grp", "in", "groupby", "(", "acc", "[", "trt", "]", ",", "lambda", "x", ":", "x", ".", "source_id", ")", ".", "values", "(", ")", ":", "src", "=", "grp", "[", "0", "]", "n", "+=", "1", "tot", "+=", "len", "(", "grp", ")", "# src.src_group_id can be a list if get_sources_by_trt was", "# called before", "if", "len", "(", "grp", ")", ">", "1", "and", "not", "isinstance", "(", "src", ".", "src_group_id", ",", "list", ")", ":", "src", ".", "src_group_id", "=", "[", "s", ".", "src_group_id", "for", "s", "in", "grp", "]", "dic", "[", "trt", "]", ".", "append", "(", "src", ")", "if", "n", "<", "tot", ":", "logging", ".", "info", "(", "'Reduced %d sources to %d sources with unique IDs'", ",", "tot", ",", "n", ")", "return", "atomic", "+", "list", "(", "dic", ".", "items", "(", ")", ")" ]
:returns: a list of pairs [(trt, group of sources)]
[ ":", "returns", ":", "a", "list", "of", "pairs", "[", "(", "trt", "group", "of", "sources", ")", "]" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L482-L516
gem/oq-engine
openquake/commonlib/source.py
CompositeSourceModel.get_num_ruptures
def get_num_ruptures(self): """ :returns: the number of ruptures per source group ID """ return {grp.id: sum(src.num_ruptures for src in grp) for grp in self.src_groups}
python
def get_num_ruptures(self): return {grp.id: sum(src.num_ruptures for src in grp) for grp in self.src_groups}
[ "def", "get_num_ruptures", "(", "self", ")", ":", "return", "{", "grp", ".", "id", ":", "sum", "(", "src", ".", "num_ruptures", "for", "src", "in", "grp", ")", "for", "grp", "in", "self", ".", "src_groups", "}" ]
:returns: the number of ruptures per source group ID
[ ":", "returns", ":", "the", "number", "of", "ruptures", "per", "source", "group", "ID" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L518-L523
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): 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" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L525-L535
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): 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" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L537-L544
gem/oq-engine
openquake/commonlib/source.py
CompositeSourceModel.get_floating_spinning_factors
def get_floating_spinning_factors(self): """ :returns: (floating rupture factor, spinning rupture factor) """ data = [] for src in self.get_sources(): if hasattr(src, 'hypocenter_distribution'): data.append( (len(src.hypocenter_distribution.data), len(src.nodal_plane_distribution.data))) if not data: return numpy.array([1, 1]) return numpy.array(data).mean(axis=0)
python
def get_floating_spinning_factors(self): data = [] for src in self.get_sources(): if hasattr(src, 'hypocenter_distribution'): data.append( (len(src.hypocenter_distribution.data), len(src.nodal_plane_distribution.data))) if not data: return numpy.array([1, 1]) return numpy.array(data).mean(axis=0)
[ "def", "get_floating_spinning_factors", "(", "self", ")", ":", "data", "=", "[", "]", "for", "src", "in", "self", ".", "get_sources", "(", ")", ":", "if", "hasattr", "(", "src", ",", "'hypocenter_distribution'", ")", ":", "data", ".", "append", "(", "(", "len", "(", "src", ".", "hypocenter_distribution", ".", "data", ")", ",", "len", "(", "src", ".", "nodal_plane_distribution", ".", "data", ")", ")", ")", "if", "not", "data", ":", "return", "numpy", ".", "array", "(", "[", "1", ",", "1", "]", ")", "return", "numpy", ".", "array", "(", "data", ")", ".", "mean", "(", "axis", "=", "0", ")" ]
:returns: (floating rupture factor, spinning rupture factor)
[ ":", "returns", ":", "(", "floating", "rupture", "factor", "spinning", "rupture", "factor", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/source.py#L546-L558
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): 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" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L71-L86
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): output_region_dict = [] tuple_keys = ['Displacement_Length_Ratio', 'Shear_Modulus'] for region in region_dict: for val_name in tuple_keys: region[val_name] = weight_list_to_tuple(region[val_name], val_name) 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" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L89-L105
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 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" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L108-L120
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): 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", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L138-L189
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): 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" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L191-L203
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): if geo_dict['Fault_Typology'] == 'Simple': 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': 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", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/parsers/faults/fault_yaml_parser.py#L205-L242
gem/oq-engine
openquake/hazardlib/gsim/atkinson_2015.py
Atkinson2015.get_mean_and_stddevs
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ C = self.COEFFS[imt] imean = (self._get_magnitude_term(C, rup.mag) + self._get_distance_term(C, dists.rhypo, rup.mag)) # Convert mean from cm/s and cm/s/s if imt.name in "SA PGA": mean = np.log((10.0 ** (imean - 2.0)) / g) else: mean = np.log(10.0 ** imean) stddevs = self._get_stddevs(C, len(dists.rhypo), stddev_types) return mean, stddevs
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): C = self.COEFFS[imt] imean = (self._get_magnitude_term(C, rup.mag) + self._get_distance_term(C, dists.rhypo, rup.mag)) if imt.name in "SA PGA": mean = np.log((10.0 ** (imean - 2.0)) / g) else: mean = np.log(10.0 ** imean) stddevs = self._get_stddevs(C, len(dists.rhypo), stddev_types) return mean, stddevs
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "C", "=", "self", ".", "COEFFS", "[", "imt", "]", "imean", "=", "(", "self", ".", "_get_magnitude_term", "(", "C", ",", "rup", ".", "mag", ")", "+", "self", ".", "_get_distance_term", "(", "C", ",", "dists", ".", "rhypo", ",", "rup", ".", "mag", ")", ")", "# Convert mean from cm/s and cm/s/s", "if", "imt", ".", "name", "in", "\"SA PGA\"", ":", "mean", "=", "np", ".", "log", "(", "(", "10.0", "**", "(", "imean", "-", "2.0", ")", ")", "/", "g", ")", "else", ":", "mean", "=", "np", ".", "log", "(", "10.0", "**", "imean", ")", "stddevs", "=", "self", ".", "_get_stddevs", "(", "C", ",", "len", "(", "dists", ".", "rhypo", ")", ",", "stddev_types", ")", "return", "mean", ",", "stddevs" ]
See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
[ "See", ":", "meth", ":", "superclass", "method", "<", ".", "base", ".", "GroundShakingIntensityModel", ".", "get_mean_and_stddevs", ">", "for", "spec", "of", "input", "and", "result", "values", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/atkinson_2015.py#L74-L90
gem/oq-engine
openquake/hazardlib/gsim/atkinson_2015.py
Atkinson2015._get_distance_term
def _get_distance_term(self, C, rhypo, mag): """ Returns the distance scaling term """ h_eff = self._get_effective_distance(mag) r_val = np.sqrt(rhypo ** 2.0 + h_eff ** 2.0) return C["c3"] * np.log10(r_val)
python
def _get_distance_term(self, C, rhypo, mag): h_eff = self._get_effective_distance(mag) r_val = np.sqrt(rhypo ** 2.0 + h_eff ** 2.0) return C["c3"] * np.log10(r_val)
[ "def", "_get_distance_term", "(", "self", ",", "C", ",", "rhypo", ",", "mag", ")", ":", "h_eff", "=", "self", ".", "_get_effective_distance", "(", "mag", ")", "r_val", "=", "np", ".", "sqrt", "(", "rhypo", "**", "2.0", "+", "h_eff", "**", "2.0", ")", "return", "C", "[", "\"c3\"", "]", "*", "np", ".", "log10", "(", "r_val", ")" ]
Returns the distance scaling term
[ "Returns", "the", "distance", "scaling", "term" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/atkinson_2015.py#L98-L104
gem/oq-engine
openquake/hazardlib/gsim/douglas_stochastic_2013.py
DouglasEtAl2013StochasticSD001Q200K005.get_mean_and_stddevs
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ C = self.COEFFS[imt] C_SIG = self.SIGMA_COEFFS[imt] mean = (self.get_magnitude_scaling_term(C, rup.mag) + self.get_distance_scaling_term(C, dists.rhypo)) std_devs = self.get_stddevs(C_SIG, stddev_types, len(dists.rhypo)) #: Mean ground motions initially returned in cm/s/s (for PGA, SA) #: and cm/s for PGV if not imt.name == "PGV": # Convert mean from log(cm/s/s) to g mean = np.log(np.exp(mean) / (100. * g)) return mean, std_devs
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): C = self.COEFFS[imt] C_SIG = self.SIGMA_COEFFS[imt] mean = (self.get_magnitude_scaling_term(C, rup.mag) + self.get_distance_scaling_term(C, dists.rhypo)) std_devs = self.get_stddevs(C_SIG, stddev_types, len(dists.rhypo)) if not imt.name == "PGV": mean = np.log(np.exp(mean) / (100. * g)) return mean, std_devs
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "C", "=", "self", ".", "COEFFS", "[", "imt", "]", "C_SIG", "=", "self", ".", "SIGMA_COEFFS", "[", "imt", "]", "mean", "=", "(", "self", ".", "get_magnitude_scaling_term", "(", "C", ",", "rup", ".", "mag", ")", "+", "self", ".", "get_distance_scaling_term", "(", "C", ",", "dists", ".", "rhypo", ")", ")", "std_devs", "=", "self", ".", "get_stddevs", "(", "C_SIG", ",", "stddev_types", ",", "len", "(", "dists", ".", "rhypo", ")", ")", "#: Mean ground motions initially returned in cm/s/s (for PGA, SA)", "#: and cm/s for PGV", "if", "not", "imt", ".", "name", "==", "\"PGV\"", ":", "# Convert mean from log(cm/s/s) to g", "mean", "=", "np", ".", "log", "(", "np", ".", "exp", "(", "mean", ")", "/", "(", "100.", "*", "g", ")", ")", "return", "mean", ",", "std_devs" ]
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/douglas_stochastic_2013.py#L144-L164
gem/oq-engine
openquake/hazardlib/gsim/douglas_stochastic_2013.py
DouglasEtAl2013StochasticSD001Q200K005.get_magnitude_scaling_term
def get_magnitude_scaling_term(self, C, mag): """ Returns the magnitude scaling term (equation 1) """ mval = mag - 3.0 return C['b1'] + C['b2'] * mval + C['b3'] * (mval ** 2.0) +\ C['b4'] * (mval ** 3.0)
python
def get_magnitude_scaling_term(self, C, mag): mval = mag - 3.0 return C['b1'] + C['b2'] * mval + C['b3'] * (mval ** 2.0) +\ C['b4'] * (mval ** 3.0)
[ "def", "get_magnitude_scaling_term", "(", "self", ",", "C", ",", "mag", ")", ":", "mval", "=", "mag", "-", "3.0", "return", "C", "[", "'b1'", "]", "+", "C", "[", "'b2'", "]", "*", "mval", "+", "C", "[", "'b3'", "]", "*", "(", "mval", "**", "2.0", ")", "+", "C", "[", "'b4'", "]", "*", "(", "mval", "**", "3.0", ")" ]
Returns the magnitude scaling term (equation 1)
[ "Returns", "the", "magnitude", "scaling", "term", "(", "equation", "1", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/douglas_stochastic_2013.py#L166-L172
gem/oq-engine
openquake/hazardlib/gsim/douglas_stochastic_2013.py
DouglasEtAl2013StochasticSD001Q200K005.get_distance_scaling_term
def get_distance_scaling_term(self, C, rhyp): """ Returns the distance scaling term (equation 1) """ rval = rhyp + C['bh'] return C['b5'] * np.log(rval) + C['b6'] * rval
python
def get_distance_scaling_term(self, C, rhyp): rval = rhyp + C['bh'] return C['b5'] * np.log(rval) + C['b6'] * rval
[ "def", "get_distance_scaling_term", "(", "self", ",", "C", ",", "rhyp", ")", ":", "rval", "=", "rhyp", "+", "C", "[", "'bh'", "]", "return", "C", "[", "'b5'", "]", "*", "np", ".", "log", "(", "rval", ")", "+", "C", "[", "'b6'", "]", "*", "rval" ]
Returns the distance scaling term (equation 1)
[ "Returns", "the", "distance", "scaling", "term", "(", "equation", "1", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/douglas_stochastic_2013.py#L174-L179
gem/oq-engine
openquake/hazardlib/gsim/douglas_stochastic_2013.py
DouglasEtAl2013StochasticSD001Q200K005.get_stddevs
def get_stddevs(self, C_SIG, stddev_types, num_sites): """ Returns the standard deviations N.B. In the paper, and with confirmation from the author, the aleatory variability terms from the empirical model are used in conjunction with the median coefficients from the stochastic model. In the empirical model, coefficients for a single-station intra-event sigma are derived. These are labeled as "phi". Inter-event coefficients corresponding to two observed geothermal sequences (Soultz-Sous-Forets and Basel) are also derived. The inter-event standard deviation is therefore taken as the ordinary mean of the two inter-event sigma terms """ stddevs = [] intra = C_SIG['phi'] inter = (C_SIG['tau_s'] + C_SIG['tau_b']) / 2.0 total = sqrt(intra ** 2.0 + inter ** 2.0) for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: stddevs.append(total + np.zeros(num_sites)) elif stddev_type == const.StdDev.INTER_EVENT: stddevs.append(inter + np.zeros(num_sites)) elif stddev_type == const.StdDev.INTRA_EVENT: stddevs.append(intra + np.zeros(num_sites)) return stddevs
python
def get_stddevs(self, C_SIG, stddev_types, num_sites): stddevs = [] intra = C_SIG['phi'] inter = (C_SIG['tau_s'] + C_SIG['tau_b']) / 2.0 total = sqrt(intra ** 2.0 + inter ** 2.0) for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: stddevs.append(total + np.zeros(num_sites)) elif stddev_type == const.StdDev.INTER_EVENT: stddevs.append(inter + np.zeros(num_sites)) elif stddev_type == const.StdDev.INTRA_EVENT: stddevs.append(intra + np.zeros(num_sites)) return stddevs
[ "def", "get_stddevs", "(", "self", ",", "C_SIG", ",", "stddev_types", ",", "num_sites", ")", ":", "stddevs", "=", "[", "]", "intra", "=", "C_SIG", "[", "'phi'", "]", "inter", "=", "(", "C_SIG", "[", "'tau_s'", "]", "+", "C_SIG", "[", "'tau_b'", "]", ")", "/", "2.0", "total", "=", "sqrt", "(", "intra", "**", "2.0", "+", "inter", "**", "2.0", ")", "for", "stddev_type", "in", "stddev_types", ":", "assert", "stddev_type", "in", "self", ".", "DEFINED_FOR_STANDARD_DEVIATION_TYPES", "if", "stddev_type", "==", "const", ".", "StdDev", ".", "TOTAL", ":", "stddevs", ".", "append", "(", "total", "+", "np", ".", "zeros", "(", "num_sites", ")", ")", "elif", "stddev_type", "==", "const", ".", "StdDev", ".", "INTER_EVENT", ":", "stddevs", ".", "append", "(", "inter", "+", "np", ".", "zeros", "(", "num_sites", ")", ")", "elif", "stddev_type", "==", "const", ".", "StdDev", ".", "INTRA_EVENT", ":", "stddevs", ".", "append", "(", "intra", "+", "np", ".", "zeros", "(", "num_sites", ")", ")", "return", "stddevs" ]
Returns the standard deviations N.B. In the paper, and with confirmation from the author, the aleatory variability terms from the empirical model are used in conjunction with the median coefficients from the stochastic model. In the empirical model, coefficients for a single-station intra-event sigma are derived. These are labeled as "phi". Inter-event coefficients corresponding to two observed geothermal sequences (Soultz-Sous-Forets and Basel) are also derived. The inter-event standard deviation is therefore taken as the ordinary mean of the two inter-event sigma terms
[ "Returns", "the", "standard", "deviations" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/douglas_stochastic_2013.py#L181-L207
gem/oq-engine
openquake/hazardlib/gsim/cauzzi_2014.py
CauzziEtAl2014.get_mean_and_stddevs
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extract dictionaries of coefficients specific to required # intensity measure type C = self.COEFFS[imt] mean = self._compute_mean(C, rup, dists, sites, imt) stddevs = self._get_stddevs(C, stddev_types, sites.vs30.shape[0]) return mean, stddevs
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): C = self.COEFFS[imt] mean = self._compute_mean(C, rup, dists, sites, imt) stddevs = self._get_stddevs(C, stddev_types, sites.vs30.shape[0]) return mean, stddevs
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "# extract dictionaries of coefficients specific to required", "# intensity measure type", "C", "=", "self", ".", "COEFFS", "[", "imt", "]", "mean", "=", "self", ".", "_compute_mean", "(", "C", ",", "rup", ",", "dists", ",", "sites", ",", "imt", ")", "stddevs", "=", "self", ".", "_get_stddevs", "(", "C", ",", "stddev_types", ",", "sites", ".", "vs30", ".", "shape", "[", "0", "]", ")", "return", "mean", ",", "stddevs" ]
See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
[ "See", ":", "meth", ":", "superclass", "method", "<", ".", "base", ".", "GroundShakingIntensityModel", ".", "get_mean_and_stddevs", ">", "for", "spec", "of", "input", "and", "result", "values", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L89-L103
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): 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" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L132-L136
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): 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" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L138-L149
gem/oq-engine
openquake/hazardlib/gsim/cauzzi_2014.py
CauzziEtAl2014NoSOF._compute_mean
def _compute_mean(self, C, rup, dists, sites, imt): """ Returns the mean ground motion acceleration and velocity """ mean = (self._get_magnitude_scaling_term(C, rup.mag) + self._get_distance_scaling_term(C, rup.mag, dists.rrup) + self._get_site_amplification_term(C, sites.vs30)) # convert from cm/s**2 to g for SA and from m/s**2 to g for PGA (PGV # is already in cm/s) and also convert from base 10 to base e. if imt.name == "PGA": mean = np.log((10 ** mean) * ((2 * np.pi / 0.01) ** 2) * 1e-2 / g) elif imt.name == "SA": mean = np.log((10 ** mean) * ((2 * np.pi / imt.period) ** 2) * 1e-2 / g) else: mean = np.log(10 ** mean) return mean
python
def _compute_mean(self, C, rup, dists, sites, imt): mean = (self._get_magnitude_scaling_term(C, rup.mag) + self._get_distance_scaling_term(C, rup.mag, dists.rrup) + self._get_site_amplification_term(C, sites.vs30)) if imt.name == "PGA": mean = np.log((10 ** mean) * ((2 * np.pi / 0.01) ** 2) * 1e-2 / g) elif imt.name == "SA": mean = np.log((10 ** mean) * ((2 * np.pi / imt.period) ** 2) * 1e-2 / g) else: mean = np.log(10 ** mean) return mean
[ "def", "_compute_mean", "(", "self", ",", "C", ",", "rup", ",", "dists", ",", "sites", ",", "imt", ")", ":", "mean", "=", "(", "self", ".", "_get_magnitude_scaling_term", "(", "C", ",", "rup", ".", "mag", ")", "+", "self", ".", "_get_distance_scaling_term", "(", "C", ",", "rup", ".", "mag", ",", "dists", ".", "rrup", ")", "+", "self", ".", "_get_site_amplification_term", "(", "C", ",", "sites", ".", "vs30", ")", ")", "# convert from cm/s**2 to g for SA and from m/s**2 to g for PGA (PGV", "# is already in cm/s) and also convert from base 10 to base e.", "if", "imt", ".", "name", "==", "\"PGA\"", ":", "mean", "=", "np", ".", "log", "(", "(", "10", "**", "mean", ")", "*", "(", "(", "2", "*", "np", ".", "pi", "/", "0.01", ")", "**", "2", ")", "*", "1e-2", "/", "g", ")", "elif", "imt", ".", "name", "==", "\"SA\"", ":", "mean", "=", "np", ".", "log", "(", "(", "10", "**", "mean", ")", "*", "(", "(", "2", "*", "np", ".", "pi", "/", "imt", ".", "period", ")", "**", "2", ")", "*", "1e-2", "/", "g", ")", "else", ":", "mean", "=", "np", ".", "log", "(", "10", "**", "mean", ")", "return", "mean" ]
Returns the mean ground motion acceleration and velocity
[ "Returns", "the", "mean", "ground", "motion", "acceleration", "and", "velocity" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L401-L419
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): 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" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L471-L477
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): 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" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_2014.py#L479-L489
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): 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) if 'AndersonLucoAreaMmax' in config['Model_Name']: if not self.disp_length_ratio: 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" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L145-L177
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): 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] if not self.shear_modulus: self.shear_modulus = self.regionalisation.shear_modulus if not self.msr: self.msr = self.regionalisation.scaling_rel 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" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L265-L301
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): if selector.catalogue.get_number_events() < 1: raise ValueError('No events found in catalogue!') if ('rupture' in distance_metric): self.catalogue = selector.within_rupture_distance( self.geometry.surface, distance, upper_depth=upper_eq_depth, lower_depth=lower_eq_depth) else: 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" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L303-L325
gem/oq-engine
openquake/hmtk/faults/fault_models.py
mtkActiveFault._generate_branching_index
def _generate_branching_index(self): ''' Generates a branching index (i.e. a list indicating the number of branches in each branching level. Current branching levels are: 1) Slip 2) MSR 3) Shear Modulus 4) DLR 5) MSR_Sigma 6) Config :returns: * branch_index - A 2-D numpy.ndarray where each row is a pointer to a particular combination of values * number_branches - Total number of branches (int) ''' branch_count = np.array([len(self.slip), len(self.msr), len(self.shear_modulus), len(self.disp_length_ratio), len(self.msr_sigma), len(self.config)]) n_levels = len(branch_count) number_branches = np.prod(branch_count) branch_index = np.zeros([number_branches, n_levels], dtype=int) cumval = 1 dstep = 1E-9 for iloc in range(0, n_levels): idx = np.linspace(0., float(branch_count[iloc]) - dstep, number_branches // cumval) branch_index[:, iloc] = np.reshape(np.tile(idx, [cumval, 1]), number_branches) cumval *= branch_count[iloc] return branch_index.tolist(), number_branches
python
def _generate_branching_index(self): branch_count = np.array([len(self.slip), len(self.msr), len(self.shear_modulus), len(self.disp_length_ratio), len(self.msr_sigma), len(self.config)]) n_levels = len(branch_count) number_branches = np.prod(branch_count) branch_index = np.zeros([number_branches, n_levels], dtype=int) cumval = 1 dstep = 1E-9 for iloc in range(0, n_levels): idx = np.linspace(0., float(branch_count[iloc]) - dstep, number_branches // cumval) branch_index[:, iloc] = np.reshape(np.tile(idx, [cumval, 1]), number_branches) cumval *= branch_count[iloc] return branch_index.tolist(), number_branches
[ "def", "_generate_branching_index", "(", "self", ")", ":", "branch_count", "=", "np", ".", "array", "(", "[", "len", "(", "self", ".", "slip", ")", ",", "len", "(", "self", ".", "msr", ")", ",", "len", "(", "self", ".", "shear_modulus", ")", ",", "len", "(", "self", ".", "disp_length_ratio", ")", ",", "len", "(", "self", ".", "msr_sigma", ")", ",", "len", "(", "self", ".", "config", ")", "]", ")", "n_levels", "=", "len", "(", "branch_count", ")", "number_branches", "=", "np", ".", "prod", "(", "branch_count", ")", "branch_index", "=", "np", ".", "zeros", "(", "[", "number_branches", ",", "n_levels", "]", ",", "dtype", "=", "int", ")", "cumval", "=", "1", "dstep", "=", "1E-9", "for", "iloc", "in", "range", "(", "0", ",", "n_levels", ")", ":", "idx", "=", "np", ".", "linspace", "(", "0.", ",", "float", "(", "branch_count", "[", "iloc", "]", ")", "-", "dstep", ",", "number_branches", "//", "cumval", ")", "branch_index", "[", ":", ",", "iloc", "]", "=", "np", ".", "reshape", "(", "np", ".", "tile", "(", "idx", ",", "[", "cumval", ",", "1", "]", ")", ",", "number_branches", ")", "cumval", "*=", "branch_count", "[", "iloc", "]", "return", "branch_index", ".", "tolist", "(", ")", ",", "number_branches" ]
Generates a branching index (i.e. a list indicating the number of branches in each branching level. Current branching levels are: 1) Slip 2) MSR 3) Shear Modulus 4) DLR 5) MSR_Sigma 6) Config :returns: * branch_index - A 2-D numpy.ndarray where each row is a pointer to a particular combination of values * number_branches - Total number of branches (int)
[ "Generates", "a", "branching", "index", "(", "i", ".", "e", ".", "a", "list", "indicating", "the", "number", "of", "branches", "in", "each", "branching", "level", ".", "Current", "branching", "levels", "are", ":", "1", ")", "Slip", "2", ")", "MSR", "3", ")", "Shear", "Modulus", "4", ")", "DLR", "5", ")", "MSR_Sigma", "6", ")", "Config" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L327-L363
gem/oq-engine
openquake/hmtk/faults/fault_models.py
mtkActiveFault.generate_config_set
def generate_config_set(self, config): ''' Generates a list of magnitude frequency distributions and renders as a tuple :param dict/list config: Configuration paramters of magnitude frequency distribution ''' if isinstance(config, dict): # Configuration list contains only one element self.config = [(config, 1.0)] elif isinstance(config, list): # Multiple configurations with correscponding weights total_weight = 0. self.config = [] for params in config: weight = params['Model_Weight'] total_weight += params['Model_Weight'] self.config.append((params, weight)) if fabs(total_weight - 1.0) > 1E-7: raise ValueError('MFD config weights do not sum to 1.0 for ' 'fault %s' % self.id) else: raise ValueError('MFD config must be input as dictionary or list!')
python
def generate_config_set(self, config): if isinstance(config, dict): self.config = [(config, 1.0)] elif isinstance(config, list): total_weight = 0. self.config = [] for params in config: weight = params['Model_Weight'] total_weight += params['Model_Weight'] self.config.append((params, weight)) if fabs(total_weight - 1.0) > 1E-7: raise ValueError('MFD config weights do not sum to 1.0 for ' 'fault %s' % self.id) else: raise ValueError('MFD config must be input as dictionary or list!')
[ "def", "generate_config_set", "(", "self", ",", "config", ")", ":", "if", "isinstance", "(", "config", ",", "dict", ")", ":", "# Configuration list contains only one element", "self", ".", "config", "=", "[", "(", "config", ",", "1.0", ")", "]", "elif", "isinstance", "(", "config", ",", "list", ")", ":", "# Multiple configurations with correscponding weights", "total_weight", "=", "0.", "self", ".", "config", "=", "[", "]", "for", "params", "in", "config", ":", "weight", "=", "params", "[", "'Model_Weight'", "]", "total_weight", "+=", "params", "[", "'Model_Weight'", "]", "self", ".", "config", ".", "append", "(", "(", "params", ",", "weight", ")", ")", "if", "fabs", "(", "total_weight", "-", "1.0", ")", ">", "1E-7", ":", "raise", "ValueError", "(", "'MFD config weights do not sum to 1.0 for '", "'fault %s'", "%", "self", ".", "id", ")", "else", ":", "raise", "ValueError", "(", "'MFD config must be input as dictionary or list!'", ")" ]
Generates a list of magnitude frequency distributions and renders as a tuple :param dict/list config: Configuration paramters of magnitude frequency distribution
[ "Generates", "a", "list", "of", "magnitude", "frequency", "distributions", "and", "renders", "as", "a", "tuple" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L365-L388
gem/oq-engine
openquake/hmtk/faults/fault_models.py
mtkActiveFault.generate_recurrence_models
def generate_recurrence_models( self, collapse=False, bin_width=0.1, config=None, rendered_msr=None): ''' Iterates over the lists of values defining epistemic uncertainty in the parameters and calculates the corresponding recurrence model At present epistemic uncertainty is supported for: 1) slip rate, 2) magnitude scaling relation, 3) shear modulus, 4) displacement to length ratio) and 5) recurrence model. :param list config: List of MFD model configurations :param bool collapse: Boolean flag indicating whether to collapse the logic tree branches :param float bin_width: If collapsing the logic tree branches the reference mfd must be defined. The minimum and maximum magnitudes are updated from the model, but the bin width must be specified here :param list/dict config: Configuration (or sets of configurations) of the recurrence calculations :param rendered_msr: If collapsing the logic tree branches a resulting magnitude scaling relation must be defined as instance of :class: openquake.hazardlib.scalerel.base.BaseASR ''' if collapse and not rendered_msr: raise ValueError('Collapsing logic tree branches requires input ' 'of a single msr for rendering sources') # Generate a set of tuples with corresponding weights if config is not None: self.generate_config_set(config) if not isinstance(self.config, list): raise ValueError('MFD configuration missing or incorrectly ' 'formatted') # Generate the branching index branch_index, _number_branches = self._generate_branching_index() mmin = np.inf mmax = -np.inf for idx in branch_index: tuple_list = [] # Get slip tuple_list.append(self.slip[idx[0]]) # Get msr tuple_list.append(self.msr[idx[1]]) # Get shear modulus tuple_list.append(self.shear_modulus[idx[2]]) # Get displacement length ratio tuple_list.append(self.disp_length_ratio[idx[3]]) # Get msr sigma tuple_list.append(self.msr_sigma[idx[4]]) # Get config tuple_list.append(self.config[idx[5]]) # Calculate branch weight as product of tuple weights branch_weight = np.prod(np.array([val[1] for val in tuple_list])) # Instantiate recurrence model model = RecurrenceBranch(self.area, tuple_list[0][0], tuple_list[1][0], self.rake, tuple_list[2][0], tuple_list[3][0], tuple_list[4][0], weight=branch_weight) model.get_recurrence(tuple_list[5][0]) self.mfd_models.append(model) # Update the total minimum and maximum magnitudes for the fault if model.recurrence.min_mag < mmin: mmin = model.recurrence.min_mag if np.max(model.magnitudes) > mmax: mmax = np.max(model.magnitudes) if collapse: self.mfd = ([self.collapse_branches(mmin, bin_width, mmax)], [1.0], [rendered_msr]) else: mfd_mods = [] mfd_wgts = [] mfd_msr = [] for model in self.mfd_models: mfd_mods.append(IncrementalMFD(model.recurrence.min_mag, model.recurrence.bin_width, model.recurrence.occur_rates)) mfd_wgts.append(model.weight) mfd_msr.append(model.msr) self.mfd = (mfd_mods, mfd_wgts, mfd_msr)
python
def generate_recurrence_models( self, collapse=False, bin_width=0.1, config=None, rendered_msr=None): if collapse and not rendered_msr: raise ValueError('Collapsing logic tree branches requires input ' 'of a single msr for rendering sources') if config is not None: self.generate_config_set(config) if not isinstance(self.config, list): raise ValueError('MFD configuration missing or incorrectly ' 'formatted') branch_index, _number_branches = self._generate_branching_index() mmin = np.inf mmax = -np.inf for idx in branch_index: tuple_list = [] tuple_list.append(self.slip[idx[0]]) tuple_list.append(self.msr[idx[1]]) tuple_list.append(self.shear_modulus[idx[2]]) tuple_list.append(self.disp_length_ratio[idx[3]]) tuple_list.append(self.msr_sigma[idx[4]]) tuple_list.append(self.config[idx[5]]) branch_weight = np.prod(np.array([val[1] for val in tuple_list])) model = RecurrenceBranch(self.area, tuple_list[0][0], tuple_list[1][0], self.rake, tuple_list[2][0], tuple_list[3][0], tuple_list[4][0], weight=branch_weight) model.get_recurrence(tuple_list[5][0]) self.mfd_models.append(model) if model.recurrence.min_mag < mmin: mmin = model.recurrence.min_mag if np.max(model.magnitudes) > mmax: mmax = np.max(model.magnitudes) if collapse: self.mfd = ([self.collapse_branches(mmin, bin_width, mmax)], [1.0], [rendered_msr]) else: mfd_mods = [] mfd_wgts = [] mfd_msr = [] for model in self.mfd_models: mfd_mods.append(IncrementalMFD(model.recurrence.min_mag, model.recurrence.bin_width, model.recurrence.occur_rates)) mfd_wgts.append(model.weight) mfd_msr.append(model.msr) self.mfd = (mfd_mods, mfd_wgts, mfd_msr)
[ "def", "generate_recurrence_models", "(", "self", ",", "collapse", "=", "False", ",", "bin_width", "=", "0.1", ",", "config", "=", "None", ",", "rendered_msr", "=", "None", ")", ":", "if", "collapse", "and", "not", "rendered_msr", ":", "raise", "ValueError", "(", "'Collapsing logic tree branches requires input '", "'of a single msr for rendering sources'", ")", "# Generate a set of tuples with corresponding weights", "if", "config", "is", "not", "None", ":", "self", ".", "generate_config_set", "(", "config", ")", "if", "not", "isinstance", "(", "self", ".", "config", ",", "list", ")", ":", "raise", "ValueError", "(", "'MFD configuration missing or incorrectly '", "'formatted'", ")", "# Generate the branching index", "branch_index", ",", "_number_branches", "=", "self", ".", "_generate_branching_index", "(", ")", "mmin", "=", "np", ".", "inf", "mmax", "=", "-", "np", ".", "inf", "for", "idx", "in", "branch_index", ":", "tuple_list", "=", "[", "]", "# Get slip", "tuple_list", ".", "append", "(", "self", ".", "slip", "[", "idx", "[", "0", "]", "]", ")", "# Get msr", "tuple_list", ".", "append", "(", "self", ".", "msr", "[", "idx", "[", "1", "]", "]", ")", "# Get shear modulus", "tuple_list", ".", "append", "(", "self", ".", "shear_modulus", "[", "idx", "[", "2", "]", "]", ")", "# Get displacement length ratio", "tuple_list", ".", "append", "(", "self", ".", "disp_length_ratio", "[", "idx", "[", "3", "]", "]", ")", "# Get msr sigma", "tuple_list", ".", "append", "(", "self", ".", "msr_sigma", "[", "idx", "[", "4", "]", "]", ")", "# Get config", "tuple_list", ".", "append", "(", "self", ".", "config", "[", "idx", "[", "5", "]", "]", ")", "# Calculate branch weight as product of tuple weights", "branch_weight", "=", "np", ".", "prod", "(", "np", ".", "array", "(", "[", "val", "[", "1", "]", "for", "val", "in", "tuple_list", "]", ")", ")", "# Instantiate recurrence model", "model", "=", "RecurrenceBranch", "(", "self", ".", "area", ",", "tuple_list", "[", "0", "]", "[", "0", "]", ",", "tuple_list", "[", "1", "]", "[", "0", "]", ",", "self", ".", "rake", ",", "tuple_list", "[", "2", "]", "[", "0", "]", ",", "tuple_list", "[", "3", "]", "[", "0", "]", ",", "tuple_list", "[", "4", "]", "[", "0", "]", ",", "weight", "=", "branch_weight", ")", "model", ".", "get_recurrence", "(", "tuple_list", "[", "5", "]", "[", "0", "]", ")", "self", ".", "mfd_models", ".", "append", "(", "model", ")", "# Update the total minimum and maximum magnitudes for the fault", "if", "model", ".", "recurrence", ".", "min_mag", "<", "mmin", ":", "mmin", "=", "model", ".", "recurrence", ".", "min_mag", "if", "np", ".", "max", "(", "model", ".", "magnitudes", ")", ">", "mmax", ":", "mmax", "=", "np", ".", "max", "(", "model", ".", "magnitudes", ")", "if", "collapse", ":", "self", ".", "mfd", "=", "(", "[", "self", ".", "collapse_branches", "(", "mmin", ",", "bin_width", ",", "mmax", ")", "]", ",", "[", "1.0", "]", ",", "[", "rendered_msr", "]", ")", "else", ":", "mfd_mods", "=", "[", "]", "mfd_wgts", "=", "[", "]", "mfd_msr", "=", "[", "]", "for", "model", "in", "self", ".", "mfd_models", ":", "mfd_mods", ".", "append", "(", "IncrementalMFD", "(", "model", ".", "recurrence", ".", "min_mag", ",", "model", ".", "recurrence", ".", "bin_width", ",", "model", ".", "recurrence", ".", "occur_rates", ")", ")", "mfd_wgts", ".", "append", "(", "model", ".", "weight", ")", "mfd_msr", ".", "append", "(", "model", ".", "msr", ")", "self", ".", "mfd", "=", "(", "mfd_mods", ",", "mfd_wgts", ",", "mfd_msr", ")" ]
Iterates over the lists of values defining epistemic uncertainty in the parameters and calculates the corresponding recurrence model At present epistemic uncertainty is supported for: 1) slip rate, 2) magnitude scaling relation, 3) shear modulus, 4) displacement to length ratio) and 5) recurrence model. :param list config: List of MFD model configurations :param bool collapse: Boolean flag indicating whether to collapse the logic tree branches :param float bin_width: If collapsing the logic tree branches the reference mfd must be defined. The minimum and maximum magnitudes are updated from the model, but the bin width must be specified here :param list/dict config: Configuration (or sets of configurations) of the recurrence calculations :param rendered_msr: If collapsing the logic tree branches a resulting magnitude scaling relation must be defined as instance of :class: openquake.hazardlib.scalerel.base.BaseASR
[ "Iterates", "over", "the", "lists", "of", "values", "defining", "epistemic", "uncertainty", "in", "the", "parameters", "and", "calculates", "the", "corresponding", "recurrence", "model", "At", "present", "epistemic", "uncertainty", "is", "supported", "for", ":", "1", ")", "slip", "rate", "2", ")", "magnitude", "scaling", "relation", "3", ")", "shear", "modulus", "4", ")", "displacement", "to", "length", "ratio", ")", "and", "5", ")", "recurrence", "model", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L390-L477
gem/oq-engine
openquake/hmtk/faults/fault_models.py
mtkActiveFault.collapse_branches
def collapse_branches(self, mmin, bin_width, mmax): ''' Collapse the logic tree branches into a single IncrementalMFD :param float mmin: Minimum magnitude of reference mfd :param float bin_width: Bin width of reference mfd :param float mmax: Maximum magnitude of reference mfd :returns: :class: openquake.hmtk.models.IncrementalMFD ''' master_mags = np.arange(mmin, mmax + (bin_width / 2.), bin_width) master_rates = np.zeros(len(master_mags), dtype=float) for model in self.mfd_models: id0 = np.logical_and( master_mags >= np.min(model.magnitudes) - 1E-9, master_mags <= np.max(model.magnitudes) + 1E-9) # Use interpolation in log10-y values yvals = np.log10(model.recurrence.occur_rates) interp_y = np.interp(master_mags[id0], model.magnitudes, yvals) master_rates[id0] = master_rates[id0] + (model.weight * 10. ** interp_y) return IncrementalMFD(mmin, bin_width, master_rates)
python
def collapse_branches(self, mmin, bin_width, mmax): master_mags = np.arange(mmin, mmax + (bin_width / 2.), bin_width) master_rates = np.zeros(len(master_mags), dtype=float) for model in self.mfd_models: id0 = np.logical_and( master_mags >= np.min(model.magnitudes) - 1E-9, master_mags <= np.max(model.magnitudes) + 1E-9) yvals = np.log10(model.recurrence.occur_rates) interp_y = np.interp(master_mags[id0], model.magnitudes, yvals) master_rates[id0] = master_rates[id0] + (model.weight * 10. ** interp_y) return IncrementalMFD(mmin, bin_width, master_rates)
[ "def", "collapse_branches", "(", "self", ",", "mmin", ",", "bin_width", ",", "mmax", ")", ":", "master_mags", "=", "np", ".", "arange", "(", "mmin", ",", "mmax", "+", "(", "bin_width", "/", "2.", ")", ",", "bin_width", ")", "master_rates", "=", "np", ".", "zeros", "(", "len", "(", "master_mags", ")", ",", "dtype", "=", "float", ")", "for", "model", "in", "self", ".", "mfd_models", ":", "id0", "=", "np", ".", "logical_and", "(", "master_mags", ">=", "np", ".", "min", "(", "model", ".", "magnitudes", ")", "-", "1E-9", ",", "master_mags", "<=", "np", ".", "max", "(", "model", ".", "magnitudes", ")", "+", "1E-9", ")", "# Use interpolation in log10-y values", "yvals", "=", "np", ".", "log10", "(", "model", ".", "recurrence", ".", "occur_rates", ")", "interp_y", "=", "np", ".", "interp", "(", "master_mags", "[", "id0", "]", ",", "model", ".", "magnitudes", ",", "yvals", ")", "master_rates", "[", "id0", "]", "=", "master_rates", "[", "id0", "]", "+", "(", "model", ".", "weight", "*", "10.", "**", "interp_y", ")", "return", "IncrementalMFD", "(", "mmin", ",", "bin_width", ",", "master_rates", ")" ]
Collapse the logic tree branches into a single IncrementalMFD :param float mmin: Minimum magnitude of reference mfd :param float bin_width: Bin width of reference mfd :param float mmax: Maximum magnitude of reference mfd :returns: :class: openquake.hmtk.models.IncrementalMFD
[ "Collapse", "the", "logic", "tree", "branches", "into", "a", "single", "IncrementalMFD" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L479-L507
gem/oq-engine
openquake/hmtk/faults/fault_models.py
mtkActiveFault.generate_fault_source_model
def generate_fault_source_model(self): ''' Creates a resulting `openquake.hmtk` fault source set. :returns: source_model - list of instances of either the :class: `openquake.hmtk.sources.simple_fault_source.mtkSimpleFaultSource` or :class: `openquake.hmtk.sources.complex_fault_source.mtkComplexFaultSource` model_weight - Corresponding weights for each source model ''' source_model = [] model_weight = [] for iloc in range(0, self.get_number_mfd_models()): model_mfd = EvenlyDiscretizedMFD( self.mfd[0][iloc].min_mag, self.mfd[0][iloc].bin_width, self.mfd[0][iloc].occur_rates.tolist()) if isinstance(self.geometry, ComplexFaultGeometry): # Complex fault class source = mtkComplexFaultSource( self.id, self.name, self.trt, self.geometry.surface, self.mfd[2][iloc], self.rupt_aspect_ratio, model_mfd, self.rake) source.fault_edges = self.geometry.trace else: # Simple Fault source source = mtkSimpleFaultSource( self.id, self.name, self.trt, self.geometry.surface, self.geometry.dip, self.geometry.upper_depth, self.geometry.lower_depth, self.mfd[2][iloc], self.rupt_aspect_ratio, model_mfd, self.rake) source.fault_trace = self.geometry.trace source_model.append(source) model_weight.append(self.mfd[1][iloc]) return source_model, model_weight
python
def generate_fault_source_model(self): source_model = [] model_weight = [] for iloc in range(0, self.get_number_mfd_models()): model_mfd = EvenlyDiscretizedMFD( self.mfd[0][iloc].min_mag, self.mfd[0][iloc].bin_width, self.mfd[0][iloc].occur_rates.tolist()) if isinstance(self.geometry, ComplexFaultGeometry): source = mtkComplexFaultSource( self.id, self.name, self.trt, self.geometry.surface, self.mfd[2][iloc], self.rupt_aspect_ratio, model_mfd, self.rake) source.fault_edges = self.geometry.trace else: source = mtkSimpleFaultSource( self.id, self.name, self.trt, self.geometry.surface, self.geometry.dip, self.geometry.upper_depth, self.geometry.lower_depth, self.mfd[2][iloc], self.rupt_aspect_ratio, model_mfd, self.rake) source.fault_trace = self.geometry.trace source_model.append(source) model_weight.append(self.mfd[1][iloc]) return source_model, model_weight
[ "def", "generate_fault_source_model", "(", "self", ")", ":", "source_model", "=", "[", "]", "model_weight", "=", "[", "]", "for", "iloc", "in", "range", "(", "0", ",", "self", ".", "get_number_mfd_models", "(", ")", ")", ":", "model_mfd", "=", "EvenlyDiscretizedMFD", "(", "self", ".", "mfd", "[", "0", "]", "[", "iloc", "]", ".", "min_mag", ",", "self", ".", "mfd", "[", "0", "]", "[", "iloc", "]", ".", "bin_width", ",", "self", ".", "mfd", "[", "0", "]", "[", "iloc", "]", ".", "occur_rates", ".", "tolist", "(", ")", ")", "if", "isinstance", "(", "self", ".", "geometry", ",", "ComplexFaultGeometry", ")", ":", "# Complex fault class", "source", "=", "mtkComplexFaultSource", "(", "self", ".", "id", ",", "self", ".", "name", ",", "self", ".", "trt", ",", "self", ".", "geometry", ".", "surface", ",", "self", ".", "mfd", "[", "2", "]", "[", "iloc", "]", ",", "self", ".", "rupt_aspect_ratio", ",", "model_mfd", ",", "self", ".", "rake", ")", "source", ".", "fault_edges", "=", "self", ".", "geometry", ".", "trace", "else", ":", "# Simple Fault source", "source", "=", "mtkSimpleFaultSource", "(", "self", ".", "id", ",", "self", ".", "name", ",", "self", ".", "trt", ",", "self", ".", "geometry", ".", "surface", ",", "self", ".", "geometry", ".", "dip", ",", "self", ".", "geometry", ".", "upper_depth", ",", "self", ".", "geometry", ".", "lower_depth", ",", "self", ".", "mfd", "[", "2", "]", "[", "iloc", "]", ",", "self", ".", "rupt_aspect_ratio", ",", "model_mfd", ",", "self", ".", "rake", ")", "source", ".", "fault_trace", "=", "self", ".", "geometry", ".", "trace", "source_model", ".", "append", "(", "source", ")", "model_weight", ".", "append", "(", "self", ".", "mfd", "[", "1", "]", "[", "iloc", "]", ")", "return", "source_model", ",", "model_weight" ]
Creates a resulting `openquake.hmtk` fault source set. :returns: source_model - list of instances of either the :class: `openquake.hmtk.sources.simple_fault_source.mtkSimpleFaultSource` or :class: `openquake.hmtk.sources.complex_fault_source.mtkComplexFaultSource` model_weight - Corresponding weights for each source model
[ "Creates", "a", "resulting", "openquake", ".", "hmtk", "fault", "source", "set", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L509-L557
gem/oq-engine
openquake/hmtk/models.py
SeismicSource.attrib
def attrib(self): """ General XML element attributes for a seismic source, as a dict. """ return dict([ ('id', str(self.id)), ('name', str(self.name)), ('tectonicRegion', str(self.trt)), ])
python
def attrib(self): return dict([ ('id', str(self.id)), ('name', str(self.name)), ('tectonicRegion', str(self.trt)), ])
[ "def", "attrib", "(", "self", ")", ":", "return", "dict", "(", "[", "(", "'id'", ",", "str", "(", "self", ".", "id", ")", ")", ",", "(", "'name'", ",", "str", "(", "self", ".", "name", ")", ")", ",", "(", "'tectonicRegion'", ",", "str", "(", "self", ".", "trt", ")", ")", ",", "]", ")" ]
General XML element attributes for a seismic source, as a dict.
[ "General", "XML", "element", "attributes", "for", "a", "seismic", "source", "as", "a", "dict", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/models.py#L53-L61
gem/oq-engine
openquake/hmtk/models.py
TGRMFD.attrib
def attrib(self): """ An dict of XML element attributes for this MFD. """ return dict([ ('aValue', str(self.a_val)), ('bValue', str(self.b_val)), ('minMag', str(self.min_mag)), ('maxMag', str(self.max_mag)), ])
python
def attrib(self): return dict([ ('aValue', str(self.a_val)), ('bValue', str(self.b_val)), ('minMag', str(self.min_mag)), ('maxMag', str(self.max_mag)), ])
[ "def", "attrib", "(", "self", ")", ":", "return", "dict", "(", "[", "(", "'aValue'", ",", "str", "(", "self", ".", "a_val", ")", ")", ",", "(", "'bValue'", ",", "str", "(", "self", ".", "b_val", ")", ")", ",", "(", "'minMag'", ",", "str", "(", "self", ".", "min_mag", ")", ")", ",", "(", "'maxMag'", ",", "str", "(", "self", ".", "max_mag", ")", ")", ",", "]", ")" ]
An dict of XML element attributes for this MFD.
[ "An", "dict", "of", "XML", "element", "attributes", "for", "this", "MFD", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/models.py#L325-L334
gem/oq-engine
openquake/hmtk/models.py
NodalPlane.attrib
def attrib(self): """ A dict of XML element attributes for this NodalPlane. """ return dict([ ('probability', str(self.probability)), ('strike', str(self.strike)), ('dip', str(self.dip)), ('rake', str(self.rake)), ])
python
def attrib(self): return dict([ ('probability', str(self.probability)), ('strike', str(self.strike)), ('dip', str(self.dip)), ('rake', str(self.rake)), ])
[ "def", "attrib", "(", "self", ")", ":", "return", "dict", "(", "[", "(", "'probability'", ",", "str", "(", "self", ".", "probability", ")", ")", ",", "(", "'strike'", ",", "str", "(", "self", ".", "strike", ")", ")", ",", "(", "'dip'", ",", "str", "(", "self", ".", "dip", ")", ")", ",", "(", "'rake'", ",", "str", "(", "self", ".", "rake", ")", ")", ",", "]", ")" ]
A dict of XML element attributes for this NodalPlane.
[ "A", "dict", "of", "XML", "element", "attributes", "for", "this", "NodalPlane", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/models.py#L359-L368
gem/oq-engine
openquake/hazardlib/correlation.py
jbcorrelation
def jbcorrelation(sites_or_distances, imt, vs30_clustering=False): """ Returns the Jayaram-Baker correlation model. :param sites_or_distances: SiteCollection instance o ristance matrix :param imt: Intensity Measure Type (PGA or SA) :param vs30_clustering: flag, defalt false """ if hasattr(sites_or_distances, 'mesh'): distances = sites_or_distances.mesh.get_distance_matrix() else: distances = sites_or_distances # formulae are from page 1700 if imt.period < 1: if not vs30_clustering: # case 1, eq. (17) b = 8.5 + 17.2 * imt.period else: # case 2, eq. (18) b = 40.7 - 15.0 * imt.period else: # both cases, eq. (19) b = 22.0 + 3.7 * imt.period # eq. (20) return numpy.exp((- 3.0 / b) * distances)
python
def jbcorrelation(sites_or_distances, imt, vs30_clustering=False): if hasattr(sites_or_distances, 'mesh'): distances = sites_or_distances.mesh.get_distance_matrix() else: distances = sites_or_distances if imt.period < 1: if not vs30_clustering: b = 8.5 + 17.2 * imt.period else: b = 40.7 - 15.0 * imt.period else: b = 22.0 + 3.7 * imt.period return numpy.exp((- 3.0 / b) * distances)
[ "def", "jbcorrelation", "(", "sites_or_distances", ",", "imt", ",", "vs30_clustering", "=", "False", ")", ":", "if", "hasattr", "(", "sites_or_distances", ",", "'mesh'", ")", ":", "distances", "=", "sites_or_distances", ".", "mesh", ".", "get_distance_matrix", "(", ")", "else", ":", "distances", "=", "sites_or_distances", "# formulae are from page 1700", "if", "imt", ".", "period", "<", "1", ":", "if", "not", "vs30_clustering", ":", "# case 1, eq. (17)", "b", "=", "8.5", "+", "17.2", "*", "imt", ".", "period", "else", ":", "# case 2, eq. (18)", "b", "=", "40.7", "-", "15.0", "*", "imt", ".", "period", "else", ":", "# both cases, eq. (19)", "b", "=", "22.0", "+", "3.7", "*", "imt", ".", "period", "# eq. (20)", "return", "numpy", ".", "exp", "(", "(", "-", "3.0", "/", "b", ")", "*", "distances", ")" ]
Returns the Jayaram-Baker correlation model. :param sites_or_distances: SiteCollection instance o ristance matrix :param imt: Intensity Measure Type (PGA or SA) :param vs30_clustering: flag, defalt false
[ "Returns", "the", "Jayaram", "-", "Baker", "correlation", "model", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/correlation.py#L116-L145
gem/oq-engine
openquake/hazardlib/correlation.py
hmcorrelation
def hmcorrelation(sites_or_distances, imt, uncertainty_multiplier=0): """ Returns the Heresi-Miranda correlation model. :param sites_or_distances: SiteCollection instance o distance matrix :param imt: Intensity Measure Type (PGA or SA) :param uncertainty_multiplier: Value to be multiplied by the uncertainty in the correlation parameter beta. If uncertainty_multiplier = 0 (default), the median value is used as a constant value. """ if hasattr(sites_or_distances, 'mesh'): distances = sites_or_distances.mesh.get_distance_matrix() else: distances = sites_or_distances period = imt.period # Eq. (9) if period < 1.37: Med_b = 4.231 * period * period - 5.180 * period + 13.392 else: Med_b = 0.140 * period * period - 2.249 * period + 17.050 # Eq. (10) Std_b = (4.63e-3 * period*period + 0.028 * period + 0.713) # Obtain realization of b if uncertainty_multiplier == 0: beta = Med_b else: beta = numpy.random.lognormal( numpy.log(Med_b), Std_b * uncertainty_multiplier) # Eq. (8) return numpy.exp(-numpy.power((distances / beta), 0.55))
python
def hmcorrelation(sites_or_distances, imt, uncertainty_multiplier=0): if hasattr(sites_or_distances, 'mesh'): distances = sites_or_distances.mesh.get_distance_matrix() else: distances = sites_or_distances period = imt.period if period < 1.37: Med_b = 4.231 * period * period - 5.180 * period + 13.392 else: Med_b = 0.140 * period * period - 2.249 * period + 17.050 Std_b = (4.63e-3 * period*period + 0.028 * period + 0.713) if uncertainty_multiplier == 0: beta = Med_b else: beta = numpy.random.lognormal( numpy.log(Med_b), Std_b * uncertainty_multiplier) return numpy.exp(-numpy.power((distances / beta), 0.55))
[ "def", "hmcorrelation", "(", "sites_or_distances", ",", "imt", ",", "uncertainty_multiplier", "=", "0", ")", ":", "if", "hasattr", "(", "sites_or_distances", ",", "'mesh'", ")", ":", "distances", "=", "sites_or_distances", ".", "mesh", ".", "get_distance_matrix", "(", ")", "else", ":", "distances", "=", "sites_or_distances", "period", "=", "imt", ".", "period", "# Eq. (9)", "if", "period", "<", "1.37", ":", "Med_b", "=", "4.231", "*", "period", "*", "period", "-", "5.180", "*", "period", "+", "13.392", "else", ":", "Med_b", "=", "0.140", "*", "period", "*", "period", "-", "2.249", "*", "period", "+", "17.050", "# Eq. (10)", "Std_b", "=", "(", "4.63e-3", "*", "period", "*", "period", "+", "0.028", "*", "period", "+", "0.713", ")", "# Obtain realization of b", "if", "uncertainty_multiplier", "==", "0", ":", "beta", "=", "Med_b", "else", ":", "beta", "=", "numpy", ".", "random", ".", "lognormal", "(", "numpy", ".", "log", "(", "Med_b", ")", ",", "Std_b", "*", "uncertainty_multiplier", ")", "# Eq. (8)", "return", "numpy", ".", "exp", "(", "-", "numpy", ".", "power", "(", "(", "distances", "/", "beta", ")", ",", "0.55", ")", ")" ]
Returns the Heresi-Miranda correlation model. :param sites_or_distances: SiteCollection instance o distance matrix :param imt: Intensity Measure Type (PGA or SA) :param uncertainty_multiplier: Value to be multiplied by the uncertainty in the correlation parameter beta. If uncertainty_multiplier = 0 (default), the median value is used as a constant value.
[ "Returns", "the", "Heresi", "-", "Miranda", "correlation", "model", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/correlation.py#L225-L262
gem/oq-engine
openquake/hazardlib/correlation.py
BaseCorrelationModel.apply_correlation
def apply_correlation(self, sites, imt, residuals, stddev_intra=0): """ Apply correlation to randomly sampled residuals. :param sites: :class:`~openquake.hazardlib.site.SiteCollection` residuals were sampled for. :param imt: Intensity measure type object, see :mod:`openquake.hazardlib.imt`. :param residuals: 2d numpy array of sampled residuals, where first dimension represents sites (the length as ``sites`` parameter) and second one represents different realizations (samples). :param stddev_intra: Intra-event standard deviation array. Note that different sites do not necessarily have the same intra-event standard deviation. :returns: Array of the same structure and semantics as ``residuals`` but with correlations applied. NB: the correlation matrix is cached. It is computed only once per IMT for the complete site collection and then the portion corresponding to the sites is multiplied by the residuals. """ # intra-event residual for a single relization is a product # of lower-triangle decomposed correlation matrix and vector # of N random numbers (where N is equal to number of sites). # we need to do that multiplication once per realization # with the same matrix and different vectors. try: corma = self.cache[imt] except KeyError: corma = self.get_lower_triangle_correlation_matrix( sites.complete, imt) self.cache[imt] = corma if len(sites.complete) == len(sites): return numpy.dot(corma, residuals) # it is important to allocate little memory, this is why I am # accumulating below; if S is the length of the complete sites # the correlation matrix has shape (S, S) and the residuals (N, s), # where s is the number of samples return numpy.sum(corma[sites.sids, sid] * res for sid, res in zip(sites.sids, residuals))
python
def apply_correlation(self, sites, imt, residuals, stddev_intra=0): try: corma = self.cache[imt] except KeyError: corma = self.get_lower_triangle_correlation_matrix( sites.complete, imt) self.cache[imt] = corma if len(sites.complete) == len(sites): return numpy.dot(corma, residuals) return numpy.sum(corma[sites.sids, sid] * res for sid, res in zip(sites.sids, residuals))
[ "def", "apply_correlation", "(", "self", ",", "sites", ",", "imt", ",", "residuals", ",", "stddev_intra", "=", "0", ")", ":", "# intra-event residual for a single relization is a product", "# of lower-triangle decomposed correlation matrix and vector", "# of N random numbers (where N is equal to number of sites).", "# we need to do that multiplication once per realization", "# with the same matrix and different vectors.", "try", ":", "corma", "=", "self", ".", "cache", "[", "imt", "]", "except", "KeyError", ":", "corma", "=", "self", ".", "get_lower_triangle_correlation_matrix", "(", "sites", ".", "complete", ",", "imt", ")", "self", ".", "cache", "[", "imt", "]", "=", "corma", "if", "len", "(", "sites", ".", "complete", ")", "==", "len", "(", "sites", ")", ":", "return", "numpy", ".", "dot", "(", "corma", ",", "residuals", ")", "# it is important to allocate little memory, this is why I am", "# accumulating below; if S is the length of the complete sites", "# the correlation matrix has shape (S, S) and the residuals (N, s),", "# where s is the number of samples", "return", "numpy", ".", "sum", "(", "corma", "[", "sites", ".", "sids", ",", "sid", "]", "*", "res", "for", "sid", ",", "res", "in", "zip", "(", "sites", ".", "sids", ",", "residuals", ")", ")" ]
Apply correlation to randomly sampled residuals. :param sites: :class:`~openquake.hazardlib.site.SiteCollection` residuals were sampled for. :param imt: Intensity measure type object, see :mod:`openquake.hazardlib.imt`. :param residuals: 2d numpy array of sampled residuals, where first dimension represents sites (the length as ``sites`` parameter) and second one represents different realizations (samples). :param stddev_intra: Intra-event standard deviation array. Note that different sites do not necessarily have the same intra-event standard deviation. :returns: Array of the same structure and semantics as ``residuals`` but with correlations applied. NB: the correlation matrix is cached. It is computed only once per IMT for the complete site collection and then the portion corresponding to the sites is multiplied by the residuals.
[ "Apply", "correlation", "to", "randomly", "sampled", "residuals", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/correlation.py#L29-L71
gem/oq-engine
openquake/hazardlib/correlation.py
JB2009CorrelationModel.get_lower_triangle_correlation_matrix
def get_lower_triangle_correlation_matrix(self, sites, imt): """ Get lower-triangle matrix as a result of Cholesky-decomposition of correlation matrix. The resulting matrix should have zeros on values above the main diagonal. The actual implementations of :class:`BaseCorrelationModel` interface might calculate the matrix considering site collection and IMT (like :class:`JB2009CorrelationModel` does) or might have it pre-constructed for a specific site collection and IMT, in which case they will need to make sure that parameters to this function match parameters that were used to pre-calculate decomposed correlation matrix. :param sites: :class:`~openquake.hazardlib.site.SiteCollection` to create correlation matrix for. :param imt: Intensity measure type object, see :mod:`openquake.hazardlib.imt`. """ return numpy.linalg.cholesky(self._get_correlation_matrix(sites, imt))
python
def get_lower_triangle_correlation_matrix(self, sites, imt): return numpy.linalg.cholesky(self._get_correlation_matrix(sites, imt))
[ "def", "get_lower_triangle_correlation_matrix", "(", "self", ",", "sites", ",", "imt", ")", ":", "return", "numpy", ".", "linalg", ".", "cholesky", "(", "self", ".", "_get_correlation_matrix", "(", "sites", ",", "imt", ")", ")" ]
Get lower-triangle matrix as a result of Cholesky-decomposition of correlation matrix. The resulting matrix should have zeros on values above the main diagonal. The actual implementations of :class:`BaseCorrelationModel` interface might calculate the matrix considering site collection and IMT (like :class:`JB2009CorrelationModel` does) or might have it pre-constructed for a specific site collection and IMT, in which case they will need to make sure that parameters to this function match parameters that were used to pre-calculate decomposed correlation matrix. :param sites: :class:`~openquake.hazardlib.site.SiteCollection` to create correlation matrix for. :param imt: Intensity measure type object, see :mod:`openquake.hazardlib.imt`.
[ "Get", "lower", "-", "triangle", "matrix", "as", "a", "result", "of", "Cholesky", "-", "decomposition", "of", "correlation", "matrix", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/correlation.py#L92-L113
gem/oq-engine
openquake/hazardlib/correlation.py
HM2018CorrelationModel.apply_correlation
def apply_correlation(self, sites, imt, residuals, stddev_intra): """ Apply correlation to randomly sampled residuals. See Parent function """ # stddev_intra is repeated if it is only 1 value for all the residuals if stddev_intra.shape[0] == 1: stddev_intra = numpy.matlib.repmat( stddev_intra, len(sites.complete), 1) # Reshape 'stddev_intra' if needed stddev_intra = stddev_intra.squeeze() if not stddev_intra.shape: stddev_intra = stddev_intra[None] if self.uncertainty_multiplier == 0: # No uncertainty # residuals were sampled from a normal distribution with # stddev_intra standard deviation. 'residuals_norm' are residuals # normalized, sampled from a standard normal distribution. # For this, every row of 'residuals' (every site) is divided by its # corresponding standard deviation element. residuals_norm = residuals / stddev_intra[sites.sids, None] # Lower diagonal of the Cholesky decomposition from/to cache try: cormaLow = self.cache[imt] except KeyError: # Note that instead of computing the whole correlation matrix # corresponding to sites.complete, here we compute only the # correlation matrix corresponding to sites. cormaLow = numpy.linalg.cholesky( numpy.diag(stddev_intra[sites.sids]) * self._get_correlation_matrix(sites, imt) * numpy.diag(stddev_intra[sites.sids])) self.cache[imt] = cormaLow # Apply correlation return numpy.dot(cormaLow, residuals_norm) else: # Variability (uncertainty) is included nsim = len(residuals[1]) nsites = len(residuals) # Re-sample all the residuals residuals_correlated = residuals * 0 for isim in range(0, nsim): corma = self._get_correlation_matrix(sites, imt) cov = (numpy.diag(stddev_intra[sites.sids]) * corma * numpy.diag(stddev_intra[sites.sids])) residuals_correlated[0:, isim] = ( numpy.random.multivariate_normal( numpy.zeros(nsites), cov, 1)) return residuals_correlated
python
def apply_correlation(self, sites, imt, residuals, stddev_intra): if stddev_intra.shape[0] == 1: stddev_intra = numpy.matlib.repmat( stddev_intra, len(sites.complete), 1) stddev_intra = stddev_intra.squeeze() if not stddev_intra.shape: stddev_intra = stddev_intra[None] if self.uncertainty_multiplier == 0: residuals_norm = residuals / stddev_intra[sites.sids, None] try: cormaLow = self.cache[imt] except KeyError: cormaLow = numpy.linalg.cholesky( numpy.diag(stddev_intra[sites.sids]) * self._get_correlation_matrix(sites, imt) * numpy.diag(stddev_intra[sites.sids])) self.cache[imt] = cormaLow return numpy.dot(cormaLow, residuals_norm) else: nsim = len(residuals[1]) nsites = len(residuals) residuals_correlated = residuals * 0 for isim in range(0, nsim): corma = self._get_correlation_matrix(sites, imt) cov = (numpy.diag(stddev_intra[sites.sids]) * corma * numpy.diag(stddev_intra[sites.sids])) residuals_correlated[0:, isim] = ( numpy.random.multivariate_normal( numpy.zeros(nsites), cov, 1)) return residuals_correlated
[ "def", "apply_correlation", "(", "self", ",", "sites", ",", "imt", ",", "residuals", ",", "stddev_intra", ")", ":", "# stddev_intra is repeated if it is only 1 value for all the residuals", "if", "stddev_intra", ".", "shape", "[", "0", "]", "==", "1", ":", "stddev_intra", "=", "numpy", ".", "matlib", ".", "repmat", "(", "stddev_intra", ",", "len", "(", "sites", ".", "complete", ")", ",", "1", ")", "# Reshape 'stddev_intra' if needed", "stddev_intra", "=", "stddev_intra", ".", "squeeze", "(", ")", "if", "not", "stddev_intra", ".", "shape", ":", "stddev_intra", "=", "stddev_intra", "[", "None", "]", "if", "self", ".", "uncertainty_multiplier", "==", "0", ":", "# No uncertainty", "# residuals were sampled from a normal distribution with", "# stddev_intra standard deviation. 'residuals_norm' are residuals", "# normalized, sampled from a standard normal distribution.", "# For this, every row of 'residuals' (every site) is divided by its", "# corresponding standard deviation element.", "residuals_norm", "=", "residuals", "/", "stddev_intra", "[", "sites", ".", "sids", ",", "None", "]", "# Lower diagonal of the Cholesky decomposition from/to cache", "try", ":", "cormaLow", "=", "self", ".", "cache", "[", "imt", "]", "except", "KeyError", ":", "# Note that instead of computing the whole correlation matrix", "# corresponding to sites.complete, here we compute only the", "# correlation matrix corresponding to sites.", "cormaLow", "=", "numpy", ".", "linalg", ".", "cholesky", "(", "numpy", ".", "diag", "(", "stddev_intra", "[", "sites", ".", "sids", "]", ")", "*", "self", ".", "_get_correlation_matrix", "(", "sites", ",", "imt", ")", "*", "numpy", ".", "diag", "(", "stddev_intra", "[", "sites", ".", "sids", "]", ")", ")", "self", ".", "cache", "[", "imt", "]", "=", "cormaLow", "# Apply correlation", "return", "numpy", ".", "dot", "(", "cormaLow", ",", "residuals_norm", ")", "else", ":", "# Variability (uncertainty) is included", "nsim", "=", "len", "(", "residuals", "[", "1", "]", ")", "nsites", "=", "len", "(", "residuals", ")", "# Re-sample all the residuals", "residuals_correlated", "=", "residuals", "*", "0", "for", "isim", "in", "range", "(", "0", ",", "nsim", ")", ":", "corma", "=", "self", ".", "_get_correlation_matrix", "(", "sites", ",", "imt", ")", "cov", "=", "(", "numpy", ".", "diag", "(", "stddev_intra", "[", "sites", ".", "sids", "]", ")", "*", "corma", "*", "numpy", ".", "diag", "(", "stddev_intra", "[", "sites", ".", "sids", "]", ")", ")", "residuals_correlated", "[", "0", ":", ",", "isim", "]", "=", "(", "numpy", ".", "random", ".", "multivariate_normal", "(", "numpy", ".", "zeros", "(", "nsites", ")", ",", "cov", ",", "1", ")", ")", "return", "residuals_correlated" ]
Apply correlation to randomly sampled residuals. See Parent function
[ "Apply", "correlation", "to", "randomly", "sampled", "residuals", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/correlation.py#L168-L222
gem/oq-engine
openquake/calculators/ebrisk.py
start_ebrisk
def start_ebrisk(rupgetter, srcfilter, param, monitor): """ Launcher for ebrisk tasks """ with monitor('weighting ruptures'): rupgetter.set_weights(srcfilter, param['num_taxonomies']) if rupgetter.weights.sum() <= param['maxweight']: yield ebrisk(rupgetter, srcfilter, param, monitor) else: for rgetter in rupgetter.split(param['maxweight']): yield ebrisk, rgetter, srcfilter, param
python
def start_ebrisk(rupgetter, srcfilter, param, monitor): with monitor('weighting ruptures'): rupgetter.set_weights(srcfilter, param['num_taxonomies']) if rupgetter.weights.sum() <= param['maxweight']: yield ebrisk(rupgetter, srcfilter, param, monitor) else: for rgetter in rupgetter.split(param['maxweight']): yield ebrisk, rgetter, srcfilter, param
[ "def", "start_ebrisk", "(", "rupgetter", ",", "srcfilter", ",", "param", ",", "monitor", ")", ":", "with", "monitor", "(", "'weighting ruptures'", ")", ":", "rupgetter", ".", "set_weights", "(", "srcfilter", ",", "param", "[", "'num_taxonomies'", "]", ")", "if", "rupgetter", ".", "weights", ".", "sum", "(", ")", "<=", "param", "[", "'maxweight'", "]", ":", "yield", "ebrisk", "(", "rupgetter", ",", "srcfilter", ",", "param", ",", "monitor", ")", "else", ":", "for", "rgetter", "in", "rupgetter", ".", "split", "(", "param", "[", "'maxweight'", "]", ")", ":", "yield", "ebrisk", ",", "rgetter", ",", "srcfilter", ",", "param" ]
Launcher for ebrisk tasks
[ "Launcher", "for", "ebrisk", "tasks" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ebrisk.py#L38-L48
gem/oq-engine
openquake/calculators/ebrisk.py
ebrisk
def ebrisk(rupgetter, srcfilter, param, monitor): """ :param rupgetter: a RuptureGetter instance :param srcfilter: a SourceFilter instance :param param: a dictionary of parameters :param monitor: :class:`openquake.baselib.performance.Monitor` instance :returns: an ArrayWrapper with shape (E, L, T, ...) """ riskmodel = param['riskmodel'] E = rupgetter.num_events L = len(riskmodel.lti) N = len(srcfilter.sitecol.complete) e1 = rupgetter.first_event with monitor('getting assets', measuremem=False): with datastore.read(srcfilter.filename) as dstore: assetcol = dstore['assetcol'] assets_by_site = assetcol.assets_by_site() A = len(assetcol) getter = getters.GmfGetter(rupgetter, srcfilter, param['oqparam']) with monitor('getting hazard'): getter.init() # instantiate the computers hazard = getter.get_hazard() # sid -> (rlzi, sid, eid, gmv) mon_risk = monitor('computing risk', measuremem=False) mon_agg = monitor('aggregating losses', measuremem=False) events = rupgetter.get_eid_rlz() # numpy.testing.assert_equal(events['eid'], sorted(events['eid'])) eid2idx = dict(zip(events['eid'], range(e1, e1 + E))) tagnames = param['aggregate_by'] shape = assetcol.tagcol.agg_shape((E, L), tagnames) elt_dt = [('eid', U64), ('rlzi', U16), ('loss', (F32, shape[1:]))] if param['asset_loss_table']: alt = numpy.zeros((A, E, L), F32) acc = numpy.zeros(shape, F32) # shape (E, L, T...) if param['avg_losses']: losses_by_A = numpy.zeros((A, L), F32) else: losses_by_A = 0 # NB: IMT-dependent weights are not supported in ebrisk times = numpy.zeros(N) # risk time per site_id num_events_per_sid = 0 epspath = param['epspath'] for sid, haz in hazard.items(): t0 = time.time() assets_on_sid = assets_by_site[sid] if len(assets_on_sid) == 0: continue num_events_per_sid += len(haz) weights = getter.weights[haz['rlzi'], 0] assets_by_taxo = get_assets_by_taxo(assets_on_sid, epspath) eidx = numpy.array([eid2idx[eid] for eid in haz['eid']]) - e1 haz['eid'] = eidx + e1 with mon_risk: out = riskmodel.get_output(assets_by_taxo, haz) with mon_agg: for a, asset in enumerate(assets_on_sid): aid = asset['ordinal'] tagi = asset[tagnames] if tagnames else () tagidxs = tuple(idx - 1 for idx in tagi) for lti, lt in enumerate(riskmodel.loss_types): lratios = out[lt][a] if lt == 'occupants': losses = lratios * asset['occupants_None'] else: losses = lratios * asset['value-' + lt] if param['asset_loss_table']: alt[aid, eidx, lti] = losses acc[(eidx, lti) + tagidxs] += losses if param['avg_losses']: losses_by_A[aid, lti] += losses @ weights times[sid] = time.time() - t0 if hazard: num_events_per_sid /= len(hazard) with monitor('building event loss table'): elt = numpy.fromiter( ((event['eid'], event['rlz'], losses) for event, losses in zip(events, acc) if losses.sum()), elt_dt) agg = general.AccumDict(accum=numpy.zeros(shape[1:], F32)) # rlz->agg for rec in elt: agg[rec['rlzi']] += rec['loss'] * param['ses_ratio'] res = {'elt': elt, 'agg_losses': agg, 'times': times, 'events_per_sid': num_events_per_sid} if param['avg_losses']: res['losses_by_A'] = losses_by_A * param['ses_ratio'] if param['asset_loss_table']: res['alt_eids'] = alt, events['eid'] return res
python
def ebrisk(rupgetter, srcfilter, param, monitor): riskmodel = param['riskmodel'] E = rupgetter.num_events L = len(riskmodel.lti) N = len(srcfilter.sitecol.complete) e1 = rupgetter.first_event with monitor('getting assets', measuremem=False): with datastore.read(srcfilter.filename) as dstore: assetcol = dstore['assetcol'] assets_by_site = assetcol.assets_by_site() A = len(assetcol) getter = getters.GmfGetter(rupgetter, srcfilter, param['oqparam']) with monitor('getting hazard'): getter.init() hazard = getter.get_hazard() mon_risk = monitor('computing risk', measuremem=False) mon_agg = monitor('aggregating losses', measuremem=False) events = rupgetter.get_eid_rlz() eid2idx = dict(zip(events['eid'], range(e1, e1 + E))) tagnames = param['aggregate_by'] shape = assetcol.tagcol.agg_shape((E, L), tagnames) elt_dt = [('eid', U64), ('rlzi', U16), ('loss', (F32, shape[1:]))] if param['asset_loss_table']: alt = numpy.zeros((A, E, L), F32) acc = numpy.zeros(shape, F32) if param['avg_losses']: losses_by_A = numpy.zeros((A, L), F32) else: losses_by_A = 0 times = numpy.zeros(N) num_events_per_sid = 0 epspath = param['epspath'] for sid, haz in hazard.items(): t0 = time.time() assets_on_sid = assets_by_site[sid] if len(assets_on_sid) == 0: continue num_events_per_sid += len(haz) weights = getter.weights[haz['rlzi'], 0] assets_by_taxo = get_assets_by_taxo(assets_on_sid, epspath) eidx = numpy.array([eid2idx[eid] for eid in haz['eid']]) - e1 haz['eid'] = eidx + e1 with mon_risk: out = riskmodel.get_output(assets_by_taxo, haz) with mon_agg: for a, asset in enumerate(assets_on_sid): aid = asset['ordinal'] tagi = asset[tagnames] if tagnames else () tagidxs = tuple(idx - 1 for idx in tagi) for lti, lt in enumerate(riskmodel.loss_types): lratios = out[lt][a] if lt == 'occupants': losses = lratios * asset['occupants_None'] else: losses = lratios * asset['value-' + lt] if param['asset_loss_table']: alt[aid, eidx, lti] = losses acc[(eidx, lti) + tagidxs] += losses if param['avg_losses']: losses_by_A[aid, lti] += losses @ weights times[sid] = time.time() - t0 if hazard: num_events_per_sid /= len(hazard) with monitor('building event loss table'): elt = numpy.fromiter( ((event['eid'], event['rlz'], losses) for event, losses in zip(events, acc) if losses.sum()), elt_dt) agg = general.AccumDict(accum=numpy.zeros(shape[1:], F32)) for rec in elt: agg[rec['rlzi']] += rec['loss'] * param['ses_ratio'] res = {'elt': elt, 'agg_losses': agg, 'times': times, 'events_per_sid': num_events_per_sid} if param['avg_losses']: res['losses_by_A'] = losses_by_A * param['ses_ratio'] if param['asset_loss_table']: res['alt_eids'] = alt, events['eid'] return res
[ "def", "ebrisk", "(", "rupgetter", ",", "srcfilter", ",", "param", ",", "monitor", ")", ":", "riskmodel", "=", "param", "[", "'riskmodel'", "]", "E", "=", "rupgetter", ".", "num_events", "L", "=", "len", "(", "riskmodel", ".", "lti", ")", "N", "=", "len", "(", "srcfilter", ".", "sitecol", ".", "complete", ")", "e1", "=", "rupgetter", ".", "first_event", "with", "monitor", "(", "'getting assets'", ",", "measuremem", "=", "False", ")", ":", "with", "datastore", ".", "read", "(", "srcfilter", ".", "filename", ")", "as", "dstore", ":", "assetcol", "=", "dstore", "[", "'assetcol'", "]", "assets_by_site", "=", "assetcol", ".", "assets_by_site", "(", ")", "A", "=", "len", "(", "assetcol", ")", "getter", "=", "getters", ".", "GmfGetter", "(", "rupgetter", ",", "srcfilter", ",", "param", "[", "'oqparam'", "]", ")", "with", "monitor", "(", "'getting hazard'", ")", ":", "getter", ".", "init", "(", ")", "# instantiate the computers", "hazard", "=", "getter", ".", "get_hazard", "(", ")", "# sid -> (rlzi, sid, eid, gmv)", "mon_risk", "=", "monitor", "(", "'computing risk'", ",", "measuremem", "=", "False", ")", "mon_agg", "=", "monitor", "(", "'aggregating losses'", ",", "measuremem", "=", "False", ")", "events", "=", "rupgetter", ".", "get_eid_rlz", "(", ")", "# numpy.testing.assert_equal(events['eid'], sorted(events['eid']))", "eid2idx", "=", "dict", "(", "zip", "(", "events", "[", "'eid'", "]", ",", "range", "(", "e1", ",", "e1", "+", "E", ")", ")", ")", "tagnames", "=", "param", "[", "'aggregate_by'", "]", "shape", "=", "assetcol", ".", "tagcol", ".", "agg_shape", "(", "(", "E", ",", "L", ")", ",", "tagnames", ")", "elt_dt", "=", "[", "(", "'eid'", ",", "U64", ")", ",", "(", "'rlzi'", ",", "U16", ")", ",", "(", "'loss'", ",", "(", "F32", ",", "shape", "[", "1", ":", "]", ")", ")", "]", "if", "param", "[", "'asset_loss_table'", "]", ":", "alt", "=", "numpy", ".", "zeros", "(", "(", "A", ",", "E", ",", "L", ")", ",", "F32", ")", "acc", "=", "numpy", ".", "zeros", "(", "shape", ",", "F32", ")", "# shape (E, L, T...)", "if", "param", "[", "'avg_losses'", "]", ":", "losses_by_A", "=", "numpy", ".", "zeros", "(", "(", "A", ",", "L", ")", ",", "F32", ")", "else", ":", "losses_by_A", "=", "0", "# NB: IMT-dependent weights are not supported in ebrisk", "times", "=", "numpy", ".", "zeros", "(", "N", ")", "# risk time per site_id", "num_events_per_sid", "=", "0", "epspath", "=", "param", "[", "'epspath'", "]", "for", "sid", ",", "haz", "in", "hazard", ".", "items", "(", ")", ":", "t0", "=", "time", ".", "time", "(", ")", "assets_on_sid", "=", "assets_by_site", "[", "sid", "]", "if", "len", "(", "assets_on_sid", ")", "==", "0", ":", "continue", "num_events_per_sid", "+=", "len", "(", "haz", ")", "weights", "=", "getter", ".", "weights", "[", "haz", "[", "'rlzi'", "]", ",", "0", "]", "assets_by_taxo", "=", "get_assets_by_taxo", "(", "assets_on_sid", ",", "epspath", ")", "eidx", "=", "numpy", ".", "array", "(", "[", "eid2idx", "[", "eid", "]", "for", "eid", "in", "haz", "[", "'eid'", "]", "]", ")", "-", "e1", "haz", "[", "'eid'", "]", "=", "eidx", "+", "e1", "with", "mon_risk", ":", "out", "=", "riskmodel", ".", "get_output", "(", "assets_by_taxo", ",", "haz", ")", "with", "mon_agg", ":", "for", "a", ",", "asset", "in", "enumerate", "(", "assets_on_sid", ")", ":", "aid", "=", "asset", "[", "'ordinal'", "]", "tagi", "=", "asset", "[", "tagnames", "]", "if", "tagnames", "else", "(", ")", "tagidxs", "=", "tuple", "(", "idx", "-", "1", "for", "idx", "in", "tagi", ")", "for", "lti", ",", "lt", "in", "enumerate", "(", "riskmodel", ".", "loss_types", ")", ":", "lratios", "=", "out", "[", "lt", "]", "[", "a", "]", "if", "lt", "==", "'occupants'", ":", "losses", "=", "lratios", "*", "asset", "[", "'occupants_None'", "]", "else", ":", "losses", "=", "lratios", "*", "asset", "[", "'value-'", "+", "lt", "]", "if", "param", "[", "'asset_loss_table'", "]", ":", "alt", "[", "aid", ",", "eidx", ",", "lti", "]", "=", "losses", "acc", "[", "(", "eidx", ",", "lti", ")", "+", "tagidxs", "]", "+=", "losses", "if", "param", "[", "'avg_losses'", "]", ":", "losses_by_A", "[", "aid", ",", "lti", "]", "+=", "losses", "@", "weights", "times", "[", "sid", "]", "=", "time", ".", "time", "(", ")", "-", "t0", "if", "hazard", ":", "num_events_per_sid", "/=", "len", "(", "hazard", ")", "with", "monitor", "(", "'building event loss table'", ")", ":", "elt", "=", "numpy", ".", "fromiter", "(", "(", "(", "event", "[", "'eid'", "]", ",", "event", "[", "'rlz'", "]", ",", "losses", ")", "for", "event", ",", "losses", "in", "zip", "(", "events", ",", "acc", ")", "if", "losses", ".", "sum", "(", ")", ")", ",", "elt_dt", ")", "agg", "=", "general", ".", "AccumDict", "(", "accum", "=", "numpy", ".", "zeros", "(", "shape", "[", "1", ":", "]", ",", "F32", ")", ")", "# rlz->agg", "for", "rec", "in", "elt", ":", "agg", "[", "rec", "[", "'rlzi'", "]", "]", "+=", "rec", "[", "'loss'", "]", "*", "param", "[", "'ses_ratio'", "]", "res", "=", "{", "'elt'", ":", "elt", ",", "'agg_losses'", ":", "agg", ",", "'times'", ":", "times", ",", "'events_per_sid'", ":", "num_events_per_sid", "}", "if", "param", "[", "'avg_losses'", "]", ":", "res", "[", "'losses_by_A'", "]", "=", "losses_by_A", "*", "param", "[", "'ses_ratio'", "]", "if", "param", "[", "'asset_loss_table'", "]", ":", "res", "[", "'alt_eids'", "]", "=", "alt", ",", "events", "[", "'eid'", "]", "return", "res" ]
:param rupgetter: a RuptureGetter instance :param srcfilter: a SourceFilter instance :param param: a dictionary of parameters :param monitor: :class:`openquake.baselib.performance.Monitor` instance :returns: an ArrayWrapper with shape (E, L, T, ...)
[ ":", "param", "rupgetter", ":", "a", "RuptureGetter", "instance", ":", "param", "srcfilter", ":", "a", "SourceFilter", "instance", ":", "param", "param", ":", "a", "dictionary", "of", "parameters", ":", "param", "monitor", ":", ":", "class", ":", "openquake", ".", "baselib", ".", "performance", ".", "Monitor", "instance", ":", "returns", ":", "an", "ArrayWrapper", "with", "shape", "(", "E", "L", "T", "...", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ebrisk.py#L51-L141
gem/oq-engine
openquake/calculators/ebrisk.py
compute_loss_curves_maps
def compute_loss_curves_maps(filename, builder, rlzi, monitor): """ :param filename: path to the datastore :param builder: LossCurvesMapsBuilder instance :param rlzi: realization index :param monitor: Monitor instance :returns: rlzi, (curves, maps) """ with datastore.read(filename) as dstore: rlzs = dstore['losses_by_event']['rlzi'] losses = dstore['losses_by_event'][rlzs == rlzi]['loss'] return rlzi, builder.build_curves_maps(losses, rlzi)
python
def compute_loss_curves_maps(filename, builder, rlzi, monitor): with datastore.read(filename) as dstore: rlzs = dstore['losses_by_event']['rlzi'] losses = dstore['losses_by_event'][rlzs == rlzi]['loss'] return rlzi, builder.build_curves_maps(losses, rlzi)
[ "def", "compute_loss_curves_maps", "(", "filename", ",", "builder", ",", "rlzi", ",", "monitor", ")", ":", "with", "datastore", ".", "read", "(", "filename", ")", "as", "dstore", ":", "rlzs", "=", "dstore", "[", "'losses_by_event'", "]", "[", "'rlzi'", "]", "losses", "=", "dstore", "[", "'losses_by_event'", "]", "[", "rlzs", "==", "rlzi", "]", "[", "'loss'", "]", "return", "rlzi", ",", "builder", ".", "build_curves_maps", "(", "losses", ",", "rlzi", ")" ]
:param filename: path to the datastore :param builder: LossCurvesMapsBuilder instance :param rlzi: realization index :param monitor: Monitor instance :returns: rlzi, (curves, maps)
[ ":", "param", "filename", ":", "path", "to", "the", "datastore", ":", "param", "builder", ":", "LossCurvesMapsBuilder", "instance", ":", "param", "rlzi", ":", "realization", "index", ":", "param", "monitor", ":", "Monitor", "instance", ":", "returns", ":", "rlzi", "(", "curves", "maps", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ebrisk.py#L362-L373
gem/oq-engine
openquake/hazardlib/mfd/youngs_coppersmith_1985.py
YoungsCoppersmith1985MFD.get_min_max_mag
def get_min_max_mag(self): "Return the minimum and maximum magnitudes" mag, num_bins = self._get_min_mag_and_num_bins() return mag, mag + self. bin_width * (num_bins - 1)
python
def get_min_max_mag(self): "Return the minimum and maximum magnitudes" mag, num_bins = self._get_min_mag_and_num_bins() return mag, mag + self. bin_width * (num_bins - 1)
[ "def", "get_min_max_mag", "(", "self", ")", ":", "mag", ",", "num_bins", "=", "self", ".", "_get_min_mag_and_num_bins", "(", ")", "return", "mag", ",", "mag", "+", "self", ".", "bin_width", "*", "(", "num_bins", "-", "1", ")" ]
Return the minimum and maximum magnitudes
[ "Return", "the", "minimum", "and", "maximum", "magnitudes" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L91-L94
gem/oq-engine
openquake/hazardlib/mfd/youngs_coppersmith_1985.py
YoungsCoppersmith1985MFD.check_constraints
def check_constraints(self): """ Checks the following constraints: * minimum magnitude is positive. * ``b`` value is positive. * characteristic magnitude is positive * characteristic rate is positive * bin width is in the range (0, 0.5] to allow for at least one bin representing the characteristic distribution * characteristic magnitude minus 0.25 (that is the maximum magnitude of the G-R distribution) is greater than the minimum magnitude by at least one magnitude bin. * rate of events at the characteristic magnitude is equal to the rate of events for magnitude equal to m_prime - 1. This is done by asserting the equality (up to 7 digit precision) :: 10 ** (a_incr - b * (m' - 1)) == char_rate / 0.5 where ``a_incr`` is the incremental a value obtained from the cumulative a value using the following formula :: a_incr = a_val + log10(b_val * ln(10)) and ``m' - 1 = char_mag - 1.25`` """ if not self.min_mag > 0: raise ValueError('minimum magnitude must be positive') if not self.b_val > 0: raise ValueError('b value must be positive') if not self.char_mag > 0: raise ValueError('characteristic magnitude must be positive') if not self.char_rate > 0: raise ValueError('characteristic rate must be positive') if not 0 < self.bin_width <= DELTA_CHAR: err_msg = 'bin width must be in the range (0, %s] to allow for ' \ 'at least one magnitude bin representing the ' \ 'characteristic distribution' % DELTA_CHAR raise ValueError(err_msg) if not self.char_mag - DELTA_CHAR / 2 >= self.min_mag + self.bin_width: err_msg = 'Maximum magnitude of the G-R distribution (char_mag ' \ '- 0.25) must be greater than the minimum magnitude ' \ 'by at least one magnitude bin.' raise ValueError(err_msg) a_incr = self.a_val + numpy.log10(self.b_val * numpy.log(10)) actual = 10 ** (a_incr - self.b_val * (self.char_mag - 1.25)) desired = self.char_rate / DELTA_CHAR if not numpy.allclose(actual, desired, rtol=0.0, atol=1e-07): err_msg = 'Rate of events at the characteristic magnitude is ' \ 'not equal to the rate of events for magnitude equal ' \ 'to char_mag - 1.25' raise ValueError(err_msg)
python
def check_constraints(self): if not self.min_mag > 0: raise ValueError('minimum magnitude must be positive') if not self.b_val > 0: raise ValueError('b value must be positive') if not self.char_mag > 0: raise ValueError('characteristic magnitude must be positive') if not self.char_rate > 0: raise ValueError('characteristic rate must be positive') if not 0 < self.bin_width <= DELTA_CHAR: err_msg = 'bin width must be in the range (0, %s] to allow for ' \ 'at least one magnitude bin representing the ' \ 'characteristic distribution' % DELTA_CHAR raise ValueError(err_msg) if not self.char_mag - DELTA_CHAR / 2 >= self.min_mag + self.bin_width: err_msg = 'Maximum magnitude of the G-R distribution (char_mag ' \ '- 0.25) must be greater than the minimum magnitude ' \ 'by at least one magnitude bin.' raise ValueError(err_msg) a_incr = self.a_val + numpy.log10(self.b_val * numpy.log(10)) actual = 10 ** (a_incr - self.b_val * (self.char_mag - 1.25)) desired = self.char_rate / DELTA_CHAR if not numpy.allclose(actual, desired, rtol=0.0, atol=1e-07): err_msg = 'Rate of events at the characteristic magnitude is ' \ 'not equal to the rate of events for magnitude equal ' \ 'to char_mag - 1.25' raise ValueError(err_msg)
[ "def", "check_constraints", "(", "self", ")", ":", "if", "not", "self", ".", "min_mag", ">", "0", ":", "raise", "ValueError", "(", "'minimum magnitude must be positive'", ")", "if", "not", "self", ".", "b_val", ">", "0", ":", "raise", "ValueError", "(", "'b value must be positive'", ")", "if", "not", "self", ".", "char_mag", ">", "0", ":", "raise", "ValueError", "(", "'characteristic magnitude must be positive'", ")", "if", "not", "self", ".", "char_rate", ">", "0", ":", "raise", "ValueError", "(", "'characteristic rate must be positive'", ")", "if", "not", "0", "<", "self", ".", "bin_width", "<=", "DELTA_CHAR", ":", "err_msg", "=", "'bin width must be in the range (0, %s] to allow for '", "'at least one magnitude bin representing the '", "'characteristic distribution'", "%", "DELTA_CHAR", "raise", "ValueError", "(", "err_msg", ")", "if", "not", "self", ".", "char_mag", "-", "DELTA_CHAR", "/", "2", ">=", "self", ".", "min_mag", "+", "self", ".", "bin_width", ":", "err_msg", "=", "'Maximum magnitude of the G-R distribution (char_mag '", "'- 0.25) must be greater than the minimum magnitude '", "'by at least one magnitude bin.'", "raise", "ValueError", "(", "err_msg", ")", "a_incr", "=", "self", ".", "a_val", "+", "numpy", ".", "log10", "(", "self", ".", "b_val", "*", "numpy", ".", "log", "(", "10", ")", ")", "actual", "=", "10", "**", "(", "a_incr", "-", "self", ".", "b_val", "*", "(", "self", ".", "char_mag", "-", "1.25", ")", ")", "desired", "=", "self", ".", "char_rate", "/", "DELTA_CHAR", "if", "not", "numpy", ".", "allclose", "(", "actual", ",", "desired", ",", "rtol", "=", "0.0", ",", "atol", "=", "1e-07", ")", ":", "err_msg", "=", "'Rate of events at the characteristic magnitude is '", "'not equal to the rate of events for magnitude equal '", "'to char_mag - 1.25'", "raise", "ValueError", "(", "err_msg", ")" ]
Checks the following constraints: * minimum magnitude is positive. * ``b`` value is positive. * characteristic magnitude is positive * characteristic rate is positive * bin width is in the range (0, 0.5] to allow for at least one bin representing the characteristic distribution * characteristic magnitude minus 0.25 (that is the maximum magnitude of the G-R distribution) is greater than the minimum magnitude by at least one magnitude bin. * rate of events at the characteristic magnitude is equal to the rate of events for magnitude equal to m_prime - 1. This is done by asserting the equality (up to 7 digit precision) :: 10 ** (a_incr - b * (m' - 1)) == char_rate / 0.5 where ``a_incr`` is the incremental a value obtained from the cumulative a value using the following formula :: a_incr = a_val + log10(b_val * ln(10)) and ``m' - 1 = char_mag - 1.25``
[ "Checks", "the", "following", "constraints", ":" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L96-L153
gem/oq-engine
openquake/hazardlib/mfd/youngs_coppersmith_1985.py
YoungsCoppersmith1985MFD.from_total_moment_rate
def from_total_moment_rate(cls, min_mag, b_val, char_mag, total_moment_rate, bin_width): """ Define Youngs and Coppersmith 1985 MFD by constraing cumulative a value and characteristic rate from total moment rate. The cumulative a value and characteristic rate are obtained by solving equations (16) and (17), page 954, for the cumulative rate of events with magnitude greater than the minimum magnitude - N(min_mag) - and the cumulative rate of characteristic earthquakes - N(char_mag). The difference ``N(min_mag) - N(char_mag)`` represents the rate of noncharacteristic, exponentially distributed earthquakes and is used to derive the cumulative a value by solving the following equation :: 10 ** (a_val - b_val * min_mag) - 10 ** (a_val - b_val * (char_mag - 0.25)) = N(min_mag) - N(char_mag) which can be written as :: a_val = log10(N(min_mag) - N(char_mag)) / (10 ** (- b_val * min_mag) - 10 ** (- b_val * (char_mag - 0.25)) In the calculation of N(min_mag) and N(char_mag), the Hanks and Kanamori (1979) formula :: M0 = 10 ** (1.5 * Mw + 9.05) is used to convert moment magnitude (Mw) to seismic moment (M0, Newton × m) :param min_mag: The lowest magnitude for the MFD. The first bin in the :meth:`result histogram <get_annual_occurrence_rates>` is aligned to make its left border match this value. :param b_val: The Gutenberg-Richter ``b`` value -- the gradient of the loglinear G-R relationship. :param char_mag: The characteristic magnitude defining the middle point of characteristic distribution. That is the boxcar function representing the characteristic distribution is defined in the range [char_mag - 0.25, char_mag + 0.25]. :param total_moment_rate: Total moment rate in N * m / year. :param bin_width: A positive float value -- the width of a single histogram bin. :returns: An instance of :class:`YoungsCoppersmith1985MFD`. Values for ``min_mag`` and the maximum magnitude (char_mag + 0.25) don't have to be aligned with respect to ``bin_width``. They get rounded accordingly anyway so that both are divisible by ``bin_width`` just before converting a function to a histogram. See :meth:`_get_min_mag_and_num_bins`. """ beta = b_val * numpy.log(10) mu = char_mag + DELTA_CHAR / 2 m0 = min_mag # seismic moment (in Nm) for the maximum magnitude c = 1.5 d = 9.05 mo_u = 10 ** (c * mu + d) # equations (16) and (17) solved for N(min_mag) and N(char_mag) c1 = numpy.exp(-beta * (mu - m0 - 0.5)) c2 = numpy.exp(-beta * (mu - m0 - 1.5)) c3 = beta * c2 / (2 * (1 - c1) + beta * c2) c4 = (b_val * (10 ** (-c / 2)) / (c - b_val)) + \ (b_val * numpy.exp(beta) * (1 - (10 ** (-c / 2))) / c) n_min_mag = (1 - c1) * total_moment_rate / ((1 - c3) * c1 * mo_u * c4) n_char_mag = c3 * n_min_mag a_val = numpy.log10( (n_min_mag - n_char_mag) / (10 ** (- b_val * min_mag) - 10 ** (- b_val * (char_mag - 0.25))) ) return cls(min_mag, a_val, b_val, char_mag, n_char_mag, bin_width)
python
def from_total_moment_rate(cls, min_mag, b_val, char_mag, total_moment_rate, bin_width): beta = b_val * numpy.log(10) mu = char_mag + DELTA_CHAR / 2 m0 = min_mag c = 1.5 d = 9.05 mo_u = 10 ** (c * mu + d) c1 = numpy.exp(-beta * (mu - m0 - 0.5)) c2 = numpy.exp(-beta * (mu - m0 - 1.5)) c3 = beta * c2 / (2 * (1 - c1) + beta * c2) c4 = (b_val * (10 ** (-c / 2)) / (c - b_val)) + \ (b_val * numpy.exp(beta) * (1 - (10 ** (-c / 2))) / c) n_min_mag = (1 - c1) * total_moment_rate / ((1 - c3) * c1 * mo_u * c4) n_char_mag = c3 * n_min_mag a_val = numpy.log10( (n_min_mag - n_char_mag) / (10 ** (- b_val * min_mag) - 10 ** (- b_val * (char_mag - 0.25))) ) return cls(min_mag, a_val, b_val, char_mag, n_char_mag, bin_width)
[ "def", "from_total_moment_rate", "(", "cls", ",", "min_mag", ",", "b_val", ",", "char_mag", ",", "total_moment_rate", ",", "bin_width", ")", ":", "beta", "=", "b_val", "*", "numpy", ".", "log", "(", "10", ")", "mu", "=", "char_mag", "+", "DELTA_CHAR", "/", "2", "m0", "=", "min_mag", "# seismic moment (in Nm) for the maximum magnitude", "c", "=", "1.5", "d", "=", "9.05", "mo_u", "=", "10", "**", "(", "c", "*", "mu", "+", "d", ")", "# equations (16) and (17) solved for N(min_mag) and N(char_mag)", "c1", "=", "numpy", ".", "exp", "(", "-", "beta", "*", "(", "mu", "-", "m0", "-", "0.5", ")", ")", "c2", "=", "numpy", ".", "exp", "(", "-", "beta", "*", "(", "mu", "-", "m0", "-", "1.5", ")", ")", "c3", "=", "beta", "*", "c2", "/", "(", "2", "*", "(", "1", "-", "c1", ")", "+", "beta", "*", "c2", ")", "c4", "=", "(", "b_val", "*", "(", "10", "**", "(", "-", "c", "/", "2", ")", ")", "/", "(", "c", "-", "b_val", ")", ")", "+", "(", "b_val", "*", "numpy", ".", "exp", "(", "beta", ")", "*", "(", "1", "-", "(", "10", "**", "(", "-", "c", "/", "2", ")", ")", ")", "/", "c", ")", "n_min_mag", "=", "(", "1", "-", "c1", ")", "*", "total_moment_rate", "/", "(", "(", "1", "-", "c3", ")", "*", "c1", "*", "mo_u", "*", "c4", ")", "n_char_mag", "=", "c3", "*", "n_min_mag", "a_val", "=", "numpy", ".", "log10", "(", "(", "n_min_mag", "-", "n_char_mag", ")", "/", "(", "10", "**", "(", "-", "b_val", "*", "min_mag", ")", "-", "10", "**", "(", "-", "b_val", "*", "(", "char_mag", "-", "0.25", ")", ")", ")", ")", "return", "cls", "(", "min_mag", ",", "a_val", ",", "b_val", ",", "char_mag", ",", "n_char_mag", ",", "bin_width", ")" ]
Define Youngs and Coppersmith 1985 MFD by constraing cumulative a value and characteristic rate from total moment rate. The cumulative a value and characteristic rate are obtained by solving equations (16) and (17), page 954, for the cumulative rate of events with magnitude greater than the minimum magnitude - N(min_mag) - and the cumulative rate of characteristic earthquakes - N(char_mag). The difference ``N(min_mag) - N(char_mag)`` represents the rate of noncharacteristic, exponentially distributed earthquakes and is used to derive the cumulative a value by solving the following equation :: 10 ** (a_val - b_val * min_mag) - 10 ** (a_val - b_val * (char_mag - 0.25)) = N(min_mag) - N(char_mag) which can be written as :: a_val = log10(N(min_mag) - N(char_mag)) / (10 ** (- b_val * min_mag) - 10 ** (- b_val * (char_mag - 0.25)) In the calculation of N(min_mag) and N(char_mag), the Hanks and Kanamori (1979) formula :: M0 = 10 ** (1.5 * Mw + 9.05) is used to convert moment magnitude (Mw) to seismic moment (M0, Newton × m) :param min_mag: The lowest magnitude for the MFD. The first bin in the :meth:`result histogram <get_annual_occurrence_rates>` is aligned to make its left border match this value. :param b_val: The Gutenberg-Richter ``b`` value -- the gradient of the loglinear G-R relationship. :param char_mag: The characteristic magnitude defining the middle point of characteristic distribution. That is the boxcar function representing the characteristic distribution is defined in the range [char_mag - 0.25, char_mag + 0.25]. :param total_moment_rate: Total moment rate in N * m / year. :param bin_width: A positive float value -- the width of a single histogram bin. :returns: An instance of :class:`YoungsCoppersmith1985MFD`. Values for ``min_mag`` and the maximum magnitude (char_mag + 0.25) don't have to be aligned with respect to ``bin_width``. They get rounded accordingly anyway so that both are divisible by ``bin_width`` just before converting a function to a histogram. See :meth:`_get_min_mag_and_num_bins`.
[ "Define", "Youngs", "and", "Coppersmith", "1985", "MFD", "by", "constraing", "cumulative", "a", "value", "and", "characteristic", "rate", "from", "total", "moment", "rate", ".", "The", "cumulative", "a", "value", "and", "characteristic", "rate", "are", "obtained", "by", "solving", "equations", "(", "16", ")", "and", "(", "17", ")", "page", "954", "for", "the", "cumulative", "rate", "of", "events", "with", "magnitude", "greater", "than", "the", "minimum", "magnitude", "-", "N", "(", "min_mag", ")", "-", "and", "the", "cumulative", "rate", "of", "characteristic", "earthquakes", "-", "N", "(", "char_mag", ")", ".", "The", "difference", "N", "(", "min_mag", ")", "-", "N", "(", "char_mag", ")", "represents", "the", "rate", "of", "noncharacteristic", "exponentially", "distributed", "earthquakes", "and", "is", "used", "to", "derive", "the", "cumulative", "a", "value", "by", "solving", "the", "following", "equation", "::" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L156-L235
gem/oq-engine
openquake/hazardlib/mfd/youngs_coppersmith_1985.py
YoungsCoppersmith1985MFD.from_characteristic_rate
def from_characteristic_rate(cls, min_mag, b_val, char_mag, char_rate, bin_width): """ Define Youngs and Coppersmith 1985 MFD by constraing cumulative a value from characteristic rate. The cumulative a value is obtained by making use of the property that the rate of events at m' - 1 must be equal to the rate at the characteristic magnitude, and therefore by first computing the incremental a value, using the following equation:: 10 ** (a_incr - b_val * (m_prime - 1)) == char_rate / 0.5 where ``m' - 1 = char_mag - 1.25``. The cumulative a value is then obtained as :: a_val = a_incr - log10(b_val * ln(10)) :param min_mag: The lowest magnitude for the MFD. The first bin in the :meth:`result histogram <get_annual_occurrence_rates>` is aligned to make its left border match this value. :param b_val: The Gutenberg-Richter ``b`` value -- the gradient of the loglinear G-R relationship. :param char_mag: The characteristic magnitude defining the middle point of characteristic distribution. That is the boxcar function representing the characteristic distribution is defined in the range [char_mag - 0.25, char_mag + 0.25]. :param char_rate: The characteristic rate associated to the characteristic magnitude, to be distributed over the domain of the boxcar function representing the characteristic distribution (that is λ_char = char_rate / 0.5) :param bin_width: A positive float value -- the width of a single histogram bin. :returns: An instance of :class:`YoungsCoppersmith1985MFD`. Values for ``min_mag`` and the maximum magnitude (char_mag + 0.25) don't have to be aligned with respect to ``bin_width``. They get rounded accordingly anyway so that both are divisible by ``bin_width`` just before converting a function to a histogram. See :meth:`_get_min_mag_and_num_bins`. """ a_incr = b_val * (char_mag - 1.25) + numpy.log10(char_rate / DELTA_CHAR) a_val = a_incr - numpy.log10(b_val * numpy.log(10)) return cls(min_mag, a_val, b_val, char_mag, char_rate, bin_width)
python
def from_characteristic_rate(cls, min_mag, b_val, char_mag, char_rate, bin_width): a_incr = b_val * (char_mag - 1.25) + numpy.log10(char_rate / DELTA_CHAR) a_val = a_incr - numpy.log10(b_val * numpy.log(10)) return cls(min_mag, a_val, b_val, char_mag, char_rate, bin_width)
[ "def", "from_characteristic_rate", "(", "cls", ",", "min_mag", ",", "b_val", ",", "char_mag", ",", "char_rate", ",", "bin_width", ")", ":", "a_incr", "=", "b_val", "*", "(", "char_mag", "-", "1.25", ")", "+", "numpy", ".", "log10", "(", "char_rate", "/", "DELTA_CHAR", ")", "a_val", "=", "a_incr", "-", "numpy", ".", "log10", "(", "b_val", "*", "numpy", ".", "log", "(", "10", ")", ")", "return", "cls", "(", "min_mag", ",", "a_val", ",", "b_val", ",", "char_mag", ",", "char_rate", ",", "bin_width", ")" ]
Define Youngs and Coppersmith 1985 MFD by constraing cumulative a value from characteristic rate. The cumulative a value is obtained by making use of the property that the rate of events at m' - 1 must be equal to the rate at the characteristic magnitude, and therefore by first computing the incremental a value, using the following equation:: 10 ** (a_incr - b_val * (m_prime - 1)) == char_rate / 0.5 where ``m' - 1 = char_mag - 1.25``. The cumulative a value is then obtained as :: a_val = a_incr - log10(b_val * ln(10)) :param min_mag: The lowest magnitude for the MFD. The first bin in the :meth:`result histogram <get_annual_occurrence_rates>` is aligned to make its left border match this value. :param b_val: The Gutenberg-Richter ``b`` value -- the gradient of the loglinear G-R relationship. :param char_mag: The characteristic magnitude defining the middle point of characteristic distribution. That is the boxcar function representing the characteristic distribution is defined in the range [char_mag - 0.25, char_mag + 0.25]. :param char_rate: The characteristic rate associated to the characteristic magnitude, to be distributed over the domain of the boxcar function representing the characteristic distribution (that is λ_char = char_rate / 0.5) :param bin_width: A positive float value -- the width of a single histogram bin. :returns: An instance of :class:`YoungsCoppersmith1985MFD`. Values for ``min_mag`` and the maximum magnitude (char_mag + 0.25) don't have to be aligned with respect to ``bin_width``. They get rounded accordingly anyway so that both are divisible by ``bin_width`` just before converting a function to a histogram. See :meth:`_get_min_mag_and_num_bins`.
[ "Define", "Youngs", "and", "Coppersmith", "1985", "MFD", "by", "constraing", "cumulative", "a", "value", "from", "characteristic", "rate", ".", "The", "cumulative", "a", "value", "is", "obtained", "by", "making", "use", "of", "the", "property", "that", "the", "rate", "of", "events", "at", "m", "-", "1", "must", "be", "equal", "to", "the", "rate", "at", "the", "characteristic", "magnitude", "and", "therefore", "by", "first", "computing", "the", "incremental", "a", "value", "using", "the", "following", "equation", "::" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L238-L287
gem/oq-engine
openquake/hazardlib/mfd/youngs_coppersmith_1985.py
YoungsCoppersmith1985MFD._get_rate
def _get_rate(self, mag): """ Calculate and return the annual occurrence rate for a specific bin. :param mag: Magnitude value corresponding to the center of the bin of interest. :returns: Float number, the annual occurrence rate for the :param mag value. """ mag_lo = mag - self.bin_width / 2.0 mag_hi = mag + self.bin_width / 2.0 if mag >= self.min_mag and mag < self.char_mag - DELTA_CHAR / 2: # return rate according to exponential distribution return (10 ** (self.a_val - self.b_val * mag_lo) - 10 ** (self.a_val - self.b_val * mag_hi)) else: # return characteristic rate (distributed over the characteristic # range) for the given bin width return (self.char_rate / DELTA_CHAR) * self.bin_width
python
def _get_rate(self, mag): mag_lo = mag - self.bin_width / 2.0 mag_hi = mag + self.bin_width / 2.0 if mag >= self.min_mag and mag < self.char_mag - DELTA_CHAR / 2: return (10 ** (self.a_val - self.b_val * mag_lo) - 10 ** (self.a_val - self.b_val * mag_hi)) else: return (self.char_rate / DELTA_CHAR) * self.bin_width
[ "def", "_get_rate", "(", "self", ",", "mag", ")", ":", "mag_lo", "=", "mag", "-", "self", ".", "bin_width", "/", "2.0", "mag_hi", "=", "mag", "+", "self", ".", "bin_width", "/", "2.0", "if", "mag", ">=", "self", ".", "min_mag", "and", "mag", "<", "self", ".", "char_mag", "-", "DELTA_CHAR", "/", "2", ":", "# return rate according to exponential distribution", "return", "(", "10", "**", "(", "self", ".", "a_val", "-", "self", ".", "b_val", "*", "mag_lo", ")", "-", "10", "**", "(", "self", ".", "a_val", "-", "self", ".", "b_val", "*", "mag_hi", ")", ")", "else", ":", "# return characteristic rate (distributed over the characteristic", "# range) for the given bin width", "return", "(", "self", ".", "char_rate", "/", "DELTA_CHAR", ")", "*", "self", ".", "bin_width" ]
Calculate and return the annual occurrence rate for a specific bin. :param mag: Magnitude value corresponding to the center of the bin of interest. :returns: Float number, the annual occurrence rate for the :param mag value.
[ "Calculate", "and", "return", "the", "annual", "occurrence", "rate", "for", "a", "specific", "bin", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L289-L308
gem/oq-engine
openquake/hazardlib/mfd/youngs_coppersmith_1985.py
YoungsCoppersmith1985MFD._get_min_mag_and_num_bins
def _get_min_mag_and_num_bins(self): """ Estimate the number of bins in the histogram and return it along with the first bin center value. Rounds ``min_mag`` and ``max_mag`` with respect to ``bin_width`` to make the distance between them include integer number of bins. :returns: A tuple of 2 items: first bin center, and total number of bins. """ min_mag = round(self.min_mag / self.bin_width) * self.bin_width max_mag = (round((self.char_mag + DELTA_CHAR / 2) / self.bin_width) * self.bin_width) min_mag += self.bin_width / 2.0 max_mag -= self.bin_width / 2.0 # here we use math round on the result of division and not just # cast it to integer because for some magnitude values that can't # be represented as an IEEE 754 double precisely the result can # look like 7.999999999999 which would become 7 instead of 8 # being naively casted to int so we would lose the last bin. num_bins = int(round((max_mag - min_mag) / self.bin_width)) + 1 return min_mag, num_bins
python
def _get_min_mag_and_num_bins(self): min_mag = round(self.min_mag / self.bin_width) * self.bin_width max_mag = (round((self.char_mag + DELTA_CHAR / 2) / self.bin_width) * self.bin_width) min_mag += self.bin_width / 2.0 max_mag -= self.bin_width / 2.0 num_bins = int(round((max_mag - min_mag) / self.bin_width)) + 1 return min_mag, num_bins
[ "def", "_get_min_mag_and_num_bins", "(", "self", ")", ":", "min_mag", "=", "round", "(", "self", ".", "min_mag", "/", "self", ".", "bin_width", ")", "*", "self", ".", "bin_width", "max_mag", "=", "(", "round", "(", "(", "self", ".", "char_mag", "+", "DELTA_CHAR", "/", "2", ")", "/", "self", ".", "bin_width", ")", "*", "self", ".", "bin_width", ")", "min_mag", "+=", "self", ".", "bin_width", "/", "2.0", "max_mag", "-=", "self", ".", "bin_width", "/", "2.0", "# here we use math round on the result of division and not just", "# cast it to integer because for some magnitude values that can't", "# be represented as an IEEE 754 double precisely the result can", "# look like 7.999999999999 which would become 7 instead of 8", "# being naively casted to int so we would lose the last bin.", "num_bins", "=", "int", "(", "round", "(", "(", "max_mag", "-", "min_mag", ")", "/", "self", ".", "bin_width", ")", ")", "+", "1", "return", "min_mag", ",", "num_bins" ]
Estimate the number of bins in the histogram and return it along with the first bin center value. Rounds ``min_mag`` and ``max_mag`` with respect to ``bin_width`` to make the distance between them include integer number of bins. :returns: A tuple of 2 items: first bin center, and total number of bins.
[ "Estimate", "the", "number", "of", "bins", "in", "the", "histogram", "and", "return", "it", "along", "with", "the", "first", "bin", "center", "value", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L310-L332
gem/oq-engine
openquake/hazardlib/mfd/youngs_coppersmith_1985.py
YoungsCoppersmith1985MFD.get_annual_occurrence_rates
def get_annual_occurrence_rates(self): """ Calculate and return the annual occurrence rates histogram. :returns: See :meth: `openquake.hazardlib.mfd.base.BaseMFD.get_annual_occurrence_rates`. """ mag, num_bins = self._get_min_mag_and_num_bins() rates = [] for i in range(num_bins): rate = self._get_rate(mag) rates.append((mag, rate)) mag += self.bin_width return rates
python
def get_annual_occurrence_rates(self): mag, num_bins = self._get_min_mag_and_num_bins() rates = [] for i in range(num_bins): rate = self._get_rate(mag) rates.append((mag, rate)) mag += self.bin_width return rates
[ "def", "get_annual_occurrence_rates", "(", "self", ")", ":", "mag", ",", "num_bins", "=", "self", ".", "_get_min_mag_and_num_bins", "(", ")", "rates", "=", "[", "]", "for", "i", "in", "range", "(", "num_bins", ")", ":", "rate", "=", "self", ".", "_get_rate", "(", "mag", ")", "rates", ".", "append", "(", "(", "mag", ",", "rate", ")", ")", "mag", "+=", "self", ".", "bin_width", "return", "rates" ]
Calculate and return the annual occurrence rates histogram. :returns: See :meth: `openquake.hazardlib.mfd.base.BaseMFD.get_annual_occurrence_rates`.
[ "Calculate", "and", "return", "the", "annual", "occurrence", "rates", "histogram", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L334-L348
gem/oq-engine
openquake/hmtk/sources/area_source.py
mtkAreaSource.create_geometry
def create_geometry(self, input_geometry, upper_depth, lower_depth): ''' If geometry is defined as a numpy array then create instance of nhlib.geo.polygon.Polygon class, otherwise if already instance of class accept class :param input_geometry: Input geometry (polygon) as either i) instance of nhlib.geo.polygon.Polygon class ii) numpy.ndarray [Longitude, Latitude] :param float upper_depth: Upper seismogenic depth (km) :param float lower_depth: Lower seismogenic depth (km) ''' self._check_seismogenic_depths(upper_depth, lower_depth) # Check/create the geometry class if not isinstance(input_geometry, Polygon): if not isinstance(input_geometry, np.ndarray): raise ValueError('Unrecognised or unsupported geometry ' 'definition') if np.shape(input_geometry)[0] < 3: raise ValueError('Incorrectly formatted polygon geometry -' ' needs three or more vertices') geometry = [] for row in input_geometry: geometry.append(Point(row[0], row[1], self.upper_depth)) self.geometry = Polygon(geometry) else: self.geometry = input_geometry
python
def create_geometry(self, input_geometry, upper_depth, lower_depth): self._check_seismogenic_depths(upper_depth, lower_depth) if not isinstance(input_geometry, Polygon): if not isinstance(input_geometry, np.ndarray): raise ValueError('Unrecognised or unsupported geometry ' 'definition') if np.shape(input_geometry)[0] < 3: raise ValueError('Incorrectly formatted polygon geometry -' ' needs three or more vertices') geometry = [] for row in input_geometry: geometry.append(Point(row[0], row[1], self.upper_depth)) self.geometry = Polygon(geometry) else: self.geometry = input_geometry
[ "def", "create_geometry", "(", "self", ",", "input_geometry", ",", "upper_depth", ",", "lower_depth", ")", ":", "self", ".", "_check_seismogenic_depths", "(", "upper_depth", ",", "lower_depth", ")", "# Check/create the geometry class", "if", "not", "isinstance", "(", "input_geometry", ",", "Polygon", ")", ":", "if", "not", "isinstance", "(", "input_geometry", ",", "np", ".", "ndarray", ")", ":", "raise", "ValueError", "(", "'Unrecognised or unsupported geometry '", "'definition'", ")", "if", "np", ".", "shape", "(", "input_geometry", ")", "[", "0", "]", "<", "3", ":", "raise", "ValueError", "(", "'Incorrectly formatted polygon geometry -'", "' needs three or more vertices'", ")", "geometry", "=", "[", "]", "for", "row", "in", "input_geometry", ":", "geometry", ".", "append", "(", "Point", "(", "row", "[", "0", "]", ",", "row", "[", "1", "]", ",", "self", ".", "upper_depth", ")", ")", "self", ".", "geometry", "=", "Polygon", "(", "geometry", ")", "else", ":", "self", ".", "geometry", "=", "input_geometry" ]
If geometry is defined as a numpy array then create instance of nhlib.geo.polygon.Polygon class, otherwise if already instance of class accept class :param input_geometry: Input geometry (polygon) as either i) instance of nhlib.geo.polygon.Polygon class ii) numpy.ndarray [Longitude, Latitude] :param float upper_depth: Upper seismogenic depth (km) :param float lower_depth: Lower seismogenic depth (km)
[ "If", "geometry", "is", "defined", "as", "a", "numpy", "array", "then", "create", "instance", "of", "nhlib", ".", "geo", ".", "polygon", ".", "Polygon", "class", "otherwise", "if", "already", "instance", "of", "class", "accept", "class" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/area_source.py#L118-L151
gem/oq-engine
openquake/hmtk/sources/area_source.py
mtkAreaSource.select_catalogue
def select_catalogue(self, selector, distance=None): ''' Selects the catalogue of earthquakes attributable to the source :param selector: Populated instance of openquake.hmtk.seismicity.selector.CatalogueSelector class :param float distance: Distance (in km) to extend or contract (if negative) the zone for selecting events ''' if selector.catalogue.get_number_events() < 1: raise ValueError('No events found in catalogue!') self.catalogue = selector.within_polygon(self.geometry, distance, upper_depth=self.upper_depth, lower_depth=self.lower_depth) if self.catalogue.get_number_events() < 5: # Throw a warning regarding the small number of earthquakes in # the source! warnings.warn('Source %s (%s) has fewer than 5 events' % (self.id, self.name))
python
def select_catalogue(self, selector, distance=None): if selector.catalogue.get_number_events() < 1: raise ValueError('No events found in catalogue!') self.catalogue = selector.within_polygon(self.geometry, distance, upper_depth=self.upper_depth, lower_depth=self.lower_depth) if self.catalogue.get_number_events() < 5: warnings.warn('Source %s (%s) has fewer than 5 events' % (self.id, self.name))
[ "def", "select_catalogue", "(", "self", ",", "selector", ",", "distance", "=", "None", ")", ":", "if", "selector", ".", "catalogue", ".", "get_number_events", "(", ")", "<", "1", ":", "raise", "ValueError", "(", "'No events found in catalogue!'", ")", "self", ".", "catalogue", "=", "selector", ".", "within_polygon", "(", "self", ".", "geometry", ",", "distance", ",", "upper_depth", "=", "self", ".", "upper_depth", ",", "lower_depth", "=", "self", ".", "lower_depth", ")", "if", "self", ".", "catalogue", ".", "get_number_events", "(", ")", "<", "5", ":", "# Throw a warning regarding the small number of earthquakes in", "# the source!", "warnings", ".", "warn", "(", "'Source %s (%s) has fewer than 5 events'", "%", "(", "self", ".", "id", ",", "self", ".", "name", ")", ")" ]
Selects the catalogue of earthquakes attributable to the source :param selector: Populated instance of openquake.hmtk.seismicity.selector.CatalogueSelector class :param float distance: Distance (in km) to extend or contract (if negative) the zone for selecting events
[ "Selects", "the", "catalogue", "of", "earthquakes", "attributable", "to", "the", "source" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/area_source.py#L180-L202
gem/oq-engine
openquake/hmtk/sources/area_source.py
mtkAreaSource.create_oqhazardlib_source
def create_oqhazardlib_source(self, tom, mesh_spacing, area_discretisation, use_defaults=False): """ Converts the source model into an instance of the :class: openquake.hazardlib.source.area.AreaSource :param tom: Temporal Occurrence model as instance of :class: openquake.hazardlib.tom.TOM :param float mesh_spacing: Mesh spacing """ if not self.mfd: raise ValueError("Cannot write to hazardlib without MFD") return AreaSource( self.id, self.name, self.trt, self.mfd, mesh_spacing, conv.mag_scale_rel_to_hazardlib(self.mag_scale_rel, use_defaults), conv.render_aspect_ratio(self.rupt_aspect_ratio, use_defaults), tom, self.upper_depth, self.lower_depth, conv.npd_to_pmf(self.nodal_plane_dist, use_defaults), conv.hdd_to_pmf(self.hypo_depth_dist, use_defaults), self.geometry, area_discretisation)
python
def create_oqhazardlib_source(self, tom, mesh_spacing, area_discretisation, use_defaults=False): if not self.mfd: raise ValueError("Cannot write to hazardlib without MFD") return AreaSource( self.id, self.name, self.trt, self.mfd, mesh_spacing, conv.mag_scale_rel_to_hazardlib(self.mag_scale_rel, use_defaults), conv.render_aspect_ratio(self.rupt_aspect_ratio, use_defaults), tom, self.upper_depth, self.lower_depth, conv.npd_to_pmf(self.nodal_plane_dist, use_defaults), conv.hdd_to_pmf(self.hypo_depth_dist, use_defaults), self.geometry, area_discretisation)
[ "def", "create_oqhazardlib_source", "(", "self", ",", "tom", ",", "mesh_spacing", ",", "area_discretisation", ",", "use_defaults", "=", "False", ")", ":", "if", "not", "self", ".", "mfd", ":", "raise", "ValueError", "(", "\"Cannot write to hazardlib without MFD\"", ")", "return", "AreaSource", "(", "self", ".", "id", ",", "self", ".", "name", ",", "self", ".", "trt", ",", "self", ".", "mfd", ",", "mesh_spacing", ",", "conv", ".", "mag_scale_rel_to_hazardlib", "(", "self", ".", "mag_scale_rel", ",", "use_defaults", ")", ",", "conv", ".", "render_aspect_ratio", "(", "self", ".", "rupt_aspect_ratio", ",", "use_defaults", ")", ",", "tom", ",", "self", ".", "upper_depth", ",", "self", ".", "lower_depth", ",", "conv", ".", "npd_to_pmf", "(", "self", ".", "nodal_plane_dist", ",", "use_defaults", ")", ",", "conv", ".", "hdd_to_pmf", "(", "self", ".", "hypo_depth_dist", ",", "use_defaults", ")", ",", "self", ".", "geometry", ",", "area_discretisation", ")" ]
Converts the source model into an instance of the :class: openquake.hazardlib.source.area.AreaSource :param tom: Temporal Occurrence model as instance of :class: openquake.hazardlib.tom.TOM :param float mesh_spacing: Mesh spacing
[ "Converts", "the", "source", "model", "into", "an", "instance", "of", "the", ":", "class", ":", "openquake", ".", "hazardlib", ".", "source", ".", "area", ".", "AreaSource" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/area_source.py#L204-L232
gem/oq-engine
openquake/baselib/performance.py
Monitor.get_data
def get_data(self): """ :returns: an array of dtype perf_dt, with the information of the monitor (operation, time_sec, memory_mb, counts); the lenght of the array can be 0 (for counts=0) or 1 (otherwise). """ data = [] if self.counts: time_sec = self.duration memory_mb = self.mem / 1024. / 1024. if self.measuremem else 0 data.append((self.operation, time_sec, memory_mb, self.counts)) return numpy.array(data, perf_dt)
python
def get_data(self): data = [] if self.counts: time_sec = self.duration memory_mb = self.mem / 1024. / 1024. if self.measuremem else 0 data.append((self.operation, time_sec, memory_mb, self.counts)) return numpy.array(data, perf_dt)
[ "def", "get_data", "(", "self", ")", ":", "data", "=", "[", "]", "if", "self", ".", "counts", ":", "time_sec", "=", "self", ".", "duration", "memory_mb", "=", "self", ".", "mem", "/", "1024.", "/", "1024.", "if", "self", ".", "measuremem", "else", "0", "data", ".", "append", "(", "(", "self", ".", "operation", ",", "time_sec", ",", "memory_mb", ",", "self", ".", "counts", ")", ")", "return", "numpy", ".", "array", "(", "data", ",", "perf_dt", ")" ]
:returns: an array of dtype perf_dt, with the information of the monitor (operation, time_sec, memory_mb, counts); the lenght of the array can be 0 (for counts=0) or 1 (otherwise).
[ ":", "returns", ":", "an", "array", "of", "dtype", "perf_dt", "with", "the", "information", "of", "the", "monitor", "(", "operation", "time_sec", "memory_mb", "counts", ")", ";", "the", "lenght", "of", "the", "array", "can", "be", "0", "(", "for", "counts", "=", "0", ")", "or", "1", "(", "otherwise", ")", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/performance.py#L117-L129
gem/oq-engine
openquake/baselib/performance.py
Monitor.flush
def flush(self): """ Save the measurements on the performance file (or on stdout) """ if not self._flush: raise RuntimeError( 'Monitor(%r).flush() must not be called in a worker' % self.operation) for child in self.children: child.hdf5 = self.hdf5 child.flush() data = self.get_data() if len(data) == 0: # no information return [] elif self.hdf5: hdf5.extend(self.hdf5['performance_data'], data) # reset monitor self.duration = 0 self.mem = 0 self.counts = 0 return data
python
def flush(self): if not self._flush: raise RuntimeError( 'Monitor(%r).flush() must not be called in a worker' % self.operation) for child in self.children: child.hdf5 = self.hdf5 child.flush() data = self.get_data() if len(data) == 0: return [] elif self.hdf5: hdf5.extend(self.hdf5['performance_data'], data) self.duration = 0 self.mem = 0 self.counts = 0 return data
[ "def", "flush", "(", "self", ")", ":", "if", "not", "self", ".", "_flush", ":", "raise", "RuntimeError", "(", "'Monitor(%r).flush() must not be called in a worker'", "%", "self", ".", "operation", ")", "for", "child", "in", "self", ".", "children", ":", "child", ".", "hdf5", "=", "self", ".", "hdf5", "child", ".", "flush", "(", ")", "data", "=", "self", ".", "get_data", "(", ")", "if", "len", "(", "data", ")", "==", "0", ":", "# no information", "return", "[", "]", "elif", "self", ".", "hdf5", ":", "hdf5", ".", "extend", "(", "self", ".", "hdf5", "[", "'performance_data'", "]", ",", "data", ")", "# reset monitor", "self", ".", "duration", "=", "0", "self", ".", "mem", "=", "0", "self", ".", "counts", "=", "0", "return", "data" ]
Save the measurements on the performance file (or on stdout)
[ "Save", "the", "measurements", "on", "the", "performance", "file", "(", "or", "on", "stdout", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/performance.py#L153-L174
gem/oq-engine
openquake/baselib/performance.py
Monitor.new
def new(self, operation='no operation', **kw): """ Return a copy of the monitor usable for a different operation. """ self_vars = vars(self).copy() del self_vars['operation'] del self_vars['children'] del self_vars['counts'] del self_vars['_flush'] new = self.__class__(operation) vars(new).update(self_vars) vars(new).update(kw) return new
python
def new(self, operation='no operation', **kw): self_vars = vars(self).copy() del self_vars['operation'] del self_vars['children'] del self_vars['counts'] del self_vars['_flush'] new = self.__class__(operation) vars(new).update(self_vars) vars(new).update(kw) return new
[ "def", "new", "(", "self", ",", "operation", "=", "'no operation'", ",", "*", "*", "kw", ")", ":", "self_vars", "=", "vars", "(", "self", ")", ".", "copy", "(", ")", "del", "self_vars", "[", "'operation'", "]", "del", "self_vars", "[", "'children'", "]", "del", "self_vars", "[", "'counts'", "]", "del", "self_vars", "[", "'_flush'", "]", "new", "=", "self", ".", "__class__", "(", "operation", ")", "vars", "(", "new", ")", ".", "update", "(", "self_vars", ")", "vars", "(", "new", ")", ".", "update", "(", "kw", ")", "return", "new" ]
Return a copy of the monitor usable for a different operation.
[ "Return", "a", "copy", "of", "the", "monitor", "usable", "for", "a", "different", "operation", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/performance.py#L185-L197
gem/oq-engine
openquake/hazardlib/site.py
SiteCollection.from_shakemap
def from_shakemap(cls, shakemap_array): """ Build a site collection from a shakemap array """ self = object.__new__(cls) self.complete = self n = len(shakemap_array) dtype = numpy.dtype([(p, site_param_dt[p]) for p in 'sids lon lat depth vs30'.split()]) self.array = arr = numpy.zeros(n, dtype) arr['sids'] = numpy.arange(n, dtype=numpy.uint32) arr['lon'] = shakemap_array['lon'] arr['lat'] = shakemap_array['lat'] arr['depth'] = numpy.zeros(n) arr['vs30'] = shakemap_array['vs30'] arr.flags.writeable = False return self
python
def from_shakemap(cls, shakemap_array): self = object.__new__(cls) self.complete = self n = len(shakemap_array) dtype = numpy.dtype([(p, site_param_dt[p]) for p in 'sids lon lat depth vs30'.split()]) self.array = arr = numpy.zeros(n, dtype) arr['sids'] = numpy.arange(n, dtype=numpy.uint32) arr['lon'] = shakemap_array['lon'] arr['lat'] = shakemap_array['lat'] arr['depth'] = numpy.zeros(n) arr['vs30'] = shakemap_array['vs30'] arr.flags.writeable = False return self
[ "def", "from_shakemap", "(", "cls", ",", "shakemap_array", ")", ":", "self", "=", "object", ".", "__new__", "(", "cls", ")", "self", ".", "complete", "=", "self", "n", "=", "len", "(", "shakemap_array", ")", "dtype", "=", "numpy", ".", "dtype", "(", "[", "(", "p", ",", "site_param_dt", "[", "p", "]", ")", "for", "p", "in", "'sids lon lat depth vs30'", ".", "split", "(", ")", "]", ")", "self", ".", "array", "=", "arr", "=", "numpy", ".", "zeros", "(", "n", ",", "dtype", ")", "arr", "[", "'sids'", "]", "=", "numpy", ".", "arange", "(", "n", ",", "dtype", "=", "numpy", ".", "uint32", ")", "arr", "[", "'lon'", "]", "=", "shakemap_array", "[", "'lon'", "]", "arr", "[", "'lat'", "]", "=", "shakemap_array", "[", "'lat'", "]", "arr", "[", "'depth'", "]", "=", "numpy", ".", "zeros", "(", "n", ")", "arr", "[", "'vs30'", "]", "=", "shakemap_array", "[", "'vs30'", "]", "arr", ".", "flags", ".", "writeable", "=", "False", "return", "self" ]
Build a site collection from a shakemap array
[ "Build", "a", "site", "collection", "from", "a", "shakemap", "array" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L164-L180
gem/oq-engine
openquake/hazardlib/site.py
SiteCollection.from_points
def from_points(cls, lons, lats, depths=None, sitemodel=None, req_site_params=()): """ Build the site collection from :param lons: a sequence of longitudes :param lats: a sequence of latitudes :param depths: a sequence of depths (or None) :param sitemodel: None or an object containing site parameters as attributes :param req_site_params: a sequence of required site parameters, possibly empty """ assert len(lons) < U32LIMIT, len(lons) if depths is None: depths = numpy.zeros(len(lons)) assert len(lons) == len(lats) == len(depths), (len(lons), len(lats), len(depths)) self = object.__new__(cls) self.complete = self req = ['sids', 'lon', 'lat', 'depth'] + sorted( par for par in req_site_params if par not in ('lon', 'lat')) if 'vs30' in req and 'vs30measured' not in req: req.append('vs30measured') self.dtype = numpy.dtype([(p, site_param_dt[p]) for p in req]) self.array = arr = numpy.zeros(len(lons), self.dtype) arr['sids'] = numpy.arange(len(lons), dtype=numpy.uint32) arr['lon'] = fix_lon(numpy.array(lons)) arr['lat'] = numpy.array(lats) arr['depth'] = numpy.array(depths) if sitemodel is None: pass elif hasattr(sitemodel, 'reference_vs30_value'): # sitemodel is actually an OqParam instance self._set('vs30', sitemodel.reference_vs30_value) self._set('vs30measured', sitemodel.reference_vs30_type == 'measured') self._set('z1pt0', sitemodel.reference_depth_to_1pt0km_per_sec) self._set('z2pt5', sitemodel.reference_depth_to_2pt5km_per_sec) self._set('siteclass', sitemodel.reference_siteclass) else: for name in sitemodel.dtype.names: if name not in ('lon', 'lat'): self._set(name, sitemodel[name]) return self
python
def from_points(cls, lons, lats, depths=None, sitemodel=None, req_site_params=()): assert len(lons) < U32LIMIT, len(lons) if depths is None: depths = numpy.zeros(len(lons)) assert len(lons) == len(lats) == len(depths), (len(lons), len(lats), len(depths)) self = object.__new__(cls) self.complete = self req = ['sids', 'lon', 'lat', 'depth'] + sorted( par for par in req_site_params if par not in ('lon', 'lat')) if 'vs30' in req and 'vs30measured' not in req: req.append('vs30measured') self.dtype = numpy.dtype([(p, site_param_dt[p]) for p in req]) self.array = arr = numpy.zeros(len(lons), self.dtype) arr['sids'] = numpy.arange(len(lons), dtype=numpy.uint32) arr['lon'] = fix_lon(numpy.array(lons)) arr['lat'] = numpy.array(lats) arr['depth'] = numpy.array(depths) if sitemodel is None: pass elif hasattr(sitemodel, 'reference_vs30_value'): self._set('vs30', sitemodel.reference_vs30_value) self._set('vs30measured', sitemodel.reference_vs30_type == 'measured') self._set('z1pt0', sitemodel.reference_depth_to_1pt0km_per_sec) self._set('z2pt5', sitemodel.reference_depth_to_2pt5km_per_sec) self._set('siteclass', sitemodel.reference_siteclass) else: for name in sitemodel.dtype.names: if name not in ('lon', 'lat'): self._set(name, sitemodel[name]) return self
[ "def", "from_points", "(", "cls", ",", "lons", ",", "lats", ",", "depths", "=", "None", ",", "sitemodel", "=", "None", ",", "req_site_params", "=", "(", ")", ")", ":", "assert", "len", "(", "lons", ")", "<", "U32LIMIT", ",", "len", "(", "lons", ")", "if", "depths", "is", "None", ":", "depths", "=", "numpy", ".", "zeros", "(", "len", "(", "lons", ")", ")", "assert", "len", "(", "lons", ")", "==", "len", "(", "lats", ")", "==", "len", "(", "depths", ")", ",", "(", "len", "(", "lons", ")", ",", "len", "(", "lats", ")", ",", "len", "(", "depths", ")", ")", "self", "=", "object", ".", "__new__", "(", "cls", ")", "self", ".", "complete", "=", "self", "req", "=", "[", "'sids'", ",", "'lon'", ",", "'lat'", ",", "'depth'", "]", "+", "sorted", "(", "par", "for", "par", "in", "req_site_params", "if", "par", "not", "in", "(", "'lon'", ",", "'lat'", ")", ")", "if", "'vs30'", "in", "req", "and", "'vs30measured'", "not", "in", "req", ":", "req", ".", "append", "(", "'vs30measured'", ")", "self", ".", "dtype", "=", "numpy", ".", "dtype", "(", "[", "(", "p", ",", "site_param_dt", "[", "p", "]", ")", "for", "p", "in", "req", "]", ")", "self", ".", "array", "=", "arr", "=", "numpy", ".", "zeros", "(", "len", "(", "lons", ")", ",", "self", ".", "dtype", ")", "arr", "[", "'sids'", "]", "=", "numpy", ".", "arange", "(", "len", "(", "lons", ")", ",", "dtype", "=", "numpy", ".", "uint32", ")", "arr", "[", "'lon'", "]", "=", "fix_lon", "(", "numpy", ".", "array", "(", "lons", ")", ")", "arr", "[", "'lat'", "]", "=", "numpy", ".", "array", "(", "lats", ")", "arr", "[", "'depth'", "]", "=", "numpy", ".", "array", "(", "depths", ")", "if", "sitemodel", "is", "None", ":", "pass", "elif", "hasattr", "(", "sitemodel", ",", "'reference_vs30_value'", ")", ":", "# sitemodel is actually an OqParam instance", "self", ".", "_set", "(", "'vs30'", ",", "sitemodel", ".", "reference_vs30_value", ")", "self", ".", "_set", "(", "'vs30measured'", ",", "sitemodel", ".", "reference_vs30_type", "==", "'measured'", ")", "self", ".", "_set", "(", "'z1pt0'", ",", "sitemodel", ".", "reference_depth_to_1pt0km_per_sec", ")", "self", ".", "_set", "(", "'z2pt5'", ",", "sitemodel", ".", "reference_depth_to_2pt5km_per_sec", ")", "self", ".", "_set", "(", "'siteclass'", ",", "sitemodel", ".", "reference_siteclass", ")", "else", ":", "for", "name", "in", "sitemodel", ".", "dtype", ".", "names", ":", "if", "name", "not", "in", "(", "'lon'", ",", "'lat'", ")", ":", "self", ".", "_set", "(", "name", ",", "sitemodel", "[", "name", "]", ")", "return", "self" ]
Build the site collection from :param lons: a sequence of longitudes :param lats: a sequence of latitudes :param depths: a sequence of depths (or None) :param sitemodel: None or an object containing site parameters as attributes :param req_site_params: a sequence of required site parameters, possibly empty
[ "Build", "the", "site", "collection", "from" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L183-L230
gem/oq-engine
openquake/hazardlib/site.py
SiteCollection.filtered
def filtered(self, indices): """ :param indices: a subset of indices in the range [0 .. tot_sites - 1] :returns: a filtered SiteCollection instance if `indices` is a proper subset of the available indices, otherwise returns the full SiteCollection """ if indices is None or len(indices) == len(self): return self new = object.__new__(self.__class__) indices = numpy.uint32(sorted(indices)) new.array = self.array[indices] new.complete = self.complete return new
python
def filtered(self, indices): if indices is None or len(indices) == len(self): return self new = object.__new__(self.__class__) indices = numpy.uint32(sorted(indices)) new.array = self.array[indices] new.complete = self.complete return new
[ "def", "filtered", "(", "self", ",", "indices", ")", ":", "if", "indices", "is", "None", "or", "len", "(", "indices", ")", "==", "len", "(", "self", ")", ":", "return", "self", "new", "=", "object", ".", "__new__", "(", "self", ".", "__class__", ")", "indices", "=", "numpy", ".", "uint32", "(", "sorted", "(", "indices", ")", ")", "new", ".", "array", "=", "self", ".", "array", "[", "indices", "]", "new", ".", "complete", "=", "self", ".", "complete", "return", "new" ]
:param indices: a subset of indices in the range [0 .. tot_sites - 1] :returns: a filtered SiteCollection instance if `indices` is a proper subset of the available indices, otherwise returns the full SiteCollection
[ ":", "param", "indices", ":", "a", "subset", "of", "indices", "in", "the", "range", "[", "0", "..", "tot_sites", "-", "1", "]", ":", "returns", ":", "a", "filtered", "SiteCollection", "instance", "if", "indices", "is", "a", "proper", "subset", "of", "the", "available", "indices", "otherwise", "returns", "the", "full", "SiteCollection" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L240-L254
gem/oq-engine
openquake/hazardlib/site.py
SiteCollection.make_complete
def make_complete(self): """ Turns the site collection into a complete one, if needed """ # reset the site indices from 0 to N-1 and set self.complete to self self.array['sids'] = numpy.arange(len(self), dtype=numpy.uint32) self.complete = self
python
def make_complete(self): self.array['sids'] = numpy.arange(len(self), dtype=numpy.uint32) self.complete = self
[ "def", "make_complete", "(", "self", ")", ":", "# reset the site indices from 0 to N-1 and set self.complete to self", "self", ".", "array", "[", "'sids'", "]", "=", "numpy", ".", "arange", "(", "len", "(", "self", ")", ",", "dtype", "=", "numpy", ".", "uint32", ")", "self", ".", "complete", "=", "self" ]
Turns the site collection into a complete one, if needed
[ "Turns", "the", "site", "collection", "into", "a", "complete", "one", "if", "needed" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L256-L262
gem/oq-engine
openquake/hazardlib/site.py
SiteCollection.split_in_tiles
def split_in_tiles(self, hint): """ Split a SiteCollection into a set of tiles (SiteCollection instances). :param hint: hint for how many tiles to generate """ tiles = [] for seq in split_in_blocks(range(len(self)), hint or 1): sc = SiteCollection.__new__(SiteCollection) sc.array = self.array[numpy.array(seq, int)] tiles.append(sc) return tiles
python
def split_in_tiles(self, hint): tiles = [] for seq in split_in_blocks(range(len(self)), hint or 1): sc = SiteCollection.__new__(SiteCollection) sc.array = self.array[numpy.array(seq, int)] tiles.append(sc) return tiles
[ "def", "split_in_tiles", "(", "self", ",", "hint", ")", ":", "tiles", "=", "[", "]", "for", "seq", "in", "split_in_blocks", "(", "range", "(", "len", "(", "self", ")", ")", ",", "hint", "or", "1", ")", ":", "sc", "=", "SiteCollection", ".", "__new__", "(", "SiteCollection", ")", "sc", ".", "array", "=", "self", ".", "array", "[", "numpy", ".", "array", "(", "seq", ",", "int", ")", "]", "tiles", ".", "append", "(", "sc", ")", "return", "tiles" ]
Split a SiteCollection into a set of tiles (SiteCollection instances). :param hint: hint for how many tiles to generate
[ "Split", "a", "SiteCollection", "into", "a", "set", "of", "tiles", "(", "SiteCollection", "instances", ")", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L313-L324
gem/oq-engine
openquake/hazardlib/site.py
SiteCollection.split
def split(self, location, distance): """ :returns: (close_sites, far_sites) """ if distance is None: # all close return self, None close = location.distance_to_mesh(self) < distance return self.filter(close), self.filter(~close)
python
def split(self, location, distance): if distance is None: return self, None close = location.distance_to_mesh(self) < distance return self.filter(close), self.filter(~close)
[ "def", "split", "(", "self", ",", "location", ",", "distance", ")", ":", "if", "distance", "is", "None", ":", "# all close", "return", "self", ",", "None", "close", "=", "location", ".", "distance_to_mesh", "(", "self", ")", "<", "distance", "return", "self", ".", "filter", "(", "close", ")", ",", "self", ".", "filter", "(", "~", "close", ")" ]
:returns: (close_sites, far_sites)
[ ":", "returns", ":", "(", "close_sites", "far_sites", ")" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L326-L333
gem/oq-engine
openquake/hazardlib/site.py
SiteCollection.filter
def filter(self, mask): """ Create a SiteCollection with only a subset of sites. :param mask: Numpy array of boolean values of the same length as the site collection. ``True`` values should indicate that site with that index should be included into the filtered collection. :returns: A new :class:`SiteCollection` instance, unless all the values in ``mask`` are ``True``, in which case this site collection is returned, or if all the values in ``mask`` are ``False``, in which case method returns ``None``. New collection has data of only those sites that were marked for inclusion in the mask. """ assert len(mask) == len(self), (len(mask), len(self)) if mask.all(): # all sites satisfy the filter, return # this collection unchanged return self if not mask.any(): # no sites pass the filter, return None return None # extract indices of Trues from the mask indices, = mask.nonzero() return self.filtered(indices)
python
def filter(self, mask): assert len(mask) == len(self), (len(mask), len(self)) if mask.all(): return self if not mask.any(): return None indices, = mask.nonzero() return self.filtered(indices)
[ "def", "filter", "(", "self", ",", "mask", ")", ":", "assert", "len", "(", "mask", ")", "==", "len", "(", "self", ")", ",", "(", "len", "(", "mask", ")", ",", "len", "(", "self", ")", ")", "if", "mask", ".", "all", "(", ")", ":", "# all sites satisfy the filter, return", "# this collection unchanged", "return", "self", "if", "not", "mask", ".", "any", "(", ")", ":", "# no sites pass the filter, return None", "return", "None", "# extract indices of Trues from the mask", "indices", ",", "=", "mask", ".", "nonzero", "(", ")", "return", "self", ".", "filtered", "(", "indices", ")" ]
Create a SiteCollection with only a subset of sites. :param mask: Numpy array of boolean values of the same length as the site collection. ``True`` values should indicate that site with that index should be included into the filtered collection. :returns: A new :class:`SiteCollection` instance, unless all the values in ``mask`` are ``True``, in which case this site collection is returned, or if all the values in ``mask`` are ``False``, in which case method returns ``None``. New collection has data of only those sites that were marked for inclusion in the mask.
[ "Create", "a", "SiteCollection", "with", "only", "a", "subset", "of", "sites", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L345-L370
gem/oq-engine
openquake/hazardlib/site.py
SiteCollection.within
def within(self, region): """ :param region: a shapely polygon :returns: a filtered SiteCollection of sites within the region """ mask = numpy.array([ geometry.Point(rec['lon'], rec['lat']).within(region) for rec in self.array]) return self.filter(mask)
python
def within(self, region): mask = numpy.array([ geometry.Point(rec['lon'], rec['lat']).within(region) for rec in self.array]) return self.filter(mask)
[ "def", "within", "(", "self", ",", "region", ")", ":", "mask", "=", "numpy", ".", "array", "(", "[", "geometry", ".", "Point", "(", "rec", "[", "'lon'", "]", ",", "rec", "[", "'lat'", "]", ")", ".", "within", "(", "region", ")", "for", "rec", "in", "self", ".", "array", "]", ")", "return", "self", ".", "filter", "(", "mask", ")" ]
:param region: a shapely polygon :returns: a filtered SiteCollection of sites within the region
[ ":", "param", "region", ":", "a", "shapely", "polygon", ":", "returns", ":", "a", "filtered", "SiteCollection", "of", "sites", "within", "the", "region" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L372-L380
gem/oq-engine
openquake/hazardlib/site.py
SiteCollection.within_bbox
def within_bbox(self, bbox): """ :param bbox: a quartet (min_lon, min_lat, max_lon, max_lat) :returns: site IDs within the bounding box """ min_lon, min_lat, max_lon, max_lat = bbox lons, lats = self.array['lon'], self.array['lat'] if cross_idl(lons.min(), lons.max()) or cross_idl(min_lon, max_lon): lons = lons % 360 min_lon, max_lon = min_lon % 360, max_lon % 360 mask = (min_lon < lons) * (lons < max_lon) * \ (min_lat < lats) * (lats < max_lat) return mask.nonzero()[0]
python
def within_bbox(self, bbox): min_lon, min_lat, max_lon, max_lat = bbox lons, lats = self.array['lon'], self.array['lat'] if cross_idl(lons.min(), lons.max()) or cross_idl(min_lon, max_lon): lons = lons % 360 min_lon, max_lon = min_lon % 360, max_lon % 360 mask = (min_lon < lons) * (lons < max_lon) * \ (min_lat < lats) * (lats < max_lat) return mask.nonzero()[0]
[ "def", "within_bbox", "(", "self", ",", "bbox", ")", ":", "min_lon", ",", "min_lat", ",", "max_lon", ",", "max_lat", "=", "bbox", "lons", ",", "lats", "=", "self", ".", "array", "[", "'lon'", "]", ",", "self", ".", "array", "[", "'lat'", "]", "if", "cross_idl", "(", "lons", ".", "min", "(", ")", ",", "lons", ".", "max", "(", ")", ")", "or", "cross_idl", "(", "min_lon", ",", "max_lon", ")", ":", "lons", "=", "lons", "%", "360", "min_lon", ",", "max_lon", "=", "min_lon", "%", "360", ",", "max_lon", "%", "360", "mask", "=", "(", "min_lon", "<", "lons", ")", "*", "(", "lons", "<", "max_lon", ")", "*", "(", "min_lat", "<", "lats", ")", "*", "(", "lats", "<", "max_lat", ")", "return", "mask", ".", "nonzero", "(", ")", "[", "0", "]" ]
:param bbox: a quartet (min_lon, min_lat, max_lon, max_lat) :returns: site IDs within the bounding box
[ ":", "param", "bbox", ":", "a", "quartet", "(", "min_lon", "min_lat", "max_lon", "max_lat", ")", ":", "returns", ":", "site", "IDs", "within", "the", "bounding", "box" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L382-L396
gem/oq-engine
openquake/hazardlib/geo/point.py
Point.point_at
def point_at(self, horizontal_distance, vertical_increment, azimuth): """ Compute the point with given horizontal, vertical distances and azimuth from this point. :param horizontal_distance: Horizontal distance, in km. :type horizontal_distance: float :param vertical_increment: Vertical increment, in km. When positive, the new point has a greater depth. When negative, the new point has a smaller depth. :type vertical_increment: float :type azimuth: Azimuth, in decimal degrees. :type azimuth: float :returns: The point at the given distances. :rtype: Instance of :class:`Point` """ lon, lat = geodetic.point_at(self.longitude, self.latitude, azimuth, horizontal_distance) return Point(lon, lat, self.depth + vertical_increment)
python
def point_at(self, horizontal_distance, vertical_increment, azimuth): lon, lat = geodetic.point_at(self.longitude, self.latitude, azimuth, horizontal_distance) return Point(lon, lat, self.depth + vertical_increment)
[ "def", "point_at", "(", "self", ",", "horizontal_distance", ",", "vertical_increment", ",", "azimuth", ")", ":", "lon", ",", "lat", "=", "geodetic", ".", "point_at", "(", "self", ".", "longitude", ",", "self", ".", "latitude", ",", "azimuth", ",", "horizontal_distance", ")", "return", "Point", "(", "lon", ",", "lat", ",", "self", ".", "depth", "+", "vertical_increment", ")" ]
Compute the point with given horizontal, vertical distances and azimuth from this point. :param horizontal_distance: Horizontal distance, in km. :type horizontal_distance: float :param vertical_increment: Vertical increment, in km. When positive, the new point has a greater depth. When negative, the new point has a smaller depth. :type vertical_increment: float :type azimuth: Azimuth, in decimal degrees. :type azimuth: float :returns: The point at the given distances. :rtype: Instance of :class:`Point`
[ "Compute", "the", "point", "with", "given", "horizontal", "vertical", "distances", "and", "azimuth", "from", "this", "point", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/point.py#L94-L120
gem/oq-engine
openquake/hazardlib/geo/point.py
Point.azimuth
def azimuth(self, point): """ Compute the azimuth (in decimal degrees) between this point and the given point. :param point: Destination point. :type point: Instance of :class:`Point` :returns: The azimuth, value in a range ``[0, 360)``. :rtype: float """ return geodetic.azimuth(self.longitude, self.latitude, point.longitude, point.latitude)
python
def azimuth(self, point): return geodetic.azimuth(self.longitude, self.latitude, point.longitude, point.latitude)
[ "def", "azimuth", "(", "self", ",", "point", ")", ":", "return", "geodetic", ".", "azimuth", "(", "self", ".", "longitude", ",", "self", ".", "latitude", ",", "point", ".", "longitude", ",", "point", ".", "latitude", ")" ]
Compute the azimuth (in decimal degrees) between this point and the given point. :param point: Destination point. :type point: Instance of :class:`Point` :returns: The azimuth, value in a range ``[0, 360)``. :rtype: float
[ "Compute", "the", "azimuth", "(", "in", "decimal", "degrees", ")", "between", "this", "point", "and", "the", "given", "point", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/point.py#L122-L137
gem/oq-engine
openquake/hazardlib/geo/point.py
Point.distance
def distance(self, point): """ Compute the distance (in km) between this point and the given point. Distance is calculated using pythagoras theorem, where the hypotenuse is the distance and the other two sides are the horizontal distance (great circle distance) and vertical distance (depth difference between the two locations). :param point: Destination point. :type point: Instance of :class:`Point` :returns: The distance. :rtype: float """ return geodetic.distance(self.longitude, self.latitude, self.depth, point.longitude, point.latitude, point.depth)
python
def distance(self, point): return geodetic.distance(self.longitude, self.latitude, self.depth, point.longitude, point.latitude, point.depth)
[ "def", "distance", "(", "self", ",", "point", ")", ":", "return", "geodetic", ".", "distance", "(", "self", ".", "longitude", ",", "self", ".", "latitude", ",", "self", ".", "depth", ",", "point", ".", "longitude", ",", "point", ".", "latitude", ",", "point", ".", "depth", ")" ]
Compute the distance (in km) between this point and the given point. Distance is calculated using pythagoras theorem, where the hypotenuse is the distance and the other two sides are the horizontal distance (great circle distance) and vertical distance (depth difference between the two locations). :param point: Destination point. :type point: Instance of :class:`Point` :returns: The distance. :rtype: float
[ "Compute", "the", "distance", "(", "in", "km", ")", "between", "this", "point", "and", "the", "given", "point", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/point.py#L139-L158
gem/oq-engine
openquake/hazardlib/geo/point.py
Point.distance_to_mesh
def distance_to_mesh(self, mesh, with_depths=True): """ Compute distance (in km) between this point and each point of ``mesh``. :param mesh: :class:`~openquake.hazardlib.geo.mesh.Mesh` of points to calculate distance to. :param with_depths: If ``True`` (by default), distance is calculated between actual point and the mesh, geodetic distance of projections is combined with vertical distance (difference of depths). If this is set to ``False``, only geodetic distance between projections is calculated. :returns: Numpy array of floats of the same shape as ``mesh`` with distance values in km in respective indices. """ if with_depths: if mesh.depths is None: mesh_depths = numpy.zeros_like(mesh.lons) else: mesh_depths = mesh.depths return geodetic.distance(self.longitude, self.latitude, self.depth, mesh.lons, mesh.lats, mesh_depths) else: return geodetic.geodetic_distance(self.longitude, self.latitude, mesh.lons, mesh.lats)
python
def distance_to_mesh(self, mesh, with_depths=True): if with_depths: if mesh.depths is None: mesh_depths = numpy.zeros_like(mesh.lons) else: mesh_depths = mesh.depths return geodetic.distance(self.longitude, self.latitude, self.depth, mesh.lons, mesh.lats, mesh_depths) else: return geodetic.geodetic_distance(self.longitude, self.latitude, mesh.lons, mesh.lats)
[ "def", "distance_to_mesh", "(", "self", ",", "mesh", ",", "with_depths", "=", "True", ")", ":", "if", "with_depths", ":", "if", "mesh", ".", "depths", "is", "None", ":", "mesh_depths", "=", "numpy", ".", "zeros_like", "(", "mesh", ".", "lons", ")", "else", ":", "mesh_depths", "=", "mesh", ".", "depths", "return", "geodetic", ".", "distance", "(", "self", ".", "longitude", ",", "self", ".", "latitude", ",", "self", ".", "depth", ",", "mesh", ".", "lons", ",", "mesh", ".", "lats", ",", "mesh_depths", ")", "else", ":", "return", "geodetic", ".", "geodetic_distance", "(", "self", ".", "longitude", ",", "self", ".", "latitude", ",", "mesh", ".", "lons", ",", "mesh", ".", "lats", ")" ]
Compute distance (in km) between this point and each point of ``mesh``. :param mesh: :class:`~openquake.hazardlib.geo.mesh.Mesh` of points to calculate distance to. :param with_depths: If ``True`` (by default), distance is calculated between actual point and the mesh, geodetic distance of projections is combined with vertical distance (difference of depths). If this is set to ``False``, only geodetic distance between projections is calculated. :returns: Numpy array of floats of the same shape as ``mesh`` with distance values in km in respective indices.
[ "Compute", "distance", "(", "in", "km", ")", "between", "this", "point", "and", "each", "point", "of", "mesh", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/point.py#L160-L186
gem/oq-engine
openquake/hazardlib/geo/point.py
Point.equally_spaced_points
def equally_spaced_points(self, point, distance): """ Compute the set of points equally spaced between this point and the given point. :param point: Destination point. :type point: Instance of :class:`Point` :param distance: Distance between points (in km). :type distance: float :returns: The list of equally spaced points. :rtype: list of :class:`Point` instances """ lons, lats, depths = geodetic.intervals_between( self.longitude, self.latitude, self.depth, point.longitude, point.latitude, point.depth, distance) return [Point(lons[i], lats[i], depths[i]) for i in range(len(lons))]
python
def equally_spaced_points(self, point, distance): lons, lats, depths = geodetic.intervals_between( self.longitude, self.latitude, self.depth, point.longitude, point.latitude, point.depth, distance) return [Point(lons[i], lats[i], depths[i]) for i in range(len(lons))]
[ "def", "equally_spaced_points", "(", "self", ",", "point", ",", "distance", ")", ":", "lons", ",", "lats", ",", "depths", "=", "geodetic", ".", "intervals_between", "(", "self", ".", "longitude", ",", "self", ".", "latitude", ",", "self", ".", "depth", ",", "point", ".", "longitude", ",", "point", ".", "latitude", ",", "point", ".", "depth", ",", "distance", ")", "return", "[", "Point", "(", "lons", "[", "i", "]", ",", "lats", "[", "i", "]", ",", "depths", "[", "i", "]", ")", "for", "i", "in", "range", "(", "len", "(", "lons", ")", ")", "]" ]
Compute the set of points equally spaced between this point and the given point. :param point: Destination point. :type point: Instance of :class:`Point` :param distance: Distance between points (in km). :type distance: float :returns: The list of equally spaced points. :rtype: list of :class:`Point` instances
[ "Compute", "the", "set", "of", "points", "equally", "spaced", "between", "this", "point", "and", "the", "given", "point", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/point.py#L235-L257
gem/oq-engine
openquake/hazardlib/geo/point.py
Point.to_polygon
def to_polygon(self, radius): """ Create a circular polygon with specified radius centered in the point. :param radius: Required radius of a new polygon, in km. :returns: Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon` that approximates a circle around the point with specified radius. """ assert radius > 0 # avoid circular imports from openquake.hazardlib.geo.polygon import Polygon # get a projection that is centered in the point proj = geo_utils.OrthographicProjection( self.longitude, self.longitude, self.latitude, self.latitude) # create a shapely object from a projected point coordinates, # which are supposedly (0, 0) point = shapely.geometry.Point(*proj(self.longitude, self.latitude)) # extend the point to a shapely polygon using buffer() # and create openquake.hazardlib.geo.polygon.Polygon object from it return Polygon._from_2d(point.buffer(radius), proj)
python
def to_polygon(self, radius): assert radius > 0 from openquake.hazardlib.geo.polygon import Polygon proj = geo_utils.OrthographicProjection( self.longitude, self.longitude, self.latitude, self.latitude) point = shapely.geometry.Point(*proj(self.longitude, self.latitude)) return Polygon._from_2d(point.buffer(radius), proj)
[ "def", "to_polygon", "(", "self", ",", "radius", ")", ":", "assert", "radius", ">", "0", "# avoid circular imports", "from", "openquake", ".", "hazardlib", ".", "geo", ".", "polygon", "import", "Polygon", "# get a projection that is centered in the point", "proj", "=", "geo_utils", ".", "OrthographicProjection", "(", "self", ".", "longitude", ",", "self", ".", "longitude", ",", "self", ".", "latitude", ",", "self", ".", "latitude", ")", "# create a shapely object from a projected point coordinates,", "# which are supposedly (0, 0)", "point", "=", "shapely", ".", "geometry", ".", "Point", "(", "*", "proj", "(", "self", ".", "longitude", ",", "self", ".", "latitude", ")", ")", "# extend the point to a shapely polygon using buffer()", "# and create openquake.hazardlib.geo.polygon.Polygon object from it", "return", "Polygon", ".", "_from_2d", "(", "point", ".", "buffer", "(", "radius", ")", ",", "proj", ")" ]
Create a circular polygon with specified radius centered in the point. :param radius: Required radius of a new polygon, in km. :returns: Instance of :class:`~openquake.hazardlib.geo.polygon.Polygon` that approximates a circle around the point with specified radius.
[ "Create", "a", "circular", "polygon", "with", "specified", "radius", "centered", "in", "the", "point", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/point.py#L259-L283
gem/oq-engine
openquake/hazardlib/geo/point.py
Point.closer_than
def closer_than(self, mesh, radius): """ Check for proximity of points in the ``mesh``. :param mesh: :class:`openquake.hazardlib.geo.mesh.Mesh` instance. :param radius: Proximity measure in km. :returns: Numpy array of boolean values in the same shape as the mesh coordinate arrays with ``True`` on indexes of points that are not further than ``radius`` km from this point. Function :func:`~openquake.hazardlib.geo.geodetic.distance` is used to calculate distances to points of the mesh. Points of the mesh that lie exactly ``radius`` km away from this point also have ``True`` in their indices. """ dists = geodetic.distance(self.longitude, self.latitude, self.depth, mesh.lons, mesh.lats, 0 if mesh.depths is None else mesh.depths) return dists <= radius
python
def closer_than(self, mesh, radius): dists = geodetic.distance(self.longitude, self.latitude, self.depth, mesh.lons, mesh.lats, 0 if mesh.depths is None else mesh.depths) return dists <= radius
[ "def", "closer_than", "(", "self", ",", "mesh", ",", "radius", ")", ":", "dists", "=", "geodetic", ".", "distance", "(", "self", ".", "longitude", ",", "self", ".", "latitude", ",", "self", ".", "depth", ",", "mesh", ".", "lons", ",", "mesh", ".", "lats", ",", "0", "if", "mesh", ".", "depths", "is", "None", "else", "mesh", ".", "depths", ")", "return", "dists", "<=", "radius" ]
Check for proximity of points in the ``mesh``. :param mesh: :class:`openquake.hazardlib.geo.mesh.Mesh` instance. :param radius: Proximity measure in km. :returns: Numpy array of boolean values in the same shape as the mesh coordinate arrays with ``True`` on indexes of points that are not further than ``radius`` km from this point. Function :func:`~openquake.hazardlib.geo.geodetic.distance` is used to calculate distances to points of the mesh. Points of the mesh that lie exactly ``radius`` km away from this point also have ``True`` in their indices.
[ "Check", "for", "proximity", "of", "points", "in", "the", "mesh", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/point.py#L285-L305
gem/oq-engine
openquake/commands/info.py
source_model_info
def source_model_info(nodes): """ Extract information about NRML/0.5 source models. Returns a table with TRTs as rows and source classes as columns. """ c = collections.Counter() for node in nodes: for src_group in node: trt = src_group['tectonicRegion'] for src in src_group: src_class = src.tag.split('}')[1] c[trt, src_class] += 1 trts, classes = zip(*c) trts = sorted(set(trts)) classes = sorted(set(classes)) dtlist = [('TRT', (bytes, 30))] + [(name, int) for name in classes] out = numpy.zeros(len(trts) + 1, dtlist) # +1 for the totals for i, trt in enumerate(trts): out[i]['TRT'] = trt for src_class in classes: out[i][src_class] = c[trt, src_class] out[-1]['TRT'] = 'Total' for name in out.dtype.names[1:]: out[-1][name] = out[name][:-1].sum() return rst_table(out)
python
def source_model_info(nodes): c = collections.Counter() for node in nodes: for src_group in node: trt = src_group['tectonicRegion'] for src in src_group: src_class = src.tag.split('}')[1] c[trt, src_class] += 1 trts, classes = zip(*c) trts = sorted(set(trts)) classes = sorted(set(classes)) dtlist = [('TRT', (bytes, 30))] + [(name, int) for name in classes] out = numpy.zeros(len(trts) + 1, dtlist) for i, trt in enumerate(trts): out[i]['TRT'] = trt for src_class in classes: out[i][src_class] = c[trt, src_class] out[-1]['TRT'] = 'Total' for name in out.dtype.names[1:]: out[-1][name] = out[name][:-1].sum() return rst_table(out)
[ "def", "source_model_info", "(", "nodes", ")", ":", "c", "=", "collections", ".", "Counter", "(", ")", "for", "node", "in", "nodes", ":", "for", "src_group", "in", "node", ":", "trt", "=", "src_group", "[", "'tectonicRegion'", "]", "for", "src", "in", "src_group", ":", "src_class", "=", "src", ".", "tag", ".", "split", "(", "'}'", ")", "[", "1", "]", "c", "[", "trt", ",", "src_class", "]", "+=", "1", "trts", ",", "classes", "=", "zip", "(", "*", "c", ")", "trts", "=", "sorted", "(", "set", "(", "trts", ")", ")", "classes", "=", "sorted", "(", "set", "(", "classes", ")", ")", "dtlist", "=", "[", "(", "'TRT'", ",", "(", "bytes", ",", "30", ")", ")", "]", "+", "[", "(", "name", ",", "int", ")", "for", "name", "in", "classes", "]", "out", "=", "numpy", ".", "zeros", "(", "len", "(", "trts", ")", "+", "1", ",", "dtlist", ")", "# +1 for the totals", "for", "i", ",", "trt", "in", "enumerate", "(", "trts", ")", ":", "out", "[", "i", "]", "[", "'TRT'", "]", "=", "trt", "for", "src_class", "in", "classes", ":", "out", "[", "i", "]", "[", "src_class", "]", "=", "c", "[", "trt", ",", "src_class", "]", "out", "[", "-", "1", "]", "[", "'TRT'", "]", "=", "'Total'", "for", "name", "in", "out", ".", "dtype", ".", "names", "[", "1", ":", "]", ":", "out", "[", "-", "1", "]", "[", "name", "]", "=", "out", "[", "name", "]", "[", ":", "-", "1", "]", ".", "sum", "(", ")", "return", "rst_table", "(", "out", ")" ]
Extract information about NRML/0.5 source models. Returns a table with TRTs as rows and source classes as columns.
[ "Extract", "information", "about", "NRML", "/", "0", ".", "5", "source", "models", ".", "Returns", "a", "table", "with", "TRTs", "as", "rows", "and", "source", "classes", "as", "columns", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/info.py#L38-L62
gem/oq-engine
openquake/commands/info.py
print_csm_info
def print_csm_info(fname): """ Parse the composite source model without instantiating the sources and prints information about its composition and the full logic tree """ oqparam = readinput.get_oqparam(fname) csm = readinput.get_composite_source_model(oqparam, in_memory=False) print(csm.info) print('See http://docs.openquake.org/oq-engine/stable/' 'effective-realizations.html for an explanation') rlzs_assoc = csm.info.get_rlzs_assoc() print(rlzs_assoc) dupl = [(srcs[0]['id'], len(srcs)) for srcs in csm.check_dupl_sources()] if dupl: print(rst_table(dupl, ['source_id', 'multiplicity'])) tot, pairs = get_pickled_sizes(rlzs_assoc) print(rst_table(pairs, ['attribute', 'nbytes']))
python
def print_csm_info(fname): oqparam = readinput.get_oqparam(fname) csm = readinput.get_composite_source_model(oqparam, in_memory=False) print(csm.info) print('See http://docs.openquake.org/oq-engine/stable/' 'effective-realizations.html for an explanation') rlzs_assoc = csm.info.get_rlzs_assoc() print(rlzs_assoc) dupl = [(srcs[0]['id'], len(srcs)) for srcs in csm.check_dupl_sources()] if dupl: print(rst_table(dupl, ['source_id', 'multiplicity'])) tot, pairs = get_pickled_sizes(rlzs_assoc) print(rst_table(pairs, ['attribute', 'nbytes']))
[ "def", "print_csm_info", "(", "fname", ")", ":", "oqparam", "=", "readinput", ".", "get_oqparam", "(", "fname", ")", "csm", "=", "readinput", ".", "get_composite_source_model", "(", "oqparam", ",", "in_memory", "=", "False", ")", "print", "(", "csm", ".", "info", ")", "print", "(", "'See http://docs.openquake.org/oq-engine/stable/'", "'effective-realizations.html for an explanation'", ")", "rlzs_assoc", "=", "csm", ".", "info", ".", "get_rlzs_assoc", "(", ")", "print", "(", "rlzs_assoc", ")", "dupl", "=", "[", "(", "srcs", "[", "0", "]", "[", "'id'", "]", ",", "len", "(", "srcs", ")", ")", "for", "srcs", "in", "csm", ".", "check_dupl_sources", "(", ")", "]", "if", "dupl", ":", "print", "(", "rst_table", "(", "dupl", ",", "[", "'source_id'", ",", "'multiplicity'", "]", ")", ")", "tot", ",", "pairs", "=", "get_pickled_sizes", "(", "rlzs_assoc", ")", "print", "(", "rst_table", "(", "pairs", ",", "[", "'attribute'", ",", "'nbytes'", "]", ")", ")" ]
Parse the composite source model without instantiating the sources and prints information about its composition and the full logic tree
[ "Parse", "the", "composite", "source", "model", "without", "instantiating", "the", "sources", "and", "prints", "information", "about", "its", "composition", "and", "the", "full", "logic", "tree" ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/info.py#L65-L81
gem/oq-engine
openquake/commands/info.py
do_build_reports
def do_build_reports(directory): """ Walk the directory and builds pre-calculation reports for all the job.ini files found. """ for cwd, dirs, files in os.walk(directory): for f in sorted(files): if f in ('job.ini', 'job_h.ini', 'job_haz.ini', 'job_hazard.ini'): job_ini = os.path.join(cwd, f) logging.info(job_ini) try: reportwriter.build_report(job_ini, cwd) except Exception as e: logging.error(str(e))
python
def do_build_reports(directory): for cwd, dirs, files in os.walk(directory): for f in sorted(files): if f in ('job.ini', 'job_h.ini', 'job_haz.ini', 'job_hazard.ini'): job_ini = os.path.join(cwd, f) logging.info(job_ini) try: reportwriter.build_report(job_ini, cwd) except Exception as e: logging.error(str(e))
[ "def", "do_build_reports", "(", "directory", ")", ":", "for", "cwd", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "directory", ")", ":", "for", "f", "in", "sorted", "(", "files", ")", ":", "if", "f", "in", "(", "'job.ini'", ",", "'job_h.ini'", ",", "'job_haz.ini'", ",", "'job_hazard.ini'", ")", ":", "job_ini", "=", "os", ".", "path", ".", "join", "(", "cwd", ",", "f", ")", "logging", ".", "info", "(", "job_ini", ")", "try", ":", "reportwriter", ".", "build_report", "(", "job_ini", ",", "cwd", ")", "except", "Exception", "as", "e", ":", "logging", ".", "error", "(", "str", "(", "e", ")", ")" ]
Walk the directory and builds pre-calculation reports for all the job.ini files found.
[ "Walk", "the", "directory", "and", "builds", "pre", "-", "calculation", "reports", "for", "all", "the", "job", ".", "ini", "files", "found", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/info.py#L84-L97
gem/oq-engine
openquake/commands/info.py
info
def info(calculators, gsims, views, exports, extracts, parameters, report, input_file=''): """ Give information. You can pass the name of an available calculator, a job.ini file, or a zip archive with the input files. """ if calculators: for calc in sorted(base.calculators): print(calc) if gsims: for gs in gsim.get_available_gsims(): print(gs) if views: for name in sorted(view): print(name) if exports: dic = groupby(export, operator.itemgetter(0), lambda group: [r[1] for r in group]) n = 0 for exporter, formats in dic.items(): print(exporter, formats) n += len(formats) print('There are %d exporters defined.' % n) if extracts: for key in extract: func = extract[key] if hasattr(func, '__wrapped__'): fm = FunctionMaker(func.__wrapped__) else: fm = FunctionMaker(func) print('%s(%s)%s' % (fm.name, fm.signature, fm.doc)) if parameters: params = [] for val in vars(OqParam).values(): if hasattr(val, 'name'): params.append(val) params.sort(key=lambda x: x.name) for param in params: print(param.name) if os.path.isdir(input_file) and report: with Monitor('info', measuremem=True) as mon: with mock.patch.object(logging.root, 'info'): # reduce logging do_build_reports(input_file) print(mon) elif input_file.endswith('.xml'): node = nrml.read(input_file) if node[0].tag.endswith('sourceModel'): if node['xmlns'].endswith('nrml/0.4'): raise InvalidFile( '%s is in NRML 0.4 format, please run the following ' 'command:\noq upgrade_nrml %s' % ( input_file, os.path.dirname(input_file) or '.')) print(source_model_info([node[0]])) elif node[0].tag.endswith('logicTree'): nodes = [nrml.read(sm_path)[0] for sm_path in logictree.collect_info(input_file).smpaths] print(source_model_info(nodes)) else: print(node.to_str()) elif input_file.endswith(('.ini', '.zip')): with Monitor('info', measuremem=True) as mon: if report: print('Generated', reportwriter.build_report(input_file)) else: print_csm_info(input_file) if mon.duration > 1: print(mon) elif input_file: print("No info for '%s'" % input_file)
python
def info(calculators, gsims, views, exports, extracts, parameters, report, input_file=''): if calculators: for calc in sorted(base.calculators): print(calc) if gsims: for gs in gsim.get_available_gsims(): print(gs) if views: for name in sorted(view): print(name) if exports: dic = groupby(export, operator.itemgetter(0), lambda group: [r[1] for r in group]) n = 0 for exporter, formats in dic.items(): print(exporter, formats) n += len(formats) print('There are %d exporters defined.' % n) if extracts: for key in extract: func = extract[key] if hasattr(func, '__wrapped__'): fm = FunctionMaker(func.__wrapped__) else: fm = FunctionMaker(func) print('%s(%s)%s' % (fm.name, fm.signature, fm.doc)) if parameters: params = [] for val in vars(OqParam).values(): if hasattr(val, 'name'): params.append(val) params.sort(key=lambda x: x.name) for param in params: print(param.name) if os.path.isdir(input_file) and report: with Monitor('info', measuremem=True) as mon: with mock.patch.object(logging.root, 'info'): do_build_reports(input_file) print(mon) elif input_file.endswith('.xml'): node = nrml.read(input_file) if node[0].tag.endswith('sourceModel'): if node['xmlns'].endswith('nrml/0.4'): raise InvalidFile( '%s is in NRML 0.4 format, please run the following ' 'command:\noq upgrade_nrml %s' % ( input_file, os.path.dirname(input_file) or '.')) print(source_model_info([node[0]])) elif node[0].tag.endswith('logicTree'): nodes = [nrml.read(sm_path)[0] for sm_path in logictree.collect_info(input_file).smpaths] print(source_model_info(nodes)) else: print(node.to_str()) elif input_file.endswith(('.ini', '.zip')): with Monitor('info', measuremem=True) as mon: if report: print('Generated', reportwriter.build_report(input_file)) else: print_csm_info(input_file) if mon.duration > 1: print(mon) elif input_file: print("No info for '%s'" % input_file)
[ "def", "info", "(", "calculators", ",", "gsims", ",", "views", ",", "exports", ",", "extracts", ",", "parameters", ",", "report", ",", "input_file", "=", "''", ")", ":", "if", "calculators", ":", "for", "calc", "in", "sorted", "(", "base", ".", "calculators", ")", ":", "print", "(", "calc", ")", "if", "gsims", ":", "for", "gs", "in", "gsim", ".", "get_available_gsims", "(", ")", ":", "print", "(", "gs", ")", "if", "views", ":", "for", "name", "in", "sorted", "(", "view", ")", ":", "print", "(", "name", ")", "if", "exports", ":", "dic", "=", "groupby", "(", "export", ",", "operator", ".", "itemgetter", "(", "0", ")", ",", "lambda", "group", ":", "[", "r", "[", "1", "]", "for", "r", "in", "group", "]", ")", "n", "=", "0", "for", "exporter", ",", "formats", "in", "dic", ".", "items", "(", ")", ":", "print", "(", "exporter", ",", "formats", ")", "n", "+=", "len", "(", "formats", ")", "print", "(", "'There are %d exporters defined.'", "%", "n", ")", "if", "extracts", ":", "for", "key", "in", "extract", ":", "func", "=", "extract", "[", "key", "]", "if", "hasattr", "(", "func", ",", "'__wrapped__'", ")", ":", "fm", "=", "FunctionMaker", "(", "func", ".", "__wrapped__", ")", "else", ":", "fm", "=", "FunctionMaker", "(", "func", ")", "print", "(", "'%s(%s)%s'", "%", "(", "fm", ".", "name", ",", "fm", ".", "signature", ",", "fm", ".", "doc", ")", ")", "if", "parameters", ":", "params", "=", "[", "]", "for", "val", "in", "vars", "(", "OqParam", ")", ".", "values", "(", ")", ":", "if", "hasattr", "(", "val", ",", "'name'", ")", ":", "params", ".", "append", "(", "val", ")", "params", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", ".", "name", ")", "for", "param", "in", "params", ":", "print", "(", "param", ".", "name", ")", "if", "os", ".", "path", ".", "isdir", "(", "input_file", ")", "and", "report", ":", "with", "Monitor", "(", "'info'", ",", "measuremem", "=", "True", ")", "as", "mon", ":", "with", "mock", ".", "patch", ".", "object", "(", "logging", ".", "root", ",", "'info'", ")", ":", "# reduce logging", "do_build_reports", "(", "input_file", ")", "print", "(", "mon", ")", "elif", "input_file", ".", "endswith", "(", "'.xml'", ")", ":", "node", "=", "nrml", ".", "read", "(", "input_file", ")", "if", "node", "[", "0", "]", ".", "tag", ".", "endswith", "(", "'sourceModel'", ")", ":", "if", "node", "[", "'xmlns'", "]", ".", "endswith", "(", "'nrml/0.4'", ")", ":", "raise", "InvalidFile", "(", "'%s is in NRML 0.4 format, please run the following '", "'command:\\noq upgrade_nrml %s'", "%", "(", "input_file", ",", "os", ".", "path", ".", "dirname", "(", "input_file", ")", "or", "'.'", ")", ")", "print", "(", "source_model_info", "(", "[", "node", "[", "0", "]", "]", ")", ")", "elif", "node", "[", "0", "]", ".", "tag", ".", "endswith", "(", "'logicTree'", ")", ":", "nodes", "=", "[", "nrml", ".", "read", "(", "sm_path", ")", "[", "0", "]", "for", "sm_path", "in", "logictree", ".", "collect_info", "(", "input_file", ")", ".", "smpaths", "]", "print", "(", "source_model_info", "(", "nodes", ")", ")", "else", ":", "print", "(", "node", ".", "to_str", "(", ")", ")", "elif", "input_file", ".", "endswith", "(", "(", "'.ini'", ",", "'.zip'", ")", ")", ":", "with", "Monitor", "(", "'info'", ",", "measuremem", "=", "True", ")", "as", "mon", ":", "if", "report", ":", "print", "(", "'Generated'", ",", "reportwriter", ".", "build_report", "(", "input_file", ")", ")", "else", ":", "print_csm_info", "(", "input_file", ")", "if", "mon", ".", "duration", ">", "1", ":", "print", "(", "mon", ")", "elif", "input_file", ":", "print", "(", "\"No info for '%s'\"", "%", "input_file", ")" ]
Give information. You can pass the name of an available calculator, a job.ini file, or a zip archive with the input files.
[ "Give", "information", ".", "You", "can", "pass", "the", "name", "of", "an", "available", "calculator", "a", "job", ".", "ini", "file", "or", "a", "zip", "archive", "with", "the", "input", "files", "." ]
train
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/info.py#L103-L171