File size: 14,087 Bytes
caa4bd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b0b96f
caa4bd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b0b96f
 
caa4bd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b0b96f
caa4bd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b0b96f
caa4bd5
 
 
 
7b0b96f
 
caa4bd5
 
 
 
 
 
 
 
 
 
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
"""Resumable T4 v1 structural-dynamics campaign built on the validated pilot."""

from __future__ import annotations

import argparse
from copy import deepcopy
import json
import os
from pathlib import Path
import shutil
import tempfile
from time import perf_counter

import h5py
import numpy as np
from scipy.stats import qmc

try:
    from .t4_structural_dynamics import (
        ROOT,
        analytical_first_frequency,
        read_field_history,
        run_trajectory,
        solve_modes,
    )
except ImportError:  # Direct script execution.
    from t4_structural_dynamics import (
        ROOT,
        analytical_first_frequency,
        read_field_history,
        run_trajectory,
        solve_modes,
    )


CONFIG_PATH = ROOT / "configs" / "t4_structural_dynamics_v1.json"
DATA_DIR = ROOT / "data" / "t4_structural_dynamics_v1"
CASE_DIR = DATA_DIR / "cases"
REPRESENTATIVE_DIR = DATA_DIR / "representative_fields"
PARAMETERS = (
    "length_m",
    "height_m",
    "young_pa",
    "density_kg_m3",
    "damping_ratio",
    "traction_amplitude_pa",
)


def load_config(path: Path = CONFIG_PATH) -> dict:
    return json.loads(path.read_text(encoding="utf-8"))


def _map_ranges(unit: np.ndarray, ranges: dict) -> dict[str, float]:
    return {
        name: float(ranges[name][0] + unit[index] * (ranges[name][1] - ranges[name][0]))
        for index, name in enumerate(PARAMETERS)
    }


def configuration_design(config: dict | None = None) -> list[dict]:
    selected = load_config() if config is None else config
    count = int(selected["configuration_count"])
    if count != 128:
        raise ValueError("The frozen v1 Sobol design requires 128 configurations.")
    unit = qmc.Sobol(d=len(PARAMETERS), scramble=True, seed=int(selected["seed"])).random_base2(7)
    interior = selected["interior_parameter_ranges"]
    full = selected["full_parameter_ranges"]
    rows: list[dict] = []
    for index in range(count):
        parameters = _map_ranges(unit[index], interior)
        if index < 96:
            split, role = "train", "id"
        elif index < 112:
            split, role = "validation", "id"
        elif index < 120:
            split, role = "test", "id"
        elif index < 124:
            split, role = "test", "excitation_ood"
        else:
            split, role = "test", "parameter_ood"

        # The four parameter-OOD cases jointly cover all six physical inputs.
        if index == 124:
            parameters["length_m"] = full["length_m"][0]
            parameters["damping_ratio"] = full["damping_ratio"][1]
        elif index == 125:
            parameters["height_m"] = full["height_m"][0]
            parameters["young_pa"] = full["young_pa"][0]
        elif index == 126:
            parameters["length_m"] = full["length_m"][1]
            parameters["density_kg_m3"] = full["density_kg_m3"][1]
        elif index == 127:
            parameters["height_m"] = full["height_m"][1]
            parameters["traction_amplitude_pa"] = full["traction_amplitude_pa"][1]

        if role == "excitation_ood":
            sub_factor = 0.35 + 0.15 * unit[index, 0]
            near_factor = 1.20 + 0.20 * unit[index, 1]
            chirp_start = 0.25 + 0.10 * unit[index, 2]
            chirp_end = 2.40 + 0.20 * unit[index, 3]
        else:
            sub_factor = 0.65 + 0.20 * unit[index, 0]
            near_factor = 0.90 + 0.20 * unit[index, 1]
            chirp_start = 0.40 + 0.20 * unit[index, 2]
            chirp_end = 1.80 + 0.40 * unit[index, 3]
        rows.append(
            {
                "configuration_id": index,
                "case_id": f"config_{index:04d}",
                "split": split,
                "protocol_role": role,
                "parameters": parameters,
                "excitations": [
                    {"name": "half_sine_pulse", "kind": "half_sine_pulse"},
                    {"name": "sub_resonant_sine", "kind": "sine", "frequency_factor": sub_factor},
                    {"name": "near_resonant_sine", "kind": "sine", "frequency_factor": near_factor},
                    {
                        "name": "chirp",
                        "kind": "chirp",
                        "start_frequency_factor": chirp_start,
                        "end_frequency_factor": chirp_end,
                    },
                ],
            }
        )
    return rows


def case_config(global_config: dict, row: dict) -> dict:
    parameters = row["parameters"]
    length = float(parameters["length_m"])
    height = float(parameters["height_m"])
    return {
        "dataset": global_config["dataset"],
        "seed": global_config["seed"],
        "software": global_config["software"],
        "geometry": {
            **global_config["geometry"],
            "length_m": length,
            "height_m": height,
        },
        "material": {
            **global_config["fixed_material"],
            "young_pa": float(parameters["young_pa"]),
            "density_kg_m3": float(parameters["density_kg_m3"]),
        },
        "dynamics": {
            **global_config["dynamics"],
            "target_damping_ratio": float(parameters["damping_ratio"]),
            "traction_amplitude_pa": float(parameters["traction_amplitude_pa"]),
        },
        "sensors": [[fraction * length, 0.5 * height] for fraction in (0.2, 0.4, 0.6, 0.8, 1.0)],
        "excitations": deepcopy(row["excitations"]),
    }


def write_design(config: dict, rows: list[dict]) -> None:
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    payload = {
        "schema": "agentfem.physics-data.structural-dynamics-v1-design",
        "schema_version": "1.0.0",
        "config": config,
        "configurations": rows,
    }
    temporary = DATA_DIR / "design.json.tmp"
    temporary.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    os.replace(temporary, DATA_DIR / "design.json")
    temporary = DATA_DIR / "design.jsonl.tmp"
    temporary.write_text(
        "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows),
        encoding="utf-8",
    )
    os.replace(temporary, DATA_DIR / "design.jsonl")


def valid_case_file(path: Path) -> bool:
    if not path.is_file():
        return False
    try:
        with h5py.File(path, "r") as h5:
            return (
                h5.attrs.get("schema") == "agentfem.physics-data.structural-dynamics-v1-case"
                and h5.attrs.get("schema_version") == "1.1.0"
                and bool(h5.attrs.get("quality_passed", False))
                and len(h5["trajectories"]) == 4
            )
    except OSError:
        return False


def _write_case(
    path: Path,
    row: dict,
    config: dict,
    frequencies: np.ndarray,
    analytical: float,
    trajectories: list[dict],
    quality: dict,
) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(".h5.tmp")
    with h5py.File(temporary, "w") as h5:
        h5.attrs["schema"] = "agentfem.physics-data.structural-dynamics-v1-case"
        h5.attrs["schema_version"] = "1.1.0"
        h5.attrs["generator_fix"] = "component-preserving-kinematic-bcs"
        h5.attrs["configuration_id"] = int(row["configuration_id"])
        h5.attrs["case_id"] = row["case_id"]
        h5.attrs["split"] = row["split"]
        h5.attrs["protocol_role"] = row["protocol_role"]
        h5.attrs["quality_passed"] = bool(quality["passed"])
        h5.attrs["config_json"] = json.dumps(config, sort_keys=True)
        h5.attrs["quality_json"] = json.dumps(quality, sort_keys=True)
        modal = h5.create_group("modal")
        modal.create_dataset("frequencies_hz", data=frequencies)
        modal.attrs["analytical_first_frequency_hz"] = analytical
        modal.attrs["first_frequency_relative_error"] = quality[
            "first_frequency_relative_error"
        ]
        root = h5.create_group("trajectories")
        common_written = False
        for trajectory in trajectories:
            group = root.create_group(trajectory["name"])
            group.attrs["spec_json"] = json.dumps(trajectory["spec"], sort_keys=True)
            for key in (
                "dt_s",
                "steps",
                "rayleigh_mass_coefficient_per_s",
                "rayleigh_stiffness_coefficient_s",
                "wall_time_s",
                "dof_count",
                "kinematic_bc_scalar_dof_count",
                "energy_balance_reference_j_per_m",
            ):
                group.attrs[key] = trajectory[key]
            for key in (
                "time_s",
                "force_scale",
                "sensor_displacement_m",
                "strain_energy_j_per_m",
                "kinetic_energy_j_per_m",
                "external_power_w_per_m",
                "damping_power_w_per_m",
                "external_work_j_per_m",
                "damping_dissipation_j_per_m",
                "energy_balance_residual_j_per_m",
                "energy_balance_relative_residual",
            ):
                group.create_dataset(key, data=trajectory[key], compression="gzip", shuffle=True)
            field = read_field_history(trajectory["field_hdf5"])
            if not common_written:
                common = h5.create_group("common")
                common.create_dataset("reference_geometry_m", data=field["reference_geometry_m"])
                common.create_dataset("topology", data=field["topology"])
                common.create_dataset("sensor_coordinates_m", data=np.asarray(config["sensors"]))
                common_written = True
            field_group = group.create_group("fields")
            for key in ("time_s", "displacement_m", "velocity_m_per_s", "acceleration_m_per_s2"):
                field_group.create_dataset(key, data=field[key], compression="gzip", shuffle=True)
    os.replace(temporary, path)


def run_case(global_config: dict, row: dict, *, force: bool = False) -> dict:
    path = CASE_DIR / f"{row['case_id']}.h5"
    if not force and valid_case_file(path):
        return {"case_id": row["case_id"], "status": "reused", "path": str(path)}
    config = case_config(global_config, row)
    started = perf_counter()
    modal_result = solve_modes(config, modes=4)
    frequencies = np.asarray(modal_result.quantity("frequencies"), dtype=float)
    analytical = analytical_first_frequency(config)
    frequency_error = float(abs(frequencies[0] - analytical) / analytical)
    with tempfile.TemporaryDirectory(prefix=f"t4_{row['case_id']}_", dir=DATA_DIR) as scratch:
        scratch_path = Path(scratch)
        trajectories = [
            run_trajectory(
                config,
                spec,
                frequencies_hz=frequencies,
                output_dir=scratch_path,
                save_fields=True,
            )
            for spec in config["excitations"]
        ]
        energy = {
            item["name"]: float(np.max(np.abs(item["energy_balance_relative_residual"])))
            for item in trajectories
        }
        quality = {
            "first_frequency_relative_error": frequency_error,
            "maximum_energy_balance_relative_residual": max(energy.values()),
            "trajectory_energy_balance_relative_residual": energy,
            "all_finite": bool(
                all(
                    np.all(np.isfinite(item["sensor_displacement_m"]))
                    and np.all(np.isfinite(item["energy_balance_relative_residual"]))
                    for item in trajectories
                )
            ),
        }
        quality["gates"] = {
            "analytical_frequency": frequency_error
            <= float(global_config["quality"]["maximum_first_frequency_analytical_relative_error"]),
            "energy_balance": quality["maximum_energy_balance_relative_residual"]
            <= float(global_config["quality"]["maximum_energy_balance_relative_residual"]),
            "finite": quality["all_finite"],
        }
        quality["passed"] = bool(all(quality["gates"].values()))
        if not quality["passed"]:
            raise RuntimeError(f"Quality gate failed for {row['case_id']}: {quality}")
        _write_case(path, row, config, frequencies, analytical, trajectories, quality)
        if int(row["configuration_id"]) in set(global_config["storage"]["native_field_representatives"]):
            destination = REPRESENTATIVE_DIR / row["case_id"]
            destination.mkdir(parents=True, exist_ok=True)
            for item in trajectories:
                shutil.copy2(item["field_hdf5"], destination / Path(item["field_hdf5"]).name)
                shutil.copy2(item["field_xdmf"], destination / Path(item["field_xdmf"]).name)
    return {
        "case_id": row["case_id"],
        "status": "generated",
        "path": str(path),
        "wall_time_s": perf_counter() - started,
        "first_frequency_hz": float(frequencies[0]),
        "first_frequency_relative_error": frequency_error,
        "maximum_energy_balance_relative_residual": quality[
            "maximum_energy_balance_relative_residual"
        ],
        "bytes": path.stat().st_size,
    }


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", type=Path, default=CONFIG_PATH)
    parser.add_argument("--start", type=int, default=0)
    parser.add_argument("--stop", type=int)
    parser.add_argument("--design-only", action="store_true")
    parser.add_argument("--skip-design-write", action="store_true")
    parser.add_argument("--force", action="store_true")
    args = parser.parse_args()
    config = load_config(args.config)
    rows = configuration_design(config)
    if not args.skip_design_write:
        write_design(config, rows)
    if args.design_only:
        print(json.dumps({"status": "design_written", "configuration_count": len(rows)}, indent=2))
        return
    stop = len(rows) if args.stop is None else min(args.stop, len(rows))
    for row in rows[max(0, args.start):stop]:
        print(json.dumps(run_case(config, row, force=args.force), sort_keys=True), flush=True)


if __name__ == "__main__":
    main()