AgentFEM-Material-Loading-Memory / src /plot_t2_graybox_closure.py
HaomingLuo's picture
Add DENIM incomplete-physics closure dataset and evidence
bbe9b3e verified
Raw
History Blame Contribute Delete
5.06 kB
"""Create compact paper-ready figures for the incomplete-physics closure."""
from __future__ import annotations
import json
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import torch
from src import t2_graybox_discrete_energy as graybox
from src.generate_t2_graybox_closure import MATERIAL
from src.train_t2_graybox_discrete_energy import load_cohort
from src.train_t2_multiaxial_models import RecurrentStress
ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data" / "t2_graybox_closure_v1" / "cohort.h5"
MODELS = ROOT / "models" / "t2_graybox_closure_v1"
ARTIFACTS = ROOT / "artifacts" / "t2_graybox_closure_v1"
def main() -> None:
cohort = load_cohort(DATA)
denrm_checkpoint = torch.load(MODELS / "denrm.pt", map_location="cpu", weights_only=False)
denrm = graybox.NeuralHardeningLaw(channels=2)
denrm.load_state_dict(denrm_checkpoint["state_dict"])
denrm.eval()
gru_checkpoint = torch.load(MODELS / "gru.pt", map_location="cpu", weights_only=False)
gru = RecurrentStress(6, cell="gru", hidden=72)
gru.load_state_dict(gru_checkpoint["state_dict"])
gru.eval()
norm = gru_checkpoint["normalization"]
with torch.no_grad():
denrm_stress = graybox.rollout(
cohort.strain,
torch.full((len(cohort.strain),), float(MATERIAL["young_pa"])),
torch.full((len(cohort.strain),), float(MATERIAL["poisson"])),
torch.full((len(cohort.strain),), float(MATERIAL["yield_stress_pa"])),
denrm,
bisection_iterations=24,
)["stress"]
gru_stress = (
gru((cohort.strain - norm["strain_mean"]) / norm["strain_std"])
* norm["stress_std"]
+ norm["stress_mean"]
)
metrics = json.loads((ARTIFACTS / "model_metrics.json").read_text())
figure, axes = plt.subplots(2, 2, figsize=(11.0, 7.8), constrained_layout=True)
colors = {"truth": "#1f2937", "denrm": "#e11d48", "gru": "#2563eb"}
component_labels = ("xx", "yy", "zz", "xy", "yz", "xz")
for axis, family in zip(
axes[0], ("out_of_phase_lissajous", "random_direction_blocks"), strict=True
):
index = next(i for i, value in enumerate(cohort.families) if value == family)
strain = cohort.strain[index].numpy()
component = int(np.argmax(np.ptp(strain, axis=0)))
x = 100.0 * strain[:, component]
axis.plot(
x,
cohort.stress[index, :, component].numpy() / 1.0e6,
color=colors["truth"],
linewidth=2.1,
label="AgentFEM reference",
)
axis.plot(
x,
denrm_stress[index, :, component].numpy() / 1.0e6,
"--",
color=colors["denrm"],
linewidth=1.8,
label="DENIM (2-state closure)",
)
axis.plot(
x,
gru_stress[index, :, component].numpy() / 1.0e6,
color=colors["gru"],
linewidth=1.1,
alpha=0.85,
label="GRU",
)
axis.set_title(family.replace("_", " "))
axis.set_xlabel(f"strain {component_labels[component]} (%)")
axis.set_ylabel(f"stress {component_labels[component]} (MPa)")
axis.grid(alpha=0.22)
axes[0, 0].legend(frameon=False, fontsize=8)
names = ("Incomplete J2", "GRU", "DENIM")
keys = ("incomplete_j2", "gru", "denrm")
rmse = [metrics["models"][key]["test"]["rmse_mpa"] for key in keys]
bars = axes[1, 0].bar(
names, rmse, color=("#9ca3af", colors["gru"], colors["denrm"])
)
axes[1, 0].bar_label(bars, fmt="%.2f")
axes[1, 0].set_ylabel("held-out path RMSE (MPa)")
axes[1, 0].set_title("unseen loading-path accuracy")
axes[1, 0].grid(axis="y", alpha=0.22)
peeq = np.linspace(0.0, 0.10, 250)
with torch.no_grad():
learned = denrm.isotropic(
torch.tensor(peeq, dtype=torch.float32),
torch.full((len(peeq),), float(MATERIAL["yield_stress_pa"])),
).numpy()
reference = np.interp(
peeq,
np.asarray(MATERIAL["hardening_peeq"]),
np.asarray(MATERIAL["hardening_stress_pa"]),
) - float(MATERIAL["yield_stress_pa"])
axes[1, 1].plot(peeq, reference / 1.0e6, color=colors["truth"], linewidth=2.1, label="hidden table")
axes[1, 1].plot(peeq, learned / 1.0e6, "--", color=colors["denrm"], linewidth=1.8, label="learned monotone law")
axes[1, 1].set_xlabel("equivalent plastic strain")
axes[1, 1].set_ylabel("isotropic hardening radius (MPa)")
axes[1, 1].set_title("unknown hardening-law recovery")
axes[1, 1].grid(alpha=0.22)
axes[1, 1].legend(frameon=False, fontsize=8)
figure.suptitle(
"Incomplete-physics closure: 3-state tabulated reference → 2-state DENIM",
fontsize=13,
)
ARTIFACTS.mkdir(parents=True, exist_ok=True)
figure.savefig(ARTIFACTS / "closure_summary.png", dpi=220)
plt.close(figure)
if __name__ == "__main__":
main()