def inv(A): Nrow, Ncol = A.shape det = np.linalg.det(A) assert Nrow == Ncol, "inv: A matriz não é quadrada" assert det != 0, "inv: A matriz tem determinante nulo e não pode ser invertida" B = np.zeros([Nrow, Ncol]) L, U = LU.LUdecomposition(A) for j in range(0, Ncol): b = np.zeros(Nrow) b[j] = 1 x = LU.subpro(L, b) B[:, j] = LU.subreg(U, x) return B
def unblur(blurred_img, mask): inv_mask = LU.solve(mask, np.identity(mask.shape[0])) np.save('inv_mask.npy', inv_mask) unblurred_img = flatten_mult(inv_mask, blurred_img) if WRITE: cv2.imwrite('images/unblurred_img.png', unblurred_img * 255) value = 0.1 #whatever value you want to add cv2.add(unblurred_img[:, :], value, unblurred_img[:, :]) return unblurred_img
def solve_all(): output_win = Tk() output_win.title("NUMERICAL METHODS") output_win.configure(bg="#B7C3D0") output_win.geometry("1000x700") results = Label(output_win, text="RESULTS\n*output windows are scrollable*", bg="#B7C3D0", fg="black") results.place(x=400, y=15) output = Text(output_win, width=80, height=8.5, wrap=WORD, background="white") output.place(x=160, y=50) output2 = Text(output_win, width=80, height=8.5, wrap=WORD, background="white") output2.place(x=160, y=205) output3 = Text(output_win, width=80, height=8.5, wrap=WORD, background="white") output3.place(x=160, y=360) output4 = Text(output_win, width=120, height=8.5, wrap=WORD, background="white") output4.place(x=15, y=515) unknownsNoField = unknownsEntry.get() equationField = equEntry.get() output.delete(0.0, END) output.insert(END, '**Gauss Elimination**\n\n') output.insert(END, GaussianElimination(int(unknownsNoField), equationField)) unknownsNoField = unknownsEntry2.get() equationField = equEntry2.get() output2.delete(0.0, END) output2.insert(END, '**Gauss Jordan**\n\n') output2.insert(END, gauss_jordan(int(unknownsNoField), equationField)) unknownsNoField = unknownsEntry3.get() equationField = equEntry3.get() output3.delete(0.0, END) output3.insert(END, '**LU Without pivoting**\n\n') output3.insert(END, LU(inputToMatrix(int(unknownsNoField), equationField))) output3.insert(END, '\n\n**LU With pivoting**\n\n') unknownsNoField = unknownsEntry3.get() equationField = equEntry3.get() output3.insert(END, lu_pivoting(int(unknownsNoField), equationField)) unknownsNoField = unknownsEntry4.get() equationField = equEntry4.get() iterationsField = iterationsEntry.get() epsilonField = epsilonEntry.get() initialValField = initialValEntry.get() initPoints = initialValField x = initPoints.split() initPoints = [] for i in range(0, int(unknownsNoField)): initPoints.append(float(x[i])) output4.delete(0.0, END) output4.insert(END, '***Gauss Seidel**\n\n') y = function(equationField, int(unknownsNoField), int(iterationsField), float(epsilonField), initPoints) for i in range(len(y)): output4.insert(END, y[i])
def __init__(self, n): """Even n preferred""" super(flowGAN, self).__init__() self.lin = nn.ModuleList([LU(2) for i in range(n+1)]) aff = [] for i in range(n): if i % 2 == 0: aff.append(affine2(2, hidden=128)) else: aff.append(affine2(2, hidden=128)) # aff.append(backLayer(2)) self.aff = nn.ModuleList(aff) self.n = n
class layer1(nn.Module): def __init__(self): super(layer1, self).__init__() self.fc1 = LU(2) self.nln = nLayer(2) self.fc2 = LU(2) def forward(self, x): y1, lJ1 = self.fc1(x) y2, lJ2 = self.nln(y1) y3, lJ3 = self.fc2(y2) # print(lJ2) # y = x + self.fc.bias return y3, math.log( 1 / (2 * math.pi)) - torch.sum(y3 * y3, 1) / 2 + lJ1 + lJ2 + lJ3 def sample(self, n, y3=None): if (type(y3) == type(None)): y3 = Variable(torch.randn(n, 2)).cuda() y2, _ = self.fc2.pushback(y3) y1, _ = self.nln.pushback(y2) x, _ = self.fc1.pushback(y1) return x
class layer1(nn.Module): def __init__(self): super(layer1, self).__init__() self.fc = LU(2) def forward(self, x): y, lJ = self.fc(x) return y, math.log(1/(2*math.pi)) - torch.sum(y*y, 1)/2 + lJ def sample(self, n, x = None): if (type(x) == type(None)): x = Variable(torch.randn(n, 2)).cuda() y, _ = self.fc.pushback(x) return y
def __init__(self, n): """Even n preferred""" super(flowGAN, self).__init__() self.lin = nn.ModuleList([LU(2) for i in range(n + 1)]) hyp = [] for i in range(n): if i % 2 == 0: hyp.append(nLayer(2)) else: hyp.append(nLayer(2)) # hyp.append(backLayer(2)) self.hyp = nn.ModuleList(hyp) self.n = n
def Newtons_nonlinear(G, x0, N=20, epsilon=.1): F = lambda X: matrix.Mat(G(X)).transpose() k = 1 x = matrix.Mat([x0]) while k <= N: b_k = (-1 * F(x.A[0])) A_k = J(G, x.A[0], 0.01) #print("b_k:",b_k.shape) #print("A_k:",A_k.shape) y = (LU.solve(A_k, b_k)).transpose() x = x + y # x(n+1) - x(n) = y if abs(y) < epsilon: return x.flatten().A[0] break k = k + 1 print("Error-maxiters exceeded") return x.flatten().A[0]
import LU import numpy a = numpy.array([[3., -8, 1, -7, 96], [6, 4, 8, 5, -13], [-1, 1, -9, -3, -54], [-6, 6, 9, -4, 82]]) print('Исходная матрица:') print(a) print("\n") b = LU.lu(a) print("Ответ:") print(b)
def unblur(blurred_img, mask): inv_mask = LU.solve(mask, np.identity(mask.shape[0])) unblurred_img = flatten_mult(inv_mask, blurred_img) value = 0.1 #whatever value you want to add cv2.add(unblurred_img[:,:], value, unblurred_img[:,:]) return unblurred_img
import LU import random def RndMat(n): A = matrix.Mat([[]]).zero(n,n) for j in range(n): for i in range(n): v = random.uniform(-1,1) A.s(i,j,v) return A A = matrix.Mat([[1,2,3],[3,2,1],[4,2,1]]) b = matrix.Mat([[1,2,3]]).transpose() Tol = 1e-8 x = LU.solve(A,b) print("A = ",A) print("b = ",b) print("x = LUPSolve(A,b) =",x) print("A.dot(x)=",A.dot(x)) B = LU.inv(A) print("B = LUPInvert(A) = ",B) print("A.dot(B) = ",A.dot(B)) print("LUPDeterminant(A) =",LU.det(A)) print("A.det() = ", A.det()) A = RndMat(9) import datetime print("A = RndMat(9)") t0 = datetime.datetime.now() print("LU.det(A) =",LU.det(A)) t1 = datetime.datetime.now()
def printLU(A): print("The LU orthogonalization of the matrix is as follows:") (Q, R) = LU.LU_reflection(A) print(Q) print(R) print(np.dot(Q, R))
def main(): sys.stdout.flush() DM = initialize() disease = [] week = [] division = [] doctor = [] with open('../data_resource/disease_dict.txt', 'r', encoding='utf-8') as r_disease: for line in r_disease: disease.append(line.replace('\n', '')) with open('../data_resource/week_dict.txt', 'r', encoding='utf-8') as r_week: for line in r_week: week.append(line.replace('\n', '')) with open('../data_resource/division_dict.txt', 'r', encoding='utf-8') as r_division: for line in r_division: division.append(line.replace('\n', '')) # with open('../data_resource/doctor_dict.txt','r') as r_doctor: # for line in r_doctor: # doctor.append(line) while True: if os.path.exists("DM.json"): with open("DM.json", 'r') as f: DM = json.load(f) slot_dictionary = { 'disease': '', 'division': '', 'doctor': '', 'time': '' } sentence = input('U: ') pattern = re.compile("[0-9]+\.[0-9]+\.[0-9]+") match = pattern.match(sentence) if match: DM["State"]["time"] = sentence elif sentence in week: DM["State"]["time"] = sentence # elif sentence in doctor: # DM["State"]["doctor"] = sentence elif sentence in division: DM["State"]["division"] = sentence elif sentence in disease: DM["State"]["disease"] = sentence else: slot_dictionary = LU.SlotFilling().decode(sentence) print("[ Slot ]") for slot, value in slot_dictionary.items(): print(slot, ": ", value) for slot in slot_dictionary: if slot_dictionary[slot] != '' and ( DM["State"][slot] == None or (type(DM["State"][slot]) == list and len(DM["State"][slot]) > 1)): DM["State"][slot] = slot_dictionary[slot] if type(DM["State"]["time"] ) == str and DM["State"]["time"] not in week and not match: DM["State"]["time"] = None if DM["Intent"] == None: intent = LU.IntentPredict().get_intent(sentence) intent_index = intent.index(max(intent)) DM["Intent"] = intent_index DM = DM_request(DM) print("[ DM ]") for i in DM: print(i, DM[i]) with open("DM.json", 'w') as fp: json.dump(DM, fp) if DM["Request"] == "end": sys.exit()
def interp(xdata, ydata): matrix = [] v = [] # i 1 to n-1, python i = 0 is first entry but here we need to go from i = 1 to n-1 n = len(xdata) z = 0 j = 0 # n points n - 1 equations so n - 1 entries in matrix #np.zeros(,) - nxn while z < n - 2: # n - 1 because first and last data points positions will not have outer data # to use for calcs matrix.append([]) v.append(0) while j < n - 2: matrix[z].append(0) # makes all entries= 0 j += 1 j = 0 z += 1 #empty matrix with correct dimensions works #now filling in the matrix # every i move to next coloumn and change the zeros to the coefficients i = 1 j = 0 offset = 0 # each row will have coefficients move one coloumn to right # MAKE THIS A TRIDAGANOL MATRIX REMOVE ALL F''_0 TERMS SEE WRITTEN PAD NOTE while i <= n - 2: #starting position is at 0 for list so use i - 1 to place numbers in matrix #need another counter for coefficients co = 1 #need another statement for the last two rows while (j + offset) <= n - 2: #as j starts from 0? #using formula 4.15 if co == 1 and i > 1: matrix[i - 1][j + offset] = (xdata[i] - xdata[i - 1]) / 6 elif co == 1 and i == 1: matrix[i - 1][j + offset] = (xdata[i + 1] - xdata[i - 1]) / 3 offset = -1 elif co == 2 and (i < n - 1): matrix[i - 1][j + offset] = (xdata[i + 1] - xdata[i - 1]) / 3 elif (co == 3) and (i < n - 2): matrix[i - 1][j + offset] = (xdata[i + 1] - xdata[i]) / 6 # check whether entering last two rows co += 1 j += 1 j = 0 offset += 1 i += 1 # compute v vector i = 1 while i <= n - 2: v[i - 1] = ((ydata[i + 1] - ydata[i]) / (xdata[i + 1] - xdata[i])) - ((ydata[i] - ydata[i - 1]) / (xdata[i] - xdata[i - 1])) i += 1 #once solved for f''_n then plot the cubic spline f(x) at as many points as you like #so loop over x values and plot f(x) #use matrix solver to get f''_n values as a vector #implement boudary conditions # here matrix is always an upper matrix so can set L = I # fdash is f derivatives L = m.LU(matrix)[0] U = m.LU(matrix)[1] fdash = m.solvex(L, U, v) # boudary conditions: fdash2 = [0] # sets f''_0 = 0 fdash2 += fdash fdash2.append(0) # sets f''_n = 0 # set number of points to plot cubic spline dx = 0.001 ddx = dx y = [] x = [] # spline exists between every two points # must loop through values between each x points and plot spline for those then move next pair # plot from x[0] to x[-1] i = 0 while i < n - 1: # plot between points while (xdata[i] + dx) < xdata[i + 1]: A = (xdata[i + 1] - (xdata[i] + dx)) / (xdata[i + 1] - xdata[i]) B = 1 - A C = (((A**3 - A) * (xdata[i + 1] - xdata[i])**2)) / 6 D = (((B**3 - B) * (xdata[i + 1] - xdata[i])**2)) / 6 y.append((A * ydata[i]) + (B * ydata[i + 1]) + (C * fdash2[i]) + (D * fdash2[i + 1])) x.append(xdata[i] + dx) dx += ddx dx = 0 i += 1 return np.array(x), np.array(y)
def __init__(self): super(layer1, self).__init__() self.fc = LU(2)
import UTILITY as ut import LU as lu matrix = ut.get_file("q2.txt") A = [[matrix[i][j] for j in range(4)] for i in range(4)] n = len(A) inv_mat = [[1 if i == j else 0 for j in range(n)] for i in range(n)] value = lu.lu_and_det( A, inv_mat ) #lu_and_det function decomposes A to LU if possible and returns the determinant if value == 0: print("The Determinant of operator is zero. Hence Inverse does not exist.") else: print("Determinant=%0.4f. So Inverse exists." % value) print("Inverse=") for i in range(n): column = [inv_mat[j][i] for j in range(n)] column = lu.forward_substitution(A, column) column = lu.backward_substitution(A, column) for j in range(n): inv_mat[j][i] = column[j] ut.display_matrix(inv_mat) #output ''' Determinant=-36.0000. So Inverse exists. Inverse= [[-0.250 1.667 -1.833 0.333] [0.083 -0.667 0.833 0.000] [0.167 -0.333 -0.333 0.000] [-0.083 0.667 0.167 0.000]] '''
import UTILITY as ut import LU as lu matrix=ut.get_file("q1.txt") A=[[matrix[i][j] for j in range(4)] for i in range(4)] b=[matrix[i][4] for i in range(4)] value=lu.lu_and_det(A,b) #lu_and_det function decomposes Ar to LU and calculates the determinant if value==0: print("The Determinant of operator is zero. Hence No unique solution is possible.") else: b=lu.forward_substitution(A,b) b=lu.backward_substitution(A,b) print("Solution=",end='') ut.display_vector(b) #Output ''' Solution=[1.000 -1.000 1.000 2.000 ] '''
def __init__(self): super(layer1, self).__init__() self.fc1 = LU(2) self.nln = nLayer(2) self.fc2 = LU(2)
import LU import numpy as np A = [[10, 2, 1, 7], [1, 5, 1, -8], [2, 3, 10, 6]] LU.solve(np.array(A, dtype=np.float64))
import LU import Generate import numpy as np np.set_printoptions(suppress=True) matrix, b = Generate.Generate(6) #matrix = np.array([[2,7,-6],[8,2,1],[7,4,2]], dtype=float) #b = np.array([1,2,3], dtype=float) print(" matrix:") print(matrix) print(" b:") print(b) luMatrix = LU.LU(matrix, b) LU = np.dot( np.tril(luMatrix.C, -1) + np.eye(len(luMatrix.C)), np.triu(luMatrix.C)) print("\n show: ") luMatrix.show() print("\n solve: ") print(luMatrix.solve()) print(" numpy.linalg.solve: ") print(np.linalg.solve(matrix, luMatrix.b)) print("\n det: ") print(luMatrix.det()) print("\n L*U:") print( np.dot( np.tril(luMatrix.C, -1) + np.eye(len(luMatrix.C)), np.triu(luMatrix.C))) print("\n P*A:") print(np.dot(luMatrix.P, matrix)) print("\n inverse: ")
def Parse(equations, type, n, IntialGuesses, ea, it): # It will read the entire file global con global a global x a = np.zeros((n, n + 1)) x = np.zeros(n) k = 0 alphabets = {} while k < n: con = equations[k] con = con.replace(' ', '') for element in con: if element.isalpha(): alphabets[element] = 0 k += 1 j = 0 for i in alphabets: alphabets[i] = j j += 1 k = 0 while k < n: con = equations[k] con = con.replace(' ', '') count = 0 while (count < len(con)): if con[count].isalpha() and ((con[count - 2].isdigit() == False and con[count - 1].isdigit() == False) or (count == 0)): con = con[:count] + '1*' + con[count:] count += 1 count = 0 z = re.findall(r"[+-]?\d+(?:\.\d+)?", con) f = 0 for element in con: if element.isalpha() and (con[count - 2].isdigit() or con[count - 1].isdigit()): a[k][alphabets[element]] = z[f] f += 1 if count + 1 >= len(con) and element.isdigit(): a[k][n] = -1 * float(z[f]) f += 1 elif count + 1 < len(con) and element.isdigit(): if con[count + 1] != "*" and con[count + 1] != "." and con[ count + 1].isdigit() == False and con[count + 1].isalpha() == False: a[k][n] = -1 * float(z[f]) f += 1 count += 1 k += 1 if type == 'LU': arr1 = temp.LU(a) f = open("LU.txt", "w") for i in range(0, len(arr1)): f.write(str(arr1[i])) f.write(" ") f.close() return arr1, string elif type == "Gaussian-jordan": arr2 = Gauss_Jordan.Gaussian_jordan(a) f = open("jordan.txt", "w") for i in range(0, len(arr2)): f.write(str(arr2[i])) f.write(" ") f.close() elif type == 'Gaussian-elimination': arr3 = Gaussian_elimination.Gaussian_elimination(a) f = open("elimination.txt", "w") for i in range(0, len(arr3)): f.write(str(arr3[i])) f.write(" ") f.close() elif type == 'seidel': results = [] errors = [] seidel.seidel(a, IntialGuesses, ea, it) f = open("seidel.txt", "w") for i in range(0, len(results)): f.write(str(i)) f.write(" ") for j in range(0, len(a)): f.write(str(results[i][j])) f.write(" ") for j in range(0, len(a)): if (i > 0): f.write(str(errors[i - 1][j])) f.write(" ") f.write("\n") f.close()
def __init__(self): super(layer1, self).__init__() self.fc1 = LU(2) self.bl = backLayer(2) self.fc2 = LU(2)
#! /usr/bin/env python3 # author bravomikekilo [email protected] # under GPLv3 # for LICENSE see LICENSE at root. import numpy as np import LU a = np.array([[8.1, 2.3, -1.5], [0.5, -6.23, 0.87], [2.5, 1.5, 10.2]]) print('input|>') print(a) L, U = LU.crout(a, inplace=False) print('L|>') print(L) print('U|>') print(U) print('LU|>') print(L.dot(U)) A = np.array([[1, 2, 3], [4, 3, 6], [7, 8, 9]], dtype=np.float32) b = np.array([8, 7, 5], dtype=np.float32).T print('A|>\n', A, sep='') print('b|>\n', b, sep='') x = LU.LU_solve(A.copy(), b) print('x|>\n', x, sep='') print("b'|>\n", A.dot(x), sep='')
def main(): client = db.MongoClient(DB_IP, DB_PORT) collection_division = client[DB_NAME]["division"] collection_disease = client[DB_NAME]["disease"] sys.stdout.flush() print("您好,我是Seek Doctor Bot,如果您想要\n" + "1.查詢某疾病相關症狀,您可以問我:請問青光眼會怎樣\n" + "2.知道某疾病屬於什麼科別,您可以問我:青光眼是哪科\n" + "3.查詢某疾病或科別主治醫師,您可以問我:青光眼要看哪些醫生\n" + "4.查詢某疾病,科別或醫生的門診時間,您可以說:給我青光眼門診時刻表\n" + "5.預約掛號某疾病,科別或醫生的門診,您可以說:我要掛號眼科") while True: sentence = input('\n\n請輸入: ') slot_dictionary = LU.SlotFilling().decode(sentence) print("[ Slot ]") for slot, value in slot_dictionary.items(): print(slot, ": ", value) intent = LU.IntentPredict().get_intent(sentence) intent_index = intent.index(max(intent)) intents = [ 'greeting', 'search_symptom', 'search_division', 'search_doctor', 'search_timetable', 'register' ] print('[ Intent ] ' + intents[intent_index]) print('\n\n') if intent_index == 1: # search_symptom print("好的,您想查詢" + slot_dictionary['disease'] + "會有什麼症狀,以下為相關可能症狀:") for data in collection_disease.find( {"disease_c": { "$regex": slot_dictionary['disease'] }}): print(", ".join(data['symptom'])) elif intent_index == 2: # search_division print("好的,您想查詢" + slot_dictionary['disease'] + "是屬於哪一科,以下為相關科別:") for data in collection_disease.find( {"disease_c": { "$regex": slot_dictionary['disease'] }}): print(", ".join(data['department'])) elif intent_index == 3: # search_doctor print("好的,您想查詢" + slot_dictionary['division'] + slot_dictionary['disease'] + "有哪些醫生可以掛號,以下為醫生表列:") for data in collection_division.find({ "$and": [{ "disease": { "$regex": slot_dictionary['disease'] } }, { "department": { "$regex": slot_dictionary['division'] } }] }): print(data['department'] + " 醫師: " + ", ".join(data['doctor'])) elif intent_index == 4: # search_timetable print("好的,您想查詢" + slot_dictionary['division'] + slot_dictionary['disease'] + slot_dictionary['doctor'] + slot_dictionary['time'] + "的門診時間") elif intent_index == 5: # register print("好的,幫您預約掛號" + " " + slot_dictionary['division'] + " " + slot_dictionary['disease'] + " " + slot_dictionary['doctor'] + " " + slot_dictionary['time'] + "的門診") else: print("不好意思,我不確定您的意思")
import input_output as io import gauss import aditional_functions as af import LU A = io.Input_matrix_from_keyboard() b = io.Input_matrix_from_keyboard() af.checking_SLAR(A, b) x = gauss.Gauss(A, b) if type(x) == int: print("The system is degenerate, we figure out it on the " + str(-x) + " iteration") else: io.print_matrix(x, "Answer via Gauss: ") io.print_matrix(af.subtraction(af.multiplying(A, x), b), "r = A*x - b = ") (L, U) = LU.Factorization(A) if L == False: print("This matrix can't be factorized") quit(-1) io.print_matrix(L, "Matrix L:") io.print_matrix(U, "Matrix U:") io.print_matrix(af.multiplying(L, U), "L*U = ") B = LU.Inversed_matrix(L, U) io.print_matrix(B, "A^(-1) = ") x = LU.solution(L, U, b) io.print_matrix(x, "Answer via LU factorization: ") print("Number of conditionality = " + str(round(LU.matrix_norm(A) * LU.matrix_norm(B)))) io.print_matrix(af.subtraction(af.multiplying(A, x), b), "r = A*x - b = ")
def solve(): global Nodes, A, b, x mshNodes = np.array(model.mesh.getNodes()[0]) numMeshNodes = len(mshNodes) if (PRINTF): printf('numMeshNodes =', numMeshNodes) maxNodeTag = int(np.amax(mshNodes)) if (PRINTF): printf('maxNodeTag =', maxNodeTag) # initializations of global assembly arrays iteratively filled-in during assembly matrowflat = np.array([], dtype=np.int32) matcolflat = np.array([], dtype=np.int32) matflat = np.array([], dtype=np.int32) rhsrowflat = np.array([], dtype=np.int32) rhsflat = np.array([], dtype=np.int32) # typNodes[tag] = {0,1,2} 0: does not exist, 1:internal node, 2:boundary node # Existing node tags are set to 1 here. # Boundary node tag are identified later. typNodes = np.zeros(maxNodeTag + 1, dtype=np.int32) for tagNode in mshNodes: typNodes[tagNode] = 1 # The mesh is iterated over, looping successively (nested loops) over: # Physical groups/Geometrical entities/Element types/Elements vGroups = model.getPhysicalGroups() for iGroup in vGroups: dimGroup = iGroup[0] # 1D, 2D or 3D tagGroup = iGroup[ 1] # the word 'tag' is systematically used instead of 'number' vEntities = model.getEntitiesForPhysicalGroup(dimGroup, tagGroup) for tagEntity in vEntities: dimEntity = dimGroup # FIXME dimEntity should be optional when tagEntity given. vElementTypes = model.mesh.getElementTypes(dimEntity, tagEntity) for elementType in vElementTypes: vTags, vNodes = model.mesh.getElementsByType( elementType, tagEntity) numElements = len(vTags) numGroupNodes = len(vNodes) enode = np.array(vNodes).reshape((numElements, -1)) numElementNodes = enode.shape[1] if (PRINTF): printf('\nIn group', tagGroup, ', numElements = e =', numElements) if (PRINTF): printf('numGroupNodes =', numGroupNodes, ', numElementNodes = n =', numElementNodes) if (PRINTF): printf('%enodes (e,n) =', enode.shape) # Assembly of stiffness matrix for all 2 dimensional elements # (i.e., triangles or quadrangles) if dimEntity == 2: uvw, weights = gmsh.model.mesh.getIntegrationPoints( 2, "Gauss2") numcomp, sf = model.mesh.getBasisFunctions( elementType, uvw, 'Lagrange') numGaussPoints = weights.shape[0] if (PRINTF): printf('numGaussPoints = g =', numGaussPoints, ', %weights (g) =', weights.shape) sf = np.array(sf).reshape((numGaussPoints, -1)) if (PRINTF): printf('%sf (g,n) =', sf.shape) if sf.shape[1] != numElementNodes: errorf('Something went wrong') numcomp, dsfdu = model.mesh.getBasisFunctions( elementType, uvw, 'GradLagrange') #remove useless dsfdw dsfdu = np.array(dsfdu).reshape( (numGaussPoints, numElementNodes, 3))[:, :, :-1] if (PRINTF): printf('%dsfdu (g,n,u) =', dsfdu.shape) qjac, qdet, qpoint = model.mesh.getJacobians( elementType, uvw, tagEntity) if (PRINTF): printf('Gauss integr:', len(qjac), len(qdet), len(qpoint), '= (9, 1, 3) x', numGaussPoints, 'x', numElements) qdet = np.array(qdet).reshape( (numElements, numGaussPoints)) if (PRINTF): printf('%qdet (e,g) =', qdet.shape) #remove components of dxdu useless in dimEntity dimensions (here 2D) dxdu = np.array(qjac).reshape( (numElements, numGaussPoints, 3, 3))[:, :, :-1, :-1] # jacobien stored by row, so dxdu[i][j] = dxdu_ij = dxi/duj if (PRINTF): printf('%dxdu (e,g,x,u)=', dxdu.shape) # material characteristic if tagGroup == CORE: nu = complex(1., 0) / (mur * mu0) else: nu = complex(1., 0) / mu0 # dsdfx = dudx * dsfdu dudx = np.linalg.inv( dxdu) # dudx[j][k] = dudx_jk = duj/dxk if (PRINTF): printf('%dudx (e,g,u,x) =', dudx.shape) dsfdx = np.einsum("egxu,gnu->egnx", dudx, dsfdu) # sum over u = dot product if (PRINTF): printf('%dsfdx (e,g,n,x) =', dsfdx.shape) # performs the Gauss integration with einsum localmat = nu * np.einsum("egik,egjk,eg,g->eij", dsfdx, dsfdx, qdet, weights) if (PRINTF): printf('%localmat (e,n,n) =', localmat.shape) if tagGroup == PLATE: localmat += sigma * jomega * np.einsum( "gi,gj,eg,g->eij", sf, sf, qdet, weights) Liesf = np.einsum("egik,k->egi", dsfdx, np.array([vel, 0])) localmat += sigma * np.einsum("gi,egj,eg,g->eij", sf, Liesf, qdet, weights) # The next two lines are rather obscure. # See explanations at the bottom of the file. matcol = np.repeat(enode[:, :, None], numElementNodes, axis=2) matrow = np.repeat(enode[:, None, :], numElementNodes, axis=1) matcolflat = np.append(matcolflat, matcol.flatten()) matrowflat = np.append(matrowflat, matrow.flatten()) matflat = np.append(matflat, localmat.flatten()) if tagGroup == COILP or tagGroup == COILN: if tagGroup == COILP: load = J elif tagGroup == COILN: load = -J localrhs = load * np.einsum("gn,eg,g->en", sf, qdet, weights) if (PRINTF): printf('Check rhs:', np.sum(localrhs), "=", load * CoilSection) rhsrowflat = np.append(rhsrowflat, enode.flatten()) rhsflat = np.append(rhsflat, localrhs.flatten()) # identify boundary node if tagGroup == DIRICHLET0: for tagNode in vNodes: typNodes[tagNode] = 2 if (PRINTF): printf('\nDimension of arrays built by the assembly process') printf('%colflat = ', matcolflat.shape) printf('%rowflat = ', matrowflat.shape) printf('%localmatflat = ', matflat.shape) printf('%rhsrowflat = ', rhsrowflat.shape) printf('%rhsflat = ', rhsflat.shape) # Associate to all mesh nodes a line number in the system matrix # reserving top lines for internal nodes and bottom lines for fixed nodes (boundary nodes). node2unknown = np.zeros(maxNodeTag + 1, dtype=np.int32) index = 0 for tagNode, typ in enumerate(typNodes): if typ == 1: # not fixed index += 1 node2unknown[tagNode] = index numUnknowns = index if (PRINTF): printf('numUnknowns =', numUnknowns) for tagNode, typ in enumerate(typNodes): if typ == 2: # fixed index += 1 node2unknown[tagNode] = index if index != numMeshNodes: errorf('Something went wrong') unknown2node = np.zeros(numMeshNodes + 1, dtype=np.int32) for node, unkn in enumerate(node2unknown): unknown2node[unkn] = node if (PRINTF): printf('\nDimension of nodes vs unknowns arrays') printf('%mshNodes=', mshNodes.shape) printf('%typNodes=', typNodes.shape) printf('%node2unknown=', node2unknown.shape) printf('%unknown2node=', unknown2node.shape) # Generate system matrix A=globalmat and right hand side b=globalrhs # https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html # 'node2unknown-1' are because python numbers rows and columns from 0 if (TEST): print("Nombre d'éléments définis : {}".format(matflat.shape[0])) print("Pourcentage matrice creuse : %.2f %%" % ((matflat.shape[0]) / ((numMeshNodes * numMeshNodes * 0.01)))) globalmat = scipy.sparse.coo_matrix( (matflat, (node2unknown[matcolflat.astype(int)] - 1, node2unknown[matrowflat.astype(int)] - 1)), shape=(numMeshNodes, numMeshNodes)).todense() globalrhs = np.zeros(numMeshNodes) for index, node in enumerate(rhsrowflat): globalrhs[node2unknown[int(node)] - 1] += rhsflat[int(index)] if (PRINTF): printf('%globalmat =', globalmat.shape, ' %globalrhs =', globalrhs.shape) Nodes = globalmat.shape[0] A = globalmat[:numUnknowns, :numUnknowns] if SAVE: color = {'cmap': 'Purples'} plt.subplot(221) plt.spy(A, markersize=1) plt.subplot(222) plt.spy(LU.LU(A)[0], markersize=1) plt.subplot(223) sA, iA, jA = my.CSRformat(A) r = my.RCMK(iA, jA) a_rcmk = (A[:, r])[r, :] plt.spy((a_rcmk), markersize=1) plt.subplot(224) plt.spy(LU.LU(a_rcmk)[0], markersize=1) # my.plot_matrix(LU.LU(a_rcmk)[0], NAME+str(numUnknowns)) plt.show() # my.plot_matrix(A.real, NAME+str(numUnknowns)) if TEST: # my.all_test(A, NAME) S = get_min_max_singular_values(A) ymin.append(S[0]) ymax.append(S[1]) k.append(S[1] / S[0]) if PRINT: print("\nMIN SINGULAR VALUES %.2f" % (S[0])) print("MAX SINGULAR VALUES %.2f" % (S[1])) print("CONDITIONNEMENT %.2f\n" % (S[1] / S[0])) b = globalrhs[:numUnknowns] if (SOLVE): success, x = my.mysolve(A, b, **kwargs) if not success: errorf('Solver not implemented yet') sol = np.append(x, np.zeros(numMeshNodes - numUnknowns)) if (PRINTF): printf('%sol =', sol.shape) # Export solution sview = gmsh.view.add("solution") gmsh.view.addModelData(sview, 0, "", "NodeData", unknown2node[1:], sol[:, None]) #gmsh.view.write(sview,"a.pos") if (PRINTF): printf('Flux (computed) =', np.max(sol) - np.min(sol)) return