Skip to content

Troubleshooting and Common Errors

This guide documents the most common syntax, logical, and quantum physical errors encountered when building circuits with quantum-emotion, showing the exact Python error tracebacks, explaining the root causes, and providing working solutions.

Tutorial Signposts: - Common Mistakes: Tutorial 15: Common Mistakes and Fixes (GitHub) - Debugging Exercises: Tutorial 16: Debugging Exercises (GitHub) - Large Circuits & Limits: Tutorial 14: Large Circuits and Tensor Networks (GitHub)


1. Syntax and API Errors

1.1 AttributeError: 'KetState' object has no attribute 'probabilities'

Trigger Code

from quantum_emotion import KetState, Hadamard

psi = Hadamard(wires=0) @ KetState(N=1)
probs = psi.probabilities()  # ERROR

Traceback

AttributeError: 'KetState' object has no attribute 'probabilities'

Root Cause

In quantum-emotion, KetState represents a state register abstraction backed by a tensor network graph, not a simple NumPy probability vector. There is no built-in .probabilities() method.

Fixed Code

Calculate probabilities directly using the Born rule (\(P(x) = |\langle x|\psi\rangle|^2\)):

import numpy as np
from quantum_emotion import KetState, Hadamard

psi = Hadamard(wires=0) @ KetState(N=1)

# Evaluate state vector and compute squared amplitudes
state_vector = psi.eval()
probs = np.abs(state_vector) ** 2
print("Measurement probabilities:", probs)

1.2 AttributeError: 'complex' object has no attribute 'eval'

Trigger Code

from quantum_emotion import KetState, PauliZ

psi = KetState(N=1)
exp_val = (psi.conj @ PauliZ(wires=0) @ psi).eval()  # ERROR

Traceback

AttributeError: 'complex' object has no attribute 'eval'

Root Cause

Dirac notation contractions between a BraState and a KetState (bra @ ket or bra @ Operator @ ket) immediately contract the tensor network into a scalar. The return value is a native Python complex number, not a wrapper object. Calling .eval() on a scalar raises an AttributeError.

Fixed Code

Use the returned scalar directly without calling .eval():

import numpy as np
from quantum_emotion import KetState, PauliZ

psi = KetState(N=1)
exp_val = float(np.real(psi.conj @ PauliZ(wires=0) @ psi))
print("<Z> expectation value:", exp_val)

1.3 ValueError: Register has no mid-circuit measurements to sample

Trigger Code

from quantum_emotion import KetState, Hadamard

psi = Hadamard(wires=0) @ KetState(N=1)
samples = psi.sample(shots=1000)  # ERROR

Traceback

ValueError: Register has no mid-circuit measurements to sample.

Root Cause

The .sample(shots=...) method simulates laboratory readout by sampling classical measurement bits recorded during circuit execution. If no Measure gate was placed in the circuit graph, there are no measurement records to sample.

Fixed Code

Insert a Measure(wires=...) operator into the circuit before sampling:

import numpy as np
from quantum_emotion import KetState, Hadamard, Measure

# Apply Hadamard and measure wire 0
state = Measure(wires=0) @ Hadamard(wires=0) @ KetState(N=1)
samples = state.sample(shots=1000)
print("Sample counts:", {val: int(cnt) for val, cnt in zip(*np.unique(samples, return_counts=True))})

If you only want theoretical sampling from the Born rule without circuit measurement gates:

import numpy as np

probs = np.abs(psi.eval()) ** 2
shots = np.random.choice(len(probs), size=1000, p=probs)

1.4 TypeError: 'BaseGate' object is not callable when Using .dagger

Trigger Code

from quantum_emotion import Hadamard

h_inv = Hadamard(wires=0).dagger()  # ERROR: called as method

Traceback

TypeError: 'BaseGate' object is not callable

Root Cause

In quantum-emotion, BaseGate.dagger is a property, not a method. Appending parentheses attempts to execute the gate as a function.

Fixed Code

Access .dagger as a property without parentheses:

from quantum_emotion import Hadamard

h_inv = Hadamard(wires=0).dagger  # Correct: property access

1.5 TypeError: BaseGate.__init__() got an unexpected keyword argument 'd'

Trigger Code

import numpy as np
from quantum_emotion import BaseGate

class CustomGate(BaseGate):
    def __init__(self, wires):
        mat = np.array([[1, 0], [0, -1]], dtype=np.complex128)
        super().__init__(wires=wires, d=2, mat=mat)  # ERROR: unexpected 'd'

Traceback

TypeError: BaseGate.__init__() got an unexpected keyword argument 'd'

Root Cause

The constructor signature for BaseGate is __init__(wires, mat=None, is_unitary=True). The Hilbert space dimension is automatically inferred from mat.shape.

Fixed Code

Remove the d keyword argument:

import numpy as np
from quantum_emotion import BaseGate

class CustomGate(BaseGate):
    def __init__(self, wires):
        mat = np.array([[1, 0], [0, -1]], dtype=np.complex128)
        super().__init__(wires=wires, mat=mat)

2. Logical and Circuit Design Errors

2.1 TypeError: Unsupported circuit operation: CompositeGate

Trigger Code

from quantum_emotion import KetState, PauliX, CompositeGate

class Oracle(CompositeGate):
    def __init__(self, wires):
        ops = [PauliX(wires=0), PauliX(wires=1)]
        super().__init__(wires=wires, gates=ops)

class Algorithm(CompositeGate):
    def __init__(self, wires):
        # ERROR: Nesting CompositeGate inside another CompositeGate
        ops = [Oracle(wires=wires)]
        super().__init__(wires=wires, gates=ops)

Traceback

TypeError: Unsupported circuit operation: CompositeGate

Root Cause

CoreRegister._apply() requires a flat sequence of operations (BaseGate, ModularGate, Measure, ClassicallyControlledGate). Nesting CompositeGate objects directly inside another CompositeGate is unsupported.

Fixed Code

Either chain operations sequentially onto the state with @, define the sub-circuit as a Python function, or encapsulate it as a ModularGate:

from quantum_emotion import KetState, ModularGate, PauliX

def create_oracle_module(wires=(0, 1)):
    return ModularGate(PauliX(wires=wires[0]), PauliX(wires=wires[1]), wires=wires)

state = create_oracle_module() @ KetState(N=2)

2.2 AttributeError: 'tuple' object has no attribute 'eval_density_matrix'

Trigger Code

from quantum_emotion import KetState, Hadamard, Measure

circuit = Measure(wires=0) @ Hadamard(wires=0) @ KetState(N=1)
branches = circuit.eval_branches()

for outcome, state in branches.items():
    rho = state.eval_density_matrix(wires=0)  # ERROR: state is a tuple

Traceback

AttributeError: 'tuple' object has no attribute 'eval_density_matrix'

Root Cause

eval_branches() returns a dictionary mapping measurement outcomes to a tuple of (probability: float, state_vector: np.ndarray). The dictionary values are raw tuples, not KetState objects.

Fixed Code

Unpack the tuple into its probability and state vector components:

for outcome, (prob, branch_vec) in branches.items():
    print(f"Outcome {outcome}: Probability = {prob:.2f}, State Vector = {branch_vec}")

2.3 Applying Multi-Qubit Gates with Non-Distinct Wires

Trigger Code

from quantum_emotion import KetState, CNOT

psi = CNOT(wires=(0, 0)) @ KetState(N=2)  # ERROR: control equals target

Root Cause

In quantum mechanics, a multi-qubit gate requires distinct physical subsystems. A qubit cannot act simultaneously as both the control and the target of a coherent interaction.

Fixed Code

Specify distinct wire indices for control and target:

from quantum_emotion import KetState, CNOT

psi = CNOT(wires=(0, 1)) @ KetState(N=2)  # Wire 0 controls wire 1

3. Quantum Physics and Simulation Limits

3.1 Calling psi.eval() on Large Registers (\(N \ge 30\) Qubits)

Trigger Code

from quantum_emotion import KetState, Hadamard, CNOT

N = 40
psi = KetState(N=N)
psi = Hadamard(wires=0) @ psi
for w in range(N - 1):
    psi = CNOT(wires=(w, w + 1)) @ psi

full_vector = psi.eval()  # ValueError: would materialize ~16,384 GiB

Root Cause

An \(N\)-qubit state vector contains \(2^N\) complex amplitudes (16 bytes each): - \(N = 30\): \(\approx 16 \text{ GB}\) - \(N = 40\): \(\approx 16 \text{ TB}\) - \(N = 100\): \(\approx 2 \times 10^{19} \text{ TB}\)

Rather than letting Python crash your machine, quantum-emotion checks the dense size upfront and raises a ValueError when .eval() would exceed safe array limits.

Working Solution

Don't materialize the full state vector. Instead, compute local expectation values, sample shots, or evaluate reduced density matrices on a small set of wires:

import numpy as np
from quantum_emotion import PauliZ

exp_corr = float(np.real(psi.conj @ PauliZ(wires=0) @ PauliZ(wires=N - 1) @ psi))
print("<Z_0 Z_39> correlation:", exp_corr)

# 2-qubit reduced density matrix on the ends (traces out middle wires)
rho_boundary = psi.eval_density_matrix(wires=(0, N - 1))
print("Boundary density matrix shape:", rho_boundary.shape)  # (4, 4)

3.2 Volume-Law vs Area-Law Entanglement in Tensor Networks

If quantum-emotion handles a 40-qubit 1D GHZ chain easily, why can't it simulate any 40-qubit circuit?

  1. Area-Law Entanglement + Unitary Cancellation (Fast): In a 1D chain like a GHZ state, entanglement across any cut is bounded (1 bit), and when measuring endpoint observables, unmeasured middle gates cancel out (\(U^\dagger U = I\)).
  2. Volume-Law Entanglement (Hard): In deep 2D or all-to-all circuits, entanglement spreads across every cut and intermediate tensor sizes grow exponentially (\(D \sim 2^{N/2}\)).

Simulating arbitrary deep circuits at \(N = 40+\) remains classically intractable.


3.3 ValueError: Gate matrix is not unitary

Trigger Code

import numpy as np
from quantum_emotion import BaseGate

# Non-unitary matrix: does not satisfy M @ M^dagger = I
bad_mat = np.array([[2.0, 0.0], [0.0, 1.0]], dtype=np.complex128)
bad_gate = BaseGate(wires=0, mat=bad_mat)  # Raises ValueError

Root Cause

Closed quantum gates must preserve total probability (\(\sum_x |\alpha_x|^2 = 1\)), meaning \(M M^\dagger = I\). BaseGate validates unitarity at construction by default and raises ValueError if your matrix isn't unitary.

Working Solution

  • For a quantum gate, check unitarity before constructing it:
    assert np.allclose(mat @ mat.conj().T, np.eye(mat.shape[0])), "Matrix is not unitary!"
    
  • If you are intentionally building a non-unitary operator (e.g., a projector or observable), pass is_unitary=False to BaseGate(wires=..., mat=..., is_unitary=False).

3.4 Trying to Clone an Unknown State with CNOT

The Physics Mistake

A common mistake is trying to copy a qubit \(|\psi\rangle = \alpha|0\rangle + \beta|1\rangle\) onto a second qubit in \(|0\rangle\) using CNOT:

from quantum_emotion import KetState, Hadamard, CNOT

# Prepare |+> on wire 0, |0> on wire 1, then apply CNOT
psi_entangled = CNOT(wires=(0, 1)) @ Hadamard(wires=0) @ KetState(N=2)

This does not copy \(|+\rangle\) onto wire 1: - A true copy would be \(|+\rangle \otimes |+\rangle = \frac{1}{2}(|00\rangle + |01\rangle + |10\rangle + |11\rangle)\). - What CNOT actually produces is the entangled Bell state \(\frac{1}{\sqrt{2}}(|00\rangle + |11\rangle)\).

By the No-Cloning Theorem, no unitary gate can duplicate an arbitrary unknown quantum state.

Working Solution

To move a state from one wire to another without copying it, use Quantum Teleportation (Tutorial 5: Quantum Teleportation), which transfers the state to the destination wire while collapsing the original wire.