Download src/analyze_t2_denim_capability_v4.py from HaomingLuo/AgentFEM-Material-Loading-Memory: direct link, hf CLI and curl.
- Browser
- Download file 8.16 kB
-
https://huggingface.co/datasets/HaomingLuo/AgentFEM-Material-Loading-Memory/resolve/main/src/analyze_t2_denim_capability_v4.py
- Command line
-
hf download hf://datasets/HaomingLuo/AgentFEM-Material-Loading-Memory/src/analyze_t2_denim_capability_v4.py
-
curl -L -o analyze_t2_denim_capability_v4.py https://huggingface.co/datasets/HaomingLuo/AgentFEM-Material-Loading-Memory/resolve/main/src/analyze_t2_denim_capability_v4.py
8.16 kB
| """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()) | |