ZX-calculus rewriting and circuit extraction

Import std.zx to convert a std.quantum.Circuit into a ZX diagram, reduce it, and extract an executable circuit. The resulting circuit acts on the same ordered wires and preserves the unitary up to a global phase.

import std.zx

fn main() {
    let gates = [zx.Gate.H(1), zx.Gate.Cnot(0, 1), zx.Gate.H(1),
        zx.Gate.T(0), zx.Gate.Tdg(0)]
    let original = zx.word_circuit(2, gates).unwrap()
    var diagram = zx.from_circuit(original).unwrap()
    let report = zx.full_reduce(&diagram)
    let extracted = zx.extract_circuit(diagram).unwrap()
    assert(report.after.t_count == 0, "the T phases cancel")
    assert(zx.unitary_error(original, extracted) < 1e-12, "same unitary")
}

Diagrams and tensor evaluation

Graph.new() starts an empty diagram. add_input() and add_output() append to the two ordered boundaries. add_spider(kind, phase) creates a Z or X spider, and connect(a, b, kind) connects vertices with a Simple or Hadamard edge. Vertex IDs remain stable through rewrites. is_live(id), kind(id), phase(id), and neighbors(id) inspect the diagram. Boundary vertices are single wire endpoints.

Phase.rational(num, den) represents π × num/den modulo 2π, with a positive denominator and a reduced fraction that fits in i64. Phase addition uses i128 intermediates. Phase.angle(radians) accepts arbitrary finite angles. Circuit recordings store matrices, so from_circuit recovers familiar dyadic multiples of π from their entries and retains floating-point radians for general rotations.

Conversion supports the Pauli gates, Hadamard, S and T with their adjoints, rx, ry, rz, p, CNOT, CZ, controlled phase, SWAP, Toffoli, CCZ, and positive or negative controls on general single-target unitaries. CCZ uses seven exact π/4 parity phases, and Toffoli surrounds that construction with Hadamards. Wider controls use half-angle decomposition with temporary, restored changes to existing wires. Ancilla zero-release checks are runtime assertions on the recording and are outside its unitary map.

to_matrix(graph) contracts the ZX tensors in the Z basis. It groups ordinary wires by equality and sums interior bit variables in a smallest-neighborhood order. The entries are complex f64 values in row-major order, including the diagram’s scalar, with outputs indexing rows and inputs indexing columns. The boundary limit is 12 endpoints in total, and contraction allows up to 20 remaining variables in an intermediate factor. projective_error(a, b) compares two such matrices up to a nonzero global scalar. unitary_error(a, b) runs the full recorded gate sequences on CpuSim for each basis state and a normalized complex superposition. It reports the largest amplitude error after aligning one shared global phase and supports up to ten wires.

Reduction and extraction

to_graph_like(&diagram) changes X spiders into Z spiders and applies spider fusion and degree-two identity removal. Graph-like diagrams have Hadamard edges between Z spiders and degree-one boundaries, including direct boundary-to-boundary wires. Parallel edges and loops simplify when inserted. The diagram tracks the factors from normalized Hadamards. Individual rules are callable on hand-built diagrams, including spider_fuse, id_simp, copy, bialgebra, lcomp, pivot, pivot_boundary, pivot_gadget, and gadget_fuse.

full_reduce(&diagram) alternates the basic rules with local complementation, Pauli pivots, phase-gadget pivots, and gadget fusion to a fixed point. Local complementation eliminates an interior ±π/2 spider by complementing its neighborhood and shifting the neighbors’ phases. Pivoting removes a pair of adjacent interior Pauli spiders. Gadget and boundary pivots expose phase gadgets to further simplification. Gadgets acting on the same set of target spiders add their phases. Zero gadgets disappear, and the Clifford rules absorb Clifford gadgets. The report includes before-and-after spider, Hadamard edge and non-Clifford spider counts, and step counts for each pass. The non-Clifford count is the ZX T-count for Clifford+T diagrams and counts arbitrary rotations as well. Graph-theoretic simplification · Phase gadgets and T-count reduction

extract_circuit(diagram) sweeps a graph-like diagram from its outputs toward its inputs. At each frontier it emits single-wire phase and Hadamard gates and removes frontier CZ edges. If no frontier row has one neighbor, it performs packed Gaussian elimination over F₂ and emits CNOTs for the row additions. It moves a singleton neighbor onto the frontier through a Hadamard and finishes with input Hadamards and wire swaps. Extraction returns an error for invalid boundaries or a frontier that cannot advance. extract_with_stats(diagram) also reports row additions and extraction-time gadget pivots. The reduction objective is the non-Clifford spider count. Total gate and CNOT counts can increase. Frontier extraction, Section 7

Ruler-style rewrite discovery

discover_rules(wires, depth) enumerates gate words in execution order, including the empty word. The alphabet is H, S, S†, T, T†, X and Z on each wire, with both CNOT directions, CZ and SWAP on two wires. The depth limit is six for one wire and four for two wires.

Each matrix is evaluated exactly over ℤ[1/√2, i]. Multiplying every entry by the conjugate of the first nonzero entry gives an exact projective fingerprint. Hash matches are checked against the matrix coefficients. The e-graph hash-conses identity, gate, and composition nodes, maintains e-classes with union–find and restores congruence after a merge. It represents associativity by including every split of each enumerated word. Discovery adds an equality only when the preceding rules fail to imply it. A backward deletion pass removes redundant rules in the enumerated e-graph, yielding an inclusion-minimal set for that search space. Each retained rule is checked independently on CpuSim. Rewrite Rule Inference Using Equality Saturation

saturate(wires, word, rules, term_limit) explores contextual applications of both rule directions through the input word’s length. Shorter associative contexts from the rule domain allow implied equalities to fire even when the main word has no room to grow. Cost extraction counts logical gates, with SWAP counting as one gate. A Word supports up to 12 gates. The result gives the cheapest represented word and reports whether the bounded search reached a fixed point within the term budget.

Run jihoo run examples/zx.jh for the three-Toffoli circuit, QFT-4, two-bit Cuccaro adder and gadget cancellation, followed by rule discovery and saturation. The table reports native gate counts before conversion and executable gate counts after extraction. The one-wire run enumerates 2,801 terms and retains nine rules. The two-wire run enumerates 6,175 terms and retains 145 rules. Both sample words shrink from five logical gates to one.

Esc