AgentFEM-Material-Loading-Memory / src /t2_material_loading_memory.py
HaomingLuo's picture
Release AgentFEM Material Loading Memory v1
ebc46a9 verified
Raw
History Blame Contribute Delete
31.7 kB
"""Generate the T2 material-loading-memory pilot dataset.
The sample unit is one complete material-point trajectory. Time frames are not
counted as independent samples. The pilot deliberately keeps J2 linear
isotropic hardening and Chaboche combined hardening as separate model labels.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import platform
import time
from pathlib import Path
import h5py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import qmc
import agentfem
from agentfem import campaigns, constitutive
ROOT = Path(__file__).resolve().parents[1]
CONFIG_PATH = ROOT / "configs" / "t2_material_loading_memory_pilot.json"
DATA_DIR = ROOT / "data" / "t2_material_loading_memory_pilot"
ARTIFACT_DIR = ROOT / "artifacts" / "t2_material_loading_memory_pilot"
DATA_PATH = DATA_DIR / "t2_material_loading_memory_pilot.h5"
DESIGN_PATH = DATA_DIR / "design.jsonl"
INDEX_PATH = DATA_DIR / "index.jsonl"
AGENTFEM_COMMIT = "058faecc05aeda143d014fd229401003a9258bbb"
MATERIAL_MODELS = ("j2_linear_isotropic", "chaboche_combined")
PATH_FAMILIES = (
"monotonic_tension",
"unload_reload",
"tension_compression",
"symmetric_cyclic",
"mean_shifted_cyclic",
"variable_amplitude",
)
def load_config() -> dict[str, object]:
return json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
def _scale(value: float, bounds: list[float]) -> float:
return float(bounds[0] + value * (bounds[1] - bounds[0]))
def design_parameters(seed: int | None = None) -> tuple[dict[str, object], ...]:
"""Return a deterministic balanced 96-trajectory Sobol design."""
config = load_config()
actual_seed = int(config["seed"] if seed is None else seed)
ranges = config["ranges"]
unit = qmc.Sobol(12, scramble=True, seed=actual_seed).random_base2(7)
rows: list[dict[str, object]] = []
cursor = 0
for material_model in MATERIAL_MODELS:
for path_family in PATH_FAMILIES:
for replicate in range(8):
u = unit[cursor]
cursor += 1
row: dict[str, object] = {
"material_model": material_model,
"path_family": path_family,
"replicate": replicate,
"young_pa": _scale(u[0], ranges["young_pa"]),
"poisson": _scale(u[1], ranges["poisson"]),
"yield_stress_pa": _scale(u[2], ranges["yield_stress_pa"]),
"maximum_equivalent_strain": _scale(
u[3], ranges["maximum_equivalent_strain"]
),
"path_shape_a": float(u[10]),
"path_shape_b": float(u[11]),
}
if material_model == "j2_linear_isotropic":
row.update(
{
"hardening_modulus_pa": _scale(
u[4], ranges["j2_hardening_modulus_pa"]
),
"backstress_c1_pa": 0.0,
"backstress_gamma1": 0.0,
"backstress_c2_pa": 0.0,
"backstress_gamma2": 0.0,
"isotropic_saturation_pa": 0.0,
"isotropic_rate": 0.0,
}
)
else:
row.update(
{
"hardening_modulus_pa": 0.0,
"backstress_c1_pa": _scale(
u[4], ranges["chaboche_c1_pa"]
),
"backstress_gamma1": _scale(
u[5], ranges["chaboche_gamma1"]
),
"backstress_c2_pa": _scale(
u[6], ranges["chaboche_c2_pa"]
),
"backstress_gamma2": _scale(
u[7], ranges["chaboche_gamma2"]
),
"isotropic_saturation_pa": _scale(
u[8], ranges["chaboche_isotropic_saturation_pa"]
),
"isotropic_rate": _scale(
u[9], ranges["chaboche_isotropic_rate"]
),
}
)
rows.append(row)
if len(rows) != int(config["sample_count"]):
raise RuntimeError("T2 design size differs from the frozen configuration.")
return tuple(rows)
def case_identity(parameters: dict[str, object]) -> str:
return campaigns.case_id("t2_material_loading_memory_pilot", parameters)
def split_assignments(parameters: tuple[dict[str, object], ...]) -> dict[int, str]:
"""Create 6/1/1 train/validation/test splits within every stratum."""
seed = int(load_config()["seed"])
result: dict[int, str] = {}
for model_index, material_model in enumerate(MATERIAL_MODELS):
for path_index, path_family in enumerate(PATH_FAMILIES):
members = np.asarray(
[
index
for index, row in enumerate(parameters)
if row["material_model"] == material_model
and row["path_family"] == path_family
],
dtype=int,
)
rng = np.random.default_rng(seed + 100 * model_index + path_index)
members = rng.permutation(members)
for index in members[:6]:
result[int(index)] = "train"
result[int(members[6])] = "validation"
result[int(members[7])] = "test"
return result
def path_anchors(parameters: dict[str, object]) -> np.ndarray:
"""Return signed equivalent-deviatoric-strain control points."""
amplitude = float(parameters["maximum_equivalent_strain"])
a = float(parameters["path_shape_a"])
b = float(parameters["path_shape_b"])
family = str(parameters["path_family"])
if family == "monotonic_tension":
values = (0.0, amplitude)
elif family == "unload_reload":
unload = amplitude * (-0.25 + 0.60 * a)
reload = amplitude * (0.85 + 0.30 * b)
values = (0.0, amplitude, unload, reload)
elif family == "tension_compression":
reverse = -amplitude * (0.70 + 0.45 * a)
values = (0.0, amplitude, reverse)
elif family == "symmetric_cyclic":
values = (0.0, amplitude, -amplitude, amplitude, -amplitude, amplitude)
elif family == "mean_shifted_cyclic":
lower = -amplitude * (0.25 + 0.40 * a)
upper = amplitude * (0.90 + 0.10 * b)
values = (0.0, upper, lower, upper, lower, upper)
elif family == "variable_amplitude":
first_reverse = -amplitude * (0.55 + 0.30 * a)
second_reverse = -amplitude * (0.25 + 0.35 * b)
values = (
0.0,
0.45 * amplitude,
first_reverse,
amplitude,
second_reverse,
0.75 * amplitude,
-amplitude,
0.20 * amplitude,
)
else:
raise ValueError(f"Unknown path family: {family}")
return np.asarray(values, dtype=float)
def prescribed_history(
parameters: dict[str, object], *, points: int | None = None
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Return a path that samples every reversal anchor exactly.
The 241-point refinement doubles the interval count of every 121-point
segment. Therefore every coarse state is present at ``fine[::2]`` and the
refinement audit measures constitutive integration, not a missed path
extremum.
"""
base_count = int(load_config()["points_per_trajectory"])
count = int(base_count if points is None else points)
if count < 3 or count % 2 == 0:
raise ValueError("points must be an odd integer of at least three.")
anchors = path_anchors(parameters)
segments = len(anchors) - 1
def allocated(intervals: int) -> np.ndarray:
if intervals < segments:
raise ValueError("points must provide at least one interval per segment.")
values = np.full(segments, intervals // segments, dtype=int)
values[: intervals % segments] += 1
return values
base_segments = allocated(base_count - 1)
if (count - 1) % (base_count - 1) == 0:
segment_intervals = base_segments * ((count - 1) // (base_count - 1))
else:
segment_intervals = allocated(count - 1)
pieces: list[np.ndarray] = []
for index, intervals in enumerate(segment_intervals):
values = np.linspace(anchors[index], anchors[index + 1], intervals + 1)
pieces.append(values if index == 0 else values[1:])
scalar_strain = np.concatenate(pieces)
if len(scalar_strain) != count:
raise RuntimeError("Piecewise path allocation produced the wrong point count.")
time_coordinate = np.linspace(0.0, 1.0, count)
return time_coordinate, scalar_strain, anchors
def _strain_tensor(signed_equivalent_strain: float) -> np.ndarray:
value = float(signed_equivalent_strain)
return np.diag((value, -0.5 * value, -0.5 * value))
def _material(parameters: dict[str, object]):
if parameters["material_model"] == "j2_linear_isotropic":
return constitutive.J2LinearIsotropicHardening(
young=float(parameters["young_pa"]),
poisson=float(parameters["poisson"]),
yield_stress=float(parameters["yield_stress_pa"]),
hardening_modulus=float(parameters["hardening_modulus_pa"]),
)
return constitutive.chaboche(
young=float(parameters["young_pa"]),
poisson=float(parameters["poisson"]),
yield_stress=float(parameters["yield_stress_pa"]),
backstresses=(
(
float(parameters["backstress_c1_pa"]),
float(parameters["backstress_gamma1"]),
),
(
float(parameters["backstress_c2_pa"]),
float(parameters["backstress_gamma2"]),
),
),
isotropic_saturation=float(parameters["isotropic_saturation_pa"]),
isotropic_rate=float(parameters["isotropic_rate"]),
)
def solve_trajectory(
parameters: dict[str, object], *, points: int | None = None
) -> tuple[dict[str, np.ndarray], dict[str, float | int | bool]]:
"""Integrate one committed material-point path through AgentFEM."""
time_coordinate, scalar_strain, anchors = prescribed_history(
parameters, points=points
)
material = _material(parameters)
count = len(time_coordinate)
total_strain = np.empty((count, 3, 3), dtype=float)
stress = np.empty((count, 3, 3), dtype=float)
plastic_strain = np.empty((count, 3, 3), dtype=float)
peeq = np.empty(count, dtype=float)
signed_stress = np.empty(count, dtype=float)
mises = np.empty(count, dtype=float)
shifted_mises = np.empty(count, dtype=float)
yield_radius = np.empty(count, dtype=float)
trial_yield = np.empty(count, dtype=float)
plastic_increment = np.empty(count, dtype=float)
elastic = np.empty(count, dtype=np.uint8)
backstress = np.zeros((count, 3, 3), dtype=float)
backstress_components = np.zeros((count, 2, 3, 3), dtype=float)
state = None
for index, value in enumerate(scalar_strain):
strain = _strain_tensor(value)
update = material.update(strain, state)
state = update.state
total_strain[index] = strain
stress[index] = update.stress
plastic_strain[index] = state.plastic_strain
peeq[index] = state.equivalent_plastic_strain
signed_stress[index] = update.stress[0, 0] - update.stress[1, 1]
mises[index] = constitutive.von_mises(update.stress)
trial_yield[index] = update.yield_function_trial
plastic_increment[index] = update.plastic_multiplier_increment
elastic[index] = np.uint8(update.elastic)
if parameters["material_model"] == "chaboche_combined":
backstress[index] = state.total_backstress
backstress_components[index] = state.backstresses
shifted_mises[index] = constitutive.von_mises(
update.stress - backstress[index]
)
yield_radius[index] = material.current_yield_stress(peeq[index])
plastic_work_increment = np.zeros(count, dtype=float)
external_work_increment = np.zeros(count, dtype=float)
for index in range(1, count):
mean_stress = 0.5 * (stress[index] + stress[index - 1])
plastic_work_increment[index] = float(
np.tensordot(
mean_stress,
plastic_strain[index] - plastic_strain[index - 1],
)
)
external_work_increment[index] = float(
np.tensordot(
mean_stress,
total_strain[index] - total_strain[index - 1],
)
)
arrays = {
"time_coordinate": time_coordinate,
"path_anchors": anchors,
"signed_equivalent_strain": scalar_strain,
"total_strain": total_strain,
"stress_pa": stress,
"signed_equivalent_stress_pa": signed_stress,
"mises_stress_pa": mises,
"plastic_strain": plastic_strain,
"equivalent_plastic_strain": peeq,
"plastic_multiplier_increment": plastic_increment,
"elastic_step": elastic,
"trial_yield_function_pa": trial_yield,
"yield_radius_pa": yield_radius,
"shifted_mises_stress_pa": shifted_mises,
"backstress_pa": backstress,
"backstress_components_pa": backstress_components,
"plastic_work_increment_j_m3": plastic_work_increment,
"cumulative_plastic_work_j_m3": np.cumsum(plastic_work_increment),
"external_work_increment_j_m3": external_work_increment,
"cumulative_external_work_j_m3": np.cumsum(external_work_increment),
}
plastic_mask = plastic_increment > 0.0
zero_strain_mask = np.abs(scalar_strain) <= 1.0e-14
residual = np.abs(shifted_mises - yield_radius) / np.maximum(
yield_radius, 1.0
)
metrics: dict[str, float | int | bool] = {
"maximum_absolute_stress_pa": float(np.max(np.abs(signed_stress))),
"final_equivalent_plastic_strain": float(peeq[-1]),
"maximum_equivalent_plastic_strain": float(np.max(peeq)),
"final_cumulative_plastic_work_j_m3": float(
np.sum(plastic_work_increment)
),
"plastic_step_count": int(np.count_nonzero(plastic_mask)),
"maximum_plastic_strain_trace": float(
np.max(np.abs(np.trace(plastic_strain, axis1=1, axis2=2)))
),
"maximum_yield_surface_relative_residual": float(
np.max(residual[plastic_mask]) if np.any(plastic_mask) else 0.0
),
"minimum_peeq_increment": float(np.min(np.diff(peeq))),
"minimum_plastic_work_increment_j_m3": float(
np.min(plastic_work_increment)
),
"zero_strain_stress_range_pa": float(
np.ptp(signed_stress[zero_strain_mask])
if np.count_nonzero(zero_strain_mask) >= 2
else 0.0
),
"all_finite": bool(
all(np.all(np.isfinite(value)) for value in arrays.values())
),
}
return arrays, metrics
def _j2_monotonic_reference(parameters: dict[str, object]) -> tuple[float, float]:
strain = float(parameters["maximum_equivalent_strain"])
young = float(parameters["young_pa"])
poisson = float(parameters["poisson"])
shear = young / (2.0 * (1.0 + poisson))
yield_stress = float(parameters["yield_stress_pa"])
hardening = float(parameters["hardening_modulus_pa"])
trial = 3.0 * shear * strain
increment = max(0.0, (trial - yield_stress) / (3.0 * shear + hardening))
return yield_stress + hardening * increment, increment
def _sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def _write_json_atomic(path: Path, value: object) -> None:
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_text(
json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
os.replace(temporary, path)
def _write_jsonl_atomic(path: Path, rows: list[dict[str, object]]) -> None:
temporary = path.with_suffix(path.suffix + ".tmp")
with temporary.open("w", encoding="utf-8") as stream:
for row in rows:
stream.write(json.dumps(row, sort_keys=True) + "\n")
os.replace(temporary, path)
def _quality_failures(
parameters: tuple[dict[str, object], ...],
records: list[dict[str, object]],
refinements: list[dict[str, object]],
) -> list[dict[str, object]]:
thresholds = load_config()["quality_thresholds"]
failures: list[dict[str, object]] = []
for index, (row, record) in enumerate(zip(parameters, records, strict=True)):
metrics = record["metrics"]
checks = {
"all_finite": bool(metrics["all_finite"]),
"initial_stress": abs(float(record["initial_signed_stress_pa"]))
<= thresholds["initial_stress_pa"],
"plastic_incompressibility": metrics["maximum_plastic_strain_trace"]
<= thresholds["plastic_strain_trace"],
"peeq_monotone": metrics["minimum_peeq_increment"]
>= -thresholds["equivalent_plastic_strain_decrease"],
"yield_surface": metrics["maximum_yield_surface_relative_residual"]
<= thresholds["yield_surface_relative_residual"],
"positive_total_plastic_work": metrics[
"final_cumulative_plastic_work_j_m3"
]
> thresholds["final_plastic_work_minimum_j_m3"],
"plastic_excitation": metrics["plastic_step_count"] > 0,
}
if row["material_model"] == "j2_linear_isotropic":
checks["j2_nonnegative_plastic_work_increment"] = metrics[
"minimum_plastic_work_increment_j_m3"
] >= -thresholds["j2_plastic_work_negative_tolerance_j_m3"]
if (
row["material_model"] == "j2_linear_isotropic"
and row["path_family"] == "monotonic_tension"
):
checks["j2_analytical"] = (
record["j2_analytical_relative_error"]
<= thresholds["j2_monotonic_analytical_relative_error"]
)
if row["path_family"] == "symmetric_cyclic":
checks["history_memory_contrast"] = metrics[
"zero_strain_stress_range_pa"
] >= thresholds["zero_strain_memory_contrast_pa"]
failed = sorted(name for name, passed in checks.items() if not passed)
if failed:
failures.append({"index": index, "failed_checks": failed})
for item in refinements:
failed = []
if item["maximum_stress_relative_change"] > thresholds[
"refined_stress_relative_change"
]:
failed.append("refined_stress")
if item["maximum_peeq_relative_change"] > thresholds[
"refined_peeq_relative_change"
]:
failed.append("refined_peeq")
if failed:
failures.append({"index": item["index"], "failed_checks": failed})
return failures
def _plot_preview(
parameters: tuple[dict[str, object], ...],
stored: dict[int, dict[str, np.ndarray]],
) -> Path:
ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)
fig, axes = plt.subplots(2, 3, figsize=(12.0, 7.2), constrained_layout=True)
colors = {"j2_linear_isotropic": "#2563eb", "chaboche_combined": "#dc2626"}
labels = {"j2_linear_isotropic": "J2 isotropic", "chaboche_combined": "Chaboche"}
for axis, family in zip(axes.flat, PATH_FAMILIES, strict=True):
for model in MATERIAL_MODELS:
index = next(
idx
for idx, row in enumerate(parameters)
if row["material_model"] == model
and row["path_family"] == family
and row["replicate"] == 0
)
arrays = stored[index]
axis.plot(
100.0 * arrays["signed_equivalent_strain"],
arrays["signed_equivalent_stress_pa"] / 1.0e6,
color=colors[model],
lw=1.8,
label=labels[model],
)
axis.axhline(0.0, color="#9ca3af", lw=0.6)
axis.axvline(0.0, color="#9ca3af", lw=0.6)
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=9)
fig.suptitle(
"AgentFEM T2 pilot: path-dependent material memory\n"
"Representative independent cases; J2 and Chaboche parameters are not matched.",
fontsize=13,
)
output = ARTIFACT_DIR / "hysteresis_preview.png"
fig.savefig(output, dpi=180)
plt.close(fig)
return output
def generate() -> dict[str, object]:
config = load_config()
parameters = design_parameters()
splits = split_assignments(parameters)
DATA_DIR.mkdir(parents=True, exist_ok=True)
ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)
design_rows: list[dict[str, object]] = []
records: list[dict[str, object]] = []
stored: dict[int, dict[str, np.ndarray]] = {}
started = time.perf_counter()
temporary = DATA_PATH.with_suffix(".h5.tmp")
with h5py.File(temporary, "w") as h5:
h5.attrs["schema"] = config["schema"]
h5.attrs["schema_version"] = config["schema_version"]
h5.attrs["dataset_version"] = config["dataset_version"]
h5.attrs["agentfem_version"] = agentfem.__version__
h5.attrs["agentfem_commit"] = AGENTFEM_COMMIT
h5.attrs["numpy_version"] = np.__version__
h5.attrs["python_version"] = platform.python_version()
for index, row in enumerate(parameters):
case_id = case_identity(row)
split = splits[index]
arrays, metrics = solve_trajectory(row)
reference_error = 0.0
if (
row["material_model"] == "j2_linear_isotropic"
and row["path_family"] == "monotonic_tension"
):
reference_stress, reference_peeq = _j2_monotonic_reference(row)
reference_error = max(
abs(arrays["signed_equivalent_stress_pa"][-1] - reference_stress)
/ max(reference_stress, 1.0),
abs(arrays["equivalent_plastic_strain"][-1] - reference_peeq)
/ max(reference_peeq, 1.0e-15),
)
record: dict[str, object] = {
"id": f"{index:05d}",
"case_id": case_id,
"split": split,
"parameters": row,
"metrics": metrics,
"initial_signed_stress_pa": float(
arrays["signed_equivalent_stress_pa"][0]
),
"j2_analytical_relative_error": float(reference_error),
}
group = h5.create_group(f"{index:05d}")
group.attrs["case_id"] = case_id
group.attrs["split"] = split
group.attrs["material_model"] = row["material_model"]
group.attrs["path_family"] = row["path_family"]
group.attrs["parameters_json"] = json.dumps(row, sort_keys=True)
group.attrs["metrics_json"] = json.dumps(metrics, sort_keys=True)
for name, value in arrays.items():
group.create_dataset(name, data=value, compression="gzip", shuffle=True)
design_rows.append(
{
"id": f"{index:05d}",
"case_id": case_id,
"split": split,
"parameters": row,
}
)
records.append(record)
if row["replicate"] == 0:
stored[index] = arrays
os.replace(temporary, DATA_PATH)
_write_jsonl_atomic(DESIGN_PATH, design_rows)
_write_jsonl_atomic(INDEX_PATH, records)
refinements: list[dict[str, object]] = []
for index, row in enumerate(parameters):
if row["replicate"] != 0:
continue
coarse = stored[index]
fine, _ = solve_trajectory(row, points=241)
fine_stress = fine["signed_equivalent_stress_pa"][::2]
fine_peeq = fine["equivalent_plastic_strain"][::2]
stress_scale = max(float(np.max(np.abs(fine_stress))), 1.0)
peeq_scale = max(float(np.max(fine_peeq)), 1.0e-15)
refinements.append(
{
"index": index,
"material_model": row["material_model"],
"path_family": row["path_family"],
"maximum_stress_relative_change": float(
np.max(
np.abs(
coarse["signed_equivalent_stress_pa"] - fine_stress
)
)
/ stress_scale
),
"maximum_peeq_relative_change": float(
np.max(
np.abs(coarse["equivalent_plastic_strain"] - fine_peeq)
)
/ peeq_scale
),
}
)
failures = _quality_failures(parameters, records, refinements)
preview = _plot_preview(parameters, stored)
summary = {
"status": "accepted" if not failures else "rejected",
"sample_count": len(parameters),
"material_models": {
model: sum(row["material_model"] == model for row in parameters)
for model in MATERIAL_MODELS
},
"path_families": {
family: sum(row["path_family"] == family for row in parameters)
for family in PATH_FAMILIES
},
"splits": {
name: sum(value == name for value in splits.values())
for name in ("train", "validation", "test")
},
"all_case_ids_unique": len({case_identity(row) for row in parameters})
== len(parameters),
"quality_failure_count": len(failures),
"quality_failures": failures,
"maximum_yield_surface_relative_residual": float(
max(
record["metrics"]["maximum_yield_surface_relative_residual"]
for record in records
)
),
"maximum_plastic_strain_trace": float(
max(
record["metrics"]["maximum_plastic_strain_trace"]
for record in records
)
),
"maximum_j2_analytical_relative_error": float(
max(record["j2_analytical_relative_error"] for record in records)
),
"minimum_symmetric_zero_strain_memory_contrast_pa": float(
min(
record["metrics"]["zero_strain_stress_range_pa"]
for record in records
if record["parameters"]["path_family"] == "symmetric_cyclic"
)
),
"maximum_refined_stress_relative_change": float(
max(item["maximum_stress_relative_change"] for item in refinements)
),
"maximum_refined_peeq_relative_change": float(
max(item["maximum_peeq_relative_change"] for item in refinements)
),
"minimum_plastic_work_increment_j_m3": float(
min(
record["metrics"]["minimum_plastic_work_increment_j_m3"]
for record in records
)
),
"wall_seconds": float(time.perf_counter() - started),
"data_file": str(DATA_PATH.relative_to(ROOT)),
"data_bytes": DATA_PATH.stat().st_size,
"data_sha256": _sha256(DATA_PATH),
"preview": str(preview.relative_to(ROOT)),
"agentfem_version": agentfem.__version__,
"agentfem_commit": AGENTFEM_COMMIT,
"refinement_audits": refinements,
}
_write_json_atomic(ARTIFACT_DIR / "quality.json", summary)
report = f"""# T2 material-loading-memory pilot quality report
Status: **{summary['status']}**
Independent trajectories: {summary['sample_count']}
Quality failures: {summary['quality_failure_count']}
## Coverage
- J2 linear isotropic hardening: {summary['material_models']['j2_linear_isotropic']}
- Chaboche combined hardening: {summary['material_models']['chaboche_combined']}
- Six loading-path families: 16 trajectories each
- Train/validation/test trajectories: 72/12/12
- Points per trajectory: {config['points_per_trajectory']}
## Verification
- Maximum yield-surface relative residual: {summary['maximum_yield_surface_relative_residual']:.3e}
- Maximum plastic-strain trace: {summary['maximum_plastic_strain_trace']:.3e}
- Maximum J2 monotonic analytical relative error: {summary['maximum_j2_analytical_relative_error']:.3e}
- Minimum repeated-zero-strain stress contrast in symmetric cycles: {summary['minimum_symmetric_zero_strain_memory_contrast_pa'] / 1.0e6:.3f} MPa
- Maximum 121-to-241-point stress change: {summary['maximum_refined_stress_relative_change']:.3%}
- Maximum 121-to-241-point PEEQ change: {summary['maximum_refined_peeq_relative_change']:.3%}
- Minimum raw `stress:plastic-strain-increment` diagnostic: {summary['minimum_plastic_work_increment_j_m3']:.3e} J/m^3
- All case IDs unique: {summary['all_case_ids_unique']}
The data are synthetic three-dimensional small-strain material-point histories under
prescribed proportional deviatoric strain. They are not structural FEM fields, an
experimental material calibration, or fatigue-life labels. Chaboche remains explicitly
labelled as an experimental AgentFEM capability. For Chaboche, raw stress work on plastic
strain is recorded but is not labelled as thermodynamic dissipation because the current
material-point contract does not expose a complete backstress storage/recovery energy split.
![Hysteresis preview](hysteresis_preview.png)
"""
(ARTIFACT_DIR / "QUALITY_REPORT.md").write_text(report, encoding="utf-8")
print(json.dumps(summary, indent=2, sort_keys=True))
if failures:
raise RuntimeError(f"T2 pilot failed {len(failures)} quality checks.")
return summary
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--generate", action="store_true", help="Generate and verify the full pilot."
)
parser.add_argument(
"--design-only", action="store_true", help="Write only the frozen design."
)
args = parser.parse_args()
parameters = design_parameters()
splits = split_assignments(parameters)
if args.design_only:
DATA_DIR.mkdir(parents=True, exist_ok=True)
_write_jsonl_atomic(
DESIGN_PATH,
[
{
"id": f"{index:05d}",
"case_id": case_identity(row),
"split": splits[index],
"parameters": row,
}
for index, row in enumerate(parameters)
],
)
print(DESIGN_PATH)
return
if args.generate:
generate()
return
parser.error("Choose --generate or --design-only.")
if __name__ == "__main__":
main()