def get_solid_section(self): self.__get_element_sets_according_to_compaction() solid_sections = [] for mat_numb in range(self.__steps): if not len(self.__sets[mat_numb]) == 0: new_material = copy.deepcopy(self.__material) # Change material propertys according to the given material function (law) # Structural material settings for young_modul in new_material.get_young_module(): young_modul.set_young_module(young_modul.get_young_module() * (1.0 - (float(self.__steps - mat_numb - 1)) / float(self.__steps)) ** self.__exponent) for poisson_ratio in new_material.get_poisson_ratio(): poisson_ratio.set_poisson_ratio(poisson_ratio.get_poisson_ratio()) # Heat exchange material settings for conductivity in new_material.get_conductivity(): conductivity.set_conductivity(conductivity.get_conductivity() * (1.0 - (float(self.__steps - mat_numb - 1)) / float(self.__steps)) ** self.__exponent) new_material.set_name(new_material.get_name() + "_" + str(mat_numb)) solid_sections.append(FEM.SolidSection(new_material, FEM.ElementSet("topo_mat_" + str(mat_numb), self.__sets[mat_numb]))) return solid_sections
def homogen(h0, f, n): # First lets generate the uniform mesh for this mesh width mesh = msh.grid_square(1, h0) # Matrix of nodes p = mesh[0] # Matrix of triangles index t = mesh[1] # Now lets compute the stiffness matrix A = fem.stiffness(p, t) # Lets compute the load vector Load = fem.load(p, t, n, f) # Lets compute the vector m that analogous to the load vector # with f(x.y)=1 m = fem.load(p, t, n, lambda x, y: 1) # Lets create the matrix and vectors of the modified bigger system to # solve with lagrangian multipliers of size (size(A)+(1,1)) size = A.shape[0] B = sparse.lil_matrix(np.zeros([size + 1, size + 1])) B[0:size, 0:size] = A B[0:size, size] = m B[size, 0:size] = m.transpose() # We add a zero at the end of f Load = np.concatenate((Load, np.array([[0]]))) # Now lets get the solution of the linear system using spsolve function U = spla.spsolve(B, Load) #We extract the solution u and the multiplicer l u = U[0:size] l = U[size] # We return [p,t,u,l] return p, t, u, l
def discSol(h): (p,t,e,z,be)=mesh.generate_shifted_quad(h,1,True) width=mesh.max_mesh_width() nDN=FE.notDiricNodes(p,t,be) Stiff=FE.stiffness(p,t).tocsr() Load=FE.load(p,t,3,f) N=sp.lil_matrix((nDN.size,p[0:,0].size)) for j in range(nDN.size): # Initialisierung von Reduktionsmatrizen, aehnlich der T Matrizen. N[j,nDN[j]]=1 # Dies sind quasi NxN Einheitsmatrizen bei denen die Zeilen entfernt # sind, deren Indizes mit denen der Boundary Nodes korrelieren. rStiff=N.dot(Stiff).dot(N.transpose()) # Durch Multiplikation der N Matrizen von Links und Rechts werden die rLoad=N.dot(Load) run=spla.spsolve(rStiff,rLoad) un=N.transpose().dot(run) # if h==0.1: # FE.plot(p,t,un) # plt.title('Diskrete Loesung') # plt.show() return (np.dot(un, Load),width)
def homogen(h0,f,n): # First lets generate the uniform mesh for this mesh width mesh=msh.grid_square(1,h0) # Matrix of nodes p=mesh[0] # Matrix of triangles index t=mesh[1] # Now lets compute the stiffness matrix A=fem.stiffness(p,t) # Lets compute the load vector Load=fem.load(p,t,n,f) # Lets compute the vector m that analogous to the load vector # with f(x.y)=1 m=fem.load(p,t,n,lambda x,y:1) # Lets create the matrix and vectors of the modified bigger system to # solve with lagrangian multipliers of size (size(A)+(1,1)) size=A.shape[0] B=sparse.lil_matrix(np.zeros([size+1,size+1])) B[0:size,0:size]=A B[0:size,size]=m B[size,0:size]=m.transpose() # We add a zero at the end of f Load=np.concatenate((Load,np.array([[0]]))) # Now lets get the solution of the linear system using spsolve function U=spla.spsolve(B,Load) #We extract the solution u and the multiplicer l u=U[0:size] l=U[size] # We return [p,t,u,l] return p,t,u,l
def exactFEMFEM(x1, x2, ys, ye, lmd1, lmd2, f1, f2): n1 = len(x1) - 2 n2 = len(x2) - 2 A = sp.lil_matrix((n1 + n2 + 1, n1 + n2 + 1)) Agen(A, 0, 0, x1, lmd1) Agen(A, n1, n1, x2, lmd2) A[n1 - 1, -1] = -lmd1 / (x1[-1] - x1[-2]) #add second system A[n1, -1] = -lmd2 / (x2[1] - x2[0]) #add dirvitive equation A[-1, n1 - 1] = -lmd1 / (x1[-1] - x1[-2]) A[-1, n1] = -lmd2 / (x2[1] - x2[0]) A[-1, -1] = lmd1 / (x1[-1] - x1[-2]) + lmd2 / (x2[1] - x2[0]) B = sc.zeros(n1 + n2 + 1) B[0] = ys * (lmd1 / (x1[1] - x1[0])) B[-2] = ye * (lmd2 / (x2[-1] - x2[-2])) for i in range(n1): B[i] -= integrate.quad(lambda x: f1(x) * fem.phi(i, x, x1), x1[i], x1[i + 2])[0] for i in range(n2): B[n1 + i] -= integrate.quad(lambda x: f2(x) * fem.phi(i, x, x2), x2[i], x2[i + 2])[0] B[-1] -= integrate.quad(lambda x: f2(x) * fem.phi_start(x, x2), x2[0], x2[1])[0] B[-1] -= integrate.quad(lambda x: f1(x) * fem.phi_end(x, x1), x1[-2], x1[-1])[0] sol = list(slin.spsolve(sp.csr_matrix(A), B)) gamma = sol[-1] vh = ap.femapprox(x1, ys, gamma, sol[:n1]) wh = ap.femapprox(x2, gamma, ye, sol[n1:n2 + n1]) return (vh, wh)
def __read_element_sets(self, elem_dic): i_file = open(self.__filename, "r") elem_sets = [] read_element_set = False set_type_is_elset = True for line in i_file: line = line[0:-1] # Coments and line does not exist if len(line) == 0: continue elif len(line) >= 2: if line[0:1] == "**": continue # Stop reading if line[0] == "*": read_element_set = False if read_element_set: words = line.split(",") if set_type_is_elset: for word in words: if word.isdigit(): elem_set.add_element(elem_dic[int(word)]) else: elem_set.add_element(elem_dic[int(words[0])]) # Check if node key is found and not *NODE PRINT ... if "*ELSET" in line.upper(): set_type_is_elset = True read_element_set = True words = line.split(",") new_word = words[1].split("=") elset_name = self.__remove_char_on_black_list(new_word[1]) elem_set = FEM.ElementSet(elset_name) elem_sets.append(elem_set) if "*ELEMENT" in line.upper(): if "ELSET" in line.upper(): set_type_is_elset = False read_element_set = True words = line.split(",") for word in words: if "ELSET" in word.upper(): new_word = word.split("=") elset_name = self.__remove_char_on_black_list( new_word[1]) elem_set = FEM.ElementSet(elset_name) elem_sets.append(elem_set) return elem_sets
def UNV2467Reader(f, fem): while True: # Read Record 1: line1 = f.readline() # Read Record 2 line2 = f.readline().strip() if len(line2) and not line1.startswith(FLAG): # Read group dataline = Line2Int(line1) group_name = line2.replace(' ', '_') nitems = dataline[-1] nlines = int((nitems + 1) / 2) # check if there are to be any items in the group. if nlines == 0: fpos = f.tell() # If not, skip row - or if not empty: let row be # and start next read of Record 1 if f.readline().strip(): f.seek(fpos) else: # Read group items group_items = [] for i in range(nlines): dat = Line2Int(f.readline()) group_items.append(dat[0:3]) if len(dat) > 4: group_items.append(dat[4:7]) # Split group in node and element sets nset = []; eset = [] for item in group_items: if item[0] == 7: nset.append(item[1]) if item[0] == 8: eset.append(item[1]) # Store non empty groups if len(nset): nset = FEM.Group(group_name, 7, nset) fem.nsets.append(nset) if len(eset): eset = FEM.Group(group_name, 8, eset) fem.esets.append(eset) else: break logging.info('{} nsets'.format(len(fem.nsets))) logging.info('{} esets'.format(len(fem.esets))) return fem
def __init__(self,Z,Ne=0,ni=None,spin=2,scf=True,\ gridN=350,gridMin=1e-4,gridMax=100,Lmax=3,\ convCrit=1e-3, mixConst=0.3): """ Main class to calculate find LSDA solution of atom in: Z : Atomic number Ne : Additional electrons 0, +-1 etc. ni : Initial electron density on radial grid spin : 1 (non) or 2 (spin) polarized solution scf : Find SCF solution (True) one iteration (False) grid N,min,max : Radial grid specification """ self.grid = FEM.radialGrid(NN=gridN,rmin=gridMin,rmax=gridMax) print len(self.grid.x) self.spin, self.Lmax = spin, Lmax self.Z, self.Ne, self.convCrit = Z, Ne, convCrit self.mixConst = mixConst if ni==None: self.initDensity() else: self.n = ni self.initMat() if scf: self.runSCF()
def __read_solid_section(self, materials, elem_sets): i_file = open(self.__filename, "r") solid_sections = [] for line in i_file: line = line[0:-1] # Coments and line does not exist if len(line) == 0: continue elif len(line) >= 2: if line[0:1] == "**": continue # Check if node key is found and not *NODE PRINT ... if "*SOLID SECTION" in line.upper(): solid_section = FEM.SolidSection() words = line.split(",") for word in words: if "ELSET" in word.upper(): new_word = word.split("=") elset_name = self.__remove_char_on_black_list(new_word) if "MATERIAL" in word.upper(): new_word = word.split("=") material_name = self.__remove_char_on_black_list( new_word[1]) for material in materials: if material.get_name() == material_name: solid_section.set_material(material) for elset in elem_sets: if elset.get_name() == elset_name: solid_section.set_elset(elset) solid_sections.append(solid_section) return solid_sections
def dirichlet_nonhomogeneous(h0, f, g, n): # First lets generate the uniform mesh for this mesh width mesh = msh.grid_square(1, h0) # Matrix of nodes p = mesh[0] # Matrix of triangles index t = mesh[1] # Matrix of border element index be = mesh[2] #Lets get the interior nodes in the mesh innod = fem.interiorNodes(p, t, be) # Rewrite the innod to match with indices beginning at 0 innod = [i - 1 for i in innod] # Now lets compute the stiffness matrix Stiff = fem.stiffness(p, t) # Now lets compute the mass matrix Mass = fem.mass(p, t) # Lets compute the load vector Load = fem.load(p, t, n, f) # The complete matrix for the bilinear form is given by the sum of #the stiffness and the mass B = Stiff + Mass # Lets define a vector with of the values of u_g in each node # that is zero in the innernodes and g everywhere else ug = np.array([g(p[i][0], p[i][1]) for i in range(len(p))]) ug[innod] = np.zeros(len(innod)) #Calculate the new load vector with the Dirichleft taken in account Load = Load - B.dot(ug).reshape(len(p), 1) #Now lets get the homogeneous problem solution as we did before # First lets initialize the array in zeros to respect the homogeneous # Dirichlet boundary conditions U = np.zeros(len(p)) # Lets take just the interior points in the matrix B and the Load vector Bint = B[innod][:, innod] Loadint = Load[innod] # Now lets get the solution of the linear system of the interior points # using spsolve function Uint = spla.spsolve(Bint, Loadint) # We put them in the correspondence interior points of the complete # solution U[innod] = Uint # Finally we sum up the two solutions to get the final solution u = U + ug # We return [p,t,U] return p, t, u
def dirichlet_nonhomogeneous(h0, f, g, n): # First lets generate the uniform mesh for this mesh width mesh = msh.grid_square(1, h0) # Matrix of nodes p = mesh[0] # Matrix of triangles index t = mesh[1] # Matrix of border element index be = mesh[2] # Lets get the interior nodes in the mesh innod = fem.interiorNodes(p, t, be) # Rewrite the innod to match with indices beginning at 0 innod = [i - 1 for i in innod] # Now lets compute the stiffness matrix Stiff = fem.stiffness(p, t) # Now lets compute the mass matrix Mass = fem.mass(p, t) # Lets compute the load vector Load = fem.load(p, t, n, f) # The complete matrix for the bilinear form is given by the sum of # the stiffness and the mass B = Stiff + Mass # Lets define a vector with of the values of u_g in each node # that is zero in the innernodes and g everywhere else ug = np.array([g(p[i][0], p[i][1]) for i in range(len(p))]) ug[innod] = np.zeros(len(innod)) # Calculate the new load vector with the Dirichleft taken in account Load = Load - B.dot(ug).reshape(len(p), 1) # Now lets get the homogeneous problem solution as we did before # First lets initialize the array in zeros to respect the homogeneous # Dirichlet boundary conditions U = np.zeros(len(p)) # Lets take just the interior points in the matrix B and the Load vector Bint = B[innod][:, innod] Loadint = Load[innod] # Now lets get the solution of the linear system of the interior points # using spsolve function Uint = spla.spsolve(Bint, Loadint) # We put them in the correspondence interior points of the complete # solution U[innod] = Uint # Finally we sum up the two solutions to get the final solution u = U + ug # We return [p,t,U] return p, t, u
def __init__(self, filename): self.file = None self.filename = filename self.fem = FEM.FEM() self.sections = [] # List of supported datasets and corresponding dataset handler functions self.datasetsIds = [2411, 2412, 2467, 2477] self.datasetsHandlers = [UNV2411Reader, UNV2412Reader, UNV2467Reader, UNV2467Reader]
def __init__(self,filename): self.file=None self.filename=filename self.FEM=FEM() self.startFlag=' -1' self.endFlag=' -1' # list of supported datasets and corresponding dataset handler functions self.datasetsIds=[2411,2412,2467, 2477] self.datasetsHandlers=[self.UNV2411Reader, self.UNV2412Reader, self.UNV2467Reader, self.UNV2467Reader] self.sections=[]
def neumann(h0,f,n): # First lets generate the uniform mesh for this mesh width mesh=msh.grid_square(1,h0) # Matrix of nodes p=mesh[0] # Matrix of triangles index t=mesh[1] # Now lets compute the stiffness matrix Stiff=fem.stiffness(p,t) # Now lets compute the mass matrix Mass=fem.mass(p,t) # Lets compute the load vector Load=fem.load(p,t,n,f) # The complete matrix for the bilinear form is given by the sum of #the stiffness and the mass B=Stiff+Mass # Now lets get the solution of the linear system using spsolve function U=spla.spsolve(B,Load) # We return [p,t,U] return p,t,U
def neumann(h0, f, n): # First lets generate the uniform mesh for this mesh width mesh = msh.grid_square(1, h0) # Matrix of nodes p = mesh[0] # Matrix of triangles index t = mesh[1] # Now lets compute the stiffness matrix Stiff = fem.stiffness(p, t) # Now lets compute the mass matrix Mass = fem.mass(p, t) # Lets compute the load vector Load = fem.load(p, t, n, f) # The complete matrix for the bilinear form is given by the sum of #the stiffness and the mass B = Stiff + Mass # Now lets get the solution of the linear system using spsolve function U = spla.spsolve(B, Load) # We return [p,t,U] return p, t, U
def read(self): if not os.path.isfile(self.__filename): raise ValueError("Given file does not exist %f", self.__filename) node_dic = self.__read_node() elem_dic = self.__read_element(node_dic) materials = self.__read_material() elem_sets = self.__read_element_sets(elem_dic) solid_sections = self.__read_solid_section(materials, elem_sets) fe_body = FEM.Body(1, node_dic, elem_dic, solid_sections) return fe_body
def UNV2411Reader(f, fem): while True: line1 = f.readline() line2 = f.readline().strip() if len(line2) and not line1.startswith(FLAG): dataline = Line2Int(line1) line2 = line2.replace('D', 'E') # replacement is inserted by Prool coords = Line2Float(line2) n = FEM.Node(dataline[0], coords) fem.nodes.append(n) else: break logging.info('{} nodes'.format(len(fem.nodes))) return fem
def dirichlet_homogeneous(h0,f,n): # First lets generate the uniform mesh for this mesh width mesh=msh.grid_square(1,h0) # Matrix of nodes p=mesh[0] # Matrix of triangles index t=mesh[1] # Matrix of border element index be=mesh[2] #Lets get the interior nodes in the mesh innod=fem.interiorNodes(p,t,be) # Rewrite the innod to match with indices beginning at 0 innod=[i-1 for i in innod] # Now lets compute the stiffness matrix Stiff=fem.stiffness(p,t) # Now lets compute the mass matrix Mass=fem.mass(p,t) # Lets compute the load vector Load=fem.load(p,t,n,f) # The complete matrix for the bilinear form is given by the sum of #the stiffness and the mass B=Stiff+Mass # Now lets initialize the array in zeros to respect the homogeneous # Dirichlet boundary conditions U=np.zeros(len(p)) # Lets take just the interior points in the matrix B and the Load vector Bint=B[innod][:,innod] Loadint=Load[innod] # Now lets get the solution of the linear system of the interior points # using spsolve function Uint=spla.spsolve(Bint,Loadint) # Finally we put them in the correspondence interior points of the complete # solution U[innod]=Uint # We return [p,t,U] return p,t,U
def dirichlet_homogeneous(h0, f, n): # First lets generate the uniform mesh for this mesh width mesh = msh.grid_square(1, h0) # Matrix of nodes p = mesh[0] # Matrix of triangles index t = mesh[1] # Matrix of border element index be = mesh[2] #Lets get the interior nodes in the mesh innod = fem.interiorNodes(p, t, be) # Rewrite the innod to match with indices beginning at 0 innod = [i - 1 for i in innod] # Now lets compute the stiffness matrix Stiff = fem.stiffness(p, t) # Now lets compute the mass matrix Mass = fem.mass(p, t) # Lets compute the load vector Load = fem.load(p, t, n, f) # The complete matrix for the bilinear form is given by the sum of #the stiffness and the mass B = Stiff + Mass # Now lets initialize the array in zeros to respect the homogeneous # Dirichlet boundary conditions U = np.zeros(len(p)) # Lets take just the interior points in the matrix B and the Load vector Bint = B[innod][:, innod] Loadint = Load[innod] # Now lets get the solution of the linear system of the interior points # using spsolve function Uint = spla.spsolve(Bint, Loadint) # Finally we put them in the correspondence interior points of the complete # solution U[innod] = Uint # We return [p,t,U] return p, t, U
def no_homogen(h0, f, n, g): # First lets generate the mesh for the unite circle mesh_gen(h0) mesh = msh.read_gmsh('circle.msh') # Matrix of nodes p = mesh[0] # Matrix of triangles index t = mesh[1] # Matrix of boundary edges be = mesh[2] # Now lets compute the stiffness matrix A = fem.stiffness(p, t) # Lets compute the load vector Load = fem.load(p, t, n, f) # Lets compute the load neumann vector Loadneumann = fem.loadNeumann(p, be, n, g) #Finally the Loadvector will be the sum of the one with the source f # and the one with f Load = Load + Loadneumann # Lets compute the vector m that analogous to the load vector # with f(x.y)=1 m = fem.load(p, t, n, lambda x, y: 1) # Lets create the matrix and vectors of the modified bigger system to # solve with lagrangian multipliers of size (size(A)+(1,1)) size = A.shape[0] B = sparse.lil_matrix(np.zeros([size + 1, size + 1])) B[0:size, 0:size] = A B[0:size, size] = m B[size, 0:size] = m.transpose() # We add a zero at the end of f Load = np.concatenate((Load, np.array([[0]]))) # Now lets get the solution of the linear system using spsolve function U = spla.spsolve(B, Load) u = U[0:size] l = U[size] return [p, t, u, l]
def no_homogen(h0,f,n,g): # First lets generate the mesh for the unite circle mesh_gen(h0) mesh=msh.read_gmsh('circle.msh') # Matrix of nodes p=mesh[0] # Matrix of triangles index t=mesh[1] # Matrix of boundary edges be=mesh[2] # Now lets compute the stiffness matrix A=fem.stiffness(p,t) # Lets compute the load vector Load=fem.load(p,t,n,f) # Lets compute the load neumann vector Loadneumann=fem.loadNeumann(p,be,n,g) #Finally the Loadvector will be the sum of the one with the source f # and the one with f Load=Load+Loadneumann # Lets compute the vector m that analogous to the load vector # with f(x.y)=1 m=fem.load(p,t,n,lambda x,y:1) # Lets create the matrix and vectors of the modified bigger system to # solve with lagrangian multipliers of size (size(A)+(1,1)) size=A.shape[0] B=sparse.lil_matrix(np.zeros([size+1,size+1])) B[0:size,0:size]=A B[0:size,size]=m B[size,0:size]=m.transpose() # We add a zero at the end of f Load=np.concatenate((Load,np.array([[0]]))) # Now lets get the solution of the linear system using spsolve function U=spla.spsolve(B,Load) u=U[0:size] l=U[size] return [p,t,u,l]
def elemLoad(p, n, f): import FEM as FEM fK = zeros((3,1)) Phi = np.array([p[1]-p[0], p[2]-p[0]]) [x, w] = FEM.gaussTriangle(n) z = [] for i in range(len(x)): shifted = list(map(lambda x: (x+1)/2,x[i])) z.append(shifted) for i in range(3): for j in range(len(x)): ab = [0,0] ab[0] = Phi[0].dot(z[j]) ab[1] = Phi[1].dot(z[j]) fK[i] = fK[i] + 1/4*w[j]*f(ab[0],ab[1])*N(z[j],i) return fK
def elemLoad(p, n, f): fK = zeros((3,1)) # p=np.array(p) # Phi = np.zeros((2,2)) # Phi[:,0]=p[1,:]-p[0,:] # Phi[:,1]=p[2,:]-p[0,:] # Phi = np.array([p[1]-p[0], p[2]-p[0]]) Phi = np.column_stack((p[1]-p[0],p[2]-p[0])) [x, w] = FEM.gaussTriangle(n) z = [] for i in range(len(x)): shifted = list(map(lambda x: (x+1)/2,x[i])) z.append(shifted) for i in range(3): for j in range(len(x)): ab = [0,0] ab[0] = Phi[0].dot(z[j])+p[0][0] ab[1] = Phi[1].dot(z[j])+p[0][1] fK[i] = fK[i] + det(Phi)*w[j]*f(ab[0],ab[1])*N(z[j],i)/4 return fK
def error_energy(h0): # First lets compute the discrite solution Sol=neum.neumann(h0,f,n) p=Sol[0] t=Sol[1] un=Sol[2] # Lets get the vector load vector # We need to transpose it to get do the inne producto with un fn=np.array([f(pi[0],pi[1]) for pi in p]) fn=fem.load(p,t,n,f) fn=np.transpose(fn)[0] # For this source f and the analytic solution the first part of the # discretization error related with the load vector evaluated on # analytic solution will be lu=1./4+2*np.pi**2 # The part related to the approximate soluiton will be the innerproduct # of fn and pn lun=un.dot(fn) #finally the discretiazaion error in the energy norm return np.sqrt(lu-lun)
def error_energyP2(h0): # First lets compute the discrite solution Sol=neumP2.neumannP2(h0,f,n) p=Sol[0] t=Sol[1] un=Sol[2] # Lets get the vector load vector # We need to transpose it to get do the inne producto with un fn=np.array([f(pi[0],pi[1]) for pi in p]) fn=fem.load(p,t,n,f) fn=np.transpose(fn)[0] # For this source f and the analytic solution the first part of the # discretization error related with the load vector evaluated on # analytic solution will be lu=1./4+2*np.pi**2 # The part related to the approximate soluiton will be the innerproduct # of fn and pn lun=un.dot(fn) #finally the discretiazaion error in the energy norm return np.sqrt(lu-lun)
def __read_element(self, node_dic): i_file = open(self.__filename, "r") elem_dic = {} read_element = False for line in i_file: line = line[0:-1] # Coments and line does not exist if len(line) == 0: continue elif len(line) >= 2: if line[0:1] == "**": continue # Stop reading if line[0] == "*": read_element = False if read_element: words = line.split(", ") first_word = True node_list = [] for word in words: if first_word: elem_id = int(word) first_word = False else: node_list.append(node_dic[int(word)]) elem_dic[elem_id] = FEM.Element(elem_id, node_list) # Check if node key is found and not *NODE PRINT ... if "*ELEMENT" in line.upper(): words = line.split(",") for word in words: new_word = word.split(" ") for word_no_space in new_word: if word_no_space.upper() == "*ELEMENT": read_element = True return elem_dic
def __read_node(self): i_file = open(self.__filename, "r") node_dic = {} read_node = False for line in i_file: line = line[0:-1] # Coments and line does not exist if len(line) == 0: continue elif len(line) >= 2: if line[0:1] == "**": continue # Stop reading if line[0] == "*": read_node = False if read_node: words = line.split(", ") node_dic[int(words[0])] = FEM.Node(int(words[0]), float(words[1]), float(words[2]), float(words[3])) # Check if node key is found and not *NODE PRINT ... if "*NODE" in line.upper(): words = line.split(",") for word in words: word_no_space = word.split(" ") for word2 in word_no_space: if word2.upper() == "*NODE": read_node = True if "FILE" in word2.upper(): read_node = False if "PRINT" in word2.upper(): read_node = False return node_dic
def UNV2412Reader(f, fem): SpecialElemTypes = [11] # types of elements which are defined on 3 lines while True: line1 = f.readline() line2 = f.readline().strip() if len(line2) and not line1.startswith(FLAG): dataline = Line2Int(line1) etype = dataline[1] nnodes = dataline[-1] if etype < 33: # 1D elements have an additionnal line in definition nodes = Line2Int(f.readline()) else: # Standard elements have connectivities on secnd line nodes = Line2Int(line2) while nnodes > 8: nodes.extend(Line2Int(f.readline())) nnodes -= 8 e = FEM.Element(dataline[0], etype, nodes) fem.elements.append(e) else: break logging.info('{} elements'.format(len(fem.elements))) return fem
def main(h0, n): p, t, be = mesh.grid_square(2, h0) # shift mesh to origin# h = mesh.max_mesh_width(p, t) IN = fem.interiorNodes(p, t, be) S = fem.stiffness(p, t) M = fem.mass(p, t) L = fem.load(p, t, n, lambda x, y: 1) S = S.tocsr() M = M.tocsr() L = L.tocsr() # neumannnodes N = np.zeros(len(p)) j = 0 for i in range(0, len(p)): if p[i, 0] == 0 or p[i, 0] == 2: if 2 > p[i, 1] and p[i, 1] >= 1: N[j] = i j = j + 1 if p[i, 1] == 2: N[j] = i j = j + 1 j = j - 1 # number of neumannnodes print(N) Sr = sp.csr_matrix((len(IN) + j, len(IN) + j)) Mr = sp.csr_matrix((len(IN) + j, len(IN) + j)) Lr = sp.csr_matrix((len(IN) + j, 1)) A = sp.csr_matrix((len(IN) + j, len(p))) for i in range(0, len(IN)): A[i, IN[i]] = 1 for i in range(0, j): A[i + len(IN), N[i]] = 1 Sr = A * S * A.transpose() Mr = A * M * A.transpose() Lr = A * L un = spla.spsolve(Sr + Mr, Lr) u1 = A.transpose() * un fem.plot(p, t, u1)
def main(msh,n): p,t,be=mesh.read_gmsh(msh) h=mesh.max_mesh_width(p,t) IN=fem.interiorNodes(p,t,be) S=fem.stiffness(p,t) M=fem.mass(p,t) L=fem.load(p,t,n,lambda x,y:1) S=S.tocsr() M=M.tocsr() L=L.tocsr() #neumannnodes N=np.zeros(len(p)) j=0 for i in range (0,len(p)): if (p[i,0]==-1 or p[i,0]==1): if 1>p[i,1] and p[i,1]>=0: N[j]=i j=j+1 if p[i,1]==1: N[j]=i j=j+1 j=j-1 #number of neumannnodes Sr=sp.csr_matrix((len(IN)+j,len(IN)+j)) #adjusting solution to boundary condition Mr=sp.csr_matrix((len(IN)+j,len(IN)+j)) Lr=sp.csr_matrix((len(IN)+j,1)) A=sp.csr_matrix((len(IN)+j,len(p))) for i in range(0,len(IN)): A[i,IN[i]]=1 for i in range(0,j): A[i+len(IN),N[i]]=1 Sr=A*S*A.transpose() Mr=A*M*A.transpose() Lr=A*L un=spla.spsolve(Sr+Mr,Lr) u1=A.transpose()*un fem.plot(p,t,u1)
import numpy.linalg as la import scipy.sparse as sparse from scipy.sparse.linalg import spsolve import meshes as msh import FEM h0 = 0.1 qo = 1 u = lambda x,y: sin(pi*x)*sin(pi*y) f = lambda x,y: (2*pi*pi+1)*u(x,y) [p,t]=msh.square(1,h0) A=FEM.stiffness(p,t).tocsr() M=FEM.mass(p,t).tocsr() F=FEM.load(p,t,qo,f) IN = FEM.interiorNodes(p,t) T0 = sparse.lil_matrix((len(p),len(IN))) for j in range(len(IN)): T0[IN[j],j] = 1 T0t = T0.transpose() T0 = T0.tocsr() T0t = T0t.tocsr() A0 = T0t.dot(A.dot(T0)) M0 = T0t.dot(M.dot(T0)) F0 = T0t.dot(F) U0 = spsolve(A0+M0,F0) Un = T0.dot(U0)
# Try the quad mesh with Q1 elements: if True: import poisson_optimized as poisson # import poisson pts, quads, tri = create_mesh.quad_rectangle(0, 1, 0, 1, 21, 21) bc_nodes = set_bc_nodes_square(pts) # forcing term at mesh nodes f_pts = f(pts) # Dirichlet boundary conditions at *all* mesh nodes (most of these values are not used) u_bc_pts = u_bc(pts) # Set up the system and solve: tic = time.clock() A, b = poisson.poisson(pts, quads, bc_nodes, f_pts, u_bc_pts, FEM.Q1Aligned, FEM.GaussQuad2x2()) toc = time.clock() print "Matrix assembly took %f s" % (toc - tic) if pts.shape[0] < 50: print "cond(A) = %3.3f" % np.linalg.cond(A.todense()) tic = time.clock() x = spsolve(A.tocsr(), b) toc = time.clock() print "Sparse solve took %f s" % (toc - tic) # Plot: plt.figure() plot_mesh.plot_mesh(pts, quads) plt.figure()
) else: conRate[probNum][meshNum].append([float('nan')]) print "printing plots" #create plots -> the 3d plots will be gif images which #rotate the figure for better viewing angles = [] fignames = ["",""] for probNum in range(len(femsol)): if(probNum == 1): angles = np.linspace(0,360,21)[:-1] # Take 20 angles between 0 and 360 for meshNum in range(len(meshSz[probNum])): for polyNum in range(len(poly[probNum])): ax = FEM.pltSoln(femsol[probNum][meshNum][polyNum]) nameStr = "outputs/prob%d_%d_%d"%(probNum+1,meshSz[probNum][meshNum],poly[probNum][polyNum]) #save the plots if(probNum == 0): plt.savefig(nameStr + ".png") fignames[probNum] += nameStr + ".png\n" elif(probNum == 1): plt.savefig(nameStr + ".png") anim.rotanimate(ax, angles,nameStr + '.gif',delay=20) fignames[probNum] += nameStr + ".png, " + nameStr + ".gif\n" print #Writing output with open("outputs/proj1Results.txt",'w') as f: f.write("MA5629\nProject 1\nPeter Solfest\n\n") f.write("=================================\n\n")
from IPython import get_ipython get_ipython().magic('reset -sf') import numpy as np import numpy.matlib import meshing import Grid import auxiliary import FEM import plot import matplotlib.pyplot as plt aux = auxiliary.AuxiFu() discre = FEM.Discretization() boucon = FEM.SetupModel() solution = FEM.PostProcessing() thick = 25E-3 young = 15 * 10**9 poisson = 0.21 material = young / (1 - poisson**2) * np.array( ([[1, poisson, 0], [poisson, 1, 0], [0, 0, (1 - poisson) / 2]])) * thick k = (3 - poisson) / (1 + poisson) KIC = 2 * 1E6 fy = 1E6 fy0 = 0.01 * fy p, t = meshing.gmshpy(open('Mesh_circle_45.msh')) p, t, nodaro, tipcra, moucra, roscra, nodcra, iniang, dc, aremin, lmin, R = meshing.reprocessing( p, t, 1, 'circle crack') lmin = lmin * 1.5 aremin = lmin**2 * np.sqrt(3) / 4
return np.cos(np.pi*x)*np.cos(np.pi*y)*(1+2*np.power(np.pi,2)) # # calculating the system to solve # print("[Calculating the system Bu = l]") cStiff = lfem.stiffness(p,t) cMass = lfem.mass(p,t) B = cMass+cStiff l = lfem.load(p, t, n, f) # # Solving the system # print("[Solving the system Bu = l]") bn = lfem.boundaryNodes(p,t) In = lfem.interiorNodes(p,t) solution = np.zeros((B.shape[0])) l = np.delete(l,bn,0) T = np.eye(B.shape[0]) T = np.delete(T,bn,0) T = csr_matrix(T) B_new = T.dot(B).dot(T.transpose()) u = spsolve(B_new,l) for i in range(len(u)): solution[In[i]] = u[i] # # plotting the solution # print("[Plotting solution u(x1,x2)]") FEM.plot(p, t, solution)
# solution U[innod] = Uint # Finally we sum up the two solutions to get the final solution u = U + ug # We return [p,t,U] return p, t, u # Now lets get the solution u=sin(pi*x)sin(pi*y) that gives a source # function f(x,y)=(2pi^2+1)sin(pi*x)sin(pi*y) # Lets define first the function f f = lambda x1, x2: 0 # Lets define the function g = lambda x1, x2: x1 + x2 # The closest value of h0 to 1 to be able to generate a regular h0 = np.sqrt(2) / 14 n = 3 # Lets get the solution Sol = dirichlet_nonhomogeneous(h0, f, g, n) p = Sol[0] t = Sol[1] u = Sol[2] # Change the t to put the value 1 to zero to be able to plot with the # function in the FEM module t = np.array([list(ti - 1) for ti in t]) # Lets finally generate the plot fem.plot(p, t, u, "fem_dirichnonhom.png", "FEM dirichlet nonhomogeneous solution")
h0 = 0.1 qo = 1 u = lambda x, y: cos(2 * pi * x) * cos(2 * pi * y) f = lambda x, y: (8 * pi * pi + 1) * u(x, y) [p, t] = msh.square(1, h0) # r = lambda x,y: sqrt(x*x+y*y) # u = lambda x,y: cos(2*pi*r(x,y)) # f = lambda x,y: (4*pi*pi+1)*u(x,y)+2*pi/r(x,y)*sin(2*pi*r(x,y)) # def r(x,y): # return sqrt(x*x+y*y) # def u(x,y): # return cos(2*pi*r(x,y)) # def f(x,y): # return (4*pi*pi+1)*u(x,y)+2*pi/r(x,y)*sin(2*pi*r(x,y)) # [p,t]=msh.circle(1,h0,1) A = FEM.stiffness(p, t).tocsr() M = FEM.mass(p, t).tocsr() F = FEM.load(p, t, qo, f) Un = spsolve(A + M, F) FEM.plot(p, t, Un) U = np.zeros((p.shape[0])) for i in range(0, p.shape[0]): U[i] = u(p[i, 0], p[i, 1]) FEM.plot(p, t, U - Un)
import numpy as np from numpy.linalg import pinv import FEM as fem fem.main() fem.force_stiff(x, 1)
count +=1; # Now, label the Dirichlet-inner nodes properly num_inner_points = N-count; IN = [None]*(num_inner_points); # list of interior indices count = 0; for i in range(0,N): # labelling indices of interior nodes if (insideflags[i][0]): IN[count] = i; count += 1; if count!=num_inner_points: error('Number of Dirichlet-inner nodes missmatch'); ndof[k] = num_inner_points; # there are as many degrees of freedom as inner nodes # ---------------- assemble algebraic problem ------------------------------ # Computing the discretized system: A = FEM.stiffness(p, t); # stiffness-matrix #M = FEM.mass(p, t); # mass-matrix F = FEM.load(p, t, n, f); # load-vector # Assembling the reduced system: Ared = sp.lil_matrix((num_inner_points, num_inner_points)); #Mred = sp.lil_matrix((num_inner_points, num_inner_points)); Fred = np.zeros((num_inner_points, 1)); for i in range(0, num_inner_points): for j in range(0, num_inner_points): Ared[i,j] = A[IN[i], IN[j]]; # reduced stiffness matrix #Mred[i,j] = M[IN[i], IN[j]]; # reduced mass matrix Fred[i] = F[IN[i]]; # reduced RHS # --------------------- solve algebraic problem ----------------------------- # Solving the reduced system (Ared + Mred)ured = Fred:
# The closest value of h0 to 1 to be able to generate a regular h0 = np.sqrt(2) / 14 n = 3 # Lets get the solution Sol = neumann(h0, f, n) p = Sol[0] t = Sol[1] u = Sol[2] #Change the t to put the value 1 to zero to be able to plot with the # function in the FEM module t = np.array([list(ti - 1) for ti in t]) #Now lets define the exact solution as a function def uexact(x1, x2): return np.cos(2 * np.pi * x1) * np.cos(2 * np.pi * x2) #Lets get a np.array of the exact solution evaluated in each Uexact = np.array([uexact(pi[0], pi[1]) for pi in p]) # Lets generate the plot of both fem.plot(p, t, u, "fem_neumann.png", "FEM neumann solution") fem.plot(p, t, Uexact, "exact_neumann.png", "Exact neumann solution") # Lets get the discretization error and plot it error = Uexact - u fem.plot(p, t, error, "error_neumann.png", "Discretization nuemann error")
from numpy import pi #import numpy.linalg as la import scipy.sparse as sparse from scipy.sparse.linalg import spsolve import meshes as msh import FEM h0 = 0.1 qo = 3 u = lambda x,y: cos(pi*x)*cos(pi*y) f = lambda x,y: 2.0*pi*pi*u(x,y) m = lambda x,y: 1.0 [p,t]=msh.square(1,h0) A=FEM.stiffness(p,t).tocsr() F=FEM.load(p,t,qo,f) M=sparse.lil_matrix(FEM.load(p,t,1,m)) S=sparse.bmat([[A, M.transpose()], [M, None]]).tocsr() F=np.hstack([F,0.0]) U_n=spsolve(S,F) lambda_n=U_n[-1] print "lambda", lambda_n FEM.plot(p,t,U_n[0:-1]) U=np.zeros((p.shape[0])) for i in range(0,p.shape[0]): U[i]=u(p[i,0],p[i,1]) FEM.plot(p,t,U-U_n[0:-1])
num_inner_points = N - count IN = [None] * (num_inner_points) # list of interior indices count = 0 for i in range(0, N): # labelling indices of interior nodes if insideflags[i][0]: IN[count] = i count += 1 if count != num_inner_points: error("Number of Dirichlet-inner nodes missmatch") ndof[k] = num_inner_points # there are as many degrees of freedom as inner nodes # ---------------- assemble algebraic problem ------------------------------ # Computing the discretized system: A = FEM.stiffness(p, t) # stiffness-matrix # M = FEM.mass(p, t); # mass-matrix F = FEM.load(p, t, n, f) # load-vector # Assembling the reduced system: Ared = sp.lil_matrix((num_inner_points, num_inner_points)) # Mred = sp.lil_matrix((num_inner_points, num_inner_points)); Fred = np.zeros((num_inner_points, 1)) for i in range(0, num_inner_points): for j in range(0, num_inner_points): Ared[i, j] = A[IN[i], IN[j]] # reduced stiffness matrix # Mred[i,j] = M[IN[i], IN[j]]; # reduced mass matrix Fred[i] = F[IN[i]]
Sol = homogen(h0, f, n) p = Sol[0] t = Sol[1] u = Sol[2] l = Sol[3] #Change the t to put the value 1 to zero to be able to plot with the # function in the FEM module t = np.array([list(ti - 1) for ti in t]) #Now lets define the exact solution as a function def uexact(x1, x2): return np.cos(np.pi * x1) * np.cos(np.pi * x2) #Lets get a np.array of the exact solution evaluated in each Uexact = np.array([uexact(pi[0], pi[1]) for pi in p]) # Lets generate the plot of both fem.plot(p, t, u, "fem_homogen.png", "FEM homogeneous solution") fem.plot(p, t, Uexact, "exact_homogen.png", "Exact homogeneous solution") # Lets get the discretization error and plot it error = Uexact - u fem.plot(p, t, error, "error_homogen.png", "Discretization homogeneous error") # Is also noticable that l=1.5075455299440885e-05 that is approximately # zero which is the exact value of lambda with g=0
h0=np.sqrt(2)/14 n=3 # Lets get the solution Sol=neumann(h0,f,n) p=Sol[0] t=Sol[1] u=Sol[2] #Change the t to put the value 1 to zero to be able to plot with the # function in the FEM module t=np.array([list(ti-1) for ti in t]) #Now lets define the exact solution as a function def uexact(x1,x2): return np.cos(2*np.pi*x1)*np.cos(2*np.pi*x2) #Lets get a np.array of the exact solution evaluated in each Uexact=np.array([uexact(pi[0],pi[1]) for pi in p]) # Lets generate the plot of both fem.plot(p,t,u,"fem_neumann.png","FEM neumann solution") fem.plot(p,t,Uexact,"exact_neumann.png","Exact neumann solution") # Lets get the discretization error and plot it error=Uexact-u fem.plot(p,t,error,"error_neumann.png","Discretization nuemann error")
def __init__(self, filename): self.file = None self.filename = filename self.FEM = FEM() self.ElementConfiguration = self.setupElements()
def main(): # 'linear;, 'quadratic' or 'cubic' elementType = 'cubic' # '2pt','3pt', '4pt' quadratureRule = '4pt' # meshType = 'uniform' or 'adaptive' meshType = 'uniform' # FIXME: generalize later numAtoms = 1 if(numAtoms == 1): # define number of elements numberElements = 52 # define domain size in 1D domainStart = -17.5 domainEnd = 17.5 #define parameters for adaptive Mesh innerDomainSize = 8 innerMeshSize = 0.25 #read the external potental from matlab if(meshType == 'uniform'): pot = open('vpotOneAtomUniform52Elem.txt','r') else : pot = open('vpotOneAtomAdaptive52Elem.txt','r') else: # define number of elements numberElements = 84 # define domain size in 1D domainStart = -17.5 domainEnd = 17.5 #define parameters for adaptive Mesh innerDomainSize = 16 innerMeshSize = 0.25 #read the external potental from matlab if(meshType =='uniform'): pot = open('vpot14AtomUniform84Elem.txt','r') else : pot = open('vpot14AtomAdaptive84Elem.txt','r') # create FEM object fem=FEM.FEM(numberElements, quadratureRule, elementType, domainStart, domainEnd, innerDomainSize, innerMeshSize, meshType) # mesh the domain in 1D globalNodalCoordinates = fem.generateNodes() # generate Adaptive Mesh numberNodes = fem.numberNodes #get number quadrature points numberQuadraturePoints = fem.getNumberQuadPointsPerElement() totalnumberQuadraturePoints = numberElements*numberQuadraturePoints v= [] for line in pot: v.append(float(line)) v = np.array(v) data= np.reshape(v,(totalnumberQuadraturePoints,totalnumberQuadraturePoints,totalnumberQuadraturePoints)) # reducedRank rankVeff = 5 reducedRank = (rankVeff, rankVeff, rankVeff) #perform tensor decomposition of effective potential time_tensorStart = time.clock() #convert to a tensor fTensor = tensor.tensor(data) [a,b] = DTA.DTA(fTensor,reducedRank) time_tensorEnd = time.clock() print 'time elapsed for tensor decomposition of Veff (s)',time_tensorEnd-time_tensorStart sigma_core = a.core sigma = sigma_core.tondarray() umat = a.u[0].real vmat = a.u[1].real wmat = a.u[2].real sigma = sigma.real sigma2D = sigma.reshape((rankVeff**2,rankVeff)) # done to reduce cost while contracting functional = FunctionalRayleighQuotientSeparable.FEMFunctional(fem, rankVeff, sigma2D, [umat,vmat,wmat]) # initial guess for psix, psiy, psiz xx = globalNodalCoordinates yy = xx.copy() zz = xx.copy() X, Y, Z = meshgrid2(xx,yy,zz) psixyz = (1/np.sqrt(np.pi))*np.exp(-np.sqrt(X**2 + Y**2 + Z**2)) igTensor = tensor.tensor(psixyz) # generate tensor decomposition of above guess of rank 1 time_tensorStart = time.clock() rankIG = (1,1,1) [Psi,Xi] = DTA.DTA(igTensor,rankIG) time_tensorEnd = time.clock() print 'time elapsed(s) for DTA of initial guess',time_tensorEnd-time_tensorStart guessPsix = Psi.u[0].real guessPsiy = Psi.u[1].real guessPsiz = Psi.u[2].real guessLM = 0.2 guessFields = np.concatenate((guessPsix[1:-1],guessPsiy[1:-1],guessPsiz[1:-1])) #append the initial guess for lagrange multiplier guessFields = np.append(guessFields,guessLM) petsc = True if (petsc == False): t0 = time.clock() print 'Method fsolve' [result,infodict,ier,mesg] = scipy.optimize.fsolve(residual,guessFields,args=(functional),full_output=1,xtol=1.0e-8,maxfev=20000) print 'Number of Function Evaluations: ',infodict['nfev'] print 'Ground State Energy: ',result[-1] print 'numberElements ',numberElements print mesg t1 = time.clock() print 'time elapsed(s) for minimization problem',t1-t0 else: t0 = time.clock() snes = PETSc.SNES().create() pde = SeparableHamiltonian(functional) n = len(guessFields) F = PETSc.Vec().createSeq(n) snes.setFunction(pde.residualPetsc,F) snes.setUseMF() snes.getKSP().setType('gmres') snes.setFromOptions() X = PETSc.Vec().createSeq(n) pde.formInitGuess(snes, X,guessFields) snes.solve(None, X) print X[n-1] t1 = time.clock() print 'time elapsed(s) for minimization problem',t1-t0 result = pde.copySolution(X,guessFields)
discret_err_lin = [None]*Nspacings; # vector for discretization errors for linear FEM discret_err_quad = [None]*Nspacings; # vector for discretization errors for quadratic FEM for j in range(0,Nspacings): # Maximal mesh width h0 of the grid: h[j] = h0*2.0**(-j/2.0); # Mesh generation: [p,t]=msh.square(q0,h[j]) # determine actual max. mesh width mmw[j] = msh.max_mesh_width(p,t); # LINEAR FINITE ELEMENTS # Compute the discretized system: A_lin = FEM.stiffness(p, t); # stiffness-matrix M_lin = FEM.mass(p, t); # mass-matrix F_lin = FEM.load(p, t, 3, f); # load-vector # Solve the discretized system (A + M)u = F: A_lin = A_lin.tocsr(); # conversion from lil to csr format M_lin = M_lin.tocsr(); u_lin = spsolve(A_lin + M_lin, F_lin); eIndex = msh.edgeIndex(p,t) N = p.shape[0]; # Computing the discretized system: A = FEM.stiffnessP2(p,t,eIndex) M = FEM.massP2(p,t,eIndex) F = FEM.loadP2(p,t,eIndex,f,3)
#Lets define first the function f f= lambda x1,x2: (2*(np.pi**2)+1)*np.sin(np.pi*x1)*np.sin(np.pi*x2) # The closest value of h0 to 1 to be able to generate a regular h0=np.sqrt(2)/14 n=3 # Lets get the solution Sol=dirichlet_homogeneous(h0,f,n) p=Sol[0] t=Sol[1] u=Sol[2] #Change the t to put the value 1 to zero to be able to plot with the # function in the FEM module t=np.array([list(ti-1) for ti in t]) #Now lets define the exact solution as a function def uexact(x1,x2): return np.sin(np.pi*x1)*np.sin(np.pi*x2) #Lets get a np.array of the exact solution evaluated in each Uexact=np.array([uexact(pi[0],pi[1]) for pi in p]) # Lets generate the plot of both fem.plot(p,t,u,"fem_dirichhom.png","FEM dirichlet homogeneous solution") fem.plot(p,t,Uexact,"exact_dirichhom.png","Exact dirichlet homogeneous solution") # Lets get the discretization error and plot it error=Uexact-u fem.plot(p,t,error,"error_dirichhom.png","Discretization homogeneous dirichleterror")
# scaling of time derivative dt /= 10 # FE mesh [coord,trian] = msh.square(1,h0) # analytical static limit solution uASL=np.zeros((coord.shape[0])) for i in range(0,coord.shape[0]): uASL[i]=u(coord[i,0],coord[i,1]) # l(u) lofu = (8*pi*pi+1)/4.0 # FE matrices and load vector A = FEM.stiffness(coord,trian) M = FEM.mass(coord,trian) F = FEM.load(coord,trian,qo,f) # time-stepping methods if theta > 0.0: S = (M+theta*dt*(A+M)).tocsr() U = np.zeros((coord.shape[0],n+1)) t = time() for i in range(1,n+1): U[:,i] = spla.spsolve(S,dt*(theta*ft[i]+(1.0-theta)*ft[i-1])*F+(M-dt*(1.0-theta)*(A+M))*U[:,i-1]) #print "t:", t[i], "norm of u:", la.norm(U[:,i]) print "time of spsolve: ", time()-t if not np.isfinite(U[:,-1]).all(): print "error of spsolve: inf"
import meshes as msh import FEM h0 = 0.5 qo = 1 u = lambda x,y: cos(2*pi*x)*cos(2*pi*y) f = lambda x,y: (8*pi*pi+1)*u(x,y) lu = (8*pi*pi+1)/4.0 n=10 error = np.zeros((n)) h = np.zeros((n)) for i in range(n): h[i]=h0*pow(2,-i/2.0) [p,t]=msh.square(1,h[i]) h[i]=msh.max_mesh_width(p,t) A=FEM.stiffness(p,t).tocsr() M=FEM.mass(p,t).tocsr() F=FEM.load(p,t,qo,f) Un=spsolve(A+M,F) error[i] = np.sqrt(lu-np.dot(Un,F)) if i>0: print "rate", (np.log(error[i-1])-np.log(error[i]))/(np.log(h[i-1])-np.log(h[i])) plt.loglog(h,error) plt.grid(True) plt.show()
meshSz = [[], []] poly = [[], []] meshSz[0] = [5 * 2**i for i in range(5)] meshSz[1] = [5 * 2**i for i in range(3, 4)] #meshSz[1] = [5*2**i for i in range(4)] poly[0] = range(1, 4) poly[1] = range(2, 3) #poly[1] = range(1,3) for probNum in range(len(femsol)): for meshNum in range(len(meshSz[probNum])): femsol[probNum].append([]) for polyNum in range(len(poly[probNum])): namestr = "prob%d_%d_%d.setup" % ( probNum + 1, meshSz[probNum][meshNum], poly[probNum][polyNum]) print "Problem " + namestr + " ..." femsol[probNum][meshNum].append(FEM.FEMcalc("setups/" + namestr)) print " solved" print "calculating l2 errors" #go through and calculate l2 errors and convergence rates exsol = [None, None] exsol[0] = lambda x: math.sin(x[0]) - math.sin(1) * x[0] exsol[1] = lambda x, y: femsol[1][-1][-1] #use best solution as exact solution l2err = [[], []] conRate = [[], []] for probNum in range(len(femsol)): for meshNum in range(len(meshSz[probNum])): l2err[probNum].append([]) conRate[probNum].append([]) for polyNum in range(len(poly[probNum])): l2err[probNum][meshNum].append(
#We gonna use maximal width h0=0.1 and order of quadrature n=3 h0=0.1 n=3 # Lets get the solution Sol=no_homogen(h0,f,n,g) p=Sol[0] t=Sol[1] u=Sol[2] l=Sol[3] #Change the t to put the value 1 to zero to be able to plot with the # function in the FEM module t=np.array([list(ti-1) for ti in t]) #Lets define the exact solution def uexact(x1,x2): r=np.sqrt(x1**2+x2**2) return x1*np.sin(np.pi*r) #Lets get a np.array of the exact solution evaluated in each Uexact=np.array([uexact(pi[0],pi[1]) for pi in p]) # Lets generate the plot of both fem.plot(p,t,u,"fem_non_homogen.png","FEM nonhomogeneous solution") fem.plot(p,t,Uexact,"exact_non_homogen.png","Exact nonhomogeneous solution") # Lets get the discretization error and plot it error=Uexact-u fem.plot(p,t,error,"error_non_homogen.png","Discretization non homogeneous error")
import meshes as msh import FEM h0 = 0.1 qo = 3 r = lambda x, y: sqrt(x * x + y * y) u = lambda x, y: x * sin(pi * r(x, y)) f = lambda x, y: pi * pi * u(x, y) - 3.0 * pi * (x / r(x, y)) * cos(pi * r(x, y)) g = lambda x, y: -pi * x m = lambda x, y: 1.0 [p, t] = msh.circle(1, h0, 1) be = FEM.boundaryEdges(p, t) A = FEM.stiffness(p, t).tocsr() F = FEM.load(p, t, qo, f) G = FEM.loadNeumann(p, be, qo, g) M = sparse.lil_matrix(FEM.load(p, t, 1, m)) S = sparse.bmat([[A, M.transpose()], [M, None]]).tocsr() F = np.hstack([F + G, 0.0]) U_n = spsolve(S, F) lambda_n = U_n[-1] print "lambda", lambda_n FEM.plot(p, t, U_n[0:-1]) U = np.zeros((p.shape[0])) for i in range(0, p.shape[0]): U[i] = u(p[i, 0], p[i, 1]) FEM.plot(p, t, U - U_n[0:-1])
def main(): lu = 1.548888; # value of l(sol) f = lambda x, y: (1.0); Nspacings = 9; # number of mesh widths to test (in powers of sqrt(2)) -> CHANGE BACK TO 10!!!! h0 = 0.3; # maximum value of mesh width h = [None]*Nspacings; # vector for mesh widths (set values) dof = np.zeros(Nspacings); # vector for mesh widths (true values) dof_reg = np.zeros(Nspacings); # vector for mesh widths (true values) discret_err_bgm = [None]*Nspacings; # vector for discretization errors for linear FEM discret_err_reg = [None]*Nspacings; # vector for discretization errors for quadratic FEM # regular mesh for j in range(Nspacings): h = h0*2.0**(-j/2.0); [p, t, be, bd]=msh.create_msh("regular", h) # LINEAR FINITE ELEMENTS # Compute the discretized system: A_lin = FEM.stiffness(p, t); # stiffness-matrix F_lin = FEM.load(p, t, 3, f); # load-vector # degrees of freedom dof_reg[j] = p.shape[0] # solve system with Dirichtlet boundary conditions u_n = FEM.solve_d0(p, t, bd, A_lin, F_lin) # LINEAR FINITE ELEMENTS lun_lin = np.dot(u_n,F_lin); # value of l(u_n) en_lin = lu-sqrt(abs(lun_lin)); # energy norm of error vector discret_err_reg[j] = en_lin; print print "energy error with the regular mesh" print discret_err_reg # background mesh for j in range(Nspacings): #[p, t, be, bd]=msh.create_msh_bgm("bgmesh"+str(j)) [p, t, be, bd]=msh.read_gmsh("bgmesh"+str(j)+".msh") # LINEAR FINITE ELEMENTS # Compute the discretized system: A_lin = FEM.stiffness(p, t); # stiffness-matrix F_lin = FEM.load(p, t, 3, f); # load-vector # degrees of freedom dof[j] = p.shape[0] # solve system with Dirichtlet boundary conditions u_n = FEM.solve_d0(p, t, bd, A_lin, F_lin) # LINEAR FINITE ELEMENTS lun_lin = np.dot(u_n,F_lin); # value of l(u_n) en_lin = lu-sqrt(abs(lun_lin)); # energy norm of error vector discret_err_bgm[j] = en_lin; print print "energy error with the background mesh" print discret_err_bgm # ploting energy error distribution plt.loglog(dof_reg, discret_err_reg,':*', label='energy error - regular mesh') plt.loglog(dof, discret_err_bgm,':*', label='energy error - bgm') plt.title('energy error depending on degrees of freedom') plt.legend(loc=1) plt.show() # Visualization of the solution FEM.plot(p, t, u_n); # approximated solution plt.show()
def f(x): res = b1 * fem.phi_start(x, x_grid) res += b2 * fem.phi_end(x, x_grid) for i in range(len(x_grid) - 2): res += p[i] * fem.phi(i, x, x_grid) return res
# time T=1! kappa=1 h0 = 0.15 qo = 3 theta = 0.0 T = 1 n = 1000 time = np.linspace(0.0,T,num=n+1) dt = T/float(n) u = lambda x,y: kappa*sin(pi*x)*sin(pi*y) f = lambda x,y: (2*pi*pi)*u(x,y) ft = 1.0-np.exp(-10*time) [p,t]=msh.square(1,h0) A=kappa*FEM.stiffness(p,t).tocsr() M=FEM.mass(p,t).tocsr() F=FEM.load(p,t,qo,f) IN = FEM.interiorNodes(p,t) T0 = sparse.lil_matrix((len(p),len(IN))) for j in range(len(IN)): T0[IN[j],j] = 1 T0t = T0.transpose() T0 = T0.tocsr() T0t = T0t.tocsr() A = T0t.dot(A.dot(T0)) M = T0t.dot(M.dot(T0)) F = T0t.dot(F) S = (M+theta*dt*A)
import meshes import FEM import time import scipy.sparse.linalg as spla meshwidth = 0.05 processes = 8 p,t=meshes.grid_square(1,meshwidth) timer=time.time() seqM=FEM.mass(p,t) seqTime=time.time()-timer timer=time.time() parM,processes=FEM.massParallel(p,t,processes) parTime=time.time()-timer print "difference of matrices: ", spla.onenormest(seqM-parM) print "time for sequential assembling:", seqTime print "time for parallel assembling: ", parTime print "speed-up: ", seqTime/parTime print "efficiency:", (seqTime/parTime)/processes
connectivity, boundaries_names, boundary_nodes, evolutionary_rate, minimum_density, \ penalty, minimum_area_ratio, minimum_density, filter_radius, plot_type, print_all, \ dpi, surface_type, boundary_type, boundary_value, thickness, young_module, poisson_ratio, \ use_parallelism, treads, nodes_dof, chuncksize = import_files() console_output.write('done\n') #plt.ioff() complete_start_time = time.time() print('Getting proprieties, this will take a while') console_output.write('Getting proprieties\n') print('Getting elements area') console_output.write('Getting elements area\n') start_time = time.time() areas = FEM.get_elements_area(x_nodes_coordinates, y_nodes_coordinates, connectivity) end_time = time.time() print('Process time: %f seconds' % (end_time - start_time)) console_output.write('Process time: %f seconds\n' % (end_time - start_time)) print('Getting elements centers') console_output.write('Getting elements centers\n') start_time = time.time() centers = FEM.get_elements_center(x_nodes_coordinates, y_nodes_coordinates, connectivity) end_time = time.time() print('Getting elements on filtering radius') console_output.write('Getting elements on filtering radius\n') start_time = time.time()
U[innod] = Uint # Finally we sum up the two solutions to get the final solution u = U + ug # We return [p,t,U] return p, t, u #Now lets get the solution u=sin(pi*x)sin(pi*y) that gives a source # function f(x,y)=(2pi^2+1)sin(pi*x)sin(pi*y) #Lets define first the function f f = lambda x1, x2: 0 #Lets define the function g = lambda x1, x2: x1 + x2 # The closest value of h0 to 1 to be able to generate a regular h0 = np.sqrt(2) / 14 n = 3 # Lets get the solution Sol = dirichlet_nonhomogeneous(h0, f, g, n) p = Sol[0] t = Sol[1] u = Sol[2] #Change the t to put the value 1 to zero to be able to plot with the # function in the FEM module t = np.array([list(ti - 1) for ti in t]) # Lets finally generate the plot fem.plot(p, t, u, "fem_dirichnonhom.png", "FEM dirichlet nonhomogeneous solution")
import numpy as np import math import auxiliary aux = auxiliary.AuxiFu() import FEM discre = FEM.Discretization() solution = FEM.PostProcessing() def norvec(p, nod): # compute tangential and norm vectors for each edge if nod.ndim == 1: boupoi = p[nod, :] tanedg = boupoi[1::] - boupoi[0:-1] lenedg = np.sqrt(np.sum(tanedg**2, axis=1)) noredg = np.copy(tanedg) noredg[:, 0] = tanedg[:, 1] / lenedg noredg[:, 1] = -tanedg[:, 0] / lenedg # compute norm vector for each point bounor = np.zeros(shape=(len(nod), 2)) bounor[0, :] = noredg[0, :] bounor[-1, :] = noredg[-1, :] bounor[1:-1:1, 0] = (noredg[0:-1, 0] * lenedg[0:-1] + noredg[1::, 0] * lenedg[1::]) / (lenedg[0:-1] + lenedg[1::]) bounor[1:-1:1, 1] = (noredg[0:-1, 1] * lenedg[0:-1] + noredg[1::, 1] * lenedg[1::]) / (lenedg[0:-1] + lenedg[1::]) elif nod.ndim == 2: slapoi = p[nod[:, 0], :]