openquake.risklib package

openquake.risklib.riskinput module

class openquake.risklib.riskinput.AssetCollection(assets_by_site, cost_calculator, time_event, time_events='')[source]

Bases: object

D = 11
I = 16
R = 12
Returns:numpy array of lists with the assets by each site
static build_asset_collection(assets_by_site, time_event=None)[source]
  • assets_by_site – a list of lists of assets
  • time_event – a time event string (or None)

two arrays assetcol and taxonomies

Returns:a composite array of asset values by loss type
class openquake.risklib.riskinput.CompositeRiskModel(oqparam, rmdict, retrodict)[source]

Bases: _abcoll.Mapping

A container (imt, taxonomy) -> riskmodel

gen_outputs(riskinput, monitor, assetcol=None)[source]

Group the assets per taxonomy and compute the outputs by using the underlying riskmodels. Yield the outputs generated as dictionaries out_by_lr.

  • riskinput – a RiskInput instance
  • monitor – a monitor object used to measure the performance
  • assetcol – not None only for event based risk
Returns:a 1-dimensional composite array with loss ratios by loss type
class openquake.risklib.riskinput.GmfDataGetter(gmf_data, grp_id, rlzs_by_gsim, start=0, stop=None)[source]

Bases: openquake.risklib.riskinput.GmfGetter

Extracts a dictionary of GMVs from the datastore

classmethod gen_gmfs(gmf_data, rlzs_assoc, eid=None)[source]

Yield GMF records


Yield gmv records from the datastore, if present

class openquake.risklib.riskinput.GmfGetter(grp_id, rlzs_by_gsim, ebruptures, sitecol, imts, min_iml, truncation_level, correlation_model, samples)[source]

Bases: object

An hazard getter with methods .gen_gmv and .get_hazard returning ground motion values.


Compute the GMFs for the given realization and populate the .gmdata array. Yields tuples of the form (sid, eid, imti, gmv).

get_hazard(gsim, data=None)[source]
  • gsim – a GSIM instance
  • data – if given, an iterator of records of dtype gmf_data_dt

an array (rlzi, sid, imti) -> array(gmv, eid)


Initialize the computers. Should be called on the workers

class openquake.risklib.riskinput.HazardGetter(kind, grp_id, rlzs_by_gsim, hazards_by_rlz, sids, imts)[source]

Bases: object

  • kind – kind of HazardGetter; can be ‘poe’ or ‘gmf’
  • grp_id – source group ID
  • rlzs_by_gsim – a dictionary gsim -> realizations for that GSIM
  • hazards_by_rlz – a nested dictionary rlz -> imt -> PoE array or a flat dictionary rlz -> GMF array of shape (N, I, E)
  • imts – a list of IMT strings
Params sids:

array of site IDs of interest

Parameters:gsim – a GSIM instance
Returns:a list of dictionaries (num_sites, num_imts)
class openquake.risklib.riskinput.LossRatiosGetter(dstore)[source]

Bases: object

Read loss ratios from the datastore for all realizations or for a specific realization.

Parameters:dstore – a DataStore instance
get(aids, rlzi)[source]
  • aids – a list of A asset ordinals
  • rlzi – a realization ordinal

a dictionary aid -> list of loss ratios

Parameters:aids – a list of A asset ordinals
Returns:a list of A composite arrays of dtype lrs_dt
class openquake.risklib.riskinput.Output(loss_types, assets, values, sid, rlzi)[source]

Bases: object

A container for the losses of the assets on the given site ID for the given realization ordinal.

class openquake.risklib.riskinput.RiskInput(hazard_getter, assets_by_site, eps_dict)[source]

Bases: object

Contains all the assets and hazard values associated to a given imt and site.

  • hazard_getter – a callable returning the hazard data for a given realization
  • assets_by_site – array of assets, one per site
  • eps_dict – dictionary of epsilons
Parameters:asset_ordinals – list of ordinals of the assets
Returns:a closure returning an array of epsilons from the event IDs

Return a list of pairs (imt, taxonomies) with a single element


Returns the realizations contained in the riskinput object.

class openquake.risklib.riskinput.RiskInputFromRuptures(hazard_getter, epsilons=None)[source]

Bases: object

Contains all the assets associated to the given IMT and a subsets of the ruptures for a given calculation.

Parameters:hazard_getter – a callable returning the hazard data for a given realization
Params epsilons:
 a matrix of epsilons (or None)
Parameters:asset_ordinals – ordinals of the assets
Returns:a closure returning an array of epsilons from the event IDs

Returns the realizations contained in the riskinput object.

exception openquake.risklib.riskinput.ValidationError[source]

Bases: exceptions.Exception

openquake.risklib.riskinput.get_refs(assets, hdf5path)[source]

Debugging method returning the string IDs of the assets from the datastore


Returns the realizations contained in the riskinput object.

openquake.risklib.riskinput.make_eps(assetcol, num_samples, seed, correlation)[source]
  • assetcol – an AssetCollection instance
  • num_samples (int) – the number of ruptures
  • seed (int) – a random seed
  • correlation (float) – the correlation coefficient

epsilons matrix of shape (num_assets, num_samples)

Parameters:dstore – a DataStore instance
Returns:a CompositeRiskModel instance
openquake.risklib.riskinput.rsi2str(rlzi, sid, imt)[source]

Convert a triple (XXXX, YYYY, ZZZ) into a string of the form ‘rlz-XXXX/sid-YYYY/ZZZ’


Convert a string of the form ‘rlz-XXXX/sid-YYYY/ZZZ’ into a triple (XXXX, YYYY, ZZZ)

openquake.risklib.riskmodels module

class openquake.risklib.riskmodels.Asset(asset_id, taxonomy, number, location, values, area=1, deductibles=None, insurance_limits=None, retrofitteds=None, calc=<CostCalculator {'units': {'structural': 'EUR'}, 'deduct_abs': True, 'area_types': {'structural': 'per_asset'}, 'limit_abs': True, 'cost_types': {'structural': 'per_area'}}>, ordinal=None)[source]

Bases: object

Describe an Asset as a collection of several values. A value can represent a replacement cost (e.g. structural cost, business interruption cost) or another quantity that can be considered for a risk analysis (e.g. occupants).

Optionally, a Asset instance can hold also a collection of deductible values and insured limits considered for insured losses calculations.

Returns:the deductible fraction of the asset cost for loss_type
Returns:the limit fraction of the asset cost for loss_type
retrofitted(loss_type, time_event=None)[source]
Returns:the asset retrofitted value for loss_type
value(loss_type, time_event=None)[source]
Returns:the total asset value for loss_type
class openquake.risklib.riskmodels.Classical(taxonomy, vulnerability_functions, hazard_imtls, lrem_steps_per_interval, conditional_loss_poes, poes_disagg, insured_losses=False)[source]

Bases: openquake.risklib.riskmodels.RiskModel

Classical PSHA-Based RiskModel. Computes loss curves and insured curves.

kind = 'vulnerability'
class openquake.risklib.riskmodels.ClassicalBCR(taxonomy, vulnerability_functions_orig, vulnerability_functions_retro, hazard_imtls, lrem_steps_per_interval, interest_rate, asset_life_expectancy)[source]

Bases: openquake.risklib.riskmodels.RiskModel

kind = 'vulnerability'
class openquake.risklib.riskmodels.ClassicalDamage(taxonomy, fragility_functions, hazard_imtls, investigation_time, risk_investigation_time)[source]

Bases: openquake.risklib.riskmodels.Damage

Implements the ClassicalDamage riskmodel. Computes the damages.

kind = 'fragility'
class openquake.risklib.riskmodels.CostCalculator(cost_types, area_types, units, deduct_abs=True, limit_abs=True)[source]

Bases: object

Return the value of an asset for the given loss type depending on the cost types declared in the exposure, as follows:

case 1: cost type: aggregated:
cost = economic value
case 2: cost type: per asset:
cost * number (of assets) = economic value
case 3: cost type: per area and area type: aggregated:
cost * area = economic value
case 4: cost type: per area and area type: per asset:
cost * area * number = economic value

The same “formula” applies to retrofitting cost.

class openquake.risklib.riskmodels.Damage(taxonomy, fragility_functions)[source]

Bases: openquake.risklib.riskmodels.RiskModel

Implements the ScenarioDamage riskmodel. Computes the damages.

kind = 'fragility'
class openquake.risklib.riskmodels.ProbabilisticEventBased(taxonomy, vulnerability_functions, loss_curve_resolution, conditional_loss_poes, insured_losses=False)[source]

Bases: openquake.risklib.riskmodels.RiskModel

Implements the Probabilistic Event Based riskmodel. Computes loss ratios and event IDs.

kind = 'vulnerability'
class openquake.risklib.riskmodels.RiskModel(taxonomy, risk_functions)[source]

Bases: object

Base class. Can be used in the tests as a mock.

compositemodel = None
Parameters:imt – Intensity Measure Type string
Returns:loss types with risk functions of the given imt
kind = None

The list of loss types in the underlying vulnerability functions, in lexicographic order

time_event = None
class openquake.risklib.riskmodels.Scenario(taxonomy, vulnerability_functions, insured_losses, time_event=None)[source]

Bases: openquake.risklib.riskmodels.RiskModel

Implements the Scenario riskmodel. Computes the loss matrix.

kind = 'vulnerability'
openquake.risklib.riskmodels.get_riskmodel(taxonomy, oqparam, **extra)[source]

Return an instance of the correct riskmodel class, depending on the attribute calculation_mode of the object oqparam.

  • 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.riskmodels.get_values(loss_type, assets, time_event=None)[source]
Returns:a numpy array with the values for the given assets, depending on the loss_type.
openquake.risklib.riskmodels.rescale(curves, values)[source]

Multiply the losses in each curve of kind (losses, poes) by the corresponding value.

openquake.risklib.scientific module

This module includes the scientific API of the oq-risklib

class openquake.risklib.scientific.BetaDistribution[source]

Bases: openquake.risklib.scientific.Distribution

sample(means, _covs, stddevs, _idxs=None)[source]
survival(loss_ratio, mean, stddev)[source]
class openquake.risklib.scientific.ConsequenceFunction(id, dist, params)

Bases: tuple


Alias for field number 1


Alias for field number 0


Alias for field number 2

class openquake.risklib.scientific.ConsequenceModel(id, assetCategory, lossCategory, description, limitStates)[source]

Bases: dict

Container for a set of consequence functions. You can access each function given its name with the square bracket notation.

  • 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
  • consequence_functions – a dictionary name -> ConsequenceFunction
class openquake.risklib.scientific.CurveBuilder(cbs, insured_losses, conditional_loss_poes=())[source]

Bases: object

Build curves for all loss types at the same time.

  • cbs – a list of LossTypeCurveBuilder instances
  • insured_losses – insured losses flag from the job.ini
  • conditional_loss_poes – list of PoEs from the job.ini
build_all_poes(aids, loss_ratios, rlzs)[source]
  • aids – a list of asset IDs
  • loss_ratios – a list of loss ratios
  • rlzs – a list of realizations

a matrix of shape (A, R) of PoEs

build_curves(assets, loss_ratios)[source]
  • assets – a list of assets
  • loss_ratios – a list of dictionaries aid -> loss ratios

A curves of dtype loss_curve_dt

build_maps(assets, getter, rlzs, stats, mon)[source]

aids, loss_maps, loss_maps_stats

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.

sample(means, _covs, _stddev, _idxs)[source]
survival(loss_ratio, mean, _stddev)[source]
class openquake.risklib.scientific.DiscreteDistribution[source]

Bases: openquake.risklib.scientific.Distribution

sample(loss_ratios, probs)[source]
seed = None
survival(loss_ratios, probs)[source]

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

sample(means, covs, stddevs, idxs)[source]

sample a set of losses

  • means – an array of mean losses
  • covs – an array of covariances
  • stddevs – an array of stddevs
survival(loss_ratio, mean, stddev)[source]

Return the survival function of the distribution with mean and stddev applied to loss_ratio

class openquake.risklib.scientific.FragilityFunctionContinuous(limit_state, mean, stddev)[source]

Bases: object

class openquake.risklib.scientific.FragilityFunctionDiscrete(limit_state, imls, poes, no_damage_limit=None)[source]

Bases: object

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.


For compatibility with vulnerability functions

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.

  • 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
build(continuous_fragility_discretization, steps_per_interval)[source]

Return a new FragilityModel instance, in which the values have been replaced with FragilityFunctionList instances.

  • continuous_fragility_discretization – configuration parameter
  • steps_per_interval – configuration parameter
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
sample(means, covs, _stddevs, idxs)[source]
survival(loss_ratio, mean, stddev)[source]
class openquake.risklib.scientific.LossTypeCurveBuilder(loss_type, curve_resolution, loss_ratios, ses_ratio, user_provided, conditional_loss_poes=(), insured_losses=False)[source]

Bases: object

Build loss ratio curves. The loss ratios can be provided by the user or automatically generated (user_provided=False). The usage is something like this:

builder = LossTypeCurveBuilder(loss_type, loss_ratios, ses_ratio,
counts = builder.build_counts(loss_matrix)
Parameters:losses – array of length E
Returns:curve of dtype agg_curve_dt
class openquake.risklib.scientific.VulnerabilityFunction(vf_id, imt, imls, mean_loss_ratios, covs=None, distribution='LN')[source]

Bases: object

dtype = dtype([('iml', '<f4'), ('loss_ratio', '<f4'), ('cov', '<f4')])
Parameters:gmvs – array of intensity measure levels
Returns:(interpolated loss ratios, interpolated covs, indices > min)
loss_ratio_exceedance_matrix = <functools.partial object>
mean_imls = <functools.partial object>

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

Sample the epsilons and apply the corrections to the means. This method is called only if there are nonzero covs.

  • means – array of E’ loss ratios
  • covs – array of E’ floats
  • idxs – array of E booleans with E >= E’
  • epsilons – array of E floats

array of E’ loss ratios

Returns:a new vulnerability function that is strictly increasing. It is built by removing piece of the function where the mean loss ratio is constant.
class openquake.risklib.scientific.VulnerabilityFunctionWithPMF(vf_id, imt, imls, loss_ratios, probs, seed=42)[source]

Bases: openquake.risklib.scientific.VulnerabilityFunction

Vulnerability function with an explicit distribution of probabilities

  • 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)
Parameters:gmvs – array of intensity measure levels
Returns:(interpolated probabilities, None, indices > min)
loss_ratio_exceedance_matrix = <functools.partial object>
sample(probs, _covs, idxs, epsilons)[source]

Sample the epsilons and applies the corrections to the probabilities. This method is called only if there are epsilons.

  • 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

array of E’ probabilities

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.

  • 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]
  • poe – hazard probability of exceedence
  • t_haz – hazard investigation time

Given a loss curve with poes over losses defined on a given time span it computes the average loss on this 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)


  • 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_dtypes(curve_resolution, conditional_loss_poes, insured=False)[source]

Returns loss_curve_dt and loss_maps_dt

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.

  • ff – a fragility function object
  • continuous_fragility_discretization – .ini file parameter
  • steps_per_interval – .ini file parameter

generated imls

openquake.risklib.scientific.build_loss_dtypes(curve_resolution, conditional_loss_poes, insured_losses=False)[source]
  • curve_resolution – dictionary loss_type -> curve_resolution
  • conditional_loss_poes – configuration parameter
  • insured_losses – configuration parameter

loss_curve_dt and loss_maps_dt

openquake.risklib.scientific.build_poes(counts, nses)[source]
  • counts – an array of counts of exceedence for the bins
  • nses – number of stochastic event sets

an array of PoEs

openquake.risklib.scientific.classical(vulnerability_function, hazard_imls, hazard_poes, steps=10)[source]
  • 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
  • steps (int) – Number of steps between loss ratios.
openquake.risklib.scientific.classical_damage(fragility_functions, hazard_imls, hazard_poes, investigation_time, risk_investigation_time)[source]
  • 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

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:

  1. If probability is in poes it takes the bigger corresponding loss_ratios.
  2. If it is in (poe1, poe2) where both poe1 and poe2 are in poes, then we perform a linear interpolation on the corresponding losses
  3. if the given probability is smaller than the lowest PoE defined, it returns the max loss ratio .
  4. if the given probability is greater than the highest PoE defined it returns zero.
  • 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.fine_graining(points, steps)[source]
  • 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

  • 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]
  • 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]
  • curves – an array of loss curves
  • conditional_loss_poes – a list of conditional loss poes

a composite array of loss maps with the same shape

openquake.risklib.scientific.make_epsilons(matrix, seed, correlation)[source]

Given a matrix N * R returns a matrix of the same shape N * R obtained by applying the multivariate_normal distribution to N points and R samples, by starting from the given seed and correlation.


Given an N x M matrix, returns mean and std computed on the rows, i.e. two M-dimensional vectors.


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

Differences between a value and the next value in a sequence


Averages between a value and the next value in a sequence

openquake.risklib.scientific.scenario_damage(fragility_functions, gmv)[source]

Compute the damage state fractions for the given ground motion value. Return am array of M values where M is the numbers of damage states.

openquake.risklib.utils module

class openquake.risklib.utils.memoized(func)[source]

Bases: object

Minimalistic memoizer decorator

openquake.risklib.utils.numpy_map(f, *args)[source]

s -> (s0,s1), (s1,s2), (s2, s3), ...

Module contents