diff --git a/.gitignore b/.gitignore index d54d4bb..64a88ca 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,7 @@ # シミュ・評価結果(コミット対象外) output/ -# 実機実測データ(SmTIAS-Evaluation からの引き渡し入力.コミット対象外) +# 実測データの旧置き場(廃止.撮影データは ../SmTIAS-Lab に置く.誤って戻したときに入らないよう残す) lightsim/ # docs 下の生成画像(再生成可能なので追跡しない.生成スクリプトは追跡する) @@ -27,7 +27,7 @@ # 目視確認用の一時スクリーンショット(リポジトリルートに上書き生成される作業ファイル) /image.png -# SmTIAS-Evaluation 側から受け取った実測リファレンスデータ(個人ローカル) +# 実測リファレンスデータの旧置き場(廃止.SmTIAS-Lab へ移した) reference_measurement/ # Python / uv diff --git a/CLAUDE.md b/CLAUDE.md index 71980ad..b6ad3ff 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -13,7 +13,7 @@ | [SmTIAS-Evaluation](https://github.com/rintoHasegawa/SmTIAS-Evaluation) | 実機の照明均一性評価ツール | `../SmTIAS-Evaluation` | | [SmTIAS-Capture](https://github.com/rintoHasegawa/SmTIAS-Capture) | スマホ撮影アプリ | 無し(`gh api` で読む) | -- **撮影データは SmTIAS-Lab に置く**(`experiments/_<内容>/raw/`.git の対象外).本リポジトリの直下や `lightsim/`・`reference_measurement/` には新しく置かない(この 2 つは旧来の置き場で,Lab へ移す予定) +- **撮影データは SmTIAS-Lab に置く**(`experiments/_<内容>/raw/`.git の対象外).本リポジトリには置かない(旧置き場の `lightsim/`・`reference_measurement/` は廃止).スクリプト・テストは `src/sm_tias_lightsim/lab.py` で Lab を指す(環境変数 `SMTIAS_LAB`,無ければ `../SmTIAS-Lab`).Lab のデータは `sm-remote push` でサーバへ送らないので,実機の DNG を読むスクリプトは手元で実行する - 「何のために何を撮り,何が分かったか」は Lab の実験フォルダの `README.md` と `PROGRESS.md` に書く.本リポジトリの `docs/PROGRESS.md`・`docs/06_TEST/` にはシミュとコードの経緯を書き,Lab から TEST へリンクする - **Evaluation のコードは import せず,Evaluation の環境で実行する**(パッケージ名が `src` で環境も別のため): `uv run --project ../SmTIAS-Evaluation python ../SmTIAS-Evaluation/scripts/<スクリプト>.py ...` - Evaluation・Lab の変更のコミットはそれぞれのリポジトリで行う(`/commit` は本リポジトリ用).Evaluation を大きく直すときは Evaluation のフォルダで Claude Code を起動し直す(向こうの CLAUDE.md・ルールが読み込まれるため) @@ -60,6 +60,9 @@ - `src/sm_tias_lightsim/scene/paths.py` — `relative_mesh_path()`:スイープ生成スクリプトが `_tmp` YAML に書くメッシュパスを YAML からの相対パス(POSIX 区切り)にする(手元とサーバで同じ YAML を読むため.別ドライブは警告して絶対パス) - `src/sm_tias_lightsim/remote/{commands,files,transfer}.py` + `src/sm_tias_lightsim/cli/remote.py` — `sm-remote` CLI(研究室サーバ Newton での実行).push(tar over ssh.`.venv`/`output`/`.git`/`configs/_tmp_*` 除外)/ run(tmux でデタッチ起動.既定 `cuda_ad_rgb`・`--gpu`・`--threads`)/ status / logs / attach / kill / pull(`output/` 配下のみ.要求パス外・不正な名前・リンクを拒否).サーバ上で実行すると止まって案内.使い方は ENV_04「研究室サーバでの実行」 - `src/sm_tias_lightsim/evaluation/dng_loader.py` — DNG 読み込みモジュール.SmTIAS-Evaluation `src/io/dng_loader.py` を SmTIAS-LightSim にコピーしたもの (オリジナルは SmTIAS-Evaluation 側で管理.バグ修正・機能追加はそちらで反映).主要 API: `load_image_dng(path, demosaic, black_level, output_format)`.`output_format` は `rgb_float32` / `luma_float32` / `rgb_uint8`.linear 系出力 (`rgb_float32` / `luma_float32`) は `output_color=raw` でカラーマトリクス非適用・per-channel 比例性保持.`gamma=(1,1) + no_auto_bright=True + use_camera_wb=False + user_wb=[1,1,1,1]` で linear raw を保つ.依存: `rawpy>=0.21.0` +- `src/sm_tias_lightsim/lab.py` — 実験データ(SmTIAS-Lab)の場所の解決.環境変数 `SMTIAS_LAB`,無ければリポジトリの隣の `../SmTIAS-Lab`.実験フォルダ内のファイルを指す関数(存在確認あり/なし/無ければ None)と,v3 の実機撮影(全灯・下・左・右)の一覧.見つからないときは `SMTIAS_LAB` の設定方法を添えたエラー,Lab の外を指すパスは拒否 +- `src/sm_tias_lightsim/evaluation/dng_pipeline.py` — DNG → linear 輝度(meta.json の LSC マップで補正・portrait・0〜255).SmTIAS-Evaluation `src/io/dng_pipeline.py` の `dng_luminance` と同じ処理(値が一致することを確認済み) +- `src/sm_tias_lightsim/evaluation/real_maps.py` — 実機の白板 ROI の輝度マップ(旧 `lightsim/luminance_maps/*.npy` の代わり).DNG から作り `output/_cache/real_maps/` に保存(DNG・meta より新しいときだけ再利用) - `src/sm_tias_lightsim/evaluation/radial.py` — 20 ビン放射状輝度プロファイル.既存 `calc_radial_profile` に加えて SmTIAS-Evaluation `src/analysis/spatial.py:calc_radial_min_max_ratio` をマージ.動径 min/max 比 (20 点輪帯平均) は画素単位 max/min よりノイズに対しロバスト.nan ビン除外を移植時に補強 (既存 `calc_radial_profile` は空ビンを nan で返す) - `src/sm_tias_lightsim/evaluation/fullimage.py` — 画像全体で評価するノイズ補正付き最小/最大比(`calc_fullimage_min_max_ratio`).σ=12 平滑化の min/max からノイズ場(残差の空間シャッフルを同じ平滑化)の極値を差し引く.動径 min/max 比が方位平均で非対称を見逃す問題(TEST_18)と,画素・パーセンタイルがノイズの裾を拾う問題の両方を避ける.`MetricsConfig.fullimage_min_max` / `fullimage_sigma` で有効化(既定 False).偏りとノイズ床の注意は SPEC_04 - `src/sm_tias_lightsim/evaluation/shape_metrics.py` — 輝度分布「形」評価指標モジュール(新規).現状 CoV/勾配/C/P/動径 min/max は不均一性の絶対量しか測れず,Y 軸単調勾配と中央ピーク楕円を構造的に区別できない問題を解決する 5 つの純関数: `calc_intensity_centroid`(輝度重心,5 値)/ `calc_angular_radial_decomposition`(極座標分解,angular_ratio が 0=同心円〜1=方向依存,3 値)/ `calc_ssim`(構造的類似度,scikit-image 依存,shape_reference 指定時のみ)/ `calc_ncc`(正規化相関係数,絶対輝度不変)/ `calc_intensity_pca`(weighted PCA で主軸角度と eccentricity,4 値).mask 省略可能,完全均一画像で angular_ratio/NCC は NaN を返す.`MetricsConfig.shape_metrics=true` / `shape_reference` フィールドで有効化,後方互換保持.依存追加: `scikit-image>=0.21.0`.詳細: [TECH_11 形状指標の見直し](docs/05_TECH/TECH_11_形状指標の見直しと新指標導入.md) diff --git a/configs/eval_baseline_dng_target.yaml b/configs/eval_baseline_dng_target.yaml index 6c52f26..1e80353 100644 --- a/configs/eval_baseline_dng_target.yaml +++ b/configs/eval_baseline_dng_target.yaml @@ -3,7 +3,7 @@ # # 実機側 (SmTIAS-Evaluation): DNG → LSC 順方向適用 → linear → 白板 ROI で評価 # mean=207.82, CoV=0.0695, 中心/周辺=1.0911, 勾配=8.35%, 動径 min/max=0.860 -# (`reference_measurement/quantitative/MiniTIAS_QM_20260601_124500.dng` 暗闇撮影, +# (SmTIAS-Lab `experiments/2026-06-01_v3_all_leds/raw/SmTIAS_QM_20260601_124500.dng` 暗闇撮影, # 詳細は docs/06_TEST/TEST_05_PNG_DNG評価比較.md と TEST_06_外乱光影響評価.md) # # シミュ側 (本設定): @@ -42,4 +42,4 @@ normalization: enabled: true type: mean_anchor - target_mean: 207.82 # 実機 DNG+LSC の白板 ROI mean (reference_measurement/quantitative/expected_results/MiniTIAS_QM_20260601_124500_uniformity.csv より) + target_mean: 207.82 # 実機 DNG+LSC の白板 ROI mean (SmTIAS-Lab experiments/2026-06-01_v3_all_leds/results/SmTIAS_QM_20260601_124500_uniformity.csv より) diff --git a/configs/eval_baseline_dng_target_shape.yaml b/configs/eval_baseline_dng_target_shape.yaml index e35cbdc..2b0af79 100644 --- a/configs/eval_baseline_dng_target_shape.yaml +++ b/configs/eval_baseline_dng_target_shape.yaml @@ -15,7 +15,10 @@ # - metrics.shape_reference: null(実機 DNG 由来参照画像は別途用意後に指定) # # SSIM / NCC を有効化するには shape_reference に参照画像パスを指定すること: -# 例: shape_reference: reference_measurement/quantitative/expected_results/MiniTIAS_QM_20260601_124500_luminance_map.npy +# 例: shape_reference: ../output/real_full_sim_roi.npy(パスは本 YAML のディレクトリ基準) +# 実機全灯の白板 ROI 輝度マップは SmTIAS-Lab の DNG から +# sm_tias_lightsim.evaluation.real_maps.real_roi_luminance("full") で作れる(1409×1400). +# シミュ ROI(450×464)と大きさが違うので,resize してから npy に保存して指定する. # 参照画像は ROI 抽出後の輝度 npy(同じ ROI サイズであること)を期待する. # 形状 (H, W) が ROI と異なる場合は SSIM/NCC を自動スキップして NaN を格納する. # diff --git a/configs/white_board_bbox.json b/configs/white_board_bbox.json index de3fcf9..c11fcdd 100644 --- a/configs/white_board_bbox.json +++ b/configs/white_board_bbox.json @@ -1,5 +1,5 @@ { - "image": "reference_measurement\\MiniTIAS_20260408_144434\\MiniTIAS_20260408_144434.png", + "image": "../SmTIAS-Lab/experiments/2026-04-08_v3_png/raw/SmTIAS_20260408_144434.png", "x": 473, "y": 916, "width": 1530, diff --git "a/docs/02_ENV/ENV_02_\347\222\260\345\242\203\346\247\213\347\257\211\346\211\213\351\240\206.md" "b/docs/02_ENV/ENV_02_\347\222\260\345\242\203\346\247\213\347\257\211\346\211\213\351\240\206.md" index 3da78e8..2ad183b 100644 --- "a/docs/02_ENV/ENV_02_\347\222\260\345\242\203\346\247\213\347\257\211\346\211\213\351\240\206.md" +++ "b/docs/02_ENV/ENV_02_\347\222\260\345\242\203\346\247\213\347\257\211\346\211\213\351\240\206.md" @@ -70,6 +70,14 @@ uv run ruff --version # Lint / Format 用 ``` +### 6. 実験データ(SmTIAS-Lab)を置く + +実機の撮影データ(DNG・meta.json・PNG)は隣のリポジトリ [SmTIAS-Lab](https://github.com/rintoHasegawa/SmTIAS-Lab) の `experiments/_<内容>/raw/` に置く(git の対象外).実機と比べるスクリプトとテストは `src/sm_tias_lightsim/lab.py` を通して Lab を読む. + +- 既定の場所: 本リポジトリの隣の `SmTIAS-Lab`(`../SmTIAS-Lab`) +- 別の場所に置くときは環境変数 `SMTIAS_LAB` に Lab のルートを設定する +- `raw/` は git の対象外なので,clone した後に撮影データを手元の Lab からコピーする.無ければ実機の DNG を使うテストはスキップされ,スクリプトは設定方法を含むエラーで止まる + ## よくある操作 (Common Tasks) | やりたいこと | コマンド | @@ -250,7 +258,8 @@ - 送り先: `Newton:~/lab/SmTIAS-LightSim`(`--host` / `--remote-dir`,または環境変数 `SM_REMOTE_HOST` / `SM_REMOTE_DIR` で変更可) - 送らないもの: `.venv/`(Windows 用)・`output/`・`.git/`・`__pycache__/`・`.pytest_cache/`・`.ruff_cache/`・`configs/_tmp_*`(スイープ生成物.約 450 MB.必要なら `--include` / `--only` で個別に送る) -- gitignore 対象でも送るもの: `lightsim/`・`reference_measurement/`・`REFERENCE/`(実測参照データ.サーバでの評価に使う) +- gitignore 対象でも,除外規則に当たらなければ送る(`REFERENCE/` 等).実測データの旧置き場 `lightsim/`・`reference_measurement/` は廃止した +- 撮影データ(隣のリポジトリ SmTIAS-Lab)はサーバへ送らない.実機の DNG を読むスクリプト(`scripts/compare_real_vs_sim_*.py`・`scripts/build_*_panel.py` 等)は手元で実行する - 全体で約 160 MB.初回(2026-09-13,tar + ssh の手動転送)は LAN で 39 秒,以後の `sm-remote push` は 10 秒前後だった.日本語ファイル名(`configs/meshes/*.stl`)もそのまま展開される ### 依存の同期 (uv sync) diff --git "a/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" "b/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" index 810b6b7..238af7f 100644 --- "a/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" +++ "b/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" @@ -72,6 +72,18 @@ - `--search` の指標(画像全体の min/max のノイズ補正)は 1 通り約 1.5 秒かかるので,手元ではなくサーバの CPU で並列に回す - 基底画像の出力は 124 か所で 250 MB 前後(figures の PNG を含む).`sm-remote pull` が時間切れになるときは,PNG を除いて ssh の tar で受け取る(`ssh Newton "cd ~/lab/SmTIAS-LightSim/output/led_mounts_v4 && tar cf - --exclude='*.png' ." | tar xf - -C output/led_mounts_v4`) +## 実機のデータ (Real Measurements) + +実機の撮影データは SmTIAS-Lab から読む(場所は環境変数 `SMTIAS_LAB`.下記「環境変数」).現行機(v3)の全灯・単灯 3 種の白板 ROI 輝度マップは DNG から作る(`evaluation/real_maps.py:real_roi_luminance`.初回は 1 枚数秒,結果は `output/_cache/real_maps/` に保存され以後はそこから読む). + +```bash +uv run python -c "from sm_tias_lightsim.evaluation.real_maps import real_roi_luminance as f; a = f('full'); print(a.shape, a.mean())" # (1409, 1400) 207.82 +uv run python scripts/compare_real_vs_sim_shapes.py # 実機(全灯・単灯 3 種)とシミュの形の比較 +``` + +- 撮影の対応(キー → Lab の実験フォルダ)は `src/sm_tias_lightsim/lab.py` の `V3_SHOTS` +- Lab のデータはサーバへ送らないので,実機の DNG を読むスクリプトは手元で実行する + ## テスト (Tests) テスト方針の詳細は `.claude/rules/testing.md` を参照. @@ -183,4 +195,5 @@ - `SM_RENDER_VARIANT` — sm-render が使う Mitsuba variant を YAML の `render.variant` より優先して上書きする(`sm-render --variant` がさらに優先).スイープスクリプトは sm-render をサブプロセスで呼ぶので,環境変数にしておけば配下のレンダすべてに効く.`sm-remote run` が既定で `cuda_ad_rgb` を設定する. - `SM_DRJIT_THREADS` — Dr.Jit の CPU スレッド数の上限(未設定なら全論理コア).`render/runner.py`・`visualize/baker.py` が起動時に `dr.set_thread_count` で適用する.`sm-remote run --threads` で設定する.1 以上の整数以外(`0`・負数・整数でない文字列)はエラーになる(sm-render は終了コード 1.黙って全コアで回すことはしない). - `SM_REMOTE_HOST` / `SM_REMOTE_DIR` / `SM_REMOTE_UV` / `SM_REMOTE_SSH` / `SM_REMOTE_VARIANT` — `sm-remote` の既定値の上書き.それぞれ接続先ホスト(既定 `Newton`)・サーバ上のプロジェクトルート(既定 `~/lab/SmTIAS-LightSim`)・サーバ上の uv(既定 `~/.local/bin/uv`)・手元の ssh(Windows の既定は `C:\Windows\System32\OpenSSH\ssh.exe`)・`run` が渡す variant(既定 `cuda_ad_rgb`). +- `SMTIAS_LAB` — 実験データのリポジトリ SmTIAS-Lab のルート(未設定なら本リポジトリの隣の `../SmTIAS-Lab`).`src/sm_tias_lightsim/lab.py` が使う.見つからないと `FileNotFoundError`(設定方法をメッセージに含む). - `SM_REMOTE_ALLOW_SELF` — `1` にすると,`sm-remote` の「サーバ上で実行されている」検出を無効にする(誤検出したときの逃げ道). diff --git "a/docs/04_SPEC/SPEC_04_\350\251\225\344\276\241\344\273\225\346\247\230.md" "b/docs/04_SPEC/SPEC_04_\350\251\225\344\276\241\344\273\225\346\247\230.md" index 9a7155f..3e8fb80 100644 --- "a/docs/04_SPEC/SPEC_04_\350\251\225\344\276\241\344\273\225\346\247\230.md" +++ "b/docs/04_SPEC/SPEC_04_\350\251\225\344\276\241\344\273\225\346\247\230.md" @@ -11,7 +11,7 @@ ## 概要 (Overview) -シミュレーション結果(`output//luminance.npy` または `render_uint8.png`)と実測 PNG (`reference_measurement/.../*.png`) を **同一の評価パイプライン**に通し,無次元の均一性指標(CoV,勾配 %,中心/周辺比 等)を算出する.シミュと実測を比較可能にする鍵は **OETF 順方向適用** で,シミュの linear ドメインを実機の sRGB 符号化ドメインに揃える操作である(後述). +シミュレーション結果(`output//luminance.npy` または `render_uint8.png`)と実測(SmTIAS-Lab の `experiments/<日付>_<内容>/raw/` の PNG・DNG.読み方は `src/sm_tias_lightsim/lab.py`)を **同一の評価パイプライン**に通し,無次元の均一性指標(CoV,勾配 %,中心/周辺比 等)を算出する.シミュと実測を比較可能にする鍵は **OETF 順方向適用** で,シミュの linear ドメインを実機の sRGB 符号化ドメインに揃える操作である(後述). 設計目的は SmTIAS-Evaluation との **数値整合性**(実測 PNG に対し小数点 14 桁レベルで一致確認済み,[TEST_01](../06_TEST/TEST_01_キャリブレーション検証履歴.md) 既知差分 #9)と,シミュ⇄実測の **公平な比較**. @@ -86,7 +86,7 @@ | ROI 名 | 用途 | x, y, w, h | | --- | --- | --- | | `configs/eval_baseline.yaml` | シミュ 512×512 | 24, 37, 464, 450 | -| `configs/eval_real.yaml` | 実機 1500×1500 ベース | reference_measurement の `roi_config.json` 参照 | +| `configs/eval_real.yaml` | 実機 1500×1500 ベース | 539, 1015, 1400, 1409(SmTIAS-Lab `experiments/2026-04-08_v3_png/results/roi_config.json` 由来.`roi_presets.REAL_ROI`) | シミュ ROI と実機 ROI は **物理対応済み**(評価板の同じ XY 領域).シミュの orthographic センサと実機カメラの向き変換は [SPEC_03 画像 ↔ 物理 の向き](SPEC_03_基準設計の物理構成.md#画像--物理-の向き検証済み) を参照. @@ -317,10 +317,10 @@ ```yaml metrics: shape_metrics: true - shape_reference: ../reference_measurement/quantitative/expected_results/MiniTIAS_QM_20260601_124500_luminance_map.npy # 任意 + shape_reference: ../output/real_full_sim_roi.npy # 任意.実機全灯の ROI 輝度マップをシミュ ROI の大きさにしたもの ``` -`shape_reference` 相対パスは config YAML のディレクトリ基準で解決.未指定(null)なら SSIM/NCC は NaN になり他の指標は計算される. +`shape_reference` 相対パスは config YAML のディレクトリ基準で解決.実機の白板 ROI 輝度マップは SmTIAS-Lab の DNG から `evaluation/real_maps.py:real_roi_luminance("full")` で作れる(1409×1400.シミュ ROI と大きさが違うので resize して保存する).未指定(null)なら SSIM/NCC は NaN になり他の指標は計算される. #### 注意 diff --git "a/docs/05_TECH/TECH_11_\345\275\242\347\212\266\346\214\207\346\250\231\343\201\256\350\246\213\347\233\264\343\201\227\343\201\250\346\226\260\346\214\207\346\250\231\345\260\216\345\205\245.md" "b/docs/05_TECH/TECH_11_\345\275\242\347\212\266\346\214\207\346\250\231\343\201\256\350\246\213\347\233\264\343\201\227\343\201\250\346\226\260\346\214\207\346\250\231\345\260\216\345\205\245.md" index c226e4c..d2e4b26 100644 --- "a/docs/05_TECH/TECH_11_\345\275\242\347\212\266\346\214\207\346\250\231\343\201\256\350\246\213\347\233\264\343\201\227\343\201\250\346\226\260\346\214\207\346\250\231\345\260\216\345\205\245.md" +++ "b/docs/05_TECH/TECH_11_\345\275\242\347\212\266\346\214\207\346\250\231\343\201\256\350\246\213\347\233\264\343\201\227\343\201\250\346\226\260\346\214\207\346\250\231\345\260\216\345\205\245.md" @@ -223,11 +223,11 @@ ```yaml metrics: shape_metrics: true - shape_reference: reference_measurement/quantitative/expected_results/MiniTIAS_QM_20260601_124500_luminance_map.npy + shape_reference: ../output/real_full_sim_roi.npy ``` 参照画像は ROI 抽出後の輝度マップ(`luminance.npy` と同じ ROI サイズの 2D float64 配列)を期待する. -実機 DNG からの輝度マップ生成は SmTIAS-Evaluation で行い,`reference_measurement/quantitative/expected_results/` に配置する(gitignore 対象外として管理すること). +実機 DNG からの輝度マップは SmTIAS-Lab の DNG から `evaluation/real_maps.py:real_roi_luminance` で作る(Evaluation の `dng_luminance` と同じ処理.結果は `output/_cache/real_maps/` に保存される).シミュ ROI と大きさが違うので,resize してから npy に保存して指定する. ### 後方互換 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index b60d24e..6c1fa8b 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -172,3 +172,6 @@ - 失敗パターン(Fusion): ① 古い台座のフィーチャを消すと,そのあとの前側のフィーチャ(配線の切れ込み・鼻当て)の計算が壊れた → 配線と鼻当てを消してから LED モジュール → 配線 → 鼻当ての順に作り直す / ② 和を取った一時ボディは名前が付かず台座を集められなかった → ベースフィーチャのボディから集める. - [x] **LED 基板 v3: 違う線どうしの銅の間を広げた (2026-11-10)**: 溝が細いとはんだがはみ出して基板が使えなくなるので,削る時間が長くなってもよいから銅の間を広げたい(ユーザー).間隔を全部測る台本で洗い出し,電源の線を縁へ寄せ,LED のパッドの間を 0.55 → 0.85 mm にし,LED の間の線を真ん中に通した(一番狭い所 0.50 → 0.70 mm.LED の位置は同じ).Fusion に `*_v3` として取り込み,ガーバーを作り直した.研究室ではパターン以外の銅をハッチングではがす(SPEC_05). - 失敗パターン: Fusion を起動し直した直後(ドキュメントが開いていない)に取り込むと Fusion が落ちた → 何か開いてから取り込む(TECH_12). +- [x] **実機のデータを SmTIAS-Lab から読むようにした (2026-11-12)**: 撮影データと実験の記録を新しく作った SmTIAS-Lab(`../SmTIAS-Lab`,環境変数 `SMTIAS_LAB`)にまとめたので,スクリプト・テストが読む実機の DNG・PNG を Lab に切り替えた.旧置き場の `lightsim/`(Evaluation から単灯データを渡したときの残り)は削除,`reference_measurement/` も Lab と中身が一致するので消せる状態.単灯・全灯の輝度マップ .npy は DNG から作ってキャッシュする. + - 設計判断(ユーザー判断): Lab のデータは `sm-remote push` でサーバへ送らない.実機の DNG を読むスクリプトは手元で実行する. + - 未実装・後段: Evaluation 側も同じく Lab から読むように直す(Evaluation のフォルダで行う).そのあと Evaluation の `data/` を消す. diff --git a/scripts/build_blend_bottom_panel.py b/scripts/build_blend_bottom_panel.py index a89231e..c3cdc1a 100644 --- a/scripts/build_blend_bottom_panel.py +++ b/scripts/build_blend_bottom_panel.py @@ -21,7 +21,8 @@ 前提: - output/blend_bottom/ に対象ジョブの luminance.npy が存在すること - area diffuse 基準(bottom: output/depth_bottom/d16,left/right: output/sanity_fix_1024/) - - lightsim/luminance_maps/{side}_*.npy(実機単灯実測,ROI 適用済み)が存在すること + - SmTIAS-Lab に実機単灯の DNG(experiments/2026-06-15_v3_single_led/raw/)があること + (ROI 輝度マップは evaluation/real_maps が DNG から作り output/_cache/ に保存する) """ from __future__ import annotations @@ -36,6 +37,7 @@ import numpy as np from skimage.transform import resize +from sm_tias_lightsim.evaluation.real_maps import real_roi_luminance from sm_tias_lightsim.evaluation.roi_presets import SIM_ROI, extract_roi_xywh from sm_tias_lightsim.evaluation.shape_metrics import calc_ncc @@ -50,7 +52,6 @@ SWEEP_BASE = ROOT / "output" / "blend_bottom" PANEL_DIR = ROOT / "output" / "_slide_panels" -REAL_DIR = ROOT / "lightsim" / "luminance_maps" # 灯ごとの設定(configs/_tmp_blend_bottom/ のジョブ命名・グリッドと整合) # baseline: area diffuse(純 Lambertian)の同条件出力. @@ -59,21 +60,21 @@ SIDES: dict[str, dict] = { "bottom": { "baseline": ROOT / "output" / "depth_bottom" / "d16" / "luminance.npy", - "real": REAL_DIR / "bottom_SmTIAS_QM_20260615_141420.npy", + "real": "bottom", # lab.V3_SHOTS のキー(実機単灯 DNG) "job_prefix": "", "weights": [0.05, 0.15, 0.3, 0.6], "alphas": [0.1, 0.3, 0.6], }, "left": { "baseline": ROOT / "output" / "sanity_fix_1024" / "left" / "luminance.npy", - "real": REAL_DIR / "left_SmTIAS_QM_20260615_150300.npy", + "real": "left", # lab.V3_SHOTS のキー(実機単灯 DNG) "job_prefix": "left_", "weights": [0.05, 0.3, 0.6], "alphas": [0.1, 0.6], }, "right": { "baseline": ROOT / "output" / "sanity_fix_1024" / "right" / "luminance.npy", - "real": REAL_DIR / "right_SmTIAS_QM_20260615_170948.npy", + "real": "right", # lab.V3_SHOTS のキー(実機単灯 DNG) "job_prefix": "right_", "weights": [0.05, 0.3, 0.6], "alphas": [0.1, 0.6], @@ -251,11 +252,11 @@ cfg = SIDES[side] weights, alphas, prefix = cfg["weights"], cfg["alphas"], cfg["job_prefix"] - real_npy: Path = cfg["real"] - if not real_npy.exists(): - print(f"エラー: 実機 npy が見つかりません: {real_npy}", file=sys.stderr) + try: + real = real_roi_luminance(cfg["real"]).astype(np.float64) + except FileNotFoundError as exc: + print(f"エラー: 実機の DNG が読めません: {exc}", file=sys.stderr) return 1 - real = np.load(real_npy).astype(np.float64) real_metrics = { "peak_mean": float(real.max() / real.mean()), "top_bot": float(real[: real.shape[0] // 2].mean() / real[real.shape[0] // 2 :].mean()), diff --git a/scripts/build_bsdf_grid_panel.py b/scripts/build_bsdf_grid_panel.py index 5f00638..5ffc826 100644 --- a/scripts/build_bsdf_grid_panel.py +++ b/scripts/build_bsdf_grid_panel.py @@ -29,6 +29,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) +from sm_tias_lightsim.evaluation.real_maps import real_roi_luminance # noqa: E402 from sm_tias_lightsim.evaluation.roi_presets import SIM_ROI, extract_roi_xywh # noqa: E402 matplotlib.rcParams["font.family"] = ["Meiryo", "Yu Gothic", "DejaVu Sans"] @@ -37,7 +38,6 @@ SUMMARY_CSV = ROOT / "output" / "bsdf_grid_fix" / "summary.csv" OUTPUT_BASE = ROOT / "output" / "bsdf_grid_fix" REFERENCE_DIR = ROOT / "output" / "full_base_fix" -REAL_FULL = ROOT / "lightsim" / "luminance_maps" / "full_MiniTIAS_QM_20260601_124500.npy" PANEL_DIR = ROOT / "output" / "_slide_panels" # 実機(全灯)の指標: sweep_bsdf_grid_fix.py と同じ出典 @@ -126,7 +126,7 @@ def plot_top_shapes(rows: list[dict[str, float]], top: int) -> Path: """スコア上位 top 条件と実機の輝度マップを並べる.""" best = sorted(rows, key=lambda r: r["score"])[:top] - real = _smooth(np.load(REAL_FULL), False) + real = _smooth(real_roi_luminance("full"), False) # 実機全灯(SmTIAS-Lab の DNG) cells = [(f"{r['job']}\nscore={r['score']:.4f} CoV={r['cov']:.4f} " f"NCC={r['ncc_smooth']:.3f}", _smooth(np.load(_job_luminance(r["job"])), True)) for r in best] diff --git a/scripts/build_bsdf_grid_visual.py b/scripts/build_bsdf_grid_visual.py index 45a2252..9ae0879 100644 --- a/scripts/build_bsdf_grid_visual.py +++ b/scripts/build_bsdf_grid_visual.py @@ -33,6 +33,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) +from sm_tias_lightsim.evaluation.real_maps import real_roi_luminance # noqa: E402 from sm_tias_lightsim.evaluation.roi_presets import SIM_ROI, extract_roi_xywh # noqa: E402 matplotlib.rcParams["font.family"] = ["Meiryo", "Yu Gothic", "DejaVu Sans"] @@ -41,7 +42,6 @@ SUMMARY_CSV = ROOT / "output" / "bsdf_grid_fix" / "summary.csv" OUTPUT_BASE = ROOT / "output" / "bsdf_grid_fix" REFERENCE_DIR = ROOT / "output" / "full_base_fix" -REAL_FULL = ROOT / "lightsim" / "luminance_maps" / "full_MiniTIAS_QM_20260601_124500.npy" PANEL_DIR = ROOT / "output" / "_slide_panels" RESIDUAL_LIMIT = 12.0 # 残差カラーバーの上下限 [%] @@ -83,7 +83,7 @@ def _real_map(shape: tuple[int, int]) -> np.ndarray: """実機マップを指定 shape に合わせ mean 正規化して返す.""" - real = _smooth(np.load(REAL_FULL), False) + real = _smooth(real_roi_luminance("full"), False) # 実機全灯(SmTIAS-Lab の DNG) real = resize(real, shape, anti_aliasing=True) return real / real.mean() diff --git a/scripts/build_full_vs_singles_panel.py b/scripts/build_full_vs_singles_panel.py index 7985bde..2018c74 100644 --- a/scripts/build_full_vs_singles_panel.py +++ b/scripts/build_full_vs_singles_panel.py @@ -14,7 +14,8 @@ 前提: - output/full_base_fix/luminance.npy・output/singles_fix/{bottom,left,right}/luminance.npy - - lightsim/luminance_maps/{full,bottom,left,right}_*.npy(実機) + - SmTIAS-Lab に実機(全灯・単灯 3 種)の DNG があること(lab.V3_SHOTS. + ROI 輝度マップは evaluation/real_maps が作り output/_cache/ に保存する) """ from __future__ import annotations @@ -28,6 +29,7 @@ from scipy.ndimage import gaussian_filter, median_filter from skimage.transform import resize +from sm_tias_lightsim.evaluation.real_maps import real_roi_luminance from sm_tias_lightsim.evaluation.roi_presets import SIM_ROI, extract_roi_xywh from sm_tias_lightsim.evaluation.shape_metrics import calc_ncc @@ -49,19 +51,13 @@ "left": ROOT / "output" / "singles_fix" / "left" / "luminance.npy", "right": ROOT / "output" / "singles_fix" / "right" / "luminance.npy", } -REAL = { - "full": ROOT / "lightsim" / "luminance_maps" / "full_MiniTIAS_QM_20260601_124500.npy", - "bottom": ROOT / "lightsim" / "luminance_maps" / "bottom_SmTIAS_QM_20260615_141420.npy", - "left": ROOT / "lightsim" / "luminance_maps" / "left_SmTIAS_QM_20260615_150300.npy", - "right": ROOT / "lightsim" / "luminance_maps" / "right_SmTIAS_QM_20260615_170948.npy", -} CELL_SHAPE = (450, 464) -def _load_smooth(path: Path, is_sim: bool) -> np.ndarray: - """luminance を読み込み(シミュは SIM_ROI 抽出後)平滑化して返す.""" - arr = np.load(path) +def _load_smooth(path: Path | np.ndarray, is_sim: bool) -> np.ndarray: + """luminance を読み込み(シミュは SIM_ROI 抽出後)平滑化して返す(配列も受け付ける).""" + arr = np.load(path) if isinstance(path, Path) else path if arr.ndim == 3: arr = 0.2126 * arr[..., 0] + 0.7152 * arr[..., 1] + 0.0722 * arr[..., 2] arr = arr.astype(np.float64) @@ -76,14 +72,18 @@ Returns: 終了コード(成功なら 0,入力不足なら 1). """ - for paths in (SIM, REAL): - for p in paths.values(): - if not p.exists(): - print(f"エラー: {p} が見つかりません", file=sys.stderr) - return 1 + for p in SIM.values(): + if not p.exists(): + print(f"エラー: {p} が見つかりません", file=sys.stderr) + return 1 sim = {c: _load_smooth(SIM[c], True) for c in COLS} - real = {c: _load_smooth(REAL[c], False) for c in COLS} + try: + # 実機(SmTIAS-Lab の DNG から作る白板 ROI.lab.V3_SHOTS のキー = COLS) + real = {c: _load_smooth(real_roi_luminance(c), False) for c in COLS} + except FileNotFoundError as exc: + print(f"エラー: 実機の DNG が読めません: {exc}", file=sys.stderr) + return 1 fig, axes = plt.subplots(2, 4, figsize=(4 * 4.2, 2 * 4.4), constrained_layout=True) for r, (row_label, maps) in enumerate((("シミュ(面法線修正後)", sim), ("実機", real))): diff --git a/scripts/build_loft_w1p4_panel.py b/scripts/build_loft_w1p4_panel.py index f36d3fb..2e6ee86 100644 --- a/scripts/build_loft_w1p4_panel.py +++ b/scripts/build_loft_w1p4_panel.py @@ -16,9 +16,9 @@ 前提: - output/loft_w1p4/{bottom,left,right,full,full_base}/luminance.npy が存在すること - 元メッシュ単灯基準 output/blend_bottom/{,left_,right_}w0.05_a0.1/luminance.npy - - 実機マップ lightsim/luminance_maps/{side}_*.npy(単灯 3 種 + full.full は - reference_measurement/quantitative/MiniTIAS_QM_20260601_124500.dng から - 単灯と同一手順(linear raw + LSC 順適用 + Rec.709 + REAL_ROI)で生成したもの) + - SmTIAS-Lab に実機(単灯 3 種 + 全灯)の DNG があること(lab.V3_SHOTS. + evaluation/real_maps が linear raw + LSC 順適用 + Rec.709 + REAL_ROI で ROI 輝度マップを + 作り output/_cache/ に保存する) """ from __future__ import annotations @@ -32,6 +32,7 @@ import numpy as np from skimage.transform import resize +from sm_tias_lightsim.evaluation.real_maps import real_roi_luminance from sm_tias_lightsim.evaluation.roi_presets import SIM_ROI, extract_roi_xywh from sm_tias_lightsim.evaluation.shape_metrics import calc_ncc @@ -41,12 +42,8 @@ PANEL_PATH = ROOT / "output" / "_slide_panels" / "loft_w1p4_shape_roi.png" SUMMARY_CSV = ROOT / "output" / "loft_w1p4" / "summary.csv" -REAL = { - "bottom": ROOT / "lightsim" / "luminance_maps" / "bottom_SmTIAS_QM_20260615_141420.npy", - "left": ROOT / "lightsim" / "luminance_maps" / "left_SmTIAS_QM_20260615_150300.npy", - "right": ROOT / "lightsim" / "luminance_maps" / "right_SmTIAS_QM_20260615_170948.npy", - "full": ROOT / "lightsim" / "luminance_maps" / "full_MiniTIAS_QM_20260601_124500.npy", -} +# 実機マップ(lab.V3_SHOTS のキー.SmTIAS-Lab の DNG から evaluation/real_maps が作る) +REAL = ("bottom", "left", "right", "full") BASE = { "bottom": ROOT / "output" / "blend_bottom" / "w0.05_a0.1" / "luminance.npy", "left": ROOT / "output" / "blend_bottom" / "left_w0.05_a0.1" / "luminance.npy", @@ -82,6 +79,11 @@ return arr.astype(np.float64) +def _load_real(side: str) -> np.ndarray: + """実機の白板 ROI 輝度マップ(SmTIAS-Lab の DNG から作る.2 回目以降はキャッシュ).""" + return real_roi_luminance(side).astype(np.float64) + + def _metrics(img: np.ndarray, real: np.ndarray | None) -> dict[str, float]: """TEST_09/10 の形指標(peak/mean・top/bot・NCC 対実機)を算出する.""" h = img.shape[0] @@ -105,7 +107,7 @@ cells: dict[tuple[str, str], np.ndarray] = {} rows: list[list[str]] = [] for side in SIDES: - real = _load_luminance(REAL[side]) if side in REAL else None + real = _load_real(side) if side in REAL else None for ver in ["base", "w1p4"]: if ver == "base": path = BASE[side] @@ -126,7 +128,7 @@ rows.append([side, "real", f"{rm['peak_mean']:.4f}", f"{rm['top_bot']:.4f}", "1.0000"]) # 全灯ロフト重みスイープ(w2p0/w4p0 は 4×3 パネル外のため summary にのみ追記) - real_full = _load_luminance(REAL["full"]) + real_full = _load_real("full") sweep_cells: list[tuple[str, np.ndarray, dict[str, float]]] = [] for label, job_dir in FULL_SWEEP: npy = job_dir / "luminance.npy" diff --git a/scripts/build_luminance_evolution_panel.py b/scripts/build_luminance_evolution_panel.py index 689a0c4..539c49c 100644 --- a/scripts/build_luminance_evolution_panel.py +++ b/scripts/build_luminance_evolution_panel.py @@ -33,6 +33,7 @@ from sm_tias_lightsim.evaluation.normalize import apply_mean_anchor from sm_tias_lightsim.evaluation.oetf import apply_srgb_oetf, solve_exposure from sm_tias_lightsim.evaluation.roi_presets import REAL_ROI, SIM_ROI, extract_roi_xywh +from sm_tias_lightsim.lab import V3_PNG_WHITEBOARD, lab_file ROOT = Path(__file__).resolve().parents[1] TARGET_MEAN = 146.7146 @@ -50,9 +51,7 @@ def _load_real() -> np.ndarray: """実機 PNG → Rec.709 luma → ROI 抽出 → mean アンカー(恒等近い).""" - png = ( - ROOT / "reference_measurement" / "MiniTIAS_20260408_144434" / "MiniTIAS_20260408_144434.png" - ) + png = lab_file(*V3_PNG_WHITEBOARD) # SmTIAS-Lab の通常モード PNG img = np.array(Image.open(png)) if img.ndim == 3: img = img[..., :3] # 念のため RGBA → RGB diff --git a/scripts/build_sim_vs_darkroom_panel.py b/scripts/build_sim_vs_darkroom_panel.py index 1a729df..2794d7e 100644 --- a/scripts/build_sim_vs_darkroom_panel.py +++ b/scripts/build_sim_vs_darkroom_panel.py @@ -19,6 +19,7 @@ → Rec.709 luma × 255 → rot90(-1) で portrait 向き合わせ → 白板 ROI 抽出 これは reference_scripts/run_uniformity_dng.py と同一 (mean=207.82 を再現). +DNG は SmTIAS-Lab から読む (sm_tias_lightsim.lab.処理は evaluation/dng_pipeline). シミュ側は output/baseline/luminance.npy を SIM_ROI で抽出. @@ -35,13 +36,12 @@ from __future__ import annotations -import json from pathlib import Path import matplotlib.pyplot as plt import numpy as np -from sm_tias_lightsim.evaluation.dng_loader import load_image_dng +from sm_tias_lightsim.evaluation.dng_pipeline import dng_luminance from sm_tias_lightsim.evaluation.radial import ( calc_radial_min_max_ratio, calc_radial_profile, @@ -52,17 +52,14 @@ classify_zones, compute_normalized_distance_map, ) +from sm_tias_lightsim.lab import V3_SHOTS, shot_dng ROOT = Path(__file__).resolve().parents[1] # Rec.709 luma 係数 (uniformity.py / dng_loader.py と一致) _REC709 = (0.2126, 0.7152, 0.0722) -# 実機 暗室 DNG (Step 8-13 以降の正規 baseline) -REAL_DNG = ROOT / "reference_measurement" / "quantitative" / "MiniTIAS_QM_20260601_124500.dng" -REAL_META = ( - ROOT / "reference_measurement" / "quantitative" / "MiniTIAS_QM_20260601_124500.meta.json" -) +# 実機 暗室 DNG (Step 8-13 以降の正規 baseline) は lab.V3_SHOTS["full"](SmTIAS-Lab). # REAL_ROI(白板 portrait)/ SIM_ROI は roi_presets に集約(configs と整合). # シミュ baseline (max_depth=16, R=0.85, spp=1024) @@ -76,41 +73,9 @@ return _REC709[0] * rgb[..., 0] + _REC709[1] * rgb[..., 1] + _REC709[2] * rgb[..., 2] -def _upsample(grid: np.ndarray, shape: tuple[int, int]) -> np.ndarray: - """(rows, cols) グリッドを (H, W) へバイリニア補間する (run_uniformity_dng.py と同一).""" - rows, cols = grid.shape - h, w = shape - ys = np.linspace(0, rows - 1, h) - xs = np.linspace(0, cols - 1, w) - y0 = np.floor(ys).astype(int) - y1 = np.minimum(y0 + 1, rows - 1) - x0 = np.floor(xs).astype(int) - x1 = np.minimum(x0 + 1, cols - 1) - wy = (ys - y0)[:, None] - wx = (xs - x0)[None, :] - top = grid[y0][:, x0] * (1 - wx) + grid[y0][:, x1] * wx - bot = grid[y1][:, x0] * (1 - wx) + grid[y1][:, x1] * wx - return top * (1 - wy) + bot * wy - - -def _lsc_gain_rgb(meta_path: Path, shape: tuple[int, int]) -> np.ndarray: - """meta.json lscMap (rows, cols, 4=[R,Geven,Godd,B]) → (H, W, 3) RGB ゲイン.""" - meta = json.loads(meta_path.read_text(encoding="utf-8")) - rows, cols = meta["lscMapRowCount"], meta["lscMapColumnCount"] - m = np.array(meta["lscMap"], dtype=np.float64).reshape(rows, cols, 4) - gr = _upsample(m[:, :, 0], shape) - gg = _upsample((m[:, :, 1] + m[:, :, 2]) / 2.0, shape) - gb = _upsample(m[:, :, 3], shape) - return np.stack([gr, gg, gb], axis=2) - - def _load_real_darkroom() -> np.ndarray: - """暗室 DNG → linear raw → LSC 順適用 → Rec.709×255 → portrait → 白板 ROI (物理値).""" - rgb = load_image_dng(str(REAL_DNG), output_format="rgb_float32") # linear landscape - rgb = rgb * _lsc_gain_rgb(REAL_META, rgb.shape[:2]) # LSC 順方向適用 (ビネット除去) - luma = _rec709_luma(rgb) * 255.0 # 0〜255 linear スケール - luma = np.rot90(luma, -1) # portrait (PNG / ROI と同じ向き) - return extract_roi_xywh(luma, REAL_ROI) + """暗室 DNG(SmTIAS-Lab)→ linear raw → LSC 順適用 → Rec.709×255 → portrait → 白板 ROI.""" + return extract_roi_xywh(dng_luminance(shot_dng(V3_SHOTS["full"])), REAL_ROI) def _load_sim() -> np.ndarray: diff --git a/scripts/build_singles_fix_summary.py b/scripts/build_singles_fix_summary.py index 8c1f5a5..5c3913a 100644 --- a/scripts/build_singles_fix_summary.py +++ b/scripts/build_singles_fix_summary.py @@ -18,7 +18,7 @@ 前提: - output/singles_fix/{bottom,left,right}{,_w1p4}/luminance.npy(面法線修正後) - output/blend_bottom/{,left_,right_}w0.05_a0.1/luminance.npy(修正前,対比用) - - lightsim/luminance_maps/{bottom,left,right}_*.npy(実機単灯) + - SmTIAS-Lab に実機単灯の DNG(experiments/2026-06-15_v3_single_led/raw/)があること """ from __future__ import annotations @@ -33,6 +33,7 @@ import numpy as np from skimage.transform import resize +from sm_tias_lightsim.evaluation.real_maps import real_roi_luminance from sm_tias_lightsim.evaluation.roi_presets import SIM_ROI, extract_roi_xywh from sm_tias_lightsim.evaluation.shape_metrics import calc_ncc @@ -44,11 +45,6 @@ PANEL_PATH = ROOT / "output" / "_slide_panels" / "singles_fix_shape_roi.png" SIDES = ["bottom", "left", "right"] -REAL = { - "bottom": ROOT / "lightsim" / "luminance_maps" / "bottom_SmTIAS_QM_20260615_141420.npy", - "left": ROOT / "lightsim" / "luminance_maps" / "left_SmTIAS_QM_20260615_150300.npy", - "right": ROOT / "lightsim" / "luminance_maps" / "right_SmTIAS_QM_20260615_170948.npy", -} OLD_BASE = { "bottom": ROOT / "output" / "blend_bottom" / "w0.05_a0.1" / "luminance.npy", "left": ROOT / "output" / "blend_bottom" / "left_w0.05_a0.1" / "luminance.npy", @@ -99,7 +95,7 @@ Returns: 終了コード(成功なら 0,入力不足なら 1). """ - for paths in (FIX_BASE, FIX_W1P4, REAL, OLD_BASE): + for paths in (FIX_BASE, FIX_W1P4, OLD_BASE): for p in paths.values(): if not p.exists(): print(f"エラー: {p} が見つかりません", file=sys.stderr) @@ -112,7 +108,12 @@ def _smooth(m: np.ndarray) -> np.ndarray: return gaussian_filter(median_filter(m, size=5), sigma=4) - real = {s: _load_luminance(REAL[s]) for s in SIDES} + try: + # 実機単灯(SmTIAS-Lab の DNG から作る白板 ROI.lab.V3_SHOTS のキー = SIDES) + real = {s: real_roi_luminance(s).astype(np.float64) for s in SIDES} + except FileNotFoundError as exc: + print(f"エラー: 実機の DNG が読めません: {exc}", file=sys.stderr) + return 1 sets = { "old": {s: extract_roi_xywh(_load_luminance(OLD_BASE[s]), SIM_ROI) for s in SIDES}, "fix": {s: extract_roi_xywh(_load_luminance(FIX_BASE[s]), SIM_ROI) for s in SIDES}, diff --git a/scripts/build_sphere_panel.py b/scripts/build_sphere_panel.py index eb5388a..065160c 100644 --- a/scripts/build_sphere_panel.py +++ b/scripts/build_sphere_panel.py @@ -17,7 +17,7 @@ 前提: - output/full_base_fix/luminance.npy(現行筐体全灯,configs/_tmp_fn_full_base.yaml) - output/sphere_r100_loft_disk_fix/luminance.npy(球ロフト円形光源) - - lightsim/luminance_maps/full_MiniTIAS_QM_20260601_124500.npy(実機全灯) + - SmTIAS-Lab に実機全灯の DNG(experiments/2026-06-01_v3_all_leds/raw/)があること """ from __future__ import annotations @@ -31,6 +31,7 @@ import numpy as np from skimage.transform import resize +from sm_tias_lightsim.evaluation.real_maps import real_roi_luminance from sm_tias_lightsim.evaluation.roi_presets import SIM_ROI, extract_roi_xywh from sm_tias_lightsim.evaluation.shape_metrics import calc_ncc @@ -41,7 +42,8 @@ SHAPE_PANEL_PATH = ROOT / "output" / "_slide_panels" / "sphere_fix_shape_roi.png" REL_PANEL_PATH = ROOT / "output" / "_slide_panels" / "sphere_fix_relative.png" -# (ラベル, luminance.npy パス, シミュか否か).シミュのみ SIM_ROI を抽出する +# (ラベル, luminance.npy パス(実機は lab.V3_SHOTS のキー), シミュか否か). +# シミュのみ SIM_ROI を抽出する # TEST_12 面法線修正後の出力のみで比較する(修正前の出力とはシェーディング法線が # 異なり混在比較は不可.修正前の記録は TEST_11 の表を参照) CELLS = [ @@ -57,7 +59,7 @@ ), ( "実機 全灯 18 灯", - ROOT / "lightsim" / "luminance_maps" / "full_MiniTIAS_QM_20260601_124500.npy", + "full", # lab.V3_SHOTS のキー(SmTIAS-Lab の DNG から白板 ROI を作る) False, ), ] @@ -67,9 +69,12 @@ VMAX_PERCENTILE = 99.0 -def _load_luminance(path: Path) -> np.ndarray: - """luminance.npy を読み込み 2D 輝度にする(3D RGB は Rec.709 変換).""" - arr = np.load(path) +def _load_luminance(path: Path | str) -> np.ndarray: + """luminance.npy を読み込み 2D 輝度にする(3D RGB は Rec.709 変換). + + 文字列は lab.V3_SHOTS のキーとみなし,実機の白板 ROI 輝度マップを DNG から作る. + """ + arr = real_roi_luminance(path) if isinstance(path, str) else np.load(path) if arr.ndim == 3: arr = 0.2126 * arr[..., 0] + 0.7152 * arr[..., 1] + 0.0722 * arr[..., 2] return arr.astype(np.float64) @@ -99,7 +104,7 @@ real = _load_luminance(CELLS[-1][1]) loaded: list[tuple[str, np.ndarray, dict[str, float]]] = [] for label, path, is_sim in CELLS: - if not path.exists(): + if isinstance(path, Path) and not path.exists(): print(f"エラー: {path} が見つかりません", file=sys.stderr) return 1 img = _load_luminance(path) diff --git a/scripts/compare_real_vs_sim_metrics.py b/scripts/compare_real_vs_sim_metrics.py index d3b151e..ad46c84 100644 --- a/scripts/compare_real_vs_sim_metrics.py +++ b/scripts/compare_real_vs_sim_metrics.py @@ -10,9 +10,10 @@ を数値で比べる. -実機の読み込みは TEST_14 と同じ経路(load_image_dng → lscMap 順適用 → Rec.709 → rot90(-1) -→ 白板 ROI).実機 ROI(1400×1409 px)はシミュ ROI(464×450 px)へリサイズしてから同じ -処理を掛ける(平滑化 σ を画素で揃えるため.リサイズは約 3×3 画素の平均になりセンサノイズ +実機の読み込みは TEST_14 と同じ経路(SmTIAS-Lab の DNG を load_image_dng → lscMap 順適用 → +Rec.709 → rot90(-1) → 白板 ROI.evaluation/dng_pipeline.dng_luminance). +実機 ROI(1400×1409 px)はシミュ ROI(464×450 px)へリサイズしてから同じ処理を掛ける +(平滑化 σ を画素で揃えるため.リサイズは約 3×3 画素の平均になりセンサノイズ も落ちるが,ノイズ補正はリサイズ後の残差から推定するので整合する). 実行方法: @@ -25,7 +26,6 @@ import argparse import csv -import json import sys from pathlib import Path @@ -43,7 +43,7 @@ from analyze_fourfold_component import aggregate, ring_harmonics # noqa: E402 from build_radial_comparison import MAX_DISTANCE # noqa: E402 -from sm_tias_lightsim.evaluation.dng_loader import load_image_dng # noqa: E402 +from sm_tias_lightsim.evaluation.dng_pipeline import dng_luminance # noqa: E402 from sm_tias_lightsim.evaluation.fullimage import calc_fullimage_min_max_ratio # noqa: E402 from sm_tias_lightsim.evaluation.radial import calc_radial_profile # noqa: E402 from sm_tias_lightsim.evaluation.roi_presets import ( # noqa: E402 @@ -53,12 +53,11 @@ ) from sm_tias_lightsim.evaluation.shape_metrics import calc_ncc, calc_ssim # noqa: E402 from sm_tias_lightsim.evaluation.zones import compute_normalized_distance_map # noqa: E402 +from sm_tias_lightsim.lab import V3_SHOTS, shot_dng # noqa: E402 plt.rcParams["font.family"] = ["Yu Gothic", "MS Gothic", "DejaVu Sans"] ROOT = Path(__file__).resolve().parents[1] -REAL_DNG = ROOT / "reference_measurement" / "quantitative" / "MiniTIAS_QM_20260601_124500.dng" -REAL_META = REAL_DNG.with_name("MiniTIAS_QM_20260601_124500.meta.json") DEFAULT_SIM = ROOT / "output" / "bsdf_grid_fix" / "r0.82_w0.00_a0.1" / "luminance.npy" OUT_DIR = ROOT / "output" / "real_vs_sim" @@ -75,40 +74,9 @@ # --------------------------------------------------------------------------- -def _upsample(grid: np.ndarray, shape: tuple[int, int]) -> np.ndarray: - """(rows, cols) の格子を画像サイズへバイリニア補間する(参照スクリプトと同一).""" - rows, cols = grid.shape - h, w = shape - ys = np.linspace(0, rows - 1, h) - xs = np.linspace(0, cols - 1, w) - y0 = np.floor(ys).astype(int) - y1 = np.minimum(y0 + 1, rows - 1) - x0 = np.floor(xs).astype(int) - x1 = np.minimum(x0 + 1, cols - 1) - wy = (ys - y0)[:, None] - wx = (xs - x0)[None, :] - top = grid[y0][:, x0] * (1 - wx) + grid[y0][:, x1] * wx - bot = grid[y1][:, x0] * (1 - wx) + grid[y1][:, x1] * wx - return top * (1 - wy) + bot * wy - - -def lsc_gain_rgb(meta_path: Path, shape: tuple[int, int]) -> np.ndarray: - """meta.json の lscMap(rows, cols, 4=[R, G_even, G_odd, B])→ (H, W, 3) の RGB ゲイン.""" - meta = json.loads(meta_path.read_text(encoding="utf-8")) - rows, cols = meta["lscMapRowCount"], meta["lscMapColumnCount"] - m = np.array(meta["lscMap"], dtype=np.float64).reshape(rows, cols, 4) - return np.stack([_upsample(m[:, :, 0], shape), - _upsample((m[:, :, 1] + m[:, :, 2]) / 2.0, shape), - _upsample(m[:, :, 3], shape)], axis=2) - - def load_real_roi() -> np.ndarray: - """実機 DNG → linear raw → LSC 順適用 → Rec.709 × 255 → portrait → 白板 ROI.""" - rgb = load_image_dng(str(REAL_DNG), output_format="rgb_float32").astype(np.float64) - rgb = rgb * lsc_gain_rgb(REAL_META, rgb.shape[:2]) - luma = 0.2126 * rgb[..., 0] + 0.7152 * rgb[..., 1] + 0.0722 * rgb[..., 2] - luma = np.rot90(luma * 255.0, -1) - return extract_roi_xywh(luma, REAL_ROI) + """実機 DNG(SmTIAS-Lab)→ linear raw → LSC 順適用 → Rec.709 × 255 → portrait → 白板 ROI.""" + return extract_roi_xywh(dng_luminance(shot_dng(V3_SHOTS["full"])), REAL_ROI) def load_sim_roi(path: Path) -> np.ndarray: diff --git a/scripts/compare_real_vs_sim_shapes.py b/scripts/compare_real_vs_sim_shapes.py index f3ff69d..1b76e60 100644 --- a/scripts/compare_real_vs_sim_shapes.py +++ b/scripts/compare_real_vs_sim_shapes.py @@ -37,6 +37,7 @@ from analyze_fourfold_component import aggregate, ring_harmonics # noqa: E402 from build_radial_comparison import MAX_DISTANCE # noqa: E402 +from sm_tias_lightsim.evaluation.real_maps import real_roi_luminance # noqa: E402 from sm_tias_lightsim.evaluation.roi_presets import SIM_ROI, extract_roi_xywh # noqa: E402 from sm_tias_lightsim.evaluation.shape_metrics import calc_ncc, calc_ssim # noqa: E402 from sm_tias_lightsim.evaluation.zones import compute_normalized_distance_map # noqa: E402 @@ -45,16 +46,10 @@ ROOT = Path(__file__).resolve().parents[1] OUT_DIR = ROOT / "output" / "real_vs_sim" -REAL_DIR = ROOT / "lightsim" / "luminance_maps" CONFIGS = ("full", "bottom", "left", "right") CONFIG_LABEL = {"full": "全灯 18 灯", "bottom": "下 単灯", "left": "左 単灯", "right": "右 単灯"} -REAL = { - "full": REAL_DIR / "full_MiniTIAS_QM_20260601_124500.npy", - "bottom": REAL_DIR / "bottom_SmTIAS_QM_20260615_141420.npy", - "left": REAL_DIR / "left_SmTIAS_QM_20260615_150300.npy", - "right": REAL_DIR / "right_SmTIAS_QM_20260615_170948.npy", -} +# 実機は CONFIGS の名前を lab.V3_SHOTS のキーとして SmTIAS-Lab の DNG から作る(load_real) SIM_SETS = { # TEST_14 で確定した内壁(純 diffuse ρ=0.81)・spp 4096(本スクリプト用にサーバでレンダ) "rho081": { @@ -87,9 +82,14 @@ return extract_roi_xywh(arr, SIM_ROI) -def load_real(path: Path, shape: tuple[int, int]) -> np.ndarray: - """実機 ROI(DNG 由来・LSC 適用済み)をシミュ ROI の解像度へリサイズして返す(生).""" - arr = np.load(path).astype(np.float64) +def load_real(shot: str, shape: tuple[int, int]) -> np.ndarray: + """実機 ROI(DNG 由来・LSC 適用済み)をシミュ ROI の解像度へリサイズして返す(生). + + Args: + shot: lab.V3_SHOTS のキー("full"・"bottom"・"left"・"right"). + shape: リサイズ先(シミュ ROI の shape). + """ + arr = real_roi_luminance(shot).astype(np.float64) return resize(arr, shape, anti_aliasing=True, preserve_range=True) @@ -196,12 +196,12 @@ results: dict[str, dict] = {} maps: dict[str, tuple[np.ndarray, np.ndarray]] = {} for cfg in CONFIGS: - sim_path, real_path = sim_set[cfg], REAL[cfg] - if not sim_path.exists() or not real_path.exists(): - print(f"スキップ {cfg}: {sim_path if not sim_path.exists() else real_path} が無い") + sim_path = sim_set[cfg] + if not sim_path.exists(): + print(f"スキップ {cfg}: {sim_path} が無い") continue sim_roi = load_sim(sim_path) - real_roi = load_real(real_path, sim_roi.shape) + real_roi = load_real(cfg, sim_roi.shape) sim_map, real_map = normalized_shape(sim_roi), normalized_shape(real_roi) results[cfg] = shape_metrics(sim_map, real_map, sim_roi, real_roi) maps[cfg] = (real_map, sim_map) diff --git a/scripts/select_white_board.py b/scripts/select_white_board.py index 8e91fa7..1905962 100644 --- a/scripts/select_white_board.py +++ b/scripts/select_white_board.py @@ -2,7 +2,10 @@ 使い方: uv run python scripts/select_white_board.py \ - [--image reference_measurement/.../*.png] [--output configs/white_board_bbox.json] + [--image ] [--output configs/white_board_bbox.json] + + --image を省くと SmTIAS-Lab の experiments/2026-04-08_v3_png/raw/SmTIAS_20260408_144434.png + を使う(Lab の場所は環境変数 SMTIAS_LAB,無ければ本リポジトリの隣の SmTIAS-Lab). 操作: 1. 表示された画像で白色板の **境界を囲むように** マウスでドラッグして矩形を引く @@ -21,14 +24,16 @@ import cv2 +from sm_tias_lightsim.lab import V3_PNG_WHITEBOARD, lab_file + def main() -> None: parser = argparse.ArgumentParser(description="Select white board boundary in real PNG") parser.add_argument( "--image", type=Path, - default=Path("reference_measurement/MiniTIAS_20260408_144434/MiniTIAS_20260408_144434.png"), - help="実測 PNG パス", + default=None, + help="実測 PNG パス(既定: SmTIAS-Lab の 2026-04-08_v3_png の SmTIAS_20260408_144434.png)", ) parser.add_argument( "--output", @@ -38,6 +43,8 @@ ) parser.add_argument("--scale", type=float, default=0.3, help="表示時の縮小率") args = parser.parse_args() + if args.image is None: + args.image = lab_file(*V3_PNG_WHITEBOARD) if not args.image.exists(): msg = f"画像が見つかりません: {args.image}" diff --git a/scripts/sweep_bsdf_grid_fix.py b/scripts/sweep_bsdf_grid_fix.py index f14467b..86d3034 100644 --- a/scripts/sweep_bsdf_grid_fix.py +++ b/scripts/sweep_bsdf_grid_fix.py @@ -46,6 +46,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) +from sm_tias_lightsim.evaluation.real_maps import real_roi_luminance # noqa: E402 from sm_tias_lightsim.evaluation.roi_presets import SIM_ROI, extract_roi_xywh # noqa: E402 from sm_tias_lightsim.evaluation.shape_metrics import calc_ncc # noqa: E402 from sm_tias_lightsim.scene.paths import relative_mesh_path # noqa: E402 @@ -58,7 +59,6 @@ OUTPUT_BASE = ROOT / "output" / "bsdf_grid_fix" SUMMARY_CSV = OUTPUT_BASE / "summary.csv" -REAL_FULL = ROOT / "lightsim" / "luminance_maps" / "full_MiniTIAS_QM_20260601_124500.npy" REFERENCE_JOB_DIR = ROOT / "output" / "full_base_fix" # 基準点(= output/full_base_fix/ を生成した条件) @@ -288,10 +288,12 @@ log_file.write(message + "\n") log_file.flush() - if not REAL_FULL.exists(): - log(f"エラー: 実機マップ {REAL_FULL} が見つかりません") + try: + real_full = real_roi_luminance("full") # 実機全灯(SmTIAS-Lab の DNG) + except FileNotFoundError as exc: + log(f"エラー: 実機の DNG が読めません: {exc}") return 1 - real_smooth = _smooth(np.load(REAL_FULL), False) + real_smooth = _smooth(real_full, False) log(f"=== ρ×ω×α 再スイープ(面法線修正後)予算 {args.budget_hours}h ===") log(f" 固定条件: spp=1024 / max_depth=16 / 512^2({TEMPLATE_YAML.name} 準拠)") diff --git a/src/sm_tias_lightsim/evaluation/dng_pipeline.py b/src/sm_tias_lightsim/evaluation/dng_pipeline.py new file mode 100644 index 0000000..d44118f --- /dev/null +++ b/src/sm_tias_lightsim/evaluation/dng_pipeline.py @@ -0,0 +1,124 @@ +"""DNG 定量モードの輝度化パイプライン(実機の輝度マップを作る). + +SmTIAS-Evaluation `src/io/dng_pipeline.py` の `dng_luminance` と同じ処理を LightSim 側に +置いたもの(Evaluation は import しない方針のため.処理を変えるときは両方をそろえる). + +- 読み込みは `load_image_dng`(output_format="rgb_float32"・linear・output_color=raw) +- DNG は RAW_SENSOR で未補正のため,meta.json の lscMap でレンズビネットを順適用(任意) +- Rec.709 で輝度化して 0〜255 の linear スケールにする(PNG の図と軸をそろえるため. + CoV 等のスケール不変な指標は変わらない) +- センサの向き(landscape)を PNG と同じ portrait へ rot90(-1) でそろえる +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np + +from sm_tias_lightsim.evaluation.dng_loader import load_image_dng +from sm_tias_lightsim.uniformity import REC709_COEFF_B, REC709_COEFF_G, REC709_COEFF_R + +# 輝度を 0〜255 のスケールで返す(Evaluation の dng_luminance・旧 luminance_maps/*.npy と同じ) +LUMA_SCALE = 255.0 + + +def _upsample(grid: np.ndarray, shape: tuple[int, int]) -> np.ndarray: + """(rows, cols) の格子を画像サイズ shape へバイリニア補間する. + + Args: + grid: 補間元の格子(rows x cols). + shape: 補間先の画像サイズ (height, width). + + Returns: + 補間後の配列(height x width, float64). + """ + rows, cols = grid.shape + h, w = shape + ys = np.linspace(0, rows - 1, h) + xs = np.linspace(0, cols - 1, w) + y0 = np.floor(ys).astype(int) + y1 = np.minimum(y0 + 1, rows - 1) + x0 = np.floor(xs).astype(int) + x1 = np.minimum(x0 + 1, cols - 1) + wy = (ys - y0)[:, None] + wx = (xs - x0)[None, :] + top = grid[y0][:, x0] * (1 - wx) + grid[y0][:, x1] * wx + bot = grid[y1][:, x0] * (1 - wx) + grid[y1][:, x1] * wx + return top * (1 - wy) + bot * wy + + +def lsc_gain_rgb(meta_path: Path, shape: tuple[int, int]) -> np.ndarray: + """meta.json の lscMap を (H, W, 3) の RGB ゲインへ補間する. + + lscMap は (rows, cols, 4=[R, G_even, G_odd, B]).G は G_even と G_odd の平均を使う. + + Args: + meta_path: meta.json のパス. + shape: 補間先の画像サイズ (height, width).DNG の向き(landscape)のまま渡す. + + Returns: + RGB ゲイン(H x W x 3, float64). + + Raises: + ValueError: meta.json に lscMap・lscMapRowCount・lscMapColumnCount が無い, + または要素数が合わない場合. + """ + meta = json.loads(Path(meta_path).read_text(encoding="utf-8")) + try: + rows, cols = int(meta["lscMapRowCount"]), int(meta["lscMapColumnCount"]) + m = np.asarray(meta["lscMap"], dtype=np.float64).reshape(rows, cols, 4) + except (KeyError, TypeError, ValueError) as exc: + msg = f"meta.json の LSC マップを読めません(lscMap / lscMapRowCount 等): {meta_path}" + raise ValueError(msg) from exc + return np.stack( + [ + _upsample(m[:, :, 0], shape), + _upsample((m[:, :, 1] + m[:, :, 2]) / 2.0, shape), + _upsample(m[:, :, 3], shape), + ], + axis=2, + ) + + +def meta_path_for(dng_path: Path) -> Path: + """DNG と同名の meta.json のパスを返す(`.dng` → `.meta.json`). + + Args: + dng_path: DNG のパス. + + Returns: + meta.json のパス(存在は確かめない). + """ + dng_path = Path(dng_path) + return dng_path.with_name(f"{dng_path.stem}.meta.json") + + +def dng_luminance( + dng_path: Path, *, apply_lsc: bool = True, meta_path: Path | None = None +) -> np.ndarray: + """DNG から portrait・linear・(任意で LSC 補正済みの)輝度画像を返す. + + Args: + dng_path: DNG のパス. + apply_lsc: True なら meta.json の lscMap を順適用してレンズビネットを除く. + meta_path: meta.json のパス.None なら DNG と同名の `.meta.json`. + + Returns: + portrait 向きの輝度画像(H x W, float64.0〜255 の linear スケール). + + Raises: + FileNotFoundError: DNG,または LSC に要る meta.json が無い場合. + ValueError: DNG・meta.json の形式が不正な場合. + """ + rgb = load_image_dng(str(dng_path), output_format="rgb_float32").astype(np.float64) + if apply_lsc: + meta = Path(meta_path) if meta_path is not None else meta_path_for(dng_path) + if not meta.is_file(): + raise FileNotFoundError(f"meta.json が見つかりません(LSC 補正に必要): {meta}") + rgb = rgb * lsc_gain_rgb(meta, rgb.shape[:2]) + luma = ( + REC709_COEFF_R * rgb[..., 0] + REC709_COEFF_G * rgb[..., 1] + REC709_COEFF_B * rgb[..., 2] + ) + return np.rot90(luma * LUMA_SCALE, -1) diff --git a/src/sm_tias_lightsim/evaluation/real_maps.py b/src/sm_tias_lightsim/evaluation/real_maps.py new file mode 100644 index 0000000..55272f8 --- /dev/null +++ b/src/sm_tias_lightsim/evaluation/real_maps.py @@ -0,0 +1,95 @@ +"""実機の白板 ROI 輝度マップ(SmTIAS-Lab の DNG から作り,output/ にキャッシュする). + +以前は `lightsim/luminance_maps/{full,bottom,left,right}_*.npy` として配っていた +マップを,Lab の DNG から同じ処理で作り直す.処理は +DNG → linear raw → LSC 順適用 → Rec.709 × 255 → portrait → 白板 ROI(`REAL_ROI`)で, +結果は shape (1409, 1400) の float32(旧 .npy と同じ). + +DNG の読み込みとデモザイクに数秒かかるため,結果を +`output/_cache/real_maps/_<処理>.npy` に保存し,DNG・meta.json より新しければ +そのまま読む. +""" + +from __future__ import annotations + +import logging +from pathlib import Path + +import numpy as np + +from sm_tias_lightsim.evaluation.dng_pipeline import dng_luminance +from sm_tias_lightsim.evaluation.roi_presets import REAL_ROI, extract_roi_xywh +from sm_tias_lightsim.lab import REPO_ROOT, V3_SHOTS, LabShot, shot_dng, shot_meta + +logger = logging.getLogger(__name__) + +DEFAULT_CACHE_DIR = REPO_ROOT / "output" / "_cache" / "real_maps" + + +def resolve_shot(shot: LabShot | str) -> LabShot: + """撮影の指定(`LabShot` または `V3_SHOTS` のキー)を `LabShot` にする. + + Args: + shot: `LabShot`,または `"full"`・`"bottom"`・`"left"`・`"right"`. + + Returns: + 撮影. + + Raises: + ValueError: 知らないキーの場合. + """ + if isinstance(shot, LabShot): + return shot + try: + return V3_SHOTS[shot] + except KeyError as exc: + msg = f"知らない撮影の名前です: {shot!r}(使えるもの: {', '.join(V3_SHOTS)})" + raise ValueError(msg) from exc + + +def _cache_name(shot: LabShot, roi: dict, apply_lsc: bool) -> str: + """処理条件をファイル名に入れる(条件が変われば別のキャッシュになる).""" + lsc = "lsc" if apply_lsc else "nolsc" + return f"{shot.stem}_{lsc}_x{roi['x']}_y{roi['y']}_w{roi['w']}_h{roi['h']}.npy" + + +def real_roi_luminance( + shot: LabShot | str, + *, + roi: dict | None = None, + apply_lsc: bool = True, + cache_dir: Path | None = DEFAULT_CACHE_DIR, +) -> np.ndarray: + """Lab の DNG から実機の白板 ROI 輝度マップを作る(キャッシュがあれば読む). + + Args: + shot: 撮影(`LabShot`,または `V3_SHOTS` のキー `"full"`・`"bottom"` 等). + roi: 切り出す ROI(`{"x", "y", "w", "h"}`.portrait 座標).None なら `REAL_ROI`. + apply_lsc: True なら meta.json の lscMap を順適用する. + cache_dir: キャッシュの置き場.None ならキャッシュを使わない. + + Returns: + ROI の輝度マップ(h x w, float32.0〜255 の linear スケール). + + Raises: + FileNotFoundError: Lab・DNG・meta.json が見つからない場合. + ValueError: 知らない撮影の名前,または DNG・meta.json の形式が不正な場合. + """ + shot = resolve_shot(shot) + roi = REAL_ROI if roi is None else roi + dng = shot_dng(shot) + meta = shot_meta(shot) if apply_lsc else None + + cache = cache_dir / _cache_name(shot, roi, apply_lsc) if cache_dir is not None else None + if cache is not None and cache.is_file(): + sources = [dng] + ([meta] if meta is not None else []) + if cache.stat().st_mtime >= max(p.stat().st_mtime for p in sources): + return np.load(cache) + + luma = dng_luminance(dng, apply_lsc=apply_lsc, meta_path=meta) + out = extract_roi_xywh(luma, roi).astype(np.float32) + if cache is not None: + cache.parent.mkdir(parents=True, exist_ok=True) + np.save(cache, out) + logger.info("実機の輝度マップをキャッシュしました: %s", cache) + return out diff --git a/src/sm_tias_lightsim/lab.py b/src/sm_tias_lightsim/lab.py new file mode 100644 index 0000000..de0159d --- /dev/null +++ b/src/sm_tias_lightsim/lab.py @@ -0,0 +1,212 @@ +"""実験データのリポジトリ SmTIAS-Lab の場所と,LightSim が読む撮影ファイルの一覧. + +撮影データ(DNG・meta.json・PNG)は SmTIAS-Lab の +`experiments/_<内容>/raw/` に置く(git の対象外).LightSim のスクリプトと +テストは本モジュールを通して Lab のファイルを指す. + +Lab の場所は次の順で決める. + +1. 環境変数 `SMTIAS_LAB`(Lab のリポジトリのルート) +2. 本リポジトリのルートの隣の `SmTIAS-Lab`(`../SmTIAS-Lab`.研究室サーバでも同じ並びにする) +""" + +from __future__ import annotations + +import os +from dataclasses import dataclass +from pathlib import Path, PurePath + +LAB_ENV_VAR = "SMTIAS_LAB" +LAB_DIR_NAME = "SmTIAS-Lab" +EXPERIMENTS_DIR = "experiments" + +# src/sm_tias_lightsim/lab.py → リポジトリのルート(uv の editable インストール前提) +REPO_ROOT = Path(__file__).resolve().parents[2] + + +@dataclass(frozen=True) +class LabShot: + """Lab の 1 回の撮影(DNG と同名の meta.json). + + Attributes: + experiment: 実験フォルダ名(例: `2026-06-01_v3_all_leds`). + stem: ファイル名の拡張子より前(例: `SmTIAS_QM_20260601_124500`). + """ + + experiment: str + stem: str + + @property + def dng_name(self) -> str: + """DNG のファイル名.""" + return f"{self.stem}.dng" + + @property + def meta_name(self) -> str: + """meta.json のファイル名(LSC マップを含む).""" + return f"{self.stem}.meta.json" + + +# 現行機(v3)の定量モード DNG.全灯は暗室撮影の基準(TEST_01 Step 8-13 以降の TARGET), +# 単灯 3 種は 2026-06-15 の撮影(下・左・右の基板の LED 1 個だけ点灯) +V3_SHOTS: dict[str, LabShot] = { + "full": LabShot("2026-06-01_v3_all_leds", "SmTIAS_QM_20260601_124500"), + "bottom": LabShot("2026-06-15_v3_single_led", "SmTIAS_QM_20260615_141420"), + "left": LabShot("2026-06-15_v3_single_led", "SmTIAS_QM_20260615_150300"), + "right": LabShot("2026-06-15_v3_single_led", "SmTIAS_QM_20260615_170948"), +} + +# 現行機の全灯 DNG を Evaluation で評価した結果(白板 ROI の mean・CoV 等) +V3_FULL_UNIFORMITY_CSV = ( + "2026-06-01_v3_all_leds", + "results", + "SmTIAS_QM_20260601_124500_uniformity.csv", +) + +# 現行機の通常モード PNG(Step 8 のキャリブで白板 ROI を決めた画像) +V3_PNG_WHITEBOARD = ("2026-04-08_v3_png", "raw", "SmTIAS_20260408_144434.png") + + +def _setup_hint() -> str: + """Lab が見つからないときの対処方法.""" + return ( + f"SmTIAS-Lab を本リポジトリの隣({REPO_ROOT.parent / LAB_DIR_NAME})に clone するか," + f"環境変数 {LAB_ENV_VAR} に Lab のリポジトリのルートを設定してください" + f"(PowerShell: $env:{LAB_ENV_VAR} = 'C:\\path\\to\\SmTIAS-Lab' / " + f"bash: export {LAB_ENV_VAR}=/path/to/SmTIAS-Lab)." + "撮影データ(raw/)は git の対象外なので,clone 後に手元の Lab から別途コピーが要ります." + ) + + +def lab_root() -> Path: + """SmTIAS-Lab のリポジトリのルートを返す. + + Returns: + Lab のルートディレクトリ(存在を確認済み). + + Raises: + FileNotFoundError: 環境変数 `SMTIAS_LAB` の指す先,または既定の `../SmTIAS-Lab` が + ディレクトリとして存在しない場合. + """ + env = os.environ.get(LAB_ENV_VAR, "").strip() + if env: + root = Path(env).expanduser() + if not root.is_dir(): + msg = f"環境変数 {LAB_ENV_VAR} の指す SmTIAS-Lab が見つかりません: {root}." + raise FileNotFoundError(msg + _setup_hint()) + return root.resolve() + root = REPO_ROOT.parent / LAB_DIR_NAME + if not root.is_dir(): + raise FileNotFoundError(f"SmTIAS-Lab が見つかりません: {root}." + _setup_hint()) + return root + + +def _validate_parts(parts: tuple[str, ...]) -> None: + """実験フォルダ名・サブパスが Lab の experiments/ の外を指さないことを確かめる.""" + if not parts: + raise ValueError("実験フォルダ名を指定してください.") + for part in parts: + path = PurePath(part) + # Windows では "/Windows" はドライブ無しで is_absolute() が False になるため root も見る + if not part or path.is_absolute() or path.drive or path.root or ".." in path.parts: + msg = ( + f"Lab のパスの要素が不正です: {part!r}" + "(ルート(/ や \\)から始めない相対パスで,'..' を含めない)" + ) + raise ValueError(msg) + + +def lab_path(experiment: str, *parts: str) -> Path: + """Lab の実験フォルダ内のパスを返す(存在は確かめない). + + Args: + experiment: 実験フォルダ名(例: `2026-06-01_v3_all_leds`). + *parts: 実験フォルダ内のサブパス(例: `"raw", "SmTIAS_QM_20260601_124500.dng"`). + + Returns: + `/experiments//`. + + Raises: + FileNotFoundError: Lab 自体が見つからない場合(`lab_root` 参照). + ValueError: 絶対パス・ルート(`/`・`\\`)から始まるパスや `..` を含む場合. + """ + _validate_parts((experiment, *parts)) + return lab_root().joinpath(EXPERIMENTS_DIR, experiment, *parts) + + +def lab_file(experiment: str, *parts: str) -> Path: + """Lab の実験フォルダ内のファイルを返す(存在を確かめる). + + 例: `lab_file("2026-06-01_v3_all_leds", "raw", "SmTIAS_QM_20260601_124500.dng")` + + Args: + experiment: 実験フォルダ名. + *parts: 実験フォルダ内のサブパス. + + Returns: + 存在を確認したファイルのパス. + + Raises: + FileNotFoundError: Lab またはファイルが見つからない場合. + ValueError: 絶対パス・ルート(`/`・`\\`)から始まるパスや `..` を含む場合. + """ + path = lab_path(experiment, *parts) + if not path.is_file(): + msg = ( + f"SmTIAS-Lab にファイルがありません: {path}." + "raw/ は git の対象外なので,撮影データを手元の Lab にコピーしたか確かめてください" + f"(別の場所の Lab を使うなら環境変数 {LAB_ENV_VAR} を設定)." + ) + raise FileNotFoundError(msg) + return path + + +def find_lab_file(experiment: str, *parts: str) -> Path | None: + """Lab の実験フォルダ内のファイルを返す.Lab かファイルが無ければ None. + + Lab のデータが無い環境でテストをスキップする判定などに使う. + + Args: + experiment: 実験フォルダ名. + *parts: 実験フォルダ内のサブパス. + + Returns: + ファイルのパス,または None. + + Raises: + ValueError: 絶対パス・ルート(`/`・`\\`)から始まるパスや `..` を含む場合. + """ + try: + return lab_file(experiment, *parts) + except FileNotFoundError: + return None + + +def shot_dng(shot: LabShot) -> Path: + """撮影の DNG のパスを返す(存在を確かめる). + + Args: + shot: 撮影. + + Returns: + `/experiments//raw/.dng`. + + Raises: + FileNotFoundError: Lab または DNG が見つからない場合. + """ + return lab_file(shot.experiment, "raw", shot.dng_name) + + +def shot_meta(shot: LabShot) -> Path: + """撮影の meta.json のパスを返す(存在を確かめる). + + Args: + shot: 撮影. + + Returns: + `/experiments//raw/.meta.json`. + + Raises: + FileNotFoundError: Lab または meta.json が見つからない場合. + """ + return lab_file(shot.experiment, "raw", shot.meta_name) diff --git a/src/sm_tias_lightsim/remote/files.py b/src/sm_tias_lightsim/remote/files.py index f06437c..7865903 100644 --- a/src/sm_tias_lightsim/remote/files.py +++ b/src/sm_tias_lightsim/remote/files.py @@ -1,8 +1,9 @@ """push で送るファイルの選定(除外規則・追加指定・サーバ側の削除対象の算出). 既定では,Windows 専用の仮想環境・計算結果・キャッシュ・スイープの一時生成物を除いた -プロジェクト全体を送る.gitignore 対象でも実測参照データ(lightsim/・reference_measurement/・ -REFERENCE/)はサーバでの評価に要るので送る. +プロジェクト全体を送る.gitignore 対象のファイルも,除外規則に当たらなければ送る +(REFERENCE/ 等).実測データの旧置き場(lightsim/・reference_measurement/)は廃止した. +撮影データは隣のリポジトリ SmTIAS-Lab に置き,サーバへは送らない. """ from __future__ import annotations diff --git a/tests/evaluation/test_dng_loader.py b/tests/evaluation/test_dng_loader.py index fb6475a..d039a6e 100644 --- a/tests/evaluation/test_dng_loader.py +++ b/tests/evaluation/test_dng_loader.py @@ -28,17 +28,23 @@ from sm_tias_lightsim.evaluation.dng_loader import load_image_dng from sm_tias_lightsim.evaluation.radial import calc_radial_min_max_ratio, calc_radial_profile +from sm_tias_lightsim.lab import V3_SHOTS, find_lab_file # --------------------------------------------------------------------------- # テストデータのパス定義 # --------------------------------------------------------------------------- -_REPO_ROOT = Path(__file__).resolve().parent.parent.parent -_QUANTITATIVE_DIR = _REPO_ROOT / "reference_measurement" / "quantitative" -_DNG_PATH = _QUANTITATIVE_DIR / "MiniTIAS_QM_20260601_124500.dng" -_META_PATH = _QUANTITATIVE_DIR / "MiniTIAS_QM_20260601_124500.meta.json" +# 実機の全灯 DNG は SmTIAS-Lab に置く(場所は環境変数 SMTIAS_LAB.docs/02_ENV/ENV_04 +# 「実機のデータ」).Lab かファイルが無い環境では実 DNG を使うテストをスキップする +_FULL_SHOT = V3_SHOTS["full"] +_DNG_PATH = find_lab_file(_FULL_SHOT.experiment, "raw", _FULL_SHOT.dng_name) +_META_PATH = find_lab_file(_FULL_SHOT.experiment, "raw", _FULL_SHOT.meta_name) -_DNG_EXISTS = _DNG_PATH.exists() +_DNG_EXISTS = _DNG_PATH is not None and _META_PATH is not None +_DNG_SKIP_REASON = ( + f"SmTIAS-Lab に実機の全灯 DNG・meta.json がありません" + f"(experiments/{_FULL_SHOT.experiment}/raw/{_FULL_SHOT.stem}.*)" +) # --------------------------------------------------------------------------- # A. load_image_dng の単体仕様テスト @@ -121,11 +127,11 @@ @pytest.mark.slow -@pytest.mark.skipif(not _DNG_EXISTS, reason=f"実 DNG ファイルが存在しません: {_DNG_PATH}") +@pytest.mark.skipif(not _DNG_EXISTS, reason=_DNG_SKIP_REASON) class TestLoadImageDngOutputFormats: """A5〜A8: 実 DNG ファイルを用いた出力形式の仕様検証. - DNG ファイル: reference_measurement/quantitative/MiniTIAS_QM_20260601_124500.dng + DNG ファイル: SmTIAS-Lab experiments/2026-06-01_v3_all_leds/raw/SmTIAS_QM_20260601_124500.dng """ def test_a5_rgb_float32_shape_dtype_range(self): @@ -455,7 +461,7 @@ # minitias.whiteboard: {x: 539, y: 1015, width: 1400, height: 1409} _WHITEBOARD_ROI = {"x": 539, "y": 1015, "width": 1400, "height": 1409} -# 期待値 (expected_results/MiniTIAS_QM_20260601_124500_uniformity.csv) +# 期待値 (SmTIAS-Lab results/SmTIAS_QM_20260601_124500_uniformity.csv) _EXPECTED_UNIFORMITY = { "cov": 0.06953368075883541, "std": 14.450766770999131, @@ -478,14 +484,14 @@ @pytest.mark.slow -@pytest.mark.skipif(not _DNG_EXISTS, reason=f"実 DNG ファイルが存在しません: {_DNG_PATH}") +@pytest.mark.skipif(not _DNG_EXISTS, reason=_DNG_SKIP_REASON) class TestV4ReproducibilityWithRealDng: """検証 V4 — 実機 DNG での再現性統合テスト (TECH_06 §6). 評価データ: - DNG: reference_measurement/quantitative/MiniTIAS_QM_20260601_124500.dng - meta.json: reference_measurement/quantitative/MiniTIAS_QM_20260601_124500.meta.json - 期待値 CSV: expected_results/MiniTIAS_QM_20260601_124500_uniformity.csv + DNG: SmTIAS-Lab experiments/2026-06-01_v3_all_leds/raw/SmTIAS_QM_20260601_124500.dng + meta.json: 同フォルダの SmTIAS_QM_20260601_124500.meta.json + 期待値 CSV: 同実験の results/SmTIAS_QM_20260601_124500_uniformity.csv 評価条件: linear (output_color=raw) / portrait / LSC 補正あり / 白板 ROI @@ -509,7 +515,7 @@ """V4-1: CoV が期待値 ≈ 0.0695 と相対誤差 1% 以内で一致すること. 仕様: CoV = std / mean (uniformity.py calc_uniformity) - 期待値出典: expected_results/MiniTIAS_QM_20260601_124500_uniformity.csv + 期待値出典: SmTIAS-Lab results/SmTIAS_QM_20260601_124500_uniformity.csv """ from sm_tias_lightsim.uniformity import calc_uniformity @@ -523,7 +529,7 @@ def test_v4_uniformity_std(self, roi_luminance): """V4-2: std が期待値 ≈ 14.45 と相対誤差 1% 以内で一致すること. - 期待値出典: expected_results/MiniTIAS_QM_20260601_124500_uniformity.csv + 期待値出典: SmTIAS-Lab results/SmTIAS_QM_20260601_124500_uniformity.csv """ from sm_tias_lightsim.uniformity import calc_uniformity @@ -537,7 +543,7 @@ def test_v4_uniformity_max_min_ratio(self, roi_luminance): """V4-3: max/min 比が期待値 ≈ 1.617 と相対誤差 1% 以内で一致すること. - 期待値出典: expected_results/MiniTIAS_QM_20260601_124500_uniformity.csv + 期待値出典: SmTIAS-Lab results/SmTIAS_QM_20260601_124500_uniformity.csv """ from sm_tias_lightsim.uniformity import calc_uniformity @@ -551,7 +557,7 @@ def test_v4_uniformity_mean(self, roi_luminance): """V4-4: mean が期待値 ≈ 207.82 と相対誤差 1% 以内で一致すること. - 期待値出典: expected_results/MiniTIAS_QM_20260601_124500_uniformity.csv + 期待値出典: SmTIAS-Lab results/SmTIAS_QM_20260601_124500_uniformity.csv """ from sm_tias_lightsim.uniformity import calc_uniformity @@ -565,7 +571,7 @@ def test_v4_uniformity_max(self, roi_luminance): """V4-5: max が期待値 ≈ 239.95 と相対誤差 1% 以内で一致すること. - 期待値出典: expected_results/MiniTIAS_QM_20260601_124500_uniformity.csv + 期待値出典: SmTIAS-Lab results/SmTIAS_QM_20260601_124500_uniformity.csv """ from sm_tias_lightsim.uniformity import calc_uniformity @@ -579,7 +585,7 @@ def test_v4_uniformity_min(self, roi_luminance): """V4-6: min が期待値 ≈ 148.43 と相対誤差 1% 以内で一致すること. - 期待値出典: expected_results/MiniTIAS_QM_20260601_124500_uniformity.csv + 期待値出典: SmTIAS-Lab results/SmTIAS_QM_20260601_124500_uniformity.csv """ from sm_tias_lightsim.uniformity import calc_uniformity diff --git a/tests/evaluation/test_dng_pipeline.py b/tests/evaluation/test_dng_pipeline.py new file mode 100644 index 0000000..cf7e82d --- /dev/null +++ b/tests/evaluation/test_dng_pipeline.py @@ -0,0 +1,219 @@ +"""evaluation/dng_pipeline.py の仕様ベーステスト. + +仕様出典: +- docs/04_SPEC/SPEC_04_評価仕様.md(実機の DNG → linear・LSC 順適用・Rec.709・portrait) +- docs/02_ENV/ENV_04_開発コマンド.md「実機のデータ」 +- dng_pipeline.py の docstring(SmTIAS-Evaluation と同じ処理.lscMap は + (rows, cols, 4=[R, G_even, G_odd, B]),G は 2 つの平均,画像サイズへバイリニア補間) + +合成の小さな meta.json で lsc_gain_rgb を検証する.実 DNG を使う dng_luminance の検証は +Lab が無ければスキップし,DNG のデコードが重いので slow を付ける. +""" + +from __future__ import annotations + +import json + +import numpy as np +import pytest + +from sm_tias_lightsim.evaluation.dng_pipeline import ( + LUMA_SCALE, + dng_luminance, + lsc_gain_rgb, + meta_path_for, +) +from sm_tias_lightsim.lab import V3_SHOTS, find_lab_file + + +def _write_meta(path, lsc: np.ndarray, rows: int | None = None, cols: int | None = None): + """lscMap (rows, cols, 4) を入れた meta.json を書く(ネストしたリストで,実物と同じ形).""" + r, c, _ = lsc.shape + meta = { + "lscMap": lsc.tolist(), + "lscMapRowCount": r if rows is None else rows, + "lscMapColumnCount": c if cols is None else cols, + } + path.write_text(json.dumps(meta), encoding="utf-8") + return path + + +class TestLscGainRgb: + def test_shape_and_dtype(self, tmp_path): + lsc = np.ones((3, 4, 4)) + meta = _write_meta(tmp_path / "a.meta.json", lsc) + gain = lsc_gain_rgb(meta, (30, 40)) + assert gain.shape == (30, 40, 3) + assert gain.dtype == np.float64 + + def test_constant_map_gives_constant_gain_per_channel(self, tmp_path): + """R・G(G_even/G_odd の平均)・B の定数マップはそのままのゲインになる.""" + lsc = np.zeros((3, 5, 4)) + lsc[..., 0] = 2.0 # R + lsc[..., 1] = 1.0 # G_even + lsc[..., 2] = 3.0 # G_odd + lsc[..., 3] = 4.0 # B + meta = _write_meta(tmp_path / "a.meta.json", lsc) + gain = lsc_gain_rgb(meta, (7, 11)) + np.testing.assert_allclose(gain[..., 0], 2.0) + np.testing.assert_allclose(gain[..., 1], 2.0) # (1 + 3) / 2 + np.testing.assert_allclose(gain[..., 2], 4.0) + + def test_corners_match_grid_corners(self, tmp_path): + """格子の四隅は画像の四隅に対応する(端点を合わせた補間).""" + rng = np.random.default_rng(0) + lsc = rng.uniform(1.0, 3.0, size=(4, 6, 4)) + meta = _write_meta(tmp_path / "a.meta.json", lsc) + gain = lsc_gain_rgb(meta, (20, 30)) + for gy, gx, iy, ix in [(0, 0, 0, 0), (0, -1, 0, -1), (-1, 0, -1, 0), (-1, -1, -1, -1)]: + assert gain[iy, ix, 0] == pytest.approx(lsc[gy, gx, 0]) + assert gain[iy, ix, 1] == pytest.approx((lsc[gy, gx, 1] + lsc[gy, gx, 2]) / 2) + assert gain[iy, ix, 2] == pytest.approx(lsc[gy, gx, 3]) + + def test_linear_ramp_is_interpolated_linearly(self, tmp_path): + """列方向に線形な格子は,画像でも列方向に線形(バイリニア補間).""" + cols = 5 + ramp = np.arange(cols, dtype=float) # 0..4 + lsc = np.broadcast_to(ramp[None, :, None], (3, cols, 4)).copy() + meta = _write_meta(tmp_path / "a.meta.json", lsc) + w = 9 # 格子点の間に 1 点ずつ + gain = lsc_gain_rgb(meta, (4, w)) + expected = np.linspace(0, cols - 1, w) + for ch in range(3): + np.testing.assert_allclose(gain[0, :, ch], expected) + np.testing.assert_allclose(gain[-1, :, ch], expected) + + def test_row_ramp_is_interpolated_linearly(self, tmp_path): + rows = 4 + ramp = np.arange(rows, dtype=float) * 2.0 + lsc = np.broadcast_to(ramp[:, None, None], (rows, 3, 4)).copy() + meta = _write_meta(tmp_path / "a.meta.json", lsc) + h = 7 + gain = lsc_gain_rgb(meta, (h, 5)) + np.testing.assert_allclose(gain[:, 2, 0], np.linspace(0, 6.0, h)) + + def test_values_within_grid_range(self, tmp_path): + rng = np.random.default_rng(1) + lsc = rng.uniform(1.0, 4.0, size=(5, 7, 4)) + meta = _write_meta(tmp_path / "a.meta.json", lsc) + gain = lsc_gain_rgb(meta, (50, 60)) + assert gain[..., 0].min() >= lsc[..., 0].min() - 1e-12 + assert gain[..., 0].max() <= lsc[..., 0].max() + 1e-12 + + def test_rows_cols_orientation(self, tmp_path): + """lscMapRowCount が縦,lscMapColumnCount が横(shape の (height, width) と対応).""" + lsc = np.zeros((2, 3, 4)) + lsc[1, :, 0] = 1.0 # 下の行だけ R=1 + meta = _write_meta(tmp_path / "a.meta.json", lsc) + gain = lsc_gain_rgb(meta, (5, 9)) + np.testing.assert_allclose(gain[0, :, 0], 0.0) + np.testing.assert_allclose(gain[-1, :, 0], 1.0) + + def test_missing_lsc_map_raises_value_error(self, tmp_path): + meta = tmp_path / "a.meta.json" + meta.write_text(json.dumps({"lscMapRowCount": 2, "lscMapColumnCount": 2}), "utf-8") + with pytest.raises(ValueError): + lsc_gain_rgb(meta, (4, 4)) + + def test_missing_row_count_raises_value_error(self, tmp_path): + meta = tmp_path / "a.meta.json" + meta.write_text(json.dumps({"lscMap": [[[1, 1, 1, 1]]], "lscMapColumnCount": 1}), "utf-8") + with pytest.raises(ValueError): + lsc_gain_rgb(meta, (4, 4)) + + def test_size_mismatch_raises_value_error(self, tmp_path): + meta = _write_meta(tmp_path / "a.meta.json", np.ones((3, 4, 4)), rows=5, cols=4) + with pytest.raises(ValueError): + lsc_gain_rgb(meta, (4, 4)) + + def test_non_numeric_raises_value_error(self, tmp_path): + meta = tmp_path / "a.meta.json" + meta.write_text( + json.dumps({"lscMap": "abc", "lscMapRowCount": 1, "lscMapColumnCount": 1}), "utf-8" + ) + with pytest.raises(ValueError): + lsc_gain_rgb(meta, (4, 4)) + + def test_null_row_count_raises_value_error(self, tmp_path): + meta = tmp_path / "a.meta.json" + meta.write_text( + json.dumps({"lscMap": [1, 1, 1, 1], "lscMapRowCount": None, "lscMapColumnCount": 1}), + "utf-8", + ) + with pytest.raises(ValueError): + lsc_gain_rgb(meta, (4, 4)) + + +class TestMetaPathFor: + def test_same_folder_same_stem(self, tmp_path): + dng = tmp_path / "raw" / "SmTIAS_QM_1.dng" + assert meta_path_for(dng) == tmp_path / "raw" / "SmTIAS_QM_1.meta.json" + + def test_accepts_str(self, tmp_path): + assert meta_path_for(str(tmp_path / "x.dng")) == tmp_path / "x.meta.json" + + +def test_luma_scale_is_255(): + """0〜255 の linear スケール(Evaluation・旧 npy とそろえる).""" + assert LUMA_SCALE == 255.0 + + +def test_dng_luminance_missing_meta_raises(tmp_path): + """LSC を掛けるのに meta.json が無ければ FileNotFoundError.""" + full = V3_SHOTS["full"] + dng = find_lab_file(full.experiment, "raw", full.dng_name) + if dng is None: + pytest.skip("SmTIAS-Lab に実機の全灯 DNG がありません") + with pytest.raises(FileNotFoundError): + dng_luminance(dng, apply_lsc=True, meta_path=tmp_path / "missing.meta.json") + + +def test_dng_luminance_missing_dng_raises(tmp_path): + with pytest.raises(FileNotFoundError): + dng_luminance(tmp_path / "missing.dng", apply_lsc=False) + + +@pytest.mark.slow +class TestDngLuminanceRealDng: + """実機の全灯 DNG で portrait・float64・LSC の掛け方を確かめる.""" + + @pytest.fixture(scope="class") + def paths(self): + full = V3_SHOTS["full"] + dng = find_lab_file(full.experiment, "raw", full.dng_name) + meta = find_lab_file(full.experiment, "raw", full.meta_name) + if dng is None or meta is None: + pytest.skip("SmTIAS-Lab に実機の全灯 DNG・meta.json がありません") + return dng, meta + + @pytest.fixture(scope="class") + def lumas(self, paths): + dng, _ = paths + return dng_luminance(dng, apply_lsc=True), dng_luminance(dng, apply_lsc=False) + + def test_portrait_float64(self, lumas): + luma, _ = lumas + assert luma.dtype == np.float64 + assert luma.ndim == 2 + assert luma.shape[0] > luma.shape[1] # portrait + + def test_scale_0_255(self, lumas): + _, raw = lumas + assert raw.min() >= 0.0 + assert raw.max() <= 255.0 * 1.01 + + def test_lsc_is_forward_gain(self, paths, lumas): + """LSC 済み / 未適用 の比は,lscMap のゲインの範囲に入る(順適用).""" + _, meta = paths + luma, raw = lumas + lsc = np.asarray(json.loads(meta.read_text(encoding="utf-8"))["lscMap"], dtype=float) + mask = raw > 10.0 + ratio = luma[mask] / raw[mask] + assert ratio.min() >= lsc.min() * 0.99 + assert ratio.max() <= lsc.max() * 1.01 + assert luma.mean() > raw.mean() + + def test_explicit_meta_path_matches_default(self, paths, lumas): + dng, meta = paths + luma, _ = lumas + np.testing.assert_array_equal(dng_luminance(dng, meta_path=meta), luma) diff --git a/tests/evaluation/test_real_maps.py b/tests/evaluation/test_real_maps.py new file mode 100644 index 0000000..ec32aca --- /dev/null +++ b/tests/evaluation/test_real_maps.py @@ -0,0 +1,331 @@ +"""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) diff --git a/tests/test_lab.py b/tests/test_lab.py new file mode 100644 index 0000000..d9ec1b0 --- /dev/null +++ b/tests/test_lab.py @@ -0,0 +1,230 @@ +"""lab.py(SmTIAS-Lab の場所と撮影ファイルの解決)の仕様ベーステスト. + +仕様出典: +- docs/02_ENV/ENV_04_開発コマンド.md「実機のデータ」「環境変数」 +- docs/04_SPEC/SPEC_04_評価仕様.md(実測は SmTIAS-Lab の experiments/<日付>_<内容>/raw/) +- CLAUDE.md「関連リポジトリと実験データ」(Lab は ../SmTIAS-Lab) + +Lab の実データには依存しない(環境変数 SMTIAS_LAB を tmp_path に向けて検証する). +既定の ../SmTIAS-Lab の解決だけは,手元に Lab がある場合のみ確かめる. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from sm_tias_lightsim import lab +from sm_tias_lightsim.lab import ( + LAB_ENV_VAR, + V3_FULL_UNIFORMITY_CSV, + V3_PNG_WHITEBOARD, + V3_SHOTS, + LabShot, + find_lab_file, + lab_file, + lab_path, + lab_root, + shot_dng, + shot_meta, +) + +_EXP = "2026-01-01_test" + + +@pytest.fixture +def fake_lab(tmp_path, monkeypatch) -> Path: + """SMTIAS_LAB を tmp_path 配下の空の Lab に向ける.""" + root = tmp_path / "MyLab" + (root / "experiments" / _EXP / "raw").mkdir(parents=True) + monkeypatch.setenv(LAB_ENV_VAR, str(root)) + return root + + +def test_env_var_name_is_smtias_lab(): + """ENV_04: Lab の場所は環境変数 SMTIAS_LAB で上書きする.""" + assert LAB_ENV_VAR == "SMTIAS_LAB" + + +class TestLabRoot: + def test_env_var_points_to_lab(self, fake_lab): + assert lab_root() == fake_lab.resolve() + + def test_env_var_whitespace_only_falls_back_to_default(self, monkeypatch, tmp_path): + """空白だけの SMTIAS_LAB は未設定扱い(既定の ../SmTIAS-Lab を見る).""" + monkeypatch.setenv(LAB_ENV_VAR, " ") + fake_repo = tmp_path / "repos" / "SmTIAS-LightSim" + fake_repo.mkdir(parents=True) + (tmp_path / "repos" / "SmTIAS-Lab").mkdir() + monkeypatch.setattr(lab, "REPO_ROOT", fake_repo) + assert lab_root() == tmp_path / "repos" / "SmTIAS-Lab" + + def test_env_var_missing_dir_raises_with_hint(self, monkeypatch, tmp_path): + missing = tmp_path / "nope" + monkeypatch.setenv(LAB_ENV_VAR, str(missing)) + with pytest.raises(FileNotFoundError) as exc: + lab_root() + assert str(missing) in str(exc.value) + assert "SMTIAS_LAB" in str(exc.value) + + def test_default_is_sibling_smtias_lab(self, monkeypatch, tmp_path): + """未設定ならリポジトリの隣の SmTIAS-Lab を使う.""" + monkeypatch.delenv(LAB_ENV_VAR, raising=False) + fake_repo = tmp_path / "SmTIAS-LightSim" + fake_repo.mkdir() + (tmp_path / "SmTIAS-Lab").mkdir() + monkeypatch.setattr(lab, "REPO_ROOT", fake_repo) + assert lab_root() == tmp_path / "SmTIAS-Lab" + + def test_default_missing_raises_with_hint(self, monkeypatch, tmp_path): + monkeypatch.delenv(LAB_ENV_VAR, raising=False) + fake_repo = tmp_path / "SmTIAS-LightSim" + fake_repo.mkdir() + monkeypatch.setattr(lab, "REPO_ROOT", fake_repo) + with pytest.raises(FileNotFoundError) as exc: + lab_root() + msg = str(exc.value) + assert "SmTIAS-Lab" in msg + assert "SMTIAS_LAB" in msg + + def test_real_default_points_next_to_repo(self, monkeypatch): + """手元に ../SmTIAS-Lab があれば,未設定時にそこを指す.""" + monkeypatch.delenv(LAB_ENV_VAR, raising=False) + repo = Path(__file__).resolve().parents[1] + expected = repo.parent / "SmTIAS-Lab" + if not expected.is_dir(): + pytest.skip(f"隣に SmTIAS-Lab がありません: {expected}") + assert lab_root().resolve() == expected.resolve() + + +class TestLabPath: + def test_joins_experiments_dir(self, fake_lab): + p = lab_path(_EXP, "raw", "a.dng") + assert p == fake_lab.resolve() / "experiments" / _EXP / "raw" / "a.dng" + + def test_does_not_check_existence(self, fake_lab): + p = lab_path(_EXP, "raw", "missing.dng") + assert not p.exists() + + @pytest.mark.parametrize( + "parts", + [ + ("..",), + ("../other",), + (_EXP, ".."), + (_EXP, "raw", "../../x"), + (_EXP, "..", "secret.txt"), + ], + ) + def test_rejects_parent_dir(self, fake_lab, parts): + with pytest.raises(ValueError): + lab_path(*parts) + + def test_rejects_absolute_path(self, fake_lab, tmp_path): + with pytest.raises(ValueError): + lab_path(str(tmp_path / "abs")) + with pytest.raises(ValueError): + lab_path(_EXP, str(tmp_path / "abs.dng")) + + def test_rejects_posix_absolute_path(self, fake_lab): + with pytest.raises(ValueError): + lab_path(_EXP, "/etc/passwd") + + def test_rejects_empty(self, fake_lab): + with pytest.raises(ValueError): + lab_path("") + with pytest.raises(ValueError): + lab_path(_EXP, "") + + def test_validation_before_lab_lookup(self, monkeypatch, tmp_path): + """不正なパスは Lab が無くても ValueError(FileNotFoundError ではない).""" + monkeypatch.setenv(LAB_ENV_VAR, str(tmp_path / "nope")) + with pytest.raises(ValueError): + find_lab_file("..", "x") + + +class TestLabFile: + def test_returns_existing_file(self, fake_lab): + f = fake_lab / "experiments" / _EXP / "raw" / "a.dng" + f.write_bytes(b"x") + assert lab_file(_EXP, "raw", "a.dng") == f.resolve() + + def test_missing_file_message(self, fake_lab): + with pytest.raises(FileNotFoundError) as exc: + lab_file(_EXP, "raw", "missing.dng") + msg = str(exc.value) + assert "missing.dng" in msg + assert "SMTIAS_LAB" in msg + + def test_directory_is_not_a_file(self, fake_lab): + with pytest.raises(FileNotFoundError): + lab_file(_EXP, "raw") + + def test_missing_lab_message_explains_setup(self, monkeypatch, tmp_path): + monkeypatch.setenv(LAB_ENV_VAR, str(tmp_path / "nope")) + with pytest.raises(FileNotFoundError) as exc: + lab_file(_EXP, "raw", "a.dng") + assert "SMTIAS_LAB" in str(exc.value) + + +class TestFindLabFile: + def test_returns_path_when_exists(self, fake_lab): + f = fake_lab / "experiments" / _EXP / "raw" / "a.dng" + f.write_bytes(b"x") + assert find_lab_file(_EXP, "raw", "a.dng") == f.resolve() + + def test_none_when_file_missing(self, fake_lab): + assert find_lab_file(_EXP, "raw", "missing.dng") is None + + def test_none_when_lab_missing(self, monkeypatch, tmp_path): + monkeypatch.setenv(LAB_ENV_VAR, str(tmp_path / "nope")) + assert find_lab_file(_EXP, "raw", "a.dng") is None + + def test_invalid_path_still_raises(self, fake_lab): + with pytest.raises(ValueError): + find_lab_file(_EXP, "..", "a.dng") + + +class TestShots: + def test_v3_shot_keys(self): + """ENV_04: 現行機の全灯・単灯 3 種(キー full/bottom/left/right).""" + assert set(V3_SHOTS) == {"full", "bottom", "left", "right"} + + def test_full_shot_is_2026_06_01_all_leds(self): + full = V3_SHOTS["full"] + assert full.experiment == "2026-06-01_v3_all_leds" + assert full.stem == "SmTIAS_QM_20260601_124500" + + def test_file_names(self): + shot = LabShot(_EXP, "S_1") + assert shot.dng_name == "S_1.dng" + assert shot.meta_name == "S_1.meta.json" + + def test_shot_dng_and_meta_are_in_raw(self, fake_lab): + raw = fake_lab / "experiments" / _EXP / "raw" + (raw / "S_1.dng").write_bytes(b"x") + (raw / "S_1.meta.json").write_text("{}", encoding="utf-8") + shot = LabShot(_EXP, "S_1") + assert shot_dng(shot) == (raw / "S_1.dng").resolve() + assert shot_meta(shot) == (raw / "S_1.meta.json").resolve() + + def test_shot_dng_missing_raises(self, fake_lab): + with pytest.raises(FileNotFoundError): + shot_dng(LabShot(_EXP, "absent")) + + def test_constant_paths_are_valid_parts(self, fake_lab): + """定数のパスは lab_path に渡せる(.. や絶対パスを含まない).""" + lab_path(*V3_FULL_UNIFORMITY_CSV) + lab_path(*V3_PNG_WHITEBOARD) + + +def test_real_lab_has_v3_shots(): + """手元に Lab のデータがあれば,V3_SHOTS の DNG と meta.json がすべて揃っている.""" + full = V3_SHOTS["full"] + if find_lab_file(full.experiment, "raw", full.dng_name) is None: + pytest.skip("SmTIAS-Lab に実機のデータがありません") + for key, shot in V3_SHOTS.items(): + assert find_lab_file(shot.experiment, "raw", shot.dng_name) is not None, key + assert find_lab_file(shot.experiment, "raw", shot.meta_name) is not None, key + assert find_lab_file(*V3_FULL_UNIFORMITY_CSV) is not None