Qx.CalcFast (Qx - Quantum Computing Simulator v0.6.0)
View SourceOptimized quantum gate operations using direct statevector manipulation.
This module provides high-performance implementations that apply gates directly to statevectors without building full 2^n x 2^n gate matrices. All functions are compiled with Nx.Defn for GPU/CPU acceleration.
Performance
Compared to the original matrix-based approach:
- Memory: O(2^n) instead of O(2^(2n))
- Speed: 10-1000x faster depending on circuit size
- GPU-friendly: All operations use Nx primitives that compile to XLA
Implementation Notes
These implementations follow the approach used by production quantum simulators like Qiskit-Aer and Cirq, manipulating statevector amplitudes directly rather than constructing and multiplying large matrices.
Summary
Functions
Applies a CNOT gate directly to a statevector.
Applies a Toffoli (CCX) gate directly to a statevector.
Applies a single-qubit gate directly to a statevector.
Functions
Applies a CNOT gate directly to a statevector.
CNOT flips the target qubit if and only if the control qubit is |1⟩.
Parameters
state- State vector (2^n dimensional complex tensor)control_qubit- Index of control qubittarget_qubit- Index of target qubitnum_qubits- Total number of qubits in the system
Algorithm
For each basis state in the statevector:
- Check if control qubit is |1⟩
- If yes, swap amplitude with state that has target qubit flipped
- If no, leave amplitude unchanged
This is much faster than building a 2^n x 2^n CNOT matrix.
Applies a Toffoli (CCX) gate directly to a statevector.
Toffoli flips the target qubit if and only if both control qubits are |1⟩.
Parameters
state- State vector (2^n dimensional complex tensor)control1- Index of first control qubitcontrol2- Index of second control qubittarget- Index of target qubitnum_qubits- Total number of qubits in the system
Applies a single-qubit gate directly to a statevector.
This function applies a 2x2 gate matrix to a specific qubit in an n-qubit system by manipulating the statevector amplitudes directly.
Parameters
state- State vector (2^n dimensional complex tensor)gate_matrix- 2x2 gate matrix (from Qx.Gates)target_qubit- Index of qubit to apply gate to (0-based)num_qubits- Total number of qubits in the system
Algorithm
For a gate applied to qubit k in an n-qubit system:
- Iterate through statevector indices in pairs that differ only in qubit k
- Apply 2x2 gate matrix to each pair of amplitudes
- Update statevector in-place
This avoids building a 2^n x 2^n matrix, using only O(2^n) memory.