Evolving Quantum Circuits
Use DEAP to evolve gate sequences and Qiskit to evaluate them. The reference expresses \(X=HZH\); the search can discover a single X gate. Five slots drawn from I, H, Z, and X keep the problem small, with identity slots excluded from gate count.
"""Evolve a small quantum circuit, then compare the winner with its reference."""
import random
from math import inf
import numpy as np
import pytest
from deap import algorithms, base, creator, tools
from hypothesis import given
from hypothesis import strategies as st
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import HGate, IGate, XGate, ZGate
from qiskit.exceptions import QiskitError
from qiskit.quantum_info import Operator
import alternative
GATES = (IGate(), HGate(), ZGate(), XGate())
TARGET = np.array([[0, 1], [1, 0]], dtype=np.complex128)
creator.create("CircuitDemoFitness", base.Fitness, weights=(-1.0, -1.0))
creator.create("CircuitDemoIndividual", list, fitness=creator.CircuitDemoFitness)
def reference_program() -> tuple[int, ...]:
"""Express X as the readable identity H Z H."""
return (1, 2, 1)
def fitness(program) -> tuple[float, float]:
"""Minimise phase-sensitive unitary error, then correct circuits' gate count."""
try:
if len(program) > 5 or any(gene not in range(len(GATES)) for gene in program):
raise ValueError("invalid genome")
circuit = QuantumCircuit(1)
for gene in program:
if gene:
circuit.append(GATES[gene], [0])
error = float(np.linalg.norm(Operator(circuit).data - TARGET))
except (ValueError, QiskitError):
return inf, inf
if not np.isfinite(error):
return inf, inf
if error > 1e-12:
return error, inf
return 0.0, float(sum(gene != 0 for gene in program))
def evolve(*, seed: int = 7, generations: int = 30):
"""Evolve a circuit, then register the winner alongside the readable reference."""
reference = reference_program()
if fitness(reference)[0] != 0:
raise ValueError("invalid reference")
random.seed(seed)
toolbox = base.Toolbox()
toolbox.register("evaluate", fitness)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutUniformInt, low=0, up=3, indpb=0.2)
toolbox.register("select", tools.selBest)
individual = creator.CircuitDemoIndividual
population = [individual(random.choices(range(4), k=5)) for _ in range(63)]
population.append(individual((*reference, 0, 0)))
population, _ = algorithms.eaMuPlusLambda(
population,
toolbox,
mu=64,
lambda_=64,
cxpb=0.5,
mutpb=0.5,
ngen=generations,
verbose=False,
)
winner = tuple(gene for gene in tools.selBest(population, 1)[0] if gene)
comparison = alternative.reference(reference_program)
@comparison.add
def evolved_x() -> tuple[int, ...]:
"""Return the frozen search result."""
return winner
return comparison
circuits = evolve() # Register all finalists before pytest collection freezes the set.
Fitness minimises unitary error first, then correct circuits’ gate count. Every correct circuit beats every incorrect one; error distance guides the remaining genomes toward correctness. Wrong or failed circuits have infinite gate cost. Qiskit’s Operator checks the whole unitary, preserving global phase: \(X\) and \(-X\) differ under this contract. The error tolerance is \(10^{-12}\).
The reference seeds the population, and DEAP retains the best parents and
offspring. After searching, evolve registers its frozen winner in a fresh
alternatives set. Normal calls still use the reference; review the result before
selecting a new default. A bounded search need not find an optimum.
Test, Score, and Benchmark the Finalists
alternative supplies every registered implementation to the same correctness
test, and .measure(len) ranks the returned circuits by gate count:
@circuits.pytest_parametrize()
def test_circuit_correctness(implementation) -> None:
"""Check the whole unitary of every registered circuit against X."""
assert fitness(implementation())[0] == 0
def test_gate_costs() -> None:
"""Rank finalists by gate count while normal calls retain the reference."""
costs = circuits.measure(len)
assert 1 <= min(costs.values()) <= max(costs.values()) == 3
assert circuits() == reference_program()
@circuits.pytest_parametrize()
@pytest.mark.benchmark(group="circuit_simulation")
def test_benchmark(benchmark, implementation) -> None:
"""Time construction and Qiskit evaluation for each registered circuit."""
assert benchmark(lambda: fitness(implementation()))[0] == 0
The shared benchmark includes circuit construction and Qiskit evaluation.
Evolution runs once before registration and pytest parametrisation, outside
timed calls. Scoring keeps the reference default unchanged; .measure()
compares output costs, while pytest-benchmark measures elapsed time.
With the demo dependencies installed:
$ python docs/examples/test_circuit_search.py
$ pytest docs/examples/test_circuit_search.py
The complete module prints costs
and gate sequences. Run it as a standalone, sequential example: DEAP uses
Python’s seeded random generator. Hypothesis tests cancelling gate words;
other tests check the real search, phase errors, and reference preservation.