Coverage for trimesh/voxel/encoding.py: 79%
616 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-22 02:08 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-22 02:08 +0000
1"""OO interfaces to encodings for ND arrays which caching."""
3import abc
5import numpy as np
7from .. import caching
8from ..typed import Integer, ShapeLike
9from ..util import ABC
10from . import runlength
12try:
13 from scipy import sparse as sp
14except BaseException as E:
15 from ..exceptions import ExceptionWrapper
17 sp = ExceptionWrapper(E)
20def _empty_stripped(shape: tuple[Integer, ...]):
21 num_dims = len(shape)
22 encoding = DenseEncoding(np.zeros(shape=(0,) * num_dims, dtype=bool))
23 padding = np.zeros(shape=(num_dims, 2), dtype=int)
24 padding[:, 1] = shape
25 return encoding, padding
28class Encoding(ABC):
29 """
30 Base class for objects that implement a specific subset of of ndarray ops.
32 This presents a unified interface for various different ways of encoding
33 conceptually dense arrays and to interoperate between them.
35 Example implementations are ND sparse arrays, run length encoded arrays
36 and dense encodings (wrappers around np.ndarrays).
37 """
39 def __init__(self, data):
40 self._data = data
41 self._cache = caching.Cache(id_function=self._data.__hash__)
43 @property
44 @abc.abstractmethod
45 def dtype(self):
46 pass
48 @property
49 @abc.abstractmethod
50 def shape(self):
51 pass
53 @property
54 @abc.abstractmethod
55 def sum(self):
56 pass
58 @property
59 @abc.abstractmethod
60 def size(self):
61 pass
63 @property
64 @abc.abstractmethod
65 def sparse_indices(self):
66 pass
68 @property
69 @abc.abstractmethod
70 def sparse_values(self):
71 pass
73 @property
74 @abc.abstractmethod
75 def dense(self):
76 pass
78 @abc.abstractmethod
79 def gather_nd(self, indices):
80 pass
82 @abc.abstractmethod
83 def mask(self, mask):
84 pass
86 @abc.abstractmethod
87 def get_value(self, index):
88 pass
90 @abc.abstractmethod
91 def copy(self):
92 pass
94 @property
95 def is_empty(self):
96 return self.sparse_indices[self.sparse_values != 0].size == 0
98 @caching.cache_decorator
99 def stripped(self):
100 """
101 Get encoding with all zeros stripped from the start and end
102 of each axis.
104 Returns
105 ------------
106 encoding: ?
107 padding : (n, 2) int
108 Padding at the start and end that was stripped
109 """
110 if self.is_empty:
111 return _empty_stripped(self.shape)
112 dense = self.dense
113 shape = dense.shape
114 ndims = len(shape)
115 padding = []
116 slices = []
117 for dim, size in enumerate(shape):
118 axis = tuple(range(dim)) + tuple(range(dim + 1, ndims))
119 filled = np.any(dense, axis=axis)
120 (indices,) = np.nonzero(filled)
121 lower = indices.min()
122 upper = indices.max() + 1
123 padding.append([lower, size - upper])
124 slices.append(slice(lower, upper))
125 return DenseEncoding(dense[tuple(slices)]), np.array(padding, int)
127 def _flip(self, axes):
128 return FlippedEncoding(self, axes)
130 def __hash__(self):
131 """
132 Get the hash of the current transformation matrix.
134 Returns
135 ------------
136 hash : str
137 Hash of transformation matrix
138 """
139 return self._data.__hash__()
141 @property
142 def ndims(self):
143 return len(self.shape)
145 def reshape(self, shape: ShapeLike):
146 # numpy accepts a bare integer as a 1D shape
147 shape = np.atleast_1d(shape)
148 if len(shape) == 1:
149 return self.flat
150 return ShapedEncoding(self, shape)
152 @property
153 def flat(self):
154 return FlattenedEncoding(self)
156 def flip(self, axis=0):
157 return _flipped(self, axis)
159 @property
160 def sparse_components(self):
161 return self.sparse_indices, self.sparse_values
163 @property
164 def data(self):
165 return self._data
167 def run_length_data(self, dtype=np.int64):
168 if self.ndims != 1:
169 raise ValueError("`run_length_data` only valid for flat encodings")
170 return runlength.dense_to_rle(self.dense, dtype=dtype)
172 def binary_run_length_data(self, dtype=np.int64):
173 if self.ndims != 1:
174 raise ValueError("`run_length_data` only valid for flat encodings")
175 return runlength.dense_to_brle(self.dense, dtype=dtype)
177 def transpose(self, perm):
178 return _transposed(self, perm)
180 def _transpose(self, perm):
181 return TransposedEncoding(self, perm)
183 @property
184 def mutable(self):
185 return self._data.mutable
187 @mutable.setter
188 def mutable(self, value):
189 self._data.mutable = value
192class DenseEncoding(Encoding):
193 """Simple `Encoding` implementation based on a numpy ndarray."""
195 def __init__(self, data):
196 if not isinstance(data, caching.TrackedArray):
197 if not isinstance(data, np.ndarray):
198 raise ValueError("DenseEncoding data must be a numpy array")
199 data = caching.tracked_array(data)
200 super().__init__(data=data)
202 @property
203 def dtype(self):
204 return self._data.dtype
206 @property
207 def shape(self):
208 return self._data.shape
210 @caching.cache_decorator
211 def sum(self):
212 return self._data.sum()
214 @caching.cache_decorator
215 def is_empty(self):
216 return not np.any(self._data)
218 @property
219 def size(self):
220 return self._data.size
222 @property
223 def sparse_components(self):
224 indices = self.sparse_indices
225 values = self.gather(indices)
226 return indices, values
228 @caching.cache_decorator
229 def sparse_indices(self):
230 return np.column_stack(np.where(self._data))
232 @caching.cache_decorator
233 def sparse_values(self):
234 return self.sparse_components[1]
236 def _flip(self, axes):
237 dense = self.dense
238 for a in axes:
239 dense = np.flip(dense, a)
240 return DenseEncoding(dense)
242 @property
243 def dense(self):
244 return self._data
246 def gather(self, indices):
247 return self._data[indices]
249 def gather_nd(self, indices):
250 return self._data[tuple(indices.T)]
252 def mask(self, mask):
253 return self._data[mask if isinstance(mask, np.ndarray) else mask.dense]
255 def get_value(self, index):
256 return self._data[tuple(index)]
258 def reshape(self, shape: ShapeLike):
259 return DenseEncoding(self._data.reshape(shape))
261 def _transpose(self, perm):
262 return DenseEncoding(self._data.transpose(perm))
264 @property
265 def flat(self):
266 return DenseEncoding(self._data.reshape((-1,)))
268 def copy(self):
269 return DenseEncoding(self._data.copy())
272class SparseEncoding(Encoding):
273 """
274 `Encoding` implementation based on an ND sparse implementation.
276 Since the scipy.sparse implementations are for 2D arrays only, this
277 implementation uses a single-column CSC matrix with index
278 raveling/unraveling.
279 """
281 def __init__(self, indices, values, shape: ShapeLike | None = None):
282 """
283 Parameters
284 ------------
285 indices: (m, n)-sized int array of indices
286 values: (m, n)-sized dtype array of values at the specified indices
287 shape: (n,) iterable of integers. If None, the maximum value of indices
288 + 1 is used.
289 """
290 data = caching.DataStore()
291 super().__init__(data)
292 data["indices"] = indices
293 data["values"] = values
294 indices = data["indices"]
295 if len(indices.shape) != 2:
296 raise ValueError(f"indices must be 2D, got shaped {indices.shape!s}")
297 if data["values"].shape != (indices.shape[0],):
298 raise ValueError(
299 "values and indices shapes inconsistent: {} and {}".format(
300 data["values"], data["indices"]
301 )
302 )
303 if shape is None:
304 self._shape = tuple(data["indices"].max(axis=0) + 1)
305 else:
306 self._shape = tuple(np.atleast_1d(shape).tolist())
307 if not np.all(indices < self._shape):
308 raise ValueError("all indices must be less than shape")
309 if not np.all(indices >= 0):
310 raise ValueError("all indices must be non-negative")
312 @staticmethod
313 def from_dense(dense_data):
314 sparse_indices = np.where(dense_data)
315 values = dense_data[sparse_indices]
316 return SparseEncoding(
317 np.stack(sparse_indices, axis=-1), values, shape=dense_data.shape
318 )
320 def copy(self):
321 return SparseEncoding(
322 indices=self.sparse_indices.copy(),
323 values=self.sparse_values.copy(),
324 shape=self.shape,
325 )
327 @property
328 def sparse_indices(self):
329 return self._data["indices"]
331 @property
332 def sparse_values(self):
333 return self._data["values"]
335 @property
336 def dtype(self):
337 return self.sparse_values.dtype
339 @caching.cache_decorator
340 def sum(self):
341 return self.sparse_values.sum()
343 @property
344 def ndims(self):
345 return self.sparse_indices.shape[-1]
347 @property
348 def shape(self):
349 return self._shape
351 @property
352 def size(self):
353 return np.prod(self.shape)
355 @property
356 def sparse_components(self):
357 return self.sparse_indices, self.sparse_values
359 @caching.cache_decorator
360 def dense(self):
361 sparse = self._csc
362 # sparse.todense gives an `np.matrix` which cannot be reshaped
363 dense = np.zeros(shape=sparse.shape, dtype=sparse.dtype)
364 sparse.todense(out=dense)
365 return np.reshape(dense, self.shape)
367 @caching.cache_decorator
368 def _csc(self):
369 values = self.sparse_values
370 indices = self._flat_indices(self.sparse_indices)
371 indptr = [0, len(indices)]
372 return sp.csc_matrix((values, indices, indptr), shape=(self.size, 1))
374 def _flat_indices(self, indices):
375 assert indices.shape[1] == 3 and len(indices.shape) == 2
376 return np.ravel_multi_index(indices.T, self.shape)
378 def _shaped_indices(self, flat_indices):
379 return np.column_stack(np.unravel_index(flat_indices, self.shape))
381 def gather_nd(self, indices):
382 mat = self._csc[self._flat_indices(indices)].todense()
383 # mat is a np matrix, which stays rank 2 after squeeze
384 # np.asarray changes this to a standard rank 2 array.
385 return np.asarray(mat).squeeze(axis=-1)
387 def mask(self, mask):
388 i, _ = np.where(self._csc[mask.reshape((-1,))])
389 return self._shaped_indices(i)
391 def get_value(self, index):
392 return self._gather_nd(np.expand_dims(index, axis=0))[0]
394 @caching.cache_decorator
395 def stripped(self):
396 """
397 Get encoding with all zeros stripped from the start/end of each axis.
399 Returns:
400 encoding: SparseEncoding with same values but indices shifted down
401 by padding[:, 0]
402 padding: (n, 2) array of ints denoting padding at the start/end
403 that was stripped
404 """
405 if self.is_empty:
406 return _empty_stripped(self.shape)
407 indices = self.sparse_indices
408 pad_left = np.min(indices, axis=0)
409 pad_right = np.max(indices, axis=0)
410 pad_right *= -1
411 pad_right += self.shape
412 padding = np.column_stack((pad_left, pad_right))
413 return SparseEncoding(indices - pad_left, self.sparse_values), padding
416def SparseBinaryEncoding(indices, shape: ShapeLike | None = None):
417 """
418 Convenient factory constructor for SparseEncodings with values all ones.
420 Parameters
421 ------------
422 indices: (m, n) sparse indices into conceptual rank-n array
423 shape: length n iterable or None. If None, maximum of indices along first
424 axis + 1 is used
426 Returns
427 ------------
428 rank n bool `SparseEncoding` with True values at each index.
429 """
430 return SparseEncoding(indices, np.ones(shape=(indices.shape[0],), dtype=bool), shape)
433class RunLengthEncoding(Encoding):
434 """1D run length encoding.
436 See `trimesh.voxel.runlength` documentation for implementation details.
437 """
439 def __init__(self, data, dtype=None):
440 """
441 Parameters
442 ------------
443 data: run length encoded data.
444 dtype: dtype of encoded data. Each second value of data is cast will be
445 cast to this dtype if provided.
446 """
447 super().__init__(data=caching.tracked_array(data))
448 if dtype is None:
449 dtype = self._data.dtype
450 if len(self._data.shape) != 1:
451 raise ValueError("data must be 1D numpy array")
452 self._dtype = dtype
454 @caching.cache_decorator
455 def is_empty(self):
456 return not np.any(np.logical_and(self._data[::2], self._data[1::2]))
458 @property
459 def ndims(self):
460 return 1
462 @property
463 def shape(self):
464 return (self.size,)
466 @property
467 def dtype(self):
468 return self._dtype
470 def __hash__(self):
471 """
472 Get the hash of the current transformation matrix.
474 Returns
475 ------------
476 hash : str
477 Hash of transformation matrix
478 """
479 return self._data.__hash__()
481 @staticmethod
482 def from_dense(dense_data, dtype=np.int64, encoding_dtype=np.int64):
483 return RunLengthEncoding(
484 runlength.dense_to_rle(dense_data, dtype=encoding_dtype), dtype=dtype
485 )
487 @staticmethod
488 def from_rle(rle_data, dtype=None):
489 if dtype != rle_data.dtype:
490 rle_data = runlength.rle_to_rle(rle_data, dtype=dtype)
491 return RunLengthEncoding(rle_data)
493 @staticmethod
494 def from_brle(brle_data, dtype=None):
495 return RunLengthEncoding(runlength.brle_to_rle(brle_data, dtype=dtype))
497 @caching.cache_decorator
498 def stripped(self):
499 if self.is_empty:
500 return _empty_stripped(self.shape)
501 data, padding = runlength.rle_strip(self._data)
502 if padding == (0, 0):
503 encoding = self
504 else:
505 encoding = RunLengthEncoding(data, dtype=self._dtype)
506 padding = np.expand_dims(padding, axis=0)
507 return encoding, padding
509 @caching.cache_decorator
510 def sum(self):
511 return (self._data[::2] * self._data[1::2]).sum()
513 @caching.cache_decorator
514 def size(self):
515 return runlength.rle_length(self._data)
517 def _flip(self, axes):
518 if axes != (0,):
519 raise ValueError(f"encoding is 1D - cannot flip on axis {axes!s}")
520 return RunLengthEncoding(runlength.rle_reverse(self._data))
522 @caching.cache_decorator
523 def sparse_components(self):
524 return runlength.rle_to_sparse(self._data)
526 @caching.cache_decorator
527 def sparse_indices(self):
528 return self.sparse_components[0]
530 @caching.cache_decorator
531 def sparse_values(self):
532 return self.sparse_components[1]
534 @caching.cache_decorator
535 def dense(self):
536 return runlength.rle_to_dense(self._data, dtype=self._dtype)
538 def gather(self, indices):
539 return runlength.rle_gather_1d(self._data, indices, dtype=self._dtype)
541 def gather_nd(self, indices):
542 indices = np.squeeze(indices, axis=-1)
543 return self.gather(indices)
545 def sorted_gather(self, ordered_indices):
546 return np.array(
547 tuple(runlength.sorted_rle_gather_1d(self._data, ordered_indices)),
548 dtype=self._dtype,
549 )
551 def mask(self, mask):
552 return np.array(tuple(runlength.rle_mask(self._data, mask)), dtype=self._dtype)
554 def get_value(self, index):
555 for value in self.sorted_gather((index,)):
556 return np.asanyarray(value, dtype=self._dtype)
558 def copy(self):
559 return RunLengthEncoding(self._data.copy(), dtype=self.dtype)
561 def run_length_data(self, dtype=np.int64):
562 return runlength.rle_to_rle(self._data, dtype=dtype)
564 def binary_run_length_data(self, dtype=np.int64):
565 return runlength.rle_to_brle(self._data, dtype=dtype)
568class BinaryRunLengthEncoding(RunLengthEncoding):
569 """1D binary run length encoding.
571 See `trimesh.voxel.runlength` documentation for implementation details.
572 """
574 def __init__(self, data):
575 """
576 Parameters
577 ------------
578 data: binary run length encoded data.
579 """
580 super().__init__(data=data, dtype=bool)
582 @caching.cache_decorator
583 def is_empty(self):
584 return not np.any(self._data[1::2])
586 @staticmethod
587 def from_dense(dense_data, encoding_dtype=np.int64):
588 return BinaryRunLengthEncoding(
589 runlength.dense_to_brle(dense_data, dtype=encoding_dtype)
590 )
592 @staticmethod
593 def from_rle(rle_data, dtype=None):
594 return BinaryRunLengthEncoding(runlength.rle_to_brle(rle_data, dtype=dtype))
596 @staticmethod
597 def from_brle(brle_data, dtype=None):
598 if dtype != brle_data.dtype:
599 brle_data = runlength.brle_to_brle(brle_data, dtype=dtype)
600 return BinaryRunLengthEncoding(brle_data)
602 @caching.cache_decorator
603 def stripped(self):
604 if self.is_empty:
605 return _empty_stripped(self.shape)
606 data, padding = runlength.rle_strip(self._data)
607 if padding == (0, 0):
608 encoding = self
609 else:
610 encoding = BinaryRunLengthEncoding(data)
611 padding = np.expand_dims(padding, axis=0)
612 return encoding, padding
614 @caching.cache_decorator
615 def sum(self):
616 return self._data[1::2].sum()
618 @caching.cache_decorator
619 def size(self):
620 return runlength.brle_length(self._data)
622 def _flip(self, axes):
623 if axes != (0,):
624 raise ValueError(f"encoding is 1D - cannot flip on axis {axes!s}")
625 return BinaryRunLengthEncoding(runlength.brle_reverse(self._data))
627 @property
628 def sparse_components(self):
629 return self.sparse_indices, self.sparse_values
631 @caching.cache_decorator
632 def sparse_values(self):
633 return np.ones(shape=(self.sum,), dtype=bool)
635 @caching.cache_decorator
636 def sparse_indices(self):
637 return runlength.brle_to_sparse(self._data)
639 @caching.cache_decorator
640 def dense(self):
641 return runlength.brle_to_dense(self._data)
643 def gather(self, indices):
644 return runlength.brle_gather_1d(self._data, indices)
646 def gather_nd(self, indices):
647 indices = np.squeeze(indices)
648 return self.gather(indices)
650 def sorted_gather(self, ordered_indices):
651 gen = runlength.sorted_brle_gather_1d(self._data, ordered_indices)
652 return np.array(tuple(gen), dtype=bool)
654 def mask(self, mask):
655 gen = runlength.brle_mask(self._data, mask)
656 return np.array(tuple(gen), dtype=bool)
658 def copy(self):
659 return BinaryRunLengthEncoding(self._data.copy())
661 def run_length_data(self, dtype=np.int64):
662 return runlength.brle_to_rle(self._data, dtype=dtype)
664 def binary_run_length_data(self, dtype=np.int64):
665 return runlength.brle_to_brle(self._data, dtype=dtype)
668class LazyIndexMap(Encoding):
669 """
670 Abstract class for implementing lazy index mapping operations.
672 Implementations include transpose, flatten/reshaping and flipping
674 Derived classes must implement:
675 * _to_base_indices(indices)
676 * _from_base_indices(base_indices)
677 * shape
678 * dense
679 * mask(mask)
680 """
682 @abc.abstractmethod
683 def _to_base_indices(self, indices):
684 pass
686 @abc.abstractmethod
687 def _from_base_indices(self, base_indices):
688 pass
690 @property
691 def is_empty(self):
692 return self._data.is_empty
694 @property
695 def dtype(self):
696 return self._data.dtype
698 @property
699 def sum(self):
700 return self._data.sum
702 @property
703 def size(self):
704 return self._data.size
706 @property
707 def sparse_indices(self):
708 return self._from_base_indices(self._data.sparse_indices)
710 @property
711 def sparse_values(self):
712 return self._data.sparse_values
714 def gather_nd(self, indices):
715 return self._data.gather_nd(self._to_base_indices(indices))
717 def get_value(self, index):
718 return self._data[tuple(self._to_base_indices(index))]
721class FlattenedEncoding(LazyIndexMap):
722 """
723 Lazily flattened encoding.
725 Dense equivalent is np.reshape(data, (-1,)) (np.flatten creates a copy).
726 """
728 def _to_base_indices(self, indices):
729 return np.column_stack(np.unravel_index(indices, self._data.shape))
731 def _from_base_indices(self, base_indices):
732 return np.expand_dims(
733 np.ravel_multi_index(base_indices.T, self._data.shape), axis=-1
734 )
736 @property
737 def shape(self):
738 return (self.size,)
740 @property
741 def dense(self):
742 return self._data.dense.reshape((-1,))
744 def mask(self, mask):
745 return self._data.mask(mask.reshape(self._data.shape))
747 @property
748 def flat(self):
749 return self
751 def copy(self):
752 return FlattenedEncoding(self._data.copy())
755class ShapedEncoding(LazyIndexMap):
756 """
757 Lazily reshaped encoding.
759 Numpy equivalent is `np.reshape`
760 """
762 def __init__(self, encoding, shape: ShapeLike):
763 if isinstance(encoding, Encoding):
764 if encoding.ndims != 1:
765 encoding = encoding.flat
766 else:
767 raise ValueError("encoding must be an Encoding")
768 super().__init__(data=encoding)
769 self._shape = tuple(np.atleast_1d(shape).tolist())
770 nn = self._shape.count(-1)
771 size = np.prod(self._shape)
772 if nn == 1:
773 size = np.abs(size)
774 if self._data.size % size != 0:
775 raise ValueError(
776 "cannot reshape encoding of size %d into shape %s",
777 self._data.size,
778 str(self._shape),
779 )
781 rem = self._data.size // size
782 self._shape = tuple(rem if s == -1 else s for s in self._shape)
783 elif nn > 2:
784 raise ValueError("shape cannot have more than one -1 value")
785 elif np.prod(self._shape) != self._data.size:
786 raise ValueError(
787 "cannot reshape encoding of size %d into shape %s",
788 self._data.size,
789 str(self._shape),
790 )
792 def _from_base_indices(self, base_indices):
793 return np.column_stack(np.unravel_index(base_indices, self.shape))
795 def _to_base_indices(self, indices):
796 return np.expand_dims(np.ravel_multi_index(indices.T, self.shape), axis=-1)
798 @property
799 def flat(self):
800 return self._data
802 @property
803 def shape(self):
804 return self._shape
806 @property
807 def dense(self):
808 return self._data.dense.reshape(self.shape)
810 def mask(self, mask):
811 return self._data.mask(mask.flat)
813 def copy(self):
814 return ShapedEncoding(encoding=self._data.copy(), shape=self.shape)
817class TransposedEncoding(LazyIndexMap):
818 """
819 Lazily transposed encoding
821 Dense equivalent is `np.transpose`
822 """
824 def __init__(self, base_encoding, perm):
825 if not isinstance(base_encoding, Encoding):
826 raise ValueError(f"base_encoding must be an Encoding, got {base_encoding!s}")
827 if len(base_encoding.shape) != len(perm):
828 raise ValueError(
829 "base_encoding has %d ndims - cannot transpose with perm %s",
830 base_encoding.ndims,
831 str(perm),
832 )
834 super().__init__(base_encoding)
835 perm = np.array(perm, dtype=np.int64)
836 if not all(i in perm for i in range(base_encoding.ndims)):
837 raise ValueError(f"perm {perm!s} is not a valid permutation")
838 inv_perm = np.zeros_like(perm)
839 inv_perm[perm] = np.arange(base_encoding.ndims)
840 self._perm = perm
841 self._inv_perm = inv_perm
843 def transpose(self, perm):
844 return _transposed(self._data, [self._perm[p] for p in perm])
846 def _transpose(self, perm):
847 raise RuntimeError("Should not be here")
849 @property
850 def perm(self):
851 return self._perm
853 @property
854 def shape(self):
855 shape = self._data.shape
856 return tuple(shape[p] for p in self._perm)
858 def _to_base_indices(self, indices):
859 return np.take(indices, self._perm, axis=-1)
861 def _from_base_indices(self, base_indices):
862 try:
863 return np.take(base_indices, self._inv_perm, axis=-1)
864 except TypeError:
865 # windows sometimes tries to use wrong dtypes
866 return np.take(
867 base_indices.astype(np.int64), self._inv_perm.astype(np.int64), axis=-1
868 )
870 @property
871 def dense(self):
872 return self._data.dense.transpose(self._perm)
874 def gather(self, indices):
875 return self._data.gather(self._base_indices(indices))
877 def mask(self, mask):
878 return self._data.mask(mask.transpose(self._inv_perm)).transpose(self._perm)
880 def get_value(self, index):
881 return self._data[tuple(self._base_indices(index))]
883 @property
884 def data(self):
885 return self._data
887 def copy(self):
888 return TransposedEncoding(base_encoding=self._data.copy(), perm=self._perm)
891class FlippedEncoding(LazyIndexMap):
892 """
893 Encoding with entries flipped along one or more axes.
895 Dense equivalent is `np.flip`
896 """
898 def __init__(self, encoding, axes):
899 ndims = encoding.ndims
900 if isinstance(axes, np.ndarray) and axes.size == 1:
901 axes = (axes.item(),)
902 elif isinstance(axes, int):
903 axes = (axes,)
904 axes = tuple(a + ndims if a < 0 else a for a in axes)
905 self._axes = tuple(sorted(axes))
906 if len(set(self._axes)) != len(self._axes):
907 raise ValueError(f"Axes cannot contain duplicates, got {self._axes!s}")
908 super().__init__(encoding)
909 if not all(0 <= a < self._data.ndims for a in axes):
910 raise ValueError(
911 "Invalid axes %s for %d-d encoding", str(axes), self._data.ndims
912 )
914 def _to_base_indices(self, indices):
915 indices = indices.copy()
916 shape = self.shape
917 for a in self._axes:
918 indices[:, a] *= -1
919 indices[:, a] += shape
920 return indices
922 def _from_base_indices(self, base_indices):
923 return self._to_base_indices(base_indices)
925 @property
926 def shape(self):
927 return self._data.shape
929 @property
930 def dense(self):
931 dense = self._data.dense
932 for a in self._axes:
933 dense = np.flip(dense, a)
934 return dense
936 def mask(self, mask):
937 if not isinstance(mask, Encoding):
938 mask = DenseEncoding(mask)
939 mask = mask.flip(self._axes)
940 return self._data.mask(mask).flip(self._axes)
942 def copy(self):
943 return FlippedEncoding(self._data.copy(), self._axes)
945 def flip(self, axis=0):
946 if isinstance(axis, np.ndarray):
947 if axis.size == 1:
948 axis = (axis.item(),)
949 else:
950 axis = tuple(axis)
951 elif isinstance(axis, int):
952 axes = (axis,)
953 else:
954 axes = tuple(axis)
955 return _flipped(self, self._axes + axes)
957 def _flip(self, axes):
958 raise RuntimeError("Should not be here")
961def _flipped(encoding, axes):
962 if not hasattr(axes, "__iter__"):
963 axes = (axes,)
964 unique_ax = set()
965 ndims = encoding.ndims
966 axes = tuple(a + ndims if a < 0 else a for a in axes)
967 for a in axes:
968 if a in unique_ax:
969 unique_ax.remove(a)
970 else:
971 unique_ax.add(a)
972 if len(unique_ax) == 0:
973 return encoding
974 else:
975 return encoding._flip(tuple(sorted(unique_ax)))
978def _transposed(encoding, perm):
979 ndims = encoding.ndims
980 perm = tuple(p + ndims if p < 0 else p for p in perm)
981 if np.all(np.arange(ndims) == perm):
982 return encoding
983 else:
984 return encoding._transpose(perm)