Download src/eval/metrics.py from codewithyug/certified-safe-neural-control: direct link, hf CLI and curl.
- Browser
- Download file 3.63 kB
-
https://huggingface.co/codewithyug/certified-safe-neural-control/resolve/main/src/eval/metrics.py
- Command line
-
hf download hf://codewithyug/certified-safe-neural-control/src/eval/metrics.py
-
curl -L -o metrics.py https://huggingface.co/codewithyug/certified-safe-neural-control/resolve/main/src/eval/metrics.py
3.63 kB
| """ | |
| 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) | |