openquake.hazardlib package#

Subpackages#

source_reader module#

openquake.hazardlib.source_reader.add_bangs(smdict)[source]#

Discriminate different sources with same ID (false duplicates) and put an exclamation mark in their source ID

openquake.hazardlib.source_reader.add_checksums(srcs)[source]#

Build and attach a checksum to each source

openquake.hazardlib.source_reader.add_semicolons(src_groups)[source]#

Add semicolons to differentiate different sources with the same source_id and then sort the sources in each group by extended source_id

openquake.hazardlib.source_reader.build_csm(oq, full_lt, smdict, dstore)[source]#
Parameters:
  • oq – OqParam instance

  • full_lt – FullLogicTree instance

  • smdict – dictionary source_model_path -> SourceModel instance

  • dstore – DataStore instance

Returns:

a CompositeSourceModel instance

openquake.hazardlib.source_reader.build_groups(full_lt, rlz_groups, oq, dstore=None)[source]#

Build the source groups without applying the uncertainties, as needed by the workers. The uncertainties to be applied in each realization are not known until the workers, so the realizations with different uncertainties are stored in the field ts of the ts_samples of each source (see get_ts_sets).

openquake.hazardlib.source_reader.check_branchID(branchID)[source]#

Forbids invalid characters .:; used in fragmentno

openquake.hazardlib.source_reader.check_duplicates(smdict, strict)[source]#
openquake.hazardlib.source_reader.check_mfd_variants(smdict, fname)[source]#

Log a warning if a source appears in different source model files with the same ID and the same content except the MFD: then the copies are computed separately, once per file, while they could be computed together, sharing the contexts, if the MFDs were given as uncertainties in the source model logic tree (see make_results). For instance in the IND model the HimalayanThrust source is defined in 3 files (himalaya_cut, himalaya_area, himalaya_m55) with different incrementalMFDs and it takes 64% of the time of the calculation.

Parameters:
  • smdict – a dictionary source model file -> SourceModel

  • fname – the source model logic tree file, used in the warning

Returns:

the list of the IDs of the sources with MFD variants

NB: must be called after add_bangs, which adds the branch to the sources and a bang to the IDs of the sources with the same ID and a different content

openquake.hazardlib.source_reader.check_same_sources(smdict, fname)[source]#

Log a warning if the same source (i.e. a source with the same content) appears in different source models with different IDs: then the engine cannot recognize the copies as the same source, i.e. it cannot reduce them (see reduce_sources), and the source is computed once per source model. It is an error in oq check_input. A different warning is logged if the sources have the same geometry but different MFDs and different IDs: they could be computed together if they had the same ID and the MFDs were uncertainties of the logic tree, see check_mfd_variants.

Parameters:
  • smdict – a dictionary source model file -> SourceModel

  • fname – the source model logic tree file, used in the warning

openquake.hazardlib.source_reader.check_unique(ids, msg='', strict=True)[source]#

Raise a DuplicatedID exception if there are duplicated IDs

openquake.hazardlib.source_reader.collect_sources(full_lt, rlz_groups)[source]#
Parameters:
  • full_lt – a FullLogicTree instance

  • rlz_groups – an iterator of (sm_rlz, source group) pairs

Returns:

a dictionary id(grp) -> [grp, {id(src): (src, pairs)}], where pairs is a list of (trt_smr, samples, signature) tuples, one per realization of the source

openquake.hazardlib.source_reader.content_hash(src, exclude={'branch', 'bysrc_unc', 'checksum', 'name', 'sigts', 'source_id', 'ts_samples', 'width_of_mfd_bin'})[source]#
Parameters:
  • src – a source object

  • exclude – the attributes to ignore

Returns:

the md5 hex digest of the other attributes of the source

NB: by default the ID and the name are ignored, i.e. two copies of the same source with different IDs or names have the same hash

openquake.hazardlib.source_reader.create_source_info(csm, h5)[source]#

Creates source_info, trt_smrs, toms

openquake.hazardlib.source_reader.fix_geometry_sections(smdict, src_groups, hdf5path='', site1=None, split=True)[source]#

If there are MultiFaultSources, fix the sections according to the GeometryModels (if any).

openquake.hazardlib.source_reader.gen_groups(full_lt, smdict, rlz)[source]#
openquake.hazardlib.source_reader.get_bset_values(full_lt, sources)[source]#
Parameters:
  • full_lt – a FullLogicTree instance

  • sources – a SourceGroup or a list of sources of the same group

Returns:

the dictionary of uncertainties to apply expected by modified_groups, i.e. one entry for each set of realizations with the same uncertainties; the uncertainties of a set are the ones of its first realization

NB: only the uncertainties relevant for the given sources are

returned, i.e. the ones of their realizations, without the branchsets applied to other sources, since the logic tree can be huge and the dictionary is sent to the workers

openquake.hazardlib.source_reader.get_core_size(core_trt_smrs, full_lt)[source]#
Parameters:
  • core_trt_smrs – the sets of realizations with the same uncertainties, as returned by get_core_trt_smrs

  • full_lt – a FullLogicTree instance

Returns:

the core size Gt = Σ_i G(trt_i) of the logic tree, i.e. the number of distinct rate components, i.e. of gids (see FullLogicTree.get_gids), which is >= len(core_trt_smrs) since each unit contributes G(trt_i) >= 1 gids

openquake.hazardlib.source_reader.get_core_trt_smrs(groups)[source]#
Parameters:

groups – a list of SourceGroups built without applying the uncertainties (i.e. the src_groups of a CompositeSourceModel)

Returns:

a sorted list of trt_smrs (to be stored as hdf5.vuint32)

The uncertainties are applied in the workers, so the realizations with different uncertainties are not separated at build time (see build_groups). The rates are nevertheless computed separately for each set of uncertainties and must be attributed to the right realizations, hence this extra list; a rate is attributed to the unit containing its trt_smrs.

openquake.hazardlib.source_reader.get_csm(oq, full_lt, dstore=None)[source]#

Build a CompositeSourceModel without applying the uncertainties, that are applied in the workers, see modified_groups.

openquake.hazardlib.source_reader.modified_groups(sources, bset_values)[source]#

Apply the uncertainties to a group of sources built without them, as needed by the workers computing the rates or the ruptures: this is done one set of realizations at a time, i.e. one set with the same uncertainties at a time (see build_groups).

Parameters:
  • sources – a SourceGroup or a list of sources of the same group

  • bset_values – the uncertainties to apply, as returned by get_bset_values; it can be empty, if there are no uncertainties at all

Returns:

a generator of (trt_smrs, group) pairs, one for each set of realizations with the same uncertainties, with the uncertainties applied and the ts_samples restricted to the set of realizations

openquake.hazardlib.source_reader.read_source_model(fname, branch, converter, applied, sample, stride, monitor)[source]#
Parameters:
  • fname – path to a source model XML file

  • branch – source model logic tree branch ID

  • converter – SourceConverter

  • applied – list of source IDs within applyToSources

  • sample – a string with the sampling factor (if any)

  • stride – None or a pair (k, n) to keep only the k-th source over n

  • monitor – a Monitor instance

Returns:

a dictionary (fname, k) -> SourceModel

openquake.hazardlib.source_reader.reduce_sources(sources_with_same_id)[source]#
Parameters:

sources_with_same_id – a list of sources with the same source_id

Returns:

a list of truly unique sources

openquake.hazardlib.source_reader.save_read_times(dstore, source_models)[source]#

Store how many seconds it took to read each source model file in a table (fname, rtime)

openquake.hazardlib.source_reader.source_with_ts_sets(src, pairs, sigrows)[source]#
Parameters:
  • src – a source

  • pairs – a list of (trt_smr, samples, signature) tuples, one per realization of the source

  • sigrows – a list of rows describing the uncertainty signatures, extended with the signatures of the source

Returns:

a copy of the source with the attributes ts_samples and bysrc_unc set, i.e. the sets of realizations with the same uncertainties are stored in the field ts

openquake.hazardlib.source_reader.splitMF(sources, disagg_by_src, blocksize=1000)[source]#

Split the MultiPointSources to avoid oceanic sources with 160M ruptures hanging during rupture sampling

openquake.hazardlib.source_reader.split_by_tom(sources)[source]#

Groups together sources with the same TOM and collect multifault sources

openquake.hazardlib.source_reader.store_data(oq, smdict, csm, dstore)[source]#

Create src_mutex, grp_probability in calc_XXX.hdf5 and sources and mf_sections in calc_XXX_tmp.hdf5

openquake.hazardlib.source_reader.store_unc_signatures(groups, sigrows, full_lt, oq, dstore=None)[source]#

Store the uncertainty signatures of the sources in the datastore, so that they can be printed by oq check_input (see the check_input command) and read back with oq show unc_signatures. NB: the signatures are stored as JSON objects, so that the unc_signatures view can display a column for each branchset.

Parameters:
  • groups – a list of SourceGroups built without the uncertainties

  • sigrows – a list of dicts with keys source_id, realizations, signature (a dictionary branchset_id -> value) and count

  • full_lt – a FullLogicTree instance

  • oq – an OqParam instance

  • dstore – a DataStore instance or None

openquake.hazardlib.source_reader.trt_smrs(src)[source]#
openquake.hazardlib.source_reader.ts_samples(samples, trt_smr)[source]#
Returns:

a structured array (trt_smr, samples) of length 1

openquake.hazardlib.source_reader.unc_signature(bset_values, src)[source]#
Returns:

a tuple identifying the uncertainties applied to src

logictree module#

Source model logic tree parser, verifier and processor, and the full logic tree combining the source model, GSIM and extra logic trees. The common interface of the logic trees and their hierarchy are documented in openquake.hazardlib.lt.

class openquake.hazardlib.logictree.FullLogicTree(source_model_lt, gsim_lt, oversampling='tolerate', extra_lt=None)[source]#

Bases: AbstractLogicTree

The full logic tree as composition of

Parameters:
classmethod fake(gsimlt=None)[source]#
Returns:

a fake FullLogicTree instance with the given gsim logic tree object; if None, builds automatically a fake gsim logic tree

g_weights(unique_trt_smrs)[source]#
Returns:

an array of weights of shape (Gt, 1) or (Gt, M+1)

get_bset_values(ordinal)[source]#
Parameters:

ordinal – the ordinal of a source model realization

Returns:

the list of (branchset, value) pairs whose uncertainties must be applied in the given realization, see build_groups

get_gids(unique_trt_smrs)[source]#
Returns:

list of of arrays of gids, one for each source group

get_num_paths()[source]#
Returns:

number of the paths in the full logic tree

get_num_potential_paths()[source]#
Returns:

the number of potential realizations

get_realizations()[source]#
Returns:

the complete list of LtRealizations

get_rlzs_by_gsim(trt_smr)[source]#
Parameters:

trt_smr – index or array of indices

Returns:

a dictionary gsim -> array of rlz indices

get_rlzs_by_gsim_dic()[source]#
Returns:

a dictionary trt_smr -> gsim -> rlz ordinals

get_trt_rlzs(unique_trt_smrs)[source]#
Returns:

a list with Gt arrays of dtype uint32

get_trt_smrs(src_id=None)[source]#
Returns:

a tuple of indices trt_smr for the given source

gsim_by_trt(rlz)[source]#
Returns:

a dictionary trt->gsim for the given realization

init()[source]#
property num_samples#
Returns:

the source_model_lt num_samples parameter

oversampling = 'tolerate'#
property rlzs#
Returns:

an array of realizations

sample(n, seed, sampling_method='early_weights')[source]#
Parameters:
  • n – number of samples, must be positive

  • seed – random seed, used for the source model, the GSIMs (seed + 1) and the extra logic tree (seed + 2)

  • sampling_method – by default ‘early_weights’

Returns:

n realizations, as get_realizations does with number_of_logic_tree_samples=n; the tree is not modified

property sampling_method#
Returns:

the source_model_lt sampling_method parameter

property sd#
property seed#
Returns:

the source_model_lt seed

trt_by(trt_smr)[source]#
Returns:

the TRT associated to trt_smr

property xR#
Returns:

number of extra logic tree realizations (1 if none)

class openquake.hazardlib.logictree.Info(smpaths, h5paths, applytosources)#

Bases: tuple

applytosources#

Alias for field number 2

h5paths#

Alias for field number 1

smpaths#

Alias for field number 0

class openquake.hazardlib.logictree.LtRealization(ordinal, sm_lt_path, gsim_rlz, weight, extra_rlz=None)[source]#

Bases: object

Composite realization build on top of a source model realization and a GSIM realization; optionally carries an amplification realization

extra_rlz#
property gsim_lt_path#
gsim_rlz#
ordinal#
sm_lt_path#
weight#
class openquake.hazardlib.logictree.SourceModelLogicTree(filename, seed=0, num_samples=0, sampling_method='early_weights', test_mode=False, branchID='', source_id='', strict=False)[source]#

Bases: BranchSetLogicTree

Source model logic tree parser.

Parameters:

filename – Full pathname of logic tree file

Raises:

LogicTreeError – If logic tree file has a logic error, which can not be prevented by xml schema rules (like referencing sources with missing id).

FILTERS = ('applyToTectonicRegionType', 'applyToSources', 'applyToBranches')#
bset_values(lt_path)[source]#
Parameters:

sm_rlz – an effective realization

Returns:

a list of B - 1 pairs (branchset, value)

collect_source_model_data(branch_id, fname)[source]#

Parse source model file and collect information about source ids, source types and tectonic region types available in it. That information is used then for validate_filters() and validate_uncertainty_value().

Parameters:
  • branch_id – source model logic tree branch ID

  • fname – relative filename for the current source model portion

Returns:

the number of sources in the source model portion

decompose()[source]#

If the logic tree is source specific, returns a dictionary source ID -> CompositeLogicTree instance with the branchsets applied to the source; the key None (if present) corresponds to the root branchset, i.e. the source models, applied to all the sources

classmethod fake()[source]#
Returns:

a fake SourceModelLogicTree with a single branch

h5attrs()[source]#
Returns:

the attributes of the logic tree stored by __toh5__; the subclasses can extend them

index_branches()[source]#

Build the dictionaries branch ID -> branch and branch ID -> short ID from the branchsets

keep_files(rows)[source]#

Restrict source_data and info to the given rows, i.e. to the source model files defining the source; the geometry model files, having no source, are kept as they are.

Parameters:

rows – an array of source_dt

parse_branches(branchset_node, branchset)[source]#

Create and attach branches at branchset_node to branchset.

Parameters:
  • branchset_node – Same as for parse_branchset().

  • branchset – An instance of BranchSet.

Checks that each branch has valid value, unique id and that all branches have total weight of 1.0.

Returns:

None, all branches are attached to provided branchset.

parse_branchset(branchset_node, bsno)[source]#
Parameters:
  • node (branchset) – etree.Element object with tag “logicTreeBranchSet”.

  • bsno – The sequential number of the branchset, starting from 0.

Enumerates children branchsets and call parse_branchset(), validate_branchset(), parse_branches() and finally apply_branchset() for each.

Keeps track of “open ends” – the set of branches that don’t have any child branchset on this step of execution. After processing of every branchset only those branches that are listed in it can have child branchsets (if there is one on the next level).

parse_filters(branchset_node, uncertainty_type, filters)[source]#

Converts “applyToSources” and “applyToBranches” filters by splitting into lists.

parse_tree(tree_node)[source]#

Parse the whole tree and point root_branchset attribute to the tree’s root.

prune(source_id)[source]#

Discard from each branchset the branches not affecting the source:

  • in the sourceModel/extendModel branchsets the files not defining the source are removed and the empty branches are merged together, with the sum of the weights, so that the probability of the source not being defined is preserved

  • the other branchsets are replaced by a single branch if they cannot be applied to the source at all

Parameters:

source_id – the base source ID, possibly followed by “!” and the ID of the branch defining it

reduce(source_id, num_samples=None)[source]#
Returns:

a new logic tree reduced to a single source

The reduction is performed on the already parsed logic tree, i.e. no XML file is read again and no corner case can arise from re-deriving the sources from the source model files. NB: source_id contains “@” in the case of a split multi fault source and “!” in the case of a source defined in more than one branch.

set_num_paths()[source]#

Count the total number of paths in a smart way

classmethod trivial(source_model_file, sampling_method='early_weights', source_id='')[source]#
Returns:

a trivial SourceModelLogicTree with a single branch

property utypes#

Returns the uncertainty types for each branchset

validate_branchset(branchset_node, bsno, branchset)[source]#

See superclass’ method for description and signature specification.

Checks that the following conditions are met:

  • First branching level must contain exactly one branchset, which must be of type “sourceModel”.

  • All other branchsets must not be of type “sourceModel” or “gmpeModel”.

validate_filters(branchset_node, uncertainty_type, filters)[source]#

See superclass’ method for description and signature specification.

Checks that the following conditions are met:

  • “sourceModel” uncertainties can not have filters.

  • Absolute uncertainties must have only one filter – “applyToSources”, with only one source id.

  • All other uncertainty types can have either no or one filter.

  • Filter “applyToSources” must mention only source ids that exist in source models.

  • Filter “applyToTectonicRegionType” must mention only tectonic region types that exist in source models.

openquake.hazardlib.logictree.applies_to(bset, srcid, brids)[source]#
Parameters:
  • bset – a BranchSet

  • srcid – a source ID

  • brids – the IDs of the branches defining the source

Returns:

True if the branchset can change the parameters of the source

openquake.hazardlib.logictree.branch_id(branch, strict=False)[source]#
Parameters:
  • branch – a logicTreeBranch node or a branch ID string

  • strict – if True, raise an error for invalid IDs

Returns:

the branch ID, validated by valid.branch_id; if it is invalid and strict is False every character not allowed in an ID (spaces, commas, …) is replaced by an underscore, since applyToBranches is a list of IDs separated by spaces

openquake.hazardlib.logictree.capitalize(words)[source]#

Capitalize words separated by spaces.

openquake.hazardlib.logictree.check_branchset_weights(node, filename, bsid, weights)[source]#

Raise a LogicTreeError unless the branch weights sum to 1 (within pmf.PRECISION); shared by SourceModelLogicTree and PFDLogicTree.

Parameters:
  • node – XML node for the error line number (or None)

  • filename – logic tree filename

  • bsid – branchset ID, used in the message

  • weights – iterable of weights (float or float-convertible)

openquake.hazardlib.logictree.check_unique_uncertainties(source_specific_lts)[source]#

Make sure that each uncertainty in the underlying logic trees is unique

openquake.hazardlib.logictree.collect_info(smltpath, branchID='')[source]#

Given a path to a source model logic tree, collect all of the path names to the source models it contains.

Parameters:
  • smltpath – source model logic tree file

  • branchID – if given, consider only that branch

Returns:

an Info namedtuple (smpaths, h5paths, applytosources)

openquake.hazardlib.logictree.collect_paths(paths, b1=91, b2=93, til=126)[source]#

Collect branch paths belonging to the same cluster

>>> collect_paths([b'0~A0', b'0~A1'])
b'[0]~[A][01]'
openquake.hazardlib.logictree.compose(source_model_lt, gsim_lt)[source]#
Returns:

a CompositeLogicTree instance

openquake.hazardlib.logictree.copy_chain(branchsets)[source]#
Returns:

copies of the branchsets and of their branches, where each branch of a branchset points to the copy of the next branchset, so that the copies can be used in a new logic tree without changing the original one (see SourceModelLogicTree.decompose)

openquake.hazardlib.logictree.get_effective_rlzs(ltree)[source]#

Group together realizations with the same path and yield the first representative of each group.

Parameters:

ltree – a logic tree, used as key of the cache

openquake.hazardlib.logictree.get_field(data, field, default)[source]#
Parameters:

data – a record with a field field, possibily missing

openquake.hazardlib.logictree.get_trt_by_src(source_model_file)[source]#
Returns:

a dictionary source ID -> tectonic region type of the source

openquake.hazardlib.logictree.prod(iterator)[source]#

Replacement of math.prod for Python < 3.8

openquake.hazardlib.logictree.prune_files(bset, files)[source]#

Keep in the branchset only the files defining the given sources; the branches left without files are merged into a single branch with an empty value and the sum of the weights, preserving the probability of the source not being defined.

Parameters:
  • bset – a sourceModel/extendModel BranchSet

  • files – a dictionary branch ID -> list of files

openquake.hazardlib.logictree.reduce_full(full_lt, rlz_clusters)[source]#
Parameters:
  • full_lt – a FullLogicTree instance

  • rlz_clusters – list of paths for a realization cluster

Returns:

a dictionary with what can be reduced

openquake.hazardlib.logictree.reducible(lt, cluster_paths)[source]#
Parameters:
  • lt – a logic tree with B branches

  • cluster_paths – list of paths for a realization cluster

Returns:

a list [filename, (branchSetID, branchIDs), …]

openquake.hazardlib.logictree.shorten(path_tuple, shortener, kind)[source]#
Parameters:
  • path – sequence of strings

  • shortener – dictionary longstring -> shortstring

  • kind – ‘smlt’ or ‘gslt’

Returns:

shortened version of the path

openquake.hazardlib.logictree.unique(objects, key=None)[source]#

Raise a ValueError if there is a duplicated object, otherwise returns the objects as they are.

contexts#

class openquake.hazardlib.contexts.ContextMaker(trt, gsims, oq, monitor=<Monitor [runner]>, extraparams=())[source]#

Bases: object

A class to manage the creation of contexts and to compute mean/stddevs and possibly PoEs.

Parameters:
  • trt – tectonic region type string

  • gsims – list of GSIMs or a dictionary gsim -> rlz indices

  • oq – dictionary of parameters like the maximum_distance, the IMTLs, the investigation time, etc, or an OqParam instance

  • extraparams – additional site parameters to consider, used only in the tests

NB: the trt can be different from the tectonic region type for which the underlying GSIMs are defined. This is intentional.

REQUIRES = ['DISTANCES', 'SITES_PARAMETERS', 'RUPTURE_PARAMETERS']#
property Z#
Returns:

the number of realizations associated to self

apply_horiz_comp_conv(mean_stds, gsim)[source]#

Convert ground-motion from the GSIM’s native horizontal component to “horiz_comp_target”.

The ratio used for each component pair is (SA source listed; PGA/PGV come from BB06 Table 2 or the BK17 electronic supplement as applicable):

  • GMRotI50 <-> GEOM: BB06 Table 3 (SA); BK17 e-supp (PGA/PGV)

  • RANDOM <-> GEOM: BB06 Tables 2, 3

  • RotD50 <-> GEOM: BK17 Table 2 col 2 + e-supp

  • Larger <-> GEOM: BK17 Table 2 col 5 + e-supp

  • RotD50 <-> GMRotI50: BK17 Table 2 col 1 + e-supp

  • Larger <-> GMRotI50: BK17 Table 2 col 4 + e-supp

  • Larger <-> RotD50: BK17 Table 2 col 6 + e-supp

  • RotD100 <-> RotD50: BK17 Table 2 col 3 + e-supp

GSIMs whose native component has no direct ratio to the target (e.g. RANDOM <-> RotD50, RotD100 <-> GEOM) are logged and left unconverted.

cluster = None#
copy(**kw)[source]#
Returns:

a copy of the ContextMaker with modified attributes

property cross_correl#

Compatibility alias for the total-residual correlation model.

deltagetter = None#
dt = 0#
estimate_weight(src, srcfilter)[source]#
Parameters:
  • src – a source object

  • srcfilter – a SourceFilter instance

Returns:

an estimate of the CPU cost of processing the source

fewsites = False#
from_planar(rup, hdist, step, point='TC', toward_azimuth=90.0, direction='positive')[source]#
Parameters:

rup – a BaseRupture instance with a PlanarSurface and site parameters

Returns:

a context array for the sites around the rupture

from_srcs(srcs, sitecol, psdists=())[source]#
Parameters:
  • srcs – a list of Source objects with consistent TOM

  • sitecol – a SiteCollection instance

  • psdists – if given, a sorted list of pointsource distances

Returns:

a context array or, if psdists is given, a dictionary pointsource distance -> context array

NB: the number of close sites is stored in the .nsites attribute of each source

gen_contexts(rups_sites, src_id)[source]#
Yields:

the old-style RuptureContexts generated by the source

gen_poes(ctx)[source]#
Parameters:
  • ctx – a vectorized context (recarray) of size N

  • rup_indep – rupture flag (false for mutex ruptures)

Yields:

poes, mea_sig, ctxt with poes of shape (N, L, G)

genctxs(same_mag_rups, sites, src_id)[source]#
Params same_mag_rups:

a list of ruptures

Parameters:
  • sites – a (filtered) site collection

  • src_id – source index

Yields:

a context array for each rupture

get_4MN(ctxs, gsim)[source]#

Called by the GmfComputer

get_att_curves(site, msr, mag, aratio=1.0, strike=0.0, dip=45.0, rake=-90)[source]#
Returns:

4 attenuation curves mea, sig, tau, phi (up to 500 km from the site at steps of 5 km)

get_ctx_params()[source]#
Returns:

the interesting attributes of the context

get_ctxs(src, sitecol, src_id=0, step=1)[source]#
Parameters:
  • src – a source object (already split) or a list of ruptures

  • sitecol – a (filtered) SiteCollection

  • src_id – integer source ID used where src is actually a list

  • step – > 1 only in preclassical

Returns:

list of recarrays

get_mean_stds(ctxs, split_by_mag=True)[source]#
Parameters:
  • ctxs – a list of contexts with N=sum(len(ctx) for ctx in ctxs)

  • split_by_mag – where to split by magnitude

Returns:

an array of shape (4, G, M, N) with mean and stddevs

get_occ_rates(ctxt)[source]#
Parameters:

ctxt – context array generated by this ContextMaker

Returns:

occurrence rates, possibly from probs_occur[0]

get_pmap(ctx, tom=None, rup_mutex={})[source]#
Parameters:
  • ctx – a context array

  • tom – temporal occurrence model (default PoissonTom)

  • rup_mutex – dictionary of weights (default empty)

Returns:

a MapArray

get_poes(srcs, sitecol, tom=None, rup_mutex={})[source]#
Parameters:
  • srcs – a list of sources with the same TRT

  • sitecol – a SiteCollection instance with N sites

Returns:

an array of PoEs of shape (N, L, G)

get_rmap(ctx, tom=None)[source]#
Parameters:
  • ctx – a context array

  • tom – temporal occurrence model (default PoissonTom)

Returns:

a MapArray of rates of shape (N, L, G)

NB: the rates are accumulated directly, without converting probabilities into rates

get_rparams(rup)[source]#
Returns:

a dictionary with the rupture parameters

property gid#
Returns:

the ids of the columns of the rates generated by this cmaker, i.e. the gids of an index of rate attribution if the cmaker has been restricted (see restrict_trt_smrs), otherwise the gsim_idx, since for a whole group the ids of the rates and the indexes of the gsims coincide

ilabel = None#
init_monitoring(monitor)[source]#
new_ctx(size)[source]#
Returns:

a recarray of the given size full of zeros

recarray(ctxs)[source]#
Params ctxs:

a non-empty list of homogeneous contexts

Returns:

a recarray, possibly collapsed

restrict(imts, step=1)[source]#
Parameters:
  • imts – a list of IMT strings subset of the full list

  • step – keep one level every step (default all the levels)

Returns:

a new ContextMaker involving less IMTs (and levels)

restrict_trt_smrs(trt_smrs, gid, wei)[source]#
Parameters:
  • trt_smrs – the trt_smrs of the index of rate attribution

  • gid – the gids identifying the index of rate attribution, i.e. the columns of the rates generated by the new cmaker; NB: the gsim_idx are not changed, since the gsims are not restricted either

  • wei – the weights of the gids

Returns:

a shallow copy of the cmaker restricted to the realizations trt_smrs, since a group has the trt_smrs of all the realizations but the sources can have different uncertainties in different ones

NB: the gsims are not restricted, since the number of gsims of an index of rate attribution is the number of gsims of its TRT, see get_rlzs_by_gsim, and must match the number of gids, see get_gids

property scenario#

True if scenario

set_imts_conv()[source]#

Set the .imts list and .conv dictionary for the horizontal component conversion (if any). Also set the .loglevels.

set_weight(sources, srcfilter)[source]#

Set the weight attribute on each prefiltered source

source_mb = 0#
split(blocksize)[source]#

Split the ContextMaker by blocks of GSIMs

tom = None#
update(pmap, ctx, rup_mutex=None)[source]#
Parameters:
  • pmap – probability map to update

  • ctx – a context array

  • rup_mutex – dictionary (src_id, rup_id) -> weight

exception openquake.hazardlib.contexts.FarAwayRupture[source]#

Bases: Exception

Raised if the rupture is outside the maximum distance for all sites

class openquake.hazardlib.contexts.Oq(**hparams)[source]#

Bases: object

A mock for OqParam

af = None#
correlation_strategy = 'cholesky_decomposition'#
get_max_iml()[source]#
get_reqv()[source]#
impact = False#
infer_occur_rates = False#
inputs = ()#
keep_rupdata = True#
mea_tau_phi = False#
property min_iml#
minimum_intensity = {}#
sec_imts = []#
split_sources = True#
total_residual_correlation_model = None#
use_rates = False#
with_betw_ratio = None#
openquake.hazardlib.contexts.PAIR_COST = 20.0#

How many (rupture, site) pairs are as expensive as a single surviving context, i.e. how much a discarded pair costs with respect to a context on which the GSIMs are actually evaluated. Determined heuristically from the @slowtask in oq-risk-tests

class openquake.hazardlib.contexts.RuptureContext(param_pairs=())[source]#

Bases: object

Rupture calculation context for ground shaking intensity models.

Instances of this class represent relevant features of a single rupture. Every GSIM class is required to declare what rupture parameters does it need. Only those required parameters are made available in a result context object.

rup_id = 0#
size()[source]#

If the context is a multi rupture context, i.e. it contains an array of magnitudes and it refers to a single site, returns the size of the array, otherwise returns 1.

src_id = 0#
openquake.hazardlib.contexts.collapse_ctx(ctx, rparams, dparams, prec)[source]#

Merge rows for the same site with matching rupture parameters and binned distances. Round dip, strike, rake and width to one decimal place for matching; compare other rupture parameters exactly, considering NaN equal to NaN. Sum occurrence rates and average distances with those rates as weights. Nonpoissonian contexts are unchanged.

Parameters:
  • ctx – context recarray with sids and occurrence_rate fields

  • rparams – rupture parameter names; dip, strike, rake and width are rounded, other parameters are kept exact

  • dparams – distance parameter names; rrup is always included

  • prec – positive bin width on sign(d) * log(1 + abs(d))

Returns:

collapsed recarray, or ctx if no rows are merged

Parameter names absent from ctx are ignored. Distances are grouped by rounding their transformed values divided by prec.

The first two rows below share a site, magnitude and distance bin. Their rates sum to 0.04 and their weighted distance is 106.15 km. The third row stays separate because it belongs to another site.

>>> ctx = numpy.rec.fromarrays(
...     [[0, 0, 1], [6.5] * 3, [106., 106.2, 106.], [.01, .03, .02]],
...     names='sids,mag,rrup,occurrence_rate')
>>> out = collapse_ctx(ctx, {'mag'}, {'rrup'}, prec=.01)
>>> out.sids.tolist()
[0, 1]
>>> out.occurrence_rate.round(2).tolist()
[0.04, 0.02]
>>> out.rrup.round(2).tolist()
[106.15, 106.0]
openquake.hazardlib.contexts.combine_pmf(o1, o2)[source]#

Combine probabilities of occurrence; used to collapse nonparametric ruptures.

Parameters:
  • o1 – probability distribution of length n1

  • o2 – probability distribution of length n2

Returns:

probability distribution of length n1 + n2 - 1

>>> combine_pmf([.99, .01], [.98, .02])
array([9.702e-01, 2.960e-02, 2.000e-04])
openquake.hazardlib.contexts.concat(ctxs)[source]#

Concatenate context arrays

openquake.hazardlib.contexts.estimate_nctxs(cmaker, srcs, sitecol)[source]#

Fast estimate of the number of contexts generated by point sources (see genctxs_Pp). For each magnitude a source generates a context for each site within the magnitude distance, plus nphc - 1 contexts for each site within the pointsource distance, being nphc the number of nodal planes times the number of hypocenters. The rupture distances are approximated with the distances from the source location, so that the number of pairs (source, site) within a distance is computed with SiteCollection.count_close for each group of sources with the same magnitudes and rupture radii, reusing the site collection’s KDTree.

Returns:

the estimated number of contexts, an integer

openquake.hazardlib.contexts.genctxs_Pp(src, sitecol, cmaker, prec=0, psdists=())[source]#

Context generator for point sources and collapsed point sources; the contexts are collapsed with precision prec if it is nonzero. Yields pairs (ks, ctx), being ks the indices of the pointsource distances psdists (sorted, by default the one of the cmaker) for which the context array is valid

openquake.hazardlib.contexts.get_dists(ctx)[source]#

Extract the distance parameters from a context.

Returns:

a dictionary dist_name -> distances

openquake.hazardlib.contexts.get_mean_stds(gsim, ctx, imts, return_dicts=False, **kw)[source]#
Parameters:
  • gsim – a single GSIM or a a list of GSIMs

  • ctx – a RuptureContext or a recarray of size N with same magnitude

  • imts – a list of M IMT objects

  • return_dicts – if True, returns 4 dictionaries keyed by IMT strings

  • kw – additional keyword arguments

Returns:

an array of shape (4, M, N) obtained by applying the given GSIM, ctx amd imts, or an array of shape (G, 4, M, N)

openquake.hazardlib.contexts.get_num_distances(gsims)[source]#
Returns:

the number of distances required for the given GSIMs

openquake.hazardlib.contexts.is_modifiable(gsim)[source]#
Returns:

True if it is a ModifiableGMPE

openquake.hazardlib.contexts.mean_stds(rctx, gsim, imt, idx=[0, 1, 2, 3])[source]#
Parameters:
  • rctx – a RuptureContext with site and distance information

  • gsim – a GSIM instance

  • imt – an IMT string

  • idx – index (or list of indices) in the range 0..3 (default [0,1,2,3])

Returns:

array of shape N or (len(idx), N)

openquake.hazardlib.contexts.set_distances(ctx, rup, r_sites, param, dparam, mask, tu)[source]#

Set the distance attributes on the context; also manages paired attributes like clon_lat and rx_ry0.

openquake.hazardlib.contexts.set_poes(gsim, mean_std, cmaker, ctx, out, slc)[source]#

Calculate and return probabilities of exceedance (PoEs) of one or more intensity measure levels (IMLs) of one intensity measure type (IMT) for one or more pairs “site – rupture”.

Parameters:
  • gsim – A GMPE instance

  • mean_std – An array of shape (2, M, N) with mean and standard deviations for the sites and intensity measure types

  • cmaker – A ContextMaker instance, used only in nhsm_2014

  • ctx – A context array used only in avg_poe_gmpe

  • out – An array of PoEs of shape (N, L) to be filled

  • slc – A slice object used only in avg_poe_gmpe

Raises:

ValueError – If truncation level is not None and neither non-negative float number, and if imts dictionary contain wrong or unsupported IMTs (see DEFINED_FOR_INTENSITY_MEASURE_TYPES).

openquake.hazardlib.contexts.simple_cmaker(gsims, imts, **params)[source]#
Returns:

a simplified ContextMaker for use in the tests

openquake.hazardlib.contexts.size(imtls)[source]#
Returns:

size of the dictionary of arrays imtls

openquake.hazardlib.contexts.trivial(ctx, name)[source]#
Parameters:
  • ctx – a recarray

  • name – name of a parameter

Returns:

True if the parameter is missing or single valued

const#

Module openquake.hazardlib.const defines various constants.

class openquake.hazardlib.const.IMC(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

Bases: Enum

The intensity measure component is the component of interest of ground shaking for an intensity measure.

GEOMETRIC_MEAN = 'Average Horizontal'#

Usually defined as the geometric average of the maximum of the two horizontal components (which may not occur at the same time).

GMRotD100 = 'Average Horizontal (GMRotD100)'#

The geometric mean of the records rotated into the most adverse direction for the structure.

GMRotI50 = 'Average Horizontal (GMRotI50)'#

An orientation-independent alternative to AVERAGE_HORIZONTAL. Defined at Boore et al. (2006, Bull. Seism. Soc. Am. 96, 1502-1511) and is used for all the NGA GMPEs.

GREATER_OF_TWO_HORIZONTAL = 'Greater of two horizontal'#

The largest value obtained from two perpendicular horizontal components.

HORIZONTAL = 'Horizontal'#

The horizontal component.

MEDIAN_HORIZONTAL = 'Median horizontal'#

The median horizontal component.

PEAK_SRSS_HORIZONTAL = 'Peak square root of sum of squares of horizontals'#

“the peak square root of the sum of squares of two orthogonal horizontal components in the time domain” p. 880 of Kanno et al. (2006, Bull. Seism. Soc. Am. 96, 879-897)

RANDOM_HORIZONTAL = 'Random horizontal'#

A randomly chosen horizontal component.

RotD100 = 'Horizontal Maximum Direction (RotD100)'#
RotD50 = 'Average Horizontal (RotD50)'#

An orientation-independent alternative to AVERAGE_HORIZONTAL. Defined at Boore et al. (2006, Bull. Seism. Soc. Am. 96, 1502-1511) and is used for all the NGA GMPEs.

VECTORIAL = 'Square root of sum of squares of peak horizontals'#

“Vectorial addition: a_V = sqrt(max|a_1(t)|^2 + max|a_2(t)|^2)). This means that the maximum ground amplitudes occur simultaneously on the two horizontal components; this is a conservative assumption.” p. 53 of Douglas (2003, Earth-Sci. Rev. 61, 43-104)

VERTICAL = 'Vertical'#

The vertical component.

VERTICAL_TO_HORIZONTAL_RATIO = 'Vertical-to-Horizontal Ratio'#

A vertical-to-horizontal spectral ratio

openquake.hazardlib.const.KNOWN_DISTANCES = frozenset({'azimuth', 'azimuthcp', 'clat', 'clon', 'clon_clat', 'rcdpp', 'repi', 'rhypo', 'rjb', 'rrup', 'rtor', 'rvolc', 'rx', 'rx_ry0', 'ry0', 'x_l'})#

Distance parameters known to the GSIMs and the ContextMaker

class openquake.hazardlib.const.StdDev[source]#

Bases: object

GSIM standard deviation represents ground shaking variability at a site.

ALL = 'All'#

Used in event based calculations, correspond to TOTAL if the gsim is defined for TOTAL, otherwise to the pair (INTER_EVENT, INTRA_EVENT)

EVENT = 'Event'#

Total standard deviation, defined as the square root of the sum of inter- and intra-event squared standard deviations, represents the total ground shaking variability, and is the only one that is used for calculating a probability of intensity exceedance (see openquake.hazardlib.gsim.base.get_poes()).

INTER_EVENT = 'Inter event'#

Standard deviation representing ground shaking variability within different events.

INTRA_EVENT = 'Intra event'#

Standard deviation representing ground shaking variability within a single event.

TOTAL = 'Total'#
idx = {'Inter event': 1, 'Intra event': 2, 'Total': 0}#
class openquake.hazardlib.const.TRT(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

Bases: Enum

Container for constants that define some of the common Tectonic Region Types.

ACTIVE_SHALLOW_CRUST = 'Active Shallow Crust'#
GEOTHERMAL = 'Geothermal'#
INDUCED = 'Induced'#
STABLE_CONTINENTAL = 'Stable Shallow Crust'#
SUBDUCTION_INTERFACE = 'Subduction Interface'#
SUBDUCTION_INTRASLAB = 'Subduction IntraSlab'#
UPPER_MANTLE = 'Upper Mantle'#
VOLCANIC = 'Volcanic'#

imc_conversion#

Horizontal-component intensity-measure-component (IMC) conversion.

Only pairs for which Beyer & Bommer (2006) or Boore & Kishida (2017) publish a direct ratio are supported currently. The eight directly tabulated pairs, with their SA source (PGA/PGV sources noted separately below) are:

GMRotI50 <-> GEOM (SA: BB06 Table 3) RANDOM <-> GEOM (SA: BB06 Table 3; PGA/PGV: BB06 Table 2) RotD50 <-> GEOM (SA: BK17 Table 2 col 2) RotD50 <-> GMRotI50 (SA: BK17 Table 2 col 1) RotD100 <-> RotD50 (SA: BK17 Table 2 col 3) Larger <-> GEOM (SA: BK17 Table 2 col 5) Larger <-> GMRotI50 (SA: BK17 Table 2 col 4) Larger <-> RotD50 (SA: BK17 Table 2 col 6)

Any other pair (e.g. RANDOM <-> RotD50, RotD100 <-> GEOM) is left unconverted; callers skip the GSIM (i.e., no conversion) and log a notice.

Every direct ratio is a Ratio record keyed by (source, target). The triple returned by ratio_at(imt) is (conv_median, conv_sigma, ratio_sigma), where:

conv_median : median of source_IM / target_IM conv_sigma : standard deviation of ln(ratio) ratio_sigma : total_sigma(source) / total_sigma(target)

PGV for every BK17-sourced pair, plus PGA and PGV for the GMRotI50/GEOM pair (whose SA is BB06 Table 3 but whose PGA/PGV BB06 does not publish), come from the BK17 electronic supplement, specifically the Rrup <= 200 km, M 2-9 all-magnitude CSVs:

nga-w2.gmean.Rot_Ratios.Sdev.RrupMin_0000.RrupMax_0200.Mmin_2.00.Mmax_9.00.4paper.csv nga-w2.gmean.Larger_Ratios.Sdev.RrupMin_0000.RrupMax_0200.Mmin_2.00.Mmax_9.00.4paper.csv

BK17 PGA (for the six BK17-sourced pairs) is kept at R1, the first knot of the SA line-segment fit. Equation (2) clamps to R1 at T=0, so R1 is the mathematically consistent T->0 plateau. The real e-supp PGA differs by ~0.5-1.5% but to minimise Mosaic/AELO changes we retain the R1 values.

For PGV from the e-supplement, ratio_sigma is kept at 1.0 as an approximation; the full propagation per BK17 eq. (3) inflates the output sigma by only ~1% across all periods (BK17 p. 339 Table 3). BK17 SA uses conv_sigma=0, ratio_sigma=1 for the same reason: the ~1% figure applies at SA periods too.

References#

Beyer, K., and J. J. Bommer (2006). Relationships between median values

and between aleatory variabilities for different definitions of the horizontal component of motion, Bulletin of the Seismological Society of America 96(4A), 1512-1522.

Boore, D. M., and T. Kishida (2017). Relations between some

horizontal-component ground-motion intensity measures used in practice, Bulletin of the Seismological Society of America 107(1), 334-343.

class openquake.hazardlib.imc_conversion.Ratio(paper, kind, sa, pga, pgv)[source]#

Bases: NamedTuple

kind: str#

Alias for field number 1

paper: str#

Alias for field number 0

pga: tuple#

Alias for field number 3

pgv: tuple#

Alias for field number 4

sa: tuple#

Alias for field number 2

openquake.hazardlib.imc_conversion.apply_conversion(src_imc, tgt_imc, imt)[source]#

Build the sequence of steps that converts a GSIM prediction from src_imc to tgt_imc at the given IMT.

Parameters:
  • src_imc – the GSIM’s native IMC

  • tgt_imc – the desired target IMC

  • imt – the intensity measure type

Returns:

A tuple of steps for “apply_in_place” function to use.

openquake.hazardlib.imc_conversion.apply_in_place(mean_sig, steps)[source]#

Apply a sequence of steps to a (mean, sigma) pair in place. Each step is (kind, conv_median, conv_sigma, ratio_sigma):

“forward”: me -= ln(conv_median)

si = sqrt((si**2 - conv_sigma**2) / ratio_sigma**2)

“reverse”: me += ln(conv_median)

si = sqrt(si**2 * ratio_sigma**2 + conv_sigma**2)

openquake.hazardlib.imc_conversion.can_convert(src_imc, tgt_imc)[source]#
Returns:

True if a direct ratio exists between src_imc and tgt_imc (in either direction), or they are the same IMC.

openquake.hazardlib.imc_conversion.log_unsupported(gsim_cls_name, src_imc, tgt_imc)[source]#

Log once that no direct ratio connects a GSIM’s native IMC to the requested target. Repeated calls for the same triple are silent.

openquake.hazardlib.imc_conversion.ratio_at(r, imt)[source]#

Evaluate a Ratio object at the given IMT and return (conv_median, conv_sigma, ratio_sigma).

openquake.hazardlib.imc_conversion.target_from_name(name)[source]#
Returns:

the IMC enum member for a horiz_comp_to value, or None if the value is empty (no conversion requested).

correlation#

Compatibility imports for spatial ground-motion correlation models.

openquake.hazardlib.correlation.BaseCorrelationModel#

alias of SpatialCorrelationModel

openquake.hazardlib.correlation.HM2018CorrelationModel#

alias of HeresiMiranda2019

openquake.hazardlib.correlation.JB2009CorrelationModel#

alias of JayaramBaker2009

imt#

Module openquake.hazardlib.imt defines different intensity measure types.

openquake.hazardlib.imt.ASH()[source]#

Level of the ash fall in millimeters

openquake.hazardlib.imt.AvgSA(period=None, damping=5.0)[source]#

Dummy spectral acceleration to compute average ground motion over several spectral ordinates. Depending on the choice of AvgSA GMPE, this can operate as a scalar value or as a vector quantity.

openquake.hazardlib.imt.CAV()[source]#

Cumulative Absolute Velocity. Defins the integral of the absolute acceleration time series. Units are “g-sec”

openquake.hazardlib.imt.DRVT(frequency)[source]#

Duration as defined in Bora et al. (2019)

openquake.hazardlib.imt.Disp()[source]#

Displacement

openquake.hazardlib.imt.DispProb()[source]#

Displacement probability

openquake.hazardlib.imt.EAS(frequency)[source]#

Effective Amplitude Spectrum in terms of a frequency (in Hz).

openquake.hazardlib.imt.FAS(frequency)[source]#

Fourier Amplitude Spectrum in terms of a frequency (in Hz).

openquake.hazardlib.imt.FIV3(period, damping=5.0)[source]#

Filtered incremental velocity, as defined in: Dávalos, H. and Miranda, E. (2019) ‘Filtered incremental velocity: A novel approach in intensity measures for seismic collapse estimation’, Earthquake Engineering and Structural Dynamics, 48(12), pp. 1384–1405. Available at: https://doi.org/10.1002/eqe.3205. Units are cm/s.

openquake.hazardlib.imt.FlowDepth()[source]#

Flow depth in meters.

openquake.hazardlib.imt.FlowVel()[source]#

Flow velocity in m/s.

openquake.hazardlib.imt.IA()[source]#

Arias intensity. Determines the intensity of shaking by measuring the acceleration of transient seismic waves. Units are m/s.

class openquake.hazardlib.imt.IMT(string, period, damping, strength_ratio)#

Bases: tuple

damping#

Alias for field number 2

property frequency#
property name#
period#

Alias for field number 1

strength_ratio#

Alias for field number 3

string#

Alias for field number 0

openquake.hazardlib.imt.JMA()[source]#

Modified Mercalli intensity, a Roman numeral describing the severity of an earthquake in terms of its effects on the earth’s surface and on humans and their structures.

openquake.hazardlib.imt.LAHAR()[source]#

Lahar Intensity

openquake.hazardlib.imt.LAVA()[source]#

Lava Intensity

openquake.hazardlib.imt.LSD()[source]#

Liquefaction-induced lateral spread displacements measured in units of m.

openquake.hazardlib.imt.LSE()[source]#

Liquefaction or Landslide spatial extent.

openquake.hazardlib.imt.LiqOccur()[source]#

Liquefaction occurrence class

openquake.hazardlib.imt.LiqProb()[source]#

Liquefaction probability

openquake.hazardlib.imt.LsProb()[source]#

Probability of landsliding.

openquake.hazardlib.imt.MMI()[source]#

Modified Mercalli intensity, a Roman numeral describing the severity of an earthquake in terms of its effects on the earth’s surface and on humans and their structures.

openquake.hazardlib.imt.MomFlux()[source]#

Momentum flux in m^3/s.

openquake.hazardlib.imt.PGA()[source]#

Peak ground acceleration during an earthquake measured in units of g, times of gravitational acceleration.

openquake.hazardlib.imt.PGD()[source]#

Peak ground displacement during an earthquake measured in units of cm.

openquake.hazardlib.imt.PGDGeomMean(vert_settlement, lat_spread)[source]#

Geometric mean between vert_settlement and lat_spread

openquake.hazardlib.imt.PGDMax(vert_settlement, lat_spread)[source]#

Maximum between vert_settlement and lat_spread

openquake.hazardlib.imt.PGV()[source]#

Peak ground velocity during an earthquake measured in units of cm/sec.

openquake.hazardlib.imt.PYRO()[source]#

Pyroclastic Flow Intensity

openquake.hazardlib.imt.RSD()[source]#

Relative significant duration, 5-95% of Arias intensity, in seconds.

openquake.hazardlib.imt.RSD2080()[source]#

Relative significant duration, 20-80% of Arias intensity, in seconds.

openquake.hazardlib.imt.RSD575()[source]#

Relative significant duration, 5-75% of Arias intensity, in seconds.

openquake.hazardlib.imt.RSD595()[source]#

Alias for RSD

openquake.hazardlib.imt.SA(period, damping=5.0)[source]#

Spectral acceleration, defined as the maximum acceleration of a damped, single-degree-of-freedom harmonic oscillator. Units are g, times of gravitational acceleration.

openquake.hazardlib.imt.SDi(period, strength_ratio, damping=5.0)[source]#

Inelastic spectral displacement, defined as the maximum displacement of a damped, single-degree-of-freedom inelastic oscillator. Units are cm.

openquake.hazardlib.imt.Sa_avg2(period, damping=5.0)[source]#
openquake.hazardlib.imt.Sa_avg3(period, damping=5.0)[source]#
openquake.hazardlib.imt.dictarray(imtls)[source]#
Returns:

a DictArray sorted by IMT

openquake.hazardlib.imt.from_string(imt, _damping=5.0)[source]#

Convert an IMT string into an hazardlib object.

Parameters:

imt (str) – Intensity Measure Type.

openquake.hazardlib.imt.imt2tup(string)[source]#

Used in sort_by_imt -> from_string to sort keys by period >>> imt2tup(‘PGA’) (‘PGA’,) >>> imt2tup(‘SA(1.0)’) (‘SA(1.0)’, 1.0) >>> imt2tup(‘SA(1)’) (‘SA(1.0)’, 1.0)

openquake.hazardlib.imt.positivefloat(val)[source]#

Raise a ValueError if val <= 0

openquake.hazardlib.imt.repr(self)[source]#
openquake.hazardlib.imt.sort_by_imt(imtls)[source]#
Parameters:

imtls – a dictionary keyed by IMT string

Returns:

a new dictionary with the keys sorted by period

>>> sort_by_imt({'SA(10.0)': 1, 'SA(2.0)': 2})
{'SA(2.0)': 2, 'SA(10.0)': 1}

lt#

Branches, branchsets, uncertainties and the base classes of the logic trees. All the logic trees implement the interface of AbstractLogicTree; the logic trees made of branchsets derive from BranchSetLogicTree and the logic trees which can be the extra logic tree of a FullLogicTree derive from ExtraLogicTree. Here is the hierarchy, with the methods defined or overridden by each class:

AbstractLogicTree
│   [abstract] get_num_paths, get_realizations, __toh5__, __fromh5__
│   sample, to_node, to_nrml
├── BranchSetLogicTree
│   │   root_branchset, set_num_paths, get_num_paths, get_realizations,
│   │   sample, get_all_paths, to_node, h5attrs, __toh5__, __fromh5__
│   ├── CompositeLogicTree
│   │       sample_paths, apply_all
│   ├── SourceModelLogicTree
│   │       set_num_paths, decompose, reduce, prune, bset_values, h5attrs,
│   │       __fromh5__
│   └── ExtraLogicTree
│       │   get_realizations, shortener
│       ├── PFDLogicTree
│       │       selections_for, check_r_sigma_conflict
│       └── AmplificationLogicTree
│               from_xml, is_amp_lt, names, weights, filenames,
│               branchset_id, amplify, check, __fromh5__
├── GsimLogicTree
│       get_realizations, sample, get_num_paths, to_node, __toh5__,
│       __fromh5__
└── FullLogicTree
        get_realizations, get_num_paths, sample, __toh5__, __fromh5__

NRML export is optional: AbstractLogicTree.to_nrml calls to_node, which BranchSetLogicTree and GsimLogicTree implement. FullLogicTree combines separate trees and inherits the default to_node raising NotImplementedError. The uncertainty_to_node helper serializes MFD values and correlated mappings. The gsim_lt.read_branchsets helper reads editable branchsets without validating branch IDs or loading source files, retaining nested uncertainty XML.

The classes are defined in the modules lt, logictree, gsim_lt, pfd_lt and amp_lt of openquake.hazardlib.

class openquake.hazardlib.lt.AbstractLogicTree[source]#

Bases: ABC

Common interface of the logic trees. The subclasses must define get_num_paths, get_realizations and the serialization methods __toh5__ and __fromh5__; sample can be overridden, by default it samples the realizations by weight. Subclasses supporting NRML export override to_node and inherit to_nrml.

abstract get_num_paths()[source]#
Returns:

the number of paths in the logic tree

abstract get_realizations()[source]#
Returns:

the list of the realizations of the logic tree

sample(n, seed, sampling_method='early_weights')[source]#
Parameters:
  • n – number of samples

  • seed – random seed

  • sampling_method – by default ‘early_weights’

Returns:

n realizations sampled with probability equal to their weight (they may repeat or be absent)

to_node()[source]#

Return an XML node, when this tree supports NRML export.

to_nrml(fmt='%.7E')[source]#

Converts the logic tree into a string in NRML format.

Parameters:

fmt – format for floating-point values

class openquake.hazardlib.lt.Branch(branch_id, value, weight, bs_id='')[source]#

Bases: object

Branch object, represents a <logicTreeBranch /> element.

Parameters:
  • branch_id – String identifier of the branch

  • value – The actual uncertainty parameter value. A text node contents of <uncertaintyModel /> child node. Type depends on the branchset’s uncertainty type. For serialization, an unparsed uncertaintyModel or MFD Node can retain nested XML. Correlated uncertainties use a dictionary of source IDs to uncertainty values.

  • weight – float value of weight assigned to the branch. A text node contents of <uncertaintyWeight /> child node.

  • bs_id – BranchSetID of the branchset to which the branch belongs

property id#
is_dummy()[source]#
Returns:

True with the parent branchset ID starts with ‘dummy’

is_leaf()[source]#
Returns:

True if the branch has no branchset or has a dummy branchset

to_node(uncertainty_type=None, correlated=False)[source]#
class openquake.hazardlib.lt.BranchSet(uncertainty_type, filters=None, ordinal=0, collapsed=False)[source]#

Bases: object

Branchset object, represents a <logicTreeBranchSet /> element.

Parameters:
  • uncertainty_type –

    String value. According to the spec one of:

    gmpeModel

    Branches contain references to different GMPEs. Values are parsed as strings and are supposed to be one of supported GMPEs. See list at GMPELogicTree.

    sourceModel

    Branches contain references to different PSHA source models. Values are treated as file names, relatively to base path.

    maxMagGRRelative

    Different values to add to Gutenberg-Richter (“GR”) maximum magnitude. Value should be interpretable as float.

    bGRRelative

    Values to add to GR “b” value. Parsed as float.

    maxMagGRAbsolute

    Values to replace GR maximum magnitude. Values expected to be lists of floats separated by space, one float for each GR MFD in a target source in order of appearance.

    minMagGRAbsolute

    Values to replace GR minimum magnitude. Value should be interpretable as float.

    abGRAbsolute

    Values to replace “a” and “b” values of GR MFD. Lists of pairs of floats, one pair for one GR MFD in a target source.

    incrementalMFDAbsolute

    Replaces an evenly discretized MFD with the values provided

    multiMFDAbsolute

    Replaces the MultiMFD of a multiPointSource (i.e. the MFDs of all its points) with the multiMFD provided

    simpleFaultDipRelative

    Increases or decreases the angle of fault dip from that given in the original source model

    simpleFaultDipAbsolute

    Replaces the fault dip in the specified source(s)

    simpleFaultGeometryAbsolute

    Replaces the simple fault geometry (trace, upper seismogenic depth lower seismogenic depth and dip) of a given source with the values provided

    complexFaultGeometryAbsolute

    Replaces the complex fault geometry edges of a given source with the values provided

    characteristicFaultGeometryAbsolute

    Replaces the complex fault geometry surface of a given source with the values provided

    truncatedGRFromSlipAbsolute

    Updates a TruncatedGR using a slip rate and a rigidity

    maxMagAndDeltaMagACRelative

    Different values to add to maximum magnitude and delta_m_AC. Value should be a pair of floats separated by space.

    maxMagAndDeltaMagACRelativeNoMoBalance

    Same as maxMagAndDeltaMagACRelative but without rebalancing the total rate to preserve total moment rate.

  • filters –

    Dictionary, a set of filters to specify which sources should the uncertainty be applied to. Represented as branchset element’s attributes in xml:

    applyToSources

    The uncertainty should be applied only to specific sources. This filter is required for absolute uncertainties (also only one source can be used for those). Value should be the list of source ids. Can be used only in source model logic tree.

    applyToTectonicRegionType

    Can be used in both the source model and GMPE logic trees. Allows to specify to which tectonic region type (Active Shallow Crust, Stable Shallow Crust, etc.) the uncertainty applies to. This filter is required for all branchsets in GMPE logic tree.

applied = None#
check_duplicates(filename='')[source]#

Check if the underlying branches are duplicated

check_weights()[source]#

The branch weights must sum up to 1.

collapse()[source]#

Collapse to the first branch (with side effects)

property correlated#

The branchset is applied to correlated sources

enumerate_paths()[source]#

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 Branch objects. Total sum of all paths’ weights is 1.0

filter_source(source)[source]#

Apply filters to source and return True if uncertainty should be applied to it.

get_bset_values(ltpath)[source]#
Parameters:

ltpath – String of chars

Returns:

A list of pairs [(bset, value), …]

sample(probabilities, sampling_method)[source]#
Parameters:
  • num_samples – the number of samples

  • probabilities – (Ns, Nb) random numbers in the range 0..1

  • sampling_method – the sampling method used

Returns:

a list of num_samples lists of branches

to_list()[source]#
Returns:

a literal list describing the branchset

class openquake.hazardlib.lt.BranchSetLogicTree[source]#

Bases: AbstractLogicTree

Logic tree made of branchsets, each one attached to branches of the previous ones (see attach_branches). The subclasses must set the attribute branchsets and call set_num_paths (or set num_paths); they can set num_samples, seed and sampling_method. To be stored in the datastore, the branchsets must have an id and the subclasses must set filename and the dictionary bsetdict branchset ID -> attributes of the branchset (including the filters).

get_all_paths()[source]#
Returns:

the paths of the logic tree as strings, padded with dots

get_num_paths()[source]#
Returns:

the number of paths in the logic tree

get_realizations()[source]#
Returns:

the list of the realizations, sampled if num_samples is set, otherwise all of them; notice that the weight is homogeneous with early sampling, since it is accounted for in the sampling procedure

h5attrs()[source]#
Returns:

the attributes of the logic tree stored by __toh5__; the subclasses can extend them

num_samples = 0#
property root_branchset#

The first branchset, or None if there are no branchsets

sample(n, seed, sampling_method='early_weights')[source]#

Sample the logic tree branchset by branchset. Notice that the weight is homogeneous with early sampling, since it is accounted for in the sampling procedure. Late sampling uses importance weights p/q, correcting for uniform choices at each visited branchset. These weights are unnormalized; FullLogicTree normalizes combined weights.

Parameters:
  • n – number of samples

  • seed – random seed

  • sampling_method – by default ‘early_weights’

Returns:

n Realization objects

sampling_method = 'early_weights'#
seed = 42#
set_num_paths()[source]#

Set the attribute num_paths, i.e. the number of end branches

to_node()[source]#

Converts the underlying branchsets, with their filters, into a node that can be serialized into XML with nrml.write([node], outfile); the branchsets keep their IDs, if any

class openquake.hazardlib.lt.CompositeLogicTree(branchsets, seed=42, num_samples=0, sampling_method='early_weights')[source]#

Bases: BranchSetLogicTree

Build a logic tree from a set of branches by automatically setting the branch IDs.

NB: it is not stored in the datastore, since the serialization inherited from BranchSetLogicTree requires branchset IDs, a filename and a bsetdict

apply_all(src)[source]#

Apply all uncertainties for each realization.

Parameters:

src – source object

Returns:

R modified sources

sample_paths(num_samples, seed=42, sampling_method='early_weights')[source]#
class openquake.hazardlib.lt.ExtraLogicTree[source]#

Bases: BranchSetLogicTree

Logic tree which can be the extra logic tree of a FullLogicTree, like PFDLogicTree and AmplificationLogicTree: the realizations are the end branches, with value and path given by the branch IDs. Sampling is inherited from BranchSetLogicTree and walks branchsets without enumerating complete paths. Late sampling chooses uniformly at each branchset, so conditional paths need not have equal selection chances. get_realizations always enumerates the tree; FullLogicTree controls when to request samples instead.

get_realizations()[source]#

Return all end branches in traversal order, without sampling.

property shortener#
Returns:

dict realization path -> two-char abbreviation, matching the format of the source model and GSIM shorteners

exception openquake.hazardlib.lt.LogicTreeError(node, filename, message)[source]#

Bases: Exception

Logic tree file contains a logic error.

Parameters:

node – XML node object that causes fail. Used to determine the affected line number.

All other constructor parameters are passed to superclass' constructor.

class openquake.hazardlib.lt.Realization(value, weight, ordinal, lt_path, samples=1)[source]#

Bases: object

Generic Realization object with attributes value, weight, ordinal, lt_path, samples.

lt_path#
ordinal#
property pid#
samples#
value#
weight#
openquake.hazardlib.lt.abGR(utype, node, filename)[source]#
openquake.hazardlib.lt.abMMax(utype, node, filename)[source]#
openquake.hazardlib.lt.apply_uncertainties(bset_values, src_group, check=True)[source]#
Parameters:
  • bset_values – a list of pairs (branchset, value)

  • src_group – SourceGroup instance

  • check – if True, check that the sources of the correlated branchsets exist; set it to False when the group is a fragment of the original one (as it happens applying the uncertainties in the workers)

Returns:

A copy of the original group with possibly modified sources

openquake.hazardlib.lt.areaGeom(utype, node, filename)[source]#
openquake.hazardlib.lt.attach_branches(ltree, override=False)[source]#

Attach branchsets to branches depending on applyToBranches, plus attach dummy branchsets to dummy branches.

openquake.hazardlib.lt.branches_to_h5(branches, bsetdict)[source]#

Build the (branch_dt array, attrs) pair shared by the logic-tree classes, so their __toh5__ methods do not duplicate the layout.

Parameters:
  • branches – iterable of (branchset_id, branch_id, uncertainty_type, value, weight)

  • bsetdict – mapping branchset_id -> attribute dict

openquake.hazardlib.lt.build(*bslists, applyToSources='')[source]#
Parameters:
  • bslists – a list of lists describing branchsets

  • applyToSources – source ID (used on Absolute uncertainties)

Returns:

a CompositeLogicTree instance

>>> lt = build(['sourceModel', '',
...              ['A', 'common1', 0.6],
...              ['B', 'common2', 0.4]],
...           ['extendModel', '',
...              ['C', 'extra1', 0.6],
...              ['D', 'extra2', 0.2],
...              ['E', 'extra3', 0.2]])
>>> lt.get_all_paths()
['AC', 'AD', 'AE', 'BC', 'BD', 'BE']
openquake.hazardlib.lt.charGeom(utype, node, filename)[source]#
openquake.hazardlib.lt.check_correlated(bset_values, srcids)[source]#

Check that the sources of the correlated branchsets are in the given set of source IDs, i.e. in the sources of the realization. The sources are also looked up by basename, since they can be fragments of the sources in the logic tree (i.e. ‘area1.0’ for ‘area1’)

Parameters:
  • bset_values – a list of pairs (branchset, value)

  • srcids – a set of source IDs and basenames, see source_ids

openquake.hazardlib.lt.complexGeom(utype, node, filename)[source]#
openquake.hazardlib.lt.count_paths(branches)[source]#
Parameters:

branches – a list of branches or a logic tree

Returns:

the total number of paths including sub-branches

openquake.hazardlib.lt.dummy_branchset(branch_id)[source]#
Returns:

a dummy BranchSet with a single branch

openquake.hazardlib.lt.fix_bytes(record)[source]#
openquake.hazardlib.lt.fmtlist(lst)[source]#

Format a list of strings for display purposes.

openquake.hazardlib.lt.get_bset_value(bset, value, source)[source]#
Parameters:
  • bset – a BranchSet instance

  • value – the value of the branch

  • source – a source instance

Returns:

a pair (ok, value), where ok tells if the branchset applies to the source and value is the value to apply to it

NB: the source of a correlated branchset is looked up by ID and by basename, since it can be a fragment of the source in the logic tree (i.e. ‘area1.0’ for ‘area1’); this happens when the uncertainties are applied after the splitting of the sources, as done by classical

openquake.hazardlib.lt.get_bset_values(lt_path, source_model_lt)[source]#
Parameters:
  • lt_path – the logic tree path of a source model realization

  • source_model_lt – a SourceModelLogicTree instance

Returns:

the list of (branchset, value) pairs whose uncertainties must be applied to the sources, i.e. excluding the extendModel branchsets, which add sources and are handled in gen_groups

openquake.hazardlib.lt.h5_to_branches(array)[source]#

Decode a branch_dt array into the shared (utypes, rows) form.

Returns:

utypes maps branchset_id -> uncertainty_type and rows maps branchset_id -> [(branch_id, value, weight), ...] in file order

openquake.hazardlib.lt.incMFD(utype, node, filename)[source]#
openquake.hazardlib.lt.maxMagAndDeltaMagAC(utype, node, filename)[source]#
openquake.hazardlib.lt.multiMFD(utype, node, filename)[source]#
openquake.hazardlib.lt.parse_filters(attrs, sort=False)[source]#
Parameters:
  • attrs – the attributes of a branchset, as read from the XML file or from the datastore (where the lists of IDs can be JSON lists)

  • sort – if True, sort the lists of IDs

Returns:

the filters, i.e. the attributes starting with “applyTo”, with the lists of IDs split

openquake.hazardlib.lt.pfd_model(utype, node, filename)[source]#

Parse an PFD <uncertaintyModel>: a bare model class name or an oq-engine style [ClassName] TOML block of constructor parameters.

Returns:

(class_name, params)

openquake.hazardlib.lt.pfd_r_sigma(utype, node, filename)[source]#

Parse an fdhaCalcRSigma <uncertaintyModel>: the two-sided mapping-accuracy sigma r_sigma_km – a finite float >= 0 (zero selects the boxcar W_p path).

openquake.hazardlib.lt.print_tree(bob, prefix='', is_last=True, _seen=None)[source]#

Recursively prints a tree structure using ASCII art.

Parameters:
  • bob – a tree, a branchset or a branch

  • prefix – The visual padding/lines accumulated from parent levels.

  • is_last – Boolean indicating if this node is the last child

  • _seen – internal mapping of branchsets already expanded

openquake.hazardlib.lt.random(size, seed, sampling_method='early_weights')[source]#
Parameters:
  • size – size of the returned array (integer or pair of integers)

  • seed – random seed

  • sampling_method – ‘early_weights’, ‘early_latin’, …

Returns:

an array of floats in the range 0..1

You can compare montecarlo sampling with latin square sampling with the following code:

openquake.hazardlib.lt.rate_split(utype, node, filename)[source]#
openquake.hazardlib.lt.recur_row(utype, node, filename)[source]#
openquake.hazardlib.lt.recur_set(utype, node, filename)[source]#
openquake.hazardlib.lt.restrict_ts_samples(src, trt_smrs)[source]#
Returns:

a copy of the source with the ts_samples restricted to trt_smrs, i.e. belonging to a single set of uncertainties

openquake.hazardlib.lt.sample(weighted_objects, probabilities, sampling_method='early_weights')[source]#

Take random samples of a sequence of weighted objects

Parameters:
  • weighted_objects – A finite sequence of N objects with a .weight attribute. The weights must sum up to 1.

  • probabilities – An array of S random numbers in the range 0..1

  • sampling_method – Default early_weights, i.e. use the CDF of the weights

Returns:

A list of S objects extracted randomly

openquake.hazardlib.lt.setHypoDepthDistribution(utype, node, filename)[source]#
openquake.hazardlib.lt.setMSR_absolute(utype, node, filename)[source]#
openquake.hazardlib.lt.set_short_id(branches, short_ids)[source]#
openquake.hazardlib.lt.shallow_unc(bset_values, bset_applications, source)[source]#
openquake.hazardlib.lt.simpleGeom(utype, node, filename)[source]#
openquake.hazardlib.lt.smlt_path(branches)[source]#
Returns:

a tuple with the branch IDs (dots for dummy branches)

openquake.hazardlib.lt.smodel(utype, node, filename)[source]#
openquake.hazardlib.lt.source_ids(sources)[source]#
Returns:

the IDs and the basenames of the given sources, as written in the logic tree (i.e. without the branch, see corename)

openquake.hazardlib.lt.to_surface(pairs)[source]#
openquake.hazardlib.lt.trucMFDFromSlip_absolute(utype, node, filename)[source]#
openquake.hazardlib.lt.uncertainty_to_node(utype, value, correlated=False)[source]#

Serialize a text value, parsed MFD uncertainty or correlated mapping. Unparsed uncertaintyModel or MFD nodes are also accepted, so editing a tree does not require parsing and reconstructing unrelated geometries.

openquake.hazardlib.lt.unknown(utype, node, filename)[source]#

pfd_lt#

PFD (Probabilistic Fault Displacement) logic tree.

The PFD logic tree is an NRML 0.4 <logicTree> whose uncertaintyType is one of the four model slots plus the fdhaCalcRSigma calculation parameter, with the <logicTreeBranchSet> elements directly under <logicTree> or wrapped in the legacy <logicTreeBranchingLevel> (both accepted through gsim_lt.bsnodes). Like openquake.hazardlib.logictree.SourceModelLogicTree it is source-oriented (applyToSources / applyToBranches / applyToStyle) and it is built on the generic openquake.hazardlib.lt.Branch/ BranchSet structures, so it exposes a root_branchset and its number of paths is count_paths(root_branchset.branches). The <uncertaintyModel> values are parsed by openquake.hazardlib.lt.parse_uncertainty.

class openquake.hazardlib.pfd_lt.PFDLogicTree(fname, seed=0, num_samples=0, sampling_method='early_weights')[source]#

Bases: ExtraLogicTree

Reader and realization enumerator for PFD-style logic trees.

The XML schema is the oq-pfdha one. The <logicTreeBranchSet> elements may sit directly under <logicTree> or be wrapped in a <logicTreeBranchingLevel>: both are accepted, through the same gsim_lt.bsnodes helper used by SourceModelLogicTree. Each branch set carries one of the four model slots or fdhaCalcRSigma; <uncertaintyModel> is a bare model class name or an oq-engine style [ClassName] TOML block. End branches are enumerated per source with the oq-pfdha applyToSources / applyToBranches / applyToStyle semantics.

check_r_sigma_conflict(r_sigma_km)[source]#

Reject a scalar [calculation] r_sigma_km combined with an fdhaCalcRSigma logic-tree branchset: the two would fight over the same parameter. Either pin it in the job.ini or vary it in the logic tree, not both.

Parameters:

r_sigma_km – the r_sigma_km in the job.ini, or None if missing

selections_for(lt_path, source_id, style)[source]#
Parameters:
  • lt_path – tuple of end-branch IDs (a realization path)

  • source_id – the source id

  • style – the faulting style of the source

Returns:

the selections applicable to the given source, i.e. the global path filtered by applyToSources/applyToStyle

class openquake.hazardlib.pfd_lt.PfdModelChoice(class_name: str, params: dict, branch_id: str, weight: float)[source]#

Bases: object

One uncertaintyModel selection inside a PFD realization.

branch_id: str#
class_name: str#
params: dict#
weight: float#

amp_lt#

Epistemic uncertainty on the site-amplification function: a NRML logic tree whose single uncertaintyType=”amplificationModel” branchset lists per-branch amplification CSV files with weights summing to 1

class openquake.hazardlib.amp_lt.AmplificationLogicTree(names, weights, dframes=None, amplifiers=None, filenames=None, tree_filename='', branchset_id='bs_ampl', rlz_ampl_ord=None)[source]#

Bases: ExtraLogicTree

Site amplification for one or more branches: a logic tree with a single branchset of type amplificationModel, whose branches are the amplification CSV files (a single branch for a plain CSV file)

property amplevels#
amplify(ampl_code, hcurve)[source]#
Parameters:
  • ampl_code – 2-letter code for the amplification function

  • hcurve – an array of shape (L*M, R) on rock levels

Returns:

amplified array of shape (A*M, R) on soil levels

property branchset_id#
check(vs30, vs30_tolerance, gsims_by_trt)[source]#
property filenames#
classmethod from_xml(filename)[source]#
Parameters:

filename – an XML file with a single amplificationModel branchset, whose branches refer to CSV files relative to it

Returns:

an AmplificationLogicTree without amplifiers

classmethod is_amp_lt(filename)[source]#
Returns:

True if the given file is an amplification logic tree XML

property names#
property weights#

near_fault#

Module openquake.hazardlib.nearfault provides methods for near fault PSHA calculation.

openquake.hazardlib.near_fault.average_s_rad(site, hypocenter, reference, pp, normal, dist_to_plane, e, p0, p1, delta_slip)[source]#

Gets the average S-wave radiation pattern given an e-path as described in: Spudich et al. (2013) “Final report of the NGA-West2 directivity working group”, PEER report, page 90- 92 and computes: the site to the direct point distance, rd, and the hypocentral distance, r_hyp.

Parameters:
  • site – Point object representing the location of the target site

  • hypocenter – Point object representing the location of hypocenter

  • reference – Point object representing the location of the reference point for coordinate projection within the calculation. The suggested reference point is Epicentre.

  • pp – the projection point pp on the patch plane, a numpy array

  • normal – normal of the plane, describe by a normal vector[a, b, c]

  • dist_to_plane – d is the constant term in the plane equation, e.g., ax + by + cz = d

  • e – a float defining the E-path length, which is the distance from Pd(direction) point to hypocentre. In km.

  • p0 – Point object representing the location of the starting point on fault segment

  • p1 – Point object representing the location of the ending point on fault segment.

  • delta_slip – slip direction away from the strike direction, in decimal degrees. A positive angle is generated by a counter-clockwise rotation.

Returns:

fs, float value of the average S-wave radiation pattern. rd, float value of the distance from site to the direct point. r_hyp, float value of the hypocetre distance.

openquake.hazardlib.near_fault.build_seg(segment_s, segment_e, pp, pp_xyz, hypocenter_xyz, x_min, y_min, x_max, y_max, atol)[source]#
openquake.hazardlib.near_fault.directp(node0, node1, node2, node3, hypocenter, reference, pp)[source]#

Get the Direct Point and the corresponding E-path as described in Spudich et al. (2013). This method also provides a logical variable stating if the DPP calculation must consider the neighbouring patch. To define the intersection point(Pd) of PpPh line segment and fault plane, we obtain the intersection points(Pd) with each side of fault plan, and check which intersection point(Pd) is the one fitting the definition in the Chiou and Spudich(2014) directivity model. Two possible locations for Pd, the first case, Pd locates on the side of the fault patch when Pp is not inside the fault patch. The second case is when Pp is inside the fault patch, then Pd=Pp.

For the first case, it follows three conditions: 1. the PpPh and PdPh line vector are the same, 2. PpPh >= PdPh, 3. Pd is not inside the fault patch.

If we can not find solution for all the four possible intersection points for the first case, we check if the intersection point fit the second case by checking if Pp is inside the fault patch.

Because of the coordinate system mapping(from geographic system to Catestian system), we allow an error when we check the location. The allow error will keep increasing after each loop when no solution in the two cases are found, until the solution get obtained.

Parameters:
  • node0 – Point object representing the location of one vertices on the target fault segment.

  • node1 – Point object representing the location of one vertices on the target fault segment. Note, the order should be clockwise.

  • node2 – Point object representing the location of one vertices on the target fault segment. Note, the order should be clockwise.

  • node3 – Point object representing the location of one vertices on the target fault segment. Note, the order should be clockwise.

  • hypocenter – Point object representing the location of floating hypocenter on each segment calculation. In the method, we take the direction point of the previous fault patch as hypocentre for the current fault patch.

  • reference – Point object representing the location of reference point for projection

  • pp – the projection of the site onto the plane containing the fault slipped area. A numpy array.

Returns:

Pd, a numpy array, representing the location of direction point E, the distance from direction point to hypocentre. go_next_patch, flag indicates if the calculation goes on the next fault patch. 1: yes, 0: no.

openquake.hazardlib.near_fault.get_plane_equation(p0, p1, p2, reference)[source]#

Define the equation of target fault plane passing through 3 given points which includes two points on the fault trace and one point on the fault plane but away from the fault trace. Note: in order to remain the consistency of the fault normal vector direction definition, the order of the three given points is strickly defined.

Parameters:
  • p0 – The fault trace and is the closer points from the starting point of fault trace. Point object representing the location of the one vertex of the fault patch.

  • p1 – The fault trace and is the further points from the starting point of fault trace. Point object representing the location of the one vertex of the fault patch.

  • p2 – The point on the fault plane but away from the fault trace. Point object representing the location of the one vertex of the fault patch.

  • reference – Point object representing the origin of the cartesian system used the represent objects in a projected reference

Returns:

normal: normal vector of the plane (a,b,c) dist_to_plane: d in the plane equation, ax + by + cz = d

openquake.hazardlib.near_fault.get_xyz_from_ll(projected, reference)[source]#

This method computes the x, y and z coordinates of a set of points provided a reference point.

Parameters:
  • projected – Point object representing the coordinates of target point to be projected

  • reference – Point object representing the coordinates of the reference point.

Returns:

a 3D vector

openquake.hazardlib.near_fault.isochone_ratio(e, rd, r_hyp)[source]#

Get the isochone ratio as described in Spudich et al. (2013) PEER report, page 88.

Parameters:
  • e – a float defining the E-path length, which is the distance from Pd(direction) point to hypocentre. In km.

  • rd – float, distance from the site to the direct point.

  • r_hyp – float, the hypocentre distance.

Returns:

c_prime, a float defining the isochone ratio

openquake.hazardlib.near_fault.projection_pp(site, normal, dist_to_plane, reference)[source]#

This method finds the projection of the site onto the plane containing the slipped area, defined as the Pp(i.e. ‘perpendicular projection of site location onto the fault plane’ Spudich et al. (2013) - page 88) given a site.

Parameters:
  • site – Location of the site, [lon, lat, dep]

  • normal – Normal to the plane including the fault patch, describe by a normal vector[a, b, c]

  • dist_to_plane – D in the plane equation, ax + by + cz = d

  • reference – Point object representing the location of project reference point

Returns:

pp, the projection point, [ppx, ppy, ppz], in xyz domain , a numpy array.

openquake.hazardlib.near_fault.vectors2angle(v1, v2)[source]#

Returns the angle in radians between vectors ‘v1’ and ‘v2’.

Parameters:
  • v1 – vector, a numpy array

  • v2 – vector, a numpy array

Returns:

the angle in radians between the two vetors

nrml#

It is possible to save a Node object into a NRML file by using the function write(nodes, output) where output is a file object. If you want to make sure that the generated file is valid according to the NRML schema just open it in ‘w+’ mode: immediately after writing it will be read and validated. It is also possible to convert a NRML file into a Node object with the routine read(node, input) where input is the path name of the NRML file or a file object opened for reading. The file will be validated as soon as opened.

For instance an exposure file like the following:

<?xml version='1.0' encoding='utf-8'?>
<nrml xmlns="http://openquake.org/xmlns/nrml/0.4"
      xmlns:gml="http://www.opengis.net/gml">
  <exposureModel
      id="my_exposure_model_for_population"
      category="population"
      taxonomySource="fake population datasource">

    <description>
      Sample population
    </description>

    <assets>
      <asset id="asset_01" number="7" taxonomy="IT-PV">
          <location lon="9.15000" lat="45.16667" />
      </asset>

      <asset id="asset_02" number="7" taxonomy="IT-CE">
          <location lon="9.15333" lat="45.12200" />
      </asset>
    </assets>
  </exposureModel>
</nrml>

can be converted as follows:

>> nrml = read(<path_to_the_exposure_file.xml>)

Then subnodes and attributes can be conveniently accessed:

>> nrml.exposureModel.assets[0][‘taxonomy’] ‘IT-PV’ >> nrml.exposureModel.assets[0][‘id’] ‘asset_01’ >> nrml.exposureModel.assets[0].location[‘lon’] ‘9.15000’ >> nrml.exposureModel.assets[0].location[‘lat’] ‘45.16667’

The Node class provides no facility to cast strings into Python types; this is a job for the Node class which can be subclassed and supplemented by a dictionary of validators.

exception openquake.hazardlib.nrml.DuplicatedID[source]#

Bases: Exception

Raised when two sources with the same ID are found in a source model

class openquake.hazardlib.nrml.GeometryModel(sections)[source]#

Bases: object

Contains a dictionary of unique sections

class openquake.hazardlib.nrml.SourceModel(src_groups, name='', investigation_time='', start_time='')[source]#

Bases: Sequence

A container of source groups with attributes name, investigation_time and start_time. It is serialize on hdf5 as follows:

>> with openquake.baselib.hdf5.File(‘/tmp/sm.hdf5’, ‘w’) as f: .. f[‘/’] = source_model

openquake.hazardlib.nrml.get(xml, investigation_time=50.0, rupture_mesh_spacing=5.0, width_of_mfd_bin=1.0, area_source_discretization=10)[source]#
Parameters:
  • xml – the XML representation of a source

  • investigation_time – investigation time

  • rupture_mesh_spacing – rupture mesh spacing

  • width_of_mfd_bin – width of MFD bin

  • area_source_discretization – area source discretization

Returns:

a python source object

openquake.hazardlib.nrml.get_geometry_model(node, fname, converter)[source]#
openquake.hazardlib.nrml.get_rupture_collection(node, fname, converter)[source]#
openquake.hazardlib.nrml.get_source_model_04(node, fname, converter=<openquake.hazardlib.sourceconverter.SourceConverter object>)[source]#
openquake.hazardlib.nrml.get_source_model_05(node, fname, converter=<openquake.hazardlib.sourceconverter.SourceConverter object>)[source]#
openquake.hazardlib.nrml.get_tag_version(nrml_node)[source]#

Extract from a node of kind NRML the tag and the version. For instance from ‘{http://openquake.org/xmlns/nrml/0.4}fragilityModel’ one gets the pair (‘fragilityModel’, ‘nrml/0.4’).

openquake.hazardlib.nrml.read(source, stop=None, stride=None)[source]#

Convert a NRML file into a validated Node object. Keeps the entire tree in memory.

Parameters:
  • source – a file name or file object open for reading

  • stop – the tag where to stop the parsing (if any)

  • stride – if given, a pair (k, n) to keep only the k-th source over n

openquake.hazardlib.nrml.read_source_models(fnames, converter, stride=None)[source]#
Parameters:
Yields:

SourceModel instances

openquake.hazardlib.nrml.to_python(fname, *args)[source]#

Parse a NRML file and return an associated Python object. It works by calling nrml.read() and node_to_obj() in sequence.

openquake.hazardlib.nrml.to_string(node, fmt='%.7E')[source]#

Convert a node into a string in NRML format, using the given float format

openquake.hazardlib.nrml.write(nodes, output=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, fmt='%.7E', gml=True, xmlns=None, commentstr=None)[source]#

Convert nodes into a NRML file. output must be a file object open in write mode. If you want to perform a consistency check, open it in read-write mode, then it will be read after creation and validated.

Params nodes:

an iterable over Node objects

Params output:

a file-like object in write or read-write mode

Parameters:

pmf#

Module openquake.hazardlib.pmf implements PMF.

class openquake.hazardlib.pmf.PMF(data, epsilon=1e-07)[source]#

Bases: object

reduce(bin=0)[source]#

Reduce the original PMF to a single bin distribution.

Parameters:

bin – the bin to keep (default the first)

sample(number_samples)[source]#

Produces a list of samples from the probability mass function.

Parameters:

data (int) – Number of samples

Returns:

Samples from PMF as a list

sample_pairs(number_samples)[source]#

Produces a list of samples from the probability mass function.

Parameters:

data (int) – Number of samples

Returns:

Samples from PMF as a list of pairs

map_array#

class openquake.hazardlib.map_array.MapArray(sids, shape_y, shape_z, rates=False)[source]#

Bases: object

Thin wrapper over a 3D-array of probabilities.

convert(imtls, nsites, idx=0)[source]#

Convert a probability map into a composite array of length nsites and dtype imtls.dt.

Parameters:
  • imtls – DictArray instance

  • nsites – the total number of sites

  • idx – index on the z-axis (default 0)

expand(full_lt, trt_rlzs)[source]#

Convert a MapArray with shape (N, L, Gt) into a MapArray with shape (N, L, R): works only for rates

fill(value)[source]#
Parameters:

value – a scalar probability

Fill the MapArray underlying array with the given scalar and build the .sidx array

interp4D(imtls, poes)[source]#
Parameters:
  • imtls – a dictionary imt->imls with M items

  • poes – a list of P PoEs

Returns:

an array of shape (N, M, P, Z)

new(arr)[source]#
remove_zeros()[source]#
reshape(N, M, P)[source]#
Returns:

a new Pmap associated to a reshaped array

property sidx#
Returns:

an array of length N site_id -> index

property size_mb#
split()[source]#
Yields:

G MapArrays of shape (N, L, 1)

to_array(gid)[source]#

Assuming self contains an array of rates, returns a composite array with fields sid, lid, gid, rate

to_dframe()[source]#
Returns:

a DataFrame with fields sid, gid, lid, poe

to_rates(itime=1.0)[source]#

Convert into a map of rates unless the map already contains rates

update_indep(poes, ctxt, itime, rates=None, gslc=slice(None, None, None))[source]#

Update probabilities for independent ruptures; if gslc is given, only the gsims in that slice are updated

update_mutex(poes, ctxt, itime, mutex_weight)[source]#

Update probabilities for mutex ruptures

class openquake.hazardlib.map_array.RateMap(sids, L, gids)[source]#

Bases: object

A kind of MapArray specifically for rates

level0 = 0#
property sidx#
Returns:

an array of length N site_id -> index

property size_mb#
split(L1)[source]#

Split in M = L / L1 RateMaps, one for each IMT

to_array(g)[source]#

Assuming self contains an array of rates, returns a composite array with fields sid, lid, gid, rate

openquake.hazardlib.map_array.check_hmaps(hcurves, imtls, poes)[source]#
Parameters:
  • hcurves – hazard curves of shape (N, M, L1)

  • imtls – a dictionary imt -> imls

  • poes – a list of poes

  • poes – P poes

openquake.hazardlib.map_array.combine_probs(array, other, rlzs)[source]#
openquake.hazardlib.map_array.compute_hazard_maps(curves, imls, poes)[source]#

Given a set of hazard curve poes, interpolate hazard maps at the specified poes.

Parameters:
  • curves – Array of floats of shape N x L. Each row represents a curve, where the values in the row are the PoEs (Probabilities of Exceedance) corresponding to the imls. Each curve corresponds to a geographical location.

  • imls – Intensity Measure Levels associated with these hazard curves. Type should be an array-like of floats.

  • poes – Value(s) on which to interpolate a hazard map from the input curves.

Returns:

An array of shape N x P, where N is the number of curves and P the number of poes.

openquake.hazardlib.map_array.compute_hmaps(curvesNML, imtls, poes)[source]#
Parameters:
  • curvesNML – an array of shape (N, M, L1)

  • imlts – a DictArray with M keys

  • poes – a sequence of P poes

Returns:

array of shape (N, M, P) with the hazard maps

openquake.hazardlib.map_array.fix_probs_occur(probs_occur)[source]#

Try to convert object arrays into regular arrays

openquake.hazardlib.map_array.gen_chunks(sids, num_chunks)[source]#
Yields:

chunkno, mask

openquake.hazardlib.map_array.get_lvl(hcurve, imls, poe)[source]#
Parameters:
  • hcurve – a hazard curve, i.e. array of L1 PoEs

  • imls – L1 intensity measure levels

Returns:

index of the intensity measure level associated to the poe

>>> imls = numpy.array([.1, .2, .3, .4])
>>> hcurve = numpy.array([1., .99, .90, .8])
>>> int(get_lvl(hcurve, imls, 1))
0
>>> int(get_lvl(hcurve, imls, .99))
1
>>> int(get_lvl(hcurve, imls, .91))
2
>>> int(get_lvl(hcurve, imls, .8))
3
openquake.hazardlib.map_array.get_mean_curve(dstore, imt, site_id=0)[source]#

Extract the mean hazard curve from the datastore for the first site.

openquake.hazardlib.map_array.get_poe_from_mean_curve(dstore, imt, iml, site_id=0)[source]#

Extract the poe corresponding to the given iml by looking at the mean curve for the given imt. iml can also be an array.

openquake.hazardlib.map_array.iadd(arr, array, sidx)[source]#
openquake.hazardlib.map_array.to_rates(ratesNLG, sids, g, i, level0)[source]#
Parameters:
  • ratesNLG – an array of shape (N, L, G)

  • sids – an array of site IDs

  • g – an integer representing a GSIM index

  • i – an index in the range 0..G-1

  • level0 – level offset

openquake.hazardlib.map_array.update_pmap_i(arr, poes, rates, probs_occur, sidxs, itime)[source]#
openquake.hazardlib.map_array.update_pmap_m(arr, poes, rates, probs_occur, weights, sidxs, itime)[source]#
openquake.hazardlib.map_array.update_pmap_r(arr, poes, rates, probs_occur, sidxs, itime)[source]#

site#

Module openquake.hazardlib.site defines Site.

openquake.hazardlib.site.CORE_SITE_PARAMS = ('lon', 'lat', 'vs30', 'z1pt0', 'z2pt5', 'z1pt4')#

Core site parameters whose NaN values would silently produce NaN hazard; lon/lat included because valid.coordinates accepts ‘nan’

class openquake.hazardlib.site.Site(location, vs30=nan, z1pt0=nan, z2pt5=nan, **extras)[source]#

Bases: object

Site object represents a geographical location defined by its position as well as its soil characteristics.

Parameters:
  • location – Instance of Point representing where the site is located.

  • vs30 – Average shear wave velocity in the top 30 m, in m/s.

  • z1pt0 – Vertical distance from earth surface to the layer where seismic waves start to propagate with a speed above 1.0 km/sec, in meters.

  • z2pt5 – Vertical distance from earth surface to the layer where seismic waves start to propagate with a speed above 2.5 km/sec, in km.

Raises:

ValueError – If vs30 is zero or negative OR z1pt0 or z2pt5 is zero, or negative AND not -999 (a value of -999 informs basin param using GMMs to estimate values for such sites with median value from GMM’s own vs30 to z1pt0 or z2pt5 relationship).

Note

Sites are pickleable

class openquake.hazardlib.site.SiteCollection(sites)[source]#

Bases: object

add_col(colname, dtype, values=None)[source]#

Add a column to the underlying array (if not already there)

assoc(site_model, assoc_dist, mode, ignore=(), station_sids=None)[source]#

Associate the site_model parameters to the sites. Log a warning if the site parameters are more distant than assoc_dist.

Parameters:

station_sids – set of site ids that should bypass ‘strict’ distance checks

Returns:

the site model array reduced to the hazard sites

at_sea_level()[source]#

True if all depths are zero

by_country()[source]#

Returns a table with the number of sites per country.

calculate_z1pt0()[source]#

Compute the column z1pt0 from the vs30 using a region-dependent formula for NGA-West2

calculate_z2pt5()[source]#

Compute the column z2pt5 from the vs30 using a region-dependent formula for NGA-West2

check_nan(fields)[source]#

Raise a ValueError if any of the given fields contains NaNs. fields may be a single field name or a sequence of them.

count_close(location, distance)[source]#
Parameters:
  • location – a Point, a record with ‘hypo’, or a Mesh

  • distance – a distance in km

Returns:

the number of sites within the distance from the location, or an array of counts for a Mesh, in flattened mesh order

NB: mesh queries are vectorized and reuse a KDTree, so they are much faster than calling SourceFilter.close_sids on many point sources.

property countries#

Return the countries for each site in the SiteCollection. The boundaries of the countries are defined as in the file geoBoundariesCGAZ_ADM0.gpkg

ensure_custom_site_id(size)[source]#

Add a custom_site_id if not present

extend(lons, lats)[source]#

Extend the site collection to additional (and different) points. Used for station_data in conditioned GMFs.

filter(mask)[source]#

Create a SiteCollection with only a subset of sites.

Parameters:

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 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.

filtered(indices)[source]#
Parameters:

indices – a subset of indices in the range [0 .. tot_sites - 1]

Returns:

a filtered SiteCollection instance if indices is a proper subset of the available indices, otherwise returns the full SiteCollection

classmethod from_(array)[source]#

Build a site collection from a site model array

classmethod from_planar(rup, point='TC', toward_azimuth=90, direction='positive', hdist=100, step=5.0, req_site_params=())[source]#
Parameters:

rup – a rupture built with rupture.get_planar

Returns:

a openquake.hazardlib.site.SiteCollection instance

classmethod from_points(lons, lats, depths=None, sitemodel=None, req_site_params=())[source]#

Build the site collection from

Parameters:
  • lons – a sequence of longitudes

  • lats – a sequence of latitudes

  • depths – a sequence of depths (or None)

  • sitemodel – None or an object containing site parameters as attributes

  • req_site_params – a sequence of required site parameters, possibly empty

classmethod from_usgs_shakemap(shakemap_array)[source]#

Build a site collection from a shakemap array

geohash(length)[source]#
Parameters:

length – length of the geohash in the range 1..8

Returns:

an array of N geohashes, one per site

get_around(lon, lat, digits=5)[source]#
Returns:

the submesh around lon, lat with the given precision

get_cdist(rec_or_loc)[source]#
Parameters:

rec_or_loc – a record with field ‘hypo’ or a Point instance

Returns:

array of N euclidean distances from rec[‘hypo’]

lower_res(res=2)[source]#

Collapse together points within the same hexagon (with an edge of 84 km for res=2, the default).

Returns:

(reduce sitecol, list of arrays orig_sids)

make_complete()[source]#

Turns the site collection into a complete one, if needed

property mesh#
Returns:

a mesh with the given lons, lats, and depths

multiply(vs30s, soil_classes=array([b'E', b'DE', b'D', b'CD', b'C', b'BC', b'B', b'A'], dtype='|S2'), soil_values=array([152., 213., 305., 442., 640., 914., 1500.]))[source]#

Multiply a site collection with the given vs30 values. NB: if there are multiple values the sites with vs30 = -999. are multiplied, otherwise the given value is applied to all sites.

property names#
Returns:

.array.dtype.names

num_geohashes(length)[source]#
Parameters:

length – length of the geohash in the range 1..8

Returns:

number of distinct geohashes in the site collection

one()[source]#
Returns:

a SiteCollection with a site of the minimal vs30

reduce(nsites)[source]#
Returns:

a filtered SiteCollection with at most nsites sites evenly spread over the region, obtained by taking every n-th site in geohash order, with n = ceil(N / nsites)

req_site_params = ()#
set_global_params(oq, req_site_params=('z1pt0', 'z2pt5'))[source]#

Set the global site parameters (i.e. those specifiable in the job file as reference values).

split(ntiles, minsize=1)[source]#
Parameters:

ntiles – number of tiles to generate (ceiled if float)

Returns:

self if there are <=1 tiles, otherwise the tiles

split_by_gh3()[source]#

Split a SiteCollection into a set of tiles with the same geohash3

split_in_tiles(hint)[source]#

Split a SiteCollection into at most hint tiles, assigning the site IDs round-robin (sids % hint), so that the sites of a tile are not contiguous in space; the empty tiles are dropped

split_max(max_sites)[source]#

Split a SiteCollection into SiteCollection instances

within(region)[source]#
Parameters:

region – a shapely polygon

Returns:

a filtered SiteCollection of sites within the region

within_bbox(bbox)[source]#
Parameters:

bbox – a quartet (min_lon, min_lat, max_lon, max_lat)

Returns:

site IDs within the bounding box

NB: if the bounding box crosses the IDL, do not filter.

property xyz#
Returns:

an array of shape (N, 3) with the cartesian coordinates

class openquake.hazardlib.site.TileGetter(tileno, ntiles)[source]#

Bases: object

An extractor complete->tile

get_tile_size(complete)[source]#
Returns:

how many sites per tile (at max)

openquake.hazardlib.site.add(string, suffix, maxlen)[source]#

Add a suffix to a string staying within the maxlen limit

>>> add('pippo', ':xxx', 8)
'pippo:xx'
>>> add('pippo', ':x', 8)
'pippo:x'
openquake.hazardlib.site.calculate_z1pt0(vs30, country)[source]#

Reads an array of vs30 values (in m/s) and returns the depth to the 1.0 km/s velocity horizon (in m) Ref: Chiou, B. S.-J. and Youngs, R. R., 2014. ‘Update of the Chiou and Youngs NGA model for the average horizontal component of peak ground motion and response spectra.’ Earthquake Spectra, 30(3), pp.1117–1153. :param vs30: the shear wave velocity (in m/s) at a depth of 30m :param country: country as defined by geoBoundariesCGAZ_ADM0.gpkg

openquake.hazardlib.site.calculate_z2pt5(vs30, country)[source]#

Reads an array of vs30 values (in m/s) and returns the depth to the 2.5 km/s velocity horizon (in km) Ref: Campbell, K.W. & Bozorgnia, Y., 2014. ‘NGA-West2 ground motion model for the average horizontal components of PGA, PGV, and 5pct damped linear acceleration response spectra.’ Earthquake Spectra, 30(3), pp.1087–1114.

Parameters:
  • vs30 – the shear wave velocity (in m/s) at a depth of 30 m

  • country – country as defined by geoBoundariesCGAZ_ADM0.gpkg

openquake.hazardlib.site.check_all_equal(mosaic_model, dicts, *keys)[source]#

Check all the dictionaries have the same value for the same key

openquake.hazardlib.site.get_countries(lons, lats)[source]#
Returns:

array of 3-letter country codes

openquake.hazardlib.site.merge_sitecols(hdf5fnames, mosaic_model='', check_gmfs=False)[source]#

Read a number of site collections from the given filenames and returns a single SiteCollection instance, plus a list of site ID arrays, one for each site collection, excluding the duplicates.

If check_gmfs is set, assume there are gmf_data groups and make sure the attributes are consistent (i.e. the same over all files).

openquake.hazardlib.site.merge_without_dupl(array1, array2, uniquefield)[source]#
>>> dt = [('code', 'S1'), ('value', numpy.int32)]
>>> a1 = numpy.array([('a', 1), ('b', 2)], dt)
>>> a2 = numpy.array([('b', 2), ('c', 3)], dt)
>>> merged, dupl = merge_without_dupl(a1, a2, 'code')
>>> merged
array([(b'a', 1), (b'b', 2), (b'c', 3)],
      dtype=[('code', 'S1'), ('value', '<i4')])
>>> a2[dupl]
array([(b'b', 2)], dtype=[('code', 'S1'), ('value', '<i4')])
openquake.hazardlib.site.rnd5(lons)[source]#

sourceconverter#

class openquake.hazardlib.sourceconverter.NPRow(id: str, name: str, code: str, tectonicregion: str, geom: str, coords: list, wkt: str)[source]#

Bases: object

code: str#
coords: list#
geom: str#
id: str#
name: str#
tectonicregion: str#
wkt: str#
class openquake.hazardlib.sourceconverter.Row(id: str, name: str, code: str, groupname: str, tectonicregion: str, mfd: str, magscalerel: str, ruptaspectratio: float, upperseismodepth: float, lowerseismodepth: float, nodalplanedist: list, hypodepthdist: list, hypoList: list, slipList: list, rake: float, geomprops: list, geom: str, coords: list, wkt: str)[source]#

Bases: object

code: str#
coords: list#
geom: str#
geomprops: list#
groupname: str#
hypoList: list#
hypodepthdist: list#
id: str#
lowerseismodepth: float#
magscalerel: str#
mfd: str#
name: str#
nodalplanedist: list#
rake: float#
ruptaspectratio: float#
slipList: list#
tectonicregion: str#
upperseismodepth: float#
wkt: str#
class openquake.hazardlib.sourceconverter.RowConverter(investigation_time=50.0, rupture_mesh_spacing=5.0, complex_fault_mesh_spacing=None, width_of_mfd_bin=1.0, area_source_discretization=None, minimum_magnitude={'default': 0}, source_id=(), discard_trts=(), floating_x_step=0, floating_y_step=0, source_nodes=(), infer_occur_rates=False, filter_sourcecodes='')[source]#

Bases: SourceConverter

Used in the command oq nrml_to_csv to convert source models into Row objects.

convert_areaSource(node)[source]#

Convert the given node into an area source object.

Parameters:

node – a node with tag areaGeometry

Returns:

a openquake.hazardlib.source.AreaSource instance

convert_characteristicFaultSource(node)[source]#

Convert the given node into a characteristic fault object.

Parameters:

node – a characteristicFaultSource node

Returns:

a openquake.hazardlib.source.CharacteristicFaultSource instance

convert_complexFaultSource(node)[source]#

Convert the given node into a complex fault object.

Parameters:

node – a node with tag areaGeometry

Returns:

a openquake.hazardlib.source.ComplexFaultSource instance

convert_geomprops(node)[source]#
convert_hddist(node)[source]#

Convert the given node into a probability mass function for the hypo depth distribution.

Parameters:

node – a hypoDepthDist node

Returns:

a openquake.hazardlib.pmf.PMF instance

convert_hypolist(node)[source]#
convert_mfdist(node)[source]#

Convert the given node into a Magnitude-Frequency Distribution object.

Parameters:

node – a node of kind incrementalMFD or truncGutenbergRichterMFD

Returns:

a openquake.hazardlib.mfd.EvenlyDiscretizedMFD. or openquake.hazardlib.mfd.TruncatedGRMFD instance

convert_multiFaultSource(node)[source]#

Convert the given node into a multi fault source object.

Parameters:

node – a node with tag multiFaultSource

Returns:

a openquake.hazardlib.source.multiFaultSource instance

convert_multiPointSource(node)[source]#

Convert the given node into a MultiPointSource object.

Parameters:

node – a node with tag multiPointGeometry

Returns:

a openquake.hazardlib.source.MultiPointSource

convert_node(node)[source]#

Convert the given source node into a Row object

convert_nonParametricSeismicSource(node)[source]#

Convert the given node into a non parametric source object.

Parameters:

node – a node with tag areaGeometry

Returns:

a openquake.hazardlib.source.NonParametricSeismicSource instance

convert_npdist(node)[source]#

Convert the given node into a Nodal Plane Distribution.

Parameters:

node – a nodalPlaneDist node

Returns:

a openquake.hazardlib.geo.NodalPlane instance

convert_pointSource(node)[source]#

Convert the given node into a point source object.

Parameters:

node – a node with tag pointGeometry

Returns:

a openquake.hazardlib.source.PointSource instance

convert_rake(node)[source]#
convert_simpleFaultSource(node)[source]#

Convert the given node into a simple fault object.

Parameters:

node – a node with tag areaGeometry

Returns:

a openquake.hazardlib.source.SimpleFaultSource instance

convert_sliplist(node)[source]#
class openquake.hazardlib.sourceconverter.RuptureConverter(rupture_mesh_spacing, complex_fault_mesh_spacing=None)[source]#

Bases: object

Convert ruptures from nodes into Hazardlib ruptures.

convert_complexFaultRupture(node)[source]#

Convert a complexFaultRupture node.

Parameters:

node – the rupture node

convert_griddedRupture(node)[source]#

Convert a griddedRupture node.

Parameters:

node – the rupture node

convert_multiPlanesRupture(node)[source]#

Convert a multiPlanesRupture node.

Parameters:

node – the rupture node

convert_node(node)[source]#

Convert the given rupture node into a hazardlib rupture, depending on the node tag.

Parameters:

node – a node representing a rupture

convert_ruptureCollection(node)[source]#
Parameters:

node – a ruptureCollection node

Returns:

a dictionary trt_smr -> EBRuptures

convert_simpleFaultRupture(node)[source]#

Convert a simpleFaultRupture node.

Parameters:

node – the rupture node

convert_singlePlaneRupture(node)[source]#

Convert a singlePlaneRupture node.

Parameters:

node – the rupture node

convert_surfaces(surface_nodes, sec_id='')[source]#
Parameters:

surface_nodes – surface nodes as described below

Utility to convert a list of surface nodes into a single hazardlib surface. There are four possibilities:

  1. there is a single simpleFaultGeometry node; returns a openquake.hazardlib.geo.simpleFaultSurface instance

  2. there is a single complexFaultGeometry node; returns a openquake.hazardlib.geo.complexFaultSurface instance

  3. there is a single griddedSurface node; returns a openquake.hazardlib.geo.GriddedSurface instance

  4. there is either a single planarSurface or a list of planarSurface nodes; returns a openquake.hazardlib.geo.PlanarSurface instance or a openquake.hazardlib.geo.MultiSurface instance

  5. there is either a single kiteSurface or a list of kiteSurface nodes; returns a openquake.hazardlib.geo.KiteSurface instance or a openquake.hazardlib.geo.MultiSurface instance

fname = None#
geo_line(edge)[source]#

Utility function to convert a node of kind edge into a openquake.hazardlib.geo.Line instance.

Parameters:

edge – a node describing an edge

geo_lines(edges)[source]#

Utility function to convert a list of edges into a list of openquake.hazardlib.geo.Line instances.

Parameters:

edge – a node describing an edge

geo_planar(surface)[source]#

Utility to convert a PlanarSurface node with subnodes topLeft, topRight, bottomLeft, bottomRight into a openquake.hazardlib.geo.PlanarSurface instance.

Parameters:

surface – PlanarSurface node

get_mag_rake_hypo(node)[source]#
class openquake.hazardlib.sourceconverter.SourceConverter(investigation_time=50.0, rupture_mesh_spacing=5.0, complex_fault_mesh_spacing=None, width_of_mfd_bin=1.0, area_source_discretization=None, minimum_magnitude={'default': 0}, source_id=(), discard_trts=(), floating_x_step=0, floating_y_step=0, source_nodes=(), infer_occur_rates=False, filter_sourcecodes='')[source]#

Bases: RuptureConverter

Convert sources from valid nodes into Hazardlib objects.

convert_areaSource(node)[source]#

Convert the given node into an area source object.

Parameters:

node – a node with tag areaGeometry

Returns:

a openquake.hazardlib.source.AreaSource instance

convert_characteristicFaultSource(node)[source]#

Convert the given node into a characteristic fault object.

Parameters:

node – a characteristicFaultSource node

Returns:

a openquake.hazardlib.source.CharacteristicFaultSource instance

convert_complexFaultSource(node)[source]#

Convert the given node into a complex fault object.

Parameters:

node – a node with tag areaGeometry

Returns:

a openquake.hazardlib.source.ComplexFaultSource instance

convert_geometryModel(node)[source]#
Parameters:

node – a geometryModel node

Returns:

a dictionary sec_id -> section

convert_hddist(node)[source]#

Convert the given node into a probability mass function for the hypo depth distribution.

Parameters:

node – a hypoDepthDist node

Returns:

a openquake.hazardlib.pmf.PMF instance

convert_hypo_dip_fracs(node)[source]#

Read fixedDipFrac from each hypoDepth entry in a hypoDepthDist.

Each value is the down-dip fraction placing the hypocentre on the rupture (0=top, 1=bottom); the rupture is shifted so the hypocentre lands at that fraction along dip, then clamped to [USD, LSD].

NOTE: Missing entries default to 0.5 (rupture centroid, default OQ behaviour).

NOTE: Returns None when no entry specifies fixedDipFrac.

convert_kiteFaultSource(node)[source]#

Convert the given node into a kite fault object.

Parameters:

node – a node with tag kiteFaultSource

Returns:

a openquake.hazardlib.source.KiteFaultSource instance

convert_mfdist(node)[source]#

Convert the given node into a Magnitude-Frequency Distribution object.

Parameters:

node – a node of kind incrementalMFD or truncGutenbergRichterMFD

Returns:

a openquake.hazardlib.mfd.EvenlyDiscretizedMFD. or openquake.hazardlib.mfd.TruncatedGRMFD instance

convert_multiFaultSource(node)[source]#

Convert the given node into a multi fault source object.

Parameters:

node – a node with tag multiFaultSource

Returns:

a openquake.hazardlib.source.multiFaultSource instance

convert_multiPointSource(node)[source]#

Convert the given node into a MultiPointSource object.

Parameters:

node – a node with tag multiPointGeometry

Returns:

a openquake.hazardlib.source.MultiPointSource

convert_node(node)[source]#

Convert the given node into a hazardlib source or group, depending on the node tag.

Parameters:

node – a node representing a source or a SourceGroup

convert_nonParametricSeismicSource(node)[source]#

Convert the given node into a non parametric source object.

Parameters:

node – a node with tag areaGeometry

Returns:

a openquake.hazardlib.source.NonParametricSeismicSource instance

convert_npdist(node)[source]#

Convert the given node into a Nodal Plane Distribution.

Parameters:

node – a nodalPlaneDist node

Returns:

a openquake.hazardlib.geo.NodalPlane instance

convert_pointSource(node)[source]#

Convert the given node into a point source object.

Parameters:

node – a node with tag pointGeometry

Returns:

a openquake.hazardlib.source.PointSource instance

convert_section(node)[source]#
Parameters:

node – a section node

Returns:

a list of surfaces

convert_simpleFaultSource(node)[source]#

Convert the given node into a simple fault object.

Parameters:

node – a node with tag areaGeometry

Returns:

a openquake.hazardlib.source.SimpleFaultSource instance

convert_sourceGroup(node)[source]#

Convert the given node into a SourceGroup object.

Parameters:

node – a node with tag sourceGroup

Returns:

a SourceGroup instance

convert_sourceModel(node)[source]#
get_tom(node)[source]#

Convert the given node into a Temporal Occurrence Model object.

Parameters:

node – a node of kind poissonTOM or similar

Returns:

a openquake.hazardlib.tom.BaseTOM instance

openquake.hazardlib.sourceconverter.collapse(array)[source]#

Collapse a homogeneous array into a scalar; do nothing if the array is not homogenous

openquake.hazardlib.sourceconverter.convert_nonParametricSeismicSource(fname, node, rup_spacing=5.0)[source]#

Convert the given node into a non parametric source object.

Parameters:
  • fname – full pathname to the XML file associated to the node

  • node – a Node object coming from an XML file

  • rup_spacing – Rupture spacing [km]

Returns:

a openquake.hazardlib.source.NonParametricSeismicSource instance

openquake.hazardlib.sourceconverter.drop_trivial_weights(group)[source]#
openquake.hazardlib.sourceconverter.extract_dupl(values)[source]#
Parameters:

values – a sequence of values

Returns:

the duplicated values

openquake.hazardlib.sourceconverter.fix_dupl(dist, fname=None, lineno=None)[source]#

Fix the distribution if it contains identical values or raise an error.

Parameters:
  • dist – a list of pairs [(prob, value)…] for a hypocenter or nodal plane dist

  • fname – the file which is being read; if it is None, it means you are writing the distribution: in that case raise an error for duplicated values

  • lineno – the line number of the file which is being read (None in writing mode)

openquake.hazardlib.sourceconverter.mfds2multimfd(mfds)[source]#

Convert a list of MFD nodes into a single MultiMFD node

openquake.hazardlib.sourceconverter.multikey(node)[source]#
Returns:

(usd, lsd, rar, hddist, npdist, magScaleRel) for the given node

openquake.hazardlib.sourceconverter.rounded_unique(mags, idxs)[source]#
Parameters:
  • mags – a list of magnitudes

  • idxs – a list of tuples of section indices

Returns:

an array of magnitudes rounded to 2 digits

Raises:

ValueError if the rounded magnitudes contain duplicates

openquake.hazardlib.sourceconverter.split_coords_2d(seq)[source]#
Parameters:

seq – a flat list with lons and lats

Returns:

a validated list of pairs (lon, lat)

>>> split_coords_2d([1.1, 2.1, 2.2, 2.3])
[(1.1, 2.1), (2.2, 2.3)]
openquake.hazardlib.sourceconverter.split_coords_3d(seq)[source]#
Parameters:

seq – a flat list with lons, lats and depths

Returns:

a validated list of (lon, lat, depths) triplets

>>> split_coords_3d([1.1, 2.1, 0.1, 2.3, 2.4, 0.1])
[(1.1, 2.1, 0.1), (2.3, 2.4, 0.1)]
openquake.hazardlib.sourceconverter.update_source_model(sm_node, fname)[source]#
Parameters:

sm_node – a sourceModel Node object containing sourceGroups

sourcewriter#

Source model XML Writer

openquake.hazardlib.sourcewriter.build_arbitrary_mfd(mfd)[source]#

Parses the arbitrary MFD as a Node

Parameters:

mfd – MFD as instance of :class: openquake.hazardlib.mfd.arbitrary.ArbitraryMFD

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_area_source_geometry(area_source)[source]#

Returns the area source geometry as a Node

Parameters:

area_source – Area source model as an instance of the :class: openquake.hazardlib.source.area.AreaSource

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_area_source_node(area_source)[source]#

Parses an area source to a Node class

Parameters:

area_source – Area source as instance of :class: openquake.hazardlib.source.area.AreaSource

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_characteristic_fault_source_node(source)[source]#
openquake.hazardlib.sourcewriter.build_complex_fault_geometry(fault_source)[source]#

Returns the complex fault source geometry as a Node

Parameters:

fault_source – Complex fault source model as an instance of the :class: openquake.hazardlib.source.complex_fault.ComplexFaultSource

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_complex_fault_source_node(fault_source)[source]#

Parses a complex fault source to a Node class

Parameters:

fault_source – Complex fault source as instance of :class: openquake.hazardlib.source.complex_fault.ComplexFaultSource

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_evenly_discretised_mfd(mfd)[source]#

Returns the evenly discretized MFD as a Node

Parameters:

mfd – MFD as instance of :class: openquake.hazardlib.mfd.evenly_discretized.EvenlyDiscretizedMFD

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_hypo_depth_dist(hypo_depth_list)[source]#

Returns a hypoDepthDist Node from a list of (prob, depth, fdf_or_None) triples.

Parameters:

hypo_depth_list – List of (probability, depth, fixed_dip_frac_or_None) triples.

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_hypo_list_node(hypo_list)[source]#
Parameters:

hypo_list – an array of shape (N, 3) with columns (alongStrike, downDip, weight)

Returns:

a hypoList node containing N hypo nodes

openquake.hazardlib.sourcewriter.build_kite_fault_source_node(fault_source)[source]#

Parses a kite fault source to a Node class

Parameters:

fault_source – Kite fault source as instance of :class: openquake.hazardlib.source.kite_fault.KiteFaultSource

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_kite_surface(ksurface)[source]#

Returns the KiteSurface instance as a Node

Parameters:

ksurface – Kite fault source model as an instance of the :class: openquake.hazardlib.source.kite_fault.KiteFaultSource

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_linestring_node(line, with_depth=False)[source]#

Parses a line to a Node class

Parameters:
Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_multi_fault_source_node(multi_fault_source)[source]#

Parses a MultiFaultSource to a Node class

Parameters:

multi_fault_source – Multi fault source as instance of :class: openquake.hazardlib.source.multi_fault.MultiFaultSource

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_multi_mfd(mfd)[source]#

Parses the MultiMFD as a Node

Parameters:

mfd – MFD as instance of :class: openquake.hazardlib.mfd.multi_mfd.MultiMFD

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_multi_point_source_node(multi_point_source)[source]#

Parses a point source to a Node class

Parameters:

point_source – MultiPoint source as instance of :class: openquake.hazardlib.source.point.MultiPointSource

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_nodal_plane_dist(npd)[source]#

Returns the nodal plane distribution as a Node instance

Parameters:

npd – Nodal plane distribution as instance of :class: openquake.hazardlib.pmf.PMF

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_nonparametric_source_node(source)[source]#
openquake.hazardlib.sourcewriter.build_point_source_geometry(point_source)[source]#

Returns the poing source geometry as a Node

Parameters:

point_source – Point source model as an instance of the :class: openquake.hazardlib.source.point.PointSource

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_point_source_node(point_source)[source]#

Parses a point source to a Node class

Parameters:

point_source – Point source as instance of :class: openquake.hazardlib.source.point.PointSource

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_rupture_node(rupt, probs_occur)[source]#
Parameters:
  • rupt – a hazardlib rupture object

  • probs_occur – a list of floats with sum 1

openquake.hazardlib.sourcewriter.build_simple_fault_geometry(fault_source)[source]#

Returns the simple fault source geometry as a Node

Parameters:

fault_source – Simple fault source model as an instance of the :class: openquake.hazardlib.source.simple_fault.SimpleFaultSource

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_simple_fault_source_node(fault_source)[source]#

Parses a simple fault source to a Node class

Parameters:

fault_source – Simple fault source as instance of :class: openquake.hazardlib.source.simple_fault.SimpleFaultSource

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_slip_list_node(slip_list)[source]#
Parameters:

slip_list – an array of shape (N, 2) with columns (slip, weight)

Returns:

a hypoList node containing N slip nodes

openquake.hazardlib.sourcewriter.build_source_group(source_group)[source]#
openquake.hazardlib.sourcewriter.build_source_model(csm)[source]#
openquake.hazardlib.sourcewriter.build_source_model_node(source_model)[source]#
openquake.hazardlib.sourcewriter.build_tapered_gr_mfd(mfd)[source]#

Parses the truncated Gutenberg Richter MFD as a Node

Parameters:

mfd – MFD as instance of :class: openquake.hazardlib.mfd.tapered_gr_mfd.TaperedGRMFD

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_truncated_gr_mfd(mfd)[source]#

Parses the truncated Gutenberg Richter MFD as a Node

Parameters:

mfd – MFD as instance of :class: openquake.hazardlib.mfd.truncated_gr.TruncatedGRMFD

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.build_youngs_coppersmith_mfd(mfd)[source]#

Parses the Youngs & Coppersmith MFD as a node. Note that the MFD does not hold the total moment rate, but only the characteristic rate. Therefore the node is written to the characteristic rate version regardless of whether or not it was originally created from total moment rate

Parameters:

mfd – MFD as instance of :class: openquake.hazardlib.mfd.youngs_coppersmith_1985. YoungsCoppersmith1985MFD

Returns:

Instance of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.extract_gridded_attrs(src_groups)[source]#

Extract the attributes of nonparametric/multifault sources. The attributes are arrays or a list of strings for rupture_idxs.

Returns:

a dictionary source_id -> attr -> value

openquake.hazardlib.sourcewriter.get_distributed_seismicity_source_nodes(source)[source]#

Returns list of nodes of attributes common to all distributed seismicity source classes

Parameters:

source – Seismic source as instance of :class: openquake.hazardlib.source.area.AreaSource or :class: openquake.hazardlib.source.point.PointSource

Returns:

List of instances of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.get_fault_source_nodes(source)[source]#

Returns list of nodes of attributes common to all fault source classes

Parameters:

source – Fault source as instance of :class: openquake.hazardlib.source.simple_fault.SimpleFaultSource or :class: openquake.hazardlib.source.complex_fault.ComplexFaultSource

Returns:

List of instances of openquake.baselib.node.Node

openquake.hazardlib.sourcewriter.get_source_attributes(source)[source]#

Retreives a dictionary of source attributes from the source class

Parameters:

source – Seismic source as instance of :class: openquake.hazardlib.source.base.BaseSeismicSource

Returns:

Dictionary of source attributes

openquake.hazardlib.sourcewriter.r4(x)[source]#

Round lon, lat to 4 digits (11 meters)

openquake.hazardlib.sourcewriter.tomldump(obj, fileobj=None)[source]#

Write a generic serializable object in TOML format

openquake.hazardlib.sourcewriter.write_source_model(dest, sources_or_groups, name=None, investigation_time=None, prefix='')[source]#

Writes a source model to XML.

Parameters:
  • dest – Destination path

  • sources_or_groups – Source model in different formats

  • name – Name of the source model (if missing, extracted from the filename)

  • investigation_time – Investigation time (for time-dependent sources)

  • prefix – Add a prefix to the rupture_idxs, if given

Returns:

the list of generated filenames

stats#

Utilities to compute mean and quantile curves

openquake.hazardlib.stats.apply_stat(f, arraylist, *extra, **kw)[source]#
Parameters:
  • f – a callable arraylist -> array (of the same shape and dtype)

  • arraylist – a list of arrays of the same shape and dtype

  • extra – additional positional arguments

  • kw – keyword arguments

Returns:

an array of the same shape and dtype

Broadcast statistical functions to composite arrays. Here is an example:

>>> dt = numpy.dtype([('a', (float, 2)), ('b', float)])
>>> a1 = numpy.array([([1, 2], 3)], dt)
>>> a2 = numpy.array([([4, 5], 6)], dt)
>>> apply_stat(mean_curve, [a1, a2])
array([([2.5, 3.5], 4.5)], dtype=[('a', '<f8', (2,)), ('b', '<f8')])
openquake.hazardlib.stats.average_df(dframes, weights=None)[source]#

Compute weighted average of DataFrames with the same index and columns.

>>> df1 = pandas.DataFrame(dict(value=[1, 1, 1]), [1, 2, 3])
>>> df2 = pandas.DataFrame(dict(value=[2, 2, 2]), [1, 2, 3])
>>> average_df([df1, df2], [.4, .6])
   value
1    1.6
2    1.6
3    1.6
openquake.hazardlib.stats.avg_std(array, weights=None)[source]#
Parameters:
  • array – an array of shape E, …

  • weights – an array of length E (or None for equal weights)

Returns:

an array of shape (2, …) with average and standard deviation

>>> avg_std(numpy.array([[2, 4, 6], [3, 5, 7]]))
array([[2.5, 4.5, 6.5],
       [0.5, 0.5, 0.5]])
openquake.hazardlib.stats.calc_avg_std(momenta)[source]#
Parameters:
  • momenta – an array of shape (2, …) obtained via calc_momenta

  • totweight – total weight to divide for

Returns:

an array of shape (2, …) with average and standard deviation

>>> arr = numpy.array([[2, 4, 6], [3, 5, 7]])
>>> weights = numpy.ones(2)
>>> calc_avg_std(calc_momenta(arr, weights))
array([[2.5, 4.5, 6.5],
       [0.5, 0.5, 0.5]])
openquake.hazardlib.stats.calc_momenta(array, weights)[source]#
Parameters:
  • array – an array of shape (E, …)

  • weights – an array of length E

Returns:

an array of shape (3, …) with the first 3 statistical moments

openquake.hazardlib.stats.calc_stats(df, kfields, stats, weights)[source]#
Parameters:
  • df – a pandas DataFrame with a column rlz_id

  • kfields – fields used in the group by

  • stats – a dictionary stat_name->stat_func

  • weights – an array of weights for each realization

Returns:

a DataFrame with the statistics

openquake.hazardlib.stats.combine_probs(values_by_grp, cmakers, rlz)[source]#
Parameters:
  • values_by_grp – C arrays of shape (D1, D2…, G)

  • cmakers – C ContextMakers with G gsims each

  • rlz – a realization index

Returns:

array of shape (D1, D2, …)

openquake.hazardlib.stats.compute_pmap_stats(pmaps, stats, weights, imtls)[source]#
Parameters:
  • pmaps – a list of R probability maps

  • stats – a sequence of S statistic functions

  • weights – a list of ImtWeights

  • imtls – a DictArray of intensity measure types

Returns:

a probability map with S internal values

openquake.hazardlib.stats.compute_stats(array, stats, weights)[source]#
Parameters:
  • array – an array of R elements (which can be arrays)

  • stats – a sequence of S statistic functions

  • weights – a list of R weights

Returns:

an array of S elements (which can be arrays)

openquake.hazardlib.stats.compute_stats2(arrayNR, stats, weights)[source]#
Parameters:
  • arrayNR – an array of (N, R) elements

  • stats – a sequence of S statistic functions

  • weights – a list of R weights

Returns:

an array of (N, S) elements

openquake.hazardlib.stats.geom_avg_std(array, weights=None)[source]#
Returns:

geometric mean and geometric stddev (see https://en.wikipedia.org/wiki/Log-normal_distribution)

openquake.hazardlib.stats.get_tmax(phi_b)[source]#
Parameters:

phi_b – ndtr(truncation_level)

Returns:

the value of x beyond which truncnorm_sf(phi_b, x) is 0

openquake.hazardlib.stats.max_curve(values, weights=None)[source]#

Compute the maximum curve by taking the upper limits of the values; the weights are ignored and present only for API compatibility. The values can be arrays and then the maximum is taken pointwise:

>>> max_curve([numpy.array([.3, .2]), numpy.array([.1, .4])])
array([0.3, 0.4])
openquake.hazardlib.stats.mean_curve(values, weights=None)[source]#

Compute the mean by using numpy.average on the first axis.

openquake.hazardlib.stats.norm_cdf(x, a, s)[source]#

Gaussian cumulative distribution function; if s=0, returns an Heaviside function instead. NB: for x=a, 0.5 is returned for all s.

>>> round(float(norm_cdf(1.2, 1, .1)), 10)
0.9772498681
>>> float(norm_cdf(1.2, 1, 0))
1.0
>>> round(float(norm_cdf(.8, 1, .1)), 10)
0.0227501319
>>> float(norm_cdf(.8, 1, 0))
0.0
>>> float(norm_cdf(1, 1, .1))
0.5
>>> float(norm_cdf(1, 1, 0))
0.5
openquake.hazardlib.stats.quantile_curve(quantile, curves, weights=None)[source]#

Compute the weighted quantile aggregate of an array or list of arrays

Parameters:
  • quantile – Quantile value to calculate. Should be in the range [0.0, 1.0].

  • curves – R arrays

  • weights – R weights with sum 1, or None

Returns:

A numpy array representing the quantile of the underlying arrays

>>> arr = numpy.array([.15, .25, .3, .4, .5, .6, .75, .8, .9])
>>> quantile_curve(.8, arr)
array(0.76)
>>> quantile_curve(.85, numpy.array([.15, .15, .15]))  # constant array
array(0.15)
openquake.hazardlib.stats.set_rlzs_stats(dstore, name, **attrs)[source]#
Parameters:
  • dstore – a DataStore object

  • name – dataset name of kind <prefix>-rlzs

openquake.hazardlib.stats.std_curve(values, weights=None)[source]#
openquake.hazardlib.stats.truncnorm_sf(phi_b, values)[source]#

Fast survival function for truncated normal distribution. Assumes zero mean, standard deviation equal to one and symmetric truncation. It is faster than using scipy.stats.truncnorm.sf.

Parameters:
  • phi_b – ndtr(truncation_level); assume phi_b > .5

  • values – Numpy array of values as input to a survival function for the given distribution.

Returns:

Numpy array of survival function results in a range between 0 and 1. For phi_b close to .5 returns a step function 1 1 1 1 .5 0 0 0 0 0.

openquake.hazardlib.stats.weighted_quantiles(qs, values, weights)[source]#

Compute weighted quantiles

tom#

Module openquake.hazardlib.tom contains implementations of probability density functions for earthquake temporal occurrence modeling.

class openquake.hazardlib.tom.BaseTOM(time_span)[source]#

Bases: object

Base class for temporal occurrence model.

Parameters:

time_span – The time interval of interest, in years.

Raises:

ValueError – If time_span is not positive.

get_probability_n_occurrences()[source]#

Calculate the probability of occurrence of a number of events in the constructor’s time_span.

get_probability_no_exceedance()[source]#

Compute and return, for a number of ground motion levels and sites, the probability that a rupture with annual occurrence rate given by occurrence_rate and able to cause ground motion values higher than a given level at a site with probability poes, does not cause any exceedance in the time window specified by the time_span parameter given in the constructor.

get_probability_one_or_more_occurrences()[source]#

Calculate and return the probability of event to happen one or more times within the time range defined by constructor’s time_span parameter value.

sample_number_of_occurrences(rng)[source]#

Draw a random sample from the distribution and return a number of events to occur.

class openquake.hazardlib.tom.ClusterPoissonTOM(time_span, occurrence_rate)[source]#

Bases: PoissonTOM

Poissonian temporal occurrence model with an occurrence rate

class openquake.hazardlib.tom.FatedTOM(time_span)[source]#

Bases: BaseTOM

get_probability_n_occurrences(occurrence_rate, num)[source]#

Calculate the probability of occurrence of a number of events in the constructor’s time_span.

get_probability_no_exceedance(occurrence_rate, poes)[source]#

Compute and return, for a number of ground motion levels and sites, the probability that a rupture with annual occurrence rate given by occurrence_rate and able to cause ground motion values higher than a given level at a site with probability poes, does not cause any exceedance in the time window specified by the time_span parameter given in the constructor.

get_probability_one_or_more_occurrences(occurrence_rate)[source]#

Calculate and return the probability of event to happen one or more times within the time range defined by constructor’s time_span parameter value.

sample_number_of_occurrences(rng)[source]#

Draw a random sample from the distribution and return a number of events to occur.

class openquake.hazardlib.tom.NegativeBinomialTOM(time_span, mu, alpha)[source]#

Bases: BaseTOM

Negative Binomial temporal occurrence model.

get_pmf(mean_rate)[source]#
Parameters:

mean_rate – The average number of events per year (scalar or array)

Returns:

1D or 2D array containing the probability mass distribution, up to tolerance level.

get_probability_n_occurrences(num)[source]#

Calculate the probability of occurrence of num events in the constructor’s time_span.

Parameters:

num – Number of events

Returns:

Probability of occurrence

get_probability_no_exceedance(mean_rate, poes)[source]#
Parameters:
  • mean_rate – The average number of events per year.

  • poes – 2D numpy array containing conditional probabilities that the rupture occurrence causes a ground shaking value exceeding a ground motion level at a site. First dimension represent sites, second dimension intensity measure levels. poes can be obtained calling the func.

Returns:

2D numpy array containing probabilities of no exceedance. First dimension represents sites, second dimension intensity measure levels.

get_probability_one_or_more_occurrences(mean_rate=None)[source]#
Parameters:

mean_rate – The mean rate, or mean number of events per year

Returns:

Float value between 0 and 1 inclusive.

sample_number_of_occurrences(rng, mean_rate=None)[source]#

Draw a random sample from the distribution and return a number of events to occur.

The method uses the numpy random generator, which needs a seed in order to get reproducible results. If the seed is None, it should be set outside of this method.

Parameters:
  • rng – Random number generator

  • mean_rate – The mean rate, or mean number of events per year

Returns:

Sampled integer number of events to occur within model’s time span.

x = array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])#
class openquake.hazardlib.tom.PoissonTOM(time_span)[source]#

Bases: BaseTOM

Poissonian temporal occurrence model.

get_probability_n_occurrences(occurrence_rate, num)[source]#

Calculate the probability of occurrence of num events in the constructor’s time_span.

Parameters:
  • occurrence_rate – Annual rate of occurrence

  • num – Number of events

Returns:

Probability of occurrence

get_probability_no_exceedance(occurrence_rate, poes)[source]#
Parameters:
  • occurrence_rate – The average number of events per year.

  • poes – 2D numpy array containing conditional probabilities that the rupture occurrence causes a ground shaking value exceeding a ground motion level at a site. First dimension represent sites, second dimension intensity measure levels. poes can be obtained calling the func.

Returns:

2D numpy array containing probabilities of no exceedance. First dimension represents sites, second dimension intensity measure levels.

The probability is computed as exp(-occurrence_rate * time_span * poes)

get_probability_one_or_more_occurrences(occurrence_rate)[source]#

Calculates probability as 1 - e ** (-occurrence_rate*time_span).

Parameters:

occurrence_rate – The average number of events per year.

Returns:

Float value between 0 and 1 inclusive.

sample_number_of_occurrences(rng, occurrence_rate)[source]#

Draw a random sample from the distribution and return a number of events to occur.

The method uses the numpy random generator, which needs a seed in order to get reproducible results. If the seed is None, it should be set outside of this method.

Parameters:
  • rng – Random number generator

  • occurrence_rate – The average number of events per year.

Returns:

Sampled integer number of events to occur within model’s time span.

openquake.hazardlib.tom.get_pnes(rate, probs, poes, time_span)[source]#
Parameters:
  • rate – occurrence rate in case of a poissonian rupture

  • probs – probabilities of occurrence in the nonpoissonian case

  • poes – array of PoEs of shape 1D or 3D

  • time_span – time span in the poissonian case (0. for FatedTOM)

Fast way to return probabilities of no exceedence given an array of PoEs and some parameter.

valid#

Validation library for the engine, the desktop tools, and anything else

class openquake.hazardlib.valid.Choice(*choices)[source]#

Bases: object

Check if the choice is valid (case sensitive).

class openquake.hazardlib.valid.ChoiceCI(*choices)[source]#

Bases: object

Check if the choice is valid (case insensitive version).

class openquake.hazardlib.valid.Choices(*choices)[source]#

Bases: Choice

Convert the choices, passed as a comma separated string, into a tuple of validated strings. For instance

>>> Choices('xml', 'csv')('xml,csv')
('xml', 'csv')
class openquake.hazardlib.valid.FloatRange(minrange, maxrange, name='', accept=None)[source]#

Bases: object

class openquake.hazardlib.valid.FromFile[source]#

Bases: object

Fake GSIM to be used when the GMFs are imported from an external file and not computed with a GSIM.

DEFINED_FOR_INTENSITY_MEASURE_TYPES = {}#
DEFINED_FOR_REFERENCE_VELOCITY = None#
DEFINED_FOR_STANDARD_DEVIATION_TYPES = {}#
REQUIRES_DISTANCES = {}#
REQUIRES_RUPTURE_PARAMETERS = {}#
REQUIRES_SITES_PARAMETERS = {}#
compute(ctx, imts, mean, sig, tau, phi)[source]#
kwargs = {}#
requires()[source]#
class openquake.hazardlib.valid.MetaParamSet(name, bases, dic)[source]#

Bases: type

Set the .name attribute of every Param instance defined inside any subclass of ParamSet.

class openquake.hazardlib.valid.NoneOr(cast)[source]#

Bases: object

Accept the empty string (casted to None) or something else validated by the underlying cast validator.

class openquake.hazardlib.valid.Param(validator, default=<object object>, name=None)[source]#

Bases: object

A descriptor for validated parameters with a default, to be used as attributes in ParamSet objects.

Parameters:
  • validator – the validator

  • default – the default value

NODEFAULT = <object object>#
class openquake.hazardlib.valid.ParamSet(**names_vals)[source]#

Bases: object

A set of valid interrelated parameters. Here is an example of usage:

>>> class MyParams(ParamSet):
...     a = Param(positiveint)
...     b = Param(positivefloat)
...
...     def is_valid_not_too_big(self):
...         "The sum of a and b must be under 10: a={a} and b={b}"
...         return self.a + self.b < 10
>>> mp = MyParams(a='1', b='7.2')
>>> mp
<MyParams a=1, b=7.2>
>>> MyParams(a='1', b='9.2').validate()
Traceback (most recent call last):
...
ValueError: The sum of a and b must be under 10: a=1 and b=9.2

The constrains are applied in lexicographic order. The attribute corresponding to a Param descriptor can be set as usual:

>>> mp.a = '2'
>>> mp.a
'2'

A list with the literal strings can be extracted as follows:

>>> mp.to_params()
[('a', "'2'"), ('b', '7.2')]

It is possible to build a new object from a dictionary of parameters which are assumed to be already validated:

>>> MyParams.from_(dict(a="'2'", b='7.2'))
<MyParams a='2', b=7.2>
KNOWN_INPUTS = {}#
classmethod check(dic)[source]#

Check if a dictionary name->string can be converted into a dictionary name->value. If the name does not correspond to a known parameter, print a warning.

Returns:

a dictionary of converted parameters

classmethod from_(dic)[source]#

Build a new ParamSet from a dictionary of string-valued parameters which are assumed to be already valid.

json()[source]#
Returns:

the parameters as a JSON string

params = {}#
to_params()[source]#

Convert the instance dictionary into a sorted list of pairs (name, valrepr) where valrepr is the string representation of the underlying value.

validate()[source]#

Apply the is_valid methods to self and possibly raise a ValueError.

class openquake.hazardlib.valid.Regex(regex)[source]#

Bases: object

Compare the value with the given regex

class openquake.hazardlib.valid.RjbEquivalent(filename)[source]#

Bases: object

A class to compute the equivalent Rjb distance. Usage:

>> reqv = RjbEquivalent(‘lookup.hdf5’) >> reqv.get(repi_distances, mag)

get(repi, mag)[source]#
Parameters:
  • repi – an array of epicentral distances in the range self.repi

  • mag – a magnitude in the range self.mags

Returns:

an array of equivalent distances

class openquake.hazardlib.valid.SimpleId(length, regex='^[\\w_\\-:]+$')[source]#

Bases: object

Check if the given value is a valid ID.

Parameters:
  • length – maximum length of the ID

  • regex – accepted characters

openquake.hazardlib.valid.ab_values(value)[source]#

a and b values of the GR magniture-scaling relation. a is a positive float, b is just a float.

openquake.hazardlib.valid.base64names(value)[source]#
Parameters:

value – input string

Returns:

list of strings of <=8 characters in base64

>>> base64names('XYzu- f_')
['XYzu-', 'f_']
>>> base64names('XYzu+')
Traceback (most recent call last):
...
ValueError: List of names containing an invalid name: 'XYzu+'
openquake.hazardlib.valid.basename(src, splitchars='.:')[source]#
Returns:

the base name of a split source

>>> basename('SC:10;0')
'SC;0'
openquake.hazardlib.valid.boolean(value)[source]#
Parameters:

value – input string such as ‘0’, ‘1’, ‘true’, ‘false’

Returns:

boolean

>>> boolean('')
False
>>> boolean('True')
True
>>> boolean('false')
False
>>> boolean('t')
Traceback (most recent call last):
    ...
ValueError: Not a boolean: t
openquake.hazardlib.valid.calculation(value)[source]#

Convert a string into an integer calculation ID or return it as it is if it ends with .ini or .hdf5

openquake.hazardlib.valid.check_levels(imls, imt, min_iml=1e-10)[source]#

Raise a ValueError if the given levels are invalid.

Parameters:
  • imls – a list of intensity measure and levels

  • imt – the intensity measure type

  • min_iml – minimum intensity measure level (default 1E-10)

>>> check_levels([0.1, 0.2], 'PGA')  # ok
>>> check_levels([], 'PGA')
Traceback (most recent call last):
   ...
ValueError: No imls for PGA: []
>>> check_levels([0.2, 0.1], 'PGA')
Traceback (most recent call last):
   ...
ValueError: The imls for PGA are not sorted: [0.2, 0.1]
>>> check_levels([0.2, 0.2], 'PGA')
Traceback (most recent call last):
   ...
ValueError: Found duplicated levels for PGA: [0.2, 0.2]
openquake.hazardlib.valid.check_weights(nodes_with_a_weight)[source]#

Ensure that the sum of the values is 1

Parameters:

nodes_with_a_weight – a list of Node objects with a weight attribute

openquake.hazardlib.valid.compose(*validators)[source]#

Implement composition of validators. For instance

>>> utf8_not_empty = compose(utf8, not_empty)
openquake.hazardlib.valid.coordinates(value)[source]#

Convert a non-empty string into a list of lon-lat coordinates.

>>> coordinates('')
Traceback (most recent call last):
...
ValueError: Empty list of coordinates: ''
>>> coordinates('1.1 1.2')
[(1.1, 1.2, 0.0)]
>>> coordinates('1.1 1.2, 2.2 2.3')
[(1.1, 1.2, 0.0), (2.2, 2.3, 0.0)]
>>> coordinates('1.1 1.2 -0.4, 2.2 2.3 -0.5')
[(1.1, 1.2, -0.4), (2.2, 2.3, -0.5)]
>>> coordinates('0 0 0, 0 0 -1')
Traceback (most recent call last):
...
ValueError: Found overlapping site #2,  0 0 -1
openquake.hazardlib.valid.corename(src, splitchars='!:;.')[source]#
Parameters:
  • src – source object or source name

  • splitchars – the characters starting a suffix to remove

Returns:

the core name of a source

>>> corename('SC_10:124!b_1')
'SC_10'
>>> corename('SC_10:124!b_1', '!')  # the ID as written in the logic tree
'SC_10:124'
openquake.hazardlib.valid.decreasing_probabilities(value)[source]#
Parameters:

value – input string, comma separated or space separated

Returns:

a list of decreasing probabilities

>>> decreasing_probabilities('1')
Traceback (most recent call last):
...
ValueError: Not enough probabilities, found '1'
>>> decreasing_probabilities('0.2 0.1')
[0.2, 0.1]
>>> decreasing_probabilities('0.1 0.2')
Traceback (most recent call last):
...
ValueError: The probabilities 0.1 0.2 are not in decreasing order
openquake.hazardlib.valid.depth(value)[source]#
Parameters:

value – input string

Returns:

a finite float (NaN would give NaN hypocenters)

>>> depth('nan')
Traceback (most recent call last):
...
ValueError: depth nan is not finite
openquake.hazardlib.valid.dictionary(value)[source]#
Parameters:

value – input string corresponding to a literal Python object

Returns:

the Python object

>>> dictionary('')
{}
>>> dictionary('{}')
{}
>>> dictionary('{"a": 1}')
{'a': 1}
>>> dictionary('"vs30_clustering: true"')  # an error really done by a user
Traceback (most recent call last):
   ...
ValueError: '"vs30_clustering: true"' is not a valid Python dictionary
>>> numpy.array(dictionary('{"ls": logscale(0.01, 2, 5)}')['ls'])
array([0.01      , 0.03760603, 0.14142136, 0.53182959, 2.        ])
openquake.hazardlib.valid.disagg_outputs(value)[source]#

Validate disaggregation outputs. For instance

>>> disagg_outputs('TRT Mag_Dist')
['TRT', 'Mag_Dist']
>>> disagg_outputs('TRT, Mag_Dist')
['TRT', 'Mag_Dist']
openquake.hazardlib.valid.float_(value)[source]#
Parameters:

value – input string

Returns:

a floating point number

openquake.hazardlib.valid.floats(value)[source]#
Parameters:

value – string of whitespace separated floats

Returns:

a list of floats

openquake.hazardlib.valid.fragmentno(src)[source]#

Postfix after @:.; as an integer

openquake.hazardlib.valid.gsim(value, basedir='')[source]#

Convert a string into a GSIM instance

>>> gsim('BooreAtkinson2011')
[BooreAtkinson2011]
openquake.hazardlib.valid.hypo_list(nodes)[source]#
Parameters:

nodes – a hypoList node with N hypocenter nodes

Returns:

a numpy array of shape (N, 3) with strike, dip and weight

openquake.hazardlib.valid.indexes(value)[source]#
>>> indexes("1,2,A")
('1', '2', 'A')
openquake.hazardlib.valid.integers(value)[source]#
Parameters:

value – input string

Returns:

non-empty list of integers

>>> integers('1, 2')
[1, 2]
>>> integers(' ')
Traceback (most recent call last):
   ...
ValueError: Not a list of integers: ' '
openquake.hazardlib.valid.intensity_measure_type(value)[source]#

Make sure value is a valid intensity measure type and return it in a normalized form

>>> intensity_measure_type('SA(0.10)')  # NB: strips the trailing 0
'SA(0.1)'
>>> intensity_measure_type('SA')  # this is invalid
Traceback (most recent call last):
  ...
ValueError: Invalid IMT: 'SA'
openquake.hazardlib.valid.intensity_measure_types(value)[source]#
Parameters:

value – input string

Returns:

non-empty list of ordered Intensity Measure Type objects

>>> intensity_measure_types('')
[]
>>> intensity_measure_types('PGA')
['PGA']
>>> intensity_measure_types('PGA, SA(1.00)')
['PGA', 'SA(1.0)']
>>> intensity_measure_types('SA(0.1), SA(0.10)')
Traceback (most recent call last):
  ...
ValueError: Duplicated IMTs in SA(0.1), SA(0.10)
>>> intensity_measure_types('PGV, SA(1), PGA')
['PGV', 'PGA', 'SA(1.0)']
openquake.hazardlib.valid.intensity_measure_types_and_levels(value)[source]#
Parameters:

value – input string

Returns:

Intensity Measure Type and Levels dictionary

>>> intensity_measure_types_and_levels('{"SA(0.10)": [0.1, 0.2]}')
{'SA(0.1)': [0.1, 0.2]}
openquake.hazardlib.valid.latitude(value)[source]#
Parameters:

value – input string

Returns:

latitude float, rounded to 5 digits, i.e. 1 meter maximum

>>> latitude('-0.123456')
-0.12346
openquake.hazardlib.valid.latitudes(value)[source]#
Parameters:

value – a comma separated string of latitudes

Returns:

a list of latitudes

openquake.hazardlib.valid.linscale(x_min, x_max, n)[source]#
Parameters:
  • x_min – minumum value

  • x_max – maximum value

  • n – number of steps

Returns:

an array of n values from x_min to x_max

openquake.hazardlib.valid.list_of_dict(value)[source]#
Parameters:

value – input string corresponding to a list of literal Python dictionaries

Returns:

the list

openquake.hazardlib.valid.logic_tree_path(value)[source]#
>>> logic_tree_path('SM2_a3b1')
['SM2', 'a3b1']
openquake.hazardlib.valid.logscale(x_min, x_max, n)[source]#
Parameters:
  • x_min – minumum value

  • x_max – maximum value

  • n – number of steps

Returns:

an array of n values from x_min to x_max

openquake.hazardlib.valid.lon_lat(value)[source]#
Parameters:

value – a pair of coordinates

Returns:

a tuple (longitude, latitude)

>>> lon_lat('12 14')
(12.0, 14.0)
>>> lon_lat('12,14')
(12.0, 14.0)
openquake.hazardlib.valid.longitude(value)[source]#
Parameters:

value – input string

Returns:

longitude float, rounded to 5 digits, i.e. 1 meter maximum

>>> longitude('0.123456')
0.12346
openquake.hazardlib.valid.longitudes(value)[source]#
Parameters:

value – a comma separated string of longitudes

Returns:

a list of longitudes

openquake.hazardlib.valid.loss_ratios(value)[source]#
Parameters:

value – input string

Returns:

dictionary loss_type -> loss ratios

>>> loss_ratios('{"structural": [0.1, 0.2]}')
{'structural': [0.1, 0.2]}
openquake.hazardlib.valid.mag_scale_rel(value)[source]#
Parameters:

value – a Magnitude-Scale relationship in hazardlib

Returns:

the corresponding hazardlib object

Parametric MSR classes are supported with TOML syntax; for instance

>>> mag_scale_rel("CScalingMSR.C=4.7")
<CScalingMSR>
openquake.hazardlib.valid.modified_gsim(gmpe, **kwargs)[source]#

Builds a ModifiableGMPE from a gmpe. Used for instance in the GEESE project as follows:

mgs = modified_gsim(gsim, add_between_within_stds={‘with_betw_ratio’:1.5})

openquake.hazardlib.valid.namelist(value)[source]#
Parameters:

value – input string

Returns:

list of identifiers separated by whitespace or commas

>>> namelist('a,b')
['a', 'b']
>>> namelist('a1  b_2       _c')
['a1', 'b_2', '_c']
>>> namelist('a1 b_2 1c')
['a1', 'b_2', '1c']
openquake.hazardlib.valid.namelists(value)[source]#
Parameters:

value – input string

Returns:

list of lists of identifiers

>>> namelists('a,b')
[['a', 'b']]
>>> namelists('a1, b_2; _c')
[['a1', 'b_2'], ['_c']]
>>> namelists('a1; b_2; 1c')
[['a1'], ['b_2'], ['1c']]
openquake.hazardlib.valid.nonzero(value)[source]#
Parameters:

value – input string

Returns:

the value unchanged

>>> nonzero('1')
'1'
>>> nonzero('0')
Traceback (most recent call last):
  ...
ValueError: '0' is zero
openquake.hazardlib.valid.not_empty(value)[source]#

Check that the string is not all blanks

openquake.hazardlib.valid.occurrence_model(value)[source]#

Converts a TOML string into a TOM instance

>>> print(occurrence_model('[PoissonTOM]\ntime_span=50.0'))
[PoissonTOM]
time_span = 50.0
openquake.hazardlib.valid.pmf(value)[source]#

Comvert a string into a Probability Mass Function.

Parameters:

value – a sequence of probabilities summing up to 1 (no commas)

Returns:

a list of pairs [(probability, index), …] with index starting from 0

>>> pmf("0.157 0.843")
[(0.157, 0), (0.843, 1)]
openquake.hazardlib.valid.point(value)[source]#
Parameters:

value – a tuple of coordinates as a string (2D or 3D)

Returns:

a tuple of coordinates as a string (2D or 3D)

openquake.hazardlib.valid.point3d(value, lon, lat, depth)[source]#

This is used to convert nodes of the form <hypocenter lon=”LON” lat=”LAT” depth=”DEPTH”/>

Parameters:
  • value – None

  • lon – longitude string

  • lat – latitude string

Returns:

a validated triple (lon, lat, depth)

openquake.hazardlib.valid.posList(value)[source]#
Parameters:

value – a string with the form lon1 lat1 [depth1] … lonN latN [depthN] without commas, where the depts are optional.

Returns:

a list of floats without other validations

openquake.hazardlib.valid.positivefloat(value)[source]#
Parameters:

value – input string

Returns:

positive float

openquake.hazardlib.valid.positivefloat_or_auto(value)[source]#
Parameters:

value – input string

Returns:

positive float or the string “auto”

>>> positivefloat_or_auto('auto')
'auto'
>>> positivefloat_or_auto('50')
50.0
openquake.hazardlib.valid.positivefloatorsentinel(value)[source]#
Parameters:

value – input string

Returns:

positive float or -999 (sentinel)

openquake.hazardlib.valid.positivefloats(value)[source]#
Parameters:

value – string of whitespace separated floats

Returns:

a list of positive floats

openquake.hazardlib.valid.positivefloatsorsentinels(value)[source]#
Parameters:

value – string of whitespace separated floats

Returns:

a list of positive floats or -999 (sentinel) values

openquake.hazardlib.valid.positiveint(value)[source]#
Parameters:

value – input string

Returns:

positive integer

openquake.hazardlib.valid.positiveints(value)[source]#
>>> positiveints('1, -1')
Traceback (most recent call last):
   ...
ValueError: -1 is negative in '1, -1'
openquake.hazardlib.valid.probabilities(value, rows=0, cols=0)[source]#
Parameters:
  • value – input string, comma separated or space separated

  • rows – the number of rows if the floats are in a matrix (0 otherwise)

  • cols – the number of columns if the floats are in a matrix (or 0

Returns:

a list of probabilities

>>> probabilities('')
[]
>>> probabilities('1')
[1.0]
>>> probabilities('0.1 0.2')
[0.1, 0.2]
>>> probabilities('[0.1, 0.2]')  # commas and brackets are ignored
[0.1, 0.2]
openquake.hazardlib.valid.range01(value)[source]#
Parameters:

value – a string convertible to a float in the range 0..1

openquake.hazardlib.valid.risk_id(value)[source]#

A valid risk ID cannot contain the characters #’”

openquake.hazardlib.valid.secondary_perils(value: str)[source]#
>>> secondary_perils("Jibson2007ALandslides, AllstadtEtAl2022Liquefaction")
['Jibson2007ALandslides', 'AllstadtEtAl2022Liquefaction']
openquake.hazardlib.valid.simple_slice(value)[source]#
>>> simple_slice('2:5')
(2, 5)
>>> simple_slice('0:None')
(0, None)
openquake.hazardlib.valid.site_param(dic)[source]#

Convert a dictionary site_model_param -> string into a dictionary of valid casted site parameters.

openquake.hazardlib.valid.slip_list(nodes)[source]#
Parameters:

nodes – a slipList node with N slip nodes

Returns:

a numpy array of shape (N, 2) with slip angle and weight

openquake.hazardlib.valid.sourcecodes(value)[source]#
Parameters:

value – input string

Returns:

a string of source codes, e.g. ‘pPAM’

>>> sourcecodes('pPAM')
'pPAM'
>>> sourcecodes('PAZ')
Traceback (most recent call last):
...
ValueError: Invalid source code 'Z' in 'PAZ', valid codes are ACFKMNPSXp
openquake.hazardlib.valid.tile_spec(value)[source]#

Specify a tile with a string of format “no:nt” where no is an integer in the range 1..nt and nt is the total number of tiles.

>>> tile_spec('[1,2]')
[1, 2]
>>> tile_spec('[2,2]')
[2, 2]
openquake.hazardlib.valid.to_toml(uncertainty)[source]#

Converts an uncertainty node into a TOML string

openquake.hazardlib.valid.trt_pmf(matrices)[source]#

From T matrices of shape (Ma, D, Lo, La, E, …) into one matrix of shape (T, …)

openquake.hazardlib.valid.uint8dict(value)[source]#
Parameters:

value – input string corresponding to a literal Python dictionary

Returns:

dictionary string -> uint8 number

>>> uint8dict('')
{}
>>> uint8dict('{}')
{}
>>> uint8dict('{"a": 1}')
{'a': 1}
>>> uint8dict('{"a": 0}')
Traceback (most recent call last):
   ...
AssertionError: a must be in the range 1-255, got 0
openquake.hazardlib.valid.uncertainty_model(value)[source]#

Format whitespace in XML nodes of kind uncertaintyModel

openquake.hazardlib.valid.utf8(value)[source]#

Check that the string is UTF-8. Returns an encode bytestring.

>>> utf8(b'\xe0')  
Traceback (most recent call last):
...
ValueError: Not UTF-8: ...
openquake.hazardlib.valid.utf8_not_empty(value)[source]#

Check that the string is UTF-8 and not empty

openquake.hazardlib.valid.version(value: str)[source]#
>>> version('3.22')
(3, 22, 0)
>>> version('3.22.0-gitXXX')
(3, 22, 0)
openquake.hazardlib.valid.weights(value)[source]#

Space-separated list of weights:

>>> weights('0.1 0.2 0.7')
[0.1, 0.2, 0.7]
>>> weights('0.1 0.2 0.8')
Traceback (most recent call last):
  ...
ValueError: The weights do not sum up to 1: [0.1, 0.2, 0.8]
openquake.hazardlib.valid.wkt_polygon(value)[source]#

Convert a string with a comma separated list of coordinates into a WKT polygon, by closing the ring.