AgentFEM-Controlled-Transient-Heat / code /t3_controlled_transient_heat.py
HaomingLuo's picture
Publish AgentFEM T3 controlled transient heat v1
5c6f861 verified
Raw History Blame Contribute Delete
26.7 kB
"""T3 controlled transient heat dataset built with the public AgentFEM API.
Each scenario contains three counterfactual branches. They share material,
geometry, heat sources and the complete loading prefix, then maintain, throttle
or shut down the sources. Splits are assigned by scenario, never by branch.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
import time
import numpy as np
from scipy.stats import qmc
import ufl
from dolfinx import fem
from mpi4py import MPI
from agentfem import amplitudes, campaigns, constitutive, fields, mesh, models, results, studies
from agentfem.solvers import LinearSolverOptions
ROOT = Path(__file__).resolve().parents[1]
CONFIG_PATH = ROOT / "configs" / "t3_controlled_transient_heat_pilot.json"
DATA_DIR = ROOT / "data" / "t3_controlled_transient_heat_pilot"
SAMPLE_DIR = DATA_DIR / "samples"
ARTIFACT_DIR = ROOT / "artifacts" / "t3_controlled_transient_heat_pilot"
SOLVER = LinearSolverOptions(ksp_type="preonly", pc_type="lu")
def load_config(path: Path = CONFIG_PATH) -> dict[str, object]:
return json.loads(path.read_text(encoding="utf-8"))
def _scale(value: float, bounds: list[float]) -> float:
return float(bounds[0] + value * (bounds[1] - bounds[0]))
def scenario_design(config: dict[str, object] | None = None) -> tuple[dict[str, object], ...]:
"""Return the frozen Sobol design for independent physical scenarios."""
cfg = load_config() if config is None else config
count = int(cfg["scenario_count"])
exponent = int(np.log2(count))
if 2**exponent != count:
raise ValueError("scenario_count must be a power of two for the Sobol design.")
unit = qmc.Sobol(16, scramble=True, seed=int(cfg["seed"])).random_base2(exponent)
material = cfg["material_ranges"]
source_ranges = cfg["source_ranges"]
domain = cfg["domain"]
rows: list[dict[str, object]] = []
for scenario_index, values in enumerate(unit):
sources = []
offset = 4
for source_index, x_window in enumerate(source_ranges["relative_x_windows"]):
cursor = offset + 4 * source_index
sources.append(
{
"x_m": _scale(values[cursor], x_window) * float(domain["length_m"]),
"y_m": _scale(values[cursor + 1], source_ranges["relative_y"])
* float(domain["height_m"]),
"sigma_m": _scale(values[cursor + 2], source_ranges["sigma_m"]),
"peak_power_density_w_m3": _scale(
values[cursor + 3], source_ranges["peak_power_density_w_m3"]
),
}
)
rows.append(
{
"scenario_index": scenario_index,
"conductivity_w_mk": _scale(
values[0], material["conductivity_w_mk"]
),
"density_kg_m3": _scale(values[1], material["density_kg_m3"]),
"specific_heat_j_kgk": _scale(
values[2], material["specific_heat_j_kgk"]
),
"convection_coefficient_w_m2k": _scale(
values[3], cfg["convection_coefficient_range_w_m2k"]
),
"sources": sources,
}
)
return tuple(rows)
def scenario_id(parameters: dict[str, object]) -> str:
payload = {key: value for key, value in parameters.items() if key != "scenario_index"}
return campaigns.case_id("t3_controlled_transient_heat_scenario", payload)
def scenario_splits(config: dict[str, object] | None = None) -> dict[int, str]:
"""Assign all branches from one scenario to one deterministic split."""
cfg = load_config() if config is None else config
count = int(cfg["scenario_count"])
order = np.random.default_rng(int(cfg["seed"]) + 31).permutation(count)
if count < 4:
return {int(index): "train" for index in order}
test_count = max(1, count // 8)
validation_count = max(1, count // 8)
result = {int(index): "train" for index in order}
for index in order[:test_count]:
result[int(index)] = "test"
for index in order[test_count : test_count + validation_count]:
result[int(index)] = "validation"
return result
def branch_schedule(
branch: str,
*,
config: dict[str, object] | None = None,
) -> tuple[np.ndarray, np.ndarray]:
"""Return a dimensionless source multiplier with a shared causal prefix."""
cfg = load_config() if config is None else config
if branch not in cfg["branches"]:
raise ValueError(f"Unknown branch {branch!r}.")
timing = cfg["time"]
end_time = float(timing["dt_s"]) * int(timing["steps"])
times = np.asarray(
[
0.0,
float(timing["ramp_end_s"]),
float(timing["branch_time_s"]),
float(timing["transition_end_s"]),
end_time,
],
dtype=float,
)
factor = float(cfg["branch_power_factors"][branch])
values = np.asarray([0.0, 1.0, 1.0, factor, factor], dtype=float)
return times, values
def _topology(domain) -> np.ndarray:
tdim = domain.topology.dim
domain.topology.create_connectivity(tdim, 0)
connectivity = domain.topology.connectivity(tdim, 0)
offsets = np.asarray(connectivity.offsets)
widths = np.diff(offsets)
if not np.all(widths == widths[0]):
raise ValueError("T3 packaging requires one fixed cell topology.")
return np.asarray(connectivity.array, dtype=np.int64).reshape(-1, int(widths[0]))
def _history_values(simulation, name: str) -> tuple[np.ndarray, np.ndarray]:
history = simulation.histories[name]
return np.asarray(history.abscissa, dtype=float), np.asarray(history.values, dtype=float)
def solve_branch(
parameters: dict[str, object],
branch: str,
*,
config: dict[str, object] | None = None,
cells: tuple[int, int] | None = None,
dt_s: float | None = None,
steps: int | None = None,
output: Path | None = None,
) -> tuple[dict[str, object], dict[str, np.ndarray]]:
"""Solve one complete branch and return metadata plus learning arrays."""
cfg = load_config() if config is None else config
domain_cfg = cfg["domain"]
timing = cfg["time"]
selected_cells = cells or (int(domain_cfg["cells_x"]), int(domain_cfg["cells_y"]))
selected_dt = float(timing["dt_s"] if dt_s is None else dt_s)
selected_steps = int(timing["steps"] if steps is None else steps)
final_time = selected_dt * selected_steps
if not np.isclose(final_time, float(timing["dt_s"]) * int(timing["steps"])):
raise ValueError("Refined time grids must preserve the configured final time.")
started = time.perf_counter()
domain = mesh.rectangle(
(0.0, 0.0),
(float(domain_cfg["length_m"]), float(domain_cfg["height_m"])),
selected_cells,
comm=MPI.COMM_SELF,
cell_type=str(domain_cfg["cell_type"]),
)
model = models.create(
study=studies.transient_heat_transfer(dimension=2),
mesh=domain,
name="t3_controlled_transient_heat",
)
initial_temperature = float(cfg["initial_temperature_k"])
temperature = model.field(fields.temperature(domain, degree=1, value=initial_temperature))
model.material(
constitutive.thermoelastic(
name="synthetic_metallic_thermal_solid",
young=70.0e9,
poisson=0.3,
density=float(parameters["density_kg_m3"]),
thermal_expansion=23.0e-6,
conductivity=float(parameters["conductivity_w_mk"]),
specific_heat=float(parameters["specific_heat_j_kgk"]),
reference_temperature=initial_temperature,
)
)
exterior = mesh.boundary(
domain,
lambda x: np.isclose(x[0], 0.0)
| np.isclose(x[0], float(domain_cfg["length_m"]))
| np.isclose(x[1], 0.0)
| np.isclose(x[1], float(domain_cfg["height_m"])),
name="exterior",
tag=1,
)
model.convection(
on=exterior,
coefficient=float(parameters["convection_coefficient_w_m2k"]),
ambient_temperature=initial_temperature,
)
schedule_times, schedule_values = branch_schedule(branch, config=cfg)
coordinate = ufl.SpatialCoordinate(domain)
source_controls = []
for source_index, source in enumerate(parameters["sources"]):
sigma = float(source["sigma_m"])
shape = ufl.exp(
-(
(coordinate[0] - float(source["x_m"])) ** 2
+ (coordinate[1] - float(source["y_m"])) ** 2
)
/ (2.0 * sigma**2)
)
history_values = schedule_values * float(source["peak_power_density_w_m3"])
source_controls.append(history_values)
model.heat_source(
shape,
amplitude=amplitudes.tabular(
schedule_times,
history_values,
name=f"source_{source_index + 1}_{branch}",
),
name=f"gaussian_source_{source_index + 1}",
)
model.check()
if output is not None:
output.parent.mkdir(parents=True, exist_ok=True)
step = model.step(
target=temperature,
dt=selected_dt,
steps=selected_steps,
save_every=max(1, selected_steps // 12),
print_every=max(1, selected_steps // 6),
progress=False,
solver_options=SOLVER,
output=output,
name=f"t3_{branch}",
)
field_history = step.capture_history(
name="temperature",
unit="K",
)
sensor_requests = tuple(
results.probe_history(
f"sensor_{index + 1}_temperature",
at=location,
unit="K",
)
for index, location in enumerate(cfg["fixed_sensor_locations_m"])
)
simulation = step.solve_result(history=sensor_requests)
if simulation.status != "completed":
raise RuntimeError(f"Transient solve ended with status {simulation.status!r}.")
times = np.asarray(field_history.times, dtype=float)
temperature_history = np.stack([field_history.sample(value) for value in times])
coordinates = np.asarray(temperature.value.function_space.tabulate_dof_coordinates())[:, :2]
controls = np.column_stack(
[np.interp(times, schedule_times, values) for values in source_controls]
)
sensor_values = np.column_stack(
[_history_values(simulation, request.name)[1] for request in sensor_requests]
)
ledger_names = (
"thermal_content",
"applied_heat_rate",
"outward_heat_rate",
"heat_balance_residual",
)
ledgers = {name: _history_values(simulation, name)[1] for name in ledger_names}
hottest = np.argmax(temperature_history, axis=1)
branch_time = float(timing["branch_time_s"])
prefix_count = int(np.count_nonzero(times <= branch_time + 1.0e-12))
residual_scale = np.maximum(
1.0,
selected_dt
* np.maximum(
np.abs(ledgers["applied_heat_rate"]),
np.abs(ledgers["outward_heat_rate"]),
),
)
metrics = {
"maximum_temperature_k": float(np.max(temperature_history)),
"maximum_temperature_rise_k": float(np.max(temperature_history) - initial_temperature),
"final_mean_temperature_k": float(np.mean(temperature_history[-1])),
"maximum_absolute_heat_balance_residual_j_per_m": float(
np.max(np.abs(ledgers["heat_balance_residual"]))
),
"maximum_relative_heat_balance_residual": float(
np.max(np.abs(ledgers["heat_balance_residual"]) / residual_scale)
),
"prefix_frame_count": prefix_count,
"wall_seconds": float(time.perf_counter() - started),
}
arrays = {
"time_s": times,
"temperature_dof_coordinates_m": coordinates,
"mesh_connectivity": _topology(domain),
"temperature_history_k": temperature_history,
"source_control_w_m3": controls,
"sensor_locations_m": np.asarray(cfg["fixed_sensor_locations_m"], dtype=float),
"sensor_temperature_k": sensor_values,
"hotspot_coordinates_m": coordinates[hottest],
**{name: values for name, values in ledgers.items()},
}
if not all(np.isfinite(value).all() for value in arrays.values()):
raise RuntimeError("Non-finite values found in T3 result arrays.")
record = {
"schema": cfg["schema"],
"schema_version": cfg["schema_version"],
"dataset_version": cfg["dataset_version"],
"scenario_id": scenario_id(parameters),
"scenario_index": int(parameters["scenario_index"]),
"branch": branch,
"parameters": parameters,
"discretization": {
"cells": list(selected_cells),
"dt_s": selected_dt,
"steps": selected_steps,
"time_integrator": "implicit_euler",
"temperature_element": "CG1",
},
"metrics": metrics,
"limitations": [
"two-dimensional solid conduction with unit out-of-plane thickness",
"constant isotropic thermal properties within each trajectory",
"synthetic metallic parameter range; not a named alloy calibration",
"no radiation, phase change, fluid flow, or thermo-mechanical feedback",
],
}
return record, arrays
def sample_paths(index: int, parameters: dict[str, object], branch: str) -> tuple[Path, Path, Path]:
folder = SAMPLE_DIR / f"{index:05d}_{scenario_id(parameters)}_{branch}"
return folder, folder / "sample.json", folder / "fields.npz"
def _atomic_npz(path: Path, arrays: dict[str, np.ndarray]) -> None:
temporary = path.with_suffix(".npz.tmp")
with temporary.open("wb") as stream:
np.savez_compressed(stream, **arrays)
os.replace(temporary, path)
def write_design() -> Path:
cfg = load_config()
scenarios = scenario_design(cfg)
splits = scenario_splits(cfg)
DATA_DIR.mkdir(parents=True, exist_ok=True)
path = DATA_DIR / "design.jsonl"
temporary = path.with_suffix(".jsonl.tmp")
with temporary.open("w", encoding="utf-8") as stream:
sample_index = 0
for parameters in scenarios:
for branch in cfg["branches"]:
stream.write(
json.dumps(
{
"id": f"{sample_index:05d}",
"scenario_id": scenario_id(parameters),
"scenario_index": parameters["scenario_index"],
"branch": branch,
"split": splits[int(parameters["scenario_index"])],
"parameters": parameters,
},
sort_keys=True,
)
+ "\n"
)
sample_index += 1
os.replace(temporary, path)
return path
def generate(*, force: bool = False) -> dict[str, object]:
cfg = load_config()
scenarios = scenario_design(cfg)
splits = scenario_splits(cfg)
write_design()
completed = reused = failed = 0
records = []
started = time.perf_counter()
sample_index = 0
for parameters in scenarios:
for branch in cfg["branches"]:
folder, record_path, field_path = sample_paths(sample_index, parameters, branch)
if not force and record_path.exists() and field_path.exists():
record = json.loads(record_path.read_text(encoding="utf-8"))
reused += 1
else:
folder.mkdir(parents=True, exist_ok=True)
output = folder / "fields.xdmf" if sample_index in {0, 1, 2} else None
try:
record, arrays = solve_branch(parameters, branch, config=cfg, output=output)
record.update({"id": f"{sample_index:05d}", "split": splits[int(parameters["scenario_index"])]})
_atomic_npz(field_path, arrays)
temporary = record_path.with_suffix(".json.tmp")
temporary.write_text(json.dumps(record, indent=2, sort_keys=True) + "\n", encoding="utf-8")
os.replace(temporary, record_path)
completed += 1
except Exception as exc:
failed += 1
print(json.dumps({"id": sample_index, "status": "failed", "error": repr(exc)}), flush=True)
sample_index += 1
continue
records.append(record)
print(
json.dumps(
{
"id": sample_index,
"scenario": parameters["scenario_index"],
"branch": branch,
"split": splits[int(parameters["scenario_index"])],
"max_temperature_k": record["metrics"]["maximum_temperature_k"],
"heat_balance_relative": record["metrics"]["maximum_relative_heat_balance_residual"],
}
),
flush=True,
)
sample_index += 1
summary = {
"scenario_count": len(scenarios),
"trajectory_count": len(scenarios) * len(cfg["branches"]),
"completed": completed,
"reused": reused,
"failed": failed,
"wall_seconds": float(time.perf_counter() - started),
}
ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)
(ARTIFACT_DIR / "generation_summary.json").write_text(
json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
if failed:
raise RuntimeError(f"{failed} T3 trajectories failed.")
return summary
def audit_prefixes() -> dict[str, object]:
"""Verify counterfactual branches are bitwise identical before intervention."""
cfg = load_config()
scenarios = scenario_design(cfg)
maximum_temperature_difference = 0.0
maximum_control_difference = 0.0
groups = []
sample_index = 0
for parameters in scenarios:
branch_arrays = []
for branch in cfg["branches"]:
_, _, path = sample_paths(sample_index, parameters, branch)
with np.load(path, allow_pickle=False) as data:
branch_arrays.append({name: np.asarray(data[name]) for name in data.files})
sample_index += 1
time_values = branch_arrays[0]["time_s"]
prefix = time_values <= float(cfg["time"]["branch_time_s"]) + 1.0e-12
reference = branch_arrays[0]
group_temperature = max(
float(np.max(np.abs(item["temperature_history_k"][prefix] - reference["temperature_history_k"][prefix])))
for item in branch_arrays[1:]
)
group_control = max(
float(np.max(np.abs(item["source_control_w_m3"][prefix] - reference["source_control_w_m3"][prefix])))
for item in branch_arrays[1:]
)
maximum_temperature_difference = max(maximum_temperature_difference, group_temperature)
maximum_control_difference = max(maximum_control_difference, group_control)
groups.append(
{
"scenario_id": scenario_id(parameters),
"prefix_max_temperature_difference_k": group_temperature,
"prefix_max_control_difference_w_m3": group_control,
}
)
report = {
"status": "passed" if maximum_temperature_difference <= 1.0e-12 and maximum_control_difference <= 1.0e-12 else "failed",
"maximum_prefix_temperature_difference_k": maximum_temperature_difference,
"maximum_prefix_control_difference_w_m3": maximum_control_difference,
"groups": groups,
}
ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)
(ARTIFACT_DIR / "prefix_audit.json").write_text(
json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
if report["status"] != "passed":
raise RuntimeError("Counterfactual prefix audit failed.")
return report
def _decay_benchmark(*, cells_per_axis: int, steps: int) -> dict[str, float]:
"""Run a manufactured transient heat problem with a closed-form solution."""
final_time = 0.02
domain = mesh.rectangle(
(0.0, 0.0),
(1.0, 1.0),
(cells_per_axis, cells_per_axis),
comm=MPI.COMM_SELF,
cell_type="quadrilateral",
)
model = models.create(
study=studies.transient_heat_transfer(dimension=2),
mesh=domain,
name="t3_decay_verification",
)
temperature = model.field(fields.temperature(domain, degree=1, value=300.0))
model.material(
constitutive.thermoelastic(
young=1.0,
poisson=0.3,
density=1.0,
thermal_expansion=0.0,
conductivity=1.0,
specific_heat=1.0,
reference_temperature=300.0,
)
)
temperature.value.interpolate(
lambda x: 300.0 + np.sin(np.pi * x[0]) * np.sin(np.pi * x[1])
)
exterior = mesh.boundary(
domain,
lambda x: np.isclose(x[0], 0.0)
| np.isclose(x[0], 1.0)
| np.isclose(x[1], 0.0)
| np.isclose(x[1], 1.0),
name="exterior",
tag=1,
)
model.fix(temperature, on=exterior, value=300.0)
step = model.step(
target=temperature,
dt=final_time / steps,
steps=steps,
progress=False,
solver_options=SOLVER,
)
simulation = step.solve_result()
x = ufl.SpatialCoordinate(domain)
exact = (
np.exp(-2.0 * np.pi**2 * final_time)
* ufl.sin(np.pi * x[0])
* ufl.sin(np.pi * x[1])
)
measure = ufl.Measure("dx", domain=domain, metadata={"quadrature_degree": 8})
error = fem.assemble_scalar(
fem.form((temperature.value - 300.0 - exact) ** 2 * measure)
)
norm = fem.assemble_scalar(fem.form(exact**2 * measure))
return {
"cells_per_axis": cells_per_axis,
"steps": steps,
"relative_l2_error": float(np.sqrt(error / norm)),
"status": simulation.status,
}
def validate_numerics() -> dict[str, object]:
"""Run analytical, time-step and mesh-refinement gates for the pilot."""
cfg = load_config()
parameters = scenario_design(cfg)[0]
decay_coarse = _decay_benchmark(cells_per_axis=12, steps=40)
decay_fine = _decay_benchmark(cells_per_axis=24, steps=80)
_, base = solve_branch(parameters, "maintain", config=cfg)
_, time_fine = solve_branch(
parameters,
"maintain",
config=cfg,
dt_s=float(cfg["time"]["dt_s"]) / 2.0,
steps=int(cfg["time"]["steps"]) * 2,
)
base_cells = (int(cfg["domain"]["cells_x"]), int(cfg["domain"]["cells_y"]))
_, mesh_fine = solve_branch(
parameters,
"maintain",
config=cfg,
cells=(2 * base_cells[0], 2 * base_cells[1]),
)
base_sensors = base["sensor_temperature_k"]
time_sensor_change = float(
np.linalg.norm(base_sensors[-1] - time_fine["sensor_temperature_k"][-1])
/ np.linalg.norm(time_fine["sensor_temperature_k"][-1] - float(cfg["initial_temperature_k"]))
)
mesh_sensor_change = float(
np.linalg.norm(base_sensors[-1] - mesh_fine["sensor_temperature_k"][-1])
/ np.linalg.norm(mesh_fine["sensor_temperature_k"][-1] - float(cfg["initial_temperature_k"]))
)
maximum_heat_balance = max(
float(
np.max(np.abs(item["heat_balance_residual"]))
/ max(1.0, np.max(np.abs(item["thermal_content"] - item["thermal_content"][0])))
)
for item in (base, time_fine, mesh_fine)
)
checks = {
"analytical_error_decreases": decay_fine["relative_l2_error"] < decay_coarse["relative_l2_error"],
"analytical_fine_relative_l2_below_0p5pct": decay_fine["relative_l2_error"] < 0.005,
"time_refinement_sensor_change_below_2pct": time_sensor_change < 0.02,
"mesh_refinement_sensor_change_below_2pct": mesh_sensor_change < 0.02,
"heat_balance_relative_to_stored_energy_below_1e_8": maximum_heat_balance < 1.0e-8,
}
report = {
"status": "passed" if all(checks.values()) else "failed",
"checks": checks,
"analytical_decay": {"coarse": decay_coarse, "fine": decay_fine},
"time_refinement_final_sensor_relative_change": time_sensor_change,
"mesh_refinement_final_sensor_relative_change": mesh_sensor_change,
"maximum_heat_balance_residual_relative_to_stored_energy_change": maximum_heat_balance,
}
ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)
(ARTIFACT_DIR / "numerical_validation.json").write_text(
json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
if report["status"] != "passed":
raise RuntimeError("T3 numerical validation did not pass all declared gates.")
return report
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 smoke() -> dict[str, object]:
"""Run one complete trajectory before launching the pilot campaign."""
cfg = load_config()
parameters = scenario_design(cfg)[0]
ARTIFACT_DIR.mkdir(parents=True, exist_ok=True)
record, arrays = solve_branch(
parameters,
"maintain",
config=cfg,
output=ARTIFACT_DIR / "smoke_fields.xdmf",
)
_atomic_npz(ARTIFACT_DIR / "smoke_fields.npz", arrays)
path = ARTIFACT_DIR / "smoke_report.json"
path.write_text(json.dumps(record, indent=2, sort_keys=True) + "\n", encoding="utf-8")
return record
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"command",
choices=("design", "smoke", "generate", "audit", "validate", "all"),
)
parser.add_argument("--force", action="store_true")
args = parser.parse_args()
if args.command in {"design", "all"}:
print(write_design())
if args.command == "smoke":
print(json.dumps(smoke(), indent=2))
if args.command in {"generate", "all"}:
print(json.dumps(generate(force=args.force), indent=2))
if args.command in {"audit", "all"}:
print(json.dumps(audit_prefixes(), indent=2))
if args.command in {"validate", "all"}:
print(json.dumps(validate_numerics(), indent=2))
if __name__ == "__main__":
main()