cclib-mojo 0.2.5__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.
cclib_mojo/__init__.py ADDED
@@ -0,0 +1,37 @@
1
+ """cclib-mojo: fast electron-density and wavefunction-on-grid evaluation.
2
+
3
+ A drop-in accelerator for cclib's ``cclib.method.volume`` path
4
+ (wavefunction / electron density on 3-D grids), powered by a Mojo kernel
5
+ where the platform supports it (macOS arm64, Linux x86_64), with a vendored
6
+ NumPy fallback everywhere else (including Windows). Also usable standalone:
7
+
8
+ from cclib_mojo import density_on_grid, wavefunction_on_grid
9
+
10
+ # gbasis/atomcoords/mocoeffs as parsed by cclib (Angstrom geometry):
11
+ psi = wavefunction_on_grid(gbasis, atomcoords, mocoeffs,
12
+ origin=(-5, -5, -5), step=(0.2, 0.2, 0.2),
13
+ shape=(51, 51, 51))
14
+ rho = density_on_grid(gbasis, atomcoords, mocoeffs[:nocc],
15
+ origin=(-5, -5, -5), step=(0.2, 0.2, 0.2),
16
+ shape=(51, 51, 51)) # sum_mo |psi_mo|^2
17
+
18
+ For cclib-API-shaped helpers see ``cclib_mojo.cclib_integration``.
19
+ Set CCLIB_MOJO_DISABLE_NATIVE=1 to force the pure-Python fallback.
20
+ """
21
+
22
+ from cclib_mojo import cclib_integration
23
+ from cclib_mojo._basis import BasisError
24
+ from cclib_mojo._native import backend_info, native_available
25
+ from cclib_mojo.core import GridError, density_on_grid, wavefunction_on_grid
26
+
27
+ __version__ = "0.2.5" # x-release-please-version
28
+ __all__ = [
29
+ "BasisError",
30
+ "GridError",
31
+ "backend_info",
32
+ "cclib_integration",
33
+ "density_on_grid",
34
+ "native_available",
35
+ "wavefunction_on_grid",
36
+ "__version__",
37
+ ]
cclib_mojo/_basis.py ADDED
@@ -0,0 +1,334 @@
1
+ """Basis-set validation, normalization, and flattening — shared by both backends.
2
+
3
+ Converts cclib's ``gbasis`` (per-atom, per-shell primitive lists, as parsed
4
+ from a quantum-chemistry logfile) into the flat typed arrays the Mojo kernel
5
+ and the NumPy fallback both consume. Because this module is the single source
6
+ of basis data for the native and fallback paths, the two backends can never
7
+ disagree about normalization constants or centers.
8
+
9
+ Conventions (all verified against cclib + PyQuante, see README):
10
+
11
+ - Shell expansion order follows cclib's ``sym2powerlist`` verbatim
12
+ (cclib/method/volume.py): S, then P (x, y, z), then Cartesian D
13
+ (xx, yy, zz, xy, yz, xz), then Cartesian F
14
+ (xxx, xxy, xxz, xyy, xyz, xzz, yyy, yyz, yzz, zzz).
15
+ - Centers are converted Angstrom -> bohr with cclib's own constant
16
+ (``convertor(x, "Angstrom", "bohr")`` = x * 1.8897261245,
17
+ cclib/parser/utils.py). Grid axes are converted separately in
18
+ ``cclib_mojo.core`` (cclib divides by 0.5291772109 there — the two
19
+ constants are not exact reciprocals, and we mirror cclib exactly).
20
+ - Primitive norms follow THO eq. 2.2 exactly as PyQuante's
21
+ ``PGBF.normalize`` computes them; the contracted norm is
22
+ ``1/sqrt(<g|g>)`` with the self-overlap from THO eq. 2.12, in PyQuante's
23
+ operation order (PyQuante 1.6.5, R. P. Muller, BSD licensed).
24
+ - Exponents stay in bohr^-2 exactly as parsed (cclib never converts them).
25
+
26
+ The math below is textbook Gaussian-basis algebra (Taketa, Huzinaga,
27
+ O-ohata, J. Phys. Soc. Jap. 21, 2313 (1966)); operation order mirrors the
28
+ published PyQuante reference so results agree to the last few ulps.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import math
34
+ from dataclasses import dataclass
35
+
36
+ import numpy as np
37
+
38
+ # cclib/method/volume.py `sym2powerlist`, verbatim: the Cartesian power
39
+ # triples (lx, ly, lz) each shell symbol expands into, in cclib's order.
40
+ SYM2POWERS: dict[str, list[tuple[int, int, int]]] = {
41
+ "S": [(0, 0, 0)],
42
+ "P": [(1, 0, 0), (0, 1, 0), (0, 0, 1)],
43
+ "D": [(2, 0, 0), (0, 2, 0), (0, 0, 2), (1, 1, 0), (0, 1, 1), (1, 0, 1)],
44
+ "F": [
45
+ (3, 0, 0),
46
+ (2, 1, 0),
47
+ (2, 0, 1),
48
+ (1, 2, 0),
49
+ (1, 1, 1),
50
+ (1, 0, 2),
51
+ (0, 3, 0),
52
+ (0, 2, 1),
53
+ (0, 1, 2),
54
+ (0, 0, 3),
55
+ ],
56
+ }
57
+
58
+ # cclib/parser/utils.py `convertor`, Angstrom -> bohr (used for centers).
59
+ ANG2BOHR = 1.8897261245
60
+ # cclib/parser/utils.py `convertor`, bohr -> Angstrom (cclib's getGrid
61
+ # divides Angstrom grid coordinates by this value).
62
+ BOHR2ANG = 0.5291772109
63
+
64
+ # Physical input domain enforced by the fail-fast validation contract.
65
+ # Anything outside these windows has no quantum-chemistry meaning and overflows
66
+ # the THO normalization arithmetic for the supported shells (S/P/D/F).
67
+ # Exponents are in bohr^-2; coordinates are in Angstrom.
68
+ EXPONENT_SANE_MIN = 1e-100
69
+ EXPONENT_SANE_MAX = 1e60
70
+ COORDINATE_SANE_MAX = 1e100
71
+ # Ceiling on every intermediate product one grid term can build, bounded per
72
+ # basis function with a non-zero MO coefficient as
73
+ # max(1, |c| N_c) * max(1, |x-cx|)^l (...)^m (...)^n * max(1, sum_p |w_p|)
74
+ # with distances in bohr, the unit both backends evaluate in (enforced in
75
+ # cclib_mojo.core, in log10 space). The two backends multiply
76
+ # these factors in different orders; below this ceiling no order overflows,
77
+ # and a term squared (density mode) stays below 1e280, which leaves 28 orders
78
+ # of magnitude for the sums over primitives, basis functions and MOs.
79
+ # Physical inputs stay below ~1e10.
80
+ INTERMEDIATE_MAGNITUDE_MAX = 1e140
81
+
82
+
83
+ class BasisError(ValueError):
84
+ """Malformed basis-set or geometry input (structured, fail-fast)."""
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class BasisArrays:
89
+ """Flat typed arrays describing every contracted Cartesian basis function.
90
+
91
+ Primitive ``w`` folds the contraction coefficient and the primitive
92
+ norm: w_p = coef_p * N_p. ``bf_norm`` is the contracted norm N_c, so
93
+ bf(r) = bf_norm * (x-cx)^l (y-cy)^m (z-cz)^n * sum_p w_p exp(-alpha_p r^2).
94
+ """
95
+
96
+ offsets: np.ndarray # int64 [n_bf + 1], CSR row offsets into alpha/w
97
+ powers_l: np.ndarray # int32 [n_bf]
98
+ powers_m: np.ndarray # int32 [n_bf]
99
+ powers_n: np.ndarray # int32 [n_bf]
100
+ center_x: np.ndarray # float64 [n_bf], bohr
101
+ center_y: np.ndarray # float64 [n_bf], bohr
102
+ center_z: np.ndarray # float64 [n_bf], bohr
103
+ bf_norm: np.ndarray # float64 [n_bf]
104
+ prim_alpha: np.ndarray # float64 [n_prims], bohr^-2
105
+ prim_w: np.ndarray # float64 [n_prims]
106
+ n_bf: int
107
+ n_prims: int
108
+
109
+
110
+ def _fact2(n: int) -> int:
111
+ """Double factorial n!! = n*(n-2)*...*1; fact2(n) = 1 for n <= 0."""
112
+ val = 1
113
+ while n > 0:
114
+ val *= n
115
+ n -= 2
116
+ return val
117
+
118
+
119
+ def primitive_norm(alpha: float, l: int, m: int, n: int) -> float: # noqa: E741
120
+ """Normalization of a primitive Cartesian Gaussian, THO eq. 2.2.
121
+
122
+ Same expression (and operation order) as PyQuante 1.6.5
123
+ ``PGBF.normalize``.
124
+ """
125
+ L = l + m + n
126
+ return math.sqrt(
127
+ pow(2, 2 * L + 1.5)
128
+ * pow(alpha, L + 1.5)
129
+ / _fact2(2 * l - 1)
130
+ / _fact2(2 * m - 1)
131
+ / _fact2(2 * n - 1)
132
+ / pow(math.pi, 1.5)
133
+ )
134
+
135
+
136
+ def _binomial_prefactor(s: int, ia: int, ib: int, xpa: float, xpb: float) -> float:
137
+ """THO binomial expansion term (PyQuante pyints.binomial_prefactor)."""
138
+ total = 0.0
139
+ for t in range(s + 1):
140
+ if s - ia <= t <= ib:
141
+ total += (
142
+ math.comb(ia, s - t)
143
+ * math.comb(ib, t)
144
+ * pow(xpa, ia - s + t)
145
+ * pow(xpb, ib - t)
146
+ )
147
+ return total
148
+
149
+
150
+ def _overlap_1d(l1: int, l2: int, pax: float, pbx: float, gamma: float) -> float:
151
+ """THO eq. 2.12 one-dimensional overlap (PyQuante pyints.overlap_1D)."""
152
+ total = 0.0
153
+ for i in range(1 + (l1 + l2) // 2):
154
+ total += (
155
+ _binomial_prefactor(2 * i, l1, l2, pax, pbx)
156
+ * _fact2(2 * i - 1)
157
+ / pow(2 * gamma, i)
158
+ )
159
+ return total
160
+
161
+
162
+ def _overlap(
163
+ alpha1: float,
164
+ powers: tuple[int, int, int],
165
+ a_center: tuple[float, float, float],
166
+ alpha2: float,
167
+ b_center: tuple[float, float, float],
168
+ ) -> float:
169
+ """Unnormalized overlap of two primitives, THO eq. 2.12.
170
+
171
+ Both primitives carry the same Cartesian powers (they belong to one
172
+ contracted function). Mirrors PyQuante pyints.overlap operation order.
173
+ """
174
+ l1, m1, n1 = powers
175
+ rab2 = (
176
+ pow(a_center[0] - b_center[0], 2)
177
+ + pow(a_center[1] - b_center[1], 2)
178
+ + pow(a_center[2] - b_center[2], 2)
179
+ )
180
+ gamma = alpha1 + alpha2
181
+ px = (alpha1 * a_center[0] + alpha2 * b_center[0]) / gamma
182
+ py = (alpha1 * a_center[1] + alpha2 * b_center[1]) / gamma
183
+ pz = (alpha1 * a_center[2] + alpha2 * b_center[2]) / gamma
184
+ pre = pow(math.pi / gamma, 1.5) * math.exp(-alpha1 * alpha2 * rab2 / gamma)
185
+ wx = _overlap_1d(l1, l1, px - a_center[0], px - b_center[0], gamma)
186
+ wy = _overlap_1d(m1, m1, py - a_center[1], py - b_center[1], gamma)
187
+ wz = _overlap_1d(n1, n1, pz - a_center[2], pz - b_center[2], gamma)
188
+ return pre * wx * wy * wz
189
+
190
+
191
+ def _contracted_norm(
192
+ prims: list[tuple[float, float]],
193
+ pnorms: list[float],
194
+ powers: tuple[int, int, int],
195
+ center: tuple[float, float, float],
196
+ ) -> float:
197
+ """N_c = 1/sqrt(<g|g>) over normalized primitives (PyQuante order)."""
198
+ S = 0.0
199
+ for (ai, ci), ni in zip(prims, pnorms):
200
+ for (aj, cj), nj in zip(prims, pnorms):
201
+ S += ci * cj * (ni * nj * _overlap(ai, powers, center, aj, center))
202
+ if S <= 0.0 or not math.isfinite(S):
203
+ raise BasisError(
204
+ f"contracted basis function with powers {powers} has non-positive "
205
+ f"self-overlap {S!r}; check exponents and coefficients"
206
+ )
207
+ return 1.0 / math.sqrt(S)
208
+
209
+
210
+ def _validate_shell(atom_index: int, shell: object) -> tuple[str, list[tuple[float, float]]]:
211
+ if not (isinstance(shell, (list, tuple)) and len(shell) == 2):
212
+ raise BasisError(
213
+ f"gbasis[{atom_index}]: each shell must be a (symbol, primitives) "
214
+ f"pair, got {shell!r}"
215
+ )
216
+ sym, prims = shell
217
+ if not isinstance(sym, str) or sym not in SYM2POWERS:
218
+ raise BasisError(
219
+ f"gbasis[{atom_index}]: unsupported shell symbol {sym!r}; "
220
+ f"supported shells match cclib: {sorted(SYM2POWERS)}"
221
+ )
222
+ if not isinstance(prims, (list, tuple)) or len(prims) == 0:
223
+ raise BasisError(f"gbasis[{atom_index}] shell {sym!r}: empty primitive list")
224
+ out: list[tuple[float, float]] = []
225
+ for prim in prims:
226
+ if not (isinstance(prim, (list, tuple)) and len(prim) == 2):
227
+ raise BasisError(
228
+ f"gbasis[{atom_index}] shell {sym!r}: each primitive must be an "
229
+ f"(exponent, coefficient) pair, got {prim!r}"
230
+ )
231
+ alpha, coef = float(prim[0]), float(prim[1])
232
+ if not math.isfinite(alpha) or alpha <= 0.0:
233
+ raise BasisError(
234
+ f"gbasis[{atom_index}] shell {sym!r}: exponent must be finite "
235
+ f"and > 0, got {alpha!r}"
236
+ )
237
+ if alpha < EXPONENT_SANE_MIN or alpha > EXPONENT_SANE_MAX:
238
+ raise BasisError(
239
+ f"gbasis[{atom_index}] shell {sym!r}: exponent {alpha!r} is "
240
+ f"outside the supported physical domain "
241
+ f"[{EXPONENT_SANE_MIN!r}, {EXPONENT_SANE_MAX!r}] bohr^-2"
242
+ )
243
+ if not math.isfinite(coef):
244
+ raise BasisError(
245
+ f"gbasis[{atom_index}] shell {sym!r}: coefficient must be "
246
+ f"finite, got {coef!r}"
247
+ )
248
+ out.append((alpha, coef))
249
+ return sym, out
250
+
251
+
252
+ def flatten_gbasis(gbasis: object, atomcoords: object) -> BasisArrays:
253
+ """Validate cclib-style inputs and build the flat kernel arrays.
254
+
255
+ ``gbasis`` is cclib's per-atom list of (symbol, primitives) shells;
256
+ ``atomcoords`` is an (n_atoms, 3) array in Angstrom (cclib convention;
257
+ converted to bohr here with cclib's constant).
258
+ """
259
+ coords = np.asarray(atomcoords, dtype=np.float64)
260
+ if coords.ndim != 2 or coords.shape[1] != 3:
261
+ raise BasisError(
262
+ f"atomcoords must have shape (n_atoms, 3), got {coords.shape}"
263
+ )
264
+ if not np.all(np.isfinite(coords)):
265
+ raise BasisError("atomcoords contains non-finite values")
266
+ if np.any(np.abs(coords) > COORDINATE_SANE_MAX):
267
+ bad = np.unravel_index(int(np.argmax(np.abs(coords))), coords.shape)
268
+ raise BasisError(
269
+ f"atomcoords[{bad[0]}, {bad[1]}] = {coords[bad]!r} is outside the "
270
+ f"supported physical domain [-{COORDINATE_SANE_MAX!r}, "
271
+ f"{COORDINATE_SANE_MAX!r}] Angstrom"
272
+ )
273
+ if not isinstance(gbasis, (list, tuple)) or len(gbasis) == 0:
274
+ raise BasisError("gbasis must be a non-empty per-atom list of shells")
275
+ if len(gbasis) != coords.shape[0]:
276
+ raise BasisError(
277
+ f"len(gbasis) ({len(gbasis)}) != n_atoms ({coords.shape[0]})"
278
+ )
279
+
280
+ offsets = [0]
281
+ powers_l: list[int] = []
282
+ powers_m: list[int] = []
283
+ powers_n: list[int] = []
284
+ center_x: list[float] = []
285
+ center_y: list[float] = []
286
+ center_z: list[float] = []
287
+ bf_norm: list[float] = []
288
+ prim_alpha: list[float] = []
289
+ prim_w: list[float] = []
290
+
291
+ for atom_index, atom_shells in enumerate(gbasis):
292
+ if not isinstance(atom_shells, (list, tuple)) or len(atom_shells) == 0:
293
+ raise BasisError(f"gbasis[{atom_index}]: no shells")
294
+ # cclib's pyquante2 bridge: convertor(atom, "Angstrom", "bohr").
295
+ center = (
296
+ float(coords[atom_index, 0]) * ANG2BOHR,
297
+ float(coords[atom_index, 1]) * ANG2BOHR,
298
+ float(coords[atom_index, 2]) * ANG2BOHR,
299
+ )
300
+ for shell in atom_shells:
301
+ sym, prims = _validate_shell(atom_index, shell)
302
+ for powers in SYM2POWERS[sym]:
303
+ l, m, n = powers # noqa: E741
304
+ pnorms = [primitive_norm(alpha, l, m, n) for alpha, _ in prims]
305
+ cnorm = _contracted_norm(prims, pnorms, powers, center)
306
+ powers_l.append(l)
307
+ powers_m.append(m)
308
+ powers_n.append(n)
309
+ center_x.append(center[0])
310
+ center_y.append(center[1])
311
+ center_z.append(center[2])
312
+ bf_norm.append(cnorm)
313
+ for (alpha, coef), pnorm in zip(prims, pnorms):
314
+ prim_alpha.append(alpha)
315
+ prim_w.append(coef * pnorm)
316
+ offsets.append(len(prim_alpha))
317
+
318
+ n_bf = len(bf_norm)
319
+ if n_bf == 0:
320
+ raise BasisError("gbasis expands to zero basis functions")
321
+ return BasisArrays(
322
+ offsets=np.asarray(offsets, dtype=np.int64),
323
+ powers_l=np.asarray(powers_l, dtype=np.int32),
324
+ powers_m=np.asarray(powers_m, dtype=np.int32),
325
+ powers_n=np.asarray(powers_n, dtype=np.int32),
326
+ center_x=np.asarray(center_x, dtype=np.float64),
327
+ center_y=np.asarray(center_y, dtype=np.float64),
328
+ center_z=np.asarray(center_z, dtype=np.float64),
329
+ bf_norm=np.asarray(bf_norm, dtype=np.float64),
330
+ prim_alpha=np.asarray(prim_alpha, dtype=np.float64),
331
+ prim_w=np.asarray(prim_w, dtype=np.float64),
332
+ n_bf=n_bf,
333
+ n_prims=len(prim_alpha),
334
+ )
cclib_mojo/_native.py ADDED
@@ -0,0 +1,254 @@
1
+ """ctypes loader for the gaussgridmojo native kernel, with an ABI handshake.
2
+
3
+ Resolution order:
4
+
5
+ 1. ``$CCLIB_MOJO_NATIVE_LIB`` (explicit path override, for development)
6
+ 2. the shared library bundled in this wheel under ``cclib_mojo/_native/``
7
+ 3. the repository development build output ``kernels/gaussgrid/build/``
8
+
9
+ If the library cannot be found, fails to load, or reports an ABI version this
10
+ package does not understand, :class:`NativeUnavailable` is raised and the
11
+ caller falls back to the vendored pure-Python reference implementation.
12
+ Set ``CCLIB_MOJO_DISABLE_NATIVE=1`` to force that fallback (used by the
13
+ differential test suite).
14
+
15
+ Stable C ABI (v1)::
16
+
17
+ int32_t gaussgridmojo_abi_version(void)
18
+ int32_t gaussgridmojo_eval(int64_t n_bf, const int64_t* bf_offsets,
19
+ const int32_t* bf_l, const int32_t* bf_m,
20
+ const int32_t* bf_n,
21
+ const double* bf_cx, const double* bf_cy,
22
+ const double* bf_cz, const double* bf_norm,
23
+ const double* prim_alpha, const double* prim_w,
24
+ const double* ax, const double* ay,
25
+ const double* az,
26
+ int64_t nx, int64_t ny, int64_t nz,
27
+ int64_t n_mo, const double* mo_coeff,
28
+ int32_t mode, double* out)
29
+
30
+ mode 0 (wavefunction): out = sum_bf mo_coeff[0,bf] * bf(r) (n_mo == 1)
31
+ mode 1 (density): out = sum_mo (sum_bf coeff*bf(r))^2
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import ctypes
37
+ import os
38
+ import sys
39
+ import threading
40
+
41
+ import numpy as np
42
+
43
+ # Must equal ABI_VERSION in kernels/gaussgrid/src/gaussgridmojo.mojo. A
44
+ # mismatch means the installed wheel and the resolved shared library
45
+ # disagree; fall back.
46
+ ABI_VERSION = 1
47
+
48
+ MODE_WAVEFUNCTION = 0
49
+ MODE_DENSITY = 1
50
+
51
+ _ENV_LIB = "CCLIB_MOJO_NATIVE_LIB"
52
+ _ENV_DISABLE = "CCLIB_MOJO_DISABLE_NATIVE"
53
+
54
+
55
+ class NativeUnavailable(RuntimeError): # noqa: N818
56
+ """The native gaussgridmojo kernel could not be found, loaded, or verified."""
57
+
58
+
59
+ def _lib_basename() -> str:
60
+ if sys.platform == "darwin":
61
+ return "libgaussgridmojo.dylib"
62
+ if sys.platform.startswith("linux"):
63
+ return "libgaussgridmojo.so"
64
+ if sys.platform.startswith("win"):
65
+ return "gaussgridmojo.dll" # no Mojo toolchain builds this today
66
+ return "libgaussgridmojo.so"
67
+
68
+
69
+ def _candidate_paths() -> list[tuple[str, str]]:
70
+ """(source_label, path) candidates, in resolver order."""
71
+ out: list[tuple[str, str]] = []
72
+ override = os.environ.get(_ENV_LIB)
73
+ if override:
74
+ out.append((f"env {_ENV_LIB}", override))
75
+ here = os.path.dirname(__file__)
76
+ out.append(("bundled in wheel", os.path.join(here, "_native", _lib_basename())))
77
+ out.append(
78
+ (
79
+ "repo-dev build output",
80
+ os.path.abspath(
81
+ os.path.join(
82
+ here, "..", "..", "..", "kernels", "gaussgrid", "build", _lib_basename()
83
+ )
84
+ ),
85
+ )
86
+ )
87
+ return out
88
+
89
+
90
+ def _bind_abi(lib: ctypes.CDLL) -> None:
91
+ f64p = ctypes.POINTER(ctypes.c_double)
92
+ i32p = ctypes.POINTER(ctypes.c_int32)
93
+ i64p = ctypes.POINTER(ctypes.c_int64)
94
+ lib.gaussgridmojo_abi_version.argtypes = []
95
+ lib.gaussgridmojo_abi_version.restype = ctypes.c_int32
96
+ lib.gaussgridmojo_eval.argtypes = [
97
+ ctypes.c_int64, # n_bf
98
+ i64p, # bf_offsets[n_bf+1]
99
+ i32p, # bf_l[n_bf]
100
+ i32p, # bf_m[n_bf]
101
+ i32p, # bf_n[n_bf]
102
+ f64p, # bf_cx[n_bf]
103
+ f64p, # bf_cy[n_bf]
104
+ f64p, # bf_cz[n_bf]
105
+ f64p, # bf_norm[n_bf]
106
+ f64p, # prim_alpha[n_prims]
107
+ f64p, # prim_w[n_prims]
108
+ f64p, # ax[nx]
109
+ f64p, # ay[ny]
110
+ f64p, # az[nz]
111
+ ctypes.c_int64, # nx
112
+ ctypes.c_int64, # ny
113
+ ctypes.c_int64, # nz
114
+ ctypes.c_int64, # n_mo
115
+ f64p, # mo_coeff[n_mo * n_bf]
116
+ ctypes.c_int32, # mode
117
+ f64p, # out[nx*ny*nz]
118
+ ]
119
+ lib.gaussgridmojo_eval.restype = ctypes.c_int32
120
+
121
+
122
+ _LOCK = threading.Lock()
123
+ _LIB: ctypes.CDLL | None = None
124
+ _LIB_SOURCE: str | None = None
125
+ _LOAD_ERROR: str | None = None
126
+
127
+
128
+ def _load() -> ctypes.CDLL:
129
+ """Resolve, dlopen, and ABI-handshake the native kernel. Never caches failure."""
130
+ global _LIB, _LIB_SOURCE, _LOAD_ERROR
131
+ if os.environ.get(_ENV_DISABLE) == "1":
132
+ raise NativeUnavailable(f"native kernel disabled by {_ENV_DISABLE}=1")
133
+ if _LIB is not None:
134
+ return _LIB
135
+ with _LOCK:
136
+ if _LIB is not None:
137
+ return _LIB
138
+ errors: list[str] = []
139
+ for label, path in _candidate_paths():
140
+ try:
141
+ if not path or not os.path.exists(path):
142
+ continue
143
+ try:
144
+ lib = ctypes.CDLL(path)
145
+ except OSError as exc:
146
+ errors.append(f"{label} ({path}): {exc}")
147
+ continue
148
+ try:
149
+ _bind_abi(lib)
150
+ abi = int(lib.gaussgridmojo_abi_version())
151
+ except Exception as exc: # missing/renamed symbol = wrong lib
152
+ errors.append(f"{label} ({path}): ABI not recognized: {exc}")
153
+ continue
154
+ if abi != ABI_VERSION:
155
+ errors.append(
156
+ f"{label} ({path}): native ABI v{abi} != wrapper ABI v{ABI_VERSION}"
157
+ )
158
+ continue
159
+ _LIB, _LIB_SOURCE = lib, f"{label} ({path})"
160
+ _LOAD_ERROR = None
161
+ return lib
162
+ except OSError as exc:
163
+ errors.append(f"{label}: {exc}")
164
+ _LOAD_ERROR = "; ".join(errors) or "no native kernel found on any resolver path"
165
+ raise NativeUnavailable(_LOAD_ERROR)
166
+
167
+
168
+ def native_available() -> bool:
169
+ """True if the native kernel can evaluate right now. Never raises."""
170
+ try:
171
+ _load()
172
+ return True
173
+ except NativeUnavailable:
174
+ return False
175
+
176
+
177
+ def backend_info() -> dict:
178
+ """Diagnostics for the active backend. Never raises."""
179
+ info = {
180
+ "native_available": False,
181
+ "native_source": None,
182
+ "abi_version_expected": ABI_VERSION,
183
+ "abi_version_native": None,
184
+ "disabled_by_env": os.environ.get(_ENV_DISABLE) == "1",
185
+ "platform": sys.platform,
186
+ "error": None,
187
+ }
188
+ try:
189
+ lib = _load()
190
+ except NativeUnavailable as exc:
191
+ info["error"] = str(exc)
192
+ return info
193
+ info["native_available"] = True
194
+ info["native_source"] = _LIB_SOURCE
195
+ info["abi_version_native"] = int(lib.gaussgridmojo_abi_version())
196
+ return info
197
+
198
+
199
+ def eval_grid(
200
+ basis,
201
+ ax: np.ndarray,
202
+ ay: np.ndarray,
203
+ az: np.ndarray,
204
+ coeff: np.ndarray,
205
+ mode: int,
206
+ ) -> np.ndarray:
207
+ """Evaluate on the native kernel; raises NativeUnavailable on any failure.
208
+
209
+ ``basis`` is a ``_basis.BasisArrays`` (already contiguous typed arrays),
210
+ ``ax``/``ay``/``az`` are the grid axes in bohr, ``coeff`` is the
211
+ (n_mo, n_bf) coefficient matrix, and the return is the C-order raveled
212
+ grid, float64[nx*ny*nz]. The kernel writes into a fresh buffer per call;
213
+ input buffers are only read.
214
+ """
215
+ if mode == MODE_WAVEFUNCTION and coeff.shape[0] != 1:
216
+ raise NativeUnavailable("wavefunction mode requires exactly one MO row")
217
+ if mode not in (MODE_WAVEFUNCTION, MODE_DENSITY):
218
+ raise NativeUnavailable(f"unknown mode {mode}")
219
+ lib = _load() # raises NativeUnavailable
220
+ f64p = ctypes.POINTER(ctypes.c_double)
221
+ i32p = ctypes.POINTER(ctypes.c_int32)
222
+ i64p = ctypes.POINTER(ctypes.c_int64)
223
+ ax = np.ascontiguousarray(ax, dtype=np.float64)
224
+ ay = np.ascontiguousarray(ay, dtype=np.float64)
225
+ az = np.ascontiguousarray(az, dtype=np.float64)
226
+ coeff = np.ascontiguousarray(coeff, dtype=np.float64)
227
+ nx, ny, nz = ax.shape[0], ay.shape[0], az.shape[0]
228
+ out = np.empty(nx * ny * nz, dtype=np.float64)
229
+ rc = lib.gaussgridmojo_eval(
230
+ ctypes.c_int64(basis.n_bf),
231
+ basis.offsets.ctypes.data_as(i64p),
232
+ basis.powers_l.ctypes.data_as(i32p),
233
+ basis.powers_m.ctypes.data_as(i32p),
234
+ basis.powers_n.ctypes.data_as(i32p),
235
+ basis.center_x.ctypes.data_as(f64p),
236
+ basis.center_y.ctypes.data_as(f64p),
237
+ basis.center_z.ctypes.data_as(f64p),
238
+ basis.bf_norm.ctypes.data_as(f64p),
239
+ basis.prim_alpha.ctypes.data_as(f64p),
240
+ basis.prim_w.ctypes.data_as(f64p),
241
+ ax.ctypes.data_as(f64p),
242
+ ay.ctypes.data_as(f64p),
243
+ az.ctypes.data_as(f64p),
244
+ ctypes.c_int64(nx),
245
+ ctypes.c_int64(ny),
246
+ ctypes.c_int64(nz),
247
+ ctypes.c_int64(coeff.shape[0]),
248
+ coeff.ctypes.data_as(f64p),
249
+ ctypes.c_int32(mode),
250
+ out.ctypes.data_as(f64p),
251
+ )
252
+ if rc != 0:
253
+ raise NativeUnavailable(f"native evaluation failed with status {rc}")
254
+ return out