Basic calculations

What to do when the SCF does not converge

Compare the SCF convergence of a difficult Al(111) slab with different SCF settings, and learn the order in which to try the settings when the SCF does not converge.

Category
Basic calculations
APIs used
scf_stylemix_betamix_nstoredmix_precondnoisy_precondmax_iterdegaussscf_converged
Script
scf_troubleshooting.py

When the SCF calculation does not converge, review the preset scf_style and the parameters of the density mixing. Here an 8-layer Al(111) slab with a vacuum region (32 atoms) is calculated with several settings, and the convergence histories are read from the log files and compared.

Order of remedies

  1. Choose the preset for the system: scf_style="bulk" for bulk crystals, "magnetic" for magnetic materials and "molecule" for molecules. For a system that fits none of them, such as a metal slab, try several presets and compare how the SCF behaves. The values of each preset are listed in Controlling and monitoring the SCF.
  2. noisy_precond="damping" for inorganic materials: damps the high-frequency noise of the kinetic potential. It is on by default in the "bulk" and "magnetic" presets.
  3. Set the mixing parameters individually: a smaller mixing ratio mix_beta makes the change of the density per iteration smaller, which can help the SCF to converge. Another option is a longer mixing history mix_nstored: the "magnetic" and "molecule" presets use 4, and 32, the value of "bulk", can be used instead. A further option is to switch off the Thomas-Fermi preconditioner of the "bulk" preset with mix_precond=None. For metal slabs the SCF needs fewer iterations without it (as used in Planar-averaged electrostatic potential and work function).
  4. Increase degauss for insulators: a smearing width of 1.0 - 2.0 eV often makes the SCF converge, especially for wide-gap insulators. Since it changes the total energy, use the same degauss for all calculations whose energies are compared (see Fermi energy and smearing).
scf_troubleshooting.pyDownload
"""
Advance/OF-DFT example: what to do when the SCF calculation does not converge.

The same Al(111) slab is calculated with several sets of SCF parameters, and the
convergence histories are compared.

Copyright (C) 2026 AdvanceSoft Corporation, All rights reserved.
"""

import re

import matplotlib.pyplot as plt
from ase.build import fcc111
from ase.units import Hartree

from aofdft.calculator import AOFDFTCalculator

VPS_DIR = "path/to/DFT_DATA19_AS/VPS"  # edit these two paths for your environment
PAO_DIR = "path/to/DFT_DATA19_AS/PAO"

# a metal slab with a vacuum region (8 layers, 2x2 in the surface plane, 32 atoms):
# none of the three presets is made for this kind of system
slab = fcc111("Al", size=(2, 2, 8), a=4.05, vacuum=10.0)

SETTINGS = {
    "bulk preset"               : dict(scf_style="bulk"),
    "magnetic preset"           : dict(scf_style="magnetic"),
    "molecule preset"           : dict(scf_style="molecule"),
    "magnetic, mix_nstored=32"  : dict(scf_style="magnetic", mix_nstored=32),
    "molecule, mix_nstored=32"  : dict(scf_style="molecule", mix_nstored=32),
}

ROW = re.compile(r"^\s*(\d+) \|\s*(\S+) \|\s*(\S+) \|")


def read_history(log_file):
    """(iteration, SCF error in eV) from the log file"""
    history = []
    with open(log_file, encoding="utf-8") as f:
        for line in f:
            m = ROW.match(line)
            if m:
                history.append((int(m.group(1)), float(m.group(3)) * Hartree))
    return history


fig, ax = plt.subplots(figsize=(6.4, 4.2))
print(f"{'setting':24s} | conv. | iter. | energy (eV)")
for label, params in SETTINGS.items():
    log_file = "scf_" + re.sub(r"\W+", "_", label).strip("_") + ".log"
    atoms = slab.copy()
    atoms.calc = AOFDFTCalculator(
        console      = False,
        logging_file = log_file,
        kin_type     = "AS26",
        kin_model    = "Crystal26",
        vps_dir      = VPS_DIR,
        pao_dir      = PAO_DIR,
        max_iter     = 150,
        **params,
    )
    energy = atoms.get_potential_energy()  # scf_must_conv=False: returns even if not converged
    hist   = read_history(log_file)
    print(f"{label:24s} | {str(atoms.calc.scf_converged):5s} | {len(hist):5d} | {energy:.6f}", flush=True)
    ax.semilogy([h[0] for h in hist], [abs(h[1]) for h in hist], label=label)

ax.axhline(1.0e-6 * Hartree, color="gray", linestyle="--", linewidth=0.8)
ax.set_xlabel("SCF iteration")
ax.set_ylabel("SCF error (eV)")
ax.legend(fontsize=8)
fig.tight_layout()
fig.savefig("al111_scf_settings.png", dpi=150)
print("Saved al111_scf_settings.png")

Example output

Results with v1.0.0 (Crystal26), stopped at max_iter=150.

text
setting                  | conv. | iter. | energy (eV)
bulk preset              | True  |    56 | -2144.016483
magnetic preset          | False |   150 | 41036.470020
molecule preset          | False |   150 | 68979.461672
magnetic, mix_nstored=32 | True  |    29 | -2144.016900
molecule, mix_nstored=32 | True  |    30 | -2144.928768
Saved al111_scf_settings.png
SCF error of an 8-layer Al(111) slab (v1.0.0, Crystal26). The dashed line is the convergence threshold.
SCF error of an 8-layer Al(111) slab (v1.0.0, Crystal26). The dashed line is the convergence threshold.
  • The "bulk" preset converged in 56 iterations. Although the system contains a vacuum region, "bulk" suited this metal slab, and "molecule", the preset for molecules, did not.
  • With the "magnetic" and "molecule" presets the SCF diverged, and the total energy after 150 iterations is a large positive value.
  • With mix_nstored=32 added, these two converged in 29 and 30 iterations. Of the differences between the three presets, the one that matters for this system is the length of the mixing history.
  • The converged total energy of the setting based on "molecule" is about 0.9 eV lower than the others, because noisy_precond differs ("2/3" in "molecule", "damping" in the others). Use the same settings for all calculations whose energies are compared.

Notes

  • With scf_must_conv=False (default), the calculation stops after max_iter iterations and returns the total energy even if the SCF has not converged. Always check calc.scf_converged. In structure optimizations and automated workflows, set scf_must_conv=True so that unconverged results are not used.
  • read_history() reads the SCF error (Hartree) from the line of each SCF step in the log file and converts it to eV. See Controlling and monitoring the SCF for the contents of the log.
  • Parameters given individually, such as mix_beta and mix_nstored, take precedence over the values of the scf_style preset.
  • When trying settings, look at how the error behaves in the log (decreasing steadily, oscillating or growing) before choosing the next one; this saves trials.
  • Increasing max_iter alone does not cure oscillation or divergence.

Improving the accuracy and SCF convergence of AdvanceSoft26 for systems with surfaces and vacuum is part of the development roadmap.