vvox 0.4.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.
vvox/__init__.py ADDED
@@ -0,0 +1,31 @@
1
+ from vvox.mesh import prepare_mesh, validate_prepared_mesh
2
+ from vvox.pipeline import voxelize_mesh, voxelize_mesh_on_grid
3
+ from vvox.types import (
4
+ DenseGrid,
5
+ GridMetadata,
6
+ MeshArrays,
7
+ MeshInspection,
8
+ MeshRepairAction,
9
+ MeshRepairReport,
10
+ PreparedMesh,
11
+ SparseBrickGrid,
12
+ VoxelizationDiagnostics,
13
+ VoxelizationResult,
14
+ )
15
+
16
+ __all__ = [
17
+ "DenseGrid",
18
+ "GridMetadata",
19
+ "MeshArrays",
20
+ "MeshInspection",
21
+ "MeshRepairAction",
22
+ "MeshRepairReport",
23
+ "PreparedMesh",
24
+ "SparseBrickGrid",
25
+ "VoxelizationDiagnostics",
26
+ "VoxelizationResult",
27
+ "prepare_mesh",
28
+ "validate_prepared_mesh",
29
+ "voxelize_mesh",
30
+ "voxelize_mesh_on_grid",
31
+ ]
vvox/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from vvox.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
vvox/backend.py ADDED
@@ -0,0 +1,210 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ from contextlib import contextmanager
6
+ from math import ceil
7
+ from pathlib import Path
8
+ from tempfile import NamedTemporaryFile, TemporaryDirectory
9
+ from typing import Any
10
+
11
+ from vvox.errors import MemoryLimitError, MissingDependencyError
12
+ from vvox.kernels import CUDA_KERNELS
13
+
14
+ _RAW_MODULE = None
15
+ _CUDA_ENV_CONFIGURED = False
16
+ _DLL_DIRECTORY_HANDLES: list[Any] = []
17
+ _TEMPORARY_CACHE_DIRECTORIES: list[TemporaryDirectory[str]] = []
18
+
19
+
20
+ def _normalize_path(path: str | Path) -> str:
21
+ return str(Path(path).resolve()).casefold()
22
+
23
+
24
+ def _prepend_env_path(path: Path) -> None:
25
+ current = os.environ.get("PATH", "")
26
+ entries = [entry for entry in current.split(os.pathsep) if entry]
27
+ normalized_target = _normalize_path(path)
28
+ if any(_normalize_path(entry) == normalized_target for entry in entries):
29
+ return
30
+ os.environ["PATH"] = str(path) if not current else f"{path}{os.pathsep}{current}"
31
+
32
+
33
+ def _register_windows_dll_directory(path: Path) -> None:
34
+ if os.name != "nt" or not path.exists():
35
+ return
36
+ _prepend_env_path(path)
37
+ add_dll_directory = getattr(os, "add_dll_directory", None)
38
+ if callable(add_dll_directory):
39
+ _DLL_DIRECTORY_HANDLES.append(add_dll_directory(str(path)))
40
+
41
+
42
+ def _cache_directory_is_writable(cache_dir: Path) -> bool:
43
+ try:
44
+ cache_dir.mkdir(parents=True, exist_ok=True)
45
+ with NamedTemporaryFile(dir=cache_dir, prefix=".vvox-write-test-"):
46
+ pass
47
+ except OSError:
48
+ return False
49
+ return True
50
+
51
+
52
+ def _configure_temporary_cupy_cache() -> None:
53
+ os.environ.setdefault("CUPY_CACHE_IN_MEMORY", "1")
54
+ try:
55
+ temporary_cache = TemporaryDirectory(prefix="vvox-cupy-cache-")
56
+ except OSError:
57
+ return
58
+ _TEMPORARY_CACHE_DIRECTORIES.append(temporary_cache)
59
+ os.environ["CUPY_CACHE_DIR"] = temporary_cache.name
60
+
61
+
62
+ def _configure_cupy_cache(prefix: Path) -> None:
63
+ if "CUPY_CACHE_DIR" in os.environ:
64
+ return
65
+ if os.environ.get("CUPY_CACHE_IN_MEMORY") == "1":
66
+ _configure_temporary_cupy_cache()
67
+ return
68
+
69
+ cache_dir = prefix / ".vvox-runtime" / "cupy-cache"
70
+ if _cache_directory_is_writable(cache_dir):
71
+ os.environ["CUPY_CACHE_DIR"] = str(cache_dir)
72
+ else:
73
+ _configure_temporary_cupy_cache()
74
+
75
+
76
+ def configure_cuda_environment() -> None:
77
+ global _CUDA_ENV_CONFIGURED
78
+ if _CUDA_ENV_CONFIGURED:
79
+ return
80
+
81
+ prefix = Path(sys.prefix)
82
+ cuda_root = prefix / "Library" if os.name == "nt" else prefix
83
+ cuda_bin = cuda_root / "bin"
84
+ environment_bin = prefix / "bin"
85
+
86
+ if cuda_bin.exists():
87
+ current_cuda_path = os.environ.get("CUDA_PATH")
88
+ has_valid_cuda_path = (
89
+ bool(current_cuda_path) and (Path(current_cuda_path) / "bin").exists()
90
+ )
91
+ # A POSIX virtual environment has bin/ even when it has no CUDA toolkit.
92
+ has_toolkit_layout = (
93
+ os.name == "nt"
94
+ or (cuda_bin / "nvcc").is_file()
95
+ or (cuda_root / "include" / "cuda_runtime.h").is_file()
96
+ )
97
+ if not has_valid_cuda_path and has_toolkit_layout:
98
+ os.environ["CUDA_PATH"] = str(cuda_root)
99
+ _register_windows_dll_directory(cuda_bin)
100
+ _register_windows_dll_directory(environment_bin)
101
+
102
+ _configure_cupy_cache(prefix)
103
+
104
+ _CUDA_ENV_CONFIGURED = True
105
+
106
+
107
+ def get_cupy() -> Any:
108
+ configure_cuda_environment()
109
+ try:
110
+ import cupy as cp
111
+ except ImportError as exc:
112
+ raise MissingDependencyError(
113
+ "The CUDA backend requires CuPy; install it with 'pip install vvox[cuda]'"
114
+ ) from exc
115
+ return cp
116
+
117
+
118
+ def ceil_div(numerator: int, denominator: int) -> int:
119
+ return int(ceil(numerator / denominator))
120
+
121
+
122
+ @contextmanager
123
+ def use_device(cp: Any, device_id: int):
124
+ with cp.cuda.Device(device_id):
125
+ yield
126
+
127
+
128
+ def get_raw_module(cp: Any):
129
+ global _RAW_MODULE
130
+ if _RAW_MODULE is None:
131
+ _RAW_MODULE = cp.RawModule(
132
+ code=CUDA_KERNELS,
133
+ options=("--std=c++11",),
134
+ name_expressions=(
135
+ "emit_triangle_tiles",
136
+ "count_column_hits",
137
+ "write_column_hits",
138
+ "fill_dense",
139
+ "mark_active_bricks",
140
+ "fill_sparse_bricks",
141
+ "count_column_events_v2",
142
+ "write_column_events_v2",
143
+ "mark_column_event_uncertainty_v2",
144
+ "fill_dense_v2",
145
+ "mark_active_bricks_v2",
146
+ "fill_sparse_bricks_v2",
147
+ "fill_dense_overrides_v2",
148
+ "mark_override_bricks_v2",
149
+ "fill_sparse_overrides_v2",
150
+ ),
151
+ )
152
+ return _RAW_MODULE
153
+
154
+
155
+ def launch_1d(
156
+ kernel: Any, size: int, args: tuple[Any, ...], threads_per_block: int = 128
157
+ ) -> None:
158
+ if size <= 0:
159
+ return
160
+ blocks = ceil_div(size, threads_per_block)
161
+ kernel((blocks,), (threads_per_block,), args)
162
+
163
+
164
+ def estimate_device_bytes(
165
+ shape_xyz: tuple[int, int, int],
166
+ triangle_count: int,
167
+ *,
168
+ include_dense: bool,
169
+ include_sparse: bool,
170
+ brick_size: int,
171
+ ) -> int:
172
+ nx, ny, nz = shape_xyz
173
+ voxel_count = nx * ny * nz
174
+ column_count = nx * ny
175
+ estimate = triangle_count * 64
176
+ estimate += column_count * (8 + 8 + 4)
177
+ # Event count varies with projected surface area. Eight crossings per
178
+ # column is a deliberately conservative planning value for ordinary closed
179
+ # meshes; allocation failures remain execution errors and never trigger an
180
+ # automatic backend switch.
181
+ estimate += column_count * 8 * (4 + 1 + 4 + 4)
182
+
183
+ if include_dense:
184
+ estimate += ceil_div(voxel_count, 64) * 8
185
+
186
+ if include_sparse:
187
+ bx = ceil_div(nx, brick_size)
188
+ by = ceil_div(ny, brick_size)
189
+ bz = ceil_div(nz, brick_size)
190
+ total_bricks = bx * by * bz
191
+ estimate += ceil_div(total_bricks, 64) * 8
192
+ estimate += total_bricks * 4
193
+
194
+ return estimate
195
+
196
+
197
+ def enforce_memory_limit(
198
+ estimated_bytes: int,
199
+ memory_limit_gb: float | None,
200
+ *,
201
+ memory_kind: str = "device",
202
+ ) -> None:
203
+ if memory_limit_gb is None:
204
+ return
205
+ limit_bytes = int(memory_limit_gb * (1024**3))
206
+ if estimated_bytes > limit_bytes:
207
+ raise MemoryLimitError(
208
+ f"Estimated {memory_kind} memory requirement {estimated_bytes / (1024**3):.2f} GiB "
209
+ f"exceeds configured limit {memory_limit_gb:.2f} GiB"
210
+ )
@@ -0,0 +1,11 @@
1
+ from vvox.backends.base import BackendResult, VoxelizationBackend
2
+ from vvox.backends.cuda import CudaBackend
3
+ from vvox.backends.selection import BackendName, select_backend
4
+
5
+ __all__ = [
6
+ "BackendName",
7
+ "BackendResult",
8
+ "CudaBackend",
9
+ "VoxelizationBackend",
10
+ "select_backend",
11
+ ]
vvox/backends/base.py ADDED
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Protocol
5
+
6
+ import numpy as np
7
+
8
+ from vvox.types import (
9
+ DenseGrid,
10
+ GridMetadata,
11
+ SparseBrickGrid,
12
+ VoxelizationDiagnostics,
13
+ )
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class BackendResult:
18
+ dense: DenseGrid | None
19
+ sparse: SparseBrickGrid | None
20
+ diagnostics: VoxelizationDiagnostics
21
+
22
+
23
+ class VoxelizationBackend(Protocol):
24
+ name: str
25
+
26
+ def estimate_memory_bytes(
27
+ self,
28
+ shape_xyz: tuple[int, int, int],
29
+ triangle_count: int,
30
+ outputs: tuple[str, ...],
31
+ ) -> int: ...
32
+
33
+ def voxelize(
34
+ self,
35
+ triangles_voxel: np.ndarray,
36
+ metadata: GridMetadata,
37
+ outputs: tuple[str, ...],
38
+ ) -> BackendResult: ...