openquake.hazardlib package

Subpackages

source_reader module

class openquake.hazardlib.source_reader.CompositeSourceModel(full_lt, src_groups)[source]

Bases: object

Parameters:
  • full_lt – a FullLogicTree instance

  • src_groups – a list of SourceGroups

  • event_based – a flag True for event based calculations, flag otherwise

count_ruptures()[source]

Call src.count_ruptures() on each source. Slow.

fix_src_offset()[source]

Set the src.offset field for each source

get_basenames()[source]
Returns:

a sorted list of source names stripped of the suffixes

get_floating_spinning_factors()[source]
Returns:

(floating rupture factor, spinning rupture factor)

get_mags_by_trt(maximum_distance)[source]
Parameters:

maximum_distance – dictionary trt -> magdist interpolator

Returns:

a dictionary trt -> magnitudes in the sources as strings

get_max_weight(oq)[source]
Parameters:

oq – an OqParam instance

Returns:

total weight and max weight of the sources

get_sources(atomic=None)[source]

There are 3 options:

atomic == None => return all the sources (default) atomic == True => return all the sources in atomic groups atomic == True => return all the sources not in atomic groups

get_trt_smrs()[source]
Returns:

an array of trt_smrs (to be stored as an hdf5.vuint32 array)

init(full_lt)[source]
update_source_info(source_data)[source]

Update (eff_ruptures, num_sites, calc_time) inside the source_info

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

Build and attach a checksum to each source

openquake.hazardlib.source_reader.build_rup_mutex(src_groups)[source]
Returns:

a composite array with fields (grp_id, src_id, rup_id, weight)

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

Creates source_info, source_wkt, trt_smrs, toms

openquake.hazardlib.source_reader.find_false_duplicates(smdict)[source]

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

openquake.hazardlib.source_reader.fix_geometry_sections(smdict, dstore)[source]

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

openquake.hazardlib.source_reader.fragmentno(src)[source]

Postfix after :.; as an integer

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

Build source models from the logic tree and to store them inside the source_full_lt dataset.

openquake.hazardlib.source_reader.gzpik(obj)[source]

gzip and pickle a python object

openquake.hazardlib.source_reader.mutex_by_grp(src_groups)[source]
Returns:

a composite array with boolean fields src_mutex, rup_mutex

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

  • converter – SourceConverter

  • monitor – a Monitor instance

Returns:

a SourceModel instance

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

sources_with_same_id – a list of sources with the same source_id

Returns:

a list of truly unique sources, ordered by trt_smr

openquake.hazardlib.source_reader.trt_smrs(src)[source]

logictree module

Logic tree parser, verifier and processor. See specs at https://blueprints.launchpad.net/openquake-old/+spec/openquake-logic-tree-module

A logic tree object must be iterable and yielding realizations, i.e. objects with attributes value, weight, lt_path and ordinal.

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

Bases: object

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(trt_rlzs)[source]
Returns:

a list of Gt weights

get_gids(all_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_smr_by_ltp()[source]
Returns:

a dictionary sm_lt_path -> effective realization index

get_trt_rlzs(all_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'
reduce_groups(src_groups)[source]

Filter the sources and set the tuple .trt_smr

property rlzs
Returns:

an array of realizations

property sampling_method
Returns:

the source_model_lt sampling_method parameter

property seed
Returns:

the source_model_lt seed

set_trt_smr(srcs, source_id=None, smr=None)[source]
Parameters:
  • srcs – source objects

  • source_id – base source ID

  • srm – source model realization index

Returns:

list of sources with the same base source ID

trt_by(trt_smr)[source]
Returns:

the TRT associated to trt_smr

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)[source]

Bases: object

Composite realization build on top of a source model realization and a GSIM realization.

property gsim_lt_path
class openquake.hazardlib.logictree.SourceLogicTree(source_id, branchsets, bsetdict)[source]

Bases: object

Source specific logic tree (full enumeration)

get_num_paths()[source]
class openquake.hazardlib.logictree.SourceModelLogicTree(filename, seed=0, num_samples=0, sampling_method='early_weights', test_mode=False, branchID='', source_id='')[source]

Bases: object

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

ABSOLUTE_UNCERTAINTIES = ('abGRAbsolute', 'bGRAbsolute', 'maxMagGRAbsolute', 'simpleFaultGeometryAbsolute', 'truncatedGRFromSlipAbsolute', 'complexFaultGeometryAbsolute', 'setMSRAbsolute')
FILTERS = ('applyToTectonicRegionType', 'applyToSources', 'applyToBranches')
apply_branchset(apply_to_branches, lineno, branchset)[source]

See superclass’ method for description and signature specification.

Parses branchset node’s attribute @applyToBranches to apply following branchests to preceding branches selectively. Branching level can have more than one branchset exactly for this: different branchsets can apply to different open ends.

Checks that branchset tries to be applied only to branches on previous branching level which do not have a child branchset yet.

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 -> SourceLogicTree instance

classmethod fake()[source]
Returns:

a fake SourceModelLogicTree with a single branch

get_duplicated_sources()[source]
Returns:

{src_id: affected branches}

get_num_paths()[source]
Returns:

the number of paths in the logic tree

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.

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

a new logic tree reduced to a single source

set_num_paths()[source]

Count the total number of paths in a smart way

to_node()[source]
Returns:

a logicTree Node convertible into NRML format

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.capitalize(words)[source]

Capitalize words separated by spaces.

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.get_eff_rlzs(sm_rlzs, gsim_rlzs)[source]

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

openquake.hazardlib.logictree.get_effective_rlzs(rlzs)[source]

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

Parameters:

rlzs – a list of Realization instances with a .pid property

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_id='')[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.read_source_groups(fname)[source]
Parameters:

fname – a path to a source model XML file

Returns:

a list of SourceGroup objects containing source nodes

openquake.hazardlib.logictree.reduce_fnames(fnames, source_id)[source]

If the source ID is ambiguous (i.e. there is “!”) only returns the filenames containing the source, otherwise return all the filenames

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)[source]
Path:

sequence of strings

Shortener:

dictionary longstring -> shortstring

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.BaseContext[source]

Bases: object

Base class for context object.

class openquake.hazardlib.contexts.Collapser(collapse_level, kfields)[source]

Bases: object

Class managing the collapsing logic.

collapse(ctx, mon, rup_indep, collapse_level=None)[source]

Collapse a context recarray if possible.

Parameters:
  • ctx – a recarray with “sids”

  • rup_indep – False if the ruptures are mutually exclusive

  • collapse_level – if None, use .collapse_level

Returns:

the collapsed array and the inverting indices

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

dcache_size()[source]
Returns:

the size in bytes of the distance cache

deltagetter = None
estimate_sites(src, sites)[source]
Parameters:
  • src – a (Collapsed)PointSource

  • sites – a filtered SiteCollection

Returns:

how many sites are impacted overall

estimate_weight(src, srcfilter, multiplier=1)[source]
Parameters:
  • src – a source object

  • srcfilter – a SourceFilter instance

Returns:

(weight, estimate_sites)

fewsites = False
from_planar(rup, hdist, step, point='TC', toward_azimuth=90, 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)[source]
Parameters:
  • srcs – a list of Source objects

  • sitecol – a SiteCollection instance

Returns:

a list of context arrays

gen_contexts(rups_sites, src_id)[source]
Yields:

the old-style RuptureContexts generated by the source

gen_ctxs_planar(src, sitecol)[source]
Parameters:
  • src – a (Collapsed)PointSource

  • sitecol – a filtered SiteCollection

Yields:

context arrays

gen_poes(ctx, rup_indep=True)[source]
Parameters:
  • ctx – a vectorized context (recarray) of size N

  • rup_indep – rupture flag (false for mutex ruptures)

Yields:

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

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

4 attenuation curves mu, sig, tau, phi

get_ctx_iter(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:

iterator over recarrays

get_ctx_params()[source]
Returns:

the interesting attributes of the context

get_legacy_ctx(rup, sites, distances=None)[source]
Returns:

a legacy RuptureContext (or None if filtered away)

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_pmap(ctxs, tom=None, rup_mutex={})[source]
Parameters:
  • ctxs – a list of context arrays (only one for poissonian ctxs)

  • tom – temporal occurrence model (default PoissonTom)

  • rup_mutex – dictionary of weights (default empty)

Returns:

a ProbabilityMap

get_poes(srcs, sitecol, tom=None, rup_mutex={}, collapse_level=-1)[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)

horiz_comp_to_geom_mean(mean_stds)[source]

This function converts ground-motion obtained for a given description of horizontal component into ground-motion values for geometric_mean.

The conversion equations used are from:
  • Beyer and Bommer (2006): for arithmetic mean, GMRot and random

  • Boore and Kishida (2017): for RotD50

init_monitoring(monitor)[source]
make_legacy_ctx(rup)[source]

Add .REQUIRES_RUPTURE_PARAMETERS to the rupture

max_intensity(sitecol1, mags, dists)[source]
Parameters:
  • sitecol1 – a SiteCollection instance with a single site

  • mags – a sequence of magnitudes

  • dists – a sequence of distances

Returns:

an array of GMVs of shape (#mags, #dists)

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)[source]
Parameters:

imts – a list of IMT strings subset of the full list

Returns:

a new ContextMaker involving less IMTs

set_imts_conv()[source]

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

set_weight(sources, srcfilter, multiplier=1, mon=<Monitor [runner]>)[source]

Set the weight attribute on each prefiltered source

tom = None
update(pmap, ctxs, tom, rup_mutex={})[source]
Parameters:
  • pmap – probability map to update

  • ctxs – a list of context arrays (only one for parametric ctxs)

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

The rup_mutex dictionary is read-only and normally empty

class openquake.hazardlib.contexts.DeltaRatesGetter(dstore)[source]

Bases: object

Read the delta rates from an aftershock datastore

class openquake.hazardlib.contexts.DistancesContext(param_dist_pairs=())[source]

Bases: BaseContext

Distances context for ground shaking intensity models.

Instances of this class are passed into GroundShakingIntensityModel.get_mean_and_stddevs(). They are intended to represent relevant distances between sites from the collection and the rupture. Every GSIM class is required to declare what distance measures does it need. Only those required values are calculated and made available in a result context object.

roundup(minimum_distance)[source]

If the minimum_distance is nonzero, returns a copy of the DistancesContext with updated distances, i.e. the ones below minimum_distance are rounded up to the minimum_distance. Otherwise, returns the original DistancesContext unchanged.

class openquake.hazardlib.contexts.Effect(effect_by_mag, dists, collapse_dist=None)[source]

Bases: object

Compute the effect of a rupture of a given magnitude and distance.

Parameters:
  • effect_by_mag – a dictionary magstring -> intensities

  • dists – array of distances, one per each intensity

  • cdist – collapse distance

collapse_value(collapse_dist)[source]
Returns:

intensity at collapse distance

dist_by_mag(intensity)[source]
Returns:

a dict magstring -> distance

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

get_reqv()[source]
class openquake.hazardlib.contexts.PmapMaker(cmaker, srcfilter, group)[source]

Bases: object

A class to compute the PoEs from a given source

count_bytes(ctxs)[source]
gen_ctxs(src)[source]
make(pmap)[source]
class openquake.hazardlib.contexts.RuptureContext(param_pairs=())[source]

Bases: BaseContext

Rupture calculation context for ground shaking intensity models.

Instances of this class are passed into GroundShakingIntensityModel.get_mean_and_stddevs(). They are intended to 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.

roundup(minimum_distance)[source]

If the minimum_distance is nonzero, returns a copy of the RuptureContext with updated distances, i.e. the ones below minimum_distance are rounded up to the minimum_distance. Otherwise, returns the original.

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
class openquake.hazardlib.contexts.SitesContext(slots=['vs30', 'vs30measured', 'z1pt0', 'z2pt5'], sitecol=None)[source]

Bases: BaseContext

Sites calculation context for ground shaking intensity models.

Instances of this class are passed into GroundShakingIntensityModel.get_mean_and_stddevs(). They are intended to represent relevant features of the sites collection. Every GSIM class is required to declare what sites parameters does it need. Only those required parameters are made available in a result context object.

openquake.hazardlib.contexts.basename(src, splitchars='.:')[source]
Returns:

the base name of a split source

>>> basename('SC:10;0')
'SC;0'
openquake.hazardlib.contexts.by_dists(gsim)[source]
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. :returns: [] or [poisson_ctx] or [poisson_ctx, nonpoisson_ctx, …]

openquake.hazardlib.contexts.full_context(sites, rup, dctx=None)[source]
Returns:

a full RuptureContext with all the relevant attributes

openquake.hazardlib.contexts.get_cmakers(src_groups, full_lt, oq)[source]
Params src_groups:

a list of SourceGroups

Parameters:
  • full_lt – a FullLogicTree instance

  • oq – object containing the calculation parameters

Returns:

list of ContextMakers associated to the given src_groups

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

Extract the distance parameters from a context.

Returns:

a dictionary dist_name -> distances

openquake.hazardlib.contexts.get_effect_by_mag(mags, sitecol1, gsims_by_trt, maximum_distance, imtls)[source]
Parameters:
  • mags – an ordered list of magnitude strings with format %.2f

  • sitecol1 – a SiteCollection with a single site

  • gsims_by_trt – a dictionary trt -> gsims

  • maximum_distance – an IntegrationDistance object

  • imtls – a DictArray with intensity measure types and levels

Returns:

a dict magnitude-string -> array(#dists, #trts)

openquake.hazardlib.contexts.get_maxsize(M, G)[source]
Returns:

an integer N such that arrays N*M*G fit in the CPU cache

openquake.hazardlib.contexts.get_mean_stds(gsim, ctx, imts, **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 IMTs

  • 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.get_src_mutex(srcs)[source]
Parameters:

srcs – a list of sources with weights and the same grp_id

Returns:

a dictionary grp_id -> {‘src_id’: […], ‘weight’: […]}

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

True if it is a ModifiableGMPE

openquake.hazardlib.contexts.kround1(ctx, kfields)[source]
openquake.hazardlib.contexts.kround2(ctx, kfields)[source]
openquake.hazardlib.contexts.print_finite_size(rups)[source]

Used to print the number of finite-size ruptures

openquake.hazardlib.contexts.read_cmaker(dstore, trt_smr)[source]
Parameters:

dstore – a DataStore-like object

Returns:

a ContextMaker instance

openquake.hazardlib.contexts.read_cmakers(dstore, csm=None)[source]
Parameters:
  • dstore – a DataStore-like object

  • csm – a CompositeSourceModel instance, if given

Returns:

a list of ContextMaker instances, one per source group

openquake.hazardlib.contexts.read_ctx_by_grp(dstore)[source]
Parameters:

dstore – DataStore instance

Returns:

dictionary grp_id -> ctx

openquake.hazardlib.contexts.round_dist(dst)[source]
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.split_by_occur(ctx)[source]
Returns:

[poissonian] or [poissonian, nonpoissonian,…]

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)[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

apply_conversion(imt)
Parameters:
  • imc – IMC instance

  • imt – intensity measure type instance

Returns:

conversion coefficients conv_median, conv_sigma, rstd

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)[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'
openquake.hazardlib.const.apply_conversion(imc, imt)[source]
Parameters:
  • imc – IMC instance

  • imt – intensity measure type instance

Returns:

conversion coefficients conv_median, conv_sigma, rstd

correlation

Module openquake.hazardlib.correlation defines correlation models for spatially-distributed ground-shaking intensities.

class openquake.hazardlib.correlation.BaseCorrelationModel[source]

Bases: object

Base class for correlation models for spatially-distributed ground-shaking intensities.

apply_correlation(sites, imt, residuals, stddev_intra=0)[source]

Apply correlation to randomly sampled residuals.

Parameters:
  • sitesSiteCollection residuals were sampled for.

  • imt – Intensity measure type object, see openquake.hazardlib.imt.

  • residuals – 2d numpy array of sampled residuals, where first dimension represents sites (the length as sites parameter) and second one represents different realizations (samples).

  • stddev_intra – Intra-event standard deviation array (phi). Different sites do not necessarily have the same intra-event standard deviation.

Returns:

Array of the same structure and semantics as residuals but with correlations applied.

NB: the correlation matrix is cached. It is computed only once per IMT for the complete site collection and then the portion corresponding to the sites is multiplied by the residuals.

class openquake.hazardlib.correlation.HM2018CorrelationModel(uncertainty_multiplier=0)[source]

Bases: BaseCorrelationModel

“Uncertainty in intraevent spatial correlation of elastic pseudo- acceleration spectral ordinates” by Pablo Heresi and Eduardo Miranda. Submitted for possible publication in Bulletin of Earthquake Engineering, 2018.

Parameters:

uncertainty_multiplier – Value to be multiplied by the uncertainty in the correlation parameter beta. If uncertainty_multiplier = 0 (default), the median value is used as a constant value.

apply_correlation(sites, imt, residuals, stddev_intra)[source]

Apply correlation to randomly sampled residuals

class openquake.hazardlib.correlation.JB2009CorrelationModel(vs30_clustering)[source]

Bases: BaseCorrelationModel

“Correlation model for spatially distributed ground-motion intensities” by Nirmal Jayaram and Jack W. Baker. Published in Earthquake Engineering and Structural Dynamics 2009; 38, pages 1687-1708.

Parameters:

vs30_clustering – Boolean value to indicate whether “Case 1” or “Case 2” from page 1700 should be applied. True value means that Vs 30 values show or are expected to show clustering (“Case 2”), False means otherwise.

get_lower_triangle_correlation_matrix(sites, imt)[source]

Get lower-triangle matrix as a result of Cholesky-decomposition of correlation matrix.

The resulting matrix should have zeros on values above the main diagonal.

The actual implementations of BaseCorrelationModel interface might calculate the matrix considering site collection and IMT (like JB2009CorrelationModel does) or might have it pre-constructed for a specific site collection and IMT, in which case they will need to make sure that parameters to this function match parameters that were used to pre-calculate decomposed correlation matrix.

Parameters:
openquake.hazardlib.correlation.hmcorrelation(sites_or_distances, imt, uncertainty_multiplier=0)[source]

Returns the Heresi-Miranda correlation model.

Parameters:
  • sites_or_distances – SiteCollection instance o distance matrix

  • imt – Intensity Measure Type (PGA or SA)

  • uncertainty_multiplier – Value to be multiplied by the uncertainty in the correlation parameter beta. If uncertainty_multiplier = 0 (default), the median value is used as a constant value.

openquake.hazardlib.correlation.jbcorrelation(sites_or_distances, imt, vs30_clustering=False)[source]

Returns the Jayaram-Baker correlation model.

Parameters:
  • sites_or_distances – SiteCollection instance o ristance matrix

  • imt – Intensity Measure Type (PGA or SA)

  • vs30_clustering – flag, defalt false

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()[source]

Dummy spectral acceleration to compute average ground motion over several spectral ordinates.

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

Bases: tuple

damping

Alias for field number 2

property frequency
period

Alias for field number 1

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.LSD()[source]

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

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

Liquefaction spatial extent as percentage of a pixel area.

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

Liquefaction occurrence class

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

Liquefaction probability

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

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

Bases: object

Branch object, represents a <logicTreeBranch /> element.

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

  • branch_id – String identifier of the branch

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

  • value – The actual uncertainty parameter value. A text node contents of <uncertaintyModel /> child node. Type depends on the branchset’s uncertainty type.

property id
is_leaf()[source]
Returns:

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

class openquake.hazardlib.lt.BranchSet(uncertainty_type, ordinal=0, filters=None, 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.

    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

    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

  • 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
collapse()[source]

Collapse to the first branch (with side effects)

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 – List of branch IDs

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.CompositeLogicTree(branchsets)[source]

Bases: object

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

get_all_paths()[source]
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.

property pid
class openquake.hazardlib.lt.Weighted(object, weight)

Bases: tuple

object

Alias for field number 0

weight

Alias for field number 1

openquake.hazardlib.lt.abGR(utype, node, filename)[source]
openquake.hazardlib.lt.add_path(bset, bsno, brno, num_prev, tot, paths)[source]
openquake.hazardlib.lt.apply_uncertainties(bset_values, src_group)[source]
Parameters:
  • bset_value – a list of pairs (branchset, value) List of branch IDs

  • src_group – SourceGroup instance

Returns:

A copy of the original group with possibly modified sources

openquake.hazardlib.lt.build(*bslists)[source]
Parameters:

bslists – a list of lists describing branchsets

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', 'extra2', 0.2]])
>>> lt.get_all_paths()
['AC', 'AD', 'AE', 'BC', 'BD', 'BE']
openquake.hazardlib.lt.charGeom(utype, node, filename)[source]
openquake.hazardlib.lt.complexGeom(utype, node, filename)[source]
openquake.hazardlib.lt.count_paths(branches)[source]
Parameters:

branches – a list of branches (endpoints or nodes)

Returns:

the number of paths in the branchset (slow)

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

a dummy BranchSet with a single branch

openquake.hazardlib.lt.incMFD(utype, node, filename)[source]
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.random_sample(branchsets, num_samples, seed, sampling_method)[source]
>>> bsets = [[('X', .4), ('Y', .6)], [('A', .2), ('B', .3), ('C', .5)]]
>>> paths = random_sample(bsets, 100, 42, 'early_weights')
>>> collections.Counter(paths)
Counter({'YC': 26, 'XC': 24, 'YB': 17, 'XA': 13, 'YA': 10, 'XB': 10})
>>> paths = random_sample(bsets, 100, 42, 'late_weights')
>>> collections.Counter(paths)
Counter({'XA': 20, 'YA': 18, 'XB': 17, 'XC': 15, 'YB': 15, 'YC': 15})
>>> paths = random_sample(bsets, 100, 42, 'early_latin')
>>> collections.Counter(paths)
Counter({'YC': 31, 'XC': 19, 'YB': 17, 'XB': 13, 'YA': 12, 'XA': 8})
>>> paths = random_sample(bsets, 100, 45, 'late_latin')
>>> collections.Counter(paths)
Counter({'YC': 18, 'XA': 18, 'XC': 16, 'YA': 16, 'XB': 16, 'YB': 16})
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.setMSR_absolute(utype, node, filename)[source]
openquake.hazardlib.lt.simpleGeom(utype, node, filename)[source]
openquake.hazardlib.lt.smodel(utype, node, filename)[source]
openquake.hazardlib.lt.trucMFDFromSlip_absolute(utype, node, filename)[source]
openquake.hazardlib.lt.unknown(utype, node, filename)[source]

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:
  • sitePoint object representing the location of the target site

  • hypocenterPoint object representing the location of hypocenter

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

  • p0Point object representing the location of the starting point on fault segment

  • p1Point 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.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:
  • node0Point object representing the location of one vertices on the target fault segment.

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

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

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

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

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

  • referencePoint 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:
  • projectedPoint object representing the coordinates of target point to be projected

  • referencePoint 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

  • referencePoint 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 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.check_unique(ids, msg='')[source]

Raise a DuplicatedID exception if there are duplicated IDs

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)[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

openquake.hazardlib.nrml.read_source_models(fnames, converter)[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)[source]

Convert a node into a string in NRML format

openquake.hazardlib.nrml.write(nodes, output=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, fmt='%.7E', gml=True, xmlns=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

probability_map

class openquake.hazardlib.probability_map.ProbabilityCurve(array)[source]

Bases: object

This class is a small wrapper over an array of PoEs associated to a set of intensity measure types and levels. It provides a few operators, including the complement operator ~

~p = 1 - p

and the inclusive or operator |

p = p1 | p2 = ~(~p1 * ~p2)

Such operators are implemented efficiently at the numpy level, by dispatching on the underlying array.

Here is an example of use:

>>> poe = ProbabilityCurve(numpy.array([0.1, 0.2, 0.3, 0, 0]))
>>> ~(poe | poe) * .5
<ProbabilityCurve
[0.405 0.32  0.245 0.5   0.5  ]>
convert(imtls, idx=0)[source]

Convert a probability curve into a record of dtype imtls.dt.

Parameters:
  • imtls – DictArray instance

  • idx – extract the data corresponding to the given inner index

extract(inner_idx)[source]

Extracts the component specified by the index inner_idx.

class openquake.hazardlib.probability_map.ProbabilityMap(sids, shape_y, shape_z)[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 ProbabilityMap with shape (N, L, Gt) into a ProbabilityMap with shape (N, L, R): works only for rates

fill(value)[source]
Parameters:

value – a scalar probability

Fill the ProbabilityMap 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)

multiply_pnes(other, g, i)[source]

Multiply by the probabilities of no exceedence

new(array)[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

split()[source]
Yields:

G ProbabilityMaps of shape (N, L, 1)

to_dframe()[source]
Returns:

a DataFrame with fields sid, gid, lid, poe

to_rates(slc=slice(None, None, None))[source]

Assuming self contains an array of probabilities of no exceedance, returns an array of rates of shape (N, L, G).

update(poes, invs, ctxt, itime, mutex_weight)[source]

Update probabilities

openquake.hazardlib.probability_map.combine_probs(array, other, rlzs)[source]
openquake.hazardlib.probability_map.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.probability_map.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.probability_map.fix_probs_occur(probs_occur)[source]

Try to convert object arrays into regular arrays

openquake.hazardlib.probability_map.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])
>>> get_lvl(hcurve, imls, 1)
0
>>> get_lvl(hcurve, imls, .99)
1
>>> get_lvl(hcurve, imls, .91)
2
>>> get_lvl(hcurve, imls, .8)
3
openquake.hazardlib.probability_map.get_mean_curve(dstore, imt, site_id=0)[source]

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

openquake.hazardlib.probability_map.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.probability_map.update_pmap_i(arr, poes, inv, rates, probs_occur, idxs, itime)[source]
openquake.hazardlib.probability_map.update_pmap_m(arr, poes, inv, rates, probs_occur, weights, idxs, itime)[source]

site

Module openquake.hazardlib.site defines Site.

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 any of vs30, z1pt0 or z2pt5 is zero or negative.

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

assoc(site_model, assoc_dist, ignore=())[source]

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

Returns:

the site model array reduced to the hazard sites

at_sea_level()[source]

True if all depths are zero

calculate_z1pt0()[source]

Compute the column z1pt0 from the vs30

calculate_z2pt5()[source]

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

count_close(location, distance)[source]
Returns:

the number of sites within the distance from the location

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_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_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’]

make_complete()[source]

Turns the site collection into a complete one, if needed

property mesh

Return a mesh with the given lons, lats, and depths

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 around nsites (if nsites<=N)

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

Set the global site parameters (vs30, vs30measured, z1pt0, z2pt5, backarc)

split(ntiles)[source]
Parameters:

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

Returns:

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

split_in_tiles(hint)[source]

Split a SiteCollection into a set of tiles with contiguous site IDs

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

property xyz
Returns:

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

openquake.hazardlib.site.calculate_z1pt0(vs30)[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 & Youngs (2014) California model :param vs30: the shear wave velocity (in m/s) at a depth of 30m

openquake.hazardlib.site.calculate_z2pt5(vs30)[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

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=None, discard_trts=(), floating_x_step=0, floating_y_step=0, source_nodes=(), infer_occur_rates=False)[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=None, discard_trts=(), floating_x_step=0, floating_y_step=0, source_nodes=(), infer_occur_rates=False)[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_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 source node into a hazardlib source, 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

class openquake.hazardlib.sourceconverter.SourceGroup(trt, sources=None, name=None, src_interdep='indep', rup_interdep='indep', grp_probability=1.0, min_mag={'default': 0}, max_mag=None, temporal_occurrence_model=None, cluster=False)[source]

Bases: Sequence

A container for the following parameters:

Parameters:
  • trt (str) – the tectonic region type all the sources belong to

  • sources (list) – a list of hazardlib source objects

  • name – The name of the group

  • src_interdep – A string specifying if the sources in this cluster are independent or mutually exclusive

  • rup_indep – A string specifying if the ruptures within each source of the cluster are independent or mutually exclusive

  • weights – A dictionary whose keys are the source IDs of the cluster and the values are the weights associated with each source

  • min_mag – the minimum magnitude among the given sources

  • max_mag – the maximum magnitude among the given sources

  • id – an optional numeric ID (default 0) set by the engine and used when serializing SourceModels to HDF5

  • temporal_occurrence_model – A temporal occurrence model controlling the source group occurrence

  • cluster – A boolean indicating if the sources behaves as a cluster similarly to what used by the USGS for the New Madrid in the 2008 National Hazard Model.

property atomic
Returns:

True if the group cannot be split

changes = 0
classmethod collect(sources)[source]
Parameters:

sources – dictionaries with a key ‘tectonicRegion’

Returns:

an ordered list of SourceGroup instances

count_ruptures()[source]

Set src.num_ruptures on each source in the group

get_tom_toml(time_span)[source]
Returns:

the TOM as a json string {‘PoissonTOM’: {‘time_span’: 50}}

get_trt_smr()[source]
Returns:

the .trt_smr attribute of the underlying sources

split(maxweight)[source]

Split the group in subgroups with weight <= maxweight, unless it it atomic.

property tom_name
Returns:

name of the associated temporal occurrence model

update(src)[source]

Update the attributes sources, min_mag, max_mag according to the given source.

Parameters:

src – an instance of :class: openquake.hazardlib.source.base.BaseSeismicSource

property weight
Returns:

total weight of the underlying sources

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(hdd)[source]

Returns the hypocentral depth distribution as a Node instance

Parameters:

hdd – Hypocentral depth distribution as an instance of :class: openquake.hzardlib.pmf.PMF

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_ddict(src_groups)[source]
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.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.

>>> norm_cdf(1.2, 1, .1)
0.9772498680518208
>>> norm_cdf(1.2, 1, 0)
1.0
>>> norm_cdf(.8, 1, .1)
0.022750131948179216
>>> norm_cdf(.8, 1, 0)
0.0
>>> norm_cdf(1, 1, .1)
0.5
>>> 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.

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(seeds=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.

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(seeds=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.

class openquake.hazardlib.tom.NegativeBinomialTOM(time_span, mu, alpha)[source]

Bases: BaseTOM

Negative Binomial temporal occurrence model.

get_pmf(mean_rate, tol=0.99999999999999, n_max=None)[source]
Parameters:
  • mean_rate – The average number of events per year.

  • tol – Quantile value up to which calculate the pmf

Returns:

1D numpy 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(mean_rate=None, seed=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:
  • mean_rate – The mean rate, or mean number of events per year

  • seed – Random number generator seed

Returns:

Sampled integer number of events to occur within model’s time span.

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(occurrence_rate, seeds=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:
  • occurrence_rate – The average number of events per year.

  • seeds – Random number generator seeds, one per each occurrence_rate

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
REQUIRES_DISTANCES = {}
REQUIRES_RUPTURE_PARAMETERS = {}
REQUIRES_SITES_PARAMETERS = {}
compute(ctx, imts, mean, sig, tau, phi)[source]
init()[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.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.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.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)
Parameters:

value – input string

Returns:

a floating point number

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
>>> dictionary('{"ls": logscale(0.01, 2, 5)}')
{'ls': [0.01, 0.03760603093086393, 0.14142135623730948, 0.5318295896944986, 1.9999999999999991]}
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.gsim(value, basedir='')[source]

Convert a string into a GSIM instance

>>> gsim('BooreAtkinson2011')
[BooreAtkinson2011]
openquake.hazardlib.valid.host_port(value=None)[source]

Returns a pair (host_IP, port_number).

>>> host_port('localhost:1908')
('127.0.0.1', 1908)

If value is missing returns the parameters in openquake.cfg

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.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.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)
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.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.positivefloats(value)[source]
Parameters:

value – string of whitespace separated floats

Returns:

a list of positive floats

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