Esempio n. 1
0
def start_cubit(init=False):
    """
    start cubit, it return the cubit object
    init argument set the monitotr files
    """
    import sys,os
    try:
        cubit.silent_cmd('comment')
    except:
        try:
            import cubit
            import utilities
            cubit.init([""])
        except:
            print 'error importing cubit'
            sys.exit()
        try:
            if init:
                from start import start_cfg,start_mpi
                cfg=start_cfg()
                mpiflag,iproc,numproc,mpi   = start_mpi()
                cubit.cmd('set logging on file "'+cfg.working_dir+'/cubit_proc_'+str(iproc)+'.log"')
                cubit.cmd("set echo off")
                cubit.cmd("set info off")
                if iproc == cfg.monitored_cpu:
                    cubit.cmd("record '"+cfg.working_dir+"/monitor_"+str(cfg.monitored_cpu)+".jou'")
                    cubit.cmd("set journal on")
                    cubit.cmd("journal error on")
                    d=cfg.__dict__
                    ks=d.keys()
                    ks.sort()
                    for k in ks:
                        if '__'  not in k and '<'  not in str(d[k]) and d[k] is not None:
                            txt=str(k)+' -----> '+str(d[k])
                            txt=txt.replace("'","").replace('"','')
                            cubit.cmd('comment "'+txt+'"')
                else:
                    cubit.cmd("set journal "+cfg.jou_info)
                    cubit.cmd("journal error "+cfg.jer_info)
                    d=cfg.__dict__
                    ks=d.keys()
                    ks.sort()
                    for k in ks:
                        if '__'  not in k and '<'  not in str(d[k]) and d[k] is not None:
                            txt=str(k)+' -----> '+str(d[k])
                            txt=txt.replace("'","").replace('"','')
                            cubit.cmd('comment "'+txt+'"')
                cubit.cmd("set echo "+cfg.echo_info)
                cubit.cmd("set info "+cfg.cubit_info)
                version_cubit=utilities.get_cubit_version()
                if version_cubit > 13 and version_cubit < 15:
                    print 'VERSION CUBIT ',version_cubit
                    print 'VERSIONs of CUBIT > 13 have bugs with merge node commands and equivalence'
                    print 'the merge option is not operative with this version, please download CUBIT 13'
                else:
                    print 'VERSION CUBIT ',version_cubit
        except:
            print 'error start cubit'
            sys.exit()
    return cubit
Esempio n. 2
0
def start_cfg(filename=None, importmenu=True):
    """
    return the object cfg with the parameters of the mesh
    """
    import read_parameter_cfg
    mpiflag, iproc, numproc, mpi = start_mpi()
    if filename:
        importmenu = False
    cfg = read_parameter_cfg.readcfg(
        filename=filename, importmenu=importmenu, mpiflag=mpiflag)
    import os
    try:
        os.makedirs(cfg.working_dir)
    except OSError:
        pass
    try:
        os.makedirs(cfg.output_dir)
    except OSError:
        pass
    try:
        os.makedirs(cfg.SPECFEM3D_output_dir)
    except OSError:
        pass

    return cfg
Esempio n. 3
0
def importgeometry(geometryfile, iproc=0, filename=None):
    import start as start
    cfg = start.start_cfg(filename=filename)
    mpiflag, iproc, numproc, mpi = start.start_mpi()

    if iproc == 0:
        print 'importing geometry....'
    a = ['ok from ' + str(iproc)]

    mpi.barrier()
    total_a = mpi.allgather(a)
    if iproc == 0:
        print total_a

    def runimport(geometryfile, iproc, filename=None):
        import start as start
        cubit = start.start_cubit()
        cfg = start.start_cfg(filename=filename)
        file1 = cfg.output_dir + '/' + geometryfile
        cubitcommand = 'open "' + file1 + '"  '
        cubit.cmd(cubitcommand)

    if cfg.parallel_import:
        runimport(geometryfile, iproc, filename=filename)
    else:
        if iproc == 0:
            runimport(geometryfile, iproc, filename=filename)
            for i in range(1, mpi.size):
                mpi.send('import', i)
                msg, status = mpi.recv(i)
        else:
            msg, status = mpi.recv(0)
            runimport(geometryfile, iproc, filename=filename)
            mpi.send('ok' + str(iproc), 0)
Esempio n. 4
0
def importgeometry(geometryfile, iproc=0, filename=None):
    import start as start
    cfg = start.start_cfg(filename=filename)
    mpiflag, iproc, numproc, mpi = start.start_mpi()

    if iproc == 0: print 'importing geometry....'
    a = ['ok from ' + str(iproc)]

    mpi.barrier()
    total_a = mpi.allgather(a)
    if iproc == 0: print total_a

    def runimport(geometryfile, iproc, filename=None):
        import start as start
        cubit = start.start_cubit()
        cfg = start.start_cfg(filename=filename)
        file1 = cfg.output_dir + '/' + geometryfile
        cubitcommand = 'open "' + file1 + '"  '
        cubit.cmd(cubitcommand)

    if cfg.parallel_import:
        runimport(geometryfile, iproc, filename=filename)
    else:
        if iproc == 0:
            runimport(geometryfile, iproc, filename=filename)
            for i in range(1, mpi.size):
                mpi.send('import', i)
                msg, status = mpi.recv(i)
        else:
            msg, status = mpi.recv(0)
            runimport(geometryfile, iproc, filename=filename)
            mpi.send('ok' + str(iproc), 0)
Esempio n. 5
0
def start_cfg(filename=None, importmenu=True):
    """
    return the object cfg with the parameters of the mesh
    """
    import read_parameter_cfg
    mpiflag, iproc, numproc, mpi = start_mpi()
    if filename:
        importmenu = False
    cfg = read_parameter_cfg.readcfg(
        filename=filename, importmenu=importmenu, mpiflag=mpiflag)
    import os
    try:
        os.makedirs(cfg.working_dir)
    except OSError:
        pass
    try:
        os.makedirs(cfg.output_dir)
    except OSError:
        pass
    try:
        os.makedirs(cfg.SPECFEM3D_output_dir)
    except OSError:
        pass

    return cfg
Esempio n. 6
0
def savegeometry(iproc=0, surf=False, filename=None):
    import start as start
    cfg = start.start_cfg(filename=filename)
    mpiflag, iproc, numproc, mpi = start.start_mpi()

    def runsave(geometryfile, iproc, filename=None):
        import start as start
        cubit = start.start_cubit()
        cfg = start.start_cfg(filename=filename)
        flag = [0]
        ner = cubit.get_error_count()
        cubitcommand = 'save as "' + cfg.output_dir + '/' + geometryfile + '"  overwrite'
        cubit.cmd(cubitcommand)
        ner2 = cubit.get_error_count()
        if ner == ner2:
            flag = [1]
        return flag

    if surf:
        geometryfile = 'surf_vol_' + str(iproc) + '.cub'
    else:
        geometryfile = 'geometry_vol_' + str(iproc) + '.cub'

    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[0]:
                flagsaved = runsave(geometryfile, iproc, filename=filename)
                if flagsaved[0]:
                    infosave = (iproc, flagsaved[0])
                    if numproc > 1:
                        f = open('geometry_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('geometry_saving.log', 'w')
        f.write('\n'.join(str(x) for x in info_total_saved))
        f.close()
Esempio n. 7
0
def savegeometry(iproc=0,surf=False,filename=None):
    import start as start
    cfg                         = start.start_cfg(filename=filename)
    mpiflag,iproc,numproc,mpi   = start.start_mpi()
    
    def runsave(geometryfile,iproc,filename=None):
        import start as start
        cubit                   = start.start_cubit()
        cfg                         = start.start_cfg(filename=filename)
        flag=[0]
        ner=cubit.get_error_count()
        cubitcommand= 'save as "'+ cfg.output_dir+'/'+geometryfile+ '"  overwrite' 
        cubit.cmd(cubitcommand)                                                    
        ner2=cubit.get_error_count()                                             
        if ner == ner2:
            flag=[1]
        return flag
        
    if surf:
        geometryfile='surf_vol_'+str(iproc)+'.cub'
    else:
        geometryfile='geometry_vol_'+str(iproc)+'.cub'
        
    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[0]: 
                flagsaved=runsave(geometryfile,iproc,filename=filename)
                if flagsaved[0]:
                    infosave=(iproc,flagsaved[0])        
                    if numproc > 1:
                        f=open('geometry_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('geometry_saving.log','w')
        f.write('\n'.join(str(x) for x in info_total_saved))                
        f.close()
Esempio n. 8
0
def mesh(filename=None):
    """create the mesh"""
    import start as start
    cfg                     = start.start_cfg(filename=filename)
    mpiflag,iproc,numproc,mpi   = start.start_mpi()
    #
    if cfg.map_meshing_type == 'regularmap':
            mesh_layercake_regularmap(filename=filename)
    else:
        print 'error: map_meshing_type ', cfg.map_meshing_type,' not implemented'
Esempio n. 9
0
def read_grid(filename=None):
    import start as start
    mpiflag, iproc, numproc, mpi = start.start_mpi()
    #
    numpy = start.start_numpy()
    cfg = start.start_cfg(filename=filename)

    # if cfg.irregulargridded_surf==True then cfg.nx and cfg.ny are the
    # desired number of point along the axis....
    if cfg.nx and cfg.ny:
        nx = cfg.nx
        ny = cfg.ny
        if cfg.nstep:
            nx = min(cfg.nx, int(cfg.nx / cfg.nstep) + 1)
            ny = min(cfg.ny, int(cfg.ny / cfg.nstep) + 1)
            nstep = cfg.nstep
        else:
            nstep = 1
    else:
        try:
            xstep = cfg.step
            ystep = cfg.step
        except:
            xstep = cfg.xstep
            ystep = cfg.ystep
        nx = int((cfg.longitude_max - cfg.longitude_min) / xstep) + 1
        ny = int((cfg.latitude_max - cfg.latitude_min) / ystep) + 1
        nstep = 1
    #

    if cfg.irregulargridded_surf:
        xt, xstep = numpy.linspace(cfg.xmin, cfg.xmax, num=nx, retstep=True)
        yt, ystep = numpy.linspace(cfg.ymin, cfg.ymax, num=ny, retstep=True)

    elev = numpy.zeros([nx, ny, cfg.nz], float)
    #
    if cfg.bottomflat:
        elev[:, :, 0] = cfg.depth_bottom
        bottomsurface = 1
    else:
        bottomsurface = 0

    for inz in range(bottomsurface, cfg.nz - 1):
        grdfilename = cfg.filename[inz - bottomsurface]

        if cfg.irregulargridded_surf:
            coordx, coordy, elev_1 = process_irregular_surfacefiles(
                iproc, nx, ny, cfg.xmin, cfg.xmax, cfg.ymin, cfg.ymax,
                xstep, ystep, grdfilename)
        else:
            coordx, coordy, elev_1 = process_surfacefiles(
                iproc, nx, ny, nstep, grdfilename, cfg.unit,
                cfg.lat_orientation)
        elev[:, :, inz] = elev_1[:, :]
        #

    inz = cfg.nz - 1  # last surface
    if cfg.sea:
        elev[:, :, inz] = elev[:, :, inz - 1]
    else:
        if cfg.topflat:
            elev[:, :, inz] = cfg.depth_top
        else:
            grdfile = cfg.filename[inz - bottomsurface]
            print 'reading ', cfg.filename[inz - bottomsurface]
            if cfg.irregulargridded_surf:
                coordx, coordy, elev_1 = process_irregular_surfacefiles(
                    iproc, nx, ny, cfg.xmin, cfg.xmax, cfg.ymin, cfg.ymax,
                    xstep, ystep, grdfile)
            else:
                coordx, coordy, elev_1 = process_surfacefiles(
                    iproc, nx, ny, nstep, grdfile, cfg.unit,
                    cfg.lat_orientation)
            elev[:, :, inz] = elev_1[:, :]

        if cfg.subduction:
            print 'subduction'
            top = elev[:, :, inz]
            slab = elev[:, :, inz - 1]
            subcrit = numpy.abs(top - slab) < cfg.subduction_thres
            top[subcrit] = slab[subcrit] + cfg.subduction_thres
            print len(top[subcrit])
            elev[:, :, inz] = top
    return coordx, coordy, elev, nx, ny
Esempio n. 10
0
 if o in ('--x3'):
     x3 = value
 if o in ('--x4'):
     x4 = value
 if o in ('--unit'):
     unit = value
 #
 if o in ('--build_volume'):
     build_volume = True
 if o in ("-h", "--help"):
     usage()
     sys.exit(2)
 # check the configuration
 if o in ("--chklib"):
     import start as start
     mpiflag, iproc, numproc, mpi = start.start_mpi()
     if mpiflag:
         print '--------, MPI ON, parallel mesher ready'
     else:
         print '--------, MPI OFF, serial mesher ready'
     numpy = start.start_numpy()
     print '--------, Numpy ON'
     cubit = start.start_cubit()
     print '--------, CUBIT ON'
     sys.exit()
 if o in ("--cfg"):
     cfg_name = value
     try:
         if open(cfg_name):
             pass
     except IOError, e:
Esempio n. 11
0
def layercake_volume_ascii_regulargrid_mpiregularmap(filename=None,verticalsandwich=False,onlysurface=False):
    import sys
    import start as start
    #
    mpiflag,iproc,numproc,mpi   = start.start_mpi()
    #
    numpy                       = start.start_numpy()
    cfg                         = start.start_cfg(filename=filename)                       
    
    from utilities import geo2utm, savegeometry,savesurf,cubit_command_check
    
    from math import sqrt
    #
    try:
        mpi.barrier()
    except:
        pass
    #
    #
    command = "comment '"+"PROC: "+str(iproc)+"/"+str(numproc)+" '"
    cubit_command_check(iproc,command,stop=True)
    if verticalsandwich: cubit.cmd("comment 'Starting Vertical Sandwich'")
    #
    #get icpuy,icpux values
    if mpiflag:
        icpux = iproc % cfg.nproc_xi
        icpuy = int(iproc / cfg.nproc_xi)
    else:
        icpuy=int(cfg.id_proc/cfg.nproc_xi)
        icpux=cfg.id_proc%cfg.nproc_xi
    
    #
    if  cfg.geometry_format == 'ascii':
        #for the original surfaces
        #number of points in the files that describe the topography
        import local_volume
        if cfg.localdir_is_globaldir:
            if iproc == 0 or not mpiflag:
                coordx_0,coordy_0,elev_0,nx_0,ny_0=local_volume.read_grid(filename)
                print 'end of reading grd files '+str(nx_0*ny_0)+ ' points'
            else:
                pass
            if iproc == 0 or not mpiflag:
                coordx=mpi.bcast(coordx_0)
            else:
                coordx=mpi.bcast()
            if iproc == 0 or not mpiflag:
                coordy=mpi.bcast(coordy_0)
            else:
                coordy=mpi.bcast()
            if iproc == 0 or not mpiflag:
                elev=mpi.bcast(elev_0)
            else:
                elev=mpi.bcast()
            if iproc == 0 or not mpiflag:
                nx=mpi.bcast(nx_0)
            else:
                nx=mpi.bcast()       
            if iproc == 0 or not mpiflag:
                ny=mpi.bcast(ny_0)
            else:
                ny=mpi.bcast()
        else:
            coordx,coordy,elev,nx,ny=local_volume.read_grid(filename)
        print str(iproc)+ ' end of receving grd files '
        nx_segment=int(nx/cfg.nproc_xi)+1
        ny_segment=int(ny/cfg.nproc_eta)+1
        
    elif cfg.geometry_format=='regmesh': # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        
        if cfg.depth_bottom != cfg.zdepth[0]:
            if iproc == 0: print 'the bottom of the block is at different depth than depth[0] in the configuration file'
        nx= cfg.nproc_xi+1
        ny= cfg.nproc_eta+1
        nx_segment=2
        ny_segment=2
        #if iproc == 0: print nx,ny,cfg.cpux,cfg.cpuy
        xp=(cfg.xmax-cfg.xmin)/float((nx-1))
        yp=(cfg.ymax-cfg.ymin)/float((ny-1))
        #
        elev=numpy.zeros([nx,ny,cfg.nz],float)
        coordx=numpy.zeros([nx,ny],float)
        coordy=numpy.zeros([nx,ny],float)
        #
        #
        xlength=(cfg.xmax-cfg.xmin)/float(cfg.nproc_xi) #length of x slide for chunk
        ylength=(cfg.ymax-cfg.ymin)/float(cfg.nproc_eta) #length of y slide for chunk
        nelem_chunk_x=1    
        nelem_chunk_y=1
        ivxtot=nelem_chunk_x+1
        ivytot=nelem_chunk_y+1 
        xstep=xlength #distance between vertex on x
        ystep=ylength
        for i in range(0,cfg.nz):
            elev[:,:,i] = cfg.zdepth[i]
        
        icoord=0
        for iy in range(0,ny):
            for ix in range(0,nx):
                icoord=icoord+1
                coordx[ix,iy]=cfg.xmin+xlength*(ix)
                coordy[ix,iy]=cfg.ymin+ylength*(iy)
        
        #print coordx,coordy,nx,ny
    #
    print 'end of building grid '+str(iproc)
    print 'number of point: ', len(coordx)*len(coordy)
    #
    #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    #for each processor
    #
    nxmin_cpu=(nx_segment-1)*(icpux)
    nymin_cpu=(ny_segment-1)*(icpuy)
    nxmax_cpu=min(nx-1,(nx_segment-1)*(icpux+1))
    nymax_cpu=min(ny-1,(ny_segment-1)*(icpuy+1))
    #if iproc == 0:
    #    print nx_segment,ny_segment,nx,ny
    #    print icpux,icpuy,nxmin_cpu,nxmax_cpu
    #    print icpux,icpuy,nymin_cpu,nymax_cpu
    #    print coordx[0,0],coordx[nx-1,ny-1]
    #    print coordy[0,0],coordy[nx-1,ny-1]
    #
    #
    icurve=0
    isurf=0
    ivertex=0
    #
    #create vertex
    for inz in range(0,cfg.nz):
        if cfg.sea and inz==cfg.nz-1: #sea layer
            sealevel=True
            bathymetry=False
        elif cfg.sea and inz==cfg.nz-2: #bathymetry layer
            sealevel=False
            bathymetry=True
        else:
            sealevel=False
            bathymetry=False
        print sealevel,bathymetry
        
        if  cfg.bottomflat and inz == 0: #bottom layer
                #
                if cfg.geometry_format == 'ascii':
                    lv=cubit.get_last_id("vertex")     
                    
                    x_current,y_current=(coordx[nxmin_cpu,nymin_cpu],coordy[nxmin_cpu,nymin_cpu])
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)
                    #
                    x_current,y_current=(coordx[nxmin_cpu,nymax_cpu],coordy[nxmin_cpu,nymax_cpu])
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)                                                                              
                    #
                    x_current,y_current=(coordx[nxmax_cpu,nymax_cpu],coordy[nxmax_cpu,nymax_cpu])
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)
                    #
                    x_current,y_current=(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu])
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)
                    #
                    lv2=cubit.get_last_id("vertex")     
                    
                    cubitcommand= 'create surface vertex '+str(lv+1)+' to '+str(lv2)
                    cubit.cmd(cubitcommand)
                    #
                    isurf = isurf + 1
                else:
                    lv=cubit.get_last_id("vertex") 
                    x_current,y_current=geo2utm(coordx[nxmin_cpu,nymin_cpu],coordy[nxmin_cpu,nymin_cpu],'utm')
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)
                    #
                    x_current,y_current=geo2utm(coordx[nxmin_cpu,nymax_cpu],coordy[nxmin_cpu,nymax_cpu],'utm')
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)                                                                              
                    #
                    x_current,y_current=geo2utm(coordx[nxmax_cpu,nymax_cpu],coordy[nxmax_cpu,nymax_cpu],'utm')
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)
                    #
                    x_current,y_current=geo2utm(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu],'utm')
                    cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( cfg.depth_bottom )
                    cubit.cmd(cubitcommand)
                    #
                    lv2=cubit.get_last_id("vertex") 
                    cubitcommand= 'create surface vertex '+str(lv+1)+' to '+str(lv2)
                    cubit.cmd(cubitcommand)
                    #
                    isurf = isurf + 1
        else:
            if cfg.geometry_format == 'regmesh':
                zvertex=cfg.zdepth[inz]
                lv=cubit.get_last_id("vertex")                        
                x_current,y_current=geo2utm(coordx[nxmin_cpu,nymin_cpu],coordy[nxmin_cpu,nymin_cpu],'utm')
                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
                cubit.cmd(cubitcommand)
                #
                x_current,y_current=geo2utm(coordx[nxmin_cpu,nymax_cpu],coordy[nxmin_cpu,nymax_cpu],'utm')
                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
                cubit.cmd(cubitcommand)                                                                              
                #
                x_current,y_current=geo2utm(coordx[nxmax_cpu,nymax_cpu],coordy[nxmax_cpu,nymax_cpu],'utm')
                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
                cubit.cmd(cubitcommand)
                #
                x_current,y_current=geo2utm(coordx[nxmax_cpu,nymin_cpu],coordy[nxmax_cpu,nymin_cpu],'utm')
                cubitcommand= 'create vertex '+ str( x_current )+ ' ' + str( y_current) +' '+ str( zvertex )
                cubit.cmd(cubitcommand)
                #
                cubitcommand= 'create surface vertex '+str(lv+1)+' '+str(lv+2)+' '+str(lv+3)+' '+str(lv+4)
                cubit.cmd(cubitcommand)
                #
                isurf = isurf + 1
            elif cfg.geometry_format == 'ascii':
                
                vertex=[]
                
                for iy in range(nymin_cpu,nymax_cpu+1):
                    ivx=0
                    for ix in range(nxmin_cpu,nxmax_cpu+1):
                        zvertex=elev[ix,iy,inz]
                        #zvertex=adjust_sea_layers(zvertex,sealevel,bathymetry,cfg)
                        x_current,y_current=(coordx[ix,iy],coordy[ix,iy])
                        #
                        vertex.append(' Position '+ str( x_current ) +' '+ str( y_current )+' '+ str( zvertex ) )
                #
                print 'proc',iproc, 'vertex list created....',len(vertex)
                n=max(nx,ny)
                uline=[]
                vline=[]
                iv=0
                
                cubit.cmd("set info off")
                cubit.cmd("set echo off")
                cubit.cmd("set journal off")
                
                for iy in range(0,nymax_cpu-nymin_cpu+1):
                    positionx=''
                    for ix in range(0,nxmax_cpu-nxmin_cpu+1):
                        positionx=positionx+vertex[iv]
                        iv=iv+1
                    command='create curve spline '+positionx
                    cubit.cmd(command)
                    #print command
                    uline.append( cubit.get_last_id("curve") )
                for ix in range(0,nxmax_cpu-nxmin_cpu+1):
                    positiony=''
                    for iy in range(0,nymax_cpu-nymin_cpu+1):
                        positiony=positiony+vertex[ix+iy*(nxmax_cpu-nxmin_cpu+1)]
                    command='create curve spline '+positiony
                    cubit.cmd(command)
                    #print command
                    vline.append( cubit.get_last_id("curve") )
                #
                cubit.cmd("set info "+cfg.cubit_info)
                cubit.cmd("set echo "+cfg.echo_info)
                cubit.cmd("set journal "+cfg.jou_info)
                #
                #
                print 'proc',iproc, 'lines created....',len(uline),'*',len(vline)
                umax=max(uline)
                umin=min(uline)
                vmax=max(vline)
                vmin=min(vline)
                ner=cubit.get_error_count()
                cubitcommand= 'create surface net u curve '+ str( umin )+' to '+str( umax )+ ' v curve '+ str( vmin )+ ' to '+str( vmax )+' heal'
                cubit.cmd(cubitcommand)
                ner2=cubit.get_error_count()
                if ner == ner2: 
                    command = "del curve all"
                    cubit.cmd(command)
                    isurf=isurf+1
                #
            else:
                raise NameError, 'error, check geometry_format, it should be ascii or regmesh'   #
                #
        cubitcommand= 'del vertex all'
        cubit.cmd(cubitcommand)
    if cfg.save_surface_cubit:
        savegeometry(iproc=iproc,surf=True,filename=filename)
    #
    #
    #!create volume
    if not onlysurface:
        if cfg.nz == 1:
            nsurface=2
        else:
            nsurface=cfg.nz
        for inz in range(1,nsurface):
            ner=cubit.get_error_count()
            create_volume(inz,inz+1,method=cfg.volumecreation_method)
            ner2=cubit.get_error_count()
        if ner == ner2 and not cfg.debug_geometry:
            #cubitcommand= 'del surface 1 to '+ str( cfg.nz )
            cubitcommand= 'del surface all'
            cubit.cmd(cubitcommand)
            list_vol=cubit.parse_cubit_list("volume","all")
            if len(list_vol) > 1:     
                cubitcommand= 'imprint volume all'
                cubit.cmd(cubitcommand)
                cubitcommand= 'merge all'
                cubit.cmd(cubitcommand)
            #ner=cubit.get_error_count()
            #cubitcommand= 'composite create curve in vol all'
            #cubit.cmd(cubitcommand)
    savegeometry(iproc,filename=filename)
    #if cfg.geological_imprint:
    #    curvesname=[cfg.outlinebasin_curve,cfg.transition_curve,cfg.faulttrace_curve]
    #    outdir=cfg.working_dir
    #    imprint_topography_with_geological_outline(curvesname,outdir)
    #
    #        
    cubit.cmd("set info "+cfg.cubit_info)
    cubit.cmd("set echo "+cfg.echo_info)
    cubit.cmd("set journal "+cfg.jou_info)
Esempio n. 12
0
def layercake_volume_fromacis_mpiregularmap(filename=None):
    import sys
    import start as start
    #
    mpiflag,iproc,numproc,mpi   = start.start_mpi()
    #
    cfg                         = start.start_cfg(filename=filename)                       
    #
    from utilities import geo2utm, savegeometry
    #
    from math import sqrt
    #
    try:
        mpi.barrier()
    except:
        pass
    #
    #
    command = "comment '"+"PROC: "+str(iproc)+"/"+str(numproc)+" '"
    cubit.cmd(command)
    #
    #get the limit of the volume considering the cpu
    def xwebcut(x):
        command='create planar surface with plane xplane offset '+str(x)
        cubit.cmd(command)
        last_surface=cubit.get_last_id("surface")
        command="webcut volume all tool volume in surf "+str(last_surface)
        cubit.cmd(command)
        command="del surf "+str(last_surface)
        cubit.cmd(command)
        
    def ywebcut(x):
        command='create planar surface with plane yplane offset '+str(x)
        cubit.cmd(command)
        last_surface=cubit.get_last_id("surface")
        command="webcut volume all tool volume in surf "+str(last_surface)
        cubit.cmd(command)
        command="del surf "+str(last_surface)
        cubit.cmd(command)
        
    def translate2zero():
        ss=cubit.parse_cubit_list('surface','all')
        box = cubit.get_total_bounding_box("surface", ss)
        xmin=box[0]
        ymin=box[3]
        cubit.cmd('move surface all x '+str(-1*xmin)+' y '+str(-1*ymin))
        return xmin,ymin
        
    def translate2original(xmin,ymin):
        cubit.cmd('move surface all x '+str(xmin)+' y '+str(ymin))
        
    if mpiflag:
        icpux = iproc % cfg.nproc_xi
        icpuy = int(iproc / cfg.nproc_xi)
    else:
        icpuy=int(cfg.id_proc/cfg.nproc_xi)
        icpux=cfg.id_proc%cfg.nproc_xi
    #
    ner=cubit.get_error_count()
    #
    icurve=0
    isurf=0
    ivertex=0
    #
    xlength=(cfg.xmax-cfg.xmin)/float(cfg.cpux) #length of x slide for chunk
    ylength=(cfg.ymax-cfg.ymin)/float(cfg.cpuy) #length of y slide for chunk
    xmin_cpu=cfg.xmin+(xlength*(icpux))
    ymin_cpu=cfg.ymin+(ylength*(icpuy))
    xmax_cpu=xmin_cpu+xlength
    ymax_cpu=ymin_cpu+ylength
    #
    #importing the surfaces
    for inz in range(cfg.nz-2,-2,-1):
        if cfg.bottomflat and inz==-1:
            command = "create planar surface with plane zplane offset "+str(cfg.depth_bottom)
            cubit.cmd(command)
        else:
            command = "import cubit '"+cfg.filename[inz]+"'"
            cubit.cmd(command)
            
            
    #translate
    xmin,ymin=translate2zero()
    print 'translate ...', -xmin,-ymin
    xmin_cpu=xmin_cpu-xmin
    ymin_cpu=ymin_cpu-ymin
    xmax_cpu=xmax_cpu-xmin
    ymax_cpu=ymax_cpu-ymin
    
    ss=cubit.parse_cubit_list('surface','all')
    box = cubit.get_total_bounding_box("surface", ss)
    print 'dimension... ', box
    #cutting the surfaces
    xwebcut(xmin_cpu)
    xwebcut(xmax_cpu)
    ywebcut(ymin_cpu)
    ywebcut(ymax_cpu)
    #
    list_surface_all=cubit.parse_cubit_list("surface","all")
    #condisidering only the surfaces inside the boundaries
    dict_surf={}
    for isurf in list_surface_all:
        p=cubit.get_center_point("surface",isurf)
        if p[0] < xmin_cpu or p[0] > xmax_cpu or p[1] > ymax_cpu or p[1] < ymin_cpu:
            command = "del surf "+str(isurf)
            cubit.cmd(command)
        else:
            dict_surf[str(isurf)]=p[2]
    z=dict_surf.values()
    z.sort()
    list_surf=[]
    for val in z:
        isurf=[k for k, v in dict_surf.iteritems() if v == val][0]
        list_surf.append(int(isurf))
    #
    
    #lofting the volume
    for i,j in zip(list_surf,list_surf[1:]):
        ner=cubit.get_error_count()
        create_volume(i,j,method=cfg.volumecreation_method)
        #cubitcommand= 'create volume loft surface '+ str(i)+' '+str(j)
        #cubit.cmd(cubitcommand)
        ner2=cubit.get_error_count()
    #
    translate2original(xmin,ymin)
    
    
    if ner == ner2:
        cubitcommand= 'del surface all'
        cubit.cmd(cubitcommand)
        #
        #
        #cubitcommand= 'composite create curve in vol all'
        #cubit.cmd(cubitcommand)
        list_vol=cubit.parse_cubit_list("volume","all")
        if len(list_vol) > 1:     
            cubitcommand= 'imprint volume all'
            cubit.cmd(cubitcommand)
            #cubit_error_stop(iproc,cubitcommand,ner)
            #
            cubitcommand= 'merge all'
            cubit.cmd(cubitcommand)
    #
    savegeometry(iproc,filename=filename)
Esempio n. 13
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)
Esempio n. 14
0
def quality_log(tqfile=None):
    """
    creation of the quality parameter file
    """
    import start as start
    #
    #
    mpiflag, iproc, numproc, mpi = start.start_mpi()
    #
    #
    from hex_metric import SEM_metric_3D
    #
    lvol = cubit.parse_cubit_list('volume', 'all')
    if len(lvol) != 0:
        cubit.cmd('quality vol all allmetric')
    else:
        cubit.cmd('quality hex in block all allmetric')
    cubit.cmd('list model')
    #
    toclose = True
    if isinstance(tqfile, file):
        totstat_file = tqfile
    elif isinstance(tqfile, str):
        totstat_file = open(
            tqfile + '_cubitquality_skewness_proc_' + str(iproc) + '.log', 'w')
    else:
        import sys
        totstat_file = sys.stdout
        toclose = False

    mesh = SEM_metric_3D()
    mesh.check_metric()

    if mesh.max_skewness is not None:
        mesh.skew_hystogram = mesh.hyst(0, mesh.max_skewness, mesh.skew_hyst)
        totstat_file.write('-' * 70 + '\n')

        totstat_file.write('=' * 70 + '\n')
        totstat_file.write('SKEWNESS' + '\n')
        totstat_file.write('=' * 70 + '\n')
        if len(mesh.hex_max_skewness) <= 30:
            totstat_file.write('max = ' + str(mesh.max_skewness) +
                               ' in hexes ' + str(mesh.hex_max_skewness) +
                               '\n')
            totstat_file.write('(angle -> minimun =' + str(mesh.min_angle) +
                               ' maximun =' + str(mesh.max_angle) + ')' + '\n')
        else:
            totstat_file.write('max = ' + str(mesh.max_skewness) + ' in ' +
                               str(len(mesh.hex_max_skewness)) + ' hexes ' +
                               '\n')
            totstat_file.write('(angle -> minimun =' + str(mesh.min_angle) +
                               ' maximun =' + str(mesh.max_angle) + ')' + '\n')
        totstat_file.write('-' * 70 + '\n')
        totstat_file.write('skew hystogram')
        totstat_file.write('-' * 70 + '\n')
        tot = 0
        for i in mesh.skew_hystogram.values():
            tot = tot + len(i)
        # k=mesh.skew_hystogram.keys()
        # k.sort()
        factor = mesh.max_skewness / mesh.nbin
        for i in range(0, mesh.nbin + 1):
            if i in mesh.skew_hystogram.keys():
                if (i + 1) * factor <= 1:
                    nh = len(mesh.skew_hystogram[i])
                    totstat_file.write(
                        str(i) + ' [' + str(i * factor) + '->' +
                        str((i + 1) * factor) + '[ : ' + str() + '/' +
                        str(tot) + ' hexes (' + str(nh / float(tot) * 100.) +
                        '%)' + '\n')
            else:
                if (i + 1) * factor <= 1:
                    totstat_file.write(
                        str(i) + ' [' + str(i * factor) + '->' +
                        str((i + 1) * factor) + '[ : 0/' + str(tot) +
                        ' hexes (0%)' + '\n')
        totstat_file.write('-' * 70 + '\n')
    ###############################################
    if mesh.min_edge_length is not None:
        mesh.edgemin_hystogram = mesh.hyst(mesh.min_edge_length,
                                           mesh.max_edge_length,
                                           mesh.edgemin_hyst)
        mesh.edgemax_hystogram = mesh.hyst(mesh.min_edge_length,
                                           mesh.max_edge_length,
                                           mesh.edgemax_hyst)
        totstat_file.write('=' * 70 + '\n')
        totstat_file.write('edge length')
        totstat_file.write('=' * 70 + '\n')
        if len(mesh.hex_min_edge_length) <= 30:
            totstat_file.write('minimum edge length: ' +
                               str(mesh.min_edge_length) + ' in hexes ' +
                               str(mesh.hex_min_edge_length) + '\n')
        else:
            totstat_file.write('minimum edge length: ' +
                               str(mesh.min_edge_length) + ' in ' +
                               str(len(mesh.hex_min_edge_length)) + ' hexes.' +
                               '\n')
        if len(mesh.hex_max_edge_length) <= 30:
            totstat_file.write('maximum edge length: ' +
                               str(mesh.max_edge_length) + ' in hexes ' +
                               str(mesh.hex_max_edge_length) + '\n')
        else:
            totstat_file.write('maximum edge length: ' +
                               str(mesh.max_edge_length) + ' in ' +
                               str(len(mesh.hex_max_edge_length)) + ' hexes.' +
                               '\n')
        totstat_file.write('-' * 70 + '\n')
        totstat_file.write('edge length hystogram')
        totstat_file.write('-' * 70 + '\n')
        factor = (mesh.max_edge_length - mesh.min_edge_length) / mesh.nbin
        totstat_file.write('minimum edge length' + '\n')
        tot = 0
        for i in mesh.edgemin_hystogram.values():
            tot = tot + len(i)
        # k=mesh.edgemin_hystogram.keys()
        # k.sort()
        for i in range(0, mesh.nbin + 1):
            if i in mesh.edgemin_hystogram.keys():
                totstat_file.write(
                    str(i) + ' [' + str(i * factor + mesh.min_edge_length) +
                    '->' + str((i + 1) * factor + mesh.min_edge_length) +
                    '[ : ' + str(len(mesh.edgemin_hystogram[i])) + '/' +
                    str(tot) + ' hexes (' +
                    str(len(mesh.edgemin_hystogram[i]) / float(tot) * 100.) +
                    '%)' + '\n')
            else:
                totstat_file.write(
                    str(i) + ' [' + str(i * factor + mesh.min_edge_length) +
                    '->' + str((i + 1) * factor + mesh.min_edge_length) +
                    '[ : 0/' + str(tot) + ' hexes (0%)' + '\n')
        totstat_file.write('-' * 70 + '\n')
        totstat_file.write('maximum edge length')
        tot = 0
        for i in mesh.edgemax_hystogram.values():
            tot = tot + len(i)
        # k=mesh.edgemax_hystogram.keys()
        # k.sort()
        for i in range(0, mesh.nbin + 1):
            if i in mesh.edgemax_hystogram.keys():
                totstat_file.write(
                    str(i) + ' [' + str(i * factor + mesh.min_edge_length) +
                    '->' + str((i + 1) * factor + mesh.min_edge_length) +
                    '[ : ' + str(len(mesh.edgemax_hystogram[i])) + '/' +
                    str(tot) + ' hexes (' +
                    str(len(mesh.edgemax_hystogram[i]) / float(tot) * 100.) +
                    '%)' + '\n')
            else:
                totstat_file.write(
                    str(i) + ' [' + str(i * factor + mesh.min_edge_length) +
                    '->' + str((i + 1) * factor + mesh.min_edge_length) +
                    '[ : 0/' + str(tot) + ' hexes (0%)' + '\n')
    try:
        if mesh.dt is not None:
            totstat_file.write('=' * 70 + '\n')
            totstat_file.write('STABILITY')
            totstat_file.write('=' * 70 + '\n')
            totstat_file.write('time step < ' + str(mesh.dt) +
                               's,for velocity = ' + str(mesh.velocity) + '\n')
    except:
        pass

    if toclose:
        totstat_file.close()

    print 'max specfem3d skewness: ', mesh.max_skewness
    print 'min edge length: ', mesh.min_edge_length
    return mesh.max_skewness, mesh.min_edge_length
Esempio n. 15
0
def start_cubit(init=False):
    """
    start cubit, it return the cubit object
    init argument set the monitotr files
    """
    import sys
    try:
        cubit.silent_cmd('comment')
    except:
        try:
            import cubit
            import utilities
            cubit.init([""])
        except:
            print('error importing cubit')
            sys.exit()
        try:
            if init:
                from start import start_cfg, start_mpi
                cfg = start_cfg()
                mpiflag, iproc, numproc, mpi = start_mpi()
                version_cubit = utilities.get_cubit_version()
                cubit.cmd('set logging on file "' + cfg.working_dir +
                          '/cubit_proc_' + str(iproc) + '.log"')
                cubit.cmd("set echo off")
                cubit.cmd("set info off")
                if iproc == cfg.monitored_cpu:
                    cubit.cmd("record '" + cfg.working_dir +
                              "/monitor_" + str(cfg.monitored_cpu) + ".jou'")
                    cubit.cmd("set journal on")
                    if version_cubit < 16:
                        cubit.cmd("journal error on")
                    d = cfg.__dict__
                    ks = d.keys()
                    ks.sort()
                    for k in ks:
                        if '__' not in k and '<' not in str(d[k]):
                            if d[k] is not None:
                                txt = str(k) + ' -----> ' + str(d[k])
                                txt = txt.replace("'", "").replace('"', '')
                                cubit.cmd('comment "' + txt + '"')
                else:
                    cubit.cmd("set journal " + cfg.jou_info)
                    if version_cubit < 16:
                        cubit.cmd("journal error " + cfg.jer_info)
                    d = cfg.__dict__
                    ks = d.keys()
                    ks.sort()
                    for k in ks:
                        if '__' not in k and '<' not in str(d[k]):
                            if d[k] is not None:
                                txt = str(k) + ' -----> ' + str(d[k])
                                txt = txt.replace("'", "").replace('"', '')
                                cubit.cmd('comment "' + txt + '"')
                cubit.cmd("set echo " + cfg.echo_info)
                cubit.cmd("set info " + cfg.cubit_info)
                if version_cubit > 13 and version_cubit < 15:
                    print('VERSION CUBIT ', version_cubit)
                    print('VERSIONs of CUBIT > 13 have bugs with merge node')
                    print('the merge option is not operative with this version')
                    print('please download CUBIT 15+')
                else:
                    print('VERSION CUBIT ', version_cubit)
        except:
            print('error start cubit')
            sys.exit()
    return cubit
Esempio n. 16
0
def layercake_volume_ascii_regulargrid_mpiregularmap(filename=None,
                                                     verticalsandwich=False,
                                                     onlysurface=False):
    import sys
    import start as start
    #
    mpiflag, iproc, numproc, mpi = start.start_mpi()
    #
    numpy = start.start_numpy()
    cfg = start.start_cfg(filename=filename)

    from utilities import geo2utm, savegeometry, savesurf, cubit_command_check

    from math import sqrt
    #
    try:
        mpi.barrier()
    except:
        pass
    #
    #
    command = "comment '" + "PROC: " + str(iproc) + "/" + str(numproc) + " '"
    cubit_command_check(iproc, command, stop=True)
    if verticalsandwich: cubit.cmd("comment 'Starting Vertical Sandwich'")
    #
    #get icpuy,icpux values
    if mpiflag:
        icpux = iproc % cfg.nproc_xi
        icpuy = int(iproc / cfg.nproc_xi)
    else:
        icpuy = int(cfg.id_proc / cfg.nproc_xi)
        icpux = cfg.id_proc % cfg.nproc_xi

    #
    if cfg.geometry_format == 'ascii':
        #for the original surfaces
        #number of points in the files that describe the topography
        import local_volume
        if cfg.localdir_is_globaldir:
            if iproc == 0 or not mpiflag:
                coordx_0, coordy_0, elev_0, nx_0, ny_0 = local_volume.read_grid(
                    filename)
                print 'end of reading grd files ' + str(
                    nx_0 * ny_0) + ' points'
            else:
                pass
            if iproc == 0 or not mpiflag:
                coordx = mpi.bcast(coordx_0)
            else:
                coordx = mpi.bcast()
            if iproc == 0 or not mpiflag:
                coordy = mpi.bcast(coordy_0)
            else:
                coordy = mpi.bcast()
            if iproc == 0 or not mpiflag:
                elev = mpi.bcast(elev_0)
            else:
                elev = mpi.bcast()
            if iproc == 0 or not mpiflag:
                nx = mpi.bcast(nx_0)
            else:
                nx = mpi.bcast()
            if iproc == 0 or not mpiflag:
                ny = mpi.bcast(ny_0)
            else:
                ny = mpi.bcast()
        else:
            coordx, coordy, elev, nx, ny = local_volume.read_grid(filename)
        print str(iproc) + ' end of receving grd files '
        nx_segment = int(nx / cfg.nproc_xi) + 1
        ny_segment = int(ny / cfg.nproc_eta) + 1

    elif cfg.geometry_format == 'regmesh':  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

        if cfg.depth_bottom != cfg.zdepth[0]:
            if iproc == 0:
                print 'the bottom of the block is at different depth than depth[0] in the configuration file'
        nx = cfg.nproc_xi + 1
        ny = cfg.nproc_eta + 1
        nx_segment = 2
        ny_segment = 2
        #if iproc == 0: print nx,ny,cfg.cpux,cfg.cpuy
        xp = (cfg.xmax - cfg.xmin) / float((nx - 1))
        yp = (cfg.ymax - cfg.ymin) / float((ny - 1))
        #
        elev = numpy.zeros([nx, ny, cfg.nz], float)
        coordx = numpy.zeros([nx, ny], float)
        coordy = numpy.zeros([nx, ny], float)
        #
        #
        xlength = (cfg.xmax - cfg.xmin) / float(
            cfg.nproc_xi)  #length of x slide for chunk
        ylength = (cfg.ymax - cfg.ymin) / float(
            cfg.nproc_eta)  #length of y slide for chunk
        nelem_chunk_x = 1
        nelem_chunk_y = 1
        ivxtot = nelem_chunk_x + 1
        ivytot = nelem_chunk_y + 1
        xstep = xlength  #distance between vertex on x
        ystep = ylength
        for i in range(0, cfg.nz):
            elev[:, :, i] = cfg.zdepth[i]

        icoord = 0
        for iy in range(0, ny):
            for ix in range(0, nx):
                icoord = icoord + 1
                coordx[ix, iy] = cfg.xmin + xlength * (ix)
                coordy[ix, iy] = cfg.ymin + ylength * (iy)

        #print coordx,coordy,nx,ny
    #
    print 'end of building grid ' + str(iproc)
    print 'number of point: ', len(coordx) * len(coordy)
    #
    #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    #for each processor
    #
    nxmin_cpu = (nx_segment - 1) * (icpux)
    nymin_cpu = (ny_segment - 1) * (icpuy)
    nxmax_cpu = min(nx - 1, (nx_segment - 1) * (icpux + 1))
    nymax_cpu = min(ny - 1, (ny_segment - 1) * (icpuy + 1))
    #if iproc == 0:
    #    print nx_segment,ny_segment,nx,ny
    #    print icpux,icpuy,nxmin_cpu,nxmax_cpu
    #    print icpux,icpuy,nymin_cpu,nymax_cpu
    #    print coordx[0,0],coordx[nx-1,ny-1]
    #    print coordy[0,0],coordy[nx-1,ny-1]
    #
    #
    icurve = 0
    isurf = 0
    ivertex = 0
    #
    #create vertex
    for inz in range(0, cfg.nz):
        if cfg.sea and inz == cfg.nz - 1:  #sea layer
            sealevel = True
            bathymetry = False
        elif cfg.sea and inz == cfg.nz - 2:  #bathymetry layer
            sealevel = False
            bathymetry = True
        else:
            sealevel = False
            bathymetry = False
        print sealevel, bathymetry

        if cfg.bottomflat and inz == 0:  #bottom layer
            #
            if cfg.geometry_format == 'ascii':
                lv = cubit.get_last_id("vertex")

                x_current, y_current = (coordx[nxmin_cpu,
                                               nymin_cpu], coordy[nxmin_cpu,
                                                                  nymin_cpu])
                cubitcommand = 'create vertex ' + str(x_current) + ' ' + str(
                    y_current) + ' ' + str(cfg.depth_bottom)
                cubit.cmd(cubitcommand)
                #
                x_current, y_current = (coordx[nxmin_cpu,
                                               nymax_cpu], coordy[nxmin_cpu,
                                                                  nymax_cpu])
                cubitcommand = 'create vertex ' + str(x_current) + ' ' + str(
                    y_current) + ' ' + str(cfg.depth_bottom)
                cubit.cmd(cubitcommand)
                #
                x_current, y_current = (coordx[nxmax_cpu,
                                               nymax_cpu], coordy[nxmax_cpu,
                                                                  nymax_cpu])
                cubitcommand = 'create vertex ' + str(x_current) + ' ' + str(
                    y_current) + ' ' + str(cfg.depth_bottom)
                cubit.cmd(cubitcommand)
                #
                x_current, y_current = (coordx[nxmax_cpu,
                                               nymin_cpu], coordy[nxmax_cpu,
                                                                  nymin_cpu])
                cubitcommand = 'create vertex ' + str(x_current) + ' ' + str(
                    y_current) + ' ' + str(cfg.depth_bottom)
                cubit.cmd(cubitcommand)
                #
                lv2 = cubit.get_last_id("vertex")

                cubitcommand = 'create surface vertex ' + str(
                    lv + 1) + ' to ' + str(lv2)
                cubit.cmd(cubitcommand)
                #
                isurf = isurf + 1
            else:
                lv = cubit.get_last_id("vertex")
                x_current, y_current = geo2utm(coordx[nxmin_cpu, nymin_cpu],
                                               coordy[nxmin_cpu,
                                                      nymin_cpu], 'utm')
                cubitcommand = 'create vertex ' + str(x_current) + ' ' + str(
                    y_current) + ' ' + str(cfg.depth_bottom)
                cubit.cmd(cubitcommand)
                #
                x_current, y_current = geo2utm(coordx[nxmin_cpu, nymax_cpu],
                                               coordy[nxmin_cpu,
                                                      nymax_cpu], 'utm')
                cubitcommand = 'create vertex ' + str(x_current) + ' ' + str(
                    y_current) + ' ' + str(cfg.depth_bottom)
                cubit.cmd(cubitcommand)
                #
                x_current, y_current = geo2utm(coordx[nxmax_cpu, nymax_cpu],
                                               coordy[nxmax_cpu,
                                                      nymax_cpu], 'utm')
                cubitcommand = 'create vertex ' + str(x_current) + ' ' + str(
                    y_current) + ' ' + str(cfg.depth_bottom)
                cubit.cmd(cubitcommand)
                #
                x_current, y_current = geo2utm(coordx[nxmax_cpu, nymin_cpu],
                                               coordy[nxmax_cpu,
                                                      nymin_cpu], 'utm')
                cubitcommand = 'create vertex ' + str(x_current) + ' ' + str(
                    y_current) + ' ' + str(cfg.depth_bottom)
                cubit.cmd(cubitcommand)
                #
                lv2 = cubit.get_last_id("vertex")
                cubitcommand = 'create surface vertex ' + str(
                    lv + 1) + ' to ' + str(lv2)
                cubit.cmd(cubitcommand)
                #
                isurf = isurf + 1
        else:
            if cfg.geometry_format == 'regmesh':
                zvertex = cfg.zdepth[inz]
                lv = cubit.get_last_id("vertex")
                x_current, y_current = geo2utm(coordx[nxmin_cpu, nymin_cpu],
                                               coordy[nxmin_cpu,
                                                      nymin_cpu], 'utm')
                cubitcommand = 'create vertex ' + str(x_current) + ' ' + str(
                    y_current) + ' ' + str(zvertex)
                cubit.cmd(cubitcommand)
                #
                x_current, y_current = geo2utm(coordx[nxmin_cpu, nymax_cpu],
                                               coordy[nxmin_cpu,
                                                      nymax_cpu], 'utm')
                cubitcommand = 'create vertex ' + str(x_current) + ' ' + str(
                    y_current) + ' ' + str(zvertex)
                cubit.cmd(cubitcommand)
                #
                x_current, y_current = geo2utm(coordx[nxmax_cpu, nymax_cpu],
                                               coordy[nxmax_cpu,
                                                      nymax_cpu], 'utm')
                cubitcommand = 'create vertex ' + str(x_current) + ' ' + str(
                    y_current) + ' ' + str(zvertex)
                cubit.cmd(cubitcommand)
                #
                x_current, y_current = geo2utm(coordx[nxmax_cpu, nymin_cpu],
                                               coordy[nxmax_cpu,
                                                      nymin_cpu], 'utm')
                cubitcommand = 'create vertex ' + str(x_current) + ' ' + str(
                    y_current) + ' ' + str(zvertex)
                cubit.cmd(cubitcommand)
                #
                cubitcommand = 'create surface vertex ' + str(
                    lv + 1) + ' ' + str(lv + 2) + ' ' + str(lv +
                                                            3) + ' ' + str(lv +
                                                                           4)
                cubit.cmd(cubitcommand)
                #
                isurf = isurf + 1
            elif cfg.geometry_format == 'ascii':

                vertex = []

                for iy in range(nymin_cpu, nymax_cpu + 1):
                    ivx = 0
                    for ix in range(nxmin_cpu, nxmax_cpu + 1):
                        zvertex = elev[ix, iy, inz]
                        #zvertex=adjust_sea_layers(zvertex,sealevel,bathymetry,cfg)
                        x_current, y_current = (coordx[ix, iy], coordy[ix, iy])
                        #
                        vertex.append(' Position ' + str(x_current) + ' ' +
                                      str(y_current) + ' ' + str(zvertex))
                #
                print 'proc', iproc, 'vertex list created....', len(vertex)
                n = max(nx, ny)
                uline = []
                vline = []
                iv = 0

                cubit.cmd("set info off")
                cubit.cmd("set echo off")
                cubit.cmd("set journal off")

                for iy in range(0, nymax_cpu - nymin_cpu + 1):
                    positionx = ''
                    for ix in range(0, nxmax_cpu - nxmin_cpu + 1):
                        positionx = positionx + vertex[iv]
                        iv = iv + 1
                    command = 'create curve spline ' + positionx
                    cubit.cmd(command)
                    #print command
                    uline.append(cubit.get_last_id("curve"))
                for ix in range(0, nxmax_cpu - nxmin_cpu + 1):
                    positiony = ''
                    for iy in range(0, nymax_cpu - nymin_cpu + 1):
                        positiony = positiony + vertex[
                            ix + iy * (nxmax_cpu - nxmin_cpu + 1)]
                    command = 'create curve spline ' + positiony
                    cubit.cmd(command)
                    #print command
                    vline.append(cubit.get_last_id("curve"))
                #
                cubit.cmd("set info " + cfg.cubit_info)
                cubit.cmd("set echo " + cfg.echo_info)
                cubit.cmd("set journal " + cfg.jou_info)
                #
                #
                print 'proc', iproc, 'lines created....', len(uline), '*', len(
                    vline)
                umax = max(uline)
                umin = min(uline)
                vmax = max(vline)
                vmin = min(vline)
                ner = cubit.get_error_count()
                cubitcommand = 'create surface net u curve ' + str(
                    umin) + ' to ' + str(umax) + ' v curve ' + str(
                        vmin) + ' to ' + str(vmax) + ' heal'
                cubit.cmd(cubitcommand)
                ner2 = cubit.get_error_count()
                if ner == ner2:
                    command = "del curve all"
                    cubit.cmd(command)
                    isurf = isurf + 1
                #
            else:
                raise NameError, 'error, check geometry_format, it should be ascii or regmesh'  #
                #
        cubitcommand = 'del vertex all'
        cubit.cmd(cubitcommand)
    if cfg.save_surface_cubit:
        savegeometry(iproc=iproc, surf=True, filename=filename)
    #
    #
    #!create volume
    if not onlysurface:
        if cfg.nz == 1:
            nsurface = 2
        else:
            nsurface = cfg.nz
        for inz in range(1, nsurface):
            ner = cubit.get_error_count()
            create_volume(inz, inz + 1, method=cfg.volumecreation_method)
            ner2 = cubit.get_error_count()
        if ner == ner2 and not cfg.debug_geometry:
            #cubitcommand= 'del surface 1 to '+ str( cfg.nz )
            cubitcommand = 'del surface all'
            cubit.cmd(cubitcommand)
            list_vol = cubit.parse_cubit_list("volume", "all")
            if len(list_vol) > 1:
                cubitcommand = 'imprint volume all'
                cubit.cmd(cubitcommand)
                cubitcommand = 'merge all'
                cubit.cmd(cubitcommand)
            #ner=cubit.get_error_count()
            #cubitcommand= 'composite create curve in vol all'
            #cubit.cmd(cubitcommand)
    savegeometry(iproc, filename=filename)
    #if cfg.geological_imprint:
    #    curvesname=[cfg.outlinebasin_curve,cfg.transition_curve,cfg.faulttrace_curve]
    #    outdir=cfg.working_dir
    #    imprint_topography_with_geological_outline(curvesname,outdir)
    #
    #
    cubit.cmd("set info " + cfg.cubit_info)
    cubit.cmd("set echo " + cfg.echo_info)
    cubit.cmd("set journal " + cfg.jou_info)
Esempio n. 17
0
def layercake_volume_fromacis_mpiregularmap(filename=None):
    import sys
    import start as start
    #
    mpiflag, iproc, numproc, mpi = start.start_mpi()
    #
    cfg = start.start_cfg(filename=filename)
    #
    from utilities import geo2utm, savegeometry
    #
    from math import sqrt
    #
    try:
        mpi.barrier()
    except:
        pass
    #
    #
    command = "comment '" + "PROC: " + str(iproc) + "/" + str(numproc) + " '"
    cubit.cmd(command)

    #
    #get the limit of the volume considering the cpu
    def xwebcut(x):
        command = 'create planar surface with plane xplane offset ' + str(x)
        cubit.cmd(command)
        last_surface = cubit.get_last_id("surface")
        command = "webcut volume all tool volume in surf " + str(last_surface)
        cubit.cmd(command)
        command = "del surf " + str(last_surface)
        cubit.cmd(command)

    def ywebcut(x):
        command = 'create planar surface with plane yplane offset ' + str(x)
        cubit.cmd(command)
        last_surface = cubit.get_last_id("surface")
        command = "webcut volume all tool volume in surf " + str(last_surface)
        cubit.cmd(command)
        command = "del surf " + str(last_surface)
        cubit.cmd(command)

    def translate2zero():
        ss = cubit.parse_cubit_list('surface', 'all')
        box = cubit.get_total_bounding_box("surface", ss)
        xmin = box[0]
        ymin = box[3]
        cubit.cmd('move surface all x ' + str(-1 * xmin) + ' y ' +
                  str(-1 * ymin))
        return xmin, ymin

    def translate2original(xmin, ymin):
        cubit.cmd('move surface all x ' + str(xmin) + ' y ' + str(ymin))

    if mpiflag:
        icpux = iproc % cfg.nproc_xi
        icpuy = int(iproc / cfg.nproc_xi)
    else:
        icpuy = int(cfg.id_proc / cfg.nproc_xi)
        icpux = cfg.id_proc % cfg.nproc_xi
    #
    ner = cubit.get_error_count()
    #
    icurve = 0
    isurf = 0
    ivertex = 0
    #
    xlength = (cfg.xmax - cfg.xmin) / float(
        cfg.cpux)  #length of x slide for chunk
    ylength = (cfg.ymax - cfg.ymin) / float(
        cfg.cpuy)  #length of y slide for chunk
    xmin_cpu = cfg.xmin + (xlength * (icpux))
    ymin_cpu = cfg.ymin + (ylength * (icpuy))
    xmax_cpu = xmin_cpu + xlength
    ymax_cpu = ymin_cpu + ylength
    #
    #importing the surfaces
    for inz in range(cfg.nz - 2, -2, -1):
        if cfg.bottomflat and inz == -1:
            command = "create planar surface with plane zplane offset " + str(
                cfg.depth_bottom)
            cubit.cmd(command)
        else:
            command = "import cubit '" + cfg.filename[inz] + "'"
            cubit.cmd(command)

    #translate
    xmin, ymin = translate2zero()
    print 'translate ...', -xmin, -ymin
    xmin_cpu = xmin_cpu - xmin
    ymin_cpu = ymin_cpu - ymin
    xmax_cpu = xmax_cpu - xmin
    ymax_cpu = ymax_cpu - ymin

    ss = cubit.parse_cubit_list('surface', 'all')
    box = cubit.get_total_bounding_box("surface", ss)
    print 'dimension... ', box
    #cutting the surfaces
    xwebcut(xmin_cpu)
    xwebcut(xmax_cpu)
    ywebcut(ymin_cpu)
    ywebcut(ymax_cpu)
    #
    list_surface_all = cubit.parse_cubit_list("surface", "all")
    #condisidering only the surfaces inside the boundaries
    dict_surf = {}
    for isurf in list_surface_all:
        p = cubit.get_center_point("surface", isurf)
        if p[0] < xmin_cpu or p[0] > xmax_cpu or p[1] > ymax_cpu or p[
                1] < ymin_cpu:
            command = "del surf " + str(isurf)
            cubit.cmd(command)
        else:
            dict_surf[str(isurf)] = p[2]
    z = dict_surf.values()
    z.sort()
    list_surf = []
    for val in z:
        isurf = [k for k, v in dict_surf.iteritems() if v == val][0]
        list_surf.append(int(isurf))
    #

    #lofting the volume
    for i, j in zip(list_surf, list_surf[1:]):
        ner = cubit.get_error_count()
        create_volume(i, j, method=cfg.volumecreation_method)
        #cubitcommand= 'create volume loft surface '+ str(i)+' '+str(j)
        #cubit.cmd(cubitcommand)
        ner2 = cubit.get_error_count()
    #
    translate2original(xmin, ymin)

    if ner == ner2:
        cubitcommand = 'del surface all'
        cubit.cmd(cubitcommand)
        #
        #
        #cubitcommand= 'composite create curve in vol all'
        #cubit.cmd(cubitcommand)
        list_vol = cubit.parse_cubit_list("volume", "all")
        if len(list_vol) > 1:
            cubitcommand = 'imprint volume all'
            cubit.cmd(cubitcommand)
            #cubit_error_stop(iproc,cubitcommand,ner)
            #
            cubitcommand = 'merge all'
            cubit.cmd(cubitcommand)
    #
    savegeometry(iproc, filename=filename)
Esempio n. 18
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
Esempio n. 19
0
 if o in ('--x3'):
     x3 = value
 if o in ('--x4'):
     x4 = value
 if o in ('--unit'):
     unit = value
 #
 if o in ('--build_volume'):
     build_volume = True
 if o in ("-h", "--help"):
     usage()
     sys.exit(2)
 # check the configuration
 if o in ("--chklib"):
     import start as start
     mpiflag, iproc, numproc, mpi = start.start_mpi()
     if mpiflag:
         print '--------, MPI ON, parallel mesher ready'
     else:
         print '--------, MPI OFF, serial mesher ready'
     numpy = start.start_numpy()
     print '--------, Numpy ON'
     cubit = start.start_cubit()
     print '--------, CUBIT ON'
     sys.exit()
 if o in ("--cfg"):
     cfg_name = value
     try:
         if open(cfg_name):
             pass
     except IOError, e:
Esempio n. 20
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
Esempio n. 21
0
def quality_log(tqfile=None):
    """
    creation of the quality parameter file
    """
    import start as start
    #
    #
    mpiflag,iproc,numproc,mpi   = start.start_mpi()
    #
    #
    from hex_metric import SEM_metric_3D
    #
    lvol=cubit.parse_cubit_list('volume','all')
    if len(lvol)!=0:
        cubit.cmd('quality vol all allmetric                                      ')
    else:
        cubit.cmd('quality hex in block all allmetric                                      ')
    cubit.cmd('list model                                                      ')
    #
    toclose=True
    if isinstance(tqfile,file): 
        totstat_file=tqfile
    elif isinstance(tqfile,str):
        totstat_file=open(tqfile+'_cubitquality_skewness_proc_'+str(iproc)+'.log','w')
    else:
        import sys
        totstat_file=sys.stdout
        toclose=False
    
    mesh=SEM_metric_3D()
    mesh.check_metric()
    
    if mesh.max_skewness is not None:
        mesh.skew_hystogram=mesh.hyst(0,mesh.max_skewness,mesh.skew_hyst)
        totstat_file.write('-'*70+'\n')
        
        
        
        
        
        totstat_file.write('='*70+'\n')
        totstat_file.write('SKEWNESS'+'\n')
        totstat_file.write('='*70+'\n') 
        if len(mesh.hex_max_skewness) <= 30:
            totstat_file.write('max = '+str(mesh.max_skewness)+' in hexes '+str(mesh.hex_max_skewness)+'\n')
            totstat_file.write('(angle -> minimun ='+str(mesh.min_angle)+ ' maximun ='+str(mesh.max_angle)+')'+'\n')
        else:
            totstat_file.write('max = '+str(mesh.max_skewness)+' in '+str(len(mesh.hex_max_skewness))+' hexes '+'\n')
            totstat_file.write('(angle -> minimun ='+str(mesh.min_angle)+' maximun ='+str(mesh.max_angle)+')'+'\n')
        totstat_file.write('-'*70+'\n')
        totstat_file.write('skew hystogram')
        totstat_file.write('-'*70+'\n')
        tot=0
        for i in mesh.skew_hystogram.values():
            tot=tot+len(i)
        #k=mesh.skew_hystogram.keys()
        #k.sort()
        factor=mesh.max_skewness/mesh.nbin
        for i in range(0,mesh.nbin+1):
            if mesh.skew_hystogram.has_key(i):
                if (i+1)*factor <= 1:
                    totstat_file.write(str(i)+' ['+str(i*factor)+'->'+str((i+1)*factor)+'[ : '+str(len(mesh.skew_hystogram[i]))+'/'+str(tot)+' hexes ('+str(len(mesh.skew_hystogram[i])/float(tot)*100.)+'%)'+'\n')
            else:
                if (i+1)*factor <= 1:
                    totstat_file.write(str(i)+' ['+str(i*factor)+'->'+str((i+1)*factor)+'[ : 0/'+str(tot)+' hexes (0%)'+'\n')
        totstat_file.write('-'*70+'\n')
    ###############################################
    if mesh.min_edge_length is not None:
        mesh.edgemin_hystogram=mesh.hyst(mesh.min_edge_length,mesh.max_edge_length,mesh.edgemin_hyst)
        mesh.edgemax_hystogram=mesh.hyst(mesh.min_edge_length,mesh.max_edge_length,mesh.edgemax_hyst)
        totstat_file.write('='*70+'\n')
        totstat_file.write('edge length')
        totstat_file.write('='*70+'\n')
        if len(mesh.hex_min_edge_length) <= 30:
            totstat_file.write('minimum edge length: '+str(mesh.min_edge_length)+ ' in hexes '+str(mesh.hex_min_edge_length)+'\n')
        else:
            totstat_file.write('minimum edge length: '+str(mesh.min_edge_length)+ ' in '+str(len(mesh.hex_min_edge_length))+ ' hexes.'+'\n')
        if len(mesh.hex_max_edge_length) <= 30:
            totstat_file.write('maximum edge length: '+str(mesh.max_edge_length)+ ' in hexes '+str(mesh.hex_max_edge_length)+'\n')              
        else:                                                                                                                        
            totstat_file.write('maximum edge length: '+str(mesh.max_edge_length)+' in '+str(len(mesh.hex_max_edge_length))+ ' hexes.'+'\n')    
        totstat_file.write('-'*70+'\n')
        totstat_file.write('edge length hystogram')
        totstat_file.write('-'*70+'\n')
        factor=(mesh.max_edge_length-mesh.min_edge_length)/mesh.nbin
        totstat_file.write('minimum edge length'+'\n')
        tot=0
        for i in mesh.edgemin_hystogram.values():
            tot=tot+len(i)
        #k=mesh.edgemin_hystogram.keys()
        #k.sort()
        for i in range(0,mesh.nbin+1):
            if mesh.edgemin_hystogram.has_key(i):
                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : '+str(len(mesh.edgemin_hystogram[i]))+'/'+str(tot)+' hexes ('+str(len(mesh.edgemin_hystogram[i])/float(tot)*100.)+'%)'+'\n')
            else:
                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : 0/'+str(tot)+' hexes (0%)'+'\n')
        totstat_file.write('-'*70+'\n')
        totstat_file.write('maximum edge length')
        tot=0
        for i in mesh.edgemax_hystogram.values():
            tot=tot+len(i)
        #k=mesh.edgemax_hystogram.keys()
        #k.sort()
        for i in range(0,mesh.nbin+1):
            if mesh.edgemax_hystogram.has_key(i):
                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : '+str(len(mesh.edgemax_hystogram[i]))+'/'+str(tot)+' hexes ('+str(len(mesh.edgemax_hystogram[i])/float(tot)*100.)+'%)'+'\n')
            else:
                totstat_file.write(str(i)+' ['+str(i*factor+mesh.min_edge_length)+'->'+str((i+1)*factor+mesh.min_edge_length)+'[ : 0/'+str(tot)+' hexes (0%)'+'\n')
    try:
        if mesh.dt is not None:
            totstat_file.write('='*70+'\n')
            totstat_file.write('STABILITY')
            totstat_file.write('='*70+'\n')
            totstat_file.write('time step < '+str(mesh.dt)+'s, for velocity = '+str(mesh.velocity)+'\n')
    except:
        pass
    
    if toclose: 
        totstat_file.close()
    
    print 'max specfem3d skewness: ',mesh.max_skewness
    print 'min edge length: ',mesh.min_edge_length
    return mesh.max_skewness,mesh.min_edge_length
Esempio n. 22
0
def read_grid(filename=None):
    import sys
    import start as start
    mpiflag,iproc,numproc,mpi   = start.start_mpi()
    #
    numpy                       = start.start_numpy()
    cfg                         = start.start_cfg(filename=filename)
    from utilities import geo2utm
    
    #if cfg.irregulargridded_surf==True then cfg.nx and cfg.ny are the desired number of point along the axis....
    if cfg.nx and cfg.ny:
        nx=cfg.nx
        ny=cfg.ny
        if cfg.nstep:
            nx=min(cfg.nx,int(cfg.nx/cfg.nstep)+1)
            ny=min(cfg.ny,int(cfg.ny/cfg.nstep)+1)
            nstep=cfg.nstep
        else:
            nstep=1
    else:
        try:
            xstep=cfg.step
            ystep=cfg.step
        except:
            xstep=cfg.xstep
            ystep=cfg.ystep
        nx= int((cfg.longitude_max-cfg.longitude_min)/xstep)+1
        ny= int((cfg.latitude_max-cfg.latitude_min)/ystep)+1
        nstep=1
    #
    
    if cfg.irregulargridded_surf:
        xt,xstep=numpy.linspace(cfg.xmin, cfg.xmax, num=nx, retstep=True)
        yt,ystep=numpy.linspace(cfg.ymin, cfg.ymax, num=ny, retstep=True)
    
    elev=numpy.zeros([nx,ny,cfg.nz],float)
    #
    if  cfg.bottomflat: 
        elev[:,:,0] = cfg.depth_bottom
        bottomsurface=1
    else:
        bottomsurface=0
        
    for inz in range(bottomsurface,cfg.nz-1):
        grdfilename=cfg.filename[inz-bottomsurface]

        if cfg.irregulargridded_surf:
            coordx,coordy,elev_1=process_irregular_surfacefiles(iproc,nx,ny,cfg.xmin,cfg.xmax,cfg.ymin,cfg.ymax,xstep,ystep,grdfilename)
        else:
            coordx,coordy,elev_1=process_surfacefiles(iproc,nx,ny,nstep,grdfilename,cfg.unit,cfg.lat_orientation)
        elev[:,:,inz]=elev_1[:,:]
        #
    
    inz=cfg.nz-1 #last surface
    if cfg.sea:
        elev[:,:,inz]=elev[:,:,inz-1]
    else:
        #try:
        grdfile = cfg.filename[inz-bottomsurface]
        print 'reading ',cfg.filename[inz-bottomsurface]
        if cfg.irregulargridded_surf:
            coordx,coordy,elev_1=process_irregular_surfacefiles(iproc,nx,ny,cfg.xmin,cfg.xmax,cfg.ymin,cfg.ymax,xstep,ystep,grdfile)
        else:
            coordx,coordy,elev_1=process_surfacefiles(iproc,nx,ny,nstep,grdfile,cfg.unit,cfg.lat_orientation)
        elev[:,:,inz]=elev_1[:,:]
        #except:
        #     txt='error reading: '+  str( cfg.filename[inz-bottomsurface] )
        #    raise NameError, txt
        
        
        if cfg.subduction:
          print 'subduction'
          top=elev[:,:,inz]
          slab=elev[:,:,inz-1]
          subcrit=numpy.abs(top-slab)<cfg.subduction_thres
          top[subcrit]=slab[subcrit]+cfg.subduction_thres
          print len(top[subcrit])
          elev[:,:,inz]=top
    return coordx,coordy,elev,nx,ny
Esempio n. 23
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)