#!/usr/bin/env python3 import argparse import json from collections import defaultdict from pathlib import Path from typing import Dict, List, Optional, Set, Tuple import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt def parse_int_list(value: Optional[str]) -> Optional[Set[int]]: if not value: return None return {int(item.strip()) for item in value.split(",") if item.strip()} def load_records(json_path: Path) -> List[dict]: with json_path.open("r") as f: payload = json.load(f) if isinstance(payload, list): return payload if isinstance(payload, dict) and isinstance(payload.get("records"), list): return payload["records"] raise ValueError(f"Cannot find records in {json_path}") def group_records(records: List[dict], chunk_ids: Optional[Set[int]], max_chunks: Optional[int]) -> Dict[int, List[dict]]: grouped = defaultdict(list) for record in records: chunk_idx = int(record["chunk_idx"]) if chunk_ids is not None and chunk_idx not in chunk_ids: continue grouped[chunk_idx].append(record) grouped = dict(sorted(grouped.items())) if max_chunks is not None: grouped = dict(list(grouped.items())[:max_chunks]) return grouped def build_plot( grouped_records: Dict[int, List[dict]], output_path: Path, x_field: str, y_field: str, title: Optional[str], reverse_x: bool, figsize: Tuple[float, float], dpi: int, ) -> None: fig, ax = plt.subplots(figsize=figsize) for chunk_idx, records in grouped_records.items(): points = [] for record in records: if x_field not in record or y_field not in record: continue if record[x_field] is None or record[y_field] is None: continue points.append((float(record[x_field]), float(record[y_field]))) if not points: continue points.sort(key=lambda item: item[0]) xs, ys = zip(*points) ax.plot(xs, ys, marker="o", linewidth=1.6, markersize=3, label=f"chunk {chunk_idx}") ax.set_xlabel(x_field) ax.set_ylabel(y_field) ax.set_title(title or f"{y_field} by timestep") ax.grid(True, alpha=0.3) if reverse_x: ax.invert_xaxis() ax.legend(loc="best", fontsize="small", ncols=2) fig.tight_layout() output_path.parent.mkdir(parents=True, exist_ok=True) fig.savefig(output_path, dpi=dpi) plt.close(fig) def parse_arguments(): parser = argparse.ArgumentParser(description="Plot per-chunk residual norm curves from MAGI residual stats JSON.") parser.add_argument("json_path", type=Path, help="Path to residual stats JSON saved by --residual_stats_path.") parser.add_argument( "-o", "--output", type=Path, help="Output image path. Defaults to _residual_norms.png.", ) parser.add_argument("--chunks", type=str, help="Comma-separated chunk_idx list to plot, for example: 0,1,2.") parser.add_argument("--max-chunks", type=int, help="Plot at most this many chunks after filtering.") parser.add_argument( "--x-field", choices=["timestep", "cur_denoise_step", "denoise_idx"], default="timestep", help="Record field used for the x axis.", ) parser.add_argument( "--y-field", choices=["residual_norm", "residual_diff_norm"], default="residual_norm", help="Record field used for the y axis.", ) parser.add_argument("--reverse-x", action="store_true", help="Reverse the x axis.") parser.add_argument("--title", type=str, help="Figure title.") parser.add_argument("--figsize", type=str, default="10,6", help="Figure size as width,height.") parser.add_argument("--dpi", type=int, default=160, help="Output image DPI.") return parser.parse_args() def main(): args = parse_arguments() output_path = args.output or args.json_path.with_name(f"{args.json_path.stem}_residual_norms.png") figsize_parts = [float(part.strip()) for part in args.figsize.split(",")] if len(figsize_parts) != 2: raise ValueError("--figsize must be formatted as width,height") records = load_records(args.json_path) grouped_records = group_records(records, parse_int_list(args.chunks), args.max_chunks) if not grouped_records: raise ValueError("No records matched the requested chunks.") build_plot( grouped_records=grouped_records, output_path=output_path, x_field=args.x_field, y_field=args.y_field, title=args.title, reverse_x=args.reverse_x, figsize=(figsize_parts[0], figsize_parts[1]), dpi=args.dpi, ) print(f"Saved plot to {output_path}") if __name__ == "__main__": main()