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.
@@ -0,0 +1,83 @@
1
+ """Vendored pure-Python (NumPy-vectorized) reference grid evaluator.
2
+
3
+ This is the fallback path used when the native Mojo kernel is unavailable
4
+ (unsupported platform, missing shared library, ABI mismatch, or
5
+ ``CCLIB_MOJO_DISABLE_NATIVE=1``). It is a clean-room implementation of the
6
+ textbook contracted-Cartesian-Gaussian amplitude (Taketa, Huzinaga, O-ohata,
7
+ J. Phys. Soc. Jap. 21, 2313 (1966)):
8
+
9
+ bf(r) = N_c * (x-cx)^l (y-cy)^m (z-cz)^n * sum_p w_p exp(-alpha_p |r-c|^2)
10
+
11
+ written to match the published PyQuante reference semantics (same primitive
12
+ and contracted normalization, same zero-coefficient skipping rule as
13
+ cclib). Both backends consume the same ``_basis.BasisArrays``, so they can
14
+ never disagree about centers, powers, or normalization constants; the
15
+ differential suite asserts both against PyQuante within 1e-10 relative.
16
+
17
+ Only the grid evaluation lives here — basis validation and normalization
18
+ are shared with the native path in ``cclib_mojo._basis``.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import numpy as np
24
+
25
+ MODE_WAVEFUNCTION = 0
26
+ MODE_DENSITY = 1
27
+
28
+
29
+ def eval_grid(
30
+ basis,
31
+ ax: np.ndarray,
32
+ ay: np.ndarray,
33
+ az: np.ndarray,
34
+ coeff: np.ndarray,
35
+ mode: int,
36
+ ) -> np.ndarray:
37
+ """Evaluate MO amplitude(s) or the summed density on the whole grid.
38
+
39
+ Same contract as ``cclib_mojo._native.eval_grid``: returns the C-order
40
+ raveled float64 grid of shape (nx*ny*nz,). ``coeff`` is (n_mo, n_bf).
41
+ """
42
+ if mode not in (MODE_WAVEFUNCTION, MODE_DENSITY):
43
+ raise ValueError(f"unknown mode {mode}")
44
+ if mode == MODE_WAVEFUNCTION and coeff.shape[0] != 1:
45
+ raise ValueError("wavefunction mode requires exactly one MO row")
46
+
47
+ nx, ny, nz = ax.shape[0], ay.shape[0], az.shape[0]
48
+ out = np.zeros((nx, ny, nz), dtype=np.float64)
49
+ for mo in range(coeff.shape[0]):
50
+ crow = coeff[mo]
51
+ psi = np.zeros((nx, ny, nz), dtype=np.float64)
52
+ for b in range(basis.n_bf):
53
+ c = crow[b]
54
+ if c == 0.0:
55
+ # cclib's `if abs(mocoeffs[bs]) > 0.0` rule: functions with
56
+ # an exactly zero coefficient contribute exactly zero.
57
+ continue
58
+ dx = ax - basis.center_x[b]
59
+ dy = ay - basis.center_y[b]
60
+ dz = az - basis.center_z[b]
61
+ dx3 = dx[:, None, None]
62
+ dy3 = dy[None, :, None]
63
+ dz3 = dz[None, None, :]
64
+ r2 = dx3 * dx3 + dy3 * dy3 + dz3 * dz3
65
+ o0, o1 = int(basis.offsets[b]), int(basis.offsets[b + 1])
66
+ contraction = np.zeros((nx, ny, nz), dtype=np.float64)
67
+ for p in range(o0, o1):
68
+ contraction += basis.prim_w[p] * np.exp(-basis.prim_alpha[p] * r2)
69
+ psi += (
70
+ c
71
+ * basis.bf_norm[b]
72
+ * (
73
+ np.power(dx3, basis.powers_l[b])
74
+ * np.power(dy3, basis.powers_m[b])
75
+ * np.power(dz3, basis.powers_n[b])
76
+ * contraction
77
+ )
78
+ )
79
+ if mode == MODE_WAVEFUNCTION:
80
+ out = psi
81
+ else:
82
+ out += psi * psi
83
+ return out.reshape(nx * ny * nz)
@@ -0,0 +1,90 @@
1
+ """cclib integration: drop-in equivalents of cclib's volume functions.
2
+
3
+ These functions mirror the signatures and semantics of
4
+ ``cclib.method.volume.wavefunction``, ``electrondensity_spin`` and
5
+ ``electrondensity`` — without monkeypatching cclib. They duck-type the two
6
+ inputs (any object with the ``ccdata.gbasis``/``ccdata.atomcoords``
7
+ attributes and any object with the ``Volume`` attributes
8
+ ``origin``/``topcorner``/``spacing``/``data``), evaluate with cclib_mojo,
9
+ and return a copy of the volume whose ``data`` attribute holds the result.
10
+
11
+ Usage with a real parsed logfile::
12
+
13
+ import cclib
14
+ from cclib.method.volume import Volume
15
+ from cclib_mojo import cclib_integration
16
+
17
+ data = cclib.io.ccread("calc.log")
18
+ vol = Volume(origin=(-5, -5, -5), topcorner=(5, 5, 5),
19
+ spacing=(0.2, 0.2, 0.2))
20
+ wf = cclib_integration.wavefunction(data, vol, data.mocoeffs[0][3])
21
+ wf.writeascube("mo4.cube") # same layout cclib would write
22
+
23
+ No cclib import happens here; cclib is an optional, user-side dependency.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import copy
29
+
30
+ import numpy as np
31
+
32
+ from cclib_mojo.core import density_on_grid, wavefunction_on_grid
33
+
34
+
35
+ def _grid_spec(volume) -> tuple[np.ndarray, np.ndarray, tuple[int, int, int]]:
36
+ """(origin, spacing, shape) from a cclib-Volume-like object."""
37
+ origin = np.asarray(volume.origin, dtype=np.float64)
38
+ spacing = np.asarray(volume.spacing, dtype=np.float64)
39
+ shape = tuple(int(d) for d in volume.data.shape)
40
+ return origin, spacing, shape
41
+
42
+
43
+ def wavefunction(ccdata, volume, mocoeffs):
44
+ """cclib ``wavefunction`` equivalent: one MO's amplitude on the volume.
45
+
46
+ ``mocoeffs`` is a 1-D coefficient vector (e.g. ``ccdata.mocoeffs[0][3]``).
47
+ Returns a copy of ``volume`` with ``data`` replaced.
48
+ """
49
+ origin, spacing, shape = _grid_spec(volume)
50
+ grid = wavefunction_on_grid(
51
+ ccdata.gbasis, ccdata.atomcoords[-1], mocoeffs, origin, spacing, shape
52
+ )
53
+ wavefn = copy.copy(volume)
54
+ wavefn.data = grid
55
+ return wavefn
56
+
57
+
58
+ def electrondensity_spin(ccdata, volume, mocoeffslist: list) -> object:
59
+ """cclib ``electrondensity_spin`` equivalent: sum of squared MOs.
60
+
61
+ ``mocoeffslist`` is a length-1 list of MO coefficient matrices, exactly
62
+ as cclib expects (``[ccdata.mocoeffs[0][1:2]]``).
63
+ """
64
+ if len(mocoeffslist) != 1:
65
+ raise ValueError("mocoeffslist input to the function should have length of 1.")
66
+ origin, spacing, shape = _grid_spec(volume)
67
+ grid = np.zeros(shape, dtype=np.float64)
68
+ for mocoeffs in mocoeffslist:
69
+ grid += density_on_grid(
70
+ ccdata.gbasis, ccdata.atomcoords[-1], mocoeffs, origin, spacing, shape
71
+ )
72
+ density = copy.copy(volume)
73
+ density.data = grid
74
+ return density
75
+
76
+
77
+ def electrondensity(ccdata, volume, mocoeffslist: list) -> object:
78
+ """cclib ``electrondensity`` equivalent.
79
+
80
+ One spin set (restricted) doubles the spin density; two spin sets
81
+ (unrestricted) sums them — the same convention as cclib.
82
+ """
83
+ if len(mocoeffslist) == 2:
84
+ alpha = electrondensity_spin(ccdata, volume, [mocoeffslist[0]])
85
+ beta = electrondensity_spin(ccdata, volume, [mocoeffslist[1]])
86
+ alpha.data = alpha.data + beta.data
87
+ return alpha
88
+ edens = electrondensity_spin(ccdata, volume, [mocoeffslist[0]])
89
+ edens.data *= 2
90
+ return edens
cclib_mojo/core.py ADDED
@@ -0,0 +1,284 @@
1
+ """Public grid API: MO wavefunctions and electron densities on 3-D grids.
2
+
3
+ Both entry points evaluate contracted Cartesian Gaussian basis functions
4
+ (cclib's ``gbasis``) on a regular 3-D grid and return float64 NumPy arrays
5
+ whose layout matches cclib's ``Volume.data`` exactly: shape
6
+ ``(nx, ny, nz)``, C-order, element ``[i, j, k]`` at coordinate
7
+ ``(origin[0]+i*step[0], origin[1]+j*step[1], origin[2]+k*step[2])``.
8
+
9
+ Units follow cclib: ``atomcoords``, ``origin`` and ``step`` are in
10
+ Angstrom; Gaussian exponents in ``gbasis`` are in bohr^-2 (as parsed by
11
+ cclib); amplitudes are in atomic units. Evaluation runs on the native Mojo
12
+ kernel when available and on the vendored NumPy reference otherwise; both
13
+ backends share basis flattening and normalization in ``cclib_mojo._basis``.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+
20
+ import numpy as np
21
+
22
+ from cclib_mojo import _reference
23
+ from cclib_mojo._basis import (
24
+ BOHR2ANG,
25
+ COORDINATE_SANE_MAX,
26
+ INTERMEDIATE_MAGNITUDE_MAX,
27
+ BasisArrays,
28
+ flatten_gbasis,
29
+ )
30
+ from cclib_mojo._native import (
31
+ MODE_DENSITY,
32
+ MODE_WAVEFUNCTION,
33
+ NativeUnavailable,
34
+ _load,
35
+ )
36
+
37
+ _INTERMEDIATE_LOG10_MAX = math.log10(INTERMEDIATE_MAGNITUDE_MAX)
38
+
39
+
40
+ class GridError(ValueError):
41
+ """Malformed grid or MO-coefficient input (structured, fail-fast)."""
42
+
43
+
44
+ def _validate_vector3(name: str, value: object) -> np.ndarray:
45
+ arr = np.asarray(value, dtype=np.float64)
46
+ if arr.shape != (3,):
47
+ raise GridError(f"{name} must be a 3-vector, got shape {arr.shape}")
48
+ if not np.all(np.isfinite(arr)):
49
+ raise GridError(f"{name} contains non-finite values")
50
+ return arr
51
+
52
+
53
+ def _validate_shape(shape: object) -> tuple[int, int, int]:
54
+ if not isinstance(shape, (list, tuple)) or len(shape) != 3:
55
+ raise GridError(f"shape must be a 3-tuple (nx, ny, nz), got {shape!r}")
56
+ out = []
57
+ for dim in shape:
58
+ if isinstance(dim, bool) or int(dim) != dim or int(dim) <= 0:
59
+ raise GridError(f"shape entries must be positive integers, got {shape!r}")
60
+ out.append(int(dim))
61
+ return out[0], out[1], out[2]
62
+
63
+
64
+ def _validate_grid_coordinates(
65
+ origin: np.ndarray, step: np.ndarray, shape: tuple[int, int, int]
66
+ ) -> None:
67
+ """Every grid corner must stay inside the documented coordinate domain."""
68
+ for i, (o, st, n) in enumerate(zip(origin, step, shape)):
69
+ end = o + (n - 1) * st
70
+ if abs(o) > COORDINATE_SANE_MAX or abs(end) > COORDINATE_SANE_MAX:
71
+ raise GridError(
72
+ f"grid axis {i} spans [{o!r}, {end!r}] Angstrom; every grid "
73
+ f"coordinate must be inside "
74
+ f"[-{COORDINATE_SANE_MAX!r}, {COORDINATE_SANE_MAX!r}] Angstrom"
75
+ )
76
+
77
+
78
+ def _grid_axes(
79
+ origin: np.ndarray, step: np.ndarray, shape: tuple[int, int, int]
80
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
81
+ """Grid-point coordinates in bohr, one vector per axis.
82
+
83
+ Mirrors cclib's ``getGrid`` (cclib/method/volume.py): points are
84
+ ``origin + i*step`` in Angstrom, divided element-wise by cclib's
85
+ bohr->Angstrom constant 0.5291772109.
86
+ """
87
+ nx, ny, nz = shape
88
+ ax = (origin[0] + np.arange(nx, dtype=np.float64) * step[0]) / BOHR2ANG
89
+ ay = (origin[1] + np.arange(ny, dtype=np.float64) * step[1]) / BOHR2ANG
90
+ az = (origin[2] + np.arange(nz, dtype=np.float64) * step[2]) / BOHR2ANG
91
+ return ax, ay, az
92
+
93
+
94
+ def _validate_coeff(coeff: object, n_bf: int) -> np.ndarray:
95
+ arr = np.asarray(coeff, dtype=np.float64)
96
+ if arr.ndim == 1:
97
+ arr = arr[None, :]
98
+ if arr.ndim != 2:
99
+ raise GridError(f"coeff must be an (n_mo, n_bf) array, got ndim={arr.ndim}")
100
+ if arr.shape[1] != n_bf:
101
+ raise GridError(
102
+ f"coeff has {arr.shape[1]} columns but the basis expands to "
103
+ f"{n_bf} Cartesian basis functions"
104
+ )
105
+ if arr.shape[0] == 0:
106
+ raise GridError("coeff contains zero MO rows")
107
+ if not np.all(np.isfinite(arr)):
108
+ raise GridError("coeff contains non-finite values")
109
+ return arr
110
+
111
+
112
+ def _intermediate_log10_magnitudes(
113
+ basis: BasisArrays,
114
+ axes: tuple[np.ndarray, np.ndarray, np.ndarray],
115
+ coeff2d: np.ndarray,
116
+ ) -> np.ndarray:
117
+ """Per basis function: log10 of a bound on every intermediate product.
118
+
119
+ Each grid term ``c N_c (x-cx)^l (y-cy)^m (z-cz)^n w_p exp(-alpha_p r^2)``
120
+ is a chain of float64 products that the two backends associate
121
+ differently (the kernel forms ``((c N_c) x^l) y^m`` first, the fallback
122
+ the polynomial times the contraction ``sum_p w_p exp(...)``). Since
123
+ ``exp(...) <= 1``, every partial product in either order is at most
124
+
125
+ max(1, |c| N_c) * max(1, |x-cx|)^l * max(1, |y-cy|)^m
126
+ * max(1, |z-cz|)^n * max(1, sum_p |w_p|)
127
+
128
+ with ``|c|`` the largest coefficient over the evaluated MO rows and each
129
+ distance the farthest grid coordinate. The bound is returned as a sum of
130
+ log10 terms so that computing it cannot overflow. Functions whose
131
+ coefficient is exactly zero in every row are skipped by both backends
132
+ (cclib's rule) and build no product: their bound is 0 (= log10 1).
133
+ """
134
+ coeff_peak = np.max(np.abs(coeff2d), axis=0)
135
+ active = coeff_peak > 0.0
136
+ # The placeholder 1.0 keeps log10 away from the skipped zeros.
137
+ log10_coeff_norm = np.maximum(
138
+ 0.0, np.log10(np.where(active, coeff_peak, 1.0)) + np.log10(basis.bf_norm)
139
+ )
140
+
141
+ log10_polynomial = np.zeros(basis.n_bf, dtype=np.float64)
142
+ centers = (basis.center_x, basis.center_y, basis.center_z)
143
+ powers = (basis.powers_l, basis.powers_m, basis.powers_n)
144
+ for axis, center, power in zip(axes, centers, powers):
145
+ # The farthest grid coordinate from a center is one of the axis ends.
146
+ reach = np.maximum(np.abs(axis.min() - center), np.abs(axis.max() - center))
147
+ log10_polynomial += power * np.log10(np.maximum(reach, 1.0))
148
+
149
+ # log10(max(1, sum_p |w_p|)), summed relative to max(1, max_p |w_p|) so
150
+ # that every ratio is <= 1 and the per-function sum cannot overflow.
151
+ abs_w = np.abs(basis.prim_w)
152
+ starts = basis.offsets[:-1]
153
+ w_unit = np.maximum(np.maximum.reduceat(abs_w, starts), 1.0)
154
+ prims_per_function = np.diff(basis.offsets)
155
+ w_rel_sum = np.add.reduceat(abs_w / np.repeat(w_unit, prims_per_function), starts)
156
+ log10_weights = np.maximum(
157
+ 0.0,
158
+ np.log10(w_unit) + np.log10(np.maximum(w_rel_sum, np.finfo(np.float64).tiny)),
159
+ )
160
+
161
+ return np.where(active, log10_coeff_norm + log10_polynomial + log10_weights, 0.0)
162
+
163
+
164
+ def _validate_intermediate_magnitudes(
165
+ basis: BasisArrays,
166
+ axes: tuple[np.ndarray, np.ndarray, np.ndarray],
167
+ coeff2d: np.ndarray,
168
+ ) -> None:
169
+ """No grid term may build a product above ``INTERMEDIATE_MAGNITUDE_MAX``.
170
+
171
+ Past the double range the backends' product orders overflow at different
172
+ stages (inf on one side, inf * 0 = NaN on the other), so such inputs have
173
+ no well-defined result and are rejected before evaluation.
174
+ """
175
+ log10_bound = _intermediate_log10_magnitudes(basis, axes, coeff2d)
176
+ worst = int(np.argmax(log10_bound))
177
+ if log10_bound[worst] > _INTERMEDIATE_LOG10_MAX:
178
+ powers = (
179
+ int(basis.powers_l[worst]),
180
+ int(basis.powers_m[worst]),
181
+ int(basis.powers_n[worst]),
182
+ )
183
+ raise GridError(
184
+ f"basis function {worst} (Cartesian powers {powers}) builds "
185
+ f"intermediate products up to ~1e{log10_bound[worst]:.1f} on this "
186
+ f"grid (|MO coefficient| x contracted norm x polynomial x "
187
+ f"primitive weights); every term must stay at or below "
188
+ f"{INTERMEDIATE_MAGNITUDE_MAX!r} so that no evaluation order "
189
+ f"overflows"
190
+ )
191
+
192
+
193
+ def _eval(
194
+ gbasis: object,
195
+ atomcoords: object,
196
+ coeff: object,
197
+ origin: object,
198
+ step: object,
199
+ shape: object,
200
+ mo_index: int | None,
201
+ ) -> np.ndarray:
202
+ basis = flatten_gbasis(gbasis, atomcoords)
203
+ coeff2d = _validate_coeff(coeff, basis.n_bf)
204
+ origin3 = _validate_vector3("origin", origin)
205
+ step3 = _validate_vector3("step", step)
206
+ if not np.all(step3 > 0.0):
207
+ raise GridError(f"step entries must be positive, got {tuple(step3)}")
208
+ shape3 = _validate_shape(shape)
209
+ _validate_grid_coordinates(origin3, step3, shape3)
210
+
211
+ if mo_index is not None:
212
+ if isinstance(mo_index, bool) or int(mo_index) != mo_index:
213
+ raise GridError(f"mo_index must be an integer, got {mo_index!r}")
214
+ mo_index = int(mo_index)
215
+ if not 0 <= mo_index < coeff2d.shape[0]:
216
+ raise GridError(
217
+ f"mo_index {mo_index} out of range for {coeff2d.shape[0]} MO rows"
218
+ )
219
+ coeff2d = coeff2d[mo_index : mo_index + 1]
220
+ mode = MODE_WAVEFUNCTION
221
+ else:
222
+ # Sum of squared MOs over every provided row (psi^2 for one row).
223
+ mode = MODE_DENSITY
224
+
225
+ axes = _grid_axes(origin3, step3, shape3)
226
+ _validate_intermediate_magnitudes(basis, axes, coeff2d)
227
+ try:
228
+ flat = _native_eval(basis, axes, coeff2d, mode)
229
+ except NativeUnavailable:
230
+ flat = _reference.eval_grid(basis, *axes, coeff2d, mode)
231
+ return flat.reshape(shape3)
232
+
233
+
234
+ def _native_eval(basis, axes, coeff2d: np.ndarray, mode: int) -> np.ndarray:
235
+ """Native path; raises NativeUnavailable so the caller can fall back."""
236
+ from cclib_mojo import _native
237
+
238
+ _load() # fail fast here if the kernel cannot be used at all
239
+ return _native.eval_grid(basis, *axes, coeff2d, mode)
240
+
241
+
242
+ def wavefunction_on_grid(
243
+ gbasis: object,
244
+ atomcoords: object,
245
+ mocoeffs: object,
246
+ origin: object,
247
+ step: object,
248
+ shape: object,
249
+ ) -> np.ndarray:
250
+ """Evaluate one molecular orbital's amplitude on a 3-D grid.
251
+
252
+ Equivalent to cclib's ``cclib.method.volume.wavefunction``: the result
253
+ equals that function's ``Volume.data`` for the same ``gbasis``,
254
+ ``atomcoords`` (Angstrom), ``mocoeffs`` (1-D, length n_bf), and grid
255
+ (Angstrom). Values are signed amplitudes in atomic units.
256
+ """
257
+ coeff = np.asarray(mocoeffs, dtype=np.float64)
258
+ if coeff.ndim != 1:
259
+ raise GridError(
260
+ f"mocoeffs for wavefunction_on_grid must be 1-D, got shape {coeff.shape}"
261
+ )
262
+ return _eval(gbasis, atomcoords, coeff, origin, step, shape, mo_index=0)
263
+
264
+
265
+ def density_on_grid(
266
+ gbasis: object,
267
+ atomcoords: object,
268
+ coeff: object,
269
+ origin: object,
270
+ step: object,
271
+ shape: object,
272
+ mo_index: int | None = None,
273
+ ) -> np.ndarray:
274
+ """Evaluate electron density (or one MO) on a 3-D grid.
275
+
276
+ ``coeff`` is an (n_mo, n_bf) array of MO coefficients (a 1-D array is
277
+ promoted to a single row). With ``mo_index=None`` the result is
278
+ ``sum_mo |psi_mo(r)|^2`` — cclib's ``electrondensity_spin`` semantics;
279
+ for a closed-shell total density pass the occupied spatial MOs and
280
+ multiply by 2, exactly as cclib's ``electrondensity`` does. With an
281
+ integer ``mo_index`` the result is that MO's signed amplitude instead
282
+ (cclib's ``wavefunction`` semantics).
283
+ """
284
+ return _eval(gbasis, atomcoords, coeff, origin, step, shape, mo_index)