Coverage for trimesh/caching.py: 89%

268 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-22 02:08 +0000

1""" 

2caching.py 

3----------- 

4 

5Functions and classes that help with tracking changes 

6in `numpy.ndarray` and clearing cached values based 

7on those changes. 

8 

9You should really `pip install xxhash`: 

10 

11``` 

12In [23]: %timeit int(blake2b(d).hexdigest(), 16) 

13102 us +/- 684 ns per loop 

14 

15In [24]: %timeit int(sha256(d).hexdigest(), 16) 

16142 us +/- 3.73 us 

17 

18In [25]: %timeit xxh3_64_intdigest(d) 

193.37 us +/- 116 ns per loop 

20``` 

21""" 

22 

23import os 

24import time 

25from functools import wraps 

26from hashlib import blake2b as _blake2b 

27from hashlib import sha256 as _sha256 

28 

29import numpy as np 

30 

31from .constants import log 

32from .typed import Any, Callable, Hashable 

33from .util import is_sequence 

34 

35try: 

36 from collections.abc import Mapping 

37except BaseException: 

38 from collections.abc import Mapping 

39 

40 

41def sha256(item) -> int: 

42 return int(_sha256(item).hexdigest(), 16) 

43 

44 

45def hash_fallback(item): 

46 return int(_blake2b(item, usedforsecurity=False).hexdigest(), 16) 

47 

48 

49# xxhash is up to 30x faster than sha256: 

50# `pip install xxhash` 

51try: 

52 # newest version of algorithm 

53 from xxhash import xxh3_64_intdigest as hash_fast 

54except BaseException: 

55 try: 

56 # older version of the algorithm 

57 from xxhash import xxh64_intdigest as hash_fast 

58 except BaseException: 

59 # use hashlib as a fallback hashing library 

60 log.debug( 

61 "falling back to hashlib " 

62 + "hashing: `pip install xxhash`" 

63 + "for 50x faster cache checks" 

64 ) 

65 hash_fast = hash_fallback 

66 

67 

68def tracked_array(array, dtype=None): 

69 """ 

70 Properly subclass a numpy ndarray to track changes. 

71 

72 Avoids some pitfalls of subclassing by forcing contiguous 

73 arrays and does a view into a TrackedArray. 

74 

75 Parameters 

76 ------------ 

77 array : array- like object 

78 To be turned into a TrackedArray 

79 dtype : np.dtype 

80 Which dtype to use for the array 

81 

82 Returns 

83 ------------ 

84 tracked : TrackedArray 

85 Contains input array data. 

86 """ 

87 # if someone passed us None, just create an empty array 

88 if array is None: 

89 array = [] 

90 # make sure it is contiguous then view it as our subclass 

91 tracked = np.ascontiguousarray(array, dtype=dtype).view(TrackedArray) 

92 # should always be contiguous here 

93 assert tracked.flags["C_CONTIGUOUS"] 

94 

95 return tracked 

96 

97 

98def cache_decorator(function): 

99 """ 

100 A decorator for class methods, replaces @property 

101 but will store and retrieve function return values 

102 in object cache. 

103 

104 Parameters 

105 ------------ 

106 function : method 

107 This is used as a decorator: 

108 ``` 

109 @cache_decorator 

110 def foo(self, things): 

111 return 'happy days' 

112 ``` 

113 """ 

114 

115 # use wraps to preserve docstring 

116 @wraps(function) 

117 def get_cached(*args, **kwargs): 

118 """ 

119 Only execute the function if its value isn't stored 

120 in cache already. 

121 """ 

122 self = args[0] 

123 # use function name as key in cache 

124 name = function.__name__ 

125 # do the dump logic ourselves to avoid 

126 # verifying cache twice per call 

127 self._cache.verify() 

128 # access cache dict to avoid automatic validation 

129 # since we already called cache.verify manually 

130 if name in self._cache.cache: 

131 # already stored so return value 

132 return self._cache.cache[name] 

133 # value not in cache so execute the function 

134 value = function(*args, **kwargs) 

135 # store the value 

136 if ( 

137 self._cache.force_immutable 

138 and hasattr(value, "flags") 

139 and len(value.shape) > 0 

140 ): 

141 value.flags.writeable = False 

142 

143 self._cache.cache[name] = value 

144 

145 return value 

146 

147 # all cached values are also properties 

148 # so they can be accessed like value attributes 

149 # rather than functions 

150 return property(get_cached) 

151 

152 

153class TrackedArray(np.ndarray): 

154 """ 

155 Subclass of numpy.ndarray that provides hash methods 

156 to track changes. 

157 

158 General method is to aggressively set 'modified' flags 

159 on operations which might (but don't necessarily) alter 

160 the array, ideally we sometimes compute hashes when we 

161 don't need to, but we don't return wrong hashes ever. 

162 

163 We store boolean modified flag for each hash type to 

164 make checks fast even for queries of different hashes. 

165 

166 Methods 

167 ---------- 

168 __hash__ : int 

169 Runs the fastest available hash in this order: 

170 `xxh3_64, xxh_64, blake2b, sha256` 

171 """ 

172 

173 def __array_finalize__(self, obj): 

174 """ 

175 Sets a modified flag on every TrackedArray 

176 This flag will be set on every change as well as 

177 during copies and certain types of slicing. 

178 """ 

179 

180 self._dirty_hash = True 

181 if isinstance(obj, type(self)): 

182 obj._dirty_hash = True 

183 

184 def __array_wrap__(self, out_arr, context=None, *args, **kwargs): 

185 """ 

186 Return a numpy scalar if array is 0d. 

187 See https://github.com/numpy/numpy/issues/5819 

188 """ 

189 if out_arr.ndim: 

190 return np.ndarray.__array_wrap__(self, out_arr, context, *args, **kwargs) 

191 # Match numpy's behavior and return a numpy dtype scalar 

192 return out_arr[()] 

193 

194 @property 

195 def mutable(self): 

196 return self.flags["WRITEABLE"] 

197 

198 @mutable.setter 

199 def mutable(self, value): 

200 self.flags.writeable = value 

201 

202 def __hash__(self): 

203 """ 

204 Return a fast hash of the contents of the array. 

205 

206 Returns 

207 ------------- 

208 hash : long int 

209 A hash of the array contents. 

210 """ 

211 # repeat the bookkeeping to get a contiguous array 

212 if not self._dirty_hash and hasattr(self, "_hashed"): 

213 # we have a valid hash without recomputing. 

214 return self._hashed 

215 

216 # run a hashing function on the C-order bytes copy 

217 hashed = hash_fast(self.tobytes(order="C")) 

218 

219 # assign the value and set the flag 

220 self._hashed = hashed 

221 self._dirty_hash = False 

222 

223 return hashed 

224 

225 def __iadd__(self, *args, **kwargs): 

226 """ 

227 In-place addition. 

228 

229 The i* operations are in- place and modify the array, 

230 so we better catch all of them. 

231 """ 

232 

233 self._dirty_hash = True 

234 return super(self.__class__, self).__iadd__(*args, **kwargs) 

235 

236 def __isub__(self, *args, **kwargs): 

237 self._dirty_hash = True 

238 return super(self.__class__, self).__isub__(*args, **kwargs) 

239 

240 def fill(self, *args, **kwargs): 

241 self._dirty_hash = True 

242 return super(self.__class__, self).fill(*args, **kwargs) 

243 

244 def partition(self, *args, **kwargs): 

245 self._dirty_hash = True 

246 return super(self.__class__, self).partition(*args, **kwargs) 

247 

248 def put(self, *args, **kwargs): 

249 self._dirty_hash = True 

250 return super(self.__class__, self).put(*args, **kwargs) 

251 

252 def byteswap(self, *args, **kwargs): 

253 self._dirty_hash = True 

254 return super(self.__class__, self).byteswap(*args, **kwargs) 

255 

256 def itemset(self, *args, **kwargs): 

257 self._dirty_hash = True 

258 return super(self.__class__, self).itemset(*args, **kwargs) 

259 

260 def sort(self, *args, **kwargs): 

261 self._dirty_hash = True 

262 return super(self.__class__, self).sort(*args, **kwargs) 

263 

264 def setflags(self, *args, **kwargs): 

265 self._dirty_hash = True 

266 return super(self.__class__, self).setflags(*args, **kwargs) 

267 

268 def __imul__(self, *args, **kwargs): 

269 self._dirty_hash = True 

270 return super(self.__class__, self).__imul__(*args, **kwargs) 

271 

272 def __idiv__(self, *args, **kwargs): 

273 self._dirty_hash = True 

274 return super(self.__class__, self).__idiv__(*args, **kwargs) 

275 

276 def __itruediv__(self, *args, **kwargs): 

277 self._dirty_hash = True 

278 return super(self.__class__, self).__itruediv__(*args, **kwargs) 

279 

280 def __imatmul__(self, *args, **kwargs): 

281 self._dirty_hash = True 

282 return super(self.__class__, self).__imatmul__(*args, **kwargs) 

283 

284 def __ipow__(self, *args, **kwargs): 

285 self._dirty_hash = True 

286 return super(self.__class__, self).__ipow__(*args, **kwargs) 

287 

288 def __imod__(self, *args, **kwargs): 

289 self._dirty_hash = True 

290 return super(self.__class__, self).__imod__(*args, **kwargs) 

291 

292 def __ifloordiv__(self, *args, **kwargs): 

293 self._dirty_hash = True 

294 return super(self.__class__, self).__ifloordiv__(*args, **kwargs) 

295 

296 def __ilshift__(self, *args, **kwargs): 

297 self._dirty_hash = True 

298 return super(self.__class__, self).__ilshift__(*args, **kwargs) 

299 

300 def __irshift__(self, *args, **kwargs): 

301 self._dirty_hash = True 

302 return super(self.__class__, self).__irshift__(*args, **kwargs) 

303 

304 def __iand__(self, *args, **kwargs): 

305 self._dirty_hash = True 

306 return super(self.__class__, self).__iand__(*args, **kwargs) 

307 

308 def __ixor__(self, *args, **kwargs): 

309 self._dirty_hash = True 

310 return super(self.__class__, self).__ixor__(*args, **kwargs) 

311 

312 def __ior__(self, *args, **kwargs): 

313 self._dirty_hash = True 

314 return super(self.__class__, self).__ior__(*args, **kwargs) 

315 

316 def __setitem__(self, *args, **kwargs): 

317 self._dirty_hash = True 

318 return super(self.__class__, self).__setitem__(*args, **kwargs) 

319 

320 def __setslice__(self, *args, **kwargs): 

321 self._dirty_hash = True 

322 return super(self.__class__, self).__setslice__(*args, **kwargs) 

323 

324 

325class Cache: 

326 """ 

327 Class to cache values which will be stored until the 

328 result of an ID function changes. 

329 """ 

330 

331 def __init__(self, id_function: Callable[[], Hashable], force_immutable=False): 

332 """ 

333 Create a cache object. 

334 

335 Parameters 

336 ------------ 

337 id_function : Callable[[], Hashable] 

338 Returns a value that changes when the data changes 

339 force_immutable : bool 

340 If set will make all numpy arrays read-only 

341 """ 

342 self._id_function = id_function 

343 # for stored numpy arrays set `flags.writable = False` 

344 self.force_immutable = bool(force_immutable) 

345 # call the id function for initial value 

346 self.id_current = None 

347 # a counter for locks 

348 self._lock = 0 

349 # actual store for data 

350 self.cache = {} 

351 

352 def delete(self, key): 

353 """ 

354 Remove a key from the cache. 

355 """ 

356 if key in self.cache: 

357 self.cache.pop(key, None) 

358 

359 def verify(self): 

360 """ 

361 Verify that the cached values are still for the same 

362 value of id_function and delete all stored items if 

363 the value of id_function has changed. 

364 """ 

365 # if we are in a lock don't check anything 

366 if self._lock != 0: 

367 return 

368 

369 # check the hash of our data 

370 id_new = self._id_function() 

371 

372 # things changed 

373 if id_new != self.id_current: 

374 if len(self.cache) > 0: 

375 log.debug( 

376 "%d items cleared from cache: %s", 

377 len(self.cache), 

378 str(list(self.cache.keys())), 

379 ) 

380 # hash changed, so dump the cache 

381 # do it manually rather than calling clear() 

382 # as we are internal logic and can avoid function calls 

383 self.cache = {} 

384 # set the id to the new data hash 

385 self.id_current = id_new 

386 

387 def clear(self, exclude=None): 

388 """ 

389 Remove elements in the cache. 

390 

391 Parameters 

392 ----------- 

393 exclude : list 

394 List of keys in cache to not clear. 

395 """ 

396 if exclude is None: 

397 self.cache = {} 

398 else: 

399 self.cache = {k: v for k, v in self.cache.items() if k in exclude} 

400 

401 def update(self, items): 

402 """ 

403 Update the cache with a set of key, value pairs without 

404 checking id_function. 

405 """ 

406 self.cache.update(items) 

407 

408 if self.force_immutable: 

409 for v in self.cache.values(): 

410 if hasattr(v, "flags") and len(v.shape) > 0: 

411 v.flags.writeable = False 

412 self.id_set() 

413 

414 def id_set(self): 

415 """ 

416 Set the current ID to the value of the ID function. 

417 """ 

418 self.id_current = self._id_function() 

419 

420 def __getitem__(self, key: Hashable): 

421 """ 

422 Get an item from the cache. If the item 

423 is not in the cache, it will return None 

424 

425 Parameters 

426 ------------- 

427 key : Hashable 

428 Key in dict 

429 

430 Returns 

431 ------------- 

432 cached : object, or None 

433 Object that was stored 

434 """ 

435 self.verify() 

436 if key in self.cache: 

437 return self.cache[key] 

438 return None 

439 

440 def __setitem__(self, key: Hashable, value: Any): 

441 """ 

442 Add an item to the cache. 

443 

444 Parameters 

445 ------------ 

446 key : Hashable 

447 Key to reference value 

448 value : any 

449 Value to store in cache 

450 """ 

451 # dumpy cache if ID function has changed 

452 self.verify() 

453 # make numpy arrays read-only if asked to 

454 if self.force_immutable and hasattr(value, "flags") and len(value.shape) > 0: 

455 value.flags.writeable = False 

456 # assign data to dict 

457 self.cache[key] = value 

458 

459 return value 

460 

461 def __contains__(self, key): 

462 self.verify() 

463 return key in self.cache 

464 

465 def __len__(self): 

466 self.verify() 

467 return len(self.cache) 

468 

469 def __enter__(self): 

470 self._lock += 1 

471 

472 def __exit__(self, *args): 

473 self._lock -= 1 

474 self.id_current = self._id_function() 

475 

476 

477class DiskCache: 

478 """ 

479 Store results of expensive operations on disk 

480 with an option to expire the results. This is used 

481 to cache the multi-gigabyte test corpuses in 

482 `tests/corpus.py` 

483 """ 

484 

485 def __init__(self, path, expire_days=30): 

486 """ 

487 Create a cache on disk for storing expensive results. 

488 

489 Parameters 

490 -------------- 

491 path : str 

492 A writeable location on the current file path. 

493 expire_days : int or float 

494 How old should results be considered expired. 

495 

496 """ 

497 # store how old we allow results to be 

498 self.expire_days = expire_days 

499 # store the location for saving results 

500 self.path = os.path.abspath(os.path.expanduser(path)) 

501 # make sure the specified path exists 

502 os.makedirs(self.path, exist_ok=True) 

503 

504 def get(self, key, fetch): 

505 """ 

506 Get a key from the cache or run a calculation. 

507 

508 Parameters 

509 ----------- 

510 key : str 

511 Key to reference item with 

512 fetch : function 

513 If key isn't stored and recent run this 

514 function and store its result on disk. 

515 """ 

516 # hash the key so we have a fixed length string 

517 key_hash = _sha256(key.encode("utf-8")).hexdigest() 

518 # full path of result on local disk 

519 path = os.path.join(self.path, key_hash) 

520 

521 # check to see if we can use the cache 

522 if os.path.isfile(path): 

523 # compute the age of the existing file in days 

524 age_days = (time.time() - os.stat(path).st_mtime) / 86400.0 

525 if age_days < self.expire_days: 

526 # this nested condition means that 

527 # the file both exists and is recent 

528 # enough, so just return its contents 

529 with open(path, "rb") as f: 

530 return f.read() 

531 

532 log.debug(f"not in cache fetching: `{key}`") 

533 # since we made it here our data isn't cached 

534 # run the expensive function to fetch the file 

535 raw = fetch() 

536 # write the data so we can save it 

537 with open(path, "wb") as f: 

538 f.write(raw) 

539 

540 # return the data 

541 return raw 

542 

543 

544class DataStore(Mapping): 

545 """ 

546 A class to store multiple numpy arrays and track them all 

547 for changes. 

548 

549 Operates like a dict that only stores numpy.ndarray 

550 """ 

551 

552 def __init__(self): 

553 self.data = {} 

554 

555 def __iter__(self): 

556 return iter(self.data) 

557 

558 def pop(self, key): 

559 return self.data.pop(key, None) 

560 

561 def __delitem__(self, key): 

562 self.data.pop(key, None) 

563 

564 @property 

565 def mutable(self): 

566 """ 

567 Is data allowed to be altered or not. 

568 

569 Returns 

570 ----------- 

571 is_mutable : bool 

572 Can data be altered in the DataStore 

573 """ 

574 return getattr(self, "_mutable", True) 

575 

576 @mutable.setter 

577 def mutable(self, value): 

578 """ 

579 Is data allowed to be altered or not. 

580 

581 Parameters 

582 ------------ 

583 is_mutable : bool 

584 Should data be allowed to be altered 

585 """ 

586 # make sure passed value is a bool 

587 is_mutable = bool(value) 

588 # apply the flag to any data stored 

589 for v in self.data.values(): 

590 if isinstance(v, TrackedArray): 

591 v.mutable = value 

592 # save the mutable setting 

593 self._mutable = is_mutable 

594 

595 def is_empty(self): 

596 """ 

597 Is the current DataStore empty or not. 

598 

599 Returns 

600 ---------- 

601 empty : bool 

602 False if there are items in the DataStore 

603 """ 

604 if len(self.data) == 0: 

605 return True 

606 for v in self.data.values(): 

607 if is_sequence(v): 

608 if len(v) == 0: 

609 return True 

610 else: 

611 return False 

612 elif bool(np.isreal(v)): 

613 return False 

614 return True 

615 

616 def clear(self): 

617 """ 

618 Remove all data from the DataStore. 

619 """ 

620 self.data = {} 

621 

622 def __getitem__(self, key): 

623 return self.data[key] 

624 

625 def __setitem__(self, key: Hashable, data: Any): 

626 """ 

627 Store an item in the DataStore. 

628 

629 Parameters 

630 ------------- 

631 key : Hashable 

632 Key to store under 

633 data : Any 

634 Usually a numpy array which will be subclassed 

635 but anything hashable should be able to be stored. 

636 """ 

637 # we shouldn't allow setting on immutable datastores 

638 if not self.mutable: 

639 raise ValueError("DataStore is configured immutable!") 

640 

641 if isinstance(data, TrackedArray): 

642 # don't bother to re-track TrackedArray 

643 tracked = data 

644 elif isinstance(data, (np.ndarray, list, set, tuple)): 

645 # wrap data if it is array-like 

646 tracked = tracked_array(data) 

647 else: 

648 try: 

649 # will raise if this is not a hashable type 

650 hash(data) 

651 except BaseException: 

652 raise ValueError(f"unhashable `{key}:{type(data)}`") 

653 tracked = data 

654 

655 # apply our mutability setting 

656 if hasattr(self, "_mutable"): 

657 # apply our mutability setting only if it was explicitly set 

658 tracked.mutable = self.mutable 

659 # store data 

660 self.data[key] = tracked 

661 

662 def __contains__(self, key): 

663 return key in self.data 

664 

665 def __len__(self): 

666 return len(self.data) 

667 

668 def update(self, values): 

669 if not isinstance(values, dict): 

670 raise ValueError("Update only implemented for dicts") 

671 for key, value in values.items(): 

672 self[key] = value 

673 

674 def __hash__(self): 

675 """ 

676 Get a hash reflecting everything in the DataStore. 

677 

678 Returns 

679 ---------- 

680 hash : str 

681 hash of data in hexadecimal 

682 """ 

683 # only hash values that aren't None 

684 # or if they are arrays require length greater than zero 

685 return hash_fast( 

686 np.array( 

687 [ 

688 hash(v) 

689 for v in self.data.values() 

690 if v is not None and (not hasattr(v, "__len__") or len(v) > 0) 

691 ], 

692 dtype=np.int64, 

693 ).tobytes() 

694 )