def __init__(self,hex27=False):
     super(mesh, self).__init__()
     self.mesh_name='mesh_file'
     self.nodecoord_name='nodes_coords_file'
     self.material_name='materials_file'
     self.nummaterial_name='nummaterial_velocity_file'
     self.absname='absorbing_surface_file'
     self.freename='free_surface_file'
     self.recname='STATIONS'
     try:
         version_cubit=float(cubit.get_version())
     except:
         version_cubit=float(cubit.get_version()[0:2])
     #
     if version_cubit >= 12:
         self.face='SHELL4'
     else:
         self.face='QUAD4'
     self.hex='HEX'
     self.hex27=hex27
     self.edge='BAR2'
     self.topo='face_topo'
     self.rec='receivers'
     if hex27: cubit.cmd('block all except (block 1001 1002 1003 1004 1005 1006) type hex27')
     self.block_definition()
     self.ngll=5
     self.percent_gll=0.172
     self.point_wavelength=5
     cubit.cmd('compress all')
     print 'version hex27'
def prepare_equivalence_new(name_group='lateral'):
    length={}
    cmd="group 'tmpn' add edge in face in group "+name_group
    cubit.cmd(cmd)
    ge=cubit.get_id_from_name("tmpn")
    e1=cubit.get_group_edges(ge)
    lengthmin=1e9
    for e in e1:
        lengthmin=min(lengthmin,cubit.get_mesh_edge_length(e))
        length[e]=lengthmin*.5
    cubit.cmd('delete group '+str(ge))                
    minvalue=min(length.values())
    maxvalue=max(length.values())
    #
    print 'min lentgh: ',minvalue,'max lentgh: ',maxvalue
    nbin= int((maxvalue/minvalue)/2.)+1
    factor=(maxvalue-minvalue)/nbin
    dic_new={}
    for k in length.keys():
        dic_new[k]=int((length[k]-minvalue)/factor)
    inv_length=invert_dict(dic_new)
    print inv_length.keys(),factor,minvalue
    ks=inv_length.keys()
    ks.sort()
    for k in range(0,len(inv_length.keys())-1):
        inv_length[ks[k]]=inv_length[ks[k]]+inv_length[ks[k+1]]
    return factor,minvalue,inv_length
Exemple #3
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
Exemple #4
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"
Exemple #5
0
def createSkinCurve2(curves):
    circles = ""
    for c in curves:
        circles += str(c) + " "
    cubit.cmd("create surface skin curve %s" % (circles))
    surfID = cubit.get_last_id("surface")
    return surfID
 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')
Exemple #7
0
def createCombineCurve(curves):
    cs = ""
    for c in curves:
        cs += str(c) + " "
    cubit.cmd("create curve combine curve %s" % (cs))
    curveID = cubit.get_last_id("curve")
    return curveID 
Exemple #8
0
def createSpline2(pts):
    points = ""
    for p in pts:
        points += str(p) + " "
    cubit.cmd("create curve spline vertex %s" % (points))
    splineID = cubit.get_last_id("curve")
    return splineID
 def seismic_resolution(self,edges,velocity,bins_d=None,bins_u=None,sidelist=None):
     """
     dt,edge_dt,freq,edge_freq=seismic_resolution(edges,velocity,bins_d=None,bins_u=None,sidelist=None,ngll=5,np=8)
         Given the velocity of a list of edges, seismic_resolution provides the minimum Dt required for the stability condition (and the corrisponding edge).
         Furthermore, given the number of gll point in the element (ngll) and the number of GLL point for wavelength, it provide the maximum resolved frequency.
     """
     ratiostore=1e10
     dtstore=1e10
     edgedtstore=-1
     edgeratiostore=-1
     for edge in edges:
         d=self.edge_length(edge)
         ratio=(1/2.5)*velocity/d*(self.ngll-1)/self.point_wavelength
         dt=.4*d/velocity*self.percent_gll
         if dt<dtstore:
            dtstore=dt
            edgedtstore=edge
         if ratio < ratiostore:
             ratiostore=ratio
             edgeratiostore=edge
         try:
             for bin_d,bin_u,side in zip(bins_d,bins_u,sidelist):
                 if ratio >= bin_d and ratio < bin_u:
                     command = "sideset "+str(side)+" edge "+str(edge)
                     cubit.cmd(command)
                     break
         except:
             pass
     return dtstore,edgedtstore,ratiostore,edgeratiostore
Exemple #10
0
 def runimport(geometryfile, iproc, filename=None):
     import start as start
     cubit = start.start_cubit()
     cfg = start.start_cfg(filename=filename)
     file1 = cfg.output_dir + '/' + geometryfile
     cubitcommand = 'open "' + file1 + '"  '
     cubit.cmd(cubitcommand)
 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 '  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()   
     cubit.cmd('set info on')
     cubit.cmd('set echo on')
def getAllVolumeIds ():

  cubit.cmd ('compress all')
  numVolumes = cubit.get_volume_count ()
  volumeIds  = [x for x in range (1, numVolumes+1)]
  
  return volumeIds
 def write(self, path=""):
     cubit.cmd("set info off")
     cubit.cmd("set echo off")
     cubit.cmd("set journal off")
     if len(path) != 0:
         if path[-1] != "/":
             path = path + "/"
     # mesh file
     self.mesh_write(path + self.mesh_name)
     # mesh material
     self.material_write(path + self.material_name)
     # mesh coordinates
     self.nodescoord_write(path + self.nodecoord_name)
     # material definitions
     self.nummaterial_write(path + self.nummaterial_name)
     # free surface: face_top
     self.free_write(path + self.freename)
     # absorbing surfaces: abs_***
     self.abs_write(path + self.absname)
     # any other surfaces: ***surface***
     self.surface_write(path)
     # receivers
     if self.receivers:
         self.rec_write(path + self.recname)
     cubit.cmd("set info on")
     cubit.cmd("set echo on")
 def write(self,path = ''):
     """ Write mesh in specfem2d format """
     print 'Writing '+self.recname+'.....'
     import os
     cubit.cmd('set info off') # Turn off return messages from Cubit commands
     cubit.cmd('set echo off') # Turn off echo of Cubit commands
     cubit.cmd('set journal off') # Do not save journal file
     if len(path) != 0: # If a path is supplied add a / at the end if needed
         if path[-1] != '/': path = path+'/'
     else:
         path = os.getcwd()+'/'
     self.mesh_write(path+self.mesh_name) # Write mesh file 
     self.material_write(path+self.material_name) # Write material file
     self.nodescoord_write(path+self.nodecoord_name) # Write nodes coord file
     self.free_write(path+self.freename) # Write free surface file (specfem2d needs it even if there is no free surface)
     if self.abs_mesh:
         self.abs_write(path+self.absname) # Write absorbing surface file
     if self.axisymmetric_mesh:
         self.axis_write(path+self.axisname) # Write axis on file
     if self.pml_layers:
         self.pmls_write(path+self.pmlname) # Write axis on file
     if self.write_nummaterial_velocity_file:
         self.nummaterial_write(path+self.nummaterial_name) # Write nummaterial file
     if self.receivers: 
         self.rec_write(path+self.recname) # If receivers has been set (as nodeset) write receiver file as well
     print 'Mesh files has been writen in '+path
     cubit.cmd('set info on') # Turn on return messages from Cubit commands
     cubit.cmd('set echo on') # Turn on echo of Cubit commands
 def __init__(self):
     super(mesh, self).__init__()
     self.mesh_name = 'mesh_file'
     self.axisymmetric_mesh = False # Will be set to true if a group self.pml_boun_name is found
     self.topo_mesh = False # Will be set to true if a group self.topo is found
     self.abs_mesh = False # Will be set to true if a group self.pml_boun_name or self.abs_boun_name is found
     self.pml_layers = False # Will be set to true if a group self.pml_boun_name is found
     self.write_nummaterial_velocity_file = False # Will be set to True if 2d blocks have 6 attributes
     self.nodecoord_name = 'nodes_coords_file' # Name of nodes coordinates file to create
     self.material_name = 'materials_file' # Name of material file to create
     self.nummaterial_name = 'nummaterial_velocity_file'
     self.absname = 'absorbing_surface_file' # Name of absorbing surface file to create
     self.freename = 'free_surface_file' # Name of free surface file to create
     self.pmlname = 'elements_cpml_list' # Name of cpml file to create
     self.axisname = 'elements_axis' # Name of axial elements file to create and name of the block containing axial edges
     self.recname = 'STATIONS'
     self.face = 'QUAD9'  # Faces' type
     self.edge = 'BAR3'   # Edges' type
     self.topo = 'topo'   # Name of the block containing topography edges
     self.pml_boun_name = ['pml_x_acoust','pml_z_acoust','pml_xz_acoust','pml_x_elast','pml_z_elast','pml_xz_elast']  # Name of the block containing pml layers elements
     self.abs_boun_name = ['abs_bottom','abs_right','abs_top','abs_left'] # Name of the block containing absorbing layer edges
     self.abs_boun = []  # block numbers for abs boundaries
     self.pml_boun = []  # block numbers for pml boundaries
     self.nabs = 4 # Maximum number of absorbing surfaces (4)
     self.rec = 'receivers'
     self.block_definition() # Import blocks features from Cubit
     self.ngll = 5
     self.percent_gll = 0.172
     self.point_wavelength = 5
     cubit.cmd('compress') # Fill the gaps in the numbering of the entities
Exemple #16
0
def cubit_command_check(iproc, command, stop=True):
    """
    Run a cubit command, checking if it performs correctly.
    If the command fails, it writes the result on a file
    "error_[processor number]" and stop the meshing process

    iproc = process number
    command = cubit command
    stop = if command fails, stop the meshing process (Default: True)

    return status variable (0 ok, -1 fail)

    """
    flag = True
    er = cubit.get_error_count()
    cubit.cmd(command)
    print command
    ner = cubit.get_error_count()
    if ner > er:
        text = '"Proc: ' + str(iproc) + ' ERROR ' + str(command) + \
            ' number of error ' + str(er) + '/' + str(ner) + '"'
        cubitcommand = 'comment ' + text
        cubit.cmd(cubitcommand)
        f = open('error_' + str(iproc) + '.log', 'a')
        f.write("CUBIT ERROR: \n" + text)
        f.close()
        if stop:
            raise Exception("CUBIT ERROR: " + text)
        flag = False
    return flag
def check_lateral_nodes(name_group='lateral'):
    cubit.cmd("group 'lateral_nodes' add Node in face in group "+name_group)
    ilateral_nodes=cubit.get_id_from_name('lateral_nodes')
    lateral_nodes=cubit.get_group_nodes(ilateral_nodes)
    cubit.cmd('del group '+str(ilateral_nodes))
    print name_group, ' nodes ',len(lateral_nodes)
    return len(lateral_nodes)
Exemple #18
0
def createSurfaceCurve2(curves):
    cc = ""
    for c in curves:
        cc += str(c) + " "
    cubit.cmd("create surface curve %s" % (cc))
    surfID = cubit.get_last_id("surface")
    return surfID
Exemple #19
0
def cubit_error_continue(iproc,command,n_er):
    """obsolete"""
    er=cubit.get_error_count()
    if  er >= n_er: 
        text='"Proc: '+str(iproc)+' ERROR continue '+str(command)+' number of error '+str(er)+' '+str(n_er)+'"'
        cubit.cmd('comment '+ text)
        print 'error: ',text
    return er
Exemple #20
0
def cubit_error_stop(iproc,command,ner):
    """obsolete"""
    er=cubit.get_error_count()
    if er > ner: 
       text='"Proc: '+str(iproc)+' ERROR '+str(command)+' number of error '+str(er)+'/'+str(ner)+'"'
       cubitcommand = 'comment '+text
       cubit.cmd(cubitcommand)
       raise NameError, text
Exemple #21
0
def createVolume(surfs):
    volID = cubit.get_owning_volume("surface", surfs[-1])
    ss = ""
    for s in surfs:
        ss += str(s) + " "
    cubit.cmd("create volume surface %s noheal" % (ss))
    #volID = cubit.get_last_id("volume")
    return volID
 def get_face_connectivity(self,ind):
     if self.hex27:
             cubit.silent_cmd('group "nf" add Node in face '+str(ind))
             group1 = cubit.get_id_from_name("nf")
             result=cubit.get_group_nodes(group1)
             cubit.cmd('del group '+str(group1))
     else:
         result=cubit.get_connectivity('face',ind)
     return result
 def get_hex_connectivity(self,ind):
     if self.hex27:
             cubit.silent_cmd('group "nh" add Node in hex '+str(ind))
             group1 = cubit.get_id_from_name("nh")
             result=cubit.get_group_nodes(group1)
             if len(result) != 27: print 'error hex27'
             cubit.cmd('del group '+str(group1))
     else:
         result=cubit.get_connectivity('hex',ind)
     return result
Exemple #24
0
 def forcing_write(self,forcname):
     """ Write forcing surfaces on file : forcname """
     cubit.cmd('set info off') # Turn off return messages from Cubit commands
     cubit.cmd('set echo off') # Turn off echo of Cubit commands
     cubit.cmd('set journal off') # Do not save journal file
     from sets import Set
     forceedge = open(forcname,'w')
     print 'Writing '+forcname+'.....'
     edges_forc = [Set()]*self.nforc # edges_forc[0] will be a Set containing the nodes describing the forcing boundary
     # (index 0 : bottom, index 1 : right, index 2 : top, index 3 : left)
     nedges_all = 0 # To count the total number of forcing edges
     for block,flag in zip(self.block_bc,self.block_bc_flag): # For each 1D block
         for iforc in range(0, self.nforc): # iforc = 0,1,2,3 : for each forcing boundaries
             if block == self.forcing_boun[iforc]: # If the block considered correspond to the boundary
                 edges_forc[iforc] = Set(cubit.get_block_edges(block)) # Store each edge on edges_forc
                 nedges_all = nedges_all+len(edges_forc[iforc]) # add the number of edges to nedges_all
     toWritetoFile = [""]*(nedges_all+1)
     toWritetoFile[0] = '%10i\n' % nedges_all # Write the total number of forcing edges to the first line of file
     #forceedge.write('%10i\n' % nedges_all) # Write the total number of forcing edges to the first line of file
     print 'Number of edges', nedges_all
     #id_element = 0
     indexFile = 1
     for block,flag in zip(self.block_mat,self.block_flag): # For each 2D block
             quads = cubit.get_block_faces(block) # Import quads id
             for quad in quads: # For each quad
                 #id_element = id_element+1 # id of this quad
                 edges = Set(cubit.get_sub_elements("face", quad, 1)) # Get the lower dimension entities associated with a higher dimension entities.
                 # Here it gets the 1D edges associates with the face of id "quad". Store it as a Set
                 for iforc in range(0,self.nforc): # iforc = 0,1,2,3 : for each forcing boundaries
                     intersection = edges & edges_forc[iforc]  # Contains the edges of the considered quad that is on the forcing boundary considered
                     if len(intersection) != 0: # If this quad touch the forcing boundary considered
                         nodes = cubit.get_connectivity('face',quad) # Import the nodes describing the quad
                         nodes = self.jac_check(list(nodes)) # Check the jacobian of the quad
                         for e in intersection: # For each edge on the forcing boundary considered
                             node_edge = cubit.get_connectivity('edge',e) # Import the nodes describing the edge
                             nodes_ok = []
                             for i in nodes: # Loop on the nodes of the quad
                                 if i in node_edge: # If this node is belonging to forcing surface
                                     nodes_ok.append(i) # add it to nodes_ok
                             # forcname contains 1/ element number, 2/ number of nodes that form the acoustic forcing edge
                             # (which currently must always be equal to two, see comment below),
                             # 3/ first node on the acforcing surface, 4/ second node on the acforcing surface
                             # 5/ 1 = IBOTTOME, 2 = IRIGHT, 3 = ITOP, 4 = ILEFT
                             #txt = '%10i %10i %10i %10i %10i\n' % (id_element,2,nodes_ok[0],nodes_ok[1],iforc+1)
                             txt = '%10i %10i %10i %10i %10i\n' % (quad,2,nodes_ok[0],nodes_ok[1],iforc+1)
                             # Write the id of the quad, 2 (number of nodes describing a free surface elements), the nodes and the type of boundary
                             #print indexFile
                             toWritetoFile[indexFile] = txt
                             indexFile = indexFile + 1
                             #forceedge.write(txt)
     forceedge.writelines(toWritetoFile)
     forceedge.close()
     print 'Ok'
     cubit.cmd('set info on') # Turn on return messages from Cubit commands
     cubit.cmd('set echo on') # Turn on echo of Cubit commands
Exemple #25
0
 def group_timestep(self):
     tot = 0.0
     if self.dt_hyst is not None:
         dtmax = max(self.dt_hyst.values())
         dt = self.hyst(self.dt, dtmax, self.dt_hyst)
         factor = (dtmax - self.dt) / self.nbin
         for i in range(0, self.nbin + 1):
             if dt.has_key(i):
                 txt = 'group "timestep_%.1e_%.1e" add hex ' % (self.dt + factor * i, self.dt + factor * (i + 1))
                 txt = txt + " ".join(str(hh) for hh in dt[i])
                 cubit.cmd(txt)
Exemple #26
0
 def group_period(self):
     tot = 0.0
     if self.period_hyst is not None:
         pmin = min(self.period_hyst.values())
         period = self.hyst(pmin, self.period, self.period_hyst)
         factor = (self.period - pmin) / self.nbin
         for i in range(0, self.nbin + 1):
             if period.has_key(i):
                 txt = 'group "period_%.1e_%.1e" add hex ' % (pmin + factor * i, pmin + factor * (i + 1))
                 txt = txt + " ".join(str(hh) for hh in period[i])
                 cubit.cmd(txt)
def export2SPECFEM3D(path_exporting_mesh_SPECFEM3D='.',hex27=False,cpml=False,cpml_size=False,top_absorbing=False):
    sem_mesh=mesh(hex27,cpml,cpml_size,top_absorbing)
    #sem_mesh.block_definition()
    #print sem_mesh.block_mat
    #print sem_mesh.block_flag
    #
    sem_mesh.write(path=path_exporting_mesh_SPECFEM3D)
    print 'END SPECFEM3D exporting process......'
    if cpml:
        cmd='save as "cpml.cub" overwrite'
        cubit.cmd(cmd)
Exemple #28
0
 def runsave(geometryfile,iproc,filename=None):
     import start as start
     cubit                   = start.start_cubit()
     cfg                         = start.start_cfg(filename=filename)
     flag=[0]
     ner=cubit.get_error_count()
     cubitcommand= 'save as "'+ cfg.output_dir+'/'+geometryfile+ '"  overwrite' 
     cubit.cmd(cubitcommand)                                                    
     ner2=cubit.get_error_count()                                             
     if ner == ner2:
         flag=[1]
     return flag
Exemple #29
0
 def highlight_edgemax(self, low=None, high=None):
     if low is None and high is not None:
         hexlist = self.show(low, self.max_edge_length, self.edgemax_hyst)
     elif low is not None and high is None:
         hexlist = self.show(self.min_edge_length, high, self.edgemax_hyst)
     if low is not None and high is not None:
         hexlist = self.show(low, high, self.edgemax_hyst)
     else:
         hexlist = self.hex_max_edge_length
     command = "highlight hex " + str(hexlist)
     command = command.replace("[", " ").replace("]", " ").replace("(", " ").replace(")", " ")
     cubit.cmd(command)  #
Exemple #30
0
 def abs_write(self,absname):
     """ Write absorbing surfaces on file : absname """
     cubit.cmd('set info off') # Turn off return messages from Cubit commands
     cubit.cmd('set echo off') # Turn off echo of Cubit commands
     cubit.cmd('set journal off') # Do not save journal file.
     from sets import Set
     # if not absname: absname = self.absname
     absedge = open(absname,'w')
     print 'Writing '+absname+'.....'
     edges_abs = [Set()]*self.nabs # edges_abs[0] will be a Set containing the nodes describing bottom adsorbing boundary
     # (index 0 : bottom, index 1 : right, index 2 : top, index 3 : left)
     nedges_all = 0 # To count the total number of absorbing edges
     for block,flag in zip(self.block_bc,self.block_bc_flag): # For each 1D block
         for iabs in range(0, self.nabs): # iabs = 0,1,2,3 : for each absorbing boundaries
             if block == self.abs_boun[iabs]: # If the block considered correspond to the boundary
                 edges_abs[iabs] = Set(cubit.get_block_edges(block)) # Store each edge on edges_abs
                 nedges_all = nedges_all+len(edges_abs[iabs]); # add the number of edges to nedges_all
     toWritetoFile = [""]*(nedges_all+1)
     toWritetoFile[0] = '%10i\n' % nedges_all # Write the total number of absorbing edges to the first line of file
     #absedge.write('%10i\n' % nedges_all) # Write the total number of absorbing edges to the first line of file
     print 'Number of edges', nedges_all
     #id_element = 0
     indexFile = 1
     for block,flag in zip(self.block_mat,self.block_flag): # For each 2D block
             quads = cubit.get_block_faces(block) # Import quads id
             for quad in quads: # For each quad
                 #id_element = id_element+1 # id of this quad
                 edges = Set(cubit.get_sub_elements("face", quad, 1)) # Get the lower dimension entities associated with a higher dimension entities.
                 # Here it gets the 1D edges associates with the face of id "quad". Store it as a Set
                 for iabs in range(0,self.nabs): # iabs = 0,1,2,3 : for each absorbing boundaries
                     intersection = edges & edges_abs[iabs]  # Contains the edges of the considered quad that is on the absorbing boundary considered
                     if len(intersection) != 0: # If this quad touch the absorbing boundary considered
                         nodes = cubit.get_connectivity('face',quad) # Import the nodes describing the quad
                         nodes = self.jac_check(list(nodes)) # Check the jacobian of the quad
                         for e in intersection: # For each edge on the absorbing boundary considered
                             node_edge = cubit.get_connectivity('edge',e) # Import the nodes describing the edge
                             nodes_ok = []
                             for i in nodes: # Loop on the nodes of the quad
                                 if i in node_edge: # If this node is belonging to absorbing surface
                                     nodes_ok.append(i) # Add it to nodes_ok
                             #txt = '%10i %10i %10i %10i %10i\n' % (id_element,2,nodes_ok[0],nodes_ok[1],iabs+1)
                             txt = '%10i %10i %10i %10i %10i\n' % (quad,2,nodes_ok[0],nodes_ok[1],iabs+1)
                             # Write the id of the quad, 2 (number of nodes describing a free surface elements), the nodes and the type of boundary
                             toWritetoFile[indexFile] = txt
                             indexFile = indexFile + 1
                             #absedge.write(txt)
     absedge.writelines(toWritetoFile)
     absedge.close()
     print 'Ok'
     cubit.cmd('set info on') # Turn on return messages from Cubit commands
     cubit.cmd('set echo on') # Turn on echo of Cubit commands
Exemple #31
0
print sys.path

cubit.init([""])

# gets version string
cubit_version = cubit.get_version()
print "version: ",cubit_version

# extracts major number
v = cubit_version.split('.')
cubit_version_major = int(v[0])
print "major version number: ",cubit_version_major

# current work directory
cubit.cmd('pwd')

# Creating the volumes
cubit.cmd('reset')

# single volume
cubit.cmd('brick x 134000 y 134000 z 60000')
cubit.cmd('volume 1 move x 67000 y 67000 z -30000')

# two merged volumes
#cubit.cmd('brick x 67000 y 134000 z 60000')
#cubit.cmd('volume 1 move x 33500 y 67000 z -30000')
#cubit.cmd('brick x 67000 y 134000 z 60000')
#cubit.cmd('volume 2 move x 100500 y 67000 z -30000')
#cubit.cmd('merge all')
Exemple #32
0
#### Then you can run cubit2specfem2d.py
#### Author alexis dot bottero at gmail dot com
###########################################################################

import cubit

lx = 50000  #5000
lz = 50000  #500
nPml = 3  # PMLs Thickness (number of elements in pmls)

######################

elementSize = 1000  # Mean element size

#cubit.cmd('cd "/home1/bottero/Desktop/mesh2d"') # Change Cubit working directory
cubit.cmd('reset')

### Create the rectangle :
cubit.cmd('create surface rectangle width ' + str(lx) + ' height ' + str(lz) +
          ' yplane')  # Create a lx*lz rectangle
cubit.cmd('volume 1 move x ' + str(lx / 2.0) + ' z ' +
          str(-lz / 2.0))  # To get correct coordinates

### Meshing the surface :
cubit.cmd('surface 1 size ' +
          str(elementSize))  # Define the size of an element in surface 1
cubit.cmd('mesh surface 1')  # Mesh the surface

### Define blocks and material properties
cubit.cmd('#### DEFINE MATERIAL PROPERTIES #######################')
cubit.cmd(' block 1 face in surface 1')
Exemple #33
0
def MilledLayer(Body_IDs, BB, Alpha, Theta1, Theta2, secmin, Xoffset=.5):
    import cubit
    import numpy as np
    ###
    ###      Body_ID: a single volume ID
    ###      BB:            bounding box in the form [xmin, xmax, ymin, ymax, zmin, zmax]
    ###      Alpha:     lamination angle
    ###      Theta1:    thickness of layer 1
    ###      Theta2:    thickness of layer 2
    ###      secmin:    the cross section after machining
    ###      Xoffset: distance along the x-axis between the center of the bounding box
    ###                         and the first interface l1-l2 if specified, in fraction of Theta1
    ###                         i.e. 0 -> interface l2-l1 at center
    ###                                  1 -> interface l1-l2 at center
    ###                         otherwise, the center of BB corresponds to the center of a Layer1
    ###                         i.e. Xoffset = .5
    ###
    YL = np.sqrt((BB[1] - BB[0])**2 + (BB[3] - BB[2])**2)
    ZL = BB[5] - BB[4]
    XC = (BB[0] + BB[1]) / 2.
    YC = (BB[2] + BB[3]) / 2.
    ZC = (BB[4] + BB[5]) / 2.
    Theta = Theta1 + Theta2
    if Alpha > 0:
        l1 = (BB[0] - XC) * np.cos(np.radians(Alpha)) + (BB[2] - YC) * np.sin(
            np.radians(Alpha))
        l2 = (BB[1] - XC) * np.cos(np.radians(Alpha)) + (BB[3] - YC) * np.sin(
            np.radians(Alpha))
    else:
        l1 = (BB[0] - XC) * np.cos(np.radians(Alpha)) + (BB[3] - YC) * np.sin(
            np.radians(Alpha))
        l2 = (BB[1] - XC) * np.cos(np.radians(Alpha)) + (BB[2] - YC) * np.sin(
            np.radians(Alpha))
    n1 = int(np.ceil(l1 / Theta))
    n2 = int(np.ceil(l2 / Theta))
    for i in range(n1, n2):
        X = XC + i * np.cos(
            np.radians(Alpha)) * Theta + Theta1 * (Xoffset - .5)
        Y = YC + i * np.sin(np.radians(Alpha)) * Theta
        cubit.cmd('create brick X %f Y %f Z %f' % (Theta1, YL, ZL))
        tmp_ID = cubit.get_last_id("volume")
        cubit.cmd('move volume %i X %f Y %f Z %f' %
                  (tmp_ID, X, Y, ZL / 2. + secmin[1]))
        if not Alpha == 0.:
            ### cubit doesn't like rotations will 0 angle...
            cubit.cmd('create vertex X %f Y %f Z %f' % (X, Y, BB[4]))
            v1_ID = cubit.get_last_id("vertex")
            cubit.cmd('create vertex X %f Y %f Z %f' % (X, Y, BB[5]))
            v2_ID = cubit.get_last_id("vertex")
            cubit.cmd('rotate volume %i about vertex %i vertex %i angle %f' %
                      (tmp_ID, v1_ID, v2_ID, Alpha))
            cubit.cmd('delete vertex %i' % v1_ID)
            cubit.cmd('delete vertex %i' % v2_ID)
        (Body_IDs, tmp_layer) = WebcutTool(Body_IDs, tmp_ID, delete=False)
        cmd = "delete volume "
        for v in tmp_layer:
            cmd += " %i" % v
        cubit.cmd(cmd)
        cubit.cmd("move volume %i Z %f" %
                  (tmp_ID, -ZL - secmin[1] + secmin[0]))
        (Body_IDs, tmp_layer) = WebcutTool(Body_IDs, tmp_ID, delete=True)
        cmd = "delete volume "
        for v in tmp_layer:
            cmd += " %i" % v
        cubit.cmd(cmd)
    return (Body_IDs)
Exemple #34
0
def GroupAddVolList(groupname, vol_IDs):
    import cubit
    cmd = 'group "%s" add volume ' % groupname
    for vol in vol_IDs:
        cmd += ' %i' % vol
    cubit.cmd(cmd)
Exemple #35
0
def PacmanCoinLayeredCreate(R,
                            lx,
                            ly,
                            lz,
                            alpha,
                            theta1,
                            theta2,
                            thetacrack,
                            xc=0):
    import cubit
    import numpy as np
    ###
    ### Create Main body
    ###
    OUTSIDE_3D = []
    cubit.cmd("Create cylinder height %f radius %f" % (lz, R))
    OUTSIDE_3D.append(cubit.get_last_id("volume"))
    ###
    ### Create wedge
    ###
    w_ID = []
    cubit.cmd("create vertex X %f Y 0 Z %f" % (xc, -lz))
    w_ID.append(cubit.get_last_id("vertex"))
    X = 1.1 * R * np.cos(np.radians(thetacrack / 2.))
    Y = 1.1 * R * np.sin(np.radians(thetacrack / 2.))
    cubit.cmd("create vertex X %f Y %f Z %f" % (-X, Y, -lz))
    w_ID.append(cubit.get_last_id("vertex"))
    cubit.cmd("create vertex X %f Y %f Z %f" % (-X, -Y, -lz))
    w_ID.append(cubit.get_last_id("vertex"))
    cubit.cmd("create surface vertex %i %i %i" % (w_ID[0], w_ID[1], w_ID[2]))
    cubit.cmd("sweep surface %i perpendicular distance %f" %
              (cubit.get_last_id("surface"), 2 * lz))
    WEDGE = cubit.get_last_id("volume")
    ###
    ### remove crack
    ###
    cubit.cmd("subtract volume %i from volume %i" % (WEDGE, OUTSIDE_3D[0]))
    ###
    ### Create center coin
    ###
    cubit.cmd("Create cylinder height %f major radius %f minor radius %f" %
              (lz, lx, ly))
    CYL = cubit.get_last_id("volume")
    (OUTSIDE_3D, CYL_ID) = WebcutTool(OUTSIDE_3D, CYL, delete=True)
    ###
    ### create layers
    ###
    bb = [-lx, lx, -ly, ly, -2. * lz, 2. * lz]
    print('CYL_ID, bb, alpha, theta1, theta2', CYL_ID, bb, alpha, theta1,
          theta2)
    (LAYER1_3D, LAYER2_3D) = Layer(CYL_ID, bb, alpha, theta1, theta2, 0.)
    ###
    ### imprint and merge
    ###
    cubit.cmd("imprint all")
    cubit.cmd("merge all")
    ###
    ### groups
    ###
    GroupAddVolList("LAYER1_3D", LAYER1_3D)
    GroupAddVolList("LAYER2_3D", LAYER2_3D)
    GroupAddVolList("OUTSIDE_3D", OUTSIDE_3D)
Exemple #36
0
import cubit
cubit.init([""])
try:

from geocubitlib import boundary_definition
from geocubitlib import cubit2specfem3d
except:

 import boundary_definition
import cubit2specfem3d

import os
import sys

cubit.cmd('reset')
cubit.cmd('brick x 134000 y 134000 z 60000')

# This seems to conflict with boundary_definition.py
# ....which leaves the model space at e.g. x=[-67,67] km
cubit.cmd('volume 1 move x 67000 y 67000 z -30000')

# create vertices for discontinuity
cubit.cmd('split curve 9  distance 3000')
cubit.cmd('split curve 10  distance 3000')
cubit.cmd('split curve 11  distance 3000')
cubit.cmd('split curve 12  distance 3000')

# create surface for interface
cubit.cmd('create surface vertex 9 10 12 11')
Exemple #37
0
import sys

import cubit
try:
    #cubit.init([""])
    cubit.init(["-noecho", "-nojournal"])
except:
    pass

version = cubit.get_version()
version_major = int(version.split(".")[0])
version_minor = int(version.split(".")[1])
print("cubit version: ", version)

# allows for elements in multiple block definitions (topo, absorbing faces,..)
cubit.cmd('set duplicate block elements on')

# mesh
#cubit.cmd('open "coffee_cup_with_handle_CUBIT_mesh.cub"')

## block definitions
#
# works with coffee_cup_with_handle_CUBIT_mesh.cub
cubit.cmd('delete block all')

# acoustic volume
if version_major <= 15:
    # older cubit versions
    cubit.cmd('block 1 hex in volume 2')
else:
    # version 16
Exemple #38
0
def mesh_layercake_regularmap(filename=None):

    import start as start
    mpiflag, iproc, numproc, mpi = start.start_mpi()
    from utilities import importgeometry, savemesh, get_v_h_list
    from utilities import cubit_command_check, get_cubit_version
    #
    # numpy = start.start_numpy()
    cfg = start.start_cfg(filename=filename)
    # from math import sqrt
    from sets import Set

    version_cubit = get_cubit_version()

    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])
                str_interval = [str(iv[0]) for iv in interval_store]
                cmd = "curve " + ' '.join(str_interval) + \
                      " interval " + str(interval_min)
                cubit.cmd(cmd)
                command = "curve " + \
                    ' '.join(str(iv[0])
                             for iv in interval_store) + " scheme equal"
                cubit.cmd(command)
        command = "surface " + str(s) + " scheme submap"
        cubit.cmd(command)

    # 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)
            if version_cubit < 16:
                command_set_meshvol = '''volume all redistribute nodes on
                volume all autosmooth target off
                volume all scheme Sweep Vector 0 0 -1
                volume all sweep smooth Auto
                '''
            else:
                command_set_meshvol = '''volume all redistribute nodes on
                volume all autosmooth target off
                volume all scheme Sweep Vector 0 0 -1
                '''
            status2 = cubit_command_check(iproc,
                                          command_set_meshvol,
                                          stop=False)
            status2 = cubit_command_check(iproc, command, stop=False)
            if not status2:
                _surf = cubit.get_relatives('volume', vol[id_volume].ID,
                                            'surface')
                local_o_surf = [x for x in _surf if x in surf_or]
                cubit.cmd('volume ' + str(vol[id_volume].ID) +
                          ' redistribute nodes off')
                cubit.cmd('volume ' + str(vol[id_volume].ID) +
                          ' scheme Sweep  source surface ' +
                          ' '.join(str(x) for x in local_o_surf[0:-1]) +
                          ' target surface ' + str(local_o_surf[-1]))
                cubit.cmd('volume ' + str(vol[id_volume].ID) +
                          ' autosmooth_target off')
                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:
        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)
Exemple #39
0
# topography file, data points per lon-increment
inputFile = 'ptopo.mean.utm'

# X coordinate in topography file repeats after line
nstep = 34

#############################################################

# converts xyz to utm
#os.system('./convert_lonlat2utm.pl ptopo.mean.xyz 10 > ptopo.mean.utm ')

# reads in points
print '#reading from file: ', inputFile

cubit.cmd('reset')
cubit.cmd('echo off')
cubit.cmd('Graphics Pause')

# creates point vertices
print '#creating points...'
count = 0
for line in fileinput.input(inputFile):
    count = count + 1
    #print '# '+str(count)+' point: '+line
    lineitems = line.split()
    x = lineitems[0]
    y = lineitems[1]
    z = lineitems[2]
    xyz = str(x) + ' ' + str(y) + ' ' + str(z)
    #print '#point: ',xyz
Exemple #40
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)
Exemple #41
0
 def translate2original(xmin,ymin):
     cubit.cmd('move surface all x '+str(xmin)+' y '+str(ymin))
Exemple #42
0
def main():
    import os
    import os.path
    import numpy as np
    import pymef90
    import shutil

    parser = LCSS.createParser()
    options = pymef90.parse(parser, key='configfile')
    Geometry = pymef90.parseGroup(parser, options, 'Geometry')
    str = repr(Geometry).encode("utf-8")
    options.hash = hashlib.sha1(str).hexdigest()
    D = options.__dict__
    D['dt'] = (options.time_max - options.time_min) / (
        options.time_numstep - 1) / options.time_numsubstep
    options.__dict__ = pymef90.PrepareJob(Geometry, options.__dict__)
    print(options)
    scriptpath = os.path.dirname(os.path.abspath(__file__))

    ###
    ### Search for the mesh file, and generate it if it is missing
    ###
    archmeshprefix = os.path.join(options.meshdir, options.hash)
    if not os.path.isfile(archmeshprefix + '.gen') or options.forcemesh:
        if options.dontmesh:
            print('Cannot find mesh, exiting')
            return -1
        else:
            print('{0}.gen not found: generating new mesh'.format(
                archmeshprefix))
            if not os.path.exists(options.meshdir):
                os.makedirs(options.meshdir)
            ext = os.path.splitext(options.geofile)[-1][1:].lower()
            if ext == 'geo':
                pymef90.argsWrite(
                    options.geofile,
                    os.path.join(options.meshdir, options.hash + '.geo'),
                    options.__dict__)
                os.chdir(options.meshdir)
                cmd = 'gmsh -2 -format msh2 -order {order} {hash}.geo'.format(
                    **options.__dict__)
                print("Now running {0}".format(cmd))
                os.system(cmd)

                cmd = 'gmsh2exo.py --force {hash}.msh {hash}.gen'.format(
                    **options.__dict__)
                print("Now running {0}".format(cmd))
                os.system(cmd)
            elif ext == 'jou':

                pymef90.argsWrite(
                    options.geofile,
                    os.path.join(options.meshdir, options.hash + '.jou'),
                    options.__dict__)
                os.chdir(options.meshdir)
                journal = open(
                    os.path.join(options.meshdir, options.hash + '.jou'))
                import cubit
                cubit.init([''])
                for l in journal.readlines():
                    cubit.cmd(l)
                cubit.cmd('set exodus netcdf4 off')
                cubit.cmd('set large exodus file on')
                cubit.cmd('set journal off')
                cubit.cmd(
                    'export mesh "{0}.gen"  dimension 2  overwrite '.format(
                        os.path.join(options.meshdir, options.hash)))
            else:
                print(
                    "unknown geometry file format {0}. Unable to generate mesh"
                    .format(options.geofile))
    else:
        print("Found matching mesh at {0}".format(archmeshprefix))

    ###
    ### Create computation directory
    ###
    if options.meshonly:
        return 0
    ###
    ### Write 00_INFO.txt and 00_INFO.json
    ###
    if not os.path.exists(options.workdir):
        os.makedirs(options.workdir)
    os.chdir(options.workdir)

    #pymef90.Dictwritetxt(options.__dict__,'00_INFO.txt',overwrite=False)
    pymef90.DictwriteJSON(options.__dict__, '00_INFO.json', overwrite=True)
    shutil.copyfile(archmeshprefix + '.gen',
                    os.path.join(options.workdir, options.prefix + '.gen'))

    ###
    ### Prepare vDef yaml options file
    ####
    pymef90.argsWrite(options.yamlfile,
                      os.path.join(options.workdir, options.prefix + '.yaml'),
                      options.__dict__)

    ### Generate heat flux in output file
    # find the flux script within the path and pythonpath
    for binpath in sys.path + os.getenv('PATH').split(':'):
        if os.path.exists(os.path.join(binpath, "LCSS_flux3.py")):
            break
    cmd = '{0} -i {prefix}.gen -o {prefix}_out.gen --cs 1 2 --force --initialPos {initialPos[0]}  {initialPos[1]} {initialPos[2]} --finalPos {finalPos[0]} {finalPos[1]} {finalPos[2]} --r0 {criticalRadius} --Wabs {intensity} --time_min {time_min} --time_max {time_max} --time_numstep {time_numstep}'.format(
        os.path.join(binpath, 'LCSS_flux3.py'), **options.__dict__)
    print('Now running: {0}'.format(cmd))
    os.system(cmd)

    ### Run the computation
    if os.path.isfile(
            os.path.join(os.getenv("MEF90_DIR"), "bin",
                         os.getenv("PETSC_ARCH"), "vDef")):
        bin = os.path.join(os.getenv("MEF90_DIR"), "bin",
                           os.getenv("PETSC_ARCH"), "vDef")
    else:
        print('Cannot find binary for vDef')
        sys.exit(-1)

    if options.mpiexec == 'mpirun':
        options.mpiexec += ' -machinefile {0}'.format(
            os.getenv("PBS_NODEFILE"))
    cmd1 = options.mpiexec + ' {0:s} -prefix {prefix:s} -options_file_yaml {prefix:s}.yaml '.format(
        bin, **options.__dict__)
    if options.extraopts:
        cmd1 += options.extraopts
    if options.hypre:
        cmd1 += ' -disp_pc_type hypre -disp_pc_hypre_type boomeramg -disp_pc_hypre_boomeramg_strong_threshold 0.9 '
    if options.ml:
        cmd1 += ' -disp_pc_type ml'
    #if options.unilateralcontact == 'none':
    #    cmd1 += ' -disp_snes_type ksponly'

    #cmd1 += ' -temp_ksp_monitor_true_residual -temp_ksp_converged_reason'
    cmd1 += ' -disp_snes_monitor -disp_ksp_converged_reason'

    print("Now running: {0}".format(cmd1))
    os.system(cmd1)

    if options.postprocess:
        cmd = 'ml visit; visit -cli -nowin -s {0} --output {1}.png {1}_out.gen;'.format(
            os.path.join(binpath, "LCSS_PNG.py"), options.prefix)
        print('now running: {0}'.format(cmd))
        os.system(cmd)
        cmd = 'ml visit; visit -cli -nowin -s {0} --output {1}_disp.png --displacementScaling 1 {1}_out.gen;'.format(
            os.path.join(binpath, "LCSS_PNG.py"), options.prefix)
        print('now running: {0}'.format(cmd))
        os.system(cmd)
Exemple #43
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))
        #
        if verticalsandwich:
            elev=numpy.zeros([nx,ny,cfg.nxvol],float)
        else:
            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
        if verticalsandwich:
            for i in range(0,cfg.nxvol):
                elev[:,:,i] = cfg.xwidth[i]
        else:
            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
    if verticalsandwich:
        nlayer=cfg.nxvol
    else:
        nlayer=cfg.nz
    
    for inz in range(0,nlayer):
        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' and not verticalsandwich:
                    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)                                                                              
                    #
                    if verticalsandwich:
                        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( 0 )
                        cubit.cmd(cubitcommand)
                        #
                        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( 0 )
                        cubit.cmd(cubitcommand)
                    else:
                        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':
                if verticalsandwich:
                    zvertex=cfg.xwidth[inz]
                    lv=cubit.get_last_id("vertex")                        
                    x_current,y_current=geo2utm(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu],'utm')
                    x_current = x_current + zvertex;
                    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')
                    x_current = x_current + zvertex;
                    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')
                    x_current = x_current + zvertex;
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( 0 )
                    cubit.cmd(cubitcommand)
                    #
                    x_current,y_current=geo2utm(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu],'utm')
                    x_current = x_current + zvertex;
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( 0 )
                    cubit.cmd(cubitcommand)
                else:
                    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 nlayer == 1:
            nsurface=2
        else:
            nsurface=nlayer
        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")
            for v in list_vol:
                sv=cubit.get_relatives("volume",v,"surface")
                if len(sv) <=1: cubit.cmd("del vol "+str(v))
            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)
Exemple #44
0
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
Exemple #45
0
#!/usr/bin/env python

import cubit
cubit.init([""])


import os
import sys

# Creating the volumes
cubit.cmd('reset')
cubit.cmd('brick x 134000 y 134000 z 60000')
cubit.cmd('volume 1 move x 67000 y 67000 z -30000')


# Meshing the volumes
elementsize = 3750.0

cubit.cmd('volume 1 size '+str(elementsize))
cubit.cmd('mesh volume 1')


#
# GEOCUBIT
#
# adds path to geocubit (if not setup yet)
sys.path.append('../../CUBIT_GEOCUBIT/')

print "path: "
print sys.path
print ""
Exemple #46
0
def surface_regular_grid(isurface=0, cfgname=None):
    """
    create an acis surface from a regular lon/lat/z grid
    """
    from utilities import geo2utm
    import start as start
    #
    #
    cfg = start.start_cfg(cfgname)
    numpy = start.start_numpy()

    #

    def create_line_u(ind, n, step, data, unit):
        last_curve_store = cubit.get_last_id("curve")
        command = 'create curve spline '
        for i in range(0, n):
            if i % step == 0:
                lon, lat, z = data[i + ind][0], data[i + ind][1], data[i +
                                                                       ind][2]
                x, y = geo2utm(lon, lat, unit)
                txt = ' Position ' + str(x) + ' ' + str(y) + ' ' + str(z)
                command = command + txt
                # print(command)
        cubit.silent_cmd(command)
        last_curve = cubit.get_last_id("curve")
        if last_curve != last_curve_store:
            return last_curve
        else:
            return 0

    def create_line_v(ind, n, n2, step, data, unit):
        last_curve_store = cubit.get_last_id("curve")
        command = 'create curve spline '
        for i in range(0, n):
            if i % step == 0:
                lon, lat, z = data[n2 * i + ind][0], \
                    data[n2 * i + ind][1], data[n2 * i + ind][2]
                x, y = geo2utm(lon, lat, unit)
                txt = ' Position ' + str(x) + ' ' + str(y) + ' ' + str(z)
                command = command + txt
                # print(command)
        cubit.silent_cmd(command)
        last_curve = cubit.get_last_id("curve")
        if last_curve != last_curve_store:
            return last_curve
        else:
            return 0

    #
    #
    cubit.cmd("reset")
    #
    #
    #
    nu = cfg.num_x[isurface]
    nv = cfg.num_y[isurface]
    ustep = cfg.xstep[isurface]
    vstep = cfg.ystep[isurface]
    unit = cfg.unit2[isurface]
    #
    #
    data = numpy.loadtxt(cfg.surface_name[isurface])
    if len(data) > 100:
        command = "set echo off"
        cubit.cmd(command)
        command = "set journal off"
        cubit.cmd(command)
    #
    u_curve = []
    v_curve = []
    #
    for iv in range(0, nv):
        if iv % vstep == 0.:
            u = create_line_u(iv * (nu), nu, ustep, data, unit)
            u_curve.append(u)
    for iu in range(0, nu):
        if iu % ustep == 0.:
            v = create_line_v(iu, nv, nu, ustep, data, unit)
            v_curve.append(v)
    #
    umax = max(u_curve)
    umin = min(u_curve)
    vmax = max(v_curve)
    vmin = min(v_curve)
    cubitcommand = 'create surface net u curve ' + \
        str(umin) + ' to ' + str(umax) + ' v curve ' + \
        str(vmin) + ' to ' + str(vmax) + ' heal'
    cubit.cmd(cubitcommand)
    command = "del curve all"
    cubit.cmd(command)
    suff = cfg.surface_name[isurface].split('/')
    command = "save as '" + cfg.working_dir + \
        "/surf_" + suff[-1] + ".cub' overwrite"
    cubit.cmd(command)
    #
    #
    #
    cubit.cmd("set info " + cfg.cubit_info)
    cubit.cmd("set echo " + cfg.echo_info)
    cubit.cmd("set journal " + cfg.jou_info)
Exemple #47
0
def save_geometry(export_path):

    cubit.cmd("set attribute on")
    cubit.cmd("export acis '" + export_path + ".sat' overwrite")
Exemple #48
0
def surface_skin(isurface=0, cfgname=None):
    """
    create an acis surface interpolating no-intersecting lines
    """
    import start as start
    #
    #
    cubit = start.start_cubit()
    cfg = start.start_cfg(cfgname)

    #

    def define_next_line(directionx, directiony, n, data):
        ndata = len(data)
        command = ''
        ind = n
        try:
            record = data[ind]
        except:
            return False, False
        try:
            x, y, z = map(float, record.split())
        except:
            return False, False
        txt = ' Position ' + record
        command = command + txt
        x_store, y_store, z_store = x, y, z
        icount = 1
        while True:
            ind += 1
            if ind >= ndata:
                return ind, command
            record = data[ind]
            try:
                x, y, z = map(float, record.split())
            except:
                return ind, command
            dx, dy = x - x_store, y - y_store
            if directionx == 0 and dy / abs(dy) * directiony >= 0:
                txt = ' Position ' + record
                command = command + txt
                icount += 1
                x_store, y_store, z_store = x, y, z
            elif directiony == 0 and dx / abs(dx) == directionx:
                txt = ' Position ' + record
                command = command + txt
                icount += 1
                x_store, y_store, z_store = x, y, z
            else:
                if icount == 1:
                    x, y, z = x_store + 1e-4 * directionx, y_store + 1e-4 * \
                        directiony, z_store
                    txt = ' Position ' + str(x) + ' ' + str(y) + ' ' + str(z)
                    command = command + txt
                return ind, command

    def create_line(position):
        if position:
            last_curve_store = cubit.get_last_id("curve")
            command = 'create curve spline ' + position
            cubit.silent_cmd(command)
            last_curve = cubit.get_last_id("curve")
            if last_curve != last_curve_store:
                return last_curve
            else:
                return False
        else:
            return False

    command = "reset"
    cubit.cmd(command)
    #
    position = True
    #
    try:
        grdfile = open(cfg.surface_name[isurface], 'r')
    except:
        raise NameError('No such file or directory: ' +
                        str(cfg.surface_name[isurface]))

    directionx = cfg.directionx[isurface]
    directiony = cfg.directiony[isurface]
    step = cfg.step[isurface]
    position = True
    curveskin = []
    data = grdfile.read().split('\n')
    n = 0
    #
    #
    command = "set echo off"
    cubit.cmd(command)
    command = "set journal off"
    cubit.cmd(command)
    command = "set info off"
    cubit.cmd(command)
    #
    while position:
        index, position = define_next_line(directionx, directiony, n, data)
        if n % step == 0:
            curve = create_line(position)
            if curve:
                curveskin.append(curve)
        elif n % step != 0 and not position:
            curve = create_line(position)
            if curve:
                curveskin.append(curve)
        n = index
    umax = max(curveskin)
    umin = min(curveskin)
    print('create surface skin curve ' + str(umin) + ' to ' + str(umax))
    cubitcommand = 'create surface skin curve ' + \
        str(umin) + ' to ' + str(umax)
    cubit.cmd(cubitcommand)
    command = "del curve all"
    cubit.cmd(command)
    last_surface = cubit.get_last_id("surface")
    command = "regularize surf " + str(last_surface)
    cubit.cmd(command)
    #
    suff = cfg.surface_name[isurface].split('/')
    command = "save as '" + cfg.working_dir + \
        "/surf_" + suff[-1] + ".cub' overwrite"
    cubit.cmd(command)
    #
    #
    #
    cubit.cmd("set info " + cfg.cubit_info)
    cubit.cmd("set echo " + cfg.echo_info)
    cubit.cmd("set journal " + cfg.jou_info)
def define_top_bottom_absorbing_surf(zmin_box, zmax_box):
    """
      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_bottom = []
    top_surf = []

    list_vol = cubit.parse_cubit_list("volume", "all")
    init_n_vol = len(list_vol)
    #   TO DO : Make zmin_box work properly.
    #   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[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_bottom, top_surf
Exemple #50
0
def PacmanCreate(lx, ly, lz, thetacrack):
    import cubit
    import numpy as np
    ###
    ### Create Main body
    ###
    cubit.cmd("Create cylinder height %f major radius %f minor radius %f" %
              (lz, lx, ly))
    CYL = cubit.get_last_id("volume")
    ###
    ### Create wedge
    ###
    w_ID = []
    cubit.cmd("create vertex X 0 Y 0 Z %f" % (-lz))
    w_ID.append(cubit.get_last_id("vertex"))
    X = 1.1 * np.max(lx, ly) * np.cos(np.radians(thetacrack / 2.))
    Y = 1.1 * np.max(lx, ly) * np.sin(np.radians(thetacrack / 2.))
    cubit.cmd("create vertex X %f Y %f Z %f" % (-X, Y, -lz))
    w_ID.append(cubit.get_last_id("vertex"))
    cubit.cmd("create vertex X %f Y %f Z %f" % (-X, -Y, -lz))
    w_ID.append(cubit.get_last_id("vertex"))
    cubit.cmd("create surface vertex %i %i %i" % (w_ID[0], w_ID[1], w_ID[2]))
    cubit.cmd("sweep surface %i perpendicular distance %f" %
              (cubit.get_last_id("surface"), 2 * lz))
    WEDGE = cubit.get_last_id("volume")
    ###
    ### remove crack
    ###
    cubit.cmd("subtract volume %i from volume %i" % (WEDGE, CYL))
    ###
    ### Return the ID of the cylinder
    ###
    return CYL
Exemple #51
0
def plane(cfg):
    from utilities import geo2utm
    import start as start
    #
    #
    cubit = start.start_cubit()
    #
    #
    command = "reset"
    cubit.cmd(command)
    #
    #
    for p in [cfg.x1, cfg.x2, cfg.x3, cfg.x4]:
        x_current, y_current = geo2utm(p[0], p[1], cfg.unit)
        cubitcommand = 'create vertex ' + \
            str(x_current) + ' ' + str(y_current) + ' ' + str(p[2])
        cubit.cmd(cubitcommand)
    #
    cubitcommand = 'create surface vertex 1 2 3 4'
    cubit.cmd(cubitcommand)
    command = "del vertex all"
    cubit.cmd(command)
    command = "save as 'plane.cub' overwrite"
    cubit.cmd(command)
    #
    #
    #
    cubit.cmd("set info " + cfg.cubit_info)
    cubit.cmd("set echo " + cfg.echo_info)
    cubit.cmd("set journal " + cfg.jou_info)
Exemple #52
0
def refine_inside_curve(curves, ntimes=1, depth=1, block=1, surface=False):
    sflag = surface
    if not isinstance(curves, list):
        if isinstance(curves, str):
            curves = map(int, curves.split())
        else:
            curves = [curves]
    for curve in curves:
        cubit.cmd('del group ntop')
        if not surface:
            cubit.cmd("group 'ntop' add node in face in block " + str(block))
        else:
            cubit.cmd("group 'ntop' add node in face in surface " + str(sflag))
        group1 = cubit.get_id_from_name("ntop")
        nodes = list(cubit.get_group_nodes(group1))
        ni = get_nodes_inside_curve(nodes, curve)
        if ntimes > 1:
            cmd = 'del group hex_ref'
            cubit.cmd(cmd)
            command = "group 'hex_ref' add hex propagate face in node " +\
                      ' '.join(str(x) for x in ni) + "times " + str(ntimes)
            cubit.cmd(command)
            # id_group = cubit.get_id_from_name('hex_ref')
            cmd = 'refine hex in group "hex_ref" numsplit 1 bias 1 depth ' + \
                str(depth) + ' smooth'
            cubit.cmd(cmd)
        else:
            command = 'refine node ' + \
                " ".join(str(x) for x in ni) + \
                ' numsplit 1 bias 1.0 depth ' + str(depth) + ' smooth'
            cubit.cmd(command)
    #
    #
    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 refining'
os.system('mkdir -p '+ SEMoutput)
os.system('mkdir -p '+ CUBIToutput)

import cubit
try:
    #cubit.init([""])
    cubit.init(["-noecho","-nojournal"])
except:
    pass

version = cubit.get_version()
version_major = int(version.split(".")[0])
version_minor = int(version.split(".")[1])
print "cubit version: ",version

cubit.cmd('reset')
cubit.cmd('brick x 134000 y 134000 z 60000')

# This seems to conflict with boundary_definition.py
# ....which leaves the model space at e.g. x=[-67,67] km
cubit.cmd('volume 1 move x 67000 y 67000 z -30000')

# create vertices for discontinuity
cubit.cmd('split curve 9  distance 3000')
cubit.cmd('split curve 10  distance 3000')
cubit.cmd('split curve 11  distance 3000')
cubit.cmd('split curve 12  distance 3000')

# create surface for interface
cubit.cmd('create surface vertex 9 10 12 11')
Exemple #54
0
def curve2poly(line):
    curve = int(line)
    cubit.cmd('curve ' + str(curve) + ' size auto factor 1')
    cubit.cmd('mesh curve ' + str(curve))
    n = cubit.get_curve_nodes(curve)
    orientnode = []
    vertex_list = cubit.get_relatives("curve", curve, "vertex")
    if len(vertex_list) != 0:
        startnode = cubit.get_vertex_node(vertex_list[0])
        cubit.cmd('del group pgon')
        cubit.cmd("group 'pgon' add edge in node " + str(startnode))
        group1 = cubit.get_id_from_name("pgon")
        edges = list(cubit.get_group_edges(group1))
        edgestart = edges[0]
    else:
        startnode = n[0]
        cubit.cmd('del group pgon')
        cubit.cmd("group 'pgon' add edge in node " + str(startnode))
        group1 = cubit.get_id_from_name("pgon")
        edges = list(cubit.get_group_edges(group1))
        edgestart = edges[0]
    begin = startnode
    orientnode.append(begin)
    node_id_list = list(cubit.get_connectivity("edge", edgestart))
    node_id_list.remove(startnode)
    startnode = node_id_list[0]
    orientnode.append(startnode)
    stopflag = False
    while startnode != begin and not stopflag:
        cubit.cmd('del group pgon')
        cubit.cmd("group 'pgon' add edge in node " + str(startnode))
        group1 = cubit.get_id_from_name("pgon")
        edges = list(cubit.get_group_edges(group1))
        if len(edges) != 1:
            edges.remove(edgestart)
            edgestart = edges[0]
            node_id_list = list(cubit.get_connectivity("edge", edgestart))
            node_id_list.remove(startnode)
            orientnode.append(node_id_list[0])
            startnode = node_id_list[0]
        else:
            stopflag = True
    vx = []
    vy = []
    for n in orientnode:
        v = cubit.get_nodal_coordinates(n)
        vx.append(v[0])
        vy.append(v[1])
    return vx, vy, orientnode
Exemple #55
0
def cohgen(exodusIn, fileOutPrefix):
    """
    This function operates within Cubit. It imports an exodus mesh of
    polycrystalline geometry with the void meshed, generates a skin of zero
    thickness cohesive elements surrounding individual crystals, and exports
    a valid ABAQUS mesh.
    """
    # Provide the installation path of Cubit
    sys.path.append('~/Software/Cubit-15.3-Lin64/bin')
    # sys.path.append('/Applications/Cubit-15.3/Cubit.app/Contents/MacOS/')
    import cubit as cb
    # Start cubit
    cb.init(['cubit', '-nojournal'])

    # Import model while creating geometry
    fileIn = "'" + exodusIn + ".e'"
    print fileIn
    cb.cmd("import mesh geometry %s feature_angle 135.00 merge" % fileIn)

    # Get volumes and separate into blocks
    # Compress volume id's and sort by volume (likely void volume is largest)
    cb.cmd('compress all sort')
    # cb.cmd('label volume id')
    # cb.cmd('label volume name id')

    # Remove pre-established element blocks
    cb.cmd('del block all')
    vols = cb.get_volume_count()
    print "Number of volumes: %s" % vols

    # Check if volumes sorted properly (largest last)
    firstvol = cb.volume(1)
    lastvol = cb.volume(vols)
    firstvol_vol = firstvol.volume()
    lastvol_vol = lastvol.volume()

    # Set volume number containing matrix material
    # Proper sort should set last (assuming it is the largest individual volume)
    # One case, it left the matrix material as volume 1
    # Could be other cases requiring a more generic fix (check cuibt file manually)
    if firstvol_vol > lastvol_vol:
        matrix_vol_num = 1
    elif firstvol_vol < lastvol_vol:
        matrix_vol_num = vols

    # Assign each grain its own element block and name.
    grain_list = []
    for cv in range(1, vols + 1):
        cb.cmd("block %s add volume %s" % (repr(cv + 1), repr(cv)))
        if cv == matrix_vol_num:
            cb.cmd("block %s name 'Matrix'" % repr(cv + 1))
        else:
            cb.cmd("block %s name 'Grain_%s'" % (repr(cv + 1), repr(cv)))
            grain_list.append('Grain_%s' % repr(cv))

    cb.cmd('disassociate mesh from Volume all')
    # cb.cmd('delete volume all')

    # Pillow each grain to skin with 0 thickness hexes for cohesive elements
    el_blocks = cb.get_block_count()
    # Note, indexing skips last element block (presumed binder)
    for block in range(2, el_blocks + 1):
        if block == matrix_vol_num + 1:
            pass
        else:
            cb.cmd("pillow hex in block %s distance 0 no_smooth" % repr(block))

    cb.cmd('block 1 add hex not block_assigned')
    cb.cmd("block 1 name 'Coh_El'")

    # Get bounding box for removing cohesive elements on the domain boundary
    # cb.get_bounding_box('entity',id) returns a vector with the following info:
    #(min_x, max_x, range_x, min_y, max_y, range_y, min_z, max_z, range_z, diag)
    bbox = cb.get_bounding_box("volume", matrix_vol_num)

    cb.cmd('delete hex in block 1 with X_Coord == %s' % repr(bbox[0]))
    cb.cmd('delete hex in block 1 with X_Coord == %s' % repr(bbox[1]))
    cb.cmd('delete hex in block 1 with Y_Coord == %s' % repr(bbox[3]))
    cb.cmd('delete hex in block 1 with Y_Coord == %s' % repr(bbox[4]))
    cb.cmd('delete hex in block 1 with Z_Coord == %s' % repr(bbox[6]))
    cb.cmd('delete hex in block 1 with Z_Coord == %s' % repr(bbox[7]))

    # Reassign domain nodesets since pillowing and removing domain hexes messes this up
    cb.cmd('delete nodeset all')
    cb.cmd('delete sideset all')

    cb.cmd('nodeset 1 add node with X_Coord == %s' % repr(bbox[0]))
    cb.cmd('nodeset 2 add node with X_Coord == %s' % repr(bbox[1]))
    cb.cmd('nodeset 3 add node with Y_Coord == %s' % repr(bbox[3]))
    cb.cmd('nodeset 4 add node with Y_Coord == %s' % repr(bbox[4]))
    cb.cmd('nodeset 5 add node with Z_Coord == %s' % repr(bbox[6]))
    cb.cmd('nodeset 6 add node with Z_Coord == %s' % repr(bbox[7]))
    cb.cmd('nodeset 7 add node in nodeset 1 to 6')
    cb.cmd('nodeset 8 add node in hex in block 1')  # Interface nodes

    cb.cmd('nodeset 1 name "negXNodes"')
    cb.cmd('nodeset 2 name "posXNodes"')
    cb.cmd('nodeset 3 name "negYNodes"')
    cb.cmd('nodeset 4 name "posYNodes"')
    cb.cmd('nodeset 5 name "negZNodes"')
    cb.cmd('nodeset 6 name "posZNodes"')
    cb.cmd('nodeset 7 name "allBoundaryNodes"')
    cb.cmd('nodeset 8 name "matIntNodes"')

    # Define nodesets for periodic boundary conditions. For universal application
    # to implicit and explicit analyses, corners, edges, and faces cannot contain
    # duplicate nodes (restriction for implicit only). Therefore, new specific
    # nodesets are defined in a way to eleminate this duplicate definition problem.

    # Redefine Faces for PBC's
    cb.cmd('nodeset 101 add node in nodeset 1')
    cb.cmd('nodeset 102 add node in nodeset 2')
    cb.cmd('nodeset 103 add node in nodeset 3')
    cb.cmd('nodeset 104 add node in nodeset 4')
    cb.cmd('nodeset 105 add node in nodeset 5')
    cb.cmd('nodeset 106 add node in nodeset 6')

    cb.cmd('nodeset 101 name "PBCnXF"')
    cb.cmd('nodeset 102 name "PBCpXF"')
    cb.cmd('nodeset 103 name "PBCnYF"')
    cb.cmd('nodeset 104 name "PBCpYF"')
    cb.cmd('nodeset 105 name "PBCnZF"')
    cb.cmd('nodeset 106 name "PBCpZF"')

    # Define Edges for PBC's
    cb.cmd(
        'nodeset 1001 add node with X_Coord == {x:s} and with Y_Coord == {y:s}'
        .format(x=repr(bbox[0]), y=repr(bbox[3])))
    cb.cmd('nodeset 1001 name "PBCnXnYE"')
    cb.cmd(
        'nodeset 1002 add node with X_Coord == {x:s} and with Y_Coord == {y:s}'
        .format(x=repr(bbox[0]), y=repr(bbox[4])))
    cb.cmd('nodeset 1002 name "PBCnXpYE"')
    cb.cmd(
        'nodeset 1003 add node with X_Coord == {x:s} and with Y_Coord == {y:s}'
        .format(x=repr(bbox[1]), y=repr(bbox[3])))
    cb.cmd('nodeset 1003 name "PBCpXnYE"')
    cb.cmd(
        'nodeset 1004 add node with X_Coord == {x:s} and with Y_Coord == {y:s}'
        .format(x=repr(bbox[1]), y=repr(bbox[4])))
    cb.cmd('nodeset 1004 name "PBCpXpYE"')
    cb.cmd(
        'nodeset 1005 add node with Y_Coord == {y:s} and with Z_Coord == {z:s}'
        .format(y=repr(bbox[3]), z=repr(bbox[6])))
    cb.cmd('nodeset 1005 name "PBCnYnZE"')
    cb.cmd(
        'nodeset 1006 add node with Y_Coord == {y:s} and with Z_Coord == {z:s}'
        .format(y=repr(bbox[3]), z=repr(bbox[7])))
    cb.cmd('nodeset 1006 name "PBCnYpZE"')
    cb.cmd(
        'nodeset 1007 add node with Y_Coord == {y:s} and with Z_Coord == {z:s}'
        .format(y=repr(bbox[4]), z=repr(bbox[6])))
    cb.cmd('nodeset 1007 name "PBCpYnZE"')
    cb.cmd(
        'nodeset 1008 add node with Y_Coord == {y:s} and with Z_Coord == {z:s}'
        .format(y=repr(bbox[4]), z=repr(bbox[7])))
    cb.cmd('nodeset 1008 name "PBCpYpZE"')
    cb.cmd(
        'nodeset 1009 add node with X_Coord == {x:s} and with Z_Coord == {z:s}'
        .format(x=repr(bbox[0]), z=repr(bbox[6])))
    cb.cmd('nodeset 1009 name "PBCnXnZE"')
    cb.cmd(
        'nodeset 1010 add node with X_Coord == {x:s} and with Z_Coord == {z:s}'
        .format(x=repr(bbox[0]), z=repr(bbox[7])))
    cb.cmd('nodeset 1010 name "PBCnXpZE"')
    cb.cmd(
        'nodeset 1011 add node with X_Coord == {x:s} and with Z_Coord == {z:s}'
        .format(x=repr(bbox[1]), z=repr(bbox[6])))
    cb.cmd('nodeset 1011 name "PBCpXnZE"')
    cb.cmd(
        'nodeset 1012 add node with X_Coord == {x:s} and with Z_Coord == {z:s}'
        .format(x=repr(bbox[1]), z=repr(bbox[7])))
    cb.cmd('nodeset 1012 name "PBCpXpZE"')

    # Remove nodes in edge sets from face sets
    for nn in range(101, 107):
        cb.cmd('nodeset {num:s} remove node in nodeset 1001 to 1012'.format(
            num=repr(nn)))

    # Define Corners for PBC's
    cb.cmd(
        'nodeset 10001 add node with X_Coord == {x:s} and with Y_Coord == {y:s} and with Z_Coord == {z:s}'
        .format(x=repr(bbox[0]), y=repr(bbox[3]), z=repr(bbox[6])))
    cb.cmd('nodeset 10001 name "PBCnXnYnZC"')
    cb.cmd(
        'nodeset 10002 add node with X_Coord == {x:s} and with Y_Coord == {y:s} and with Z_Coord == {z:s}'
        .format(x=repr(bbox[0]), y=repr(bbox[3]), z=repr(bbox[7])))
    cb.cmd('nodeset 10002 name "PBCnXnYpZC"')
    cb.cmd(
        'nodeset 10003 add node with X_Coord == {x:s} and with Y_Coord == {y:s} and with Z_Coord == {z:s}'
        .format(x=repr(bbox[0]), y=repr(bbox[4]), z=repr(bbox[6])))
    cb.cmd('nodeset 10003 name "PBCnXpYnZC"')
    cb.cmd(
        'nodeset 10004 add node with X_Coord == {x:s} and with Y_Coord == {y:s} and with Z_Coord == {z:s}'
        .format(x=repr(bbox[0]), y=repr(bbox[4]), z=repr(bbox[7])))
    cb.cmd('nodeset 10004 name "PBCnXpYpZC"')
    cb.cmd(
        'nodeset 10005 add node with X_Coord == {x:s} and with Y_Coord == {y:s} and with Z_Coord == {z:s}'
        .format(x=repr(bbox[1]), y=repr(bbox[3]), z=repr(bbox[6])))
    cb.cmd('nodeset 10005 name "PBCpXnYnZC"')
    cb.cmd(
        'nodeset 10006 add node with X_Coord == {x:s} and with Y_Coord == {y:s} and with Z_Coord == {z:s}'
        .format(x=repr(bbox[1]), y=repr(bbox[3]), z=repr(bbox[7])))
    cb.cmd('nodeset 10006 name "PBCpXnYpZC"')
    cb.cmd(
        'nodeset 10007 add node with X_Coord == {x:s} and with Y_Coord == {y:s} and with Z_Coord == {z:s}'
        .format(x=repr(bbox[1]), y=repr(bbox[4]), z=repr(bbox[6])))
    cb.cmd('nodeset 10007 name "PBCpXpYnZC"')
    cb.cmd(
        'nodeset 10008 add node with X_Coord == {x:s} and with Y_Coord == {y:s} and with Z_Coord == {z:s}'
        .format(x=repr(bbox[1]), y=repr(bbox[4]), z=repr(bbox[7])))
    cb.cmd('nodeset 10008 name "PBCpXpYpZC"')

    # Remove nodes in corner sets from edge sets
    for nn in range(1001, 1013):
        cb.cmd('nodeset {num:s} remove node in nodeset 10001 to 10008'.format(
            num=repr(nn)))

    # Export abaqus file
    absFileOutPrefix = os.path.abspath(fileOutPrefix)
    cb.cmd("set Abaqus precision 4")
    cb.cmd(
        'export abaqus "%s.inp" block all nodeset all dimension 3 overwrite' %
        absFileOutPrefix)
    cb.cmd('save as "%s.cub" overwrite' % absFileOutPrefix)
    return absFileOutPrefix, grain_list
Exemple #56
0
  import boundary_definition
  import cubit2specfem3d

# time stamp
print("#" + time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()))


# working directory
cwd = os.getcwd()
print("#current working directory: " + str(cwd))
if cwd[len(cwd)-14:len(cwd)] != "Mount_StHelens":
  print("")
  print("#please run this script from example directory: SPECFEM3D/example/Mount_StHelens/")
  print("")

cubit.cmd('version')
cubit.cmd('reset')

print("running meshing script...")
print("")
print("note: this script uses topography surface in ACIS format")
print("         meshing will take around 15 min")
print("")

# uses developer commands
cubit.cmd('set developer commands on')
cubit.cmd('set import mesh tolerance 1')

#############################################################
#
# 0. step: loading topography surface
Exemple #57
0
def mesh_cpml(list_vol,
              remesh=True,
              refinement=None,
              top_surf=None,
              size=None):
    from utilities import list2str
    top_surf = list2str(top_surf)
    if remesh:
        cubit.cmd('reset vol all')
        cubit.cmf('set dev on')
        cubit.cmd('imprint vol all')
        cubit.cmd('merge vol all')
        cubit.cmd('vol all size ' + str(size))
        cubit.cmd('mesh vol all')
        try:
            for refdepth in refinement:
                cubit.cmd('refine surf ' + top_surf +
                          ' numsplit 1 bias 1 depth ' + str(refdepth))
        except:
            print 'DEBUG: error in refinement cpml'
        xmin = xmin - size
        xmax = xmax + size
        ymin = ymin - size
        ymax = ymax + size
        zmin = zmin - size
        zmin = zmax - size
        txt = "group 'vol_xmin' add vol in surf  with X_coord < " + str(xmin)
        cubit.cmd(txt)
        txt = "group 'vol_xmax' add vol in surf  with X_coord > " + str(xmax)
        cubit.cmd(txt)
        txt = "group 'vol_ymin' add vol in surf  with Y_coord < " + str(ymin)
        cubit.cmd(txt)
        txt = "group 'vol_ymax' add vol in surf  with Y_coord > " + str(ymax)
        cubit.cmd(txt)
        txt = "group 'vol_zmin' add vol in surf  with Z_coord < " + str(zmin)
        cubit.cmd(txt)
Exemple #58
0
def Layer(Body_IDs, BB, Alpha, Theta1, Theta2, Xoffset=.5):
    import cubit
    import numpy as np
    ###
    ###      Body_ID: a single volume ID
    ###      BB:            bounding box in the form [xmin, xmax, ymin, ymax, zmin, zmax]
    ###      Alpha:     lamination angle
    ###      Theta1:    thickness of layer 1
    ###      Theta2:    thickness of layer 2
    ###      Xoffset: distance along the x-axis between the center of the bounding box
    ###                         and the first interface l1-l2 if specified, in fraction of Theta1
    ###                         i.e. 0 -> interface l2-l1 at center
    ###                                  1 -> interface l1-l2 at center
    ###                         otherwise, the center of BB corresponds to the center of a Layer1
    ###                         i.e. Xoffset = .5
    ###
    YL = np.sqrt((BB[1] - BB[0])**2 + (BB[3] - BB[2])**2)
    XC = (BB[0] + BB[1]) / 2.
    YC = (BB[2] + BB[3]) / 2.
    ZC = (BB[4] + BB[5]) / 2.
    Theta = Theta1 + Theta2
    if Alpha > 0:
        l1 = (BB[0] - XC) * np.cos(np.radians(Alpha)) + (BB[2] - YC) * np.sin(
            np.radians(Alpha))
        l2 = (BB[1] - XC) * np.cos(np.radians(Alpha)) + (BB[3] - YC) * np.sin(
            np.radians(Alpha))
    else:
        l1 = (BB[0] - XC) * np.cos(np.radians(Alpha)) + (BB[3] - YC) * np.sin(
            np.radians(Alpha))
        l2 = (BB[1] - XC) * np.cos(np.radians(Alpha)) + (BB[2] - YC) * np.sin(
            np.radians(Alpha))
    n1 = int(np.ceil(l1 / Theta)) - 1
    n2 = int(np.ceil(l2 / Theta)) + 1
    LAYER1_IDs = Body_IDs[:]
    LAYER2_IDs = []
    ###
    ### offset layers
    ###
    for i in range(n1, n2):
        X = XC + i * np.cos(np.radians(Alpha)) * Theta
        Y = YC + i * np.sin(np.radians(Alpha)) * Theta
        cubit.cmd('create brick X %f Y %f Z %f' % (Theta1, YL, BB[5] - BB[4]))
        tmp_ID = cubit.get_last_id("volume")
        cubit.cmd('move volume %i X %f Y %f Z %f' % (tmp_ID, X + Theta1 *
                                                     (.5 - Xoffset), Y, ZC))
        if not Alpha == 0.:
            ### cubit doesn't like rotations will 0 angle...
            cubit.cmd('create vertex X %f Y %f Z %f' % (X, Y, BB[4]))
            v1_ID = cubit.get_last_id("vertex")
            cubit.cmd('create vertex X %f Y %f Z %f' % (X, Y, BB[5]))
            v2_ID = cubit.get_last_id("vertex")
            cubit.cmd('rotate volume %i about vertex %i vertex %i angle %f' %
                      (tmp_ID, v1_ID, v2_ID, Alpha))
            cubit.cmd('delete vertex %i' % v1_ID)
            cubit.cmd('delete vertex %i' % v2_ID)
        (LAYER1_IDs, tmp_layer) = WebcutTool2(LAYER1_IDs, tmp_ID, delete=True)
        for l in tmp_layer:
            LAYER2_IDs.append(l)
    return (LAYER1_IDs, LAYER2_IDs)
#!/usr/bin/env python
from __future__ import print_function

import cubit
import boundary_definition
import cubit2specfem3d

import os
import sys

# two volumes separating 134000x134000x60000 block horizontally
cubit.cmd('reset')
cubit.cmd('brick x 67000 y 134000 z 60000')
cubit.cmd('volume 1 move x 33500 y 67000 z -30000')
cubit.cmd('brick x 67000 y 134000 z 60000')
cubit.cmd('volume 2 move x 100500 y 67000 z -30000')
cubit.cmd('merge all')

# Meshing the volumes
elementsize = 3750.0

cubit.cmd('volume 1 size ' + str(elementsize))
cubit.cmd('volume 2 size ' + str(elementsize))
cubit.cmd('mesh volume 1 2')

#### End of meshing

###### 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)
Exemple #60
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)