Skip to content

Gates

quanta.core.gates

  • A name (name)
  • Unitary matrix representation (matrix)
Example

from quanta.core.gates import H, CX H.matrix.shape (2, 2) CX.num_qubits 2

Gate

Base class for a quantum gate.

Attributes:

Name Type Description
name str

Gate name (e.g. "H", "CX").

num_qubits int

Number of qubits this gate acts on.

Source code in quanta/core/gates.py
class Gate:
    """Base class for a quantum gate.

    Attributes:
        name: Gate name (e.g. "H", "CX").
        num_qubits: Number of qubits this gate acts on.
    """

    name: str = ""
    num_qubits: int = 1

    @property
    def matrix(self) -> np.ndarray:
        """Unitary matrix representation of the gate."""
        return self._build_matrix()

    def _build_matrix(self) -> np.ndarray:
        raise NotImplementedError

    @property
    def inverse(self) -> Gate:
        """Returns the inverse (adjoint) gate: U†.

        For self-inverse gates (H, X, Y, Z, CX, CZ, SWAP) returns self.
        For known pairs (S↔SDG, T↔TDG, SX↔SXdg) returns the partner.
        Otherwise computes U† from the matrix.

        Example:
            >>> S.inverse.name
            'SDG'
            >>> H.inverse is H
            True
        """
        # Check known inverse pairs
        if self.name in _INVERSE_MAP:
            return GATE_REGISTRY[_INVERSE_MAP[self.name]]
        # Self-inverse gates
        if self.name in _SELF_INVERSE_GATES:
            return self
        # Fallback: compute U† from matrix
        return _MatrixGate(
            f"{self.name}†", self.matrix.conj().T, self.num_qubits,
        )

    def controlled(self, num_ctrl: int = 1) -> Gate:
        """Returns a controlled version of this gate.

        Builds a (num_ctrl + num_qubits)-qubit controlled-U gate.
        The first num_ctrl qubits are controls, the rest are targets.

        Args:
            num_ctrl: Number of control qubits (default: 1).

        Returns:
            A new Gate with the controlled-U matrix.

        Example:
            >>> X.controlled().name
            'CX'
            >>> H.controlled().num_qubits
            2
        """
        if num_ctrl < 1:
            from quanta.core.types import GateError
            raise GateError(f"num_ctrl must be >= 1, got {num_ctrl}")

        total_qubits = self.num_qubits + num_ctrl
        dim = 2 ** total_qubits
        target_dim = 2 ** self.num_qubits

        # Build controlled-U: identity for all states except
        # when all controls are |1⟩
        cu = np.eye(dim, dtype=complex)
        # Replace bottom-right block with U
        u_mat = self.matrix
        start = dim - target_dim
        cu[start:, start:] = u_mat

        prefix = "C" * num_ctrl
        return _MatrixGate(f"{prefix}{self.name}", cu, total_qubits)

    def __call__(self, *args: QubitRef | Iterable[QubitRef]) -> None:
        """Records gate to active circuit. Supports broadcast.

            H(q[0])           → single qubit
            H(q)              → broadcast to all qubits
        """
        qubits = _flatten_qubits(args)

        if self.num_qubits == 1 and len(qubits) > 1:
            # Broadcast: H(q) = H(q[0]), H(q[1]), ...
            for qubit in qubits:
                _get_active_builder().record(
                    Instruction(self.name, (qubit,))
                )
        else:
            if len(qubits) != self.num_qubits:
                from quanta.core.types import GateError
                raise GateError(
                    f"Gate '{self.name}' expects {self.num_qubits} "
                    f"qubit(s), got {len(qubits)}."
                )
            _get_active_builder().record(
                Instruction(self.name, tuple(qubits))
            )

    def __repr__(self) -> str:
        return f"Gate({self.name})"
inverse property
inverse: Gate

Returns the inverse (adjoint) gate: U†.

For self-inverse gates (H, X, Y, Z, CX, CZ, SWAP) returns self. For known pairs (S↔SDG, T↔TDG, SX↔SXdg) returns the partner. Otherwise computes U† from the matrix.

Example

S.inverse.name 'SDG' H.inverse is H True

matrix property
matrix: ndarray

Unitary matrix representation of the gate.

__call__
__call__(*args: QubitRef | Iterable[QubitRef]) -> None

Records gate to active circuit. Supports broadcast.

H(q[0]) → single qubit H(q) → broadcast to all qubits

Source code in quanta/core/gates.py
def __call__(self, *args: QubitRef | Iterable[QubitRef]) -> None:
    """Records gate to active circuit. Supports broadcast.

        H(q[0])           → single qubit
        H(q)              → broadcast to all qubits
    """
    qubits = _flatten_qubits(args)

    if self.num_qubits == 1 and len(qubits) > 1:
        # Broadcast: H(q) = H(q[0]), H(q[1]), ...
        for qubit in qubits:
            _get_active_builder().record(
                Instruction(self.name, (qubit,))
            )
    else:
        if len(qubits) != self.num_qubits:
            from quanta.core.types import GateError
            raise GateError(
                f"Gate '{self.name}' expects {self.num_qubits} "
                f"qubit(s), got {len(qubits)}."
            )
        _get_active_builder().record(
            Instruction(self.name, tuple(qubits))
        )
controlled
controlled(num_ctrl: int = 1) -> Gate

Returns a controlled version of this gate.

Builds a (num_ctrl + num_qubits)-qubit controlled-U gate. The first num_ctrl qubits are controls, the rest are targets.

Parameters:

Name Type Description Default
num_ctrl int

Number of control qubits (default: 1).

1

Returns:

Type Description
Gate

A new Gate with the controlled-U matrix.

Example

X.controlled().name 'CX' H.controlled().num_qubits 2

Source code in quanta/core/gates.py
def controlled(self, num_ctrl: int = 1) -> Gate:
    """Returns a controlled version of this gate.

    Builds a (num_ctrl + num_qubits)-qubit controlled-U gate.
    The first num_ctrl qubits are controls, the rest are targets.

    Args:
        num_ctrl: Number of control qubits (default: 1).

    Returns:
        A new Gate with the controlled-U matrix.

    Example:
        >>> X.controlled().name
        'CX'
        >>> H.controlled().num_qubits
        2
    """
    if num_ctrl < 1:
        from quanta.core.types import GateError
        raise GateError(f"num_ctrl must be >= 1, got {num_ctrl}")

    total_qubits = self.num_qubits + num_ctrl
    dim = 2 ** total_qubits
    target_dim = 2 ** self.num_qubits

    # Build controlled-U: identity for all states except
    # when all controls are |1⟩
    cu = np.eye(dim, dtype=complex)
    # Replace bottom-right block with U
    u_mat = self.matrix
    start = dim - target_dim
    cu[start:, start:] = u_mat

    prefix = "C" * num_ctrl
    return _MatrixGate(f"{prefix}{self.name}", cu, total_qubits)

MultiParametricGate

Multi-parameter gate factory. Like U(θ, φ, λ).

Source code in quanta/core/gates.py
class MultiParametricGate:
    """Multi-parameter gate factory. Like U(θ, φ, λ)."""

    def __init__(self, name: str, matrix_fn, num_params: int = 3) -> None:
        self.name = name
        self._matrix_fn = matrix_fn
        self.num_params = num_params

    def __call__(self, *params: float) -> _BoundMultiParametricGate:
        return _BoundMultiParametricGate(
            self.name, params, self._matrix_fn,
        )

    def __repr__(self) -> str:
        return f"MultiParametricGate({self.name})"

ParametricGate

Parametric gate factory. Like RX(θ), RY(θ), RZ(θ).

Example

RY(np.pi/4)(q[0]) # θ=π/4 ile RY uygula

Source code in quanta/core/gates.py
class ParametricGate:
    """Parametric gate factory. Like RX(θ), RY(θ), RZ(θ).


    Example:
        >>> RY(np.pi/4)(q[0])  # θ=π/4 ile RY uygula
    """

    def __init__(self, name: str, matrix_fn, num_qubits: int = 1) -> None:
        self.name = name
        self._matrix_fn = matrix_fn
        self.num_qubits = num_qubits

    def __call__(self, theta: float) -> _BoundParametricGate:
        """Returns a gate bound with an angle."""
        return _BoundParametricGate(
            self.name, theta, self._matrix_fn, self.num_qubits,
        )

    def __repr__(self) -> str:
        return f"ParametricGate({self.name})"
__call__
__call__(theta: float) -> _BoundParametricGate

Returns a gate bound with an angle.

Source code in quanta/core/gates.py
def __call__(self, theta: float) -> _BoundParametricGate:
    """Returns a gate bound with an angle."""
    return _BoundParametricGate(
        self.name, theta, self._matrix_fn, self.num_qubits,
    )