File size: 5,484 Bytes
8fca640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
125
126
127
128
129
130
"""Combine model positions only, in the original structural coordinate grid."""

import numpy as np
from src.inference.postprocess import transform


def combine_positions(positions, method="mean", weights=None):
    if not positions:
        raise ValueError("No ensemble members")
    shape = positions[0].shape
    if any(p.shape != shape for p in positions):
        raise ValueError("Ensemble geometry differs")
    stack = np.stack(positions).astype(np.float32, copy=False)
    if not np.isfinite(stack).all():
        raise ValueError("Nonfinite ensemble member")
    if method == "mean":
        if weights is None:
            return stack.mean(axis=0, dtype=np.float32)
        weight = np.asarray(weights, dtype=np.float32)
        if (
            weight.shape != (len(positions),)
            or not np.isfinite(weight).all()
            or (weight < 0).any()
            or weight.sum() <= 0
        ):
            raise ValueError("Invalid ensemble weights")
        weight = weight / weight.sum()
        return (stack * weight.reshape((-1,) + (1,) * len(shape))).sum(
            0, dtype=np.float32
        )
    if weights is not None:
        raise ValueError("Only means accept weights")
    if method == "median":
        return np.median(stack, axis=0).astype(np.float32)
    raise ValueError("Unknown position combination")


def finish_positions(positions, device, height, configuration):
    return transform(positions, device, height, configuration or {})


def combine_named_heads(positions, member_names, boundary_keys, device, configuration):
    """Select fixed trained heads by device/anatomy; no case-dependent routing."""
    weighted = configuration.get("head_weights_by_device")
    if weighted is not None:
        if (
            "head_source_by_device" in configuration
            or "weights" in configuration
            or configuration.get("method") != "weighted_heads"
        ):
            raise ValueError(
                "Weighted anatomical heads require their own explicit combination method"
            )
        if (
            not positions
            or len(member_names) != len(positions)
            or len(set(member_names)) != len(member_names)
        ):
            raise ValueError("Invalid weighted head sources")
        if not boundary_keys or len(set(boundary_keys)) != len(boundary_keys):
            raise ValueError("Invalid weighted boundary identities")
        shape = positions[0].shape
        if (
            len(shape) != 3
            or shape[0] != len(boundary_keys)
            or any(p.shape != shape or not np.isfinite(p).all() for p in positions)
        ):
            raise ValueError("Invalid weighted head geometry or values")
        if device not in weighted or set(weighted[device]) != set(boundary_keys):
            raise ValueError("Weighted anatomical identities differ")
        output = []
        for index, key in enumerate(boundary_keys):
            rule = weighted[device][key]
            if (
                not isinstance(rule, dict)
                or not 1 <= len(rule) <= 2
                or not set(rule) <= set(member_names)
            ):
                raise ValueError("One or two known weighted heads are required")
            names = [name for name in member_names if name in rule]
            weights = np.asarray([rule[name] for name in names], dtype=np.float32)
            if (
                not np.isfinite(weights).all()
                or (weights <= 0).any()
                or abs(float(weights.sum()) - 1) > 1e-6
            ):
                raise ValueError(
                    "Weighted head coefficients must be positive and sum to one"
                )
            output.append(
                combine_positions(
                    [positions[member_names.index(name)][index] for name in names],
                    "mean",
                    weights,
                )
            )
        return np.stack(output).astype(np.float32, copy=False)
    mapping = configuration.get("head_source_by_device")
    if mapping is None:
        return combine_positions(
            positions, configuration.get("method", "mean"), configuration.get("weights")
        )
    if "weights" in configuration or configuration.get("method", "mean") != "mean":
        raise ValueError("Head selection cannot also configure averaging weights")
    if len(member_names) != len(positions) or len(set(member_names)) != len(
        member_names
    ):
        raise ValueError("Invalid named head sources")
    if not positions or len(set(boundary_keys)) != len(boundary_keys):
        raise ValueError("Invalid boundary identities")
    shape = positions[0].shape
    if (
        len(shape) != 3
        or shape[0] != len(boundary_keys)
        or any(p.shape != shape for p in positions)
    ):
        raise ValueError("Head-source prediction geometry differs")
    if device not in mapping or set(mapping[device]) != set(boundary_keys):
        raise ValueError("Head-source anatomical identities differ")
    if any(name not in member_names for name in mapping[device].values()):
        raise ValueError("Unknown selected head source")
    if any(not np.isfinite(p).all() for p in positions):
        raise ValueError("Nonfinite head source")
    return np.stack(
        [
            positions[member_names.index(mapping[device][key])][index]
            for index, key in enumerate(boundary_keys)
        ]
    ).astype(np.float32, copy=False)