Exemplo n.º 1
0
def build_block(vol_list, name):
    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
    #print("# build block: ",block_list,"vol",vol_list,"id_block",id_block)
    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 vol ' + str(v)
        command = command.replace("[", " ").replace("]", " ")
        #print("# build block: ",command)
        cubit.cmd(command)
        command = "block " + str(id_block) + " name '" + n + "'"
        #print("# build block: ",command)
        cubit.cmd(command)
Exemplo n.º 2
0
def e2SEM(files=False,listblock=None,listflag=None,outdir='.',cpml=False,cpml_size=False,top_absorbing=False,hex27=False):
    import glob
    if files:
        filenames=glob.glob(files)
        for f in filenames:
            print f
            extension=f.split('.')[-1]
            if extension == 'cub':
                cubit.cmd('open "'+f+'"')
            elif extension== 'e':
                cubit.cmd('import mesh "'+f+'" no_geom')
            else:
                print extension
    if listblock and listflag:
        pass
    else:
        listblock=[]
        listflag=[]
        block_list=list(cubit.get_block_id_list())
        for block in block_list:
            ty=cubit.get_block_element_type(block)
            if 'HEX' in ty:
                listblock.append(block)
                #listflag.append(block)
        listflag=range(1,len(block_list)+1)  
    #       
    for ib,iflag in zip(listblock,listflag):
        cubit.cmd("block "+str(ib)+" attribute count 1")
        cubit.cmd("block "+str(ib)+" attribute index 1 "+ str(iflag)            )
    #
    import cubit2specfem3d
    cubit2specfem3d.export2SPECFEM3D(outdir,cpml=cpml,cpml_size=cpml_size,top_absorbing=top_absorbing,hex27=hex27)
Exemplo n.º 3
0
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 vol ' + str(v)
        command = command.replace("[", " ").replace("]", " ")
        cubit.cmd(command)
        command = "block " + str(id_block) + " name '" + n + "'"
        cubit.cmd(command)
Exemplo n.º 4
0
def build_block(vol_list, name, id_0=1, top_surf=None, optionsea=False):
    #
    from sets import Set
    if optionsea:
        sea = optionsea['sea']
        seaup = optionsea['seaup']
        sealevel = optionsea['sealevel']
        seathres = optionsea['seathres']
    else:
        sea = False
        seaup = False
        sealevel = False
        seathres = False

    #
    block_list = cubit.get_block_id_list()
    if len(block_list) > 0:
        id_block = max(max(block_list), 2) + id_0
    else:
        id_block = 2 + id_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))
        if sea and v == vol_list[-1]:
            cubit.cmd('set duplicate block elements off')
            tsurf_string = " ".join(str(x) for x in top_surf)
            #sea
            command = 'block ' + str(
                id_block
            ) + ' hex in node in surf ' + tsurf_string + ' with Z_coord < ' + str(
                seathres)
            cubit.cmd(command)
            command = "block " + str(id_block) + " name 'sea" + n + "'"
            cubit.cmd(command)
            if not seaup:
                id_block += 1
                command = 'block ' + str(
                    id_block
                ) + ' hex in node in surf ' + tsurf_string + ' with (Z_coord > ' + str(
                    seathres) + ' and Z_coord < ' + str(sealevel)
                cubit.cmd(command)
                command = "block " + str(id_block) + " name 'shwater" + n + "'"
                cubit.cmd(command)
            id_block += 1
            command = 'block ' + str(
                id_block
            ) + ' hex in node in surf ' + tsurf_string + ' with Z_coord >= ' + str(
                sealevel)
            cubit.cmd(command)
            command = "block " + str(id_block) + " name 'continent" + n + "'"
            cubit.cmd(command)
        else:
            command = 'block ' + str(id_block) + ' hex in vol ' + str(
                v) + ' except hex in vol ' + str(list(v_other))
            print command
            command = command.replace("[", " ").replace("]", " ")
            cubit.cmd(command)
            command = "block " + str(id_block) + " name '" + n + "'"
            cubit.cmd(command)
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)
Exemplo n.º 6
0
def add_sea_layer(block=1001,optionsea=False):
    if optionsea:
            sea=optionsea['sea']
            seaup=optionsea['seaup']
            sealevel=optionsea['sealevel']
            seathres=optionsea['seathres']
    else:
            sea=False
            seaup=False
            sealevel=False
            seathres=False
    
    ######TODO
    #add sea hex
    #change hex absoorbing....
    block_list=cubit.get_block_id_list()
    id_block = max(block for block in block_list if block<1000)
    cubit.cmd('delete block '+str(id_block))
    #sea
    command= 'block '+str(id_block)+' hex in node in face in block '+str(block)+' with Z_coord < '+str(seathres)
    cubit.cmd(command)
    command = "block "+str(id_block)+" name 'sea'"
    cubit.cmd(command)
    if not seaup:
        id_block+=1
        command= 'block '+str(id_block)+' hex in node in face in block '+str(block)+' with (Z_coord > '+str(seathres)+' and Z_coord < '+str(sealevel)+')'
        cubit.cmd(command)
        command = "block "+str(id_block)+" name 'shwater'"
        cubit.cmd(command)
    id_block+=1
    command= 'block '+str(id_block)+' hex in node in face in block '+str(block)+' with Z_coord >= '+str(sealevel)
    cubit.cmd(command)
    command = "block "+str(id_block)+" name 'continent'"
    cubit.cmd(command)
Exemplo n.º 7
0
def build_block(vol_list, name, id_0=1, top_surf=None, optionsea=False):
    #
    from sets import Set
    if optionsea:
        sea = optionsea['sea']
        seaup = optionsea['seaup']
        sealevel = optionsea['sealevel']
        seathres = optionsea['seathres']
    else:
        sea = False
        seaup = False
        sealevel = False
        seathres = False

    #
    block_list = cubit.get_block_id_list()
    if len(block_list) > 0:
        id_block = max(max(block_list), 2) + id_0
    else:
        id_block = 2 + id_0
    for v, n in zip(vol_list, name):
        id_block += 1
        v_other = Set(vol_list) - Set([v])
        if sea and v == vol_list[-1]:
            cubit.cmd('set duplicate block elements off')
            tsurf_string = " ".join(str(x) for x in top_surf)
            # sea
            command = 'block ' + str(id_block) + ' hex in node in surf ' + \
                tsurf_string + ' with Z_coord < ' + str(seathres)
            cubit.cmd(command)
            command = "block " + str(id_block) + " name 'sea" + n + "'"
            cubit.cmd(command)
            if not seaup:
                id_block += 1
                command = 'block ' + str(id_block) + ' hex in node in surf ' +\
                          tsurf_string + ' with (Z_coord > ' + str(seathres) +\
                          ' and Z_coord < ' + str(sealevel)
                cubit.cmd(command)
                command = "block " + str(id_block) + " name 'shwater" + n + "'"
                cubit.cmd(command)
            id_block += 1
            command = 'block ' + str(id_block) + ' hex in node in surf ' + \
                tsurf_string + ' with Z_coord >= ' + str(sealevel)
            cubit.cmd(command)
            command = "block " + str(id_block) + " name 'continent" + n + "'"
            cubit.cmd(command)
        else:
            version_cubit = get_cubit_version()
            if version_cubit >= 15:
                command = 'block ' + str(id_block) + ' hex in vol ' + \
                          str(v)
            else:
                command = 'block ' + str(id_block) + ' hex in vol ' + \
                          str(v) + ' except hex in vol ' + str(list(v_other))
            print command
            command = command.replace("[", " ").replace("]", " ")
            cubit.cmd(command)
            command = "block " + str(id_block) + " name '" + n + "'"
            cubit.cmd(command)
Exemplo n.º 8
0
def collecting_cpml(ip,size=None,cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1,cubfiles=False,decimate=False,layers=2):
    import glob
    import re
    from utilities import list2str
    #
    if not size:
        print 'cpml size must be specified'
        return


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


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

    list_vol=list(cubit.parse_cubit_list('volume','all'))
    create_pml(xmin=xmin,xmax=xmax,ymax=ymax,ymin=ymin,zmin=zmin,zmax=zmax,size=size,layers=layers,vol=list_vol)
Exemplo n.º 9
0
def collecting_cpml(ip,size=None,cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1,cubfiles=False,decimate=False,layers=2):
    import glob
    import re
    from utilities import list2str
    #
    if not size:
        print 'cpml size must be specified'
        return
        
        
    boundary_dict={}
    ##
    try:
        from boundary_definition import check_bc, map_boundary, define_surf
    except:
        pass
    #
    xmin,xmax,ymin,ymax,listfull=map_boundary(cpuxmin,cpuxmax,cpuymin,cpuymax,cpux,cpuy)
    #
    if cubfiles:        
        nf,listip,filenames,cubflag=importing_cubfiles(cubfiles)
    else:
        nf=0
        filenames=[]
        ip=0
    #
    if nf > 0:
        for ip,filename in zip(listip,filenames):
            try:
                if ip in listfull:
                    if cubflag:
                        cubit.cmd('import cubit "'+filename+'"')
                    else:
                        cubit.cmd('import mesh geometry "'+filename+'" block all use nodeset sideset feature_angle 135.00 linear merge')
                    if decimate: cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
            except:
                cubit.cmd('import mesh geometry "'+filename+'" block all use nodeset sideset feature_angle 135.00 linear merge')
                if decimate: cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
                ip=0
        if decimate: cubit.cmd('export mesh "decimated_before_cmpl.e" dimension 3 block all overwrite')
    else:
        if decimate: 
            cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
            cubit.cmd('export mesh "decimated_before_cmpl.e" dimension 3 block all overwrite')

    
    #
    #
    #print boundary_dict
    block_list=cubit.get_block_id_list()
    for block in block_list:
        ty=cubit.get_block_element_type(block)
        if ty == 'HEX8':
            cubit.cmd('block '+str(block)+' name "vol'+str(block)+'"')
            
    list_vol=list(cubit.parse_cubit_list('volume','all'))
    create_pml(xmin=xmin,xmax=xmax,ymax=ymax,ymin=ymin,zmin=zmin,zmax=zmax,size=size,layers=layers,vol=list_vol)
Exemplo n.º 10
0
def e2SEM(files=False,
          listblock=None,
          listflag=None,
          outdir='.',
          cpml=False,
          cpml_size=False,
          top_absorbing=False,
          hex27=False):
    import glob
    if files:
        filenames = glob.glob(files)
        for f in filenames:
            print f
            extension = f.split('.')[-1]
            if extension == 'cub':
                cubit.cmd('open "' + f + '"')
            elif extension == 'e':
                cubit.cmd('import mesh "' + f + '" no_geom')
            else:
                print extension
    if listblock and listflag:
        pass
    else:
        listblock = []
        listflag = []
        block_list = list(cubit.get_block_id_list())
        for block in block_list:
            ty = cubit.get_block_element_type(block)
            if 'HEX' in ty:
                listblock.append(block)
                #listflag.append(block)
        listflag = range(1, len(block_list) + 1)
    #
    for ib, iflag in zip(listblock, listflag):
        cubit.cmd("block " + str(ib) + " attribute count 1")
        cubit.cmd("block " + str(ib) + " attribute index 1 " + str(iflag))
    #
    import cubit2specfem3d
    print "#e2SEM: output dir = ", outdir
    cubit2specfem3d.export2SPECFEM3D(outdir,
                                     cpml=cpml,
                                     cpml_size=cpml_size,
                                     top_absorbing=top_absorbing,
                                     hex27=hex27)
Exemplo n.º 11
0
def add_sea_layer(block=1001, optionsea=False):
    if optionsea:
        sea = optionsea['sea']
        seaup = optionsea['seaup']
        sealevel = optionsea['sealevel']
        seathres = optionsea['seathres']
    else:
        sea = False
        seaup = False
        sealevel = False
        seathres = False

    ######TODO
    #add sea hex
    #change hex absoorbing....
    block_list = cubit.get_block_id_list()
    id_block = max(block for block in block_list if block < 1000)
    cubit.cmd('delete block ' + str(id_block))
    #sea
    command = 'block ' + str(
        id_block) + ' hex in node in face in block ' + str(
            block) + ' with Z_coord < ' + str(seathres)
    cubit.cmd(command)
    command = "block " + str(id_block) + " name 'sea'"
    cubit.cmd(command)
    if not seaup:
        id_block += 1
        command = 'block ' + str(
            id_block) + ' hex in node in face in block ' + str(
                block) + ' with (Z_coord > ' + str(
                    seathres) + ' and Z_coord < ' + str(sealevel) + ')'
        cubit.cmd(command)
        command = "block " + str(id_block) + " name 'shwater'"
        cubit.cmd(command)
    id_block += 1
    command = 'block ' + str(
        id_block) + ' hex in node in face in block ' + str(
            block) + ' with Z_coord >= ' + str(sealevel)
    cubit.cmd(command)
    command = "block " + str(id_block) + " name 'continent'"
    cubit.cmd(command)
Exemplo n.º 12
0
def collecting_block(store_group_name,ip=0,xmin=[0],xmax=[0],ymin=[0],ymax=[0],index_block=0):
    block_list=list(cubit.get_block_id_list())
    block_list.sort()
    block_hex =[x for x in block_list if x <= 1000]
    block_side=[x for x in block_list if x >  1000]
    for ib,block in enumerate(block_hex):
            if index_block==0: 
                cubit.cmd("group 'vol"+str(block)+"' add Hex in block "+str(block))
                store_group_name.append('vol'+str(block))
                cubit.cmd("del block "+str(block))
            else:
                cubit.cmd("group '"+store_group_name[ib]+"' add Hex in block "+str(block))
                cubit.cmd("del block "+str(block))
    for ib,side in enumerate(block_side):
            if side == 1004:
                if ip in ymin:
                    cubit.cmd("group 'ymin' add face in block "+str(side))
                else:
                    cubit.cmd("group 'lateral' add face in block "+str(side)) 
            elif side == 1003:
                if ip in xmin:
                    cubit.cmd("group 'xmin' add face in block "+str(side))
                else:
                    cubit.cmd("group 'lateral' add face in block "+str(side))
            elif side == 1006:
                if ip in ymax:
                    cubit.cmd("group 'ymax' add face in block "+str(side))
                else:
                    cubit.cmd("group 'lateral' add face in block "+str(side))
            elif side == 1005:
                if ip in xmax:
                    cubit.cmd("group 'xmax' add face in block "+str(side))
                else:
                    cubit.cmd("group 'lateral' add face in block "+str(side))
            elif side == 1001:
                cubit.cmd("group 'topo' add face in block "+str(side))
            elif side == 1002:
                cubit.cmd("group 'bot' add face in block "+str(side))
            cubit.cmd("del block "+str(side))
    return store_group_name
Exemplo n.º 13
0
def collect(cpuxmin=0,
            cpuxmax=1,
            cpuymin=0,
            cpuymax=1,
            cpux=1,
            cpuy=1,
            cubfiles=False,
            ckbound_method1=False,
            ckbound_method2=False,
            merge_tolerance=None,
            curverefining=False,
            outfilename='totalmesh_merged',
            qlog=False,
            export2SPECFEM3D=False,
            listblock=None,
            listflag=None,
            outdir='.',
            add_sea=False,
            decimate=False,
            cpml=False,
            cpml_size=False,
            top_absorbing=False,
            hex27=False):
    #
    cubit.cmd('set journal error off')
    cubit.cmd('set verbose error off')
    collecting_merging(cpuxmin,
                       cpuxmax,
                       cpuymin,
                       cpuymax,
                       cpux,
                       cpuy,
                       cubfiles=cubfiles,
                       ckbound_method1=ckbound_method1,
                       ckbound_method2=ckbound_method2,
                       merge_tolerance=merge_tolerance,
                       decimate=decimate)
    cubit.cmd('set journal error on')
    cubit.cmd('set verbose error on')
    #
    if curverefining:
        block = 1001  #topography
        refine_closecurve(block, curverefining, acis=True)
    #
    #
    if add_sea:
        block = 1001
        add_sea_layer(block=block)

    outdir2 = '/'.join(x for x in outfilename.split('/')[:-1])
    if outdir2 == '':
        outdir2 = outdir + '/'
    else:
        outdir2 = outdir + '/' + outdir2 + '/'

    import os
    try:
        os.makedirs(outdir2)
    except OSError:
        pass

    cubit.cmd('compress all')
    command = "export mesh '" + outdir2 + outfilename + ".e' block all overwrite xml '" + outdir2 + outfilename + ".xml'"
    cubit.cmd(command)
    f = open(outdir2 + 'blocks.dat', 'w')
    blocks = cubit.get_block_id_list()
    #
    for block in blocks:
        name = cubit.get_exodus_entity_name('block', block)
        element_count = cubit.get_exodus_element_count(block, "block")
        nattrib = cubit.get_block_attribute_count(block)
        attr = [
            cubit.get_block_attribute_value(block, x)
            for x in range(0, nattrib)
        ]
        ty = cubit.get_block_element_type(block)
        f.write(
            str(block) + ' ; ' + name + ' ; nattr ' + str(nattrib) + ' ; ' +
            ' '.join(str(x) for x in attr) + ' ; ' + ty + ' ' +
            str(element_count) + '\n')
    f.close()
    #
    #
    cubit.cmd('set info echo journ off')
    cmd = 'del group all'
    cubit.silent_cmd(cmd)
    cubit.cmd('set info echo journ on')
    #
    command = "save as '" + outdir2 + outfilename + ".cub' overwrite"
    cubit.cmd(command)
    #
    print 'end meshing'
    #
    #
    if qlog:
        print '\n\nQUALITY CHECK.... ***************\n\n'
        import quality_log
        tq = open(outdir2 + outfilename + '.quality', 'w')
        max_skewness, min_length = quality_log.quality_log(tq)
    #
    #
    #
    if export2SPECFEM3D:
        e2SEM(files=False,
              listblock=listblock,
              listflag=listflag,
              outdir=outdir,
              cpml=cpml,
              cpml_size=cpml_size,
              top_absorbing=top_absorbing,
              hex27=hex27)
Exemplo n.º 14
0
def collecting_merging(cpuxmin=0,
                       cpuxmax=1,
                       cpuymin=0,
                       cpuymax=1,
                       cpux=1,
                       cpuy=1,
                       cubfiles=False,
                       ckbound_method1=False,
                       ckbound_method2=False,
                       merge_tolerance=None,
                       decimate=False):
    import glob
    import re
    #
    rule_st = re.compile("(.+)_[0-9]+\.")
    rule_ex = re.compile(".+_[0-9]+\.(.+)")
    rule_int = re.compile(".+_([0-9]+)\.")
    boundary_dict = {}
    ##
    try:
        from boundary_definition import check_bc, map_boundary
    except:
        pass
    #
    xmin, xmax, ymin, ymax, listfull = map_boundary(cpuxmin, cpuxmax, cpuymin,
                                                    cpuymax, cpux, cpuy)
    #
    if cubfiles:
        nf, listip, filenames, cubflag = importing_cubfiles(cubfiles)
    else:
        nf = 0
        filenames = []
        ip = 0
    #
    if nf > 0:
        for ip, filename in zip(listip, filenames):
            try:
                if ip in listfull:
                    if cubflag:
                        cubit.cmd('import cubit "' + filename + '"')
                    else:
                        cubit.cmd(
                            'import mesh geometry "' + filename +
                            '" block all use nodeset sideset feature_angle 135.00 linear merge'
                        )
                    if decimate:
                        cubit.cmd(
                            'refine volume all numsplit 1 bias 1.0 depth 1 ')
                    boundary = check_bc(ip, xmin, xmax, ymin, ymax, cpux, cpuy,
                                        cpuxmin, cpuxmax, cpuymin, cpuymax)
                    boundary_dict[ip] = boundary
                    list_vol = list(cubit.parse_cubit_list('volume', 'all'))
                    for v in list_vol:
                        cubit.cmd("disassociate mesh from volume " + str(v))
                        command = "del vol " + str(v)
                        cubit.cmd(command)
            except:
                cubit.cmd(
                    'import mesh geometry "' + filename +
                    '" block all use nodeset sideset feature_angle 135.00 linear merge'
                )
                if decimate:
                    cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
                ip = 0
                boundary = check_bc(ip, xmin, xmax, ymin, ymax, cpux, cpuy,
                                    cpuxmin, cpuxmax, cpuymin, cpuymax)
                boundary_dict[ip] = boundary
                list_vol = list(cubit.parse_cubit_list('volume', 'all'))
                for v in list_vol:
                    cubit.cmd("disassociate mesh from volume " + str(v))
                    command = "del vol " + str(v)
                    cubit.cmd(command)
        cubit.cmd(
            'export mesh "tmp_collect_NOmerging.e" dimension 3 block all overwrite'
        )
    else:
        if decimate:
            cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
        boundary = check_bc(ip, xmin, xmax, ymin, ymax, cpux, cpuy, cpuxmin,
                            cpuxmax, cpuymin, cpuymax)
    #
    #
    #print boundary_dict
    block_list = cubit.get_block_id_list()
    for block in block_list:
        ty = cubit.get_block_element_type(block)
        if ty == 'HEX8':
            cubit.cmd('block ' + str(block) + ' name "vol' + str(block) + '"')
    #
    #
    print 'chbound', ckbound_method1, ckbound_method2

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

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

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

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

        #
        #
        cmd = 'group "negativejac" add quality hex all Jacobian high'
        cubit.cmd(cmd)
        group_id_1 = cubit.get_id_from_name("negativejac")
        n1 = cubit.get_group_nodes(group_id_1)
        if len(n1) != 0:
            print 'error, negative jacobian after the equivalence node command, use --merge2 instead of --equivalence/--merge/--merge1'
    elif ckbound_method2 and not ckbound_method1 and len(filenames) != 1:
        if isinstance(merge_tolerance, list):
            tol = merge_tolerance[0]
        elif merge_tolerance:
            tol = merge_tolerance
        else:
            tol = 100000
        #
        idiag = None
        for ix in range(cpuxmin, cpuxmax):
            for iy in range(cpuymin, cpuymax):
                ip = iy * cpux + ix
                print '******************* ', ip
                #
                #   ileft    |   ip
                #  --------------------
                #   idiag    |   idown
                #
                #
                if ip not in xmin and ip not in ymin:
                    ileft = iy * cpux + ix - 1
                    idown = (iy - 1) * cpux + ix
                    idiag = idown - 1
                elif ip in xmin and ip in ymin:
                    ileft = ip
                    idown = ip
                elif ip in xmin:
                    ileft = ip
                    idown = (iy - 1) * cpux + ix
                    idiag = idown
                elif ip in ymin:
                    ileft = iy * cpux + ix - 1
                    idown = ip
                    idiag = ileft
                #
                #
                if ip != idown:
                    nup = boundary_dict[ip]['nodes_surf_ymin']
                    ndow = boundary_dict[idown]['nodes_surf_ymax']
                    for n1, n2 in zip(nup, ndow):
                        cubit.cmd('equivalence node ' + str(n1) + ' ' +
                                  str(n2) + ' tolerance ' + str(tol))
                    if idiag != idown:
                        if ip in ymax and ip not in xmin:
                            nlu = boundary_dict[ip][
                                'node_curve_xminymax']  #node in curve chunck left up... r u
                            nru = boundary_dict[ileft]['node_curve_xmaxymax']
                            for n in zip(nlu, nru):
                                cubit.cmd('equivalence node ' +
                                          ' '.join(str(x) for x in n) +
                                          ' tolerance ' + str(tol))
                        nru = boundary_dict[ip][
                            'node_curve_xminymin']  #node in curve chunck right up... r u
                        nrd = boundary_dict[idown]['node_curve_xminymax']
                        nld = boundary_dict[idiag]['node_curve_xmaxymax']
                        nlu = boundary_dict[ileft]['node_curve_xmaxymin']
                        for n in zip(nru, nrd, nlu, nld):
                            cubit.cmd('equivalence node ' +
                                      ' '.join(str(x) for x in n) +
                                      ' tolerance ' + str(tol))
                    elif ip in xmin:
                        nru = boundary_dict[ip][
                            'node_curve_xminymin']  #node in curve chunck right up... r u
                        nrd = boundary_dict[idown]['node_curve_xminymax']
                        for n in zip(nru, nrd):
                            cubit.cmd('equivalence node ' +
                                      ' '.join(str(x) for x in n) +
                                      ' tolerance ' + str(tol))
                #
                #
                if ip != ileft:
                    nright = boundary_dict[ip]['nodes_surf_xmin']
                    nleft = boundary_dict[ileft]['nodes_surf_xmax']
                    for n1, n2 in zip(nleft, nright):
                        cubit.cmd('equivalence node ' + str(n1) + ' ' +
                                  str(n2) + ' tolerance ' + str(tol))
                    #
                    #
                    if ip in ymin:
                        nrd = boundary_dict[ip][
                            'node_curve_xminymin']  #node in curve chunck right down... r u
                        nld = boundary_dict[ileft]['node_curve_xmaxymin']
                        for n in zip(nrd, nld):
                            cubit.cmd('equivalence node ' +
                                      ' '.join(str(x) for x in n) +
                                      ' tolerance ' + str(tol))
                    if ip in ymax:
                        nru = boundary_dict[ip][
                            'node_curve_xminymax']  #node in curve chunck right up... r u
                        nlu = boundary_dict[ileft]['node_curve_xmaxymax']
                        for n in zip(nru, nlu):
                            cubit.cmd('equivalence node ' +
                                      ' '.join(str(x) for x in n) +
                                      ' tolerance ' + str(tol))
        #
        #
        cmd = 'topology check coincident node face all tolerance ' + str(
            tol * 2) + ' nodraw brief result group "checkcoinc"'
        cubit.silent_cmd(cmd)
        group_id_1 = cubit.get_id_from_name("checkcoinc")
        if group_id_1 != 0:
            n1 = cubit.get_group_nodes(group_id_1)
            if len(n1) != 0:
                print 'error, coincident nodes after the equivalence node command, check the tolerance'
                import sys
                sys.exit()
        cmd = 'group "negativejac" add quality hex all Jacobian high'
        cubit.cmd(cmd)
        group_id_1 = cubit.get_id_from_name("negativejac")
        n1 = cubit.get_group_nodes(group_id_1)
        if len(n1) != 0:
            print 'error, negative jacobian after the equivalence node command, check the mesh'
    elif ckbound_method1 and ckbound_method2 and len(filenames) != 1:
        block_list = cubit.get_block_id_list()
        i = -1
        for block in block_list:
            ty = cubit.get_block_element_type(block)
            if ty == 'HEX8':
                i = i + 1
                if isinstance(merge_tolerance, list):
                    try:
                        tol = merge_tolerance[i]
                    except:
                        tol = merge_tolerance[-1]
                elif merge_tolerance:
                    tol = merge_tolerance
                else:
                    tol = 1
                cmd = 'topology check coincident node face in hex in block ' + str(
                    block) + ' tolerance ' + str(
                        tol) + ' nodraw brief result group "b' + str(
                            block) + '"'
                cubit.cmd(cmd)
                print cmd
                cmd = 'equivalence node in group b' + str(
                    block) + ' tolerance ' + str(tol)
                cubit.cmd(cmd)
                print cmd
        if isinstance(merge_tolerance, list):
            tol = max(merge_tolerance)
        elif merge_tolerance:
            tol = merge_tolerance
        else:
            tol = 1
        #
        #
        cmd = 'topology check coincident node face all tolerance ' + str(
            tol) + ' nodraw brief result group "checkcoinc"'
        cubit.silent_cmd(cmd)
        group_id_1 = cubit.get_id_from_name("checkcoinc")
        if group_id_1 != 0:
            n1 = cubit.get_group_nodes(group_id_1)
            if len(n1) != 0:
                print 'error, coincident nodes after the equivalence node command, check the tolerance'
                import sys
                sys.exit()
        cmd = 'group "negativejac" add quality hex all Jacobian high'
        cubit.silent_cmd(cmd)
        group_id_1 = cubit.get_id_from_name("negativejac")
        n1 = cubit.get_group_nodes(group_id_1)
        if len(n1) != 0:
            print 'error, negative jacobian after the equivalence node command, use --merge instead of --equivalence'
Exemplo n.º 15
0
    def block_definition(self):
        block_flag=[]
        block_mat=[]
        block_bc=[]
        block_bc_flag=[]
        material={}
        bc={}
        blocks=cubit.get_block_id_list()
        for block in blocks:
            name=cubit.get_exodus_entity_name('block',block)
            ty=cubit.get_block_element_type(block)
            #print block,blocks,ty,self.hex,self.face
            if self.hex in ty:
                flag=None
                vel=None
                vs=None
                rho=None
                q=0
                ani=0
                # material domain id
                if "acoustic" in name :
                  imaterial = 1
                elif "elastic"  in name:
                  imaterial = 2
                elif "poroelastic"  in name:
                  imaterial = 3
                else :
                  imaterial = 0
                #
                nattrib=cubit.get_block_attribute_count(block)
                if nattrib > 1:
                    # material flag:
                    #   positive => material properties,
                    #   negative => interface/tomography domain
                    flag=int(cubit.get_block_attribute_value(block,0))
                    if flag > 0 and nattrib >= 2:
                        # material properties
                        # vp
                        vel=cubit.get_block_attribute_value(block,1)
                        if nattrib >= 3:
                            # vs
                            vs=cubit.get_block_attribute_value(block,2)
                            if nattrib >= 4:
                                # density
                                rho=cubit.get_block_attribute_value(block,3)
                                if nattrib >= 5:
                                  # next: Q_kappa or Q_mu (new/old format style)
                                  q=cubit.get_block_attribute_value(block,4)
                                  if nattrib == 6:
                                    # only 6 parameters given (skipping Q_kappa ), old format style
                                    qmu = q
                                    #Q_kappa is 10 times stronger than Q_mu
                                    qk = q * 10
                                    # last entry is anisotropic flag
                                    ani=cubit.get_block_attribute_value(block,5)
                                  elif nattrib > 6:
                                     #Q_kappa
                                     qk=q
                                     #Q_mu
                                     qmu=cubit.get_block_attribute_value(block,5)
                                     if nattrib == 7:
                                        #anisotropy_flag
                                        ani=cubit.get_block_attribute_value(block,6)
                                  # for q to be valid: it must be positive
                                  if qk < 0 or qmu < 0:
                                    print 'error, Q value invalid:',qk,qmu
                                    break
                    elif flag < 0:
                        # interface/tomography domain
                        # velocity model
                        vel=name
                        attrib=cubit.get_block_attribute_value(block,1)
                        if attrib == 1:
                            kind='interface'
                            flag_down=cubit.get_block_attribute_value(block,2)
                            flag_up=cubit.get_block_attribute_value(block,3)
                        elif attrib == 2:
                            kind='tomography'
                elif  nattrib == 1:
                    flag=cubit.get_block_attribute_value(block,0)
                    #print 'only 1 attribute ', name,block,flag
                    vel,vs,rho,qk,qmu,ani=(0,0,0,9999.,9999.,0)
                else:
                    flag=block
                    vel,vs,rho,qk,qmu,ani=(name,0,0,9999.,9999.,0)
                block_flag.append(int(flag))
                block_mat.append(block)
                if (flag > 0) and nattrib != 1:
                    par=tuple([imaterial,flag,vel,vs,rho,qk,qmu,ani])
                elif flag < 0 and nattrib != 1:
                    if kind=='interface':
                        par=tuple([imaterial,flag,kind,name,flag_down,flag_up])
                    elif kind=='tomography':
                        par=tuple([imaterial,flag,kind,name])
                elif flag==0 or nattrib == 1:
                    par=tuple([imaterial,flag,name])
                material[block]=par
            elif ty == self.face:
                block_bc_flag.append(4)
                block_bc.append(block)
                bc[block]=4 #face has connectivity = 4
                if name == self.topo or block == 1001:
                    self.topography=block
                if self.freetxt in name:
                    self.free=block
            elif ty == 'SPHERE':
                pass
            else:
                # block elements differ from HEX8/QUAD4/SHELL4
                print '****************************************'
                print 'block not properly defined:'
                print '  name:',name
                print '  type:',type
                print
                print 'please check your block definitions!'
                print
                print 'only supported types are:'
                print '  HEX/HEX8  for volumes'
                print '  QUAD4 for surface'
                print '  SHELL4 for surface'
                print '****************************************'
                continue
                return None, None,None,None,None,None,None,None
        nsets=cubit.get_nodeset_id_list()
        if len(nsets) == 0: self.receivers=None
        for nset in nsets:
            name=cubit.get_exodus_entity_name('nodeset',nset)
            if name == self.rec:
                self.receivers=nset
            else:
                print 'nodeset '+name+' not defined'
                self.receivers=None

        try:
            self.block_mat=block_mat
            self.block_flag=block_flag
            self.block_bc=block_bc
            self.block_bc_flag=block_bc_flag
            self.material=material
            self.bc=bc
            print 'HEX Blocks:'
            for m,f in zip(self.block_mat,self.block_flag):
                print 'block ',m,'material flag ',f
            print 'Absorbing Boundary Conditions:'
            for m,f in zip(self.block_bc,self.block_bc_flag):
                print  'bc ',m,'bc flag ',f
            print 'Topography (free surface)'
            print self.topography
            print 'Free surface'
            print self.free
        except:
            print '****************************************'
            print 'sorry, no blocks or blocks not properly defined'
            print block_mat
            print block_flag
            print block_bc
            print block_bc_flag
            print material
            print bc
            print '****************************************'
    def block_definition(self):
        block_flag=[]
        block_mat=[]
        block_bc=[]
        block_bc_flag=[]
        material={}
        bc={}
        blocks=cubit.get_block_id_list()
        for block in blocks:
            name=cubit.get_exodus_entity_name('block',block)
            type=cubit.get_block_element_type(block)
            print block,name,blocks,type,self.hex,self.face
            # block has hexahedral elements (HEX8)
            if type == self.hex:
                flag=None
                vel=None
                vs=None
                rho=None
                q=0
                ani=0
                # material domain id
                if name.find("acoustic") >= 0 :
                  imaterial = 1
                elif name.find("elastic") >= 0 :
                  imaterial = 2
                elif name.find("poroelastic") >= 0 :
                  imaterial = 3
                else :
                  imaterial = 0
                  print "block: ",name
                  print "  could not find appropriate material for this block..."
                  print ""
                  break

                nattrib=cubit.get_block_attribute_count(block)
                if nattrib != 0:
                    # material flag:
                    #   positive => material properties,
                    #   negative => interface/tomography domain
                    flag=int(cubit.get_block_attribute_value(block,0))
                    if flag > 0 and nattrib >= 2:
                      # vp
                      vel=cubit.get_block_attribute_value(block,1)
                      if nattrib >= 3:
                        # vs
                        vs=cubit.get_block_attribute_value(block,2)
                        if nattrib >= 4:
                          #density
                          rho=cubit.get_block_attribute_value(block,3)
                          if nattrib >= 5:
                            #Q_mu
                            q=cubit.get_block_attribute_value(block,4)
                            # for q to be valid: it must be positive
                            if q < 0 :
                              print 'error, q value invalid:', q
                              break
                            if nattrib == 6:
                              #anisotropy_flag
                              ani=cubit.get_block_attribute_value(block,5)
                    elif flag < 0:
                        # velocity model
                        vel=name
                        attrib=cubit.get_block_attribute_value(block,1)
                        if attrib == 1:
                            kind='interface'
                            flag_down=cubit.get_block_attribute_value(block,2)
                            flag_up=cubit.get_block_attribute_value(block,3)
                        elif attrib == 2:
                            kind='tomography'
                else:
                    flag=block
                    vel,vs,rho,q,ani=(name,0,0,0,0)
                block_flag.append(int(flag))
                block_mat.append(block)
                if flag > 0:
                    par=tuple([imaterial,flag,vel,vs,rho,q,ani])
                elif flag < 0:
                    if kind=='interface':
                        par=tuple([imaterial,flag,kind,name,flag_down,flag_up])
                    elif kind=='tomography':
                        par=tuple([imaterial,flag,kind,name])
                elif flag==0:
                    par=tuple([imaterial,flag,name])
                material[block]=par
            elif (type == self.face) or (type == self.face2) :
                # block has surface elements (QUAD4 or SHELL4)
                block_bc_flag.append(4)
                block_bc.append(block)
                bc[block]=4 #face has connectivity = 4
                if name == self.topo: topography_face=block
            else:
                # block elements differ from HEX8/QUAD4/SHELL4
                print '****************************************'
                print 'block not properly defined:'
                print '  name:',name
                print '  type:',type
                print
                print 'please check your block definitions!'
                print
                print 'only supported types are:'
                print '  HEX8  for volumes'
                print '  QUAD4 for surface'
                print '  SHELL4 for surface'
                print '****************************************'
                continue

        nsets=cubit.get_nodeset_id_list()
        if len(nsets) == 0: self.receivers=None
        for nset in nsets:
            name=cubit.get_exodus_entity_name('nodeset',nset)
            if name == self.rec:
                self.receivers=nset
            else:
                print 'nodeset '+name+' not defined'
                self.receivers=None
        try:
            self.block_mat=block_mat
            self.block_flag=block_flag
            self.block_bc=block_bc
            self.block_bc_flag=block_bc_flag
            self.material=material
            self.bc=bc
            self.topography=topography_face
        except:
            print '****************************************'
            print 'sorry, no blocks or blocks not properly defined'
            print block_mat
            print block_flag
            print block_bc
            print block_bc_flag
            print material
            print bc
            print topography
            print '****************************************'
Exemplo n.º 17
0
def refine_closecurve(block=1001, closed_filenames=None, acis=True):
    from utilities import load_curves
    from boundary_definition import build_block_side, define_surf
    from mesh_volume import refine_inside_curve
    #
    #
    curves = []
    if not isinstance(closed_filenames, list):
        closed_filenames = [closed_filenames]
    for f in closed_filenames:
        print f
        if acis:
            curves = curves + load_curves(f)
    print curves
    blist = list(cubit.get_block_id_list())
    try:
        blist.remove(1001)
    except:
        pass
    try:
        blist.remove(1002)
    except:
        pass
    try:
        blist.remove(1003)
    except:
        pass
    try:
        blist.remove(1004)
    except:
        pass
    try:
        blist.remove(1005)
    except:
        pass
    try:
        blist.remove(1006)
    except:
        pass
    id_top = max(blist)
    cmd = 'group "coi" add node in hex in block ' + str(id_top)
    cubit.cmd(cmd)
    #
    id_inside_arc = None
    for c in map(int, curves[0].split()):  #curves is a list of one string
        c1001 = cubit.get_exodus_element_count(1001, "block")
        c1002 = cubit.get_exodus_element_count(1002, "block")
        c1003 = cubit.get_exodus_element_count(1003, "block")
        c1004 = cubit.get_exodus_element_count(1004, "block")
        c1005 = cubit.get_exodus_element_count(1005, "block")
        c1006 = cubit.get_exodus_element_count(1006, "block")
        #
        refine_inside_curve(c, ntimes=1, depth=1, block=block, surface=False)
        blist = list(cubit.get_block_id_list())
        cmd = 'create mesh geometry hex all except hex in block all feature_angle 135'
        cubit.cmd(cmd)
        blist_after = list(cubit.get_block_id_list())
        [blist_after.remove(x) for x in blist]
        id_inside = max(blist_after)
        cmd = 'group "coi" add node in hex in block ' + str(id_inside)
        cubit.cmd(cmd)
        if id_inside_arc:
            cmd = 'del block ' + str(id_inside - 1)
            cubit.cmd(cmd)
        cmd = 'block ' + str(id_inside) + ' name "refined"'
        cubit.cmd(cmd)
        id_inside_arc = id_inside
        #
        _, _, _, _, _, top_surf, bottom_surf, surf_xmin, surf_ymin, surf_xmax, surf_ymax = define_surf(
        )
        #
        c1001_after = cubit.get_exodus_element_count(1001, "block")
        c1002_after = cubit.get_exodus_element_count(1002, "block")
        c1003_after = cubit.get_exodus_element_count(1003, "block")
        c1004_after = cubit.get_exodus_element_count(1004, "block")
        c1005_after = cubit.get_exodus_element_count(1005, "block")
        c1006_after = cubit.get_exodus_element_count(1006, "block")
        entity = 'face'
        if c1001_after != c1001:
            refname = entity + '_topo'
            build_block_side(top_surf, refname, obj=entity, id_0=1001)
        #
        if c1002_after != c1002:
            refname = entity + '_bottom'
            build_block_side(bottom_surf, refname, obj=entity, id_0=1002)
        #
        if c1003_after != c1003:
            refname = entity + '_abs_xmin'
            build_block_side(surf_xmin, refname, obj=entity, id_0=1003)
        #
        if c1004_after != c1004:
            refname = entity + '_abs_ymin'
            build_block_side(surf_ymin, refname, obj=entity, id_0=1004)
        #
        if c1005_after != c1005:
            refname = entity + '_abs_xmax'
            build_block_side(surf_xmax, refname, obj=entity, id_0=1005)
        #
        if c1006_after != c1006:
            refname = entity + '_abs_ymax'
            build_block_side(surf_ymax, refname, obj=entity, id_0=1006)
        #
        cmd = 'disassociate mesh from volume all'
        cubit.cmd(cmd)
        cmd = 'group "coi" add node in face in block 1001 1002 1003 1004 1005 1006'
        cubit.cmd(cmd)
        cubit.cmd('del vol all')
        cubit.cmd('group "removedouble" add hex all except hex in block all')
        cubit.cmd('delete hex in removedouble')
        cubit.cmd('delet group removedouble')
        cmd = 'equivalence node in group coi tolerance 20'
        cubit.cmd(cmd)
    cmd = 'equivalence node all tolerance 10'
    cubit.cmd(cmd)
    cubit.cmd('del curve ' + ' '.join(str(x) for x in curves))
Exemplo n.º 18
0
def mesh_layercake_regularmap(filename=None):
    import sys,os
    import start as start
    mpiflag,iproc,numproc,mpi   = start.start_mpi()
    from utilities import  importgeometry,savemesh,get_v_h_list,cubit_command_check
    #
    numpy                       = start.start_numpy()
    cfg                         = start.start_cfg(filename=filename)
    from math import sqrt
    from sets import Set

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

    if max(vcurve_interval.values()) != min(vcurve_interval.values()):
        print 'mesh scheme is set to pave'
        schemepave=True
        for sk in surf_or:
            command = "surface "+str(sk)+" scheme pave"
            cubit.cmd(command)
    #
    for s in surf_vertical:
        lcurve=cubit.get_relatives("surface",s,"curve")
        interval_store=[]
        for k in lcurve:
            interval_curve=cubit.get_mesh_intervals('curve',k)
            if k in list_curve_vertical:
                volume_id = cubit.get_owning_volume("curve", k)
                for idv in range(0,nvol):
                    if vol[idv].ID == volume_id:
                        int_v=vol[idv].intervalv
                command = "curve "+str(k)+" interval "+str(int_v)
                cubit.cmd(command)
                #cubit_error_stop(iproc,command,ner)
                command = "curve "+str(k)+" scheme equal"
                cubit.cmd(command)
                #cubit_error_stop(iproc,command,ner)
            else:
                interval_store.append((k,interval_curve))
            if len(interval_store) != 0:
                interval_min=min([iv[1] for iv in interval_store])
                command = "curve "+' '.join(str(iv[0]) for iv in interval_store)+" interval "+str(interval_min)
                cubit.cmd(command)
                #cubit_error_stop(iproc,command,ner)
                command = "curve "+' '.join(str(iv[0]) for iv in interval_store)+" scheme equal"
                cubit.cmd(command)
                #cubit_error_stop(iproc,command,ner)
        command = "surface "+str(s)+" scheme submap"
        cubit.cmd(command)
        
    #cubit_error_stop(iproc,command,ner)
    #
    #meshing
    if cfg.or_mesh_scheme == 'pave' or schemepave:
        command='mesh surf '+' '.join(str(t) for t in top)
        status=cubit_command_check(iproc,command,stop=True)
        #cubit.cmd(command)    
    elif cfg.or_mesh_scheme == 'map':
        command='mesh surf '+' '.join(str(t) for t in bottom)
        status=cubit_command_check(iproc,command,stop=True)
        #cubit.cmd(command)
    for id_volume in range(nvol-1,-1,-1):
        command = "mesh vol "+str(vol[id_volume].ID)
        status=cubit_command_check(iproc,command,stop=False)
        if not status:
            for s in surf_vertical:
                command_surf="mesh surf "+str(s)
                cubit.cmd(command_surf)
            command_set_meshvol='volume all redistribute nodes on\nvolume all autosmooth target off\nvolume all scheme Sweep Vector 0 0 -1\nvolume all sweep smooth Auto\n'
            status=cubit_command_check(iproc,command_set_meshvol,stop=False)
            status=cubit_command_check(iproc,command,stop=True)    
    
    #
    #smoothing
    print iproc, 'untangling...'
    cmd="volume all smooth scheme untangle beta 0.02 cpu 10"
    cubit.cmd(cmd)
    cmd="smooth volume all"
    cubit.cmd(cmd)
    
    
    
    if  cfg.smoothing:
        print 'smoothing .... '+str(cfg.smoothing)
        cubitcommand= 'surf all smooth scheme laplacian '
        cubit.cmd(cubitcommand)
        cubitcommand= 'smooth surf all'
        cubit.cmd(cubitcommand)
        #
        cubitcommand= 'vol all smooth scheme laplacian '
        cubit.cmd(cubitcommand)
        cubitcommand= 'smooth vol all'
        cubit.cmd(cubitcommand)
    #
    #
    ##vertical refinement
    ##for nvol = 3 
    ##
    ##___________________________ interface 4
    ##                 
    ##vol 2              
    ##___________________________ interface 3
    ##
    ##vol 1
    ##___________________________ interface 2
    ##
    ##vol 0
    ##___________________________ interface 1
    ##
    refinement(nvol,vol,filename=filename)
    #
    #top layer vertical coarsening
    print 'coarsening top layer... ',cfg.coarsening_top_layer
    if  cfg.coarsening_top_layer:
        from sets import Set
        cubitcommand= 'del mesh vol '+str(vol[-1].ID)+ ' propagate'
        cubit.cmd(cubitcommand)
        s1=Set(list_curve_vertical)
        command = "group 'list_curve_tmp' add curve "+"in vol "+str(vol[-1].ID)
        cubit.cmd(command)
        group=cubit.get_id_from_name("list_curve_tmp")
        list_curve_tmp=cubit.get_group_curves(group)
        command = "delete group "+ str(group)
        cubit.cmd(command)
        s2=Set(list_curve_tmp)
        lc=list(s1 & s2)
        #
        cubitcommand= 'curve '+' '.join(str(x) for x in lc)+' interval '+str(cfg.actual_vertical_interval_top_layer)
        cubit.cmd(cubitcommand)
        cubitcommand= 'mesh vol '+str(vol[-1].ID)
        cubit.cmd(cubitcommand)
    #
    n=cubit.get_sideset_id_list()
    if len(n) != 0:
        command = "del sideset all"
        cubit.cmd(command)
    n=cubit.get_block_id_list()
    if len(n) != 0:    
        command = "del block all"
        cubit.cmd(command)
    #
    import boundary_definition
    entities=['face']
    print iproc, 'hex block definition...'
    boundary_definition.define_bc(entities,parallel=True,cpux=cfg.cpux,cpuy=cfg.cpuy,cpuxmin=0,cpuymin=0,optionsea=False)
    #save mesh
    
    print iproc, 'untangling...'
    cmd="volume all smooth scheme untangle beta 0.02 cpu 10"
    cubit.cmd(cmd)
    cmd="smooth volume all"
    cubit.cmd(cmd)
    
    print iproc, 'saving...'
    savemesh(mpiflag,iproc=iproc,filename=filename)
Exemplo n.º 19
0
    def block_definition(self):
        block_flag=[]
        block_mat=[]
        block_bc=[]
        block_bc_flag=[]
        material={}
        bc={}
        blocks=cubit.get_block_id_list()
        for block in blocks:
            name=cubit.get_exodus_entity_name('block',block)
            ty=cubit.get_block_element_type(block)
            #print block,blocks,ty,self.hex,self.face
            if self.hex in ty:
                flag=None
                vel=None
                vs=None
                rho=None
                q=0
                ani=0
                # material domain id
                if "acoustic" in name :
                  imaterial = 1
                elif "elastic"  in name:
                  imaterial = 2
                elif "poroelastic"  in name:
                  imaterial = 3
                else :
                  imaterial = 0
                #
                nattrib=cubit.get_block_attribute_count(block)
                if nattrib > 1:
                    # material flag:
                    #   positive => material properties,
                    #   negative => interface/tomography domain
                    flag=int(cubit.get_block_attribute_value(block,0))
                    if flag > 0 and nattrib >= 2:
                        # material properties
                        # vp
                        vel=cubit.get_block_attribute_value(block,1)
                        if nattrib >= 3:
                            # vs
                            vs=cubit.get_block_attribute_value(block,2)
                            if nattrib >= 4:
                                # density
                                rho=cubit.get_block_attribute_value(block,3)
                                if nattrib >= 5:
                                  # next: Q_kappa or Q_mu (new/old format style)
                                  q=cubit.get_block_attribute_value(block,4)
                                  if nattrib == 6:
                                    # only 6 parameters given (skipping Q_kappa ), old format style
                                    qmu = q
                                    #Q_kappa is 10 times stronger than Q_mu
                                    qk = q * 10
                                    # last entry is anisotropic flag
                                    ani=cubit.get_block_attribute_value(block,5)
                                  elif nattrib > 6:
                                     #Q_kappa
                                     qk=q
                                     #Q_mu
                                     qmu=cubit.get_block_attribute_value(block,5)
                                     if nattrib == 7:
                                        #anisotropy_flag
                                        ani=cubit.get_block_attribute_value(block,6)
                                  # for q to be valid: it must be positive
                                  if qk < 0 or qmu < 0:
                                    print 'error, Q value invalid:',qk,qmu
                                    break
                    elif flag < 0:
                        # interface/tomography domain
                        # velocity model
                        vel=name
                        attrib=cubit.get_block_attribute_value(block,1)
                        if attrib == 1:
                            kind='interface'
                            flag_down=cubit.get_block_attribute_value(block,2)
                            flag_up=cubit.get_block_attribute_value(block,3)
                        elif attrib == 2:
                            kind='tomography'
                elif  nattrib == 1:
                    flag=cubit.get_block_attribute_value(block,0)
                    #print 'only 1 attribute ', name,block,flag
                    vel,vs,rho,qk,qmu,ani=(0,0,0,9999.,9999.,0)
                else:
                    flag=block
                    vel,vs,rho,qk,qmu,ani=(name,0,0,9999.,9999.,0)
                block_flag.append(int(flag))
                block_mat.append(block)
                if (flag > 0) and nattrib != 1:
                    par=tuple([imaterial,flag,vel,vs,rho,qk,qmu,ani])
                elif flag < 0 and nattrib != 1:
                    if kind=='interface':
                        par=tuple([imaterial,flag,kind,name,flag_down,flag_up])
                    elif kind=='tomography':
                        par=tuple([imaterial,flag,kind,name])
                elif flag==0 or nattrib == 1:
                    par=tuple([imaterial,flag,name])
                material[block]=par
            elif ty == self.face:
                block_bc_flag.append(4)
                block_bc.append(block)
                bc[block]=4 #face has connectivity = 4
                if name == self.topo or block == 1001:
                    self.topography=block
                if self.freetxt in name:
                    self.free=block
            elif ty == 'SPHERE':
                pass
            else:
                # block elements differ from HEX8/QUAD4/SHELL4
                print '****************************************'
                print 'block not properly defined:'
                print '  name:',name
                print '  type:',type
                print
                print 'please check your block definitions!'
                print
                print 'only supported types are:'
                print '  HEX/HEX8  for volumes'
                print '  QUAD4 for surface'
                print '  SHELL4 for surface'
                print '****************************************'
                continue
                return None, None,None,None,None,None,None,None
        nsets=cubit.get_nodeset_id_list()
        if len(nsets) == 0: self.receivers=None
        for nset in nsets:
            name=cubit.get_exodus_entity_name('nodeset',nset)
            if name == self.rec:
                self.receivers=nset
            else:
                print 'nodeset '+name+' not defined'
                self.receivers=None

        try:
            self.block_mat=block_mat
            self.block_flag=block_flag
            self.block_bc=block_bc
            self.block_bc_flag=block_bc_flag
            self.material=material
            self.bc=bc
            print 'HEX Blocks:'
            for m,f in zip(self.block_mat,self.block_flag):
                print 'block ',m,'material flag ',f
            print 'Absorbing Boundary Conditions:'
            for m,f in zip(self.block_bc,self.block_bc_flag):
                print  'bc ',m,'bc flag ',f
            print 'Topography (free surface)'
            print self.topography
            print 'Free surface'
            print self.free
        except:
            print '****************************************'
            print 'sorry, no blocks or blocks not properly defined'
            print block_mat
            print block_flag
            print block_bc
            print block_bc_flag
            print material
            print bc
            print '****************************************'
Exemplo n.º 20
0
    def get_block(self):
        ''' extract block information '''
        block_flag = []
        block_mat = []
        block_pml = []
        block_pmlflag = []
        ns_free = []
        ns_absorb = []
        material = []
        # number of blocks
        blocks = cubit.get_block_id_list()

        # go through blocks
        for block in blocks:
            name = cubit.get_exodus_entity_name('block', block)
            type = cubit.get_block_element_type(block)
            print block, name, blocks, type

            if type == self.tri:
                # check if elastic
                if name.find('elastic') >= 0:
                    print('found elastic block')
                    imat = 1

                    # get number of attributes
                    values = name.split(" ")
                    print values
                    flag = int(values[1])
                    vp = float(values[2])
                    vs = float(values[3])
                    rho = float(values[4])
                    qp = float(values[5])
                    qs = float(values[6])

                    block_flag.append(flag)
                    block_mat.append(block)
                    material.append([imat, vp, vs, rho, qp, qs])
                elif name.find('pml') >= 0:
                    ipml = 1
                    values = name.split(" ")
                    flag = int(values[1])
                    block_pmlflag.append(flag)
                    block_pml.append(block)
                else:
                    print('error, no correct material in block', block)

        ns = cubit.get_nodeset_id_list()
        for n in ns:
            name = cubit.get_exodus_entity_name('nodeset', n)
            if name.find('free') >= 0:
                print('found free surface nodes')
                ns_free.append(n)
            elif name.find('absorb') >= 0:
                print('found absorb surface nodes')
                ns_absorb.append(n)
            else:
                print('error in boundaries', n)

        print('BLOCKFLAG', block_flag)
        self.block_flag = block_flag
        self.block_mat = block_mat
        self.block_pml = block_pml
        self.block_pmlflag = block_pmlflag
        self.mat = material
        self.ns_free = ns_free
        self.ns_absorb = ns_absorb
Exemplo n.º 21
0
    def get_block(self):
        ''' extract block information '''
        block_flag=[]
        block_mat=[]
        block_pml=[]
        block_pmlflag=[]
        ns_free=[]
        ns_absorb=[]
        material=[]
        # number of blocks
        blocks=cubit.get_block_id_list()

        # go through blocks
        for block in blocks:
            name=cubit.get_exodus_entity_name('block',block)
            type=cubit.get_block_element_type(block)
            print block,name,blocks,type

            if type == self.tri:
                # check if elastic
                if name.find('elastic') >=0:
                    print('found elastic block')
                    imat=1
                
                    # get number of attributes
                    values=name.split(" ")
                    print values
                    flag=int(values[1])
                    vp=float(values[2])
                    vs=float(values[3])
                    rho=float(values[4])
                    qp=float(values[5])
                    qs=float(values[6])
                    pml=float(values[7])

                    block_flag.append(flag)
                    block_pmlflag.append(pml)
                    block_mat.append(block)
                    material.append([imat,vp,vs,rho,qp,qs])
                elif name.find('poro') >=0:
                    print('found poroelastic block')
                    self.poro=True
                    imat=2
                    
                    # get number of attributes
                    values=name.split(" ")
                    print values
                    flag=int(values[1])
                    typeid=float(values[2])
                    rhos=float(values[3])
                    lambdau=float(values[4])
                    my=float(values[5])
                    phi=float(values[6])
                    kappa=float(values[7])
                    b=float(values[8])
                    invT=float(values[9])
                    invN=float(values[10])
                    rho1=float(values[11])
                    S1=float(values[12])
                    K1=float(values[13])
                    ny1=float(values[14])
                    rho2=float(values[15])
                    S2=float(values[16])
                    K2=float(values[17])
                    ny2=float(values[18])
                    fitting_n=float(values[19])
                    fitting_chi=float(values[20])
                    Sr1=float(values[21])
                    Sr2=float(values[22])

                    block_flag.append(flag)
                    block_pmlflag.append(0)
                    block_mat.append(block)
                    material.append([imat,typeid,rhos,lambdau,my,phi,kappa,b,invT,invN,rho1,S1,K1,ny1,rho2,S2,K2,ny2,fitting_n,fitting_chi,Sr1,Sr2])
                elif name.find('pml') >=0:
                    ipml=1
                    values=name.split(" ")
                    flag=int(values[1])
                    block_pmlflag.append(flag)
                    block_pml.append(block)
                else:
                    print('error, no correct material in block',block)

        ns=cubit.get_nodeset_id_list()
        for n in ns:
            name=cubit.get_exodus_entity_name('nodeset',n)
            if name.find('free') >=0:
                print('found free surface nodes')
                ns_free.append(n)
            elif name.find('absorb') >=0:
                print('found absorb surface nodes')
                ns_absorb.append(n)
            elif name.find('vtk') >=0:
                pass
            else:
                print('error in boundaries',n)
            
        print('BLOCKFLAG',block_flag)
        self.block_flag=block_flag
        self.block_mat=block_mat
        self.block_pml=block_pml
        self.block_pmlflag=block_pmlflag
        self.mat=material
        self.ns_free=ns_free
        self.ns_absorb=ns_absorb
Exemplo n.º 22
0
def collect_new(cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1,cubfiles=False,ckbound_method1=False,ckbound_method2=False,merge_tolerance=None,curverefining=False,outfilename='totalmesh_merged',qlog=False,export2SPECFEM3D=False,listblock=None,listflag=None,outdir='.',add_sea=False,decimate=False,cpml=False,cpml_size=False,top_absorbing=False,hex27=False,save_cubfile=True,check_merging=False):
    #
    cubit.cmd('set info off')
    cubit.cmd('set echo off')
    cubit.cmd('set journal off')
    #cubit.cmd('set error off')
    version_cubit=get_cubit_version()
    
    if decimate:
        if version_cubit >= 14.0:
            raise VersionException('check cubit version, decimate capability has been tested only with cubit <= 12.2')
    
    if version_cubit <= 12.2:
        collecting_merging(cpuxmin,cpuxmax,cpuymin,cpuymax,cpux,cpuy,cubfiles=cubfiles,ckbound_method1=ckbound_method1,ckbound_method2=ckbound_method2,merge_tolerance=merge_tolerance,decimate=decimate)
    elif version_cubit >= 14:
        collecting_merging_new(cpuxmin,cpuxmax+1,cpuymin,cpuymax+1,cpux,cpuy,cubfiles=cubfiles,check_merging=check_merging)
    else:
        raise VersionException('check cubit version, parallel capability of geocubit is working with cubit/trelis 14+ (or cubit 12.2)')
    cubit.cmd('set info on')
    cubit.cmd('set echo on')
    cubit.cmd('set journal on')
    #cubit.cmd('set error on')
    #
    if curverefining:
        if version_cubit <= 12.2:
            block=1001 #topography
            refine_closecurve(block,curverefining,acis=True)
        else:
            raise VersionException('check cubit version, refine curve capability has been tested only with cubit <= 12.2')
        
    #
    #
    if add_sea:
        if version_cubit <= 12.2:
            block=1001
            add_sea_layer(block=block)
        else:
            raise VersionException('check cubit version, sea capability has been tested only with cubit <= 12.2')


    outdir2='/'.join(x for x in outfilename.split('/')[:-1])
    if outdir2 == '': 
        outdir2=outdir+'/'
    else:
        outdir2=outdir+'/'+outdir2+'/'    
    
    import os
    try:
        os.makedirs(outdir2)
    except OSError:
        pass
    
    cubit.cmd('compress all')
    command="export mesh '"+outdir2+outfilename+".e' block all overwrite xml '"+outdir2+outfilename+".xml'"
    cubit.cmd(command)
    f=open(outdir2+'blocks.dat','w')
    blocks=cubit.get_block_id_list()
    #
    for block in blocks:
        name=cubit.get_exodus_entity_name('block',block)
        element_count = cubit.get_exodus_element_count(block, "block")
        nattrib=cubit.get_block_attribute_count(block)
        attr=[cubit.get_block_attribute_value(block,x) for x in range(0,nattrib)]
        ty=cubit.get_block_element_type(block)
        f.write(str(block)+' ; '+name+' ; nattr '+str(nattrib)+' ; '+' '.join(str(x) for x in attr)+' ; '+ty+' '+str(element_count)+'\n')
    f.close()
    #
    #
    cubit.cmd('set info echo journ off')
    cmd='del group all'
    cubit.silent_cmd(cmd)
    cubit.cmd('set info echo journ on')
    #
    #
    print 'end meshing'
    #
    #
    if qlog:
        print '\n\nQUALITY CHECK.... ***************\n\n'
        import quality_log
        tq=open(outdir2+outfilename+'.quality','w')
        max_skewness,min_length=quality_log.quality_log(tq)
    #
    #
    #
    if export2SPECFEM3D:
        e2SEM(files=False,listblock=listblock,listflag=listflag,outdir=outdir,cpml=cpml,cpml_size=cpml_size,top_absorbing=top_absorbing,hex27=hex27)
    
    if save_cubfile:
        vol_blocks=[x for x in blocks if x <=1000]
        cubit.cmd("create mesh geometry block "+' '.join(str(x) for x in vol_blocks)+" feature_angle 135.0")
        command = "save as '"+outdir2+outfilename+".cub' overwrite"
        print command
        cubit.cmd(command)
Exemplo n.º 23
0
    def get_block(self):
        ''' extract block information '''
        block_flag = []
        block_mat = []
        block_free = []
        block_absorb = []
        block_pml = []
        material = []
        # number of blocks
        blocks = cubit.get_block_id_list()

        # go through blocks
        for block in blocks:
            name = cubit.get_exodus_entity_name('block', block)
            type = cubit.get_block_element_type(block)
            print block, name, blocks, type

            if type == self.tet:
                # check if elastic
                if name.find('elastic') >= 0:
                    print('found elastic block')
                    imat = 1
                else:
                    print('error, no correct material in block', block)

                # get number of attributes
                nattrib = cubit.get_block_attribute_count(block)
                if nattrib != 0:
                    flag = int(cubit.get_block_attribute_value(block, 0))
                    vp = cubit.get_block_attribute_value(block, 1)
                    vs = cubit.get_block_attribute_value(block, 2)
                    rho = cubit.get_block_attribute_value(block, 3)
                    qp = cubit.get_block_attribute_value(block, 4)
                    qs = cubit.get_block_attribute_value(block, 5)
                    pml = int(cubit.get_block_attribute_value(block, 6))
                else:
                    print('error no attributes in block', block)
                block_flag.append(flag)
                block_mat.append(block)
                block_pml.append(pml)
                material.append([imat, vp, vs, rho, qp, qs])
            elif type == self.tri:
                if name.find('free') >= 0:
                    print('found free surface')
                    block_free.append(block)
                elif name.find('absorb') >= 0:
                    print('found absorb surface')
                    block_absorb.append(block)
                else:
                    print('error in boundaries', block)

#        ns=cubit.get_nodeset_id_list()
#        for n in ns:
#            name=cubit.get_exodus_entity_name('nodeset',n)
#            if name.find('free') >=0:
#                print('found free surface nodes')
#                ns_free.append(n)
#            elif name.find('absorb') >=0:
#                print('found absorb surface nodes')
#                ns_absorb.append(n)
#            else:
#                print('error in boundaries',n)

        print('BLOCKFLAG', block_flag)
        self.block_flag = block_flag
        self.block_mat = block_mat
        self.mat = material
        self.block_free = block_free
        self.block_absorb = block_absorb
        self.block_pml = block_pml
Exemplo n.º 24
0
 def block_definition(self):
     block_flag=[]
     block_mat=[]
     block_bc=[]
     block_bc_flag=[]
     material={}
     bc={}
     blocks=cubit.get_block_id_list()
     for block in blocks:
         name=cubit.get_exodus_entity_name('block',block)
         ty=cubit.get_block_element_type(block)
         #print block,blocks,ty,self.hex,self.face
         if self.hex in ty:
             nattrib=cubit.get_block_attribute_count(block)
             flag=None
             vel=None
             vs=None
             rho=None
             q=0
             ani=0
             # material domain id
             if "acoustic" in name :
               imaterial = 1
             elif "elastic"  in name:
               imaterial = 2
             elif "poroelastic"  in name:
               imaterial = 3
             else :
               imaterial = 0
             #
             if nattrib > 1:
                 # material flag:
                 #   positive => material properties,
                 #   negative => interface/tomography domain
                 flag=int(cubit.get_block_attribute_value(block,0))
                 if flag > 0 and nattrib >= 2:
                     vel=cubit.get_block_attribute_value(block,1)
                     if nattrib >= 3:
                         vs=cubit.get_block_attribute_value(block,2)
                         if nattrib >= 4:
                             rho=cubit.get_block_attribute_value(block,3)
                             if nattrib >= 5:
                                 q=cubit.get_block_attribute_value(block,4)
                                 # for q to be valid: it must be positive
                                 if q < 0 :
                                   print 'error, q value invalid:', q
                                   break                                                   
                                 if nattrib == 6:
                                     ani=cubit.get_block_attribute_value(block,5)
                 elif flag < 0:
                     vel=name
                     attrib=cubit.get_block_attribute_value(block,1)
                     if attrib == 1: 
                         kind='interface'
                         flag_down=cubit.get_block_attribute_value(block,2)
                         flag_up=cubit.get_block_attribute_value(block,3)
                     elif attrib == 2:
                         kind='tomography'
             elif  nattrib == 1:
                 flag=cubit.get_block_attribute_value(block,0)
                 print 'only 1 attribute ', name,block,flag
                 vel,vs,rho,q,ani=(0,0,0,0,0)
             else:
                 flag=block
                 vel,vs,rho,q,ani=(name,0,0,0,0)
             block_flag.append(int(flag))
             block_mat.append(block)
             if flag > 0 and nattrib != 1:
                 par=tuple([imaterial,flag,vel,vs,rho,q,ani])
             elif flag < 0 and nattrib != 1:
                 if kind=='interface':
                     par=tuple([imaterial,flag,kind,name,flag_down,flag_up])
                 elif kind=='tomography':
                     par=tuple([imaterial,flag,kind,name])
             elif flag==0 or nattrib == 1:
                 par=tuple([imaterial,flag,name])
             material[block]=par
         elif ty == self.face: #Stacey condition, we need hex here for pml
             block_bc_flag.append(4)
             block_bc.append(block)
             bc[block]=4 #face has connectivity = 4
             if name == self.topo or block == 1001: topography_face=block
         elif ty == 'SPHERE':
             pass
         else:
             # block elements differ from HEX8/QUAD4/SHELL4
             print '****************************************'
             print 'block not properly defined:'
             print '  name:',name
             print '  type:',type
             print
             print 'please check your block definitions!'
             print
             print 'only supported types are:'
             print '  HEX/HEX8  for volumes'
             print '  QUAD4 for surface'
             print '  SHELL4 for surface'
             print '****************************************'
             continue
             return None, None,None,None,None,None,None,None
     nsets=cubit.get_nodeset_id_list()
     if len(nsets) == 0: self.receivers=None
     for nset in nsets:
         name=cubit.get_exodus_entity_name('nodeset',nset)
         if name == self.rec:
             self.receivers=nset
         else:
             print 'nodeset '+name+' not defined'
             self.receivers=None
     print block_mat
     print block_flag
     print block_bc
     print block_bc_flag
     print material
     print bc
     print topography_face
     #
     try:
         self.block_mat=block_mat
         self.block_flag=block_flag
         self.block_bc=block_bc
         self.block_bc_flag=block_bc_flag
         self.material=material
         self.bc=bc
         self.topography=topography_face
     except:
         print '****************************************'
         print 'sorry, no blocks or blocks not properly defined'
         print block_mat
         print block_flag
         print block_bc
         print block_bc_flag
         print material
         print bc
         print topography
         print '****************************************'
Exemplo n.º 25
0
def build_block(vol_list, name, id_0=1, top_surf=None, optionsea=False):
    #
    from sets import Set

    if optionsea:
        sea = optionsea["sea"]
        seaup = optionsea["seaup"]
        sealevel = optionsea["sealevel"]
        seathres = optionsea["seathres"]
    else:
        sea = False
        seaup = False
        sealevel = False
        seathres = False

    #
    block_list = cubit.get_block_id_list()
    if len(block_list) > 0:
        id_block = max(max(block_list), 2) + id_0
    else:
        id_block = 2 + id_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))
        if sea and v == vol_list[-1]:
            cubit.cmd("set duplicate block elements off")
            tsurf_string = " ".join(str(x) for x in top_surf)
            # sea
            command = (
                "block " + str(id_block) + " hex in node in surf " + tsurf_string + " with Z_coord < " + str(seathres)
            )
            cubit.cmd(command)
            command = "block " + str(id_block) + " name 'sea" + n + "'"
            cubit.cmd(command)
            if not seaup:
                id_block += 1
                command = (
                    "block "
                    + str(id_block)
                    + " hex in node in surf "
                    + tsurf_string
                    + " with (Z_coord > "
                    + str(seathres)
                    + " and Z_coord < "
                    + str(sealevel)
                )
                cubit.cmd(command)
                command = "block " + str(id_block) + " name 'shwater" + n + "'"
                cubit.cmd(command)
            id_block += 1
            command = (
                "block " + str(id_block) + " hex in node in surf " + tsurf_string + " with Z_coord >= " + str(sealevel)
            )
            cubit.cmd(command)
            command = "block " + str(id_block) + " name 'continent" + n + "'"
            cubit.cmd(command)
        else:
            command = "block " + str(id_block) + " hex in vol " + str(v) + " except hex in vol " + str(list(v_other))
            print command
            command = command.replace("[", " ").replace("]", " ")
            cubit.cmd(command)
            command = "block " + str(id_block) + " name '" + n + "'"
            cubit.cmd(command)
    def block_definition(self):
        block_flag = []
        block_mat = []
        block_bc = []
        block_bc_flag = []
        material = {}
        bc = {}
        blocks = cubit.get_block_id_list()
        for block in blocks:
            name = cubit.get_exodus_entity_name('block', block)
            type = cubit.get_block_element_type(block)
            print block, name, blocks, type, self.hex, self.face
            # block has hexahedral elements (HEX8)
            if type == self.hex:
                flag = None
                vel = None
                vs = None
                rho = None
                q = 0
                ani = 0
                # material domain id
                if name.find("acoustic") >= 0:
                    imaterial = 1
                elif name.find("elastic") >= 0:
                    imaterial = 2
                elif name.find("poroelastic") >= 0:
                    imaterial = 3
                else:
                    imaterial = 0
                    print "block: ", name
                    print "  could not find appropriate material for this block..."
                    print ""
                    break

                nattrib = cubit.get_block_attribute_count(block)
                if nattrib != 0:
                    # material flag:
                    #   positive => material properties,
                    #   negative => interface/tomography domain
                    flag = int(cubit.get_block_attribute_value(block, 0))
                    if flag > 0 and nattrib >= 2:
                        # vp
                        vel = cubit.get_block_attribute_value(block, 1)
                        if nattrib >= 3:
                            # vs
                            vs = cubit.get_block_attribute_value(block, 2)
                            if nattrib >= 4:
                                #density
                                rho = cubit.get_block_attribute_value(block, 3)
                                if nattrib >= 5:
                                    #Q_kappa
                                    qkappa = cubit.get_block_attribute_value(
                                        block, 4)
                                    # for q to be valid: it must be positive
                                    if qkappa < 0:
                                        print 'error, qkappa value invalid:', qkappa
                                        break
                                    if nattrib >= 6:
                                        #Q_mu
                                        qmu = cubit.get_block_attribute_value(
                                            block, 5)
                                        # for q to be valid: it must be positive
                                        if qmu < 0:
                                            print 'error, qmu value invalid:', qmu
                                            break
                                        if nattrib == 7:
                                            #anisotropy_flag
                                            ani = cubit.get_block_attribute_value(
                                                block, 5)
                    elif flag < 0:
                        # velocity model
                        vel = name
                        attrib = cubit.get_block_attribute_value(block, 1)
                        if attrib == 1:
                            kind = 'interface'
                            flag_down = cubit.get_block_attribute_value(
                                block, 2)
                            flag_up = cubit.get_block_attribute_value(block, 3)
                        elif attrib == 2:
                            kind = 'tomography'
                else:
                    flag = block
                    vel, vs, rho, qkappa, qmu, ani = (name, 0, 0, 0, 0, 0)
                block_flag.append(int(flag))
                block_mat.append(block)
                if flag > 0:
                    par = tuple(
                        [imaterial, flag, vel, vs, rho, qkappa, qmu, ani])
                elif flag < 0:
                    if kind == 'interface':
                        par = tuple(
                            [imaterial, flag, kind, name, flag_down, flag_up])
                    elif kind == 'tomography':
                        par = tuple([imaterial, flag, kind, name])
                elif flag == 0:
                    par = tuple([imaterial, flag, name])
                material[block] = par
            elif (type == self.face) or (type == self.face2):
                # block has surface elements (QUAD4 or SHELL4)
                block_bc_flag.append(4)
                block_bc.append(block)
                bc[block] = 4  #face has connectivity = 4
                if name == self.topo: topography_face = block
            else:
                # block elements differ from HEX8/QUAD4/SHELL4
                print '****************************************'
                print 'block not properly defined:'
                print '  name:', name
                print '  type:', type
                print
                print 'please check your block definitions!'
                print
                print 'only supported types are:'
                print '  HEX8  for volumes'
                print '  QUAD4 for surface'
                print '  SHELL4 for surface'
                print '****************************************'
                continue

        nsets = cubit.get_nodeset_id_list()
        if len(nsets) == 0: self.receivers = None
        for nset in nsets:
            name = cubit.get_exodus_entity_name('nodeset', nset)
            if name == self.rec:
                self.receivers = nset
            else:
                print 'nodeset ' + name + ' not defined'
                self.receivers = None
        try:
            self.block_mat = block_mat
            self.block_flag = block_flag
            self.block_bc = block_bc
            self.block_bc_flag = block_bc_flag
            self.material = material
            self.bc = bc
            self.topography = topography_face
        except:
            print '****************************************'
            print 'sorry, no blocks or blocks not properly defined'
            print block_mat
            print block_flag
            print block_bc
            print block_bc_flag
            print material
            print bc
            print topography
            print '****************************************'
Exemplo n.º 27
0
def savemesh(mpiflag, iproc=0, filename=None):
    import start as start
    cfg = start.start_cfg(filename=filename)
    mpiflag, iproc, numproc, mpi = start.start_mpi()

    def runsave(meshfile, 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 + '/' + meshfile + '.cub' + '" overwrite'
        cubit.cmd(cubitcommand)
        ner2 = cubit.get_error_count()
        if ner == ner2:
            cubitcommand = 'export mesh "' + cfg.output_dir + '/' + meshfile + '.e' + '" dimension 3 block all overwrite'
            cubit.cmd(cubitcommand)
            ner2 = cubit.get_error_count()
        if ner == ner2:
            flag = 1
        return flag

    meshfile = 'mesh_vol_' + str(iproc)

    flagsaved = 0
    infosave = (iproc, flagsaved)

    mpi.barrier()
    total_saved = mpi.allgather(flagsaved)
    if isinstance(total_saved, int): total_saved = [total_saved]

    ind = 0
    saving = True
    while saving:
        if len(total_saved) != sum(total_saved):
            #
            if not flagsaved:
                flagsaved = runsave(meshfile, iproc, filename=filename)
                if flagsaved:
                    infosave = (iproc, flagsaved)
                    if numproc > 1:
                        f = open('mesh_saved' + str(iproc), 'w')
                        f.close()
            mpi.barrier()
            total_saved = mpi.allgather(flagsaved)
            if isinstance(total_saved, int): total_saved = [total_saved]
            ind = ind + 1
        else:
            saving = False
        if ind > len(total_saved) + 10: saving = False
        print sum(total_saved), '/', len(total_saved), ' saved'

    info_total_saved = mpi.allgather(infosave)
    if isinstance(info_total_saved, int): info_total_saved = [info_total_saved]

    if iproc == 0:
        f = open('mesh_saving.log', 'w')
        f.write('\n'.join(str(x) for x in info_total_saved))
        f.close()

    f = open(cfg.output_dir + '/' + 'blocks_' + str(iproc).zfill(5), 'w')
    blocks = cubit.get_block_id_list()

    for block in blocks:
        name = cubit.get_exodus_entity_name('block', block)
        element_count = cubit.get_exodus_element_count(block, "block")
        nattrib = cubit.get_block_attribute_count(block)
        attr = [
            cubit.get_block_attribute_value(block, x)
            for x in range(0, nattrib)
        ]
        ty = cubit.get_block_element_type(block)
        f.write(
            str(block) + ' ; ' + name + ' ; nattr ' + str(nattrib) + ' ; ' +
            ' '.join(str(x) for x in attr) + ' ; ' + ty + ' ' +
            str(element_count) + '\n')
    f.close()

    import quality_log
    f = open(cfg.output_dir + '/' + 'quality_' + str(iproc).zfill(5), 'w')
    max_skewness, min_length = quality_log.quality_log(f)
    f.close()

    count_hex = [cubit.get_hex_count()]
    count_node = [cubit.get_node_count()]
    max_skew = [(iproc, max_skewness)]
    min_l = [(iproc, min_length)]

    mpi.barrier()
    total_min_l = mpi.gather(min_l)
    total_hex = mpi.gather(count_hex)
    total_node = mpi.gather(count_node)
    total_max_skew = mpi.gather(max_skew)

    mpi.barrier()
    if iproc == 0:
        min_total_min_l = min([ms[1] for ms in total_min_l])
        max_total_max_skew = max([ms[1] for ms in total_max_skew])
        sum_total_node = sum(total_node)
        sum_total_hex = sum(total_hex)

        totstat_file = open(cfg.output_dir + '/totstat.log', 'w')
        text = 'hex total number,node total number,max skew, min length\n'
        totstat_file.write(text)

        text = str(sum_total_hex) + ' , ' + str(sum_total_node) + ' , ' + str(
            max_total_max_skew) + ' , ' + str(min_total_min_l) + '\n'
        totstat_file.write(text)

        totstat_file.write(str(total_max_skew))
        totstat_file.close()

    print 'meshing process end... proc ', iproc
    def getstats(self):
        ''' Get statistics for differend blocks in the hexmesh '''
    ############################## READ BLOCKS ######################
        try:
            blocks=cubit.get_block_id_list()
        except:
            print('no blocks defined')

        nblocks=len(blocks)
        print('Found ',nblocks,' Blocks')
        # lists of details of all elastic blocks. For each elastic block, append respective values
        name=[]
        typ=[]
        nattrib=[]
        vp=[]
        vs=[]
        rho=[]
        minEdge=[]
        maxEdge=[]
        minEdgeMesh = []
        maxEdgeMesh = []
        # k: counter of all elastic blocks
        k=0
        for block in blocks:
            minEdgeMeshTmp = []
            maxEdgeMeshTmp = []
            blockname=cubit.get_exodus_entity_name('block',block)
            # only apply stats to elastic blocks
            if blockname.find("elastic") >= 0:
                # NOW APPEND VALUES OF THIS ELASTIC BLOCK TO LISTS (defined as empty above)
                name.append(blockname)
                typ.append(cubit.get_block_element_type(block))
                # attribute count
                nattrib.append(cubit.get_block_attribute_count(block))
                # vp
                vp.append(cubit.get_block_attribute_value(block,1))
                # vs
                vs.append(cubit.get_block_attribute_value(block,2))
                # rho
                rho.append(cubit.get_block_attribute_value(block,3))
                hexes=cubit.get_block_hexes(block)
                print(block, k,'name: ',name[k],'#hexes:',len(hexes),'type: ',typ[k],'attribute count: ',nattrib[k],'vp: ',vp[k],'vs: ',vs[k],'rho: ',rho[k])
                
                # minimum/maximum edgelength search for this elastic block
                # initiate  with very large minEdge and very small maxEdge
                minEdge.append(1e9)
                maxEdge.append(1e-9)
                # now search
                for hexa in hexes:
                    nodes=cubit.get_connectivity('Hex',hexa)
                    # get coordinates of nodes of this hexahedron
                    node_coords=[]
                    for node in nodes:
                        node_coords.append(cubit.get_nodal_coordinates(node))

                    minv=self.minEdgeHex(node_coords)
                    minEdgeMeshTmp.append(minv)
                    maxv=self.maxEdgeHex(node_coords)
                    maxEdgeMeshTmp.append(maxv)

                    # is minimum edgelength of this this element smaller than minimum edgelength found before?
                    if minv < minEdge[k]:
                        minEdge[k]=minv

                    # is maximum edgelength of this this element larger than maximum edgelength found before?
                    if maxv > maxEdge[k]:
                        maxEdge[k]=maxv

                minEdgeMesh.append(minEdgeMeshTmp)
                maxEdgeMesh.append(maxEdgeMeshTmp)
                # end of processing of this elastic block. incremet counter
                k=k+1
            # if not "elastic" in this blockname
            else:
                print(blockname, '--no elastic')

        # now calculate maximum frequency for which the mesh is stable
        # and maximal dt

        # first do that for each block
        fmax=[]
        dtmax_05=[]
        for i in range(len(name)):
            fmax.append(self.calcMaxFreq(maxEdge[i],vs[i]))
            dtmax_05.append(self.calcMaxDt(minEdge[i],vp[i],cn=0.5))
            min_dx = minEdge[i]*0.1727
            max_dx = maxEdge[i]*0.3272*sqrt(3.)
            print('Block ', name[i], ' min dx: ',min_dx, ' max dx: ',max_dx, 'max frequency: ',fmax[i],
                  ' maximal dt (C=0.5):',dtmax_05[i])
            vals,bin_edges = histogram(minEdgeMesh[i],10)
            nhexa = sum(vals)
            print('   '+str(nhexa)+' HEXAS IN THIS BLOCK')
            print('   histogram of minimum edge length of hexa of this block:')
            for j,val in enumerate(vals):
                print('       %6.3f %% of hexas have minimum edgelength between %3.3f and %3.3f  ->   dt (C=0.5) is %8.3e'%(100.*val/float(nhexa),bin_edges[j],bin_edges[j+1],self.calcMaxDt(bin_edges[j],vp[i],cn=0.5)))
            vals,bin_edges = histogram(maxEdgeMesh[i],10)
            nhexa = sum(vals)
            print('   '+str(nhexa)+' HEXAS IN THIS BLOCK')
            print('   histogram of maximum edge length of hexa of this block:')
            for j,val in enumerate(vals):
                print('       %6.3f %% of hexas have maximum edgelength between %3.3f and %3.3f  ->   fmax (5 GLL points per wavelength) is %8.3e'%(100.*val/float(nhexa),bin_edges[j],bin_edges[j+1],self.calcMaxFreq(bin_edges[j+1],vs[i])))
        # now compare the values for all the blocks
        dtm_05=sorted(dtmax_05)
        print('The minimum over all blocks of the respective maximal dt for C=0.5 is: ',dtm_05[0])
        fmax_min=sorted(fmax)
        print('The minimum over all blocks of the respective maximal frequency is: ',fmax_min[0])
Exemplo n.º 29
0
def refine_closecurve(block=1001,closed_filenames=None,acis=True):
    from utilities import load_curves
    from boundary_definition import build_block_side,define_surf
    from mesh_volume import refine_inside_curve
    #
    #
    curves=[]
    if not isinstance(closed_filenames,list): closed_filenames=[closed_filenames]
    for f in closed_filenames:
        print f
        if acis: 
            curves=curves+load_curves(f)
    print curves
    blist=list(cubit.get_block_id_list())
    try:
        blist.remove(1001)
    except:
        pass
    try:
        blist.remove(1002)
    except:
        pass
    try:
        blist.remove(1003)
    except:
        pass        
    try:
        blist.remove(1004)    
    except:                             
        pass             
    try:
        blist.remove(1005)
    except:
        pass
    try:
        blist.remove(1006)
    except:
        pass
    id_top=max(blist)
    cmd='group "coi" add node in hex in block '+str(id_top)
    cubit.cmd(cmd)
    #
    id_inside_arc=None
    for c in map(int,curves[0].split()):   #curves is a list of one string
        c1001 = cubit.get_exodus_element_count(1001, "block")
        c1002 = cubit.get_exodus_element_count(1002, "block")
        c1003 = cubit.get_exodus_element_count(1003, "block")
        c1004 = cubit.get_exodus_element_count(1004, "block")
        c1005 = cubit.get_exodus_element_count(1005, "block")
        c1006 = cubit.get_exodus_element_count(1006, "block")
        #
        refine_inside_curve(c,ntimes=1,depth=1,block=block,surface=False)
        blist=list(cubit.get_block_id_list())
        cmd='create mesh geometry hex all except hex in block all feature_angle 135'
        cubit.cmd(cmd)
        blist_after=list(cubit.get_block_id_list())
        [blist_after.remove(x) for x in blist]
        id_inside=max(blist_after)
        cmd='group "coi" add node in hex in block '+str(id_inside)
        cubit.cmd(cmd)
        if id_inside_arc: 
                cmd='del block '+str(id_inside-1)
                cubit.cmd(cmd)
        cmd='block '+str(id_inside)+' name "refined"'
        cubit.cmd(cmd)
        id_inside_arc=id_inside                                            
        #
        _,_,_,_,_,top_surf,bottom_surf,surf_xmin,surf_ymin,surf_xmax,surf_ymax=define_surf()
        #
        c1001_after = cubit.get_exodus_element_count(1001, "block")
        c1002_after = cubit.get_exodus_element_count(1002, "block")
        c1003_after = cubit.get_exodus_element_count(1003, "block")
        c1004_after = cubit.get_exodus_element_count(1004, "block")
        c1005_after = cubit.get_exodus_element_count(1005, "block")
        c1006_after = cubit.get_exodus_element_count(1006, "block")
        entity='face'
        if c1001_after != c1001:
            refname=entity+'_topo'
            build_block_side(top_surf,refname,obj=entity,id_0=1001)
        #
        if c1002_after != c1002:
            refname=entity+'_bottom'
            build_block_side(bottom_surf,refname,obj=entity,id_0=1002)
        #
        if c1003_after != c1003:
            refname=entity+'_abs_xmin'
            build_block_side(surf_xmin,refname,obj=entity,id_0=1003)
        #                                                              
        if c1004_after != c1004:
            refname=entity+'_abs_ymin'
            build_block_side(surf_ymin,refname,obj=entity,id_0=1004)
        #                                                              
        if c1005_after != c1005:  
            refname=entity+'_abs_xmax'                                     
            build_block_side(surf_xmax,refname,obj=entity,id_0=1005)
        #
        if c1006_after != c1006:    
            refname=entity+'_abs_ymax'                                   
            build_block_side(surf_ymax,refname,obj=entity,id_0=1006)
        #
        cmd='disassociate mesh from volume all'
        cubit.cmd(cmd)
        cmd='group "coi" add node in face in block 1001 1002 1003 1004 1005 1006'
        cubit.cmd(cmd)
        cubit.cmd('del vol all')
        cubit.cmd('group "removedouble" add hex all except hex in block all')
        cubit.cmd('delete hex in removedouble')
        cubit.cmd('delet group removedouble')
        cmd='equivalence node in group coi tolerance 20'
        cubit.cmd(cmd)
    cmd='equivalence node all tolerance 10'
    cubit.cmd(cmd)
    cubit.cmd('del curve '+' '.join(str(x) for x in curves) )
    def getstats(self):
        ''' Get statistics for differend blocks in the hexmesh '''
        ############################## READ BLOCKS ######################
        try:
            blocks = cubit.get_block_id_list()
        except:
            print('no blocks defined')

        nblocks = len(blocks)
        print('Found ', nblocks, ' Blocks')
        # lists of details of all elastic blocks. For each elastic block, append respective values
        name = []
        typ = []
        nattrib = []
        vp = []
        vs = []
        rho = []
        minEdge = []
        maxEdge = []
        minEdgeMesh = []
        maxEdgeMesh = []
        # k: counter of all elastic blocks
        k = 0
        for block in blocks:
            minEdgeMeshTmp = []
            maxEdgeMeshTmp = []
            blockname = cubit.get_exodus_entity_name('block', block)
            # only apply stats to elastic blocks
            if blockname.find("elastic") >= 0:
                # NOW APPEND VALUES OF THIS ELASTIC BLOCK TO LISTS (defined as empty above)
                name.append(blockname)
                typ.append(cubit.get_block_element_type(block))
                # attribute count
                nattrib.append(cubit.get_block_attribute_count(block))
                # vp
                vp.append(cubit.get_block_attribute_value(block, 1))
                # vs
                vs.append(cubit.get_block_attribute_value(block, 2))
                # rho
                rho.append(cubit.get_block_attribute_value(block, 3))
                hexes = cubit.get_block_hexes(block)
                print(block, k, 'name: ', name[k], '#hexes:', len(hexes),
                      'type: ', typ[k], 'attribute count: ', nattrib[k],
                      'vp: ', vp[k], 'vs: ', vs[k], 'rho: ', rho[k])

                # minimum/maximum edgelength search for this elastic block
                # initiate  with very large minEdge and very small maxEdge
                minEdge.append(1e9)
                maxEdge.append(1e-9)
                # now search
                for hexa in hexes:
                    nodes = cubit.get_connectivity('Hex', hexa)
                    # get coordinates of nodes of this hexahedron
                    node_coords = []
                    for node in nodes:
                        node_coords.append(cubit.get_nodal_coordinates(node))

                    minv = self.minEdgeHex(node_coords)
                    minEdgeMeshTmp.append(minv)
                    maxv = self.maxEdgeHex(node_coords)
                    maxEdgeMeshTmp.append(maxv)

                    # is minimum edgelength of this this element smaller than minimum edgelength found before?
                    if minv < minEdge[k]:
                        minEdge[k] = minv

                    # is maximum edgelength of this this element larger than maximum edgelength found before?
                    if maxv > maxEdge[k]:
                        maxEdge[k] = maxv

                minEdgeMesh.append(minEdgeMeshTmp)
                maxEdgeMesh.append(maxEdgeMeshTmp)
                # end of processing of this elastic block. incremet counter
                k = k + 1
            # if not "elastic" in this blockname
            else:
                print(blockname, '--no elastic')

        # now calculate maximum frequency for which the mesh is stable
        # and maximal dt

        # first do that for each block
        fmax = []
        dtmax_05 = []
        for i in range(len(name)):
            fmax.append(self.calcMaxFreq(maxEdge[i], vs[i]))
            dtmax_05.append(self.calcMaxDt(minEdge[i], vp[i], cn=0.5))
            min_dx = minEdge[i] * 0.1727
            max_dx = maxEdge[i] * 0.3272 * sqrt(3.)
            print('Block ', name[i], ' min dx: ', min_dx, ' max dx: ', max_dx,
                  'max frequency: ', fmax[i], ' maximal dt (C=0.5):',
                  dtmax_05[i])
            vals, bin_edges = histogram(minEdgeMesh[i], 10)
            nhexa = sum(vals)
            print('   ' + str(nhexa) + ' HEXAS IN THIS BLOCK')
            print('   histogram of minimum edge length of hexa of this block:')
            for j, val in enumerate(vals):
                print(
                    '       %6.3f %% of hexas have minimum edgelength between %3.3f and %3.3f  ->   dt (C=0.5) is %8.3e'
                    %
                    (100. * val / float(nhexa), bin_edges[j], bin_edges[j + 1],
                     self.calcMaxDt(bin_edges[j], vp[i], cn=0.5)))
            vals, bin_edges = histogram(maxEdgeMesh[i], 10)
            nhexa = sum(vals)
            print('   ' + str(nhexa) + ' HEXAS IN THIS BLOCK')
            print('   histogram of maximum edge length of hexa of this block:')
            for j, val in enumerate(vals):
                print(
                    '       %6.3f %% of hexas have maximum edgelength between %3.3f and %3.3f  ->   fmax (5 GLL points per wavelength) is %8.3e'
                    %
                    (100. * val / float(nhexa), bin_edges[j], bin_edges[j + 1],
                     self.calcMaxFreq(bin_edges[j + 1], vs[i])))
        # now compare the values for all the blocks
        dtm_05 = sorted(dtmax_05)
        print(
            'The minimum over all blocks of the respective maximal dt for C=0.5 is: ',
            dtm_05[0])
        fmax_min = sorted(fmax)
        print(
            'The minimum over all blocks of the respective maximal frequency is: ',
            fmax_min[0])
Exemplo n.º 31
0
    def block_definition(self):
        block_flag = []
        block_mat = []
        block_bc = []
        block_bc_flag = []
        material = {}
        bc = {}
        blocks = cubit.get_block_id_list()
        for block in blocks:
            name = cubit.get_exodus_entity_name("block", block)
            type = cubit.get_block_element_type(block)
            print block, name, blocks, type, self.hex, self.face
            # block has hexahedral elements (HEX8)
            if type == self.hex:
                flag = None
                vel = None
                vs = None
                rho = None
                q = 0
                ani = 0
                # material domain id
                if name.find("acoustic") >= 0:
                    imaterial = 1
                elif name.find("elastic") >= 0:
                    imaterial = 2
                elif name.find("poroelastic") >= 0:
                    imaterial = 3
                else:
                    imaterial = 0
                    print "block: ", name
                    print "  could not find appropriate material for this block..."
                    print ""
                    break

                nattrib = cubit.get_block_attribute_count(block)
                if nattrib != 0:
                    # material flag:
                    #   positive => material properties,
                    #   negative => interface/tomography domain
                    flag = int(cubit.get_block_attribute_value(block, 0))
                    if flag > 0 and nattrib >= 2:
                        # vp
                        vel = cubit.get_block_attribute_value(block, 1)
                        if nattrib >= 3:
                            # vs
                            vs = cubit.get_block_attribute_value(block, 2)
                            if nattrib >= 4:
                                # density
                                rho = cubit.get_block_attribute_value(block, 3)
                                if nattrib >= 5:
                                    # Q_mu
                                    q = cubit.get_block_attribute_value(block, 4)
                                    # for q to be valid: it must be positive
                                    if q < 0:
                                        print "error, q value invalid:", q
                                        break
                                    if nattrib == 6:
                                        # only 6 parameters given (skipping Q_kappa ), old format style
                                        # Q_kappa is 10 times stronger than Q_mu
                                        q2 = q * 10
                                        # last entry is anisotropic flag
                                        ani = cubit.get_block_attribute_value(block, 5)
                                    elif nattrib > 6:
                                        # Q_kappa
                                        q2 = cubit.get_block_attribute_value(block, 5)
                                        # for q to be valid: it must be positive
                                        if q2 < 0:
                                            print "error, q value invalid:", q2
                                            break
                                        if nattrib == 7:
                                            # anisotropy_flag
                                            ani = cubit.get_block_attribute_value(block, 6)
                    elif flag < 0:
                        # velocity model
                        vel = name
                        attrib = cubit.get_block_attribute_value(block, 1)
                        if attrib == 1:
                            kind = "interface"
                            flag_down = cubit.get_block_attribute_value(block, 2)
                            flag_up = cubit.get_block_attribute_value(block, 3)
                        elif attrib == 2:
                            kind = "tomography"
                else:
                    flag = block
                    vel, vs, rho, q, q2, ani = (name, 0, 0, 0, 0, 0)
                block_flag.append(int(flag))
                block_mat.append(block)
                if flag > 0:
                    par = tuple([imaterial, flag, vel, vs, rho, q, q2, ani])
                elif flag < 0:
                    if kind == "interface":
                        par = tuple([imaterial, flag, kind, name, flag_down, flag_up])
                    elif kind == "tomography":
                        par = tuple([imaterial, flag, kind, name])
                elif flag == 0:
                    par = tuple([imaterial, flag, name])
                material[block] = par
            elif (type == self.face) or (type == self.face2):
                # block has surface elements (QUAD4 or SHELL4)
                block_bc_flag.append(4)
                block_bc.append(block)
                bc[block] = 4  # face has connectivity = 4
                if name == self.topo:
                    topography_face = block
            else:
                # block elements differ from HEX8/QUAD4/SHELL4
                print "****************************************"
                print "block not properly defined:"
                print "  name:", name
                print "  type:", type
                print
                print "please check your block definitions!"
                print
                print "only supported types are:"
                print "  HEX8  for volumes"
                print "  QUAD4 for surface"
                print "  SHELL4 for surface"
                print "****************************************"
                continue

        nsets = cubit.get_nodeset_id_list()
        if len(nsets) == 0:
            self.receivers = None
        for nset in nsets:
            name = cubit.get_exodus_entity_name("nodeset", nset)
            if name == self.rec:
                self.receivers = nset
            else:
                print "nodeset " + name + " not defined"
                self.receivers = None
        try:
            self.block_mat = block_mat
            self.block_flag = block_flag
            self.block_bc = block_bc
            self.block_bc_flag = block_bc_flag
            self.material = material
            self.bc = bc
            self.topography = topography_face
        except:
            print "****************************************"
            print "sorry, no blocks or blocks not properly defined"
            print block_mat
            print block_flag
            print block_bc
            print block_bc_flag
            print material
            print bc
            print topography
            print "****************************************"
Exemplo n.º 32
0
 def block_definition(self):
     """ Import blocks features from Cubit """ 
     block_flag = [] # Will contain material id (1 if fluid 2 if solid)
     block_mat = [] # Will contain face block ids
     block_bc = [] # Will contain edge block ids
     block_bc_flag = [] # Will contain edge id -> 2
     abs_boun = [-1] * self.nabs # total 4 sides of absorbing boundaries (index 0 : bottom, index 1 : right, index 2 : top, index 3 : left)
     #pml_boun = [-1] * 6 # To store pml layers id (for each pml layer : x_acoust, z_acoust, xz_acoust, x_elast, z_elast, xz_elast)
     pml_boun = [[] for _ in range(6)] # To store the block id corresponding to pml layers id (arbitrary number of blocks for each pml layer : x_acoust, z_acoust, xz_acoust, x_elast, z_elast, xz_elast)
     material = {} # Will contain each material name and their properties
     bc = {} # Will contains each boundary name and their connectivity -> 2
     blocks = cubit.get_block_id_list() # Load the blocks list
     for block in blocks: # Loop on the blocks
         name = cubit.get_exodus_entity_name('block',block) # Contains the name of the blocks
         ty = cubit.get_block_element_type(block) # Contains the block element type (QUAD4...)
         if ty == self.face: # If we are dealing with a block containing faces
             nAttributes = cubit.get_block_attribute_count(block)
             if (nAttributes != 1 and nAttributes != 6):
                 print 'Blocks not properly defined, 2d blocks must have one attribute (material id) or 6 attributes'
                 return None,None,None,None,None,None,None,None
             flag=int(cubit.get_block_attribute_value(block,0)) # Fetch the first attribute value (containing material id)
             print "nAttributes : ",nAttributes
             if nAttributes == 6:
                 self.write_nummaterial_velocity_file = True
                 velP = cubit.get_block_attribute_value(block,1)  # Fetch the first attribute value (containing P wave velocity)
                 velS = cubit.get_block_attribute_value(block,2)  # Fetch the second attribute value (containing S wave velocity)
                 rho = cubit.get_block_attribute_value(block,3)  # Fetch the third attribute value (containing material density)
                 qFlag = cubit.get_block_attribute_value(block,4)  # Fetch the first attribute value (containing Qflag)
                 anisotropy_flag = cubit.get_block_attribute_value(block,5)  # Fetch the first attribute value (containing anisotropy_flag) 
                 # Store (material_id,rho,velP,velS,Qflag,anisotropy_flag) in par :
                 par = tuple([flag,rho,velP,velS,qFlag,anisotropy_flag])
                 material[name] = par # associate the name of the block to its id and properties
             block_flag.append(int(flag)) # Append material id to block_flag
             block_mat.append(block)  # Append block id to block_mat
             if name in self.pml_boun_name : # If the block considered refered to one of the pml layer
                 self.abs_mesh=True
                 self.pml_layers=True
                 pml_boun[self.pml_boun_name.index(name)]=block 
                 # -> Put it at the correct position in pml_boun 
                 # (index 0 : pml_x_acoust, index 1 : pml_z_acoust, index 2 : pml_xz_acoust, 
                 #  index 3 : pml_x_elast, index 4 : pml_z_elast, index 5 : pml_xz_elast)
         elif ty == self.edge: # If we are dealing with a block containing edges
             block_bc_flag.append(2) # Append "2" to block_bc_flag
             block_bc.append(block) # Append block id to block_bc
             bc[name] = 2 # Associate the name of the block with its connectivity : an edge has connectivity = 2
             if name == self.topo: 
                 self.topo_mesh=True
                 topography=block # If the block considered refered to topography store its id in "topography"
             if name == self.axisname:
                 self.axisymmetric_mesh = True
                 axisId = block # AXISYM If the block considered refered to the axis store its id in "axisId"
             if name in self.abs_boun_name : # If the block considered refered to one of the boundaries
                 self.abs_mesh = True
                 abs_boun[self.abs_boun_name.index(name)] = block 
                 # -> Put it at the correct position in abs_boun (index 0 : bottom, index 1 : right, index 2 : top, index 3 : left)
         else:
             print 'Blocks not properly defined', ty
             return None,None,None,None,None,None,None,None
     nsets = cubit.get_nodeset_id_list() # Get the list of all nodeset
     if len(nsets) == 0: self.receivers = None # If this list is empty : put None in self.receivers
     for nset in nsets:
         name = cubit.get_exodus_entity_name('nodeset',nset) # Contains the name of the nodeset
         if name == self.rec: # If the name considered match self.rec (receivers)
             self.receivers = nset # Store the id of the nodeset in self.receivers
         else:
             print 'nodeset '+name+' not defined'
             self.receivers = None
     # Store everything in the object :
     try:
         self.block_mat = block_mat
         self.block_flag = block_flag
         self.block_bc = block_bc
         self.block_bc_flag = block_bc_flag
         self.bc = bc
         if self.write_nummaterial_velocity_file:
             self.material = material
         if self.abs_mesh:
             self.abs_boun = abs_boun
         if self.topo_mesh:
             self.topography = topography
         if self.axisymmetric_mesh:
             self.axisId = axisId
         if self.pml_layers:
             self.pml_boun = pml_boun
     except: 
         print 'Blocks not properly defined'
Exemplo n.º 33
0
def collecting_merging(cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1,cubfiles=False,ckbound_method1=False,ckbound_method2=False,merge_tolerance=None,decimate=False):
    import glob
    import re
    #
    rule_st=re.compile("(.+)_[0-9]+\.")
    rule_ex=re.compile(".+_[0-9]+\.(.+)")
    rule_int=re.compile(".+_([0-9]+)\.")
    boundary_dict={}
    ##
    try:
        from boundary_definition import check_bc, map_boundary
    except:
        pass
    #
    xmin,xmax,ymin,ymax,listfull=map_boundary(cpuxmin,cpuxmax,cpuymin,cpuymax,cpux,cpuy)
    #
    if cubfiles:
        nf,listip,filenames,cubflag=importing_cubfiles(cubfiles)
    else:
        nf=0
        filenames=[]
        ip=0
    #
    if nf > 0:
        for ip,filename in zip(listip,filenames):
            try:
                if ip in listfull:
                    if cubflag:
                        cubit.cmd('import cubit "'+filename+'"')
                    else:
                        cubit.cmd('import mesh geometry "'+filename+'" block all use nodeset sideset feature_angle 135.00 linear merge')
                    if decimate: cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
                    boundary=check_bc(ip,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax)
                    boundary_dict[ip]=boundary
                    list_vol=list(cubit.parse_cubit_list('volume','all'))
                    for v in list_vol:
                        cubit.cmd("disassociate mesh from volume "+str(v))
                        command = "del vol "+str(v)
                        cubit.cmd(command)
            except:
                cubit.cmd('import mesh geometry "'+filename+'" block all use nodeset sideset feature_angle 135.00 linear merge')
                if decimate: cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
                ip=0
                boundary=check_bc(ip,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax)
                boundary_dict[ip]=boundary
                list_vol=list(cubit.parse_cubit_list('volume','all'))
                for v in list_vol:
                    cubit.cmd("disassociate mesh from volume "+str(v))
                    command = "del vol "+str(v)
                    cubit.cmd(command)
        cubit.cmd('export mesh "tmp_collect_NOmerging.e" dimension 3 block all overwrite')
    else:
        if decimate: cubit.cmd('refine volume all numsplit 1 bias 1.0 depth 1 ')
        boundary=check_bc(ip,xmin,xmax,ymin,ymax,cpux,cpuy,cpuxmin,cpuxmax,cpuymin,cpuymax)
    #
    #
    #print boundary_dict
    block_list=cubit.get_block_id_list()
    for block in block_list:
        ty=cubit.get_block_element_type(block)
        if ty == 'HEX8':
            cubit.cmd('block '+str(block)+' name "vol'+str(block)+'"')
    #
    #
    print 'chbound',ckbound_method1,ckbound_method2
    
    
    if ckbound_method1 and not ckbound_method2 and len(filenames) != 1:
        #use the equivalence method for groups
        if isinstance(merge_tolerance,list):
            tol=merge_tolerance[0]
        elif merge_tolerance:
            tol=merge_tolerance
        else:
            tol=100000
        #
        idiag=None
        #cubit.cmd('set info off')
        #cubit.cmd('set journal off')
        #cubit.cmd('set echo off')
        ind=0
        for ix in range(cpuxmin,cpuxmax):
            for iy in range(cpuymin,cpuymax):
                ind=ind+1
                ip=iy*cpux+ix
                print '******************* ',ip, ind,'/',len(listfull)
                #
                #   ileft    |   ip
                #  --------------------
                #   idiag    |   idown
                #
                #
                if ip not in xmin and ip not in ymin:
                    ileft=iy*cpux+ix-1
                    idown=(iy-1)*cpux+ix
                    idiag=idown-1
                elif ip in xmin and ip in ymin:
                    ileft=ip
                    idown=ip
                    idiag=None
                elif ip in xmin:
                    ileft=ip
                    idown=(iy-1)*cpux+ix
                    idiag=idown
                elif ip in ymin:
                    ileft=iy*cpux+ix-1
                    idown=ip
                    idiag=ileft
                #
                print ip,ileft,idiag,idown
                if ip != idown:
                    nup=boundary_dict[ip]['nodes_surf_ymin']
                    ndow=boundary_dict[idown]['nodes_surf_ymax']
                    merge_node_ck(nup,ndow)
                 
                    if idiag != idown:
                        if ip in ymax and ip not in xmin:
                            nlu=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck left up... r u
                            nru=boundary_dict[ileft]['node_curve_xmaxymax']
                            merge_node(nlu,nru)
                        if ip in xmax:
                            nrd=boundary_dict[ip]['node_curve_xmaxymin'] #node in curve chunck left up... r u
                            nru=boundary_dict[idown]['node_curve_xmaxymax']
                            merge_node(nrd,nru)
                        nru=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
                        nrd=boundary_dict[idown]['node_curve_xminymax']
                        nld=boundary_dict[idiag]['node_curve_xmaxymax']
                        nlu=boundary_dict[ileft]['node_curve_xmaxymin']
                        merge_node_4(nru,nrd,nld,nlu)
                    elif ip in xmin:
                        nlu=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
                        nld=boundary_dict[idown]['node_curve_xminymax']
                        merge_node(nld,nlu)
                        nru=boundary_dict[ip]['node_curve_xmaxymin'] #node in curve chunck right up... r u
                        nrd=boundary_dict[idown]['node_curve_xmaxymax']
                        merge_node(nrd,nru)
                        
                        
                        
                        
                #
                if ip != ileft:
                    nright=boundary_dict[ip]['nodes_surf_xmin']
                    nleft=boundary_dict[ileft]['nodes_surf_xmax']
                    merge_node_ck(nright,nleft)
                    #
                    #
                    if ip in ymin:
                        nrd=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right down... r u
                        nld=boundary_dict[ileft]['node_curve_xmaxymin']
                        merge_node(nrd,nld)
                    if ip in ymax:
                        nru=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck right up... r u
                        nlu=boundary_dict[ileft]['node_curve_xmaxymax']
                        merge_node(nlu,nru)
        
        cubit.cmd('set info on')
        cubit.cmd('set echo on')
        cubit.cmd('set journal on')
        
        
        #
        #
        cmd='group "negativejac" add quality hex all Jacobian high'
        cubit.cmd(cmd) 
        group_id_1=cubit.get_id_from_name("negativejac")
        n1=cubit.get_group_nodes(group_id_1)
        if len(n1) != 0:
            print 'error, negative jacobian after the equivalence node command, use --merge2 instead of --equivalence/--merge/--merge1'
    elif ckbound_method2 and not ckbound_method1 and len(filenames) != 1:
        if isinstance(merge_tolerance,list):
            tol=merge_tolerance[0]
        elif merge_tolerance:
            tol=merge_tolerance
        else:
            tol=100000
        #
        idiag=None
        for ix in range(cpuxmin,cpuxmax):
            for iy in range(cpuymin,cpuymax):
                ip=iy*cpux+ix
                print '******************* ',ip
                #
                #   ileft    |   ip
                #  --------------------
                #   idiag    |   idown
                #
                #
                if ip not in xmin and ip not in ymin:
                    ileft=iy*cpux+ix-1
                    idown=(iy-1)*cpux+ix
                    idiag=idown-1
                elif ip in xmin and ip in ymin:
                    ileft=ip
                    idown=ip
                elif ip in xmin:
                    ileft=ip
                    idown=(iy-1)*cpux+ix
                    idiag=idown
                elif ip in ymin:
                    ileft=iy*cpux+ix-1
                    idown=ip
                    idiag=ileft
                #
                #
                if ip != idown:
                    nup=boundary_dict[ip]['nodes_surf_ymin']
                    ndow=boundary_dict[idown]['nodes_surf_ymax']
                    for n1,n2 in zip(nup,ndow):
                        cubit.cmd('equivalence node '+str(n1)+' '+str(n2)+' tolerance '+str(tol))
                    if idiag != idown:
                        if ip in ymax and ip not in xmin:
                            nlu=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck left up... r u
                            nru=boundary_dict[ileft]['node_curve_xmaxymax']
                            for n in zip(nlu,nru):
                                cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
                        nru=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
                        nrd=boundary_dict[idown]['node_curve_xminymax']
                        nld=boundary_dict[idiag]['node_curve_xmaxymax']
                        nlu=boundary_dict[ileft]['node_curve_xmaxymin']
                        for n in zip(nru,nrd,nlu,nld):
                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
                    elif ip in xmin:
                        nru=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right up... r u
                        nrd=boundary_dict[idown]['node_curve_xminymax']
                        for n in zip(nru,nrd):
                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
                #
                #
                if ip != ileft:
                    nright=boundary_dict[ip]['nodes_surf_xmin']
                    nleft=boundary_dict[ileft]['nodes_surf_xmax']
                    for n1,n2 in zip(nleft,nright):
                        cubit.cmd('equivalence node '+str(n1)+' '+str(n2)+' tolerance '+str(tol))
                    #
                    #
                    if ip in ymin:
                        nrd=boundary_dict[ip]['node_curve_xminymin'] #node in curve chunck right down... r u
                        nld=boundary_dict[ileft]['node_curve_xmaxymin']
                        for n in zip(nrd,nld):
                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
                    if ip in ymax:
                        nru=boundary_dict[ip]['node_curve_xminymax'] #node in curve chunck right up... r u
                        nlu=boundary_dict[ileft]['node_curve_xmaxymax']
                        for n in zip(nru,nlu):
                            cubit.cmd('equivalence node '+' '.join(str(x) for x in n)+' tolerance '+str(tol))
        #
        #
        cmd='topology check coincident node face all tolerance '+str(tol*2)+' nodraw brief result group "checkcoinc"' 
        cubit.silent_cmd(cmd)
        group_id_1=cubit.get_id_from_name("checkcoinc")
        if group_id_1 != 0:
            n1=cubit.get_group_nodes(group_id_1)
            if len(n1) != 0:
                print 'error, coincident nodes after the equivalence node command, check the tolerance'
                import sys
                sys.exit()
        cmd='group "negativejac" add quality hex all Jacobian high'
        cubit.cmd(cmd) 
        group_id_1=cubit.get_id_from_name("negativejac")
        n1=cubit.get_group_nodes(group_id_1)
        if len(n1) != 0:
            print 'error, negative jacobian after the equivalence node command, check the mesh'
    elif ckbound_method1 and  ckbound_method2 and len(filenames) != 1:
        block_list=cubit.get_block_id_list()
        i=-1
        for block in block_list:
            ty=cubit.get_block_element_type(block)
            if ty == 'HEX8':
                i=i+1
                if isinstance(merge_tolerance,list):
                    try:
                        tol=merge_tolerance[i]
                    except:
                        tol=merge_tolerance[-1]
                elif merge_tolerance:
                    tol=merge_tolerance
                else:
                    tol=1
                cmd='topology check coincident node face in hex in block '+str(block)+' tolerance '+str(tol)+' nodraw brief result group "b'+str(block)+'"'
                cubit.cmd(cmd)
                print cmd
                cmd='equivalence node in group b'+str(block)+' tolerance '+str(tol)
                cubit.cmd(cmd)
                print cmd
        if isinstance(merge_tolerance,list):
            tol=max(merge_tolerance)
        elif merge_tolerance:
            tol=merge_tolerance
        else:
            tol=1
        #
        #
        cmd='topology check coincident node face all tolerance '+str(tol)+' nodraw brief result group "checkcoinc"' 
        cubit.silent_cmd(cmd)
        group_id_1=cubit.get_id_from_name("checkcoinc")
        if group_id_1 != 0:
            n1=cubit.get_group_nodes(group_id_1)
            if len(n1) != 0:
                print 'error, coincident nodes after the equivalence node command, check the tolerance'
                import sys
                sys.exit()
        cmd='group "negativejac" add quality hex all Jacobian high'
        cubit.silent_cmd(cmd) 
        group_id_1=cubit.get_id_from_name("negativejac")
        n1=cubit.get_group_nodes(group_id_1)
        if len(n1) != 0:
            print 'error, negative jacobian after the equivalence node command, use --merge instead of --equivalence'
Exemplo n.º 34
0
def savemesh(mpiflag, iproc=0, filename=None):
    import start as start
    cfg = start.start_cfg(filename=filename)
    mpiflag, iproc, numproc, mpi = start.start_mpi()

    def runsave(meshfile, 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 + \
            '/' + meshfile + '.cub' + '" overwrite'
        cubit.cmd(cubitcommand)
        ner2 = cubit.get_error_count()
        if ner == ner2:
            cubitcommand = 'export mesh "' + cfg.output_dir + '/' + \
                meshfile + '.e' + '" dimension 3 block all overwrite'
            cubit.cmd(cubitcommand)
            ner2 = cubit.get_error_count()
        if ner == ner2:
            flag = 1
        return flag

    meshfile = 'mesh_vol_' + str(iproc)

    flagsaved = 0
    infosave = (iproc, flagsaved)

    mpi.barrier()
    total_saved = mpi.allgather(flagsaved)
    if isinstance(total_saved, int):
        total_saved = [total_saved]

    ind = 0
    saving = True
    while saving:
        if len(total_saved) != sum(total_saved):
            #
            if not flagsaved:
                flagsaved = runsave(meshfile, iproc, filename=filename)
                if flagsaved:
                    infosave = (iproc, flagsaved)
                    if numproc > 1:
                        f = open('mesh_saved' + str(iproc), 'w')
                        f.close()
            mpi.barrier()
            total_saved = mpi.allgather(flagsaved)
            if isinstance(total_saved, int):
                total_saved = [total_saved]
            ind = ind + 1
        else:
            saving = False
        if ind > len(total_saved) + 10:
            saving = False
        print sum(total_saved), '/', len(total_saved), ' saved'

    info_total_saved = mpi.allgather(infosave)
    if isinstance(info_total_saved, int):
        info_total_saved = [info_total_saved]

    if iproc == 0:
        f = open('mesh_saving.log', 'w')
        f.write('\n'.join(str(x) for x in info_total_saved))
        f.close()

    f = open(cfg.output_dir + '/' + 'blocks_' + str(iproc).zfill(5), 'w')
    blocks = cubit.get_block_id_list()

    for block in blocks:
        name = cubit.get_exodus_entity_name('block', block)
        element_count = cubit.get_exodus_element_count(block, "block")
        nattrib = cubit.get_block_attribute_count(block)
        attr = [cubit.get_block_attribute_value(
            block, x) for x in range(0, nattrib)]
        ty = cubit.get_block_element_type(block)
        f.write(str(block) + ' ; ' + name + ' ; nattr ' + str(nattrib) +
                ' ; ' + ' '.join(str(x) for x in attr) + ' ; ' + ty + ' ' +
                str(element_count) + '\n')
    f.close()

    import quality_log
    f = open(cfg.output_dir + '/' + 'quality_' + str(iproc).zfill(5), 'w')
    max_skewness, min_length = quality_log.quality_log(f)
    f.close()

    count_hex = [cubit.get_hex_count()]
    count_node = [cubit.get_node_count()]
    max_skew = [(iproc, max_skewness)]
    min_l = [(iproc, min_length)]

    mpi.barrier()
    total_min_l = mpi.gather(min_l)
    total_hex = mpi.gather(count_hex)
    total_node = mpi.gather(count_node)
    total_max_skew = mpi.gather(max_skew)

    mpi.barrier()
    if iproc == 0:
        min_total_min_l = min([ms[1] for ms in total_min_l])
        max_total_max_skew = max([ms[1] for ms in total_max_skew])
        sum_total_node = sum(total_node)
        sum_total_hex = sum(total_hex)

        totstat_file = open(cfg.output_dir + '/totstat.log', 'w')
        text = 'hex total number,node total number,max skew, min length\n'
        totstat_file.write(text)

        text = str(sum_total_hex) + ' , ' + str(sum_total_node) + ' , ' + \
            str(max_total_max_skew) + ' , ' + str(min_total_min_l) + '\n'
        totstat_file.write(text)

        totstat_file.write(str(total_max_skew))
        totstat_file.close()

    print 'meshing process end... proc ', iproc
Exemplo n.º 35
0
def collect_old(cpuxmin=0,cpuxmax=1,cpuymin=0,cpuymax=1,cpux=1,cpuy=1,cubfiles=False,ckbound_method1=False,ckbound_method2=False,merge_tolerance=None,curverefining=False,outfilename='totalmesh_merged',qlog=False,export2SPECFEM3D=False,listblock=None,listflag=None,outdir='.',add_sea=False,decimate=False,cpml=False,cpml_size=False,top_absorbing=False,hex27=False):
    #
    cubit.cmd('set journal error off')
    cubit.cmd('set verbose error off')
    collecting_merging(cpuxmin,cpuxmax,cpuymin,cpuymax,cpux,cpuy,cubfiles=cubfiles,ckbound_method1=ckbound_method1,ckbound_method2=ckbound_method2,merge_tolerance=merge_tolerance,decimate=decimate)
    cubit.cmd('set journal error on')
    cubit.cmd('set verbose error on')
    #
    if curverefining:
        block=1001 #topography
        refine_closecurve(block,curverefining,acis=True)
    #
    #
    if add_sea:
        block=1001
        add_sea_layer(block=block)

    outdir2='/'.join(x for x in outfilename.split('/')[:-1])
    if outdir2 == '': 
        outdir2=outdir+'/'
    else:
        outdir2=outdir+'/'+outdir2+'/'    
    
    import os
    try:
        os.makedirs(outdir2)
    except OSError:
        pass
    
    cubit.cmd('compress all')
    command="export mesh '"+outdir2+outfilename+".e' block all overwrite xml '"+outdir2+outfilename+".xml'"
    cubit.cmd(command)
    f=open(outdir2+'blocks.dat','w')
    blocks=cubit.get_block_id_list()
    #
    for block in blocks:
        name=cubit.get_exodus_entity_name('block',block)
        element_count = cubit.get_exodus_element_count(block, "block")
        nattrib=cubit.get_block_attribute_count(block)
        attr=[cubit.get_block_attribute_value(block,x) for x in range(0,nattrib)]
        ty=cubit.get_block_element_type(block)
        f.write(str(block)+' ; '+name+' ; nattr '+str(nattrib)+' ; '+' '.join(str(x) for x in attr)+' ; '+ty+' '+str(element_count)+'\n')
    f.close()
    #
    #
    cubit.cmd('set info echo journ off')
    cmd='del group all'
    cubit.silent_cmd(cmd)
    cubit.cmd('set info echo journ on')
    #
    command = "save as '"+outdir2+outfilename+".cub' overwrite"
    cubit.cmd(command)
    #
    print 'end meshing'
    #
    #
    if qlog:
        print '\n\nQUALITY CHECK.... ***************\n\n'
        import quality_log
        tq=open(outdir2+outfilename+'.quality','w')
        max_skewness,min_length=quality_log.quality_log(tq)
    #
    #
    #
    if export2SPECFEM3D:
        e2SEM(files=False,listblock=listblock,listflag=listflag,outdir=outdir,cpml=cpml,cpml_size=cpml_size,top_absorbing=top_absorbing,hex27=hex27)
Exemplo n.º 36
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

    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)