File size: 5,055 Bytes
bbe9b3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
"""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()