Deterministic Gaussian Sampling (Python API)
Python bindings for deterministic Gaussian sampling and Dirac mixture reduction.
Loading...
Searching...
No Matches
python_variant.py
Go to the documentation of this file.
1# python_variant.py
2from __future__ import annotations
3from typing import Callable, Sequence, Union
4from dataclasses import dataclass
5import ctypes
6import numpy as np
7
9
10@dataclass
12 success: bool
13 result: "GslMinimizerResultPy"
14 x: np.ndarray
15
16 @staticmethod
18 success: ctypes.c_bool,
19 minimizer_result,
20 x_ptr: ctypes.POINTER[ctypes.c_double],
21 L: int,
22 N: int,
23 ) -> "ApproximationResultPy":
24 from deterministic_gaussian_sampling.type_wrapper import ctypes_wrapper
25
27 bool(success),
28 minimizer_result.to_py_type(),
29 np.ctypeslib.as_array(x_ptr, shape=(L, N)),
30 )
31
32 def __str__(self):
33 lines = []
34 lines.append(f"Success: {self.success}")
35 lines.append(str(self.result))
36 lines.append(f"x: {str(self.x)}")
37 return "\n".join(lines)
38
39 __repr__ = __str__
40
41
42@dataclass
44 initalStepSize: float = 0.0
45 stepTolerance: float = 0.0
46 lastXtolAbs: float = 0.0
47 lastXtolRel: float = 0.0
48 lastFtolAbs: float = 0.0
49 lastFtolRel: float = 0.0
50 lastGtol: float = 0.0
51 xtolAbs: float = 0.0
52 xtolRel: float = 0.0
53 ftolAbs: float = 0.0
54 ftolRel: float = 0.0
55 gtol: float = 0.0
56 iterations: int = 0
57 maxIterations: int = 0
58 elapsedTimeMicro: int = 0
59
60 @staticmethod
61 def _format_elapsed_time(elapsedMicro):
62 if elapsedMicro < 1_000:
63 return f"{elapsedMicro:.1f} µs"
64 if elapsedMicro < 1_000_000:
65 return f"{(elapsedMicro / 1_000):.3f} ms"
66 if elapsedMicro < 60_000_000:
67 return f"{(elapsedMicro / 1_000_000):.3f} s"
68 return f"{(elapsedMicro / 60_000_000):.3f} m, {((elapsedMicro % 60_000_000) / 1_000_000):.2f} s"
69
70 @staticmethod
72 if a < b:
73 return "<"
74 if a > b:
75 return ">"
76 return "="
77
78 def __str__(self):
79 lines = []
80 lines.append(f"GslMinimizerResultPy:")
81 lines.append(f" initialStepSize: {self.initalStepSize}")
82 lines.append(f" stepTolerance: {self.stepTolerance}")
83 lines.append(
84 f" |x - x'|: {self.lastXtolAbs} {self._print_comp_symbol(self.lastXtolAbs, self.xtolAbs)} {self.xtolAbs}"
85 )
86 lines.append(
87 f" |x - x'|/|x'|: {self.lastXtolRel} {self._print_comp_symbol(self.lastXtolRel, self.xtolRel)} {self.xtolRel}"
88 )
89 lines.append(
90 f" |f(x) - f(x')|: {self.lastFtolAbs} {self._print_comp_symbol(self.lastFtolAbs, self.ftolAbs)} {self.ftolAbs}"
91 )
92 lines.append(
93 f" |f(x) - f(x')|/|f(x')|: {self.lastFtolRel} {self._print_comp_symbol(self.lastFtolRel, self.ftolRel)} {self.ftolRel}"
94 )
95 lines.append(
96 f" |g(x)|: {self.lastGtol} {self._print_comp_symbol(self.lastGtol, self.gtol)} {self.gtol}"
97 )
98 lines.append(f" iterations: {self.iterations} of {self.maxIterations}")
99 lines.append(
100 f" timeTaken: {self._format_elapsed_time(self.elapsedTimeMicro)}"
101 )
102 return "\n".join(lines)
103
104 __repr__ = __str__
105
106
107@dataclass
109 xtolAbs: float
110 xtolRel: float
111 ftolAbs: float
112 ftolRel: float
113 gtol: float
114 initialX: bool
115 maxIterations: int
116 verbose: bool
117 bMax: int
118
119 def __str__(self):
120 lines = []
121 lines.append(f"ApproximateOptionsPy:")
122 lines.append(f" xtolAbs: {self.xtolAbs}")
123 lines.append(f" xtolRel: {self.xtolRel}")
124 lines.append(f" ftolAbs: {self.ftolAbs}")
125 lines.append(f" ftolRel: {self.ftolRel}")
126 lines.append(f" gtol: {self.gtol}")
127 lines.append(f" initialX: {self.initialX}")
128 lines.append(f" maxIterations: {self.maxIterations}")
129 lines.append(f" verbose: {self.verbose}")
130 lines.append(f" bMax: {self.bMax}")
131 return "\n".join(lines)
132
133 __repr__ = __str__
134
135ArrayLike = Union[Sequence[float], np.ndarray]
136# Function type: (x, L, N) -> res
137wXCallbackPythonType = Callable[[ArrayLike, int, int], ArrayLike]
138wXDCallbackPythonType = wXCallbackPythonType
139
140def wx_callback_python_wrapper(func: wXCallbackPythonType) -> "ctypes_wrapper.wXCallbackCTypes":
141 """
142 Wrap a Python function of signature (x: ndarray[L,N], L, N) -> res
143 to a ctypes callback for C.
144 """
145 def c_callback(x_ptr, res_ptr, L, N):
146 L = int(L)
147 N = int(N)
148 size = L * N
149
150 # Convert C pointer to 1D array and reshape to (N,L) for row-major -> column-major
151 x_raw = np.ctypeslib.as_array(x_ptr, shape=(size,))
152 x = x_raw.reshape((L, N))
153
154 # Call user Python function
155 res_val = func(x, L, N)
156 res_val = np.asarray(res_val, dtype=np.float64)
157
158 # Prepare the result to write back to C in row-major
159 if res_val.ndim == 1:
160 # vector case (L,)
161 if res_val.size != L:
162 raise ValueError(f"Returned array has size {res_val.size}, expected {L}")
163 res_arr = np.ctypeslib.as_array(res_ptr, shape=(L,))
164 res_arr[:] = res_val
165 elif res_val.ndim == 2:
166 if res_val.shape != (L, N):
167 raise ValueError(f"Returned array has shape {res_val.shape}, expected ({L},{N})")
168 # Convert to row-major (flattened)
169 res_row_major = res_val.flatten()
170 res_arr = np.ctypeslib.as_array(res_ptr, shape=(size,))
171 res_arr[:] = res_row_major
172 else:
173 raise ValueError(f"Returned array has invalid ndim {res_val.ndim}")
174
175 cb = ctypes_wrapper.wXCallbackCTypes(c_callback)
176 cb._keepalive = func # keep reference alive
177 return cb
178
179# Alias for your derivative callback if needed
180wxd_callback_python_wrapper = wx_callback_python_wrapper
"ApproximationResultPy" from_ctypes(ctypes.c_bool success, minimizer_result, ctypes.POINTER[ctypes.c_double] x_ptr, int L, int N)
"ctypes_wrapper.wXCallbackCTypes" wx_callback_python_wrapper(wXCallbackPythonType func)
Wrap a Python function of signature (x: ndarray[L,N], L, N) -> res to a ctypes callback for C.