qiskit.circuit.gate의 소스 코드

# This code is part of Qiskit.
# (C) Copyright IBM 2017.
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""Unitary gate."""

from warnings import warn
from typing import List, Optional, Union, Tuple
import numpy as np
from scipy.linalg import schur

from qiskit.circuit.parameter import ParameterExpression
from qiskit.circuit.exceptions import CircuitError
from .instruction import Instruction

[문서]class Gate(Instruction): """Unitary gate."""
[문서] def __init__(self, name: str, num_qubits: int, params: List, label: Optional[str] = None) -> None: """Create a new gate. Args: name: The Qobj name of the gate. num_qubits: The number of qubits the gate acts on. params: A list of parameters. label: An optional label for the gate. """ self._label = label self.definition = None super().__init__(name, num_qubits, 0, params)
[문서] def to_matrix(self) -> np.ndarray: """Return a Numpy.array for the gate unitary matrix. Raises: CircuitError: If a Gate subclass does not implement this method an exception will be raised when this base class method is called. """ raise CircuitError("to_matrix not defined for this {}".format(type(self)))
[문서] def power(self, exponent: float): """Creates a unitary gate as `gate^exponent`. Args: exponent (float): Gate^exponent Returns: qiskit.extensions.UnitaryGate: To which `to_matrix` is self.to_matrix^exponent. Raises: CircuitError: If Gate is not unitary """ from qiskit.quantum_info.operators import Operator # pylint: disable=cyclic-import from qiskit.extensions.unitary import UnitaryGate # pylint: disable=cyclic-import # Should be diagonalized because it's a unitary. decomposition, unitary = schur(Operator(self).data, output='complex') # Raise the diagonal entries to the specified power decomposition_power = list() decomposition_diagonal = decomposition.diagonal() # assert off-diagonal are 0 if not np.allclose(np.diag(decomposition_diagonal), decomposition): raise CircuitError('The matrix is not diagonal') for element in decomposition_diagonal: decomposition_power.append(pow(element, exponent)) # Then reconstruct the resulting gate. unitary_power = unitary @ np.diag(decomposition_power) @ unitary.conj().T return UnitaryGate(unitary_power, label='%s^%s' % (, exponent))
def _return_repeat(self, exponent: float) -> 'Gate': return Gate(name="%s*%s" % (, exponent), num_qubits=self.num_qubits, params=self.params)
[문서] def assemble(self) -> 'Instruction': """Assemble a QasmQobjInstruction""" instruction = super().assemble() if self.label: instruction.label = self.label return instruction
@property def label(self) -> str: """Return gate label""" return self._label @label.setter def label(self, name: str): """Set gate label to name Args: name (str or None): label to assign unitary Raises: TypeError: name is not string or None. """ if isinstance(name, (str, type(None))): self._label = name else: raise TypeError('label expects a string or None')
[문서] def control(self, num_ctrl_qubits: Optional[int] = 1, label: Optional[str] = None, ctrl_state: Optional[Union[int, str]] = None): """Return controlled version of gate. See :class:`.ControlledGate` for usage. Args: num_ctrl_qubits: number of controls to add to gate (default=1) label: optional gate label ctrl_state: The control state in decimal or as a bitstring (e.g. '111'). If None, use 2**num_ctrl_qubits-1. Returns: qiskit.circuit.ControlledGate: Controlled version of gate. This default algorithm uses num_ctrl_qubits-1 ancillae qubits so returns a gate of size num_qubits + 2*num_ctrl_qubits - 1. Raises: QiskitError: unrecognized mode or invalid ctrl_state """ # pylint: disable=cyclic-import from .add_control import add_control return add_control(self, num_ctrl_qubits, label, ctrl_state)
@staticmethod def _broadcast_single_argument(qarg: List) -> List: """Expands a single argument. For example: [q[0], q[1]] -> [q[0]], [q[1]] """ # [q[0], q[1]] -> [q[0]] # -> [q[1]] for arg0 in qarg: yield [arg0], [] @staticmethod def _broadcast_2_arguments(qarg0: List, qarg1: List) -> List: if len(qarg0) == len(qarg1): # [[q[0], q[1]], [r[0], r[1]]] -> [q[0], r[0]] # -> [q[1], r[1]] for arg0, arg1 in zip(qarg0, qarg1): yield [arg0, arg1], [] elif len(qarg0) == 1: # [[q[0]], [r[0], r[1]]] -> [q[0], r[0]] # -> [q[0], r[1]] for arg1 in qarg1: yield [qarg0[0], arg1], [] elif len(qarg1) == 1: # [[q[0], q[1]], [r[0]]] -> [q[0], r[0]] # -> [q[1], r[0]] for arg0 in qarg0: yield [arg0, qarg1[0]], [] else: raise CircuitError('Not sure how to combine these two-qubit arguments:\n %s\n %s' % (qarg0, qarg1)) @staticmethod def _broadcast_3_or_more_args(qargs: List) -> List: if all(len(qarg) == len(qargs[0]) for qarg in qargs): for arg in zip(*qargs): yield list(arg), [] else: raise CircuitError( 'Not sure how to combine these qubit arguments:\n %s\n' % qargs)
[문서] def broadcast_arguments(self, qargs: List, cargs: List) -> Tuple[List, List]: """Validation and handling of the arguments and its relationship. For example, ``cx([q[0],q[1]], q[2])`` means ``cx(q[0], q[2]); cx(q[1], q[2])``. This method yields the arguments in the right grouping. In the given example:: in: [[q[0],q[1]], q[2]],[] outs: [q[0], q[2]], [] [q[1], q[2]], [] The general broadcasting rules are: * If len(qargs) == 1:: [q[0], q[1]] -> [q[0]],[q[1]] * If len(qargs) == 2:: [[q[0], q[1]], [r[0], r[1]]] -> [q[0], r[0]], [q[1], r[1]] [[q[0]], [r[0], r[1]]] -> [q[0], r[0]], [q[0], r[1]] [[q[0], q[1]], [r[0]]] -> [q[0], r[0]], [q[1], r[0]] * If len(qargs) >= 3:: [q[0], q[1]], [r[0], r[1]], ...] -> [q[0], r[0], ...], [q[1], r[1], ...] Args: qargs: List of quantum bit arguments. cargs: List of classical bit arguments. Returns: A tuple with single arguments. Raises: CircuitError: If the input is not valid. For example, the number of arguments does not match the gate expectation. """ if len(qargs) != self.num_qubits or cargs: raise CircuitError( 'The amount of qubit/clbit arguments does not match the gate expectation.') if any([not qarg for qarg in qargs]): raise CircuitError('One or more of the arguments are empty') if len(qargs) == 1: return Gate._broadcast_single_argument(qargs[0]) elif len(qargs) == 2: return Gate._broadcast_2_arguments(qargs[0], qargs[1]) elif len(qargs) >= 3: return Gate._broadcast_3_or_more_args(qargs) else: raise CircuitError('This gate cannot handle %i arguments' % len(qargs))
[문서] def validate_parameter(self, parameter): """Gate parameters should be int, float, or ParameterExpression""" if isinstance(parameter, (int, float, ParameterExpression)): return parameter elif isinstance(parameter, (np.integer, np.floating)): return parameter.item() elif isinstance(parameter, np.ndarray): warn("Gate param type %s is being deprecated as of 0.16.0, and will be removed " "no earlier than 3 months after that release date. " "Considering creating your own Gate subclass with the method validate_parameter " " to allow this param type." % type(parameter), DeprecationWarning, 3) return parameter else: raise CircuitError("Invalid param type {0} for gate {1}.".format(type(parameter),

© Copyright 2020, Qiskit Development Team. 최종 업데이트: 2021/01/17

Built with Sphinx using a theme provided by Read the Docs.
당신은 다음 언어로 문서를 보고 있다 lang: Korean