Coverage for src/braket/circuits/quantum_operator_helpers.py : 100%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Copyright 2019-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License"). You
4# may not use this file except in compliance with the License. A copy of
5# the License is located at
6#
7# http://aws.amazon.com/apache2.0/
8#
9# or in the "license" file accompanying this file. This file is
10# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
11# ANY KIND, either express or implied. See the License for the specific
12# language governing permissions and limitations under the License.
14from functools import lru_cache
16import numpy as np
19def verify_quantum_operator_matrix_dimensions(matrix: np.array) -> None:
20 """
21 Verifies matrix is square and matrix dimensions are positive exponents of 2,
22 raising `ValueError` otherwise.
24 Args:
25 matrix (np.ndarray): matrix to verify
27 Raises:
28 ValueError: If `matrix` is not a two-dimensional square matrix,
29 or has a dimension length which is not a positive exponent of 2
30 """
31 if not is_square_matrix(matrix):
32 raise ValueError(f"{matrix} is not a two-dimensional square matrix")
34 matrix = np.array(matrix, dtype=complex)
35 qubit_count = int(np.log2(matrix.shape[0]))
36 if 2 ** qubit_count != matrix.shape[0] or qubit_count < 1:
37 raise ValueError(f"`matrix` dimension {matrix.shape[0]} is not a positive exponent of 2")
40def is_hermitian(matrix: np.array) -> bool:
41 """
42 Whether matrix is Hermitian
44 Args:
45 matrix (np.ndarray): matrix to verify
47 Return:
48 bool: If matrix is Hermitian
49 """
50 return np.allclose(matrix, matrix.conj().T)
53def is_square_matrix(matrix: np.array) -> bool:
54 """
55 Whether matrix is square, meaning matrix has two dimensions are both are equivalent
57 Args:
58 matrix (np.ndarray): matrix to verify
60 Return:
61 bool: If matrix is square
62 """
63 return len(matrix.shape) == 2 and matrix.shape[0] == matrix.shape[1]
66def is_unitary(matrix: np.array) -> bool:
67 """
68 Whether matrix is unitary
70 Args:
71 matrix (np.ndarray): matrix to verify
73 Return:
74 bool: If matrix is unitary
75 """
76 return np.allclose(np.eye(len(matrix)), matrix.dot(matrix.T.conj()))
79@lru_cache()
80def get_pauli_eigenvalues(num_qubits: int) -> np.ndarray:
81 """
82 Get the eigenvalues of Pauli operators and their tensor products as
83 an immutable Numpy array.
85 Args:
86 num_qubits (int): the number of qubits the operator acts on
88 Returns:
89 np.ndarray: the eigenvalues of a Pauli product operator of the given size
90 """
91 if num_qubits == 1:
92 eigs = np.array([1, -1])
93 eigs.setflags(write=False)
94 return eigs
95 eigs = np.concatenate(
96 [get_pauli_eigenvalues(num_qubits - 1), -get_pauli_eigenvalues(num_qubits - 1)]
97 )
98 eigs.setflags(write=False)
99 return eigs