calibrate

This commit is contained in:
2026-10-06 17:58:35 +03:00
parent 86222f5f93
commit 476cfe0b17
21 changed files with 1666 additions and 14 deletions
+144
View File
@@ -0,0 +1,144 @@
"""Юнит-тесты калибровщика настроек сравнения (app/cv/calibration.py, docs/08 §8.4).
Логика подбора порогов проверяется на синтетических метриках пар (без CV);
сквозной смоук — на синтетических изображениях (tests/synth.py, docs/08 §8.6)
через CLI-обёртку tools/calibrate.py (то же ядро, что и в /api/v1/calibrate).
"""
from __future__ import annotations
import pytest
import numpy as np
from app.cv.calibration import (
Grid,
PairRow,
_threshold_candidates,
derive_uncertain_min,
select_thresholds,
verdict_of,
)
from app.cv.exceptions import CalibrationDatasetInvalid
from tests import synth
from tests.conftest import make_config
from tools.calibrate import calibrate
def _row(is_positive: bool, inliers: int, ratio: float = 0.6, coverage: float = 0.3) -> PairRow:
return PairRow("probe", "ref", is_positive, good_matches=200, inliers=inliers,
inlier_ratio=ratio, coverage=coverage)
# ------------------------------------------------------------- кандидаты порогов
def test_candidates_clip_to_allowed_range():
# наблюдённые значения ниже допустимого минимума (5) — порог не может опуститься ниже
assert list(_threshold_candidates(np.array([3, 4]), 5, 1000, is_int=True)) == [5, 1000]
def test_candidates_are_midpoints_and_bounds():
cands = _threshold_candidates(np.array([10, 20, 30]), 5, 1000, is_int=True)
assert list(cands) == [5, 15, 25, 1000]
# ------------------------------------------------------------- подбор порогов
def test_select_perfect_separation():
rows = [
_row(True, 80, 0.6, 0.30),
_row(True, 100, 0.7, 0.40),
_row(True, 120, 0.65, 0.35),
_row(False, 5, 0.1, 0.01),
_row(False, 10, 0.2, 0.01),
_row(False, 30, 0.15, 0.02),
]
sel = select_thresholds(rows)
assert sel.f1 == 1.0 and sel.tp == 3 and sel.fp == 0 and sel.fn == 0
assert 30 < sel.match_inliers_min <= 80
assert 0.2 < sel.match_inliers_ratio_min <= 0.6
assert 0.02 < sel.match_coverage_min <= 0.3
assert sel.margin > 0
assert sel.uncertain_inliers_min == 31 # над худшим негативом (30)
for row in rows:
expected = "match" if row.is_positive else "no_match"
assert verdict_of(row, sel) == expected
def test_select_prefers_zero_false_matches_on_f1_tie():
# ti=5: tp=2, fp=2 → F1=0.667; ti=80: tp=1, fp=0 → F1=0.667.
# При равном F1 выбираем вариант без ложных срабатываний.
rows = [_row(True, 50), _row(True, 90), _row(False, 60), _row(False, 70)]
sel = select_thresholds(rows)
assert sel.f1 == pytest.approx(2 / 3)
assert sel.fp == 0 and sel.tp == 1
assert sel.match_inliers_min == 80 # максимум_TP-позитив (90) выше худшего негатива (70)
assert sel.uncertain_inliers_min == 71
def test_select_degenerate_metrics_do_not_crash():
rows = [_row(True, 3), _row(False, 0)]
sel = select_thresholds(rows)
assert sel.f1 == 0.0 and sel.tp == 0
def test_derive_uncertain_min_clamped_by_match_threshold():
assert derive_uncertain_min(np.array([30, 12]), match_inliers_min=60) == 31
assert derive_uncertain_min(np.array([90, 40]), match_inliers_min=80) == 80
# ------------------------------------------------------------- сквозной смоук
@pytest.fixture()
def small_facade_dirs(tmp_path):
"""Позитивы: синтетический «фасад» + его проективный поворот;
негатив: другой фасад (другая раскраска окон)."""
pos = tmp_path / "pos"
neg = tmp_path / "neg"
pos.mkdir()
neg.mkdir()
facade = synth.make_facade(seed=7, width=900, height=640)
(pos / "a.jpg").write_bytes(synth.encode_jpg(facade))
(pos / "b.jpg").write_bytes(synth.encode_jpg(synth.warp_perspective(facade)))
(neg / "c.jpg").write_bytes(synth.encode_jpg(synth.make_facade(seed=99, width=900, height=640)))
return pos, neg
def test_calibrate_synthetic(small_facade_dirs):
pos, neg = small_facade_dirs
outcome = calibrate(
pos, neg, make_config(),
Grid(geometry_models=("homography",), lowe_ratios=(0.75,), ransac_thresholds=(5.0,)),
jobs=2,
)
# пробы: a, b, c; эталоны: a, b → 4 упорядоченные пары (2 позитивные, 2 негативные)
assert outcome.pairs_total == 4
assert outcome.pairs_positive == 2
assert outcome.skipped == []
best = outcome.best
assert best.selection.fp == 0
assert best.selection.tp == 2
assert best.selection.f1 == 1.0
assert outcome.settings["comparison"]["geometry_model"] == "homography"
verdicts = {(r.probe, r.ref): verdict_of(r, best.selection) for r in best.rows}
assert verdicts[("a.jpg", "b.jpg")] == "match"
assert verdicts[("b.jpg", "a.jpg")] == "match"
assert verdicts[("c.jpg", "a.jpg")] != "match"
assert verdicts[("c.jpg", "b.jpg")] != "match"
# выданные настройки валидны для сервиса и самопроверка боевым пайплайном сошлась
assert outcome.selfcheck["matched"] == outcome.selfcheck["checked"] == 4
assert outcome.settings["comparison"]["lowe_ratio"] == 0.75
def test_calibrate_requires_minimum_inputs(tmp_path):
pos = tmp_path / "pos"
neg = tmp_path / "neg"
pos.mkdir()
neg.mkdir()
(pos / "only.jpg").write_bytes(synth.encode_jpg(synth.make_facade(seed=3, width=640, height=480)))
with pytest.raises(CalibrationDatasetInvalid):
calibrate(pos, neg, make_config(), jobs=1) # один позитив — нет позитивных пар
(pos / "second.jpg").write_bytes(
synth.encode_jpg(synth.make_facade(seed=4, width=640, height=480))
)
with pytest.raises(CalibrationDatasetInvalid):
calibrate(pos, neg, make_config(), jobs=1) # нет негативов