File size: 28,759 Bytes
f1564a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
"""Embed learned constitutive histories in a displacement-controlled bar FE test.

This is a controlled one-dimensional structural deployment gate.  The global
finite-element equilibrium is solved independently for a smooth notched bar,
while each element obtains its path-dependent generalized stress either from
the native AgentFEM Chaboche update or from a trained neural constitutive
model.  It is not presented as a general three-dimensional learned-material
provider for AgentFEM.
"""

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 scipy.optimize import least_squares

from agentfem import constitutive

try:
    from src import train_t2_multiaxial_models as learning
    from src import train_t2_physics_integrator as physics_integrator
except ModuleNotFoundError:
    import train_t2_multiaxial_models as learning
    import train_t2_physics_integrator as physics_integrator


ROOT = Path(__file__).resolve().parents[1]
MODEL_ROOT = ROOT / "models" / "t2_multiaxial_ood_v2"
ARTIFACT_ROOT = ROOT / "artifacts" / "t2_multiaxial_ood_v2" / "structural_validation"
BASIS = np.diag((1.0, -0.5, -0.5))
BASIS_VOIGT = np.asarray((1.0, -0.5, -0.5, 0.0, 0.0, 0.0))

MATERIAL_PARAMETERS = np.asarray(
    (
        190.0e9,
        0.30,
        280.0e6,
        0.0,
        35.0e9,
        60.0,
        8.0e9,
        8.0,
        70.0e6,
        8.0,
    ),
    dtype=float,
)


def load_history(points: int = 81, *, scale: float = 1.0) -> np.ndarray:
    anchors = np.asarray((0.0, 0.0035, -0.0025, 0.0055, -0.0035, 0.0065, 0.0))
    positions = np.linspace(0.0, len(anchors) - 1, points)
    lower = np.minimum(np.floor(positions).astype(int), len(anchors) - 2)
    fraction = positions - lower
    return scale * ((1.0 - fraction) * anchors[lower] + fraction * anchors[lower + 1])


def material() -> constitutive.ChabocheCombinedHardening:
    p = MATERIAL_PARAMETERS
    return constitutive.chaboche(
        young=float(p[0]),
        poisson=float(p[1]),
        yield_stress=float(p[2]),
        backstresses=((float(p[4]), float(p[5])), (float(p[6]), float(p[7]))),
        isotropic_saturation=float(p[8]),
        isotropic_rate=float(p[9]),
    )


def _normalization(values: dict[str, object]) -> learning.Normalization:
    def tensor(name: str, shape: tuple[int, ...]) -> torch.Tensor:
        return torch.tensor(values[name], dtype=torch.float32).reshape(shape)

    return learning.Normalization(
        strain_mean=tensor("strain_mean", (1, 1, 6)),
        strain_std=tensor("strain_std", (1, 1, 6)),
        parameter_mean=tensor("parameter_mean", (1, 10)),
        parameter_std=tensor("parameter_std", (1, 10)),
        stress_mean=tensor("stress_mean", (1, 1, 6)),
        stress_std=tensor("stress_std", (1, 1, 6)),
        plastic_scale=tensor("plastic_scale", (1, 1, 6)),
        backstress_scale=tensor("backstress_scale", (1, 1, 6)),
        peeq_scale=tensor("peeq_scale", (1, 1)),
    )


def load_checkpoint(name: str):
    if name == physics_integrator.MODEL_NAME:
        return physics_integrator.load_checkpoint("id")
    path = MODEL_ROOT / f"id_{name}.pt"
    checkpoint = torch.load(path, map_location="cpu", weights_only=False)
    model = learning.build_model(str(checkpoint["model_name"]), int(checkpoint["input_size"]))
    model.load_state_dict(checkpoint["state_dict"])
    model.eval()
    return model, _normalization(checkpoint["normalization"])


def neural_response(
    model: torch.nn.Module,
    model_name: str,
    norm,
    history: list[float],
) -> tuple[float, float]:
    previous = torch.tensor(history[:-1], dtype=torch.float32)
    current = torch.tensor(float(history[-1]), dtype=torch.float32, requires_grad=True)
    scalar = torch.cat((previous, current.reshape(1)))
    strain = scalar[:, None] * torch.tensor(BASIS_VOIGT, dtype=torch.float32)[None, :]
    parameters = torch.tensor(MATERIAL_PARAMETERS, dtype=torch.float32).reshape(1, 10)
    if model_name == physics_integrator.MODEL_NAME:
        parameter_mean, parameter_std, correction_steps = norm
        output = physics_integrator.rollout(
            strain[None, ...], parameters, model,
            parameter_mean, parameter_std,
            correction_steps=correction_steps,
        )["stress"]
        generalized = output[0, -1, 0] - 0.5 * output[0, -1, 1] - 0.5 * output[0, -1, 2]
        tangent = torch.autograd.grad(generalized, current, create_graph=False)[0]
        return float(generalized.detach()), float(tangent.detach())
    normalized_strain = (strain[None, ...] - norm.strain_mean) / norm.strain_std
    normalized_parameters = (parameters - norm.parameter_mean) / norm.parameter_std
    repeated = normalized_parameters[:, None, :].expand(1, len(scalar), -1)
    indicator = torch.tensor((0.0, 1.0), dtype=torch.float32).reshape(1, 1, 2).expand(1, len(scalar), -1)
    x = torch.cat((normalized_strain, repeated, indicator), dim=-1)
    if model_name == "physics_state_gru":
        output = model(x, strain[None, ...], parameters, norm)["stress"]
    else:
        output = model(x) * norm.stress_std + norm.stress_mean
    generalized = (
        output[0, -1, 0] - 0.5 * output[0, -1, 1] - 0.5 * output[0, -1, 2]
    )
    tangent = torch.autograd.grad(generalized, current, create_graph=False)[0]
    return float(generalized.detach()), float(tangent.detach())


def native_response(
    law: constitutive.ChabocheCombinedHardening,
    old_state,
    strain: float,
):
    update = law.update(float(strain) * BASIS, old_state)
    generalized = float(np.tensordot(update.stress, BASIS))
    tangent = float(np.einsum("ij,ijkl,kl", BASIS, update.algorithmic_tangent, BASIS))
    return generalized, tangent, update.state


def geometry(elements: int, notch_depth: float = 0.42) -> tuple[np.ndarray, np.ndarray]:
    nodes = np.linspace(0.0, 1.0, elements + 1)
    centers = 0.5 * (nodes[:-1] + nodes[1:])
    area = 1.0 - float(notch_depth) * np.exp(-((centers - 0.5) / 0.13) ** 2)
    return nodes, area


def solve_native(elements: int, displacement: np.ndarray, *, notch_depth: float = 0.42) -> dict[str, np.ndarray | float | int]:
    nodes, area = geometry(elements, notch_depth)
    lengths = np.diff(nodes)
    law = material()
    states = [None] * elements
    strain_histories = [[] for _ in range(elements)]
    u = np.zeros(elements + 1)
    reactions = []
    strains = []
    stresses = []
    iterations = []
    started = time.perf_counter()
    for step, end_value in enumerate(displacement):
        if step > 0:
            u += np.linspace(0.0, end_value - u[-1], elements + 1)
        u[0] = 0.0
        u[-1] = end_value
        converged_states = None
        for iteration in range(30):
            internal = np.zeros(elements + 1)
            stiffness = np.zeros((elements + 1, elements + 1))
            trial_states = []
            current_strain = np.diff(u) / lengths
            current_stress = np.empty(elements)
            for element in range(elements):
                stress, tangent, state = native_response(law, states[element], current_strain[element])
                current_stress[element] = stress
                trial_states.append(state)
                b = np.asarray((-1.0 / lengths[element], 1.0 / lengths[element]))
                dofs = (element, element + 1)
                internal[list(dofs)] += area[element] * stress * b * lengths[element]
                stiffness[np.ix_(dofs, dofs)] += area[element] * tangent * np.outer(b, b) * lengths[element]
            residual = internal[1:-1]
            scale = max(float(np.linalg.norm(internal)), 1.0)
            if np.linalg.norm(residual) <= 1.0e-8 * scale + 1.0e-3:
                converged_states = trial_states
                break
            u[1:-1] -= np.linalg.solve(stiffness[1:-1, 1:-1], residual)
        if converged_states is None:
            raise RuntimeError(f"Native structural solve failed at step {step}.")
        states = converged_states
        current_strain = np.diff(u) / lengths
        for element, value in enumerate(current_strain):
            strain_histories[element].append(float(value))
        reactions.append(float(internal[-1]))
        strains.append(current_strain.copy())
        stresses.append(current_stress.copy())
        iterations.append(iteration + 1)
    return {
        "displacement": displacement,
        "reaction": np.asarray(reactions),
        "strain": np.asarray(strains),
        "stress": np.asarray(stresses),
        "nodes": nodes,
        "area": area,
        "iterations": np.asarray(iterations),
        "elapsed_seconds": time.perf_counter() - started,
    }


def solve_neural(
    elements: int,
    displacement: np.ndarray,
    model_name: str,
    *,
    notch_depth: float = 0.42,
) -> dict[str, np.ndarray | float | int]:
    if model_name == physics_integrator.MODEL_NAME:
        return solve_physics_integrator(
            elements, displacement, notch_depth=notch_depth
        )
    nodes, area = geometry(elements, notch_depth)
    lengths = np.diff(nodes)
    loaded = load_checkpoint(model_name)
    if model_name == physics_integrator.MODEL_NAME:
        model, parameter_mean, parameter_std, correction_steps = loaded
        norm = (parameter_mean, parameter_std, correction_steps)
    else:
        model, norm = loaded
    histories = [[] for _ in range(elements)]
    u = np.zeros(elements + 1)
    reactions = []
    strains = []
    stresses = []
    iterations = []
    started = time.perf_counter()
    for step, end_value in enumerate(displacement):
        if step > 0:
            u += np.linspace(0.0, end_value - u[-1], elements + 1)
        u[0] = 0.0
        u[-1] = end_value
        converged = False
        for iteration in range(40):
            internal = np.zeros(elements + 1)
            stiffness = np.zeros((elements + 1, elements + 1))
            current_strain = np.diff(u) / lengths
            current_stress = np.empty(elements)
            for element in range(elements):
                history = histories[element] + [float(current_strain[element])]
                stress, tangent = neural_response(model, model_name, norm, history)
                current_stress[element] = stress
                # Prevent a local noisy or nearly singular learned derivative from
                # destroying the global linear solve; the event is counted below.
                if not np.isfinite(tangent) or tangent <= 0.0:
                    raise RuntimeError(
                        f"{physics_integrator.MODEL_NAME} produced an invalid tangent "
                        f"({tangent}) at step {step}."
                    )
                b = np.asarray((-1.0 / lengths[element], 1.0 / lengths[element]))
                dofs = (element, element + 1)
                internal[list(dofs)] += area[element] * stress * b * lengths[element]
                stiffness[np.ix_(dofs, dofs)] += area[element] * tangent * np.outer(b, b) * lengths[element]
            residual = internal[1:-1]
            scale = max(float(np.linalg.norm(internal)), 1.0)
            if np.linalg.norm(residual) <= 2.0e-6 * scale + 1.0e2:
                converged = True
                break
            increment = np.linalg.solve(stiffness[1:-1, 1:-1], residual)
            maximum = 0.20 * max(abs(end_value), 1.0e-5)
            norm_increment = np.max(np.abs(increment))
            if norm_increment > maximum:
                increment *= maximum / norm_increment
            u[1:-1] -= increment
        if not converged:
            raise RuntimeError(f"{model_name} structural solve failed at step {step}.")
        current_strain = np.diff(u) / lengths
        for element, value in enumerate(current_strain):
            histories[element].append(float(value))
        reactions.append(float(internal[-1]))
        strains.append(current_strain.copy())
        stresses.append(current_stress.copy())
        iterations.append(iteration + 1)
    return {
        "displacement": displacement,
        "reaction": np.asarray(reactions),
        "strain": np.asarray(strains),
        "stress": np.asarray(stresses),
        "nodes": nodes,
        "area": area,
        "iterations": np.asarray(iterations),
        "elapsed_seconds": time.perf_counter() - started,
    }


def _detach_state(state: physics_integrator.State) -> physics_integrator.State:
    return physics_integrator.State(
        state.plastic.detach(), state.peeq.detach(),
        state.alpha1.detach(), state.alpha2.detach(),
    )


def physics_increment_response(
    model: torch.nn.Module,
    parameter_mean: torch.Tensor,
    parameter_std: torch.Tensor,
    correction_steps: int,
    committed: physics_integrator.State,
    previous_strain: float,
    current_strain: float,
) -> tuple[float, float, physics_integrator.State]:
    dtype = next(model.parameters()).dtype
    basis = torch.tensor(BASIS_VOIGT, dtype=dtype).reshape(1, 6)
    current = torch.tensor(float(current_strain), dtype=dtype)
    strain = current.reshape(1, 1) * basis
    previous = torch.tensor(float(previous_strain), dtype=dtype).reshape(1, 1) * torch.tensor(
        BASIS_VOIGT, dtype=dtype
    ).reshape(1, 6)
    parameters = torch.tensor(MATERIAL_PARAMETERS, dtype=dtype).reshape(1, 10)
    stress, updated, _ = physics_integrator.advance(
        strain, previous, committed, parameters, model,
        parameter_mean, parameter_std, correction_steps=correction_steps,
    )
    generalized = stress[0, 0] - 0.5 * stress[0, 1] - 0.5 * stress[0, 2]
    # The learned seed and active-set switch make a raw autograd tangent noisy
    # near first yield.  Differentiate the fully discrete update numerically,
    # matching the robust tangent strategy used by AgentFEM's native Chaboche
    # implementation.
    step = max(2.0e-8, 2.0e-5 * max(abs(float(current_strain)), 1.0e-3))
    neighboring = []
    with torch.no_grad():
        for value in (float(current_strain) - step, float(current_strain) + step):
            neighbor_stress, _, _ = physics_integrator.advance(
                torch.tensor(value, dtype=dtype).reshape(1, 1) * basis,
                previous, committed, parameters, model,
                parameter_mean, parameter_std, correction_steps=correction_steps,
            )
            neighboring.append(
                neighbor_stress[0, 0] - 0.5 * neighbor_stress[0, 1] - 0.5 * neighbor_stress[0, 2]
            )
    tangent = (neighboring[1] - neighboring[0]) / (2.0 * step)
    return float(generalized.detach()), float(tangent.detach()), _detach_state(updated)


def solve_physics_integrator(
    elements: int,
    displacement: np.ndarray,
    *,
    notch_depth: float,
) -> dict[str, np.ndarray | float | int]:
    nodes, area = geometry(elements, notch_depth)
    lengths = np.diff(nodes)
    model, parameter_mean, parameter_std, correction_steps = physics_integrator.load_checkpoint("id")
    model = model.double()
    parameter_mean = parameter_mean.double()
    parameter_std = parameter_std.double()
    correction_steps = max(correction_steps, 8)
    states = [physics_integrator.initial_state(1, dtype=torch.float64) for _ in range(elements)]
    previous_strains = np.zeros(elements)
    u = np.zeros(elements + 1)
    reactions, strains, stresses, iterations = [], [], [], []
    trust_region_fallback_steps: list[int] = []
    started = time.perf_counter()
    for step, end_value in enumerate(displacement):
        if step > 0:
            u += np.linspace(0.0, end_value - u[-1], elements + 1)
        u[0] = 0.0
        u[-1] = end_value
        converged = False
        converged_states = None
        for iteration in range(40):
            internal = np.zeros(elements + 1)
            stiffness = np.zeros((elements + 1, elements + 1))
            current_strain = np.diff(u) / lengths
            current_stress = np.empty(elements)
            trial_states = []
            for element in range(elements):
                stress, tangent, trial_state = physics_increment_response(
                    model, parameter_mean, parameter_std, correction_steps,
                    states[element], previous_strains[element], current_strain[element],
                )
                current_stress[element] = stress
                trial_states.append(trial_state)
                tangent = float(np.clip(tangent, 1.0e7, 4.0e11))
                b = np.asarray((-1.0 / lengths[element], 1.0 / lengths[element]))
                dofs = (element, element + 1)
                internal[list(dofs)] += area[element] * stress * b * lengths[element]
                stiffness[np.ix_(dofs, dofs)] += area[element] * tangent * np.outer(b, b) * lengths[element]
            residual = internal[1:-1]
            scale = max(float(np.linalg.norm(internal)), 1.0)
            if np.linalg.norm(residual) <= 2.0e-6 * scale + 1.0e2:
                converged = True
                converged_states = trial_states
                break
            increment = np.linalg.solve(stiffness[1:-1, 1:-1], residual)
            maximum = 0.20 * max(abs(end_value), 1.0e-5)
            norm_increment = np.max(np.abs(increment))
            if norm_increment > maximum:
                increment *= maximum / norm_increment
            u[1:-1] -= increment
        if not converged:
            # At complete displacement reversals the residual-stress state can
            # make a plain Newton step leave the local basin.  Use a bounded
            # trust-region least-squares fallback on the same FE equilibrium;
            # this changes only the global nonlinear strategy, not the learned
            # constitutive response.
            end_fixed = float(end_value)

            def equilibrium(interior: np.ndarray) -> np.ndarray:
                candidate = np.concatenate(([0.0], interior, [end_fixed]))
                candidate_strain = np.diff(candidate) / lengths
                candidate_internal = np.zeros(elements + 1)
                for local_element in range(elements):
                    local_stress, _, _ = physics_increment_response(
                        model, parameter_mean, parameter_std, correction_steps,
                        states[local_element], previous_strains[local_element],
                        candidate_strain[local_element],
                    )
                    local_b = np.asarray(
                        (-1.0 / lengths[local_element], 1.0 / lengths[local_element])
                    )
                    local_dofs = (local_element, local_element + 1)
                    candidate_internal[list(local_dofs)] += (
                        area[local_element] * local_stress * local_b * lengths[local_element]
                    )
                return candidate_internal[1:-1] / 1.0e8

            recovered = least_squares(
                equilibrium, u[1:-1], method="trf", jac="3-point",
                max_nfev=250, xtol=1.0e-12, ftol=1.0e-12, gtol=1.0e-12,
            )
            if recovered.success:
                u[1:-1] = recovered.x
                current_strain = np.diff(u) / lengths
                internal = np.zeros(elements + 1)
                current_stress = np.empty(elements)
                trial_states = []
                for element in range(elements):
                    stress, _, trial_state = physics_increment_response(
                        model, parameter_mean, parameter_std, correction_steps,
                        states[element], previous_strains[element], current_strain[element],
                    )
                    current_stress[element] = stress
                    trial_states.append(trial_state)
                    b = np.asarray((-1.0 / lengths[element], 1.0 / lengths[element]))
                    dofs = (element, element + 1)
                    internal[list(dofs)] += area[element] * stress * b * lengths[element]
                residual = internal[1:-1]
                scale = max(float(np.linalg.norm(internal)), 1.0)
                if np.linalg.norm(residual) <= 2.0e-6 * scale + 1.0e2:
                    converged = True
                    converged_states = trial_states
                    iteration = 40 + int(recovered.nfev)
                    trust_region_fallback_steps.append(step)
        if not converged or converged_states is None:
            raise RuntimeError(
                f"{physics_integrator.MODEL_NAME} structural solve failed at step {step}; "
                f"max_abs_element_strain={float(np.max(np.abs(current_strain))):.6g}."
            )
        states = converged_states
        previous_strains = np.diff(u) / lengths
        reactions.append(float(internal[-1]))
        strains.append(previous_strains.copy())
        stresses.append(current_stress.copy())
        iterations.append(iteration + 1)
    return {
        "displacement": displacement,
        "reaction": np.asarray(reactions),
        "strain": np.asarray(strains),
        "stress": np.asarray(stresses),
        "nodes": nodes,
        "area": area,
        "iterations": np.asarray(iterations),
        "trust_region_fallback_steps": trust_region_fallback_steps,
        "elapsed_seconds": time.perf_counter() - started,
    }


def compare(reference: dict[str, object], predicted: dict[str, object]) -> dict[str, float | int]:
    reaction_reference = np.asarray(reference["reaction"])
    reaction_predicted = np.asarray(predicted["reaction"])
    strain_reference = np.asarray(reference["strain"])
    strain_predicted = np.asarray(predicted["strain"])
    stress_reference = np.asarray(reference["stress"])
    stress_predicted = np.asarray(predicted["stress"])
    reaction_scale = max(float(np.max(np.abs(reaction_reference))), 1.0)
    stress_scale = max(float(np.max(np.abs(stress_reference))), 1.0)
    result = {
        "reaction_relative_l2": float(np.linalg.norm(reaction_predicted - reaction_reference) / max(np.linalg.norm(reaction_reference), 1.0)),
        "reaction_max_relative_error": float(np.max(np.abs(reaction_predicted - reaction_reference)) / reaction_scale),
        "strain_relative_l2": float(np.linalg.norm(strain_predicted - strain_reference) / max(np.linalg.norm(strain_reference), 1.0e-15)),
        "stress_relative_l2": float(np.linalg.norm(stress_predicted - stress_reference) / max(np.linalg.norm(stress_reference), 1.0)),
        "stress_max_relative_error": float(np.max(np.abs(stress_predicted - stress_reference)) / stress_scale),
        "maximum_newton_iterations": int(np.max(predicted["iterations"])),
        "mean_newton_iterations": float(np.mean(predicted["iterations"])),
        "elapsed_seconds": float(predicted["elapsed_seconds"]),
    }
    if "trust_region_fallback_steps" in predicted:
        result["trust_region_fallback_count"] = len(predicted["trust_region_fallback_steps"])
        result["trust_region_fallback_steps"] = list(predicted["trust_region_fallback_steps"])
    return result


def run(
    elements: int = 12,
    points: int = 81,
    model_names: tuple[str, ...] = ("gru", "physics_state_gru", "physics_integrator_nn"),
    case_name: str = "severe_ood",
) -> dict[str, object]:
    if case_name == "mild_id":
        notch_depth = 0.12
        load_scale = 0.65
    elif case_name == "moderate_ood":
        notch_depth = 0.30
        load_scale = 0.85
    elif case_name == "severe_ood":
        notch_depth = 0.42
        load_scale = 1.0
    else:
        raise ValueError(f"Unknown structural case: {case_name}")
    displacement = load_history(points, scale=load_scale)
    print("solving native AgentFEM Chaboche reference", flush=True)
    reference = solve_native(elements, displacement, notch_depth=notch_depth)
    learned = {}
    metrics = {}
    failures = {}
    for model_name in model_names:
        print(f"solving learned structural model: {model_name}", flush=True)
        try:
            result = solve_neural(
                elements,
                displacement,
                model_name,
                notch_depth=notch_depth,
            )
        except RuntimeError as error:
            failures[model_name] = str(error)
            print(f"recorded structural failure: {error}", flush=True)
        else:
            learned[model_name] = result
            metrics[model_name] = compare(reference, result)

    output_directory = ARTIFACT_ROOT / case_name
    output_directory.mkdir(parents=True, exist_ok=True)
    figure, axes = plt.subplots(1, 3, figsize=(14.0, 4.2), constrained_layout=True)
    axes[0].plot(displacement, np.asarray(reference["reaction"]) / 1.0e6, color="#111827", lw=2.2, label="AgentFEM Chaboche")
    colors = {"gru": "#2563eb", "physics_state_gru": "#dc2626", "physics_integrator_nn": "#059669"}
    labels = {"gru": "GRU", "physics_state_gru": "Physics-state GRU", "physics_integrator_nn": "Physics-integrator NN"}
    for name, result in learned.items():
        axes[0].plot(displacement, np.asarray(result["reaction"]) / 1.0e6, color=colors[name], lw=1.5, label=labels[name])
    axes[0].set_xlabel("End displacement / length")
    axes[0].set_ylabel("Reaction (MN for unit area)")
    axes[0].set_title("Structural force-displacement")
    centers = 0.5 * (np.asarray(reference["nodes"])[:-1] + np.asarray(reference["nodes"])[1:])
    axes[1].plot(centers, np.asarray(reference["strain"])[-2], color="#111827", lw=2.2)
    axes[2].plot(centers, np.asarray(reference["stress"])[-2] / 1.0e6, color="#111827", lw=2.2)
    for name, result in learned.items():
        axes[1].plot(centers, np.asarray(result["strain"])[-2], color=colors[name], lw=1.4)
        axes[2].plot(centers, np.asarray(result["stress"])[-2] / 1.0e6, color=colors[name], lw=1.4)
    axes[1].set_title("Near-final element strain")
    axes[1].set_xlabel("Bar coordinate")
    axes[1].set_ylabel("Generalized strain")
    axes[2].set_title("Near-final generalized stress")
    axes[2].set_xlabel("Bar coordinate")
    axes[2].set_ylabel("Stress (MPa)")
    for axis in axes:
        axis.grid(alpha=0.2)
    axes[0].legend(frameon=False, fontsize=8)
    figure.savefig(output_directory / "notched_bar_comparison.png", dpi=190)
    plt.close(figure)

    archive = {
        "displacement": displacement,
        "nodes": reference["nodes"],
        "area": reference["area"],
        "reference_reaction": reference["reaction"],
        "reference_strain": reference["strain"],
        "reference_stress": reference["stress"],
    }
    for name, result in learned.items():
        archive[f"{name}_reaction"] = result["reaction"]
        archive[f"{name}_strain"] = result["strain"]
        archive[f"{name}_stress"] = result["stress"]
    np.savez_compressed(output_directory / "notched_bar_results.npz", **archive)
    summary = {
        "status": "completed" if not failures else "completed_with_model_failures",
        "scope": "controlled one-dimensional notched-bar finite-element deployment",
        "case_name": case_name,
        "notch_depth_fraction": notch_depth,
        "load_scale": load_scale,
        "elements": elements,
        "load_points": points,
        "material_model": "chaboche_combined",
        "native_elapsed_seconds": float(reference["elapsed_seconds"]),
        "models": metrics,
        "model_failures": failures,
        "limitations": [
            "This is a reduced one-dimensional structural gate, not a general 3D learned AgentFEM material provider.",
            "The physics-integrator uses a numerical tangent of its fully discrete update and records any trust-region fallback used when plain global Newton leaves its local basin.",
            "The loading is proportional at each material point even though the training dataset is multiaxial.",
        ],
    }
    (output_directory / "structural_validation.json").write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    print(json.dumps(summary, indent=2), flush=True)
    return summary


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--elements", type=int, default=12)
    parser.add_argument("--points", type=int, default=81)
    parser.add_argument(
        "--models",
        nargs="+",
        choices=("gru", "physics_state_gru", "physics_integrator_nn"),
        default=("gru", "physics_state_gru", "physics_integrator_nn"),
    )
    parser.add_argument("--case", choices=("mild_id", "moderate_ood", "severe_ood"), default="severe_ood")
    args = parser.parse_args()
    run(
        elements=args.elements,
        points=args.points,
        model_names=tuple(args.models),
        case_name=args.case,
    )


if __name__ == "__main__":
    main()