Exemple #1
0
def start_cubit(init=False):
    """
    start cubit, it return the cubit object
    init argument set the monitotr files
    """
    import sys,os
    try:
        cubit.silent_cmd('comment')
    except:
        try:
            import cubit
            import utilities
            cubit.init([""])
        except:
            print 'error importing cubit'
            sys.exit()
        try:
            if init:
                from start import start_cfg,start_mpi
                cfg=start_cfg()
                mpiflag,iproc,numproc,mpi   = start_mpi()
                cubit.cmd('set logging on file "'+cfg.working_dir+'/cubit_proc_'+str(iproc)+'.log"')
                cubit.cmd("set echo off")
                cubit.cmd("set info off")
                if iproc == cfg.monitored_cpu:
                    cubit.cmd("record '"+cfg.working_dir+"/monitor_"+str(cfg.monitored_cpu)+".jou'")
                    cubit.cmd("set journal on")
                    cubit.cmd("journal error on")
                    d=cfg.__dict__
                    ks=d.keys()
                    ks.sort()
                    for k in ks:
                        if '__'  not in k and '<'  not in str(d[k]) and d[k] is not None:
                            txt=str(k)+' -----> '+str(d[k])
                            txt=txt.replace("'","").replace('"','')
                            cubit.cmd('comment "'+txt+'"')
                else:
                    cubit.cmd("set journal "+cfg.jou_info)
                    cubit.cmd("journal error "+cfg.jer_info)
                    d=cfg.__dict__
                    ks=d.keys()
                    ks.sort()
                    for k in ks:
                        if '__'  not in k and '<'  not in str(d[k]) and d[k] is not None:
                            txt=str(k)+' -----> '+str(d[k])
                            txt=txt.replace("'","").replace('"','')
                            cubit.cmd('comment "'+txt+'"')
                cubit.cmd("set echo "+cfg.echo_info)
                cubit.cmd("set info "+cfg.cubit_info)
                version_cubit=utilities.get_cubit_version()
                if version_cubit > 13 and version_cubit < 15:
                    print 'VERSION CUBIT ',version_cubit
                    print 'VERSIONs of CUBIT > 13 have bugs with merge node commands and equivalence'
                    print 'the merge option is not operative with this version, please download CUBIT 13'
                else:
                    print 'VERSION CUBIT ',version_cubit
        except:
            print 'error start cubit'
            sys.exit()
    return cubit
def build_block(vol_list,name):
    from sets import Set
    try:
            cubit.cmd('comment')
    except:
            try:
                import cubit
                cubit.init([""])
            except:
                print 'error importing cubit'
                import sys
                sys.exit()
    block_list=cubit.get_block_id_list()
    if len(block_list) > 0:
        id_block=max(block_list)
    else:
        id_block=0
    for v,n in zip(vol_list,name):
       id_block+=1
       v_other=Set(vol_list)-Set([v])
       #command= 'block '+str(id_block)+' hex in node in vol '+str(v)+' except hex in vol '+str(list(v_other))
       command= 'block '+str(id_block)+' hex in vol '+str(v)
       command = command.replace("["," ").replace("]"," ")
       cubit.cmd(command)
       command = "block "+str(id_block)+" name '"+n+"'"
       cubit.cmd(command)
Exemple #3
0
def geometry(g, t, l, w):
    import cubit
    cubit.init('[]')
    print "Other side of initializing"
    cubit.cmd('reset')
    print "resetting"    
    offset = (g + t/2.0)
    cubit.cmd('brick x 700 y 300 z 10')
    cubit.cmd('move volume 1 location 0 0 %e' %(5.e0-offset))
    cubit.cmd('create surface rectangle width 80 height 200 zplane')
    cubit.cmd('create surface rectangle width 80 height 200 zplane ')
    cubit.cmd('create surface rectangle width 80 height 200 zplane')
    cubit.cmd('move surface 7 location 95 0 -%e' % offset)
    cubit.cmd('move surface 8 location -95 0 -%e' % offset)
    cubit.cmd('move surface 9 location 0 0 -%e' % offset)
    
    cubit.cmd('webcut volume 1 with plane normal to curve 16 close_to vertex 12')
    cubit.cmd('webcut volume 1 with plane normal to curve 16 close_to vertex 9')
    cubit.cmd('webcut volume 6 with plane normal to curve 17 close_to vertex 14')
    cubit.cmd('webcut volume 7 with plane normal to curve 69 close_to vertex 13')
    cubit.cmd('webcut volume 8 with plane normal to curve 43 close_to vertex 18')
    cubit.cmd('webcut volume 9 with plane normal to curve 104 close_to vertex 17')
    cubit.cmd('webcut volume 10 with plane normal to curve 118 close_to vertex 10')
    cubit.cmd('webcut volume 11 with plane normal to curve 133 close_to vertex 9')
    cubit.cmd('imprint volume all with volume all')
    cubit.cmd('merge all')

    cubit.cmd('curve all interval 60')
    cubit.cmd('curve 13 15 17 19 21 23 77 78 111 112 141 142 interval 10')
    cubit.cmd('curve 14 16 18 20 22 24 53 54 55 56 58 60 75 92 105 122 137 139 interval 20')
    cubit.cmd('curve 93 94 95 96 125 126 127 128 interval 2')
    cubit.cmd('curve 61 62 63 64 149 150 151 152 interval 30')
    cubit.cmd('curve 37 38 39 40 45 46 47 48 interval 10')
    cubit.cmd('curve 2 4 6 8 interval 94')

    cubit.cmd('mesh curve  37 38 39 40 45 46 47 48 94 96 125 127 13 15 17 19 21 23 77 78 111 112 141 142 14 16 18 20 22 24 53 54 55 56 58 75 92 105 122 139')
    cubit.cmd('surface all scheme SubMap')
    cubit.cmd('mesh surface all')
    cubit.cmd('mesh volume all')
    cubit.cmd('Volume all scale 1.e-6 ')
    cubit.cmd('Sideset 1 surface 7 8 9')
    cubit.cmd('Sideset 2 surface 3 5 16 17 18 19 21 22 23 24 26 29 32 34 41 52 54 63 72 74 81 87 89')
    cubit.cmd('block 1 volume all')
    cubit.cmd('export Fluent "backgroundMesh.msh" Block all Sideset all overwrite')

    cubit.cmd('reset')
    cubit.cmd('create surface rectangle width %e height %e zplane'  % (l,  w))
    cubit.cmd('curve 2 4  interval 20')
    cubit.cmd('curve 1 3  interval 360')
    cubit.cmd('mesh curve all')
    cubit.cmd('mesh surface all')
    cubit.cmd('Sideset 1 curve 2 4 ')
    cubit.cmd('Sideset 2 curve 1 3')
    cubit.cmd('block 1 surface 1')
    #cubit.cmd('volume all scale 1e-6')
    cubit.cmd('export Fluent "beam.msh" Block all Sideset all overwrite')
    cubit.cmd('reset')
    cubit.destroy()
Exemple #4
0
def createMesh(nameFileBase, nElementsCoarse, nElementsFine, sizeOverlap):

    with stdout_redirected():

        #start cubit - this step is key
        cubit.init([''])

        sizeElementFine = 1.0 / float(nElementsFine)
        sizeElementCoarse = 1.0 / float(nElementsCoarse)

        cubit.cmd('reset')
        cubit.cmd('undo on')
        cubit.cmd('create brick x 1.0 y 1.0 z ' + str(1.0 + sizeOverlap))
        cubit.cmd('move volume 1 z '+str(1.0 - sizeOverlap) +' include_merged')
        cubit.cmd('volume 1 size '+str(sizeElementCoarse))
        cubit.cmd('mesh volume 1')
        cubit.cmd('block 1 volume 1')
        cubit.cmd('block 1 name "coarse"')
        cubit.cmd('nodeset 1 surface 6')
        cubit.cmd('nodeset 2 surface 4')
        cubit.cmd('nodeset 3 surface 3')
        cubit.cmd('nodeset 4 surface 5')
        cubit.cmd('nodeset 5 surface 2')
        cubit.cmd('nodeset 6 surface 1')
        cubit.cmd('set large exodus file off')
        cubit.cmd('export mesh "' + str(nameFileBase) + '_Cube1.g" overwrite')

        cubit.cmd('reset')
        cubit.cmd('undo on')
        cubit.cmd('create brick x 1.0 y 1.0 z ' + str(1.0 + sizeOverlap))
        cubit.cmd('volume 1 size '+str(sizeElementFine))
        cubit.cmd('mesh volume 1')
        cubit.cmd('block 1 volume 1')
        cubit.cmd('block 1 name "fine"')
        cubit.cmd('nodeset 1 surface 6')
        cubit.cmd('nodeset 2 surface 4')
        cubit.cmd('nodeset 3 surface 3')
        cubit.cmd('nodeset 4 surface 5')
        cubit.cmd('nodeset 5 surface 2')
        cubit.cmd('nodeset 6 surface 1')
        cubit.cmd('set large exodus file off')
        cubit.cmd('export mesh "' + str(nameFileBase) + '_Cube0.g" overwrite')

    files = os.listdir(os.getcwd())

    filesCubit = [file for file in files if file.find('.jou') != -1]

    for file in filesCubit:
        os.remove(file)
def define_block():
    try:
            cubit.cmd('comment')
    except:
            try:
                import cubit
                cubit.init([""])
            except:
                print 'error importing cubit'
                import sys
                sys.exit()
    list_vol=cubit.parse_cubit_list("volume","all")
    init_n_vol=len(list_vol)
    list_name=map(lambda x: 'vol'+x,map(str,list_vol))
    return list_vol,list_name
def define_absorbing_surf_sphere():
    try:
        cubit.cmd('comment')
    except:
        try:
            import cubit
            cubit.init([""])
        except:
            print 'error importing cubit'
            import sys
            sys.exit()
    surf=[]
    list_surf=cubit.parse_cubit_list("surface","all")
    for s in list_surf:
       v=cubit.get_relatives('surface',s,'volume')
       if len(v) == 1:
           surf.append(s)
    return surf
Exemple #7
0
def main():
    cubit.init([''])
    cubit.cmd('## Cubit Version 11.0')
    cubit.cmd('## -warning = On')
    cubit.cmd('## -information = On')
    cubit.cmd('reset')
#
    cubit.cmd('brick x 10 y 10 z 10')
    cubit.cmd('volume 1 size auto factor 4')
    cubit.cmd('mesh volume 1')
    cubit.cmd('sideset 1 surface 4')
    cubit.cmd('sideset 2 surface 6')
#
    hexs = cubit.get_hex_count()
    for i in xrange(1, hexs+1):
        cubit.cmd('block ' + str(i) + ' hex ' + str(i))
#
    cubit.cmd('export genesis "large_sub_cube.e" dimension 3 overwrite')
def build_block_side(surf_list,name,obj='surface'):
    try:
            cubit.cmd('comment')
    except:
            try:
                import cubit
                cubit.init([""])
            except:
                print 'error importing cubit'
                import sys
                sys.exit()
                
    id_nodeset=cubit.get_next_nodeset_id()
    id_block=cubit.get_next_block_id()

    # creates command string
    if obj == 'hex':
        txt='hex in node in surface'
        txt1='block '+str(id_block)+ ' '+ txt +' '+str(list(surf_list))
        txt2="block "+str(id_block)+" name '"+name+"'"
        txt1=txt1.replace("["," ").replace("]"," ")
    elif obj == 'node':
         txt=obj+' in surface'
         txt1= 'nodeset '+str(id_nodeset)+ ' '+ txt +' '+str(list(surf_list))
         txt1 = txt1.replace("["," ").replace("]"," ")
         txt2 = "nodeset "+str(id_nodeset)+" name '"+name+"'"
    elif obj == 'face' or obj == 'edge':
        txt=obj+' in surface'
        txt1= 'block '+str(id_block)+ ' '+ txt +' '+str(list(surf_list))
        txt1 = txt1.replace("["," ").replace("]"," ")
        txt2 = "block "+str(id_block)+" name '"+name+"'"
    else:
        txt1=''
        # do not execute: block id might be wrong
        print "##block "+str(id_block)+" name '"+name+"_notsupported (only hex,face,edge,node)'"
        txt2=''

    # executes commands
    print "# command: " + txt1
    print "# command: " + txt2
    cubit.cmd(txt1)
    cubit.cmd(txt2)
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
# User specifies where the read directories are.
if ( len (sys.argv) < 2 or sys.argv[1] == '--help' or sys.argv[1] == '-h' ):
  sys.exit ('Usage: ./addModelChunksToEarth.py -f \n-f base write path (contains /mesh and /geom)')    

# Read in command line options.
for i in range (len (sys.argv) - 1 ):
  if sys.argv[i] == '-f':
    basePath = sys.argv[i+1]

# Code looks for a /geom directory to find the earth chunk files (generated in previous step).
path     = basePath
geomPath = basePath + 'geom/'
  
# Initialize cubit.
cubit.init ('.')

# Here we loop through all the files in the master earth chunk directory
for file in os.listdir ( geomPath + 'masters/' ):
  

  fields      = file.split ('.')
  
  cubit.cmd  ('open "' + geomPath + 'cutters/all_cutters.cub')

  paramBool = params.copy ()
  for key in paramBool.keys ():
    paramBool[key] = False

  names = []
  sizes = []
#!/usr/bin/python2.7
#from matplotlib.mlab import griddata
#this script generates topology and slab interface in cubit
import cubit
import os
import sys
import math
import numpy as np
#import matplotlib.pyplot as plt

cubit.init([''])
cubit.cmd('reset')


#-- BEGIN user settings ----------------------

FaultFileName = './kur_slab1.0_clip.xyz'  # fault surface file: longitude, latitude, depth (in km, negative)
#FaultFileName = './alu_slab1.0_clip.xyz'
#FaultFileName = './aluslab.xyz'

Latmin = 33          # regional box limits
Latmax = 44
Lonmin = 136
Lonmax = 150
Lat2dis = 100.0      # latitude to km conversion factor
                     # The true latitude to distance conversion ratio should be 111.195 km = 1 deg.
                     # We will reflect that at the end of exportmesh.py by scaling up the model
                     # by a factor of 1.1195. The reason we don't do that here is that it would
                     # change the whole mesh generation script.
Lon2dis = 76.0       # longitude to km conversion factor
zcutBottom = 100.0   # bottom depth of the fault in km, preliminary value (the final depth is set in exportmesh.py)
Exemple #12
0
            dist[j][i] = np.linalg.norm(pt2 - pt1)

    dist =  np.array(np.transpose(dist))
    
    surface_ids = ''
    
    for id in dist.argmin(axis=0):
        surface_ids += (str(id+1) + ' ')
        
    return (surface_ids)
        
dome_plane = float(argv[2])
venturi_angle = float(argv[3])
vane_height = float(argv[4])

cubit.init(" ")

# --- Create New Cubit File
cubit.cmd('new')

# --- Import STEP file with automatic heal
fname = 'Config' + argv[1] + '.step'
cubit.cmd('import step "%s" heal'%fname)

cubit.cmd('Set Max Memory On 500') 

cubit.cmd('regularize volume all')
cubit.cmd('undo on')    
cubit.cmd('set multisweep off') 

p0 = -3.0
Exemple #13
0
def start_cubit(init=False):
    """
    start cubit, it return the cubit object
    init argument set the monitotr files
    """
    import sys
    try:
        cubit.silent_cmd('comment')
    except:
        try:
            import cubit
            import utilities
            cubit.init([""])
        except:
            print 'error importing cubit'
            sys.exit()
        try:
            if init:
                from start import start_cfg, start_mpi
                cfg = start_cfg()
                mpiflag, iproc, numproc, mpi = start_mpi()
                version_cubit = utilities.get_cubit_version()
                cubit.cmd('set logging on file "' + cfg.working_dir +
                          '/cubit_proc_' + str(iproc) + '.log"')
                cubit.cmd("set echo off")
                cubit.cmd("set info off")
                if iproc == cfg.monitored_cpu:
                    cubit.cmd("record '" + cfg.working_dir +
                              "/monitor_" + str(cfg.monitored_cpu) + ".jou'")
                    cubit.cmd("set journal on")
                    if version_cubit < 16:
                        cubit.cmd("journal error on")
                    d = cfg.__dict__
                    ks = d.keys()
                    ks.sort()
                    for k in ks:
                        if '__' not in k and '<' not in str(d[k]):
                            if d[k] is not None:
                                txt = str(k) + ' -----> ' + str(d[k])
                                txt = txt.replace("'", "").replace('"', '')
                                cubit.cmd('comment "' + txt + '"')
                else:
                    cubit.cmd("set journal " + cfg.jou_info)
                    if version_cubit < 16:
                        cubit.cmd("journal error " + cfg.jer_info)
                    d = cfg.__dict__
                    ks = d.keys()
                    ks.sort()
                    for k in ks:
                        if '__' not in k and '<' not in str(d[k]):
                            if d[k] is not None:
                                txt = str(k) + ' -----> ' + str(d[k])
                                txt = txt.replace("'", "").replace('"', '')
                                cubit.cmd('comment "' + txt + '"')
                cubit.cmd("set echo " + cfg.echo_info)
                cubit.cmd("set info " + cfg.cubit_info)
                if version_cubit > 13 and version_cubit < 15:
                    print 'VERSION CUBIT ', version_cubit
                    print 'VERSIONs of CUBIT > 13 have bugs with merge node'
                    print 'the merge option is not operative with this version'
                    print 'please download CUBIT 15+'
                else:
                    print 'VERSION CUBIT ', version_cubit
        except:
            print 'error start cubit'
            sys.exit()
    return cubit
def define_absorbing_surf():
    """
    define the absorbing surfaces for a layered topological box where boundary are surfaces parallel to the axis.
    it returns absorbing_surf,absorbing_surf_xmin,absorbing_surf_xmax,absorbing_surf_ymin,absorbing_surf_ymax,absorbing_surf_bottom,topo_surf
    where
    absorbing_surf is the list of all the absorbing boundary surf
    absorbing_surf_xmin is the list of the absorbing boundary surfaces that correnspond to x=xmin
    ...
    absorbing_surf_bottom is the list of the absorbing boundary surfaces that correspond to z=zmin
    """
    try:
        cubit.cmd('comment')
    except:
        try:
            import cubit
            cubit.init([""])
        except:
            print 'error importing cubit'
            import sys
            sys.exit()
    absorbing_surf=[]
    absorbing_surf_xmin=[]
    absorbing_surf_xmax=[]
    absorbing_surf_ymin=[]
    absorbing_surf_ymax=[]
    absorbing_surf_bottom=[]
    top_surf=[]


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

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

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

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

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

    return absorbing_surf,absorbing_surf_xmin,absorbing_surf_xmax,absorbing_surf_ymin,absorbing_surf_ymax,absorbing_surf_bottom,top_surf
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 #16
0
def define_absorbing_surf():
    """
    define the absorbing surfaces for a layered topological box where boundary are surfaces parallel to the axis.
    it returns absorbing_surf,absorbing_surf_xmin,absorbing_surf_xmax,absorbing_surf_ymin,absorbing_surf_ymax,absorbing_surf_bottom,topo_surf
    where
    absorbing_surf is the list of all the absorbing boundary surf
    absorbing_surf_xmin is the list of the absorbing boundary surfaces that correnspond to x=xmin
    ...
    absorbing_surf_bottom is the list of the absorbing boundary surfaces that correspond to z=zmin
    """
    try:
        cubit.cmd('comment')
    except:
        try:
            import cubit
            cubit.init([""])
        except:
            print 'error importing cubit'
            import sys
            sys.exit()
    absorbing_surf = []
    absorbing_surf_xmin = []
    absorbing_surf_xmax = []
    absorbing_surf_ymin = []
    absorbing_surf_ymax = []
    absorbing_surf_bottom = []
    top_surf = []

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

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

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

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

    # debug
    print '##  xmin: ' + str(xmin_box)
    print '##  xmax: ' + str(xmax_box)
    print '##  ymin: ' + str(ymin_box)
    print '##  ymax: ' + str(ymax_box)
    print '##  zmin: ' + str(zmin_box)
    print '##  zmax: ' + str(zmax_box)

    ############################################
    ##
    ## tolerance parameters
    ##
    ## modified for surface topography
    ############################################
    absorbing_surface_distance_tolerance = 0.1
    topographic_surface_distance_tolerance = 0.1
    topographic_surface_normal_tolerance = 0.3

    for k in list_surf:
        center_point = cubit.get_center_point("surface", k)

        #debug
        print '##surface: ' + str(k)
        print '## center point: ' + str(center_point)

        if abs((center_point[0] - xmin_box) /
               x_len) <= absorbing_surface_distance_tolerance:
            #debug
            print '## xmin surface: ' + str(k)
            absorbing_surf_xmin.append(k)
            absorbing_surf.append(k)
        elif abs((center_point[0] - xmax_box) /
                 x_len) <= absorbing_surface_distance_tolerance:
            #debug
            print '## xmax surface: ' + str(k)
            absorbing_surf_xmax.append(k)
            absorbing_surf.append(k)
        elif abs((center_point[1] - ymin_box) /
                 y_len) <= absorbing_surface_distance_tolerance:
            #debug
            print '## ymin surface: ' + str(k)
            absorbing_surf_ymin.append(k)
            absorbing_surf.append(k)
        elif abs((center_point[1] - ymax_box) /
                 y_len) <= absorbing_surface_distance_tolerance:
            #debug
            print '## ymax surface: ' + str(k)
            absorbing_surf_ymax.append(k)
            absorbing_surf.append(k)
        elif abs((center_point[2] - zmin_box) /
                 z_len) <= absorbing_surface_distance_tolerance:
            #debug
            print '## bottom surface: ' + str(k)
            absorbing_surf_bottom.append(k)
            absorbing_surf.append(k)
        else:
            sbox = cubit.get_bounding_box('surface', k)
            dz = abs((sbox[7] - zmax_box) / z_len)
            normal = cubit.get_surface_normal(k)
            zn = normal[2]
            dn = abs(abs(zn) - 1)
            #debug
            #print '## surface element: ' + str(k)
            #print '## surface element: zn ' + str(zn)
            #print '## surface element: dn ' + str(dn)
            #print '## surface element: dz ' + str(dz)
            if dz <= topographic_surface_distance_tolerance and dn < topographic_surface_normal_tolerance:
                #debug
                print '## topo surface: ' + str(k)
                top_surf.append(k)

    return absorbing_surf, absorbing_surf_xmin, absorbing_surf_xmax, absorbing_surf_ymin, absorbing_surf_ymax, absorbing_surf_bottom, top_surf
Exemple #17
0
    sys.path.append('../../CUBIT_GEOCUBIT')
print("path:")
for path in sys.path: print("  ",path)
print("")

## choose your element mesh size
elementsize = 300.0

# default directories
outputdir='MESH'
os.system('mkdir -p '+ outputdir)

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')

# 4-layered model
#
if 1 == 1:
    # way 1: merges bricks to create volumes
    # layer 1
import os
import sys
import numpy
import scipy

sys.path.append("/Applications/Cubit-15.3/Cubit.app/Contents/MacOS/")
import cubit
cubit.init(['cubit','-info','off','-warning','off'])

def displayHelp():
    print "About:"
    print "This script uses Cubit-Python to generate an input file for MeshGenie Maximal Poisson Grid Solver" + "\n"
    print "Syntax:"
    print "python Cubit_Trimesh_2_MeshGenie.py mode geom_type method meshsize fileoutput" + "\n"
    print "Arguments:"
    print "mode: Used to define which geometry creation method user wants"
    print "\t" + "Simple: Use one of Cubit's geometry primitives"
    print "\t" + "UserSpecified: User will supply a geometry model"
    print "geom_type: Used to specify which geometry should be made, dependent on value of <mode>"
    print "\t" + "If <mode> is 'Simple', user must supply a valid Cubit syntax for creating a primitive using " + '"cubit command here"' + " syntax"
    print "\t" + "If <mode> is 'UserSpecified', user must provide a path to a valid geometry file that Cubit can read"
    print "\t\t" + "CAD format must be one of the following types:"
    print "\t\t\t" + "ACIS (.sat) | STEP (.stp) | STL (.stl) | Exodus (.g | .e)"
    print "method: Used to specify which mesh generation method to use:"
    print "\t" + "Tri: Uses a surface tri-mesher to construct surface mesh"
    print "\t" + "Tet: Uses a volumetric tet-mesher, which may result in higher quality surface mesh, and extracts surface triangles"
    print "meshsize: Specifies the approximate element size for the selected mesh techniqe"
    print "radius: The radius to use in MeshGenie Maximal Poisson Grid Solver"
    print "rseed: The random seed to use in MeshGenie Maximal Poisson Grid Solver"
    print "fileoutput: The path and name of the output file"
#!/usr/bin/env python
import os
import cubit
try:
    cubit.init([""])
except:
    pass



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 = 3000.0

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


from geocubitlib import boundary_definition,exportlib

boundary_definition.define_bc(parallel=True)

os.system('mkdir -p MESH/')
exportlib.collect(outdir='MESH/')
Exemple #20
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 #21
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 #22
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
os.system('mkdir -p '+ SEMoutput)
os.system('mkdir -p '+ CUBIToutput)

## obsolete:
#import boundary_definition
#import cubit2specfem3d
## new:
from geocubitlib import boundary_definition
from geocubitlib import cubit2specfem3d

## CUBIT/Trelis
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')
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 #25
0
#!/usr/bin/env python



import cubit
try:
    cubit.init([""])
except:
    pass

f='./cubit_mesh_files/mesh.e'
o='./specfem3d_mesh_files'


cubit.cmd('import mesh "'+f+'" block all  no_geom ')




from geocubitlib import  exportlib

exportlib.e2SEM(outdir=o)
Exemple #26
0
    cubit.cmd(
        'block {0} attribute index 1 1'.format(nb))  # flag for fault side 1
    cubit.cmd('block {0} attribute index 2 {1}'.format(nb, vp))  # vp
    cubit.cmd('block {0} attribute index 3 {1}'.format(nb, vs))  # vs
    cubit.cmd('block {0} attribute index 4 {1}'.format(nb, rho))  # rho
    cubit.cmd('block {0} attribute index 5 {1}'.format(
        nb, Q))  # Q flag (see constants.h: #IATTENUATION_ ... )


def define_block_hex27(i):
    cubit.cmd('block {0}  vol {0} '.format(i))
    cubit.cmd('block {0} element type hex27'.format(i))
    cubit.cmd('reset block {0}'.format(i))


cubit.init([''])
#cubit.cmd('open "tpv29.cub"')
cubit.cmd('open "slab_rotate.cub"')
cubit.cmd('vol all scale 1000')
cubit.cmd('vol all scale 1.11195')
#This reflects the fact that 1deg=111.195km
########### Fault elements and nodes ###############
os.system('mkdir -p MESH')
cubit.cmd('unmerge surf 3')
cubit.cmd('set node constraint on')
for iblock in range(1, 11, 1):
    define_block_hex27(iblock)

cubit.cmd('set node constraint off')
cubit.cmd("group 'upp'  add node in surface 39")
cubit.cmd("group 'lowr' add node in surface 9")