Download code/package_t4_structural_dynamics_v1.py from HaomingLuo/AgentFEM-Structural-Dynamics-Virtual-Sensing: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/datasets/HaomingLuo/AgentFEM-Structural-Dynamics-Virtual-Sensing/resolve/main/code/package_t4_structural_dynamics_v1.py
- Command line
-
hf download hf://datasets/HaomingLuo/AgentFEM-Structural-Dynamics-Virtual-Sensing/code/package_t4_structural_dynamics_v1.py
-
curl -L -o package_t4_structural_dynamics_v1.py https://huggingface.co/datasets/HaomingLuo/AgentFEM-Structural-Dynamics-Virtual-Sensing/resolve/main/code/package_t4_structural_dynamics_v1.py
11.7 kB
| """Audit 128 T4 configurations and pack them into eight publication shards.""" | |
| from __future__ import annotations | |
| import hashlib | |
| import csv | |
| import json | |
| import os | |
| from pathlib import Path | |
| import shutil | |
| import h5py | |
| import numpy as np | |
| try: | |
| from .audit_t4_modal_transient_consistency import measured_frequency | |
| except ImportError: | |
| from audit_t4_modal_transient_consistency import measured_frequency | |
| try: | |
| from .t4_structural_dynamics_v1 import ( | |
| CASE_DIR, | |
| DATA_DIR, | |
| configuration_design, | |
| load_config, | |
| valid_case_file, | |
| ) | |
| except ImportError: | |
| from t4_structural_dynamics_v1 import ( | |
| CASE_DIR, | |
| DATA_DIR, | |
| configuration_design, | |
| load_config, | |
| valid_case_file, | |
| ) | |
| SHARD_DIR = DATA_DIR / "shards" | |
| def sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as stream: | |
| for chunk in iter(lambda: stream.read(1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def audit_cases() -> tuple[list[dict], dict]: | |
| config = load_config() | |
| rows = configuration_design(config) | |
| index: list[dict] = [] | |
| missing: list[str] = [] | |
| invalid: list[str] = [] | |
| frequency_errors: list[float] = [] | |
| modal_transient_frequency_errors: list[float] = [] | |
| energy_residuals: list[float] = [] | |
| for row in rows: | |
| path = CASE_DIR / f"{row['case_id']}.h5" | |
| if not path.is_file(): | |
| missing.append(row["case_id"]) | |
| continue | |
| if not valid_case_file(path): | |
| invalid.append(row["case_id"]) | |
| continue | |
| with h5py.File(path, "r") as h5: | |
| quality = json.loads(h5.attrs["quality_json"]) | |
| frequency_errors.append(float(quality["first_frequency_relative_error"])) | |
| energy_residuals.append(float(quality["maximum_energy_balance_relative_residual"])) | |
| case_config = json.loads(h5.attrs["config_json"]) | |
| modal_hz = float(h5["modal/frequencies_hz"][0]) | |
| pulse = h5["trajectories/half_sine_pulse"] | |
| transient_hz = measured_frequency( | |
| np.asarray(pulse["time_s"], dtype=np.float64), | |
| np.asarray(pulse["sensor_displacement_m"], dtype=np.float64)[:, -1], | |
| modal_hz, | |
| ) | |
| modal_transient_frequency_errors.append(abs(transient_hz - modal_hz) / modal_hz) | |
| for name in sorted(h5["trajectories"]): | |
| trajectory = h5[f"trajectories/{name}"] | |
| required = ( | |
| "time_s", | |
| "force_scale", | |
| "sensor_displacement_m", | |
| "fields/displacement_m", | |
| "fields/velocity_m_per_s", | |
| "fields/acceleration_m_per_s2", | |
| ) | |
| finite = all(np.all(np.isfinite(trajectory[key][...])) for key in required) | |
| if not finite: | |
| invalid.append(f"{row['case_id']}:{name}:nonfinite") | |
| sensors = np.asarray(trajectory["sensor_displacement_m"]) | |
| spec = json.loads(trajectory.attrs["spec_json"]) | |
| index.append( | |
| { | |
| "trajectory_id": f"{row['case_id']}__{name}", | |
| "configuration_id": int(row["configuration_id"]), | |
| "case_id": row["case_id"], | |
| "split": row["split"], | |
| "protocol_role": row["protocol_role"], | |
| "excitation": name, | |
| "excitation_spec": spec, | |
| "length_m": case_config["geometry"]["length_m"], | |
| "height_m": case_config["geometry"]["height_m"], | |
| "young_pa": case_config["material"]["young_pa"], | |
| "density_kg_m3": case_config["material"]["density_kg_m3"], | |
| "damping_ratio": case_config["dynamics"]["target_damping_ratio"], | |
| "traction_amplitude_pa": case_config["dynamics"]["traction_amplitude_pa"], | |
| "first_frequency_hz": float(h5["modal/frequencies_hz"][0]), | |
| "time_states": int(trajectory["time_s"].shape[0]), | |
| "field_frames": int(trajectory["fields/time_s"].shape[0]), | |
| "sensor_count": int(sensors.shape[1]), | |
| "max_abs_tip_displacement_m": float(np.max(np.abs(sensors[:, -1]))), | |
| "energy_balance_relative_residual": float( | |
| np.max(np.abs(trajectory["energy_balance_relative_residual"][...])) | |
| ), | |
| } | |
| ) | |
| counts = { | |
| "configuration_count": len(rows) - len(missing), | |
| "trajectory_count": len(index), | |
| "split_trajectories": { | |
| split: sum(item["split"] == split for item in index) | |
| for split in ("train", "validation", "test") | |
| }, | |
| "protocol_trajectories": { | |
| role: sum(item["protocol_role"] == role for item in index) | |
| for role in ("id", "excitation_ood", "parameter_ood") | |
| }, | |
| } | |
| refinement_records = [] | |
| refinement_missing = [] | |
| for configuration_id in config["quality"]["time_refinement_configuration_ids"]: | |
| audit_path = DATA_DIR / "time_refinement" / f"config_{configuration_id:04d}.json" | |
| if not audit_path.is_file(): | |
| refinement_missing.append(configuration_id) | |
| else: | |
| refinement_records.append(json.loads(audit_path.read_text(encoding="utf-8"))) | |
| refinement_values = [ | |
| float(record["five_sensor_history_relative_l2"]) | |
| for record in refinement_records | |
| ] | |
| quality = { | |
| **counts, | |
| "missing_configurations": missing, | |
| "invalid_entries": sorted(set(invalid)), | |
| "maximum_first_frequency_relative_error": max(frequency_errors, default=float("nan")), | |
| "median_first_frequency_relative_error": float(np.median(frequency_errors)) | |
| if frequency_errors | |
| else float("nan"), | |
| "maximum_modal_transient_frequency_relative_difference": max( | |
| modal_transient_frequency_errors, default=float("nan") | |
| ), | |
| "median_modal_transient_frequency_relative_difference": float( | |
| np.median(modal_transient_frequency_errors) | |
| ) | |
| if modal_transient_frequency_errors | |
| else float("nan"), | |
| "maximum_energy_balance_relative_residual": max(energy_residuals, default=float("nan")), | |
| "median_energy_balance_relative_residual": float(np.median(energy_residuals)) | |
| if energy_residuals | |
| else float("nan"), | |
| "time_refinement": { | |
| "configuration_ids": config["quality"]["time_refinement_configuration_ids"], | |
| "missing_configuration_ids": refinement_missing, | |
| "maximum_five_sensor_history_relative_l2": max( | |
| refinement_values, default=float("nan") | |
| ), | |
| "median_five_sensor_history_relative_l2": float(np.median(refinement_values)) | |
| if refinement_values | |
| else float("nan"), | |
| "records": refinement_records, | |
| }, | |
| } | |
| quality["gates"] = { | |
| "complete": not missing and counts["configuration_count"] == 128 and counts["trajectory_count"] == 512, | |
| "valid": not invalid, | |
| "frequency": quality["maximum_first_frequency_relative_error"] | |
| <= float(config["quality"]["maximum_first_frequency_analytical_relative_error"]), | |
| "modal_transient_consistency": quality[ | |
| "maximum_modal_transient_frequency_relative_difference" | |
| ] | |
| <= 0.005, | |
| "energy": quality["maximum_energy_balance_relative_residual"] | |
| <= float(config["quality"]["maximum_energy_balance_relative_residual"]), | |
| "splits": counts["split_trajectories"] == {"train": 384, "validation": 64, "test": 64}, | |
| "time_refinement": not refinement_missing | |
| and all(record["passed"] for record in refinement_records), | |
| } | |
| quality["passed"] = bool(all(quality["gates"].values())) | |
| return index, quality | |
| def pack_shards(index: list[dict], quality: dict) -> dict: | |
| if not quality["passed"]: | |
| raise RuntimeError(f"Cannot pack failed T4 campaign: {quality}") | |
| config = load_config() | |
| rows = configuration_design(config) | |
| per_shard = int(config["storage"]["formal_shard_configuration_count"]) | |
| temporary_dir = DATA_DIR / "shards_building" | |
| if temporary_dir.exists(): | |
| shutil.rmtree(temporary_dir) | |
| temporary_dir.mkdir(parents=True) | |
| shard_records = [] | |
| for start in range(0, len(rows), per_shard): | |
| selected = rows[start : start + per_shard] | |
| shard_path = temporary_dir / f"t4_structural_dynamics_v1_{start // per_shard:02d}.h5" | |
| with h5py.File(shard_path, "w") as target: | |
| target.attrs["schema"] = "agentfem.physics-data.structural-dynamics-v1-shard" | |
| target.attrs["schema_version"] = "1.1.0" | |
| target.attrs["configuration_start"] = start | |
| target.attrs["configuration_stop"] = start + len(selected) | |
| for row in selected: | |
| with h5py.File(CASE_DIR / f"{row['case_id']}.h5", "r") as source: | |
| destination = target.create_group(row["case_id"]) | |
| for key, value in source.attrs.items(): | |
| destination.attrs[key] = value | |
| for name in source: | |
| source.copy(name, destination, name=name) | |
| shard_records.append( | |
| { | |
| "path": f"shards/{shard_path.name}", | |
| "configuration_start": start, | |
| "configuration_stop": start + len(selected), | |
| "configuration_count": len(selected), | |
| "trajectory_count": 4 * len(selected), | |
| "bytes": shard_path.stat().st_size, | |
| "sha256": sha256(shard_path), | |
| } | |
| ) | |
| if SHARD_DIR.exists(): | |
| shutil.rmtree(SHARD_DIR) | |
| os.replace(temporary_dir, SHARD_DIR) | |
| for item in index: | |
| shard = int(item["configuration_id"]) // per_shard | |
| item["shard"] = f"shards/t4_structural_dynamics_v1_{shard:02d}.h5" | |
| item["group"] = f"{item['case_id']}/trajectories/{item['excitation']}" | |
| (DATA_DIR / "index.jsonl").write_text( | |
| "".join(json.dumps(item, sort_keys=True) + "\n" for item in index), encoding="utf-8" | |
| ) | |
| with (DATA_DIR / "index.csv").open("w", encoding="utf-8", newline="") as stream: | |
| flattened = [] | |
| for item in index: | |
| row = dict(item) | |
| row["excitation_spec"] = json.dumps(row["excitation_spec"], sort_keys=True) | |
| flattened.append(row) | |
| writer = csv.DictWriter(stream, fieldnames=list(flattened[0])) | |
| writer.writeheader() | |
| writer.writerows(flattened) | |
| manifest = { | |
| "dataset": "AgentFEM-Structural-Dynamics-Virtual-Sensing", | |
| "release": "v1.1.0-local-candidate", | |
| "configuration_count": 128, | |
| "trajectory_count": 512, | |
| "shards": shard_records, | |
| "software": config["software"], | |
| } | |
| (DATA_DIR / "manifest.json").write_text( | |
| json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8" | |
| ) | |
| (DATA_DIR / "quality.json").write_text( | |
| json.dumps(quality, indent=2, sort_keys=True) + "\n", encoding="utf-8" | |
| ) | |
| return manifest | |
| def main() -> None: | |
| index, quality = audit_cases() | |
| print(json.dumps(quality, indent=2, sort_keys=True)) | |
| if quality["passed"]: | |
| print(json.dumps(pack_shards(index, quality), indent=2, sort_keys=True)) | |
| if __name__ == "__main__": | |
| main() | |