Skip to content

Events: delay and false alarms

← Events

A fault is not one sample: it lasts. EventMetrics takes the labelled event windows, then the alarm times, and answers the two questions an operator asks first: how late was the alarm, and how often does it ring for nothing? An event with no alarm inside is missed. A robot controller with fault alarms is judged the same way, in the last section.

The mean detection delay of the flash crashes of 60 s on a stock tick, for 25 alarm thresholds and 25 shifts of the event.

1. A first example: flash crashes on a stock tick

Two flash crashes were labelled: seconds 10 to 20 and seconds 40 to 45. The detector rang at 5, 12, 12.5 and 30 seconds, over one hour of normal operation.

from dense_armor.core.evaluation.metrics import EventMetrics

m = EventMetrics([(10.0, 20.0), (40.0, 45.0)], dt=0.5, normal_time_s=3600.0)
for t in (5.0, 12.0, 12.5, 30.0):
    m.add_alarm(t)
print(m.detection_delays_s(), m.missed_events(), m.false_alarms(), m.false_alarms_per_hour())
[2.0, None] 1 2 2.0

The first crash starts at 10 s and the first alarm inside it is at 12 s: delay 2 s. The second crash has no alarm: missed. The alarms at 5 s and 30 s are outside every event: two false alarms over one hour of normal operation, 2 per hour. dt is the sample period, used to count the points of a window on the next pages.

A stock tick with a flash crash of 60 s: the labelled event, and the alarms of the threshold 2.5.

The figure shows 180 s of the stream around the first crash. With a shift of 3 and the threshold 2.5 the four crashes are caught with delays of 0, 0, 2 and 0 s and none is missed, and over the 3360 s of normal operation the detector rings 28 times for nothing, 30.0 per hour.

The event window

EventMetrics takes a list of (start, end) tuples. Internally these are validated as EventWindow objects: a frozen dataclass with start and end (seconds), where end >= start is enforced. It provides contains(t) to test whether a time stamp falls inside, and n_points(dt) to compute how many discrete samples the window covers at a given sample period dt.

from dense_armor.core.evaluation.metrics import EventWindow

ew = EventWindow(start=10.0, end=20.0)
print(f"contains(15.0): {ew.contains(15.0)}")
print(f"n_points(dt=1.0): {ew.n_points(1.0)}")
contains(15.0): True
n_points(dt=1.0): 11

Count by hand: a window from 10.0 to 20.0 s at dt=1.0 covers the points 10.0, 11.0, …, 20.0, that is 11 points. At dt=0.5 it would be 21 points. The formula is round((end - start) / dt) + 1, with a minimum of 1.

EventWindow raises ValueError if end < start or if n_points is called with dt <= 0. It is a plain data carrier; EventMetrics builds a list of EventWindow objects from the input tuples and uses their contains and n_points methods for all range-based calculations.

The picture follows the same 3600 seconds of a stock tick, with four flash crashes of 60 s in which the mean of the tick shifts, and a detector that rings on every sample above a threshold c. Each point of the surface is the mean detection delay of the crashes it caught, for 25 thresholds and 25 shifts; where no crash was caught there is a gap. With a shift of 2.98 the alarms come at the first second of the crash or at the third: for the threshold 3.0 the four delays are 0, 0, 2 and 0 s. With a shift of 1.52 and the same threshold the delays are 2, 5, 21 and 11 s, mean 9.75 s. The threshold also decides the false alarms: over the 3360 s of normal operation the threshold 3.0 rings 7 times for nothing (7.5 per hour), the threshold 2.0 rings 75 times (80.36 per hour) and the threshold 1.0 rings 559 times (598.93 per hour).

class what it does
EventMetrics collects the alarms against the labelled windows and reports the metrics of the events
EventWindow one labelled event interval, with contains and n_points

2. What the metric keeps

EventMetrics keeps the labelled windows and the alarm times. The delay of an event is the time of the first alarm inside the window minus the start of the window, or None if there is none; a false alarm is an alarm outside every window; the false alarms per hour are their number divided by the normal time in hours. If normal_time_s is not given, the normal time is inferred from the first and last alarm time stamps minus the event durations. Two alarms within threshold_window seconds are the same detection (default 0).

Source: the docstring of the module dense_armor.core.evaluation.metrics.events explains that in event detection the target is a set of intervals and that two alarms close together are one event, and an alarm outside every labelled event is a false alarm. The delay, the missed events and the false alarms are not attributed to a paper; the module lists three papers for the other metrics: Tatbul et al. (2018), Lavin and Ahmad (2015) and Xu et al. (2018) with Kim et al. (2021).

3. The parameters

Parameter Meaning Default
events the labelled event windows, as EventWindow or (start, end) pairs none
dt sample period in seconds, used to count the discrete points of a window 1.0
normal_time_s total normal time in seconds, the denominator of false alarms per hour None
threshold_window two alarms within this many seconds are the same detection 0.0

The other parameters (alpha, positional_bias, cardinality, a_tp, a_fp, a_fn) belong to the range metrics and to the NAB score, on their pages. EventMetrics raises ValueError on a bad bias, an empty events, or out-of-range weights.

4. The same metrics on a robot joint

A joint controller raises a fault alarm, and the maintenance log says when the faults really were: from 2 s to 4 s and from 9 s to 10 s, in one minute of normal operation, sampled at 100 Hz. The controller rang at 1.0, 3.5, 6.0 and 9.2 seconds.

from dense_armor.core.evaluation.metrics import EventMetrics

m = EventMetrics([(2.0, 4.0), (9.0, 10.0)], dt=0.01, normal_time_s=60.0)
for t in (1.0, 3.5, 6.0, 9.2):
    m.add_alarm(t)
print([round(v, 2) for v in m.detection_delays_s()], m.missed_events(), m.false_alarms(), m.false_alarms_per_hour())
[1.5, 0.2] 0 2 120.0

The first fault starts at 2 s and the alarm at 3.5 s is the first inside it: delay 1.5 s. The second starts at 9 s and the alarm at 9.2 s gives 0.2 s. The alarms at 1.0 s and 6.0 s are outside both faults: two false alarms in one minute, that is \(2 / (60/3600) = 120\) per hour.

API reference

EventMetrics

EventMetrics(
    events: Iterable[EventWindow | tuple[float, float]],
    dt: float = 1.0,
    alpha: float = 0.0,
    positional_bias: str = "front",
    cardinality: bool = True,
    normal_time_s: float | None = None,
    threshold_window: float = 0.0,
    a_tp: float = 1.0,
    a_fp: float = -0.11,
    a_fn: float = -1.0,
)

Collect the event metrics for a stream of alarms.

Feed the labelled windows once, then each alarm as it happens. report() returns all the metrics in one dict.

Parameters:

Name Type Description Default
events Iterable[EventWindow | tuple[float, float]]

the labelled event windows, as :class:EventWindow or as (start, end) pairs.

required
dt float

sample period in seconds, used to count the discrete points of a window. Default 1.0 (one point per second).

1.0
alpha float

existence-reward weight of Tatbul et al. (2018), in [0, 1]. 0 ignores existence and rewards only overlap.

0.0
positional_bias str

one of "flat", "front", "back", "middle". Used for recall; precision always uses flat.

'front'
cardinality bool

whether the cardinality factor of equation 7 penalises a real event split across several predictions.

True
normal_time_s float | None

total normal time in seconds, used as the denominator of false alarms per hour. If None, it is inferred from the first and last alarm timestamps minus the event durations.

None
threshold_window float

two alarms within this many seconds are the same detection. Default 0.0.

0.0
a_tp float

NAB weight of a true positive (Lavin and Ahmad 2015), in [0, 1]; standard profile 1.0.

1.0
a_fp float

NAB weight of a false positive, in [-1, 0]; standard profile -0.11.

-0.11
a_fn float

NAB weight of a missed window, in [-1, 0]; standard profile -1.0.

-1.0

Raises:

Type Description
ValueError

on a bad bias, an empty events, or out-of-range weights.

Examples:

>>> from dense_armor.core.evaluation.metrics import EventMetrics
>>> m = EventMetrics([(10.0, 20.0), (40.0, 45.0)], dt=0.5, normal_time_s=3600.0)
>>> for t in (5.0, 12.0, 12.5, 30.0):
...     _ = m.add_alarm(t)
>>> m.detection_delays_s(), m.missed_events(), m.false_alarms()
([2.0, None], 1, 2)
Source code in dense_armor/core/evaluation/metrics/events.py
def __init__(
    self,
    events: Iterable[EventWindow | tuple[float, float]],
    dt: float = 1.0,
    alpha: float = 0.0,
    positional_bias: str = "front",
    cardinality: bool = True,
    normal_time_s: float | None = None,
    threshold_window: float = 0.0,
    a_tp: float = 1.0,
    a_fp: float = -0.11,
    a_fn: float = -1.0,
) -> None:
    if dt <= 0.0:
        raise ValueError(f"dt must be > 0, got {dt}")
    self.events: list[EventWindow] = []
    for e in events:
        if isinstance(e, EventWindow):
            self.events.append(e)
        else:
            self.events.append(EventWindow(float(e[0]), float(e[1])))
    if not self.events:
        raise ValueError("EventMetrics needs at least one event window")
    if not 0.0 <= alpha <= 1.0:
        raise ValueError(f"alpha must be in [0, 1], got {alpha}")
    if not 0.0 <= a_tp <= 1.0:
        raise ValueError(f"a_tp must be in [0, 1], got {a_tp}")
    if not -1.0 <= a_fp <= 0.0:
        raise ValueError(f"a_fp must be in [-1, 0], got {a_fp}")
    if not -1.0 <= a_fn <= 0.0:
        raise ValueError(f"a_fn must be in [-1, 0], got {a_fn}")
    self.dt = dt
    self.alpha = alpha
    self.positional_bias = positional_bias
    self._bias_recall = _PositionalBias.get(positional_bias)
    self._bias_precision = _PositionalBias.get("flat")
    self.cardinality = cardinality
    self.normal_time_s = normal_time_s
    self.threshold_window = threshold_window
    self.a_tp = a_tp
    self.a_fp = a_fp
    self.a_fn = a_fn
    self.alarms_: list[float] = []

add_alarm

add_alarm(t: float) -> EventMetrics

Register an alarm at time t (seconds).

Source code in dense_armor/core/evaluation/metrics/events.py
def add_alarm(self, t: float) -> "EventMetrics":
    """Register an alarm at time ``t`` (seconds)."""
    self.alarms_.append(float(t))
    return self

detection_delays_s

detection_delays_s() -> list[float | None]

Delay in seconds for every event, None if it was missed.

Source code in dense_armor/core/evaluation/metrics/events.py
def detection_delays_s(self) -> list[float | None]:
    """Delay in seconds for every event, ``None`` if it was missed."""
    return [self._delay_for(e) for e in self.events]

missed_events

missed_events() -> int

Number of event windows with no alarm inside.

Source code in dense_armor/core/evaluation/metrics/events.py
def missed_events(self) -> int:
    """Number of event windows with no alarm inside."""
    return sum(1 for d in self.detection_delays_s() if d is None)

false_alarms

false_alarms() -> int

Number of alarms outside every event window.

Source code in dense_armor/core/evaluation/metrics/events.py
def false_alarms(self) -> int:
    """Number of alarms outside every event window."""
    return sum(1 for t in self.alarms_ if self._is_false_alarm(t))

false_alarms_per_hour

false_alarms_per_hour() -> float

False alarms divided by the observed normal time in hours.

Source code in dense_armor/core/evaluation/metrics/events.py
def false_alarms_per_hour(self) -> float:
    """False alarms divided by the observed normal time in hours."""
    fa = self.false_alarms()
    if self.normal_time_s is not None:
        hours = self.normal_time_s / 3600.0
    elif not self.alarms_:
        return 0.0
    else:
        t_lo = min(self.alarms_)
        t_hi = max(self.alarms_)
        span = t_hi - t_lo
        in_events = sum(
            max(0.0, min(e.end, t_hi) - max(e.start, t_lo))
            for e in self.events
        )
        hours = max(0.0, span - in_events) / 3600.0
    if hours <= 0.0:
        return 0.0
    return fa / hours

range_recall

range_recall() -> float

Range-based recall of Tatbul et al. (2018), equation 3.

Source code in dense_armor/core/evaluation/metrics/events.py
def range_recall(self) -> float:
    """Range-based recall of Tatbul et al. (2018), equation 3."""
    alarms = self._merged_alarms()
    if not self.events:
        return 0.0
    total = 0.0
    for e in self.events:
        ex = self._existence_reward(e)
        ov = self._overlap_reward(e, alarms, self._bias_recall)
        total += self.alpha * ex + (1.0 - self.alpha) * (
            self._cardinality_factor(e, alarms) * ov
        )
    return total / len(self.events)

range_precision

range_precision() -> float

Range-based precision of Tatbul et al. (2018), equation 8.

Precision always uses the flat positional bias (Section 5).

Source code in dense_armor/core/evaluation/metrics/events.py
def range_precision(self) -> float:
    """Range-based precision of Tatbul et al. (2018), equation 8.

    Precision always uses the flat positional bias (Section 5).
    """
    alarms = self._merged_alarms()
    if not alarms:
        return 0.0
    total = 0.0
    for a in alarms:
        ov = 0.0
        for e in self.events:
            if _has_overlap(a, e, self.dt):
                ov += self._overlap_reward(a, [e], self._bias_precision)
        card = 1.0
        if self.cardinality:
            n_overlap = sum(
                1 for e in self.events if _has_overlap(a, e, self.dt)
            )
            if n_overlap > 1:
                card = 1.0 / n_overlap
        total += card * ov
    return total / len(alarms)

range_f1

range_f1() -> float

Harmonic mean of :meth:range_precision and :meth:range_recall.

Source code in dense_armor/core/evaluation/metrics/events.py
def range_f1(self) -> float:
    """Harmonic mean of :meth:`range_precision` and :meth:`range_recall`."""
    p = self.range_precision()
    r = self.range_recall()
    return 2.0 * p * r / (p + r) if (p + r) > 0 else 0.0

nab_score

nab_score() -> float

Normalised NAB score of Lavin and Ahmad (2015), equation 4.

The score uses the scaled sigmoid of Figure 3, s(y) = 2 / (1 + exp(5 y)) - 1, with y = -1 at the window start and y = 0 at the window end. Each window contributes a_tp * s(y) for its earliest detection, or a_fn if missed; each false alarm contributes |a_fp| * s(y) with y measured after the preceding window, and -|a_fp| when no window precedes it (Figure 3).

Returns:

Type Description
float

The score; 100 for the perfect detector, 0 for the null one,

float

and a negative value for a detector worse than the null one

float

(the score is not clamped at 0).

Source code in dense_armor/core/evaluation/metrics/events.py
def nab_score(self) -> float:
    """Normalised NAB score of Lavin and Ahmad (2015), equation 4.

    The score uses the scaled sigmoid of Figure 3,
    ``s(y) = 2 / (1 + exp(5 y)) - 1``, with ``y = -1`` at the
    window start and ``y = 0`` at the window end. Each window
    contributes ``a_tp * s(y)`` for its earliest detection, or
    ``a_fn`` if missed; each false alarm contributes
    ``|a_fp| * s(y)`` with ``y`` measured after the preceding
    window, and ``-|a_fp|`` when no window precedes it (Figure 3).

    Returns:
        The score; 100 for the perfect detector, 0 for the null one,
        and a negative value for a detector worse than the null one
        (the score is not clamped at 0).
    """
    raw = 0.0
    for e in self.events:
        hits = [t for t in self.alarms_ if e.contains(t)]
        if hits:
            first = min(hits)
            raw += self.a_tp * _nab_sigmoid(self._nab_y_tp(e, first))
        else:
            raw += self.a_fn
    for t in self.alarms_:
        if self._is_false_alarm(t):
            y = self._nab_y_fp(t)
            s_fp = -1.0 if y is None else _nab_sigmoid(y)
            raw += abs(self.a_fp) * s_fp
    s_null = self.a_fn * len(self.events)
    s_perfect = self.a_tp * _nab_sigmoid(-1.0) * len(self.events)
    denom = s_perfect - s_null
    if denom == 0.0:
        return 0.0
    return 100.0 * (raw - s_null) / denom

report

report() -> dict

Return all event metrics in one dict.

Returns:

Type Description
dict

A dict with detection_delays_s (list, one per event,

dict

None for missed), mean_delay_s, missed,

dict

false_alarms, false_alarms_per_hour,

dict

range_precision, range_recall, range_f1, and

dict

nab_score.

Source code in dense_armor/core/evaluation/metrics/events.py
def report(self) -> dict:
    """Return all event metrics in one dict.

    Returns:
        A dict with ``detection_delays_s`` (list, one per event,
        ``None`` for missed), ``mean_delay_s``, ``missed``,
        ``false_alarms``, ``false_alarms_per_hour``,
        ``range_precision``, ``range_recall``, ``range_f1``, and
        ``nab_score``.
    """
    delays = self.detection_delays_s()
    seen = [d for d in delays if d is not None]
    return {
        "detection_delays_s": delays,
        "mean_delay_s": sum(seen) / len(seen) if seen else None,
        "missed": self.missed_events(),
        "false_alarms": self.false_alarms(),
        "false_alarms_per_hour": self.false_alarms_per_hour(),
        "range_precision": self.range_precision(),
        "range_recall": self.range_recall(),
        "range_f1": self.range_f1(),
        "nab_score": self.nab_score(),
    }

EventWindow dataclass

EventWindow(start: float, end: float)

A labelled event interval.

Attributes:

Name Type Description
start float

start time of the event, in seconds.

end float

end time of the event, in seconds; end >= start.

Raises:

Type Description
ValueError

if end < start.

Examples:

>>> from dense_armor.core.evaluation.metrics import EventWindow
>>> w = EventWindow(start=10.0, end=20.0)
>>> w.contains(15.0), w.n_points(1.0)
(True, 11)

n_points

n_points(dt: float) -> int

Number of discrete points in the window at period dt.

A window [start, end] sampled at period dt covers the points start, start+dt, ..., end; the count is round((end - start) / dt) + 1.

Source code in dense_armor/core/evaluation/metrics/events.py
def n_points(self, dt: float) -> int:
    """Number of discrete points in the window at period ``dt``.

    A window ``[start, end]`` sampled at period ``dt`` covers the
    points ``start, start+dt, ..., end``; the count is
    ``round((end - start) / dt) + 1``.
    """
    if dt <= 0.0:
        raise ValueError(f"dt must be > 0, got {dt}")
    return max(1, round((self.end - self.start) / dt) + 1)

Details

Choices

  • Base implementation: EventMetrics is not a Metric: it collects alarms and answers with several numbers, and report() returns all of them in one dict.
  • The figures are drawn with the library by docs/assets/metrics/make_events_figures.py. One stream of 3600 one-second samples of N(0, 1) noise with four events of 60 s at 600, 1400, 2200 and 3000 s in which the mean shifts; the same noise for every shift. The surface uses 25 thresholds from 1 to 4 and 25 shifts from 0.5 to 4; the second figure uses the shift 3 and the threshold 2.5.