| |
| """ |
| Generate comparison tables for remove-all subset results in experiments_final. |
| |
| Default setup compares 4 models on: |
| experiments_final/<model>/eval_outputs_test_3k_removeall/results.eval.pth |
| |
| It prints: |
| 1) Comparable metrics table (metrics available for all loaded models) |
| 2) Full metrics table (union of supported metrics, with N/A where unavailable) |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import os |
| from collections import defaultdict |
| from typing import Dict, List, Tuple |
|
|
| import numpy as np |
| import pandas as pd |
| import torch |
|
|
|
|
| DEFAULT_MODELS: List[Tuple[str, str]] = [ |
| ("combined_v1", "combined_v1"), |
| ("no_TSDL", "no_TSDL_old_mixtures"), |
| ("metricganplus", "metricganplus_baseline"), |
| ("mossformer2", "mossformer2_baseline"), |
| ] |
|
|
| SUPPORTED_METRICS = [ |
| "scale_invariant_signal_noise_ratio", |
| "signal_noise_ratio", |
| "si_snr", |
| "pesq", |
| "td_loss", |
| "delta_ILD", |
| "delta_ITD", |
| "delta_ITD_gcc", |
| "spatial_clap_score", |
| "msclap_score", |
| ] |
|
|
| METRIC_NAMES = { |
| "scale_invariant_signal_noise_ratio": "SI-SNRi(dB)", |
| "signal_noise_ratio": "SNRi(dB)", |
| "si_snr": "SI-SNR(dB)", |
| "pesq": "PESQ", |
| "td_loss": "TD Loss", |
| "delta_ILD": "d_ILD", |
| "delta_ITD": "d_ITD(xcorr)", |
| "delta_ITD_gcc": "d_ITD(gcc)", |
| "spatial_clap_score": "CLAP(spat)", |
| "msclap_score": "CLAP(ms)", |
| } |
|
|
| LOWER_BETTER = {"td_loss", "delta_ILD", "delta_ITD", "delta_ITD_gcc"} |
| COL_W = 18 |
|
|
|
|
| def parse_model_arg(value: str) -> List[Tuple[str, str]]: |
| """ |
| Parse --models argument. |
| |
| Format: |
| "display1=folder1,display2=folder2,..." |
| """ |
| items = [] |
| for token in value.split(","): |
| token = token.strip() |
| if not token: |
| continue |
| if "=" not in token: |
| raise ValueError( |
| f"Invalid model token '{token}'. Expected format: display=folder" |
| ) |
| display, folder = token.split("=", 1) |
| display = display.strip() |
| folder = folder.strip() |
| if not display or not folder: |
| raise ValueError( |
| f"Invalid model token '{token}'. Expected non-empty display/folder." |
| ) |
| items.append((display, folder)) |
| if not items: |
| raise ValueError("No valid models parsed from --models") |
| return items |
|
|
|
|
| def load_results(pth_path: str) -> Tuple[Dict[str, np.ndarray], int, set]: |
| batches = torch.load(pth_path, map_location="cpu", weights_only=False) |
| all_metrics = defaultdict(list) |
| available_metrics = set() |
| total_samples = 0 |
|
|
| for batch in batches: |
| metadata = batch.get("metadata", []) |
| n = len(metadata) |
| total_samples += n |
|
|
| |
| available_metrics.update(set(batch.keys()) - {"metadata"}) |
|
|
| for metric in SUPPORTED_METRICS: |
| if metric not in batch: |
| continue |
| values = batch[metric] |
| |
| if isinstance(values, list) and len(values) == n: |
| all_metrics[metric].extend(values) |
| elif isinstance(values, tuple) and len(values) == n: |
| all_metrics[metric].extend(values) |
| elif isinstance(values, torch.Tensor) and values.ndim >= 1 and values.shape[0] == n: |
| all_metrics[metric].extend(values.detach().cpu().tolist()) |
|
|
| metric_arrays = {} |
| for metric, values in all_metrics.items(): |
| arr = np.asarray(values, dtype=float) |
| metric_arrays[metric] = arr |
|
|
| |
| pesq_csv = os.path.join(os.path.dirname(pth_path), "pesq_scores.csv") |
| if os.path.exists(pesq_csv): |
| try: |
| df = pd.read_csv(pesq_csv) |
| if "pesq" in df.columns: |
| pesq_vals = df["pesq"].dropna().astype(float).to_numpy() |
| if pesq_vals.size > 0: |
| metric_arrays["pesq"] = pesq_vals |
| available_metrics.add("pesq") |
| except Exception as e: |
| print(f"[WARN] Failed to read PESQ CSV ({pesq_csv}): {e}", flush=True) |
|
|
| return metric_arrays, total_samples, available_metrics |
|
|
|
|
| def get_best_per_metric( |
| metrics: List[str], |
| model_data: Dict[str, Tuple[Dict[str, np.ndarray], int]], |
| model_names: List[str], |
| ) -> Dict[str, float]: |
| best = {} |
| for metric in metrics: |
| vals = [] |
| for name in model_names: |
| metric_map, _ = model_data[name] |
| if metric not in metric_map or len(metric_map[metric]) == 0: |
| continue |
| vals.append(float(np.mean(metric_map[metric]))) |
| if not vals: |
| continue |
| best[metric] = min(vals) if metric in LOWER_BETTER else max(vals) |
| return best |
|
|
|
|
| def render_table( |
| title: str, |
| metrics: List[str], |
| model_data: Dict[str, Tuple[Dict[str, np.ndarray], int]], |
| model_names: List[str], |
| ) -> str: |
| lines = [] |
| lines.append("\n" + "=" * 170) |
| lines.append(title) |
| lines.append("=" * 170) |
|
|
| header = f"{'Model':<16}{'N':>{8}}" |
| for metric in metrics: |
| header += f"{METRIC_NAMES[metric]:>{COL_W}}" |
| lines.append(header) |
| lines.append("-" * len(header)) |
|
|
| best = get_best_per_metric(metrics, model_data, model_names) |
|
|
| for name in model_names: |
| metric_map, n_samples = model_data[name] |
| row = f"{name:<16}{n_samples:>8}" |
| for metric in metrics: |
| if metric not in metric_map or len(metric_map[metric]) == 0: |
| row += f"{'N/A':>{COL_W}}" |
| continue |
| vals = metric_map[metric] |
| mean_val = float(np.mean(vals)) |
| std_val = float(np.std(vals)) |
| marker = "*" if metric in best and abs(mean_val - best[metric]) < 1e-6 else " " |
| cell = f"{mean_val:.2f}±{std_val:.2f}" |
| row += f"{cell:>{COL_W-1}}{marker}" |
| lines.append(row) |
|
|
| return "\n".join(lines) |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser( |
| description="Generate removeall comparison tables for experiments_final." |
| ) |
| parser.add_argument( |
| "--base", |
| type=str, |
| default="experiments_final", |
| help="Base experiments directory (default: experiments_final)", |
| ) |
| parser.add_argument( |
| "--eval-dir", |
| type=str, |
| default="eval_outputs_test_3k_removeall", |
| help="Eval directory name under each model folder", |
| ) |
| parser.add_argument( |
| "--models", |
| type=str, |
| default=",".join(f"{d}={f}" for d, f in DEFAULT_MODELS), |
| help="Comma-separated display=folder list", |
| ) |
| parser.add_argument( |
| "--save", |
| type=str, |
| default="", |
| help="Optional output text file path to save printed tables", |
| ) |
| args = parser.parse_args() |
|
|
| models = parse_model_arg(args.models) |
| base = args.base |
|
|
| model_data: Dict[str, Tuple[Dict[str, np.ndarray], int]] = {} |
| model_availability: Dict[str, set] = {} |
| model_names: List[str] = [] |
|
|
| for display_name, folder_name in models: |
| pth = os.path.join(base, folder_name, args.eval_dir, "results.eval.pth") |
| if not os.path.exists(pth): |
| print(f"[SKIP] {display_name}: missing {pth}", flush=True) |
| continue |
| metric_map, n_samples, avail = load_results(pth) |
| model_data[display_name] = (metric_map, n_samples) |
| model_availability[display_name] = set(metric_map.keys()) |
| model_names.append(display_name) |
| print( |
| f"Loaded {display_name}: {n_samples} samples, metrics={sorted(metric_map.keys())}", |
| flush=True, |
| ) |
|
|
| if not model_names: |
| print("\n[ERROR] No model results loaded.\n", flush=True) |
| return |
|
|
| |
| comparable_metrics = [ |
| m |
| for m in SUPPORTED_METRICS |
| if all(m in model_availability[name] for name in model_names) |
| ] |
|
|
| |
| full_metrics = [ |
| m |
| for m in SUPPORTED_METRICS |
| if any(m in model_availability[name] for name in model_names) |
| ] |
|
|
| blocks = [] |
| blocks.append( |
| render_table( |
| f"REMOVEALL ({args.eval_dir}) — GLOBAL COMPARABLE METRICS", |
| comparable_metrics, |
| model_data, |
| model_names, |
| ) |
| ) |
| blocks.append( |
| render_table( |
| f"REMOVEALL ({args.eval_dir}) — GLOBAL FULL METRICS", |
| full_metrics, |
| model_data, |
| model_names, |
| ) |
| ) |
| blocks.append("\n" + "=" * 170) |
| blocks.append("LEGEND: * = best model for that metric") |
| blocks.append( |
| "Higher=better: SI-SNRi(dB), SNRi(dB), SI-SNR(dB), CLAP(spat), CLAP(ms)" |
| ) |
| blocks.append("Lower=better: TD Loss, d_ILD, d_ITD(xcorr), d_ITD(gcc)") |
| blocks.append("N/A = metric not available for that model") |
| blocks.append("=" * 170) |
|
|
| report = "\n".join(blocks) |
| print(report, flush=True) |
|
|
| if args.save: |
| out_path = args.save |
| with open(out_path, "w") as f: |
| f.write(report + "\n") |
| print(f"\nSaved report to: {out_path}", flush=True) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|