"""Utilities for handling diagnostic time-step sequences with overlaps."""
from __future__ import annotations
import numpy as np
[docs]
def build_last_occurrence_step_mask(step_values) -> np.ndarray:
"""
Return indices that sort by step value and keep the last duplicate occurrence.
This is useful for diagnostics that may contain overlapping sections in time.
Parameters
----------
step_values : array-like
1D or broadcastable array of step indices / timestamps.
Returns
-------
np.ndarray
Integer indices into the original sequence, ordered by increasing step
value, with duplicate step values reduced to their last occurrence.
"""
steps = np.asarray(step_values).reshape(-1)
if steps.size <= 1:
return np.arange(steps.size, dtype=int)
# Stable sort by step value; later duplicates overwrite earlier ones.
order = np.argsort(steps, kind="stable")
last_for_value = {}
for idx in order:
key = steps[idx].item() if hasattr(steps[idx], "item") else steps[idx]
last_for_value[key] = int(idx)
# Return mask ordered by increasing step value.
return np.array([last_for_value[k] for k in sorted(last_for_value.keys())], dtype=int)