/
testMatrixTools.py
211 lines (162 loc) · 8.67 KB
/
testMatrixTools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
from ..testutils import BaseTestCase, compare_files, temp_files
import numpy as np
import scipy.sparse as sps
import pygsti
import unittest
import pygsti.tools.matrixtools as mt
class MatrixBaseTestCase(BaseTestCase):
def test_matrixtools(self):
herm_mx = np.array( [[ 1, 1+2j],
[1-2j, 3]], 'complex' )
non_herm_mx = np.array( [[ 1, 4+2j],
[1+2j, 3]], 'complex' )
self.assertTrue( pygsti.is_hermitian(herm_mx) )
self.assertFalse( pygsti.is_hermitian(non_herm_mx) )
pos_mx = np.array( [[ 4, 0.2],
[0.1, 3]], 'complex' )
non_pos_mx = np.array( [[ 0, 1],
[1, 0]], 'complex' )
self.assertTrue( pygsti.is_pos_def(pos_mx) )
self.assertFalse( pygsti.is_pos_def(non_pos_mx) )
density_mx = np.array( [[ 0.9, 0],
[ 0, 0.1]], 'complex' )
non_density_mx = np.array( [[ 2.0, 1.0],
[-1.0, 0]], 'complex' )
self.assertTrue( pygsti.is_valid_density_mx(density_mx) )
self.assertFalse( pygsti.is_valid_density_mx(non_density_mx) )
s1 = pygsti.mx_to_string(density_mx)
s2 = pygsti.mx_to_string(non_herm_mx)
def test_nullspace(self):
a = np.array([[1,1], [1,1]])
print("Nullspace = ",mt.nullspace(a))
expected = np.array(
[[ 0.70710678],
[-0.70710678]] )
diff1 = np.linalg.norm(mt.nullspace(a) - expected)
diff2 = np.linalg.norm(mt.nullspace(a) + expected) # -1*expected is OK too (just an eigenvector)
self.assertTrue( np.isclose(diff1,0) or np.isclose(diff2,0) )
diff1 = np.linalg.norm(mt.nullspace_qr(a) - expected)
diff2 = np.linalg.norm(mt.nullspace_qr(a) + expected) # -1*expected is OK too (just an eigenvector)
self.assertTrue( np.isclose(diff1,0) or np.isclose(diff2,0) )
mt.print_mx(a)
b = np.array([[1,2],[3,4]],dtype='complex')
with self.assertRaises(ValueError):
mt.real_matrix_log(b)
with self.assertRaises(AssertionError):
mt.real_matrix_log(a)
def test_helpers(self):
a = np.array([1,2,3],'d')
self.assertTrue( mt.array_eq(a,a) )
def test_matrix_log(self):
M = np.array( [[-1,0],[0,-1]], 'complex') # degenerate negative evals
mt.real_matrix_log(M, actionIfImaginary="raise", TOL=1e-6)
M = np.array( [[-1,1e-10],[1e-10,-1]], 'complex') # degenerate negative evals, but will generate complex evecs
mt.real_matrix_log(M, actionIfImaginary="raise", TOL=1e-6)
M = np.array( [[1,0],[0,-1]], 'd') # a negative *unparied* eigenvalue => log may be imaginary
mt.real_matrix_log(M, actionIfImaginary="ignore", TOL=1e-6)
self.assertWarns( mt.real_matrix_log, M, actionIfImaginary="warn", TOL=1e-6)
with self.assertRaises(ValueError):
mt.real_matrix_log(M, actionIfImaginary="raise", TOL=1e-6)
with self.assertRaises(AssertionError):
mt.real_matrix_log(M, actionIfImaginary="foobar", TOL=1e-6)
def test_minweight_match(self):
a = np.array([1,2,3,4],'d')
b = np.array([3.1,2.1,4.1,1.1],'d')
expectedPairs = [(0,3),(1,1),(2,0),(3,2)] # (i,j) indices into a & b
wts = mt.minweight_match(a, b, metricfn=None, return_pairs=False,
pass_indices_to_metricfn=False)
wts, pairs = mt.minweight_match(a, b, metricfn=None, return_pairs=True,
pass_indices_to_metricfn=False)
self.assertEqual( set(pairs), set(expectedPairs))
def fn(x,y): return abs(x-y)
wts, pairs = mt.minweight_match(a, b, metricfn=fn, return_pairs=True,
pass_indices_to_metricfn=False)
self.assertEqual( set(pairs), set(expectedPairs))
def fn(i,j): return abs(a[i]-b[j])
wts, pairs = mt.minweight_match(a, b, metricfn=fn, return_pairs=True,
pass_indices_to_metricfn=True)
self.assertEqual( set(pairs), set(expectedPairs))
def test_fancy_assignment(self):
a = np.zeros( (4,4,4), 'd')
twoByTwo = np.ones( (2,2), 'd')
#NOTEs from commit message motivating why we need this:
# a = np.zeros((3,3,3))
# a[:,1:2,1:3].shape == (3,1,2) # good!
# a[0,:,1:3].shape == (3,2) #good!
# a[0,:,[1,2]].shape == (2,3) # ?? (broacasting ':' makes this like a[0,[1,2]])
# a[:,[1,2],[1,2]].shape == (3,2) # ?? not (3,2,2) b/c lists broadcast
# a[:,[1],[1,2]].shape == (3,2) # ?? not (3,1,2) b/c lists broadcast
# a[:,[1,2],[0,1,2]].shape == ERROR b/c [1,2] can't broadcast to [0,1,2]!
#simple integer indices
mt._fas(a, (0,0,0), 4.5) # a[0,0,0] = 4.5
self.assertAlmostEqual(a[0,0,0], 4.5)
mt._fas(a, (0,0,0), 4.5, add=True) # a[0,0,0] += 4.5
self.assertAlmostEqual(a[0,0,0], 9.0)
#still simple: mix of slices and integers
mt._fas(a, (slice(0,2),slice(0,2),0), twoByTwo) # a[0:2,0:2,0] = twoByTwo
self.assertArraysAlmostEqual(a[0:2,0:2,0], twoByTwo)
#complex case: some/all indices are integer arrays
mt._fas(a, ([0,1],[0,1],0), twoByTwo[:,:]) # a[0:2,0:2,0] = twoByTwo - but a[[0,1],[0,1],0] wouldn't do this!
self.assertArraysAlmostEqual(a[0:2,0:2,0], twoByTwo)
mt._fas(a, ([0,1],[0,1],0), twoByTwo[:,:], add=True) # a[0:2,0:2,0] = twoByTwo - but a[[0,1],[0,1],0] wouldn't do this!
self.assertArraysAlmostEqual(a[0:2,0:2,0], 2*twoByTwo)
# Fancy indexing (without assignment)
self.assertEqual( mt._findx(a, (0,0,0)).shape, ()) # (1,1,1))
self.assertEqual( mt._findx(a, (slice(0,2),slice(0,2),slice(0,2))).shape, (2,2,2))
self.assertEqual( mt._findx(a, (slice(0,2),slice(0,2),0)).shape, (2,2))
self.assertEqual( mt._findx(a, ([0,1],[0,1],0)).shape, (2,2))
self.assertEqual( mt._findx(a, ([],[0,1],0)).shape, (0,2))
def test_safe_ops(self):
mx = np.array([[1+1j, 0],
[2+2j, 3+3j]], 'complex')
smx = sps.csr_matrix(mx)
smx_lil = sps.lil_matrix(mx) # currently unsupported
r = mt.safereal(mx, inplace=False)
self.assertArraysAlmostEqual(r, np.real(mx))
i = mt.safeimag(mx, inplace=False)
self.assertArraysAlmostEqual(i, np.imag(mx))
r = mt.safereal(smx, inplace=False)
self.assertArraysAlmostEqual(r.toarray(), np.real(mx))
i = mt.safeimag(smx, inplace=False)
self.assertArraysAlmostEqual(i.toarray(), np.imag(mx))
with self.assertRaises(NotImplementedError):
mt.safereal(smx_lil, inplace=False)
with self.assertRaises(NotImplementedError):
mt.safeimag(smx_lil, inplace=False)
with self.assertRaises(AssertionError):
mt.safereal(mx, check=True)
with self.assertRaises(AssertionError):
mt.safeimag(mx, check=True)
M = mx.copy(); M = mt.safereal(M, inplace=True)
self.assertArraysAlmostEqual(M, np.real(mx))
M = mx.copy(); M = mt.safeimag(M, inplace=True)
self.assertArraysAlmostEqual(M, np.imag(mx))
M = smx.copy(); M = mt.safereal(M, inplace=True)
self.assertArraysAlmostEqual(M.toarray(), np.real(mx))
M = smx.copy(); M = mt.safeimag(M, inplace=True)
self.assertArraysAlmostEqual(M.toarray(), np.imag(mx))
def test_fast_expm(self):
mx = np.array([[1, 2],
[2, 3]], 'd')
A = sps.csr_matrix(mx)
A, mu, m_star, s, eta = mt.expm_multiply_prep(A)
tol = 1e-6
B = np.array([1,1],'d')
expA = mt._custom_expm_multiply_simple_core(A, B, mu, m_star, s, tol, eta)
nonSq = np.array([[1, 2, 4],
[2, 3, 5]], 'd')
N = sps.csr_matrix(nonSq)
with self.assertRaises(ValueError):
mt.expm_multiply_prep(N)
def test_complex_compare(self):
self.assertEqual(mt.complex_compare(1.0+2.0j,1.0+2.0j), 0) # ==
self.assertEqual(mt.complex_compare(1.0+2.0j,2.0+2.0j), -1) #real a < real b
self.assertEqual(mt.complex_compare(1.0+2.0j,0.5+2.0j), +1) #real a > real b
self.assertEqual(mt.complex_compare(1.0+2.0j,1.0+3.0j), -1) #imag a < imag b
self.assertEqual(mt.complex_compare(1.0+2.0j,1.0+1.0j), +1) #imag a > imag b
def test_prime_factors(self):
self.assertEqual(mt.prime_factors(7), [7])
self.assertEqual(mt.prime_factors(10), [2,5])
self.assertEqual(mt.prime_factors(12), [2,2,3])
if __name__ == '__main__':
unittest.main(verbosity=2)