A framework for creating, editing, and invoking Noisy Intermediate Scale Quantum (NISQ) circuits.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
The qis module provides tools and methods for quantum information science, including quantum state representations, channel transformations, information measures, and stabilizer formalism. It serves as the mathematical foundation for quantum computing operations.
class QuantumState:
"""General quantum state representation."""
def __init__(self, data: 'cirq.QUANTUM_STATE_LIKE',
qid_shape: Optional[Tuple[int, ...]] = None,
dtype: Optional[Type[np.number]] = None,
validate: bool = True,
atol: float = 1e-7) -> None:
"""Initialize quantum state.
Args:
data: State vector, density matrix, or integer
qid_shape: Shape of qid system
dtype: Numeric data type
validate: Whether to validate the state
atol: Absolute tolerance for validation
"""
@property
def data(self) -> np.ndarray:
"""State data (vector or density matrix)."""
@property
def qid_shape(self) -> Tuple[int, ...]:
"""Shape of the qid system."""
def state_vector(self) -> np.ndarray:
"""Get state vector representation (if pure state)."""
def density_matrix(self) -> np.ndarray:
"""Get density matrix representation."""
def partial_trace_over(self, keep_indices: Sequence[int]) -> 'QuantumState':
"""Compute partial trace, keeping specified subsystems."""
class QuantumStateRepresentation(enum.Enum):
"""Enumeration of quantum state representations."""
STATE_VECTOR = "STATE_VECTOR"
DENSITY_MATRIX = "DENSITY_MATRIX"
def quantum_state(state_like: 'cirq.QUANTUM_STATE_LIKE',
qid_shape: Optional[Tuple[int, ...]] = None,
validate: bool = True,
dtype: Optional[Type[np.number]] = None) -> QuantumState:
"""Create quantum state from various inputs."""Functions for working with pure quantum states.
def to_valid_state_vector(state_rep: 'cirq.STATE_VECTOR_LIKE',
num_qubits: Optional[int] = None,
qid_shape: Optional[Tuple[int, ...]] = None,
dtype: Optional[Type[np.number]] = None,
atol: float = 1e-7) -> np.ndarray:
"""Convert and validate state vector.
Args:
state_rep: State vector representation
num_qubits: Number of qubits (if qid_shape not given)
qid_shape: Shape of qid system
dtype: Numeric data type
atol: Tolerance for normalization validation
Returns:
Valid normalized state vector
"""
def validate_normalized_state_vector(state_vector: np.ndarray,
qid_shape: Tuple[int, ...],
dtype: Optional[Type[np.number]] = None,
atol: float = 1e-7) -> np.ndarray:
"""Validate that state vector is normalized."""
def bloch_vector_from_state_vector(state_vector: np.ndarray,
index: int,
qid_shape: Optional[Tuple[int, ...]] = None) -> np.ndarray:
"""Calculate Bloch vector for a single qubit from state vector.
Args:
state_vector: Full system state vector
index: Index of qubit to get Bloch vector for
qid_shape: Shape of qid system
Returns:
3D Bloch vector [x, y, z] coordinates
"""
def dirac_notation(state_vector: np.ndarray,
decimals: int = 2,
qid_shape: Optional[Tuple[int, ...]] = None) -> str:
"""Convert state vector to Dirac notation string.
Args:
state_vector: State vector to represent
decimals: Number of decimal places for coefficients
qid_shape: Shape of qid system
Returns:
Dirac notation string like "|00⟩ + |11⟩"
"""Functions for working with mixed quantum states.
def density_matrix(state: 'cirq.QUANTUM_STATE_LIKE',
qid_shape: Optional[Tuple[int, ...]] = None,
validate: bool = True,
dtype: Optional[Type[np.number]] = None,
atol: float = 1e-7) -> np.ndarray:
"""Create density matrix from state specification.
Args:
state: State vector, density matrix, or integer
qid_shape: Shape of qid system
validate: Whether to validate result
dtype: Numeric data type
atol: Tolerance for validation
Returns:
Density matrix as numpy array
"""
def density_matrix_from_state_vector(state_vector: np.ndarray) -> np.ndarray:
"""Convert state vector to density matrix.
Args:
state_vector: Pure state vector
Returns:
Density matrix ρ = |ψ⟩⟨ψ|
"""
def to_valid_density_matrix(density_matrix_rep: Union[np.ndarray, 'cirq.QUANTUM_STATE_LIKE'],
num_qubits: Optional[int] = None,
qid_shape: Optional[Tuple[int, ...]] = None,
dtype: Optional[Type[np.number]] = None,
atol: float = 1e-7) -> np.ndarray:
"""Convert and validate density matrix."""
def validate_density_matrix(density_matrix: np.ndarray,
qid_shape: Tuple[int, ...],
dtype: Optional[Type[np.number]] = None,
atol: float = 1e-7) -> np.ndarray:
"""Validate density matrix properties (Hermitian, positive semidefinite, trace 1)."""Functions for converting between different quantum channel representations.
def kraus_to_choi(kraus_operators: Sequence[np.ndarray]) -> np.ndarray:
"""Convert Kraus operators to Choi matrix representation.
Args:
kraus_operators: Sequence of Kraus operator matrices
Returns:
Choi matrix of the quantum channel
"""
def choi_to_kraus(choi: np.ndarray, atol: float = 1e-10) -> Tuple[np.ndarray, ...]:
"""Convert Choi matrix to Kraus operators.
Args:
choi: Choi matrix representation
atol: Tolerance for eigenvalue cutoff
Returns:
Tuple of Kraus operator matrices
"""
def kraus_to_superoperator(kraus_operators: Sequence[np.ndarray],
qid_shape: Optional[Tuple[int, ...]] = None) -> np.ndarray:
"""Convert Kraus operators to superoperator matrix.
Args:
kraus_operators: Sequence of Kraus operators
qid_shape: Shape of qid system
Returns:
Superoperator matrix representation
"""
def superoperator_to_kraus(superoperator: np.ndarray,
qid_shape: Optional[Tuple[int, ...]] = None,
atol: float = 1e-10) -> Tuple[np.ndarray, ...]:
"""Convert superoperator matrix to Kraus operators."""
def choi_to_superoperator(choi: np.ndarray,
qid_shape: Optional[Tuple[int, ...]] = None) -> np.ndarray:
"""Convert Choi matrix to superoperator matrix."""
def superoperator_to_choi(superoperator: np.ndarray,
qid_shape: Optional[Tuple[int, ...]] = None) -> np.ndarray:
"""Convert superoperator matrix to Choi matrix."""def operation_to_choi(operation: 'cirq.Operation') -> np.ndarray:
"""Get Choi representation of a quantum operation.
Args:
operation: Quantum operation
Returns:
Choi matrix of the operation
"""
def operation_to_superoperator(operation: 'cirq.Operation') -> np.ndarray:
"""Get superoperator representation of a quantum operation.
Args:
operation: Quantum operation
Returns:
Superoperator matrix of the operation
"""def fidelity(state1: 'cirq.QUANTUM_STATE_LIKE',
state2: 'cirq.QUANTUM_STATE_LIKE',
qid_shape: Optional[Tuple[int, ...]] = None,
validate: bool = True,
atol: float = 1e-7) -> float:
"""Calculate quantum fidelity between two states.
Args:
state1: First quantum state
state2: Second quantum state
qid_shape: Shape of qid system
validate: Whether to validate inputs
atol: Tolerance for validation
Returns:
Fidelity F(ρ₁, ρ₂) ∈ [0, 1]
Notes:
For pure states: F(|ψ⟩, |φ⟩) = |⟨ψ|φ⟩|²
For mixed states: F(ρ₁, ρ₂) = tr(√(√ρ₁ρ₂√ρ₁))
"""
def entanglement_fidelity(channel: Union[Sequence[np.ndarray], np.ndarray],
state: Optional['cirq.QUANTUM_STATE_LIKE'] = None) -> float:
"""Calculate entanglement fidelity of a quantum channel.
Args:
channel: Kraus operators or Choi matrix of channel
state: Input state (maximally mixed if not specified)
Returns:
Entanglement fidelity of the channel
"""def von_neumann_entropy(state: 'cirq.QUANTUM_STATE_LIKE',
qid_shape: Optional[Tuple[int, ...]] = None,
validate: bool = True,
atol: float = 1e-7) -> float:
"""Calculate von Neumann entropy of a quantum state.
Args:
state: Quantum state (pure or mixed)
qid_shape: Shape of qid system
validate: Whether to validate input
atol: Tolerance for validation
Returns:
von Neumann entropy S(ρ) = -tr(ρ log ρ) in bits
Notes:
- Pure states have zero entropy
- Maximally mixed n-qubit state has entropy n
"""
def process_renyi_entropy_from_bitstrings(bitstrings: Sequence[int],
num_qubits: int,
alpha: float = 2.0) -> float:
"""Calculate process Rényi entropy from measurement bitstrings.
Args:
bitstrings: Measurement outcomes as integers
num_qubits: Number of qubits measured
alpha: Rényi entropy parameter
Returns:
Process Rényi entropy
"""Stabilizer state representation using Clifford tableau.
class CliffordTableau:
"""Clifford tableau for stabilizer state representation."""
def __init__(self, num_qubits: int,
initial_state: int = 0) -> None:
"""Initialize Clifford tableau.
Args:
num_qubits: Number of qubits
initial_state: Initial computational basis state
"""
@property
def num_qubits(self) -> int:
"""Number of qubits in the tableau."""
def copy(self) -> 'CliffordTableau':
"""Create a copy of the tableau."""
def stabilizers(self) -> List['cirq.PauliString']:
"""Get stabilizer generators."""
def destabilizers(self) -> List['cirq.PauliString']:
"""Get destabilizer generators."""
def to_state_vector(self) -> np.ndarray:
"""Convert to state vector representation (exponential cost)."""
def apply_single_qubit_clifford(self, clifford: 'cirq.SingleQubitCliffordGate',
qubit_index: int) -> None:
"""Apply single-qubit Clifford gate."""
def apply_cx(self, control: int, target: int) -> None:
"""Apply CNOT gate between control and target qubits."""
def apply_cz(self, qubit1: int, qubit2: int) -> None:
"""Apply CZ gate between two qubits."""
def measure(self, qubit_index: int, prng: Optional[np.random.Generator] = None) -> int:
"""Measure qubit in computational basis."""General stabilizer state representation.
class StabilizerState:
"""Stabilizer state representation."""
def __init__(self, num_qubits: int, initial_state: int = 0) -> None:
"""Initialize stabilizer state."""
@property
def num_qubits(self) -> int:
"""Number of qubits."""
def copy(self) -> 'StabilizerState':
"""Create a copy of the state."""
def stabilizer_generators(self) -> List['cirq.PauliString']:
"""Get stabilizer generators."""
def to_numpy(self) -> np.ndarray:
"""Convert to state vector (exponential cost for large systems)."""
def inner_product_of_state_and_x(self, x: int) -> complex:
"""Compute ⟨ψ|x⟩ where |x⟩ is computational basis state."""def eye_tensor(qid_shape: Sequence[int]) -> np.ndarray:
"""Create identity tensor for given qid shape.
Args:
qid_shape: Dimensions of each qid
Returns:
Identity tensor
"""
def one_hot(*, index: Union[int, Sequence[int]],
shape: Union[int, Sequence[int]],
dtype: Type[np.number] = np.complex64) -> np.ndarray:
"""Create one-hot state vector.
Args:
index: Index or indices for non-zero entry
shape: Shape of resulting tensor
dtype: Data type
Returns:
One-hot tensor with single non-zero entry
"""
def validate_indices(num_qubits: int, indices: Sequence[int]) -> None:
"""Validate qubit indices are in valid range."""
def validate_qid_shape(vals: Any, qid_shape: Tuple[int, ...], name: str = 'vals') -> None:
"""Validate that values match expected qid shape."""
def infer_qid_shape(vals: Any, default: Optional[Tuple[int, ...]] = None) -> Tuple[int, ...]:
"""Infer qid shape from values."""Functions for characterizing and converting noise parameters.
def decay_constant_to_xeb_fidelity(decay_constant: float, num_qubits: int) -> float:
"""Convert decay constant to cross-entropy benchmarking fidelity."""
def decay_constant_to_pauli_error(decay_constant: float) -> float:
"""Convert decay constant to Pauli error rate."""
def pauli_error_to_decay_constant(pauli_error: float) -> float:
"""Convert Pauli error rate to decay constant."""
def xeb_fidelity_to_decay_constant(xeb_fidelity: float, num_qubits: int) -> float:
"""Convert XEB fidelity to decay constant."""
def pauli_error_from_t1(t1_ns: float, gate_time_ns: float) -> float:
"""Calculate Pauli error from T1 coherence time."""
def average_error(errors: Sequence[float]) -> float:
"""Calculate average error rate."""
def decoherence_pauli_error(t1_ns: float, t2_ns: float, gate_time_ns: float) -> float:
"""Calculate decoherence Pauli error from T1, T2, and gate time."""QUANTUM_STATE_LIKE = Union[int, np.ndarray, 'cirq.QuantumState']
"""Type for objects that can represent quantum states."""
STATE_VECTOR_LIKE = Union[int, np.ndarray, Sequence[Union[int, float, complex]]]
"""Type for objects that can represent state vectors."""import cirq
import numpy as np
# Create quantum states in different ways
print("=== Creating Quantum States ===")
# From computational basis
zero_state = cirq.quantum_state(0, qid_shape=(2, 2)) # |00⟩
print(f"Zero state: {cirq.dirac_notation(zero_state.state_vector())}")
# From state vector
bell_state = np.array([1, 0, 0, 1]) / np.sqrt(2) # (|00⟩ + |11⟩)/√2
bell_qs = cirq.quantum_state(bell_state)
print(f"Bell state: {cirq.dirac_notation(bell_qs.state_vector())}")
# From density matrix
mixed_state = np.eye(4) / 4 # Maximally mixed 2-qubit state
mixed_qs = cirq.quantum_state(mixed_state)
print(f"Mixed state entropy: {cirq.von_neumann_entropy(mixed_qs):.3f} bits")
# Bloch vector of single qubit
qubit_0_bloch = cirq.bloch_vector_from_state_vector(bell_state, index=0)
print(f"Qubit 0 Bloch vector: {qubit_0_bloch}")import cirq
import numpy as np
# Analyze depolarizing channel
print("=== Quantum Channel Analysis ===")
# Create depolarizing channel
p = 0.1 # Error probability
depol_channel = cirq.depolarize(p)
kraus_ops = cirq.kraus(depol_channel)
print(f"Depolarizing channel has {len(kraus_ops)} Kraus operators")
# Convert between representations
choi_matrix = cirq.kraus_to_choi(kraus_ops)
superop_matrix = cirq.kraus_to_superoperator(kraus_ops)
print(f"Choi matrix shape: {choi_matrix.shape}")
print(f"Superoperator shape: {superop_matrix.shape}")
# Channel fidelity
input_state = np.array([1, 0]) # |0⟩ state
ent_fidelity = cirq.entanglement_fidelity(kraus_ops, input_state)
print(f"Entanglement fidelity: {ent_fidelity:.4f}")
# Back-convert to verify
recovered_kraus = cirq.choi_to_kraus(choi_matrix)
print(f"Recovered {len(recovered_kraus)} Kraus operators")import cirq
import numpy as np
print("=== Fidelity Measures ===")
# Create two quantum states
state1 = np.array([1, 0, 0, 0]) # |00⟩
state2 = np.array([0, 1, 1, 0]) / np.sqrt(2) # (|01⟩ + |10⟩)/√2
# Pure state fidelity
fid = cirq.fidelity(state1, state2)
print(f"Fidelity between |00⟩ and (|01⟩ + |10⟩)/√2: {fid:.4f}")
# Mixed state fidelity
rho1 = np.outer(state1, state1) # Pure state density matrix
rho2 = np.eye(4) / 4 # Maximally mixed state
mixed_fid = cirq.fidelity(rho1, rho2)
print(f"Fidelity between pure |00⟩ and maximally mixed: {mixed_fid:.4f}")
# von Neumann entropy
entropy1 = cirq.von_neumann_entropy(rho1)
entropy2 = cirq.von_neumann_entropy(rho2)
print(f"Entropy of pure state: {entropy1:.6f}")
print(f"Entropy of maximally mixed: {entropy2:.3f}")import cirq
print("=== Stabilizer Formalism ===")
# Create Clifford tableau
num_qubits = 3
tableau = cirq.CliffordTableau(num_qubits)
# Apply Clifford gates
tableau.apply_single_qubit_clifford(cirq.H, 0) # H on qubit 0
tableau.apply_cx(0, 1) # CNOT(0, 1)
tableau.apply_cx(0, 2) # CNOT(0, 2)
# Get stabilizer generators
stabilizers = tableau.stabilizers()
print("Stabilizers of GHZ state:")
for i, stab in enumerate(stabilizers):
print(f" S_{i}: {stab}")
# Convert to state vector (expensive for large systems)
if num_qubits <= 10: # Only for small systems
state_vector = tableau.to_state_vector()
print(f"State vector: {cirq.dirac_notation(state_vector)}")
# Measure a qubit
measurement_result = tableau.measure(0)
print(f"Measured qubit 0: {measurement_result}")import cirq
print("=== Noise Characterization ===")
# Convert between noise representations
t1_ns = 50000 # 50 μs T1 time
t2_ns = 25000 # 25 μs T2 time
gate_time_ns = 50 # 50 ns gate time
# Calculate various error rates
pauli_error_t1 = cirq.pauli_error_from_t1(t1_ns, gate_time_ns)
decoherence_error = cirq.decoherence_pauli_error(t1_ns, t2_ns, gate_time_ns)
print(f"Pauli error from T1: {pauli_error_t1:.6f}")
print(f"Total decoherence error: {decoherence_error:.6f}")
# Convert to decay constants
decay_constant = cirq.pauli_error_to_decay_constant(decoherence_error)
xeb_fidelity = cirq.decay_constant_to_xeb_fidelity(decay_constant, num_qubits=2)
print(f"Decay constant: {decay_constant:.6f}")
print(f"2-qubit XEB fidelity: {xeb_fidelity:.6f}")
# Average multiple error sources
gate_errors = [0.001, 0.0015, 0.0008, 0.0012] # Different gate error rates
avg_error = cirq.average_error(gate_errors)
print(f"Average gate error: {avg_error:.6f}")This quantum information science toolkit provides the mathematical foundation for quantum computing, enabling analysis of quantum states, channels, and information-theoretic quantities essential for NISQ applications.
Install with Tessl CLI
npx tessl i tessl/pypi-cirq