Skip to content

calculators

A collection of calculation functions for hazard aggregation.

The aggregates of a task are calculated by composite_rate_aggs(). What it calculates is simple: for each level, sum the component rates of every composite branch, then find the weighted mean, std and quantiles of those rates. How it does so is arranged to keep the rates out of memory, as storing and reading them took most of the time of a task:

  1. composite_rate_bounds() bounds the rates of each level from the component rates, to set the range of the bins.
  2. _pass_a() sums every rate, a small block of branches at a time. Each block gives its part of the mean and std, and each rate is put in a bin by value. Only the bin of each rate is kept.
  3. _target_bins() finds the bins that hold the quantiles from the weight in each bin.
  4. _pass_b() sums again only the rates in or next to those bins.
  5. _select_quantiles() sorts the rates in each of those bins and interpolates the quantiles.

See docs/aggregate_calculation.md for a full explanation, starting from a simple version of the same calculation, with a worked example and which code must be kept in step.

composite_rate_aggs(branch_index_table, component_rates, weights, quantiles, columns, nbins=QUANTILE_NBINS, sort_size=QUANTILE_SORT_SIZE)

Calculate the weighted mean, std and quantiles of each level of the composite rates, without building them.

The rate of a composite branch is the sum of the rates of its component branches. The composite rates are summed as they are needed rather than stored: a (IMTL, composite branch) array is about 345 MB for NSHM_v1.0.4, and reading it from memory took most of the time of an aggregation.

For the quantiles, the rates of a level are put in ascending order, with equal rates kept in branch order. Each rate sits at the cumulative weight up to and including it, less half its own weight, as a fraction of the total weight. A quantile is linearly interpolated between the rates either side of it, and is the smallest or largest rate if it is outside of them. Only the rates near each quantile are sorted, see _select_quantiles(). nbins and sort_size change the time taken, and the quantiles only by rounding (the cumulative weights are summed in another order).

The indices are not bounds checked, every entry of branch_index_table must be a valid row of component_rates.

Parameters:

Name Type Description Default
branch_index_table NDArray

composite branches as rows of indices into component_rates (composite branch, component)

required
component_rates NDArray

rates of the component branches (component branch, IMTL). They must not be NaN.

required
weights NDArray

weights of the composite branches (composite branch, ). They do not need to sum to 1.

required
quantiles Union[list[float], NDArray]

quantiles to be found (quantile, ). Values should be in [0,1]

required
columns Sequence[NDArray]

the component branches in each column of branch_index_table, see logic_tree.branch_index_columns()

required
nbins int

the number of bins that a large set of values are put in, 4 to 65536

QUANTILE_NBINS
sort_size int

a set of values no larger than this is sorted rather than put in bins

QUANTILE_SORT_SIZE

Returns:

Type Description
(mean, std, quantiles)

the weighted mean and std (IMTL, ) and the weighted quantiles (quantile, IMTL)

Source code in toshi_hazard_post/calculators.py
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
def composite_rate_aggs(
    branch_index_table: 'npt.NDArray',
    component_rates: 'npt.NDArray',
    weights: 'npt.NDArray',
    quantiles: Union[list[float], 'npt.NDArray'],
    columns: Sequence['npt.NDArray'],
    nbins: int = QUANTILE_NBINS,
    sort_size: int = QUANTILE_SORT_SIZE,
) -> tuple['npt.NDArray', 'npt.NDArray', 'npt.NDArray']:
    """Calculate the weighted mean, std and quantiles of each level of the composite rates, without building them.

    The rate of a composite branch is the sum of the rates of its component branches. The composite rates are summed
    as they are needed rather than stored: a (IMTL, composite branch) array is about 345 MB for NSHM_v1.0.4, and
    reading it from memory took most of the time of an aggregation.

    For the quantiles, the rates of a level are put in ascending order, with equal rates kept in branch order. Each
    rate sits at the cumulative weight up to and including it, less half its own weight, as a fraction of the total
    weight. A quantile is linearly interpolated between the rates either side of it, and is the smallest or largest
    rate if it is outside of them. Only the rates near each quantile are sorted, see _select_quantiles(). nbins and
    sort_size change the time taken, and the quantiles only by rounding (the cumulative weights are summed in another
    order).

    The indices are not bounds checked, every entry of branch_index_table must be a valid row of component_rates.

    Args:
        branch_index_table: composite branches as rows of indices into component_rates (composite branch, component)
        component_rates: rates of the component branches (component branch, IMTL). They must not be NaN.
        weights: weights of the composite branches (composite branch, ). They do not need to sum to 1.
        quantiles: quantiles to be found (quantile, ). Values should be in [0,1]
        columns: the component branches in each column of branch_index_table, see
            logic_tree.branch_index_columns()
        nbins: the number of bins that a large set of values are put in, 4 to 65536
        sort_size: a set of values no larger than this is sorted rather than put in bins

    Returns:
        (mean, std, quantiles): the weighted mean and std (IMTL, ) and the weighted quantiles (quantile, IMTL)
    """
    nbranches, ncomponents = branch_index_table.shape
    if nbranches == 0:
        raise ValueError("branch_index_table must have at least one composite branch")
    if weights.shape != (nbranches,):
        raise ValueError("weights must have one entry for each composite branch")
    if len(columns) != ncomponents:
        raise ValueError("columns must have one entry for each column of the branch index table")
    # two of the bins are for the smallest and largest rates, the rest have to divide the rates in between
    if not 4 <= nbins <= COMPOSITE_RATE_AGGS_MAX_NBINS:
        raise ValueError(f"nbins must be from 4 to {COMPOSITE_RATE_AGGS_MAX_NBINS}")
    component_rates = np.ascontiguousarray(component_rates, dtype=np.float64)
    weights = np.ascontiguousarray(weights, dtype=np.float64)
    quantiles = np.asarray(quantiles, dtype=np.float64)
    lo, hi, hi_finite = composite_rate_bounds(columns, component_rates)
    return _composite_rate_aggs(
        branch_index_table, component_rates, weights, quantiles, lo, hi, hi_finite, nbins, sort_size
    )

composite_rate_bounds(columns, component_rates)

Bound the rates of the composite branches of each level, without building them.

A composite rate is the sum of one component rate from each column of the branch index table, added in column order (see _composite_rate()). Rounded addition is monotonic, so adding the smallest (largest) rate of each column in the same order bounds every composite rate below (above). The bounds are exact if every combination of the component branches of the columns is a composite branch.

Parameters:

Name Type Description Default
columns Sequence[NDArray]

the component branches in each column of the branch index table, see logic_tree.branch_index_columns()

required
component_rates NDArray

rates of the component branches (component branch, IMTL)

required

Returns:

Type Description
lo, hi, hi_finite) each with shape (IMTL,

at most the smallest, at least the largest and at least the largest finite composite rate of each level. If lo equals hi, every rate of the level is equal to it.

Source code in toshi_hazard_post/calculators.py
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def composite_rate_bounds(
    columns: Sequence['npt.NDArray'], component_rates: 'npt.NDArray'
) -> tuple['npt.NDArray', 'npt.NDArray', 'npt.NDArray']:
    """Bound the rates of the composite branches of each level, without building them.

    A composite rate is the sum of one component rate from each column of the branch index table, added in
    column order (see _composite_rate()). Rounded addition is monotonic, so adding the smallest (largest) rate
    of each column in the same order bounds every composite rate below (above). The bounds are exact if every
    combination of the component branches of the columns is a composite branch.

    Args:
        columns: the component branches in each column of the branch index table, see
            logic_tree.branch_index_columns()
        component_rates: rates of the component branches (component branch, IMTL)

    Returns:
        (lo, hi, hi_finite) each with shape (IMTL, ): at most the smallest, at least the largest and at least the
            largest finite composite rate of each level. If lo equals hi, every rate of the level is equal to it.
    """
    nlevels = component_rates.shape[1]
    lo = np.zeros(nlevels)
    hi = np.zeros(nlevels)
    hi_finite = np.zeros(nlevels)
    for column in columns:
        rates = component_rates[column]
        lo = lo + rates.min(axis=0)
        hi = hi + rates.max(axis=0)
        hi_finite = hi_finite + np.where(np.isinf(rates), -np.inf, rates).max(axis=0)
    return lo, hi, hi_finite

cov(mean, std)

Calculate the coeficient of variation handling zero mean by setting cov to zero.

Parameters:

Name Type Description Default
mean NDArray

array of mean values

required
std NDArray

array of standard deviation values

required

Returns:

Name Type Description
cov NDArray

array of coeficient of variation values

Source code in toshi_hazard_post/calculators.py
135
136
137
138
139
140
141
142
143
144
145
146
147
def cov(mean: 'npt.NDArray', std: 'npt.NDArray') -> 'npt.NDArray':
    """Calculate the coeficient of variation handling zero mean by setting cov to zero.

    Args:
        mean: array of mean values
        std: array of standard deviation values

    Returns:
        cov: array of coeficient of variation values
    """
    cov = std / mean
    cov[mean == 0] = 0
    return cov

prob_to_rate(prob, inv_time)

Convert probability of exceedance to rate assuming Poisson distribution.

Parameters:

Name Type Description Default
prob NDArray

probability of exceedance

required
inv_time float

time period for probability (e.g. 1.0 for annual probability)

required

Returns:

Name Type Description
rate NDArray

return rate in inv_time

Source code in toshi_hazard_post/calculators.py
31
32
33
34
35
36
37
38
39
40
41
42
@jit(nopython=True)
def prob_to_rate(prob: 'npt.NDArray', inv_time: float) -> 'npt.NDArray':
    """Convert probability of exceedance to rate assuming Poisson distribution.

    Args:
        prob: probability of exceedance
        inv_time: time period for probability (e.g. 1.0 for annual probability)

    Returns:
        rate: return rate in inv_time
    """
    return -np.log(1.0 - prob) / inv_time

rate_to_prob(rate, inv_time)

Convert rate to probabiility of exceedance assuming Poisson distribution.

Parameters:

Name Type Description Default
rate NDArray

rate over inv_time

required
inv_time float

time period of rate (e.g. 1.0 for annual rate)

required

Returns:

Name Type Description
prob NDArray

probability of exceedance in inv_time

Source code in toshi_hazard_post/calculators.py
45
46
47
48
49
50
51
52
53
54
55
56
@jit(nopython=True)
def rate_to_prob(rate: 'npt.NDArray', inv_time: float) -> 'npt.NDArray':
    """Convert rate to probabiility of exceedance assuming Poisson distribution.

    Args:
        rate: rate over inv_time
        inv_time: time period of rate (e.g. 1.0 for annual rate)

    Returns:
        prob: probability of exceedance in inv_time
    """
    return 1.0 - np.exp(-inv_time * rate)

warm_up(branch_index_dtype)

Compile the composite rate aggregate kernel, or load it from the numba cache.

Call this before starting worker processes. Workers that are forked inherit the compiled kernel and workers that are spawned load it from the cache, rather than each of them compiling it for their first task.

Parameters:

Name Type Description Default
branch_index_dtype dtype

the type of the branch index table of the aggregation. The composite rate aggregate kernel is compiled for each type, and logic_tree.build_branch_index_table() uses the smallest unsigned type that holds the component indices.

required
Source code in toshi_hazard_post/calculators.py
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
def warm_up(branch_index_dtype: np.dtype) -> None:
    """Compile the composite rate aggregate kernel, or load it from the numba cache.

    Call this before starting worker processes. Workers that are forked inherit the compiled kernel and workers
    that are spawned load it from the cache, rather than each of them compiling it for their first task.

    Args:
        branch_index_dtype: the type of the branch index table of the aggregation. The composite rate aggregate
            kernel is compiled for each type, and logic_tree.build_branch_index_table() uses the smallest unsigned
            type that holds the component indices.
    """
    zeros = np.zeros(1)
    _composite_rate_aggs(
        np.zeros((1, 1), dtype=branch_index_dtype), np.zeros((1, 1)), np.ones(1), np.array([0.5]), zeros, zeros, zeros,
        QUANTILE_NBINS, QUANTILE_SORT_SIZE,
    )  # fmt: skip