diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 9f0b8442a..b184889b6 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -221,6 +221,68 @@ jobs: run: | uv run --package map2loop pytest packages/map2loop/tests + loop-link-test: + # Separate job (not part of the packages-test matrix above): packages/loop_link + # is listed in the uv workspace `exclude` list, so `uv sync --package loop-link` + # cannot resolve it as a workspace member. Install it into its own venv with + # uv pip instead. The package needs Python 3.10 or later. + name: loop-link (python ${{ matrix.python-version }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: ${{ fromJSON(vars.BUILD_OS) }} + python-version: ["3.10", "3.11", "3.12"] + # The real-codec test (tests/test_codec_real.py) needs the private geoviewer repository. + # The secret GEOVIEWER_READ_TOKEN gives read access to it. If the secret does not exist + # (for example in a pull request from a fork), the steps for geoviewer do not run and the + # real-codec test skips. All other tests run in both cases. + env: + GEOVIEWER_REPO_TOKEN: ${{ secrets.GEOVIEWER_READ_TOKEN }} + steps: + - uses: actions/checkout@v4 + + - name: Set up uv + uses: astral-sh/setup-uv@v3 + with: + version: "latest" + + - name: Set up Python ${{ matrix.python-version }} + run: uv python install ${{ matrix.python-version }} + + - name: Create virtual environment + run: uv venv --python ${{ matrix.python-version }} .venv-loop-link + + - name: Install package with test extras + run: | + uv pip install --python .venv-loop-link -e "packages/loop_link[tests]" -e packages/loop_common + + - name: Check out geoviewer (for the real-codec test) + if: env.GEOVIEWER_REPO_TOKEN != '' + uses: actions/checkout@v4 + with: + repository: lachlangrose/geoviewer + token: ${{ secrets.GEOVIEWER_READ_TOKEN }} + path: geoviewer-src + ref: b938de0ff522a6cba7b79cf2bb4b3739bb88efc0 + + - name: Set up Rust (geoviewer needs Rust 1.95) + if: env.GEOVIEWER_REPO_TOKEN != '' + uses: dtolnay/rust-toolchain@stable + + - name: Cache the codec validator build + if: env.GEOVIEWER_REPO_TOKEN != '' + uses: actions/cache@v4 + with: + path: packages/loop_link/.codec-validator-build/target + key: codec-validator-${{ runner.os }}-b938de0ff522a6cba7b79cf2bb4b3739bb88efc0 + + - name: pytest + env: + LOOP_LINK_GEOVIEWER_REPO: ${{ env.GEOVIEWER_REPO_TOKEN != '' && format('{0}/geoviewer-src', github.workspace) || '' }} + run: | + uv run --no-project --python .venv-loop-link python -m pytest packages/loop_link/tests + loopstructural-test: name: LoopStructural (python ${{ matrix.python-version }}) needs: [changes, packages-test, map2loop-test] diff --git a/.gitignore b/.gitignore index d2b110435..d3fc9326c 100644 --- a/.gitignore +++ b/.gitignore @@ -149,3 +149,6 @@ packages/loop_interpolation_core/pkg/ packages/loop_interpolation_core/tests_web/node_modules/ packages/loop_interpolation_core/tests_web/test-results/ packages/loop_interpolation_core/tests_web/playwright-report/ + +# Build folder of the optional real-codec test +packages/loop_link/.codec-validator-build/ diff --git a/.release-please-config.json b/.release-please-config.json index 1f1853d88..ba601927a 100644 --- a/.release-please-config.json +++ b/.release-please-config.json @@ -11,6 +11,7 @@ "packages/loop_interpolation", "packages/loop_interpolation_core", "packages/map2loop", + "packages/loop_link", "packages/loopstructural_visualisation" ] }, @@ -40,6 +41,10 @@ "packages/loopstructural_visualisation": { "release-type": "python", "component": "loopstructuralvisualisation" + }, + "packages/loop_link": { + "release-type": "python", + "component": "loop-link" } } } diff --git a/.release-please-manifest.json b/.release-please-manifest.json index d1b350183..f6ca71892 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -4,5 +4,6 @@ "packages/loop_interpolation": "0.2.0", "packages/loop_interpolation_core": "0.1.0", "packages/map2loop": "3.5.1", - "packages/loopstructural_visualisation": "0.2.2" + "packages/loopstructural_visualisation": "0.2.2", + "packages/loop_link": "0.1.0" } diff --git a/ROADMAP.md b/ROADMAP.md index 9e2708e9d..7e664cc07 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -631,6 +631,11 @@ deferred. The notice is in `COMPAT.md`. Phase A-C status notes. Phase D remains the open item for the dedicated discussion. +- [ ] **Stage 7 — `loop_link`: Python link to geoviewer.** New package + `packages/loop_link` (spec `specs/006-loop-link`). It gives Python a way to + send data to geoviewer: send, adapters and the plugin push API. Stage S5 (select, read the selection + and fetch; geoviewer spec 067) is done. Stage S4 (filter and colour) is done. + ## Status log - **2026-07-24:** Stage 0 done in worktree `~/dev/LoopStructural-roadmap` @@ -917,3 +922,7 @@ deferred. The notice is in `COMPAT.md`. - **2026-11-05:** Spec 005 stage S4 implemented: display, export and intrusion classification use stored world locations; rescale and scale deprecated. - **2026-11-05:** Spec 005 stage S5 implemented: resize paths keep the extent, cell-centre guard tests, non-mutating world-correct misfit diagnostics, residual and exclusion report. - **2026-11-06:** Spec 005 complete: stages S1 to S6 implemented; the auxiliary transformation, the R2 displacement validation, the backend matrix and the golden review are done. Gate result: root pytest 2781 passed, 30 skipped (every skip names its dependency in `specs/005-coordinate-frame-correctness/verification.md`). +- **2026-11-06:** Stage 7 started. The spec and the plan for + `packages/loop_link` exist (`specs/006-loop-link`). The package is new. +- **2026-11-07:** Stage 7 stage S5 implemented: tool connection, select, read selection, fetch and round trip in `packages/loop_link`. +- **2026-11-09:** Stage 7 stage S4 implemented: filter and colour calls, colour in `send` and the fake commands endpoint in `packages/loop_link`. diff --git a/packages/loop_link/LICENSE b/packages/loop_link/LICENSE new file mode 100644 index 000000000..3a62ff6af --- /dev/null +++ b/packages/loop_link/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Lachlan Grose + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/loop_link/README.md b/packages/loop_link/README.md new file mode 100644 index 000000000..9a4e5d2a2 --- /dev/null +++ b/packages/loop_link/README.md @@ -0,0 +1,82 @@ +# loop-link + +Send geoscience data from Python to the LoopConnect viewer. + +## Install + +``` +pip install loop-link +``` + +Optional extras: `pyvista`, `loopstructural`, `pandas`. + +## Token + +The package needs a token. It reads the `GEOVIEWER_TOKEN` environment +variable. If this variable is not set, it uses the token that the viewer +saved. + +## Example + +```python +import numpy as np +from loop_link import Viewer, Points + +viewer = Viewer() +xyz = np.random.rand(100, 3) +viewer.connect() +viewer.send(Points(xyz), id="random-points", name="random points") +viewer.close() +``` + +## Select and fetch + +```python +from loop_link import Viewer, BlockModel + +grid = BlockModel((0, 0, 0), (1, 1, 1), (4, 4, 4)) +viewer = Viewer() +viewer.send(grid, id="grid") +viewer.select("grid", cells=[12, 13]) +sel = viewer.selection() +print(sel.object_id, sel.cells) +watcher = viewer.watch_selection(print, interval=0.5) +watcher.stop() +result = viewer.fetch("grid") +print(result.object) +``` + +Select, read and fetch use the tool connection. They work while another program holds the data connection. +A viewer without geoviewer protocol 1.18 gives `MissingFeatureError`. +A fetch of a drillhole keeps the first interval set. It warns about dropped properties. + +## Filter and colour + +```python +from loop_link import BlockModel, ColourSettings, Viewer + +grid = BlockModel((0, 0, 0), (1, 1, 1), (4, 4, 4)) +viewer = Viewer() +viewer.send(grid, id="grid", colour=ColourSettings(array="grade", colour_map="viridis", range=(0.0, 1.0), scale="linear")) +result = viewer.filter_range("grid", "grade", 0.5, 1.0) +print(result.passing, result.total) +viewer.filter_values("grid", "unit", [0, 2], exclude=True) +viewer.filter_remove("grid", "grade") +viewer.set_colour_map("grid", "coolwarm") +print(viewer.colour_map_names()) +``` + +Filter and colour use the tool connection. They work while another program holds the data connection. +The colour map names come from the viewer. A viewer without geoviewer protocol 1.18 gives `MissingFeatureError` for `colour_map_names()`. +A filter call waits for the end of the build by default. `wait=False` does not wait, `cancel` is a `threading.Event`, and `progress` gets the fraction. +The counts need a viewer of protocol 1.20. An older viewer gives a `FilterResult` with no counts. +`state` is `building` when the viewer stopped to wait (the build goes on) and `unbuilt` when the viewer has no counts for the new filters. +A value filter uses the integer ids of the categories. These are the codes of `Categorical`. + +## Test against the real codec + +Some tests give the frames of `loop_link` to the real geoviewer codec. +The geoviewer repository is private, so these tests are optional. +Set `LOOP_LINK_GEOVIEWER_REPO` to a geoviewer checkout and install Rust (`cargo`). +The tests build a small validator program the first time that they run. +Without the variable, or without `cargo`, these tests skip. diff --git a/packages/loop_link/pyproject.toml b/packages/loop_link/pyproject.toml new file mode 100644 index 000000000..75fe8f1ae --- /dev/null +++ b/packages/loop_link/pyproject.toml @@ -0,0 +1,38 @@ +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[project] +name = "loop-link" +description = "Send geoscience data to the LoopConnect viewer" +version = "0.1.0" +requires-python = ">=3.10" +authors = [{ name = "Lachlan Grose", email = "lachlan.grose@monash.edu" }] +readme = "README.md" +license = { text = "MIT" } +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Science/Research", + "Topic :: Scientific/Engineering :: Information Analysis", + "License :: OSI Approved :: MIT License", + "Operating System :: Microsoft :: Windows", + "Operating System :: POSIX", + "Operating System :: MacOS", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", +] +dependencies = ["numpy"] + +[project.optional-dependencies] +pyvista = ["pyvista"] +loopstructural = ["loop-common"] +pandas = ["pandas"] +tests = ["pytest", "pyvista", "loop-common", "pandas"] + +[tool.setuptools.packages.find] +where = ["src"] +include = ["loop_link", "loop_link.*"] + +[tool.pytest.ini_options] +markers = ["slow: tests that take a long time to run"] diff --git a/packages/loop_link/ruff.toml b/packages/loop_link/ruff.toml new file mode 100644 index 000000000..456965361 --- /dev/null +++ b/packages/loop_link/ruff.toml @@ -0,0 +1,2 @@ +extend = "../../pyproject.toml" +target-version = "py310" diff --git a/packages/loop_link/src/loop_link/__init__.py b/packages/loop_link/src/loop_link/__init__.py new file mode 100644 index 000000000..1307318e0 --- /dev/null +++ b/packages/loop_link/src/loop_link/__init__.py @@ -0,0 +1,61 @@ +"""loop-link: send geoscience data to the LoopConnect viewer.""" + +from __future__ import annotations + +from .commands import ColourSettings, FilterResult +from .errors import ( + BusyError, + CancelledError, + InvalidInputError, + LoopLinkError, + MissingExtraError, + MissingFeatureError, + NoViewerError, + ObjectTooLargeError, + Refusal, + StaleRevisionError, + TokenError, + UnsupportedObjectError, + ViewerClosedError, + ViewerRefusedError, +) +from .fetch import FetchResult +from .objects import BlockModel, Categorical, Drillhole, Lines, Points, Surface, TetraMesh, Vectors +from .push import PushResult, push_objects +from .selection import Selection, SelectionWatcher +from .version import __version__ +from .viewer import InventoryEntry, Viewer + +__all__ = [ + "BlockModel", + "BusyError", + "CancelledError", + "Categorical", + "ColourSettings", + "Drillhole", + "FetchResult", + "FilterResult", + "InvalidInputError", + "InventoryEntry", + "Lines", + "LoopLinkError", + "MissingExtraError", + "MissingFeatureError", + "NoViewerError", + "ObjectTooLargeError", + "Points", + "PushResult", + "Refusal", + "Selection", + "SelectionWatcher", + "StaleRevisionError", + "Surface", + "TetraMesh", + "TokenError", + "UnsupportedObjectError", + "Vectors", + "Viewer", + "ViewerClosedError", + "ViewerRefusedError", + "push_objects", +] diff --git a/packages/loop_link/src/loop_link/_websocket.py b/packages/loop_link/src/loop_link/_websocket.py new file mode 100644 index 000000000..888a56c01 --- /dev/null +++ b/packages/loop_link/src/loop_link/_websocket.py @@ -0,0 +1,436 @@ +"""A small WebSocket client for the link to the viewer. + +It uses the standard library only, because some host applications do not ship a +WebSocket package for every platform. It does what the link needs: one +connection with an ``Authorization`` header, binary messages in both +directions, and the control frames (ping, pong, close). It does not do TLS. +""" + +from __future__ import annotations + +import base64 +import hashlib +import os +import socket +import struct +import time + +import numpy as np + +from loop_link.errors import LoopLinkError, NoViewerError, TokenError +from loop_link.protocol import MAX_FRAME_BYTES, MAX_HEADER_BYTES + +_GUID = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + +OP_CONTINUATION = 0x0 +OP_TEXT = 0x1 +OP_BINARY = 0x2 +OP_CLOSE = 0x8 +OP_PING = 0x9 +OP_PONG = 0xA + +# The largest incoming message: one protocol frame, which is a header and a body. +MAX_INCOMING_BYTES: int = MAX_FRAME_BYTES + MAX_HEADER_BYTES +_HANDSHAKE_MAX_BYTES = 16 * 1024 +# Time for the rest of a frame after its first bytes arrived +_FRAME_TIMEOUT = 10.0 +# Time to send one frame. A receive can leave a short timeout on the socket, +# so each send sets this first. +_SEND_TIMEOUT = 60.0 +# The smallest socket timeout: a timeout of zero makes the socket non-blocking. +_MIN_WAIT = 1e-3 +# The size of one chunk for the mask. It must be a multiple of 4. +_MASK_CHUNK_BYTES = 1024 * 1024 + + +class WebSocketError(LoopLinkError): + """The connection failed, or the server broke the protocol.""" + + +class WebSocketClosed(WebSocketError): + """The server closed the connection.""" + + +def _mask(data: bytes | bytearray, key: bytes) -> bytes | bytearray: + """Apply the WebSocket mask to data. + + The function works in chunks, so the peak memory is about two times the + size of the data. + + Parameters + ---------- + data : bytes or bytearray + The bytes to mask or unmask. + key : bytes + The 4-byte mask key. + + Returns + ------- + bytes or bytearray + The data after the XOR with the repeated key. + """ + size = len(data) + if not size: + return data + source = np.frombuffer(data, dtype=np.uint8) + result = bytearray(size) + target = np.frombuffer(result, dtype=np.uint8) + key_array = np.frombuffer(key, dtype=np.uint8) + # The chunk size is a multiple of 4, so the key stays aligned between chunks. + # Make the pattern only as long as the data needs, so small frames stay cheap. + pattern = np.tile(key_array, (min(size, _MASK_CHUNK_BYTES) + 3) // 4) + for start in range(0, size, _MASK_CHUNK_BYTES): + end = min(start + _MASK_CHUNK_BYTES, size) + np.bitwise_xor(source[start:end], pattern[: end - start], out=target[start:end]) + return result + + +class WebSocketClient: + """One client connection. Not thread safe: use it from one thread. + + Parameters + ---------- + sock : socket.socket + A connected socket. Use :meth:`connect` to make a client. + + Attributes + ---------- + closed : bool + True after the connection is closed. + """ + + def __init__(self, sock: socket.socket) -> None: + self._sock = sock + self._buffer = b"" + self._partial = False + self._fragmenting = False + self._fragment_opcode = OP_BINARY + self._fragments = bytearray() + self.closed = False + + @classmethod + def connect( + cls, + host: str, + port: int, + *, + token: str = "", + timeout: float = 5.0, + path: str = "/", + ) -> WebSocketClient: + """Open the connection and do the handshake. + + Parameters + ---------- + host : str + The host name or address of the viewer. + port : int + The TCP port of the viewer. + token : str, optional + The access token. It is sent as ``Authorization: Bearer ``. + timeout : float, optional + The time in seconds to wait for the TCP connection. + path : str, optional + The path of the WebSocket request. + + Returns + ------- + WebSocketClient + The connected client. + + Raises + ------ + NoViewerError + If the TCP connection is refused or times out. + TokenError + If the viewer answers with HTTP 401. + WebSocketError + If the handshake fails for another reason. + """ + try: + sock = socket.create_connection((host, port), timeout=timeout) + except OSError as error: + raise NoViewerError(f"Cannot connect to a viewer at {host}:{port}: {error}") from error + try: + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + client = cls(sock) + client._handshake(host, port, token, path) + except BaseException: + sock.close() + raise + return client + + def _handshake(self, host: str, port: int, token: str, path: str) -> None: + """Send the upgrade request and check the answer. + + Parameters + ---------- + host : str + The host name for the ``Host`` header. + port : int + The port for the ``Host`` header. + token : str + The access token. An empty string sends no ``Authorization`` header. + path : str + The path of the request. + """ + key = base64.b64encode(os.urandom(16)) + lines = [ + f"GET {path} HTTP/1.1", + f"Host: {host}:{port}", + "Upgrade: websocket", + "Connection: Upgrade", + f"Sec-WebSocket-Key: {key.decode()}", + "Sec-WebSocket-Version: 13", + ] + if token: + lines.append(f"Authorization: Bearer {token}") + try: + self._sock.sendall(("\r\n".join(lines) + "\r\n\r\n").encode("ascii")) + data = b"" + while b"\r\n\r\n" not in data: + chunk = self._sock.recv(4096) + if not chunk: + raise WebSocketError("The viewer closed the connection during the handshake.") + data += chunk + if len(data) > _HANDSHAKE_MAX_BYTES: + raise WebSocketError("The handshake answer is too long.") + except OSError as error: + raise WebSocketError(f"The handshake failed: {error}") from error + head, _, rest = data.partition(b"\r\n\r\n") + self._buffer = rest + status_line, *header_lines = head.decode("latin-1").split("\r\n") + parts = status_line.split(" ", 2) + status = parts[1] if len(parts) > 1 else "" + if status == "401": + raise TokenError("The viewer refused the token. Check the token of the link.") + if status != "101": + raise WebSocketError(f"The viewer refused the connection: {status_line}") + headers = {} + for line in header_lines: + name, _, value = line.partition(":") + headers[name.strip().lower()] = value.strip() + expected = base64.b64encode(hashlib.sha1(key + _GUID).digest()).decode() + if headers.get("sec-websocket-accept") != expected: + raise WebSocketError("The server did not answer as a WebSocket server.") + + # -- sending ------------------------------------------------------------ + + def _send_frame(self, opcode: int, payload: bytes) -> None: + """Send one masked frame. + + Parameters + ---------- + opcode : int + The frame opcode. + payload : bytes + The frame body, before masking. + """ + length = len(payload) + head = bytearray([0x80 | opcode]) + if length < 126: + head.append(0x80 | length) + elif length < 1 << 16: + head.append(0x80 | 126) + head += struct.pack(">H", length) + else: + head.append(0x80 | 127) + head += struct.pack(">Q", length) + key = os.urandom(4) + try: + self._sock.settimeout(_SEND_TIMEOUT) + self._sock.sendall(bytes(head) + key) + self._sock.sendall(_mask(payload, key)) + except OSError as error: + # This includes a timeout: part of the frame can be sent, so the stream is broken. + self._abort() + raise WebSocketError(f"Cannot send to the viewer: {error}") from error + + def send_binary(self, data: bytes) -> None: + """Send one binary message. + + Parameters + ---------- + data : bytes + The message body. + + Raises + ------ + WebSocketClosed + If the connection is already closed. + WebSocketError + If the send fails. The connection is then closed. + """ + self._check_open() + self._send_frame(OP_BINARY, data) + + # -- receiving ---------------------------------------------------------- + + def _read_exactly(self, count: int) -> bytes: + """Read an exact number of bytes from the buffer and the socket. + + Parameters + ---------- + count : int + The number of bytes to read. + + Returns + ------- + bytes + The bytes that were read. + """ + while len(self._buffer) < count: + chunk = self._sock.recv(65536) + if not chunk: + self.closed = True + raise WebSocketClosed("The viewer closed the connection.") + self._buffer += chunk + data, self._buffer = self._buffer[:count], self._buffer[count:] + return data + + def _read_frame(self, wait: float | None) -> tuple[bool, int, bytes]: + """Read one frame. + + Parameters + ---------- + wait : float or None + The time to wait for the first bytes of the frame. + + Returns + ------- + tuple of (bool, int, bytes) + The FIN flag, the opcode and the unmasked body. + """ + # The wait applies to the start of a frame only. A frame that started + # is read to the end, so a timeout cannot leave half a frame behind. + self._sock.settimeout(wait) + first, second = self._read_exactly(2) + self._partial = True + self._sock.settimeout(_FRAME_TIMEOUT) + fin, opcode = bool(first & 0x80), first & 0x0F + length = second & 0x7F + if length == 126: + (length,) = struct.unpack(">H", self._read_exactly(2)) + elif length == 127: + (length,) = struct.unpack(">Q", self._read_exactly(8)) + if first & 0x70: + self._abort() + raise WebSocketError("The viewer sent a frame with a reserved bit set.") + if opcode >= OP_CLOSE and length > 125: + self._abort() + raise WebSocketError("The viewer sent a control frame that is too long.") + if length > MAX_INCOMING_BYTES: + self._abort() + raise WebSocketError("The viewer sent a message that is too large.") + key = self._read_exactly(4) if second & 0x80 else None + payload = self._read_exactly(length) + return fin, opcode, _mask(payload, key) if key else payload + + def receive(self, timeout: float) -> bytes | None: + """Return the next binary message. + + Ping frames get a pong. A text message is skipped. A binary message in + parts is joined. + + Parameters + ---------- + timeout : float + The time in seconds to wait for a message to start. + + Returns + ------- + bytes or None + The message body, or None if nothing arrives in ``timeout`` seconds. + The socket stays usable after a timeout. + + Raises + ------ + WebSocketClosed + If the viewer closes the connection or sends a close frame. + WebSocketError + If a message is too large, the stream breaks, or a read fails. + """ + self._check_open() + deadline = time.monotonic() + timeout + try: + while True: + self._partial = False + wait = max(deadline - time.monotonic(), _MIN_WAIT) + fin, opcode, payload = self._read_frame(wait) + if opcode == OP_PING: + self._send_frame(OP_PONG, payload) + elif opcode == OP_PONG: + continue + elif opcode == OP_CLOSE: + self.closed = True + try: + self._send_frame(OP_CLOSE, payload[:2]) + except WebSocketError: + pass + self._close_socket() + raise WebSocketClosed("The viewer closed the connection.") + else: + if opcode == OP_CONTINUATION: + if not self._fragmenting: + self._abort() + raise WebSocketError("The viewer sent an unexpected continuation.") + else: + if self._fragmenting: + self._abort() + raise WebSocketError("The viewer sent a new message too early.") + self._fragment_opcode = opcode + self._fragments = bytearray() + self._fragments += payload + if len(self._fragments) > MAX_INCOMING_BYTES: + self._abort() + raise WebSocketError("The viewer sent a message that is too large.") + self._fragmenting = not fin + if fin: + message = bytes(self._fragments) + self._fragments = bytearray() + if self._fragment_opcode == OP_BINARY: + return message + except (TimeoutError, BlockingIOError) as error: + if not self._partial: + # The state of a message in parts stays: a later call goes on with it. + return None + # The bytes of the frame that were read are gone, so the next read + # would start in the middle of a frame. + self._abort() + raise WebSocketError("The viewer stopped in the middle of a message.") from error + except OSError as error: + self._abort() + raise WebSocketError(f"Cannot read from the viewer: {error}") from error + + def _check_open(self) -> None: + """Raise ``WebSocketClosed`` if the connection is closed.""" + if self.closed: + raise WebSocketClosed("The connection is closed.") + + def _close_socket(self) -> None: + """Close the socket and ignore errors.""" + try: + self._sock.close() + except OSError: + pass + + def _abort(self) -> None: + """Close the socket without a close frame: the stream is broken.""" + self.closed = True + try: + self._sock.close() + except OSError: + pass + + def close(self) -> None: + """Close the connection. It is safe to call it more than one time.""" + if not self.closed: + self.closed = True + try: + self._send_frame(OP_CLOSE, struct.pack(">H", 1000)) + except WebSocketError: + pass + try: + self._sock.close() + except OSError: + pass diff --git a/packages/loop_link/src/loop_link/adapters/__init__.py b/packages/loop_link/src/loop_link/adapters/__init__.py new file mode 100644 index 000000000..6fe8fa706 --- /dev/null +++ b/packages/loop_link/src/loop_link/adapters/__init__.py @@ -0,0 +1,51 @@ +"""Adapters that turn outside objects into loop_link scene objects.""" + +from __future__ import annotations + +from typing import Any, get_args + +from loop_link.errors import InvalidInputError +from loop_link.objects import SceneObject + +_ACCEPTED_INPUTS = ( + "Accepted inputs: loop_link objects (Points, Vectors, Lines, Surface, BlockModel, " + "TetraMesh, Drillhole); pyvista meshes and grids; LoopStructural Surface and " + "StructuredGrid; pandas tables for drillholes " + "(use loop_link.adapters.pandas.drillholes_from_pandas)." +) + + +def convert(obj: Any, **hints: Any) -> SceneObject: # noqa: ANN401 + """Convert an input object to a loop_link scene object. + + Parameters + ---------- + obj : Any + A loop_link object, a pyvista mesh or grid, or a LoopStructural object. + **hints : Any + Options for the pyvista adapter. + + Returns + ------- + SceneObject + ``obj`` itself when it is a scene object, else the converted object. + + Raises + ------ + loop_link.errors.InvalidInputError + The input type is not accepted. + ImportError + The adapter module for the input type is not available. + """ + if isinstance(obj, get_args(SceneObject)): + return obj + package = type(obj).__module__.split(".", 1)[0] + if package == "pyvista": + from loop_link.adapters.pyvista import from_pyvista + + return from_pyvista(obj, **hints) + if package == "loop_common": + from loop_link.adapters.loopstructural import from_loopstructural + + return from_loopstructural(obj) + raise InvalidInputError(_ACCEPTED_INPUTS) diff --git a/packages/loop_link/src/loop_link/adapters/loopstructural.py b/packages/loop_link/src/loop_link/adapters/loopstructural.py new file mode 100644 index 000000000..eedd105e2 --- /dev/null +++ b/packages/loop_link/src/loop_link/adapters/loopstructural.py @@ -0,0 +1,83 @@ +"""Adapter that turns LoopStructural geometry objects into loop_link scene objects.""" + +from __future__ import annotations + +import sys +from typing import Any + +import numpy as np + +from loop_link.errors import InvalidInputError, MissingExtraError +from loop_link.objects import BlockModel, SceneObject, Surface + + +def from_loopstructural(obj: Any) -> SceneObject: # noqa: ANN401 + """Convert a LoopStructural Surface or StructuredGrid to a scene object. + + The coordinates stay in world coordinates. No other transform is applied. + + Parameters + ---------- + obj : Any + A ``loop_common.geometry.Surface`` or ``loop_common.geometry.StructuredGrid``. + + Returns + ------- + SceneObject + A loop_link ``Surface`` for a Surface, or a ``BlockModel`` for a StructuredGrid. + + Raises + ------ + loop_link.errors.InvalidInputError + The input is not a Surface or a StructuredGrid. + loop_link.errors.MissingExtraError + The ``loop_common`` package is not installed. + """ + from loop_link.adapters import _ACCEPTED_INPUTS + + module = sys.modules.get("loop_common.geometry") + if module is None: + try: + import loop_common.geometry as module + except ImportError as error: + raise MissingExtraError("loopstructural") from error + if isinstance(obj, module.Surface): + return Surface( + vertices=obj.vertices, + triangles=obj.triangles, + properties=dict(obj.properties or {}), + cell_properties=dict(obj.cell_properties or {}), + ) + if isinstance(obj, module.StructuredGrid): + return BlockModel( + origin=obj.origin, + cell_sizes=obj.step_vector, + cells=obj.nsteps_cells, + properties=_flatten(obj.properties), + cell_properties=_flatten(obj.cell_properties), + ) + raise InvalidInputError(_ACCEPTED_INPUTS) + + +def _flatten(properties: dict[str, Any] | None) -> dict[str, Any]: + """Return the grid properties as 1-D arrays in x-fastest order. + + ``StructuredGrid.vtk()`` reshapes each property to ``(n, -1)`` with ``order="F"``, + so a property can be a grid of shape ``(nx, ny, nz)`` or have more than one value + for each node, for example a vector of shape ``(n, 3)``. A grid is flattened in + x-fastest order. Each column of a 2-D array becomes one property with the name + ``"_"``. A 2-D array with one column keeps its name. + """ + result: dict[str, Any] = {} + for name, values in (properties or {}).items(): + array = np.asarray(values) + if array.ndim == 3: + array = array.ravel(order="F") + if array.ndim == 2 and array.shape[1] == 1: + array = array[:, 0] + if array.ndim == 2: + for column in range(array.shape[1]): + result[f"{name}_{column}"] = array[:, column] + continue + result[name] = array + return result diff --git a/packages/loop_link/src/loop_link/adapters/pandas.py b/packages/loop_link/src/loop_link/adapters/pandas.py new file mode 100644 index 000000000..69af8d95d --- /dev/null +++ b/packages/loop_link/src/loop_link/adapters/pandas.py @@ -0,0 +1,227 @@ +"""Adapter that builds drillholes from pandas tables.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np + +from loop_link.errors import InvalidInputError, MissingExtraError +from loop_link.objects import Drillhole + +if TYPE_CHECKING: + import pandas as pd + + +def _column_array(values: pd.Series, name: str) -> np.ndarray: + """Convert one table column to a numpy array. + + Parameters + ---------- + values : pandas.Series + The column values. + name : str + The column name. The error text uses it. + + Returns + ------- + numpy.ndarray + A ``U`` array for a string column. Other columns keep their dtype. + + Raises + ------ + InvalidInputError + If the column is an ``object`` column that holds a value that is not a string. + """ + if values.dtype.kind != "f" and values.isna().any(): + raise InvalidInputError( + f"The column '{name}' has missing values. " + "Fill or remove the missing values, then try again." + ) + if str(values.dtype) == "category": + # A category column, for example a lithology log: use the values of the + # categories. A string column then becomes a Categorical in the viewer. + return _column_array(values.astype(values.cat.categories.dtype), name) + if values.dtype.kind in "biuf" and values.dtype != object: + return values.to_numpy() + if values.dtype.kind in "US": + return np.asarray(values.to_numpy(), dtype="U") + if values.dtype == object or str(values.dtype) in ("string", "str"): + if values.dtype == object and values.isna().any(): + raise InvalidInputError( + f"The column '{name}' has missing values. " + "Fill or remove the missing values, then try again." + ) + if pd_infer(values) == "string": + return np.asarray(values.to_numpy(dtype=object), dtype="U") + raise InvalidInputError( + f"The column '{name}' has values that are not all strings. " + "Convert the column to numbers or to strings, then try again." + ) + raise InvalidInputError( + f"The column '{name}' has a type that is not supported. " + "Convert the column to numbers or to strings, then try again." + ) + + +def pd_infer(values: pd.Series) -> str: + """Return the pandas inferred type name of a column.""" + from pandas.api.types import infer_dtype + + return str(infer_dtype(values, skipna=False)) + + +def _require(table: pd.DataFrame, table_name: str, columns: list[str]) -> None: + """Raise if a table does not have all the named columns.""" + for column in columns: + if column not in table.columns: + raise InvalidInputError( + f"The column '{column}' is not in the {table_name} table. " + "Check the column names and try again." + ) + + +def _hole_ids(table: pd.DataFrame, table_name: str, hole_id: str) -> list[str]: + """Return the hole ids of a table as strings. Raise if an id is missing.""" + column = table[hole_id] + if column.isna().any(): + raise InvalidInputError( + f"The {table_name} table has a missing hole id in column '{hole_id}'. " + "Give each row a hole id." + ) + return column.astype(str).tolist() + + +def drillholes_from_pandas( + collar: pd.DataFrame, + survey: pd.DataFrame, + logs: pd.DataFrame | None = None, + *, + hole_id: str = "hole_id", + x: str = "x", + y: str = "y", + z: str = "z", + depth: str = "depth", + azimuth: str = "azimuth", + dip: str = "dip", + from_: str = "from", + to: str = "to", + dip_positive_down: bool = True, +) -> dict[str, Drillhole]: + """Build drillholes from a collar table, a survey table and a log table. + + Parameters + ---------- + collar : pandas.DataFrame + One row for each hole, with the hole id and the x, y and z of the collar. + survey : pandas.DataFrame + Survey stations, with the hole id, depth, azimuth and dip. + logs : pandas.DataFrame, optional + Interval rows, with the hole id, from and to. All other columns become + interval properties. + hole_id : str + Name of the hole id column in all tables. + x, y, z : str + Names of the collar coordinate columns. + depth, azimuth, dip : str + Names of the survey columns. + from_, to : str + Names of the interval columns in ``logs``. + dip_positive_down : bool + If True, a dip that points down is positive. If False, the dip sign is + reversed. + + Returns + ------- + dict of str to Drillhole + One drillhole for each row of ``collar``, in the order of ``collar``. + The keys are the hole ids as strings. + + Raises + ------ + MissingExtraError + If pandas is not installed. + InvalidInputError + If a hole id in ``survey`` or ``logs`` is not in ``collar``, or if a log + column has a type that is not supported. + """ + try: + import pandas as pd # noqa: F401 + except ImportError as exc: + raise MissingExtraError("pandas") from exc + + _require(collar, "collar", [hole_id, x, y, z]) + _require(survey, "survey", [hole_id, depth, azimuth, dip]) + if logs is not None: + _require(logs, "logs", [hole_id, from_, to]) + + ids = _hole_ids(collar, "collar", hole_id) + if len(set(ids)) != len(ids): + seen: set[str] = set() + for name in ids: + if name in seen: + raise InvalidInputError( + f"The hole id '{name}' is in the collar table more than once. " + "Use one collar row for each hole." + ) + seen.add(name) + known = set(ids) + + def _group(table: pd.DataFrame, table_name: str, sort_by: str) -> tuple[pd.DataFrame, dict]: + """Sort a table once and return it with the row positions of each hole.""" + table = table.assign(**{hole_id: _hole_ids(table, table_name, hole_id)}) + table = table.sort_values(sort_by, kind="stable").reset_index(drop=True) + positions = table.groupby(hole_id, sort=False).indices + for name in positions: + if name not in known: + raise InvalidInputError( + f"The hole id '{name}' is not in the collar table. " + "Add the hole to the collar table or remove its rows." + ) + return table, positions + + survey_sorted, survey_pos = _group(survey, "survey", depth) + sign = 1.0 if dip_positive_down else -1.0 + survey_all = np.column_stack( + [ + survey_sorted[depth].to_numpy(dtype=np.float64), + survey_sorted[azimuth].to_numpy(dtype=np.float64), + sign * survey_sorted[dip].to_numpy(dtype=np.float64), + ] + ).reshape(-1, 3) + + log_pos: dict = {} + intervals_all = np.zeros((0, 2), dtype=np.float64) + log_arrays: dict[str, np.ndarray] = {} + if logs is not None: + logs_sorted, log_pos = _group(logs, "logs", from_) + intervals_all = np.column_stack( + [ + logs_sorted[from_].to_numpy(dtype=np.float64), + logs_sorted[to].to_numpy(dtype=np.float64), + ] + ).reshape(-1, 2) + for column in logs_sorted.columns: + if column not in (hole_id, from_, to): + log_arrays[str(column)] = _column_array(logs_sorted[column], str(column)) + + xyz = np.column_stack( + [ + collar[x].to_numpy(dtype=np.float64), + collar[y].to_numpy(dtype=np.float64), + collar[z].to_numpy(dtype=np.float64), + ] + ) + empty = np.zeros(0, dtype=np.intp) + holes: dict[str, Drillhole] = {} + for position, name in enumerate(ids): + rows = survey_pos.get(name, empty) + log_rows = log_pos.get(name, empty) + holes[name] = Drillhole( + collar=xyz[position], + survey=survey_all[rows], + intervals=intervals_all[log_rows], + properties={}, + interval_properties={col: arr[log_rows] for col, arr in log_arrays.items()}, + ) + return holes diff --git a/packages/loop_link/src/loop_link/adapters/pyvista.py b/packages/loop_link/src/loop_link/adapters/pyvista.py new file mode 100644 index 000000000..b47be8e28 --- /dev/null +++ b/packages/loop_link/src/loop_link/adapters/pyvista.py @@ -0,0 +1,267 @@ +"""Adapter that turns pyvista meshes and grids into loop_link scene objects.""" + +from __future__ import annotations + +from typing import Any + +import numpy as np + +from loop_link.errors import InvalidInputError, MissingExtraError +from loop_link.objects import ( + BlockModel, + Lines, + Points, + SceneObject, + Surface, + TetraMesh, + Vectors, +) + +try: + import pyvista as _pv +except ImportError: # pragma: no cover - depends on the environment + _pv = None + +_DRILLHOLE_TEXT = ( + "A pyvista mesh cannot hold a drillhole. Use loop_link.Drillhole or " + "loop_link.adapters.pandas.drillholes_from_pandas." +) + +# Arrays that pyvista adds by itself. The adapter skips them. +_SKIPPED_ARRAYS = ("Normals", "Texture Coordinates", "TextureCoordinates") + + +def _refuse(reason: str) -> InvalidInputError: + """Make an error that gives the reason and the accepted inputs.""" + from loop_link.adapters import _ACCEPTED_INPUTS + + return InvalidInputError(f"{reason} {_ACCEPTED_INPUTS}") + + +def _collect(data: Any, where: str) -> dict[str, np.ndarray]: # noqa: ANN401 + """Copy the arrays of a pyvista data set to a dictionary of numpy arrays. + + Parameters + ---------- + data : Any + A pyvista ``point_data`` or ``cell_data`` object. + where : str + The name of the data set, used in error text. + + Returns + ------- + dict of str to numpy.ndarray + The 1-D arrays, without the arrays that pyvista adds itself. + + Raises + ------ + InvalidInputError + An array is not 1-D. + """ + result: dict[str, np.ndarray] = {} + for name in list(data.keys()): + if name in _SKIPPED_ARRAYS: + continue + array = np.asarray(data[name]) + if array.ndim != 1: + raise InvalidInputError( + f"The {where} array '{name}' has {array.ndim} dimensions. " + "Only 1-D arrays are accepted. Split the array into 1-D arrays." + ) + result[name] = array + return result + + +def _polydata_lines(mesh: Any) -> tuple[np.ndarray, np.ndarray]: # noqa: ANN401 + """Return the segments of a PolyData and the source line of each segment.""" + from vtkmodules.util.numpy_support import vtk_to_numpy + + cells = mesh.GetLines() + offsets = vtk_to_numpy(cells.GetOffsetsArray()).astype(np.int64) + connectivity = vtk_to_numpy(cells.GetConnectivityArray()).astype(np.int64) + counts = np.diff(offsets) + if connectivity.size < 2: + return np.empty((0, 2), dtype=np.int64), np.empty(0, dtype=np.int64) + # Each point of a line, except the last one, starts a segment. + starts = np.ones(connectivity.size - 1, dtype=bool) + ends = offsets[1:] - 1 + starts[ends[(ends >= 0) & (ends < connectivity.size - 1)]] = False + first = np.flatnonzero(starts) + segments = np.column_stack((connectivity[first], connectivity[first + 1])) + owners = np.repeat(np.arange(counts.size, dtype=np.int64), np.maximum(counts - 1, 0)) + return segments, owners + + +def _convert_polydata( + mesh: Any, # noqa: ANN401 + vectors: str | None, + vectors_kind: str, +) -> SceneObject: + """Convert a PolyData to Lines, Surface, Points or Vectors.""" + if mesh.n_lines > 0: + if len(mesh.faces) > 0 or mesh.n_strips > 0: + raise InvalidInputError( + "The PolyData mixes lines with polygons or strips. " + "Split the mesh into one mesh for each kind of cell." + ) + segments, owners = _polydata_lines(mesh) + # Cell data is ordered: vertices, lines, polygons, strips. + first = int(mesh.n_verts) + cell_properties = { + name: values[first : first + int(mesh.n_lines)][owners] + for name, values in _collect(mesh.cell_data, "cell").items() + } + return Lines( + vertices=np.asarray(mesh.points), + segments=segments, + properties=_collect(mesh.point_data, "point"), + cell_properties=cell_properties, + ) + if len(mesh.faces) > 0: + if mesh.n_verts > 0 or mesh.n_strips > 0: + raise InvalidInputError( + "The PolyData mixes polygons with vertices or strips. " + "Split the mesh into one mesh for each kind of cell." + ) + if not mesh.is_all_triangles: + mesh = mesh.triangulate() + return Surface( + vertices=np.asarray(mesh.points), + triangles=np.asarray(mesh.faces).reshape(-1, 4)[:, 1:], + properties=_collect(mesh.point_data, "point"), + cell_properties=_collect(mesh.cell_data, "cell"), + ) + points = np.asarray(mesh.points) + if vectors is None: + return Points(vertices=points, properties=_collect(mesh.point_data, "point")) + if vectors not in mesh.point_data: + raise InvalidInputError( + f"The point array '{vectors}' does not exist. Give the name of a point array." + ) + directions = np.asarray(mesh.point_data[vectors]) + properties = _collect(_Without(mesh.point_data, vectors), "point") + return Vectors.from_directions(points, directions, kind=vectors_kind, properties=properties) + + +class _Without: + """A read-only view of a pyvista data set that hides one array.""" + + def __init__(self, data: Any, hidden: str) -> None: # noqa: ANN401 + self._data = data + self._hidden = hidden + + def keys(self) -> list[str]: + """Return the array names without the hidden name.""" + return [name for name in self._data if name != self._hidden] + + def __getitem__(self, name: str) -> Any: # noqa: ANN401 + return self._data[name] + + +def _check_direction(mesh: Any) -> None: # noqa: ANN401 + """Raise an error when an ImageData has a rotation.""" + direction = getattr(mesh, "direction_matrix", None) + if direction is not None and not np.allclose(np.asarray(direction), np.eye(3)): + raise InvalidInputError( + "The image data has a rotation that the viewer cannot show. " + "Resample the image data to a grid without rotation, or remove the rotation " + "(set direction_matrix to the identity matrix), then try again." + ) + + +def _even_step(axis: np.ndarray, label: str) -> float: + """Return the step of an axis, or raise an error when the steps are not equal.""" + if len(axis) < 2: + raise _refuse(f"The {label} axis of the rectilinear grid has less than 2 nodes.") + step = float(axis[1] - axis[0]) + if not np.allclose(np.diff(axis), step): + raise _refuse( + f"The {label} axis of the rectilinear grid has unequal steps. " + "A BlockModel needs equal steps on each axis." + ) + return step + + +def _convert_block(mesh: Any, pv: Any) -> BlockModel: # noqa: ANN401 + """Convert an ImageData or a RectilinearGrid to a BlockModel.""" + if isinstance(mesh, pv.ImageData): + _check_direction(mesh) + origin = np.asarray(mesh.origin, dtype=np.float64) + sizes = np.asarray(mesh.spacing, dtype=np.float64) + cells = np.array(mesh.dimensions) - 1 + else: + axes = [np.asarray(mesh.x), np.asarray(mesh.y), np.asarray(mesh.z)] + sizes = np.array([_even_step(a, n) for a, n in zip(axes, "xyz")], dtype=np.float64) + origin = np.array([a[0] for a in axes], dtype=np.float64) + cells = np.array([len(a) - 1 for a in axes]) + return BlockModel( + origin=origin, + cell_sizes=sizes, + cells=cells, + properties=_collect(mesh.point_data, "point"), + cell_properties=_collect(mesh.cell_data, "cell"), + ) + + +def from_pyvista( + mesh: Any, # noqa: ANN401 + *, + kind: str | None = None, + vectors: str | None = None, + vectors_kind: str = "normal", +) -> SceneObject: + """Convert a pyvista mesh or grid to a loop_link scene object. + + Parameters + ---------- + mesh : pyvista.DataSet + A ``PolyData``, ``ImageData``, ``RectilinearGrid`` or ``UnstructuredGrid``. + kind : str, optional + The name of the scene object type that the caller expects. When it does not + match the type that the mesh gives, an error is raised. + vectors : str, optional + The name of a point array that holds direction vectors. It is used for a + ``PolyData`` of vertices only, and gives ``Vectors``. + vectors_kind : str, default "normal" + How to read the vectors: ``"normal"`` or ``"lineation"``. + + Returns + ------- + SceneObject + The converted object. Point data gives ``properties``. Cell data gives + ``cell_properties``. The order of image data is x fastest, and is not changed. + + Raises + ------ + MissingExtraError + pyvista is not installed. + InvalidInputError + The mesh type is not accepted, ``kind`` does not match, or an array is not 1-D. + """ + if _pv is None: + raise MissingExtraError("pyvista") + pv = _pv + if kind == "Drillhole": + raise InvalidInputError(_DRILLHOLE_TEXT) + result: SceneObject + if isinstance(mesh, pv.PolyData): + result = _convert_polydata(mesh, vectors, vectors_kind) + elif isinstance(mesh, (pv.ImageData, pv.RectilinearGrid)): + result = _convert_block(mesh, pv) + elif isinstance(mesh, pv.UnstructuredGrid): + types = np.asarray(mesh.celltypes) + if len(types) == 0 or not np.all(types == pv.CellType.TETRA): + raise _refuse("An UnstructuredGrid is accepted only when all cells are tetrahedra.") + result = TetraMesh( + vertices=np.asarray(mesh.points), + tetrahedra=np.asarray(mesh.cells_dict[pv.CellType.TETRA]), + properties=_collect(mesh.point_data, "point"), + cell_properties=_collect(mesh.cell_data, "cell"), + ) + else: + raise _refuse(f"The pyvista type '{type(mesh).__name__}' is not accepted.") + if kind is not None and kind != type(result).__name__: + raise _refuse( + f"The kind '{kind}' does not match the mesh. The mesh gives '{type(result).__name__}'." + ) + return result diff --git a/packages/loop_link/src/loop_link/commands.py b/packages/loop_link/src/loop_link/commands.py new file mode 100644 index 000000000..d61cd19db --- /dev/null +++ b/packages/loop_link/src/loop_link/commands.py @@ -0,0 +1,418 @@ +"""Filter and colour commands: input checks, colour settings, results and requests.""" + +from __future__ import annotations + +import math +import numbers +import threading +from collections.abc import Callable, Iterable, Mapping, Sequence +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +from loop_link import encode +from loop_link.errors import InvalidInputError +from loop_link.protocol import Frame, ProtocolError + +if TYPE_CHECKING: + from loop_link.tool import ToolConnection + +__all__ = [ + "ColourSettings", + "FilterResult", + "check_codes", + "check_number", + "check_rgb", + "check_text", + "format_number", + "list_colour_map_names", + "parse_colour_map_names", + "raise_for_command_result", + "run_command", +] + +_FEATURE = "filter and colour commands (geoviewer protocol 1.11)" +_SCALES = ("linear", "log") +_CODE_MAX = 2**32 - 1 + + +def format_number(value: numbers.Real) -> str: + """Return the text of a number, as the ``repr`` of its float value. + + Parameters + ---------- + value : number + The number to format. + + Returns + ------- + str + The text of the float value. + """ + return repr(float(value)) + + +def check_number(value: object, name: str) -> float: + """Check that a value is a finite number and return it as a float. + + Parameters + ---------- + value : number + The value to check. ``bool``, NaN and infinity are not valid. + name : str + The name of the argument, for the error message. + + Returns + ------- + float + The value as a float. + + Raises + ------ + loop_link.errors.InvalidInputError + The value is not a finite number. + """ + if ( + isinstance(value, (bool, str)) + or not isinstance(value, numbers.Real) + or not math.isfinite(float(value)) + ): + raise InvalidInputError(f"'{name}' must be a finite number. Got {value!r}.") + return float(value) + + +def check_text(value: object, name: str) -> str: + """Check that a value is a text that is not empty. + + Parameters + ---------- + value : str + The value to check. + name : str + The name of the argument, for the error message. + + Returns + ------- + str + The text. + + Raises + ------ + loop_link.errors.InvalidInputError + The value is not a ``str`` or it is empty. + """ + if not isinstance(value, str) or not value: + raise InvalidInputError(f"'{name}' must be a text that is not empty. Got {value!r}.") + return value + + +def _check_int(value: object, name: str, low: int, high: int) -> int: + """Return a value as an ``int`` when it is an integer in a range.""" + if isinstance(value, bool) or not isinstance(value, numbers.Integral): + raise InvalidInputError(f"'{name}' must contain only integers. Got {value!r}.") + number = int(value) + if not low <= number <= high: + raise InvalidInputError(f"'{name}' must contain only integers from {low} to {high}.") + return number + + +def check_rgb(value: object, name: str) -> tuple[int, int, int]: + """Check that a value is three integers from 0 to 255. + + Parameters + ---------- + value : sequence of int + The value to check. + name : str + The name of the argument, for the error message. + + Returns + ------- + tuple of int + The red, green and blue values. + + Raises + ------ + loop_link.errors.InvalidInputError + The value is not three integers from 0 to 255. + """ + if isinstance(value, (str, bytes)) or not isinstance(value, Sequence) or len(value) != 3: + raise InvalidInputError(f"'{name}' must be three integers from 0 to 255. Got {value!r}.") + red, green, blue = (_check_int(item, name, 0, 255) for item in value) + return (red, green, blue) + + +def check_codes(values: Iterable[Any], name: str) -> list[int]: + """Check that each value is an integer code from 0 to 2**32-1. + + Parameters + ---------- + values : iterable of int + The codes to check. A numpy array is valid. + name : str + The name of the argument, for the error message. + + Returns + ------- + list of int + The codes as Python integers. + + Raises + ------ + loop_link.errors.InvalidInputError + The value is not iterable or one code is not valid. + """ + if isinstance(values, (str, bytes)): + raise InvalidInputError(f"'{name}' must be a list of integer codes. Got {values!r}.") + try: + items = list(values) + except TypeError as error: + raise InvalidInputError(f"'{name}' must be a list of integer codes.") from error + return [_check_int(item, name, 0, _CODE_MAX) for item in items] + + +@dataclass(frozen=True) +class ColourSettings: + """The colour settings of one object. A value of ``None`` means no change. + + Parameters + ---------- + array : str, optional + The name of the array to colour by. + colour_map : str, optional + The name of the colour map. + range : tuple of float, optional + The low and high limit of the colour range. The low limit is less than the high limit. + scale : str, optional + The colour scale, ``"linear"`` or ``"log"``. + plain : tuple of int, optional + The plain colour as red, green and blue values from 0 to 255. + + Raises + ------ + loop_link.errors.InvalidInputError + A value is not valid. The message names the field. + """ + + array: str | None = None + colour_map: str | None = None + range: tuple[float, float] | None = None + scale: str | None = None + plain: tuple[int, int, int] | None = None + + def __post_init__(self) -> None: + """Check the values and store them in their final form.""" + if self.array is not None: + check_text(self.array, "array") + if self.colour_map is not None: + check_text(self.colour_map, "colour_map") + if self.range is not None: + limits = self.range + if isinstance(limits, (str, bytes)) or not isinstance(limits, Sequence): + raise InvalidInputError(f"'range' must be two numbers. Got {limits!r}.") + if len(limits) != 2: + raise InvalidInputError(f"'range' must be two numbers. Got {limits!r}.") + low = check_number(limits[0], "range") + high = check_number(limits[1], "range") + if not low < high: + raise InvalidInputError("'range' must have a low limit less than the high limit.") + object.__setattr__(self, "range", (low, high)) + if self.scale is not None and self.scale not in _SCALES: + raise InvalidInputError(f"'scale' must be 'linear' or 'log'. Got {self.scale!r}.") + if self.plain is not None: + object.__setattr__(self, "plain", check_rgb(self.plain, "plain")) + + +def _count(result: Mapping[str, Any], key: str) -> int | None: + """Return a count of a result, or ``None`` when it is absent.""" + value = result.get(key) + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise ProtocolError(f"The viewer sent a filter result '{key}' that is not valid.") + return value + + +@dataclass(frozen=True) +class FilterResult: + """The result of a filter call. A field is ``None`` when the viewer gives no value. + + Parameters + ---------- + passing : int, optional + The number of elements that pass the filters. + total : int, optional + The number of elements of the object. + state : str, optional + ``"unbuilt"`` when the viewer did not build the filters, or ``"building"`` when + the viewer stopped to wait and the build goes on. + """ + + passing: int | None = None + total: int | None = None + state: str | None = None + + @classmethod + def from_result(cls, result: Mapping[str, Any]) -> FilterResult: + """Read a ``command.result`` body of ``filter.edit``. + + Parameters + ---------- + result : mapping + The ``result`` body, with the status ``done``. + + Returns + ------- + FilterResult + The counts and the state of the body. + + Raises + ------ + loop_link.protocol.ProtocolError + A count is not a whole number of 0 or more, or the state is not a text. + """ + state = result.get("state") + if state is not None and not isinstance(state, str): + raise ProtocolError("The viewer sent a filter result 'state' that is not a text.") + return cls(_count(result, "passing"), _count(result, "total"), state) + + +def raise_for_command_result(result: Mapping[str, Any], *, command: str) -> None: + """Raise an error when a ``command.result`` body is not ``done``. + + Parameters + ---------- + result : mapping + The ``result`` body of the frame. + command : str + The name of the command, for the error message. + + Raises + ------ + loop_link.errors.InvalidInputError + The status is ``refused``. + loop_link.protocol.ProtocolError + The status is not known. + """ + status = result.get("status") + if status == "done": + return + if status == "refused": + raise InvalidInputError( + f"The viewer refused the command '{command}': {result.get('text', '')}" + ) + raise ProtocolError(f"The viewer sent an unknown result status '{status}'.") + + +def parse_colour_map_names(frame: Frame) -> tuple[str, ...] | None: + """Read the colour map names from a ``commands`` frame. + + Parameters + ---------- + frame : loop_link.protocol.Frame + The ``commands`` frame of the viewer. + + Returns + ------- + tuple of str or None + The names, or ``None`` when the frame has no ``colour.set_map`` entry or the entry + has no list of names. + + Raises + ------ + loop_link.protocol.ProtocolError + The list of names is not a list of ``str``. + """ + entries = frame.header.get("commands") + if not isinstance(entries, list): + return None + for entry in entries: + if not isinstance(entry, Mapping) or entry.get("name") != "colour.set_map": + continue + schema = entry.get("input_schema") + properties = schema.get("properties") if isinstance(schema, Mapping) else None + name = properties.get("name") if isinstance(properties, Mapping) else None + if not isinstance(name, Mapping) or "enum" not in name: + return None + names = name["enum"] + if not isinstance(names, list) or not all(isinstance(item, str) for item in names): + raise ProtocolError("The viewer sent colour map names that are not a list of text.") + return tuple(names) + return None + + +def run_command( + tool: ToolConnection, + command: str, + input: Mapping[str, Any], + *, + object_id: str | None = None, + cancel: threading.Event | None = None, + timeout: float | None = None, + progress: Callable[[float], None] | None = None, +) -> Mapping[str, Any]: + """Send one command and return its result. + + Parameters + ---------- + tool : loop_link.tool.ToolConnection + The tool connection. + command : str + The name of the command. + input : mapping + The input of the command. + object_id : str, optional + The identifier of the object that the command is about, for error messages. + cancel : threading.Event, optional + When it is set, the request is cancelled. + timeout : float, optional + The time in seconds to wait for the next frame. + progress : callable, optional + Called with the fraction of each ``command.progress`` frame. + + Returns + ------- + mapping + The ``result`` body, with the status ``done``. + + Raises + ------ + loop_link.errors.InvalidInputError + The viewer refused the command. + loop_link.protocol.ProtocolError + The result is not a mapping with a ``str`` status, or the status is not known. + """ + frame = tool.request( + lambda number: encode.command_frame(number, command, input), + until=("command.result",), + feature=_FEATURE, + object_id=object_id, + progress=progress, + cancel=cancel, + timeout=timeout, + ) + result = frame.header.get("result") + if not isinstance(result, Mapping) or not isinstance(result.get("status"), str): + raise ProtocolError("The viewer sent a command result that is not valid.") + raise_for_command_result(result, command=command) + return result + + +def list_colour_map_names(tool: ToolConnection) -> tuple[str, ...] | None: + """Ask the viewer for the names of its colour maps. + + Parameters + ---------- + tool : loop_link.tool.ToolConnection + The tool connection. + + Returns + ------- + tuple of str or None + The names, or ``None`` when the viewer gives no list. + """ + frame = tool.request( + lambda number: encode.commands_list_frame(number), + until=("commands",), + feature=_FEATURE, + ) + return parse_colour_map_names(frame) diff --git a/packages/loop_link/src/loop_link/discovery.py b/packages/loop_link/src/loop_link/discovery.py new file mode 100644 index 000000000..46515d06c --- /dev/null +++ b/packages/loop_link/src/loop_link/discovery.py @@ -0,0 +1,170 @@ +"""Find a running viewer and the token to talk to it. + +The functions here only read settings files and test a socket. They never +start a program. +""" + +from __future__ import annotations + +import json +import math +import os +import socket +import sys +from dataclasses import dataclass +from pathlib import Path + +from loop_link.errors import NoViewerError, TokenError + +DEFAULT_PORT: int = 47615 + +_TOKEN_TEXT = "Set GEOVIEWER_TOKEN, or save a token in the link popup of the viewer." +_NO_VIEWER_TEXT = ( + "No viewer found. Start geoviewer and turn the link on. " "This library never starts a viewer." +) + + +@dataclass(frozen=True) +class ViewerAddress: + """The address and token of a viewer. + + Parameters + ---------- + host : str + The host name or IP address of the viewer. + port : int + The TCP port of the viewer. + token : str + The access token of the viewer. + """ + + host: str + port: int + token: str + + +def settings_dir() -> Path: + r"""Return the folder where the viewer keeps its settings. + + Returns + ------- + pathlib.Path + ``%APPDATA%\\geoviewer`` on Windows, else ``~/.geoviewer``. + """ + if sys.platform == "win32": + appdata = os.environ.get("APPDATA") + base = Path(appdata) if appdata else Path.home() / "AppData" / "Roaming" + return base / "geoviewer" + return Path.home() / ".geoviewer" + + +def _read_json(path: Path) -> object: + # Return the parsed JSON, or None if the file is missing or damaged. + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + + +def _file_token(settings: Path) -> str: + data = _read_json(settings / "link.json") + if isinstance(data, dict): + token = data.get("token") + if isinstance(token, str): + return token + return "" + + +def _resolve_token(token: str | None, settings: Path) -> str: + if token: + return token + env_token = os.environ.get("GEOVIEWER_TOKEN") + if env_token: + return env_token + file_token = _file_token(settings) + if file_token: + return file_token + raise TokenError(_TOKEN_TEXT) + + +def _is_alive(host: str, port: int, timeout: float) -> bool: + try: + sock = socket.create_connection((host, port), timeout) + except OSError: + return False + sock.close() + return True + + +def _find_port(settings: Path, host: str, timeout: float) -> int: + live: list[tuple[tuple[bool, int], int]] = [] + folder = settings / "instances" + try: + files = sorted(folder.glob("*.json")) + except OSError: + files = [] + for path in files: + data = _read_json(path) + if not isinstance(data, dict): + continue + port = data.get("port") + kind = data.get("kind") + focused = data.get("focused", 0) + if isinstance(focused, bool) or not isinstance(focused, (int, float)): + focused = 0 + if not math.isfinite(focused): + focused = 0 + if not isinstance(port, int) or isinstance(port, bool) or not isinstance(kind, str): + continue + if _is_alive(host, port, timeout): + live.append(((kind != "window", -focused), port)) + if live: + live.sort(key=lambda item: item[0]) + return live[0][1] + if _is_alive(host, DEFAULT_PORT, timeout): + return DEFAULT_PORT + raise NoViewerError(_NO_VIEWER_TEXT) + + +def find_viewer( + *, + port: int | None = None, + token: str | None = None, + host: str = "127.0.0.1", + settings: Path | None = None, + timeout: float = 0.5, +) -> ViewerAddress: + """Find a running viewer and the token for it. + + Parameters + ---------- + port : int, optional + The port of the viewer. If given, it is returned as given: the + function does not check it and does not read the instance files. + token : str, optional + The access token. If not given, the function reads the + ``GEOVIEWER_TOKEN`` environment variable, then ``link.json``. + host : str + The host of the viewer. + settings : pathlib.Path, optional + The settings folder. The default is :func:`settings_dir`. + timeout : float + The time in seconds to wait for each connection test. + + Returns + ------- + ViewerAddress + The host, port and token of the viewer. + + Raises + ------ + TokenError + If no token is available. + NoViewerError + If no viewer is running. + """ + folder = settings if settings is not None else settings_dir() + resolved = _resolve_token(token, folder) + if port is not None: + return ViewerAddress(host=host, port=port, token=resolved) + return ViewerAddress(host=host, port=_find_port(folder, host, timeout), token=resolved) diff --git a/packages/loop_link/src/loop_link/encode.py b/packages/loop_link/src/loop_link/encode.py new file mode 100644 index 000000000..6ec026d54 --- /dev/null +++ b/packages/loop_link/src/loop_link/encode.py @@ -0,0 +1,688 @@ +"""Encode scene objects into protocol frames. + +The public functions return ``bytes``. Each frame has a JSON header and a list of +named binary buffers. See :mod:`loop_link.protocol` for the frame layout. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from typing import Any + +import numpy as np + +from loop_link import protocol +from loop_link.errors import InvalidInputError, ObjectTooLargeError +from loop_link.objects import ( + DEFAULT_CATEGORY_COLOURS, + BlockModel, + Categorical, + Drillhole, + Lines, + Points, + SceneObject, + Surface, + TetraMesh, + Vectors, +) + +__all__ = [ + "cancel_frame", + "clear_frame", + "command_frame", + "commands_list_frame", + "encode_object", + "fetch_frame", + "group_frame", + "heartbeat_frame", + "hello_frame", + "remove_frame", + "selection_get_frame", + "selection_set_frame", +] + +_I32_MIN = -(2**31) +_I32_MAX = 2**31 - 1 + +# The name of the log set that holds the interval properties of a Drillhole. +_INTERVAL_LOG_SET = "intervals" + +Buffers = list[tuple[str, np.ndarray]] + + +def hello_frame(crs: str, origin: Sequence[float], version: str) -> bytes: + """Return the ``hello`` frame. + + Parameters + ---------- + crs : str + The coordinate reference system, for example ``"EPSG:28350"``. + origin : sequence of float + The scene origin, three values. + version : str + The version of loop_link. + + Returns + ------- + bytes + The frame. + """ + header = { + "type": "hello", + "application": {"name": "loop_link", "version": version}, + "crs": crs, + "origin": [float(v) for v in origin], + } + return protocol.encode_frame(header) + + +def heartbeat_frame(seq: int) -> bytes: + """Return a ``heartbeat`` frame. + + Parameters + ---------- + seq : int + The sequence number. + + Returns + ------- + bytes + The frame. + """ + return protocol.encode_frame({"type": "heartbeat", "seq": seq}) + + +def remove_frame(id: str) -> bytes: + """Return a ``scene.remove`` frame. + + Parameters + ---------- + id : str + The identifier of the object to remove. + + Returns + ------- + bytes + The frame. + """ + return protocol.encode_frame({"type": "scene.remove", "id": id}) + + +def clear_frame() -> bytes: + """Return a ``scene.clear`` frame. + + Returns + ------- + bytes + The frame. + """ + return protocol.encode_frame({"type": "scene.clear"}) + + +def selection_set_frame( + request: int, + object_id: str, + cells: np.ndarray | None, + vertices: np.ndarray | None, + revision: int | None, +) -> bytes: + """Return a ``selection.set`` frame. + + An empty or None array adds no entry and no buffer. The function does not + check the index range. + + Parameters + ---------- + request : int + The request number. + object_id : str + The identifier of the object. + cells : numpy.ndarray or None + The cell indices. + vertices : numpy.ndarray or None + The vertex (node) indices. + revision : int or None + The revision of the object. If it is None, the header has no ``revision`` key. + + Returns + ------- + bytes + The frame. + """ + header: dict[str, Any] = {"type": "selection.set", "request": request, "object": object_id} + if revision is not None: + header["revision"] = revision + entries: list[dict[str, str]] = [] + buffers: Buffers = [] + for kind, name, values in (("cells", "cells", cells), ("nodes", "nodes", vertices)): + if values is None: + continue + array = np.ascontiguousarray(np.asarray(values, dtype=np.uint32)) + if array.size == 0: + continue + entries.append({"kind": kind, "indices": name}) + buffers.append((name, array)) + header["entries"] = entries + return protocol.encode_frame(header, buffers, version=protocol.TOOL_PROTOCOL_VERSION) + + +def selection_get_frame(request: int) -> bytes: + """Return a ``selection.get`` frame. + + Parameters + ---------- + request : int + The request number. + + Returns + ------- + bytes + The frame. + """ + return protocol.encode_frame( + {"type": "selection.get", "request": request}, + version=protocol.TOOL_PROTOCOL_VERSION, + ) + + +def fetch_frame(request: int, id: str) -> bytes: + """Return an ``object.fetch`` frame. + + Parameters + ---------- + request : int + The request number. + id : str + The identifier of the object. + + Returns + ------- + bytes + The frame. + """ + return protocol.encode_frame( + {"type": "object.fetch", "request": request, "id": id}, + version=protocol.TOOL_PROTOCOL_VERSION, + ) + + +def cancel_frame(request: int) -> bytes: + """Return a ``command.cancel`` frame. + + Parameters + ---------- + request : int + The number of the request to cancel. + + Returns + ------- + bytes + The frame. + """ + return protocol.encode_frame( + {"type": "command.cancel", "request": request}, + version=protocol.CANCEL_PROTOCOL_VERSION, + ) + + +def commands_list_frame(request: int) -> bytes: + """Return a ``commands.list`` frame. + + Parameters + ---------- + request : int + The request number. + + Returns + ------- + bytes + The frame. + """ + return protocol.encode_frame( + {"type": "commands.list", "request": request}, + version=protocol.COMMAND_PROTOCOL_VERSION, + ) + + +def command_frame(request: int, command: str, input: Mapping[str, Any]) -> bytes: + """Return a ``command.run`` frame. + + The function copies the input mapping. It does not change the mapping of the + caller. The input must be JSON values. A NaN or an infinite number raises an error. + + Parameters + ---------- + request : int + The request number. + command : str + The name of the command, for example ``"object.set_visible"``. + input : Mapping[str, Any] + The arguments of the command. + + Returns + ------- + bytes + The frame. + + Raises + ------ + ProtocolError + If the input cannot be encoded as JSON, for example for a NaN value. + """ + header = { + "type": "command.run", + "request": request, + "command": command, + "input": dict(input), + } + try: + return protocol.encode_frame(header, version=protocol.COMMAND_PROTOCOL_VERSION) + except ValueError as error: + raise protocol.ProtocolError( + "The input of the command has a value that JSON cannot store, such as NaN " + "or an infinite number. Use finite numbers." + ) from error + + +def _upsert_header( + id: str, + object_type: str, + name: str | None, + parent: str | None, + revision: int, +) -> dict[str, Any]: + """Return the header of a ``scene.upsert`` frame without data.""" + return { + "type": "scene.upsert", + "id": id, + "object_type": object_type, + "name": id if name is None else name, + "parent": parent, + "revision": revision, + "edit": [], + "replaces": None, + "geometry": {}, + "params": {}, + "data": [], + "property_groups": [], + "drape": None, + "style": {}, + } + + +def group_frame( + id: str, + name: str | None, + parent: str | None, + revision: int, +) -> bytes: + """Return a ``scene.upsert`` frame for a group. + + Parameters + ---------- + id : str + The identifier of the group. + name : str or None + The display name. If it is None, the name is the identifier. + parent : str or None + The identifier of the parent group. + revision : int + The revision number. + + Returns + ------- + bytes + The frame. + """ + return protocol.encode_frame(_upsert_header(id, "Group", name, parent, revision)) + + +def _utf8_size(value_map: list[dict[str, Any]], name: str) -> int: + """Return the declared bytes of a value map. Raise if a name is not valid UTF-8.""" + total = 0 + try: + for item in value_map: + total += 8 + len(item["name"].encode("utf-8")) + except UnicodeEncodeError as error: + raise InvalidInputError( + f"A category name of the property '{name}' cannot be encoded as UTF-8. " + "Remove the characters that are not valid." + ) from error + return total + + +def _declared_bytes(name: str, value: object) -> int: + """Return the bytes that a property needs, from its shape and target type. + + The function does not copy the values. For text it returns an upper bound. + """ + if isinstance(value, Categorical): + codes = np.asarray(value.codes) + total = int(codes.size) * 4 + for label in value.names: + try: + total += 8 + len(str(label).encode("utf-8")) + except UnicodeEncodeError as error: + raise InvalidInputError( + f"A category name of the property '{name}' cannot be encoded as UTF-8. " + "Remove the characters that are not valid." + ) from error + return total + arr = np.asarray(value) + kind = arr.dtype.kind + if kind == "f": + return int(arr.size) * (4 if arr.dtype == np.dtype("float32") else 8) + if kind == "b": + return int(arr.size) + if kind in "iu": + return int(arr.size) * 4 + if kind in "US": + return int(arr.size) * int(arr.dtype.itemsize) + (int(arr.size) + 1) * 4 + return 0 + + +def _data_array( + name: str, value: object, association: str, log_set: str | None = None +) -> tuple[dict[str, Any], Buffers]: + """Return the data description and the buffers of one property. + + Parameters + ---------- + name : str + The name of the property. + value : numpy.ndarray or Categorical + The values. + association : str + ``"vertex"``, ``"cell"`` or ``"interval"``. For a Drillhole, ``"vertex"`` has one + value for each survey station and ``"interval"`` has one value for each row of + ``intervals``. An ``"interval"`` array belongs to a log set. ``"cell"`` is for + the other object types. + log_set : str or None + The name of the log set of an ``"interval"`` array. The function writes it to + the data description as ``log_set``. Use ``None`` for the other associations. + + Returns + ------- + desc : dict + The entry for the ``data`` list of the header. + buffers : list of (str, numpy.ndarray) + The buffers of the property. + + Raises + ------ + InvalidInputError + If the type of the values is not supported, or an integer is outside i32. + """ + buffer_name = f"data/{name}" + desc: dict[str, Any] = { + "id": name, + "name": name, + "buffer": buffer_name, + "association": association, + } + if log_set is not None: + desc["log_set"] = log_set + if isinstance(value, Categorical): + codes = np.asarray(value.codes).astype(np.uint32, copy=False) + colours = value.colours + value_map = [] + for index, label in enumerate(value.names): + if colours is None: + colour = list(DEFAULT_CATEGORY_COLOURS[index % len(DEFAULT_CATEGORY_COLOURS)]) + else: + colour = [int(c) for c in colours[index]] + value_map.append({"id": index, "name": str(label), "colour": colour}) + _utf8_size(value_map, name) + desc["data_type"] = "referenced" + desc["value_map"] = value_map + return desc, [(buffer_name, codes)] + arr = np.asarray(value) + kind = arr.dtype.kind + if kind == "f": + if arr.dtype != np.dtype("float32"): + arr = arr.astype(np.float64, copy=False) + desc["data_type"] = "float" + return desc, [(buffer_name, arr)] + if kind == "b": + desc["data_type"] = "boolean" + return desc, [(buffer_name, arr.astype(np.uint8, copy=False))] + if kind in "iu": + if arr.size and (arr.min() < _I32_MIN or arr.max() > _I32_MAX): + raise InvalidInputError( + f"The property '{name}' has integers outside the i32 range. " + "Use values from -2147483648 to 2147483647." + ) + desc["data_type"] = "integer" + return desc, [(buffer_name, arr.astype(np.int32, copy=False))] + if kind in "US": + try: + if kind == "U": + parts = [str(item).encode("utf-8") for item in arr.tolist()] + else: + parts = [bytes(item) for item in arr.tolist()] + for part in parts: + part.decode("utf-8") + except (UnicodeEncodeError, UnicodeDecodeError) as error: + raise InvalidInputError( + f"The property '{name}' has text that is not valid UTF-8. " + "Remove the characters that are not valid." + ) from error + offsets = np.zeros(len(parts) + 1, dtype=np.uint32) + if parts: + offsets[1:] = np.cumsum([len(p) for p in parts], dtype=np.uint64) + data = np.frombuffer(b"".join(parts), dtype=np.uint8) + offsets_name = f"{buffer_name}/offsets" + desc["data_type"] = "text" + desc["offsets"] = offsets_name + return desc, [(buffer_name, data), (offsets_name, offsets)] + raise InvalidInputError( + f"The property '{name}' has the type {arr.dtype}, which is not supported. " + "Use numbers, booleans, text or Categorical." + ) + + +class _Builder: + """Collect the header parts and the buffers of one object.""" + + def __init__(self, id: str, origin: np.ndarray) -> None: + self.id = id + self.origin = origin + self.buffers: Buffers = [] + self.names: set[str] = set() + self.geometry: dict[str, str] = {} + self.data: list[dict[str, Any]] = [] + self.groups: list[dict[str, Any]] = [] + self.declared = 0 + + def reserve(self, size: int) -> None: + """Add a declared size. Raise if a limit is passed. Call before any copy.""" + self.declared += size + limit = protocol.MAX_OBJECT_BYTES + if self.declared > limit: + raise ObjectTooLargeError(self.id, self.declared, limit) + frame_limit = protocol.MAX_FRAME_BYTES + if self.declared > frame_limit - protocol.MAX_HEADER_BYTES: + raise ObjectTooLargeError(self.id, self.declared, frame_limit) + + def add_buffer(self, name: str, array: np.ndarray) -> None: + """Add a buffer. Raise if the name is already used.""" + if name in self.names: + raise InvalidInputError( + f"The buffer name '{name}' is used two times. Use different property names." + ) + self.names.add(name) + self.buffers.append((name, array)) + + def add_geometry(self, role: str, array: np.ndarray) -> None: + """Add a geometry buffer for a role.""" + name = f"geometry/{role}" + self.add_buffer(name, array) + self.geometry[role] = name + + def add_vertices(self, verts: np.ndarray) -> None: + """Shift the vertices in f64 and add them as f32 or f64.""" + # Use the declared size first. Do not copy the array before this check. + self.reserve(int(verts.size) * 8) + # The shift makes one new f64 array. The array of the caller does not change. + shifted = np.subtract(verts, self.origin, dtype=np.float64) + low = float(shifted.min()) if shifted.size else 0.0 + high = float(shifted.max()) if shifted.size else 0.0 + if not (np.isfinite(low) and np.isfinite(high)): + raise InvalidInputError("The vertices must be finite numbers. Check the input.") + if max(abs(low), abs(high)) > protocol.F32_LIMIT: + self.add_geometry("vertices", shifted) + else: + self.add_geometry("vertices", shifted.astype(np.float32)) + + def add_index(self, role: str, array: object) -> None: + """Add an index buffer as u32.""" + view = np.asarray(array) + self.reserve(int(view.size) * 4) + self.add_geometry(role, view.astype(np.uint32, copy=False)) + + def add_property( + self, name: str, value: object, association: str, log_set: str | None = None + ) -> None: + """Add a property with its buffers. A log set name is optional.""" + self.reserve(_declared_bytes(name, value)) + desc, buffers = _data_array(name, value, association, log_set) + for buffer_name, array in buffers: + self.add_buffer(buffer_name, array) + self.data.append(desc) + + def add_properties( + self, props: Mapping[str, object], association: str, log_set: str | None = None + ) -> None: + """Add a mapping of properties. A log set name is optional.""" + for name, value in props.items(): + self.add_property(name, value, association, log_set) + + def add_pair_group(self, role: str, names: tuple[str, str], pair: Sequence[object]) -> None: + """Add a property group of two float arrays, such as orientation.""" + members = [] + for member_role, values in zip(names, pair): + data_name = f"{role}/{member_role}" + self.add_property(data_name, np.asarray(values, dtype=np.float64), "vertex") + members.append({"role": member_role, "data": data_name}) + self.groups.append({"id": role, "name": role, "role": role, "members": members}) + + +def _finite_f64(value: object, label: str) -> np.ndarray: + """Return a finite float64 array. Raise if a value is NaN or infinite.""" + arr = np.asarray(value, dtype=np.float64) + if not np.all(np.isfinite(arr)): + raise InvalidInputError(f"The field '{label}' must be finite numbers. Check the input.") + return arr + + +def encode_object( + obj: SceneObject, + *, + id: str, + name: str | None, + parent: str | None, + revision: int, + origin: Sequence[float], +) -> bytes: + """Return the ``scene.upsert`` frame for an object. + + The function subtracts the origin from the coordinates in float64. Then it + writes the vertices as f32 if all values are near the origin, or as f64 if not. + + Parameters + ---------- + obj : SceneObject + The object to encode. + id : str + The identifier of the object. + name : str or None + The display name. If it is None, the name is the identifier. + parent : str or None + The identifier of the parent group. + revision : int + The revision number. + origin : sequence of float + The scene origin, three values. + + Returns + ------- + bytes + The frame. + + Raises + ------ + InvalidInputError + If a coordinate is NaN or infinite, or a property is not supported. + ObjectTooLargeError + If the object or the frame is over the size limit. + """ + try: + origin_arr = np.asarray(origin, dtype=np.float64) + except (TypeError, ValueError) as error: + raise InvalidInputError("The origin must be three numbers. Check the input.") from error + if origin_arr.shape != (3,) or not np.all(np.isfinite(origin_arr)): + raise InvalidInputError("The origin must be three finite numbers. Check the input.") + builder = _Builder(id, origin_arr) + params: dict[str, Any] = {} + log_sets: list[dict[str, str]] = [] + if isinstance(obj, Drillhole): + object_type = "Drillhole" + builder.reserve( + (3 + int(np.asarray(obj.survey).size) + int(np.asarray(obj.intervals).size)) * 8 + ) + collar = _finite_f64(obj.collar, "collar") - origin_arr + builder.add_geometry("collar", collar) + builder.add_geometry("survey", _finite_f64(obj.survey, "survey")) + builder.add_geometry("intervals", _finite_f64(obj.intervals, "intervals")) + if obj.end_of_hole is not None: + params["end_of_hole"] = [float(obj.end_of_hole)] + builder.add_properties(obj.properties, "vertex") + if obj.interval_properties: + log_sets.append({"name": _INTERVAL_LOG_SET, "kind": "interval"}) + builder.add_properties(obj.interval_properties, "interval", _INTERVAL_LOG_SET) + elif isinstance(obj, BlockModel): + object_type = "BlockModel" + shifted = _finite_f64(obj.origin, "origin") - origin_arr + params["origin"] = [float(v) for v in shifted] + params["cell_sizes"] = [float(v) for v in np.asarray(obj.cell_sizes)] + params["cells"] = [int(v) for v in np.asarray(obj.cells)] + builder.add_properties(obj.properties, "vertex") + builder.add_properties(obj.cell_properties, "cell") + else: + if isinstance(obj, Lines): + object_type, index_role, index_attr = "Curve", "segments", "segments" + elif isinstance(obj, Surface): + object_type, index_role, index_attr = "Surface", "triangles", "triangles" + elif isinstance(obj, TetraMesh): + object_type, index_role, index_attr = "TetraMesh", "tetrahedra", "tetrahedra" + elif isinstance(obj, (Points, Vectors)): + object_type, index_role, index_attr = "Points", "", "" + else: + raise InvalidInputError( + f"The object type {type(obj).__name__} is not supported. " + "Use Points, Vectors, Lines, Surface, BlockModel, TetraMesh or Drillhole." + ) + builder.add_vertices(obj.vertices) + if index_role: + builder.add_index(index_role, getattr(obj, index_attr)) + if isinstance(obj, Vectors): + if obj.orientation is not None: + builder.add_pair_group("orientation", ("dip_direction", "dip"), obj.orientation) + if obj.lineation is not None: + builder.add_pair_group("lineation", ("trend", "plunge"), obj.lineation) + builder.add_properties(obj.properties, "vertex") + cell_properties = getattr(obj, "cell_properties", None) + if cell_properties: + builder.add_properties(cell_properties, "cell") + + header = _upsert_header(id, object_type, name, parent, revision) + header["geometry"] = builder.geometry + header["params"] = params + header["data"] = builder.data + header["property_groups"] = builder.groups + if log_sets: + header["log_sets"] = log_sets + try: + return protocol.encode_frame(header, builder.buffers) + except protocol.ProtocolError as error: + raise ObjectTooLargeError(id, builder.declared, protocol.MAX_FRAME_BYTES) from error diff --git a/packages/loop_link/src/loop_link/errors.py b/packages/loop_link/src/loop_link/errors.py new file mode 100644 index 000000000..a4fc5da9a --- /dev/null +++ b/packages/loop_link/src/loop_link/errors.py @@ -0,0 +1,279 @@ +"""Error types that loop_link raises. + +All errors derive from :class:`LoopLinkError`, so a caller can catch every +loop_link error with one ``except`` clause. +""" + +from __future__ import annotations + +from dataclasses import dataclass + + +class LoopLinkError(Exception): + """Base class for all loop_link errors.""" + + +class NoViewerError(LoopLinkError): + """No viewer is available. + + Parameters + ---------- + message : str + The error text. The default text tells the user how to start a viewer. + """ + + def __init__( + self, + message: str = "No viewer is running. Start a viewer before you send objects.", + ) -> None: + super().__init__(message) + + +class TokenError(LoopLinkError): + """The access token is missing, wrong or expired. + + Parameters + ---------- + message : str + The error text. The default text tells the user how to get a new token. + """ + + def __init__( + self, + message: str = "The access token is not valid. Create a new token and try again.", + ) -> None: + super().__init__(message) + + +class BusyError(LoopLinkError): + """The viewer is busy with another request. + + Parameters + ---------- + message : str + The error text. The default text tells the user to wait and retry. + """ + + def __init__( + self, + message: str = "The viewer is busy. Wait a moment and try again.", + ) -> None: + super().__init__(message) + + +class InvalidInputError(LoopLinkError): + """An input value is not valid. + + Parameters + ---------- + message : str + The error text. The default text tells the user to check the input. + """ + + def __init__( + self, + message: str = "An input value is not valid. Check the input and try again.", + ) -> None: + super().__init__(message) + + +class ViewerClosedError(LoopLinkError): + """The viewer was closed. + + Parameters + ---------- + message : str + The error text. The default text tells the user to open the viewer again. + """ + + def __init__( + self, + message: str = "The viewer was closed. Open the viewer again and retry.", + ) -> None: + super().__init__(message) + + +class MissingFeatureError(LoopLinkError): + """A required feature is not available. + + Parameters + ---------- + feature : str + The name of the missing feature. + + Attributes + ---------- + feature : str + The name of the missing feature. + """ + + def __init__(self, feature: str) -> None: + self.feature = feature + super().__init__( + f"The feature '{feature}' is not available in this installation. " + f"Check that the '{feature}' feature is installed and enabled, then retry." + ) + + +class ObjectTooLargeError(LoopLinkError): + """An object is larger than the allowed limit. + + Parameters + ---------- + object_id : str + The identifier of the object. + size : int + The size of the object. + limit : int + The largest size that is allowed. + + Attributes + ---------- + object_id : str + The identifier of the object. + size : int + The size of the object. + limit : int + The largest size that is allowed. + """ + + def __init__(self, object_id: str, size: int, limit: int) -> None: + self.object_id = object_id + self.size = size + self.limit = limit + super().__init__( + f"Object '{object_id}' is {size} units, which is larger than the limit of " + f"{limit} units. Reduce the size of the object or split it into smaller " + "objects, then try again." + ) + + +class StaleRevisionError(LoopLinkError): + """An object is not at the revision that the caller expects. + + Parameters + ---------- + object_id : str + The identifier of the object. + revision : int, optional + The revision that the caller expected. + + Attributes + ---------- + object_id : str + The identifier of the object. + revision : int, optional + The revision that the caller expected. + """ + + def __init__(self, object_id: str, revision: int | None = None) -> None: + self.object_id = object_id + self.revision = revision + super().__init__( + f"The object '{object_id}' is not at that revision in the viewer. " + "Read the selection or fetch the object again, then try again." + ) + + +class CancelledError(LoopLinkError): + """The request was cancelled. + + Parameters + ---------- + message : str + The error text. The default text says that the request was cancelled. + """ + + def __init__(self, message: str = "The request was cancelled.") -> None: + super().__init__(message) + + +class UnsupportedObjectError(LoopLinkError): + """The object type cannot be fetched by loop_link. + + Parameters + ---------- + object_id : str + The identifier of the object. + object_type : str + The type of the object. + + Attributes + ---------- + object_id : str + The identifier of the object. + object_type : str + The type of the object. + """ + + def __init__(self, object_id: str, object_type: str) -> None: + self.object_id = object_id + self.object_type = object_type + super().__init__( + f"The object '{object_id}' has the type '{object_type}'. loop_link can fetch " + "Points, Curve, Surface, BlockModel, TetraMesh and Drillhole objects only." + ) + + +@dataclass(frozen=True) +class Refusal: + """A reason why the viewer refused one object. + + Parameters + ---------- + object_id : str + The identifier of the refused object. + code : str + A short code that names the reason. + message : str + A message that explains the reason. + """ + + object_id: str + code: str + message: str + + +class ViewerRefusedError(LoopLinkError): + """The viewer refused one or more objects. + + Parameters + ---------- + refusals : list of Refusal + The refusals, one for each refused object. + + Attributes + ---------- + refusals : list of Refusal + The refusals, one for each refused object. + """ + + def __init__(self, refusals: list[Refusal]) -> None: + self.refusals = refusals + count = len(refusals) + super().__init__( + f"The viewer refused {count} object(s). Read the code and message of each " + "refusal, fix those objects, and try again." + ) + + +class MissingExtraError(LoopLinkError): + """An optional extra package is not installed. + + Parameters + ---------- + extra : str + The name of the extra. + + Attributes + ---------- + extra : str + The name of the extra. + """ + + def __init__(self, extra: str) -> None: + self.extra = extra + super().__init__( + f"The optional '{extra}' part of loop-link is not installed. " + f"Run: pip install loop-link[{extra}]" + ) diff --git a/packages/loop_link/src/loop_link/fetch.py b/packages/loop_link/src/loop_link/fetch.py new file mode 100644 index 000000000..1dd8d041d --- /dev/null +++ b/packages/loop_link/src/loop_link/fetch.py @@ -0,0 +1,610 @@ +"""Fetch viewer objects and decode them into scene objects. + +The viewer sends an object as a JSON header and a set of named arrays. The +function :func:`decode_object` makes a scene object from them. The coordinates +of the result are world coordinates in float64. The function +:func:`fetch_object` asks the viewer for an object and collects the reply. +""" + +from __future__ import annotations + +import itertools +import math +import threading +import warnings +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +import numpy as np + +from loop_link import encode, protocol +from loop_link.errors import ( + InvalidInputError, + ObjectTooLargeError, + UnsupportedObjectError, + ViewerClosedError, +) +from loop_link.objects import ( + DEFAULT_CATEGORY_COLOURS, + BlockModel, + Categorical, + Drillhole, + Lines, + Points, + SceneObject, + Surface, + TetraMesh, + Vectors, +) +from loop_link.protocol import Frame, ProtocolError +from loop_link.tool import ToolConnection + +__all__ = ["FetchResult", "decode_object", "fetch_object"] + +# The numpy type of each array type name in the protocol. All are little-endian. +_ARRAY_DTYPES = { + "f32": np.dtype(" None: + """Tell the user that a property is not in the result.""" + warnings.warn( + f"loop_link dropped the property '{name}' of object '{object_id}': {reason}", + UserWarning, + stacklevel=4, + ) + + +def _decode_text(desc: Mapping[str, Any], arrays: Mapping[str, np.ndarray]) -> np.ndarray: + """Return a numpy unicode array from the bytes and the offsets of a text property.""" + if desc.get("offsets") is None: + raise ProtocolError(f"The text property '{desc.get('name')}' has no offsets.") + data = np.asarray(arrays[desc["buffer"]], dtype=np.uint8).tobytes() + offsets = np.asarray(arrays[desc["offsets"]]).astype(np.int64) + items = [ + data[int(start) : int(end)].decode("utf-8") for start, end in itertools.pairwise(offsets) + ] + return np.array(items, dtype=str) + + +class _UnmappedCodeError(Exception): + """A code of a referenced property is not in its value map.""" + + +def _decode_referenced( + desc: Mapping[str, Any], arrays: Mapping[str, np.ndarray], object_id: str +) -> Categorical: + """Return a :class:`Categorical` from the codes and the value map of a property.""" + value_map = sorted(desc.get("value_map") or [], key=lambda item: item["id"]) + ids = np.array([item["id"] for item in value_map], dtype=np.int64) + names = [str(item["name"]) for item in value_map] + colours = [] + for index, item in enumerate(value_map): + colour = item.get("colour") + if colour is None: + colours.append(DEFAULT_CATEGORY_COLOURS[index % len(DEFAULT_CATEGORY_COLOURS)]) + continue + values = tuple(int(c) for c in colour) + colours.append(values if len(values) == 4 else (*values[:3], 255)) + raw = np.asarray(arrays[desc["buffer"]]).astype(np.int64) + positions = np.searchsorted(ids, raw) + safe = np.minimum(positions, max(len(ids) - 1, 0)) + if raw.size and (len(ids) == 0 or not np.all(ids[safe] == raw)): + raise _UnmappedCodeError + return Categorical(positions, names, colours) + + +def _decode_values( + desc: Mapping[str, Any], arrays: Mapping[str, np.ndarray], object_id: str +) -> np.ndarray | Categorical: + """Return the values of one data entry as a numpy array or a Categorical.""" + data_type = desc.get("data_type") + if data_type == "referenced": + return _decode_referenced(desc, arrays, object_id) + if data_type == "text": + return _decode_text(desc, arrays) + values = np.asarray(arrays[desc["buffer"]]) + if data_type == "boolean": + return values != 0 + if data_type == "integer": + return values.astype(np.int32) + if values.dtype == np.float32: + return values + return values.astype(np.float64) + + +def _route( + desc: Mapping[str, Any], + object_type: str, + object_id: str, + interval_set: str | None, +) -> str | None: + """Return the target dictionary of a data entry, or None with a reason in a warning. + + The result is ``"properties"``, ``"cell_properties"`` or ``"interval_properties"``. + """ + name = str(desc.get("name", desc.get("id"))) + association = desc.get("association") + if association == "vertex": + return "properties" + if association == "cell": + if object_type == "Drillhole": + return "interval_properties" + if object_type == "Points": + raise UnsupportedObjectError(object_id, object_type) + return "cell_properties" + if association == "interval" and object_type == "Drillhole": + log_set = desc.get("log_set") + if log_set is None or log_set == interval_set: + return "interval_properties" + _warn_dropped(name, object_id, f"it belongs to the log set '{log_set}', not the first one") + return None + _warn_dropped(name, object_id, f"the association '{association}' is not supported") + return None + + +def _group_pair( + group: Mapping[str, Any], + names: tuple[str, str], + entries: Mapping[str, Mapping[str, Any]], + arrays: Mapping[str, np.ndarray], +) -> tuple[np.ndarray, np.ndarray]: + """Return the two float64 arrays of a property group.""" + by_role = {member["role"]: member["data"] for member in group.get("members") or []} + result = [] + for role in names: + if role not in by_role or by_role[role] not in entries: + raise InvalidInputError( + f"The property group '{group.get('id')}' has no member '{role}'. " + "Check the object in the viewer." + ) + buffer = entries[by_role[role]]["buffer"] + result.append(np.asarray(arrays[buffer]).astype(np.float64)) + return result[0], result[1] + + +def decode_object( + header: Mapping[str, Any], + arrays: Mapping[str, np.ndarray], + origin: Sequence[float] | None, +) -> SceneObject: + """Decode the header and the arrays of a viewer object into a scene object. + + Parameters + ---------- + header : mapping + The ``scene.upsert`` header of the object. + arrays : mapping of str to numpy.ndarray + The buffers of the object, by name. + origin : sequence of float or None + The scene origin. The function adds it to the coordinates. None means + (0, 0, 0). + + Returns + ------- + SceneObject + The object, with float64 world coordinates. + + Raises + ------ + UnsupportedObjectError + If the object type is not supported, or a cell property is on a Points object. + + Warns + ----- + UserWarning + One time for each property that the function drops. This includes a + referenced property that has a code that is not in its value map. + """ + object_id = str(header.get("id")) + object_type = str(header.get("object_type")) + if object_type not in _SUPPORTED_TYPES: + raise UnsupportedObjectError(object_id, object_type) + shift = np.zeros(3) if origin is None else np.asarray(origin, dtype=np.float64) + geometry = header.get("geometry") or {} + params = header.get("params") or {} + + def geo(role: str) -> np.ndarray: + return np.asarray(arrays[geometry[role]]) + + entries = {str(desc["id"]): desc for desc in header.get("data") or []} + groups = [ + group + for group in header.get("property_groups") or [] + if object_type == "Points" and group.get("role") in _GROUP_MEMBERS + ] + member_ids = {member["data"] for group in groups for member in group.get("members") or []} + + interval_set = None + for log_set in header.get("log_sets") or []: + if log_set.get("kind") == "interval": + interval_set = log_set.get("name") + break + + targets: dict[str, dict[str, Any]] = { + "properties": {}, + "cell_properties": {}, + "interval_properties": {}, + } + for data_id, desc in entries.items(): + if data_id in member_ids: + continue + target = _route(desc, object_type, object_id, interval_set) + if target is not None: + try: + targets[target][str(desc["name"])] = _decode_values(desc, arrays, object_id) + except _UnmappedCodeError: + _warn_dropped( + str(desc["name"]), + object_id, + "a code is not in its value map", + ) + + if object_type == "Drillhole": + end_of_hole = params.get("end_of_hole") + return Drillhole( + geo("collar").astype(np.float64) + shift, + geo("survey").astype(np.float64), + geo("intervals").astype(np.float64), + end_of_hole=None if end_of_hole is None else float(end_of_hole[0]), + properties=targets["properties"], + interval_properties=targets["interval_properties"], + ) + if object_type == "BlockModel": + return BlockModel( + np.asarray(params["origin"], dtype=np.float64) + shift, + params["cell_sizes"], + params["cells"], + properties=targets["properties"], + cell_properties=targets["cell_properties"], + ) + + vertices = geo("vertices").astype(np.float64) + shift + if object_type == "Curve": + return Lines(vertices, geo("segments"), targets["properties"], targets["cell_properties"]) + if object_type == "Surface": + return Surface( + vertices, geo("triangles"), targets["properties"], targets["cell_properties"] + ) + if object_type == "TetraMesh": + return TetraMesh( + vertices, geo("tetrahedra"), targets["properties"], targets["cell_properties"] + ) + if not groups: + return Points(vertices, targets["properties"]) + pairs: dict[str, tuple[np.ndarray, np.ndarray]] = {} + for group in groups: + role = group["role"] + pairs[role] = _group_pair(group, _GROUP_MEMBERS[role], entries, arrays) + return Vectors( + vertices, + orientation=pairs.get("orientation"), + lineation=pairs.get("lineation"), + properties=targets["properties"], + ) + + +def _is_int(value: object) -> bool: + """Return whether the value is an integer and not a boolean.""" + return isinstance(value, int) and not isinstance(value, bool) + + +def _as_dict(value: object, what: str) -> dict[str, Any]: + """Return the value if it is a dict, or raise a ProtocolError.""" + if not isinstance(value, dict): + raise ProtocolError(f"The {what} is not an object.") + return value + + +def _is_origin(origin: object) -> bool: + """Return whether the value is a list of 3 finite numbers.""" + return ( + isinstance(origin, list) + and len(origin) == 3 + and all( + isinstance(v, int | float) and not isinstance(v, bool) and math.isfinite(v) + for v in origin + ) + ) + + +def _as_origin(origin: Sequence[float]) -> tuple[float, float, float]: + """Return the origin as a tuple of 3 floats.""" + x, y, z = (float(value) for value in origin) + return (x, y, z) + + +class _Assembler: + """Collect the frames of one ``object.fetch`` reply and make the result. + + Parameters + ---------- + object_id : str + The identifier of the object that was requested. + """ + + def __init__(self, object_id: str) -> None: + self._object_id = object_id + self._header: dict[str, Any] | None = None + self._arrays: dict[str, np.ndarray] = {} + self._shapes: dict[str, tuple[int, ...]] = {} + self._dtypes: dict[str, np.dtype] = {} + self._filled: dict[str, int] = {} + self._parts = 0 + self._ended = False + + def feed(self, frame: Frame) -> None: + """Take the next frame of the reply. + + Parameters + ---------- + frame : loop_link.protocol.Frame + An ``object.header``, ``object.part`` or ``object.end`` frame. + + Raises + ------ + loop_link.protocol.ProtocolError + If the frame breaks a rule of the stream. + loop_link.errors.ObjectTooLargeError + If the arrays of the header are larger than the limit. + """ + kind = frame.header.get("type") + if self._ended: + raise ProtocolError(f"The viewer sent a '{kind}' frame after 'object.end'.") + if self._header is None: + if kind != "object.header": + raise ProtocolError( + f"The first frame of an object must be 'object.header', not '{kind}'." + ) + self._take_header(frame.header) + elif kind == "object.part": + self._take_part(frame) + elif kind == "object.end": + self._take_end(frame.header) + else: + raise ProtocolError(f"The viewer sent an unknown frame '{kind}' for an object.") + + def finish(self) -> FetchResult: + """Return the object that the frames described. + + Returns + ------- + FetchResult + The decoded object and its data from the header. + + Raises + ------ + loop_link.protocol.ProtocolError + If the stream did not end, or the header is not valid. + """ + header = self._header + if header is None or not self._ended: + raise ProtocolError("The viewer did not finish the object.") + arrays = { + name: data.view(self._dtypes[name]).reshape(self._shapes[name]) + for name, data in self._arrays.items() + } + try: + obj = _as_dict(header["object"], "object header") + origin = header["origin"] + object_type = obj["object_type"] + revision = obj["revision"] + if not isinstance(object_type, str): + raise ProtocolError("The field 'object_type' is not a string.") + if not _is_int(revision) or revision < 0: + raise ProtocolError("The field 'revision' is not a non-negative integer.") + for field, value in ( + ("name", obj.get("name")), + ("parent", obj.get("parent")), + ("crs", header.get("crs")), + ): + if value is not None and not isinstance(value, str): + raise ProtocolError(f"The field '{field}' is not a string or null.") + if origin is not None and not _is_origin(origin): + raise ProtocolError("The field 'origin' is not null or 3 finite numbers.") + scene_object = decode_object(obj, arrays, origin) + return FetchResult( + id=self._object_id, + object=scene_object, + object_type=object_type, + revision=revision, + name=obj.get("name"), + parent=obj.get("parent"), + origin=None if origin is None else _as_origin(origin), + crs=header.get("crs"), + ) + except ( + KeyError, + TypeError, + ValueError, + IndexError, + OverflowError, + AttributeError, + ) as error: + raise ProtocolError(f"The object header is not valid: {error!r}") from error + + def _take_header(self, header: dict[str, Any]) -> None: + """Check the header, then make the empty arrays.""" + entries = header.get("arrays") + if not isinstance(entries, list): + raise ProtocolError("The 'arrays' field of the object header is not a list.") + sizes: dict[str, int] = {} + shapes: dict[str, tuple[int, ...]] = {} + dtypes: dict[str, np.dtype] = {} + for entry in entries: + entry = _as_dict(entry, "array entry") + name, dtype_name, shape = entry.get("name"), entry.get("dtype"), entry.get("shape") + if not isinstance(name, str) or name in sizes: + raise ProtocolError(f"The array name {name!r} is not valid or not unique.") + if not isinstance(dtype_name, str) or dtype_name not in _ARRAY_DTYPES: + raise ProtocolError(f"The array '{name}' has the type {dtype_name!r}.") + if not isinstance(shape, list) or not all(_is_int(n) and n >= 0 for n in shape): + raise ProtocolError(f"The array '{name}' has a shape that is not valid.") + dtypes[name] = _ARRAY_DTYPES[dtype_name] + shapes[name] = tuple(shape) + sizes[name] = math.prod(shape) * dtypes[name].itemsize + total = sum(sizes.values()) + if total > protocol.MAX_OBJECT_BYTES: + raise ObjectTooLargeError(self._object_id, total, protocol.MAX_OBJECT_BYTES) + obj = _as_dict(header.get("object"), "object header") + self._check_buffer_names(obj, sizes) + self._header = header + self._shapes = shapes + self._dtypes = dtypes + self._arrays = {name: np.empty(size, dtype=np.uint8) for name, size in sizes.items()} + self._filled = dict.fromkeys(sizes, 0) + + @staticmethod + def _check_buffer_names(obj: dict[str, Any], sizes: Mapping[str, int]) -> None: + """Check that each buffer name of the object is in the arrays.""" + names = list(_as_dict(obj.get("geometry") or {}, "geometry").values()) + data = obj.get("data") or [] + if not isinstance(data, list): + raise ProtocolError("The 'data' field of the object is not a list.") + for desc in data: + desc = _as_dict(desc, "data entry") + names.append(desc.get("buffer")) + if desc.get("offsets") is not None: + names.append(desc["offsets"]) + for name in names: + if not isinstance(name, str) or name not in sizes: + raise ProtocolError(f"The object uses the buffer {name!r}, which is not sent.") + + def _take_part(self, frame: Frame) -> None: + """Copy the bytes of one ``object.part`` frame into its array.""" + header = frame.header + name, offset, size = header.get("array"), header.get("offset"), header.get("bytes") + if not isinstance(name, str) or name not in self._arrays: + raise ProtocolError(f"The viewer sent a part for the unknown array {name!r}.") + if not _is_int(offset) or not _is_int(size) or offset < 0 or size < 0: + raise ProtocolError(f"The part of the array '{name}' has a bad offset or size.") + if offset % 8 != 0: + raise ProtocolError( + f"The part of the array '{name}' starts at {offset}, not a multiple of 8." + ) + part = frame.buffers.get("part") + if not isinstance(part, np.ndarray) or part.dtype != np.uint8 or part.size != size: + raise ProtocolError(f"The part of the array '{name}' is not {size} bytes of type u8.") + if offset != self._filled[name]: + raise ProtocolError( + f"The part of the array '{name}' starts at {offset}, " + f"but {self._filled[name]} bytes are filled." + ) + target = self._arrays[name] + if offset + size > target.size: + raise ProtocolError(f"The part of the array '{name}' goes past the end of the array.") + target[offset : offset + size] = part.reshape(-1) + self._filled[name] = offset + size + self._parts += 1 + + def _take_end(self, header: dict[str, Any]) -> None: + """Check the ``object.end`` frame.""" + parts = header.get("parts") + if not _is_int(parts) or parts != self._parts: + raise ProtocolError(f"The viewer said {parts!r} parts, but sent {self._parts}.") + for name, array in self._arrays.items(): + if self._filled[name] != array.size: + raise ProtocolError(f"The array '{name}' is not full when the object ends.") + self._ended = True + + +def fetch_object( + tool: ToolConnection, + id: str, + *, + progress: Callable[[float], None] | None = None, + cancel: threading.Event | None = None, + timeout: float = 30.0, +) -> FetchResult: + """Ask the viewer for one object and decode it. + + Parameters + ---------- + tool : loop_link.tool.ToolConnection + The connection to the viewer. + id : str + The identifier of the object. + progress : callable, optional + Called with the fraction of each progress report. + cancel : threading.Event, optional + When it is set, the request is cancelled. + timeout : float, optional + The time in seconds to wait for the next frame. + + Returns + ------- + FetchResult + The object, in world coordinates. + + Raises + ------ + loop_link.errors.ViewerClosedError + If the connection closed, or the viewer sent an object that is not valid. + In the second case the function closes the connection. + loop_link.errors.ObjectTooLargeError + If the object is larger than the limit. + """ + assembler = _Assembler(id) + try: + tool.request( + lambda n: encode.fetch_frame(n, id), + until=("object.end",), + feature="selection and fetch (geoviewer protocol 1.18)", + object_id=id, + on_frame=assembler.feed, + progress=progress, + cancel=cancel, + timeout=timeout, + ) + return assembler.finish() + except ProtocolError as error: + tool.close() + raise ViewerClosedError(f"The viewer sent an object that is not valid: {error}") from error diff --git a/packages/loop_link/src/loop_link/objects.py b/packages/loop_link/src/loop_link/objects.py new file mode 100644 index 000000000..4a95949d9 --- /dev/null +++ b/packages/loop_link/src/loop_link/objects.py @@ -0,0 +1,581 @@ +"""The object model of loop_link. + +Each class is a frozen dataclass. A class checks its input in ``__post_init__`` +and stores the arrays as numpy arrays. A check that fails raises +:class:`loop_link.errors.InvalidInputError` with the name of the field. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from typing import Any, Union + +import numpy as np + +from loop_link.errors import InvalidInputError +from loop_link.orientation import directions_to_lineation, normals_to_orientation + +__all__ = [ + "DEFAULT_CATEGORY_COLOURS", + "ArrayLike", + "BlockModel", + "Categorical", + "Drillhole", + "Lines", + "Points", + "Property", + "SceneObject", + "Surface", + "TetraMesh", + "Vectors", +] + +ArrayLike = Union[np.ndarray, Sequence] + +#: The ten tab10 colours as RGBA, with alpha 255. +DEFAULT_CATEGORY_COLOURS: tuple[tuple[int, int, int, int], ...] = ( + (31, 119, 180, 255), + (255, 127, 14, 255), + (44, 160, 44, 255), + (214, 39, 40, 255), + (148, 103, 189, 255), + (140, 86, 75, 255), + (227, 119, 194, 255), + (127, 127, 127, 255), + (188, 189, 34, 255), + (23, 190, 207, 255), +) + +_MAX_CODES = 2**32 + + +def _vertices(value: object, name: str = "vertices") -> np.ndarray: + """Return vertices as a finite float64 array with shape (n, 3).""" + try: + arr = np.array(value, dtype=np.float64, copy=True) + except (TypeError, ValueError) as exc: + raise InvalidInputError(f"The field '{name}' must be numbers. Check the input.") from exc + if arr.size == 0 and arr.ndim == 1: + arr = arr.reshape(0, 3) + if arr.ndim != 2 or arr.shape[1] != 3: + raise InvalidInputError(f"The field '{name}' must have shape (n, 3). Check the input.") + if not np.all(np.isfinite(arr)): + raise InvalidInputError(f"The field '{name}' must be finite numbers. Check the input.") + return arr + + +def _vector3(value: object, name: str) -> np.ndarray: + """Return a finite float64 array with shape (3,).""" + try: + arr = np.array(value, dtype=np.float64, copy=True) + except (TypeError, ValueError) as exc: + raise InvalidInputError(f"The field '{name}' must be numbers. Check the input.") from exc + if arr.shape != (3,): + raise InvalidInputError(f"The field '{name}' must have shape (3,). Check the input.") + if not np.all(np.isfinite(arr)): + raise InvalidInputError(f"The field '{name}' must be finite numbers. Check the input.") + return arr + + +def _integer_array(value: object, name: str) -> np.ndarray: + """Return ``value`` as an int64 array. + + Raises + ------ + InvalidInputError + If the values are not integers. + """ + try: + arr = np.array(value, copy=True) + except (TypeError, ValueError) as exc: + raise InvalidInputError(f"The field '{name}' must be integers. Check the input.") from exc + if arr.size == 0: + return arr.astype(np.int64) + if arr.dtype.kind not in "iu": + raise InvalidInputError(f"The field '{name}' must be integers. Check the input.") + return arr.astype(np.int64) + + +def _index_array(value: object, name: str, width: int, count: int) -> np.ndarray: + """Return an index array with shape (m, width) and values in [0, count).""" + arr = _integer_array(value, name) + if arr.size == 0 and arr.ndim == 1: + arr = arr.reshape(0, width) + if arr.ndim != 2 or arr.shape[1] != width: + raise InvalidInputError( + f"The field '{name}' must have shape (m, {width}). Check the input." + ) + if arr.size and (arr.min() < 0 or arr.max() >= count): + raise InvalidInputError( + f"The field '{name}' has an index outside the range 0 to {count - 1}. " + "Check the input." + ) + return arr + + +@dataclass(frozen=True, eq=False) +class Categorical: + """A property that holds categories. + + Parameters + ---------- + codes : array-like of int + One code for each item. A code is an index into ``names``. + names : sequence of str + The name of each category. + colours : sequence of tuple, optional + One RGBA colour for each category. A category without a colour uses + ``DEFAULT_CATEGORY_COLOURS[i % 10]``. + """ + + codes: ArrayLike + names: Sequence[str] + colours: Sequence[tuple[int, int, int, int]] | None = None + + def __post_init__(self) -> None: + """Check the input and store it as numpy arrays.""" + codes = _integer_array(self.codes, "codes") + if codes.ndim != 1: + raise InvalidInputError("The field 'codes' must be one-dimensional. Check the input.") + limit = min(len(self.names), _MAX_CODES) + if codes.size and (codes.min() < 0 or codes.max() >= limit): + raise InvalidInputError( + f"The field 'codes' must have values from 0 to {limit - 1}. Check the input." + ) + colours = self.colours + if colours is not None: + try: + arr = np.array(colours, copy=True) + except (TypeError, ValueError) as exc: + raise InvalidInputError( + "The field 'colours' must be RGBA numbers. Check the input." + ) from exc + if arr.shape != (len(self.names), 4) or arr.dtype.kind not in "iu": + raise InvalidInputError( + "The field 'colours' must have one RGBA tuple of 4 integers for each name. " + "Check the input." + ) + if arr.size and (arr.min() < 0 or arr.max() > 255): + raise InvalidInputError( + "The field 'colours' must have values from 0 to 255. Check the input." + ) + colours = tuple(tuple(int(v) for v in row) for row in arr) + object.__setattr__(self, "codes", codes) + object.__setattr__(self, "colours", colours) + + +Property = Union[np.ndarray, Sequence, Categorical] + + +def _properties(properties: dict[str, Any] | None, length: int, field_name: str) -> dict[str, Any]: + """Check a mapping of properties and return a new mapping. + + Parameters + ---------- + properties : dict + Property name to values or :class:`Categorical`. + length : int + The required number of values for each property. + field_name : str + The name of the field. The name is used in error messages. + + Returns + ------- + dict + The properties as numpy arrays. A :class:`Categorical` stays the same object. + + Raises + ------ + InvalidInputError + If a property is not one-dimensional or has the wrong length. + """ + if properties is None: + properties = {} + if not isinstance(properties, Mapping): + raise InvalidInputError(f"The field '{field_name}' must be a mapping. Check the input.") + result: dict[str, Any] = {} + for key, value in properties.items(): + if isinstance(value, Categorical): + size = len(value.codes) + result[key] = value + else: + try: + arr = np.array(value, copy=True) + except (TypeError, ValueError) as exc: + raise InvalidInputError( + f"The property '{key}' in '{field_name}' is not valid. Check the input." + ) from exc + if arr.ndim != 1: + raise InvalidInputError( + f"The property '{key}' in '{field_name}' must be one-dimensional. " + "Check the input." + ) + size = arr.shape[0] + result[key] = arr + if size != length: + raise InvalidInputError( + f"The property '{key}' in '{field_name}' has {size} values, but {length} " + "values are needed. Check the input." + ) + return result + + +@dataclass(frozen=True, eq=False) +class Points: + """A set of points. + + Parameters + ---------- + vertices : array-like + Coordinates with shape (n, 3). + properties : dict + Property name to n values or a :class:`Categorical`. + """ + + vertices: ArrayLike + properties: dict[str, Property] = field(default_factory=dict) + + def __post_init__(self) -> None: + """Check the input and store it as numpy arrays.""" + verts = _vertices(self.vertices) + object.__setattr__(self, "vertices", verts) + object.__setattr__( + self, "properties", _properties(self.properties, len(verts), "properties") + ) + + +@dataclass(frozen=True, eq=False) +class Vectors: + """A set of points with orientation or lineation data. + + Parameters + ---------- + vertices : array-like + Coordinates with shape (n, 3). + orientation : tuple of array-like, optional + ``(dip_direction, dip)`` in degrees, n values each. + lineation : tuple of array-like, optional + ``(trend, plunge)`` in degrees, n values each. + properties : dict + Property name to n values or a :class:`Categorical`. + """ + + vertices: ArrayLike + orientation: tuple[ArrayLike, ArrayLike] | None = None + lineation: tuple[ArrayLike, ArrayLike] | None = None + properties: dict[str, Property] = field(default_factory=dict) + + def __post_init__(self) -> None: + """Check the input and store it as numpy arrays.""" + verts = _vertices(self.vertices) + object.__setattr__(self, "vertices", verts) + for name in ("orientation", "lineation"): + pair = getattr(self, name) + if pair is None: + continue + try: + first, second = pair + except (TypeError, ValueError) as exc: + raise InvalidInputError( + f"The field '{name}' must be a tuple of two arrays. Check the input." + ) from exc + arrays = [] + for part in (first, second): + try: + arr = np.array(part, dtype=np.float64, copy=True) + except (TypeError, ValueError) as exc: + raise InvalidInputError( + f"The field '{name}' must be numbers. Check the input." + ) from exc + if arr.shape != (len(verts),) or not np.all(np.isfinite(arr)): + raise InvalidInputError( + f"The field '{name}' must have {len(verts)} finite values in each array. " + "Check the input." + ) + arrays.append(arr) + object.__setattr__(self, name, (arrays[0], arrays[1])) + object.__setattr__( + self, "properties", _properties(self.properties, len(verts), "properties") + ) + + @classmethod + def from_directions( + cls, + vertices: ArrayLike, + directions: ArrayLike, + *, + kind: str, + properties: dict[str, Property] | None = None, + ) -> Vectors: + """Make vectors from direction vectors. + + Parameters + ---------- + vertices : array-like + Coordinates with shape (n, 3). + directions : array-like + Vectors with shape (n, 3). They are plane normals or line directions. + kind : {"normal", "lineation"} + The meaning of ``directions``. + properties : dict, optional + Property name to n values or a :class:`Categorical`. + + Returns + ------- + Vectors + The vectors with ``orientation`` or ``lineation`` set. + + Raises + ------ + InvalidInputError + If ``kind`` is not "normal" or "lineation". + """ + props = properties if properties is not None else {} + if kind == "normal": + return cls(vertices, orientation=normals_to_orientation(directions), properties=props) + if kind == "lineation": + return cls(vertices, lineation=directions_to_lineation(directions), properties=props) + raise InvalidInputError("The argument 'kind' must be 'normal' or 'lineation'.") + + +@dataclass(frozen=True, eq=False) +class Lines: + """A set of line segments. + + Parameters + ---------- + vertices : array-like + Coordinates with shape (n, 3). + segments : array-like of int + Vertex indices with shape (m, 2). + properties : dict + Vertex properties, n values each. + cell_properties : dict + Segment properties, m values each. + """ + + vertices: ArrayLike + segments: ArrayLike + properties: dict[str, Property] = field(default_factory=dict) + cell_properties: dict[str, Property] = field(default_factory=dict) + + def __post_init__(self) -> None: + """Check the input and store it as numpy arrays.""" + verts = _vertices(self.vertices) + segs = _index_array(self.segments, "segments", 2, len(verts)) + object.__setattr__(self, "vertices", verts) + object.__setattr__(self, "segments", segs) + object.__setattr__( + self, "properties", _properties(self.properties, len(verts), "properties") + ) + object.__setattr__( + self, + "cell_properties", + _properties(self.cell_properties, len(segs), "cell_properties"), + ) + + +@dataclass(frozen=True, eq=False) +class Surface: + """A triangle mesh. + + Parameters + ---------- + vertices : array-like + Coordinates with shape (n, 3). + triangles : array-like of int + Vertex indices with shape (m, 3). + properties : dict + Vertex properties, n values each. + cell_properties : dict + Triangle properties, m values each. + """ + + vertices: ArrayLike + triangles: ArrayLike + properties: dict[str, Property] = field(default_factory=dict) + cell_properties: dict[str, Property] = field(default_factory=dict) + + def __post_init__(self) -> None: + """Check the input and store it as numpy arrays.""" + verts = _vertices(self.vertices) + tris = _index_array(self.triangles, "triangles", 3, len(verts)) + object.__setattr__(self, "vertices", verts) + object.__setattr__(self, "triangles", tris) + object.__setattr__( + self, "properties", _properties(self.properties, len(verts), "properties") + ) + object.__setattr__( + self, + "cell_properties", + _properties(self.cell_properties, len(tris), "cell_properties"), + ) + + +@dataclass(frozen=True, eq=False) +class BlockModel: + """A regular grid of cells. + + Node and cell values are in x-fastest order. + + Parameters + ---------- + origin : array-like + The corner of the grid, shape (3,). + cell_sizes : array-like + The size of a cell on each axis, shape (3,). All values are above zero. + cells : array-like of int + The number of cells on each axis, shape (3,). All values are at least 1. + properties : dict + Node properties, (nx+1)*(ny+1)*(nz+1) values each. + cell_properties : dict + Cell properties, nx*ny*nz values each. + """ + + origin: ArrayLike + cell_sizes: ArrayLike + cells: ArrayLike + properties: dict[str, Property] = field(default_factory=dict) + cell_properties: dict[str, Property] = field(default_factory=dict) + + def __post_init__(self) -> None: + """Check the input and store it as numpy arrays.""" + origin = _vector3(self.origin, "origin") + sizes = _vector3(self.cell_sizes, "cell_sizes") + if np.any(sizes <= 0): + raise InvalidInputError("The field 'cell_sizes' must be above zero. Check the input.") + try: + raw = np.asarray(self.cells) + except (TypeError, ValueError) as exc: + raise InvalidInputError("The field 'cells' must be integers. Check the input.") from exc + if raw.shape != (3,): + raise InvalidInputError("The field 'cells' must have shape (3,). Check the input.") + if raw.dtype.kind == "f": + if not np.all(np.isfinite(raw)) or np.any(raw != np.round(raw)): + raise InvalidInputError("The field 'cells' must be integers. Check the input.") + raw = raw.astype(np.int64) + cells = _integer_array(raw, "cells") + if np.any(cells < 1): + raise InvalidInputError("The field 'cells' must be at least 1. Check the input.") + nodes = int(np.prod(cells + 1)) + count = int(np.prod(cells)) + object.__setattr__(self, "origin", origin) + object.__setattr__(self, "cell_sizes", sizes) + object.__setattr__(self, "cells", cells) + object.__setattr__(self, "properties", _properties(self.properties, nodes, "properties")) + object.__setattr__( + self, + "cell_properties", + _properties(self.cell_properties, count, "cell_properties"), + ) + + +@dataclass(frozen=True, eq=False) +class TetraMesh: + """A mesh of tetrahedra. + + Parameters + ---------- + vertices : array-like + Coordinates with shape (n, 3). + tetrahedra : array-like of int + Vertex indices with shape (m, 4). + properties : dict + Vertex properties, n values each. + cell_properties : dict + Tetrahedron properties, m values each. + """ + + vertices: ArrayLike + tetrahedra: ArrayLike + properties: dict[str, Property] = field(default_factory=dict) + cell_properties: dict[str, Property] = field(default_factory=dict) + + def __post_init__(self) -> None: + """Check the input and store it as numpy arrays.""" + verts = _vertices(self.vertices) + tets = _index_array(self.tetrahedra, "tetrahedra", 4, len(verts)) + object.__setattr__(self, "vertices", verts) + object.__setattr__(self, "tetrahedra", tets) + object.__setattr__( + self, "properties", _properties(self.properties, len(verts), "properties") + ) + object.__setattr__( + self, + "cell_properties", + _properties(self.cell_properties, len(tets), "cell_properties"), + ) + + +@dataclass(frozen=True, eq=False) +class Drillhole: + """A drillhole with a survey and intervals. + + Parameters + ---------- + collar : array-like + The collar position, shape (3,). + survey : array-like + Survey stations with shape (k, 3). + intervals : array-like + Interval start and end with shape (j, 2). + end_of_hole : float, optional + The depth of the end of the hole. + properties : dict + Survey station properties, k values each. + interval_properties : dict + Interval properties, j values each. + """ + + collar: ArrayLike + survey: ArrayLike + intervals: ArrayLike + end_of_hole: float | None = None + properties: dict[str, Property] = field(default_factory=dict) + interval_properties: dict[str, Property] = field(default_factory=dict) + + def __post_init__(self) -> None: + """Check the input and store it as numpy arrays.""" + collar = _vector3(self.collar, "collar") + survey = _vertices(self.survey, "survey") + try: + intervals = np.array(self.intervals, dtype=np.float64, copy=True) + except (TypeError, ValueError) as exc: + raise InvalidInputError( + "The field 'intervals' must be numbers. Check the input." + ) from exc + if intervals.ndim != 2 or intervals.shape[1] != 2: + raise InvalidInputError( + "The field 'intervals' must have shape (j, 2). Check the input." + ) + if not np.all(np.isfinite(intervals)): + raise InvalidInputError( + "The field 'intervals' must be finite numbers. Check the input." + ) + if self.end_of_hole is not None: + try: + eoh = float(self.end_of_hole) + except (TypeError, ValueError) as exc: + raise InvalidInputError( + "The field 'end_of_hole' must be a number. Check the input." + ) from exc + if not np.isfinite(eoh): + raise InvalidInputError( + "The field 'end_of_hole' must be a finite number. Check the input." + ) + object.__setattr__(self, "end_of_hole", eoh) + object.__setattr__(self, "collar", collar) + object.__setattr__(self, "survey", survey) + object.__setattr__(self, "intervals", intervals) + object.__setattr__( + self, "properties", _properties(self.properties, len(survey), "properties") + ) + object.__setattr__( + self, + "interval_properties", + _properties(self.interval_properties, len(intervals), "interval_properties"), + ) + + +SceneObject = Union[Points, Vectors, Lines, Surface, BlockModel, TetraMesh, Drillhole] diff --git a/packages/loop_link/src/loop_link/orientation.py b/packages/loop_link/src/loop_link/orientation.py new file mode 100644 index 000000000..9904d36cc --- /dev/null +++ b/packages/loop_link/src/loop_link/orientation.py @@ -0,0 +1,164 @@ +"""Convert between vectors and orientation angles. + +Convention: x is east, y is north, z is up. All angles are in degrees. +A plane has an upward normal. A lineation is an axis that points down. +""" + +from __future__ import annotations + +import numpy as np + +from loop_link.errors import InvalidInputError + +__all__ = [ + "directions_to_lineation", + "lineation_to_directions", + "normals_to_orientation", + "orientation_to_normals", +] + + +def _unit_vectors(vectors: object, name: str) -> np.ndarray: + """Return the input as unit vectors with shape (n, 3). + + Parameters + ---------- + vectors : array-like + Vectors with shape (n, 3) or (3,). + name : str + The name of the input. The name is used in error messages. + + Returns + ------- + numpy.ndarray + Unit vectors with shape (n, 3). + + Raises + ------ + InvalidInputError + If the shape is wrong, or a vector is zero-length or not finite. + """ + try: + arr = np.asarray(vectors, dtype=float) + except (TypeError, ValueError) as exc: + raise InvalidInputError(f"The {name} must be numbers. Check the input.") from exc + arr = np.atleast_2d(arr) + if arr.ndim != 2 or arr.shape[1] != 3: + raise InvalidInputError(f"The {name} must have shape (n, 3) or (3,). Check the input.") + if not np.all(np.isfinite(arr)): + raise InvalidInputError(f"The {name} must be finite numbers. Check the input.") + lengths = np.linalg.norm(arr, axis=1) + if not np.all(np.isfinite(lengths)) or np.any(lengths == 0.0): + raise InvalidInputError(f"The {name} must not have a zero-length vector. Check the input.") + return arr / lengths[:, None] + + +def _angles(x: np.ndarray, y: np.ndarray) -> np.ndarray: + """Return the azimuth of (x, y) in degrees, in [0, 360). + + The azimuth is 0.0 when x and y are both zero. + """ + flat = (x == 0.0) & (y == 0.0) + # Adding 0.0 turns -0.0 into 0.0. + azimuth = np.degrees(np.arctan2(np.where(flat, 0.0, x), np.where(flat, 1.0, y))) % 360.0 + 0.0 + # A tiny negative angle can round to 360.0 after the modulo. + azimuth = np.where(azimuth >= 360.0, 0.0, azimuth) + return azimuth + + +def normals_to_orientation(normals: object) -> tuple[np.ndarray, np.ndarray]: + """Convert plane normals to dip direction and dip. + + A downward normal is flipped to point up before the conversion. + + Parameters + ---------- + normals : array-like + Normal vectors with shape (n, 3) or (3,). + + Returns + ------- + dip_direction : numpy.ndarray + Dip direction in degrees, in [0, 360). + dip : numpy.ndarray + Dip in degrees, in [0, 90]. + + Raises + ------ + InvalidInputError + If a vector is zero-length or not finite. + """ + n = _unit_vectors(normals, "normals") + n = np.where(n[:, 2:3] < 0.0, -n, n) + dip = np.degrees(np.arccos(np.clip(n[:, 2], -1.0, 1.0))) + dip_direction = _angles(n[:, 0], n[:, 1]) + return dip_direction, dip + + +def directions_to_lineation(directions: object) -> tuple[np.ndarray, np.ndarray]: + """Convert line directions to trend and plunge. + + An upward direction is flipped to point down before the conversion. + + Parameters + ---------- + directions : array-like + Direction vectors with shape (n, 3) or (3,). + + Returns + ------- + trend : numpy.ndarray + Trend in degrees, in [0, 360). + plunge : numpy.ndarray + Plunge in degrees, in [0, 90]. + + Raises + ------ + InvalidInputError + If a vector is zero-length or not finite. + """ + d = _unit_vectors(directions, "directions") + d = np.where(d[:, 2:3] > 0.0, -d, d) + plunge = np.degrees(np.arcsin(np.clip(-d[:, 2], -1.0, 1.0))) + trend = _angles(d[:, 0], d[:, 1]) + return trend, plunge + + +def orientation_to_normals(dip_direction: object, dip: object) -> np.ndarray: + """Convert dip direction and dip to upward unit normals. + + Parameters + ---------- + dip_direction : array-like + Dip direction in degrees. + dip : array-like + Dip in degrees. + + Returns + ------- + numpy.ndarray + Unit normals with shape (n, 3). + """ + a = np.radians(np.atleast_1d(np.asarray(dip_direction, dtype=float))) + d = np.radians(np.atleast_1d(np.asarray(dip, dtype=float))) + return np.column_stack((np.sin(d) * np.sin(a), np.sin(d) * np.cos(a), np.cos(d) + 0.0 * a)) + + +def lineation_to_directions(trend: object, plunge: object) -> np.ndarray: + """Convert trend and plunge to downward unit direction vectors. + + Parameters + ---------- + trend : array-like + Trend in degrees. + plunge : array-like + Plunge in degrees. + + Returns + ------- + numpy.ndarray + Unit direction vectors with shape (n, 3). + """ + t = np.radians(np.atleast_1d(np.asarray(trend, dtype=float))) + p = np.radians(np.atleast_1d(np.asarray(plunge, dtype=float))) + return np.column_stack((np.cos(p) * np.sin(t), np.cos(p) * np.cos(t), -np.sin(p) + 0.0 * t)) diff --git a/packages/loop_link/src/loop_link/protocol.py b/packages/loop_link/src/loop_link/protocol.py new file mode 100644 index 000000000..c11c95624 --- /dev/null +++ b/packages/loop_link/src/loop_link/protocol.py @@ -0,0 +1,235 @@ +"""The binary frame codec of the loop_link protocol. + +A message is one binary frame. All numbers are little-endian:: + + [u32 header_len][JSON header, UTF-8][buffer 0][buffer 1]... + +The header lists the buffers in order. This module uses only numpy and the +standard library. +""" + +from __future__ import annotations + +import json +import math +import struct +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Any + +import numpy as np + +from .errors import LoopLinkError + +PROTOCOL_VERSION: dict[str, int] = {"major": 1, "minor": 14} +TOOL_PROTOCOL_VERSION: dict[str, int] = {"major": 1, "minor": 18} +CANCEL_PROTOCOL_VERSION: dict[str, int] = {"major": 1, "minor": 11} +# The version of the commands.list and command.run frames. +COMMAND_PROTOCOL_VERSION: dict[str, int] = {"major": 1, "minor": 11} + +# The largest frame that is allowed, in bytes. +MAX_FRAME_BYTES: int = 256 * 1024 * 1024 +# The largest JSON header that is allowed, in bytes. +MAX_HEADER_BYTES: int = 1024 * 1024 +# The largest object that is allowed, in bytes. The encoder in encode.py uses it. +MAX_OBJECT_BYTES: int = 2 * 1024**3 +# Beyond this distance from the origin an f32 coordinate is not exact to 1 mm. +F32_LIMIT: float = 4000.0 + +_LENGTH = struct.Struct(" bytes: + """Return the frame for a header and its named buffers. + + The function adds ``version`` and ``buffers`` to the header. + + Parameters + ---------- + header : dict + The header fields. The function does not change this dict. + buffers : sequence of (str, numpy.ndarray) + The named arrays. The dtype must be f32, f64, u32, i32 or u8. + version : dict, optional + The protocol version for the header. The default is ``PROTOCOL_VERSION``. + The function does not change this dict. + + Returns + ------- + bytes + The frame. + + Raises + ------ + ProtocolError + If a dtype is not supported, or the header or the frame is too large. + """ + descriptions = [] + payload = [] + for name, array in buffers: + array = np.ascontiguousarray(array) + little = array.dtype.newbyteorder("<") + dtype_name = _DTYPE_NAMES.get(little.str) + if dtype_name is None: + raise ProtocolError( + f"Buffer {name!r} has the type {array.dtype}, which is not supported. " + "Use f32, f64, u32, i32 or u8." + ) + descriptions.append({"name": name, "dtype": dtype_name, "shape": list(array.shape)}) + payload.append(array.astype(little, copy=False).tobytes()) + full = dict(header) + full["version"] = PROTOCOL_VERSION if version is None else dict(version) + full["buffers"] = descriptions + header_bytes = json.dumps(full, separators=(",", ":"), allow_nan=False).encode("utf-8") + if len(header_bytes) > MAX_HEADER_BYTES: + raise ProtocolError( + f"The header is {len(header_bytes)} bytes. The limit is {MAX_HEADER_BYTES} bytes." + ) + total = _LENGTH.size + len(header_bytes) + sum(len(part) for part in payload) + if total > MAX_FRAME_BYTES: + raise ProtocolError( + f"The frame is {total} bytes. The limit is {MAX_FRAME_BYTES} bytes. " + "Send smaller objects." + ) + return b"".join([_LENGTH.pack(len(header_bytes)), header_bytes, *payload]) + + +def _read_header(data: bytes) -> tuple[dict[str, Any], int]: + """Return the header and the offset where the buffers start.""" + if len(data) < _LENGTH.size: + raise ProtocolError("The frame is shorter than 4 bytes.") + (length,) = _LENGTH.unpack_from(data, 0) + if length > MAX_HEADER_BYTES: + raise ProtocolError( + f"The header length is {length} bytes. The limit is {MAX_HEADER_BYTES} bytes." + ) + end = _LENGTH.size + length + if end > len(data): + raise ProtocolError("The frame stops inside the header.") + try: + header = json.loads(data[_LENGTH.size : end].decode("utf-8")) + except (ValueError, RecursionError) as error: + raise ProtocolError(f"The header is not valid JSON: {error}") from error + if not isinstance(header, dict): + raise ProtocolError("The header is not a JSON object.") + return header, end + + +def decode_header(data: bytes) -> dict[str, Any]: + """Return the JSON header of a frame. The buffers are ignored. + + Parameters + ---------- + data : bytes + The frame. + + Returns + ------- + dict + The header. + + Raises + ------ + ProtocolError + If the frame is too short or the header is not valid. + """ + return _read_header(data)[0] + + +def decode_frame(data: bytes) -> Frame: + """Return the header and the arrays of a frame. + + Parameters + ---------- + data : bytes + The frame. + + Returns + ------- + Frame + The header and the named arrays. + + Raises + ------ + ProtocolError + If the frame is not valid, or its length does not match the header. + """ + if len(data) > MAX_FRAME_BYTES: + raise ProtocolError( + f"The frame is {len(data)} bytes. The limit is {MAX_FRAME_BYTES} bytes." + ) + header, offset = _read_header(data) + descriptions = header.get("buffers", []) + if not isinstance(descriptions, list): + raise ProtocolError("The header field 'buffers' is not a list.") + buffers: dict[str, np.ndarray] = {} + for entry in descriptions: + if not isinstance(entry, dict): + raise ProtocolError(f"A buffer description is not valid: {entry!r}.") + name = entry.get("name") + dtype_name = entry.get("dtype") + raw_shape = entry.get("shape") + if not isinstance(name, str): + raise ProtocolError(f"A buffer name is not a string: {name!r}.") + if name in buffers: + raise ProtocolError(f"The buffer name {name!r} is used more than once.") + if not isinstance(dtype_name, str) or dtype_name not in _NAME_DTYPES: + raise ProtocolError(f"Buffer {name!r} has an unknown dtype: {dtype_name!r}.") + if not isinstance(raw_shape, list) or any(type(n) is not int or n < 0 for n in raw_shape): + raise ProtocolError(f"Buffer {name!r} has a shape that is not valid: {raw_shape!r}.") + dtype = _NAME_DTYPES[dtype_name] + shape = tuple(raw_shape) + count = math.prod(shape) + size = count * dtype.itemsize + if offset + size > len(data): + raise ProtocolError(f"The frame stops inside buffer {name!r}.") + try: + buffers[name] = np.frombuffer(data, dtype=dtype, count=count, offset=offset).reshape( + shape + ) + except ValueError as error: + raise ProtocolError(f"Buffer {name!r} cannot be read: {error}") from error + offset += size + if offset != len(data): + raise ProtocolError(f"The frame is {len(data)} bytes. The header describes {offset} bytes.") + return Frame(header=header, buffers=buffers) diff --git a/packages/loop_link/src/loop_link/push.py b/packages/loop_link/src/loop_link/push.py new file mode 100644 index 000000000..052b878c3 --- /dev/null +++ b/packages/loop_link/src/loop_link/push.py @@ -0,0 +1,166 @@ +"""Push many objects to GeoViewer in one call. + +The module has no Qt code and no module state. The progress callback runs on the +calling thread. +""" + +from __future__ import annotations + +import threading +from collections.abc import Callable, Iterable +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any + +from loop_link.errors import InvalidInputError, ObjectTooLargeError, Refusal + +if TYPE_CHECKING: + from loop_link.viewer import Viewer + + +_OPTION_KEYS = ("name", "parent") + + +def _read_options(options: Any) -> dict[str, Any]: # noqa: ANN401 + """Check the options of one item and return them. + + Parameters + ---------- + options : Any + The third part of an item. It must be a dict with the keys ``name`` and + ``parent`` only. + + Returns + ------- + dict + The same options as a new dict. + + Raises + ------ + InvalidInputError + If ``options`` is not a dict or it has an unknown key. + """ + if not isinstance(options, dict): + raise InvalidInputError("The options of an object must be a dict.") + unknown = sorted(str(key) for key in options if key not in _OPTION_KEYS) + if unknown: + raise InvalidInputError( + f"Unknown options: {', '.join(unknown)}. Use only 'name' and 'parent'." + ) + return dict(options) + + +@dataclass +class PushResult: + """Result of one call to `push_objects`. + + Attributes + ---------- + sent : int + Number of objects sent to the viewer. + removed : int + Number of old objects removed from the viewer. + refused : list of Refusal + Messages that the viewer refused. + skipped : list of tuple of str + Pairs of object id and reason for each object that was not sent. + cancelled : bool + True when the cancel event stopped the push. + """ + + sent: int = 0 + removed: int = 0 + refused: list[Refusal] = field(default_factory=list) + skipped: list[tuple[str, str]] = field(default_factory=list) + cancelled: bool = False + + def summary(self) -> str: + """Return a short text that describes the result. + + Returns + ------- + str + The summary text. + """ + text = f"{self.sent} objects sent to GeoViewer" + if self.removed: + text += f", {self.removed} old objects removed" + if self.skipped: + text += f", {len(self.skipped)} objects skipped" + text += "." + if self.refused: + text += f" The viewer refused {len(self.refused)} messages." + return text + + +def push_objects( + viewer: Viewer, + objects: Iterable[tuple[Any, ...]], + *, + replace_prefix: str | None = None, + progress: Callable[[str], None] | None = None, + cancel: threading.Event | None = None, +) -> PushResult: + """Send objects to the viewer and report the result. + + Parameters + ---------- + viewer : Viewer + The viewer connection. The function connects it when it is not connected. + objects : iterable of tuple + Items of the form ``(id, obj)`` or ``(id, obj, options)``. ``options`` is a + dict with the optional keys ``name`` (display name) and ``parent`` (id of a + group). An unknown key, or an ``options`` value that is not a dict, skips + the item. + replace_prefix : str, optional + When given, the function removes each old object in the viewer inventory + whose id starts with this prefix and that this call did not send or skip. + The function never removes a group (an entry with the type ``Group``). + The function does not remove old objects when the push is cancelled. + progress : callable, optional + Called with a text before each object is sent. It runs on the calling thread. + cancel : threading.Event, optional + When this event is set, the push stops before the next object. + + Returns + ------- + PushResult + Counts, skipped objects and refusals. + + Raises + ------ + ViewerClosedError + If the viewer closes during the push. + BusyError + If the viewer is busy. + """ + result = PushResult() + if not viewer.connected: + viewer.connect() + kept_ids: set[str] = set() + for item in objects: + object_id, obj = item[0], item[1] + if cancel is not None and cancel.is_set(): + result.cancelled = True + break + if progress is not None: + progress(f"Sending {object_id}...") + try: + options = _read_options(item[2]) if len(item) > 2 else {} + viewer.send(obj, id=object_id, **options) + except (InvalidInputError, ObjectTooLargeError) as error: + result.skipped.append((object_id, str(error))) + kept_ids.add(object_id) + continue + kept_ids.add(object_id) + result.sent += 1 + if replace_prefix and not result.cancelled: + for entry in viewer.inventory(): + if ( + entry.id.startswith(replace_prefix) + and entry.id not in kept_ids + and entry.object_type != "Group" + ): + viewer.remove(entry.id) + result.removed += 1 + result.refused = viewer.flush(raise_on_refusal=False) + return result diff --git a/packages/loop_link/src/loop_link/selection.py b/packages/loop_link/src/loop_link/selection.py new file mode 100644 index 000000000..563f9fb24 --- /dev/null +++ b/packages/loop_link/src/loop_link/selection.py @@ -0,0 +1,215 @@ +"""The selection in the viewer: the ``Selection`` value and the ``SelectionWatcher``.""" + +from __future__ import annotations + +import threading +import weakref +from collections.abc import Callable +from dataclasses import dataclass +from types import TracebackType +from typing import TYPE_CHECKING + +import numpy as np + +from loop_link.protocol import Frame, ProtocolError + +if TYPE_CHECKING: + from loop_link.viewer import Viewer + +_KIND_FIELDS = {"cells": "cells", "nodes": "vertices"} + + +def _empty() -> np.ndarray: + """Return an empty ``uint32`` array.""" + return np.empty(0, dtype=np.uint32) + + +@dataclass(frozen=True, eq=False) +class Selection: + """The cells and vertices that are selected in the viewer. + + Parameters + ---------- + object_id : str or None + The identifier of the selected object. ``None`` when nothing is selected. + revision : int or None + The revision of the object when the selection was read. + cells : numpy.ndarray + The selected cell indices. A 1-D ``uint32`` array. + vertices : numpy.ndarray + The selected vertex indices. A 1-D ``uint32`` array. + """ + + object_id: str | None + revision: int | None + cells: np.ndarray + vertices: np.ndarray + + @property + def empty(self) -> bool: + """Return True when no cell and no vertex is selected.""" + return self.cells.size == 0 and self.vertices.size == 0 + + def same_as(self, other: Selection) -> bool: + """Return True when ``other`` selects the same indices of the same object. + + The order of the indices and the revision are not compared. + + Parameters + ---------- + other : Selection + The selection to compare with. + + Returns + ------- + bool + True when the object ids are equal and the sorted cells and the sorted + vertices are equal. + """ + return ( + self.object_id == other.object_id + and np.array_equal(np.sort(self.cells), np.sort(other.cells)) + and np.array_equal(np.sort(self.vertices), np.sort(other.vertices)) + ) + + +def parse_selection_result(frame: Frame) -> Selection: + """Return the selection in a ``selection.result`` frame. + + Parameters + ---------- + frame : Frame + The decoded ``selection.result`` frame. + + Returns + ------- + Selection + The selection. The entry kind ``cells`` gives ``cells``. The entry kind + ``nodes`` gives ``vertices``. + + Raises + ------ + ProtocolError + If an entry has a count but no buffer, a buffer is not ``uint32``, or the + length of a buffer is not the count. + """ + header = frame.header + arrays = {"cells": _empty(), "vertices": _empty()} + for entry in header.get("entries") or []: + field = _KIND_FIELDS.get(entry.get("kind")) + if field is None: + continue + count = int(entry.get("count", 0)) + name = entry.get("indices") + if name is None or name not in frame.buffers: + if count: + raise ProtocolError( + f"The selection entry '{entry.get('kind')}' has a count but no indices." + ) + continue + array = frame.buffers[name] + if array.dtype != np.uint32: + raise ProtocolError( + f"The selection indices '{name}' are {array.dtype}. They must be uint32." + ) + if array.ndim != 1 or array.shape[0] != count: + raise ProtocolError( + f"The selection indices '{name}' have shape {array.shape}. " + f"The entry count is {count}." + ) + # Copy, so the array is writeable and does not keep the frame bytes in memory. + arrays[field] = array.copy() + return Selection( + header.get("object"), header.get("revision"), arrays["cells"], arrays["vertices"] + ) + + +class SelectionWatcher: + """Poll the selection of a viewer and call a function when it changes. + + Only ``Viewer.watch_selection`` makes a watcher. The thread holds only a weak + reference to the viewer. + + Parameters + ---------- + viewer_ref : weakref.ref + A weak reference to the viewer. + callback : callable + The function to call with the new ``Selection`` at each change. + interval : float + The seconds between two polls. + last : Selection + The selection that counts as already seen. + """ + + def __init__( + self, + viewer_ref: weakref.ref[Viewer], + callback: Callable[[Selection], None], + interval: float, + last: Selection, + ) -> None: + self._viewer_ref = viewer_ref + self._callback = callback + self._interval = interval + self._last = last + self._stop_event = threading.Event() + self._error: BaseException | None = None + self._thread = threading.Thread( + target=self._run, name="loop-link-selection-poll", daemon=True + ) + + def start(self) -> None: + """Start the poll thread.""" + self._thread.start() + + @property + def running(self) -> bool: + """Return True when the poll thread is alive.""" + return self._thread.is_alive() + + @property + def error(self) -> BaseException | None: + """Return the exception that ended the thread, or None.""" + return self._error + + def stop(self) -> None: + """Stop the poll thread and wait for it. A second call does no harm.""" + self._stop_event.set() + if self._thread.is_alive() and self._thread is not threading.current_thread(): + self._thread.join(2 * self._interval + 1) + + def __enter__(self) -> SelectionWatcher: + """Return the watcher.""" + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + traceback: TracebackType | None, + ) -> None: + """Stop the watcher.""" + self.stop() + + def _run(self) -> None: + """Poll until stopped, until the viewer is gone, or until an error.""" + while not self._stop_event.wait(self._interval): + viewer = self._viewer_ref() + if viewer is None: + return + try: + selection = viewer.selection() + except Exception as error: + self._error = error + return + finally: + del viewer + if selection.same_as(self._last): + continue + self._last = selection + try: + self._callback(selection) + except Exception as error: + self._error = error + return diff --git a/packages/loop_link/src/loop_link/testing/__init__.py b/packages/loop_link/src/loop_link/testing/__init__.py new file mode 100644 index 000000000..d1d14f494 --- /dev/null +++ b/packages/loop_link/src/loop_link/testing/__init__.py @@ -0,0 +1,7 @@ +"""Test helpers for loop_link.""" + +from __future__ import annotations + +from .fake_viewer import FakeViewer, StoredObject + +__all__ = ["FakeViewer", "StoredObject"] diff --git a/packages/loop_link/src/loop_link/testing/fake_viewer.py b/packages/loop_link/src/loop_link/testing/fake_viewer.py new file mode 100644 index 000000000..e317fe101 --- /dev/null +++ b/packages/loop_link/src/loop_link/testing/fake_viewer.py @@ -0,0 +1,1587 @@ +"""A fake viewer for the tests: a WebSocket server on 127.0.0.1. + +The fake viewer does what the link of the real viewer does. It checks the bearer +token, answers ``hello`` with ``hello`` and ``scene.inventory``, and keeps the +objects that it receives. It has its own small server-side WebSocket code. +""" + +from __future__ import annotations + +import base64 +import copy +import hashlib +import json +import math +import os +import socket +import struct +import threading +import time +from collections.abc import Iterator, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import numpy as np + +from .. import protocol +from ..protocol import ( + MAX_FRAME_BYTES, + MAX_HEADER_BYTES, + MAX_OBJECT_BYTES, + Frame, + ProtocolError, +) + +_GUID = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + +# The geometry roles that each object type needs. +_REQUIRED_ROLES: dict[str, tuple[str, ...]] = { + "Points": ("vertices",), + "Curve": ("vertices", "segments"), + "Surface": ("vertices", "triangles"), + "TetraMesh": ("vertices", "tetrahedra"), + "BlockModel": (), + "Drillhole": ("collar", "survey", "intervals"), + "Group": (), +} +# The roles whose rows hold vertex indices, and the roles that hold coordinates. +_INDEX_ROLES = ("segments", "triangles", "tetrahedra") +_COORDINATE_ROLES = ("vertices", "collar", "survey") +# The roles that give the cell count of an object. +_CELL_ROLES = ("segments", "triangles", "tetrahedra") +# The row width that each geometry role needs. +_ROLE_WIDTH = { + "vertices": 3, + "survey": 3, + "intervals": 2, + "segments": 2, + "triangles": 3, + "tetrahedra": 4, +} + + +# The protocol names of the array types, by NumPy dtype name. +_PROTOCOL_DTYPES = { + "float32": "f32", + "float64": "f64", + "uint32": "u32", + "int32": "i32", + "uint8": "u8", +} + + +class _Closed(Exception): + """The peer closed the connection.""" + + +@dataclass +class StoredObject: + """An object that the fake viewer keeps. + + Parameters + ---------- + header : dict + The header of the ``scene.upsert`` frame. + buffers : dict of str to numpy.ndarray + The arrays of the frame, by name. + """ + + header: dict[str, Any] + buffers: dict[str, np.ndarray] = field(default_factory=dict) + + +def _error(code: str, message: str, object_id: object = None) -> Frame: + """Return an ``error`` frame.""" + header: dict[str, Any] = {"type": "error", "code": code, "message": message} + if object_id is not None: + header["object"] = object_id + return Frame(header=header, buffers={}) + + +def _encode(frame: Frame, version: dict[str, int] | None = None) -> bytes: + """Return the bytes of a frame, with ``version`` in the header if it is given.""" + return protocol.encode_frame(frame.header, list(frame.buffers.items()), version=version) + + +def _request_error( + request: object, code: str, message: str, field_name: str | None = None +) -> Frame: + """Return a ``request.error`` frame for a tool request.""" + error: dict[str, Any] = {"code": code, "message": message} + if field_name is not None: + error["field"] = field_name + return Frame(header={"type": "request.error", "request": request, "error": error}, buffers={}) + + +# The kinds of selection that each object type has. Drillhole and Group have none. +_SELECTION_KINDS: dict[str, tuple[str, ...]] = { + "Points": ("nodes",), + "Curve": ("nodes", "cells"), + "Surface": ("nodes", "cells"), + "BlockModel": ("nodes", "cells"), + "TetraMesh": ("nodes", "cells"), + "Drillhole": (), + "Group": (), +} + + +# The value types of the command inputs, with the JSON schema of each type. +_INPUT_SCHEMAS: dict[str, dict[str, Any]] = { + "str": {"type": "string"}, + "str_or_null": {"type": ["string", "null"]}, + "bool": {"type": "boolean"}, + "u32_list": {"type": "array", "items": {"type": "integer", "minimum": 0}}, + "colour": { + "type": ["array", "null"], + "items": {"type": "integer", "minimum": 0, "maximum": 255}, + "minItems": 3, + "maxItems": 3, + }, + "scale": {"type": "string", "enum": ["linear", "log"]}, + "edit": {"type": "object"}, +} +# The commands: (description, needs_window, {field: (value type, required)}). +_COMMANDS: dict[str, tuple[str, bool, dict[str, tuple[str, bool]]]] = { + "filter.edit": ( + "Change the filters of an object.", + False, + {"object": ("str", True), "edit": ("edit", True)}, + ), + "colour.set_active": ( + "Choose the array that colours an object.", + False, + {"id": ("str", True), "array": ("str_or_null", False)}, + ), + "colour.set_map": ( + "Choose the colour map of an object.", + False, + {"id": ("str", True), "name": ("str", True)}, + ), + "colour.set_range": ( + "Set the colour range of an object.", + False, + {"id": ("str", True), "min": ("str", True), "max": ("str", True)}, + ), + "colour.clear_range": ( + "Clear the colour range of an object.", + False, + {"id": ("str", True)}, + ), + "colour.set_scale": ( + "Set the colour scale of an object.", + True, + {"object": ("str", True), "scale": ("scale", True)}, + ), + "object.set_colour": ( + "Set the plain colour of an object, or clear it.", + False, + {"id": ("str", True), "colour": ("colour", True)}, + ), +} +# The fields of each kind of filter edit. +_EDIT_FIELDS: dict[str, dict[str, str]] = { + "add": {"array": "str"}, + "set_range": {"array": "str", "min": "str", "max": "str", "keep_nan": "bool"}, + "set_values": {"array": "str", "values": "u32_list"}, + "set_on": {"array": "str", "on": "bool"}, + "set_exclude": {"array": "str", "exclude": "bool"}, + "remove": {"array": "str"}, + "cancel": {}, +} +# The colour maps that the viewer lists from minor version 18. +_COLOUR_MAPS = ["viridis", "grey", "coolwarm"] +# The data types that have no colour map, range or scale. +_FIXED_COLOUR_TYPES = ("referenced", "boolean") + + +def _value_ok(kind: str, value: object) -> bool: + """Return whether ``value`` fits the input type ``kind``.""" + if kind == "str": + return isinstance(value, str) + if kind == "str_or_null": + return value is None or isinstance(value, str) + if kind == "bool": + return isinstance(value, bool) + if kind == "u32_list": + return isinstance(value, list) and all(type(v) is int and 0 <= v < 1 << 32 for v in value) + if kind == "colour": + return value is None or ( + isinstance(value, list) + and len(value) == 3 + and all(type(v) is int and 0 <= v <= 255 for v in value) + ) + if kind == "scale": + return value in ("linear", "log") + return isinstance(value, dict) + + +def _check_input(fields: dict[str, tuple[str, bool]], given: object) -> str | None: + """Return the name of the first bad field of a command input, or ``None``. + + A field is bad if it is unknown, missing, or of the wrong type. + """ + if not isinstance(given, dict): + return "input" + for key in given: + if key not in fields: + return str(key) + for key, (kind, required) in fields.items(): + if key not in given: + if required: + return key + elif not _value_ok(kind, given[key]): + return key + return None + + +def _check_edit(edit: dict[str, Any]) -> str | None: + """Return the name of the first bad field of a filter edit, or ``None``.""" + kind = edit.get("kind") + if not isinstance(kind, str) or kind not in _EDIT_FIELDS: + return "edit" + fields = {key: (value_kind, True) for key, value_kind in _EDIT_FIELDS[kind].items()} + fields["kind"] = ("str", True) + return _check_input(fields, edit) + + +def _send(conn: socket.socket, payload: bytes) -> None: + """Write one unmasked binary WebSocket frame.""" + length = len(payload) + if length < 126: + head = bytes([0x82, length]) + elif length < 1 << 16: + head = bytes([0x82, 126]) + struct.pack(">H", length) + else: + head = bytes([0x82, 127]) + struct.pack(">Q", length) + conn.sendall(head + payload) + + +class _Reader: + """Read masked client frames from a socket. + + Attributes + ---------- + deferred : list of bytes + Messages that a read-ahead took from the socket but that the viewer must + still handle, in arrival order. + """ + + def __init__(self, conn: socket.socket, buffer: bytes = b"") -> None: + self._conn = conn + self._buffer = buffer + self.deferred: list[bytes] = [] + + def _take(self, count: int) -> bytes: + while len(self._buffer) < count: + chunk = self._conn.recv(65536) + if not chunk: + raise _Closed + self._buffer += chunk + data, self._buffer = self._buffer[:count], self._buffer[count:] + return data + + def _frame(self) -> tuple[bool, int, bytes]: + """Return (fin, opcode, payload) of one WebSocket frame.""" + head = self._take(2) + fin = bool(head[0] & 0x80) + opcode = head[0] & 0x0F + length = head[1] & 0x7F + if not head[1] & 0x80: + raise _Closed + if length == 126: + (length,) = struct.unpack(">H", self._take(2)) + elif length == 127: + (length,) = struct.unpack(">Q", self._take(8)) + if length > MAX_FRAME_BYTES + MAX_HEADER_BYTES: + raise _Closed + key = self._take(4) + payload = self._take(length) + if length: + mask = np.frombuffer((key * (length // 4 + 1))[:length], dtype=np.uint8) + payload = (np.frombuffer(payload, dtype=np.uint8) ^ mask).tobytes() + return fin, opcode, payload + + def message(self) -> bytes | None: + """Return the next binary message, or ``None`` after a close frame. + + The method joins fragments and answers ping frames. It ignores text frames. + """ + parts: list[bytes] = [] + binary = False + while True: + fin, opcode, payload = self._frame() + if opcode == 0x8: + self._conn.sendall(bytes([0x88, 0])) + return None + if opcode == 0x9: + self._conn.sendall(bytes([0x8A, len(payload[:125])]) + payload[:125]) + continue + if opcode == 0xA: + continue + if opcode in (0x1, 0x2): + parts = [payload] + binary = opcode == 0x2 + elif opcode == 0x0: + parts.append(payload) + if fin: + if binary: + return b"".join(parts) + parts = [] + + +def _cell_count(arrays: dict[str, np.ndarray]) -> int | None: + """Return the number of segments, triangles or tetrahedra, or ``None``.""" + return next((arrays[r].shape[0] for r in _CELL_ROLES if r in arrays), None) + + +def _expected_length( + object_type: str, + association: object, + arrays: dict[str, np.ndarray], + params: object, + log_sets: object, +) -> int | None: + """Return the length that a data array needs, or ``None`` if it cannot fit.""" + if object_type == "BlockModel": + cells = params.get("cells") if isinstance(params, dict) else None + if not isinstance(cells, list) or not all(type(n) is int and n >= 0 for n in cells): + return None + if association == "cell": + return math.prod(cells) + if association == "vertex": + return math.prod(n + 1 for n in cells) + return None + if object_type == "Drillhole": + if association == "vertex" and "survey" in arrays: + return arrays["survey"].shape[0] + has_set = isinstance(log_sets, list) and any( + isinstance(item, dict) and item.get("kind") == "interval" for item in log_sets + ) + if association == "interval" and has_set and "intervals" in arrays: + return arrays["intervals"].shape[0] + return None + vertices = arrays.get("vertices") + if association == "vertex" and vertices is not None: + return vertices.shape[0] + if association == "cell" and object_type in ("Curve", "Surface", "TetraMesh"): + return _cell_count(arrays) + return None + + +def _check_data( + object_type: str, + entry: object, + arrays: dict[str, np.ndarray], + buffers: dict[str, np.ndarray], + params: object, + log_sets: object = None, +) -> str | None: + """Return the text of a problem in one data array entry, or ``None``. + + An ``interval`` array must name a log set of kind ``interval`` in ``log_set``. + """ + if not isinstance(entry, dict): + return "A data entry is not an object." + name = entry.get("buffer") + if name not in buffers: + return f"The data entry {entry.get('name')!r} names the buffer {name!r}, which is missing." + association = entry.get("association") + if association not in ("vertex", "cell", "interval"): + return f"The association {association!r} is not known." + if association == "interval": + log_set = entry.get("log_set") + kinds = { + item.get("name"): item.get("kind") + for item in (log_sets if isinstance(log_sets, list) else []) + if isinstance(item, dict) + } + if kinds.get(log_set) != "interval": + return ( + f"The interval array {name!r} names the log set {log_set!r}. " + "It needs a log set of kind 'interval' in 'log_sets'." + ) + length = buffers[name].shape[0] if buffers[name].ndim else 0 + if entry.get("data_type") == "text": + offsets_name = entry.get("offsets") + if offsets_name not in buffers: + return f"The text array {name!r} has no offsets buffer." + offsets = buffers[offsets_name].astype(np.int64) + if offsets.ndim != 1 or offsets.size < 1: + return f"The offsets of {name!r} are not valid." + if offsets[0] != 0 or offsets[-1] != length or np.any(np.diff(offsets) < 0): + return f"The offsets of {name!r} do not fit its {length} bytes." + length = offsets.size - 1 + expected = _expected_length(object_type, association, arrays, params, log_sets) + if expected is None: + return f"The association {association!r} does not fit the object type {object_type}." + if length != expected: + return f"The data array {name!r} has {length} values. The association needs {expected}." + return None + + +_GROUP_MEMBERS: dict[str, tuple[set[str], set[str]]] = { + "orientation": ({"dip_direction", "dip", "polarity"}, {"dip_direction", "dip"}), + "lineation": ({"trend", "plunge"}, {"trend", "plunge"}), +} + + +def _check_group(group: object, data_ids: list[Any]) -> str | None: + """Return the text of a problem in one property group, or ``None``.""" + if not isinstance(group, dict): + return "A property group is not an object." + members = group.get("members") or [] + for member in members: + if not isinstance(member, dict) or member.get("data") not in data_ids: + return f"The group {group.get('id')!r} names a data array that the object lacks." + role = group.get("role") + if role is None: + return None + if role not in _GROUP_MEMBERS: + return f"The group role {role!r} is not known." + allowed, required = _GROUP_MEMBERS[role] + roles = [member.get("role") for member in members] + if any(r not in allowed for r in roles): + return ( + f"The {role} group {group.get('id')!r} has a member role that the role does not list." + ) + if len(set(roles)) != len(roles) or not required <= set(roles): + return f"The {role} group {group.get('id')!r} needs each of {sorted(required)} once." + return None + + +class FakeViewer: + """A fake viewer that listens on ``127.0.0.1``. + + Parameters + ---------- + token : str + The bearer token that a client must send. + crs : str + The CRS that the viewer reports in ``hello``. + origin : tuple of float + The origin that the viewer reports in ``hello``. + kind : str + The kind of the viewer for the instance file, ``"window"`` or other. + heartbeat_timeout : float + The seconds without a frame after which a data connection is closed. + reply_errors : dict of str to str, optional + Object id to error text. The viewer refuses these objects. + read_delay : float + The seconds to wait after each frame. + protocol_minor : int + The minor protocol version of the tool endpoint. Below 18, the tool endpoint + answers each message with an ``unknown_message`` error. + part_bytes : int + The size in bytes of one part of an ``object.fetch`` reply. + fetch_delay : float + The seconds to wait between the parts of an ``object.fetch`` reply. + filter_delay : float + The seconds that the scene stays busy after a ``filter.edit`` that changes a filter. + For ``protocol_minor`` 20 or more, the seconds that a filter build takes. + busy_wait : float + The seconds that a waiting command waits for the busy time to end. After that, + the viewer answers ``busy``. + filter_stop_after : float, optional + For ``protocol_minor`` 20 or more, the seconds after which a filter build gives + the result ``{"status": "done", "state": "building"}``. The edit stays applied. + It has no effect if it is not shorter than the build. + + Attributes + ---------- + port : int + The port of the server. + objects : dict of str to StoredObject + The objects in the scene. + received : list of Frame + All frames that the viewer received on all connections. + tool_requests : list of Frame + All frames that the viewer received on the tool endpoint. + """ + + def __init__( + self, + token: str = "secret", + crs: str = "EPSG:28350", + origin: tuple[float, float, float] = (0.0, 0.0, 0.0), + kind: str = "window", + heartbeat_timeout: float = 15.0, + reply_errors: dict[str, str] | None = None, + read_delay: float = 0.0, + protocol_minor: int = 18, + part_bytes: int = 64 * 1024 * 1024, + fetch_delay: float = 0.0, + filter_delay: float = 0.0, + busy_wait: float = 5.0, + filter_stop_after: float | None = None, + ) -> None: + self.token = token + self.crs = crs + self.origin = origin + self.kind = kind + self.heartbeat_timeout = heartbeat_timeout + self.reply_errors = dict(reply_errors or {}) + self.read_delay = read_delay + self.protocol_minor = protocol_minor + self.part_bytes = part_bytes + self.fetch_delay = fetch_delay + self.filter_delay = filter_delay + self.busy_wait = busy_wait + self.filter_stop_after = filter_stop_after + self._filters: dict[str, dict[str, dict[str, Any]]] = {} + self._colouring: dict[str, dict[str, Any]] = {} + self._busy_until = 0.0 + self._selection: dict[str, Any] | None = None + self.tool_requests: list[Frame] = [] + self.objects: dict[str, StoredObject] = {} + self.received: list[Frame] = [] + self._lock = threading.Lock() + self._state_lock = threading.Lock() + self._data_connections = 0 + self._connections: set[socket.socket] = set() + self._server = socket.socket() + self._server.bind(("127.0.0.1", 0)) + self._server.listen(8) + self.port: int = self._server.getsockname()[1] + self._thread = threading.Thread(target=self._serve, daemon=True) + self._thread.start() + + def __enter__(self) -> FakeViewer: + """Return the viewer.""" + return self + + def __exit__(self, *exc: object) -> None: + """Close the viewer.""" + self.close() + + def close(self) -> None: + """Stop the server and close all connections.""" + try: + self._server.close() + except OSError: + pass + with self._lock: + connections = list(self._connections) + for conn in connections: + try: + conn.shutdown(socket.SHUT_RDWR) + except OSError: + pass + try: + conn.close() + except OSError: + pass + + # -- state -------------------------------------------------------------- + + def inventory(self) -> list[dict[str, Any]]: + """Return the inventory entries of the objects in the scene.""" + with self._state_lock: + items = list(self.objects.items()) + return [ + { + "id": object_id, + "object_type": stored.header.get("object_type"), + "revision": stored.header.get("revision", 1), + } + for object_id, stored in items + ] + + @property + def filters(self) -> dict[str, dict[str, dict[str, Any]]]: + """A copy of the filters, by object id and then by array name. + + A filter is a dict with the keys ``kind`` (``"range"``, ``"values"`` or ``None``), + ``on``, ``minimum``, ``maximum``, ``keep_nan``, ``values`` and ``exclude``. + """ + with self._state_lock: + return copy.deepcopy(self._filters) + + @property + def colouring(self) -> dict[str, dict[str, Any]]: + """A copy of the colouring, by object id. + + Each value is a dict with the keys ``array``, ``colour_map``, ``range``, + ``scale`` and ``plain``. + """ + with self._state_lock: + return copy.deepcopy(self._colouring) + + @property + def selection(self) -> dict[str, Any] | None: + """The selection, or ``None``. + + The dict has the keys ``object``, ``revision``, ``cells`` and ``nodes``. The + value of ``cells`` or ``nodes`` is a ``uint32`` array without repeats, or + ``None`` if the selection has no index of that kind. + """ + with self._state_lock: + return None if self._selection is None else dict(self._selection) + + def set_user_selection( + self, + object_id: str, + *, + cells: Sequence[int] | None = None, + nodes: Sequence[int] | None = None, + ) -> None: + """Select cells or nodes, as if the user did it in the window. + + Parameters + ---------- + object_id : str + The id of the object. + cells, nodes : sequence of int, optional + The indices to select. + + Raises + ------ + ValueError + If the object is not known, the object lacks a kind, or an index is out of range. + """ + kinds = { + kind: np.asarray(values, dtype=np.int64) + for kind, values in (("cells", cells), ("nodes", nodes)) + if values is not None + } + with self._state_lock: + problem = self._selection_problem(object_id, None, kinds) + if problem is not None: + raise ValueError(problem[1]) + self._store_selection(object_id, kinds) + + def _store_selection(self, object_id: str, kinds: dict[str, np.ndarray]) -> None: + """Replace the selection. The caller holds the state lock.""" + unique = { + kind: np.unique(values).astype(np.uint32) + for kind, values in kinds.items() + if values.size + } + if not unique: + self._selection = None + return + self._selection = { + "object": object_id, + "revision": self.objects[object_id].header.get("revision", 1), + "cells": unique.get("cells"), + "nodes": unique.get("nodes"), + } + + @staticmethod + def _element_count(stored: StoredObject, kind: str) -> int: + """Return the number of nodes or cells of an object.""" + header = stored.header + if header.get("object_type") == "BlockModel": + params = header.get("params") + shape = params.get("cells") if isinstance(params, dict) else None + shape = [int(n) for n in shape] if isinstance(shape, list) else [0, 0, 0] + if kind == "cells": + return math.prod(shape) + return math.prod(n + 1 for n in shape) + geometry = header.get("geometry") or {} + roles = ("vertices",) if kind == "nodes" else _CELL_ROLES + for role in roles: + if role in geometry and geometry[role] in stored.buffers: + return int(stored.buffers[geometry[role]].shape[0]) + return 0 + + def _selection_problem( + self, object_id: object, revision: object, kinds: dict[str, np.ndarray] + ) -> tuple[str, str] | None: + """Return (field, message) for the first problem of a selection, or ``None``. + + The caller holds the state lock. + """ + stored = self.objects.get(object_id) if isinstance(object_id, str) else None + if stored is None: + return "object", f"The object {object_id!r} is not in the scene." + current = stored.header.get("revision", 1) + if revision is not None and revision != current: + return "revision", f"The revision {revision!r} is not the revision {current}." + allowed = _SELECTION_KINDS.get(stored.header.get("object_type"), ()) + for kind, values in kinds.items(): + if kind not in allowed: + return "kind", f"The object {object_id!r} has no {kind}." + count = self._element_count(stored, kind) + if values.size and (int(values.min()) < 0 or int(values.max()) >= count): + return "indices", f"The {kind} need indices from 0 to {count - 1}." + return None + + def write_instance_file(self, settings: Path) -> Path: + """Write ``instances/.json`` in a settings folder and return its path. + + The method does not write ``link.json``. + """ + folder = Path(settings) / "instances" + folder.mkdir(parents=True, exist_ok=True) + path = folder / f"{os.getpid()}.json" + data = {"port": self.port, "kind": self.kind, "pid": os.getpid(), "focused": time.time()} + path.write_text(json.dumps(data), encoding="utf-8") + return path + + # -- frames ------------------------------------------------------------- + + def accept_frame(self, data: bytes) -> list[Frame]: + """Apply one data-client frame and return the reply frames. + + Parameters + ---------- + data : bytes + The frame from the client. + + Returns + ------- + list of Frame + The frames that the viewer sends back. The list can be empty. + """ + try: + frame = protocol.decode_frame(data) + except ProtocolError as error: + return [_error("invalid_frame", str(error))] + with self._state_lock: + self.received.append(frame) + header = frame.header + version = header.get("version") + major = version.get("major") if isinstance(version, dict) else None + if major != protocol.PROTOCOL_VERSION["major"]: + return [_error("unsupported_version", f"The version {version!r} is not supported.")] + kind = header.get("type") + if kind == "hello": + hello = { + "type": "hello", + "application": {"name": "fake-viewer"}, + "crs": self.crs, + "origin": list(self.origin), + } + inventory = {"type": "scene.inventory", "entries": self.inventory()} + return [Frame(header=hello, buffers={}), Frame(header=inventory, buffers={})] + if kind == "heartbeat": + return [] + if kind == "scene.upsert": + return self._upsert(frame) + if kind == "scene.remove": + with self._state_lock: + self.objects.pop(header.get("id"), None) + return [] + if kind == "scene.clear": + with self._state_lock: + self.objects.clear() + return [] + return [_error("unknown_message", f"The message type {kind!r} is not known.")] + + def _upsert(self, frame: Frame) -> list[Frame]: + """Check and keep one object.""" + header = frame.header + object_id = header.get("id") + if object_id in self.reply_errors: + return [_error("invalid_object", self.reply_errors[object_id], object_id)] + problem = self._check_object(frame) + if problem is not None: + return [_error("invalid_object", problem, object_id)] + names = {entry.get("name") for entry in header.get("data") or [] if isinstance(entry, dict)} + with self._state_lock: + self.objects[object_id] = StoredObject(header=header, buffers=dict(frame.buffers)) + kept = self._filters.get(object_id) + if kept is not None: + self._filters[object_id] = {k: v for k, v in kept.items() if k in names} + return [] + + @staticmethod + def _check_object(frame: Frame) -> str | None: + """Return the text of the first problem of an object, or ``None``.""" + header, buffers = frame.header, frame.buffers + object_id = header.get("id") + object_type = header.get("object_type") + if not isinstance(object_id, str): + return "The object has no id." + if object_type not in _REQUIRED_ROLES: + return f"The object type {object_type!r} is not known." + geometry = header.get("geometry") or {} + if not isinstance(geometry, dict): + return "The field 'geometry' is not an object." + for role in _REQUIRED_ROLES[object_type]: + if role not in geometry: + return f"The geometry role {role!r} is missing." + arrays: dict[str, np.ndarray] = {} + for role, name in geometry.items(): + if name not in buffers: + return f"The geometry role {role!r} names the buffer {name!r}, which is missing." + arrays[role] = buffers[name] + collar = arrays.get("collar") + if collar is not None and collar.shape not in ((3,), (1, 3)): + return f"The buffer for 'collar' has the shape {collar.shape}. It needs (3,) or (1, 3)." + for role, width in _ROLE_WIDTH.items(): + array = arrays.get(role) + if array is not None and (array.ndim != 2 or array.shape[1] != width): + return ( + f"The buffer for {role!r} has the shape {array.shape}. It needs (n, {width})." + ) + for role in _COORDINATE_ROLES: + array = arrays.get(role) + if array is not None and array.dtype.kind == "f" and not np.all(np.isfinite(array)): + return f"The buffer for {role!r} has a coordinate that is not finite." + if "vertices" in arrays: + vertices = arrays["vertices"] + count = vertices.shape[0] if vertices.ndim else 0 + for role in _INDEX_ROLES: + array = arrays.get(role) + if array is None or not array.size: + continue + if array.dtype.kind not in "iu": + return f"The buffer for {role!r} does not hold integers." + if int(array.min()) < 0 or int(array.max()) >= count: + return f"The buffer for {role!r} has an index outside 0 to {count - 1}." + revision = header.get("revision") + if type(revision) is not int or revision < 1: + return f"The revision {revision!r} is not an integer of 1 or more." + data = header.get("data") or [] + ids = [entry.get("id") for entry in data if isinstance(entry, dict)] + if len(set(ids)) != len(ids): + return "Two data arrays have the same id." + for entry in data: + problem = _check_data( + object_type, entry, arrays, buffers, header.get("params"), header.get("log_sets") + ) + if problem is not None: + return problem + for group in header.get("property_groups") or []: + problem = _check_group(group, ids) + if problem is not None: + return problem + for name, array in buffers.items(): + if array.size * array.itemsize != array.nbytes: + return f"The buffer {name!r} does not match its declared size." + size = sum(int(array.nbytes) for array in buffers.values()) + if size > MAX_OBJECT_BYTES: + return f"The object is {size} bytes. The limit is {MAX_OBJECT_BYTES} bytes." + return None + + def tool_frame(self, data: bytes) -> list[Frame]: + """Apply one tool-client frame and return the reply frames. + + Parameters + ---------- + data : bytes + The frame from the client. + + Returns + ------- + list of Frame + The frames that the viewer sends back. + """ + try: + frame = protocol.decode_frame(data) + except ProtocolError as error: + return [_error("invalid_frame", str(error))] + with self._state_lock: + self.tool_requests.append(frame) + return self._tool_reply(frame) + + def _tool_reply(self, frame: Frame) -> list[Frame]: + """Return the reply frames for one decoded tool-client frame. + + For ``object.fetch`` the list holds all reply frames. A real connection + uses ``_stream_fetch`` instead, which can stop on ``command.cancel``. + """ + kind = frame.header.get("type") + request = frame.header.get("request") + if self.protocol_minor >= 11 and kind == "commands.list": + return [self._commands_list(request)] + if self.protocol_minor >= 11 and kind == "command.run": + return [self._command_run(frame)] + if self.protocol_minor >= 18 and kind == "object.fetch": + return list(self._fetch_frames(frame)) + if self.protocol_minor >= 18 and kind in ("selection.set", "selection.get"): + if self.kind == "headless": + return [_request_error(request, "needs_window", "The viewer has no window.")] + if kind == "selection.get": + return [self._selection_get(request)] + return [self._selection_set(frame)] + return [_error("unknown_message", f"The message type {kind!r} is not known.")] + + def _commands_list(self, request: object) -> Frame: + """Return the ``commands`` frame for ``commands.list``.""" + entries = [] + for name, (description, needs_window, fields) in _COMMANDS.items(): + properties = {key: dict(_INPUT_SCHEMAS[kind]) for key, (kind, _) in fields.items()} + if name == "colour.set_map": + properties["name"] = ( + {"type": "string", "enum": list(_COLOUR_MAPS)} + if self.protocol_minor >= 18 + else {"type": "string"} + ) + entry: dict[str, Any] = { + "name": name, + "description": description, + "needs_window": needs_window, + "tool_available": True, + "unavailable_reason": None, + "input_schema": { + "type": "object", + "properties": properties, + "required": [key for key, (_, required) in fields.items() if required], + "additionalProperties": False, + }, + "result_schema": { + "type": "object", + "properties": { + "status": {"enum": ["done", "refused"]}, + "text": {"type": "string"}, + }, + "required": ["status"], + }, + } + if name == "filter.edit" and self.protocol_minor >= 20: + entry["long"] = True + entries.append(entry) + header = {"type": "commands", "request": request, "viewer": self.kind, "commands": entries} + return Frame(header=header, buffers={}) + + def _wait_if_busy(self, command: str) -> bool: + """Wait for the busy time to end. Return ``False`` if the command must get ``busy``. + + ``colour.set_scale`` does not wait. It gets ``busy`` at once. Other commands wait + at most ``busy_wait`` seconds. + """ + with self._state_lock: + remaining = self._busy_until - time.monotonic() + if remaining <= 0: + return True + if command == "colour.set_scale": + return False + time.sleep(min(remaining, self.busy_wait)) + return remaining <= self.busy_wait + + def _command_problem(self, frame: Frame) -> Frame | None: + """Check the input and the object of a command. Return a ``request.error`` or ``None``.""" + request = frame.header.get("request") + command = frame.header.get("command") + spec = _COMMANDS.get(command) if isinstance(command, str) else None + if spec is None: + return _request_error( + request, "invalid_input", f"The command {command!r} is not known." + ) + _, needs_window, fields = spec + given = frame.header.get("input") + bad = _check_input(fields, given) + if bad is None and command == "filter.edit": + bad = _check_edit(given["edit"]) + if bad is not None: + return _request_error( + request, "invalid_input", f"The input field {bad!r} is not valid.", bad + ) + id_field = "object" if "object" in fields else "id" + with self._state_lock: + known = given[id_field] in self.objects + if not known: + return _request_error( + request, + "invalid_input", + f"The object {given[id_field]!r} is not in the scene.", + id_field, + ) + if needs_window and self.kind == "headless": + return _request_error(request, "needs_window", "The viewer has no window.") + return None + + def _command_run(self, frame: Frame) -> Frame: + """Check and run one command. Return the ``command.result`` or ``request.error`` frame.""" + problem = self._command_problem(frame) + if problem is not None: + return problem + request = frame.header.get("request") + command = frame.header.get("command") + given = frame.header["input"] + cancel = command == "filter.edit" and given["edit"]["kind"] == "cancel" + if not cancel and not self._wait_if_busy(command): + return _request_error(request, "busy", "The scene is busy with a filter change.") + if command == "filter.edit": + result = self._filter_edit(given["object"], given["edit"]) + else: + result = self._colour_command(command, given) + header = {"type": "command.result", "request": request, "result": result} + return Frame(header=header, buffers={}) + + def _filter_edit(self, object_id: str, edit: dict[str, Any]) -> dict[str, Any]: + """Apply one filter edit and return the result dict. + + ``add`` makes an off filter. Its kind is ``"values"`` for a ``referenced`` or + ``boolean`` array, and ``"range"`` for other arrays. The ``set_*`` edits change + a filter that exists. ``remove`` deletes a filter. ``cancel`` ends the busy time. + An edit that changes a filter starts the busy time. + """ + kind = edit["kind"] + if kind == "cancel": + with self._state_lock: + self._busy_until = 0.0 + return {"status": "done"} + array = edit["array"] + with self._state_lock: + entries = { + e.get("name"): e + for e in self.objects[object_id].header.get("data") or [] + if isinstance(e, dict) + } + entry = entries.get(array) + filters = self._filters.setdefault(object_id, {}) + if kind == "add": + if entry is None: + return {"status": "refused", "text": f"The object has no array {array!r}."} + if entry.get("data_type") == "text" or entry.get("association") == "object": + return { + "status": "refused", + "text": f"The array {array!r} cannot have a filter.", + } + by_values = entry.get("data_type") in _FIXED_COLOUR_TYPES + filters[array] = { + "kind": "values" if by_values else "range", + "on": False, + "minimum": None, + "maximum": None, + "keep_nan": False, + "values": [], + "exclude": False, + } + elif kind == "remove": + if filters.pop(array, None) is None: + return {"status": "done"} + else: + state = filters.get(array) + if state is None: + return {"status": "refused", "text": f"The array {array!r} has no filter."} + if kind == "set_range": + if state["kind"] != "range": + return { + "status": "refused", + "text": f"The array {array!r} has no range filter.", + } + try: + state["minimum"] = float(edit["min"]) + state["maximum"] = float(edit["max"]) + except ValueError: + return {"status": "refused", "text": "The range is not a number."} + state["keep_nan"] = edit["keep_nan"] + elif kind == "set_values": + if state["kind"] != "values": + return { + "status": "refused", + "text": f"The array {array!r} has no values filter.", + } + state["values"] = list(edit["values"]) + elif kind == "set_on": + state["on"] = edit["on"] + else: + state["exclude"] = edit["exclude"] + if self.protocol_minor < 20: + self._busy_until = time.monotonic() + self.filter_delay + return {"status": "done"} + + def _filter_counts(self, object_id: str, array: str) -> tuple[int, int]: + """Return ``(passing, total)`` for the array ``array`` of an object. + + The count uses the filters that are on and that have the association of the + array. A range filter keeps ``minimum <= v <= maximum``, and NaN only if + ``keep_nan`` is set. A values filter keeps the listed codes, or all other + codes if ``exclude`` is set. + """ + with self._state_lock: + stored = self.objects[object_id] + entries = { + e.get("name"): e for e in stored.header.get("data") or [] if isinstance(e, dict) + } + filters = copy.deepcopy(self._filters.get(object_id, {})) + buffers = stored.buffers + entry = entries[array] + total = int(buffers[entry["buffer"]].shape[0]) + keep = np.ones(total, dtype=bool) + for name, state in filters.items(): + other = entries.get(name) + if not state["on"] or other is None: + continue + if other.get("association") != entry.get("association"): + continue + values = buffers[other["buffer"]] + if state["kind"] == "range": + passed = (values >= state["minimum"]) & (values <= state["maximum"]) + if state["keep_nan"]: + passed = passed | np.isnan(values) + else: + passed = np.isin(values, state["values"]) + if state["exclude"]: + passed = ~passed + keep &= passed + return int(keep.sum()), total + + def _build(self, conn: socket.socket, reader: _Reader, request: object) -> str: + """Send ``command.progress`` frames for one filter build. + + The method sends a frame about every 0.1 s and reads a possible + ``command.cancel`` between them. It returns ``"cancelled"`` on cancel, + ``"stopped"`` when ``filter_stop_after`` ends the wait, and ``"done"`` at + the end of the build. + """ + version = protocol.TOOL_PROTOCOL_VERSION + stop = self.filter_stop_after + if stop is not None and stop >= self.filter_delay: + stop = None + started = time.monotonic() + fraction = 0.0 + while True: + progress = { + "type": "command.progress", + "request": request, + "fraction": fraction, + "text": "filter.edit", + } + _send(conn, _encode(Frame(header=progress, buffers={}), version)) + if fraction >= 1.0: + return "done" + end = self.filter_delay if stop is None else stop + wait = min(0.1, end - (time.monotonic() - started)) + if wait > 0: + time.sleep(wait) + if self._cancelled(conn, reader, request): + return "cancelled" + elapsed = time.monotonic() - started + if stop is not None and elapsed >= stop: + return "stopped" + fraction = min(1.0, elapsed / self.filter_delay) + + def _filter_request(self, data: bytes) -> Frame | None: + """Return the frame if ``data`` is a ``filter.edit`` that this viewer builds in steps. + + The method also keeps the frame in ``tool_requests``. It returns ``None`` below + protocol 1.20 and for other messages. + """ + if self.protocol_minor < 20: + return None + try: + frame = protocol.decode_frame(data) + except ProtocolError: + return None + if frame.header.get("type") != "command.run": + return None + if frame.header.get("command") != "filter.edit": + return None + with self._state_lock: + self.tool_requests.append(frame) + return frame + + def _stream_filter(self, conn: socket.socket, reader: _Reader, frame: Frame) -> None: + """Run one ``filter.edit`` and send ``command.progress`` frames during a build. + + A build runs when the edit is ``set_range``, ``set_values``, ``set_exclude`` or + ``set_on``, the filter is on after the edit and ``filter_delay`` is above 0. On + ``command.cancel``, the method restores the filters of the object and sends + ``cancelled``. If ``filter_stop_after`` is shorter than the build, the result is + ``{"status": "done", "state": "building"}`` at that time. At the end of a build, + and for an edit with no build, the result has ``passing`` and ``total``. + """ + version = protocol.TOOL_PROTOCOL_VERSION + request = frame.header.get("request") + problem = self._command_problem(frame) + if problem is not None: + _send(conn, _encode(problem, version)) + return + given = frame.header["input"] + object_id = given["object"] + edit = given["edit"] + with self._state_lock: + before = copy.deepcopy(self._filters.get(object_id)) + result = self._filter_edit(object_id, edit) + on = False + if result["status"] == "done" and edit["kind"].startswith("set_"): + with self._state_lock: + on = self._filters[object_id][edit["array"]]["on"] + # ``set_on`` always gives the count. Other edits give it only if the filter is on. + if result["status"] == "done" and (on or edit["kind"] == "set_on"): + array = edit["array"] + outcome = "done" + if on and self.filter_delay > 0: + outcome = self._build(conn, reader, request) + if outcome == "cancelled": + with self._state_lock: + if before is None: + self._filters.pop(object_id, None) + else: + self._filters[object_id] = before + error = _request_error(request, "cancelled", "The client cancelled the request.") + _send(conn, _encode(error, version)) + return + if outcome == "stopped": + result = {"status": "done", "state": "building"} + else: + passing, total = self._filter_counts(object_id, array) + result = {"status": "done", "passing": passing, "total": total} + header = {"type": "command.result", "request": request, "result": result} + _send(conn, _encode(Frame(header=header, buffers={}), version)) + + def _colour_command(self, command: str, given: dict[str, Any]) -> dict[str, Any]: + """Run one colour command and return its result dict.""" + object_id = given["object"] if command == "colour.set_scale" else given["id"] + with self._state_lock: + stored = self.objects[object_id] + state = self._colouring.setdefault( + object_id, + { + "array": None, + "colour_map": None, + "range": None, + "scale": "linear", + "plain": None, + }, + ) + entries = { + e.get("name"): e for e in stored.header.get("data") or [] if isinstance(e, dict) + } + if command == "colour.set_active": + array = given.get("array") + if array is not None and array not in entries: + return { + "status": "refused", + "text": f"The object {object_id!r} has no array {array!r}.", + } + state["array"] = array + elif command == "colour.clear_range": + state["range"] = None + elif command == "object.set_colour": + colour = given["colour"] + state["plain"] = None if colour is None else list(colour) + else: + active = entries.get(state["array"]) + if active is not None and active.get("data_type") in _FIXED_COLOUR_TYPES: + return { + "status": "refused", + "text": f"The array {state['array']!r} has a fixed colouring.", + } + if command == "colour.set_map": + if self.protocol_minor >= 18 and given["name"] not in _COLOUR_MAPS: + return { + "status": "refused", + "text": f"The colour map {given['name']!r} is not known.", + } + state["colour_map"] = given["name"] + elif command == "colour.set_range": + try: + state["range"] = (float(given["min"]), float(given["max"])) + except ValueError: + return {"status": "refused", "text": "The range is not a number."} + else: + state["scale"] = given["scale"] + return {"status": "done"} + + def _selection_get(self, request: object) -> Frame: + """Return the ``selection.result`` frame for ``selection.get``.""" + header: dict[str, Any] = {"type": "selection.result", "request": request, "entries": []} + buffers: dict[str, np.ndarray] = {} + with self._state_lock: + current = self._selection + if current is not None: + header["object"] = current["object"] + header["revision"] = current["revision"] + for kind in ("cells", "nodes"): + values = current[kind] + if values is not None: + header["entries"].append( + {"kind": kind, "count": int(values.size), "indices": kind} + ) + buffers[kind] = np.asarray(values, dtype=np.uint32) + return Frame(header=header, buffers=buffers) + + def _selection_set(self, frame: Frame) -> Frame: + """Check and keep a selection. Return the reply to ``selection.set``.""" + header = frame.header + request = header.get("request") + object_id = header.get("object") + entries = header.get("entries") + if not isinstance(entries, list): + return _request_error(request, "invalid_input", "The entries are missing.", "entries") + kinds: dict[str, np.ndarray] = {} + for item in entries: + name = item.get("indices") if isinstance(item, dict) else None + array = frame.buffers.get(name) if isinstance(name, str) else None + if array is None or array.dtype != np.dtype("uint32") or array.ndim != 1: + return _request_error( + request, "invalid_input", "An entry needs a u32 buffer of indices.", "indices" + ) + kinds[item.get("kind")] = array.astype(np.int64) + with self._state_lock: + problem = self._selection_problem(object_id, header.get("revision"), kinds) + if problem is not None: + return _request_error(request, "invalid_input", problem[1], problem[0]) + self._store_selection(object_id, kinds) + revision = self.objects[object_id].header.get("revision", 1) + result: dict[str, Any] = { + "type": "selection.result", + "request": request, + "object": object_id, + "revision": revision, + "entries": [ + {"kind": kind, "count": int(np.unique(values).size)} + for kind, values in kinds.items() + ], + } + return Frame(header=result, buffers={}) + + def _fetch_frames(self, frame: Frame) -> Iterator[Frame]: + """Yield the reply frames of ``object.fetch``. + + The frames are the ``object.header`` frame, the ``object.part`` frames of each + array in order (each followed by ``command.progress`` if there is more than one + part), and the ``object.end`` frame. An unknown id gives one ``request.error``. + """ + request = frame.header.get("request") + object_id = frame.header.get("id") + with self._state_lock: + stored = self.objects.get(object_id) if isinstance(object_id, str) else None + if stored is None: + header = None + buffers: dict[str, np.ndarray] = {} + else: + header = dict(stored.header, buffers=[]) + header["data"] = [ + {"offsets": None, "value_map": None, "colour_map": None, **entry} + for entry in stored.header.get("data") or [] + ] + buffers = dict(stored.buffers) + if header is None: + yield _request_error( + request, "invalid_input", f"The object {object_id!r} is not in the scene.", "id" + ) + return + step = max(8, self.part_bytes // 8 * 8) + raw = { + name: np.ascontiguousarray(array) + .astype(array.dtype.newbyteorder("<"), copy=False) + .tobytes() + for name, array in buffers.items() + } + total = sum(-(-len(data) // step) for data in raw.values()) + arrays = [ + { + "name": name, + "dtype": _PROTOCOL_DTYPES[array.dtype.name], + "shape": [int(n) for n in array.shape], + } + for name, array in buffers.items() + ] + yield Frame( + header={ + "type": "object.header", + "request": request, + "origin": list(self.origin), + "crs": self.crs, + "object": header, + "arrays": arrays, + }, + buffers={}, + ) + sent = 0 + for name, data in raw.items(): + for offset in range(0, len(data), step): + chunk = data[offset : offset + step] + sent += 1 + yield Frame( + header={ + "type": "object.part", + "request": request, + "array": name, + "offset": offset, + "bytes": len(chunk), + }, + buffers={"part": np.frombuffer(chunk, dtype=np.uint8)}, + ) + if total > 1: + progress = { + "type": "command.progress", + "request": request, + "fraction": sent / total, + "text": f"Part {sent} of {total}", + } + yield Frame(header=progress, buffers={}) + yield Frame(header={"type": "object.end", "request": request, "parts": total}, buffers={}) + + def _stream_fetch(self, conn: socket.socket, reader: _Reader, frame: Frame) -> None: + """Send the reply to ``object.fetch`` and read between the parts. + + After the header and after each part, the method waits at most 0.001 s for a + message (an object without parts has the header only). If it is a + ``command.cancel`` with the same request, it sends ``cancelled`` and stops. + """ + request = frame.header.get("request") + for reply in self._fetch_frames(frame): + _send(conn, _encode(reply, protocol.TOOL_PROTOCOL_VERSION)) + if reply.header["type"] not in ("object.header", "object.part"): + continue + if self.fetch_delay: + time.sleep(self.fetch_delay) + if self._cancelled(conn, reader, request): + error = _request_error(request, "cancelled", "The client cancelled the request.") + _send(conn, _encode(error, protocol.TOOL_PROTOCOL_VERSION)) + return + + @staticmethod + def _cancelled(conn: socket.socket, reader: _Reader, request: object) -> bool: + """Return whether a ``command.cancel`` for ``request`` arrives within 0.001 s. + + A message that is not a ``command.cancel`` is kept in ``reader.deferred``. + The viewer handles it after the current work, as a real viewer does. A + ``command.cancel`` for another request is dropped. + """ + previous = conn.gettimeout() + conn.settimeout(0.001) + try: + data = reader.message() + except (TimeoutError, BlockingIOError): + return False + finally: + conn.settimeout(previous) + if data is None: + raise _Closed + try: + header = protocol.decode_frame(data).header + except ProtocolError: + reader.deferred.append(data) + return False + if header.get("type") != "command.cancel": + reader.deferred.append(data) + return False + return header.get("request") == request + + # -- server ------------------------------------------------------------- + + def _serve(self) -> None: + """Accept connections, each in its own thread.""" + while True: + try: + conn, _ = self._server.accept() + except OSError: + return + with self._lock: + self._connections.add(conn) + threading.Thread(target=self._connection, args=(conn,), daemon=True).start() + + def _connection(self, conn: socket.socket) -> None: + """Run one connection until it ends.""" + is_data = False + try: + opened = self._handshake(conn) + if opened is None: + return + path, reader = opened + if path.split("?")[0] == "/tool": + self._run(conn, reader, tool=True) + return + with self._lock: + busy = self._data_connections > 0 + if not busy: + self._data_connections += 1 + is_data = True + if busy: + refusal = _error("busy", "Another client is connected.") + _send(conn, _encode(refusal)) + conn.sendall(bytes([0x88, 0])) + self._drain(conn) + return + conn.settimeout(self.heartbeat_timeout) + self._run(conn, reader, tool=False) + except (_Closed, OSError): + pass + finally: + if is_data: + with self._lock: + self._data_connections -= 1 + with self._lock: + self._connections.discard(conn) + try: + conn.close() + except OSError: + pass + + @staticmethod + def _drain(conn: socket.socket) -> None: + """Stop sending, then read until the peer closes or 0.5 s pass. + + This stops a reset from the system that would destroy the last frames. + """ + try: + conn.shutdown(socket.SHUT_WR) + conn.settimeout(0.5) + while conn.recv(65536): + pass + except OSError: + pass + + def _handshake(self, conn: socket.socket) -> tuple[str, _Reader] | None: + """Read the HTTP upgrade request. Return the path and a reader, or ``None``.""" + data = b"" + while b"\r\n\r\n" not in data: + chunk = conn.recv(4096) + if not chunk: + return None + data += chunk + head, _, rest = data.partition(b"\r\n\r\n") + lines = head.decode("latin-1").split("\r\n") + parts = lines[0].split(" ") + path = parts[1] if len(parts) > 1 else "/" + headers = { + k.strip().lower(): v.strip() for k, _, v in (line.partition(":") for line in lines[1:]) + } + if headers.get("authorization") != f"Bearer {self.token}": + conn.sendall(b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n") + return None + key = headers.get("sec-websocket-key") + if key is None: + conn.sendall(b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n") + return None + accept = base64.b64encode(hashlib.sha1(key.encode() + _GUID).digest()).decode() + conn.sendall( + ( + "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n" + f"Connection: Upgrade\r\nSec-WebSocket-Accept: {accept}\r\n\r\n" + ).encode() + ) + return path, _Reader(conn, rest) + + def _fetch_request(self, data: bytes) -> Frame | None: + """Return the frame if ``data`` is an ``object.fetch`` that this viewer supports. + + The method also keeps the frame in ``tool_requests``. + """ + if self.protocol_minor < 18: + return None + try: + frame = protocol.decode_frame(data) + except ProtocolError: + return None + if frame.header.get("type") != "object.fetch": + return None + with self._state_lock: + self.tool_requests.append(frame) + return frame + + def _run(self, conn: socket.socket, reader: _Reader, tool: bool) -> None: + """Read messages and send the replies. + + The method handles the messages in ``reader.deferred`` first, in order. + """ + while True: + data = reader.deferred.pop(0) if reader.deferred else reader.message() + if data is None: + return + if tool: + fetch = self._fetch_request(data) + if fetch is not None: + self._stream_fetch(conn, reader, fetch) + continue + edit = self._filter_request(data) + if edit is not None: + self._stream_filter(conn, reader, edit) + continue + for reply in self.tool_frame(data): + _send(conn, _encode(reply, protocol.TOOL_PROTOCOL_VERSION)) + else: + for reply in self.accept_frame(data): + _send(conn, _encode(reply)) + if self.read_delay: + time.sleep(self.read_delay) diff --git a/packages/loop_link/src/loop_link/tool.py b/packages/loop_link/src/loop_link/tool.py new file mode 100644 index 000000000..f066f4cda --- /dev/null +++ b/packages/loop_link/src/loop_link/tool.py @@ -0,0 +1,343 @@ +"""The tool connection: one request and its reply frames on the ``/tool`` path of the viewer.""" + +from __future__ import annotations + +import threading +import time +from collections.abc import Callable, Mapping, Sequence +from pathlib import Path +from typing import Any, NoReturn + +from loop_link import discovery, encode, protocol +from loop_link._websocket import WebSocketClient, WebSocketClosed, WebSocketError +from loop_link.errors import ( + BusyError, + CancelledError, + InvalidInputError, + MissingFeatureError, + Refusal, + StaleRevisionError, + ViewerClosedError, + ViewerRefusedError, +) +from loop_link.protocol import Frame, ProtocolError + +_LINK_ERRORS = (OSError, WebSocketClosed, WebSocketError) +_POLL = 0.1 + + +def raise_for_request_error(error: Mapping[str, Any], *, object_id: str | None) -> NoReturn: + """Raise the loop_link error that matches a ``request.error`` body. + + Parameters + ---------- + error : mapping + The ``error`` body of the frame, with the keys ``code``, ``message`` and ``field``. + object_id : str, optional + The identifier of the object that the request is about. + + Raises + ------ + loop_link.errors.StaleRevisionError + The code is ``invalid_input`` and the field is ``revision``. + loop_link.errors.InvalidInputError + The code is ``invalid_input`` and the field is another field. + loop_link.errors.MissingFeatureError + The code is ``needs_window``. + loop_link.errors.CancelledError + The code is ``cancelled``. + loop_link.errors.BusyError + The code is ``busy``. + loop_link.errors.ViewerRefusedError + The code is another code. + """ + code = str(error.get("code", "")) + message = str(error.get("message", "")) + if code == "invalid_input": + if error.get("field") == "revision": + raise StaleRevisionError(object_id or "") + raise InvalidInputError(f"The viewer refused the request: {message}") + if code == "needs_window": + raise MissingFeatureError("a viewer window (this viewer has no window)") + if code == "cancelled": + raise CancelledError + if code == "busy": + raise BusyError + raise ViewerRefusedError([Refusal(object_id or "", code, message)]) + + +class ToolConnection: + """A connection to the ``/tool`` path of the viewer. + + The connection sends one request at a time. It opens when the first request needs it. + + Parameters + ---------- + port : int, optional + The port of the viewer. The default is to search for it. + token : str, optional + The access token. The default is to read it from the environment or the settings. + host : str + The host of the viewer. + settings_dir : pathlib.Path, optional + The settings folder of the viewer. + timeout : float + The time in seconds to wait for the connection and for each reply frame. + resolve : callable, optional + Returns the address of the viewer. When it is given, the connection uses it in + place of its own search, so that it connects to the same viewer as another + connection. The other address parameters are then not used. + """ + + def __init__( + self, + *, + port: int | None = None, + token: str | None = None, + host: str = "127.0.0.1", + settings_dir: Path | None = None, + timeout: float = 5.0, + resolve: Callable[[], discovery.ViewerAddress] | None = None, + ) -> None: + self._resolve = resolve + self._port = port + self._token = token + self._host = host + self._settings_dir = settings_dir + self._timeout = timeout + self._lock = threading.Lock() + self._client: WebSocketClient | None = None + self._number = 0 + + @property + def connected(self) -> bool: + """True while the connection is open.""" + return self._client is not None + + def connect(self) -> ToolConnection: + """Connect to the ``/tool`` path of the viewer. No ``hello`` is sent. + + Raises + ------ + loop_link.errors.NoViewerError + No viewer was found. + loop_link.errors.TokenError + The viewer refused the token. + + Returns + ------- + ToolConnection + The connection itself. + """ + with self._lock: + self._connect_locked() + return self + + def close(self) -> None: + """Close the connection. It is safe to call it more than one time.""" + with self._lock: + self._drop_locked() + + def request( + self, + build: Callable[[int], bytes], + *, + until: Sequence[str], + feature: str, + object_id: str | None = None, + on_frame: Callable[[Frame], None] | None = None, + progress: Callable[[float], None] | None = None, + cancel: threading.Event | None = None, + timeout: float | None = None, + ) -> Frame: + """Send one request and read frames until the reply ends. + + Parameters + ---------- + build : callable + Gets the request number and returns the frame to send. + until : sequence of str + The frame types that end the request. The matching frame is returned. + feature : str + The name of the feature, for the error when the viewer does not know the message. + object_id : str, optional + The identifier of the object that the request is about, for error messages. + on_frame : callable, optional + Called with each frame of the request, except ``command.progress`` and + ``request.error`` frames. + progress : callable, optional + Called with the fraction of each ``command.progress`` frame. + cancel : threading.Event, optional + When it is set, one ``command.cancel`` frame is sent. + timeout : float, optional + The time in seconds to wait for the next frame. The default is the + timeout of the connection. + + Returns + ------- + loop_link.protocol.Frame + The frame whose type is in ``until``. + + Raises + ------ + loop_link.errors.NoViewerError + No viewer was found. + loop_link.errors.TokenError + The viewer refused the token. + loop_link.errors.ViewerClosedError + The connection closed, the viewer did not answer in time, or it sent a bad frame. + loop_link.errors.MissingFeatureError + The viewer does not know the message or the protocol version. + loop_link.errors.CancelledError + The request was cancelled. + loop_link.errors.ViewerRefusedError + The viewer refused the request. + """ + wait = self._timeout if timeout is None else timeout + with self._lock: + client = self._connect_locked() + self._number += 1 + number = self._number + try: + client.send_binary(build(number)) + return self._read_locked( + client, number, until, feature, object_id, on_frame, progress, cancel, wait + ) + except _LINK_ERRORS as error: + self._drop_locked() + raise ViewerClosedError from error + + def post(self, build: Callable[[int], bytes]) -> int: + """Send one request and do not wait for a reply. + + The reply frames of the request stay in the socket. A later request skips them, + because their request number is not its own. + + Parameters + ---------- + build : callable + Gets the request number and returns the frame to send. + + Returns + ------- + int + The request number. + + Raises + ------ + loop_link.errors.NoViewerError + No viewer was found. + loop_link.errors.TokenError + The viewer refused the token. + loop_link.errors.ViewerClosedError + The connection closed. + """ + with self._lock: + client = self._connect_locked() + self._number += 1 + number = self._number + try: + client.send_binary(build(number)) + except _LINK_ERRORS as error: + self._drop_locked() + raise ViewerClosedError from error + return number + + # -- helpers -------------------------------------------------------------- + + def _connect_locked(self) -> WebSocketClient: + """Return the open client, or open one. The caller holds the lock.""" + if self._client is not None: + return self._client + if self._resolve is not None: + address = self._resolve() + else: + address = discovery.find_viewer( + port=self._port, + token=self._token, + host=self._host, + settings=self._settings_dir, + ) + self._client = WebSocketClient.connect( + address.host, address.port, token=address.token, timeout=self._timeout, path="/tool" + ) + return self._client + + def _drop_locked(self) -> None: + """Close the socket, if there is one. The caller holds the lock.""" + client, self._client = self._client, None + if client is not None: + try: + client.close() + except Exception: + pass + + def _read_locked( + self, + client: WebSocketClient, + number: int, + until: Sequence[str], + feature: str, + object_id: str | None, + on_frame: Callable[[Frame], None] | None, + progress: Callable[[float], None] | None, + cancel: threading.Event | None, + wait: float, + ) -> Frame: + """Read the frames of one request. The caller holds the lock.""" + last_frame = time.monotonic() + cancel_sent = False + while True: + if cancel is not None and cancel.is_set() and not cancel_sent: + client.send_binary(encode.cancel_frame(number)) + cancel_sent = True + data = client.receive(_POLL) + if data is None: + if time.monotonic() - last_frame >= wait: + self._drop_locked() + raise ViewerClosedError( + "The viewer did not answer in time. Check the viewer and retry." + ) + continue + try: + frame = protocol.decode_frame(data) + except ProtocolError as error: + self._drop_locked() + raise ViewerClosedError( + "The viewer sent a frame that is not valid. The connection is closed." + ) from error + header = frame.header + kind = header.get("type") + if kind == "error": + self._raise_error_frame(header, feature) + if header.get("request") != number: + continue + last_frame = time.monotonic() + if kind == "request.error": + raise_for_request_error(header.get("error") or {}, object_id=object_id) + if kind == "command.progress": + fraction = header.get("fraction") + if progress is not None and isinstance(fraction, (int, float)): + progress(float(fraction)) + continue + if on_frame is not None: + try: + on_frame(frame) + except BaseException: + # The viewer can continue to send the frames of this request. Close + # the connection so that they stop and a later request does not + # read them. + self._drop_locked() + raise + if kind in until: + return frame + + @staticmethod + def _raise_error_frame(header: Mapping[str, Any], feature: str) -> NoReturn: + """Raise the error for an ``error`` frame, which has no request number.""" + code = str(header.get("code", "")) + if code == "unknown_message": + raise MissingFeatureError(feature) + if code == "unsupported_version": + raise MissingFeatureError("protocol " + str(header.get("supported"))) + raise ViewerRefusedError([Refusal("", code, str(header.get("message", "")))]) diff --git a/packages/loop_link/src/loop_link/version.py b/packages/loop_link/src/loop_link/version.py new file mode 100644 index 000000000..1f6f8607a --- /dev/null +++ b/packages/loop_link/src/loop_link/version.py @@ -0,0 +1,12 @@ +"""The version of loop_link, read from the installed package metadata.""" + +# The version is set in pyproject.toml. Do not write a version string here: +# release-please changes each "__version__ = ..." string in every version.py +# file in the repository to the version of the release it makes. +from importlib.metadata import PackageNotFoundError, version + +try: + __version__ = version("loop-link") +except PackageNotFoundError: + # the package is imported from source and is not installed + __version__ = "unknown" diff --git a/packages/loop_link/src/loop_link/viewer.py b/packages/loop_link/src/loop_link/viewer.py new file mode 100644 index 000000000..008a5a3ce --- /dev/null +++ b/packages/loop_link/src/loop_link/viewer.py @@ -0,0 +1,1518 @@ +"""The ``Viewer`` class: one connection from Python to the viewer.""" + +from __future__ import annotations + +import threading +import time +import weakref +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from types import TracebackType +from typing import Any + +import numpy as np + +from loop_link import discovery, encode, protocol +from loop_link._websocket import WebSocketClient, WebSocketClosed, WebSocketError +from loop_link.adapters import convert +from loop_link.commands import ( + ColourSettings, + FilterResult, + check_codes, + check_number, + check_rgb, + check_text, + format_number, + list_colour_map_names, + run_command, +) +from loop_link.errors import ( + BusyError, + InvalidInputError, + MissingFeatureError, + NoViewerError, + Refusal, + ViewerClosedError, + ViewerRefusedError, +) +from loop_link.fetch import FetchResult, fetch_object +from loop_link.protocol import ProtocolError +from loop_link.selection import Selection, SelectionWatcher, parse_selection_result +from loop_link.tool import ToolConnection + +_LINK_ERRORS = (OSError, WebSocketClosed, WebSocketError) +_SELECTION_FEATURE = "selection and fetch (geoviewer protocol 1.18)" +_KIND_NAMES = {"cells": "cell", "nodes": "vertex"} +_INDEX_MAX = 2**32 - 1 +_COLOUR_SCALES = ("linear", "log") + + +@dataclass(frozen=True) +class InventoryEntry: + """One object in the scene of the viewer. + + Parameters + ---------- + id : str + The identifier of the object. + object_type : str + The type of the object, as the viewer names it. + revision : int + The revision of the object in the viewer. + """ + + id: str + object_type: str + revision: int + + +class Viewer: + """A connection to the viewer. + + Parameters + ---------- + port : int, optional + The port of the viewer. The default is to search for it. + token : str, optional + The access token. The default is to read it from the environment or the settings. + host : str + The host of the viewer. + crs : str + The coordinate reference system that this client proposes. + origin : sequence of float + The scene origin that this client proposes, three values. + settings_dir : pathlib.Path, optional + The settings folder of the viewer. + timeout : float + The time in seconds to wait for the connection and the first replies. + heartbeat_interval : float + The time in seconds between keepalive checks. + """ + + def __init__( + self, + *, + port: int | None = None, + token: str | None = None, + host: str = "127.0.0.1", + crs: str = "", + origin: Sequence[float] = (0.0, 0.0, 0.0), + settings_dir: Path | None = None, + timeout: float = 5.0, + heartbeat_interval: float = 5.0, + ) -> None: + self._port = port + self._token = token + self._host = host + self._crs = crs + self._proposed_origin = _triple(origin) + self._settings_dir = settings_dir + self._timeout = timeout + self._heartbeat_interval = heartbeat_interval + + self._lock = threading.Lock() + self._client: WebSocketClient | None = None + self._stop = threading.Event() + self._shared: dict[str, Any] = {"client": None, "stop": self._stop} + weakref.finalize(self, _release_shared, self._shared) + self._thread: threading.Thread | None = None + # _dead: the data connection failed. A later send opens a new connection. + # _closed: close() was called. Only connect() opens the viewer again. + self._dead = False + self._closed = False + self._address_lock = threading.Lock() + self._address: discovery.ViewerAddress | None = None + self._last_send = 0.0 + self._seq = 0 + self._tool_lock = threading.Lock() + self._tool_connection: ToolConnection | None = None + self._watchers: list[SelectionWatcher] = [] + self._colour_map_names: tuple[str, ...] | None = None + + self._revisions: dict[str, int] = {} + self._inventory: dict[str, InventoryEntry] = {} + self._inventory_revisions: dict[str, int] = {} + self._refusals: list[Refusal] = [] + self._scene_origin = self._proposed_origin + self._scene_crs = crs + + # -- properties ----------------------------------------------------------- + + @property + def revisions(self) -> Mapping[str, int]: + """The last revision that this client used for each id.""" + return dict(self._revisions) + + @property + def scene_origin(self) -> tuple[float, float, float]: + """The scene origin that all frames use.""" + return self._scene_origin + + @property + def scene_crs(self) -> str: + """The coordinate reference system of the scene, as the viewer reported it.""" + return self._scene_crs + + @property + def connected(self) -> bool: + """True while the connection is open.""" + return self._client is not None and not self._dead + + @property + def tool_connected(self) -> bool: + """True while the tool connection is open.""" + tool = self._tool_connection + return tool is not None and tool.connected and not self._closed + + # -- context manager ------------------------------------------------------ + + def __enter__(self) -> Viewer: + """Connect and return the viewer.""" + self.connect() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + """Close the connection.""" + self.close() + + # -- connection ----------------------------------------------------------- + + def connect(self) -> Viewer: + """Connect to the viewer and read its ``hello`` and inventory. + + Raises + ------ + loop_link.errors.NoViewerError + No viewer was found. + loop_link.errors.TokenError + The viewer refused the token. + loop_link.errors.BusyError + Another client owns the scene. + loop_link.errors.MissingFeatureError + The viewer does not support this protocol version. + loop_link.errors.ViewerRefusedError + The viewer sent another error. + loop_link.errors.ViewerClosedError + The viewer closed the connection before it finished the hello. + + Returns + ------- + Viewer + The viewer itself. + """ + from loop_link import __version__ + + if self.connected: + return self + self._closed = False + self._stop_thread() + self._drop_client() + address = self._resolve_address() + try: + client = WebSocketClient.connect( + address.host, address.port, token=address.token, timeout=self._timeout, path="/" + ) + except NoViewerError: + # The viewer at the known address is gone. Search again. + self._forget_address() + address = self._resolve_address() + client = WebSocketClient.connect( + address.host, address.port, token=address.token, timeout=self._timeout, path="/" + ) + try: + _read_early(client) + client.send_binary(encode.hello_frame(self._crs, self._proposed_origin, __version__)) + hello, entries = self._read_hello(client) + origin, crs = _parse_hello(hello) + except _LINK_ERRORS as error: + try: + _read_early(client, 0.3) + except _LINK_ERRORS: + pass + except BaseException: + _close_client(client) + raise + _close_client(client) + raise ViewerClosedError from error + except BaseException: + _close_client(client) + raise + self._scene_origin = origin if origin is not None else self._proposed_origin + self._scene_crs = crs + self._inventory = {entry.id: entry for entry in entries} + self._inventory_revisions = {entry.id: entry.revision for entry in entries} + self._refusals = [] + self._client = client + self._shared["client"] = client + self._dead = False + self._last_send = time.monotonic() + self._stop = threading.Event() + self._shared["stop"] = self._stop + self._thread = threading.Thread( + target=_heartbeat_loop, + args=(weakref.ref(self), self._stop, self._heartbeat_interval), + name="loop-link-heartbeat", + daemon=True, + ) + self._thread.start() + return self + + def _read_hello(self, client: WebSocketClient) -> tuple[dict[str, Any], list[InventoryEntry]]: + """Read frames until the ``hello`` and the inventory arrive.""" + hello: dict[str, Any] | None = None + entries: list[InventoryEntry] | None = None + deadline = time.monotonic() + self._timeout + while hello is None or entries is None: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise ViewerClosedError( + "The viewer did not answer the hello in time. Check the viewer and retry." + ) + data = client.receive(min(remaining, 0.5)) + if data is None: + continue + header = protocol.decode_frame(data).header + kind = header.get("type") + if kind == "error": + _raise_hello_error(header) + elif kind == "hello": + hello = header + elif kind == "scene.inventory": + entries = _parse_inventory(header) + return hello, entries + + # -- sending -------------------------------------------------------------- + + def send( + self, + obj: Any, # noqa: ANN401 + *, + id: str, + name: str | None = None, + parent: str | None = None, + colour: ColourSettings | None = None, + **hints: Any, # noqa: ANN401 + ) -> int: + """Send one object to the viewer. + + If ``colour`` is given, the method waits for a late refusal of the object + and then applies the colour settings with ``apply_colour``. + + Parameters + ---------- + obj : Any + The object to send: a loop_link object, or an input that an adapter converts. + id : str + The identifier of the object. The same id replaces the object. + name : str, optional + The display name. The default is the id. + parent : str, optional + The identifier of a group that holds the object. + colour : loop_link.commands.ColourSettings, optional + The colour settings to apply after the object is sent. + **hints : Any + Options for the adapter that converts ``obj``. + + Returns + ------- + int + The revision that the frame used. + + Raises + ------ + loop_link.errors.InvalidInputError + The input type is not accepted, ``colour`` is not a ``ColourSettings`` + object, or the viewer refused a colour command. The object stays in + the viewer. + loop_link.errors.ViewerRefusedError + The viewer refused this object and ``colour`` is given. Refusals of + other objects stay for the next ``flush``. + loop_link.errors.MissingFeatureError + ``colour`` is given and the viewer does not support the colour commands. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + if colour is not None and not isinstance(colour, ColourSettings): + raise InvalidInputError("colour must be a ColourSettings object.") + obj = convert(obj, **hints) + self._ensure_connected() + revision = self._next_revision(id) + data = encode.encode_object( + obj, + id=id, + name=id if name is None else name, + parent=parent, + revision=revision, + origin=self._scene_origin, + ) + self._send_frame(data) + self._revisions[id] = revision + object_type = str(protocol.decode_header(data).get("object_type", "")) + self._inventory[id] = InventoryEntry(id, object_type, revision) + if colour is not None: + refusals = self.flush(raise_on_refusal=False) + own = [r for r in refusals if r.object_id == id] + others = [r for r in refusals if r.object_id != id] + # Keep the refusals of other objects for the next flush. + self._refusals = others + self._refusals + if own: + raise ViewerRefusedError(own) + self.apply_colour(id, colour) + return revision + + def send_group(self, id: str, name: str | None = None, parent: str | None = None) -> int: + """Send a group. + + Parameters + ---------- + id : str + The identifier of the group. + name : str, optional + The display name. The default is the id. + parent : str, optional + The identifier of a parent group. + + Returns + ------- + int + The revision that the frame used. + """ + self._ensure_connected() + revision = self._next_revision(id) + self._send_frame(encode.group_frame(id, id if name is None else name, parent, revision)) + self._revisions[id] = revision + self._inventory[id] = InventoryEntry(id, "Group", revision) + return revision + + def remove(self, id: str) -> None: + """Remove one object from the scene. The revision count of the id is dropped. + + Parameters + ---------- + id : str + The identifier of the object. + """ + self._ensure_connected() + self._send_frame(encode.remove_frame(id)) + self._inventory.pop(id, None) + self._revisions.pop(id, None) + self._inventory_revisions.pop(id, None) + + def clear(self) -> None: + """Remove all objects from the scene.""" + self._ensure_connected() + self._send_frame(encode.clear_frame()) + self._inventory.clear() + self._revisions.clear() + self._inventory_revisions.clear() + + def inventory(self) -> list[InventoryEntry]: + """Return the known scene. + + The list starts with the inventory from the hello frame. ``send`` and + ``send_group`` add or update an entry, ``remove`` drops one, and ``clear`` + drops all. A new connection replaces the list with the hello list. + + Returns + ------- + list of InventoryEntry + The entries. + """ + return list(self._inventory.values()) + + def flush(self, settle: float = 0.5, *, raise_on_refusal: bool = True) -> list[Refusal]: + """Wait for late replies and return the refusals. + + Parameters + ---------- + settle : float + The time in seconds to wait for late frames. + raise_on_refusal : bool + If true, raise when the viewer refused an object. + + Returns + ------- + list of Refusal + The refusals since the last flush. + + Raises + ------ + loop_link.errors.ViewerRefusedError + The viewer refused one or more objects and ``raise_on_refusal`` is true. + """ + self._ensure_connected() + deadline = time.monotonic() + settle + while True: + self._drain(max(0.001, min(0.05, deadline - time.monotonic()))) + if time.monotonic() >= deadline: + break + refusals, self._refusals = self._refusals, [] + if refusals and raise_on_refusal: + raise ViewerRefusedError(refusals) + return refusals + + # -- selection ------------------------------------------------------------ + + def select( + self, + object_id: str, + *, + cells: Sequence[int] | np.ndarray | None = None, + vertices: Sequence[int] | np.ndarray | None = None, + revision: int | None = None, + ) -> dict[str, int]: + """Select cells and vertices of one object in the viewer. + + Parameters + ---------- + object_id : str + The identifier of the object. + cells : sequence of int, optional + The cell indices. Each index is from 0 to 2**32-1. + vertices : sequence of int, optional + The vertex indices. Each index is from 0 to 2**32-1. + revision : int, optional + The revision that the selection is for. The viewer refuses an old revision. + + Returns + ------- + dict of str to int + The number of selected cells (key ``cell``) and vertices (key ``vertex``). + + Raises + ------ + loop_link.errors.InvalidInputError + The id is not valid, no index list is given, an index list is not valid, + or the viewer refused the indices. + loop_link.errors.StaleRevisionError + The revision is old. + loop_link.errors.MissingFeatureError + The viewer does not support the selection. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + if not isinstance(object_id, str) or not object_id: + raise InvalidInputError("The object_id must be a string that is not empty.") + if cells is None and vertices is None: + raise InvalidInputError( + "Give cells or vertices. Use an empty list to clear the selection." + ) + cell_array = None if cells is None else _indices(cells, "cells") + vertex_array = None if vertices is None else _indices(vertices, "vertices") + tool = self._tool() + frame = tool.request( + lambda request: encode.selection_set_frame( + request, object_id, cell_array, vertex_array, revision + ), + until=("selection.result",), + feature=_SELECTION_FEATURE, + object_id=object_id, + ) + counts = {"cell": 0, "vertex": 0} + for entry in frame.header.get("entries") or []: + name = _KIND_NAMES.get(entry.get("kind")) + if name is not None: + counts[name] = int(entry.get("count", 0)) + return counts + + def selection(self) -> Selection: + """Read the selection in the viewer. + + Returns + ------- + Selection + The selection. It is empty when nothing is selected. + + Raises + ------ + loop_link.errors.MissingFeatureError + The viewer does not support the selection. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + tool = self._tool() + frame = tool.request( + encode.selection_get_frame, + until=("selection.result",), + feature=_SELECTION_FEATURE, + ) + return parse_selection_result(frame) + + def watch_selection( + self, + callback: Callable[[Selection], None], + *, + interval: float = 0.5, + initial: bool = False, + ) -> SelectionWatcher: + """Call a function each time the selection in the viewer changes. + + Parameters + ---------- + callback : callable + The function to call with the new ``Selection``. + interval : float + The time in seconds between two polls. It must be more than zero. + initial : bool + If true, call the function once with the current selection when it is + not empty. + + Returns + ------- + SelectionWatcher + The running watcher. Call its ``stop`` method to end it. + + Raises + ------ + loop_link.errors.InvalidInputError + The interval is not more than zero. + loop_link.errors.MissingFeatureError + The viewer does not support the selection. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + if not interval > 0: + raise InvalidInputError("The interval must be more than zero.") + last = self.selection() + if initial and not last.empty: + callback(last) + watcher = SelectionWatcher(weakref.ref(self), callback, interval, last) + self._watchers.append(watcher) + watcher.start() + return watcher + + # -- filters -------------------------------------------------------------- + + def filter_range( + self, + object_id: str, + array: str, + minimum: float, + maximum: float, + *, + keep_nan: bool = False, + wait: bool = True, + cancel: threading.Event | None = None, + timeout: float = 60.0, + progress: Callable[[float], None] | None = None, + ) -> FilterResult: + """Keep the cells or vertices with an array value in a range. + + Parameters + ---------- + object_id : str + The identifier of the object. + array : str + The name of a number array of the object. + minimum : float + The low limit of the range. + maximum : float + The high limit of the range. It is not less than ``minimum``. + keep_nan : bool + If true, keep the items that have no value (NaN). + wait : bool + If true, wait for the end of the filter build. If false, send the last edit and + return an empty result at once. A refusal of that edit is not seen. + cancel : threading.Event, optional + When it is set, the viewer cancels the build and the call raises ``CancelledError``. + timeout : float + The time in seconds to wait for the next frame of the viewer. It must be more + than zero. + progress : callable, optional + Called with the fraction of each progress frame of the build. + + Returns + ------- + FilterResult + The counts of the build. A field is ``None`` when the viewer gives no value. + + Raises + ------ + loop_link.errors.CancelledError + The ``cancel`` event was set. + loop_link.errors.InvalidInputError + An argument is not valid, or the viewer refused the filter. + loop_link.errors.MissingFeatureError + The viewer does not support the filter commands. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + object_id = check_text(object_id, "object_id") + array = check_text(array, "array") + low = check_number(minimum, "minimum") + high = check_number(maximum, "maximum") + if low > high: + raise InvalidInputError("'minimum' must not be more than 'maximum'.") + keep_nan = _check_bool(keep_nan, "keep_nan") + _check_wait(wait, timeout) + tool = self._tool() + self._filter_add(tool, object_id, array, cancel, timeout) + return _filter_edits( + tool, + object_id, + ( + { + "kind": "set_range", + "array": array, + "min": format_number(low), + "max": format_number(high), + "keep_nan": keep_nan, + }, + {"kind": "set_on", "array": array, "on": True}, + ), + wait=wait, + cancel=cancel, + timeout=timeout, + progress=progress, + ) + + def filter_values( + self, + object_id: str, + array: str, + values: Sequence[int] | np.ndarray, + *, + exclude: bool = False, + wait: bool = True, + cancel: threading.Event | None = None, + timeout: float = 60.0, + progress: Callable[[float], None] | None = None, + ) -> FilterResult: + """Keep the cells or vertices with an array value in a list of codes. + + Parameters + ---------- + object_id : str + The identifier of the object. + array : str + The name of a category array of the object. + values : sequence of int + The category codes. Each code is from 0 to 2**32-1. + exclude : bool + If true, remove the items with these codes and keep the others. + wait : bool + If true, wait for the end of the filter build. If false, send the last edit and + return an empty result at once. A refusal of that edit is not seen. + cancel : threading.Event, optional + When it is set, the viewer cancels the build and the call raises ``CancelledError``. + timeout : float + The time in seconds to wait for the next frame of the viewer. It must be more + than zero. + progress : callable, optional + Called with the fraction of each progress frame of the build. + + Returns + ------- + FilterResult + The counts of the build. A field is ``None`` when the viewer gives no value. + + Raises + ------ + loop_link.errors.CancelledError + The ``cancel`` event was set. + loop_link.errors.InvalidInputError + An argument is not valid, or the viewer refused the filter. + loop_link.errors.MissingFeatureError + The viewer does not support the filter commands. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + object_id = check_text(object_id, "object_id") + array = check_text(array, "array") + codes = check_codes(values, "values") + exclude = _check_bool(exclude, "exclude") + _check_wait(wait, timeout) + tool = self._tool() + self._filter_add(tool, object_id, array, cancel, timeout) + return _filter_edits( + tool, + object_id, + ( + {"kind": "set_values", "array": array, "values": codes}, + {"kind": "set_exclude", "array": array, "exclude": exclude}, + {"kind": "set_on", "array": array, "on": True}, + ), + wait=wait, + cancel=cancel, + timeout=timeout, + progress=progress, + ) + + def filter_enable( + self, + object_id: str, + array: str, + on: bool = True, + *, + wait: bool = True, + cancel: threading.Event | None = None, + timeout: float = 60.0, + progress: Callable[[float], None] | None = None, + ) -> FilterResult: + """Turn the filter of one array on or off. + + Parameters + ---------- + object_id : str + The identifier of the object. + array : str + The name of the array of the filter. + on : bool + True to turn the filter on, false to turn it off. + wait : bool + If true, wait for the end of the filter build. If false, send the edit and + return an empty result at once. + cancel : threading.Event, optional + When it is set, the viewer cancels the build and the call raises ``CancelledError``. + timeout : float + The time in seconds to wait for the next frame of the viewer. It must be more + than zero. + progress : callable, optional + Called with the fraction of each progress frame of the build. + + Returns + ------- + FilterResult + The counts of the build. A field is ``None`` when the viewer gives no value. + + Raises + ------ + loop_link.errors.CancelledError + The ``cancel`` event was set. + loop_link.errors.InvalidInputError + An argument is not valid, or the viewer refused the command. + loop_link.errors.MissingFeatureError + The viewer does not support the filter commands. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + object_id = check_text(object_id, "object_id") + array = check_text(array, "array") + on = _check_bool(on, "on") + _check_wait(wait, timeout) + return _filter_edits( + self._tool(), + object_id, + ({"kind": "set_on", "array": array, "on": on},), + wait=wait, + cancel=cancel, + timeout=timeout, + progress=progress, + ) + + def filter_remove( + self, + object_id: str, + array: str, + *, + wait: bool = True, + cancel: threading.Event | None = None, + timeout: float = 60.0, + progress: Callable[[float], None] | None = None, + ) -> FilterResult: + """Remove the filter of one array. + + Parameters + ---------- + object_id : str + The identifier of the object. + array : str + The name of the array of the filter. + wait : bool + If true, wait for the end of the filter build. If false, send the edit and + return an empty result at once. + cancel : threading.Event, optional + When it is set, the viewer cancels the build and the call raises ``CancelledError``. + timeout : float + The time in seconds to wait for the next frame of the viewer. It must be more + than zero. + progress : callable, optional + Called with the fraction of each progress frame of the build. + + Returns + ------- + FilterResult + The counts of the build. A field is ``None`` when the viewer gives no value. + + Raises + ------ + loop_link.errors.CancelledError + The ``cancel`` event was set. + loop_link.errors.InvalidInputError + An argument is not valid, or the viewer refused the command. + loop_link.errors.MissingFeatureError + The viewer does not support the filter commands. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + object_id = check_text(object_id, "object_id") + array = check_text(array, "array") + _check_wait(wait, timeout) + return _filter_edits( + self._tool(), + object_id, + ({"kind": "remove", "array": array},), + wait=wait, + cancel=cancel, + timeout=timeout, + progress=progress, + ) + + def cancel_filter(self, object_id: str) -> None: + """Cancel the filter build that runs for one object. + + Parameters + ---------- + object_id : str + The identifier of the object. + + Raises + ------ + loop_link.errors.InvalidInputError + The id is not valid, or the viewer refused the command. + loop_link.errors.MissingFeatureError + The viewer does not support the filter commands. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + object_id = check_text(object_id, "object_id") + _filter_edit(self._tool(), object_id, {"kind": "cancel"}) + + @staticmethod + def _filter_add( + tool: ToolConnection, + object_id: str, + array: str, + cancel: threading.Event | None, + timeout: float, + ) -> None: + """Add a filter. A refusal is not an error: the filter can exist already.""" + try: + _filter_edit(tool, object_id, {"kind": "add", "array": array}, cancel, timeout) + except InvalidInputError: + pass + + # -- colour --------------------------------------------------------------- + + def colour_map_names(self) -> tuple[str, ...]: + """Return the names of the colour maps of the viewer. + + The names are kept until the viewer is closed. + + Returns + ------- + tuple of str + The names. + + Raises + ------ + loop_link.errors.MissingFeatureError + The viewer does not give the names. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + names = self._read_colour_map_names(self._tool()) + if names is None: + raise MissingFeatureError("colour map names (geoviewer protocol 1.18)") + return names + + def set_colour_property(self, object_id: str, array: str | None) -> None: + """Set the array that colours an object. + + Parameters + ---------- + object_id : str + The identifier of the object. + array : str or None + The name of the array. ``None`` shows no array. + + Raises + ------ + loop_link.errors.InvalidInputError + An argument is not valid, or the viewer refused the command. + loop_link.errors.MissingFeatureError + The viewer does not support the colour commands. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + object_id = check_text(object_id, "object_id") + body: dict[str, Any] = {"id": object_id} + if array is not None: + body["array"] = check_text(array, "array") + run_command(self._tool(), "colour.set_active", body, object_id=object_id) + + def set_colour_map(self, object_id: str, name: str) -> None: + """Set the colour map of an object. + + Parameters + ---------- + object_id : str + The identifier of the object. + name : str + The name of the colour map. + + Raises + ------ + loop_link.errors.InvalidInputError + An argument is not valid, the name is not known, or the viewer refused + the command. + loop_link.errors.MissingFeatureError + The viewer does not support the colour commands. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + object_id = check_text(object_id, "object_id") + name = check_text(name, "name") + tool = self._tool() + self._check_colour_map(tool, name) + run_command(tool, "colour.set_map", {"id": object_id, "name": name}, object_id=object_id) + + def set_colour_range(self, object_id: str, minimum: float, maximum: float) -> None: + """Set the colour range of an object. + + Parameters + ---------- + object_id : str + The identifier of the object. + minimum : float + The low limit of the range. + maximum : float + The high limit of the range. It is more than ``minimum``. + + Raises + ------ + loop_link.errors.InvalidInputError + An argument is not valid, or the viewer refused the command. + loop_link.errors.MissingFeatureError + The viewer does not support the colour commands. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + object_id = check_text(object_id, "object_id") + low = check_number(minimum, "minimum") + high = check_number(maximum, "maximum") + if not low < high: + raise InvalidInputError("'minimum' must be less than 'maximum'.") + body = {"id": object_id, "min": format_number(low), "max": format_number(high)} + run_command(self._tool(), "colour.set_range", body, object_id=object_id) + + def clear_colour_range(self, object_id: str) -> None: + """Remove the colour range of an object. + + Parameters + ---------- + object_id : str + The identifier of the object. + + Raises + ------ + loop_link.errors.InvalidInputError + The id is not valid, or the viewer refused the command. + loop_link.errors.MissingFeatureError + The viewer does not support the colour commands. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + object_id = check_text(object_id, "object_id") + run_command(self._tool(), "colour.clear_range", {"id": object_id}, object_id=object_id) + + def set_colour_scale(self, object_id: str, scale: str) -> None: + """Set the colour scale of an object. + + Parameters + ---------- + object_id : str + The identifier of the object. + scale : str + The scale, ``"linear"`` or ``"log"``. + + Raises + ------ + loop_link.errors.InvalidInputError + An argument is not valid, or the viewer refused the command. + loop_link.errors.MissingFeatureError + The viewer does not support the colour scale. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + object_id = check_text(object_id, "object_id") + if scale not in _COLOUR_SCALES: + raise InvalidInputError(f"'scale' must be 'linear' or 'log'. Got {scale!r}.") + body = {"object": object_id, "scale": scale} + run_command(self._tool(), "colour.set_scale", body, object_id=object_id) + + def set_object_colour(self, object_id: str, colour: Sequence[int] | None) -> None: + """Set the plain colour of an object. + + Parameters + ---------- + object_id : str + The identifier of the object. + colour : sequence of int or None + The red, green and blue values from 0 to 255. ``None`` removes the plain colour. + + Raises + ------ + loop_link.errors.InvalidInputError + An argument is not valid, or the viewer refused the command. + loop_link.errors.MissingFeatureError + The viewer does not support the colour commands. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + object_id = check_text(object_id, "object_id") + value = None if colour is None else list(check_rgb(colour, "colour")) + body = {"id": object_id, "colour": value} + run_command(self._tool(), "object.set_colour", body, object_id=object_id) + + def apply_colour(self, object_id: str, settings: ColourSettings) -> None: + """Apply the colour settings of an object. + + The commands go in this order: array, colour map, range, scale, plain colour. + A field that is ``None`` sends no command. + + Parameters + ---------- + object_id : str + The identifier of the object. + settings : loop_link.commands.ColourSettings + The colour settings. + + Raises + ------ + loop_link.errors.InvalidInputError + An argument is not valid, or the viewer refused a command. + loop_link.errors.MissingFeatureError + The viewer does not support the colour commands. + loop_link.errors.ViewerClosedError + The connection is closed. + """ + object_id = check_text(object_id, "object_id") + if not isinstance(settings, ColourSettings): + raise InvalidInputError("The settings must be a ColourSettings object.") + if settings.array is not None: + self.set_colour_property(object_id, settings.array) + if settings.colour_map is not None: + self.set_colour_map(object_id, settings.colour_map) + if settings.range is not None: + self.set_colour_range(object_id, *settings.range) + if settings.scale is not None: + self.set_colour_scale(object_id, settings.scale) + if settings.plain is not None: + self.set_object_colour(object_id, settings.plain) + + def _read_colour_map_names(self, tool: ToolConnection) -> tuple[str, ...] | None: + """Return the colour map names. Ask the viewer at the first call only.""" + if self._colour_map_names is None: + self._colour_map_names = list_colour_map_names(tool) + return self._colour_map_names + + def _check_colour_map(self, tool: ToolConnection, name: str) -> None: + """Raise when the viewer has names and ``name`` is not one of them.""" + names = self._read_colour_map_names(tool) + if names is not None and name not in names: + raise InvalidInputError( + f"The viewer has no colour map '{name}'. The names are: {', '.join(names)}." + ) + + # -- fetching ------------------------------------------------------------- + + def fetch( + self, + id: str, + *, + progress: Callable[[float], None] | None = None, + cancel: threading.Event | None = None, + ) -> FetchResult: + """Read one object from the viewer. + + This method uses the tool connection. It does not open the data connection. + + Parameters + ---------- + id : str + The identifier of the object. + progress : callable, optional + The function to call with the fraction done, from 0 to 1. + cancel : threading.Event, optional + When this event is set, the fetch stops. + + Returns + ------- + FetchResult + The object, with its id, type, revision and name. + + Raises + ------ + loop_link.errors.InvalidInputError + The id is not valid, or the viewer does not know the id. + loop_link.errors.CancelledError + The ``cancel`` event was set. + loop_link.errors.MissingFeatureError + The viewer does not support the fetch. + loop_link.errors.ViewerClosedError + The connection is closed, or the viewer sent an object that is not valid. + loop_link.errors.UnsupportedObjectError + The viewer sent an object type that this package cannot read. + loop_link.errors.NoViewerError + No viewer was found. + loop_link.errors.TokenError + The viewer refused the token. + loop_link.errors.ObjectTooLargeError + The object is larger than the limit. + """ + if not isinstance(id, str) or not id: + raise InvalidInputError("The id must be a string that is not empty.") + tool = self._tool() + return fetch_object(tool, id, progress=progress, cancel=cancel) + + # -- closing -------------------------------------------------------------- + + def release_data(self) -> None: + """Close the connection so another client can own the scene. + + A later ``send`` opens a new connection. The revision numbers stay. The + tool connection stays open. A later ``send`` also opens a new connection + after the connection fails. + """ + self._stop_thread() + self._drop_client() + + def close(self) -> None: + """Close the connection and stop all selection watchers. The revision numbers stay.""" + watchers, self._watchers = self._watchers, [] + for watcher in watchers: + watcher.stop() + with self._tool_lock: + self._closed = True + tool, self._tool_connection = self._tool_connection, None + self._colour_map_names = None + if tool is not None: + tool.close() + self._stop_thread() + self._drop_client() + self._dead = True + with self._address_lock: + self._address = None + + # -- helpers -------------------------------------------------------------- + + def _tool(self) -> ToolConnection: + """Return the tool connection. Make it at the first call.""" + if self._closed: + raise ViewerClosedError + with self._tool_lock: + if self._closed: + raise ViewerClosedError + if self._tool_connection is None: + self._tool_connection = ToolConnection( + timeout=self._timeout, resolve=self._resolve_address + ) + return self._tool_connection + + def _resolve_address(self) -> discovery.ViewerAddress: + """Return the address of the viewer. + + While the data connection or the tool connection is open, the known address + is used again, so that both connections go to the same viewer. Otherwise the + viewer is found again. + """ + with self._address_lock: + tool = self._tool_connection + in_use = (self._client is not None and not self._dead) or ( + tool is not None and tool.connected + ) + if self._address is None or not in_use: + self._address = discovery.find_viewer( + port=self._port, + token=self._token, + host=self._host, + settings=self._settings_dir, + ) + return self._address + + def _forget_address(self) -> None: + """Forget the known address and close the tool connection that uses it.""" + with self._tool_lock: + tool = self._tool_connection + self._colour_map_names = None + if tool is not None: + tool.close() + with self._address_lock: + self._address = None + + def _ensure_connected(self) -> None: + if self._closed: + raise ViewerClosedError + if self._client is None: + self.connect() + elif self._dead: + # The last connection failed: open a new one. If the viewer is gone, give + # the error of a closed viewer, as the failed send did. + try: + self.connect() + except NoViewerError as error: + raise ViewerClosedError( + "The viewer closed the connection and no viewer was found again. " + "Start geoviewer and turn the link on, then send again." + ) from error + + def _drop_client(self) -> None: + """Close the socket, if there is one.""" + with self._lock: + client, self._client = self._client, None + self._shared["client"] = None + if client is not None: + _close_client(client) + + def _next_revision(self, id: str) -> int: + return max(self._revisions.get(id, 0), self._inventory_revisions.get(id, 0)) + 1 + + def _send_frame(self, data: bytes) -> None: + with self._lock: + client = self._client + if client is None: + raise ViewerClosedError + try: + client.send_binary(data) + self._last_send = time.monotonic() + self._drain_locked(client, 0.001) + except _LINK_ERRORS as error: + self._dead = True + raise ViewerClosedError from error + + def _drain(self, wait: float) -> None: + with self._lock: + client = self._client + if client is None: + raise ViewerClosedError + try: + self._drain_locked(client, wait) + except _LINK_ERRORS as error: + self._dead = True + raise ViewerClosedError from error + + def _drain_locked(self, client: WebSocketClient, wait: float) -> None: + """Read all waiting frames. The caller holds the lock.""" + while True: + data = client.receive(wait) + if data is None: + return + try: + header = protocol.decode_frame(data).header + except ProtocolError as error: + self._dead = True + _close_client(client) + raise ViewerClosedError( + "The viewer sent a frame that is not valid. The connection is closed." + ) from error + if header.get("type") == "error" and header.get("object") is not None: + self._refusals.append( + Refusal( + str(header["object"]), + str(header.get("code", "")), + str(header.get("message", "")), + ) + ) + wait = 0.001 + + def _heartbeat_tick(self) -> bool: + """Do one keepalive step. Return False when the thread must stop.""" + if not self._lock.acquire(blocking=False): + return True + try: + client = self._client + if client is None or self._dead: + return False + try: + self._drain_locked(client, 0.001) + except _LINK_ERRORS + (ViewerClosedError,): + self._dead = True + return False + if time.monotonic() - self._last_send < self._heartbeat_interval: + return True + self._seq += 1 + try: + client.send_binary(encode.heartbeat_frame(self._seq)) + self._last_send = time.monotonic() + except _LINK_ERRORS: + self._dead = True + return False + return True + finally: + self._lock.release() + + def _stop_thread(self) -> None: + thread, self._thread = self._thread, None + self._stop.set() + if thread is not None and thread is not threading.current_thread(): + thread.join(timeout=2 * self._heartbeat_interval) + + +def _triple(values: Sequence[float]) -> tuple[float, float, float]: + """Return three floats from a sequence of three numbers.""" + x, y, z = (float(v) for v in values) + return (x, y, z) + + +def _indices(values: Any, name: str) -> np.ndarray: # noqa: ANN401 + """Return a 1-D ``uint32`` array from index values. Raise InvalidInputError if bad.""" + try: + array = np.asarray(values) + except (TypeError, ValueError) as error: + raise InvalidInputError(f"The {name} must be a list of integers.") from error + if array.size == 0 and array.ndim == 1: + return np.empty(0, dtype=np.uint32) + if array.dtype.kind not in "iu": + raise InvalidInputError(f"The {name} must be integers. Do not use float or bool values.") + if array.ndim != 1: + raise InvalidInputError(f"The {name} must be a 1-D list of integers.") + if array.min() < 0 or array.max() > _INDEX_MAX: + raise InvalidInputError(f"The {name} must be from 0 to {_INDEX_MAX}.") + return array.astype(np.uint32) + + +def _check_bool(value: object, name: str) -> bool: + """Return a value that must be a ``bool``. Raise InvalidInputError if it is not.""" + if not isinstance(value, bool): + raise InvalidInputError(f"'{name}' must be True or False. Got {value!r}.") + return value + + +def _check_wait(wait: object, timeout: object) -> None: + """Check the ``wait`` and ``timeout`` arguments of a filter call.""" + _check_bool(wait, "wait") + if check_number(timeout, "timeout") <= 0: + raise InvalidInputError("'timeout' must be more than zero.") + + +def _filter_edit( + tool: ToolConnection, + object_id: str, + edit: dict[str, Any], + cancel: threading.Event | None = None, + timeout: float | None = None, + progress: Callable[[float], None] | None = None, +) -> Mapping[str, Any]: + """Send one ``filter.edit`` command and wait for its result.""" + return run_command( + tool, + "filter.edit", + {"object": object_id, "edit": edit}, + object_id=object_id, + cancel=cancel, + timeout=timeout, + progress=progress, + ) + + +def _filter_edits( + tool: ToolConnection, + object_id: str, + edits: Sequence[dict[str, Any]], + *, + wait: bool, + cancel: threading.Event | None, + timeout: float, + progress: Callable[[float], None] | None, +) -> FilterResult: + """Send the edits of a filter call and return the result of the last one. + + With ``wait`` false, the last edit goes with ``post`` and the result is empty. + """ + result: Mapping[str, Any] = {} + last = len(edits) - 1 + for index, edit in enumerate(edits): + if index == last and not wait: + body = {"object": object_id, "edit": edit} + tool.post(lambda number: encode.command_frame(number, "filter.edit", body)) + return FilterResult() + result = _filter_edit(tool, object_id, edit, cancel, timeout, progress) + return FilterResult.from_result(result) + + +def _close_client(client: WebSocketClient) -> None: + """Close a client. An error on close does not matter.""" + try: + client.close() + except Exception: + pass + + +def _raise_hello_error(header: dict[str, Any]) -> None: + """Raise the right error for an ``error`` frame during the hello.""" + code = header.get("code") + message = str(header.get("message", "")) + if code == "busy": + raise BusyError(message or "The viewer is busy. Wait a moment and try again.") + if code == "unsupported_version": + supported = header.get("supported") + feature = "protocol version" + if supported is not None: + feature = f"protocol 1.x (the viewer supports: {supported})" + raise MissingFeatureError(feature) + raise ViewerRefusedError([Refusal(str(header.get("object", "")), str(code), message)]) + + +def _parse_hello(hello: dict[str, Any]) -> tuple[tuple[float, float, float] | None, str]: + """Return the origin and the CRS of a ``hello`` frame. Raise ProtocolError if it is bad.""" + try: + origin = hello.get("origin") + crs = hello.get("crs") + return ( + _triple(origin) if origin is not None else None, + "" if crs is None else str(crs), + ) + except (TypeError, ValueError, AttributeError) as error: + raise ProtocolError("The viewer sent a hello frame that is not valid.") from error + + +def _parse_inventory(header: dict[str, Any]) -> list[InventoryEntry]: + """Return the entries of a ``scene.inventory`` frame. Raise ProtocolError if it is bad.""" + try: + return [ + InventoryEntry( + id=str(item["id"]), + object_type=str(item.get("object_type", "")), + revision=int(item.get("revision", 1)), + ) + for item in header.get("entries", []) + ] + except (TypeError, ValueError, KeyError, AttributeError) as error: + raise ProtocolError("The viewer sent an inventory frame that is not valid.") from error + + +def _read_early(client: WebSocketClient, wait: float = 0.05) -> None: + """Read frames that wait already. Raise the hello error if one is an ``error`` frame.""" + for _ in range(4): + data = client.receive(wait) + if data is None: + return + header = protocol.decode_frame(data).header + if header.get("type") == "error": + _raise_hello_error(header) + + +def _heartbeat_loop( + ref: weakref.ReferenceType[Viewer], stop: threading.Event, interval: float +) -> None: + """Run the keepalive. The thread holds only a weak reference to the viewer.""" + while not stop.wait(interval): + viewer = ref() + if viewer is None or not viewer._heartbeat_tick(): + return + del viewer + + +def _release_shared(shared: dict[str, Any]) -> None: + """Stop the thread and close the socket of a viewer that is gone.""" + shared["stop"].set() + client = shared.get("client") + if client is not None: + _close_client(client) diff --git a/packages/loop_link/tests/codec_validator/Cargo.toml.template b/packages/loop_link/tests/codec_validator/Cargo.toml.template new file mode 100644 index 000000000..e52094c7f --- /dev/null +++ b/packages/loop_link/tests/codec_validator/Cargo.toml.template @@ -0,0 +1,17 @@ +# Template of the codec validator package. The test fixture fills in the path +# and writes the result as Cargo.toml in the build folder. +[package] +name = "codec-validator" +version = "0.0.0" +edition = "2021" +publish = false + +[[bin]] +name = "codec-validator" +path = "src/main.rs" + +[dependencies] +geoviewer-protocol = { path = "@GEOVIEWER_PROTOCOL_PATH@" } + +# An empty table makes this package its own workspace. +[workspace] diff --git a/packages/loop_link/tests/codec_validator/main.rs b/packages/loop_link/tests/codec_validator/main.rs new file mode 100644 index 000000000..542ea4c70 --- /dev/null +++ b/packages/loop_link/tests/codec_validator/main.rs @@ -0,0 +1,37 @@ +//! Check frames with the real geoviewer codec. +//! +//! Usage: codec-validator FILE... +//! For each file the program reads the bytes, decodes the frame and validates the object. +//! It prints `OK ` or `FAIL : `. +//! Exit code: 0 if all files are valid, 1 if one file is not valid, 2 for a usage error. + +use geoviewer_protocol::Frame; + +fn main() { + let paths: Vec = std::env::args().skip(1).collect(); + if paths.is_empty() { + eprintln!("usage: codec-validator FILE..."); + std::process::exit(2); + } + let mut failed = false; + for path in &paths { + let result = match std::fs::read(path) { + Err(error) => Err(format!("cannot read file: {error}")), + Ok(bytes) => Frame::decode(&bytes) + .map_err(|error| format!("decode: {error}")) + .and_then(|frame| { + frame + .validate_object() + .map_err(|error| format!("validate_object: {error}")) + }), + }; + match result { + Ok(()) => println!("OK {path}"), + Err(message) => { + failed = true; + println!("FAIL {path}: {message}"); + } + } + } + std::process::exit(i32::from(failed)); +} diff --git a/packages/loop_link/tests/conftest.py b/packages/loop_link/tests/conftest.py new file mode 100644 index 000000000..eba1a1148 --- /dev/null +++ b/packages/loop_link/tests/conftest.py @@ -0,0 +1,65 @@ +"""Shared test support for the loop_link tests.""" + +from __future__ import annotations + +import contextlib +import os +from collections.abc import Callable, Iterator +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import pytest + +from loop_link.testing import FakeViewer + + +@dataclass +class FakeViewerHandle: + """A running fake viewer and the settings folder that holds its instance file.""" + + viewer: FakeViewer + settings: Path + + +@pytest.fixture +def fake_viewer(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[FakeViewerHandle]: + """Start a fake viewer and publish its instance file in a temporary settings folder.""" + viewer = FakeViewer() + settings = tmp_path / "geoviewer" + try: + viewer.write_instance_file(settings) + monkeypatch.setenv("GEOVIEWER_TOKEN", "secret") + yield FakeViewerHandle(viewer=viewer, settings=settings) + finally: + viewer.close() + + +@pytest.fixture +def viewer_factory(fake_viewer: FakeViewerHandle) -> Iterator[Callable[..., Any]]: + """Return a function that makes viewers. Each made viewer is closed at teardown.""" + + from loop_link.viewer import Viewer # Viewer is built by a later task, so import it here + + made: list[Any] = [] + + def make(**kwargs: Any) -> Any: + options = {"settings_dir": fake_viewer.settings, "heartbeat_interval": 0.1} + options.update(kwargs) + viewer = Viewer(**options) + made.append(viewer) + return viewer + + yield make + for viewer in made: + with contextlib.suppress(Exception): # errors on close do not matter at teardown + viewer.close() + + +def geoviewer_fixtures() -> Path | None: + """Return the folder in LOOP_LINK_GEOVIEWER_FIXTURES, or None when it is not a folder.""" + value = os.environ.get("LOOP_LINK_GEOVIEWER_FIXTURES") + if not value: + return None + path = Path(value) + return path if path.is_dir() else None diff --git a/packages/loop_link/tests/manual_checks.md b/packages/loop_link/tests/manual_checks.md new file mode 100644 index 000000000..bfb54e52b --- /dev/null +++ b/packages/loop_link/tests/manual_checks.md @@ -0,0 +1,160 @@ +## M1: speed with the real headless viewer (SC-001) + +Purpose: check that an object is visible in the viewer within 5 s after a reconnect. + +1. In PowerShell, set the token. Type `$env:GEOVIEWER_TOKEN = "secret"` and press Enter. +2. Start the viewer. Type `geoviewer-headless --port 0` and press Enter. +3. Read the port number that the viewer prints. +4. Save this script as a file outside the repository. + +```python +import sys +import time +import numpy as np +from loop_link.errors import BusyError +from loop_link.objects import BlockModel +from loop_link.viewer import Viewer + +PORT = int(sys.argv[1]) # the port that the viewer printed +grade = np.random.default_rng(0).random(1_000_000, dtype=np.float32) +block = BlockModel(origin=(0, 0, 0), cell_sizes=(1, 1, 1), cells=(100, 100, 100), + cell_properties={"grade": grade}) + +start = time.perf_counter() +viewer = Viewer(port=PORT, token="secret", crs="EPSG:28350") +viewer.send(block, id="grid") +viewer.release_data() + +while True: + other = Viewer(port=PORT, token="secret") + try: + other.connect() + except BusyError: + time.sleep(0.1) # the viewer has not yet noticed the close + continue + found = any(entry.id == "grid" for entry in other.inventory()) + other.close() + if found: + break + time.sleep(0.1) +print(f"Time until grid is in the inventory: {time.perf_counter() - start:.3f} s") +``` + +5. Run the script. Type `packages/loop_link/.venv/Scripts/python.exe