Newer
Older
SmTIAS-LightSim / tests / evaluation / test_real_maps.py
"""evaluation/real_maps.py(実機の白板 ROI 輝度マップとキャッシュ)の仕様ベーステスト.

仕様出典:
- docs/02_ENV/ENV_04_開発コマンド.md「実機のデータ」(real_roi_luminance("full") は
  (1409, 1400)・mean 207.82.結果は output/_cache/real_maps/ に保存し以後そこから読む)
- docs/04_SPEC/SPEC_04_評価仕様.md(実機 ROI 539, 1015, 1400, 1409.REAL_ROI)
- real_maps.py の docstring(float32.キャッシュ名に撮影名・LSC 有無・ROI.
  DNG・meta.json より新しいキャッシュだけ使う)

キャッシュの判定は,SMTIAS_LAB を tmp_path の偽の Lab に向け,重い DNG の処理
(dng_luminance)だけ差し替えて確かめる(ファイル I/O は実ファイル).実 DNG を使う
検証は Lab が無ければスキップし,slow を付ける.
"""

from __future__ import annotations

import csv
import os
import shutil

import numpy as np
import pytest

from sm_tias_lightsim.evaluation import real_maps
from sm_tias_lightsim.evaluation.real_maps import (
    DEFAULT_CACHE_DIR,
    real_roi_luminance,
    resolve_shot,
)
from sm_tias_lightsim.evaluation.roi_presets import REAL_ROI
from sm_tias_lightsim.lab import (
    LAB_ENV_VAR,
    V3_FULL_UNIFORMITY_CSV,
    V3_SHOTS,
    LabShot,
    find_lab_file,
)
from sm_tias_lightsim.uniformity import calc_uniformity

_EXP = "2026-01-01_fake"
_STEM = "SmTIAS_QM_FAKE"
_SHOT = LabShot(_EXP, _STEM)
_SMALL_ROI = {"x": 2, "y": 3, "w": 4, "h": 5}


@pytest.fixture
def fake_lab(tmp_path, monkeypatch):
    """偽の Lab(DNG・meta.json は中身の無いファイル)に SMTIAS_LAB を向ける."""
    root = tmp_path / "Lab"
    raw = root / "experiments" / _EXP / "raw"
    raw.mkdir(parents=True)
    dng = raw / f"{_STEM}.dng"
    meta = raw / f"{_STEM}.meta.json"
    dng.write_bytes(b"dng")
    meta.write_text("{}", encoding="utf-8")
    monkeypatch.setenv(LAB_ENV_VAR, str(root))
    return dng, meta


@pytest.fixture
def fake_luminance(monkeypatch):
    """dng_luminance を軽い関数に差し替え,呼び出しを記録する."""
    calls = []

    def _fake(dng_path, *, apply_lsc=True, meta_path=None):
        calls.append({"dng": dng_path, "apply_lsc": apply_lsc, "meta": meta_path})
        h, w = 20, 15
        return np.arange(h * w, dtype=np.float64).reshape(h, w) + (100.0 if apply_lsc else 0.0)

    monkeypatch.setattr(real_maps, "dng_luminance", _fake)
    return calls


def _set_mtime(path, t):
    os.utime(path, (t, t))


class TestResolveShot:
    @pytest.mark.parametrize("key", ["full", "bottom", "left", "right"])
    def test_keys(self, key):
        assert resolve_shot(key) == V3_SHOTS[key]

    def test_labshot_passthrough(self):
        assert resolve_shot(_SHOT) is _SHOT

    def test_unknown_key_raises(self):
        with pytest.raises(ValueError, match="full"):
            resolve_shot("top")


def test_default_cache_dir_is_output_cache_real_maps():
    assert DEFAULT_CACHE_DIR.parts[-3:] == ("output", "_cache", "real_maps")


class TestRealRoiLuminanceCache:
    def test_roi_crop_float32(self, fake_lab, fake_luminance, tmp_path):
        out = real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=tmp_path / "c")
        assert out.dtype == np.float32
        assert out.shape == (5, 4)
        full = np.arange(20 * 15, dtype=np.float64).reshape(20, 15) + 100.0
        np.testing.assert_array_equal(out, full[3:8, 2:6].astype(np.float32))

    def test_lsc_passes_meta(self, fake_lab, fake_luminance, tmp_path):
        dng, meta = fake_lab
        real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=None)
        assert fake_luminance[0]["apply_lsc"] is True
        assert fake_luminance[0]["dng"].resolve() == dng.resolve()
        assert fake_luminance[0]["meta"].resolve() == meta.resolve()

    def test_cache_file_name_contains_shot_lsc_roi(self, fake_lab, fake_luminance, tmp_path):
        cache_dir = tmp_path / "c"
        real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=cache_dir)
        real_roi_luminance(_SHOT, roi=_SMALL_ROI, apply_lsc=False, cache_dir=cache_dir)
        names = sorted(p.name for p in cache_dir.iterdir())
        assert names == [
            f"{_STEM}_lsc_x2_y3_w4_h5.npy",
            f"{_STEM}_nolsc_x2_y3_w4_h5.npy",
        ]

    def test_default_roi_is_real_roi(self, fake_lab, monkeypatch, tmp_path):
        def _big(dng_path, *, apply_lsc=True, meta_path=None):
            return np.ones((2500, 2000))

        monkeypatch.setattr(real_maps, "dng_luminance", _big)
        cache_dir = tmp_path / "c"
        out = real_roi_luminance(_SHOT, cache_dir=cache_dir)
        assert out.shape == (REAL_ROI["h"], REAL_ROI["w"]) == (1409, 1400)
        assert (cache_dir / f"{_STEM}_lsc_x539_y1015_w1400_h1409.npy").is_file()

    def test_cache_written_and_reused(self, fake_lab, fake_luminance, tmp_path):
        cache_dir = tmp_path / "c"
        first = real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=cache_dir)
        second = real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=cache_dir)
        assert len(fake_luminance) == 1
        np.testing.assert_array_equal(first, second)
        assert second.dtype == np.float32

    def test_uses_newer_cache_without_computing(self, fake_lab, fake_luminance, tmp_path):
        """DNG・meta より新しいキャッシュはそのまま読む(中身はキャッシュの値)."""
        dng, meta = fake_lab
        cache_dir = tmp_path / "c"
        cache_dir.mkdir()
        cache = cache_dir / f"{_STEM}_lsc_x2_y3_w4_h5.npy"
        sentinel = np.full((5, 4), 42.0, dtype=np.float32)
        np.save(cache, sentinel)
        _set_mtime(dng, 1_000_000)
        _set_mtime(meta, 1_000_000)
        _set_mtime(cache, 2_000_000)
        out = real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=cache_dir)
        assert fake_luminance == []
        np.testing.assert_array_equal(out, sentinel)

    def test_recomputes_when_dng_is_newer(self, fake_lab, fake_luminance, tmp_path):
        dng, meta = fake_lab
        cache_dir = tmp_path / "c"
        cache_dir.mkdir()
        cache = cache_dir / f"{_STEM}_lsc_x2_y3_w4_h5.npy"
        np.save(cache, np.full((5, 4), 42.0, dtype=np.float32))
        _set_mtime(cache, 1_000_000)
        _set_mtime(meta, 1_000_000)
        _set_mtime(dng, 2_000_000)
        out = real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=cache_dir)
        assert len(fake_luminance) == 1
        assert not np.any(out == 42.0)
        # キャッシュは作り直され,新しい値になっている
        np.testing.assert_array_equal(np.load(cache), out)
        assert cache.stat().st_mtime >= dng.stat().st_mtime

    def test_recomputes_when_meta_is_newer(self, fake_lab, fake_luminance, tmp_path):
        dng, meta = fake_lab
        cache_dir = tmp_path / "c"
        cache_dir.mkdir()
        cache = cache_dir / f"{_STEM}_lsc_x2_y3_w4_h5.npy"
        np.save(cache, np.full((5, 4), 42.0, dtype=np.float32))
        _set_mtime(cache, 1_500_000)
        _set_mtime(dng, 1_000_000)
        _set_mtime(meta, 2_000_000)
        real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=cache_dir)
        assert len(fake_luminance) == 1

    def test_nolsc_ignores_meta(self, fake_lab, fake_luminance, tmp_path):
        """LSC 無しなら meta.json は不要で,meta の更新ではキャッシュを捨てない."""
        dng, meta = fake_lab
        cache_dir = tmp_path / "c"
        cache_dir.mkdir()
        cache = cache_dir / f"{_STEM}_nolsc_x2_y3_w4_h5.npy"
        np.save(cache, np.full((5, 4), 7.0, dtype=np.float32))
        _set_mtime(dng, 1_000_000)
        _set_mtime(cache, 1_500_000)
        _set_mtime(meta, 2_000_000)
        out = real_roi_luminance(_SHOT, roi=_SMALL_ROI, apply_lsc=False, cache_dir=cache_dir)
        assert fake_luminance == []
        np.testing.assert_array_equal(out, 7.0)

    def test_nolsc_works_without_meta(self, fake_lab, fake_luminance, tmp_path):
        _, meta = fake_lab
        meta.unlink()
        real_roi_luminance(_SHOT, roi=_SMALL_ROI, apply_lsc=False, cache_dir=None)
        assert fake_luminance[0]["apply_lsc"] is False

    def test_cache_dir_none_writes_nothing(self, fake_lab, fake_luminance, tmp_path):
        before = set(tmp_path.rglob("*"))
        real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=None)
        real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=None)
        assert len(fake_luminance) == 2
        assert set(tmp_path.rglob("*")) == before

    def test_cache_dir_created(self, fake_lab, fake_luminance, tmp_path):
        cache_dir = tmp_path / "a" / "b" / "c"
        real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=cache_dir)
        assert cache_dir.is_dir()

    def test_different_roi_is_separate_cache(self, fake_lab, fake_luminance, tmp_path):
        cache_dir = tmp_path / "c"
        real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=cache_dir)
        other = {"x": 0, "y": 0, "w": 3, "h": 3}
        out = real_roi_luminance(_SHOT, roi=other, cache_dir=cache_dir)
        assert out.shape == (3, 3)
        assert len(fake_luminance) == 2

    def test_missing_dng_raises(self, fake_lab, fake_luminance, tmp_path):
        dng, _ = fake_lab
        dng.unlink()
        with pytest.raises(FileNotFoundError):
            real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=tmp_path / "c")

    def test_missing_meta_with_lsc_raises(self, fake_lab, fake_luminance, tmp_path):
        _, meta = fake_lab
        meta.unlink()
        with pytest.raises(FileNotFoundError):
            real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=tmp_path / "c")
        assert fake_luminance == []

    def test_missing_dng_raises_even_with_cache(self, fake_lab, fake_luminance, tmp_path):
        """Lab の DNG が無ければ,キャッシュがあっても読まずにエラー(データの所在を確かめる)."""
        dng, _ = fake_lab
        cache_dir = tmp_path / "c"
        real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=cache_dir)
        dng.unlink()
        with pytest.raises(FileNotFoundError):
            real_roi_luminance(_SHOT, roi=_SMALL_ROI, cache_dir=cache_dir)

    def test_unknown_shot_name_raises(self, fake_lab, tmp_path):
        with pytest.raises(ValueError):
            real_roi_luminance("nope", cache_dir=tmp_path / "c")


# ---------------------------------------------------------------------------
# 実 DNG(SmTIAS-Lab が無ければスキップ)
# ---------------------------------------------------------------------------


def _full_paths():
    full = V3_SHOTS["full"]
    dng = find_lab_file(full.experiment, "raw", full.dng_name)
    meta = find_lab_file(full.experiment, "raw", full.meta_name)
    csv_path = find_lab_file(*V3_FULL_UNIFORMITY_CSV)
    return dng, meta, csv_path


@pytest.mark.slow
class TestRealFullMatchesLabResults:
    """ENV_04: real_roi_luminance("full") は (1409, 1400)・mean 207.82.
    Lab results の uniformity.csv(Evaluation で評価した値)と一致すること.
    """

    @pytest.fixture(scope="class")
    def full_map(self, tmp_path_factory):
        dng, meta, csv_path = _full_paths()
        if dng is None or meta is None or csv_path is None:
            pytest.skip("SmTIAS-Lab に実機の全灯 DNG・meta.json・uniformity.csv がありません")
        cache_dir = tmp_path_factory.mktemp("real_maps_cache")
        out = real_roi_luminance("full", cache_dir=cache_dir)
        with csv_path.open(encoding="utf-8") as f:
            expected = {k: float(v) for k, v in next(csv.DictReader(f)).items()}
        return out, expected, cache_dir

    def test_shape_dtype(self, full_map):
        out, _, _ = full_map
        assert out.shape == (1409, 1400)
        assert out.dtype == np.float32

    def test_mean_matches_csv(self, full_map):
        out, expected, _ = full_map
        assert float(np.mean(out, dtype=np.float64)) == pytest.approx(expected["mean"], rel=1e-5)

    def test_cov_matches_csv(self, full_map):
        out, expected, _ = full_map
        result = calc_uniformity(out.astype(np.float64))
        assert result["cov"] == pytest.approx(expected["cov"], rel=1e-4)

    def test_max_min_match_csv(self, full_map):
        out, expected, _ = full_map
        assert float(out.max()) == pytest.approx(expected["max"], rel=1e-5)
        assert float(out.min()) == pytest.approx(expected["min"], rel=1e-5)

    def test_cache_written_with_expected_name(self, full_map):
        _, _, cache_dir = full_map
        stem = V3_SHOTS["full"].stem
        assert (cache_dir / f"{stem}_lsc_x539_y1015_w1400_h1409.npy").is_file()

    def test_second_call_reads_same_cache(self, full_map):
        out, _, cache_dir = full_map
        again = real_roi_luminance("full", cache_dir=cache_dir)
        np.testing.assert_array_equal(again, out)


@pytest.mark.slow
def test_real_dng_newer_than_cache_is_recomputed(tmp_path, monkeypatch):
    """実 DNG を偽の Lab にコピーし,DNG を新しくすると古いキャッシュを捨てて作り直す."""
    dng, meta, _ = _full_paths()
    if dng is None or meta is None:
        pytest.skip("SmTIAS-Lab に実機の全灯 DNG・meta.json がありません")
    full = V3_SHOTS["full"]
    raw = tmp_path / "Lab" / "experiments" / full.experiment / "raw"
    raw.mkdir(parents=True)
    dng_copy = shutil.copy2(dng, raw / full.dng_name)
    meta_copy = shutil.copy2(meta, raw / full.meta_name)
    monkeypatch.setenv(LAB_ENV_VAR, str(tmp_path / "Lab"))

    cache_dir = tmp_path / "cache"
    cache_dir.mkdir()
    cache = cache_dir / f"{full.stem}_lsc_x539_y1015_w1400_h1409.npy"
    np.save(cache, np.zeros((1409, 1400), dtype=np.float32))
    _set_mtime(cache, 1_000_000)
    _set_mtime(meta_copy, 1_000_000)
    _set_mtime(dng_copy, 2_000_000)

    out = real_roi_luminance("full", cache_dir=cache_dir)
    assert out.mean() == pytest.approx(207.82, rel=1e-3)
    assert np.load(cache).mean() == pytest.approx(207.82, rel=1e-3)