Coverage for src/bioimageio/core/axis.py: 98%

123 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-20 09:46 +0000

1from __future__ import annotations 

2 

3from collections.abc import Mapping, Sequence 

4from dataclasses import dataclass 

5from typing import ( 

6 Literal, 

7 TypeAlias, 

8 TypeVar, 

9 Union, 

10) 

11 

12from loguru import logger 

13from typing_extensions import Protocol, assert_never, runtime_checkable 

14 

15from bioimageio.spec.model import v0_5 

16 

17 

18def _guess_axis_type(a: str): 

19 a = a.lower() 

20 if a in ("b", "batch"): 

21 return "batch" 

22 elif a in ("t", "time"): 

23 return "time" 

24 elif a in ("s", "sample", "i", "index"): 

25 return "index" 

26 elif a in ("c", "channel"): 

27 return "channel" 

28 elif a in ("x", "y", "z") or a.startswith("space"): 

29 return "space" 

30 else: 

31 logger.warning( 

32 "Failed to infer axis type for axis id '{}'." 

33 + " Consider using one of:" 

34 + " 'b', 'batch', 't', 'time', 's', 'sample', 'i'," 

35 + " 'index', 'c', 'channel', 'x', 'y', 'z'," 

36 + " 'space*'. Or create an `Axis` object with an explicity type instead.", 

37 a, 

38 ) 

39 return "unknown" 

40 

41 

42S = TypeVar("S", bound=str) 

43 

44 

45AxisId: TypeAlias = v0_5.AxisId 

46"""An axis identifier, e.g. 'batch', 'channel', 'z', 'y', 'x'""" 

47 

48BATCH_AXIS_ID = v0_5.BATCH_AXIS_ID 

49CHANNEL_AXIS_ID = v0_5.CHANNEL_AXIS_ID 

50TIME_AXIS_ID = v0_5.DEFAULT_TIME_AXIS_ID 

51 

52_T = TypeVar("_T") 

53PerAxis = Mapping[AxisId, _T] 

54 

55 

56BatchSize = int 

57 

58AxisLetter = Literal["b", "i", "t", "c", "z", "y", "x"] 

59_AxisLikePlain = str | AxisId | AxisLetter 

60 

61 

62@runtime_checkable 

63class AxisDescrLike(Protocol): 

64 id: _AxisLikePlain 

65 type: Literal["batch", "channel", "index", "space", "time"] 

66 

67 

68AxisLike = Union[_AxisLikePlain, AxisDescrLike, v0_5.AnyAxis, "Axis", "AxisInfo"] 

69 

70 

71def axis_id_from_axis_like(a: AxisLike) -> AxisId: 

72 if isinstance( 

73 a, 

74 (Axis, v0_5.AxisBase), 

75 ): 

76 return a.id 

77 elif isinstance(a, AxisDescrLike): 

78 a = a.id 

79 

80 if isinstance(a, AxisId): 

81 return a 

82 elif isinstance(a, str): 

83 return AxisId(a) 

84 else: 

85 assert_never(a) 

86 

87 

88@dataclass 

89class Axis: 

90 id: AxisId 

91 type: Literal["batch", "channel", "index", "space", "time", "unknown"] 

92 

93 def __post_init__(self): 

94 if self.type == "batch" and self.id != BATCH_AXIS_ID: 

95 raise ValueError( 

96 f"Axis with type 'batch' must have id '{BATCH_AXIS_ID}', but got '{self.id}'" 

97 ) 

98 if self.type == "channel" and self.id != CHANNEL_AXIS_ID: 

99 raise ValueError( 

100 f"Axis with type 'channel' must have id '{CHANNEL_AXIS_ID}', but got '{self.id}'" 

101 ) 

102 

103 @classmethod 

104 def create(cls, axis: AxisLike) -> Axis: 

105 if isinstance(axis, cls): 

106 return axis 

107 

108 if isinstance(axis, (AxisId, str)): 

109 axis_id = axis 

110 axis_type = _guess_axis_type(str(axis)) 

111 else: 

112 if hasattr(axis, "type"): 112 ↛ 115line 112 didn't jump to line 115 because the condition on line 112 was always true

113 axis_type = axis.type 

114 else: 

115 axis_type = _guess_axis_type(str(axis)) 

116 

117 if hasattr(axis, "id"): 117 ↛ 120line 117 didn't jump to line 120 because the condition on line 117 was always true

118 axis_id = axis.id 

119 else: 

120 axis_id = axis 

121 

122 return Axis(id=AxisId(axis_id), type=axis_type) 

123 

124 

125@dataclass 

126class AxisSize: 

127 min: int 

128 max: int | None = None 

129 step: int | None = None 

130 

131 def __post_init__(self): 

132 if self.min < 0: 

133 raise ValueError(f"AxisSize min must be non-negative, but got {self.min}") 

134 if self.max is not None and self.max < self.min: 

135 raise ValueError( 

136 f"AxisSize max must be greater than or equal to min, but got min={self.min}, max={self.max}" 

137 ) 

138 if self.step is not None and self.step <= 0: 

139 raise ValueError(f"AxisSize step must be positive, but got {self.step}") 

140 

141 

142@dataclass 

143class AxisInfo(Axis): 

144 size: AxisSize 

145 

146 @classmethod 

147 def create(cls, axis: AxisLike, size: int | AxisSize | None = None) -> AxisInfo: 

148 if isinstance(axis, AxisInfo): 

149 return axis 

150 

151 axis_base = super().create(axis) 

152 if size is None: 

153 if not isinstance(axis, v0_5.AxisBase): 

154 size = AxisSize(min=1) 

155 else: 

156 if axis.size is None: 

157 size = AxisSize(min=1) 

158 elif isinstance(axis.size, int): 

159 size = AxisSize( 

160 min=axis.size, 

161 max=None 

162 if isinstance(axis, (v0_5.TimeAxisBase, v0_5.SpaceAxisBase)) 

163 or ( 

164 not isinstance(axis, v0_5.IndexOutputAxis) 

165 and axis.concatenable 

166 ) 

167 else axis.size, 

168 ) 

169 elif isinstance(axis.size, v0_5.SizeReference): 

170 size = AxisSize(min=axis.size.offset + 1) 

171 elif isinstance(axis.size, v0_5.ParameterizedSize): 

172 size = AxisSize(min=axis.size.min, step=axis.size.step) 

173 elif isinstance(axis.size, v0_5.DataDependentSize): 

174 size = AxisSize(min=axis.size.min, max=axis.size.max) 

175 else: 

176 assert_never(axis.size) 

177 elif isinstance(size, int): 

178 size = AxisSize(min=size, max=size) 

179 

180 return AxisInfo(id=axis_base.id, type=axis_base.type, size=size) 

181 

182 

183def single_letter_dims_if_possible( 

184 dims: Sequence[AxisId], 

185) -> tuple[str, ...]: 

186 """Return a tuple of single-letter dimension names if possible, otherwise return the original dimension names.""" 

187 single_letter_dims: list[str] = [] 

188 

189 for d in dims: 

190 d = str(d).lower() 

191 if d in ("batch", "b"): 

192 single_letter_dims.append("b") 

193 elif d in ("time", "t"): 

194 single_letter_dims.append("t") 

195 elif d in ("index", "i"): 

196 single_letter_dims.append("i") 

197 elif d in ("channel", "c"): 

198 single_letter_dims.append("c") 

199 elif d in "zyx": 

200 single_letter_dims.append(d) 

201 else: 

202 # Return original dims if any dim cannot be converted to a single letter 

203 return tuple(dims) 

204 

205 if len(set(single_letter_dims)) != len(single_letter_dims): 

206 # Return original dims if any single letter dim is not unique 

207 return tuple(dims) 

208 

209 return tuple(single_letter_dims)