File: test_arpack.py

package info (click to toggle)
python-scipy 0.7.2%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 28,500 kB
  • ctags: 36,081
  • sloc: cpp: 216,880; fortran: 76,016; python: 71,576; ansic: 62,118; makefile: 243; sh: 17
file content (267 lines) | stat: -rw-r--r-- 8,442 bytes parent folder | download | duplicates (2)
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#!/usr/bin/env python
__usage__ = """
To run tests locally:
  python tests/test_arpack.py [-l<int>] [-v<int>]

"""

from numpy.testing import *

from numpy import array, finfo, argsort, dot, round, conj, random
from scipy.sparse.linalg.eigen.arpack import eigen_symmetric, eigen

def assert_almost_equal_cc(actual,desired,decimal=7,err_msg='',verbose=True):
    # almost equal or complex conjugates almost equal
    try:
        assert_almost_equal(actual,desired,decimal,err_msg,verbose)
    except:
        assert_almost_equal(actual,conj(desired),decimal,err_msg,verbose)


def assert_array_almost_equal_cc(actual,desired,decimal=7,
                                 err_msg='',verbose=True):
    # almost equal or complex conjugates almost equal
    try:
        assert_array_almost_equal(actual,desired,decimal,err_msg,verbose)
    except:
        assert_array_almost_equal(actual,conj(desired),decimal,err_msg,verbose)



# precision for tests
_ndigits = {'f':4, 'd':12, 'F':4, 'D':12}

class TestArpack(TestCase):

    def setUp(self):
        self.symmetric=[]
        self.nonsymmetric=[]

        S1={}
        S1['mat']=\
        array([[ 2.,  0.,  0., -1.,  0., -1.],
               [ 0.,  2.,  0., -1.,  0., -1.],
               [ 0.,  0.,  2., -1.,  0., -1.],
               [-1., -1., -1.,  4.,  0., -1.],
               [ 0.,  0.,  0.,  0.,  1., -1.],
               [-1., -1., -1., -1., -1.,  5.]])

        S1['eval']=array([0,1,2,2,5,6])
        self.symmetric.append(S1)

        N1={}
        N1['mat']=\
            array([[-2., -8.,  1.,  2., -5.],
                   [ 6.,  6.,  0.,  2.,  1.],
                   [ 0.,  4., -2., 11.,  0.],
                   [ 1.,  6.,  1.,  0., -4.],
                   [ 2., -6.,  4.,  9., -3]])

        N1['eval']=\
            array([ -5.4854094033782888+0.0j,
                     -2.2169058544873783+8.5966096591588261j,
                     -2.2169058544873783-8.5966096591588261j,
                     4.4596105561765107+3.8007839204319454j,
                     4.4596105561765107-3.8007839204319454j],'D')



        self.nonsymmetric.append(N1)


class TestEigenSymmetric(TestArpack):

    def get_exact_eval(self,d,typ,k,which):
        eval=d['eval'].astype(typ)
        ind=argsort(eval)
        eval=eval[ind]
        if which=='LM':
            return eval[-k:]
        if which=='SM':
            return eval[:k]
        if which=='BE':
            # one ev from each end - if k is odd, extra ev on high end
            l=k/2
            h=k/2+k%2
            low=range(len(eval))[:l]
            high=range(len(eval))[-h:]
            return eval[low+high]

    def eval_evec(self,d,typ,k,which,**kwds):
        a=d['mat'].astype(typ)
        exact_eval=self.get_exact_eval(d,typ,k,which)
        eval,evec=eigen_symmetric(a,k,which=which,**kwds)
        # check eigenvalues
        assert_array_almost_equal(eval,exact_eval,decimal=_ndigits[typ])
        # check eigenvectors A*evec=eval*evec
        for i in range(k):
            assert_array_almost_equal(dot(a,evec[:,i]),
                                      eval[i]*evec[:,i],
                                      decimal=_ndigits[typ])

    def test_symmetric_modes(self):
        k=2
        for typ in 'fd':
            for which in ['LM','SM','BE']:
                self.eval_evec(self.symmetric[0],typ,k,which)

    def test_starting_vector(self):
        k=2
        for typ in 'fd':
            A=self.symmetric[0]['mat']
            n=A.shape[0]
            v0 = random.rand(n).astype(typ)
            self.eval_evec(self.symmetric[0],typ,k,which='LM',v0=v0)


class TestEigenComplexSymmetric(TestArpack):

    def sort_choose(self,eval,typ,k,which):
        # sort and choose the eigenvalues and eigenvectors
        # both for the exact answer and that returned from ARPACK
        reval=round(eval,decimals=_ndigits[typ])
        ind=argsort(reval)
        if which=='LM' or which=='LR':
            return ind[-k:]
        if which=='SM' or which=='SR':
            return ind[:k]

    def eval_evec(self,d,typ,k,which):
        a=d['mat'].astype(typ)
        # get exact eigenvalues
        exact_eval=d['eval'].astype(typ)
        ind=self.sort_choose(exact_eval,typ,k,which)
        exact_eval=exact_eval[ind]
        # compute eigenvalues
        eval,evec=eigen(a,k,which=which)
        ind=self.sort_choose(eval,typ,k,which)
        eval=eval[ind]
        evec=evec[:,ind]

        # check eigenvalues
        assert_array_almost_equal(eval,exact_eval,decimal=_ndigits[typ])
        # check eigenvectors A*evec=eval*evec
        for i in range(k):
            assert_array_almost_equal(dot(a,evec[:,i]),
                                      eval[i]*evec[:,i],
                                      decimal=_ndigits[typ])

    def test_complex_symmetric_modes(self):
        k=2
        for typ in 'FD':
            for which in ['LM','SM','LR','SR']:
                self.eval_evec(self.symmetric[0],typ,k,which)



class TestEigenNonSymmetric(TestArpack):


    def sort_choose(self,eval,typ,k,which):
        reval=round(eval,decimals=_ndigits[typ])
        if which in ['LR','SR']:
            ind=argsort(reval.real)
        elif which in ['LI','SI']:
            # for LI,SI ARPACK returns largest,smallest abs(imaginary) why?
            ind=argsort(abs(reval.imag))
        else:
            ind=argsort(abs(reval))

        if which in ['LR','LM','LI']:
            return ind[-k:]
        if which in ['SR','SM','SI']:
            return ind[:k]


    def eval_evec(self,d,typ,k,which,**kwds):
        a=d['mat'].astype(typ)
        # get exact eigenvalues
        exact_eval=d['eval'].astype(typ.upper())
        ind=self.sort_choose(exact_eval,typ,k,which)
        exact_eval=exact_eval[ind]
        # compute eigenvalues
        eval,evec=eigen(a,k,which=which,**kwds)
        ind=self.sort_choose(eval,typ,k,which)
        eval=eval[ind]
        evec=evec[:,ind]
        # check eigenvalues
        # check eigenvectors A*evec=eval*evec
        for i in range(k):
            assert_almost_equal_cc(eval[i],exact_eval[i],decimal=_ndigits[typ])
            assert_array_almost_equal_cc(dot(a,evec[:,i]),
                                      eval[i]*evec[:,i],
                                      decimal=_ndigits[typ])


    def test_nonsymmetric_modes(self):
        k=2
        for typ in 'fd':
            for which in ['LI','LR','LM','SM','SR','SI']:
                for m in self.nonsymmetric:
                    self.eval_evec(m,typ,k,which)



    def test_starting_vector(self):
        k=2
        for typ in 'fd':
            A=self.symmetric[0]['mat']
            n=A.shape[0]
            v0 = random.rand(n).astype(typ)
            self.eval_evec(self.symmetric[0],typ,k,which='LM',v0=v0)




class TestEigenComplexNonSymmetric(TestArpack):

    def sort_choose(self,eval,typ,k,which):
        eps=finfo(typ).eps
        reval=round(eval,decimals=_ndigits[typ])
        if which in ['LR','SR']:
            ind=argsort(reval)
        elif which in ['LI','SI']:
            ind=argsort(reval.imag)
        else:
            ind=argsort(abs(reval))

        if which in ['LR','LI','LM']:
            return ind[-k:]
        if which in ['SR','SI','SM']:
            return ind[:k]

    def eval_evec(self,d,typ,k,which):
        a=d['mat'].astype(typ)
        # get exact eigenvalues
        exact_eval=d['eval'].astype(typ.upper())
        ind=self.sort_choose(exact_eval,typ,k,which)
        exact_eval=exact_eval[ind]
        if verbose >= 3:
            print "exact"
            print exact_eval


        # compute eigenvalues
        eval,evec=eigen(a,k,which=which)
        ind=self.sort_choose(eval,typ,k,which)
        eval=eval[ind]
        evec=evec[:,ind]
        if verbose >= 3:
            print eval
        # check eigenvalues
        # check eigenvectors A*evec=eval*evec
        for i in range(k):
            assert_almost_equal_cc(eval[i],exact_eval[i],decimal=_ndigits[typ])
            assert_array_almost_equal_cc(dot(a,evec[:,i]),
                                      eval[i]*evec[:,i],
                                      decimal=_ndigits[typ])

    def test_complex_nonsymmetric_modes(self):
        k=2
        for typ in 'FD':
            for which in ['LI','LR','LM','SI','SR','SM']:
                for m in self.nonsymmetric:
                    self.eval_evec(m,typ,k,which)

if __name__ == "__main__":
    run_module_suite()