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

1"""OO interfaces to encodings for ND arrays which caching.""" 

2 

3import abc 

4 

5import numpy as np 

6 

7from .. import caching 

8from ..typed import Integer, ShapeLike 

9from ..util import ABC 

10from . import runlength 

11 

12try: 

13 from scipy import sparse as sp 

14except BaseException as E: 

15 from ..exceptions import ExceptionWrapper 

16 

17 sp = ExceptionWrapper(E) 

18 

19 

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 

26 

27 

28class Encoding(ABC): 

29 """ 

30 Base class for objects that implement a specific subset of of ndarray ops. 

31 

32 This presents a unified interface for various different ways of encoding 

33 conceptually dense arrays and to interoperate between them. 

34 

35 Example implementations are ND sparse arrays, run length encoded arrays 

36 and dense encodings (wrappers around np.ndarrays). 

37 """ 

38 

39 def __init__(self, data): 

40 self._data = data 

41 self._cache = caching.Cache(id_function=self._data.__hash__) 

42 

43 @property 

44 @abc.abstractmethod 

45 def dtype(self): 

46 pass 

47 

48 @property 

49 @abc.abstractmethod 

50 def shape(self): 

51 pass 

52 

53 @property 

54 @abc.abstractmethod 

55 def sum(self): 

56 pass 

57 

58 @property 

59 @abc.abstractmethod 

60 def size(self): 

61 pass 

62 

63 @property 

64 @abc.abstractmethod 

65 def sparse_indices(self): 

66 pass 

67 

68 @property 

69 @abc.abstractmethod 

70 def sparse_values(self): 

71 pass 

72 

73 @property 

74 @abc.abstractmethod 

75 def dense(self): 

76 pass 

77 

78 @abc.abstractmethod 

79 def gather_nd(self, indices): 

80 pass 

81 

82 @abc.abstractmethod 

83 def mask(self, mask): 

84 pass 

85 

86 @abc.abstractmethod 

87 def get_value(self, index): 

88 pass 

89 

90 @abc.abstractmethod 

91 def copy(self): 

92 pass 

93 

94 @property 

95 def is_empty(self): 

96 return self.sparse_indices[self.sparse_values != 0].size == 0 

97 

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. 

103 

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) 

126 

127 def _flip(self, axes): 

128 return FlippedEncoding(self, axes) 

129 

130 def __hash__(self): 

131 """ 

132 Get the hash of the current transformation matrix. 

133 

134 Returns 

135 ------------ 

136 hash : str 

137 Hash of transformation matrix 

138 """ 

139 return self._data.__hash__() 

140 

141 @property 

142 def ndims(self): 

143 return len(self.shape) 

144 

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) 

151 

152 @property 

153 def flat(self): 

154 return FlattenedEncoding(self) 

155 

156 def flip(self, axis=0): 

157 return _flipped(self, axis) 

158 

159 @property 

160 def sparse_components(self): 

161 return self.sparse_indices, self.sparse_values 

162 

163 @property 

164 def data(self): 

165 return self._data 

166 

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) 

171 

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) 

176 

177 def transpose(self, perm): 

178 return _transposed(self, perm) 

179 

180 def _transpose(self, perm): 

181 return TransposedEncoding(self, perm) 

182 

183 @property 

184 def mutable(self): 

185 return self._data.mutable 

186 

187 @mutable.setter 

188 def mutable(self, value): 

189 self._data.mutable = value 

190 

191 

192class DenseEncoding(Encoding): 

193 """Simple `Encoding` implementation based on a numpy ndarray.""" 

194 

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) 

201 

202 @property 

203 def dtype(self): 

204 return self._data.dtype 

205 

206 @property 

207 def shape(self): 

208 return self._data.shape 

209 

210 @caching.cache_decorator 

211 def sum(self): 

212 return self._data.sum() 

213 

214 @caching.cache_decorator 

215 def is_empty(self): 

216 return not np.any(self._data) 

217 

218 @property 

219 def size(self): 

220 return self._data.size 

221 

222 @property 

223 def sparse_components(self): 

224 indices = self.sparse_indices 

225 values = self.gather(indices) 

226 return indices, values 

227 

228 @caching.cache_decorator 

229 def sparse_indices(self): 

230 return np.column_stack(np.where(self._data)) 

231 

232 @caching.cache_decorator 

233 def sparse_values(self): 

234 return self.sparse_components[1] 

235 

236 def _flip(self, axes): 

237 dense = self.dense 

238 for a in axes: 

239 dense = np.flip(dense, a) 

240 return DenseEncoding(dense) 

241 

242 @property 

243 def dense(self): 

244 return self._data 

245 

246 def gather(self, indices): 

247 return self._data[indices] 

248 

249 def gather_nd(self, indices): 

250 return self._data[tuple(indices.T)] 

251 

252 def mask(self, mask): 

253 return self._data[mask if isinstance(mask, np.ndarray) else mask.dense] 

254 

255 def get_value(self, index): 

256 return self._data[tuple(index)] 

257 

258 def reshape(self, shape: ShapeLike): 

259 return DenseEncoding(self._data.reshape(shape)) 

260 

261 def _transpose(self, perm): 

262 return DenseEncoding(self._data.transpose(perm)) 

263 

264 @property 

265 def flat(self): 

266 return DenseEncoding(self._data.reshape((-1,))) 

267 

268 def copy(self): 

269 return DenseEncoding(self._data.copy()) 

270 

271 

272class SparseEncoding(Encoding): 

273 """ 

274 `Encoding` implementation based on an ND sparse implementation. 

275 

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

280 

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

311 

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 ) 

319 

320 def copy(self): 

321 return SparseEncoding( 

322 indices=self.sparse_indices.copy(), 

323 values=self.sparse_values.copy(), 

324 shape=self.shape, 

325 ) 

326 

327 @property 

328 def sparse_indices(self): 

329 return self._data["indices"] 

330 

331 @property 

332 def sparse_values(self): 

333 return self._data["values"] 

334 

335 @property 

336 def dtype(self): 

337 return self.sparse_values.dtype 

338 

339 @caching.cache_decorator 

340 def sum(self): 

341 return self.sparse_values.sum() 

342 

343 @property 

344 def ndims(self): 

345 return self.sparse_indices.shape[-1] 

346 

347 @property 

348 def shape(self): 

349 return self._shape 

350 

351 @property 

352 def size(self): 

353 return np.prod(self.shape) 

354 

355 @property 

356 def sparse_components(self): 

357 return self.sparse_indices, self.sparse_values 

358 

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) 

366 

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

373 

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) 

377 

378 def _shaped_indices(self, flat_indices): 

379 return np.column_stack(np.unravel_index(flat_indices, self.shape)) 

380 

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) 

386 

387 def mask(self, mask): 

388 i, _ = np.where(self._csc[mask.reshape((-1,))]) 

389 return self._shaped_indices(i) 

390 

391 def get_value(self, index): 

392 return self._gather_nd(np.expand_dims(index, axis=0))[0] 

393 

394 @caching.cache_decorator 

395 def stripped(self): 

396 """ 

397 Get encoding with all zeros stripped from the start/end of each axis. 

398 

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 

414 

415 

416def SparseBinaryEncoding(indices, shape: ShapeLike | None = None): 

417 """ 

418 Convenient factory constructor for SparseEncodings with values all ones. 

419 

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 

425 

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) 

431 

432 

433class RunLengthEncoding(Encoding): 

434 """1D run length encoding. 

435 

436 See `trimesh.voxel.runlength` documentation for implementation details. 

437 """ 

438 

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 

453 

454 @caching.cache_decorator 

455 def is_empty(self): 

456 return not np.any(np.logical_and(self._data[::2], self._data[1::2])) 

457 

458 @property 

459 def ndims(self): 

460 return 1 

461 

462 @property 

463 def shape(self): 

464 return (self.size,) 

465 

466 @property 

467 def dtype(self): 

468 return self._dtype 

469 

470 def __hash__(self): 

471 """ 

472 Get the hash of the current transformation matrix. 

473 

474 Returns 

475 ------------ 

476 hash : str 

477 Hash of transformation matrix 

478 """ 

479 return self._data.__hash__() 

480 

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 ) 

486 

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) 

492 

493 @staticmethod 

494 def from_brle(brle_data, dtype=None): 

495 return RunLengthEncoding(runlength.brle_to_rle(brle_data, dtype=dtype)) 

496 

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 

508 

509 @caching.cache_decorator 

510 def sum(self): 

511 return (self._data[::2] * self._data[1::2]).sum() 

512 

513 @caching.cache_decorator 

514 def size(self): 

515 return runlength.rle_length(self._data) 

516 

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

521 

522 @caching.cache_decorator 

523 def sparse_components(self): 

524 return runlength.rle_to_sparse(self._data) 

525 

526 @caching.cache_decorator 

527 def sparse_indices(self): 

528 return self.sparse_components[0] 

529 

530 @caching.cache_decorator 

531 def sparse_values(self): 

532 return self.sparse_components[1] 

533 

534 @caching.cache_decorator 

535 def dense(self): 

536 return runlength.rle_to_dense(self._data, dtype=self._dtype) 

537 

538 def gather(self, indices): 

539 return runlength.rle_gather_1d(self._data, indices, dtype=self._dtype) 

540 

541 def gather_nd(self, indices): 

542 indices = np.squeeze(indices, axis=-1) 

543 return self.gather(indices) 

544 

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 ) 

550 

551 def mask(self, mask): 

552 return np.array(tuple(runlength.rle_mask(self._data, mask)), dtype=self._dtype) 

553 

554 def get_value(self, index): 

555 for value in self.sorted_gather((index,)): 

556 return np.asanyarray(value, dtype=self._dtype) 

557 

558 def copy(self): 

559 return RunLengthEncoding(self._data.copy(), dtype=self.dtype) 

560 

561 def run_length_data(self, dtype=np.int64): 

562 return runlength.rle_to_rle(self._data, dtype=dtype) 

563 

564 def binary_run_length_data(self, dtype=np.int64): 

565 return runlength.rle_to_brle(self._data, dtype=dtype) 

566 

567 

568class BinaryRunLengthEncoding(RunLengthEncoding): 

569 """1D binary run length encoding. 

570 

571 See `trimesh.voxel.runlength` documentation for implementation details. 

572 """ 

573 

574 def __init__(self, data): 

575 """ 

576 Parameters 

577 ------------ 

578 data: binary run length encoded data. 

579 """ 

580 super().__init__(data=data, dtype=bool) 

581 

582 @caching.cache_decorator 

583 def is_empty(self): 

584 return not np.any(self._data[1::2]) 

585 

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 ) 

591 

592 @staticmethod 

593 def from_rle(rle_data, dtype=None): 

594 return BinaryRunLengthEncoding(runlength.rle_to_brle(rle_data, dtype=dtype)) 

595 

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) 

601 

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 

613 

614 @caching.cache_decorator 

615 def sum(self): 

616 return self._data[1::2].sum() 

617 

618 @caching.cache_decorator 

619 def size(self): 

620 return runlength.brle_length(self._data) 

621 

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

626 

627 @property 

628 def sparse_components(self): 

629 return self.sparse_indices, self.sparse_values 

630 

631 @caching.cache_decorator 

632 def sparse_values(self): 

633 return np.ones(shape=(self.sum,), dtype=bool) 

634 

635 @caching.cache_decorator 

636 def sparse_indices(self): 

637 return runlength.brle_to_sparse(self._data) 

638 

639 @caching.cache_decorator 

640 def dense(self): 

641 return runlength.brle_to_dense(self._data) 

642 

643 def gather(self, indices): 

644 return runlength.brle_gather_1d(self._data, indices) 

645 

646 def gather_nd(self, indices): 

647 indices = np.squeeze(indices) 

648 return self.gather(indices) 

649 

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) 

653 

654 def mask(self, mask): 

655 gen = runlength.brle_mask(self._data, mask) 

656 return np.array(tuple(gen), dtype=bool) 

657 

658 def copy(self): 

659 return BinaryRunLengthEncoding(self._data.copy()) 

660 

661 def run_length_data(self, dtype=np.int64): 

662 return runlength.brle_to_rle(self._data, dtype=dtype) 

663 

664 def binary_run_length_data(self, dtype=np.int64): 

665 return runlength.brle_to_brle(self._data, dtype=dtype) 

666 

667 

668class LazyIndexMap(Encoding): 

669 """ 

670 Abstract class for implementing lazy index mapping operations. 

671 

672 Implementations include transpose, flatten/reshaping and flipping 

673 

674 Derived classes must implement: 

675 * _to_base_indices(indices) 

676 * _from_base_indices(base_indices) 

677 * shape 

678 * dense 

679 * mask(mask) 

680 """ 

681 

682 @abc.abstractmethod 

683 def _to_base_indices(self, indices): 

684 pass 

685 

686 @abc.abstractmethod 

687 def _from_base_indices(self, base_indices): 

688 pass 

689 

690 @property 

691 def is_empty(self): 

692 return self._data.is_empty 

693 

694 @property 

695 def dtype(self): 

696 return self._data.dtype 

697 

698 @property 

699 def sum(self): 

700 return self._data.sum 

701 

702 @property 

703 def size(self): 

704 return self._data.size 

705 

706 @property 

707 def sparse_indices(self): 

708 return self._from_base_indices(self._data.sparse_indices) 

709 

710 @property 

711 def sparse_values(self): 

712 return self._data.sparse_values 

713 

714 def gather_nd(self, indices): 

715 return self._data.gather_nd(self._to_base_indices(indices)) 

716 

717 def get_value(self, index): 

718 return self._data[tuple(self._to_base_indices(index))] 

719 

720 

721class FlattenedEncoding(LazyIndexMap): 

722 """ 

723 Lazily flattened encoding. 

724 

725 Dense equivalent is np.reshape(data, (-1,)) (np.flatten creates a copy). 

726 """ 

727 

728 def _to_base_indices(self, indices): 

729 return np.column_stack(np.unravel_index(indices, self._data.shape)) 

730 

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 ) 

735 

736 @property 

737 def shape(self): 

738 return (self.size,) 

739 

740 @property 

741 def dense(self): 

742 return self._data.dense.reshape((-1,)) 

743 

744 def mask(self, mask): 

745 return self._data.mask(mask.reshape(self._data.shape)) 

746 

747 @property 

748 def flat(self): 

749 return self 

750 

751 def copy(self): 

752 return FlattenedEncoding(self._data.copy()) 

753 

754 

755class ShapedEncoding(LazyIndexMap): 

756 """ 

757 Lazily reshaped encoding. 

758 

759 Numpy equivalent is `np.reshape` 

760 """ 

761 

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 ) 

780 

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 ) 

791 

792 def _from_base_indices(self, base_indices): 

793 return np.column_stack(np.unravel_index(base_indices, self.shape)) 

794 

795 def _to_base_indices(self, indices): 

796 return np.expand_dims(np.ravel_multi_index(indices.T, self.shape), axis=-1) 

797 

798 @property 

799 def flat(self): 

800 return self._data 

801 

802 @property 

803 def shape(self): 

804 return self._shape 

805 

806 @property 

807 def dense(self): 

808 return self._data.dense.reshape(self.shape) 

809 

810 def mask(self, mask): 

811 return self._data.mask(mask.flat) 

812 

813 def copy(self): 

814 return ShapedEncoding(encoding=self._data.copy(), shape=self.shape) 

815 

816 

817class TransposedEncoding(LazyIndexMap): 

818 """ 

819 Lazily transposed encoding 

820 

821 Dense equivalent is `np.transpose` 

822 """ 

823 

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 ) 

833 

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 

842 

843 def transpose(self, perm): 

844 return _transposed(self._data, [self._perm[p] for p in perm]) 

845 

846 def _transpose(self, perm): 

847 raise RuntimeError("Should not be here") 

848 

849 @property 

850 def perm(self): 

851 return self._perm 

852 

853 @property 

854 def shape(self): 

855 shape = self._data.shape 

856 return tuple(shape[p] for p in self._perm) 

857 

858 def _to_base_indices(self, indices): 

859 return np.take(indices, self._perm, axis=-1) 

860 

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 ) 

869 

870 @property 

871 def dense(self): 

872 return self._data.dense.transpose(self._perm) 

873 

874 def gather(self, indices): 

875 return self._data.gather(self._base_indices(indices)) 

876 

877 def mask(self, mask): 

878 return self._data.mask(mask.transpose(self._inv_perm)).transpose(self._perm) 

879 

880 def get_value(self, index): 

881 return self._data[tuple(self._base_indices(index))] 

882 

883 @property 

884 def data(self): 

885 return self._data 

886 

887 def copy(self): 

888 return TransposedEncoding(base_encoding=self._data.copy(), perm=self._perm) 

889 

890 

891class FlippedEncoding(LazyIndexMap): 

892 """ 

893 Encoding with entries flipped along one or more axes. 

894 

895 Dense equivalent is `np.flip` 

896 """ 

897 

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 ) 

913 

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 

921 

922 def _from_base_indices(self, base_indices): 

923 return self._to_base_indices(base_indices) 

924 

925 @property 

926 def shape(self): 

927 return self._data.shape 

928 

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 

935 

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) 

941 

942 def copy(self): 

943 return FlippedEncoding(self._data.copy(), self._axes) 

944 

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) 

956 

957 def _flip(self, axes): 

958 raise RuntimeError("Should not be here") 

959 

960 

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

976 

977 

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)