loop-common 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. loop_common/__init__.py +6 -0
  2. loop_common/base.py +98 -0
  3. loop_common/geometry/__init__.py +19 -0
  4. loop_common/geometry/_aabb.py +37 -0
  5. loop_common/geometry/_bounding_box.py +792 -0
  6. loop_common/geometry/_face_table.py +42 -0
  7. loop_common/geometry/_point.py +238 -0
  8. loop_common/geometry/_structured_grid.py +114 -0
  9. loop_common/geometry/_structured_grid_2d.py +146 -0
  10. loop_common/geometry/_structured_grid_3d.py +243 -0
  11. loop_common/geometry/_surface.py +288 -0
  12. loop_common/geometry/_unstructured_mesh.py +208 -0
  13. loop_common/interfaces/__init__.py +0 -0
  14. loop_common/interfaces/representation.py +45 -0
  15. loop_common/io/__init__.py +0 -0
  16. loop_common/logging/__init__.py +14 -0
  17. loop_common/logging/logger.py +123 -0
  18. loop_common/logging/sinks.py +221 -0
  19. loop_common/logging/timing.py +113 -0
  20. loop_common/math/__init__.py +5 -0
  21. loop_common/math/_maths.py +441 -0
  22. loop_common/math/_transformation.py +178 -0
  23. loop_common/math/finite_difference_stencil.py +38 -0
  24. loop_common/observations/__init__.py +3 -0
  25. loop_common/observations/lineset.py +41 -0
  26. loop_common/observations/orientation.py +122 -0
  27. loop_common/observations/pointset.py +8 -0
  28. loop_common/observer.py +284 -0
  29. loop_common/supports/_2d_base_unstructured.py +361 -0
  30. loop_common/supports/_2d_p1_unstructured.py +131 -0
  31. loop_common/supports/_2d_p2_unstructured.py +349 -0
  32. loop_common/supports/_2d_structured_grid.py +545 -0
  33. loop_common/supports/_3d_base_structured.py +546 -0
  34. loop_common/supports/_3d_p2_tetra.py +374 -0
  35. loop_common/supports/_3d_rectilinear_grid.py +315 -0
  36. loop_common/supports/_3d_structured_grid.py +510 -0
  37. loop_common/supports/_3d_structured_tetra.py +764 -0
  38. loop_common/supports/_3d_unstructured_tetra.py +656 -0
  39. loop_common/supports/__init__.py +69 -0
  40. loop_common/supports/_aabb.py +77 -0
  41. loop_common/supports/_base_support.py +118 -0
  42. loop_common/supports/_face_table.py +70 -0
  43. loop_common/supports/_p2_structured_tetra.py +627 -0
  44. loop_common/supports/_support_factory.py +78 -0
  45. loop_common/utils.py +74 -0
  46. loop_common-0.0.1.dist-info/METADATA +35 -0
  47. loop_common-0.0.1.dist-info/RECORD +50 -0
  48. loop_common-0.0.1.dist-info/WHEEL +5 -0
  49. loop_common-0.0.1.dist-info/licenses/LICENSE +21 -0
  50. loop_common-0.0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,113 @@
1
+ """Timing/instrumentation helpers for staged, long-running work.
2
+
3
+ :func:`timed_stage` is the primitive (a context manager); :func:`timed` is
4
+ a thin decorator wrapping it for whole-function timing. Both emit
5
+ structured start/end log records (via the `extra=` mechanism of the
6
+ stdlib `logging` module) carrying `stage`, `event`, `run_id` and, on
7
+ completion, `duration_s` -- fields a `SqliteSink` stores in dedicated
8
+ columns so run history can be queried without parsing message text.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import functools
14
+ import logging
15
+ import time
16
+ import uuid
17
+ from contextlib import contextmanager
18
+ from typing import Callable
19
+
20
+ __all__ = ["timed", "timed_stage"]
21
+
22
+
23
+ @contextmanager
24
+ def timed_stage(
25
+ logger: logging.Logger,
26
+ stage: str,
27
+ *,
28
+ run_id: str | None = None,
29
+ level: int = logging.INFO,
30
+ **extra,
31
+ ):
32
+ """Time a named stage (e.g. "update", "interpolate") and log its duration.
33
+
34
+ Emits a ``event="start"`` record on entry and an ``event="end"`` record
35
+ (with a ``duration_s`` field) on exit -- even if the block raises.
36
+
37
+ Parameters
38
+ ----------
39
+ logger : logging.Logger
40
+ Logger to emit the start/end records on.
41
+ stage : str
42
+ Name of the stage being timed, e.g. "update" or "interpolate".
43
+ run_id : str, optional
44
+ Correlates stages from the same run; generated if omitted.
45
+ level : int, optional
46
+ Logging level for the emitted records, by default `logging.INFO`.
47
+ **extra
48
+ Additional fields attached to both log records.
49
+
50
+ Yields
51
+ ------
52
+ str
53
+ The `run_id` used for this timed block.
54
+ """
55
+ run_id = run_id or uuid.uuid4().hex[:8]
56
+ start = time.perf_counter()
57
+ # stacklevel=3: past this frame and contextlib's generator-CM __enter__,
58
+ # so module/funcName/lineno on the record point at the `with` site.
59
+ logger.log(
60
+ level,
61
+ f"{stage}: started",
62
+ extra={"stage": stage, "event": "start", "run_id": run_id, **extra},
63
+ stacklevel=3,
64
+ )
65
+ try:
66
+ yield run_id
67
+ finally:
68
+ duration_s = time.perf_counter() - start
69
+ logger.log(
70
+ level,
71
+ f"{stage}: finished in {duration_s:.3f}s",
72
+ extra={
73
+ "stage": stage,
74
+ "event": "end",
75
+ "run_id": run_id,
76
+ "duration_s": duration_s,
77
+ **extra,
78
+ },
79
+ stacklevel=3,
80
+ )
81
+
82
+
83
+ def timed(
84
+ stage: str | None = None,
85
+ *,
86
+ logger: logging.Logger | None = None,
87
+ level: int = logging.INFO,
88
+ ):
89
+ """Decorator version of `timed_stage`, timing an entire function call.
90
+
91
+ Parameters
92
+ ----------
93
+ stage : str, optional
94
+ Name of the stage; defaults to the wrapped function's qualified name.
95
+ logger : logging.Logger, optional
96
+ Logger to use; defaults to a stdlib logger named after the
97
+ function's module.
98
+ level : int, optional
99
+ Logging level for the emitted records, by default `logging.INFO`.
100
+ """
101
+
102
+ def decorator(func: Callable) -> Callable:
103
+ stage_name = stage or func.__qualname__
104
+
105
+ @functools.wraps(func)
106
+ def wrapper(*args, **kwargs):
107
+ active_logger = logger or logging.getLogger(func.__module__)
108
+ with timed_stage(active_logger, stage_name):
109
+ return func(*args, **kwargs)
110
+
111
+ return wrapper
112
+
113
+ return decorator
@@ -0,0 +1,5 @@
1
+ import numpy as np
2
+
3
+ from ._maths import *
4
+
5
+ rng = np.random.default_rng()
@@ -0,0 +1,441 @@
1
+ import numbers
2
+
3
+ import numpy as np
4
+ import numpy.typing as npt
5
+
6
+ NumericInput = npt.ArrayLike
7
+
8
+
9
+ def strikedip2vector(strike: NumericInput, dip: NumericInput) -> np.ndarray:
10
+ """Convert strike and dip to a vector
11
+
12
+ Parameters
13
+ ----------
14
+ strike : _type_
15
+ _description_
16
+ dip : _type_
17
+ _description_
18
+
19
+ Returns
20
+ -------
21
+ _type_
22
+ _description_
23
+ """
24
+ if isinstance(strike, numbers.Number):
25
+ strike = np.array([strike])
26
+ else:
27
+ strike = np.array(strike)
28
+ if isinstance(dip, numbers.Number):
29
+ dip = np.array([dip])
30
+ else:
31
+ dip = np.array(dip)
32
+
33
+ vec = np.zeros((len(strike), 3))
34
+ s_r = np.deg2rad(strike)
35
+ d_r = np.deg2rad(dip)
36
+ vec[:, 0] = np.sin(d_r) * np.cos(s_r)
37
+ vec[:, 1] = -np.sin(d_r) * np.sin(s_r)
38
+ vec[:, 2] = np.cos(d_r)
39
+ vec /= np.linalg.norm(vec, axis=1)[:, None]
40
+ return vec
41
+
42
+
43
+ def dipdipdirection2vector(
44
+ dip_direction: NumericInput, dip: NumericInput, degrees: bool = True
45
+ ) -> np.ndarray:
46
+ """Convert dip direction and dip to a vector
47
+
48
+ Parameters
49
+ ----------
50
+ dip_direction : _type_
51
+ _description_
52
+ dip : _type_
53
+ _description_
54
+ degrees : bool, optional
55
+ _description_, by default True
56
+
57
+ Returns
58
+ -------
59
+ _type_
60
+ _description_
61
+ """
62
+ if isinstance(dip_direction, numbers.Number):
63
+ dip_direction = np.array([dip_direction])
64
+ else:
65
+ dip_direction = np.array(dip_direction)
66
+ if isinstance(dip, numbers.Number):
67
+ dip = np.array([dip])
68
+ else:
69
+ dip = np.array(dip)
70
+ if degrees:
71
+ dip_direction = np.deg2rad(dip_direction)
72
+ dip = np.deg2rad(dip)
73
+ vec = np.zeros((len(dip_direction), 3))
74
+ vec[:, 0] = np.sin(dip) * np.sin(dip_direction)
75
+ vec[:, 1] = np.sin(dip) * np.cos(dip_direction)
76
+ vec[:, 2] = np.cos(dip)
77
+ vec /= np.linalg.norm(vec, axis=1)[:, None]
78
+ return vec
79
+
80
+
81
+ def azimuthplunge2vector(
82
+ plunge: NumericInput,
83
+ azimuth: NumericInput,
84
+ degrees: bool = True,
85
+ ) -> np.ndarray:
86
+ raise DeprecationWarning("azimuthplunge2vector is deprecated, use plungeazimuth2vector instead")
87
+
88
+
89
+ def plungeazimuth2vector(
90
+ plunge: NumericInput,
91
+ azimuth: NumericInput,
92
+ degrees: bool = True,
93
+ ) -> np.ndarray:
94
+ """Convert plunge and plunge direction to a vector
95
+
96
+ Parameters
97
+ ----------
98
+ azimuth : Union[np.ndarray, list]
99
+ array or array like of plunge direction values
100
+ plunge : Union[np.ndarray, list]
101
+ array or array like of plunge values
102
+
103
+ Returns
104
+ -------
105
+ np.array
106
+ nx3 vector
107
+ """
108
+ if isinstance(plunge, numbers.Number):
109
+ plunge = np.array([plunge], dtype=float)
110
+ else:
111
+ plunge = np.array(plunge, dtype=float)
112
+ if isinstance(azimuth, numbers.Number):
113
+ azimuth = np.array([azimuth], dtype=float)
114
+ else:
115
+ azimuth = np.array(azimuth, dtype=float)
116
+ if degrees:
117
+ plunge = np.deg2rad(plunge)
118
+ azimuth = np.deg2rad(azimuth)
119
+ vec = np.zeros((len(plunge), 3))
120
+ vec[:, 0] = np.sin(azimuth) * np.cos(plunge)
121
+ vec[:, 1] = np.cos(azimuth) * np.cos(plunge)
122
+ vec[:, 2] = -np.sin(plunge)
123
+ return vec
124
+
125
+
126
+ def normal_vector_to_strike_and_dip(
127
+ normal_vector: NumericInput, degrees: bool = True
128
+ ) -> np.ndarray:
129
+ """Convert from a normal vector to strike and dip
130
+
131
+ Parameters
132
+ ----------
133
+ normal_vector : np.ndarray, list
134
+ array of normal vectors
135
+ degrees : bool, optional
136
+ whether to return in degrees or radians, by default True
137
+ Returns
138
+ -------
139
+ np.ndarray
140
+ 2xn array of strike and dip values
141
+
142
+ Notes
143
+ ------
144
+
145
+ if a 1d array is passed in it is assumed to be a single normal vector
146
+ and cast into a 1x3 array
147
+
148
+ """
149
+ normal_vector = np.array(normal_vector)
150
+ if len(normal_vector.shape) == 1:
151
+ normal_vector = normal_vector[None, :]
152
+ # normalise the normal vector
153
+ normal_vector /= np.linalg.norm(normal_vector, axis=1)[:, None]
154
+ dip = np.arccos(normal_vector[:, 2])
155
+ strike = -np.arctan2(normal_vector[:, 1], normal_vector[:, 0])
156
+ if degrees:
157
+ dip = np.rad2deg(dip)
158
+ strike = np.rad2deg(strike)
159
+
160
+ return np.array([strike, dip]).T
161
+
162
+
163
+ def normal_vector_to_dip_and_dip_direction(
164
+ normal_vector: NumericInput, degrees: bool = True
165
+ ) -> np.ndarray:
166
+ """Convert from a normal vector to dip and dip direction
167
+
168
+ Parameters
169
+ ----------
170
+ normal_vector : np.ndarray, list
171
+ array of normal vectors
172
+ degrees : bool, optional
173
+ whether to return in degrees or radians, by default True
174
+ Returns
175
+ -------
176
+ np.ndarray
177
+ 2xn array of dip direction and dip values
178
+
179
+ Notes
180
+ ------
181
+
182
+ if a 1d array is passed in it is assumed to be a single normal vector
183
+ and cast into a 1x3 array
184
+
185
+ """
186
+ normal_vector = np.array(normal_vector)
187
+ if len(normal_vector.shape) == 1:
188
+ normal_vector = normal_vector[None, :]
189
+ # normalise the normal vector
190
+ normal_vector /= np.linalg.norm(normal_vector, axis=1)[:, None]
191
+ dip = np.arccos(normal_vector[:, 2])
192
+ dip_direction = np.arctan2(normal_vector[:, 0], normal_vector[:, 1])
193
+ if degrees:
194
+ dip = np.rad2deg(dip)
195
+ dip_direction = np.rad2deg(dip_direction)
196
+ dip_direction = (dip_direction + 360) % 360
197
+
198
+ return np.array([dip_direction, dip]).T
199
+
200
+
201
+ def rotation(axis: NumericInput, angle: NumericInput) -> np.ndarray:
202
+ """Create a rotation matrix for an axis and angle
203
+
204
+ Parameters
205
+ ----------
206
+ axis : Union[np.ndarray, list]
207
+ vector defining the axis of rotation
208
+ angle : Union[np.ndarray, list]
209
+ angle to rotate in degrees
210
+
211
+ Returns
212
+ -------
213
+ np.ndarray
214
+ 3x3 rotation matrix
215
+ """
216
+ c = np.cos(np.deg2rad(angle))
217
+ s = np.sin(np.deg2rad(angle))
218
+ C = 1.0 - c
219
+ x = axis[:, 0]
220
+ y = axis[:, 1]
221
+ z = axis[:, 2]
222
+ xs = x * s
223
+ ys = y * s
224
+ zs = z * s
225
+ xC = x * C
226
+ yC = y * C
227
+ zC = z * C
228
+ xyC = x * yC
229
+ yzC = y * zC
230
+ zxC = z * xC
231
+ rotation_mat = np.zeros((axis.shape[0], 3, 3))
232
+ rotation_mat[:, 0, 0] = x * xC + c
233
+ rotation_mat[:, 0, 1] = xyC - zs
234
+ rotation_mat[:, 0, 2] = zxC + ys
235
+
236
+ rotation_mat[:, 1, 0] = xyC + zs
237
+ rotation_mat[:, 1, 1] = y * yC + c
238
+ rotation_mat[:, 1, 2] = yzC - xs
239
+
240
+ rotation_mat[:, 2, 0] = zxC - ys
241
+ rotation_mat[:, 2, 1] = yzC + xs
242
+ rotation_mat[:, 2, 2] = z * zC + c
243
+ return rotation_mat
244
+
245
+
246
+ def rotate(vector: NumericInput, axis: NumericInput, angle: NumericInput) -> np.ndarray:
247
+ """Rotate a vector about an axis
248
+
249
+ Parameters
250
+ ----------
251
+ vector : Union[np.ndarray, list]
252
+ vector to rotate
253
+ alpha : Union[np.ndarray, list]
254
+ axis to rotate about
255
+ beta : Union[np.ndarray, list]
256
+ angle to rotate in degrees
257
+
258
+ Returns
259
+ -------
260
+ np.ndarray
261
+ rotated vector
262
+ """
263
+ return np.einsum("ijk,ik->ij", rotation(axis, angle), vector)
264
+ # rotation_mat = rotation(
265
+ # np.tile(np.array([0, 0, 1])[None, :], (yaw.shape[0], 1)), yaw
266
+ # )
267
+ # vector = np.einsum("ijk,ik->ij", rotation_mat, vector)
268
+ # rotation_mat = rotation(
269
+ # np.tile(np.array([0, 1, 0])[None, :], (pitch.shape[0], 1)), pitch
270
+ # )
271
+ # vector = np.einsum("ijk,ik->ij", rotation_mat, vector)
272
+
273
+ # return vector
274
+
275
+
276
+ def get_vectors(normal: NumericInput) -> tuple[np.ndarray, np.ndarray]:
277
+ """Find strike and dip vectors for a normal vector.
278
+ Makes assumption the strike vector is horizontal component and the dip is vertical.
279
+ Found by calculating strike and and dip angle and then finding the appropriate vectors
280
+
281
+ Parameters
282
+ ----------
283
+ normal : Union[np.ndarray, list]
284
+ input
285
+
286
+ Returns
287
+ -------
288
+ np.ndarray, np.ndarray
289
+ strike vector, dip vector
290
+ """
291
+ length = np.linalg.norm(normal, axis=1)[:, None]
292
+ normal /= length # np.linalg.norm(normal,axis=1)[:,None]
293
+ strikedip = normal_vector_to_strike_and_dip(normal)
294
+ strike_vec = get_strike_vector(strikedip[:, 0])
295
+ strike_vec /= np.linalg.norm(strike_vec, axis=0)[None, :]
296
+ dip_vec = np.cross(strike_vec, normal, axisa=0, axisb=1).T # (strikedip[:, 0], strikedip[:, 1])
297
+ dip_vec /= np.linalg.norm(dip_vec, axis=0)[None, :]
298
+ return strike_vec * length.T, dip_vec * length.T
299
+
300
+
301
+ def get_strike_vector(strike: NumericInput, degrees: bool = True) -> np.ndarray:
302
+ """Return strike direction vector(s) from strike angle(s).
303
+
304
+ Parameters
305
+ ----------
306
+ strike : NumericInput
307
+ Single strike angle or array-like of strike angles, measured clockwise from North.
308
+ degrees : bool, optional
309
+ Whether the input angles are in degrees. If False, angles are assumed to be in radians.
310
+ Default is True.
311
+
312
+ Returns
313
+ -------
314
+ np.ndarray
315
+ Array of shape (3, n) where each column is a 3D unit vector (x, y, z) representing
316
+ the horizontal strike direction. The z-component is always 0.
317
+
318
+ """
319
+ if isinstance(strike, numbers.Number):
320
+ strike = np.array([strike])
321
+ strike = np.array(strike)
322
+ if degrees:
323
+ strike = np.deg2rad(strike)
324
+ v = np.array(
325
+ [
326
+ np.sin(-strike),
327
+ -np.cos(-strike),
328
+ np.zeros(strike.shape[0]),
329
+ ]
330
+ )
331
+
332
+ return v
333
+
334
+
335
+ def get_dip_vector(strike, dip):
336
+ """Return the dip vector based on strike and dip angles.
337
+
338
+ Parameters
339
+ ----------
340
+ strike : float
341
+ Strike angle in degrees, measured clockwise from North.
342
+ dip : float
343
+ Dip angle in degrees, measured from the horizontal plane.
344
+
345
+ Returns
346
+ -------
347
+ np.ndarray
348
+ Unit vector (length 3) representing the dip direction in 3D space.
349
+
350
+ """
351
+ v = np.array(
352
+ [
353
+ -np.cos(np.deg2rad(-strike)) * np.cos(-np.deg2rad(dip)),
354
+ np.sin(np.deg2rad(-strike)) * np.cos(-np.deg2rad(dip)),
355
+ np.sin(-np.deg2rad(dip)),
356
+ ]
357
+ )
358
+ return v
359
+
360
+
361
+ def regular_tetraherdron_for_points(xyz, scale_parameter):
362
+ """Generate regular tetrahedrons centered at given 3D points.
363
+
364
+ Parameters
365
+ ----------
366
+ xyz : np.ndarray
367
+ Array of shape (n, 3) representing the coordinates of n points in 3D space,
368
+ which will serve as the centers of the generated tetrahedrons.
369
+ scale_parameter : float
370
+ Scaling factor controlling the size of the regular tetrahedrons.
371
+
372
+ Returns
373
+ -------
374
+ np.ndarray
375
+ Array of shape (n, 4, 3) representing n regular tetrahedrons, where each
376
+ tetrahedron has 4 vertices in 3D space, positioned relative to the corresponding center point.
377
+
378
+ """
379
+ regular_tetrahedron = np.array(
380
+ [
381
+ [np.sqrt(8 / 9), 0, -1 / 3],
382
+ [-np.sqrt(2 / 9), np.sqrt(2 / 3), -1 / 3],
383
+ [-np.sqrt(2 / 9), -np.sqrt(2 / 3), -1 / 3],
384
+ [0, 0, 1],
385
+ ]
386
+ )
387
+ regular_tetrahedron *= scale_parameter
388
+ tetrahedron = np.zeros((xyz.shape[0], 4, 3))
389
+ tetrahedron[:] = xyz[:, None, :]
390
+ tetrahedron[:, :, :] += regular_tetrahedron[None, :, :]
391
+
392
+ return tetrahedron
393
+
394
+
395
+ def gradient_from_tetrahedron(tetrahedron, value):
396
+ """Compute the gradient of values within tetrahedral elements
397
+
398
+ Parameters
399
+ ----------
400
+ tetrahedron : np.ndarray
401
+ Array of shape (n, 4, 3) representing the coordinates of tetrahedral elements,
402
+ where each tetrahedron is defined by 4 vertices in 3D space.
403
+ value : np.ndarray
404
+ Array of shape (n, 4) representing the scalar values at the 4 vertices
405
+ of each tetrahedron.
406
+
407
+ Returns
408
+ -------
409
+ np.ndarray
410
+ Array of shape (n, 3) representing the gradient vector of the scalar field
411
+ inside each tetrahedral element.
412
+
413
+ """
414
+ tetrahedron = tetrahedron.reshape(-1, 4, 3)
415
+ m = np.array(
416
+ [
417
+ [
418
+ (tetrahedron[:, 1, 0] - tetrahedron[:, 0, 0]),
419
+ (tetrahedron[:, 1, 1] - tetrahedron[:, 0, 1]),
420
+ (tetrahedron[:, 1, 2] - tetrahedron[:, 0, 2]),
421
+ ],
422
+ [
423
+ (tetrahedron[:, 2, 0] - tetrahedron[:, 0, 0]),
424
+ (tetrahedron[:, 2, 1] - tetrahedron[:, 0, 1]),
425
+ (tetrahedron[:, 2, 2] - tetrahedron[:, 0, 2]),
426
+ ],
427
+ [
428
+ (tetrahedron[:, 3, 0] - tetrahedron[:, 0, 0]),
429
+ (tetrahedron[:, 3, 1] - tetrahedron[:, 0, 1]),
430
+ (tetrahedron[:, 3, 2] - tetrahedron[:, 0, 2]),
431
+ ],
432
+ ]
433
+ )
434
+ I = np.array([[-1.0, 1.0, 0.0, 0.0], [-1.0, 0.0, 1.0, 0.0], [-1.0, 0.0, 0.0, 1.0]])
435
+ m = np.swapaxes(m, 0, 2)
436
+ element_gradients = np.linalg.inv(m)
437
+
438
+ element_gradients = element_gradients.swapaxes(1, 2)
439
+ element_gradients = element_gradients @ I
440
+ v = np.sum(element_gradients * value[:, None, :], axis=2)
441
+ return v