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
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
"""Time-discretization and structural deployment gates for T2 DENRM."""

from __future__ import annotations

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 src import structural_validate_t2_models as structure
from src import t2_graybox_discrete_energy as graybox
from src.generate_t2_graybox_cohort import MATERIAL, design, solve


ROOT = Path(__file__).resolve().parents[1]
MODEL_PATH = ROOT / "models" / "t2_graybox_hardening_v1" / "denrm.pt"
ARTIFACT_DIR = ROOT / "artifacts" / "t2_graybox_hardening_v1"
OUTPUT = ARTIFACT_DIR / "deployment_validation.json"
BASIS = torch.tensor((1.0, -0.5, -0.5, 0.0, 0.0, 0.0), dtype=torch.float64)


def load_model(model_path: Path = MODEL_PATH) -> graybox.NeuralHardeningLaw:
    checkpoint = torch.load(model_path, map_location="cpu", weights_only=False)
    model = graybox.NeuralHardeningLaw(channels=2).double()
    model.load_state_dict(checkpoint["state_dict"])
    model.eval()
    return model


def _rollout(
    model: graybox.NeuralHardeningLaw,
    strain: np.ndarray,
    material: dict[str, object] = MATERIAL,
) -> dict[str, torch.Tensor]:
    selected = torch.tensor(strain, dtype=torch.float64)
    batch = len(selected)
    with torch.no_grad():
        return graybox.rollout(
            selected,
            torch.full((batch,), float(material["young_pa"]), dtype=torch.float64),
            torch.full((batch,), float(material["poisson"]), dtype=torch.float64),
            torch.full((batch,), float(material["yield_stress_pa"]), dtype=torch.float64),
            model,
            bisection_iterations=30,
        )


def time_discretization_gate(
    model: graybox.NeuralHardeningLaw,
    *,
    rows: list[dict[str, object]] | None = None,
    solve_function=solve,
    material: dict[str, object] = MATERIAL,
) -> dict[str, object]:
    rows = design(4) if rows is None else rows
    selected = [rows[index] for index in range(0, len(rows), 4)]
    result: dict[str, object] = {}
    predictions: dict[int, dict[str, torch.Tensor]] = {}
    references: dict[int, np.ndarray] = {}
    for points in (121, 481):
        solved = [solve_function(row, points=points) for row in selected]
        strain = np.stack([case["strain"] for case in solved])
        reference = np.stack([case["stress_pa"] for case in solved])
        prediction = _rollout(model, strain, material)
        error = prediction["stress"].numpy() - reference
        active = prediction["plastic_increment"] > 1.0e-11
        predictions[points] = prediction
        references[points] = reference
        result[str(points)] = {
            "trajectory_count": len(selected),
            "rmse_mpa": float(np.sqrt(np.mean(error**2)) / 1.0e6),
            "mae_mpa": float(np.mean(np.abs(error)) / 1.0e6),
            "maximum_yield_residual_pa": float(
                prediction["yield_residual"][active].abs().max()
            ),
        }
    coarse_terminal = predictions[121]["stress"][:, -1]
    fine_terminal = predictions[481]["stress"][:, -1]
    reference_scale = torch.tensor(references[481][:, -1]).norm().clamp_min(1.0)
    result["terminal_121_to_481_relative_change"] = float(
        (coarse_terminal - fine_terminal).norm() / reference_scale
    )
    return result


def _response(
    model: graybox.NeuralHardeningLaw,
    old_state: graybox.GrayboxState,
    scalar_strain: float,
) -> tuple[float, float, graybox.GrayboxState]:
    def evaluate(value: float):
        strain = (float(value) * BASIS).reshape(1, 6)
        with torch.no_grad():
            return graybox.advance(
                strain,
                old_state,
                torch.tensor((float(MATERIAL["young_pa"]),), dtype=torch.float64),
                torch.tensor((float(MATERIAL["poisson"]),), dtype=torch.float64),
                torch.tensor((float(MATERIAL["yield_stress_pa"]),), dtype=torch.float64),
                model,
                bisection_iterations=30,
            )

    stress, state, _ = evaluate(scalar_strain)
    generalized = float(graybox.double_contract(stress[0], BASIS))
    step = 1.0e-7 * max(1.0, abs(scalar_strain) / 0.005)
    upper, _, _ = evaluate(scalar_strain + step)
    lower, _, _ = evaluate(scalar_strain - step)
    tangent = float(
        (graybox.double_contract(upper[0], BASIS) - graybox.double_contract(lower[0], BASIS))
        / (2.0 * step)
    )
    return generalized, tangent, state


def _batch_response(
    model: graybox.NeuralHardeningLaw,
    old_state: graybox.GrayboxState,
    scalar_strain: np.ndarray,
    material: dict[str, object] = MATERIAL,
) -> tuple[np.ndarray, np.ndarray, graybox.GrayboxState]:
    """Evaluate every element in one batched constitutive call.

    The global bar problem has independent quadrature-point states, which map
    directly to DENRM's batch dimension.  Batching preserves the local return
    map while avoiding thousands of tiny Python/PyTorch calls.
    """

    values = torch.as_tensor(scalar_strain, dtype=torch.float64)
    batch = len(values)
    young = torch.full((batch,), float(material["young_pa"]), dtype=torch.float64)
    poisson = torch.full((batch,), float(material["poisson"]), dtype=torch.float64)
    yield_stress = torch.full(
        (batch,), float(material["yield_stress_pa"]), dtype=torch.float64
    )

    def evaluate(selected: torch.Tensor):
        strain = selected[:, None] * BASIS[None, :]
        return graybox.advance(
            strain,
            old_state,
            young,
            poisson,
            yield_stress,
            model,
            bisection_iterations=30,
        )

    with torch.no_grad():
        stress, state, _ = evaluate(values)
        generalized = graybox.double_contract(stress, BASIS)
        step = 1.0e-7 * torch.maximum(
            torch.ones_like(values), values.abs() / 0.005
        )
        upper, _, _ = evaluate(values + step)
        lower, _, _ = evaluate(values - step)
        tangent = (
            graybox.double_contract(upper, BASIS)
            - graybox.double_contract(lower, BASIS)
        ) / (2.0 * step)
    return generalized.numpy(), tangent.numpy(), state


def solve_structure(
    model: graybox.NeuralHardeningLaw,
    displacement: np.ndarray,
    *,
    elements: int = 12,
    notch_depth: float,
    material: dict[str, object] = MATERIAL,
) -> dict[str, np.ndarray | float]:
    nodes, area = structure.geometry(elements, notch_depth)
    lengths = np.diff(nodes)
    states = graybox.initial_state(elements, channels=2, dtype=torch.float64)
    u = np.zeros(elements + 1)
    reactions = []
    iterations = []
    trust_region_fallback_steps: list[int] = []
    started = time.perf_counter()
    for step_index, end_value in enumerate(displacement):
        if step_index > 0:
            u += np.linspace(0.0, end_value - u[-1], elements + 1)
        u[0] = 0.0
        u[-1] = end_value
        accepted = None
        for iteration in range(60):
            internal = np.zeros(elements + 1)
            stiffness = np.zeros((elements + 1, elements + 1))
            strains = np.diff(u) / lengths
            current_stress, current_tangent, trial_states = _batch_response(
                model, states, strains, material
            )
            for element in range(elements):
                stress = current_stress[element]
                tangent = float(np.clip(current_tangent[element], 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)
            # The local law is solved tightly, but its scalar tangent is a
            # finite-difference directional derivative across an active-set
            # switch.  Use an engineering equilibrium tolerance and a bounded
            # Newton correction, matching the deployment gate used for the
            # other learned constitutive models in this project.
            if np.linalg.norm(residual) <= 2.0e-6 * scale + 1.0e2:
                accepted = 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 accepted is None:
            # Reversal points can place several integration points on different
            # sides of the elastic/plastic active-set switch.  Recover the same
            # FE equilibrium with a bounded trust-region solve; the local
            # constitutive law and its committed state remain unchanged.
            end_fixed = float(end_value)

            # In a one-dimensional bar, equilibrium is equivalently expressed
            # by a single constant axial force.  Solving for all element
            # strains plus that force avoids poor conditioning in nodal
            # coordinates at a displacement reversal.
            def force_compatibility(unknown: np.ndarray) -> np.ndarray:
                candidate_strain = unknown[:-1]
                force_scaled = unknown[-1]
                candidate_stress, _, _ = _batch_response(
                    model, states, candidate_strain, material
                )
                force_balance = area * candidate_stress / 1.0e8 - force_scaled
                compatibility = (
                    np.dot(lengths, candidate_strain) - end_fixed
                ) / 0.005
                return np.concatenate((force_balance, (compatibility,)))

            def force_compatibility_jacobian(unknown: np.ndarray) -> np.ndarray:
                candidate_strain = unknown[:-1]
                _, candidate_tangent, _ = _batch_response(
                    model, states, candidate_strain, material
                )
                candidate_tangent = np.clip(candidate_tangent, 1.0e7, 4.0e11)
                jacobian = np.zeros((elements + 1, elements + 1))
                jacobian[np.arange(elements), np.arange(elements)] = (
                    area * candidate_tangent / 1.0e8
                )
                jacobian[:elements, -1] = -1.0
                jacobian[-1, :elements] = lengths / 0.005
                return jacobian

            initial_strain = np.diff(u) / lengths
            initial_force = float(internal[-1]) / 1.0e8
            recovered = least_squares(
                force_compatibility,
                np.concatenate((initial_strain, (initial_force,))),
                method="trf",
                jac=force_compatibility_jacobian,
                x_scale=np.concatenate((np.full(elements, 0.005), (1.0,))),
                max_nfev=120,
                xtol=1.0e-12,
                ftol=1.0e-12,
                gtol=1.0e-12,
            )
            if recovered.success:
                strains = recovered.x[:-1]
                u = np.concatenate(((0.0,), np.cumsum(lengths * strains)))
                current_stress, _, trial_states = _batch_response(
                    model, states, strains, material
                )
                internal = np.zeros(elements + 1)
                for element in range(elements):
                    b = np.asarray((-1.0 / lengths[element], 1.0 / lengths[element]))
                    dofs = (element, element + 1)
                    internal[list(dofs)] += (
                        area[element]
                        * current_stress[element]
                        * 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:
                    accepted = trial_states
                    iteration = 60 + int(recovered.nfev)
                    trust_region_fallback_steps.append(step_index)
        if accepted is None:
            raise RuntimeError(
                f"DENRM structural solve failed at step {step_index}; "
                f"max_abs_element_strain={float(np.max(np.abs(strains))):.6g}."
            )
        states = accepted
        reactions.append(float(internal[-1]))
        iterations.append(iteration + 1)
    return {
        "reaction": np.asarray(reactions),
        "iterations": np.asarray(iterations),
        "trust_region_fallback_steps": trust_region_fallback_steps,
        "elapsed_seconds": time.perf_counter() - started,
    }


def structural_gate(
    model: graybox.NeuralHardeningLaw,
    *,
    material: dict[str, object] = MATERIAL,
    native_law_factory=structure.material,
    artifact_dir: Path = ARTIFACT_DIR,
) -> dict[str, object]:
    result: dict[str, object] = {}
    figure, axes = plt.subplots(1, 2, figsize=(10.0, 4.2), constrained_layout=True)
    cases = (
        ("mild_cyclic", 0.12, structure.load_history(points=81)),
        ("severe_monotonic", 0.42, np.linspace(0.0, 0.0065, 61)),
    )
    for axis, (name, depth, displacement) in zip(
        axes,
        cases,
        strict=True,
    ):
        reference = structure.solve_native(
            12,
            displacement,
            notch_depth=depth,
            law_factory=native_law_factory,
        )
        learned = solve_structure(
            model, displacement, notch_depth=depth, material=material
        )
        difference = learned["reaction"] - reference["reaction"]
        relative = float(
            np.linalg.norm(difference) / max(np.linalg.norm(reference["reaction"]), 1.0)
        )
        result[name] = {
            "reaction_relative_l2": relative,
            "maximum_absolute_reaction_error": float(np.max(np.abs(difference))),
            "maximum_newton_iterations": int(np.max(learned["iterations"])),
            "mean_newton_iterations": float(np.mean(learned["iterations"])),
            "trust_region_fallback_count": len(
                learned["trust_region_fallback_steps"]
            ),
            "trust_region_fallback_steps": list(
                learned["trust_region_fallback_steps"]
            ),
            "elapsed_seconds": float(learned["elapsed_seconds"]),
        }
        axis.plot(displacement, reference["reaction"], label="AgentFEM reference")
        axis.plot(displacement, learned["reaction"], "--", label="DENRM")
        axis.set_title(name.replace("_", " "))
        axis.set_xlabel("prescribed end displacement")
        axis.set_ylabel("reaction")
        axis.grid(alpha=0.2)
    axes[0].legend(frameon=False)
    artifact_dir.mkdir(parents=True, exist_ok=True)
    figure.savefig(artifact_dir / "structural_reaction_comparison.png", dpi=190)
    plt.close(figure)

    # Deliberately retain a stronger cyclic extrapolation as a falsification
    # gate.  It currently exceeds the training strain envelope during reversal;
    # recording the failure is more informative than silently shrinking it.
    try:
        severe_cyclic = solve_structure(
            model,
            structure.load_history(points=81),
            notch_depth=0.42,
            material=material,
        )
        result["severe_cyclic_stress_test"] = {
            "passed": True,
            "maximum_newton_iterations": int(
                np.max(severe_cyclic["iterations"])
            ),
            "trust_region_fallback_count": len(
                severe_cyclic["trust_region_fallback_steps"]
            ),
        }
    except RuntimeError as error:
        result["severe_cyclic_stress_test"] = {
            "passed": False,
            "failure": str(error),
            "interpretation": (
                "strong cyclic localization leaves the present training envelope; "
                "this is a declared promotion-gate failure, not a successful deployment"
            ),
        }
    return result


def main() -> None:
    model = load_model()
    ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)
    result = {
        "time_discretization": time_discretization_gate(model),
        "structure": structural_gate(model),
    }
    OUTPUT.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()