Newer
Older
SmTIAS-LightSim / scripts / v4_led_mount_search.py
"""SmTIASv4 の筐体(Fusion から書き出したもの)の中で,削った LED 基板を付ける高さと位置を探す.

TEST_21 結果 9・12 の方法(光は線形なので,LED 3 個 1 組を 1 か所だけ点けた基底画像の和で
組み合わせを近似する)を,シミュの箱 H_y90 ではなく Fusion の SmTIASv4 の筐体
(`configs/scene_smtias_v4.yaml` の `box_housing`.鼻の穴を閉じて鼻当てを付けた版)で行う.

基板はもう削ってあるので(SPEC_05.2026-11-09),LED の並びは変えない:

- 横の基板(右と左.同じ基板): 3 個 1 組 2 本が Y 方向に中心間隔 20 mm.横の壁から 6 mm(X ±74)
- 下の基板(1 枚): 3 個 1 組 2 本が X ±21.下の壁から 6 mm(Y −84)

変えられるのは,横の基板の高さ Z と上下の位置(下の組の Y),下の基板の高さ Z と明るさ
(定電流 IC を 1 個にすると 30 mA で半分).座標は Fusion のまま(顔の面が Z 0,
天井の内面が Z −3).
基板どうしの遮りは無視する近似なので,よい組み合わせは最後に Fusion で基板を動かして確かめる.

実行方法(基底画像は研究室サーバで):
    uv run python scripts/v4_led_mount_search.py --prepare-only
    uv run python scripts/v4_led_mount_search.py --part 0/2      # GPU ごとに分けて
    uv run python scripts/v4_led_mount_search.py --search --workers 32   # 指標が重いのでサーバで
"""

from __future__ import annotations

import argparse
import csv
import sys
import time
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path

import numpy as np
import yaml

sys.path.insert(0, str(Path(__file__).resolve().parent))
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))

from led_site_basis import (  # noqa: E402
    Site,
    _inside_cavity,
    build_modules_yaml,
    camera_block,
    mirror_site,
    module_fits,
)
from sweep_candidate_layouts import TMP_DIR  # noqa: E402

from sm_tias_lightsim.scene.paths import relative_mesh_path  # noqa: E402

ROOT = Path(__file__).resolve().parents[1]
SCENE_V4 = ROOT / "configs" / "scene_smtias_v4.yaml"
OUTPUT = ROOT / "output" / "led_mounts_v4"
A0_LUMINANCE = ROOT / "output" / "candidate_layouts" / "A0" / "s0" / "luminance.npy"
# Fusion の天井の内面(Z −3)とシミュの箱(Z 0)の差.収まりの判定はシミュの箱で行う
CEILING_SHIFT = -3.0
SIDE_X = 74.0
BOTTOM_Y = -84.0
BOTTOM_X = 21.0
SIDE_PITCH = 20.0  # 横の基板の 2 組の中心間隔
SIDE_U = (-18.3, 44.0)  # 横の基板の外形(下の組の中心を Y 10 としたときの Y.上の角を落とす)
SIDE_CHAMFER = (38.0, 3.5)
Z_LEVELS = (-18.0, -23.0, -28.0, -33.0, -38.0, -43.0, -48.0, -55.0, -65.0)
SIDE_Y = tuple(float(y) for y in range(-30, 51, 5))  # 横の基板の下の組の中心
BOTTOM_GAINS = (1.0, 0.5)
MIRROR_PROBE = "v4_R_y10_z-38"


def side_site(y: float, z: float) -> Site:
    return Site(f"v4_R_y{y:g}_z{z:g}", "right", (SIDE_X, y, z), (0.0, 1.0), (-1.0, 0.0))


def bottom_site(z: float) -> Site:
    return Site(f"v4_B_x{BOTTOM_X:g}_z{z:g}", "bottom", (BOTTOM_X, BOTTOM_Y, z), (1.0, 0.0),
                (0.0, 1.0))


def _sim(site: Site) -> Site:
    """収まりとカメラの視野の判定用に,シミュの箱の座標へ写す."""
    x, y, z = site.led
    return Site(site.name, site.wall, (x, y, z - CEILING_SHIFT), site.along, site.inward)


def side_board_fits(y_low: float, z: float) -> bool:
    """横の基板全体(上の角を落とした外形)がシミュの箱の内側に収まるか."""
    dy = y_low - 10.0
    u0, u1 = SIDE_U
    uc, vc = SIDE_CHAMFER
    pts = [(SIDE_X + v, u0 + dy) for v in (-5.0, 5.0)]
    pts += [(SIDE_X + v, uc + dy) for v in (-5.0, 5.0)]
    pts += [(SIDE_X + v, u1 + dy) for v in (-(5.0 - vc), 5.0 - vc)]
    zs = z - CEILING_SHIFT
    return all(_inside_cavity(x, y, zz) for x, y in pts for zz in (zs + 0.05, zs + 1.65))


def build_sites() -> list[Site]:
    sites = [side_site(y, z) for z in Z_LEVELS for y in SIDE_Y]
    sites += [side_site(y + SIDE_PITCH, z) for z in Z_LEVELS for y in SIDE_Y]
    sites += [bottom_site(z) for z in Z_LEVELS]
    unique = {s.name: s for s in sites}
    return [s for s in unique.values()
            if module_fits(_sim(s)) and camera_block(_sim(s)) == 0.0]


def base_scene() -> Path:
    """Fusion の筐体と評価板だけのシーン(基板・配線・LED を外す)."""
    config = yaml.safe_load(SCENE_V4.read_text(encoding="utf-8"))
    dest = TMP_DIR / "led_mounts_v4" / "base.yaml"
    dest.parent.mkdir(parents=True, exist_ok=True)
    meshes = []
    for mesh in config["geometry"]["meshes"]:
        if mesh["id"].startswith("led_cover_") or mesh["id"] == "wires":
            continue
        mesh["path"] = relative_mesh_path((SCENE_V4.parent / mesh["path"]).resolve(), dest.parent)
        meshes.append(mesh)
    config["geometry"]["meshes"] = meshes
    config["lights"] = []
    dest.write_text(yaml.safe_dump(config, allow_unicode=True, sort_keys=False),
                    encoding="utf-8", newline="\n")
    return dest


def render_basis(part: tuple[int, int] | None, prepare_only: bool) -> int:
    base = base_scene()
    sites = build_sites()
    probe = next(s for s in sites if s.name == MIRROR_PROBE)
    all_sites = [*sites, mirror_site(probe)]
    OUTPUT.mkdir(parents=True, exist_ok=True)
    with (OUTPUT / "sites.csv").open("w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["name", "wall", "x", "y", "z"])
        for s in all_sites:
            writer.writerow([s.name, s.wall, *s.led])
    scenes = {s.name: build_modules_yaml(s.name, [(s, 1.0)], base,
                                         f"SmTIASv4 の筐体・LED 3 個 1 組の基底画像: {s.name}")
              for s in all_sites}
    print(f"[prepare] {len(all_sites)} か所")
    if prepare_only:
        return 0
    from sm_tias_lightsim.render.pipeline import render_yaml

    names = sorted(scenes)
    if part is not None:
        k, n = part
        names = names[k::n]
    for name in names:
        out = OUTPUT / name
        if (out / "luminance.npy").exists():
            continue
        t0 = time.perf_counter()
        render_yaml(scenes[name], out)
        print(f"[render] {name} ({time.perf_counter() - t0:.1f}s)", flush=True)
    print("[done]")
    return 0


def _metrics(image: np.ndarray) -> dict[str, float]:
    from compare_real_vs_sim_metrics import metrics_for

    return metrics_for(image)


def search(top: int, workers: int) -> int:
    from compare_real_vs_sim_metrics import load_sim_roi, metrics_for
    from scipy.ndimage import gaussian_filter

    probe = load_sim_roi(OUTPUT / MIRROR_PROBE / "luminance.npy")
    mirrored = load_sim_roi(OUTPUT / f"{MIRROR_PROBE}_mirror" / "luminance.npy")
    err = {a: float(np.abs(gaussian_filter(np.flip(probe, axis=a) - mirrored, 8)).mean())
           for a in (0, 1)}
    axis = min(err, key=err.get)
    print(f"[mirror] 軸 {axis}(平均差 {err[axis] / mirrored.mean():.4f}・もう一方 "
          f"{err[1 - axis] / mirrored.mean():.4f})")

    def pair(name: str) -> np.ndarray | None:
        path = OUTPUT / name / "luminance.npy"
        if not path.exists():
            return None
        roi = load_sim_roi(path)
        return roi + np.flip(roi, axis=axis)

    a0 = metrics_for(load_sim_roi(A0_LUMINANCE))
    jobs = []
    for zs in Z_LEVELS:
        for y in SIDE_Y:
            if not side_board_fits(y, zs):
                continue
            lo, hi = pair(side_site(y, zs).name), pair(side_site(y + SIDE_PITCH, zs).name)
            if lo is None or hi is None:
                continue
            for zb in Z_LEVELS:
                bottom = pair(bottom_site(zb).name)
                if bottom is None:
                    continue
                for gain in BOTTOM_GAINS:
                    jobs.append(((y, zs, zb, gain), lo + hi + gain * bottom))
    print(f"[search] {len(jobs)} 通り・{workers} 並列", flush=True)
    with ProcessPoolExecutor(max_workers=workers) as pool:
        results = list(pool.map(_metrics, [img for _, img in jobs], chunksize=8))
    rows = []
    for ((y, zs, zb, gain), _), m in zip(jobs, results, strict=True):
        rows.append({
            "side_y": y, "side_z": zs, "bottom_z": zb, "bottom_gain": gain,
            "same_z": zs == zb,
            "structure_cov_ratio": round(m["structure_cov"] / a0["structure_cov"], 3),
            "min_fullimage": round(m["min_fullimage"], 3),
            "min_ring": round(m["min_ring"], 3),
            "b1": round(m["b1"], 4), "a1": round(m["a1"], 4),
            "bright_ratio": round(m["mean"] / a0["mean"], 2),
        })
    rows.sort(key=lambda r: r["structure_cov_ratio"])
    out = OUTPUT / "search.csv"
    with out.open("w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    now = next(r for r in rows if r["side_y"] == 10.0 and r["side_z"] == -38.0
               and r["bottom_z"] == -38.0 and r["bottom_gain"] == 1.0)
    print("[now]", now)
    for title, sel in (("全部", rows), ("同じ高さ", [r for r in rows if r["same_z"]]),
                       ("下も 60 mA", [r for r in rows if r["bottom_gain"] == 1.0])):
        print(f"== {title}")
        for r in sel[:top]:
            print(f"  {r['structure_cov_ratio']:.3f} min {r['min_fullimage']:.3f} "
                  f"輪帯 {r['min_ring']:.3f} b1 {r['b1']:+.4f} 明るさ {r['bright_ratio']:.2f}  "
                  f"横 Y{r['side_y']:g}/{r['side_y'] + SIDE_PITCH:g} Z{r['side_z']:g}  "
                  f"下 Z{r['bottom_z']:g}×{r['bottom_gain']:g}")
    print(f"[saved] {out}({len(rows)} 通り)")
    return 0


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--prepare-only", action="store_true", help="シーンと sites.csv だけ作る")
    parser.add_argument("--part", help="k/n: 場所を n 個に分けた k 番目だけレンダする")
    parser.add_argument("--search", action="store_true", help="基底画像の和で組み合わせを探す")
    parser.add_argument("--top", type=int, default=10)
    parser.add_argument("--workers", type=int, default=8, help="--search の並列数")
    args = parser.parse_args(argv)
    if args.search:
        return search(args.top, args.workers)
    part = None
    if args.part:
        k, n = (int(v) for v in args.part.split("/"))
        part = (k, n)
    return render_basis(part, args.prepare_only)


if __name__ == "__main__":
    raise SystemExit(main())