Skip to content

API Reference

The TQC API is organized into several key modules, each handling different aspects of topological quantum compilation.

Overview

TQC provides a clean, well-documented Python API for topological quantum compilation:

import tqc

# Main components
compiler = tqc.TopologicalCompiler(tqc.FibonacciAnyons())
braid = tqc.BraidWord([tqc.BraidGenerator(0, tqc.BraidDirection.OVER)], 2) 
simulator = tqc.AnyonicSimulator(tqc.FibonacciAnyons())
optimizer = tqc.BraidOptimizer(tqc.FibonacciAnyons())

Core Modules

Compiler Module

Main topological compiler that translates quantum circuits to braid programs.

CompilationResult dataclass

Result of compiling a quantum circuit to braids.

Attributes:

Name Type Description
braid_program BraidWord

The compiled braid word

anyon_mapping Dict[int, int]

Maps qubits to anyon positions

fidelity_estimate float

Estimated compilation fidelity

original_circuit QuantumCircuit

Original quantum circuit

compilation_stats Dict[str, Any]

Statistics about the compilation process

TopologicalCompiler

Universal compiler for quantum circuits using topological braiding.

This class implements the core TQC functionality: translating standard quantum gate sequences into fault-tolerant anyonic braiding operations.

The compilation process involves: 1. Mapping qubits to anyonic degrees of freedom 2. Decomposing gates into universal gate sets 3. Approximating gates with braid sequences 4. Optimizing braid length and fidelity

Example

from tqc import TopologicalCompiler, FibonacciAnyons from qiskit import QuantumCircuit

compiler = TopologicalCompiler(FibonacciAnyons()) qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1)

result = compiler.compile(qc) print(f"Compiled to {len(result.braid_program)} braids") print(f"Fidelity: {result.fidelity_estimate:.4f}")

__init__(anyon_type, optimization_level=1, target_fidelity=0.99, max_braid_length=None)

Initialize the topological compiler.

Parameters:

Name Type Description Default
anyon_type AnyonType

Type of anyons to use for compilation

required
optimization_level int

Level of optimization (0-3) 0: No optimization 1: Basic simplification 2: Solovay-Kitaev approximation 3: Advanced heuristic search

1
target_fidelity float

Target compilation fidelity

0.99
max_braid_length Optional[int]

Maximum allowed braid word length

None

Raises:

Type Description
ValueError

If parameters are invalid

compile(circuit, anyon_layout=None)

Compile a quantum circuit into a topological braid program.

Parameters:

Name Type Description Default
circuit QuantumCircuit

Qiskit quantum circuit to compile

required
anyon_layout Optional[Dict[int, int]]

Optional mapping from qubits to anyon positions

None

Returns:

Type Description
CompilationResult

CompilationResult containing the braid program and metadata

Raises:

Type Description
ValueError

If circuit cannot be compiled

The main compilation engine that translates quantum circuits to braid sequences.

Key Classes: - TopologicalCompiler - Main compiler class - CompilationResult - Results of compilation process

Anyons Module

Core anyonic types and their algebraic structures.

AnyonType

Bases: ABC

Abstract base class for anyon types and their algebraic properties.

__init__(name, quantum_dimension)

Initialize anyon type.

Parameters:

Name Type Description Default
name str

Human-readable name of the anyon type

required
quantum_dimension float

Quantum dimension of the anyon

required

Raises:

Type Description
ValueError

If quantum dimension is not positive

f_matrix(a, b, c, d) abstractmethod

Get F-matrix for pentagon equation.

The F-matrix relates different ways of associating triple fusion: (a ⊗ b) ⊗ c ≅ a ⊗ (b ⊗ c)

Parameters:

Name Type Description Default
a, (b, c, d)

Anyon labels for the transformation

required

Returns:

Type Description
ndarray

Complex matrix representing the F-transformation

Raises:

Type Description
ValueError

If transformation is not defined

fusion_rules(a, b) abstractmethod

Get fusion outcomes for two anyons.

Parameters:

Name Type Description Default
a str

First anyon label

required
b str

Second anyon label

required

Returns:

Type Description
Dict[str, complex]

Dictionary mapping outcome labels to fusion coefficients

Raises:

Type Description
ValueError

If anyon labels are invalid

get_labels() abstractmethod

Get all anyon labels for this type.

Returns:

Type Description
List[str]

List of string labels identifying each anyon species

r_matrix(a, b) abstractmethod

Get R-matrix for braiding transformation.

The R-matrix gives the phase for exchanging two anyons: a ⊗ b → b ⊗ a

Parameters:

Name Type Description Default
a str

First anyon label

required
b str

Second anyon label

required

Returns:

Type Description
complex

Complex phase for the braiding transformation

validate_labels(labels)

Validate that all labels are recognized anyon types.

Parameters:

Name Type Description Default
labels List[str]

List of anyon labels to validate

required

Raises:

Type Description
ValueError

If any label is not recognized

FibonacciAnyons

Bases: AnyonType

Fibonacci anyons - the simplest universal anyon type.

Fibonacci anyons have two species: I (identity) and τ (tau). The fusion rule is: τ × τ = I + τ

This is the most studied anyon type for topological quantum computation because it's universal for quantum computation and has relatively simple structure.

f_matrix(a, b, c, d)

F-matrices for Fibonacci anyons.

fusion_rules(a, b)

Fibonacci fusion rules.

Rules: - I × I = I - I × τ = τ × I = τ
- τ × τ = I + τ (both outcomes with equal weight)

get_labels()

Get Fibonacci anyon labels: ['I', 'τ'].

r_matrix(a, b)

R-matrices (braiding phases) for Fibonacci anyons.

FusionChannel

Bases: Enum

Enumeration of possible fusion channels.

FusionRule dataclass

Represents a fusion rule between anyons.

Attributes:

Name Type Description
left str

First anyon in fusion

right str

Second anyon in fusion

result Dict[str, complex]

Possible fusion outcomes with coefficients

__post_init__()

Validate fusion rule after initialization.

IsingAnyons

Bases: AnyonType

Ising anyons - related to the 2D Ising model at criticality.

Ising anyons have three species: I (identity), σ (sigma), ψ (psi). Key fusion rules: - σ × σ = I + ψ - σ × ψ = σ
- ψ × ψ = I

f_matrix(a, b, c, d)

F-matrices for Ising anyons.

fusion_rules(a, b)

Ising anyon fusion rules.

get_labels()

Get Ising anyon labels: ['I', 'σ', 'ψ'].

r_matrix(a, b)

R-matrices for Ising anyons.

get_anyon_type(name)

Factory function to create anyon type by name.

Parameters:

Name Type Description Default
name str

Name of anyon type ('fibonacci', 'ising', etc.)

required

Returns:

Type Description
AnyonType

Instance of the requested anyon type

Raises:

Type Description
ValueError

If anyon type is not recognized

Example

from tqc.anyons import get_anyon_type fib = get_anyon_type('fibonacci') print(fib.quantum_dimension) 1.618...

Anyon types and their mathematical properties.

Key Classes: - AnyonType - Abstract base class for anyon types - FibonacciAnyons - Fibonacci anyon implementation - IsingAnyons - Ising anyon implementation

Braids Module

Braid group operations and representations.

BraidDirection

Bases: Enum

Direction of braid crossing.

BraidGenerator dataclass

A single braid generator σᵢ or σᵢ⁻¹.

Represents the exchange of strands i and i+1 in an n-strand braid.

Attributes:

Name Type Description
index int

Which pair of strands to exchange (0-indexed)

direction BraidDirection

Whether this is σᵢ (OVER) or σᵢ⁻¹ (UNDER)

Example

gen = BraidGenerator(0, BraidDirection.OVER) # σ₀ inv_gen = BraidGenerator(0, BraidDirection.UNDER) # σ₀⁻¹

__post_init__()

Validate generator after creation.

__repr__()

Detailed string representation.

__str__()

String representation of the generator.

inverse()

Get the inverse of this generator.

Returns:

Type Description
BraidGenerator

BraidGenerator with opposite direction

BraidWord dataclass

A word in the braid group B_n.

Represents a sequence of braid generators that can be applied to a set of n strands. This is the fundamental data structure for representing braided computations.

Attributes:

Name Type Description
generators List[BraidGenerator]

Sequence of braid generators

n_strands int

Number of strands in the braid

metadata Dict[str, Any]

Optional metadata (anyon labels, etc.)

__len__()

Get the length (number of generators) of the braid word.

__mul__(other)

Multiply (concatenate) two braid words.

Parameters:

Name Type Description Default
other BraidWord

BraidWord to multiply with

required

Returns:

Type Description
BraidWord

New BraidWord representing the product

__post_init__()

Validate braid word after creation.

__repr__()

Detailed string representation.

__str__()

String representation of the braid word.

append(generator)

Add a generator to the end of the braid word.

Parameters:

Name Type Description Default
generator BraidGenerator

Braid generator to append

required

Raises:

Type Description
ValueError

If generator index is too large for this braid

extend(other)

Concatenate another braid word to this one.

Parameters:

Name Type Description Default
other BraidWord

BraidWord to concatenate

required

Raises:

Type Description
ValueError

If braids have different numbers of strands

inverse()

Compute the inverse of this braid word.

The inverse is obtained by reversing the sequence and taking the inverse of each generator.

Returns:

Type Description
BraidWord

New BraidWord representing the inverse braid

simplify()

Apply basic simplification rules to reduce braid word length.

Applies: 1. σᵢ σᵢ⁻¹ = e (generator-inverse cancellation) 2. σᵢ⁻¹ σᵢ = e

Returns:

Type Description
BraidWord

Simplified BraidWord (new instance)

to_permutation()

Convert braid word to the permutation it induces on strand labels.

Returns:

Type Description
List[int]

List where result[i] is the final position of strand i

Example

braid = BraidWord([BraidGenerator(0, BraidDirection.OVER)], 3) braid.to_permutation() [1, 0, 2] # Strands 0 and 1 are swapped

visualize(filename=None, show_labels=True, colormap='tab10')

Generate a visual representation of the braid.

Creates an SVG diagram showing the braiding pattern with over/under crossings clearly marked.

Parameters:

Name Type Description Default
filename Optional[str]

If provided, save SVG to this file

None
show_labels bool

Whether to show anyon labels

True
colormap str

Matplotlib colormap for strand colors

'tab10'

Returns:

Type Description
str

SVG markup as string

create_braid_from_permutation(perm)

Create a braid word that realizes a given permutation.

Uses the bubble sort algorithm to construct a minimal-length braid word for the given permutation.

Parameters:

Name Type Description Default
perm List[int]

Target permutation as a list

required

Returns:

Type Description
BraidWord

BraidWord that induces the given permutation

Example

braid = create_braid_from_permutation([1, 0, 2]) str(braid) 'σ_0'

Braid group operations and representations.

Key Classes: - BraidWord - Sequence of braid generators - BraidGenerator - Single braiding operation - BraidDirection - Direction enumeration (OVER/UNDER)

Simulation Module

Anyonic simulation engine using tensor networks and linear algebra.

AnyonicSimulator

Efficient simulator for anyonic quantum computations.

Uses tensor network methods and sparse linear algebra to simulate braiding operations on systems with many anyons.

__init__(anyon_type, max_bond_dimension=None)

Initialize the simulator.

Parameters:

Name Type Description Default
anyon_type AnyonType

Type of anyons to simulate

required
max_bond_dimension Optional[int]

Maximum bond dimension for tensor networks

None

benchmark_performance(max_anyons=10)

Benchmark simulation performance vs. number of anyons.

Parameters:

Name Type Description Default
max_anyons int

Maximum number of anyons to test

10

Returns:

Type Description
Dict[int, float]

Dictionary mapping n_anyons to simulation time

compute_expectation_value(braid_program, observable, initial_state=None)

Compute expectation value of an observable.

Parameters:

Name Type Description Default
braid_program BraidWord

Braid program to apply

required
observable str

Observable to measure ('X', 'Y', 'Z', etc.)

required
initial_state Optional[AnyonicState]

Initial state

None

Returns:

Type Description
float

Expectation value

simulate(braid_program, shots=1000, initial_state=None)

Simulate a braided quantum computation.

Parameters:

Name Type Description Default
braid_program BraidWord

Braid word to simulate

required
shots int

Number of measurement shots

1000
initial_state Optional[AnyonicState]

Initial anyonic state (default: all identity)

None

Returns:

Type Description
SimulationResult

SimulationResult with measurement outcomes

simulate_statevector(braid_program, initial_state=None)

Simulate braid program and return final statevector.

Parameters:

Name Type Description Default
braid_program BraidWord

Braid word to simulate

required
initial_state Optional[AnyonicState]

Initial state

None

Returns:

Type Description
AnyonicState

Final anyonic state after braiding

AnyonicState

Represents the quantum state of a system of anyons.

The state is represented using the fusion tree basis, where each basis state corresponds to a particular way of fusing the anyons from left to right.

__init__(anyon_type, n_anyons, anyon_labels)

Initialize anyonic state.

Parameters:

Name Type Description Default
anyon_type AnyonType

Type of anyons in the system

required
n_anyons int

Number of anyons

required
anyon_labels List[str]

Labels for each anyon

required

Raises:

Type Description
ValueError

If parameters are inconsistent

apply_braid(generator)

Apply a braid generator to the anyonic state.

Parameters:

Name Type Description Default
generator BraidGenerator

Braid generator to apply

required

Raises:

Type Description
ValueError

If generator is invalid for this state

copy()

Create a copy of this state.

get_fidelity(target_state)

Compute fidelity with respect to target state.

measure(measurement_basis=None)

Perform a measurement on the anyonic state.

Parameters:

Name Type Description Default
measurement_basis Optional[str]

Basis for measurement ('computational', 'fusion', etc.)

None

Returns:

Type Description
Tuple[str, float]

Tuple of (outcome, probability)

SimulationResult dataclass

Result of simulating a braided quantum computation.

Attributes:

Name Type Description
counts Dict[str, int]

Measurement outcome counts

statevector Optional[ndarray]

Final quantum state (if available)

fidelity Optional[float]

Fidelity with respect to ideal computation

simulation_time float

Time taken for simulation

metadata Dict[str, Any]

Additional simulation information

total_shots property

Total number of measurement shots.

get_probabilities()

Get measurement probabilities from counts.

Efficient simulation of anyonic quantum systems.

Key Classes: - AnyonicSimulator - Main simulation engine - AnyonicState - Quantum state of anyonic system
- SimulationResult - Results of simulation

Optimization Module

Braid optimization algorithms including Solovay-Kitaev approximation.

ApproximationResult dataclass

Result of approximating a unitary with braids.

Attributes:

Name Type Description
braid_word BraidWord

Approximating braid sequence

fidelity float

Approximation fidelity

iterations int

Number of optimization iterations

computation_time float

Time taken for approximation

BraidOptimizer

Main optimization engine combining multiple strategies.

__init__(anyon_type, target_fidelity=0.99)

Initialize the optimizer.

Parameters:

Name Type Description Default
anyon_type AnyonType

Type of anyons to optimize for

required
target_fidelity float

Target approximation fidelity

0.99

approximate_rotation(axis, angle, anyon_pos)

Approximate single-qubit rotation with braids.

Parameters:

Name Type Description Default
axis str

Rotation axis ('X', 'Y', 'Z')

required
angle float

Rotation angle in radians

required
anyon_pos int

Position of anyon to rotate

required

Returns:

Type Description
BraidWord

BraidWord approximating the rotation

approximate_unitary(unitary, n_anyons, target_fidelity=None)

Approximate a unitary matrix with braids.

Parameters:

Name Type Description Default
unitary ndarray

Target unitary matrix

required
n_anyons int

Number of anyons to use

required
target_fidelity Optional[float]

Target approximation fidelity

None

Returns:

Type Description
ApproximationResult

ApproximationResult with approximating braid and metadata

optimize(braid, target_fidelity=None, strategy='auto')

Optimize a braid word using the specified strategy.

Parameters:

Name Type Description Default
braid BraidWord

Input braid word to optimize

required
target_fidelity Optional[float]

Target fidelity (default: use instance default)

None
strategy str

Optimization strategy ('auto', 'greedy', 'solovay_kitaev', 'heuristic')

'auto'

Returns:

Type Description
BraidWord

Optimized braid word

GreedySimplification

Bases: OptimizationStrategy

Greedy simplification using braid relations.

optimize(braid, target_fidelity)

Apply greedy simplification rules.

HeuristicSearch

Bases: OptimizationStrategy

Heuristic search for optimal braid sequences.

Uses A* search or beam search to find short, high-fidelity braid approximations for target unitaries.

__init__(anyon_type, search_type='astar', beam_width=100, max_nodes=10000)

Initialize heuristic search.

Parameters:

Name Type Description Default
anyon_type AnyonType

Type of anyons

required
search_type str

Search algorithm ('astar', 'beam')

'astar'
beam_width int

Beam width for beam search

100
max_nodes int

Maximum nodes to explore

10000

optimize(braid, target_fidelity)

Optimize using heuristic search.

OptimizationStrategy

Bases: ABC

Abstract base class for braid optimization strategies.

optimize(braid, target_fidelity) abstractmethod

Optimize a braid word.

Parameters:

Name Type Description Default
braid BraidWord

Input braid word to optimize

required
target_fidelity float

Target approximation fidelity

required

Returns:

Type Description
BraidWord

Optimized braid word

SolovayKitaevApproximation

Bases: OptimizationStrategy

Solovay-Kitaev algorithm adapted for anyonic braiding.

The Solovay-Kitaev algorithm efficiently approximates arbitrary unitaries using a finite set of generators. Here we adapt it to find short braid sequences that approximate given unitaries to high precision.

__init__(anyon_type, base_generators=None, recursion_depth=10)

Initialize Solovay-Kitaev approximator.

Parameters:

Name Type Description Default
anyon_type AnyonType

Type of anyons to work with

required
base_generators Optional[List[BraidGenerator]]

Basic braid generators to use

None
recursion_depth int

Maximum recursion depth

10

approximate_rotation(axis, angle, anyon_pos)

Approximate a rotation gate with braids.

Parameters:

Name Type Description Default
axis str

Rotation axis ('X', 'Y', 'Z')

required
angle float

Rotation angle in radians

required
anyon_pos int

Position of anyon to rotate

required

Returns:

Type Description
BraidWord

BraidWord approximating the rotation

optimize(braid, target_fidelity)

Apply Solovay-Kitaev optimization.

Algorithms for optimizing braid sequences.

Key Classes: - BraidOptimizer - Main optimization engine - OptimizationStrategy - Abstract optimization strategy - SolovayKitaevApproximation - SK algorithm implementation

Utility Functions

Factory Functions

# Create compiler with anyon type name
compiler = tqc.create_compiler('fibonacci', optimization_level=2)

# Get supported anyon types
anyon_types = tqc.get_supported_anyons()
print(anyon_types)  # ['fibonacci', 'ising', 'su2_k3']

Version Information

import tqc
print(tqc.__version__)  # Current TQC version

Detailed API Documentation

For complete API documentation with all classes, methods, and parameters, see the individual module pages: