Compiler Passes

qb-compiler uses a pass-based architecture. Every pass inherits from BasePass and is executed through a PassManager.

Pass Infrastructure

Compiler pass infrastructure.

Every pass in qb-compiler inherits from BasePass. Passes are either analysis (read-only, populate context) or transformation (may modify the circuit). A PassManager orchestrates an ordered sequence of passes.

class qb_compiler.passes.base.AnalysisPass

Bases: BasePass

A pass that inspects but does not modify the circuit.

Subclasses should set modified=False in their PassResult and return the same circuit object they received.

abstractmethod analyze(circuit: QBCircuit, context: dict) None

Perform analysis and write results into context.

run(circuit: QBCircuit, context: dict) PassResult

Execute the pass.

Parameters:
  • circuit (QBCircuit) – Input circuit. Transformation passes may return a different QBCircuit instance in the result; analysis passes must return the same object.

  • context (dict) – Mutable mapping shared across all passes in a PassManager run. Analysis passes write results here; transformation passes may read from it.

Return type:

PassResult

class qb_compiler.passes.base.BasePass

Bases: ABC

Abstract base for all compiler passes.

abstract property name: str

Human-readable pass name (used in logs and metadata).

abstractmethod run(circuit: QBCircuit, context: dict) PassResult

Execute the pass.

Parameters:
  • circuit (QBCircuit) – Input circuit. Transformation passes may return a different QBCircuit instance in the result; analysis passes must return the same object.

  • context (dict) – Mutable mapping shared across all passes in a PassManager run. Analysis passes write results here; transformation passes may read from it.

Return type:

PassResult

class qb_compiler.passes.base.PassManager(passes: Sequence[BasePass] | None = None)

Bases: object

Ordered pipeline of compiler passes.

Usage:

pm = PassManager([DepthAnalysis(), GateCancellationPass()])
result = pm.run_all(circuit)
add(pass_: BasePass) PassManager

Append a pass. Returns self for chaining.

insert(index: int, pass_: BasePass) PassManager

Insert a pass at a specific position. Returns self.

property passes: list[BasePass]
remove(name: str) bool

Remove the first pass with the given name. Returns True if found.

run_all(circuit: QBCircuit, context: dict | None = None) PassResult

Run all passes in order.

Parameters:
  • circuit (QBCircuit) – Input circuit (will not be mutated — a copy is made).

  • context (dict | None) – Shared context dict. Created if None.

Returns:

Final result with the last circuit, combined metadata, and modified=True if any transformation pass modified the circuit.

Return type:

PassResult

class qb_compiler.passes.base.PassResult(circuit: QBCircuit, metadata: dict = <factory>, modified: bool = False)

Bases: object

Return value of a single pass invocation.

circuit

The (potentially modified) circuit.

Type:

QBCircuit

metadata

Arbitrary data produced by the pass (timings, stats, etc.).

Type:

dict

modified

Whether the pass actually changed the circuit.

Type:

bool

circuit: QBCircuit
metadata: dict
modified: bool = False
class qb_compiler.passes.base.TransformationPass

Bases: BasePass

A pass that may modify the circuit.

run(circuit: QBCircuit, context: dict) PassResult

Execute the pass.

Parameters:
  • circuit (QBCircuit) – Input circuit. Transformation passes may return a different QBCircuit instance in the result; analysis passes must return the same object.

  • context (dict) – Mutable mapping shared across all passes in a PassManager run. Analysis passes write results here; transformation passes may read from it.

Return type:

PassResult

abstractmethod transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

Analysis Passes

Analysis passes inspect the circuit without modifying it. They write results into the shared context dictionary for downstream passes to consume.

Built-in analysis passes.

class qb_compiler.passes.analysis.ConnectivityCheck(coupling_map: Sequence[tuple[int, int]])

Bases: AnalysisPass

Check if all 2-qubit gates use connected qubits.

Parameters:

coupling_map – Edges [(q0, q1), ...] describing physical connectivity. Treated as undirected.

analyze(circuit: QBCircuit, context: dict) None

Perform analysis and write results into context.

property name: str

Human-readable pass name (used in logs and metadata).

class qb_compiler.passes.analysis.DepthAnalysis

Bases: AnalysisPass

Compute circuit depth and store it in context["depth"].

analyze(circuit: QBCircuit, context: dict) None

Perform analysis and write results into context.

property name: str

Human-readable pass name (used in logs and metadata).

class qb_compiler.passes.analysis.ErrorBudgetEstimator(qubit_properties: Sequence[QubitProperties], gate_error_rates: dict[str, float] | None = None, gate_duration_us: float = 0.1)

Bases: AnalysisPass

Estimate total circuit fidelity from a noise model.

Accumulates three error sources:

  1. Gate errors – per-gate infidelity (1 - fidelity).

  2. Decoherence – idle-time decay exp(-t/T1) per qubit.

  3. Readout errors – measurement error for each measured qubit.

Results are written to context as "estimated_fidelity" (float) and "error_budget" (dict with gate, decoherence, readout breakdown).

Parameters:
  • qubit_properties (Sequence[QubitProperties]) – Per-qubit calibration data (T1, T2, readout error).

  • gate_error_rates (dict[str, float]) – Mapping from gate name to error rate (probability of error per application). Missing gates are assumed perfect (error = 0).

  • gate_duration_us (float) – Assumed uniform gate duration in microseconds.

analyze(circuit: QBCircuit, context: dict) None

Perform analysis and write results into context.

property name: str

Human-readable pass name (used in logs and metadata).

class qb_compiler.passes.analysis.GateCountAnalysis

Bases: AnalysisPass

Count gates by type and store in context["gate_counts"].

Also populates: - context["total_gates"] — total gate count - context["two_qubit_gates"] — number of 2+ qubit gates

analyze(circuit: QBCircuit, context: dict) None

Perform analysis and write results into context.

property name: str

Human-readable pass name (used in logs and metadata).

Depth analysis pass.

class qb_compiler.passes.analysis.depth_analysis.DepthAnalysis

Bases: AnalysisPass

Compute circuit depth and store it in context["depth"].

analyze(circuit: QBCircuit, context: dict) None

Perform analysis and write results into context.

property name: str

Human-readable pass name (used in logs and metadata).

Gate count analysis pass.

class qb_compiler.passes.analysis.gate_count.GateCountAnalysis

Bases: AnalysisPass

Count gates by type and store in context["gate_counts"].

Also populates: - context["total_gates"] — total gate count - context["two_qubit_gates"] — number of 2+ qubit gates

analyze(circuit: QBCircuit, context: dict) None

Perform analysis and write results into context.

property name: str

Human-readable pass name (used in logs and metadata).

Connectivity check analysis pass.

Checks whether all 2-qubit gates in the circuit operate on physically connected qubits. Populates context["connectivity_satisfied"] and context["violating_gates"] so downstream passes can decide whether routing is needed.

class qb_compiler.passes.analysis.connectivity_check.ConnectivityCheck(coupling_map: Sequence[tuple[int, int]])

Bases: AnalysisPass

Check if all 2-qubit gates use connected qubits.

Parameters:

coupling_map – Edges [(q0, q1), ...] describing physical connectivity. Treated as undirected.

analyze(circuit: QBCircuit, context: dict) None

Perform analysis and write results into context.

property name: str

Human-readable pass name (used in logs and metadata).

Error budget estimation analysis pass.

Estimates the total expected infidelity of a circuit given per-gate error rates and per-qubit T1/T2 calibration data.

class qb_compiler.passes.analysis.error_budget_estimator.ErrorBudgetEstimator(qubit_properties: Sequence[QubitProperties], gate_error_rates: dict[str, float] | None = None, gate_duration_us: float = 0.1)

Bases: AnalysisPass

Estimate total circuit fidelity from a noise model.

Accumulates three error sources:

  1. Gate errors – per-gate infidelity (1 - fidelity).

  2. Decoherence – idle-time decay exp(-t/T1) per qubit.

  3. Readout errors – measurement error for each measured qubit.

Results are written to context as "estimated_fidelity" (float) and "error_budget" (dict with gate, decoherence, readout breakdown).

Parameters:
  • qubit_properties (Sequence[QubitProperties]) – Per-qubit calibration data (T1, T2, readout error).

  • gate_error_rates (dict[str, float]) – Mapping from gate name to error rate (probability of error per application). Missing gates are assumed perfect (error = 0).

  • gate_duration_us (float) – Assumed uniform gate duration in microseconds.

analyze(circuit: QBCircuit, context: dict) None

Perform analysis and write results into context.

property name: str

Human-readable pass name (used in logs and metadata).

Transformation Passes

Transformation passes modify the circuit – decomposing gates, cancelling redundant operations, or simplifying sub-circuits.

Built-in transformation passes.

class qb_compiler.passes.transformation.CircuitSimplifier

Bases: TransformationPass

Template-based circuit simplification.

Applies the following rewrite rules in a single forward scan:

  1. X-X → identity (same qubit, no intervening ops on that qubit)

  2. CX-CX → identity (same qubit pair)

  3. H-CX-H → CX with swapped control/target When H(t), CX(c, t), H(t) appears and no other operation touches qubit t in between, it is replaced by CX(t, c).

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

class qb_compiler.passes.transformation.CommutationOptimizer

Bases: TransformationPass

Merge consecutive same-axis rotation gates.

Scans the operation list and merges adjacent rotation gates on the same qubits by summing their parameters. If the resulting rotation angle is effectively zero, the gate is eliminated entirely.

Barriers and measurements break adjacency.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

class qb_compiler.passes.transformation.GateCancellationPass

Bases: TransformationPass

Cancel adjacent pairs of self-inverse gates.

Scans the operation list and removes consecutive identical gate applications (same name, same qubits, no parameters or identical parameters) when the gate is known to be self-inverse.

Barriers and measurements break adjacency.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

class qb_compiler.passes.transformation.GateDecompositionPass(target_basis: tuple[str, ...])

Bases: TransformationPass

Decompose gates into a target native basis gate set.

Parameters:

target_basis (tuple[str, ...]) – Gate names in the target native basis (e.g. ("cx", "rz", "sx", "x", "id") for IBM Eagle, or ("cz", "rx", "rz") for Rigetti).

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

Gate decomposition transformation pass.

Decomposes gates into a target native basis gate set, applying known decomposition rules for standard gates.

class qb_compiler.passes.transformation.gate_decomposition.GateDecompositionPass(target_basis: tuple[str, ...])

Bases: TransformationPass

Decompose gates into a target native basis gate set.

Parameters:

target_basis (tuple[str, ...]) – Gate names in the target native basis (e.g. ("cx", "rz", "sx", "x", "id") for IBM Eagle, or ("cz", "rx", "rz") for Rigetti).

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

Gate cancellation transformation pass.

Cancels adjacent pairs of self-inverse gates: H-H, X-X, Y-Y, Z-Z, CX-CX (same qubits), CZ-CZ, SWAP-SWAP, etc.

class qb_compiler.passes.transformation.gate_cancellation.GateCancellationPass

Bases: TransformationPass

Cancel adjacent pairs of self-inverse gates.

Scans the operation list and removes consecutive identical gate applications (same name, same qubits, no parameters or identical parameters) when the gate is known to be self-inverse.

Barriers and measurements break adjacency.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

Commutation-based gate optimisation pass.

Identifies and exploits gate commutativity to merge consecutive gates. Currently handles:

  • RZ + RZ merge: RZ(a) followed by RZ(b) on the same qubit collapses to RZ(a + b). Applies to all same-axis rotation gates (rz, rx, ry, p, u1, rzz, rxx, ryy).

  • Identity elimination: merged rotations that evaluate to angle 0 (within tolerance) are removed entirely.

class qb_compiler.passes.transformation.commutation_analysis.CommutationOptimizer

Bases: TransformationPass

Merge consecutive same-axis rotation gates.

Scans the operation list and merges adjacent rotation gates on the same qubits by summing their parameters. If the resulting rotation angle is effectively zero, the gate is eliminated entirely.

Barriers and measurements break adjacency.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

Template-based circuit simplification pass.

Applies known circuit identities to reduce gate count:

  • X-X cancellation: Two consecutive X gates on the same qubit → identity

  • CX-CX cancellation: Two consecutive CX gates on the same qubit pair → identity

  • H-CX-H simplification: H(t) CX(c,t) H(t) → CX(t,c) (control/target swap)

Reports how many simplifications were applied.

class qb_compiler.passes.transformation.circuit_simplification.CircuitSimplifier

Bases: TransformationPass

Template-based circuit simplification.

Applies the following rewrite rules in a single forward scan:

  1. X-X → identity (same qubit, no intervening ops on that qubit)

  2. CX-CX → identity (same qubit pair)

  3. H-CX-H → CX with swapped control/target When H(t), CX(c, t), H(t) appears and no other operation touches qubit t in between, it is replaced by CX(t, c).

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

Mapping Passes

Mapping passes handle logical-to-physical qubit assignment and routing. The calibration-aware mapper is qb-compiler’s key differentiator – it uses live device error rates to select the highest-fidelity qubit subset.

Qubit mapping and routing passes.

class qb_compiler.passes.mapping.CorrelatedErrorRouter(coupling_map: Sequence[tuple[int, int]], gate_errors: dict[tuple[int, int], float] | None = None, correlation_matrix: dict[tuple[int, int], float] | None = None, correlation_weight: float = 1.0, correlation_threshold: float = 0.1, default_error: float = 0.01)

Bases: TransformationPass

Route 2-qubit gates while avoiding temporally correlated qubit pairs.

Parameters:
  • coupling_map – Edges [(q0, q1), ...] describing physical connectivity.

  • gate_errors – Mapping (q0, q1) -> error_rate for 2-qubit gates.

  • correlation_matrix – Mapping (q0, q1) -> correlation_score (0-1) indicating temporal error correlation between qubit pairs. Higher values mean the pair is more likely to experience correlated errors. If None, no correlation penalty is applied.

  • correlation_weight – How much to weight correlation data relative to gate error.

  • correlation_threshold – Correlation values below this threshold are ignored.

  • default_error – Fallback gate error for edges not in gate_errors.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

class qb_compiler.passes.mapping.TemporalCorrelationAnalyzer(snapshots: list[BackendProperties])

Bases: object

Detect temporal error correlations from multiple calibration snapshots.

Works with public calibration data only — no proprietary API needed. For real-time correlation monitoring, see LiveCalibrationProvider with QubitBoost SafetyGate (requires qubitboost-sdk).

Parameters:

snapshots – Two or more BackendProperties snapshots from different calibration cycles. Order does not matter (sorted by timestamp).

edge_correlation(q0: int, q1: int) float

Correlation coefficient for a qubit pair (-1 to +1).

classmethod from_snapshots(snapshots: list[BackendProperties]) TemporalCorrelationAnalyzer

Convenience constructor.

qubit_drift(qubit_id: int) float

Directional drift for a qubit (positive = getting worse).

qubit_volatility(qubit_id: int) float

Error volatility for a specific qubit (0 = perfectly stable).

property result: CorrelationResult

Lazily compute and return correlation results.

class qb_compiler.passes.mapping.TopologyMapper(coupling_map: Sequence[tuple[int, int]], max_candidates: int = 100)

Bases: TransformationPass

Map logical qubits to physical qubits using coupling map only.

Unlike CalibrationMapper, this pass does not use gate error rates or coherence data. It picks the first valid VF2 subgraph isomorphism, or falls back to a trivial identity mapping if no 2-qubit interactions exist or VF2 finds no match.

Parameters:
  • coupling_map – Edges [(q0, q1), ...] describing physical connectivity. Treated as undirected.

  • max_candidates – Maximum number of VF2 candidate mappings to evaluate.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

Topology-only qubit mapping pass.

Maps logical qubits to physical qubits using only the coupling map (no calibration data). Uses rustworkx.vf2_mapping for subgraph isomorphism and picks the first valid layout. This is a simpler fallback for when calibration data is not available.

class qb_compiler.passes.mapping.topology_mapper.TopologyMapper(coupling_map: Sequence[tuple[int, int]], max_candidates: int = 100)

Bases: TransformationPass

Map logical qubits to physical qubits using coupling map only.

Unlike CalibrationMapper, this pass does not use gate error rates or coherence data. It picks the first valid VF2 subgraph isomorphism, or falls back to a trivial identity mapping if no 2-qubit interactions exist or VF2 finds no match.

Parameters:
  • coupling_map – Edges [(q0, q1), ...] describing physical connectivity. Treated as undirected.

  • max_candidates – Maximum number of VF2 candidate mappings to evaluate.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

Correlated-error-aware SWAP router.

Extends the standard noise-aware routing strategy by penalising qubit pairs that exhibit high temporal error correlation (as measured by SafetyGate / QubitBoost). When correlation data is unavailable, falls back to standard error-weighted routing.

class qb_compiler.passes.mapping.correlated_error_router.CorrelatedErrorRouter(coupling_map: Sequence[tuple[int, int]], gate_errors: dict[tuple[int, int], float] | None = None, correlation_matrix: dict[tuple[int, int], float] | None = None, correlation_weight: float = 1.0, correlation_threshold: float = 0.1, default_error: float = 0.01)

Bases: TransformationPass

Route 2-qubit gates while avoiding temporally correlated qubit pairs.

Parameters:
  • coupling_map – Edges [(q0, q1), ...] describing physical connectivity.

  • gate_errors – Mapping (q0, q1) -> error_rate for 2-qubit gates.

  • correlation_matrix – Mapping (q0, q1) -> correlation_score (0-1) indicating temporal error correlation between qubit pairs. Higher values mean the pair is more likely to experience correlated errors. If None, no correlation penalty is applied.

  • correlation_weight – How much to weight correlation data relative to gate error.

  • correlation_threshold – Correlation values below this threshold are ignored.

  • default_error – Fallback gate error for edges not in gate_errors.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

Scheduling Passes

Scheduling passes determine the time ordering of gates to minimise decoherence or satisfy hardware timing constraints.

Built-in scheduling passes.

class qb_compiler.passes.scheduling.ALAPScheduler

Bases: TransformationPass

Schedule gates as late as possible while respecting dependencies.

Operations are partitioned into layers via the DAG and emitted in reverse-dependency order — each gate is placed in the latest possible layer. The output preserves correctness (topological order) while pushing operations toward the end of the circuit.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

class qb_compiler.passes.scheduling.ASAPScheduler

Bases: TransformationPass

Schedule gates as soon as possible while respecting dependencies.

Operations are partitioned into layers via the DAG; each gate is placed in the earliest layer allowed by its data dependencies. This minimises circuit depth.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

class qb_compiler.passes.scheduling.NoiseAwareScheduler(qubit_properties: Sequence[QubitProperties], default_gate_duration_us: float = 0.1)

Bases: TransformationPass

ALAP scheduler that accounts for per-qubit T1/T2 decay.

Within each parallel layer of the DAG, operations are sorted so that high-urgency qubits (short T2) are placed later – closer to measurement. The overall topological ordering is preserved; only the intra-layer ordering changes.

Parameters:
  • qubit_properties (Sequence[QubitProperties]) – Per-qubit calibration data. Must cover every qubit in the circuit.

  • default_gate_duration_us (float) – Assumed gate duration in microseconds (used for decoherence estimation when no per-gate durations are available).

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

As-Soon-As-Possible (ASAP) scheduler.

Schedules each gate as early as its dependencies allow, useful for minimising overall circuit depth.

class qb_compiler.passes.scheduling.asap_scheduler.ASAPScheduler

Bases: TransformationPass

Schedule gates as soon as possible while respecting dependencies.

Operations are partitioned into layers via the DAG; each gate is placed in the earliest layer allowed by its data dependencies. This minimises circuit depth.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

As-Late-As-Possible (ALAP) scheduler — no noise awareness.

Delays each gate as late as possible while respecting data dependencies. This is the simpler counterpart of NoiseAwareScheduler for use when no calibration data is available.

class qb_compiler.passes.scheduling.alap_scheduler.ALAPScheduler

Bases: TransformationPass

Schedule gates as late as possible while respecting dependencies.

Operations are partitioned into layers via the DAG and emitted in reverse-dependency order — each gate is placed in the latest possible layer. The output preserves correctness (topological order) while pushing operations toward the end of the circuit.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

Noise-aware ALAP scheduler.

Reorders gates within dependency constraints so that qubits with shorter T1/T2 times have their gates packed as close to measurement as possible, minimising idle-time-weighted decoherence.

class qb_compiler.passes.scheduling.noise_aware_scheduler.NoiseAwareScheduler(qubit_properties: Sequence[QubitProperties], default_gate_duration_us: float = 0.1)

Bases: TransformationPass

ALAP scheduler that accounts for per-qubit T1/T2 decay.

Within each parallel layer of the DAG, operations are sorted so that high-urgency qubits (short T2) are placed later – closer to measurement. The overall topological ordering is preserved; only the intra-layer ordering changes.

Parameters:
  • qubit_properties (Sequence[QubitProperties]) – Per-qubit calibration data. Must cover every qubit in the circuit.

  • default_gate_duration_us (float) – Assumed gate duration in microseconds (used for decoherence estimation when no per-gate durations are available).

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

Qiskit Plugin Passes

These passes subclass Qiskit’s native TransformationPass and AnalysisPass base classes, making them directly composable with any Qiskit PassManager or StagedPassManager.

Qiskit TransformationPass powered by live calibration data.

QBCalibrationPass is a Qiskit TransformationPass that uses per-qubit and per-gate error rates from a Backend or Target to optimise circuit layout and cancel redundant gates.

Usage inside a Qiskit pass pipeline:

from qb_compiler.qiskit_plugin.calibration_pass import QBCalibrationPass

pass_ = QBCalibrationPass(backend=backend)
dag_out = pass_.run(dag)

Usage with the convenience factory:

from qb_compiler import passmanager

pm = passmanager(backend)
compiled = pm.run(circuit)
class qb_compiler.qiskit_plugin.calibration_pass.QBCalibrationPass(*args, **kwargs)

Bases: TransformationPass

Calibration-aware transformation pass for Qiskit pipelines.

Accepts a Qiskit Backend or Target at init. During run(), the pass:

  1. Scores physical qubits using calibration data (gate error, readout error, T1/T2 coherence).

  2. Sets an optimal layout in property_set so downstream routing passes (e.g. SabreSwap) place virtual qubits on the best hardware.

  3. Cancels adjacent self-inverse gate pairs (H-H, CX-CX, etc.) to reduce gate count.

Parameters:
  • backend – A Qiskit Backend instance (e.g. from QiskitRuntimeService). Calibration is extracted from backend.target.

  • target – A Qiskit Target directly. Used when no Backend is available.

run(dag: DAGCircuit) DAGCircuit

Apply calibration-aware layout and gate cancellation.

Sets property_set["layout"] when calibration data is available, then cancels adjacent self-inverse gate pairs in the DAG.

Parameters:

dag – Input DAG circuit.

Returns:

The optimised DAG.

Return type:

DAGCircuit

Qiskit-compatible transformation pass wrappers for qb-compiler.

Wraps qb-compiler optimisation passes as Qiskit TransformationPass objects.

class qb_compiler.qiskit_plugin.transformation_passes.QBGateCancellation(*args, **kwargs)

Bases: TransformationPass

Qiskit transformation pass that cancels adjacent inverse gates.

Scans the DAG for adjacent self-inverse gate pairs (e.g. CX-CX, H-H, X-X) and removes them. Also cancels adjacent rotation gates that sum to zero or 2pi.

Parameters:

max_iterations – Maximum number of cancellation sweeps. Each sweep may reveal new cancellation opportunities. Default is 3.

run(dag: DAGCircuit) DAGCircuit

Run gate cancellation on the DAG.

This is a structural pass — it looks for patterns in the DAG topology rather than doing full unitary simulation.

Returns the (potentially modified) DAG.

class qb_compiler.qiskit_plugin.transformation_passes.QBGateDecomposition(*args, **kwargs)

Bases: TransformationPass

Qiskit transformation pass for basis gate decomposition.

Decomposes gates not in the target basis set into sequences of basis gates. This is a simplified version that handles common decompositions; for full decomposition, use Qiskit’s built-in BasisTranslator.

Parameters:

target_basis – Set of allowed gate names in the target basis. Gates not in this set will be decomposed if a decomposition rule exists.

run(dag: DAGCircuit) DAGCircuit

Decompose non-basis gates in the DAG.

Currently delegates to Qiskit’s built-in decomposition for gates that have a definition property. Gates without a definition that are not in the target basis are left unchanged with a warning.

Returns the (potentially modified) DAG.

Qiskit-compatible analysis pass wrappers for qb-compiler.

Wraps qb-compiler analysis functionality as Qiskit AnalysisPass objects so they can be inserted into any Qiskit pass manager pipeline.

class qb_compiler.qiskit_plugin.analysis_passes.QBDepthAnalysis(*args, **kwargs)

Bases: AnalysisPass

Qiskit analysis pass that records circuit depth in the property set.

After running, sets property_set["qb_depth"] to the circuit depth and property_set["qb_depth_by_type"] to a breakdown by gate type.

run(dag: Any) None

Analyse circuit depth from the DAG representation.

class qb_compiler.qiskit_plugin.analysis_passes.QBErrorBudgetAnalysis(*args, **kwargs)

Bases: AnalysisPass

Qiskit analysis pass that estimates the circuit error budget.

Uses gate counts and configurable error rates to compute a rough error budget. Sets property_set["qb_error_budget"] to the estimated total error probability.

Parameters:
  • single_qubit_error – Assumed single-qubit gate error rate.

  • two_qubit_error – Assumed two-qubit gate error rate.

  • readout_error – Assumed per-qubit readout error rate.

run(dag: Any) None

Estimate the error budget from the DAG.

class qb_compiler.qiskit_plugin.analysis_passes.QBGateCountAnalysis(*args, **kwargs)

Bases: AnalysisPass

Qiskit analysis pass that records gate counts in the property set.

After running, sets: - property_set["qb_gate_count"]: total gate count - property_set["qb_gate_counts_by_type"]: {gate_name: count} - property_set["qb_two_qubit_count"]: count of 2-qubit gates

run(dag: Any) None

Count gates in the DAG.

QEC Passes

Quantum error correction passes prepare circuits for fault-tolerant execution. These passes require the QubitBoost SDK (>= 2.5).

QEC (Quantum Error Correction) compiler passes.

These passes require the QubitBoost SDK (>= 2.5) and will raise NotImplementedError until that dependency is available.

class qb_compiler.passes.qec.CorrelatedErrorAvoidance(correlation_threshold: float = 0.3, correlation_data: dict[tuple[int, int], float] | None = None, insert_dd_sequences: bool = False)

Bases: TransformationPass

Restructure QEC circuits to avoid correlated error pairs.

Given temporal correlation data (from SafetyGate monitoring), this pass:

  • Identifies stabiliser measurements that touch correlated qubit pairs

  • Reorders syndrome extraction to avoid simultaneous operations on correlated pairs

  • Inserts dynamical decoupling sequences on idle qubits near correlated pairs to suppress cross-talk

  • Optionally adjusts the decoder graph weights to account for residual correlations

Parameters:
  • correlation_threshold (float) – Minimum correlation coefficient (0-1) to consider a pair as “correlated”. Pairs below this threshold are treated as independent.

  • correlation_data (dict[tuple[int, int], float] | None) – Pre-loaded correlation data mapping qubit pairs to correlation coefficients. If None, the pass will attempt to fetch live data from a QubitBoost session.

  • insert_dd_sequences (bool) – If True, insert dynamical decoupling sequences on idle qubits adjacent to correlated pairs.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

class qb_compiler.passes.qec.LogicalQubitMapper(code_distance: int = 3, code_type: str = 'surface', coupling_map: list[tuple[int, int]] | None = None)

Bases: TransformationPass

Map logical QEC qubits to physical hardware qubits.

Given a quantum error-correcting code (e.g. surface code, repetition code) and a hardware coupling map, this pass determines an optimal placement of data qubits and ancilla qubits on the physical device. The mapping accounts for:

  • Code distance and stabiliser weight

  • Hardware connectivity constraints

  • Ancilla placement for efficient syndrome extraction

  • Minimisation of cross-talk between logical patches

Parameters:
  • code_distance (int) – Distance of the error-correcting code.

  • code_type (str) – Type of QEC code (e.g. "surface", "repetition", "steane").

  • coupling_map (list[tuple[int, int]] | None) – Physical device coupling map. If None, assumes all-to-all.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

class qb_compiler.passes.qec.SyndromeScheduler(code_distance: int = 3, avoid_hook_errors: bool = True, max_parallel_measurements: int | None = None)

Bases: TransformationPass

Optimise syndrome extraction circuit scheduling.

Given a QEC syndrome extraction circuit, this pass reorders CNOT gates within each stabiliser measurement round to:

  • Minimise circuit depth (parallelise where possible)

  • Avoid hook errors by enforcing safe gate orderings

  • Reduce idle time on data qubits between stabiliser interactions

  • Balance ancilla reset/measurement overhead

Parameters:
  • code_distance (int) – Distance of the error-correcting code.

  • avoid_hook_errors (bool) – If True, enforce gate orderings that prevent weight-2 hook errors from appearing as logical errors.

  • max_parallel_measurements (int | None) – Maximum number of ancilla measurements that can run in parallel. Hardware-dependent; None means no limit.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

Logical-to-physical QEC qubit mapping pass.

Maps logical QEC qubits (data qubits + ancillas for a given error-correcting code) to physical hardware qubits, taking into account code distance, stabiliser structure, and hardware connectivity.

This pass requires the QubitBoost SDK (>= 2.5) for access to code definitions and hardware-aware placement algorithms.

class qb_compiler.passes.qec.logical_mapping.LogicalQubitMapper(code_distance: int = 3, code_type: str = 'surface', coupling_map: list[tuple[int, int]] | None = None)

Bases: TransformationPass

Map logical QEC qubits to physical hardware qubits.

Given a quantum error-correcting code (e.g. surface code, repetition code) and a hardware coupling map, this pass determines an optimal placement of data qubits and ancilla qubits on the physical device. The mapping accounts for:

  • Code distance and stabiliser weight

  • Hardware connectivity constraints

  • Ancilla placement for efficient syndrome extraction

  • Minimisation of cross-talk between logical patches

Parameters:
  • code_distance (int) – Distance of the error-correcting code.

  • code_type (str) – Type of QEC code (e.g. "surface", "repetition", "steane").

  • coupling_map (list[tuple[int, int]] | None) – Physical device coupling map. If None, assumes all-to-all.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

Syndrome extraction scheduling optimisation pass.

Optimises the order and parallelism of syndrome extraction circuits for quantum error-correcting codes. Proper scheduling of stabiliser measurements can reduce circuit depth, minimise idle time (reducing decoherence), and avoid hook errors that arise from particular gate orderings.

This pass requires the QubitBoost SDK (>= 2.5) for access to code definitions, hook-error analysis, and scheduling heuristics.

class qb_compiler.passes.qec.syndrome_scheduling.SyndromeScheduler(code_distance: int = 3, avoid_hook_errors: bool = True, max_parallel_measurements: int | None = None)

Bases: TransformationPass

Optimise syndrome extraction circuit scheduling.

Given a QEC syndrome extraction circuit, this pass reorders CNOT gates within each stabiliser measurement round to:

  • Minimise circuit depth (parallelise where possible)

  • Avoid hook errors by enforcing safe gate orderings

  • Reduce idle time on data qubits between stabiliser interactions

  • Balance ancilla reset/measurement overhead

Parameters:
  • code_distance (int) – Distance of the error-correcting code.

  • avoid_hook_errors (bool) – If True, enforce gate orderings that prevent weight-2 hook errors from appearing as logical errors.

  • max_parallel_measurements (int | None) – Maximum number of ancilla measurements that can run in parallel. Hardware-dependent; None means no limit.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.

Correlated error avoidance pass for QEC circuits.

Uses temporal correlation data from SafetyGate / QubitBoost to identify qubit pairs that exhibit correlated errors over time and restructures QEC circuits to avoid scheduling critical operations on those pairs simultaneously.

Correlated errors are particularly damaging to QEC because decoders (e.g. MWPM, union-find) assume independent error models. When errors are correlated, the effective code distance is reduced.

This pass requires the QubitBoost SDK (>= 2.5) for access to SafetyGate temporal correlation analysis.

class qb_compiler.passes.qec.correlated_error_avoidance.CorrelatedErrorAvoidance(correlation_threshold: float = 0.3, correlation_data: dict[tuple[int, int], float] | None = None, insert_dd_sequences: bool = False)

Bases: TransformationPass

Restructure QEC circuits to avoid correlated error pairs.

Given temporal correlation data (from SafetyGate monitoring), this pass:

  • Identifies stabiliser measurements that touch correlated qubit pairs

  • Reorders syndrome extraction to avoid simultaneous operations on correlated pairs

  • Inserts dynamical decoupling sequences on idle qubits near correlated pairs to suppress cross-talk

  • Optionally adjusts the decoder graph weights to account for residual correlations

Parameters:
  • correlation_threshold (float) – Minimum correlation coefficient (0-1) to consider a pair as “correlated”. Pairs below this threshold are treated as independent.

  • correlation_data (dict[tuple[int, int], float] | None) – Pre-loaded correlation data mapping qubit pairs to correlation coefficients. If None, the pass will attempt to fetch live data from a QubitBoost session.

  • insert_dd_sequences (bool) – If True, insert dynamical decoupling sequences on idle qubits adjacent to correlated pairs.

property name: str

Human-readable pass name (used in logs and metadata).

transform(circuit: QBCircuit, context: dict) PassResult

Transform circuit and return a PassResult.