# Your first calculation: SCF and cube files :::{admonition} Video :class: tip [Watch the narrated video of this tutorial on YouTube](https://www.youtube.com/watch?v=5HvUKsAHYGA). ::: :::{admonition} In this tutorial :class: tip You run a single-point Kohn–Sham calculation on water (PBE/def2-TZVP), read every part of the output, and plot the SCF convergence, the orbital-energy diagram, orbitals and the density from cube files. **Time:** about 1 second on 8 cores. **Files:** {download}`h2o_scf.yaml `, {download}`h2o_scf.out ` (reference output), {download}`run.sh `. ::: ## What you need - A built `run_dft` (`./build_run_dft.sh` in the repository root; see the User Manual, *Building and running*). - Python 3 with `numpy` and `matplotlib` for the plots, plus `pyvista` for the 3D pictures (`pip install -r tutorials/requirements.txt`). - Any cube viewer if you prefer one (VMD, Avogadro, VESTA, Jmol, ChimeraX): DFTSW27 writes standard Gaussian cube files. ## The input file DFTSW27 reads one YAML-style input file. This is `files/h2o_scf.yaml`: ```yaml system: charge: 0 unpaired_electrons: 0 units: angstrom functional: exchange: pbe correlation: pbe basis: name: def2-TZVP file: basis/def2-TZVP.nw scf: max_iter: 50 conv_tol: 1.0e-8 print_energies: false cube: prefix: h2o spacing: 0.2 margin: 6.0 quantities: density, mo_alpha:homo, mo_alpha:lumo, mo_alpha:1-5 atoms: - element: O position: [0.000000, 0.000000, 0.117300] - element: H position: [0.000000, 0.757200, -0.469200] - element: H position: [0.000000, -0.757200, -0.469200] ``` Section by section: `system` : Charge and number of unpaired electrons ($N_\alpha-N_\beta$). Water is a closed-shell singlet, so both are 0. `units` applies to the atom positions; **the default is bohr**, so give `units: angstrom` when you paste Ångström coordinates. `functional` : Exchange and correlation are chosen separately. `pbe`/`pbe` is the PBE GGA. Leaving out the `functional` section gives Hartree–Fock. Hybrids and libxc functionals are covered in the User Manual (`functional` section). `basis` : An NWChem-format basis file, as downloaded from the Basis Set Exchange. Every element in the molecule must be in the file. `name` is only a label. DFTSW27 uses **Cartesian** basis functions (6 d functions per d shell), so water/def2-TZVP has 48 functions, not the 43 of a spherical-harmonic code. `scf` : At most 50 iterations, converged when both the energy change and the mixing (DIIS) error are below `conv_tol`. `print_energies: true` prints the energy breakdown at every iteration. `cube` : Cube files to write after convergence: the total density, the HOMO, the LUMO and orbitals 1–5. `spacing` (bohr) is the grid step; `margin` (bohr) is the space around the molecule. Diffuse virtual orbitals need a generous margin. `atoms` : One record per atom. Without a `mesh:` entry each atom gets the built-in integration grid, which is what you want in almost all cases. Notice what is **not** in the input. There is no grid, mixing, initial guess or Coulomb method. The defaults are a pruned Lebedev grid, DIIS mixing, an atomic-potential initial guess and the numerical **Poisson** Coulomb solver for DFT. The output tells you each choice. ## Running From the repository root: ```bash $ OMP_NUM_THREADS=8 ./run_dft tutorials/01_scf/files/h2o_scf.yaml > h2o_scf.out ``` Always set `OMP_NUM_THREADS`. Without it OpenMP uses every core, and small molecules gain little beyond about 8 threads. Everything is written to standard output. The run also writes `evalues.log`, `POPULATION_ANALYSIS.dat` and the cube files to the current directory. `tutorials/01_scf/run.sh` does all of this in `tutorials/01_scf/work/` and makes every figure on this page. ## Reading the output The full reference output is {download}`files/h2o_scf.out`. Here it is part by part. ### Header and setup ```text --- geometry summary --- natoms = 3 total electrons = 10.0000 atom 1 O pos(Bohr)= 0.00000 0.00000 0.22166 moment= 0.00 core=ALL ... coulomb: method = poisson (default for DFT and SIC runs; coulomb: method: eri selects the integral-based J) n_alpha = 5, n_beta = 5 n_basis = 48 grid points = 44568 (angular pruning: auto) initial guess = atomic_potential_fit method: DFT, backend=inhouse, exchange=pbe, correlation=pbe ``` Check these lines first. Positions are always printed in **bohr**, whatever units you gave. Confirm the electron count and the $\alpha/\beta$ split. The `coulomb:` line tells you that the Hartree potential comes from a numerical Poisson solution on the grid. That is the default for DFT and is fast. `coulomb: method: eri` uses exact two-electron integrals instead; the two agree to 1.5 µHa here. ### The SCF iterations ```text iter e_total dE max|dD| mix err time(s) iter 1 -76.2528541598 -7.625285E+01 2.636987E-01 1.854474E-01 0.048 iter 2 -75.8625072699 3.903469E-01 2.329358E-01 3.120354E-01 0.042 ... iter 9 -76.3773236077 -2.387424E-12 2.622689E-09 3.100551E-09 0.041 ``` Each `iter` line gives: - `e_total`: the total energy (Ha). - `dE`: its change from the previous iteration. In iteration 1 this is the energy itself. - `max|dD|`: the largest change of a density-matrix element. - `mix err`: the DIIS error, the norm of the commutator $[F,DS]$. Between `iter` lines the output prints the orbital energies around the gap and the time spent in the Coulomb and XC builds. ```{figure} figures/scf_convergence.png :width: 80% SCF convergence. The energy converges much faster than the density and the DIIS error. The run stops when **both** criteria are below `conv_tol` (iteration 9). ``` Make this plot from any DFTSW27 output with ```bash $ python3 tutorials/tools/dftsw27plot.py scf h2o_scf.out -o scf_convergence.png ``` ### Results, populations and the summary ```text converged = T iterations = 9 e_total (Ha) = -76.3773236077 grid quadrature: integrated density = 10.00000909 Tr(DS) = 10.00000000 error = 9.09E-06 ``` The `grid quadrature` line is a useful sanity check. The density integrated on the grid should match the electron count to about $10^{-5}$. A much larger error means the integration grid is too coarse for the basis, which usually happens with very tight or very diffuse functions. Mulliken and Löwdin charges come next (oxygen $\approx -0.6$, hydrogens $\approx +0.3$). Then come the spin populations and $\langle S^2\rangle$, which are trivially zero for this closed-shell molecule. The `SUMMARY` block collects the main results: ```text Energy contributions (Ha) nuclear repulsion = 9.1895344241 kinetic = 76.1060682300 electron-nuclear (+ECP) = -199.1475120553 Coulomb (Hartree) = 46.7240010930 exchange = -8.9237061342 correlation = -0.3257091048 TOTAL ENERGY = -76.3773236077 |mu| = 0.797923 a.u. = 2.028117 Debye alpha HOMO -0.25692297 -6.991230 alpha LUMO -0.00203471 -0.055367 HOMO-LUMO gap 0.25488826 6.935863 ``` :::{admonition} How good are these numbers? :class: note PySCF with the same Cartesian def2-TZVP basis and PBE gives $E=-76.3773229$ Ha, $|\mu|=2.028$ D and $\varepsilon_{\rm HOMO}=-6.992$ eV. The 0.7 µHa difference is grid quadrature. Two physical points: - The dipole is larger than the experimental 1.85 D because def2-TZVP has no diffuse functions (see the exercises). - $-\varepsilon_{\rm HOMO}=7.0$ eV is far below the experimental ionization energy of 12.6 eV. This is the self-interaction error of semilocal functionals. The FLOSIC tutorials show how self-interaction correction fixes it. ::: ### Files written next to the output | File | Contents | |---|---| | `evalues.log` | All $\alpha$ and $\beta$ eigenvalues and occupations at every SCF iteration (10 virtual levels per spin). | | `POPULATION_ANALYSIS.dat` | Mulliken and Löwdin populations. | | `h2o_density.cube` | Total electron density. | | `h2o_mo_alpha_.cube` | Orbital $n$ (here 1–6; `homo` = 5 and `lumo` = 6 are written once). | ## Plotting the results ### Orbital-energy diagram ```bash $ python3 tutorials/tools/dftsw27plot.py levels evalues.log -o levels.png --emin -100 ``` ```{figure} figures/levels.png :width: 45% Kohn–Sham levels of water from the last SCF iteration in `evalues.log`. The O 1s level at $-18.8$ Ha is hidden with `--emin`. Use `--spin` for open-shell molecules to draw the $\alpha$ and $\beta$ columns. ``` ### Orbitals and density in 3D Cube files are in bohr. Orbitals have both signs, so draw a positive and a negative isosurface: ```bash $ python3 tutorials/tools/dftsw27plot.py cube h2o_mo_alpha_5.cube --sign --iso 0.08 \ --view xz --azimuth 40 --elevation 15 -o homo.png ``` ::::{grid} 3 :::{grid-item} ```{figure} figures/homo.png HOMO (1b1): the oxygen lone pair perpendicular to the molecular plane. ``` ::: :::{grid-item} ```{figure} figures/lumo.png LUMO (4a1): diffuse, antibonding along the O–H bonds. ``` ::: :::{grid-item} ```{figure} figures/density.png Total density, 0.1 e/bohr$^3$ isosurface. ``` ::: :::: The isosurface value sets how much of the function you see. Orbitals usually need 0.02–0.1 and densities 0.002–0.1. Try a few values; an isovalue that is too small shows an uninformative blob. ### 2D slices A slice through the molecular plane (here the $yz$ plane, $x=0$) is often clearer than a 3D picture: ```bash $ python3 tutorials/tools/dftsw27plot.py slice h2o_mo_alpha_3.cube --plane yz --at 0 --range 4 -o mo3_slice.png $ python3 tutorials/tools/dftsw27plot.py slice h2o_density.cube --plane yz --at 0 --range 4 --log -o density_slice.png ``` ::::{grid} 3 :::{grid-item} ```{figure} figures/mo3_slice.png Orbital 3 (1b2): O–H bonding, antisymmetric between the two bonds. ``` ::: :::{grid-item} ```{figure} figures/lumo_slice.png The LUMO in the molecular plane. ``` ::: :::{grid-item} ```{figure} figures/density_slice.png Density, logarithmic contours from $10^{-3}$ to 10 e/bohr$^3$. ``` ::: :::: ### Other viewers Every program that reads Gaussian cube files works: - **VMD:** `vmd h2o_mo_alpha_5.cube`, then *Graphics → Representations → Isosurface*. - **Avogadro / VESTA / ChimeraX:** *File → Open*. The `cube` and `slice` commands above are a scripted alternative for figures in papers and reports. ## Things to try 1. **Diffuse functions.** Replace the basis by `basis/aug-pc-2.nw` and compare the dipole moment with the experimental 1.85 D. Note how the LUMO changes. 2. **Exact Coulomb.** Add `coulomb:` with `method: eri` and compare the total energy with the Poisson result. 3. **Hartree–Fock.** Delete the `functional` section. Compare $-\varepsilon_{\rm HOMO}$ with the PBE value and with the experimental 12.6 eV (Koopmans' theorem). 4. **The cation.** Set `charge: 1` and `unpaired_electrons: 1`. Plot `spin_density` (add it to `quantities`) and use `levels --spin`. :::{dropdown} What you should find | Run | basis functions | $E$ (Ha) | $\lvert\mu\rvert$ (D) | $-\varepsilon_{\rm HOMO}$ (eV) | |---|---|---|---|---| | PBE/def2-TZVP (this tutorial) | 48 | $-76.3773236$ | 2.03 | 6.99 | | PBE/aug-pc-2 | 105 | $-76.3850621$ | 1.80 | 7.25 | | PBE/def2-TZVP, `coulomb: eri` | 48 | $-76.3773251$ | 2.03 | 6.99 | | HF/def2-TZVP | 48 | $-76.0594112$ | 2.16 | 13.83 | | PBE/def2-TZVP cation ($\langle S^2\rangle=0.752$) | 48 | $-75.9105235$ | — | — | The diffuse aug-pc-2 basis brings the dipole close to experiment. HF overestimates the ionization energy through Koopmans' theorem by about 1 eV. PBE underestimates it by more than 5 eV. The dipole of a charged molecule depends on the origin, so it is not listed for the cation. ::: ## Troubleshooting - **`n_alpha`/`n_beta` look wrong.** Check `charge` and `unpaired_electrons`. The parity of the electron count and of `unpaired_electrons` must match. - **Strange geometry or a huge nuclear repulsion.** Coordinates were in Ångström but `units` was left at the bohr default. - **The SCF oscillates.** Try `scf: level_shift: 0.2`, or another `initial_guess` (User Manual, `scf` section). - **A cube looks cut off.** Increase `cube: margin`. **Next:** {doc}`../02_geomopt/index` of the same molecule.