コード例 #1
0
def test_contained_parameters():
    x = Parameter("x")
    assert _contained_parameters(x) == {x}

    y = Parameter("y")
    assert _contained_parameters(x + y) == {x, y}

    assert _contained_parameters(x ** y ** quil_sin(x * y * 4)) == {x, y}
コード例 #2
0
    def __init__(
        self,
        name: str,
        matrix: Union[List[List[Any]], np.ndarray, np.matrix],
        parameters: Optional[List[Parameter]] = None,
    ):
        if not isinstance(name, str):
            raise TypeError("Gate name must be a string")

        if name in RESERVED_WORDS:
            raise ValueError(
                "Cannot use {} for a gate name since it's a reserved word".
                format(name))

        if isinstance(matrix, list):
            rows = len(matrix)
            if not all([len(row) == rows for row in matrix]):
                raise ValueError("Matrix must be square.")
        elif isinstance(matrix, (np.ndarray, np.matrix)):
            rows, cols = matrix.shape
            if rows != cols:
                raise ValueError("Matrix must be square.")
        else:
            raise TypeError(
                "Matrix argument must be a list or NumPy array/matrix")

        if 0 != rows & (rows - 1):
            raise ValueError(
                "Dimension of matrix must be a power of 2, got {0}".format(
                    rows))
        self.name = name
        self.matrix = np.asarray(matrix)

        if parameters:
            if not isinstance(parameters, list):
                raise TypeError("Paramaters must be a list")

            expressions = [
                elem for row in self.matrix for elem in row
                if isinstance(elem, Expression)
            ]
            used_params = {
                param
                for exp in expressions for param in _contained_parameters(exp)
            }

            if set(parameters) != used_params:
                raise ValueError(
                    "Parameters list does not match parameters actually used in gate matrix:\n"
                    "Parameters in argument: {}, Parameters in matrix: {}".
                    format(parameters, used_params))
        else:
            is_unitary = np.allclose(np.eye(rows),
                                     self.matrix.dot(self.matrix.T.conj()))
            if not is_unitary:
                raise ValueError("Matrix must be unitary.")

        self.parameters = parameters