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

circuit-construction.mddocs/

Circuit Construction

Qiskit's circuit construction framework provides the foundation for building quantum algorithms through quantum circuits, registers, and instructions. The framework supports parameterized circuits, control flow, and extensive gate libraries.

Capabilities

Quantum Circuit Creation

The QuantumCircuit class is the central object for building quantum algorithms, supporting gate operations, measurements, and circuit composition.

class QuantumCircuit:
    def __init__(self, *args, name: str = None, global_phase: float = 0):
        """
        Create a quantum circuit.
        
        Parameters:
        - *args: QuantumRegister, ClassicalRegister, or int (number of qubits)
        - name: Circuit name
        - global_phase: Global phase of the circuit
        """
    
    def add_register(self, register):
        """Add a quantum or classical register to the circuit."""
    
    def compose(self, other, qubits=None, clbits=None, front=False):
        """Compose this circuit with another circuit or instruction."""
    
    def copy(self, name=None):
        """Create a copy of the circuit."""
    
    def reverse_ops(self):
        """Reverse the order of circuit operations."""
    
    def inverse(self):
        """Return the inverse of the circuit."""
    
    @property
    def num_qubits(self) -> int:
        """Number of qubits in the circuit."""
    
    @property  
    def num_clbits(self) -> int:
        """Number of classical bits in the circuit."""
    
    @property
    def depth(self) -> int:
        """Circuit depth (number of layers)."""
    
    @property
    def width(self) -> int:
        """Total circuit width (qubits + clbits)."""

Register Management

Quantum and classical registers organize qubits and classical bits for circuit construction and measurement.

class QuantumRegister:
    def __init__(self, size: int, name: str = None):
        """
        Create a quantum register.
        
        Parameters:
        - size: Number of qubits in the register
        - name: Register name
        """
    
    @property
    def size(self) -> int:
        """Number of qubits in the register."""
    
    def __getitem__(self, key) -> 'Qubit':
        """Access individual qubits by index."""

class ClassicalRegister:  
    def __init__(self, size: int, name: str = None):
        """
        Create a classical register.
        
        Parameters:
        - size: Number of classical bits in the register  
        - name: Register name
        """
    
    @property
    def size(self) -> int:
        """Number of classical bits in the register."""
    
    def __getitem__(self, key) -> 'Clbit':
        """Access individual classical bits by index."""

class AncillaRegister(QuantumRegister):
    def __init__(self, size: int, name: str = None):
        """
        Create an ancilla register for auxiliary qubits.
        
        Parameters:
        - size: Number of ancilla qubits
        - name: Register name  
        """

Basic Quantum Operations

Fundamental quantum operations including gates, measurements, and control operations.

# Gate operations (methods of QuantumCircuit)
def h(self, qubit):
    """Apply Hadamard gate to qubit."""

def x(self, qubit):
    """Apply Pauli-X gate to qubit."""

def y(self, qubit):
    """Apply Pauli-Y gate to qubit."""

def z(self, qubit):
    """Apply Pauli-Z gate to qubit."""

def s(self, qubit):
    """Apply S gate to qubit."""

def t(self, qubit):
    """Apply T gate to qubit."""

def rx(self, theta, qubit):
    """Apply rotation about X-axis."""

def ry(self, theta, qubit):
    """Apply rotation about Y-axis."""

def rz(self, phi, qubit):  
    """Apply rotation about Z-axis."""

def cx(self, control_qubit, target_qubit):
    """Apply controlled-X (CNOT) gate."""

def cz(self, control_qubit, target_qubit):
    """Apply controlled-Z gate."""

def swap(self, qubit1, qubit2):
    """Apply SWAP gate between two qubits."""

def measure(self, qubit, clbit):
    """Measure qubit and store result in classical bit."""

def measure_all(self, add_bits=True):
    """Measure all qubits."""

def reset(self, qubit):
    """Reset qubit to |0⟩ state."""

def barrier(self, *qubits):
    """Add synchronization barrier."""

Parameterized Circuits

Support for parameterized quantum circuits enabling variational algorithms and circuit families.

class Parameter:
    def __init__(self, name: str):
        """
        Create a circuit parameter.
        
        Parameters:
        - name: Parameter name
        """
    
    @property
    def name(self) -> str:
        """Parameter name."""

class ParameterVector:
    def __init__(self, name: str, length: int):
        """
        Create a vector of parameters.
        
        Parameters:
        - name: Base name for parameters
        - length: Number of parameters
        """
    
    def __getitem__(self, key) -> Parameter:
        """Access individual parameters by index."""
    
    @property  
    def params(self) -> List[Parameter]:
        """List of all parameters in vector."""

class ParameterExpression:
    """Mathematical expression involving parameters."""
    
    def bind(self, parameter_values: Dict) -> float:
        """Bind parameter values to get numeric result."""
    
    @property
    def parameters(self) -> Set[Parameter]:
        """Set of parameters in the expression."""

# Circuit parameter methods
def assign_parameters(self, parameter_values: Dict, inplace=False):
    """Assign values to circuit parameters."""

def bind_parameters(self, parameter_values: Dict):
    """Bind parameter values (alias for assign_parameters)."""

@property
def parameters(self) -> Set[Parameter]:
    """Set of all parameters in the circuit."""

Control Flow Operations

Quantum control flow including conditional operations, loops, and control transfer operations.

from qiskit.circuit.controlflow import IfElseOp, WhileLoopOp, ForLoopOp, SwitchCaseOp, BreakLoopOp, ContinueLoopOp

class IfElseOp(ControlFlowOp):
    def __init__(self, condition, true_body, false_body=None, label=None):
        """
        Conditional operation: if-else statement.
        
        Parameters:
        - condition: Classical condition to test
        - true_body: Circuit executed if condition is true
        - false_body: Circuit executed if condition is false (optional)
        - label: Optional operation label
        """

class WhileLoopOp(ControlFlowOp):
    def __init__(self, condition, body, label=None):
        """
        While loop operation.
        
        Parameters:
        - condition: Loop continuation condition
        - body: Circuit executed in each loop iteration
        - label: Optional operation label
        """

class ForLoopOp(ControlFlowOp):
    def __init__(self, indexset, loop_parameter, body, label=None):
        """
        For loop operation.
        
        Parameters:
        - indexset: Iterable of values to loop over
        - loop_parameter: Loop variable parameter
        - body: Circuit executed in each loop iteration
        - label: Optional operation label
        """

class SwitchCaseOp(ControlFlowOp):
    def __init__(self, target, cases, label=None):
        """
        Switch-case operation.
        
        Parameters:
        - target: Value to switch on
        - cases: Iterable of (case_value, circuit) pairs
        - label: Optional operation label
        """

class BreakLoopOp(Instruction):
    def __init__(self, num_qubits: int, num_clbits: int, label=None):
        """
        Break out of the nearest containing loop.
        
        Parameters:
        - num_qubits: Number of qubits affected
        - num_clbits: Number of classical bits affected
        - label: Optional operation label
        """

class ContinueLoopOp(Instruction):
    def __init__(self, num_qubits: int, num_clbits: int, label=None):
        """
        Continue to next iteration of nearest containing loop.
        
        Parameters:
        - num_qubits: Number of qubits affected
        - num_clbits: Number of classical bits affected
        - label: Optional operation label
        """

# QuantumCircuit convenience methods
def if_test(self, condition, true_body, qubits=None, clbits=None, label=None):
    """Add if-else conditional operation to circuit."""

def while_loop(self, condition, body, qubits=None, clbits=None, label=None):
    """Add while loop operation to circuit."""

def for_loop(self, indexset, loop_parameter, body, qubits=None, clbits=None, label=None):
    """Add for loop operation to circuit."""

def switch(self, target, cases, qubits=None, clbits=None, label=None):
    """Add switch-case operation to circuit."""

Real-time Classical Computation

Support for real-time classical expressions and variables that are evaluated during quantum circuit execution.

from qiskit.circuit.classical import expr
from qiskit.circuit import Store

class Store(Instruction):
    def __init__(self, lvalue, rvalue):
        """
        Store classical expression result in a storage location.
        
        Parameters:
        - lvalue: Classical storage location (Var)
        - rvalue: Classical expression to evaluate and store
        """

# Classical expression types
class expr.Var:
    def __init__(self, name: str, type: 'Type'):
        """
        Classical variable for real-time computation.
        
        Parameters:
        - name: Variable name
        - type: Variable type (Bool, Uint8, etc.)
        """

class expr.Expr:
    """Base class for classical expressions."""
    
    @property  
    def type(self) -> 'Type':
        """Type of the expression result."""

# Expression operations
def expr.bit_and(left: expr.Expr, right: expr.Expr) -> expr.Expr:
    """Bitwise AND of two expressions."""

def expr.bit_or(left: expr.Expr, right: expr.Expr) -> expr.Expr:
    """Bitwise OR of two expressions."""

def expr.bit_xor(left: expr.Expr, right: expr.Expr) -> expr.Expr:
    """Bitwise XOR of two expressions."""

def expr.bit_not(operand: expr.Expr) -> expr.Expr:
    """Bitwise NOT of expression."""

def expr.logic_and(left: expr.Expr, right: expr.Expr) -> expr.Expr:
    """Logical AND of two expressions."""

def expr.logic_or(left: expr.Expr, right: expr.Expr) -> expr.Expr:
    """Logical OR of two expressions."""

def expr.logic_not(operand: expr.Expr) -> expr.Expr:
    """Logical NOT of expression."""

def expr.equal(left: expr.Expr, right: expr.Expr) -> expr.Expr:
    """Equality comparison of two expressions."""

def expr.not_equal(left: expr.Expr, right: expr.Expr) -> expr.Expr:
    """Inequality comparison of two expressions."""

def expr.less(left: expr.Expr, right: expr.Expr) -> expr.Expr:
    """Less-than comparison of two expressions."""

# Classical types
class expr.Type:
    """Base class for classical types."""

class expr.Bool(expr.Type):
    """Boolean type for classical expressions."""

class expr.Uint8(expr.Type):
    """8-bit unsigned integer type."""

Instruction Framework

Base classes for quantum instructions and gates enabling custom operation development.

class Instruction:
    def __init__(self, name: str, num_qubits: int, num_clbits: int, params: List):
        """
        Base quantum instruction.
        
        Parameters:
        - name: Instruction name
        - num_qubits: Number of qubits instruction acts on
        - num_clbits: Number of classical bits instruction acts on  
        - params: Instruction parameters
        """
    
    @property
    def name(self) -> str:
        """Instruction name."""
    
    @property
    def num_qubits(self) -> int:
        """Number of qubits."""
    
    @property
    def num_clbits(self) -> int:
        """Number of classical bits."""
    
    def copy(self):
        """Create a copy of the instruction."""

class Gate(Instruction):
    def __init__(self, name: str, num_qubits: int, params: List):
        """
        Base unitary gate.
        
        Parameters:
        - name: Gate name
        - num_qubits: Number of qubits gate acts on
        - params: Gate parameters
        """
    
    def control(self, num_ctrl_qubits=1, label=None):
        """Create controlled version of gate."""
    
    def inverse(self):
        """Return inverse of gate."""
    
    def power(self, exponent):
        """Return gate raised to a power."""

class ControlledGate(Gate):
    def __init__(self, name: str, num_qubits: int, params: List, num_ctrl_qubits: int):
        """
        Controlled gate with multiple control qubits.
        
        Parameters:
        - name: Gate name
        - num_qubits: Total number of qubits (including controls)
        - params: Gate parameters
        - num_ctrl_qubits: Number of control qubits
        """
    
    @property
    def num_ctrl_qubits(self) -> int:
        """Number of control qubits."""

Circuit Analysis and Utilities

Tools for analyzing and manipulating quantum circuits.

def count_ops(self) -> Dict[str, int]:
    """Count occurrences of each operation type."""

def decompose(self, gate=None):
    """Decompose circuit into more elementary operations."""

def qasm(self, formatted=False, filename=None):
    """Generate OpenQASM representation of circuit."""

def draw(self, output=None, **kwargs):
    """Draw the circuit."""

@property  
def size(self) -> int:
    """Total number of operations in circuit."""

@property
def data(self) -> List:
    """List of circuit instructions."""

def remove_final_measurements(self, inplace=True):
    """Remove final measurement operations."""

def reverse_bits(self):
    """Reverse bit ordering in circuit."""

def tensor(self, other):
    """Tensor product with another circuit."""

Usage Examples

from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Parameter
import numpy as np

# Basic circuit construction
qreg = QuantumRegister(3, 'q')
creg = ClassicalRegister(3, 'c')
circuit = QuantumCircuit(qreg, creg)

# Add gates
circuit.h(qreg[0])  # Hadamard on first qubit
circuit.cx(qreg[0], qreg[1])  # CNOT gate
circuit.cx(qreg[1], qreg[2])  # Another CNOT
circuit.measure(qreg, creg)  # Measure all qubits

# Parameterized circuit
theta = Parameter('θ')
param_circuit = QuantumCircuit(1)
param_circuit.ry(theta, 0)

# Bind parameter value
bound_circuit = param_circuit.assign_parameters({theta: np.pi/4})

# Circuit composition
bell_pair = QuantumCircuit(2)
bell_pair.h(0)
bell_pair.cx(0, 1)

larger_circuit = QuantumCircuit(4)
larger_circuit.compose(bell_pair, qubits=[0, 1])
larger_circuit.compose(bell_pair, qubits=[2, 3])

# Control flow example  
condition_circuit = QuantumCircuit(2, 1)
condition_circuit.h(0)
condition_circuit.measure(0, 0)

# Apply X gate conditionally
with condition_circuit.if_test((0, 1)):  # If measurement result is 1
    condition_circuit.x(1)

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