code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
dbserver.ensure_on() try: calc_id = int(calc_id) except ValueError: # assume calc_id is a pathname calc_id, datadir = datastore.extract_calc_id_datadir(calc_id) status = 'complete' remote = False else: remote = True job = logs.dbcmd('get_job', calc_id) ...
def importcalc(calc_id)
Import a remote calculation into the local database. server, username and password must be specified in an openquake.cfg file. NB: calc_id can be a local pathname to a datastore not already present in the database: in that case it is imported in the db.
6.257043
5.897098
1.061038
# extract dictionaries of coefficients specific to required # intensity measure type and for PGA C = self.COEFFS[imt] # For inslab GMPEs the correction term is fixed at -0.3 dc1 = -0.3 C_PGA = self.COEFFS[PGA()] # compute median pga on rock (vs30=1000), n...
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.
4.171959
4.191787
0.99527
return ((C['theta2'] + C['theta14'] + C['theta3'] * (mag - 7.8)) * np.log(dists.rhypo + self.CONSTS['c4'] * np.exp((mag - 6.) * self.CONSTS['theta9'])) + (C['theta6'] * dists.rhypo)) + C["theta10"]
def _compute_distance_term(self, C, mag, dists)
Computes the distance scaling term, as contained within equation (1b)
7.901997
7.592187
1.040806
global sock if sock is None: sock = zeromq.Socket( 'tcp://%s:%s' % (config.dbserver.host, DBSERVER_PORT), zeromq.zmq.REQ, 'connect').__enter__() # the socket will be closed when the calculation ends res = sock.send((action,) + args) if isinstance(res, paralle...
def dbcmd(action, *args)
A dispatcher to the database server. :param action: database action to perform :param args: arguments
7.508914
8.164474
0.919706
if not hasattr(record, 'hostname'): record.hostname = '-' if not hasattr(record, 'job_id'): record.job_id = self.job_id
def _update_log_record(self, record)
Massage a log record before emitting it. Intended to be used by the custom log handlers defined in this module.
3.988848
3.996055
0.998197
handlers = [LogDatabaseHandler(job_id)] # log on db always if log_file is None: # add a StreamHandler if not already there if not any(h for h in logging.root.handlers if isinstance(h, logging.StreamHandler)): handlers.append(LogStreamHandler(job_id)) else...
def handle(job_id, log_level='info', log_file=None)
Context manager adding and removing log handlers. :param job_id: ID of the current job :param log_level: one of debug, info, warn, error, critical :param log_file: log file path (if None, logs on stdout only)
3.394696
3.427925
0.990306
if config.dbserver.multi_user: job = dbcmd('get_job', -1, username) # can be None return getattr(job, 'id', 0) else: # single user return datastore.get_last_calc_id()
def get_last_calc_id(username=None)
:param username: if given, restrict to it :returns: the last calculation in the database or the datastore
10.244162
9.415932
1.08796
if not logging.root.handlers: # first time logging.basicConfig(level=level) if calc_id == 'job': # produce a calc_id by creating a job in the db calc_id = dbcmd('create_job', datastore.get_datadir()) elif calc_id == 'nojob': # produce a calc_id without creating a job calc_id ...
def init(calc_id='nojob', level=logging.INFO)
1. initialize the root logger (if not already initialized) 2. set the format of the root handlers (if any) 3. return a new calculation ID candidate if calc_id is 'job' or 'nojob' (with 'nojob' the calculation ID is not stored in the database)
3.411689
3.261748
1.04597
# strike slip length = 10.0 ** (-2.57 + 0.62 * mag) seis_wid = 20.0 # estimate area based on length if length < seis_wid: return length ** 2. else: return length * seis_wid
def get_median_area(self, mag, rake)
The values are a function of magnitude.
7.153076
7.288639
0.981401
depths = np.array([ np.zeros_like(lons) + upper_depth, np.zeros_like(lats) + lower_depth ]) mesh = RectangularMesh( np.tile(lons, (2, 1)), np.tile(lats, (2, 1)), depths ) return SimpleFaultSurface(mesh)
def _construct_surface(lons, lats, upper_depth, lower_depth)
Utility method that constructs and return a simple fault surface with top edge specified by `lons` and `lats` and extending vertically from `upper_depth` to `lower_depth`. The underlying mesh is built by repeating the same coordinates (`lons` and `lats`) at the two specified depth levels.
3.001932
2.90238
1.0343
trench = _construct_surface(SUB_TRENCH_LONS, SUB_TRENCH_LATS, 0., 10.) sites = Mesh(lons, lats, None) return np.abs(trench.get_rx_distance(sites))
def _get_min_distance_to_sub_trench(lons, lats)
Compute and return minimum distance between subduction trench and points specified by 'lon' and 'lat' The method creates an instance of :class:`openquake.hazardlib.geo.SimpleFaultSurface` to model the subduction trench. The surface is assumed vertical and extending from 0 to 10 km depth. The 10...
7.808249
5.202763
1.500789
vf = _construct_surface(VOLCANIC_FRONT_LONS, VOLCANIC_FRONT_LATS, 0., 10.) sites = Mesh(lons, lats, None) return vf.get_rx_distance(sites)
def _get_min_distance_to_volcanic_front(lons, lats)
Compute and return minimum distance between volcanic front and points specified by 'lon' and 'lat'. Distance is negative if point is located east of the volcanic front, positive otherwise. The method uses the same approach as :meth:`_get_min_distance_to_sub_trench` but final distance is returned w...
8.699282
10.353076
0.840261
if imt.name == 'PGV': V1 = 10 ** ((-4.021e-5 * x_tr + 9.905e-3) * (H - 30)) V2 = np.maximum(1., (10 ** (-0.012)) * ((rrup / 300.) ** 2.064)) corr = V2 if H > 30: corr *= V1 else: V2 = np.maximum(1., (10 ** (+0.13)) * ((rrup / 300.) ** 3.2)) corr =...
def _apply_subduction_trench_correction(mean, x_tr, H, rrup, imt)
Implement equation for subduction trench correction as described in equation 3.5.2-1, page 3-148 of "Technical Reports on National Seismic Hazard Maps for Japan"
3.381471
3.326967
1.016383
V1 = np.zeros_like(x_vf) if imt.name == 'PGV': idx = x_vf <= 75 V1[idx] = 4.28e-5 * x_vf[idx] * (H - 30) idx = x_vf > 75 V1[idx] = 3.21e-3 * (H - 30) V1 = 10 ** V1 else: idx = x_vf <= 75 V1[idx] = 7.06e-5 * x_vf[idx] * (H - 30) idx = x_vf ...
def _apply_volcanic_front_correction(mean, x_vf, H, imt)
Implement equation for volcanic front correction as described in equation 3.5.2.-2, page 3-149 of "Technical Reports on National Seismic Hazard Maps for Japan"
2.193542
2.158489
1.01624
mean = self._get_mean(imt, rup.mag, rup.hypo_depth, dists.rrup, d=0) stddevs = self._get_stddevs(stddev_types, dists.rrup) mean = self._apply_amplification_factor(mean, sites.vs30) return mean, stddevs
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)
Implements equation 3.5.1-1 page 148 for mean value and equation 3.5.5-2 page 151 for total standard deviation. See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
3.351478
3.585812
0.93465
# clip magnitude at 8.3 as per note at page 3-36 in table Table 3.3.2-6 # in "Technical Reports on National Seismic Hazard Maps for Japan" mag = min(mag, 8.3) if imt.name == 'PGV': mean = ( 0.58 * mag + 0.0038 * hypo_depth + ...
def _get_mean(self, imt, mag, hypo_depth, rrup, d)
Return mean value as defined in equation 3.5.1-1 page 148
4.458847
4.408688
1.011377
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types) std = np.zeros_like(rrup) std[rrup <= 20] = 0.23 idx = (rrup > 20) & (rrup <= 30) std[idx] = 0.23 - 0.03 * np.log10(rrup[idx] / 20) / np.log10(30. / 20...
def _get_stddevs(self, stddev_types, rrup)
Return standard deviations as defined in equation 3.5.5-2 page 151
2.339285
2.322194
1.00736
assert np.all(vs30 == vs30[0]) if abs(vs30[0]-600.) < 1e-10: return mean * np.log(10) elif abs(vs30[0]-400.) < 1e-10: return mean * np.log(10) + np.log(self.AMP_F) elif abs(vs30[0]-800.) < 1e-10: return mean * np.log(10) - np.log(1.25) ...
def _apply_amplification_factor(self, mean, vs30)
Apply amplification factor to scale PGV value from 600 to 400 m/s vs30 and convert mean from base 10 to base e. The scaling factor from 600 m/s to 400 m/s was defined by NIED. The scaling factor from 600 m/s to 800m/s is valid just for the elastic case as no adjustment for kappa was co...
3.426885
3.225914
1.062299
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types) std = np.zeros_like(pgv) std[pgv <= 25] = 0.20 idx = (pgv > 25) & (pgv <= 50) std[idx] = 0.20 - 0.05 * (pgv[idx] - 25) / 25 std[pgv > 50] = 0.1...
def _get_stddevs(self, stddev_types, pgv)
Return standard deviations as defined in equation 3.5.5-1 page 151
2.496996
2.501745
0.998102
mean, stddevs = super().get_mean_and_stddevs( sites, rup, dists, imt, stddev_types) x_tr = _get_min_distance_to_sub_trench(sites.lon, sites.lat) mean = _apply_subduction_trench_correction( mean, x_tr, rup.hypo_depth, dists.rrup, imt) return mean, stddevs
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)
Implements equation 3.5.1-1 page 148 for mean value and equation 3.5.5-1 page 151 for total standard deviation. See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
3.829053
4.314232
0.88754
mean, stddevs = super().get_mean_and_stddevs( sites, rup, dists, imt, stddev_types) x_vf = _get_min_distance_to_volcanic_front(sites.lon, sites.lat) mean = _apply_volcanic_front_correction(mean, x_vf, rup.hypo_depth, imt) return mean, stddevs
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)
Implements equation 3.5.1-1 page 148 for mean value and equation 3.5.5-1 page 151 for total standard deviation. See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
3.719337
4.15396
0.895371
# NB: matplotlib is imported inside since it is a costly import import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.grid(True) ax.set_xlabel('tasks') ax.set_ylabel('GB') start = 0 for task_name, mem in plots: ax.plot(range(start, start + len(mem)), mem, label=task_n...
def make_figure(plots)
:param plots: list of pairs (task_name, memory array)
3.893698
2.976459
1.308164
dstore = util.read(calc_id) plots = [] for task_name in dstore['task_info']: mem = dstore['task_info/' + task_name]['mem_gb'] plots.append((task_name, mem)) plt = make_figure(plots) plt.show()
def plot_memory(calc_id=-1)
Plot the memory occupation
5.445975
5.645708
0.964622
lst = [] # build the export dtype, of the form PGA-0.1, PGA-0.2 ... for imt, imls in imtls.items(): for iml in imls: lst.append(('%s-%s' % (imt, iml), F32)) curves = numpy.zeros(nsites, numpy.dtype(lst)) for sid, pcurve in pmap.items(): curve = curves[sid] id...
def convert_to_array(pmap, nsites, imtls, inner_idx=0)
Convert the probability map into a composite array with header of the form PGA-0.1, PGA-0.2 ... :param pmap: probability map :param nsites: total number of sites :param imtls: a DictArray with IMT and levels :returns: a composite array of lenght nsites
3.623506
3.070353
1.180159
poes = numpy.array(poes) if len(poes.shape) == 0: # `poes` was passed in as a scalar; # convert it to 1D array of 1 element poes = poes.reshape(1) if len(curves.shape) == 1: # `curves` was passed as 1 dimensional array, there is a single site curves = curves.re...
def compute_hazard_maps(curves, imls, poes)
Given a set of hazard curve poes, interpolate a hazard map at the specified ``poe``. :param curves: 2D array of floats. Each row represents a curve, where the values in the row are the PoEs (Probabilities of Exceedance) corresponding to ``imls``. Each curve corresponds to a geographical...
4.83796
4.863406
0.994768
# convert to numpy array and redimension so that it can be broadcast with # the gmvs for computing PoE values; there is a gmv for each rupture # here is an example: imls = [0.03, 0.04, 0.05], gmvs=[0.04750576] # => num_exceeding = [1, 1, 0] coming from 0.04750576 > [0.03, 0.04, 0.05] imls = num...
def _gmvs_to_haz_curve(gmvs, imls, invest_time, duration)
Given a set of ground motion values (``gmvs``) and intensity measure levels (``imls``), compute hazard curve probabilities of exceedance. :param gmvs: A list of ground motion values, as floats. :param imls: A list of intensity measure levels, as floats. :param float invest_time: ...
4.880785
4.606614
1.059517
M, P = len(imtls), len(poes) hmap = probability_map.ProbabilityMap.build(M, P, pmap, dtype=F32) if len(pmap) == 0: return hmap # empty hazard map for i, imt in enumerate(imtls): curves = numpy.array([pmap[sid].array[imtls(imt), 0] for sid in pmap.sids]...
def make_hmap(pmap, imtls, poes)
Compute the hazard maps associated to the passed probability map. :param pmap: hazard curves in the form of a ProbabilityMap :param imtls: DictArray with M intensity measure types :param poes: P PoEs where to compute the maps :returns: a ProbabilityMap with size (N, M, P)
5.180434
4.3554
1.189428
if isinstance(pmap, probability_map.ProbabilityMap): # this is here for compatibility with the # past, it could be removed in the future hmap = make_hmap(pmap, imtls, poes) pdic = general.DictArray({imt: poes for imt in imtls}) return convert_to_array(hmap, nsites, pdic)...
def make_hmap_array(pmap, imtls, poes, nsites)
:returns: a compound array of hazard maps of shape nsites
4.652668
4.468728
1.041161
uhs = numpy.zeros(len(hmap), info['uhs_dt']) for p, poe in enumerate(info['poes']): for m, imt in enumerate(info['imtls']): if imt.startswith(('PGA', 'SA')): uhs[str(poe)][imt] = hmap[:, m, p] return uhs
def make_uhs(hmap, info)
Make Uniform Hazard Spectra curves for each location. :param hmap: array of shape (N, M, P) :param info: a dictionary with keys poes, imtls, uhs_dt :returns: a composite array containing uniform hazard spectra
5.47691
3.630936
1.508402
data = [] for ebr in ebruptures: rup = ebr.rupture self.cmaker.add_rup_params(rup) ruptparams = tuple(getattr(rup, param) for param in self.params) point = rup.surface.get_middle_point() multi_lons, multi_lats = rup.surface.get_surface...
def to_array(self, ebruptures)
Convert a list of ebruptures into an array of dtype RuptureRata.dt
4.053836
3.989175
1.016209
self.nruptures += len(rup_array) offset = len(self.datastore['rupgeoms']) rup_array.array['gidx1'] += offset rup_array.array['gidx2'] += offset previous = self.datastore.get_attr('ruptures', 'nbytes', 0) self.datastore.extend( 'ruptures', rup_array, n...
def save(self, rup_array)
Store the ruptures in array format.
5.858317
5.751989
1.018485
if 'ruptures' not in self.datastore: # for UCERF return codes = numpy.unique(self.datastore['ruptures']['code']) attr = {'code_%d' % code: ' '.join( cls.__name__ for cls in BaseRupture.types[code]) for code in codes} self.datastore.set_at...
def close(self)
Save information about the rupture codes as attributes of the 'ruptures' dataset.
8.40486
5.659595
1.485064
oq = dstore['oqparam'] weights = dstore['weights'][:, 0] eff_time = oq.investigation_time * oq.ses_per_logic_tree_path num_events = countby(dstore['events'].value, 'rlz') periods = return_periods or oq.return_periods or scientific.return_periods( eff_time, max(num_events.values())) ...
def get_loss_builder(dstore, return_periods=None, loss_dt=None)
:param dstore: datastore for an event based risk calculation :returns: a LossCurvesMapsBuilder instance
11.728495
9.946182
1.179196
if '/' not in what: key, spec = what, '' else: key, spec = what.split('/') if spec and not spec.startswith(('ref-', 'sid-')): raise ValueError('Wrong specification in %s' % what) elif spec == '': # export losses for all assets aid...
def parse(self, what)
:param what: can be 'rlz-1/ref-asset1', 'rlz-2/sid-1', ...
3.6281
3.325171
1.091102
writer = writers.CsvWriter(fmt=writers.FIVEDIGITS) ebr = hasattr(self, 'builder') for key in sorted(curves_dict): recs = curves_dict[key] data = [['asset', 'loss_type', 'loss', 'period' if ebr else 'poe']] for li, loss_type in enumerate(self.loss_type...
def export_csv(self, spec, asset_refs, curves_dict)
:param asset_ref: name of the asset :param curves_dict: a dictionary tag -> loss curves
5.03787
4.92031
1.023893
aids, arefs, spec, key = self.parse(what) if key.startswith('rlz'): curves = self.export_curves_rlzs(aids, key) else: # statistical exports curves = self.export_curves_stats(aids, key) return getattr(self, 'export_' + export_type)(spec, arefs, curves)
def export(self, export_type, what)
:param export_type: 'csv', 'json', ... :param what: string describing what to export :returns: list of exported file names
7.10112
7.54105
0.941662
if 'loss_curves-stats' in self.dstore: # classical_risk if self.R == 1: data = self.dstore['loss_curves-stats'][aids] # shape (A, 1) else: data = self.dstore['loss_curves-rlzs'][aids] # shape (A, R) if key.startswith('rlz-'): ...
def export_curves_rlzs(self, aids, key)
:returns: a dictionary key -> record of dtype loss_curve_dt
3.769628
3.615208
1.042714
oq = self.dstore['oqparam'] stats = oq.hazard_stats().items() # pair (name, func) stat2idx = {stat[0]: s for s, stat in enumerate(stats)} if 'loss_curves-stats' in self.dstore: # classical_risk dset = self.dstore['loss_curves-stats'] data = dset[aids] ...
def export_curves_stats(self, aids, key)
:returns: a dictionary rlzi -> record of dtype loss_curve_dt
3.722455
3.530003
1.054519
C = self.COEFFS[imt] C_PGA = self.COEFFS[PGA()] C_AMP = self.AMP_COEFFS[imt] # Gets the PGA on rock - need to convert from g to cm/s/s pga_rock = self._compute_pga_rock(C_PGA, rup.mag, dists.rjb) * 980.665 # Get the mean ground motion value mean = (self...
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. Implements equation 14 of Hong & Goda (2007)
3.421331
3.404528
1.004936
return np.exp(self._compute_linear_magnitude_term(C_PGA, mag) + self._compute_simple_distance_term(C_PGA, rjb))
def _compute_pga_rock(self, C_PGA, mag, rjb)
Returns the PGA (g) on rock, as defined in equation 15
4.992195
5.224727
0.955494
return self._compute_linear_magnitude_term(C, mag) +\ C["b3"] * ((mag - 7.0) ** 2.)
def _compute_nonlinear_magnitude_term(self, C, mag)
Computes the non-linear magnitude term
7.269055
7.310943
0.99427
return C["b4"] * np.log(np.sqrt(rjb ** 2. + C["h"] ** 2.))
def _compute_simple_distance_term(self, C, rjb)
The distance term for the PGA case ignores magnitude (equation 15)
6.901823
5.649414
1.221688
rval = np.sqrt(rjb ** 2. + C["h"] ** 2.) return (C["b4"] + C["b5"] * (mag - 4.5)) * np.log(rval)
def _compute_magnitude_distance_term(self, C, rjb, mag)
Returns the magntude dependent distance term
5.089188
5.056911
1.006383
# Get nonlinear term bnl = self._get_bnl(C_AMP, vs30) # f_nl_coeff = np.log(60.0 / 100.0) * np.ones_like(vs30) idx = pga_rock > 60.0 f_nl_coeff[idx] = np.log(pga_rock[idx] / 100.0) return np.log(np.exp( C_AMP["blin"] * np.log(vs30 / self.CONST...
def _get_site_amplification(self, C_AMP, vs30, pga_rock)
Gets the site amplification term based on equations 7 and 8 of Atkinson & Boore (2006)
4.551487
4.614746
0.986292
# Default case 8d bnl = np.zeros_like(vs30) if np.all(vs30 >= self.CONSTS["Vref"]): return bnl # Case 8a bnl[vs30 < self.CONSTS["v1"]] = C_AMP["b1sa"] # Cade 8b idx = np.logical_and(vs30 > self.CONSTS["v1"], vs30 <...
def _get_bnl(self, C_AMP, vs30)
Gets the nonlinear term, given by equation 8 of Atkinson & Boore 2006
2.151289
2.148534
1.001283
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(C["sigtot"] + np.zeros(stddev_shape)) elif stddev_type == const.StdDev.INTRA_EVE...
def _get_stddevs(self, C, stddev_types, stddev_shape)
Returns the standard deviations given in Table 2
1.968019
1.964371
1.001857
for fname in fnames: try: node = nrml.read(fname) except ValueError as err: print(err) return with open(fname + '.bak', 'wb') as f: f.write(open(fname, 'rb').read()) with open(fname, 'wb') as f: # make sure the xmlns i....
def tidy(fnames)
Reformat a NRML file in a canonical form. That also means reducing the precision of the floats to a standard value. If the file is invalid, a clear error message is shown.
6.159224
5.351033
1.151035
if is_from_fault_source: # for simple and complex fault sources, # rupture surface geometry is represented by a mesh surf_mesh = surface.mesh lons = surf_mesh.lons lats = surf_mesh.lats depths = surf_mesh.depths else: if is_multi_surface: ...
def get_geom(surface, is_from_fault_source, is_multi_surface, is_gridded_surface)
The following fields can be interpreted different ways, depending on the value of `is_from_fault_source`. If `is_from_fault_source` is True, each of these fields should contain a 2D numpy array (all of the same shape). Each triple of (lon, lat, depth) for a given index represents the node of a recta...
2.751593
2.766425
0.994639
all_eids = [] for rup in rup_array: grp_id = rup['grp_id'] samples = samples_by_grp[grp_id] num_rlzs = num_rlzs_by_grp[grp_id] num_events = rup['n_occ'] if samples > 1 else rup['n_occ'] * num_rlzs eids = TWO32 * U64(rup['serial']) + numpy.arange(num_events, dtype=U64...
def get_eids(rup_array, samples_by_grp, num_rlzs_by_grp)
:param rup_array: a composite array with fields serial, n_occ and grp_id :param samples_by_grp: a dictionary grp_id -> samples :param num_rlzs_by_grp: a dictionary grp_id -> num_rlzs
3.026639
2.480789
1.220031
# compute cdf from pmf cdf = numpy.cumsum(self.probs_occur) n_occ = numpy.digitize(numpy.random.random(n), cdf) return n_occ
def sample_number_of_occurrences(self, n=1)
See :meth:`superclass method <.rupture.BaseRupture.sample_number_of_occurrences>` for spec of input and result values. Uses 'Inverse Transform Sampling' method.
5.764899
6.06933
0.949841
j = 0 dic = {} if self.samples == 1: # full enumeration or akin to it for rlzs in rlzs_by_gsim.values(): for rlz in rlzs: dic[rlz] = numpy.arange(j, j + self.n_occ, dtype=U64) + ( TWO32 * U64(self.serial)) ...
def get_eids_by_rlz(self, rlzs_by_gsim)
:param n_occ: number of occurrences :params rlzs_by_gsim: a dictionary gsims -> rlzs array :param samples: number of samples in current source group :returns: a dictionary rlz index -> eids array
3.771306
3.602437
1.046876
all_eids, rlzs = [], [] for rlz, eids in self.get_eids_by_rlz(rlzs_by_gsim).items(): all_eids.extend(eids) rlzs.extend([rlz] * len(eids)) return numpy.fromiter(zip(all_eids, rlzs), events_dt)
def get_events(self, rlzs_by_gsim)
:returns: an array of events with fields eid, rlz
3.482543
2.787791
1.249212
num_events = self.n_occ if self.samples > 1 else self.n_occ * num_rlzs return TWO32 * U64(self.serial) + numpy.arange(num_events, dtype=U64)
def get_eids(self, num_rlzs)
:param num_rlzs: the number of realizations for the given group :returns: an array of event IDs
10.398494
11.180071
0.930092
numpy.random.seed(self.serial) sess = numpy.random.choice(num_ses, len(events)) + 1 events_by_ses = collections.defaultdict(list) for ses, event in zip(sess, events): events_by_ses[ses].append(event) for ses in events_by_ses: events_by_ses[ses] = ...
def get_events_by_ses(self, events, num_ses)
:returns: a dictionary ses index -> events array
2.333844
2.179869
1.070635
rupture = self.rupture events = self.get_events(rlzs_by_gsim) events_by_ses = self.get_events_by_ses(events, num_ses) new = ExportedRupture(self.serial, events_by_ses) new.mesh = mesh[()] if isinstance(rupture.surface, geo.ComplexFaultSurface): new.ty...
def export(self, mesh, rlzs_by_gsim, num_ses)
Yield :class:`Rupture` objects, with all the attributes set, suitable for export in XML format.
2.129582
2.111441
1.008592
with performance.Monitor('to_hdf5') as mon: for input_file in input: if input_file.endswith('.npz'): output = convert_npz_hdf5(input_file, input_file[:-3] + 'hdf5') elif input_file.endswith('.xml'): # for source model files output = convert_x...
def to_hdf5(input)
Convert .xml and .npz files to .hdf5 files.
3.791095
3.433414
1.104177
for source, s_sites in source_site_filter(sources): try: for rupture in source.iter_ruptures(): [n_occ] = rupture.sample_number_of_occurrences() for _ in range(n_occ): yield rupture except Exception as err: etype, err, ...
def stochastic_event_set(sources, source_site_filter=nofilter)
Generates a 'Stochastic Event Set' (that is a collection of earthquake ruptures) representing a possible *realization* of the seismicity as described by a source model. The calculator loops over sources. For each source, it loops over ruptures. For each rupture, the number of occurrence is randomly sam...
3.682089
3.180903
1.157561
if not BaseRupture._code: BaseRupture.init() # initialize rupture codes rups = [] geoms = [] nbytes = 0 offset = 0 for ebrupture in ebruptures: rup = ebrupture.rupture mesh = surface_to_array(rup.surface) sy, sz = mesh.shape[1:] # sanity checks ass...
def get_rup_array(ebruptures, srcfilter=nofilter)
Convert a list of EBRuptures into a numpy composite array, by filtering out the ruptures far away from every site
4.551273
4.625269
0.984002
eb_ruptures = [] numpy.random.seed(sources[0].serial) [grp_id] = set(src.src_group_id for src in sources) # AccumDict of arrays with 3 elements weight, nsites, calc_time calc_times = AccumDict(accum=numpy.zeros(3, numpy.float32)) # Set the parameters required to compute the number of occurr...
def sample_cluster(sources, srcfilter, num_ses, param)
Yields ruptures generated by a cluster of sources. :param sources: A sequence of sources of the same group :param num_ses: Number of stochastic event sets :param param: a dictionary of additional parameters including ses_per_logic_tree_path :yields: dictionaries ...
5.221614
5.068709
1.030167
# AccumDict of arrays with 3 elements weight, nsites, calc_time calc_times = AccumDict(accum=numpy.zeros(3, numpy.float32)) # Compute and save stochastic event sets num_ses = param['ses_per_logic_tree_path'] eff_ruptures = 0 ir_mon = monitor('iter_ruptures', measuremem=False) # Compute ...
def sample_ruptures(sources, srcfilter, param, monitor=Monitor())
:param sources: a sequence of sources of the same group :param srcfilter: SourceFilter instance used also for bounding box post filtering :param param: a dictionary of additional parameters including ses_per_logic_tree_path :param monitor: monitor instance :yields...
4.276579
3.771639
1.133878
data = _get_shakemap_array(grid_file) if uncertainty_file: data2 = _get_shakemap_array(uncertainty_file) # sanity check: lons and lats must be the same for coord in ('lon', 'lat'): numpy.testing.assert_equal(data[coord], data2[coord]) # copy the stddevs from the ...
def get_shakemap_array(grid_file, uncertainty_file=None)
:param grid_file: a shakemap grid file :param uncertainty_file: a shakemap uncertainty_file file :returns: array with fields lon, lat, vs30, val, std
2.978899
3.104834
0.959439
# NB: matplotlib is imported inside since it is a costly import import matplotlib.pyplot as p dstore = util.read(calc_id) sitecol = dstore['sitecol'] lons, lats = sitecol.lons, sitecol.lats if len(lons) > 1 and cross_idl(*lons): lons %= 360 fig, ax = p.subplots() ax.grid(Tr...
def plot_sites(calc_id=-1)
Plot the sites
3.690222
3.693407
0.999138
C = self.COEFFS[imt] imean = (self._get_magnitude_term(C, rup.mag) + self._get_distance_term(C, dists.rrup, sites.backarc) + self._get_site_term(C, sites.vs30) + self._get_scaling_term(C, dists.rrup)) # Convert mean from cm/s and cm/s/...
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.
3.479802
3.473545
1.001801
# Geometric attenuation function distance_scale = -np.log10(np.sqrt(rrup ** 2 + 3600.0)) # Anelastic attenuation in the backarc distance_scale[backarc] += (C["c2"] * rrup[backarc]) # Anelastic Attenuation in the forearc idx = np.logical_not(backarc) dista...
def _get_distance_term(self, C, rrup, backarc)
Returns the distance scaling term, which varies depending on whether the site is in the forearc or the backarc
4.563389
3.987283
1.144486
a_f = 0.15 + 0.0007 * rrup a_f[a_f > 0.35] = 0.35 return C["af"] + a_f
def _get_scaling_term(self, C, rrup)
Applies the Cascadia correction factor from Table 2 and the positive correction factor given on Page 567
6.340125
5.975488
1.061022
# see https://bugs.launchpad.net/oq-engine/+bug/1279247 for an explanation # of the algorithm used result = {'trti': trti, 'num_ruptures': 0} # all the time is spent in collect_bin_data ruptures = [] for src in sources: ruptures.extend(src.iter_ruptures()) bin_data = disagg.coll...
def compute_disagg(sitecol, sources, cmaker, iml4, trti, bin_edges, oqparam, monitor)
:param sitecol: a :class:`openquake.hazardlib.site.SiteCollection` instance :param sources: list of hazardlib source objects :param cmaker: a :class:`openquake.hazardlib.gsim.base.ContextMaker` instance :param iml4: an array of intensities of shape (N, R, M, P) :param dic...
5.97215
5.217347
1.144672
m1 = 6.4 r1 = 50. h = 6. R = np.sqrt(rjb ** 2 + h ** 2) R1 = np.sqrt(r1 ** 2 + h ** 2) less_r1 = rjb < r1 ge_r1 = rjb >= r1 mean = (C['c1'] + C['c4'] * (mag - m1) * np.log(R) + C['c5'] * rjb + C['c8'] * (8.5 - mag) ** 2) ...
def _compute_mean(self, C, mag, rjb)
Compute mean value, see table 2.
2.641412
2.60097
1.015549
''' Returns the adjustment factors (fval, fival) proposed by Hermann (1978) :param float bval: Gutenberg & Richter (1944) b-value :param np.ndarray min_mag: Minimum magnitude of completeness table :param non-negative float mag_inc: Magnitude increment of the completeness t...
def hermann_adjustment_factors(bval, min_mag, mag_inc)
Returns the adjustment factors (fval, fival) proposed by Hermann (1978) :param float bval: Gutenberg & Richter (1944) b-value :param np.ndarray min_mag: Minimum magnitude of completeness table :param non-negative float mag_inc: Magnitude increment of the completeness table
4.820876
1.73625
2.776602
''' Incremental a-value from cumulative - using the version of the Hermann (1979) formula described in Wesson et al. (2003) :param float bval: Gutenberg & Richter (1944) b-value :param np.ndarray min_mag: Minimum magnitude of completeness table :param float mag_inc: Ma...
def incremental_a_value(bval, min_mag, mag_inc)
Incremental a-value from cumulative - using the version of the Hermann (1979) formula described in Wesson et al. (2003) :param float bval: Gutenberg & Richter (1944) b-value :param np.ndarray min_mag: Minimum magnitude of completeness table :param float mag_inc: Magnitude incr...
5.240383
2.003698
2.615356
''' Gets the Weichert adjustment factor for each the magnitude bins :param float beta: Beta value of Gutenberg & Richter parameter (b * log(10.)) :param np.ndarray cmag: Magnitude values of the completeness table :param np.ndarray cyear: Year values of the completeness tab...
def get_weichert_factor(beta, cmag, cyear, end_year)
Gets the Weichert adjustment factor for each the magnitude bins :param float beta: Beta value of Gutenberg & Richter parameter (b * log(10.)) :param np.ndarray cmag: Magnitude values of the completeness table :param np.ndarray cyear: Year values of the completeness table :par...
5.625714
3.183433
1.767184
''' Check to ensure completeness table is in the correct format `completeness_table = np.array([[year_, mag_i]]) for i in number of bins` :param np.ndarray completeness_table: Completeness table in format [[year, mag]] :param catalogue: Instance of openquake.hmtk.seismicity.catalog...
def check_completeness_table(completeness_table, catalogue)
Check to ensure completeness table is in the correct format `completeness_table = np.array([[year_, mag_i]]) for i in number of bins` :param np.ndarray completeness_table: Completeness table in format [[year, mag]] :param catalogue: Instance of openquake.hmtk.seismicity.catalogue.Catalogue...
3.704793
2.071567
1.788401
''' To make the magnitudes evenly spaced, render to a constant 0.1 magnitude unit :param np.ndarray completeness_table: Completeness table in format [[year, mag]] :param catalogue: Instance of openquake.hmtk.seismicity.catalogue.Catalogue class :returns: Correct comple...
def get_even_magnitude_completeness(completeness_table, catalogue=None)
To make the magnitudes evenly spaced, render to a constant 0.1 magnitude unit :param np.ndarray completeness_table: Completeness table in format [[year, mag]] :param catalogue: Instance of openquake.hmtk.seismicity.catalogue.Catalogue class :returns: Correct completeness table
3.053761
2.196669
1.390178
dupl = [] for obj, group in itertools.groupby(sorted(objects), key): if sum(1 for _ in group) > 1: dupl.append(obj) if dupl: raise ValueError('Found duplicates %s' % dupl) return objects
def unique(objects, key=None)
Raise a ValueError if there is a duplicated object, otherwise returns the objects as they are.
3.300337
3.127399
1.055298
effective = [] for uid, group in groupby(rlzs, operator.attrgetter('uid')).items(): rlz = group[0] if all(path == '@' for path in rlz.lt_uid): # empty realization continue effective.append( Realization(rlz.value, sum(r.weight for r in group), ...
def get_effective_rlzs(rlzs)
Group together realizations with the same unique identifier (uid) and yield the first representative of each group.
6.337165
5.69647
1.112472
weights = [] for obj in weighted_objects: w = obj.weight if isinstance(obj.weight, float): weights.append(w) else: weights.append(w['weight']) numpy.random.seed(seed) idxs = numpy.random.choice(len(weights), num_samples, p=weights) # NB: returning...
def sample(weighted_objects, num_samples, seed)
Take random samples of a sequence of weighted objects :param weighted_objects: A finite sequence of objects with a `.weight` attribute. The weights must sum up to 1. :param num_samples: The number of samples to return :param seed: A random seed :return: A subsequ...
2.90482
3.321805
0.87447
n = nrml.read(smlt) try: blevels = n.logicTree except Exception: raise InvalidFile('%s is not a valid source_model_logic_tree_file' % smlt) paths = collections.defaultdict(set) # branchID -> paths applytosources = collections.defaultdict(list) # branc...
def collect_info(smlt)
Given a path to a source model logic tree, collect all of the path names to the source models it contains and build 1. a dictionary source model branch ID -> paths 2. a dictionary source model branch ID -> source IDs in applyToSources :param smlt: source model logic tree file :returns: an Info name...
6.217753
4.523678
1.374491
smodel = nrml.read(fname).sourceModel src_groups = [] if smodel[0].tag.endswith('sourceGroup'): # NRML 0.5 format for sg_node in smodel: sg = SourceGroup(sg_node['tectonicRegion']) sg.sources = sg_node.nodes src_groups.append(sg) else: # NRML 0.4 format...
def read_source_groups(fname)
:param fname: a path to a source model XML file :return: a list of SourceGroup objects containing source nodes
5.29392
4.92266
1.075419
text = uncertainty.text.strip() if not text.startswith('['): # a bare GSIM name was passed text = '[%s]' % text for k, v in uncertainty.attrib.items(): try: v = ast.literal_eval(v) except ValueError: v = repr(v) text += '\n%s = %s' % (k, v) r...
def toml(uncertainty)
Converts an uncertainty node into a TOML string
4.474813
4.006005
1.117026
names = self.names.split() if len(names) == 1: return names[0] elif len(names) == 2: return ' '.join(names) else: return ' '.join([names[0], '...', names[-1]])
def name(self)
Compact representation for the names
2.737685
2.481452
1.103259
src_groups = [] for grp in self.src_groups: sg = copy.copy(grp) sg.sources = [] src_groups.append(sg) return self.__class__(self.names, self.weight, self.path, src_groups, self.num_gsim_paths, self.ordinal, self.samples)
def get_skeleton(self)
Return an empty copy of the source model, i.e. without sources, but with the proper attributes for each SourceGroup contained within.
7.300448
5.022285
1.453611
for path in self._enumerate_paths([]): flat_path = [] weight = 1.0 while path: path, branch = path weight *= branch.weight flat_path.append(branch) yield weight, flat_path[::-1]
def enumerate_paths(self)
Generate all possible paths starting from this branch set. :returns: Generator of two-item tuples. Each tuple contains weight of the path (calculated as a product of the weights of all path's branches) and list of path's :class:`Branch` objects. Total sum of all ...
5.059124
3.90782
1.294615
for branch in self.branches: path = [prefix_path, branch] if branch.child_branchset is not None: for subpath in branch.child_branchset._enumerate_paths(path): yield subpath else: yield path
def _enumerate_paths(self, prefix_path)
Recursive (private) part of :func:`enumerate_paths`. Returns generator of recursive lists of two items, where second item is the branch object and first one is itself list of two items.
3.431244
2.922738
1.173983
for branch in self.branches: if branch.branch_id == branch_id: return branch raise AssertionError("couldn't find branch '%s'" % branch_id)
def get_branch_by_id(self, branch_id)
Return :class:`Branch` object belonging to this branch set with id equal to ``branch_id``.
3.054509
3.127254
0.976738
# pylint: disable=R0911,R0912 for key, value in self.filters.items(): if key == 'applyToTectonicRegionType': if value != source.tectonic_region_type: return False elif key == 'applyToSourceType': if value == 'area': ...
def filter_source(self, source)
Apply filters to ``source`` and return ``True`` if uncertainty should be applied to it.
2.688224
2.626789
1.023388
if not self.filter_source(source): # source didn't pass the filter return 0 if self.uncertainty_type in MFD_UNCERTAINTY_TYPES: self._apply_uncertainty_to_mfd(source.mfd, value) elif self.uncertainty_type in GEOMETRY_UNCERTAINTY_TYPES: self...
def apply_uncertainty(self, value, source)
Apply this branchset's uncertainty with value ``value`` to source ``source``, if it passes :meth:`filters <filter_source>`. This method is not called for uncertainties of types "gmpeModel" and "sourceModel". :param value: The actual uncertainty value of :meth:`sampled <samp...
2.865255
2.569253
1.115209
if self.uncertainty_type == 'simpleFaultDipRelative': source.modify('adjust_dip', dict(increment=value)) elif self.uncertainty_type == 'simpleFaultDipAbsolute': source.modify('set_dip', dict(dip=value)) elif self.uncertainty_type == 'simpleFaultGeometryAbsolute':...
def _apply_uncertainty_to_geometry(self, source, value)
Modify ``source`` geometry with the uncertainty value ``value``
3.22976
3.146883
1.026336
if self.uncertainty_type == 'abGRAbsolute': a, b = value mfd.modify('set_ab', dict(a_val=a, b_val=b)) elif self.uncertainty_type == 'bGRRelative': mfd.modify('increment_b', dict(value=value)) elif self.uncertainty_type == 'maxMagGRRelative': ...
def _apply_uncertainty_to_mfd(self, mfd, value)
Modify ``mfd`` object with uncertainty value ``value``.
2.921812
2.798183
1.044182
num_gsim_paths = 1 if self.num_samples else gsim_lt.get_num_paths() for i, rlz in enumerate(self): yield LtSourceModel( rlz.value, rlz.weight, ('b1',), [], num_gsim_paths, i, 1)
def gen_source_models(self, gsim_lt)
Yield the underlying LtSourceModel, multiple times if there is sampling
8.355865
6.755532
1.236892
return (self.info.applytosources and self.info.applytosources == self.source_ids)
def on_each_source(self)
True if there is an applyToSources for each source.
20.010319
8.589417
2.329648
self.info = collect_info(self.filename) self.source_ids = collections.defaultdict(list) t0 = time.time() for depth, branchinglevel_node in enumerate(tree_node.nodes): self.parse_branchinglevel(branchinglevel_node, depth, validate) dt = time.time() - t0 ...
def parse_tree(self, tree_node, validate)
Parse the whole tree and point ``root_branchset`` attribute to the tree's root.
4.224448
4.193323
1.007423
new_open_ends = set() branchsets = branchinglevel_node.nodes for number, branchset_node in enumerate(branchsets): branchset = self.parse_branchset(branchset_node, depth, number, validate) self.parse_branches(branchset_...
def parse_branchinglevel(self, branchinglevel_node, depth, validate)
Parse one branching level. :param branchinglevel_node: ``etree.Element`` object with tag "logicTreeBranchingLevel". :param depth: The sequential number of this branching level, based on 0. :param validate: Whether or not the branching level, its branchsets an...
3.244989
2.995875
1.083152
uncertainty_type = branchset_node.attrib.get('uncertaintyType') filters = dict((filtername, branchset_node.attrib.get(filtername)) for filtername in self.FILTERS if filtername in branchset_node.attrib) if validate: self.validate_...
def parse_branchset(self, branchset_node, depth, number, validate)
Create :class:`BranchSet` object using data in ``branchset_node``. :param branchset_node: ``etree.Element`` object with tag "logicTreeBranchSet". :param depth: The sequential number of branchset's branching level, based on 0. :param number: Index number of th...
2.478075
2.374397
1.043665
weight_sum = 0 branches = branchset_node.nodes values = [] for branchnode in branches: weight = ~branchnode.uncertaintyWeight weight_sum += weight value_node = node_from_elem(branchnode.uncertaintyModel) if value_node.text is not N...
def parse_branches(self, branchset_node, branchset, validate)
Create and attach branches at ``branchset_node`` to ``branchset``. :param branchset_node: Same as for :meth:`parse_branchset`. :param branchset: An instance of :class:`BranchSet`. :param validate: Whether or not branches' uncertainty values should be validate...
2.566741
2.538838
1.01099
samples_by_lt_path = self.samples_by_lt_path() for i, rlz in enumerate(get_effective_rlzs(self)): smpath = rlz.lt_path num_samples = samples_by_lt_path[smpath] num_gsim_paths = (num_samples if self.num_samples else gsim_lt.get_nu...
def gen_source_models(self, gsim_lt)
Yield empty LtSourceModel instances (one per effective realization)
6.092728
4.991512
1.220618
branchset = self.root_branchset branch_ids = [] while branchset is not None: [branch] = sample(branchset.branches, 1, seed) branch_ids.append(branch.branch_id) branchset = branch.child_branchset modelname = self.root_branchset.get_branch_by_id...
def sample_path(self, seed)
Return the model name and a list of branch ids. :param seed: the seed used for the sampling
3.81218
3.468431
1.099108
if branchset.uncertainty_type == 'sourceModel': return node.text.strip() elif branchset.uncertainty_type == 'abGRAbsolute': [a, b] = node.text.strip().split() return float(a), float(b) elif branchset.uncertainty_type == 'incrementalMFDAbsolute': ...
def parse_uncertainty_value(self, node, branchset)
See superclass' method for description and signature specification. Doesn't change source model file name, converts other values to either pair of floats or a single float depending on uncertainty type.
2.847826
2.777214
1.025426
spacing = node["spacing"] usd, lsd, dip = (~node.upperSeismoDepth, ~node.lowerSeismoDepth, ~node.dip) # Parse the geometry coords = split_coords_2d(~node.LineString.posList) trace = geo.Line([geo.Point(*p) for p in coords]) return trace, ...
def _parse_simple_fault_geometry_surface(self, node)
Parses a simple fault geometry surface
12.71502
11.715296
1.085335
spacing = node["spacing"] edges = [] for edge_node in node.nodes: coords = split_coords_3d(~edge_node.LineString.posList) edges.append(geo.Line([geo.Point(*p) for p in coords])) return edges, spacing
def _parse_complex_fault_geometry_surface(self, node)
Parses a complex fault geometry surface
9.767385
9.192933
1.062488
nodes = [] for key in ["topLeft", "topRight", "bottomRight", "bottomLeft"]: nodes.append(geo.Point(getattr(node, key)["lon"], getattr(node, key)["lat"], getattr(node, key)["depth"])) top_left, top_right, b...
def _parse_planar_geometry_surface(self, node)
Parses a planar geometry surface
2.941027
2.946542
0.998128
_float_re = re.compile(r'^(\+|\-)?(\d+|\d*\.\d+)$') if branchset.uncertainty_type == 'sourceModel': try: for fname in node.text.strip().split(): self.collect_source_model_data( branchnode['branchID'], fname) ex...
def validate_uncertainty_value(self, node, branchnode, branchset)
See superclass' method for description and signature specification. Checks that the following conditions are met: * For uncertainty of type "sourceModel": referenced file must exist and be readable. This is checked in :meth:`collect_source_model_data` along with saving the source m...
2.753863
2.443837
1.12686