Download compare_excitations.py from HaomingLuo/AgentFEM-Structural-Dynamics-Virtual-Sensing: direct link, hf CLI and curl.
- Browser
- Download file 5.83 kB
-
https://huggingface.co/datasets/HaomingLuo/AgentFEM-Structural-Dynamics-Virtual-Sensing/resolve/main/compare_excitations.py
- Command line
-
hf download hf://datasets/HaomingLuo/AgentFEM-Structural-Dynamics-Virtual-Sensing/compare_excitations.py
-
curl -L -o compare_excitations.py https://huggingface.co/datasets/HaomingLuo/AgentFEM-Structural-Dynamics-Virtual-Sensing/resolve/main/compare_excitations.py
5.83 kB
| """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() | |