loop-link 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- loop_link/__init__.py +61 -0
- loop_link/_websocket.py +436 -0
- loop_link/adapters/__init__.py +51 -0
- loop_link/adapters/loopstructural.py +83 -0
- loop_link/adapters/pandas.py +227 -0
- loop_link/adapters/pyvista.py +267 -0
- loop_link/commands.py +418 -0
- loop_link/discovery.py +170 -0
- loop_link/encode.py +688 -0
- loop_link/errors.py +279 -0
- loop_link/fetch.py +610 -0
- loop_link/objects.py +581 -0
- loop_link/orientation.py +164 -0
- loop_link/protocol.py +235 -0
- loop_link/push.py +166 -0
- loop_link/selection.py +215 -0
- loop_link/testing/__init__.py +7 -0
- loop_link/testing/fake_viewer.py +1587 -0
- loop_link/tool.py +343 -0
- loop_link/version.py +12 -0
- loop_link/viewer.py +1518 -0
- loop_link-0.1.0.dist-info/METADATA +115 -0
- loop_link-0.1.0.dist-info/RECORD +26 -0
- loop_link-0.1.0.dist-info/WHEEL +5 -0
- loop_link-0.1.0.dist-info/licenses/LICENSE +21 -0
- loop_link-0.1.0.dist-info/top_level.txt +1 -0
loop_link/encode.py
ADDED
|
@@ -0,0 +1,688 @@
|
|
|
1
|
+
"""Encode scene objects into protocol frames.
|
|
2
|
+
|
|
3
|
+
The public functions return ``bytes``. Each frame has a JSON header and a list of
|
|
4
|
+
named binary buffers. See :mod:`loop_link.protocol` for the frame layout.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Mapping, Sequence
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
from loop_link import protocol
|
|
15
|
+
from loop_link.errors import InvalidInputError, ObjectTooLargeError
|
|
16
|
+
from loop_link.objects import (
|
|
17
|
+
DEFAULT_CATEGORY_COLOURS,
|
|
18
|
+
BlockModel,
|
|
19
|
+
Categorical,
|
|
20
|
+
Drillhole,
|
|
21
|
+
Lines,
|
|
22
|
+
Points,
|
|
23
|
+
SceneObject,
|
|
24
|
+
Surface,
|
|
25
|
+
TetraMesh,
|
|
26
|
+
Vectors,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"cancel_frame",
|
|
31
|
+
"clear_frame",
|
|
32
|
+
"command_frame",
|
|
33
|
+
"commands_list_frame",
|
|
34
|
+
"encode_object",
|
|
35
|
+
"fetch_frame",
|
|
36
|
+
"group_frame",
|
|
37
|
+
"heartbeat_frame",
|
|
38
|
+
"hello_frame",
|
|
39
|
+
"remove_frame",
|
|
40
|
+
"selection_get_frame",
|
|
41
|
+
"selection_set_frame",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
_I32_MIN = -(2**31)
|
|
45
|
+
_I32_MAX = 2**31 - 1
|
|
46
|
+
|
|
47
|
+
# The name of the log set that holds the interval properties of a Drillhole.
|
|
48
|
+
_INTERVAL_LOG_SET = "intervals"
|
|
49
|
+
|
|
50
|
+
Buffers = list[tuple[str, np.ndarray]]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def hello_frame(crs: str, origin: Sequence[float], version: str) -> bytes:
|
|
54
|
+
"""Return the ``hello`` frame.
|
|
55
|
+
|
|
56
|
+
Parameters
|
|
57
|
+
----------
|
|
58
|
+
crs : str
|
|
59
|
+
The coordinate reference system, for example ``"EPSG:28350"``.
|
|
60
|
+
origin : sequence of float
|
|
61
|
+
The scene origin, three values.
|
|
62
|
+
version : str
|
|
63
|
+
The version of loop_link.
|
|
64
|
+
|
|
65
|
+
Returns
|
|
66
|
+
-------
|
|
67
|
+
bytes
|
|
68
|
+
The frame.
|
|
69
|
+
"""
|
|
70
|
+
header = {
|
|
71
|
+
"type": "hello",
|
|
72
|
+
"application": {"name": "loop_link", "version": version},
|
|
73
|
+
"crs": crs,
|
|
74
|
+
"origin": [float(v) for v in origin],
|
|
75
|
+
}
|
|
76
|
+
return protocol.encode_frame(header)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def heartbeat_frame(seq: int) -> bytes:
|
|
80
|
+
"""Return a ``heartbeat`` frame.
|
|
81
|
+
|
|
82
|
+
Parameters
|
|
83
|
+
----------
|
|
84
|
+
seq : int
|
|
85
|
+
The sequence number.
|
|
86
|
+
|
|
87
|
+
Returns
|
|
88
|
+
-------
|
|
89
|
+
bytes
|
|
90
|
+
The frame.
|
|
91
|
+
"""
|
|
92
|
+
return protocol.encode_frame({"type": "heartbeat", "seq": seq})
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def remove_frame(id: str) -> bytes:
|
|
96
|
+
"""Return a ``scene.remove`` frame.
|
|
97
|
+
|
|
98
|
+
Parameters
|
|
99
|
+
----------
|
|
100
|
+
id : str
|
|
101
|
+
The identifier of the object to remove.
|
|
102
|
+
|
|
103
|
+
Returns
|
|
104
|
+
-------
|
|
105
|
+
bytes
|
|
106
|
+
The frame.
|
|
107
|
+
"""
|
|
108
|
+
return protocol.encode_frame({"type": "scene.remove", "id": id})
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def clear_frame() -> bytes:
|
|
112
|
+
"""Return a ``scene.clear`` frame.
|
|
113
|
+
|
|
114
|
+
Returns
|
|
115
|
+
-------
|
|
116
|
+
bytes
|
|
117
|
+
The frame.
|
|
118
|
+
"""
|
|
119
|
+
return protocol.encode_frame({"type": "scene.clear"})
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def selection_set_frame(
|
|
123
|
+
request: int,
|
|
124
|
+
object_id: str,
|
|
125
|
+
cells: np.ndarray | None,
|
|
126
|
+
vertices: np.ndarray | None,
|
|
127
|
+
revision: int | None,
|
|
128
|
+
) -> bytes:
|
|
129
|
+
"""Return a ``selection.set`` frame.
|
|
130
|
+
|
|
131
|
+
An empty or None array adds no entry and no buffer. The function does not
|
|
132
|
+
check the index range.
|
|
133
|
+
|
|
134
|
+
Parameters
|
|
135
|
+
----------
|
|
136
|
+
request : int
|
|
137
|
+
The request number.
|
|
138
|
+
object_id : str
|
|
139
|
+
The identifier of the object.
|
|
140
|
+
cells : numpy.ndarray or None
|
|
141
|
+
The cell indices.
|
|
142
|
+
vertices : numpy.ndarray or None
|
|
143
|
+
The vertex (node) indices.
|
|
144
|
+
revision : int or None
|
|
145
|
+
The revision of the object. If it is None, the header has no ``revision`` key.
|
|
146
|
+
|
|
147
|
+
Returns
|
|
148
|
+
-------
|
|
149
|
+
bytes
|
|
150
|
+
The frame.
|
|
151
|
+
"""
|
|
152
|
+
header: dict[str, Any] = {"type": "selection.set", "request": request, "object": object_id}
|
|
153
|
+
if revision is not None:
|
|
154
|
+
header["revision"] = revision
|
|
155
|
+
entries: list[dict[str, str]] = []
|
|
156
|
+
buffers: Buffers = []
|
|
157
|
+
for kind, name, values in (("cells", "cells", cells), ("nodes", "nodes", vertices)):
|
|
158
|
+
if values is None:
|
|
159
|
+
continue
|
|
160
|
+
array = np.ascontiguousarray(np.asarray(values, dtype=np.uint32))
|
|
161
|
+
if array.size == 0:
|
|
162
|
+
continue
|
|
163
|
+
entries.append({"kind": kind, "indices": name})
|
|
164
|
+
buffers.append((name, array))
|
|
165
|
+
header["entries"] = entries
|
|
166
|
+
return protocol.encode_frame(header, buffers, version=protocol.TOOL_PROTOCOL_VERSION)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def selection_get_frame(request: int) -> bytes:
|
|
170
|
+
"""Return a ``selection.get`` frame.
|
|
171
|
+
|
|
172
|
+
Parameters
|
|
173
|
+
----------
|
|
174
|
+
request : int
|
|
175
|
+
The request number.
|
|
176
|
+
|
|
177
|
+
Returns
|
|
178
|
+
-------
|
|
179
|
+
bytes
|
|
180
|
+
The frame.
|
|
181
|
+
"""
|
|
182
|
+
return protocol.encode_frame(
|
|
183
|
+
{"type": "selection.get", "request": request},
|
|
184
|
+
version=protocol.TOOL_PROTOCOL_VERSION,
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def fetch_frame(request: int, id: str) -> bytes:
|
|
189
|
+
"""Return an ``object.fetch`` frame.
|
|
190
|
+
|
|
191
|
+
Parameters
|
|
192
|
+
----------
|
|
193
|
+
request : int
|
|
194
|
+
The request number.
|
|
195
|
+
id : str
|
|
196
|
+
The identifier of the object.
|
|
197
|
+
|
|
198
|
+
Returns
|
|
199
|
+
-------
|
|
200
|
+
bytes
|
|
201
|
+
The frame.
|
|
202
|
+
"""
|
|
203
|
+
return protocol.encode_frame(
|
|
204
|
+
{"type": "object.fetch", "request": request, "id": id},
|
|
205
|
+
version=protocol.TOOL_PROTOCOL_VERSION,
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def cancel_frame(request: int) -> bytes:
|
|
210
|
+
"""Return a ``command.cancel`` frame.
|
|
211
|
+
|
|
212
|
+
Parameters
|
|
213
|
+
----------
|
|
214
|
+
request : int
|
|
215
|
+
The number of the request to cancel.
|
|
216
|
+
|
|
217
|
+
Returns
|
|
218
|
+
-------
|
|
219
|
+
bytes
|
|
220
|
+
The frame.
|
|
221
|
+
"""
|
|
222
|
+
return protocol.encode_frame(
|
|
223
|
+
{"type": "command.cancel", "request": request},
|
|
224
|
+
version=protocol.CANCEL_PROTOCOL_VERSION,
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def commands_list_frame(request: int) -> bytes:
|
|
229
|
+
"""Return a ``commands.list`` frame.
|
|
230
|
+
|
|
231
|
+
Parameters
|
|
232
|
+
----------
|
|
233
|
+
request : int
|
|
234
|
+
The request number.
|
|
235
|
+
|
|
236
|
+
Returns
|
|
237
|
+
-------
|
|
238
|
+
bytes
|
|
239
|
+
The frame.
|
|
240
|
+
"""
|
|
241
|
+
return protocol.encode_frame(
|
|
242
|
+
{"type": "commands.list", "request": request},
|
|
243
|
+
version=protocol.COMMAND_PROTOCOL_VERSION,
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def command_frame(request: int, command: str, input: Mapping[str, Any]) -> bytes:
|
|
248
|
+
"""Return a ``command.run`` frame.
|
|
249
|
+
|
|
250
|
+
The function copies the input mapping. It does not change the mapping of the
|
|
251
|
+
caller. The input must be JSON values. A NaN or an infinite number raises an error.
|
|
252
|
+
|
|
253
|
+
Parameters
|
|
254
|
+
----------
|
|
255
|
+
request : int
|
|
256
|
+
The request number.
|
|
257
|
+
command : str
|
|
258
|
+
The name of the command, for example ``"object.set_visible"``.
|
|
259
|
+
input : Mapping[str, Any]
|
|
260
|
+
The arguments of the command.
|
|
261
|
+
|
|
262
|
+
Returns
|
|
263
|
+
-------
|
|
264
|
+
bytes
|
|
265
|
+
The frame.
|
|
266
|
+
|
|
267
|
+
Raises
|
|
268
|
+
------
|
|
269
|
+
ProtocolError
|
|
270
|
+
If the input cannot be encoded as JSON, for example for a NaN value.
|
|
271
|
+
"""
|
|
272
|
+
header = {
|
|
273
|
+
"type": "command.run",
|
|
274
|
+
"request": request,
|
|
275
|
+
"command": command,
|
|
276
|
+
"input": dict(input),
|
|
277
|
+
}
|
|
278
|
+
try:
|
|
279
|
+
return protocol.encode_frame(header, version=protocol.COMMAND_PROTOCOL_VERSION)
|
|
280
|
+
except ValueError as error:
|
|
281
|
+
raise protocol.ProtocolError(
|
|
282
|
+
"The input of the command has a value that JSON cannot store, such as NaN "
|
|
283
|
+
"or an infinite number. Use finite numbers."
|
|
284
|
+
) from error
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _upsert_header(
|
|
288
|
+
id: str,
|
|
289
|
+
object_type: str,
|
|
290
|
+
name: str | None,
|
|
291
|
+
parent: str | None,
|
|
292
|
+
revision: int,
|
|
293
|
+
) -> dict[str, Any]:
|
|
294
|
+
"""Return the header of a ``scene.upsert`` frame without data."""
|
|
295
|
+
return {
|
|
296
|
+
"type": "scene.upsert",
|
|
297
|
+
"id": id,
|
|
298
|
+
"object_type": object_type,
|
|
299
|
+
"name": id if name is None else name,
|
|
300
|
+
"parent": parent,
|
|
301
|
+
"revision": revision,
|
|
302
|
+
"edit": [],
|
|
303
|
+
"replaces": None,
|
|
304
|
+
"geometry": {},
|
|
305
|
+
"params": {},
|
|
306
|
+
"data": [],
|
|
307
|
+
"property_groups": [],
|
|
308
|
+
"drape": None,
|
|
309
|
+
"style": {},
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def group_frame(
|
|
314
|
+
id: str,
|
|
315
|
+
name: str | None,
|
|
316
|
+
parent: str | None,
|
|
317
|
+
revision: int,
|
|
318
|
+
) -> bytes:
|
|
319
|
+
"""Return a ``scene.upsert`` frame for a group.
|
|
320
|
+
|
|
321
|
+
Parameters
|
|
322
|
+
----------
|
|
323
|
+
id : str
|
|
324
|
+
The identifier of the group.
|
|
325
|
+
name : str or None
|
|
326
|
+
The display name. If it is None, the name is the identifier.
|
|
327
|
+
parent : str or None
|
|
328
|
+
The identifier of the parent group.
|
|
329
|
+
revision : int
|
|
330
|
+
The revision number.
|
|
331
|
+
|
|
332
|
+
Returns
|
|
333
|
+
-------
|
|
334
|
+
bytes
|
|
335
|
+
The frame.
|
|
336
|
+
"""
|
|
337
|
+
return protocol.encode_frame(_upsert_header(id, "Group", name, parent, revision))
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _utf8_size(value_map: list[dict[str, Any]], name: str) -> int:
|
|
341
|
+
"""Return the declared bytes of a value map. Raise if a name is not valid UTF-8."""
|
|
342
|
+
total = 0
|
|
343
|
+
try:
|
|
344
|
+
for item in value_map:
|
|
345
|
+
total += 8 + len(item["name"].encode("utf-8"))
|
|
346
|
+
except UnicodeEncodeError as error:
|
|
347
|
+
raise InvalidInputError(
|
|
348
|
+
f"A category name of the property '{name}' cannot be encoded as UTF-8. "
|
|
349
|
+
"Remove the characters that are not valid."
|
|
350
|
+
) from error
|
|
351
|
+
return total
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _declared_bytes(name: str, value: object) -> int:
|
|
355
|
+
"""Return the bytes that a property needs, from its shape and target type.
|
|
356
|
+
|
|
357
|
+
The function does not copy the values. For text it returns an upper bound.
|
|
358
|
+
"""
|
|
359
|
+
if isinstance(value, Categorical):
|
|
360
|
+
codes = np.asarray(value.codes)
|
|
361
|
+
total = int(codes.size) * 4
|
|
362
|
+
for label in value.names:
|
|
363
|
+
try:
|
|
364
|
+
total += 8 + len(str(label).encode("utf-8"))
|
|
365
|
+
except UnicodeEncodeError as error:
|
|
366
|
+
raise InvalidInputError(
|
|
367
|
+
f"A category name of the property '{name}' cannot be encoded as UTF-8. "
|
|
368
|
+
"Remove the characters that are not valid."
|
|
369
|
+
) from error
|
|
370
|
+
return total
|
|
371
|
+
arr = np.asarray(value)
|
|
372
|
+
kind = arr.dtype.kind
|
|
373
|
+
if kind == "f":
|
|
374
|
+
return int(arr.size) * (4 if arr.dtype == np.dtype("float32") else 8)
|
|
375
|
+
if kind == "b":
|
|
376
|
+
return int(arr.size)
|
|
377
|
+
if kind in "iu":
|
|
378
|
+
return int(arr.size) * 4
|
|
379
|
+
if kind in "US":
|
|
380
|
+
return int(arr.size) * int(arr.dtype.itemsize) + (int(arr.size) + 1) * 4
|
|
381
|
+
return 0
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _data_array(
|
|
385
|
+
name: str, value: object, association: str, log_set: str | None = None
|
|
386
|
+
) -> tuple[dict[str, Any], Buffers]:
|
|
387
|
+
"""Return the data description and the buffers of one property.
|
|
388
|
+
|
|
389
|
+
Parameters
|
|
390
|
+
----------
|
|
391
|
+
name : str
|
|
392
|
+
The name of the property.
|
|
393
|
+
value : numpy.ndarray or Categorical
|
|
394
|
+
The values.
|
|
395
|
+
association : str
|
|
396
|
+
``"vertex"``, ``"cell"`` or ``"interval"``. For a Drillhole, ``"vertex"`` has one
|
|
397
|
+
value for each survey station and ``"interval"`` has one value for each row of
|
|
398
|
+
``intervals``. An ``"interval"`` array belongs to a log set. ``"cell"`` is for
|
|
399
|
+
the other object types.
|
|
400
|
+
log_set : str or None
|
|
401
|
+
The name of the log set of an ``"interval"`` array. The function writes it to
|
|
402
|
+
the data description as ``log_set``. Use ``None`` for the other associations.
|
|
403
|
+
|
|
404
|
+
Returns
|
|
405
|
+
-------
|
|
406
|
+
desc : dict
|
|
407
|
+
The entry for the ``data`` list of the header.
|
|
408
|
+
buffers : list of (str, numpy.ndarray)
|
|
409
|
+
The buffers of the property.
|
|
410
|
+
|
|
411
|
+
Raises
|
|
412
|
+
------
|
|
413
|
+
InvalidInputError
|
|
414
|
+
If the type of the values is not supported, or an integer is outside i32.
|
|
415
|
+
"""
|
|
416
|
+
buffer_name = f"data/{name}"
|
|
417
|
+
desc: dict[str, Any] = {
|
|
418
|
+
"id": name,
|
|
419
|
+
"name": name,
|
|
420
|
+
"buffer": buffer_name,
|
|
421
|
+
"association": association,
|
|
422
|
+
}
|
|
423
|
+
if log_set is not None:
|
|
424
|
+
desc["log_set"] = log_set
|
|
425
|
+
if isinstance(value, Categorical):
|
|
426
|
+
codes = np.asarray(value.codes).astype(np.uint32, copy=False)
|
|
427
|
+
colours = value.colours
|
|
428
|
+
value_map = []
|
|
429
|
+
for index, label in enumerate(value.names):
|
|
430
|
+
if colours is None:
|
|
431
|
+
colour = list(DEFAULT_CATEGORY_COLOURS[index % len(DEFAULT_CATEGORY_COLOURS)])
|
|
432
|
+
else:
|
|
433
|
+
colour = [int(c) for c in colours[index]]
|
|
434
|
+
value_map.append({"id": index, "name": str(label), "colour": colour})
|
|
435
|
+
_utf8_size(value_map, name)
|
|
436
|
+
desc["data_type"] = "referenced"
|
|
437
|
+
desc["value_map"] = value_map
|
|
438
|
+
return desc, [(buffer_name, codes)]
|
|
439
|
+
arr = np.asarray(value)
|
|
440
|
+
kind = arr.dtype.kind
|
|
441
|
+
if kind == "f":
|
|
442
|
+
if arr.dtype != np.dtype("float32"):
|
|
443
|
+
arr = arr.astype(np.float64, copy=False)
|
|
444
|
+
desc["data_type"] = "float"
|
|
445
|
+
return desc, [(buffer_name, arr)]
|
|
446
|
+
if kind == "b":
|
|
447
|
+
desc["data_type"] = "boolean"
|
|
448
|
+
return desc, [(buffer_name, arr.astype(np.uint8, copy=False))]
|
|
449
|
+
if kind in "iu":
|
|
450
|
+
if arr.size and (arr.min() < _I32_MIN or arr.max() > _I32_MAX):
|
|
451
|
+
raise InvalidInputError(
|
|
452
|
+
f"The property '{name}' has integers outside the i32 range. "
|
|
453
|
+
"Use values from -2147483648 to 2147483647."
|
|
454
|
+
)
|
|
455
|
+
desc["data_type"] = "integer"
|
|
456
|
+
return desc, [(buffer_name, arr.astype(np.int32, copy=False))]
|
|
457
|
+
if kind in "US":
|
|
458
|
+
try:
|
|
459
|
+
if kind == "U":
|
|
460
|
+
parts = [str(item).encode("utf-8") for item in arr.tolist()]
|
|
461
|
+
else:
|
|
462
|
+
parts = [bytes(item) for item in arr.tolist()]
|
|
463
|
+
for part in parts:
|
|
464
|
+
part.decode("utf-8")
|
|
465
|
+
except (UnicodeEncodeError, UnicodeDecodeError) as error:
|
|
466
|
+
raise InvalidInputError(
|
|
467
|
+
f"The property '{name}' has text that is not valid UTF-8. "
|
|
468
|
+
"Remove the characters that are not valid."
|
|
469
|
+
) from error
|
|
470
|
+
offsets = np.zeros(len(parts) + 1, dtype=np.uint32)
|
|
471
|
+
if parts:
|
|
472
|
+
offsets[1:] = np.cumsum([len(p) for p in parts], dtype=np.uint64)
|
|
473
|
+
data = np.frombuffer(b"".join(parts), dtype=np.uint8)
|
|
474
|
+
offsets_name = f"{buffer_name}/offsets"
|
|
475
|
+
desc["data_type"] = "text"
|
|
476
|
+
desc["offsets"] = offsets_name
|
|
477
|
+
return desc, [(buffer_name, data), (offsets_name, offsets)]
|
|
478
|
+
raise InvalidInputError(
|
|
479
|
+
f"The property '{name}' has the type {arr.dtype}, which is not supported. "
|
|
480
|
+
"Use numbers, booleans, text or Categorical."
|
|
481
|
+
)
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
class _Builder:
|
|
485
|
+
"""Collect the header parts and the buffers of one object."""
|
|
486
|
+
|
|
487
|
+
def __init__(self, id: str, origin: np.ndarray) -> None:
|
|
488
|
+
self.id = id
|
|
489
|
+
self.origin = origin
|
|
490
|
+
self.buffers: Buffers = []
|
|
491
|
+
self.names: set[str] = set()
|
|
492
|
+
self.geometry: dict[str, str] = {}
|
|
493
|
+
self.data: list[dict[str, Any]] = []
|
|
494
|
+
self.groups: list[dict[str, Any]] = []
|
|
495
|
+
self.declared = 0
|
|
496
|
+
|
|
497
|
+
def reserve(self, size: int) -> None:
|
|
498
|
+
"""Add a declared size. Raise if a limit is passed. Call before any copy."""
|
|
499
|
+
self.declared += size
|
|
500
|
+
limit = protocol.MAX_OBJECT_BYTES
|
|
501
|
+
if self.declared > limit:
|
|
502
|
+
raise ObjectTooLargeError(self.id, self.declared, limit)
|
|
503
|
+
frame_limit = protocol.MAX_FRAME_BYTES
|
|
504
|
+
if self.declared > frame_limit - protocol.MAX_HEADER_BYTES:
|
|
505
|
+
raise ObjectTooLargeError(self.id, self.declared, frame_limit)
|
|
506
|
+
|
|
507
|
+
def add_buffer(self, name: str, array: np.ndarray) -> None:
|
|
508
|
+
"""Add a buffer. Raise if the name is already used."""
|
|
509
|
+
if name in self.names:
|
|
510
|
+
raise InvalidInputError(
|
|
511
|
+
f"The buffer name '{name}' is used two times. Use different property names."
|
|
512
|
+
)
|
|
513
|
+
self.names.add(name)
|
|
514
|
+
self.buffers.append((name, array))
|
|
515
|
+
|
|
516
|
+
def add_geometry(self, role: str, array: np.ndarray) -> None:
|
|
517
|
+
"""Add a geometry buffer for a role."""
|
|
518
|
+
name = f"geometry/{role}"
|
|
519
|
+
self.add_buffer(name, array)
|
|
520
|
+
self.geometry[role] = name
|
|
521
|
+
|
|
522
|
+
def add_vertices(self, verts: np.ndarray) -> None:
|
|
523
|
+
"""Shift the vertices in f64 and add them as f32 or f64."""
|
|
524
|
+
# Use the declared size first. Do not copy the array before this check.
|
|
525
|
+
self.reserve(int(verts.size) * 8)
|
|
526
|
+
# The shift makes one new f64 array. The array of the caller does not change.
|
|
527
|
+
shifted = np.subtract(verts, self.origin, dtype=np.float64)
|
|
528
|
+
low = float(shifted.min()) if shifted.size else 0.0
|
|
529
|
+
high = float(shifted.max()) if shifted.size else 0.0
|
|
530
|
+
if not (np.isfinite(low) and np.isfinite(high)):
|
|
531
|
+
raise InvalidInputError("The vertices must be finite numbers. Check the input.")
|
|
532
|
+
if max(abs(low), abs(high)) > protocol.F32_LIMIT:
|
|
533
|
+
self.add_geometry("vertices", shifted)
|
|
534
|
+
else:
|
|
535
|
+
self.add_geometry("vertices", shifted.astype(np.float32))
|
|
536
|
+
|
|
537
|
+
def add_index(self, role: str, array: object) -> None:
|
|
538
|
+
"""Add an index buffer as u32."""
|
|
539
|
+
view = np.asarray(array)
|
|
540
|
+
self.reserve(int(view.size) * 4)
|
|
541
|
+
self.add_geometry(role, view.astype(np.uint32, copy=False))
|
|
542
|
+
|
|
543
|
+
def add_property(
|
|
544
|
+
self, name: str, value: object, association: str, log_set: str | None = None
|
|
545
|
+
) -> None:
|
|
546
|
+
"""Add a property with its buffers. A log set name is optional."""
|
|
547
|
+
self.reserve(_declared_bytes(name, value))
|
|
548
|
+
desc, buffers = _data_array(name, value, association, log_set)
|
|
549
|
+
for buffer_name, array in buffers:
|
|
550
|
+
self.add_buffer(buffer_name, array)
|
|
551
|
+
self.data.append(desc)
|
|
552
|
+
|
|
553
|
+
def add_properties(
|
|
554
|
+
self, props: Mapping[str, object], association: str, log_set: str | None = None
|
|
555
|
+
) -> None:
|
|
556
|
+
"""Add a mapping of properties. A log set name is optional."""
|
|
557
|
+
for name, value in props.items():
|
|
558
|
+
self.add_property(name, value, association, log_set)
|
|
559
|
+
|
|
560
|
+
def add_pair_group(self, role: str, names: tuple[str, str], pair: Sequence[object]) -> None:
|
|
561
|
+
"""Add a property group of two float arrays, such as orientation."""
|
|
562
|
+
members = []
|
|
563
|
+
for member_role, values in zip(names, pair):
|
|
564
|
+
data_name = f"{role}/{member_role}"
|
|
565
|
+
self.add_property(data_name, np.asarray(values, dtype=np.float64), "vertex")
|
|
566
|
+
members.append({"role": member_role, "data": data_name})
|
|
567
|
+
self.groups.append({"id": role, "name": role, "role": role, "members": members})
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def _finite_f64(value: object, label: str) -> np.ndarray:
|
|
571
|
+
"""Return a finite float64 array. Raise if a value is NaN or infinite."""
|
|
572
|
+
arr = np.asarray(value, dtype=np.float64)
|
|
573
|
+
if not np.all(np.isfinite(arr)):
|
|
574
|
+
raise InvalidInputError(f"The field '{label}' must be finite numbers. Check the input.")
|
|
575
|
+
return arr
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def encode_object(
|
|
579
|
+
obj: SceneObject,
|
|
580
|
+
*,
|
|
581
|
+
id: str,
|
|
582
|
+
name: str | None,
|
|
583
|
+
parent: str | None,
|
|
584
|
+
revision: int,
|
|
585
|
+
origin: Sequence[float],
|
|
586
|
+
) -> bytes:
|
|
587
|
+
"""Return the ``scene.upsert`` frame for an object.
|
|
588
|
+
|
|
589
|
+
The function subtracts the origin from the coordinates in float64. Then it
|
|
590
|
+
writes the vertices as f32 if all values are near the origin, or as f64 if not.
|
|
591
|
+
|
|
592
|
+
Parameters
|
|
593
|
+
----------
|
|
594
|
+
obj : SceneObject
|
|
595
|
+
The object to encode.
|
|
596
|
+
id : str
|
|
597
|
+
The identifier of the object.
|
|
598
|
+
name : str or None
|
|
599
|
+
The display name. If it is None, the name is the identifier.
|
|
600
|
+
parent : str or None
|
|
601
|
+
The identifier of the parent group.
|
|
602
|
+
revision : int
|
|
603
|
+
The revision number.
|
|
604
|
+
origin : sequence of float
|
|
605
|
+
The scene origin, three values.
|
|
606
|
+
|
|
607
|
+
Returns
|
|
608
|
+
-------
|
|
609
|
+
bytes
|
|
610
|
+
The frame.
|
|
611
|
+
|
|
612
|
+
Raises
|
|
613
|
+
------
|
|
614
|
+
InvalidInputError
|
|
615
|
+
If a coordinate is NaN or infinite, or a property is not supported.
|
|
616
|
+
ObjectTooLargeError
|
|
617
|
+
If the object or the frame is over the size limit.
|
|
618
|
+
"""
|
|
619
|
+
try:
|
|
620
|
+
origin_arr = np.asarray(origin, dtype=np.float64)
|
|
621
|
+
except (TypeError, ValueError) as error:
|
|
622
|
+
raise InvalidInputError("The origin must be three numbers. Check the input.") from error
|
|
623
|
+
if origin_arr.shape != (3,) or not np.all(np.isfinite(origin_arr)):
|
|
624
|
+
raise InvalidInputError("The origin must be three finite numbers. Check the input.")
|
|
625
|
+
builder = _Builder(id, origin_arr)
|
|
626
|
+
params: dict[str, Any] = {}
|
|
627
|
+
log_sets: list[dict[str, str]] = []
|
|
628
|
+
if isinstance(obj, Drillhole):
|
|
629
|
+
object_type = "Drillhole"
|
|
630
|
+
builder.reserve(
|
|
631
|
+
(3 + int(np.asarray(obj.survey).size) + int(np.asarray(obj.intervals).size)) * 8
|
|
632
|
+
)
|
|
633
|
+
collar = _finite_f64(obj.collar, "collar") - origin_arr
|
|
634
|
+
builder.add_geometry("collar", collar)
|
|
635
|
+
builder.add_geometry("survey", _finite_f64(obj.survey, "survey"))
|
|
636
|
+
builder.add_geometry("intervals", _finite_f64(obj.intervals, "intervals"))
|
|
637
|
+
if obj.end_of_hole is not None:
|
|
638
|
+
params["end_of_hole"] = [float(obj.end_of_hole)]
|
|
639
|
+
builder.add_properties(obj.properties, "vertex")
|
|
640
|
+
if obj.interval_properties:
|
|
641
|
+
log_sets.append({"name": _INTERVAL_LOG_SET, "kind": "interval"})
|
|
642
|
+
builder.add_properties(obj.interval_properties, "interval", _INTERVAL_LOG_SET)
|
|
643
|
+
elif isinstance(obj, BlockModel):
|
|
644
|
+
object_type = "BlockModel"
|
|
645
|
+
shifted = _finite_f64(obj.origin, "origin") - origin_arr
|
|
646
|
+
params["origin"] = [float(v) for v in shifted]
|
|
647
|
+
params["cell_sizes"] = [float(v) for v in np.asarray(obj.cell_sizes)]
|
|
648
|
+
params["cells"] = [int(v) for v in np.asarray(obj.cells)]
|
|
649
|
+
builder.add_properties(obj.properties, "vertex")
|
|
650
|
+
builder.add_properties(obj.cell_properties, "cell")
|
|
651
|
+
else:
|
|
652
|
+
if isinstance(obj, Lines):
|
|
653
|
+
object_type, index_role, index_attr = "Curve", "segments", "segments"
|
|
654
|
+
elif isinstance(obj, Surface):
|
|
655
|
+
object_type, index_role, index_attr = "Surface", "triangles", "triangles"
|
|
656
|
+
elif isinstance(obj, TetraMesh):
|
|
657
|
+
object_type, index_role, index_attr = "TetraMesh", "tetrahedra", "tetrahedra"
|
|
658
|
+
elif isinstance(obj, (Points, Vectors)):
|
|
659
|
+
object_type, index_role, index_attr = "Points", "", ""
|
|
660
|
+
else:
|
|
661
|
+
raise InvalidInputError(
|
|
662
|
+
f"The object type {type(obj).__name__} is not supported. "
|
|
663
|
+
"Use Points, Vectors, Lines, Surface, BlockModel, TetraMesh or Drillhole."
|
|
664
|
+
)
|
|
665
|
+
builder.add_vertices(obj.vertices)
|
|
666
|
+
if index_role:
|
|
667
|
+
builder.add_index(index_role, getattr(obj, index_attr))
|
|
668
|
+
if isinstance(obj, Vectors):
|
|
669
|
+
if obj.orientation is not None:
|
|
670
|
+
builder.add_pair_group("orientation", ("dip_direction", "dip"), obj.orientation)
|
|
671
|
+
if obj.lineation is not None:
|
|
672
|
+
builder.add_pair_group("lineation", ("trend", "plunge"), obj.lineation)
|
|
673
|
+
builder.add_properties(obj.properties, "vertex")
|
|
674
|
+
cell_properties = getattr(obj, "cell_properties", None)
|
|
675
|
+
if cell_properties:
|
|
676
|
+
builder.add_properties(cell_properties, "cell")
|
|
677
|
+
|
|
678
|
+
header = _upsert_header(id, object_type, name, parent, revision)
|
|
679
|
+
header["geometry"] = builder.geometry
|
|
680
|
+
header["params"] = params
|
|
681
|
+
header["data"] = builder.data
|
|
682
|
+
header["property_groups"] = builder.groups
|
|
683
|
+
if log_sets:
|
|
684
|
+
header["log_sets"] = log_sets
|
|
685
|
+
try:
|
|
686
|
+
return protocol.encode_frame(header, builder.buffers)
|
|
687
|
+
except protocol.ProtocolError as error:
|
|
688
|
+
raise ObjectTooLargeError(id, builder.declared, protocol.MAX_FRAME_BYTES) from error
|