I have created a module which calculates QR decomposition and tests .It contains several different functions. I have saved this file as Numla.py . I want to import these functions in Jupyter Notebook but I keep having this error . I have also tried other importing methods e.g from Numla import qr , from Numla import * , import Numla as num . But I keep jhaving the same name error .
import Numla Numla.qr(A)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [11], in <cell line: 2>()
1 import Numla
----> 2 Numla.qr(A)
NameError: name 'A' is not defined
import numpy as np
def qr(A):
#source: #https://rosettacode.org/wiki/QR_decomposition#Python
m, n = A.shape
Q = np.eye(m)
for i in range(n - (m == n)):
H = np.eye(m)
#calculates Householder matrix i: rows and i: columns from A i: rows and ith column
H[i:, i:] = make_householder(A[i:, i])
Q = Q@H
A = H@A
return Q, A
def make_householder(a):
#finds orthogonal vector to mirror
u = a / (a[0] + np.copysign(np.linalg.norm(a), a[0]))
u[0] = 1
H = np.eye(a.shape[0])
#finds Householder projection
H -= (2 / np.dot(u, u)) * u[:, None] @ u[None, :]
return H
def compose(qr, make_householder):
def comp(arg):
return qr()(make_householder(arg))
return comp
def test_compose(qr, make_householder):
m=3
n=3
A = np.random.rand(m, n)
Q, R = qr(A)
Q.round(3)
R.round(3)
Q_np, R_np=np.linalg.qr(A)
np.allclose(Q, Q_np)
np.allclose(R, R_np)
print (" QR-Decomposition and test ")
print ('\n')
print ("Q vs Q_np")
print (Q.round(8))
print (Q_np)
print ('\n')
print ("R vs R_np")
print (R.round(8))
print (R_np)
print ('\n')
if np.allclose(Q, Q_np) == True:
print('ok')
if np.allclose(R, R_np) == True:
print ('ok')
print('\n')
return
#test_compose(qr, make_householder)
def back_substitution(U, y):
n = U.shape[0]
x = np.zeros_like(y, dtype=np.double);
x[-1] = y[-1] / U[-1, -1]
for i in range(n-2, -1, -1):
x[i] = (y[i] - np.dot(U[i,i:], x[i:])) / U[i,i]
return x
def linsolve_qr():
#QR decomposition with qr function
Q, R = np.linalg.qr(A)
y = Q.T @ B
#solve for x using back substitution method
K=back_substitution(R, y)
#using np solver to prove back substitution+QR method works
L=np.linalg.solve(R, y)
return
def test_linsolve_qr():
A = np.array([
[6., 7., 8.],
[2., 4., 3.],
[8., 1., 2]])
B = np.array([1., -2., 3.])
#QR decomposition with qr function
Q, R = np.linalg.qr(A)
y = Q.T @ B
K=back_substitution(R, y)
L=np.linalg.solve(R, y)
print (" QR-Decomposition implementation to solve LGS ")
print ('\n')
print (back_substitution(R, y))
print (np.linalg.solve(R, y))
if np.allclose(K, L) == True:
print('ok')
return
#test_linsolve_qr()
if __name__ == "__main__":
test_compose(qr, make_householder)
test_linsolve_qr()