AgentFEM-Material-Loading-Memory / src /validate_t2_graybox.py
HaomingLuo's picture
Add DENIM incomplete-physics closure dataset and evidence
bbe9b3e verified
Raw History Blame Contribute Delete
16.7 kB
"""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()