Appendix E: Python Environment Setup

This appendix walks you through installing Python, setting up a clean virtual environment, installing every package used in this textbook, and verifying that everything works. If you have never used Python before, follow every step. If you are an experienced Python user, skip to Section E.3 for the one-line install command and Section E.5 for the verification script.


E.1 Installing Python

Which version?

This textbook requires Python 3.10 or later. We recommend Python 3.11 or 3.12 for the best balance of performance and package compatibility. Do not use Python 2 (it has been end-of-life since 2020) or Python 3.9 or earlier (some type-hint syntax used in the toolkit requires 3.10+).

Windows

  1. Download the latest Python installer from python.org/downloads.
  2. Run the installer. Check the box "Add Python to PATH" at the bottom of the first screen — this is the single most common source of problems.
  3. Click "Install Now" for the default installation, or "Customize installation" if you want to change the install location.
  4. Verify in a terminal (Command Prompt or PowerShell):
python --version

You should see something like Python 3.12.2.

macOS

macOS ships with a system Python that should not be modified. Install a separate Python:

Option A — Official installer: Download from python.org/downloads and run the .pkg file.

Option B — Homebrew (recommended):

brew install python@3.12

Verify:

python3 --version

Linux (Ubuntu/Debian)

sudo apt update
sudo apt install python3.12 python3.12-venv python3-pip

On other distributions, use your package manager or build from source. Verify:

python3 --version

E.2 Setting Up a Virtual Environment

A virtual environment isolates this textbook's packages from your system Python and from other projects. This prevents version conflicts and keeps things clean.

Creating the environment

Open a terminal and navigate to wherever you keep your course materials. Then:

# Create a directory for the textbook code (if you haven't already)
mkdir quantum-mechanics
cd quantum-mechanics

# Create the virtual environment
python -m venv .venv

On some Linux systems, replace python with python3.

Activating the environment

You must activate the environment every time you open a new terminal session.

Windows (Command Prompt):

.venv\Scripts\activate

Windows (PowerShell):

.venv\Scripts\Activate.ps1

If you get an execution-policy error in PowerShell, run:

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned

macOS / Linux:

source .venv/bin/activate

When activated, your prompt will show (.venv) at the beginning. All pip install commands will now install into this isolated environment.

Deactivating

When you are done working:

deactivate

E.3 Installing Required Packages

With your virtual environment activated, run:

pip install numpy scipy matplotlib qutip sympy jupyter

This installs the six packages used throughout the textbook:

Package Version Purpose in this textbook
NumPy >= 1.24 Array operations, linear algebra, FFT
SciPy >= 1.10 Eigenvalue solvers, special functions, integration, sparse matrices
Matplotlib >= 3.7 All plots: wave functions, energy levels, Bloch spheres, cross sections
QuTiP >= 5.0 Open quantum systems, master equations, Bloch sphere widget, verification of hand-coded results
SymPy >= 1.12 Symbolic algebra for exact solutions, commutator verification, Clebsch-Gordan tables
Jupyter >= 1.0 Interactive notebooks for exploration and exercises

Installing the Quantum Simulation Toolkit

If you have been building the toolkit chapter by chapter, it already lives in your code/qm_toolkit/ directory. To make it importable:

cd code/
pip install -e .

If you downloaded the complete toolkit from the textbook repository:

git clone https://github.com/example/qm-textbook-code.git
cd qm-textbook-code
pip install -e ".[full]"

For exact reproducibility of every plot and numerical result in the textbook:

pip install numpy==1.26.4 scipy==1.12.0 matplotlib==3.8.3 qutip==5.0.4 sympy==1.12 jupyter==1.0.0

E.4 IDE and Editor Recommendations

Most exercises in this textbook are designed to be worked in Jupyter notebooks. After installing Jupyter, launch it:

jupyter notebook

This opens a browser tab. Create a new notebook (Python 3 kernel) and you are ready to go. Jupyter lets you mix code, equations (LaTeX), and plots in a single document — ideal for quantum mechanics, where you want to see formulas and their numerical verification side by side.

JupyterLab is a more modern interface:

pip install jupyterlab
jupyter lab

If you are writing or modifying the toolkit modules (.py files), Visual Studio Code provides the best experience:

  1. Download from code.visualstudio.com.
  2. Install the Python extension (by Microsoft) from the Extensions marketplace.
  3. Open your quantum-mechanics/ folder in VS Code.
  4. Select your virtual environment as the Python interpreter: press Ctrl+Shift+P, type "Python: Select Interpreter", and choose the .venv one.
  5. The integrated terminal, debugger, and IntelliSense will all use your virtual environment.

VS Code also has excellent Jupyter notebook support built in — you can open .ipynb files directly.

Other options

  • PyCharm (Community Edition, free): Full-featured IDE with good scientific Python support.
  • Spyder: MATLAB-like interface, comes with Anaconda. Good variable explorer for inspecting arrays.
  • Command line + text editor: Perfectly adequate. Run scripts with python script.py and use ipython for interactive exploration.

E.5 Verification Script

Copy the following script into a file called verify_install.py (or a Jupyter cell) and run it. It tests every package and the core toolkit functionality.

"""
Verification script for the Quantum Mechanics textbook environment.
Run this after installation to confirm everything works.
"""
import sys

print(f"Python version: {sys.version}")
print(f"Python path:    {sys.executable}")
print()

# --- Check core packages ---
packages = {}

try:
    import numpy as np
    packages["NumPy"] = np.__version__
except ImportError:
    packages["NumPy"] = "MISSING"

try:
    import scipy
    packages["SciPy"] = scipy.__version__
except ImportError:
    packages["SciPy"] = "MISSING"

try:
    import matplotlib
    packages["Matplotlib"] = matplotlib.__version__
except ImportError:
    packages["Matplotlib"] = "MISSING"

try:
    import qutip
    packages["QuTiP"] = qutip.__version__
except ImportError:
    packages["QuTiP"] = "MISSING (optional but recommended)"

try:
    import sympy
    packages["SymPy"] = sympy.__version__
except ImportError:
    packages["SymPy"] = "MISSING (optional)"

try:
    import jupyter
    packages["Jupyter"] = jupyter.__version__
except ImportError:
    packages["Jupyter"] = "MISSING (optional)"

print("Package versions:")
all_ok = True
for name, version in packages.items():
    status = "OK" if "MISSING" not in version else "!!"
    if "MISSING" in version and "optional" not in version:
        all_ok = False
    print(f"  {status}  {name:12s} {version}")

print()

# --- Functional tests ---
print("Running functional tests...")

# Test 1: NumPy linear algebra
A = np.array([[0, 1], [1, 0]])
eigenvalues = np.linalg.eigvalsh(A)
assert np.allclose(sorted(eigenvalues), [-1, 1]), "NumPy eigenvalue test failed"
print("  [PASS] NumPy eigenvalue decomposition")

# Test 2: SciPy special functions (Hermite polynomial)
from scipy.special import hermite
H3 = hermite(3)
assert np.isclose(H3(1.0), -4.0), "SciPy Hermite polynomial test failed"
print("  [PASS] SciPy special functions (Hermite)")

# Test 3: SciPy integration (Gaussian integral)
from scipy.integrate import quad
result, _ = quad(lambda x: np.exp(-x**2), -np.inf, np.inf)
assert np.isclose(result, np.sqrt(np.pi), rtol=1e-10), "Gaussian integral test failed"
print("  [PASS] SciPy numerical integration (Gaussian)")

# Test 4: Matplotlib (create and close a figure without display)
import matplotlib
matplotlib.use("Agg")  # non-interactive backend for testing
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = np.linspace(0, 2 * np.pi, 100)
ax.plot(x, np.sin(x))
plt.close(fig)
print("  [PASS] Matplotlib figure creation")

# Test 5: SciPy sparse eigenvalue solver (used in matrix diagonalization)
from scipy.sparse import diags
from scipy.sparse.linalg import eigsh
N = 100
dx = 0.1
diag_main = np.ones(N) * 2.0 / dx**2
diag_off = np.ones(N - 1) * (-1.0) / dx**2
H = diags([diag_off, diag_main, diag_off], [-1, 0, 1])
evals, _ = eigsh(H, k=3, which="SM")
print("  [PASS] SciPy sparse eigenvalue solver")

# Test 6: QuTiP (if available)
try:
    import qutip
    psi = qutip.basis(2, 0)  # |0>
    sz = qutip.sigmaz()
    exp_val = qutip.expect(sz, psi)
    assert np.isclose(exp_val, 1.0), "QuTiP expectation value test failed"
    print("  [PASS] QuTiP state creation and expectation value")
except ImportError:
    print("  [SKIP] QuTiP not installed")

# Test 7: SymPy (if available)
try:
    import sympy
    x = sympy.Symbol("x")
    expr = sympy.integrate(sympy.exp(-x**2), (x, -sympy.oo, sympy.oo))
    assert expr == sympy.sqrt(sympy.pi), "SymPy Gaussian integral test failed"
    print("  [PASS] SymPy symbolic integration")
except ImportError:
    print("  [SKIP] SymPy not installed")

print()
if all_ok:
    print("All required packages installed and functional tests passed.")
    print("You are ready to begin the textbook exercises.")
else:
    print("WARNING: Some required packages are missing. Install them with:")
    print("  pip install numpy scipy matplotlib qutip sympy jupyter")

Run with:

python verify_install.py

Expected output (version numbers will vary):

Python version: 3.12.2 (main, Feb  6 2024, 20:19:44)
Python path:    /home/user/quantum-mechanics/.venv/bin/python

Package versions:
  OK  NumPy        1.26.4
  OK  SciPy        1.12.0
  OK  Matplotlib   3.8.3
  OK  QuTiP        5.0.4
  OK  SymPy        1.12
  OK  Jupyter      1.0.0

Running functional tests...
  [PASS] NumPy eigenvalue decomposition
  [PASS] SciPy special functions (Hermite)
  [PASS] SciPy numerical integration (Gaussian)
  [PASS] Matplotlib figure creation
  [PASS] SciPy sparse eigenvalue solver
  [PASS] QuTiP state creation and expectation value
  [PASS] SymPy symbolic integration

All required packages installed and functional tests passed.
You are ready to begin the textbook exercises.

E.6 Troubleshooting Common Issues

QuTiP installation fails on Windows

QuTiP 5.x has improved Windows support, but you may still encounter build issues. Try:

pip install qutip --only-binary :all:

If that fails, install via conda instead:

conda install -c conda-forge qutip

If you cannot get QuTiP installed at all, don't panic. QuTiP is used for verification and advanced open-systems simulations (Chapters 30, 33). The core toolkit (qm_toolkit) runs on NumPy and SciPy alone. You can complete the vast majority of exercises without QuTiP.

Matplotlib shows no plots (blank window or no window at all)

This usually means the matplotlib backend is misconfigured. Try explicitly setting a backend:

import matplotlib
matplotlib.use("TkAgg")  # or "Qt5Agg" or "WebAgg"
import matplotlib.pyplot as plt

On WSL (Windows Subsystem for Linux), matplotlib cannot open GUI windows unless you have an X server (like VcXsrv or the built-in WSLg in Windows 11). Alternatives: - Save figures to files: plt.savefig("plot.png") - Use Jupyter notebooks (they display inline) - Use the %matplotlib inline magic in Jupyter

"DLL load failed" errors on Windows

This typically means a compiled dependency (NumPy, SciPy) was built for a different Python version. Ensure your virtual environment matches your Python installation:

python --version          # Check system Python version
.venv\Scripts\python --version  # Check venv Python version (should match)

If they don't match, delete .venv and recreate it.

Import errors for qm_toolkit

If from qm_toolkit.core import Ket fails:

  1. Make sure you ran pip install -e . from the code/ directory.
  2. Make sure your virtual environment is activated (you should see (.venv) in your prompt).
  3. As a quick fix, add the code directory to your Python path:
import sys
sys.path.insert(0, "/path/to/quantum-mechanics/code")

Jupyter kernel does not see installed packages

The Jupyter kernel might be using a different Python than your virtual environment. Fix this by installing the kernel spec:

# With your venv activated:
pip install ipykernel
python -m ipykernel install --user --name=qm --display-name="Python (QM)"

Then in Jupyter, select the "Python (QM)" kernel from the Kernel menu.

Performance issues with large matrices

Some exercises (especially the variational methods in Chapter 23 and the scattering calculations in Chapter 28) involve matrices with dimensions in the thousands. If these are slow:

  1. Make sure you have a recent version of NumPy compiled with optimized BLAS/LAPACK (Intel MKL or OpenBLAS). Check with numpy.show_config().
  2. Use sparse matrices (scipy.sparse) for Hamiltonians that are mostly zeros.
  3. Use scipy.sparse.linalg.eigsh instead of numpy.linalg.eigh for finding a few eigenvalues of large matrices.

SymPy is slow for large symbolic expressions

SymPy's symbolic engine can be slow for expressions with many terms. For the exercises in this textbook, keep symbolic calculations small (2x2 or 3x3 matrices) and switch to NumPy for anything larger. SymPy is best used for verification of analytical results, not for heavy computation.


E.7 Using the Quantum Simulation Toolkit

Once installed, the toolkit is available from any Python script or notebook:

from qm_toolkit.core import Ket, Bra, Operator, QuantumState
from qm_toolkit.wavefunctions import Wavefunction
from qm_toolkit.harmonic import ho_eigenstate, coherent_state
from qm_toolkit.hydrogen import hydrogen_radial_wf, hydrogen_energy
from qm_toolkit.spin import pauli_matrices, spinor
from qm_toolkit.angular import spherical_harmonic, clebsch_gordan
from qm_toolkit.visualization import plot_wavefunction, plot_bloch_sphere
from qm_toolkit.constants import hbar, m_e, e_charge, a_0

See Appendix B for the complete API reference, grouped by topic and indexed by chapter.

A good first exercise to make sure everything is wired up:

import numpy as np
from qm_toolkit.harmonic import ho_eigenstate, ho_energy
from qm_toolkit.visualization import plot_wavefunction
from qm_toolkit.constants import hbar

# Plot the first 4 harmonic oscillator eigenstates
omega = 1.0  # natural units
x = np.linspace(-6, 6, 500)

for n in range(4):
    psi_n = ho_eigenstate(n, x, omega=omega, mass=1.0, hbar=1.0)
    E_n = ho_energy(n, omega=omega, hbar=1.0)
    plot_wavefunction(x, psi_n, label=f"n={n}, E={E_n:.1f}")

If you see four clean oscillator wave functions with the correct number of nodes, your environment is ready for the rest of the textbook.


Environment troubles are the least interesting part of learning quantum mechanics. If you get stuck, the textbook repository's issue tracker and discussion forum are the fastest way to get help. Include your operating system, Python version, and the full error message.