loop-link 0.1.0__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_link/__init__.py +61 -0
- loop_link/_websocket.py +436 -0
- loop_link/adapters/__init__.py +51 -0
- loop_link/adapters/loopstructural.py +83 -0
- loop_link/adapters/pandas.py +227 -0
- loop_link/adapters/pyvista.py +267 -0
- loop_link/commands.py +418 -0
- loop_link/discovery.py +170 -0
- loop_link/encode.py +688 -0
- loop_link/errors.py +279 -0
- loop_link/fetch.py +610 -0
- loop_link/objects.py +581 -0
- loop_link/orientation.py +164 -0
- loop_link/protocol.py +235 -0
- loop_link/push.py +166 -0
- loop_link/selection.py +215 -0
- loop_link/testing/__init__.py +7 -0
- loop_link/testing/fake_viewer.py +1587 -0
- loop_link/tool.py +343 -0
- loop_link/version.py +12 -0
- loop_link/viewer.py +1518 -0
- loop_link-0.1.0.dist-info/METADATA +115 -0
- loop_link-0.1.0.dist-info/RECORD +26 -0
- loop_link-0.1.0.dist-info/WHEEL +5 -0
- loop_link-0.1.0.dist-info/licenses/LICENSE +21 -0
- loop_link-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Adapter that builds drillholes from pandas tables."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from loop_link.errors import InvalidInputError, MissingExtraError
|
|
10
|
+
from loop_link.objects import Drillhole
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
import pandas as pd
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _column_array(values: pd.Series, name: str) -> np.ndarray:
|
|
17
|
+
"""Convert one table column to a numpy array.
|
|
18
|
+
|
|
19
|
+
Parameters
|
|
20
|
+
----------
|
|
21
|
+
values : pandas.Series
|
|
22
|
+
The column values.
|
|
23
|
+
name : str
|
|
24
|
+
The column name. The error text uses it.
|
|
25
|
+
|
|
26
|
+
Returns
|
|
27
|
+
-------
|
|
28
|
+
numpy.ndarray
|
|
29
|
+
A ``U`` array for a string column. Other columns keep their dtype.
|
|
30
|
+
|
|
31
|
+
Raises
|
|
32
|
+
------
|
|
33
|
+
InvalidInputError
|
|
34
|
+
If the column is an ``object`` column that holds a value that is not a string.
|
|
35
|
+
"""
|
|
36
|
+
if values.dtype.kind != "f" and values.isna().any():
|
|
37
|
+
raise InvalidInputError(
|
|
38
|
+
f"The column '{name}' has missing values. "
|
|
39
|
+
"Fill or remove the missing values, then try again."
|
|
40
|
+
)
|
|
41
|
+
if str(values.dtype) == "category":
|
|
42
|
+
# A category column, for example a lithology log: use the values of the
|
|
43
|
+
# categories. A string column then becomes a Categorical in the viewer.
|
|
44
|
+
return _column_array(values.astype(values.cat.categories.dtype), name)
|
|
45
|
+
if values.dtype.kind in "biuf" and values.dtype != object:
|
|
46
|
+
return values.to_numpy()
|
|
47
|
+
if values.dtype.kind in "US":
|
|
48
|
+
return np.asarray(values.to_numpy(), dtype="U")
|
|
49
|
+
if values.dtype == object or str(values.dtype) in ("string", "str"):
|
|
50
|
+
if values.dtype == object and values.isna().any():
|
|
51
|
+
raise InvalidInputError(
|
|
52
|
+
f"The column '{name}' has missing values. "
|
|
53
|
+
"Fill or remove the missing values, then try again."
|
|
54
|
+
)
|
|
55
|
+
if pd_infer(values) == "string":
|
|
56
|
+
return np.asarray(values.to_numpy(dtype=object), dtype="U")
|
|
57
|
+
raise InvalidInputError(
|
|
58
|
+
f"The column '{name}' has values that are not all strings. "
|
|
59
|
+
"Convert the column to numbers or to strings, then try again."
|
|
60
|
+
)
|
|
61
|
+
raise InvalidInputError(
|
|
62
|
+
f"The column '{name}' has a type that is not supported. "
|
|
63
|
+
"Convert the column to numbers or to strings, then try again."
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def pd_infer(values: pd.Series) -> str:
|
|
68
|
+
"""Return the pandas inferred type name of a column."""
|
|
69
|
+
from pandas.api.types import infer_dtype
|
|
70
|
+
|
|
71
|
+
return str(infer_dtype(values, skipna=False))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _require(table: pd.DataFrame, table_name: str, columns: list[str]) -> None:
|
|
75
|
+
"""Raise if a table does not have all the named columns."""
|
|
76
|
+
for column in columns:
|
|
77
|
+
if column not in table.columns:
|
|
78
|
+
raise InvalidInputError(
|
|
79
|
+
f"The column '{column}' is not in the {table_name} table. "
|
|
80
|
+
"Check the column names and try again."
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _hole_ids(table: pd.DataFrame, table_name: str, hole_id: str) -> list[str]:
|
|
85
|
+
"""Return the hole ids of a table as strings. Raise if an id is missing."""
|
|
86
|
+
column = table[hole_id]
|
|
87
|
+
if column.isna().any():
|
|
88
|
+
raise InvalidInputError(
|
|
89
|
+
f"The {table_name} table has a missing hole id in column '{hole_id}'. "
|
|
90
|
+
"Give each row a hole id."
|
|
91
|
+
)
|
|
92
|
+
return column.astype(str).tolist()
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def drillholes_from_pandas(
|
|
96
|
+
collar: pd.DataFrame,
|
|
97
|
+
survey: pd.DataFrame,
|
|
98
|
+
logs: pd.DataFrame | None = None,
|
|
99
|
+
*,
|
|
100
|
+
hole_id: str = "hole_id",
|
|
101
|
+
x: str = "x",
|
|
102
|
+
y: str = "y",
|
|
103
|
+
z: str = "z",
|
|
104
|
+
depth: str = "depth",
|
|
105
|
+
azimuth: str = "azimuth",
|
|
106
|
+
dip: str = "dip",
|
|
107
|
+
from_: str = "from",
|
|
108
|
+
to: str = "to",
|
|
109
|
+
dip_positive_down: bool = True,
|
|
110
|
+
) -> dict[str, Drillhole]:
|
|
111
|
+
"""Build drillholes from a collar table, a survey table and a log table.
|
|
112
|
+
|
|
113
|
+
Parameters
|
|
114
|
+
----------
|
|
115
|
+
collar : pandas.DataFrame
|
|
116
|
+
One row for each hole, with the hole id and the x, y and z of the collar.
|
|
117
|
+
survey : pandas.DataFrame
|
|
118
|
+
Survey stations, with the hole id, depth, azimuth and dip.
|
|
119
|
+
logs : pandas.DataFrame, optional
|
|
120
|
+
Interval rows, with the hole id, from and to. All other columns become
|
|
121
|
+
interval properties.
|
|
122
|
+
hole_id : str
|
|
123
|
+
Name of the hole id column in all tables.
|
|
124
|
+
x, y, z : str
|
|
125
|
+
Names of the collar coordinate columns.
|
|
126
|
+
depth, azimuth, dip : str
|
|
127
|
+
Names of the survey columns.
|
|
128
|
+
from_, to : str
|
|
129
|
+
Names of the interval columns in ``logs``.
|
|
130
|
+
dip_positive_down : bool
|
|
131
|
+
If True, a dip that points down is positive. If False, the dip sign is
|
|
132
|
+
reversed.
|
|
133
|
+
|
|
134
|
+
Returns
|
|
135
|
+
-------
|
|
136
|
+
dict of str to Drillhole
|
|
137
|
+
One drillhole for each row of ``collar``, in the order of ``collar``.
|
|
138
|
+
The keys are the hole ids as strings.
|
|
139
|
+
|
|
140
|
+
Raises
|
|
141
|
+
------
|
|
142
|
+
MissingExtraError
|
|
143
|
+
If pandas is not installed.
|
|
144
|
+
InvalidInputError
|
|
145
|
+
If a hole id in ``survey`` or ``logs`` is not in ``collar``, or if a log
|
|
146
|
+
column has a type that is not supported.
|
|
147
|
+
"""
|
|
148
|
+
try:
|
|
149
|
+
import pandas as pd # noqa: F401
|
|
150
|
+
except ImportError as exc:
|
|
151
|
+
raise MissingExtraError("pandas") from exc
|
|
152
|
+
|
|
153
|
+
_require(collar, "collar", [hole_id, x, y, z])
|
|
154
|
+
_require(survey, "survey", [hole_id, depth, azimuth, dip])
|
|
155
|
+
if logs is not None:
|
|
156
|
+
_require(logs, "logs", [hole_id, from_, to])
|
|
157
|
+
|
|
158
|
+
ids = _hole_ids(collar, "collar", hole_id)
|
|
159
|
+
if len(set(ids)) != len(ids):
|
|
160
|
+
seen: set[str] = set()
|
|
161
|
+
for name in ids:
|
|
162
|
+
if name in seen:
|
|
163
|
+
raise InvalidInputError(
|
|
164
|
+
f"The hole id '{name}' is in the collar table more than once. "
|
|
165
|
+
"Use one collar row for each hole."
|
|
166
|
+
)
|
|
167
|
+
seen.add(name)
|
|
168
|
+
known = set(ids)
|
|
169
|
+
|
|
170
|
+
def _group(table: pd.DataFrame, table_name: str, sort_by: str) -> tuple[pd.DataFrame, dict]:
|
|
171
|
+
"""Sort a table once and return it with the row positions of each hole."""
|
|
172
|
+
table = table.assign(**{hole_id: _hole_ids(table, table_name, hole_id)})
|
|
173
|
+
table = table.sort_values(sort_by, kind="stable").reset_index(drop=True)
|
|
174
|
+
positions = table.groupby(hole_id, sort=False).indices
|
|
175
|
+
for name in positions:
|
|
176
|
+
if name not in known:
|
|
177
|
+
raise InvalidInputError(
|
|
178
|
+
f"The hole id '{name}' is not in the collar table. "
|
|
179
|
+
"Add the hole to the collar table or remove its rows."
|
|
180
|
+
)
|
|
181
|
+
return table, positions
|
|
182
|
+
|
|
183
|
+
survey_sorted, survey_pos = _group(survey, "survey", depth)
|
|
184
|
+
sign = 1.0 if dip_positive_down else -1.0
|
|
185
|
+
survey_all = np.column_stack(
|
|
186
|
+
[
|
|
187
|
+
survey_sorted[depth].to_numpy(dtype=np.float64),
|
|
188
|
+
survey_sorted[azimuth].to_numpy(dtype=np.float64),
|
|
189
|
+
sign * survey_sorted[dip].to_numpy(dtype=np.float64),
|
|
190
|
+
]
|
|
191
|
+
).reshape(-1, 3)
|
|
192
|
+
|
|
193
|
+
log_pos: dict = {}
|
|
194
|
+
intervals_all = np.zeros((0, 2), dtype=np.float64)
|
|
195
|
+
log_arrays: dict[str, np.ndarray] = {}
|
|
196
|
+
if logs is not None:
|
|
197
|
+
logs_sorted, log_pos = _group(logs, "logs", from_)
|
|
198
|
+
intervals_all = np.column_stack(
|
|
199
|
+
[
|
|
200
|
+
logs_sorted[from_].to_numpy(dtype=np.float64),
|
|
201
|
+
logs_sorted[to].to_numpy(dtype=np.float64),
|
|
202
|
+
]
|
|
203
|
+
).reshape(-1, 2)
|
|
204
|
+
for column in logs_sorted.columns:
|
|
205
|
+
if column not in (hole_id, from_, to):
|
|
206
|
+
log_arrays[str(column)] = _column_array(logs_sorted[column], str(column))
|
|
207
|
+
|
|
208
|
+
xyz = np.column_stack(
|
|
209
|
+
[
|
|
210
|
+
collar[x].to_numpy(dtype=np.float64),
|
|
211
|
+
collar[y].to_numpy(dtype=np.float64),
|
|
212
|
+
collar[z].to_numpy(dtype=np.float64),
|
|
213
|
+
]
|
|
214
|
+
)
|
|
215
|
+
empty = np.zeros(0, dtype=np.intp)
|
|
216
|
+
holes: dict[str, Drillhole] = {}
|
|
217
|
+
for position, name in enumerate(ids):
|
|
218
|
+
rows = survey_pos.get(name, empty)
|
|
219
|
+
log_rows = log_pos.get(name, empty)
|
|
220
|
+
holes[name] = Drillhole(
|
|
221
|
+
collar=xyz[position],
|
|
222
|
+
survey=survey_all[rows],
|
|
223
|
+
intervals=intervals_all[log_rows],
|
|
224
|
+
properties={},
|
|
225
|
+
interval_properties={col: arr[log_rows] for col, arr in log_arrays.items()},
|
|
226
|
+
)
|
|
227
|
+
return holes
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""Adapter that turns pyvista meshes and grids into loop_link scene objects."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from loop_link.errors import InvalidInputError, MissingExtraError
|
|
10
|
+
from loop_link.objects import (
|
|
11
|
+
BlockModel,
|
|
12
|
+
Lines,
|
|
13
|
+
Points,
|
|
14
|
+
SceneObject,
|
|
15
|
+
Surface,
|
|
16
|
+
TetraMesh,
|
|
17
|
+
Vectors,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
import pyvista as _pv
|
|
22
|
+
except ImportError: # pragma: no cover - depends on the environment
|
|
23
|
+
_pv = None
|
|
24
|
+
|
|
25
|
+
_DRILLHOLE_TEXT = (
|
|
26
|
+
"A pyvista mesh cannot hold a drillhole. Use loop_link.Drillhole or "
|
|
27
|
+
"loop_link.adapters.pandas.drillholes_from_pandas."
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
# Arrays that pyvista adds by itself. The adapter skips them.
|
|
31
|
+
_SKIPPED_ARRAYS = ("Normals", "Texture Coordinates", "TextureCoordinates")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _refuse(reason: str) -> InvalidInputError:
|
|
35
|
+
"""Make an error that gives the reason and the accepted inputs."""
|
|
36
|
+
from loop_link.adapters import _ACCEPTED_INPUTS
|
|
37
|
+
|
|
38
|
+
return InvalidInputError(f"{reason} {_ACCEPTED_INPUTS}")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _collect(data: Any, where: str) -> dict[str, np.ndarray]: # noqa: ANN401
|
|
42
|
+
"""Copy the arrays of a pyvista data set to a dictionary of numpy arrays.
|
|
43
|
+
|
|
44
|
+
Parameters
|
|
45
|
+
----------
|
|
46
|
+
data : Any
|
|
47
|
+
A pyvista ``point_data`` or ``cell_data`` object.
|
|
48
|
+
where : str
|
|
49
|
+
The name of the data set, used in error text.
|
|
50
|
+
|
|
51
|
+
Returns
|
|
52
|
+
-------
|
|
53
|
+
dict of str to numpy.ndarray
|
|
54
|
+
The 1-D arrays, without the arrays that pyvista adds itself.
|
|
55
|
+
|
|
56
|
+
Raises
|
|
57
|
+
------
|
|
58
|
+
InvalidInputError
|
|
59
|
+
An array is not 1-D.
|
|
60
|
+
"""
|
|
61
|
+
result: dict[str, np.ndarray] = {}
|
|
62
|
+
for name in list(data.keys()):
|
|
63
|
+
if name in _SKIPPED_ARRAYS:
|
|
64
|
+
continue
|
|
65
|
+
array = np.asarray(data[name])
|
|
66
|
+
if array.ndim != 1:
|
|
67
|
+
raise InvalidInputError(
|
|
68
|
+
f"The {where} array '{name}' has {array.ndim} dimensions. "
|
|
69
|
+
"Only 1-D arrays are accepted. Split the array into 1-D arrays."
|
|
70
|
+
)
|
|
71
|
+
result[name] = array
|
|
72
|
+
return result
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _polydata_lines(mesh: Any) -> tuple[np.ndarray, np.ndarray]: # noqa: ANN401
|
|
76
|
+
"""Return the segments of a PolyData and the source line of each segment."""
|
|
77
|
+
from vtkmodules.util.numpy_support import vtk_to_numpy
|
|
78
|
+
|
|
79
|
+
cells = mesh.GetLines()
|
|
80
|
+
offsets = vtk_to_numpy(cells.GetOffsetsArray()).astype(np.int64)
|
|
81
|
+
connectivity = vtk_to_numpy(cells.GetConnectivityArray()).astype(np.int64)
|
|
82
|
+
counts = np.diff(offsets)
|
|
83
|
+
if connectivity.size < 2:
|
|
84
|
+
return np.empty((0, 2), dtype=np.int64), np.empty(0, dtype=np.int64)
|
|
85
|
+
# Each point of a line, except the last one, starts a segment.
|
|
86
|
+
starts = np.ones(connectivity.size - 1, dtype=bool)
|
|
87
|
+
ends = offsets[1:] - 1
|
|
88
|
+
starts[ends[(ends >= 0) & (ends < connectivity.size - 1)]] = False
|
|
89
|
+
first = np.flatnonzero(starts)
|
|
90
|
+
segments = np.column_stack((connectivity[first], connectivity[first + 1]))
|
|
91
|
+
owners = np.repeat(np.arange(counts.size, dtype=np.int64), np.maximum(counts - 1, 0))
|
|
92
|
+
return segments, owners
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _convert_polydata(
|
|
96
|
+
mesh: Any, # noqa: ANN401
|
|
97
|
+
vectors: str | None,
|
|
98
|
+
vectors_kind: str,
|
|
99
|
+
) -> SceneObject:
|
|
100
|
+
"""Convert a PolyData to Lines, Surface, Points or Vectors."""
|
|
101
|
+
if mesh.n_lines > 0:
|
|
102
|
+
if len(mesh.faces) > 0 or mesh.n_strips > 0:
|
|
103
|
+
raise InvalidInputError(
|
|
104
|
+
"The PolyData mixes lines with polygons or strips. "
|
|
105
|
+
"Split the mesh into one mesh for each kind of cell."
|
|
106
|
+
)
|
|
107
|
+
segments, owners = _polydata_lines(mesh)
|
|
108
|
+
# Cell data is ordered: vertices, lines, polygons, strips.
|
|
109
|
+
first = int(mesh.n_verts)
|
|
110
|
+
cell_properties = {
|
|
111
|
+
name: values[first : first + int(mesh.n_lines)][owners]
|
|
112
|
+
for name, values in _collect(mesh.cell_data, "cell").items()
|
|
113
|
+
}
|
|
114
|
+
return Lines(
|
|
115
|
+
vertices=np.asarray(mesh.points),
|
|
116
|
+
segments=segments,
|
|
117
|
+
properties=_collect(mesh.point_data, "point"),
|
|
118
|
+
cell_properties=cell_properties,
|
|
119
|
+
)
|
|
120
|
+
if len(mesh.faces) > 0:
|
|
121
|
+
if mesh.n_verts > 0 or mesh.n_strips > 0:
|
|
122
|
+
raise InvalidInputError(
|
|
123
|
+
"The PolyData mixes polygons with vertices or strips. "
|
|
124
|
+
"Split the mesh into one mesh for each kind of cell."
|
|
125
|
+
)
|
|
126
|
+
if not mesh.is_all_triangles:
|
|
127
|
+
mesh = mesh.triangulate()
|
|
128
|
+
return Surface(
|
|
129
|
+
vertices=np.asarray(mesh.points),
|
|
130
|
+
triangles=np.asarray(mesh.faces).reshape(-1, 4)[:, 1:],
|
|
131
|
+
properties=_collect(mesh.point_data, "point"),
|
|
132
|
+
cell_properties=_collect(mesh.cell_data, "cell"),
|
|
133
|
+
)
|
|
134
|
+
points = np.asarray(mesh.points)
|
|
135
|
+
if vectors is None:
|
|
136
|
+
return Points(vertices=points, properties=_collect(mesh.point_data, "point"))
|
|
137
|
+
if vectors not in mesh.point_data:
|
|
138
|
+
raise InvalidInputError(
|
|
139
|
+
f"The point array '{vectors}' does not exist. Give the name of a point array."
|
|
140
|
+
)
|
|
141
|
+
directions = np.asarray(mesh.point_data[vectors])
|
|
142
|
+
properties = _collect(_Without(mesh.point_data, vectors), "point")
|
|
143
|
+
return Vectors.from_directions(points, directions, kind=vectors_kind, properties=properties)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class _Without:
|
|
147
|
+
"""A read-only view of a pyvista data set that hides one array."""
|
|
148
|
+
|
|
149
|
+
def __init__(self, data: Any, hidden: str) -> None: # noqa: ANN401
|
|
150
|
+
self._data = data
|
|
151
|
+
self._hidden = hidden
|
|
152
|
+
|
|
153
|
+
def keys(self) -> list[str]:
|
|
154
|
+
"""Return the array names without the hidden name."""
|
|
155
|
+
return [name for name in self._data if name != self._hidden]
|
|
156
|
+
|
|
157
|
+
def __getitem__(self, name: str) -> Any: # noqa: ANN401
|
|
158
|
+
return self._data[name]
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _check_direction(mesh: Any) -> None: # noqa: ANN401
|
|
162
|
+
"""Raise an error when an ImageData has a rotation."""
|
|
163
|
+
direction = getattr(mesh, "direction_matrix", None)
|
|
164
|
+
if direction is not None and not np.allclose(np.asarray(direction), np.eye(3)):
|
|
165
|
+
raise InvalidInputError(
|
|
166
|
+
"The image data has a rotation that the viewer cannot show. "
|
|
167
|
+
"Resample the image data to a grid without rotation, or remove the rotation "
|
|
168
|
+
"(set direction_matrix to the identity matrix), then try again."
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _even_step(axis: np.ndarray, label: str) -> float:
|
|
173
|
+
"""Return the step of an axis, or raise an error when the steps are not equal."""
|
|
174
|
+
if len(axis) < 2:
|
|
175
|
+
raise _refuse(f"The {label} axis of the rectilinear grid has less than 2 nodes.")
|
|
176
|
+
step = float(axis[1] - axis[0])
|
|
177
|
+
if not np.allclose(np.diff(axis), step):
|
|
178
|
+
raise _refuse(
|
|
179
|
+
f"The {label} axis of the rectilinear grid has unequal steps. "
|
|
180
|
+
"A BlockModel needs equal steps on each axis."
|
|
181
|
+
)
|
|
182
|
+
return step
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _convert_block(mesh: Any, pv: Any) -> BlockModel: # noqa: ANN401
|
|
186
|
+
"""Convert an ImageData or a RectilinearGrid to a BlockModel."""
|
|
187
|
+
if isinstance(mesh, pv.ImageData):
|
|
188
|
+
_check_direction(mesh)
|
|
189
|
+
origin = np.asarray(mesh.origin, dtype=np.float64)
|
|
190
|
+
sizes = np.asarray(mesh.spacing, dtype=np.float64)
|
|
191
|
+
cells = np.array(mesh.dimensions) - 1
|
|
192
|
+
else:
|
|
193
|
+
axes = [np.asarray(mesh.x), np.asarray(mesh.y), np.asarray(mesh.z)]
|
|
194
|
+
sizes = np.array([_even_step(a, n) for a, n in zip(axes, "xyz")], dtype=np.float64)
|
|
195
|
+
origin = np.array([a[0] for a in axes], dtype=np.float64)
|
|
196
|
+
cells = np.array([len(a) - 1 for a in axes])
|
|
197
|
+
return BlockModel(
|
|
198
|
+
origin=origin,
|
|
199
|
+
cell_sizes=sizes,
|
|
200
|
+
cells=cells,
|
|
201
|
+
properties=_collect(mesh.point_data, "point"),
|
|
202
|
+
cell_properties=_collect(mesh.cell_data, "cell"),
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def from_pyvista(
|
|
207
|
+
mesh: Any, # noqa: ANN401
|
|
208
|
+
*,
|
|
209
|
+
kind: str | None = None,
|
|
210
|
+
vectors: str | None = None,
|
|
211
|
+
vectors_kind: str = "normal",
|
|
212
|
+
) -> SceneObject:
|
|
213
|
+
"""Convert a pyvista mesh or grid to a loop_link scene object.
|
|
214
|
+
|
|
215
|
+
Parameters
|
|
216
|
+
----------
|
|
217
|
+
mesh : pyvista.DataSet
|
|
218
|
+
A ``PolyData``, ``ImageData``, ``RectilinearGrid`` or ``UnstructuredGrid``.
|
|
219
|
+
kind : str, optional
|
|
220
|
+
The name of the scene object type that the caller expects. When it does not
|
|
221
|
+
match the type that the mesh gives, an error is raised.
|
|
222
|
+
vectors : str, optional
|
|
223
|
+
The name of a point array that holds direction vectors. It is used for a
|
|
224
|
+
``PolyData`` of vertices only, and gives ``Vectors``.
|
|
225
|
+
vectors_kind : str, default "normal"
|
|
226
|
+
How to read the vectors: ``"normal"`` or ``"lineation"``.
|
|
227
|
+
|
|
228
|
+
Returns
|
|
229
|
+
-------
|
|
230
|
+
SceneObject
|
|
231
|
+
The converted object. Point data gives ``properties``. Cell data gives
|
|
232
|
+
``cell_properties``. The order of image data is x fastest, and is not changed.
|
|
233
|
+
|
|
234
|
+
Raises
|
|
235
|
+
------
|
|
236
|
+
MissingExtraError
|
|
237
|
+
pyvista is not installed.
|
|
238
|
+
InvalidInputError
|
|
239
|
+
The mesh type is not accepted, ``kind`` does not match, or an array is not 1-D.
|
|
240
|
+
"""
|
|
241
|
+
if _pv is None:
|
|
242
|
+
raise MissingExtraError("pyvista")
|
|
243
|
+
pv = _pv
|
|
244
|
+
if kind == "Drillhole":
|
|
245
|
+
raise InvalidInputError(_DRILLHOLE_TEXT)
|
|
246
|
+
result: SceneObject
|
|
247
|
+
if isinstance(mesh, pv.PolyData):
|
|
248
|
+
result = _convert_polydata(mesh, vectors, vectors_kind)
|
|
249
|
+
elif isinstance(mesh, (pv.ImageData, pv.RectilinearGrid)):
|
|
250
|
+
result = _convert_block(mesh, pv)
|
|
251
|
+
elif isinstance(mesh, pv.UnstructuredGrid):
|
|
252
|
+
types = np.asarray(mesh.celltypes)
|
|
253
|
+
if len(types) == 0 or not np.all(types == pv.CellType.TETRA):
|
|
254
|
+
raise _refuse("An UnstructuredGrid is accepted only when all cells are tetrahedra.")
|
|
255
|
+
result = TetraMesh(
|
|
256
|
+
vertices=np.asarray(mesh.points),
|
|
257
|
+
tetrahedra=np.asarray(mesh.cells_dict[pv.CellType.TETRA]),
|
|
258
|
+
properties=_collect(mesh.point_data, "point"),
|
|
259
|
+
cell_properties=_collect(mesh.cell_data, "cell"),
|
|
260
|
+
)
|
|
261
|
+
else:
|
|
262
|
+
raise _refuse(f"The pyvista type '{type(mesh).__name__}' is not accepted.")
|
|
263
|
+
if kind is not None and kind != type(result).__name__:
|
|
264
|
+
raise _refuse(
|
|
265
|
+
f"The kind '{kind}' does not match the mesh. The mesh gives '{type(result).__name__}'."
|
|
266
|
+
)
|
|
267
|
+
return result
|