Skip to content

aggregation_calc

Primary functions for calculating an aggregation for a single, site, IMT, etc.

calc_aggregation() does one task: it converts the probabilities of the component branches to rates, calculates the aggregates of the composite branches with calculate_aggs_from_components(), converts them back to probabilities and saves them. The rates of the composite branches are never stored, see calculators.composite_rate_aggs() and docs/aggregate_calculation.md for how the aggregates are calculated without them.

AggSharedArgs dataclass

A class to store arguments shared by multiple aggregation jobs (used for parallelization).

Attribues
Source code in toshi_hazard_post/aggregation_calc.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
@dataclass
class AggSharedArgs:
    """A class to store arguments shared by multiple aggregation jobs (used for parallelization).

    Attribues:
        agg_types: the types of aggregation to perform (e.g. 'mean', '0.9', etc.).
        compatibility_key: the toshi-hazard-store compatibility key.
        hazard_model_id: the name of the model to use when storing the result.
        weights_shape: the shape of the weights array.
        branch_index_table_shape: the shape of the branch index table array.
        branch_index_table_dtype: the data type of the branch index table array.
        weights_shm_name: the name of the shared memory segment holding the weights.
        branch_index_table_shm_name: the name of the shared memory segment holding the branch index table.
        branch_index_columns: the component branches in each column of the branch index table, used to bound the
            composite rates of each level for the quantiles (see logic_tree.branch_index_columns()).
        skip_save: set to True if skipping saving the aggregations. Used when debugging to avoid writing to a database.
    """

    agg_types: list[str]
    compatibility_key: str
    hazard_model_id: str
    weights_shape: tuple[int, ...]
    branch_index_table_shape: tuple[int, ...]
    branch_index_table_dtype: str
    weights_shm_name: str
    branch_index_table_shm_name: str
    branch_index_columns: list['npt.NDArray']
    skip_save: bool

AggTaskArgs dataclass

The arguments for a specific aggregation task.

A aggregation task is for a single location, vs30, imt, etc.

Attributes:

Name Type Description
location CodedLocation

the site locaiton.

vs30 int

the site vs30.

imt str

the intensity measure type.

probs NDArray

the realization probabilities with shape (n component branches, n IMTL), where row i is for the component branch at position i of the branch index table.

Source code in toshi_hazard_post/aggregation_calc.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@dataclass
class AggTaskArgs:
    """The arguments for a specific aggregation task.

    A aggregation task is for a single location, vs30, imt, etc.

    Attributes:
        location: the site locaiton.
        vs30: the site vs30.
        imt: the intensity measure type.
        probs: the realization probabilities with shape (n component branches, n IMTL), where row i is for the
            component branch at position i of the branch index table.
    """

    location: 'CodedLocation'
    vs30: int
    imt: str
    probs: 'npt.NDArray'

    def __repr__(self) -> str:
        # failed tasks are logged with their arguments, so leave out the data
        return (
            f"AggTaskArgs(location={self.location.code}, vs30={self.vs30}, imt={self.imt}, "
            f"probs={self.probs.shape} {self.probs.dtype})"
        )

calc_aggregation(task_args, shared_args)

Calculate hazard aggregation for a single site and imt and save result.

Parameters:

Name Type Description Default
task_args AggTaskArgs

The arguments fot the specific aggregation calculation.

required
shared_args AggSharedArgs

The arguments shared among all workers.

required
Source code in toshi_hazard_post/aggregation_calc.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def calc_aggregation(task_args: AggTaskArgs, shared_args: AggSharedArgs) -> None:
    """Calculate hazard aggregation for a single site and imt and save result.

    Args:
        task_args: The arguments fot the specific aggregation calculation.
        shared_args: The arguments shared among all workers.
    """
    time0 = time.perf_counter()
    worker_name = os.getpid()

    location = task_args.location
    vs30 = task_args.vs30
    imt = task_args.imt

    agg_types = shared_args.agg_types
    compatibility_key = shared_args.compatibility_key
    hazard_model_id = shared_args.hazard_model_id

    # the arrays below point into the shared memory but do not keep it mapped: never close() these
    # SharedMemory objects while the arrays are alive, or reading them segfaults
    branch_index_table_shm = shared_memory.SharedMemory(name=shared_args.branch_index_table_shm_name)
    branch_index_table: npt.NDArray = np.ndarray(
        shared_args.branch_index_table_shape,
        dtype=shared_args.branch_index_table_dtype,
        buffer=branch_index_table_shm.buf,
    )

    weights_shm = shared_memory.SharedMemory(name=shared_args.weights_shm_name)
    weights: npt.NDArray = np.ndarray(shared_args.weights_shape, dtype=np.float64, buffer=weights_shm.buf)

    # convert probabilities to rates
    time1 = time.perf_counter()
    component_rates_array = calculators.prob_to_rate(task_args.probs, 1.0)
    time2 = time.perf_counter()
    log.debug("worker %s: time to convert probabilities to rates %0.2f seconds", worker_name, time2 - time1)

    log.debug('worker %s: rates_table %s', worker_name, component_rates_array.shape)

    log.info("worker %s:  calculating aggregates . . . ", worker_name)
    hazard = calculate_aggs_from_components(
        branch_index_table, component_rates_array, weights, agg_types, shared_args.branch_index_columns
    )
    time3 = time.perf_counter()
    log.debug("worker %s: time to calculate aggs %0.2f seconds", worker_name, time3 - time2)

    probs = calculators.rate_to_prob(hazard, 1.0)
    if shared_args.skip_save:
        log.info("worker %s SKIPPING SAVE . . . ", worker_name)
    else:
        log.info("worker %s saving result . . . ", worker_name)
        save_aggregations(probs, location, vs30, imt, agg_types, hazard_model_id, compatibility_key)
    time4 = time.perf_counter()
    log.info("worker %s time to perform one aggregation %0.2f seconds", worker_name, time4 - time0)

calculate_aggs_from_components(branch_index_table, component_rates, weights, agg_types, columns)

Calculate weighted aggregate statistics of the composite realizations from the component realizations.

The rate of a composite realization is the sum of the rates of its component realizations. The aggregates are calculated without building the array of composite rates (see calculators.composite_rate_aggs()).

Parameters:

Name Type Description Default
branch_index_table NDArray

composite branches represented as rows of indices into component_rates

required
component_rates NDArray

component realization rates with shape (n component branches, n IMTL)

required
weights NDArray

one dimensional array of weights for composite branches with dimensions (branch,)

required
agg_types Sequence[str]

the aggregate statistics to be calculated (e.g., "mean", "0.5") with dimension (agg_type,)

required
columns Sequence[NDArray]

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

required

Returns:

Name Type Description
hazard NDArray

aggregate rates array with dimension (agg_type, IMTL)

Raises:

Type Description
IndexError

if the branch index table refers to a component branch not in component_rates.

Source code in toshi_hazard_post/aggregation_calc.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def calculate_aggs_from_components(
    branch_index_table: 'npt.NDArray',
    component_rates: 'npt.NDArray',
    weights: 'npt.NDArray',
    agg_types: Sequence[str],
    columns: Sequence['npt.NDArray'],
) -> 'npt.NDArray':
    """Calculate weighted aggregate statistics of the composite realizations from the component realizations.

    The rate of a composite realization is the sum of the rates of its component realizations. The aggregates are
    calculated without building the array of composite rates (see calculators.composite_rate_aggs()).

    Args:
        branch_index_table: composite branches represented as rows of indices into component_rates
        component_rates: component realization rates with shape (n component branches, n IMTL)
        weights: one dimensional array of weights for composite branches with dimensions (branch,)
        agg_types: the aggregate statistics to be calculated (e.g., "mean", "0.5") with dimension (agg_type,)
        columns: the component branches in each column of the branch index table (see
            logic_tree.branch_index_columns())

    Returns:
        hazard: aggregate rates array with dimension (agg_type, IMTL)

    Raises:
        IndexError: if the branch index table refers to a component branch not in component_rates.
    """
    _check_branch_index_table(branch_index_table, component_rates)
    quantile_points = _quantile_points(agg_types)
    mean, std, quantiles = calculators.composite_rate_aggs(
        branch_index_table, component_rates, weights, quantile_points, columns
    )
    return _assemble_aggs(agg_types, component_rates.shape[1], mean, std, quantiles if quantile_points else None)