openquake.risklib package¶
openquake.risklib.riskinput module¶
-
class
openquake.risklib.riskinput.
RiskInput
(hazard_getter, assets)[source]¶ Bases:
object
Contains all the assets and hazard values associated to a given imt and site.
Parameters: - hazard_getter – a callable returning the hazard data for a given realization
- assets_by_site – array of assets, one per site
-
openquake.risklib.riskinput.
cache_epsilons
(dstore, oq, assetcol, crmodel, E)[source]¶ Do nothing if there are no coefficients of variation of ignore_covs is set. Otherwise, generate an epsilon matrix of shape (A, E) and save it in the cache file, by returning the path to it.
-
openquake.risklib.riskinput.
get_assets_by_taxo
(assets, tempname=None)[source]¶ Parameters: - assets – an array of assets
- tempname – hdf5 file where the epsilons are (or None)
Returns: assets_by_taxo with attributes eps and idxs
-
openquake.risklib.riskinput.
get_output
(crmodel, assets_by_taxo, haz, rlzi=None)[source]¶ Parameters: - assets_by_taxo – a dictionary taxonomy index -> assets on a site
- haz – an array or a dictionary of hazard on that site
- rlzi – if given, a realization index
Returns: an ArrayWrapper loss_type -> array of shape (A, …)
-
openquake.risklib.riskinput.
make_eps
(asset_array, num_samples, seed, correlation)[source]¶ Parameters: - asset_array – an array of assets
- num_samples (int) – the number of ruptures
- seed (int) – a random seed
- correlation (float) – the correlation coefficient
Returns: epsilons matrix of shape (num_assets, num_samples)
openquake.risklib.riskmodels module¶
-
class
openquake.risklib.riskmodels.
CompositeRiskModel
(oqparam, risklist, consdict=())[source]¶ Bases:
collections.abc.Mapping
A container (riskid, kind) -> riskmodel
Parameters: - oqparam – an
openquake.commonlib.oqvalidation.OqParam
instance - fragdict – a dictionary riskid -> loss_type -> fragility functions
- vulndict – a dictionary riskid -> loss_type -> vulnerability function
- consdict – a dictionary riskid -> loss_type -> consequence functions
-
asset_damage_dt
(float_dmg_dist)[source]¶ Returns: a list [(‘aid’, U32), (‘eid’, U32), (‘lid’, U8), (‘moderate_0’, U32), …]
-
compute_csq
(asset, fractions, loss_type)[source]¶ Parameters: - asset – asset record
- fractions – array of probabilies of shape (E, D)
- loss_type – loss type as a string
Returns: a dict consequence_name -> array of length E
-
get_rmodels_weights
(loss_type, taxidx)[source]¶ Returns: a list of weighted risk models for the given taxonomy index
-
classmethod
read
(dstore, oqparam)[source]¶ Parameters: dstore – a DataStore instance Returns: a CompositeRiskModel
instance
-
reduce
(taxonomies)[source]¶ Parameters: taxonomies – a set of taxonomies Returns: a new CompositeRiskModel reduced to the given taxonomies
-
reduce_cons_model
(tagcol)[source]¶ Convert the dictionaries tag -> coeffs in the consequence model into dictionaries tag index -> coeffs (one per cname)
-
taxonomy_dict
¶ Returns: a dict taxonomy string -> taxonomy index
- oqparam – an
-
class
openquake.risklib.riskmodels.
RiskFuncList
[source]¶ Bases:
list
A list of risk functions with attributes .id, .loss_type, .kind
-
class
openquake.risklib.riskmodels.
RiskModel
(calcmode, taxonomy, risk_functions, **kw)[source]¶ Bases:
object
Base class. Can be used in the tests as a mock.
Parameters: - taxonomy – a taxonomy string
- risk_functions – a dict (loss_type, kind) -> risk_function
-
classical_bcr
(loss_type, assets, hazard, eids=None, eps=None)[source]¶ Parameters: - loss_type – the loss type
- assets – a list of N assets of the same taxonomy
- hazard – an hazard curve
- _eps – dummy parameter, unused
- _eids – dummy parameter, unused
Returns: a list of triples (eal_orig, eal_retro, bcr_result)
-
classical_damage
(loss_type, assets, hazard_curve, eids=None, eps=None)[source]¶ Parameters: - loss_type – the loss type
- assets – a list of N assets of the same taxonomy
- hazard_curve – an hazard curve array
Returns: an array of N x D elements
where N is the number of points and D the number of damage states.
-
classical_risk
(loss_type, assets, hazard_curve, eids=None, eps=None)[source]¶ Parameters: - loss_type (str) – the loss type considered
- assets – assets is an iterator over A
openquake.risklib.scientific.Asset
instances - hazard_curve – an array of poes
- eids – ignored, here only for API compatibility with other calculators
- eps – ignored, here only for API compatibility with other calculators
Returns: a composite array (loss, poe) of shape (A, C)
-
compositemodel
= None¶
-
ebrisk
(loss_type, assets, gmvs, eids, epsilons)¶ Returns: an array of shape (A, E)
-
event_based_damage
(loss_type, assets, gmvs, eids=None, eps=None)¶ Parameters: - loss_type – the loss type
- assets – a list of A assets of the same taxonomy
- gmvs – an array of E ground motion values
- eids – an array of E event IDs
- eps – dummy parameter, unused
Returns: an array of shape (A, E, D) elements
where N is the number of points, E the number of events and D the number of damage states.
-
loss_types
¶ The list of loss types in the underlying vulnerability functions, in lexicographic order
-
scenario
(loss_type, assets, gmvs, eids, epsilons)¶ Returns: an array of shape (A, E)
-
scenario_damage
(loss_type, assets, gmvs, eids=None, eps=None)[source]¶ Parameters: - loss_type – the loss type
- assets – a list of A assets of the same taxonomy
- gmvs – an array of E ground motion values
- eids – an array of E event IDs
- eps – dummy parameter, unused
Returns: an array of shape (A, E, D) elements
where N is the number of points, E the number of events and D the number of damage states.
-
scenario_risk
(loss_type, assets, gmvs, eids, epsilons)¶ Returns: an array of shape (A, E)
-
time_event
= None¶
-
openquake.risklib.riskmodels.
build_vf_node
(vf)[source]¶ Convert a VulnerabilityFunction object into a Node suitable for XML conversion.
-
openquake.risklib.riskmodels.
get_risk_files
(inputs)[source]¶ Parameters: inputs – a dictionary key -> path name Returns: a pair (file_type, {risk_type: path})
-
openquake.risklib.riskmodels.
get_risk_functions
(oqparam, kind='vulnerability fragility consequence vulnerability_retrofitted')[source]¶ Parameters: - oqparam – an OqParam instance
- kind – a space-separated string with the kinds of risk models to read
Returns: a list of risk functions
-
openquake.risklib.riskmodels.
get_riskmodel
(taxonomy, oqparam, **extra)[source]¶ Return an instance of the correct risk model class, depending on the attribute calculation_mode of the object oqparam.
Parameters: - taxonomy – a taxonomy string
- oqparam – an object containing the parameters needed by the RiskModel class
- extra – extra parameters to pass to the RiskModel class
openquake.risklib.scientific module¶
This module includes the scientific API of the oq-risklib
-
class
openquake.risklib.scientific.
AggLossTable
(dic=None, accum=None, keys=())[source]¶ Bases:
openquake.baselib.general.AccumDict
A dictionary of matrices of shape L’, with L’ the total number of loss types (primary + secondary). :param aggkey: a dictionary tuple -> integer :param loss_types: a list of primary loss types :param sec_losses: a list of SecondaryLosses (can be empty)
-
class
openquake.risklib.scientific.
ConsequenceModel
(id, assetCategory, lossCategory, description, limitStates)[source]¶ Bases:
dict
Dictionary of consequence functions. You can access each function given its name with the square bracket notation.
Parameters: - id (str) – ID of the model
- assetCategory (str) – asset category (i.e. buildings, population)
- lossCategory (str) – loss type (i.e. structural, contents, …)
- description (str) – description of the model
- limitStates – a list of limit state strings
-
class
openquake.risklib.scientific.
CurveParams
(index, loss_type, curve_resolution, ratios, user_provided)¶ Bases:
tuple
-
curve_resolution
¶ Alias for field number 2
-
index
¶ Alias for field number 0
-
loss_type
¶ Alias for field number 1
-
ratios
¶ Alias for field number 3
-
user_provided
¶ Alias for field number 4
-
-
class
openquake.risklib.scientific.
DegenerateDistribution
[source]¶ Bases:
openquake.risklib.scientific.Distribution
The degenerate distribution. E.g. a distribution with a delta corresponding to the mean.
-
class
openquake.risklib.scientific.
DiscreteDistribution
[source]¶ Bases:
openquake.risklib.scientific.Distribution
-
seed
= None¶
-
-
class
openquake.risklib.scientific.
Distribution
[source]¶ Bases:
object
A Distribution class models continuous probability distribution of random variables used to sample losses of a set of assets. It is usually registered with a name (e.g. LN, BT, PM) by using
openquake.baselib.general.CallableDict
-
class
openquake.risklib.scientific.
FragilityFunctionContinuous
(limit_state, mean, stddev, minIML, maxIML, nodamage=0)[source]¶ Bases:
object
-
class
openquake.risklib.scientific.
FragilityFunctionDiscrete
(limit_state, imls, poes, no_damage_limit=None)[source]¶ Bases:
object
-
interp
¶
-
-
class
openquake.risklib.scientific.
FragilityFunctionList
(array, **attrs)[source]¶ Bases:
list
A list of fragility functions with common attributes; there is a function for each limit state.
-
class
openquake.risklib.scientific.
FragilityModel
(id, assetCategory, lossCategory, description, limitStates)[source]¶ Bases:
dict
Container for a set of fragility functions. You can access each function given the IMT and taxonomy with the square bracket notation.
Parameters: - id (str) – ID of the model
- assetCategory (str) – asset category (i.e. buildings, population)
- lossCategory (str) – loss type (i.e. structural, contents, …)
- description (str) – description of the model
- limitStates – a list of limit state strings
-
class
openquake.risklib.scientific.
InsuredLosses
(policy_name, policy_dict)[source]¶ Bases:
object
There is an insured loss for each loss type in the policy dictionary.
-
class
openquake.risklib.scientific.
LogNormalDistribution
(epsilons=None)[source]¶ Bases:
openquake.risklib.scientific.Distribution
Model a distribution of a random variable whoose logarithm are normally distributed.
Attr epsilons: An array of random numbers generated with numpy.random.multivariate_normal()
with size E
-
class
openquake.risklib.scientific.
LossCurvesMapsBuilder
(conditional_loss_poes, return_periods, loss_dt, weights, num_events, eff_time, risk_investigation_time)[source]¶ Bases:
object
Build losses curves and maps for all loss types at the same time.
Parameters: - conditional_loss_poes – a list of PoEs, possibly empty
- return_periods – ordered array of return periods
- loss_dt – composite dtype for the loss types
- weights – weights of the realizations
- num_events – number of events for each realization
- eff_time – ses_per_logic_tree_path * hazard investigation time
-
class
openquake.risklib.scientific.
VulnerabilityFunction
(vf_id, imt, imls, mean_loss_ratios, covs=None, distribution='LN')[source]¶ Bases:
object
-
dtype
= dtype([('iml', '<f8'), ('loss_ratio', '<f8'), ('cov', '<f8')])¶
-
interpolate
(gmvs)[source]¶ Parameters: gmvs – array of intensity measure levels Returns: (interpolated loss ratios, interpolated covs, indices > min)
-
mean_imls
[source]¶ Compute the mean IMLs (Intensity Measure Level) for the given vulnerability function.
Parameters: vulnerability_function – the vulnerability function where the IMLs (Intensity Measure Level) are taken from.
-
mean_loss_ratios_with_steps
(steps)[source]¶ Split the mean loss ratios, producing a new set of loss ratios. The new set of loss ratios always includes 0.0 and 1.0
Parameters: steps (int) – the number of steps we make to go from one loss ratio to the next. For example, if we have [0.5, 0.7]:
steps = 1 produces [0.0, 0.5, 0.7, 1] steps = 2 produces [0.0, 0.25, 0.5, 0.6, 0.7, 0.85, 1] steps = 3 produces [0.0, 0.17, 0.33, 0.5, 0.57, 0.63, 0.7, 0.8, 0.9, 1]
-
sample
(means, covs, idxs, epsilons=None)[source]¶ Sample the distribution and apply the corrections to the means. This method is called only if there are nonzero covs.
Parameters: - means – array of E’ loss ratios
- covs – array of E’ floats
- idxs – array of E booleans with E >= E’
- epsilons – array of E floats (or None)
Returns: array of E’ loss ratios
-
seed
= None¶
-
-
class
openquake.risklib.scientific.
VulnerabilityFunctionWithPMF
(vf_id, imt, imls, loss_ratios, probs)[source]¶ Bases:
openquake.risklib.scientific.VulnerabilityFunction
Vulnerability function with an explicit distribution of probabilities
Parameters: - vf_id (str) – vulnerability function ID
- imt (str) – Intensity Measure Type
- imls – intensity measure levels (L)
- ratios – an array of mean ratios (M)
- probs – a matrix of probabilities of shape (M, L)
-
interpolate
(gmvs)[source]¶ Parameters: gmvs – array of intensity measure levels Returns: (interpolated probabilities, zeros, indices > min)
-
loss_ratio_exceedance_matrix
[source]¶ Compute the LREM (Loss Ratio Exceedance Matrix). Required for the Classical Risk and BCR Calculators. Currently left unimplemented as the PMF format is used only for the Scenario and Event Based Risk Calculators.
Parameters: steps (int) – Number of steps between loss ratios.
-
sample
(probs, _covs, idxs, epsilons)[source]¶ Sample the .loss_ratios with the given probabilities.
Parameters: - probs – array of E’ floats
- _covs – ignored, it is there only for API consistency
- idxs – array of E booleans with E >= E’
- epsilons – array of E floats
Returns: array of E’ probabilities
-
seed
= None¶
-
class
openquake.risklib.scientific.
VulnerabilityModel
(id=None, assetCategory=None, lossCategory=None)[source]¶ Bases:
dict
Container for a set of vulnerability functions. You can access each function given the IMT and taxonomy with the square bracket notation.
Parameters: - id (str) – ID of the model
- assetCategory (str) – asset category (i.e. buildings, population)
- lossCategory (str) – loss type (i.e. structural, contents, …)
All such attributes are None for a vulnerability model coming from a NRML 0.4 file.
-
openquake.risklib.scientific.
annual_frequency_of_exceedence
(poe, t_haz)[source]¶ Parameters: - poe – array of probabilities of exceedence
- t_haz – hazard investigation time
Returns: array of frequencies (with +inf values where poe=1)
-
openquake.risklib.scientific.
average_loss
(lc)[source]¶ Given a loss curve array with poe and loss fields, computes the average loss on a period of time.
Note: As the loss curve is supposed to be piecewise linear as it is a result of a linear interpolation, we compute an exact integral by using the trapeizodal rule with the width given by the loss bin width.
-
openquake.risklib.scientific.
bcr
(eal_original, eal_retrofitted, interest_rate, asset_life_expectancy, asset_value, retrofitting_cost)[source]¶ Compute the Benefit-Cost Ratio.
BCR = (EALo - EALr)(1-exp(-r*t))/(r*C)
Where:
- BCR – Benefit cost ratio
- EALo – Expected annual loss for original asset
- EALr – Expected annual loss for retrofitted asset
- r – Interest rate
- t – Life expectancy of the asset
- C – Retrofitting cost
-
openquake.risklib.scientific.
broadcast
(func, composite_array, *args)[source]¶ Broadcast an array function over a composite array
-
openquake.risklib.scientific.
build_imls
(ff, continuous_fragility_discretization, steps_per_interval=0)[source]¶ Build intensity measure levels from a fragility function. If the function is continuous, they are produced simply as a linear space between minIML and maxIML. If the function is discrete, they are generated with a complex logic depending on the noDamageLimit and the parameter steps per interval.
Parameters: - ff – a fragility function object
- continuous_fragility_discretization – .ini file parameter
- steps_per_interval – .ini file parameter
Returns: generated imls
-
openquake.risklib.scientific.
build_loss_curve_dt
(curve_resolution, insured_losses=False)[source]¶ Parameters: - curve_resolution – dictionary loss_type -> curve_resolution
- insured_losses – configuration parameter
Returns: loss_curve_dt
-
openquake.risklib.scientific.
classical
(vulnerability_function, hazard_imls, hazard_poes, loss_ratios)[source]¶ Parameters: - vulnerability_function – an instance of
openquake.risklib.scientific.VulnerabilityFunction
representing the vulnerability function used to compute the curve. - hazard_imls – the hazard intensity measure type and levels
- loss_ratios – a tuple of C loss ratios
Returns: an array of shape (2, C)
- vulnerability_function – an instance of
-
openquake.risklib.scientific.
classical_damage
(fragility_functions, hazard_imls, hazard_poes, investigation_time, risk_investigation_time, steps_per_interval=1, debug=False)[source]¶ Parameters: - fragility_functions – a list of fragility functions for each damage state
- hazard_imls – Intensity Measure Levels
- hazard_poes – hazard curve
- investigation_time – hazard investigation time
- risk_investigation_time – risk investigation time
- steps_per_interval – steps per interval
Returns: an array of M probabilities of occurrence where M is the numbers of damage states.
-
openquake.risklib.scientific.
conditional_loss_ratio
(loss_ratios, poes, probability)[source]¶ Return the loss ratio corresponding to the given PoE (Probability of Exceendance). We can have four cases:
- If probability is in poes it takes the bigger corresponding loss_ratios.
- If it is in (poe1, poe2) where both poe1 and poe2 are in poes, then we perform a linear interpolation on the corresponding losses
- if the given probability is smaller than the lowest PoE defined, it returns the max loss ratio .
- if the given probability is greater than the highest PoE defined it returns zero.
Parameters: - loss_ratios – an iterable over non-decreasing loss ratio values (float)
- poes – an iterable over non-increasing probability of exceedance values (float)
- probability (float) – the probability value used to interpolate the loss curve
-
openquake.risklib.scientific.
economic_losses
(coeffs, asset, dmgdist, loss_type)[source]¶ Parameters: - coeffs – coefficients per damage state
- asset – asset record
- dmgdist – an array of probabilies of shape (E, D - 1)
- loss_type – loss type string
Returns: array of economic losses of length E
-
openquake.risklib.scientific.
fine_graining
(points, steps)[source]¶ Parameters: - points – a list of floats
- steps (int) – expansion steps (>= 2)
>>> fine_graining([0, 1], steps=0) [0, 1] >>> fine_graining([0, 1], steps=1) [0, 1] >>> fine_graining([0, 1], steps=2) array([0. , 0.5, 1. ]) >>> fine_graining([0, 1], steps=3) array([0. , 0.33333333, 0.66666667, 1. ]) >>> fine_graining([0, 0.5, 0.7, 1], steps=2) array([0. , 0.25, 0.5 , 0.6 , 0.7 , 0.85, 1. ])
N points become S * (N - 1) + 1 points with S > 0
-
openquake.risklib.scientific.
insured_loss_curve
(curve, deductible, insured_limit)[source]¶ Compute an insured loss ratio curve given a loss ratio curve
Parameters: - curve – an array 2 x R (where R is the curve resolution)
- deductible (float) – the deductible limit in fraction form
- insured_limit (float) – the insured limit in fraction form
>>> losses = numpy.array([3, 20, 101]) >>> poes = numpy.array([0.9, 0.5, 0.1]) >>> insured_loss_curve(numpy.array([losses, poes]), 5, 100) array([[ 3. , 20. ], [ 0.85294118, 0.5 ]])
-
openquake.risklib.scientific.
insured_losses
(losses, deductible, insured_limit)[source]¶ Parameters: - losses – an array of ground-up loss ratios
- deductible (float) – the deductible limit in fraction form
- insured_limit (float) – the insured limit in fraction form
Compute insured losses for the given asset and losses, from the point of view of the insurance company. For instance:
>>> insured_losses(numpy.array([3, 20, 101]), 5, 100) array([ 0, 15, 95])
- if the loss is 3 (< 5) the company does not pay anything
- if the loss is 20 the company pays 20 - 5 = 15
- if the loss is 101 the company pays 100 - 5 = 95
-
openquake.risklib.scientific.
loss_maps
(curves, conditional_loss_poes)[source]¶ Parameters: - curves – an array of loss curves
- conditional_loss_poes – a list of conditional loss poes
Returns: a composite array of loss maps with the same shape
-
openquake.risklib.scientific.
losses_by_period
(losses, return_periods, num_events=None, eff_time=None)[source]¶ Parameters: - losses – array of simulated losses
- return_periods – return periods of interest
- num_events – the number of events (>= number of losses)
- eff_time – investigation_time * ses_per_logic_tree_path
Returns: interpolated losses for the return periods, possibly with NaN
NB: the return periods must be ordered integers >= 1. The interpolated losses are defined inside the interval min_time < time < eff_time where min_time = eff_time /num_events. On the right of the interval they have NaN values; on the left zero values. If num_events is not passed, it is inferred from the number of losses; if eff_time is not passed, it is inferred from the longest return period. Here is an example:
>>> losses = [3, 2, 3.5, 4, 3, 23, 11, 2, 1, 4, 5, 7, 8, 9, 13] >>> losses_by_period(losses, [1, 2, 5, 10, 20, 50, 100], 20) array([ 0. , 0. , 0. , 3.5, 8. , 13. , 23. ])
-
openquake.risklib.scientific.
make_epsilons
(matrix, seed, correlation)[source]¶ Given a matrix of shape (A, E) returns a matrix of the same shape obtained by applying the multivariate_normal distribution to A points and E samples, by starting from the given seed and correlation.
-
openquake.risklib.scientific.
mean_std
(fractions)[source]¶ Given an N x M matrix, returns mean and std computed on the rows, i.e. two M-dimensional vectors.
-
openquake.risklib.scientific.
normalize_curves_eb
(curves)[source]¶ A more sophisticated version of normalize_curves, used in the event based calculator.
Parameters: curves – a list of pairs (losses, poes) Returns: first losses, all_poes
-
openquake.risklib.scientific.
pairwise_diff
(values)[source]¶ Differences between a value and the next value in a sequence
-
openquake.risklib.scientific.
pairwise_mean
(values)[source]¶ Averages between a value and the next value in a sequence
-
openquake.risklib.scientific.
return_periods
(eff_time, num_losses)[source]¶ Parameters: - eff_time – ses_per_logic_tree_path * investigation_time
- num_losses – used to determine the minimum period
Returns: an array of 32 bit periods
Here are a few examples:
>>> return_periods(1, 1) Traceback (most recent call last): ... ValueError: eff_time too small: 1 >>> return_periods(2, 2) array([1, 2], dtype=uint32) >>> return_periods(2, 10) array([1, 2], dtype=uint32) >>> return_periods(100, 2) array([ 50, 100], dtype=uint32) >>> return_periods(1000, 1000) array([ 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000], dtype=uint32)