Repository navigation
Add nonorthogonal configuration interaction with the extended nonorthogonal Wick's theorem - #226
Conversation
…rank case separately
|
I'm a bit curious about whether it's possible to build the pyscf implementation of NOCI upon a reusable library since there's already noci-rs/libgnme. Or is there any reason for re-writing a C library here? |
The principal reason with regard to Using I would say that writing the C implementation here is useful because it means the port can be self-contained and add no new dependencies. |
|
The CI failure was a name clash between |
|
I built Should fix1. A complex Hamiltonian with real references silently loses its imaginary part. In 2. AVX2 kernels go untested on AVX-512 machines. def test_simd_levels(self):
refs = _references()
dets = _dets(refs, 6, 3, 8)
try:
for level in range(3):
if _wicks.libwick.NOWICKset_simd(level) != level:
continue
with self.subTest(simd=level):
self.check(refs, dets)
finally:
_wicks.libwick.NOWICKset_simd(-1)This would replace Implementation: questions and optional improvements
I also checked the Faddeev–LeVerrier determinants against LU for n ≤ 8 on random matrices: the 95th-percentile relative error is 3e-14, so I have no concern there. Tests: gaps where I checked the code by handI ran these locally and they all pass. They are listed so you can decide which ones are worth keeping as tests.
Tests and examples: optional / readability
PR contextpyscf/pyscf#1697 (a NOCI feature request) was closed with a pointer to the existing This review was drafted with the help of Claude Code (Claude Opus 5.5), which read the code, built the PR, ran the tests, examples and the extra checks above, and composed the text. I reviewed and edited it before posting, specifically by deleting a bunch of stuff that I thought wasn't worth bugging you about. |
|
Thanks for this review and for the extra check of the Faddeev–LeVerrier determinants against LU; that is helpful. Both "Should fix" points have been addressed using your suggested implementations: the dtype is taken from The duplication described is removed with the A new check in Finally, I have edited the PR description to describe how it is d
8000
ifferentiated from |
Remove add_subdirectory(sfnoci) (no such directory) and a duplicate add_subdirectory(pwscf) introduced while resolving rebase conflicts. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…and det <-> CSF transforms (#225) * Initial commit: trying to make mem-efficient hdiag * Try to reorganize csf C code * Syntax cleanup * Finish writing vector coupling coeff * fix normalization and write some commentary * hdiag_csf rework to use hdiag_det instead of hcoul * Syntax in-place Numerically very buggy * partial debug * continuing debug of csf_mem indexing * debugging printouts * passes test_csf hdiag unittest! * Silence debug i/o * Update test_csf to have a spin potential The hdiag_csf rewrite is 1) slow, and 2) does not yet account for spin potentials * signoff commit * more printouts * Apparent debug but I don't understand why There's a factor of 2 that appeared out of nowhere that I still need to understand in szfac * generalize test_hdiag_csf to other m it instantly fails * Fix generalization Actually it was the reference that was wrong, if I recompute the reference each time it passes. * make test_csf generalizeable to diff norb In case you wanted to test that * Clean up csf_op.c I can finally say this is actually debugged * remove whitespace * commentary explanation of xdiag * add general wigner_6j function to csf_op * forgot square root * fix comment * permutation logic in wigner function * xdiag use wigner function * syntax * Debug wigner code I guess there was an OOP issue with the remainder operator? * generalize csf get_x * generalize get_x to 4 points * comments * rationalize normalization stuff * factorize norms out of x expresssion * refactor get_x to have arrays with S * trying to document my insane notes about parity * update notes * _get_x generalize p,r completely * remove assert * safety commit * _get_x is allegedly complete Except there is an overall factor of -1 (that does not affect Sz) that I can't account for * Factor out xcore diagram * Clarify func names and commentary * Use Str3 struct in csf CGC code more * safety commit * Clean up CGC_link * GCG_link fix for spin flips * Safety commit * index handling in FCICSFpspace * sign-off commit * GCG_1e pp, hh logic * csf_Sai * csf_Sai debugged and used in hdiag * safety commit * nicer find_spin_Oai * csf_EaiEbj safety commit * csf_EaiEbj diag debug * cleanup obsolete code * Tried to implement pspace using new code assertions checking index logic are failing in the c code * fix twoS array size logic Now failing index value asserts and segfaulting when those asserts are disabled. * Fix orbital index issue now it's just segfaulting * fixed segfault now something related to the bit counting in the excitation analysis is failing. different # electrons? * dconfstrs sometimes go below 0 as a sentinel * break statements in switch?? * partial debug: state logic pass asserts still not checking the CGC stuff yet!! * one csf_Sai call; no segfault/assert fail * one csf_EaiEbj call; no segfault/assert fail * Parity tracking problem in csf_Eai/CGC_1e * Fix a bad assert The segfault now happening is guaranteed not to be in CGC_1e * Cure segfault in csf_Eai, I think * Mark assert failures of remaining csf_ calls * csf_Sai fix parity failure all switch blocks need breaks in C * fix assert fails in first call to csf_EaiEbj * update tags identifying failed asserts on remaining calls to csf_EaiEbj * csf_EaiEbj endless parity debugging in progress Also an issue with sorting ambiguity! * trying to figure out sorting ambiguity in the 4-point diagram, when the internal indices collide with opposite signs and both doubly-occupied, the order is undefined. * still stuck in the parity mines * parity mines aaah * Avoid referencing undefined values of twoSx * glitch in _get_spinindices2 when np = nq = 2 entries were undefined because nspin0 was not the size of the array through q. * just define the internal pair spins * First "successfull" (no C crashes) run of pspace * Clean up print statements in c code We might have a memory leak. Check for this somehow later * fix lint issues * remove unnecessary pointer reassignment you can redefine a pointer in a function without messing up its pointer in calling scope. the problem i was having earlier was the memory leak elsewhere. * Fix nan in csf_Sai Need to use the original length for the get_twoS command * Debugging zoomins Down to 2 electrons; I'm getting 1 when I should be getting -1/sqrt(2). * CGC_1e also needs norm factor * CGC_1e 2-electron singlet parity correct The parity tracking in A(q) and B(p) needs to be revisited. The way it is now, 2-electron singlet terms appear to always have the correct parity, but there are still some sign problems with more electrons. * CSF coupstr orth logic & zero-spin special case All 1- and 2-electron Eai terms now seem to work * Fix off-by-1 in CGC_1e norm Possible error still in CGC_2e_X norm. * Separate test_csf.py for safer debugging test_csf.py is for making sure I don't mess up the hdiag. test_csf_2elec is for making sure the 2-electron case stays working (N.B.: it currently only works for h1e) * type in the Drake signs in CGC_1e even though it breaks 2 electron * CSF sign debugging: consistency across seniorities The CSF sign convention is still not consistent across CSFs of different seniorities. If it were, ai bi |csf> should always generate +1 * a CSF in a different particle-number sector. A check for this has been added to debug_csf.py and has not yet passed. * Comment describing the spin-consistency mod That has to happen * safety commit: sign * test old pspace * test old_pspace with symmetry * Try to implement proper sign rule for CSFs? It still doesn't work though, what am I missing? * Correct handling of npair in det2csf_sign_rule Might still be a question mark about dconf when npair = 0. Also need to extend the range of debug_csf to see all possible failures * Fix very old edge case bug in csdstring.py Transpose if shape[1] == 2? Only if shape[0] is not also 2!!! * debug det2csf_sign_rule Ensure sign of a CSF vector does not change upon addition or removal of a pair of electrons in a single spatial orbital. * pair creation order convention in CSF solver For some reason, it appears that for (3e,3o) and (4e,3o) at least, the CSF vector coupling elements I've implemented are consistent with electron pair creation operators being b'a', not a'b'. Add the corresponding sign flip to the CSF vector transformation. * Fix normalization bug in CGC_1e If p==q+1, a factor of sqrt (1/(2S(q-1)+1)) might not be accounted for by implicit product range restrictions and has to be explicitly computed. * csf_Eai fully debugged??? * add operator anticommutation parity in csf_Sai Seems to fix the sign problem, at least for 2 electrons * Debug csf_Sai w claude code sonnet 4.6; summary message follows: Fixed. Two bugs in the normalization loop of CGC_2e_X (pyscf/lib/csf/csf_op.c:449), both causing exactly a sqrt(2) error in doublet pspace elements where a doubly-occupied orbital sits at the edge of the active spin-graph segment: 1. Off-by-one in the ket's DOMO gap (csf_op.c:449). csf_Sai increments sa an extra time for a bra DOMO (if (abs(na)==2){ sa++; }) but never does so for si. So r = si points at the top of the ket's gap (gap = [r-1, r]) while p = sa sits two above the bra gap's bottom (gap = [p-2, p-1]). The loop assumed the ket gap was [r, r+1] — the line carried your own TODO: not sure if off by 1!. 2. The i==0 "dummy electron" rule zeroed the wrong side (csf_op.c:459). It unconditionally dropped the bra's CG factor, but when position 0 already lies inside the bra's DOMO gap that factor is already zero, so the rule became a no-op and left a spurious (2S_ket+1) in the norm. It now drops the ket's factor in that case. * noting previous commit claude session id claude --resume 5c6acb8f-5f71-43d9-b6a5-02f8e5be130b * add commentary to csf_op.c source * fix dbl-counting EaiEaj in FCICSFpspace_h0tril * debugging csf_EaiEbj Add code to check one element at a time. Add debugging printouts. In parity, replace (int) (i>j) with 1, because it always is true in hdiag_csf but the i<=j branch apparently causes a spurious sign flip in <du00|e|00du>. * safety commit * safety commit I'm thinking (int) (i>j) makes sense, but i still can't figure out how <du00|e|00du> is supposed to not cancel out. * add DIARY.md * clarifications * csf_op: fix pp/hh norm in CGC_1e; drop (i>j) from EaiEbj parity CGC_1e's norm product counted a CG coefficient at S(q) for both spin chains. In the pp/hh case one chain is subsequently padded with a fabricated singlet pair, and that chain's S(q) node carries no CG coefficient of its own. Skip it, mirroring the existing nq==+/-2 exclusions. The pp/hh branch is unreachable from csf_Eai and csf_Sai, whose np and nq always have opposite signs, and from the hdiag path, so it was untested by everything the hdiag and 1e tests cover. In csf_EaiEbj, (i>j) was the only surviving difference between E^a_i E^b_j and E^a_j E^b_i after canonicalization -- both reduce to identical (sp,sr,sq,st) and (np,nr,nq,nt) -- so it was forcing a spurious cancellation of <du00|e|00du> to zero instead of 2. Key the term on whether the p,r pair is pp/hh rather than ph instead. This is bit-identical on the hdiag path, where (i>j) was always 1. It is fit to two data points and not yet derived from Drake & Schlesinger. Open-shell double excitations in test_csf_2elec.py's pspace are now exact. Still wrong: nch==1 elements are uniformly a factor of 2 short, and doubles involving a doubly-occupied orbital have the right magnitude but the wrong sign. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * update parity comment in csf_EaiEbj * DIARY.md about csf_EaiEbj parity line * e^ap_ip missing permutation e^ap_ip -> E^a_i E^p_p, E^a_p E^p_i. First one was omitted before. Now included. * test_csf_2elec.py fully debugged in general A sign of +1 was apparently wrong in csf_EaiEaj. * Update DIARY.md * Commentary and asserts, csf_op.c and DIARY.md * Tighten index assignment in csf_EaiEbj The rule p >= r >= q >= t in CGC_2e_X should now be *almost* always followed, with one particular exception in the "pphh" case. * assert (false) in questionable branch Claude thinks it's possible to reach that branch. I suspect there's some principle forbidding it, but I need to review its logic with fresh eyes because it's late and I'm tired. * Update DIARY.md * Add guards in csf_EaiEbj. The heap can get corrupted if the csf_* functions get called with malformed arguments. TODO: implement similar guards in csf_Eai, csf_Sai, and csf_EaiEaj. * refine comment * Two q/r errors 1. When I interchange sq and sr, I need to also interchange q and r so that the connectivity test (i==r) works. 2. When evaluating unlinked_orth, I accidentally interchanged them. Fixing this doesn't make that right because there's a logical problem when pphh, but one thing at a time * Rework unlinked_orth check Use the multiplicitly lists rather than the bit strings to identify when unlinked diagram products are orthogonal because internal spins are not identical. * Shift the ket line for unlinked pphh * Remove some dbl-counting in CGC_2e_X pphh * Try to fix antisymmetry of linked doubles I assigned an i>j toggle to the parity line in csf_EaiEbj. Kinda empirical. * Special unlinked sign flip. D&S don't mention it, but I think B&S rule (7.5) is essential to understanding how they decompose the double excitations. I finally get why they put the arrows where they did on Fig. 3 as well as the factor of 1/2 that seems to come out of nowhere, and it has to do with the fact that you CAN'T just drop a line with s = 0. * Update refs, add conv check in test_csf* kernel * add test_csf_spinless.py (temporary) This checks the more-or-less trivial result when all electrons are parallel and ferromagnetically coupled, for varying numbers of electrons. * Loop over m in all test_pspace I mean this may be pointless since I guess csf_op.c doesn't even see m, but it makes me feel better. * csf_EaiEbj right escape mask fix x<<p - 1 (like the other three fns), not x<<(p-1) - 1 * off-by-1 in CGC_2e_X_core Found empirically with Claude's aid. This off-by-1 error resulted in terms touching the undefined intermediate spin values of paired electrons. There might still be a similar error on the other side of the diagram. * All but pphh debugged in csf_mem Merging the substantive parts of Claude's csf_mem_reads branch (6b9b85d). This uses a brute-force oracle for the pphh terms, which need to be rederived. Probably I should just branch to a different X_core function and then ask Claude whether it corresponds to a special case of my first one. Also added guard tape around norb > 30 because I think I was dumb and used int rather than uint for something. * Graphical pphh and nested hphp in csf_EaiEbj pphh (a<b, i<j or j<i) is now evaluated graphically by default (CSF_PPHH_GRAPHICAL=1) instead of through the RI oracle; building with -DCSF_PPHH_GRAPHICAL=0 falls back to csf_EaiEbj_ri_local as a check. The linked part is my recipe (phph outer T strings times the hphp X_core with the bra spins shifted by 2); the bugs were bra-index vs ket-index mixups in the sq > sr swap, the |nq|==2 block, the T-string edge skips for a pair at b or i, and the norm boundary drop for pairs (_pair_claims). The unlinked part now goes through the unique intermediate CSF and two csf_EaiEaj pair hops (_pphh_unlinked), which replaces the CGC_1e pphh branch (now dead code). Nested hphp (j<a<i<b) no longer branches to the adjoint (CSF_HPHP_GRAPHICAL=1); only the setup in csf_EaiEbj needed generalizing. Also removes an underflowing twoSb[sx-2] read in the unlinked_orth check. Checked against the RI oracle: fullcheck has 0 wrong in every category at norb=6 and 7, csf_fci tests pass with and without the debug skips, ASan clean, and pspace is 7-20% faster than the RI route. Still empirical: the parity line in csf_EaiEbj. Other orderings still use the adjoint. Debugged and drafted with Claude. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Clean up dead code. Removed: 1. GCG_1e pphh branch. pp and hh interactions are now evaluated entirely through csf_EaiEaj with a -> dummy orbital. 2. CGC_2e_X qt_pp nq<0 branch: not reached because we always do pphh, never hhpp. 3. i==j and a==b blocks in csf_EaiEbj that are below the branch to csf_EaiEaj, and therefore unreachable 4. DUMMY_RULE machinery, which was a harness for finding illegal reads of undefined spins. 5. CGC_1e's p<q flip; which is redundant with the CSF_Eai caller's a <-> i flip. * One last 4elec check Generalize the 1- and 2-electron operators * Remove temporary test_csf files I also updated DIARY.md last commit and forgot to mention it. * Update DIARY.md with next problem statement * Apply umat one spin at a time for large nspin The det <-> CSF transformations no longer build the dense umat array from get_spin_evecs when there are many unpaired electrons. The new FCICSFspinevecs_dot in csf_string.c computes x . umat or x . umat^T as a sequence of nspin sparse steps, each coupling one more spin by 2x2 Clebsch-Gordan rotations, with the same sign conventions as FCICSFmakecsf. No step holds more than ndet states, so it needs about nspin*ndet*20 bytes of index tables plus a fixed-size buffer per thread, never a max_memory check. At nspin = 20 that's ~74 MB versus ~25 GB for the singlet umat. csfstring.spin_evecs_dot uses the dense umat below SWEEP_MIN_NSPIN and the sweep at or above it. The cutoff is a performance crossover, not a memory limit, and is set by the __config__ key csf_fci_csfstring_sweep_min_nspin (default 14). With an -O3 build the sweep is 1.7-6.5x faster at nspin = 14 and 4-21x faster at 16. _transform_det2csf and transform_opmat_det2csf_pspace both go through it, and project=True no longer builds the ndet x ndet Pmat. New tests in test_csfstring.py check the sweep against the dense umat for every (nspin, S, M) up to nspin = 12, and check that the transformations agree with the cutoff at 0 and at 99. The default test suite never reaches nspin >= 11, so without them the sweep side would be untested. project_civec_csf fails for any input (it ravels to 1D before a 2D shape assert); that predates this commit, so the test calls _transform_det2csf with project=True directly. Partially addresses #156. Written and tested with Claude. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * cache expensive refs in test_csf.py * ftr Claude Opus 5.5 wrote the code last commit * Fix int shift; 64 > n > 30 enabled in csf * Avoid shift by 64 in _pad_Str3 Both padding loops computed (x >> p) << (p+1), which is undefined for p = 63. The spin loop reaches p = 63 on nearly every call, because ~sconf has bit 63 set unless orbital 63 is singly occupied. The sconf loop reaches it when orbital 63 is doubly occupied, which happens for the spare orbital in _pphh_unlinked. The shifted value was always 0, so results were correct on x86, but the compiler is free to assume p + 1 < 64. The csf_fci tests now run clean under -fsanitize=undefined. Written and tested with Claude. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Remove DIARY.md Was for orienting agents during debugging. No longer necessary. * remove unused vars (ruff/flake) * caution tape around nspin > 31 stuff ...which otherwise crashes cistring and overflows indices in FCICSFspinevecs_dot * Fix CMakeLists.txt after rebase onto #226 Remove add_subdirectory(sfnoci) (no such directory) and a duplicate add_subdirectory(pwscf) introduced while resolving rebase conflicts. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Summary
This PR adds
pyscf.nonorthogonal, which evaluates Hamiltonian and overlap matrix elements between arbitrary excitations of nonorthogonal reference determinants with the extended nonorthogonal Wick's theorem (see H. G. A. Burton, J. Chem. Phys. 154, 144109 (2021); 157, 204109 (2022)), and nonorthogonal configuration interaction (NOCI) using said matrix elements.It is a port of the Wick's theorem engine in noci-rs, my Rust NOCI code, which itself is based upon that of libgnme. noci-rs is MIT licensed; I am its copyright holder and contribute this port under Apache-2.0.
It includes:
NOCIclass following the PySCF CI interface, withNOCISDandNOCISDTand any excitation level throughlevel=.WickEngineandDeterminantfor individual matrix elements and dense H/S over any list of determinants.libnonorthwick) for real and complex orbitals, with AVX2/AVX-512 packed variants selected at run time and OpenMP.Short usage example:
Implementation
NOCI driver
NOCI(mol, references, level)builds every reference and its excitations up tolevel(default 0, the references only), evaluates H and S, and solves the generalised eigenproblem densely withlib.linalg_helper.safe_eigh.excitations()returns the determinants of one reference, andNOCISDandNOCISDTsetlevelto 2 and 3. References may be RHF/ROHF/UHF objects or(mo_coeff, mo_occ)pairs, real or complex, with the same number of MOs (at most 128) and electrons.Matrix elements
FCIpspace_h0tril_uhfto complex orbitals and up to 128 MOs.1/S_kterms.C backend
The kernels are written once and instantiated for real and complex orbitals. They are built as
libnonorthwickthrough the CMake configuration inpyscf/lib.Tests
The unit tests compare against an FCI-space expansion of each determinant. They cover real and complex orbitals, up to quadruple excitations, zero-overlap and near-zero pairs, and the scalar, SIMD and general paths. They also check NOCISD of one RHF reference against
ci.CISD, and full-level NOCI against FCI. Matrix elements also agree with noci-rs to about 1e-14 on H6/cc-pVDZ.They can be run with:
The examples in
examples/nonorthogonaldemonstrate:Performance
WickEngine.build_matricesfor the singles and doubles of three H6/cc-pVDZ references (26,490 determinants, 3.5e8 elements of the upper triangle) on an AMD Ryzen 9 5950X:The scalar kernels are always built and are used when the CPU supports neither instruction set. The AVX-512 kernels pass the full test suite under the Intel Software Development Emulator (Sapphire Rapids); they have not been benchmarked on AVX-512 hardware, which was unavailable.
Scope
This PR is limited to the matrix-element engine and NOCI with a dense eigensolver.
Review Edits
The
hf_det_ovlpofmsdft.nociprovides elements only between reference determinants, without excitations, and, as its comments note, deals with more than two zero singular values only approximately. This PR is therefore differentiated in that it covers arbitrary excitation levels and any number of zero or near-zero overlaps without approximation. It would likely be helpful formsdftto useWickEngineat some point, and this is something I would be interested in doing in future.AI assistance
Claude Code (Claude Opus models) was used to port this code from noci-rs, and to write the tests, examples and documentation. The implementation follows noci-rs where it can while keeping PySCF's style and conventions; the differences are described above. I have reviewed the code and tests.