AgentFEM-Structural-Dynamics-Virtual-Sensing / code /visualize_t4_structural_dynamics_v1.py
HaomingLuo's picture
Release T4 v1: 128 configurations and 512 trajectories
caa4bd5 verified
Raw History Blame Contribute Delete
4.43 kB
"""Create the publication preview for the T4 v1 structural-dynamics dataset."""
from __future__ import annotations
import json
from pathlib import Path
import h5py
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.tri import Triangulation
try:
from .t4_structural_dynamics_v1 import CASE_DIR, DATA_DIR, configuration_design, load_config
except ImportError:
from t4_structural_dynamics_v1 import CASE_DIR, DATA_DIR, configuration_design, load_config
def main() -> None:
rows = configuration_design(load_config())
colors = {
"train": "#4C78A8",
"validation": "#59A14F",
"test_id": "#F28E2B",
"excitation_ood": "#E15759",
"parameter_ood": "#B07AA1",
}
fig, axes = plt.subplots(2, 2, figsize=(13.5, 8.2), constrained_layout=True)
ax = axes[0, 0]
for row in rows:
role = row["protocol_role"]
key = row["split"] if row["split"] != "test" else ("test_id" if role == "id" else role)
p = row["parameters"]
ax.scatter(p["length_m"], p["height_m"] * 1e3, s=28, c=colors[key], alpha=0.88)
labels = (
("train", "Train · 96 configurations"),
("validation", "Validation · 16"),
("test_id", "Test ID · 8"),
("excitation_ood", "Test excitation OOD · 4"),
("parameter_ood", "Test parameter OOD · 4"),
)
for key, label in labels:
ax.scatter([], [], s=34, c=colors[key], label=label)
ax.set(xlabel="Beam length (m)", ylabel="Beam height (mm)", title="Leakage-safe physical configurations")
ax.legend(frameon=False, fontsize=8, ncol=2)
frequencies = []
frequency_colors = []
for row in rows:
with h5py.File(CASE_DIR / f"{row['case_id']}.h5", "r") as h5:
frequencies.append(float(h5["modal/frequencies_hz"][0]))
role = row["protocol_role"]
key = row["split"] if row["split"] != "test" else ("test_id" if role == "id" else role)
frequency_colors.append(colors[key])
ax = axes[0, 1]
ax.scatter(range(128), frequencies, c=frequency_colors, s=24)
ax.axvline(95.5, color="#777777", lw=1, ls="--")
ax.axvline(111.5, color="#777777", lw=1, ls="--")
ax.set(xlabel="Configuration ID", ylabel="First natural frequency (Hz)", title="Dynamic diversity and frozen split")
case_path = CASE_DIR / "config_0119.h5"
with h5py.File(case_path, "r") as h5:
group = h5["trajectories/near_resonant_sine"]
time = np.asarray(group["time_s"])
sensors = np.asarray(group["sensor_displacement_m"])
field_time = np.asarray(group["fields/time_s"])
displacement = np.asarray(group["fields/displacement_m"])
geometry = np.asarray(h5["common/reference_geometry_m"])
topology = np.asarray(h5["common/topology"])
ax = axes[1, 0]
for index, fraction in enumerate((0.2, 0.4, 0.6, 0.8, 1.0)):
ax.plot(time, sensors[:, index] * 1e3, lw=1.25, label=f"x/L={fraction:.1f}")
ax.set(xlabel="Time (s)", ylabel="Vertical displacement (mm)", title="Five virtual sensors · near-resonant loading")
ax.legend(frameon=False, fontsize=8, ncol=3)
sampled_tip = np.interp(field_time, time, sensors[:, -1])
frame = int(np.argmax(np.abs(sampled_tip)))
deformed = geometry[:, :2] + 12.0 * displacement[frame, :, :2]
values = displacement[frame, :, 1] * 1e3
triangulation = Triangulation(deformed[:, 0], deformed[:, 1])
ax = axes[1, 1]
collection = ax.tripcolor(triangulation, values, shading="gouraud", cmap="coolwarm")
length = float(np.max(geometry[:, 0]))
height = float(np.max(geometry[:, 1]))
ax.plot([0, length, length, 0, 0], [0, 0, height, height, 0], color="#555555", lw=0.7, ls="--")
ax.set_aspect("equal")
ax.set(xlabel="x (m)", ylabel="y (m)", title=f"Full-field response · t={field_time[frame]:.3f} s · deformation ×12")
colorbar = fig.colorbar(collection, ax=ax, shrink=0.85)
colorbar.set_label("Vertical displacement (mm)")
fig.suptitle(
"AgentFEM Structural Dynamics · 128 configurations · 512 complete trajectories",
fontsize=17,
fontweight="bold",
)
DATA_DIR.mkdir(parents=True, exist_ok=True)
output = DATA_DIR / "preview.png"
fig.savefig(output, dpi=180, bbox_inches="tight")
plt.close(fig)
print(json.dumps({"preview": str(output), "bytes": output.stat().st_size}))
if __name__ == "__main__":
main()