Ejemplo n.º 1
0
    def Execute(self):

        from vmtk import vmtkscripts
        if self.Surface == None:
            self.PrintError('Error: No input surface.')

        smoothingFilter = None

        if self.Method == 'taubin':
            smoothingFilter = vtk.vtkWindowedSincPolyDataFilter()
            smoothingFilter.SetInputData(self.Surface)
            smoothingFilter.SetNumberOfIterations(self.NumberOfIterations)
            smoothingFilter.SetPassBand(self.PassBand)
            smoothingFilter.SetBoundarySmoothing(self.BoundarySmoothing)
            smoothingFilter.SetNormalizeCoordinates(self.NormalizeCoordinates)
            smoothingFilter.Update()
        elif self.Method == 'laplace':
            smoothingFilter = vtk.vtkSmoothPolyDataFilter()
            smoothingFilter.SetInputData(self.Surface)
            smoothingFilter.SetNumberOfIterations(self.NumberOfIterations)
            smoothingFilter.SetRelaxationFactor(self.RelaxationFactor)
            smoothingFilter.Update()
        else:
            self.PrintError('Error: smoothing method not supported.')

        self.Surface = smoothingFilter.GetOutput()

        normals = vmtkscripts.vmtkSurfaceNormals()
        normals.Surface = self.Surface
        normals.Execute()

        self.Surface = normals.Surface
Ejemplo n.º 2
0
def vmtk_compute_surface_normals(surface,
                                 auto_orient_normals=True,
                                 orient_normals=True,
                                 compute_cell_normals=False,
                                 flip_normals=False):
    """
    Wrapper for vmtkSurfaceNormals.
    Computes the normals of the input surface.

    Args:
        surface (vtkPolyData): Input surface model
        auto_orient_normals (bool): Try to auto orient normals outwards
        orient_normals (bool): Try to orient normals so that neighboring points have similar orientations
        compute_cell_normals (bool): Compute cell normals instead of point normals
        flip_normals (bool): Flip normals after computing them

    Returns:
        vtkPolyData: Surface model with computed normals
    """
    surface_normals = vmtkscripts.vmtkSurfaceNormals()
    surface_normals.Surface = surface
    surface_normals.NormalsArrayName = surfaceNormalsArrayName
    if not auto_orient_normals:
        surface_normals.AutoOrientNormals = 0
    if not orient_normals:
        surface_normals.Consistency = 0
    if compute_cell_normals:
        surface_normals.ComputeCellNormals = 1
    if flip_normals:
        surface_normals.FlipNormals = 1

    surface_normals.Execute()
    surface_with_normals = surface_normals.Surface

    return surface_with_normals
Ejemplo n.º 3
0
    def Execute(self):

        from vmtk import vmtkscripts
        if self.Surface == None:
            self.PrintError('Error: No input surface.')

        smoothingFilter = None

        if self.Method == 'taubin':
            smoothingFilter = vtk.vtkWindowedSincPolyDataFilter()
            smoothingFilter.SetInputData(self.Surface)
            smoothingFilter.SetNumberOfIterations(self.NumberOfIterations)
            smoothingFilter.SetPassBand(self.PassBand)
            smoothingFilter.SetBoundarySmoothing(self.BoundarySmoothing)
            smoothingFilter.SetNormalizeCoordinates(self.NormalizeCoordinates)
            smoothingFilter.Update()
        elif self.Method == 'laplace':
            smoothingFilter = vtk.vtkSmoothPolyDataFilter()
            smoothingFilter.SetInputData(self.Surface)
            smoothingFilter.SetNumberOfIterations(self.NumberOfIterations)
            smoothingFilter.SetRelaxationFactor(self.RelaxationFactor)
            smoothingFilter.Update()
        else:
            self.PrintError('Error: smoothing method not supported.')

        self.Surface = smoothingFilter.GetOutput()

        normals = vmtkscripts.vmtkSurfaceNormals()
        normals.Surface = self.Surface
        normals.Execute()

        self.Surface = normals.Surface
Ejemplo n.º 4
0
def vmtksurfacenormals(surface):
    """Compute normals to a surface.

    Args:
        surface: Surface mesh.

    Returns:
        Surface mesh with 'Normals' vector pointdata.

    """
    normaller = vmtkscripts.vmtkSurfaceNormals()
    normaller.Surface = surface
    normaller.Execute()
    return normaller.Surface
Ejemplo n.º 5
0
def vmtksurfacenormals(surface):
    """Compute normals to a surface.

    Args:
        surface: Surface mesh.

    Returns:
        Surface mesh with 'Normals' vector pointdata.

    """
    normaller = vmtkscripts.vmtkSurfaceNormals()
    normaller.Surface = surface
    normaller.Execute()
    return normaller.Surface
Ejemplo n.º 6
0
def Execute(args):
    print("evaluate centerlines")

    reader_ctr = vmtkscripts.vmtkSurfaceReader()
    reader_ctr.InputFileName = args.centerlines
    reader_ctr.Execute()

    print(args.clean_ctr)
    if (args.clean_ctr):
        cleaner = vtk.vtkCleanPolyData()
        cleaner.PointMergingOn()
        cleaner.SetInputData(reader_ctr.Surface)
        cleaner.Update()
        centerlines = cleaner.GetOutput()
    else:
        centerlines = reader_ctr.Surface

    centerlines.BuildLinks()
    centerlines.BuildCells()

    reader_br = vmtkscripts.vmtkSurfaceReader()
    reader_br.InputFileName = args.surface
    reader_br.Execute()

    #if (reader_br.Surface.GetPointData().GetNormals() == None):
    #normalsFilter = vmtkscripts.vmtkSurfaceNormals()
    #normalsFilter.ComputeCellNormals = 1
    #normalsFilter.Surface = reader_br.Surface
    #normalsFilter.NormalsArrayName = 'Normals'
    #normalsFilter.Execute()
    #surface_reference = normalsFilter.Surface
    #else:
    surface_reference = reader_br.Surface

    locator_surf = vtk.vtkPointLocator()
    locator_surf.SetDataSet(surface_reference)
    locator_surf.BuildLocator()

    locator_cell = vtk.vtkCellLocator()
    locator_cell.SetDataSet(surface_reference)
    locator_cell.BuildLocator()

    cell_Ids = vtk.vtkIdList()
    outputLines = vtk.vtkCellArray()
    output = vtk.vtkPolyData()

    triangles = vtk.vtkCellArray()
    triangle_pd = vtk.vtkPolyData()
    triangle_pts = vtk.vtkPoints()

    lengthArray = vtk.vtkDoubleArray()
    lengthArray.SetName("length")
    lengthArray.SetNumberOfComponents(1)

    pts_ids = vtk.vtkIdList()
    factor = 1.0
    factor2 = 2.0
    pd_count = 0

    size_range = [0.0, 0.0]

    bifurcation_info = {}
    for i in range(centerlines.GetNumberOfCells()):
        bifurcation_info[i] = {"clip_id": [], "cell_id": []}
        cell = centerlines.GetCell(i)
        if cell.GetCellType() not in (vtk.VTK_POLY_LINE, vtk.VTK_LINE):
            continue

        n_cell_pts = cell.GetNumberOfPoints()

        start_end_pt = [0, n_cell_pts - 1]

        for j in start_end_pt:
            pt_id_pd = cell.GetPointIds().GetId(j)

            centerlines.GetPointCells(pt_id_pd, cell_Ids)
            if (cell_Ids.GetNumberOfIds() > 1):
                radius = centerlines.GetPointData().GetArray(
                    "MaximumInscribedSphereRadius").GetTuple(pt_id_pd)[0]
                length = 0.0
                radius2 = 0.0
                prev_point = centerlines.GetPoint(pt_id_pd)
                if (j == start_end_pt[0]):
                    step = 1
                    stop = start_end_pt[-1]
                else:
                    step = -1
                    stop = -1
                for k in range(j, stop, step):
                    point = centerlines.GetPoint(cell.GetPointIds().GetId(k))
                    length += vtk.vtkMath.Distance2BetweenPoints(
                        prev_point, point)**0.5
                    prev_point = point
                    if (length > (factor * radius + factor2 * radius2)):
                        #print(length)
                        pl_vec = centerlines.GetPointData().GetArray(
                            "FrenetTangent").GetTuple(
                                cell.GetPointIds().GetId(k))
                        pl = vtk.vtkPlane()
                        pl.SetOrigin(point)
                        pl.SetNormal(pl_vec)

                        cut = vtk.vtkCutter()
                        cut.SetInputData(surface_reference)
                        cut.SetCutFunction(pl)
                        cut.Update()

                        ex = vtk.vtkPolyDataConnectivityFilter()
                        ex.SetInputConnection(cut.GetOutputPort())
                        #ex.SetExtractionModeToAllRegions()
                        ex.SetExtractionModeToClosestPointRegion()
                        ex.SetClosestPoint(point)
                        ex.Update()

                        lp = ex.GetOutput()
                        close_cell(lp)

                        cutStrips = vtk.vtkStripper(
                        )  # Forms loops (closed polylines) from cutter
                        cutStrips.SetInputData(lp)
                        cutStrips.Update()
                        cutPoly = vtk.vtkPolyData(
                        )  # This trick defines polygons as polyline loop
                        cutPoly.SetPoints((cutStrips.GetOutput()).GetPoints())
                        cutPoly.SetPolys((cutStrips.GetOutput()).GetLines())

                        area_test = ComputePolygonArea(cutPoly)
                        size_ratio = area_test / (np.pi * radius**2)
                        #print(area_test, radius, size_ratio)
                        if (size_ratio > 2.0):
                            continue

                        cv, offset, shape = ComputeBranchSectionShape(
                            cutPoly, point)

                        if (cv > 0.2):
                            continue
                        if (offset > 0.10):
                            continue
                        #if(shape > 0.8):
                        #   continue

                        #else:
                        #average area
                        #radius2 = max(radius, np.sqrt(area_test/np.pi))

                        #shape = ComputeBranchSectionShape(cutPoly, point, size_range)

                        writerline = vmtkscripts.vmtkSurfaceWriter()
                        writerline.OutputFileName = "test_loop_{0}.vtp".format(
                            pd_count)
                        writerline.Input = cutPoly  #ex.GetOutput()
                        writerline.Execute()
                        pd_count += 1

                        #if (radius2 <= 0.0):
                        #radius2 = centerlines.GetPointData().GetArray("MaximumInscribedSphereRadius").GetTuple(cell.GetPointIds().GetId(k))[0]
                        ##if ( radius2 > radius):
                        ##radius = radius2
                        ##else:
                        ##ratio = radius/radius2

                        #else:

                        #print(length)
                        clip_id = cell.GetPointIds().GetId(k)
                        bifurcation_info[i]["clip_id"].append(clip_id)
                        bifurcation_info[i]["cell_id"].append(k)
                        break
        #return

    #t = [ 1 for i in bifurcation_info.keys() if len(bifurcation_info[i]) == 2]
    two_bif = False
    pd_count = 0
    for cell in bifurcation_info:
        id_sorted = sorted(bifurcation_info[cell]["cell_id"])

        if (len(bifurcation_info[cell]["cell_id"]) < 2):
            two_bif = False
        else:
            two_bif = True
            diff = bifurcation_info[cell]["cell_id"][0] - bifurcation_info[
                cell]["cell_id"][1]
            if (abs(diff) <
                    2):  # there is a problem if there less than two points
                print("houston we got a problem")

        clip_id = centerlines.GetCell(cell).GetPointIds().GetId(id_sorted[0])
        clip_id_m1 = centerlines.GetCell(cell).GetPointIds().GetId(
            id_sorted[0] + 1)
        start_pt = centerlines.GetPoint(clip_id)
        surface_pt_id = locator_surf.FindClosestPoint(start_pt)

        # vector from pt(start_pt+1) - pt(start_pt)
        v_start = [
            x - y for x, y in zip(centerlines.GetPoint(clip_id_m1), start_pt)
        ]
        v_ctr_start = centerlines.GetPointData().GetArray(
            "FrenetTangent").GetTuple(clip_id)
        v_normal_start = centerlines.GetPointData().GetArray(
            "FrenetNormal").GetTuple(clip_id)

        # want inward facing normals
        if (vtk.vtkMath.Dot(v_start, v_ctr_start) < 0.0):
            v_ctr_start = [-1.0 * x for x in v_ctr_start]

        #print(clip_tangent)
        plane1 = vtk.vtkPlane()
        plane1.SetOrigin(start_pt)
        plane1.SetNormal(v_ctr_start)

        #tree = vtk.vtkModifiedBSPTree()
        #tree.SetDataSet(surface_reference)
        #tree.BuildLocator()
        ##intersect the locator with the line
        #LineP0 = start_pt

        ## 200 points
        #radius_est = centerlines.GetPointData().GetArray("MaximumInscribedSphereRadius").GetTuple(clip_id)[0]
        ##radii increment is proportional to circumference
        ##distance between points
        #cnt_dist = 0.05
        #n_radii = int(np.pi*2.0*radius_est/cnt_dist)
        #dt = radius_est*4.0*cnt_dist #estimate ray step from radius
        #dtheta = [0.0 + i*(359.0-0.0)/(n_radii-1) for i in range(n_radii)] #[0.0]
        #out_vector = (0.0,0.0,0.0)
        #tolerance = 0.0000001

        #polylines = vtk.vtkCellArray()
        #cut_surface = vtk.vtkPolyData()
        #new_line = vtk.vtkPolyLine()
        #new_line.GetPointIds().SetNumberOfIds(len(dtheta)+1)

        #IntersectPointsList = vtk.vtkPoints()
        #loop_pts_list = vtk.vtkPoints()
        #IntersectCellsList = vtk.vtkIdList()
        #for idx, theta in enumerate(dtheta):
        #IntersectPoints = vtk.vtkPoints()
        #IntersectCells = vtk.vtkIdList()
        #code = 0
        #count = 1
        #rotate = vtk.vtkTransform()
        #rotate.RotateWXYZ(theta,  v_ctr_start)
        #rotate.Update()

        ##print(dir(rotate))
        ##trans_m = vtk.vtkMatrix4x4()
        ##rotate.GetMatrix(trans_m)

        #out_vector = rotate.TransformVector(v_normal_start)
        #LineP1 = [ c2 + count*dt*c1 for c2, c1 in zip(start_pt, out_vector)]
        ##print(v_normal_start, out_vector)
        #while ( code == 0 and count < 10000):
        #count += 1
        #code = tree.IntersectWithLine(LineP0, LineP1,
        #tolerance, IntersectPoints,
        #IntersectCells)
        #LineP1 = [ c2 + count*dt*c1 for c2, c1 in zip(start_pt, out_vector)]
        #if(count > 10000 and code == 0):
        #print("no intersection")
        #continue

        #if (code != 0):
        #if(IntersectCells.GetNumberOfIds() > 1):
        #print(IntersectCells.GetNumberOfIds())
        #pt = IntersectPoints.GetPoint(0)
        ##pt = [ c2 + dt*c1 for c2, c1 in zip(pt, out_vector)] # add some buffer, may not need it
        #new_pt_id = IntersectPointsList.InsertNextPoint(pt)
        #new_line.GetPointIds().SetId(idx, new_pt_id)
        #loop_pts_list.InsertNextPoint(LineP1)
        #IntersectCellsList.InsertNextId(IntersectCells.GetId(0))
        ##print(IntersectPoints.GetPoint(0), IntersectCells.GetId(0) )

        #new_line.GetPointIds().SetId(len(dtheta), 0)
        #print(IntersectPointsList.GetPoint(0))
        #print(v_ctr_start, start_pt)
        #polylines.InsertNextCell(new_line)
        #cut_surface.SetPoints(IntersectPointsList)
        #cut_surface.SetLines(polylines)

        #writerline = vmtkscripts.vmtkSurfaceWriter()
        #writerline.OutputFileName = "test_loop_{0}.vtp".format(pd_count)

        #writerline.Input = cut_surface
        #writerline.Execute()

        cutter = vtk.vtkCutter()
        cutter.SetInputData(surface_reference)
        cutter.SetCutFunction(plane1)
        cutter.Update()

        extract = vtk.vtkPolyDataConnectivityFilter()
        extract.SetInputConnection(cutter.GetOutputPort())
        extract.SetExtractionModeToClosestPointRegion()
        extract.SetClosestPoint(start_pt)

        extract.Update()

        loop = extract.GetOutput()
        weights = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
        gencell = vtk.vtkGenericCell()
        cross_inter = [0.0, 0.0, 0.0]
        cross_edges = [0.0, 0.0, 0.0]
        cross_test = [0.0, 0.0, 0.0]
        test_pt = [0.0, 0.0, 0.0]
        thresh = 0.0
        first_3tris = False
        for i in range(loop.GetNumberOfCells()):
            pt1 = loop.GetPoint(loop.GetCell(i).GetPointIds().GetId(0))
            pt2 = loop.GetPoint(loop.GetCell(i).GetPointIds().GetId(1))
            mid_pt = [(x + y) / 2.0 for x, y in zip(pt2, pt1)]
            direction = [x - y for x, y in zip(pt2, pt1)]

            cell_id = locator_cell.FindCell(mid_pt, 0.0001, gencell, test_pt,
                                            weights)

            cell_ = surface_reference.GetCell(cell_id)

            right = []
            left = []
            center = []
            pt_list = []
            for j in range(cell_.GetNumberOfPoints()):
                #get distance
                pt_list.append(
                    surface_reference.GetPoint(cell_.GetPointIds().GetId(j)))
                dist = plane1.EvaluateFunction(pt_list[-1])
                if (dist < -thresh):
                    left.append(j)
                elif (dist > thresh):
                    right.append(j)
                else:
                    center.append(j)

            tag = ""
            if len(center) > 1:
                # don't do anything its already split on edge
                tag = "edge"
                print("edge")
            elif len(center) > 0:
                # split into two triangles
                pt = center[0]
                tag = "2_tris"
            else:
                tag = "3_tris"

                if (len(left) > 1):
                    #print("left")
                    pt = right[0]
                elif (len(right) > 1):
                    pt = left[0]
                else:
                    print("split triangle")

            edge1 = [x - y for x, y in zip(pt_list[(pt + 1) % 3], pt_list[pt])]
            edge2 = [x - y for x, y in zip(pt_list[(pt + 2) % 3], pt_list[pt])]

            vtk.vtkMath.Cross(edge1, edge2, cross_edges)
            vtk.vtkMath.Normalize(cross_edges)
            vtk.vtkMath.Cross(edge1, direction, cross_test)
            vtk.vtkMath.Normalize(cross_test)

            is_winding = vtk.vtkMath.Dot(cross_edges, cross_test)

            # switch the winding of the intersection points
            if (is_winding < 0.0):
                tmp = pt1
                pt1 = pt2
                pt2 = tmp

            if (tag == "3_tris"):
                if (first_3tris == False):
                    first_3tris = True

                # first triangle
                #new_cell = vtk.vtkTriangle()
                #pts_id_list = []
                #pt_id_1 = triangle_pts.InsertNextPoint(pt_list[pt])
                #new_cell.GetPointIds().SetId(0, pt_id_1)

                #pt_id_2 = triangle_pts.InsertNextPoint(pt1)
                #new_cell.GetPointIds().SetId(1, pt_id_2)

                #pt_id_3 = triangle_pts.InsertNextPoint(pt2)
                #new_cell.GetPointIds().SetId(2, pt_id_3)

                #triangles.InsertNextCell(new_cell)

                triangle_pts = vtk.vtkPoints()

                quad_id_1 = triangle_pts.InsertNextPoint(pt2)
                quad_id_2 = triangle_pts.InsertNextPoint(pt1)
                quad_id_3 = triangle_pts.InsertNextPoint(pt_list[(pt + 1) % 3])
                quad_id_4 = triangle_pts.InsertNextPoint(pt_list[(pt + 2) % 3])

                pts_new_triangle = []

                pt_id_2 = surface_reference.GetPoints().InsertNextPoint(pt1)
                pts_new_triangle.append(
                    surface_reference.GetCell(cell_id).GetPointIds().GetId(pt))
                pts_new_triangle.append(pt_id_2)
                surface_reference.GetPointData().GetArray(
                    "Ids").InsertNextTuple([pt_id_2])
                pt_id_2_old = surface_reference.GetCell(
                    cell_id).GetPointIds().GetId((pt + 1) % 3)
                #surface_reference.GetCell(cell_id).GetPointIds().SetId((pt+1)%3, pt_id_2)

                pt_id_3 = surface_reference.GetPoints().InsertNextPoint(pt2)
                pts_new_triangle.append(pt_id_3)
                surface_reference.GetPointData().GetArray(
                    "Ids").InsertNextTuple([pt_id_2])
                pt_id_3_old = surface_reference.GetCell(
                    cell_id).GetPointIds().GetId((pt + 2) % 3)
                #surface_reference.GetCell(cell_id).GetPointIds().SetId((pt+2)%3, pt_id_3)

                surface_reference.ReplaceCell(cell_id, len(pts_new_triangle),
                                              pts_new_triangle)
                # map polygon to reference mesh
                map_to = {
                    quad_id_1: pt_id_3,
                    quad_id_2: pt_id_2,
                    quad_id_3: pt_id_2_old,
                    quad_id_4: pt_id_3_old
                }

                npts = 4
                polygon = vtk.vtkPolygon()
                polygon.GetPointIds().SetNumberOfIds(npts)
                polygon.GetPoints().SetNumberOfPoints(npts)

                polygon.GetPointIds().SetId(0, quad_id_1)
                polygon.GetPoints().SetPoint(0,
                                             triangle_pts.GetPoint(quad_id_1))
                polygon.GetPointIds().SetId(1, quad_id_2)
                polygon.GetPoints().SetPoint(1,
                                             triangle_pts.GetPoint(quad_id_2))

                polygon.GetPointIds().SetId(2, quad_id_3)
                polygon.GetPoints().SetPoint(2,
                                             triangle_pts.GetPoint(quad_id_3))
                polygon.GetPointIds().SetId(3, quad_id_4)
                polygon.GetPoints().SetPoint(3,
                                             triangle_pts.GetPoint(quad_id_4))

                quad_ids = vtk.vtkIdList()

                polygon.Triangulate(quad_ids)
                numPts = quad_ids.GetNumberOfIds()
                numSimplices = numPts // 3
                triPts = [0, 0, 0]
                triPts_map = [0, 0, 0]
                #print(numSimplices, numPts
                for j in range(numSimplices):
                    for k in range(3):
                        triPts[k] = polygon.GetPointIds().GetId(
                            quad_ids.GetId(int(3 * j + k)))
                        triPts_map[k] = map_to[triPts[k]]
                    #triangles.InsertNextCell(3, triPts)

                    cell_id_new = surface_reference.GetPolys().InsertNextCell(
                        3, triPts_map)
                    surface_reference.GetCellData().GetArray(
                        "Ids").InsertNextTuple([cell_id_new])
                #surface_reference.Modified()
                #print("hello")

            #if ( tag == "2_tris"):
            ## doesnt' work well
            ## for collapse of intersection line on
            #new_cell = vtk.vtkTriangle()
            #pts_id_list = []
            #pt_id_1 = triangle_pts.InsertNextPoint(pt_list[pt])
            #new_cell.GetPointIds().SetId(0, pt_id_1)

            #pt_id_2 = triangle_pts.InsertNextPoint(pt_list[(pt+1)%3])
            #new_cell.GetPointIds().SetId(1, pt_id_2)

            #pt_id_3 = triangle_pts.InsertNextPoint(pt2)
            #new_cell.GetPointIds().SetId(2, pt_id_3)

            #triangles.InsertNextCell(new_cell)

            #new_cell = vtk.vtkTriangle()
            #new_cell.GetPointIds().SetId(0, pt_id_1)
            #new_cell.GetPointIds().SetId(1, pt_id_3)
            #pt_id_4 = triangle_pts.InsertNextPoint(pt_list[(pt+2)%3])
            #new_cell.GetPointIds().SetId(2, pt_id_4)

            #triangles.InsertNextCell(new_cell)

        #triangle_pd.SetPoints(triangle_pts)
        #triangle_pd.SetPolys(triangles)

        #pass_ = vtk.vtkPassArrays()
        #pass_.SetInputData(surface_reference)
        #pass_.RemoveArraysOn()
        #pass_.RemoveCellDataArray("Ids")
        #pass_.RemoveCellDataArray("Normals")
        #pass_.RemovePointDataArray("Ids")
        #pass_.RemovePointDataArray("Normals")

        ##pass_.ClearPointDataArrays()
        ##pass_.ClearCellDataArrays()
        #pass_.Update()

        #geom = vtk.vtkGeometryFilter()
        #geom.SetInputConnection(pass_.GetOutputPort())
        #geom.Update()

        #normalsFilter2 = vmtkscripts.vmtkSurfaceNormals()
        #normalsFilter2.ComputeCellNormals = 1
        #normalsFilter2.Surface = surface_reference
        #normalsFilter2.NormalsArrayName = 'Normals'
        #normalsFilter2.Execute()

        #writer = vmtkscripts.vmtkSurfaceWriter()
        #writer.OutputFileName = "test_file_{0}.vtp".format(pd_count)
        #writer.Input = surface_reference #geom.GetOutput() #triangle_pd #extract.GetOutput()
        #writer.Execute()
        pd_count += 1

        #print("yp")
        surface_reference.Modified()
        #print("zzz")
        surface_reference.BuildCells()
        surface_reference.BuildLinks()
        #print("yppp")
        locator_surf = vtk.vtkPointLocator()
        locator_surf.SetDataSet(surface_reference)
        locator_surf.BuildLocator()

        #print("ydddp")
        locator_cell = vtk.vtkCellLocator()
        locator_cell.SetDataSet(surface_reference)
        locator_cell.BuildLocator()

        #return

    print(bifurcation_info)
    #return

    normalsFilter2 = vmtkscripts.vmtkSurfaceNormals()
    normalsFilter2.ComputeCellNormals = 1
    normalsFilter2.Surface = surface_reference
    normalsFilter2.NormalsArrayName = 'Normals'
    normalsFilter2.Execute()

    writer = vmtkscripts.vmtkSurfaceWriter()
    writer.OutputFileName = args.out_file
    writer.Input = normalsFilter2.Surface
    writer.Execute()
Ejemplo n.º 7
0
def Execute(args):
    print("get average along line probes")
    cell_type = "point"

    if (cell_type == "cell"):
        vtk_process = vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS
        vtk_data_type = vtk.vtkDataObject.CELL
    else:
        vtk_process = vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS
        vtk_data_type = vtk.vtkDataObject.POINT

    reader = vmtkscripts.vmtkMeshReader()
    reader.InputFileName = args.mesh_file
    reader.Execute()
    mesh = reader.Mesh

    pass_filt = vtk.vtkPassArrays()
    pass_filt.SetInputData(mesh)
    pass_filt.AddArray(vtk_data_type, "velocity")
    pass_filt.Update()

    surf = vmtkscripts.vmtkMeshToSurface()
    surf.Mesh = pass_filt.GetOutput()
    surf.Execute()

    normals = vmtkscripts.vmtkSurfaceNormals()
    normals.Surface = surf.Surface
    #accept defaults
    normals.Execute()

    calc1 = vtk.vtkArrayCalculator()
    calc1.SetFunction(
        "velocity_X*-Normals_X+velocity_Y*-Normals_Y+velocity_Z*-Normals_Z")
    calc1.AddScalarVariable("velocity_X", "velocity_X", 0)
    calc1.AddScalarVariable("velocity_Y", "velocity_Y", 0)
    calc1.AddScalarVariable("velocity_Z", "velocity_Z", 0)
    calc1.SetResultArrayName("vdotn")
    calc1.SetInputData(normals.Surface)
    if (cell_type == "cell"):
        calc1.SetAttributeModeToUseCellData()

    else:
        calc1.SetAttributeModeToUsePointData()
    calc1.SetResultArrayType(vtk.VTK_DOUBLE)

    integrate_attrs = vtk.vtkIntegrateAttributes()
    integrate_attrs.SetInputConnection(calc1.GetOutputPort())

    integrate_attrs.UpdateData()

    area = integrate_attrs.GetCellData().GetArray(0).GetValue(0)

    D = 2.0 * np.sqrt(area / np.pi)

    calc2 = vtk.vtkArrayCalculator()
    calc2.SetFunction("vdotn*10**6*60")
    calc2.AddScalarVariable("vdotn", "vdotn", 0)
    calc2.SetResultArrayName("Q")
    calc2.SetInputConnection(integrate_attrs.GetOutputPort())
    if (cell_type == "cell"):
        calc2.SetAttributeModeToUseCellData()
    else:
        calc2.SetAttributeModeToUsePointData()
    calc2.SetResultArrayType(vtk.VTK_DOUBLE)
    calc2.UpdateData()

    calc3 = vtk.vtkArrayCalculator()
    calc3.SetFunction("vdotn/{0}*1050.0/0.0035*{1}".format(area, D))
    calc3.AddScalarVariable("vdotn", "vdotn", 0)
    calc3.SetResultArrayName("Re")
    calc3.SetInputConnection(integrate_attrs.GetOutputPort())
    if (cell_type == "cell"):
        calc3.SetAttributeModeToUseCellData()
    else:
        calc3.SetAttributeModeToUsePointData()
    calc3.SetResultArrayType(vtk.VTK_DOUBLE)

    calc3.UpdateData()

    over_time = vtk.vtkExtractDataArraysOverTime()
    over_time.SetInputConnection(calc3.GetOutputPort())

    if (cell_type == "cell"):
        over_time.SetFieldAssociation(vtk_data_type)
    else:
        over_time.SetFieldAssociation(vtk_data_type)
    over_time.UpdateData()

    writer = vtk.vtkDelimitedTextWriter()
    writer.SetInputConnection(over_time.GetOutputPort())
    writer.SetFileName(args.file_out)
    writer.Write()
Ejemplo n.º 8
0
    def Execute(self):

        from vmtk import vmtkscripts
        if self.Surface == None:
            self.PrintError('Error: no Surface.')

        triangleFilter = vtk.vtkTriangleFilter()
        triangleFilter.SetInputData(self.Surface)
        triangleFilter.Update()

        self.Surface = triangleFilter.GetOutput()

        if self.Loop == None:
            self.PrintError('Error: no Loop.')

        select = vtk.vtkImplicitSelectionLoop()
        select.SetLoop(self.Loop.GetPoints())
        normal = [0.0,0.0,0.0]
        centroid = [0.0,0.0,0.0]
        vtk.vtkPolygon().ComputeNormal(self.Loop.GetPoints(),normal)

        #compute centroid and check normals
        p = [0.0,0.0,0.0]
        for i in range (self.Loop.GetNumberOfPoints()):
            p = self.Loop.GetPoint(i)
            centroid[0] += p[0]
            centroid[1] += p[1]
            centroid[2] += p[2]
        centroid[0] = centroid[0] / self.Loop.GetNumberOfPoints()
        centroid[1] = centroid[1] / self.Loop.GetNumberOfPoints()
        centroid[2] = centroid[2] / self.Loop.GetNumberOfPoints()
        print("loop centroid", centroid)

        locator = vtk.vtkPointLocator()
        locator.SetDataSet(self.Surface)
        locator.AutomaticOn()
        locator.BuildLocator()
        idsurface = locator.FindClosestPoint(centroid)

        if (self.Surface.GetPointData().GetNormals() == None):
            normalsFilter = vmtkscripts.vmtkSurfaceNormals()
            normalsFilter.Surface = self.Surface
            normalsFilter.NormalsArrayName = 'Normals'
            normalsFilter.Execute()
            self.Surface = normalsFilter.Surface
        normalsurface = [0.0,0.0,0.0]
        self.Surface.GetPointData().GetNormals().GetTuple(idsurface,normalsurface)
        print("loop normal: ", normal)
        print("surface normal inside the loop: ", normalsurface)
        check = vtk.vtkMath.Dot(normalsurface,normal)
        if check < 0:
            normal[0] = - normal[0]
            normal[1] = - normal[1]
            normal[2] = - normal[2]

        #compute plane
        proj = float(vtk.vtkMath.Dot(self.Loop.GetPoint(0),normal))
        point = [0.0,0.0,0.0]
        self.Loop.GetPoint(0,point)
        for i in range (self.Loop.GetNumberOfPoints()):
            tmp = vtk.vtkMath.Dot(self.Loop.GetPoint(i),normal)
            if tmp < proj:
                proj = tmp
                self.Loop.GetPoint(i,point)
        origin = [0.0,0.0,0.0]
        origin[0] = point[0] #- normal[0]
        origin[1] = point[1] #- normal[1]
        origin[2] = point[2] #- normal[2]
        plane=vtk.vtkPlane()
        plane.SetNormal(normal[0],normal[1],normal[2])
        plane.SetOrigin(origin[0],origin[1],origin[2])

        #set bool
        Bool = vtk.vtkImplicitBoolean()
        Bool.SetOperationTypeToDifference()
        Bool.AddFunction(select)
        Bool.AddFunction(plane)

        clipper=vtk.vtkClipPolyData()
        clipper.SetInputData(self.Surface)
        clipper.SetClipFunction(Bool)
        clipper.GenerateClippedOutputOn()
        clipper.InsideOutOff()
        clipper.Update()

        self.Surface = clipper.GetOutput()
Ejemplo n.º 9
0
def vmtksurfacenormals(surface):
    computer = vmtkscripts.vmtkSurfaceNormals()
    computer.Surface = surface
    computer.Execute()
    return computer.Surface
Ejemplo n.º 10
0
    def Execute(self):

        from vmtk import vmtkscripts
        if self.Surface == None:
            self.PrintError('Error: No input surface.')

        wallEntityOffset = 1

        if self.SkipCapping or not self.BoundaryLayerOnCaps:
            self.PrintLog("Not capping surface")
            surface = self.Surface
            cellEntityIdsArray = vtk.vtkIntArray()
            cellEntityIdsArray.SetName(self.CellEntityIdsArrayName)
            cellEntityIdsArray.SetNumberOfTuples(surface.GetNumberOfCells())
            cellEntityIdsArray.FillComponent(0,0.0)
            surface.GetCellData().AddArray(cellEntityIdsArray)
        else:
            self.PrintLog("Capping surface")
            capper = vmtkscripts.vmtkSurfaceCapper()
            capper.Surface = self.Surface
            capper.Interactive = 0
            capper.Method = self.CappingMethod
            capper.TriangleOutput = 0
            capper.CellEntityIdOffset = wallEntityOffset
            capper.Execute()
            surface = capper.Surface

        if self.SkipRemeshing:
            remeshedSurface = surface
        else:
            self.PrintLog("Remeshing surface")
            remeshing = vmtkscripts.vmtkSurfaceRemeshing()
            remeshing.Surface = surface
            remeshing.CellEntityIdsArrayName = self.CellEntityIdsArrayName
            remeshing.TargetEdgeLength = self.TargetEdgeLength
            remeshing.MaxEdgeLength = self.MaxEdgeLength
            remeshing.MinEdgeLength = self.MinEdgeLength
            remeshing.TargetEdgeLengthFactor = self.TargetEdgeLengthFactor
            remeshing.TargetEdgeLengthArrayName = self.TargetEdgeLengthArrayName
            remeshing.TriangleSplitFactor = self.TriangleSplitFactor
            remeshing.ElementSizeMode = self.ElementSizeMode
            if self.RemeshCapsOnly:
                remeshing.ExcludeEntityIds = [wallEntityOffset]
            remeshing.Execute()
            remeshedSurface = remeshing.Surface

        if self.BoundaryLayer:

            projection = vmtkscripts.vmtkSurfaceProjection()
            projection.Surface = remeshedSurface
            projection.ReferenceSurface = surface
            projection.Execute()

            normals = vmtkscripts.vmtkSurfaceNormals()
            normals.Surface = projection.Surface
            normals.NormalsArrayName = 'Normals'
            normals.Execute()

            surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh()
            surfaceToMesh.Surface = normals.Surface
            surfaceToMesh.Execute()

            self.PrintLog("Generating boundary layer")
            placeholderCellEntityId = 9999
            boundaryLayer = vmtkscripts.vmtkBoundaryLayer()
            boundaryLayer.Mesh = surfaceToMesh.Mesh
            boundaryLayer.WarpVectorsArrayName = 'Normals'
            boundaryLayer.NegateWarpVectors = True
            boundaryLayer.ThicknessArrayName = self.TargetEdgeLengthArrayName
            if self.ElementSizeMode == 'edgelength':
                boundaryLayer.ConstantThickness = True
            else:
                boundaryLayer.ConstantThickness = False
            boundaryLayer.IncludeSurfaceCells = 0
            boundaryLayer.NumberOfSubLayers = self.NumberOfSubLayers
            boundaryLayer.NumberOfSubsteps = self.NumberOfSubsteps
            boundaryLayer.Relaxation = self.Relaxation
            boundaryLayer.LocalCorrectionFactor = self.LocalCorrectionFactor
            boundaryLayer.SubLayerRatio = self.SubLayerRatio
            boundaryLayer.Thickness = self.BoundaryLayerThicknessFactor * self.TargetEdgeLength
            boundaryLayer.ThicknessRatio = self.BoundaryLayerThicknessFactor * self.TargetEdgeLengthFactor
            boundaryLayer.MaximumThickness = self.BoundaryLayerThicknessFactor * self.MaxEdgeLength
            if not self.BoundaryLayerOnCaps:
                boundaryLayer.SidewallCellEntityId = placeholderCellEntityId
                boundaryLayer.InnerSurfaceCellEntityId = wallEntityOffset
            boundaryLayer.Execute()

            meshToSurface = vmtkscripts.vmtkMeshToSurface()
            meshToSurface.Mesh = boundaryLayer.InnerSurfaceMesh
            meshToSurface.Execute()

            innerSurface = meshToSurface.Surface

            if not self.BoundaryLayerOnCaps:

                self.PrintLog("Capping inner surface")
                capper = vmtkscripts.vmtkSurfaceCapper()
                capper.Surface = innerSurface
                capper.Interactive = 0
                capper.Method = self.CappingMethod
                capper.TriangleOutput = 1
                capper.CellEntityIdOffset = wallEntityOffset
                capper.Execute()

                self.PrintLog("Remeshing endcaps")
                remeshing = vmtkscripts.vmtkSurfaceRemeshing()
                remeshing.Surface = capper.Surface
                remeshing.CellEntityIdsArrayName = self.CellEntityIdsArrayName
                remeshing.TargetEdgeLength = self.TargetEdgeLength * self.EndcapsEdgeLengthFactor
                remeshing.MaxEdgeLength = self.MaxEdgeLength
                remeshing.MinEdgeLength = self.MinEdgeLength
                remeshing.TargetEdgeLengthFactor = self.TargetEdgeLengthFactor * self.EndcapsEdgeLengthFactor
                remeshing.TargetEdgeLengthArrayName = self.TargetEdgeLengthArrayName
                remeshing.TriangleSplitFactor = self.TriangleSplitFactor
                remeshing.ElementSizeMode = self.ElementSizeMode
                remeshing.ExcludeEntityIds = [wallEntityOffset]
                remeshing.Execute()

                innerSurface = remeshing.Surface

            self.PrintLog("Computing sizing function")
            sizingFunction = vtkvmtk.vtkvmtkPolyDataSizingFunction()
            sizingFunction.SetInputData(innerSurface)
            sizingFunction.SetSizingFunctionArrayName(self.SizingFunctionArrayName)
            sizingFunction.SetScaleFactor(self.VolumeElementScaleFactor)
            sizingFunction.Update()

            surfaceToMesh2 = vmtkscripts.vmtkSurfaceToMesh()
            surfaceToMesh2.Surface = sizingFunction.GetOutput()
            surfaceToMesh2.Execute()
            
            self.PrintLog("Generating volume mesh")
            tetgen = vmtkscripts.vmtkTetGen()
            tetgen.Mesh = surfaceToMesh2.Mesh
            tetgen.GenerateCaps = 0
            tetgen.UseSizingFunction = 1
            tetgen.SizingFunctionArrayName = self.SizingFunctionArrayName
            tetgen.CellEntityIdsArrayName = self.CellEntityIdsArrayName
            tetgen.Order = 1
            tetgen.Quality = 1
            tetgen.PLC = 1
            tetgen.NoBoundarySplit = 1
            tetgen.RemoveSliver = 1
            tetgen.OutputSurfaceElements = 0
            tetgen.OutputVolumeElements = 1
            tetgen.Execute()

            #w = vtk.vtkXMLUnstructuredGridWriter()
            #w.SetInput(tetgen.Mesh)
            #w.SetFileName('tet.vtu')
            #w.Write()

            if tetgen.Mesh.GetNumberOfCells() == 0 and surfaceToMesh.Mesh.GetNumberOfCells() > 0:
                self.PrintLog('An error occurred during tetrahedralization. Will only output surface mesh and boundary layer.')

            if not self.BoundaryLayerOnCaps:
                surfaceToMesh.Mesh.GetCellData().GetArray(self.CellEntityIdsArrayName).FillComponent(0,wallEntityOffset)

            self.PrintLog("Assembling final mesh")
            appendFilter = vtkvmtk.vtkvmtkAppendFilter()
            appendFilter.AddInputData(surfaceToMesh.Mesh)
            appendFilter.AddInputData(boundaryLayer.Mesh)
            appendFilter.AddInputData(tetgen.Mesh)

            #appendFilter.AddInput(boundaryLayer.InnerSurfaceMesh)

            if not self.BoundaryLayerOnCaps:
                threshold = vtk.vtkThreshold()
                threshold.SetInputData(surfaceToMesh2.Mesh)
                threshold.ThresholdByUpper(1.5)
                threshold.SetInputArrayToProcess(0,0,0,1,self.CellEntityIdsArrayName)
                threshold.Update()
                endcaps = threshold.GetOutput()
                appendFilter.AddInputData(endcaps)

            appendFilter.Update()

            self.Mesh = appendFilter.GetOutput()

            if not self.BoundaryLayerOnCaps:
                cellEntityIdsArray = self.Mesh.GetCellData().GetArray(self.CellEntityIdsArrayName)

                def VisitNeighbors(i, cellEntityId):
                    cellPointIds = vtk.vtkIdList()
                    self.Mesh.GetCellPoints(i,cellPointIds)
                    neighborPointIds = vtk.vtkIdList()
                    neighborPointIds.SetNumberOfIds(1)
                    pointNeighborCellIds = vtk.vtkIdList()
                    neighborCellIds = vtk.vtkIdList()

                    for j in range(cellPointIds.GetNumberOfIds()):
                        neighborPointIds.SetId(0,cellPointIds.GetId(j))
                        self.Mesh.GetCellNeighbors(i,neighborPointIds,pointNeighborCellIds)
                        for k in range(pointNeighborCellIds.GetNumberOfIds()):
                            neighborCellIds.InsertNextId(pointNeighborCellIds.GetId(k))

                    for j in range(neighborCellIds.GetNumberOfIds()):
                        cellId = neighborCellIds.GetId(j)
                        neighborCellEntityId = cellEntityIdsArray.GetTuple1(cellId)
                        neighborCellType = self.Mesh.GetCellType(cellId)
                        if neighborCellType not in [vtk.VTK_TRIANGLE, vtk.VTK_QUADRATIC_TRIANGLE, vtk.VTK_QUAD]:
                            continue
                        if neighborCellEntityId != placeholderCellEntityId:
                            continue
                        cellEntityIdsArray.SetTuple1(cellId,cellEntityId)
                        VisitNeighbors(cellId,cellEntityId)

                for i in range(self.Mesh.GetNumberOfCells()):
                    cellEntityId = cellEntityIdsArray.GetTuple1(i)
                    cellType = self.Mesh.GetCellType(i)
                    if cellType not in [vtk.VTK_TRIANGLE, vtk.VTK_QUADRATIC_TRIANGLE, vtk.VTK_QUAD]:
                        continue
                    if cellEntityId in [0, 1, placeholderCellEntityId]:
                        continue
                    VisitNeighbors(i,cellEntityId)

        else:

            self.PrintLog("Computing sizing function")
            sizingFunction = vtkvmtk.vtkvmtkPolyDataSizingFunction()
            sizingFunction.SetInputData(remeshedSurface)
            sizingFunction.SetSizingFunctionArrayName(self.SizingFunctionArrayName)
            sizingFunction.SetScaleFactor(self.VolumeElementScaleFactor)
            sizingFunction.Update()

            self.PrintLog("Converting surface to mesh")
            surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh()
            surfaceToMesh.Surface = sizingFunction.GetOutput()
            surfaceToMesh.Execute()

            self.PrintLog("Generating volume mesh")
            tetgen = vmtkscripts.vmtkTetGen()
            tetgen.Mesh = surfaceToMesh.Mesh
            tetgen.GenerateCaps = 0
            tetgen.UseSizingFunction = 1
            tetgen.SizingFunctionArrayName = self.SizingFunctionArrayName
            tetgen.CellEntityIdsArrayName = self.CellEntityIdsArrayName
            tetgen.Order = 1
            tetgen.Quality = 1
            tetgen.PLC = 1
            tetgen.NoBoundarySplit = 1
            tetgen.RemoveSliver = 1
            tetgen.OutputSurfaceElements = 1
            tetgen.OutputVolumeElements = 1
            tetgen.Execute()

            self.Mesh = tetgen.Mesh

            if self.Mesh.GetNumberOfCells() == 0 and surfaceToMesh.Mesh.GetNumberOfCells() > 0:
                self.PrintLog('An error occurred during tetrahedralization. Will only output surface mesh.')
                self.Mesh = surfaceToMesh.Mesh

        if self.Tetrahedralize:

            tetrahedralize = vtkvmtk.vtkvmtkUnstructuredGridTetraFilter()
            tetrahedralize.SetInputData(self.Mesh)
            tetrahedralize.Update()

            self.Mesh = tetrahedralize.GetOutput()

        self.RemeshedSurface = remeshedSurface
Ejemplo n.º 11
0
    def Execute(self):

        from vmtk import vmtkscripts
        if self.Surface == None:
            self.PrintError('Error: No input surface.')

        wallEntityOffset = 1

        if self.SkipCapping or not self.BoundaryLayerOnCaps:
            self.PrintLog("Not capping surface")
            surface = self.Surface
            cellEntityIdsArray = vtk.vtkIntArray()
            cellEntityIdsArray.SetName(self.CellEntityIdsArrayName)
            cellEntityIdsArray.SetNumberOfTuples(surface.GetNumberOfCells())
            cellEntityIdsArray.FillComponent(0,0.0)
            surface.GetCellData().AddArray(cellEntityIdsArray)
        else:
            self.PrintLog("Capping surface")
            capper = vmtkscripts.vmtkSurfaceCapper()
            capper.Surface = self.Surface
            capper.Interactive = 0
            capper.Method = self.CappingMethod
            capper.TriangleOutput = 0
            capper.CellEntityIdOffset = wallEntityOffset
            capper.Execute()
            surface = capper.Surface

        if self.SkipRemeshing:
            remeshedSurface = surface
        else:
            self.PrintLog("Remeshing surface")
            remeshing = vmtkscripts.vmtkSurfaceRemeshing()
            remeshing.Surface = surface
            remeshing.CellEntityIdsArrayName = self.CellEntityIdsArrayName
            remeshing.TargetEdgeLength = self.TargetEdgeLength
            remeshing.MaxEdgeLength = self.MaxEdgeLength
            remeshing.MinEdgeLength = self.MinEdgeLength
            remeshing.TargetEdgeLengthFactor = self.TargetEdgeLengthFactor
            remeshing.TargetEdgeLengthArrayName = self.TargetEdgeLengthArrayName
            remeshing.TriangleSplitFactor = self.TriangleSplitFactor
            remeshing.ElementSizeMode = self.ElementSizeMode
            if self.RemeshCapsOnly:
                remeshing.ExcludeEntityIds = [wallEntityOffset]
            remeshing.Execute()
            remeshedSurface = remeshing.Surface



        if self.BoundaryLayer:

            projection = vmtkscripts.vmtkSurfaceProjection()
            projection.Surface = remeshedSurface
            projection.ReferenceSurface = surface
            projection.Execute()

            normals = vmtkscripts.vmtkSurfaceNormals()
            normals.Surface = projection.Surface
            normals.NormalsArrayName = 'Normals'
            normals.Execute()

            surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh()
            surfaceToMesh.Surface = normals.Surface
            surfaceToMesh.Execute()

            self.PrintLog("Generating boundary layer fluid")
            placeholderCellEntityId = 9999
            boundaryLayer = vmtkscripts.vmtkBoundaryLayer()
            boundaryLayer.Mesh = surfaceToMesh.Mesh
            boundaryLayer.WarpVectorsArrayName = 'Normals'
            boundaryLayer.NegateWarpVectors = True
            boundaryLayer.ThicknessArrayName = self.TargetEdgeLengthArrayName
            if self.ElementSizeMode == 'edgelength':
                boundaryLayer.ConstantThickness = True
            else:
                boundaryLayer.ConstantThickness = False
            boundaryLayer.IncludeSurfaceCells = 0
            boundaryLayer.NumberOfSubLayers = self.NumberOfSubLayers
            boundaryLayer.NumberOfSubsteps = self.NumberOfSubsteps
            boundaryLayer.Relaxation = self.Relaxation
            boundaryLayer.LocalCorrectionFactor = self.LocalCorrectionFactor
            boundaryLayer.SubLayerRatio = self.SubLayerRatio
            boundaryLayer.Thickness = self.BoundaryLayerThicknessFactor * self.TargetEdgeLength
            boundaryLayer.ThicknessRatio = self.BoundaryLayerThicknessFactor * self.TargetEdgeLengthFactor
            boundaryLayer.MaximumThickness = self.BoundaryLayerThicknessFactor * self.MaxEdgeLength
            if not self.BoundaryLayerOnCaps:
                boundaryLayer.SidewallCellEntityId     = placeholderCellEntityId
                boundaryLayer.InnerSurfaceCellEntityId = wallEntityOffset
                boundaryLayer.VolumeCellEntityId       = self.VolumeId_fluid
            boundaryLayer.Execute()



            self.PrintLog("Generating boundary layer solid")
            boundaryLayer2 = vmtkscripts.vmtkBoundaryLayer()
            boundaryLayer2.Mesh = surfaceToMesh.Mesh
            boundaryLayer2.WarpVectorsArrayName = 'Normals'
            boundaryLayer2.NegateWarpVectors = True
            boundaryLayer2.ThicknessArrayName = self.TargetEdgeLengthArrayName
            if self.ElementSizeMode == 'edgelength':
                boundaryLayer2.ConstantThickness = True
            else:
                boundaryLayer2.ConstantThickness = False
            boundaryLayer2.IncludeSurfaceCells = 1
            boundaryLayer2.NumberOfSubLayers = self.NumberOfSubLayers
            boundaryLayer2.NumberOfSubsteps = self.NumberOfSubsteps
            boundaryLayer2.Relaxation = self.Relaxation
            boundaryLayer2.LocalCorrectionFactor = self.LocalCorrectionFactor
            boundaryLayer2.SubLayerRatio = self.SubLayerRatio
            boundaryLayer2.Thickness = self.BoundaryLayerThicknessFactor * self.TargetEdgeLength
            boundaryLayer2.ThicknessRatio = self.BoundaryLayerThicknessFactor * self.TargetEdgeLengthFactor
            boundaryLayer2.MaximumThickness = self.BoundaryLayerThicknessFactor * self.MaxEdgeLength
            if not self.BoundaryLayerOnCaps:
                boundaryLayer2.SidewallCellEntityId     = self.SolidSideWallId #placeholderCellEntityId
                boundaryLayer2.InnerSurfaceCellEntityId = self.InterfaceId_fsi # wallEntityOffset
                boundaryLayer2.OuterSurfaceCellEntityId = self.InterfaceId_outer # wallEntityOffset
                boundaryLayer2.VolumeCellEntityId       = self.VolumeId_solid
            boundaryLayer2.Execute()


            meshToSurface = vmtkscripts.vmtkMeshToSurface()
            meshToSurface.Mesh = boundaryLayer.InnerSurfaceMesh
            meshToSurface.Execute()

            innerSurface = meshToSurface.Surface


            if not self.BoundaryLayerOnCaps:

                self.PrintLog("Capping inner surface")
                capper = vmtkscripts.vmtkSurfaceCapper()
                capper.Surface = innerSurface
                capper.Interactive = 0
                capper.Method = self.CappingMethod
                capper.TriangleOutput = 1
                capper.CellEntityIdOffset = wallEntityOffset
                capper.Execute()

                self.PrintLog("Remeshing endcaps")
                remeshing = vmtkscripts.vmtkSurfaceRemeshing()
                remeshing.Surface = capper.Surface
                remeshing.CellEntityIdsArrayName = self.CellEntityIdsArrayName
                remeshing.TargetEdgeLength = self.TargetEdgeLength * self.EndcapsEdgeLengthFactor
                remeshing.MaxEdgeLength = self.MaxEdgeLength
                remeshing.MinEdgeLength = self.MinEdgeLength
                remeshing.TargetEdgeLengthFactor = self.TargetEdgeLengthFactor * self.EndcapsEdgeLengthFactor
                remeshing.TargetEdgeLengthArrayName = self.TargetEdgeLengthArrayName
                remeshing.TriangleSplitFactor = self.TriangleSplitFactor
                remeshing.ElementSizeMode = self.ElementSizeMode
                remeshing.ExcludeEntityIds = [wallEntityOffset] # [wallEntityOffset, InterfaceId] #[wallEntityOffset]
                remeshing.Execute()

                innerSurface = remeshing.Surface

            self.PrintLog("Computing sizing function")
            sizingFunction = vtkvmtk.vtkvmtkPolyDataSizingFunction()
            sizingFunction.SetInputData(innerSurface)
            sizingFunction.SetSizingFunctionArrayName(self.SizingFunctionArrayName)
            sizingFunction.SetScaleFactor(self.VolumeElementScaleFactor)
            sizingFunction.Update()

            surfaceToMesh2 = vmtkscripts.vmtkSurfaceToMesh()
            surfaceToMesh2.Surface = sizingFunction.GetOutput()
            surfaceToMesh2.Execute()

            self.PrintLog("Generating volume mesh")
            tetgen = vmtkscripts.vmtkTetGen()
            tetgen.Mesh = surfaceToMesh2.Mesh
            tetgen.GenerateCaps = 0
            tetgen.UseSizingFunction = 1
            tetgen.SizingFunctionArrayName = self.SizingFunctionArrayName
            tetgen.CellEntityIdsArrayName = self.CellEntityIdsArrayName
            tetgen.Order = 1
            tetgen.Quality = 1
            tetgen.PLC = 1
            tetgen.NoBoundarySplit = 1
            tetgen.RemoveSliver = 1
            tetgen.OutputSurfaceElements = 1
            tetgen.OutputVolumeElements = 1
            tetgen.RegionAttrib = 0
            tetgen.Execute()

            ##### ADDING CELL IDs

            #array = vtk.vtkDoubleArray()
            #array.SetNumberOfTuples(tetgen.Mesh.GetNumberOfCells())
            #array.SetNumberOfComponents(1)
            #array.FillComponent(0, 1.0)
            #array.SetName('RegionIDs')
            #tetgen.Mesh.GetCellData().AddArray(array)

            #array = vtk.vtkDoubleArray()
            #array.SetNumberOfTuples(boundaryLayer.Mesh.GetNumberOfCells())
            #array.SetNumberOfComponents(1)
            #array.FillComponent(0, 1.0)
            #array.SetName('RegionIDs')
            #boundaryLayer.Mesh.GetCellData().AddArray(array)

            #array = vtk.vtkDoubleArray()
            #array.SetNumberOfTuples(boundaryLayer2.Mesh.GetNumberOfCells())
            #array.SetNumberOfComponents(1)
            #array.FillComponent(0, 2.0)
            #array.SetName('RegionIDs')
            #boundaryLayer2.Mesh.GetCellData().AddArray(array)

            #####

            # w1 = vtk.vtkXMLUnstructuredGridWriter()
            # w1.SetInputData(boundaryLayer2.Mesh)
            # w1.SetFileName('BoundaryLayer2.vtu')
            # w1.Write()
            #
            # w2 = vtk.vtkXMLUnstructuredGridWriter()
            # w2.SetInputData(tetgen.Mesh)
            # w2.SetFileName('Tetgen.vtu')
            # w2.Write()
            #
            # w3 = vtk.vtkXMLUnstructuredGridWriter()
            # w3.SetInputData(boundaryLayer.Mesh)
            # w3.SetFileName('BoundaryLayer.vtu')
            # w3.Write()
            #
            # w4 = vtk.vtkXMLUnstructuredGridWriter()
            # w4.SetInputData(boundaryLayer.InnerSurfaceMesh)
            # w4.SetFileName('InnerLayer.vtu')
            # w4.Write()

            #from IPython import embed; embed()

            self.PrintLog("Assembling fluid mesh")
            appendFilter = vtkvmtk.vtkvmtkAppendFilter()
            appendFilter.AddInputData(boundaryLayer.Mesh)
            appendFilter.AddInputData(tetgen.Mesh)
            appendFilter.Update()
            self.Mesh = appendFilter.GetOutput()

            if not self.BoundaryLayerOnCaps:
                cellEntityIdsArray = self.Mesh.GetCellData().GetArray(self.CellEntityIdsArrayName)

                def VisitNeighbors(i, cellEntityId):
                    cellPointIds = vtk.vtkIdList()
                    self.Mesh.GetCellPoints(i,cellPointIds)
                    neighborPointIds = vtk.vtkIdList()
                    neighborPointIds.SetNumberOfIds(1)
                    pointNeighborCellIds = vtk.vtkIdList()
                    neighborCellIds = vtk.vtkIdList()

                    for j in range(cellPointIds.GetNumberOfIds()):
                        neighborPointIds.SetId(0,cellPointIds.GetId(j))
                        self.Mesh.GetCellNeighbors(i,neighborPointIds,pointNeighborCellIds)
                        for k in range(pointNeighborCellIds.GetNumberOfIds()):
                            neighborCellIds.InsertNextId(pointNeighborCellIds.GetId(k))

                    for j in range(neighborCellIds.GetNumberOfIds()):
                        cellId = neighborCellIds.GetId(j)
                        neighborCellEntityId = cellEntityIdsArray.GetTuple1(cellId)
                        neighborCellType = self.Mesh.GetCellType(cellId)
                        if neighborCellType not in [vtk.VTK_TRIANGLE, vtk.VTK_QUADRATIC_TRIANGLE, vtk.VTK_QUAD]:
                            continue
                        if neighborCellEntityId != placeholderCellEntityId:
                            continue
                        cellEntityIdsArray.SetTuple1(cellId,cellEntityId)
                        VisitNeighbors(cellId,cellEntityId)

                for i in range(self.Mesh.GetNumberOfCells()):
                    cellEntityId = cellEntityIdsArray.GetTuple1(i)
                    cellType = self.Mesh.GetCellType(i)
                    if cellType not in [vtk.VTK_TRIANGLE, vtk.VTK_QUADRATIC_TRIANGLE, vtk.VTK_QUAD]:
                        continue
                    if cellEntityId in [0, 1, placeholderCellEntityId]:
                        continue
                    VisitNeighbors(i,cellEntityId)


            self.PrintLog("Assembling final FSI mesh")
            appendFilter2 = vtkvmtk.vtkvmtkAppendFilter()
            appendFilter2.AddInputData(appendFilter.GetOutput())
            appendFilter2.AddInputData(boundaryLayer2.Mesh)
            appendFilter2.Update()
            self.Mesh = appendFilter2.GetOutput()


        else:

            self.PrintLog("Computing sizing function")
            sizingFunction = vtkvmtk.vtkvmtkPolyDataSizingFunction()
            sizingFunction.SetInputData(remeshedSurface)
            sizingFunction.SetSizingFunctionArrayName(self.SizingFunctionArrayName)
            sizingFunction.SetScaleFactor(self.VolumeElementScaleFactor)
            sizingFunction.Update()

            self.PrintLog("Converting surface to mesh")
            surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh()
            surfaceToMesh.Surface = sizingFunction.GetOutput()
            surfaceToMesh.Execute()

            self.PrintLog("Generating volume mesh")
            tetgen = vmtkscripts.vmtkTetGen()
            tetgen.Mesh = surfaceToMesh.Mesh
            tetgen.GenerateCaps = 0
            tetgen.UseSizingFunction = 1
            tetgen.SizingFunctionArrayName = self.SizingFunctionArrayName
            tetgen.CellEntityIdsArrayName = self.CellEntityIdsArrayName
            tetgen.Order = 1
            tetgen.Quality = 1
            tetgen.PLC = 1
            tetgen.NoBoundarySplit = 1
            tetgen.RemoveSliver = 1
            tetgen.OutputSurfaceElements = 1
            tetgen.OutputVolumeElements = 1

            tetgen.Execute()

            self.Mesh = tetgen.Mesh

            if self.Mesh.GetNumberOfCells() == 0 and surfaceToMesh.Mesh.GetNumberOfCells() > 0:
                self.PrintLog('An error occurred during tetrahedralization. Will only output surface mesh.')
                self.Mesh = surfaceToMesh.Mesh

        if self.Tetrahedralize:

            tetrahedralize = vtkvmtk.vtkvmtkUnstructuredGridTetraFilter()
            tetrahedralize.SetInputData(self.Mesh)
            tetrahedralize.Update()

            self.Mesh = tetrahedralize.GetOutput()

        self.RemeshedSurface = remeshedSurface
Ejemplo n.º 12
0
    def Execute(self):

        from vmtk import vmtkscripts
        if self.Surface == None:
            self.PrintError('Error: No input surface.')

        wallEntityOffset = 1

        if self.SkipCapping or not self.BoundaryLayerOnCaps:
            self.PrintLog("Not capping surface")
            surface = self.Surface
            cellEntityIdsArray = vtk.vtkIntArray()
            cellEntityIdsArray.SetName(self.CellEntityIdsArrayName)
            cellEntityIdsArray.SetNumberOfTuples(surface.GetNumberOfCells())
            cellEntityIdsArray.FillComponent(0, 0.0)
            surface.GetCellData().AddArray(cellEntityIdsArray)
        else:
            self.PrintLog("Capping surface")
            capper = vmtkscripts.vmtkSurfaceCapper()
            capper.Surface = self.Surface
            capper.Interactive = 0
            capper.Method = self.CappingMethod
            capper.TriangleOutput = 0
            capper.CellEntityIdOffset = self.Vessel_inlet_outlet
            capper.Execute()
            surface = capper.Surface

        if self.SkipRemeshing:
            remeshedSurface = surface
        else:
            self.PrintLog("Remeshing surface")
            remeshing = vmtkscripts.vmtkSurfaceRemeshing()
            remeshing.Surface = surface
            remeshing.CellEntityIdsArrayName = self.CellEntityIdsArrayName
            remeshing.TargetEdgeLength = self.TargetEdgeLength
            remeshing.MaxEdgeLength = self.MaxEdgeLength
            remeshing.MinEdgeLength = self.MinEdgeLength
            remeshing.TargetEdgeLengthFactor = self.TargetEdgeLengthFactor
            remeshing.TargetEdgeLengthArrayName = self.TargetEdgeLengthArrayName
            remeshing.TriangleSplitFactor = self.TriangleSplitFactor
            remeshing.ElementSizeMode = self.ElementSizeMode
            if self.RemeshCapsOnly:
                remeshing.ExcludeEntityIds = [self.Vessel_wall]
            remeshing.Execute()
            remeshedSurface = remeshing.Surface

        if self.BoundaryLayer:

            projection = vmtkscripts.vmtkSurfaceProjection()
            projection.Surface = remeshedSurface
            projection.ReferenceSurface = surface
            projection.Execute()

            normals = vmtkscripts.vmtkSurfaceNormals()
            normals.Surface = projection.Surface
            normals.NormalsArrayName = 'Normals'
            normals.Execute()

            surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh()
            surfaceToMesh.Surface = normals.Surface
            surfaceToMesh.Execute()

            self.PrintLog("Generating 1st boundary layer -- PVS")
            placeholderCellEntityId = 9999
            boundaryLayer = vmtkscripts.vmtkBoundaryLayer()
            boundaryLayer.Mesh = surfaceToMesh.Mesh
            boundaryLayer.WarpVectorsArrayName = 'Normals'
            boundaryLayer.NegateWarpVectors = True
            boundaryLayer.ThicknessArrayName = self.TargetEdgeLengthArrayName
            if self.ElementSizeMode == 'edgelength':
                boundaryLayer.ConstantThickness = True
            else:
                boundaryLayer.ConstantThickness = False
            boundaryLayer.IncludeSurfaceCells = 0
            boundaryLayer.NumberOfSubLayers = self.NumberOfSubLayers
            boundaryLayer.NumberOfSubsteps = self.NumberOfSubsteps
            boundaryLayer.Relaxation = self.Relaxation
            boundaryLayer.LocalCorrectionFactor = self.LocalCorrectionFactor
            boundaryLayer.SubLayerRatio = self.SubLayerRatio
            boundaryLayer.Thickness = self.BoundaryLayerThicknessFactor * self.TargetEdgeLength
            boundaryLayer.ThicknessRatio = self.BoundaryLayerThicknessFactor * self.TargetEdgeLengthFactor
            boundaryLayer.MaximumThickness = self.BoundaryLayerThicknessFactor * self.MaxEdgeLength
            if not self.BoundaryLayerOnCaps:
                boundaryLayer.SidewallCellEntityId = placeholderCellEntityId
                boundaryLayer.InnerSurfaceCellEntityId = self.Vessel_wall
                boundaryLayer.VolumeCellEntityId = self.PVS
            boundaryLayer.Execute()

            # We need a second boundary layer to make sure we have the right OuterSurface
            self.PrintLog("Generating 2nd boundary layer -- PVS")
            placeholderCellEntityId2 = 99999
            boundaryLayer2 = vmtkscripts.vmtkBoundaryLayer()
            boundaryLayer2.Mesh = surfaceToMesh.Mesh
            boundaryLayer2.WarpVectorsArrayName = 'Normals'
            boundaryLayer2.NegateWarpVectors = True
            boundaryLayer2.ThicknessArrayName = self.TargetEdgeLengthArrayName
            if self.ElementSizeMode == 'edgelength':
                boundaryLayer2.ConstantThickness = True
            else:
                boundaryLayer2.ConstantThickness = False
            boundaryLayer2.IncludeSurfaceCells = 1
            boundaryLayer2.NumberOfSubLayers = self.NumberOfSubLayers
            boundaryLayer2.NumberOfSubsteps = self.NumberOfSubsteps
            boundaryLayer2.Relaxation = self.Relaxation
            boundaryLayer2.LocalCorrectionFactor = self.LocalCorrectionFactor
            boundaryLayer2.SubLayerRatio = self.SubLayerRatio
            boundaryLayer2.Thickness = self.BoundaryLayerThicknessFactor * self.TargetEdgeLength
            boundaryLayer2.ThicknessRatio = self.BoundaryLayerThicknessFactor * self.TargetEdgeLengthFactor
            boundaryLayer2.MaximumThickness = self.BoundaryLayerThicknessFactor * self.MaxEdgeLength
            if not self.BoundaryLayerOnCaps:
                boundaryLayer2.SidewallCellEntityId = placeholderCellEntityId2
                boundaryLayer2.OuterSurfaceCellEntityId = self.PVS_wall
                boundaryLayer2.VolumeCellEntityId = self.PVS
            boundaryLayer2.Execute()

            meshToSurface = vmtkscripts.vmtkMeshToSurface()
            meshToSurface.Mesh = boundaryLayer.InnerSurfaceMesh
            meshToSurface.Execute()

            innerSurface = meshToSurface.Surface

            if not self.BoundaryLayerOnCaps:

                self.PrintLog("Capping inner surface")
                capper = vmtkscripts.vmtkSurfaceCapper()
                capper.Surface = innerSurface
                capper.Interactive = 0
                capper.Method = self.CappingMethod
                capper.TriangleOutput = 1
                capper.CellEntityIdOffset = self.Vessel_inlet_outlet
                capper.Execute()

                self.PrintLog("Remeshing endcaps")
                remeshing = vmtkscripts.vmtkSurfaceRemeshing()
                remeshing.Surface = capper.Surface
                remeshing.CellEntityIdsArrayName = self.CellEntityIdsArrayName
                remeshing.TargetEdgeLength = self.TargetEdgeLength * self.EndcapsEdgeLengthFactor
                remeshing.MaxEdgeLength = self.MaxEdgeLength
                remeshing.MinEdgeLength = self.MinEdgeLength
                remeshing.TargetEdgeLengthFactor = self.TargetEdgeLengthFactor * self.EndcapsEdgeLengthFactor
                remeshing.TargetEdgeLengthArrayName = self.TargetEdgeLengthArrayName
                remeshing.TriangleSplitFactor = self.TriangleSplitFactor
                remeshing.ElementSizeMode = self.ElementSizeMode
                remeshing.ExcludeEntityIds = [self.Vessel_wall]
                remeshing.Execute()

                innerSurface = remeshing.Surface

            self.PrintLog("Computing sizing function")
            sizingFunction = vtkvmtk.vtkvmtkPolyDataSizingFunction()
            sizingFunction.SetInputData(innerSurface)
            sizingFunction.SetSizingFunctionArrayName(
                self.SizingFunctionArrayName)
            sizingFunction.SetScaleFactor(self.VolumeElementScaleFactor)
            sizingFunction.Update()

            surfaceToMesh2 = vmtkscripts.vmtkSurfaceToMesh()
            surfaceToMesh2.Surface = sizingFunction.GetOutput()
            surfaceToMesh2.Execute()

            self.PrintLog("Generating volume mesh")
            tetgen = vmtkscripts.vmtkTetGen()
            tetgen.Mesh = surfaceToMesh2.Mesh
            tetgen.GenerateCaps = 0
            tetgen.UseSizingFunction = 1
            tetgen.SizingFunctionArrayName = self.SizingFunctionArrayName
            tetgen.CellEntityIdsArrayName = self.CellEntityIdsArrayName
            tetgen.Order = 1
            tetgen.Quality = 1
            tetgen.PLC = 1
            tetgen.NoBoundarySplit = 1
            tetgen.RemoveSliver = 1
            tetgen.OutputSurfaceElements = 1
            tetgen.OutputVolumeElements = 1
            tetgen.RegionAttrib = 1
            tetgen.Execute()

            # Define VisitNeighbors used to differenciate markers in Sidewall areas
            def VisitNeighbors(i, cellEntityId, cellEntityIdsArray,
                               placeholderTag):
                cellPointIds = vtk.vtkIdList()
                self.Mesh.GetCellPoints(i, cellPointIds)
                neighborPointIds = vtk.vtkIdList()
                neighborPointIds.SetNumberOfIds(1)
                pointNeighborCellIds = vtk.vtkIdList()
                neighborCellIds = vtk.vtkIdList()

                for j in range(cellPointIds.GetNumberOfIds()):
                    neighborPointIds.SetId(0, cellPointIds.GetId(j))
                    self.Mesh.GetCellNeighbors(i, neighborPointIds,
                                               pointNeighborCellIds)
                    for k in range(pointNeighborCellIds.GetNumberOfIds()):
                        neighborCellIds.InsertNextId(
                            pointNeighborCellIds.GetId(k))

                for j in range(neighborCellIds.GetNumberOfIds()):
                    cellId = neighborCellIds.GetId(j)
                    neighborCellEntityId = cellEntityIdsArray.GetTuple1(cellId)
                    neighborCellType = self.Mesh.GetCellType(cellId)
                    if neighborCellType not in [
                            vtk.VTK_TRIANGLE, vtk.VTK_QUADRATIC_TRIANGLE,
                            vtk.VTK_QUAD
                    ]:
                        continue
                    if neighborCellEntityId != placeholderTag:
                        continue
                    cellEntityIdsArray.SetTuple1(cellId, cellEntityId)
                    VisitNeighbors(cellId, cellEntityId, cellEntityIdsArray,
                                   placeholderTag)

            self.PrintLog("Assembling PVS mesh - 1st layer")
            appendFilter = vtkvmtk.vtkvmtkAppendFilter()
            appendFilter.AddInputData(boundaryLayer.Mesh)
            appendFilter.AddInputData(tetgen.Mesh)
            appendFilter.Update()
            self.Mesh = appendFilter.GetOutput()

            # Use placeholderCellEntityId - inlet/outlet for the PVS-1
            if not self.BoundaryLayerOnCaps:
                cellEntityIdsArray = self.Mesh.GetCellData().GetArray(
                    self.CellEntityIdsArrayName)

                for i in range(self.Mesh.GetNumberOfCells()):
                    cellEntityId = cellEntityIdsArray.GetTuple1(i)
                    cellType = self.Mesh.GetCellType(i)
                    if cellType not in [
                            vtk.VTK_TRIANGLE, vtk.VTK_QUADRATIC_TRIANGLE,
                            vtk.VTK_QUAD
                    ]:
                        continue
                    if cellEntityId in [
                            0, 1, placeholderCellEntityId, self.Vessel_wall
                    ]:
                        continue
                    VisitNeighbors(
                        i, cellEntityId + self.PVS_inlet_outlet -
                        self.Vessel_inlet_outlet, cellEntityIdsArray,
                        placeholderCellEntityId)

            appendFilter.Update()
            self.Mesh = appendFilter.GetOutput()
            self.PrintLog("Assembling PVS mesh - 2nd layer")
            appendFilter2 = vtkvmtk.vtkvmtkAppendFilter()
            appendFilter2.AddInputData(appendFilter.GetOutput())
            appendFilter2.AddInputData(boundaryLayer2.Mesh)
            appendFilter2.Update()
            self.Mesh = appendFilter2.GetOutput()

            # Use placeholderCellEntityId2 - inlet/outlet for the PVS-2
            if not self.BoundaryLayerOnCaps:
                cellEntityIdsArray = self.Mesh.GetCellData().GetArray(
                    self.CellEntityIdsArrayName)

                for i in range(self.Mesh.GetNumberOfCells()):
                    cellEntityId = cellEntityIdsArray.GetTuple1(i)
                    cellType = self.Mesh.GetCellType(i)
                    if cellType not in [
                            vtk.VTK_TRIANGLE, vtk.VTK_QUADRATIC_TRIANGLE,
                            vtk.VTK_QUAD
                    ]:
                        continue
                    if cellEntityId in [
                            0, 1, placeholderCellEntityId2, self.Vessel_wall
                    ]:
                        continue
                    VisitNeighbors(i, cellEntityId, cellEntityIdsArray,
                                   placeholderCellEntityId2)

            self.PrintLog("Assembling final mesh")
            appendFilter2.Update()
            self.Mesh = appendFilter2.GetOutput()
        else:

            self.PrintLog("Computing sizing function")
            sizingFunction = vtkvmtk.vtkvmtkPolyDataSizingFunction()
            sizingFunction.SetInputData(remeshedSurface)
            sizingFunction.SetSizingFunctionArrayName(
                self.SizingFunctionArrayName)
            sizingFunction.SetScaleFactor(self.VolumeElementScaleFactor)
            sizingFunction.Update()

            self.PrintLog("Converting surface to mesh")
            surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh()
            surfaceToMesh.Surface = sizingFunction.GetOutput()
            surfaceToMesh.Execute()

            self.PrintLog("Generating volume mesh")
            tetgen = vmtkscripts.vmtkTetGen()
            tetgen.Mesh = surfaceToMesh.Mesh
            tetgen.GenerateCaps = 0
            tetgen.UseSizingFunction = 1
            tetgen.SizingFunctionArrayName = self.SizingFunctionArrayName
            tetgen.CellEntityIdsArrayName = self.CellEntityIdsArrayName
            tetgen.Order = 1
            tetgen.Quality = 1
            tetgen.PLC = 1
            tetgen.NoBoundarySplit = 1
            tetgen.RemoveSliver = 1
            tetgen.OutputSurfaceElements = 1
            tetgen.OutputVolumeElements = 1

            tetgen.Execute()

            self.Mesh = tetgen.Mesh

            if self.Mesh.GetNumberOfCells(
            ) == 0 and surfaceToMesh.Mesh.GetNumberOfCells() > 0:
                self.PrintLog(
                    'An error occurred during tetrahedralization. Will only output surface mesh.'
                )
                self.Mesh = surfaceToMesh.Mesh

        if self.Tetrahedralize:

            tetrahedralize = vtkvmtk.vtkvmtkUnstructuredGridTetraFilter()
            tetrahedralize.SetInputData(self.Mesh)
            tetrahedralize.Update()

            self.Mesh = tetrahedralize.GetOutput()

        self.RemeshedSurface = remeshedSurface
Ejemplo n.º 13
0
def run_script(args):
    print("extract dome from clipped cfd surface")

    reader_dome = vmtkscripts.vmtkSurfaceReader()
    reader_dome.InputFileName = args.surface_file
    reader_dome.Execute()
    dome_surface = reader_dome.Surface

    wall_reader = vmtkscripts.vmtkSurfaceReader()
    wall_reader.InputFileName = args.wall_file
    wall_reader.Execute()

    #mesh_reader = vmtkscripts.vmtkMeshReader()
    #mesh_reader.InputFileName = args.mesh_file
    #mesh_reader.Execute()

    #mesh2surf = vmtkscripts.vmtkMeshToSurface()
    #mesh2surf.Mesh = mesh_reader.Mesh
    #mesh2surf.CleanOutput = 0
    #mesh2surf.Execute()

    #scale_cfd = vmtkscripts.vmtkSurfaceScaling()
    #scale_cfd.ScaleFactor = 1000 # meters to mm
    #scale_cfd.Surface = mesh2surf.Surface
    #scale_cfd.Execute()

    dist = vmtkscripts.vmtkSurfaceDistance()
    dist.Surface = wall_reader.Surface
    dist.ReferenceSurface = dome_surface
    dist.DistanceArrayName = "distance"
    dist.DistanceVectorsArrayName = "distance_vectors"
    dist.SignedDistanceArrayName = "signed_distance"
    dist.Execute()

    clip_copy = vtk.vtkPolyData()
    clip_copy.DeepCopy(dist.Surface)

    clip = vmtkscripts.vmtkSurfaceClipper()
    clip.Surface = dist.Surface
    clip.Interactive = 0
    clip.InsideOut = 1
    clip.ClipArrayName = "distance"
    clip.ClipValue = 0.1
    clip.Execute()

    conn = vmtkscripts.vmtkSurfaceConnectivity()
    conn.Surface = clip.Surface
    conn.Method = "largest"
    conn.CleanOutput = 0
    conn.Execute()

    normals = vmtkscripts.vmtkSurfaceNormals()
    normals.Surface = conn.Surface
    #accept defaults
    normals.Execute()

    writer = vmtkscripts.vmtkSurfaceWriter()
    writer.OutputFileName = args.file_out
    writer.Input = normals.Surface
    writer.Execute()

    if (args.inverse_out):
        clip_inverse = vmtkscripts.vmtkSurfaceClipper()
        clip_inverse.Surface = clip_copy
        clip_inverse.Interactive = 0
        clip_inverse.InsideOut = 0
        clip_inverse.ClipArrayName = "distance"
        clip_inverse.ClipValue = 0.1
        clip_inverse.Execute()

        conn2 = vmtkscripts.vmtkSurfaceConnectivity()
        conn2.Surface = clip_inverse.Surface
        conn2.Method = "all"
        conn2.CleanOutput = 0
        conn2.Execute()

        writer2 = vmtkscripts.vmtkSurfaceWriter()
        writer2.OutputFileName = args.inverse_out
        writer2.Input = conn2.Surface
        writer2.Execute()
Ejemplo n.º 14
0
    def Execute(self):
        if self.Surface == None:
            self.PrintError('Error: no Surface.')

        triangleFilter = vtk.vtkTriangleFilter()
        triangleFilter.SetInput(self.Surface)
        triangleFilter.Update()

        self.Surface = triangleFilter.GetOutput()

        if self.Loop == None:
            self.PrintError('Error: no Loop.')

        select = vtk.vtkImplicitSelectionLoop()
        select.SetLoop(self.Loop.GetPoints())
        normal = [0.0,0.0,0.0]
        centroid = [0.0,0.0,0.0]
        vtk.vtkPolygon().ComputeNormal(self.Loop.GetPoints(),normal)

        #compute centroid and check normals
        p = [0.0,0.0,0.0]
        for i in range (self.Loop.GetNumberOfPoints()):
            p = self.Loop.GetPoint(i)
            centroid[0] += p[0]
            centroid[1] += p[1]
            centroid[2] += p[2]
        centroid[0] = centroid[0] / self.Loop.GetNumberOfPoints()
        centroid[1] = centroid[1] / self.Loop.GetNumberOfPoints()
        centroid[2] = centroid[2] / self.Loop.GetNumberOfPoints()
        print "loop centroid", centroid

        locator = vtk.vtkPointLocator()
        locator.SetDataSet(self.Surface)
        locator.AutomaticOn()
        locator.BuildLocator()
        idsurface = locator.FindClosestPoint(centroid)

        if (self.Surface.GetPointData().GetNormals() == None):
            normalsFilter = vmtkscripts.vmtkSurfaceNormals()
            normalsFilter.Surface = self.Surface
            normalsFilter.NormalsArrayName = 'Normals'
            normalsFilter.Execute()
            self.Surface = normalsFilter.Surface
        normalsurface = [0.0,0.0,0.0]
        self.Surface.GetPointData().GetNormals().GetTuple(idsurface,normalsurface)
        print "loop normal: ", normal
        print "surface normal inside the loop: ", normalsurface
        check = vtk.vtkMath.Dot(normalsurface,normal)
        if check < 0:
            normal[0] = - normal[0]
            normal[1] = - normal[1]
            normal[2] = - normal[2]

        #compute plane
        proj = float(vtk.vtkMath.Dot(self.Loop.GetPoint(0),normal))
        point = [0.0,0.0,0.0]
        self.Loop.GetPoint(0,point)
        for i in range (self.Loop.GetNumberOfPoints()):
            tmp = vtk.vtkMath.Dot(self.Loop.GetPoint(i),normal)
            if tmp < proj:
                proj = tmp
                self.Loop.GetPoint(i,point)
        origin = [0.0,0.0,0.0]
        origin[0] = point[0] #- normal[0]
        origin[1] = point[1] #- normal[1]
        origin[2] = point[2] #- normal[2]
        plane=vtk.vtkPlane()
        plane.SetNormal(normal[0],normal[1],normal[2])
        plane.SetOrigin(origin[0],origin[1],origin[2])

        #set bool
        Bool = vtk.vtkImplicitBoolean()
        Bool.SetOperationTypeToDifference()
        Bool.AddFunction(select)
        Bool.AddFunction(plane)

        clipper=vtk.vtkClipPolyData()
        clipper.SetInput(self.Surface)
        clipper.SetClipFunction(Bool)
        clipper.GenerateClippedOutputOn()
        clipper.InsideOutOff()
        clipper.Update()

        self.Surface = clipper.GetOutput()