openquake.hazardlib.calc package

Hazardlib calculators

Disaggregation (disagg)

openquake.hazardlib.calc.disagg contains disaggregation() as well as several aggregation functions for extracting a specific PMF from the result of disaggregation().

class openquake.hazardlib.calc.disagg.BinData(dists, lons, lats, pnes)

Bases: tuple


Alias for field number 0


Alias for field number 2


Alias for field number 1


Alias for field number 3


Raises an AssertionError if the shapes are not consistent

openquake.hazardlib.calc.disagg.disaggregate(ctxs, g_by_z, iml2dict, eps3, sid=0, bin_edges=())[source]
  • ctxs – a list of U fat RuptureContexts
  • imts – a list of Intensity Measure Type objects
  • g_by_z – an array of gsim indices
  • imt – an Intensity Measure Type
  • iml2dict – a dictionary of arrays imt -> (P, Z)
  • eps3 – a triplet (truncnorm, epsilons, eps_bands)
openquake.hazardlib.calc.disagg.disaggregation(sources, site, imt, iml, gsim_by_trt, truncation_level, n_epsilons, mag_bin_width, dist_bin_width, coord_bin_width, source_filter=<openquake.hazardlib.calc.filters.SourceFilter object>, **kwargs)[source]

Compute “Disaggregation” matrix representing conditional probability of an intensity mesaure type imt exceeding, at least once, an intensity measure level iml at a geographical location site, given rupture scenarios classified in terms of:

  • rupture magnitude
  • Joyner-Boore distance from rupture surface to site
  • longitude and latitude of the surface projection of a rupture’s point closest to site
  • epsilon: number of standard deviations by which an intensity measure level deviates from the median value predicted by a GSIM, given the rupture parameters
  • rupture tectonic region type

In other words, the disaggregation matrix allows to compute the probability of each scenario with the specified properties (e.g., magnitude, or the magnitude and distance) to cause one or more exceedences of a given hazard level.

For more detailed information about the disaggregation, see for instance “Disaggregation of Seismic Hazard”, Paolo Bazzurro, C. Allin Cornell, Bulletin of the Seismological Society of America, Vol. 89, pp. 501-520, April 1999.

  • sources – Seismic source model, as for PSHA calculator it should be an iterator of seismic sources.
  • siteSite of interest to calculate disaggregation matrix for.
  • imt – Instance of intensity measure type class.
  • iml – Intensity measure level. A float value in units of imt.
  • gsim_by_trt – Tectonic region type to GSIM objects mapping.
  • truncation_level – Float, number of standard deviations for truncation of the intensity distribution.
  • n_epsilons – Integer number of epsilon histogram bins in the result matrix.
  • mag_bin_width – Magnitude discretization step, width of one magnitude histogram bin.
  • dist_bin_width – Distance histogram discretization step, in km.
  • coord_bin_width – Longitude and latitude histograms discretization step, in decimal degrees.
  • source_filter – Optional source-site filter function. See openquake.hazardlib.calc.filters.

A tuple of two items. First is itself a tuple of bin edges information for (in specified order) magnitude, distance, longitude, latitude, epsilon and tectonic region types.

Second item is 6d-array representing the full disaggregation matrix. Dimensions are in the same order as bin edges in the first item of the result tuple. The matrix can be used directly by pmf-extractor functions.

openquake.hazardlib.calc.disagg.get_edges_shapedic(oq, sitecol, mags_by_trt)[source]
Returns:(mag dist lon lat eps trt) edges and shape dictionary
openquake.hazardlib.calc.disagg.lon_lat_bins(lon, lat, size_km, coord_bin_width)[source]

Define lon, lat bin edges for disaggregation histograms.

  • lon – longitude of the site
  • lat – latitude of the site
  • size_km – total size of the bins in km
  • coord_bin_width – bin width in degrees

two arrays lon bins, lat bins


Fold full disaggregation matrices to lon / lat / TRT PMF.

Parameters:matrices – a matrix with T submatrices
Returns:4d array. First dimension represents longitude histogram bins, second one latitude histogram bins, third one trt histogram bins, last dimension is the z index, associatd to the realization.
openquake.hazardlib.calc.disagg.set_mean_std(ctxs, imts, gsims)[source]

Filters (filters)

class openquake.hazardlib.calc.filters.MagDepDistance[source]

Bases: dict

A dictionary trt -> [(mag, dist), …]

get_bounding_box(lon, lat, trt=None, mag=None)[source]

Build a bounding box around the given lon, lat by computing the maximum_distance at the given tectonic region type and magnitude.

  • lon – longitude
  • lat – latitude
  • trt – tectonic region type, possibly None
  • mag – magnitude, possibly None

min_lon, min_lat, max_lon, max_lat

get_dist_bins(trt, nbins=51)[source]
Returns:an array of distance bins, from 10m to maxdist
Parameters:mags_by_trt – a dictionary trt -> magnitudes as strings
Returns:a dictionary trt->mag->dist
Returns:a dictionary trt -> maxdist
classmethod new(value)[source]
Parameters:value – string to be converted
Returns:MagDepDistance dictionary
>>> md ='50')
>>> md
{'default': [(1.0, 50), (10.0, 50)]}
>>> md.max()
{'default': 50}
>>> md.interp(dict(default=[5.0, 5.1, 5.2])); md.ddic
{'default': {'5.00': 50.0, '5.10': 50.0, '5.20': 50.0}}
Returns:True if there is a ? for any TRT
class openquake.hazardlib.calc.filters.SourceFilter(sitecol, integration_distance)[source]

Bases: object

Filter objects have a .filter method yielding filtered sources and the IDs of the sites within the given maximum distance. Filter the sources by using self.sitecol.within_bbox which is based on numpy.

close_sids(src_or_rec, trt=None, maxdist=None)[source]
  • src_or_rec – a source or a rupture record
  • trt – passed only if src_or_rec is a rupture record

the site indices within the maximum_distance of the hypocenter, plus the maximum size of the bounding box

Parameters:sources – a sequence of sources
Yields:sources with indices

Returns the sites within the integration distance from the source, or None.

get_enlarged_box(src, maxdist=None)[source]

Get the enlarged bounding box of a source.

  • src – a source object
  • maxdist – a scalar maximum distance (or None)

a bounding box (min_lon, min_lat, max_lon, max_lat)

Parameters:src – a source object
Returns:((min_lon, min_lat), width, height), useful for plotting

Reduce the SourceFilter to a subset of sites

Yields:pairs (split, sites)

Split the SourceFilter by splitting the site collection in tiles


Used to add the source_id to the error message. To be used as

with context(src):

Typically the operation is filtering a source, that can fail for tricky geometries.

Parameters:value – input string corresponding to a literal Python number or dictionary
Returns:a Python dictionary key -> number
>>> floatdict("200")
{'default': 200}
>>> text = "{'active shallow crust': 250., 'default': 200}"
>>> sorted(floatdict(text).items())
[('active shallow crust', 250.0), ('default', 200)]
openquake.hazardlib.calc.filters.getdefault(dic_with_default, key)[source]
  • dic_with_default – a dictionary with a ‘default’ key
  • key – a key that may be present in the dictionary or not

the value associated to the key, or to ‘default’

Parameters:src – a splittable (or not splittable) source
Returns:the underlying sources (or the source itself)

Check that the items are unique and sorted

Ground Motion Fields (gmf)

Module gmf exports ground_motion_fields().

exception openquake.hazardlib.calc.gmf.CorrelationButNoInterIntraStdDevs(corr, gsim)[source]

Bases: Exception

class openquake.hazardlib.calc.gmf.GmfComputer(rupture, sitecol, cmaker, truncation_level=None, correlation_model=None, amplifier=None, sec_perils=())[source]

Bases: object

Given an earthquake rupture, the ground motion field computer computes ground shaking over a set of sites, by randomly sampling a ground shaking intensity model.

Parameters:rupture – Rupture to calculate ground motion fields radiated from.
:param sitecol:
a complete SiteCollection
  • imts – a sorted list of Intensity Measure Type strings
  • cmaker – a openquake.hazardlib.gsim.base.ContextMaker instance
  • truncation_level – Float, number of standard deviations for truncation of the intensity distribution, or None.
  • correlation_model – Instance of correlation model object. See openquake.hazardlib.correlation. Can be None, in which case non-correlated ground motion fields are calculated. Correlation model is not used if truncation_level is zero.
  • amplifier – None or an instance of Amplifier
compute(gsim, num_events)[source]
  • gsim – a GSIM instance
  • num_events – the number of seismic events

a 32 bit array of shape (num_imts, num_sites, num_events) and two arrays with shape (num_imts, num_events): sig for stddev_inter and eps for the random part

compute_all(min_iml, rlzs_by_gsim, sig_eps=None)[source]
Returns:(dict with fields eid, sid, gmv_…), dt
openquake.hazardlib.calc.gmf.ground_motion_fields(rupture, sites, imts, gsim, truncation_level, realizations, correlation_model=None, seed=None)[source]

Given an earthquake rupture, the ground motion field calculator computes ground shaking over a set of sites, by randomly sampling a ground shaking intensity model. A ground motion field represents a possible ‘realization’ of the ground shaking due to an earthquake rupture.


This calculator is using random numbers. In order to reproduce the same results numpy random numbers generator needs to be seeded, see

  • rupture (openquake.hazardlib.source.rupture.Rupture) – Rupture to calculate ground motion fields radiated from.
  • sites ( – Sites of interest to calculate GMFs.
  • imts – List of intensity measure type objects (see openquake.hazardlib.imt).
  • gsim – Ground-shaking intensity model, instance of subclass of either GMPE or IPE.
  • truncation_level – Float, number of standard deviations for truncation of the intensity distribution, or None.
  • realizations – Integer number of GMF realizations to compute.
  • correlation_model – Instance of correlation model object. See openquake.hazardlib.correlation. Can be None, in which case non-correlated ground motion fields are calculated. Correlation model is not used if truncation_level is zero.
  • seed (int) – The seed used in the numpy random number generator

Dictionary mapping intensity measure type objects (same as in parameter imts) to 2d numpy arrays of floats, representing different realizations of ground shaking intensity for all sites in the collection. First dimension represents sites and second one is for realizations.

openquake.hazardlib.calc.gmf.rvs(distribution, *size)[source]
openquake.hazardlib.calc.gmf.to_imt_unit_values(vals, imt)[source]

Exponentiate the values unless the IMT is MMI

Hazard Curves (hazard_curve)

openquake.hazardlib.calc.hazard_curve implements calc_hazard_curves(). Here is an example of a classical PSHA parallel calculator computing the hazard curves per each realization in less than 20 lines of code:

import sys
from openquake.commonlib import logs
from openquake.calculators.base import get_calc

def main(job_ini):
    calc_id = logs.init()
    calc = get_calc(job_ini, calc_id)'true', shutdown=True)
    print('The hazard curves are in %s::/hcurves-rlzs'
          % calc.datastore.filename)

if __name__ == '__main__':
    main(sys.argv[1])  # path to a job.ini file

NB: the implementation in the engine is smarter and more efficient. Here we start a parallel computation per each realization, the engine manages all the realizations at once.

openquake.hazardlib.calc.hazard_curve.calc_hazard_curve(site1, src, gsims, oqparam)[source]
  • site1 – site collection with a single site
  • src – a seismic source object
  • gsims – a list of GSIM objects
  • oqparam – an object with attributes .maximum_distance, .imtls

a ProbabilityCurve object

openquake.hazardlib.calc.hazard_curve.calc_hazard_curves(groups, srcfilter, imtls, gsim_by_trt, truncation_level=None, apply=<function sequential_apply>, reqv=None, **kwargs)[source]

Compute hazard curves on a list of sites, given a set of seismic source groups and a dictionary of ground shaking intensity models (one per tectonic region type).

Probability of ground motion exceedance is computed in different ways depending if the sources are independent or mutually exclusive.

  • groups – A sequence of groups of seismic sources objects (instances of of BaseSeismicSource).
  • srcfilter – A source filter over the site collection or the site collection itself
  • imtls – Dictionary mapping intensity measure type strings to lists of intensity measure levels.
  • gsim_by_trt – Dictionary mapping tectonic region types (members of openquake.hazardlib.const.TRT) to GMPE or IPE objects.
  • truncation_level – Float, number of standard deviations for truncation of the intensity distribution.
  • apply – apply function to use (default sequential_apply)
  • reqv – If not None, an instance of RjbEquivalent

An array of size N, where N is the number of sites, which elements are records with fields given by the intensity measure types; the size of each field is given by the number of levels in imtls.

openquake.hazardlib.calc.hazard_curve.classical(group, src_filter, gsims, param, monitor=<Monitor [runner]>)[source]

Compute the hazard curves for a set of sources belonging to the same tectonic region type for all the GSIMs associated to that TRT. The arguments are the same as in calc_hazard_curves(), except for gsims, which is a list of GSIM instances.

Returns:a dictionary with keys pmap, calc_times, rup_data, extra

Stochastic Event Set (stochastic)

openquake.hazardlib.calc.stochastic contains stochastic_event_set().

openquake.hazardlib.calc.stochastic.get_rup_array(ebruptures, srcfilter=<openquake.hazardlib.calc.filters.SourceFilter object>)[source]

Convert a list of EBRuptures into a numpy composite array, by filtering out the ruptures far away from every site

openquake.hazardlib.calc.stochastic.sample_cluster(sources, srcfilter, num_ses, param)[source]

Yields ruptures generated by a cluster of sources.

  • sources – A sequence of sources of the same group
  • num_ses – Number of stochastic event sets
  • param – a dictionary of additional parameters including ses_per_logic_tree_path

dictionaries with keys rup_array, calc_times, eff_ruptures

openquake.hazardlib.calc.stochastic.sample_ruptures(sources, srcfilter, param, monitor=<Monitor [runner]>)[source]
  • sources – a sequence of sources of the same group
  • srcfilter – SourceFilter instance used also for bounding box post filtering
  • param – a dictionary of additional parameters including ses_per_logic_tree_path
  • monitor – monitor instance

dictionaries with keys rup_array, calc_times

openquake.hazardlib.calc.stochastic.stochastic_event_set(sources, source_site_filter=<openquake.hazardlib.calc.filters.SourceFilter object>, **kwargs)[source]

Generates a ‘Stochastic Event Set’ (that is a collection of earthquake ruptures) representing a possible realization of the seismicity as described by a source model.

The calculator loops over sources. For each source, it loops over ruptures. For each rupture, the number of occurrence is randomly sampled by calling openquake.hazardlib.source.rupture.BaseProbabilisticRupture.sample_number_of_occurrences()


This calculator is using random numbers. In order to reproduce the same results numpy random numbers generator needs to be seeded, see

  • sources – An iterator of seismic sources objects (instances of subclasses of BaseSeismicSource).
  • source_site_filter – The source filter to use (default noop filter)

Generator of Rupture objects that are contained in an event set. Some ruptures can be missing from it, others can appear one or more times in a row.