AgentFEM-Programmable-Soft-Rods / compare_branches.py
HaomingLuo's picture
Add runnable same-load equilibrium-branch visualization
4c3edf3 verified
Raw History Blame Contribute Delete
4.98 kB
"""Plot stored equilibria at identical controls; no solver or neural model runs.
Copyright 2026 Haoming Luo. SPDX-License-Identifier: Apache-2.0
Data and generated figures: CC BY 4.0. See the dataset card for attribution.
"""
import argparse
import gzip
import json
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
REPO = "HaomingLuo/AgentFEM-Programmable-Soft-Rods"
REVISION = "dcd30783bc4dad627f5c7d732d2adabf312d60cd"
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--data", type=Path, help="Offline states/test.jsonl.gz")
parser.add_argument("--scene", default="microforce_001")
parser.add_argument("--step", type=int, default=12)
parser.add_argument("--output", type=Path, default=Path("rod-branches.png"))
args = parser.parse_args()
path = args.data
if path is None:
from huggingface_hub import hf_hub_download
path = hf_hub_download(REPO, "states/test.jsonl.gz", repo_type="dataset",
revision=REVISION)
with gzip.open(path, "rt", encoding="utf-8") as stream:
rows = [json.loads(line) for line in stream if line.strip()]
groups = {}
for row in rows:
if row["family"] != "microforce":
continue
if row["split"] != "test":
raise ValueError("Expected test split")
key = (row["scene_id"], row["step"])
group = groups.setdefault(key, {})
branch = row["branch"]
if branch in group:
raise ValueError(f"Duplicate branch at {key}")
group[branch] = row
for key, group in groups.items():
if set(group) != {"up", "down", "straight"}:
raise ValueError(f"Incomplete branch triplet: {key}")
ref = group["straight"]
for row in group.values():
if row["controls"] != ref["controls"]:
raise ValueError(f"Different controls: {key}")
xy = np.asarray(row["centerline"], dtype=float)
if xy.shape != (65, 2) or not np.isfinite(xy).all():
raise ValueError(f"Invalid centerline: {row['id']}")
np.testing.assert_allclose(xy[-1], row["tip"], atol=1e-12)
key = (args.scene, args.step)
if key not in groups:
parser.error("Unknown scene/step. Test scenes: " +
", ".join(sorted({k[0] for k in groups})))
group = groups[key]
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 11})
fig, (shape, branchplot) = plt.subplots(1, 2, figsize=(12, 5.6),
layout="constrained")
colors = {"up": "#148b87", "down": "#b16b31", "straight": "#737b85"}
for name in ("up", "down", "straight"):
row = group[name]
xy = np.asarray(row["centerline"])
style = "--" if row["stability"] == "unstable" else "-"
shape.plot(*xy.T, style, color=colors[name], lw=2.5,
label=f"{name} ({row['stability']})")
shape.scatter(*xy[-1], color=colors[name], s=30)
sweep = sorted((r for r in rows if r["scene_id"] == args.scene
and r["branch"] == name), key=lambda r: r["step"])
branchplot.plot([r["controls"]["fx"] / r["controls"]["chi"] for r in sweep],
[r["tip"][1] for r in sweep], color=colors[name],
linestyle=style, lw=2, label=name)
control = group["straight"]["controls"]
selected = control["fx"] / control["chi"]
branchplot.axvline(selected, color="#adb5bd", ls=":", label="selected load")
shape.set(title="Same controls, three equilibria", xlabel="x / L", ylabel="y / L")
shape.set_aspect("equal", adjustable="box")
shape.legend(loc="best", fontsize=9)
branchplot.set(title="Stored equilibrium branches", xlabel="End force p / chi",
ylabel="Tip y / L")
branchplot.text(selected + .04, .02, "selected load", fontsize=9,
rotation=90, color="#626970", va="bottom")
for ax in (shape, branchplot):
ax.grid(alpha=.15)
ax.spines[["top", "right"]].set_visible(False)
fig.suptitle(f"AgentFEM | {args.scene} | sample {args.step}", fontweight="bold")
fig.supxlabel("Quasi-static angle-FE data. Dashed straight branch is unstable; not a motion trajectory.",
fontsize=10)
args.output.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(args.output, dpi=180)
plt.close(fig)
print(json.dumps({"validated_triplets": len(groups), "scene": args.scene,
"step": args.step, "controls": control,
"branches": {name: {k: row[k] for k in
("id", "tip", "stability", "lambda_min_over_chi", "residual")}
for name, row in group.items()},
"output": str(args.output)}, indent=2))
if __name__ == "__main__":
main()