diff --git a/scripts/led_site_basis.py b/scripts/led_site_basis.py new file mode 100644 index 0000000..16778ea --- /dev/null +++ b/scripts/led_site_basis.py @@ -0,0 +1,298 @@ +"""LED の置き場所を 3 個 1 組のモジュール単位で網羅的に調べるための「1 か所だけ点けた」画像を作る. + +光の足し合わせは線形なので,置き場所の候補ごとに LED モジュールを 1 個だけ置いてレンダした +輝度画像(基底画像)を作っておけば,任意の組み合わせの画像はその和で近似できる +(他のモジュールの基板による遮りと反射は無視する近似.よい組み合わせは最後に本番どおりレンダして +確かめる).組み合わせの探索は scripts/optimize_led_sites.py で行う. + +モジュールは現行基板の電気的な単位(LED 3 個を直列にして定電流 IC で 60 mA.SPEC_05)を +小さな基板にしたもの: LED 3 個(間隔 4 mm)を壁に沿って並べ,箱の奥(-Z)へ向ける. +筐体は TEST_21 の H_y90(上面を傾けた箱・内側の角 R20・鼻の穴あり・-Y 側 -90)に固定する. + +壁の丸みに食い込む場所と,カメラから開口部への視線をふさぐ場所は候補から外す.X について +左右対称なので,候補は X ≥ 0 側だけ置き,左側は画像を左右反転して使う(反転の向きは +確認用の 1 か所(名前の末尾 _mirror)で確かめる). + +実行方法(重いので研究室サーバで): + uv run python scripts/led_site_basis.py --prepare-only # シーンと sites.csv だけ + uv run python scripts/led_site_basis.py # 全候補をレンダ + uv run python scripts/led_site_basis.py --only R_y-10_z-35 +""" + +from __future__ import annotations + +import argparse +import copy +import csv +import sys +import time +from dataclasses import dataclass, replace +from pathlib import Path + +import numpy as np +import trimesh +import yaml + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) + +from check_camera_view import OPENING_HALF, OPENING_Z, segment_hits_aabb # noqa: E402 +from sweep_candidate_layouts import ( # noqa: E402 + BASE_YAML, + CANDIDATES, + LED_WALL_OFFSET, + MESH_DIR, + ROOT, + SLOPED_SLOPE, + SLOPED_Y_TOP, + TMP_DIR, + _bottom_leds, + build_candidate_yaml, +) + +from sm_tias_lightsim.scene.paths import relative_mesh_path # noqa: E402 + +OUTPUT_BASE = ROOT / "output" / "led_sites" +BASE_CANDIDATE = "H_y90" + +# モジュールの寸法: LED 3 個を間隔 4 mm で並べた小基板.LED の中心は壁から LED_WALL_OFFSET +MODULE_PITCH = 4.0 +MODULE_ALONG = 16.0 # 壁に沿った長さ +MODULE_TO_WALL = LED_WALL_OFFSET - 1.0 # LED 列から壁側の端まで(壁と 1 mm 空ける) +MODULE_INWARD = 4.0 # LED 列から箱の内側の端まで +MODULE_THICKNESS = 1.6 + +# 箱(H_y90)の内面: X ±80,Y -90 〜 y_top(z),角の丸み R20(安全側に全部 R20 で判定) +HALF_X = 80.0 +Y_MIN = -90.0 +CORNER_R = 20.0 +Z_LEVELS = (-15.0, -25.0, -35.0, -50.0, -70.0, -100.0) +CAMERA = np.array([0.0, 4.0, -144.0]) +CAMERA_SPREAD = 10.0 + + +def y_top(z: float) -> float: + """上の傾いた壁の内面の Y.""" + return SLOPED_Y_TOP + SLOPED_SLOPE * z + + +@dataclass(frozen=True) +class Site: + """LED モジュールを置く場所 1 つ.""" + + name: str + wall: str # "right" / "bottom" / "top" + led: tuple[float, float, float] # 真ん中の LED の中心 + along: tuple[float, float] # LED を並べる向き(XY 平面の単位ベクトル) + inward: tuple[float, float] # 壁から箱の内側への向き + + +def _module_box(site: Site) -> tuple[np.ndarray, np.ndarray]: + """モジュールの基板(軸平行の箱)の (最小角, 最大角).""" + led = np.array(site.led) + along = np.array([*site.along, 0.0]) + inward = np.array([*site.inward, 0.0]) + corners = [] + for a in (-MODULE_ALONG / 2, MODULE_ALONG / 2): + for b in (-MODULE_TO_WALL, MODULE_INWARD): + for c in (0.05, 0.05 + MODULE_THICKNESS): + corners.append(led + a * along + b * inward + np.array([0.0, 0.0, c])) + pts = np.array(corners) + return pts.min(axis=0), pts.max(axis=0) + + +def _inside_cavity(x: float, y: float, z: float) -> bool: + """点が箱の内面(角の丸みを R20 とした安全側の近似)の内側にあるか.""" + top = y_top(z) + if abs(x) > HALF_X or y < Y_MIN or y > top: + return False + dx = abs(x) - (HALF_X - CORNER_R) + for dy in (y - (top - CORNER_R), (Y_MIN + CORNER_R) - y): + if dx > 0 and dy > 0 and dx * dx + dy * dy > CORNER_R * CORNER_R: + return False + return True + + +def module_fits(site: Site) -> bool: + """モジュールの基板の四隅が箱の内側に収まるか.""" + lo, hi = _module_box(site) + return all(_inside_cavity(x, y, z) for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) + for z in (lo[2], hi[2])) + + +def camera_block(site: Site, grid: int = 41) -> float: + """カメラ位置の候補(中心 ±10 mm の 9 点)のうち最悪の,開口部をふさぐ割合.""" + lo, hi = _module_box(site) + xs = np.linspace(-OPENING_HALF[0], OPENING_HALF[0], grid) + ys = np.linspace(-OPENING_HALF[1], OPENING_HALF[1], grid) + targets = np.array([[x, y, OPENING_Z] for x in xs for y in ys]) + return max( + segment_hits_aabb(CAMERA + np.array([dx, dy, 0.0]), targets, lo, hi).mean() + for dx in (-CAMERA_SPREAD, 0.0, CAMERA_SPREAD) + for dy in (-CAMERA_SPREAD, 0.0, CAMERA_SPREAD) + ) + + +def build_sites() -> list[Site]: + """候補の場所を並べる(X ≥ 0 側.収まらない場所は除く).""" + sites = [] + wall_x = HALF_X - LED_WALL_OFFSET + wall_y = Y_MIN + LED_WALL_OFFSET + for z in Z_LEVELS: + for y in (-70.0, -50.0, -30.0, -10.0, 10.0, 30.0): + sites.append(Site(f"R_y{y:g}_z{z:g}", "right", (wall_x, y, z), (0.0, 1.0), + (-1.0, 0.0))) + for x in (0.0, 13.0, 26.0, 39.0, 52.0): + sites.append(Site(f"B_x{x:g}_z{z:g}", "bottom", (x, wall_y, z), (1.0, 0.0), + (0.0, 1.0))) + for x in (0.0, 15.0, 30.0, 45.0): + sites.append(Site(f"T_x{x:g}_z{z:g}", "top", (x, y_top(z) - LED_WALL_OFFSET, z), + (1.0, 0.0), (0.0, -1.0))) + # L3(下の壁 X ±39・Z -15 + 左右の壁 Y +10 と +30・Z -35)のまわりを細かく + for z in (-10.0, -15.0, -20.0): + for x in np.arange(30.0, 48.1, 3.0): + sites.append(Site(f"B_x{x:g}_z{z:g}", "bottom", (float(x), wall_y, z), (1.0, 0.0), + (0.0, 1.0))) + for z in (-30.0, -35.0, -40.0): + for y in np.arange(0.0, 40.1, 5.0): + sites.append(Site(f"R_y{y:g}_z{z:g}", "right", (wall_x, float(y), z), (0.0, 1.0), + (-1.0, 0.0))) + unique = {s.name: s for s in sites} + return [s for s in unique.values() if module_fits(s) and camera_block(s) == 0.0] + + +def mirror_site(site: Site) -> Site: + """X を反転した場所(左右反転の向きの確認用).""" + x, y, z = site.led + return replace(site, name=f"{site.name}_mirror", led=(-x, y, z), + along=(-site.along[0], site.along[1]), inward=(-site.inward[0], site.inward[1])) + + +def build_modules_yaml( + name: str, modules: list[tuple[Site, float]], base_scene: Path, description: str +) -> Path: + """箱だけのシーンに LED モジュール(基板 + LED 3 個.明るさの倍率つき)を足した YAML を書く.""" + config = yaml.safe_load(base_scene.read_text(encoding="utf-8")) + base = yaml.safe_load(BASE_YAML.read_text(encoding="utf-8")) + template = _bottom_leds(base)[0] + dest = TMP_DIR / "led_sites" / f"scene_{name}.yaml" + dest.parent.mkdir(parents=True, exist_ok=True) + for mesh in config["geometry"]["meshes"]: + mesh["path"] = relative_mesh_path(base_scene.parent / mesh["path"], dest.parent) + + lights = [] + for j, (site, gain) in enumerate(modules): + lo, hi = _module_box(site) + plate = trimesh.creation.box(extents=hi - lo) + plate.apply_translation((lo + hi) / 2) + plate_path = MESH_DIR / "led_sites" / f"{site.name}.stl" + plate_path.parent.mkdir(parents=True, exist_ok=True) + plate.export(plate_path) + config["geometry"]["meshes"].append({ + "id": f"led_cover_module{j}", "path": relative_mesh_path(plate_path, dest.parent), + "unit": "mm", "material": "printer_white", + }) + led = np.array(site.led) + along = np.array([*site.along, 0.0]) + for k in (-1, 0, 1): + light = copy.deepcopy(template) + light["id"] = f"led_module{j}_{k + 1}" + light["center"] = [round(float(c), 4) for c in led + k * MODULE_PITCH * along] + light["direction"] = [0.0, 0.0, -1.0] + light["radiance"] = [float(r) * gain for r in template["radiance"]] + if abs(site.along[0]) < 0.5: # Y に沿って並べるときは LED の縦横を入れ替える + light["size"] = [template["size"][1], template["size"][0]] + lights.append(light) + config["lights"] = lights + config["name"] = name + config["description"] = description + config["render"]["seed"] = 0 + dest.write_text(yaml.safe_dump(config, allow_unicode=True, sort_keys=False), + encoding="utf-8", newline="\n") + return dest + + +def build_site_yaml(site: Site, base_scene: Path) -> Path: + """箱だけのシーンにモジュール 1 個を足した基底画像用の YAML.""" + return build_modules_yaml(site.name, [(site, 1.0)], base_scene, + f"LED モジュール 1 個の基底画像: {site.name}(H_y90 の箱)") + + +def parse_layout(spec: str, sites: dict[str, Site]) -> list[tuple[Site, float]]: + """「場所:倍率,場所:倍率」を,X > 0 の場所は左右対称に 2 個にしたモジュールの並びにする.""" + modules = [] + for item in spec.split(","): + site_name, gain = item.split(":") + site = sites[site_name] + modules.append((site, float(gain))) + if abs(site.led[0]) > 1e-6: + modules.append((mirror_site(site), float(gain))) + return modules + + +def render_layouts(specs: list[str], sites: dict[str, Site], base_scene: Path, base_cand) -> int: + """組み合わせを基板込みでレンダし,候補比較(candidate_layouts)と同じ指標で集計する.""" + from sweep_candidate_layouts import OUTPUT_BASE as CAND_OUTPUT + from sweep_candidate_layouts import SUMMARY_COLUMNS, run_candidate + + names = [spec.split("=", 1)[0] for spec in specs] + summary = CAND_OUTPUT / f"summary_layouts_{'_'.join(names)}.csv" + CAND_OUTPUT.mkdir(parents=True, exist_ok=True) + with summary.open("w", newline="", encoding="utf-8") as f: + writer = csv.DictWriter(f, fieldnames=SUMMARY_COLUMNS) + writer.writeheader() + for spec in specs: + name, layout = spec.split("=", 1) + note = f"H_y90 の箱・3 個 1 組のモジュール: {layout}" + scene = build_modules_yaml(name, parse_layout(layout, sites), base_scene, note) + cand = replace(base_cand, name=name, note=note) + for seed in (0, 1, 2): + writer.writerow(run_candidate(cand, scene, seed)) + f.flush() + print(f"[done] {summary}") + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--only", nargs="+", help="レンダする場所の名前(既定: 全部)") + parser.add_argument("--prepare-only", action="store_true", help="シーンと sites.csv だけ作る") + parser.add_argument("--layouts", nargs="+", metavar="NAME=SPEC", + help="組み合わせを基板込みで本番どおりにレンダする(seed 3 本)." + "SPEC は「場所:倍率,場所:倍率」(X > 0 の場所は左右に置く)") + args = parser.parse_args(argv) + + base_cand = next(c for c in CANDIDATES if c.name == BASE_CANDIDATE) + base_scene = build_candidate_yaml(replace(base_cand, name="led_sites_base", boards=())) + sites = build_sites() + if args.layouts: + return render_layouts(args.layouts, {s.name: s for s in sites}, base_scene, base_cand) + probe = next(s for s in sites if s.name == "R_y-10_z-35") + all_sites = [*sites, mirror_site(probe)] + + OUTPUT_BASE.mkdir(parents=True, exist_ok=True) + with (OUTPUT_BASE / "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_site_yaml(s, base_scene) for s in all_sites} + print(f"[prepare] {len(all_sites)} か所({OUTPUT_BASE / 'sites.csv'})") + if args.prepare_only: + return 0 + + from sm_tias_lightsim.render.pipeline import render_yaml + + for name in args.only or list(scenes): + out = OUTPUT_BASE / 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 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/optimize_led_sites.py b/scripts/optimize_led_sites.py new file mode 100644 index 0000000..2c0cd98 --- /dev/null +++ b/scripts/optimize_led_sites.py @@ -0,0 +1,174 @@ +"""LED モジュール(3 個 1 組)の置き場所の組み合わせを,基底画像の和で探す. + +scripts/led_site_basis.py で作った「1 か所だけ点けた」画像を使う.光は線形なので, +組み合わせの画像は基底画像の重み付き和で近似できる(他のモジュールの基板による遮りは無視). + +X > 0 の場所は左右対称に 2 個(左側は画像を左右反転)を 1 単位,X = 0 の場所は 1 個を 1 単位とする. +各単位の明るさは 60 mA(定電流 IC 2 個.重み 1)か 30 mA(IC 1 個.重み 0.5). + +ムラの指標は σ=12 px のガウス平滑化後の CoV(TEST_21 の構造 CoV と同じ平滑化.ノイズ補正なし). +平滑化は線形なので,平滑化した基底画像の内積の表(グラム行列)を先に作れば,組み合わせの +CoV² = N·wᵀGw / (wᵀm)² − 1 が小さな行列計算で求まる.これで単位を 2〜4 種類選ぶ組み合わせを +総当たりし,上位を本来の指標(metrics_for)で計算し直す. + +実行方法: + uv run python scripts/optimize_led_sites.py + uv run python scripts/optimize_led_sites.py --max-units 3 --top 20 +""" + +from __future__ import annotations + +import argparse +import csv +import itertools +import sys +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +from scipy.ndimage import gaussian_filter + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) + +from compare_real_vs_sim_metrics import ( # noqa: E402 + STRUCTURE_SIGMA, + load_sim_roi, + metrics_for, +) + +ROOT = Path(__file__).resolve().parents[1] +SITE_DIR = ROOT / "output" / "led_sites" +A0_LUMINANCE = ROOT / "output" / "candidate_layouts" / "A0" / "s0" / "luminance.npy" +MIRROR_PROBE = "R_y-10_z-35" +WEIGHTS = (0.5, 1.0) +LEDS_PER_MODULE = 3 + + +@dataclass(frozen=True) +class Unit: + """左右対称に置くモジュールの組(X = 0 なら 1 個).""" + + site: str + modules: int # 1(X = 0)か 2(左右) + image: np.ndarray # 輝度 ROI(重み 1 のとき) + + +def mirror_axis() -> int: + """左右反転に使う画像の軸を,確認用の反転レンダと比べて決める.""" + probe = load_sim_roi(SITE_DIR / MIRROR_PROBE / "luminance.npy") + mirrored = load_sim_roi(SITE_DIR / f"{MIRROR_PROBE}_mirror" / "luminance.npy") + errors = {axis: float(np.abs(gaussian_filter(np.flip(probe, axis=axis) - mirrored, 8)).mean()) + for axis in (0, 1)} + axis = min(errors, key=errors.get) + rel = errors[axis] / mirrored.mean() + print(f"[mirror] 画像の軸 {axis} で反転(平均差 {rel:.4f}・もう一方 " + f"{errors[1 - axis] / mirrored.mean():.4f})") + return axis + + +def load_units(axis: int) -> list[Unit]: + """sites.csv の場所ごとに単位(左右の組)の画像を作る.""" + units = [] + with (SITE_DIR / "sites.csv").open(encoding="utf-8") as f: + for row in csv.DictReader(f): + if row["name"].endswith("_mirror"): + continue + path = SITE_DIR / row["name"] / "luminance.npy" + if not path.exists(): + print(f"[skip] {row['name']}(画像なし)") + continue + roi = load_sim_roi(path) + if abs(float(row["x"])) > 1e-6: + units.append(Unit(row["name"], 2, roi + np.flip(roi, axis=axis))) + else: + units.append(Unit(row["name"], 1, roi)) + return units + + +def search(units: list[Unit], max_units: int, top: int, min_bright: float, a0_mean: float, + max_modules: int) -> list[tuple[float, tuple[int, ...], tuple[float, ...]]]: + """単位を 1〜max_units 種類選び,重み(0.5 / 1)の全組み合わせで平滑化 CoV を求める.""" + smooth = np.stack([gaussian_filter(u.image, STRUCTURE_SIGMA).ravel() for u in units]) + n_pix = smooth.shape[1] + gram = smooth @ smooth.T + means = smooth.sum(axis=1) + modules = np.array([u.modules for u in units]) + best: list[tuple[float, tuple[int, ...], tuple[float, ...]]] = [] + for k in range(1, max_units + 1): + combos = np.array(list(itertools.combinations(range(len(units)), k))) + for weights in itertools.product(WEIGHTS, repeat=k): + w = np.array(weights) + n_mod = (modules[combos] * (w > 0)).sum(axis=1) + sub_g = gram[combos[:, :, None], combos[:, None, :]] + num = np.einsum("ci,cij,cj->c", np.broadcast_to(w, combos.shape), sub_g, + np.broadcast_to(w, combos.shape)) + den = (means[combos] * w).sum(axis=1) + cov2 = n_pix * num / den**2 - 1.0 + bright = den / n_pix / a0_mean + ok = (n_mod <= max_modules) & (bright >= min_bright) + for idx in np.argsort(np.where(ok, cov2, np.inf))[:top]: + if not ok[idx]: + break + best.append((float(np.sqrt(max(cov2[idx], 0.0))), tuple(combos[idx]), + tuple(weights))) + best.sort(key=lambda t: t[0]) + return best[:top] + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--max-units", type=int, default=3, help="選ぶ場所の種類の最大数") + parser.add_argument("--max-modules", type=int, default=8, + help="モジュール(3 個 1 組)の最大数(8 で LED 24 個)") + parser.add_argument("--min-bright", type=float, default=0.6, + help="明るさの下限(現行機 A0 の平均輝度との比)") + parser.add_argument("--top", type=int, default=15) + parser.add_argument("--out", type=Path, default=SITE_DIR / "best_layouts.csv") + args = parser.parse_args(argv) + + axis = mirror_axis() + units = load_units(axis) + a0 = load_sim_roi(A0_LUMINANCE) + a0_metrics = metrics_for(a0) + print(f"[units] {len(units)} 単位") + best = search(units, args.max_units, args.top * 4, args.min_bright, a0.mean(), + args.max_modules) + + rows = [] + seen = set() + for proxy, combo, weights in best: + key = (combo, weights) + if key in seen: + continue + seen.add(key) + image = sum(w * units[i].image for i, w in zip(combo, weights, strict=True)) + m = metrics_for(image) + n_mod = sum(units[i].modules for i in combo) + rows.append({ + "layout": " + ".join(f"{units[i].site}×{w:g}" for i, w in zip(combo, weights, + strict=True)), + "modules": n_mod, "leds": n_mod * LEDS_PER_MODULE, + "proxy_cov": round(proxy, 5), + "structure_cov_ratio": round(m["structure_cov"] / a0_metrics["structure_cov"], 3), + "min_fullimage": round(m["min_fullimage"], 3), + "b1": round(m["b1"], 4), "a1": round(m["a1"], 4), + "bright_ratio": round(m["mean"] / a0_metrics["mean"], 2), + }) + if len(rows) >= args.top: + break + rows.sort(key=lambda r: r["structure_cov_ratio"]) + with args.out.open("w", newline="", encoding="utf-8") as f: + writer = csv.DictWriter(f, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + for r in rows: + print(f"{r['structure_cov_ratio']:.3f} min {r['min_fullimage']:.3f} " + f"b1 {r['b1']:+.4f} 明るさ {r['bright_ratio']:.2f} LED {r['leds']:2d} " + f"{r['layout']}") + print(f"[saved] {args.out}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())