File size: 8,162 Bytes
4452800 | 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 | """Analyze and visualize DENIM capability-extension v4 without model claims."""
from __future__ import annotations
import json
from collections import defaultdict
from pathlib import Path
import h5py
import matplotlib.pyplot as plt
import numpy as np
from src.generate_t2_denim_capability_v4 import (
ARTIFACT_DIR,
DATA_PATH,
INDEX_PATH,
MANIFEST_PATH,
_write_json,
)
ROOT = Path(__file__).resolve().parents[1]
SUMMARY_PATH = ARTIFACT_DIR / "capability_summary.json"
PREVIEW_PATH = ARTIFACT_DIR / "capability_extension_preview.png"
def _rmse(left: np.ndarray, right: np.ndarray) -> float:
return float(np.sqrt(np.mean(np.square(np.asarray(left) - np.asarray(right)))))
def analyze() -> dict[str, object]:
rows = [json.loads(line) for line in INDEX_PATH.read_text(encoding="utf-8").splitlines() if line]
manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
by_group: dict[str, list[tuple[int, dict[str, object]]]] = defaultdict(list)
for index, row in enumerate(rows):
by_group[str(row["group_id"])].append((index, row))
resolution_errors: dict[int, list[float]] = defaultdict(list)
active_components = []
observation_keep = []
strain_noise = []
stress_noise_mpa = []
structure_metrics: dict[str, dict[str, float | int]] = {}
long_metrics: dict[str, list[float]] = defaultdict(list)
with h5py.File(DATA_PATH, "r") as h5:
for group_id, members in by_group.items():
if not group_id.startswith("matched-resolution-"):
continue
reference_index, _ = next((item for item in members if int(item[1]["points"]) == 481))
reference = h5[f"{reference_index:05d}"]
reference_time = reference["time_coordinate"][...]
reference_stress = reference["stress_pa"][...]
for index, row in members:
points = int(row["points"])
group = h5[f"{index:05d}"]
time = group["time_coordinate"][...]
stress = group["stress_pa"][...]
interpolated = np.column_stack(
[np.interp(time, reference_time, reference_stress[:, component]) for component in range(6)]
)
resolution_errors[points].append(_rmse(stress, interpolated) / 1.0e6)
mask = group["observation_mask"][...].astype(bool)
observation_keep.append(float(mask.mean()))
strain_noise.append(
_rmse(group["observed_strain"][...], group["strain"][...])
/ max(float(np.max(np.abs(group["strain"][...]))), 1.0e-15)
)
stress_noise_mpa.append(
_rmse(group["observed_stress_pa"][...], group["stress_pa"][...]) / 1.0e6
)
for index, row in enumerate(rows):
group = h5[f"{index:05d}"]
cohort = str(row["cohort"])
if cohort == "full_3d_nonproportional":
strain = group["strain"][...]
maxima = np.max(np.abs(strain), axis=0)
threshold = 0.01 * max(float(maxima.max()), 1.0e-15)
active_components.append(int(np.count_nonzero(maxima > threshold)))
elif cohort == "structure_derived":
entry = structure_metrics.setdefault(
str(row["group_id"]),
{"trajectory_count": 0, "maximum_peeq": 0.0, "maximum_absolute_stress_mpa": 0.0},
)
entry["trajectory_count"] = int(entry["trajectory_count"]) + 1
entry["maximum_peeq"] = max(float(entry["maximum_peeq"]), float(np.max(group["peeq"][...])))
entry["maximum_absolute_stress_mpa"] = max(
float(entry["maximum_absolute_stress_mpa"]),
float(np.max(np.abs(group["stress_pa"][...]))) / 1.0e6,
)
elif cohort == "long_cycle":
long_metrics[str(row["split"])].append(float(group["peeq"][-1]))
summary: dict[str, object] = {
"schema": "agentfem.physics-data.denim-capability-extension.analysis",
"sample_count": len(rows),
"cohort_counts": manifest["cohort_counts"],
"quality": manifest["quality"],
"long_cycle_final_peeq": {
split: {
"count": len(values),
"median": float(np.median(values)),
"maximum": float(np.max(values)),
}
for split, values in sorted(long_metrics.items())
},
"full_3d_component_coverage": {
"minimum_active_voigt_components": int(min(active_components)),
"median_active_voigt_components": float(np.median(active_components)),
"all_six_components_active_fraction": float(np.mean(np.asarray(active_components) == 6)),
},
"structure_derived": structure_metrics,
"matched_resolution_stress_rmse_mpa_against_481": {
str(points): {
"median": float(np.median(values)),
"maximum": float(np.max(values)),
}
for points, values in sorted(resolution_errors.items())
},
"observation_protocol": {
"retained_fraction_minimum": float(np.min(observation_keep)),
"retained_fraction_median": float(np.median(observation_keep)),
"retained_fraction_maximum": float(np.max(observation_keep)),
"relative_strain_noise_rmse_median": float(np.median(strain_noise)),
"stress_noise_rmse_mpa_median": float(np.median(stress_noise_mpa)),
},
}
_write_json(SUMMARY_PATH, summary)
return summary
def plot() -> Path:
ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)
with h5py.File(DATA_PATH, "r") as h5:
long = h5["00299"]
full3d = h5["00300"]
structural = h5["00600"]
observed = h5["00801"]
figure, axes = plt.subplots(2, 2, figsize=(13.0, 8.2), constrained_layout=True)
axes[0, 0].plot(long["time_coordinate"][...], long["stress_pa"][:, 0] / 1.0e6, lw=1.0, color="#1f6feb")
axes[0, 0].set_title("100-cycle long-horizon response")
axes[0, 0].set_xlabel("normalized history coordinate")
axes[0, 0].set_ylabel(r"$\sigma_{xx}$ (MPa)")
strain = full3d["strain"][...]
labels = ("xx", "yy", "zz", "xy", "yz", "xz")
for component, label in enumerate(labels):
axes[0, 1].plot(full3d["time_coordinate"][...], 100.0 * strain[:, component], lw=1.1, label=label)
axes[0, 1].set_title("Full six-component non-proportional path")
axes[0, 1].set_xlabel("normalized history coordinate")
axes[0, 1].set_ylabel("tensor strain (%)")
axes[0, 1].legend(ncol=3, fontsize=8, frameon=False)
axes[1, 0].plot(100.0 * structural["strain"][:, 0], structural["stress_pa"][:, 0] / 1.0e6, lw=1.5, color="#d97706")
axes[1, 0].set_title("AgentFEM-derived local structural path")
axes[1, 0].set_xlabel(r"$\varepsilon_{xx}$ (%)")
axes[1, 0].set_ylabel(r"$\sigma_{xx}$ (MPa)")
time = observed["time_coordinate"][...]
mask = observed["observation_mask"][...].astype(bool)
axes[1, 1].plot(time, observed["stress_pa"][:, 0] / 1.0e6, lw=1.5, color="#22c55e", label="clean truth")
axes[1, 1].scatter(
time[mask], observed["observed_stress_pa"][mask, 0] / 1.0e6,
s=10, alpha=0.65, color="#ef4444", label="noisy sparse observation",
)
axes[1, 1].set_title("Paired observation robustness protocol")
axes[1, 1].set_xlabel("normalized history coordinate")
axes[1, 1].set_ylabel(r"$\sigma_{xx}$ (MPa)")
axes[1, 1].legend(frameon=False, fontsize=8)
for axis in axes.ravel():
axis.grid(alpha=0.20)
figure.suptitle("AgentFEM DENIM capability extension v4", fontsize=16, fontweight="bold")
figure.savefig(PREVIEW_PATH, dpi=180)
plt.close(figure)
return PREVIEW_PATH
if __name__ == "__main__":
print(json.dumps(analyze(), indent=2, sort_keys=True))
print(plot())
|