File size: 6,477 Bytes
473c56f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
115
116
117
118
119
120
121
122
123
124
"""
GIN (global intensity non-linear) augmentation applied to ONE channel (FLAIR) on the GPU, after Ouyang et al. (TMI 2022,
causality-inspired single-source domain generalisation): a freshly randomised shallow conv net (3-4 layers, kernel 1 or 3,
LeakyReLU, N(0,1) weights) maps the channel to a new appearance; output re-standardised to the input's brain mean/std and
mixed with the original (alpha ~ U(0, 1)). Applied per sample with probability p. Brain = T1 channel != 0.
"""
import torch, torch.nn.functional as F


@torch.no_grad()
def gin_channel(x: torch.Tensor, ch: int = 1, p: float = 0.8, gen: torch.Generator = None, hidden: int = 4,
                faithful: bool = False) -> torch.Tensor:
    """faithful=True: Ouyang et al. reference settings (4 layers, `hidden` intermediate channels, N(0,1) weights + bias,
    kernel from {1, 3} per layer, output rescaled to the input's Frobenius norm inside the brain)."""
    B = x.shape[0]
    for b in range(B):
        if torch.rand(1, generator=gen).item() >= p:
            continue
        v = x[b:b + 1, ch:ch + 1].float()
        brain = (x[b:b + 1, 0:1] != 0)
        if brain.sum() < 100:
            continue
        nl = 4 if faithful else int(torch.randint(3, 5, (1,), generator=gen)); C = hidden
        h = v
        for i in range(nl):
            k = int([1, 3][torch.randint(0, 2, (1,), generator=gen)])
            cin = h.shape[1]; cout = 1 if i == nl - 1 else C
            w = torch.randn(cout, cin, k, k, k, generator=gen).to(h.device) / (1.0 if faithful else (cin * k ** 3) ** 0.5)
            bias = torch.randn(cout, generator=gen).to(h.device) if faithful else None
            h = F.conv3d(h, w, bias=bias, padding=k // 2)
            if i < nl - 1:
                h = F.leaky_relu(h, 0.2)
        a = torch.rand(1, generator=gen).item()
        if faithful:   # alpha-blend, then rescale to the input's Frobenius norm (brain voxels)
            h = (h - h[brain].mean()) / (h[brain].std() + 1e-6) * (v[brain].std() + 1e-6) + v[brain].mean()
            out = a * h + (1 - a) * v
            out = out * (v[brain].norm() / (out[brain].norm() + 1e-6))
        else:
            mu, sd = v[brain].mean(), v[brain].std() + 1e-6
            hm, hs = h[brain].mean(), h[brain].std() + 1e-6
            h = (h - hm) / hs * sd + mu
            out = a * h + (1 - a) * v
        x[b:b + 1, ch:ch + 1] = torch.where(brain, out, v).to(x.dtype)
    return x


@torch.no_grad()
def ipa_pair(x: torch.Tensor, ch: int = 1, gen: torch.Generator = None, faithful: bool = False):
    """GIN-IPA style pair: two independent GIN views of channel `ch` (p = 1), and an interventional mix
    v_ipa = m * v1 + (1 - m) * v2 with a smooth random spatial mask m (low-res Gaussian field, upsampled, sigmoid).
    Returns (view1, view_ipa)."""
    kw = dict(hidden=2, faithful=True) if faithful else {}
    v1 = gin_channel(x.clone(), ch=ch, p=1.0, gen=gen, **kw)
    v2 = gin_channel(x.clone(), ch=ch, p=1.0, gen=gen, **kw)
    B, _, D, H, W = x.shape
    low = torch.randn(B, 1, max(2, D // 16), max(2, H // 16), max(2, W // 16), generator=gen).to(x.device)
    m = torch.sigmoid(4.0 * F.interpolate(low, size=(D, H, W), mode="trilinear", align_corners=False))
    vi = v1.clone()
    vi[:, ch:ch + 1] = m * v1[:, ch:ch + 1] + (1 - m) * v2[:, ch:ch + 1]
    return v1, vi


# ------------------------------------------------------------------------------- extreme, border-free randomisations
# All operate on the whole (realistic) image: edges come from G1 / real T1 anatomy, never from label maps.
@torch.no_grad()
def gin_extreme(x, ch=1, p=1.0, gen=None):
    """GIN-X: 4-6 layers, 8 hidden channels, kernels {1, 3, 5}, alpha ~ U(0.6, 1), contrast inversion with p = 0.25."""
    for b in range(x.shape[0]):
        if torch.rand(1, generator=gen).item() >= p:
            continue
        v = x[b:b + 1, ch:ch + 1].float(); brain = (x[b:b + 1, 0:1] != 0)
        if brain.sum() < 100:
            continue
        h = v; nl = int(torch.randint(4, 7, (1,), generator=gen))
        for i in range(nl):
            k = int([1, 3, 5][torch.randint(0, 3, (1,), generator=gen)]); cin = h.shape[1]; cout = 1 if i == nl - 1 else 8
            w = torch.randn(cout, cin, k, k, k, generator=gen).to(h.device) / (cin * k ** 3) ** 0.5
            h = F.conv3d(h, w, padding=k // 2)
            if i < nl - 1:
                h = F.leaky_relu(h, 0.2)
        if torch.rand(1, generator=gen).item() < 0.25:
            h = -h
        h = (h - h[brain].mean()) / (h[brain].std() + 1e-6) * (v[brain].std() + 1e-6) + v[brain].mean()
        a = 0.6 + 0.4 * torch.rand(1, generator=gen).item()
        x[b:b + 1, ch:ch + 1] = torch.where(brain, a * h + (1 - a) * v, v).to(x.dtype)
    return x


@torch.no_grad()
def bezier_global(x, ch=1, p=1.0, gen=None):
    """SLAug-style global random cubic Bezier intensity curve on the whole channel (inversion with p = 0.5)."""
    for b in range(x.shape[0]):
        if torch.rand(1, generator=gen).item() >= p:
            continue
        v = x[b, ch].float(); brain = x[b, 0] != 0
        if brain.sum() < 100:
            continue
        lo, hi = torch.quantile(v[brain][::max(1, int(brain.sum()) // 200000)], torch.tensor([0.005, 0.995], device=v.device))
        t = ((v - lo) / (hi - lo + 1e-6)).clamp(0, 1)
        p1, p2 = torch.rand(2, generator=gen).tolist()
        y = 3 * (1 - t) ** 2 * t * p1 + 3 * (1 - t) * t ** 2 * p2 + t ** 3      # control points (0,0),(.,p1),(.,p2),(1,1)
        if torch.rand(1, generator=gen).item() < 0.5:
            y = 1 - y
        y = (y - y[brain].mean()) / (y[brain].std() + 1e-6) * (v[brain].std() + 1e-6) + v[brain].mean()
        x[b, ch] = torch.where(brain, y, v).to(x.dtype)
    return x


@torch.no_grad()
def modality_mix(x, ch=1, p=1.0, gen=None):
    """FLAIR channel := a * FLAIR + b * T1 (a ~ U(0, 1), b ~ U(-1, 1)), re-standardised: an arbitrary contrast of the
    same real anatomy (border-free)."""
    for b_ in range(x.shape[0]):
        if torch.rand(1, generator=gen).item() >= p:
            continue
        f = x[b_, ch].float(); t = x[b_, 0].float(); brain = t != 0
        if brain.sum() < 100:
            continue
        a = torch.rand(1, generator=gen).item(); bb = 2 * torch.rand(1, generator=gen).item() - 1
        y = a * f + bb * t
        y = (y - y[brain].mean()) / (y[brain].std() + 1e-6) * (f[brain].std() + 1e-6) + f[brain].mean()
        x[b_, ch] = torch.where(brain, y, f).to(x.dtype)
    return x