cubie.outputhandling.summarymetrics.metrics

Summary metrics system for CUDA-accelerated batch integration.

This module provides the core infrastructure for summary metrics in the cubie integrator system, including registration and function dispatch for CUDA device functions.

Functions

register_metric(registry)

Decorator factory for registering summary metrics.

Classes

SummaryMetric([buffer_size, output_size, ...])

Abstract base class for summary metrics in the cubie integrator system.

SummaryMetrics()

Registry and dispatcher for summary metrics.

class cubie.outputhandling.summarymetrics.metrics.SummaryMetric(buffer_size: int | Callable = 0, output_size: int | Callable = 0, update_device_func: Callable = None, save_device_func: Callable = None, name: str = '', input_variable: dict[str, int] | None = None)[source]

Bases: ABC

Abstract base class for summary metrics in the cubie integrator system.

This class defines the interface for all summary metrics and holds memory requirements for buffer and output arrays, as well as dispatchers for update and save functions. All concrete metric implementations must inherit from this class and implement the abstract methods.

buffer_size

Size required in the summary buffer, or a callable that computes the size based on parameters. For parameterized metrics (like peaks), use a lambda function: lambda n: 3 + n.

Type:

int or callable, default 0

output_size

Size required in the output array, or a callable that computes the size based on parameters. For parameterized metrics (like peaks), use a lambda function: lambda n: n.

Type:

int or callable, default 0

update_device_func

CUDA device function for updating the metric during integration. Set by CUDA_factory() during initialization.

Type:

callable, default None

save_device_func

CUDA device function for saving final metric results. Set by CUDA_factory() during initialization.

Type:

callable, default None

name

Name identifier for the metric (e.g., “max”, “mean”, “peaks”).

Type:

str, default “”

input_variable

Optional input variable specifications.

Type:

dict[str, int] or None, default None

Notes

All concrete implementations must: 1. Implement __init__() to call CUDA_factory() and configure the metric 2. Implement CUDA_factory() to generate the required CUDA device functions 3. Follow the exact function signatures for update and save functions 4. Register the metric using the @register_metric(summary_metrics) decorator

The CUDA device functions must have these exact signatures: - update(value, buffer, current_index, customisable_variable) - save(buffer, output_array, summarise_every, customisable_variable)

Not included in this base class is an abstract init method, as it breaks the attrs init method. The docstring for such a method is: Initialize the summary metric.

This method must be implemented by all concrete metric classes. It should call CUDA_factory() to generate the CUDA device functions and then call super().__init__() with the appropriate parameters.

Notes

The standard implementation pattern is:

  1. Call self.CUDA_factory() to get update and save functions

  2. Call super().__init__() with: - name: string identifier for the metric - buffer_size: int or callable for buffer memory requirements - output_size: int or callable for output memory requirements - update_device_func: CUDA function from CUDA_factory() - save_device_func: CUDA function from CUDA_factory()

Examples

For a simple metric with fixed sizes: ```python def __init__(self):

update_func, save_func = self.CUDA_factory() super().__init__(

name=”mean”, buffer_size=1, output_size=1, update_device_func=update_func, save_device_func=save_func,

)

```

For a parameterized metric: ```python def __init__(self):

update_func, save_func = self.CUDA_factory() super().__init__(

name=”peaks”, buffer_size=lambda n: 3 + n, output_size=lambda n: n, update_device_func=update_func, save_device_func=save_func,

)

```

Examples

See the implemented metrics (Max, Mean, RMS, Peaks) for concrete examples of how to properly implement this interface.

abstractmethod CUDA_factory()[source]

Generate CUDA device functions for the metric.

This method must be implemented by all concrete metric classes. It should create and return the CUDA-compiled update and save functions with the exact required signatures.

Returns:

Tuple containing (update_function, save_function) for CUDA execution. Both functions must be compiled with @cuda.jit decorators.

Return type:

tuple[callable, callable]

Notes

The generated functions must have these exact signatures:

update(value, buffer, current_index, customisable_variable):

Called during each integration step to update running calculations.

Parameters: - value (float): New variable value to process - buffer (array): Buffer for storing intermediate calculations - current_index (int): Current integration step number - customisable_variable (int): Parameter for metric configuration

save(buffer, output_array, summarise_every, customisable_variable):

Called at summary intervals to compute final results and reset buffers.

Parameters: - buffer (array): Buffer containing intermediate calculations - output_array (array): Array to store final metric results - summarise_every (int): Number of steps between summary saves - customisable_variable (int): Parameter for metric configuration

Both functions must be decorated with: @cuda.jit([“float32, float32[::1], int64, int64”,

“float64, float64[::1], int64, int64”],

device=True, inline=True)

Examples

For a simple maximum value metric: ```python def CUDA_factory(self):

@cuda.jit([…], device=True, inline=True) def update(value, buffer, current_index, customisable_variable):

if value > buffer[0]:

buffer[0] = value

@cuda.jit([…], device=True, inline=True) def save(

buffer, output_array, summarise_every, customisable_variable

):

output_array[0] = buffer[0] buffer[0] = -1.0e30 # Reset for next period

return update, save

```

For a mean calculation metric: ```python def CUDA_factory(self):

@cuda.jit([…], device=True, inline=True) def update(value, buffer, current_index, customisable_variable):

buffer[0] += value # Accumulate sum

@cuda.jit([…], device=True, inline=True) def save(

buffer, output_array, summarise_every, customisable_variable

):

output_array[0] = buffer[0] / summarise_every buffer[0] = 0.0 # Reset for next period

return update, save

```

buffer_size: int | Callable
input_variable: dict[str, int] | None
name: str
output_size: int | Callable
save_device_func: Callable
update_device_func: Callable
class cubie.outputhandling.summarymetrics.metrics.SummaryMetrics[source]

Bases: object

Registry and dispatcher for summary metrics.

This class holds the complete set of implemented summary metrics and provides summary information to other modules. It manages memory layout, function dispatch, and parameter handling for all registered metrics.

_names

List of registered metric names.

Type:

list[str]

_buffer_sizes

Buffer size requirements for each metric.

Type:

dict[str, int or callable]

_output_sizes

Output size requirements for each metric.

Type:

dict[str, int or callable]

_save_functions

Save functions for each metric.

Type:

dict[str, callable]

_update_functions

Update functions for each metric.

Type:

dict[str, callable]

_metric_objects

Complete metric objects for each registered metric.

Type:

dict[str, SummaryMetric]

_params

Parameters for each metric.

Type:

dict[str, Any]

Notes

All methods consistently return data only for requested metrics, not for all implemented metrics. This allows efficient compilation of only the needed functionality.

The class provides: - implemented_metrics: List of available metric names - buffer_offsets/sizes: Memory layout for summary buffers - output_offsets/sizes: Memory layout for output arrays - save/update_functions: CUDA device functions for metrics - params: Parameter values for parameterized metrics

_get_size(metric_name, size_dict)[source]

Calculate size based on parameters if needed.

Parameters:
  • metric_name (str) – Name of the metric.

  • size_dict (dict) – Dictionary containing size specifications.

Returns:

Calculated size for the metric.

Return type:

int

Warning

UserWarning

If a callable size has parameter set to 0.

buffer_offsets(output_types_requested)[source]

Get buffer starting offsets for requested summary metrics.

Parameters:

output_types_requested (list[str]) – List of metric names to generate offsets for.

Returns:

Buffer starting offsets for the requested metrics.

Return type:

tuple[int]

buffer_sizes(output_types_requested)[source]

Get buffer sizes for requested summary metrics.

Parameters:

output_types_requested (list[str]) – List of metric names to generate sizes for.

Returns:

Buffer sizes for the requested metrics.

Return type:

tuple[int]

property implemented_metrics

Get list of all registered summary metric names.

Returns:

Names of all registered summary metrics.

Return type:

list[str]

legend(output_types_requested)[source]

Generate column headings for requested summary metrics.

Parameters:

output_types_requested (list[str]) – List of metric names to generate headings for.

Returns:

Column headings for the metrics in order.

Return type:

list[str]

Notes

For metrics with output_size=1, the heading is just the metric name. For metrics with output_size>1, the headings are {name}_1, {name}_2, etc.

output_offsets(output_types_requested)[source]

Get output array starting offsets for requested summary metrics.

Parameters:

output_types_requested (list[str]) – List of metric names to generate offsets for.

Returns:

Output array starting offsets for the requested metrics.

Return type:

tuple[int]

output_offsets_dict(output_types_requested)[source]

Get output array offsets as a dictionary for requested metrics.

Parameters:

output_types_requested (list[str]) – List of metric names to generate offsets for.

Returns:

Dictionary with metric names as keys and their offsets as values.

Return type:

dict[str, int]

output_sizes(output_types_requested)[source]

Get output array sizes for requested summary metrics.

Parameters:

output_types_requested (list[str]) – List of metric names to generate sizes for.

Returns:

Output array sizes for the requested metrics.

Return type:

tuple[int]

params(output_types_requested: list[str])[source]

Get parameters for requested summary metrics.

Parameters:

output_types_requested (list[str]) – List of metric names to get parameters for.

Returns:

Parameter values for the requested metrics.

Return type:

tuple[Any]

parse_string_for_params(dirty_request: list[str])[source]

Extract parameters from metric specification strings.

Parameters:

dirty_request (list[str]) – List of metric specifications that may contain parameters in the format ‘metric[param]’.

Returns:

List of metrics with any [param] stripped

Return type:

list[str]

Notes

Any params stripped from the string are saved in self._params, keyed by ‘metric’ name.

preprocess_request(request)[source]

Parse parameters from metric specifications and validate.

Parameters:

request (list[str]) – List of metric specifications, potentially with parameters.

Returns:

List of validated metric names with parameters extracted.

Return type:

list[str]

Notes

Parses metric specifications like ‘peaks[3]’ to extract parameters and validates that all requested metrics are registered. Issues warnings for unregistered metrics.

register_metric(metric: SummaryMetric)[source]

Register a new summary metric with the system.

Parameters:

metric (SummaryMetric) – A SummaryMetric instance to register.

Raises:

ValueError – If a metric with the same name is already registered.

Notes

Once registered, the metric becomes available for use in output configurations and will be automatically included in update and save function chains when requested.

save_functions(output_types_requested)[source]

Get save functions for requested summary metrics.

Parameters:

output_types_requested (list[str]) – List of metric names to get save functions for.

Returns:

CUDA device save functions for the requested metrics.

Return type:

tuple[callable]

summaries_buffer_height(output_types_requested)[source]

Calculate total buffer size for requested summary metrics.

Parameters:

output_types_requested (list[str]) – List of metric names to calculate total buffer size for.

Returns:

Total buffer size needed for all requested metrics.

Return type:

int

summaries_output_height(output_types_requested)[source]

Calculate total output size for requested summary metrics.

Parameters:

output_types_requested (list[str]) – List of metric names to calculate total output size for.

Returns:

Total output size needed for all requested metrics.

Return type:

int

update_functions(output_types_requested)[source]

Get update functions for requested summary metrics.

Parameters:

output_types_requested (list[str]) – List of metric names to get update functions for.

Returns:

CUDA device update functions for the requested metrics.

Return type:

tuple[callable]

cubie.outputhandling.summarymetrics.metrics.register_metric(registry)[source]

Decorator factory for registering summary metrics.

Parameters:

registry (SummaryMetrics) – The registry instance to register the metric with.

Returns:

Decorator function that registers a metric class.

Return type:

callable

Notes

This decorator automatically creates an instance of the decorated class and registers it with the provided registry.