"""Numerical routines projected from the frozen evaluation implementation.""" import math import os from collections import defaultdict, deque from datetime import datetime from zoneinfo import ZoneInfo import numpy as np DATASET_DEFAULT_CONFIG = {} assert not os.environ.get("PIDSM_ADP_LEGACY"), "Tie-sensitive legacy ADP is not supported" def _legacy_attack_detection_points(scores, nodes, node2attacks, labels): """PIDSMaker v4.0.0's original per-node walk (tied nodes enter one at a time), kept verbatim so the tie-sensitive values can be regenerated: set PIDSM_ADP_LEGACY=1. Without it the tie-safe points below are used.""" sorted_indices = np.argsort(scores)[::-1] sorted_nodes = [nodes[i] for i in sorted_indices] sorted_labels = [labels[i] for i in sorted_indices] total_attacks = len(set(attack for attacks in node2attacks.values() for attack in attacks)) detected_attacks = set() detected_attacks_percentages = [0] precisions = [0] tp = fp = 0 for i, node in enumerate(sorted_nodes): if sorted_labels[i] == 1: tp += 1 if node in node2attacks: detected_attacks.update(node2attacks[node]) else: fp += 1 precisions.append(tp / (tp + fp)) detected_attacks_percentages.append((len(detected_attacks) / total_attacks) * 100 if total_attacks else 0.0) precision_to_attacks = defaultdict(float) for precision, detected_percentage in zip(precisions, detected_attacks_percentages): precision_to_attacks[precision] = max(precision_to_attacks[precision], detected_percentage) return sorted(precision_to_attacks.items()) def _attack_detection_points(scores, nodes, node2attacks, labels): """Return attainable (precision, attacks-detected-percent) points. PIDSM_ADP_LEGACY=1 selects the original tie-sensitive walk (this rewrite is otherwise unconditional and changes best_adp epoch selection).""" if os.environ.get("PIDSM_ADP_LEGACY"): return _legacy_attack_detection_points(scores, nodes, node2attacks, labels) order = np.argsort(-np.asarray(scores), kind="stable") scores = np.asarray(scores) labels = np.asarray(labels) total_attacks = len({attack for attacks in node2attacks.values() for attack in attacks}) if not len(order): return [(0.0, 0.0)] sorted_scores = scores[order] sorted_labels = labels[order] ends = np.flatnonzero(np.r_[sorted_scores[1:] != sorted_scores[:-1], True]) + 1 cumulative_tp = np.cumsum(sorted_labels) precisions = np.r_[0.0, cumulative_tp[ends - 1] / ends] # Attack count changes only at the first score group containing that attack. first_group = {} for position in np.flatnonzero(sorted_labels == 1): group = int(np.searchsorted(ends, position, side="right")) for attack in node2attacks.get(nodes[order[position]], ()): first_group[attack] = min(group, first_group.get(attack, group)) new_attacks = np.zeros(len(ends), dtype=int) for group in first_group.values(): new_attacks[group] += 1 detected_percentages = np.r_[0.0, 100 * np.cumsum(new_attacks) / total_attacks] if total_attacks else np.zeros(len(ends) + 1) precision_to_attacks = defaultdict(float) for precision, detected_percentage in zip(precisions, detected_percentages): precision_to_attacks[precision] = max(precision_to_attacks[precision], detected_percentage) return sorted(precision_to_attacks.items()) def attack_detection_precision(scores, nodes, node2attacks, labels): """Compute ADP at attainable score thresholds; tied scores enter together.""" points = _attack_detection_points(scores, nodes, node2attacks, labels) return float(np.trapz([y for _, y in points], [x for x, _ in points]) / 100) def metrics(pred, y, nodes, node2attacks): tp = int(((pred == 1) & (y == 1)).sum()); fp = int(((pred == 1) & (y == 0)).sum()) fn = int(y.sum()) - tp; tn = len(y) - tp - fp - fn den = np.sqrt(float(tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) mcc = ((tp * tn) - (fp * fn)) / den if den else 0.0 found = {a for n, p_, y_ in zip(nodes, pred, y) if p_ == 1 and y_ == 1 for a in node2attacks.get(n, ())} # labelled alerts only, as in ADP total = len({a for s in node2attacks.values() for a in s}) return dict(tp=tp, fp=fp, precision=tp / (tp + fp) if tp + fp else float("nan"), recall=tp / (tp + fn) if tp + fn else float("nan"), mcc=mcc, attacks=len(found) / total) def adp(scores, nodes, node2attacks, y): """Tie-safe Attack Detection Precision shared with PIDSMaker.""" return attack_detection_precision(scores, nodes, node2attacks, y) def coverage_cost(scores, nodes, node2attacks): """Bound every legal descending-score ordering, including overlapping campaigns. The last required score block is the minimum, over campaigns, of that campaign's highest score. Above it all other campaigns are already covered. Inside it, the best ordering solves a small exact set-cover over missing campaigns; the worst postpones the rarest missing campaign until every nonmember has been examined. """ scores, nodes = np.asarray(scores, float), np.asarray(nodes) if scores.ndim != 1 or nodes.shape != scores.shape or len(set(nodes.tolist())) != len(nodes): raise ValueError("invalid or duplicate score/node vector") if np.isnan(scores).any(): raise ValueError("NaN ranking score") index = {node: i for i, node in enumerate(nodes.tolist())} campaigns = {} for node, attacks in node2attacks.items(): for attack in attacks: campaigns.setdefault(attack, []) if node in index: campaigns[attack].append(index[node]) if not campaigns or any(not positions for positions in campaigns.values()): raise ValueError("full coverage undefined: absent campaign") peak = {c: float(scores[ix].max()) for c, ix in campaigns.items()} cutoff = min(peak.values()) above, block = int((scores > cutoff).sum()), int((scores == cutoff).sum()) missing = [c for c in campaigns if peak[c] == cutoff] masks, counts = {}, [] for bit, c in enumerate(missing): positions = [i for i in campaigns[c] if scores[i] == cutoff] counts.append(len(positions)) for i in positions: masks[i] = masks.get(i, 0) | (1 << bit) # Exact DP is exponential only in campaigns in the last block, not graph nodes. costs = {0: 0} for mask in set(masks.values()): for covered, cost in list(costs.items()): union = covered | mask costs[union] = min(costs.get(union, len(missing) + 1), cost + 1) best = above + costs[(1 << len(missing)) - 1] worst = above + block - min(counts) + 1 order = np.lexsort((nodes, -scores)) rank = np.empty(len(scores), int) rank[order] = np.arange(1, len(scores) + 1) observed = max(int(rank[ix].min()) for ix in campaigns.values()) assert best <= observed <= worst return dict(bstar=observed, best=best, worst=worst, above=above, block=block, missing_campaigns=len(missing), cutoff=cutoff) def _time_ns(value): base, _, fraction = value.partition(".") seconds = int(datetime.strptime(base, "%Y-%m-%d %H:%M:%S") .replace(tzinfo=ZoneInfo("America/New_York")).timestamp()) return seconds * 1_000_000_000 + int((fraction or "0").ljust(9, "0")[:9]) def attack_windows(dataset): return [(_time_ns(start), _time_ns(end)) for _, start, end in DATASET_DEFAULT_CONFIG[dataset]["attack_to_time_window"]] def exposure_days(timeline, block_minutes): return len(timeline) * block_minutes / (24 * 60) def cooldown_mask(alerted, blocks, nodes, block_minutes, cooldown_hours): """Keep the first alert for a node within each chronological cooldown interval.""" keep = np.zeros(len(alerted), dtype=bool) last = {} cooldown = math.ceil(cooldown_hours * 60 / block_minutes) for i in np.flatnonzero(alerted): node, block = int(nodes[i]), int(blocks[i]) if block - last.get(node, -math.inf) >= cooldown: keep[i] = True last[node] = block return keep def rolling_cap_mask(alerted, blocks, nodes, priority, block_minutes, target): """Delete alerts from the frozen threshold stream until every rolling day meets the cap.""" if target != int(target): raise ValueError("rolling cap target must be an integer") target = int(target) keep = np.zeros(len(alerted), dtype=bool) candidates = np.flatnonzero(alerted) candidates = candidates[np.lexsort((nodes[candidates], -priority[candidates], blocks[candidates]))] recent = deque() blocks_per_day = 1440 // block_minutes for index in candidates: block = int(blocks[index]) while recent and block - recent[0] >= blocks_per_day: recent.popleft() if len(recent) < target: keep[index] = True recent.append(block) return keep def temporal_metrics(alerted, blocks, nodes, dataset, node2attacks, onsets, block_minutes): """Score alerts only in attack blocks after the node's first malicious-period event.""" block_ns = block_minutes * 60_000_000_000 windows = attack_windows(dataset) tp, found, start_delays, onset_delays, attack_delays = 0, set(), [], [], {} for i in np.flatnonzero(alerted): block_start = int(blocks[i]) * block_ns block_end = block_start + block_ns matches = [int(a) for a in node2attacks.get(int(nodes[i]), ()) if (int(a), int(nodes[i])) in onsets and block_start < windows[int(a)][1] and block_end > onsets[(int(a), int(nodes[i]))]] if matches: tp += 1 for attack in matches: if attack not in found: start_delays.append((block_end - windows[attack][0]) / 60_000_000_000) onset_delays.append((block_end - onsets[(attack, int(nodes[i]))]) / 60_000_000_000) attack_delays[attack] = start_delays[-1] # per-campaign first-alert delay (rule 5) found.add(attack) count = int(alerted.sum()) return dict(event_tp=tp, event_fp=count - tp, event_precision=tp / count if count else float("nan"), event_attacks=len(found) / len(windows) if windows else float("nan"), median_delay_minutes=float(np.median(start_delays)) if start_delays else float("nan"), median_onset_delay_minutes=float(np.median(onset_delays)) if onset_delays else float("nan"), attack_delays={int(a): float(d) for a, d in attack_delays.items()}, campaigns=len(windows)) def finite_json(value): """Undefined precision/delay stays missing, never zero or nonstandard JSON NaN.""" if isinstance(value, dict): return {str(k): finite_json(v) for k, v in value.items()} if isinstance(value, (list, tuple)): return [finite_json(v) for v in value] if isinstance(value, (float, np.floating)): return float(value) if math.isfinite(value) else None if isinstance(value, np.integer): return int(value) return value def interval(values): """The declared fixed bootstrap stream is reproducible for each reported mean.""" values = np.asarray(values, float) assert len(values) == 10 and np.isfinite(values).all() rng = np.random.default_rng(0) sample = values[rng.integers(0, len(values), (10000, len(values)))].mean(axis=1) return dict(mean=float(values.mean()), ci=np.percentile(sample, [2.5,97.5]).tolist(), min=float(values.min()), max=float(values.max()), sd=float(values.std(ddof=1)))