Skip to content

How the aggregates are calculated

How the aggregates are calculated

This page is for developers. It explains how one task, a single location, vs30 and IMT, turns the probabilities of the component branches into the mean, std, cov and quantiles of the hazard. The code is in aggregation_calc.py (the task) and calculators.py (the numerical kernels).

The calculation itself is simple. The code that does it is not, because it is arranged to move as little data as possible to and from memory. Start with the simple version: everything after it is a faster way to get the same answer.

The simple version

The task has three inputs:

Name Shape NSHM_v1.0.4 What it is
component_rates (component branch, IMTL) (912, 44) the rate of each component branch, converted from its probability
branch_index_table (composite branch, column) (979776, 4) the rows of component_rates that make up each composite branch
weights (composite branch,) (979776,) the logic tree weight of each composite branch

There is one column in the table for each source branch set. The rate of a composite branch is the sum of the rates of its component branches. Each level (IMTL) is independent of the others:

def simple_aggs(branch_index_table, component_rates, weights, quantiles):
    nlevels = component_rates.shape[1]
    total_weight = weights.sum()
    mean = np.empty(nlevels)
    std = np.empty(nlevels)
    wq = np.empty((len(quantiles), nlevels))
    for j in range(nlevels):
        # the rate of every composite branch
        rates = component_rates[branch_index_table, j].sum(axis=1)

        mean[j] = (weights * rates).sum() / total_weight
        std[j] = np.sqrt((weights * (rates - mean[j]) ** 2).sum() / total_weight)

        # each rate sits in the middle of its own weight, quantiles are interpolated between rates
        order = np.argsort(rates, kind='stable')
        position = np.cumsum(weights[order]) - 0.5 * weights[order]
        wq[:, j] = np.interp(np.array(quantiles) * total_weight, position, rates[order])
    return mean, std, wq

calculators.composite_rate_aggs() gives the same results as this function, up to floating point rounding. (The cov is std / mean, done afterwards.)

Why the code is not that simple

For NSHM_v1.0.4 the rates of all levels are an array of about 345 MB (979776 branches x 44 levels x 8 bytes), and every worker has its own. Writing it and reading it back is limited by the memory bandwidth of the machine, which all the workers share, so adding workers stopped helping. Sorting about a million rates per level is also slow.

Three ideas avoid this:

  1. Sum each rate when it is needed and don't store it. The component rates of a level are only about 7 KB, so they stay in the processor's cache. The table and the weights are in shared memory, and are the same for every level and every worker.
  2. Work on blocks of 256 branches. Everything that needs a rate in the first pass uses it while the block is in cache.
  3. Sort only the rates near each quantile. Put the rates in bins, use the weight in each bin to find which bins the quantiles are in, and sort only the rates in those bins.

The calculation, step by step

calc_aggregation                          aggregation_calc.py: one task
 ├─ prob_to_rate                          component probabilities to component rates
 ├─ calculate_aggs_from_components
 │   ├─ composite_rate_aggs               calculators.py: checks its arguments
 │   │   ├─ composite_rate_bounds         range of the rates at each level
 │   │   └─ _composite_rate_aggs          for each level:
 │   │       ├─ _pass_a                     sum every rate: mean and std, and put it in a bin
 │   │       ├─ _target_bins                which bins hold the quantiles?
 │   │       ├─ _pass_b                     sum the rates in those bins again and gather them
 │   │       └─ _select_quantiles           sort each bin's rates and interpolate
 │   └─ _assemble_aggs                    cov, and the order of agg_types
 └─ rate_to_prob, save_aggregations

1. Bound the rates: composite_rate_bounds

The bins need the range of the rates before any rate has been summed. Each composite rate takes one component rate from each column of the table, so the sum of the smallest rate in each column can't be more than any composite rate, and the sum of the largest can't be less. logic_tree.branch_index_columns() lists the component branches in each column.

These are bounds, and the smallest rate may be larger than the lower bound if not every combination of component branches is in the table. (In NSHM_v1.0.4 the table has fewer than 3% of the combinations.) This only makes the bins a bit less well fitted. If the two bounds are equal, so is every rate (e.g. a level of zeros): the quantiles are that rate, and the binning and steps 3 to 5 are skipped.

The bounds hold exactly, with no tolerance for rounding, because they are added in the same column order as the rates.

2. Pass A: mean, std and bins: _pass_a

For each block of 256 branches (SUM_BLOCK_SIZE), sum the rates into a small buffer, then use the buffer three times:

  • add up weight * rate for the block, which gives the block's mean
  • add up weight * (rate - block mean)^2, the block's squared deviations
  • find the bin of each rate, add its weight and count to the bin, and keep the bin number in bins (2 bytes per branch, instead of 8 for the rate)

Then the blocks are combined. The total of the weighted sums gives the mean. The std needs deviations from the mean of the level, which isn't known until the pass is finished, so they are worked out from the block values:

squared deviations from the mean = sum over blocks of
      the block's squared deviations from its own mean
    + block weight * (block mean - mean)^2

This is exact algebra (Chan et al.), not an approximation.

The shift. All of this is done on rate - shift, where shift is the mean of the first block with weight. The shift is added back to the mean and doesn't change the std. It keeps the std accurate when it is much smaller than the mean. If that block has an infinite rate the shift is 0, as otherwise the mean would be NaN instead of infinite.

Four partial sums. The s0 to s3 in the block loops are one sum split in four, so that the processor doesn't have to wait for one addition before it starts the next.

3. Find the target bins: _target_bins

There are 16384 bins (QUANTILE_NBINS), numbered in order of rate:

  • bin 0 holds the rates equal to the lower bound (often all the zero rates)
  • the bins between are equally wide
  • the last bin holds the rates at or above the largest finite bound, including infinite rates

Each quantile becomes a target cumulative weight, quantile * total weight. Adding up the bin weights in order shows which bin each target falls in: its target bin.

The rates of the target bins are not quite enough. A quantile is interpolated between two rates, and near the edge of a bin one of the two can be in the next bin. So the nearest non-empty bin on each side is selected too, but only the one rate closest to the target bin is needed from it.

4. Pass B: gather the rates near the quantiles: _pass_b

Go through the branches again, looking only at bins. Most branches aren't in a selected bin and are skipped. The rates of the rest are summed a second time, and for each selected bin:

  • the smallest and largest rates are kept (first_v, last_v), with their weights
  • the rates and weights are gathered, if it is a target bin

5. Sort and interpolate: _select_quantiles

For each target bin, sort the gathered rates, work out their positions starting from the weight of all the bins below, add the neighbouring rate on each side (left and right), and interpolate with np.interp.

If a target bin has more than 4096 rates it is treated as a level of its own: its rates are put in bins that span only that bin, and _select_quantiles() calls itself for the target bins among those. This is the only recursion. The gathered rates are stored, so there is no need to sum them again.

A worked example

One level with seven composite branches, six bins, and the median as the only quantile.

branch     0    1    2    3    4    5    6
rate       2    9    4    5    4.5  11   3
weight     0.1  0.1  0.3  0.1  0.1  0.1  0.2     total weight 1, target = 0.5
bin        0    4    1    2    2    5    1       <- pass A keeps only this row

The weight in each bin gives the target bin:

bin             0    1     2       3    4    5
rates           2    3,4   4.5,5   -    9    11
weight          0.1  0.5   0.2     0    0.1  0.1
weight below    0    0.1   0.6     0.8  0.8  0.9
                     ^ the target 0.5 is between 0.1 and 0.6: target bin 1

Pass B gathers the rates of bin 1 (4 and 3, in branch order). From its neighbours, bins 0 and 2, it keeps the largest rate of bin 0 (2) and the smallest rate of bin 2 (4.5). Each rate sits at the weight before it plus half its own:

rate        2 (left)   3      4      4.5 (right)
position    0.05       0.2    0.45   0.65
                                 ^ target 0.5

The median is 4 + (4.5 - 4) * (0.5 - 0.45) / (0.65 - 0.45) = 4.125. The target was in bin 1, but the answer needed a rate from bin 2: this is what the neighbours are for. The rates 5, 9 and 11 were never sorted.

Changing this code

The kernels have deliberate repetition: some helpers made them slower when numba compiled them. These have to be kept in step:

If you change Also change Because
the loop in _pass_b the gather loop in _select_quantiles they are the same loop, one on summed rates and one on stored values
the rest of _composite_rate_aggs after pass A the end of _select_quantiles it is the top level of that function
the order of addition in _composite_rate composite_rate_bounds the bounds only hold if the order is the same
the type of bins (uint16) COMPOSITE_RATE_AGGS_MAX_NBINS the bin number has to fit

Things to know:

  • Branch order matters for equal rates. They are kept in branch order, as a stable sort leaves them. This is why pass B compares with < for the first rate but >= for the last.
  • Four columns is a special case in _composite_rate, for speed only. Other numbers of columns use the loop.
  • Array bounds are not checked inside the compiled kernels. _check_branch_index_table() checks the table first.
  • QUANTILE_NBINS and QUANTILE_SORT_SIZE are tuning values. They change the time taken, and the quantiles only by rounding.
  • warm_up() compiles the kernel before the workers start. If you change the arguments of _composite_rate_aggs, change it too.

The tests in tests/test_calculators.py are the safety net. They check the results against the definition of each aggregate, worked out from every composite rate and by sorting all of them, and against the simple version on this page. The kernels are run as plain Python too, where bad array indices do raise an error.