Appendix BSetting Up the Computing Environment and Introduction to PySCF
From Chapter 6 onward, this book checks on a computer the theory that we have followed by hand. For this we use a Python module called PySCF (Python-based Simulations of Chemistry Framework) and a module for materials science called pymatgen (Python Materials Genomics). Both are free of charge, and both run on a single laptop.
However, what trips up many students is not the theory but setting up the environment. “I don't know where python is,” “I ran pip install but the module cannot be found,” “I cannot specify the location of a file”—all of these come from not knowing the concepts of the terminal and the path. In this appendix we first settle these points, and then move on to how to use PySCF.
- The meanings of five words: directory, path, command, shell, and environment variable
- The minimum set of UNIX commands used in the terminal (
pwd,cd,ls,mkdir,cp,rm,cat,grep,awk,sed) - Preparing a Python environment (a local Anaconda/miniconda installation, or Google Colab)
- Installing PySCF and pymatgen and checking that they work
- The formats of xyz files and POSCAR files
- How to use the six calculation scripts used in this book, and a list of their options
- Systematic calculations with for loops, and extracting and plotting the results with
grep/awk - Visualizing molecular structures and wave functions with VESTA
B.1 Five Words to Learn First
Definition: The minimum vocabulary for using a computer
- Directory: A box that holds files. It is the same thing that is called a “folder” on Windows and macOS screens.
- Path: The address of a file or directory. It is written like
/Users/ymochizuki/Downloads/XYZ_H.xyz. A path that starts from/(the root) is called an absolute path, and a path that gives the position relative to where you currently are is called a relative path. - Command: An instruction that you type into the terminal. It is executed when you press the Enter key.
- Shell: The “shell” that translates the commands written by a human into machine language.
bashandzshare the mainstream ones; the default on macOS iszsh, and the default on Ubuntu running on Windows isbash. You can check which one you are using withecho $SHELL. - Environment variable: A variable that determines the behavior of the shell.
$SHELLand$PATHare examples. When you display one, you put a dollar sign at the front.
Why? Why do we use commands instead of the mouse?
There are two kinds of interaction with a computer. One is the GUI (Graphical User Interface), in which you manipulate icons on the screen with the mouse; the other is the CLI (Command Line Interface), in which you type commands as text.
The reason for using the CLI in research is that it lets us repeat the same task in large numbers, accurately, and while leaving a record. For example, in Chapter 8 we compute the total energy of $\mathrm{O_2}$ for 12 different bond lengths, from 0.9 Å to 2.0 Å. You could click 12 times in a GUI to run them, but if you changed the bond length in steps of 0.01 Å, it would become 110 runs. With the CLI, you only need to write three lines of a for loop, and afterward what you did remains as the history of commands. In research, where reproducibility is vital, this makes a decisive difference.
~.B.2 The Terminal and UNIX Commands
On macOS, launch the “Terminal” app; on Windows, launch Ubuntu on WSL (Windows Subsystem for Linux). This is that familiar black screen on which you type text.
B.2.1 Moving around and listing
$ pwd # show where you are now (print working directory)
/Users/ymochizuki
$ ls # list the files in this location (list segments)
Desktop Documents Downloads
$ ls -a # show everything, including hidden files
$ ls -l # show details (size, modification time)
$ mkdir 2026_comp_mat_sci # create a directory (make directory)
$ cd 2026_comp_mat_sci # move into it (change directory)
$ pwd
/Users/ymochizuki/2026_comp_mat_sci
$ cd .. # go back up one level
$ cd ~ # go back to the home directory (cd alone does the same)
Listing B.1: Basic commands for moving around and listing. $ is the prompt, so do not type it.
Not a Math Note but an “Operations Note”: The meaning of the dot
Let us sort out the meaning of the symbols that appear in paths.
.(one dot): the place where you are now..(two dots): one level up~(tilde): the home directory/(a leading slash): the root (the top level)*(asterisk): a wildcard that matches any string.output_*means all files whose names begin withoutput_.
For example, cp ~/Downloads/XYZ_CH4.xyz . means “copy XYZ_CH4.xyz, located in Downloads in the home directory, to the place where you are now.”
B.2.2 Copying, deleting, and displaying
$ cp XYZ_H.xyz XYZ_H_backup.xyz # copy a file (copy)
$ cp ~/Downloads/XYZ_CH4.xyz . # copy from another location to where you are now
$ cp -r pyscf_tutorial1 backup/ # copy a whole directory (recursive)
$ mv old.xyz new.xyz # rename / move (move)
$ rm XYZ_H_backup.xyz # delete a file (remove)
$ rm -r backup # delete a whole directory
$ cat XYZ_H2O.xyz # display the contents of a file (concatenate)
3
962
O 6.30121 0.00000 -0.38499
H 7.63502 0.00000 0.38499
H 4.96764 0.00000 0.38499
$ head -20 output.txt # show only the first 20 lines
$ tail -20 output.txt # show only the last 20 lines
Listing B.2: Basic commands for file operations.
Caution: rm has no trash can
When you delete a file in a GUI, it goes into the trash can, and you can restore it later. The terminal’s rm, however, deletes it immediately and permanently. In particular, rm -r deletes a whole directory, so before running it, make a habit of always checking with pwd and ls “where am I now, and what am I about to delete?” Accidents in which research data are lost in an instant usually happen with this command.
B.2.3 Replacing, searching, and extracting strings
These are the three commands we use in Chapter 8 when systematically varying the bond length of $\mathrm{O_2}$.
# sed: replace a string and save the result to another file
$ sed -e 's/1.20000/2.00000/g' XYZ_O2_1p20000.xyz > XYZ_O2_2p00000.xyz
# grep: extract only the lines containing a specific string
$ grep "Total Energy" output_1p20000.txt
Total Energy (eV) : -4069.348
# search several files at once (wildcard)
$ grep "Total Energy" output_*.txt
# awk: extract only the nth column of whitespace-separated data
$ grep "Total Energy" output_*.txt | awk '{print $NF}'
-4069.348
-4061.466
...
Listing B.3: sed, grep, and awk. The vertical bar | is called a “pipe”; it passes the output of the command on the left to the input of the command on the right.
In awk, $1, $2, … are the numbers of the whitespace-separated columns, and $NF means the last column. Count the columns according to the format of the output, and extract only the numbers you need.
B.3 Setting Up a Python Environment
There are broadly two ways to run Python.
| Local environment (Anaconda/miniconda) | Google Colab | |
|---|---|---|
| Preparation | Installation is required (30 minutes to several hours) | Only a Google account is needed. Start immediately in a browser |
| Computation speed | Depends on the performance of your own PC | Reasonably fast even on the free tier |
| Saving files | Remain permanently on your PC | Deleted if left idle for 12 hours (kept if placed on Google Drive) |
| UNIX commands | Can be used as they are | Need ! at the beginning (only cd needs %) |
| Suited to | People who want to use Python seriously in research | People who want to try running something first, or who got stuck setting up the environment |
B.3.1 The local environment
Search for “windows anaconda install,” “mac anaconda install,” and so on, and install it by following the instructions. After the installation, check the following in the terminal.
$ which python3 # where the Python executable is located
/Users/ymochizuki/anaconda3/bin/python3
$ python3 --version
Python 3.11.5
$ echo $SHELL # the type of shell
/bin/zsh
$ pip3 list | grep pyscf # whether PySCF is installed
Listing B.4: Checking the environment. If which returns nothing, the path to Python has not been set yet.
B.3.2 Installing the necessary modules
$ pip3 install pyscf
$ pip3 install numpy matplotlib
$ pip3 install pymatgen # used in Chapter 13
$ pip3 install geometric # sometimes used for geometry optimization
Listing B.5: Installing modules.
To open a Jupyter Notebook (file extension .ipynb), the easy way is to install Visual Studio Code and add the Python extension. Files such as pyscf_tutorial1.ipynb in the lecture handout are in this format.
B.4 Using Google Colab
If you get stuck while setting up the environment, you can switch to Google Colab without hesitation. Go to https://colab.research.google.com/ and just click “New notebook,” and a Jupyter Notebook starts up in your browser. It is a good idea to rename the file to something easy to recognize, such as 2026_Computational_Materials_Science.ipynb.
Caution: Colab runs Python, not Linux
What you write in a Colab cell is Python code. echo and ls are Linux commands, so writing them as they are results in an error. When you want to use a Linux command in a Notebook, put ! at the beginning. The only exception is cd, for which you put % (with !cd, the change of directory is effective only within that one cell).
# Contents to write in a Colab cell
!pwd
!ls
!pip install pyscf
%cd /content/drive/MyDrive/pyscf_tutorial1
!python3 calc_pyscf.py --xyz XYZ_H.xyz --spin 1
B.4.1 Connecting to Google Drive
The Colab working area (/content) is completely erased if it is left idle for more than 12 hours. To keep the files you create, mount (connect) your own Google Drive.
# Run in a Colab cell
from google.colab import drive
drive.mount('/content/drive')
Listing B.6: Mounting Google Drive. An authentication screen appears, so grant permission.
Once mounted, /content/drive/MyDrive/ becomes the root of your own Drive. The pyscf_tutorial1.zip distributed in the lecture must be unzipped before you place it on the Drive (if you leave it zipped, you cannot access the files inside).
# If the environment is reset after 12 hours of idleness, just run these again in order
from google.colab import drive
drive.mount('/content/drive')
!pip install pyscf
%cd /content/drive/MyDrive/pyscf_tutorial1
!python3 calc_pyscf.py --xyz XYZ_Be.xyz --spin 0 --basis 6-31g
Listing B.7: Procedure for recovering after the session has expired.
When you have finished, it is a good idea to unmount the Drive.
drive.flush_and_unmount()
Listing B.8: Unmounting.
B.5 Installing PySCF and Your First Calculation
Once you are ready, move to the pyscf_tutorial1 directory distributed in the lecture and let us calculate the hydrogen atom.
$ cd ~/Downloads/pyscf_tutorial1
$ ls
XYZ_B.xyz XYZ_Be.xyz XYZ_CH4.xyz XYZ_F.xyz XYZ_H.xyz XYZ_He.xyz
XYZ_Li.xyz XYZ_N.xyz XYZ_Ne.xyz XYZ_O.xyz XYZ_O2.xyz calc_pyscf.py
$ python3 calc_pyscf.py --xyz XYZ_H.xyz --spin 1
Listing B.9: Calculation of the hydrogen atom. --spin 1 means “the difference between the numbers of up-spin and down-spin electrons is 1.”
The output lists the computational method (Method : UHF), the total energy (Total Energy), the molecular orbital energies (MO energies), and the occupation numbers. The total energy of the hydrogen atom in the STO-3G basis is $-12.696$ eV, which has an error of 6.7% relative to the exact solution of $-13.606$ eV (Chapter 6, Section 6.7).
Caution: --spin is $2S$, not the number of electrons
The --spin of PySCF is neither the spin multiplicity $2S+1$ nor the number of electrons, but $2S$ (= the difference between the numbers of up-spin and down-spin electrons).
- H atom (one electron): $2S=1$ →
--spin 1 - He atom (closed shell): $2S=0$ →
--spin 0 - $\mathrm{O_2}$ (triplet, ground state): $2S=2$ →
--spin 2 - C atom ($2p^2$, $^3P$): $2S=2$ →
--spin 2
If you get this wrong, the calculation itself runs, but the answer has no physical meaning. When the energy deviates greatly from the experimental value, first suspect --spin.
B.6 Formats of Structure Files
B.6.1 xyz files (molecules)
This is the simplest format for describing the structure of a molecule.
3
962
O 6.30121 0.00000 -0.38499
H 7.63502 0.00000 0.38499
H 4.96764 0.00000 0.38499
Listing B.10: XYZ_H2O.xyz. The first line is the number of atoms, the second line is a comment (you may write anything), and the third and subsequent lines are “element symbol x y z.” The unit of the coordinates is the ångström.
B.6.2 Conversion from SDF files
You can search PubChem (https://pubchem.ncbi.nlm.nih.gov/) by molecule name or chemical formula and save the structure in SDF format from Download Coordinates under “3D Conformer.” It is a good idea to rename the file so that it shows “which molecule it is,” as in SDF_D-glucose.sdf; then you can tell at a glance when you run ls later.
$ python3 sdf2xyz.py --sdf SDF_D-glucose.sdf --xyz XYZ_D-glucose.xyz
$ head -3 XYZ_D-glucose.xyz
24
converted from SDF_D-glucose.sdf
C -0.7810 1.2680 0.4980
Listing B.11: Conversion from SDF to xyz. If --xyz is omitted, the output is written under a default name.
B.6.3 POSCAR files (crystals)
In the pymatgen of Chapter 13, the crystal structure is given in the POSCAR format of VASP. It can be downloaded free of charge from the Materials Project (https://next-gen.materialsproject.org/).
Na4 Cl4
1.0
5.6920 0.0000 0.0000
0.0000 5.6920 0.0000
0.0000 0.0000 5.6920
Na Cl
4 4
Direct
0.000 0.000 0.000
0.000 0.500 0.500
...
Listing B.12: Structure of a POSCAR file. The first line is a comment, the second line is the scale factor, lines 3–5 are the lattice vectors, the sixth line is the elements, the seventh line is the number of atoms of each element, the eighth line is the coordinate system (Direct = fractional coordinates), and the rest are the atomic coordinates.
B.7 List of Calculation Scripts and Options
Six scripts are distributed in the lecture. For each of them, adding --help displays how to use it.
$ python3 calc_pyscf_dos.py --help
Listing B.13: When in trouble, first try --help.
| Script | What it does | Corresponding chapters |
|---|---|---|
calc_pyscf.py | Single-point calculation (total energy and molecular orbital energies) | Chapters 6, 7, and 9 |
calc_pyscf_relax.py | Geometry optimization (structural relaxation) | Chapters 8 and 10 |
calc_pyscf_dos.py | Density of states (DOS/PDOS), crystal orbital overlap population (COOP) and crystal orbital Hamilton population (COHP) | Chapter 10 |
calc_pyscf_wf.py | Output of the molecular orbital wave functions to cube files | Chapter 10 |
calc_pyscf_vib.py | Calculation of vibrational frequencies (vibrational levels) | Chapter 10 |
sdf2xyz.py | SDF → xyz conversion | Chapter 10 |
B.7.1 Common options
| Option | Meaning | Default |
|---|---|---|
--xyz FILE | Input structure file (required) | — |
--basis NAME | Basis function (sto-3g, 3-21g, 6-31g, 6-31g*, 6-31+g, etc.) | sto-3g |
--method NAME | SCF method (auto/rhf/uhf/rohf) | auto |
--theory NAME | Level of theory (scf/dft/mp2/ccsd/ccsd_t) | scf |
--xc NAME | Exchange–correlation functional (when --theory dft) | b3lyp |
--spin N | $2S$ (difference between the numbers of up-spin and down-spin electrons) | 0 |
--charge N | Total charge of the system | 0 |
--unit NAME | Unit of the coordinates (Angstrom/Bohr) | Angstrom |
B.7.2 Options specific to calc_pyscf.py
| Option | Meaning |
|---|---|
--decompose-total-energy | Decomposes and displays the total energy into $T$ (kinetic), $V_{ne}$ (nucleus–electron), $J$ (Hartree term), $K$ (exchange term), and $V_{nn}$ (nucleus–nucleus). Used in Chapter 9, Section 9.10 |
--pes --rmin A --rmax B --npts N | Scans the potential energy curve of a diatomic molecule in one run (the unit of distance is bohr) |
--zpe | Calculates the zero-point energy in the harmonic approximation |
--mom --promote-from i --promote-to j | $\Delta$SCF calculation of an excited state by the MOM method (UHF only) |
# Chapter 9: Look at the breakdown of the total energy
$ python3 calc_pyscf.py --xyz XYZ_He.xyz --spin 0 --basis 6-31g --decompose-total-energy
# Chapter 6: Compare the Li atom with UHF and ROHF
$ python3 calc_pyscf.py --xyz XYZ_Li.xyz --spin 1
$ python3 calc_pyscf.py --xyz XYZ_Li.xyz --spin 1 --method rohf
# Chapter 6: Change the charge (Li+)
$ python3 calc_pyscf.py --xyz XYZ_Li.xyz --spin 0 --charge 1
# Chapter 7: Low spin and high spin of the carbon atom
$ python3 calc_pyscf.py --xyz XYZ_C.xyz --spin 2 --basis 6-31g
$ python3 calc_pyscf.py --xyz XYZ_C.xyz --spin 4 --basis 6-31g
Listing B.14: Usage examples of calc_pyscf.py.
B.7.3 Geometry optimization, DOS, wave functions, and vibrations
# Chapters 8 and 10: Structural relaxation. XYZ_name-finish.xyz is output
$ python3 calc_pyscf_relax.py --xyz XYZ_O2_0p900000.xyz --spin 2 --basis 6-31g
# Chapter 10: Density of states (with element and orbital decomposition, display range -30 to 10 eV)
$ python3 calc_pyscf_dos.py --xyz XYZ_D-glucose-finish.xyz --spin 0 \
--basis 6-31g --xrange -30 10 --element-pdos
# Chapter 10: COHP (analysis of bond strength)
$ python3 calc_pyscf_dos.py --xyz XYZ_CH4-finish.xyz --spin 0 --basis 6-31g \
--cohp --pair C,H
# Chapter 10: Output the HOMO and LUMO to cube files
$ python3 calc_pyscf_wf.py --xyz XYZ_CH4-finish.xyz --spin 0 --basis 6-31g \
--homo --lumo
# Specify particular molecular orbitals for output (zero-based numbers)
$ python3 calc_pyscf_wf.py --xyz XYZ_CH4-finish.xyz --spin 0 --basis 6-31g \
--mo 1 2 3 4 7
# Chapter 10: Calculation of vibrational frequencies
$ python3 calc_pyscf_vib.py --xyz XYZ_H2O-finish.xyz --spin 0 --basis 6-31g
Listing B.15: Typical usage of each script. The \ at the end of a line means “continued on the next line”; you may also write everything on one line.
calc_pyscf_dos.py also has options such as --sigma (width of the Gaussian broadening, default 0.3 eV) and --csv/--txt/--output (where to save the numerical data and figures). With calc_pyscf_wf.py, you can adjust the number of grid points of the cube file with --nx --ny --nz and the margin of the box (in bohr) with --margin.
B.8 Systematic Calculations with for Loops and Extracting the Results
Let us run through the task carried out in Chapter 8, “calculate the total energy while varying the bond length of $\mathrm{O_2}$,” from start to finish. Done by hand, it would take several dozen repetitions, but in the terminal it takes only a few lines.
B.8.1 Mass-producing structure files
# Source file (bond length 1.20000 Å)
$ cat XYZ_O2_1p20000.xyz
2
O2 molecule
O 0.00000 0.00000 0.00000
O 0.00000 0.00000 1.20000
# Create structure files from 0.90 Å to 1.90 Å in steps of 0.10 Å
$ for d in 0p90000 1p00000 1p10000 1p20000 1p30000 1p40000 1p50000 \
1p60000 1p70000 1p80000 1p90000
do
r=$(echo $d | sed -e 's/p/./')
sed -e "s/1.20000/$r/" XYZ_O2_1p20000.xyz > XYZ_O2_${d}.xyz
done
$ ls XYZ_O2_*.xyz
XYZ_O2_0p90000.xyz XYZ_O2_1p00000.xyz ... XYZ_O2_1p90000.xyz
Listing B.16: Mass-producing structure files with sed and a for loop. The dollar sign denotes a variable. Since a period in a file name would be confusing, p is substituted for it.
B.8.2 Running the calculations in batch
$ for f in XYZ_O2_*.xyz
do
tag=$(basename $f .xyz)
python3 calc_pyscf.py --xyz $f --spin 2 --basis 6-31g > output_${tag}.txt
done
Listing B.17: Calculating every file in turn and saving the results to text files. The symbol > means “write the output to a file” (redirection).
B.8.3 Extracting the results and plotting them
# Extract only the total-energy lines
$ grep "Total Energy" output_*.txt
# Pick out only the numbers
$ grep "Total Energy" output_*.txt | awk '{print $NF}'
# Make a file with the bond length in column 1 and the total energy in column 2
$ for f in output_XYZ_O2_*.txt
do
d=$(echo $f | sed -e 's/.*O2_//' -e 's/.txt//' -e 's/p/./')
e=$(grep "Total Energy" $f | awk '{print $NF}')
echo "$d $e"
done > energy_vs_distance.dat
$ cat energy_vs_distance.dat
0.90000 -4060.401
1.00000 -4066.xxx
...
1.20000 -4069.348
...
2.00000 -4061.466
Listing B.18: Collecting the results into a two-column data file.
# plot_energy.py
import numpy as np
import matplotlib.pyplot as plt
d, e = np.loadtxt("energy_vs_distance.dat", unpack=True)
plt.figure(figsize=(5, 4))
plt.plot(d, e, "o-", color="#14684a")
plt.xlabel(r"Bond length $R$ (Å)", fontsize=13)
plt.ylabel("Total energy (eV)", fontsize=13)
plt.grid(alpha=0.4)
plt.tight_layout()
plt.savefig("O2_potential_curve.png", dpi=200)
plt.show()
Listing B.19: Plotting with matplotlib. This directly yields the interatomic potential curve that appears in textbooks.
Why? This sequence of steps is “computational science” itself
What we have just done consists of four stages: (1) systematically create the input, (2) run the calculations in batch, (3) extract only the necessary numbers from the output, and (4) turn them into a figure and read off the physics. Whether the object is a molecule or a solid, and whether the method is a quantum-chemical calculation or molecular dynamics, the structure of these four stages does not change. Being able to run through this sequence with your own hands is far more important than knowing how to use any individual piece of software.
B.9 Visualization with VESTA
VESTA (https://jp-minerals.org/vesta/) is free software for visualizing crystal structures, molecular structures, and wave functions. It was developed in Japan and is used by first-principles calculation users around the world.
| Extension | Contents | Use in this book |
|---|---|---|
.xyz | Molecular structure | Checking structures, measuring bond lengths and bond angles |
POSCAR | Crystal structure (VASP format) | The ionic crystals of Chapter 13 |
.cube | Three-dimensional scalar field (wave function, electron density) | HOMO/LUMO visualization in Chapter 10 |
The key points of usage are as follows.
- Drag to rotate, and use the mouse wheel to zoom in and out.
- If you click two atoms in succession, the bond length is displayed at the bottom; if you click three in succession, the bond angle is displayed. Use these when comparing with experimental values.
- When you open a cube file, an isosurface is displayed. Yellow is the positive region of the wave function, and blue is the negative region. The isosurface value can be changed under Properties → Isosurfaces.
- By looking at how the positive and negative regions are arranged, you can judge whether an orbital is a bonding orbital or an antibonding orbital. If the sign is the same between the atoms (no node), it is bonding; if the signs are opposite (there is a node), it is antibonding (Chapter 11).
B.10 pymatgen and the Madelung Energy
In Chapter 13, we calculate the electrostatic energy of ionic crystals (the Madelung energy) with pymatgen. pymatgen is a Python module developed within the Materials Genome Initiative, which the United States launched in 2011, and it has become the de facto standard for Materials Informatics.
$ pip3 install pymatgen
$ cd ~/Downloads/pymatgen_tutorial
$ ls
POSCAR_NaCl_Fm-3m POSCAR_MgO_Fm-3m POSCAR_TiO2_P42mnm_rutile ...
calc_madelung_constant.py
$ python3 calc_madelung_constant.py POSCAR_NaCl_Fm-3m
Listing B.20: Calculating the Madelung energy of NaCl.
The output lists the Madelung energy per cell (four Na and four Cl), the Madelung energy per formula unit (one Na and one Cl), and the Madelung constant. Be careful: if you confuse “per cell” with “per formula unit,” the result is off by a factor of four.
When the automatic estimation of the ion valences does not work well, they can be specified explicitly.
# Specify the valences explicitly
$ python3 calc_madelung_constant.py POSCAR_Mg2Si_Fm-3m --oxidation-state Mg=2 Si=-4
# Obtain the Madelung constant with respect to a specific cation-anion pair
$ python3 calc_madelung_constant.py POSCAR_NaCl_Fm-3m --reference-pair Na Cl
Listing B.21: Specifying the valences and specifying the reference ion pair.
The content of the script is essentially just a few lines.
from pymatgen.analysis.ewald import EwaldSummation
from pymatgen.io.vasp.inputs import Poscar
structure = Poscar.from_file("POSCAR_NaCl_Fm-3m").structure
structure.add_oxidation_state_by_guess()
ewald = EwaldSummation(structure)
print("Madelung energy (cell) :", ewald.total_energy, "eV")
Listing B.22: The core of pymatgen. EwaldSummation is responsible for calculating the electrostatic energy by the Ewald method.
Supplement: Why is the Ewald method needed?
As we see in Chapter 13, the series $\sum_j \pm N_j/c_j$ that determines the Madelung constant is conditionally convergent, so the answer changes depending on the order in which the terms are added. Even if we naively add the terms from the nearest ones outward, the sum hardly converges. The Ewald method is a technique that splits this sum into a sum in real space and a sum in reciprocal space (Fourier space), making both converge exponentially fast. It is used almost without exception in first-principles calculations of periodic systems.
B.11 Common Errors and How to Deal with Them
| Symptom | Cause | Remedy |
|---|---|---|
command not found: python3 | Python is not on the path | Check with which python3. If nothing is printed, reinstall Python or switch to Colab |
ModuleNotFoundError: No module named 'pyscf' | The module is not installed, or it was installed in a different Python environment | Run pip3 install pyscf. On Colab the installation disappears after 12 hours, so run it again |
No such file or directory | The file is in a different location | Check where you are and what is there with pwd and ls. Specifying the absolute path again is the surest fix |
| The zip file was placed as it is | It has not been unzipped | Always unzip it before placing it in Google Drive |
| The SCF does not converge | The spin multiplicity was specified incorrectly, or the initial structure is broken | Review --spin. Check the structure visually in VESTA |
| The energy deviates greatly from the experimental value | The basis set is too small / the spin state is wrong | Try --basis 6-31g or larger. Change --spin and compare |
| The energy is higher after structural relaxation | The basis set is too coarse (Chapter 10, Section 10.3) | Recalculate with a larger basis set to check |
| The calculation does not finish | There are many atoms / the basis set is large | First try a small molecule and a small basis set, and then scale up step by step |
Mindset: An error is not a failure
When setting up the environment and debugging eat up your time, it is easy to think, “I am not cut out for programming.” In research practice, however, a considerable part of the computing time is spent on exactly this. An error message is information that tells you what is wrong and how; it is not a scolding. Read it, search for it, and if you still cannot figure it out, it is a good idea to paste it into a generative AI and ask. What matters is the habit of staying calm when an error appears and checking again from pwd and ls.
B.12 Exercises
Exercise B.1: Checking your environment
On your own PC (or on Colab), run the following and record the results.
(1) which python3, python3 --version, echo $SHELL
(2) Create a working directory 2026_comp_mat_sci in your home directory, move into it, and confirm your location with pwd.
(3) Install PySCF and check the version with pip3 list | grep pyscf.
Exercise B.2: Writing an xyz file yourself
Create by hand an xyz file for the $\mathrm{H_2}$ molecule with a bond length of 0.74 Å, and calculate the total energy with PySCF. Try both the sto-3g and 6-31g basis sets and compare the values.
Hint: The first line is the number of atoms (2), the second line is an arbitrary comment, and lines 3 and 4 are “H 0 0 0” and “H 0 0 0.74”. Since the molecule is closed-shell, use --spin 0. Confirm that enlarging the basis set always lowers the total energy (variational principle, Chapter 3).
Exercise B.3: Specifying the spin state
For the oxygen atom (XYZ_O.xyz), calculate the total energy for each of the three settings --spin 0, --spin 2 and --spin 4, and answer which one is the most stable. Is the result consistent with Hund's rules (Chapters 7 and 9)?
Hint: The electron configuration of the oxygen atom is $1s^2 2s^2 2p^4$. When four electrons are placed in the three $2p$ orbitals, Hund's rules make the number of up spins larger by two.
Exercise B.4: Systematic calculations with a for loop
Vary the bond length of the $\mathrm{H_2}$ molecule from 0.5 Å to 2.5 Å in steps of 0.1 Å, and plot the total energy. Read off the equilibrium bond length and compare it with the experimental value of 0.741 Å. Also find the dissociation energy (the difference between the sum of the energies of two H atoms at infinite separation and the energy at the equilibrium point), and compare it with the experimental value of 4.75 eV.
Hint: Listings B.16–B.19 can be reused as they are. Since $\mathrm{H_2}$ is closed-shell, use --spin 0. For the energy at infinite separation, it suffices to double the result of a calculation on a single H atom (--spin 1). It is known that restricted Hartree–Fock (RHF) cannot describe the dissociation limit correctly, so a large deviation should appear. Consider why this happens by relating it to the discussion in Chapter 11, Section 11.9.
Exercise B.5: Calculating a molecule of your choice
Download the structure of a molecule of your choice from PubChem, carry out the following in order, and discuss the results.
(1) SDF → xyz conversion → check the structure in VESTA
(2) Optimize the geometry with calc_pyscf_relax.py and compare the total energies before and after relaxation
(3) Obtain the density of states with calc_pyscf_dos.py --element-pdos, and state which elements and which orbitals make up the region near the HOMO
(4) Obtain the wave functions with calc_pyscf_wf.py --homo --lumo, visualize them in VESTA, and determine their bonding and antibonding character
Hint: A molecule with many atoms takes a long time, so it is a good idea to start by choosing a molecule with up to about 20 atoms. Benzene $\mathrm{C_6H_6}$ (12 atoms) and acetic acid $\mathrm{CH_3COOH}$ (8 atoms) are convenient choices.
Exercise B.6: Comparing Madelung constants
Among the POSCAR files in pymatgen_tutorial, calculate the Madelung constants for POSCAR_NaCl_Fm-3m (rock-salt type), POSCAR_CsCl_Pm-3m (cesium chloride type), POSCAR_NaCl_F-43m (zinc-blende type) and POSCAR_NaCl_P63mc (wurtzite type), and compare them with the values in the table of Chapter 13 (1.7476, 1.7627, 1.6381, 1.6413).
Hint: Confirm that even for the same composition NaCl, the Madelung constant differs if the structure differs, and that the Madelung constant tends to be larger the larger the coordination number is. However, which structure actually becomes stable is determined not only by the electrostatic energy but also by the ionic radius ratio and the repulsion term.
References
- Q. Sun et al., "PySCF: the Python-based simulations of chemistry framework", WIREs Comput. Mol. Sci. 8, e1340 (2018). The original paper on PySCF.
- Q. Sun et al., "Recent developments in the PySCF program package", J. Chem. Phys. 153, 024109 (2020).
- PySCF official documentation https://pyscf.org/
- S. P. Ong et al., "Python Materials Genomics (pymatgen): A robust, open-source python library for materials analysis", Comput. Mater. Sci. 68, 314 (2013). The original paper on pymatgen.
- A. Jain et al., "Commentary: The Materials Project: A materials genome approach to accelerating materials innovation", APL Materials 1, 011002 (2013). An overview of the Materials Project.
- K. Momma and F. Izumi, "VESTA 3 for three-dimensional visualization of crystal, volumetric and morphology data", J. Appl. Crystallogr. 44, 1272 (2011). The original paper on VESTA.
- J. C. Kromann, J. H. Jensen et al., Molcalc—https://molcalc.org/. A web app that lets you run quantum-chemical calculations in a browser alone.
- PubChem https://pubchem.ncbi.nlm.nih.gov/. A database of molecular structures.
- Materials Project https://next-gen.materialsproject.org/. A database of crystal structures and calculated properties.
- P. P. Ewald, "Die Berechnung optischer und elektrostatischer Gitterpotentiale", Ann. Phys. 369, 253 (1921). The original paper on the Ewald method.