Spaces:
Running

hyperFVC / workflow /scripts /collect_sensor_metrics.py
lauransotomayor's picture
Mirror GitHub Pages presentation build (part 4)
d1ffd83 verified
Raw History Blame Contribute Delete
22.4 kB
#!/usr/bin/env python3
"""Collect per-class IoU metrics from sensor-profile training outputs."""
from __future__ import annotations
import argparse
import math
import os
import re
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
try:
import pandas as pd
except ModuleNotFoundError as exc:
env_python = Path(os.environ.get("ENV_PYTHON", "/home/laura/.local/share/mamba/envs/fvc_function/bin/python"))
if env_python.exists() and Path(sys.executable).resolve() != env_python.resolve():
os.execv(str(env_python), [str(env_python), str(Path(__file__).resolve()), *sys.argv[1:]])
raise SystemExit(
"pandas is required for DataFrame output. Run with the project environment, for example: "
f"{env_python} {Path(__file__).resolve()}"
) from exc
DEFAULT_OUTPUT_ROOT = Path(
"/media/laura/8402326D023263F8/calperumResearch/site1_1_DD0001/outputs_ecosystems/medium"
)
DEFAULT_SCRIPT = Path("scripts/run_sensor_profiles_in_order.sh")
DEFAULT_LOG_ROOT = Path("logs/sensor_profile_runs")
DEFAULT_MICA_SCALE = "s304_crop608"
SENSOR_PREFIXES = ("FX10_FX17", "FX10", "FX17", "MICA")
JSON_METRIC_PATTERNS = {
"best_val": "block_*_best_val_metrics.json",
"val": "block_*_val_metrics.json",
}
TEXT_METRIC_PATTERNS = {
"best_model": "best_model_metrics_block_*.txt",
"final_model": "final_model_metrics_block_*.txt",
}
LOG_METRICS = {
"log_best_test": "Test",
"log_best_val": "Validation",
}
@dataclass(frozen=True)
class Profile:
name: str
checkpoint_dir: Path
@dataclass(frozen=True)
class MetricRow:
sensor: str
variant: str
scale: str
iou_values: tuple[float, ...]
f1_values: tuple[float, ...]
miou: float
mf1: float
hiou: float
hf1: float
metric_files: int
checkpoint_dir: Path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=(
"Summarize BE/NPV/PV IoU and MIoU across sensor-profile output "
"directories produced by scripts/run_sensor_profiles_in_order.sh."
)
)
parser.add_argument("--script", type=Path, default=DEFAULT_SCRIPT)
parser.add_argument("--output-root", type=Path, default=DEFAULT_OUTPUT_ROOT)
parser.add_argument("--log-root", type=Path, default=DEFAULT_LOG_ROOT)
parser.add_argument("--mica-scale", default=DEFAULT_MICA_SCALE)
parser.add_argument(
"--metric",
choices=tuple(JSON_METRIC_PATTERNS) + tuple(TEXT_METRIC_PATTERNS) + tuple(LOG_METRICS),
default="best_val",
help="Metric files or log average blocks to summarize. Default: best_val.",
)
parser.add_argument(
"--classes",
default="BE,NPV,PV",
help="Comma-separated class names matching the IoU order. Default: BE,NPV,PV.",
)
parser.add_argument(
"--format",
choices=("tsv", "csv", "markdown"),
default="tsv",
help="Output table format. Default: tsv.",
)
parser.add_argument(
"--sort",
choices=("miou", "harmonic", "script", "sensor"),
default="miou",
help="Row ordering. Default: miou descending.",
)
parser.add_argument("--digits", type=int, default=3)
parser.add_argument(
"--include-empty",
action="store_true",
help="Include discovered profile directories even when no metric files were found.",
)
parser.add_argument(
"--include-preweights",
action="store_true",
help="Include existing *_preweights output directories. They may come from older runs.",
)
parser.add_argument(
"--include-base",
action="store_true",
help="Include unaugmented *_base profiles. By default they are excluded from five-configuration summaries.",
)
parser.add_argument(
"--include-dir",
action="store_true",
help="Append Blocks and CheckpointDir columns for auditing.",
)
parser.add_argument(
"--include-f1",
action="store_true",
help="Append per-class F1 and mean F1 columns.",
)
parser.add_argument(
"--include-harmonic",
action="store_true",
help="Append harmonic mean columns for per-class IoU and, with --include-f1, per-class F1.",
)
parser.add_argument(
"--by-sensor",
action="store_true",
help=(
"Output a per-sensor aggregated summary (best and mean MIoU / IoU_NPV / F1_NPV per "
"sensor family: MICA, FX10, FX17, FX10_FX17) instead of the per-profile table."
),
)
parser.add_argument(
"--npv-class",
default="NPV",
help="Class name used as the minority focus class in --by-sensor aggregation. Default: NPV.",
)
return parser.parse_args()
def resolve_token(token: str, output_root: Path, mica_scale: str) -> str:
value = token.strip().strip('"').strip("'")
replacements = {
"${OUTPUT_ROOT}": str(output_root),
"$OUTPUT_ROOT": str(output_root),
"${MICA_OUTPUT_SCALE}": mica_scale,
"$MICA_OUTPUT_SCALE": mica_scale,
}
for old, new in replacements.items():
value = value.replace(old, new)
return value
def discover_script_profiles(script_path: Path, output_root: Path, mica_scale: str) -> list[Profile]:
if not script_path.exists():
raise FileNotFoundError(f"Script not found: {script_path}")
lines = script_path.read_text().splitlines()
profiles: list[Profile] = []
index = 0
while index < len(lines):
if lines[index].strip() != "run_profile \\":
index += 1
continue
profile_index = index + 1
while profile_index < len(lines) and not lines[profile_index].strip():
profile_index += 1
if profile_index >= len(lines):
break
profile_name = lines[profile_index].strip().rstrip("\\").strip()
block_lines: list[str] = []
block_index = profile_index + 1
while block_index < len(lines):
stripped = lines[block_index].strip()
if stripped == "run_profile \\" or stripped.startswith("run_hyspec_preweights_after_sweep"):
break
block_lines.append(lines[block_index])
block_index += 1
block_text = "\n".join(block_lines)
match = re.search(r"CHECKPOINT_DIR_OVERRIDE=([^\s\\]+)", block_text)
if match:
checkpoint_dir = Path(resolve_token(match.group(1), output_root, mica_scale))
profiles.append(Profile(profile_name, checkpoint_dir))
index = block_index
return profiles
def discover_existing_preweights(output_root: Path, known_dirs: set[Path]) -> list[Profile]:
if not output_root.exists():
return []
profiles = []
for checkpoint_dir in sorted(output_root.glob("*_preweights")):
if checkpoint_dir.is_dir() and checkpoint_dir not in known_dirs:
profiles.append(Profile(checkpoint_dir.name, checkpoint_dir))
return profiles
def split_profile_name(checkpoint_dir: Path) -> tuple[str, str, str]:
name = checkpoint_dir.name
is_preweights = name.lower().endswith("_preweights")
base_name = name[: -len("_preweights")] if is_preweights else name
scale = ""
scale_match = re.search(r"_s(\d+)(?:_crop\d+)?$", base_name, flags=re.IGNORECASE)
if scale_match:
scale = f"{scale_match.group(1)}px"
base_name = base_name[: scale_match.start()]
sensor = "UNKNOWN"
variant = base_name
for prefix in SENSOR_PREFIXES:
if base_name.upper().startswith(prefix):
sensor = prefix
variant = base_name[len(prefix) :]
break
variant = variant or "_base"
if is_preweights:
variant = f"{variant}_preweights"
return sensor, variant, scale
def finite_values(values: Iterable[float]) -> list[float]:
return [value for value in values if math.isfinite(value)]
def mean(values: Iterable[float]) -> float:
items = finite_values(values)
return sum(items) / len(items) if items else math.nan
def harmonic_mean(values: Iterable[float]) -> float:
items = finite_values(values)
if not items:
return math.nan
if any(value < 0 for value in items):
return math.nan
if any(value == 0 for value in items):
return 0.0
return len(items) / sum(1.0 / value for value in items)
def extract_json_metrics(path: Path) -> tuple[list[float], list[float], float] | None:
text = path.read_text(errors="ignore")
iou_match = re.search(r'"iou"\s*:\s*\[(.*?)\]', text, flags=re.DOTALL)
f1_match = re.search(r'"f1"\s*:\s*\[(.*?)\]', text, flags=re.DOTALL)
miou_match = re.search(
r'"miou"\s*:\s*([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)',
text,
)
if not iou_match or not miou_match:
return None
iou_values = [float(value) for value in re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?", iou_match.group(1))]
f1_values = []
if f1_match:
f1_values = [float(value) for value in re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?", f1_match.group(1))]
return iou_values, f1_values, float(miou_match.group(1))
def extract_text_metrics(path: Path) -> tuple[list[float], list[float], float] | None:
text = path.read_text(errors="ignore")
iou_match = re.search(r"^IoU:\s*(.+)$", text, flags=re.MULTILINE)
f1_match = re.search(r"^F1 Score:\s*(.+)$", text, flags=re.MULTILINE)
miou_match = re.search(r"^MIoU:\s*([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)", text, flags=re.MULTILINE)
if not iou_match or not miou_match:
return None
iou_values = [float(value) for value in re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?", iou_match.group(1))]
f1_values = []
if f1_match:
f1_values = [float(value) for value in re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?", f1_match.group(1))]
return iou_values, f1_values, float(miou_match.group(1))
def extract_log_average_metrics(path: Path, split: str) -> tuple[list[float], list[float], float, Path] | None:
text = path.read_text(errors="ignore")
metric_pattern = re.compile(
rf"Average Metrics Across All Best Models \({re.escape(split)} Set\):\s*\n"
r"Accuracy:\s*[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?\s*\n"
r"Precision:\s*.+?\n"
r"Recall:\s*.+?\n"
r"F1 Score:\s*(?P<f1>.+?)\n"
r"IoU:\s*(?P<iou>.+?)\n"
r"MIoU:\s*(?P<miou>[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)\s*\n"
r"Average metrics across all blocks saved to\s*(?P<checkpoint>.+)",
flags=re.MULTILINE,
)
matches = list(metric_pattern.finditer(text))
if not matches:
return None
match = matches[-1]
iou_values = [
float(value)
for value in re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?", match.group("iou"))
]
f1_values = [
float(value)
for value in re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?", match.group("f1"))
]
return iou_values, f1_values, float(match.group("miou")), Path(match.group("checkpoint").strip())
def metric_files(checkpoint_dir: Path, metric: str) -> list[Path]:
if metric in JSON_METRIC_PATTERNS:
pattern = JSON_METRIC_PATTERNS[metric]
else:
pattern = TEXT_METRIC_PATTERNS[metric]
return sorted(checkpoint_dir.glob(pattern))
def collect_profile_metrics(profile: Profile, metric: str, class_count: int) -> MetricRow | None:
if not profile.checkpoint_dir.exists():
return None
extractor = extract_json_metrics if metric in JSON_METRIC_PATTERNS else extract_text_metrics
per_class_values = [[] for _ in range(class_count)]
per_class_f1_values = [[] for _ in range(class_count)]
miou_values: list[float] = []
files_used = 0
for path in metric_files(profile.checkpoint_dir, metric):
extracted = extractor(path)
if not extracted:
continue
iou_values, f1_values, miou = extracted
for class_index in range(class_count):
if class_index < len(iou_values):
per_class_values[class_index].append(iou_values[class_index])
if class_index < len(f1_values):
per_class_f1_values[class_index].append(f1_values[class_index])
miou_values.append(miou)
files_used += 1
sensor, variant, scale = split_profile_name(profile.checkpoint_dir)
if files_used == 0:
nan_values = tuple(math.nan for _ in range(class_count))
return MetricRow(
sensor,
variant,
scale,
nan_values,
nan_values,
math.nan,
math.nan,
math.nan,
math.nan,
0,
profile.checkpoint_dir,
)
iou_means = tuple(mean(values) for values in per_class_values)
f1_means = tuple(mean(values) for values in per_class_f1_values)
return MetricRow(
sensor=sensor,
variant=variant,
scale=scale,
iou_values=iou_means,
f1_values=f1_means,
miou=mean(miou_values),
mf1=mean(f1_means),
hiou=harmonic_mean(iou_means),
hf1=harmonic_mean(f1_means),
metric_files=files_used,
checkpoint_dir=profile.checkpoint_dir,
)
def collect_log_metrics(log_root: Path, split: str, class_count: int) -> list[MetricRow]:
if not log_root.exists():
return []
latest_by_checkpoint: dict[Path, tuple[Path, tuple[list[float], list[float], float, Path]]] = {}
for log_path in sorted(log_root.glob("**/*.log")):
if log_path.name.endswith(".fault.log"):
continue
extracted = extract_log_average_metrics(log_path, split)
if not extracted:
continue
checkpoint_dir = extracted[3]
previous = latest_by_checkpoint.get(checkpoint_dir)
if previous is None or log_path.stat().st_mtime >= previous[0].stat().st_mtime:
latest_by_checkpoint[checkpoint_dir] = (log_path, extracted)
rows: list[MetricRow] = []
for _log_path, (iou_values, f1_values, miou, checkpoint_dir) in latest_by_checkpoint.values():
sensor, variant, scale = split_profile_name(checkpoint_dir)
padded_iou = tuple(iou_values[index] if index < len(iou_values) else math.nan for index in range(class_count))
padded_f1 = tuple(f1_values[index] if index < len(f1_values) else math.nan for index in range(class_count))
rows.append(
MetricRow(
sensor=sensor,
variant=variant,
scale=scale,
iou_values=padded_iou,
f1_values=padded_f1,
miou=miou,
mf1=mean(padded_f1),
hiou=harmonic_mean(padded_iou),
hf1=harmonic_mean(padded_f1),
metric_files=1,
checkpoint_dir=checkpoint_dir,
)
)
return rows
def fmt(value: float, digits: int) -> str:
if not math.isfinite(value):
return ""
return f"{value:.{digits}f}"
def sort_rows(rows: list[MetricRow], mode: str) -> list[MetricRow]:
if mode == "miou":
return sorted(rows, key=lambda row: (math.isfinite(row.miou), row.miou), reverse=True)
if mode == "harmonic":
return sorted(rows, key=lambda row: (math.isfinite(row.hiou), row.hiou), reverse=True)
if mode == "sensor":
return sorted(rows, key=lambda row: (row.sensor, row.scale, row.variant))
return rows
def is_unaugmented_base_variant(variant: str) -> bool:
return "aug" not in variant.lower()
def filter_base_rows(rows: list[MetricRow], include_base: bool) -> list[MetricRow]:
if include_base:
return rows
return [row for row in rows if not is_unaugmented_base_variant(row.variant)]
def build_dataframe(rows: list[MetricRow], class_names: list[str], args: argparse.Namespace) -> pd.DataFrame:
records = []
for row in rows:
record = {
"Sensor": row.sensor,
"Variant": row.variant,
"Scale": row.scale,
}
for class_name, iou_value in zip(class_names, row.iou_values):
record[f"IoU_{class_name}"] = round(iou_value, args.digits) if math.isfinite(iou_value) else pd.NA
record["MIoU"] = round(row.miou, args.digits) if math.isfinite(row.miou) else pd.NA
if args.include_harmonic:
record["HIoU"] = round(row.hiou, args.digits) if math.isfinite(row.hiou) else pd.NA
if args.include_f1:
for class_name, f1_value in zip(class_names, row.f1_values):
record[f"F1_{class_name}"] = round(f1_value, args.digits) if math.isfinite(f1_value) else pd.NA
record["MF1"] = round(row.mf1, args.digits) if math.isfinite(row.mf1) else pd.NA
if args.include_harmonic:
record["HF1"] = round(row.hf1, args.digits) if math.isfinite(row.hf1) else pd.NA
if args.include_dir:
record["Blocks"] = row.metric_files
record["CheckpointDir"] = str(row.checkpoint_dir)
records.append(record)
columns = ["Sensor", "Variant", "Scale"] + [f"IoU_{name}" for name in class_names] + ["MIoU"]
if args.include_harmonic:
columns += ["HIoU"]
if args.include_f1:
columns += [f"F1_{name}" for name in class_names] + ["MF1"]
if args.include_harmonic:
columns += ["HF1"]
if args.include_dir:
columns += ["Blocks", "CheckpointDir"]
return pd.DataFrame.from_records(records, columns=columns)
def build_sensor_summary(
rows: list[MetricRow],
class_names: list[str],
npv_class: str,
digits: int,
) -> pd.DataFrame:
"""Aggregate per-profile rows into one row per sensor family.
For each sensor we report the best (argmax) profile for MIoU, IoU_<npv>, and
F1_<npv>, plus mean values across all profiles of that sensor.
"""
npv_index = class_names.index(npv_class) if npv_class in class_names else None
finite_rows = [row for row in rows if math.isfinite(row.miou)]
sensors_in_order: list[str] = []
for row in finite_rows:
if row.sensor not in sensors_in_order:
sensors_in_order.append(row.sensor)
# Stable preferred order, then any others trailing.
preferred = [s for s in ("MICA", "FX10", "FX17", "FX10_FX17") if s in sensors_in_order]
trailing = [s for s in sensors_in_order if s not in preferred]
sensors_ordered = preferred + trailing
records = []
for sensor in sensors_ordered:
sensor_rows = [row for row in finite_rows if row.sensor == sensor]
if not sensor_rows:
continue
def label(row: MetricRow) -> str:
scale = row.scale or "-"
return f"{row.variant}@{scale}"
best_miou = max(sensor_rows, key=lambda r: r.miou)
record: dict[str, object] = {
"Sensor": sensor,
"Profiles": len(sensor_rows),
"Best_MIoU": round(best_miou.miou, digits),
"Best_MIoU_Profile": label(best_miou),
"Mean_MIoU": round(mean(r.miou for r in sensor_rows), digits),
}
if npv_index is not None:
npv_iou_rows = [r for r in sensor_rows if math.isfinite(r.iou_values[npv_index])]
if npv_iou_rows:
best_npv_iou = max(npv_iou_rows, key=lambda r: r.iou_values[npv_index])
record[f"Best_IoU_{npv_class}"] = round(best_npv_iou.iou_values[npv_index], digits)
record[f"Best_IoU_{npv_class}_Profile"] = label(best_npv_iou)
record[f"Mean_IoU_{npv_class}"] = round(
mean(r.iou_values[npv_index] for r in npv_iou_rows), digits
)
npv_f1_rows = [r for r in sensor_rows if math.isfinite(r.f1_values[npv_index])]
if npv_f1_rows:
best_npv_f1 = max(npv_f1_rows, key=lambda r: r.f1_values[npv_index])
record[f"Best_F1_{npv_class}"] = round(best_npv_f1.f1_values[npv_index], digits)
record[f"Best_F1_{npv_class}_Profile"] = label(best_npv_f1)
record[f"Mean_F1_{npv_class}"] = round(
mean(r.f1_values[npv_index] for r in npv_f1_rows), digits
)
records.append(record)
return pd.DataFrame.from_records(records)
def write_table(rows: list[MetricRow], class_names: list[str], args: argparse.Namespace) -> None:
if args.by_sensor:
dataframe = build_sensor_summary(rows, class_names, args.npv_class, args.digits)
else:
dataframe = build_dataframe(rows, class_names, args)
if args.format == "markdown":
headers = [str(column) for column in dataframe.columns]
print("| " + " | ".join(headers) + " |")
print("| " + " | ".join("---" for _ in headers) + " |")
for values in dataframe.astype("string").fillna("").itertuples(index=False, name=None):
print("| " + " | ".join(str(value) for value in values) + " |")
return
separator = "\t" if args.format == "tsv" else ","
dataframe.to_csv(sys.stdout, sep=separator, index=False, lineterminator="\n")
def main() -> int:
args = parse_args()
class_names = [name.strip() for name in args.classes.split(",") if name.strip()]
if not class_names:
raise ValueError("At least one class name is required")
if args.metric in LOG_METRICS:
rows = collect_log_metrics(args.log_root, LOG_METRICS[args.metric], len(class_names))
else:
profiles = discover_script_profiles(args.script, args.output_root, args.mica_scale)
if args.include_preweights:
known_dirs = {profile.checkpoint_dir for profile in profiles}
profiles.extend(discover_existing_preweights(args.output_root, known_dirs))
rows = []
for profile in profiles:
row = collect_profile_metrics(profile, args.metric, len(class_names))
if row and (args.include_empty or row.metric_files > 0):
rows.append(row)
rows = filter_base_rows(rows, args.include_base)
write_table(sort_rows(rows, args.sort), class_names, args)
return 0
if __name__ == "__main__":
raise SystemExit(main())