zarr-vectors 0.2.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.
Files changed (76) hide show
  1. zarr_vectors/__init__.py +52 -0
  2. zarr_vectors/_version.py +24 -0
  3. zarr_vectors/composite.py +486 -0
  4. zarr_vectors/constants.py +330 -0
  5. zarr_vectors/core/__init__.py +0 -0
  6. zarr_vectors/core/_batch_reader.py +143 -0
  7. zarr_vectors/core/_batch_writer.py +240 -0
  8. zarr_vectors/core/arrays.py +1786 -0
  9. zarr_vectors/core/attr_chunking.py +118 -0
  10. zarr_vectors/core/backends/__init__.py +203 -0
  11. zarr_vectors/core/backends/async_base.py +84 -0
  12. zarr_vectors/core/backends/base.py +84 -0
  13. zarr_vectors/core/backends/fsspec_backend.py +226 -0
  14. zarr_vectors/core/backends/icechunk_backend.py +183 -0
  15. zarr_vectors/core/backends/local.py +175 -0
  16. zarr_vectors/core/backends/obstore_backend.py +265 -0
  17. zarr_vectors/core/group.py +546 -0
  18. zarr_vectors/core/metadata.py +1125 -0
  19. zarr_vectors/core/multiscale.py +281 -0
  20. zarr_vectors/core/paths.py +75 -0
  21. zarr_vectors/core/store.py +1429 -0
  22. zarr_vectors/encoding/__init__.py +0 -0
  23. zarr_vectors/encoding/categorical.py +185 -0
  24. zarr_vectors/encoding/compression.py +148 -0
  25. zarr_vectors/encoding/draco.py +264 -0
  26. zarr_vectors/encoding/fragments.py +682 -0
  27. zarr_vectors/encoding/ragged.py +234 -0
  28. zarr_vectors/exceptions.py +63 -0
  29. zarr_vectors/headers/__init__.py +11 -0
  30. zarr_vectors/headers/registry.py +116 -0
  31. zarr_vectors/lazy/__init__.py +20 -0
  32. zarr_vectors/lazy/arrays.py +363 -0
  33. zarr_vectors/lazy/level.py +403 -0
  34. zarr_vectors/lazy/store.py +218 -0
  35. zarr_vectors/lazy/views.py +522 -0
  36. zarr_vectors/lazy/writer.py +663 -0
  37. zarr_vectors/multiresolution/__init__.py +0 -0
  38. zarr_vectors/multiresolution/coarsen.py +957 -0
  39. zarr_vectors/multiresolution/metanodes.py +127 -0
  40. zarr_vectors/multiresolution/object_selection.py +406 -0
  41. zarr_vectors/multiresolution/strategies/__init__.py +0 -0
  42. zarr_vectors/multiresolution/strategies/graphs.py +280 -0
  43. zarr_vectors/multiresolution/strategies/meshes.py +229 -0
  44. zarr_vectors/multiresolution/strategies/points.py +196 -0
  45. zarr_vectors/multiresolution/strategies/polylines.py +282 -0
  46. zarr_vectors/ops/__init__.py +0 -0
  47. zarr_vectors/rechunk/__init__.py +61 -0
  48. zarr_vectors/rechunk/engine.py +349 -0
  49. zarr_vectors/rechunk/rebin.py +200 -0
  50. zarr_vectors/rechunk/spec.py +181 -0
  51. zarr_vectors/sharding/__init__.py +16 -0
  52. zarr_vectors/sharding/hilbert.py +140 -0
  53. zarr_vectors/sharding/io.py +321 -0
  54. zarr_vectors/sharding/layout.py +98 -0
  55. zarr_vectors/sharding/morton.py +69 -0
  56. zarr_vectors/spatial/__init__.py +0 -0
  57. zarr_vectors/spatial/boundary.py +444 -0
  58. zarr_vectors/spatial/chunking.py +429 -0
  59. zarr_vectors/types/__init__.py +0 -0
  60. zarr_vectors/types/graphs.py +854 -0
  61. zarr_vectors/types/lines.py +515 -0
  62. zarr_vectors/types/meshes.py +591 -0
  63. zarr_vectors/types/parametric.py +317 -0
  64. zarr_vectors/types/points.py +830 -0
  65. zarr_vectors/types/polylines.py +691 -0
  66. zarr_vectors/typing.py +104 -0
  67. zarr_vectors/validate/__init__.py +40 -0
  68. zarr_vectors/validate/conformance.py +192 -0
  69. zarr_vectors/validate/consistency.py +204 -0
  70. zarr_vectors/validate/metadata.py +170 -0
  71. zarr_vectors/validate/structure.py +125 -0
  72. zarr_vectors-0.2.0.dist-info/METADATA +103 -0
  73. zarr_vectors-0.2.0.dist-info/RECORD +76 -0
  74. zarr_vectors-0.2.0.dist-info/WHEEL +5 -0
  75. zarr_vectors-0.2.0.dist-info/licenses/LICENSE +11 -0
  76. zarr_vectors-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,52 @@
1
+ """
2
+ zarr-vectors: Python utilities for the Zarr Vectors (ZV) format.
3
+
4
+ Cloud-native storage for points, lines, streamlines, graphs, and meshes
5
+ built on Zarr v3.
6
+ """
7
+
8
+ from zarr_vectors.core.backends import StorageBackend, detect_scheme
9
+ from zarr_vectors.core.group import Group
10
+ from zarr_vectors.core.store import (
11
+ FsGroup,
12
+ create_store,
13
+ open_store,
14
+ rebind,
15
+ )
16
+ from zarr_vectors.lazy.writer import ZVWriter
17
+ from zarr_vectors.rechunk import RechunkSpec, rechunk, rechunk_by_attribute
18
+
19
+ # Version resolution. Three sources in priority order:
20
+ # 1. ``zarr_vectors/_version.py`` — written by setuptools-scm at build
21
+ # time from the git tag (e.g. ``v0.1.0`` → ``0.1.0``). Present in
22
+ # wheels and in any checkout that has been ``pip install -e``'d.
23
+ # 2. ``importlib.metadata`` — the version recorded in the installed
24
+ # package's metadata; covers the case where _version.py is absent
25
+ # but the package is installed.
26
+ # 3. ``"0.0.0+unknown"`` — running from a raw source checkout that
27
+ # has never been built or installed. Tools that key on version
28
+ # should treat this as a sentinel.
29
+ try:
30
+ from zarr_vectors._version import __version__ # type: ignore[no-redef]
31
+ except ImportError:
32
+ from importlib.metadata import PackageNotFoundError
33
+ from importlib.metadata import version as _pkg_version
34
+ try:
35
+ __version__ = _pkg_version("zarr-vectors")
36
+ except PackageNotFoundError:
37
+ __version__ = "0.0.0+unknown"
38
+
39
+ __all__ = [
40
+ "StorageBackend",
41
+ "Group",
42
+ "FsGroup",
43
+ "create_store",
44
+ "open_store",
45
+ "rebind",
46
+ "detect_scheme",
47
+ "RechunkSpec",
48
+ "rechunk",
49
+ "rechunk_by_attribute",
50
+ "ZVWriter",
51
+ "__version__",
52
+ ]
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.2.0'
22
+ __version_tuple__ = version_tuple = (0, 2, 0)
23
+
24
+ __commit_id__ = commit_id = None
@@ -0,0 +1,486 @@
1
+ """Composite stores — multiple geometry types in one zarr vectors store.
2
+
3
+ A single ``.zarrvectors`` store can hold points, streamlines, meshes,
4
+ and graphs simultaneously. Each geometry type's data is stored under
5
+ a named namespace within the resolution level, tracked by a
6
+ ``geometry_index`` that maps geometry types to their array ranges.
7
+
8
+ Usage::
9
+
10
+ from zarr_vectors.composite import add_geometry, read_composite
11
+
12
+ # Start with a point cloud
13
+ write_points("brain.zarrvectors", positions, chunk_shape=(100, 100, 100))
14
+
15
+ # Add a graph to the same store
16
+ add_geometry("brain.zarrvectors", "graph", positions=nodes, edges=edges)
17
+
18
+ # Read all geometries
19
+ composite = read_composite("brain.zarrvectors")
20
+ print(composite.keys()) # ['point_cloud', 'graph']
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ import numpy as np
30
+ import numpy.typing as npt
31
+
32
+ from zarr_vectors.constants import (
33
+ GEOM_GRAPH,
34
+ GEOM_LINE,
35
+ GEOM_MESH,
36
+ GEOM_POINT_CLOUD,
37
+ GEOM_SKELETON,
38
+ GEOM_STREAMLINE,
39
+ RESOLUTION_PREFIX,
40
+ VERTICES,
41
+ )
42
+ from zarr_vectors.core.arrays import (
43
+ create_object_index_array,
44
+ create_vertices_array,
45
+ list_chunk_keys,
46
+ read_chunk_vertices,
47
+ write_chunk_vertices,
48
+ write_object_index,
49
+ )
50
+ from zarr_vectors.core.metadata import LevelMetadata, RootMetadata
51
+ from zarr_vectors.core.store import (
52
+ FsGroup,
53
+ _create_or_open_store,
54
+ _ensure_root_metadata_for_write,
55
+ create_resolution_level,
56
+ get_resolution_level,
57
+ open_store,
58
+ read_root_metadata,
59
+ )
60
+ from zarr_vectors.spatial.chunking import assign_chunks, compute_bounds
61
+ from zarr_vectors.typing import ChunkCoords, ObjectManifest
62
+
63
+
64
+ # ===================================================================
65
+ # Geometry index
66
+ # ===================================================================
67
+
68
+ def _read_geometry_index(level_group: FsGroup) -> dict[str, dict[str, Any]]:
69
+ """Read the geometry index from a level group.
70
+
71
+ Returns:
72
+ ``{geometry_type: {"vertex_range": [start, end], ...}}``
73
+ """
74
+ try:
75
+ gi_group = level_group["geometry_index"]
76
+ return gi_group.attrs.to_dict()
77
+ except Exception:
78
+ return {}
79
+
80
+
81
+ def _write_geometry_index(
82
+ level_group: FsGroup,
83
+ index: dict[str, dict[str, Any]],
84
+ ) -> None:
85
+ """Write/update the geometry index on a level group."""
86
+ gi_group = level_group.require_group("geometry_index")
87
+ gi_group.attrs.update(index)
88
+
89
+
90
+ def _update_root_geometry_types(
91
+ root: FsGroup,
92
+ new_type: str,
93
+ ) -> None:
94
+ """Add a geometry type to the root metadata if not already present."""
95
+ attrs = root.attrs.to_dict()
96
+ zv = attrs.get("zarr_vectors", attrs)
97
+ current_types = zv.get("geometry_types", [])
98
+ if new_type not in current_types:
99
+ current_types.append(new_type)
100
+ zv["geometry_types"] = current_types
101
+ if "zarr_vectors" in attrs:
102
+ attrs["zarr_vectors"] = zv
103
+ root.attrs.update(attrs)
104
+
105
+
106
+ # ===================================================================
107
+ # Add geometry to existing store
108
+ # ===================================================================
109
+
110
+ def add_geometry(
111
+ store_path: str | Path,
112
+ geometry_type: str,
113
+ *,
114
+ positions: npt.NDArray[np.floating] | None = None,
115
+ edges: npt.NDArray[np.integer] | None = None,
116
+ faces: npt.NDArray[np.integer] | None = None,
117
+ polylines: list[npt.NDArray[np.floating]] | None = None,
118
+ vertex_attributes: dict[str, npt.NDArray] | None = None,
119
+ level: int = 0,
120
+ # Deprecated alias:
121
+ attributes: dict[str, npt.NDArray] | None = None,
122
+ ) -> dict[str, Any]:
123
+ """Add a geometry type to an existing zarr vectors store.
124
+
125
+ The new geometry's vertex data is written to a namespaced array
126
+ ``vertices_<geometry_type>/`` within the same resolution level.
127
+ A geometry index tracks which arrays belong to which type.
128
+
129
+ Args:
130
+ store_path: Path to an existing store.
131
+ geometry_type: One of ``"point_cloud"``, ``"graph"``,
132
+ ``"skeleton"``, ``"mesh"``, ``"streamline"``, ``"line"``.
133
+ positions: ``(N, D)`` vertex positions (for points, graphs, meshes).
134
+ edges: ``(E, 2)`` edge array (for graphs/skeletons).
135
+ faces: ``(F, L)`` face array (for meshes).
136
+ polylines: List of ``(N_k, D)`` arrays (for streamlines).
137
+ vertex_attributes: Per-vertex attributes ``{name: array}``.
138
+ (Spec name; replaces ``attributes``.)
139
+ level: Resolution level to add to (default 0).
140
+
141
+ Returns:
142
+ Summary dict with ``vertex_count``, ``geometry_type``.
143
+
144
+ Raises:
145
+ ValueError: If the geometry type requires data not provided.
146
+ """
147
+ # Back-compat: accept the legacy `attributes` kwarg.
148
+ if attributes is not None:
149
+ if vertex_attributes is not None:
150
+ raise TypeError(
151
+ "got both `attributes` and `vertex_attributes`; "
152
+ "pass only `vertex_attributes`."
153
+ )
154
+ import warnings
155
+ warnings.warn(
156
+ "`attributes` is deprecated; use `vertex_attributes`.",
157
+ DeprecationWarning, stacklevel=2,
158
+ )
159
+ vertex_attributes = attributes
160
+
161
+ store_path = Path(store_path)
162
+ sample_points: npt.NDArray | None = None
163
+ if positions is not None:
164
+ sample_points = np.asarray(positions)
165
+ elif polylines:
166
+ sample_points = np.concatenate([np.asarray(p) for p in polylines], axis=0)
167
+
168
+ create_kwargs: dict[str, Any] = {}
169
+ if sample_points is not None and sample_points.size > 0:
170
+ inferred_bounds = compute_bounds(sample_points)
171
+ create_kwargs["bounds"] = (
172
+ inferred_bounds[0].tolist(),
173
+ inferred_bounds[1].tolist(),
174
+ )
175
+ create_kwargs["ndim"] = int(sample_points.shape[1])
176
+
177
+ root = _create_or_open_store(str(store_path), **create_kwargs)
178
+
179
+ if sample_points is None or sample_points.size == 0:
180
+ meta = read_root_metadata(root)
181
+ else:
182
+ meta = _ensure_root_metadata_for_write(
183
+ root,
184
+ inferred_ndim=int(sample_points.shape[1]),
185
+ geometry_type=geometry_type,
186
+ )
187
+ ndim = meta.sid_ndim
188
+ chunk_shape = meta.chunk_shape
189
+
190
+ # Get or create the level group
191
+ try:
192
+ level_group = get_resolution_level(root, level)
193
+ except Exception:
194
+ level_meta = LevelMetadata(
195
+ level=level, vertex_count=0, arrays_present=[VERTICES],
196
+ )
197
+ level_group = create_resolution_level(root, level, level_meta)
198
+
199
+ # Determine the namespaced array name
200
+ array_namespace = f"vertices_{geometry_type}"
201
+
202
+ # Read existing geometry index
203
+ geom_index = _read_geometry_index(level_group)
204
+
205
+ vertex_count = 0
206
+
207
+ if geometry_type in (GEOM_POINT_CLOUD,):
208
+ if positions is None:
209
+ raise ValueError("Point cloud requires 'positions'")
210
+ vertex_count = _write_namespaced_vertices(
211
+ level_group, array_namespace, positions, chunk_shape, ndim,
212
+ )
213
+ geom_index[geometry_type] = {
214
+ "array": array_namespace,
215
+ "vertex_count": vertex_count,
216
+ "has_links": False,
217
+ }
218
+
219
+ elif geometry_type in (GEOM_GRAPH, GEOM_SKELETON):
220
+ if positions is None:
221
+ raise ValueError(f"{geometry_type} requires 'positions'")
222
+ vertex_count = _write_namespaced_vertices(
223
+ level_group, array_namespace, positions, chunk_shape, ndim,
224
+ )
225
+ links_ns = f"links_{geometry_type}"
226
+ if edges is not None:
227
+ _write_namespaced_links(level_group, links_ns, edges)
228
+ geom_index[geometry_type] = {
229
+ "array": array_namespace,
230
+ "vertex_count": vertex_count,
231
+ "links_array": links_ns if edges is not None else None,
232
+ "edge_count": len(edges) if edges is not None else 0,
233
+ "has_links": edges is not None,
234
+ }
235
+
236
+ elif geometry_type == GEOM_MESH:
237
+ if positions is None:
238
+ raise ValueError("Mesh requires 'positions'")
239
+ vertex_count = _write_namespaced_vertices(
240
+ level_group, array_namespace, positions, chunk_shape, ndim,
241
+ )
242
+ links_ns = f"links_{geometry_type}"
243
+ if faces is not None:
244
+ _write_namespaced_links(level_group, links_ns, faces)
245
+ geom_index[geometry_type] = {
246
+ "array": array_namespace,
247
+ "vertex_count": vertex_count,
248
+ "links_array": links_ns if faces is not None else None,
249
+ "face_count": len(faces) if faces is not None else 0,
250
+ "has_links": faces is not None,
251
+ }
252
+
253
+ elif geometry_type in (GEOM_STREAMLINE, "polyline"):
254
+ if polylines is None:
255
+ raise ValueError("Streamlines require 'polylines'")
256
+ # Concatenate all polyline vertices and write
257
+ all_verts = np.concatenate(polylines, axis=0).astype(np.float32)
258
+ vertex_count = _write_namespaced_vertices(
259
+ level_group, array_namespace, all_verts, chunk_shape, ndim,
260
+ )
261
+ geom_index[geometry_type] = {
262
+ "array": array_namespace,
263
+ "vertex_count": vertex_count,
264
+ "polyline_count": len(polylines),
265
+ "has_links": False,
266
+ }
267
+
268
+ elif geometry_type == GEOM_LINE:
269
+ if positions is None:
270
+ raise ValueError("Lines require 'positions' (endpoints)")
271
+ vertex_count = _write_namespaced_vertices(
272
+ level_group, array_namespace, positions, chunk_shape, ndim,
273
+ )
274
+ geom_index[geometry_type] = {
275
+ "array": array_namespace,
276
+ "vertex_count": vertex_count,
277
+ "has_links": False,
278
+ }
279
+
280
+ else:
281
+ raise ValueError(f"Unknown geometry type: '{geometry_type}'")
282
+
283
+ # Update geometry index
284
+ _write_geometry_index(level_group, geom_index)
285
+
286
+ # Update root metadata geometry_types
287
+ _update_root_geometry_types(root, geometry_type)
288
+
289
+ return {
290
+ "geometry_type": geometry_type,
291
+ "vertex_count": vertex_count,
292
+ "array_namespace": array_namespace,
293
+ }
294
+
295
+
296
+ # ===================================================================
297
+ # Read composite
298
+ # ===================================================================
299
+
300
+ def read_composite(
301
+ store_path: str | Path,
302
+ level: int = 0,
303
+ ) -> dict[str, dict[str, Any]]:
304
+ """Read all geometry types from a composite store.
305
+
306
+ Returns:
307
+ ``{geometry_type: {"positions": ..., "vertex_count": ..., ...}}``
308
+ for each geometry type present in the store.
309
+ """
310
+ store_path = Path(store_path)
311
+ root = open_store(str(store_path))
312
+ meta = read_root_metadata(root)
313
+ ndim = meta.sid_ndim
314
+
315
+ level_group = get_resolution_level(root, level)
316
+ geom_index = _read_geometry_index(level_group)
317
+
318
+ result: dict[str, dict[str, Any]] = {}
319
+
320
+ if geom_index:
321
+ # Composite store with geometry index — read namespaced arrays
322
+ for geom_type, info in geom_index.items():
323
+ array_name = info.get("array", f"vertices_{geom_type}")
324
+ try:
325
+ positions = _read_namespaced_vertices(
326
+ level_group, array_name, ndim,
327
+ )
328
+ entry: dict[str, Any] = {
329
+ "positions": positions,
330
+ "vertex_count": len(positions),
331
+ }
332
+ links_array = info.get("links_array")
333
+ if links_array and info.get("has_links"):
334
+ try:
335
+ links = _read_namespaced_links(level_group, links_array)
336
+ entry["links"] = links
337
+ if "edge_count" in info:
338
+ entry["edge_count"] = info["edge_count"]
339
+ if "face_count" in info:
340
+ entry["face_count"] = info["face_count"]
341
+ except Exception:
342
+ pass
343
+ if "polyline_count" in info:
344
+ entry["polyline_count"] = info["polyline_count"]
345
+ result[geom_type] = entry
346
+ except Exception:
347
+ result[geom_type] = {"vertex_count": 0, "error": "unreadable"}
348
+
349
+ # Also read standard vertices/ for geometry types NOT in the index
350
+ # (the original geometry written via write_points/write_graph etc.)
351
+ indexed_types = set(geom_index.keys())
352
+ for geom_type in meta.geometry_types:
353
+ if geom_type not in indexed_types and geom_type not in result:
354
+ try:
355
+ chunk_keys = list_chunk_keys(level_group)
356
+ all_verts: list[npt.NDArray] = []
357
+ for ck in chunk_keys:
358
+ groups = read_chunk_vertices(
359
+ level_group, ck, dtype=np.float32, ndim=ndim,
360
+ )
361
+ for g in groups:
362
+ if len(g) > 0:
363
+ all_verts.append(g)
364
+ if all_verts:
365
+ positions = np.concatenate(all_verts, axis=0)
366
+ else:
367
+ positions = np.zeros((0, ndim), dtype=np.float32)
368
+ result[geom_type] = {
369
+ "positions": positions,
370
+ "vertex_count": len(positions),
371
+ }
372
+ except Exception:
373
+ result[geom_type] = {"vertex_count": 0, "error": "unreadable"}
374
+ else:
375
+ # Single-geometry store (no geometry index) — read via standard path
376
+ for geom_type in meta.geometry_types:
377
+ try:
378
+ chunk_keys = list_chunk_keys(level_group)
379
+ all_verts: list[npt.NDArray] = []
380
+ for ck in chunk_keys:
381
+ groups = read_chunk_vertices(
382
+ level_group, ck, dtype=np.float32, ndim=ndim,
383
+ )
384
+ for g in groups:
385
+ if len(g) > 0:
386
+ all_verts.append(g)
387
+ if all_verts:
388
+ positions = np.concatenate(all_verts, axis=0)
389
+ else:
390
+ positions = np.zeros((0, ndim), dtype=np.float32)
391
+ result[geom_type] = {
392
+ "positions": positions,
393
+ "vertex_count": len(positions),
394
+ }
395
+ except Exception:
396
+ result[geom_type] = {"vertex_count": 0, "error": "unreadable"}
397
+
398
+ return result
399
+
400
+
401
+ # ===================================================================
402
+ # Helpers
403
+ # ===================================================================
404
+
405
+ def _write_namespaced_vertices(
406
+ level_group: FsGroup,
407
+ array_name: str,
408
+ positions: npt.NDArray[np.floating],
409
+ chunk_shape: tuple[float, ...],
410
+ ndim: int,
411
+ ) -> int:
412
+ """Write vertices to a namespaced array within a level."""
413
+ positions = np.asarray(positions, dtype=np.float32)
414
+ n_verts = len(positions)
415
+
416
+ arr_group = level_group.require_group(array_name)
417
+ arr_group.attrs.update({
418
+ "dtype": "float32",
419
+ "ndim": ndim,
420
+ "vertex_count": n_verts,
421
+ })
422
+
423
+ chunk_assignments = assign_chunks(positions, chunk_shape)
424
+
425
+ for chunk_coords, global_indices in sorted(chunk_assignments.items()):
426
+ chunk_verts = positions[global_indices]
427
+ key = ".".join(str(c) for c in chunk_coords)
428
+
429
+ raw = chunk_verts.astype(np.float32).tobytes()
430
+ level_group.write_bytes(array_name, key, raw)
431
+
432
+ return n_verts
433
+
434
+
435
+ def _read_namespaced_vertices(
436
+ level_group: FsGroup,
437
+ array_name: str,
438
+ ndim: int,
439
+ ) -> npt.NDArray[np.float32]:
440
+ """Read all vertices from a namespaced array."""
441
+ if not level_group.array_exists(array_name):
442
+ return np.zeros((0, ndim), dtype=np.float32)
443
+
444
+ parts: list[npt.NDArray] = []
445
+ for chunk_key in level_group.list_chunks(array_name):
446
+ raw = level_group.read_bytes(array_name, chunk_key)
447
+ if raw:
448
+ arr = np.frombuffer(raw, dtype=np.float32).reshape(-1, ndim)
449
+ parts.append(arr)
450
+
451
+ if not parts:
452
+ return np.zeros((0, ndim), dtype=np.float32)
453
+ return np.concatenate(parts, axis=0)
454
+
455
+
456
+ def _write_namespaced_links(
457
+ level_group: FsGroup,
458
+ array_name: str,
459
+ links: npt.NDArray[np.integer],
460
+ ) -> None:
461
+ """Write links (edges/faces) to a namespaced array."""
462
+ links = np.asarray(links, dtype=np.int64)
463
+ level_group.write_bytes(array_name, "data", links.tobytes())
464
+ link_group = level_group.require_group(array_name)
465
+ link_group.attrs.update({
466
+ "link_count": len(links),
467
+ "link_width": links.shape[1] if links.ndim == 2 else 2,
468
+ })
469
+
470
+
471
+ def _read_namespaced_links(
472
+ level_group: FsGroup,
473
+ array_name: str,
474
+ ) -> npt.NDArray[np.int64]:
475
+ """Read links from a namespaced array."""
476
+ if not level_group.array_exists(array_name):
477
+ return np.zeros((0, 2), dtype=np.int64)
478
+ if not level_group.chunk_exists(array_name, "data"):
479
+ return np.zeros((0, 2), dtype=np.int64)
480
+ raw = level_group.read_bytes(array_name, "data")
481
+ try:
482
+ link_group = level_group[array_name]
483
+ link_width = link_group.attrs.to_dict().get("link_width", 2)
484
+ except Exception:
485
+ link_width = 2
486
+ return np.frombuffer(raw, dtype=np.int64).reshape(-1, link_width)