AgentFEM-Pipe-Components / compare_dampers.py
HaomingLuo's picture
Add reproducible harmonic damper comparison example
d86db46 verified
Raw History Blame Contribute Delete
7.09 kB
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Plot published pipe-ROM harmonic sweeps; no FEM runtime required.
Install: python -m pip install numpy matplotlib
Run: python compare_dampers.py
Offline: python compare_dampers.py --input dynamics/harmonic_cases.jsonl
Plots stored responses, not a new solve or neural prediction. Data: CC BY 4.0,
Haoming Luo, AgentFEM Pipe Components. Peaks are sampled over the given sweep,
not continuous resonance maxima, RMS values, or plant performance guarantees.
"""
import argparse
import csv
import hashlib
import json
from pathlib import Path
from urllib.request import urlopen
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
REPO = "HaomingLuo/AgentFEM-Pipe-Components"
REVISION = "339464086e6211c6f7048723510d97df0b414a06"
SOURCE = f"https://huggingface.co/datasets/{REPO}/resolve/{REVISION}/dynamics/harmonic_cases.jsonl"
ROUTES = ("L", "U", "spatial")
COEFFICIENTS = (0, 1000, 100000)
def validate(records):
by_id = {r["id"]: r for r in records}
expected = {f"{route}_{axis}_{c}" for route in ROUTES
for axis in (1, 2) for c in COEFFICIENTS} | {"blocked"}
if len(by_id) != len(records) or set(by_id) != expected:
raise ValueError("Expected the 19 unique v1.2 harmonic cases.")
for r in records:
f = np.asarray(r["frequency_Hz"], dtype=float)
a = np.asarray(r["without_added_damper_m"], dtype=float)
b = np.asarray(r["with_added_damper_m"], dtype=float)
if f.shape != (161,) or a.shape != f.shape or b.shape != f.shape:
raise ValueError(f"Invalid sweep dimensions: {r['id']}")
if not (np.isfinite([f, a, b]).all() and (np.diff(f) > 0).all()
and (f > 0).all() and (a >= 0).all() and (b >= 0).all()):
raise ValueError(f"Invalid sweep values: {r['id']}")
if (r["amplitude_convention"] != "peak, not RMS"
or r["label_source"] != "component_ROM_complex_steady_response"
or r["probe"] != "force point and direction"
or r["mode_count"] != 12):
raise ValueError("Unexpected response convention or model provenance.")
for route in ROUTES:
for axis in (1, 2):
ref = by_id[f"{route}_{axis}_0"]
for c in COEFFICIENTS:
r = by_id[f"{route}_{axis}_{c}"]
for key in ("component_ids", "rolls", "supports", "frequency_Hz",
"without_added_damper_m"):
if r[key] != ref[key]:
raise ValueError(f"Comparison changes {key}: {r['id']}")
h, h0 = r["harmonic"], ref["harmonic"]
if ({k: v for k, v in h.items() if k != "damper"}
!= {k: v for k, v in h0.items() if k != "damper"}
or h["force"] != 100 or h["zeta"] != 0.02
or h["axis"] != axis or h["damper"] != {
"node": h["node"], "axis": axis, "c": c}):
raise ValueError(f"Unexpected loading or damper: {r['id']}")
if ref["with_added_damper_m"] != ref["without_added_damper_m"]:
raise ValueError("Zero-added-damping control does not match.")
blocked = by_id["blocked"]
if np.any(blocked["with_added_damper_m"]) or np.any(blocked["without_added_damper_m"]):
raise ValueError("Blocked-direction control must have zero measured response.")
return by_id
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input", type=Path, help="Use a local copy, without network access")
parser.add_argument("--output", type=Path, default=Path("damper_comparison"))
args = parser.parse_args()
if args.input:
data = args.input.read_bytes()
else:
with urlopen(SOURCE, timeout=60) as response:
data = response.read()
records = [json.loads(line) for line in data.decode("utf-8").splitlines() if line.strip()]
cases = validate(records)
args.output.mkdir(parents=True, exist_ok=True)
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 10,
"axes.spines.top": False, "axes.spines.right": False})
fig, axes = plt.subplots(2, 3, figsize=(13, 7.5), layout="constrained")
colors = ("#52646d", "#15978c", "#c77d32")
rows = []
for col, route in enumerate(ROUTES):
for row, axis in enumerate((1, 2)):
ax = axes[row, col]
ref = cases[f"{route}_{axis}_0"]
ref_peak = max(ref["without_added_damper_m"])
for c, color in zip(COEFFICIENTS, colors):
r = cases[f"{route}_{axis}_{c}"]
f = np.asarray(r["frequency_Hz"])
a = np.asarray(r["with_added_damper_m"]) * 1000
peak_index = int(np.argmax(a))
label = "No added damper" if c == 0 else f"c = {c/1000:g} kN s/m"
ax.plot(f, a, color=color, lw=2, label=label)
rows.append({"case": r["id"], "damper_N_s_per_m": c,
"sampled_peak_mm": float(a[peak_index]),
"sampled_peak_frequency_Hz": float(f[peak_index]),
"peak_ratio_to_no_added_damper": float(a[peak_index]/(1000*ref_peak))})
ax.set_title(f"{route.capitalize()} route / {'Y' if axis == 1 else 'Z'} excitation",
loc="left", fontweight="bold")
ax.set_xlabel("Excitation frequency / Hz")
ax.set_ylabel("Peak displacement / mm")
ax.set_ylim(bottom=0)
ax.grid(alpha=0.16)
axes[0, 0].legend(frameon=False, fontsize=9)
fig.suptitle("Same pipe. Same forcing. Different damping.\n"
"100 N peak force · 2% background modal damping · stored component-ROM responses",
fontsize=15)
fig.supxlabel("Probe and damper: force joint / direction. Linear dry-pipe research model; not plant measurements.",
fontsize=10)
fig.savefig(args.output / "damper_comparison.png", dpi=180)
plt.close(fig)
with (args.output / "sampled_peaks.csv").open("w", newline="", encoding="utf-8") as stream:
writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
report = {"repository": REPO, "revision": REVISION, "source_url": SOURCE,
"local_input": str(args.input) if args.input else None,
"input_sha256": hashlib.sha256(data).hexdigest(),
"cases_checked": len(records), "blocked_direction_peak_m": 0.0,
"note": "Ratios compare sampled maxima across a finite sweep, not same-frequency ratios or ML errors.",
"peaks": rows}
(args.output / "summary.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
print(f"Validated {len(records)} stored cases; wrote figure, sampled_peaks.csv and summary.json to {args.output}")
if __name__ == "__main__":
main()