openquake.hazardlib package¶
Subpackages¶
- openquake.hazardlib.calc package
- openquake.hazardlib.geo package
- Surface classes
- openquake.hazardlib.geo.surface package
- Submodules
- openquake.hazardlib.geo.surface.base module
- openquake.hazardlib.geo.surface.complex_fault module
- openquake.hazardlib.geo.surface.gridded module
- openquake.hazardlib.geo.surface.multi module
- openquake.hazardlib.geo.surface.planar module
- openquake.hazardlib.geo.surface.simple_fault module
- Module contents
- openquake.hazardlib.geo.surface package
- Geographic primitives and utilities
- geodetic
- line
- mesh
- nodalplane
- point
- polygon
- utils
- Module contents
- Surface classes
- openquake.hazardlib.gsim package
- Ground-shaking intensity models
- abrahamson_2014
- abrahamson_2015
- abrahamson_2018
- abrahamson_gulerce_2020
- abrahamson_silva_1997
- abrahamson_silva_2008
- afshari_stewart_2016
- akkar_2013
- akkar_2014
- akkar_bommer_2010
- akkar_bommer_2010_swiss_coeffs
- akkar_cagnan_2010
- allen_2012
- allen_2012_ipe
- allen_2022
- ameri_2017
- armenia_2016
- arroyo_2010
- arteta_2021
- atkinson_2015
- atkinson_boore_1995
- atkinson_boore_2003
- atkinson_boore_2006
- atkinson_macias_2009
- bahrampouri_2021_Arias_Intensity
- bahrampouri_2021_duration
- baumont_2018
- bayless_abrahamson_2018
- bchydro_2016_epistemic
- berge_thierry_2003
- bindi_2011
- bindi_2011_ipe
- bindi_2011scaled
- bindi_2014
- bindi_2014scaled
- bindi_2017
- bommer_2009
- boore_1993
- boore_1997
- boore_2014
- boore_2020
- boore_atkinson_2008
- boore_atkinson_2011
- bora_2019
- bozorgnia_campbell_2016
- bozorgnia_campbell_2016_vh
- bradley_2013
- campbell_1997
- campbell_2003
- campbell_bozorgnia_2003
- campbell_bozorgnia_2008
- campbell_bozorgnia_2014
- cauzzi_2014
- cauzzi_faccioli_2008
- cauzzi_faccioli_2008_swiss
- cauzzi_faccioli_2008_swiss_coeffs
- chao_2020
- chiou_youngs_2008
- chiou_youngs_2008_swiss
- chiou_youngs_2008_swiss_coeffs
- chiou_youngs_2014
- climent_1994
- coeffs_table
- convertito_2012
- derras_2014
- dost_2004
- douglas_stochastic_2013
- dowrickrhoades_2005
- drouet_2015_brazil
- drouet_alpes_2015
- ecos_2009
- edwards_fah_2013a
- edwards_fah_2013a_coeffs
- edwards_fah_2013f
- edwards_fah_2013f_coeffs
- eshm20_craton
- faccioli_cauzzi_2006
- frankel_1996
- fukushima_tanaka_1990
- garcia_2005
- geomatrix_1993
- ghofrani_atkinson_2014
- gmpe_table
- gulerce_abrahamson_2011
- gulerce_2017
- gupta_2010
- hassani_atkinson_2018
- hassani_atkinson_2020
- hong_goda_2007
- idini_2017
- idriss_2014
- jaimes_2020
- kale_2015
- kanno_2006
- kuehn_2020
- kotha_2016
- kotha_2020
- lanzano_2016
- lanzano_2019
- lanzano_2020
- lanzano_luzi_2019
- lin_2009
- lin_2011
- lin_lee_2008
- manea_2021
- mcverry_2006
- megawati_2003
- megawati_pan_2010
- montalva_2016
- montalva_2017
- multi
- munson_thurber_1997
- morikawa_fujiwara_2013
- nath_2012
- nga_east
- nrcan15_site_term
- nshmp_2014
- pankow_pechmann_2004
- parker_2020
- pezeshk_2011
- phung_2020
- raghukanth_iyengar_2007
- rietbrock_2013
- rietbrock_edwards_2019
- sadigh_1997
- sera_amplification_models
- sgobba_2020
- shahjouei_pezeshk_2016
- sharma_2009
- si_midorikawa_1999
- si_2020
- silva_2002
- skarlatoudis_2013
- somerville_2001
- somerville_2009
- stewart_2016
- stewart_2016_vh
- tavakoli_pezeshk_2005
- example_a_2021
- toro_1997
- toro_2002
- travasarou_2003
- tromans_2019
- tusa_langer_2016
- tusa_langer_azzaro_2019
- utils
- utils_swiss_gmpe
- usgs_ceus_2019
- vanhoutte_2018
- wong2022
- yenier_atkinson_2015
- youd_etal_2002
- youngs_1997
- yu_2013
- zalachoris_rathje_2019
- zhang_zhao_2005
- zhao_2006
- zhao_2006_swiss
- zhao_2006_swiss_coeffs
- zhao_2016
- openquake.hazardlib.mfd package
- openquake.hazardlib.scalerel package
- openquake.hazardlib.source package
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.
- 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']¶
- 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_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_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_mean_stds(ctxs, split_by_mag=False)[source]¶
- Parameters
ctxs – a list of contexts with N=sum(len(ctx) for ctx in ctxs)
disagg – True when called from the disaggregation calculator
- Returns
an array of shape (4, G, M, N) with mean and stddevs
- get_pmap(ctxs, rup_indep=True)[source]¶
- Parameters
ctxs – a list of context arrays (only one for poissonian ctxs)
rup_indep – default True
- Returns
a ProbabilityMap
- get_poes(srcs, sitecol, rup_indep=True, 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
- 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)
- read_ctxs(dstore, slc=None, magi=None)[source]¶
- Parameters
dstore – a DataStore instance
slice – a slice of contexts with the same grp_id
- Returns
a list of contexts
- recarray(ctxs, magi=None)[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
- property stop¶
- tom = None¶
- 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:
openquake.hazardlib.contexts.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 whatdistance measures
does it need. Only those required values are calculated and made available in a result context object.
- 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
- exception openquake.hazardlib.contexts.FarAwayRupture[source]¶
Bases:
Exception
Raised if the rupture is outside the maximum distance for all sites
- class openquake.hazardlib.contexts.PmapMaker(cmaker, srcfilter, group)[source]¶
Bases:
object
A class to compute the PoEs from a given source
- class openquake.hazardlib.contexts.RuptureContext(param_pairs=())[source]¶
Bases:
openquake.hazardlib.contexts.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 whatrupture 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:
openquake.hazardlib.contexts.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 whatsites parameters
does it need. Only those required parameters are made available in a result context object.
- 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: list with 0, 1 or 2 elements
- openquake.hazardlib.contexts.full_context(sites, rup, dctx=None)[source]¶
- Returns
a full RuptureContext with all the relevant attributes
- 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
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.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
const¶
Module openquake.hazardlib.const
defines various constants.
- class openquake.hazardlib.const.IMC(value)[source]¶
Bases:
enum.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.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'¶
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
sites –
SiteCollection
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. Note that 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:
openquake.hazardlib.correlation.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.
- class openquake.hazardlib.correlation.JB2009CorrelationModel(vs30_clustering)[source]¶
Bases:
openquake.hazardlib.correlation.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 (likeJB2009CorrelationModel
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
sites –
SiteCollection
to create correlation matrix for.imt – Intensity measure type object, see
openquake.hazardlib.imt
.
- 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.
imt¶
Module openquake.hazardlib.imt
defines different intensity measure
types.
- 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.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.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.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.
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¶
- 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¶
- 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 returnTrue
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), …]
- class openquake.hazardlib.lt.CompositeLogicTree(branchsets)[source]¶
Bases:
object
Build a logic tree from a set of branches by automatically setting the branch IDs.
- 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.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.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.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)[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
- Returns
A list of S objects extracted randomly
near_fault¶
Module openquake.hazardlib.nearfault
provides methods for near fault
PSHA calculation.
- openquake.hazardlib.near_fault.average_s_rad(site, hypocenter, reference, pp, normal, dist_to_plane, e, p0, p1, delta_slip)[source]¶
Gets the average S-wave radiation pattern given an e-path as described in: Spudich et al. (2013) “Final report of the NGA-West2 directivity working group”, PEER report, page 90- 92 and computes: the site to the direct point distance, rd, and the hypocentral distance, r_hyp.
- Parameters
site –
Point
object representing the location of the target sitehypocenter –
Point
object representing the location of hypocenterreference –
Point
object representing the location of the reference point for coordinate projection within the calculation. The suggested reference point is Epicentre.pp – the projection point pp on the patch plane, a numpy array
normal – normal of the plane, describe by a normal vector[a, b, c]
dist_to_plane – d is the constant term in the plane equation, e.g., ax + by + cz = d
e – a float defining the E-path length, which is the distance from Pd(direction) point to hypocentre. In km.
p0 –
Point
object representing the location of the starting point on fault segmentp1 –
Point
object representing the location of the ending point on fault segment.delta_slip – slip direction away from the strike direction, in decimal degrees. A positive angle is generated by a counter-clockwise rotation.
- Returns
fs, float value of the average S-wave radiation pattern. rd, float value of the distance from site to the direct point. r_hyp, float value of the hypocetre distance.
- openquake.hazardlib.near_fault.directp(node0, node1, node2, node3, hypocenter, reference, pp)[source]¶
Get the Direct Point and the corresponding E-path as described in Spudich et al. (2013). This method also provides a logical variable stating if the DPP calculation must consider the neighbouring patch. To define the intersection point(Pd) of PpPh line segment and fault plane, we obtain the intersection points(Pd) with each side of fault plan, and check which intersection point(Pd) is the one fitting the definition in the Chiou and Spudich(2014) directivity model. Two possible locations for Pd, the first case, Pd locates on the side of the fault patch when Pp is not inside the fault patch. The second case is when Pp is inside the fault patch, then Pd=Pp.
For the first case, it follows three conditions: 1. the PpPh and PdPh line vector are the same, 2. PpPh >= PdPh, 3. Pd is not inside the fault patch.
If we can not find solution for all the four possible intersection points for the first case, we check if the intersection point fit the second case by checking if Pp is inside the fault patch.
Because of the coordinate system mapping(from geographic system to Catestian system), we allow an error when we check the location. The allow error will keep increasing after each loop when no solution in the two cases are found, until the solution get obtained.
- Parameters
node0 –
Point
object representing the location of one vertices on the target fault segment.node1 –
Point
object representing the location of one vertices on the target fault segment. Note, the order should be clockwise.node2 –
Point
object representing the location of one vertices on the target fault segment. Note, the order should be clockwise.node3 –
Point
object representing the location of one vertices on the target fault segment. Note, the order should be clockwise.hypocenter –
Point
object representing the location of floating hypocenter on each segment calculation. In the method, we take the direction point of the previous fault patch as hypocentre for the current fault patch.reference –
Point
object representing the location of reference point for projectionpp – the projection of the site onto the plane containing the fault slipped area. A numpy array.
- Returns
Pd, a numpy array, representing the location of direction point E, the distance from direction point to hypocentre. go_next_patch, flag indicates if the calculation goes on the next fault patch. 1: yes, 0: no.
- openquake.hazardlib.near_fault.get_plane_equation(p0, p1, p2, reference)[source]¶
Define the equation of target fault plane passing through 3 given points which includes two points on the fault trace and one point on the fault plane but away from the fault trace. Note: in order to remain the consistency of the fault normal vector direction definition, the order of the three given points is strickly defined.
- Parameters
p0 – The fault trace and is the closer points from the starting point of fault trace.
Point
object representing the location of the one vertex of the fault patch.p1 – The fault trace and is the further points from the starting point of fault trace.
Point
object representing the location of the one vertex of the fault patch.p2 – The point on the fault plane but away from the fault trace.
Point
object representing the location of the one vertex of the fault patch.reference –
Point
object representing the origin of the cartesian system used the represent objects in a projected reference
- Returns
normal: normal vector of the plane (a,b,c) dist_to_plane: d in the plane equation, ax + by + cz = d
- openquake.hazardlib.near_fault.get_xyz_from_ll(projected, reference)[source]¶
This method computes the x, y and z coordinates of a set of points provided a reference point
- openquake.hazardlib.near_fault.isochone_ratio(e, rd, r_hyp)[source]¶
Get the isochone ratio as described in Spudich et al. (2013) PEER report, page 88.
- Parameters
e – a float defining the E-path length, which is the distance from Pd(direction) point to hypocentre. In km.
rd – float, distance from the site to the direct point.
r_hyp – float, the hypocentre distance.
- Returns
c_prime, a float defining the isochone ratio
- openquake.hazardlib.near_fault.projection_pp(site, normal, dist_to_plane, reference)[source]¶
This method finds the projection of the site onto the plane containing the slipped area, defined as the Pp(i.e. ‘perpendicular projection of site location onto the fault plane’ Spudich et al. (2013) - page 88) given a site.
- Parameters
site – Location of the site, [lon, lat, dep]
normal – Normal to the plane including the fault patch, describe by a normal vector[a, b, c]
dist_to_plane – D in the plane equation, ax + by + cz = d
reference –
Point
object representing the location of project reference point
- Returns
pp, the projection point, [ppx, ppy, ppz], in xyz domain , a numpy array.
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:
collections.abc.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_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
fnames – list of source model files
converter – a
openquake.hazardlib.sourceconverter.SourceConverter
instance
- 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.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
fmt – format used for writing the floats (default ‘%.7E’)
gml – add the http://www.opengis.net/gml namespace
xmlns – NRML namespace like http://openquake.org/xmlns/nrml/0.4
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)
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 ]>
- combine(other, rlz_groups)[source]¶
Update a ProbabilityCurve with shape (L, R) with a pcurve with shape (L, G), being G the number of realization groups, which are list of integers in the range 0..R-1.
- 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)
- fill(value)[source]¶
- Parameters
value – a scalar probability
Fill the ProbabilityMap underlying array with the given scalar and build the .sidx array
- property sidx¶
- Returns
an array of length N site_id -> index
- openquake.hazardlib.probability_map.update_pmap_i(arr, poes, inv, rates, probs_occur, 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
orz2pt5
is zero or negative.
Note
Sites
are pickleable
- class openquake.hazardlib.site.SiteCollection(sites)[source]¶
Bases:
object
- 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
- count_close(location, distance)[source]¶
- Returns
the number of sites within the distance from the location
- 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 inmask
areTrue
, in which case this site collection is returned, or if all the values inmask
areFalse
, in which case method returnsNone
. 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_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’]
- 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
- split(ntiles)[source]¶
- Parameters
ntiles – number of tiles to generate (rounded if float)
- Returns
self if there are <=1 tiles, otherwise the tiles
- 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
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=())[source]¶
Bases:
openquake.hazardlib.sourceconverter.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_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_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.
oropenquake.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_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
- 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:
there is a single simpleFaultGeometry node; returns a
openquake.hazardlib.geo.simpleFaultSurface
instancethere is a single complexFaultGeometry node; returns a
openquake.hazardlib.geo.complexFaultSurface
instancethere is a single griddedSurface node; returns a
openquake.hazardlib.geo.GriddedSurface
instancethere is either a single planarSurface or a list of planarSurface nodes; returns a
openquake.hazardlib.geo.PlanarSurface
instance or aopenquake.hazardlib.geo.MultiSurface
instancethere is either a single kiteSurface or a list of kiteSurface nodes; returns a
openquake.hazardlib.geo.KiteSurface
instance or aopenquake.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
- 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=())[source]¶
Bases:
openquake.hazardlib.sourceconverter.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.
oropenquake.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_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
- 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:
collections.abc.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
- 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.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)]
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_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
line – Line as instance of
openquake.hazardlib.geo.line.Line
with_depth (bool) – Include the depth values (True) or not (False):
- 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_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_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.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)[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)
- 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)
- 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.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 probabilitypoes
, does not cause any exceedance in the time window specified by thetime_span
parameter given in the constructor.
- class openquake.hazardlib.tom.ClusterPoissonTOM(time_span, occurrence_rate)[source]¶
Bases:
openquake.hazardlib.tom.PoissonTOM
Poissonian temporal occurrence model with an occurrence rate
- class openquake.hazardlib.tom.FatedTOM(time_span)[source]¶
Bases:
openquake.hazardlib.tom.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 probabilitypoes
, does not cause any exceedance in the time window specified by thetime_span
parameter given in the constructor.
- class openquake.hazardlib.tom.NegativeBinomialTOM(time_span, mu, alpha)[source]¶
Bases:
openquake.hazardlib.tom.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’stime_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 thefunc
.
- 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:
openquake.hazardlib.tom.BaseTOM
Poissonian temporal occurrence model.
- get_probability_n_occurrences(occurrence_rate, num)[source]¶
Calculate the probability of occurrence of
num
events in the constructor’stime_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 thefunc
.
- 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 2D or 4D
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:
openquake.hazardlib.valid.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 = {}¶
- kwargs = {}¶
- 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.
- params = {}¶
- 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)
- 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.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.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.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