oasislmf.pytools.gulmc.manager¶
Ground-up loss Monte Carlo (gulmc) manager.
Jagged Array Naming Convention¶
<key_name>_ja_id_ind — optional sparse ID → dense index (id_index.py) <key_name>_ja_offsets — row boundaries: row i spans [offsets[i], offsets[i+1]) <key_name>_ja_<values> — one or more parallel flat arrays holding payload data
Two-level (nested) jagged arrays repeat the pattern on the payload: <key_name>_ja_<inner_key>_ja_offsets — L2 row boundaries <key_name>_ja_<inner_key>_ja_<values> — L2 payload data
Attributes¶
Functions¶
|
Validate a coverage-dependency configuration against the loaded model data (fail-loud). |
|
Execute the main gulmc workflow. |
|
Remove empty bucket from the end |
|
Write the cumulative distribution of |
|
Convolve the vulnerability pdf with the hazard pdf into an effective damage cdf. |
|
Return the longest parent chain length in the coverage dependency forest. |
|
|
|
Determine the tiv scaling factor to apply to gul values for a coverage. |
|
Bin a dynamic footprint areaperil's records for one item, summing the probability of the |
|
Copy an item's hazard intensity bin ids and probabilities into the per-item scratch buffers. |
|
Assemble the per-hazard-bin vulnerability pdf for an item. |
|
Compute or read from the cache an item's effective-damage CDF (and per-hazard-bin vuln CDFs). |
|
Draw the (optionally correlated) hazard and damage random values for one item. |
|
Write the per-sample gul (or debug random values) for one item into |
|
Compute ground-up losses for all coverages in a single event. |
|
Process areaperils in the footprint, filtering to those with vulnerability functions. |
|
Register each item to its coverage and prepare per-item event data for loss computation. |
Module Contents¶
- oasislmf.pytools.gulmc.manager.validate_coverage_dependency(items, vuln_idx_to_cond_idx)[source]¶
Validate a coverage-dependency configuration against the loaded model data (fail-loud).
A dependent item (
source_item_id > 0) is driven by its source item’s sampled damage bin through a conditional (damage-transition) vulnerability. This checks the invariants the gulmc kernel relies on, raising a clear error rather than silently producing wrong losses:a dependent must not use an aggregate vulnerability (the aggregate assembly path is not wired for the damage-bin-indexed conditional matrix);
a dependent must use a conditional vulnerability (present in conditional_vulnerability, i.e.
vuln_idx_to_cond_idx[vulnerability_idx] >= 0);an item with no source must NOT use a conditional vulnerability, since there is no source damage bin to index it with and the footprint hazard cannot sample it. An item with no source and a hazard-indexed vulnerability is simply computed independently — file generation leaves such items unpaired deliberately, because only the model’s static data says which vulnerabilities are conditional.
The source’s sampled damage bin is captured directly during sampling (not re-derived from a ratio), so a source coverage may use any damage type (relative / absolute / duration).
- Parameters:
items (np.ndarray) – items table (coverage_id, vulnerability_id, vulnerability_idx, areaperil_agg_vuln_idx, source_item_id).
vuln_idx_to_cond_idx (np.ndarray) – dense vuln idx -> conditional row, or -1 if not conditional.
- Raises:
OasisException – if any of the three invariants is violated.
- oasislmf.pytools.gulmc.manager.run(run_dir, ignore_file_type, sample_size, loss_threshold, alloc_rule, debug, random_generator, peril_filter=[], file_in=None, file_out=None, data_server=None, ignore_correlation=False, ignore_haz_correlation=False, effective_damageability=False, max_cached_vuln_cdf_size_MB=200, model_df_engine='oasis_data_manager.df_reader.reader.OasisPandasReader', dynamic_footprint=False, section_merge=None, **kwargs)[source]¶
Execute the main gulmc workflow.
- Parameters:
run_dir (str) – the directory of where the process is running
ignore_file_type (set(str)) – file extension to ignore when loading
sample_size (int) – number of random samples to draw.
loss_threshold (float) – threshold above which losses are printed to the output stream.
alloc_rule (int) – back-allocation rule.
debug (int) – for each random sample, print to the output stream the random loss (if 0), the random value used to draw the hazard intensity sample (if 1), the random value used to draw the damage sample (if 2). Defaults to 0.
random_generator (int) – random generator function id.
peril_filter (list[int], optional) – list of perils to include in the computation (if None, all perils will be included). Defaults to [].
file_in (str, optional) – filename of input stream. Defaults to None.
file_out (str, optional) – filename of output stream. Defaults to None.
data_server (bool, optional) – if True, run the data server. Defaults to None.
ignore_correlation (bool, optional) – if True, do not compute correlated random samples. Defaults to False.
ignore_haz_correlation (bool, optional) – if True, do not compute correlated hazard intensity samples. Defaults to False.
effective_damageability (bool, optional) – if True, it uses effective damageability to draw damage samples instead of using the full monte carlo approach (i.e., to draw hazard intensity first, then damage).
max_cached_vuln_cdf_size_MB (int, optional) – size in MB of the in-memory cache to store and reuse vulnerability cdf. Defaults to 200.
model_df_engine (str, optional) – The engine to use when loading model dataframes. Defaults to OasisPandasReader.
dynamic_footprint (bool, optional) – if True, load the dynamic footprint data and adjust hazard intensities at runtime. Defaults to False.
section_merge (str, optional) – how a dynamic footprint merges an areaperil’s intensities across the sections of one event (see Footprint.load). Defaults to None, the footprint’s default.
**kwargs – additional keyword arguments. socket_server (str) enables the progress pings (a gul_ready ping once the model is loaded, then events_complete counts) and, when numeric, gives the port to override; analysis_pk is reported with each ping.
- Raises:
ValueError – if alloc_rule is not 0, 1, 2, or 3.
ValueError – if alloc_rule is 1, 2, or 3 when debug is 1 or 2.
- Returns:
0 if no errors occurred.
- Return type:
- oasislmf.pytools.gulmc.manager.get_last_non_empty(cdf, bin_i)[source]¶
Remove empty bucket from the end
- Parameters:
cdf – cumulative distribution
bin_i – last valid bin index
- Returns:
last bin index with an increased in the cdf
- oasislmf.pytools.gulmc.manager.pdf_to_cdf(pdf, n_pdf, cdf)[source]¶
Write the cumulative distribution of
pdf[:n_pdf]intocdfand return its valid length.The cdf stops once it reaches 1 (to float32 precision) and drops trailing bins that add no probability, so the returned length can be shorter than
n_pdf. It returns a length rather than acdf[:n]slice so the per-item loop creates no array view (see the refcount note in common/event_stream.py).
- oasislmf.pytools.gulmc.manager.calc_eff_damage_cdf(vuln_pdf, haz_pdf, Nhaz_bins, eff_damage_cdf)[source]¶
Convolve the vulnerability pdf with the hazard pdf into an effective damage cdf.
- Parameters:
vuln_pdf (np.array[float]) – 2d vulnerability pdf; rows
[:Nhaz_bins]are used, one per hazard bin, columns are damage bins.haz_pdf (np.array[float]) – hazard probabilities;
[:Nhaz_bins]are used.Nhaz_bins (int) – number of hazard bins.
eff_damage_cdf (np.array[float]) – output buffer, at least
vuln_pdf.shape[1]long.
- Returns:
- valid length of the cdf written to
eff_damage_cdf(seepdf_to_cdffor why a length rather than a slice).
- valid length of the cdf written to
- Return type:
- oasislmf.pytools.gulmc.manager.compute_max_dependency_depth(coverage_source_id)[source]¶
Return the longest parent chain length in the coverage dependency forest.
Walks the parent links (
coverage_source_id) up from every coverage and returns the deepest chain found. Used to size the per-depth stacks that hold a source coverage’s result while its dependent subtree is computed.- Parameters:
coverage_source_id (np.ndarray) – parent coverage_id per coverage_id (0 = root).
- Returns:
the maximum dependency depth (number of ancestors) over all coverages.
- Return type:
- oasislmf.pytools.gulmc.manager.get_gul_from_vuln_cdf(vuln_rval, vuln_cdf, Ndamage_bins, damage_bins, bin_scaling, src_bin_out, out_i)[source]¶
- oasislmf.pytools.gulmc.manager.compute_damage_bin_scaling(damage_bins, Neff_damage_bins, tiv)[source]¶
Determine the tiv scaling factor to apply to gul values for a coverage.
The scaling depends on the damage type recorded in the last effective damage bin: relative functions scale by tiv, absolute by 1, duration converts annual tiv to daily, and the default path infers relative-vs-absolute from whether the last bin_to is <= 1.
A coverage with no tiv has no value at risk, so it yields no loss whatever the damage type. Relative and duration functions get that from their tiv factor, but absolute functions carry currency directly in the damage bins, so they need the zero explicitly (write_losses’ tiv split, which caps absolute losses at the tiv, is likewise skipped when tiv is 0). This only arises for a coverage dependency source retained with zero tiv (an uninsured building driving its insured contents): it must drive its dependents but report no loss of its own. The sampled damage bin and the effective damage cdf that do the driving are independent of this scaling.
- oasislmf.pytools.gulmc.manager.merge_dynamic_haz_records_per_bin(haz_pdf, haz_start, Nhaz_records, item, intensity_adjustment, intensity_bin_peril_ids, intensity_bins, bin_slot, haz_bin_id_out, haz_prob_out)[source]¶
Bin a dynamic footprint areaperil’s records for one item, summing the probability of the records that fall in the same intensity bin.
A dynamic footprint record holds a raw intensity, binned here because the item’s intensity_adjustment shifts it first. An areaperil lying in several sections of an event can hold many more records than the model has intensity bins, but all the per-hazard-bin work that follows (vulnerability rows, their CDFs, the CDF cache, sampling) depends on the bin alone. So the hazard axis is the bins the records fall in, never longer than the number of intensity bins, which the per-hazard-bin buffers and the CDF cache are sized on.
Entries are kept in the order of each bin’s first record. Records come largest intensity first and intensity_bins does not decrease with intensity, so the records of a bin are adjacent and the hazard CDF keeps its bin boundaries: a random number picks the same bin as unmerged.
- Parameters:
haz_pdf (np.array[haz_arr_type]) – hazard pdf records of all areaperils for the event.
haz_start (int) – index of the areaperil’s first record in
haz_pdf.Nhaz_records (int) – number of records of the areaperil.
item (np.void) – the item record (uses peril_id).
intensity_adjustment (int) – intensity shift applied before binning.
intensity_bin_peril_ids (np.array[int32]) – sorted unique encoded peril_ids.
intensity_bins (np.array[int32, 2d]) – [peril_idx, intensity_value] -> intensity_bin_id.
bin_slot (np.array[int64]) – scratch indexed by bin id, -1 everywhere on entry and on return.
haz_bin_id_out (np.array[int32]) – receives the bin id of each entry.
haz_prob_out (np.array[oasis_float]) – receives the summed probability of each entry.
- Returns:
the number of entries written.
- Return type:
- oasislmf.pytools.gulmc.manager.fill_haz_bins(haz_pdf, haz_start, Nhaz_records, item, intensity_adjustment, dynamic_footprint, intensity_bin_peril_ids, intensity_bins, bin_slot, haz_bin_id, haz_pdf_prob)[source]¶
Copy an item’s hazard intensity bin ids and probabilities into the per-item scratch buffers.
The item’s records are
haz_pdf[haz_start:haz_start + Nhaz_records], read by index and copied rather than sliced or field-viewed (see the refcount note in common/event_stream.py). With no dynamic footprint each record is one hazard entry, its bin id read from the hazard pdf. With a dynamic footprint the records are binned and merged per bin (merge_dynamic_haz_records_per_bin).- Parameters:
haz_pdf (np.array[haz_arr_type]) – hazard pdf records of all areaperils for the event.
haz_start (int) – index of this item’s first record in
haz_pdf.Nhaz_records (int) – number of records for this item.
item (np.void) – the item record (needs peril_id when dynamic footprint is active).
intensity_adjustment (int) – intensity shift to apply under a dynamic footprint.
dynamic_footprint (None or object) – None if no dynamic footprint, otherwise truthy.
intensity_bin_peril_ids (np.array[int32]) – sorted unique encoded peril_ids.
intensity_bins (np.array[int32, 2d]) – [peril_idx, intensity_value] -> intensity_bin_id.
bin_slot (np.array[int64]) – scratch for merge_dynamic_haz_records_per_bin.
haz_bin_id (np.array[int32]) – output, intensity bin id per hazard entry.
haz_pdf_prob (np.array[float]) – output, probability per hazard entry.
- Returns:
the number of hazard entries written.
- Return type:
- oasislmf.pytools.gulmc.manager.build_vuln_pdf(item, Nhaz_bins, haz_bin_id, vuln_array, Ndamage_bins_max, areaperil_agg_vuln_idx_ja_offsets, areaperil_agg_vuln_idx_ja_data, vuln_pdf_empty)[source]¶
Assemble the per-hazard-bin vulnerability pdf for an item.
For a single (non-aggregate) vulnerability the pdf is read straight out of
vuln_array. For an aggregate vulnerability the weighted sum of the member vulnerabilities is built from the jagged arrays; bins with no probability collapse to 100% no-loss in the first damage bin, and the result is normalised by the total weight. When no member has a positive weight, each counts once and the result is their plain average.The pdf is written to rows
[:Nhaz_bins]ofvuln_pdf_emptywith explicit loops rather than through views or row slices (see the refcount note in common/event_stream.py).- Parameters:
item (np.void) – the item record (uses areaperil_agg_vuln_idx / vulnerability_idx).
Nhaz_bins (int) – number of hazard bins for this item.
haz_bin_id (np.array) – intensity bin id per hazard record.
vuln_array (np.array[float]) – 3d vulnerability array (Nvulnerability, Ndamage_bins_max, Nintensity_bins).
Ndamage_bins_max (int) – maximum number of damage bins.
areaperil_agg_vuln_idx_ja_offsets (np.array[oasis_int]) – jagged array offsets.
areaperil_agg_vuln_idx_ja_data (np.array) – merged structured array with ‘vuln_idx’ and ‘weight’.
vuln_pdf_empty (np.array[float]) – output buffer of shape (>= Nhaz_bins, Ndamage_bins_max); rows
[:Nhaz_bins]are overwritten.
- oasislmf.pytools.gulmc.manager.resolve_item_cdfs(compute_info, cdf_group, do_calc_vuln_ptf, Nhaz_bins, item, haz_bin_id, haz_pdf_prob, vuln_array, areaperil_agg_vuln_idx_ja_offsets, areaperil_agg_vuln_idx_ja_data, cdf_cache_tag, cdf_cache_nbins, cdf_cache_mask, cached_vuln_cdfs, vuln_pdf_empty, eff_damage_cdf, haz_i_to_Ndamage_bins, haz_i_to_vuln_cdf, is_dependent, conditional_vuln_array, vuln_idx_to_cond_idx)[source]¶
Compute or read from the cache an item’s effective-damage CDF (and per-hazard-bin vuln CDFs).
On a cache miss the vulnerability pdf is (re)built, the effective damage CDF is computed and written to cache slot 0, and — when not running effective_damageability — each per-hazard-bin vulnerability CDF is computed and written to the following contiguous slots. On a cache hit the same CDFs are read back from those slots.
compute_info['cdf_cache_ctr'],cdf_cache_tag,cdf_cache_nbinsandcached_vuln_cdfsare mutated in place.Results are written into the caller’s buffers, never returned as views: the effective damage CDF always ends up in
eff_damage_cdf(a cache hit copies it there), and the per-hazard-bin CDFs in rows[:Nhaz_bins]ofhaz_i_to_vuln_cdfwith their lengths inhaz_i_to_Ndamage_bins(only wheneffective_damageabilityis False, the only case in which the caller reads them). Copying a few tens of floats is cheaper than a view (see the refcount note in common/event_stream.py).Coverage dependency: for a dependent item (
is_dependent) the vuln pdf is assembled from the conditional (damage-transition) matrixconditional_vuln_array— columnhaz_iis the dependent’s damage pmf given the source landed in damage binhaz_i— instead of the hazard-indexedvuln_array. A dependent’s CDFs depend on the source’s damage this event, so they are event-specific and never cached (the caller forcesdo_calc_vuln_ptffor dependents).- Returns:
length of the effective damage CDF in
eff_damage_cdf.- Return type:
- oasislmf.pytools.gulmc.manager.draw_correlation_samples(compute_info, item, hazard_rng_index, sample_size, haz_rndms_item, vuln_rndms_item, haz_eps_ij, damage_eps_ij, norm_inv_parameters, norm_inv_cdf, norm_cdf, vuln_adj, haz_z_unif, vuln_z_unif)[source]¶
Draw the (optionally correlated) hazard and damage random values for one item.
Writes
sample_sizevalues intohaz_z_unifandvuln_z_unifin place. When correlation is enabled for the relevant dimension the values are drawn through the Gaussian copula (get_corr_rval); otherwise the item’s base random values are copied straight across. Hazard values are only drawn whenhazard_rng_index >= 0(non-deterministic hazard under full Monte Carlo). For a single (non-aggregate) vulnerability the damage values are scaled by the per-vulnerability adjustment.- Parameters:
compute_info (gulmc_compute_info_type) – computation state (do_haz_correlation, do_correlation).
item (np.void) – the item record (correlation values, peril_correlation_group, vuln idx).
hazard_rng_index (int) – < 0 when the hazard is deterministic, in which case no hazard values are drawn. Only its sign is used; the caller has already sliced the values.
sample_size (int) – number of random samples to draw.
haz_rndms_item (np.array[float64]) – this item’s
sample_sizehazard random values. Under building packing this is one building’s slice of the group’s block, which is what lets one routine serve every building of an item.vuln_rndms_item (np.array[float64]) – this item’s
sample_sizedamage random values.haz_eps_ij (np.array[float]) – correlated random values for hazard sampling.
damage_eps_ij (np.array[float]) – correlated random values for damage sampling.
norm_inv_parameters (NormInversionParameters) – parameters for Gaussian inversion.
norm_inv_cdf (np.array[float]) – inverse Gaussian cdf lookup table.
norm_cdf (np.array[float]) – Gaussian cdf lookup table.
vuln_adj (np.array[float]) – per-vulnerability adjustment factors.
haz_z_unif (np.array[float]) – output buffer for hazard random values.
vuln_z_unif (np.array[float]) – output buffer for damage random values.
- oasislmf.pytools.gulmc.manager.sample_item_losses(compute_info, sample_size, hazard_rng_index, haz_z_unif, vuln_z_unif, haz_cdf_prob, Nhaz_bins, eff_damage_cdf, Neff_damage_bins, haz_i_to_Ndamage_bins, haz_i_to_vuln_cdf, damage_bins, damage_bin_scaling, out, is_dependent, src_bin_out, parent_bins)[source]¶
Write the per-sample gul (or debug random values) for one item into
losses.In debug modes 1/2 the drawn hazard/damage random values are stored directly. Otherwise the gul is computed per sample: under effective_damageability from the single effective damage CDF; with a single hazard bin from that bin’s vulnerability CDF; and in the general case by drawing the hazard bin per sample and using that bin’s vulnerability CDF. Return-period protection is not handled here: the caller skips a protected item whole, before any sampling.
Coverage dependency: a dependent item (
is_dependent, full Monte Carlo) selects its hazard bin as its source’s per-sample sampled damage bin, read fromparent_bins, rather than by drawing from the hazard CDF. This item’s own sampled damage bin is recorded insrc_bin_outso a dependent below it in the DFS can consume it. Both are slices of one building’s bins, so a packed item’s buildings each drive their own dependent.- Parameters:
compute_info (gulmc_compute_info_type) – computation state (debug, effective_damageability).
sample_size (int) – number of random samples.
hazard_rng_index (int) – index into hazard random values, or < 0 if hazard deterministic.
haz_z_unif (np.array[float]) – hazard random values for this item.
vuln_z_unif (np.array[float]) – damage random values for this item.
haz_cdf_prob (np.array[float]) – hazard intensity cdf buffer;
[:Nhaz_bins]is valid.Nhaz_bins (int) – number of hazard bins.
eff_damage_cdf (np.array[oasis_float]) – effective damage cdf buffer;
[:Neff_damage_bins]is valid.Neff_damage_bins (int) – number of effective damage bins.
haz_i_to_Ndamage_bins (np.array[oasis_int]) – per-hazard-bin vulnerability cdf lengths.
haz_i_to_vuln_cdf (np.array) – per-hazard-bin vulnerability cdfs.
damage_bins (np.array) – damage bin dictionary.
damage_bin_scaling (float) – tiv scaling factor.
out (np.array[oasis_float]) – 1-d view of length
sample_sizewritten in place, holding this item’s samples only. Callers pass one building’s column ofbuilding_losses; an unpacked item is the single-building case. Taking a view rather than (buffer, index) is what lets both use this routine.is_dependent (bool) – True if this item is driven by a source item’s sampled damage bin.
src_bin_out (np.array[int32]) – where the sampled damage bin is written, one per sample. The caller points it at this item’s slice of the stack when something below will read it, and at a discard slot otherwise, so the store here needs no condition.
parent_bins (np.array[int32]) – the source item’s bins for the SAME building, read when
is_dependent. Aliasessrc_bin_outotherwise, which keeps the argument typed without giving it a meaning.
- oasislmf.pytools.gulmc.manager.compute_event_losses(compute_info, coverages, coverage_ids, items_event_data, items, sample_size, haz_pdf, haz_arr_ptr, vuln_array, conditional_vuln_array, vuln_idx_to_cond_idx, damage_bins, cdf_cache_tag, cdf_cache_nbins, cdf_cache_mask, cached_vuln_cdfs, areaperil_agg_vuln_idx_ja_offsets, areaperil_agg_vuln_idx_ja_data, losses, vuln_adj, haz_eps_ij, damage_eps_ij, norm_inv_parameters, norm_inv_cdf, norm_cdf, vuln_z_unif, haz_z_unif, byte_mv, dynamic_footprint, intensity_bin_peril_ids, intensity_bins, building_losses, loss_correlation_by_item, hermite_coeffs, vuln_rndms_base, haz_rndms_base, vuln_seeds, haz_seeds, vuln_draw_scratch, haz_draw_scratch, perm_scratch, coverage_has_dependents, compute_depth, source_damage_bin_stack, source_eff_damage_cdf_stack, source_eff_damage_cdf_len_stack)[source]¶
Compute ground-up losses for all coverages in a single event.
Iterates over coverages and their items, looking up or computing the vulnerability cdf for each item, then sampling losses using the pre-generated random numbers. Results are written into a byte buffer for streaming output.
CDF caching uses a monotonic write counter and array-based slot tracking. Each unique (areaperil, vuln_id[, intensity_adjustment]) CDF group has a pre-computed index stored in eff_cdf_id. cdf_cache_tag[triplet_idx] records the write counter value when the CDFs were cached. A slot is valid when cdf_cache_tag[triplet_idx] >= 0 and cdf_cache_ctr - cdf_cache_tag[triplet_idx] < cdf_cache_size. Physical slot indexing uses bitwise AND with cdf_cache_mask (power-of-two sized cache).
For effective_damageability=False, CDFs are stored as contiguous blocks: slot 0 = effective damage CDF, slots 1..Nhaz_bins = per-intensity-bin vulnerability CDFs.
- Parameters:
compute_info (gulmc_compute_info_type) – computation state (event_id, cursor position, coverage range, cdf_cache_ctr, thresholds, flags).
coverages (numpy.array[coverage_type]) – coverage data indexed by coverage_id.
coverage_ids (numpy.array[int]) – ordered list of coverage_ids to process in this event.
items_event_data (numpy.array[items_MC_data_type]) – per-item event data populated by reconstruct_coverages, containing item_idx, haz_arr_i, rng_index, hazard_rng_index, and eff_cdf_id (CDF group index).
items (np.ndarray) – items table merged with correlation parameters.
sample_size (int) – number of random samples to draw.
haz_pdf (np.array[haz_arr_type]) – hazard intensity pdf records for this event.
haz_arr_ptr (np.array[int64]) – indices where each areaperil’s hazard records start in haz_pdf.
vuln_array (np.array[float]) – 3d vulnerability array of shape (Nvulnerability, Ndamage_bins_max, Nintensity_bins).
damage_bins (np.array) – damage bin dictionary with bin_from, bin_to, interpolation, damage_type.
cdf_cache_tag (np.array[int64]) – CDF group index → write counter when cached (CDF_CACHE_EMPTY = -1).
cdf_cache_nbins (np.array[int32]) – physical slot → CDF length (Ndamage_bins).
cdf_cache_mask (int64) – bitmask for physical slot indexing (cdf_cache_size - 1).
cached_vuln_cdfs (np.array[oasis_float]) – 2d cdf cache of shape (cdf_cache_size, Ndamage_bins_max).
areaperil_agg_vuln_idx_ja_offsets (np.array[oasis_int]) – jagged array offsets.
areaperil_agg_vuln_idx_ja_data (np.array[agg_vuln_idx_weight_dtype]) – merged structured array with fields ‘vuln_idx’ (dense vulnerability index) and ‘weight’ (vulnerability weight).
losses (numpy.array[oasis_float]) – reusable 2d buffer for loss values.
vuln_adj (np.array[float]) – per-vulnerability adjustment factors.
haz_eps_ij (np.array[float]) – correlated random values for hazard sampling.
damage_eps_ij (np.array[float]) – correlated random values for damage sampling.
norm_inv_parameters (NormInversionParameters) – parameters for Gaussian inversion.
norm_inv_cdf (np.array[float]) – inverse Gaussian cdf lookup table.
norm_cdf (np.array[float]) – Gaussian cdf lookup table.
vuln_z_unif (np.array[float]) – reusable buffer for correlated vulnerability random values.
haz_z_unif (np.array[float]) – reusable buffer for correlated hazard random values.
byte_mv (numpy.array[byte]) – output byte buffer for the binary stream.
dynamic_footprint (None or object) – None if no dynamic footprint, otherwise truthy.
intensity_bin_peril_ids (np.array[int32]) – sorted unique encoded peril_ids (length n_perils).
intensity_bins (np.array[int32, 2d]) – shape (n_perils, max_intensity + 1) mapping [peril_idx, intensity_value] -> intensity_bin_id.
conditional_vuln_array (np.array[oasis_float]) – damage-transition matrices, indexed [cond_idx, dependent damage bin - 1, source damage bin - 1]. Empty when no dependency.
vuln_idx_to_cond_idx (np.array[int64]) – dense vuln index -> conditional row, or -1.
coverage_has_dependents (np.array[int8]) – per coverage_id, 1 if any coverage names it as its source. Only those coverages’ sampled damage bins are stored, and the bin stack is sized on that basis, so storing for any other coverage would write past its width.
compute_depth (np.array[int32]) – per entry of
coverage_ids, its depth in the dependency forest (0 for a root), matching the DFS order the caller put them in.source_damage_bin_stack (np.array[int32]) – per-depth, per-item sampled damage bins, holding a source coverage’s result while its dependent subtree is computed.
source_eff_damage_cdf_stack (np.array[oasis_float]) – per-depth, per-item effective damage cdfs, the effective-damageability counterpart of the sampled bins.
source_eff_damage_cdf_len_stack (np.array[int64]) – valid length of each entry of
source_eff_damage_cdf_stack.building_losses (numpy.array[oasis_float]) – 3d (S, max_items, max_buildings) reusable buffer for the per-building sample losses. Every coverage holds all of its buildings here before write_losses emits it, so it is sized by the portfolio’s largest location.
loss_correlation_by_item (numpy.array[oasis_float]) – per item of the current coverage, the correlation between two of its buildings’ losses, written where the analytic moments are and read when its summed specials are emitted. 0 for everything that does not report the spread of a sum.
hermite_coeffs (numpy.array[float64]) – length HERMITE_TERMS scratch for that.
vuln_rndms_base (numpy.array[float64]) – 2d (damage rng groups, S) random draws, one row per group, which is also every packed item’s first building.
haz_rndms_base (numpy.array[float64]) – the same for the hazard rng groups.
vuln_seeds (numpy.array[int]) – per damage rng group, the Philox key. Read for a packed item’s buildings 2..N, which are drawn per item rather than shared.
haz_seeds (numpy.array[int]) – the same for the hazard rng groups.
vuln_draw_scratch (numpy.array[float64]) – length-S buffer for one building’s damage block.
haz_draw_scratch (numpy.array[float64]) – the same for hazard.
perm_scratch (numpy.array[float64]) – length-S scratch the block generator permutes in.
- Returns:
- True if all coverages have been processed, False if the buffer is full and
the caller should flush and call again.
- Return type:
- oasislmf.pytools.gulmc.manager.process_areaperils_in_footprint(event_footprint, areaperil_id_ind, dynamic_footprint, ap_inds, event_rps, haz_arr_ptr)[source]¶
Process areaperils in the footprint, filtering to those with vulnerability functions.
Writes into pre-allocated arrays (ap_inds, event_rps, haz_arr_ptr) that are owned by the caller and reused across events.
The buffer stores the dense areaperil index (from areaperil_id_ind) rather than the raw areaperil_id, so downstream consumers (reconstruct_coverages) can index item_map_ja_offsets directly and skip a second id_index lookup.
- Parameters:
event_footprint (np.array[Event or footprint_event_dtype]) – footprint entries.
areaperil_id_ind (np.array) – id_index structure for known areaperil_ids.
dynamic_footprint (bool) – true if there is dynamic_footprint.
ap_inds (np.array[uint32]) – pre-allocated output buffer for dense areaperil indices.
event_rps (np.array[int32]) – pre-allocated output buffer for return periods (dynamic only).
haz_arr_ptr (np.array[int64]) – pre-allocated output buffer for hazard pdf offsets.
- Returns:
number of areaperils stored. If zero, no items have losses. haz_pdf (np.array[haz_arr_type]): hazard intensity pdf (freshly sliced).
- Return type:
Nhaz_arr_this_event (int)
- oasislmf.pytools.gulmc.manager.reconstruct_coverages(compute_info, ap_inds, Nhaz_arr_this_event, haz_arr_ptr, event_rps, item_map_ja_offsets, item_map_ja_vuln_ja_offsets, item_map_ja_vuln_ja_item_idxs, items, item_cdf_group_idx, coverages, compute, haz_seeds, haz_peril_correlation_groups, haz_corr_seeds, vuln_seeds, damage_peril_correlation_groups, damage_corr_seeds, dynamic_footprint, byte_mv, items_event_data, group_seq_rng_index, hazard_group_seq_rng_index, coverage_source_id, coverage_dependents_ja_offsets, coverage_dependents_ja_data, compute_depth, compute_footprint_order, dependency_dfs_stack, source_item_idx, item_idx_to_item_j)[source]¶
Register each item to its coverage and prepare per-item event data for loss computation.
For each (areaperil_id, vulnerability_id) pair present in the event footprint, iterates over all mapped items and:
Computes deterministic hash-based random seeds for hazard and damage sampling, using group_id and hazard_group_id respectively. Seeds are deduplicated via pre-allocated arrays indexed by sequential group ids.
Maps each item to its coverage structure, tracking the start offset and count.
Stores per-item event data (haz_arr_i, rng_index, hazard_rng_index, eff_cdf_id) in the items_event_data array. The eff_cdf_id is the pre-computed CDF group index from item_cdf_group_idx.
- Parameters:
compute_info (gulmc_compute_info_type) – computation state; coverage_i, coverage_n, and event_id fields are read/written.
ap_inds (np.array[uint32]) – dense areaperil indices present in the event footprint (from process_areaperils_in_footprint), length >= Nhaz_arr_this_event.
Nhaz_arr_this_event (int) – number of valid entries in ap_inds.
haz_arr_ptr (np.array[int64]) – per-areaperil offsets into the event hazard pdf; the number of hazard intensity bins for areaperil ap_i is haz_arr_ptr[ap_i+1] - haz_arr_ptr[ap_i]. A count of 1 means the hazard is deterministic and no hazard rng row is needed.
event_rps (np.array[int32]) – parallel array of return periods per areaperil (dynamic only).
item_map_ja_offsets (np.array[oasis_int]) – L1 CSR offsets (N_areaperil + 1).
item_map_ja_vuln_ja_offsets (np.array[oasis_int]) – L2 CSR offsets (N_pairs + 1).
item_map_ja_vuln_ja_item_idxs (np.array[oasis_int]) – flat item indices into items array.
items (np.ndarray) – items table merged with correlation parameters, containing group_id, hazard_group_id, coverage_id, group_seq_id, hazard_group_seq_id, etc.
item_cdf_group_idx (np.array[int64]) – pre-computed mapping from item_idx to CDF group index.
coverages (numpy.array[coverage_type]) – coverage data indexed by coverage_id. On entry, cur_items is non-zero only for the coverages in
compute[:compute_info['coverage_n']](the previous event’s), which are the only ones reset here.compute (numpy.array[int]) – output buffer for the list of coverage_ids to be computed. Must still hold the previous event’s list on entry, see
coverages.haz_seeds (numpy.array[int]) – output buffer for hazard intensity random seeds.
haz_peril_correlation_groups (numpy.array[int]) – unique peril correlation groups for hazard.
haz_corr_seeds (numpy.array[int]) – output buffer for hazard correlation seeds.
vuln_seeds (numpy.array[int]) – output buffer for damage random seeds.
damage_peril_correlation_groups (numpy.array[int]) – unique peril correlation groups for damage.
damage_corr_seeds (numpy.array[int]) – output buffer for damage correlation seeds.
dynamic_footprint (None or object) – None if no dynamic footprint, otherwise truthy.
byte_mv (numpy.array[byte]) – output byte buffer, may be resized if needed.
items_event_data (numpy.array[items_MC_data_type]) – per-item event data buffer, reused across events and grown (doubled) when an event needs more room. Its contents on entry are irrelevant: every field read for an item is written for this event first.
group_seq_rng_index (numpy.array[int64]) – pre-allocated array of size n_unique_groups, used for O(1) group_id to rng_index mapping. All NO_RNG_INDEX on entry; only the entries of this event’s groups are set, and they are restored before returning.
coverage_source_id (numpy.array) – source coverage_id per coverage_id, 0 for a root.
coverage_dependents_ja_offsets (numpy.array[oasis_int]) – CSR offsets into
coverage_dependents_ja_data, indexed by source coverage_id.coverage_dependents_ja_data (numpy.array) – dependent coverage ids, grouped by source.
compute_depth (numpy.array[int32]) – written per emitted coverage: its depth in the dependency forest, 0 for a root.
compute_footprint_order (numpy.array) – scratch holding the present coverages in footprint order while
computeis rewritten into DFS order.dependency_dfs_stack (numpy.array[int64]) – scratch (coverage_id, depth) work stack for the DFS reorder.
source_item_idx (numpy.array[int64]) – per item, the index into
itemsof its source item, or -1 when it has none.item_idx_to_item_j (numpy.array[oasis_int]) – scratch mapping an item index to its position within its coverage for this event, used to pair a dependent item with its source item.
hazard_group_seq_rng_index (numpy.array[int64]) – pre-allocated array of size n_unique_haz_groups, for hazard_group_id to rng_index mapping. Same contract as
group_seq_rng_index.
- Returns:
- (items_event_data, rng_index, hazard_rng_index, byte_mv)
items_event_data (numpy.array[items_MC_data_type]): per-item data including item_idx, haz_arr_i, rng_index, hazard_rng_index, eff_cdf_id. The buffer passed in, or a grown copy of it: the caller must keep the returned one for the next event.
rng_index (int): number of unique damage random seeds generated.
hazard_rng_index (int): number of unique hazard random seeds generated. Only hazard groups touching a non-deterministic areaperil (and only under full Monte Carlo, not effective damageability) are counted, so this is 0 for events with no hazard uncertainty. Items not assigned a hazard rng row carry the NO_RNG_INDEX sentinel in items_event_data[‘hazard_rng_index’].
byte_mv (numpy.array[byte]): output buffer, possibly resized.
- Return type: