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/selection.py ADDED
@@ -0,0 +1,215 @@
1
+ """The selection in the viewer: the ``Selection`` value and the ``SelectionWatcher``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ import weakref
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass
9
+ from types import TracebackType
10
+ from typing import TYPE_CHECKING
11
+
12
+ import numpy as np
13
+
14
+ from loop_link.protocol import Frame, ProtocolError
15
+
16
+ if TYPE_CHECKING:
17
+ from loop_link.viewer import Viewer
18
+
19
+ _KIND_FIELDS = {"cells": "cells", "nodes": "vertices"}
20
+
21
+
22
+ def _empty() -> np.ndarray:
23
+ """Return an empty ``uint32`` array."""
24
+ return np.empty(0, dtype=np.uint32)
25
+
26
+
27
+ @dataclass(frozen=True, eq=False)
28
+ class Selection:
29
+ """The cells and vertices that are selected in the viewer.
30
+
31
+ Parameters
32
+ ----------
33
+ object_id : str or None
34
+ The identifier of the selected object. ``None`` when nothing is selected.
35
+ revision : int or None
36
+ The revision of the object when the selection was read.
37
+ cells : numpy.ndarray
38
+ The selected cell indices. A 1-D ``uint32`` array.
39
+ vertices : numpy.ndarray
40
+ The selected vertex indices. A 1-D ``uint32`` array.
41
+ """
42
+
43
+ object_id: str | None
44
+ revision: int | None
45
+ cells: np.ndarray
46
+ vertices: np.ndarray
47
+
48
+ @property
49
+ def empty(self) -> bool:
50
+ """Return True when no cell and no vertex is selected."""
51
+ return self.cells.size == 0 and self.vertices.size == 0
52
+
53
+ def same_as(self, other: Selection) -> bool:
54
+ """Return True when ``other`` selects the same indices of the same object.
55
+
56
+ The order of the indices and the revision are not compared.
57
+
58
+ Parameters
59
+ ----------
60
+ other : Selection
61
+ The selection to compare with.
62
+
63
+ Returns
64
+ -------
65
+ bool
66
+ True when the object ids are equal and the sorted cells and the sorted
67
+ vertices are equal.
68
+ """
69
+ return (
70
+ self.object_id == other.object_id
71
+ and np.array_equal(np.sort(self.cells), np.sort(other.cells))
72
+ and np.array_equal(np.sort(self.vertices), np.sort(other.vertices))
73
+ )
74
+
75
+
76
+ def parse_selection_result(frame: Frame) -> Selection:
77
+ """Return the selection in a ``selection.result`` frame.
78
+
79
+ Parameters
80
+ ----------
81
+ frame : Frame
82
+ The decoded ``selection.result`` frame.
83
+
84
+ Returns
85
+ -------
86
+ Selection
87
+ The selection. The entry kind ``cells`` gives ``cells``. The entry kind
88
+ ``nodes`` gives ``vertices``.
89
+
90
+ Raises
91
+ ------
92
+ ProtocolError
93
+ If an entry has a count but no buffer, a buffer is not ``uint32``, or the
94
+ length of a buffer is not the count.
95
+ """
96
+ header = frame.header
97
+ arrays = {"cells": _empty(), "vertices": _empty()}
98
+ for entry in header.get("entries") or []:
99
+ field = _KIND_FIELDS.get(entry.get("kind"))
100
+ if field is None:
101
+ continue
102
+ count = int(entry.get("count", 0))
103
+ name = entry.get("indices")
104
+ if name is None or name not in frame.buffers:
105
+ if count:
106
+ raise ProtocolError(
107
+ f"The selection entry '{entry.get('kind')}' has a count but no indices."
108
+ )
109
+ continue
110
+ array = frame.buffers[name]
111
+ if array.dtype != np.uint32:
112
+ raise ProtocolError(
113
+ f"The selection indices '{name}' are {array.dtype}. They must be uint32."
114
+ )
115
+ if array.ndim != 1 or array.shape[0] != count:
116
+ raise ProtocolError(
117
+ f"The selection indices '{name}' have shape {array.shape}. "
118
+ f"The entry count is {count}."
119
+ )
120
+ # Copy, so the array is writeable and does not keep the frame bytes in memory.
121
+ arrays[field] = array.copy()
122
+ return Selection(
123
+ header.get("object"), header.get("revision"), arrays["cells"], arrays["vertices"]
124
+ )
125
+
126
+
127
+ class SelectionWatcher:
128
+ """Poll the selection of a viewer and call a function when it changes.
129
+
130
+ Only ``Viewer.watch_selection`` makes a watcher. The thread holds only a weak
131
+ reference to the viewer.
132
+
133
+ Parameters
134
+ ----------
135
+ viewer_ref : weakref.ref
136
+ A weak reference to the viewer.
137
+ callback : callable
138
+ The function to call with the new ``Selection`` at each change.
139
+ interval : float
140
+ The seconds between two polls.
141
+ last : Selection
142
+ The selection that counts as already seen.
143
+ """
144
+
145
+ def __init__(
146
+ self,
147
+ viewer_ref: weakref.ref[Viewer],
148
+ callback: Callable[[Selection], None],
149
+ interval: float,
150
+ last: Selection,
151
+ ) -> None:
152
+ self._viewer_ref = viewer_ref
153
+ self._callback = callback
154
+ self._interval = interval
155
+ self._last = last
156
+ self._stop_event = threading.Event()
157
+ self._error: BaseException | None = None
158
+ self._thread = threading.Thread(
159
+ target=self._run, name="loop-link-selection-poll", daemon=True
160
+ )
161
+
162
+ def start(self) -> None:
163
+ """Start the poll thread."""
164
+ self._thread.start()
165
+
166
+ @property
167
+ def running(self) -> bool:
168
+ """Return True when the poll thread is alive."""
169
+ return self._thread.is_alive()
170
+
171
+ @property
172
+ def error(self) -> BaseException | None:
173
+ """Return the exception that ended the thread, or None."""
174
+ return self._error
175
+
176
+ def stop(self) -> None:
177
+ """Stop the poll thread and wait for it. A second call does no harm."""
178
+ self._stop_event.set()
179
+ if self._thread.is_alive() and self._thread is not threading.current_thread():
180
+ self._thread.join(2 * self._interval + 1)
181
+
182
+ def __enter__(self) -> SelectionWatcher:
183
+ """Return the watcher."""
184
+ return self
185
+
186
+ def __exit__(
187
+ self,
188
+ exc_type: type[BaseException] | None,
189
+ exc: BaseException | None,
190
+ traceback: TracebackType | None,
191
+ ) -> None:
192
+ """Stop the watcher."""
193
+ self.stop()
194
+
195
+ def _run(self) -> None:
196
+ """Poll until stopped, until the viewer is gone, or until an error."""
197
+ while not self._stop_event.wait(self._interval):
198
+ viewer = self._viewer_ref()
199
+ if viewer is None:
200
+ return
201
+ try:
202
+ selection = viewer.selection()
203
+ except Exception as error:
204
+ self._error = error
205
+ return
206
+ finally:
207
+ del viewer
208
+ if selection.same_as(self._last):
209
+ continue
210
+ self._last = selection
211
+ try:
212
+ self._callback(selection)
213
+ except Exception as error:
214
+ self._error = error
215
+ return
@@ -0,0 +1,7 @@
1
+ """Test helpers for loop_link."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .fake_viewer import FakeViewer, StoredObject
6
+
7
+ __all__ = ["FakeViewer", "StoredObject"]