Deterministic Gaussian Sampling (Python API)
Python bindings for deterministic Gaussian sampling and Dirac mixture reduction.
Loading...
Searching...
No Matches
base_approximation.py
Go to the documentation of this file.
1import ctypes
2from dataclasses import dataclass
3import numpy
4from typing import Optional
6
7@dataclass
9 cov: numpy.ndarray
10 eigvals: numpy.ndarray
11 Q: numpy.ndarray
12 sqrt_eigvals: numpy.ndarray
13
14 def __init__(self, cov: numpy.ndarray):
15 self.cov = cov
16 self.eigvals, self.Q = numpy.linalg.eigh(cov)
17 self.eigvals = numpy.maximum(self.eigvals, 1e-14)
18 self.sqrt_eigvals = numpy.sqrt(self.eigvals)
19
20 self.cov = numpy.ascontiguousarray(self.cov, dtype=numpy.float64)
21 self.Q = numpy.ascontiguousarray(self.Q, dtype=numpy.float64)
22 self.eigvals = numpy.ascontiguousarray(self.eigvals, dtype=numpy.float64)
23 self.sqrt_eigvals = numpy.ascontiguousarray(self.sqrt_eigvals, dtype=numpy.float64)
24
26 cdll: Optional[ctypes.CDLL] = None
27
28 def __init__(self):
29 if self.cdll is None:
30 lib = load_dll()
31 self._register_cdll(lib)
32
33 def _map_ctypes_numpy(self, ctype) -> type:
34 if ctype == ctypes.c_double:
35 return numpy.float64
36 elif ctype == ctypes.c_float:
37 return numpy.float32
38 elif ctype == ctypes.c_size_t:
39 return numpy.uint64
40 else:
41 raise TypeError("Unsupported ctype for mapping to numpy dtype")
42
44 self, arr: Optional[numpy.ndarray], L: int, N: Optional[int] = None
45 ) -> Optional[numpy.ndarray]:
46 if arr is None:
47 return None
48 if not isinstance(arr, numpy.ndarray):
49 raise TypeError("Input must be a numpy array")
50 if not numpy.issubdtype(arr.dtype, numpy.floating):
51 raise TypeError(
52 f"Input array must be of a floating type, but got {arr.dtype}."
53 )
54 if L <= 0 or (N is not None and N <= 0):
55 raise ValueError("L and N must be positive integers.")
56 arrShape = arr.shape
57 if arr.ndim == 1:
58 if arrShape[0] != L:
59 raise ValueError(
60 f"Input array must have size [{L}] but got [{arrShape[0]}]"
61 )
62 if N is not None and N != 1:
63 raise ValueError(
64 f"Input array must have size [{L}x{N}] but got [{L}]"
65 )
66 elif arr.ndim == 2:
67 if arrShape != (L, N):
68 row, cols = arrShape
69 raise ValueError(
70 f"Input array must have size [{L}x{N}] but got [{row}x{cols}]"
71 )
72 else:
73 raise ValueError("Input array must be 1D or 2D")
74
75 # ensure contiguous float64 memory
76 return numpy.ascontiguousarray(arr, dtype=numpy.float64)
77
78 def _check_covariance_matrix(self, cov: numpy.ndarray, N: int, tol = 1e-6) -> CovarianceData:
79 if cov.shape != (N, N):
80 raise ValueError(f"Covariance matrix must be of shape [{N}x{N}] but got {cov.shape}")
81 if not numpy.allclose(cov, cov.T, atol=tol):
82 raise ValueError("Covariance matrix must be symmetric")
83 if numpy.any(numpy.linalg.eigvalsh(cov) <= -tol):
84 raise ValueError("Covariance matrix must be positive definite")
85
86 covChecked = self._check_numpy_ndarray(cov, N, N)
87 return CovarianceData(covChecked)
88
89 def _check_weights(self, weight: Optional[numpy.ndarray], size: int, tol=1e-6) -> Optional[numpy.ndarray]:
90 if weight is None:
91 return None
92 wChecked = self._check_numpy_ndarray(weight, size, None)
93 if numpy.any(wChecked < 0):
94 raise ValueError("Weights cannot be negative")
95 if numpy.abs(1 - numpy.sum(wChecked)) > tol:
96 raise ValueError(f"Sum of weights must be 1 within tolerance +/-{tol}, but got {numpy.sum(wChecked)}")
97 return wChecked
98
99 def _check_even_dimension(self, N: int):
100 if N < 2 or N % 2 != 0:
101 raise ValueError(f"Dimension N must be even and >= 2, but got {N}")
102
103 def _check_positive(self, value: float, name: str):
104 if not value > 0:
105 raise ValueError(f"{name} must be positive, but got {value}")
106
107 @staticmethod
108 def _register_cdll(cdll: ctypes.CDLL):
109 BaseApproximation.cdll = cdll
Optional[numpy.ndarray] _check_weights(self, Optional[numpy.ndarray] weight, int size, tol=1e-6)
CovarianceData _check_covariance_matrix(self, numpy.ndarray cov, int N, tol=1e-6)
Optional[numpy.ndarray] _check_numpy_ndarray(self, Optional[numpy.ndarray] arr, int L, Optional[int] N=None)