sph_dataset / parameter_heatmaps.py
ioandanielc's picture
Add files using upload-large-folder tool
aa07075 verified
Raw
History Blame Contribute Delete
4.43 kB
#!/usr/bin/env python3
"""
Plot 6 pairwise 2D heatmaps (1v1) for the 4 process parameters across all
simulations, and save the parameter list as JSON for later merging.
Outputs (written next to this script):
parameter_list.json — list of dicts, one per simulation
parameter_heatmaps.png — 2×3 grid of 2D histograms
"""
from __future__ import annotations
import json
from itertools import combinations
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
# ── config ────────────────────────────────────────────────────────────────────
HERE = Path(__file__).parent
DATA_DIR = HERE / "final_data_processed"
OUT_JSON = HERE / "parameter_list.json"
OUT_PNG = HERE / "parameter_heatmaps.png"
BINS = 15
PARAMS = [
("laser_power", "Laser Power (W)"),
("scan_speed_x", "Scan Speed (m/s)"),
("laser_spot_size", "Spot Size (m)"),
("substrate_temperature","Substrate Temp (K)"),
]
PARAM_KEYS = [k for k, _ in PARAMS]
PARAM_LABELS = {k: lbl for k, lbl in PARAMS}
# ── load ──────────────────────────────────────────────────────────────────────
records = []
for sim_dir in sorted(DATA_DIR.iterdir()):
pjson = sim_dir / "parameters.json"
if not pjson.exists():
continue
raw = json.loads(pjson.read_text())
try:
rec = {
"sim": sim_dir.name,
"laser_power": float(raw["laser_power"]["value"]),
"scan_speed_x": float(raw["scan_speed_x"]["value"]),
"laser_spot_size": float(raw["laser_spot_size"]["value"]),
"substrate_temperature": float(raw["substrate_temperature"]["value"]),
}
except (KeyError, ValueError) as e:
print(f" SKIP {sim_dir.name}: {e}")
continue
records.append(rec)
print(f"Loaded {len(records)} simulations")
# ── save JSON list ────────────────────────────────────────────────────────────
OUT_JSON.write_text(json.dumps(records, indent=2))
print(f"Saved parameter list → {OUT_JSON}")
# ── parameter domains ─────────────────────────────────────────────────────────
values_raw = {k: np.array([r[k] for r in records]) for k in PARAM_KEYS}
print("\nParameter domains:")
print(f" {'Parameter':<25} {'Min':>14} {'Max':>14}")
print(" " + "-" * 55)
for k, lbl in PARAMS:
vmin, vmax = values_raw[k].min(), values_raw[k].max()
print(f" {lbl:<25} {vmin:>14.6g} {vmax:>14.6g}")
# Normalize each parameter to [0, 1] over its observed domain
def normalize(v: np.ndarray) -> np.ndarray:
lo, hi = v.min(), v.max()
return (v - lo) / (hi - lo) if hi > lo else np.zeros_like(v)
values = {k: normalize(values_raw[k]) for k in PARAM_KEYS}
# ── heatmaps ──────────────────────────────────────────────────────────────────
pairs = list(combinations(PARAM_KEYS, 2)) # 6 pairs
assert len(pairs) == 6
fig, axes = plt.subplots(2, 3, figsize=(14, 9))
axes = axes.flatten()
for ax, (kx, ky) in zip(axes, pairs):
x, y = values[kx], values[ky]
h, xe, ye = np.histogram2d(x, y, bins=BINS, range=[[0, 1], [0, 1]])
im = ax.imshow(
h.T, origin="lower", aspect="auto", cmap="YlOrRd",
extent=[0, 1, 0, 1],
interpolation="nearest",
vmin=0,
)
fig.colorbar(im, ax=ax, shrink=0.85, label="# simulations")
ax.set_xlabel(f"{PARAM_LABELS[kx]} [norm]", fontsize=8)
ax.set_ylabel(f"{PARAM_LABELS[ky]} [norm]", fontsize=8)
ax.tick_params(labelsize=7)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.suptitle(
f"Pairwise parameter coverage — normalized domains (N={len(records)} simulations)",
fontsize=11, y=1.01,
)
plt.tight_layout()
plt.savefig(OUT_PNG, dpi=150, bbox_inches="tight")
print(f"\nSaved heatmaps → {OUT_PNG}")
plt.show()