Debian Codegraph @

DisplayCAL/cubeiterator.py

raw
1 """Classes for working with and iterating over 3D data cubes.
2
3 It includes functionality to define a cube, access its elements, and iterate
4 through its contents.
5 """
6
7 from __future__ import annotations
8
9 import sys
10 from typing import TYPE_CHECKING
11
12 if TYPE_CHECKING:
13 if sys.version_info >= (3, 11):
14 from typing import Self
15 else:
16 from typing_extensions import Self
17
18
19 class Cube3D:
20 """A 3D cube of data.
21
22 This class provides functionality to define a cube, access its elements,
23 and iterate through its contents. It allows for specifying the size of the
24 cube and the range of indices to be used.
25
26 Args:
27 size (int): The size of the cube along each dimension. Default is 65.
28 start (int): The starting index for the cube. Default is 0.
29 end (None | int, optional): The ending index for the cube. If not
30 specified, it defaults to the total number of entries in the cube,
31 which is `size**3`. If specified, it must be greater than or equal
32 to `start`. Default is None.
33
34 Raises:
35 TypeError: If `start` or `end` is not an integer.
36 ValueError: If `start` or `end` is out of range or if `end` is less
37 than `start`.
38 """
39
40 def __init__(self, size: int = 65, start: int = 0, end: None | int = None) -> None:
41 num_entries = size**3
42 if end is None:
43 end = num_entries
44
45 if not isinstance(start, int):
46 raise TypeError(
47 f"integer start argument expected, got {start.__class__.__name__}"
48 )
49
50 if not isinstance(end, int):
51 raise TypeError(
52 f"integer end argument expected, got {end.__class__.__name__}"
53 )
54
55 start = self._clamp(start, 0, num_entries, -1)
56 end = self._clamp(end, 0, num_entries, -1)
57
58 if start == -1:
59 raise ValueError(f"start argument {start:.0f} out of range")
60
61 if end == -1:
62 raise ValueError(f"end argument {end:.0f} out of range")
63
64 self._size = size
65 self._start = start
66 self._len = end - start
67
68 def get(
69 self, i: int, default: None | tuple[int, int, int] = None
70 ) -> None | tuple[int, int, int]:
71 """Return the item at the specified index or a default value.
72
73 Args:
74 i (int): The index of the item to return.
75 default (None, optional)): The value to return if the index is out
76 of range.
77
78 Returns:
79 None | tuple[int, int, int]: The item at the specified index or the
80 default value if the index is out of range.
81 """
82 if i < 0:
83 i = self._len + i
84 if i < 0 or i > self._len - 1:
85 return default
86 return self[i]
87
88 def index(self, item: tuple[int, int, int]) -> int:
89 """Return the index of the specified item in the cube.
90
91 Args:
92 item (tuple[int, int, int]): The item to find the index of.
93
94 Raises:
95 ValueError: If the item is not found in the cube.
96
97 Returns:
98 int: The index of the item in the cube.
99 """
100 (c0, c1, c2) = item
101 if (c0, c1, c2) not in self:
102 raise ValueError(f"{(c0, c1, c2)!r} not in {self!r}")
103 i = c0 * self._size**2 + c1 * self._size + c2
104 return int(i) - self._start
105
106 def _clamp(
107 self,
108 v: int,
109 lower: int = 0,
110 upper: None | int = None,
111 fallback: None | int = None,
112 ) -> int:
113 """Clamp a value to a specified range.
114
115 Args:
116 v (int): The value to clamp.
117 lower (int): The lower bound of the range. Default is 0.
118 upper (None | int, optional): The upper bound of the range. If not
119 specified, it defaults to the length of the cube.
120 fallback (None | int, optional): A fallback value to use if `v` is
121 out of range. If not specified, it defaults to `lower` if `v`
122 is less than `lower`, or `upper` if `v` is greater than
123 `upper`.
124
125 Returns:
126 int: The clamped value.
127 """
128 if not upper:
129 upper = self._len
130 if v < lower:
131 v = fallback or lower if v < -upper else upper + v
132 elif v > upper:
133 v = fallback or upper
134 return v
135
136 def __contains__(self, other: tuple[int, int, int]) -> bool:
137 """Check if the cube contains the specified item.
138
139 Args:
140 other (tuple): The item to check.
141
142 Returns:
143 bool: True if the cube contains the item, False otherwise.
144 """
145 (c0, c1, c2) = other
146 return (
147 c0 == int(c0)
148 and c1 == int(c1)
149 and c2 == int(c2)
150 and max(c0, c1, c2) < self._size
151 and self._start
152 <= c0 * self._size**2 + c1 * self._size + c2
153 < self._len + self._start
154 )
155
156 def __getitem__(self, i: int) -> tuple[int, int, int]:
157 """Return the item at the specified index.
158
159 Args:
160 i (int): The index of the item to return.
161
162 Raises:
163 IndexError: If the index is out of range.
164
165 Returns:
166 tuple[int, int, int]: The item at the specified index.
167 """
168 oi = i
169 if i < 0:
170 i = self._len + i
171 if i < 0 or i > self._len - 1:
172 raise IndexError(f"index {oi} out of range")
173 i += self._start
174 return (
175 i // self._size // self._size,
176 i // self._size % self._size,
177 i % self._size,
178 )
179
180 def __len__(self) -> int:
181 """Return the length of the cube.
182
183 Returns:
184 int: The length of the cube.
185 """
186 return self._len
187
188 def __repr__(self) -> str:
189 """Return the string representation of the object.
190
191 Returns:
192 str: The string representation of the object.
193 """
194 return "{}(size={:.0f}, start={:.0f}, end={:.0f})".format( # noqa: UP032
195 self.__class__.__name__,
196 self._size,
197 self._start,
198 self._start + self._len,
199 )
200
201
202 class Cube3DIterator(Cube3D):
203 """An iterator for the Cube3D class.
204
205 This iterator is actually slightly slower especially with large cubes
206 than using iter(<Cube3D instance>).
207 """
208
209 def __init__(self, *args, **kwargs) -> None:
210 Cube3D.__init__(self, *args, **kwargs)
211 self._next = 0
212
213 def __iter__(self) -> Self:
214 """Return the object itself as an iterator."""
215 return self
216
217 def __next__(self) -> tuple[int, int, int]:
218 """Return the next item in the iteration.
219
220 Raises:
221 StopIteration: If there are no more items to iterate over.
222
223 Returns:
224 tuple[int, int, int]: The next item in the iteration.
225 """
226 if self._next == self._len:
227 raise StopIteration
228 result = self[self._next]
229 self._next += 1
230 return result