"""BIPOLE-style periodic RKS driver in CRYSTAL's electrostatic gauge.
The DFT counterpart of :mod:`vibeqc.pbc_bipole`. Pure functionals use
the exact analytical-FT, G=0-dropped periodic Hartree J in the same
neutral-background convention as the GDF reference; hybrid functionals
retain the CRYSTAL-gauge Ewald split so the HF exchange correction can
share the native ``build_jk_2e_real_space`` component builder.
This driver keeps the same multi-k SCF scaffold as the RHF BIPOLE
driver: shared Ewald a across V_ne/E_nn/J^LR, analytic V_ne via
AO-pair Fourier transforms, real-space energy accounting, and
the full suite of convergence accelerators (DIIS, ODA, MOM,
level-shift schedule, damping).
"""
from __future__ import annotations
import warnings
from dataclasses import dataclass, field
from typing import List, Optional, Sequence, Tuple, Union
import numpy as np
from ._vibeqc_core import (
BasisSet,
BlochKMesh,
EwaldOptions,
Functional,
GridOptions,
InitialGuess,
LatticeMatrixSet,
LatticeSumOptions,
PeriodicKSOptions,
PeriodicSystem,
SCFIteration,
bloch_sum,
build_grid,
build_xc_periodic,
compute_kinetic_lattice,
compute_overlap_lattice,
direct_lattice_cells,
ewald_nuclear_repulsion,
make_lattice_matrix_set,
nuclear_repulsion_per_cell,
real_space_density_from_kpoints,
real_space_density_from_kpoints_fractional,
)
from .bipole_ext_el_pole import compute_ext_el_spheropole
from .guess import initial_density_closed_shell
from .level_shift_schedule import LevelShiftSchedule
from .mom import select_occupied_by_max_overlap as _mom_select
from .oda import compute_oda_lambda as _compute_oda_lambda
from .oda import oda_mix_densities as _oda_mix
from .pbc_bipole_common import (
PBCBipoleEnergyComponents,
_bloch_sum_blocks,
_compute_nuclear_lattice_ewald_reciprocal_ft,
_crystal_ewald_options,
_default_bipole_v_ne_grid_options,
_density_set_gamma_or_lattice,
_expand_ibz_kmesh_for_ewald_j,
_lattice_contract,
_zero_cross_cell_density,
prepare_bipole_lattice_options,
resolve_bipole_fock_symmetry,
warn_bipole_charged_cell,
warn_bipole_legacy_multik_gauge,
smearing_basin_warning,
)
from .pbc_bipole_fock import (
BipoleFockContext,
build_bipole_restricted_fock,
split_k_density_list,
)
from .periodic_grid import build_periodic_becke_grid
from .periodic_rhf_multi_k_ewald import (
_canonical_orthogonalizer_complex,
_damp_lattice_matrix,
_diag_in_orth_basis,
)
from .periodic_scf_accelerators import (
DynamicDamping,
MultiKPeriodicSCFAccelerator,
)
from .periodic_v_ne import compute_nuclear_lattice_dispatch
from .periodic_screened_exchange import resolve_periodic_exchange
from .progress import ProgressLogger, resolve_progress
from .scf_divergence import check_scf_divergence
from .smearing import (
SmearingOptions,
)
from .smearing import (
closed_shell_periodic_occupations as _closed_shell_periodic_occupations,
)
from .symmetry_integrals_reduced import (
compute_kinetic_lattice_reduced,
compute_nuclear_lattice_reduced,
compute_overlap_lattice_reduced,
)
__all__ = [
"PBCBipoleRKSResult",
"run_pbc_bipole_rks",
]
[docs]
@dataclass
class PBCBipoleRKSResult:
"""Result of :func:`run_pbc_bipole_rks`."""
energy: float
e_electronic: float
e_nuclear: float
e_xc: float
e_coulomb: float
e_hf_exchange: float
n_iter: int
converged: bool
mo_energies: List[np.ndarray]
mo_coeffs: List[np.ndarray]
fock: List[np.ndarray]
overlap: List[np.ndarray]
hcore: List[np.ndarray]
density: LatticeMatrixSet
scf_trace: List[SCFIteration] = field(default_factory=list)
e_ext_el_spheropole: Optional[float] = None
ewald_alpha_bohr_inv: Optional[float] = None
# Dudarev DFT+U contribution per unit cell (Hartree). 0 unless the
# caller passed ``dft_plus_u=[HubbardSite(...)]``.
e_dft_plus_u: float = 0.0
energy_components: List[PBCBipoleEnergyComponents] = field(
default_factory=list,
)
functional: str = ""
# Smearing diagnostics (zero when smearing_temperature == 0).
smearing_temperature: float = 0.0
fermi_level: float = 0.0
entropy: float = 0.0
free_energy: float = 0.0
occupations: List[np.ndarray] = field(default_factory=list)
# Gauge provenance (option (b)): True when the run used the
# corrected gauge (full-Bloch density, no spheropole, a_HF-scaled
# Ewald exchange split for hybrids).
exchange_ewald_split: bool = False
exchange_exxdiv: Optional[str] = None
# Non-None when finite-T smearing straddled the HOMO-LUMO gap and may
# have selected a near-metallic basin (ionic-Γ basin trap); carries
# the warning message. See smearing_basin_warning.
basin_warning: Optional[str] = None
# Cartesian k-points (bohr^-1) and weights this result spans, in the
# same order as the per-k ``mo_coeffs`` / ``mo_energies`` lists. Lets
# optional Gamma-only / single-k output writers locate Gamma instead of
# assuming the first k-point is Gamma. See PBCBipoleRHFResult.
kpoints_cart: Optional[np.ndarray] = None
kpoint_weights: Optional[np.ndarray] = None
@dataclass
class _PBCBipoleRKSFockBuild:
"""Internal Fock-build bundle for the BIPOLE RKS driver."""
f2e_real: LatticeMatrixSet
f_k_list: List[np.ndarray]
e_j_short_range: Optional[float] = None
e_j_long_range: Optional[float] = None
e_exchange: Optional[float] = None
e_j_multipole: Optional[float] = None
# k-space exchange correction (Ewald exchange split, a_HF-scaled):
# lives in F(k), so its energy must be added to the
# lattice-contracted E_2e by the caller.
e_2e_k_correction: float = 0.0
# XC energy of the SAME grid quadrature whose V_xc entered f_k_list.
# Consuming this instead of re-running build_xc_periodic keeps the
# iteration's V_xc and e_xc from one build (they used to come from
# two independent quadratures per iteration -- one discarded).
e_xc: Optional[float] = None
[docs]
def run_pbc_bipole_rks(
system: PeriodicSystem,
basis: BasisSet,
kmesh: BlochKMesh,
options=None,
*,
functional: Optional[str] = None,
linear_dep_threshold: float = 1e-7,
canonical_orth_normalize_diag_first: bool = True,
level_shift_schedule: Optional[LevelShiftSchedule] = None,
use_mom: bool = False,
use_oda: bool = False,
oda_trust_lambda_max: float = 1.0,
use_incremental_fock: bool = True,
use_ewald_j_split: Optional[bool] = None,
ewald_omega: Optional[float] = None,
ewald_precision: float = 1e-8,
v_ne_grid_options: Optional[GridOptions] = None,
use_multipole_far_field: bool = False,
multipole_l_max: int = 2,
use_exchange_ewald_split: Optional[bool] = None,
exchange_exxdiv: str = "ewald",
use_fock_symmetry: Optional[bool] = None,
use_fock_symmetry_reduce: bool = False,
sr_image_extent_bohr: Optional[float] = None,
progress: Union[bool, ProgressLogger, None] = None,
verbose: Optional[int] = None,
initial_density: Optional[Sequence[np.ndarray]] = None,
dft_plus_u: Optional[List["HubbardSite"]] = None,
bz_integration: Optional[str] = None,
) -> PBCBipoleRKSResult:
"""Multi-k closed-shell RKS via the CRYSTAL-gauge BIPOLE scaffold.
Parameters
----------
system, basis, kmesh
As in :func:`run_pbc_bipole_rhf`.
options
:class:`PeriodicKSOptions` or None for PBE defaults.
functional
XC functional name (overrides ``options.functional`` if given).
use_exchange_ewald_split, exchange_exxdiv
Exchange/gauge convention (option (b), 2026-06-11). ``None`` =
auto: the corrected gauge is ON at 3D Γ-only sampling under the
Ewald J split -- full-Bloch density (no Γ-locality projection,
which also fixes the XC grid density r(r): the projected
density dropped the cross-cell AO products), no EXT
EL-SPHEROPOLE term, and for hybrids (a_HF > 0) the Ewald
exchange split ``K = K_SR(erfc w) + K_LR(reciprocal K!=0) +
(ξ_M - pi/(Vw^2)).S.D.S`` scaled by a_HF. Pure functionals need
no exchange machinery -- the gauge change alone applies (and
the wasted full-Coulomb K traversal of the legacy path is
skipped). See :func:`run_pbc_bipole_rhf` for the full
convention notes. The corrected gauge is the default at BOTH
Γ and multi-k (Phase-5 flip 2026-06-13): at multi-k it adds the
q = k-k′ LR-exchange channels + BvK-supercell Madelung
correction (requires a Monkhorst-Pack mesh; an ad-hoc k-list
falls back to the legacy gauge under the auto default). Pass
``use_exchange_ewald_split=False`` for the legacy gauge.
bz_integration
``None`` / ``"smearing"`` use the existing Aufbau or
Fermi-Dirac occupation path. ``"gilat"`` selects the
parameter-free Gilat-Raubenheimer net at T = 0; it cannot be
combined with finite-temperature smearing.
All other parameters
As in :func:`run_pbc_bipole_rhf`.
Returns
-------
PBCBipoleRKSResult
"""
from ._vibeqc_core import PeriodicKSOptions as _PKSOpts
opts = options if options is not None else _PKSOpts()
if functional is not None:
opts.functional = str(functional)
if not getattr(opts, "functional", None):
opts.functional = "pbe"
smearing_T = float(getattr(opts, "smearing_temperature", 0.0))
if smearing_T < 0.0:
raise ValueError("run_pbc_bipole_rks: smearing_temperature must be >= 0")
if bz_integration is not None:
bz_integration = str(bz_integration).strip().lower()
if bz_integration not in ("smearing", "gilat"):
raise ValueError(
"run_pbc_bipole_rks: bz_integration must be None, "
f"'smearing', or 'gilat'; got {bz_integration!r}"
)
use_gilat = bz_integration == "gilat"
if use_gilat and smearing_T > 0.0:
raise NotImplementedError(
"run_pbc_bipole_rks: bz_integration='gilat' is a "
"sharp-Fermi-surface occupation backend and cannot be combined "
"with finite-temperature smearing."
)
use_fractional_occupations = smearing_T > 0.0 or use_gilat
func = Functional(opts.functional, 1) # spin-unpolarised
# CAM exchange assembly. alpha_hf is the FULL-RANGE exact-exchange
# fraction and drives the Ewald exchange-split machinery (xi_M,
# K_LR q-channels, K_corr). Screened hybrids (hse06) have c_full
# = 0 -- none of that machinery engages; their erfc short-range K
# is added inside build_bipole_restricted_fock (no seam, no
# far-field, per the CRYSTAL RSH treatment). LR-heavy RSH fails
# closed in the resolver.
exx = resolve_periodic_exchange(func, where="run_pbc_bipole_rks")
alpha_hf = float(exx.c_full)
fock_mixing_value = float(getattr(opts, "fock_mixing", 0.0))
if fock_mixing_value == 0.0 and alpha_hf < 1.0:
# CRYSTAL-style default FMIXING for pure DFT: 30% previous
# Fock matrix weight to damp SCF oscillations on tight
# ionic cells. Zero for HF (alpha_hf == 1.0).
fock_mixing_value = 0.30
if not (0.0 <= fock_mixing_value < 1.0):
raise ValueError(
f"run_pbc_bipole_rks: fock_mixing must be in [0, 1); "
f"got {fock_mixing_value}"
)
lat_opts: LatticeSumOptions = opts.lattice_opts
plog = resolve_progress(progress, verbose=verbose)
(
use_ewald_j_split,
use_ewald_j_split_auto,
lat_opts_2e,
lat_opts_1e,
) = prepare_bipole_lattice_options(system, lat_opts, use_ewald_j_split, plog)
plog.info(
f"PBC BIPOLE RKS (CRYSTAL-gauge) / cutoff {lat_opts.cutoff_bohr:.2f} bohr"
)
if exx.is_screened:
plog.info(
f" functional = {opts.functional}, screened exchange "
f"K = {exx.c_sr:g}*K_erfc(omega={exx.omega_screen:g} bohr^-1)"
)
else:
plog.info(
f" functional = {opts.functional}, hf_exchange_fraction = {alpha_hf}"
)
if use_gilat:
plog.info(" bz integration = Gilat-Raubenheimer sharp-Fermi net")
plog.info(
f" F^2e (J + V_xc{'+ K' if exx.needs_exchange else ''}) : "
f"{'EWALD_J_SPLIT' if use_ewald_j_split else lat_opts_2e.coulomb_method.name}"
)
n_elec = system.n_electrons()
if n_elec % 2 != 0:
raise ValueError(
f"run_pbc_bipole_rks: closed-shell RKS requires even electron "
f"count; got {n_elec}"
)
if system.multiplicity != 1:
raise ValueError(
f"run_pbc_bipole_rks: requires multiplicity=1; got {system.multiplicity}"
)
n_occ = n_elec // 2
_kmesh_ibz = kmesh
_ir_mapping = np.asarray(getattr(kmesh, "ir_mapping", []), dtype=int).reshape(-1)
k_points = list(_kmesh_ibz.kpoints)
weights = np.asarray(_kmesh_ibz.weights, dtype=float)
if use_ewald_j_split and _ir_mapping.size > 0:
# IBZ inputs run on the EXPANDED full mesh (correctness: the
# IBZ-native replication shortcut lacked the star AO rotations
# D(R.k) = P(R).D(k).P(R)ᵀ and broke non-trivial crystals -- MgO
# probe 2026-06-10, 8.25 Ha. See vibeqc.periodic_k_symmetry for
# the transport groundwork and pbc_bipole.py for the full note).
kmesh_full = _expand_ibz_kmesh_for_ewald_j(system, kmesh, plog)
if len(list(kmesh_full.kpoints)) > len(k_points):
kmesh = kmesh_full
k_points = list(kmesh.kpoints)
weights = np.asarray(kmesh.weights, dtype=float)
_ir_mapping = np.asarray([], dtype=int)
k_points_full = k_points
weights_full = weights
else:
k_points_full = k_points
weights_full = weights
n_k = len(k_points)
if n_k == 0:
raise ValueError("kmesh has no k-points")
if not np.isclose(weights.sum(), 1.0):
raise ValueError(f"kmesh.weights must sum to 1; got {weights.sum():.6f}")
plog.info(
f"k-mesh: {n_k} k-point{'s' if n_k != 1 else ''}, "
f"weights sum = {weights.sum():.4f}"
)
# ---- Exchange/gauge resolution (option (b), 2026-06-11) ----------
# Mirrors run_pbc_bipole_rhf: corrected gauge at 3D Γ under the J
# split (full-Bloch density, no spheropole; a_HF-scaled Ewald
# exchange split for hybrids). Multi-k: explicit opt-in runs the
# q!=0 LR-exchange channels (Phase 3); auto stays legacy pending
# certification.
if exchange_exxdiv not in ("ewald", "none"):
raise ValueError(
f"run_pbc_bipole_rks: exchange_exxdiv must be 'ewald' or "
f"'none'; got {exchange_exxdiv!r}"
)
_x_split_auto = use_exchange_ewald_split is None
exchange_split_active = (
bool(use_ewald_j_split) if _x_split_auto else bool(use_exchange_ewald_split)
)
if exchange_split_active and not use_ewald_j_split:
raise ValueError(
"run_pbc_bipole_rks: use_exchange_ewald_split=True requires "
"the Ewald J split (use_ewald_j_split=True)."
)
# Multi-k split (option (b) Phase 3): q-channel tables, the
# BvK-torus density fold, and the supercell Madelung correction
# all need the true Monkhorst-Pack dimensions; ad-hoc k-lists
# (mesh = (1,1,1) placeholders) are rejected.
_bvk_mesh: Optional[Tuple[int, int, int]] = None
if exchange_split_active and n_k > 1:
_mesh_attr = tuple(int(x) for x in getattr(kmesh, "mesh", (1, 1, 1)))
if int(np.prod(_mesh_attr)) != n_k:
if _x_split_auto:
plog.info(
" multi-k corrected exchange gauge needs a "
"Monkhorst-Pack mesh (BvK-torus fold + supercell ξ_M); "
"this ad-hoc k-list has no mesh metadata -> falling back "
"to the legacy gauge. Pass a monkhorst_pack(...) mesh "
"for the corrected gauge."
)
exchange_split_active = False
else:
raise ValueError(
"run_pbc_bipole_rks: the Ewald exchange split at multi-k "
"requires a Monkhorst-Pack BlochKMesh carrying its mesh "
f"dimensions (got mesh={_mesh_attr} for {n_k} k-points). "
"Build the mesh via monkhorst_pack(...); ad-hoc k-point "
"lists are not supported on the corrected gauge."
)
else:
_bvk_mesh = _mesh_attr
warn_bipole_legacy_multik_gauge(system, exchange_split_active, n_k, plog)
warn_bipole_charged_cell(system, plog)
_xi_madelung = 0.0
if exchange_split_active and exchange_exxdiv == "ewald" and alpha_hf > 0.0:
if n_k > 1:
from .bipole_fock_ewald import probe_charge_madelung_supercell
assert _bvk_mesh is not None
_xi_madelung = probe_charge_madelung_supercell(system, _bvk_mesh)
else:
from .bipole_fock_ewald import probe_charge_madelung
_xi_madelung = probe_charge_madelung(system)
if exchange_split_active:
plog.info(
" Gauge: corrected (full Bloch density, no spheropole"
+ (
f"; exchange split exxdiv={exchange_exxdiv}, "
f"a_HF={alpha_hf:g}"
+ (
f", ξ_M = {_xi_madelung:.6f} Ha"
if exchange_exxdiv == "ewald"
else ""
)
if alpha_hf > 0.0
else "; pure functional -- no HF exchange"
)
+ ")"
)
use_exact_ewald_j_for_pure_rks = bool(
use_ewald_j_split
and exchange_split_active
and alpha_hf == 0.0
and not use_multipole_far_field
)
exact_j_ke_cutoff = 200.0
exact_j_chunk_size = 512
if use_exact_ewald_j_for_pure_rks:
import os
exact_j_ke_cutoff = float(os.environ.get("VIBEQC_J_EWALD3D_KE", "200.0"))
exact_j_chunk_size = max(
1,
int(os.environ.get("VIBEQC_J_EWALD3D_CHUNK", "512")),
)
plog.info(
" Pure-RKS Hartree J: exact analytic-FT Ewald "
f"(G=0 dropped, ke_cutoff={exact_j_ke_cutoff:g} Ha)"
)
# ---- Shared Ewald state (one a across V_ne / E_nn / J_LR) -------
ewald_options_1e: Optional[EwaldOptions] = None
omega_used: Optional[float] = None
ewald_cell_volume: Optional[float] = None
ewald_k_max: Optional[float] = None
if system.dim == 3:
from .bipole_ext_el_pole import (
crystal_default_ewald_alpha,
crystal_ewald_reciprocal_cutoff,
)
V_cell = float(abs(np.linalg.det(np.asarray(system.lattice, dtype=float))))
ewald_cell_volume = V_cell
omega_used = (
float(ewald_omega)
if ewald_omega is not None
else crystal_default_ewald_alpha(V_cell)
)
ewald_k_max = crystal_ewald_reciprocal_cutoff(V_cell)
ewald_options_1e = _crystal_ewald_options(
lat_opts_1e,
alpha_bohr_inv=omega_used,
tolerance=float(ewald_precision),
recip_cutoff_bohr_inv=ewald_k_max,
)
# ---- DFT grid ----------------------------------------------------
# Wrapped in plog.stage so a job that stalls here (periodic Becke
# partitioning over image cells can be minutes on dense/large cells)
# shows ``[dft_grid]`` as its last live line instead of going dark --
# the pre-SCF setup that walltimed P13 MgO BIPOLE/XC left no marker
# localizing which stage was slow.
with plog.stage(
"dft_grid",
detail=(
"periodic Becke" if getattr(opts, "use_periodic_becke", False)
else "molecular grid on unit cell"
),
):
if getattr(opts, "use_periodic_becke", False):
grid = build_periodic_becke_grid(
system,
grid_options=opts.grid,
image_radius_bohr=float(
getattr(opts, "becke_image_radius_bohr", 10.0)
),
)
else:
grid = build_grid(system.unit_cell_molecule(), opts.grid)
# ---- Real-space one-electron integrals ---------------------------
with plog.stage(
"integrals_lattice",
detail=f"S/T/V at cutoff {lat_opts.cutoff_bohr:.2f} bohr",
):
_use_sym = bool(getattr(getattr(system, "symmetry", None), "operations", None))
if _use_sym:
ops = system.symmetry.operations
cells = direct_lattice_cells(system, lat_opts_2e.cutoff_bohr)
plog.info(
f"symmetry-reduced integrals: {len(ops)} operators, "
f"{len(cells)} lattice cells"
)
_, S_blocks = compute_overlap_lattice_reduced(
basis, system, lat_opts_2e, ops
)
nbf = basis.nbasis
S_lat = make_lattice_matrix_set(
nbf, cells, [np.asarray(b, dtype=float) for b in S_blocks]
)
_, T_blocks = compute_kinetic_lattice_reduced(
basis, system, lat_opts_2e, ops
)
T_lat = make_lattice_matrix_set(
nbf, cells, [np.asarray(b, dtype=float) for b in T_blocks]
)
else:
S_lat = compute_overlap_lattice(basis, system, lat_opts_2e)
T_lat = compute_kinetic_lattice(basis, system, lat_opts_2e)
v_ne_lr_cache = None
if (
system.dim == 3
and ewald_options_1e is not None
and v_ne_grid_options is None
):
V_lat, v_ne_lr_cache = _compute_nuclear_lattice_ewald_reciprocal_ft(
basis,
system,
lat_opts_1e,
ewald_options_1e,
S_lat,
precision=ewald_precision,
K_max=ewald_k_max,
)
else:
v_ne_grid = (
v_ne_grid_options
if v_ne_grid_options is not None
else (_default_bipole_v_ne_grid_options() if system.dim == 3 else None)
)
V_lat = compute_nuclear_lattice_dispatch(
basis,
system,
lat_opts_1e,
grid_options=v_ne_grid,
ewald_options=ewald_options_1e,
)
cells = list(S_lat.cells)
plog.info(f"n_cells in lattice sum = {len(cells)}")
# Lattice-fold convergence guard + wide density list under the
# corrected gauge -- same rationale as run_pbc_bipole_rhf (the
# corrected gauge contracts full Bloch folds; the C++ builder's
# traversal forms |b-a| differences up to 2x the cutoff and skips
# P(h) lookups beyond the density's own list).
if exchange_split_active:
from .pbc_bipole_common import s_fold_truncation_drift
# Recomputes S over an extended cutoff (per-k at multi-k) to gauge
# lattice-fold truncation -- silent and O(n_k x Ncells x Nbf^2), so
# bracket it. This is on the pure-RKS/LDA corrected-gauge path (the
# P13 failing row), where the J/K reciprocal caches are skipped.
with plog.stage(
"s_fold_drift",
detail=f"S recompute at extended cutoff (n_k={n_k})",
):
_s_drift = s_fold_truncation_drift(
basis,
system,
lat_opts_2e,
k_points=(k_points if n_k > 1 else None),
)
_s_label = (
"S(k) fold truncation (max over mesh)"
if n_k > 1
else "S(Γ) fold truncation"
)
if _s_drift > 1e-2:
plog.info(
f" WARNING: {_s_label} {_s_drift:.1e} at cutoff "
f"{lat_opts_2e.cutoff_bohr:.1f} bohr -- lattice sums badly "
f"under-converged for this basis's AO tails; absolute "
f"energies UNRELIABLE (spurious SCF states possible). "
f"Increase lattice_opts.cutoff_bohr until the drift falls "
f"below 1e-4."
)
elif _s_drift > 1e-4:
plog.info(
f" note: {_s_label} {_s_drift:.1e} at cutoff "
f"{lat_opts_2e.cutoff_bohr:.1f} bohr -- expect "
f"~{_s_drift:.0e}-scale absolute-energy truncation"
)
else:
plog.info(f" {_s_label}: {_s_drift:.1e} (converged)")
cells_density = list(
direct_lattice_cells(system, 2.0 * float(lat_opts_2e.cutoff_bohr))
)
plog.info(
f" density cell list: {len(cells_density)} cells "
f"(2x cutoff -- resolves every P(b-a) difference)"
)
else:
cells_density = cells
# ---- Per-k S(k), Hcore(k), X(k) ---------------------------------
from .linear_dependence import (
check_overlap_matrix,
format_linear_dependence_report,
raise_if_severe,
scf_preflight_overlap_check,
)
S_k_list: List[np.ndarray] = []
Hcore_k_list: List[np.ndarray] = []
X_k_list: List[np.ndarray] = []
overlap_reports = []
for k_idx, k in enumerate(k_points):
k_arr = np.asarray(k, dtype=float).reshape(3)
S_k = np.asarray(bloch_sum(S_lat, k_arr))
T_k = np.asarray(bloch_sum(T_lat, k_arr))
V_k = np.asarray(bloch_sum(V_lat, k_arr))
H_k = T_k + V_k
S_k = 0.5 * (S_k + S_k.conj().T)
H_k = 0.5 * (H_k + H_k.conj().T)
overlap_label = f"S(k={k_idx}, k_cart={k_arr.round(4).tolist()})"
if n_k <= 16:
report = scf_preflight_overlap_check(
S_k,
plog=plog,
label=overlap_label,
basis=basis,
)
else:
report = check_overlap_matrix(
S_k,
basis=basis,
label=overlap_label,
)
if report.severity != "ok":
prefix = {
"warn": "WARN",
"error": "ERROR",
"critical": "CRITICAL",
}[report.severity]
plog.info(
f"[{prefix}] overlap [{overlap_label}]: "
f"nbf={report.n_basis}, "
f"min eig={report.min_eigenvalue:+.2e}, "
f"cond={report.condition_number:.2e}"
)
plog.write_raw(format_linear_dependence_report(report))
raise_if_severe(report)
X_k, n_kept = _canonical_orthogonalizer_complex(
S_k,
linear_dep_threshold,
normalize_diag_first=canonical_orth_normalize_diag_first,
)
overlap_reports.append(report)
if n_occ > n_kept:
raise RuntimeError(
f"run_pbc_bipole_rks: canonical orth at k={k_idx} "
f"dropped too many directions (n_occ={n_occ}, "
f"n_kept={n_kept})"
)
S_k_list.append(S_k)
Hcore_k_list.append(H_k)
X_k_list.append(X_k)
# ---- Nuclear repulsion -------------------------------------------
if ewald_options_1e is not None:
e_nuc = float(ewald_nuclear_repulsion(system, ewald_options_1e))
else:
e_nuc = float(nuclear_repulsion_per_cell(system, lat_opts_1e))
plog.info(f"E_nuc per cell = {e_nuc:+.10f} Ha")
# ---- Initial guess -----------------------------------------------
C_per_k: List[np.ndarray] = []
eps_per_k: List[np.ndarray] = []
for H_k, X_k in zip(Hcore_k_list, X_k_list):
C_k, eps_k = _diag_in_orth_basis(H_k, X_k)
C_per_k.append(C_k.astype(complex))
eps_per_k.append(eps_k)
n_occ_per_k = [n_occ] * n_k
n_electrons_per_cell = float(n_elec)
def _occupations_from_eps(
eps_per_k_local: Sequence[np.ndarray],
) -> Tuple[List[np.ndarray], float, float]:
if use_gilat:
from .bz_integration import gilat_occupations_for_kmesh
occ_gr, ef_gr = gilat_occupations_for_kmesh(
system,
kmesh,
eps_per_k_local,
n_electrons_per_cell,
spin_degeneracy=2.0,
)
return occ_gr, float(ef_gr), 0.0
return _closed_shell_periodic_occupations(
eps_per_k_local,
weights,
n_electrons_per_cell,
n_occ,
smearing_T,
)
occ_per_k, fermi_level, entropy = _occupations_from_eps(eps_per_k)
# Per-k -> real-space density fold over the wide (2x-cutoff) cell list
# is O(n_k x Ncells x Nbf^2) and silent; a prime multi-k cost for the
# LDA (2,2,2) row, so bracket it for localization.
with plog.stage(
"initial_density_fold",
detail=f"per-k SAD/Hcore -> real space over {len(cells_density)} cells",
):
if not use_fractional_occupations:
D_real = real_space_density_from_kpoints(
C_per_k,
n_occ_per_k,
kmesh,
cells_density,
)
else:
D_real = real_space_density_from_kpoints_fractional(
C_per_k,
occ_per_k,
kmesh,
cells_density,
)
if not exchange_split_active:
_zero_cross_cell_density(D_real, basis.nbasis, n_k)
# Caller-supplied warm-start density takes precedence over the
# SAD/Hcore guess engine. Block ordering matches the canonical
# ``direct_lattice_cells(kmesh)`` ordering -- same contract as the
# RHF driver. Used by the NEB driver for within-image density
# warm-start for periodic NEB.
if initial_density is not None:
blocks_in = list(initial_density)
if len(blocks_in) != len(D_real.cells):
raise ValueError(
f"run_pbc_bipole_rks: initial_density has "
f"{len(blocks_in)} blocks; expected {len(D_real.cells)}"
)
for g_idx, block in enumerate(blocks_in):
D_real.set_block(g_idx, np.asarray(block, dtype=float))
plog.info("initial guess: caller-supplied density (warm-start)")
initial_density_is_local = True
density_from_c_per_k = False
else:
guess = getattr(opts, "initial_guess", InitialGuess.HCORE)
D_engine = initial_density_closed_shell(
system.unit_cell_molecule(),
basis,
n_occ,
guess,
is_periodic=True,
periodic_system=system,
lattice_opts=lat_opts_2e,
# READ restart (Γ-only): prior g=0 cell density (pre-resolved from
# read_from, or read + projected from read_path). Ignored unless READ.
read_density=getattr(opts, "read_density", None),
read_path=getattr(opts, "read_path", ""),
)
if D_engine is not None:
# --- Multi-k cross-cell density fix (v0.14.0) -------------------
# For n_k > 1 the per-k HCORE diagonalisation at line 619 already
# gave C_per_k that vary with k, so D_real from the per-k fold
# (line 640) carries physically correct P(g!=0) blocks that restore
# the image-cell AO overlap on the DFT grid (∫rdr -> N_elec ≈ 20
# instead of ~18.95). Without this fix, P(g!=0) = 0 on the first
# iteration makes r(r) systematically ~5 % too low on dense
# crystals (MgO, NaCl, ...), the XC potential V_xc is too weak,
# and the SCF converges ~400 mHa above the correct stationary
# point -- functional-independent (LDA / PBE / r^2SCAN tested).
#
# For multi-k we keep the per-k density in full (g=0 + g!=0) rather
# than injecting just the g!=0 blocks from the fold while keeping
# SAD at g=0 -- the mixed density is not idempotent under the Bloch
# fold and the inconsistent cross-cell charge causes Fock-overshoot
# at iteration 2. The per-k HCORE g=0 block is a slightly worse
# guess than SAD but the benefit of correct cross-cell r(r)
# dominates on dense crystals (the SCF descends correctly from
# iteration 1 instead of moving upward).
#
# Γ-only and n_k == 1 are unaffected -- P(g!=0) = 0 is physically
# correct there. Tracked by the parity ladder:
# examples/regression/crystal_parity/parity_mgo_{svwn,pbe,r2scan}_sto3g.py
# ---------------------------------------------------------------
if n_k > 1:
# Multi-k: keep the full per-k density (with proper P(g!=0)).
# Replacing only g=0 with SAD while keeping HCORE g!=0 blocks
# produces an inconsistent density set -- the mixed g=0 and
# g!=0 blocks are not idempotent under the Bloch fold and
# cause iteration-2 Fock overshoot. Using the per-k density
# in full (including its g=0 block) gives a slightly worse
# initial home-cell guess but the correct cross-cell charge
# and idempotency mean the SCF descends monotonically from
# iteration 1.
plog.info(
f"initial guess: {guess.name} (multi-k: per-k density "
f"with Hcore-diag cross-cell blocks -- ∫rdr restored)"
)
# D_real already carries the per-k density; skip the overwrite.
else:
plog.info(f"initial guess: {guess.name} (g=0 density from GuessEngine)")
for g_idx in range(len(D_real.cells)):
if (D_real.cells[g_idx].index == np.array([0, 0, 0])).all():
D_real.set_block(g_idx, D_engine)
else:
D_real.set_block(
g_idx,
np.zeros_like(D_engine, dtype=float),
)
else:
plog.info(f"initial guess: {guess.name} (Hcore-diag per k)")
initial_density_is_local = D_engine is not None
density_from_c_per_k = not initial_density_is_local
D_real_prev: Optional[LatticeMatrixSet] = None
# ---- SCF aids ----------------------------------------------------
damping = float(opts.damping)
damper: Optional[DynamicDamping] = None
if bool(getattr(opts, "dynamic_damping", False)):
damper = DynamicDamping(
initial_alpha=damping,
alpha_min=float(getattr(opts, "dynamic_damping_min", 0.0)),
alpha_max=float(getattr(opts, "dynamic_damping_max", 0.95)),
)
use_diis = bool(opts.use_diis)
diis_start_iter = int(opts.diis_start_iter)
accel: Optional[MultiKPeriodicSCFAccelerator] = (
MultiKPeriodicSCFAccelerator(opts) if use_diis else None
)
level_shift_static = float(getattr(opts, "level_shift", 0.0))
if level_shift_schedule is not None and not isinstance(
level_shift_schedule,
LevelShiftSchedule,
):
raise TypeError(
f"level_shift_schedule must be LevelShiftSchedule; "
f"got {type(level_shift_schedule).__name__}"
)
# CRYSTAL-style FMIXING (same convention as RHF BIPOLE driver).
# Value resolved above in the options setup; log it here near the
# SCF-loop preamble.
if fock_mixing_value != 0.0:
plog.info(
f"fock mixing: CRYSTAL FMIXING "
f"{100.0 * fock_mixing_value:.1f}% "
"(previous Fock matrix weight)"
)
F_k_prev_mixed: Optional[List[np.ndarray]] = None
if use_mom:
plog.info("MOM: ON")
C_prev_occ_per_k: Optional[List[np.ndarray]] = None
if use_oda and use_diis:
raise ValueError("use_oda and use_diis are mutually exclusive")
if use_oda:
plog.info(f"ODA: ON (trust l_max = {oda_trust_lambda_max})")
# ---- Ewald J-split cache -----------------------------------------
j_lr_cache = v_ne_lr_cache
if use_ewald_j_split and not use_exact_ewald_j_for_pure_rks:
if system.dim != 3:
raise ValueError("use_ewald_j_split requires dim=3")
if n_k > 1 and _ir_mapping.size == 0:
uniform_w = 1.0 / float(n_k)
if not np.allclose(weights, uniform_w, atol=1e-9):
raise ValueError(
"use_ewald_j_split at multi-k requires uniform "
"full-mesh weights or IBZ-reduced mesh with ir_mapping"
)
from .bipole_fock_ewald import _build_j_long_range_cache
assert omega_used is not None
cells_r_cart_arr = np.array(
[np.asarray(c.r_cart, dtype=float) for c in cells],
dtype=float,
)
if j_lr_cache is None:
# The reciprocal-space Ewald long-range J kernel precompute is
# one of the heaviest silent pre-SCF stages (can be many
# minutes on a tight lattice / large K_max). Bracket it so a
# stalled job shows ``[j_lr_cache]`` as its last live line.
with plog.stage(
"j_lr_cache",
detail=f"Ewald long-range J kernel (K_max={ewald_k_max} bohr^-1)",
):
j_lr_cache = _build_j_long_range_cache(
basis,
system,
cells_r_cart_arr,
omega_used,
ewald_precision,
K_max=ewald_k_max,
)
# Multi-k split: per-(k,k′) q-channel tables for the LR exchange
# (hybrids only -- pure functionals carry no HF exchange). Shares
# the J^LR cache's Ewald w and K_max envelope.
x_lr_cache = None
if exchange_split_active and n_k > 1 and alpha_hf > 0.0:
from .bipole_fock_ewald import build_k_exchange_long_range_cache
assert j_lr_cache is not None and ewald_k_max is not None
# Per-(k,k') q-channel exchange tables: O(n_k^2) channels, the
# heaviest multi-k hybrid setup stage -- bracket for localization.
with plog.stage(
"k_lr_cache",
detail=f"{n_k} q-channels, K_max={ewald_k_max} bohr^-1",
):
x_lr_cache = build_k_exchange_long_range_cache(
basis,
system,
j_lr_cache,
K_max=ewald_k_max,
)
plog.info(
f" K^LR q-channels: {n_k} distinct q = k-k′ shifts on the "
f"shared K_max = {ewald_k_max:.2f} bohr⁻¹ envelope "
f"(a_HF = {alpha_hf:g})"
)
# Incremental/differential J_SR(+K_SR) accumulator (opt-in; see
# run_pbc_bipole_rhf). One accumulator on the total density: hybrids
# build J_SR+K_SR (build_jk), pure functionals build J_SR only
# (build_fock, K=None in the shim). Corrected gauge + DIIS only.
incremental_jk = None
if use_incremental_fock:
if exchange_split_active and not use_oda:
from .bipole_fock_ewald import IncrementalJK
incremental_jk = IncrementalJK()
plog.info(
" incremental Fock (differential J_SR/K_SR via ΔD "
"density-envelope screening): ON"
)
else:
plog.info(
" incremental Fock requested but inactive "
"(needs the corrected gauge + DIIS, not ODA)"
)
def _build_fock_for_density(
density: LatticeMatrixSet,
*,
coeffs_for_rho: Optional[Sequence[np.ndarray]],
use_incremental: bool = True,
) -> _PBCBipoleRKSFockBuild:
"""Build F^2e(g), add V_xc, and assemble F(k)."""
fb = build_bipole_restricted_fock(
_fock_ctx,
density,
coeffs_for_rho=coeffs_for_rho,
alpha_hf=alpha_hf,
exchange_assembly=exx,
use_incremental=use_incremental,
)
f2e_real = fb.f2e_real
K_corr_per_k = fb.k_corr_per_k
# ---- Build XC potential on the DFT grid ----------------------
D_xc_set = _density_set_gamma_or_lattice(S_lat, density)
xc_result = build_xc_periodic(
basis,
system,
grid,
func,
D_xc_set,
lat_opts_2e,
)
# ---- Assemble per-k Fock matrices ----------------------------
f_k_list: List[np.ndarray] = []
for k_idx, k in enumerate(k_points):
k_arr = np.asarray(k, dtype=float)
F2e_k = _bloch_sum_blocks(
f2e_real.blocks,
f2e_real.cells,
k_arr,
)
Vxc_k = np.asarray(bloch_sum(xc_result.V_xc, k_arr))
F_k = F2e_k + Vxc_k + np.asarray(Hcore_k_list[k_idx], dtype=complex)
if K_corr_per_k is not None:
# Ewald exchange split: a_HF.(K_LR + G=0) per k (a
# single Γ entry at n_k = 1).
F_k = F_k - 0.5 * K_corr_per_k[k_idx]
F_k = 0.5 * (F_k + F_k.conj().T)
f_k_list.append(F_k)
return _PBCBipoleRKSFockBuild(
f2e_real=f2e_real,
f_k_list=f_k_list,
e_j_short_range=fb.e_j_short_range,
e_j_long_range=fb.e_j_long_range,
e_exchange=fb.e_exchange,
e_j_multipole=fb.e_j_multipole,
e_2e_k_correction=fb.e_2e_k_correction,
e_xc=float(xc_result.e_xc),
)
# ---- Multipole far-field config (resolve once before SCF loop) -----
from .bipole_fock_multipole import ( # noqa: E402
BipoleMultipoleConfig,
resolve_multipole_config,
)
if exchange_split_active and use_multipole_far_field:
raise NotImplementedError(
"run_pbc_bipole_rks: the multipole far-field J replacement has "
"not been re-validated under the corrected gauge. Pass "
"use_exchange_ewald_split=False to combine it with the legacy "
"gauge, or omit use_multipole_far_field."
)
_mp_config = resolve_multipole_config(
system,
basis,
lat_opts_2e,
user_enable=(False if exchange_split_active else use_multipole_far_field),
multipole_l_max=multipole_l_max,
)
if _mp_config.enabled:
plog.info(
f" BIPOLE multipole far-field: ENABLED "
f"(L_max={_mp_config.L_max}, R_bipole={_mp_config.R_bipole:.1f} bohr, "
f"n_cells={len(_mp_config.cache.cells) if _mp_config.cache else 0})"
)
else:
plog.info(
f" BIPOLE multipole far-field: off "
f"(R_bipole={_mp_config.R_bipole:.1f} bohr, "
f"cutoff={lat_opts_2e.cutoff_bohr:.1f} bohr)"
)
# SYM3b Fock symmetry enforcement is OPT-IN ONLY -- rationale
# (boundary truncation asymmetry) lives on the shared resolver.
_fock_sym_map, _rep_cell_indices = resolve_bipole_fock_symmetry(
system,
basis,
lat_opts_2e,
use_fock_symmetry,
use_fock_symmetry_reduce,
plog,
)
# ---- Shared restricted Fock-build context (M2 unification) ----------
# The RKS wrapper adds V_xc after the shared two-electron builder returns.
# _build_fock_for_density (above) references this via late binding; it is
# only called from the SCF loop below, after this point.
_fock_ctx = BipoleFockContext(
basis=basis,
system=system,
lat_opts_2e=lat_opts_2e,
use_ewald_j_split=use_ewald_j_split,
exchange_split_active=exchange_split_active,
n_k=n_k,
omega_used=omega_used,
ewald_precision=ewald_precision,
ewald_cell_volume=ewald_cell_volume,
n_elec=n_elec,
xi_madelung=_xi_madelung,
j_lr_cache=j_lr_cache,
x_lr_cache=x_lr_cache,
incremental_jk=incremental_jk,
rep_cell_indices=_rep_cell_indices,
fock_sym_map=_fock_sym_map,
mp_config=_mp_config,
s_lat=S_lat,
s_k_list=S_k_list,
k_points=k_points,
weights=weights,
k_points_full=k_points_full,
weights_full=weights_full,
ir_mapping=_ir_mapping,
bvk_mesh=_bvk_mesh,
n_occ=n_occ,
plog=plog,
sr_image_extent=sr_image_extent_bohr,
exact_j_for_pure_rks=use_exact_ewald_j_for_pure_rks,
exact_j_ke_cutoff=exact_j_ke_cutoff,
exact_j_chunk_size=exact_j_chunk_size,
)
def _split_k_density_list(density: LatticeMatrixSet) -> List[np.ndarray]:
return split_k_density_list(_fock_ctx, density)
plog.banner("SCF (PBC BIPOLE RKS, direct-space)")
plog.info(" iter energy (Ha) dE ||[F,DS]|| DIIS")
scf_trace: List[SCFIteration] = []
energy_components: List[PBCBipoleEnergyComponents] = []
E_prev = 0.0
F_k_list: List[np.ndarray] = [np.zeros_like(H) for H in Hcore_k_list]
E_elec = 0.0
e_xc = 0.0
e_dft_plus_u = 0.0
converged = False
iter_idx = 0
# ---- DFT+U setup (closed-shell BIPOLE RKS +U) ------------------------
dft_plus_u_sites_cxx: List = []
dft_plus_u_ao_groups: List[List[int]] = []
if dft_plus_u:
from ._vibeqc_core import _HubbardSiteCxx
from .dft_plus_u import ao_group_indices
ao_groups_map = ao_group_indices(basis)
for site in dft_plus_u:
key = (site.atom_index, site.l)
if key not in ao_groups_map:
raise ValueError(
f"run_pbc_bipole_rks: HubbardSite{key} has no AOs "
f"in the basis. Available channels: "
f"{sorted(ao_groups_map.keys())}"
)
dft_plus_u_sites_cxx.append(
_HubbardSiteCxx(site.atom_index, site.l, site.U_eff_hartree)
)
dft_plus_u_ao_groups.append(ao_groups_map[key])
for iter_idx in range(1, int(opts.max_iter) + 1):
if damper is not None:
damping = damper.alpha
diis_active = use_diis and iter_idx >= diis_start_iter
D_used = D_real
if iter_idx > 1 and damping > 0.0 and not diis_active:
D_used = _damp_lattice_matrix(D_real, D_real_prev, damping)
d_used_is_damped = iter_idx > 1 and damping > 0.0 and not diis_active
d_used_from_coeffs = (
density_from_c_per_k
and not (initial_density_is_local and iter_idx == 1)
and not d_used_is_damped
)
fock_build = _build_fock_for_density(
D_used,
coeffs_for_rho=(C_per_k if d_used_from_coeffs else None),
)
F2e_real = fock_build.f2e_real
F_k_list = fock_build.f_k_list
# ---- DFT+U: per-spin per-k Fock contribution (closed-shell).
# Same pattern as run_pbc_bipole_rhf -- closed-shell uses
# P_s = P_total/2 and E_U_total = 2 x E_s.
e_dft_plus_u = 0.0
if dft_plus_u_sites_cxx:
from ._vibeqc_core import (
_compute_dft_plus_u_multi_k_per_spin_cxx,
)
P_split_k_for_u: Optional[List[np.ndarray]] = None
if exchange_split_active:
# Unprojected Bloch fold: S_g over the full cell list
# overcounts -- BvK representative instead (home block
# at Γ; exact torus fold at multi-k).
P_split_k_for_u = _split_k_density_list(D_used)
P_sigma_k_for_U: List[np.ndarray] = []
for k_idx in range(n_k):
if P_split_k_for_u is not None:
P_k = P_split_k_for_u[k_idx]
else:
k_arr = np.asarray(k_points[k_idx], dtype=float)
P_k = _bloch_sum_blocks(
D_used.blocks,
D_used.cells,
k_arr,
)
P_sigma = 0.25 * (P_k + P_k.conj().T)
P_sigma_k_for_U.append(P_sigma)
E_sigma, V_AO = _compute_dft_plus_u_multi_k_per_spin_cxx(
dft_plus_u_sites_cxx,
dft_plus_u_ao_groups,
S_k_list,
P_sigma_k_for_U,
list(weights),
)
e_dft_plus_u = 2.0 * float(E_sigma)
V_AO_cmplx = np.asarray(V_AO, dtype=complex)
for k_idx in range(n_k):
S_k = S_k_list[k_idx]
F_k_list[k_idx] = F_k_list[k_idx] + (S_k @ V_AO_cmplx @ S_k)
F_k_list[k_idx] = 0.5 * (F_k_list[k_idx] + F_k_list[k_idx].conj().T)
# ---- XC energy -----------------------------------------------
# From the SAME quadrature that produced this iteration's V_xc
# (inside _build_fock_for_density on D_used) -- the loop used to
# run a second, redundant build_xc_periodic here every iteration
# just to extract e_xc.
assert fock_build.e_xc is not None
e_xc = float(fock_build.e_xc)
# ---- Energy --------------------------------------------------
E_kin = _lattice_contract(D_used, T_lat, operator_name="T")
E_ne = _lattice_contract(D_used, V_lat, operator_name="V_ne")
E_2e = (
0.5
* _lattice_contract(
D_used,
F2e_real,
operator_name="F2e",
)
# k-space exchange correction (Ewald exchange split).
+ fock_build.e_2e_k_correction
)
E_elec = E_kin + E_ne + E_2e + e_xc
grad_norm_sum = 0.0
error_k_list: List[np.ndarray] = []
D_k_list: List[np.ndarray] = []
D_k_split_guess: Optional[List[np.ndarray]] = None
if exchange_split_active and initial_density_is_local and iter_idx == 1:
# BvK representative for local AND Bloch warm-start storage
# (home block at Γ; exact torus fold at multi-k -- S_g over
# the unprojected fold would overcount).
D_k_split_guess = _split_k_density_list(D_used)
for idx in range(n_k):
if initial_density_is_local and iter_idx == 1:
if D_k_split_guess is not None:
D_k = D_k_split_guess[idx]
else:
k_arr = np.asarray(k_points[idx], dtype=float)
D_k = _bloch_sum_blocks(
D_used.blocks,
D_used.cells,
k_arr,
)
D_k = 0.5 * (D_k + D_k.conj().T)
else:
C_k = C_per_k[idx]
if not use_fractional_occupations:
C_occ = C_k[:, :n_occ]
D_k = 2.0 * (C_occ @ C_occ.conj().T)
else:
# Fractional-occupation density: D(k) = S_i n_i C_i C_i+
occ = np.asarray(occ_per_k[idx], dtype=float)
C_full = np.asarray(C_k, dtype=np.complex128)
D_k = (C_full * occ[None, :]) @ C_full.conj().T
D_k_list.append(D_k)
F_k = F_k_list[idx]
w = float(weights[idx])
S_k = S_k_list[idx]
FDS = F_k @ D_k @ S_k
grad = FDS - FDS.conj().T
error_k_list.append(grad)
grad_norm_sum += w * float(np.linalg.norm(grad))
E_total = float(E_elec) + e_nuc + e_dft_plus_u
# EXT EL-SPHEROPOLE -- a 3D-Ewald-gauge correction, identically
# zero in the direct (non-Ewald) gauge used for dim<3, and
# OMITTED under the corrected gauge (double-count -- see the
# RHF driver note).
if system.dim == 3 and not exchange_split_active:
E_sphero = compute_ext_el_spheropole(D_used, basis, system, lat_opts)
E_total += E_sphero
else:
E_sphero = None
free_energy = E_total - smearing_T * entropy
dE = free_energy - E_prev if iter_idx > 1 else 0.0
check_scf_divergence(
"run_pbc_bipole_rks",
iter_idx,
free_energy,
grad_norm_sum,
dE,
)
scf_trace.append(
SCFIteration(
iter=iter_idx,
energy=float(free_energy),
delta_e=float(dE if iter_idx > 1 else 0.0),
grad_norm=float(grad_norm_sum),
diis_subspace=(accel.subspace_size if accel is not None else 0),
)
)
plog.iteration(
iter_idx,
energy=float(free_energy),
dE=float(dE if iter_idx > 1 else 0.0),
grad=float(grad_norm_sum),
diis=(accel.subspace_size if accel is not None else 0),
)
energy_components.append(
PBCBipoleEnergyComponents(
iter=int(iter_idx),
e_total=float(E_total),
e_electronic=float(E_elec),
e_kinetic=float(E_kin),
e_nuclear_attraction=float(E_ne),
e_two_electron=float(E_2e),
e_nuclear_repulsion=float(e_nuc),
e_j_short_range=fock_build.e_j_short_range,
e_j_long_range=fock_build.e_j_long_range,
e_exchange=fock_build.e_exchange,
e_ext_el_spheropole=E_sphero,
)
)
plog.energy_decomposition(
iter_idx,
E_kin=float(E_kin),
E_ne=float(E_ne),
E_2e=float(E_2e),
E_elec=float(E_elec),
E_nuc=float(e_nuc),
)
converged = (
iter_idx > 1
and abs(dE) < float(opts.conv_tol_energy)
and grad_norm_sum < float(opts.conv_tol_grad)
)
# SCF-accelerator extrapolation. Full
# {DIIS, KDIIS, EDIIS, EDIIS_DIIS, ADIIS} family wired here;
# bridged modes route through the M2e stacked-real-block bridge
# (see ``per_k_to_stacked_real_blocks`` in
# ``periodic_scf_accelerators.py``).
if accel is not None:
if exchange_split_active:
# Unprojected fold: BvK representative per k (home
# block at Γ; exact torus fold at multi-k).
density_k_list = _split_k_density_list(D_used)
else:
density_k_list = [
_bloch_sum_blocks(D_used.blocks, D_used.cells, np.asarray(k))
for k in k_points
]
F_ex_list = accel.extrapolate_rhf(
F_k_list,
error_k_list=error_k_list,
density_k_list=density_k_list,
energy=free_energy,
mo_coeffs_k_list=C_per_k,
n_occ=n_occ,
weights=list(weights),
cells=cells,
kpoints=list(k_points),
)
# On the converged iteration, diagonalise the *physical* Fock
# F(D) -- not the extrapolated one -- so the final orbitals/
# density stay on the converged fixed point. A near-machine-
# zero DIIS error history (SCF nailing the solution in one
# step) makes the Pulay B-matrix singular and its extrapolated
# Fock garbage. See the RHF twin in pbc_bipole.py and
# tests/test_pbc_bipole_diis_converged_basin.py.
if diis_active and not converged:
F_k_list = F_ex_list
# --- FMIXING (CRYSTAL-style, after DIIS, before level-shift)
# Skipped on the converged iteration (see DIIS note above).
if fock_mixing_value != 0.0 and not converged:
if F_k_prev_mixed is not None:
F_mixed_list: List[np.ndarray] = []
for idx in range(n_k):
F_mixed = (1.0 - fock_mixing_value) * F_k_list[
idx
] + fock_mixing_value * F_k_prev_mixed[idx]
F_mixed = 0.5 * (F_mixed + F_mixed.conj().T)
F_mixed_list.append(F_mixed)
F_k_list = F_mixed_list
F_k_prev_mixed = [np.asarray(F, dtype=complex).copy() for F in F_k_list]
# Level shift
if level_shift_schedule is not None:
level_shift_b = level_shift_schedule.at(iter_idx)
else:
level_shift_b = level_shift_static
if level_shift_b != 0.0 and not converged:
F_for_diag: List[np.ndarray] = []
for idx in range(n_k):
D_k = D_k_list[idx]
S_k = S_k_list[idx]
F_shift = (
F_k_list[idx]
+ level_shift_b * S_k
- (level_shift_b / 2.0) * (S_k @ D_k @ S_k)
)
F_shift = 0.5 * (F_shift + F_shift.conj().T)
F_for_diag.append(F_shift)
else:
F_for_diag = F_k_list
# Diagonalise
new_C_per_k = []
new_eps_per_k = []
for idx in range(n_k):
C_k, eps_k = _diag_in_orth_basis(
F_for_diag[idx],
X_k_list[idx],
)
new_C_per_k.append(C_k)
new_eps_per_k.append(eps_k)
# MOM
if use_mom and C_prev_occ_per_k is not None:
for idx in range(n_k):
C_k = new_C_per_k[idx]
eps_k = new_eps_per_k[idx]
S_k = S_k_list[idx]
sel = _mom_select(
C_k,
S_k,
C_prev_occ_per_k[idx],
n_occ,
eps_new=eps_k,
)
n_kept_idx = C_k.shape[1]
virt_mask = np.ones(n_kept_idx, dtype=bool)
virt_mask[sel] = False
virt_sel = np.where(virt_mask)[0]
virt_sel = virt_sel[np.argsort(np.real(eps_k[virt_sel]))]
order = np.concatenate([sel, virt_sel])
new_C_per_k[idx] = C_k[:, order]
new_eps_per_k[idx] = eps_k[order]
C_per_k = new_C_per_k
eps_per_k = new_eps_per_k
occ_per_k, fermi_level, entropy = _occupations_from_eps(eps_per_k)
if not use_fractional_occupations:
D_real_new = real_space_density_from_kpoints(
C_per_k,
[n_occ] * n_k,
kmesh,
cells_density,
)
else:
D_real_new = real_space_density_from_kpoints_fractional(
C_per_k,
occ_per_k,
kmesh,
cells_density,
)
# Corrected gauge: the full Bloch fold IS the density the
# builders need (see run_pbc_bipole_rhf); legacy keeps the
# Γ-locality projection.
if not exchange_split_active:
_zero_cross_cell_density(D_real_new, basis.nbasis, n_k)
# ODA
if use_oda:
fock_naive = _build_fock_for_density(
D_real_new,
coeffs_for_rho=C_per_k,
use_incremental=False, # off the per-iter ΔD chain
)
oda_step = _compute_oda_lambda(
D_used,
D_real_new,
F_k_list,
fock_naive.f_k_list,
[np.asarray(k) for k in k_points],
weights,
trust_lambda_max=oda_trust_lambda_max,
)
_oda_mix(D_used, D_real_new, oda_step.lam)
D_real_prev = D_real
D_real = D_used
density_from_c_per_k = oda_step.lam == 1.0
plog.info(f" ODA: l = {oda_step.lam:.4f}")
else:
D_real_prev = D_used
D_real = D_real_new
density_from_c_per_k = True
if use_mom:
C_prev_occ_per_k = [
np.asarray(C_per_k[idx][:, :n_occ]).copy() for idx in range(n_k)
]
if damper is not None:
damper.update(free_energy)
E_prev = free_energy
if converged:
break
plog.converged(n_iter=iter_idx, energy=E_total, converged=converged)
# ---- Ionic-Γ basin-health diagnostic (smearing straddle) -----------
# Surface (don't bury, Sec.7) the case where finite-T smearing washes
# out a small (often minimal-basis-underestimated) gap and selects a
# near-metallic basin hundreds of mHa off the physical solution.
basin_warning = smearing_basin_warning(
smearing_T,
[(eps_per_k, occ_per_k, n_occ, 2.0)],
entropy,
"run_pbc_bipole_rks",
)
if basin_warning is not None:
plog.info(" WARNING: " + basin_warning)
warnings.warn(basin_warning, UserWarning, stacklevel=2)
# ---- Post-loop: recompute energy on final density for consistency
if converged:
_fb = _build_fock_for_density(
D_real, coeffs_for_rho=C_per_k, use_incremental=False
)
D_xc_set = _density_set_gamma_or_lattice(S_lat, D_real)
_xc = build_xc_periodic(
basis,
system,
grid,
func,
D_xc_set,
lat_opts,
)
E_kin_f = _lattice_contract(D_real, T_lat, operator_name="T")
E_ne_f = _lattice_contract(D_real, V_lat, operator_name="V_ne")
E_2e_f = (
0.5 * _lattice_contract(D_real, _fb.f2e_real, operator_name="F2e")
+ _fb.e_2e_k_correction
)
E_elec = E_kin_f + E_ne_f + E_2e_f + float(_xc.e_xc)
E_total = float(E_elec) + e_nuc + e_dft_plus_u
# Fresh E_total doesn't include spheropole -- add it (3D only; the
# term is zero in the direct gauge used for dim<3, and omitted
# under the corrected gauge).
if system.dim == 3 and not exchange_split_active:
E_sphero_final = compute_ext_el_spheropole(D_real, basis, system, lat_opts)
E_total += E_sphero_final
else:
E_sphero_final = None
else:
E_sphero_final = energy_components[-1].e_ext_el_spheropole
free_energy_final = E_total - smearing_T * entropy
return PBCBipoleRKSResult(
energy=float(E_total),
e_electronic=float(E_elec),
e_nuclear=e_nuc,
e_ext_el_spheropole=E_sphero_final,
e_xc=float(e_xc),
e_coulomb=float(E_2e),
e_hf_exchange=float(fock_build.e_exchange or 0.0),
n_iter=iter_idx,
converged=converged,
mo_energies=eps_per_k,
mo_coeffs=C_per_k,
fock=F_k_list,
overlap=S_k_list,
hcore=Hcore_k_list,
density=D_real,
scf_trace=scf_trace,
ewald_alpha_bohr_inv=omega_used,
e_dft_plus_u=float(e_dft_plus_u),
energy_components=energy_components,
functional=str(opts.functional),
smearing_temperature=smearing_T,
fermi_level=float(fermi_level),
entropy=float(entropy),
free_energy=float(free_energy_final),
occupations=[np.asarray(o, dtype=float) for o in occ_per_k],
exchange_ewald_split=bool(exchange_split_active),
exchange_exxdiv=(exchange_exxdiv if exchange_split_active else None),
basin_warning=basin_warning,
kpoints_cart=np.asarray(k_points, dtype=float).reshape(-1, 3),
kpoint_weights=np.asarray(weights, dtype=float).reshape(-1),
)