loop-common 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. loop_common/__init__.py +6 -0
  2. loop_common/base.py +98 -0
  3. loop_common/geometry/__init__.py +19 -0
  4. loop_common/geometry/_aabb.py +37 -0
  5. loop_common/geometry/_bounding_box.py +792 -0
  6. loop_common/geometry/_face_table.py +42 -0
  7. loop_common/geometry/_point.py +238 -0
  8. loop_common/geometry/_structured_grid.py +114 -0
  9. loop_common/geometry/_structured_grid_2d.py +146 -0
  10. loop_common/geometry/_structured_grid_3d.py +243 -0
  11. loop_common/geometry/_surface.py +288 -0
  12. loop_common/geometry/_unstructured_mesh.py +208 -0
  13. loop_common/interfaces/__init__.py +0 -0
  14. loop_common/interfaces/representation.py +45 -0
  15. loop_common/io/__init__.py +0 -0
  16. loop_common/logging/__init__.py +14 -0
  17. loop_common/logging/logger.py +123 -0
  18. loop_common/logging/sinks.py +221 -0
  19. loop_common/logging/timing.py +113 -0
  20. loop_common/math/__init__.py +5 -0
  21. loop_common/math/_maths.py +441 -0
  22. loop_common/math/_transformation.py +178 -0
  23. loop_common/math/finite_difference_stencil.py +38 -0
  24. loop_common/observations/__init__.py +3 -0
  25. loop_common/observations/lineset.py +41 -0
  26. loop_common/observations/orientation.py +122 -0
  27. loop_common/observations/pointset.py +8 -0
  28. loop_common/observer.py +284 -0
  29. loop_common/supports/_2d_base_unstructured.py +361 -0
  30. loop_common/supports/_2d_p1_unstructured.py +131 -0
  31. loop_common/supports/_2d_p2_unstructured.py +349 -0
  32. loop_common/supports/_2d_structured_grid.py +545 -0
  33. loop_common/supports/_3d_base_structured.py +546 -0
  34. loop_common/supports/_3d_p2_tetra.py +374 -0
  35. loop_common/supports/_3d_rectilinear_grid.py +315 -0
  36. loop_common/supports/_3d_structured_grid.py +510 -0
  37. loop_common/supports/_3d_structured_tetra.py +764 -0
  38. loop_common/supports/_3d_unstructured_tetra.py +656 -0
  39. loop_common/supports/__init__.py +69 -0
  40. loop_common/supports/_aabb.py +77 -0
  41. loop_common/supports/_base_support.py +118 -0
  42. loop_common/supports/_face_table.py +70 -0
  43. loop_common/supports/_p2_structured_tetra.py +627 -0
  44. loop_common/supports/_support_factory.py +78 -0
  45. loop_common/utils.py +74 -0
  46. loop_common-0.0.1.dist-info/METADATA +35 -0
  47. loop_common-0.0.1.dist-info/RECORD +50 -0
  48. loop_common-0.0.1.dist-info/WHEEL +5 -0
  49. loop_common-0.0.1.dist-info/licenses/LICENSE +21 -0
  50. loop_common-0.0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,792 @@
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+
5
+ import numpy as np
6
+
7
+ from loop_common.logging import get_logger as getLogger
8
+
9
+ # from LoopStructural.utils.exceptions import LoopValueError
10
+ from loop_common.math import rng
11
+ from loop_common.supports import StructuredGrid
12
+
13
+ logger = getLogger(__name__)
14
+
15
+
16
+ class LoopValueError(ValueError):
17
+ """Custom error for invalid values in LoopStructural."""
18
+
19
+
20
+
21
+ class BoundingBox:
22
+ def __init__(
23
+ self,
24
+ origin: np.ndarray | None = None,
25
+ maximum: np.ndarray | None = None,
26
+ nsteps: np.ndarray | None = None,
27
+ step_vector: np.ndarray | None = None,
28
+ dimensions: int | None = 3,
29
+ ):
30
+ """A bounding box for a model, defined by the
31
+ origin, maximum and number of steps in each direction
32
+
33
+ Parameters
34
+ ----------
35
+ dimensions : int, optional
36
+ _description_, by default 3
37
+ origin : Optional[np.ndarray], optional
38
+ _description_, by default None
39
+ maximum : Optional[np.ndarray], optional
40
+ _description_, by default None
41
+ nsteps : Optional[np.ndarray], optional
42
+ _description_, by default None
43
+ """
44
+ self.dimensions = dimensions
45
+
46
+ def _coerce_point(point, name):
47
+ if point is None:
48
+ return None
49
+ arr = np.asarray(point, dtype=float)
50
+ if arr.shape != (self.dimensions,):
51
+ logger.warning(
52
+ f"{name} has shape {arr.shape} but bounding box has {self.dimensions} dimensions"
53
+ )
54
+ raise LoopValueError(f"{name} has incorrect number of dimensions")
55
+ return arr
56
+
57
+ origin = _coerce_point(origin, "Origin")
58
+ maximum = _coerce_point(maximum, "Maximum")
59
+
60
+ if nsteps is not None:
61
+ if len(nsteps) != dimensions:
62
+ logger.warning(f"Nsteps has {len(nsteps)} dimensions but bounding box has {dimensions}")
63
+ raise LoopValueError("Nsteps has incorrect number of dimensions")
64
+ if np.any(np.asarray(nsteps) <= 0):
65
+ raise LoopValueError("Nsteps must be positive integers")
66
+
67
+ if (
68
+ maximum is None
69
+ and nsteps is not None
70
+ and step_vector is not None
71
+ and origin is not None
72
+ ):
73
+ maximum = np.asarray(origin, dtype=float) + np.asarray(nsteps) * np.asarray(
74
+ step_vector, dtype=float
75
+ )
76
+
77
+ if origin is not None and maximum is not None and np.any(maximum < origin):
78
+ raise LoopValueError("Maximum must be greater than or equal to origin")
79
+
80
+ self._origin = origin
81
+ self._maximum = maximum
82
+
83
+ # Local interpolation coordinate frame (world -> local affine transform).
84
+ self._world_to_local = np.eye(4)
85
+ self._local_to_world = np.eye(4)
86
+ self._local_origin = np.zeros(self.dimensions, dtype=float)
87
+ self._local_rotation = np.eye(self.dimensions, dtype=float)
88
+
89
+ if self.valid:
90
+ self.nelements = 10_000
91
+ else:
92
+ default_nsteps = np.ones(self.dimensions, dtype=int) * 50
93
+ if self.dimensions == 3:
94
+ default_nsteps[-1] = 25
95
+ self.nsteps = default_nsteps
96
+ if nsteps is not None:
97
+ self.nsteps = np.array(nsteps)
98
+
99
+ self.set_local_transform(local_origin=np.zeros(self.dimensions, dtype=float))
100
+
101
+ self.name_map = {
102
+ "xmin": (0, 0),
103
+ "ymin": (0, 1),
104
+ "zmin": (0, 2),
105
+ "xmax": (1, 0),
106
+ "ymax": (1, 1),
107
+ "zmax": (1, 2),
108
+ "lower": (0, 2),
109
+ "upper": (1, 2),
110
+ "minx": (0, 0),
111
+ "miny": (0, 1),
112
+ "minz": (0, 2),
113
+ "maxx": (1, 0),
114
+ "maxy": (1, 1),
115
+ "maxz": (1, 2),
116
+ }
117
+
118
+ def set_local_transform(
119
+ self,
120
+ local_origin: np.ndarray | None = None,
121
+ rotation_matrix: np.ndarray | None = None,
122
+ ):
123
+ """Set the world->local affine transform used for interpolation coordinates.
124
+
125
+ Parameters
126
+ ----------
127
+ local_origin : Optional[np.ndarray]
128
+ World-space origin of the local frame. If None, uses zeros.
129
+ rotation_matrix : Optional[np.ndarray]
130
+ Rotation matrix mapping world axes to local axes.
131
+ """
132
+ if local_origin is None:
133
+ local_origin = np.zeros(self.dimensions, dtype=float)
134
+ local_origin = np.asarray(local_origin, dtype=float)
135
+ if local_origin.shape != (self.dimensions,):
136
+ raise LoopValueError("Local origin has incorrect number of dimensions")
137
+
138
+ if rotation_matrix is None:
139
+ rotation_matrix = np.eye(self.dimensions, dtype=float)
140
+ rotation_matrix = np.asarray(rotation_matrix, dtype=float)
141
+ if rotation_matrix.shape != (self.dimensions, self.dimensions):
142
+ raise LoopValueError(
143
+ f"Rotation matrix must have shape ({self.dimensions}, {self.dimensions})"
144
+ )
145
+
146
+ self._local_origin = local_origin
147
+ self._local_rotation = rotation_matrix
148
+
149
+ world_to_local = np.eye(4)
150
+ world_to_local[: self.dimensions, : self.dimensions] = rotation_matrix
151
+ world_to_local[: self.dimensions, 3] = -rotation_matrix @ local_origin
152
+
153
+ self._world_to_local = world_to_local
154
+ self._local_to_world = np.linalg.inv(world_to_local)
155
+
156
+ def _apply_affine(
157
+ self, xyz: np.ndarray, matrix: np.ndarray, inplace: bool = False
158
+ ) -> np.ndarray:
159
+ arr = np.asarray(xyz, dtype=float)
160
+ is_vector = arr.ndim == 1
161
+ points = arr.reshape(1, -1) if is_vector else arr
162
+ if points.shape[1] != self.dimensions:
163
+ raise LoopValueError(
164
+ f"locations array is {points.shape[1]}D but bounding box is {self.dimensions}"
165
+ )
166
+
167
+ hom = np.ones((points.shape[0], 4), dtype=float)
168
+ hom[:, : self.dimensions] = points
169
+ transformed = (matrix @ hom.T).T[:, : self.dimensions]
170
+
171
+ if inplace and isinstance(xyz, np.ndarray):
172
+ xyz[...] = transformed.reshape(arr.shape)
173
+ return xyz
174
+ if is_vector:
175
+ return transformed[0]
176
+ return transformed
177
+
178
+ @property
179
+ def local_origin(self):
180
+ """World-space origin of the local interpolation frame."""
181
+ return self._local_origin.copy()
182
+
183
+ @property
184
+ def local_rotation(self):
185
+ """Rotation matrix that maps world coordinates into local coordinates."""
186
+ return self._local_rotation.copy()
187
+
188
+ @property
189
+ def world_to_local_matrix(self):
190
+ """Homogeneous 4x4 matrix for world -> local coordinates."""
191
+ return self._world_to_local.copy()
192
+
193
+ @property
194
+ def local_to_world_matrix(self):
195
+ """Homogeneous 4x4 matrix for local -> world coordinates."""
196
+ return self._local_to_world.copy()
197
+
198
+ @property
199
+ def valid(self):
200
+ """Check if the bounding box has valid origin and maximum values.
201
+
202
+ Returns
203
+ -------
204
+ bool
205
+ True if both origin and maximum are set, False otherwise
206
+ """
207
+ return self._origin is not None and self._maximum is not None
208
+
209
+ @property
210
+ def origin(self) -> np.ndarray:
211
+ """Get the origin coordinates of the bounding box.
212
+
213
+ Returns
214
+ -------
215
+ np.ndarray
216
+ Origin coordinates
217
+
218
+ Raises
219
+ ------
220
+ LoopValueError
221
+ If the origin is not set
222
+ """
223
+ if self._origin is None:
224
+ raise LoopValueError("Origin is not set")
225
+ return self._origin
226
+
227
+ @origin.setter
228
+ def origin(self, origin: np.ndarray):
229
+ """Set the origin coordinates of the bounding box.
230
+
231
+ Parameters
232
+ ----------
233
+ origin : np.ndarray
234
+ Origin coordinates
235
+ """
236
+ if self.dimensions != len(origin):
237
+ logger.warning(
238
+ f"Origin has {len(origin)} dimensions but bounding box has {self.dimensions}"
239
+ )
240
+ self._origin = np.asarray(origin, dtype=float)
241
+
242
+ @property
243
+ def maximum(self) -> np.ndarray:
244
+ """Get the maximum coordinates of the bounding box.
245
+
246
+ Returns
247
+ -------
248
+ np.ndarray
249
+ Maximum coordinates
250
+
251
+ Raises
252
+ ------
253
+ LoopValueError
254
+ If the maximum is not set
255
+ """
256
+ if self._maximum is None:
257
+ raise LoopValueError("Maximum is not set")
258
+ return self._maximum
259
+
260
+ @maximum.setter
261
+ def maximum(self, maximum: np.ndarray):
262
+ """Set the maximum coordinates of the bounding box.
263
+
264
+ Parameters
265
+ ----------
266
+ maximum : np.ndarray
267
+ Maximum coordinates
268
+ """
269
+ self._maximum = np.asarray(maximum, dtype=float)
270
+
271
+ @property
272
+ def nelements(self):
273
+ """Get the total number of elements in the bounding box.
274
+
275
+ Returns
276
+ -------
277
+ int
278
+ Total number of elements (product of nsteps)
279
+ """
280
+
281
+ return self.nsteps.prod()
282
+
283
+ @property
284
+ def volume(self):
285
+ """Calculate the volume of the bounding box.
286
+
287
+ Returns
288
+ -------
289
+ float
290
+ Volume of the bounding box
291
+ """
292
+ length = self.maximum - self.origin
293
+ length = length.astype(float)
294
+ return np.prod(length)
295
+
296
+ @property
297
+ def bb(self):
298
+ """Get a numpy array containing origin and maximum coordinates.
299
+
300
+ Returns
301
+ -------
302
+ np.ndarray
303
+ Array with shape (2, n_dimensions) containing [origin, maximum]
304
+ """
305
+ return np.array([self.origin, self.maximum])
306
+
307
+ @nelements.setter
308
+ def nelements(self, nelements: float):
309
+ """Update the number of elements in the associated grid
310
+ This is for visualisation, not for the interpolation
311
+ When set it will update the nsteps/step vector for cubic
312
+ elements
313
+
314
+ Parameters
315
+ ----------
316
+ nelements : int,float
317
+ The new number of elements
318
+ """
319
+ box_vol = self.volume
320
+ ele_vol = box_vol / nelements
321
+ # calculate the step vector of a regular cube
322
+ step_vector = np.zeros(self.dimensions)
323
+ if self.dimensions == 2:
324
+ step_vector[:] = ele_vol ** (1.0 / 2.0)
325
+ elif self.dimensions == 3:
326
+ step_vector[:] = ele_vol ** (1.0 / 3.0)
327
+ else:
328
+ logger.warning("Can only set nelements for 2d or 3D bounding box")
329
+ return
330
+ # number of steps is the length of the box / step vector
331
+ nsteps = np.ceil((self.maximum - self.origin) / step_vector).astype(int)
332
+ self.nsteps = nsteps
333
+
334
+ @property
335
+ def corners(self) -> np.ndarray:
336
+ """Returns the corners of the bounding box in local coordinates
337
+
338
+
339
+
340
+ Returns
341
+ -------
342
+ np.ndarray
343
+ array of corners in clockwise order
344
+
345
+ Raises
346
+ ------
347
+ NotImplementedError
348
+ If the bounding box has a number of dimensions other than 2 or 3
349
+ """
350
+
351
+ if self.dimensions == 3:
352
+ return np.array(
353
+ [
354
+ self.origin.tolist(),
355
+ [self.maximum[0], self.origin[1], self.origin[2]],
356
+ [self.maximum[0], self.maximum[1], self.origin[2]],
357
+ [self.origin[0], self.maximum[1], self.origin[2]],
358
+ [self.origin[0], self.origin[1], self.maximum[2]],
359
+ [self.maximum[0], self.origin[1], self.maximum[2]],
360
+ self.maximum.tolist(),
361
+ [self.origin[0], self.maximum[1], self.maximum[2]],
362
+ ]
363
+ )
364
+ elif self.dimensions == 2:
365
+ return np.array(
366
+ [
367
+ self.origin.tolist(),
368
+ [self.maximum[0], self.origin[1]],
369
+ self.maximum.tolist(),
370
+ [self.origin[0], self.maximum[1]],
371
+ ]
372
+ )
373
+ else:
374
+ raise NotImplementedError(
375
+ f"corners not yet supported for a {self.dimensions}D bounding box"
376
+ )
377
+
378
+ @property
379
+ def corners_global(self) -> np.ndarray:
380
+ """Returns the corners of the bounding box
381
+ in the original space
382
+
383
+ Returns
384
+ -------
385
+ np.ndarray
386
+ corners of the bounding box
387
+ """
388
+ return self.corners
389
+
390
+ @property
391
+ def step_vector(self):
392
+ if np.any(self.nsteps == 0):
393
+ raise LoopValueError("Cannot compute step_vector: nsteps contains zero values")
394
+ return (self.maximum - self.origin) / self.nsteps
395
+
396
+ @property
397
+ def length(self):
398
+ return self.maximum - self.origin
399
+
400
+ def fit(self, locations: np.ndarray, local_coordinate: bool = False) -> BoundingBox:
401
+ """Initialise the bounding box from a set of points.
402
+
403
+ Parameters
404
+ ----------
405
+ locations : np.ndarray
406
+ xyz locations of the points to fit the bbox
407
+ local_coordinate : bool, optional
408
+ whether to set the origin to [0,0,0], by default False
409
+
410
+ Returns
411
+ -------
412
+ BoundingBox
413
+ A reference to the bounding box object, note this is not a new bounding box
414
+ it updates the current one in place.
415
+
416
+ Raises
417
+ ------
418
+ LoopValueError
419
+ _description_
420
+ """
421
+ if locations.shape[1] != self.dimensions:
422
+ raise LoopValueError(
423
+ f"locations array is {locations.shape[1]}D but bounding box is {self.dimensions}"
424
+ )
425
+ origin = locations.min(axis=0)
426
+ maximum = locations.max(axis=0)
427
+ origin = np.array(origin)
428
+ maximum = np.array(maximum)
429
+ self.origin = origin
430
+ self.maximum = maximum
431
+ if local_coordinate:
432
+ self.set_local_transform(local_origin=origin)
433
+ else:
434
+ self.set_local_transform(local_origin=np.zeros(self.dimensions, dtype=float))
435
+ return self
436
+
437
+ def with_buffer(self, buffer: float = 0.2) -> BoundingBox:
438
+ """Create a new bounding box with a buffer around the existing bounding box
439
+
440
+ Parameters
441
+ ----------
442
+ buffer : float, optional
443
+ percentage to expand the dimensions by, by default 0.2
444
+
445
+ Returns
446
+ -------
447
+ BoundingBox
448
+ The new bounding box object.
449
+
450
+ Raises
451
+ ------
452
+ LoopValueError
453
+ if the current bounding box is invalid
454
+ """
455
+ if self.origin is None or self.maximum is None:
456
+ raise LoopValueError("Cannot create bounding box with buffer, no origin or maximum")
457
+ # local coordinates, rescale into the original bounding boxes global coordinates
458
+ origin = self.origin - buffer * np.max(self.maximum - self.origin)
459
+ maximum = self.maximum + buffer * np.max(self.maximum - self.origin)
460
+ buffered = BoundingBox(
461
+ origin=origin,
462
+ maximum=maximum,
463
+ nsteps=self.nsteps,
464
+ dimensions=self.dimensions,
465
+ )
466
+ buffered.set_local_transform(
467
+ local_origin=self.local_origin,
468
+ rotation_matrix=self.local_rotation,
469
+ )
470
+ return buffered
471
+
472
+ def __call__(self, xyz):
473
+ xyz = np.asarray(xyz, dtype=float)
474
+ if xyz.ndim == 1:
475
+ xyz = xyz[None, :]
476
+ # Calculate center and half-extents of the box
477
+ center = (self.maximum + self.origin) / 2
478
+ half_extents = (self.maximum - self.origin) / 2
479
+
480
+ # Calculate the distance from point to center
481
+ offset = np.abs(xyz - center) - half_extents
482
+
483
+ # Inside distance: negative value based on the smallest penetration
484
+ inside_distance = np.min(half_extents - np.abs(xyz - center), axis=1)
485
+
486
+ # Outside distance: length of the positive components of offset
487
+ outside_distance = np.linalg.norm(np.maximum(offset, 0), axis=1)
488
+
489
+ # If any component of offset is positive, we're outside
490
+ # Otherwise, we're inside and return the negative penetration distance
491
+ distance = np.zeros(xyz.shape[0])
492
+ mask = np.any(offset > 0, axis=1)
493
+ distance[mask] = outside_distance
494
+ distance[~mask] = -inside_distance[~mask]
495
+ return distance
496
+ # return outside_distance if np.any(offset > 0) else -inside_distance
497
+
498
+ def get_value(self, name):
499
+ ix, iy = self.name_map.get(name, (-1, -1))
500
+ if ix == -1 and iy == -1:
501
+ raise LoopValueError(f"{name} is not a valid bounding box name")
502
+ if iy == -1:
503
+ return self.origin[ix]
504
+
505
+ return self.bb[ix, iy]
506
+
507
+ def __getitem__(self, name):
508
+ if isinstance(name, str):
509
+ return self.get_value(name)
510
+ elif isinstance(name, tuple):
511
+ return self.origin
512
+ return self.get_value(name)
513
+
514
+ def is_inside(self, xyz):
515
+ xyz = np.array(xyz)
516
+ if len(xyz.shape) == 1:
517
+ xyz = xyz.reshape((1, -1))
518
+ if xyz.shape[1] != self.dimensions:
519
+ raise LoopValueError(
520
+ f"locations array is {xyz.shape[1]}D but bounding box is {self.dimensions}"
521
+ )
522
+ if self.dimensions not in (2, 3):
523
+ raise NotImplementedError(
524
+ f"is_inside not yet supported for a {self.dimensions}D bounding box"
525
+ )
526
+ inside = np.ones(xyz.shape[0], dtype=bool)
527
+ for i in range(self.dimensions):
528
+ inside = np.logical_and(inside, xyz[:, i] > self.origin[i])
529
+ inside = np.logical_and(inside, xyz[:, i] < self.maximum[i])
530
+ return inside
531
+
532
+ def regular_grid(
533
+ self,
534
+ nsteps: list | np.ndarray | None = None,
535
+ shuffle: bool = False,
536
+ order: str = "F",
537
+ local: bool = True,
538
+ ) -> np.ndarray:
539
+ """Get the grid of points from the bounding box
540
+
541
+ Parameters
542
+ ----------
543
+ nsteps : Optional[Union[list, np.ndarray]], optional
544
+ number of steps, by default None uses self.nsteps
545
+ shuffle : bool, optional
546
+ Whether to return points in order or random, by default False
547
+ order : str, optional
548
+ when flattening using numpy "C" or "F", by default "C"
549
+ local : bool, optional
550
+ Whether to return the points in the local coordinate system of global
551
+ , by default True
552
+
553
+ Returns
554
+ -------
555
+ np.ndarray
556
+ numpy array N,3 of the points
557
+ """
558
+
559
+ if nsteps is None:
560
+ nsteps = self.nsteps
561
+ coordinates = [
562
+ np.linspace(self.origin[i], self.maximum[i], nsteps[i]) for i in range(self.dimensions)
563
+ ]
564
+ coordinate_grid = np.meshgrid(*coordinates, indexing="ij")
565
+ locs = np.array([coord.flatten(order=order) for coord in coordinate_grid]).T
566
+
567
+ if local:
568
+ locs = self.project(locs)
569
+
570
+ if shuffle:
571
+ # logger.info("Shuffling points")
572
+ rng.shuffle(locs)
573
+ return locs
574
+
575
+ def cell_centres(self, order: str = "F") -> np.ndarray:
576
+ """Get the cell centres of a regular grid
577
+
578
+ Parameters
579
+ ----------
580
+ order : str, optional
581
+ order of the grid, by default "C"
582
+
583
+ Returns
584
+ -------
585
+ np.ndarray
586
+ array of cell centres
587
+ """
588
+ locs = self.regular_grid(order=order, nsteps=self.nsteps - 1)
589
+
590
+ return locs + 0.5 * self.step_vector
591
+
592
+ def to_dict(self) -> dict:
593
+ """Export the defining characteristics of the bounding
594
+ box to a dictionary for json serialisation
595
+
596
+ Returns
597
+ -------
598
+ dict
599
+ dictionary with origin, maximum and nsteps
600
+ """
601
+ return {
602
+ "origin": self.origin.tolist(),
603
+ "maximum": self.maximum.tolist(),
604
+ "nsteps": self.nsteps.tolist(),
605
+ "local_origin": self.local_origin.tolist(),
606
+ "local_rotation": self.local_rotation.tolist(),
607
+ }
608
+
609
+ @classmethod
610
+ def from_dict(cls, data: dict) -> BoundingBox:
611
+ """Create a bounding box from a dictionary
612
+
613
+ Parameters
614
+ ----------
615
+ data : dict
616
+ dictionary with origin, maximum and nsteps
617
+
618
+ Returns
619
+ -------
620
+ BoundingBox
621
+ bounding box object
622
+ """
623
+ bbox = cls(
624
+ origin=np.array(data["origin"]),
625
+ maximum=np.array(data["maximum"]),
626
+ nsteps=np.array(data["nsteps"]),
627
+ )
628
+ if "local_origin" in data or "local_rotation" in data:
629
+ bbox.set_local_transform(
630
+ local_origin=np.array(data.get("local_origin", np.zeros(bbox.dimensions))),
631
+ rotation_matrix=np.array(
632
+ data.get("local_rotation", np.eye(bbox.dimensions).tolist())
633
+ ),
634
+ )
635
+ return bbox
636
+
637
+ def vtk(self):
638
+ """Export the model as a pyvista RectilinearGrid
639
+
640
+ Returns
641
+ -------
642
+ pv.RectilinearGrid
643
+ a pyvista grid object
644
+
645
+ Raises
646
+ ------
647
+ ImportError
648
+ If pyvista is not installed raise import error
649
+ """
650
+ try:
651
+ import pyvista as pv
652
+ except ImportError:
653
+ raise ImportError("pyvista is required for vtk support")
654
+ x = np.linspace(self.origin[0], self.maximum[0], self.nsteps[0])
655
+ y = np.linspace(self.origin[1], self.maximum[1], self.nsteps[1])
656
+ z = np.linspace(self.origin[2], self.maximum[2], self.nsteps[2])
657
+ return pv.RectilinearGrid(
658
+ x,
659
+ y,
660
+ z,
661
+ )
662
+
663
+ def structured_grid(
664
+ self,
665
+ cell_data: dict[str, np.ndarray] | None = None,
666
+ vertex_data: dict | None = None,
667
+ name: str = "bounding_box",
668
+ local_coordinates: bool = False,
669
+ ):
670
+ # python is passing a reference to the cell_data, vertex_data dicts so we need to
671
+ # copy them to make sure that different instances of StructuredGrid are not sharing the same
672
+ # underlying objects
673
+ if cell_data is None:
674
+ cell_data = {}
675
+ if vertex_data is None:
676
+ vertex_data = {}
677
+ _cell_data = copy.deepcopy(cell_data)
678
+ _vertex_data = copy.deepcopy(vertex_data)
679
+ if local_coordinates:
680
+ # Project all corners of the box through the affine transform and
681
+ # take the min/max over all of them. Projecting only the
682
+ # origin/maximum corners is only exact for translation-only
683
+ # transforms; a rotation can move any of the other corners
684
+ # outside the [origin, maximum] range in local space.
685
+ local_points = self.project(self.corners)
686
+ local_origin = np.min(local_points, axis=0)
687
+ local_maximum = np.max(local_points, axis=0)
688
+ step_vector = (local_maximum - local_origin) / self.nsteps
689
+ origin = local_origin
690
+ else:
691
+ step_vector = self.step_vector
692
+ origin = self.origin
693
+ return StructuredGrid(
694
+ origin=origin,
695
+ step_vector=step_vector,
696
+ nsteps=self.nsteps,
697
+ cell_properties=_cell_data,
698
+ properties=_vertex_data,
699
+ name=name,
700
+ )
701
+
702
+ def project(self, xyz, inplace=False):
703
+ """Project a point into the bounding box
704
+
705
+ Parameters
706
+ ----------
707
+ xyz : np.ndarray
708
+ point to project
709
+ inplace : bool, optional
710
+ Whether to modify the input array in place, by default False
711
+
712
+ Returns
713
+ -------
714
+ np.ndarray
715
+ projected point
716
+ """
717
+ return self._apply_affine(xyz, self.world_to_local_matrix, inplace=inplace)
718
+
719
+ def project_vectors(self, vectors: np.ndarray) -> np.ndarray:
720
+ """Rotate vectors from world frame into local frame."""
721
+ arr = np.asarray(vectors, dtype=float)
722
+ is_vector = arr.ndim == 1
723
+ vec = arr.reshape(1, -1) if is_vector else arr
724
+ if vec.shape[1] != self.dimensions:
725
+ raise LoopValueError(
726
+ f"vector array is {vec.shape[1]}D but bounding box is {self.dimensions}"
727
+ )
728
+ projected = (self.local_rotation @ vec.T).T
729
+ return projected[0] if is_vector else projected
730
+
731
+ def scale_by_projection_factor(self, value):
732
+ return value / np.max(self.maximum - self.origin)
733
+
734
+ def reproject(self, xyz, inplace=False):
735
+ """Reproject a point from the bounding box to the global space
736
+
737
+ Parameters
738
+ ----------
739
+ xyz : np.ndarray
740
+ point to reproject
741
+ inplace : bool, optional
742
+ Whether to modify the input array in place, by default False
743
+ Returns
744
+ -------
745
+ np.ndarray
746
+ reprojected point
747
+ """
748
+ return self._apply_affine(xyz, self.local_to_world_matrix, inplace=inplace)
749
+
750
+ def reproject_vectors(self, vectors: np.ndarray) -> np.ndarray:
751
+ """Rotate vectors from local frame back into world frame."""
752
+ arr = np.asarray(vectors, dtype=float)
753
+ is_vector = arr.ndim == 1
754
+ vec = arr.reshape(1, -1) if is_vector else arr
755
+ if vec.shape[1] != self.dimensions:
756
+ raise LoopValueError(
757
+ f"vector array is {vec.shape[1]}D but bounding box is {self.dimensions}"
758
+ )
759
+ rotation = self.local_to_world_matrix[: self.dimensions, : self.dimensions]
760
+ reprojected = (rotation @ vec.T).T
761
+ return reprojected[0] if is_vector else reprojected
762
+
763
+ def __repr__(self):
764
+ return f"BoundingBox(origin:{self.origin}, maximum:{self.maximum}, nsteps:{self.nsteps})"
765
+
766
+ def __str__(self):
767
+ return f"BoundingBox(origin:{self.origin}, maximum:{self.maximum}, nsteps:{self.nsteps})"
768
+
769
+ def __eq__(self, other):
770
+ if not isinstance(other, BoundingBox):
771
+ return False
772
+ return (
773
+ np.allclose(self.origin, other.origin)
774
+ and np.allclose(self.maximum, other.maximum)
775
+ and np.allclose(self.nsteps, other.nsteps)
776
+ )
777
+
778
+ def matrix(self, normalise: bool = False) -> np.ndarray:
779
+ """Get the world-to-local transformation matrix.
780
+
781
+ Returns
782
+ -------
783
+ np.ndarray
784
+ 4x4 transformation matrix
785
+ """
786
+ matrix = self.world_to_local_matrix
787
+ if normalise:
788
+ L = np.max(self.maximum - self.origin)
789
+ if L > 0:
790
+ matrix[: self.dimensions, : self.dimensions] /= L
791
+ matrix[: self.dimensions, 3] /= L
792
+ return matrix