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,178 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from . import getLogger
|
|
6
|
+
|
|
7
|
+
logger = getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class EuclideanTransformation:
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
dimensions: int = 2,
|
|
14
|
+
angle: float = 0,
|
|
15
|
+
translation: np.ndarray | None = None,
|
|
16
|
+
fit_rotation: bool = True,
|
|
17
|
+
):
|
|
18
|
+
"""Transforms points into a new coordinate
|
|
19
|
+
system where the main eigenvector is aligned with x
|
|
20
|
+
|
|
21
|
+
Parameters
|
|
22
|
+
----------
|
|
23
|
+
dimensions : int, optional
|
|
24
|
+
Do transformation in map view or on 3d volume, by default 2
|
|
25
|
+
angle : float, optional
|
|
26
|
+
Angle to rotate the points by, by default 0
|
|
27
|
+
translation : np.ndarray, default zeros
|
|
28
|
+
Translation to apply to the points, by default
|
|
29
|
+
"""
|
|
30
|
+
if translation is None:
|
|
31
|
+
translation = np.zeros(3)
|
|
32
|
+
self.translation = translation[:dimensions]
|
|
33
|
+
self.dimensions = dimensions
|
|
34
|
+
self.angle = angle
|
|
35
|
+
self.fit_rotation = fit_rotation
|
|
36
|
+
|
|
37
|
+
def fit(self, points: np.ndarray):
|
|
38
|
+
"""Fit the transformation to a point cloud
|
|
39
|
+
This function will find the main eigenvector of the point cloud
|
|
40
|
+
and rotate the point cloud so that this is aligned with x
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
Parameters
|
|
44
|
+
----------
|
|
45
|
+
points : np.ndarray
|
|
46
|
+
xyz points as as numpy array
|
|
47
|
+
"""
|
|
48
|
+
try:
|
|
49
|
+
from sklearn import decomposition
|
|
50
|
+
except ImportError:
|
|
51
|
+
logger.error("scikit-learn is required for this function")
|
|
52
|
+
return
|
|
53
|
+
points = np.array(points)
|
|
54
|
+
if points.shape[1] < self.dimensions:
|
|
55
|
+
raise ValueError(f"Points must have at least {self.dimensions} dimensions")
|
|
56
|
+
# standardise the points so that centre is 0
|
|
57
|
+
# self.translation = np.zeros(3)
|
|
58
|
+
self.translation = np.mean(points[:, : self.dimensions], axis=0)
|
|
59
|
+
# find main eigenvector and and calculate the angle of this with x
|
|
60
|
+
if self.fit_rotation:
|
|
61
|
+
pca = decomposition.PCA(n_components=self.dimensions).fit(
|
|
62
|
+
points[:, : self.dimensions] - self.translation[None, : self.dimensions]
|
|
63
|
+
)
|
|
64
|
+
coeffs = pca.components_
|
|
65
|
+
self.angle = -np.arccos(np.dot(coeffs[0, :], [1, 0]))
|
|
66
|
+
else:
|
|
67
|
+
self.angle = 0
|
|
68
|
+
return self
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def rotation(self):
|
|
72
|
+
return self._rotation(self.angle)
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def inverse_rotation(self):
|
|
76
|
+
return self._rotation(-self.angle)
|
|
77
|
+
|
|
78
|
+
def _rotation(self, angle):
|
|
79
|
+
return np.array(
|
|
80
|
+
[
|
|
81
|
+
[np.cos(angle), -np.sin(angle), 0],
|
|
82
|
+
[np.sin(angle), np.cos(angle), 0],
|
|
83
|
+
[0, 0, -1],
|
|
84
|
+
]
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
def fit_transform(self, points: np.ndarray) -> np.ndarray:
|
|
88
|
+
"""Fit the transformation and transform the points"""
|
|
89
|
+
|
|
90
|
+
self.fit(points)
|
|
91
|
+
return self.transform(points)
|
|
92
|
+
|
|
93
|
+
def transform(self, points: np.ndarray) -> np.ndarray:
|
|
94
|
+
"""Transform points using the transformation and rotation
|
|
95
|
+
|
|
96
|
+
Parameters
|
|
97
|
+
----------
|
|
98
|
+
points : np.ndarray
|
|
99
|
+
xyz points as as numpy array
|
|
100
|
+
|
|
101
|
+
Returns
|
|
102
|
+
-------
|
|
103
|
+
np.ndarray
|
|
104
|
+
xyz points in the transformed coordinate system
|
|
105
|
+
"""
|
|
106
|
+
points = np.array(points)
|
|
107
|
+
if points.shape[1] < self.dimensions:
|
|
108
|
+
raise ValueError(f"Points must have at least {self.dimensions} dimensions")
|
|
109
|
+
centred = points[:, : self.dimensions] - self.translation[None, :]
|
|
110
|
+
rotated = np.einsum(
|
|
111
|
+
"ik,jk->ij",
|
|
112
|
+
centred,
|
|
113
|
+
self.rotation[: self.dimensions, : self.dimensions],
|
|
114
|
+
)
|
|
115
|
+
transformed_points = np.copy(points)
|
|
116
|
+
transformed_points[:, : self.dimensions] = rotated
|
|
117
|
+
return transformed_points
|
|
118
|
+
|
|
119
|
+
def inverse_transform(self, points: np.ndarray) -> np.ndarray:
|
|
120
|
+
"""
|
|
121
|
+
Transform points back to the original coordinate system
|
|
122
|
+
|
|
123
|
+
Parameters
|
|
124
|
+
----------
|
|
125
|
+
points : np.ndarray
|
|
126
|
+
xyz points as as numpy array
|
|
127
|
+
|
|
128
|
+
Returns
|
|
129
|
+
-------
|
|
130
|
+
np.ndarray
|
|
131
|
+
xyz points in the original coordinate system
|
|
132
|
+
"""
|
|
133
|
+
inversed = (
|
|
134
|
+
np.einsum(
|
|
135
|
+
"ik,jk->ij",
|
|
136
|
+
points[: self.dimensions],
|
|
137
|
+
self.inverse_rotation[: self.dimensions, : self.dimensions],
|
|
138
|
+
)
|
|
139
|
+
+ self.translation
|
|
140
|
+
)
|
|
141
|
+
inversed = (
|
|
142
|
+
np.vstack([inversed, points[self.dimensions :]])
|
|
143
|
+
if points.shape[1] > self.dimensions
|
|
144
|
+
else inversed
|
|
145
|
+
)
|
|
146
|
+
return inversed
|
|
147
|
+
|
|
148
|
+
def __call__(self, points: np.ndarray) -> np.ndarray:
|
|
149
|
+
"""
|
|
150
|
+
Transform points into the transformed space
|
|
151
|
+
|
|
152
|
+
Parameters
|
|
153
|
+
----------
|
|
154
|
+
points : np.ndarray
|
|
155
|
+
xyz points as as numpy array
|
|
156
|
+
|
|
157
|
+
Returns
|
|
158
|
+
-------
|
|
159
|
+
np.ndarray
|
|
160
|
+
xyz points in the transformed coordinate system
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
return self.transform(points)
|
|
164
|
+
|
|
165
|
+
def _repr_html_(self):
|
|
166
|
+
"""
|
|
167
|
+
Provides an HTML representation of the TransRotator.
|
|
168
|
+
"""
|
|
169
|
+
html_str = f"""
|
|
170
|
+
<div class="collapsible">
|
|
171
|
+
<button class="collapsible-button">{self.__class__.__name__}</button>
|
|
172
|
+
<div class="content">
|
|
173
|
+
<p>Translation: {self.translation}</p>
|
|
174
|
+
<p>Rotation Angle: {self.angle} degrees</p>
|
|
175
|
+
</div>
|
|
176
|
+
</div>
|
|
177
|
+
"""
|
|
178
|
+
return html_str
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Finite difference masks
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from ..logging import get_logger
|
|
8
|
+
|
|
9
|
+
logger = get_logger(__name__)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Operator:
|
|
13
|
+
"""
|
|
14
|
+
Finite difference masks for adding constraints for the derivatives and second derivatives
|
|
15
|
+
Operator.Dx_mask gives derivative in x direction
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
z = np.zeros((3, 3))
|
|
19
|
+
Dx_mask = np.array([z, [[0.0, 0.0, 0.0], [-0.5, 0.0, 0.5], [0.0, 0.0, 0.0]], z])
|
|
20
|
+
Dy_mask = Dx_mask.swapaxes(1, 2)
|
|
21
|
+
Dz_mask = Dx_mask.swapaxes(0, 2)
|
|
22
|
+
|
|
23
|
+
Dxx_mask = np.array([z, [[0, 0, 0], [1, -2, 1], [0, 0, 0]], z])
|
|
24
|
+
Dyy_mask = Dxx_mask.swapaxes(1, 2)
|
|
25
|
+
Dzz_mask = Dxx_mask.swapaxes(0, 2)
|
|
26
|
+
|
|
27
|
+
Dxy_mask = np.array([z, [[-0.25, 0, 0.25], [0, 0, 0], [0.25, 0, -0.25]], z]) / np.sqrt(2)
|
|
28
|
+
Dxz_mask = Dxy_mask.swapaxes(0, 1)
|
|
29
|
+
Dyz_mask = Dxy_mask.swapaxes(0, 2)
|
|
30
|
+
|
|
31
|
+
# from https://en.wikipedia.org/wiki/Discrete_Laplace_operator
|
|
32
|
+
Lapacian = np.array(
|
|
33
|
+
[
|
|
34
|
+
[[0, 0, 0], [0, 1, 0], [0, 0, 0]], # first plane
|
|
35
|
+
[[0, 1, 0], [1, -6, 1], [0, 1, 0]], # second plane
|
|
36
|
+
[[0, 0, 0], [0, 1, 0], [0, 0, 0]], # third plane
|
|
37
|
+
]
|
|
38
|
+
)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
from loop_common.base import LoopEntity, NumpyArray
|
|
5
|
+
|
|
6
|
+
from .orientation import Orientation, OrientationType
|
|
7
|
+
from .pointset import PointSet
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class LineSet(LoopEntity):
|
|
11
|
+
"""A set of lines representing geological features like faults or horizons."""
|
|
12
|
+
|
|
13
|
+
vertices: NumpyArray # Shape (N, 3) for N points along the line
|
|
14
|
+
# Indices that mark the START of each new line segment
|
|
15
|
+
offsets: NumpyArray # Shape (M,) - e.g., [0, 5, 12]
|
|
16
|
+
|
|
17
|
+
def to_tangent_vectors(self) -> list[Orientation]:
|
|
18
|
+
"""Compute tangent vectors for each line segment."""
|
|
19
|
+
tangents = []
|
|
20
|
+
for start, end in zip(self.offsets[:-1], self.offsets[1:]):
|
|
21
|
+
# Compute tangent as the difference between consecutive points
|
|
22
|
+
segment_tangents = self.vertices[start + 1 : end] - self.vertices[start : end - 1]
|
|
23
|
+
segment_centres = (self.vertices[start : end - 1] + self.vertices[start + 1 : end]) / 2
|
|
24
|
+
segment_tangents = segment_tangents / np.linalg.norm(
|
|
25
|
+
segment_tangents, axis=1, keepdims=True
|
|
26
|
+
)
|
|
27
|
+
tangents.append(
|
|
28
|
+
Orientation(
|
|
29
|
+
coords=segment_centres,
|
|
30
|
+
vector=segment_tangents,
|
|
31
|
+
magnitude=np.ones(segment_tangents.shape[0]),
|
|
32
|
+
polarity=np.ones(segment_tangents.shape[0]),
|
|
33
|
+
type=OrientationType.TANGENT,
|
|
34
|
+
)
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
return tangents
|
|
38
|
+
|
|
39
|
+
def to_point_set(self) -> PointSet:
|
|
40
|
+
"""Convert LineSet to PointSet by taking the vertices."""
|
|
41
|
+
return PointSet(coords=self.vertices)
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from enum import Enum
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from pydantic import model_validator
|
|
7
|
+
|
|
8
|
+
from loop_common.base import LoopEntity, NumpyArray
|
|
9
|
+
from loop_common.math import dipdipdirection2vector, plungeazimuth2vector, strikedip2vector
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class OrientationType(str, Enum):
|
|
13
|
+
PLANE = "plane"
|
|
14
|
+
LINEATION = "lineation"
|
|
15
|
+
TANGENT = "tangent"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class OrientationObservation(LoopEntity):
|
|
19
|
+
"""Strike/Dip or Dip/DipDirection measurements."""
|
|
20
|
+
|
|
21
|
+
coords: NumpyArray
|
|
22
|
+
vector: NumpyArray # Normal vector to the surface
|
|
23
|
+
magnitude: NumpyArray
|
|
24
|
+
polarity: NumpyArray # 1 for upright, -1 for overturned
|
|
25
|
+
type: OrientationType
|
|
26
|
+
|
|
27
|
+
@model_validator(mode="after")
|
|
28
|
+
def check_dimensions(self):
|
|
29
|
+
if self.coords.shape[-1] != 3:
|
|
30
|
+
raise ValueError("Coords must have shape (N, 3)")
|
|
31
|
+
if self.vector.shape[-1] != 3:
|
|
32
|
+
raise ValueError("Vector must have shape (N, 3)")
|
|
33
|
+
if self.magnitude.shape[0] != self.coords.shape[0]:
|
|
34
|
+
raise ValueError("Magnitude must have same length as coords")
|
|
35
|
+
if self.polarity.shape[0] != self.coords.shape[0]:
|
|
36
|
+
raise ValueError("Polarity must have same length as coords")
|
|
37
|
+
if self.vector.shape[0] != self.coords.shape[0]:
|
|
38
|
+
raise ValueError("Vector must have same length as coords")
|
|
39
|
+
return self
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def from_strike_dip(
|
|
43
|
+
cls,
|
|
44
|
+
coords: np.ndarray,
|
|
45
|
+
strike: np.ndarray,
|
|
46
|
+
dip: np.ndarray,
|
|
47
|
+
polarity: np.ndarray,
|
|
48
|
+
name: str | None = None,
|
|
49
|
+
):
|
|
50
|
+
"""Create an OrientationObservation from strike/dip measurements."""
|
|
51
|
+
# Convert strike/dip to normal vector
|
|
52
|
+
# This is a simplified conversion assuming right-hand rule and that strike is measured clockwise from north
|
|
53
|
+
vector = strikedip2vector(strike, dip)
|
|
54
|
+
magnitude = np.ones_like(strike) # Placeholder for magnitude, could be set to
|
|
55
|
+
|
|
56
|
+
return cls(
|
|
57
|
+
name=name,
|
|
58
|
+
coords=coords,
|
|
59
|
+
vector=vector,
|
|
60
|
+
magnitude=magnitude,
|
|
61
|
+
polarity=polarity,
|
|
62
|
+
type=OrientationType.PLANE,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def from_dip_direction_and_dip(
|
|
67
|
+
cls,
|
|
68
|
+
coords: np.ndarray,
|
|
69
|
+
dip_direction: np.ndarray,
|
|
70
|
+
dip: np.ndarray,
|
|
71
|
+
polarity: np.ndarray | None = None,
|
|
72
|
+
name: str | None = None,
|
|
73
|
+
):
|
|
74
|
+
"""Create an OrientationObservation from dip direction/dip measurements."""
|
|
75
|
+
# Convert dip direction/dip to normal vector
|
|
76
|
+
if not hasattr(dip_direction, 'len'):
|
|
77
|
+
dip_direction = np.ones_like(coords[:, 0]) * dip_direction
|
|
78
|
+
if not hasattr(dip, 'len'):
|
|
79
|
+
dip = np.ones_like(coords[:, 0]) * dip
|
|
80
|
+
vector = dipdipdirection2vector(dip_direction, dip)
|
|
81
|
+
magnitude = np.ones_like(
|
|
82
|
+
dip_direction
|
|
83
|
+
) # Placeholder for magnitude, could be set to something else
|
|
84
|
+
if polarity is None:
|
|
85
|
+
polarity = np.ones_like(dip_direction) # Default to upright if not provided
|
|
86
|
+
return cls(
|
|
87
|
+
name=name,
|
|
88
|
+
coords=coords,
|
|
89
|
+
vector=vector,
|
|
90
|
+
magnitude=magnitude,
|
|
91
|
+
polarity=polarity,
|
|
92
|
+
type=OrientationType.PLANE,
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
@classmethod
|
|
96
|
+
def from_plunge_and_plunge_direction(
|
|
97
|
+
cls,
|
|
98
|
+
coords: np.ndarray,
|
|
99
|
+
plunge_direction: np.ndarray,
|
|
100
|
+
plunge: np.ndarray,
|
|
101
|
+
polarity: np.ndarray,
|
|
102
|
+
name: str | None = None,
|
|
103
|
+
):
|
|
104
|
+
"""Create an OrientationObservation from plunge direction/plunge measurements."""
|
|
105
|
+
# Convert plunge direction/plunge to normal vector
|
|
106
|
+
vector = plungeazimuth2vector(plunge, plunge_direction)
|
|
107
|
+
magnitude = np.ones_like(
|
|
108
|
+
plunge_direction
|
|
109
|
+
) # Placeholder for magnitude, could be set to something else
|
|
110
|
+
|
|
111
|
+
return cls(
|
|
112
|
+
name=name,
|
|
113
|
+
coords=coords,
|
|
114
|
+
vector=vector,
|
|
115
|
+
magnitude=magnitude,
|
|
116
|
+
polarity=polarity,
|
|
117
|
+
type=OrientationType.PLANE,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
# Backwards-compatible alias expected by other modules
|
|
122
|
+
Orientation = OrientationObservation
|
loop_common/observer.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""A generic, thread-safe observer pattern used across Loop packages."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
import threading
|
|
7
|
+
import weakref
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from contextlib import contextmanager
|
|
10
|
+
from typing import Any, Generic, Protocol, TypeVar, runtime_checkable
|
|
11
|
+
|
|
12
|
+
from typing_extensions import Self
|
|
13
|
+
|
|
14
|
+
__all__ = ["Disposable", "Observable", "Observer"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@runtime_checkable
|
|
18
|
+
class Observer(Protocol):
|
|
19
|
+
"""Protocol for objects that can observe events from Observable objects.
|
|
20
|
+
|
|
21
|
+
Classes implementing this protocol must provide an update method that
|
|
22
|
+
will be called when observed events occur.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def update(self, observable: Observable, event: str, *args: Any, **kwargs: Any) -> None:
|
|
26
|
+
"""Receive a notification from an observable object.
|
|
27
|
+
|
|
28
|
+
Parameters
|
|
29
|
+
----------
|
|
30
|
+
observable : Observable
|
|
31
|
+
The observable object that triggered the event
|
|
32
|
+
event : str
|
|
33
|
+
The name of the event that occurred
|
|
34
|
+
*args : Any
|
|
35
|
+
Positional arguments associated with the event
|
|
36
|
+
**kwargs : Any
|
|
37
|
+
Keyword arguments associated with the event
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
Callback = Callable[["Observable", str, Any], None]
|
|
42
|
+
T = TypeVar("T", bound="Observable")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Disposable:
|
|
46
|
+
"""A helper class that manages detachment of observers.
|
|
47
|
+
|
|
48
|
+
This class provides a convenient way to detach observers from observables.
|
|
49
|
+
It can be used as a context manager for temporary subscriptions.
|
|
50
|
+
|
|
51
|
+
Parameters
|
|
52
|
+
----------
|
|
53
|
+
detach : Callable[[], None]
|
|
54
|
+
Function to call when disposing of the observer
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
__slots__ = ("_detach",)
|
|
58
|
+
|
|
59
|
+
def __init__(self, detach: Callable[[], None]):
|
|
60
|
+
self._detach = detach
|
|
61
|
+
|
|
62
|
+
def dispose(self) -> None:
|
|
63
|
+
"""Detach the associated observer immediately."""
|
|
64
|
+
|
|
65
|
+
self._detach()
|
|
66
|
+
|
|
67
|
+
# Allow use as a context‑manager for temporary subscriptions
|
|
68
|
+
def __enter__(self) -> Self:
|
|
69
|
+
return self
|
|
70
|
+
|
|
71
|
+
def __exit__(self, exc_type, exc, tb):
|
|
72
|
+
self.dispose()
|
|
73
|
+
return False # do not swallow exceptions
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Observable(Generic[T]):
|
|
77
|
+
"""Base class that implements the Observer pattern.
|
|
78
|
+
|
|
79
|
+
This class provides the infrastructure for managing observers and
|
|
80
|
+
notifying them of events. Observers can be attached to specific events
|
|
81
|
+
or to all events.
|
|
82
|
+
|
|
83
|
+
Attributes
|
|
84
|
+
----------
|
|
85
|
+
_observers : dict[str, weakref.WeakSet[Callback]]
|
|
86
|
+
Internal storage mapping event names to sets of callbacks
|
|
87
|
+
_any_observers : weakref.WeakSet[Callback]
|
|
88
|
+
Set of callbacks that listen to all events
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
#: Internal storage: mapping *event* → WeakSet[Callback]
|
|
92
|
+
_observers: dict[str, weakref.WeakSet[Callback]]
|
|
93
|
+
_any_observers: weakref.WeakSet[Callback]
|
|
94
|
+
#: Bound-method listeners, kept separately as `weakref.WeakMethod` objects.
|
|
95
|
+
#: A bound method (e.g. ``self.some_method``) is a transient wrapper object -
|
|
96
|
+
#: nothing keeps it alive once the expression that created it finishes, so a
|
|
97
|
+
#: plain `weakref.ref`/`WeakSet` entry for it dies almost immediately. Storing
|
|
98
|
+
#: a strongly-held `WeakMethod` instead correctly tracks the lifetime of the
|
|
99
|
+
#: *owning instance* (`__self__`) rather than the throwaway wrapper.
|
|
100
|
+
_observer_methods: dict[str, set[weakref.WeakMethod]]
|
|
101
|
+
_any_observer_methods: set[weakref.WeakMethod]
|
|
102
|
+
|
|
103
|
+
def __init__(self) -> None:
|
|
104
|
+
self._lock = threading.RLock()
|
|
105
|
+
self._observers = {}
|
|
106
|
+
self._any_observers = weakref.WeakSet()
|
|
107
|
+
self._observer_methods = {}
|
|
108
|
+
self._any_observer_methods = set()
|
|
109
|
+
self._frozen = 0
|
|
110
|
+
self._pending: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = []
|
|
111
|
+
|
|
112
|
+
# ‑‑‑ subscription api --------------------------------------------------
|
|
113
|
+
def attach(self, listener: Observer | Callback, event: str | None = None) -> Disposable:
|
|
114
|
+
"""Register a listener for specific event or all events.
|
|
115
|
+
|
|
116
|
+
Parameters
|
|
117
|
+
----------
|
|
118
|
+
listener : Observer | Callback
|
|
119
|
+
The observer object or callback function to attach
|
|
120
|
+
event : str | None, optional
|
|
121
|
+
The specific event to listen for. If None, listens to all events, by default None
|
|
122
|
+
|
|
123
|
+
Returns
|
|
124
|
+
-------
|
|
125
|
+
Disposable
|
|
126
|
+
A disposable object that can be used to detach the listener
|
|
127
|
+
"""
|
|
128
|
+
callback: Callback = (
|
|
129
|
+
listener.update # type: ignore[attr‑defined]
|
|
130
|
+
if isinstance(listener, Observer) # type: ignore[misc]
|
|
131
|
+
else listener # already a callable
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
with self._lock:
|
|
135
|
+
if inspect.ismethod(callback):
|
|
136
|
+
method_ref = weakref.WeakMethod(callback)
|
|
137
|
+
if event is None:
|
|
138
|
+
self._any_observer_methods.add(method_ref)
|
|
139
|
+
else:
|
|
140
|
+
self._observer_methods.setdefault(event, set()).add(method_ref)
|
|
141
|
+
elif event is None:
|
|
142
|
+
self._any_observers.add(callback)
|
|
143
|
+
else:
|
|
144
|
+
self._observers.setdefault(event, weakref.WeakSet()).add(callback)
|
|
145
|
+
|
|
146
|
+
return Disposable(lambda: self.detach(listener, event))
|
|
147
|
+
|
|
148
|
+
def detach(self, listener: Observer | Callback, event: str | None = None) -> None:
|
|
149
|
+
"""Unregister a previously attached listener.
|
|
150
|
+
|
|
151
|
+
Parameters
|
|
152
|
+
----------
|
|
153
|
+
listener : Observer | Callback
|
|
154
|
+
The observer object or callback function to detach
|
|
155
|
+
event : str | None, optional
|
|
156
|
+
The specific event to stop listening for. If None, detaches from all events, by default None
|
|
157
|
+
"""
|
|
158
|
+
|
|
159
|
+
callback: Callback = (
|
|
160
|
+
listener.update # type: ignore[attr‑defined]
|
|
161
|
+
if isinstance(listener, Observer) # type: ignore[misc]
|
|
162
|
+
else listener
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
with self._lock:
|
|
166
|
+
if inspect.ismethod(callback):
|
|
167
|
+
method_ref = weakref.WeakMethod(callback)
|
|
168
|
+
if event is None:
|
|
169
|
+
self._any_observer_methods.discard(method_ref)
|
|
170
|
+
for s in self._observer_methods.values():
|
|
171
|
+
s.discard(method_ref)
|
|
172
|
+
else:
|
|
173
|
+
self._observer_methods.get(event, set()).discard(method_ref)
|
|
174
|
+
elif event is None:
|
|
175
|
+
self._any_observers.discard(callback)
|
|
176
|
+
for s in self._observers.values():
|
|
177
|
+
s.discard(callback)
|
|
178
|
+
else:
|
|
179
|
+
self._observers.get(event, weakref.WeakSet()).discard(callback)
|
|
180
|
+
|
|
181
|
+
def __getstate__(self):
|
|
182
|
+
"""Prepare object state for pickling by removing unpicklable attributes.
|
|
183
|
+
|
|
184
|
+
Returns
|
|
185
|
+
-------
|
|
186
|
+
dict
|
|
187
|
+
Object state dictionary with thread locks and weak references removed
|
|
188
|
+
"""
|
|
189
|
+
state = self.__dict__.copy()
|
|
190
|
+
state.pop('_lock', None) # RLock cannot be pickled
|
|
191
|
+
state.pop('_observers', None) # WeakSet cannot be pickled
|
|
192
|
+
state.pop('_any_observers', None)
|
|
193
|
+
state.pop('_observer_methods', None) # WeakMethod cannot be pickled
|
|
194
|
+
state.pop('_any_observer_methods', None)
|
|
195
|
+
return state
|
|
196
|
+
|
|
197
|
+
def __setstate__(self, state):
|
|
198
|
+
"""Restore object state after unpickling and reinitialize locks and observers.
|
|
199
|
+
|
|
200
|
+
Parameters
|
|
201
|
+
----------
|
|
202
|
+
state : dict
|
|
203
|
+
The restored object state dictionary
|
|
204
|
+
"""
|
|
205
|
+
self.__dict__.update(state)
|
|
206
|
+
self._lock = threading.RLock()
|
|
207
|
+
self._observers = {}
|
|
208
|
+
self._any_observers = weakref.WeakSet()
|
|
209
|
+
self._observer_methods = {}
|
|
210
|
+
self._any_observer_methods = set()
|
|
211
|
+
self._frozen = 0
|
|
212
|
+
|
|
213
|
+
# ‑‑‑ notification api --------------------------------------------------
|
|
214
|
+
def notify(self, event: str, *args: Any, **kwargs: Any) -> None:
|
|
215
|
+
"""Notify all observers that an event has occurred.
|
|
216
|
+
|
|
217
|
+
Parameters
|
|
218
|
+
----------
|
|
219
|
+
event : str
|
|
220
|
+
The name of the event that occurred
|
|
221
|
+
*args : Any
|
|
222
|
+
Positional arguments to pass to the observers
|
|
223
|
+
**kwargs : Any
|
|
224
|
+
Keyword arguments to pass to the observers
|
|
225
|
+
"""
|
|
226
|
+
|
|
227
|
+
with self._lock:
|
|
228
|
+
if self._frozen:
|
|
229
|
+
# defer until freeze_notifications() exits
|
|
230
|
+
self._pending.append((event, args, kwargs))
|
|
231
|
+
return
|
|
232
|
+
|
|
233
|
+
observers = list(self._any_observers)
|
|
234
|
+
observers.extend(self._observers.get(event, ()))
|
|
235
|
+
method_refs = list(self._any_observer_methods)
|
|
236
|
+
method_refs.extend(self._observer_methods.get(event, ()))
|
|
237
|
+
|
|
238
|
+
# Resolve weak method references to live bound methods, dropping any
|
|
239
|
+
# whose owning instance has since been garbage collected.
|
|
240
|
+
for method_ref in method_refs:
|
|
241
|
+
method = method_ref()
|
|
242
|
+
if method is not None:
|
|
243
|
+
observers.append(method)
|
|
244
|
+
|
|
245
|
+
# Call outside lock — prevent deadlocks if observers trigger other
|
|
246
|
+
# notifications.
|
|
247
|
+
for cb in observers:
|
|
248
|
+
try:
|
|
249
|
+
cb(self, event, *args, **kwargs)
|
|
250
|
+
except Exception: # pragma: no cover
|
|
251
|
+
# Optionally log; never allow an observer error to break flow.
|
|
252
|
+
import logging
|
|
253
|
+
|
|
254
|
+
logging.getLogger(__name__).exception(
|
|
255
|
+
"Unhandled error in observer %s for event %s", cb, event
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
# ‑‑‑ batching ----------------------------------------------------------
|
|
259
|
+
@contextmanager
|
|
260
|
+
def freeze_notifications(self):
|
|
261
|
+
"""Context manager that batches notifications until exit.
|
|
262
|
+
|
|
263
|
+
While in this context, notifications are queued rather than sent
|
|
264
|
+
immediately. When the context exits, all queued notifications are
|
|
265
|
+
sent in order.
|
|
266
|
+
|
|
267
|
+
Yields
|
|
268
|
+
------
|
|
269
|
+
Observable
|
|
270
|
+
Self reference for method chaining
|
|
271
|
+
"""
|
|
272
|
+
|
|
273
|
+
with self._lock:
|
|
274
|
+
self._frozen += 1
|
|
275
|
+
try:
|
|
276
|
+
yield self
|
|
277
|
+
finally:
|
|
278
|
+
with self._lock:
|
|
279
|
+
self._frozen -= 1
|
|
280
|
+
if self._frozen == 0 and self._pending:
|
|
281
|
+
pending = self._pending[:]
|
|
282
|
+
self._pending.clear()
|
|
283
|
+
for event, args, kw in pending: # type: ignore[has‑type]
|
|
284
|
+
self.notify(event, *args, **kw)
|