CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-qiskit

An open-source SDK for working with quantum computers at the level of extended quantum circuits, operators, and primitives.

Pending
Overview
Eval results
Files

transpilation.mddocs/

Circuit Transpilation

Qiskit's transpilation system optimizes and maps quantum circuits for execution on specific quantum hardware backends. It provides comprehensive pass management, hardware-aware optimization, and automatic circuit compilation pipelines.

Capabilities

Main Transpilation Interface

The primary transpilation function provides a high-level interface for circuit optimization and backend mapping.

def transpile(circuits, backend=None, basis_gates=None, inst_map=None, 
              coupling_map=None, backend_properties=None, initial_layout=None,
              layout_method=None, routing_method=None, translation_method=None,
              scheduling_method=None, instruction_durations=None, dt=None,
              approximation_degree=None, timing_constraints=None, seed_transpiler=None,
              optimization_level=None, callback=None, output_name=None, 
              unroll_3q=None, target=None, hls_config=None, init_method=None,
              optimization_method=None):
    """
    Transpile quantum circuits for a backend.
    
    Parameters:
    - circuits: Circuit or list of circuits to transpile
    - backend: Target backend (provides coupling_map, basis_gates, etc.)
    - basis_gates: Allowed gate set for target backend
    - coupling_map: Coupling constraints between qubits
    - backend_properties: Backend calibration data
    - initial_layout: Initial qubit mapping
    - layout_method: Qubit layout algorithm ('trivial', 'dense', 'noise_adaptive', 'sabre')
    - routing_method: Routing algorithm ('basic', 'lookahead', 'stochastic', 'sabre')
    - translation_method: Basis translation method ('translator', 'synthesis', 'unroller')
    - scheduling_method: Instruction scheduling method ('alap', 'asap')
    - optimization_level: Optimization level (0-3)
    - seed_transpiler: Random seed for reproducible transpilation
    - target: Backend target specification (alternative to backend)
    
    Returns:
    QuantumCircuit or List[QuantumCircuit]: Transpiled circuit(s)
    """

def generate_preset_pass_manager(optimization_level, backend=None, target=None,
                                basis_gates=None, inst_map=None, coupling_map=None,
                                instruction_durations=None, backend_properties=None,
                                timing_constraints=None, initial_layout=None,
                                layout_method=None, routing_method=None,
                                translation_method=None, scheduling_method=None,
                                approximation_degree=None, seed_transpiler=None,
                                unroll_3q=None, hls_config=None, init_method=None,
                                optimization_method=None):
    """
    Generate preset pass manager for given optimization level.
    
    Parameters:
    - optimization_level: Optimization level (0-3)
    - backend: Target backend
    - target: Backend target specification
    - Other parameters: Same as transpile()
    
    Returns:
    PassManager: Configured pass manager
    """

Pass Manager Framework

The pass manager system orchestrates transpilation passes for flexible circuit optimization workflows.

class PassManager:
    def __init__(self, passes=None, max_iteration=1000):
        """
        Initialize pass manager.
        
        Parameters:
        - passes: Initial passes to add
        - max_iteration: Maximum iterations for iterative passes
        """
    
    def append(self, passes, **kwargs):
        """
        Add passes to the pass manager.
        
        Parameters:
        - passes: Pass or list of passes to add
        - **kwargs: Pass execution conditions
        """
    
    def replace(self, index, passes, **kwargs):
        """Replace pass at given index."""
    
    def remove(self, index):
        """Remove pass at given index."""
    
    def run(self, circuits):
        """
        Execute all passes on circuits.
        
        Parameters:
        - circuits: Circuit or list of circuits
        
        Returns:
        Transpiled circuits
        """
    
    def draw(self, filename=None, style=None, raw=False):
        """Visualize pass manager structure."""
    
    @property
    def passes(self):
        """List of passes in the manager."""

class StagedPassManager(PassManager):
    def __init__(self, stages=None):
        """
        Multi-stage pass manager.
        
        Parameters:
        - stages: List of pass manager stages
        """
    
    def append(self, passes, **kwargs):
        """Append passes to the last stage."""
    
    def replace(self, stage_index, passes, **kwargs):
        """Replace entire stage."""
    
    @property
    def stages(self):
        """List of pass manager stages."""

Backend Target Specification

Hardware target specification and coupling constraints for backend-aware transpilation.

class Target:
    def __init__(self, description=None, num_qubits=0, dt=None, granularity=1,
                 min_length=1, pulse_alignment=1, acquire_alignment=1, 
                 qubit_properties=None, concurrent_measurements=None):
        """
        Backend target specification.
        
        Parameters:
        - description: Target description
        - num_qubits: Number of qubits
        - dt: System time resolution
        - granularity: Pulse granularity
        - min_length: Minimum pulse length
        - pulse_alignment: Pulse alignment constraint
        - acquire_alignment: Acquisition alignment constraint
        - qubit_properties: Physical qubit properties
        - concurrent_measurements: Concurrent measurement constraints
        """
    
    def add_instruction(self, instruction, qargs=None, properties=None):
        """
        Add supported instruction to target.
        
        Parameters:
        - instruction: Instruction class or instance
        - qargs: Qubit arguments (None for all combinations)
        - properties: Instruction properties (error rate, duration, etc.)
        """
    
    def instruction_supported(self, operation_name, qargs):
        """Check if instruction is supported."""
    
    def operation_from_name(self, operation_name):
        """Get operation class from name."""
    
    def operations_for_qargs(self, qargs):
        """Get supported operations for qubit arguments."""
    
    def instruction_properties(self, index):
        """Get instruction properties by index."""
    
    @property
    def num_qubits(self):
        """Number of qubits in target."""
    
    @property
    def instructions(self):
        """List of supported instructions."""

class CouplingMap:
    def __init__(self, couplinglist=None, description=None):
        """
        Coupling map representing qubit connectivity.
        
        Parameters:
        - couplinglist: List of [control, target] qubit pairs
        - description: Description of coupling map
        """
    
    def add_edge(self, src, dst):
        """Add coupling edge between qubits."""
    
    def get_edges(self):
        """Get list of coupling edges."""
    
    def neighbors(self, physical_qubit):
        """Get neighboring qubits."""
    
    def distance(self, physical_qubit1, physical_qubit2):
        """Calculate distance between qubits."""
    
    def shortest_undirected_path(self, physical_qubit1, physical_qubit2):
        """Find shortest path between qubits."""
    
    def is_connected(self):
        """Check if coupling map is fully connected."""
    
    def connected_components(self):
        """Get connected components."""
    
    def reduce(self, mapping):
        """Reduce coupling map to subset of qubits."""
    
    def compose(self, other, qubits):
        """Compose with another coupling map."""
    
    @property
    def physical_qubits(self):
        """List of physical qubits."""
    
    @property
    def size(self):
        """Number of qubits in coupling map."""

class Layout:
    def __init__(self, input_dict=None):
        """
        Layout mapping logical to physical qubits.
        
        Parameters:
        - input_dict: Dictionary mapping logical to physical qubits
        """
    
    def add(self, virtual_bit, physical_bit=None):
        """Add mapping from virtual to physical bit."""
    
    def add_register(self, reg):
        """Add register to layout."""
    
    def get_registers(self):
        """Get all registers in layout."""
    
    def get_physical_bits(self):
        """Get all physical bits."""
    
    def get_virtual_bits(self):
        """Get all virtual bits."""
    
    def swap(self, left, right):
        """Swap two physical bits in layout."""
    
    def combine_into_edge_map(self, another_layout):
        """Combine layouts into edge map."""
    
    def copy(self):
        """Create copy of layout."""
    
    @classmethod
    def generate_trivial_layout(cls, *regs):
        """Generate trivial layout for registers."""
    
    @classmethod
    def from_dict(cls, input_dict):
        """Create layout from dictionary."""

Pass Base Classes

Base classes for implementing custom transpilation passes.

class BasePass:
    def __init__(self):
        """Base class for all transpiler passes."""
    
    def name(self):
        """Pass name."""
        return self.__class__.__name__
    
    def run(self, dag):
        """
        Execute pass on DAGCircuit.
        
        Parameters:
        - dag: DAGCircuit to transform
        
        Returns:
        DAGCircuit: Transformed circuit
        """
        raise NotImplementedError

class AnalysisPass(BasePass):
    def __init__(self):
        """Base class for analysis passes that collect information."""
    
    def run(self, dag):
        """Analyze circuit and store results in property_set."""
        raise NotImplementedError

class TransformationPass(BasePass):
    def __init__(self):
        """Base class for passes that transform circuits."""
    
    def run(self, dag):
        """Transform circuit and return modified DAG."""
        raise NotImplementedError

Property Set and Flow Control

Shared state management and conditional pass execution.

class PropertySet:
    def __init__(self):
        """Storage for pass analysis results and shared properties."""
    
    def __getitem__(self, key):
        """Get property value."""
    
    def __setitem__(self, key, value):
        """Set property value."""
    
    def __contains__(self, key):
        """Check if property exists."""
    
    def keys(self):
        """Get all property keys."""
    
    def values(self):
        """Get all property values."""
    
    def items(self):
        """Get all (key, value) pairs."""

class FlowController:
    def __init__(self, passes, options=None, **partial_controller):
        """
        Control pass execution flow.
        
        Parameters:
        - passes: Passes to control
        - options: Flow control options
        - **partial_controller: Partial controller arguments
        """
    
    def iter_tasks(self, max_iteration):
        """Iterate through controlled tasks."""

class ConditionalController(FlowController):
    def __init__(self, passes, condition=None, **partial_controller):
        """
        Execute passes conditionally.
        
        Parameters:
        - passes: Passes to execute conditionally
        - condition: Condition function or property name
        """

class DoWhileController(FlowController):
    def __init__(self, passes, do_while=None, **partial_controller):
        """
        Execute passes in do-while loop.
        
        Parameters:
        - passes: Passes to execute in loop
        - do_while: Loop continuation condition
        """

Common Analysis Passes

Built-in passes for circuit analysis and property collection.

class Depth(AnalysisPass):
    def __init__(self):
        """Analyze circuit depth."""

class Size(AnalysisPass):
    def __init__(self):
        """Count total number of operations."""

class Width(AnalysisPass):
    def __init__(self):
        """Analyze circuit width (total qubits + clbits)."""

class CountOps(AnalysisPass):
    def __init__(self):
        """Count operations by type."""

class CountOpsLongestPath(AnalysisPass):
    def __init__(self):
        """Count operations on longest path."""

class NumTensorFactors(AnalysisPass):
    def __init__(self):
        """Count number of tensor factors."""

class GatesInBasis(AnalysisPass):
    def __init__(self, basis_gates, target=None):
        """
        Check if all gates are in basis.
        
        Parameters:
        - basis_gates: Allowed gate set
        - target: Backend target (alternative to basis_gates)
        """

Common Transformation Passes

Built-in passes for circuit transformation and optimization.

class Unroller(TransformationPass):
    def __init__(self, basis):
        """
        Unroll custom gates to basis gates.
        
        Parameters:
        - basis: Target basis gate set
        """

class BasisTranslator(TransformationPass):
    def __init__(self, equivalence_library, target_basis):
        """
        Translate gates using equivalence library.
        
        Parameters:
        - equivalence_library: Gate equivalence rules
        - target_basis: Target gate basis
        """

class Optimize1qGates(TransformationPass):
    def __init__(self, basis=None, eps=1e-15, target=None):
        """
        Optimize single-qubit gate chains.
        
        Parameters:
        - basis: Single-qubit basis gates
        - eps: Tolerance for optimization
        - target: Backend target
        """

class CXCancellation(TransformationPass):
    def __init__(self):
        """Cancel adjacent CX gates."""

class CommutativeCancellation(TransformationPass):
    def __init__(self, basis_gates=None, target=None):
        """
        Cancel commuting gates.
        
        Parameters:
        - basis_gates: Allowed gate set
        - target: Backend target
        """

Usage Examples

from qiskit import QuantumCircuit, transpile
from qiskit.transpiler import PassManager, CouplingMap, Target
from qiskit.transpiler.passes import Unroller, Optimize1qGates, CXCancellation
from qiskit.providers.fake_provider import FakeManila
import numpy as np

# Basic transpilation
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0, 1)
circuit.cx(1, 2)
circuit.rz(np.pi/4, 2)

# Transpile for specific backend
backend = FakeManila()
transpiled = transpile(circuit, backend=backend, optimization_level=2)
print(f"Original depth: {circuit.depth()}, Transpiled depth: {transpiled.depth()}")

# Manual pass manager construction
pass_manager = PassManager()
pass_manager.append(Unroller(['cx', 'u3']))  # Unroll to basis gates
pass_manager.append(Optimize1qGates())       # Optimize single-qubit gates
pass_manager.append(CXCancellation())        # Cancel adjacent CX gates

optimized_circuit = pass_manager.run(circuit)

# Custom coupling map
coupling_list = [[0, 1], [1, 2], [2, 3], [3, 4]]
coupling_map = CouplingMap(coupling_list)

# Transpile with custom coupling
routed_circuit = transpile(circuit, 
                          coupling_map=coupling_map,
                          basis_gates=['cx', 'u3'],
                          optimization_level=1)

# Target specification for custom backend
target = Target(num_qubits=5)
target.add_instruction('cx', [(0, 1), (1, 2), (2, 3), (3, 4)])
target.add_instruction('u3', None)  # Available on all qubits

# Transpile with target
target_transpiled = transpile(circuit, target=target)

# Preset pass managers for different optimization levels
pm_level_0 = generate_preset_pass_manager(0, backend=backend)  # No optimization
pm_level_1 = generate_preset_pass_manager(1, backend=backend)  # Light optimization  
pm_level_2 = generate_preset_pass_manager(2, backend=backend)  # Heavy optimization
pm_level_3 = generate_preset_pass_manager(3, backend=backend)  # Maximum optimization

# Compare optimization levels
results = {}
for level in [0, 1, 2, 3]:
    pm = generate_preset_pass_manager(level, backend=backend)
    result = pm.run(circuit)
    results[level] = {
        'depth': result.depth(), 
        'size': len(result),
        'cx_count': result.count_ops().get('cx', 0)
    }

for level, metrics in results.items():
    print(f"Level {level}: depth={metrics['depth']}, size={metrics['size']}, cx={metrics['cx_count']}")

# Parameterized transpilation options
circuits = [circuit] * 4
transpiled_batch = transpile(
    circuits,
    backend=backend,
    initial_layout=[0, 1, 2],           # Force specific qubit assignment
    layout_method='sabre',               # Use SABRE layout algorithm
    routing_method='sabre',              # Use SABRE routing
    optimization_level=2,
    seed_transpiler=42                   # Reproducible results
)

print(f"Batch transpiled {len(transpiled_batch)} circuits")

Install with Tessl CLI

npx tessl i tessl/pypi-qiskit

docs

circuit-construction.md

circuit-formats.md

gates-operations.md

index.md

primitives.md

providers.md

quantum-information.md

synthesis.md

transpilation.md

visualization.md

tile.json