Question: Using the two algorithms to Python code: Algorithm 2 Forward substitution to solve Lx = b , where L is lower triangular for i =

Using the two algorithms to Python code:
Algorithm 2 Forward substitution to solve Lx = b, where L is lower triangular
for i =1,2,..., n do
xi bi
for j =1,2,..., i 1 do
xi xi Lij xj
end for
xi xi/Lii Not necessary if L is unit lower triangular.
end for
Algorithm 3 Backward substitution to solve U x = b, where U is upper triangular
for i = n, n 1,...,1 do
xi bi
for j = i +1, i +2,..., n do
xi xi Uij xj
end for
xi xi/Uii
end for
The input is the file with matrix in COO format, the functions below are used to tranform it to CSR format:
def load_as_csr(filename):
# Read m, n, and nnz from the file
m, n, nnz = np.genfromtxt(filename, max_rows=1, dtype=None)
# Read the data as a list of tuples [(i,j,v),...]
data = np.genfromtxt(filename, skip_header=1, dtype=None)
# Allocate arrays
I = np.zeros(m +1, dtype=int)
J = np.zeros(nnz, dtype=int)
V = np.zeros(nnz)
for k in range(nnz):
i = data[k][0]
I[i+1]+=1
for i in range(m):
I[i+1]+= I[i]
for k in range(nnz):
i, j, v = data[k]
idx = I[i]
I[i]+=1
J[idx]= j
V[idx]= v
for i in reversed(range(m)):
I[i+1]= I[i]
I[0]=0
return I, J, V
def num_rows(A):
return len(A[0])-1
def matvec(A, v):
I, J, V = A
m = num_rows(A)
w = np.zeros(m)
for i in range(m):
begin = I[i]
end = I[i+1]
for idx in range(begin, end):
j = J[idx]
w[i]+= V[idx]*v[j]
return w
Finish these two functions please:
Write functions tril_solve and triu_solve that take a matrix A in CSR format (as a tuple of three arrays, the output of load_as_csr) and a right-hand side vector b , and returns the solution to Lx=b and Ux=b where L and U are the lower and upper triangular parts of A respectively.
def tril_solve(A, b):
I, J, V = A
x = np.zeros(len(b))
# Perform lower-triangular solve (forward substitution)
return x
def triu_solve(A, b):
I, J, V = A
x = np.zeros(len(b))
# Perform upper-triangular solve (backward substitution)
return x
Example of how the input file look like:
161674
07-0.0865112
08-0.0114965
06-0.64942
05-1.25134
003.98189
16-0.171279
12-0.18625
115-0.614682
117.61259
21-0.18625
24-0.0288556
210-6.60903
229.37045
28-2.04836
26-0.388906
339.57473
42-0.0288556
410-0.357678
412-0.319544
413-1.00507
48-0.489719
443.77272
59-0.0234982
57-7.24611
513-0.20906
514-0.214743
50-1.25134
559.50564
61-0.171279
615-50.7619
62-0.388906
68-0.26047
6652.7065
60-0.64942
713-0.916151
...

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!