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.
14import numpy as np
17def verify_quantum_operator_matrix_dimensions(matrix: np.array) -> None:
18 """
19 Verifies matrix is square and matrix dimensions are positive exponents of 2,
20 raising `ValueError` otherwise.
22 Args:
23 matrix (np.ndarray): matrix to verify
25 Raises:
26 ValueError: If `matrix` is not a two-dimensional square matrix,
27 or has a dimension length which is not a positive exponent of 2
28 """
29 if not is_square_matrix(matrix):
30 raise ValueError(f"{matrix} is not a two-dimensional square matrix")
32 matrix = np.array(matrix, dtype=complex)
33 qubit_count = int(np.log2(matrix.shape[0]))
34 if 2 ** qubit_count != matrix.shape[0] or qubit_count < 1:
35 raise ValueError(f"`matrix` dimension {matrix.shape[0]} is not a positive exponent of 2")
38def is_hermitian(matrix: np.array) -> bool:
39 """
40 Whether matrix is Hermitian
42 Args:
43 matrix (np.ndarray): matrix to verify
45 Return:
46 bool: If matrix is Hermitian
47 """
48 return np.allclose(matrix, matrix.conj().T)
51def is_square_matrix(matrix: np.array) -> bool:
52 """
53 Whether matrix is square, meaning matrix has two dimensions are both are equivalent
55 Args:
56 matrix (np.ndarray): matrix to verify
58 Return:
59 bool: If matrix is square
60 """
61 return len(matrix.shape) == 2 and matrix.shape[0] == matrix.shape[1]
64def is_unitary(matrix: np.array) -> bool:
65 """
66 Whether matrix is unitary
68 Args:
69 matrix (np.ndarray): matrix to verify
71 Return:
72 bool: If matrix is unitary
73 """
74 return np.allclose(np.eye(len(matrix)), matrix.dot(matrix.T.conj()))