File size: 5,827 Bytes
148bb80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
108
109
"""Compare published peak responses without downloading the 1.12 GiB fields.

pip install numpy matplotlib huggingface_hub
python compare_excitations.py
python compare_excitations.py --index index.jsonl --configuration 119
SPDX-License-Identifier: Apache-2.0
Data: HaomingLuo/AgentFEM-Structural-Dynamics-Virtual-Sensing, CC BY 4.0.
"""
import argparse
import json
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np

REPO = "HaomingLuo/AgentFEM-Structural-Dynamics-Virtual-Sensing"
REVISION = "b171870a1efddf858245cf2ecf92f96b2280c47a"
KINDS = ("half_sine_pulse", "sub_resonant_sine", "near_resonant_sine", "chirp")
LABELS = ("Pulse", "Sub-resonant\nsine", "Near-resonant\nsine", "Chirp")


def load_cases(path):
    rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
    cases = {}
    for row in rows:
        case = cases.setdefault(row["configuration_id"], {})
        if row["excitation"] in case:
            raise ValueError("Duplicate configuration/excitation pair")
        case[row["excitation"]] = row
    if len(rows) != 512 or len(cases) != 128:
        raise ValueError("Expected the pinned v1.1 release: 512 trajectories / 128 configurations")
    fields = ("length_m", "height_m", "young_pa", "density_kg_m3", "damping_ratio",
              "traction_amplitude_pa", "first_frequency_hz", "split", "protocol_role")
    for case in cases.values():
        if set(case) != set(KINDS):
            raise ValueError("Missing excitation")
        reference = case[KINDS[0]]
        for row in case.values():
            if any(row[key] != reference[key] for key in fields):
                raise ValueError("Comparisons require the same physical configuration")
            peak = row["max_abs_tip_displacement_m"]
            if not np.isfinite(peak) or peak <= 0:
                raise ValueError("Invalid peak displacement")
    return cases


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--index", type=Path, help="Local v1.1 index; omit to download only the index")
    parser.add_argument("--configuration", type=int, default=119)
    parser.add_argument("--output", type=Path, default=Path("excitation-comparison.png"))
    args = parser.parse_args()
    if args.index is None:
        from huggingface_hub import hf_hub_download
        args.index = Path(hf_hub_download(REPO, "index.jsonl", repo_type="dataset", revision=REVISION))
    cases = load_cases(args.index)
    if args.configuration not in cases:
        parser.error("configuration must be an integer from 0 to 127")
    case = cases[args.configuration]
    reference = case[KINDS[0]]
    peaks = np.array([case[k]["max_abs_tip_displacement_m"] * 1000 for k in KINDS])
    plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 10})
    fig, axes = plt.subplots(1, 2, figsize=(12, 5.3))
    ax = axes[0]
    bars = ax.bar(np.arange(4), peaks, color=["#7792a2", "#368b90", "#c58a43", "#746899"], width=.62)
    ax.bar_label(bars, labels=[f"{p:.4f}" for p in peaks], padding=5, fontsize=9)
    ax.set_xticks(np.arange(4), LABELS)
    ax.set_ylim(0, max(peaks) * 1.24)
    ax.set_ylabel("Peak absolute tip displacement / mm")
    ax.set_title(f"One structure, four load histories\nConfiguration {args.configuration:04d} · {reference['split']}", loc="left", pad=12)
    ax = axes[1]
    roles = [("id", "Test ID", "#368b90"), ("excitation_ood", "Excitation OOD", "#c58a43"),
             ("parameter_ood", "Parameter OOD", "#746899")]
    upper = 0.0
    counts = {}
    for role, label, color in roles:
        selected = [c for c in cases.values() if c[KINDS[0]]["split"] == "test" and c[KINDS[0]]["protocol_role"] == role]
        counts[role] = len(selected)
        x = np.array([c["sub_resonant_sine"]["max_abs_tip_displacement_m"] * 1000 for c in selected])
        y = np.array([c["near_resonant_sine"]["max_abs_tip_displacement_m"] * 1000 for c in selected])
        upper = max(upper, float(max(x.max(), y.max())))
        ax.scatter(x, y, label=f"{label} ({len(selected)})", color=color, s=38, zorder=3)
    if counts != {"id": 8, "excitation_ood": 4, "parameter_ood": 4}:
        raise ValueError("Unexpected frozen test cohorts")
    ax.plot([0, upper * 1.08], [0, upper * 1.08], "--", color="#8b9498", lw=1, label="Equal peak response")
    ax.set(xlim=(0, upper * 1.08), ylim=(0, upper * 1.08),
           xlabel="Sub-resonant sine peak / mm", ylabel="Near-resonant sine peak / mm")
    ax.set_title("Paired responses on 16 test structures\nOne point = one physical configuration", loc="left", pad=12)
    ax.legend(frameon=False, fontsize=8, loc="lower right")
    for ax in axes:
        ax.spines[["top", "right"]].set_visible(False)
        ax.grid(axis="y", alpha=.15)
        ax.set_axisbelow(True)
    fig.suptitle("AgentFEM · How excitation changes structural response", x=.08, ha="left", fontsize=16, fontweight="bold")
    fig.text(.08, .075, f"Selected case: f1 = {reference['first_frequency_hz']:.2f} Hz · damping = {100*reference['damping_ratio']:.2f}% · traction amplitude = {reference['traction_amplitude_pa']/1000:.3f} kPa", fontsize=9)
    fig.text(.08, .025, "Synthetic FEM peaks over 0.5 s. Different load histories, not a steady-state frequency response or an ML score.", fontsize=9, color="#52606a")
    fig.tight_layout(rect=(0, .12, 1, .92), w_pad=3)
    fig.savefig(args.output, dpi=160)
    plt.close(fig)
    print(json.dumps({"configuration": args.configuration, "peak_displacement_mm": dict(zip(KINDS, peaks.tolist())),
                      "verified_index_trajectories": 512, "test_configurations": counts,
                      "source_revision": REVISION, "output": str(args.output)}, indent=2))


if __name__ == "__main__":
    main()