File size: 3,625 Bytes
0210a65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
54
55
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
84
85
86
87
88
89
90
91
92
93
94
"""
Metrics and Telemetry Aggregator for Safety-Critical Control
Computes the six primary metrics defined in Section 9 of the build spec.
"""

from typing import List, Dict, Any
import numpy as np


def calculate_run_metrics(history: List[Dict[str, Any]], target_miscoverage: float = 0.05) -> Dict[str, float]:
    """
    Computes key performance metrics across an episode rollout:
    1. Safety-violation rate (%)
    2. Task-completion rate (%)
    3. Empirical coverage (%)
    4. Control loop frequency (Hz)
    5. Conservatism ratio (||u - u_nom|| / ||u_nom||)
    6. Infeasibility / solver failure rate (%)
    """
    steps = len(history)
    if steps == 0:
        return {}

    # Extract arrays
    ground_truth_safeties = np.array([h["ground_truth_barrier"] for h in history])
    solve_times = np.array([h.get("solve_time_ms", 1.0) for h in history])
    u_noms = np.array([h["u_nom"] for h in history])
    u_safes = np.array([h["u_safe"] for h in history])
    is_violations = np.array([h.get("is_calib_violation", 0.0) for h in history])
    solver_statuses = [h.get("solver_status", "optimal") for h in history]

    # 1. Safety Violation Rate: fraction of steps where ground-truth barrier < 0
    num_ground_truth_violations = np.sum(ground_truth_safeties < 0.0)
    safety_violation_rate = (num_ground_truth_violations / steps) * 100.0

    # 2. Task Completion (last step reached goal within threshold)
    task_completed = float(history[-1].get("goal_reached", False)) * 100.0

    # 3. Empirical Calibration Coverage
    if len(is_violations) > 0:
        empirical_miscoverage = np.mean(is_violations)
        empirical_coverage = (1.0 - empirical_miscoverage) * 100.0
    else:
        empirical_coverage = 100.0

    # 4. Control Rate (Hz)
    mean_solve_ms = np.mean(solve_times)
    control_rate_hz = 1000.0 / max(mean_solve_ms, 0.01)

    # 5. Conservatism Ratio: relative intervention magnitude
    nom_norm = np.linalg.norm(u_noms, axis=1) + 1e-4
    intervention_norm = np.linalg.norm(u_safes - u_noms, axis=1)
    conservatism_ratio = float(np.mean(intervention_norm / nom_norm))

    # 6. Infeasibility Rate
    infeasible_steps = sum(1 for s in solver_statuses if s not in ["optimal", "OPTIMAL"])
    infeasibility_rate = (infeasible_steps / steps) * 100.0

    return {
        "total_steps": steps,
        "safety_violation_rate_pct": float(safety_violation_rate),
        "task_completion_pct": float(task_completed),
        "empirical_coverage_pct": float(empirical_coverage),
        "mean_solve_time_ms": float(mean_solve_ms),
        "control_rate_hz": float(control_rate_hz),
        "conservatism_ratio": float(conservatism_ratio),
        "infeasibility_rate_pct": float(infeasibility_rate),
    }


def compare_ablation_runs(results: Dict[str, Dict[str, float]]) -> str:
    """
    Renders formatted comparison table across benchmark configurations.
    """
    header = (
        f"{'Configuration':<24} | {'Violations (%)':<15} | {'Goal Reached (%)':<16} | "
        f"{'Coverage (%)':<13} | {'Rate (Hz)':<10} | {'Conservatism':<12}"
    )
    separator = "-" * len(header)
    lines = [header, separator]

    for config_name, m in results.items():
        line = (
            f"{config_name:<24} | "
            f"{m.get('safety_violation_rate_pct', 0.0):<15.2f} | "
            f"{m.get('task_completion_pct', 0.0):<16.1f} | "
            f"{m.get('empirical_coverage_pct', 0.0):<13.2f} | "
            f"{m.get('control_rate_hz', 0.0):<10.1f} | "
            f"{m.get('conservatism_ratio', 0.0):<12.3f}"
        )
        lines.append(line)

    return "\n".join(lines)