Exemplo n.º 1
0
def onlyvolumes():
    list_surfaces=cubit.parse_cubit_list("surface","all")
    ord_list_surfaces=ordering_surfaces(list_surfaces)
    for s1,s2 in zip(ord_list_surfaces[:-1],ord_list_surfaces[1:]):
        create_volume(s1,s2,method=None)
    cubitcommand= 'del surface all'
    cubit.cmd(cubitcommand)
    list_vol=cubit.parse_cubit_list("volume","all")
    if len(list_vol) > 1:     
        cubitcommand= 'imprint volume all'
        cubit.cmd(cubitcommand)
        cubitcommand= 'merge all'
        cubit.cmd(cubitcommand)
Exemplo n.º 2
0
def onlyvolumes():
    list_surfaces = cubit.parse_cubit_list("surface", "all")
    ord_list_surfaces = ordering_surfaces(list_surfaces)
    for s1, s2 in zip(ord_list_surfaces[:-1], ord_list_surfaces[1:]):
        create_volume(s1, s2, method=None)
    cubitcommand = 'del surface all'
    cubit.cmd(cubitcommand)
    list_vol = cubit.parse_cubit_list("volume", "all")
    if len(list_vol) > 1:
        cubitcommand = 'imprint volume all'
        cubit.cmd(cubitcommand)
        cubitcommand = 'merge all'
        cubit.cmd(cubitcommand)
Exemplo n.º 3
0
 def free_write(self, freename=None):
     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
     freehex = open(freename, 'w')
     print 'Writing ' + freename + '.....'
     #
     #
     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 'free surface (topography) 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
                         txt = self.create_facenode_string(h,
                                                           f,
                                                           normal,
                                                           cknormal=True)
                         freehex.write(txt)
             freehex.close()
         elif block == self.free:
             name = cubit.get_exodus_entity_name('block', block)
             print 'free surface 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):
                         txt = self.create_facenode_string(h,
                                                           f,
                                                           normal,
                                                           cknormal=False)
                         freehex.write(txt)
             freehex.close()
     cubit.cmd('set info on')
     cubit.cmd('set echo on')
Exemplo n.º 4
0
 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 'free surface (topography) 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
                         txt=self.create_facenode_string(h,f,normal,cknormal=True)
                         freehex.write(txt)
             freehex.close()
         elif block == self.free:
             name=cubit.get_exodus_entity_name('block',block)
             print 'free surface 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):
                         txt=self.create_facenode_string(h,f,normal,cknormal=False)
                         freehex.write(txt)
             freehex.close()
     print 'Ok'
     cubit.cmd('set info on')
     cubit.cmd('set echo on')
Exemplo n.º 5
0
 def translate2zero():
     ss=cubit.parse_cubit_list('surface','all')
     box = cubit.get_total_bounding_box("surface", ss)
     xmin=box[0]
     ymin=box[3]
     cubit.cmd('move surface all x '+str(-1*xmin)+' y '+str(-1*ymin))
     return xmin,ymin
Exemplo n.º 6
0
    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)
Exemplo n.º 7
0
 def nodescoord_write(self,nodecoord_name):
     nodecoord=open(nodecoord_name,'w')
     print 'Writing '+nodecoord_name+'.....'
     node_list=cubit.parse_cubit_list('node','all')
     # number of nodes
     num_nodes=len(node_list)
     print '  number of nodes:',str(num_nodes)
     nodecoord.write('%10i\n' % num_nodes)
     # coordinates
     for node in node_list:
         x,y,z=cubit.get_nodal_coordinates(node)
         # min/max
         self.xmin,self.xmax=self.get_extreme(x,self.xmin,self.xmax)
         self.ymin,self.ymax=self.get_extreme(y,self.ymin,self.ymax)
         self.zmin,self.zmax=self.get_extreme(z,self.zmin,self.zmax)
         if abs(x) < 1.0 and abs(y) < 1.0 and abs(z) < 1.0:
             # avoids problem w/ fixed floating point formatting for very small values
             txt=('%10i %20e %20e %20e\n') % (node,x,y,z)
         else:
             # standard float format
             txt=('%10i %20f %20f %20f\n') % (node,x,y,z)
         nodecoord.write(txt)
     nodecoord.close()
     print '  x-coordinate min/max:',str(self.xmin),str(self.xmax)
     print '  y-coordinate min/max:',str(self.ymin),str(self.ymax)
     print '  z-coordinate min/max:',str(self.zmin),str(self.zmax)
     print 'Ok'
Exemplo n.º 8
0
 def translate2zero():
     ss=cubit.parse_cubit_list('surface','all')
     box = cubit.get_total_bounding_box("surface", ss)
     xmin=box[0]
     ymin=box[3]
     cubit.cmd('move surface all x '+str(-1*xmin)+' y '+str(-1*ymin))
     return xmin,ymin
 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 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()
Exemplo n.º 11
0
 def pick_hex(self, list_hex=None, volume=None):
     if self.cubit_skew > 0:
         command = "del group skew_top"
         cubit.cmd(command)
         command = "group 'skew_top' add quality volume all skew low " + str(self.cubit_skew)
         cubit.silent_cmd(command)
         group = cubit.get_id_from_name("skew_top")
         self.list_hex = cubit.get_group_hexes(group)
     elif list_hex is not None:
         self.list_hex = list_hex
     elif volume is not None:
         command = "group 'hextmp' add hex in volume " + str(volume)
         cubit.silent_cmd(command)
         group = cubit.get_id_from_name("hextmp")
         self.list_hex = cubit.get_group_hexes(group)
         command = "del group hextmp"
         cubit.silent_cmd(command)
     elif self.volume is not None:
         command = "group 'hextmp' add hex in volume " + str(self.volume)
         cubit.silent_cmd(command)
         group = cubit.get_id_from_name("hextmp")
         self.list_hex = cubit.get_group_hexes(group)
         command = "del group hextmp"
         cubit.silent_cmd(command)
     elif list_hex is None and self.list_hex is None:
         self.list_hex = cubit.parse_cubit_list("hex", "all")
     print "list_hex: ", len(self.list_hex), " hexes"
Exemplo n.º 12
0
def computeNonlinearConstraint(x, y):
    nlcon = numpy.zeros(len(x))
    target_surface = cubit.surface(2)  # Target surface is id = 2
    vertex_on_surface = [False for i in range(0, len(x))]
    # First, determine whether the nonlinear constraint is satisfied
    for i in range(0, len(x)):
        vertex_on_surface[i] = target_surface.point_containment(
            [x[i], y[i], 0.])
    # Second, determine the magnitude of the nonlinear constraint value
    #         which is the distance of the point to the closest curve
    cid = cubit.parse_cubit_list("curve", "in vol 2")
    for i in range(0, len(x)):
        dist = numpy.zeros(len(cid))
        pXYZ = numpy.array([x[i], y[i], 0.])
        for c in range(0, len(cid)):
            C = cubit.curve(cid[c])
            cpXYZ = numpy.array(C.closest_point(pXYZ))
            dist[c] = numpy.linalg.norm(cpXYZ - pXYZ)
        if vertex_on_surface[i] == True:
            # Nonlinear constraint is satisfied
            nlcon[i] = -1. * numpy.min(dist)
        else:
            # Nonlinear constraint not satisfied
            nlcon[i] = +1. * numpy.min(dist)
    return nlcon
Exemplo n.º 13
0
def makeGeometry(x, y):
    cubit.cmd("reset")
    cubit.cmd('open "circleGeom.trelis"')

    for i in range(0, len(x)):
        cubit.cmd("create vertex " + str(x[i]) + " " + str(y[i]) +
                  " 0 on surface 1")
    V = cubit.get_list_of_free_ref_entities("vertex")
    for i in range(0, len(V)):
        cubit.cmd("imprint volume all with vertex " + str(V[i]))
    cubit.cmd("delete free vertex all")
    cubit.cmd("compress ids")
    for i in range(0, len(V)):
        cubit.cmd("nodeset 1 add vertex " + str(V[i]))
    cubit.cmd("surface all size 0.2")
    cubit.cmd("mesh surf all")
    cubit.cmd("surface all smooth scheme mean ratio cpu 0.1")
    cubit.cmd("smooth surf all")

    cubit.cmd('create group "cf_crease_entities"')
    for i in range(0, len(V)):
        ssID = cubit.get_next_sideset_id()
        N = cubit.get_vertex_node(V[i])
        nodeEdges = cubit.parse_cubit_list('edge', 'in node ' + str(N))
        for e in range(0, len(nodeEdges)):
            cubit.cmd("sideset " + str(ssID) + " add Edge " +
                      str(nodeEdges[e]))
            cubit.cmd("cf_crease_entities add Edge " + str(nodeEdges[e]))
        cubit.cmd("sideset " + str(ssID) + ' name "node_' + str(N) + '_edges"')
Exemplo n.º 14
0
 def nodescoord_write(self,nodecoord_name):
     nodecoord=open(nodecoord_name,'w')
     print 'Writing '+nodecoord_name+'.....'
     node_list=cubit.parse_cubit_list('node','all')
     # number of nodes
     num_nodes=len(node_list)
     print '  number of nodes:',str(num_nodes)
     nodecoord.write('%10i\n' % num_nodes)
     # coordinates
     for node in node_list:
         x,y,z=cubit.get_nodal_coordinates(node)
         # min/max
         self.xmin,self.xmax=self.get_extreme(x,self.xmin,self.xmax)
         self.ymin,self.ymax=self.get_extreme(y,self.ymin,self.ymax)
         self.zmin,self.zmax=self.get_extreme(z,self.zmin,self.zmax)
         if abs(x) < 1.0 and abs(y) < 1.0 and abs(z) < 1.0:
             # avoids problem w/ fixed floating point formatting for very small values
             txt=('%10i %20e %20e %20e\n') % (node,x,y,z)
         else:
             # standard float format
             txt=('%10i %20f %20f %20f\n') % (node,x,y,z)
         nodecoord.write(txt)
     nodecoord.close()
     print '  x-coordinate min/max:',str(self.xmin),str(self.xmax)
     print '  y-coordinate min/max:',str(self.ymin),str(self.ymax)
     print '  z-coordinate min/max:',str(self.zmin),str(self.zmax)
     print 'Ok'
Exemplo n.º 15
0
 def pick_hex(self, list_hex=None, volume=None):
     if self.cubit_skew > 0:
         command = "del group skew_top"
         cubit.cmd(command)
         command = "group 'skew_top' add quality volume all skew low " + str(
             self.cubit_skew)
         cubit.silent_cmd(command)
         group = cubit.get_id_from_name("skew_top")
         self.list_hex = cubit.get_group_hexes(group)
     elif list_hex is not None:
         self.list_hex = list_hex
     elif volume is not None:
         command = "group 'hextmp' add hex in volume " + str(volume)
         cubit.silent_cmd(command)
         group = cubit.get_id_from_name("hextmp")
         self.list_hex = cubit.get_group_hexes(group)
         command = "del group hextmp"
         cubit.silent_cmd(command)
     elif self.volume is not None:
         command = "group 'hextmp' add hex in volume " + str(self.volume)
         cubit.silent_cmd(command)
         group = cubit.get_id_from_name("hextmp")
         self.list_hex = cubit.get_group_hexes(group)
         command = "del group hextmp"
         cubit.silent_cmd(command)
     elif list_hex is None and self.list_hex is None:
         self.list_hex = cubit.parse_cubit_list('hex', 'all')
     print 'list_hex: ', len(self.list_hex), ' hexes'
Exemplo n.º 16
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 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')
Exemplo n.º 18
0
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()
Exemplo n.º 19
0
def collecting_cpml(ip,size=None,cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1,cubfiles=False,decimate=False,layers=2):
    import glob
    import re
    from utilities import list2str
    #
    if not size:
        print 'cpml size must be specified'
        return
        
        
    boundary_dict={}
    ##
    try:
        from boundary_definition import check_bc, map_boundary, define_surf
    except:
        pass
    #
    xmin,xmax,ymin,ymax,listfull=map_boundary(cpuxmin,cpuxmax,cpuymin,cpuymax,cpux,cpuy)
    #
    if cubfiles:        
        nf,listip,filenames,cubflag=importing_cubfiles(cubfiles)
    else:
        nf=0
        filenames=[]
        ip=0
    #
    if nf > 0:
        for ip,filename in zip(listip,filenames):
            try:
                if ip in listfull:
                    if cubflag:
                        cubit.cmd('import cubit "'+filename+'"')
                    else:
                        cubit.cmd('import mesh geometry "'+filename+'" block all use nodeset sideset feature_angle 135.00 linear merge')
                    if decimate: cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
            except:
                cubit.cmd('import mesh geometry "'+filename+'" block all use nodeset sideset feature_angle 135.00 linear merge')
                if decimate: cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
                ip=0
        if decimate: cubit.cmd('export mesh "decimated_before_cmpl.e" dimension 3 block all overwrite')
    else:
        if decimate: 
            cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
            cubit.cmd('export mesh "decimated_before_cmpl.e" dimension 3 block all overwrite')

    
    #
    #
    #print boundary_dict
    block_list=cubit.get_block_id_list()
    for block in block_list:
        ty=cubit.get_block_element_type(block)
        if ty == 'HEX8':
            cubit.cmd('block '+str(block)+' name "vol'+str(block)+'"')
            
    list_vol=list(cubit.parse_cubit_list('volume','all'))
    create_pml(xmin=xmin,xmax=xmax,ymax=ymax,ymin=ymin,zmin=zmin,zmax=zmax,size=size,layers=layers,vol=list_vol)
Exemplo n.º 20
0
def collecting_cpml(ip,size=None,cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1,cubfiles=False,decimate=False,layers=2):
    import glob
    import re
    from utilities import list2str
    #
    if not size:
        print 'cpml size must be specified'
        return


    boundary_dict={}
    ##
    try:
        from boundary_definition import check_bc, map_boundary, define_surf
    except:
        pass
    #
    xmin,xmax,ymin,ymax,listfull=map_boundary(cpuxmin,cpuxmax,cpuymin,cpuymax,cpux,cpuy)
    #
    if cubfiles:
        nf,listip,filenames,cubflag=importing_cubfiles(cubfiles)
    else:
        nf=0
        filenames=[]
        ip=0
    #
    if nf > 0:
        for ip,filename in zip(listip,filenames):
            try:
                if ip in listfull:
                    if cubflag:
                        cubit.cmd('import cubit "'+filename+'"')
                    else:
                        cubit.cmd('import mesh geometry "'+filename+'" block all use nodeset sideset feature_angle 135.00 linear merge')
                    if decimate: cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
            except:
                cubit.cmd('import mesh geometry "'+filename+'" block all use nodeset sideset feature_angle 135.00 linear merge')
                if decimate: cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
                ip=0
        if decimate: cubit.cmd('export mesh "decimated_before_cmpl.e" dimension 3 block all overwrite')
    else:
        if decimate:
            cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
            cubit.cmd('export mesh "decimated_before_cmpl.e" dimension 3 block all overwrite')


    #
    #
    #print boundary_dict
    block_list=cubit.get_block_id_list()
    for block in block_list:
        ty=cubit.get_block_element_type(block)
        if ty == 'HEX8':
            cubit.cmd('block '+str(block)+' name "vol'+str(block)+'"')

    list_vol=list(cubit.parse_cubit_list('volume','all'))
    create_pml(xmin=xmin,xmax=xmax,ymax=ymax,ymin=ymin,zmin=zmin,zmax=zmax,size=size,layers=layers,vol=list_vol)
Exemplo n.º 21
0
def define_4side_lateral_surfaces(tres=0.0003, tol=0.000001):
    list_vol = cubit.parse_cubit_list("volume", "all")
    surf_xmin = []
    surf_ymin = []
    surf_xmax = []
    surf_ymax = []

    # min/max of bounding box
    xmin_box = cubit.get_total_bounding_box("volume", list_vol)[0]
    xmax_box = cubit.get_total_bounding_box("volume", list_vol)[1]
    ymin_box = cubit.get_total_bounding_box("volume", list_vol)[3]
    ymax_box = cubit.get_total_bounding_box("volume", list_vol)[4]
    zmin_box = cubit.get_total_bounding_box("volume", list_vol)[6]
    zmax_box = cubit.get_total_bounding_box("volume", list_vol)[7]
    #print('absorbing boundary xmin:' + str(xmin_box) + ' xmax: ' + str(xmax_box))
    #print('absorbing boundary ymin:' + str(ymin_box) + ' ymax: ' + str(ymax_box))
    #print('absorbing boundary zmin:' + str(zmin_box) + ' zmax: ' + str(zmax_box))

    for id_vol in list_vol:
        surf_vertical = []
        xsurf = []
        ysurf = []
        lsurf = cubit.get_relatives("volume", id_vol, "surface")
        for k in lsurf:
            normal = cubit.get_surface_normal(k)
            # checks if normal is horizontal (almost 0, i.e., +/- tres)
            if normal[2] >= -1 * tres and normal[2] <= tres:
                # checks if surface is on minimum/maximum side of the whole model
                center_point = cubit.get_center_point("surface", k)
                # note: for models with smaller volumes inscribed, we want only the outermost surfaces
                #       as absorbing ones
                #sbox = cubit.get_bounding_box('surface', k)
                # xmin of surface box relative to total box xmin
                if (abs(center_point[0] - xmin_box) / abs(xmax_box - xmin_box) <= tol) or \
                   (abs(center_point[0] - xmax_box) / abs(xmax_box - xmin_box) <= tol) or \
                   (abs(center_point[1] - ymin_box) / abs(ymax_box - ymin_box) <= tol) or \
                   (abs(center_point[1] - ymax_box) / abs(ymax_box - ymin_box) <= tol):
                    # adds as vertical surface
                    surf_vertical.append(k)
                    xsurf.append(center_point[0])
                    ysurf.append(center_point[1])
        # adds surfaces when on boundary
        if len(surf_vertical) > 0:
            surf_xmin.append(surf_vertical[xsurf.index(min(xsurf))])
            surf_ymin.append(surf_vertical[ysurf.index(min(ysurf))])
            surf_xmax.append(surf_vertical[xsurf.index(max(xsurf))])
            surf_ymax.append(surf_vertical[ysurf.index(max(ysurf))])
    #debug
    #print('define_4side_lateral_surfaces: xmin ',surf_xmin)
    #print('define_4side_lateral_surfaces: xmax ',surf_xmax)
    #print('define_4side_lateral_surfaces: ymin ',surf_ymin)
    #print('define_4side_lateral_surfaces: ymax ',surf_ymax)
    return surf_xmin, surf_ymin, surf_xmax, surf_ymax
Exemplo n.º 22
0
 def write_node(self, path):
     f = open(path + self.filename_nodes, 'w')
     nodes = cubit.parse_cubit_list('node', 'all')
     nnodes = len(nodes)
     print "writing node coordinates file '" + path + self.filename_nodes + "' containing " + str(
         nnodes) + " nodes"
     f.write('%10i\n' % nnodes)
     #
     for node in nodes:
         xyz = cubit.get_nodal_coordinates(node)
         f.write('%20f %20f %20f\n' % xyz)
     f.close()
Exemplo n.º 23
0
 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
Exemplo n.º 24
0
 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
Exemplo n.º 25
0
 def nodescoord_write(self,nodecoord_name):
     """ Write nodes coordinates on file : nodecoord_name """ 
     nodecoord = open(nodecoord_name,'w')
     print 'Writing '+nodecoord_name+'.....'
     node_list = cubit.parse_cubit_list('node','all') # Import all the nodes of the model
     num_nodes = len(node_list) # Total number of nodes
     nodecoord.write('%10i\n' % num_nodes) # Write the number of nodes on the first line
     for node in node_list: # For all nodes
         x,y,z = cubit.get_nodal_coordinates(node) # Import its coordinates (3 coordinates even for a 2D model in cubit) 
         txt = ('%20f %20f\n') % (x,z) 
         nodecoord.write(txt) # Write x and z coordinates on the file -> Model must be in x,z coordinates. TODO
     nodecoord.close()
     print 'Ok'
Exemplo n.º 26
0
 def nodescoord_write(self,nodecoord_name):
     nodecoord=open(nodecoord_name,'w')
     print 'Writing '+nodecoord_name+'.....'
     node_list=cubit.parse_cubit_list('node','all')
     num_nodes=len(node_list)
     print '  number of nodes:',str(num_nodes)
     nodecoord.write('%10i\n' % num_nodes)
     #
     for node in node_list:
         x,y,z=cubit.get_nodal_coordinates(node)
         txt=('%10i %20f %20f %20f\n') % (node,x,y,z)
         nodecoord.write(txt)
     nodecoord.close()
Exemplo n.º 27
0
 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
Exemplo n.º 28
0
 def nodescoord_write(self, nodecoord_name):
     nodecoord = open(nodecoord_name, "w")
     print "Writing " + nodecoord_name + "....."
     node_list = cubit.parse_cubit_list("node", "all")
     num_nodes = len(node_list)
     print "  number of nodes:", str(num_nodes)
     nodecoord.write("%10i\n" % num_nodes)
     #
     for node in node_list:
         x, y, z = cubit.get_nodal_coordinates(node)
         txt = ("%10i %20f %20f %20f\n") % (node, x, y, z)
         nodecoord.write(txt)
     nodecoord.close()
     print "Ok"
 def nodescoord_write(self, nodecoord_name):
     nodecoord = open(nodecoord_name, 'w')
     print 'Writing ' + nodecoord_name + '.....'
     node_list = cubit.parse_cubit_list('node', 'all')
     num_nodes = len(node_list)
     print '  number of nodes:', str(num_nodes)
     nodecoord.write('%10i\n' % num_nodes)
     #
     for node in node_list:
         x, y, z = cubit.get_nodal_coordinates(node)
         txt = ('%10i %20f %20f %20f\n') % (node, x, y, z)
         nodecoord.write(txt)
     nodecoord.close()
     print 'Ok'
def define_block():
    try:
            cubit.cmd('comment')
    except:
            try:
                import cubit
                cubit.init([""])
            except:
                print 'error importing cubit'
                import sys
                sys.exit()
    list_vol=cubit.parse_cubit_list("volume","all")
    init_n_vol=len(list_vol)
    list_name=map(lambda x: 'vol'+x,map(str,list_vol))
    return list_vol,list_name
def define_block():
    try:
        cubit.cmd('comment')
    except:
        try:
            import cubit
            cubit.init([""])
        except:
            print 'error importing cubit'
            import sys
            sys.exit()
    list_vol = cubit.parse_cubit_list("volume", "all")
    init_n_vol = len(list_vol)
    list_name = map(lambda x: 'vol' + x, map(str, list_vol))
    return list_vol, list_name
Exemplo n.º 32
0
 def coord_write(self, coord_name):
     ''' write nodes file '''
     coord = open(coord_name, 'w')
     print('writing ' + coord_name)
     node_list = cubit.parse_cubit_list('node', 'all')
     ncoord = len(node_list)
     print('number of nodes:', str(ncoord))
     # write ncoord
     coord.write('%10i\n' % ncoord)
     #write coords
     for node in node_list:
         x, y, z = cubit.get_nodal_coordinates(node)
         txt = ('%10i %20f %20f\n') % (node, x, y)
         coord.write(txt)
     coord.close()
     print('Ok')
def define_absorbing_surf_sphere():
    try:
        cubit.cmd('comment')
    except:
        try:
            import cubit
            cubit.init([""])
        except:
            print 'error importing cubit'
            import sys
            sys.exit()
    surf = []
    list_surf = cubit.parse_cubit_list("surface", "all")
    for s in list_surf:
        v = cubit.get_relatives('surface', s, 'volume')
        if len(v) == 1:
            surf.append(s)
    return surf
def define_absorbing_surf_sphere():
    try:
        cubit.cmd('comment')
    except:
        try:
            import cubit
            cubit.init([""])
        except:
            print 'error importing cubit'
            import sys
            sys.exit()
    surf=[]
    list_surf=cubit.parse_cubit_list("surface","all")
    for s in list_surf:
       v=cubit.get_relatives('surface',s,'volume')
       if len(v) == 1:
           surf.append(s)
    return surf
 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'
Exemplo n.º 37
0
    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"
Exemplo n.º 38
0
def define_block():
    """
     Renumbering number of volumes from 1 to NVOLUMES.
    """
    try:
        cubit.cmd('comment')
    except:
        try:
            import cubit
            cubit.init([""])
        except:
            print('error importing cubit')
            import sys
            sys.exit()
    list_vol = cubit.parse_cubit_list("volume", "all")
    #print("# define block: ",list_vol)
    init_n_vol = len(list_vol)
    list_name = map(lambda x: 'vol' + x, map(str, list_vol))
    return list_vol, list_name
Exemplo n.º 39
0
    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 define_4side_lateral_surfaces():
    list_vol=cubit.parse_cubit_list("volume","all")
    surf_xmin=[]
    surf_ymin=[]
    surf_xmax=[]
    surf_ymax=[]
    for id_vol in list_vol:
        surf_vertical=[]
        xsurf=[]
        ysurf=[]
        tres=0.3
        lsurf=cubit.get_relatives("volume",id_vol,"surface")
        for k in lsurf:
            normal=cubit.get_surface_normal(k)
            center_point = cubit.get_center_point("surface", k)
            if normal[2] >= -1*tres and normal[2] <= tres:
                surf_vertical.append(k)
                xsurf.append(center_point[0])
                ysurf.append(center_point[1])
        surf_xmin.append(surf_vertical[xsurf.index(min(xsurf))])
        surf_ymin.append(surf_vertical[ysurf.index(min(ysurf))])
        surf_xmax.append(surf_vertical[xsurf.index(max(xsurf))])
        surf_ymax.append(surf_vertical[ysurf.index(max(ysurf))])
    return surf_xmin,surf_ymin,surf_xmax,surf_ymax
Exemplo n.º 41
0
def define_4side_lateral_surfaces():
    list_vol = cubit.parse_cubit_list("volume", "all")
    surf_xmin = []
    surf_ymin = []
    surf_xmax = []
    surf_ymax = []
    for id_vol in list_vol:
        surf_vertical = []
        xsurf = []
        ysurf = []
        tres = 0.3
        lsurf = cubit.get_relatives("volume", id_vol, "surface")
        for k in lsurf:
            normal = cubit.get_surface_normal(k)
            center_point = cubit.get_center_point("surface", k)
            if normal[2] >= -1 * tres and normal[2] <= tres:
                surf_vertical.append(k)
                xsurf.append(center_point[0])
                ysurf.append(center_point[1])
        surf_xmin.append(surf_vertical[xsurf.index(min(xsurf))])
        surf_ymin.append(surf_vertical[ysurf.index(min(ysurf))])
        surf_xmax.append(surf_vertical[xsurf.index(max(xsurf))])
        surf_ymax.append(surf_vertical[ysurf.index(max(ysurf))])
    return surf_xmin, surf_ymin, surf_xmax, surf_ymax
Exemplo n.º 42
0
########### SIDESETS (NOT USED ) ###############
#fault_A_elements_up="sideset 200 surface 2"
#fault_A_elements_down="sideset 201 surface 3"
#cubit.cmd(fault_A_elements_up)
#cubit.cmd(fault_A_elements_down)

########### Fault elements and nodes ###############

os.system('mkdir -p MESH') 

fault_u = 2  # fault surface up   : surface 2
fault_d = 3  # fault surface down : surface 3
txt =''

fault_file=open('MESH/fault_file_1.dat','w')
list_hex=cubit.parse_cubit_list('hex','all')

quads_fault_u = cubit.get_surface_quads(fault_u)
quads_fault_d = cubit.get_surface_quads(fault_d)

# TO DO : stop python properly in case fault nodes at both sides
#         do not match.
if len(quads_fault_u) != len(quads_fault_d):
   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)) 
cubit.cmd('volume 1 move x '+str(center_xy[0])+' y '+str(center_xy[1])+' z '+str(water_thickness/2.0)) # water layer
cubit.cmd('volume 2 move x '+str(center_xy[0])+' y '+str(center_xy[1])+' z -'+str(zL/2.0)) # solid
cubit.cmd('merge all')

# Meshing the volumes
elementsize = [100.0, 100.0]

cubit.cmd('volume 1 size '+str(elementsize[0]))
#cubit.cmd('mesh volume 1')
cubit.cmd('volume 2 size '+str(elementsize[1]))
cubit.cmd('mesh volume 1 2')

#### End of meshing 


node_list=cubit.parse_cubit_list('node','all')
print node_list[0]

###### This is boundary_definition.py of GEOCUBIT
#..... which extracts the bounding faces and defines them into blocks
boundary_definition.entities=['face']
boundary_definition.define_bc(boundary_definition.entities,parallel=True)

#### Define material properties for the 3 volumes ################
cubit.cmd('#### DEFINE MATERIAL PROPERTIES #######################')

cubit.cmd('block 1 name "acoustic 1" ')
cubit.cmd('block 1 attribute count 4')
cubit.cmd('block 1 attribute index 1 1')
cubit.cmd('block 1 attribute index 2 '+str(water_vp))   
cubit.cmd('block 1 attribute index 3 '+str(water_vs))   
Exemplo n.º 44
0
def collecting_merging(cpuxmin=0,
                       cpuxmax=1,
                       cpuymin=0,
                       cpuymax=1,
                       cpux=1,
                       cpuy=1,
                       cubfiles=False,
                       ckbound_method1=False,
                       ckbound_method2=False,
                       merge_tolerance=None,
                       decimate=False):
    import glob
    import re
    #
    rule_st = re.compile("(.+)_[0-9]+\.")
    rule_ex = re.compile(".+_[0-9]+\.(.+)")
    rule_int = re.compile(".+_([0-9]+)\.")
    boundary_dict = {}
    ##
    try:
        from boundary_definition import check_bc, map_boundary
    except:
        pass
    #
    xmin, xmax, ymin, ymax, listfull = map_boundary(cpuxmin, cpuxmax, cpuymin,
                                                    cpuymax, cpux, cpuy)
    #
    if cubfiles:
        nf, listip, filenames, cubflag = importing_cubfiles(cubfiles)
    else:
        nf = 0
        filenames = []
        ip = 0
    #
    if nf > 0:
        for ip, filename in zip(listip, filenames):
            try:
                if ip in listfull:
                    if cubflag:
                        cubit.cmd('import cubit "' + filename + '"')
                    else:
                        cubit.cmd(
                            'import mesh geometry "' + filename +
                            '" block all use nodeset sideset feature_angle 135.00 linear merge'
                        )
                    if decimate:
                        cubit.cmd(
                            'refine volume all numsplit 1 bias 1.0 depth 1 ')
                    boundary = check_bc(ip, xmin, xmax, ymin, ymax, cpux, cpuy,
                                        cpuxmin, cpuxmax, cpuymin, cpuymax)
                    boundary_dict[ip] = boundary
                    list_vol = list(cubit.parse_cubit_list('volume', 'all'))
                    for v in list_vol:
                        cubit.cmd("disassociate mesh from volume " + str(v))
                        command = "del vol " + str(v)
                        cubit.cmd(command)
            except:
                cubit.cmd(
                    'import mesh geometry "' + filename +
                    '" block all use nodeset sideset feature_angle 135.00 linear merge'
                )
                if decimate:
                    cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
                ip = 0
                boundary = check_bc(ip, xmin, xmax, ymin, ymax, cpux, cpuy,
                                    cpuxmin, cpuxmax, cpuymin, cpuymax)
                boundary_dict[ip] = boundary
                list_vol = list(cubit.parse_cubit_list('volume', 'all'))
                for v in list_vol:
                    cubit.cmd("disassociate mesh from volume " + str(v))
                    command = "del vol " + str(v)
                    cubit.cmd(command)
        cubit.cmd(
            'export mesh "tmp_collect_NOmerging.e" dimension 3 block all overwrite'
        )
    else:
        if decimate:
            cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
        boundary = check_bc(ip, xmin, xmax, ymin, ymax, cpux, cpuy, cpuxmin,
                            cpuxmax, cpuymin, cpuymax)
    #
    #
    #print boundary_dict
    block_list = cubit.get_block_id_list()
    for block in block_list:
        ty = cubit.get_block_element_type(block)
        if ty == 'HEX8':
            cubit.cmd('block ' + str(block) + ' name "vol' + str(block) + '"')
    #
    #
    print 'chbound', ckbound_method1, ckbound_method2

    if ckbound_method1 and not ckbound_method2 and len(filenames) != 1:
        #use the equivalence method for groups
        if isinstance(merge_tolerance, list):
            tol = merge_tolerance[0]
        elif merge_tolerance:
            tol = merge_tolerance
        else:
            tol = 100000
        #
        idiag = None
        #cubit.cmd('set info off')
        #cubit.cmd('set journal off')
        #cubit.cmd('set echo off')
        ind = 0
        for ix in range(cpuxmin, cpuxmax):
            for iy in range(cpuymin, cpuymax):
                ind = ind + 1
                ip = iy * cpux + ix
                print '******************* ', ip, ind, '/', len(listfull)
                #
                #   ileft    |   ip
                #  --------------------
                #   idiag    |   idown
                #
                #
                if ip not in xmin and ip not in ymin:
                    ileft = iy * cpux + ix - 1
                    idown = (iy - 1) * cpux + ix
                    idiag = idown - 1
                elif ip in xmin and ip in ymin:
                    ileft = ip
                    idown = ip
                    idiag = None
                elif ip in xmin:
                    ileft = ip
                    idown = (iy - 1) * cpux + ix
                    idiag = idown
                elif ip in ymin:
                    ileft = iy * cpux + ix - 1
                    idown = ip
                    idiag = ileft
                #
                print ip, ileft, idiag, idown
                if ip != idown:
                    nup = boundary_dict[ip]['nodes_surf_ymin']
                    ndow = boundary_dict[idown]['nodes_surf_ymax']
                    merge_node_ck(nup, ndow)

                    if idiag != idown:
                        if ip in ymax and ip not in xmin:
                            nlu = boundary_dict[ip][
                                'node_curve_xminymax']  #node in curve chunck left up... r u
                            nru = boundary_dict[ileft]['node_curve_xmaxymax']
                            merge_node(nlu, nru)
                        if ip in xmax:
                            nrd = boundary_dict[ip][
                                'node_curve_xmaxymin']  #node in curve chunck left up... r u
                            nru = boundary_dict[idown]['node_curve_xmaxymax']
                            merge_node(nrd, nru)
                        nru = boundary_dict[ip][
                            'node_curve_xminymin']  #node in curve chunck right up... r u
                        nrd = boundary_dict[idown]['node_curve_xminymax']
                        nld = boundary_dict[idiag]['node_curve_xmaxymax']
                        nlu = boundary_dict[ileft]['node_curve_xmaxymin']
                        merge_node_4(nru, nrd, nld, nlu)
                    elif ip in xmin:
                        nlu = boundary_dict[ip][
                            'node_curve_xminymin']  #node in curve chunck right up... r u
                        nld = boundary_dict[idown]['node_curve_xminymax']
                        merge_node(nld, nlu)
                        nru = boundary_dict[ip][
                            'node_curve_xmaxymin']  #node in curve chunck right up... r u
                        nrd = boundary_dict[idown]['node_curve_xmaxymax']
                        merge_node(nrd, nru)

                #
                if ip != ileft:
                    nright = boundary_dict[ip]['nodes_surf_xmin']
                    nleft = boundary_dict[ileft]['nodes_surf_xmax']
                    merge_node_ck(nright, nleft)
                    #
                    #
                    if ip in ymin:
                        nrd = boundary_dict[ip][
                            'node_curve_xminymin']  #node in curve chunck right down... r u
                        nld = boundary_dict[ileft]['node_curve_xmaxymin']
                        merge_node(nrd, nld)
                    if ip in ymax:
                        nru = boundary_dict[ip][
                            'node_curve_xminymax']  #node in curve chunck right up... r u
                        nlu = boundary_dict[ileft]['node_curve_xmaxymax']
                        merge_node(nlu, nru)

        cubit.cmd('set info on')
        cubit.cmd('set echo on')
        cubit.cmd('set journal on')

        #
        #
        cmd = 'group "negativejac" add quality hex all Jacobian high'
        cubit.cmd(cmd)
        group_id_1 = cubit.get_id_from_name("negativejac")
        n1 = cubit.get_group_nodes(group_id_1)
        if len(n1) != 0:
            print 'error, negative jacobian after the equivalence node command, use --merge2 instead of --equivalence/--merge/--merge1'
    elif ckbound_method2 and not ckbound_method1 and len(filenames) != 1:
        if isinstance(merge_tolerance, list):
            tol = merge_tolerance[0]
        elif merge_tolerance:
            tol = merge_tolerance
        else:
            tol = 100000
        #
        idiag = None
        for ix in range(cpuxmin, cpuxmax):
            for iy in range(cpuymin, cpuymax):
                ip = iy * cpux + ix
                print '******************* ', ip
                #
                #   ileft    |   ip
                #  --------------------
                #   idiag    |   idown
                #
                #
                if ip not in xmin and ip not in ymin:
                    ileft = iy * cpux + ix - 1
                    idown = (iy - 1) * cpux + ix
                    idiag = idown - 1
                elif ip in xmin and ip in ymin:
                    ileft = ip
                    idown = ip
                elif ip in xmin:
                    ileft = ip
                    idown = (iy - 1) * cpux + ix
                    idiag = idown
                elif ip in ymin:
                    ileft = iy * cpux + ix - 1
                    idown = ip
                    idiag = ileft
                #
                #
                if ip != idown:
                    nup = boundary_dict[ip]['nodes_surf_ymin']
                    ndow = boundary_dict[idown]['nodes_surf_ymax']
                    for n1, n2 in zip(nup, ndow):
                        cubit.cmd('equivalence node ' + str(n1) + ' ' +
                                  str(n2) + ' tolerance ' + str(tol))
                    if idiag != idown:
                        if ip in ymax and ip not in xmin:
                            nlu = boundary_dict[ip][
                                'node_curve_xminymax']  #node in curve chunck left up... r u
                            nru = boundary_dict[ileft]['node_curve_xmaxymax']
                            for n in zip(nlu, nru):
                                cubit.cmd('equivalence node ' +
                                          ' '.join(str(x) for x in n) +
                                          ' tolerance ' + str(tol))
                        nru = boundary_dict[ip][
                            'node_curve_xminymin']  #node in curve chunck right up... r u
                        nrd = boundary_dict[idown]['node_curve_xminymax']
                        nld = boundary_dict[idiag]['node_curve_xmaxymax']
                        nlu = boundary_dict[ileft]['node_curve_xmaxymin']
                        for n in zip(nru, nrd, nlu, nld):
                            cubit.cmd('equivalence node ' +
                                      ' '.join(str(x) for x in n) +
                                      ' tolerance ' + str(tol))
                    elif ip in xmin:
                        nru = boundary_dict[ip][
                            'node_curve_xminymin']  #node in curve chunck right up... r u
                        nrd = boundary_dict[idown]['node_curve_xminymax']
                        for n in zip(nru, nrd):
                            cubit.cmd('equivalence node ' +
                                      ' '.join(str(x) for x in n) +
                                      ' tolerance ' + str(tol))
                #
                #
                if ip != ileft:
                    nright = boundary_dict[ip]['nodes_surf_xmin']
                    nleft = boundary_dict[ileft]['nodes_surf_xmax']
                    for n1, n2 in zip(nleft, nright):
                        cubit.cmd('equivalence node ' + str(n1) + ' ' +
                                  str(n2) + ' tolerance ' + str(tol))
                    #
                    #
                    if ip in ymin:
                        nrd = boundary_dict[ip][
                            'node_curve_xminymin']  #node in curve chunck right down... r u
                        nld = boundary_dict[ileft]['node_curve_xmaxymin']
                        for n in zip(nrd, nld):
                            cubit.cmd('equivalence node ' +
                                      ' '.join(str(x) for x in n) +
                                      ' tolerance ' + str(tol))
                    if ip in ymax:
                        nru = boundary_dict[ip][
                            'node_curve_xminymax']  #node in curve chunck right up... r u
                        nlu = boundary_dict[ileft]['node_curve_xmaxymax']
                        for n in zip(nru, nlu):
                            cubit.cmd('equivalence node ' +
                                      ' '.join(str(x) for x in n) +
                                      ' tolerance ' + str(tol))
        #
        #
        cmd = 'topology check coincident node face all tolerance ' + str(
            tol * 2) + ' nodraw brief result group "checkcoinc"'
        cubit.silent_cmd(cmd)
        group_id_1 = cubit.get_id_from_name("checkcoinc")
        if group_id_1 != 0:
            n1 = cubit.get_group_nodes(group_id_1)
            if len(n1) != 0:
                print 'error, coincident nodes after the equivalence node command, check the tolerance'
                import sys
                sys.exit()
        cmd = 'group "negativejac" add quality hex all Jacobian high'
        cubit.cmd(cmd)
        group_id_1 = cubit.get_id_from_name("negativejac")
        n1 = cubit.get_group_nodes(group_id_1)
        if len(n1) != 0:
            print 'error, negative jacobian after the equivalence node command, check the mesh'
    elif ckbound_method1 and ckbound_method2 and len(filenames) != 1:
        block_list = cubit.get_block_id_list()
        i = -1
        for block in block_list:
            ty = cubit.get_block_element_type(block)
            if ty == 'HEX8':
                i = i + 1
                if isinstance(merge_tolerance, list):
                    try:
                        tol = merge_tolerance[i]
                    except:
                        tol = merge_tolerance[-1]
                elif merge_tolerance:
                    tol = merge_tolerance
                else:
                    tol = 1
                cmd = 'topology check coincident node face in hex in block ' + str(
                    block) + ' tolerance ' + str(
                        tol) + ' nodraw brief result group "b' + str(
                            block) + '"'
                cubit.cmd(cmd)
                print cmd
                cmd = 'equivalence node in group b' + str(
                    block) + ' tolerance ' + str(tol)
                cubit.cmd(cmd)
                print cmd
        if isinstance(merge_tolerance, list):
            tol = max(merge_tolerance)
        elif merge_tolerance:
            tol = merge_tolerance
        else:
            tol = 1
        #
        #
        cmd = 'topology check coincident node face all tolerance ' + str(
            tol) + ' nodraw brief result group "checkcoinc"'
        cubit.silent_cmd(cmd)
        group_id_1 = cubit.get_id_from_name("checkcoinc")
        if group_id_1 != 0:
            n1 = cubit.get_group_nodes(group_id_1)
            if len(n1) != 0:
                print 'error, coincident nodes after the equivalence node command, check the tolerance'
                import sys
                sys.exit()
        cmd = 'group "negativejac" add quality hex all Jacobian high'
        cubit.silent_cmd(cmd)
        group_id_1 = cubit.get_id_from_name("negativejac")
        n1 = cubit.get_group_nodes(group_id_1)
        if len(n1) != 0:
            print 'error, negative jacobian after the equivalence node command, use --merge instead of --equivalence'
def define_absorbing_surf():
    """
    define the absorbing surfaces for a layered topological box where boundary are surfaces parallel to the axis.
    it returns absorbing_surf,absorbing_surf_xmin,absorbing_surf_xmax,absorbing_surf_ymin,absorbing_surf_ymax,absorbing_surf_bottom,topo_surf
    where
    absorbing_surf is the list of all the absorbing boundary surf
    absorbing_surf_xmin is the list of the absorbing boundary surfaces that correnspond to x=xmin
    ...
    absorbing_surf_bottom is the list of the absorbing boundary surfaces that correspond to z=zmin
    """
    try:
        cubit.cmd('comment')
    except:
        try:
            import cubit
            cubit.init([""])
        except:
            print 'error importing cubit'
            import sys
            sys.exit()
    absorbing_surf=[]
    absorbing_surf_xmin=[]
    absorbing_surf_xmax=[]
    absorbing_surf_ymin=[]
    absorbing_surf_ymax=[]
    absorbing_surf_bottom=[]
    top_surf=[]


    list_vol=cubit.parse_cubit_list("volume","all")
    init_n_vol=len(list_vol)
    zmax_box=cubit.get_total_bounding_box("volume",list_vol)[7]
    zmin_box=cubit.get_total_bounding_box("volume",list_vol)[6] #it is the z_min of the box ... box= xmin,xmax,d,ymin,ymax,d,zmin...
    xmin_box=cubit.get_total_bounding_box("volume",list_vol)[0]
    xmax_box=cubit.get_total_bounding_box("volume",list_vol)[1]
    ymin_box=cubit.get_total_bounding_box("volume",list_vol)[3]
    ymax_box=cubit.get_total_bounding_box("volume",list_vol)[4]
    list_surf=cubit.parse_cubit_list("surface","all")
#    for k in list_surf:
#        center_point = cubit.get_center_point("surface", k)
#        if abs((center_point[0] - xmin_box)/xmin_box) <= 0.005:
#             absorbing_surf_xmin.append(k)
#             absorbing_surf.append(k)
#        elif abs((center_point[0] - xmax_box)/xmax_box) <= 0.005:
#             absorbing_surf_xmax.append(k)
#             absorbing_surf.append(k)
#        elif abs((center_point[1] - ymin_box)/ymin_box) <= 0.005:
#             absorbing_surf_ymin.append(k)
#             absorbing_surf.append(k)
#        elif abs((center_point[1] - ymax_box)/ymax_box) <= 0.005:
#             absorbing_surf_ymax.append(k)
#             absorbing_surf.append(k)
#        elif abs((center_point[2] - zmin_box)/zmin_box) <= 0.005:
#             absorbing_surf_bottom.append(k)
#             absorbing_surf.append(k)
#        else:
#            sbox=cubit.get_bounding_box('surface',k)
#            dz=abs((sbox[7] - zmax_box)/zmax_box)
#            normal=cubit.get_surface_normal(k)
#            zn=normal[2]
#            dn=abs(zn-1)
#            if dz <= 0.001 and dn < 0.2:
#                top_surf.append(k)

    #box lengths
    x_len = abs( xmax_box - xmin_box)
    y_len = abs( ymax_box - ymin_box)
    z_len = abs( zmax_box - zmin_box)

    print '##boundary box: '
    print '##  x length: ' + str(x_len)
    print '##  y length: ' + str(y_len)
    print '##  z length: ' + str(z_len)

    # tolerance parameters
    absorbing_surface_distance_tolerance=0.005
    topographic_surface_distance_tolerance=0.001
    topographic_surface_normal_tolerance=0.2

    for k in list_surf:
        center_point = cubit.get_center_point("surface", k)
        if abs((center_point[0] - xmin_box)/x_len) <= absorbing_surface_distance_tolerance:
             absorbing_surf_xmin.append(k)
             absorbing_surf.append(k)
        elif abs((center_point[0] - xmax_box)/x_len) <= absorbing_surface_distance_tolerance:
             absorbing_surf_xmax.append(k)
             absorbing_surf.append(k)
        elif abs((center_point[1] - ymin_box)/y_len) <= absorbing_surface_distance_tolerance:
             absorbing_surf_ymin.append(k)
             absorbing_surf.append(k)
        elif abs((center_point[1] - ymax_box)/y_len) <= absorbing_surface_distance_tolerance:
             absorbing_surf_ymax.append(k)
             absorbing_surf.append(k)
        elif abs((center_point[2] - zmin_box)/z_len) <= absorbing_surface_distance_tolerance:
             absorbing_surf_bottom.append(k)
             absorbing_surf.append(k)
        else:
            sbox=cubit.get_bounding_box('surface',k)
            dz=abs((sbox[7] - zmax_box)/z_len)
            normal=cubit.get_surface_normal(k)
            zn=normal[2]
            dn=abs(zn-1)
            if dz <= topographic_surface_distance_tolerance and dn < topographic_surface_normal_tolerance:
                top_surf.append(k)

    return absorbing_surf,absorbing_surf_xmin,absorbing_surf_xmax,absorbing_surf_ymin,absorbing_surf_ymax,absorbing_surf_bottom,top_surf
Exemplo n.º 46
0
def layercake_volume_fromacis_mpiregularmap(filename=None):
    import sys
    import start as start
    #
    mpiflag,iproc,numproc,mpi   = start.start_mpi()
    #
    cfg                         = start.start_cfg(filename=filename)                       
    #
    from utilities import geo2utm, savegeometry
    #
    from math import sqrt
    #
    try:
        mpi.barrier()
    except:
        pass
    #
    #
    command = "comment '"+"PROC: "+str(iproc)+"/"+str(numproc)+" '"
    cubit.cmd(command)
    #
    #get the limit of the volume considering the cpu
    def xwebcut(x):
        command='create planar surface with plane xplane offset '+str(x)
        cubit.cmd(command)
        last_surface=cubit.get_last_id("surface")
        command="webcut volume all tool volume in surf "+str(last_surface)
        cubit.cmd(command)
        command="del surf "+str(last_surface)
        cubit.cmd(command)
        
    def ywebcut(x):
        command='create planar surface with plane yplane offset '+str(x)
        cubit.cmd(command)
        last_surface=cubit.get_last_id("surface")
        command="webcut volume all tool volume in surf "+str(last_surface)
        cubit.cmd(command)
        command="del surf "+str(last_surface)
        cubit.cmd(command)
        
    def translate2zero():
        ss=cubit.parse_cubit_list('surface','all')
        box = cubit.get_total_bounding_box("surface", ss)
        xmin=box[0]
        ymin=box[3]
        cubit.cmd('move surface all x '+str(-1*xmin)+' y '+str(-1*ymin))
        return xmin,ymin
        
    def translate2original(xmin,ymin):
        cubit.cmd('move surface all x '+str(xmin)+' y '+str(ymin))
        
    if mpiflag:
        icpux = iproc % cfg.nproc_xi
        icpuy = int(iproc / cfg.nproc_xi)
    else:
        icpuy=int(cfg.id_proc/cfg.nproc_xi)
        icpux=cfg.id_proc%cfg.nproc_xi
    #
    ner=cubit.get_error_count()
    #
    icurve=0
    isurf=0
    ivertex=0
    #
    xlength=(cfg.xmax-cfg.xmin)/float(cfg.cpux) #length of x slide for chunk
    ylength=(cfg.ymax-cfg.ymin)/float(cfg.cpuy) #length of y slide for chunk
    xmin_cpu=cfg.xmin+(xlength*(icpux))
    ymin_cpu=cfg.ymin+(ylength*(icpuy))
    xmax_cpu=xmin_cpu+xlength
    ymax_cpu=ymin_cpu+ylength
    #
    #importing the surfaces
    for inz in range(cfg.nz-2,-2,-1):
        if cfg.bottomflat and inz==-1:
            command = "create planar surface with plane zplane offset "+str(cfg.depth_bottom)
            cubit.cmd(command)
        else:
            command = "import cubit '"+cfg.filename[inz]+"'"
            cubit.cmd(command)
            
            
    #translate
    xmin,ymin=translate2zero()
    print 'translate ...', -xmin,-ymin
    xmin_cpu=xmin_cpu-xmin
    ymin_cpu=ymin_cpu-ymin
    xmax_cpu=xmax_cpu-xmin
    ymax_cpu=ymax_cpu-ymin
    
    ss=cubit.parse_cubit_list('surface','all')
    box = cubit.get_total_bounding_box("surface", ss)
    print 'dimension... ', box
    #cutting the surfaces
    xwebcut(xmin_cpu)
    xwebcut(xmax_cpu)
    ywebcut(ymin_cpu)
    ywebcut(ymax_cpu)
    #
    list_surface_all=cubit.parse_cubit_list("surface","all")
    #condisidering only the surfaces inside the boundaries
    dict_surf={}
    for isurf in list_surface_all:
        p=cubit.get_center_point("surface",isurf)
        if p[0] < xmin_cpu or p[0] > xmax_cpu or p[1] > ymax_cpu or p[1] < ymin_cpu:
            command = "del surf "+str(isurf)
            cubit.cmd(command)
        else:
            dict_surf[str(isurf)]=p[2]
    z=dict_surf.values()
    z.sort()
    list_surf=[]
    for val in z:
        isurf=[k for k, v in dict_surf.iteritems() if v == val][0]
        list_surf.append(int(isurf))
    #
    
    #lofting the volume
    for i,j in zip(list_surf,list_surf[1:]):
        ner=cubit.get_error_count()
        create_volume(i,j,method=cfg.volumecreation_method)
        #cubitcommand= 'create volume loft surface '+ str(i)+' '+str(j)
        #cubit.cmd(cubitcommand)
        ner2=cubit.get_error_count()
    #
    translate2original(xmin,ymin)
    
    
    if ner == ner2:
        cubitcommand= 'del surface all'
        cubit.cmd(cubitcommand)
        #
        #
        #cubitcommand= 'composite create curve in vol all'
        #cubit.cmd(cubitcommand)
        list_vol=cubit.parse_cubit_list("volume","all")
        if len(list_vol) > 1:     
            cubitcommand= 'imprint volume all'
            cubit.cmd(cubitcommand)
            #cubit_error_stop(iproc,cubitcommand,ner)
            #
            cubitcommand= 'merge all'
            cubit.cmd(cubitcommand)
    #
    savegeometry(iproc,filename=filename)
def define_block():
    list_vol=cubit.parse_cubit_list("volume","all")
    init_n_vol=len(list_vol)
    list_name=map(lambda x: 'vol'+x,map(str,list_vol))
    return list_vol,list_name
def define_absorbing_surf_nopar():
    """
    define the absorbing surfaces for a layered topological box where boundary surfaces are not parallel to the axis.
    it returns absorbing_surf,topo_surf
    where
    absorbing_surf is the list of all the absorbing boundary surf
    """
    try:
        cubit.cmd('comment')
    except:
        try:
            import cubit
            cubit.init([""])
        except:
            print 'error importing cubit'
            import sys
            sys.exit()
    from sets import Set
    def product(*args, **kwds):
        # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
        # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
        pools = map(tuple, args) * kwds.get('repeat', 1)
        result = [[]]
        for pool in pools:
            result = [x+[y] for x in result for y in pool]
        return result
    absorbing_surf=[]
    absorbing_surf_xmin=[]
    absorbing_surf_xmax=[]
    absorbing_surf_ymin=[]
    absorbing_surf_ymax=[]
    absorbing_surf_bottom=[]
    top_surf=[]
    list_vol=cubit.parse_cubit_list("volume","all")
    init_n_vol=len(list_vol)
    zmax_box=cubit.get_total_bounding_box("volume",list_vol)[7]
    zmin_box=cubit.get_total_bounding_box("volume",list_vol)[6] #it is the z_min of the box ... box= xmin,xmax,d,ymin,ymax,d,zmin...
    xmin_box=cubit.get_total_bounding_box("volume",list_vol)[0]
    xmax_box=cubit.get_total_bounding_box("volume",list_vol)[1]
    ymin_box=cubit.get_total_bounding_box("volume",list_vol)[3]
    ymax_box=cubit.get_total_bounding_box("volume",list_vol)[4]
    list_surf=cubit.parse_cubit_list("surface","all")
    lv=[]
    for k in list_surf:
            sbox=cubit.get_bounding_box('surface',k)
            dzmax=abs((sbox[7] - zmax_box)/zmax_box)
            dzmin=abs((sbox[6] - zmin_box)/zmin_box)
            normal=cubit.get_surface_normal(k)
            zn=normal[2]
            if dzmax <= 0.001 and zn > 0.7:
                top_surf.append(k)
                list_vertex=cubit.get_relatives('surface',k,'vertex')
                for v in list_vertex:
                    valence=cubit.get_valence(v)
                    if valence <= 4: #valence 3 is a corner, 4 is a vertex between 2 volumes, > 4 is a vertex not in the boundaries
                        lv.append(v)
            elif dzmin <= 0.001 and zn < -0.7:
                absorbing_surf.append(k)
    lp=[]
    combs=product(lv,lv)
    for comb in combs:
        v1=comb[0]
        v2=comb[1]
        c=Set(cubit.get_relatives("vertex",v1,"curve")) & Set(cubit.get_relatives("vertex",v2,"curve"))
        if len(c) == 1:
            p=cubit.get_center_point("curve",list(c)[0])
            lp.append(p)
    for k in list_surf:
        center_point = cubit.get_center_point("surface", k)
        for p in lp:
            if abs((center_point[0] - p[0])/p[0]) <= 0.005 and abs((center_point[1] - p[1])/p[1]) <= 0.005:
             absorbing_surf.append(k)
             break
    return absorbing_surf,top_surf
Exemplo n.º 49
0
    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

        if self.cpml:
            if not absname: absname=self.cpmlname
            print 'Writing cpml'+absname+'.....'
            list_cpml=self.select_cpml()
            if list_cpml is False:
                print 'error writing cpml files'
                return
            else:
                abshex_cpml=open(absname,'w')
                hexcount=sum(map(len,list_cpml))
                abshex_cpml.write(('%10i\n') % (hexcount))
                for icpml,lcpml in enumerate(list_cpml):
                    for hexa in lcpml:
                        abshex_cpml.write(('%10i %10i\n') % (hexa,icpml))


        stacey_absorb=True
        if stacey_absorb:
            #
            #
            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 '  block name:',name,'id:',block
                    cknormal=True
                    abshex_local=False
                    # opens file
                    if re.search('xmin',name):
                        print 'xmin'
                        abshex_local=open(absname+'_xmin','w')
                        normal=(-1,0,0)
                    elif re.search('xmax',name):
                        print "xmax"
                        abshex_local=open(absname+'_xmax','w')
                        normal=(1,0,0)
                    elif re.search('ymin',name):
                        print "ymin"
                        abshex_local=open(absname+'_ymin','w')
                        normal=(0,-1,0)
                    elif re.search('ymax',name):
                        print "ymax"
                        abshex_local=open(absname+'_ymax','w')
                        normal=(0,1,0)
                    elif re.search('bottom',name):
                        print "bottom"
                        abshex_local=open(absname+'_bottom','w')
                        normal=(0,0,-1)
                    elif re.search('abs',name):
                        print "abs all - experimental, check the output"
                        cknormal=False
                        abshex_local=open(absname,'w')
                    else:
                        if block == 1003:
                            print 'xmin'
                            abshex_local=open(absname+'_xmin','w')
                            normal=(-1,0,0)
                        elif block == 1004:
                            print "ymin"
                            abshex_local=open(absname+'_ymin','w')
                            normal=(0,-1,0)
                        elif block == 1005:
                            print "xmax"
                            abshex_local=open(absname+'_xmax','w')
                            normal=(1,0,0)
                        elif block == 1006:
                            print "ymax"
                            abshex_local=open(absname+'_ymax','w')
                            normal=(0,1,0)
                        elif block == 1002:
                            print "bottom"
                            abshex_local=open(absname+'_bottom','w')
                            normal=(0,0,-1)
                        elif block == 1000:
                            print "custumized"
                            abshex_local=open(absname,'w')
                            cknormal=False
                            normal=None
                    #
                    #
                    if abshex_local:
                        # 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):
                                    txt=self.create_facenode_string(h,f,normal=normal,cknormal=cknormal)
                                    abshex_local.write(txt)
                        abshex_local.close()
                        print 'Ok'
            cubit.cmd('set info on')
            cubit.cmd('set echo on')
Exemplo n.º 50
0
def define_surf(ip=0,
                cpuxmin=0,
                cpuxmax=1,
                cpuymin=0,
                cpuymax=1,
                cpux=1,
                cpuy=1):
    """
    define the absorbing surfaces for a layered topological box where boundary are surfaces parallel to the axis.
    it returns absorbing_surf,absorbing_surf_xmin,absorbing_surf_xmax,absorbing_surf_ymin,absorbing_surf_ymax,absorbing_surf_bottom,topo_surf
    where
    absorbing_surf is the list of all the absorbing boundary surf
    absorbing_surf_xmin is the list of the absorbing boundary surfaces that correnspond to x=xmin
    ...
    absorbing_surf_bottom is the list of the absorbing boundary surfaces that correspond to z=zmin
    """
    from utilities import get_v_h_list
    #
    from sets import Set

    def product(*args, **kwds):
        # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
        # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
        # for compatibility with python2.5
        pools = map(tuple, args) * kwds.get('repeat', 1)
        result = [[]]
        for pool in pools:
            result = [x + [y] for x in result for y in pool]
        return result

    absorbing_surf = []
    xmin = []
    xmax = []
    ymin = []
    ymax = []
    #
    top_surf = []
    bottom_surf = []
    list_vol = cubit.parse_cubit_list("volume", "all")
    zmax_box = cubit.get_total_bounding_box("volume", list_vol)[7]
    zmin_box = cubit.get_total_bounding_box(
        "volume", list_vol
    )[6]  #it is the z_min of the box ... box= xmin,xmax,d,ymin,ymax,d,zmin...
    xmin_box = cubit.get_total_bounding_box("volume", list_vol)[0]
    xmax_box = cubit.get_total_bounding_box("volume", list_vol)[1]
    ymin_box = cubit.get_total_bounding_box("volume", list_vol)[3]
    ymax_box = cubit.get_total_bounding_box("volume", list_vol)[4]
    list_surf = cubit.parse_cubit_list("surface", "all")

    absorbing_surface_distance_tolerance = 0.001
    topographic_surface_distance_tolerance = 0.1
    topographic_surface_normal_tolerance = 0.4

    lv = []
    for k in list_surf:
        sbox = cubit.get_bounding_box('surface', k)
        if zmax_box == 0 and sbox[7] == 0:
            dzmax = 0
        elif zmax_box == 0 or sbox[7] == 0:
            dzmax = abs(sbox[7] - zmax_box)
        else:
            dzmax = abs(sbox[7] - zmax_box) / max(abs(sbox[7]), abs(zmax_box))
        if zmin_box == 0 and sbox[6] == 0:
            dzmin = 0
        elif zmin_box == 0 or sbox[6] == 0:
            dzmin = abs(sbox[6] - zmin_box)
        else:
            dzmin = abs(sbox[6] - zmin_box) / max(abs(sbox[6]), abs(zmin_box))
        normal = cubit.get_surface_normal(k)
        zn = normal[2]
        if dzmax <= topographic_surface_distance_tolerance and zn > topographic_surface_normal_tolerance:
            top_surf.append(k)
            list_vertex = cubit.get_relatives('surface', k, 'vertex')
            for v in list_vertex:
                valence = cubit.get_valence(v)
                if valence <= 4:  #valence 3 is a corner, 4 is a vertex between 2 volumes, > 4 is a vertex not in the boundaries
                    lv.append(v)
        elif dzmin <= 0.001 and zn < -1 + topographic_surface_normal_tolerance:
            bottom_surf.append(k)
    if len(top_surf) == 0:  #assuming that one topo surface need to be selected
        _, _, _, _, _, top_surf = get_v_h_list(list_vol, chktop=False)
    lp = []
    labelp = []
    combs = product(lv, lv)
    for comb in combs:
        v1 = comb[0]
        v2 = comb[1]
        c = Set(cubit.get_relatives("vertex", v1, "curve")) & Set(
            cubit.get_relatives("vertex", v2, "curve"))
        if len(c) == 1:
            p = cubit.get_center_point("curve", list(c)[0])
            labelp.append(list(c)[0])
    labelps = Set(labelp)
    for c in labelps:
        p = cubit.get_center_point("curve", c)
        lp.append(p)

    for k in list_surf:
        center_point = cubit.get_center_point("surface", k)
        for p in lp:
            try:
                if abs((center_point[0] - p[0]) /
                       p[0]) <= absorbing_surface_distance_tolerance and abs(
                           (center_point[1] - p[1]) /
                           p[1]) <= absorbing_surface_distance_tolerance:
                    absorbing_surf.append(k)
                    break
            except:
                if -1 <= center_point[0] <= 1 and -1 <= center_point[1] <= 1:
                    absorbing_surf.append(k)
                    break
    #
    four_side = True
    if four_side:
        xmintmp, ymintmp, xmaxtmp, ymaxtmp = define_4side_lateral_surfaces()
        xmin = list(Set(xmintmp) - Set(xmaxtmp))
        xmax = list(Set(xmaxtmp) - Set(xmintmp))
        ymin = list(Set(ymintmp) - Set(ymaxtmp))
        ymax = list(Set(ymaxtmp) - Set(ymintmp))
        abs_xmintmp, abs_xmaxtmp, abs_ymintmp, abs_ymaxtmp = lateral_boundary_are_absorbing(
            ip, cpuxmin, cpuxmax, cpuymin, cpuymax, cpux, cpuy)
        abs_xmin = list(Set(abs_xmintmp) - Set(abs_xmaxtmp))
        abs_xmax = list(Set(abs_xmaxtmp) - Set(abs_xmintmp))
        abs_ymin = list(Set(abs_ymintmp) - Set(abs_ymaxtmp))
        abs_ymax = list(Set(abs_ymaxtmp) - Set(abs_ymintmp))
    return absorbing_surf, abs_xmin, abs_xmax, abs_ymin, abs_ymax, top_surf, bottom_surf, xmin, ymin, xmax, ymax
Exemplo n.º 51
0
    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")
Exemplo n.º 52
0
def layercake_volume_ascii_regulargrid_mpiregularmap(filename=None,verticalsandwich=False,onlysurface=False):
    import sys
    import start as start
    #
    mpiflag,iproc,numproc,mpi   = start.start_mpi()
    #
    numpy                       = start.start_numpy()
    cfg                         = start.start_cfg(filename=filename)                       
    
    from utilities import geo2utm, savegeometry,savesurf,cubit_command_check
    
    from math import sqrt
    #
    try:
        mpi.barrier()
    except:
        pass
    #
    #
    command = "comment '"+"PROC: "+str(iproc)+"/"+str(numproc)+" '"
    cubit_command_check(iproc,command,stop=True)
    if verticalsandwich: cubit.cmd("comment 'Starting Vertical Sandwich'")
    #
    #get icpuy,icpux values
    if mpiflag:
        icpux = iproc % cfg.nproc_xi
        icpuy = int(iproc / cfg.nproc_xi)
    else:
        icpuy=int(cfg.id_proc/cfg.nproc_xi)
        icpux=cfg.id_proc%cfg.nproc_xi
    
    #
    if  cfg.geometry_format == 'ascii':
        #for the original surfaces
        #number of points in the files that describe the topography
        import local_volume
        if cfg.localdir_is_globaldir:
            if iproc == 0 or not mpiflag:
                coordx_0,coordy_0,elev_0,nx_0,ny_0=local_volume.read_grid(filename)
                print 'end of reading grd files '+str(nx_0*ny_0)+ ' points'
            else:
                pass
            if iproc == 0 or not mpiflag:
                coordx=mpi.bcast(coordx_0)
            else:
                coordx=mpi.bcast()
            if iproc == 0 or not mpiflag:
                coordy=mpi.bcast(coordy_0)
            else:
                coordy=mpi.bcast()
            if iproc == 0 or not mpiflag:
                elev=mpi.bcast(elev_0)
            else:
                elev=mpi.bcast()
            if iproc == 0 or not mpiflag:
                nx=mpi.bcast(nx_0)
            else:
                nx=mpi.bcast()       
            if iproc == 0 or not mpiflag:
                ny=mpi.bcast(ny_0)
            else:
                ny=mpi.bcast()
        else:
            coordx,coordy,elev,nx,ny=local_volume.read_grid(filename)
        print str(iproc)+ ' end of receving grd files '
        nx_segment=int(nx/cfg.nproc_xi)+1
        ny_segment=int(ny/cfg.nproc_eta)+1
        
    elif cfg.geometry_format=='regmesh': # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        
        if cfg.depth_bottom != cfg.zdepth[0]:
            if iproc == 0: print 'the bottom of the block is at different depth than depth[0] in the configuration file'
        nx= cfg.nproc_xi+1
        ny= cfg.nproc_eta+1
        nx_segment=2
        ny_segment=2
        #if iproc == 0: print nx,ny,cfg.cpux,cfg.cpuy
        xp=(cfg.xmax-cfg.xmin)/float((nx-1))
        yp=(cfg.ymax-cfg.ymin)/float((ny-1))
        #
        elev=numpy.zeros([nx,ny,cfg.nz],float)
        coordx=numpy.zeros([nx,ny],float)
        coordy=numpy.zeros([nx,ny],float)
        #
        #
        xlength=(cfg.xmax-cfg.xmin)/float(cfg.nproc_xi) #length of x slide for chunk
        ylength=(cfg.ymax-cfg.ymin)/float(cfg.nproc_eta) #length of y slide for chunk
        nelem_chunk_x=1    
        nelem_chunk_y=1
        ivxtot=nelem_chunk_x+1
        ivytot=nelem_chunk_y+1 
        xstep=xlength #distance between vertex on x
        ystep=ylength
        for i in range(0,cfg.nz):
            elev[:,:,i] = cfg.zdepth[i]
        
        icoord=0
        for iy in range(0,ny):
            for ix in range(0,nx):
                icoord=icoord+1
                coordx[ix,iy]=cfg.xmin+xlength*(ix)
                coordy[ix,iy]=cfg.ymin+ylength*(iy)
        
        #print coordx,coordy,nx,ny
    #
    print 'end of building grid '+str(iproc)
    print 'number of point: ', len(coordx)*len(coordy)
    #
    #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    #for each processor
    #
    nxmin_cpu=(nx_segment-1)*(icpux)
    nymin_cpu=(ny_segment-1)*(icpuy)
    nxmax_cpu=min(nx-1,(nx_segment-1)*(icpux+1))
    nymax_cpu=min(ny-1,(ny_segment-1)*(icpuy+1))
    #if iproc == 0:
    #    print nx_segment,ny_segment,nx,ny
    #    print icpux,icpuy,nxmin_cpu,nxmax_cpu
    #    print icpux,icpuy,nymin_cpu,nymax_cpu
    #    print coordx[0,0],coordx[nx-1,ny-1]
    #    print coordy[0,0],coordy[nx-1,ny-1]
    #
    #
    icurve=0
    isurf=0
    ivertex=0
    #
    #create vertex
    for inz in range(0,cfg.nz):
        if cfg.sea and inz==cfg.nz-1: #sea layer
            sealevel=True
            bathymetry=False
        elif cfg.sea and inz==cfg.nz-2: #bathymetry layer
            sealevel=False
            bathymetry=True
        else:
            sealevel=False
            bathymetry=False
        print sealevel,bathymetry
        
        if  cfg.bottomflat and inz == 0: #bottom layer
                #
                if cfg.geometry_format == 'ascii':
                    lv=cubit.get_last_id("vertex")     
                    
                    x_current,y_current=(coordx[nxmin_cpu,nymin_cpu],coordy[nxmin_cpu,nymin_cpu])
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)
                    #
                    x_current,y_current=(coordx[nxmin_cpu,nymax_cpu],coordy[nxmin_cpu,nymax_cpu])
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)                                                                              
                    #
                    x_current,y_current=(coordx[nxmax_cpu,nymax_cpu],coordy[nxmax_cpu,nymax_cpu])
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)
                    #
                    x_current,y_current=(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu])
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)
                    #
                    lv2=cubit.get_last_id("vertex")     
                    
                    cubitcommand= 'create surface vertex '+str(lv+1)+' to '+str(lv2)
                    cubit.cmd(cubitcommand)
                    #
                    isurf = isurf + 1
                else:
                    lv=cubit.get_last_id("vertex") 
                    x_current,y_current=geo2utm(coordx[nxmin_cpu,nymin_cpu],coordy[nxmin_cpu,nymin_cpu],'utm')
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)
                    #
                    x_current,y_current=geo2utm(coordx[nxmin_cpu,nymax_cpu],coordy[nxmin_cpu,nymax_cpu],'utm')
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)                                                                              
                    #
                    x_current,y_current=geo2utm(coordx[nxmax_cpu,nymax_cpu],coordy[nxmax_cpu,nymax_cpu],'utm')
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)
                    #
                    x_current,y_current=geo2utm(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu],'utm')
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)
                    #
                    lv2=cubit.get_last_id("vertex") 
                    cubitcommand= 'create surface vertex '+str(lv+1)+' to '+str(lv2)
                    cubit.cmd(cubitcommand)
                    #
                    isurf = isurf + 1
        else:
            if cfg.geometry_format == 'regmesh':
                zvertex=cfg.zdepth[inz]
                lv=cubit.get_last_id("vertex")                        
                x_current,y_current=geo2utm(coordx[nxmin_cpu,nymin_cpu],coordy[nxmin_cpu,nymin_cpu],'utm')
                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
                cubit.cmd(cubitcommand)
                #
                x_current,y_current=geo2utm(coordx[nxmin_cpu,nymax_cpu],coordy[nxmin_cpu,nymax_cpu],'utm')
                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
                cubit.cmd(cubitcommand)                                                                              
                #
                x_current,y_current=geo2utm(coordx[nxmax_cpu,nymax_cpu],coordy[nxmax_cpu,nymax_cpu],'utm')
                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
                cubit.cmd(cubitcommand)
                #
                x_current,y_current=geo2utm(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu],'utm')
                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
                cubit.cmd(cubitcommand)
                #
                cubitcommand= 'create surface vertex '+str(lv+1)+' '+str(lv+2)+' '+str(lv+3)+' '+str(lv+4)
                cubit.cmd(cubitcommand)
                #
                isurf = isurf + 1
            elif cfg.geometry_format == 'ascii':
                
                vertex=[]
                
                for iy in range(nymin_cpu,nymax_cpu+1):
                    ivx=0
                    for ix in range(nxmin_cpu,nxmax_cpu+1):
                        zvertex=elev[ix,iy,inz]
                        #zvertex=adjust_sea_layers(zvertex,sealevel,bathymetry,cfg)
                        x_current,y_current=(coordx[ix,iy],coordy[ix,iy])
                        #
                        vertex.append(' Position '+ str( x_current ) +' '+ str( y_current )+' '+ str( zvertex ) )
                #
                print 'proc',iproc, 'vertex list created....',len(vertex)
                n=max(nx,ny)
                uline=[]
                vline=[]
                iv=0
                
                cubit.cmd("set info off")
                cubit.cmd("set echo off")
                cubit.cmd("set journal off")
                
                for iy in range(0,nymax_cpu-nymin_cpu+1):
                    positionx=''
                    for ix in range(0,nxmax_cpu-nxmin_cpu+1):
                        positionx=positionx+vertex[iv]
                        iv=iv+1
                    command='create curve spline '+positionx
                    cubit.cmd(command)
                    #print command
                    uline.append( cubit.get_last_id("curve") )
                for ix in range(0,nxmax_cpu-nxmin_cpu+1):
                    positiony=''
                    for iy in range(0,nymax_cpu-nymin_cpu+1):
                        positiony=positiony+vertex[ix+iy*(nxmax_cpu-nxmin_cpu+1)]
                    command='create curve spline '+positiony
                    cubit.cmd(command)
                    #print command
                    vline.append( cubit.get_last_id("curve") )
                #
                cubit.cmd("set info "+cfg.cubit_info)
                cubit.cmd("set echo "+cfg.echo_info)
                cubit.cmd("set journal "+cfg.jou_info)
                #
                #
                print 'proc',iproc, 'lines created....',len(uline),'*',len(vline)
                umax=max(uline)
                umin=min(uline)
                vmax=max(vline)
                vmin=min(vline)
                ner=cubit.get_error_count()
                cubitcommand= 'create surface net u curve '+ str( umin )+' to '+str( umax )+ ' v curve '+ str( vmin )+ ' to '+str( vmax )+' heal'
                cubit.cmd(cubitcommand)
                ner2=cubit.get_error_count()
                if ner == ner2: 
                    command = "del curve all"
                    cubit.cmd(command)
                    isurf=isurf+1
                #
            else:
                raise NameError, 'error, check geometry_format, it should be ascii or regmesh'   #
                #
        cubitcommand= 'del vertex all'
        cubit.cmd(cubitcommand)
    if cfg.save_surface_cubit:
        savegeometry(iproc=iproc,surf=True,filename=filename)
    #
    #
    #!create volume
    if not onlysurface:
        if cfg.nz == 1:
            nsurface=2
        else:
            nsurface=cfg.nz
        for inz in range(1,nsurface):
            ner=cubit.get_error_count()
            create_volume(inz,inz+1,method=cfg.volumecreation_method)
            ner2=cubit.get_error_count()
        if ner == ner2 and not cfg.debug_geometry:
            #cubitcommand= 'del surface 1 to '+ str( cfg.nz )
            cubitcommand= 'del surface all'
            cubit.cmd(cubitcommand)
            list_vol=cubit.parse_cubit_list("volume","all")
            if len(list_vol) > 1:     
                cubitcommand= 'imprint volume all'
                cubit.cmd(cubitcommand)
                cubitcommand= 'merge all'
                cubit.cmd(cubitcommand)
            #ner=cubit.get_error_count()
            #cubitcommand= 'composite create curve in vol all'
            #cubit.cmd(cubitcommand)
    savegeometry(iproc,filename=filename)
    #if cfg.geological_imprint:
    #    curvesname=[cfg.outlinebasin_curve,cfg.transition_curve,cfg.faulttrace_curve]
    #    outdir=cfg.working_dir
    #    imprint_topography_with_geological_outline(curvesname,outdir)
    #
    #        
    cubit.cmd("set info "+cfg.cubit_info)
    cubit.cmd("set echo "+cfg.echo_info)
    cubit.cmd("set journal "+cfg.jou_info)
def define_absorbing_surf_nopar():
    """
    define the absorbing surfaces for a layered topological box where boundary surfaces are not parallel to the axis.
    it returns absorbing_surf,topo_surf
    where
    absorbing_surf is the list of all the absorbing boundary surf
    """
    try:
        cubit.cmd('comment')
    except:
        try:
            import cubit
            cubit.init([""])
        except:
            print 'error importing cubit'
            import sys
            sys.exit()
    from sets import Set

    def product(*args, **kwds):
        # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
        # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
        pools = map(tuple, args) * kwds.get('repeat', 1)
        result = [[]]
        for pool in pools:
            result = [x + [y] for x in result for y in pool]
        return result

    absorbing_surf = []
    absorbing_surf_xmin = []
    absorbing_surf_xmax = []
    absorbing_surf_ymin = []
    absorbing_surf_ymax = []
    absorbing_surf_bottom = []
    top_surf = []
    list_vol = cubit.parse_cubit_list("volume", "all")
    init_n_vol = len(list_vol)
    zmax_box = cubit.get_total_bounding_box("volume", list_vol)[7]
    zmin_box = cubit.get_total_bounding_box(
        "volume", list_vol
    )[6]  #it is the z_min of the box ... box= xmin,xmax,d,ymin,ymax,d,zmin...
    xmin_box = cubit.get_total_bounding_box("volume", list_vol)[0]
    xmax_box = cubit.get_total_bounding_box("volume", list_vol)[1]
    ymin_box = cubit.get_total_bounding_box("volume", list_vol)[3]
    ymax_box = cubit.get_total_bounding_box("volume", list_vol)[4]
    list_surf = cubit.parse_cubit_list("surface", "all")
    lv = []
    for k in list_surf:
        sbox = cubit.get_bounding_box('surface', k)
        dzmax = abs((sbox[7] - zmax_box) / zmax_box)
        dzmin = abs((sbox[6] - zmin_box) / zmin_box)
        normal = cubit.get_surface_normal(k)
        zn = normal[2]
        if dzmax <= 0.001 and zn > 0.7:
            top_surf.append(k)
            list_vertex = cubit.get_relatives('surface', k, 'vertex')
            for v in list_vertex:
                valence = cubit.get_valence(v)
                if valence <= 4:  #valence 3 is a corner, 4 is a vertex between 2 volumes, > 4 is a vertex not in the boundaries
                    lv.append(v)
        elif dzmin <= 0.001 and zn < -0.7:
            absorbing_surf.append(k)
    lp = []
    combs = product(lv, lv)
    for comb in combs:
        v1 = comb[0]
        v2 = comb[1]
        c = Set(cubit.get_relatives("vertex", v1, "curve")) & Set(
            cubit.get_relatives("vertex", v2, "curve"))
        if len(c) == 1:
            p = cubit.get_center_point("curve", list(c)[0])
            lp.append(p)
    for k in list_surf:
        center_point = cubit.get_center_point("surface", k)
        for p in lp:
            if abs((center_point[0] - p[0]) / p[0]) <= 0.005 and abs(
                (center_point[1] - p[1]) / p[1]) <= 0.005:
                absorbing_surf.append(k)
                break
    return absorbing_surf, top_surf
Exemplo n.º 54
0
def define_parallel_absorbing_surf():
    """
    define the absorbing surfaces for a layered topological box where boundary are surfaces parallel to the axis.
    it returns absorbing_surf,absorbing_surf_xmin,absorbing_surf_xmax,absorbing_surf_ymin,absorbing_surf_ymax,absorbing_surf_bottom,topo_surf
    where
    absorbing_surf is the list of all the absorbing boundary surf
    absorbing_surf_xmin is the list of the absorbing boundary surfaces that correnspond to x=xmin
    ...
    absorbing_surf_bottom is the list of the absorbing boundary surfaces that correspond to z=zmin
    """
    try:
        cubit.cmd('comment')
    except:
        try:
            import cubit
            cubit.init([""])
        except:
            print 'error importing cubit'
            import sys
            sys.exit()
    absorbing_surf_xmin = []
    absorbing_surf_xmax = []
    absorbing_surf_ymin = []
    absorbing_surf_ymax = []
    absorbing_surf_bottom = []
    top_surf = []

    list_vol = cubit.parse_cubit_list("volume", "all")
    init_n_vol = len(list_vol)
    zmax_box = cubit.get_total_bounding_box("volume", list_vol)[7]
    zmin_box = cubit.get_total_bounding_box(
        "volume", list_vol
    )[6]  #it is the z_min of the box ... box= xmin,xmax,d,ymin,ymax,d,zmin...
    xmin_box = cubit.get_total_bounding_box("volume", list_vol)[0]
    xmax_box = cubit.get_total_bounding_box("volume", list_vol)[1]
    ymin_box = cubit.get_total_bounding_box("volume", list_vol)[3]
    ymax_box = cubit.get_total_bounding_box("volume", list_vol)[4]
    list_surf = cubit.parse_cubit_list("surface", "all")
    print '##boundary box: '
    print '##  x min: ' + str(xmin_box)
    print '##  y min: ' + str(ymin_box)
    print '##  z min: ' + str(zmin_box)
    print '##  x max: ' + str(xmax_box)
    print '##  y max: ' + str(ymax_box)
    print '##  z max: ' + str(zmax_box)

    #box lengths
    x_len = abs(xmax_box - xmin_box)
    y_len = abs(ymax_box - ymin_box)
    z_len = abs(zmax_box - zmin_box)

    print '##boundary box: '
    print '##  x length: ' + str(x_len)
    print '##  y length: ' + str(y_len)
    print '##  z length: ' + str(z_len)

    # tolerance parameters
    absorbing_surface_distance_tolerance = 0.005
    topographic_surface_distance_tolerance = 0.001
    topographic_surface_normal_tolerance = 0.2

    for k in list_surf:
        center_point = cubit.get_center_point("surface", k)
        if abs((center_point[0] - xmin_box) /
               x_len) <= absorbing_surface_distance_tolerance:
            absorbing_surf_xmin.append(k)
        elif abs((center_point[0] - xmax_box) /
                 x_len) <= absorbing_surface_distance_tolerance:
            absorbing_surf_xmax.append(k)
        elif abs((center_point[1] - ymin_box) /
                 y_len) <= absorbing_surface_distance_tolerance:
            absorbing_surf_ymin.append(k)
        elif abs((center_point[1] - ymax_box) /
                 y_len) <= absorbing_surface_distance_tolerance:
            absorbing_surf_ymax.append(k)
        elif abs((center_point[2] - zmin_box) /
                 z_len) <= absorbing_surface_distance_tolerance:
            print 'center_point[2]' + str(center_point[2])
            print 'kz:' + str(k)
            absorbing_surf_bottom.append(k)

        else:
            sbox = cubit.get_bounding_box('surface', k)
            dz = abs((sbox[7] - zmax_box) / z_len)
            normal = cubit.get_surface_normal(k)
            zn = normal[2]
            dn = abs(zn - 1)
            if dz <= topographic_surface_distance_tolerance and dn < topographic_surface_normal_tolerance:
                top_surf.append(k)

    return absorbing_surf_xmin, absorbing_surf_xmax, absorbing_surf_ymin, absorbing_surf_ymax, absorbing_surf_bottom, top_surf
Exemplo n.º 55
0
def define_block():
    list_vol = cubit.parse_cubit_list("volume", "all")
    init_n_vol = len(list_vol)
    list_name = map(lambda x: 'vol' + x, map(str, list_vol))
    return list_vol, list_name
Exemplo n.º 56
0
def mesh_layercake_regularmap(filename=None):
    import sys,os
    import start as start
    mpiflag,iproc,numproc,mpi   = start.start_mpi()
    from utilities import  importgeometry,savemesh,get_v_h_list,cubit_command_check
    #
    numpy                       = start.start_numpy()
    cfg                         = start.start_cfg(filename=filename)
    from math import sqrt
    from sets import Set

    #
    class cubitvolume:
          def __init__(self,ID,intervalv,centerpoint,dimension):
              self.ID=ID
              self.intervalv=intervalv
              self.centerpoint=centerpoint
              self.dim=dimension
          
          def __repr__(self):
              msg="(vol:%3i, vertical interval: %4i, centerpoint: %8.2f)" % (self.ID, self.intervalv,self.centerpoint)
              return msg       
    #
    def by_z(x,y):
        return cmp(x.centerpoint,y.centerpoint)
    #
    #
    #
    list_vol=cubit.parse_cubit_list("volume","all")
    if len(list_vol) != 0:
        pass
    else:
        geometryfile='geometry_vol_'+str(iproc)+'.cub'
        importgeometry(geometryfile,iproc=iproc)
    #
    command = 'composite create curve all'
    cubit.cmd(command)
    print '###"No valid composites can be created from the specified curves."  is NOT a critical ERROR.'
    #
    command = "compress all"
    cubit.cmd(command)
    list_vol=cubit.parse_cubit_list("volume","all")
    nvol=len(list_vol)                                 
    vol=[]
    for id_vol in list_vol:
        p=cubit.get_center_point("volume",id_vol)
        vol.append(cubitvolume(id_vol,1,p[2],0))
    vol.sort(by_z)
    #
    for id_vol in range(0,nvol):
        vol[id_vol].intervalv=cfg.iv_interval[id_vol]
    #
    #
    surf_vertical=[]
    surf_or=[]
    top_surface=0
    top_surface_add=''
    bottom_surface=0
    #
    zmin_box=cubit.get_total_bounding_box("volume",list_vol)[6]
    xmin_box=cubit.get_total_bounding_box("volume",list_vol)[0]
    xmax_box=cubit.get_total_bounding_box("volume",list_vol)[1]
    ymin_box=cubit.get_total_bounding_box("volume",list_vol)[3]
    ymax_box=cubit.get_total_bounding_box("volume",list_vol)[4]
    #
    #
    #interval assignement
    surf_or,surf_vertical,list_curve_or,list_curve_vertical,bottom,top = get_v_h_list(list_vol,chktop=cfg.chktop)
    print 'vertical surfaces: ',surf_vertical    
    
    for k in surf_vertical:
        command = "surface "+str(k)+" scheme submap"
        cubit.cmd(command)
    for k in surf_or:
        command = "surface "+str(k)+" scheme "+cfg.or_mesh_scheme
        cubit.cmd(command)
    #
    ucurve,vcurve=get_uv_curve(list_curve_or)
    schemepave=False
    #
    ucurve_interval={}
    for k in ucurve:
        length=cubit.get_curve_length(k)
        interval=int(2*round(.5*length/cfg.size,0))
        ucurve_interval[k]=interval
        command = "curve "+str(k)+" interval "+str(interval)
        cubit.cmd(command)
        #cubit_error_stop(iproc,command,ner)
        command = "curve "+str(k)+" scheme equal"
        cubit.cmd(command)
        #cubit_error_stop(iproc,command,ner)
    if max(ucurve_interval.values()) != min(ucurve_interval.values()):
        schemepave=True
        print 'mesh scheme is set to pave'
        for sk in surf_or:
            command = "surface "+str(sk)+" scheme pave"
            cubit.cmd(command)
    #
    vcurve_interval={}
    for k in vcurve:
        length=cubit.get_curve_length(k)
        interval=int(2*round(.5*length/cfg.size,0))
        vcurve_interval[k]=interval
        command = "curve "+str(k)+" interval "+str(interval)
        cubit.cmd(command)
        #cubit_error_stop(iproc,command,ner)
        command = "curve "+str(k)+" scheme equal"
        cubit.cmd(command)
        #cubit_error_stop(iproc,command,ner)

    if max(vcurve_interval.values()) != min(vcurve_interval.values()):
        print 'mesh scheme is set to pave'
        schemepave=True
        for sk in surf_or:
            command = "surface "+str(sk)+" scheme pave"
            cubit.cmd(command)
    #
    for s in surf_vertical:
        lcurve=cubit.get_relatives("surface",s,"curve")
        interval_store=[]
        for k in lcurve:
            interval_curve=cubit.get_mesh_intervals('curve',k)
            if k in list_curve_vertical:
                volume_id = cubit.get_owning_volume("curve", k)
                for idv in range(0,nvol):
                    if vol[idv].ID == volume_id:
                        int_v=vol[idv].intervalv
                command = "curve "+str(k)+" interval "+str(int_v)
                cubit.cmd(command)
                #cubit_error_stop(iproc,command,ner)
                command = "curve "+str(k)+" scheme equal"
                cubit.cmd(command)
                #cubit_error_stop(iproc,command,ner)
            else:
                interval_store.append((k,interval_curve))
            if len(interval_store) != 0:
                interval_min=min([iv[1] for iv in interval_store])
                command = "curve "+' '.join(str(iv[0]) for iv in interval_store)+" interval "+str(interval_min)
                cubit.cmd(command)
                #cubit_error_stop(iproc,command,ner)
                command = "curve "+' '.join(str(iv[0]) for iv in interval_store)+" scheme equal"
                cubit.cmd(command)
                #cubit_error_stop(iproc,command,ner)
        command = "surface "+str(s)+" scheme submap"
        cubit.cmd(command)
        
    #cubit_error_stop(iproc,command,ner)
    #
    #meshing
    if cfg.or_mesh_scheme == 'pave' or schemepave:
        command='mesh surf '+' '.join(str(t) for t in top)
        status=cubit_command_check(iproc,command,stop=True)
        #cubit.cmd(command)    
    elif cfg.or_mesh_scheme == 'map':
        command='mesh surf '+' '.join(str(t) for t in bottom)
        status=cubit_command_check(iproc,command,stop=True)
        #cubit.cmd(command)
    for id_volume in range(nvol-1,-1,-1):
        command = "mesh vol "+str(vol[id_volume].ID)
        status=cubit_command_check(iproc,command,stop=False)
        if not status:
            for s in surf_vertical:
                command_surf="mesh surf "+str(s)
                cubit.cmd(command_surf)
            command_set_meshvol='volume all redistribute nodes on\nvolume all autosmooth target off\nvolume all scheme Sweep Vector 0 0 -1\nvolume all sweep smooth Auto\n'
            status=cubit_command_check(iproc,command_set_meshvol,stop=False)
            status=cubit_command_check(iproc,command,stop=True)    
    
    #
    #smoothing
    print iproc, 'untangling...'
    cmd="volume all smooth scheme untangle beta 0.02 cpu 10"
    cubit.cmd(cmd)
    cmd="smooth volume all"
    cubit.cmd(cmd)
    
    
    
    if  cfg.smoothing:
        print 'smoothing .... '+str(cfg.smoothing)
        cubitcommand= 'surf all smooth scheme laplacian '
        cubit.cmd(cubitcommand)
        cubitcommand= 'smooth surf all'
        cubit.cmd(cubitcommand)
        #
        cubitcommand= 'vol all smooth scheme laplacian '
        cubit.cmd(cubitcommand)
        cubitcommand= 'smooth vol all'
        cubit.cmd(cubitcommand)
    #
    #
    ##vertical refinement
    ##for nvol = 3 
    ##
    ##___________________________ interface 4
    ##                 
    ##vol 2              
    ##___________________________ interface 3
    ##
    ##vol 1
    ##___________________________ interface 2
    ##
    ##vol 0
    ##___________________________ interface 1
    ##
    refinement(nvol,vol,filename=filename)
    #
    #top layer vertical coarsening
    print 'coarsening top layer... ',cfg.coarsening_top_layer
    if  cfg.coarsening_top_layer:
        from sets import Set
        cubitcommand= 'del mesh vol '+str(vol[-1].ID)+ ' propagate'
        cubit.cmd(cubitcommand)
        s1=Set(list_curve_vertical)
        command = "group 'list_curve_tmp' add curve "+"in vol "+str(vol[-1].ID)
        cubit.cmd(command)
        group=cubit.get_id_from_name("list_curve_tmp")
        list_curve_tmp=cubit.get_group_curves(group)
        command = "delete group "+ str(group)
        cubit.cmd(command)
        s2=Set(list_curve_tmp)
        lc=list(s1 & s2)
        #
        cubitcommand= 'curve '+' '.join(str(x) for x in lc)+' interval '+str(cfg.actual_vertical_interval_top_layer)
        cubit.cmd(cubitcommand)
        cubitcommand= 'mesh vol '+str(vol[-1].ID)
        cubit.cmd(cubitcommand)
    #
    n=cubit.get_sideset_id_list()
    if len(n) != 0:
        command = "del sideset all"
        cubit.cmd(command)
    n=cubit.get_block_id_list()
    if len(n) != 0:    
        command = "del block all"
        cubit.cmd(command)
    #
    import boundary_definition
    entities=['face']
    print iproc, 'hex block definition...'
    boundary_definition.define_bc(entities,parallel=True,cpux=cfg.cpux,cpuy=cfg.cpuy,cpuxmin=0,cpuymin=0,optionsea=False)
    #save mesh
    
    print iproc, 'untangling...'
    cmd="volume all smooth scheme untangle beta 0.02 cpu 10"
    cubit.cmd(cmd)
    cmd="smooth volume all"
    cubit.cmd(cmd)
    
    print iproc, 'saving...'
    savemesh(mpiflag,iproc=iproc,filename=filename)
Exemplo n.º 57
0
def collecting_merging(cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1,cubfiles=False,ckbound_method1=False,ckbound_method2=False,merge_tolerance=None,decimate=False):
    import glob
    import re
    #
    rule_st=re.compile("(.+)_[0-9]+\.")
    rule_ex=re.compile(".+_[0-9]+\.(.+)")
    rule_int=re.compile(".+_([0-9]+)\.")
    boundary_dict={}
    ##
    try:
        from boundary_definition import check_bc, map_boundary
    except:
        pass
    #
    xmin,xmax,ymin,ymax,listfull=map_boundary(cpuxmin,cpuxmax,cpuymin,cpuymax,cpux,cpuy)
    #
    if cubfiles:
        nf,listip,filenames,cubflag=importing_cubfiles(cubfiles)
    else:
        nf=0
        filenames=[]
        ip=0
    #
    if nf > 0:
        for ip,filename in zip(listip,filenames):
            try:
                if ip in listfull:
                    if cubflag:
                        cubit.cmd('import cubit "'+filename+'"')
                    else:
                        cubit.cmd('import mesh geometry "'+filename+'" block all use nodeset sideset feature_angle 135.00 linear merge')
                    if decimate: cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
                    boundary=check_bc(ip,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax)
                    boundary_dict[ip]=boundary
                    list_vol=list(cubit.parse_cubit_list('volume','all'))
                    for v in list_vol:
                        cubit.cmd("disassociate mesh from volume "+str(v))
                        command = "del vol "+str(v)
                        cubit.cmd(command)
            except:
                cubit.cmd('import mesh geometry "'+filename+'" block all use nodeset sideset feature_angle 135.00 linear merge')
                if decimate: cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
                ip=0
                boundary=check_bc(ip,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax)
                boundary_dict[ip]=boundary
                list_vol=list(cubit.parse_cubit_list('volume','all'))
                for v in list_vol:
                    cubit.cmd("disassociate mesh from volume "+str(v))
                    command = "del vol "+str(v)
                    cubit.cmd(command)
        cubit.cmd('export mesh "tmp_collect_NOmerging.e" dimension 3 block all overwrite')
    else:
        if decimate: cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
        boundary=check_bc(ip,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax)
    #
    #
    #print boundary_dict
    block_list=cubit.get_block_id_list()
    for block in block_list:
        ty=cubit.get_block_element_type(block)
        if ty == 'HEX8':
            cubit.cmd('block '+str(block)+' name "vol'+str(block)+'"')
    #
    #
    print 'chbound',ckbound_method1,ckbound_method2
    
    
    if ckbound_method1 and not ckbound_method2 and len(filenames) != 1:
        #use the equivalence method for groups
        if isinstance(merge_tolerance,list):
            tol=merge_tolerance[0]
        elif merge_tolerance:
            tol=merge_tolerance
        else:
            tol=100000
        #
        idiag=None
        #cubit.cmd('set info off')
        #cubit.cmd('set journal off')
        #cubit.cmd('set echo off')
        ind=0
        for ix in range(cpuxmin,cpuxmax):
            for iy in range(cpuymin,cpuymax):
                ind=ind+1
                ip=iy*cpux+ix
                print '******************* ',ip, ind,'/',len(listfull)
                #
                #   ileft    |   ip
                #  --------------------
                #   idiag    |   idown
                #
                #
                if ip not in xmin and ip not in ymin:
                    ileft=iy*cpux+ix-1
                    idown=(iy-1)*cpux+ix
                    idiag=idown-1
                elif ip in xmin and ip in ymin:
                    ileft=ip
                    idown=ip
                    idiag=None
                elif ip in xmin:
                    ileft=ip
                    idown=(iy-1)*cpux+ix
                    idiag=idown
                elif ip in ymin:
                    ileft=iy*cpux+ix-1
                    idown=ip
                    idiag=ileft
                #
                print ip,ileft,idiag,idown
                if ip != idown:
                    nup=boundary_dict[ip]['nodes_surf_ymin']
                    ndow=boundary_dict[idown]['nodes_surf_ymax']
                    merge_node_ck(nup,ndow)
                 
                    if idiag != idown:
                        if ip in ymax and ip not in xmin:
                            nlu=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck left up... r u
                            nru=boundary_dict[ileft]['node_curve_xmaxymax']
                            merge_node(nlu,nru)
                        if ip in xmax:
                            nrd=boundary_dict[ip]['node_curve_xmaxymin'] #node in curve chunck left up... r u
                            nru=boundary_dict[idown]['node_curve_xmaxymax']
                            merge_node(nrd,nru)
                        nru=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
                        nrd=boundary_dict[idown]['node_curve_xminymax']
                        nld=boundary_dict[idiag]['node_curve_xmaxymax']
                        nlu=boundary_dict[ileft]['node_curve_xmaxymin']
                        merge_node_4(nru,nrd,nld,nlu)
                    elif ip in xmin:
                        nlu=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
                        nld=boundary_dict[idown]['node_curve_xminymax']
                        merge_node(nld,nlu)
                        nru=boundary_dict[ip]['node_curve_xmaxymin'] #node in curve chunck right up... r u
                        nrd=boundary_dict[idown]['node_curve_xmaxymax']
                        merge_node(nrd,nru)
                        
                        
                        
                        
                #
                if ip != ileft:
                    nright=boundary_dict[ip]['nodes_surf_xmin']
                    nleft=boundary_dict[ileft]['nodes_surf_xmax']
                    merge_node_ck(nright,nleft)
                    #
                    #
                    if ip in ymin:
                        nrd=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right down... r u
                        nld=boundary_dict[ileft]['node_curve_xmaxymin']
                        merge_node(nrd,nld)
                    if ip in ymax:
                        nru=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck right up... r u
                        nlu=boundary_dict[ileft]['node_curve_xmaxymax']
                        merge_node(nlu,nru)
        
        cubit.cmd('set info on')
        cubit.cmd('set echo on')
        cubit.cmd('set journal on')
        
        
        #
        #
        cmd='group "negativejac" add quality hex all Jacobian high'
        cubit.cmd(cmd) 
        group_id_1=cubit.get_id_from_name("negativejac")
        n1=cubit.get_group_nodes(group_id_1)
        if len(n1) != 0:
            print 'error, negative jacobian after the equivalence node command, use --merge2 instead of --equivalence/--merge/--merge1'
    elif ckbound_method2 and not ckbound_method1 and len(filenames) != 1:
        if isinstance(merge_tolerance,list):
            tol=merge_tolerance[0]
        elif merge_tolerance:
            tol=merge_tolerance
        else:
            tol=100000
        #
        idiag=None
        for ix in range(cpuxmin,cpuxmax):
            for iy in range(cpuymin,cpuymax):
                ip=iy*cpux+ix
                print '******************* ',ip
                #
                #   ileft    |   ip
                #  --------------------
                #   idiag    |   idown
                #
                #
                if ip not in xmin and ip not in ymin:
                    ileft=iy*cpux+ix-1
                    idown=(iy-1)*cpux+ix
                    idiag=idown-1
                elif ip in xmin and ip in ymin:
                    ileft=ip
                    idown=ip
                elif ip in xmin:
                    ileft=ip
                    idown=(iy-1)*cpux+ix
                    idiag=idown
                elif ip in ymin:
                    ileft=iy*cpux+ix-1
                    idown=ip
                    idiag=ileft
                #
                #
                if ip != idown:
                    nup=boundary_dict[ip]['nodes_surf_ymin']
                    ndow=boundary_dict[idown]['nodes_surf_ymax']
                    for n1,n2 in zip(nup,ndow):
                        cubit.cmd('equivalence node '+str(n1)+' '+str(n2)+' tolerance '+str(tol))
                    if idiag != idown:
                        if ip in ymax and ip not in xmin:
                            nlu=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck left up... r u
                            nru=boundary_dict[ileft]['node_curve_xmaxymax']
                            for n in zip(nlu,nru):
                                cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
                        nru=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
                        nrd=boundary_dict[idown]['node_curve_xminymax']
                        nld=boundary_dict[idiag]['node_curve_xmaxymax']
                        nlu=boundary_dict[ileft]['node_curve_xmaxymin']
                        for n in zip(nru,nrd,nlu,nld):
                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
                    elif ip in xmin:
                        nru=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
                        nrd=boundary_dict[idown]['node_curve_xminymax']
                        for n in zip(nru,nrd):
                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
                #
                #
                if ip != ileft:
                    nright=boundary_dict[ip]['nodes_surf_xmin']
                    nleft=boundary_dict[ileft]['nodes_surf_xmax']
                    for n1,n2 in zip(nleft,nright):
                        cubit.cmd('equivalence node '+str(n1)+' '+str(n2)+' tolerance '+str(tol))
                    #
                    #
                    if ip in ymin:
                        nrd=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right down... r u
                        nld=boundary_dict[ileft]['node_curve_xmaxymin']
                        for n in zip(nrd,nld):
                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
                    if ip in ymax:
                        nru=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck right up... r u
                        nlu=boundary_dict[ileft]['node_curve_xmaxymax']
                        for n in zip(nru,nlu):
                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
        #
        #
        cmd='topology check coincident node face all tolerance '+str(tol*2)+' nodraw brief result group "checkcoinc"' 
        cubit.silent_cmd(cmd)
        group_id_1=cubit.get_id_from_name("checkcoinc")
        if group_id_1 != 0:
            n1=cubit.get_group_nodes(group_id_1)
            if len(n1) != 0:
                print 'error, coincident nodes after the equivalence node command, check the tolerance'
                import sys
                sys.exit()
        cmd='group "negativejac" add quality hex all Jacobian high'
        cubit.cmd(cmd) 
        group_id_1=cubit.get_id_from_name("negativejac")
        n1=cubit.get_group_nodes(group_id_1)
        if len(n1) != 0:
            print 'error, negative jacobian after the equivalence node command, check the mesh'
    elif ckbound_method1 and  ckbound_method2 and len(filenames) != 1:
        block_list=cubit.get_block_id_list()
        i=-1
        for block in block_list:
            ty=cubit.get_block_element_type(block)
            if ty == 'HEX8':
                i=i+1
                if isinstance(merge_tolerance,list):
                    try:
                        tol=merge_tolerance[i]
                    except:
                        tol=merge_tolerance[-1]
                elif merge_tolerance:
                    tol=merge_tolerance
                else:
                    tol=1
                cmd='topology check coincident node face in hex in block '+str(block)+' tolerance '+str(tol)+' nodraw brief result group "b'+str(block)+'"'
                cubit.cmd(cmd)
                print cmd
                cmd='equivalence node in group b'+str(block)+' tolerance '+str(tol)
                cubit.cmd(cmd)
                print cmd
        if isinstance(merge_tolerance,list):
            tol=max(merge_tolerance)
        elif merge_tolerance:
            tol=merge_tolerance
        else:
            tol=1
        #
        #
        cmd='topology check coincident node face all tolerance '+str(tol)+' nodraw brief result group "checkcoinc"' 
        cubit.silent_cmd(cmd)
        group_id_1=cubit.get_id_from_name("checkcoinc")
        if group_id_1 != 0:
            n1=cubit.get_group_nodes(group_id_1)
            if len(n1) != 0:
                print 'error, coincident nodes after the equivalence node command, check the tolerance'
                import sys
                sys.exit()
        cmd='group "negativejac" add quality hex all Jacobian high'
        cubit.silent_cmd(cmd) 
        group_id_1=cubit.get_id_from_name("negativejac")
        n1=cubit.get_group_nodes(group_id_1)
        if len(n1) != 0:
            print 'error, negative jacobian after the equivalence node command, use --merge instead of --equivalence'
Exemplo n.º 58
0
def makeGeometry(x, y):
    status = 0
    cubit.cmd("reset")
    cubit.cmd('open "circleGeom.trelis"')
    cubit.cmd("compress ids")
    num_base_vertex = len(cubit.get_entities("vertex"))

    x = numpy.array(x)
    y = numpy.array(y)
    target_surface = cubit.surface(1)
    vertex_on_surface = numpy.zeros(len(x), dtype=bool)
    for i in range(0, len(x)):
        vertex_on_surface[i] = target_surface.point_containment(
            [x[i], y[i], 0.])
        if vertex_on_surface[i] == True:
            cubit.cmd("create vertex " + str(x[i]) + " " + str(y[i]) +
                      " 0 on surface 1")

    nlcon = computeNonlinearConstraint(x, y)
    sys.stdout.write("Nonlinear Constraints: ")
    sys.stdout.write(str(nlcon))
    sys.stdout.write("\n")
    sys.stdout.flush()

    X = x[vertex_on_surface]
    Y = y[vertex_on_surface]
    num_active_pins = len(X)
    if num_active_pins == 0:
        # No pins on board, return with nonlinear constraint values
        status = 1
        return status, [], [], nlcon

    V = cubit.get_list_of_free_ref_entities("vertex")
    for i in range(0, len(V)):
        cubit.cmd("imprint volume all with vertex " + str(V[i]))
    cubit.cmd("delete free vertex all")
    cubit.cmd("compress ids")
    #for i in range(0,len(V)):
    #    cubit.cmd("nodeset 1 add vertex " + str(V[i]))
    cubit.cmd("surface all size 0.2")
    cubit.cmd("mesh surf all")
    cubit.cmd("surface all smooth scheme mean ratio cpu 0.1")
    cubit.cmd("smooth surf all")

    cubit.cmd("compress ids")

    V = numpy.zeros(num_active_pins, dtype=int)
    #N = numpy.zeros(num_active_pins, dtype=int)
    bc_xyz = [[] for i in range(0, num_active_pins)]
    cubit.cmd('create group "cf_crease_entities"')
    for i in range(0, num_active_pins):
        bc_xyz[i] = [X[i], Y[i], 0.]
        N = cubit.parse_cubit_list(
            "node", " at " + str(X[i]) + " " + str(Y[i]) + " 0.")
        for n in range(0, len(N)):
            nodeEdges = cubit.parse_cubit_list("edge", "in node " + str(N[n]))
            for e in range(0, len(nodeEdges)):
                cubit.cmd("cf_crease_entities add Edge " + str(nodeEdges[e]))

    EinC = cubit.parse_cubit_list("edge", " in curve 1")
    #for e in range(0,len(EinC)):
    #    cubit.cmd("cf_crease_entities add Edge " + str(EinC[e]))

    VinC = cubit.parse_cubit_list("node", " in curve 1")
    for n in range(0, len(VinC)):
        nxyz = cubit.get_nodal_coordinates(VinC[n])
        bc_xyz.append(list(nxyz))
        N = cubit.parse_cubit_list(
            "node", " at " + str(nxyz[0]) + " " + str(nxyz[1]) + " 0.")

        for n in range(0, len(N)):
            nodeEdges = cubit.parse_cubit_list("edge", "in node " + str(N[n]))
            for e in range(0, len(nodeEdges)):
                if nodeEdges[e] in EinC:
                    pass
                else:
                    cubit.cmd("cf_crease_entities add Edge " +
                              str(nodeEdges[e]))

    #V = cubit.get_entities("vertex")[num_base_vertex:]

    #cubit.cmd('create group "cf_crease_entities"')
    #bc_xyz = [[] for i in range(0,len(V))]
    #for i in range(0,len(V)):
    #    #ssID = cubit.get_next_sideset_id()
    #    bc_xyz[i] = list(cubit.vertex(V[i]).coordinates())
    #    cubit.parse_cubit_list("vertex", "at " + str(bc_)
    #    N = cubit.get_vertex_node(V[i])
    #    nodeEdges = cubit.parse_cubit_list('edge','in node ' + str(N))
    #    for e in range(0,len(nodeEdges)):
    #        #cubit.cmd("sideset " + str(ssID) + " add Edge " + str(nodeEdges[e]))
    #        cubit.cmd("cf_crease_entities add Edge " + str(nodeEdges[e]))
    #    #cubit.cmd("sideset " + str(ssID) + ' name "node_' + str(N) + '_edges"')

    cubit.cmd('save as "mesh.cub" overwrite')
    num_elem = len(cubit.get_entities("Face"))
    return status, bc_xyz, num_elem, nlcon