Synthesize unitaries to Clifford+T
Explore unitary synthesis and the fo-synth-core Python API
Fault-tolerant quantum algorithms must approximate arbitrary unitary operations using a discrete gate set. Clifford gates alone are not universal; adding the non-Clifford T gate enables universal quantum computation through approximation. T gates typically consume costly magic-state resources, making T-count an important measure of synthesis cost.
The fo-synth-core package synthesizes single-qubit and two-qubit unitaries into Clifford+T gate words. It accepts numerical targets directly, without a circuit framework. If you instead want to compile entire Qiskit circuits, use the separate fo-synth-qiskit package.
In this tutorial, you will synthesize a single-qubit target, verify its approximation error, explore the accuracy/resource tradeoff, and synthesize an entangling two-qubit target. An advanced appendix explains the remaining public APIs.
Install and import the package
Use Python 3.11 or newer. Install the package and NumPy into the Python environment used by your Jupyter kernel:
pip install fo-synth-core numpyRestart the kernel if you installed or upgraded packages while it was running. NumPy is used here to construct targets and independently check the results.
from time import perf_counter
import numpy as np
from fo_synth_core import (
GateMetric,
clear_synthesis_cache,
synthesize_su2,
synthesize_su4,
)Synthesize a single-qubit unitary
An SU(2) matrix is a single-qubit unitary with determinant one. It can be specified by two complex numbers, alpha and beta, with abs(alpha)**2 + abs(beta)**2 = 1:
U = [[alpha, -conj(beta)],
[beta, conj(alpha)]]The synthesize_su2 function takes these two entries, not the full matrix:
| Argument | Meaning |
|---|---|
alpha, beta | Finite complex entries satisfying the normalization above |
tolerance | Required maximum operator-norm error up to global phase; finite and in (0, 1] |
The returned word has the lowest T-count among solutions within your tolerance. If no solution is found, the function raises an error rather than returning a less accurate word. You can try a larger tolerance if your application permits a coarser approximation.
Start with a target that is not just a rotation about a coordinate axis.
alpha = 0.6 * np.exp(-0.2j)
beta = 0.8
target_su2 = np.array([[alpha, -np.conj(beta)], [beta, np.conj(alpha)]])
tolerance = 1e-3
single_result = synthesize_su2(alpha, beta, tolerance=tolerance)
print("Gate word:", single_result.gates)
print("T-count:", single_result.t_count)
print("CNOT count:", single_result.cnot_count)
print(f"Reported error: {single_result.operator_error:.3e}")Gate word: SSSHSHTHTHTSHTHTHTSHTHTSHTHTHTHTSHTHTHTHTSHTHTSHTHTHTSHTHTSHTHTSHTHSSWSHSHWWWWW
T-count: 26
CNOT count: 0
Reported error: 5.403e-04
The result is a CliffordTWord; its fields are gates (the gate word), t_count, operator_error, and cnot_count. The CNOT count is always zero for single-qubit synthesis. You can inspect fields directly, or use model_dump() to obtain a dictionary.
For a single-qubit word, the allowed gates are H, S, T, X, I (identity), and W (the global phase exp(i * pi / 4) times identity). A word is a matrix product written left to right, so its rightmost gate acts first. For example, HT represents the matrix H @ T: apply T, then H.
The following helper reconstructs that product.
identity = np.eye(2, dtype=complex)
phase = np.exp(1j * np.pi / 4)
gates = {
"H": np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2),
"S": np.diag([1, 1j]),
"T": np.diag([1, phase]),
"X": np.array([[0, 1], [1, 0]], dtype=complex),
"W": phase * identity,
"I": identity,
}
def su2_word_matrix(word):
"""Reconstruct a single-qubit word in matrix-product order."""
matrix = identity.copy()
for letter in word:
matrix = matrix @ gates[letter]
return matrix
single_matrix = su2_word_matrix(single_result.gates)
assert single_result.t_count == single_result.gates.count("T")Verify approximation error
The operator norm of a matrix is its largest singular value. For the difference between target unitary U and approximation V, it measures the largest output-state-vector difference over normalized inputs. Here, error is minimized over a global phase: min_phi ||U - exp(i * phi) V||_op. Unitaries differing only by a global phase therefore have zero error.
The helper below finds the shortest arc containing the eigenphases of U.conj().T @ V. Centering this arc gives the optimal phase adjustment, and its width determines the distance. It works for both matrix sizes used here. Constructing full matrices scales exponentially with qubit count, so this is not intended for verifying large circuits.
def operator_error(target, candidate):
"""Return the operator-norm distance between unitaries up to global phase."""
relative = target.conj().T @ candidate
full_turn = 2 * np.pi
phases = np.sort(np.angle(np.linalg.eigvals(relative)) % full_turn)
gaps = np.diff(np.append(phases, phases[0] + full_turn))
arc_width = full_turn - np.max(gaps)
return float(2 * np.sin(arc_width / 4))
measured_error = operator_error(target_su2, single_matrix)
print(f"Measured error: {measured_error:.3e}")
print(f"Requested tolerance: {tolerance:.3e}")
assert measured_error <= tolerance + 1e-10
assert np.isclose(measured_error, single_result.operator_error, atol=1e-10)Measured error: 5.403e-04
Requested tolerance: 1.000e-03
Trade approximation accuracy for synthesis cost
Smaller tolerances require closer approximations and typically increase the T-count and search effort. Synthesize the same target at several tolerances and compare the independently measured errors and resource counts.
Repeated synthesis calls can reuse previously computed results. Before each timed call below, clear_synthesis_cache() removes cached results and resets the cache counters without changing its capacity. This prevents a result from an earlier call from making synthesis appear faster.
tolerances = [1e-2, 3e-3, 1e-3]
repeats = 200
for requested in tolerances:
clear_synthesis_cache()
synthesize_su2(alpha, beta, tolerance=requested)
timings = {requested: [] for requested in tolerances}
tolerance_results = {}
for _ in range(repeats):
for requested in tolerances:
clear_synthesis_cache()
start = perf_counter()
result = synthesize_su2(alpha, beta, tolerance=requested)
elapsed = perf_counter() - start
timings[requested].append(elapsed)
tolerance_results[requested] = result
print(f"{'Tolerance':>10} {'Error':>11} {'T-count':>8} {'Median ms':>10}")
for requested in tolerances:
result = tolerance_results[requested]
median_ms = 1e3 * np.median(timings[requested])
measured = operator_error(target_su2, su2_word_matrix(result.gates))
print(f"{requested:10.0e} {measured:11.3e} {result.t_count:8d} {median_ms:10.3f}")
assert measured <= requested + 1e-10
assert np.isclose(measured, result.operator_error, atol=1e-10)
assert result.t_count == result.gates.count("T") Tolerance Error T-count Median ms
1e-02 8.700e-03 15 0.164
3e-03 2.222e-03 23 0.221
1e-03 5.403e-04 26 0.332
For this target, tightening the tolerance produces a more accurate approximation at the cost of more T gates and a longer median synthesis time. These are two distinct costs: T-count reflects resources needed to implement the result, while synthesis time is the classical computation needed to find it. Choose a tolerance that meets your algorithm's error budget without paying for unnecessary accuracy.
Very small tolerances emit warnings.
The synthesizer warns when called with tolerance <= 1e-8.
Such tolerances may significantly extend synthesis time and/or fail to find a solution. Also, only devices with a QEC error per cycle ~1e-20 could take advantage of such accurate synthesis, whereas current long-term projections for achievable error per cycle are larger.
Synthesize a two-qubit unitary
The synthesize_su4 function accepts a finite, unitary 4x4 matrix as a row-major nested sequence and a required tolerance in (0, 1]. Note that you do not need to remove an input matrix's global phase or enforce determinant one. Qubit 0 is the most significant tensor factor: the basis order is |00>, |01>, |10>, |11>.
Below, combine XX and ZZ interactions. Each interaction has the form cos(angle / 2) I - i sin(angle / 2) P, where P is the tensor product of two Pauli matrices. This gives a genuinely entangling target, rather than a product of independent single-qubit gates.
The optional metric argument defaults to GateMetric.OPERATOR_NORM (also accepted as "operator_norm"). This is the same global-phase-minimized distance used above. SU(4) synthesis returns a word within the requested distance.
pauli_x = gates["X"]
pauli_z = np.diag([1, -1])
def interaction(pauli, angle):
return np.cos(angle / 2) * np.eye(4) - 1j * np.sin(angle / 2) * np.kron(
pauli, pauli
)
target_su4 = interaction(pauli_x, 0.31) @ interaction(pauli_z, 0.17)
two_qubit_tolerance = 1e-2
two_qubit_result = synthesize_su4(target_su4.tolist(), tolerance=two_qubit_tolerance)
print("Gate word:", two_qubit_result.gates)
print("T-count:", two_qubit_result.t_count)
print("CNOT count:", two_qubit_result.cnot_count)
print(f"Reported error: {two_qubit_result.operator_error:.3e}")Gate word: I0 I1 CX0,1 W0 W0 W0 W0 W0 S0 S0 X0 T0 H0 T0 H0 T0 H0 S0 T0 H0 T0 H0 S0 T0 H0 S0 T0 H0 T0 H0 S0 T0 H0 S0 T0 H0 S0 T0 H0 S0 T0 H0 S0 T0 H0 T0 H0 T0 H0 S0 T0 H0 S0 T0 H0 T0 H0 S0 T0 H0 T0 H0 T0 H0 T0 H0 S0 T0 W1 W1 S1 S1 S1 X1 H1 S1 T1 H1 T1 H1 T1 H1 T1 H1 S1 T1 H1 T1 H1 S1 T1 H1 T1 H1 T1 H1 T1 H1 S1 T1 H1 S1 T1 H1 S1 T1 H1 T1 H1 T1 H1 S1 T1 H1 S1 T1 H1 S1 T1 H1 S1 T1 H1 T1 H1 T1 H1 T1 CX0,1 I0 I1
T-count: 45
CNOT count: 2
Reported error: 5.290e-03
Two-qubit gate words use a different ordering convention. Their space-separated tokens appear in execution order, from left to right. Thus H0 T1 CX0,1 means apply H on qubit 0, then T on qubit 1, then a CNOT controlled by qubit 0 targeting qubit 1. Its matrix is CX0,1 @ T1 @ H0.
Single-qubit letters have the qubit index appended, including I0 and W1. CX1,0 reverses the CNOT control and target. The helper below uses the stated tensor-factor order and left-multiplies each gate to replay this execution order.
cnot_gates = {
"CX0,1": np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]),
"CX1,0": np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]),
}
def su4_word_matrix(word):
"""Reconstruct a two-qubit word in execution order; qubit 0 is most significant."""
matrix = np.eye(4, dtype=complex)
for token in word.split():
if token in cnot_gates:
gate = cnot_gates[token]
else:
local = gates[token[0]]
if token[1] == "0":
gate = np.kron(local, identity)
else:
gate = np.kron(identity, local)
matrix = gate @ matrix
return matrix
two_qubit_matrix = su4_word_matrix(two_qubit_result.gates)
measured = operator_error(target_su4, two_qubit_matrix)
tokens = two_qubit_result.gates.split()
print(f"Measured operator-norm error: {measured:.3e}")
assert measured <= two_qubit_tolerance + 1e-10
assert np.isclose(measured, two_qubit_result.operator_error, atol=1e-10)
assert two_qubit_result.t_count == sum(token in ("T0", "T1") for token in tokens)
assert two_qubit_result.cnot_count == sum(token in cnot_gates for token in tokens)Measured operator-norm error: 5.290e-03
Choose the distance for two-qubit synthesis
The other option is GateMetric.FIDELITY (or "fidelity"). Its distance is sqrt(1 - abs(trace(U.conj().T @ V)) / 4). It is invariant under global phase, but it is not average gate infidelity, and a numerical tolerance in this metric is not the same requirement as that tolerance in operator norm.
For SU(4), operator_error contains the distance in the selected metric, despite its name. Keep track of the metric alongside the result; the result model does not store it. Below, request the fidelity metric explicitly and verify that distance rather than comparing it with the operator-norm tolerance.
fidelity_result = synthesize_su4(
target_su4.tolist(), tolerance=two_qubit_tolerance, metric=GateMetric.FIDELITY
)
fidelity_matrix = su4_word_matrix(fidelity_result.gates)
trace_overlap = abs(np.trace(target_su4.conj().T @ fidelity_matrix)) / 4
fidelity_distance = np.sqrt(np.clip(1 - trace_overlap, 0, 1))
print(f"Measured fidelity distance: {fidelity_distance:.3e}")
print(f"Reported distance: {fidelity_result.operator_error:.3e}")
print(f"Operator-norm distance: {operator_error(target_su4, fidelity_matrix):.3e}")
assert fidelity_distance <= two_qubit_tolerance + 1e-10
assert np.isclose(fidelity_distance, fidelity_result.operator_error, atol=1e-10)Measured fidelity distance: 2.645e-03
Reported distance: 2.645e-03
Operator-norm distance: 5.290e-03
Choose settings for your own unitaries
You can now supply a normalized single-qubit target or a two-qubit unitary, interpret its gate word, and verify its approximation. Choose a tolerance that meets your accuracy needs, and compare the resulting T-count and CNOT count rather than assuming one resource determines the entire cost.
Each tolerance applies to the one target passed to that call, not to an entire algorithm. When composing approximations measured in operator norm, the sum of their individual error bounds is a conservative bound on the full product's error. For N synthesized operations and an overall operator-norm budget of epsilon, assigning each at most epsilon / N is sufficient. Do not apply that rule directly to the fidelity-distance option.
To explore performance beyond the examples here, use our fo-synth-benchmarks package to test the Fire Opal synthesizer against a broad variety of synthesis targets.
Follow the Benchmark Clifford+T synthesis tutorial to compare synthesis runtime and T-counts across targets.
Advanced appendix: additional public APIs
Inspect the synthesis cache
synthesis_cache_info() returns an immutable CacheInfo model describing the process-global SU(2) synthesis cache. Repeating an identical target with the same tolerance can reuse a previous result. A nearby target or a different tolerance is not an exact repeat. Two-qubit synthesis may use this cache for its constituent single-qubit searches; it is not a cache of complete two-qubit results.
| Field | Meaning |
|---|---|
hits | Successful result-cache lookups |
misses | Result-cache lookups that did not find the exact requested target |
entries | Number of retained results |
capacity | Maximum retained results before least-recently-used eviction |
anchor_hits, anchor_misses, anchor_entries | Reserved counters, currently zero |
Synthesize a Z rotation with gridsynth
gridsynth_rz(theta, epsilon) uses the gridsynth algorithm to approximate Rz(theta) = diag(exp(-i * theta / 2), exp(i * theta / 2)). Supply a finite angle in radians and a finite precision epsilon in (0, 1]. The implementation uses a fixed random seed.
It returns the same single-qubit word representation as the main synthesis interface, with its T-count and global-phase-minimized operator-norm error. This function can be used to compare gridsynth against the Fire Opal synthesizer.
