"""Compare three FEM futures from one thermal state. SPDX-License-Identifier: Apache-2.0""" import argparse import json from pathlib import Path import h5py import numpy as np REPO = "HaomingLuo/AgentFEM-Controlled-Transient-Heat" REVISION = "0c2d4497105487b0173bee25830047878c51588d" BRANCHES = ("maintain", "throttle", "shutdown") def load_triplets(path): """Validate all scenario groups, then return records grouped by scenario.""" groups = {} with h5py.File(path, "r") as h5: time = np.asarray(h5["common/time_s"]) assert time.ndim == 1 and np.all(np.diff(time) > 0) for key, group in h5["trajectories"].items(): record = json.loads(group.attrs["record_json"]) scenario = groups.setdefault(record["scenario_id"], {}) branch = record["branch"] assert branch not in scenario, "Duplicate branch" arrays = {k: np.asarray(group[k]) for k in ( "temperature_history_k", "source_control_w_m3", "applied_heat_rate", "thermal_content")} assert all(len(v) == len(time) and np.isfinite(v).all() for v in arrays.values()) scenario[branch] = {"id": key, "record": record, **arrays} before = time <= 300.0 assert before.any() and (time > 300.0).any() for scenario in groups.values(): assert set(scenario) == set(BRANCHES), "Incomplete triplet" assert len({v["record"]["split"] for v in scenario.values()}) == 1, "Split leakage" for branch in BRANCHES[1:]: for name in ("temperature_history_k", "source_control_w_m3"): assert np.array_equal(scenario["maintain"][name][before], scenario[branch][name][before]), "Unequal pre-intervention states" return time, groups def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--data", type=Path, help="Existing cohort.h5; otherwise download pinned 77 MB dataset") parser.add_argument("--scenario", help="Scenario id; default: first test scenario") parser.add_argument("--output", type=Path, default=Path("branch-comparison.png")) args = parser.parse_args() if args.data is None: from huggingface_hub import hf_hub_download args.data = Path(hf_hub_download(REPO, "cohort.h5", repo_type="dataset", revision=REVISION)) time, groups = load_triplets(args.data) candidates = sorted(k for k, v in groups.items() if v["maintain"]["record"]["split"] == "test") selected = args.scenario or candidates[0] if selected not in groups: parser.error("Unknown scenario. Available ids: " + ", ".join(sorted(groups))) scenario = groups[selected] import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt colors = ("#177f82", "#b47725", "#665ca5") labels = ("Maintain power", "40% power", "Shutdown") fig, axes = plt.subplots(1, 3, figsize=(14, 4.8), facecolor="#fafbf9") for branch, color, label in zip(BRANCHES, colors, labels): data = scenario[branch] peaks = np.array([s["peak_power_density_w_m3"] for s in data["record"]["parameters"]["sources"]]) command = data["source_control_w_m3"] / peaks assert np.allclose(command, command[:, :1]), "Sources have unequal commands" axes[0].plot(time, data["temperature_history_k"].max(axis=1), color=color, label=label, lw=2) axes[1].plot(time, command[:, 0] * 100, color=color, lw=2) axes[2].plot(time, (data["thermal_content"] - data["thermal_content"][0]) / 1000, color=color, lw=2) titles = ("Hottest node", "Source power command", "Heat stored since start") units = ("Temperature / K", "Fraction of full source power / %", "Thermal-content change / kJ m⁻¹") for ax, title, unit in zip(axes, titles, units): ax.set(title=title, xlabel="Time / s", ylabel=unit) ax.axvline(300, color="#7b8588", ls="--", lw=1) ax.grid(alpha=.18) ax.spines[["top", "right"]].set_visible(False) axes[0].legend(frameon=False, fontsize=9) fig.suptitle("AgentFEM · One thermal state, three power commands", x=.055, ha="left", fontsize=17) fig.text(.055, .025, f"Scenario {selected} · {scenario['maintain']['record']['split']} split · Synthetic 2D FEM, per unit depth · Intervention at 300 s", fontsize=9, color="#53626a") fig.tight_layout(rect=(0, .07, 1, .94)) fig.savefig(args.output, dpi=160) plt.close(fig) print(json.dumps({"validated_scenarios": len(groups), "selected": selected, "split": scenario["maintain"]["record"]["split"], "final_hotspot_K": {b: float(scenario[b]["temperature_history_k"][-1].max()) for b in BRANCHES}, "output": str(args.output)}, indent=2)) if __name__ == "__main__": main()