8000 Add nonorthogonal configuration interaction with the extended nonorthogonal Wick's theorem by dy-cl · Pull Request #226 · pyscf/pyscf-forge · GitHub
[go: up one dir, main page]

Skip to content

Add nonorthogonal configuration interaction with the extended nonorthogonal Wick's theorem - #226

Merged
MatthewRHermes merged 16 commits into
pyscf:masterfrom
dy-cl:nonorthogonalwicks
Oct 22, 2026
Merged

MatthewRHermes merged 16 commits into
pyscf:masterfrom
dy-cl:nonorthogonalwicks

Conversation

@dy-cl
@dy-cl dy-cl commented Oct 21, 2026 •
Copy link
Copy Markdown
Contributor

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:

  • A NOCI class following the PySCF CI interface, with NOCISD and NOCISDT and any excitation level through level=.
  • WickEngine and Determinant for individual matrix elements and dense H/S over any list of determinants.
  • C kernels (libnonorthwick) for real and complex orbitals, with AVX2/AVX-512 packed variants selected at run time and OpenMP.
  • Exact handling of zero-overlap and near-zero-overlap orbital pairs.
  • Unit tests against an FCI-space expansion of each determinant, and examples.

Short usage example:

from pyscf import nonorthogonal
mynoci = nonorthogonal.NOCISD(mol, [mf_rhf, mf_uhf1, mf_uhf2]).run()
mynoci = nonorthogonal.NOCI(mol, refs, level=3).run()  # any excitation level

Implementation

NOCI driver

NOCI(mol, references, level) builds every reference and its excitations up to level (default 0, the references only), evaluates H and S, and solves the generalised eigenproblem densely with lib.linalg_helper.safe_eigh. excitations() returns the determinants of one reference, and NOCISD and NOCISDT set level to 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

  • Reference pairs: the intermediates of each ordered pair of references are built once in Python with BLAS, after which each matrix element depends only on the excitation ranks, not on the basis size.
  • Excitations of different references: fixed-size kernels for up to quadruple excitations per side, with AVX2/AVX-512 packed variants, and a general evaluator for higher ranks and for pairs with zero-overlap orbitals.
  • Excitations of the same reference: Slater-Condon rules on occupation bit strings, adapted from PySCF's FCIpspace_h0tril_uhf to complex orbitals and up to 128 MOs.
  • Near-zero overlaps: pairs with small nonzero singular values are evaluated exactly from two well-conditioned corners per pair, avoiding the precision loss from 1/S_k terms.

C backend

The kernels are written once and instantiated for real and complex orbitals. They are built as libnonorthwick through the CMake configuration in pyscf/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.

pyscf.nonorthogonal.test.test_wicks: 9 tests passed
pyscf.nonorthogonal.test.test_noci:  7 tests passed

They can be run with:

python -m unittest pyscf.nonorthogonal.test.test_wicks
python -m unittest pyscf.nonorthogonal.test.test_noci

The examples in examples/nonorthogonal demonstrate:

  • Overlaps and matrix elements between determinants of different references.
  • NOCI, NOCISD and NOCISDT for H6 against FCI.

Performance

WickEngine.build_matrices for 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:

Threads Scalar AVX2 Speedup
1 19.1 s 12.3 s 1.56x
4 5.53 s 3.80 s 1.46x
16 2.45 s 1.98 s 1.24x

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_ovlp of msdft.noci provides 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 for msdft to use WickEngine at 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.

@jeanwsr
jeanwsr commented Oct 21, 2026
Copy link
Copy Markdown
Contributor

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?

Comment thread pyscf/nonorthogonal/noci.py Resolved
@MatthewRHermes MatthewRHermes added the enhancement New feature or request label Oct 21, 2026
@dy-cl
dy-cl commented Oct 21, 2026
Copy link
Copy Markdown
Contributor Author

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 noci-rs is that it would require a Rust toolchain and Python bindings to be added to pyscf-forge. There is also no simple interface for passing in AO integrals and reference orbitals and getting matrix elements in return, as it is intended to be an all-in-one software package for NOCI methods.

Using libgnme is probably more feasible, but would still be another external dependency, and the repository does not yet have the optimisations and bug fixes that my port here has (although I have opened PRs for these). Once those are merged, a wrapper around pygnme, the libgnme Python API, could potentially work.

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.

@dy-cl
dy-cl commented Oct 21, 2026
Copy link
Copy Markdown
Contributor Author

The CI failure was a name clash between pyscf/msdft/tests/test_noci.py and pyscf/nonorthogonal/test/test_noci.py, which stopped pytest collecting the tests. Hopefully fixed by renaming pyscf/nonorthogonal/test/test_noci.py → pyscf/nonorthogonal/test/test_nonorthogonal_noci.py.

@MatthewRHermes
MatthewRHermes commented Oct 21, 2026 •
Copy link
Copy Markdown
Collaborator

I built libnonorthwick with no compiler warnings on an Intel i5-8350U (AVX2, no AVX-512) with Python 3.12. All 16 tests pass in about 6 s and both examples run. I didn't re-derive the Wick algebra term by term; I relied on the brute-force FCI-space tests and my extra checks for that. The brute-force comparison in test_wicks.py is an excellent, independent check. Thank you for it, and for the quick turnaround on the interface: an sf-X2C UHF reference now reproduces its own e_tot on the diagonal to 4e-14, where 6003a18 was off by 5e-2.

Should fix

1. A complex Hamiltonian with real references silently loses its imaginary part. In WickEngine.build (wicks.py), the slab dtype is taken from the reference orbitals only. Passing a complex h1e (or eri) with real references writes complex intermediates into a real slab. NumPy then discards the imaginary part, with only a ComplexWarning. For H6/STO-3G NOCI(level=1), I added a 1e-2 imaginary antisymmetric part to h1e. H then differs by 2.5e-2 from the same calculation with the references cast to complex, and the real-reference H comes back float64. The fix is to take dtype from numpy.result_type over the orbitals, h1e and eri.

2. AVX2 kernels go untested on AVX-512 machines. NOWICKset_simd caps the level, and test_scalar_kernels caps it at 0. Every other test runs at the highest level the CPU supports. On a runner with AVX-512, which includes many cloud and CI hosts, the AVX2 kernels are never exercised, so an AVX2-only regression would pass CI. The reverse (no AVX-512 coverage on AVX2-only hosts) can't be avoided, but this direction can. Suggestion: run check under each level from 0 up to the native one, using subTest, and skip levels where NOWICKset_simd(level) returns a lower value than requested:

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 test_scalar_kernels.

Implementation: questions and optional improvements

  • Reuse. _coulomb/_exchange duplicate scf.hf.dot_eri_dm(eri, dm, hermi=0), which already handles complex density matrices with s1 integrals. The custom _ao2mo is justified, because ao2mo.incore is real-only and the four index sets are conjugated differently, but a one-line comment saying so would help the next reader.
  • Licensing. The description says noci-rs is "based upon that of libgnme". libgnme is MIT-licensed, copyright Hugh G. A. Burton. If any code (rather than only the algorithms) in noci-rs, and so in this port, derives from libgnme, the MIT terms require keeping its copyright and permission notice. Could you say which applies?
  • Duplicated layout constants. PAIRLEN, the block offsets and the scalar layout are defined both in nowick.h and in _wicks.py, and must be kept in sync by hand. A short comment in each file pointing to the other would help. So would a C function that returns NOWICK_PAIRLEN, checked at import.
  • GHF references give a cryptic error. A scf.GHF object passes _reference_orbitals, because it is an SCF and its mo_coeff is 2-D. It then fails at build time with ValueError: shapes (9,22) and (11,11) not aligned. Please reject anything other than RHF/ROHF/UHF in WickEngine.__init__ with a clear message.

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 hand

I ran these locally and they all pass. They are listed so you can decide which ones are worth keeping as tests.

  • The Hamiltonian taken from the SCF reference (new in 76eed87) is untested. The only test that touches the new arguments is build(ecore=0). A reference whose get_hcore differs from scf.hf.get_hcore(mol) would protect this. For example, scf.UHF(mol).x2c() should reproduce its own e_tot on the diagonal, which takes one line in test_scf_references. A related point for the docstring: with a density-fitted reference, the diagonal differs from mf.e_tot (by 5e-7 for OH/6-31G), because the exact int2e integrals are used.
  • Open-shell references are never tested. Every test system has nα = nβ, and both counts are odd (3, 3). I reused your _references/_dets/_brute_hs helpers on BeH2/STO-3G with nelec = (4, 2), (3, 2), (4, 3) and (4, 1). That covers every combination of per-spin parity. I used references with zero-overlap pairs in α only, β only, and both. H and S agree with brute force to 2e-13 for real and complex orbitals, through both build_matrices and matrix_elements(general=True). A test like this is cheap, and it would catch a realistic class of bug: an α count or stride used where the β one belongs, or a sign that depends on the parity of one spin's occupation. I'd add at least one odd-electron case, e.g. the (3, 2) cation.
  • More than 64 MOs. The same-parent Slater–Condon code uses two-word occupation strings, but no test has more than 10 MOs, so the second word is never touched. He/cc-pV5Z (Cartesian, 70 MOs) NOCISD matches ci.CISD to 4e-15, and the doubles into MOs 63 and 64 are continuous. That run takes 2.7 GB and 60 s, so I wouldn't put it in CI, but it may be worth recording somewhere.
  • Complex h1e with real references (point 1 above): once fixed, a short test comparing against complex-cast references would keep it fixed.

Tests and examples: optional / readability

  • test_near_zero_pairs: please wrap the four cases in self.subTest(sa=sa, sb=sb, phase=phase) so a failure says which one broke. I checked that this test really does protect the corner treatment: with _wicks.SINGULARTOL = 0 the four cases fail with H errors of 4e-8, 9e-2, 2e-6 and 4e-9 against the 1e-9 tolerance. The last (complex, phase 0.7) case fails by only a factor of 4, though. Singular values of 1e-4 or 1e-5 would give a much clearer margin.
  • test_noci.py:72: where does -2.8875402412 come from? If it was computed with noci-rs, or anything independent of this code, a comment saying so would make it a real cross-check rather than a regression pin.
  • 02-noci.py: printing the number of linearly independent states next to each determinant count would be informative. For H6/STO-3G that is 335 of 354 for NOCISD and 400 of 846 for NOCISDT, the full FCI dimension.
  • The README quick start uses uhf_a and uhf_b without defining them. A pointer to 02-noci.py for how to construct them would be enough.

PR context

pyscf/pyscf#1697 (a NOCI feature request) was closed with a pointer to the existing pyscf.msdft.noci in forge. That module's hf_det_ovlp already computes ⟨I|H|J⟩ between nonorthogonal reference determinants, and its own comments say that more than two zero singular values are handled only approximately. This PR adds a second public class named NOCI with different semantics. Please mention msdft.noci in the description and explain how the two relate. For what it's worth, on the H6 references from test_noci.py the two agree to 2e-15 in both H and S. So msdft could probably reuse WickEngine later, though that's a follow-up and not something for this PR.


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.

@dy-cl
dy-cl commented Oct 22, 2026
Copy link
Copy Markdown
Contributor Author

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 numpy.result_type over the orbitals, h1e and eri, rather than from the orbitals alone, with a new test to cover this, and test_scalar_kernels is replaced with test_simd_levels, which tests every level from scalar up to the highest that the hardware supports.

The duplication described is removed with the _coulomb and _exchange functions now calling scf.hf.dot_eri_dm, and _ao2mo has the clarifying comment. nowick.h and _wicks.py now refer to each other, and a new C function NOWICKlayout returns PAIRLEN, NSCAL, DHEAD and MAXMO, which _wicks.py checks at import. Passing a GHF reference now fails with an error saying it is not supported. As far as the license is concerned, although the current noci-rs implementation is largely different, early noci-rs contained code derived from libgnme, so I have added its MIT license notice to the _wicks.py header.

A new check in test_scf_references shows that an X2C UHF reference reproduces its own e_tot as expected, and the docstring and README mention the density fitting point. There is also now a test_open_shell with (3, 2) electrons that exercises both real and complex arithmetic, and a 70 MO He/cc-pV5Z check, documented in the README rather than run in CI, that matches ci.CISD to round-off. The complex h1e test is also added. Likewise, the four readability changes have been made.

Finally, I have edited the PR description to describe how it is d 8000 ifferentiated from msdft.

@MatthewRHermes
MatthewRHermes merged commit a89d966 into pyscf:master Oct 22, 2026
6 checks passed
MatthewRHermes added a commit to MatthewRHermes/pyscf-forge that referenced this pull request Oct 22, 2026
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>
@dy-cl
dy-cl deleted the nonorthogonalwicks branch October 23, 2026 09:54
sunqm pushed a commit that referenced this pull request Oct 31, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

0