loop-common 0.1.0__tar.gz → 0.2.0__tar.gz

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 (83) hide show
  1. {loop_common-0.1.0 → loop_common-0.2.0}/PKG-INFO +1 -1
  2. {loop_common-0.1.0 → loop_common-0.2.0}/pyproject.toml +2 -2
  3. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/geometry/__init__.py +5 -1
  4. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/geometry/_bounding_box.py +122 -20
  5. loop_common-0.2.0/src/loop_common/geometry/_rigid.py +50 -0
  6. loop_common-0.2.0/src/loop_common/geometry/_structured_grid.py +288 -0
  7. loop_common-0.1.0/src/loop_common/supports/_2d_structured_grid.py → loop_common-0.2.0/src/loop_common/geometry/_structured_grid_2d.py +117 -319
  8. loop_common-0.2.0/src/loop_common/geometry/_structured_grid_3d.py +496 -0
  9. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/math/__init__.py +1 -0
  10. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/math/_transformation.py +94 -52
  11. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/supports/_2d_base_unstructured.py +3 -2
  12. loop_common-0.2.0/src/loop_common/supports/_2d_structured_grid.py +162 -0
  13. loop_common-0.2.0/src/loop_common/supports/_3d_base_structured.py +141 -0
  14. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/supports/_3d_p2_tetra.py +2 -1
  15. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/supports/_3d_rectilinear_grid.py +89 -0
  16. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/supports/_3d_structured_grid.py +0 -103
  17. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/supports/_3d_structured_tetra.py +7 -1
  18. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/supports/_p2_structured_tetra.py +7 -1
  19. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common.egg-info/PKG-INFO +1 -1
  20. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common.egg-info/SOURCES.txt +12 -0
  21. loop_common-0.2.0/tests/test_bounding_box_structured_grid.py +71 -0
  22. loop_common-0.2.0/tests/test_cell_centre_sampling.py +126 -0
  23. loop_common-0.2.0/tests/test_euclidean_transformation.py +100 -0
  24. loop_common-0.2.0/tests/test_property_grid.py +163 -0
  25. loop_common-0.2.0/tests/test_resize_paths.py +183 -0
  26. loop_common-0.2.0/tests/test_rigid_transform_contract.py +154 -0
  27. loop_common-0.2.0/tests/test_structured_grid_2d_geometry.py +74 -0
  28. loop_common-0.2.0/tests/test_structured_grid_2d_reference.py +182 -0
  29. loop_common-0.2.0/tests/test_structured_grid_geometry.py +122 -0
  30. loop_common-0.2.0/tests/test_structured_support_reference.py +238 -0
  31. loop_common-0.2.0/tests/test_tetra_face_tolerance.py +61 -0
  32. loop_common-0.1.0/src/loop_common/geometry/_structured_grid.py +0 -114
  33. loop_common-0.1.0/src/loop_common/geometry/_structured_grid_2d.py +0 -146
  34. loop_common-0.1.0/src/loop_common/geometry/_structured_grid_3d.py +0 -243
  35. loop_common-0.1.0/src/loop_common/supports/_3d_base_structured.py +0 -546
  36. {loop_common-0.1.0 → loop_common-0.2.0}/LICENSE +0 -0
  37. {loop_common-0.1.0 → loop_common-0.2.0}/README.md +0 -0
  38. {loop_common-0.1.0 → loop_common-0.2.0}/setup.cfg +0 -0
  39. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/__init__.py +0 -0
  40. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/base.py +0 -0
  41. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/geometry/_aabb.py +0 -0
  42. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/geometry/_face_table.py +0 -0
  43. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/geometry/_point.py +0 -0
  44. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/geometry/_surface.py +0 -0
  45. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/geometry/_unstructured_mesh.py +0 -0
  46. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/interfaces/__init__.py +0 -0
  47. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/interfaces/representation.py +0 -0
  48. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/io/__init__.py +0 -0
  49. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/logging/__init__.py +0 -0
  50. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/logging/logger.py +0 -0
  51. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/logging/sinks.py +0 -0
  52. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/logging/timing.py +0 -0
  53. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/math/_maths.py +0 -0
  54. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/math/finite_difference_stencil.py +0 -0
  55. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/observations/__init__.py +0 -0
  56. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/observations/lineset.py +0 -0
  57. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/observations/orientation.py +0 -0
  58. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/observations/pointset.py +0 -0
  59. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/observer.py +0 -0
  60. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/supports/_2d_p1_unstructured.py +0 -0
  61. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/supports/_2d_p2_unstructured.py +0 -0
  62. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/supports/_3d_unstructured_tetra.py +0 -0
  63. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/supports/__init__.py +0 -0
  64. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/supports/_aabb.py +0 -0
  65. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/supports/_base_support.py +0 -0
  66. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/supports/_face_table.py +0 -0
  67. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/supports/_support_factory.py +0 -0
  68. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common/utils.py +0 -0
  69. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common.egg-info/dependency_links.txt +0 -0
  70. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common.egg-info/requires.txt +0 -0
  71. {loop_common-0.1.0 → loop_common-0.2.0}/src/loop_common.egg-info/top_level.txt +0 -0
  72. {loop_common-0.1.0 → loop_common-0.2.0}/tests/test_2d_discrete_support.py +0 -0
  73. {loop_common-0.1.0 → loop_common-0.2.0}/tests/test_base.py +0 -0
  74. {loop_common-0.1.0 → loop_common-0.2.0}/tests/test_bounding_box.py +0 -0
  75. {loop_common-0.1.0 → loop_common-0.2.0}/tests/test_discrete_supports.py +0 -0
  76. {loop_common-0.1.0 → loop_common-0.2.0}/tests/test_imports.py +0 -0
  77. {loop_common-0.1.0 → loop_common-0.2.0}/tests/test_observations.py +0 -0
  78. {loop_common-0.1.0 → loop_common-0.2.0}/tests/test_p0_pointset_serialization.py +0 -0
  79. {loop_common-0.1.0 → loop_common-0.2.0}/tests/test_p2_shape_derivatives_outside.py +0 -0
  80. {loop_common-0.1.0 → loop_common-0.2.0}/tests/test_p2_structured_tetra.py +0 -0
  81. {loop_common-0.1.0 → loop_common-0.2.0}/tests/test_rectilinear_grid.py +0 -0
  82. {loop_common-0.1.0 → loop_common-0.2.0}/tests/test_structured_grid_boundary_eval.py +0 -0
  83. {loop_common-0.1.0 → loop_common-0.2.0}/tests/test_unstructured_supports.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: loop-common
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Common utilities for LoopStructural
5
5
  Author-email: Lachlan Grose <lachlan.grose@monash.edu>
6
6
  License: MIT
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
5
5
  [project]
6
6
  name = "loop-common"
7
7
  description = "Common utilities for LoopStructural"
8
- version = "0.1.0"
8
+ version = "0.2.0"
9
9
  requires-python = ">=3.9"
10
10
  authors = [{ name = "Lachlan Grose", email = "lachlan.grose@monash.edu" }]
11
11
  readme = "README.md"
@@ -30,4 +30,4 @@ tests = ["pytest"]
30
30
 
31
31
  [tool.setuptools.packages.find]
32
32
  where = ["src"]
33
- include = ["loop_common", "loop_common.*"]
33
+ include = ["loop_common", "loop_common.*"]
@@ -1,6 +1,7 @@
1
1
  from ._bounding_box import BoundingBox
2
2
  from ._point import ValuePoints, VectorPoints
3
- from ._structured_grid import StructuredGrid
3
+ from ._rigid import RigidRotationError, validate_rigid_rotation
4
+ from ._structured_grid import PropertyGrid, StructuredGrid
4
5
  from ._structured_grid_2d import StructuredGrid2DGeometry
5
6
  from ._structured_grid_3d import StructuredGrid3DGeometry
6
7
  from ._surface import Surface
@@ -8,6 +9,8 @@ from ._unstructured_mesh import UnstructuredMesh2DGeometry, UnstructuredMeshGeom
8
9
 
9
10
  __all__ = [
10
11
  "BoundingBox",
12
+ "PropertyGrid",
13
+ "RigidRotationError",
11
14
  "StructuredGrid",
12
15
  "StructuredGrid2DGeometry",
13
16
  "StructuredGrid3DGeometry",
@@ -16,4 +19,5 @@ __all__ = [
16
19
  "UnstructuredMeshGeometry",
17
20
  "ValuePoints",
18
21
  "VectorPoints",
22
+ "validate_rigid_rotation",
19
23
  ]
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import copy
4
+ from itertools import product
4
5
 
5
6
  import numpy as np
6
7
 
@@ -8,7 +9,9 @@ from loop_common.logging import get_logger as getLogger
8
9
 
9
10
  # from LoopStructural.utils.exceptions import LoopValueError
10
11
  from loop_common.math import rng
11
- from loop_common.supports import StructuredGrid
12
+
13
+ from ._rigid import validate_rigid_rotation
14
+ from ._structured_grid import PropertyGrid
12
15
 
13
16
  logger = getLogger(__name__)
14
17
 
@@ -17,7 +20,6 @@ class LoopValueError(ValueError):
17
20
  """Custom error for invalid values in LoopStructural."""
18
21
 
19
22
 
20
-
21
23
  class BoundingBox:
22
24
  def __init__(
23
25
  self,
@@ -30,6 +32,20 @@ class BoundingBox:
30
32
  """A bounding box for a model, defined by the
31
33
  origin, maximum and number of steps in each direction
32
34
 
35
+ Notes
36
+ -----
37
+ ``nsteps`` is used in two ways, so two spacings are provided:
38
+
39
+ * Cell-based (interpolation): ``nsteps`` is the number of cells in each
40
+ direction and ``step_vector`` is ``(maximum - origin) / nsteps``. Interpolation
41
+ supports are built from these.
42
+ * Node-based (values on a grid): ``regular_grid`` returns ``nsteps`` points spanning
43
+ the full extent, so the spacing between them is ``node_step_vector``,
44
+ ``(maximum - origin) / (nsteps - 1)``. ``cell_centres`` returns the
45
+ ``nsteps - 1`` centres of the cells between those points. Use this
46
+ convention (as pyvista/VTK ``ImageData`` and ``numpy.linspace`` do)
47
+ when storing values computed at ``regular_grid`` or ``cell_centres``.
48
+
33
49
  Parameters
34
50
  ----------
35
51
  dimensions : int, optional
@@ -59,7 +75,9 @@ class BoundingBox:
59
75
 
60
76
  if nsteps is not None:
61
77
  if len(nsteps) != dimensions:
62
- logger.warning(f"Nsteps has {len(nsteps)} dimensions but bounding box has {dimensions}")
78
+ logger.warning(
79
+ f"Nsteps has {len(nsteps)} dimensions but bounding box has {dimensions}"
80
+ )
63
81
  raise LoopValueError("Nsteps has incorrect number of dimensions")
64
82
  if np.any(np.asarray(nsteps) <= 0):
65
83
  raise LoopValueError("Nsteps must be positive integers")
@@ -131,17 +149,15 @@ class BoundingBox:
131
149
  """
132
150
  if local_origin is None:
133
151
  local_origin = np.zeros(self.dimensions, dtype=float)
134
- local_origin = np.asarray(local_origin, dtype=float)
152
+ local_origin = np.array(local_origin, dtype=float, copy=True)
135
153
  if local_origin.shape != (self.dimensions,):
136
154
  raise LoopValueError("Local origin has incorrect number of dimensions")
155
+ if not np.all(np.isfinite(local_origin)):
156
+ raise LoopValueError("Local origin must contain only finite values")
137
157
 
138
158
  if rotation_matrix is None:
139
159
  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
- )
160
+ rotation_matrix = validate_rigid_rotation(rotation_matrix, self.dimensions)
145
161
 
146
162
  self._local_origin = local_origin
147
163
  self._local_rotation = rotation_matrix
@@ -153,6 +169,50 @@ class BoundingBox:
153
169
  self._world_to_local = world_to_local
154
170
  self._local_to_world = np.linalg.inv(world_to_local)
155
171
 
172
+ def local_enclosure(
173
+ self,
174
+ origin: np.ndarray | None = None,
175
+ maximum: np.ndarray | None = None,
176
+ ) -> tuple[np.ndarray, np.ndarray]:
177
+ """Return local bounds enclosing a world-space axis-aligned box.
178
+
179
+ Parameters
180
+ ----------
181
+ origin : np.ndarray, optional
182
+ World-space minimum corner. Defaults to the bounding box origin.
183
+ maximum : np.ndarray, optional
184
+ World-space maximum corner. Defaults to the bounding box maximum.
185
+
186
+ Returns
187
+ -------
188
+ tuple[np.ndarray, np.ndarray]
189
+ Local-space minimum and maximum coordinates.
190
+
191
+ Raises
192
+ ------
193
+ LoopValueError
194
+ If either bound is missing, invalid, or has the wrong shape.
195
+ """
196
+ if origin is None:
197
+ origin = self._origin
198
+ if maximum is None:
199
+ maximum = self._maximum
200
+ if origin is None or maximum is None:
201
+ raise LoopValueError("Origin and maximum must be set")
202
+
203
+ origin = np.asarray(origin, dtype=float)
204
+ maximum = np.asarray(maximum, dtype=float)
205
+ if origin.shape != (self.dimensions,) or maximum.shape != (self.dimensions,):
206
+ raise LoopValueError("Bounds have incorrect number of dimensions")
207
+ if not np.all(np.isfinite(origin)) or not np.all(np.isfinite(maximum)):
208
+ raise LoopValueError("Bounds must contain only finite values")
209
+ if np.any(origin > maximum):
210
+ raise LoopValueError("Maximum must be greater than or equal to origin")
211
+
212
+ corners = np.array(list(product(*zip(origin, maximum))), dtype=float)
213
+ local_corners = self.project(corners)
214
+ return np.min(local_corners, axis=0), np.max(local_corners, axis=0)
215
+
156
216
  def _apply_affine(
157
217
  self, xyz: np.ndarray, matrix: np.ndarray, inplace: bool = False
158
218
  ) -> np.ndarray:
@@ -393,6 +453,18 @@ class BoundingBox:
393
453
  raise LoopValueError("Cannot compute step_vector: nsteps contains zero values")
394
454
  return (self.maximum - self.origin) / self.nsteps
395
455
 
456
+ @property
457
+ def node_step_vector(self):
458
+ """Spacing between the ``nsteps`` points returned by :meth:`regular_grid`.
459
+
460
+ ``(maximum - origin) / (nsteps - 1)``; compare ``step_vector``, which divides
461
+ by ``nsteps`` and is the cell size used to build interpolation supports.
462
+ """
463
+ nodes = np.asarray(self.nsteps, dtype=float)
464
+ if np.any(nodes < 2):
465
+ raise LoopValueError("Cannot compute node_step_vector: nsteps must be at least 2")
466
+ return (self.maximum - self.origin) / (nodes - 1)
467
+
396
468
  @property
397
469
  def length(self):
398
470
  return self.maximum - self.origin
@@ -573,21 +645,29 @@ class BoundingBox:
573
645
  return locs
574
646
 
575
647
  def cell_centres(self, order: str = "F") -> np.ndarray:
576
- """Get the cell centres of a regular grid
648
+ """Get the centres of the cells between the points of :meth:`regular_grid`
649
+
650
+ There are ``nsteps - 1`` cells in each direction, each ``node_step_vector`` wide,
651
+ so every centre is inside the bounding box.
577
652
 
578
653
  Parameters
579
654
  ----------
580
655
  order : str, optional
581
- order of the grid, by default "C"
656
+ order of the grid, by default "F"
582
657
 
583
658
  Returns
584
659
  -------
585
660
  np.ndarray
586
- array of cell centres
661
+ array of cell centres, in the local coordinate system
587
662
  """
588
- locs = self.regular_grid(order=order, nsteps=self.nsteps - 1)
589
-
590
- return locs + 0.5 * self.step_vector
663
+ half = 0.5 * self.node_step_vector
664
+ coordinates = [
665
+ np.linspace(self.origin[i] + half[i], self.maximum[i] - half[i], self.nsteps[i] - 1)
666
+ for i in range(self.dimensions)
667
+ ]
668
+ coordinate_grid = np.meshgrid(*coordinates, indexing="ij")
669
+ locs = np.array([coord.flatten(order=order) for coord in coordinate_grid]).T
670
+ return self.project(locs)
591
671
 
592
672
  def to_dict(self) -> dict:
593
673
  """Export the defining characteristics of the bounding
@@ -666,9 +746,31 @@ class BoundingBox:
666
746
  vertex_data: dict | None = None,
667
747
  name: str = "bounding_box",
668
748
  local_coordinates: bool = False,
669
- ):
749
+ ) -> PropertyGrid:
750
+ """Create a :class:`PropertyGrid` whose nodes are the points of :meth:`regular_grid`.
751
+
752
+ The grid has ``nsteps`` nodes in each direction spanning the bounding box
753
+ (spacing :attr:`node_step_vector`), so values computed at ``regular_grid()`` /
754
+ ``cell_centres()`` can be stored on it directly. For a grid to interpolate on, use
755
+ ``loop_common.supports.StructuredGrid`` (built from ``step_vector``, the cell size).
756
+
757
+ Parameters
758
+ ----------
759
+ cell_data : dict, optional
760
+ cell properties to store on the grid (copied)
761
+ vertex_data : dict, optional
762
+ node properties to store on the grid (copied)
763
+ name : str, optional
764
+ name of the grid, by default "bounding_box"
765
+ local_coordinates : bool, optional
766
+ build the grid in the bounding box's local frame, by default False
767
+
768
+ Returns
769
+ -------
770
+ PropertyGrid
771
+ """
670
772
  # 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
773
+ # copy them to make sure that different instances of PropertyGrid are not sharing the same
672
774
  # underlying objects
673
775
  if cell_data is None:
674
776
  cell_data = {}
@@ -685,12 +787,12 @@ class BoundingBox:
685
787
  local_points = self.project(self.corners)
686
788
  local_origin = np.min(local_points, axis=0)
687
789
  local_maximum = np.max(local_points, axis=0)
688
- step_vector = (local_maximum - local_origin) / self.nsteps
790
+ step_vector = (local_maximum - local_origin) / (self.nsteps - 1)
689
791
  origin = local_origin
690
792
  else:
691
- step_vector = self.step_vector
793
+ step_vector = self.node_step_vector
692
794
  origin = self.origin
693
- return StructuredGrid(
795
+ return PropertyGrid(
694
796
  origin=origin,
695
797
  step_vector=step_vector,
696
798
  nsteps=self.nsteps,
@@ -0,0 +1,50 @@
1
+ """Validation helpers for rigid rotations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+
8
+ class RigidRotationError(ValueError):
9
+ """Raised when a matrix is not a proper rotation."""
10
+
11
+
12
+ def validate_rigid_rotation(matrix: np.ndarray, dimensions: int, atol: float = 1e-10) -> np.ndarray:
13
+ """Validate and return a copy of a proper rotation matrix.
14
+
15
+ Parameters
16
+ ----------
17
+ matrix : np.ndarray
18
+ Candidate rotation matrix.
19
+ dimensions : int
20
+ Required matrix dimensions.
21
+ atol : float, default=1e-10
22
+ Absolute tolerance for orthonormality and determinant checks.
23
+
24
+ Returns
25
+ -------
26
+ np.ndarray
27
+ Floating point copy of the validated rotation matrix.
28
+
29
+ Raises
30
+ ------
31
+ RigidRotationError
32
+ If the matrix is not a finite proper rotation.
33
+ """
34
+ rotation = np.array(matrix, dtype=float)
35
+ suffix = "; supply a proper rotation (orthonormal, det +1); scale and shear are not supported"
36
+
37
+ if rotation.shape != (dimensions, dimensions):
38
+ raise RigidRotationError(f"matrix shape must be ({dimensions}, {dimensions}){suffix}")
39
+ if not np.all(np.isfinite(rotation)):
40
+ raise RigidRotationError(f"matrix entries must be finite{suffix}")
41
+
42
+ orthogonality_error = np.max(np.abs(rotation.T @ rotation - np.eye(dimensions)))
43
+ if orthogonality_error > atol:
44
+ raise RigidRotationError(f"matrix must be orthonormal{suffix}")
45
+
46
+ determinant_error = abs(np.linalg.det(rotation) - 1.0)
47
+ if determinant_error > atol:
48
+ raise RigidRotationError(f"matrix determinant must be +1{suffix}")
49
+
50
+ return rotation
@@ -0,0 +1,288 @@
1
+ from dataclasses import dataclass, field
2
+
3
+ import numpy as np
4
+
5
+ from loop_common.logging import get_logger as getLogger
6
+
7
+ from ._structured_grid_3d import StructuredGrid3DGeometry
8
+
9
+ logger = getLogger(__name__)
10
+
11
+
12
+ @dataclass
13
+ class PropertyGrid:
14
+ """A regular 3D grid for storing property values (the result container).
15
+
16
+ This is a data container, not an interpolation support: it holds
17
+ node-based ``properties`` and ``cell_properties`` on a regular grid and can
18
+ export them (``vtk``, ``save``). For the class used to interpolate on a
19
+ grid see :class:`loop_common.supports.StructuredGrid`.
20
+
21
+ The grid geometry (node and cell positions, point-in-cell lookup) is defined once, by
22
+ :class:`StructuredGrid3DGeometry`, which is built from ``origin``, ``step_vector`` and
23
+ ``nsteps`` (the number of **nodes**) whenever it is needed; see :attr:`geometry`. Points
24
+ passed to the lookup methods are in the grid's own frame (the grid is not rotated).
25
+
26
+ It was previously named ``StructuredGrid``; that name remains as an alias.
27
+
28
+ This class represents a regular 3D grid with properties and cell properties
29
+ that can be used for geological modelling and visualisation.
30
+
31
+ Parameters
32
+ ----------
33
+ origin : np.ndarray, optional
34
+ Origin point of the grid, by default [0, 0, 0]
35
+ step_vector : np.ndarray, optional
36
+ Step size in each direction, by default [1, 1, 1]
37
+ nsteps : np.ndarray, optional
38
+ Number of steps in each direction, by default [10, 10, 10]
39
+ cell_properties : Dict[str, np.ndarray], optional
40
+ Properties defined at cell centres, by default empty dict
41
+ properties : Dict[str, np.ndarray], optional
42
+ Properties defined at grid nodes, by default empty dict
43
+ name : str, optional
44
+ Name of the grid, by default "default_grid"
45
+ """
46
+
47
+ origin: np.ndarray = field(default_factory=lambda: np.array([0, 0, 0]))
48
+ step_vector: np.ndarray = field(default_factory=lambda: np.array([1, 1, 1]))
49
+ nsteps: np.ndarray = field(default_factory=lambda: np.array([10, 10, 10]))
50
+ cell_properties: dict[str, np.ndarray] = field(default_factory=dict)
51
+ properties: dict[str, np.ndarray] = field(default_factory=dict)
52
+ name: str = "default_grid"
53
+
54
+ def to_dict(self):
55
+ """Convert the structured grid to a dictionary representation.
56
+
57
+ Returns
58
+ -------
59
+ dict
60
+ Dictionary containing all grid properties and metadata
61
+ """
62
+ return {
63
+ "origin": self.origin,
64
+ "maximum": self.maximum,
65
+ "step_vector": self.step_vector,
66
+ "nsteps": self.nsteps,
67
+ "cell_properties": self.cell_properties,
68
+ "properties": self.properties,
69
+ "name": self.name,
70
+ }
71
+
72
+ @property
73
+ def geometry(self) -> StructuredGrid3DGeometry:
74
+ """The grid geometry, built from the current ``origin``, ``step_vector`` and ``nsteps``.
75
+
76
+ It is a fresh object each time, so it always reflects the current fields.
77
+ """
78
+ return StructuredGrid3DGeometry(
79
+ origin=self.origin, nsteps=self.nsteps, step_vector=self.step_vector
80
+ )
81
+
82
+ @property
83
+ def maximum(self):
84
+ """Calculate the maximum coordinates of the grid.
85
+
86
+ Returns
87
+ -------
88
+ np.ndarray
89
+ Maximum coordinates (origin + (nsteps - 1) * step_vector)
90
+ """
91
+ return self.geometry.maximum
92
+
93
+ @property
94
+ def nsteps_cells(self):
95
+ """Number of cells in each direction (``nsteps - 1``)."""
96
+ return self.geometry.nsteps_cells
97
+
98
+ @property
99
+ def n_nodes(self):
100
+ """Total number of nodes."""
101
+ return self.geometry.n_nodes
102
+
103
+ @property
104
+ def n_cells(self):
105
+ """Total number of cells."""
106
+ return self.geometry.n_elements
107
+
108
+ def inside(self, points):
109
+ """Boolean mask of the points inside the grid (boundary included)."""
110
+ return self.geometry.inside(np.asarray(points, dtype=float))
111
+
112
+ def cell_index_at(self, points):
113
+ """Flat index of the cell each point falls in.
114
+
115
+ The flat index addresses ``cell_properties`` arrays and the rows of ``cell_centres``
116
+ (x varies fastest). Points on the maximum boundary belong to the last cell.
117
+
118
+ Parameters
119
+ ----------
120
+ points : array-like
121
+ N x 3 locations (or one location) in the grid's own frame
122
+
123
+ Returns
124
+ -------
125
+ np.ndarray
126
+ N integer indexes, ``-1`` for points outside the grid
127
+ """
128
+ geometry = self.geometry
129
+ cell_ijk, inside = geometry.position_to_cell_index(np.asarray(points, dtype=float))
130
+ index = np.full(len(inside), -1, dtype=np.int64)
131
+ index[inside] = geometry.global_cell_indices(cell_ijk[inside])
132
+ return index
133
+
134
+ def evaluate_value(self, name, points):
135
+ """Trilinear interpolation of the node property ``name`` at the points.
136
+
137
+ This is what is needed to transfer a property onto another support or mesh: pass the
138
+ other support's node coordinates as ``points``.
139
+
140
+ Parameters
141
+ ----------
142
+ name : str
143
+ key of ``properties``; values are per node, in node order (x varies fastest), either
144
+ ``(n_nodes,)`` or ``(n_nodes, k)``
145
+ points : array-like
146
+ N x 3 locations (or one location) in the grid's own frame
147
+
148
+ Returns
149
+ -------
150
+ np.ndarray
151
+ ``(N,)`` (or ``(N, k)``) values; NaN for points outside the grid
152
+ """
153
+ return self.geometry.evaluate_value(np.asarray(points, dtype=float), self.properties[name])
154
+
155
+ def cell_value_at(self, name, points):
156
+ """Value of the cell property ``name`` in the cell each point falls in.
157
+
158
+ Parameters
159
+ ----------
160
+ name : str
161
+ key of ``cell_properties``
162
+ points : array-like
163
+ N x 3 locations (or one location) in the grid's own frame
164
+
165
+ Returns
166
+ -------
167
+ np.ndarray
168
+ one entry per point; NaN for points outside the grid
169
+ """
170
+ values = np.asarray(self.cell_properties[name])
171
+ index = self.cell_index_at(points)
172
+ found = index >= 0
173
+ result = np.full((len(index),) + values.shape[1:], np.nan)
174
+ result[found] = values[index[found]]
175
+ return result
176
+
177
+ def vtk(self):
178
+ """Convert the structured grid to a PyVista RectilinearGrid.
179
+
180
+ Returns
181
+ -------
182
+ pv.RectilinearGrid
183
+ PyVista grid object with all properties attached
184
+
185
+ Raises
186
+ ------
187
+ ImportError
188
+ If PyVista is not installed
189
+ """
190
+ try:
191
+ import pyvista as pv
192
+ except ImportError:
193
+ raise ImportError("pyvista is required for vtk support")
194
+ x = np.linspace(self.origin[0], self.maximum[0], self.nsteps[0])
195
+ y = np.linspace(self.origin[1], self.maximum[1], self.nsteps[1])
196
+ z = np.linspace(self.origin[2], self.maximum[2], self.nsteps[2])
197
+ grid = pv.RectilinearGrid(
198
+ x,
199
+ y,
200
+ z,
201
+ )
202
+ for name, data in self.properties.items():
203
+ grid[name] = data.reshape((grid.n_points, -1), order="F")
204
+ for name, data in self.cell_properties.items():
205
+ grid.cell_data[name] = data.reshape((grid.n_cells, -1), order="F")
206
+ return grid
207
+
208
+ def plot(self, pyvista_kwargs=None):
209
+ """Calls pyvista plot on the vtk object
210
+
211
+ Parameters
212
+ ----------
213
+ pyvista_kwargs : dict, optional
214
+ kwargs passed to pyvista.DataSet.plot(), by default {}
215
+ """
216
+ if pyvista_kwargs is None:
217
+ pyvista_kwargs = {}
218
+ try:
219
+ self.vtk().plot(**pyvista_kwargs)
220
+ return
221
+ except ImportError:
222
+ logger.error("pyvista is required for vtk")
223
+
224
+ @property
225
+ def cell_centres(self):
226
+ """Coordinates of the centres of the ``nsteps - 1`` cells in each direction.
227
+
228
+ Returns
229
+ -------
230
+ np.ndarray
231
+ (n_cells, 3) array in the same order as ``cell_properties`` (x varies fastest)
232
+ """
233
+ geometry = self.geometry
234
+ cell_ijk = geometry.global_index_to_cell_index(np.arange(geometry.n_elements))
235
+ return geometry.origin + (cell_ijk + 0.5) * geometry.step_vector
236
+
237
+ @property
238
+ def nodes(self):
239
+ """Coordinates of the nodes, (n_nodes, 3), in the same order as ``properties``."""
240
+ return self.geometry.nodes
241
+
242
+ def merge(self, other):
243
+ if not np.all(np.isclose(self.origin, other.origin)):
244
+ raise ValueError("Origin of grids must be the same")
245
+ if not np.all(np.isclose(self.step_vector, other.step_vector)):
246
+ raise ValueError("Step vector of grids must be the same")
247
+ if not np.all(np.isclose(self.nsteps, other.nsteps)):
248
+ raise ValueError("Number of steps of grids must be the same")
249
+
250
+ for name, data in other.cell_properties.items():
251
+ self.cell_properties[name] = data
252
+ for name, data in other.properties.items():
253
+ self.properties[name] = data
254
+
255
+ def save(self, filename, *, group="Loop"):
256
+ filename = str(filename)
257
+ ext = filename.split(".")[-1].lower()
258
+ if ext == "json":
259
+ import json
260
+
261
+ with open(filename, "w") as f:
262
+ json.dump(self.to_dict(), f)
263
+ elif ext == "vtk":
264
+ self.vtk().save(filename)
265
+
266
+ elif ext == "geoh5":
267
+ from LoopStructural.export.geoh5 import add_structured_grid_to_geoh5
268
+
269
+ add_structured_grid_to_geoh5(filename, self, groupname=group)
270
+ elif ext == "pkl":
271
+ import pickle
272
+
273
+ with open(filename, "wb") as f:
274
+ pickle.dump(self, f)
275
+ elif ext == "omf":
276
+ from LoopStructural.export.omf_wrapper import add_structured_grid_to_omf
277
+
278
+ add_structured_grid_to_omf(self, filename)
279
+ elif ext == "vo" or ext == "gocad":
280
+ from LoopStructural.export.gocad import _write_structured_grid_gocad
281
+
282
+ _write_structured_grid_gocad(self, filename)
283
+ else:
284
+ raise ValueError(f"Unknown file extension {ext}")
285
+
286
+
287
+ # Backwards-compatible name (1.x); also keeps old pickles resolvable.
288
+ StructuredGrid = PropertyGrid