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.
- loop_common/__init__.py +6 -0
- loop_common/base.py +98 -0
- loop_common/geometry/__init__.py +19 -0
- loop_common/geometry/_aabb.py +37 -0
- loop_common/geometry/_bounding_box.py +792 -0
- loop_common/geometry/_face_table.py +42 -0
- loop_common/geometry/_point.py +238 -0
- loop_common/geometry/_structured_grid.py +114 -0
- loop_common/geometry/_structured_grid_2d.py +146 -0
- loop_common/geometry/_structured_grid_3d.py +243 -0
- loop_common/geometry/_surface.py +288 -0
- loop_common/geometry/_unstructured_mesh.py +208 -0
- loop_common/interfaces/__init__.py +0 -0
- loop_common/interfaces/representation.py +45 -0
- loop_common/io/__init__.py +0 -0
- loop_common/logging/__init__.py +14 -0
- loop_common/logging/logger.py +123 -0
- loop_common/logging/sinks.py +221 -0
- loop_common/logging/timing.py +113 -0
- loop_common/math/__init__.py +5 -0
- loop_common/math/_maths.py +441 -0
- loop_common/math/_transformation.py +178 -0
- loop_common/math/finite_difference_stencil.py +38 -0
- loop_common/observations/__init__.py +3 -0
- loop_common/observations/lineset.py +41 -0
- loop_common/observations/orientation.py +122 -0
- loop_common/observations/pointset.py +8 -0
- loop_common/observer.py +284 -0
- loop_common/supports/_2d_base_unstructured.py +361 -0
- loop_common/supports/_2d_p1_unstructured.py +131 -0
- loop_common/supports/_2d_p2_unstructured.py +349 -0
- loop_common/supports/_2d_structured_grid.py +545 -0
- loop_common/supports/_3d_base_structured.py +546 -0
- loop_common/supports/_3d_p2_tetra.py +374 -0
- loop_common/supports/_3d_rectilinear_grid.py +315 -0
- loop_common/supports/_3d_structured_grid.py +510 -0
- loop_common/supports/_3d_structured_tetra.py +764 -0
- loop_common/supports/_3d_unstructured_tetra.py +656 -0
- loop_common/supports/__init__.py +69 -0
- loop_common/supports/_aabb.py +77 -0
- loop_common/supports/_base_support.py +118 -0
- loop_common/supports/_face_table.py +70 -0
- loop_common/supports/_p2_structured_tetra.py +627 -0
- loop_common/supports/_support_factory.py +78 -0
- loop_common/utils.py +74 -0
- loop_common-0.0.1.dist-info/METADATA +35 -0
- loop_common-0.0.1.dist-info/RECORD +50 -0
- loop_common-0.0.1.dist-info/WHEEL +5 -0
- loop_common-0.0.1.dist-info/licenses/LICENSE +21 -0
- loop_common-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from scipy import sparse
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def _init_face_table(grid):
|
|
6
|
+
rows = np.tile(np.arange(grid.n_elements)[:, None], (1, grid.dimension + 1))
|
|
7
|
+
elements = grid.elements
|
|
8
|
+
neighbours = grid.neighbours
|
|
9
|
+
element_nodes = sparse.coo_matrix(
|
|
10
|
+
(
|
|
11
|
+
np.ones(elements.shape[0] * (grid.dimension + 1)),
|
|
12
|
+
(rows.ravel(), elements[:, : grid.dimension + 1].ravel()),
|
|
13
|
+
),
|
|
14
|
+
shape=(grid.n_elements, grid.n_nodes),
|
|
15
|
+
dtype=bool,
|
|
16
|
+
).tocsr()
|
|
17
|
+
n1 = np.tile(np.arange(neighbours.shape[0], dtype=int)[:, None], (1, grid.dimension + 1))
|
|
18
|
+
n1 = n1.flatten()
|
|
19
|
+
n2 = neighbours.flatten()
|
|
20
|
+
n1 = n1[n2 >= 0]
|
|
21
|
+
n2 = n2[n2 >= 0]
|
|
22
|
+
el_rel = np.zeros((grid.neighbours.flatten().shape[0], 2), dtype=int)
|
|
23
|
+
el_rel[:] = -1
|
|
24
|
+
el_rel[np.arange(n1.shape[0]), 0] = n1
|
|
25
|
+
el_rel[np.arange(n1.shape[0]), 1] = n2
|
|
26
|
+
el_rel = el_rel[el_rel[:, 0] >= 0, :]
|
|
27
|
+
grid._shared_element_relationships[:] = -1
|
|
28
|
+
el_pairs = sparse.coo_matrix((np.ones(el_rel.shape[0]), (el_rel[:, 0], el_rel[:, 1]))).tocsr()
|
|
29
|
+
i, j = sparse.tril(el_pairs).nonzero()
|
|
30
|
+
grid._shared_element_relationships[: len(i), 0] = i
|
|
31
|
+
grid._shared_element_relationships[: len(i), 1] = j
|
|
32
|
+
grid._shared_element_relationships = grid.shared_element_relationships[grid.shared_element_relationships[:, 0] >= 0, :]
|
|
33
|
+
faces = element_nodes[grid.shared_element_relationships[:, 0], :].multiply(element_nodes[grid.shared_element_relationships[:, 1], :])
|
|
34
|
+
shared_faces = faces[np.array(np.sum(faces, axis=1) == grid.dimension).flatten(), :]
|
|
35
|
+
row, col = shared_faces.nonzero()
|
|
36
|
+
row = row[row.argsort()]
|
|
37
|
+
col = col[row.argsort()]
|
|
38
|
+
shared_face_index = np.zeros((shared_faces.shape[0], grid.dimension), dtype=int)
|
|
39
|
+
shared_face_index[:] = -1
|
|
40
|
+
shared_face_index[row.reshape(-1, grid.dimension)[:, 0], :] = col.reshape(-1, grid.dimension)
|
|
41
|
+
grid._shared_elements[np.arange(grid.shared_element_relationships.shape[0]), :] = shared_face_index
|
|
42
|
+
grid._shared_elements = grid.shared_elements[: len(grid.shared_element_relationships), :]
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
from loop_common.logging import get_logger as getLogger
|
|
9
|
+
|
|
10
|
+
logger = getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class ValuePoints:
|
|
15
|
+
locations: np.ndarray = field(default_factory=lambda: np.array([[0, 0, 0]]))
|
|
16
|
+
values: np.ndarray = field(default_factory=lambda: np.array([0]))
|
|
17
|
+
name: str = "unnamed"
|
|
18
|
+
properties: dict | None = None
|
|
19
|
+
|
|
20
|
+
def to_dict(self):
|
|
21
|
+
return {
|
|
22
|
+
"locations": self.locations,
|
|
23
|
+
"values": self.values,
|
|
24
|
+
"name": self.name,
|
|
25
|
+
"properties": (
|
|
26
|
+
{k: p.tolist() for k, p in self.properties.items()} if self.properties else None
|
|
27
|
+
),
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
def vtk(self, scalars=None):
|
|
31
|
+
import pyvista as pv
|
|
32
|
+
|
|
33
|
+
points = pv.PolyData(self.locations)
|
|
34
|
+
if scalars is not None and len(scalars) == len(self.locations):
|
|
35
|
+
points.point_data["scalars"] = scalars
|
|
36
|
+
else:
|
|
37
|
+
points["values"] = self.values
|
|
38
|
+
return points
|
|
39
|
+
|
|
40
|
+
def plot(self, pyvista_kwargs=None):
|
|
41
|
+
"""Calls pyvista plot on the vtk object
|
|
42
|
+
|
|
43
|
+
Parameters
|
|
44
|
+
----------
|
|
45
|
+
pyvista_kwargs : dict, optional
|
|
46
|
+
kwargs passed to pyvista.DataSet.plot(), by default {}
|
|
47
|
+
"""
|
|
48
|
+
if pyvista_kwargs is None:
|
|
49
|
+
pyvista_kwargs = {}
|
|
50
|
+
try:
|
|
51
|
+
self.vtk().plot(**pyvista_kwargs)
|
|
52
|
+
return
|
|
53
|
+
except ImportError:
|
|
54
|
+
logger.error("pyvista is required for vtk")
|
|
55
|
+
|
|
56
|
+
def save(self, filename: str | io.StringIO, *, group="Loop", ext=None):
|
|
57
|
+
if isinstance(filename, io.StringIO):
|
|
58
|
+
if ext is None:
|
|
59
|
+
raise ValueError("Please provide an extension for StringIO")
|
|
60
|
+
ext = ext.lower()
|
|
61
|
+
else:
|
|
62
|
+
ext = filename.split(".")[-1].lower()
|
|
63
|
+
filename = str(filename)
|
|
64
|
+
if ext == "json":
|
|
65
|
+
import json
|
|
66
|
+
|
|
67
|
+
with open(filename, "w") as f:
|
|
68
|
+
json.dump(self.to_dict(), f)
|
|
69
|
+
elif ext == "vtk":
|
|
70
|
+
self.vtk().save(filename)
|
|
71
|
+
|
|
72
|
+
elif ext == "geoh5":
|
|
73
|
+
from LoopStructural.export.geoh5 import add_points_to_geoh5
|
|
74
|
+
|
|
75
|
+
add_points_to_geoh5(filename, self, groupname=group)
|
|
76
|
+
elif ext == "pkl":
|
|
77
|
+
import pickle
|
|
78
|
+
|
|
79
|
+
with open(filename, "wb") as f:
|
|
80
|
+
pickle.dump(self, f)
|
|
81
|
+
elif ext == "vs":
|
|
82
|
+
from LoopStructural.export.gocad import _write_pointset
|
|
83
|
+
|
|
84
|
+
_write_pointset(self, filename)
|
|
85
|
+
elif ext == "csv":
|
|
86
|
+
import pandas as pd
|
|
87
|
+
|
|
88
|
+
df = pd.DataFrame(self.locations, columns=["x", "y", "z"])
|
|
89
|
+
df["value"] = self.values
|
|
90
|
+
if self.properties is not None:
|
|
91
|
+
for k, v in self.properties.items():
|
|
92
|
+
df[k] = v
|
|
93
|
+
df.to_csv(filename, index=False)
|
|
94
|
+
elif ext == "omf":
|
|
95
|
+
from LoopStructural.export.omf_wrapper import add_pointset_to_omf
|
|
96
|
+
|
|
97
|
+
add_pointset_to_omf(self, filename)
|
|
98
|
+
else:
|
|
99
|
+
raise ValueError(f"Unknown file extension {ext}")
|
|
100
|
+
|
|
101
|
+
@classmethod
|
|
102
|
+
def from_dict(cls, d, flatten=False):
|
|
103
|
+
if "locations" not in d:
|
|
104
|
+
raise ValueError("locations not in dictionary")
|
|
105
|
+
locations = np.array(d["locations"])
|
|
106
|
+
if flatten:
|
|
107
|
+
locations = locations.reshape((-1, 3))
|
|
108
|
+
return ValuePoints(
|
|
109
|
+
locations, d.get("values", None), d.get("name", "unnamed"), d.get("properties", None)
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass
|
|
114
|
+
class VectorPoints:
|
|
115
|
+
locations: np.ndarray = field(default_factory=lambda: np.array([[0, 0, 0]]))
|
|
116
|
+
vectors: np.ndarray = field(default_factory=lambda: np.array([[0, 0, 0]]))
|
|
117
|
+
name: str = "unnamed"
|
|
118
|
+
properties: dict | None = None
|
|
119
|
+
|
|
120
|
+
def to_dict(self):
|
|
121
|
+
return {
|
|
122
|
+
"locations": self.locations,
|
|
123
|
+
"vectors": self.vectors,
|
|
124
|
+
"name": self.name,
|
|
125
|
+
"properties": (
|
|
126
|
+
{k: p.tolist() for k, p in self.properties.items()} if self.properties else None
|
|
127
|
+
),
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
def from_dict(self, d):
|
|
131
|
+
return VectorPoints(d["locations"], d["vectors"], d["name"], d.get("properties", None))
|
|
132
|
+
|
|
133
|
+
def vtk(
|
|
134
|
+
self,
|
|
135
|
+
geom="arrow",
|
|
136
|
+
scale=1.0,
|
|
137
|
+
scale_function=None,
|
|
138
|
+
normalise=False,
|
|
139
|
+
tolerance=0.05,
|
|
140
|
+
bb=None,
|
|
141
|
+
scalars=None,
|
|
142
|
+
):
|
|
143
|
+
import pyvista as pv
|
|
144
|
+
|
|
145
|
+
_projected = False
|
|
146
|
+
vectors = np.copy(self.vectors)
|
|
147
|
+
|
|
148
|
+
if normalise:
|
|
149
|
+
norm = np.linalg.norm(vectors, axis=1)
|
|
150
|
+
vectors[norm > 0, :] /= norm[norm > 0][:, None]
|
|
151
|
+
else:
|
|
152
|
+
norm = np.linalg.norm(vectors, axis=1)
|
|
153
|
+
vectors[norm > 0, :] /= norm[norm > 0][:, None]
|
|
154
|
+
norm[norm > 0] = norm[norm > 0] / norm[norm > 0].max()
|
|
155
|
+
vectors[norm > 0, :] *= norm[norm > 0, None]
|
|
156
|
+
if scale_function is not None:
|
|
157
|
+
# vectors /= np.linalg.norm(vectors, axis=1)[:, None]
|
|
158
|
+
vectors *= scale_function(self.locations)[:, None]
|
|
159
|
+
locations = self.locations
|
|
160
|
+
if bb is not None:
|
|
161
|
+
try:
|
|
162
|
+
locations = bb.project(locations)
|
|
163
|
+
_projected = True
|
|
164
|
+
except (AttributeError, TypeError, ValueError, RuntimeError) as exc:
|
|
165
|
+
logger.error(f"Failed to project points to bounding box: {exc}")
|
|
166
|
+
logger.error("Using unprojected points, this may cause issues with the glyphing")
|
|
167
|
+
points = pv.PolyData(locations)
|
|
168
|
+
if scalars is not None and len(scalars) == len(self.locations):
|
|
169
|
+
points["scalars"] = scalars
|
|
170
|
+
points.point_data.set_vectors(vectors, "vectors")
|
|
171
|
+
if geom == "arrow":
|
|
172
|
+
geom = pv.Arrow(scale=scale)
|
|
173
|
+
elif geom == "disc":
|
|
174
|
+
geom = pv.Disc(inner=0, outer=scale * 0.5, c_res=50).rotate_y(90)
|
|
175
|
+
|
|
176
|
+
# Perform the glyph
|
|
177
|
+
glyphed = points.glyph(orient="vectors", geom=geom, tolerance=tolerance)
|
|
178
|
+
if _projected:
|
|
179
|
+
glyphed.points = bb.reproject(glyphed.points)
|
|
180
|
+
return glyphed
|
|
181
|
+
|
|
182
|
+
def plot(self, pyvista_kwargs=None):
|
|
183
|
+
"""Calls pyvista plot on the vtk object
|
|
184
|
+
|
|
185
|
+
Parameters
|
|
186
|
+
----------
|
|
187
|
+
pyvista_kwargs : dict, optional
|
|
188
|
+
kwargs passed to pyvista.DataSet.plot(), by default {}
|
|
189
|
+
"""
|
|
190
|
+
if pyvista_kwargs is None:
|
|
191
|
+
pyvista_kwargs = {}
|
|
192
|
+
try:
|
|
193
|
+
self.vtk().plot(**pyvista_kwargs)
|
|
194
|
+
return
|
|
195
|
+
except ImportError:
|
|
196
|
+
logger.error("pyvista is required for vtk")
|
|
197
|
+
|
|
198
|
+
def save(self, filename, *, group="Loop"):
|
|
199
|
+
filename = str(filename)
|
|
200
|
+
ext = filename.split(".")[-1]
|
|
201
|
+
if ext == "json":
|
|
202
|
+
import json
|
|
203
|
+
|
|
204
|
+
with open(filename, "w") as f:
|
|
205
|
+
json.dump(self.to_dict(), f)
|
|
206
|
+
elif ext == "vtk":
|
|
207
|
+
self.vtk().save(filename)
|
|
208
|
+
|
|
209
|
+
elif ext == "geoh5":
|
|
210
|
+
from LoopStructural.export.geoh5 import add_points_to_geoh5
|
|
211
|
+
|
|
212
|
+
add_points_to_geoh5(filename, self, groupname=group)
|
|
213
|
+
elif ext == "pkl":
|
|
214
|
+
import pickle
|
|
215
|
+
|
|
216
|
+
with open(filename, "wb") as f:
|
|
217
|
+
pickle.dump(self, f)
|
|
218
|
+
elif ext == "vs":
|
|
219
|
+
from LoopStructural.export.gocad import _write_pointset
|
|
220
|
+
|
|
221
|
+
_write_pointset(self, filename)
|
|
222
|
+
elif ext == "csv":
|
|
223
|
+
import pandas as pd
|
|
224
|
+
|
|
225
|
+
df = pd.DataFrame(self.locations, columns=["x", "y", "z"])
|
|
226
|
+
df["vx"] = self.vectors[:, 0]
|
|
227
|
+
df["vy"] = self.vectors[:, 1]
|
|
228
|
+
df["vz"] = self.vectors[:, 2]
|
|
229
|
+
if self.properties is not None:
|
|
230
|
+
for k, v in self.properties.items():
|
|
231
|
+
df[k] = v
|
|
232
|
+
df.to_csv(filename)
|
|
233
|
+
elif ext == "omf":
|
|
234
|
+
from LoopStructural.export.omf_wrapper import add_pointset_to_omf
|
|
235
|
+
|
|
236
|
+
add_pointset_to_omf(self, filename)
|
|
237
|
+
else:
|
|
238
|
+
raise ValueError(f"Unknown file extension {ext}")
|
|
@@ -0,0 +1,114 @@
|
|
|
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
|
+
logger = getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class StructuredGrid:
|
|
12
|
+
"""A structured grid for storing 3D geological data."""
|
|
13
|
+
|
|
14
|
+
origin: np.ndarray = field(default_factory=lambda: np.array([0, 0, 0]))
|
|
15
|
+
step_vector: np.ndarray = field(default_factory=lambda: np.array([1, 1, 1]))
|
|
16
|
+
nsteps: np.ndarray = field(default_factory=lambda: np.array([10, 10, 10]))
|
|
17
|
+
cell_properties: dict[str, np.ndarray] = field(default_factory=dict)
|
|
18
|
+
properties: dict[str, np.ndarray] = field(default_factory=dict)
|
|
19
|
+
name: str = "default_grid"
|
|
20
|
+
|
|
21
|
+
def to_dict(self):
|
|
22
|
+
return {
|
|
23
|
+
"origin": self.origin,
|
|
24
|
+
"maximum": self.maximum,
|
|
25
|
+
"step_vector": self.step_vector,
|
|
26
|
+
"nsteps": self.nsteps,
|
|
27
|
+
"cell_properties": self.cell_properties,
|
|
28
|
+
"properties": self.properties,
|
|
29
|
+
"name": self.name,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def maximum(self):
|
|
34
|
+
return self.origin + (self.nsteps - 1) * self.step_vector
|
|
35
|
+
|
|
36
|
+
def vtk(self):
|
|
37
|
+
try:
|
|
38
|
+
import pyvista as pv
|
|
39
|
+
except ImportError as exc:
|
|
40
|
+
raise ImportError("pyvista is required for vtk support") from exc
|
|
41
|
+
x = np.linspace(self.origin[0], self.maximum[0], self.nsteps[0])
|
|
42
|
+
y = np.linspace(self.origin[1], self.maximum[1], self.nsteps[1])
|
|
43
|
+
z = np.linspace(self.origin[2], self.maximum[2], self.nsteps[2])
|
|
44
|
+
grid = pv.RectilinearGrid(x, y, z)
|
|
45
|
+
for name, data in self.properties.items():
|
|
46
|
+
grid[name] = data.reshape((grid.n_points, -1), order="F")
|
|
47
|
+
for name, data in self.cell_properties.items():
|
|
48
|
+
grid.cell_data[name] = data.reshape((grid.n_cells, -1), order="F")
|
|
49
|
+
return grid
|
|
50
|
+
|
|
51
|
+
def plot(self, pyvista_kwargs=None):
|
|
52
|
+
if pyvista_kwargs is None:
|
|
53
|
+
pyvista_kwargs = {}
|
|
54
|
+
try:
|
|
55
|
+
self.vtk().plot(**pyvista_kwargs)
|
|
56
|
+
return
|
|
57
|
+
except ImportError:
|
|
58
|
+
logger.error("pyvista is required for vtk")
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def cell_centres(self):
|
|
62
|
+
x = np.linspace(
|
|
63
|
+
self.origin[0] + self.step_vector[0] * 0.5,
|
|
64
|
+
self.maximum[0] + self.step_vector[0] * 0.5,
|
|
65
|
+
self.nsteps[0] - 1,
|
|
66
|
+
)
|
|
67
|
+
y = np.linspace(
|
|
68
|
+
self.origin[1] + self.step_vector[1] * 0.5,
|
|
69
|
+
self.maximum[1] - self.step_vector[1] * 0.5,
|
|
70
|
+
self.nsteps[1] - 1,
|
|
71
|
+
)
|
|
72
|
+
z = np.linspace(
|
|
73
|
+
self.origin[2] + self.step_vector[2] * 0.5,
|
|
74
|
+
self.maximum[2] - self.step_vector[2] * 0.5,
|
|
75
|
+
self.nsteps[2] - 1,
|
|
76
|
+
)
|
|
77
|
+
x, y, z = np.meshgrid(x, y, z, indexing="ij")
|
|
78
|
+
return np.vstack([x.flatten(order="f"), y.flatten(order="f"), z.flatten(order="f")]).T
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def nodes(self):
|
|
82
|
+
x = np.linspace(self.origin[0], self.maximum[0], self.nsteps[0])
|
|
83
|
+
y = np.linspace(self.origin[1], self.maximum[1], self.nsteps[1])
|
|
84
|
+
z = np.linspace(self.origin[2], self.maximum[2], self.nsteps[2])
|
|
85
|
+
x, y, z = np.meshgrid(x, y, z, indexing="ij")
|
|
86
|
+
return np.vstack([x.flatten(order="f"), y.flatten(order="f"), z.flatten(order="f")]).T
|
|
87
|
+
|
|
88
|
+
def merge(self, other):
|
|
89
|
+
if not np.all(np.isclose(self.origin, other.origin)):
|
|
90
|
+
raise ValueError("Origin of grids must be the same")
|
|
91
|
+
if not np.all(np.isclose(self.step_vector, other.step_vector)):
|
|
92
|
+
raise ValueError("Step vector of grids must be the same")
|
|
93
|
+
if not np.all(np.isclose(self.nsteps, other.nsteps)):
|
|
94
|
+
raise ValueError("Number of steps of grids must be the same")
|
|
95
|
+
for name, data in other.cell_properties.items():
|
|
96
|
+
self.cell_properties[name] = data
|
|
97
|
+
for name, data in other.properties.items():
|
|
98
|
+
self.properties[name] = data
|
|
99
|
+
|
|
100
|
+
def save(self, filename, *, group="Loop"):
|
|
101
|
+
filename = str(filename)
|
|
102
|
+
ext = filename.split(".")[-1].lower()
|
|
103
|
+
if ext == "json":
|
|
104
|
+
import json
|
|
105
|
+
with open(filename, "w") as f:
|
|
106
|
+
json.dump(self.to_dict(), f)
|
|
107
|
+
elif ext == "vtk":
|
|
108
|
+
self.vtk().save(filename)
|
|
109
|
+
elif ext == "pkl":
|
|
110
|
+
import pickle
|
|
111
|
+
with open(filename, "wb") as f:
|
|
112
|
+
pickle.dump(self, f)
|
|
113
|
+
else:
|
|
114
|
+
raise ValueError(f"Unknown file extension {ext}")
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Pure 2D regular grid geometry: origin/nsteps/step_vector indexing."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from loop_common.logging import get_logger as getLogger
|
|
7
|
+
|
|
8
|
+
logger = getLogger(__name__)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class StructuredGrid2DGeometry:
|
|
12
|
+
"""A 2D regular grid defined by an origin, step vector and number of steps."""
|
|
13
|
+
|
|
14
|
+
dimension = 2
|
|
15
|
+
|
|
16
|
+
def __init__(self, origin=None, nsteps=None, step_vector=None):
|
|
17
|
+
if origin is None:
|
|
18
|
+
origin = np.zeros(2)
|
|
19
|
+
if nsteps is None:
|
|
20
|
+
nsteps = np.array([10, 10])
|
|
21
|
+
if step_vector is None:
|
|
22
|
+
step_vector = np.ones(2)
|
|
23
|
+
self.nsteps = np.ceil(np.array(nsteps)).astype(int)
|
|
24
|
+
self.step_vector = np.array(step_vector)
|
|
25
|
+
self.origin = np.array(origin)
|
|
26
|
+
self.maximum = origin + self.nsteps * self.step_vector
|
|
27
|
+
self.dim = 2
|
|
28
|
+
self.nsteps_cells = self.nsteps - 1
|
|
29
|
+
self.n_cell_x = self.nsteps[0] - 1
|
|
30
|
+
self.n_cell_y = self.nsteps[1] - 1
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def nodes(self):
|
|
34
|
+
max = self.origin + self.nsteps_cells * self.step_vector
|
|
35
|
+
x = np.linspace(self.origin[0], max[0], self.nsteps[0])
|
|
36
|
+
y = np.linspace(self.origin[1], max[1], self.nsteps[1])
|
|
37
|
+
xx, yy = np.meshgrid(x, y, indexing="ij")
|
|
38
|
+
return np.array([xx.flatten(order="F"), yy.flatten(order="F")]).T
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def n_nodes(self):
|
|
42
|
+
return self.nsteps[0] * self.nsteps[1]
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def n_elements(self):
|
|
46
|
+
return self.nsteps_cells[0] * self.nsteps_cells[1]
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def element_size(self):
|
|
50
|
+
return np.prod(self.step_vector)
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def elements(self) -> np.ndarray:
|
|
54
|
+
global_index = np.arange(self.n_elements)
|
|
55
|
+
cell_indexes = self.global_index_to_cell_index(global_index)
|
|
56
|
+
return self.global_node_indices(self.cell_corner_indexes(cell_indexes))
|
|
57
|
+
|
|
58
|
+
def print_geometry(self):
|
|
59
|
+
logger.info(f"Origin: {self.origin[0]:f} {self.origin[1]:f} {self.origin[2]:f}")
|
|
60
|
+
logger.info(
|
|
61
|
+
f"Cell size: {self.step_vector[0]:f} {self.step_vector[1]:f} {self.step_vector[2]:f}"
|
|
62
|
+
)
|
|
63
|
+
max = self.origin + self.nsteps_cells * self.step_vector
|
|
64
|
+
logger.info(f"Max extent: {max[0]:f} {max[1]:f} {max[2]:f}")
|
|
65
|
+
|
|
66
|
+
def cell_centres(self, global_index: np.ndarray) -> np.ndarray:
|
|
67
|
+
cell_indexes = self.global_index_to_cell_index(global_index)
|
|
68
|
+
cell_centres = np.zeros((cell_indexes.shape[0], 2))
|
|
69
|
+
cell_centres[:, 0] = (
|
|
70
|
+
self.origin[None, 0]
|
|
71
|
+
+ self.step_vector[None, 0] * 0.5
|
|
72
|
+
+ self.step_vector[None, 0] * cell_indexes[:, 0]
|
|
73
|
+
)
|
|
74
|
+
cell_centres[:, 1] = (
|
|
75
|
+
self.origin[None, 1]
|
|
76
|
+
+ self.step_vector[None, 1] * 0.5
|
|
77
|
+
+ self.step_vector[None, 1] * cell_indexes[:, 1]
|
|
78
|
+
)
|
|
79
|
+
return cell_centres
|
|
80
|
+
|
|
81
|
+
def position_to_cell_index(self, pos: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
82
|
+
inside = self.inside(pos)
|
|
83
|
+
cell_indexes = np.zeros((pos.shape[0], 2))
|
|
84
|
+
cell_indexes[:, 0] = pos[:, 0] - self.origin[None, 0]
|
|
85
|
+
cell_indexes[:, 1] = pos[:, 1] - self.origin[None, 1]
|
|
86
|
+
cell_indexes /= self.step_vector[None, :]
|
|
87
|
+
return cell_indexes.astype(int), inside
|
|
88
|
+
|
|
89
|
+
def inside(self, pos: np.ndarray) -> np.ndarray:
|
|
90
|
+
inside = np.ones(pos.shape[0]).astype(bool)
|
|
91
|
+
for i in range(self.dim):
|
|
92
|
+
inside *= pos[:, i] > self.origin[None, i]
|
|
93
|
+
inside *= pos[:, i] < self.origin[None, i] + self.step_vector[None, i] * self.nsteps_cells[None, i]
|
|
94
|
+
return inside
|
|
95
|
+
|
|
96
|
+
def check_position(self, pos: np.ndarray) -> np.ndarray:
|
|
97
|
+
if len(pos.shape) == 1:
|
|
98
|
+
pos = np.array([pos])
|
|
99
|
+
if len(pos.shape) != 2:
|
|
100
|
+
raise ValueError("Position array needs to be a list of points or a point")
|
|
101
|
+
return pos
|
|
102
|
+
|
|
103
|
+
def neighbour_global_indexes(self, mask=None, **kwargs):
|
|
104
|
+
indexes = None
|
|
105
|
+
if "indexes" in kwargs:
|
|
106
|
+
indexes = kwargs["indexes"]
|
|
107
|
+
if "indexes" not in kwargs:
|
|
108
|
+
gi = np.arange(self.n_nodes)
|
|
109
|
+
indexes = self.global_index_to_node_index(gi)
|
|
110
|
+
edge_mask = (
|
|
111
|
+
(indexes[:, 0] > 0)
|
|
112
|
+
& (indexes[:, 0] < self.nsteps[0] - 1)
|
|
113
|
+
& (indexes[:, 1] > 0)
|
|
114
|
+
& (indexes[:, 1] < self.nsteps[1] - 1)
|
|
115
|
+
)
|
|
116
|
+
indexes = indexes[edge_mask, :].T
|
|
117
|
+
if indexes.ndim != 2:
|
|
118
|
+
logger.error("indexes.ndim = %s, expected 2", indexes.ndim)
|
|
119
|
+
return
|
|
120
|
+
if mask is None:
|
|
121
|
+
mask = np.array([[-1, 0, 1, -1, 0, 1, -1, 0, 1], [1, 1, 1, 0, 0, 0, -1, -1, -1]])
|
|
122
|
+
neighbours = indexes[:, None, :] + mask[:, :, None]
|
|
123
|
+
return (neighbours[0, :, :] + self.nsteps[0, None, None] * neighbours[1, :, :]).astype(np.int64)
|
|
124
|
+
|
|
125
|
+
def cell_corner_indexes(self, cell_indexes: np.ndarray) -> np.ndarray:
|
|
126
|
+
corner_indexes = np.zeros((cell_indexes.shape[0], 4, 2), dtype=np.int64)
|
|
127
|
+
xcorner = np.array([0, 1, 0, 1])
|
|
128
|
+
ycorner = np.array([0, 0, 1, 1])
|
|
129
|
+
corner_indexes[:, :, 0] = cell_indexes[:, None, 0] + corner_indexes[:, :, 0] + xcorner[None, :]
|
|
130
|
+
corner_indexes[:, :, 1] = cell_indexes[:, None, 1] + corner_indexes[:, :, 1] + ycorner[None, :]
|
|
131
|
+
return corner_indexes
|
|
132
|
+
|
|
133
|
+
def global_index_to_cell_index(self, global_index):
|
|
134
|
+
cell_indexes = np.zeros((global_index.shape[0], 2), dtype=np.int64)
|
|
135
|
+
cell_indexes[:, 0] = global_index % self.nsteps_cells[0, None]
|
|
136
|
+
cell_indexes[:, 1] = global_index // self.nsteps_cells[0, None] % self.nsteps_cells[1, None]
|
|
137
|
+
return cell_indexes
|
|
138
|
+
|
|
139
|
+
def global_index_to_node_index(self, global_index):
|
|
140
|
+
cell_indexes = np.zeros((global_index.shape[0], 2), dtype=np.int64)
|
|
141
|
+
cell_indexes[:, 0] = global_index % self.nsteps[0, None]
|
|
142
|
+
cell_indexes[:, 1] = global_index // self.nsteps[0, None] % self.nsteps[1, None]
|
|
143
|
+
return cell_indexes
|
|
144
|
+
|
|
145
|
+
def global_node_indices(self, node_indexes):
|
|
146
|
+
return node_indexes
|