# 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 . """ 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()