File size: 31,674 Bytes
ebc46a9 | 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 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 | """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.

"""
(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()
|