File size: 9,399 Bytes
e6be672
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# Copyright (C) 2026 Mattia Zatelli
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

"""
GPU accelerator for intensive geometric calculations

This service provides CUDA acceleration when available, with automatic
fallback to NumPy CPU operations. All methods work identically regardless
of backend.

Supported operations:
- Bounding box calculations
- Centroid calculations
- Volume calculations (divergence theorem)
- Surface area calculations
- Spatial queries (points in box)
"""
import logging
import numpy as np
from typing import List, Dict, Any
from functools import lru_cache

logger = logging.getLogger(__name__)


class CPUAccelerator:
    """NumPy-based CPU fallback with the same interface as GPUAccelerator"""

    def __init__(self):
        self._device_info = {
            "name": "CPU (NumPy)",
            "compute_capability": "N/A",
            "total_memory_gb": 0,
            "multiprocessor_count": 0,
        }
        logger.info("Using CPU (NumPy) for geometric calculations")

    @property
    def device_info(self) -> Dict[str, Any]:
        return self._device_info

    def calculate_bounding_box_batch(self, vertices_list: List[np.ndarray]) -> List[Dict[str, List[float]]]:
        """Calculate bounding boxes using NumPy"""
        if not vertices_list:
            return []

        results = []
        for vertices in vertices_list:
            if len(vertices) == 0:
                results.append({"min": [0.0, 0.0, 0.0], "max": [0.0, 0.0, 0.0]})
                continue

            arr = np.asarray(vertices)
            results.append({
                "min": np.min(arr, axis=0).tolist(),
                "max": np.max(arr, axis=0).tolist(),
            })
        return results

    def calculate_centroids_batch(self, vertices_list: List[np.ndarray]) -> List[List[float]]:
        """Calculate centroids using NumPy"""
        if not vertices_list:
            return []

        results = []
        for vertices in vertices_list:
            if len(vertices) == 0:
                results.append([0.0, 0.0, 0.0])
                continue

            arr = np.asarray(vertices)
            results.append(np.mean(arr, axis=0).tolist())
        return results

    def calculate_volumes_batch(self, triangles_list: List[np.ndarray]) -> List[float]:
        """Calculate volumes using NumPy (divergence theorem)"""
        if not triangles_list:
            return []

        results = []
        for triangles in triangles_list:
            if len(triangles) == 0:
                results.append(0.0)
                continue

            arr = np.asarray(triangles)
            v0, v1, v2 = arr[:, 0, :], arr[:, 1, :], arr[:, 2, :]
            cross_product = np.cross(v1, v2)
            volume = abs(np.sum(v0 * cross_product)) / 6.0
            results.append(float(volume))
        return results

    def calculate_areas_batch(self, triangles_list: List[np.ndarray]) -> List[float]:
        """Calculate surface areas using NumPy"""
        if not triangles_list:
            return []

        results = []
        for triangles in triangles_list:
            if len(triangles) == 0:
                results.append(0.0)
                continue

            arr = np.asarray(triangles)
            v0, v1, v2 = arr[:, 0, :], arr[:, 1, :], arr[:, 2, :]
            edge1 = v1 - v0
            edge2 = v2 - v0
            cross_product = np.cross(edge1, edge2)
            triangle_areas = np.linalg.norm(cross_product, axis=1) / 2.0
            results.append(float(np.sum(triangle_areas)))
        return results

    def spatial_query_points_in_box(
        self,
        points: np.ndarray,
        box_min: np.ndarray,
        box_max: np.ndarray,
    ) -> np.ndarray:
        """Find all points within a bounding box using NumPy"""
        pts = np.asarray(points)
        return np.all((pts >= box_min) & (pts <= box_max), axis=1)

    def get_memory_info(self) -> Dict[str, float]:
        return {"available": False, "used_bytes": 0, "used_gb": 0, "total_bytes": 0, "total_gb": 0}

    def clear_memory_pool(self):
        pass


class GPUAccelerator(CPUAccelerator):
    """GPU acceleration wrapper using CuPy with CUDA"""

    def __init__(self):
        self._cupy = None
        self._device_info = None
        self._initialize_gpu()

    def _initialize_gpu(self):
        import cupy as cp
        self._cupy = cp

        device_count = cp.cuda.runtime.getDeviceCount()
        if device_count == 0:
            raise RuntimeError("CUDA available but no GPU devices found")

        device_id = cp.cuda.Device().id
        device_props = cp.cuda.runtime.getDeviceProperties(device_id)

        self._device_info = {
            "name": device_props["name"].decode(),
            "compute_capability": f"{device_props['major']}.{device_props['minor']}",
            "total_memory_gb": device_props["totalGlobalMem"] / (1024**3),
            "multiprocessor_count": device_props["multiProcessorCount"],
        }
        logger.info(f"GPU initialized: {self._device_info['name']} "
                    f"({self._device_info['total_memory_gb']:.2f} GB)")

    def calculate_bounding_box_batch(self, vertices_list: List[np.ndarray]) -> List[Dict[str, List[float]]]:
        if not vertices_list:
            return []

        cp = self._cupy
        results = []
        for vertices in vertices_list:
            if len(vertices) == 0:
                results.append({"min": [0.0, 0.0, 0.0], "max": [0.0, 0.0, 0.0]})
                continue
            vertices_gpu = cp.array(vertices)
            results.append({
                "min": cp.min(vertices_gpu, axis=0).get().tolist(),
                "max": cp.max(vertices_gpu, axis=0).get().tolist(),
            })
        return results

    def calculate_centroids_batch(self, vertices_list: List[np.ndarray]) -> List[List[float]]:
        if not vertices_list:
            return []

        cp = self._cupy
        results = []
        for vertices in vertices_list:
            if len(vertices) == 0:
                results.append([0.0, 0.0, 0.0])
                continue
            vertices_gpu = cp.array(vertices)
            results.append(cp.mean(vertices_gpu, axis=0).get().tolist())
        return results

    def calculate_volumes_batch(self, triangles_list: List[np.ndarray]) -> List[float]:
        if not triangles_list:
            return []

        cp = self._cupy
        results = []
        for triangles in triangles_list:
            if len(triangles) == 0:
                results.append(0.0)
                continue
            triangles_gpu = cp.array(triangles)
            v0, v1, v2 = triangles_gpu[:, 0, :], triangles_gpu[:, 1, :], triangles_gpu[:, 2, :]
            cross_product = cp.cross(v1, v2)
            volume = cp.abs(cp.sum(v0 * cross_product)) / 6.0
            results.append(float(volume.get()))
        return results

    def calculate_areas_batch(self, triangles_list: List[np.ndarray]) -> List[float]:
        if not triangles_list:
            return []

        cp = self._cupy
        results = []
        for triangles in triangles_list:
            if len(triangles) == 0:
                results.append(0.0)
                continue
            triangles_gpu = cp.array(triangles)
            v0, v1, v2 = triangles_gpu[:, 0, :], triangles_gpu[:, 1, :], triangles_gpu[:, 2, :]
            edge1, edge2 = v1 - v0, v2 - v0
            cross_product = cp.cross(edge1, edge2)
            triangle_areas = cp.linalg.norm(cross_product, axis=1) / 2.0
            results.append(float(cp.sum(triangle_areas).get()))
        return results

    def spatial_query_points_in_box(self, points: np.ndarray, box_min: np.ndarray, box_max: np.ndarray) -> np.ndarray:
        cp = self._cupy
        points_gpu = cp.array(points)
        return cp.all((points_gpu >= cp.array(box_min)) & (points_gpu <= cp.array(box_max)), axis=1).get()

    def get_memory_info(self) -> Dict[str, float]:
        cp = self._cupy
        mem_pool = cp.get_default_memory_pool()
        return {
            "available": True,
            "used_bytes": mem_pool.used_bytes(),
            "used_gb": mem_pool.used_bytes() / (1024**3),
            "total_bytes": mem_pool.total_bytes(),
            "total_gb": mem_pool.total_bytes() / (1024**3),
        }

    def clear_memory_pool(self):
        self._cupy.get_default_memory_pool().free_all_blocks()
        logger.info("GPU memory pool cleared")


@lru_cache(maxsize=1)
def get_gpu_accelerator() -> CPUAccelerator:
    """Get GPU accelerator if available, otherwise CPU fallback"""
    try:
        return GPUAccelerator()
    except (ImportError, RuntimeError, Exception) as e:
        logger.info(f"GPU not available ({e}), using CPU (NumPy) fallback")
        return CPUAccelerator()