"""Train a physics-embedded neural stress integrator for T2 multiaxial v2. The neural network predicts a bounded correction to a mechanics-based plastic multiplier estimate. A differentiable consistency correction then projects the update back toward the J2/Chaboche yield surface. Plastic strain, equivalent plastic strain and two Chaboche backstress tensors are explicit state variables; stress is reconstructed from elasticity rather than directly regressed. """ from __future__ import annotations import argparse import json import math import random import time from dataclasses import dataclass from pathlib import Path import numpy as np import torch import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from torch import nn from torch.nn import functional as F try: from src import train_t2_multiaxial_models as baseline except ModuleNotFoundError: import train_t2_multiaxial_models as baseline ROOT = Path(__file__).resolve().parents[1] MODEL_ROOT = ROOT / "models" / "t2_multiaxial_ood_v2" ARTIFACT_ROOT = ROOT / "artifacts" / "t2_multiaxial_ood_v2" MODEL_NAME = "physics_integrator_nn" WEIGHTS = torch.tensor((1.0, 1.0, 1.0, 2.0, 2.0, 2.0)) DISPLAY_MODELS = ( "pointwise_mlp", "gru", "lstm", "causal_tcn", "physics_state_gru", MODEL_NAME, ) def write_comparison_plot(metrics: dict[str, object]) -> None: labels = ("MLP", "GRU", "LSTM", "TCN", "Physics\nstate GRU", "Physics\nintegrator NN") colors = ("#9ca3af", "#2563eb", "#7c3aed", "#0f766e", "#dc2626", "#059669") figure, axes = plt.subplots(1, 3, figsize=(15.0, 4.4), constrained_layout=True) for axis, protocol in zip(axes, baseline.PROTOCOLS, strict=True): values = [metrics[protocol][name]["rmse_mpa"] for name in DISPLAY_MODELS] axis.bar(range(len(values)), values, color=colors) axis.set_xticks(range(len(values)), labels, rotation=25, ha="right") axis.set_ylabel("Stress RMSE (MPa)") axis.set_title(protocol.replace("_", " ").upper()) axis.set_yscale("symlog", linthresh=0.1) axis.grid(axis="y", alpha=0.2) figure.savefig(ARTIFACT_ROOT / "model_protocol_comparison.png", dpi=190) plt.close(figure) def deviatoric(value: torch.Tensor) -> torch.Tensor: mean = value[..., :3].mean(dim=-1, keepdim=True) return torch.cat((value[..., :3] - mean, value[..., 3:]), dim=-1) def double_contract(left: torch.Tensor, right: torch.Tensor) -> torch.Tensor: weights = WEIGHTS.to(dtype=left.dtype, device=left.device) return (left * right * weights).sum(dim=-1) def mises(value: torch.Tensor) -> torch.Tensor: return torch.sqrt(torch.clamp(1.5 * double_contract(deviatoric(value), deviatoric(value)), min=0.0)) def elastic_stress(strain: torch.Tensor, plastic: torch.Tensor, parameters: torch.Tensor) -> torch.Tensor: elastic = strain - plastic young = parameters[..., 0] poisson = parameters[..., 1] shear = young / (2.0 * (1.0 + poisson)) bulk = young / (3.0 * (1.0 - 2.0 * poisson)) trace = elastic[..., :3].sum(dim=-1) mean = trace / 3.0 normal = 2.0 * shear[..., None] * (elastic[..., :3] - mean[..., None]) + bulk[..., None] * trace[..., None] return torch.cat((normal, 2.0 * shear[..., None] * elastic[..., 3:]), dim=-1) @dataclass class State: plastic: torch.Tensor peeq: torch.Tensor alpha1: torch.Tensor alpha2: torch.Tensor def initial_state(batch: int, *, dtype: torch.dtype = torch.float32, device: torch.device | str = "cpu") -> State: zeros6 = torch.zeros((batch, 6), dtype=dtype, device=device) return State(zeros6, torch.zeros(batch, dtype=dtype, device=device), zeros6.clone(), zeros6.clone()) class PlasticIncrementNet(nn.Module): """Small network that corrects a dimensionless mechanics-based seed.""" def __init__(self, input_size: int = 17, hidden: int = 48): super().__init__() self.network = nn.Sequential( nn.Linear(input_size, hidden), nn.SiLU(), nn.Linear(hidden, hidden), nn.SiLU(), nn.Linear(hidden, 1), ) nn.init.zeros_(self.network[-1].weight) nn.init.zeros_(self.network[-1].bias) def forward(self, value: torch.Tensor) -> torch.Tensor: return 0.75 * torch.tanh(self.network(value).squeeze(-1)) def _indicator(parameters: torch.Tensor) -> torch.Tensor: chaboche = (parameters[..., 4].abs() > 0.0).to(parameters.dtype) return torch.stack((1.0 - chaboche, chaboche), dim=-1) def trial_quantities(strain: torch.Tensor, state: State, parameters: torch.Tensor) -> dict[str, torch.Tensor]: trial = elastic_stress(strain, state.plastic, parameters) trial_dev = deviatoric(trial) shifted = trial_dev - state.alpha1 - state.alpha2 q = mises(shifted) chaboche = _indicator(parameters)[..., 1] radius_j2 = parameters[..., 2] + parameters[..., 3] * state.peeq radius_ch = parameters[..., 2] + parameters[..., 8] * (1.0 - torch.exp(-parameters[..., 9] * state.peeq)) radius = (1.0 - chaboche) * radius_j2 + chaboche * radius_ch f_trial = q - radius shear = parameters[..., 0] / (2.0 * (1.0 + parameters[..., 1])) denominator_j2 = 3.0 * shear + parameters[..., 3] denominator_ch = ( 3.0 * shear + parameters[..., 4] + parameters[..., 6] + parameters[..., 8] * parameters[..., 9] * torch.exp(-parameters[..., 9] * state.peeq) ) denominator = (1.0 - chaboche) * denominator_j2 + chaboche * denominator_ch seed = F.relu(f_trial) / denominator.clamp_min(1.0) return { "trial": trial, "trial_dev": trial_dev, "q": q, "radius": radius, "f_trial": f_trial, "shear": shear, "seed": seed, "chaboche": chaboche, } def features( quantities: dict[str, torch.Tensor], state: State, parameters: torch.Tensor, strain_increment: torch.Tensor, parameter_mean: torch.Tensor, parameter_std: torch.Tensor, ) -> torch.Tensor: scale = parameters[..., 2].clamp_min(1.0) strain_norm = torch.sqrt(torch.clamp((2.0 / 3.0) * double_contract(deviatoric(strain_increment), deviatoric(strain_increment)), min=0.0)) normalized_parameters = (parameters - parameter_mean) / parameter_std scalars = torch.stack( ( quantities["f_trial"] / scale, quantities["q"] / scale, state.peeq / 0.02, strain_norm / 0.01, quantities["seed"] / 0.01, ), dim=-1, ) return torch.cat((scalars, normalized_parameters, _indicator(parameters)), dim=-1) def _chaboche_consistency( increment: torch.Tensor, trial_dev: torch.Tensor, state: State, parameters: torch.Tensor, shear: torch.Tensor, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: gamma1, gamma2 = parameters[..., 5], parameters[..., 7] theta1 = 1.0 / (1.0 + gamma1 * increment) theta2 = 1.0 / (1.0 + gamma2 * increment) base = trial_dev - theta1[..., None] * state.alpha1 - theta2[..., None] * state.alpha2 q_base = mises(base).clamp_min(1.0) radius = parameters[..., 2] + parameters[..., 8] * ( 1.0 - torch.exp(-parameters[..., 9] * (state.peeq + increment)) ) value = ( q_base - 3.0 * shear * increment - increment * (theta1 * parameters[..., 4] + theta2 * parameters[..., 6]) - radius ) dbase = ( (gamma1 * theta1.square())[..., None] * state.alpha1 + (gamma2 * theta2.square())[..., None] * state.alpha2 ) dq = 1.5 * double_contract(base, dbase) / q_base derivative = ( dq - 3.0 * shear - theta1 * parameters[..., 4] - theta2 * parameters[..., 6] + increment * ( gamma1 * theta1.square() * parameters[..., 4] + gamma2 * theta2.square() * parameters[..., 6] ) - parameters[..., 8] * parameters[..., 9] * torch.exp(-parameters[..., 9] * (state.peeq + increment)) ) return value, derivative, theta1, theta2, base def advance( strain: torch.Tensor, previous_strain: torch.Tensor, state: State, parameters: torch.Tensor, model: PlasticIncrementNet, parameter_mean: torch.Tensor, parameter_std: torch.Tensor, *, correction_steps: int = 2, prescribed_increment: torch.Tensor | None = None, ) -> tuple[torch.Tensor, State, dict[str, torch.Tensor]]: quantities = trial_quantities(strain, state, parameters) plastic = quantities["f_trial"] > torch.maximum(parameters[..., 2], torch.ones_like(parameters[..., 2])) * 1.0e-12 if prescribed_increment is None: value = features(quantities, state, parameters, strain - previous_strain, parameter_mean, parameter_std) increment = quantities["seed"] * torch.exp(model(value)) ch_mask = plastic & (quantities["chaboche"] > 0.5) for _ in range(correction_steps): residual, derivative, _, _, _ = _chaboche_consistency( increment, quantities["trial_dev"], state, parameters, quantities["shear"] ) updated = torch.clamp(increment - residual / derivative.clamp(max=-1.0), min=0.0) increment = torch.where(ch_mask, updated, increment) else: increment = prescribed_increment increment = torch.where(plastic, increment, torch.zeros_like(increment)) chaboche = quantities["chaboche"] > 0.5 residual, _, theta1, theta2, base = _chaboche_consistency( increment, quantities["trial_dev"], state, parameters, quantities["shear"] ) direction_j2 = 1.5 * quantities["trial_dev"] / quantities["q"].clamp_min(1.0)[..., None] direction_ch = 1.5 * base / mises(base).clamp_min(1.0)[..., None] direction = torch.where(chaboche[..., None], direction_ch, direction_j2) direction = torch.where(plastic[..., None], direction, torch.zeros_like(direction)) updated_plastic = state.plastic + increment[..., None] * direction updated_peeq = state.peeq + increment alpha1_candidate = theta1[..., None] * ( state.alpha1 + (2.0 / 3.0) * parameters[..., 4, None] * increment[..., None] * direction ) alpha2_candidate = theta2[..., None] * ( state.alpha2 + (2.0 / 3.0) * parameters[..., 6, None] * increment[..., None] * direction ) alpha1 = torch.where((plastic & chaboche)[..., None], alpha1_candidate, state.alpha1) alpha2 = torch.where((plastic & chaboche)[..., None], alpha2_candidate, state.alpha2) updated = State(updated_plastic, updated_peeq, alpha1, alpha2) stress = elastic_stress(strain, updated.plastic, parameters) diagnostics = { **quantities, "increment": increment, "consistency_residual": torch.where(plastic & chaboche, residual, torch.zeros_like(residual)), } return stress, updated, diagnostics def rollout( strain: torch.Tensor, parameters: torch.Tensor, model: PlasticIncrementNet, parameter_mean: torch.Tensor, parameter_std: torch.Tensor, *, correction_steps: int = 2, ) -> dict[str, torch.Tensor]: batch, points, _ = strain.shape state = initial_state(batch, dtype=strain.dtype, device=strain.device) previous = torch.zeros_like(strain[:, 0]) stresses, plastics, peeqs, backstresses, increments, residuals = [], [], [], [], [], [] for index in range(points): stress, state, info = advance( strain[:, index], previous, state, parameters, model, parameter_mean, parameter_std, correction_steps=correction_steps, ) stresses.append(stress) plastics.append(state.plastic) peeqs.append(state.peeq) backstresses.append(state.alpha1 + state.alpha2) increments.append(info["increment"]) residuals.append(info["consistency_residual"]) previous = strain[:, index] return { "stress": torch.stack(stresses, dim=1), "plastic_strain": torch.stack(plastics, dim=1), "peeq": torch.stack(peeqs, dim=1), "backstress": torch.stack(backstresses, dim=1), "plastic_increment": torch.stack(increments, dim=1), "consistency_residual": torch.stack(residuals, dim=1), } def correction_training_data( bundle: baseline.DatasetBundle, selected: torch.Tensor, parameter_mean: torch.Tensor, parameter_std: torch.Tensor, ) -> tuple[torch.Tensor, torch.Tensor]: indices = torch.where(selected)[0] strain = bundle.strain[indices] parameters = bundle.parameters[indices] reference_increment = bundle.plastic_increment[indices] state = initial_state(len(indices), dtype=strain.dtype) previous = torch.zeros_like(strain[:, 0]) feature_rows, targets = [], [] dummy = PlasticIncrementNet() for point in range(strain.shape[1]): quantities = trial_quantities(strain[:, point], state, parameters) active = reference_increment[:, point] > 1.0e-12 if active.any(): value = features( quantities, state, parameters, strain[:, point] - previous, parameter_mean, parameter_std, ) ratio = reference_increment[:, point] / quantities["seed"].clamp_min(1.0e-14) feature_rows.append(value[active]) targets.append(torch.log(ratio[active]).clamp(-0.75, 0.75)) _, state, _ = advance( strain[:, point], previous, state, parameters, dummy, parameter_mean, parameter_std, correction_steps=0, prescribed_increment=reference_increment[:, point], ) previous = strain[:, point] return torch.cat(feature_rows), torch.cat(targets) def train_correction( x: torch.Tensor, y: torch.Tensor, *, epochs: int, seed: int, batch_size: int = 4096, ) -> tuple[PlasticIncrementNet, list[dict[str, float]]]: torch.manual_seed(seed) random.seed(seed) model = PlasticIncrementNet(input_size=x.shape[-1]) order = torch.randperm(len(x)) validation_count = max(1, len(order) // 10) validation = order[:validation_count] training = order[validation_count:] optimizer = torch.optim.AdamW(model.parameters(), lr=2.0e-3, weight_decay=1.0e-6) best = None best_loss = math.inf stale = 0 history = [] for epoch in range(epochs): model.train() training = training[torch.randperm(len(training))] losses = [] for start in range(0, len(training), batch_size): idx = training[start : start + batch_size] optimizer.zero_grad(set_to_none=True) loss = F.mse_loss(model(x[idx]), y[idx]) loss.backward() optimizer.step() losses.append(float(loss.detach())) model.eval() with torch.no_grad(): validation_loss = float(F.mse_loss(model(x[validation]), y[validation])) history.append({"epoch": epoch + 1, "train_loss": float(np.mean(losses)), "validation_loss": validation_loss}) if validation_loss < best_loss - 1.0e-8: best_loss = validation_loss best = {key: value.detach().clone() for key, value in model.state_dict().items()} stale = 0 else: stale += 1 if stale >= 8 and epoch >= 14: break if best is None: raise RuntimeError("No physics-integrator checkpoint was produced.") model.load_state_dict(best) return model, history def evaluate( bundle: baseline.DatasetBundle, selected: torch.Tensor, model: PlasticIncrementNet, parameter_mean: torch.Tensor, parameter_std: torch.Tensor, ) -> dict[str, float | int]: indices = torch.where(selected)[0] started = time.perf_counter() with torch.no_grad(): prediction = rollout( bundle.strain[indices], bundle.parameters[indices], model, parameter_mean, parameter_std, ) elapsed = time.perf_counter() - started reference = bundle.stress[indices] error = prediction["stress"] - reference rmse = torch.sqrt((error.square()).mean()) centered = reference - reference.mean() reference_mises = baseline.voigt_mises(reference) predicted_mises = baseline.voigt_mises(prediction["stress"]) peak_error = ( (predicted_mises.amax(dim=1) - reference_mises.amax(dim=1)).abs() / reference_mises.amax(dim=1).clamp_min(1.0) ).mean() strain_increment = bundle.strain[indices, 1:] - bundle.strain[indices, :-1] predicted_work = baseline._double_contract( 0.5 * (prediction["stress"][:, 1:] + prediction["stress"][:, :-1]), strain_increment ).sum(dim=1) reference_work = baseline._double_contract( 0.5 * (reference[:, 1:] + reference[:, :-1]), strain_increment ).sum(dim=1) work_error = ((predicted_work - reference_work).abs() / reference_work.abs().clamp_min(1.0)).mean() decimated = torch.arange(0, bundle.strain.shape[1], 2) with torch.no_grad(): coarse = rollout( bundle.strain[indices][:, decimated], bundle.parameters[indices], model, parameter_mean, parameter_std, )["stress"] coarse_rmse = torch.sqrt(((coarse - reference[:, decimated]).square()).mean()) plastic_mask = prediction["plastic_increment"] > 1.0e-12 residual = prediction["consistency_residual"].abs() scale = bundle.parameters[indices, 2][:, None].clamp_min(1.0) return { "rmse_mpa": float(rmse / 1.0e6), "mae_mpa": float(error.abs().mean() / 1.0e6), "r2": float(1.0 - error.square().sum() / centered.square().sum().clamp_min(1.0)), "mean_peak_mises_relative_error": float(peak_error), "mean_work_relative_error": float(work_error), "decimated_121_state_rmse_mpa": float(coarse_rmse / 1.0e6), "plastic_strain_rmse": float(torch.sqrt(((prediction["plastic_strain"] - bundle.plastic_strain[indices]).square()).mean())), "backstress_rmse_mpa": float(torch.sqrt(((prediction["backstress"] - bundle.backstress[indices]).square()).mean()) / 1.0e6), "peeq_rmse": float(torch.sqrt(((prediction["peeq"] - bundle.peeq[indices]).square()).mean())), "peeq_nonmonotone_fraction": float((prediction["peeq"][:, 1:] < prediction["peeq"][:, :-1]).float().mean()), "maximum_plastic_strain_trace": float(prediction["plastic_strain"][..., :3].sum(dim=-1).abs().max()), "mean_consistency_relative_residual": float((residual / scale)[plastic_mask].mean()) if plastic_mask.any() else 0.0, "inference_seconds": elapsed, "trajectory_count": int(len(indices)), } def train_suite(*, protocols: tuple[str, ...], epochs: int, seed: int) -> dict[str, object]: torch.set_num_threads(min(8, max(1, torch.get_num_threads()))) bundle = baseline.load_dataset() metrics_path = ARTIFACT_ROOT / "model_metrics.json" metrics = json.loads(metrics_path.read_text(encoding="utf-8")) summary: dict[str, object] = {"model": MODEL_NAME, "protocols": {}, "status": "completed"} for protocol_index, protocol in enumerate(protocols): split = baseline.masks(bundle, baseline.PROTOCOLS[protocol]) norm = baseline.fit_normalization(bundle, split["train"]) print(f"building correction data for {protocol}", flush=True) x, y = correction_training_data( bundle, split["train"], norm.parameter_mean.squeeze(0), norm.parameter_std.squeeze(0) ) print(f"training {protocol}/{MODEL_NAME} on {len(x)} plastic transitions", flush=True) model, history = train_correction(x, y, epochs=epochs, seed=seed + protocol_index) result = evaluate( bundle, split["test"], model, norm.parameter_mean.squeeze(0), norm.parameter_std.squeeze(0), ) result["parameter_count"] = sum(value.numel() for value in model.parameters()) result["epochs_completed"] = len(history) result["best_validation_loss"] = min(row["validation_loss"] for row in history) metrics.setdefault(protocol, {})[MODEL_NAME] = result checkpoint = { "model_name": MODEL_NAME, "protocol": protocol, "state_dict": model.state_dict(), "input_size": x.shape[-1], "parameter_mean": norm.parameter_mean.squeeze(0), "parameter_std": norm.parameter_std.squeeze(0), "correction_steps": 2, "state_variables": ["plastic_strain_dev", "equivalent_plastic_strain", "backstress_1_dev", "backstress_2_dev"], "architecture": "neural plastic-increment seed plus differentiable J2/Chaboche consistency correction", "seed": seed + protocol_index, } torch.save(checkpoint, MODEL_ROOT / f"{protocol}_{MODEL_NAME}.pt") (MODEL_ROOT / f"{protocol}_{MODEL_NAME}_history.json").write_text( json.dumps(history, indent=2) + "\n", encoding="utf-8" ) summary["protocols"][protocol] = { "plastic_training_transitions": len(x), "target_log_correction_min": float(y.min()), "target_log_correction_max": float(y.max()), "metrics": result, } print(json.dumps({"protocol": protocol, **result}, sort_keys=True), flush=True) metrics_path.write_text(json.dumps(metrics, indent=2, sort_keys=True) + "\n", encoding="utf-8") write_comparison_plot(metrics) output = ARTIFACT_ROOT / "physics_integrator_summary.json" output.write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8") return summary def load_checkpoint(protocol: str = "id") -> tuple[PlasticIncrementNet, torch.Tensor, torch.Tensor, int]: checkpoint = torch.load(MODEL_ROOT / f"{protocol}_{MODEL_NAME}.pt", map_location="cpu", weights_only=False) model = PlasticIncrementNet(input_size=int(checkpoint["input_size"])) model.load_state_dict(checkpoint["state_dict"]) model.eval() return model, checkpoint["parameter_mean"], checkpoint["parameter_std"], int(checkpoint["correction_steps"]) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--protocols", nargs="+", choices=tuple(baseline.PROTOCOLS), default=tuple(baseline.PROTOCOLS)) parser.add_argument("--epochs", type=int, default=40) parser.add_argument("--seed", type=int, default=20261011) args = parser.parse_args() train_suite(protocols=tuple(args.protocols), epochs=args.epochs, seed=args.seed) if __name__ == "__main__": main()