def elem_write(self, mesh_name): meshfile = open(mesh_name, 'w') print('Writing ' + mesh_name + '.....') nelem = cubit.get_tri_count() print('number of elements:', str(nelem)) meshfile.write(str(nelem) + '\n') num_write = 0 temp_tri = [] for block, flag in zip(self.block_mat, self.block_flag): tris = cubit.get_block_tris(block) for tri in tris: nodes = cubit.get_connectivity('Tri', tri) temp_tri.append(tri) # txt=('%10i ')% tri # txt=txt+('%10i %10i %10i\n')% nodes[:] # meshfile.write(txt) temp_tri.sort() for tri in temp_tri: nodes = cubit.get_connectivity('Tri', tri) txt = ('%10i ') % tri txt = txt + ('%10i %10i %10i\n') % nodes[:] meshfile.write(txt) meshfile.close() print('Ok')
def save_elements_nodes(name, quads_fault_u, quads_fault_d): fault_file = open(name, 'w') txt = '' list_hex = cubit.parse_cubit_list('hex', 'all') txt = '%10i %10i\n' % (len(quads_fault_u), len(quads_fault_d)) fault_file.write(txt) dic_quads_fault_u = dict(zip(quads_fault_u, quads_fault_u)) dic_quads_fault_d = dict(zip(quads_fault_d, quads_fault_d)) # FAULT SIDE DOWN for h in list_hex: faces = cubit.get_sub_elements('hex', h, 2) for f in faces: if dic_quads_fault_d.has_key(f): nodes = cubit.get_connectivity('Face', f) # print 'h,fault nodes side down :',h,nodes[0],nodes[1],nodes[2],nodes[3] txt='%10i %10i %10i %10i %10i\n' % (h,nodes[0],\ nodes[1],nodes[2],nodes[3]) fault_file.write(txt) # FAULT SIDE UP for h in list_hex: faces = cubit.get_sub_elements('hex', h, 2) for f in faces: if dic_quads_fault_u.has_key(f): nodes = cubit.get_connectivity('Face', f) # print 'h,fault nodes side up :',h,nodes[0],nodes[1],nodes[2],nodes[3] txt='%10i %10i %10i %10i %10i\n' % (h,nodes[0],\ nodes[1],nodes[2],nodes[3]) fault_file.write(txt) fault_file.close()
def save_elements_nodes(name,quads_fault_u,quads_fault_d): fault_file = open(name,'w') txt ='' list_hex=cubit.parse_cubit_list('hex','all') txt='%10i %10i\n' % (len(quads_fault_u),len(quads_fault_d)) fault_file.write(txt) dic_quads_fault_u = dict(zip(quads_fault_u,quads_fault_u)) dic_quads_fault_d = dict(zip(quads_fault_d,quads_fault_d)) # FAULT SIDE DOWN for h in list_hex: faces = cubit.get_sub_elements('hex',h,2) for f in faces: if dic_quads_fault_d.has_key(f): nodes=cubit.get_connectivity('Face',f) # print 'h,fault nodes side down :',h,nodes[0],nodes[1],nodes[2],nodes[3] txt='%10i %10i %10i %10i %10i\n' % (h,nodes[0],\ nodes[1],nodes[2],nodes[3]) fault_file.write(txt) # FAULT SIDE UP for h in list_hex: faces = cubit.get_sub_elements('hex',h,2) for f in faces: if dic_quads_fault_u.has_key(f): nodes=cubit.get_connectivity('Face',f) # print 'h,fault nodes side up :',h,nodes[0],nodes[1],nodes[2],nodes[3] txt='%10i %10i %10i %10i %10i\n' % (h,nodes[0],\ nodes[1],nodes[2],nodes[3]) fault_file.write(txt) fault_file.close()
def axis_write(self, axis_name): """ Write axis on file """ cubit.cmd( 'set info off') # Turn off return messages from Cubit commands cubit.cmd('set echo off') # Turn off echo of Cubit commands cubit.cmd('set journal off') # Do not save journal file from sets import Set axisedge = open(axis_name, 'w') print 'Writing ' + axis_name + '.....' for block, flag in zip(self.block_bc, self.block_bc_flag): # For each 1D block if block == self.axisId: # If the block correspond to the axis edges_all = Set(cubit.get_block_edges( block)) # Import all axis edges id as a Set toWritetoFile = [""] * (len(edges_all) + 1) toWritetoFile[0] = '%10i\n' % len( edges_all) # Write the number of edges on the axis #axisedge.write('%10i\n' % len(edges_all)) # Write the number of edges on the axis print 'Number of edges on the axis :', len(edges_all) #id_element = 0 indexFile = 1 for block, flag in zip(self.block_mat, self.block_flag): # For each 2D block quads = cubit.get_block_faces(block) # Import quads id for quad in quads: # For each quad #id_element = id_element+1 # id of this quad edges = Set( cubit.get_sub_elements("face", quad, 1) ) # Get the lower dimension entities associated with a higher dimension entities. # Here it gets the 1D edges associates with the face of id "quad". Store it as a Set intersection = edges & edges_all # Contains the edges of the considered quad that are on the axis if len(intersection) != 0: # If this quad touch the axis nodes = cubit.get_connectivity( 'face', quad) # Import the nodes describing the quad nodes = self.jac_check( list(nodes)) # Check the jacobian of the quad for e in intersection: # For each edge on the axis node_edge = cubit.get_connectivity( 'edge', e) # Import the nodes describing the edge nodes_ok = [] for i in nodes: # Loop on the nodes of the quad if i in node_edge: # If this node is belonging to the axis nodes_ok.append(i) # Add it to nodes_ok txt = '%10i %10i %10i %10i\n' % (quad, 2, nodes_ok[0], nodes_ok[1]) #txt = '%10i %10i %10i %10i\n' % (id_element,2,nodes_ok[0],nodes_ok[1]) # Write the id of the quad, 2 (number of nodes describing a free surface elements), the nodes toWritetoFile[indexFile] = txt indexFile = indexFile + 1 #axisedge.write(txt) axisedge.writelines(toWritetoFile) axisedge.close() print 'Ok' cubit.cmd('set info on') # Turn on return messages from Cubit commands cubit.cmd('set echo on') # Turn on echo of Cubit commands
def forcing_write(self,forcname): """ Write forcing surfaces on file : forcname """ cubit.cmd('set info off') # Turn off return messages from Cubit commands cubit.cmd('set echo off') # Turn off echo of Cubit commands cubit.cmd('set journal off') # Do not save journal file from sets import Set forceedge = open(forcname,'w') print 'Writing '+forcname+'.....' edges_forc = [Set()]*self.nforc # edges_forc[0] will be a Set containing the nodes describing the forcing boundary # (index 0 : bottom, index 1 : right, index 2 : top, index 3 : left) nedges_all = 0 # To count the total number of forcing edges for block,flag in zip(self.block_bc,self.block_bc_flag): # For each 1D block for iforc in range(0, self.nforc): # iforc = 0,1,2,3 : for each forcing boundaries if block == self.forcing_boun[iforc]: # If the block considered correspond to the boundary edges_forc[iforc] = Set(cubit.get_block_edges(block)) # Store each edge on edges_forc nedges_all = nedges_all+len(edges_forc[iforc]) # add the number of edges to nedges_all toWritetoFile = [""]*(nedges_all+1) toWritetoFile[0] = '%10i\n' % nedges_all # Write the total number of forcing edges to the first line of file #forceedge.write('%10i\n' % nedges_all) # Write the total number of forcing edges to the first line of file print 'Number of edges', nedges_all #id_element = 0 indexFile = 1 for block,flag in zip(self.block_mat,self.block_flag): # For each 2D block quads = cubit.get_block_faces(block) # Import quads id for quad in quads: # For each quad #id_element = id_element+1 # id of this quad edges = Set(cubit.get_sub_elements("face", quad, 1)) # Get the lower dimension entities associated with a higher dimension entities. # Here it gets the 1D edges associates with the face of id "quad". Store it as a Set for iforc in range(0,self.nforc): # iforc = 0,1,2,3 : for each forcing boundaries intersection = edges & edges_forc[iforc] # Contains the edges of the considered quad that is on the forcing boundary considered if len(intersection) != 0: # If this quad touch the forcing boundary considered nodes = cubit.get_connectivity('face',quad) # Import the nodes describing the quad nodes = self.jac_check(list(nodes)) # Check the jacobian of the quad for e in intersection: # For each edge on the forcing boundary considered node_edge = cubit.get_connectivity('edge',e) # Import the nodes describing the edge nodes_ok = [] for i in nodes: # Loop on the nodes of the quad if i in node_edge: # If this node is belonging to forcing surface nodes_ok.append(i) # add it to nodes_ok # forcname contains 1/ element number, 2/ number of nodes that form the acoustic forcing edge # (which currently must always be equal to two, see comment below), # 3/ first node on the acforcing surface, 4/ second node on the acforcing surface # 5/ 1 = IBOTTOME, 2 = IRIGHT, 3 = ITOP, 4 = ILEFT #txt = '%10i %10i %10i %10i %10i\n' % (id_element,2,nodes_ok[0],nodes_ok[1],iforc+1) txt = '%10i %10i %10i %10i %10i\n' % (quad,2,nodes_ok[0],nodes_ok[1],iforc+1) # Write the id of the quad, 2 (number of nodes describing a free surface elements), the nodes and the type of boundary #print indexFile toWritetoFile[indexFile] = txt indexFile = indexFile + 1 #forceedge.write(txt) forceedge.writelines(toWritetoFile) forceedge.close() print 'Ok' cubit.cmd('set info on') # Turn on return messages from Cubit commands cubit.cmd('set echo on') # Turn on echo of Cubit commands
def abs_write(self,absname): """ Write absorbing surfaces on file : absname """ cubit.cmd('set info off') # Turn off return messages from Cubit commands cubit.cmd('set echo off') # Turn off echo of Cubit commands cubit.cmd('set journal off') # Do not save journal file. from sets import Set # if not absname: absname = self.absname absedge = open(absname,'w') print 'Writing '+absname+'.....' edges_abs = [Set()]*self.nabs # edges_abs[0] will be a Set containing the nodes describing bottom adsorbing boundary # (index 0 : bottom, index 1 : right, index 2 : top, index 3 : left) nedges_all = 0 # To count the total number of absorbing edges for block,flag in zip(self.block_bc,self.block_bc_flag): # For each 1D block for iabs in range(0, self.nabs): # iabs = 0,1,2,3 : for each absorbing boundaries if block == self.abs_boun[iabs]: # If the block considered correspond to the boundary edges_abs[iabs] = Set(cubit.get_block_edges(block)) # Store each edge on edges_abs nedges_all = nedges_all+len(edges_abs[iabs]); # add the number of edges to nedges_all toWritetoFile = [""]*(nedges_all+1) toWritetoFile[0] = '%10i\n' % nedges_all # Write the total number of absorbing edges to the first line of file #absedge.write('%10i\n' % nedges_all) # Write the total number of absorbing edges to the first line of file print 'Number of edges', nedges_all #id_element = 0 indexFile = 1 for block,flag in zip(self.block_mat,self.block_flag): # For each 2D block quads = cubit.get_block_faces(block) # Import quads id for quad in quads: # For each quad #id_element = id_element+1 # id of this quad edges = Set(cubit.get_sub_elements("face", quad, 1)) # Get the lower dimension entities associated with a higher dimension entities. # Here it gets the 1D edges associates with the face of id "quad". Store it as a Set for iabs in range(0,self.nabs): # iabs = 0,1,2,3 : for each absorbing boundaries intersection = edges & edges_abs[iabs] # Contains the edges of the considered quad that is on the absorbing boundary considered if len(intersection) != 0: # If this quad touch the absorbing boundary considered nodes = cubit.get_connectivity('face',quad) # Import the nodes describing the quad nodes = self.jac_check(list(nodes)) # Check the jacobian of the quad for e in intersection: # For each edge on the absorbing boundary considered node_edge = cubit.get_connectivity('edge',e) # Import the nodes describing the edge nodes_ok = [] for i in nodes: # Loop on the nodes of the quad if i in node_edge: # If this node is belonging to absorbing surface nodes_ok.append(i) # Add it to nodes_ok #txt = '%10i %10i %10i %10i %10i\n' % (id_element,2,nodes_ok[0],nodes_ok[1],iabs+1) txt = '%10i %10i %10i %10i %10i\n' % (quad,2,nodes_ok[0],nodes_ok[1],iabs+1) # Write the id of the quad, 2 (number of nodes describing a free surface elements), the nodes and the type of boundary toWritetoFile[indexFile] = txt indexFile = indexFile + 1 #absedge.write(txt) absedge.writelines(toWritetoFile) absedge.close() print 'Ok' cubit.cmd('set info on') # Turn on return messages from Cubit commands cubit.cmd('set echo on') # Turn on echo of Cubit commands
def curve2poly(line): curve=int(line) cubit.cmd('curve '+str(curve)+' size auto factor 1') cubit.cmd('mesh curve '+str(curve)) n=cubit.get_curve_nodes(curve) orientnode=[] vertex_list = cubit.get_relatives("curve", curve, "vertex") if len(vertex_list) != 0: startnode=cubit.get_vertex_node(vertex_list[0]) cubit.cmd('del group pgon') cubit.cmd("group 'pgon' add edge in node "+str(startnode)) group1 = cubit.get_id_from_name("pgon") edges = list(cubit.get_group_edges(group1)) edgestart=edges[0] else: startnode=n[0] cubit.cmd('del group pgon') cubit.cmd("group 'pgon' add edge in node "+str(startnode)) group1 = cubit.get_id_from_name("pgon") edges = list(cubit.get_group_edges(group1)) edgestart=edges[0] begin=startnode orientnode.append(begin) node_id_list = list(cubit.get_connectivity("edge", edgestart)) node_id_list.remove(startnode) startnode=node_id_list[0] orientnode.append(startnode) stopflag=False while startnode != begin and not stopflag: cubit.cmd('del group pgon') cubit.cmd("group 'pgon' add edge in node "+str(startnode)) group1 = cubit.get_id_from_name("pgon") edges = list(cubit.get_group_edges(group1)) if len(edges) != 1: edges.remove(edgestart) edgestart=edges[0] node_id_list = list(cubit.get_connectivity("edge", edgestart)) node_id_list.remove(startnode) orientnode.append(node_id_list[0]) startnode=node_id_list[0] else: stopflag=True vx=[] vy=[] for n in orientnode: v=cubit.get_nodal_coordinates(n) vx.append(v[0]) vy.append(v[1]) return vx,vy,orientnode
def free_write(self, free_name): freefile = open(free_name, 'w') print('writing ' + free_name) list_tet = cubit.parse_cubit_list('tet', 'all') if (self.block_free != []): for n in self.block_free: elems_free = cubit.get_block_tris(n) dic_free = dict(zip(elems_free, elems_free)) nfree = len(elems_free) freefile.write(str(nfree) + '\n') print('Number of free elements ', nfree) for tet in list_tet: tris = cubit.get_sub_elements('tet', tet, 2) for tri in tris: if dic_free.has_key(tri): nodes = cubit.get_connectivity('Tri', tri) txt = ('%10i ') % tet txt = txt + ('%10i %10i %10i') % nodes[:] freefile.write(str(txt) + '\n') else: freefile.write(str(0) + '\n') print('Number of free elements ', 0)
def absorb_write(self, absorb_name): absorbfile = open(absorb_name, 'w') print('writing ' + absorb_name) # for n in self.ns_absorb: # nodes_absorb=cubit.get_nodeset_nodes(n) # nabs=len(nodes_absorb) # absorbfile.write(str(nabs)+'\n') # print('Number of absorbing nodes ',nabs) # for node in nodes_absorb: # absorbfile.write(str(node)+'\n') ### list_tet = cubit.parse_cubit_list('tet', 'all') if (self.block_absorb != []): for n in self.block_absorb: elems_absorb = cubit.get_block_tris(n) dic_absorb = dict(zip(elems_absorb, elems_absorb)) nabs = len(elems_absorb) absorbfile.write(str(nabs) + '\n') print('Number of absorbing elements ', nabs) for tet in list_tet: tris = cubit.get_sub_elements('tet', tet, 2) for tri in tris: if dic_absorb.has_key(tri): nodes = cubit.get_connectivity('Tri', tri) txt = ('%10i ') % tet txt = txt + ('%10i %10i %10i') % nodes[:] absorbfile.write(str(txt) + '\n') else: absorbfile.write(str(0) + '\n') print('Number of absorbing elements ', 0)
def hex_simulation_parameter(self, h, vp_static=None, vs_static=None): nodes = cubit.get_connectivity("Hex", h) id_nodes = [0, 1, 2, 3, 4, 5, 6, 7] id_faces = [[1, 3, 4], [0, 2, 5], [1, 3, 6], [0, 2, 7], [5, 7], [4, 6], [5, 7], [4, 6]] dt = [] pmax = [] vmax = [] vmin = [] for i in id_nodes[:-1]: for j in id_nodes[i + 1 :]: x1, y1, z1 = cubit.get_nodal_coordinates(nodes[i]) x2, y2, z2 = cubit.get_nodal_coordinates(nodes[j]) nvp1, nvs1 = self.tomo(x1, y1, z1, vp_static, vs_static) nvp2, nvs2 = self.tomo(x2, y2, z2, vp_static, vs_static) d = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (z2 - z1) ** 2) # pmax_tmp=d*self.gllcoeff/min(nvp1,nvp2,nvs1,nvs2)*self.Ngll_per_wavelength pmax_tmp = ( d * (0.5 - self.gllcoeff) / min(nvp1, nvp2, nvs1, nvs2) * self.Ngll_per_wavelength ) # more conservative..... dt_tmp = self.Cmax * d * self.gllcoeff / max(nvp1, nvp2, nvs1, nvs2) dt.append(dt_tmp) pmax.append(pmax_tmp) vmax.append(max(nvp1, nvp2, nvs1, nvs2)) vmin.append(min(nvp1, nvp2, nvs1, nvs2)) return min(dt), max(pmax), min(vmin), max(vmax)
def getTetsOverlapPassedVols(target_list, volume_ids): """ Return tetraherons overlap with mouse selected CUBIT volumes. Parameters: * target_list List of indices of target tetrahedrons Return: List of indices of tetrahedrons overlap with the volumes """ in_list = [] for t in target_list: verts = cubit.get_connectivity("tet", t) cords = [] for v in verts: c = cubit.get_nodal_coordinates(v) cords.append(c) for vol_id in volume_ids: volume = cubit.volume(vol_id) body = volume.bodies()[0] within = False for cord in cords: status = body.point_containment(cord) if status == 1: within = True break if within: in_list.append(t) break return in_list
def free_write(self,freename=None): # free surface cubit.cmd('set info off') cubit.cmd('set echo off') cubit.cmd('set journal off') from sets import Set normal=(0,0,1) if not freename: freename=self.freename # writes free surface file print 'Writing '+freename+'.....' freehex=open(freename,'w') # searches block definition with name face_topo for block,flag in zip(self.block_bc,self.block_bc_flag): if block == self.topography: name=cubit.get_exodus_entity_name('block',block) print ' block name:',name,'id:',block quads_all=cubit.get_block_faces(block) print ' number of faces = ',len(quads_all) dic_quads_all=dict(zip(quads_all,quads_all)) freehex.write('%10i\n' % len(quads_all)) list_hex=cubit.parse_cubit_list('hex','all') for h in list_hex: faces=cubit.get_sub_elements('hex',h,2) for f in faces: if dic_quads_all.has_key(f): #print f nodes=cubit.get_connectivity('Face',f) nodes_ok=self.normal_check(nodes,normal) txt='%10i %10i %10i %10i %10i\n' % (h,nodes_ok[0],\ nodes_ok[1],nodes_ok[2],nodes_ok[3]) freehex.write(txt) freehex.close() print 'Ok' cubit.cmd('set info on') cubit.cmd('set echo on')
def free_write(self, freename=None): # free surface cubit.cmd('set info off') cubit.cmd('set echo off') cubit.cmd('set journal off') from sets import Set normal = (0, 0, 1) if not freename: freename = self.freename # writes free surface file print 'Writing ' + freename + '.....' freehex = open(freename, 'w') # searches block definition with name face_topo for block, flag in zip(self.block_bc, self.block_bc_flag): if block == self.topography: name = cubit.get_exodus_entity_name('block', block) print ' block name:', name, 'id:', block quads_all = cubit.get_block_faces(block) print ' number of faces = ', len(quads_all) dic_quads_all = dict(zip(quads_all, quads_all)) freehex.write('%10i\n' % len(quads_all)) list_hex = cubit.parse_cubit_list('hex', 'all') for h in list_hex: faces = cubit.get_sub_elements('hex', h, 2) for f in faces: if dic_quads_all.has_key(f): #print f nodes = cubit.get_connectivity('Face', f) nodes_ok = self.normal_check(nodes, normal) txt='%10i %10i %10i %10i %10i\n' % (h,nodes_ok[0],\ nodes_ok[1],nodes_ok[2],nodes_ok[3]) freehex.write(txt) freehex.close() print 'Ok' cubit.cmd('set info on') cubit.cmd('set echo on')
def hex_simulation_parameter(self, h, vp_static=None, vs_static=None): nodes = cubit.get_connectivity('Hex', h) id_nodes = [0, 1, 2, 3, 4, 5, 6, 7] id_faces = [[1, 3, 4], [0, 2, 5], [1, 3, 6], [0, 2, 7], [5, 7], [4, 6], [5, 7], [4, 6]] dt = [] pmax = [] vmax = [] vmin = [] for i in id_nodes[:-1]: for j in id_nodes[i + 1:]: x1, y1, z1 = cubit.get_nodal_coordinates(nodes[i]) x2, y2, z2 = cubit.get_nodal_coordinates(nodes[j]) nvp1, nvs1 = self.tomo(x1, y1, z1, vp_static, vs_static) nvp2, nvs2 = self.tomo(x2, y2, z2, vp_static, vs_static) d = math.sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2) #pmax_tmp=d*self.gllcoeff/min(nvp1,nvp2,nvs1,nvs2)*self.Ngll_per_wavelength pmax_tmp = d * (.5 - self.gllcoeff) / min( nvp1, nvp2, nvs1, nvs2) * self.Ngll_per_wavelength #more conservative..... dt_tmp = self.Cmax * d * self.gllcoeff / max( nvp1, nvp2, nvs1, nvs2) dt.append(dt_tmp) pmax.append(pmax_tmp) vmax.append(max(nvp1, nvp2, nvs1, nvs2)) vmin.append(min(nvp1, nvp2, nvs1, nvs2)) return min(dt), max(pmax), min(vmin), max(vmax)
def free_write(self,freename): #freename = None): """ Write free surface on file : freename """ cubit.cmd('set info off') # Turn off return messages from Cubit commands cubit.cmd('set echo off') # Turn off echo of Cubit commands cubit.cmd('set journal off') # Do not save journal file from sets import Set # if not freename: freename = self.freename freeedge = open(freename,'w') print 'Writing '+freename+'.....' if self.topo_mesh: for block,flag in zip(self.block_bc,self.block_bc_flag): # For each 1D block if block == self.topography: # If the block correspond to topography edges_all = Set(cubit.get_block_edges(block)) # Import all topo edges id as a Set toWritetoFile = [] #[""]*(len(edges_all)+1) toWritetoFile.append('%10i\n' % len(edges_all)) # Print the number of edges on the free surface for block,flag in zip(self.block_mat,self.block_flag): # For each 2D block print block,flag quads = cubit.get_block_faces(block) # Import quads id for quad in quads: # For each quad edges = Set(cubit.get_sub_elements("face", quad, 1)) # Get the lower dimension entities associated with a higher dimension entities. # Here it gets the 1D edges associates with the face of id "quad". Store it as a Set intersection = edges & edges_all # Contains the edges of the considered quad that is on the free surface if len(intersection) != 0: # If this quad touch the free surface #print " ",quad," -> this quad touch the free surface!" nodes = cubit.get_connectivity('face',quad) # Import the nodes describing the quad #print " it is described by nodes:",nodes," and edges :",edges #print " edges:",intersection," is/are on the free surface" nodes = self.jac_check(list(nodes)) # Check the jacobian of the quad for e in intersection: # For each edge on the free surface node_edge = cubit.get_connectivity('edge',e) # Import the nodes describing the edge #print " edge",e,"is composed of nodes",node_edge nodes_ok = [] for i in nodes: # Loop on the nodes of the quad if i in node_edge: # If this node is belonging to the free surface nodes_ok.append(i) # Put it in nodes_ok #print " nodes:",nodes_ok,"belong to free surface" txt = '%10i %10i %10i %10i\n' % (quad,2,nodes_ok[0],nodes_ok[1]) toWritetoFile.append(txt) # Write the id of the quad, 2 (number of nodes describing a free surface elements), and the nodes freeedge.writelines(toWritetoFile) else: freeedge.write('0') # Even without any free surface specfem2d need a file with a 0 in first line freeedge.close() print 'Ok' cubit.cmd('set info on') # Turn on return messages from Cubit commands cubit.cmd('set echo on') # Turn on echo of Cubit commands
def get_face_connectivity(self,ind): if self.hex27: cubit.silent_cmd('group "nf" add Node in face '+str(ind)) group1 = cubit.get_id_from_name("nf") result=cubit.get_group_nodes(group1) cubit.cmd('del group '+str(group1)) else: result=cubit.get_connectivity('face',ind) return result
def free_write(self, freename): #freename = None): """ Write free surface on file : freename """ cubit.cmd( 'set info off') # Turn off return messages from Cubit commands cubit.cmd('set echo off') # Turn off echo of Cubit commands cubit.cmd('set journal off') # Do not save journal file from sets import Set # if not freename: freename = self.freename freeedge = open(freename, 'w') print 'Writing ' + freename + '.....' if self.topo_mesh: for block, flag in zip(self.block_bc, self.block_bc_flag): # For each 1D block if block == self.topography: # If the block correspond to topography edges_all = Set(cubit.get_block_edges( block)) # Import all topo edges id as a Set freeedge.write('%10i\n' % len(edges_all) ) # Print the number of edges on the free surface print 'Number of edges in free surface :', len(edges_all) id_element = 0 for block, flag in zip(self.block_mat, self.block_flag): # For each 2D block quads = cubit.get_block_faces(block) # Import quads id for quad in quads: # For each quad id_element = id_element + 1 # id of this quad edges = Set( cubit.get_sub_elements("face", quad, 1) ) # Get the lower dimension entities associated with a higher dimension entities. # Here it gets the 1D edges associates with the face of id "quad". Store it as a Set intersection = edges & edges_all # Contains the edges of the considered quad that is on the free surface if len(intersection ) != 0: # If this quad touch the free surface nodes = cubit.get_expanded_connectivity( 'face', quad) # Import the nodes describing the quad nodes = self.jac_check( list(nodes)) # Check the jacobian of the quad for e in intersection: # For each edge on the free surface node_edge = cubit.get_connectivity( 'edge', e) # Import the nodes describing the edge nodes_ok = [] for i in nodes: # ??? TODO nodes_ok == node_edge ??? if i in node_edge: nodes_ok.append(i) txt = '%10i %10i %10i %10i\n' % ( id_element, 2, nodes_ok[0], nodes_ok[1]) # Write the id of the quad, 2 (number of nodes describing a free surface elements), and the nodes freeedge.write(txt) else: freeedge.write( '0' ) # Even without any free surface specfem2d need a file with a 0 in first line freeedge.close() print 'Ok' cubit.cmd('set info on') # Turn on return messages from Cubit commands cubit.cmd('set echo on') # Turn on echo of Cubit commands
def elem_write(self, mesh_name): meshfile = open(mesh_name, 'w') print('Writing ' + mesh_name + '.....') nelem = cubit.get_tet_count() print('number of elements:', str(nelem)) meshfile.write(str(nelem) + '\n') num_write = 0 temp_tet = [] tetlength = 1 for block, flag in zip(self.block_mat, self.block_flag): tetlength += len(cubit.get_block_tets(block)) tet_vp = range(tetlength) tet_vs = range(tetlength) tet_rho = range(tetlength) tet_qp = range(tetlength) tet_qs = range(tetlength) tet_block = range(tetlength) for block, flag in zip(self.block_mat, self.block_flag): tets = cubit.get_block_tets(block) for tet in tets: nodes = cubit.get_connectivity('Tet', tet) tet_vp[tet] = cubit.get_block_attribute_value(block, 1) tet_vs[tet] = cubit.get_block_attribute_value(block, 2) tet_rho[tet] = cubit.get_block_attribute_value(block, 3) tet_qp[tet] = cubit.get_block_attribute_value(block, 4) tet_qs[tet] = cubit.get_block_attribute_value(block, 5) tet_block[tet] = block temp_tet.append(tet) # txt=('%10i ')% tet # txt=txt+('%10i %10i %10i %10i\n')% nodes[:] # meshfile.write(txt) temp_tet.sort() for tet in temp_tet: nodes = cubit.get_connectivity('Tet', tet) txt = ('%10i ') % tet txt = txt + ('%10i %10i %10i %10i') % nodes[:] txt = txt + (' %9.1f %9.1f %9.1f %5i %5i\n') % ( tet_vp[tet], tet_vs[tet], tet_rho[tet], tet_qp[tet], tet_qs[tet]) meshfile.write(txt) meshfile.close() print('Ok')
def axis_write(self,axis_name): """ Write axis on file """ cubit.cmd('set info off') # Turn off return messages from Cubit commands cubit.cmd('set echo off') # Turn off echo of Cubit commands cubit.cmd('set journal off') # Do not save journal file from sets import Set axisedge = open(axis_name,'w') print 'Writing '+axis_name+'.....' for block,flag in zip(self.block_bc,self.block_bc_flag): # For each 1D block if block == self.axisId: # If the block correspond to the axis edges_all = Set(cubit.get_block_edges(block)) # Import all axis edges id as a Set toWritetoFile = [""]*(len(edges_all)+1) toWritetoFile[0] = '%10i\n' % len(edges_all) # Write the number of edges on the axis #axisedge.write('%10i\n' % len(edges_all)) # Write the number of edges on the axis print 'Number of edges on the axis :',len(edges_all) #id_element = 0 indexFile = 1 for block,flag in zip(self.block_mat,self.block_flag): # For each 2D block quads = cubit.get_block_faces(block) # Import quads id for quad in quads: # For each quad #id_element = id_element+1 # id of this quad edges = Set(cubit.get_sub_elements("face", quad, 1)) # Get the lower dimension entities associated with a higher dimension entities. # Here it gets the 1D edges associates with the face of id "quad". Store it as a Set intersection = edges & edges_all # Contains the edges of the considered quad that are on the axis if len(intersection) != 0: # If this quad touch the axis nodes = cubit.get_connectivity('face',quad) # Import the nodes describing the quad nodes = self.jac_check(list(nodes)) # Check the jacobian of the quad for e in intersection: # For each edge on the axis node_edge = cubit.get_connectivity('edge',e) # Import the nodes describing the edge nodes_ok = [] for i in nodes: # Loop on the nodes of the quad if i in node_edge: # If this node is belonging to the axis nodes_ok.append(i) # Add it to nodes_ok txt = '%10i %10i %10i %10i\n' % (quad,2,nodes_ok[0],nodes_ok[1]) #txt = '%10i %10i %10i %10i\n' % (id_element,2,nodes_ok[0],nodes_ok[1]) # Write the id of the quad, 2 (number of nodes describing a free surface elements), the nodes toWritetoFile[indexFile] = txt indexFile = indexFile + 1 #axisedge.write(txt) axisedge.writelines(toWritetoFile) axisedge.close() print 'Ok' cubit.cmd('set info on') # Turn on return messages from Cubit commands cubit.cmd('set echo on') # Turn on echo of Cubit commands
def get_hex_connectivity(self,ind): if self.hex27: cubit.silent_cmd('group "nh" add Node in hex '+str(ind)) group1 = cubit.get_id_from_name("nh") result=cubit.get_group_nodes(group1) if len(result) != 27: print 'error hex27' cubit.cmd('del group '+str(group1)) else: result=cubit.get_connectivity('hex',ind) return result
def elem_write(self,mesh_name): meshfile=open(mesh_name,'w') print('Writing '+mesh_name+'.....') nelem=cubit.get_tri_count() print('number of elements:',str(nelem)) meshfile.write(str(nelem)+'\n') num_write=0 temp_tri=[] trilength=1 for block,flag in zip(self.block_mat,self.block_flag): trilength += len(cubit.get_block_tris(block)) tri_vp=range(trilength) tri_vs=range(trilength) tri_rho=range(trilength) tri_qp=range(trilength) tri_qs=range(trilength) tri_block=range(trilength) for block,flag in zip(self.block_mat,self.block_flag): tris=cubit.get_block_tris(block) name=cubit.get_exodus_entity_name('block',block) type=cubit.get_block_element_type(block) for tri in tris: nodes=cubit.get_connectivity('Tri',tri) temp_tri.append(tri) values=name.split(" ") tri_vp[tri]=float(values[2]) tri_vs[tri]=float(values[3]) tri_rho[tri]=float(values[4]) tri_qp[tri]=float(values[5]) tri_qs[tri]=float(values[6]) temp_tri.sort() for tri in temp_tri: nodes=cubit.get_connectivity('Tri',tri) txt=('%10i ')% tri txt=txt+('%10i %10i %10i\n')% nodes[:] # This is later needed for the inversion feature: #txt=txt+('%10i %10i %10i')% nodes[:] #txt=txt+(' %9.1f %9.1f %9.1f %5i %5i\n') % (tri_vp[tri],tri_vs[tri],tri_rho[tri],tri_qp[tri],tri_qs[tri]) meshfile.write(txt) meshfile.close() print('Ok')
def edge_length(self,edge): """ length=edge_length(edge) return the length of a edge """ from math import sqrt nodes=cubit.get_connectivity('Edge',edge) x0,y0,z0=cubit.get_nodal_coordinates(nodes[0]) x1,y1,z1=cubit.get_nodal_coordinates(nodes[1]) d=sqrt((x1-x0)**2+(y1-y0)**2+(z1-z0)**2) return d
def edge_length(self,edge): """ length = edge_length(edge) return the length of a edge """ from math import sqrt nodes = cubit.get_connectivity('edge',edge) x0,y0,z0 = cubit.get_nodal_coordinates(nodes[0]) x1,y1,z1 = cubit.get_nodal_coordinates(nodes[1]) d = sqrt((x1-x0)**2+(y1-y0)**2+(z1-z0)**2) return d
def write_hex8(self, path): f = open(path + self.filename_hex8, 'w') nhex8 = len(self.hex8) print "writing hex8 file '" + path + self.filename_hex8 + "' containing " + str( nhex8) + " hexahedral cells" f.write('%10i\n' % nhex8) # for hex8 in self.hex8: nodes = cubit.get_connectivity('Hex', hex8) f.write('%10i %10i %10i %10i %10i %10i %10i %10i\n' % nodes) f.close()
def write_tet4(self, path): f = open(path + self.filename_tet4, 'w') ntet4 = len(self.tet4) print "writing tet4 file '" + path + self.filename_tet4 + "' containing " + str( ntet4) + " tetrahedral cells" f.write('%10i\n' % ntet4) # for tet4 in self.tet4: nodes = cubit.get_connectivity('Tet', tet4) f.write('%10i %10i %10i %10i \n' % nodes) f.close()
def hex_metric(self, h): nodes = cubit.get_connectivity('Hex', h) equiangle_skewness = None min_angle = float('infinity') edge_length_min = float('infinity') max_angle = None edge_length_max = None #loopnode=[(i,j) for i in range(8) for j in range(i+1,8)] if len(nodes) == 4: faces = [[0, 1, 2, 3]] elif len(nodes) == 8: faces = [[0, 1, 2, 3], [4, 5, 6, 7], [1, 5, 6, 2], [0, 4, 7, 3], [2, 6, 7, 3], [1, 5, 4, 0]] else: print 'bad definition of nodes' return None, None, None x = [] y = [] z = [] for i in nodes: n = cubit.get_nodal_coordinates(i) x.append(n[0]) y.append(n[1]) z.append(n[2]) for face in faces: for i in range(-1, 3): vx1 = x[face[i - 1]] - x[face[i]] vy1 = y[face[i - 1]] - y[face[i]] vz1 = z[face[i - 1]] - z[face[i]] # vx2 = x[face[i + 1]] - x[face[i]] vy2 = y[face[i + 1]] - y[face[i]] vz2 = z[face[i + 1]] - z[face[i]] # norm1 = math.sqrt(vx1 * vx1 + vy1 * vy1 + vz1 * vz1) norm2 = math.sqrt(vx2 * vx2 + vy2 * vy2 + vz2 * vz2) # if norm1 == 0 or norm2 == 0: print 'degenerated mesh, 0 length edge' import sys sys.exit() angle = math.acos( (vx1 * vx2 + vy1 * vy2 + vz1 * vz2) / (norm1 * norm2)) # equiangle_skewness = max( equiangle_skewness, math.fabs(2. * angle - math.pi) / math.pi) min_angle = min(min_angle, angle * 180. / math.pi) max_angle = max(max_angle, angle * 180. / math.pi) edge_length_min = min(edge_length_min, norm1) edge_length_max = max(edge_length_max, norm1) return round(equiangle_skewness, 5), min_angle, max_angle, round( edge_length_min, 5), round(edge_length_max, 5)
def saveMeshPoisson(self): nNodes = cubit.get_node_count() nTets = cubit.get_tet_count() meshFile = open(folder+"meshPoisson.xml", 'w') meshFile.write('<mesh celltype="tetrahedron" dim="3">\n') meshFile.write(' <nodes size="%d">\n' % (nNodes)) for x in range(0, nNodes): coords = cubit.get_nodal_coordinates(x+1) meshFile.write(' <node id="%d" x="%f" y="%f" z="%f"/>\n' % (x,coords[0],coords[1],coords[2])) meshFile.write(' </nodes>\n') meshFile.write(' <elements size="%d">\n' % (nTets)) for x in range(0, nTets): nodes = cubit.get_connectivity("tet", x+1) meshFile.write(' <element id="%d" v0="%d" v1="%d" v2="%d" v3="%d"/>\n' % (x,nodes[0]-1,nodes[1]-1,nodes[2]-1,nodes[3]-1)) meshFile.write(' </elements>\n') meshFile.write(' <boundary celltype="triangle" dim="2">\n') surfs = cubit.get_relatives("volume", self.vol, "surface") ec = 0 for x in range(0, 2): tris = cubit.get_surface_tris(surfs[x]) for y in range(0, len(tris)): nodes = cubit.get_connectivity("tri", tris[y]) element = [nodes[0]-1, nodes[1]-1, nodes[2]-1] ec = ec+1 meshFile.write(' <element id="%d" marker="%d" v0="%d" v1="%d" v2="%d"/>\n' % (ec,x,element[0],element[1],element[2])) meshFile.write(' <element id="%d" marker="%d" v0="%d" v1="%d" v2="%d"/>\n' % (ec+1,2,element[0],element[1],element[2])) meshFile.write(' </boundary>\n') meshFile.write('</mesh>\n') meshFile.write('<poisson>\n') meshFile.write(' <neumann>\n') meshFile.write(' <node id="0" marker="0" value="-1.0" />\n') meshFile.write(' <node id="1" marker="1" value="1.0" />\n') meshFile.write(' </neumann>\n') meshFile.write(' <dirichlet>\n') meshFile.write(' <node id="2" marker="2" value="0.0" />\n') meshFile.write(' </dirichlet>\n') meshFile.write('</poisson>\n') meshFile.close()
def hex_metric(self, h): nodes = cubit.get_connectivity('Hex', h) equiangle_skewness = None min_angle = float('infinity') edge_length_min = float('infinity') max_angle = None edge_length_max = None if len(nodes) == 4: faces = [[0, 1, 2, 3]] elif len(nodes) == 8: faces = [[0, 1, 2, 3], [4, 5, 6, 7], [1, 5, 6, 2], [0, 4, 7, 3], [2, 6, 7, 3], [1, 5, 4, 0]] else: print 'bad definition of nodes' return None, None, None x = [] y = [] z = [] for i in nodes: n = cubit.get_nodal_coordinates(i) x.append(n[0]) y.append(n[1]) z.append(n[2]) for face in faces: for i in range(-1, 3): vx1 = x[face[i - 1]] - x[face[i]] vy1 = y[face[i - 1]] - y[face[i]] vz1 = z[face[i - 1]] - z[face[i]] # vx2 = x[face[i + 1]] - x[face[i]] vy2 = y[face[i + 1]] - y[face[i]] vz2 = z[face[i + 1]] - z[face[i]] # norm1 = math.sqrt(vx1 * vx1 + vy1 * vy1 + vz1 * vz1) norm2 = math.sqrt(vx2 * vx2 + vy2 * vy2 + vz2 * vz2) # if norm1 == 0 or norm2 == 0: print 'degenerated mesh, 0 length edge' import sys sys.exit() angle = math.acos( (vx1 * vx2 + vy1 * vy2 + vz1 * vz2) / (norm1 * norm2)) # equiangle_skewness = max(equiangle_skewness, math.fabs( 2. * angle - math.pi) / math.pi) min_angle = min(min_angle, angle * 180. / math.pi) max_angle = max(max_angle, angle * 180. / math.pi) edge_length_min = min(edge_length_min, norm1) edge_length_max = max(edge_length_max, norm1) return round(equiangle_skewness, 5), min_angle, max_angle, \ round(edge_length_min, 5), round(edge_length_max, 5)
def getMeshData(): ELEM = cubit.get_entities("tri") NODE = cubit.get_entities("node") nELEM = len(ELEM) nNODE = len(NODE) eCONNECT = numpy.zeros(shape=(nELEM,3),dtype="int64") COORD = numpy.zeros(shape=(nNODE,3),dtype="double") for i in range(0,nELEM): eCONNECT[i,:] = list(cubit.get_connectivity("tri",ELEM[i])) eCONNECT = eCONNECT - 1 for i in range(0,nNODE): COORD[i,:] = list(cubit.get_nodal_coordinates(NODE[i])) return ELEM, NODE, eCONNECT, COORD
def surface_write(self, pathdir=None): # optional surfaces, e.g. moho_surface # should be created like e.g.: # > block 10 face in surface 2 # > block 10 name 'moho_surface' import re from sets import Set for block in self.block_bc: if block != self.topography: name = cubit.get_exodus_entity_name("block", block) # skips block names like face_abs**, face_topo** if re.search("abs", name): continue elif re.search("topo", name): continue elif re.search("surface", name): filename = pathdir + name + "_file" else: continue # gets face elements print " surface block name: ", name, "id: ", block quads_all = cubit.get_block_faces(block) print " face = ", len(quads_all) if len(quads_all) == 0: continue # writes out surface infos to file print "Writing " + filename + "....." surfhex_local = open(filename, "w") dic_quads_all = dict(zip(quads_all, quads_all)) # writes number of surface elements surfhex_local.write("%10i\n" % len(quads_all)) # writes out element node ids list_hex = cubit.parse_cubit_list("hex", "all") for h in list_hex: faces = cubit.get_sub_elements("hex", h, 2) for f in faces: if dic_quads_all.has_key(f): nodes = cubit.get_connectivity("Face", f) txt = "%10i %10i %10i %10i %10i\n" % (h, nodes[0], nodes[1], nodes[2], nodes[3]) surfhex_local.write(txt) # closes file surfhex_local.close() print "Ok"
def surface_write(self,pathdir=None): # optional surfaces, e.g. moho_surface # should be created like e.g.: # > block 10 face in surface 2 # > block 10 name 'moho_surface' import re from sets import Set for block in self.block_bc : if block != self.topography: name=cubit.get_exodus_entity_name('block',block) # skips block names like face_abs**, face_topo** if re.search('abs',name): continue elif re.search('topo',name): continue elif re.search('surface',name): filename=pathdir+name+'_file' else: continue # gets face elements print ' surface block name: ',name,'id: ',block quads_all=cubit.get_block_faces(block) print ' face = ',len(quads_all) if len(quads_all) == 0 : continue # writes out surface infos to file print 'Writing '+filename+'.....' surfhex_local=open(filename,'w') dic_quads_all=dict(zip(quads_all,quads_all)) # writes number of surface elements surfhex_local.write('%10i\n' % len(quads_all)) # writes out element node ids list_hex=cubit.parse_cubit_list('hex','all') for h in list_hex: faces=cubit.get_sub_elements('hex',h,2) for f in faces: if dic_quads_all.has_key(f): nodes=cubit.get_connectivity('Face',f) txt='%10i %10i %10i %10i %10i\n' % (h,nodes[0],\ nodes[1],nodes[2],nodes[3]) surfhex_local.write(txt) # closes file surfhex_local.close() print 'Ok'
def surface_write(self, pathdir=None): # optional surfaces, e.g. moho_surface # should be created like e.g.: # > block 10 face in surface 2 # > block 10 name 'moho_surface' import re from sets import Set for block in self.block_bc: if block != self.topography: name = cubit.get_exodus_entity_name('block', block) # skips block names like face_abs**, face_topo** if re.search('abs', name): continue elif re.search('topo', name): continue elif re.search('surface', name): filename = pathdir + name + '_file' else: continue # gets face elements print ' surface block name: ', name, 'id: ', block quads_all = cubit.get_block_faces(block) print ' face = ', len(quads_all) if len(quads_all) == 0: continue # writes out surface infos to file print 'Writing ' + filename + '.....' surfhex_local = open(filename, 'w') dic_quads_all = dict(zip(quads_all, quads_all)) # writes number of surface elements surfhex_local.write('%10i\n' % len(quads_all)) # writes out element node ids list_hex = cubit.parse_cubit_list('hex', 'all') for h in list_hex: faces = cubit.get_sub_elements('hex', h, 2) for f in faces: if dic_quads_all.has_key(f): nodes = cubit.get_connectivity('Face', f) txt='%10i %10i %10i %10i %10i\n' % (h,nodes[0],\ nodes[1],nodes[2],nodes[3]) surfhex_local.write(txt) # closes file surfhex_local.close() print 'Ok'
def abs_write(self,absname): #absname=None): """ Write absorbing surfaces on file : absname """ cubit.cmd('set info off') # Turn off return messages from Cubit commands cubit.cmd('set echo off') # Turn off echo of Cubit commands cubit.cmd('set journal off') # Do not save journal file from sets import Set # if not absname: absname = self.absname absedge = open(absname,'w') print 'Writing '+absname+'.....' edges_abs = [Set()]*self.nabs # edges_abs[0] will be a Set containing the nodes describing bottom adsorbing boundary # (index 0 : bottom, index 1 : right, index 2 : top, index 3 : left) nedges_all = 0 # To count the total number of absorbing edges for block,flag in zip(self.block_bc,self.block_bc_flag): # For each 1D block for iabs in range(0, self.nabs): # iabs = 0,1,2,3 : for each absorbing boundaries if block == self.abs_boun[iabs]: # If the block considered correspond to the boundary edges_abs[iabs] = Set(cubit.get_block_edges(block)) # Store each edge on edges_abs nedges_all = nedges_all+len(edges_abs[iabs]); # add the number of edges to nedges_all absedge.write('%10i\n' % nedges_all) # Write the total number of absorbing edges to the first line of file print 'Number of edges', nedges_all id_element = 0 for block,flag in zip(self.block_mat,self.block_flag): # For each 2D block quads = cubit.get_block_faces(block) # Import quads id for quad in quads: # For each quad id_element = id_element+1 # id of this quad edges = Set(cubit.get_sub_elements("face", quad, 1)) # Get the lower dimension entities associated with a higher dimension entities. # Here it gets the 1D edges associates with the face of id "quad". Store it as a Set for iabs in range(0,self.nabs): # iabs = 0,1,2,3 : for each absorbing boundaries intersection = edges & edges_abs[iabs] # Contains the edges of the considered quad that is on the absorbing boundary considered if len(intersection) != 0: # If this quad touch the absorbing boundary considered nodes = cubit.get_expanded_connectivity('face',quad) # Import the nodes describing the quad nodes = self.jac_check(list(nodes)) # Check the jacobian of the quad for e in intersection: # For each edge on the absorbing boundary considered node_edge = cubit.get_connectivity('edge',e) # Import the nodes describing the edge nodes_ok = [] for i in nodes: # Loop on the nodes of the quad if i in node_edge: # If this node is belonging to absorbing surface nodes_ok.append(i) # Add it to nodes_ok txt = '%10i %10i %10i %10i %10i\n' % (id_element,2,nodes_ok[0],nodes_ok[1],iabs+1) # Write the id of the quad, 2 (number of nodes describing a free surface elements), the nodes and the type of boundary absedge.write(txt) absedge.close() print 'Ok' cubit.cmd('set info on') # Turn on return messages from Cubit commands cubit.cmd('set echo on') # Turn on echo of Cubit commands
def mesh_write(self,mesh_name): meshfile=open(mesh_name,'w') print 'Writing '+mesh_name+'.....' num_elems=cubit.get_hex_count() print ' number of elements:',str(num_elems) meshfile.write(str(num_elems)+'\n') num_write=0 for block,flag in zip(self.block_mat,self.block_flag): #print block,flag hexes=cubit.get_block_hexes(block) #print len(hexes) for hexa in hexes: #print hexa nodes=cubit.get_connectivity('Hex',hexa) #nodes=self.jac_check(nodes) #is it valid for 3D? TODO txt=('%10i ')% hexa txt=txt+('%10i %10i %10i %10i %10i %10i %10i %10i\n')% nodes[:] meshfile.write(txt) meshfile.close() print 'Ok'
def mesh_write(self, mesh_name): meshfile = open(mesh_name, "w") print "Writing " + mesh_name + "....." num_elems = cubit.get_hex_count() print " number of elements:", str(num_elems) meshfile.write(str(num_elems) + "\n") num_write = 0 for block, flag in zip(self.block_mat, self.block_flag): # print block,flag hexes = cubit.get_block_hexes(block) # print len(hexes) for hexa in hexes: # print hexa nodes = cubit.get_connectivity("Hex", hexa) # nodes=self.jac_check(nodes) #is it valid for 3D? TODO txt = ("%10i ") % hexa txt = txt + ("%10i %10i %10i %10i %10i %10i %10i %10i\n") % nodes[:] meshfile.write(txt) meshfile.close() print "Ok"
def free_write(self,freename): #freename = None): """ Write free surface on file : freename """ cubit.cmd('set info off') # Turn off return messages from Cubit commands cubit.cmd('set echo off') # Turn off echo of Cubit commands cubit.cmd('set journal off') # Do not save journal file from sets import Set # if not freename: freename = self.freename freeedge = open(freename,'w') print 'Writing '+freename+'.....' if self.topo_mesh: for block,flag in zip(self.block_bc,self.block_bc_flag): # For each 1D block if block == self.topography: # If the block correspond to topography edges_all = Set(cubit.get_block_edges(block)) # Import all topo edges id as a Set freeedge.write('%10i\n' % len(edges_all)) # Print the number of edges on the free surface print 'Number of edges in free surface :',len(edges_all) id_element=0 for block,flag in zip(self.block_mat,self.block_flag): # For each 2D block quads = cubit.get_block_faces(block) # Import quads id for quad in quads: # For each quad id_element = id_element+1 # id of this quad edges = Set(cubit.get_sub_elements("face", quad, 1)) # Get the lower dimension entities associated with a higher dimension entities. # Here it gets the 1D edges associates with the face of id "quad". Store it as a Set intersection = edges & edges_all # Contains the edges of the considered quad that is on the free surface if len(intersection) != 0: # If this quad touch the free surface nodes = cubit.get_expanded_connectivity('face',quad) # Import the nodes describing the quad nodes = self.jac_check(list(nodes)) # Check the jacobian of the quad for e in intersection: # For each edge on the free surface node_edge = cubit.get_connectivity('edge',e) # Import the nodes describing the edge nodes_ok = [] for i in nodes: # ??? TODO nodes_ok == node_edge ??? if i in node_edge: nodes_ok.append(i) txt='%10i %10i %10i %10i\n' % (id_element,2,nodes_ok[0],nodes_ok[1]) # Write the id of the quad, 2 (number of nodes describing a free surface elements), and the nodes freeedge.write(txt) else: freeedge.write('0') # Even without any free surface specfem2d need a file with a 0 in first line freeedge.close() print 'Ok' cubit.cmd('set info on') # Turn on return messages from Cubit commands cubit.cmd('set echo on') # Turn on echo of Cubit commands
def check_valence(self): #usage: hex_valence() # list_hex=cubit.parse_cubit_list('hex','all') list_node=cubit.parse_cubit_list('node','all') lookup=dict(zip(list_node,[0]*len(list_node))) for h in list_hex: n=cubit.get_connectivity('Hex',h) for i in n: if lookup.has_key(i): lookup[i]=lookup[i]+1 inv_lookup=self.invert_dict(lookup) # vmax=max(inv_lookup.keys()) nmax=inv_lookup[max(inv_lookup.keys())] print 'max hex valence ',vmax,' at node ',nmax print '_____' for v in inv_lookup.keys(): print ('valence %2i - %9i hexes '% (v,len(inv_lookup[v]))) self.valence_summary=inv_lookup self.max_valence=vmax self.node_with_max_valence=nmax
def mesh_write(self, mesh_name): meshfile = open(mesh_name, 'w') print 'Writing ' + mesh_name + '.....' num_elems = cubit.get_hex_count() print ' number of elements:', str(num_elems) meshfile.write(str(num_elems) + '\n') num_write = 0 for block, flag in zip(self.block_mat, self.block_flag): #print block,flag hexes = cubit.get_block_hexes(block) #print len(hexes) for hexa in hexes: #print hexa nodes = cubit.get_connectivity('Hex', hexa) #nodes=self.jac_check(nodes) #is it valid for 3D? TODO txt = ('%10i ') % hexa txt = txt + ( '%10i %10i %10i %10i %10i %10i %10i %10i\n') % nodes[:] meshfile.write(txt) meshfile.close() print 'Ok'
def check_valence(self): #usage: hex_valence() # list_hex = cubit.parse_cubit_list('hex', 'all') list_node = cubit.parse_cubit_list('node', 'all') lookup = dict(zip(list_node, [0] * len(list_node))) for h in list_hex: n = cubit.get_connectivity('Hex', h) for i in n: if lookup.has_key(i): lookup[i] = lookup[i] + 1 inv_lookup = self.invert_dict(lookup) # vmax = max(inv_lookup.keys()) nmax = inv_lookup[max(inv_lookup.keys())] print 'max hex valence ', vmax, ' at node ', nmax print '_____' for v in inv_lookup.keys(): print('valence %2i - %9i hexes ' % (v, len(inv_lookup[v]))) self.valence_summary = inv_lookup self.max_valence = vmax self.node_with_max_valence = nmax
def boundary(self): boundary = [] surfs = cubit.get_relatives("volume", self.vol, "surface") for x in range(6, len(surfs)): tris = cubit.get_surface_tris(surfs[x]) for y in range(0, len(tris)): nodes = cubit.get_connectivity("tri", tris[y]) p1 = cubit.get_nodal_coordinates(nodes[0]) p2 = cubit.get_nodal_coordinates(nodes[1]) p3 = cubit.get_nodal_coordinates(nodes[2]) u_0 = [p2[0]-p1[0],p2[1]-p1[1],p2[2]-p1[2]] u_1 = [p3[0]-p1[0],p3[1]-p1[1],p3[2]-p1[2]] u1 = geo2.crossProduct(u_0, u_1) u1 = geo2.getVector4_3(u1) geo2.normalizeVector(u1) # if y == 0: # center_point = cubit.get_center_point("tri", tris[y]) # cubit.cmd("create curve location %f %f %f direction %f %f %f length %f" %(center_point[0],center_point[1],center_point[2],u1[0],u1[1],u1[2],self.root.radius)) element = [nodes[0]-1, nodes[1]-1, nodes[2]-1, u1[0], u1[1], u1[2]] boundary.append(element) return boundary
def check_valence(self): # usage: hex_valence() # list_hex = cubit.parse_cubit_list("hex", "all") list_node = cubit.parse_cubit_list("node", "all") lookup = dict(zip(list_node, [0] * len(list_node))) for h in list_hex: n = cubit.get_connectivity("Hex", h) for i in n: if lookup.has_key(i): lookup[i] = lookup[i] + 1 inv_lookup = self.invert_dict(lookup) # vmax = max(inv_lookup.keys()) nmax = inv_lookup[max(inv_lookup.keys())] print "max hex valence ", vmax, " at node ", nmax print "_____" for v in inv_lookup.keys(): print ("valence %2i - %9i hexes " % (v, len(inv_lookup[v]))) self.valence_summary = inv_lookup self.max_valence = vmax self.node_with_max_valence = nmax
def mesh_write(self,mesh_name): """ Write mesh (quads ids with their corresponding nodes ids) on file : mesh_name """ meshfile = open(mesh_name,'w') print 'Writing '+mesh_name+'.....' num_elems = cubit.get_quad_count() # Store the number of elements toWritetoFile = [""]*(num_elems+1) toWritetoFile[0] = str(num_elems)+'\n' #meshfile.write(str(num_elems)+'\n') # Write it on first line num_write = 0 for block,flag in zip(self.block_mat,self.block_flag): # for each 2D block quads = cubit.get_block_faces(block) # Import quads ids for inum,quad in enumerate(quads): # For each of these quads nodes = cubit.get_connectivity('face',quad) # Get the nodes nodes = self.jac_check(nodes) # Check the jacobian txt = ('%10i %10i %10i %10i\n')% nodes toWritetoFile[quad] = txt #meshfile.write(txt) # Write a line to mesh file num_write = num_write+inum+1 print 'block', block, 'number of ',self.face,' : ', inum+1 meshfile.writelines(toWritetoFile) meshfile.close() print 'Ok num elements/write =',str(num_elems), str(num_write)
def getTrisBoundInSelectedVols(target_list): """ Return triangles bound in selected CUBIT volumes. Parameters: * target_list List of indices of target triangles Return: List of indices of triangles bound by the volumes """ group_id = cubit.create_new_group() cubit.silent_cmd("group %i add selection" % (group_id)) volume_ids = cubit.get_group_volumes(group_id) in_list = [] for t in target_list: verts = cubit.get_connectivity("tri", t) with_in = True cords = [] for v in verts: c = cubit.get_nodal_coordinates(v) cords.append(c) for vol_id in volume_ids: volume = cubit.volume(vol_id) body = volume.bodies()[0] within = True for cord in cords: status = body.point_containment(cord) if status == 0: within = False break if within: in_list.append(t) break cubit.delete_group(group_id) return in_list
def mesh_write(self, mesh_name): """ Write mesh (quads ids with their corresponding nodes ids) on file : mesh_name """ meshfile = open(mesh_name, 'w') print 'Writing ' + mesh_name + '.....' num_elems = cubit.get_quad_count() # Store the number of elements toWritetoFile = [""] * (num_elems + 1) toWritetoFile[0] = str(num_elems) + '\n' #meshfile.write(str(num_elems)+'\n') # Write it on first line num_write = 0 for block, flag in zip(self.block_mat, self.block_flag): # for each 2D block quads = cubit.get_block_faces(block) # Import quads ids for inum, quad in enumerate(quads): # For each of these quads nodes = cubit.get_connectivity('face', quad) # Get the nodes nodes = self.jac_check(nodes) # Check the jacobian txt = ('%10i %10i %10i %10i\n') % nodes toWritetoFile[quad] = txt #meshfile.write(txt) # Write a line to mesh file num_write = num_write + inum + 1 print 'block', block, 'number of ', self.face, ' : ', inum + 1 meshfile.writelines(toWritetoFile) meshfile.close() print 'Ok num elements/write =', str(num_elems), str(num_write)
def getTrisOverlapSelectedVols(target_list): """ Return triangles overlap with mouse selected CUBIT volumes. Parameters: * target_list List of indices of target triangles Return: List of indices of triangles overlap with the volumes """ group_id = cubit.create_new_group() cubit.silent_cmd("group %i add selection" % (group_id)) volume_ids = cubit.get_group_volumes(group_id) in_list = [] for t in target_list: verts = cubit.get_connectivity("tri", t) cords = [] for v in verts: c = cubit.get_nodal_coordinates(v) cords.append(c) for vol_id in volume_ids: volume = cubit.volume(vol_id) body = volume.bodies()[0] within = False for cord in cords: status = body.point_containment(cord) if status == 1: within = True break if within: in_list.append(t) break cubit.delete_group(group_id) return in_list
def free_write(self, freename=None): # free surface cubit.cmd("set info off") cubit.cmd("set echo off") cubit.cmd("set journal off") from sets import Set normal = (0, 0, 1) if not freename: freename = self.freename # writes free surface file print "Writing " + freename + "....." freehex = open(freename, "w") # searches block definition with name face_topo for block, flag in zip(self.block_bc, self.block_bc_flag): if block == self.topography: name = cubit.get_exodus_entity_name("block", block) print " block name:", name, "id:", block quads_all = cubit.get_block_faces(block) print " number of faces = ", len(quads_all) dic_quads_all = dict(zip(quads_all, quads_all)) freehex.write("%10i\n" % len(quads_all)) list_hex = cubit.parse_cubit_list("hex", "all") for h in list_hex: faces = cubit.get_sub_elements("hex", h, 2) for f in faces: if dic_quads_all.has_key(f): # print f nodes = cubit.get_connectivity("Face", f) nodes_ok = self.normal_check(nodes, normal) txt = "%10i %10i %10i %10i %10i\n" % (h, nodes_ok[0], nodes_ok[1], nodes_ok[2], nodes_ok[3]) freehex.write(txt) freehex.close() print "Ok" cubit.cmd("set info on") cubit.cmd("set echo on")
def forcing_write(self, forcname): """ Write forcing surfaces on file : forcname """ cubit.cmd( 'set info off') # Turn off return messages from Cubit commands cubit.cmd('set echo off') # Turn off echo of Cubit commands cubit.cmd('set journal off') # Do not save journal file from sets import Set forceedge = open(forcname, 'w') print 'Writing ' + forcname + '.....' edges_forc = [ Set() ] * self.nforc # edges_forc[0] will be a Set containing the nodes describing the forcing boundary # (index 0 : bottom, index 1 : right, index 2 : top, index 3 : left) nedges_all = 0 # To count the total number of forcing edges for block, flag in zip(self.block_bc, self.block_bc_flag): # For each 1D block for iforc in range( 0, self.nforc ): # iforc = 0,1,2,3 : for each forcing boundaries if block == self.forcing_boun[ iforc]: # If the block considered correspond to the boundary edges_forc[iforc] = Set(cubit.get_block_edges( block)) # Store each edge on edges_forc nedges_all = nedges_all + len( edges_forc[iforc] ) # add the number of edges to nedges_all toWritetoFile = [""] * (nedges_all + 1) toWritetoFile[ 0] = '%10i\n' % nedges_all # Write the total number of forcing edges to the first line of file #forceedge.write('%10i\n' % nedges_all) # Write the total number of forcing edges to the first line of file print 'Number of edges', nedges_all #id_element = 0 indexFile = 1 for block, flag in zip(self.block_mat, self.block_flag): # For each 2D block quads = cubit.get_block_faces(block) # Import quads id for quad in quads: # For each quad #id_element = id_element+1 # id of this quad edges = Set( cubit.get_sub_elements("face", quad, 1) ) # Get the lower dimension entities associated with a higher dimension entities. # Here it gets the 1D edges associates with the face of id "quad". Store it as a Set for iforc in range( 0, self.nforc ): # iforc = 0,1,2,3 : for each forcing boundaries intersection = edges & edges_forc[ iforc] # Contains the edges of the considered quad that is on the forcing boundary considered if len( intersection ) != 0: # If this quad touch the forcing boundary considered nodes = cubit.get_connectivity( 'face', quad) # Import the nodes describing the quad nodes = self.jac_check( list(nodes)) # Check the jacobian of the quad for e in intersection: # For each edge on the forcing boundary considered node_edge = cubit.get_connectivity( 'edge', e) # Import the nodes describing the edge nodes_ok = [] for i in nodes: # Loop on the nodes of the quad if i in node_edge: # If this node is belonging to forcing surface nodes_ok.append(i) # add it to nodes_ok # forcname contains 1/ element number, 2/ number of nodes that form the acoustic forcing edge # (which currently must always be equal to two, see comment below), # 3/ first node on the acforcing surface, 4/ second node on the acforcing surface # 5/ 1 = IBOTTOME, 2 = IRIGHT, 3 = ITOP, 4 = ILEFT #txt = '%10i %10i %10i %10i %10i\n' % (id_element,2,nodes_ok[0],nodes_ok[1],iforc+1) txt = '%10i %10i %10i %10i %10i\n' % ( quad, 2, nodes_ok[0], nodes_ok[1], iforc + 1) # Write the id of the quad, 2 (number of nodes describing a free surface elements), the nodes and the type of boundary #print indexFile toWritetoFile[indexFile] = txt indexFile = indexFile + 1 #forceedge.write(txt) forceedge.writelines(toWritetoFile) forceedge.close() print 'Ok' cubit.cmd('set info on') # Turn on return messages from Cubit commands cubit.cmd('set echo on') # Turn on echo of Cubit commands
def getstats(self): ''' Get statistics for differend blocks in the hexmesh ''' ############################## READ BLOCKS ###################### try: blocks = cubit.get_block_id_list() except: print('no blocks defined') nblocks = len(blocks) print('Found ', nblocks, ' Blocks') # lists of details of all elastic blocks. For each elastic block, append respective values name = [] typ = [] nattrib = [] vp = [] vs = [] rho = [] minEdge = [] maxEdge = [] minEdgeMesh = [] maxEdgeMesh = [] # k: counter of all elastic blocks k = 0 for block in blocks: minEdgeMeshTmp = [] maxEdgeMeshTmp = [] blockname = cubit.get_exodus_entity_name('block', block) # only apply stats to elastic blocks if blockname.find("elastic") >= 0: # NOW APPEND VALUES OF THIS ELASTIC BLOCK TO LISTS (defined as empty above) name.append(blockname) typ.append(cubit.get_block_element_type(block)) # attribute count nattrib.append(cubit.get_block_attribute_count(block)) # vp vp.append(cubit.get_block_attribute_value(block, 1)) # vs vs.append(cubit.get_block_attribute_value(block, 2)) # rho rho.append(cubit.get_block_attribute_value(block, 3)) hexes = cubit.get_block_hexes(block) print(block, k, 'name: ', name[k], '#hexes:', len(hexes), 'type: ', typ[k], 'attribute count: ', nattrib[k], 'vp: ', vp[k], 'vs: ', vs[k], 'rho: ', rho[k]) # minimum/maximum edgelength search for this elastic block # initiate with very large minEdge and very small maxEdge minEdge.append(1e9) maxEdge.append(1e-9) # now search for hexa in hexes: nodes = cubit.get_connectivity('Hex', hexa) # get coordinates of nodes of this hexahedron node_coords = [] for node in nodes: node_coords.append(cubit.get_nodal_coordinates(node)) minv = self.minEdgeHex(node_coords) minEdgeMeshTmp.append(minv) maxv = self.maxEdgeHex(node_coords) maxEdgeMeshTmp.append(maxv) # is minimum edgelength of this this element smaller than minimum edgelength found before? if minv < minEdge[k]: minEdge[k] = minv # is maximum edgelength of this this element larger than maximum edgelength found before? if maxv > maxEdge[k]: maxEdge[k] = maxv minEdgeMesh.append(minEdgeMeshTmp) maxEdgeMesh.append(maxEdgeMeshTmp) # end of processing of this elastic block. incremet counter k = k + 1 # if not "elastic" in this blockname else: print(blockname, '--no elastic') # now calculate maximum frequency for which the mesh is stable # and maximal dt # first do that for each block fmax = [] dtmax_05 = [] for i in range(len(name)): fmax.append(self.calcMaxFreq(maxEdge[i], vs[i])) dtmax_05.append(self.calcMaxDt(minEdge[i], vp[i], cn=0.5)) min_dx = minEdge[i] * 0.1727 max_dx = maxEdge[i] * 0.3272 * sqrt(3.) print('Block ', name[i], ' min dx: ', min_dx, ' max dx: ', max_dx, 'max frequency: ', fmax[i], ' maximal dt (C=0.5):', dtmax_05[i]) vals, bin_edges = histogram(minEdgeMesh[i], 10) nhexa = sum(vals) print(' ' + str(nhexa) + ' HEXAS IN THIS BLOCK') print(' histogram of minimum edge length of hexa of this block:') for j, val in enumerate(vals): print( ' %6.3f %% of hexas have minimum edgelength between %3.3f and %3.3f -> dt (C=0.5) is %8.3e' % (100. * val / float(nhexa), bin_edges[j], bin_edges[j + 1], self.calcMaxDt(bin_edges[j], vp[i], cn=0.5))) vals, bin_edges = histogram(maxEdgeMesh[i], 10) nhexa = sum(vals) print(' ' + str(nhexa) + ' HEXAS IN THIS BLOCK') print(' histogram of maximum edge length of hexa of this block:') for j, val in enumerate(vals): print( ' %6.3f %% of hexas have maximum edgelength between %3.3f and %3.3f -> fmax (5 GLL points per wavelength) is %8.3e' % (100. * val / float(nhexa), bin_edges[j], bin_edges[j + 1], self.calcMaxFreq(bin_edges[j + 1], vs[i]))) # now compare the values for all the blocks dtm_05 = sorted(dtmax_05) print( 'The minimum over all blocks of the respective maximal dt for C=0.5 is: ', dtm_05[0]) fmax_min = sorted(fmax) print( 'The minimum over all blocks of the respective maximal frequency is: ', fmax_min[0])
cubit.cmd("playback 'Mandel3D_msh.jou'") cubit.cmd("reset") cubit.cmd( "import mesh geometry './Mandel3D.exo' block all use nodeset sideset") surf_list = cubit.get_sideset_surfaces(1) quad_list = [ cubit.get_surface_quads(surf_list[i]) for i in range(len(surf_list)) ] vol_list = cubit.get_block_volumes(1) hex_list = [cubit.get_volume_hexes(vol_list[i]) for i in range(len(vol_list))] trac_el = [] mat_typ = np.ones(shape=(cubit.get_hex_count(), 1), dtype=np.uint8) for quadset, hexset in zip(quad_list, hex_list): for quad in quadset: nodes = cubit.get_connectivity("quad", quad) for hx in hexset: nodes_hx = cubit.get_connectivity("hex", hx) if set(nodes).issubset(set(nodes_hx)): if set(nodes).issubset(set(np.array(nodes_hx)[[0, 1, 5, 4]])): side = 1 elif set(nodes).issubset(set(np.array(nodes_hx)[[1, 2, 6, 6]])): side = 2 elif set(nodes).issubset(set(np.array(nodes_hx)[[2, 3, 7, 7]])): side = 3 elif set(nodes).issubset(set(np.array(nodes_hx)[[3, 2, 6, 7]])): side = 4 elif set(nodes).issubset(set(np.array(nodes_hx)[[0, 1, 2,
def saveMesh2D2(self): cubit.cmd("create surface rectangle width 5000 height 5000 zplane") cubit.cmd("create surface rectangle width 1000 height 1000 zplane") cubit.cmd("subtract body 2 from body 1") surfID = cubit.get_last_id("surface") cubit.cmd("surface all size auto factor 4") cubit.cmd("surface all scheme TriMesh") cubit.cmd("mesh surface all") nNodes = cubit.get_node_count() meshFile = open(folder+"mesh2D2.xml", 'w') meshFile.write('<mesh celltype="triangle" dim="2">\n') meshFile.write(' <nodes size="%d">\n' % (nNodes)) for x in range(0, nNodes): coords = cubit.get_nodal_coordinates(x+1) meshFile.write(' <node id="%d" x="%f" y="%f" z="%f"/>\n' % (x,coords[0],coords[1],coords[2])) meshFile.write(' </nodes>\n') tris = cubit.get_surface_tris(surfID) meshFile.write(' <elements size="%d">\n' % (len(tris))) for x in range(0, len(tris)): nd = cubit.get_connectivity("tri", tris[x]) meshFile.write(' <element id="%d" v0="%d" v1="%d" v2="%d"/>\n' % (x,nd[0]-1,nd[1]-1,nd[2]-1)) meshFile.write(' </elements>\n') meshFile.write(' <element_data type="fiber_transversely_isotropic">\n') for x in range(0, len(tris)): meshFile.write(' <element id="%d">\n' %(x)) meshFile.write(' <fiber>1.000000,0.000000,0.000000</fiber>\n') meshFile.write(' </element>\n') meshFile.write(' </element_data>\n') meshFile.write(' <boundary celltype="line" dim="1">\n') eds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] ec = 1 surf = cubit.surface(surfID) for y in range(0, len(eds)): nodes = cubit.get_connectivity("edge", eds[y]) element = [nodes[0]-1, nodes[1]-1] #cp = cubit.get_center_point("edge", eds[y]) #norm = surf.normal_at([cp[0],cp[1],cp[2]]) #cubit.cmd("create curve location %f %f %f direction %f %f %f length %f" % (cp[0],cp[1],cp[2], norm[0], norm[1], norm[2], 200)) #ec = ec+1 #meshFile.write(' <element id="%d" marker="%d" v0="%d" v1="%d" nx="%f" ny="%f" nz="%f"/>\n' % (ec,1,element[0],element[1], norm[0], norm[1], norm[2])) #meshFile.write(' <element id="%d" marker="%d" v0="%d" v1="%d" v2="%d"/>\n' % (ec+1,2,element[0],element[1],element[2])) meshFile.write(' </boundary>\n') meshFile.write('</mesh>\n') meshFile.write('<poisson>\n') meshFile.write(' <neumann>\n') meshFile.write(' <node id="1" marker="1" value="1.0" />\n') meshFile.write(' </neumann>\n') #meshFile.write(' <dirichlet>\n') #meshFile.write(' <node id="2" marker="2" value="0.0" />\n') #meshFile.write(' </dirichlet>\n') meshFile.write('</poisson>\n') meshFile.write('<electrophysiology>\n') meshFile.write(' <stimuli number="1">\n') bb = cubit.get_bounding_box("surface", surfID) x0 = bb[0] x1 = 0.8*x0 + 0.2*bb[1] y0 = bb[3] y1 = 0.8*y0 + 0.2*bb[4] #z0 = bb[6] #z1 = 0.8*z0 + 0.2*bb[7] meshFile.write(' <stim start="0.00" duration="4.00" value="-35.7140" x0="%f" x1="%f" y0="%f" y1="%f" />\n' % (x0,x1,y0,y1)) meshFile.write(' </stimuli>\n') meshFile.write('</electrophysiology>\n') meshFile.close()
def saveMesh(self): nNodes = cubit.get_node_count() nTets = cubit.get_tet_count() meshFile = open(folder+"Cubo.xml", 'w') meshFile.write('<mesh celltype="tetrahedron" dim="3">\n') meshFile.write(' <nodes size="%d">\n' % (nNodes)) for x in range(0, nNodes): coords = cubit.get_nodal_coordinates(x+1) meshFile.write(' <node id="%d" x="%f" y="%f" z="%f"/>\n' % (x,coords[0],coords[1],coords[2])) meshFile.write(' </nodes>\n') meshFile.write(' <elements size="%d">\n' % (nTets)) for x in range(0, nTets): nodes = cubit.get_connectivity("tet", x+1) meshFile.write(' <element id="%d" v0="%d" v1="%d" v2="%d" v3="%d"/>\n' % (x,nodes[0]-1,nodes[1]-1,nodes[2]-1,nodes[3]-1)) meshFile.write(' </elements>\n') meshFile.write(' <element_data type="fiber_transversely_isotropic">\n') for x in range(0, nTets): meshFile.write(' <element id="%d">\n' %(x)) meshFile.write(' <fiber>1.000000,0.000000,0.000000</fiber>\n') meshFile.write(' </element>\n') meshFile.write(' </element_data>\n') meshFile.write(' <boundary celltype="triangle" dim="2">\n') bsurfs = cubit.get_relatives("volume", self.vol, "surface") ec = 0 for x in range(0, len(bsurfs)): #for x in range(6, len(bsurfs)): #if x is not 16 and x is not 14: tris = cubit.get_surface_tris(bsurfs[x]) surf = cubit.surface(bsurfs[x]) for y in range(0, len(tris)): cp = cubit.get_center_point("tri", tris[y]) norm = surf.normal_at([cp[0],cp[1],cp[2]]) #cubit.cmd("create curve location %f %f %f direction %f %f %f length %f" % (cp[0],cp[1],cp[2],norm[0],norm[1],norm[2],200)) nodes = cubit.get_connectivity("tri", tris[y]) element = [nodes[0]-1, nodes[1]-1, nodes[2]-1] meshFile.write(' <element id="%d" marker="%d" v0="%d" v1="%d" v2="%d" nx="%f" ny="%f" nz="%f"/>\n' % (ec,1.0,element[0],element[1],element[2],norm[0],norm[1],norm[2])) ec = ec+1 meshFile.write(' </boundary>\n') #meshFile.write(' <boundary celltype="triangle" dim="2">\n') #surfs = cubit.get_relatives("volume", self.vol, "surface") #ec = 0 #for x in range(0, 2): # tris = cubit.get_surface_tris(surfs[x]) # for y in range(0, len(tris)): # nodes = cubit.get_connectivity("tri", tris[y]) # element = [nodes[0]-1, nodes[1]-1, nodes[2]-1] # ec = ec+1 # meshFile.write(' <element id="%d" marker="%d" v0="%d" v1="%d" v2="%d"/>\n' % (ec,x,element[0],element[1],element[2])) #meshFile.write(' <element id="%d" marker="%d" v0="%d" v1="%d" v2="%d"/>\n' % (ec+1,2,element[0],element[1],element[2])) #meshFile.write(' </boundary>\n') meshFile.write('</mesh>\n') meshFile.write('<poisson>\n') meshFile.write(' <neumann>\n') #meshFile.write(' <node id="0" marker="0" value="-1.0" />\n') meshFile.write(' <node id="1" marker="1" value="0.05"/>\n') meshFile.write(' </neumann>\n') #meshFile.write(' <dirichlet>\n') #meshFile.write(' <node id="2" marker="2" value="0.0" />\n') #meshFile.write(' </dirichlet>\n') meshFile.write('</poisson>\n') #meshFile.write('<electrophysiology>\n') #meshFile.write(' <stimuli number="1">\n') #bb = cubit.get_bounding_box("volume", self.vol) #x0 = bb[0] #x1 = 0.8*x0 + 0.2*bb[1] #y0 = bb[3] #y1 = 0.8*y0 + 0.2*bb[4] #z0 = bb[6] #z1 = 0.8*z0 + 0.2*bb[7] #meshFile.write(' <stim start="0.00" duration="4.00" value="-35.7140" x0="%f" x1="%f" y0="%f" y1="%f" z0="%f" z1="%f" />\n' % (x0,x1,y0,y1,z0,z1)) #meshFile.write(' </stimuli>\n') #meshFile.write('</electrophysiology>\n') meshFile.close()
def abs_write(self, absname=None): # absorbing boundaries import re cubit.cmd('set info off') cubit.cmd('set echo off') cubit.cmd('set journal off') from sets import Set if not absname: absname = self.absname # # loops through all block definitions list_hex = cubit.parse_cubit_list('hex', 'all') for block, flag in zip(self.block_bc, self.block_bc_flag): if block != self.topography: name = cubit.get_exodus_entity_name('block', block) print name, block absflag = False if re.search('xmin', name): filename = absname + '_xmin' normal = (-1, 0, 0) elif re.search('xmax', name): filename = absname + '_xmax' normal = (1, 0, 0) elif re.search('ymin', name): filename = absname + '_ymin' normal = (0, -1, 0) elif re.search('ymax', name): filename = absname + '_ymax' normal = (0, 1, 0) elif re.search('bottom', name): filename = absname + '_bottom' normal = (0, 0, -1) elif re.search('abs', name): print " ...face_abs - not used so far..." continue else: continue # opens file print 'Writing ' + filename + '.....' abshex_local = open(filename, 'w') # gets face elements quads_all = cubit.get_block_faces(block) dic_quads_all = dict(zip(quads_all, quads_all)) print ' number of faces = ', len(quads_all) abshex_local.write('%10i\n' % len(quads_all)) #command = "group 'list_hex' add hex in face "+str(quads_all) #command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ") #cubit.cmd(command) #group=cubit.get_id_from_name("list_hex") #list_hex=cubit.get_group_hexes(group) #command = "delete group "+ str(group) #cubit.cmd(command) for h in list_hex: faces = cubit.get_sub_elements('hex', h, 2) for f in faces: if dic_quads_all.has_key(f): nodes = cubit.get_connectivity('Face', f) if not absflag: # checks with specified normal nodes_ok = self.normal_check(nodes, normal) txt='%10i %10i %10i %10i %10i\n' % (h,nodes_ok[0],\ nodes_ok[1],nodes_ok[2],nodes_ok[3]) else: txt='%10i %10i %10i %10i %10i\n' % (h,nodes[0],\ nodes[1],nodes[2],nodes[3]) abshex_local.write(txt) # closes file abshex_local.close() print 'Ok' cubit.cmd('set info on') cubit.cmd('set echo on')
def free_write(self, freename): #freename = None): """ Write free surface on file : freename """ cubit.cmd( 'set info off') # Turn off return messages from Cubit commands cubit.cmd('set echo off') # Turn off echo of Cubit commands cubit.cmd('set journal off') # Do not save journal file from sets import Set # if not freename: freename = self.freename freeedge = open(freename, 'w') print 'Writing ' + freename + '.....' if self.topo_mesh: for block, flag in zip(self.block_bc, self.block_bc_flag): # For each 1D block if block == self.topography: # If the block correspond to topography edges_all = Set(cubit.get_block_edges( block)) # Import all topo edges id as a Set toWritetoFile = [] #[""]*(len(edges_all)+1) toWritetoFile.append( '%10i\n' % len(edges_all) ) # Print the number of edges on the free surface for block, flag in zip(self.block_mat, self.block_flag): # For each 2D block print block, flag quads = cubit.get_block_faces(block) # Import quads id for quad in quads: # For each quad edges = Set( cubit.get_sub_elements("face", quad, 1) ) # Get the lower dimension entities associated with a higher dimension entities. # Here it gets the 1D edges associates with the face of id "quad". Store it as a Set intersection = edges & edges_all # Contains the edges of the considered quad that is on the free surface if len(intersection ) != 0: # If this quad touch the free surface #print " ",quad," -> this quad touch the free surface!" nodes = cubit.get_connectivity( 'face', quad) # Import the nodes describing the quad #print " it is described by nodes:",nodes," and edges :",edges #print " edges:",intersection," is/are on the free surface" nodes = self.jac_check( list(nodes)) # Check the jacobian of the quad for e in intersection: # For each edge on the free surface node_edge = cubit.get_connectivity( 'edge', e) # Import the nodes describing the edge #print " edge",e,"is composed of nodes",node_edge nodes_ok = [] for i in nodes: # Loop on the nodes of the quad if i in node_edge: # If this node is belonging to the free surface nodes_ok.append(i) # Put it in nodes_ok #print " nodes:",nodes_ok,"belong to free surface" txt = '%10i %10i %10i %10i\n' % ( quad, 2, nodes_ok[0], nodes_ok[1]) toWritetoFile.append(txt) # Write the id of the quad, 2 (number of nodes describing a free surface elements), and the nodes freeedge.writelines(toWritetoFile) else: freeedge.write( '0' ) # Even without any free surface specfem2d need a file with a 0 in first line freeedge.close() print 'Ok' cubit.cmd('set info on') # Turn on return messages from Cubit commands cubit.cmd('set echo on') # Turn on echo of Cubit commands
def saveMesh3D(self): cubit.cmd("brick x 5000 y 5000 z 5000") cubit.cmd("create cylinder height 4000 radius 500") cubit.cmd("subtract body 2 from body 1") volID = cubit.get_last_id("volume") self.vol = volID self.mesh() nNodes = cubit.get_node_count() meshFile = open(folder+"mesh3D2.xml", 'w') meshFile.write('<mesh celltype="tetrahedron" dim="3">\n') meshFile.write(' <nodes size="%d">\n' % (nNodes)) for x in range(0, nNodes): coords = cubit.get_nodal_coordinates(x+1) meshFile.write(' <node id="%d" x="%f" y="%f" z="%f"/>\n' % (x,coords[0],coords[1],coords[2])) meshFile.write(' </nodes>\n') nTets = cubit.get_tet_count() meshFile.write(' <elements size="%d">\n' % (nTets)) for x in range(0, nTets): nodes = cubit.get_connectivity("tet", x+1) meshFile.write(' <element id="%d" v0="%d" v1="%d" v2="%d" v3="%d"/>\n' % (x,nodes[0]-1,nodes[1]-1,nodes[2]-1,nodes[3]-1)) meshFile.write(' </elements>\n') meshFile.write(' <element_data type="fiber_transversely_isotropic">\n') for x in range(0, nTets): meshFile.write(' <element id="%d">\n' %(x)) meshFile.write(' <fiber>1.000000,0.000000,0.000000</fiber>\n') meshFile.write(' </element>\n') meshFile.write(' </element_data>\n') meshFile.write(' <boundary celltype="triangle" dim="2">\n') bsurfs = [10, 11, 12] ec = 0 for x in range(0, len(bsurfs)): tris = cubit.get_surface_tris(bsurfs[x]) surf = cubit.surface(bsurfs[x]) for y in range(0, len(tris)): cp = cubit.get_center_point("tri", tris[y]) norm = surf.normal_at([cp[0],cp[1],cp[2]]) #cubit.cmd("create curve location %f %f %f direction %f %f %f length %f" % (cp[0],cp[1],cp[2],norm[0],norm[1],norm[2],200)) nodes = cubit.get_connectivity("tri", tris[y]) element = [nodes[0]-1, nodes[1]-1, nodes[2]-1] meshFile.write(' <element id="%d" marker="%d" v0="%d" v1="%d" v2="%d" nx="%f" ny="%f" nz="%f"/>\n' % (ec,1.0,element[0],element[1],element[2],norm[0],norm[1],norm[2])) ec = ec+1 meshFile.write(' </boundary>\n') meshFile.write('</mesh>\n') meshFile.write('<poisson>\n') meshFile.write(' <neumann>\n') meshFile.write(' <node id="1" marker="1" value="0.5" />\n') meshFile.write(' </neumann>\n') meshFile.write('</poisson>\n') #meshFile.write('<electrophysiology>\n') #meshFile.write(' <stimuli number="1">\n') #bb = cubit.get_bounding_box("volume", self.vol) #x0 = bb[0] #x1 = 0.8*x0 + 0.2*bb[1] #y0 = bb[3] #y1 = 0.8*y0 + 0.2*bb[4] #z0 = bb[6] #z1 = 0.8*z0 + 0.2*bb[7] #meshFile.write(' <stim start="0.00" duration="4.00" value="-35.7140" x0="%f" x1="%f" y0="%f" y1="%f" z0="%f" z1="%f" />\n' % (x0,x1,y0,y1,z0,z1)) #meshFile.write(' </stimuli>\n') #meshFile.write('</electrophysiology>\n') meshFile.close()
stop # Writting number of elements at both sides to make # double sure everything is going fine . txt='%10i %10i\n' % (len(quads_fault_u),len(quads_fault_d)) fault_file.write(txt) dic_quads_fault_u = dict(zip(quads_fault_u,quads_fault_u)) dic_quads_fault_d = dict(zip(quads_fault_d,quads_fault_d)) # FAULT SIDE DOWN for h in list_hex: faces = cubit.get_sub_elements('hex',h,2) for f in faces: if dic_quads_fault_d.has_key(f): nodes=cubit.get_connectivity('Face',f) # print 'h,fault nodes side down :',h,nodes[0],nodes[1],nodes[2],nodes[3] txt='%10i %10i %10i %10i %10i\n' % (h,nodes[0],\ nodes[1],nodes[2],nodes[3]) fault_file.write(txt) # FAULT SIDE UP for h in list_hex: faces = cubit.get_sub_elements('hex',h,2) for f in faces: if dic_quads_fault_u.has_key(f): nodes=cubit.get_connectivity('Face',f) # print 'h,fault nodes side up :',h,nodes[0],nodes[1],nodes[2],nodes[3] txt='%10i %10i %10i %10i %10i\n' % (h,nodes[0],\ nodes[1],nodes[2],nodes[3]) fault_file.write(txt)
def abs_write(self, absname=None): # absorbing boundaries import re cubit.cmd("set info off") cubit.cmd("set echo off") cubit.cmd("set journal off") from sets import Set if not absname: absname = self.absname # # loops through all block definitions list_hex = cubit.parse_cubit_list("hex", "all") for block, flag in zip(self.block_bc, self.block_bc_flag): if block != self.topography: name = cubit.get_exodus_entity_name("block", block) print name, block absflag = False if re.search("xmin", name): filename = absname + "_xmin" normal = (-1, 0, 0) elif re.search("xmax", name): filename = absname + "_xmax" normal = (1, 0, 0) elif re.search("ymin", name): filename = absname + "_ymin" normal = (0, -1, 0) elif re.search("ymax", name): filename = absname + "_ymax" normal = (0, 1, 0) elif re.search("bottom", name): filename = absname + "_bottom" normal = (0, 0, -1) elif re.search("abs", name): # print " ...face_abs - not used so far..." filename = absname + "_all" absflag = True else: continue # opens file print "Writing " + filename + "....." abshex_local = open(filename, "w") # gets face elements quads_all = cubit.get_block_faces(block) dic_quads_all = dict(zip(quads_all, quads_all)) print " number of faces = ", len(quads_all) abshex_local.write("%10i\n" % len(quads_all)) # command = "group 'list_hex' add hex in face "+str(quads_all) # command = command.replace("["," ").replace("]"," ").replace("("," ").replace(")"," ") # cubit.cmd(command) # group=cubit.get_id_from_name("list_hex") # list_hex=cubit.get_group_hexes(group) # command = "delete group "+ str(group) # cubit.cmd(command) for h in list_hex: faces = cubit.get_sub_elements("hex", h, 2) for f in faces: if dic_quads_all.has_key(f): nodes = cubit.get_connectivity("Face", f) if not absflag: # checks with specified normal nodes_ok = self.normal_check(nodes, normal) txt = "%10i %10i %10i %10i %10i\n" % ( h, nodes_ok[0], nodes_ok[1], nodes_ok[2], nodes_ok[3], ) else: txt = "%10i %10i %10i %10i %10i\n" % (h, nodes[0], nodes[1], nodes[2], nodes[3]) abshex_local.write(txt) # closes file abshex_local.close() print "Ok" cubit.cmd("set info on") cubit.cmd("set echo on")