diff --git a/CHANGELOG.md b/CHANGELOG.md index 7781c895..446e83fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,15 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht ### Fixed +- **MO symmetry labels no longer depend on the LAPACK build.** On a + geometry symmetric only to within the detection tolerance, a split + degenerate pair (e.g. an NH3 e level) could be labelled "a2" on one + platform and "e" on another, because PySCF's `symmetrize_space` rebuilt + each irrep from an arbitrary basis. Each near-degenerate cluster of + orbitals (within 5 mHa) is now rotated onto symmetry-pure combinations + before labelling, and C3v labels are refused (Cs labels kept) if they + would contain more a1, a2 or e levels than the AO basis has SALCs of that + irrep. The 90% symmetry-purity check on orbitals now actually applies. - **Results Viewer (pre-release audit, VA.1–VA.12)** — the History + Analysis viewer (desktop installer and browser build, neither of which has PySCF): - Frequency results show their saved thermochemistry instead of a red diff --git a/quantui/symmetry.py b/quantui/symmetry.py index ae81aab6..347bbe8f 100644 --- a/quantui/symmetry.py +++ b/quantui/symmetry.py @@ -481,6 +481,12 @@ def _numbered_linear(raw: Sequence[str]) -> List[str]: #: 0.4 mHa), so 1e-4 Ha was too tight. _C3V_E_PAIR_TOL = 5e-3 +#: Orbitals whose energies chain together within this gap (Hartree) form +#: one near-degenerate cluster, which is rotated onto symmetry-pure +#: combinations before labelling (:func:`_unmix_clusters`). The same window +#: as the C3v pairing, so both halves of any pair it accepts were unmixed. +_MO_CLUSTER_TOL = _C3V_E_PAIR_TOL + def _c3v_from_cs(raw: Sequence[str], mo_energy: Sequence[float]) -> Optional[List[str]]: """Cs labels of a C3v molecule → C3v labels (a1, a2, e) via degeneracy. @@ -529,6 +535,113 @@ def gap(i: int) -> Optional[float]: return out +def _irrep_components(mol: Any, s: Any, coeff: Any) -> List[Any]: + """Per irrep Γ, ``Y_Γ`` with ``|Y_Γ[:, i]|²`` the weight of orbital i in Γ. + + ``Y_Γ = L⁻¹ Σ_Γᵀ S C``, where ``Σ_Γ`` are the irrep's SALCs and + ``L Lᵀ = Σ_Γᵀ S Σ_Γ``. Linear in the columns of *coeff*, so rotating + orbitals rotates the matching columns of every ``Y_Γ``. + """ + import numpy as np + + out = [] + for so in mol.symm_orb: + chol = np.linalg.cholesky(so.T @ s @ so) + out.append(np.linalg.solve(chol, so.T @ s @ coeff)) + return out + + +def _unmix_clusters(ys: List[Any], mo_energy: Any, tol: float) -> None: + """Rotate each near-degenerate cluster of orbitals onto irrep-pure ones. + + A pair split by less than *tol* (e.g. a C3v e level on a geometry + symmetric only to within the detection tolerance) is an arbitrary, + LAPACK-dependent mixture of its two irreps. Within each cluster this + diagonalizes ``Σ_Γ γ·P_Γ`` (one Hermitian matrix, so the result stays + orthonormal and each eigenvector sits in one irrep Γ), then + diagonalizes the orbital energies inside each irrep's block so the + rotated orbitals keep an energy order. Applied to *ys* in place + (see :func:`_irrep_components`); labels then do not depend on how the + cluster was mixed. + """ + import numpy as np + + e = np.asarray(mo_energy, dtype=float) + order = np.argsort(e, kind="stable") + breaks: Any = np.nonzero(np.diff(e[order]) >= tol)[0] + 1 + for idx in np.split(order, breaks): + if len(idx) < 2: + continue + w = [y[:, idx].T @ y[:, idx] for y in ys] + _, v = np.linalg.eigh(sum(g * wg for g, wg in enumerate(w))) + weights = np.array([np.einsum("ik,ij,jk->k", v, wg, v) for wg in w]) + owner = weights.argmax(axis=0) + cols, energies = [], [] + for g in np.unique(owner): + vg = v[:, owner == g] + eg, r = np.linalg.eigh(vg.T @ (e[idx][:, None] * vg)) + cols.append(vg @ r) + energies.append(eg) + u = np.hstack(cols)[:, np.argsort(np.concatenate(energies), kind="stable")] + for y in ys: + y[:, idx] = y[:, idx] @ u + + +def _c3_shell_character(ang: int, cart: bool) -> int: + """Trace of a 120° rotation on one shell of angular momentum *ang*.""" + # Spherical l: sin((2l+1)π/3) / sin(π/3) = 1, 0, -1 for l ≡ 0, 1, 2 (mod 3). + # A Cartesian shell spans l ⊕ (l-2) ⊕ ... + ls = range(ang % 2, ang + 1, 2) if cart else (ang,) + return sum((1, 0, -1)[k % 3] for k in ls) + + +def _c3v_salc_counts(mol: Any, tol_bohr: float) -> Optional[dict]: + """``{"a1", "a2", "e"}`` counts of C3v SALCs in *mol*'s AO basis. + + From the characters of the AO representation: χ(E) = nao, χ(σv) from + the A′/A″ split of PySCF's Cs SALCs, and χ(C3) from the atoms on the C3 + axis (only they map onto themselves). ``None`` when the axis cannot be + found or the counts do not come out as non-negative integers. + """ + import numpy as np + + group, orig, axes = _detect_full(mol._atom, tol_bohr) + if group != "C3v": + return None + axis = np.asarray(axes, dtype=float)[2] + rel = mol.atom_coords() - np.asarray(orig, dtype=float) + off_axis = np.linalg.norm(rel - np.outer(rel @ axis, axis), axis=1) + on_axis = set(np.nonzero(off_axis < tol_bohr)[0].tolist()) + chi_c3 = sum( + mol.bas_nctr(b) * _c3_shell_character(mol.bas_angular(b), bool(mol.cart)) + for b in range(mol.nbas) + if mol.bas_atom(b) in on_axis + ) + sizes = {str(n): so.shape[1] for n, so in zip(mol.irrep_name, mol.symm_orb)} + if set(sizes) != {"A'", 'A"'}: + return None + chi_sigma = sizes["A'"] - sizes['A"'] + nao = int(mol.nao) + num = { + "a1": nao + 2 * chi_c3 + 3 * chi_sigma, + "a2": nao + 2 * chi_c3 - 3 * chi_sigma, + "e": 2 * nao - 2 * chi_c3, + } + if any(v < 0 or v % 6 for v in num.values()): + return None + return {k: v // 6 for k, v in num.items()} + + +def _c3v_counts_fit(labels: Sequence[str], counts: Optional[dict]) -> bool: + """No more distinct a1 / a2 / e levels in *labels* than SALCs allow.""" + if counts is None: + return True + return all( + len({lab for lab in labels if lab.endswith(name)}) <= n + for name, n in counts.items() + ) + + def label_mo_irreps( mol_atom: Any, basis: str, @@ -585,20 +698,25 @@ def label_mo_irreps( if mol is None or mol.groupname == "C1" or mol.nao != coeff.shape[0]: return None s = mol.intor_symmetric("int1e_ovlp") + energies = None + if mo_energy is not None and len(mo_energy) == coeff.shape[1]: + energies = [float(e) for e in mo_energy] # Degenerate partners (e.g. the E pair of NH3) come out of an - # unsymmetrized SCF as arbitrary mixtures; rotate each degenerate - # space onto symmetry-pure combinations first. - coeff = symm.symmetrize_space(mol, coeff, s=s, check=False) - raw = symm.label_orb_symm( - mol, mol.irrep_name, mol.symm_orb, coeff, s=s, check=False - ) + # unsymmetrized SCF as arbitrary mixtures. With energies, rotate + # each near-degenerate cluster onto symmetry-pure combinations. + # Without, fall back to PySCF's symmetrize_space; it rebuilds each + # irrep from an arbitrary (LAPACK-dependent) basis and matches it + # greedily, which mislabelled a split NH3 e pair as A″/A″ on one + # CI platform only, so it is not used when energies are known. + if energies is None: + coeff = symm.symmetrize_space(mol, coeff, s=s, check=False) + ys = _irrep_components(mol, s, coeff) + if energies is not None: + _unmix_clusters(ys, energies, _MO_CLUSTER_TOL) + weights = np.array([np.einsum("ki,ki->i", y, y) for y in ys]) + raw = [str(mol.irrep_name[g]) for g in weights.argmax(axis=0)] # Purity: weight of each orbital in its assigned irrep's subspace. - purity = [] - for i, name in enumerate(raw): - so = mol.symm_orb[list(mol.irrep_name).index(name)] - proj = so.T @ s @ coeff[:, i] - sso = so.T @ s @ so - purity.append(float(proj @ np.linalg.solve(sso, proj))) + purity = weights.max(axis=0).tolist() if min(purity) < min_purity: logger.debug( "MO irreps skipped: min purity %.3f < %.2f", min(purity), min_purity @@ -610,8 +728,16 @@ def label_mo_irreps( labels = _numbered_linear(names) else: c3v = None - if top == "C3v" and group == "Cs" and mo_energy is not None: - c3v = _c3v_from_cs(names, [float(e) for e in mo_energy]) + if top == "C3v" and group == "Cs" and energies is not None: + c3v = _c3v_from_cs(names, energies) + # Belt and braces: never more a2 (or a1, e) levels than the + # AO basis has SALCs of that irrep (NH3 in 6-31G has no a2). + if c3v is not None: + tol_bohr = tolerance_angstrom * BOHR_PER_ANGSTROM + counts = _c3v_salc_counts(mol, tol_bohr) + if not _c3v_counts_fit(c3v, counts): + logger.debug("C3v labels exceed SALC counts %s", counts) + c3v = None if c3v is not None: labels, group = c3v, "C3v" else: diff --git a/tests/test_audit_low_data.py b/tests/test_audit_low_data.py index 9e2d7f0f..699ef63a 100644 --- a/tests/test_audit_low_data.py +++ b/tests/test_audit_low_data.py @@ -89,6 +89,17 @@ def _group_leader_with_child(pids): # pragma: no cover - runs in a fork child time.sleep(60) +def _running(pid): + """True while *pid* exists and is not a zombie. The process can vanish + between any two /proc reads (ENOENT, or ESRCH from a stat file whose + process was just reaped); either way it is gone.""" + try: + with open(f"/proc/{pid}/stat") as fh: + return "Z" not in fh.read().split()[2] + except OSError: + return False + + @pytest.mark.skipif(not hasattr(os, "killpg"), reason="POSIX process groups") def test_terminate_worker_tree_kills_grandchildren(): """Stop/Skip/timeout must not orphan the worker's pool processes.""" @@ -105,12 +116,7 @@ def test_terminate_worker_tree_kills_grandchildren(): assert not worker.is_alive() deadline = time.time() + 10 while time.time() < deadline: - alive = [ - k - for k in kids - if os.path.exists(f"/proc/{k}") - and "Z" not in open(f"/proc/{k}/stat").read().split()[2] - ] + alive = [k for k in kids if _running(k)] if not alive: break time.sleep(0.1) diff --git a/tests/test_symmetry.py b/tests/test_symmetry.py index c5cfec00..44cb7bf5 100644 --- a/tests/test_symmetry.py +++ b/tests/test_symmetry.py @@ -25,6 +25,31 @@ [-0.4689, -0.8121, -0.27], ], ) +# NH3 off C3v by ~0.0006 Å (still C3v within 0.01 Å): its e pairs split +# by 0.2-0.8 mHa. +NOISY_NH3 = ( + ["N", "H", "H", "H"], + [ + [0.00016, -0.00028, 0.09945], + [0.93712, 0.00038, -0.2695], + [-0.46877, 0.81238, -0.26995], + [-0.46838, -0.81172, -0.2706], + ], +) +# Staggered CH3CF3 (C3v), with a genuine occupied a2 F lone-pair level. +CH3CF3 = ( + ["C", "C", "F", "F", "F", "H", "H", "H"], + [ + [0, 0, 0], + [0, 0, 1.53], + [1.26033, 0.0, 2.0138], + [-0.63017, 1.09148, 2.0138], + [-0.63017, -1.09148, 2.0138], + [0.51213, 0.88704, -0.3728], + [-1.02426, 0.0, -0.3728], + [0.51213, -0.88704, -0.3728], + ], +) CO2 = (["O", "C", "O"], [[0, 0, -1.16], [0, 0, 0], [0, 0, 1.16]]) CHFCLBR = ( ["C", "H", "F", "Cl", "Br"], @@ -177,46 +202,140 @@ def test_noisy_ammonia_pairs_split_e_levels(self): (audit GEOM-5).""" from quantui.symmetry import label_mo_irreps - noisy = ( - NH3[0], - [ - [0.00016, -0.00028, 0.09945], - [0.93712, 0.00038, -0.2695], - [-0.46877, 0.81238, -0.26995], - [-0.46838, -0.81172, -0.2706], - ], - ) - mol_atom, mf = self._scf(noisy, "6-31g") + mol_atom, mf = self._scf(NOISY_NH3, "6-31g") ir = label_mo_irreps(mol_atom, "6-31g", mf.mo_coeff, mo_energy=mf.mo_energy) assert ir.group == "C3v" - # The occupied labels are the defect (an occupied "1a2" instead of - # 1e). Higher virtuals on this deliberately distorted geometry - # include a pair split by ~0.8 mHa whose eigenvectors are an - # arbitrary, LAPACK-dependent mixture; asserting on those failed on - # one CI platform only (py3.9 runner) while passing on 3.9/3.11 - # locally, so they are not pinned here. assert ir.labels[:5] == ["1a1", "2a1", "1e", "1e", "3a1"] - assert not any("a2" in lab for lab in ir.labels[:5]) + # NH3 in 6-31G has no A2 SALCs at all. A virtual pair split by + # ~0.8 mHa once came out "a2" on one CI runner only, when + # PySCF's symmetrize_space picked a LAPACK-dependent basis. + assert not any("a2" in lab for lab in ir.labels) + + @pytest.mark.parametrize("theta", [0.3, 0.7854, 1.2, 1.5708, 2.5]) + def test_mixed_near_degenerate_pairs_keep_labels(self, theta): + """Rotating the two orbitals of every split e pair into each other + (any mixture an SCF on another platform could return) leaves the + labels unchanged.""" + import numpy as np + + from quantui.symmetry import label_mo_irreps + + mol_atom, mf = self._scf(NOISY_NH3, "6-31g") + e, c = mf.mo_energy, mf.mo_coeff + ref = label_mo_irreps(mol_atom, "6-31g", c, mo_energy=e).labels + pairs = [i for i in range(len(e) - 1) if e[i + 1] - e[i] < 2e-3] + # 1e, 2e, 3e and the 4e virtual pair split by ~0.8 mHa. + assert len(pairs) == 4 and pairs[-1] > int((mf.mo_occ > 0).sum()) + mixed = c.copy() + cos, sin = np.cos(theta), np.sin(theta) + for i in pairs: + mixed[:, i] = cos * c[:, i] + sin * c[:, i + 1] + mixed[:, i + 1] = -sin * c[:, i] + cos * c[:, i + 1] + ir = label_mo_irreps(mol_atom, "6-31g", mixed, mo_energy=e) + assert ir.group == "C3v" + assert ir.labels == ref + assert not any("a2" in lab for lab in ir.labels) + + def test_labels_independent_of_degenerate_eigenbasis(self, monkeypatch): + """Emulate other LAPACK builds: every eigh call returns a random + (seeded) basis inside each degenerate eigenspace, which is equally + valid. The labels must not change and never include an a2 (the + old symmetrize_space path gave "a2" for ~1 seed in 5).""" + import numpy as np + import scipy.linalg + + from quantui.symmetry import label_mo_irreps + + mol_atom, mf = self._scf(NOISY_NH3, "6-31g") + args = (mol_atom, "6-31g", mf.mo_coeff) + ref = label_mo_irreps(*args, mo_energy=mf.mo_energy).labels + rng = np.random.default_rng(1) + + def scrambled(orig): + def eigh(*a, **k): + w, v = orig(*a, **k) + v = np.array(v, copy=True) + start = 0 + for stop in range(1, len(w) + 1): + if stop == len(w) or abs(w[stop] - w[start]) > 1e-6: + if stop - start > 1: + q, _ = np.linalg.qr( + rng.standard_normal((stop - start,) * 2) + ) + v[:, start:stop] = v[:, start:stop] @ q + start = stop + return w, v + + return eigh + + monkeypatch.setattr(np.linalg, "eigh", scrambled(np.linalg.eigh)) + monkeypatch.setattr(scipy.linalg, "eigh", scrambled(scipy.linalg.eigh)) + for _ in range(20): + ir = label_mo_irreps(*args, mo_energy=mf.mo_energy) + assert ir.labels == ref + assert not any("a2" in lab for lab in ir.labels) + + def test_labels_do_not_use_symmetrize_space_with_energies(self, monkeypatch): + """symmetrize_space rebuilds each irrep from an arbitrary, + LAPACK-dependent basis; with energies the labelling must not + depend on it.""" + from pyscf import symm + + from quantui.symmetry import label_mo_irreps + + mol_atom, mf = self._scf(NOISY_NH3, "6-31g") + + def boom(*a, **k): + raise AssertionError("symmetrize_space called") + + monkeypatch.setattr(symm, "symmetrize_space", boom) + ir = label_mo_irreps(mol_atom, "6-31g", mf.mo_coeff, mo_energy=mf.mo_energy) + assert ir is not None and ir.group == "C3v" + + def test_c3v_salc_counts(self): + """A2 SALC counts from the AO characters: none for NH3/6-31G, + five in cc-pVTZ (H d and N f functions), one for CH3CF3/STO-3G.""" + from pyscf import gto + + from quantui.symmetry import ( + BOHR_PER_ANGSTROM, + _c3v_salc_counts, + detection_tolerance, + ) + + tol = 0.01 * BOHR_PER_ANGSTROM + + def counts(geom, basis, cart=False): + with detection_tolerance(0.01): + mol = gto.M( + atom=list(zip(*geom)), + basis=basis, + cart=cart, + symmetry=True, + verbose=0, + ) + return _c3v_salc_counts(mol, tol) + + assert counts(NOISY_NH3, "6-31g") == {"a1": 7, "a2": 0, "e": 4} + assert counts(NOISY_NH3, "6-31g*", cart=True) == {"a1": 9, "a2": 0, "e": 6} + assert counts(NH3, "cc-pvtz") == {"a1": 21, "a2": 5, "e": 23} + assert counts(CH3CF3, "sto-3g") == {"a1": 11, "a2": 1, "e": 8} + + def test_c3v_labels_capped_by_salc_counts(self): + from quantui.symmetry import _c3v_counts_fit + + counts = {"a1": 7, "a2": 0, "e": 4} + good = ["1a1", "2a1", "1e", "1e", "3a1", "4a1", "2e", "2e"] + assert _c3v_counts_fit(good, counts) + assert not _c3v_counts_fit(good[:6] + ["1a2", "2a2"], counts) + assert _c3v_counts_fit(good, None) def test_genuine_a2_keeps_c3v_labels(self): """CH3CF3 (staggered, C3v) has an occupied a2 F lone-pair combination with no A' level near it: labelled 1a2, not dropped to Cs.""" from quantui.symmetry import label_mo_irreps - geom = ( - ["C", "C", "F", "F", "F", "H", "H", "H"], - [ - [0, 0, 0], - [0, 0, 1.53], - [1.26033, 0.0, 2.0138], - [-0.63017, 1.09148, 2.0138], - [-0.63017, -1.09148, 2.0138], - [0.51213, 0.88704, -0.3728], - [-1.02426, 0.0, -0.3728], - [0.51213, -0.88704, -0.3728], - ], - ) - mol_atom, mf = self._scf(geom) + mol_atom, mf = self._scf(CH3CF3) ir = label_mo_irreps(mol_atom, "sto-3g", mf.mo_coeff, mo_energy=mf.mo_energy) assert ir.group == "C3v" n_occ = int((mf.mo_occ > 0).sum())