Fix mypy errors for arithmetic analysis algorithms (#4053)

This commit is contained in:
Dhruv Manilawala
2020-12-23 15:22:43 +05:30
committed by GitHub
parent 2ff2ccbeec
commit ad5108d6a4
5 changed files with 90 additions and 60 deletions

View File

@ -1,34 +1,64 @@
"""Lower-Upper (LU) Decomposition."""
"""Lower-Upper (LU) Decomposition.
# lowerupper (LU) decomposition - https://en.wikipedia.org/wiki/LU_decomposition
import numpy
Reference:
- https://en.wikipedia.org/wiki/LU_decomposition
"""
from typing import Tuple
import numpy as np
from numpy import ndarray
def LUDecompose(table):
def lower_upper_decomposition(table: ndarray) -> Tuple[ndarray, ndarray]:
"""Lower-Upper (LU) Decomposition
Example:
>>> matrix = np.array([[2, -2, 1], [0, 1, 2], [5, 3, 1]])
>>> outcome = lower_upper_decomposition(matrix)
>>> outcome[0]
array([[1. , 0. , 0. ],
[0. , 1. , 0. ],
[2.5, 8. , 1. ]])
>>> outcome[1]
array([[ 2. , -2. , 1. ],
[ 0. , 1. , 2. ],
[ 0. , 0. , -17.5]])
>>> matrix = np.array([[2, -2, 1], [0, 1, 2]])
>>> lower_upper_decomposition(matrix)
Traceback (most recent call last):
...
ValueError: 'table' has to be of square shaped array but got a 2x3 array:
[[ 2 -2 1]
[ 0 1 2]]
"""
# Table that contains our data
# Table has to be a square array so we need to check first
rows, columns = numpy.shape(table)
L = numpy.zeros((rows, columns))
U = numpy.zeros((rows, columns))
rows, columns = np.shape(table)
if rows != columns:
return []
raise ValueError(
f"'table' has to be of square shaped array but got a {rows}x{columns} "
+ f"array:\n{table}"
)
lower = np.zeros((rows, columns))
upper = np.zeros((rows, columns))
for i in range(columns):
for j in range(i):
sum = 0
total = 0
for k in range(j):
sum += L[i][k] * U[k][j]
L[i][j] = (table[i][j] - sum) / U[j][j]
L[i][i] = 1
total += lower[i][k] * upper[k][j]
lower[i][j] = (table[i][j] - total) / upper[j][j]
lower[i][i] = 1
for j in range(i, columns):
sum1 = 0
total = 0
for k in range(i):
sum1 += L[i][k] * U[k][j]
U[i][j] = table[i][j] - sum1
return L, U
total += lower[i][k] * upper[k][j]
upper[i][j] = table[i][j] - total
return lower, upper
if __name__ == "__main__":
matrix = numpy.array([[2, -2, 1], [0, 1, 2], [5, 3, 1]])
L, U = LUDecompose(matrix)
print(L)
print(U)
import doctest
doctest.testmod()