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
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 09:46 +0000
1from __future__ import annotations
3from collections.abc import Mapping, Sequence
4from dataclasses import dataclass
5from typing import (
6 Literal,
7 TypeAlias,
8 TypeVar,
9 Union,
10)
12from loguru import logger
13from typing_extensions import Protocol, assert_never, runtime_checkable
15from bioimageio.spec.model import v0_5
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"
42S = TypeVar("S", bound=str)
45AxisId: TypeAlias = v0_5.AxisId
46"""An axis identifier, e.g. 'batch', 'channel', 'z', 'y', 'x'"""
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
52_T = TypeVar("_T")
53PerAxis = Mapping[AxisId, _T]
56BatchSize = int
58AxisLetter = Literal["b", "i", "t", "c", "z", "y", "x"]
59_AxisLikePlain = str | AxisId | AxisLetter
62@runtime_checkable
63class AxisDescrLike(Protocol):
64 id: _AxisLikePlain
65 type: Literal["batch", "channel", "index", "space", "time"]
68AxisLike = Union[_AxisLikePlain, AxisDescrLike, v0_5.AnyAxis, "Axis", "AxisInfo"]
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
80 if isinstance(a, AxisId):
81 return a
82 elif isinstance(a, str):
83 return AxisId(a)
84 else:
85 assert_never(a)
88@dataclass
89class Axis:
90 id: AxisId
91 type: Literal["batch", "channel", "index", "space", "time", "unknown"]
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 )
103 @classmethod
104 def create(cls, axis: AxisLike) -> Axis:
105 if isinstance(axis, cls):
106 return axis
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))
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
122 return Axis(id=AxisId(axis_id), type=axis_type)
125@dataclass
126class AxisSize:
127 min: int
128 max: int | None = None
129 step: int | None = None
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}")
142@dataclass
143class AxisInfo(Axis):
144 size: AxisSize
146 @classmethod
147 def create(cls, axis: AxisLike, size: int | AxisSize | None = None) -> AxisInfo:
148 if isinstance(axis, AxisInfo):
149 return axis
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)
180 return AxisInfo(id=axis_base.id, type=axis_base.type, size=size)
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] = []
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)
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)
209 return tuple(single_letter_dims)