File size: 4,123 Bytes
6b02758
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
"""Per-domain tensor transforms (torchvision.transforms.v2, no PIL)."""

from __future__ import annotations

from collections.abc import Callable

import torch
from torch import nn
from torchvision.transforms import v2

from capstone.data.config import DataConfig
from capstone.data.domains import DOMAIN_ORDER

# Per-domain training augmentations. Clinical reason sits beside each entry.
# Applied only when split == "train" and config.augment is True.
DOMAIN_TRAIN_AUGMENTATIONS: dict[str, list[nn.Module]] = {
    # Orientation carries no meaning in histopathology tiles.
    "pathmnist": [
        v2.RandomHorizontalFlip(p=0.5),
        v2.RandomVerticalFlip(p=0.5),
        # Discrete 90-degree rotations only.
        # (Implemented below as Random90DegreeRotation.)
    ],
    # Orientation carries no meaning in kidney cortex microscopy.
    "tissuemnist": [
        v2.RandomHorizontalFlip(p=0.5),
        v2.RandomVerticalFlip(p=0.5),
    ],
    # Retinal OCT B-scans have a consistent anatomical orientation; a small
    # rotation of up to 5 degrees only. Conservative default pending group confirmation.
    "octmnist": [
        v2.RandomRotation(degrees=5),
    ],
    # No horizontal flip under any circumstances: laterality is clinically
    # meaningful in chest radiography and mirroring inverts left/right findings.
    # Small rotation up to 5 degrees and translation up to 2 percent only.
    "chestmnist": [
        v2.RandomRotation(degrees=5),
        v2.RandomAffine(degrees=0, translate=(0.02, 0.02)),
    ],
}


class Random90DegreeRotation(nn.Module):
    """Rotate by a random multiple of 90 degrees about the spatial axes."""

    def forward(self, image: torch.Tensor) -> torch.Tensor:
        k = int(torch.randint(0, 4, ()).item())
        if k == 0:
            return image
        return torch.rot90(image, k, dims=(-2, -1))


# Attach the shared 90-degree rotation after the dict is defined so each
# histopathology/microscopy domain gets its own module instance.
DOMAIN_TRAIN_AUGMENTATIONS["pathmnist"].append(Random90DegreeRotation())
DOMAIN_TRAIN_AUGMENTATIONS["tissuemnist"].append(Random90DegreeRotation())


def _contains_horizontal_flip(module: nn.Module) -> bool:
    if isinstance(module, v2.RandomHorizontalFlip):
        return True
    for child in module.children():
        if _contains_horizontal_flip(child):
            return True
    # v2.Compose stores transforms in .transforms
    transforms = getattr(module, "transforms", None)
    if transforms is not None:
        for child in transforms:
            if isinstance(child, nn.Module) and _contains_horizontal_flip(child):
                return True
            if isinstance(child, v2.RandomHorizontalFlip):
                return True
    return False


def assert_no_chestmnist_horizontal_flip(transform: Callable) -> None:
    """Fail loudly if a chestmnist pipeline ever includes a horizontal flip."""
    if isinstance(transform, nn.Module) and _contains_horizontal_flip(transform):
        msg = (
            "chestmnist transform pipeline must never contain RandomHorizontalFlip; "
            "laterality is clinically meaningful"
        )
        raise AssertionError(msg)


def build_transform(domain: str, split: str, config: DataConfig) -> Callable:
    """Build a tensor transform for ``domain`` and ``split``.

    Val and test are always deterministic normalisation with no randomness.
    Training augmentation is applied only when ``config.augment`` is True.
    """
    # Lazy import avoids a circular dependency with registry.py.
    from capstone.data.registry import NORM_MEAN, NORM_STD

    if domain not in DOMAIN_ORDER:
        msg = f"unknown domain {domain!r}"
        raise KeyError(msg)

    steps: list[nn.Module] = [
        v2.ToDtype(torch.float32, scale=True),
    ]

    if split == "train" and config.augment:
        steps.extend(DOMAIN_TRAIN_AUGMENTATIONS[domain])

    steps.append(v2.Normalize(mean=NORM_MEAN, std=NORM_STD))
    pipeline = v2.Compose(steps)

    if domain == "chestmnist":
        assert_no_chestmnist_horizontal_flip(pipeline)

    return pipeline