Newer
Older
TongueSegModel / tests / data / test_split.py
"""学習用と検証用の分割と `split.json`(`data/split.py`)のテスト.

期待値は SPEC_02「分割」(`subset` が `train` の組を分ける.既定は画像単位のランダム分割で
学習 2/3・検証 1/3・端数は検証側.患者単位では同じ患者が学習と検証にまたがらない)と
SPEC_01「実験の出力」の `split.json` を基準にする.
分割は純関数なので,`SegRecord` を直接作って確かめる(ファイルは要らない).
"""

from __future__ import annotations

import json
import random
from pathlib import Path

import pytest
import torch

from tongue_seg_model.data.bundle import SUBSET_TEST, SUBSET_TRAIN, SegRecord
from tongue_seg_model.data.split import (
    SPLIT_FILENAME,
    SplitResult,
    build_split_document,
    split_records,
    train_count,
    write_split_json,
)

SEED = 2021
SUBJECT_MARK = "SubjMarkXk3"
PATH_MARK = "PathMarkQz7"


def _record(index: int, *, subset: str = SUBSET_TRAIN, subject: str | None = None) -> SegRecord:
    return SegRecord(
        image_path=Path(PATH_MARK) / f"{index}-image.png",
        mask_path=Path(PATH_MARK) / f"{index}-mask.png",
        subset=subset,
        subject_id=f"{SUBJECT_MARK}-{index}" if subject is None else subject,
        image_line=2 + 2 * index,
        mask_line=3 + 2 * index,
    )


def _records(n_train: int, n_test: int = 0) -> list[SegRecord]:
    records = [_record(i) for i in range(n_train)]
    records += [_record(n_train + i, subset=SUBSET_TEST) for i in range(n_test)]
    return records


def _subject_records(sizes: list[int], n_test: int = 0) -> list[SegRecord]:
    """患者ごとの組の数 `sizes` で train の組を作る(+ test の組)."""
    records: list[SegRecord] = []
    index = 0
    for patient, size in enumerate(sizes):
        for _ in range(size):
            records.append(_record(index, subject=f"{SUBJECT_MARK}-p{patient:02d}"))
            index += 1
    for _ in range(n_test):
        records.append(_record(index, subset=SUBSET_TEST, subject=f"{SUBJECT_MARK}-t"))
        index += 1
    return records


def _lines(records: tuple[SegRecord, ...]) -> list[int]:
    return [r.image_line for r in records]


# ---------------------------------------------------------------------------
# train_count
# ---------------------------------------------------------------------------


@pytest.mark.parametrize(
    ("n", "ratio", "expected"),
    [(10, 2 / 3, 6), (9, 2 / 3, 6), (12, 2 / 3, 8), (3, 2 / 3, 2), (1, 2 / 3, 0), (7, 0.5, 3)],
)
def test_train_count_is_floor_of_n_times_ratio(n: int, ratio: float, expected: int) -> None:
    assert train_count(n, ratio) == expected


# ---------------------------------------------------------------------------
# random(画像単位)
# ---------------------------------------------------------------------------


@pytest.mark.parametrize(("n", "ratio", "n_train"), [(10, 2 / 3, 6), (9, 2 / 3, 6), (5, 0.5, 2)])
def test_random_split_counts_round_down_to_train(n: int, ratio: float, n_train: int) -> None:
    result = split_records(_records(n), "random", ratio, SEED)

    assert len(result.train) == n_train
    assert len(result.val) == n - n_train


def test_random_split_is_reproducible_with_same_seed() -> None:
    records = _records(20, 3)

    first = split_records(records, "random", 2 / 3, SEED)
    second = split_records(records, "random", 2 / 3, SEED)

    assert first == second
    assert isinstance(first, SplitResult)


def test_random_split_changes_with_seed() -> None:
    records = _records(20)

    a = split_records(records, "random", 2 / 3, 0)
    b = split_records(records, "random", 2 / 3, 1)

    assert set(_lines(a.train)) != set(_lines(b.train))


def test_random_split_is_disjoint_and_covers_train_subset() -> None:
    records = _records(10, 4)

    result = split_records(records, "random", 2 / 3, SEED)

    train_lines, val_lines = set(_lines(result.train)), set(_lines(result.val))
    assert not train_lines & val_lines
    expected = {r.image_line for r in records if r.subset == SUBSET_TRAIN}
    assert train_lines | val_lines == expected
    assert len(result.train) + len(result.val) == 10
    assert all(r.subset == SUBSET_TRAIN for r in result.train + result.val)


def test_random_split_ignores_test_records() -> None:
    train_only = _records(10)
    with_test = train_only + [_record(100 + i, subset=SUBSET_TEST) for i in range(5)]

    assert split_records(with_test, "random", 2 / 3, SEED) == split_records(
        train_only, "random", 2 / 3, SEED
    )


def test_random_split_independent_of_global_rng() -> None:
    records = _records(15)

    torch.manual_seed(1)
    random.seed(1)
    first = split_records(records, "random", 2 / 3, SEED)
    torch.manual_seed(999)
    random.seed(999)
    torch.rand(10)
    second = split_records(records, "random", 2 / 3, SEED)

    assert first == second


def test_random_split_matches_original_random_split() -> None:
    # 原本: fix_rand(2021) の直後に random_split(dataset, [int(n*r), n-int(n*r)]).
    n, ratio = 13, 2 / 3
    records = _records(n)
    torch.manual_seed(SEED)
    k = int(n * ratio)
    original_train, original_val = torch.utils.data.random_split(range(n), [k, n - k])

    result = split_records(records, "random", ratio, SEED)

    assert [records.index(r) for r in result.train] == list(original_train)
    assert [records.index(r) for r in result.val] == list(original_val)


@pytest.mark.parametrize(("n", "ratio"), [(1, 2 / 3), (0, 2 / 3), (2, 0.4)])
def test_random_split_raises_when_a_side_is_empty(n: int, ratio: float) -> None:
    with pytest.raises(ValueError):
        split_records(_records(n, 3), "random", ratio, SEED)


def test_random_split_raises_without_train_records() -> None:
    with pytest.raises(ValueError):
        split_records(_records(0, 6), "random", 2 / 3, SEED)


# ---------------------------------------------------------------------------
# subject(患者単位)
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("seed", [0, 1, 2, SEED])
def test_subject_split_keeps_each_patient_on_one_side(seed: int) -> None:
    records = _subject_records([3, 1, 2, 4, 2, 1, 3], n_test=2)

    result = split_records(records, "subject", 2 / 3, seed)

    train_subjects = {r.subject_id for r in result.train}
    val_subjects = {r.subject_id for r in result.val}
    assert train_subjects and val_subjects
    assert not train_subjects & val_subjects
    train_lines = set(_lines(result.train))
    val_lines = set(_lines(result.val))
    assert not train_lines & val_lines
    assert train_lines | val_lines == {r.image_line for r in records if r.subset == SUBSET_TRAIN}
    # 学習用は int(n × train_ratio) 件を超えない.
    assert len(result.train) <= train_count(16, 2 / 3)


def test_subject_split_is_reproducible_with_same_seed() -> None:
    records = _subject_records([2, 2, 3, 1, 2, 2])

    assert split_records(records, "subject", 2 / 3, SEED) == split_records(
        records, "subject", 2 / 3, SEED
    )


def test_subject_split_changes_with_seed() -> None:
    records = _subject_records([2] * 10)

    sides = {
        frozenset(_lines(split_records(records, "subject", 2 / 3, seed).train)) for seed in range(5)
    }

    assert len(sides) > 1


def test_subject_split_does_not_depend_on_input_order() -> None:
    records = _subject_records([3, 1, 2, 4, 2, 1, 3])
    shuffled = list(records)
    random.Random(0).shuffle(shuffled)

    a = split_records(records, "subject", 2 / 3, SEED)
    b = split_records(shuffled, "subject", 2 / 3, SEED)

    assert set(_lines(a.train)) == set(_lines(b.train))
    assert set(_lines(a.val)) == set(_lines(b.val))


def test_subject_split_independent_of_global_rng() -> None:
    records = _subject_records([2, 3, 1, 2, 2])

    torch.manual_seed(5)
    random.seed(5)
    first = split_records(records, "subject", 2 / 3, SEED)
    torch.manual_seed(123)
    random.seed(123)
    second = split_records(records, "subject", 2 / 3, SEED)

    assert first == second


def test_subject_split_ignores_test_records() -> None:
    records = _subject_records([2, 2, 2, 2])
    with_test = records + [
        _record(100, subset=SUBSET_TEST, subject=f"{SUBJECT_MARK}-p00"),
        _record(101, subset=SUBSET_TEST, subject=""),
    ]

    result = split_records(with_test, "subject", 2 / 3, SEED)

    assert result == split_records(records, "subject", 2 / 3, SEED)


def test_subject_split_raises_on_empty_subject_id() -> None:
    records = _subject_records([2, 2, 2])
    records.append(_record(50, subject=""))

    with pytest.raises(ValueError, match="1 件") as e:
        split_records(records, "subject", 2 / 3, SEED)
    assert SUBJECT_MARK not in str(e.value)


def test_subject_split_raises_with_one_patient() -> None:
    records = _subject_records([5])

    with pytest.raises(ValueError) as e:
        split_records(records, "subject", 2 / 3, SEED)
    assert SUBJECT_MARK not in str(e.value)


def test_subject_split_raises_when_train_side_is_empty() -> None:
    # 患者 2 人(3 組ずつ)で目標 int(6 × 0.4) = 2 件 → どの患者も入らない.
    records = _subject_records([3, 3])

    with pytest.raises(ValueError):
        split_records(records, "subject", 0.4, SEED)


# ---------------------------------------------------------------------------
# split.json
# ---------------------------------------------------------------------------


def _document(records: list[SegRecord], bundle: dict | None = None) -> dict:
    split = split_records(records, "random", 2 / 3, SEED)
    return build_split_document(
        split, records, method="random", seed=SEED, train_ratio=2 / 3, bundle=bundle
    )


def test_split_document_contents_are_consistent() -> None:
    records = _records(10, 3)
    split = split_records(records, "random", 2 / 3, SEED)
    fingerprint = {"name": "synthetic", "version": 1, "manifest_sha256": "0" * 64}

    document = build_split_document(
        split, records, method="random", seed=SEED, train_ratio=2 / 3, bundle=fingerprint
    )

    assert document["method"] == "random"
    assert document["seed"] == SEED
    assert document["train_ratio"] == 2 / 3
    assert document["bundle"] == fingerprint
    assert document["counts"] == {"train": 6, "val": 4, "test": 3}
    lines = document["image_lines"]
    assert set(lines) == {"train", "val", "test"}
    for name in ("train", "val", "test"):
        assert lines[name] == sorted(lines[name])
        assert len(lines[name]) == document["counts"][name]
    assert lines["train"] == sorted(_lines(split.train))
    assert lines["val"] == sorted(_lines(split.val))
    assert lines["test"] == [r.image_line for r in records if r.subset == SUBSET_TEST]
    all_lines = lines["train"] + lines["val"] + lines["test"]
    assert sorted(all_lines) == sorted(r.image_line for r in records)


def test_split_document_bundle_is_null_without_fingerprint() -> None:
    assert _document(_records(6, 1))["bundle"] is None


def test_split_document_has_no_ids_or_paths() -> None:
    text = json.dumps(_document(_records(6, 2)), ensure_ascii=False)

    assert SUBJECT_MARK not in text
    assert PATH_MARK not in text


def test_write_split_json_round_trips(tmp_path: Path) -> None:
    document = _document(
        _records(9, 2), {"name": "synthetic", "version": 1, "manifest_sha256": "a" * 64}
    )
    path = tmp_path / SPLIT_FILENAME

    written = write_split_json(path, document)

    assert written == path
    assert SPLIT_FILENAME == "split.json"
    assert json.loads(path.read_text(encoding="utf-8")) == document


def test_write_split_json_does_not_overwrite(tmp_path: Path) -> None:
    path = tmp_path / SPLIT_FILENAME
    path.write_text("existing", encoding="utf-8")

    with pytest.raises(ValueError) as e:
        write_split_json(path, _document(_records(6, 1)))
    assert path.read_text(encoding="utf-8") == "existing"
    assert str(tmp_path) not in str(e.value)