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
from __future__ import print_function, division, absolute_import
32
33
34
35
36
37

import sys

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

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

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

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

87
88
89
90
91
92
93
94
    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
95

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

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

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

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

109
110
111
112
113
114
115
116
117
118
119
120
121
122
    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
123

124
    >>> m = MyMatrix([[1,0,],[0,1,]])
Peter Eastman's avatar
Peter Eastman committed
125
    >>> print(m)
126
127
    [[1, 0]
     [0, 1]]
Peter Eastman's avatar
Peter Eastman committed
128
    >>> print(~m)
129
130
    [[1.0, 0.0]
     [0.0, 1.0]]
Peter Eastman's avatar
Peter Eastman committed
131
    >>> print(eye(5))
132
133
134
135
136
137
138
139
140
141
    [[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
142
    >>> print(m[1:4])
143
144
145
146
147
    [[0, 0, 0]
     [1, 0, 0]
     [0, 1, 0]
     [0, 0, 1]
     [0, 0, 0]]
Peter Eastman's avatar
Peter Eastman committed
148
    >>> print(m[1:4][0:2])
149
150
151
152
    [[0, 1]
     [0, 0]
     [0, 0]]
    >>> m[1:4][0:2] = [[9,8],[7,6],[5,4]]
Peter Eastman's avatar
Peter Eastman committed
153
    >>> print(m)
154
155
156
157
158
159
160
161
    [[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
162

163
164
165
166
167
168
169
170
171
172
173
174
    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 = "["
175
        for m in range(self.numRows()):
176
177
178
179
180
181
182
            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
183

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

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

190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    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
210

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

223
224
225
226
227
228
229
        """
        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)
230
231
232
        for i in range(m):
            for j in range(n):
                for k in range(r):
233
234
235
236
237
238
                    result[i][j] += self[i][k]*rhs[k][j]
        return result

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

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

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

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

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

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

    def __invert__(self):
        """
        >>> m = MyMatrix([[1,1],[0,1]])
Peter Eastman's avatar
Peter Eastman committed
287
        >>> print(m)
288
289
        [[1, 1]
         [0, 1]]
Peter Eastman's avatar
Peter Eastman committed
290
        >>> print(~m)
291
292
        [[1.0, -1.0]
         [0.0, 1.0]]
Peter Eastman's avatar
Peter Eastman committed
293
        >>> print(m*~m)
294
295
        [[1.0, 0.0]
         [0.0, 1.0]]
Peter Eastman's avatar
Peter Eastman committed
296
        >>> print(~m*m)
297
298
299
        [[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
300
        >>> print(m)
301
302
303
        [[1, 0, 0]
         [0, 0, 1]
         [0, -1, 0]]
Peter Eastman's avatar
Peter Eastman committed
304
        >>> print(~m)
305
306
307
        [[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
308
        >>> print(m*~m)
309
310
311
        [[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
312
        >>> print(~m*m)
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
        [[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:
362
                    for l in range(n):
363
364
365
366
367
368
369
370
371
                        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
372
                for l in range(n):
373
                    a[icol][l] *= pivinv
374
                for ll in range(n): # next we reduce the rows
375
376
377
378
                    if ll == icol:
                        continue # except the pivot one, of course
                    dum = a[ll][icol]
                    a[ll][icol] = 0.0
379
                    for l in range(n):
380
381
382
383
384
                        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
385
                for k in range(n):
386
387
                    temp = a[k][indxr[l]]
                    a[k][indxr[l]] = a[k][indxc[l]]
Justin MacCallum's avatar
Justin MacCallum committed
388
                    a[k][indxc[l]] = temp
389
390
391
392
393
394
395
396
397
398
            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
399

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

406
407
408
409
410
411
412
413
414
415
416
417
418
    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):
419
        for n in range(len(self.data)):
420
421
422
423
424
425
426
            self.data[n][key] = rhs[n]

    def __str__(self):
        if len(self.data) == 0:
            return "[[]]"
        start_char = "["
        result = ""
427
        for m in range(len(self.data[0])):
428
429
430
            result += start_char
            result += "["
            sep_char = ""
431
            for n in range(len(self.data)):
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
                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('
447
        for m in range(len(self.data[0])):
448
449
450
            result += start_char
            result += "["
            sep_char = ""
451
            for n in range(len(self.data)):
452
453
454
455
456
457
458
459
460
461
462
463
464
                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
465

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