"""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)