File size: 12,167 Bytes
ebc46a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
"""Train pointwise-MLP and history-aware GRU baselines for T2 v1."""

from __future__ import annotations

import argparse
import json
import time
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

try:
    from src.load_t2_material_loading_memory import iter_trajectories
except ModuleNotFoundError:
    from load_t2_material_loading_memory import iter_trajectories


ROOT = Path(__file__).resolve().parents[1]
DATA_DIR = ROOT / "data" / "t2_material_loading_memory_v1"
ARTIFACT_DIR = ROOT / "artifacts" / "t2_material_loading_memory_v1"
PARAMETER_NAMES = (
    "young_pa",
    "poisson",
    "yield_stress_pa",
    "hardening_modulus_pa",
    "backstress_c1_pa",
    "backstress_gamma1",
    "backstress_c2_pa",
    "backstress_gamma2",
    "isotropic_saturation_pa",
    "isotropic_rate",
)
MODEL_NAMES = ("j2_linear_isotropic", "chaboche_combined")
PATH_FAMILIES = (
    "monotonic_tension",
    "unload_reload",
    "tension_compression",
    "symmetric_cyclic",
    "mean_shifted_cyclic",
    "variable_amplitude",
)


class PointwiseMLP(nn.Module):
    def __init__(self, input_size: int) -> None:
        super().__init__()
        self.network = nn.Sequential(
            nn.Linear(input_size, 64),
            nn.Tanh(),
            nn.Linear(64, 64),
            nn.Tanh(),
            nn.Linear(64, 1),
        )

    def forward(self, values: torch.Tensor) -> torch.Tensor:
        return self.network(values)


class HistoryGRU(nn.Module):
    def __init__(self, input_size: int) -> None:
        super().__init__()
        self.recurrent = nn.GRU(input_size, 64, batch_first=True)
        self.output = nn.Linear(64, 1)

    def forward(self, values: torch.Tensor) -> torch.Tensor:
        hidden, _ = self.recurrent(values)
        return self.output(hidden)


def _load_arrays() -> dict[str, object]:
    samples = list(iter_trajectories(DATA_DIR))
    parameters = np.asarray(
        [[float(sample["parameters"][name]) for name in PARAMETER_NAMES] for sample in samples],
        dtype=np.float64,
    )
    model_one_hot = np.zeros((len(samples), len(MODEL_NAMES)), dtype=np.float64)
    for index, sample in enumerate(samples):
        model_one_hot[index, MODEL_NAMES.index(sample["material_model"])] = 1.0
    strain = np.asarray(
        [sample["history"]["signed_equivalent_strain"] for sample in samples],
        dtype=np.float64,
    )
    stress = np.asarray(
        [sample["history"]["signed_equivalent_stress_pa"] for sample in samples],
        dtype=np.float64,
    )
    splits = np.asarray([sample["split"] for sample in samples])
    train = splits == "train"
    parameter_mean = parameters[train].mean(axis=0)
    parameter_scale = parameters[train].std(axis=0)
    parameter_scale[parameter_scale < 1.0e-15] = 1.0
    normalized_parameters = (parameters - parameter_mean) / parameter_scale
    strain_scale = float(np.max(np.abs(strain[train])))
    normalized_strain = strain / strain_scale
    delta = np.diff(normalized_strain, axis=1, prepend=normalized_strain[:, :1])
    constant = np.concatenate((normalized_parameters, model_one_hot), axis=1)
    repeated = np.repeat(constant[:, None, :], strain.shape[1], axis=1)
    pointwise = np.concatenate((normalized_strain[:, :, None], repeated), axis=2)
    history = np.concatenate(
        (normalized_strain[:, :, None], delta[:, :, None], repeated), axis=2
    )
    stress_scale = float(np.std(stress[train]))
    target = stress / stress_scale
    return {
        "samples": samples,
        "pointwise": pointwise.astype(np.float32),
        "history": history.astype(np.float32),
        "target": target.astype(np.float32),
        "stress_pa": stress,
        "splits": splits,
        "normalization": {
            "parameter_names": list(PARAMETER_NAMES),
            "parameter_mean": parameter_mean.tolist(),
            "parameter_scale": parameter_scale.tolist(),
            "strain_scale": strain_scale,
            "stress_scale_pa": stress_scale,
        },
    }


def _train_pointwise(
    features: np.ndarray,
    target: np.ndarray,
    train: np.ndarray,
    validation: np.ndarray,
    *,
    epochs: int,
) -> PointwiseMLP:
    model = PointwiseMLP(features.shape[-1])
    optimizer = torch.optim.Adam(model.parameters(), lr=2.0e-3)
    criterion = nn.MSELoss()
    x_train = torch.from_numpy(features[train].reshape(-1, features.shape[-1]))
    y_train = torch.from_numpy(target[train].reshape(-1, 1))
    loader = DataLoader(TensorDataset(x_train, y_train), batch_size=4096, shuffle=True)
    x_validation = torch.from_numpy(
        features[validation].reshape(-1, features.shape[-1])
    )
    y_validation = torch.from_numpy(target[validation].reshape(-1, 1))
    best: dict[str, torch.Tensor] | None = None
    best_loss = float("inf")
    remaining = 6
    for _ in range(epochs):
        model.train()
        for x_batch, y_batch in loader:
            optimizer.zero_grad()
            loss = criterion(model(x_batch), y_batch)
            loss.backward()
            optimizer.step()
        model.eval()
        with torch.no_grad():
            loss = float(criterion(model(x_validation), y_validation))
        if loss < best_loss - 1.0e-6:
            best_loss = loss
            best = {name: value.detach().clone() for name, value in model.state_dict().items()}
            remaining = 6
        else:
            remaining -= 1
            if remaining == 0:
                break
    if best is not None:
        model.load_state_dict(best)
    return model


def _train_gru(
    features: np.ndarray,
    target: np.ndarray,
    train: np.ndarray,
    validation: np.ndarray,
    *,
    epochs: int,
) -> HistoryGRU:
    model = HistoryGRU(features.shape[-1])
    optimizer = torch.optim.Adam(model.parameters(), lr=2.0e-3)
    criterion = nn.MSELoss()
    loader = DataLoader(
        TensorDataset(torch.from_numpy(features[train]), torch.from_numpy(target[train, :, None])),
        batch_size=32,
        shuffle=True,
    )
    x_validation = torch.from_numpy(features[validation])
    y_validation = torch.from_numpy(target[validation, :, None])
    best: dict[str, torch.Tensor] | None = None
    best_loss = float("inf")
    remaining = 8
    for _ in range(epochs):
        model.train()
        for x_batch, y_batch in loader:
            optimizer.zero_grad()
            loss = criterion(model(x_batch), y_batch)
            loss.backward()
            optimizer.step()
        model.eval()
        with torch.no_grad():
            loss = float(criterion(model(x_validation), y_validation))
        if loss < best_loss - 1.0e-6:
            best_loss = loss
            best = {name: value.detach().clone() for name, value in model.state_dict().items()}
            remaining = 8
        else:
            remaining -= 1
            if remaining == 0:
                break
    if best is not None:
        model.load_state_dict(best)
    return model


def _predict(model: nn.Module, features: np.ndarray, *, batch_size: int) -> np.ndarray:
    model.eval()
    chunks: list[np.ndarray] = []
    with torch.no_grad():
        for start in range(0, len(features), batch_size):
            chunks.append(model(torch.from_numpy(features[start : start + batch_size])).numpy())
    return np.concatenate(chunks, axis=0).squeeze(-1)


def _metrics(reference: np.ndarray, prediction: np.ndarray) -> dict[str, float]:
    error = prediction - reference
    rmse = float(np.sqrt(np.mean(error**2)))
    mae = float(np.mean(np.abs(error)))
    centered = reference - float(np.mean(reference))
    r2 = 1.0 - float(np.sum(error**2) / np.sum(centered**2))
    scale = float(np.max(reference) - np.min(reference))
    return {
        "rmse_mpa": rmse / 1.0e6,
        "mae_mpa": mae / 1.0e6,
        "range_normalized_rmse": rmse / scale,
        "r2": r2,
    }


def train(*, mlp_epochs: int = 40, gru_epochs: int = 60) -> dict[str, object]:
    torch.manual_seed(20260925)
    np.random.seed(20260925)
    torch.set_num_threads(min(4, torch.get_num_threads()))
    torch.use_deterministic_algorithms(True)
    arrays = _load_arrays()
    splits = arrays["splits"]
    train_mask = splits == "train"
    validation_mask = splits == "validation"
    test_mask = splits == "test"
    started = time.perf_counter()
    mlp = _train_pointwise(
        arrays["pointwise"],
        arrays["target"],
        train_mask,
        validation_mask,
        epochs=mlp_epochs,
    )
    gru = _train_gru(
        arrays["history"],
        arrays["target"],
        train_mask,
        validation_mask,
        epochs=gru_epochs,
    )
    stress_scale = arrays["normalization"]["stress_scale_pa"]
    mlp_prediction = _predict(mlp, arrays["pointwise"], batch_size=128) * stress_scale
    gru_prediction = _predict(gru, arrays["history"], batch_size=64) * stress_scale
    reference = arrays["stress_pa"]
    metrics: dict[str, object] = {
        "status": "completed",
        "task": "signed-equivalent-stress history prediction",
        "split_policy": "complete trajectories; normalization fitted on train only",
        "test_trajectory_count": int(np.count_nonzero(test_mask)),
        "pointwise_mlp": {"overall": _metrics(reference[test_mask], mlp_prediction[test_mask])},
        "history_gru": {"overall": _metrics(reference[test_mask], gru_prediction[test_mask])},
        "wall_seconds": float(time.perf_counter() - started),
        "torch_version": torch.__version__,
        "normalization": arrays["normalization"],
    }
    samples = arrays["samples"]
    for model_name in MODEL_NAMES:
        mask = test_mask & np.asarray(
            [sample["material_model"] == model_name for sample in samples]
        )
        metrics["pointwise_mlp"][model_name] = _metrics(reference[mask], mlp_prediction[mask])
        metrics["history_gru"][model_name] = _metrics(reference[mask], gru_prediction[mask])

    ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)
    (ARTIFACT_DIR / "baseline_metrics.json").write_text(
        json.dumps(metrics, indent=2, sort_keys=True) + "\n", encoding="utf-8"
    )
    torch.save(
        {
            "pointwise_mlp": mlp.state_dict(),
            "history_gru": gru.state_dict(),
            "normalization": arrays["normalization"],
            "parameter_names": PARAMETER_NAMES,
            "model_names": MODEL_NAMES,
        },
        ARTIFACT_DIR / "baseline_models.pt",
    )

    fig, axes = plt.subplots(2, 3, figsize=(12.0, 7.2), constrained_layout=True)
    for axis, family in zip(axes.flat, PATH_FAMILIES, strict=True):
        index = next(
            idx
            for idx, sample in enumerate(samples)
            if test_mask[idx]
            and sample["material_model"] == "chaboche_combined"
            and sample["path_family"] == family
        )
        strain = 100.0 * samples[index]["history"]["signed_equivalent_strain"]
        axis.plot(strain, reference[index] / 1.0e6, color="#111827", lw=2.0, label="AgentFEM")
        axis.plot(strain, mlp_prediction[index] / 1.0e6, color="#f59e0b", lw=1.2, label="Pointwise MLP")
        axis.plot(strain, gru_prediction[index] / 1.0e6, color="#2563eb", lw=1.5, label="History GRU")
        axis.set_title(family.replace("_", " ").title(), fontsize=10)
        axis.set_xlabel("Signed equivalent strain (%)")
        axis.set_ylabel("Signed equivalent stress (MPa)")
        axis.grid(alpha=0.22)
    axes.flat[0].legend(frameon=False, fontsize=8)
    fig.suptitle("T2 v1 baseline comparison on held-out Chaboche trajectories", fontsize=13)
    fig.savefig(ARTIFACT_DIR / "baseline_predictions.png", dpi=180)
    plt.close(fig)
    print(json.dumps(metrics, indent=2, sort_keys=True))
    return metrics


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--mlp-epochs", type=int, default=40)
    parser.add_argument("--gru-epochs", type=int, default=60)
    args = parser.parse_args()
    train(mlp_epochs=args.mlp_epochs, gru_epochs=args.gru_epochs)


if __name__ == "__main__":
    main()