File size: 4,976 Bytes
4c3edf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"""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()