Exemple #1
0
    def prepare(self):
        # create project directory name
        self.createProjectName()

        # create snappy and domain object
        self._snappy = Snappy.Snappy(self._snappyHexMeshDir, self._logger)
        self._domain = Domain.Domain(self._snappyHexMeshDir, self._logger)
        self._simple = Simple.Simple(self._simpleFoamDir,
                                     self._snappyHexMeshDir, self._logger)

        # read/load solid
        if self._snappy.solidWritten() and not self._solidfile:
            self._logger.info("Loading Solid from snappyHexMesh")
            [self._solid, self._refsolid] = self._snappy.loadSolid()
        else:
            # check if solid file exists
            self.checkSolidFile(self._solidfile)
            self._solid = Solid.createSolidFromSTL(self._solidfile)

            self.checkSolidFile(self._refsolidfile)
            self._refsolid = Solid.createSolidFromSTL(self._refsolidfile)

            if self._edgesolidfile:
                self.checkSolidFile(self._edgesolidfile)
                self._edgesolid = Solid.createSolidFromSTL(self._edgesolidfile)

        # assign solid to snappy/domain-object
        self._snappy.setsolid(self._solid)
        self._snappy.setRefsolid(self._refsolid)
        self._snappy.setEdgesolid(self._edgesolid)
        self._domain.setsolid(self._solid)

        self._simple.setVelocityKnots(self._speedknots)
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"
Exemple #4
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"
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
try:
    import Solid
    import MeshObject
except:
    from __init__ import *
from sys import path



Solid.SetKernel("PolyData")
MeshObject.SetKernel("TetGen")

gOptions = {'meshing_kernel':'TetGen'}
gOptions['meshing_solid_kernel'] = 'PolyData'


num_procs = -1
procs_case = 0
selected_LS = -1
run_varwall = -1

# shared functions
path.append("./../../common")
import executable_names
Exemple #6
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 #7
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 #8
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 #9
0
#! /usr/bin/python3
import sys, Kickass, Solid, Extra, Sky, threading, time

searchTerm = ' '.join(sys.argv[1:])
print('Processing...')

# Object Creation
# TODO Parallel Processing

start = time.perf_counter()

kickass = Kickass.KickassClass(searchTerm)
solid = Solid.SolidClass(searchTerm)
extra = Extra.ExtraClass(searchTerm)
sky = Sky.SkyClass(searchTerm)

# start() calls the run() method of the thread
kickass.start()
solid.start()
extra.start()
sky.start()

kickass.join()
solid.join()
extra.join()
sky.join()

# object creations were drastically faster.
# averaged to around 3 secs in contrast to 7-9 secs
# TODO Learn threading on objects