-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver.py
82 lines (69 loc) · 1.95 KB
/
solver.py
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
"""
Contains a driver function to demonstrate that prepares the input for solving
a system of linear equations, uses the rref() function in rref.py to solve it,
then returns the results.
"""
from numpy import array, concatenate
from multiply import multiply
from rref import rref
__all__ = ['solve']
def solve(X, Xt, Y, PrintZero=True, Verbose=False):
"""
A driver function that builds the system of linear equations, calls rref()
to solve it, and then returns the solution in string form. It also has
the option of printing all intermediate steps, and that is why it is so
big.
Parameters
-------
X : numpy.array X
Xt : numpy.array the transpose of X
Y : numpy.array Y
PrintZero : boolean
Whether or not to print zero coefficients, in string return, default is True
Verbose : boolean
whether or not to print all steps, default is False
Returns
-------
- _ : list
list of coefficients
- phi_hat : string
the solution equation as a string.
"""
XtX = multiply(Xt,X)
XtY = multiply(Xt,Y)
if Verbose:
print()
print("X:")
print(X)
print()
print("Xt:")
print(Xt)
print()
print("Y:")
print(Y)
print()
print("XtX:")
print(XtX)
print()
print("XtY:")
print(XtY)
print()
system = concatenate((XtX, XtY), axis=1)
if Verbose:
print("System of Linear Equations: ")
print(system)
print()
solved = rref(system)
if Verbose:
print("Solution:")
print(solved)
print()
phi_hat = "phi_hat = "
for x, c in enumerate(solved[:,-1]):
if (int(c) != 0 or PrintZero == True):
phi_hat += str(c)
if (x >= 1):
phi_hat += " * x^" + str(x)
if (c != len(solved[:,-1]) - 2):
phi_hat += " + "
return list(solved[:,-1]), phi_hat