Skip to Content

Quantum Gates and Measurement

Gate methods mutate Circuit in place. Angle parameters are in radians, and qubit indices start at 0. Do not rely on gate method return values for chaining.

Single-qubit gates

from unitarylab import Circuit qc = Circuit(4) qc.h(0) qc.x(1) qc.y(2) qc.z(3) qc.s(0) qc.sdag(1) qc.t(2) qc.tdag(3) qc.sx(0) qc.sxdag(1) qc.i(2) # Broadcast a gate to multiple qubits. qc.h([0, 1, 2])

Parameterized gates

import numpy as np qc.rx(np.pi / 2, 0) qc.ry(np.pi / 4, 1) qc.rz(np.pi / 8, 2) qc.rzz(np.pi / 3, 0, 1) qc.p(np.pi / 2, 0) qc.u1(np.pi / 4, 0) qc.u2(np.pi / 3, np.pi / 5, 1) qc.u3(np.pi / 2, np.pi / 3, np.pi / 4, 2) qc.gp(np.pi / 6)

Controlled and multi-qubit gates

qc.cx(0, 1) qc.mcx([0, 1], 2) qc.cy(0, 1) qc.cz(0, 1) qc.ch(0, 1) qc.cp(np.pi / 2, 0, 1) qc.crx(np.pi / 2, 0, 1) qc.swap(0, 1)

Controlled gates accept an optional control_state. None means the gate triggers when all control qubits are 1; a pattern such as "01" specifies another control state. Add an arbitrary unitary with unitary(matrix, target).

matrix = np.array([[0, 1], [1, 0]], dtype=complex) qc.unitary(matrix, target=0)

The custom matrix must be a square matrix of dimension and be unitary. target must contain exactly k distinct qubits. Control qubits and target qubits must not overlap.

Measurement

qc = Circuit(2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) result = qc.execute() print(result.classical_results_map)
  • Both arguments to measure(qubit, clbit) may be integers or lists; their lengths must match.
  • A qubit and a classical bit can each be mapped only once; duplicate mappings raise ValueError.
  • Measurement occurs during execution, and outcomes are written to ExecutionResult.classical_results_map.

Circuit.measure() only creates a mapping from quantum to classical bits. To sample the final state of a circuit without measurement instructions, use ExecutionResult.sample(). To perform a projective measurement that collapses the state held by the result object, use ExecutionResult.measure().

Input validation

  • Rotation angles and custom matrix elements must be finite numbers.
  • Broadcast gates accept a single index or an index collection; control and target counts for multi-qubit gates must match the gate definition.
  • A circuit containing measurements is no longer purely unitary and is not suitable for direct get_matrix() calls.
  • The number of bits in control_state must match the number of control qubits; values must be 0 or 1.

For execution and result queries, see Executing Circuits and Reading Results.

Last updated on