AgentFEM-Material-Loading-Memory / src /t2_material_loading_memory_v1.py
HaomingLuo's picture
Release AgentFEM Material Loading Memory v1
ebc46a9 verified
Raw History Blame Contribute Delete
30.6 kB
"""Build the restartable T2 material-loading-memory v1 dataset.
One sample is one complete material-point trajectory. The 121 states within a
trajectory are never counted as independent samples. J2 linear isotropic
hardening and Chaboche combined hardening remain explicit 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
try:
from src import t2_material_loading_memory as core
except ModuleNotFoundError: # Direct execution from the src directory.
import t2_material_loading_memory as core
ROOT = Path(__file__).resolve().parents[1]
CONFIG_PATH = ROOT / "configs" / "t2_material_loading_memory_v1.json"
DATA_DIR = ROOT / "data" / "t2_material_loading_memory_v1"
SAMPLE_DIR = DATA_DIR / "samples"
RECORD_DIR = DATA_DIR / "records"
SHARD_DIR = DATA_DIR / "shards"
ARTIFACT_DIR = ROOT / "artifacts" / "t2_material_loading_memory_v1"
DESIGN_PATH = DATA_DIR / "design.jsonl"
INDEX_PATH = DATA_DIR / "index.jsonl"
MANIFEST_PATH = DATA_DIR / "manifest.json"
AGENTFEM_COMMIT = "058faecc05aeda143d014fd229401003a9258bbb"
MATERIAL_MODELS = core.MATERIAL_MODELS
PATH_FAMILIES = core.PATH_FAMILIES
REQUIRED_ARRAYS = (
"time_coordinate",
"path_anchors",
"signed_equivalent_strain",
"total_strain",
"stress_pa",
"signed_equivalent_stress_pa",
"mises_stress_pa",
"plastic_strain",
"equivalent_plastic_strain",
"plastic_multiplier_increment",
"elastic_step",
"trial_yield_function_pa",
"yield_radius_pa",
"shifted_mises_stress_pa",
"backstress_pa",
"backstress_components_pa",
"plastic_work_increment_j_m3",
"cumulative_plastic_work_j_m3",
"external_work_increment_j_m3",
"cumulative_external_work_j_m3",
)
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 1,008-trajectory Sobol design."""
config = load_config()
actual_seed = int(config["seed"] if seed is None else seed)
ranges = config["ranges"]
per_stratum = int(config["samples_per_stratum"])
required = len(MATERIAL_MODELS) * len(PATH_FAMILIES) * per_stratum
exponent = int(np.ceil(np.log2(required)))
unit = qmc.Sobol(12, scramble=True, seed=actual_seed).random_base2(exponent)
rows: list[dict[str, object]] = []
cursor = 0
for material_model in MATERIAL_MODELS:
for path_family in PATH_FAMILIES:
for replicate in range(per_stratum):
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 v1 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_v1", parameters)
def split_assignments(parameters: tuple[dict[str, object], ...]) -> dict[int, str]:
"""Create 64/10/10 train/validation/test splits in 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[:64]:
result[int(index)] = "train"
for index in members[64:74]:
result[int(index)] = "validation"
for index in members[74:84]:
result[int(index)] = "test"
return result
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:
path.parent.mkdir(parents=True, exist_ok=True)
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:
path.parent.mkdir(parents=True, exist_ok=True)
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 _write_npz_atomic(path: Path, arrays: dict[str, np.ndarray]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
with temporary.open("wb") as stream:
np.savez_compressed(stream, **arrays)
os.replace(temporary, path)
def sample_paths(index: int) -> tuple[Path, Path]:
return SAMPLE_DIR / f"{index:05d}.npz", RECORD_DIR / f"{index:05d}.json"
def write_design() -> Path:
parameters = design_parameters()
splits = split_assignments(parameters)
rows = [
{
"id": f"{index:05d}",
"case_id": case_identity(row),
"split": splits[index],
"parameters": row,
}
for index, row in enumerate(parameters)
]
_write_jsonl_atomic(DESIGN_PATH, rows)
return DESIGN_PATH
def _sample_complete(index: int, expected_case_id: str) -> bool:
sample_path, record_path = sample_paths(index)
if not sample_path.exists() or not record_path.exists():
return False
try:
record = json.loads(record_path.read_text(encoding="utf-8"))
if record["case_id"] != expected_case_id:
return False
with np.load(sample_path) as arrays:
if set(REQUIRED_ARRAYS) - set(arrays.files):
return False
return all(np.isfinite(arrays[name]).all() for name in REQUIRED_ARRAYS)
except (OSError, ValueError, KeyError, json.JSONDecodeError):
return False
def _solve_record(
index: int, parameters: dict[str, object], split: str
) -> tuple[dict[str, np.ndarray], dict[str, object]]:
points = int(load_config()["points_per_trajectory"])
arrays, metrics = core.solve_trajectory(parameters, points=points)
reference_error = 0.0
if (
parameters["material_model"] == "j2_linear_isotropic"
and parameters["path_family"] == "monotonic_tension"
):
reference_stress, reference_peeq = core._j2_monotonic_reference(parameters)
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_identity(parameters),
"split": split,
"parameters": parameters,
"metrics": metrics,
"initial_signed_stress_pa": float(arrays["signed_equivalent_stress_pa"][0]),
"j2_analytical_relative_error": float(reference_error),
}
return arrays, record
def generate_range(start: int, stop: int, *, force: bool = False) -> dict[str, object]:
parameters = design_parameters()
splits = split_assignments(parameters)
if start < 0 or stop > len(parameters) or start >= stop:
raise ValueError(f"Invalid range [{start}, {stop}) for {len(parameters)} samples.")
if not DESIGN_PATH.exists():
write_design()
started = time.perf_counter()
generated = 0
reused = 0
failures: list[dict[str, object]] = []
for index in range(start, stop):
row = parameters[index]
case_id = case_identity(row)
if not force and _sample_complete(index, case_id):
reused += 1
continue
sample_path, record_path = sample_paths(index)
try:
arrays, record = _solve_record(index, row, splits[index])
_write_npz_atomic(sample_path, arrays)
_write_json_atomic(record_path, record)
generated += 1
except Exception as exc: # Preserve failed identities instead of hiding them.
failures.append(
{
"id": f"{index:05d}",
"case_id": case_id,
"error_type": type(exc).__name__,
"error": str(exc),
}
)
summary = {
"start": start,
"stop": stop,
"generated": generated,
"reused": reused,
"failures": failures,
"wall_seconds": float(time.perf_counter() - started),
}
_write_json_atomic(ARTIFACT_DIR / f"range_{start:05d}_{stop:05d}.json", summary)
print(json.dumps(summary, indent=2, sort_keys=True))
if failures:
raise RuntimeError(f"Range [{start}, {stop}) had {len(failures)} failures.")
return summary
def _load_records() -> list[dict[str, object]]:
count = int(load_config()["sample_count"])
records: list[dict[str, object]] = []
missing: list[int] = []
for index in range(count):
_, record_path = sample_paths(index)
if not record_path.exists():
missing.append(index)
continue
records.append(json.loads(record_path.read_text(encoding="utf-8")))
if missing:
raise RuntimeError(f"Missing {len(missing)} records; first IDs: {missing[:8]}")
return records
def package_shards() -> dict[str, object]:
config = load_config()
parameters = design_parameters()
records = _load_records()
SHARD_DIR.mkdir(parents=True, exist_ok=True)
index_rows: list[dict[str, object]] = []
shard_rows: list[dict[str, object]] = []
for shard_index, members in enumerate(
np.array_split(np.arange(len(parameters), dtype=int), int(config["shard_count"]))
):
output = SHARD_DIR / f"part-{shard_index:05d}.h5"
temporary = output.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 in members:
record = records[int(index)]
sample_path, _ = sample_paths(int(index))
if not _sample_complete(int(index), str(record["case_id"])):
raise RuntimeError(f"Incomplete sample: {int(index):05d}")
group = h5.create_group(f"{int(index):05d}")
group.attrs["case_id"] = record["case_id"]
group.attrs["split"] = record["split"]
group.attrs["material_model"] = record["parameters"]["material_model"]
group.attrs["path_family"] = record["parameters"]["path_family"]
group.attrs["parameters_json"] = json.dumps(
record["parameters"], sort_keys=True
)
group.attrs["metrics_json"] = json.dumps(record["metrics"], sort_keys=True)
with np.load(sample_path) as arrays:
for name in REQUIRED_ARRAYS:
group.create_dataset(
name, data=arrays[name], compression="gzip", shuffle=True
)
index_rows.append(
{
**record,
"shard": str(output.relative_to(ROOT)),
}
)
os.replace(temporary, output)
shard_rows.append(
{
"path": str(output.relative_to(ROOT)),
"first_id": f"{int(members[0]):05d}",
"last_id": f"{int(members[-1]):05d}",
"sample_count": int(len(members)),
"bytes": output.stat().st_size,
"sha256": _sha256(output),
}
)
index_rows.sort(key=lambda row: str(row["id"]))
_write_jsonl_atomic(INDEX_PATH, index_rows)
manifest = {
"schema": config["schema"],
"schema_version": config["schema_version"],
"dataset_version": config["dataset_version"],
"sample_count": len(parameters),
"points_per_trajectory": config["points_per_trajectory"],
"agentfem_version": agentfem.__version__,
"agentfem_commit": AGENTFEM_COMMIT,
"shards": shard_rows,
}
_write_json_atomic(MANIFEST_PATH, manifest)
print(json.dumps(manifest, indent=2, sort_keys=True))
return manifest
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 _refinement_audits(
parameters: tuple[dict[str, object], ...]
) -> list[dict[str, object]]:
selected = [
index
for index, row in enumerate(parameters)
if int(row["replicate"]) in (0, int(load_config()["samples_per_stratum"]) - 1)
]
refinements: list[dict[str, object]] = []
for index in selected:
row = parameters[index]
sample_path, _ = sample_paths(index)
with np.load(sample_path) as coarse:
coarse_stress = np.asarray(coarse["signed_equivalent_stress_pa"])
coarse_peeq = np.asarray(coarse["equivalent_plastic_strain"])
fine, _ = core.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_stress - fine_stress)) / stress_scale
),
"maximum_peeq_relative_change": float(
np.max(np.abs(coarse_peeq - fine_peeq)) / peeq_scale
),
}
)
return refinements
def _create_preview(parameters: tuple[dict[str, object], ...]) -> 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
)
sample_path, _ = sample_paths(index)
with np.load(sample_path) as arrays:
strain = np.asarray(arrays["signed_equivalent_strain"])
stress = np.asarray(arrays["signed_equivalent_stress_pa"])
axis.plot(100.0 * strain, stress / 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 v1: 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 audit_dataset() -> dict[str, object]:
config = load_config()
parameters = design_parameters()
splits = split_assignments(parameters)
records = _load_records()
manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
integrity_failures: list[dict[str, object]] = []
observed_ids: list[str] = []
for shard in manifest["shards"]:
path = ROOT / shard["path"]
if _sha256(path) != shard["sha256"]:
integrity_failures.append({"shard": shard["path"], "error": "sha256"})
continue
with h5py.File(path, "r") as h5:
observed_ids.extend(sorted(h5.keys()))
for sample_id, group in h5.items():
missing = sorted(set(REQUIRED_ARRAYS) - set(group.keys()))
nonfinite = [
name for name in REQUIRED_ARRAYS if name in group and not np.isfinite(group[name][:]).all()
]
if missing or nonfinite:
integrity_failures.append(
{"id": sample_id, "missing": missing, "nonfinite": nonfinite}
)
expected_ids = [f"{index:05d}" for index in range(len(parameters))]
if observed_ids != expected_ids:
integrity_failures.append({"error": "sample_id_coverage"})
refinements = _refinement_audits(parameters)
failures = _quality_failures(parameters, records, refinements)
failures.extend(integrity_failures)
preview = _create_preview(parameters)
summary = {
"status": "accepted" if not failures else "rejected",
"sample_count": len(parameters),
"points_per_trajectory": config["points_per_trajectory"],
"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)
),
"data_bytes": int(sum(int(shard["bytes"]) for shard in manifest["shards"])),
"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 v1 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: 168 trajectories each
- Train/validation/test trajectories: 768/120/120
- Points per trajectory: {config['points_per_trajectory']}
- Packaged HDF5 shards: {len(manifest['shards'])}
## 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 across 24 audits: {summary['maximum_refined_stress_relative_change']:.3%}
- Maximum 121-to-241-point PEEQ change across 24 audits: {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 v1 failed {len(failures)} quality checks.")
return summary
def validate_design() -> dict[str, object]:
parameters = design_parameters()
splits = split_assignments(parameters)
config = load_config()
result = {
"sample_count": len(parameters),
"unique_case_ids": len({case_identity(row) for row in parameters}),
"splits": {
name: sum(value == name for value in splits.values())
for name in ("train", "validation", "test")
},
"strata": {
f"{model}/{family}": sum(
row["material_model"] == model and row["path_family"] == family
for row in parameters
)
for model in MATERIAL_MODELS
for family in PATH_FAMILIES
},
"expected": {
"sample_count": config["sample_count"],
"splits": config["splits"],
},
}
if result["sample_count"] != config["sample_count"]:
raise RuntimeError("Unexpected design size.")
if result["unique_case_ids"] != result["sample_count"]:
raise RuntimeError("Duplicate case IDs.")
if result["splits"] != config["splits"]:
raise RuntimeError("Unexpected split counts.")
print(json.dumps(result, indent=2, sort_keys=True))
return result
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--design-only", action="store_true")
parser.add_argument("--validate-design", action="store_true")
parser.add_argument("--range", nargs=2, type=int, metavar=("START", "STOP"))
parser.add_argument("--force", action="store_true")
parser.add_argument("--package", action="store_true")
parser.add_argument("--audit", action="store_true")
parser.add_argument("--all", action="store_true")
args = parser.parse_args()
if args.design_only:
print(write_design())
return
if args.validate_design:
validate_design()
return
if args.range:
generate_range(args.range[0], args.range[1], force=args.force)
return
if args.package:
package_shards()
return
if args.audit:
audit_dataset()
return
if args.all:
generate_range(0, int(load_config()["sample_count"]), force=args.force)
package_shards()
audit_dataset()
return
parser.error("Choose --design-only, --validate-design, --range, --package, --audit or --all.")
if __name__ == "__main__":
main()