Coverage for trimesh/util.py: 88%
777 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"""
2Grab bag of utility functions.
3"""
5import abc
6import base64
7import collections
8import json
9import logging
10import random
11import shutil
12import time
13import uuid
14import warnings
15import zipfile
16from collections.abc import (
17 Callable,
18 Collection,
19 Iterator,
20 Mapping,
21 MutableMapping,
22 MutableSet,
23 Sequence,
24)
25from copy import deepcopy
26from dataclasses import asdict as dataclass_to_dict
27from io import BytesIO, StringIO
28from typing import TYPE_CHECKING
30import numpy as np
32from .iteration import chain
34# use our wrapped types for wider version compatibility
35from .typed import (
36 Any,
37 ArrayLike,
38 BoolIsFile,
39 Floating,
40 Hashable,
41 Integer,
42 Iterable,
43 NDArray,
44 NDArray1D,
45 NDArray2D,
46 Number,
47 Seed,
48 Stream,
49)
51# imported only so type checkers can resolve the dotted forward-ref
52# string return below — never imported at runtime, and beartype
53# re-imports the dotted path itself when the function is first called
54if TYPE_CHECKING:
55 import trimesh.parent
57# create a default logger
58log: logging.Logger = logging.getLogger(__name__)
60ABC = abc.ABC
61now = time.time
62which = shutil.which
64# include constants here so we don't have to import
65# a floating point threshold for 0.0
66# we are setting it to 100x the resolution of a float64
67# which works out to be 1e-13
68TOL_ZERO: float = float(np.finfo(np.float64).resolution * 100)
69# how close to merge vertices
70TOL_MERGE: float = 1e-8
71# enable additional potentially slow checks
72_STRICT: bool = False
74# beartype is unable to resolve `NDArray[float64]` for globals
75_IDENTITY: np.ndarray = np.eye(4, dtype=np.float64)
76_IDENTITY.flags["WRITEABLE"] = False
78# one process-wide generator for the unseeded case: constructing one
79# collects OS entropy which costs ~200x more than the draw it feeds
80_RANDOM_DEFAULT = np.random.default_rng()
83def random_generator(seed: Seed = None) -> np.random.Generator:
84 """
85 Get a random generator, optionally seeded for deterministic results.
87 Parameters
88 ----------
89 seed
90 If None use a shared generator seeded from OS entropy. An integer
91 seeds a fresh generator. A `Generator` is returned unaltered which
92 lets a caller thread one stream through nested calls rather than
93 re-seeding each of them to identical values.
95 Returns
96 -------
97 generator
98 Draw random values from this.
99 """
100 if seed is None:
101 # numpy locks the bit generator on every draw so sharing
102 # this between threads is as safe as `numpy.random.random`
103 return _RANDOM_DEFAULT
104 return np.random.default_rng(seed)
107def has_module(name: str) -> bool:
108 """
109 Check to see if a module is installed by name without
110 actually importing the module.
112 Parameters
113 ------------
114 name : str
115 The name of the module to check
117 Returns
118 ------------
119 installed : bool
120 True if module is installed
121 """
122 from importlib.util import find_spec
124 return find_spec(name) is not None
127def unitize(
128 vectors: ArrayLike,
129 check_valid: bool = False,
130 threshold: Number | None = None,
131):
132 """
133 Unitize a vector or an array or row-vectors.
135 Parameters
136 ------------
137 vectors : (n,m) or (j) float
138 Vector or vectors to be unitized
139 check_valid : bool
140 If set, will return mask of nonzero vectors
141 threshold : float
142 Cutoff for a value to be considered zero.
144 Returns
145 ---------
146 unit : (n,m) or (j) float
147 Input vectors but unitized
148 valid : (n,) bool or bool
149 Mask of nonzero vectors returned if `check_valid`
150 """
151 # make sure we have a numpy array
152 vectors = np.asanyarray(vectors)
154 # allow user to set zero threshold
155 if threshold is None:
156 threshold = TOL_ZERO
158 if len(vectors.shape) == 2:
159 # for (m, d) arrays take the per-row unit vector
160 # using sqrt and avoiding exponents is slightly faster
161 # also dot with ones is faser than .sum(axis=1)
162 norm = np.sqrt(np.dot(vectors * vectors, [1.0] * vectors.shape[1]))
163 # non-zero norms
164 valid = norm > threshold
165 # in-place reciprocal of nonzero norms
166 norm[valid] **= -1
167 # multiply by reciprocal of norm
168 unit = vectors * norm.reshape((-1, 1))
170 elif len(vectors.shape) == 1:
171 # treat 1D arrays as a single vector
172 norm = np.sqrt(np.dot(vectors, vectors))
173 valid = norm > threshold
174 if valid:
175 unit = vectors / norm
176 else:
177 unit = vectors.copy()
178 else:
179 raise ValueError("vectors must be (n, ) or (n, d)!")
181 if check_valid:
182 return unit[valid], valid
183 return unit
186def euclidean(a: ArrayLike, b: ArrayLike) -> np.float64:
187 """
188 DEPRECATED: use `np.linalg.norm(a - b)` instead of this.
189 """
190 warnings.warn(
191 "`trimesh.util.euclidean` is deprecated "
192 + "and will be removed in January 2025. "
193 + "replace with `np.linalg.norm(a - b)`",
194 category=DeprecationWarning,
195 stacklevel=2,
196 )
198 a = np.asanyarray(a, dtype=np.float64)
199 b = np.asanyarray(b, dtype=np.float64)
200 return np.sqrt(((a - b) ** 2).sum())
203def is_file(obj: Any) -> BoolIsFile:
204 """
205 Check if an object is file-like
207 Parameters
208 ------------
209 obj : object
210 Any object type to be checked
212 Returns
213 -----------
214 is_file : bool
215 True if object is a file
216 """
217 return hasattr(obj, "read") or hasattr(obj, "write")
220def is_pathlib(obj: object) -> bool:
221 """
222 Check if the object is a `pathlib.Path` or subclass.
224 Parameters
225 ------------
226 obj : object
227 Object to be checked
229 Returns
230 ------------
231 is_pathlib : bool
232 Is the input object a pathlib path
233 """
234 # check class name rather than a pathlib import
235 name = obj.__class__.__name__
236 return hasattr(obj, "absolute") and name.endswith("Path")
239def is_string(obj: object) -> bool:
240 """
241 DEPRECATED : this is not necessary since we dropped Python 2.
243 Replace with `isinstance(obj, str)`
244 """
245 warnings.warn(
246 "`trimesh.util.is_string` is deprecated "
247 + "and will be removed in January 2025. "
248 + "replace with `isinstance(obj, str)`",
249 category=DeprecationWarning,
250 stacklevel=2,
251 )
253 return isinstance(obj, str)
256def is_sequence(obj: Any) -> bool:
257 """
258 Check if an object is a sequence or not.
260 Parameters
261 -------------
262 obj : object
263 Any object type to be checked
265 Returns
266 -------------
267 is_sequence : bool
268 True if object is sequence
269 """
270 seq = (not hasattr(obj, "strip") and hasattr(obj, "__getitem__")) or hasattr(
271 obj, "__iter__"
272 )
274 # check to make sure it is not a set, string, or dictionary
275 seq = seq and all(not isinstance(obj, i) for i in (dict, set, str))
277 # PointCloud objects can look like an array but are not
278 seq = seq and type(obj).__name__ not in ["PointCloud"]
280 # numpy sometimes returns objects that are single float64 values
281 # but sure look like sequences, so we check the shape
282 if hasattr(obj, "shape"):
283 seq = seq and obj.shape != ()
285 return seq
288def is_shape(
289 obj: NDArray | Any,
290 shape: Sequence[Integer | tuple[Integer, ...]],
291 allow_zeros: bool = False,
292) -> bool:
293 """
294 Compare the shape of a numpy.ndarray to a target shape,
295 with any value less than zero being considered a wildcard
297 Note that if a list-like object is passed that is not a numpy
298 array, this function will not convert it and will return False.
300 Parameters
301 ------------
302 obj : np.ndarray
303 Array to check the shape on
304 shape : list or tuple
305 Any negative term will be considered a wildcard
306 Any tuple term will be evaluated as an OR
307 allow_zeros: bool
308 if False, zeros do not match negatives in shape
310 Returns
311 ---------
312 shape_ok : bool
313 True if shape of obj matches query shape
315 Examples
316 ------------------------
317 In [1]: a = np.random.random((100, 3))
319 In [2]: a.shape
320 Out[2]: (100, 3)
322 In [3]: trimesh.util.is_shape(a, (-1, 3))
323 Out[3]: True
325 In [4]: trimesh.util.is_shape(a, (-1, 3, 5))
326 Out[4]: False
328 In [5]: trimesh.util.is_shape(a, (100, -1))
329 Out[5]: True
331 In [6]: trimesh.util.is_shape(a, (-1, (3, 4)))
332 Out[6]: True
334 In [7]: trimesh.util.is_shape(a, (-1, (4, 5)))
335 Out[7]: False
336 """
338 # if the obj.shape is different length than
339 # the goal shape it means they have different number
340 # of dimensions and thus the obj is not the query shape
341 if not hasattr(obj, "shape") or len(obj.shape) != len(shape):
342 return False
344 # empty lists with any flexible dimensions match
345 if len(obj) == 0 and -1 in shape:
346 return True
348 # loop through each integer of the two shapes
349 # multiple values are sequences
350 # wildcards are less than zero (i.e. -1)
351 for i, target in zip(obj.shape, shape):
352 # check if current field has multiple acceptable values
353 # an explicit tuple/list check narrows `target` for type
354 # checkers — `is_sequence` is not a type guard
355 if isinstance(target, (list, tuple)):
356 if i in target:
357 # obj shape is in the accepted values
358 continue
359 else:
360 return False
362 # check if current field is a wildcard
363 if int(target) < 0:
364 if i == 0 and not allow_zeros:
365 # if a dimension is 0, we don't allow
366 # that to match to a wildcard
367 # it would have to be explicitly called out as 0
368 return False
369 else:
370 continue
371 # since we have a single target and a single value,
372 # if they are not equal we have an answer
373 if target != i:
374 return False
376 # since none of the checks failed the obj.shape
377 # matches the pattern
378 return True
381def make_sequence(obj: Any) -> list:
382 """
383 Given an object, if it is a sequence return, otherwise
384 add it to a length 1 sequence and return.
386 Useful for wrapping functions which sometimes return single
387 objects and other times return lists of objects.
389 Parameters
390 -------------
391 obj : object
392 An object to be made a sequence
394 Returns
395 --------------
396 as_sequence : (n,) sequence
397 Contains input value
398 """
399 if is_sequence(obj):
400 return list(obj)
401 else:
402 return [obj]
405def vector_hemisphere(
406 vectors: ArrayLike,
407 return_sign: bool = False,
408):
409 """
410 For a set of 3D vectors alter the sign so they are all in the
411 upper hemisphere.
413 If the vector lies on the plane all vectors with negative Y
414 will be reversed.
416 If the vector has a zero Z and Y value vectors with a
417 negative X value will be reversed.
419 Parameters
420 ------------
421 vectors : (n, 3) float
422 Input vectors
423 return_sign : bool
424 Return the sign mask or not
426 Returns
427 ----------
428 oriented: (n, 3) float
429 Vectors with same magnitude as source
430 but possibly reversed to ensure all vectors
431 are in the same hemisphere.
432 sign : (n,) float
433 [OPTIONAL] sign of original vectors
434 """
435 # vectors as numpy array
436 vectors = np.asanyarray(vectors, dtype=np.float64)
438 if is_shape(vectors, (-1, 2)):
439 # 2D vector case
440 # check the Y value and reverse vector
441 # direction if negative.
442 negative = vectors < -TOL_ZERO
443 zero = np.logical_not(np.logical_or(negative, vectors > TOL_ZERO))
445 signs = np.ones(len(vectors), dtype=np.float64)
446 # negative Y values are reversed
447 signs[negative[:, 1]] = -1.0
449 # zero Y and negative X are reversed
450 signs[np.logical_and(zero[:, 1], negative[:, 0])] = -1.0
452 elif is_shape(vectors, (-1, 3)):
453 # 3D vector case
454 negative = vectors < -TOL_ZERO
455 zero = np.logical_not(np.logical_or(negative, vectors > TOL_ZERO))
456 # move all negative Z to positive
457 # then for zero Z vectors, move all negative Y to positive
458 # then for zero Y vectors, move all negative X to positive
459 signs = np.ones(len(vectors), dtype=np.float64)
460 # all vectors with negative Z values
461 signs[negative[:, 2]] = -1.0
462 # all on-plane vectors with negative Y values
463 signs[np.logical_and(zero[:, 2], negative[:, 1])] = -1.0
464 # all on-plane vectors with zero Y values
465 # and negative X values
466 signs[
467 np.logical_and(np.logical_and(zero[:, 2], zero[:, 1]), negative[:, 0])
468 ] = -1.0
470 else:
471 raise ValueError("vectors must be (n, 3)!")
473 # apply the signs to the vectors
474 oriented = vectors * signs.reshape((-1, 1))
476 if return_sign:
477 return oriented, signs
479 return oriented
482def vector_to_spherical(cartesian: ArrayLike) -> NDArray2D[np.float64]:
483 """
484 Convert a set of cartesian points to (n, 2) spherical unit
485 vectors.
487 Parameters
488 ------------
489 cartesian : (n, 3) float
490 Points in space
492 Returns
493 ------------
494 spherical : (n, 2) float
495 Angles, in radians
496 """
497 cartesian = np.asanyarray(cartesian, dtype=np.float64)
498 if not is_shape(cartesian, (-1, 3)):
499 raise ValueError("Cartesian points must be (n, 3)!")
501 unit, valid = unitize(cartesian, check_valid=True)
502 unit[np.abs(unit) < TOL_MERGE] = 0.0
504 x, y, z = unit.T
505 spherical = np.zeros((len(cartesian), 2), dtype=np.float64)
506 spherical[valid] = np.column_stack((np.arctan2(y, x), np.arccos(z)))
507 return spherical
510def spherical_to_vector(spherical: ArrayLike) -> NDArray2D[np.float64]:
511 """
512 Convert an array of `(n, 2)` spherical angles to `(n, 3)` unit vectors.
514 Parameters
515 ------------
516 spherical : (n , 2) float
517 Angles, in radians
519 Returns
520 -----------
521 vectors : (n, 3) float
522 Unit vectors
523 """
524 spherical = np.asanyarray(spherical, dtype=np.float64)
525 if not is_shape(spherical, (-1, 2)):
526 raise ValueError("spherical coordinates must be (n, 2)!")
528 theta, phi = spherical.T
529 st, ct = np.sin(theta), np.cos(theta)
530 sp, cp = np.sin(phi), np.cos(phi)
531 return np.column_stack((ct * sp, st * sp, cp))
534def pairwise(iterable: Iterable[Any]):
535 """
536 For an iterable, group values into pairs.
538 Parameters
539 ------------
540 iterable : (m, ) list
541 A sequence of values
543 Returns
544 -----------
545 pairs: (n, 2)
546 Pairs of sequential values
548 Example
549 -----------
550 In [1]: data
551 Out[1]: [0, 1, 2, 3, 4, 5, 6]
553 In [2]: list(trimesh.util.pairwise(data))
554 Out[2]: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
556 """
557 # looping through a giant numpy array would be dumb
558 # so special case ndarrays and use numpy operations
559 if isinstance(iterable, np.ndarray):
560 iterable = iterable.reshape(-1)
561 stacked = np.column_stack((iterable, iterable))
562 pairs = stacked.reshape(-1)[1:-1].reshape((-1, 2))
563 return pairs
565 # if we have a normal iterable use itertools
566 import itertools
568 a, b = itertools.tee(iterable)
569 # pop the first element of the second item
570 next(b)
572 return zip(a, b)
575multi_dot = np.linalg.multi_dot
578def diagonal_dot(a: ArrayLike, b: ArrayLike) -> np.ndarray[tuple[int], np.dtype[Any]]:
579 """
580 Dot product by row of a and b.
582 There are a lot of ways to do this though
583 performance varies very widely. This method
584 uses a dot product to sum the row and avoids
585 function calls if at all possible.
587 Comparing performance of some equivalent versions:
588 ```
589 In [1]: import numpy as np; import trimesh
591 In [2]: a = np.random.random((10000, 3))
593 In [3]: b = np.random.random((10000, 3))
595 In [4]: %timeit (a * b).sum(axis=1)
596 1000 loops, best of 3: 181 us per loop
598 In [6]: %timeit np.diag(np.dot(a, b.T))
599 1 loop, best of 3: 429 ms per loop
601 In [7]: %timeit np.dot(a * b, np.ones(a.shape[1]))
602 10000 loops, best of 3: 61.3 us per loop
604 In [8]: %timeit trimesh.util.diagonal_dot(a, b)
605 10000 loops, best of 3: 55.2 us per loop
606 ```
608 Parameters
609 ------------
610 a : (m, d) float
611 First array
612 b : (m, d) float
613 Second array
615 Returns
616 -------------
617 result : (m,) float
618 Dot product of each row
619 """
620 # make sure `a` is numpy array
621 # doing it for `a` will force the multiplication to
622 # convert `b` if necessary and avoid function call otherwise
623 a = np.asanyarray(a)
624 # 3x faster than (a * b).sum(axis=1)
625 # avoiding np.ones saves 5-10% sometimes
626 return np.dot(a * b, [1.0] * a.shape[1])
629def row_norm(data: NDArray2D[Any]) -> NDArray1D[np.float64]:
630 """
631 Compute the norm per-row of a numpy array.
633 This is identical to np.linalg.norm(data, axis=1) but roughly
634 three times faster due to being less general.
636 In [3]: %timeit trimesh.util.row_norm(a)
637 76.3 us +/- 651 ns per loop
639 In [4]: %timeit np.linalg.norm(a, axis=1)
640 220 us +/- 5.41 us per loop
642 Parameters
643 -------------
644 data : (n, d) float
645 Input 2D data to calculate per-row norm of
647 Returns
648 -------------
649 norm : (n,) float
650 Norm of each row of input array
651 """
652 return np.sqrt(np.dot(data**2, [1] * data.shape[1]))
655def stack_3D(
656 points: ArrayLike,
657 return_2D: bool = False,
658) -> NDArray2D[np.float64] | tuple[NDArray2D[np.float64], bool]:
659 """
660 For a list of (n, 2) or (n, 3) points return them
661 as (n, 3) 3D points, 2D points on the XY plane.
663 Parameters
664 ------------
665 points : (n, 2) or (n, 3) float
666 Points in either 2D or 3D space
667 return_2D : bool
668 Were the original points 2D?
670 Returns
671 ----------
672 points : (n, 3) float
673 Points in space
674 is_2D : bool
675 [OPTIONAL] if source points were (n, 2)
676 """
677 points = np.asanyarray(points, dtype=np.float64)
678 shape = points.shape
680 if shape == (0,):
681 is_2D = False
682 elif len(shape) != 2:
683 raise ValueError("Points must be 2D array!")
684 elif shape[1] == 2:
685 points = np.column_stack((points, np.zeros(len(points))))
686 is_2D = True
687 elif shape[1] == 3:
688 is_2D = False
689 else:
690 raise ValueError("Points must be (n, 2) or (n, 3)!")
692 if return_2D:
693 return points, is_2D
695 return points
698def grid_arange(bounds: ArrayLike, step: Number | ArrayLike) -> NDArray2D[np.float64]:
699 """
700 Return a grid from an (2,dimension) bounds with samples step distance apart.
702 Parameters
703 ------------
704 bounds: (2,dimension) list of [[min x, min y, etc], [max x, max y, etc]]
705 step: float, or (dimension) floats, separation between points
707 Returns
708 ---------
709 grid: (n, dimension), points inside the specified bounds
710 """
711 bounds = np.asanyarray(bounds, dtype=np.float64)
712 if len(bounds) != 2:
713 raise ValueError("bounds must be (2, dimension!")
715 # allow single float or per-dimension spacing
716 step = np.asanyarray(step, dtype=np.float64)
717 if step.shape == ():
718 step = np.tile(step, bounds.shape[1])
720 grid_elements = [np.arange(*b, step=s) for b, s in zip(bounds.T, step)]
721 grid = (
722 np.vstack(np.meshgrid(*grid_elements, indexing="ij"))
723 .reshape(bounds.shape[1], -1)
724 .T
725 )
726 return grid
729def grid_linspace(bounds: ArrayLike, count: Integer | ArrayLike) -> NDArray2D[np.float64]:
730 """
731 Return a grid spaced inside a bounding box with edges spaced using np.linspace.
733 Parameters
734 ------------
735 bounds: (2,dimension) list of [[min x, min y, etc], [max x, max y, etc]]
736 count: int, or (dimension,) int, number of samples per side
738 Returns
739 ---------
740 grid: (n, dimension) float, points in the specified bounds
741 """
742 bounds = np.asanyarray(bounds, dtype=np.float64)
743 if len(bounds) != 2:
744 raise ValueError("bounds must be (2, dimension!")
746 count = np.asanyarray(count, dtype=np.int64)
747 if count.shape == ():
748 count = np.tile(count, bounds.shape[1])
750 grid_elements = [np.linspace(*b, num=c) for b, c in zip(bounds.T, count)]
751 grid = (
752 np.vstack(np.meshgrid(*grid_elements, indexing="ij"))
753 .reshape(bounds.shape[1], -1)
754 .T
755 )
756 return grid
759def multi_dict(
760 pairs: ArrayLike | Iterable[tuple[Hashable, Any]],
761) -> collections.defaultdict[Hashable, list]:
762 """
763 Given a set of key value pairs, create a dictionary.
764 If a key occurs multiple times, stack the values into an array.
766 Can be called like the regular dict(pairs) constructor
768 Parameters
769 ------------
770 pairs: (n, 2) array of key, value pairs
772 Returns
773 ----------
774 result: dict, with all values stored (rather than last with regular dict)
776 """
777 result = collections.defaultdict(list)
778 for k, v in pairs:
779 result[k].append(v)
780 return result
783def tolist(data: object) -> Any:
784 """
785 Ensure that any arrays or dicts passed containing
786 numpy arrays are properly converted to lists
788 Parameters
789 -------------
790 data : any
791 Usually a dict with some numpy arrays as values
793 Returns
794 ----------
795 result : any
796 JSON-serializable version of data
797 """
798 result = json.loads(jsonify(data))
799 return result
802def is_binary_file(file_obj: Stream) -> bool:
803 """
804 Returns True if file has non-ASCII characters (> 0x7F, or 127)
805 """
806 start = file_obj.tell()
807 fbytes = file_obj.read(1024)
808 file_obj.seek(start)
809 is_str = isinstance(fbytes, str)
810 for fbyte in fbytes:
811 if is_str:
812 code = ord(fbyte)
813 else:
814 code = fbyte
815 if code > 127:
816 return True
817 return False
820def distance_to_end(file_obj: Stream) -> int:
821 """
822 For an open file object how far is it to the end
824 Parameters
825 ------------
826 file_obj: open file-like object
828 Returns
829 ----------
830 distance: int, bytes to end of file
831 """
832 position_current = file_obj.tell()
833 file_obj.seek(0, 2)
834 position_end = file_obj.tell()
835 file_obj.seek(position_current)
836 distance = position_end - position_current
837 return distance
840def decimal_to_digits(decimal: Floating, min_digits: Integer | None = None) -> int:
841 """
842 Return the number of digits to the first nonzero decimal.
844 Parameters
845 -----------
846 decimal: float
847 min_digits: int, minimum number of digits to return
849 Returns
850 -----------
852 digits: int, number of digits to the first nonzero decimal
853 """
854 digits = abs(int(np.log10(decimal)))
855 if min_digits is not None:
856 digits = np.clip(digits, min_digits, 20)
857 return int(digits)
860def attach_to_log(
861 level: Integer = logging.DEBUG,
862 handler: logging.Handler | None = None,
863 loggers: MutableSet[logging.Logger] | None = None,
864 colors: bool = True,
865 capture_warnings: bool = True,
866 blacklist: Iterable[str] | None = None,
867 only_parent: bool = True,
868) -> None:
869 """
870 Attach a stream handler to all loggers.
872 Parameters
873 ------------
874 level : enum
875 Logging level, like logging.INFO
876 handler : None or logging.Handler
877 Handler to attach
878 loggers : None or (n,) logging.Logger
879 If None, will try to attach to all available
880 colors : bool
881 If True try to use colorlog formatter
882 blacklist : (n,) str
883 Names of loggers NOT to attach to
884 only_parent
885 Only attach to parent loggers, i.e. `trimesh`, `trimesh.sub1`, `trimesh.sub2`
886 will only attach to `trimesh` and not the sub-loggers
887 """
889 # default blacklist includes ipython debugging stuff
890 if blacklist is None:
891 blacklist = [
892 "TerminalIPythonApp",
893 "PYREADLINE",
894 "pyembree",
895 "shapely",
896 "matplotlib",
897 "parso.cache",
898 "parso",
899 "parso.python.diff",
900 "asyncio",
901 "prompt_toolkit.buffer",
902 ]
904 # make sure we log warnings from the warnings module
905 logging.captureWarnings(capture_warnings)
907 # create a basic formatter
908 formatter = logging.Formatter(
909 "[%(asctime)s] %(levelname)-7s (%(filename)s:%(lineno)3s) %(message)s",
910 "%Y-%m-%d %H:%M:%S",
911 )
912 if colors:
913 try:
914 from colorlog import ColoredFormatter
916 formatter = ColoredFormatter(
917 (
918 "%(log_color)s%(levelname)-8s%(reset)s "
919 + "%(filename)17s:%(lineno)-4s %(blue)4s%(message)s"
920 ),
921 datefmt=None,
922 reset=True,
923 log_colors={
924 "DEBUG": "cyan",
925 "INFO": "green",
926 "WARNING": "yellow",
927 "ERROR": "red",
928 "CRITICAL": "red",
929 },
930 )
931 except ImportError:
932 pass
934 # if no handler was passed use a StreamHandler
935 if handler is None:
936 handler = logging.StreamHandler()
938 # add the formatters and set the level
939 handler.setFormatter(formatter)
940 # numpy integers aren't `int` subclasses — coerce for the stdlib stubs
941 handler.setLevel(int(level))
943 # if nothing passed use all available loggers
944 if loggers is None:
945 # de-duplicate loggers using a set
946 loggers = set(logging.Logger.manager.loggerDict.values())
948 # add the warnings logging
949 loggers.add(logging.getLogger("py.warnings"))
951 # disable pyembree warnings
952 logging.getLogger("pyembree").disabled = True
954 # cull loggers that are not actually loggers or are on the blacklist
955 loggers_dict = {
956 L.name: L
957 for L in loggers
958 if hasattr(L, "name")
959 and isinstance(L, logging.Logger)
960 and L.name not in blacklist
961 }
963 if only_parent:
964 # create a new dict to store only parent loggers
965 parent_loggers = {}
966 # sort logger names to process in hierarchical order
967 for name in sorted(loggers_dict.keys()):
968 # if it's not a child of any existing parent, add it as a parent
969 if not any(name.startswith(f"{p}.") for p in parent_loggers.keys()):
970 parent_loggers[name] = loggers_dict[name]
971 # replace loggers dict with only parent loggers
972 loggers_dict = parent_loggers
974 # loop through all available loggers
975 for logger in loggers_dict.values():
976 logger.addHandler(handler)
977 logger.setLevel(int(level))
979 # set nicer numpy print options
980 np.set_printoptions(precision=5, suppress=True)
983def stack_lines(indices: ArrayLike) -> NDArray:
984 """
985 Stack a list of values that represent a polyline into
986 individual line segments with duplicated consecutive values.
988 Parameters
989 ------------
990 indices : (m,) any
991 List of items to be stacked
993 Returns
994 ---------
995 stacked : (n, 2) any
996 Stacked items
998 Examples
999 ----------
1000 In [1]: trimesh.util.stack_lines([0, 1, 2])
1001 Out[1]:
1002 array([[0, 1],
1003 [1, 2]])
1005 In [2]: trimesh.util.stack_lines([0, 1, 2, 4, 5])
1006 Out[2]:
1007 array([[0, 1],
1008 [1, 2],
1009 [2, 4],
1010 [4, 5]])
1012 In [3]: trimesh.util.stack_lines([[0, 0], [1, 1], [2, 2], [3, 3]])
1013 Out[3]:
1014 array([[0, 0],
1015 [1, 1],
1016 [1, 1],
1017 [2, 2],
1018 [2, 2],
1019 [3, 3]])
1021 """
1022 indices = np.asanyarray(indices)
1023 if len(indices) == 0:
1024 return np.array([])
1025 elif is_sequence(indices[0]):
1026 shape = (-1, len(indices[0]))
1027 else:
1028 shape = (-1, 2)
1029 return np.column_stack((indices[:-1], indices[1:])).reshape(shape)
1032def append_faces(
1033 vertices_seq: Iterable[ArrayLike],
1034 faces_seq: Iterable[ArrayLike],
1035) -> tuple[NDArray2D[np.floating], NDArray2D[np.integer]]:
1036 """
1037 Given a sequence of zero-indexed faces and vertices
1038 combine them into a single array of faces and
1039 a single array of vertices.
1041 Parameters
1042 -----------
1043 vertices_seq : (n, ) sequence of (m, d) float
1044 Multiple arrays of verticesvertex arrays
1045 faces_seq : (n, ) sequence of (p, j) int
1046 Zero indexed faces for matching vertices
1048 Returns
1049 ----------
1050 vertices : (i, d) float
1051 Points in space
1052 faces : (j, 3) int
1053 Reference vertex indices
1054 """
1055 # the length of each vertex array
1056 vertices_len = np.array([len(i) for i in vertices_seq], dtype=np.int64)
1057 # how much each group of faces needs to be offset
1058 face_offset = np.append(0, np.cumsum(vertices_len)[:-1])
1060 new_faces = []
1061 for offset, faces in zip(face_offset, faces_seq):
1062 if len(faces) == 0:
1063 continue
1064 # apply the index offset
1065 new_faces.append(faces + offset)
1066 # stack to clean (n, 3) float
1067 vertices = vstack_empty(vertices_seq)
1068 # stack to clean (n, 3) int
1069 faces = vstack_empty(new_faces)
1071 # an all-empty stack collapses to a 1d float array — restore the
1072 # documented 2d shape and integer face dtype
1073 if len(vertices) == 0:
1074 vertices = vertices.reshape((0, 3))
1075 if len(faces) == 0:
1076 faces = faces.reshape((0, 3)).astype(np.int64)
1078 return vertices, faces
1081def array_to_string(
1082 array: ArrayLike,
1083 col_delim: str = " ",
1084 row_delim: str = "\n",
1085 digits: Integer = 8,
1086 value_format: str = "{}",
1087) -> str:
1088 """
1089 Convert a 1 or 2D array into a string with a specified number
1090 of digits and delimiter. The reason this exists is that the
1091 basic numpy array to string conversions are surprisingly slow.
1093 Parameters
1094 ------------
1095 array : (n,) or (n, d) float or int
1096 Data to be converted
1097 If shape is (n,) only column delimiter will be used
1098 col_delim : str
1099 What string should separate values in a column
1100 row_delim : str
1101 What string should separate values in a row
1102 digits : int
1103 How many digits should floating point numbers include
1104 value_format : str
1105 Format string for each value or sequence of values
1106 If multiple values per value_format it must divide
1107 into array evenly.
1109 Returns
1110 ----------
1111 formatted : str
1112 String representation of original array
1113 """
1114 # convert inputs to correct types
1115 array = np.asanyarray(array)
1116 digits = int(digits)
1117 row_delim = str(row_delim)
1118 col_delim = str(col_delim)
1119 value_format = str(value_format)
1121 # abort for non-flat arrays
1122 if len(array.shape) > 2:
1123 raise ValueError(
1124 "conversion only works on 1D/2D arrays not %s!", str(array.shape)
1125 )
1127 # abort for structured arrays
1128 if array.dtype.names is not None:
1129 raise ValueError("array is structured, use structured_array_to_string instead")
1131 # allow a value to be repeated in a value format
1132 repeats = value_format.count("{")
1134 if array.dtype.kind in ["i", "u"]:
1135 # integer types don't need a specified precision
1136 format_str = value_format + col_delim
1137 elif array.dtype.kind == "f":
1138 # add the digits formatting to floats
1139 format_str = value_format.replace("{}", "{:." + str(digits) + "f}") + col_delim
1140 else:
1141 raise ValueError("dtype %s not convertible!", array.dtype.name)
1143 # length of extra delimiters at the end
1144 end_junk = len(col_delim)
1145 # if we have a 2D array add a row delimiter
1146 if len(array.shape) == 2:
1147 format_str *= array.shape[1]
1148 # cut off the last column delimiter and add a row delimiter
1149 format_str = format_str[: -len(col_delim)] + row_delim
1150 end_junk = len(row_delim)
1152 # expand format string to whole array
1153 format_str *= len(array)
1155 # if an array is repeated in the value format
1156 # do the shaping here so we don't need to specify indexes
1157 shaped = np.tile(array.reshape((-1, 1)), (1, repeats)).reshape(-1)
1159 # run the format operation and remove the extra delimiters
1160 formatted = format_str.format(*shaped)[:-end_junk]
1162 return formatted
1165def structured_array_to_string(
1166 array: ArrayLike,
1167 col_delim: str = " ",
1168 row_delim: str = "\n",
1169 digits: Integer = 8,
1170 value_format: str = "{}",
1171) -> str:
1172 """
1173 Convert an unstructured array into a string with a specified
1174 number of digits and delimiter. The reason thisexists is
1175 that the basic numpy array to string conversions are
1176 surprisingly slow.
1178 Parameters
1179 ------------
1180 array : (n,) or (n, d) float or int
1181 Data to be converted
1182 If shape is (n,) only column delimiter will be used
1183 col_delim : str
1184 What string should separate values in a column
1185 row_delim : str
1186 What string should separate values in a row
1187 digits : int
1188 How many digits should floating point numbers include
1189 value_format : str
1190 Format string for each value or sequence of values
1191 If multiple values per value_format it must divide
1192 into array evenly.
1194 Returns
1195 ----------
1196 formatted : str
1197 String representation of original array
1198 """
1199 # convert inputs to correct types
1200 array = np.asanyarray(array)
1201 digits = int(digits)
1202 row_delim = str(row_delim)
1203 col_delim = str(col_delim)
1204 value_format = str(value_format)
1206 # abort for non-flat arrays
1207 if len(array.shape) > 1:
1208 raise ValueError(
1209 "conversion only works on 1D/2D arrays not %s!", str(array.shape)
1210 )
1212 # abort for unstructured arrays
1213 if array.dtype.names is None:
1214 raise ValueError("array is not structured, use array_to_string instead")
1216 # do not allow a value to be repeated in a value format
1217 if value_format.count("{") > 1:
1218 raise ValueError(
1219 "value_format %s is invalid, repeating unstructured array "
1220 + "values is unsupported",
1221 value_format,
1222 )
1224 format_str = ""
1225 for name in array.dtype.names:
1226 kind = array[name].dtype.kind
1227 element_row_length = array[name].shape[1] if len(array[name].shape) == 2 else 1
1228 if kind in ["i", "u"]:
1229 # integer types need a no-decimal formatting
1230 element_format_str = value_format.replace("{}", "{:0.0f}") + col_delim
1231 elif kind == "f":
1232 # add the digits formatting to floats
1233 element_format_str = (
1234 value_format.replace("{}", "{:." + str(digits) + "f}") + col_delim
1235 )
1236 else:
1237 raise ValueError("dtype %s not convertible!", array.dtype)
1238 format_str += element_row_length * element_format_str
1240 # length of extra delimiters at the end
1241 format_str = format_str[: -len(col_delim)] + row_delim
1242 # expand format string to whole array
1243 format_str *= len(array)
1245 # loop through flat fields and flatten to single array
1246 count = len(array)
1247 # will upgrade everything to a float
1248 flattened = np.hstack(
1249 [array[k].reshape((count, -1)) for k in array.dtype.names]
1250 ).reshape(-1)
1252 # run the format operation and remove the extra delimiters
1253 formatted = format_str.format(*flattened)[: -len(row_delim)]
1255 return formatted
1258def array_to_encoded(
1259 array: ArrayLike,
1260 dtype: np.typing.DTypeLike | None = None,
1261 encoding: str = "base64",
1262) -> Mapping[str, Any]:
1263 """
1264 Export a numpy array to a compact serializable dictionary.
1266 Parameters
1267 ------------
1268 array : array
1269 Any numpy array
1270 dtype : str or None
1271 Optional dtype to encode array
1272 encoding : str
1273 'base64' or 'binary'
1275 Returns
1276 ---------
1277 encoded : dict
1278 Has keys:
1279 'dtype': str, of dtype
1280 'shape': tuple of shape
1281 'base64': str, base64 encoded string
1282 """
1283 array = np.asanyarray(array)
1284 shape = array.shape
1285 # ravel also forces contiguous
1286 flat = np.ravel(array)
1287 if dtype is None:
1288 dtype = array.dtype
1290 encoded: dict[str, Any] = {"dtype": np.dtype(dtype).str, "shape": shape}
1291 if encoding in ["base64", "dict64"]:
1292 packed = base64.b64encode(flat.astype(dtype).tobytes())
1293 if hasattr(packed, "decode"):
1294 packed = packed.decode("utf-8")
1295 encoded["base64"] = packed
1296 elif encoding == "binary":
1297 encoded["binary"] = flat.astype(dtype, copy=False).tobytes()
1298 else:
1299 raise ValueError(f"encoding {encoding} is not available!")
1300 return encoded
1303def decode_keys(store: MutableMapping, encoding: str = "utf-8") -> MutableMapping:
1304 """
1305 If a dictionary has keys that are bytes decode them to a str.
1307 Parameters
1308 ------------
1309 store : MutableMapping
1310 Dictionary with data
1311 encoding : str
1312 Encoding used to decode bytes keys
1314 Returns
1315 ---------
1316 result : MutableMapping
1317 The same `store` mutated in place: bytes keys are
1318 decoded to `str` and all other keys are untouched.
1320 Example
1321 -----------
1322 In [1]: d
1323 Out[1]: {1020: 'nah', b'hi': 'stuff'}
1325 In [2]: trimesh.util.decode_keys(d)
1326 Out[2]: {1020: 'nah', 'hi': 'stuff'}
1327 """
1328 # snapshot the keys as the loop mutates `store`
1329 for key in list(store):
1330 if hasattr(key, "decode"):
1331 store[key.decode(encoding)] = store.pop(key)
1332 return store
1335def comment_strip(text: str, starts_with: str = "#", new_line: str = "\n") -> str:
1336 """
1337 Strip comments from a text block.
1339 Parameters
1340 -----------
1341 text : str
1342 Text to remove comments from
1343 starts_with : str
1344 Character or substring that starts a comment
1345 new_line : str
1346 Character or substring that ends a comment
1348 Returns
1349 -----------
1350 stripped : str
1351 Text with comments stripped
1352 """
1353 # if not contained exit immediately
1354 if starts_with not in text:
1355 return text
1357 # start by splitting into chunks by the comment indicator
1358 split = (text + new_line).split(starts_with)
1360 # special case files that start with a comment
1361 if text.startswith(starts_with):
1362 lead = ""
1363 else:
1364 lead = split[0]
1366 # take each comment up until the newline
1367 removed = [i.split(new_line, 1) for i in split]
1368 # add the leading string back on
1369 result = (
1370 lead
1371 + new_line
1372 + new_line.join(i[1] for i in removed if len(i) > 1 and len(i[1]) > 0)
1373 )
1374 # strip leading and trailing whitespace
1375 result = result.strip()
1377 return result
1380def encoded_to_array(encoded: ArrayLike | dict[Any, Any]) -> NDArray:
1381 """
1382 Turn a dictionary with base64 encoded strings back into a numpy array.
1384 Parameters
1385 ------------
1386 encoded
1387 Has keys:
1388 dtype: string of dtype
1389 shape: int tuple of shape
1390 base64: base64 encoded string of flat array
1391 binary: decode result coming from numpy.tobytes
1393 Returns
1394 ----------
1395 array
1396 """
1398 if not isinstance(encoded, dict):
1399 if is_sequence(encoded):
1400 as_array = np.asanyarray(encoded)
1401 return as_array
1402 else:
1403 raise ValueError("Unable to extract numpy array from input")
1405 encoded_dict = decode_keys(encoded)
1407 dtype = np.dtype(encoded_dict["dtype"])
1408 if "base64" in encoded_dict:
1409 array = np.frombuffer(base64.b64decode(encoded_dict["base64"]), dtype)
1410 elif "binary" in encoded_dict:
1411 array = np.frombuffer(encoded_dict["binary"], dtype=dtype)
1412 else:
1413 raise ValueError("Invalid encoded array, no 'base64' or 'binary' key found")
1414 if "shape" in encoded_dict:
1415 array = array.reshape(encoded_dict["shape"])
1416 return array
1419def is_instance_named(obj: object, name: str | list[str]) -> bool:
1420 """
1421 Given an object, if it is a member of the class 'name',
1422 or a subclass of 'name', return True.
1424 Parameters
1425 ------------
1426 obj : instance
1427 Some object of some class
1428 name: str
1429 The name of the class we want to check for
1431 Returns
1432 ---------
1433 is_instance : bool
1434 Whether the object is a member of the named class
1435 """
1436 try:
1437 if isinstance(name, list):
1438 return any(is_instance_named(obj, i) for i in name)
1439 else:
1440 type_named(obj, name)
1441 return True
1442 except ValueError:
1443 return False
1446def type_bases(obj: object, depth: Integer = 4) -> list[type]:
1447 """
1448 Return the bases of the object passed.
1449 """
1450 bases: collections.deque[list] = collections.deque([list(obj.__class__.__bases__)])
1451 for i in range(depth):
1452 bases.append([i.__base__ for i in bases[-1] if i is not None])
1453 try:
1454 bases_flat = np.hstack(bases)
1455 except IndexError:
1456 return []
1457 return [i for i in bases_flat if hasattr(i, "__name__")]
1460def type_named(obj: object, name: str) -> type:
1461 """
1462 Similar to the type() builtin, but looks in class bases
1463 for named instance.
1465 Parameters
1466 ------------
1467 obj : any
1468 Object to look for class of
1469 name : str
1470 Name of class
1472 Returns
1473 ----------
1474 class : type
1475 Named class, raises ValueError if not found
1476 """
1477 # if obj is a member of the named class, return True
1478 name = str(name)
1479 if obj.__class__.__name__ == name:
1480 return obj.__class__
1481 for base in type_bases(obj):
1482 if base.__name__ == name:
1483 return base
1484 raise ValueError("Unable to extract class of name " + name)
1487def concatenate(a, b=None) -> "trimesh.parent.Geometry":
1488 """
1489 Concatenate two or more meshes.
1491 Parameters
1492 ------------
1493 a : trimesh.Trimesh
1494 Mesh or list of meshes to be concatenated
1495 object, or list of such
1496 b : trimesh.Trimesh
1497 Mesh or list of meshes to be concatenated
1499 Returns
1500 ----------
1501 result
1502 Concatenated mesh
1503 """
1504 dump = []
1505 for i in chain(a, b):
1506 if is_instance_named(i, "Scene"):
1507 # get every mesh in the final frame.
1508 dump.extend(i.dump())
1509 else:
1510 # just append to our flat list
1511 dump.append(i)
1513 if len(dump) == 1:
1514 # if there is only one geometry just return the first
1515 return dump[0].copy()
1516 elif len(dump) == 0:
1517 # if there are no meshes return an empty mesh
1518 from .base import Trimesh
1520 return Trimesh()
1522 is_mesh = [f for f in dump if is_instance_named(f, "Trimesh")]
1523 is_path = [f for f in dump if is_instance_named(f, "Path")]
1525 # if we have more
1526 if len(is_path) > len(is_mesh):
1527 from .path.util import concatenate as concatenate_path
1529 return concatenate_path(is_path)
1531 if len(is_mesh) == 0:
1532 # nothing concatenable was passed — match the empty-input
1533 # branch above and hand back an empty mesh
1534 from .base import Trimesh
1536 return Trimesh()
1538 # extract the trimesh type to avoid a circular import
1539 # and assert that all inputs are Trimesh objects
1540 trimesh_type = type_named(is_mesh[0], "Trimesh")
1542 # append faces and vertices of meshes
1543 vertices, faces = append_faces(
1544 [m.vertices.copy() for m in is_mesh], [m.faces.copy() for m in is_mesh]
1545 )
1547 # save face normals if already calculated
1548 face_normals = None
1549 if any("face_normals" in m._cache for m in is_mesh):
1550 face_normals = vstack_empty([m.face_normals for m in is_mesh])
1551 assert face_normals.shape == faces.shape
1553 # save vertex normals if any mesh has them
1554 vertex_normals = None
1555 if any("vertex_normals" in m._cache for m in is_mesh):
1556 vertex_normals = vstack_empty([m.vertex_normals for m in is_mesh])
1557 assert vertex_normals.shape == vertices.shape
1559 try:
1560 # concatenate visuals
1561 visual = is_mesh[0].visual.concatenate([m.visual for m in is_mesh[1:]])
1562 except BaseException as E:
1563 log.debug(f"failed to combine visuals {_STRICT}", exc_info=True)
1564 visual = None
1565 if _STRICT:
1566 raise E
1568 metadata = {}
1569 try:
1570 _ = [metadata.update(deepcopy(m.metadata)) for m in is_mesh]
1571 except BaseException:
1572 pass
1574 # concatenate vertex attributes that are valid for every mesh
1575 vertex_attributes = {}
1576 for key in is_mesh[0].vertex_attributes.keys():
1577 # make sure every mesh has a valid attribute
1578 if all(len(m.vertex_attributes.get(key, [])) == len(m.vertices) for m in is_mesh):
1579 try:
1580 vertex_attributes[key] = np.concatenate(
1581 [mesh.vertex_attributes.get(key, []) for mesh in is_mesh], axis=0
1582 )
1583 except BaseException:
1584 log.warning(
1585 f"Failed to concatenate `vertex_attribute['{key}']`", exc_info=True
1586 )
1588 # concatenate face attributes that are valid for every mesh
1589 face_attributes = {}
1590 for key in is_mesh[0].face_attributes.keys():
1591 # an attribute can only be concatenated if it's valid for every mesh
1592 if all(len(m.face_attributes.get(key, [])) == len(m.faces) for m in is_mesh):
1593 try:
1594 # stack along axis 0
1595 face_attributes[key] = np.concatenate(
1596 [mesh.face_attributes.get(key, []) for mesh in is_mesh], axis=0
1597 )
1598 except BaseException:
1599 # could have failed because attribute had different shapes
1600 log.warning(
1601 f"Failed to concatenate `face_attribute['{key}']`", exc_info=True
1602 )
1604 # create the mesh object
1605 result = trimesh_type(
1606 vertices=vertices,
1607 faces=faces,
1608 face_normals=face_normals,
1609 vertex_normals=vertex_normals,
1610 visual=visual,
1611 vertex_attributes=vertex_attributes,
1612 face_attributes=face_attributes,
1613 metadata=metadata,
1614 process=False,
1615 )
1617 try:
1618 result._source = deepcopy(is_mesh[0].source)
1619 except BaseException:
1620 pass
1622 return result
1625def submesh(
1626 mesh,
1627 faces_sequence: Iterable[ArrayLike],
1628 repair: bool = True,
1629 only_watertight: bool = False,
1630 min_faces: Integer | None = None,
1631 append: bool = False,
1632 copy_material: bool = True,
1633):
1634 """
1635 Return a subset of a mesh.
1637 Parameters
1638 ------------
1639 mesh : Trimesh
1640 Source mesh to take geometry from
1641 faces_sequence : sequence (p,) int
1642 Indexes of mesh.faces
1643 repair
1644 Try to make submeshes watertight
1645 only_watertight
1646 Only return submeshes which are watertight
1647 min_faces
1648 Minimum number of faces allowed in a submesh.
1649 append : bool
1650 Return a single mesh which has the faces appended,
1651 if this flag is set, only_watertight is ignored
1652 copy_material
1653 If False textured submeshes share the material with the
1654 source mesh instead of copying its texture image.
1656 Returns
1657 ---------
1658 result : Trimesh | list[Trimesh]
1659 Depending on if `append` is true or not.
1660 """
1661 # evaluate generators so we can escape early
1662 faces_sequence = list(faces_sequence)
1664 if len(faces_sequence) == 0:
1665 return []
1667 # avoid nuking the cache on the original mesh
1668 original_faces = mesh.faces.view(np.ndarray)
1669 original_vertices = mesh.vertices.view(np.ndarray)
1671 faces = []
1672 vertices = []
1673 normals = []
1674 visuals = []
1676 # for reindexing faces
1677 mask = np.arange(len(original_vertices))
1679 for index in faces_sequence:
1680 # sanitize indices in case they are coming in as a set or tuple
1681 index = np.asanyarray(index)
1682 if len(index) == 0:
1683 # regardless of type empty arrays are useless
1684 continue
1685 if index.dtype.kind == "b":
1686 # if passed a bool with no true continue
1687 if not index.any():
1688 continue
1689 # if fewer faces than minimum
1690 if min_faces is not None and index.sum() < min_faces:
1691 continue
1692 elif min_faces is not None and len(index) < min_faces:
1693 continue
1695 current = original_faces[index]
1696 unique = np.unique(current.reshape(-1))
1698 # redefine face indices from zero
1699 mask[unique] = np.arange(len(unique))
1700 normals.append(mesh.face_normals[index])
1701 faces.append(mask[current])
1702 vertices.append(original_vertices[unique])
1704 visuals.append(mesh.visual.face_subset(index, copy_material=copy_material))
1706 if len(vertices) == 0:
1707 return []
1709 # we use type(mesh) rather than importing Trimesh from base
1710 # to avoid a circular import
1711 trimesh_type = type_named(mesh, "Trimesh")
1713 if append:
1714 visual = None
1715 try:
1716 visuals = np.array(visuals)
1717 visual = visuals[0].concatenate(visuals[1:])
1718 except Exception:
1719 log.debug("failed to combine visuals", exc_info=True)
1720 # re-index faces and stack
1721 vertices, faces = append_faces(vertices, faces)
1722 appended = trimesh_type(
1723 vertices=vertices,
1724 faces=faces,
1725 face_normals=np.vstack(normals),
1726 visual=visual,
1727 metadata=deepcopy(mesh.metadata),
1728 process=False,
1729 )
1730 appended._source = deepcopy(mesh.source)
1732 return appended
1734 if visuals is None:
1735 visuals = [None] * len(vertices)
1737 # generate a list of Trimesh objects
1738 result = [
1739 trimesh_type(
1740 vertices=v,
1741 faces=f,
1742 face_normals=n,
1743 visual=c,
1744 metadata=deepcopy(mesh.metadata),
1745 process=False,
1746 )
1747 for v, f, n, c in zip(vertices, faces, normals, visuals)
1748 ]
1750 # assign the "source" information summarizing where a mesh was
1751 # loaded from (i.e. file name) to each submesh of the result
1752 [setattr(r, "_source", deepcopy(mesh.source)) for r in result]
1754 if repair:
1755 # fill_holes will attempt a repair and returns the
1756 # watertight status at the end of the repair attempt
1757 watertight = [len(i.faces) >= 4 and i.fill_holes() for i in result]
1758 elif only_watertight:
1759 # calculate watertightness without repairing
1760 watertight = [i.is_watertight for i in result]
1762 if only_watertight:
1763 # return only the watertight meshes
1764 return [i for i, w in zip(result, watertight) if w]
1766 return result
1769def zero_pad(data: NDArray, count: Integer, right: bool = True) -> NDArray:
1770 """
1771 Parameters
1772 ------------
1773 data : (n,)
1774 1D array
1775 count : int
1776 Minimum length of result array
1778 Returns
1779 ---------
1780 padded : (m,)
1781 1D array where m >= count
1782 """
1783 if len(data) == 0:
1784 return np.zeros(count)
1785 elif len(data) < count:
1786 padded = np.zeros(count)
1787 if right:
1788 padded[-len(data) :] = data
1789 else:
1790 padded[: len(data)] = data
1791 return padded
1792 else:
1793 return np.asanyarray(data)
1796def jsonify(obj: object, **kwargs: Any) -> str:
1797 """
1798 A version of json.dumps that can handle numpy arrays
1799 by creating a custom encoder for numpy dtypes.
1801 Parameters
1802 --------------
1803 obj : list, dict
1804 A JSON-serializable blob
1805 kwargs : dict
1806 Passed to json.dumps
1808 Returns
1809 --------------
1810 dumped : str
1811 JSON dump of obj
1812 """
1814 class EdgeEncoder(json.JSONEncoder):
1815 def default(self, obj: Any):
1816 # will work for numpy.ndarrays
1817 # as well as their int64/etc objects
1818 if hasattr(obj, "tolist"):
1819 # this works on numpy arrays
1820 return obj.tolist()
1821 elif hasattr(obj, "timestamp"):
1822 # serialize datetime as the float stamp
1823 return obj.timestamp()
1824 elif hasattr(obj, "__dataclass_fields__"):
1825 # serialize dataclasses as dict
1826 return dataclass_to_dict(obj)
1827 return json.JSONEncoder.default(self, obj)
1829 # run the dumps using our encoder
1830 return json.dumps(obj, cls=EdgeEncoder, **kwargs)
1833def convert_like(item, like):
1834 """
1835 Convert an item to have the dtype of another item
1837 Parameters
1838 ------------
1839 item : any
1840 Item to be converted
1841 like : any
1842 Object with target dtype
1843 If None, item is returned unmodified
1845 Returns
1846 ----------
1847 result: item, but in dtype of like
1848 """
1849 # if it's a numpy array
1850 if isinstance(like, np.ndarray):
1851 return np.asanyarray(item, dtype=like.dtype)
1853 # if it's already the desired type just return it
1854 if isinstance(item, like.__class__) or like is None:
1855 return item
1857 # if it's an array with one item return it
1858 if is_sequence(item) and len(item) == 1 and isinstance(item[0], like.__class__):
1859 return item[0]
1861 if (
1862 isinstance(item, str)
1863 and like.__class__.__name__ == "Polygon"
1864 and item.startswith("POLYGON")
1865 ):
1866 # break our rule on imports but only a little bit
1867 # the import was a WKT serialized polygon
1868 from shapely import wkt
1870 return wkt.loads(item)
1872 # otherwise just run the conversion
1873 item = like.__class__(item)
1875 return item
1878def bounds_tree(bounds: ArrayLike) -> Any:
1879 """
1880 Given a set of axis aligned bounds create an r-tree for
1881 broad-phase collision detection.
1883 Parameters
1884 ------------
1885 bounds : (n, 2D) or (n, 2, D) float
1886 Non-interleaved bounds where D=dimension
1887 E.G a 2D bounds tree:
1888 [(minx, miny, maxx, maxy), ...]
1890 Returns
1891 ---------
1892 tree : Rtree
1893 Tree containing bounds by index
1894 """
1895 import rtree
1897 # make sure we've copied bounds
1898 bounds = np.array(bounds, dtype=np.float64, copy=True)
1899 if len(bounds.shape) == 3:
1900 # should be min-max per bound
1901 if bounds.shape[1] != 2:
1902 raise ValueError("bounds not (n, 2, dimension)!")
1903 # reshape to one-row-per-hyperrectangle
1904 bounds = bounds.reshape((len(bounds), -1))
1905 elif len(bounds.shape) != 2 or bounds.size == 0:
1906 raise ValueError("Bounds must be (n, dimension * 2)!")
1908 # check to make sure we have correct shape
1909 dimension = bounds.shape[1]
1910 if (dimension % 2) != 0:
1911 raise ValueError("Bounds must be (n,dimension*2)!")
1912 dimension = int(dimension / 2)
1914 properties = rtree.index.Property(dimension=dimension)
1915 # stream load was verified working on import above
1916 return rtree.index.Index(
1917 zip(np.arange(len(bounds)), bounds, [None] * len(bounds)), properties=properties
1918 )
1921def wrap_as_stream(item: str | bytes) -> StringIO | BytesIO:
1922 """
1923 Wrap a string or bytes object as a file object.
1925 Parameters
1926 ------------
1927 item: str or bytes
1928 Item to be wrapped
1930 Returns
1931 ---------
1932 wrapped : file-like object
1933 Contains data from item
1934 """
1935 if isinstance(item, str):
1936 return StringIO(item)
1937 elif isinstance(item, bytes):
1938 return BytesIO(item)
1939 raise ValueError(f"{type(item).__name__} is not wrappable!")
1942def sigfig_round(values: ArrayLike, sigfig: ArrayLike = 1) -> NDArray1D[np.float64]:
1943 """
1944 Round a single value to a specified number of significant figures.
1946 Parameters
1947 ------------
1948 values : float
1949 Value to be rounded
1950 sigfig : int
1951 Number of significant figures to reduce to
1953 Returns
1954 ----------
1955 rounded : float
1956 Value rounded to the specified number of significant figures
1959 Examples
1960 ----------
1961 In [1]: trimesh.util.round_sigfig(-232453.00014045456, 1)
1962 Out[1]: -200000.0
1964 In [2]: trimesh.util.round_sigfig(.00014045456, 1)
1965 Out[2]: 0.0001
1967 In [3]: trimesh.util.round_sigfig(.00014045456, 4)
1968 Out[3]: 0.0001405
1969 """
1970 as_int, multiplier = sigfig_int(values, sigfig)
1971 rounded = as_int * (10**multiplier)
1973 return rounded
1976def sigfig_int(
1977 values: ArrayLike, sigfig: ArrayLike
1978) -> tuple[NDArray1D[np.int64], NDArray1D[np.float64]]:
1979 """
1980 Convert a set of floating point values into integers
1981 with a specified number of significant figures and an
1982 exponent.
1984 Parameters
1985 ------------
1986 values : (n,) float or int
1987 Array of values
1988 sigfig : (n,) int
1989 Number of significant figures to keep
1991 Returns
1992 ------------
1993 as_int : (n,) int
1994 Every value[i] has sigfig[i] digits
1995 multiplier : (n,) float
1996 Exponent, so as_int * 10 ** multiplier is
1997 the same order of magnitude as the input
1998 """
1999 values = np.asanyarray(values).reshape(-1)
2000 sigfig = np.asanyarray(sigfig, dtype=np.int64).reshape(-1)
2002 if sigfig.shape != values.shape:
2003 raise ValueError("sigfig must match identifier")
2005 exponent = np.zeros(len(values))
2006 nonzero = np.abs(values) > TOL_ZERO
2007 exponent[nonzero] = np.floor(np.log10(np.abs(values[nonzero])))
2009 multiplier = exponent - sigfig + 1
2010 as_int = (values / (10**multiplier)).round().astype(np.int64)
2012 return as_int, multiplier
2015# skip ZIP members once declared uncompressed sizes exceed this
2016_ARCHIVE_SKIP_SIZE = 32 * 1024**3 # 32 GiB
2019def decompress(
2020 file_obj: bytes | Stream,
2021 file_type: str,
2022) -> dict[str, Stream | None]:
2023 """
2024 Given an open file object and a file type, return all components
2025 of the archive as open file objects in a dict.
2027 ZIP members are skipped once the total uncompressed size declared by
2028 the archive exceeds `_ARCHIVE_SKIP_SIZE`. Other formats don't store a
2029 per-member compressed size so there is nothing to check before reading.
2031 Parameters
2032 ------------
2033 file_obj : file-like
2034 Containing compressed data.
2035 file_type : str
2036 File extension, 'zip', 'tar.gz', etc.
2038 Returns
2039 ---------
2040 decompressed : dict
2041 Data from archive in format {file name : file-like}.
2042 """
2043 file_type = str(file_type).lower()
2044 if isinstance(file_obj, bytes):
2045 file_obj = BytesIO(file_obj)
2047 if file_type.endswith("zip"):
2048 archive = zipfile.ZipFile(file_obj)
2049 result = {}
2050 # running total of the sizes the central directory declared: this is
2051 # an upper bound on what we can actually read as `ZipExtFile` stops
2052 # at the declared size and then fails the CRC check
2053 total = 0
2054 for info in archive.infolist():
2055 if total + info.file_size > _ARCHIVE_SKIP_SIZE:
2056 log.warning(
2057 "skipping `%s`: declared %d bytes exceeds archive budget",
2058 info.filename,
2059 info.file_size,
2060 )
2061 continue
2062 total += info.file_size
2063 with archive.open(info, mode="r") as src:
2064 data = src.read()
2065 result[info.filename] = wrap_as_stream(data)
2066 return result
2067 if file_type.endswith("bz2"):
2068 import bz2
2070 # get the file name if we have one otherwise default to "archive"
2071 name = getattr(file_obj, "name", "archive1234")[:-4]
2072 return {name: wrap_as_stream(bz2.open(file_obj, mode="r").read())}
2073 if "tar" in file_type[-6:]:
2074 import tarfile
2076 archive = tarfile.open(fileobj=file_obj, mode="r")
2077 result = {}
2078 for info in archive.getmembers():
2079 if not info.isfile():
2080 continue
2081 src = archive.extractfile(info)
2082 if src is None:
2083 continue
2084 result[info.name] = wrap_as_stream(src.read())
2085 return result
2086 raise ValueError("Unsupported type passed!")
2089def compress(
2090 info: Mapping[str, str | bytes | Stream],
2091 **kwargs: Any,
2092) -> bytes:
2093 """
2094 Compress data stored in a dict.
2096 Parameters
2097 -----------
2098 info : dict
2099 Data to compress in form:
2100 {file name in archive: bytes or file-like object}
2101 kwargs : dict
2102 Passed to zipfile.ZipFile
2103 Returns
2104 -----------
2105 compressed : bytes
2106 Compressed file data
2107 """
2108 file_obj = BytesIO()
2109 with zipfile.ZipFile(
2110 file_obj, mode="w", compression=zipfile.ZIP_DEFLATED, **kwargs
2111 ) as zipper:
2112 for name, data_or_file in info.items():
2113 if isinstance(data_or_file, (str, bytes)):
2114 data = data_or_file
2115 else:
2116 # a file-like object — read its contents
2117 data = data_or_file.read()
2118 zipper.writestr(name, data)
2119 file_obj.seek(0)
2120 compressed = file_obj.read()
2121 return compressed
2124def split_extension(file_name: str, special: Iterable[str] | None = None) -> str:
2125 """
2126 Find the file extension of a file name, including support for
2127 special case multipart file extensions (like .tar.gz)
2129 Parameters
2130 ------------
2131 file_name : str
2132 File name
2133 special : list of str
2134 Multipart extensions
2135 eg: ['tar.bz2', 'tar.gz']
2137 Returns
2138 ----------
2139 extension : str
2140 Last characters after a period, or
2141 a value from 'special'
2142 """
2143 file_name = str(file_name)
2145 if special is None:
2146 special = ["tar.bz2", "tar.gz"]
2147 if file_name.endswith(tuple(special)):
2148 for end in special:
2149 if file_name.endswith(end):
2150 return end
2151 return file_name.split(".")[-1]
2154def triangle_strips_to_faces(
2155 strips: ArrayLike | Sequence[ArrayLike],
2156) -> NDArray2D[np.int64]:
2157 """
2158 Convert a sequence of triangle strips to (n, 3) faces.
2160 Processes all strips at once using np.concatenate and is significantly
2161 faster than loop-based methods.
2163 From the OpenGL programming guide describing a single triangle
2164 strip [v0, v1, v2, v3, v4]:
2166 Draws a series of triangles (three-sided polygons) using vertices
2167 v0, v1, v2, then v2, v1, v3 (note the order), then v2, v3, v4,
2168 and so on. The ordering is to ensure that the triangles are all
2169 drawn with the same orientation so that the strip can correctly form
2170 part of a surface.
2172 Parameters
2173 ------------
2174 strips: (n,) list of (m,) int
2175 Vertex indices
2177 Returns
2178 ------------
2179 faces : (m, 3) int
2180 Vertex indices representing triangles
2181 """
2183 # save the length of each list in the list of lists
2184 lengths = np.array([len(i) for i in strips], dtype=np.int64)
2185 # looping through a list of lists is extremely slow
2186 # combine all the sequences into a blob we can manipulate
2187 blob = np.concatenate(strips, dtype=np.int64)
2189 # slice the blob into rough triangles
2190 tri = np.array([blob[:-2], blob[1:-1], blob[2:]], dtype=np.int64).T
2192 # if we only have one strip we can do a *lot* less work
2193 # as we keep every triangle and flip every other one
2194 if len(strips) == 1:
2195 # flip in-place every other triangle
2196 tri[1::2] = np.fliplr(tri[1::2])
2197 return tri
2199 # remove the triangles which were implicit but not actually there
2200 # because we combined everything into one big array for speed
2201 length_index = np.cumsum(lengths)[:-1]
2202 keep = np.ones(len(tri), dtype=bool)
2203 keep[length_index - 2] = False
2204 keep[length_index - 1] = False
2205 tri = tri[keep]
2207 # flip every other triangle so they generate correct normals/winding
2208 length_index = np.append(0, np.cumsum(lengths - 2))
2209 flip = np.zeros(length_index[-1], dtype=bool)
2210 for i in range(len(length_index) - 1):
2211 flip[length_index[i] + 1 : length_index[i + 1]][::2] = True
2212 tri[flip] = np.fliplr(tri[flip])
2214 return tri
2217def triangle_fans_to_faces(
2218 fans: Iterable[ArrayLike],
2219) -> NDArray2D[np.int64]:
2220 """
2221 Convert fans of m + 2 vertex indices in fan format to m triangles
2223 Parameters
2224 ----------
2225 fans: (n,) list of (m + 2,) int
2226 Vertex indices
2228 Returns
2229 -------
2230 faces: (m, 3) int
2231 Vertex indices representing triangles
2232 """
2234 faces = [
2235 np.transpose([fan[0] * np.ones(len(fan) - 2, dtype=int), fan[1:-1], fan[2:]])
2236 for fan in fans
2237 ]
2238 return np.concatenate(faces, dtype=int)
2241def vstack_empty(tup: Iterable[ArrayLike]) -> NDArray:
2242 """
2243 A thin wrapper for numpy.vstack that ignores empty lists.
2245 Parameters
2246 ------------
2247 tup : tuple or list of arrays
2248 With the same number of columns
2250 Returns
2251 ------------
2252 stacked : (n, d) array
2253 With same number of columns as
2254 constituent arrays.
2255 """
2256 # filter out empty arrays
2257 stackable = [i for i in tup if len(i) > 0]
2258 # if we only have one array just return it
2259 if len(stackable) == 1:
2260 return np.asanyarray(stackable[0])
2261 # if we have nothing return an empty numpy array
2262 elif len(stackable) == 0:
2263 return np.array([])
2264 # otherwise just use vstack as normal
2265 return np.vstack(stackable)
2268def write_encoded(
2269 file_obj: Stream,
2270 stuff: str | bytes,
2271 encoding: str = "utf-8",
2272) -> str | bytes:
2273 """
2274 If a file is open in binary mode and a
2275 string is passed, encode and write.
2277 If a file is open in text mode and bytes are
2278 passed decode bytes to str and write.
2280 Assumes binary mode if file_obj does not have
2281 a 'mode' attribute (e.g. io.BufferedRandom).
2283 Parameters
2284 -----------
2285 file_obj : file object
2286 With 'write' and 'mode'
2287 stuff : str or bytes
2288 Stuff to be written
2289 encoding : str
2290 Encoding of text
2291 """
2292 binary_file = "b" in getattr(file_obj, "mode", "b")
2293 string_stuff = isinstance(stuff, str)
2294 binary_stuff = isinstance(stuff, bytes)
2296 if binary_file and string_stuff:
2297 file_obj.write(stuff.encode(encoding))
2298 elif not binary_file and binary_stuff:
2299 file_obj.write(stuff.decode(encoding))
2300 else:
2301 file_obj.write(stuff)
2302 file_obj.flush()
2303 return stuff
2306def unique_id(length: Integer = 12) -> str:
2307 """
2308 Generate a random alphaNumber unique identifier
2309 using UUID logic.
2311 Parameters
2312 ------------
2313 length : int
2314 Length of desired identifier
2316 Returns
2317 ------------
2318 unique : str
2319 Unique alphaNumber identifier
2320 """
2321 return uuid.UUID(int=random.getrandbits(128), version=4).hex[:length]
2324def generate_basis(z: ArrayLike, epsilon: Floating = 1e-12) -> NDArray2D[np.float64]:
2325 """
2326 Generate an arbitrary basis (also known as a coordinate frame)
2327 from a given z-axis vector.
2329 Parameters
2330 ------------
2331 z : (3,) float
2332 A vector along the positive z-axis.
2333 epsilon : Floating
2334 Numbers smaller than this considered zero.
2336 Returns
2337 ---------
2338 x : (3,) float
2339 Vector along x axis.
2340 y : (3,) float
2341 Vector along y axis.
2342 z : (3,) float
2343 Vector along z axis.
2344 """
2345 # get a copy of input vector
2346 z = np.array(z, dtype=np.float64, copy=True)
2347 # must be a 3D vector
2348 if z.shape != (3,):
2349 raise ValueError("z must be (3,) float!")
2351 z_norm = np.linalg.norm(z)
2352 if z_norm < epsilon:
2353 return np.eye(3)
2355 # normalize vector in-place
2356 z /= z_norm
2357 # X as arbitrary perpendicular vector
2358 x = np.array([-z[1], z[0], 0.0])
2359 # avoid degenerate case
2360 x_norm = np.linalg.norm(x)
2361 if x_norm < epsilon:
2362 # this means that
2363 # so a perpendicular X is just X
2364 x = np.array([-z[2], z[1], 0.0])
2365 x /= np.linalg.norm(x)
2366 else:
2367 # otherwise normalize X in-place
2368 x /= x_norm
2369 # get perpendicular Y with cross product
2370 y = np.cross(z, x)
2371 # append result values into (3, 3) vector
2372 result = np.array([x, y, z], dtype=np.float64)
2374 if _STRICT:
2375 # run checks to make sure axis are perpendicular
2376 assert np.abs(np.dot(x, z)) < 1e-8
2377 assert np.abs(np.dot(y, z)) < 1e-8
2378 assert np.abs(np.dot(x, y)) < 1e-8
2379 # all vectors should be unit vector
2380 assert np.allclose(np.linalg.norm(result, axis=1), 1.0)
2382 return result
2385def isclose(
2386 a: Number | NDArray,
2387 b: Number | NDArray,
2388 atol: Floating = 1e-8,
2389) -> np.bool_ | NDArray[np.bool_]:
2390 """
2391 A replacement for np.isclose that does fewer checks
2392 and validation and as a result is roughly 4x faster.
2394 Note that this is used in tight loops, and as such
2395 a and b MUST be np.ndarray, not list or "array-like"
2397 Parameters
2398 ------------
2399 a : np.ndarray
2400 To be compared
2401 b : np.ndarray
2402 To be compared
2403 atol : float
2404 Acceptable distance between `a` and `b` to be "close"
2406 Returns
2407 -----------
2408 close : np.ndarray, bool
2409 Per-element closeness
2410 """
2411 diff = a - b
2412 return np.logical_and(diff > -atol, diff < atol)
2415def allclose(a: Number | NDArray, b: Number | NDArray, atol: Floating = 1e-8) -> bool:
2416 """
2417 A replacement for np.allclose that does few checks
2418 and validation and as a result is faster.
2420 Parameters
2421 ------------
2422 a : np.ndarray
2423 To be compared
2424 b : np.ndarray
2425 To be compared
2426 atol : float
2427 Acceptable distance between `a` and `b` to be "close"
2429 Returns
2430 -----------
2431 bool indicating if all elements are within `atol`.
2432 """
2433 #
2434 return bool(float(np.ptp(a - b)) < atol)
2437class FunctionRegistry(Mapping[str, Callable[..., Any]]):
2438 """
2439 Non-overwritable mapping of string keys to functions.
2441 This allows external packages to register additional implementations
2442 of common functionality without risk of breaking implementations provided
2443 by trimesh.
2445 See trimesh.voxel.morphology for example usage.
2446 """
2448 def __init__(self, **kwargs: Callable[..., Any]) -> None:
2449 self._dict = {}
2450 for k, v in kwargs.items():
2451 self[k] = v
2453 def __getitem__(self, key: str) -> Callable[..., Any]:
2454 return self._dict[key]
2456 def __setitem__(self, key: str, value: Callable[..., object]) -> None:
2457 if not isinstance(key, str):
2458 raise ValueError(f"key must be a string, got {key!s}")
2459 if key in self:
2460 raise KeyError(f"Cannot set new value to existing key {key}")
2461 if not callable(value):
2462 raise ValueError("Cannot set value which is not callable.")
2463 self._dict[key] = value
2465 def __iter__(self) -> Iterator[str]:
2466 return iter(self._dict)
2468 def __len__(self) -> int:
2469 return len(self._dict)
2471 def __contains__(self, key: object) -> bool:
2472 return key in self._dict
2474 def __call__(self, key: str, *args: object, **kwargs: object) -> Any:
2475 return self[key](*args, **kwargs)
2478def decode_text(text: str | bytes, initial: str = "utf-8") -> str:
2479 """
2480 Try to decode byte input as a string.
2482 Tries initial guess (UTF-8) then if that fails it
2483 uses charset_normalizer to try another guess before failing.
2485 Parameters
2486 ------------
2487 text : bytes
2488 Data that might be a string
2489 initial : str
2490 Initial guess for text encoding.
2492 Returns
2493 ------------
2494 decoded : str
2495 Data as a string
2496 """
2497 # if it's already a string there is nothing to decode
2498 if isinstance(text, str):
2499 return text
2501 try:
2502 # initially guess file is UTF-8 or specified encoding
2503 return text.decode(initial)
2504 except UnicodeDecodeError:
2505 # detect different file encodings
2506 from charset_normalizer import detect as charset_normalizer_detect
2508 # try to detect the encoding of the file
2509 # only look at the first 1000 characters for speed
2510 detect = charset_normalizer_detect(text[:1000])
2511 # warn on files that aren't UTF-8
2512 log.debug(
2513 "Data not {}! Trying {} (confidence {})".format(
2514 initial, detect["encoding"], detect["confidence"]
2515 )
2516 )
2517 # try to decode again ignoring errors
2518 # if detect returned nothing just use the initial guess
2519 return text.decode(detect["encoding"] or initial, errors="ignore")
2522def to_ascii(text: Any) -> str:
2523 """
2524 Force a string or other to ASCII text ignoring errors.
2526 Parameters
2527 -----------
2528 text : any
2529 Input to be converted to ASCII string
2531 Returns
2532 -----------
2533 ascii : str
2534 Input as an ASCII string
2535 """
2536 if hasattr(text, "encode"):
2537 # case for existing strings
2538 return text.encode("ascii", errors="ignore").decode("ascii")
2539 elif hasattr(text, "decode"):
2540 # case for bytes
2541 return text.decode("ascii", errors="ignore")
2542 # otherwise just wrap as a string
2543 return str(text)
2546def is_ccw(points: ArrayLike, return_all: bool = False):
2547 """
2548 Check if connected 2D points are counterclockwise.
2550 Parameters
2551 -----------
2552 points : (n, 2) float
2553 Connected points on a plane
2554 return_all : bool
2555 Return polygon area and centroid or just counter-clockwise.
2557 Returns
2558 ----------
2559 ccw : bool
2560 True if points are counter-clockwise
2561 area : float
2562 Only returned if `return_centroid`
2563 centroid : (2,) float
2564 Centroid of the polygon.
2565 """
2566 points = np.array(points, dtype=np.float64)
2568 if len(points.shape) != 2 or points.shape[1] != 2:
2569 raise ValueError("only defined for `(n, 2)` points")
2571 # the "shoelace formula"
2572 product = np.subtract(*(points[:-1, [1, 0]] * points[1:]).T)
2573 # the area of the polygon
2574 area = product.sum() / 2.0
2575 # check the sign of the area
2576 ccw = area < 0.0
2578 if not return_all:
2579 return ccw
2581 # the centroid of the polygon uses the same formula
2582 centroid = ((points[:-1] + points[1:]) * product.reshape((-1, 1))).sum(axis=0) / (
2583 6.0 * area
2584 )
2586 return ccw, area, centroid
2589def unique_name(
2590 start: str | None,
2591 contains: Collection[str],
2592 counts: MutableMapping[str | None, int] | None = None,
2593) -> str:
2594 """
2595 Deterministically generate a unique name not
2596 contained in a dict, set or other grouping with
2597 `__includes__` defined. Will create names of the
2598 form "start_10" and increment accordingly.
2600 Parameters
2601 -----------
2602 start : str
2603 Initial guess for name.
2604 contains : dict, set, or list
2605 Bundle of existing names we can *not* use.
2606 counts : None or dict
2607 Maps name starts encountered before to increments in
2608 order to speed up finding a unique name as otherwise
2609 it potentially has to iterate through all of contains.
2610 Should map to "how many times has this `start`
2611 been attempted, i.e. `counts[start]: int`.
2612 Note that this *will be mutated* in-place by this function!
2614 Returns
2615 ---------
2616 unique : str
2617 A name that is not contained in `contains`
2618 """
2619 # exit early if name is not in bundle
2620 if start is not None and len(start) > 0 and start not in contains:
2621 return start
2623 # start checking with zero index unless found
2624 if counts is None:
2625 increment = 0
2626 else:
2627 increment = counts.get(start, 0)
2628 if start is not None and len(start) > 0:
2629 formatter = start + "_{}"
2630 # split by our delimiter once
2631 split = start.rsplit("_", 1)
2632 if len(split) == 2 and increment == 0:
2633 try:
2634 # start incrementing from the existing
2635 # trailing value
2636 # if it is not an integer this will fail
2637 increment = int(split[1])
2638 # include the first split value
2639 formatter = split[0] + "_{}"
2640 except BaseException:
2641 pass
2642 else:
2643 formatter = "geometry_{}"
2645 # if contains is empty we will only need to check once
2646 for i in range(increment + 1, 2 + increment + len(contains)):
2647 check = formatter.format(i)
2648 if check not in contains:
2649 if counts is not None:
2650 counts[start] = i
2651 return check
2653 # this should really never happen since we looped
2654 # through the full length of contains
2655 raise ValueError("Unable to establish unique name!")