ProductBlogAlgorithmsAboutSign inSign up

Learning Tutorial

H₂ VQE: Measure Energy and Optimize a Parameter

Run a complete small VQE loop: prepare a two-qubit state, sample three measurement bases, estimate energy and refine a parameter.

2 qubits · 25 search evaluations + 1 fresh final evaluation

How does a classical search use sampled quantum measurements to lower the energy of a small molecular model?

Define the teaching problem

Fix the H–H distance at 0.75 Å. Use the rounded two-qubit STO-6G model from the corrected v2 coefficient table of O’Malley et al.: H = 0.2252 I + 0.3435 Z0 − 0.4347 Z1 + 0.5716 Z0Z1 + 0.0910 X0X1 + 0.0910 Y0Y1, in hartree.

Prepare cos(θ/2)|01⟩ + sin(θ/2)|10⟩ using X on q1, Ry(θ) on q0, then CX from q0 to q1. This simple ansatz spans the ground-state sector of this particular model. It is a different parameterization from the research implementation.

Follow the workflow

  1. For each θ, sample three circuits, with 4,096 shots per basis. Z needs no rotation; X uses H on both qubits; Y uses Rx(+π/2) on both qubits.
  2. From the shared Z counts estimate Z0, Z1 and Z0Z1. Use even-minus-odd parity for XX and YY in their rotated bases. Combine those five expectations with the identity coefficient to obtain an energy.
  3. Evaluate 13 evenly spaced θ values from −π to 0. Starting from the lowest measured energy, halve an initial π/12 step six times and measure the left and right neighbors, clamped to the interval. Retain the best measured candidate. All 25 search evaluations use counts; the exact energy formula is never the optimizer’s cost.
  4. Measure the chosen θ again with fresh samples. Report that final estimate separately from the lowest search estimate and the exact energy at the chosen θ. The fixed budget is 78 circuits and 319,488 local simulated shots, including final validation.

Compare with the expected result

Scroll the table horizontally to see every column.

Ideal mathematical references, not hardware measurements
QuantityReference / interpretation
Exact rounded-model ground energy−1.1455991241 Ha
Exact energy at θ = 0+0.4318 Ha
Analytical minimizing θapproximately −2.911849 radians
Sampled final energyVaries with the selected angle and finite-shot samples

Independent diagonalization of the same rounded 4 × 4 Hamiltonian gives the ground-energy reference. For this ansatz, E(θ) = −0.3464 + 0.7782 cos θ + 0.1820 sin θ. This formula checks the implementation and separates optimization error from measurement fluctuation.

Finite-shot energy estimates can fall below the exact ground energy. Choosing the lowest noisy search estimate also introduces selection bias; that is why the workflow reports a fresh final measurement. Trial energies need not decrease monotonically.

The fixed seed is 7 for an inspectable local run. It does not guarantee the same optimizer outcome on another sampler or library version. No uncertainty interval is reported. This tutorial does not promise chemical accuracy (roughly 0.0016 Ha).

Run the complete tutorial locally

Download the complete Python tutorial, then open a terminal in the folder containing vqe-h2.py.

Use Python 3.10 or later and NumPy 2.x. From that folder, create a virtual environment, install NumPy and run the script. The code uses explicit small statevectors and local pseudorandom sampling. It requires no Marqov account, credentials or external service.

python3 -m venv .venv
source .venv/bin/activate
python -m pip install 'numpy>=2,<3'
python vqe-h2.py
Inspect the complete Python source
"""Learning: one-geometry ideal two-qubit H2 VQE, not a paper replication.
Run: python vqe-h2.py (NumPy required). No network or hosted jobs.
Corrected coefficients: O'Malley et al., arXiv:1512.06860v2, R=.75 Angstrom.
Order II, ZI, IZ, ZZ, XX, YY. Basis |q0 q1>, q0 leftmost.
"""
import json
import math
import numpy as np

I = np.eye(2, dtype=complex)
X = np.array([[0, 1], [1, 0]], dtype=complex)
Y = np.array([[0, -1j], [1j, 0]], dtype=complex)
Z = np.diag([1, -1]).astype(complex)
HAD = (X + Z) / math.sqrt(2)
CX = np.array([[1, 0, 0, 0], [0, 1, 0, 0],
               [0, 0, 0, 1], [0, 0, 1, 0]], dtype=complex)
COEFF = (0.2252, 0.3435, -0.4347, 0.5716, 0.0910, 0.0910)


def state(theta):
    # X(q1), Ry(theta,q0), CX(q0,q1) from |00>.
    ry = np.array([[math.cos(theta / 2), -math.sin(theta / 2)],
                   [math.sin(theta / 2), math.cos(theta / 2)]])
    return CX @ np.kron(ry, I) @ np.array([0, 1, 0, 0], dtype=complex)


def basis_probabilities(theta, basis):
    # H maps X to Z; Rx(+pi/2) maps Y to Z.
    rotation = {"Z": I, "X": HAD, "Y": (I - 1j * X) / math.sqrt(2)}[basis]
    return np.abs(np.kron(rotation, rotation) @ state(theta)) ** 2


def energy(distributions):
    # Distribution order 00,01,10,11. One Z basis supplies three terms.
    z, x, y = (distributions[b] for b in ("Z", "X", "Y"))
    parity = np.array([1, -1, -1, 1])
    expectations = (1, z @ [1, 1, -1, -1], z @ [1, -1, 1, -1],
                    z @ parity, x @ parity, y @ parity)
    return float(np.dot(COEFF, expectations))


def objective(theta):
    # Ideal probabilities emulate infinitely many shots, not noisy executions.
    return energy({b: basis_probabilities(theta, b) for b in ("Z", "X", "Y")})


def measure(theta, rng, shots=4096):
    counts = {}
    for b in ("Z", "X", "Y"):
        p = basis_probabilities(theta, b)
        counts[b] = rng.multinomial(shots, p / p.sum())
    return energy({b: c / shots for b, c in counts.items()}), counts


def optimize(rng):
    # 13 coarse evaluations + 12 refinement evaluations. Cost uses counts only.
    history = []

    def evaluate(theta):
        value, counts = measure(theta, rng)
        history.append({"theta": theta, "measured_energy_hartree": value,
                        "counts_q0_first": {b: list(map(int, c)) for b, c in counts.items()}})
        return value, theta

    best = min(evaluate(-math.pi * k / 12) for k in range(13))
    step = math.pi / 12
    for _ in range(6):
        step /= 2
        center = best[1]
        left = evaluate(max(-math.pi, center - step))
        right = evaluate(min(0.0, center + step))
        best = min(best, left, right)
    return best[1], history


def qasm(theta=None, basis="Z"):
    if theta is None:
        # Analytical reference snapshot, distinct from the noisy search result.
        theta = math.atan2(0.1820, 0.7782) - math.pi
    # Fixed snapshot only; the Python optimizer is not embedded in this QASM.
    lines = ['OPENQASM 2.0;', 'include "qelib1.inc";', 'qreg q[2];',
             'creg c[2];', 'x q[1];', f'ry({theta:.17g}) q[0];', 'cx q[0],q[1];']
    if basis == "X":
        lines += ['h q[0];', 'h q[1];']
    elif basis == "Y":
        lines += ['rx(pi/2) q[0];', 'rx(pi/2) q[1];']
    elif basis != "Z":
        raise ValueError("basis must be Z, X or Y")
    return '\n'.join(lines + ['measure q -> c;', ''])


def run():
    rng = np.random.default_rng(7)
    theta, history = optimize(rng)
    # Fresh samples, independent of the search conditional on selected theta.
    final_energy, counts = measure(theta, rng)
    # Independent reference: diagonalize this rounded 4x4 Hamiltonian.
    operators = (np.eye(4), np.kron(Z, I), np.kron(I, Z),
                 np.kron(Z, Z), np.kron(X, X), np.kron(Y, Y))
    exact = float(np.linalg.eigvalsh(sum(c * p for c, p in zip(COEFF, operators)))[0])
    return {"theta": theta, "search_evaluations": len(history),
            "backend": "local_numpy_statevector", "seed": 7,
            "ideal_energy_at_selected_theta_hartree": objective(theta),
            "exact_rounded_model_energy_hartree": exact,
            "ideal_optimization_error_hartree": objective(theta) - exact,
            "fresh_sampled_energy_hartree": final_energy,
            "final_measurement_discrepancy_hartree": final_energy - objective(theta),
            "circuits": 3 * (len(history) + 1), "total_shots": 3 * (len(history) + 1) * 4096,
            "shots_per_basis": 4096,
            "search_history": history,
            "counts_q0_first": {b: dict(zip(("00", "01", "10", "11"), map(int, c)))
                                for b, c in counts.items()}}


if __name__ == "__main__":
    print(json.dumps(run(), indent=2))

Try a fixed circuit in Marqov

The three OpenQASM snapshots use the analytical minimizing angle. They show Z, X and Y measurements of that fixed state, not the noisy optimizer’s selected state and not an automatic optimization loop.

Open Run in Marqov →

Save existing editor work, open Marqov and sign in if required. Set the editor format to OpenQASM and paste a circuit below. Choose an available browser simulator and run explicitly. The link opens the editor; it does not load code or start execution. These tutorial circuits are not in the Examples dropdown.

These Python scripts label bitstrings with q0 on the left. Before comparing editor or native framework output, check the displayed wire and classical-bit order and convert it to the same convention.

vqe-h2-z.qasm
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
x q[1];
ry(-2.9118489413160495) q[0];
cx q[0],q[1];
measure q -> c;
Download vqe-h2-z.qasm
vqe-h2-x.qasm
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
x q[1];
ry(-2.9118489413160495) q[0];
cx q[0],q[1];
h q[0];
h q[1];
measure q -> c;
Download vqe-h2-x.qasm
vqe-h2-y.qasm
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
x q[1];
ry(-2.9118489413160495) q[0];
cx q[0],q[1];
rx(pi/2) q[0];
rx(pi/2) q[1];
measure q -> c;
Download vqe-h2-y.qasm

Change one thing

  • Compare the selected angle’s exact energy with the ground energy to quantify remaining optimization error.
  • Change the local random seed and inspect the search history and fresh final energy rather than just the best noisy estimate.

Scope and verification

  • One geometry and a rounded model are not a dissociation curve, a new ab initio chemistry calculation or a reproduction of the paper’s hardware experiment.
  • The tutorial uses a bounded teaching search, not the paper’s optimizer. Its statevector simulation and sampled measurements are local and ideal.
  • The editor snapshot prepares one fixed state. Running only its Z-basis circuit does not calculate an energy; energy requires all three bases and classical aggregation.

Checks compare the Python state and OpenQASM gates with independent mathematical references, including complex phases where needed. Sampling checks use the circuit’s own predicted distribution. Local mathematical checks do not establish hosted or hardware qualification.

Learning tutorial or research replication?

The research reference investigates thirteen geometries with retained local results and a different optimizer and ansatz parameterization. This one-geometry learning workflow has its own samples and budget. The existing Fixed-Angle Ansatz editor example remains a separate state-preparation demo.

Read the H₂ VQE research replication →

References and provenance

Uses the reviewed H₂ replication’s corrected v2 coefficients and three-basis measurement approach. The teaching ansatz and bounded search are new; no historical research measurements are reused.

Learning scope reviewed with the Replications project, October 17, 2026. The local Python scripts and fixed circuit snapshots are separate from the source-pinned twelve-example editor catalog.

Explore all learning tutorials →