mymatrix.py 12.9 KB
Newer Older
1
2
"""
Pure python inversion of small matrices, to avoid requiring numpy or similar in SimTK.
3
4
5
6
7
8
9
10
11
12

This is part of the OpenMM molecular simulation toolkit originating from
Simbios, the NIH National Center for Physics-Based Simulation of
Biological Structures at Stanford, funded under the NIH Roadmap for
Medical Research, grant U54 GM072970. See https://simtk.org.

Portions copyright (c) 2012 Stanford University and the Authors.
Authors: Christopher M. Bruns
Contributors: Peter Eastman

Justin MacCallum's avatar
Justin MacCallum committed
13
Permission is hereby granted, free of charge, to any person obtaining a
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
30
31
32
33
34
35
36
"""

import sys

def eye(size):
    """
    Returns identity matrix.
Justin MacCallum's avatar
Justin MacCallum committed
37

Peter Eastman's avatar
Peter Eastman committed
38
    >>> print(eye(3))
39
40
41
42
43
44
45
46
47
48
49
50
51
52
    [[1, 0, 0]
     [0, 1, 0]
     [0, 0, 1]]
    """
    result = []
    for row in range(0, size):
        r = []
        for col in range(0, size):
            if row == col:
                r.append(1)
            else:
                r.append(0)
        result.append(r)
    return MyMatrix(result)
Justin MacCallum's avatar
Justin MacCallum committed
53

54
55
56
def zeros(m, n=None):
    """
    Returns matrix of zeroes
Justin MacCallum's avatar
Justin MacCallum committed
57

Peter Eastman's avatar
Peter Eastman committed
58
    >>> print(zeros(3))
59
60
61
62
    [[0, 0, 0]
     [0, 0, 0]
     [0, 0, 0]]
    """
63
    if n is None:
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
        n = m
    result = []
    for row in range(0, m):
        r = []
        for col in range(0, n):
            r.append(0)
        result.append(r)
    return MyMatrix(result)

class MyVector(object):
    """
    Parent class of MyMatrix and type of Matrix Row.
    """
    def __init__(self, collection):
        if isinstance(collection, MyVector):
            self.data = collection.data
        else:
            self.data = collection

    def __str__(self):
        return str(self.data)
Justin MacCallum's avatar
Justin MacCallum committed
85

86
87
88
89
90
91
92
93
    def __repr__(self):
        return self.__class__.__name__ + "(" + repr(self.data) + ")"

    def __getitem__(self, key):
        return self.data[key]

    def __contains__(self, item):
        return item in self.data
Justin MacCallum's avatar
Justin MacCallum committed
94

95
96
    def __delitem__(self, key):
        del self.data[key]
Justin MacCallum's avatar
Justin MacCallum committed
97

98
99
100
101
102
103
    def __iter__(self):
        for item in self.data:
            yield item

    def __len__(self):
        return len(self.data)
Justin MacCallum's avatar
Justin MacCallum committed
104

105
106
    def __setitem__(self, key, value):
        self.data[key] = value
Justin MacCallum's avatar
Justin MacCallum committed
107

108
109
110
111
112
113
114
115
116
117
118
119
120
121
    def __rmul__(self, lhs):
        try:
            len(lhs)
            # left side is not scalar, delegate mul to that class
            return NotImplemented
        except TypeError:
            new_vec = []
            for element in self:
                new_vec.append(lhs * element)
            return self.__class__(new_vec)

class MyMatrix(MyVector):
    """
    Pure python linear algebra matrix for internal matrix inversion in UnitSystem.
Justin MacCallum's avatar
Justin MacCallum committed
122

123
    >>> m = MyMatrix([[1,0,],[0,1,]])
Peter Eastman's avatar
Peter Eastman committed
124
    >>> print(m)
125
126
    [[1, 0]
     [0, 1]]
Peter Eastman's avatar
Peter Eastman committed
127
    >>> print(~m)
128
129
    [[1.0, 0.0]
     [0.0, 1.0]]
Peter Eastman's avatar
Peter Eastman committed
130
    >>> print(eye(5))
131
132
133
134
135
136
137
138
139
140
    [[1, 0, 0, 0, 0]
     [0, 1, 0, 0, 0]
     [0, 0, 1, 0, 0]
     [0, 0, 0, 1, 0]
     [0, 0, 0, 0, 1]]
    >>> m = eye(5)
    >>> m[1][1]
    1
    >>> m[1:4]
    MyMatrixTranspose([[0, 0, 0],[1, 0, 0],[0, 1, 0],[0, 0, 1],[0, 0, 0]])
Peter Eastman's avatar
Peter Eastman committed
141
    >>> print(m[1:4])
142
143
144
145
146
    [[0, 0, 0]
     [1, 0, 0]
     [0, 1, 0]
     [0, 0, 1]
     [0, 0, 0]]
Peter Eastman's avatar
Peter Eastman committed
147
    >>> print(m[1:4][0:2])
148
149
150
151
    [[0, 1]
     [0, 0]
     [0, 0]]
    >>> m[1:4][0:2] = [[9,8],[7,6],[5,4]]
Peter Eastman's avatar
Peter Eastman committed
152
    >>> print(m)
153
154
155
156
157
158
159
160
    [[1, 0, 0, 0, 0]
     [9, 8, 0, 0, 0]
     [7, 6, 1, 0, 0]
     [5, 4, 0, 1, 0]
     [0, 0, 0, 0, 1]]
    """
    def numRows(self):
        return len(self.data)
Justin MacCallum's avatar
Justin MacCallum committed
161

162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    def numCols(self):
        if len(self.data) == 0:
            return 0
        else:
            return len(self.data[0])

    def __len__(self):
        return self.numRows()

    def __str__(self):
        result = ""
        start_char = "["
        for m in range(0, self.numRows()):
            result += start_char
            result += str(self[m])
            if m < self.numRows() - 1:
                result += "\n"
            start_char = " "
        result += "]"
        return result
Justin MacCallum's avatar
Justin MacCallum committed
182

183
184
185
186
187
    def __repr__(self):
        return 'MyMatrix(' + MyVector.__repr__(self) + ')'

    def is_square(self):
        return self.numRows() == self.numCols()
Justin MacCallum's avatar
Justin MacCallum committed
188

189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
    def __iter__(self):
        for item in self.data:
            yield MyVector(item)

    def __getitem__(self, m):
        if isinstance(m, slice):
            return MyMatrixTranspose(self.data[m])
        else:
            return MyVector(self.data[m])

    def __setitem__(self, key, rhs):
        if isinstance(key, slice):
            self.data[key] = rhs
        else:
            assert len(rhs) == self.numCols()
            self.data[key] = MyVector(rhs)

    def __mul__(self, rhs):
        """
        Matrix multiplication.
Justin MacCallum's avatar
Justin MacCallum committed
209

210
211
        >>> a = MyMatrix([[1,2],[3,4]])
        >>> b = MyMatrix([[5,6],[7,8]])
Peter Eastman's avatar
Peter Eastman committed
212
        >>> print(a)
213
214
        [[1, 2]
         [3, 4]]
Peter Eastman's avatar
Peter Eastman committed
215
        >>> print(b)
216
217
        [[5, 6]
         [7, 8]]
Peter Eastman's avatar
Peter Eastman committed
218
        >>> print(a*b)
219
220
        [[19, 22]
         [43, 50]]
Justin MacCallum's avatar
Justin MacCallum committed
221

222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
        """
        m = self.numRows()
        n = len(rhs[0])
        r = len(rhs)
        if self.numCols() != r:
            raise ArithmeticError("Matrix multplication size mismatch (%d vs %d)" % (self.numCols(), r))
        result = zeros(m, n)
        for i in range(0, m):
            for j in range(0, n):
                for k in range(0, r):
                    result[i][j] += self[i][k]*rhs[k][j]
        return result

    def __add__(self, rhs):
        """
        Matrix addition.
Justin MacCallum's avatar
Justin MacCallum committed
238

Peter Eastman's avatar
Peter Eastman committed
239
        >>> print(MyMatrix([[1, 2],[3, 4]]) + MyMatrix([[5, 6],[7, 8]]))
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
        [[6, 8]
         [10, 12]]
        """
        m = self.numRows()
        n = self.numCols()
        assert len(rhs) == m
        assert len(rhs[0]) == n
        result = zeros(m,n)
        for i in range(0,m):
            for j in range(0,n):
                result[i][j] = self[i][j] + rhs[i][j]
        return result

    def __sub__(self, rhs):
        """
        Matrix subtraction.
Justin MacCallum's avatar
Justin MacCallum committed
256

Peter Eastman's avatar
Peter Eastman committed
257
        >>> print(MyMatrix([[1, 2],[3, 4]]) - MyMatrix([[5, 6],[7, 8]]))
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
        [[-4, -4]
         [-4, -4]]
        """
        m = self.numRows()
        n = self.numCols()
        assert len(rhs) == m
        assert len(rhs[0]) == n
        result = zeros(m,n)
        for i in range(0,m):
            for j in range(0,n):
                result[i][j] = self[i][j] - rhs[i][j]
        return result

    def __pos__(self):
        return self
Justin MacCallum's avatar
Justin MacCallum committed
273

274
275
276
277
278
279
280
281
282
283
284
285
    def __neg__(self):
        m = self.numRows()
        n = self.numCols()
        result = zeros(m, n)
        for i in range(0,m):
            for j in range(0,n):
                result[i][j] = -self[i][j]
        return result

    def __invert__(self):
        """
        >>> m = MyMatrix([[1,1],[0,1]])
Peter Eastman's avatar
Peter Eastman committed
286
        >>> print(m)
287
288
        [[1, 1]
         [0, 1]]
Peter Eastman's avatar
Peter Eastman committed
289
        >>> print(~m)
290
291
        [[1.0, -1.0]
         [0.0, 1.0]]
Peter Eastman's avatar
Peter Eastman committed
292
        >>> print(m*~m)
293
294
        [[1.0, 0.0]
         [0.0, 1.0]]
Peter Eastman's avatar
Peter Eastman committed
295
        >>> print(~m*m)
296
297
298
        [[1.0, 0.0]
         [0.0, 1.0]]
        >>> m = MyMatrix([[1,0,0],[0,0,1],[0,-1,0]])
Peter Eastman's avatar
Peter Eastman committed
299
        >>> print(m)
300
301
302
        [[1, 0, 0]
         [0, 0, 1]
         [0, -1, 0]]
Peter Eastman's avatar
Peter Eastman committed
303
        >>> print(~m)
304
305
306
        [[1.0, 0.0, 0.0]
         [0.0, 0.0, -1.0]
         [0.0, 1.0, 0.0]]
Peter Eastman's avatar
Peter Eastman committed
307
        >>> print(m*~m)
308
309
310
        [[1.0, 0.0, 0.0]
         [0.0, 1.0, 0.0]
         [0.0, 0.0, 1.0]]
Peter Eastman's avatar
Peter Eastman committed
311
        >>> print(~m*m)
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
        [[1.0, 0.0, 0.0]
         [0.0, 1.0, 0.0]
         [0.0, 0.0, 1.0]]
        """
        assert self.is_square()
        if self.numRows() == 0:
            return self
        elif self.numRows() == 1:
            val = self[0][0]
            val = 1.0/val
            return MyMatrix([[val]])
        elif self.numRows() == 2: # 2x2 is analytic
            # http://en.wikipedia.org/wiki/Invertible_matrix#Inversion_of_2.C3.972_matrices
            a = self[0][0]
            b = self[0][1]
            c = self[1][0]
            d = self[1][1]
            determinant = a*d - b*c
            if determinant == 0:
                raise ArithmeticError("Cannot invert 2x2 matrix with zero determinant")
            else:
                return 1.0/(a*d - b*c) * MyMatrix([[d, -b],[-c, a]])
        else:
            # Gauss Jordan elimination from numerical recipes
            n = self.numRows()
            m1 = self.numCols()
            assert n == m1
            # Copy initial matrix into result matrix
            a = zeros(n, n)
            for i in range (0,n):
                for j in range (0,n):
                    a[i][j] = self[i][j]
            # These arrays are used for bookkeeping on the pivoting
            indxc = [0] * n
            indxr = [0] * n
            ipiv = [0] * n
            for i in range (0,n):
                big = 0.0
                for j in range (0,n):
                    if ipiv[j] != 1:
                        for k in range (0,n):
                            if ipiv[k] == 0:
                                if abs(a[j][k]) >= big:
                                    big = abs(a[j][k])
                                    irow = j
                                    icol = k
                ipiv[icol] += 1
                # We now have the pivot element, so we interchange rows...
                if irow != icol:
                    for l in range(0,n):
                        temp = a[irow][l]
                        a[irow][l] = a[icol][l]
                        a[icol][l] = temp
                indxr[i] = irow
                indxc[i] = icol
                if a[icol][icol] == 0:
                    raise ArithmeticError("Cannot invert singular matrix")
                pivinv = 1.0/a[icol][icol]
                a[icol][icol] = 1.0
                for l in range(0,n):
                    a[icol][l] *= pivinv
                for ll in range(0,n): # next we reduce the rows
                    if ll == icol:
                        continue # except the pivot one, of course
                    dum = a[ll][icol]
                    a[ll][icol] = 0.0
                    for l in range(0,n):
                        a[ll][l] -= a[icol][l]*dum
            # Unscramble the permuted columns
            for l in range(n-1, -1, -1):
                if indxr[l] == indxc[l]:
                    continue
                for k in range(0,n):
                    temp = a[k][indxr[l]]
                    a[k][indxr[l]] = a[k][indxc[l]]
Justin MacCallum's avatar
Justin MacCallum committed
387
                    a[k][indxc[l]] = temp
388
389
390
391
392
393
394
395
396
397
            return a

    def transpose(self):
        return MyMatrixTranspose(self.data)


class MyMatrixTranspose(MyMatrix):

    def transpose(self):
        return MyMatrix(self.data)
Justin MacCallum's avatar
Justin MacCallum committed
398

399
400
401
402
403
    def numRows(self):
        if len(self.data) == 0:
            return 0
        else:
            return len(self.data[0])
Justin MacCallum's avatar
Justin MacCallum committed
404

405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
    def numCols(self):
        return len(self.data)

    def __getitem__(self, key):
        result = []
        for row in self.data:
            result.append(row[key])
        if isinstance(key, slice):
            return MyMatrix(result)
        else:
            return MyVector(result)

    def __setitem__(self, key, rhs):
        for n in range(0, len(self.data)):
            self.data[n][key] = rhs[n]

    def __str__(self):
        if len(self.data) == 0:
            return "[[]]"
        start_char = "["
        result = ""
        for m in range(0, len(self.data[0])):
            result += start_char
            result += "["
            sep_char = ""
            for n in range(0, len(self.data)):
                result += sep_char
                result += str(self.data[n][m])
                sep_char = ", "
            result += "]"
            if m < len(self.data[0]) - 1:
                result += "\n"
            start_char = " "
        result += "]"
        return result

    def __repr__(self):
        if len(self.data) == 0:
            return "MyMatrixTranspose([[]])"
        start_char = "["
        result = 'MyMatrixTranspose('
        for m in range(0, len(self.data[0])):
            result += start_char
            result += "["
            sep_char = ""
            for n in range(0, len(self.data)):
                result += sep_char
                result += repr(self.data[n][m])
                sep_char = ", "
            result += "]"
            if m < len(self.data[0]) - 1:
                result += ","
            start_char = ""
        result += '])'
        return result


# run module directly for testing
if __name__=='__main__':
Justin MacCallum's avatar
Justin MacCallum committed
464

465
466
467
    # Test the examples in the docstrings
    import doctest, sys
    doctest.testmod(sys.modules[__name__])