File size: 4,705 Bytes
e2dc0ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Plot heat inputs and recorded FEM temperatures. SPDX-License-Identifier: Apache-2.0

pip install numpy h5py matplotlib huggingface_hub
python plot_heat.py
python plot_heat.py --data test.h5 --sample 00016 --output heat.png

This reads an existing FEM result, not a new simulation or neural prediction.
Data: CC BY 4.0, Haoming Luo / AgentFEM-MultiSource-Heat-2D (2026).
"""

import argparse
import json
from pathlib import Path

import h5py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
import numpy as np

REPO = "HaomingLuo/AgentFEM-MultiSource-Heat-2D"
REVISION = "7d19e509b4fdc33c767cbc469c9a669d817b11e4"


def read_sample(path, sample_id=None):
    with h5py.File(path, "r") as handle:
        key = sample_id or sorted(handle)[0]
        if key not in handle:
            raise ValueError(f"Sample {key!r} not found. Available: {', '.join(sorted(handle))}")
        group = handle[key]
        parameters = json.loads(group.attrs["parameters_json"])
        xy = group["coordinates"][:, :2]
        triangles = group["connectivity"][:]
        source = group["inputs/source_w_m3"][:]
        temperature = group["point/Temperature"][:]
        boundary = group["inputs/cooled_boundary"][:].astype(bool)
    if triangles.shape[1] != 3:
        raise ValueError("This recipe expects linear triangular elements.")
    if not all(np.isfinite(a).all() for a in (xy, source, temperature)):
        raise ValueError("Non-finite field values.")
    if not boundary.any():
        raise ValueError("Missing cooled boundary nodes.")
    if not np.allclose(temperature[boundary], 300.0, atol=1e-7, rtol=0):
        raise ValueError("Boundary temperature differs from the documented 300 K.")
    return key, parameters, xy, triangles, source, temperature


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data", type=Path, help="Existing split HDF5 file; otherwise download pinned test split")
    parser.add_argument("--sample", help="Sample ID, for example 00016")
    parser.add_argument("--output", type=Path, default=Path("heat-input-output.png"))
    args = parser.parse_args()
    path = args.data
    if path is None:
        from huggingface_hub import hf_hub_download
        path = hf_hub_download(REPO, "test.h5", repo_type="dataset", revision=REVISION)
    key, p, xy, triangles, source, temperature = read_sample(path, args.sample)
    peak = int(np.argmax(temperature))
    report = {
        "sample": key,
        "conductivity_W_m_K": p["conductivity_w_m_k"],
        "peak_temperature_K": float(temperature[peak]),
        "peak_rise_K": float(temperature[peak] - 300),
        "peak_node_xy_mm": (xy[peak] * 1000).tolist(),
        "source": "Recorded finite-element result; not a new solve",
    }
    print(json.dumps(report, indent=2))
    mesh = mtri.Triangulation(xy[:, 0] * 1000, xy[:, 1] * 1000, triangles)
    plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 10,
                         "axes.spines.top": False, "axes.spines.right": False})
    fig, axes = plt.subplots(1, 2, figsize=(11, 4.4))
    fig.subplots_adjust(left=.065, right=.95, bottom=.21, top=.76, wspace=.34)
    fig.suptitle("Two heat sources. One temperature field.", x=.065, ha="left", y=.96,
                 fontsize=19, fontweight="bold", color="#173a42")
    fig.text(.065, .855, f"AgentFEM  /  sample {key}  /  k = {p['conductivity_w_m_k']:.2f} W/(m K)"
             "  /  all edges at 300 K", color="#536a70")
    for ax, values, title, label, cmap in zip(
        axes, (source / 1e6, temperature - 300),
        ("Input: distributed heat generation", "Output: temperature rise"),
        ("q / MW m$^{-3}$", "T - 300 K / K"), ("magma", "inferno")):
        artist = ax.tripcolor(mesh, values, shading="gouraud", cmap=cmap, vmin=0)
        fig.colorbar(artist, ax=ax, fraction=.045, pad=.035, label=label)
        ax.set(title=title, xlabel="x / mm", ylabel="y / mm", aspect="equal")
        ax.set_xlim(0, p["length_m"] * 1000)
        ax.set_ylim(0, p["height_m"] * 1000)
    axes[1].plot(*(xy[peak] * 1000), "o", ms=5, mfc="none", mec="#66e4dc", mew=1.4)
    fig.text(.065, .08, f"Peak nodal rise: {temperature[peak] - 300:.3f} K. "
             "The hottest point need not coincide with the strongest source.", color="#173a42")
    fig.text(.065, .025, "Recorded FEM fields • source shown by nodal interpolation • data CC BY 4.0 • Haoming Luo / AgentFEM",
             fontsize=8, color="#536a70")
    args.output.parent.mkdir(parents=True, exist_ok=True)
    fig.savefig(args.output, dpi=180, facecolor="white")
    plt.close(fig)


if __name__ == "__main__":
    main()