Exemple #1
0
def demo_create_cylinder (dstdir):
  # hardcode path for testing purpose
  try:
      Repository.Delete("cyl")
      Repository.Delete("resultCyl")
  except:
      pass
  cyl=Solid.pySolidModel()
  ctrL=[0.,0.,15.]
  axisL=[0.,0.,1.]
  cyl.Cylinder('cyl',2.,30.,ctrL,axisL)
  cyl.GetPolyData('resultCyl',0.5)
  cyl.GetBoundaryFaces(90)
  print ("Creating model: \nFaceID found: " + str(cyl.GetFaceIds()))
  cyl.WriteNative(dstdir + "/cylinder.vtp")
  from shutil import copyfile
  copyfile("cylinder.vtp.facenames2",dstdir + "/cylinder.vtp.facenames")  
  return dstdir+"/cylinder.vtp"
Exemple #2
0
def demo_create_model (dstdir):
  # just copy the model for now
  try:
      Repository.Delete("cyl")
  except:
      pass
  cyl=Solid.pySolidModel()
  cyl.ReadNative("cyl","cylinder.vtp")
  from shutil import copyfile
  copyfile("cylinder.vtp",dstdir + "/cylinder.vtp")
  copyfile("cylinder.vtp.facenames",dstdir + "/cylinder.vtp.facenames")  
  return dstdir+"/cylinder.vtp"
def demo_create_model(dstdir):
    # just copy the model for now
    # hardcode path for testing purpose
    try:
        Repository.Delete("bifurcation")
    except:
        pass
    cyl = Solid.pySolidModel()
    cyl.ReadNative("bifurcation", "bifurcation.vtp")
    from shutil import copyfile
    copyfile("bifurcation.vtp", dstdir + "/bifurcation.vtp")
    copyfile("bifurcation.vtp.facenames",
             dstdir + "/bifurcation.vtp.facenames")
    return dstdir + "/bifurcation.vtp"
def pulsatile_cylinder_create_mesh_TetGen(solidfn, dstdir,
                                          pulsatile_mesh_option):

    #
    #  Mesh the solid
    #

    print("Creating mesh.")

    # create meshsim style script file
    fp = open(dstdir + '/cylinder.tgs', 'w+')
    fp.write("msinit\n")
    fp.write("logon %s \n" % (dstdir + '/cylinder.logfile'))
    fp.write("loadModel %s\n" % solidfn)
    fp.write("setSolidModel\n")
    fp.write("newMesh\n")
    fp.write("option surface 1\n")
    fp.write("option volume 1\n")
    fp.write("option GlobalEdgeSize 0.75\n")
    fp.write("wallFaces wall\n")
    if pulsatile_mesh_option == 'Boundary Layer Mesh':
        fp.write("boundaryLayer 3 0.5 0.7\n")
    fp.write("option QualityRatio 1.4\n")
    fp.write("option NoBisect 1\n")
    fp.write("generateMesh\n")
    if pulsatile_mesh_option == 'Boundary Layer Mesh':
        fp.write("getBoundaries\n")
    fp.write("writeMesh %s vtu 0\n" % (dstdir + '/cylinder.sms'))
    fp.write("deleteMesh\n")
    fp.write("deleteModel\n")
    fp.write("logoff\n")
    fp.close()

    try:
        Repository.Delete("mymesh")
    except:
        pass

    mesh_utils.mesh_readTGS(dstdir + '/cylinder.tgs', 'mymesh')

    print("Writing out mesh surfaces.")
    os.mkdir(dstdir + '/mesh-complete')
    os.mkdir(dstdir + '/mesh-complete/mesh-surfaces')

    mesh_utils.mesh_writeCompleteMesh('mymesh', 'cyl', 'cylinder',
                                      dstdir + '/mesh-complete')
Exemple #5
0
def mesh_readTGS(filename, resObjName):
    #@author Fanwei Kong based on tetgen.tcl
    #@c This function processes a tetgen style meshing
    #@c script file.
    #@a filename:  script filename.
    #@a resObj:  resulting repository MeshObject.
    #@note resObj is not deleted, even if the script file
    #@note specifies deleteModel and deleteMesh.

    if (int(Repository.Exists(resObjName)) != 0):
        raise ValueError("object" + resObjName + "already exists!")
        return

    solid = "/tmp/mesh_readTGS/solid"
    try:
        Repository.Delete(solid)
    except:
        pass
    global guiMMvars
    guiMMvars['meshGenerateVolumeMesh'] = 0
    global guiPDvars
    global guiTGvars
    geom = Solid.pySolidModel()
    resObj = MeshObject.pyMeshObject()
    MeshObject.SetKernel(pc.gOptions['meshing_kernel'])
    resObj.NewObject(resObjName)
    resObj.SetSolidKernel(pc.gOptions['meshing_solid_kernel'])
    # lookup for type
    types = {}
    types[1] = 1
    types[2] = 2
    types['absolute'] = 1
    types['relative'] = 2
    types['abs'] = 1
    types['rel'] = 2
    sides = {}
    sides['negative'] = 0
    sides['positive'] = 1
    sides['both'] = 2
    sides[0] = 0
    sides[1] = 1
    sides[2] = 2
    fp = open(filename, 'r')
    for line in fp:
        # skip comment lines
        if (line[0:2] == "\#"):
            print("ignoring line: <$line>")
            continue
        # supported commands
        if (line.split()[0] == "logon"):
            MeshObject.Logon(line.split()[1])
        elif (line.split()[0] == "logoff"):
            MeshObject.Logoff
        elif (line.split()[0] == "newMesh"):
            resObj.NewMesh()
        elif (line.split()[0] == "generateMesh"):
            resObj.GenerateMesh()
        elif (line.split()[0] == "loadModel"):
            resObj.LoadModel(line.split()[1])
            try:
                Repository.Delete(solid)
            except:
                pass
            solidfn = line.split()[1]
            geom.ReadNative(solid, solidfn)
            #set smasherInputName $solid
            if (pc.gOptions['meshing_solid_kernel'] == "PolyData"):
                global gPolyDataFaceNames
                global gPolyDataFaceNamesInfo
                if (os.path.isfile(line.split()[1] + '.facenames')):
                    with open(line.split()[1] + '.facenames') as f:
                        exec(f.read())
                #import hashlib
                #hashlib.md5(open(line.split()[1],'rb').read()).hexdigest()
            #if {$mymd5 != $gPolyDataFaceNamesInfo(model_file_md5)} {
            #  return -code error "ERROR: polydata model ([lrange $line 1 end]) file doesn't match one used to generate facenames ([lindex $line 1].facenames)!"
            #}
            else:
                print("Getting Solid Boundaries...")
                gInputReturnVar = 50.0
                gInputReturnVar = input(
                    "Boundary Extraction"
                    "Enter Boundary Extraction Angle (0-90 degrees):")
                guiPDvars['angleForBoundaries'] = gInputReturnVar
                geom.GetBoundaryFaces(gInputReturnVar)
                allids = geom.GetFaceIds()
                numfaces = len(allids)
                yesno = input(
                    "The number of surfaces found was: %i.  Is this the correct number of surfaces on your polydata? yes/no"
                    % numfaces)
                if (yesno == "no"):
                    raise ValueError(
                        "Try again with a different boundary extraction angle or check the surface of the polydata for deteriorated elements."
                    )
                    return
                for newid in allids:
                    gPolyDataFaceNames[newid] = "noname_" + str(newid)
        elif (line.split()[0] == "setSolidModel"):
            solidPD = "/tmp/solid/pd"
            try:
                Repository.Delete(solidPD)
            except:
                pass
            #Set the polydatasolid in the mesh object to the current solid model
            geom.GetPolyData(solidPD)
            resObj.SetVtkPolyData(solidPD)
        elif (line.split()[0] == "localSize"):
            facename = line.split()[1]
            if (facename == ""):
                raise ValueError(
                    "ERROR: Must select a face to add local mesh size on !")
                return
            faceids = geom.GetFaceIds()
            for ids in faceids:
                if (gPolyDataFaceNames[ids] == facename):
                    regionid = ids
            resObj.SetMeshOptions("LocalEdgeSize", [float(line.split()[1])])
        elif (line.split()[0] == "useCenterlineRadius"):
            if (int(guiTGvars['meshWallFirst']) != 1):
                raise ValueError(
                    "ERROR: Must select wall faces for centerline extraction")
                return
            cappedsolid = "/tmp/solid/cappedpd"
            try:
                Repository.Delete(cappedsolid)
            except:
                pass
            cappedsolid = PolyDataVMTKGetCenterIds(resObj, "mesh")
            polys = PolyDataVMTKCenterlines(cappedsolid, resObj, "mesh")
            resObj.SetVtkPolyData(polys[0])
        elif (line.split()[0] == "functionBasedMeshing"):
            resObj.SetSizeFunctionBasedMesh(float(line.split()[1]),
                                            float(line.split()[2]))
        elif (line.split()[0] == "sphereRefinement"):
            resObj.SetSphereRefinement(float(line.split()[1]),
                                       float(line.split()[2]),
                                       [float(i) for i in line.split()[3:]])
        elif (line.split()[0] == "wallFaces"):
            guiTGvars['meshWallFirst'] = 1
            resObj.SetMeshOptions("MeshWallFirst", [1])
            walls = []
            for i in range(1, len(line.split())):
                name = line.split()[i]
                name_id = return_face_id(geom, name)
                walls.append(name_id)
            resObj.SetWalls(walls)
        elif (line.split()[0] == "boundaryLayer"):
            if (guiTGvars['meshWallFirst'] != 1):
                raise ValueError(
                    "ERROR: Must select wall faces for boundary layer")
                return
            resObj.SetBoundaryLayer(0, 0, 0, int(line.split()[1]),
                                    [float(i) for i in line.split()[2:]])
        elif (line.split()[0] == "tolerance"):
            resObj.SetTolerance(float(line.split()[1]))
        elif (line.split()[0] == "quality"):
            resObj.SetQuality(line.split()[1])
        elif (line.split()[0] == "writeMesh"):
            resObj.WriteMesh(line.split()[1], int(line.split()[-1]))
        elif (line.split()[0] == "option"):
            if (len(line.split()) == 3):
                if (line.split()[1] == "surface"):
                    resObj.SetMeshOptions("SurfaceMeshFlag",
                                          [int(line.split()[2])])
                elif (line.split()[1] == "volume"):
                    resObj.SetMeshOptions("VolumeMeshFlag",
                                          [int(line.split()[2])])
                    guiMMvars['meshGenerateVolumeMesh'] = 1
                elif (line.split()[1] == "gsize"):
                    resObj.SetMeshOptions("GlobalEdgeSize",
                                          [float(line.split()[2])])
                elif (line.split()[1] == "a"):
                    resObj.SetMeshOptions("GlobalEdgeSize",
                                          [float(line.split()[2])])
                else:
                    #lappend mylist [lindex $line 2]
                    resObj.SetMeshOptions(line.split()[1],
                                          [float(line.split()[2])])
            else:
                for lineval in line.split():
                    resObj.SetMeshOptions(lineval, [1])
        elif (line.split()[0] == "getBoundaries"):
            resObj.GetBoundaryFaces(guiPDvars['angleForBoundaries'])
        else:
            print("ignoring line: " + line)
    fp.close()
    try:
        Repository.Delete(solid)
    except:
        pass
Exemple #6
0
def mesh_writeCompleteMesh(meshName, solidName, prefix, outdir):
    global guiMMvars
    global gFilenames
    solid = Solid.pySolidModel()
    solid.GetModel(solidName)
    kernel = solid.GetKernel()

    mesh = MeshObject.pyMeshObject()
    mesh.GetMesh(meshName)

    try:
        os.mkdir(outdir + '/mesh-surfaces')
        os.mkdir(outdir + '/misc')
    except:
        pass

    ug = "myug"
    pd = "mypd"
    facepd = "myfacepd"

    try:
        Repository.Delete(ug)
    except:
        pass
    try:
        Repository.Delete(pd)
    except:
        pass
    try:
        Repository.Delete(facepd)
    except:
        pass

    if (kernel == "PolyData" and guiMMvars['meshGenerateVolumeMesh'] != 1):
        pass
    else:
        mesh.GetUnstructuredGrid(ug)
        ugwriter = vtk.vtkXMLUnstructuredGridWriter()
        ugwriter.SetCompressorTypeToZLib()
        ugwriter.EncodeAppendedDataOff()
        ugwriter.SetInputDataObject(Repository.ExportToVtk(ug))
        ugwriter.SetFileName(outdir + '/' + prefix + '.mesh.vtu')
        ugwriter.Write()
        del ugwriter

    mesh.GetPolyData(pd)

    pdwriter = vtk.vtkXMLPolyDataWriter()
    pdwriter.SetCompressorTypeToZLib()
    pdwriter.EncodeAppendedDataOff()
    pdwriter.SetInputDataObject(Repository.ExportToVtk(pd))
    pdwriter.SetFileName(outdir + '/' + prefix + '.exterior.vtp')
    pdwriter.Write()

    foundWall = 0
    appender = vtk.vtkAppendPolyData()
    appender.UserManagedInputsOff()

    foundStent = 0
    Sappender = vtk.vtkAppendPolyData()
    Sappender.UserManagedInputsOff()

    name_to_identifier = {}
    identifier_to_name = {}
    facestr = mesh.GetModelFaceInfo()
    facename = ""
    for faceinfo in facestr.split("  "):
        faceinfo = faceinfo.replace(" ", "")
        faceinfo = faceinfo.replace("{", "")
        faceinfo = faceinfo.replace("}", "")
        i = faceinfo[0]
        ident = faceinfo[1]
        if (kernel == "Parasolid"):
            try:
                facename = faceinfo[2]
            except:
                pass
        elif (kernel == "Discrete"):
            global gDiscreteModelFaceNames
            try:
                facename = gDiscreteModelFaceNames[i]
            except:
                pass
        elif (kernel == "PolyData"):
            global gPolyDataFaceNames
            try:
                facename = gPolyDataFaceNames[i]
            except:
                pass
        else:
            raise ValueError("ERROR: invalid solid kernel" + kernel)
            return
        if (facename == ""):
            facename = "missing_" + i + "\_" + ident
        elif ("noname" in facename.lower()):
            print(facename + " is not being written because it has no_name")
        else:
            name_to_identifier[facename] = ident
            identifier_to_name[ident] = facename
            try:
                Repository.Delete(facepd)
            except:
                pass
        try:
            mesh.GetFacePolyData(facepd, int(i))
        except:
            print("Warning face %s not found, skipping face" % i)
            pass
        pdwriter.SetInputDataObject(Repository.ExportToVtk(facepd))
        pdwriter.SetFileName(outdir + '/mesh-surfaces/' + facename + '.vtp')
        pdwriter.Write()
        if "wall" in facename:
            foundWall = 1
            appender.AddInputData(Repository.ExportToVtk(facepd))
        if "stent" in facename:
            foundStent = 1
            appender.AddInputData(Repository.ExportToVtk(facepd))
        try:
            Repository.Delete(facepd)
        except:
            pass

    if (foundWall):
        appender.Update()
        cleaner = vtk.vtkCleanPolyData()
        cleaner.PointMergingOn()
        cleaner.PieceInvariantOff()
        cleaner.SetInputDataObject(appender.GetOutput())
        cleaner.Update()
        pdwriter.SetFileName(outdir + '/walls_combined.vtp')
        pdwriter.SetInputDataObject(cleaner.GetOutput())
        pdwriter.Write()
        del cleaner
        del appender

    if (foundStent):
        Sappender.Update()
        Scleaner = vtk.vtkCleanPolyData()
        Scleaner.PointMergingOn()
        Scleaner.PieceInvariantOff()
        Scleaner.SetInputDataObject(Sappender.GetOutput())
        Scleaner.Update()
        pdwriter.SetFileName(outdir + '/stent_combined.vtp')
        pdwriter.SetInputDataObject(Scleaner.GetOutput())
        del pdwriter
        del Scleaner
    del Sappender

    #$mesh WriteMetisAdjacency -file $outdir/$prefix.xadj
    #mesh_kernel = mesh.GetKernel()
    #if (mesh_kernel == "TetGen"):
    #  gFilenames['tet_mesh_script_file'] = outdir+ "/" + prefix
    #  guiMMcreateTetGenScriptFile
    #elif (mesh_kernel == "MeshSim"):
    #  gFilenames['mesh_script_file'] = outdir + "/" + prefix
    #  guiMMcreateMeshSimScriptFile
    #  mesh.WriteMesh(outdir+'/'+prefix+'.sms')

    try:
        Repository.Delete(ug)
    except:
        pass
    try:
        Repository.Delete(pd)
    except:
        pass
    try:
        Repository.Delete(facepd)
    except:
        pass
Exemple #7
0
def demo_loft_cylinder(dstdir):
    Contour.SetContourKernel('Circle')
    try:
        Repository.Delete('path')
        Repository.Delete('ct')
        Repository.Delete('ct2')
    except:
        pass
    #generate path
    p = Path.pyPath()
    p.NewObject('path')
    p.AddPoint([0.,0.,0.])
    p.AddPoint([0.,0.,30.])
    p.CreatePath()
    num = p.GetPathPtsNum()
    
    #create two contours
    c = Contour.pyContour()
    c.NewObject('ct','path',0)
    c.SetCtrlPtsByRadius([0.,0.,0.],2)
    c.Create()
    print ("Contour created: area is: " + str(c.Area()) + "; center is: " +str(c.Center()))
    
    c2 = Contour.pyContour()
    c2.NewObject('ct2','path',num-1)
    c2.SetCtrlPtsByRadius([0.,0.,30.],2)
    c2.Create()
    print ("Contour created: area is: " + str(c2.Area()) + "; center is: " +str(c2.Center()))
    c.GetPolyData('ctp')
    c2.GetPolyData('ct2p')
    
    #processing the contours
    numOutPtsAlongLength = 12
    numPtsInLinearSampleAlongLength = 240
    numLinearPtsAlongLength = 120
    dstName='loft'
    numOutPtsInSegs = 60
    numModes = 20
    useFFT = 0
    useLinearSampleAlongLength = 1

    Geom.SampleLoop('ctp',numOutPtsInSegs,'ctps')
    Geom.SampleLoop('ct2p',numOutPtsInSegs,'ct2ps')
    Geom.AlignProfile('ctps','ct2ps','ct2psa',0)

    srcList = ['ctps','ct2psa']
    Geom.LoftSolid(srcList,dstName,numOutPtsInSegs,numOutPtsAlongLength,numLinearPtsAlongLength,numModes,useFFT,useLinearSampleAlongLength)
    #cap the cylinder
    VMTKUtils.Cap_with_ids(dstName,'cap',0,0)

    solid = Solid.pySolidModel()
    solid.NewObject('cyl')
    solid.SetVtkPolyData('cap')
    solid.GetBoundaryFaces(90)
    print ("Creating model: \nFaceID found: " + str(solid.GetFaceIds()))
    solid.WriteNative(dstdir + "/cylinder.vtp")
    
    Repository.Delete('ctp')
    Repository.Delete('ct2p')
    Repository.Delete('ct2ps')
    Repository.Delete(dstName)
    Repository.Delete('cap')
    Repository.Delete('path')
    
    from shutil import copyfile
    copyfile("cylinder.vtp.facenames2",dstdir + "/cylinder.vtp.facenames")  
    return dstdir+"/cylinder.vtp"
Exemple #8
0
T = 0.2
Vbar = 135
radius = 2.0
omega = 2.0*math.pi/T

pts = []
for i in range(0,256):
    dt = T/255.0
    t = float(i)*dt
    Vmean = Vbar*(1.0+math.sin(2*math.pi*t/T))
    area = math.pi*radius*radius
    pts.append([t, -Vmean*area])
    
terms = Math.FFT(pts, 2,256)
try:
    Repository.Delete('outflow')
except:
    pass
    
import os
import stat
os.chmod(fullrundir+'/mesh-complete/mesh-surfaces', 0o777)
Repository.ReadXMLPolyData('outflow',fullrundir+'/mesh-complete/mesh-surfaces/outlet.vtp')
numPts = Geom.NumPts('outflow')
outflowObj = Repository.ExportToVtk('outflow')
outflowScalars = outflowObj.GetPointData().GetScalars()

print ("Reading simulation results: " + resfn)
resReader = vtk.vtkXMLUnstructuredGridReader()
resReader.SetFileName(resfn)
resReader.Update()