2022-10-04 18:05:56 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
from typing import Any
|
|
|
|
|
|
|
|
|
2019-09-03 07:02:53 +00:00
|
|
|
class Matrix:
|
|
|
|
"""
|
|
|
|
<class Matrix>
|
|
|
|
Matrix structure.
|
|
|
|
"""
|
|
|
|
|
2022-10-04 18:05:56 +00:00
|
|
|
def __init__(self, row: int, column: int, default_value: float = 0) -> None:
|
2019-09-03 07:02:53 +00:00
|
|
|
"""
|
|
|
|
<method Matrix.__init__>
|
|
|
|
Initialize matrix with given size and default value.
|
|
|
|
Example:
|
|
|
|
>>> a = Matrix(2, 3, 1)
|
2020-05-22 06:10:11 +00:00
|
|
|
>>> a
|
2019-09-03 07:02:53 +00:00
|
|
|
Matrix consist of 2 rows and 3 columns
|
|
|
|
[1, 1, 1]
|
|
|
|
[1, 1, 1]
|
|
|
|
"""
|
|
|
|
|
|
|
|
self.row, self.column = row, column
|
2023-08-09 07:55:30 +00:00
|
|
|
self.array = [[default_value for _ in range(column)] for _ in range(row)]
|
2019-09-03 07:02:53 +00:00
|
|
|
|
2022-10-04 18:05:56 +00:00
|
|
|
def __str__(self) -> str:
|
2019-09-03 07:02:53 +00:00
|
|
|
"""
|
|
|
|
<method Matrix.__str__>
|
|
|
|
Return string representation of this matrix.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Prefix
|
2022-10-16 20:50:11 +00:00
|
|
|
s = f"Matrix consist of {self.row} rows and {self.column} columns\n"
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-09-03 07:02:53 +00:00
|
|
|
# Make string identifier
|
|
|
|
max_element_length = 0
|
|
|
|
for row_vector in self.array:
|
|
|
|
for obj in row_vector:
|
|
|
|
max_element_length = max(max_element_length, len(str(obj)))
|
2022-10-16 20:50:11 +00:00
|
|
|
string_format_identifier = f"%{max_element_length}s"
|
2019-09-03 07:02:53 +00:00
|
|
|
|
|
|
|
# Make string and return
|
2022-10-04 18:05:56 +00:00
|
|
|
def single_line(row_vector: list[float]) -> str:
|
2019-09-03 07:02:53 +00:00
|
|
|
nonlocal string_format_identifier
|
|
|
|
line = "["
|
|
|
|
line += ", ".join(string_format_identifier % (obj,) for obj in row_vector)
|
|
|
|
line += "]"
|
|
|
|
return line
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-09-03 07:02:53 +00:00
|
|
|
s += "\n".join(single_line(row_vector) for row_vector in self.array)
|
|
|
|
return s
|
|
|
|
|
2022-10-04 18:05:56 +00:00
|
|
|
def __repr__(self) -> str:
|
2019-10-05 05:14:13 +00:00
|
|
|
return str(self)
|
2019-09-03 07:02:53 +00:00
|
|
|
|
2023-08-09 07:55:30 +00:00
|
|
|
def validate_indices(self, loc: tuple[int, int]) -> bool:
|
2019-09-03 07:02:53 +00:00
|
|
|
"""
|
2022-10-12 22:54:20 +00:00
|
|
|
<method Matrix.validate_indicies>
|
2019-09-03 07:02:53 +00:00
|
|
|
Check if given indices are valid to pick element from matrix.
|
|
|
|
Example:
|
|
|
|
>>> a = Matrix(2, 6, 0)
|
2023-08-09 07:55:30 +00:00
|
|
|
>>> a.validate_indices((2, 7))
|
2019-09-03 07:02:53 +00:00
|
|
|
False
|
2023-08-09 07:55:30 +00:00
|
|
|
>>> a.validate_indices((0, 0))
|
2019-09-03 07:02:53 +00:00
|
|
|
True
|
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
if not (isinstance(loc, (list, tuple)) and len(loc) == 2):
|
|
|
|
return False
|
|
|
|
elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column):
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
2019-09-03 07:02:53 +00:00
|
|
|
|
2022-10-04 18:05:56 +00:00
|
|
|
def __getitem__(self, loc: tuple[int, int]) -> Any:
|
2019-09-03 07:02:53 +00:00
|
|
|
"""
|
|
|
|
<method Matrix.__getitem__>
|
|
|
|
Return array[row][column] where loc = (row, column).
|
|
|
|
Example:
|
|
|
|
>>> a = Matrix(3, 2, 7)
|
|
|
|
>>> a[1, 0]
|
|
|
|
7
|
|
|
|
"""
|
2023-08-09 07:55:30 +00:00
|
|
|
assert self.validate_indices(loc)
|
2019-09-03 07:02:53 +00:00
|
|
|
return self.array[loc[0]][loc[1]]
|
|
|
|
|
2022-10-04 18:05:56 +00:00
|
|
|
def __setitem__(self, loc: tuple[int, int], value: float) -> None:
|
2019-09-03 07:02:53 +00:00
|
|
|
"""
|
|
|
|
<method Matrix.__setitem__>
|
|
|
|
Set array[row][column] = value where loc = (row, column).
|
|
|
|
Example:
|
|
|
|
>>> a = Matrix(2, 3, 1)
|
|
|
|
>>> a[1, 2] = 51
|
|
|
|
>>> a
|
|
|
|
Matrix consist of 2 rows and 3 columns
|
|
|
|
[ 1, 1, 1]
|
|
|
|
[ 1, 1, 51]
|
|
|
|
"""
|
2023-08-09 07:55:30 +00:00
|
|
|
assert self.validate_indices(loc)
|
2019-09-03 07:02:53 +00:00
|
|
|
self.array[loc[0]][loc[1]] = value
|
|
|
|
|
2022-10-04 18:05:56 +00:00
|
|
|
def __add__(self, another: Matrix) -> Matrix:
|
2019-09-03 07:02:53 +00:00
|
|
|
"""
|
|
|
|
<method Matrix.__add__>
|
|
|
|
Return self + another.
|
|
|
|
Example:
|
|
|
|
>>> a = Matrix(2, 1, -4)
|
|
|
|
>>> b = Matrix(2, 1, 3)
|
|
|
|
>>> a+b
|
|
|
|
Matrix consist of 2 rows and 1 columns
|
|
|
|
[-1]
|
|
|
|
[-1]
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Validation
|
|
|
|
assert isinstance(another, Matrix)
|
|
|
|
assert self.row == another.row and self.column == another.column
|
|
|
|
|
|
|
|
# Add
|
|
|
|
result = Matrix(self.row, self.column)
|
|
|
|
for r in range(self.row):
|
|
|
|
for c in range(self.column):
|
2019-10-05 05:14:13 +00:00
|
|
|
result[r, c] = self[r, c] + another[r, c]
|
2019-09-03 07:02:53 +00:00
|
|
|
return result
|
|
|
|
|
2022-10-04 18:05:56 +00:00
|
|
|
def __neg__(self) -> Matrix:
|
2019-09-03 07:02:53 +00:00
|
|
|
"""
|
|
|
|
<method Matrix.__neg__>
|
|
|
|
Return -self.
|
|
|
|
Example:
|
|
|
|
>>> a = Matrix(2, 2, 3)
|
|
|
|
>>> a[0, 1] = a[1, 0] = -2
|
|
|
|
>>> -a
|
|
|
|
Matrix consist of 2 rows and 2 columns
|
|
|
|
[-3, 2]
|
|
|
|
[ 2, -3]
|
|
|
|
"""
|
|
|
|
|
|
|
|
result = Matrix(self.row, self.column)
|
|
|
|
for r in range(self.row):
|
|
|
|
for c in range(self.column):
|
2019-10-05 05:14:13 +00:00
|
|
|
result[r, c] = -self[r, c]
|
2019-09-03 07:02:53 +00:00
|
|
|
return result
|
|
|
|
|
2022-10-04 18:05:56 +00:00
|
|
|
def __sub__(self, another: Matrix) -> Matrix:
|
2019-10-05 05:14:13 +00:00
|
|
|
return self + (-another)
|
2019-09-03 07:02:53 +00:00
|
|
|
|
2023-08-09 07:55:30 +00:00
|
|
|
def __mul__(self, another: float | Matrix) -> Matrix:
|
2019-09-03 07:02:53 +00:00
|
|
|
"""
|
|
|
|
<method Matrix.__mul__>
|
|
|
|
Return self * another.
|
|
|
|
Example:
|
|
|
|
>>> a = Matrix(2, 3, 1)
|
|
|
|
>>> a[0,2] = a[1,2] = 3
|
|
|
|
>>> a * -2
|
|
|
|
Matrix consist of 2 rows and 3 columns
|
|
|
|
[-2, -2, -6]
|
|
|
|
[-2, -2, -6]
|
|
|
|
"""
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if isinstance(another, (int, float)): # Scalar multiplication
|
2019-09-03 07:02:53 +00:00
|
|
|
result = Matrix(self.row, self.column)
|
|
|
|
for r in range(self.row):
|
|
|
|
for c in range(self.column):
|
2019-10-05 05:14:13 +00:00
|
|
|
result[r, c] = self[r, c] * another
|
2019-09-03 07:02:53 +00:00
|
|
|
return result
|
2019-10-05 05:14:13 +00:00
|
|
|
elif isinstance(another, Matrix): # Matrix multiplication
|
|
|
|
assert self.column == another.row
|
2019-09-03 07:02:53 +00:00
|
|
|
result = Matrix(self.row, another.column)
|
|
|
|
for r in range(self.row):
|
|
|
|
for c in range(another.column):
|
|
|
|
for i in range(self.column):
|
2019-10-05 05:14:13 +00:00
|
|
|
result[r, c] += self[r, i] * another[i, c]
|
2019-09-03 07:02:53 +00:00
|
|
|
return result
|
2019-10-05 05:14:13 +00:00
|
|
|
else:
|
2023-05-26 07:34:17 +00:00
|
|
|
msg = f"Unsupported type given for another ({type(another)})"
|
|
|
|
raise TypeError(msg)
|
2019-09-03 07:02:53 +00:00
|
|
|
|
2022-10-04 18:05:56 +00:00
|
|
|
def transpose(self) -> Matrix:
|
2019-09-03 07:02:53 +00:00
|
|
|
"""
|
|
|
|
<method Matrix.transpose>
|
|
|
|
Return self^T.
|
|
|
|
Example:
|
|
|
|
>>> a = Matrix(2, 3)
|
2020-05-22 06:10:11 +00:00
|
|
|
>>> for r in range(2):
|
2019-09-03 07:02:53 +00:00
|
|
|
... for c in range(3):
|
|
|
|
... a[r,c] = r*c
|
2020-05-22 06:10:11 +00:00
|
|
|
...
|
2019-09-03 07:02:53 +00:00
|
|
|
>>> a.transpose()
|
|
|
|
Matrix consist of 3 rows and 2 columns
|
|
|
|
[0, 0]
|
|
|
|
[0, 1]
|
|
|
|
[0, 2]
|
|
|
|
"""
|
|
|
|
|
|
|
|
result = Matrix(self.column, self.row)
|
|
|
|
for r in range(self.row):
|
|
|
|
for c in range(self.column):
|
2019-10-05 05:14:13 +00:00
|
|
|
result[c, r] = self[r, c]
|
2019-09-03 07:02:53 +00:00
|
|
|
return result
|
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
def sherman_morrison(self, u: Matrix, v: Matrix) -> Any:
|
2019-09-03 07:02:53 +00:00
|
|
|
"""
|
2022-10-12 22:54:20 +00:00
|
|
|
<method Matrix.sherman_morrison>
|
2019-09-03 07:02:53 +00:00
|
|
|
Apply Sherman-Morrison formula in O(n^2).
|
2020-06-16 08:09:19 +00:00
|
|
|
To learn this formula, please look this:
|
|
|
|
https://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula
|
|
|
|
This method returns (A + uv^T)^(-1) where A^(-1) is self. Returns None if it's
|
|
|
|
impossible to calculate.
|
2020-05-22 06:10:11 +00:00
|
|
|
Warning: This method doesn't check if self is invertible.
|
2019-09-03 07:02:53 +00:00
|
|
|
Make sure self is invertible before execute this method.
|
|
|
|
Example:
|
|
|
|
>>> ainv = Matrix(3, 3, 0)
|
|
|
|
>>> for i in range(3): ainv[i,i] = 1
|
2020-05-22 06:10:11 +00:00
|
|
|
...
|
|
|
|
>>> u = Matrix(3, 1, 0)
|
2019-09-03 07:02:53 +00:00
|
|
|
>>> u[0,0], u[1,0], u[2,0] = 1, 2, -3
|
|
|
|
>>> v = Matrix(3, 1, 0)
|
|
|
|
>>> v[0,0], v[1,0], v[2,0] = 4, -2, 5
|
2022-10-12 22:54:20 +00:00
|
|
|
>>> ainv.sherman_morrison(u, v)
|
2019-09-03 07:02:53 +00:00
|
|
|
Matrix consist of 3 rows and 3 columns
|
|
|
|
[ 1.2857142857142856, -0.14285714285714285, 0.3571428571428571]
|
|
|
|
[ 0.5714285714285714, 0.7142857142857143, 0.7142857142857142]
|
|
|
|
[ -0.8571428571428571, 0.42857142857142855, -0.0714285714285714]
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Size validation
|
|
|
|
assert isinstance(u, Matrix) and isinstance(v, Matrix)
|
2019-10-05 05:14:13 +00:00
|
|
|
assert self.row == self.column == u.row == v.row # u, v should be column vector
|
|
|
|
assert u.column == v.column == 1 # u, v should be column vector
|
2019-09-03 07:02:53 +00:00
|
|
|
|
|
|
|
# Calculate
|
2022-10-12 22:54:20 +00:00
|
|
|
v_t = v.transpose()
|
|
|
|
numerator_factor = (v_t * self * u)[0, 0] + 1
|
2019-10-05 05:14:13 +00:00
|
|
|
if numerator_factor == 0:
|
2023-08-09 07:55:30 +00:00
|
|
|
return None # It's not invertible
|
2022-10-12 22:54:20 +00:00
|
|
|
return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor))
|
2019-09-03 07:02:53 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-09-03 07:02:53 +00:00
|
|
|
# Testing
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
2022-10-04 18:05:56 +00:00
|
|
|
def test1() -> None:
|
2019-09-03 07:02:53 +00:00
|
|
|
# a^(-1)
|
|
|
|
ainv = Matrix(3, 3, 0)
|
2019-10-05 05:14:13 +00:00
|
|
|
for i in range(3):
|
|
|
|
ainv[i, i] = 1
|
2020-01-03 14:25:36 +00:00
|
|
|
print(f"a^(-1) is {ainv}")
|
2019-09-03 07:02:53 +00:00
|
|
|
# u, v
|
|
|
|
u = Matrix(3, 1, 0)
|
2019-10-05 05:14:13 +00:00
|
|
|
u[0, 0], u[1, 0], u[2, 0] = 1, 2, -3
|
2019-09-03 07:02:53 +00:00
|
|
|
v = Matrix(3, 1, 0)
|
2019-10-05 05:14:13 +00:00
|
|
|
v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5
|
2020-01-03 14:25:36 +00:00
|
|
|
print(f"u is {u}")
|
|
|
|
print(f"v is {v}")
|
2022-10-16 20:50:11 +00:00
|
|
|
print(f"uv^T is {u * v.transpose()}")
|
2019-09-03 07:02:53 +00:00
|
|
|
# Sherman Morrison
|
2022-10-12 22:54:20 +00:00
|
|
|
print(f"(a + uv^T)^(-1) is {ainv.sherman_morrison(u, v)}")
|
2019-09-03 07:02:53 +00:00
|
|
|
|
2022-10-04 18:05:56 +00:00
|
|
|
def test2() -> None:
|
2019-09-03 07:02:53 +00:00
|
|
|
import doctest
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-09-03 07:02:53 +00:00
|
|
|
doctest.testmod()
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
test2()
|