Search is not available for this dataset
text stringlengths 75 104k |
|---|
def get_surface_boundaries(self):
"""
:returns: (min_max lons, min_max lats)
"""
min_lon, min_lat, max_lon, max_lat = self.get_bounding_box()
return [[min_lon, max_lon]], [[min_lat, max_lat]] |
def get_middle_point(self):
"""
Compute coordinates of surface middle point.
The actual definition of ``middle point`` depends on the type of
surface geometry.
:return:
instance of :class:`openquake.hazardlib.geo.point.Point`
representing surface middle ... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# get mean and std using the superclass
mean, stddevs = super... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# get mean and std using the superclass
mean, stddevs = super... |
def get_country_code(longname):
"""
:returns: the code of the country contained in `longname`, or a ValuError
>>> for country, code in country2code.items():
... assert get_country_code('Exp_' + country) == code, (country, code)
"""
mo = re.search(REGEX, longname, re.I)
if mo is None:
... |
def from_exposures(expnames):
"""
:returns: a dictionary E??_ -> country
"""
dic = {}
for i, expname in enumerate(expnames, 1):
cc = get_country_code(expname)
dic['E%02d_' % i] = cc
return dic |
def modify(self, modification, parameters):
"""
Apply a single modification to an MFD parameters.
Reflects the modification method and calls it passing ``parameters``
as keyword arguments. See also :attr:`MODIFICATIONS`.
Modifications can be applied one on top of another. The l... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
#... |
def _get_stddevs(self, rup, arias, stddev_types, sites):
"""
Return standard deviations as defined in table 1, p. 200.
"""
stddevs = []
# Magnitude dependent inter-event term (Eq. 13)
if rup.mag < 4.7:
tau = 0.611
elif rup.mag > 7.6:
tau = ... |
def _get_intra_event_sigmas(self, sites):
"""
The intra-event term nonlinear and dependent on both the site class
and the expected ground motion. In this case the sigma coefficients
are determined from the site class as described below Eq. 14
"""
sigma1 = 1.18 * np.ones_l... |
def _compute_magnitude(self, rup, C):
"""
Compute the first term of the equation described on p. 1144:
``c1 + c2 * (M - 6) + c3 * log(M / 6)``
"""
return C['c1'] + C['c2'] * (rup.mag - 6.0) +\
(C['c3'] * np.log(rup.mag / 6.0)) |
def _compute_distance(self, dists, C):
"""
Compute the second term of the equation described on p. 1144:
`` c4 * np.log(sqrt(R ** 2. + h ** 2.)
"""
return C["c4"] * np.log(np.sqrt(dists.rrup ** 2. + C["h"] ** 2.)) |
def _get_site_amplification(self, sites, rup, C):
"""
Compute the third term of the equation described on p. 1144:
``(s11 + s12 * (M - 6)) * Sc + (s21 + s22 * (M - 6)) * Sd`
"""
Sc, Sd = self._get_site_type_dummy_variables(sites)
return (C["s11"] + C["s12"] * (rup.mag - ... |
def _get_site_type_dummy_variables(self, sites):
"""
Get site type dummy variables, ``Sc`` (for soft and stiff soil sites)
and ``Sd`` (for rock sites).
"""
Sc = np.zeros_like(sites.vs30)
Sd = np.zeros_like(sites.vs30)
# Soft soil; Vs30 < 360 m/s. Page 199.
... |
def _get_mechanism(self, rup, C):
"""
Compute the fourth term of the equation described on p. 199:
``f1 * Fn + f2 * Fr``
"""
Fn, Fr = self._get_fault_type_dummy_variables(rup)
return (C['f1'] * Fn) + (C['f2'] * Fr) |
def _get_fault_type_dummy_variables(self, rup):
"""
The original classification considers four style of faulting categories
(normal, strike-slip, reverse-oblique and reverse).
"""
Fn, Fr = 0, 0
if rup.rake >= -112.5 and rup.rake <= -67.5:
# normal
... |
def california_basin_model(vs30):
"""
Returns the centred z1.0 (mu_z1) based on the California model
(equation 11)
"""
coeff = 570.94 ** 4.0
model = (-7.15 / 4.0) * np.log(
((vs30 ** 4.0) + coeff) / ((1360.0 ** 4.0) + coeff)
) - np.log(1000.)
return np.exp(model) |
def japan_basin_model(vs30):
"""
Returns the centred z1.0 (mu_z1) based on the Japan model
(equation 12)
"""
coeff = 412.39 ** 2.0
model = (-5.23 / 2.0) * np.log(
((vs30 ** 2.0) + coeff) / ((1360.0 ** 2.0) + coeff)
) - np.log(1000.)
return np.exp(model) |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
#... |
def _get_pga_on_rock(self, C, rup, dists):
"""
Returns the median PGA on rock, which is a sum of the
magnitude and distance scaling
"""
return np.exp(self._get_magnitude_scaling_term(C, rup) +
self._get_path_scaling(C, dists, rup.mag)) |
def _get_magnitude_scaling_term(self, C, rup):
"""
Returns the magnitude scling term defined in equation (2)
"""
dmag = rup.mag - C["Mh"]
if rup.mag <= C["Mh"]:
mag_term = (C["e4"] * dmag) + (C["e5"] * (dmag ** 2.0))
else:
mag_term = C["e6"] * dmag... |
def _get_style_of_faulting_term(self, C, rup):
"""
Get fault type dummy variables
Fault type (Strike-slip, Normal, Thrust/reverse) is
derived from rake angle.
Rakes angles within 30 of horizontal are strike-slip,
angles from 30 to 150 are reverse, and angles from
... |
def _get_path_scaling(self, C, dists, mag):
"""
Returns the path scaling term given by equation (3)
"""
rval = np.sqrt((dists.rjb ** 2.0) + (C["h"] ** 2.0))
scaling = (C["c1"] + C["c2"] * (mag - self.CONSTS["Mref"])) *\
np.log(rval / self.CONSTS["Rref"])
retur... |
def _get_site_scaling(self, C, pga_rock, sites, period, rjb):
"""
Returns the site-scaling term (equation 5), broken down into a
linear scaling, a nonlinear scaling and a basin scaling term
"""
flin = self._get_linear_site_term(C, sites.vs30)
fnl = self._get_nonlinear_sit... |
def _get_linear_site_term(self, C, vs30):
"""
Returns the linear site scaling term (equation 6)
"""
flin = vs30 / self.CONSTS["Vref"]
flin[vs30 > C["Vc"]] = C["Vc"] / self.CONSTS["Vref"]
return C["c"] * np.log(flin) |
def _get_nonlinear_site_term(self, C, vs30, pga_rock):
"""
Returns the nonlinear site scaling term (equation 7)
"""
v_s = np.copy(vs30)
v_s[vs30 > 760.] = 760.
# Nonlinear controlling parameter (equation 8)
f_2 = C["f4"] * (np.exp(C["f5"] * (v_s - 360.)) -
... |
def _get_basin_depth_term(self, C, sites, period):
"""
In the case of the base model the basin depth term is switched off.
Therefore we return an array of zeros.
"""
return np.zeros(len(sites.vs30), dtype=float) |
def _get_stddevs(self, C, rup, dists, sites, stddev_types):
"""
Returns the aleatory uncertainty terms described in equations (13) to
(17)
"""
stddevs = []
num_sites = len(sites.vs30)
tau = self._get_inter_event_tau(C, rup.mag, num_sites)
phi = self._get_i... |
def _get_inter_event_tau(self, C, mag, num_sites):
"""
Returns the inter-event standard deviation (tau), which is dependent
on magnitude
"""
base_vals = np.zeros(num_sites)
if mag <= 4.5:
return base_vals + C["t1"]
elif mag >= 5.5:
return b... |
def _get_intra_event_phi(self, C, mag, rjb, vs30, num_sites):
"""
Returns the intra-event standard deviation (phi), dependent on
magnitude, distance and vs30
"""
base_vals = np.zeros(num_sites)
# Magnitude Dependent phi (Equation 17)
if mag <= 4.5:
bas... |
def _get_basin_depth_term(self, C, sites, period):
"""
In the case of the base model the basin depth term is switched off.
Therefore we return an array of zeros.
"""
if period < 0.65:
f_dz1 = np.zeros(len(sites.vs30), dtype=float)
else:
f_dz1 = C["... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
C = self.COEFFS[imt]
M = rup.mag - 6
R = np.sqrt(dist... |
def _get_stddevs(self, C, stddev_types, num_sites):
"""
Return total standard deviation.
"""
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
for stddev_type in stddev_types)
if self.DEFINED_FOR_INTENSITY_MEASURE_COMPONENT == 'Random horizon... |
def get_min_max_mag(self):
"""
:returns: minumum and maximum magnitudes from the underlying MFDs
"""
m1s, m2s = [], []
for mfd in self:
m1, m2 = mfd.get_min_max_mag()
m1s.append(m1)
m2s.append(m2)
return min(m1s), max(m2s) |
def modify(self, modification, parameters):
"""
Apply a modification to the underlying point sources, with the
same parameters for all sources
"""
for src in self:
src.modify(modification, parameters) |
def _compute_mean(self, C, mag, ztor, rrup):
"""
Compute mean value as in ``subroutine getGeom`` in ``hazgridXnga2.f``
"""
gc0 = 0.2418
ci = 0.3846
gch = 0.00607
g4 = 1.7818
ge = 0.554
gm = 1.414
mean = (
gc0 + ci + ztor * gch ... |
def abort(job_id):
"""
Abort the given job
"""
job = logs.dbcmd('get_job', job_id) # job_id can be negative
if job is None:
print('There is no job %d' % job_id)
return
elif job.status not in ('executing', 'running'):
print('Job %d is %s' % (job.id, job.status))
r... |
def get_parentparser(parser, description=None, help=True):
"""
:param parser: :class:`argparse.ArgumentParser` instance or None
:param description: string used to build a new parser if parser is None
:param help: flag used to build a new parser if parser is None
:returns: if parser is None the new p... |
def compose(scripts, name='main', description=None, prog=None,
version=None):
"""
Collects together different scripts and builds a single
script dispatching to the subparsers depending on
the first argument, i.e. the name of the subparser to invoke.
:param scripts: a list of script inst... |
def _add(self, name, *args, **kw):
"""
Add an argument to the underlying parser and grow the list
.all_arguments and the set .names
"""
argname = list(self.argdict)[self._argno]
if argname != name:
raise NameError(
'Setting argument %s, but it ... |
def arg(self, name, help, type=None, choices=None, metavar=None,
nargs=None):
"""Describe a positional argument"""
kw = dict(help=help, type=type, choices=choices, metavar=metavar,
nargs=nargs)
default = self.argdict[name]
if default is not NODEFAULT:
... |
def opt(self, name, help, abbrev=None,
type=None, choices=None, metavar=None, nargs=None):
"""Describe an option"""
kw = dict(help=help, type=type, choices=choices, metavar=metavar,
nargs=nargs)
default = self.argdict[name]
if default is not NODEFAULT:
... |
def flg(self, name, help, abbrev=None):
"""Describe a flag"""
abbrev = abbrev or '-' + name[0]
longname = '--' + name.replace('_', '-')
self._add(name, abbrev, longname, action='store_true', help=help) |
def check_arguments(self):
"""Make sure all arguments have a specification"""
for name, default in self.argdict.items():
if name not in self.names and default is NODEFAULT:
raise NameError('Missing argparse specification for %r' % name) |
def callfunc(self, argv=None):
"""
Parse the argv list and extract a dictionary of arguments which
is then passed to the function underlying the script.
"""
if not self.checked:
self.check_arguments()
self.checked = True
namespace = self.parentpar... |
def cumulative_value(self, slip_moment, mmax, mag_value, bbar, dbar):
'''
Returns the rate of events with M > mag_value
:param float slip_moment:
:param float slip_moment:
Product of slip (cm/yr) * Area (cm ^ 2) * shear_modulus (dyne-cm)
:param float mmax:
... |
def _get_a1(bbar, dbar, slip_moment, mmax):
"""
Returns the A1 term (I.4 of Table 2 in Anderson & Luco)
"""
return ((dbar - bbar) / dbar) * (slip_moment / _scale_moment(mmax)) |
def incremental_value(self, slip_moment, mmax, mag_value, bbar, dbar):
"""
Returns the incremental rate of earthquakes with M = mag_value
"""
delta_m = mmax - mag_value
dirac_term = np.zeros_like(mag_value)
dirac_term[np.fabs(delta_m) < 1.0E-12] = 1.0
a_1 = self._... |
def cumulative_value(self, slip_moment, mmax, mag_value, bbar, dbar):
'''
Returns the rate of events with M > mag_value
:param float slip_moment:
Product of slip (cm/yr) * Area (cm ^ 2) * shear_modulus (dyne-cm)
:param float mmax:
Maximum magnitude
:param... |
def _get_a2(bbar, dbar, slip_moment, mmax):
"""
Returns the A2 value defined in II.4 of Table 2
"""
return ((dbar - bbar) / bbar) * (slip_moment / _scale_moment(mmax)) |
def cumulative_value(self, slip_moment, mmax, mag_value, bbar, dbar):
'''
Returns the rate of events with M > mag_value
:param float slip_moment:
Product of slip (cm/yr) * Area (cm ^ 2) * shear_modulus (dyne-cm)
:param float mmax:
Maximum magnitude
:param... |
def _get_a3(bbar, dbar, slip_moment, mmax):
"""
Returns the A3 term (III.4 in Table 4)
"""
return ((dbar * (dbar - bbar)) / (bbar ** 2.)) * (slip_moment /
_scale_moment(mmax)) |
def incremental_value(self, slip_moment, mmax, mag_value, bbar, dbar):
"""
Returns the incremental rate with Mmax = Mag_value
"""
delta_m = mmax - mag_value
a_3 = self._get_a3(bbar, dbar, slip_moment, mmax)
return a_3 * bbar * (np.exp(bbar * delta_m) - 1.0) * (delta_m > 0... |
def setUp(self, mfd_conf):
'''
Input core configuration parameters as specified in the
configuration file
:param dict mfd_conf:
Configuration file containing the following attributes:
* 'Type' - Choose between the 1st, 2nd or 3rd type of recurrence
mo... |
def get_mmax(self, mfd_conf, msr, rake, area):
'''
Gets the mmax for the fault - reading directly from the config file
or using the msr otherwise
:param dict mfd_config:
Configuration file (see setUp for paramters)
:param msr:
Instance of :class:`nhlib.s... |
def get_mfd(self, slip, area, shear_modulus=30.0):
'''
Calculates activity rate on the fault
:param float slip:
Slip rate in mm/yr
:param fault_area:
Width of the fault (km)
:param float shear_modulus:
Shear modulus of the fault (GPa)
... |
def reduce_sm(calc_id):
"""
Reduce the source model of the given (pre)calculation by discarding all
sources that do not contribute to the hazard.
"""
with datastore.read(calc_id) as dstore:
oqparam = dstore['oqparam']
info = dstore['source_info'].value
ok = info['weight'] > 0... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
C = self.COEFFS[imt]
mean = (
self._get_magnitude_... |
def _get_magnitude_term(self, C, mag):
"""
Returns the magnitude scaling term.
"""
lny = C['C1'] + (C['C3'] * ((8.5 - mag) ** 2.))
if mag > 6.3:
return lny + (-C['H'] * C['C5']) * (mag - 6.3)
else:
return lny + C['C2'] * (mag - 6.3) |
def _get_distance_term(self, C, mag, rrup):
"""
Returns the distance scaling term
"""
return (C['C4'] + C['C5'] * (mag - 6.3)) *\
np.log(np.sqrt(rrup ** 2. + np.exp(C['H']) ** 2.)) |
def _get_style_of_faulting_term(self, C, rake):
"""
Returns the style of faulting factor
"""
f_n, f_r = self._get_fault_type_dummy_variables(rake)
return C['C6'] * f_n + C['C7'] * f_r |
def _get_fault_type_dummy_variables(self, rake):
"""
Defines the fault type dummy variables for normal faulting (f_n) and
reverse faulting (f_r) from rake. Classification based on that
found in the original fortran code of Lin (2009)
"""
f_n, f_r = 0, 0
if rake >=... |
def _get_stddevs(self, C, stddev_types, nsites):
"""
Compute total standard deviation, see table 4.2, page 50.
"""
stddevs = []
for stddev_type in stddev_types:
assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
if stddev_type == const.StdDev.... |
def imt2tup(string):
"""
>>> imt2tup('PGA')
('PGA',)
>>> imt2tup('SA(1.0)')
('SA', 1.0)
>>> imt2tup('SA(1)')
('SA', 1.0)
"""
s = string.strip()
if not s.endswith(')'):
# no parenthesis, PGA is considered the same as PGA()
return (s,)
name, rest = s.split('(', ... |
def with_slots(cls):
"""
Decorator for a class with _slots_. It automatically defines
the methods __eq__, __ne__, assert_equal.
"""
def _compare(self, other):
for slot in self.__class__._slots_:
attr = operator.attrgetter(slot)
source = attr(self)
target =... |
def make_iml4(R, iml_disagg, imtls=None, poes_disagg=(None,), curves=()):
"""
:returns: an ArrayWrapper over a 4D array of shape (N, R, M, P)
"""
if imtls is None:
imtls = {imt: [iml] for imt, iml in iml_disagg.items()}
N = len(curves) or 1
M = len(imtls)
P = len(poes_disagg)
arr... |
def collect_bin_data(ruptures, sitecol, cmaker, iml4,
truncation_level, n_epsilons, monitor=Monitor()):
"""
:param ruptures: a list of ruptures
:param sitecol: a SiteCollection instance
:param cmaker: a ContextMaker instance
:param iml4: an ArrayWrapper of intensities of shape (... |
def lon_lat_bins(bb, coord_bin_width):
"""
Define bin edges for disaggregation histograms.
Given bins data as provided by :func:`collect_bin_data`, this function
finds edges of histograms, taking into account maximum and minimum values
of magnitude, distance and coordinates as well as requested siz... |
def get_shape(bin_edges, sid):
"""
:returns:
the shape of the disaggregation matrix for the given site, of form
(#mags-1, #dists-1, #lons-1, #lats-1, #eps-1)
"""
mag_bins, dist_bins, lon_bins, lat_bins, eps_bins = bin_edges
return (len(mag_bins) - 1, len(dist_bins) - 1,
l... |
def build_disagg_matrix(bdata, bin_edges, sid, mon=Monitor):
"""
:param bdata: a dictionary of probabilities of no exceedence
:param bin_edges: bin edges
:param sid: site index
:param mon: a Monitor instance
:returns: a dictionary key -> matrix|pmf for each key in bdata
"""
with mon('bui... |
def _digitize_lons(lons, lon_bins):
"""
Return indices of the bins to which each value in lons belongs.
Takes into account the case in which longitude values cross the
international date line.
:parameter lons:
An instance of `numpy.ndarray`.
:parameter lons_bins:
An instance of ... |
def disaggregation(
sources, site, imt, iml, gsim_by_trt, truncation_level,
n_epsilons, mag_bin_width, dist_bin_width, coord_bin_width,
source_filter=filters.nofilter, filter_distance='rjb'):
"""
Compute "Disaggregation" matrix representing conditional probability of an
intensity mes... |
def mag_pmf(matrix):
"""
Fold full disaggregation matrix to magnitude PMF.
:returns:
1d array, a histogram representing magnitude PMF.
"""
nmags, ndists, nlons, nlats, neps = matrix.shape
mag_pmf = numpy.zeros(nmags)
for i in range(nmags):
mag_pmf[i] = numpy.prod(
... |
def trt_pmf(matrices):
"""
Fold full disaggregation matrix to tectonic region type PMF.
:param matrices:
a matrix with T submatrices
:returns:
an array of T probabilities one per each tectonic region type
"""
ntrts, nmags, ndists, nlons, nlats, neps = matrices.shape
pmf = nu... |
def lon_lat_trt_pmf(matrices):
"""
Fold full disaggregation matrices to lon / lat / TRT PMF.
:param matrices:
a matrix with T submatrices
:returns:
3d array. First dimension represents longitude histogram bins,
second one latitude histogram bins, third one trt histogram bins.
... |
def db(cmd, args=()):
"""
Run a database command
"""
if cmd not in commands:
okcmds = '\n'.join(
'%s %s' % (name, repr(' '.join(args)) if args else '')
for name, args in sorted(commands.items()))
print('Invalid command "%s": choose one from\n%s' % (cmd, okcmds))
... |
def get_area(self):
'''
Calculates the area of the fault (km ** 2.) as the product of length
(km) and downdip width (km)
'''
d_z = self.lower_depth - self.upper_depth
self.downdip_width = d_z / np.sin(self.dip * np.pi / 180.)
self.surface_width = self.downdip_widt... |
def download_shakemap(id):
"""
Example of usage: utils/shakemap usp000fjta
"""
with performance.Monitor('shakemap', measuremem=True) as mon:
dest = '%s.npy' % id
numpy.save(dest, download_array(id))
print(mon)
print('Saved %s' % dest) |
def mean_curve(values, weights=None):
"""
Compute the mean by using numpy.average on the first axis.
"""
if weights is None:
weights = [1. / len(values)] * len(values)
if not isinstance(values, numpy.ndarray):
values = numpy.array(values)
return numpy.average(values, axis=0, weig... |
def quantile_curve(quantile, curves, weights=None):
"""
Compute the weighted quantile aggregate of a set of curves.
:param quantile:
Quantile value to calculate. Should be in the range [0.0, 1.0].
:param curves:
Array of R PoEs (possibly arrays)
:param weights:
Array-like of... |
def compute_pmap_stats(pmaps, stats, weights, imtls):
"""
:param pmaps:
a list of R probability maps
:param stats:
a sequence of S statistic functions
:param weights:
a list of ImtWeights
:param imtls:
a DictArray of intensity measure types
:returns:
a pro... |
def compute_stats(array, stats, weights):
"""
:param array:
an array of R elements (which can be arrays)
:param stats:
a sequence of S statistic functions
:param weights:
a list of R weights
:returns:
an array of S elements (which can be arrays)
"""
result = n... |
def compute_stats2(arrayNR, stats, weights):
"""
:param arrayNR:
an array of (N, R) elements
:param stats:
a sequence of S statistic functions
:param weights:
a list of R weights
:returns:
an array of (N, S) elements
"""
newshape = list(arrayNR.shape)
if n... |
def apply_stat(f, arraylist, *extra, **kw):
"""
:param f: a callable arraylist -> array (of the same shape and dtype)
:param arraylist: a list of arrays of the same shape and dtype
:param extra: additional positional arguments
:param kw: keyword arguments
:returns: an array of the same shape and... |
def set_rlzs_stats(dstore, prefix, arrayNR=None):
"""
:param dstore: a DataStore object
:param prefix: dataset prefix
:param arrayNR: an array of shape (N, R, ...)
"""
if arrayNR is None:
# assume the -rlzs array is already stored
arrayNR = dstore[prefix + '-rlzs'].value
else... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
... |
def _compute_term1(self, C, mag):
"""
Compute magnitude dependent terms (2nd and 3rd) in equation 3
page 46.
"""
mag_diff = mag - 6
return C['c2'] * mag_diff + C['c3'] * mag_diff ** 2 |
def _compute_term2(self, C, mag, rjb):
"""
Compute distance dependent terms (4th, 5th and 6th) in equation 3
page 46. The factor 'RM' is computed according to the 2002 model
(equation 4-3).
"""
RM = np.sqrt(rjb ** 2 + (C['c7'] ** 2) *
np.exp(-1.25 + 0... |
def _compute_mean(self, C, mag, rjb):
"""
Compute mean value according to equation 3, page 46.
"""
mean = (C['c1'] +
self._compute_term1(C, mag) +
self._compute_term2(C, mag, rjb))
return mean |
def _compute_stddevs(self, C, mag, rjb, imt, stddev_types):
"""
Compute total standard deviation, equations 5 and 6, page 48.
"""
# aleatory uncertainty
sigma_ale_m = np.interp(mag, [5.0, 5.5, 8.0],
[C['m50'], C['m55'], C['m80']])
sigma_ale... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stds_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# Prepare sites
sites_rock = copy.deepcopy(sites)
sites_... |
def BA08_AB06(self, vs30, imt, pgar):
"""
Computes amplification factor similarly to what is done in the 2015
version of the Canada building code. An initial version of this code
was kindly provided by Michal Kolaj - Geological Survey of Canada
:param vs30:
Can be ei... |
def scenario_damage(riskinputs, riskmodel, param, monitor):
"""
Core function for a damage computation.
:param riskinputs:
:class:`openquake.risklib.riskinput.RiskInput` objects
:param riskmodel:
a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance
:param monitor:
... |
def form(value):
"""
Format numbers in a nice way.
>>> form(0)
'0'
>>> form(0.0)
'0.0'
>>> form(0.0001)
'1.000E-04'
>>> form(1003.4)
'1,003'
>>> form(103.4)
'103'
>>> form(9.3)
'9.30000'
>>> form(-1.2)
'-1.2'
"""
if isinstance(value, FLOAT + INT):... |
def rst_table(data, header=None, fmt=None):
"""
Build a .rst table from a matrix.
>>> tbl = [['a', 1], ['b', 2]]
>>> print(rst_table(tbl, header=['Name', 'Value']))
==== =====
Name Value
==== =====
a 1
b 2
==== =====
"""
if header is None and hasattr(da... |
def sum_tbl(tbl, kfield, vfields):
"""
Aggregate a composite array and compute the totals on a given key.
>>> dt = numpy.dtype([('name', (bytes, 10)), ('value', int)])
>>> tbl = numpy.array([('a', 1), ('a', 2), ('b', 3)], dt)
>>> sum_tbl(tbl, 'name', ['value'])['value']
array([3, 3])
"""
... |
def view_slow_sources(token, dstore, maxrows=20):
"""
Returns the slowest sources
"""
info = dstore['source_info'].value
info.sort(order='calc_time')
return rst_table(info[::-1][:maxrows]) |
def view_contents(token, dstore):
"""
Returns the size of the contents of the datastore and its total size
"""
try:
desc = dstore['oqparam'].description
except KeyError:
desc = ''
data = sorted((dstore.getsize(key), key) for key in dstore)
rows = [(key, humansize(nbytes)) for... |
def view_job_info(token, dstore):
"""
Determine the amount of data transferred from the controller node
to the workers and back in a classical calculation.
"""
data = [['task', 'sent', 'received']]
for task in dstore['task_info']:
dset = dstore['task_info/' + task]
if 'argnames' ... |
def avglosses_data_transfer(token, dstore):
"""
Determine the amount of average losses transferred from the workers to the
controller node in a risk calculation.
"""
oq = dstore['oqparam']
N = len(dstore['assetcol'])
R = dstore['csm_info'].get_num_rlzs()
L = len(dstore.get_attr('risk_mod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.