id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
100
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): ''' 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!')
[ "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" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L365-L388
101
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): ''' 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)
[ "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" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L479-L507
102
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): ''' 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
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/faults/fault_models.py#L509-L557
103
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): """ 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)), ])
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/models.py#L53-L61
104
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): """ 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)), ])
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/models.py#L325-L334
105
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): """ 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)), ])
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/models.py#L359-L368
106
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): """ 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)
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/correlation.py#L116-L145
107
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): """ 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))
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/correlation.py#L225-L262
108
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): """ 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))
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/correlation.py#L92-L113
109
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): """ 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
[ "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" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ebrisk.py#L38-L48
110
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" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L91-L94
111
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): """ 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
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L289-L308
112
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): """ 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
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L310-L332
113
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): """ 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
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/mfd/youngs_coppersmith_1985.py#L334-L348
114
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): ''' 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
[ "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" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/area_source.py#L118-L151
115
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): ''' 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))
[ "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" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/area_source.py#L180-L202
116
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): """ 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
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/performance.py#L185-L197
117
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): """ 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
[ "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" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L164-L180
118
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=()): """ 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
[ "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" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L183-L230
119
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): """ 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
[ "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" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L256-L262
120
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): """ 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)
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/site.py#L345-L370
121
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): """ 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)
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/point.py#L94-L120
122
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): """ 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))]
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/point.py#L235-L257
123
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): """ 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)
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/point.py#L259-L283
124
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): """ 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
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/geo/point.py#L285-L305
125
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): """ 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']))
[ "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" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/info.py#L65-L81
126
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): """ 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))
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/info.py#L84-L97
127
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=''): """ 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)
[ "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", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/info.py#L103-L171
128
gem/oq-engine
openquake/calculators/classical.py
classical_split_filter
def classical_split_filter(srcs, srcfilter, gsims, params, monitor): """ Split the given sources, filter the subsources and the compute the PoEs. Yield back subtasks if the split sources contain more than maxweight ruptures. """ # first check if we are sampling the sources ss = int(os.environ.get('OQ_SAMPLE_SOURCES', 0)) if ss: splits, stime = split_sources(srcs) srcs = readinput.random_filtered_sources(splits, srcfilter, ss) yield classical(srcs, srcfilter, gsims, params, monitor) return sources = [] with monitor("filtering/splitting sources"): for src, _sites in srcfilter(srcs): if src.num_ruptures >= params['maxweight']: splits, stime = split_sources([src]) sources.extend(srcfilter.filter(splits)) else: sources.append(src) blocks = list(block_splitter(sources, params['maxweight'], operator.attrgetter('num_ruptures'))) if blocks: # yield the first blocks (if any) and compute the last block in core # NB: the last block is usually the smallest one for block in blocks[:-1]: yield classical, block, srcfilter, gsims, params yield classical(blocks[-1], srcfilter, gsims, params, monitor)
python
def classical_split_filter(srcs, srcfilter, gsims, params, monitor): """ Split the given sources, filter the subsources and the compute the PoEs. Yield back subtasks if the split sources contain more than maxweight ruptures. """ # first check if we are sampling the sources ss = int(os.environ.get('OQ_SAMPLE_SOURCES', 0)) if ss: splits, stime = split_sources(srcs) srcs = readinput.random_filtered_sources(splits, srcfilter, ss) yield classical(srcs, srcfilter, gsims, params, monitor) return sources = [] with monitor("filtering/splitting sources"): for src, _sites in srcfilter(srcs): if src.num_ruptures >= params['maxweight']: splits, stime = split_sources([src]) sources.extend(srcfilter.filter(splits)) else: sources.append(src) blocks = list(block_splitter(sources, params['maxweight'], operator.attrgetter('num_ruptures'))) if blocks: # yield the first blocks (if any) and compute the last block in core # NB: the last block is usually the smallest one for block in blocks[:-1]: yield classical, block, srcfilter, gsims, params yield classical(blocks[-1], srcfilter, gsims, params, monitor)
[ "def", "classical_split_filter", "(", "srcs", ",", "srcfilter", ",", "gsims", ",", "params", ",", "monitor", ")", ":", "# first check if we are sampling the sources", "ss", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "'OQ_SAMPLE_SOURCES'", ",", "0", ")", ")", "if", "ss", ":", "splits", ",", "stime", "=", "split_sources", "(", "srcs", ")", "srcs", "=", "readinput", ".", "random_filtered_sources", "(", "splits", ",", "srcfilter", ",", "ss", ")", "yield", "classical", "(", "srcs", ",", "srcfilter", ",", "gsims", ",", "params", ",", "monitor", ")", "return", "sources", "=", "[", "]", "with", "monitor", "(", "\"filtering/splitting sources\"", ")", ":", "for", "src", ",", "_sites", "in", "srcfilter", "(", "srcs", ")", ":", "if", "src", ".", "num_ruptures", ">=", "params", "[", "'maxweight'", "]", ":", "splits", ",", "stime", "=", "split_sources", "(", "[", "src", "]", ")", "sources", ".", "extend", "(", "srcfilter", ".", "filter", "(", "splits", ")", ")", "else", ":", "sources", ".", "append", "(", "src", ")", "blocks", "=", "list", "(", "block_splitter", "(", "sources", ",", "params", "[", "'maxweight'", "]", ",", "operator", ".", "attrgetter", "(", "'num_ruptures'", ")", ")", ")", "if", "blocks", ":", "# yield the first blocks (if any) and compute the last block in core", "# NB: the last block is usually the smallest one", "for", "block", "in", "blocks", "[", ":", "-", "1", "]", ":", "yield", "classical", ",", "block", ",", "srcfilter", ",", "gsims", ",", "params", "yield", "classical", "(", "blocks", "[", "-", "1", "]", ",", "srcfilter", ",", "gsims", ",", "params", ",", "monitor", ")" ]
Split the given sources, filter the subsources and the compute the PoEs. Yield back subtasks if the split sources contain more than maxweight ruptures.
[ "Split", "the", "given", "sources", "filter", "the", "subsources", "and", "the", "compute", "the", "PoEs", ".", "Yield", "back", "subtasks", "if", "the", "split", "sources", "contain", "more", "than", "maxweight", "ruptures", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/classical.py#L72-L100
129
gem/oq-engine
openquake/hmtk/seismicity/gcmt_utils.py
get_azimuth_plunge
def get_azimuth_plunge(vect, degrees=True): ''' For a given vector in USE format, retrieve the azimuth and plunge ''' if vect[0] > 0: vect = -1. * np.copy(vect) vect_hor = sqrt(vect[1] ** 2. + vect[2] ** 2.) plunge = atan2(-vect[0], vect_hor) azimuth = atan2(vect[2], -vect[1]) if degrees: icr = 180. / pi return icr * azimuth % 360., icr * plunge else: return azimuth % (2. * pi), plunge
python
def get_azimuth_plunge(vect, degrees=True): ''' For a given vector in USE format, retrieve the azimuth and plunge ''' if vect[0] > 0: vect = -1. * np.copy(vect) vect_hor = sqrt(vect[1] ** 2. + vect[2] ** 2.) plunge = atan2(-vect[0], vect_hor) azimuth = atan2(vect[2], -vect[1]) if degrees: icr = 180. / pi return icr * azimuth % 360., icr * plunge else: return azimuth % (2. * pi), plunge
[ "def", "get_azimuth_plunge", "(", "vect", ",", "degrees", "=", "True", ")", ":", "if", "vect", "[", "0", "]", ">", "0", ":", "vect", "=", "-", "1.", "*", "np", ".", "copy", "(", "vect", ")", "vect_hor", "=", "sqrt", "(", "vect", "[", "1", "]", "**", "2.", "+", "vect", "[", "2", "]", "**", "2.", ")", "plunge", "=", "atan2", "(", "-", "vect", "[", "0", "]", ",", "vect_hor", ")", "azimuth", "=", "atan2", "(", "vect", "[", "2", "]", ",", "-", "vect", "[", "1", "]", ")", "if", "degrees", ":", "icr", "=", "180.", "/", "pi", "return", "icr", "*", "azimuth", "%", "360.", ",", "icr", "*", "plunge", "else", ":", "return", "azimuth", "%", "(", "2.", "*", "pi", ")", ",", "plunge" ]
For a given vector in USE format, retrieve the azimuth and plunge
[ "For", "a", "given", "vector", "in", "USE", "format", "retrieve", "the", "azimuth", "and", "plunge" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L77-L90
130
gem/oq-engine
openquake/hmtk/seismicity/gcmt_utils.py
use_to_ned
def use_to_ned(tensor): ''' Converts a tensor in USE coordinate sytem to NED ''' return np.array(ROT_NED_USE.T * np.matrix(tensor) * ROT_NED_USE)
python
def use_to_ned(tensor): ''' Converts a tensor in USE coordinate sytem to NED ''' return np.array(ROT_NED_USE.T * np.matrix(tensor) * ROT_NED_USE)
[ "def", "use_to_ned", "(", "tensor", ")", ":", "return", "np", ".", "array", "(", "ROT_NED_USE", ".", "T", "*", "np", ".", "matrix", "(", "tensor", ")", "*", "ROT_NED_USE", ")" ]
Converts a tensor in USE coordinate sytem to NED
[ "Converts", "a", "tensor", "in", "USE", "coordinate", "sytem", "to", "NED" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L101-L105
131
gem/oq-engine
openquake/hmtk/seismicity/gcmt_utils.py
ned_to_use
def ned_to_use(tensor): ''' Converts a tensor in NED coordinate sytem to USE ''' return np.array(ROT_NED_USE * np.matrix(tensor) * ROT_NED_USE.T)
python
def ned_to_use(tensor): ''' Converts a tensor in NED coordinate sytem to USE ''' return np.array(ROT_NED_USE * np.matrix(tensor) * ROT_NED_USE.T)
[ "def", "ned_to_use", "(", "tensor", ")", ":", "return", "np", ".", "array", "(", "ROT_NED_USE", "*", "np", ".", "matrix", "(", "tensor", ")", "*", "ROT_NED_USE", ".", "T", ")" ]
Converts a tensor in NED coordinate sytem to USE
[ "Converts", "a", "tensor", "in", "NED", "coordinate", "sytem", "to", "USE" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/gcmt_utils.py#L108-L112
132
gem/oq-engine
openquake/hazardlib/gsim/boore_atkinson_2008.py
Atkinson2010Hawaii.get_mean_and_stddevs
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ Using a frequency dependent correction for the mean ground motion. Standard deviation is fixed. """ mean, stddevs = super().get_mean_and_stddevs(sites, rup, dists, imt, stddev_types) # Defining frequency if imt == PGA(): freq = 50.0 elif imt == PGV(): freq = 2.0 else: freq = 1./imt.period # Equation 3 of Atkinson (2010) x1 = np.min([-0.18+0.17*np.log10(freq), 0]) # Equation 4 a-b-c of Atkinson (2010) if rup.hypo_depth < 20.0: x0 = np.max([0.217-0.321*np.log10(freq), 0]) elif rup.hypo_depth > 35.0: x0 = np.min([0.263+0.0924*np.log10(freq), 0.35]) else: x0 = 0.2 # Limiting calculation distance to 1km # (as suggested by C. Bruce Worden) rjb = [d if d > 1 else 1 for d in dists.rjb] # Equation 2 and 5 of Atkinson (2010) mean += (x0 + x1*np.log10(rjb))/np.log10(np.e) return mean, stddevs
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ Using a frequency dependent correction for the mean ground motion. Standard deviation is fixed. """ mean, stddevs = super().get_mean_and_stddevs(sites, rup, dists, imt, stddev_types) # Defining frequency if imt == PGA(): freq = 50.0 elif imt == PGV(): freq = 2.0 else: freq = 1./imt.period # Equation 3 of Atkinson (2010) x1 = np.min([-0.18+0.17*np.log10(freq), 0]) # Equation 4 a-b-c of Atkinson (2010) if rup.hypo_depth < 20.0: x0 = np.max([0.217-0.321*np.log10(freq), 0]) elif rup.hypo_depth > 35.0: x0 = np.min([0.263+0.0924*np.log10(freq), 0.35]) else: x0 = 0.2 # Limiting calculation distance to 1km # (as suggested by C. Bruce Worden) rjb = [d if d > 1 else 1 for d in dists.rjb] # Equation 2 and 5 of Atkinson (2010) mean += (x0 + x1*np.log10(rjb))/np.log10(np.e) return mean, stddevs
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "mean", ",", "stddevs", "=", "super", "(", ")", ".", "get_mean_and_stddevs", "(", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", "# Defining frequency", "if", "imt", "==", "PGA", "(", ")", ":", "freq", "=", "50.0", "elif", "imt", "==", "PGV", "(", ")", ":", "freq", "=", "2.0", "else", ":", "freq", "=", "1.", "/", "imt", ".", "period", "# Equation 3 of Atkinson (2010)", "x1", "=", "np", ".", "min", "(", "[", "-", "0.18", "+", "0.17", "*", "np", ".", "log10", "(", "freq", ")", ",", "0", "]", ")", "# Equation 4 a-b-c of Atkinson (2010)", "if", "rup", ".", "hypo_depth", "<", "20.0", ":", "x0", "=", "np", ".", "max", "(", "[", "0.217", "-", "0.321", "*", "np", ".", "log10", "(", "freq", ")", ",", "0", "]", ")", "elif", "rup", ".", "hypo_depth", ">", "35.0", ":", "x0", "=", "np", ".", "min", "(", "[", "0.263", "+", "0.0924", "*", "np", ".", "log10", "(", "freq", ")", ",", "0.35", "]", ")", "else", ":", "x0", "=", "0.2", "# Limiting calculation distance to 1km", "# (as suggested by C. Bruce Worden)", "rjb", "=", "[", "d", "if", "d", ">", "1", "else", "1", "for", "d", "in", "dists", ".", "rjb", "]", "# Equation 2 and 5 of Atkinson (2010)", "mean", "+=", "(", "x0", "+", "x1", "*", "np", ".", "log10", "(", "rjb", ")", ")", "/", "np", ".", "log10", "(", "np", ".", "e", ")", "return", "mean", ",", "stddevs" ]
Using a frequency dependent correction for the mean ground motion. Standard deviation is fixed.
[ "Using", "a", "frequency", "dependent", "correction", "for", "the", "mean", "ground", "motion", ".", "Standard", "deviation", "is", "fixed", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_atkinson_2008.py#L383-L416
133
gem/oq-engine
openquake/commonlib/rlzs_assoc.py
RlzsAssoc.get_rlz
def get_rlz(self, rlzstr): r""" Get a Realization instance for a string of the form 'rlz-\d+' """ mo = re.match(r'rlz-(\d+)', rlzstr) if not mo: return return self.realizations[int(mo.group(1))]
python
def get_rlz(self, rlzstr): r""" Get a Realization instance for a string of the form 'rlz-\d+' """ mo = re.match(r'rlz-(\d+)', rlzstr) if not mo: return return self.realizations[int(mo.group(1))]
[ "def", "get_rlz", "(", "self", ",", "rlzstr", ")", ":", "mo", "=", "re", ".", "match", "(", "r'rlz-(\\d+)'", ",", "rlzstr", ")", "if", "not", "mo", ":", "return", "return", "self", ".", "realizations", "[", "int", "(", "mo", ".", "group", "(", "1", ")", ")", "]" ]
r""" Get a Realization instance for a string of the form 'rlz-\d+'
[ "r", "Get", "a", "Realization", "instance", "for", "a", "string", "of", "the", "form", "rlz", "-", "\\", "d", "+" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/rlzs_assoc.py#L190-L197
134
gem/oq-engine
openquake/commands/export.py
export
def export(datastore_key, calc_id=-1, exports='csv', export_dir='.'): """ Export an output from the datastore. """ dstore = util.read(calc_id) parent_id = dstore['oqparam'].hazard_calculation_id if parent_id: dstore.parent = util.read(parent_id) dstore.export_dir = export_dir with performance.Monitor('export', measuremem=True) as mon: for fmt in exports.split(','): fnames = export_((datastore_key, fmt), dstore) nbytes = sum(os.path.getsize(f) for f in fnames) print('Exported %s in %s' % (general.humansize(nbytes), fnames)) if mon.duration > 1: print(mon) dstore.close()
python
def export(datastore_key, calc_id=-1, exports='csv', export_dir='.'): """ Export an output from the datastore. """ dstore = util.read(calc_id) parent_id = dstore['oqparam'].hazard_calculation_id if parent_id: dstore.parent = util.read(parent_id) dstore.export_dir = export_dir with performance.Monitor('export', measuremem=True) as mon: for fmt in exports.split(','): fnames = export_((datastore_key, fmt), dstore) nbytes = sum(os.path.getsize(f) for f in fnames) print('Exported %s in %s' % (general.humansize(nbytes), fnames)) if mon.duration > 1: print(mon) dstore.close()
[ "def", "export", "(", "datastore_key", ",", "calc_id", "=", "-", "1", ",", "exports", "=", "'csv'", ",", "export_dir", "=", "'.'", ")", ":", "dstore", "=", "util", ".", "read", "(", "calc_id", ")", "parent_id", "=", "dstore", "[", "'oqparam'", "]", ".", "hazard_calculation_id", "if", "parent_id", ":", "dstore", ".", "parent", "=", "util", ".", "read", "(", "parent_id", ")", "dstore", ".", "export_dir", "=", "export_dir", "with", "performance", ".", "Monitor", "(", "'export'", ",", "measuremem", "=", "True", ")", "as", "mon", ":", "for", "fmt", "in", "exports", ".", "split", "(", "','", ")", ":", "fnames", "=", "export_", "(", "(", "datastore_key", ",", "fmt", ")", ",", "dstore", ")", "nbytes", "=", "sum", "(", "os", ".", "path", ".", "getsize", "(", "f", ")", "for", "f", "in", "fnames", ")", "print", "(", "'Exported %s in %s'", "%", "(", "general", ".", "humansize", "(", "nbytes", ")", ",", "fnames", ")", ")", "if", "mon", ".", "duration", ">", "1", ":", "print", "(", "mon", ")", "dstore", ".", "close", "(", ")" ]
Export an output from the datastore.
[ "Export", "an", "output", "from", "the", "datastore", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/export.py#L27-L43
135
gem/oq-engine
openquake/calculators/ucerf_base.py
convert_UCERFSource
def convert_UCERFSource(self, node): """ Converts the Ucerf Source node into an SES Control object """ dirname = os.path.dirname(self.fname) # where the source_model_file is source_file = os.path.join(dirname, node["filename"]) if "startDate" in node.attrib and "investigationTime" in node.attrib: # Is a time-dependent model - even if rates were originally # poissonian # Verify that the source time span is the same as the TOM time span inv_time = float(node["investigationTime"]) if inv_time != self.investigation_time: raise ValueError("Source investigation time (%s) is not " "equal to configuration investigation time " "(%s)" % (inv_time, self.investigation_time)) start_date = datetime.strptime(node["startDate"], "%d/%m/%Y") else: start_date = None return UCERFSource( source_file, self.investigation_time, start_date, float(node["minMag"]), npd=self.convert_npdist(node), hdd=self.convert_hpdist(node), aspect=~node.ruptAspectRatio, upper_seismogenic_depth=~node.pointGeometry.upperSeismoDepth, lower_seismogenic_depth=~node.pointGeometry.lowerSeismoDepth, msr=valid.SCALEREL[~node.magScaleRel](), mesh_spacing=self.rupture_mesh_spacing, trt=node["tectonicRegion"])
python
def convert_UCERFSource(self, node): """ Converts the Ucerf Source node into an SES Control object """ dirname = os.path.dirname(self.fname) # where the source_model_file is source_file = os.path.join(dirname, node["filename"]) if "startDate" in node.attrib and "investigationTime" in node.attrib: # Is a time-dependent model - even if rates were originally # poissonian # Verify that the source time span is the same as the TOM time span inv_time = float(node["investigationTime"]) if inv_time != self.investigation_time: raise ValueError("Source investigation time (%s) is not " "equal to configuration investigation time " "(%s)" % (inv_time, self.investigation_time)) start_date = datetime.strptime(node["startDate"], "%d/%m/%Y") else: start_date = None return UCERFSource( source_file, self.investigation_time, start_date, float(node["minMag"]), npd=self.convert_npdist(node), hdd=self.convert_hpdist(node), aspect=~node.ruptAspectRatio, upper_seismogenic_depth=~node.pointGeometry.upperSeismoDepth, lower_seismogenic_depth=~node.pointGeometry.lowerSeismoDepth, msr=valid.SCALEREL[~node.magScaleRel](), mesh_spacing=self.rupture_mesh_spacing, trt=node["tectonicRegion"])
[ "def", "convert_UCERFSource", "(", "self", ",", "node", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "fname", ")", "# where the source_model_file is", "source_file", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "node", "[", "\"filename\"", "]", ")", "if", "\"startDate\"", "in", "node", ".", "attrib", "and", "\"investigationTime\"", "in", "node", ".", "attrib", ":", "# Is a time-dependent model - even if rates were originally", "# poissonian", "# Verify that the source time span is the same as the TOM time span", "inv_time", "=", "float", "(", "node", "[", "\"investigationTime\"", "]", ")", "if", "inv_time", "!=", "self", ".", "investigation_time", ":", "raise", "ValueError", "(", "\"Source investigation time (%s) is not \"", "\"equal to configuration investigation time \"", "\"(%s)\"", "%", "(", "inv_time", ",", "self", ".", "investigation_time", ")", ")", "start_date", "=", "datetime", ".", "strptime", "(", "node", "[", "\"startDate\"", "]", ",", "\"%d/%m/%Y\"", ")", "else", ":", "start_date", "=", "None", "return", "UCERFSource", "(", "source_file", ",", "self", ".", "investigation_time", ",", "start_date", ",", "float", "(", "node", "[", "\"minMag\"", "]", ")", ",", "npd", "=", "self", ".", "convert_npdist", "(", "node", ")", ",", "hdd", "=", "self", ".", "convert_hpdist", "(", "node", ")", ",", "aspect", "=", "~", "node", ".", "ruptAspectRatio", ",", "upper_seismogenic_depth", "=", "~", "node", ".", "pointGeometry", ".", "upperSeismoDepth", ",", "lower_seismogenic_depth", "=", "~", "node", ".", "pointGeometry", ".", "lowerSeismoDepth", ",", "msr", "=", "valid", ".", "SCALEREL", "[", "~", "node", ".", "magScaleRel", "]", "(", ")", ",", "mesh_spacing", "=", "self", ".", "rupture_mesh_spacing", ",", "trt", "=", "node", "[", "\"tectonicRegion\"", "]", ")" ]
Converts the Ucerf Source node into an SES Control object
[ "Converts", "the", "Ucerf", "Source", "node", "into", "an", "SES", "Control", "object" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L58-L88
136
gem/oq-engine
openquake/calculators/ucerf_base.py
build_idx_set
def build_idx_set(branch_id, start_date): """ Builds a dictionary of keys based on the branch code """ code_set = branch_id.split("/") code_set.insert(3, "Rates") idx_set = { "sec": "/".join([code_set[0], code_set[1], "Sections"]), "mag": "/".join([code_set[0], code_set[1], code_set[2], "Magnitude"])} idx_set["rate"] = "/".join(code_set) idx_set["rake"] = "/".join([code_set[0], code_set[1], "Rake"]) idx_set["msr"] = "-".join(code_set[:3]) idx_set["geol"] = code_set[0] if start_date: # time-dependent source idx_set["grid_key"] = "_".join( branch_id.replace("/", "_").split("_")[:-1]) else: # time-independent source idx_set["grid_key"] = branch_id.replace("/", "_") idx_set["total_key"] = branch_id.replace("/", "|") return idx_set
python
def build_idx_set(branch_id, start_date): """ Builds a dictionary of keys based on the branch code """ code_set = branch_id.split("/") code_set.insert(3, "Rates") idx_set = { "sec": "/".join([code_set[0], code_set[1], "Sections"]), "mag": "/".join([code_set[0], code_set[1], code_set[2], "Magnitude"])} idx_set["rate"] = "/".join(code_set) idx_set["rake"] = "/".join([code_set[0], code_set[1], "Rake"]) idx_set["msr"] = "-".join(code_set[:3]) idx_set["geol"] = code_set[0] if start_date: # time-dependent source idx_set["grid_key"] = "_".join( branch_id.replace("/", "_").split("_")[:-1]) else: # time-independent source idx_set["grid_key"] = branch_id.replace("/", "_") idx_set["total_key"] = branch_id.replace("/", "|") return idx_set
[ "def", "build_idx_set", "(", "branch_id", ",", "start_date", ")", ":", "code_set", "=", "branch_id", ".", "split", "(", "\"/\"", ")", "code_set", ".", "insert", "(", "3", ",", "\"Rates\"", ")", "idx_set", "=", "{", "\"sec\"", ":", "\"/\"", ".", "join", "(", "[", "code_set", "[", "0", "]", ",", "code_set", "[", "1", "]", ",", "\"Sections\"", "]", ")", ",", "\"mag\"", ":", "\"/\"", ".", "join", "(", "[", "code_set", "[", "0", "]", ",", "code_set", "[", "1", "]", ",", "code_set", "[", "2", "]", ",", "\"Magnitude\"", "]", ")", "}", "idx_set", "[", "\"rate\"", "]", "=", "\"/\"", ".", "join", "(", "code_set", ")", "idx_set", "[", "\"rake\"", "]", "=", "\"/\"", ".", "join", "(", "[", "code_set", "[", "0", "]", ",", "code_set", "[", "1", "]", ",", "\"Rake\"", "]", ")", "idx_set", "[", "\"msr\"", "]", "=", "\"-\"", ".", "join", "(", "code_set", "[", ":", "3", "]", ")", "idx_set", "[", "\"geol\"", "]", "=", "code_set", "[", "0", "]", "if", "start_date", ":", "# time-dependent source", "idx_set", "[", "\"grid_key\"", "]", "=", "\"_\"", ".", "join", "(", "branch_id", ".", "replace", "(", "\"/\"", ",", "\"_\"", ")", ".", "split", "(", "\"_\"", ")", "[", ":", "-", "1", "]", ")", "else", ":", "# time-independent source", "idx_set", "[", "\"grid_key\"", "]", "=", "branch_id", ".", "replace", "(", "\"/\"", ",", "\"_\"", ")", "idx_set", "[", "\"total_key\"", "]", "=", "branch_id", ".", "replace", "(", "\"/\"", ",", "\"|\"", ")", "return", "idx_set" ]
Builds a dictionary of keys based on the branch code
[ "Builds", "a", "dictionary", "of", "keys", "based", "on", "the", "branch", "code" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L433-L452
137
gem/oq-engine
openquake/calculators/ucerf_base.py
get_rupture_surface
def get_rupture_surface(mag, nodal_plane, hypocenter, msr, rupture_aspect_ratio, upper_seismogenic_depth, lower_seismogenic_depth, mesh_spacing=1.0): """ Create and return rupture surface object with given properties. :param mag: Magnitude value, used to calculate rupture dimensions, see :meth:`_get_rupture_dimensions`. :param nodal_plane: Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane` describing the rupture orientation. :param hypocenter: Point representing rupture's hypocenter. :returns: Instance of :class:`~openquake.hazardlib.geo.surface.planar.PlanarSurface`. """ assert (upper_seismogenic_depth <= hypocenter.depth and lower_seismogenic_depth >= hypocenter.depth) rdip = math.radians(nodal_plane.dip) # precalculated azimuth values for horizontal-only and vertical-only # moves from one point to another on the plane defined by strike # and dip: azimuth_right = nodal_plane.strike azimuth_down = (azimuth_right + 90) % 360 azimuth_left = (azimuth_down + 90) % 360 azimuth_up = (azimuth_left + 90) % 360 rup_length, rup_width = get_rupture_dimensions( mag, nodal_plane, msr, rupture_aspect_ratio, upper_seismogenic_depth, lower_seismogenic_depth) # calculate the height of the rupture being projected # on the vertical plane: rup_proj_height = rup_width * math.sin(rdip) # and it's width being projected on the horizontal one: rup_proj_width = rup_width * math.cos(rdip) # half height of the vertical component of rupture width # is the vertical distance between the rupture geometrical # center and it's upper and lower borders: hheight = rup_proj_height / 2 # calculate how much shallower the upper border of the rupture # is than the upper seismogenic depth: vshift = upper_seismogenic_depth - hypocenter.depth + hheight # if it is shallower (vshift > 0) than we need to move the rupture # by that value vertically. if vshift < 0: # the top edge is below upper seismogenic depth. now we need # to check that we do not cross the lower border. vshift = lower_seismogenic_depth - hypocenter.depth - hheight if vshift > 0: # the bottom edge of the rupture is above the lower sesmogenic # depth. that means that we don't need to move the rupture # as it fits inside seismogenic layer. vshift = 0 # if vshift < 0 than we need to move the rupture up by that value. # now we need to find the position of rupture's geometrical center. # in any case the hypocenter point must lie on the surface, however # the rupture center might be off (below or above) along the dip. rupture_center = hypocenter if vshift != 0: # we need to move the rupture center to make the rupture fit # inside the seismogenic layer. hshift = abs(vshift / math.tan(rdip)) rupture_center = rupture_center.point_at( horizontal_distance=hshift, vertical_increment=vshift, azimuth=(azimuth_up if vshift < 0 else azimuth_down)) # from the rupture center we can now compute the coordinates of the # four coorners by moving along the diagonals of the plane. This seems # to be better then moving along the perimeter, because in this case # errors are accumulated that induce distorsions in the shape with # consequent raise of exceptions when creating PlanarSurface objects # theta is the angle between the diagonal of the surface projection # and the line passing through the rupture center and parallel to the # top and bottom edges. Theta is zero for vertical ruptures (because # rup_proj_width is zero) theta = math.degrees( math.atan((rup_proj_width / 2.) / (rup_length / 2.))) hor_dist = math.sqrt( (rup_length / 2.) ** 2 + (rup_proj_width / 2.) ** 2) left_top = rupture_center.point_at( horizontal_distance=hor_dist, vertical_increment=-rup_proj_height / 2, azimuth=(nodal_plane.strike + 180 + theta) % 360) right_top = rupture_center.point_at( horizontal_distance=hor_dist, vertical_increment=-rup_proj_height / 2, azimuth=(nodal_plane.strike - theta) % 360) left_bottom = rupture_center.point_at( horizontal_distance=hor_dist, vertical_increment=rup_proj_height / 2, azimuth=(nodal_plane.strike + 180 - theta) % 360) right_bottom = rupture_center.point_at( horizontal_distance=hor_dist, vertical_increment=rup_proj_height / 2, azimuth=(nodal_plane.strike + theta) % 360) return PlanarSurface(nodal_plane.strike, nodal_plane.dip, left_top, right_top, right_bottom, left_bottom)
python
def get_rupture_surface(mag, nodal_plane, hypocenter, msr, rupture_aspect_ratio, upper_seismogenic_depth, lower_seismogenic_depth, mesh_spacing=1.0): """ Create and return rupture surface object with given properties. :param mag: Magnitude value, used to calculate rupture dimensions, see :meth:`_get_rupture_dimensions`. :param nodal_plane: Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane` describing the rupture orientation. :param hypocenter: Point representing rupture's hypocenter. :returns: Instance of :class:`~openquake.hazardlib.geo.surface.planar.PlanarSurface`. """ assert (upper_seismogenic_depth <= hypocenter.depth and lower_seismogenic_depth >= hypocenter.depth) rdip = math.radians(nodal_plane.dip) # precalculated azimuth values for horizontal-only and vertical-only # moves from one point to another on the plane defined by strike # and dip: azimuth_right = nodal_plane.strike azimuth_down = (azimuth_right + 90) % 360 azimuth_left = (azimuth_down + 90) % 360 azimuth_up = (azimuth_left + 90) % 360 rup_length, rup_width = get_rupture_dimensions( mag, nodal_plane, msr, rupture_aspect_ratio, upper_seismogenic_depth, lower_seismogenic_depth) # calculate the height of the rupture being projected # on the vertical plane: rup_proj_height = rup_width * math.sin(rdip) # and it's width being projected on the horizontal one: rup_proj_width = rup_width * math.cos(rdip) # half height of the vertical component of rupture width # is the vertical distance between the rupture geometrical # center and it's upper and lower borders: hheight = rup_proj_height / 2 # calculate how much shallower the upper border of the rupture # is than the upper seismogenic depth: vshift = upper_seismogenic_depth - hypocenter.depth + hheight # if it is shallower (vshift > 0) than we need to move the rupture # by that value vertically. if vshift < 0: # the top edge is below upper seismogenic depth. now we need # to check that we do not cross the lower border. vshift = lower_seismogenic_depth - hypocenter.depth - hheight if vshift > 0: # the bottom edge of the rupture is above the lower sesmogenic # depth. that means that we don't need to move the rupture # as it fits inside seismogenic layer. vshift = 0 # if vshift < 0 than we need to move the rupture up by that value. # now we need to find the position of rupture's geometrical center. # in any case the hypocenter point must lie on the surface, however # the rupture center might be off (below or above) along the dip. rupture_center = hypocenter if vshift != 0: # we need to move the rupture center to make the rupture fit # inside the seismogenic layer. hshift = abs(vshift / math.tan(rdip)) rupture_center = rupture_center.point_at( horizontal_distance=hshift, vertical_increment=vshift, azimuth=(azimuth_up if vshift < 0 else azimuth_down)) # from the rupture center we can now compute the coordinates of the # four coorners by moving along the diagonals of the plane. This seems # to be better then moving along the perimeter, because in this case # errors are accumulated that induce distorsions in the shape with # consequent raise of exceptions when creating PlanarSurface objects # theta is the angle between the diagonal of the surface projection # and the line passing through the rupture center and parallel to the # top and bottom edges. Theta is zero for vertical ruptures (because # rup_proj_width is zero) theta = math.degrees( math.atan((rup_proj_width / 2.) / (rup_length / 2.))) hor_dist = math.sqrt( (rup_length / 2.) ** 2 + (rup_proj_width / 2.) ** 2) left_top = rupture_center.point_at( horizontal_distance=hor_dist, vertical_increment=-rup_proj_height / 2, azimuth=(nodal_plane.strike + 180 + theta) % 360) right_top = rupture_center.point_at( horizontal_distance=hor_dist, vertical_increment=-rup_proj_height / 2, azimuth=(nodal_plane.strike - theta) % 360) left_bottom = rupture_center.point_at( horizontal_distance=hor_dist, vertical_increment=rup_proj_height / 2, azimuth=(nodal_plane.strike + 180 - theta) % 360) right_bottom = rupture_center.point_at( horizontal_distance=hor_dist, vertical_increment=rup_proj_height / 2, azimuth=(nodal_plane.strike + theta) % 360) return PlanarSurface(nodal_plane.strike, nodal_plane.dip, left_top, right_top, right_bottom, left_bottom)
[ "def", "get_rupture_surface", "(", "mag", ",", "nodal_plane", ",", "hypocenter", ",", "msr", ",", "rupture_aspect_ratio", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "mesh_spacing", "=", "1.0", ")", ":", "assert", "(", "upper_seismogenic_depth", "<=", "hypocenter", ".", "depth", "and", "lower_seismogenic_depth", ">=", "hypocenter", ".", "depth", ")", "rdip", "=", "math", ".", "radians", "(", "nodal_plane", ".", "dip", ")", "# precalculated azimuth values for horizontal-only and vertical-only", "# moves from one point to another on the plane defined by strike", "# and dip:", "azimuth_right", "=", "nodal_plane", ".", "strike", "azimuth_down", "=", "(", "azimuth_right", "+", "90", ")", "%", "360", "azimuth_left", "=", "(", "azimuth_down", "+", "90", ")", "%", "360", "azimuth_up", "=", "(", "azimuth_left", "+", "90", ")", "%", "360", "rup_length", ",", "rup_width", "=", "get_rupture_dimensions", "(", "mag", ",", "nodal_plane", ",", "msr", ",", "rupture_aspect_ratio", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ")", "# calculate the height of the rupture being projected", "# on the vertical plane:", "rup_proj_height", "=", "rup_width", "*", "math", ".", "sin", "(", "rdip", ")", "# and it's width being projected on the horizontal one:", "rup_proj_width", "=", "rup_width", "*", "math", ".", "cos", "(", "rdip", ")", "# half height of the vertical component of rupture width", "# is the vertical distance between the rupture geometrical", "# center and it's upper and lower borders:", "hheight", "=", "rup_proj_height", "/", "2", "# calculate how much shallower the upper border of the rupture", "# is than the upper seismogenic depth:", "vshift", "=", "upper_seismogenic_depth", "-", "hypocenter", ".", "depth", "+", "hheight", "# if it is shallower (vshift > 0) than we need to move the rupture", "# by that value vertically.", "if", "vshift", "<", "0", ":", "# the top edge is below upper seismogenic depth. now we need", "# to check that we do not cross the lower border.", "vshift", "=", "lower_seismogenic_depth", "-", "hypocenter", ".", "depth", "-", "hheight", "if", "vshift", ">", "0", ":", "# the bottom edge of the rupture is above the lower sesmogenic", "# depth. that means that we don't need to move the rupture", "# as it fits inside seismogenic layer.", "vshift", "=", "0", "# if vshift < 0 than we need to move the rupture up by that value.", "# now we need to find the position of rupture's geometrical center.", "# in any case the hypocenter point must lie on the surface, however", "# the rupture center might be off (below or above) along the dip.", "rupture_center", "=", "hypocenter", "if", "vshift", "!=", "0", ":", "# we need to move the rupture center to make the rupture fit", "# inside the seismogenic layer.", "hshift", "=", "abs", "(", "vshift", "/", "math", ".", "tan", "(", "rdip", ")", ")", "rupture_center", "=", "rupture_center", ".", "point_at", "(", "horizontal_distance", "=", "hshift", ",", "vertical_increment", "=", "vshift", ",", "azimuth", "=", "(", "azimuth_up", "if", "vshift", "<", "0", "else", "azimuth_down", ")", ")", "# from the rupture center we can now compute the coordinates of the", "# four coorners by moving along the diagonals of the plane. This seems", "# to be better then moving along the perimeter, because in this case", "# errors are accumulated that induce distorsions in the shape with", "# consequent raise of exceptions when creating PlanarSurface objects", "# theta is the angle between the diagonal of the surface projection", "# and the line passing through the rupture center and parallel to the", "# top and bottom edges. Theta is zero for vertical ruptures (because", "# rup_proj_width is zero)", "theta", "=", "math", ".", "degrees", "(", "math", ".", "atan", "(", "(", "rup_proj_width", "/", "2.", ")", "/", "(", "rup_length", "/", "2.", ")", ")", ")", "hor_dist", "=", "math", ".", "sqrt", "(", "(", "rup_length", "/", "2.", ")", "**", "2", "+", "(", "rup_proj_width", "/", "2.", ")", "**", "2", ")", "left_top", "=", "rupture_center", ".", "point_at", "(", "horizontal_distance", "=", "hor_dist", ",", "vertical_increment", "=", "-", "rup_proj_height", "/", "2", ",", "azimuth", "=", "(", "nodal_plane", ".", "strike", "+", "180", "+", "theta", ")", "%", "360", ")", "right_top", "=", "rupture_center", ".", "point_at", "(", "horizontal_distance", "=", "hor_dist", ",", "vertical_increment", "=", "-", "rup_proj_height", "/", "2", ",", "azimuth", "=", "(", "nodal_plane", ".", "strike", "-", "theta", ")", "%", "360", ")", "left_bottom", "=", "rupture_center", ".", "point_at", "(", "horizontal_distance", "=", "hor_dist", ",", "vertical_increment", "=", "rup_proj_height", "/", "2", ",", "azimuth", "=", "(", "nodal_plane", ".", "strike", "+", "180", "-", "theta", ")", "%", "360", ")", "right_bottom", "=", "rupture_center", ".", "point_at", "(", "horizontal_distance", "=", "hor_dist", ",", "vertical_increment", "=", "rup_proj_height", "/", "2", ",", "azimuth", "=", "(", "nodal_plane", ".", "strike", "+", "theta", ")", "%", "360", ")", "return", "PlanarSurface", "(", "nodal_plane", ".", "strike", ",", "nodal_plane", ".", "dip", ",", "left_top", ",", "right_top", ",", "right_bottom", ",", "left_bottom", ")" ]
Create and return rupture surface object with given properties. :param mag: Magnitude value, used to calculate rupture dimensions, see :meth:`_get_rupture_dimensions`. :param nodal_plane: Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane` describing the rupture orientation. :param hypocenter: Point representing rupture's hypocenter. :returns: Instance of :class:`~openquake.hazardlib.geo.surface.planar.PlanarSurface`.
[ "Create", "and", "return", "rupture", "surface", "object", "with", "given", "properties", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L492-L593
138
gem/oq-engine
openquake/calculators/ucerf_base.py
UCERFSource.get_ridx
def get_ridx(self, iloc): """List of rupture indices for the given iloc""" with h5py.File(self.source_file, "r") as hdf5: return hdf5[self.idx_set["geol"] + "/RuptureIndex"][iloc]
python
def get_ridx(self, iloc): """List of rupture indices for the given iloc""" with h5py.File(self.source_file, "r") as hdf5: return hdf5[self.idx_set["geol"] + "/RuptureIndex"][iloc]
[ "def", "get_ridx", "(", "self", ",", "iloc", ")", ":", "with", "h5py", ".", "File", "(", "self", ".", "source_file", ",", "\"r\"", ")", "as", "hdf5", ":", "return", "hdf5", "[", "self", ".", "idx_set", "[", "\"geol\"", "]", "+", "\"/RuptureIndex\"", "]", "[", "iloc", "]" ]
List of rupture indices for the given iloc
[ "List", "of", "rupture", "indices", "for", "the", "given", "iloc" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L271-L274
139
gem/oq-engine
openquake/calculators/ucerf_base.py
UCERFSource.get_background_sids
def get_background_sids(self, src_filter): """ We can apply the filtering of the background sites as a pre-processing step - this is done here rather than in the sampling of the ruptures themselves """ branch_key = self.idx_set["grid_key"] idist = src_filter.integration_distance(DEFAULT_TRT) with h5py.File(self.source_file, 'r') as hdf5: bg_locations = hdf5["Grid/Locations"].value distances = min_geodetic_distance( src_filter.sitecol.xyz, (bg_locations[:, 0], bg_locations[:, 1])) # Add buffer equal to half of length of median area from Mmax mmax_areas = self.msr.get_median_area( hdf5["/".join(["Grid", branch_key, "MMax"])].value, 0.0) # for instance hdf5['Grid/FM0_0_MEANFS_MEANMSR/MMax'] mmax_lengths = numpy.sqrt(mmax_areas / self.aspect) ok = distances <= (0.5 * mmax_lengths + idist) # get list of indices from array of booleans return numpy.where(ok)[0].tolist()
python
def get_background_sids(self, src_filter): """ We can apply the filtering of the background sites as a pre-processing step - this is done here rather than in the sampling of the ruptures themselves """ branch_key = self.idx_set["grid_key"] idist = src_filter.integration_distance(DEFAULT_TRT) with h5py.File(self.source_file, 'r') as hdf5: bg_locations = hdf5["Grid/Locations"].value distances = min_geodetic_distance( src_filter.sitecol.xyz, (bg_locations[:, 0], bg_locations[:, 1])) # Add buffer equal to half of length of median area from Mmax mmax_areas = self.msr.get_median_area( hdf5["/".join(["Grid", branch_key, "MMax"])].value, 0.0) # for instance hdf5['Grid/FM0_0_MEANFS_MEANMSR/MMax'] mmax_lengths = numpy.sqrt(mmax_areas / self.aspect) ok = distances <= (0.5 * mmax_lengths + idist) # get list of indices from array of booleans return numpy.where(ok)[0].tolist()
[ "def", "get_background_sids", "(", "self", ",", "src_filter", ")", ":", "branch_key", "=", "self", ".", "idx_set", "[", "\"grid_key\"", "]", "idist", "=", "src_filter", ".", "integration_distance", "(", "DEFAULT_TRT", ")", "with", "h5py", ".", "File", "(", "self", ".", "source_file", ",", "'r'", ")", "as", "hdf5", ":", "bg_locations", "=", "hdf5", "[", "\"Grid/Locations\"", "]", ".", "value", "distances", "=", "min_geodetic_distance", "(", "src_filter", ".", "sitecol", ".", "xyz", ",", "(", "bg_locations", "[", ":", ",", "0", "]", ",", "bg_locations", "[", ":", ",", "1", "]", ")", ")", "# Add buffer equal to half of length of median area from Mmax", "mmax_areas", "=", "self", ".", "msr", ".", "get_median_area", "(", "hdf5", "[", "\"/\"", ".", "join", "(", "[", "\"Grid\"", ",", "branch_key", ",", "\"MMax\"", "]", ")", "]", ".", "value", ",", "0.0", ")", "# for instance hdf5['Grid/FM0_0_MEANFS_MEANMSR/MMax']", "mmax_lengths", "=", "numpy", ".", "sqrt", "(", "mmax_areas", "/", "self", ".", "aspect", ")", "ok", "=", "distances", "<=", "(", "0.5", "*", "mmax_lengths", "+", "idist", ")", "# get list of indices from array of booleans", "return", "numpy", ".", "where", "(", "ok", ")", "[", "0", "]", ".", "tolist", "(", ")" ]
We can apply the filtering of the background sites as a pre-processing step - this is done here rather than in the sampling of the ruptures themselves
[ "We", "can", "apply", "the", "filtering", "of", "the", "background", "sites", "as", "a", "pre", "-", "processing", "step", "-", "this", "is", "done", "here", "rather", "than", "in", "the", "sampling", "of", "the", "ruptures", "themselves" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L297-L317
140
gem/oq-engine
openquake/calculators/ucerf_base.py
UCERFSource.iter_ruptures
def iter_ruptures(self): """ Yield ruptures for the current set of indices """ assert self.orig, '%s is not fully initialized' % self for ridx in range(self.start, self.stop): if self.orig.rate[ridx]: # ruptures may have have zero rate rup = self.get_ucerf_rupture(ridx, self.src_filter) if rup: yield rup
python
def iter_ruptures(self): """ Yield ruptures for the current set of indices """ assert self.orig, '%s is not fully initialized' % self for ridx in range(self.start, self.stop): if self.orig.rate[ridx]: # ruptures may have have zero rate rup = self.get_ucerf_rupture(ridx, self.src_filter) if rup: yield rup
[ "def", "iter_ruptures", "(", "self", ")", ":", "assert", "self", ".", "orig", ",", "'%s is not fully initialized'", "%", "self", "for", "ridx", "in", "range", "(", "self", ".", "start", ",", "self", ".", "stop", ")", ":", "if", "self", ".", "orig", ".", "rate", "[", "ridx", "]", ":", "# ruptures may have have zero rate", "rup", "=", "self", ".", "get_ucerf_rupture", "(", "ridx", ",", "self", ".", "src_filter", ")", "if", "rup", ":", "yield", "rup" ]
Yield ruptures for the current set of indices
[ "Yield", "ruptures", "for", "the", "current", "set", "of", "indices" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L359-L368
141
gem/oq-engine
openquake/calculators/ucerf_base.py
UCERFSource.get_background_sources
def get_background_sources(self, src_filter, sample_factor=None): """ Turn the background model of a given branch into a set of point sources :param src_filter: SourceFilter instance :param sample_factor: Used to reduce the sources if OQ_SAMPLE_SOURCES is set """ background_sids = self.get_background_sids(src_filter) if sample_factor is not None: # hack for use in the mosaic background_sids = random_filter( background_sids, sample_factor, seed=42) with h5py.File(self.source_file, "r") as hdf5: grid_loc = "/".join(["Grid", self.idx_set["grid_key"]]) # for instance Grid/FM0_0_MEANFS_MEANMSR_MeanRates mags = hdf5[grid_loc + "/Magnitude"].value mmax = hdf5[grid_loc + "/MMax"][background_sids] rates = hdf5[grid_loc + "/RateArray"][background_sids, :] locations = hdf5["Grid/Locations"][background_sids, :] sources = [] for i, bg_idx in enumerate(background_sids): src_id = "_".join([self.idx_set["grid_key"], str(bg_idx)]) src_name = "|".join([self.idx_set["total_key"], str(bg_idx)]) mag_idx = (self.min_mag <= mags) & (mags < mmax[i]) src_mags = mags[mag_idx] src_mfd = EvenlyDiscretizedMFD( src_mags[0], src_mags[1] - src_mags[0], rates[i, mag_idx].tolist()) ps = PointSource( src_id, src_name, self.tectonic_region_type, src_mfd, self.mesh_spacing, self.msr, self.aspect, self.tom, self.usd, self.lsd, Point(locations[i, 0], locations[i, 1]), self.npd, self.hdd) ps.id = self.id ps.src_group_id = self.src_group_id ps.num_ruptures = ps.count_ruptures() sources.append(ps) return sources
python
def get_background_sources(self, src_filter, sample_factor=None): """ Turn the background model of a given branch into a set of point sources :param src_filter: SourceFilter instance :param sample_factor: Used to reduce the sources if OQ_SAMPLE_SOURCES is set """ background_sids = self.get_background_sids(src_filter) if sample_factor is not None: # hack for use in the mosaic background_sids = random_filter( background_sids, sample_factor, seed=42) with h5py.File(self.source_file, "r") as hdf5: grid_loc = "/".join(["Grid", self.idx_set["grid_key"]]) # for instance Grid/FM0_0_MEANFS_MEANMSR_MeanRates mags = hdf5[grid_loc + "/Magnitude"].value mmax = hdf5[grid_loc + "/MMax"][background_sids] rates = hdf5[grid_loc + "/RateArray"][background_sids, :] locations = hdf5["Grid/Locations"][background_sids, :] sources = [] for i, bg_idx in enumerate(background_sids): src_id = "_".join([self.idx_set["grid_key"], str(bg_idx)]) src_name = "|".join([self.idx_set["total_key"], str(bg_idx)]) mag_idx = (self.min_mag <= mags) & (mags < mmax[i]) src_mags = mags[mag_idx] src_mfd = EvenlyDiscretizedMFD( src_mags[0], src_mags[1] - src_mags[0], rates[i, mag_idx].tolist()) ps = PointSource( src_id, src_name, self.tectonic_region_type, src_mfd, self.mesh_spacing, self.msr, self.aspect, self.tom, self.usd, self.lsd, Point(locations[i, 0], locations[i, 1]), self.npd, self.hdd) ps.id = self.id ps.src_group_id = self.src_group_id ps.num_ruptures = ps.count_ruptures() sources.append(ps) return sources
[ "def", "get_background_sources", "(", "self", ",", "src_filter", ",", "sample_factor", "=", "None", ")", ":", "background_sids", "=", "self", ".", "get_background_sids", "(", "src_filter", ")", "if", "sample_factor", "is", "not", "None", ":", "# hack for use in the mosaic", "background_sids", "=", "random_filter", "(", "background_sids", ",", "sample_factor", ",", "seed", "=", "42", ")", "with", "h5py", ".", "File", "(", "self", ".", "source_file", ",", "\"r\"", ")", "as", "hdf5", ":", "grid_loc", "=", "\"/\"", ".", "join", "(", "[", "\"Grid\"", ",", "self", ".", "idx_set", "[", "\"grid_key\"", "]", "]", ")", "# for instance Grid/FM0_0_MEANFS_MEANMSR_MeanRates", "mags", "=", "hdf5", "[", "grid_loc", "+", "\"/Magnitude\"", "]", ".", "value", "mmax", "=", "hdf5", "[", "grid_loc", "+", "\"/MMax\"", "]", "[", "background_sids", "]", "rates", "=", "hdf5", "[", "grid_loc", "+", "\"/RateArray\"", "]", "[", "background_sids", ",", ":", "]", "locations", "=", "hdf5", "[", "\"Grid/Locations\"", "]", "[", "background_sids", ",", ":", "]", "sources", "=", "[", "]", "for", "i", ",", "bg_idx", "in", "enumerate", "(", "background_sids", ")", ":", "src_id", "=", "\"_\"", ".", "join", "(", "[", "self", ".", "idx_set", "[", "\"grid_key\"", "]", ",", "str", "(", "bg_idx", ")", "]", ")", "src_name", "=", "\"|\"", ".", "join", "(", "[", "self", ".", "idx_set", "[", "\"total_key\"", "]", ",", "str", "(", "bg_idx", ")", "]", ")", "mag_idx", "=", "(", "self", ".", "min_mag", "<=", "mags", ")", "&", "(", "mags", "<", "mmax", "[", "i", "]", ")", "src_mags", "=", "mags", "[", "mag_idx", "]", "src_mfd", "=", "EvenlyDiscretizedMFD", "(", "src_mags", "[", "0", "]", ",", "src_mags", "[", "1", "]", "-", "src_mags", "[", "0", "]", ",", "rates", "[", "i", ",", "mag_idx", "]", ".", "tolist", "(", ")", ")", "ps", "=", "PointSource", "(", "src_id", ",", "src_name", ",", "self", ".", "tectonic_region_type", ",", "src_mfd", ",", "self", ".", "mesh_spacing", ",", "self", ".", "msr", ",", "self", ".", "aspect", ",", "self", ".", "tom", ",", "self", ".", "usd", ",", "self", ".", "lsd", ",", "Point", "(", "locations", "[", "i", ",", "0", "]", ",", "locations", "[", "i", ",", "1", "]", ")", ",", "self", ".", "npd", ",", "self", ".", "hdd", ")", "ps", ".", "id", "=", "self", ".", "id", "ps", ".", "src_group_id", "=", "self", ".", "src_group_id", "ps", ".", "num_ruptures", "=", "ps", ".", "count_ruptures", "(", ")", "sources", ".", "append", "(", "ps", ")", "return", "sources" ]
Turn the background model of a given branch into a set of point sources :param src_filter: SourceFilter instance :param sample_factor: Used to reduce the sources if OQ_SAMPLE_SOURCES is set
[ "Turn", "the", "background", "model", "of", "a", "given", "branch", "into", "a", "set", "of", "point", "sources" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_base.py#L387-L427
142
gem/oq-engine
openquake/hazardlib/source/rupture_collection.py
split
def split(src, chunksize=MINWEIGHT): """ Split a complex fault source in chunks """ for i, block in enumerate(block_splitter(src.iter_ruptures(), chunksize, key=operator.attrgetter('mag'))): rup = block[0] source_id = '%s:%d' % (src.source_id, i) amfd = mfd.ArbitraryMFD([rup.mag], [rup.mag_occ_rate]) rcs = RuptureCollectionSource( source_id, src.name, src.tectonic_region_type, amfd, block) yield rcs
python
def split(src, chunksize=MINWEIGHT): """ Split a complex fault source in chunks """ for i, block in enumerate(block_splitter(src.iter_ruptures(), chunksize, key=operator.attrgetter('mag'))): rup = block[0] source_id = '%s:%d' % (src.source_id, i) amfd = mfd.ArbitraryMFD([rup.mag], [rup.mag_occ_rate]) rcs = RuptureCollectionSource( source_id, src.name, src.tectonic_region_type, amfd, block) yield rcs
[ "def", "split", "(", "src", ",", "chunksize", "=", "MINWEIGHT", ")", ":", "for", "i", ",", "block", "in", "enumerate", "(", "block_splitter", "(", "src", ".", "iter_ruptures", "(", ")", ",", "chunksize", ",", "key", "=", "operator", ".", "attrgetter", "(", "'mag'", ")", ")", ")", ":", "rup", "=", "block", "[", "0", "]", "source_id", "=", "'%s:%d'", "%", "(", "src", ".", "source_id", ",", "i", ")", "amfd", "=", "mfd", ".", "ArbitraryMFD", "(", "[", "rup", ".", "mag", "]", ",", "[", "rup", ".", "mag_occ_rate", "]", ")", "rcs", "=", "RuptureCollectionSource", "(", "source_id", ",", "src", ".", "name", ",", "src", ".", "tectonic_region_type", ",", "amfd", ",", "block", ")", "yield", "rcs" ]
Split a complex fault source in chunks
[ "Split", "a", "complex", "fault", "source", "in", "chunks" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/source/rupture_collection.py#L61-L72
143
gem/oq-engine
openquake/hazardlib/source/rupture_collection.py
RuptureCollectionSource.get_bounding_box
def get_bounding_box(self, maxdist): """ Bounding box containing all the hypocenters, enlarged by the maximum distance """ locations = [rup.hypocenter for rup in self.ruptures] return get_bounding_box(locations, maxdist)
python
def get_bounding_box(self, maxdist): """ Bounding box containing all the hypocenters, enlarged by the maximum distance """ locations = [rup.hypocenter for rup in self.ruptures] return get_bounding_box(locations, maxdist)
[ "def", "get_bounding_box", "(", "self", ",", "maxdist", ")", ":", "locations", "=", "[", "rup", ".", "hypocenter", "for", "rup", "in", "self", ".", "ruptures", "]", "return", "get_bounding_box", "(", "locations", ",", "maxdist", ")" ]
Bounding box containing all the hypocenters, enlarged by the maximum distance
[ "Bounding", "box", "containing", "all", "the", "hypocenters", "enlarged", "by", "the", "maximum", "distance" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/source/rupture_collection.py#L52-L58
144
gem/oq-engine
openquake/commands/show_attrs.py
show_attrs
def show_attrs(key, calc_id=-1): """ Show the attributes of a HDF5 dataset in the datastore. """ ds = util.read(calc_id) try: attrs = h5py.File.__getitem__(ds.hdf5, key).attrs except KeyError: print('%r is not in %s' % (key, ds)) else: if len(attrs) == 0: print('%s has no attributes' % key) for name, value in attrs.items(): print(name, value) finally: ds.close()
python
def show_attrs(key, calc_id=-1): """ Show the attributes of a HDF5 dataset in the datastore. """ ds = util.read(calc_id) try: attrs = h5py.File.__getitem__(ds.hdf5, key).attrs except KeyError: print('%r is not in %s' % (key, ds)) else: if len(attrs) == 0: print('%s has no attributes' % key) for name, value in attrs.items(): print(name, value) finally: ds.close()
[ "def", "show_attrs", "(", "key", ",", "calc_id", "=", "-", "1", ")", ":", "ds", "=", "util", ".", "read", "(", "calc_id", ")", "try", ":", "attrs", "=", "h5py", ".", "File", ".", "__getitem__", "(", "ds", ".", "hdf5", ",", "key", ")", ".", "attrs", "except", "KeyError", ":", "print", "(", "'%r is not in %s'", "%", "(", "key", ",", "ds", ")", ")", "else", ":", "if", "len", "(", "attrs", ")", "==", "0", ":", "print", "(", "'%s has no attributes'", "%", "key", ")", "for", "name", ",", "value", "in", "attrs", ".", "items", "(", ")", ":", "print", "(", "name", ",", "value", ")", "finally", ":", "ds", ".", "close", "(", ")" ]
Show the attributes of a HDF5 dataset in the datastore.
[ "Show", "the", "attributes", "of", "a", "HDF5", "dataset", "in", "the", "datastore", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/show_attrs.py#L24-L39
145
gem/oq-engine
utils/compare_mean_curves.py
compare_mean_curves
def compare_mean_curves(calc_ref, calc, nsigma=3): """ Compare the hazard curves coming from two different calculations. """ dstore_ref = datastore.read(calc_ref) dstore = datastore.read(calc) imtls = dstore_ref['oqparam'].imtls if dstore['oqparam'].imtls != imtls: raise RuntimeError('The IMTs and levels are different between ' 'calculation %d and %d' % (calc_ref, calc)) sitecol_ref = dstore_ref['sitecol'] sitecol = dstore['sitecol'] site_id_ref = {(lon, lat): sid for sid, lon, lat in zip( sitecol_ref.sids, sitecol_ref.lons, sitecol_ref.lats)} site_id = {(lon, lat): sid for sid, lon, lat in zip( sitecol.sids, sitecol.lons, sitecol.lats)} common = set(site_id_ref) & set(site_id) if not common: raise RuntimeError('There are no common sites between calculation ' '%d and %d' % (calc_ref, calc)) pmap_ref = PmapGetter(dstore_ref, sids=[site_id_ref[lonlat] for lonlat in common]).get_mean() pmap = PmapGetter(dstore, sids=[site_id[lonlat] for lonlat in common]).get_mean() for lonlat in common: mean, std = pmap[site_id[lonlat]].array.T # shape (2, N) mean_ref, std_ref = pmap_ref[site_id_ref[lonlat]].array.T err = numpy.sqrt(std**2 + std_ref**2) for imt in imtls: sl = imtls(imt) ok = (numpy.abs(mean[sl] - mean_ref[sl]) < nsigma * err[sl]).all() if not ok: md = (numpy.abs(mean[sl] - mean_ref[sl])).max() plt.title('point=%s, imt=%s, maxdiff=%.2e' % (lonlat, imt, md)) plt.loglog(imtls[imt], mean_ref[sl] + std_ref[sl], label=str(calc_ref), color='black') plt.loglog(imtls[imt], mean_ref[sl] - std_ref[sl], color='black') plt.loglog(imtls[imt], mean[sl] + std[sl], label=str(calc), color='red') plt.loglog(imtls[imt], mean[sl] - std[sl], color='red') plt.legend() plt.show()
python
def compare_mean_curves(calc_ref, calc, nsigma=3): """ Compare the hazard curves coming from two different calculations. """ dstore_ref = datastore.read(calc_ref) dstore = datastore.read(calc) imtls = dstore_ref['oqparam'].imtls if dstore['oqparam'].imtls != imtls: raise RuntimeError('The IMTs and levels are different between ' 'calculation %d and %d' % (calc_ref, calc)) sitecol_ref = dstore_ref['sitecol'] sitecol = dstore['sitecol'] site_id_ref = {(lon, lat): sid for sid, lon, lat in zip( sitecol_ref.sids, sitecol_ref.lons, sitecol_ref.lats)} site_id = {(lon, lat): sid for sid, lon, lat in zip( sitecol.sids, sitecol.lons, sitecol.lats)} common = set(site_id_ref) & set(site_id) if not common: raise RuntimeError('There are no common sites between calculation ' '%d and %d' % (calc_ref, calc)) pmap_ref = PmapGetter(dstore_ref, sids=[site_id_ref[lonlat] for lonlat in common]).get_mean() pmap = PmapGetter(dstore, sids=[site_id[lonlat] for lonlat in common]).get_mean() for lonlat in common: mean, std = pmap[site_id[lonlat]].array.T # shape (2, N) mean_ref, std_ref = pmap_ref[site_id_ref[lonlat]].array.T err = numpy.sqrt(std**2 + std_ref**2) for imt in imtls: sl = imtls(imt) ok = (numpy.abs(mean[sl] - mean_ref[sl]) < nsigma * err[sl]).all() if not ok: md = (numpy.abs(mean[sl] - mean_ref[sl])).max() plt.title('point=%s, imt=%s, maxdiff=%.2e' % (lonlat, imt, md)) plt.loglog(imtls[imt], mean_ref[sl] + std_ref[sl], label=str(calc_ref), color='black') plt.loglog(imtls[imt], mean_ref[sl] - std_ref[sl], color='black') plt.loglog(imtls[imt], mean[sl] + std[sl], label=str(calc), color='red') plt.loglog(imtls[imt], mean[sl] - std[sl], color='red') plt.legend() plt.show()
[ "def", "compare_mean_curves", "(", "calc_ref", ",", "calc", ",", "nsigma", "=", "3", ")", ":", "dstore_ref", "=", "datastore", ".", "read", "(", "calc_ref", ")", "dstore", "=", "datastore", ".", "read", "(", "calc", ")", "imtls", "=", "dstore_ref", "[", "'oqparam'", "]", ".", "imtls", "if", "dstore", "[", "'oqparam'", "]", ".", "imtls", "!=", "imtls", ":", "raise", "RuntimeError", "(", "'The IMTs and levels are different between '", "'calculation %d and %d'", "%", "(", "calc_ref", ",", "calc", ")", ")", "sitecol_ref", "=", "dstore_ref", "[", "'sitecol'", "]", "sitecol", "=", "dstore", "[", "'sitecol'", "]", "site_id_ref", "=", "{", "(", "lon", ",", "lat", ")", ":", "sid", "for", "sid", ",", "lon", ",", "lat", "in", "zip", "(", "sitecol_ref", ".", "sids", ",", "sitecol_ref", ".", "lons", ",", "sitecol_ref", ".", "lats", ")", "}", "site_id", "=", "{", "(", "lon", ",", "lat", ")", ":", "sid", "for", "sid", ",", "lon", ",", "lat", "in", "zip", "(", "sitecol", ".", "sids", ",", "sitecol", ".", "lons", ",", "sitecol", ".", "lats", ")", "}", "common", "=", "set", "(", "site_id_ref", ")", "&", "set", "(", "site_id", ")", "if", "not", "common", ":", "raise", "RuntimeError", "(", "'There are no common sites between calculation '", "'%d and %d'", "%", "(", "calc_ref", ",", "calc", ")", ")", "pmap_ref", "=", "PmapGetter", "(", "dstore_ref", ",", "sids", "=", "[", "site_id_ref", "[", "lonlat", "]", "for", "lonlat", "in", "common", "]", ")", ".", "get_mean", "(", ")", "pmap", "=", "PmapGetter", "(", "dstore", ",", "sids", "=", "[", "site_id", "[", "lonlat", "]", "for", "lonlat", "in", "common", "]", ")", ".", "get_mean", "(", ")", "for", "lonlat", "in", "common", ":", "mean", ",", "std", "=", "pmap", "[", "site_id", "[", "lonlat", "]", "]", ".", "array", ".", "T", "# shape (2, N)", "mean_ref", ",", "std_ref", "=", "pmap_ref", "[", "site_id_ref", "[", "lonlat", "]", "]", ".", "array", ".", "T", "err", "=", "numpy", ".", "sqrt", "(", "std", "**", "2", "+", "std_ref", "**", "2", ")", "for", "imt", "in", "imtls", ":", "sl", "=", "imtls", "(", "imt", ")", "ok", "=", "(", "numpy", ".", "abs", "(", "mean", "[", "sl", "]", "-", "mean_ref", "[", "sl", "]", ")", "<", "nsigma", "*", "err", "[", "sl", "]", ")", ".", "all", "(", ")", "if", "not", "ok", ":", "md", "=", "(", "numpy", ".", "abs", "(", "mean", "[", "sl", "]", "-", "mean_ref", "[", "sl", "]", ")", ")", ".", "max", "(", ")", "plt", ".", "title", "(", "'point=%s, imt=%s, maxdiff=%.2e'", "%", "(", "lonlat", ",", "imt", ",", "md", ")", ")", "plt", ".", "loglog", "(", "imtls", "[", "imt", "]", ",", "mean_ref", "[", "sl", "]", "+", "std_ref", "[", "sl", "]", ",", "label", "=", "str", "(", "calc_ref", ")", ",", "color", "=", "'black'", ")", "plt", ".", "loglog", "(", "imtls", "[", "imt", "]", ",", "mean_ref", "[", "sl", "]", "-", "std_ref", "[", "sl", "]", ",", "color", "=", "'black'", ")", "plt", ".", "loglog", "(", "imtls", "[", "imt", "]", ",", "mean", "[", "sl", "]", "+", "std", "[", "sl", "]", ",", "label", "=", "str", "(", "calc", ")", ",", "color", "=", "'red'", ")", "plt", ".", "loglog", "(", "imtls", "[", "imt", "]", ",", "mean", "[", "sl", "]", "-", "std", "[", "sl", "]", ",", "color", "=", "'red'", ")", "plt", ".", "legend", "(", ")", "plt", ".", "show", "(", ")" ]
Compare the hazard curves coming from two different calculations.
[ "Compare", "the", "hazard", "curves", "coming", "from", "two", "different", "calculations", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/utils/compare_mean_curves.py#L27-L69
146
gem/oq-engine
openquake/hazardlib/gsim/chiou_youngs_2014.py
ChiouYoungs2014PEER._get_stddevs
def _get_stddevs(self, sites, rup, C, stddev_types, ln_y_ref, exp1, exp2): """ Returns the standard deviation, which is fixed at 0.65 for every site """ ret = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: # eq. 13 ret.append(0.65 * np.ones_like(sites.vs30)) return ret
python
def _get_stddevs(self, sites, rup, C, stddev_types, ln_y_ref, exp1, exp2): """ Returns the standard deviation, which is fixed at 0.65 for every site """ ret = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: # eq. 13 ret.append(0.65 * np.ones_like(sites.vs30)) return ret
[ "def", "_get_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "C", ",", "stddev_types", ",", "ln_y_ref", ",", "exp1", ",", "exp2", ")", ":", "ret", "=", "[", "]", "for", "stddev_type", "in", "stddev_types", ":", "assert", "stddev_type", "in", "self", ".", "DEFINED_FOR_STANDARD_DEVIATION_TYPES", "if", "stddev_type", "==", "const", ".", "StdDev", ".", "TOTAL", ":", "# eq. 13", "ret", ".", "append", "(", "0.65", "*", "np", ".", "ones_like", "(", "sites", ".", "vs30", ")", ")", "return", "ret" ]
Returns the standard deviation, which is fixed at 0.65 for every site
[ "Returns", "the", "standard", "deviation", "which", "is", "fixed", "at", "0", ".", "65", "for", "every", "site" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/chiou_youngs_2014.py#L313-L323
147
gem/oq-engine
openquake/risklib/scientific.py
build_imls
def build_imls(ff, continuous_fragility_discretization, steps_per_interval=0): """ Build intensity measure levels from a fragility function. If the function is continuous, they are produced simply as a linear space between minIML and maxIML. If the function is discrete, they are generated with a complex logic depending on the noDamageLimit and the parameter steps per interval. :param ff: a fragility function object :param continuous_fragility_discretization: .ini file parameter :param steps_per_interval: .ini file parameter :returns: generated imls """ if ff.format == 'discrete': imls = ff.imls if ff.nodamage and ff.nodamage < imls[0]: imls = [ff.nodamage] + imls if steps_per_interval > 1: gen_imls = fine_graining(imls, steps_per_interval) else: gen_imls = imls else: # continuous gen_imls = numpy.linspace(ff.minIML, ff.maxIML, continuous_fragility_discretization) return gen_imls
python
def build_imls(ff, continuous_fragility_discretization, steps_per_interval=0): """ Build intensity measure levels from a fragility function. If the function is continuous, they are produced simply as a linear space between minIML and maxIML. If the function is discrete, they are generated with a complex logic depending on the noDamageLimit and the parameter steps per interval. :param ff: a fragility function object :param continuous_fragility_discretization: .ini file parameter :param steps_per_interval: .ini file parameter :returns: generated imls """ if ff.format == 'discrete': imls = ff.imls if ff.nodamage and ff.nodamage < imls[0]: imls = [ff.nodamage] + imls if steps_per_interval > 1: gen_imls = fine_graining(imls, steps_per_interval) else: gen_imls = imls else: # continuous gen_imls = numpy.linspace(ff.minIML, ff.maxIML, continuous_fragility_discretization) return gen_imls
[ "def", "build_imls", "(", "ff", ",", "continuous_fragility_discretization", ",", "steps_per_interval", "=", "0", ")", ":", "if", "ff", ".", "format", "==", "'discrete'", ":", "imls", "=", "ff", ".", "imls", "if", "ff", ".", "nodamage", "and", "ff", ".", "nodamage", "<", "imls", "[", "0", "]", ":", "imls", "=", "[", "ff", ".", "nodamage", "]", "+", "imls", "if", "steps_per_interval", ">", "1", ":", "gen_imls", "=", "fine_graining", "(", "imls", ",", "steps_per_interval", ")", "else", ":", "gen_imls", "=", "imls", "else", ":", "# continuous", "gen_imls", "=", "numpy", ".", "linspace", "(", "ff", ".", "minIML", ",", "ff", ".", "maxIML", ",", "continuous_fragility_discretization", ")", "return", "gen_imls" ]
Build intensity measure levels from a fragility function. If the function is continuous, they are produced simply as a linear space between minIML and maxIML. If the function is discrete, they are generated with a complex logic depending on the noDamageLimit and the parameter steps per interval. :param ff: a fragility function object :param continuous_fragility_discretization: .ini file parameter :param steps_per_interval: .ini file parameter :returns: generated imls
[ "Build", "intensity", "measure", "levels", "from", "a", "fragility", "function", ".", "If", "the", "function", "is", "continuous", "they", "are", "produced", "simply", "as", "a", "linear", "space", "between", "minIML", "and", "maxIML", ".", "If", "the", "function", "is", "discrete", "they", "are", "generated", "with", "a", "complex", "logic", "depending", "on", "the", "noDamageLimit", "and", "the", "parameter", "steps", "per", "interval", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L665-L690
148
gem/oq-engine
openquake/risklib/scientific.py
insured_loss_curve
def insured_loss_curve(curve, deductible, insured_limit): """ Compute an insured loss ratio curve given a loss ratio curve :param curve: an array 2 x R (where R is the curve resolution) :param float deductible: the deductible limit in fraction form :param float insured_limit: the insured limit in fraction form >>> losses = numpy.array([3, 20, 101]) >>> poes = numpy.array([0.9, 0.5, 0.1]) >>> insured_loss_curve(numpy.array([losses, poes]), 5, 100) array([[ 3. , 20. ], [ 0.85294118, 0.5 ]]) """ losses, poes = curve[:, curve[0] <= insured_limit] limit_poe = interpolate.interp1d( *curve, bounds_error=False, fill_value=1)(deductible) return numpy.array([ losses, numpy.piecewise(poes, [poes > limit_poe], [limit_poe, lambda x: x])])
python
def insured_loss_curve(curve, deductible, insured_limit): """ Compute an insured loss ratio curve given a loss ratio curve :param curve: an array 2 x R (where R is the curve resolution) :param float deductible: the deductible limit in fraction form :param float insured_limit: the insured limit in fraction form >>> losses = numpy.array([3, 20, 101]) >>> poes = numpy.array([0.9, 0.5, 0.1]) >>> insured_loss_curve(numpy.array([losses, poes]), 5, 100) array([[ 3. , 20. ], [ 0.85294118, 0.5 ]]) """ losses, poes = curve[:, curve[0] <= insured_limit] limit_poe = interpolate.interp1d( *curve, bounds_error=False, fill_value=1)(deductible) return numpy.array([ losses, numpy.piecewise(poes, [poes > limit_poe], [limit_poe, lambda x: x])])
[ "def", "insured_loss_curve", "(", "curve", ",", "deductible", ",", "insured_limit", ")", ":", "losses", ",", "poes", "=", "curve", "[", ":", ",", "curve", "[", "0", "]", "<=", "insured_limit", "]", "limit_poe", "=", "interpolate", ".", "interp1d", "(", "*", "curve", ",", "bounds_error", "=", "False", ",", "fill_value", "=", "1", ")", "(", "deductible", ")", "return", "numpy", ".", "array", "(", "[", "losses", ",", "numpy", ".", "piecewise", "(", "poes", ",", "[", "poes", ">", "limit_poe", "]", ",", "[", "limit_poe", ",", "lambda", "x", ":", "x", "]", ")", "]", ")" ]
Compute an insured loss ratio curve given a loss ratio curve :param curve: an array 2 x R (where R is the curve resolution) :param float deductible: the deductible limit in fraction form :param float insured_limit: the insured limit in fraction form >>> losses = numpy.array([3, 20, 101]) >>> poes = numpy.array([0.9, 0.5, 0.1]) >>> insured_loss_curve(numpy.array([losses, poes]), 5, 100) array([[ 3. , 20. ], [ 0.85294118, 0.5 ]])
[ "Compute", "an", "insured", "loss", "ratio", "curve", "given", "a", "loss", "ratio", "curve" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1097-L1116
149
gem/oq-engine
openquake/risklib/scientific.py
bcr
def bcr(eal_original, eal_retrofitted, interest_rate, asset_life_expectancy, asset_value, retrofitting_cost): """ Compute the Benefit-Cost Ratio. BCR = (EALo - EALr)(1-exp(-r*t))/(r*C) Where: * BCR -- Benefit cost ratio * EALo -- Expected annual loss for original asset * EALr -- Expected annual loss for retrofitted asset * r -- Interest rate * t -- Life expectancy of the asset * C -- Retrofitting cost """ return ((eal_original - eal_retrofitted) * asset_value * (1 - numpy.exp(- interest_rate * asset_life_expectancy)) / (interest_rate * retrofitting_cost))
python
def bcr(eal_original, eal_retrofitted, interest_rate, asset_life_expectancy, asset_value, retrofitting_cost): """ Compute the Benefit-Cost Ratio. BCR = (EALo - EALr)(1-exp(-r*t))/(r*C) Where: * BCR -- Benefit cost ratio * EALo -- Expected annual loss for original asset * EALr -- Expected annual loss for retrofitted asset * r -- Interest rate * t -- Life expectancy of the asset * C -- Retrofitting cost """ return ((eal_original - eal_retrofitted) * asset_value * (1 - numpy.exp(- interest_rate * asset_life_expectancy)) / (interest_rate * retrofitting_cost))
[ "def", "bcr", "(", "eal_original", ",", "eal_retrofitted", ",", "interest_rate", ",", "asset_life_expectancy", ",", "asset_value", ",", "retrofitting_cost", ")", ":", "return", "(", "(", "eal_original", "-", "eal_retrofitted", ")", "*", "asset_value", "*", "(", "1", "-", "numpy", ".", "exp", "(", "-", "interest_rate", "*", "asset_life_expectancy", ")", ")", "/", "(", "interest_rate", "*", "retrofitting_cost", ")", ")" ]
Compute the Benefit-Cost Ratio. BCR = (EALo - EALr)(1-exp(-r*t))/(r*C) Where: * BCR -- Benefit cost ratio * EALo -- Expected annual loss for original asset * EALr -- Expected annual loss for retrofitted asset * r -- Interest rate * t -- Life expectancy of the asset * C -- Retrofitting cost
[ "Compute", "the", "Benefit", "-", "Cost", "Ratio", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1124-L1142
150
gem/oq-engine
openquake/risklib/scientific.py
pairwise_mean
def pairwise_mean(values): "Averages between a value and the next value in a sequence" return numpy.array([numpy.mean(pair) for pair in pairwise(values)])
python
def pairwise_mean(values): "Averages between a value and the next value in a sequence" return numpy.array([numpy.mean(pair) for pair in pairwise(values)])
[ "def", "pairwise_mean", "(", "values", ")", ":", "return", "numpy", ".", "array", "(", "[", "numpy", ".", "mean", "(", "pair", ")", "for", "pair", "in", "pairwise", "(", "values", ")", "]", ")" ]
Averages between a value and the next value in a sequence
[ "Averages", "between", "a", "value", "and", "the", "next", "value", "in", "a", "sequence" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1147-L1149
151
gem/oq-engine
openquake/risklib/scientific.py
pairwise_diff
def pairwise_diff(values): "Differences between a value and the next value in a sequence" return numpy.array([x - y for x, y in pairwise(values)])
python
def pairwise_diff(values): "Differences between a value and the next value in a sequence" return numpy.array([x - y for x, y in pairwise(values)])
[ "def", "pairwise_diff", "(", "values", ")", ":", "return", "numpy", ".", "array", "(", "[", "x", "-", "y", "for", "x", ",", "y", "in", "pairwise", "(", "values", ")", "]", ")" ]
Differences between a value and the next value in a sequence
[ "Differences", "between", "a", "value", "and", "the", "next", "value", "in", "a", "sequence" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1152-L1154
152
gem/oq-engine
openquake/risklib/scientific.py
mean_std
def mean_std(fractions): """ Given an N x M matrix, returns mean and std computed on the rows, i.e. two M-dimensional vectors. """ n = fractions.shape[0] if n == 1: # avoid warnings when computing the stddev return fractions[0], numpy.ones_like(fractions[0]) * numpy.nan return numpy.mean(fractions, axis=0), numpy.std(fractions, axis=0, ddof=1)
python
def mean_std(fractions): """ Given an N x M matrix, returns mean and std computed on the rows, i.e. two M-dimensional vectors. """ n = fractions.shape[0] if n == 1: # avoid warnings when computing the stddev return fractions[0], numpy.ones_like(fractions[0]) * numpy.nan return numpy.mean(fractions, axis=0), numpy.std(fractions, axis=0, ddof=1)
[ "def", "mean_std", "(", "fractions", ")", ":", "n", "=", "fractions", ".", "shape", "[", "0", "]", "if", "n", "==", "1", ":", "# avoid warnings when computing the stddev", "return", "fractions", "[", "0", "]", ",", "numpy", ".", "ones_like", "(", "fractions", "[", "0", "]", ")", "*", "numpy", ".", "nan", "return", "numpy", ".", "mean", "(", "fractions", ",", "axis", "=", "0", ")", ",", "numpy", ".", "std", "(", "fractions", ",", "axis", "=", "0", ",", "ddof", "=", "1", ")" ]
Given an N x M matrix, returns mean and std computed on the rows, i.e. two M-dimensional vectors.
[ "Given", "an", "N", "x", "M", "matrix", "returns", "mean", "and", "std", "computed", "on", "the", "rows", "i", ".", "e", ".", "two", "M", "-", "dimensional", "vectors", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1157-L1165
153
gem/oq-engine
openquake/risklib/scientific.py
broadcast
def broadcast(func, composite_array, *args): """ Broadcast an array function over a composite array """ dic = {} dtypes = [] for name in composite_array.dtype.names: dic[name] = func(composite_array[name], *args) dtypes.append((name, dic[name].dtype)) res = numpy.zeros(dic[name].shape, numpy.dtype(dtypes)) for name in dic: res[name] = dic[name] return res
python
def broadcast(func, composite_array, *args): """ Broadcast an array function over a composite array """ dic = {} dtypes = [] for name in composite_array.dtype.names: dic[name] = func(composite_array[name], *args) dtypes.append((name, dic[name].dtype)) res = numpy.zeros(dic[name].shape, numpy.dtype(dtypes)) for name in dic: res[name] = dic[name] return res
[ "def", "broadcast", "(", "func", ",", "composite_array", ",", "*", "args", ")", ":", "dic", "=", "{", "}", "dtypes", "=", "[", "]", "for", "name", "in", "composite_array", ".", "dtype", ".", "names", ":", "dic", "[", "name", "]", "=", "func", "(", "composite_array", "[", "name", "]", ",", "*", "args", ")", "dtypes", ".", "append", "(", "(", "name", ",", "dic", "[", "name", "]", ".", "dtype", ")", ")", "res", "=", "numpy", ".", "zeros", "(", "dic", "[", "name", "]", ".", "shape", ",", "numpy", ".", "dtype", "(", "dtypes", ")", ")", "for", "name", "in", "dic", ":", "res", "[", "name", "]", "=", "dic", "[", "name", "]", "return", "res" ]
Broadcast an array function over a composite array
[ "Broadcast", "an", "array", "function", "over", "a", "composite", "array" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1184-L1196
154
gem/oq-engine
openquake/risklib/scientific.py
average_loss
def average_loss(lc): """ Given a loss curve array with `poe` and `loss` fields, computes the average loss on a period of time. :note: As the loss curve is supposed to be piecewise linear as it is a result of a linear interpolation, we compute an exact integral by using the trapeizodal rule with the width given by the loss bin width. """ losses, poes = (lc['loss'], lc['poe']) if lc.dtype.names else lc return -pairwise_diff(losses) @ pairwise_mean(poes)
python
def average_loss(lc): """ Given a loss curve array with `poe` and `loss` fields, computes the average loss on a period of time. :note: As the loss curve is supposed to be piecewise linear as it is a result of a linear interpolation, we compute an exact integral by using the trapeizodal rule with the width given by the loss bin width. """ losses, poes = (lc['loss'], lc['poe']) if lc.dtype.names else lc return -pairwise_diff(losses) @ pairwise_mean(poes)
[ "def", "average_loss", "(", "lc", ")", ":", "losses", ",", "poes", "=", "(", "lc", "[", "'loss'", "]", ",", "lc", "[", "'poe'", "]", ")", "if", "lc", ".", "dtype", ".", "names", "else", "lc", "return", "-", "pairwise_diff", "(", "losses", ")", "@", "pairwise_mean", "(", "poes", ")" ]
Given a loss curve array with `poe` and `loss` fields, computes the average loss on a period of time. :note: As the loss curve is supposed to be piecewise linear as it is a result of a linear interpolation, we compute an exact integral by using the trapeizodal rule with the width given by the loss bin width.
[ "Given", "a", "loss", "curve", "array", "with", "poe", "and", "loss", "fields", "computes", "the", "average", "loss", "on", "a", "period", "of", "time", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1200-L1211
155
gem/oq-engine
openquake/risklib/scientific.py
normalize_curves_eb
def normalize_curves_eb(curves): """ A more sophisticated version of normalize_curves, used in the event based calculator. :param curves: a list of pairs (losses, poes) :returns: first losses, all_poes """ # we assume non-decreasing losses, so losses[-1] is the maximum loss non_zero_curves = [(losses, poes) for losses, poes in curves if losses[-1] > 0] if not non_zero_curves: # no damage. all zero curves return curves[0][0], numpy.array([poes for _losses, poes in curves]) else: # standard case max_losses = [losses[-1] for losses, _poes in non_zero_curves] reference_curve = non_zero_curves[numpy.argmax(max_losses)] loss_ratios = reference_curve[0] curves_poes = [interpolate.interp1d( losses, poes, bounds_error=False, fill_value=0)(loss_ratios) for losses, poes in curves] # fix degenerated case with flat curve for cp in curves_poes: if numpy.isnan(cp[0]): cp[0] = 0 return loss_ratios, numpy.array(curves_poes)
python
def normalize_curves_eb(curves): """ A more sophisticated version of normalize_curves, used in the event based calculator. :param curves: a list of pairs (losses, poes) :returns: first losses, all_poes """ # we assume non-decreasing losses, so losses[-1] is the maximum loss non_zero_curves = [(losses, poes) for losses, poes in curves if losses[-1] > 0] if not non_zero_curves: # no damage. all zero curves return curves[0][0], numpy.array([poes for _losses, poes in curves]) else: # standard case max_losses = [losses[-1] for losses, _poes in non_zero_curves] reference_curve = non_zero_curves[numpy.argmax(max_losses)] loss_ratios = reference_curve[0] curves_poes = [interpolate.interp1d( losses, poes, bounds_error=False, fill_value=0)(loss_ratios) for losses, poes in curves] # fix degenerated case with flat curve for cp in curves_poes: if numpy.isnan(cp[0]): cp[0] = 0 return loss_ratios, numpy.array(curves_poes)
[ "def", "normalize_curves_eb", "(", "curves", ")", ":", "# we assume non-decreasing losses, so losses[-1] is the maximum loss", "non_zero_curves", "=", "[", "(", "losses", ",", "poes", ")", "for", "losses", ",", "poes", "in", "curves", "if", "losses", "[", "-", "1", "]", ">", "0", "]", "if", "not", "non_zero_curves", ":", "# no damage. all zero curves", "return", "curves", "[", "0", "]", "[", "0", "]", ",", "numpy", ".", "array", "(", "[", "poes", "for", "_losses", ",", "poes", "in", "curves", "]", ")", "else", ":", "# standard case", "max_losses", "=", "[", "losses", "[", "-", "1", "]", "for", "losses", ",", "_poes", "in", "non_zero_curves", "]", "reference_curve", "=", "non_zero_curves", "[", "numpy", ".", "argmax", "(", "max_losses", ")", "]", "loss_ratios", "=", "reference_curve", "[", "0", "]", "curves_poes", "=", "[", "interpolate", ".", "interp1d", "(", "losses", ",", "poes", ",", "bounds_error", "=", "False", ",", "fill_value", "=", "0", ")", "(", "loss_ratios", ")", "for", "losses", ",", "poes", "in", "curves", "]", "# fix degenerated case with flat curve", "for", "cp", "in", "curves_poes", ":", "if", "numpy", ".", "isnan", "(", "cp", "[", "0", "]", ")", ":", "cp", "[", "0", "]", "=", "0", "return", "loss_ratios", ",", "numpy", ".", "array", "(", "curves_poes", ")" ]
A more sophisticated version of normalize_curves, used in the event based calculator. :param curves: a list of pairs (losses, poes) :returns: first losses, all_poes
[ "A", "more", "sophisticated", "version", "of", "normalize_curves", "used", "in", "the", "event", "based", "calculator", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L1214-L1238
156
gem/oq-engine
openquake/risklib/scientific.py
VulnerabilityFunction.sample
def sample(self, means, covs, idxs, epsilons=None): """ Sample the epsilons and apply the corrections to the means. This method is called only if there are nonzero covs. :param means: array of E' loss ratios :param covs: array of E' floats :param idxs: array of E booleans with E >= E' :param epsilons: array of E floats (or None) :returns: array of E' loss ratios """ if epsilons is None: return means self.set_distribution(epsilons) res = self.distribution.sample(means, covs, means * covs, idxs) return res
python
def sample(self, means, covs, idxs, epsilons=None): """ Sample the epsilons and apply the corrections to the means. This method is called only if there are nonzero covs. :param means: array of E' loss ratios :param covs: array of E' floats :param idxs: array of E booleans with E >= E' :param epsilons: array of E floats (or None) :returns: array of E' loss ratios """ if epsilons is None: return means self.set_distribution(epsilons) res = self.distribution.sample(means, covs, means * covs, idxs) return res
[ "def", "sample", "(", "self", ",", "means", ",", "covs", ",", "idxs", ",", "epsilons", "=", "None", ")", ":", "if", "epsilons", "is", "None", ":", "return", "means", "self", ".", "set_distribution", "(", "epsilons", ")", "res", "=", "self", ".", "distribution", ".", "sample", "(", "means", ",", "covs", ",", "means", "*", "covs", ",", "idxs", ")", "return", "res" ]
Sample the epsilons and apply the corrections to the means. This method is called only if there are nonzero covs. :param means: array of E' loss ratios :param covs: array of E' floats :param idxs: array of E booleans with E >= E' :param epsilons: array of E floats (or None) :returns: array of E' loss ratios
[ "Sample", "the", "epsilons", "and", "apply", "the", "corrections", "to", "the", "means", ".", "This", "method", "is", "called", "only", "if", "there", "are", "nonzero", "covs", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L161-L181
157
gem/oq-engine
openquake/risklib/scientific.py
VulnerabilityFunction.mean_loss_ratios_with_steps
def mean_loss_ratios_with_steps(self, steps): """ Split the mean loss ratios, producing a new set of loss ratios. The new set of loss ratios always includes 0.0 and 1.0 :param int steps: the number of steps we make to go from one loss ratio to the next. For example, if we have [0.5, 0.7]:: steps = 1 produces [0.0, 0.5, 0.7, 1] steps = 2 produces [0.0, 0.25, 0.5, 0.6, 0.7, 0.85, 1] steps = 3 produces [0.0, 0.17, 0.33, 0.5, 0.57, 0.63, 0.7, 0.8, 0.9, 1] """ loss_ratios = self.mean_loss_ratios if min(loss_ratios) > 0.0: # prepend with a zero loss_ratios = numpy.concatenate([[0.0], loss_ratios]) if max(loss_ratios) < 1.0: # append a 1.0 loss_ratios = numpy.concatenate([loss_ratios, [1.0]]) return fine_graining(loss_ratios, steps)
python
def mean_loss_ratios_with_steps(self, steps): """ Split the mean loss ratios, producing a new set of loss ratios. The new set of loss ratios always includes 0.0 and 1.0 :param int steps: the number of steps we make to go from one loss ratio to the next. For example, if we have [0.5, 0.7]:: steps = 1 produces [0.0, 0.5, 0.7, 1] steps = 2 produces [0.0, 0.25, 0.5, 0.6, 0.7, 0.85, 1] steps = 3 produces [0.0, 0.17, 0.33, 0.5, 0.57, 0.63, 0.7, 0.8, 0.9, 1] """ loss_ratios = self.mean_loss_ratios if min(loss_ratios) > 0.0: # prepend with a zero loss_ratios = numpy.concatenate([[0.0], loss_ratios]) if max(loss_ratios) < 1.0: # append a 1.0 loss_ratios = numpy.concatenate([loss_ratios, [1.0]]) return fine_graining(loss_ratios, steps)
[ "def", "mean_loss_ratios_with_steps", "(", "self", ",", "steps", ")", ":", "loss_ratios", "=", "self", ".", "mean_loss_ratios", "if", "min", "(", "loss_ratios", ")", ">", "0.0", ":", "# prepend with a zero", "loss_ratios", "=", "numpy", ".", "concatenate", "(", "[", "[", "0.0", "]", ",", "loss_ratios", "]", ")", "if", "max", "(", "loss_ratios", ")", "<", "1.0", ":", "# append a 1.0", "loss_ratios", "=", "numpy", ".", "concatenate", "(", "[", "loss_ratios", ",", "[", "1.0", "]", "]", ")", "return", "fine_graining", "(", "loss_ratios", ",", "steps", ")" ]
Split the mean loss ratios, producing a new set of loss ratios. The new set of loss ratios always includes 0.0 and 1.0 :param int steps: the number of steps we make to go from one loss ratio to the next. For example, if we have [0.5, 0.7]:: steps = 1 produces [0.0, 0.5, 0.7, 1] steps = 2 produces [0.0, 0.25, 0.5, 0.6, 0.7, 0.85, 1] steps = 3 produces [0.0, 0.17, 0.33, 0.5, 0.57, 0.63, 0.7, 0.8, 0.9, 1]
[ "Split", "the", "mean", "loss", "ratios", "producing", "a", "new", "set", "of", "loss", "ratios", ".", "The", "new", "set", "of", "loss", "ratios", "always", "includes", "0", ".", "0", "and", "1", ".", "0" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L216-L240
158
gem/oq-engine
openquake/risklib/scientific.py
VulnerabilityFunctionWithPMF.sample
def sample(self, probs, _covs, idxs, epsilons): """ Sample the .loss_ratios with the given probabilities. :param probs: array of E' floats :param _covs: ignored, it is there only for API consistency :param idxs: array of E booleans with E >= E' :param epsilons: array of E floats :returns: array of E' probabilities """ self.set_distribution(epsilons) return self.distribution.sample(self.loss_ratios, probs)
python
def sample(self, probs, _covs, idxs, epsilons): """ Sample the .loss_ratios with the given probabilities. :param probs: array of E' floats :param _covs: ignored, it is there only for API consistency :param idxs: array of E booleans with E >= E' :param epsilons: array of E floats :returns: array of E' probabilities """ self.set_distribution(epsilons) return self.distribution.sample(self.loss_ratios, probs)
[ "def", "sample", "(", "self", ",", "probs", ",", "_covs", ",", "idxs", ",", "epsilons", ")", ":", "self", ".", "set_distribution", "(", "epsilons", ")", "return", "self", ".", "distribution", ".", "sample", "(", "self", ".", "loss_ratios", ",", "probs", ")" ]
Sample the .loss_ratios with the given probabilities. :param probs: array of E' floats :param _covs: ignored, it is there only for API consistency :param idxs: array of E booleans with E >= E' :param epsilons: array of E floats :returns: array of E' probabilities
[ "Sample", "the", ".", "loss_ratios", "with", "the", "given", "probabilities", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L406-L422
159
gem/oq-engine
openquake/risklib/scientific.py
FragilityModel.build
def build(self, continuous_fragility_discretization, steps_per_interval): """ Return a new FragilityModel instance, in which the values have been replaced with FragilityFunctionList instances. :param continuous_fragility_discretization: configuration parameter :param steps_per_interval: configuration parameter """ newfm = copy.copy(self) for key, ffl in self.items(): newfm[key] = ffl.build(self.limitStates, continuous_fragility_discretization, steps_per_interval) return newfm
python
def build(self, continuous_fragility_discretization, steps_per_interval): """ Return a new FragilityModel instance, in which the values have been replaced with FragilityFunctionList instances. :param continuous_fragility_discretization: configuration parameter :param steps_per_interval: configuration parameter """ newfm = copy.copy(self) for key, ffl in self.items(): newfm[key] = ffl.build(self.limitStates, continuous_fragility_discretization, steps_per_interval) return newfm
[ "def", "build", "(", "self", ",", "continuous_fragility_discretization", ",", "steps_per_interval", ")", ":", "newfm", "=", "copy", ".", "copy", "(", "self", ")", "for", "key", ",", "ffl", "in", "self", ".", "items", "(", ")", ":", "newfm", "[", "key", "]", "=", "ffl", ".", "build", "(", "self", ".", "limitStates", ",", "continuous_fragility_discretization", ",", "steps_per_interval", ")", "return", "newfm" ]
Return a new FragilityModel instance, in which the values have been replaced with FragilityFunctionList instances. :param continuous_fragility_discretization: configuration parameter :param steps_per_interval: configuration parameter
[ "Return", "a", "new", "FragilityModel", "instance", "in", "which", "the", "values", "have", "been", "replaced", "with", "FragilityFunctionList", "instances", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/risklib/scientific.py#L719-L734
160
gem/oq-engine
openquake/calculators/event_based.py
compute_gmfs
def compute_gmfs(rupgetter, srcfilter, param, monitor): """ Compute GMFs and optionally hazard curves """ getter = GmfGetter(rupgetter, srcfilter, param['oqparam']) with monitor('getting ruptures'): getter.init() return getter.compute_gmfs_curves(monitor)
python
def compute_gmfs(rupgetter, srcfilter, param, monitor): """ Compute GMFs and optionally hazard curves """ getter = GmfGetter(rupgetter, srcfilter, param['oqparam']) with monitor('getting ruptures'): getter.init() return getter.compute_gmfs_curves(monitor)
[ "def", "compute_gmfs", "(", "rupgetter", ",", "srcfilter", ",", "param", ",", "monitor", ")", ":", "getter", "=", "GmfGetter", "(", "rupgetter", ",", "srcfilter", ",", "param", "[", "'oqparam'", "]", ")", "with", "monitor", "(", "'getting ruptures'", ")", ":", "getter", ".", "init", "(", ")", "return", "getter", ".", "compute_gmfs_curves", "(", "monitor", ")" ]
Compute GMFs and optionally hazard curves
[ "Compute", "GMFs", "and", "optionally", "hazard", "curves" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/event_based.py#L82-L89
161
gem/oq-engine
openquake/hmtk/sources/complex_fault_source.py
mtkComplexFaultSource._get_minmax_edges
def _get_minmax_edges(self, edge): ''' Updates the upper and lower depths based on the input edges ''' if isinstance(edge, Line): # For instance of line class need to loop over values depth_vals = np.array([node.depth for node in edge.points]) else: depth_vals = edge[:, 2] temp_upper_depth = np.min(depth_vals) if not self.upper_depth: self.upper_depth = temp_upper_depth else: if temp_upper_depth < self.upper_depth: self.upper_depth = temp_upper_depth temp_lower_depth = np.max(depth_vals) if not self.lower_depth: self.lower_depth = temp_lower_depth else: if temp_lower_depth > self.lower_depth: self.lower_depth = temp_lower_depth
python
def _get_minmax_edges(self, edge): ''' Updates the upper and lower depths based on the input edges ''' if isinstance(edge, Line): # For instance of line class need to loop over values depth_vals = np.array([node.depth for node in edge.points]) else: depth_vals = edge[:, 2] temp_upper_depth = np.min(depth_vals) if not self.upper_depth: self.upper_depth = temp_upper_depth else: if temp_upper_depth < self.upper_depth: self.upper_depth = temp_upper_depth temp_lower_depth = np.max(depth_vals) if not self.lower_depth: self.lower_depth = temp_lower_depth else: if temp_lower_depth > self.lower_depth: self.lower_depth = temp_lower_depth
[ "def", "_get_minmax_edges", "(", "self", ",", "edge", ")", ":", "if", "isinstance", "(", "edge", ",", "Line", ")", ":", "# For instance of line class need to loop over values", "depth_vals", "=", "np", ".", "array", "(", "[", "node", ".", "depth", "for", "node", "in", "edge", ".", "points", "]", ")", "else", ":", "depth_vals", "=", "edge", "[", ":", ",", "2", "]", "temp_upper_depth", "=", "np", ".", "min", "(", "depth_vals", ")", "if", "not", "self", ".", "upper_depth", ":", "self", ".", "upper_depth", "=", "temp_upper_depth", "else", ":", "if", "temp_upper_depth", "<", "self", ".", "upper_depth", ":", "self", ".", "upper_depth", "=", "temp_upper_depth", "temp_lower_depth", "=", "np", ".", "max", "(", "depth_vals", ")", "if", "not", "self", ".", "lower_depth", ":", "self", ".", "lower_depth", "=", "temp_lower_depth", "else", ":", "if", "temp_lower_depth", ">", "self", ".", "lower_depth", ":", "self", ".", "lower_depth", "=", "temp_lower_depth" ]
Updates the upper and lower depths based on the input edges
[ "Updates", "the", "upper", "and", "lower", "depths", "based", "on", "the", "input", "edges" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/complex_fault_source.py#L153-L175
162
gem/oq-engine
openquake/hazardlib/gsim/kotha_2016.py
KothaEtAl2016._get_magnitude_term
def _get_magnitude_term(self, C, mag): """ Returns the magnitude scaling term - equation 3 """ if mag >= self.CONSTS["Mh"]: return C["e1"] + C["b3"] * (mag - self.CONSTS["Mh"]) else: return C["e1"] + (C["b1"] * (mag - self.CONSTS["Mh"])) +\ (C["b2"] * (mag - self.CONSTS["Mh"]) ** 2.)
python
def _get_magnitude_term(self, C, mag): """ Returns the magnitude scaling term - equation 3 """ if mag >= self.CONSTS["Mh"]: return C["e1"] + C["b3"] * (mag - self.CONSTS["Mh"]) else: return C["e1"] + (C["b1"] * (mag - self.CONSTS["Mh"])) +\ (C["b2"] * (mag - self.CONSTS["Mh"]) ** 2.)
[ "def", "_get_magnitude_term", "(", "self", ",", "C", ",", "mag", ")", ":", "if", "mag", ">=", "self", ".", "CONSTS", "[", "\"Mh\"", "]", ":", "return", "C", "[", "\"e1\"", "]", "+", "C", "[", "\"b3\"", "]", "*", "(", "mag", "-", "self", ".", "CONSTS", "[", "\"Mh\"", "]", ")", "else", ":", "return", "C", "[", "\"e1\"", "]", "+", "(", "C", "[", "\"b1\"", "]", "*", "(", "mag", "-", "self", ".", "CONSTS", "[", "\"Mh\"", "]", ")", ")", "+", "(", "C", "[", "\"b2\"", "]", "*", "(", "mag", "-", "self", ".", "CONSTS", "[", "\"Mh\"", "]", ")", "**", "2.", ")" ]
Returns the magnitude scaling term - equation 3
[ "Returns", "the", "magnitude", "scaling", "term", "-", "equation", "3" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kotha_2016.py#L101-L109
163
gem/oq-engine
openquake/hazardlib/gsim/kotha_2016.py
KothaEtAl2016._get_distance_term
def _get_distance_term(self, C, rjb, mag): """ Returns the general distance scaling term - equation 2 """ c_3 = self._get_anelastic_coeff(C) rval = np.sqrt(rjb ** 2. + C["h"] ** 2.) return (C["c1"] + C["c2"] * (mag - self.CONSTS["Mref"])) *\ np.log(rval / self.CONSTS["Rref"]) +\ c_3 * (rval - self.CONSTS["Rref"])
python
def _get_distance_term(self, C, rjb, mag): """ Returns the general distance scaling term - equation 2 """ c_3 = self._get_anelastic_coeff(C) rval = np.sqrt(rjb ** 2. + C["h"] ** 2.) return (C["c1"] + C["c2"] * (mag - self.CONSTS["Mref"])) *\ np.log(rval / self.CONSTS["Rref"]) +\ c_3 * (rval - self.CONSTS["Rref"])
[ "def", "_get_distance_term", "(", "self", ",", "C", ",", "rjb", ",", "mag", ")", ":", "c_3", "=", "self", ".", "_get_anelastic_coeff", "(", "C", ")", "rval", "=", "np", ".", "sqrt", "(", "rjb", "**", "2.", "+", "C", "[", "\"h\"", "]", "**", "2.", ")", "return", "(", "C", "[", "\"c1\"", "]", "+", "C", "[", "\"c2\"", "]", "*", "(", "mag", "-", "self", ".", "CONSTS", "[", "\"Mref\"", "]", ")", ")", "*", "np", ".", "log", "(", "rval", "/", "self", ".", "CONSTS", "[", "\"Rref\"", "]", ")", "+", "c_3", "*", "(", "rval", "-", "self", ".", "CONSTS", "[", "\"Rref\"", "]", ")" ]
Returns the general distance scaling term - equation 2
[ "Returns", "the", "general", "distance", "scaling", "term", "-", "equation", "2" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kotha_2016.py#L111-L119
164
gem/oq-engine
openquake/hazardlib/gsim/kotha_2016.py
KothaEtAl2016._get_site_term
def _get_site_term(self, C, vs30): """ Returns only a linear site amplification term """ dg1, dg2 = self._get_regional_site_term(C) return (C["g1"] + dg1) + (C["g2"] + dg2) * np.log(vs30)
python
def _get_site_term(self, C, vs30): """ Returns only a linear site amplification term """ dg1, dg2 = self._get_regional_site_term(C) return (C["g1"] + dg1) + (C["g2"] + dg2) * np.log(vs30)
[ "def", "_get_site_term", "(", "self", ",", "C", ",", "vs30", ")", ":", "dg1", ",", "dg2", "=", "self", ".", "_get_regional_site_term", "(", "C", ")", "return", "(", "C", "[", "\"g1\"", "]", "+", "dg1", ")", "+", "(", "C", "[", "\"g2\"", "]", "+", "dg2", ")", "*", "np", ".", "log", "(", "vs30", ")" ]
Returns only a linear site amplification term
[ "Returns", "only", "a", "linear", "site", "amplification", "term" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/kotha_2016.py#L128-L133
165
gem/oq-engine
openquake/hazardlib/gsim/tusa_langer_2016.py
TusaLanger2016RepiBA08SE._get_stddevs
def _get_stddevs(self, C, stddev_types, num_sites): """ Return standard deviations as defined in tables below """ assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types) stddevs = [np.zeros(num_sites) + C['SigmaTot'] for _ in stddev_types] return stddevs
python
def _get_stddevs(self, C, stddev_types, num_sites): """ Return standard deviations as defined in tables below """ assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types) stddevs = [np.zeros(num_sites) + C['SigmaTot'] for _ in stddev_types] return stddevs
[ "def", "_get_stddevs", "(", "self", ",", "C", ",", "stddev_types", ",", "num_sites", ")", ":", "assert", "all", "(", "stddev_type", "in", "self", ".", "DEFINED_FOR_STANDARD_DEVIATION_TYPES", "for", "stddev_type", "in", "stddev_types", ")", "stddevs", "=", "[", "np", ".", "zeros", "(", "num_sites", ")", "+", "C", "[", "'SigmaTot'", "]", "for", "_", "in", "stddev_types", "]", "return", "stddevs" ]
Return standard deviations as defined in tables below
[ "Return", "standard", "deviations", "as", "defined", "in", "tables", "below" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/tusa_langer_2016.py#L112-L119
166
gem/oq-engine
openquake/hazardlib/gsim/dowrickrhoades_2005.py
DowrickRhoades2005Asc._compute_mean
def _compute_mean(self, C, mag, rrup, hypo_depth, delta_R, delta_S, delta_V, delta_I, vs30): """ Compute MMI Intensity Value as per Equation in Table 5 and Table 7 pag 198. """ # mean is calculated for all the 4 classes using the same equation. # For DowrickRhoades2005SSlab, the coefficients which don't appear in # Model 3 equationare assigned to zero mean = (C['A1'] + (C['A2'] + C['A2R'] * delta_R + C['A2V'] * delta_V) * mag + (C['A3'] + C['A3S'] * delta_S + C['A3V'] * delta_V) * np.log10(np.power((rrup**3 + C['d']**3), 1.0 / 3.0)) + C['A4'] * hypo_depth + C['A5'] * delta_I) # Get S site class term S = self._get_site_class(vs30, mean) # Add S amplification term to mean value mean = mean + S return mean
python
def _compute_mean(self, C, mag, rrup, hypo_depth, delta_R, delta_S, delta_V, delta_I, vs30): """ Compute MMI Intensity Value as per Equation in Table 5 and Table 7 pag 198. """ # mean is calculated for all the 4 classes using the same equation. # For DowrickRhoades2005SSlab, the coefficients which don't appear in # Model 3 equationare assigned to zero mean = (C['A1'] + (C['A2'] + C['A2R'] * delta_R + C['A2V'] * delta_V) * mag + (C['A3'] + C['A3S'] * delta_S + C['A3V'] * delta_V) * np.log10(np.power((rrup**3 + C['d']**3), 1.0 / 3.0)) + C['A4'] * hypo_depth + C['A5'] * delta_I) # Get S site class term S = self._get_site_class(vs30, mean) # Add S amplification term to mean value mean = mean + S return mean
[ "def", "_compute_mean", "(", "self", ",", "C", ",", "mag", ",", "rrup", ",", "hypo_depth", ",", "delta_R", ",", "delta_S", ",", "delta_V", ",", "delta_I", ",", "vs30", ")", ":", "# mean is calculated for all the 4 classes using the same equation.", "# For DowrickRhoades2005SSlab, the coefficients which don't appear in", "# Model 3 equationare assigned to zero", "mean", "=", "(", "C", "[", "'A1'", "]", "+", "(", "C", "[", "'A2'", "]", "+", "C", "[", "'A2R'", "]", "*", "delta_R", "+", "C", "[", "'A2V'", "]", "*", "delta_V", ")", "*", "mag", "+", "(", "C", "[", "'A3'", "]", "+", "C", "[", "'A3S'", "]", "*", "delta_S", "+", "C", "[", "'A3V'", "]", "*", "delta_V", ")", "*", "np", ".", "log10", "(", "np", ".", "power", "(", "(", "rrup", "**", "3", "+", "C", "[", "'d'", "]", "**", "3", ")", ",", "1.0", "/", "3.0", ")", ")", "+", "C", "[", "'A4'", "]", "*", "hypo_depth", "+", "C", "[", "'A5'", "]", "*", "delta_I", ")", "# Get S site class term", "S", "=", "self", ".", "_get_site_class", "(", "vs30", ",", "mean", ")", "# Add S amplification term to mean value", "mean", "=", "mean", "+", "S", "return", "mean" ]
Compute MMI Intensity Value as per Equation in Table 5 and Table 7 pag 198.
[ "Compute", "MMI", "Intensity", "Value", "as", "per", "Equation", "in", "Table", "5", "and", "Table", "7", "pag", "198", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/dowrickrhoades_2005.py#L98-L120
167
gem/oq-engine
openquake/hazardlib/gsim/dowrickrhoades_2005.py
DowrickRhoades2005Asc._get_stddevs
def _get_stddevs(self, C, stddev_types, num_sites): """ Return total standard deviation as described in paragraph 5.2 pag 200. """ # interevent stddev sigma_inter = C['tau'] + np.zeros(num_sites) # intraevent std sigma_intra = C['sigma'] + np.zeros(num_sites) std = [] for stddev_type in stddev_types: if stddev_type == const.StdDev.TOTAL: # equation in section 5.2 page 200 std += [np.sqrt(sigma_intra**2 + sigma_inter**2)] elif stddev_type == const.StdDev.INTRA_EVENT: std.append(sigma_intra) elif stddev_type == const.StdDev.INTER_EVENT: std.append(sigma_inter) return std
python
def _get_stddevs(self, C, stddev_types, num_sites): """ Return total standard deviation as described in paragraph 5.2 pag 200. """ # interevent stddev sigma_inter = C['tau'] + np.zeros(num_sites) # intraevent std sigma_intra = C['sigma'] + np.zeros(num_sites) std = [] for stddev_type in stddev_types: if stddev_type == const.StdDev.TOTAL: # equation in section 5.2 page 200 std += [np.sqrt(sigma_intra**2 + sigma_inter**2)] elif stddev_type == const.StdDev.INTRA_EVENT: std.append(sigma_intra) elif stddev_type == const.StdDev.INTER_EVENT: std.append(sigma_inter) return std
[ "def", "_get_stddevs", "(", "self", ",", "C", ",", "stddev_types", ",", "num_sites", ")", ":", "# interevent stddev", "sigma_inter", "=", "C", "[", "'tau'", "]", "+", "np", ".", "zeros", "(", "num_sites", ")", "# intraevent std", "sigma_intra", "=", "C", "[", "'sigma'", "]", "+", "np", ".", "zeros", "(", "num_sites", ")", "std", "=", "[", "]", "for", "stddev_type", "in", "stddev_types", ":", "if", "stddev_type", "==", "const", ".", "StdDev", ".", "TOTAL", ":", "# equation in section 5.2 page 200", "std", "+=", "[", "np", ".", "sqrt", "(", "sigma_intra", "**", "2", "+", "sigma_inter", "**", "2", ")", "]", "elif", "stddev_type", "==", "const", ".", "StdDev", ".", "INTRA_EVENT", ":", "std", ".", "append", "(", "sigma_intra", ")", "elif", "stddev_type", "==", "const", ".", "StdDev", ".", "INTER_EVENT", ":", "std", ".", "append", "(", "sigma_inter", ")", "return", "std" ]
Return total standard deviation as described in paragraph 5.2 pag 200.
[ "Return", "total", "standard", "deviation", "as", "described", "in", "paragraph", "5", ".", "2", "pag", "200", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/dowrickrhoades_2005.py#L122-L143
168
gem/oq-engine
openquake/commands/plot_assets.py
plot_assets
def plot_assets(calc_id=-1, site_model=False): """ Plot the sites and the assets """ # NB: matplotlib is imported inside since it is a costly import import matplotlib.pyplot as p from openquake.hmtk.plotting.patch import PolygonPatch dstore = util.read(calc_id) try: region = dstore['oqparam'].region except KeyError: region = None sitecol = dstore['sitecol'] try: assetcol = dstore['assetcol'].value except AttributeError: assetcol = dstore['assetcol'].array fig = p.figure() ax = fig.add_subplot(111) if region: pp = PolygonPatch(shapely.wkt.loads(region), alpha=0.1) ax.add_patch(pp) ax.grid(True) if site_model and 'site_model' in dstore: sm = dstore['site_model'] sm_lons, sm_lats = sm['lon'], sm['lat'] if len(sm_lons) > 1 and cross_idl(*sm_lons): sm_lons %= 360 p.scatter(sm_lons, sm_lats, marker='.', color='orange') p.scatter(sitecol.complete.lons, sitecol.complete.lats, marker='.', color='gray') p.scatter(assetcol['lon'], assetcol['lat'], marker='.', color='green') p.scatter(sitecol.lons, sitecol.lats, marker='+', color='black') if 'discarded' in dstore: disc = numpy.unique(dstore['discarded'].value[['lon', 'lat']]) p.scatter(disc['lon'], disc['lat'], marker='x', color='red') p.show()
python
def plot_assets(calc_id=-1, site_model=False): """ Plot the sites and the assets """ # NB: matplotlib is imported inside since it is a costly import import matplotlib.pyplot as p from openquake.hmtk.plotting.patch import PolygonPatch dstore = util.read(calc_id) try: region = dstore['oqparam'].region except KeyError: region = None sitecol = dstore['sitecol'] try: assetcol = dstore['assetcol'].value except AttributeError: assetcol = dstore['assetcol'].array fig = p.figure() ax = fig.add_subplot(111) if region: pp = PolygonPatch(shapely.wkt.loads(region), alpha=0.1) ax.add_patch(pp) ax.grid(True) if site_model and 'site_model' in dstore: sm = dstore['site_model'] sm_lons, sm_lats = sm['lon'], sm['lat'] if len(sm_lons) > 1 and cross_idl(*sm_lons): sm_lons %= 360 p.scatter(sm_lons, sm_lats, marker='.', color='orange') p.scatter(sitecol.complete.lons, sitecol.complete.lats, marker='.', color='gray') p.scatter(assetcol['lon'], assetcol['lat'], marker='.', color='green') p.scatter(sitecol.lons, sitecol.lats, marker='+', color='black') if 'discarded' in dstore: disc = numpy.unique(dstore['discarded'].value[['lon', 'lat']]) p.scatter(disc['lon'], disc['lat'], marker='x', color='red') p.show()
[ "def", "plot_assets", "(", "calc_id", "=", "-", "1", ",", "site_model", "=", "False", ")", ":", "# NB: matplotlib is imported inside since it is a costly import", "import", "matplotlib", ".", "pyplot", "as", "p", "from", "openquake", ".", "hmtk", ".", "plotting", ".", "patch", "import", "PolygonPatch", "dstore", "=", "util", ".", "read", "(", "calc_id", ")", "try", ":", "region", "=", "dstore", "[", "'oqparam'", "]", ".", "region", "except", "KeyError", ":", "region", "=", "None", "sitecol", "=", "dstore", "[", "'sitecol'", "]", "try", ":", "assetcol", "=", "dstore", "[", "'assetcol'", "]", ".", "value", "except", "AttributeError", ":", "assetcol", "=", "dstore", "[", "'assetcol'", "]", ".", "array", "fig", "=", "p", ".", "figure", "(", ")", "ax", "=", "fig", ".", "add_subplot", "(", "111", ")", "if", "region", ":", "pp", "=", "PolygonPatch", "(", "shapely", ".", "wkt", ".", "loads", "(", "region", ")", ",", "alpha", "=", "0.1", ")", "ax", ".", "add_patch", "(", "pp", ")", "ax", ".", "grid", "(", "True", ")", "if", "site_model", "and", "'site_model'", "in", "dstore", ":", "sm", "=", "dstore", "[", "'site_model'", "]", "sm_lons", ",", "sm_lats", "=", "sm", "[", "'lon'", "]", ",", "sm", "[", "'lat'", "]", "if", "len", "(", "sm_lons", ")", ">", "1", "and", "cross_idl", "(", "*", "sm_lons", ")", ":", "sm_lons", "%=", "360", "p", ".", "scatter", "(", "sm_lons", ",", "sm_lats", ",", "marker", "=", "'.'", ",", "color", "=", "'orange'", ")", "p", ".", "scatter", "(", "sitecol", ".", "complete", ".", "lons", ",", "sitecol", ".", "complete", ".", "lats", ",", "marker", "=", "'.'", ",", "color", "=", "'gray'", ")", "p", ".", "scatter", "(", "assetcol", "[", "'lon'", "]", ",", "assetcol", "[", "'lat'", "]", ",", "marker", "=", "'.'", ",", "color", "=", "'green'", ")", "p", ".", "scatter", "(", "sitecol", ".", "lons", ",", "sitecol", ".", "lats", ",", "marker", "=", "'+'", ",", "color", "=", "'black'", ")", "if", "'discarded'", "in", "dstore", ":", "disc", "=", "numpy", ".", "unique", "(", "dstore", "[", "'discarded'", "]", ".", "value", "[", "[", "'lon'", ",", "'lat'", "]", "]", ")", "p", ".", "scatter", "(", "disc", "[", "'lon'", "]", ",", "disc", "[", "'lat'", "]", ",", "marker", "=", "'x'", ",", "color", "=", "'red'", ")", "p", ".", "show", "(", ")" ]
Plot the sites and the assets
[ "Plot", "the", "sites", "and", "the", "assets" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/plot_assets.py#L26-L62
169
gem/oq-engine
openquake/hmtk/seismicity/smoothing/smoothed_seismicity.py
_get_adjustment
def _get_adjustment(mag, year, mmin, completeness_year, t_f, mag_inc=0.1): ''' If the magnitude is greater than the minimum in the completeness table and the year is greater than the corresponding completeness year then return the Weichert factor :param float mag: Magnitude of an earthquake :param float year: Year of earthquake :param np.ndarray completeness_table: Completeness table :param float mag_inc: Magnitude increment :param float t_f: Weichert adjustment factor :returns: Weichert adjustment factor is event is in complete part of catalogue (0.0 otherwise) ''' if len(completeness_year) == 1: if (mag >= mmin) and (year >= completeness_year[0]): # No adjustment needed - event weight == 1 return 1.0 else: # Event should not be counted return False kval = int(((mag - mmin) / mag_inc)) + 1 if (kval >= 1) and (year >= completeness_year[kval - 1]): return t_f else: return False
python
def _get_adjustment(mag, year, mmin, completeness_year, t_f, mag_inc=0.1): ''' If the magnitude is greater than the minimum in the completeness table and the year is greater than the corresponding completeness year then return the Weichert factor :param float mag: Magnitude of an earthquake :param float year: Year of earthquake :param np.ndarray completeness_table: Completeness table :param float mag_inc: Magnitude increment :param float t_f: Weichert adjustment factor :returns: Weichert adjustment factor is event is in complete part of catalogue (0.0 otherwise) ''' if len(completeness_year) == 1: if (mag >= mmin) and (year >= completeness_year[0]): # No adjustment needed - event weight == 1 return 1.0 else: # Event should not be counted return False kval = int(((mag - mmin) / mag_inc)) + 1 if (kval >= 1) and (year >= completeness_year[kval - 1]): return t_f else: return False
[ "def", "_get_adjustment", "(", "mag", ",", "year", ",", "mmin", ",", "completeness_year", ",", "t_f", ",", "mag_inc", "=", "0.1", ")", ":", "if", "len", "(", "completeness_year", ")", "==", "1", ":", "if", "(", "mag", ">=", "mmin", ")", "and", "(", "year", ">=", "completeness_year", "[", "0", "]", ")", ":", "# No adjustment needed - event weight == 1", "return", "1.0", "else", ":", "# Event should not be counted", "return", "False", "kval", "=", "int", "(", "(", "(", "mag", "-", "mmin", ")", "/", "mag_inc", ")", ")", "+", "1", "if", "(", "kval", ">=", "1", ")", "and", "(", "year", ">=", "completeness_year", "[", "kval", "-", "1", "]", ")", ":", "return", "t_f", "else", ":", "return", "False" ]
If the magnitude is greater than the minimum in the completeness table and the year is greater than the corresponding completeness year then return the Weichert factor :param float mag: Magnitude of an earthquake :param float year: Year of earthquake :param np.ndarray completeness_table: Completeness table :param float mag_inc: Magnitude increment :param float t_f: Weichert adjustment factor :returns: Weichert adjustment factor is event is in complete part of catalogue (0.0 otherwise)
[ "If", "the", "magnitude", "is", "greater", "than", "the", "minimum", "in", "the", "completeness", "table", "and", "the", "year", "is", "greater", "than", "the", "corresponding", "completeness", "year", "then", "return", "the", "Weichert", "factor" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/smoothing/smoothed_seismicity.py#L129-L167
170
gem/oq-engine
openquake/hmtk/seismicity/smoothing/smoothed_seismicity.py
get_catalogue_bounding_polygon
def get_catalogue_bounding_polygon(catalogue): ''' Returns a polygon containing the bounding box of the catalogue ''' upper_lon = np.max(catalogue.data['longitude']) upper_lat = np.max(catalogue.data['latitude']) lower_lon = np.min(catalogue.data['longitude']) lower_lat = np.min(catalogue.data['latitude']) return Polygon([Point(lower_lon, upper_lat), Point(upper_lon, upper_lat), Point(upper_lon, lower_lat), Point(lower_lon, lower_lat)])
python
def get_catalogue_bounding_polygon(catalogue): ''' Returns a polygon containing the bounding box of the catalogue ''' upper_lon = np.max(catalogue.data['longitude']) upper_lat = np.max(catalogue.data['latitude']) lower_lon = np.min(catalogue.data['longitude']) lower_lat = np.min(catalogue.data['latitude']) return Polygon([Point(lower_lon, upper_lat), Point(upper_lon, upper_lat), Point(upper_lon, lower_lat), Point(lower_lon, lower_lat)])
[ "def", "get_catalogue_bounding_polygon", "(", "catalogue", ")", ":", "upper_lon", "=", "np", ".", "max", "(", "catalogue", ".", "data", "[", "'longitude'", "]", ")", "upper_lat", "=", "np", ".", "max", "(", "catalogue", ".", "data", "[", "'latitude'", "]", ")", "lower_lon", "=", "np", ".", "min", "(", "catalogue", ".", "data", "[", "'longitude'", "]", ")", "lower_lat", "=", "np", ".", "min", "(", "catalogue", ".", "data", "[", "'latitude'", "]", ")", "return", "Polygon", "(", "[", "Point", "(", "lower_lon", ",", "upper_lat", ")", ",", "Point", "(", "upper_lon", ",", "upper_lat", ")", ",", "Point", "(", "upper_lon", ",", "lower_lat", ")", ",", "Point", "(", "lower_lon", ",", "lower_lat", ")", "]", ")" ]
Returns a polygon containing the bounding box of the catalogue
[ "Returns", "a", "polygon", "containing", "the", "bounding", "box", "of", "the", "catalogue" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/smoothing/smoothed_seismicity.py#L170-L180
171
gem/oq-engine
openquake/hmtk/seismicity/smoothing/smoothed_seismicity.py
Grid.make_from_catalogue
def make_from_catalogue(cls, catalogue, spacing, dilate): ''' Defines the grid on the basis of the catalogue ''' new = cls() cat_bbox = get_catalogue_bounding_polygon(catalogue) if dilate > 0: cat_bbox = cat_bbox.dilate(dilate) # Define Grid spacing new.update({'xmin': np.min(cat_bbox.lons), 'xmax': np.max(cat_bbox.lons), 'xspc': spacing, 'ymin': np.min(cat_bbox.lats), 'ymax': np.max(cat_bbox.lats), 'yspc': spacing, 'zmin': 0., 'zmax': np.max(catalogue.data['depth']), 'zspc': np.max(catalogue.data['depth'])}) if new['zmin'] == new['zmax'] == new['zspc'] == 0: new['zmax'] = new['zspc'] = 1 return new
python
def make_from_catalogue(cls, catalogue, spacing, dilate): ''' Defines the grid on the basis of the catalogue ''' new = cls() cat_bbox = get_catalogue_bounding_polygon(catalogue) if dilate > 0: cat_bbox = cat_bbox.dilate(dilate) # Define Grid spacing new.update({'xmin': np.min(cat_bbox.lons), 'xmax': np.max(cat_bbox.lons), 'xspc': spacing, 'ymin': np.min(cat_bbox.lats), 'ymax': np.max(cat_bbox.lats), 'yspc': spacing, 'zmin': 0., 'zmax': np.max(catalogue.data['depth']), 'zspc': np.max(catalogue.data['depth'])}) if new['zmin'] == new['zmax'] == new['zspc'] == 0: new['zmax'] = new['zspc'] = 1 return new
[ "def", "make_from_catalogue", "(", "cls", ",", "catalogue", ",", "spacing", ",", "dilate", ")", ":", "new", "=", "cls", "(", ")", "cat_bbox", "=", "get_catalogue_bounding_polygon", "(", "catalogue", ")", "if", "dilate", ">", "0", ":", "cat_bbox", "=", "cat_bbox", ".", "dilate", "(", "dilate", ")", "# Define Grid spacing", "new", ".", "update", "(", "{", "'xmin'", ":", "np", ".", "min", "(", "cat_bbox", ".", "lons", ")", ",", "'xmax'", ":", "np", ".", "max", "(", "cat_bbox", ".", "lons", ")", ",", "'xspc'", ":", "spacing", ",", "'ymin'", ":", "np", ".", "min", "(", "cat_bbox", ".", "lats", ")", ",", "'ymax'", ":", "np", ".", "max", "(", "cat_bbox", ".", "lats", ")", ",", "'yspc'", ":", "spacing", ",", "'zmin'", ":", "0.", ",", "'zmax'", ":", "np", ".", "max", "(", "catalogue", ".", "data", "[", "'depth'", "]", ")", ",", "'zspc'", ":", "np", ".", "max", "(", "catalogue", ".", "data", "[", "'depth'", "]", ")", "}", ")", "if", "new", "[", "'zmin'", "]", "==", "new", "[", "'zmax'", "]", "==", "new", "[", "'zspc'", "]", "==", "0", ":", "new", "[", "'zmax'", "]", "=", "new", "[", "'zspc'", "]", "=", "1", "return", "new" ]
Defines the grid on the basis of the catalogue
[ "Defines", "the", "grid", "on", "the", "basis", "of", "the", "catalogue" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/smoothing/smoothed_seismicity.py#L81-L105
172
gem/oq-engine
openquake/hmtk/seismicity/smoothing/smoothed_seismicity.py
SmoothedSeismicity.write_to_csv
def write_to_csv(self, filename): ''' Exports to simple csv :param str filename: Path to file for export ''' fid = open(filename, 'wt') # Create header list header_info = ['Longitude', 'Latitude', 'Depth', 'Observed Count', 'Smoothed Rate', 'b-value'] writer = csv.DictWriter(fid, fieldnames=header_info) headers = dict((name0, name0) for name0 in header_info) # Write to file writer.writerow(headers) for row in self.data: # institute crude compression by omitting points with no seismicity # and taking advantage of the %g format if row[4] == 0: continue row_dict = {'Longitude': '%g' % row[0], 'Latitude': '%g' % row[1], 'Depth': '%g' % row[2], 'Observed Count': '%d' % row[3], 'Smoothed Rate': '%.6g' % row[4], 'b-value': '%g' % self.bval} writer.writerow(row_dict) fid.close()
python
def write_to_csv(self, filename): ''' Exports to simple csv :param str filename: Path to file for export ''' fid = open(filename, 'wt') # Create header list header_info = ['Longitude', 'Latitude', 'Depth', 'Observed Count', 'Smoothed Rate', 'b-value'] writer = csv.DictWriter(fid, fieldnames=header_info) headers = dict((name0, name0) for name0 in header_info) # Write to file writer.writerow(headers) for row in self.data: # institute crude compression by omitting points with no seismicity # and taking advantage of the %g format if row[4] == 0: continue row_dict = {'Longitude': '%g' % row[0], 'Latitude': '%g' % row[1], 'Depth': '%g' % row[2], 'Observed Count': '%d' % row[3], 'Smoothed Rate': '%.6g' % row[4], 'b-value': '%g' % self.bval} writer.writerow(row_dict) fid.close()
[ "def", "write_to_csv", "(", "self", ",", "filename", ")", ":", "fid", "=", "open", "(", "filename", ",", "'wt'", ")", "# Create header list", "header_info", "=", "[", "'Longitude'", ",", "'Latitude'", ",", "'Depth'", ",", "'Observed Count'", ",", "'Smoothed Rate'", ",", "'b-value'", "]", "writer", "=", "csv", ".", "DictWriter", "(", "fid", ",", "fieldnames", "=", "header_info", ")", "headers", "=", "dict", "(", "(", "name0", ",", "name0", ")", "for", "name0", "in", "header_info", ")", "# Write to file", "writer", ".", "writerow", "(", "headers", ")", "for", "row", "in", "self", ".", "data", ":", "# institute crude compression by omitting points with no seismicity", "# and taking advantage of the %g format", "if", "row", "[", "4", "]", "==", "0", ":", "continue", "row_dict", "=", "{", "'Longitude'", ":", "'%g'", "%", "row", "[", "0", "]", ",", "'Latitude'", ":", "'%g'", "%", "row", "[", "1", "]", ",", "'Depth'", ":", "'%g'", "%", "row", "[", "2", "]", ",", "'Observed Count'", ":", "'%d'", "%", "row", "[", "3", "]", ",", "'Smoothed Rate'", ":", "'%.6g'", "%", "row", "[", "4", "]", ",", "'b-value'", ":", "'%g'", "%", "self", ".", "bval", "}", "writer", ".", "writerow", "(", "row_dict", ")", "fid", ".", "close", "(", ")" ]
Exports to simple csv :param str filename: Path to file for export
[ "Exports", "to", "simple", "csv" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/smoothing/smoothed_seismicity.py#L491-L518
173
gem/oq-engine
openquake/commonlib/hazard_writers.py
_validate_hazard_metadata
def _validate_hazard_metadata(md): """ Validate metadata `dict` of attributes, which are more or less the same for hazard curves, hazard maps, and disaggregation histograms. :param dict md: `dict` which can contain the following keys: * statistics * gsimlt_path * smlt_path * imt * sa_period * sa_damping :raises: :exc:`ValueError` if the metadata is not valid. """ if (md.get('statistics') is not None and ( md.get('smlt_path') is not None or md.get('gsimlt_path') is not None)): raise ValueError('Cannot specify both `statistics` and logic tree ' 'paths') if md.get('statistics') is not None: # make sure only valid statistics types are specified if md.get('statistics') not in ('mean', 'max', 'quantile', 'std'): raise ValueError('`statistics` must be either `mean`, `max`, or ' '`quantile`') else: # must specify both logic tree paths if md.get('smlt_path') is None or md.get('gsimlt_path') is None: raise ValueError('Both logic tree paths are required for ' 'non-statistical results') if md.get('statistics') == 'quantile': if md.get('quantile_value') is None: raise ValueError('quantile stastics results require a quantile' ' value to be specified') if not md.get('statistics') == 'quantile': if md.get('quantile_value') is not None: raise ValueError('Quantile value must be specified with ' 'quantile statistics') if md.get('imt') == 'SA': if md.get('sa_period') is None: raise ValueError('`sa_period` is required for IMT == `SA`') if md.get('sa_damping') is None: raise ValueError('`sa_damping` is required for IMT == `SA`')
python
def _validate_hazard_metadata(md): """ Validate metadata `dict` of attributes, which are more or less the same for hazard curves, hazard maps, and disaggregation histograms. :param dict md: `dict` which can contain the following keys: * statistics * gsimlt_path * smlt_path * imt * sa_period * sa_damping :raises: :exc:`ValueError` if the metadata is not valid. """ if (md.get('statistics') is not None and ( md.get('smlt_path') is not None or md.get('gsimlt_path') is not None)): raise ValueError('Cannot specify both `statistics` and logic tree ' 'paths') if md.get('statistics') is not None: # make sure only valid statistics types are specified if md.get('statistics') not in ('mean', 'max', 'quantile', 'std'): raise ValueError('`statistics` must be either `mean`, `max`, or ' '`quantile`') else: # must specify both logic tree paths if md.get('smlt_path') is None or md.get('gsimlt_path') is None: raise ValueError('Both logic tree paths are required for ' 'non-statistical results') if md.get('statistics') == 'quantile': if md.get('quantile_value') is None: raise ValueError('quantile stastics results require a quantile' ' value to be specified') if not md.get('statistics') == 'quantile': if md.get('quantile_value') is not None: raise ValueError('Quantile value must be specified with ' 'quantile statistics') if md.get('imt') == 'SA': if md.get('sa_period') is None: raise ValueError('`sa_period` is required for IMT == `SA`') if md.get('sa_damping') is None: raise ValueError('`sa_damping` is required for IMT == `SA`')
[ "def", "_validate_hazard_metadata", "(", "md", ")", ":", "if", "(", "md", ".", "get", "(", "'statistics'", ")", "is", "not", "None", "and", "(", "md", ".", "get", "(", "'smlt_path'", ")", "is", "not", "None", "or", "md", ".", "get", "(", "'gsimlt_path'", ")", "is", "not", "None", ")", ")", ":", "raise", "ValueError", "(", "'Cannot specify both `statistics` and logic tree '", "'paths'", ")", "if", "md", ".", "get", "(", "'statistics'", ")", "is", "not", "None", ":", "# make sure only valid statistics types are specified", "if", "md", ".", "get", "(", "'statistics'", ")", "not", "in", "(", "'mean'", ",", "'max'", ",", "'quantile'", ",", "'std'", ")", ":", "raise", "ValueError", "(", "'`statistics` must be either `mean`, `max`, or '", "'`quantile`'", ")", "else", ":", "# must specify both logic tree paths", "if", "md", ".", "get", "(", "'smlt_path'", ")", "is", "None", "or", "md", ".", "get", "(", "'gsimlt_path'", ")", "is", "None", ":", "raise", "ValueError", "(", "'Both logic tree paths are required for '", "'non-statistical results'", ")", "if", "md", ".", "get", "(", "'statistics'", ")", "==", "'quantile'", ":", "if", "md", ".", "get", "(", "'quantile_value'", ")", "is", "None", ":", "raise", "ValueError", "(", "'quantile stastics results require a quantile'", "' value to be specified'", ")", "if", "not", "md", ".", "get", "(", "'statistics'", ")", "==", "'quantile'", ":", "if", "md", ".", "get", "(", "'quantile_value'", ")", "is", "not", "None", ":", "raise", "ValueError", "(", "'Quantile value must be specified with '", "'quantile statistics'", ")", "if", "md", ".", "get", "(", "'imt'", ")", "==", "'SA'", ":", "if", "md", ".", "get", "(", "'sa_period'", ")", "is", "None", ":", "raise", "ValueError", "(", "'`sa_period` is required for IMT == `SA`'", ")", "if", "md", ".", "get", "(", "'sa_damping'", ")", "is", "None", ":", "raise", "ValueError", "(", "'`sa_damping` is required for IMT == `SA`'", ")" ]
Validate metadata `dict` of attributes, which are more or less the same for hazard curves, hazard maps, and disaggregation histograms. :param dict md: `dict` which can contain the following keys: * statistics * gsimlt_path * smlt_path * imt * sa_period * sa_damping :raises: :exc:`ValueError` if the metadata is not valid.
[ "Validate", "metadata", "dict", "of", "attributes", "which", "are", "more", "or", "less", "the", "same", "for", "hazard", "curves", "hazard", "maps", "and", "disaggregation", "histograms", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/hazard_writers.py#L54-L103
174
gem/oq-engine
openquake/commonlib/hazard_writers.py
_set_metadata
def _set_metadata(element, metadata, attr_map, transform=str): """ Set metadata attributes on a given ``element``. :param element: :class:`xml.etree.ElementTree.Element` instance :param metadata: Dictionary of metadata items containing attribute data for ``element``. :param attr_map: Dictionary mapping of metadata key->attribute name. :param transform: A function accepting and returning a single value to be applied to each attribute value. Defaults to `str`. """ for kw, attr in attr_map.items(): value = metadata.get(kw) if value is not None: element.set(attr, transform(value))
python
def _set_metadata(element, metadata, attr_map, transform=str): """ Set metadata attributes on a given ``element``. :param element: :class:`xml.etree.ElementTree.Element` instance :param metadata: Dictionary of metadata items containing attribute data for ``element``. :param attr_map: Dictionary mapping of metadata key->attribute name. :param transform: A function accepting and returning a single value to be applied to each attribute value. Defaults to `str`. """ for kw, attr in attr_map.items(): value = metadata.get(kw) if value is not None: element.set(attr, transform(value))
[ "def", "_set_metadata", "(", "element", ",", "metadata", ",", "attr_map", ",", "transform", "=", "str", ")", ":", "for", "kw", ",", "attr", "in", "attr_map", ".", "items", "(", ")", ":", "value", "=", "metadata", ".", "get", "(", "kw", ")", "if", "value", "is", "not", "None", ":", "element", ".", "set", "(", "attr", ",", "transform", "(", "value", ")", ")" ]
Set metadata attributes on a given ``element``. :param element: :class:`xml.etree.ElementTree.Element` instance :param metadata: Dictionary of metadata items containing attribute data for ``element``. :param attr_map: Dictionary mapping of metadata key->attribute name. :param transform: A function accepting and returning a single value to be applied to each attribute value. Defaults to `str`.
[ "Set", "metadata", "attributes", "on", "a", "given", "element", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/hazard_writers.py#L106-L123
175
gem/oq-engine
openquake/commonlib/hazard_writers.py
HazardCurveXMLWriter.serialize
def serialize(self, data): """ Write a sequence of hazard curves to the specified file. :param data: Iterable of hazard curve data. Each datum must be an object with the following attributes: * poes: A list of probability of exceedence values (floats). * location: An object representing the location of the curve; must have `x` and `y` to represent lon and lat, respectively. """ with open(self.dest, 'wb') as fh: root = et.Element('nrml') self.add_hazard_curves(root, self.metadata, data) nrml.write(list(root), fh)
python
def serialize(self, data): """ Write a sequence of hazard curves to the specified file. :param data: Iterable of hazard curve data. Each datum must be an object with the following attributes: * poes: A list of probability of exceedence values (floats). * location: An object representing the location of the curve; must have `x` and `y` to represent lon and lat, respectively. """ with open(self.dest, 'wb') as fh: root = et.Element('nrml') self.add_hazard_curves(root, self.metadata, data) nrml.write(list(root), fh)
[ "def", "serialize", "(", "self", ",", "data", ")", ":", "with", "open", "(", "self", ".", "dest", ",", "'wb'", ")", "as", "fh", ":", "root", "=", "et", ".", "Element", "(", "'nrml'", ")", "self", ".", "add_hazard_curves", "(", "root", ",", "self", ".", "metadata", ",", "data", ")", "nrml", ".", "write", "(", "list", "(", "root", ")", ",", "fh", ")" ]
Write a sequence of hazard curves to the specified file. :param data: Iterable of hazard curve data. Each datum must be an object with the following attributes: * poes: A list of probability of exceedence values (floats). * location: An object representing the location of the curve; must have `x` and `y` to represent lon and lat, respectively.
[ "Write", "a", "sequence", "of", "hazard", "curves", "to", "the", "specified", "file", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/hazard_writers.py#L177-L192
176
gem/oq-engine
openquake/commonlib/hazard_writers.py
HazardCurveXMLWriter.add_hazard_curves
def add_hazard_curves(self, root, metadata, data): """ Add hazard curves stored into `data` as child of the `root` element with `metadata`. See the documentation of the method `serialize` and the constructor for a description of `data` and `metadata`, respectively. """ hazard_curves = et.SubElement(root, 'hazardCurves') _set_metadata(hazard_curves, metadata, _ATTR_MAP) imls_elem = et.SubElement(hazard_curves, 'IMLs') imls_elem.text = ' '.join(map(scientificformat, metadata['imls'])) gml_ns = nrml.SERIALIZE_NS_MAP['gml'] for hc in data: hc_elem = et.SubElement(hazard_curves, 'hazardCurve') gml_point = et.SubElement(hc_elem, '{%s}Point' % gml_ns) gml_pos = et.SubElement(gml_point, '{%s}pos' % gml_ns) gml_pos.text = '%s %s' % (hc.location.x, hc.location.y) poes_elem = et.SubElement(hc_elem, 'poEs') poes_elem.text = ' '.join(map(scientificformat, hc.poes))
python
def add_hazard_curves(self, root, metadata, data): """ Add hazard curves stored into `data` as child of the `root` element with `metadata`. See the documentation of the method `serialize` and the constructor for a description of `data` and `metadata`, respectively. """ hazard_curves = et.SubElement(root, 'hazardCurves') _set_metadata(hazard_curves, metadata, _ATTR_MAP) imls_elem = et.SubElement(hazard_curves, 'IMLs') imls_elem.text = ' '.join(map(scientificformat, metadata['imls'])) gml_ns = nrml.SERIALIZE_NS_MAP['gml'] for hc in data: hc_elem = et.SubElement(hazard_curves, 'hazardCurve') gml_point = et.SubElement(hc_elem, '{%s}Point' % gml_ns) gml_pos = et.SubElement(gml_point, '{%s}pos' % gml_ns) gml_pos.text = '%s %s' % (hc.location.x, hc.location.y) poes_elem = et.SubElement(hc_elem, 'poEs') poes_elem.text = ' '.join(map(scientificformat, hc.poes))
[ "def", "add_hazard_curves", "(", "self", ",", "root", ",", "metadata", ",", "data", ")", ":", "hazard_curves", "=", "et", ".", "SubElement", "(", "root", ",", "'hazardCurves'", ")", "_set_metadata", "(", "hazard_curves", ",", "metadata", ",", "_ATTR_MAP", ")", "imls_elem", "=", "et", ".", "SubElement", "(", "hazard_curves", ",", "'IMLs'", ")", "imls_elem", ".", "text", "=", "' '", ".", "join", "(", "map", "(", "scientificformat", ",", "metadata", "[", "'imls'", "]", ")", ")", "gml_ns", "=", "nrml", ".", "SERIALIZE_NS_MAP", "[", "'gml'", "]", "for", "hc", "in", "data", ":", "hc_elem", "=", "et", ".", "SubElement", "(", "hazard_curves", ",", "'hazardCurve'", ")", "gml_point", "=", "et", ".", "SubElement", "(", "hc_elem", ",", "'{%s}Point'", "%", "gml_ns", ")", "gml_pos", "=", "et", ".", "SubElement", "(", "gml_point", ",", "'{%s}pos'", "%", "gml_ns", ")", "gml_pos", ".", "text", "=", "'%s %s'", "%", "(", "hc", ".", "location", ".", "x", ",", "hc", ".", "location", ".", "y", ")", "poes_elem", "=", "et", ".", "SubElement", "(", "hc_elem", ",", "'poEs'", ")", "poes_elem", ".", "text", "=", "' '", ".", "join", "(", "map", "(", "scientificformat", ",", "hc", ".", "poes", ")", ")" ]
Add hazard curves stored into `data` as child of the `root` element with `metadata`. See the documentation of the method `serialize` and the constructor for a description of `data` and `metadata`, respectively.
[ "Add", "hazard", "curves", "stored", "into", "data", "as", "child", "of", "the", "root", "element", "with", "metadata", ".", "See", "the", "documentation", "of", "the", "method", "serialize", "and", "the", "constructor", "for", "a", "description", "of", "data", "and", "metadata", "respectively", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/hazard_writers.py#L194-L215
177
gem/oq-engine
openquake/commonlib/hazard_writers.py
EventBasedGMFXMLWriter.serialize
def serialize(self, data, fmt='%10.7E'): """ Serialize a collection of ground motion fields to XML. :param data: An iterable of "GMF set" objects. Each "GMF set" object should: * have an `investigation_time` attribute * have an `stochastic_event_set_id` attribute * be iterable, yielding a sequence of "GMF" objects Each "GMF" object should: * have an `imt` attribute * have an `sa_period` attribute (only if `imt` is 'SA') * have an `sa_damping` attribute (only if `imt` is 'SA') * have a `event_id` attribute (to indicate which rupture contributed to this gmf) * be iterable, yielding a sequence of "GMF node" objects Each "GMF node" object should have: * a `gmv` attribute (to indicate the ground motion value * `lon` and `lat` attributes (to indicate the geographical location of the ground motion field) """ gmf_set_nodes = [] for gmf_set in data: gmf_set_node = Node('gmfSet') if gmf_set.investigation_time: gmf_set_node['investigationTime'] = str( gmf_set.investigation_time) gmf_set_node['stochasticEventSetId'] = str( gmf_set.stochastic_event_set_id) gmf_set_node.nodes = gen_gmfs(gmf_set) gmf_set_nodes.append(gmf_set_node) gmf_container = Node('gmfCollection') gmf_container[SM_TREE_PATH] = self.sm_lt_path gmf_container[GSIM_TREE_PATH] = self.gsim_lt_path gmf_container.nodes = gmf_set_nodes with open(self.dest, 'wb') as dest: nrml.write([gmf_container], dest, fmt)
python
def serialize(self, data, fmt='%10.7E'): """ Serialize a collection of ground motion fields to XML. :param data: An iterable of "GMF set" objects. Each "GMF set" object should: * have an `investigation_time` attribute * have an `stochastic_event_set_id` attribute * be iterable, yielding a sequence of "GMF" objects Each "GMF" object should: * have an `imt` attribute * have an `sa_period` attribute (only if `imt` is 'SA') * have an `sa_damping` attribute (only if `imt` is 'SA') * have a `event_id` attribute (to indicate which rupture contributed to this gmf) * be iterable, yielding a sequence of "GMF node" objects Each "GMF node" object should have: * a `gmv` attribute (to indicate the ground motion value * `lon` and `lat` attributes (to indicate the geographical location of the ground motion field) """ gmf_set_nodes = [] for gmf_set in data: gmf_set_node = Node('gmfSet') if gmf_set.investigation_time: gmf_set_node['investigationTime'] = str( gmf_set.investigation_time) gmf_set_node['stochasticEventSetId'] = str( gmf_set.stochastic_event_set_id) gmf_set_node.nodes = gen_gmfs(gmf_set) gmf_set_nodes.append(gmf_set_node) gmf_container = Node('gmfCollection') gmf_container[SM_TREE_PATH] = self.sm_lt_path gmf_container[GSIM_TREE_PATH] = self.gsim_lt_path gmf_container.nodes = gmf_set_nodes with open(self.dest, 'wb') as dest: nrml.write([gmf_container], dest, fmt)
[ "def", "serialize", "(", "self", ",", "data", ",", "fmt", "=", "'%10.7E'", ")", ":", "gmf_set_nodes", "=", "[", "]", "for", "gmf_set", "in", "data", ":", "gmf_set_node", "=", "Node", "(", "'gmfSet'", ")", "if", "gmf_set", ".", "investigation_time", ":", "gmf_set_node", "[", "'investigationTime'", "]", "=", "str", "(", "gmf_set", ".", "investigation_time", ")", "gmf_set_node", "[", "'stochasticEventSetId'", "]", "=", "str", "(", "gmf_set", ".", "stochastic_event_set_id", ")", "gmf_set_node", ".", "nodes", "=", "gen_gmfs", "(", "gmf_set", ")", "gmf_set_nodes", ".", "append", "(", "gmf_set_node", ")", "gmf_container", "=", "Node", "(", "'gmfCollection'", ")", "gmf_container", "[", "SM_TREE_PATH", "]", "=", "self", ".", "sm_lt_path", "gmf_container", "[", "GSIM_TREE_PATH", "]", "=", "self", ".", "gsim_lt_path", "gmf_container", ".", "nodes", "=", "gmf_set_nodes", "with", "open", "(", "self", ".", "dest", ",", "'wb'", ")", "as", "dest", ":", "nrml", ".", "write", "(", "[", "gmf_container", "]", ",", "dest", ",", "fmt", ")" ]
Serialize a collection of ground motion fields to XML. :param data: An iterable of "GMF set" objects. Each "GMF set" object should: * have an `investigation_time` attribute * have an `stochastic_event_set_id` attribute * be iterable, yielding a sequence of "GMF" objects Each "GMF" object should: * have an `imt` attribute * have an `sa_period` attribute (only if `imt` is 'SA') * have an `sa_damping` attribute (only if `imt` is 'SA') * have a `event_id` attribute (to indicate which rupture contributed to this gmf) * be iterable, yielding a sequence of "GMF node" objects Each "GMF node" object should have: * a `gmv` attribute (to indicate the ground motion value * `lon` and `lat` attributes (to indicate the geographical location of the ground motion field)
[ "Serialize", "a", "collection", "of", "ground", "motion", "fields", "to", "XML", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/hazard_writers.py#L259-L303
178
gem/oq-engine
openquake/commonlib/hazard_writers.py
SESXMLWriter.serialize
def serialize(self, data, investigation_time): """ Serialize a collection of stochastic event sets to XML. :param data: A dictionary src_group_id -> list of :class:`openquake.commonlib.calc.Rupture` objects. Each Rupture should have the following attributes: * `rupid` * `events_by_ses` * `magnitude` * `strike` * `dip` * `rake` * `tectonic_region_type` * `is_from_fault_source` (a `bool`) * `is_multi_surface` (a `bool`) * `lons` * `lats` * `depths` If `is_from_fault_source` is `True`, the rupture originated from a simple or complex fault sources. In this case, `lons`, `lats`, and `depths` should all be 2D arrays (of uniform shape). These coordinate triples represent nodes of the rupture mesh. If `is_from_fault_source` is `False`, the rupture originated from a point or area source. In this case, the rupture is represented by a quadrilateral planar surface. This planar surface is defined by 3D vertices. In this case, the rupture should have the following attributes: * `top_left_corner` * `top_right_corner` * `bottom_right_corner` * `bottom_left_corner` Each of these should be a triple of `lon`, `lat`, `depth`. If `is_multi_surface` is `True`, the rupture originated from a multi-surface source. In this case, `lons`, `lats`, and `depths` should have uniform length. The length should be a multiple of 4, where each segment of 4 represents the corner points of a planar surface in the following order: * top left * top right * bottom left * bottom right Each of these should be a triple of `lon`, `lat`, `depth`. :param investigation_time: Investigation time parameter specified in the job.ini """ with open(self.dest, 'wb') as fh: root = et.Element('nrml') ses_container = et.SubElement(root, 'ruptureCollection') ses_container.set('investigationTime', str(investigation_time)) for grp_id in sorted(data): attrs = dict( id=grp_id, tectonicRegion=data[grp_id][0].tectonic_region_type) sg = et.SubElement(ses_container, 'ruptureGroup', attrs) for rupture in data[grp_id]: rupture_to_element(rupture, sg) nrml.write(list(root), fh)
python
def serialize(self, data, investigation_time): """ Serialize a collection of stochastic event sets to XML. :param data: A dictionary src_group_id -> list of :class:`openquake.commonlib.calc.Rupture` objects. Each Rupture should have the following attributes: * `rupid` * `events_by_ses` * `magnitude` * `strike` * `dip` * `rake` * `tectonic_region_type` * `is_from_fault_source` (a `bool`) * `is_multi_surface` (a `bool`) * `lons` * `lats` * `depths` If `is_from_fault_source` is `True`, the rupture originated from a simple or complex fault sources. In this case, `lons`, `lats`, and `depths` should all be 2D arrays (of uniform shape). These coordinate triples represent nodes of the rupture mesh. If `is_from_fault_source` is `False`, the rupture originated from a point or area source. In this case, the rupture is represented by a quadrilateral planar surface. This planar surface is defined by 3D vertices. In this case, the rupture should have the following attributes: * `top_left_corner` * `top_right_corner` * `bottom_right_corner` * `bottom_left_corner` Each of these should be a triple of `lon`, `lat`, `depth`. If `is_multi_surface` is `True`, the rupture originated from a multi-surface source. In this case, `lons`, `lats`, and `depths` should have uniform length. The length should be a multiple of 4, where each segment of 4 represents the corner points of a planar surface in the following order: * top left * top right * bottom left * bottom right Each of these should be a triple of `lon`, `lat`, `depth`. :param investigation_time: Investigation time parameter specified in the job.ini """ with open(self.dest, 'wb') as fh: root = et.Element('nrml') ses_container = et.SubElement(root, 'ruptureCollection') ses_container.set('investigationTime', str(investigation_time)) for grp_id in sorted(data): attrs = dict( id=grp_id, tectonicRegion=data[grp_id][0].tectonic_region_type) sg = et.SubElement(ses_container, 'ruptureGroup', attrs) for rupture in data[grp_id]: rupture_to_element(rupture, sg) nrml.write(list(root), fh)
[ "def", "serialize", "(", "self", ",", "data", ",", "investigation_time", ")", ":", "with", "open", "(", "self", ".", "dest", ",", "'wb'", ")", "as", "fh", ":", "root", "=", "et", ".", "Element", "(", "'nrml'", ")", "ses_container", "=", "et", ".", "SubElement", "(", "root", ",", "'ruptureCollection'", ")", "ses_container", ".", "set", "(", "'investigationTime'", ",", "str", "(", "investigation_time", ")", ")", "for", "grp_id", "in", "sorted", "(", "data", ")", ":", "attrs", "=", "dict", "(", "id", "=", "grp_id", ",", "tectonicRegion", "=", "data", "[", "grp_id", "]", "[", "0", "]", ".", "tectonic_region_type", ")", "sg", "=", "et", ".", "SubElement", "(", "ses_container", ",", "'ruptureGroup'", ",", "attrs", ")", "for", "rupture", "in", "data", "[", "grp_id", "]", ":", "rupture_to_element", "(", "rupture", ",", "sg", ")", "nrml", ".", "write", "(", "list", "(", "root", ")", ",", "fh", ")" ]
Serialize a collection of stochastic event sets to XML. :param data: A dictionary src_group_id -> list of :class:`openquake.commonlib.calc.Rupture` objects. Each Rupture should have the following attributes: * `rupid` * `events_by_ses` * `magnitude` * `strike` * `dip` * `rake` * `tectonic_region_type` * `is_from_fault_source` (a `bool`) * `is_multi_surface` (a `bool`) * `lons` * `lats` * `depths` If `is_from_fault_source` is `True`, the rupture originated from a simple or complex fault sources. In this case, `lons`, `lats`, and `depths` should all be 2D arrays (of uniform shape). These coordinate triples represent nodes of the rupture mesh. If `is_from_fault_source` is `False`, the rupture originated from a point or area source. In this case, the rupture is represented by a quadrilateral planar surface. This planar surface is defined by 3D vertices. In this case, the rupture should have the following attributes: * `top_left_corner` * `top_right_corner` * `bottom_right_corner` * `bottom_left_corner` Each of these should be a triple of `lon`, `lat`, `depth`. If `is_multi_surface` is `True`, the rupture originated from a multi-surface source. In this case, `lons`, `lats`, and `depths` should have uniform length. The length should be a multiple of 4, where each segment of 4 represents the corner points of a planar surface in the following order: * top left * top right * bottom left * bottom right Each of these should be a triple of `lon`, `lat`, `depth`. :param investigation_time: Investigation time parameter specified in the job.ini
[ "Serialize", "a", "collection", "of", "stochastic", "event", "sets", "to", "XML", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/hazard_writers.py#L440-L507
179
gem/oq-engine
openquake/commonlib/hazard_writers.py
HazardMapXMLWriter.serialize
def serialize(self, data): """ Serialize hazard map data to XML. See :meth:`HazardMapWriter.serialize` for details about the expected input. """ with open(self.dest, 'wb') as fh: root = et.Element('nrml') hazard_map = et.SubElement(root, 'hazardMap') _set_metadata(hazard_map, self.metadata, _ATTR_MAP) for lon, lat, iml in data: node = et.SubElement(hazard_map, 'node') node.set('lon', str(lon)) node.set('lat', str(lat)) node.set('iml', str(iml)) nrml.write(list(root), fh)
python
def serialize(self, data): """ Serialize hazard map data to XML. See :meth:`HazardMapWriter.serialize` for details about the expected input. """ with open(self.dest, 'wb') as fh: root = et.Element('nrml') hazard_map = et.SubElement(root, 'hazardMap') _set_metadata(hazard_map, self.metadata, _ATTR_MAP) for lon, lat, iml in data: node = et.SubElement(hazard_map, 'node') node.set('lon', str(lon)) node.set('lat', str(lat)) node.set('iml', str(iml)) nrml.write(list(root), fh)
[ "def", "serialize", "(", "self", ",", "data", ")", ":", "with", "open", "(", "self", ".", "dest", ",", "'wb'", ")", "as", "fh", ":", "root", "=", "et", ".", "Element", "(", "'nrml'", ")", "hazard_map", "=", "et", ".", "SubElement", "(", "root", ",", "'hazardMap'", ")", "_set_metadata", "(", "hazard_map", ",", "self", ".", "metadata", ",", "_ATTR_MAP", ")", "for", "lon", ",", "lat", ",", "iml", "in", "data", ":", "node", "=", "et", ".", "SubElement", "(", "hazard_map", ",", "'node'", ")", "node", ".", "set", "(", "'lon'", ",", "str", "(", "lon", ")", ")", "node", ".", "set", "(", "'lat'", ",", "str", "(", "lat", ")", ")", "node", ".", "set", "(", "'iml'", ",", "str", "(", "iml", ")", ")", "nrml", ".", "write", "(", "list", "(", "root", ")", ",", "fh", ")" ]
Serialize hazard map data to XML. See :meth:`HazardMapWriter.serialize` for details about the expected input.
[ "Serialize", "hazard", "map", "data", "to", "XML", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/hazard_writers.py#L560-L578
180
gem/oq-engine
openquake/commonlib/hazard_writers.py
UHSXMLWriter.serialize
def serialize(self, data): """ Write a sequence of uniform hazard spectra to the specified file. :param data: Iterable of UHS data. Each datum must be an object with the following attributes: * imls: A sequence of Intensity Measure Levels * location: An object representing the location of the curve; must have `x` and `y` to represent lon and lat, respectively. """ gml_ns = nrml.SERIALIZE_NS_MAP['gml'] with open(self.dest, 'wb') as fh: root = et.Element('nrml') uh_spectra = et.SubElement(root, 'uniformHazardSpectra') _set_metadata(uh_spectra, self.metadata, _ATTR_MAP) periods_elem = et.SubElement(uh_spectra, 'periods') periods_elem.text = ' '.join([str(x) for x in self.metadata['periods']]) for uhs in data: uhs_elem = et.SubElement(uh_spectra, 'uhs') gml_point = et.SubElement(uhs_elem, '{%s}Point' % gml_ns) gml_pos = et.SubElement(gml_point, '{%s}pos' % gml_ns) gml_pos.text = '%s %s' % (uhs.location.x, uhs.location.y) imls_elem = et.SubElement(uhs_elem, 'IMLs') imls_elem.text = ' '.join(['%10.7E' % x for x in uhs.imls]) nrml.write(list(root), fh)
python
def serialize(self, data): """ Write a sequence of uniform hazard spectra to the specified file. :param data: Iterable of UHS data. Each datum must be an object with the following attributes: * imls: A sequence of Intensity Measure Levels * location: An object representing the location of the curve; must have `x` and `y` to represent lon and lat, respectively. """ gml_ns = nrml.SERIALIZE_NS_MAP['gml'] with open(self.dest, 'wb') as fh: root = et.Element('nrml') uh_spectra = et.SubElement(root, 'uniformHazardSpectra') _set_metadata(uh_spectra, self.metadata, _ATTR_MAP) periods_elem = et.SubElement(uh_spectra, 'periods') periods_elem.text = ' '.join([str(x) for x in self.metadata['periods']]) for uhs in data: uhs_elem = et.SubElement(uh_spectra, 'uhs') gml_point = et.SubElement(uhs_elem, '{%s}Point' % gml_ns) gml_pos = et.SubElement(gml_point, '{%s}pos' % gml_ns) gml_pos.text = '%s %s' % (uhs.location.x, uhs.location.y) imls_elem = et.SubElement(uhs_elem, 'IMLs') imls_elem.text = ' '.join(['%10.7E' % x for x in uhs.imls]) nrml.write(list(root), fh)
[ "def", "serialize", "(", "self", ",", "data", ")", ":", "gml_ns", "=", "nrml", ".", "SERIALIZE_NS_MAP", "[", "'gml'", "]", "with", "open", "(", "self", ".", "dest", ",", "'wb'", ")", "as", "fh", ":", "root", "=", "et", ".", "Element", "(", "'nrml'", ")", "uh_spectra", "=", "et", ".", "SubElement", "(", "root", ",", "'uniformHazardSpectra'", ")", "_set_metadata", "(", "uh_spectra", ",", "self", ".", "metadata", ",", "_ATTR_MAP", ")", "periods_elem", "=", "et", ".", "SubElement", "(", "uh_spectra", ",", "'periods'", ")", "periods_elem", ".", "text", "=", "' '", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "self", ".", "metadata", "[", "'periods'", "]", "]", ")", "for", "uhs", "in", "data", ":", "uhs_elem", "=", "et", ".", "SubElement", "(", "uh_spectra", ",", "'uhs'", ")", "gml_point", "=", "et", ".", "SubElement", "(", "uhs_elem", ",", "'{%s}Point'", "%", "gml_ns", ")", "gml_pos", "=", "et", ".", "SubElement", "(", "gml_point", ",", "'{%s}pos'", "%", "gml_ns", ")", "gml_pos", ".", "text", "=", "'%s %s'", "%", "(", "uhs", ".", "location", ".", "x", ",", "uhs", ".", "location", ".", "y", ")", "imls_elem", "=", "et", ".", "SubElement", "(", "uhs_elem", ",", "'IMLs'", ")", "imls_elem", ".", "text", "=", "' '", ".", "join", "(", "[", "'%10.7E'", "%", "x", "for", "x", "in", "uhs", ".", "imls", "]", ")", "nrml", ".", "write", "(", "list", "(", "root", ")", ",", "fh", ")" ]
Write a sequence of uniform hazard spectra to the specified file. :param data: Iterable of UHS data. Each datum must be an object with the following attributes: * imls: A sequence of Intensity Measure Levels * location: An object representing the location of the curve; must have `x` and `y` to represent lon and lat, respectively.
[ "Write", "a", "sequence", "of", "uniform", "hazard", "spectra", "to", "the", "specified", "file", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/hazard_writers.py#L728-L761
181
gem/oq-engine
openquake/hmtk/seismicity/max_magnitude/kijko_sellevol_bayes.py
check_config
def check_config(config, data): '''Check config file inputs :param dict config: Configuration settings for the function ''' essential_keys = ['input_mmin', 'b-value', 'sigma-b'] for key in essential_keys: if not key in config.keys(): raise ValueError('For KijkoSellevolBayes the key %s needs to ' 'be set in the configuation' % key) if 'tolerance' not in config.keys() or not config['tolerance']: config['tolerance'] = 1E-5 if not config.get('maximum_iterations', False): config['maximum_iterations'] = 1000 if config['input_mmin'] < np.min(data['magnitude']): config['input_mmin'] = np.min(data['magnitude']) if fabs(config['sigma-b'] < 1E-15): raise ValueError('Sigma-b must be greater than zero!') return config
python
def check_config(config, data): '''Check config file inputs :param dict config: Configuration settings for the function ''' essential_keys = ['input_mmin', 'b-value', 'sigma-b'] for key in essential_keys: if not key in config.keys(): raise ValueError('For KijkoSellevolBayes the key %s needs to ' 'be set in the configuation' % key) if 'tolerance' not in config.keys() or not config['tolerance']: config['tolerance'] = 1E-5 if not config.get('maximum_iterations', False): config['maximum_iterations'] = 1000 if config['input_mmin'] < np.min(data['magnitude']): config['input_mmin'] = np.min(data['magnitude']) if fabs(config['sigma-b'] < 1E-15): raise ValueError('Sigma-b must be greater than zero!') return config
[ "def", "check_config", "(", "config", ",", "data", ")", ":", "essential_keys", "=", "[", "'input_mmin'", ",", "'b-value'", ",", "'sigma-b'", "]", "for", "key", "in", "essential_keys", ":", "if", "not", "key", "in", "config", ".", "keys", "(", ")", ":", "raise", "ValueError", "(", "'For KijkoSellevolBayes the key %s needs to '", "'be set in the configuation'", "%", "key", ")", "if", "'tolerance'", "not", "in", "config", ".", "keys", "(", ")", "or", "not", "config", "[", "'tolerance'", "]", ":", "config", "[", "'tolerance'", "]", "=", "1E-5", "if", "not", "config", ".", "get", "(", "'maximum_iterations'", ",", "False", ")", ":", "config", "[", "'maximum_iterations'", "]", "=", "1000", "if", "config", "[", "'input_mmin'", "]", "<", "np", ".", "min", "(", "data", "[", "'magnitude'", "]", ")", ":", "config", "[", "'input_mmin'", "]", "=", "np", ".", "min", "(", "data", "[", "'magnitude'", "]", ")", "if", "fabs", "(", "config", "[", "'sigma-b'", "]", "<", "1E-15", ")", ":", "raise", "ValueError", "(", "'Sigma-b must be greater than zero!'", ")", "return", "config" ]
Check config file inputs :param dict config: Configuration settings for the function
[ "Check", "config", "file", "inputs" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/seismicity/max_magnitude/kijko_sellevol_bayes.py#L60-L84
182
gem/oq-engine
openquake/hazardlib/gsim/toro_1997.py
ToroEtAl1997MblgNSHMP2008._compute_mean
def _compute_mean(self, C, mag, rjb): """ Compute ground motion mean value. """ # line 1686 in hazgridXnga2.f ffc = self._compute_finite_fault_correction(mag) d = np.sqrt(rjb ** 2 + (C['c7'] ** 2) * (ffc ** 2)) # lines 1663, 1694-1696 in hazgridXnga2.f mean = ( C['c1'] + C['c2'] * (mag - 6.) + C['c3'] * ((mag - 6.) ** 2) - C['c4'] * np.log(d) - C['c6'] * d ) factor = np.log(rjb / 100.) idx = factor > 0 mean[idx] -= (C['c5'] - C['c4']) * factor[idx] return mean
python
def _compute_mean(self, C, mag, rjb): """ Compute ground motion mean value. """ # line 1686 in hazgridXnga2.f ffc = self._compute_finite_fault_correction(mag) d = np.sqrt(rjb ** 2 + (C['c7'] ** 2) * (ffc ** 2)) # lines 1663, 1694-1696 in hazgridXnga2.f mean = ( C['c1'] + C['c2'] * (mag - 6.) + C['c3'] * ((mag - 6.) ** 2) - C['c4'] * np.log(d) - C['c6'] * d ) factor = np.log(rjb / 100.) idx = factor > 0 mean[idx] -= (C['c5'] - C['c4']) * factor[idx] return mean
[ "def", "_compute_mean", "(", "self", ",", "C", ",", "mag", ",", "rjb", ")", ":", "# line 1686 in hazgridXnga2.f", "ffc", "=", "self", ".", "_compute_finite_fault_correction", "(", "mag", ")", "d", "=", "np", ".", "sqrt", "(", "rjb", "**", "2", "+", "(", "C", "[", "'c7'", "]", "**", "2", ")", "*", "(", "ffc", "**", "2", ")", ")", "# lines 1663, 1694-1696 in hazgridXnga2.f", "mean", "=", "(", "C", "[", "'c1'", "]", "+", "C", "[", "'c2'", "]", "*", "(", "mag", "-", "6.", ")", "+", "C", "[", "'c3'", "]", "*", "(", "(", "mag", "-", "6.", ")", "**", "2", ")", "-", "C", "[", "'c4'", "]", "*", "np", ".", "log", "(", "d", ")", "-", "C", "[", "'c6'", "]", "*", "d", ")", "factor", "=", "np", ".", "log", "(", "rjb", "/", "100.", ")", "idx", "=", "factor", ">", "0", "mean", "[", "idx", "]", "-=", "(", "C", "[", "'c5'", "]", "-", "C", "[", "'c4'", "]", ")", "*", "factor", "[", "idx", "]", "return", "mean" ]
Compute ground motion mean value.
[ "Compute", "ground", "motion", "mean", "value", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/toro_1997.py#L110-L129
183
gem/oq-engine
openquake/hazardlib/gsim/toro_1997.py
ToroEtAl1997MblgNSHMP2008._compute_finite_fault_correction
def _compute_finite_fault_correction(self, mag): """ Compute finite fault correction term as geometric mean of correction terms obtained from Mw values calculated with Johnston 1996 and Atkinson and Boore 1987 conversion equations. Implement equations as in lines 1653 - 1658 in hazgridXnga2.f """ mw_j96 = mblg_to_mw_johnston_96(mag) mw_ab87 = mblg_to_mw_atkinson_boore_87(mag) t1 = np.exp(-1.25 + 0.227 * mw_j96) t2 = np.exp(-1.25 + 0.227 * mw_ab87) return np.sqrt(t1 * t2)
python
def _compute_finite_fault_correction(self, mag): """ Compute finite fault correction term as geometric mean of correction terms obtained from Mw values calculated with Johnston 1996 and Atkinson and Boore 1987 conversion equations. Implement equations as in lines 1653 - 1658 in hazgridXnga2.f """ mw_j96 = mblg_to_mw_johnston_96(mag) mw_ab87 = mblg_to_mw_atkinson_boore_87(mag) t1 = np.exp(-1.25 + 0.227 * mw_j96) t2 = np.exp(-1.25 + 0.227 * mw_ab87) return np.sqrt(t1 * t2)
[ "def", "_compute_finite_fault_correction", "(", "self", ",", "mag", ")", ":", "mw_j96", "=", "mblg_to_mw_johnston_96", "(", "mag", ")", "mw_ab87", "=", "mblg_to_mw_atkinson_boore_87", "(", "mag", ")", "t1", "=", "np", ".", "exp", "(", "-", "1.25", "+", "0.227", "*", "mw_j96", ")", "t2", "=", "np", ".", "exp", "(", "-", "1.25", "+", "0.227", "*", "mw_ab87", ")", "return", "np", ".", "sqrt", "(", "t1", "*", "t2", ")" ]
Compute finite fault correction term as geometric mean of correction terms obtained from Mw values calculated with Johnston 1996 and Atkinson and Boore 1987 conversion equations. Implement equations as in lines 1653 - 1658 in hazgridXnga2.f
[ "Compute", "finite", "fault", "correction", "term", "as", "geometric", "mean", "of", "correction", "terms", "obtained", "from", "Mw", "values", "calculated", "with", "Johnston", "1996", "and", "Atkinson", "and", "Boore", "1987", "conversion", "equations", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/toro_1997.py#L131-L145
184
gem/oq-engine
openquake/commands/upgrade_nrml.py
get_vulnerability_functions_04
def get_vulnerability_functions_04(fname): """ Parse the vulnerability model in NRML 0.4 format. :param fname: path of the vulnerability file :returns: a dictionary imt, taxonomy -> vulnerability function + vset """ categories = dict(assetCategory=set(), lossCategory=set(), vulnerabilitySetID=set()) imts = set() taxonomies = set() vf_dict = {} # imt, taxonomy -> vulnerability function for vset in nrml.read(fname).vulnerabilityModel: categories['assetCategory'].add(vset['assetCategory']) categories['lossCategory'].add(vset['lossCategory']) categories['vulnerabilitySetID'].add(vset['vulnerabilitySetID']) IML = vset.IML imt_str = IML['IMT'] imls = ~IML imts.add(imt_str) for vfun in vset.getnodes('discreteVulnerability'): taxonomy = vfun['vulnerabilityFunctionID'] if taxonomy in taxonomies: raise InvalidFile( 'Duplicated vulnerabilityFunctionID: %s: %s, line %d' % (taxonomy, fname, vfun.lineno)) taxonomies.add(taxonomy) with context(fname, vfun): loss_ratios = ~vfun.lossRatio coefficients = ~vfun.coefficientsVariation if len(loss_ratios) != len(imls): raise InvalidFile( 'There are %d loss ratios, but %d imls: %s, line %d' % (len(loss_ratios), len(imls), fname, vfun.lossRatio.lineno)) if len(coefficients) != len(imls): raise InvalidFile( 'There are %d coefficients, but %d imls: %s, line %d' % (len(coefficients), len(imls), fname, vfun.coefficientsVariation.lineno)) with context(fname, vfun): vf_dict[imt_str, taxonomy] = scientific.VulnerabilityFunction( taxonomy, imt_str, imls, loss_ratios, coefficients, vfun['probabilisticDistribution']) categories['id'] = '_'.join(sorted(categories['vulnerabilitySetID'])) del categories['vulnerabilitySetID'] return vf_dict, categories
python
def get_vulnerability_functions_04(fname): """ Parse the vulnerability model in NRML 0.4 format. :param fname: path of the vulnerability file :returns: a dictionary imt, taxonomy -> vulnerability function + vset """ categories = dict(assetCategory=set(), lossCategory=set(), vulnerabilitySetID=set()) imts = set() taxonomies = set() vf_dict = {} # imt, taxonomy -> vulnerability function for vset in nrml.read(fname).vulnerabilityModel: categories['assetCategory'].add(vset['assetCategory']) categories['lossCategory'].add(vset['lossCategory']) categories['vulnerabilitySetID'].add(vset['vulnerabilitySetID']) IML = vset.IML imt_str = IML['IMT'] imls = ~IML imts.add(imt_str) for vfun in vset.getnodes('discreteVulnerability'): taxonomy = vfun['vulnerabilityFunctionID'] if taxonomy in taxonomies: raise InvalidFile( 'Duplicated vulnerabilityFunctionID: %s: %s, line %d' % (taxonomy, fname, vfun.lineno)) taxonomies.add(taxonomy) with context(fname, vfun): loss_ratios = ~vfun.lossRatio coefficients = ~vfun.coefficientsVariation if len(loss_ratios) != len(imls): raise InvalidFile( 'There are %d loss ratios, but %d imls: %s, line %d' % (len(loss_ratios), len(imls), fname, vfun.lossRatio.lineno)) if len(coefficients) != len(imls): raise InvalidFile( 'There are %d coefficients, but %d imls: %s, line %d' % (len(coefficients), len(imls), fname, vfun.coefficientsVariation.lineno)) with context(fname, vfun): vf_dict[imt_str, taxonomy] = scientific.VulnerabilityFunction( taxonomy, imt_str, imls, loss_ratios, coefficients, vfun['probabilisticDistribution']) categories['id'] = '_'.join(sorted(categories['vulnerabilitySetID'])) del categories['vulnerabilitySetID'] return vf_dict, categories
[ "def", "get_vulnerability_functions_04", "(", "fname", ")", ":", "categories", "=", "dict", "(", "assetCategory", "=", "set", "(", ")", ",", "lossCategory", "=", "set", "(", ")", ",", "vulnerabilitySetID", "=", "set", "(", ")", ")", "imts", "=", "set", "(", ")", "taxonomies", "=", "set", "(", ")", "vf_dict", "=", "{", "}", "# imt, taxonomy -> vulnerability function", "for", "vset", "in", "nrml", ".", "read", "(", "fname", ")", ".", "vulnerabilityModel", ":", "categories", "[", "'assetCategory'", "]", ".", "add", "(", "vset", "[", "'assetCategory'", "]", ")", "categories", "[", "'lossCategory'", "]", ".", "add", "(", "vset", "[", "'lossCategory'", "]", ")", "categories", "[", "'vulnerabilitySetID'", "]", ".", "add", "(", "vset", "[", "'vulnerabilitySetID'", "]", ")", "IML", "=", "vset", ".", "IML", "imt_str", "=", "IML", "[", "'IMT'", "]", "imls", "=", "~", "IML", "imts", ".", "add", "(", "imt_str", ")", "for", "vfun", "in", "vset", ".", "getnodes", "(", "'discreteVulnerability'", ")", ":", "taxonomy", "=", "vfun", "[", "'vulnerabilityFunctionID'", "]", "if", "taxonomy", "in", "taxonomies", ":", "raise", "InvalidFile", "(", "'Duplicated vulnerabilityFunctionID: %s: %s, line %d'", "%", "(", "taxonomy", ",", "fname", ",", "vfun", ".", "lineno", ")", ")", "taxonomies", ".", "add", "(", "taxonomy", ")", "with", "context", "(", "fname", ",", "vfun", ")", ":", "loss_ratios", "=", "~", "vfun", ".", "lossRatio", "coefficients", "=", "~", "vfun", ".", "coefficientsVariation", "if", "len", "(", "loss_ratios", ")", "!=", "len", "(", "imls", ")", ":", "raise", "InvalidFile", "(", "'There are %d loss ratios, but %d imls: %s, line %d'", "%", "(", "len", "(", "loss_ratios", ")", ",", "len", "(", "imls", ")", ",", "fname", ",", "vfun", ".", "lossRatio", ".", "lineno", ")", ")", "if", "len", "(", "coefficients", ")", "!=", "len", "(", "imls", ")", ":", "raise", "InvalidFile", "(", "'There are %d coefficients, but %d imls: %s, line %d'", "%", "(", "len", "(", "coefficients", ")", ",", "len", "(", "imls", ")", ",", "fname", ",", "vfun", ".", "coefficientsVariation", ".", "lineno", ")", ")", "with", "context", "(", "fname", ",", "vfun", ")", ":", "vf_dict", "[", "imt_str", ",", "taxonomy", "]", "=", "scientific", ".", "VulnerabilityFunction", "(", "taxonomy", ",", "imt_str", ",", "imls", ",", "loss_ratios", ",", "coefficients", ",", "vfun", "[", "'probabilisticDistribution'", "]", ")", "categories", "[", "'id'", "]", "=", "'_'", ".", "join", "(", "sorted", "(", "categories", "[", "'vulnerabilitySetID'", "]", ")", ")", "del", "categories", "[", "'vulnerabilitySetID'", "]", "return", "vf_dict", ",", "categories" ]
Parse the vulnerability model in NRML 0.4 format. :param fname: path of the vulnerability file :returns: a dictionary imt, taxonomy -> vulnerability function + vset
[ "Parse", "the", "vulnerability", "model", "in", "NRML", "0", ".", "4", "format", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/upgrade_nrml.py#L32-L80
185
gem/oq-engine
openquake/commands/upgrade_nrml.py
upgrade_file
def upgrade_file(path, multipoint): """Upgrade to the latest NRML version""" node0 = nrml.read(path, chatty=False)[0] shutil.copy(path, path + '.bak') # make a backup of the original file tag = striptag(node0.tag) gml = True if tag == 'vulnerabilityModel': vf_dict, cat_dict = get_vulnerability_functions_04(path) # below I am converting into a NRML 0.5 vulnerabilityModel node0 = Node( 'vulnerabilityModel', cat_dict, nodes=[obj_to_node(val) for val in vf_dict.values()]) gml = False elif tag == 'fragilityModel': node0 = read_nrml.convert_fragility_model_04( nrml.read(path)[0], path) gml = False elif tag == 'sourceModel': node0 = nrml.read(path)[0] dic = groupby(node0.nodes, operator.itemgetter('tectonicRegion')) node0.nodes = [Node('sourceGroup', dict(tectonicRegion=trt, name="group %s" % i), nodes=srcs) for i, (trt, srcs) in enumerate(dic.items(), 1)] if multipoint: sourceconverter.update_source_model(node0, path + '.bak') with open(path, 'wb') as f: nrml.write([node0], f, gml=gml)
python
def upgrade_file(path, multipoint): """Upgrade to the latest NRML version""" node0 = nrml.read(path, chatty=False)[0] shutil.copy(path, path + '.bak') # make a backup of the original file tag = striptag(node0.tag) gml = True if tag == 'vulnerabilityModel': vf_dict, cat_dict = get_vulnerability_functions_04(path) # below I am converting into a NRML 0.5 vulnerabilityModel node0 = Node( 'vulnerabilityModel', cat_dict, nodes=[obj_to_node(val) for val in vf_dict.values()]) gml = False elif tag == 'fragilityModel': node0 = read_nrml.convert_fragility_model_04( nrml.read(path)[0], path) gml = False elif tag == 'sourceModel': node0 = nrml.read(path)[0] dic = groupby(node0.nodes, operator.itemgetter('tectonicRegion')) node0.nodes = [Node('sourceGroup', dict(tectonicRegion=trt, name="group %s" % i), nodes=srcs) for i, (trt, srcs) in enumerate(dic.items(), 1)] if multipoint: sourceconverter.update_source_model(node0, path + '.bak') with open(path, 'wb') as f: nrml.write([node0], f, gml=gml)
[ "def", "upgrade_file", "(", "path", ",", "multipoint", ")", ":", "node0", "=", "nrml", ".", "read", "(", "path", ",", "chatty", "=", "False", ")", "[", "0", "]", "shutil", ".", "copy", "(", "path", ",", "path", "+", "'.bak'", ")", "# make a backup of the original file", "tag", "=", "striptag", "(", "node0", ".", "tag", ")", "gml", "=", "True", "if", "tag", "==", "'vulnerabilityModel'", ":", "vf_dict", ",", "cat_dict", "=", "get_vulnerability_functions_04", "(", "path", ")", "# below I am converting into a NRML 0.5 vulnerabilityModel", "node0", "=", "Node", "(", "'vulnerabilityModel'", ",", "cat_dict", ",", "nodes", "=", "[", "obj_to_node", "(", "val", ")", "for", "val", "in", "vf_dict", ".", "values", "(", ")", "]", ")", "gml", "=", "False", "elif", "tag", "==", "'fragilityModel'", ":", "node0", "=", "read_nrml", ".", "convert_fragility_model_04", "(", "nrml", ".", "read", "(", "path", ")", "[", "0", "]", ",", "path", ")", "gml", "=", "False", "elif", "tag", "==", "'sourceModel'", ":", "node0", "=", "nrml", ".", "read", "(", "path", ")", "[", "0", "]", "dic", "=", "groupby", "(", "node0", ".", "nodes", ",", "operator", ".", "itemgetter", "(", "'tectonicRegion'", ")", ")", "node0", ".", "nodes", "=", "[", "Node", "(", "'sourceGroup'", ",", "dict", "(", "tectonicRegion", "=", "trt", ",", "name", "=", "\"group %s\"", "%", "i", ")", ",", "nodes", "=", "srcs", ")", "for", "i", ",", "(", "trt", ",", "srcs", ")", "in", "enumerate", "(", "dic", ".", "items", "(", ")", ",", "1", ")", "]", "if", "multipoint", ":", "sourceconverter", ".", "update_source_model", "(", "node0", ",", "path", "+", "'.bak'", ")", "with", "open", "(", "path", ",", "'wb'", ")", "as", "f", ":", "nrml", ".", "write", "(", "[", "node0", "]", ",", "f", ",", "gml", "=", "gml", ")" ]
Upgrade to the latest NRML version
[ "Upgrade", "to", "the", "latest", "NRML", "version" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/upgrade_nrml.py#L83-L110
186
gem/oq-engine
openquake/hazardlib/gsim/faccioli_2010.py
FaccioliEtAl2010._compute_term_3
def _compute_term_3(self, C, rrup, mag): """ This computes the third term in equation 2, page 2. """ return (C['a3'] * np.log10(rrup + C['a4'] * np.power(10, C['a5'] * mag)))
python
def _compute_term_3(self, C, rrup, mag): """ This computes the third term in equation 2, page 2. """ return (C['a3'] * np.log10(rrup + C['a4'] * np.power(10, C['a5'] * mag)))
[ "def", "_compute_term_3", "(", "self", ",", "C", ",", "rrup", ",", "mag", ")", ":", "return", "(", "C", "[", "'a3'", "]", "*", "np", ".", "log10", "(", "rrup", "+", "C", "[", "'a4'", "]", "*", "np", ".", "power", "(", "10", ",", "C", "[", "'a5'", "]", "*", "mag", ")", ")", ")" ]
This computes the third term in equation 2, page 2.
[ "This", "computes", "the", "third", "term", "in", "equation", "2", "page", "2", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/faccioli_2010.py#L85-L90
187
gem/oq-engine
openquake/hmtk/sources/source_conversion_utils.py
mag_scale_rel_to_hazardlib
def mag_scale_rel_to_hazardlib(mag_scale_rel, use_default=False): """ Returns the magnitude scaling relation in a format readable by openquake.hazardlib """ if isinstance(mag_scale_rel, BaseMSR): return mag_scale_rel elif isinstance(mag_scale_rel, str): if not mag_scale_rel in SCALE_RELS.keys(): raise ValueError('Magnitude scaling relation %s not supported!' % mag_scale_rel) else: return SCALE_RELS[mag_scale_rel]() else: if use_default: # Returns the Wells and Coppersmith string return WC1994() else: raise ValueError('Magnitude Scaling Relation Not Defined!')
python
def mag_scale_rel_to_hazardlib(mag_scale_rel, use_default=False): """ Returns the magnitude scaling relation in a format readable by openquake.hazardlib """ if isinstance(mag_scale_rel, BaseMSR): return mag_scale_rel elif isinstance(mag_scale_rel, str): if not mag_scale_rel in SCALE_RELS.keys(): raise ValueError('Magnitude scaling relation %s not supported!' % mag_scale_rel) else: return SCALE_RELS[mag_scale_rel]() else: if use_default: # Returns the Wells and Coppersmith string return WC1994() else: raise ValueError('Magnitude Scaling Relation Not Defined!')
[ "def", "mag_scale_rel_to_hazardlib", "(", "mag_scale_rel", ",", "use_default", "=", "False", ")", ":", "if", "isinstance", "(", "mag_scale_rel", ",", "BaseMSR", ")", ":", "return", "mag_scale_rel", "elif", "isinstance", "(", "mag_scale_rel", ",", "str", ")", ":", "if", "not", "mag_scale_rel", "in", "SCALE_RELS", ".", "keys", "(", ")", ":", "raise", "ValueError", "(", "'Magnitude scaling relation %s not supported!'", "%", "mag_scale_rel", ")", "else", ":", "return", "SCALE_RELS", "[", "mag_scale_rel", "]", "(", ")", "else", ":", "if", "use_default", ":", "# Returns the Wells and Coppersmith string", "return", "WC1994", "(", ")", "else", ":", "raise", "ValueError", "(", "'Magnitude Scaling Relation Not Defined!'", ")" ]
Returns the magnitude scaling relation in a format readable by openquake.hazardlib
[ "Returns", "the", "magnitude", "scaling", "relation", "in", "a", "format", "readable", "by", "openquake", ".", "hazardlib" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/source_conversion_utils.py#L79-L97
188
gem/oq-engine
openquake/hmtk/sources/source_conversion_utils.py
npd_to_pmf
def npd_to_pmf(nodal_plane_dist, use_default=False): """ Returns the nodal plane distribution as an instance of the PMF class """ if isinstance(nodal_plane_dist, PMF): # Aready in PMF format - return return nodal_plane_dist else: if use_default: return PMF([(1.0, NodalPlane(0.0, 90.0, 0.0))]) else: raise ValueError('Nodal Plane distribution not defined')
python
def npd_to_pmf(nodal_plane_dist, use_default=False): """ Returns the nodal plane distribution as an instance of the PMF class """ if isinstance(nodal_plane_dist, PMF): # Aready in PMF format - return return nodal_plane_dist else: if use_default: return PMF([(1.0, NodalPlane(0.0, 90.0, 0.0))]) else: raise ValueError('Nodal Plane distribution not defined')
[ "def", "npd_to_pmf", "(", "nodal_plane_dist", ",", "use_default", "=", "False", ")", ":", "if", "isinstance", "(", "nodal_plane_dist", ",", "PMF", ")", ":", "# Aready in PMF format - return", "return", "nodal_plane_dist", "else", ":", "if", "use_default", ":", "return", "PMF", "(", "[", "(", "1.0", ",", "NodalPlane", "(", "0.0", ",", "90.0", ",", "0.0", ")", ")", "]", ")", "else", ":", "raise", "ValueError", "(", "'Nodal Plane distribution not defined'", ")" ]
Returns the nodal plane distribution as an instance of the PMF class
[ "Returns", "the", "nodal", "plane", "distribution", "as", "an", "instance", "of", "the", "PMF", "class" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/sources/source_conversion_utils.py#L100-L111
189
gem/oq-engine
openquake/commands/engine.py
run_job
def run_job(job_ini, log_level='info', log_file=None, exports='', username=getpass.getuser(), **kw): """ Run a job using the specified config file and other options. :param str job_ini: Path to calculation config (INI-style) files. :param str log_level: 'debug', 'info', 'warn', 'error', or 'critical' :param str log_file: Path to log file. :param exports: A comma-separated string of export types requested by the user. :param username: Name of the user running the job :param kw: Extra parameters like hazard_calculation_id and calculation_mode """ job_id = logs.init('job', getattr(logging, log_level.upper())) with logs.handle(job_id, log_level, log_file): job_ini = os.path.abspath(job_ini) oqparam = eng.job_from_file(job_ini, job_id, username, **kw) kw['username'] = username eng.run_calc(job_id, oqparam, exports, **kw) for line in logs.dbcmd('list_outputs', job_id, False): safeprint(line) return job_id
python
def run_job(job_ini, log_level='info', log_file=None, exports='', username=getpass.getuser(), **kw): """ Run a job using the specified config file and other options. :param str job_ini: Path to calculation config (INI-style) files. :param str log_level: 'debug', 'info', 'warn', 'error', or 'critical' :param str log_file: Path to log file. :param exports: A comma-separated string of export types requested by the user. :param username: Name of the user running the job :param kw: Extra parameters like hazard_calculation_id and calculation_mode """ job_id = logs.init('job', getattr(logging, log_level.upper())) with logs.handle(job_id, log_level, log_file): job_ini = os.path.abspath(job_ini) oqparam = eng.job_from_file(job_ini, job_id, username, **kw) kw['username'] = username eng.run_calc(job_id, oqparam, exports, **kw) for line in logs.dbcmd('list_outputs', job_id, False): safeprint(line) return job_id
[ "def", "run_job", "(", "job_ini", ",", "log_level", "=", "'info'", ",", "log_file", "=", "None", ",", "exports", "=", "''", ",", "username", "=", "getpass", ".", "getuser", "(", ")", ",", "*", "*", "kw", ")", ":", "job_id", "=", "logs", ".", "init", "(", "'job'", ",", "getattr", "(", "logging", ",", "log_level", ".", "upper", "(", ")", ")", ")", "with", "logs", ".", "handle", "(", "job_id", ",", "log_level", ",", "log_file", ")", ":", "job_ini", "=", "os", ".", "path", ".", "abspath", "(", "job_ini", ")", "oqparam", "=", "eng", ".", "job_from_file", "(", "job_ini", ",", "job_id", ",", "username", ",", "*", "*", "kw", ")", "kw", "[", "'username'", "]", "=", "username", "eng", ".", "run_calc", "(", "job_id", ",", "oqparam", ",", "exports", ",", "*", "*", "kw", ")", "for", "line", "in", "logs", ".", "dbcmd", "(", "'list_outputs'", ",", "job_id", ",", "False", ")", ":", "safeprint", "(", "line", ")", "return", "job_id" ]
Run a job using the specified config file and other options. :param str job_ini: Path to calculation config (INI-style) files. :param str log_level: 'debug', 'info', 'warn', 'error', or 'critical' :param str log_file: Path to log file. :param exports: A comma-separated string of export types requested by the user. :param username: Name of the user running the job :param kw: Extra parameters like hazard_calculation_id and calculation_mode
[ "Run", "a", "job", "using", "the", "specified", "config", "file", "and", "other", "options", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/engine.py#L45-L71
190
gem/oq-engine
openquake/commands/engine.py
run_tile
def run_tile(job_ini, sites_slice): """ Used in tiling calculations """ return run_job(job_ini, sites_slice=(sites_slice.start, sites_slice.stop))
python
def run_tile(job_ini, sites_slice): """ Used in tiling calculations """ return run_job(job_ini, sites_slice=(sites_slice.start, sites_slice.stop))
[ "def", "run_tile", "(", "job_ini", ",", "sites_slice", ")", ":", "return", "run_job", "(", "job_ini", ",", "sites_slice", "=", "(", "sites_slice", ".", "start", ",", "sites_slice", ".", "stop", ")", ")" ]
Used in tiling calculations
[ "Used", "in", "tiling", "calculations" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/engine.py#L74-L78
191
gem/oq-engine
openquake/commands/engine.py
del_calculation
def del_calculation(job_id, confirmed=False): """ Delete a calculation and all associated outputs. """ if logs.dbcmd('get_job', job_id) is None: print('There is no job %d' % job_id) return if confirmed or confirm( 'Are you sure you want to (abort and) delete this calculation and ' 'all associated outputs?\nThis action cannot be undone. (y/n): '): try: abort(job_id) resp = logs.dbcmd('del_calc', job_id, getpass.getuser()) except RuntimeError as err: safeprint(err) else: if 'success' in resp: print('Removed %d' % job_id) else: print(resp['error'])
python
def del_calculation(job_id, confirmed=False): """ Delete a calculation and all associated outputs. """ if logs.dbcmd('get_job', job_id) is None: print('There is no job %d' % job_id) return if confirmed or confirm( 'Are you sure you want to (abort and) delete this calculation and ' 'all associated outputs?\nThis action cannot be undone. (y/n): '): try: abort(job_id) resp = logs.dbcmd('del_calc', job_id, getpass.getuser()) except RuntimeError as err: safeprint(err) else: if 'success' in resp: print('Removed %d' % job_id) else: print(resp['error'])
[ "def", "del_calculation", "(", "job_id", ",", "confirmed", "=", "False", ")", ":", "if", "logs", ".", "dbcmd", "(", "'get_job'", ",", "job_id", ")", "is", "None", ":", "print", "(", "'There is no job %d'", "%", "job_id", ")", "return", "if", "confirmed", "or", "confirm", "(", "'Are you sure you want to (abort and) delete this calculation and '", "'all associated outputs?\\nThis action cannot be undone. (y/n): '", ")", ":", "try", ":", "abort", "(", "job_id", ")", "resp", "=", "logs", ".", "dbcmd", "(", "'del_calc'", ",", "job_id", ",", "getpass", ".", "getuser", "(", ")", ")", "except", "RuntimeError", "as", "err", ":", "safeprint", "(", "err", ")", "else", ":", "if", "'success'", "in", "resp", ":", "print", "(", "'Removed %d'", "%", "job_id", ")", "else", ":", "print", "(", "resp", "[", "'error'", "]", ")" ]
Delete a calculation and all associated outputs.
[ "Delete", "a", "calculation", "and", "all", "associated", "outputs", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/engine.py#L81-L101
192
gem/oq-engine
openquake/commands/engine.py
smart_run
def smart_run(job_ini, oqparam, log_level, log_file, exports, reuse_hazard): """ Run calculations by storing their hazard checksum and reusing previous calculations if requested. """ haz_checksum = readinput.get_checksum32(oqparam, hazard=True) # retrieve an old calculation with the right checksum, if any job = logs.dbcmd('get_job_from_checksum', haz_checksum) reuse = reuse_hazard and job and os.path.exists(job.ds_calc_dir + '.hdf5') # recompute the hazard and store the checksum ebr = (oqparam.calculation_mode == 'event_based_risk' and 'gmfs' not in oqparam.inputs) if ebr: kw = dict(calculation_mode='event_based') if (oqparam.sites or 'sites' in oqparam.inputs or 'site_model' in oqparam.inputs): # remove exposure from the hazard kw['exposure_file'] = '' else: kw = {} if not reuse: hc_id = run_job(job_ini, log_level, log_file, exports, **kw) if job is None: logs.dbcmd('add_checksum', hc_id, haz_checksum) elif not reuse_hazard or not os.path.exists(job.ds_calc_dir + '.hdf5'): logs.dbcmd('update_job_checksum', hc_id, haz_checksum) if ebr: run_job(job_ini, log_level, log_file, exports, hazard_calculation_id=hc_id) else: hc_id = job.id logging.info('Reusing job #%d', job.id) run_job(job_ini, log_level, log_file, exports, hazard_calculation_id=hc_id)
python
def smart_run(job_ini, oqparam, log_level, log_file, exports, reuse_hazard): """ Run calculations by storing their hazard checksum and reusing previous calculations if requested. """ haz_checksum = readinput.get_checksum32(oqparam, hazard=True) # retrieve an old calculation with the right checksum, if any job = logs.dbcmd('get_job_from_checksum', haz_checksum) reuse = reuse_hazard and job and os.path.exists(job.ds_calc_dir + '.hdf5') # recompute the hazard and store the checksum ebr = (oqparam.calculation_mode == 'event_based_risk' and 'gmfs' not in oqparam.inputs) if ebr: kw = dict(calculation_mode='event_based') if (oqparam.sites or 'sites' in oqparam.inputs or 'site_model' in oqparam.inputs): # remove exposure from the hazard kw['exposure_file'] = '' else: kw = {} if not reuse: hc_id = run_job(job_ini, log_level, log_file, exports, **kw) if job is None: logs.dbcmd('add_checksum', hc_id, haz_checksum) elif not reuse_hazard or not os.path.exists(job.ds_calc_dir + '.hdf5'): logs.dbcmd('update_job_checksum', hc_id, haz_checksum) if ebr: run_job(job_ini, log_level, log_file, exports, hazard_calculation_id=hc_id) else: hc_id = job.id logging.info('Reusing job #%d', job.id) run_job(job_ini, log_level, log_file, exports, hazard_calculation_id=hc_id)
[ "def", "smart_run", "(", "job_ini", ",", "oqparam", ",", "log_level", ",", "log_file", ",", "exports", ",", "reuse_hazard", ")", ":", "haz_checksum", "=", "readinput", ".", "get_checksum32", "(", "oqparam", ",", "hazard", "=", "True", ")", "# retrieve an old calculation with the right checksum, if any", "job", "=", "logs", ".", "dbcmd", "(", "'get_job_from_checksum'", ",", "haz_checksum", ")", "reuse", "=", "reuse_hazard", "and", "job", "and", "os", ".", "path", ".", "exists", "(", "job", ".", "ds_calc_dir", "+", "'.hdf5'", ")", "# recompute the hazard and store the checksum", "ebr", "=", "(", "oqparam", ".", "calculation_mode", "==", "'event_based_risk'", "and", "'gmfs'", "not", "in", "oqparam", ".", "inputs", ")", "if", "ebr", ":", "kw", "=", "dict", "(", "calculation_mode", "=", "'event_based'", ")", "if", "(", "oqparam", ".", "sites", "or", "'sites'", "in", "oqparam", ".", "inputs", "or", "'site_model'", "in", "oqparam", ".", "inputs", ")", ":", "# remove exposure from the hazard", "kw", "[", "'exposure_file'", "]", "=", "''", "else", ":", "kw", "=", "{", "}", "if", "not", "reuse", ":", "hc_id", "=", "run_job", "(", "job_ini", ",", "log_level", ",", "log_file", ",", "exports", ",", "*", "*", "kw", ")", "if", "job", "is", "None", ":", "logs", ".", "dbcmd", "(", "'add_checksum'", ",", "hc_id", ",", "haz_checksum", ")", "elif", "not", "reuse_hazard", "or", "not", "os", ".", "path", ".", "exists", "(", "job", ".", "ds_calc_dir", "+", "'.hdf5'", ")", ":", "logs", ".", "dbcmd", "(", "'update_job_checksum'", ",", "hc_id", ",", "haz_checksum", ")", "if", "ebr", ":", "run_job", "(", "job_ini", ",", "log_level", ",", "log_file", ",", "exports", ",", "hazard_calculation_id", "=", "hc_id", ")", "else", ":", "hc_id", "=", "job", ".", "id", "logging", ".", "info", "(", "'Reusing job #%d'", ",", "job", ".", "id", ")", "run_job", "(", "job_ini", ",", "log_level", ",", "log_file", ",", "exports", ",", "hazard_calculation_id", "=", "hc_id", ")" ]
Run calculations by storing their hazard checksum and reusing previous calculations if requested.
[ "Run", "calculations", "by", "storing", "their", "hazard", "checksum", "and", "reusing", "previous", "calculations", "if", "requested", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/engine.py#L104-L137
193
gem/oq-engine
openquake/hazardlib/gsim/campbell_bozorgnia_2008.py
CampbellBozorgnia2008._get_stddevs
def _get_stddevs(self, C, sites, pga1100, sigma_pga, stddev_types): """ Returns the standard deviations as described in the "ALEATORY UNCERTAINTY MODEL" section of the paper. Equations 13 to 19, pages 147 to 151 """ std_intra = self._compute_intra_event_std(C, sites.vs30, pga1100, sigma_pga) std_inter = C['t_lny'] * np.ones_like(sites.vs30) stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: stddevs.append(self._get_total_sigma(C, std_intra, std_inter)) elif stddev_type == const.StdDev.INTRA_EVENT: stddevs.append(std_intra) elif stddev_type == const.StdDev.INTER_EVENT: stddevs.append(std_inter) return stddevs
python
def _get_stddevs(self, C, sites, pga1100, sigma_pga, stddev_types): """ Returns the standard deviations as described in the "ALEATORY UNCERTAINTY MODEL" section of the paper. Equations 13 to 19, pages 147 to 151 """ std_intra = self._compute_intra_event_std(C, sites.vs30, pga1100, sigma_pga) std_inter = C['t_lny'] * np.ones_like(sites.vs30) stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: stddevs.append(self._get_total_sigma(C, std_intra, std_inter)) elif stddev_type == const.StdDev.INTRA_EVENT: stddevs.append(std_intra) elif stddev_type == const.StdDev.INTER_EVENT: stddevs.append(std_inter) return stddevs
[ "def", "_get_stddevs", "(", "self", ",", "C", ",", "sites", ",", "pga1100", ",", "sigma_pga", ",", "stddev_types", ")", ":", "std_intra", "=", "self", ".", "_compute_intra_event_std", "(", "C", ",", "sites", ".", "vs30", ",", "pga1100", ",", "sigma_pga", ")", "std_inter", "=", "C", "[", "'t_lny'", "]", "*", "np", ".", "ones_like", "(", "sites", ".", "vs30", ")", "stddevs", "=", "[", "]", "for", "stddev_type", "in", "stddev_types", ":", "assert", "stddev_type", "in", "self", ".", "DEFINED_FOR_STANDARD_DEVIATION_TYPES", "if", "stddev_type", "==", "const", ".", "StdDev", ".", "TOTAL", ":", "stddevs", ".", "append", "(", "self", ".", "_get_total_sigma", "(", "C", ",", "std_intra", ",", "std_inter", ")", ")", "elif", "stddev_type", "==", "const", ".", "StdDev", ".", "INTRA_EVENT", ":", "stddevs", ".", "append", "(", "std_intra", ")", "elif", "stddev_type", "==", "const", ".", "StdDev", ".", "INTER_EVENT", ":", "stddevs", ".", "append", "(", "std_inter", ")", "return", "stddevs" ]
Returns the standard deviations as described in the "ALEATORY UNCERTAINTY MODEL" section of the paper. Equations 13 to 19, pages 147 to 151
[ "Returns", "the", "standard", "deviations", "as", "described", "in", "the", "ALEATORY", "UNCERTAINTY", "MODEL", "section", "of", "the", "paper", ".", "Equations", "13", "to", "19", "pages", "147", "to", "151" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2008.py#L300-L321
194
gem/oq-engine
openquake/hazardlib/gsim/campbell_bozorgnia_2008.py
CampbellBozorgnia2008._compute_intra_event_std
def _compute_intra_event_std(self, C, vs30, pga1100, sigma_pga): """ Returns the intra-event standard deviation at the site, as defined in equation 15, page 147 """ # Get intra-event standard deviation at the base of the site profile sig_lnyb = np.sqrt(C['s_lny'] ** 2. - C['s_lnAF'] ** 2.) sig_lnab = np.sqrt(sigma_pga ** 2. - C['s_lnAF'] ** 2.) # Get linearised relationship between f_site and ln PGA alpha = self._compute_intra_event_alpha(C, vs30, pga1100) return np.sqrt( (sig_lnyb ** 2.) + (C['s_lnAF'] ** 2.) + ((alpha ** 2.) * (sig_lnab ** 2.)) + (2.0 * alpha * C['rho'] * sig_lnyb * sig_lnab))
python
def _compute_intra_event_std(self, C, vs30, pga1100, sigma_pga): """ Returns the intra-event standard deviation at the site, as defined in equation 15, page 147 """ # Get intra-event standard deviation at the base of the site profile sig_lnyb = np.sqrt(C['s_lny'] ** 2. - C['s_lnAF'] ** 2.) sig_lnab = np.sqrt(sigma_pga ** 2. - C['s_lnAF'] ** 2.) # Get linearised relationship between f_site and ln PGA alpha = self._compute_intra_event_alpha(C, vs30, pga1100) return np.sqrt( (sig_lnyb ** 2.) + (C['s_lnAF'] ** 2.) + ((alpha ** 2.) * (sig_lnab ** 2.)) + (2.0 * alpha * C['rho'] * sig_lnyb * sig_lnab))
[ "def", "_compute_intra_event_std", "(", "self", ",", "C", ",", "vs30", ",", "pga1100", ",", "sigma_pga", ")", ":", "# Get intra-event standard deviation at the base of the site profile", "sig_lnyb", "=", "np", ".", "sqrt", "(", "C", "[", "'s_lny'", "]", "**", "2.", "-", "C", "[", "'s_lnAF'", "]", "**", "2.", ")", "sig_lnab", "=", "np", ".", "sqrt", "(", "sigma_pga", "**", "2.", "-", "C", "[", "'s_lnAF'", "]", "**", "2.", ")", "# Get linearised relationship between f_site and ln PGA", "alpha", "=", "self", ".", "_compute_intra_event_alpha", "(", "C", ",", "vs30", ",", "pga1100", ")", "return", "np", ".", "sqrt", "(", "(", "sig_lnyb", "**", "2.", ")", "+", "(", "C", "[", "'s_lnAF'", "]", "**", "2.", ")", "+", "(", "(", "alpha", "**", "2.", ")", "*", "(", "sig_lnab", "**", "2.", ")", ")", "+", "(", "2.0", "*", "alpha", "*", "C", "[", "'rho'", "]", "*", "sig_lnyb", "*", "sig_lnab", ")", ")" ]
Returns the intra-event standard deviation at the site, as defined in equation 15, page 147
[ "Returns", "the", "intra", "-", "event", "standard", "deviation", "at", "the", "site", "as", "defined", "in", "equation", "15", "page", "147" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2008.py#L323-L338
195
gem/oq-engine
openquake/hazardlib/gsim/campbell_bozorgnia_2008.py
CampbellBozorgnia2008._compute_intra_event_alpha
def _compute_intra_event_alpha(self, C, vs30, pga1100): """ Returns the linearised functional relationship between fsite and pga1100, determined from the partial derivative defined on equation 17 on page 148 """ alpha = np.zeros_like(vs30, dtype=float) idx = vs30 < C['k1'] if np.any(idx): temp1 = (pga1100[idx] + C['c'] * (vs30[idx] / C['k1']) ** C['n']) ** -1. temp1 = temp1 - ((pga1100[idx] + C['c']) ** -1.) alpha[idx] = C['k2'] * pga1100[idx] * temp1 return alpha
python
def _compute_intra_event_alpha(self, C, vs30, pga1100): """ Returns the linearised functional relationship between fsite and pga1100, determined from the partial derivative defined on equation 17 on page 148 """ alpha = np.zeros_like(vs30, dtype=float) idx = vs30 < C['k1'] if np.any(idx): temp1 = (pga1100[idx] + C['c'] * (vs30[idx] / C['k1']) ** C['n']) ** -1. temp1 = temp1 - ((pga1100[idx] + C['c']) ** -1.) alpha[idx] = C['k2'] * pga1100[idx] * temp1 return alpha
[ "def", "_compute_intra_event_alpha", "(", "self", ",", "C", ",", "vs30", ",", "pga1100", ")", ":", "alpha", "=", "np", ".", "zeros_like", "(", "vs30", ",", "dtype", "=", "float", ")", "idx", "=", "vs30", "<", "C", "[", "'k1'", "]", "if", "np", ".", "any", "(", "idx", ")", ":", "temp1", "=", "(", "pga1100", "[", "idx", "]", "+", "C", "[", "'c'", "]", "*", "(", "vs30", "[", "idx", "]", "/", "C", "[", "'k1'", "]", ")", "**", "C", "[", "'n'", "]", ")", "**", "-", "1.", "temp1", "=", "temp1", "-", "(", "(", "pga1100", "[", "idx", "]", "+", "C", "[", "'c'", "]", ")", "**", "-", "1.", ")", "alpha", "[", "idx", "]", "=", "C", "[", "'k2'", "]", "*", "pga1100", "[", "idx", "]", "*", "temp1", "return", "alpha" ]
Returns the linearised functional relationship between fsite and pga1100, determined from the partial derivative defined on equation 17 on page 148
[ "Returns", "the", "linearised", "functional", "relationship", "between", "fsite", "and", "pga1100", "determined", "from", "the", "partial", "derivative", "defined", "on", "equation", "17", "on", "page", "148" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2008.py#L340-L354
196
gem/oq-engine
openquake/hazardlib/gsim/campbell_bozorgnia_2008.py
CampbellBozorgnia2008Arbitrary._get_total_sigma
def _get_total_sigma(self, C, std_intra, std_inter): """ Returns the total sigma term for the arbitrary horizontal component of ground motion defined by equation 18, page 150 """ return np.sqrt(std_intra ** 2. + std_inter ** 2. + C['c_lny'] ** 2.)
python
def _get_total_sigma(self, C, std_intra, std_inter): """ Returns the total sigma term for the arbitrary horizontal component of ground motion defined by equation 18, page 150 """ return np.sqrt(std_intra ** 2. + std_inter ** 2. + C['c_lny'] ** 2.)
[ "def", "_get_total_sigma", "(", "self", ",", "C", ",", "std_intra", ",", "std_inter", ")", ":", "return", "np", ".", "sqrt", "(", "std_intra", "**", "2.", "+", "std_inter", "**", "2.", "+", "C", "[", "'c_lny'", "]", "**", "2.", ")" ]
Returns the total sigma term for the arbitrary horizontal component of ground motion defined by equation 18, page 150
[ "Returns", "the", "total", "sigma", "term", "for", "the", "arbitrary", "horizontal", "component", "of", "ground", "motion", "defined", "by", "equation", "18", "page", "150" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2008.py#L407-L412
197
gem/oq-engine
openquake/calculators/ucerf_event_based.py
generate_event_set
def generate_event_set(ucerf, background_sids, src_filter, ses_idx, seed): """ Generates the event set corresponding to a particular branch """ serial = seed + ses_idx * TWO16 # get rates from file with h5py.File(ucerf.source_file, 'r') as hdf5: occurrences = ucerf.tom.sample_number_of_occurrences(ucerf.rate, seed) indices, = numpy.where(occurrences) logging.debug( 'Considering "%s", %d ruptures', ucerf.source_id, len(indices)) # get ruptures from the indices ruptures = [] rupture_occ = [] for iloc, n_occ in zip(indices, occurrences[indices]): ucerf_rup = ucerf.get_ucerf_rupture(iloc, src_filter) if ucerf_rup: ucerf_rup.serial = serial serial += 1 ruptures.append(ucerf_rup) rupture_occ.append(n_occ) # sample background sources background_ruptures, background_n_occ = sample_background_model( hdf5, ucerf.idx_set["grid_key"], ucerf.tom, seed, background_sids, ucerf.min_mag, ucerf.npd, ucerf.hdd, ucerf.usd, ucerf.lsd, ucerf.msr, ucerf.aspect, ucerf.tectonic_region_type) for i, brup in enumerate(background_ruptures): brup.serial = serial serial += 1 ruptures.append(brup) rupture_occ.extend(background_n_occ) assert len(ruptures) < TWO16, len(ruptures) # < 2^16 ruptures per SES return ruptures, rupture_occ
python
def generate_event_set(ucerf, background_sids, src_filter, ses_idx, seed): """ Generates the event set corresponding to a particular branch """ serial = seed + ses_idx * TWO16 # get rates from file with h5py.File(ucerf.source_file, 'r') as hdf5: occurrences = ucerf.tom.sample_number_of_occurrences(ucerf.rate, seed) indices, = numpy.where(occurrences) logging.debug( 'Considering "%s", %d ruptures', ucerf.source_id, len(indices)) # get ruptures from the indices ruptures = [] rupture_occ = [] for iloc, n_occ in zip(indices, occurrences[indices]): ucerf_rup = ucerf.get_ucerf_rupture(iloc, src_filter) if ucerf_rup: ucerf_rup.serial = serial serial += 1 ruptures.append(ucerf_rup) rupture_occ.append(n_occ) # sample background sources background_ruptures, background_n_occ = sample_background_model( hdf5, ucerf.idx_set["grid_key"], ucerf.tom, seed, background_sids, ucerf.min_mag, ucerf.npd, ucerf.hdd, ucerf.usd, ucerf.lsd, ucerf.msr, ucerf.aspect, ucerf.tectonic_region_type) for i, brup in enumerate(background_ruptures): brup.serial = serial serial += 1 ruptures.append(brup) rupture_occ.extend(background_n_occ) assert len(ruptures) < TWO16, len(ruptures) # < 2^16 ruptures per SES return ruptures, rupture_occ
[ "def", "generate_event_set", "(", "ucerf", ",", "background_sids", ",", "src_filter", ",", "ses_idx", ",", "seed", ")", ":", "serial", "=", "seed", "+", "ses_idx", "*", "TWO16", "# get rates from file", "with", "h5py", ".", "File", "(", "ucerf", ".", "source_file", ",", "'r'", ")", "as", "hdf5", ":", "occurrences", "=", "ucerf", ".", "tom", ".", "sample_number_of_occurrences", "(", "ucerf", ".", "rate", ",", "seed", ")", "indices", ",", "=", "numpy", ".", "where", "(", "occurrences", ")", "logging", ".", "debug", "(", "'Considering \"%s\", %d ruptures'", ",", "ucerf", ".", "source_id", ",", "len", "(", "indices", ")", ")", "# get ruptures from the indices", "ruptures", "=", "[", "]", "rupture_occ", "=", "[", "]", "for", "iloc", ",", "n_occ", "in", "zip", "(", "indices", ",", "occurrences", "[", "indices", "]", ")", ":", "ucerf_rup", "=", "ucerf", ".", "get_ucerf_rupture", "(", "iloc", ",", "src_filter", ")", "if", "ucerf_rup", ":", "ucerf_rup", ".", "serial", "=", "serial", "serial", "+=", "1", "ruptures", ".", "append", "(", "ucerf_rup", ")", "rupture_occ", ".", "append", "(", "n_occ", ")", "# sample background sources", "background_ruptures", ",", "background_n_occ", "=", "sample_background_model", "(", "hdf5", ",", "ucerf", ".", "idx_set", "[", "\"grid_key\"", "]", ",", "ucerf", ".", "tom", ",", "seed", ",", "background_sids", ",", "ucerf", ".", "min_mag", ",", "ucerf", ".", "npd", ",", "ucerf", ".", "hdd", ",", "ucerf", ".", "usd", ",", "ucerf", ".", "lsd", ",", "ucerf", ".", "msr", ",", "ucerf", ".", "aspect", ",", "ucerf", ".", "tectonic_region_type", ")", "for", "i", ",", "brup", "in", "enumerate", "(", "background_ruptures", ")", ":", "brup", ".", "serial", "=", "serial", "serial", "+=", "1", "ruptures", ".", "append", "(", "brup", ")", "rupture_occ", ".", "extend", "(", "background_n_occ", ")", "assert", "len", "(", "ruptures", ")", "<", "TWO16", ",", "len", "(", "ruptures", ")", "# < 2^16 ruptures per SES", "return", "ruptures", ",", "rupture_occ" ]
Generates the event set corresponding to a particular branch
[ "Generates", "the", "event", "set", "corresponding", "to", "a", "particular", "branch" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_event_based.py#L41-L76
198
gem/oq-engine
openquake/calculators/ucerf_event_based.py
sample_background_model
def sample_background_model( hdf5, branch_key, tom, seed, filter_idx, min_mag, npd, hdd, upper_seismogenic_depth, lower_seismogenic_depth, msr=WC1994(), aspect=1.5, trt=DEFAULT_TRT): """ Generates a rupture set from a sample of the background model :param branch_key: Key to indicate the branch for selecting the background model :param tom: Temporal occurrence model as instance of :class: openquake.hazardlib.tom.TOM :param seed: Random seed to use in the call to tom.sample_number_of_occurrences :param filter_idx: Sites for consideration (can be None!) :param float min_mag: Minimim magnitude for consideration of background sources :param npd: Nodal plane distribution as instance of :class: openquake.hazardlib.pmf.PMF :param hdd: Hypocentral depth distribution as instance of :class: openquake.hazardlib.pmf.PMF :param float aspect: Aspect ratio :param float upper_seismogenic_depth: Upper seismogenic depth (km) :param float lower_seismogenic_depth: Lower seismogenic depth (km) :param msr: Magnitude scaling relation :param float integration_distance: Maximum distance from rupture to site for consideration """ bg_magnitudes = hdf5["/".join(["Grid", branch_key, "Magnitude"])].value # Select magnitudes above the minimum magnitudes mag_idx = bg_magnitudes >= min_mag mags = bg_magnitudes[mag_idx] rates = hdf5["/".join(["Grid", branch_key, "RateArray"])][filter_idx, :] rates = rates[:, mag_idx] valid_locs = hdf5["Grid/Locations"][filter_idx, :] # Sample remaining rates sampler = tom.sample_number_of_occurrences(rates, seed) background_ruptures = [] background_n_occ = [] for i, mag in enumerate(mags): rate_idx = numpy.where(sampler[:, i])[0] rate_cnt = sampler[rate_idx, i] occurrence = rates[rate_idx, i] locations = valid_locs[rate_idx, :] ruptures = generate_background_ruptures( tom, locations, occurrence, mag, npd, hdd, upper_seismogenic_depth, lower_seismogenic_depth, msr, aspect, trt) background_ruptures.extend(ruptures) background_n_occ.extend(rate_cnt.tolist()) return background_ruptures, background_n_occ
python
def sample_background_model( hdf5, branch_key, tom, seed, filter_idx, min_mag, npd, hdd, upper_seismogenic_depth, lower_seismogenic_depth, msr=WC1994(), aspect=1.5, trt=DEFAULT_TRT): """ Generates a rupture set from a sample of the background model :param branch_key: Key to indicate the branch for selecting the background model :param tom: Temporal occurrence model as instance of :class: openquake.hazardlib.tom.TOM :param seed: Random seed to use in the call to tom.sample_number_of_occurrences :param filter_idx: Sites for consideration (can be None!) :param float min_mag: Minimim magnitude for consideration of background sources :param npd: Nodal plane distribution as instance of :class: openquake.hazardlib.pmf.PMF :param hdd: Hypocentral depth distribution as instance of :class: openquake.hazardlib.pmf.PMF :param float aspect: Aspect ratio :param float upper_seismogenic_depth: Upper seismogenic depth (km) :param float lower_seismogenic_depth: Lower seismogenic depth (km) :param msr: Magnitude scaling relation :param float integration_distance: Maximum distance from rupture to site for consideration """ bg_magnitudes = hdf5["/".join(["Grid", branch_key, "Magnitude"])].value # Select magnitudes above the minimum magnitudes mag_idx = bg_magnitudes >= min_mag mags = bg_magnitudes[mag_idx] rates = hdf5["/".join(["Grid", branch_key, "RateArray"])][filter_idx, :] rates = rates[:, mag_idx] valid_locs = hdf5["Grid/Locations"][filter_idx, :] # Sample remaining rates sampler = tom.sample_number_of_occurrences(rates, seed) background_ruptures = [] background_n_occ = [] for i, mag in enumerate(mags): rate_idx = numpy.where(sampler[:, i])[0] rate_cnt = sampler[rate_idx, i] occurrence = rates[rate_idx, i] locations = valid_locs[rate_idx, :] ruptures = generate_background_ruptures( tom, locations, occurrence, mag, npd, hdd, upper_seismogenic_depth, lower_seismogenic_depth, msr, aspect, trt) background_ruptures.extend(ruptures) background_n_occ.extend(rate_cnt.tolist()) return background_ruptures, background_n_occ
[ "def", "sample_background_model", "(", "hdf5", ",", "branch_key", ",", "tom", ",", "seed", ",", "filter_idx", ",", "min_mag", ",", "npd", ",", "hdd", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "msr", "=", "WC1994", "(", ")", ",", "aspect", "=", "1.5", ",", "trt", "=", "DEFAULT_TRT", ")", ":", "bg_magnitudes", "=", "hdf5", "[", "\"/\"", ".", "join", "(", "[", "\"Grid\"", ",", "branch_key", ",", "\"Magnitude\"", "]", ")", "]", ".", "value", "# Select magnitudes above the minimum magnitudes", "mag_idx", "=", "bg_magnitudes", ">=", "min_mag", "mags", "=", "bg_magnitudes", "[", "mag_idx", "]", "rates", "=", "hdf5", "[", "\"/\"", ".", "join", "(", "[", "\"Grid\"", ",", "branch_key", ",", "\"RateArray\"", "]", ")", "]", "[", "filter_idx", ",", ":", "]", "rates", "=", "rates", "[", ":", ",", "mag_idx", "]", "valid_locs", "=", "hdf5", "[", "\"Grid/Locations\"", "]", "[", "filter_idx", ",", ":", "]", "# Sample remaining rates", "sampler", "=", "tom", ".", "sample_number_of_occurrences", "(", "rates", ",", "seed", ")", "background_ruptures", "=", "[", "]", "background_n_occ", "=", "[", "]", "for", "i", ",", "mag", "in", "enumerate", "(", "mags", ")", ":", "rate_idx", "=", "numpy", ".", "where", "(", "sampler", "[", ":", ",", "i", "]", ")", "[", "0", "]", "rate_cnt", "=", "sampler", "[", "rate_idx", ",", "i", "]", "occurrence", "=", "rates", "[", "rate_idx", ",", "i", "]", "locations", "=", "valid_locs", "[", "rate_idx", ",", ":", "]", "ruptures", "=", "generate_background_ruptures", "(", "tom", ",", "locations", ",", "occurrence", ",", "mag", ",", "npd", ",", "hdd", ",", "upper_seismogenic_depth", ",", "lower_seismogenic_depth", ",", "msr", ",", "aspect", ",", "trt", ")", "background_ruptures", ".", "extend", "(", "ruptures", ")", "background_n_occ", ".", "extend", "(", "rate_cnt", ".", "tolist", "(", ")", ")", "return", "background_ruptures", ",", "background_n_occ" ]
Generates a rupture set from a sample of the background model :param branch_key: Key to indicate the branch for selecting the background model :param tom: Temporal occurrence model as instance of :class: openquake.hazardlib.tom.TOM :param seed: Random seed to use in the call to tom.sample_number_of_occurrences :param filter_idx: Sites for consideration (can be None!) :param float min_mag: Minimim magnitude for consideration of background sources :param npd: Nodal plane distribution as instance of :class: openquake.hazardlib.pmf.PMF :param hdd: Hypocentral depth distribution as instance of :class: openquake.hazardlib.pmf.PMF :param float aspect: Aspect ratio :param float upper_seismogenic_depth: Upper seismogenic depth (km) :param float lower_seismogenic_depth: Lower seismogenic depth (km) :param msr: Magnitude scaling relation :param float integration_distance: Maximum distance from rupture to site for consideration
[ "Generates", "a", "rupture", "set", "from", "a", "sample", "of", "the", "background", "model" ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/ucerf_event_based.py#L79-L136
199
gem/oq-engine
openquake/hazardlib/scalerel/wc1994.py
WC1994.get_median_area
def get_median_area(self, mag, rake): """ The values are a function of both magnitude and rake. Setting the rake to ``None`` causes their "All" rupture-types to be applied. """ assert rake is None or -180 <= rake <= 180 if rake is None: # their "All" case return 10.0 ** (-3.49 + 0.91 * mag) elif (-45 <= rake <= 45) or (rake >= 135) or (rake <= -135): # strike slip return 10.0 ** (-3.42 + 0.90 * mag) elif rake > 0: # thrust/reverse return 10.0 ** (-3.99 + 0.98 * mag) else: # normal return 10.0 ** (-2.87 + 0.82 * mag)
python
def get_median_area(self, mag, rake): """ The values are a function of both magnitude and rake. Setting the rake to ``None`` causes their "All" rupture-types to be applied. """ assert rake is None or -180 <= rake <= 180 if rake is None: # their "All" case return 10.0 ** (-3.49 + 0.91 * mag) elif (-45 <= rake <= 45) or (rake >= 135) or (rake <= -135): # strike slip return 10.0 ** (-3.42 + 0.90 * mag) elif rake > 0: # thrust/reverse return 10.0 ** (-3.99 + 0.98 * mag) else: # normal return 10.0 ** (-2.87 + 0.82 * mag)
[ "def", "get_median_area", "(", "self", ",", "mag", ",", "rake", ")", ":", "assert", "rake", "is", "None", "or", "-", "180", "<=", "rake", "<=", "180", "if", "rake", "is", "None", ":", "# their \"All\" case", "return", "10.0", "**", "(", "-", "3.49", "+", "0.91", "*", "mag", ")", "elif", "(", "-", "45", "<=", "rake", "<=", "45", ")", "or", "(", "rake", ">=", "135", ")", "or", "(", "rake", "<=", "-", "135", ")", ":", "# strike slip", "return", "10.0", "**", "(", "-", "3.42", "+", "0.90", "*", "mag", ")", "elif", "rake", ">", "0", ":", "# thrust/reverse", "return", "10.0", "**", "(", "-", "3.99", "+", "0.98", "*", "mag", ")", "else", ":", "# normal", "return", "10.0", "**", "(", "-", "2.87", "+", "0.82", "*", "mag", ")" ]
The values are a function of both magnitude and rake. Setting the rake to ``None`` causes their "All" rupture-types to be applied.
[ "The", "values", "are", "a", "function", "of", "both", "magnitude", "and", "rake", "." ]
8294553a0b8aba33fd96437a35065d03547d0040
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/scalerel/wc1994.py#L33-L52