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/objects.py ADDED
@@ -0,0 +1,581 @@
1
+ """The object model of loop_link.
2
+
3
+ Each class is a frozen dataclass. A class checks its input in ``__post_init__``
4
+ and stores the arrays as numpy arrays. A check that fails raises
5
+ :class:`loop_link.errors.InvalidInputError` with the name of the field.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping, Sequence
11
+ from dataclasses import dataclass, field
12
+ from typing import Any, Union
13
+
14
+ import numpy as np
15
+
16
+ from loop_link.errors import InvalidInputError
17
+ from loop_link.orientation import directions_to_lineation, normals_to_orientation
18
+
19
+ __all__ = [
20
+ "DEFAULT_CATEGORY_COLOURS",
21
+ "ArrayLike",
22
+ "BlockModel",
23
+ "Categorical",
24
+ "Drillhole",
25
+ "Lines",
26
+ "Points",
27
+ "Property",
28
+ "SceneObject",
29
+ "Surface",
30
+ "TetraMesh",
31
+ "Vectors",
32
+ ]
33
+
34
+ ArrayLike = Union[np.ndarray, Sequence]
35
+
36
+ #: The ten tab10 colours as RGBA, with alpha 255.
37
+ DEFAULT_CATEGORY_COLOURS: tuple[tuple[int, int, int, int], ...] = (
38
+ (31, 119, 180, 255),
39
+ (255, 127, 14, 255),
40
+ (44, 160, 44, 255),
41
+ (214, 39, 40, 255),
42
+ (148, 103, 189, 255),
43
+ (140, 86, 75, 255),
44
+ (227, 119, 194, 255),
45
+ (127, 127, 127, 255),
46
+ (188, 189, 34, 255),
47
+ (23, 190, 207, 255),
48
+ )
49
+
50
+ _MAX_CODES = 2**32
51
+
52
+
53
+ def _vertices(value: object, name: str = "vertices") -> np.ndarray:
54
+ """Return vertices as a finite float64 array with shape (n, 3)."""
55
+ try:
56
+ arr = np.array(value, dtype=np.float64, copy=True)
57
+ except (TypeError, ValueError) as exc:
58
+ raise InvalidInputError(f"The field '{name}' must be numbers. Check the input.") from exc
59
+ if arr.size == 0 and arr.ndim == 1:
60
+ arr = arr.reshape(0, 3)
61
+ if arr.ndim != 2 or arr.shape[1] != 3:
62
+ raise InvalidInputError(f"The field '{name}' must have shape (n, 3). Check the input.")
63
+ if not np.all(np.isfinite(arr)):
64
+ raise InvalidInputError(f"The field '{name}' must be finite numbers. Check the input.")
65
+ return arr
66
+
67
+
68
+ def _vector3(value: object, name: str) -> np.ndarray:
69
+ """Return a finite float64 array with shape (3,)."""
70
+ try:
71
+ arr = np.array(value, dtype=np.float64, copy=True)
72
+ except (TypeError, ValueError) as exc:
73
+ raise InvalidInputError(f"The field '{name}' must be numbers. Check the input.") from exc
74
+ if arr.shape != (3,):
75
+ raise InvalidInputError(f"The field '{name}' must have shape (3,). Check the input.")
76
+ if not np.all(np.isfinite(arr)):
77
+ raise InvalidInputError(f"The field '{name}' must be finite numbers. Check the input.")
78
+ return arr
79
+
80
+
81
+ def _integer_array(value: object, name: str) -> np.ndarray:
82
+ """Return ``value`` as an int64 array.
83
+
84
+ Raises
85
+ ------
86
+ InvalidInputError
87
+ If the values are not integers.
88
+ """
89
+ try:
90
+ arr = np.array(value, copy=True)
91
+ except (TypeError, ValueError) as exc:
92
+ raise InvalidInputError(f"The field '{name}' must be integers. Check the input.") from exc
93
+ if arr.size == 0:
94
+ return arr.astype(np.int64)
95
+ if arr.dtype.kind not in "iu":
96
+ raise InvalidInputError(f"The field '{name}' must be integers. Check the input.")
97
+ return arr.astype(np.int64)
98
+
99
+
100
+ def _index_array(value: object, name: str, width: int, count: int) -> np.ndarray:
101
+ """Return an index array with shape (m, width) and values in [0, count)."""
102
+ arr = _integer_array(value, name)
103
+ if arr.size == 0 and arr.ndim == 1:
104
+ arr = arr.reshape(0, width)
105
+ if arr.ndim != 2 or arr.shape[1] != width:
106
+ raise InvalidInputError(
107
+ f"The field '{name}' must have shape (m, {width}). Check the input."
108
+ )
109
+ if arr.size and (arr.min() < 0 or arr.max() >= count):
110
+ raise InvalidInputError(
111
+ f"The field '{name}' has an index outside the range 0 to {count - 1}. "
112
+ "Check the input."
113
+ )
114
+ return arr
115
+
116
+
117
+ @dataclass(frozen=True, eq=False)
118
+ class Categorical:
119
+ """A property that holds categories.
120
+
121
+ Parameters
122
+ ----------
123
+ codes : array-like of int
124
+ One code for each item. A code is an index into ``names``.
125
+ names : sequence of str
126
+ The name of each category.
127
+ colours : sequence of tuple, optional
128
+ One RGBA colour for each category. A category without a colour uses
129
+ ``DEFAULT_CATEGORY_COLOURS[i % 10]``.
130
+ """
131
+
132
+ codes: ArrayLike
133
+ names: Sequence[str]
134
+ colours: Sequence[tuple[int, int, int, int]] | None = None
135
+
136
+ def __post_init__(self) -> None:
137
+ """Check the input and store it as numpy arrays."""
138
+ codes = _integer_array(self.codes, "codes")
139
+ if codes.ndim != 1:
140
+ raise InvalidInputError("The field 'codes' must be one-dimensional. Check the input.")
141
+ limit = min(len(self.names), _MAX_CODES)
142
+ if codes.size and (codes.min() < 0 or codes.max() >= limit):
143
+ raise InvalidInputError(
144
+ f"The field 'codes' must have values from 0 to {limit - 1}. Check the input."
145
+ )
146
+ colours = self.colours
147
+ if colours is not None:
148
+ try:
149
+ arr = np.array(colours, copy=True)
150
+ except (TypeError, ValueError) as exc:
151
+ raise InvalidInputError(
152
+ "The field 'colours' must be RGBA numbers. Check the input."
153
+ ) from exc
154
+ if arr.shape != (len(self.names), 4) or arr.dtype.kind not in "iu":
155
+ raise InvalidInputError(
156
+ "The field 'colours' must have one RGBA tuple of 4 integers for each name. "
157
+ "Check the input."
158
+ )
159
+ if arr.size and (arr.min() < 0 or arr.max() > 255):
160
+ raise InvalidInputError(
161
+ "The field 'colours' must have values from 0 to 255. Check the input."
162
+ )
163
+ colours = tuple(tuple(int(v) for v in row) for row in arr)
164
+ object.__setattr__(self, "codes", codes)
165
+ object.__setattr__(self, "colours", colours)
166
+
167
+
168
+ Property = Union[np.ndarray, Sequence, Categorical]
169
+
170
+
171
+ def _properties(properties: dict[str, Any] | None, length: int, field_name: str) -> dict[str, Any]:
172
+ """Check a mapping of properties and return a new mapping.
173
+
174
+ Parameters
175
+ ----------
176
+ properties : dict
177
+ Property name to values or :class:`Categorical`.
178
+ length : int
179
+ The required number of values for each property.
180
+ field_name : str
181
+ The name of the field. The name is used in error messages.
182
+
183
+ Returns
184
+ -------
185
+ dict
186
+ The properties as numpy arrays. A :class:`Categorical` stays the same object.
187
+
188
+ Raises
189
+ ------
190
+ InvalidInputError
191
+ If a property is not one-dimensional or has the wrong length.
192
+ """
193
+ if properties is None:
194
+ properties = {}
195
+ if not isinstance(properties, Mapping):
196
+ raise InvalidInputError(f"The field '{field_name}' must be a mapping. Check the input.")
197
+ result: dict[str, Any] = {}
198
+ for key, value in properties.items():
199
+ if isinstance(value, Categorical):
200
+ size = len(value.codes)
201
+ result[key] = value
202
+ else:
203
+ try:
204
+ arr = np.array(value, copy=True)
205
+ except (TypeError, ValueError) as exc:
206
+ raise InvalidInputError(
207
+ f"The property '{key}' in '{field_name}' is not valid. Check the input."
208
+ ) from exc
209
+ if arr.ndim != 1:
210
+ raise InvalidInputError(
211
+ f"The property '{key}' in '{field_name}' must be one-dimensional. "
212
+ "Check the input."
213
+ )
214
+ size = arr.shape[0]
215
+ result[key] = arr
216
+ if size != length:
217
+ raise InvalidInputError(
218
+ f"The property '{key}' in '{field_name}' has {size} values, but {length} "
219
+ "values are needed. Check the input."
220
+ )
221
+ return result
222
+
223
+
224
+ @dataclass(frozen=True, eq=False)
225
+ class Points:
226
+ """A set of points.
227
+
228
+ Parameters
229
+ ----------
230
+ vertices : array-like
231
+ Coordinates with shape (n, 3).
232
+ properties : dict
233
+ Property name to n values or a :class:`Categorical`.
234
+ """
235
+
236
+ vertices: ArrayLike
237
+ properties: dict[str, Property] = field(default_factory=dict)
238
+
239
+ def __post_init__(self) -> None:
240
+ """Check the input and store it as numpy arrays."""
241
+ verts = _vertices(self.vertices)
242
+ object.__setattr__(self, "vertices", verts)
243
+ object.__setattr__(
244
+ self, "properties", _properties(self.properties, len(verts), "properties")
245
+ )
246
+
247
+
248
+ @dataclass(frozen=True, eq=False)
249
+ class Vectors:
250
+ """A set of points with orientation or lineation data.
251
+
252
+ Parameters
253
+ ----------
254
+ vertices : array-like
255
+ Coordinates with shape (n, 3).
256
+ orientation : tuple of array-like, optional
257
+ ``(dip_direction, dip)`` in degrees, n values each.
258
+ lineation : tuple of array-like, optional
259
+ ``(trend, plunge)`` in degrees, n values each.
260
+ properties : dict
261
+ Property name to n values or a :class:`Categorical`.
262
+ """
263
+
264
+ vertices: ArrayLike
265
+ orientation: tuple[ArrayLike, ArrayLike] | None = None
266
+ lineation: tuple[ArrayLike, ArrayLike] | None = None
267
+ properties: dict[str, Property] = field(default_factory=dict)
268
+
269
+ def __post_init__(self) -> None:
270
+ """Check the input and store it as numpy arrays."""
271
+ verts = _vertices(self.vertices)
272
+ object.__setattr__(self, "vertices", verts)
273
+ for name in ("orientation", "lineation"):
274
+ pair = getattr(self, name)
275
+ if pair is None:
276
+ continue
277
+ try:
278
+ first, second = pair
279
+ except (TypeError, ValueError) as exc:
280
+ raise InvalidInputError(
281
+ f"The field '{name}' must be a tuple of two arrays. Check the input."
282
+ ) from exc
283
+ arrays = []
284
+ for part in (first, second):
285
+ try:
286
+ arr = np.array(part, dtype=np.float64, copy=True)
287
+ except (TypeError, ValueError) as exc:
288
+ raise InvalidInputError(
289
+ f"The field '{name}' must be numbers. Check the input."
290
+ ) from exc
291
+ if arr.shape != (len(verts),) or not np.all(np.isfinite(arr)):
292
+ raise InvalidInputError(
293
+ f"The field '{name}' must have {len(verts)} finite values in each array. "
294
+ "Check the input."
295
+ )
296
+ arrays.append(arr)
297
+ object.__setattr__(self, name, (arrays[0], arrays[1]))
298
+ object.__setattr__(
299
+ self, "properties", _properties(self.properties, len(verts), "properties")
300
+ )
301
+
302
+ @classmethod
303
+ def from_directions(
304
+ cls,
305
+ vertices: ArrayLike,
306
+ directions: ArrayLike,
307
+ *,
308
+ kind: str,
309
+ properties: dict[str, Property] | None = None,
310
+ ) -> Vectors:
311
+ """Make vectors from direction vectors.
312
+
313
+ Parameters
314
+ ----------
315
+ vertices : array-like
316
+ Coordinates with shape (n, 3).
317
+ directions : array-like
318
+ Vectors with shape (n, 3). They are plane normals or line directions.
319
+ kind : {"normal", "lineation"}
320
+ The meaning of ``directions``.
321
+ properties : dict, optional
322
+ Property name to n values or a :class:`Categorical`.
323
+
324
+ Returns
325
+ -------
326
+ Vectors
327
+ The vectors with ``orientation`` or ``lineation`` set.
328
+
329
+ Raises
330
+ ------
331
+ InvalidInputError
332
+ If ``kind`` is not "normal" or "lineation".
333
+ """
334
+ props = properties if properties is not None else {}
335
+ if kind == "normal":
336
+ return cls(vertices, orientation=normals_to_orientation(directions), properties=props)
337
+ if kind == "lineation":
338
+ return cls(vertices, lineation=directions_to_lineation(directions), properties=props)
339
+ raise InvalidInputError("The argument 'kind' must be 'normal' or 'lineation'.")
340
+
341
+
342
+ @dataclass(frozen=True, eq=False)
343
+ class Lines:
344
+ """A set of line segments.
345
+
346
+ Parameters
347
+ ----------
348
+ vertices : array-like
349
+ Coordinates with shape (n, 3).
350
+ segments : array-like of int
351
+ Vertex indices with shape (m, 2).
352
+ properties : dict
353
+ Vertex properties, n values each.
354
+ cell_properties : dict
355
+ Segment properties, m values each.
356
+ """
357
+
358
+ vertices: ArrayLike
359
+ segments: ArrayLike
360
+ properties: dict[str, Property] = field(default_factory=dict)
361
+ cell_properties: dict[str, Property] = field(default_factory=dict)
362
+
363
+ def __post_init__(self) -> None:
364
+ """Check the input and store it as numpy arrays."""
365
+ verts = _vertices(self.vertices)
366
+ segs = _index_array(self.segments, "segments", 2, len(verts))
367
+ object.__setattr__(self, "vertices", verts)
368
+ object.__setattr__(self, "segments", segs)
369
+ object.__setattr__(
370
+ self, "properties", _properties(self.properties, len(verts), "properties")
371
+ )
372
+ object.__setattr__(
373
+ self,
374
+ "cell_properties",
375
+ _properties(self.cell_properties, len(segs), "cell_properties"),
376
+ )
377
+
378
+
379
+ @dataclass(frozen=True, eq=False)
380
+ class Surface:
381
+ """A triangle mesh.
382
+
383
+ Parameters
384
+ ----------
385
+ vertices : array-like
386
+ Coordinates with shape (n, 3).
387
+ triangles : array-like of int
388
+ Vertex indices with shape (m, 3).
389
+ properties : dict
390
+ Vertex properties, n values each.
391
+ cell_properties : dict
392
+ Triangle properties, m values each.
393
+ """
394
+
395
+ vertices: ArrayLike
396
+ triangles: ArrayLike
397
+ properties: dict[str, Property] = field(default_factory=dict)
398
+ cell_properties: dict[str, Property] = field(default_factory=dict)
399
+
400
+ def __post_init__(self) -> None:
401
+ """Check the input and store it as numpy arrays."""
402
+ verts = _vertices(self.vertices)
403
+ tris = _index_array(self.triangles, "triangles", 3, len(verts))
404
+ object.__setattr__(self, "vertices", verts)
405
+ object.__setattr__(self, "triangles", tris)
406
+ object.__setattr__(
407
+ self, "properties", _properties(self.properties, len(verts), "properties")
408
+ )
409
+ object.__setattr__(
410
+ self,
411
+ "cell_properties",
412
+ _properties(self.cell_properties, len(tris), "cell_properties"),
413
+ )
414
+
415
+
416
+ @dataclass(frozen=True, eq=False)
417
+ class BlockModel:
418
+ """A regular grid of cells.
419
+
420
+ Node and cell values are in x-fastest order.
421
+
422
+ Parameters
423
+ ----------
424
+ origin : array-like
425
+ The corner of the grid, shape (3,).
426
+ cell_sizes : array-like
427
+ The size of a cell on each axis, shape (3,). All values are above zero.
428
+ cells : array-like of int
429
+ The number of cells on each axis, shape (3,). All values are at least 1.
430
+ properties : dict
431
+ Node properties, (nx+1)*(ny+1)*(nz+1) values each.
432
+ cell_properties : dict
433
+ Cell properties, nx*ny*nz values each.
434
+ """
435
+
436
+ origin: ArrayLike
437
+ cell_sizes: ArrayLike
438
+ cells: ArrayLike
439
+ properties: dict[str, Property] = field(default_factory=dict)
440
+ cell_properties: dict[str, Property] = field(default_factory=dict)
441
+
442
+ def __post_init__(self) -> None:
443
+ """Check the input and store it as numpy arrays."""
444
+ origin = _vector3(self.origin, "origin")
445
+ sizes = _vector3(self.cell_sizes, "cell_sizes")
446
+ if np.any(sizes <= 0):
447
+ raise InvalidInputError("The field 'cell_sizes' must be above zero. Check the input.")
448
+ try:
449
+ raw = np.asarray(self.cells)
450
+ except (TypeError, ValueError) as exc:
451
+ raise InvalidInputError("The field 'cells' must be integers. Check the input.") from exc
452
+ if raw.shape != (3,):
453
+ raise InvalidInputError("The field 'cells' must have shape (3,). Check the input.")
454
+ if raw.dtype.kind == "f":
455
+ if not np.all(np.isfinite(raw)) or np.any(raw != np.round(raw)):
456
+ raise InvalidInputError("The field 'cells' must be integers. Check the input.")
457
+ raw = raw.astype(np.int64)
458
+ cells = _integer_array(raw, "cells")
459
+ if np.any(cells < 1):
460
+ raise InvalidInputError("The field 'cells' must be at least 1. Check the input.")
461
+ nodes = int(np.prod(cells + 1))
462
+ count = int(np.prod(cells))
463
+ object.__setattr__(self, "origin", origin)
464
+ object.__setattr__(self, "cell_sizes", sizes)
465
+ object.__setattr__(self, "cells", cells)
466
+ object.__setattr__(self, "properties", _properties(self.properties, nodes, "properties"))
467
+ object.__setattr__(
468
+ self,
469
+ "cell_properties",
470
+ _properties(self.cell_properties, count, "cell_properties"),
471
+ )
472
+
473
+
474
+ @dataclass(frozen=True, eq=False)
475
+ class TetraMesh:
476
+ """A mesh of tetrahedra.
477
+
478
+ Parameters
479
+ ----------
480
+ vertices : array-like
481
+ Coordinates with shape (n, 3).
482
+ tetrahedra : array-like of int
483
+ Vertex indices with shape (m, 4).
484
+ properties : dict
485
+ Vertex properties, n values each.
486
+ cell_properties : dict
487
+ Tetrahedron properties, m values each.
488
+ """
489
+
490
+ vertices: ArrayLike
491
+ tetrahedra: ArrayLike
492
+ properties: dict[str, Property] = field(default_factory=dict)
493
+ cell_properties: dict[str, Property] = field(default_factory=dict)
494
+
495
+ def __post_init__(self) -> None:
496
+ """Check the input and store it as numpy arrays."""
497
+ verts = _vertices(self.vertices)
498
+ tets = _index_array(self.tetrahedra, "tetrahedra", 4, len(verts))
499
+ object.__setattr__(self, "vertices", verts)
500
+ object.__setattr__(self, "tetrahedra", tets)
501
+ object.__setattr__(
502
+ self, "properties", _properties(self.properties, len(verts), "properties")
503
+ )
504
+ object.__setattr__(
505
+ self,
506
+ "cell_properties",
507
+ _properties(self.cell_properties, len(tets), "cell_properties"),
508
+ )
509
+
510
+
511
+ @dataclass(frozen=True, eq=False)
512
+ class Drillhole:
513
+ """A drillhole with a survey and intervals.
514
+
515
+ Parameters
516
+ ----------
517
+ collar : array-like
518
+ The collar position, shape (3,).
519
+ survey : array-like
520
+ Survey stations with shape (k, 3).
521
+ intervals : array-like
522
+ Interval start and end with shape (j, 2).
523
+ end_of_hole : float, optional
524
+ The depth of the end of the hole.
525
+ properties : dict
526
+ Survey station properties, k values each.
527
+ interval_properties : dict
528
+ Interval properties, j values each.
529
+ """
530
+
531
+ collar: ArrayLike
532
+ survey: ArrayLike
533
+ intervals: ArrayLike
534
+ end_of_hole: float | None = None
535
+ properties: dict[str, Property] = field(default_factory=dict)
536
+ interval_properties: dict[str, Property] = field(default_factory=dict)
537
+
538
+ def __post_init__(self) -> None:
539
+ """Check the input and store it as numpy arrays."""
540
+ collar = _vector3(self.collar, "collar")
541
+ survey = _vertices(self.survey, "survey")
542
+ try:
543
+ intervals = np.array(self.intervals, dtype=np.float64, copy=True)
544
+ except (TypeError, ValueError) as exc:
545
+ raise InvalidInputError(
546
+ "The field 'intervals' must be numbers. Check the input."
547
+ ) from exc
548
+ if intervals.ndim != 2 or intervals.shape[1] != 2:
549
+ raise InvalidInputError(
550
+ "The field 'intervals' must have shape (j, 2). Check the input."
551
+ )
552
+ if not np.all(np.isfinite(intervals)):
553
+ raise InvalidInputError(
554
+ "The field 'intervals' must be finite numbers. Check the input."
555
+ )
556
+ if self.end_of_hole is not None:
557
+ try:
558
+ eoh = float(self.end_of_hole)
559
+ except (TypeError, ValueError) as exc:
560
+ raise InvalidInputError(
561
+ "The field 'end_of_hole' must be a number. Check the input."
562
+ ) from exc
563
+ if not np.isfinite(eoh):
564
+ raise InvalidInputError(
565
+ "The field 'end_of_hole' must be a finite number. Check the input."
566
+ )
567
+ object.__setattr__(self, "end_of_hole", eoh)
568
+ object.__setattr__(self, "collar", collar)
569
+ object.__setattr__(self, "survey", survey)
570
+ object.__setattr__(self, "intervals", intervals)
571
+ object.__setattr__(
572
+ self, "properties", _properties(self.properties, len(survey), "properties")
573
+ )
574
+ object.__setattr__(
575
+ self,
576
+ "interval_properties",
577
+ _properties(self.interval_properties, len(intervals), "interval_properties"),
578
+ )
579
+
580
+
581
+ SceneObject = Union[Points, Vectors, Lines, Surface, BlockModel, TetraMesh, Drillhole]