Your first VQE: the H₂ ground-state energy on a simulator (PennyLane)
Tested by BSVBuild the 4-qubit hydrogen Hamiltonian, optimise a one-parameter double-excitation circuit and compare the result with exact diagonalisation of the same Hamiltonian.
- Input
- H–H bond length in ångström (default 0.74), optimiser steps (default 60).H–Hの結合長(オングストローム、既定0.74)、最適化のステップ数(既定60)。
- Output
- vqe_h2.csv (step, energy in hartree) and printed Hartree–Fock start, VQE result, exact value and error in mHa.vqe_h2.csv(ステップ、エネルギー〔ハートリー〕)と、Hartree–Fockの初期値、VQEの結果、厳密値、誤差(mHa)の表示。
- Prerequisites
- Python 3.10 or later and
pip install pennylane.Python 3.10以上とpip install pennylane。 - Steps
-
- Save the code below as vqe_h2_pennylane.py.
- Run
python vqe_h2_pennylane.py. - Plot vqe_h2.csv to watch the energy fall from the Hartree–Fock value.
- Scan the bond length (for example 0.5 to 2.0 Å) and plot energy against distance: that is a potential-energy curve.
- Try fewer steps or a different step size and see when the error rises above chemical accuracy (about 1.6 mHa).
- 下のコードを vqe_h2_pennylane.py として保存します。
python vqe_h2_pennylane.pyを実行します。- vqe_h2.csv をグラフにすると、Hartree–Fockの値からエネルギーが下がっていく様子が見えます。
- 結合長を変えながら(たとえば0.5〜2.0 Å)実行し、距離に対するエネルギーをグラフにします。これがポテンシャルエネルギー曲線です。
- ステップ数を減らしたり、刻み幅を変えたりして、誤差が化学的精度(約1.6 mHa)を超えるのはどんなときかを確かめます。
- Expected result
- The VQE energy ends below the Hartree–Fock start and matches the exact value of the same 4-qubit Hamiltonian to well within chemical accuracy. Matching the exact value of a small-basis model is not the same as matching experiment.VQEのエネルギーはHartree–Fockの初期値より下がり、同じ4量子ビットのハミルトニアンの厳密値と、化学的精度を十分に下回る誤差で一致します。ただし、小さな基底での模型の厳密値に合うことと、実験値に合うことは別の話です。
- Next step
- Read PennyLane's VQE demo for other ansätze and optimisers, then try a slightly larger molecule.PennyLaneのVQEのデモで他のアンザッツや最適化手法を見たうえで、少し大きな分子に挑戦してみてください。 Open
Code (BSV original, MIT licence)
Download .py · vqe_h2_pennylane.py
#!/usr/bin/env python3
"""BSV recipe: your first VQE on a simulator — H2 ground-state energy with PennyLane.
Input : H-H bond length in angstrom (default 0.74), optimiser steps (default 60).
Output: vqe_h2.csv (step, energy in Hartree) and a printed comparison with exact diagonalisation
of the same qubit Hamiltonian (STO-3G basis, 4 qubits). Simulator only (default.qubit).
Original BSV code, MIT. Library: PennyLane (Apache-2.0); Hamiltonian from PennyLane's built-in qchem (differentiable Hartree-Fock).
"""
import csv, sys
import pennylane as qml
from pennylane import numpy as np
def main(bond_angstrom="0.74", steps="60"):
d = float(bond_angstrom) / 0.529177210903 # angstrom -> bohr (CODATA 2018 Bohr radius)
symbols, coords = ["H", "H"], np.array([0.0, 0.0, -d / 2, 0.0, 0.0, d / 2])
H, n_qubits = qml.qchem.molecular_hamiltonian(symbols, coords)
hf = qml.qchem.hf_state(electrons=2, orbitals=n_qubits)
dev = qml.device("default.qubit", wires=n_qubits)
@qml.qnode(dev)
def energy(theta):
qml.BasisState(hf, wires=range(n_qubits))
qml.DoubleExcitation(theta[0], wires=[0, 1, 2, 3])
return qml.expval(H)
opt = qml.GradientDescentOptimizer(stepsize=0.4)
theta = np.array([0.0], requires_grad=True)
trace = []
for i in range(int(steps)):
theta, e = opt.step_and_cost(energy, theta)
trace.append((i, float(e)))
final = float(energy(theta))
exact = float(min(np.linalg.eigvalsh(qml.matrix(H, wire_order=range(n_qubits)))))
with open("vqe_h2.csv", "w", newline="") as f:
w = csv.writer(f); w.writerow(["step", "energy_hartree"]); w.writerows(trace)
print(f"qubits {n_qubits}, terms {len(H.terms()[0])}")
print(f"HF start {trace[0][1]:.6f} Ha")
print(f"VQE final {final:.6f} Ha (theta = {float(theta[0]):.4f})")
print(f"exact {exact:.6f} Ha (same Hamiltonian, numpy eigvalsh)")
print(f"error {abs(final - exact) * 1000:.3f} mHa (chemical accuracy is about 1.6 mHa)")
if __name__ == "__main__":
main(*sys.argv[1:])
Output of BSV's own test run
Run on 2026-10-06 23:37 JST · Python 3.13.5, pennylane 0.45.1
qubits 4, terms 15
HF start -1.116759 Ha
VQE final -1.137284 Ha (theta = 0.2256)
exact -1.137284 Ha (same Hamiltonian, numpy eigvalsh)
error 0.000 mHa (chemical accuracy is about 1.6 mHa)