def ReadPointCloud(filename):
    print 'Reading file: ', filename
    #vtkPoints here:
    #method1: assign number of points, insert points by ID, ::SetPoint(ID, double[3])
    #method2: assign no size, insert one after anther,      ::InsertNextPoint(double[3])
    points = vtk.vtkPoints()
    poly = vtk.vtkPolyData()
    glyphFilter = vtk.vtkVertexGlyphFilter(
    )  # I don't know what is the purpose

    fp = open(filename, "rb+")
    line = fp.readline()
    while line != '':
        line = line.strip()
        if line == '':
            continue
        elif line.find('\t') < 0:
            line = line.split(' ')
        else:
            line = line.split('\t')

        points.InsertNextPoint(float(line[0]), float(line[1]), float(line[2]))
        #read next line and return to loop
        line = fp.readline()

    #add point to poly data
    poly.SetPoints(points)
    glyphFilter.SetInputData(poly)
    glyphFilter.Update()

    #visualize
    PolyVisualize(glyphFilter.GetOutputPort())
Esempio n. 2
0
    def create_path_geometry(self):
        """ 
       Create geometry for the path.
       """

        ## Show path points.
        #
        for element in self.elements:
            coords = element.points
            num_pts = len(coords)

            # Create path geometry points and line connectivity.
            points = vtk.vtkPoints()
            points.SetNumberOfPoints(num_pts)
            lines = vtk.vtkCellArray()
            lines.InsertNextCell(num_pts)
            #lines.InsertNextCell(num_pts+1)
            n = 0
            for pt in coords:
                points.SetPoint(n, pt[0], pt[1], pt[2])
                lines.InsertCellPoint(n)
                n += 1
            #_for pt in coords
            lines.InsertCellPoint(0)

            geom = vtk.vtkPolyData()
            geom.SetPoints(points)
            geom.SetLines(lines)
            #geom.BuildLinks()
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputData(geom)
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            actor.GetProperty().SetLineWidth(4.0)
            actor.GetProperty().SetColor(1.0, 0.0, 0.0)
            self.graphics.add_actor(actor)

        ## Show control points.
        #
        for element in self.elements:
            coords = element.control_points
            points = vtk.vtkPoints()
            points.SetNumberOfPoints(len(coords))
            n = 0
            for pt in coords:
                points.SetPoint(n, pt[0], pt[1], pt[2])
                n += 1
            #_for pt in coords

            geom = vtk.vtkPolyData()
            geom.SetPoints(points)
            glyphFilter = vtk.vtkVertexGlyphFilter()
            glyphFilter.SetInputData(geom)
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(glyphFilter.GetOutputPort())
            actor = vtk.vtkActor()
            actor.GetProperty().SetColor(0.0, 0.0, 0.8)
            actor.GetProperty().SetPointSize(10)
            actor.SetMapper(mapper)
            self.graphics.add_actor(actor)
Esempio n. 3
0
 def _colorPoints(plist, cols, r, alpha):
     n = len(plist)
     if n > len(cols):
         colors.printc("~times Error: mismatch in colorPoints()",
                       n,
                       len(cols),
                       c=1)
         exit()
     if n != len(cols):
         colors.printc("~lightning Warning: mismatch in colorPoints()", n,
                       len(cols))
     src = vtk.vtkPointSource()
     src.SetNumberOfPoints(n)
     src.Update()
     vgf = vtk.vtkVertexGlyphFilter()
     vgf.SetInputData(src.GetOutput())
     vgf.Update()
     pd = vgf.GetOutput()
     ucols = vtk.vtkUnsignedCharArray()
     ucols.SetNumberOfComponents(3)
     ucols.SetName("pointsRGB")
     for i in range(len(plist)):
         c = np.array(colors.getColor(cols[i])) * 255
         ucols.InsertNextTuple3(c[0], c[1], c[2])
     pd.GetPoints().SetData(numpy_to_vtk(plist, deep=True))
     pd.GetPointData().SetScalars(ucols)
     actor = Actor(pd, c, alpha)
     actor.mapper.ScalarVisibilityOn()
     actor.GetProperty().SetInterpolationToFlat()
     actor.GetProperty().SetPointSize(r)
     settings.collectable_actors.append(actor)
     return actor
Esempio n. 4
0
    def generate_vertex_glyph_filter(self, poly):

        glyph_filter = vtk.vtkVertexGlyphFilter()

        glyph_filter.SetInput(poly)

        return glyph_filter
Esempio n. 5
0
    def _add_nodes_to_cap(vtkPts, size):
        """
        Add uniformed points to cap
        """
        points = vtk_to_numpy(vtkPts.GetData())
        num = points.shape[0]
        #_plot_points(points)
        ctr = np.mean(points, axis=0)
        length = np.mean(np.linalg.norm(points - ctr, axis=1))
        r = np.linspace(0.5 * size / length, (length - size * 0.8) / length,
                        int(np.floor(length / size)))
        addedPts = vtk.vtkPoints()
        for rf in r:
            newPts = vtk.vtkPoints()
            newPts.SetData(numpy_to_vtk((points - ctr) * rf + ctr))
            addedPts.InsertPoints(addedPts.GetNumberOfPoints(),
                                  newPts.GetNumberOfPoints(), 0, newPts)
        ptsPly = vtk.vtkPolyData()
        ptsPly.SetPoints(addedPts)
        vertexFilter = vtk.vtkVertexGlyphFilter()
        vertexFilter.SetInputData(ptsPly)
        vertexFilter.Update()
        ptsPly = vertexFilter.GetOutput()
        cleanedPts = clean_polydata(ptsPly, size * 0.01)

        vtkPts.InsertPoints(vtkPts.GetNumberOfPoints(),
                            cleanedPts.GetNumberOfPoints(), 0,
                            cleanedPts.GetPoints())

        #_plot_points(vtk_to_numpy(vtkPts.GetData()))
        return vtkPts
Esempio n. 6
0
def _colorPoints(plist, cols, r, alpha, legend):
    n = len(plist)
    if n > len(cols):
        colors.printc("Mismatch in colorPoints()", n, len(cols), c=1)
        exit()
    if n != len(cols):
        colors.printc("Warning: mismatch in colorPoints()", n, len(cols))
    src = vtk.vtkPointSource()
    src.SetNumberOfPoints(n)
    src.Update()
    vertexFilter = vtk.vtkVertexGlyphFilter()
    vertexFilter.SetInputData(src.GetOutput())
    vertexFilter.Update()
    pd = vertexFilter.GetOutput()
    ucols = vtk.vtkUnsignedCharArray()
    ucols.SetNumberOfComponents(3)
    ucols.SetName("RGB")
    for i, p in enumerate(plist):
        c = np.array(colors.getColor(cols[i])) * 255
        ucols.InsertNextTuple3(c[0], c[1], c[2])
    pd.GetPoints().SetData(numpy_to_vtk(plist, deep=True))
    pd.GetPointData().SetScalars(ucols)
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(pd)
    mapper.ScalarVisibilityOn()
    actor = Actor()  #vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetInterpolationToFlat()
    actor.GetProperty().SetOpacity(alpha)
    actor.GetProperty().SetPointSize(r)
    return actor
Esempio n. 7
0
def glyph_dot(centers, colors, radius=100):
    if np.array(colors).ndim == 1:
        colors = np.tile(colors, (len(centers), 1))

    vtk_pnt = numpy_to_vtk_points(centers)

    pnt_polydata = vtk.vtkPolyData()
    pnt_polydata.SetPoints(vtk_pnt)

    vertex_filter = vtk.vtkVertexGlyphFilter()
    vertex_filter.SetInputData(pnt_polydata)
    vertex_filter.Update()

    polydata = vtk.vtkPolyData()
    polydata.ShallowCopy(vertex_filter.GetOutput())

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(polydata)
    mapper.SetScalarModeToUsePointFieldData()

    pnt_actor = vtk.vtkActor()
    pnt_actor.SetMapper(mapper)

    pnt_actor.GetProperty().SetPointSize(radius)

    cols = numpy_to_vtk_colors(255 * np.ascontiguousarray(colors))
    cols.SetName('colors')
    polydata.GetPointData().AddArray(cols)
    mapper.SelectColorArray('colors')

    return pnt_actor
Esempio n. 8
0
    def addPoints(self, points, color, thick=False, thickness=_DEFAULT_POINT_THICKNESS):
        vtkPoints = vtk.vtkPoints()
        for point in points:
            vtkPoints.InsertNextPoint(point[0], point[1], point[2])

        pointsPolyData = vtk.vtkPolyData()
        pointsPolyData.SetPoints(vtkPoints)

        if thick:
            sphereSource = vtk.vtkSphereSource()
            sphereSource.SetRadius(thickness)
            
            glyph3D = vtk.vtkGlyph3D()
            glyph3D.SetSourceConnection(sphereSource.GetOutputPort())
            glyph3D.SetInputData(pointsPolyData)
            glyph3D.Update()
 
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(glyph3D.GetOutputPort())
        else:
            vertexFilter = vtk.vtkVertexGlyphFilter()
            vertexFilter.SetInputData(pointsPolyData)
            vertexFilter.Update()                          

            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputData(vertexFilter.GetOutput())

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(color)

        self._rendererScene.AddActor(actor)
Esempio n. 9
0
    def AdjustColor(self, flag):
        if self.myactor is None:

            self.selection = vtk.vtkExtractGeometry()

            self.selection.SetInputConnection(self.input.GetOutputPort())
            filter = vtk.vtkVertexGlyphFilter()
            filter.SetInputConnection(self.selection.GetOutputPort())
            self.myactor = PolyDataActor(filter.GetOutputPort())
            self.renderer.AddMyActor(self.myactor)

        polydata = vtk.vtkPolyData()
        self.GetPolyData(polydata)
        self.selection.SetImplicitFunction(polydata)
        self.myactor.Update()
        num_points = self.myactor.GetNumberOfPoints()
        print("num of points: ", num_points)
        num_cells = self.myactor.GetNumberOfCells()

        f = self.GetEnabled() if flag else not self.GetEnabled()
        if f:
            color_name = "green"
        else:
            color_name = "red"
        # generate colors
        selected_colors = GenerateColors(num_points, color_name=color_name)

        # set attribution of points
        self.myactor.SetScalars(selected_colors)
Esempio n. 10
0
    def LeftButtonReleaseEvent(self, obj, event):
        print("LEFT BUTTON RELEASED")
        self.OnLeftButtonUp()

        self.frustum = self.area_picker.GetFrustum()

        self.extract_geometry = vtk.vtkExtractGeometry()
        self.extract_geometry.SetImplicitFunction(self.frustum)
        self.extract_geometry.SetInputData(self.pointcloud.cm_poly_data)
        self.extract_geometry.Update()

        self.glyph_filter = vtk.vtkVertexGlyphFilter()
        self.glyph_filter.SetInputConnection(
            self.extract_geometry.GetOutputPort())
        self.glyph_filter.Update()

        self.selected = self.glyph_filter.GetOutput()
        self.p1 = self.selected.GetNumberOfPoints()
        self.p2 = self.selected.GetNumberOfCells()
        print("Number of points = %s" % self.p1)
        print("Number of cells = %s" % self.p2)

        '# % COLOR SELECTED POINTS RED'
        self.selected_mapper.SetInputData(self.selected)
        try:
            self.selected_actor.GetProperty().SetPointSize(10)
            self.selected_actor.GetProperty().SetColor(0, 0, 0)  # (R, G, B)
            self.color_picked()
        except AttributeError:
            pass
Esempio n. 11
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkVertexGlyphFilter(), 'Processing.',
         ('vtkPointSet',), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Esempio n. 12
0
    def AddFilter(self, func):
        if not self.GetContinue():
            # reset history
            self.ResetHistory()

        extract_geometry_filter = vtk.vtkExtractGeometry()
        # set filter function
        extract_geometry_filter.SetImplicitFunction(func)

        # connect the last output
        # some bug here, so I use SetInputData() instead.
        # extract_geometry_filter.SetInputConnection(self.last_filters[-1].GetOutputPort())
        extract_geometry_filter.SetInputConnection(
            self.last_filter.GetOutputPort())

        # save last_filter
        self.last_filters.append(self.last_filter)

        # update the last output
        self.last_filter = vtk.vtkVertexGlyphFilter()
        self.last_filter.SetInputConnection(
            extract_geometry_filter.GetOutputPort())

        # append to the list for saving
        self.extract_geometry_filters.append(extract_geometry_filter)

        # set the last filter to the input of mapper
        self.selected_actor.SetInput(self.last_filter.GetOutputPort())
        self.selected_actor.Update()
Esempio n. 13
0
def create_node_labels(point_id_filter: vtk.vtkIdFilter,
                       grid: vtk.vtkUnstructuredGrid,
                       rend: vtk.vtkRenderer,
                       label_size: float = 10.0):
    """creates the node labels"""
    # filter inner points, so only surface points will be available
    geo = vtk.vtkUnstructuredGridGeometryFilter()
    geo.SetInputData(grid)

    # points
    vertex_filter = vtk.vtkVertexGlyphFilter()
    vertex_filter.SetInputConnection(geo.GetOutputPort())
    vertex_filter.Update()

    points_mapper = vtk.vtkPolyDataMapper()
    points_mapper.SetInputConnection(vertex_filter.GetOutputPort())
    points_mapper.ScalarVisibilityOn()
    points_actor = vtk.vtkActor()
    points_actor.SetMapper(points_mapper)
    points_actor.GetProperty().SetPointSize(label_size)

    # point labels
    label_mapper = vtk.vtkLabeledDataMapper()
    label_mapper.SetInputConnection(point_id_filter.GetOutputPort())
    label_mapper.SetLabelModeToLabelFieldData()
    label_actor = vtk.vtkActor2D()
    label_actor.SetMapper(label_mapper)
    return label_actor
def read_txt_points(filename):
    '''
    private function to read points from a file
    return a point list
    '''
    print 'Reading file: ', filename
    points = []
    vtkpt = vtk.vtkPoints()
    with open(filename, 'r') as ff:
        for line in ff.readlines():
            ss = line.strip().split(',')
            if len(ss) == 3:
                pp = [
                    string.atof(ss[0]),
                    string.atof(ss[1]),
                    string.atof(ss[2])
                ]
                points.append(pp)
                vtkpt.InsertNextPoint(pp)
    poly = vtk.vtkPolyData()
    poly.SetPoints(vtkpt)
    vx = vtk.vtkVertexGlyphFilter()
    vx.SetInputData(poly)
    vx.Update()
    poly = vx.GetOutput()
    return poly
def ReadPointCloud(filename):
    print 'Reading file: ', filename
    #vtkPoints here:
    #method1: assign number of points, insert points by ID, ::SetPoint(ID, double[3])
    #method2: assign no size, insert one after anther,      ::InsertNextPoint(double[3])
    points = vtk.vtkPoints()
    poly   = vtk.vtkPolyData()
    glyphFilter = vtk.vtkVertexGlyphFilter()  # I don't know what is the purpose

    fp = open(filename,"rb+")
    line = fp.readline()
    while line!='':
        line = line.strip()
        if line == '':
            continue
        elif line.find('\t') < 0:
            line = line.split(' ')
        else:
            line = line.split('\t')

        points.InsertNextPoint(float(line[0]),float(line[1]),float(line[2]))
        #read next line and return to loop
        line = fp.readline()

    #add point to poly data
    poly.SetPoints(points)
    glyphFilter.SetInputData(poly)
    glyphFilter.Update()

    #visualize
    PolyVisualize(glyphFilter.GetOutputPort())
Esempio n. 16
0
def create_points_actor(points):
    '''
    points:array
    '''
    vtk_points = vtk.vtkPoints()
    vtk_points.SetNumberOfPoints(len(points))
    for i in range(len(points)):
        vtk_points.SetPoint(i, points[i])
    
    colors = vtk.vtkNamedColors()
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(vtk_points)

    vertexGlyphFilter = vtk.vtkVertexGlyphFilter()
    vertexGlyphFilter.SetInputData(polydata)
    vertexGlyphFilter.Update()

    # Create a mapper and actor
    mapper =  vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(vertexGlyphFilter.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetPointSize(1)
    actor.GetProperty().SetColor(colors.GetColor3d("Yellow"))

    return actor    
Esempio n. 17
0
    def display_cloud(self, actorName, list_points, size, vec3_color):
        # extract inlier points
        vtk_points = vtk.vtkPoints()
        for p in list_points:
            vtk_points.InsertNextPoint(p[0], p[1], p[2])

        temp_cloud = vtk.vtkPolyData()
        temp_cloud.SetPoints(vtk_points)

        # add 0D topology to every point
        glfilter = vtk.vtkVertexGlyphFilter()
        glfilter.SetInput(temp_cloud)
        glfilter.Update()
        cloud = glfilter.GetOutput()

        cloudMapper = vtk.vtkPolyDataMapper()
        cloudMapper.SetInput(cloud)

        actor = vtk.vtkActor()
        actor.SetMapper(cloudMapper)
        actor.GetProperty().SetColor(vec3_color[0], vec3_color[1],
                                     vec3_color[2])
        actor.GetProperty().SetPointSize(size)
        self.ren.AddActor(actor)
        self.name2actor[actorName] = actor
        pass
    def onLeftButtonUp(self, obj, event):
        # Forward events
        self.OnLeftButtonUp()

        frustum = self.GetInteractor().GetPicker().GetFrustum()

        extractGeometry = vtk.vtkExtractGeometry()
        extractGeometry.SetImplicitFunction(frustum)
        extractGeometry.SetInputData(self.Points)
        extractGeometry.Update()

        glyphFilter = vtk.vtkVertexGlyphFilter()
        glyphFilter.SetInputConnection(extractGeometry.GetOutputPort())
        glyphFilter.Update()

        selected = glyphFilter.GetOutput()
        print("Selected " + str(selected.GetNumberOfPoints()) + " points.")
        print("Selected " + str(selected.GetNumberOfCells()) + " cells.")
        self.SelectedMapper.SetInputData(selected)
        self.SelectedMapper.ScalarVisibilityOff()

        ids = selected.GetPointData().GetArray("OriginalIds")

        for i in range(ids.GetNumberOfTuples()):
            print("Id " + str(i) + str(ids.GetValue(i)))

        self.SelectedActor.GetProperty().SetColor(1.0, 0.0, 0.0)  #(R,G,B)
        self.SelectedActor.GetProperty().SetPointSize(3)

        self.GetCurrentRenderer().AddActor(self.SelectedActor)
        self.GetInteractor().GetRenderWindow().Render()
        self.HighlightProp(None)
Esempio n. 19
0
def disk():

    np.random.seed(42)
    n_points = 1
    centers = np.random.rand(n_points, 3)
    colors = 255 * np.random.rand(n_points, 3)

    vtk_points = numpy_to_vtk_points(centers)

    points_polydata = vtk.vtkPolyData()
    points_polydata.SetPoints(vtk_points)

    vertex_filter = vtk.vtkVertexGlyphFilter()
    vertex_filter.SetInputData(points_polydata)
    vertex_filter.Update()

    polydata = vtk.vtkPolyData()
    polydata.ShallowCopy(vertex_filter.GetOutput())

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(polydata)

    points_actor = vtk.vtkActor()
    points_actor.SetMapper(mapper)
    points_actor.GetProperty().SetPointSize(1000)
    points_actor.GetProperty().SetRenderPointsAsSpheres(True)

    return points_actor
def main():
    colors = vtk.vtkNamedColors()
    # Create points on an XY grid with random Z coordinate
    points = vtk.vtkPoints()
    gridSize = 10
    seed = 0
    randomSequence = vtk.vtkMinimalStandardRandomSequence()
    randomSequence.Initialize(seed)
    for x in range(0, gridSize):
        for y in range(0, gridSize):
            d = randomSequence.GetValue()
            randomSequence.Next()
            points.InsertNextPoint(x, y, d * 3)

    # Add the grid points to a polydata object
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)

    glyphFilter = vtk.vtkVertexGlyphFilter()
    glyphFilter.SetInputData(polydata)
    glyphFilter.Update()

    # Create a mapper and actor
    pointsMapper = vtk.vtkPolyDataMapper()
    pointsMapper.SetInputConnection(glyphFilter.GetOutputPort())

    pointsActor = vtk.vtkActor()
    pointsActor.SetMapper(pointsMapper)
    pointsActor.GetProperty().SetPointSize(3)
    pointsActor.GetProperty().SetColor(colors.GetColor3d("Red"))

    # Triangulate the grid points
    delaunay = vtk.vtkDelaunay2D()
    delaunay.SetInputData(polydata)
    delaunay.Update()

    # Create a mapper and actor
    triangulatedMapper = vtk.vtkPolyDataMapper()
    triangulatedMapper.SetInputConnection(delaunay.GetOutputPort())

    triangulatedActor = vtk.vtkActor()
    triangulatedActor.SetMapper(triangulatedMapper)

    # Create a renderer, render window, and interactor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Add the actor to the scene
    renderer.AddActor(pointsActor)
    renderer.AddActor(triangulatedActor)
    renderer.SetBackground(colors.GetColor3d("Green"))  # Background color green

    # Render and interact
    renderWindow.SetWindowName('TriangulateTerrainMap')
    renderWindow.Render()
    renderWindowInteractor.Start()
    def draw_points(self, points):
        points_data = vtk.vtkPolyData()
        vertex_filter = vtk.vtkVertexGlyphFilter()
        points_data.SetPoints(points)
        vertex_filter.SetInputData(points_data)
        vertex_filter.Update()

        return vertex_filter.GetOutput()
Esempio n. 22
0
def numpy2PolyData(data):
    vtkArr = dsa.numpyTovtkDataArray(data)
    pts = v.vtkPoints()
    pts.SetData(vtkArr)
    pd = v.vtkPolyData()
    pd.SetPoints(pts)
    vgf = v.vtkVertexGlyphFilter()
    vgf.SetInputData(pd)
    vgf.Update()
    return vgf.GetOutput()
Esempio n. 23
0
def point2vertexglyph(point):
    points = vtk.vtkPoints()
    points.InsertNextPoint(point[0],point[1],point[2])

    poly = vtk.vtkPolyData()
    poly.SetPoints(points)

    glyph = vtk.vtkVertexGlyphFilter()
    glyph.SetInputData(poly)
    glyph.Update()
    return glyph.GetOutput()
Esempio n. 24
0
def main():
    colors = vtk.vtkNamedColors()

    # Create a set of heights on a grid.
    # This is often called a "terrain map".
    points = vtk.vtkPoints()

    gridSize = 10
    for x in range(gridSize):
        for y in range(gridSize):
            points.InsertNextPoint(x, y, int((x + y) / (y + 1)))

    # Add the grid points to a polydata object
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)

    delaunay = vtk.vtkDelaunay2D()
    delaunay.SetInputData(polydata)

    # Visualize
    meshMapper = vtk.vtkPolyDataMapper()
    meshMapper.SetInputConnection(delaunay.GetOutputPort())

    meshActor = vtk.vtkActor()
    meshActor.SetMapper(meshMapper)
    meshActor.GetProperty().SetColor(colors.GetColor3d('Banana'))
    meshActor.GetProperty().EdgeVisibilityOn()

    glyphFilter = vtk.vtkVertexGlyphFilter()
    glyphFilter.SetInputData(polydata)

    pointMapper = vtk.vtkPolyDataMapper()
    pointMapper.SetInputConnection(glyphFilter.GetOutputPort())

    pointActor = vtk.vtkActor()
    pointActor.GetProperty().SetColor(colors.GetColor3d('Tomato'))
    pointActor.GetProperty().SetPointSize(5)
    pointActor.SetMapper(pointMapper)

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(meshActor)
    renderer.AddActor(pointActor)
    renderer.SetBackground(colors.GetColor3d('Mint'))

    renderWindowInteractor.Initialize()
    renderWindow.SetWindowName('Delaunay2D')
    renderWindow.Render()
    renderWindowInteractor.Start()
Esempio n. 25
0
def add_glyph_points(renderer, points, color=[1.0, 1.0, 1.0], size=2):
    geom = vtk.vtkPolyData()
    geom.SetPoints(points)
    glyphFilter = vtk.vtkVertexGlyphFilter()
    glyphFilter.SetInputData(geom)
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(glyphFilter.GetOutputPort())
    actor = vtk.vtkActor()
    actor.GetProperty().SetColor(color)
    actor.GetProperty().SetPointSize(size)
    actor.SetMapper(mapper)
    renderer.AddActor(actor)
def p2actor(pp):
    pPoly = vtk.vtkPolyData()
    pPoly.SetPoints(pp)
    vx = vtk.vtkVertexGlyphFilter()
    vx.SetInputData(pPoly)
    vx.Update()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(vx.GetOutput())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    #actor.GetProperty().SetPointSize(10)
    return actor
Esempio n. 27
0
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        self.ren = vtk.vtkRenderer()
        self.ren.SetBackground(0.1, 0.2, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        points = vtk.vtkPoints()
        points.InsertNextPoint(0.0, 0.0, 0.0)
        points.InsertNextPoint(1.0, 0.0, 0.0)
        points.InsertNextPoint(0.0, 1.0, 0.0)

        pointsPolydata = vtk.vtkPolyData()
        pointsPolydata.SetPoints(points)

        vertexFilter = vtk.vtkVertexGlyphFilter()
        vertexFilter.SetInputConnection(pointsPolydata.GetProducerPort())
        vertexFilter.Update()

        polydata = vtk.vtkPolyData()
        polydata.ShallowCopy(vertexFilter.GetOutput())

        # Setup colors
        colors = vtk.vtkUnsignedCharArray()
        colors.SetNumberOfComponents(3)
        colors.SetName("Colors")
        colors.InsertNextTupleValue((255, 0, 0))
        colors.InsertNextTupleValue((0, 255, 0))
        colors.InsertNextTupleValue((0, 0, 255))

        polydata.GetPointData().SetScalars(colors)
 
        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(polydata.GetProducerPort())
 
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetPointSize(5)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Esempio n. 28
0
 def setPoints(self, points_xyz, points_rgb):
     points_polyd = vtk.vtkPolyData()
     vtk_points = numpy_support.numpy_to_vtk(points_xyz)
     self.vtkPoints.SetData(vtk_points)
     vtk_pntcols = numpy_support.numpy_to_vtk(
         (points_rgb * 255).astype(np.uint8))
     self.vtkColors = vtk_pntcols
     points_polyd.SetPoints(self.vtkPoints)
     vertexfilter = vtk.vtkVertexGlyphFilter()
     vertexfilter.SetInputData(points_polyd)
     vertexfilter.Update()
     self.vtkPolyData.ShallowCopy(vertexfilter.GetOutput())
     self.vtkPolyData.GetPointData().SetScalars(self.vtkColors)
     self.vtkPolyData.Modified()
    def visualize_crop(self, LAA_surface):
        mapper2 = vtk.vtkPolyDataMapper()
        mapper2.SetInputData(self.pred_surface)
        actor2 = vtk.vtkActor()
        actor2.SetMapper(mapper2)
        actor2.GetProperty().SetColor(0.5, 0.5, 0.5)

        # LAA only
        polyDataMapper = vtk.vtkPolyDataMapper()
        polyDataMapper.SetInputData(LAA_surface)
        actor = vtk.vtkActor()
        actor.SetMapper(polyDataMapper)
        actor.GetProperty().SetColor(1, 1, 1)

        # Add points as glyphs
        ostium_ids = np.load(self.path_ostiumIDs)
        vtk_points = vtk.vtkPoints()
        for ostium_id in ostium_ids:
            vtk_points.InsertNextPoint(
                self.surface_in_correspondance.GetPoint(ostium_id))
        pd_points = vtk.vtkPolyData()
        pd_points.SetPoints(vtk_points)
        vertexGlyphFilter = vtk.vtkVertexGlyphFilter()
        vertexGlyphFilter.AddInputData(pd_points)
        vertexGlyphFilter.Update()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(vertexGlyphFilter.GetOutputPort())
        actor1 = vtk.vtkActor()
        actor1.SetMapper(mapper)
        actor1.GetProperty().SetPointSize(3)
        actor1.GetProperty().SetColor(1, 0, 0)

        # RENDER
        renderWindow = vtk.vtkRenderWindow()
        renderWindow.SetSize(800, 600)
        renderWindow.SetWindowName("VTK")

        renderWindowInteractor = vtk.vtkRenderWindowInteractor()
        renderWindowInteractor.SetRenderWindow(renderWindow)
        renderer = vtk.vtkRenderer()
        renderer.AddActor(actor2)  #Full Surface
        renderer.AddActor(actor)  #Clipped surface
        renderer.AddActor(actor1)  #Points
        #renderer.AddActor(planeActor) #PLane
        renderer.SetBackground(1, 1, 1)

        renderWindow.AddRenderer(renderer)
        renderWindow.Render()
        renderWindowInteractor.Start()
Esempio n. 30
0
def try_point_surface():
    '''
    Workflow proved valid:

    src_surface: source surface to be moved
    src_points:  points selected from src_surface
    tgt_surface: fixed surface, src_surface will transform to this
    moved_surface: src_surface applied transform

    Workflow:
        register src_points to tgt_surface, get a matrix Mat
        apply Mat to src_surface, get moved_surface

    Result:
        moved_surface apply perfectly to tgt_surface
    '''
    pt_list = read_txt('data/point.txt')
    points = vtk.vtkPoints()
    for pt in pt_list:
        points.InsertNextPoint(pt)

    # points as source
    point_poly = vtk.vtkPolyData()
    point_poly.SetPoints(points)
    vertex = vtk.vtkVertexGlyphFilter()
    vertex.SetInputData(point_poly)
    vertex.Update()
    point_poly = vertex.GetOutput()

    # surface patch as target
    reg = icp_register()
    surface = reg._read_poly('data/tcut.stl')
    src_surface = reg._read_poly('data/cut.stl')

    mat = reg.register(point_poly, surface, 5000)

    transform = vtk.vtkTransform()
    transform.SetMatrix(mat)
    transFilter = vtk.vtkTransformFilter()
    transFilter.SetTransform(transform)
    #transFilter.SetInputData(point_poly)
    transFilter.SetInputData(src_surface)
    transFilter.Update()
    pp = transFilter.GetOutput()

    reg._write_poly(src_surface, 'data/src_tr.stl')
    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetInputData(pp)
    writer.SetFileName('data/transed_P.vtp')
Esempio n. 31
0
 def clip_area(poly, bounds):
     new_pts = vtk.vtkPoints()
     for id in range(poly.GetNumberOfPoints()):
         pt = poly.GetPoint(id)
         if ((pt[0] > bounds[0] - 10) & (pt[0] < bounds[1] + 10) &
             (pt[1] > bounds[2] - 10) & (pt[1] < bounds[3] + 10) &
             (pt[2] > bounds[4] - 10) & (pt[2] < bounds[5] + 10)):
             new_pts.InsertNextPoint(pt)
     poly = vtk.vtkPolyData()
     poly.SetPoints(new_pts)
     vx = vtk.vtkVertexGlyphFilter()
     vx.SetInputData(poly)
     vx.Update()
     new_pts = vx.GetOutput()
     return new_pts
    def __init__(self):

        # References to the converted numpy arrays to avoid seg faults
        # self.np_to_vtk_points = None
        # self.np_to_vtk_cells = None

        # VTK Data
        self.vtk_poly_data = vtk.vtkPolyData()

        self.vtk_points = vtk.vtkPoints()
        # self.vtk_points.SetNumberOfPoints(500000)
        # self.vtk_cells = vtk.vtkCellArray()

        # Colours for each point in the point cloud
        self.vtk_colours = None
        self.vtk_points_temp = vtk.vtkPoints()
        # self.something = None
        self.vtk_id_list = vtk.vtkIdList()

        # self.ranges = None
        # self.vtk_id_list = vtk.vtkIdList()

        # self.vtk_colours = vtk.vtkUnsignedCharArray()
        # self.vtk_colours.SetNumberOfComponents(3)
        # self.vtk_colours.SetName("Colours")

        self.points = np.zeros((0, 3))
        self.colours = []

        self.point_idx = 0

        # Poly Data
        self.vtk_poly_data.SetPoints(self.vtk_points)
        # self.vtk_poly_data.SetVerts(self.vtk_cells)

        self.glyphFilter = vtk.vtkVertexGlyphFilter()
        self.glyphFilter.AddInputData(self.vtk_poly_data)
        self.glyphFilter.Update()

        # Poly Data Mapper
        self.vtk_poly_data_mapper = vtk.vtkPolyDataMapper()
        # self.vtk_poly_data_mapper.SetInputData(self.vtk_poly_data)
        self.vtk_poly_data_mapper.SetInputConnection(
            self.glyphFilter.GetOutputPort())

        # Actor
        self.vtk_actor = vtk.vtkActor()
        self.vtk_actor.SetMapper(self.vtk_poly_data_mapper)
Esempio n. 33
0
def main():
    colors = vtk.vtkNamedColors()
    points = vtk.vtkPoints()
    points.InsertNextPoint(10, 10, 0)
    points.InsertNextPoint(100, 100, 0)
    points.InsertNextPoint(200, 200, 0)

    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)

    glyphFilter = vtk.vtkVertexGlyphFilter()
    glyphFilter.SetInputData(polydata)
    glyphFilter.Update()

    mapper = vtk.vtkPolyDataMapper2D()
    mapper.SetInputConnection(glyphFilter.GetOutputPort())
    mapper.Update()

    actor = vtk.vtkActor2D()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d('Gold'))
    actor.GetProperty().SetPointSize(8)

    # Create a renderer, render window, and interactor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Add the actor to the scene
    renderer.AddActor(actor)
    renderWindow.SetSize(300, 300)
    renderer.SetBackground(colors.GetColor3d('DarkSlateGray'))

    renderWindow.SetWindowName('Actor2D')

    # Render and interact
    renderWindow.Render()
    # w2if = vtk.vtkWindowToImageFilter()
    # w2if.SetInput(renderWindow)
    # w2if.Update()
    #
    # writer = vtk.vtkPNGWriter()
    # writer.SetFileName('TestActor2D.png')
    # writer.SetInputConnection(w2if.GetOutputPort())
    # writer.Write()
    renderWindowInteractor.Start()
    def FiducialsToPolyData(self, fiducials, polyData):
        #create polydata from fiducial list
        points = vtk.vtkPoints()
        n = fiducials.GetNumberOfFiducials()
        for fiducialIndex in range( 0, n ):
            p = [0, 0, 0]
            fiducials.GetNthFiducialPosition(fiducialIndex, p)
            points.InsertNextPoint(p)
        tempPolyData = vtk.vtkPolyData()
        tempPolyData.SetPoints(points)

        vertex = vtk.vtkVertexGlyphFilter()
        vertex.SetInputData(tempPolyData)
        vertex.Update()

        polyData.ShallowCopy(vertex.GetOutput())
Esempio n. 35
0
 def VertexGlyphFilter(self, currentElement):
     gFilter = vtk.vtkVertexGlyphFilter()
     AlgorithmElement = ''
     for childElement in currentElement.getchildren():
         if childElement.tag in vtkTypes['Algorithm']:
             self.logger.debug('VertexGlyphFilter trying to add: %s' % (childElement.tag))
             AlgorithmElement = childElement
     if AlgorithmElement != '':
         dataset = self.namesToFunctions[AlgorithmElement.tag](AlgorithmElement)
         try:
             gFilter.SetInputConnection(dataset.GetOutputPort())
         except Exception as err:
             self.logger.error("  .. <VertexGlyphFilter> failed to SetInputConnection")
             self.logger.error(err)
     else:
         self.logger.error('  .. <VertexGlyphFilter> needs an Algorithm-type childElement')
     return gFilter
Esempio n. 36
0
def create_actor_pts(pts, color, **kwargs):
    """ Creates a VTK actor for rendering scatter plots.

    :param pts: points
    :type pts: vtkFloatArray
    :param color: actor color
    :type color: list
    :return: a VTK actor
    :rtype: vtkActor
    """
    # Keyword arguments
    array_name = kwargs.get('name', "")
    array_index = kwargs.get('index', 0)
    point_size = kwargs.get('size', 5)
    point_sphere = kwargs.get('point_as_sphere', True)

    # Create points
    points = vtk.vtkPoints()
    points.SetData(pts)

    # Create a PolyData object and add points
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)

    # Run vertex glyph filter on the points array
    vertex_filter = vtk.vtkVertexGlyphFilter()
    vertex_filter.SetInputData(polydata)

    # Map ploy data to the graphics primitives
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(vertex_filter.GetOutputPort())
    mapper.SetArrayName(array_name)
    mapper.SetArrayId(array_index)

    # Create an actor and set its properties
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(*color)
    actor.GetProperty().SetPointSize(point_size)
    actor.GetProperty().SetRenderPointsAsSpheres(point_sphere)

    # Return the actor
    return actor
    def OnLeftButtonUp(self):
        # Forward events
        vtkInteractorStyleRubberBandPick.OnLeftButtonUp()

        frustum = vtk.vtkAreaPicker(self.GetInteractor().GetPicker()).GetFrustum()

        extractGeometry = vtk.vtkExtractGeometry.New()
        extractGeometry.SetImplicitFunction(frustum)

        if VTK_MAJOR_VERSION <= 5:
            extractGeometry.SetInput(this.Points)
        else:
            extractGeometry.SetInputData(this.Points)
        extractGeometry.Update()

        glyphFilter = vtk.vtkVertexGlyphFilter()
        glyphFilter.SetInputConnection(extractGeometry.GetOutputPort())
        glyphFilter.Update()

        selected = glyphFilter.GetOutput()
        print("Selected %s points" % selected.GetNumberOfPoints())
        print("Selected %s cells" % selected.GetNumberOfCells())
        if vtk.VTK_MAJOR_VERSION <= 5:
            self.SelectedMapper.SetInput(selected)
        else:
            self.SelectedMapper.SetInputData(selected)

        self.SelectedMapper.ScalarVisibilityOff()

        ids = vtkIdTypeArray.SafeDownCast(selected.GetPointData().GetArray("OriginalIds"))
        for i in range(ids.GetNumberOfTuples()):
            print("Id %s : %s" % (i, ids.GetValue(i)))

        self.SelectedActor.GetProperty().SetColor(1.0, 0.0, 0.0) #(R,G,B)
        self.SelectedActor.GetProperty().SetPointSize(3)

        self.CurrentRenderer.AddActor(SelectedActor)
        self.GetInteractor().GetRenderWindow().Render()
Esempio n. 38
0
def buildATPMesh():
    # Report our CWD just for testing purposes.
    print "CWD:", os.getcwd()

    # Read in the mesh.
    print 'Reading', meshFile
    meshReader = vtk.vtkXMLPolyDataReader()
    meshReader.SetFileName(meshFile)
    meshReader.Update()

    ecMesh = meshReader.GetOutput()

    # Read in the centreline.
    print 'Reading', centrelineFile
    centrelineReader = vtk.vtkPolyDataReader()
    centrelineReader.SetFileName(centrelineFile)
    centrelineReader.Update()

    centreline = centrelineReader.GetOutput()
    origin = centreline.GetPoint(0)
    print 'origin:', origin

    # Put the ecMesh through centroids filter.
    centroidFilter = vtk.vtkCellCenters()
    centroidFilter.SetInputData(ecMesh)
    centroidFilter.Update()

    centroids = centroidFilter.GetOutput()

    # Iterate over each centroid and find the closest segment
    centroidPoints = centroids.GetPoints()

    # Only for DEBUG output.
    distArray = vtk.vtkDoubleArray()
    distArray.SetName("Dist")

    # For each point calculate the distance from origin.
    totalPoints = centroidPoints.GetNumberOfPoints()
    for ptId in range(totalPoints):        
        distance = vtk.vtkMath.Distance2BetweenPoints(origin, centroidPoints.GetPoint(ptId))
        distArray.InsertNextValue(math.sqrt(distance))

    # Get the range of the distance values.
    inMin, inMax = distArray.GetRange()
    
    atpArray = vtk.vtkFloatArray()
    atpArray.SetName('initialATP')
    
    # Normalise distance values.
    for i in range(distArray.GetNumberOfTuples()):
        dist = distArray.GetTuple(i)[0]
        distRescaled = rescale(dist, inMin, inMax)
        atpVal = sigmoidATP(distRescaled)
        atpArray.InsertNextValue(atpVal)
    
    # Prepare debug ATP mesh.
    debugAtpDataset = ecMesh
    debugAtpDataset.GetCellData().AddArray(distArray)
    debugAtpDataset.GetCellData().AddArray(atpArray)

    # Save the debug ATP mesh.
    debugAtpMapWriter = vtk.vtkXMLPolyDataWriter()
    debugAtpMapWriter.SetFileName(debugAtpFile)
    debugAtpMapWriter.SetInputData(debugAtpDataset)
    debugAtpMapWriter.Update()

    # Prepare the ATP mesh by converting all points to vercices.
    pointsToVerticesFilter = vtk.vtkVertexGlyphFilter()
    pointsToVerticesFilter.SetInputData(centroids)
    pointsToVerticesFilter.Update()
    atpDataset = pointsToVerticesFilter.GetOutput()
    atpDataset.GetCellData().AddArray(atpArray)

    # Assert the number of cells is equal to the number of items in the cell arrays.
    assert atpArray.GetNumberOfTuples() == debugAtpDataset.GetNumberOfCells(), "Number of cells (%d) and cell data values (%d) mismatch." % (atpArray.GetNumberOfTuples(), debugAtpDataset.GetNumberOfCells())

    atpMapWriter = vtk.vtkXMLPolyDataWriter()
    atpMapWriter.SetFileName(atpFile)
    atpMapWriter.SetInputData(atpDataset)
    atpMapWriter.Update()
    
    # Provide a quick visualisation of the ATP profile for validation.
    pointsX = numpy.arange(outMin, outMax, 0.001)
    pointsY = []
    for pt in pointsX:
        pointsY.append(sigmoidATP(pt))
    
    pyplot.plot(pointsX, pointsY, 'b')
    pyplot.show()
Esempio n. 39
0
edgeActor.GetProperty().SetLineWidth(theme.GetLineWidth())
edgeActor.SetPosition(0, 0, -0.003);
edgeActor.SetVisibility(0)

lut = vtk.vtkLookupTable()
lutNum = 256
lut.SetNumberOfTableValues(lutNum)
ctf = vtk.vtkColorTransferFunction()
ctf.SetColorSpaceToDiverging()
ctf.AddRGBPoint(0.0, 0, 0, 1.0)
ctf.AddRGBPoint(1.0, 1.0, 0, 0)
for ii,ss in enumerate([float(xx)/float(lutNum) for xx in range(lutNum)]):
	cc = ctf.GetColor(ss)
	lut.SetTableValue(ii,cc[0],cc[1],cc[2],1.0)

vertGlyph = vtk.vtkVertexGlyphFilter()
vertGlyph.SetInputConnection(subgraph.GetOutputPort())
vertMapper = vtk.vtkPolyDataMapper()
vertMapper.SetInputConnection(vertGlyph.GetOutputPort())
vertMapper.SetImmediateModeRendering(True)
vertMapper.SetScalarModeToUsePointFieldData()
vertMapper.SetLookupTable(lut)
vertMapper.SelectColorArray('ExtBasis')
vertMapper.Update()
vertRange = vertMapper.GetInput().GetPointData().GetArray(vertMapper.GetArrayName()).GetRange()
vertMapper.SetScalarRange(-1.0*vertRange[1], vertRange[1])
vertActor = vtk.vtkActor()
vertActor.SetMapper(vertMapper)
# vertActor.GetProperty().SetColor(theme.GetPointColor())
# vertActor.GetProperty().SetOpacity(theme.GetPointOpacity())
vertActor.GetProperty().SetPointSize(theme.GetPointSize())
Esempio n. 40
0
def scatterplot_3d(data, color=None, point_size=None, cmap="jet", point_shape=None):
    if len(data.shape) != 2 or data.shape[1] != 3:
        raise ValueError("data must have shape (n, 3) where n is the number of points.")
    if point_shape is None:
        if len(data) <= 1000:
            point_shape = "spheres"
        else:
            point_shape = "squares"
    data = _numpy.float32(data)
    data_vtk = array_to_float_array(data)
    point_data = _vtk.vtkPoints()
    point_data.SetData(data_vtk)
    points_poly_data = _vtk.vtkPolyData()
    points_poly_data.SetPoints(point_data)
    
    if not color is None:
        lut = get_lookup_table(color.min(), color.max())
        color_scalars = array_to_vtk(_numpy.float32(color.copy()))
        color_scalars.SetLookupTable(lut)
        points_poly_data.GetPointData().SetScalars(color_scalars)
        
    if point_shape == "spheres":
        if point_size is None:
            point_size = _numpy.array(data).std() / len(data)**(1./3.) / 3.
        glyph_filter = _vtk.vtkGlyph3D()
        glyph_filter.SetInputData(points_poly_data)
        sphere_source = _vtk.vtkSphereSource()
        sphere_source.SetRadius(point_size)
        glyph_filter.SetSourceConnection(sphere_source.GetOutputPort())
        glyph_filter.SetScaleModeToDataScalingOff()
        if not color is None:
            glyph_filter.SetColorModeToColorByScalar()
        else:
            glyph_filter.SetColorMode(0)
        glyph_filter.Update()
    elif point_shape == "squares":
        if point_size is None:
            point_size = 3
        glyph_filter = _vtk.vtkVertexGlyphFilter()
        glyph_filter.SetInputData(points_poly_data)
        glyph_filter.Update()
    else:
        raise ValueError("{0} is not a valid entry for points".format(points))

    poly_data = _vtk.vtkPolyData()
    poly_data.ShallowCopy(glyph_filter.GetOutput())

    renderer, render_window, interactor = setup_window()

    mapper = _vtk.vtkPolyDataMapper()
    mapper.SetInputData(poly_data)
    if not color is None:
        mapper.SetLookupTable(lut)
        mapper.SetUseLookupTableScalarRange(True)

    points_actor = _vtk.vtkActor()
    points_actor.SetMapper(mapper)
    points_actor.GetProperty().SetPointSize(point_size)
    points_actor.GetProperty().SetColor(0., 0., 0.)

    axes_actor = _vtk.vtkCubeAxesActor()
    axes_actor.SetBounds(points_actor.GetBounds())
    axes_actor.SetCamera(renderer.GetActiveCamera())
    axes_actor.SetFlyModeToStaticTriad()
    #axes_actor.GetProperty().SetColor(0., 0., 0.)
    axes_actor.GetXAxesLinesProperty().SetColor(0., 0., 0.)
    axes_actor.GetYAxesLinesProperty().SetColor(0., 0., 0.)
    axes_actor.GetZAxesLinesProperty().SetColor(0., 0., 0.)
    for i in range(3):
        axes_actor.GetLabelTextProperty(i).SetColor(0., 0., 0.)
        axes_actor.GetTitleTextProperty(i).SetColor(0., 0., 0.)

    renderer.AddActor(points_actor)
    renderer.AddActor(axes_actor)

    render_window.Render()
    interactor.Start()
Esempio n. 41
0
    def loadGraph():
        
        # ----------
        # Load and construct whole graph and multi-resolution data from Matlab structure
        dataDir = '/Users/emonson/Programming/Matlab/EMonson/Fodava/DocumentAnalysis/Analysis/'
        filename = dataDir + 'X20_042709b.mat'
        # filename = '/Users/emonson/Programming/Python/VTK/X20_040609b.mat'
        X = scipy.io.loadmat(filename)
        # Get graph structure G out of matlab variables
        G = X['G']
        
        # ----------
        # Set multi-resolution level bounds in GUI sliders
        levelMax = G.Tree.shape[0]-1
        ui_window.hSlider_level.setMinimum(1)
        ui_window.hSlider_level.setMaximum(levelMax)
        ui_window.spinBox_level.setMinimum(1)
        ui_window.spinBox_level.setMaximum(levelMax)
        
        # Start setting up basis function for display as subgraph
        ExtBasis = GTree[level,0]['ExtBasis'][0][0][0]
        basisMax = ExtBasis.shape[1]-1    # zero-based indices
        
        # Set particular level basis function bounds in GUI sliders
        ui_window.hSlider_basisIndex.setMinimum(0)
        ui_window.hSlider_basisIndex.setMaximum(basisMax)
        ui_window.spinBox_basisIndex.setMinimum(0)
        ui_window.spinBox_basisIndex.setMaximum(basisMax)
        
        # Build table which will become graph
        table = vtk.vtkTable()
        col0 = vtk.vtkIntArray()
        col0.SetName('index1')
        col1 = vtk.vtkIntArray()
        col1.SetName('index2')
        val = vtk.vtkDoubleArray()
        val.SetName('weight')
        
        Tmat = G.T
        # Tmat = G.W
        
        for ii in range(Tmat.nzmax):
            col0.InsertNextValue(Tmat.rowcol(ii)[0])
            col1.InsertNextValue(Tmat.rowcol(ii)[1])
            val.InsertNextValue(abs(Tmat.getdata(ii)))
        
        table.AddColumn(col0)
        table.AddColumn(col1)
        table.AddColumn(val)
        
        # Vertex links need to be done with index2 first or indexing won't be right...
        # TODO: Make this foolproof so that graph always ends up with correct ordering of indices...
        tgraph = vtk.vtkTableToGraph()
        tgraph.SetInput(table)
        tgraph.AddLinkVertex('index2', 'stuff', False)
        tgraph.AddLinkVertex('index1', 'stuff', False)
        tgraph.AddLinkEdge('index2', 'index1')
        
        rawGraph = tgraph.GetOutput()
        rawGraph.Update()
        # print graph
        
        # Load and assign whole graph pre-layout coordinates
        ptsFile = os.path.splitext(filename)[0] + '_pts.vtp'
        if os.path.exists(ptsFile):
            polyreader = vtk.vtkXMLPolyDataReader()
            polyreader.SetFileName(ptsFile)
            polyreader.Update()
            pts = polyreader.GetOutput().GetPoints()
            rawGraph.SetPoints(pts)
            # print pts
            
        strategy = vtk.vtkPassThroughLayoutStrategy()
        layout = vtk.vtkGraphLayout()
        layout.SetInput(rawGraph)
        layout.SetLayoutStrategy(strategy)
        
        edgeLayout = vtk.vtkEdgeLayout()
        edgeStrategy = vtk.vtkArcParallelEdgeStrategy()
        edgeStrategy.SetNumberOfSubdivisions(50)
        edgeLayout.SetInputConnection(layout.GetOutputPort())
        edgeLayout.SetLayoutStrategy(edgeStrategy)
        
        graph = edgeLayout.GetOutput()
        graph.Update()
        
        # --------
        # Add ExtBasis to graph data & Select particular basis function
        
        # print 'ExtBasis shape: ' + str(ExtBasis[:,basisNum].data.shape) + ' (level,basis) (' + str(level) + ',' + str(basisNum) + ')'
        
        # Indexing of ExtBasis is backwards from graph, so need to reverse with [::-1]
        # and array not "contiguous" if don't do .copy()
        Esub = ExtBasis[:,basisNum].data[::-1].copy()
        EsubSq = Esub**2
        # Esub = N.random.random(ExtBasis[:,basisNum].data.shape[0])
        # SubIdxs = (Esub > 0.001).nonzero()
        # SubIdxs = (Esub**2 > 0.8).nonzero()
        
        # Set ExtBasis vertex data from numpy array
        basisFunc = VN.numpy_to_vtk(Esub)
        basisFunc.SetName('ExtBasis')
        basisFuncSq = VN.numpy_to_vtk(EsubSq)
        basisFuncSq.SetName('ExtBasisSq')
        
        vertexData = graph.GetVertexData()
        vertexData.AddArray(basisFunc)
        vertexData.AddArray(basisFuncSq)
        
        selection = vtk.vtkSelectionSource()
        selection.SetContentType(7) # vtkSelection::THRESHOLDS
        # selection.SetContentType(2) # vtkSelection::PEDIGREE_IDS
        selection.SetFieldType(3) # vtkSelection::VERTEX
        selection.SetArrayName("ExtBasisSq")
        selection.AddThreshold(basisCutoff, 10)
        # TODO: There was something wrong with the indexing in the PEDIGREE_IDS selection...
        # for ii in SubIdxs[0]:
        #     selection.AddID(0,ii)
        minmax = "(%3.2e, %3.2e)" % (EsubSq.min(), EsubSq.max())
        ui_window.label_basisCutoff_minmax.setText(minmax)
        selection.Update()
        
        # ----------
        # Back to pipeline
        degree = vtk.vtkVertexDegree()
        degree.SetInput(graph)
        
        subgraph = vtk.vtkExtractSelectedGraph()
        subgraph.SetRemoveIsolatedVertices(False)
        subgraph.SetInputConnection(degree.GetOutputPort())
        subgraph.SetSelectionConnection(selection.GetOutputPort())
        
        # +++++++++++++
        graphToPoly = vtk.vtkGraphToPolyData()
        graphToPoly.SetInputConnection(subgraph.GetOutputPort())
        edgeMapper = vtk.vtkPolyDataMapper()
        edgeMapper.SetInputConnection(graphToPoly.GetOutputPort())
        edgeMapper.SetScalarModeToUseCellData()
        edgeMapper.SetScalarVisibility(False)
        edgeMapper.SetImmediateModeRendering(True)
        edgeActor = vtk.vtkActor()
        edgeActor.SetMapper(edgeMapper)
        edgeActor.SetPosition(0, 0, -0.003);
        
        lut = vtk.vtkLookupTable()
        lutNum = 256
        lut.SetNumberOfTableValues(lutNum)
        ctf = vtk.vtkColorTransferFunction()
        ctf.SetColorSpaceToDiverging()
        ctf.AddRGBPoint(0.0, 0, 0, 1.0)
        ctf.AddRGBPoint(1.0, 1.0, 0, 0)
        for ii,ss in enumerate([float(xx)/float(lutNum) for xx in range(lutNum)]):
            cc = ctf.GetColor(ss)
            lut.SetTableValue(ii,cc[0],cc[1],cc[2],1.0)
        
        vertGlyph = vtk.vtkVertexGlyphFilter()
        vertGlyph.SetInputConnection(subgraph.GetOutputPort())
        vertMapper = vtk.vtkPolyDataMapper()
        vertMapper.SetInputConnection(vertGlyph.GetOutputPort())
        vertMapper.SetImmediateModeRendering(True)
        vertMapper.SetScalarModeToUsePointFieldData()
        vertMapper.SetLookupTable(lut)
        vertMapper.SelectColorArray('ExtBasis')
        vertMapper.Update()
        vertRange = vertMapper.GetInput().GetPointData().GetArray(vertMapper.GetArrayName()).GetRange()
        vertMapper.SetScalarRange(-1.0*vertRange[1], vertRange[1])
        vertActor = vtk.vtkActor()
        vertActor.SetMapper(vertMapper)
        
        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetScalarVisibility(False)
        outlineMapper.SetImmediateModeRendering(True)
        outlineMapper.SetInputConnection(vertGlyph.GetOutputPort())
        outlineActor = vtk.vtkActor()
        outlineActor.PickableOff()
        outlineActor.SetPosition(0, 0, -0.001)
        outlineActor.GetProperty().SetRepresentationToWireframe()
        outlineActor.SetMapper(outlineMapper)
        
        # Create an Actor Collection for applying visibility to group
        basisActorCollection = vtk.vtkActorCollection()
        basisActorCollection.AddItem(vertActor)
        # basisActorCollection.AddItem(edgeActor)
        basisActorCollection.AddItem(outlineActor)
        
        
        # Apply a theme to the views
        theme = vtk.vtkViewTheme.CreateMellowTheme()
        theme.SetLineWidth(3)
        theme.SetPointSize(5)
        theme.SetSelectedCellColor(1,1,1)
        theme.SetSelectedPointColor(1,1,1)
        theme.SetOutlineColor(0.8, 0.8, 0.8)
        # theme.SetPointColor(0.9, 0.7, 0.3)
        theme.SetCellColor(0.9, 0.7, 0.3)
        # theme.SetPointOpacity(0.5)
        # theme.SetPointHueRange(0.0, 0.15)
        # theme.SetPointSaturationRange(0.6, 0.8)
        # theme.SetPointValueRange(0.4,0.8)
        # theme.SetPointAlphaRange(0.2,0.8)
        # theme.SetPointAlphaRange(1.0,1.0)

        
        # Apply theme
        # vertActor.GetProperty().SetColor(theme.GetPointColor())
        # vertActor.GetProperty().SetOpacity(theme.GetPointOpacity())
        vertActor.GetProperty().SetPointSize(theme.GetPointSize())
        outlineActor.GetProperty().SetPointSize(vertActor.GetProperty().GetPointSize()+2)
        outlineActor.GetProperty().SetColor(theme.GetOutlineColor())
        outlineActor.GetProperty().SetOpacity(theme.GetPointOpacity())
        edgeActor.GetProperty().SetColor(theme.GetCellColor())
        edgeActor.GetProperty().SetOpacity(theme.GetCellOpacity())
        edgeActor.GetProperty().SetLineWidth(theme.GetLineWidth())
        
        
        # ----------
        # Background graph skeleton
        graphMapper = vtk.vtkGraphMapper()
        graphMapper.SetInputConnection(0, degree.GetOutputPort(0))
        
        # Apply a theme to the background graph
        gtheme = vtk.vtkViewTheme()
        gtheme.SetLineWidth(1)
        gtheme.SetPointSize(0)
        gtheme.SetCellColor(0.8, 0.8, 0.8)
        gtheme.SetCellOpacity(0.2)
        gtheme.SetOutlineColor(0.8, 0.8, 0.8)
        gtheme.SetPointColor(0.8, 0.8, 0.8)
        gtheme.SetPointOpacity(0.0)
        graphMapper.ApplyViewTheme(gtheme)

        graphActor = vtk.vtkActor()
        graphActor.SetMapper(graphMapper)
        graphActor.SetPosition(0,0,-0.005)
        
        # ----------
        # Background vertices
        graphPoly = vtk.vtkGraphToPolyData()
        graphPoly.SetInputConnection(0, tgraph.GetOutputPort(0))
        
        vertGlyph = vtk.vtkGlyph3D()
        vertGlyph.SetInputConnection(0, graphPoly.GetOutputPort())
        glyphSource = vtk.vtkGlyphSource2D()
        glyphSource.SetGlyphTypeToVertex()
        # glyphSource.SetGlyphTypeToCircle()
        # glyphSource.SetScale(0.025)
        vertGlyph.SetInputConnection(1, glyphSource.GetOutputPort())
        
        vertexMapper = vtk.vtkPolyDataMapper()
        vertexMapper.SetInputConnection(vertGlyph.GetOutputPort())
        vertexActor = vtk.vtkActor()
        vertexActor.SetMapper(vertexMapper)
        vertexActor.GetProperty().SetPointSize(4)
        vertexActor.GetProperty().SetOpacity(0.5)
        vertexActor.GetProperty().SetColor(0.6, 0.6, 0.6)
        vertexActor.SetPosition(0, 0, -0.004)
        
        # ----------
        # Vertex index labels
        labelMapper = vtk.vtkDynamic2DLabelMapper()
        labelMapper.SetInputConnection(0, graphPoly.GetOutputPort(0))
        labelMapper.SetLabelModeToLabelFieldData()
        labelMapper.SetFieldDataName("label")
        labelMapper.SetLabelFormat("%s")
        labelMapper.GetLabelTextProperty().SetColor(0.0, 0.0, 0.0)
        
        labelActor = vtk.vtkActor2D()
        labelActor.SetMapper(labelMapper)
        
        # ----------
        # MultiScale Graph
        msGraph = buildSubGraph(level) 
        
        msMapper = vtk.vtkGraphMapper()
        msMapper.SetInput(msGraph)
        msMapper.SetColorEdges(True)
        msMapper.SetEdgeColorArrayName('weight')
        
        # Apply a theme to the background graph
        mtheme = vtk.vtkViewTheme()
        mtheme.SetLineWidth(3)
        mtheme.SetPointSize(11)
        # mtheme.SetCellColor(0.5, 0.5, 0.7)
        # mtheme.SetCellOpacity(0.5)
        mtheme.SetOutlineColor(0.8, 0.8, 0.8)
        mtheme.SetPointColor(0.3, 0.3, 0.6)
        mtheme.SetPointOpacity(1.0)
        mtheme.SetCellHueRange(0.67, 0.67)
        mtheme.SetCellSaturationRange(0.6, 0.1)
        mtheme.SetCellValueRange(0.5,1.0)
        mtheme.SetCellAlphaRange(0.2,0.8)
        msMapper.ApplyViewTheme(mtheme)

        msActor = vtk.vtkActor()
        msActor.SetMapper(msMapper)
        msActor.SetPosition(0,0,-0.002)
        
        # ----------
        # Set up window and add actors        
        view.SetLayoutStrategyToPassThrough()
        # view.ApplyViewTheme(theme)                
        # view.SetupRenderWindow(win)
        view.GetRenderer().SetBackground(theme.GetBackgroundColor())
        view.GetRenderer().SetBackground2(theme.GetBackgroundColor2())
        view.GetRenderer().SetGradientBackground(True)
        view.GetRenderer().AddActor(vertActor)
        view.GetRenderer().AddActor(outlineActor)
        view.GetRenderer().AddActor(edgeActor)
        view.GetRenderer().AddActor(graphActor)
        view.GetRenderer().AddActor(vertexActor)
        view.GetRenderer().AddActor(labelActor)
        view.GetRenderer().AddActor(msActor)
        
        # ----------
        # General interactor
        isty = vtk.vtkInteractorStyleRubberBand2D()
        # RubberBand2D assumes/needs parallel projection ON
        view.GetRenderer().GetActiveCamera().ParallelProjectionOn()
        iren = view.GetRenderWindow().GetInteractor()
        iren.SetInteractorStyle(isty)        
        # Interactor style must be set before scalar bar can be shown
        # view.SetVertexScalarBarVisibility(True)

        sbActor = vtk.vtkScalarBarActor()
        sbActor.SetLookupTable(vertMapper.GetLookupTable())
        sbActor.SetTitle(vertMapper.GetArrayName())
        sbActor.SetNumberOfLabels(3)
        vertexScalarBar = vtk.vtkScalarBarWidget()
        vertexScalarBar.SetScalarBarActor(sbActor)
        vertexScalarBar.SetInteractor(iren)
        vertexScalarBar.SetDefaultRenderer(view.GetRenderer())
        vertexScalarBar.SetCurrentRenderer(view.GetRenderer())
        vertexScalarBar.SetEnabled(True)
        scalarBarRep = vertexScalarBar.GetRepresentation()
        scalarBarRep.SetOrientation(1)  # 0 = Horizontal, 1 = Vertical
        scalarBarRep.GetPositionCoordinate().SetValue(0.05,0.05)
        scalarBarRep.GetPosition2Coordinate().SetValue(0.15,0.25)
        
        # Adding it this way gets it to show up, but it's not interactive
        view.GetRenderer().AddActor(sbActor)
        view.ResetCamera()
        view.Render()
        
        # ----------
        # Add Actors to QListWidget to allow check and uncheck for visibility
        listItem0 = QtGui.QListWidgetItem()
        listItem0.setText('Index Labels')
        listItem0.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
        labelActor.SetVisibility(0)
        listItem0.setCheckState(QtCore.Qt.Unchecked)
        # Put actor it in as data in the list widget item
        listItem0.setData(QtCore.Qt.UserRole, QtCore.QVariant(labelActor))
        ui_window.listWidget.insertItem(0,listItem0)
        
        # Test retrieval of actor from list widget item
        # tmpItem = ui_window.listWidget.item(0)
        # tmpQtActor = tmpItem.data(QtCore.Qt.UserRole)
        # tmpActor = tmpQtActor.toPyObject()
        # tmpActor.SetVisibility(0)
        
        # Shorter way to add item to list widget
        listItem1 = QtGui.QListWidgetItem('Vertices (background)', ui_window.listWidget)
        listItem1.setData(QtCore.Qt.UserRole, QtCore.QVariant(vertexActor))
        listItem1.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
        listItem1.setCheckState(QtCore.Qt.Checked)

        listItem2 = QtGui.QListWidgetItem('Graph (background)', ui_window.listWidget)
        listItem2.setData(QtCore.Qt.UserRole, QtCore.QVariant(graphActor))
        listItem2.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
        listItem2.setCheckState(QtCore.Qt.Checked)

        listItem3 = QtGui.QListWidgetItem()
        listItem3.setText('Basis Function Vertices')
        listItem3.setData(QtCore.Qt.UserRole, QtCore.QVariant(basisActorCollection))
        listItem3.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
        listItem3.setCheckState(QtCore.Qt.Checked)
        ui_window.listWidget.insertItem(1,listItem3)
        
        listItem6 = QtGui.QListWidgetItem()
        listItem6.setText('Basis Function Edges')
        listItem6.setData(QtCore.Qt.UserRole, QtCore.QVariant(edgeActor))
        listItem6.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
        listItem6.setCheckState(QtCore.Qt.Checked)
        ui_window.listWidget.insertItem(2,listItem6)
        
        listItem4 = QtGui.QListWidgetItem()
        listItem4.setText('MultiScale Graph')
        listItem4.setData(QtCore.Qt.UserRole, QtCore.QVariant(msActor))
        listItem4.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
        listItem4.setCheckState(QtCore.Qt.Checked)
        ui_window.listWidget.insertItem(3,listItem4)
                
        listItem5 = QtGui.QListWidgetItem()
        listItem5.setText('Basis Function Scale Bar')
        listItem5.setData(QtCore.Qt.UserRole, QtCore.QVariant(sbActor))
        listItem5.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
        listItem5.setCheckState(QtCore.Qt.Checked)
        ui_window.listWidget.insertItem(3,listItem5)
        
        iren.Initialize()
        iren.Start()
# Add distances to each point
signedDistances = vtk.vtkFloatArray()
signedDistances.SetNumberOfComponents(1)
signedDistances.SetName("SignedDistances")

# Evaluate the signed distance function at all of the grid points
for pointId in range(points.GetNumberOfPoints()):
    p = points.GetPoint(pointId)
    signedDistance = implicitPolyDataDistance.EvaluateFunction(p)
    signedDistances.InsertNextValue(signedDistance)

polyData = vtk.vtkPolyData()
polyData.SetPoints(points)
polyData.GetPointData().SetScalars(signedDistances)

vertexGlyphFilter = vtk.vtkVertexGlyphFilter()
vertexGlyphFilter.SetInputData(polyData)
vertexGlyphFilter.Update()

signedDistanceMapper = vtk.vtkPolyDataMapper()
signedDistanceMapper.SetInputConnection(vertexGlyphFilter.GetOutputPort())
signedDistanceMapper.ScalarVisibilityOn()

signedDistanceActor = vtk.vtkActor()
signedDistanceActor.SetMapper(signedDistanceMapper)

renderer = vtk.vtkRenderer()
renderer.AddViewProp(sphereActor)
renderer.AddViewProp(signedDistanceActor)

renderWindow = vtk.vtkRenderWindow()
def writeLegacyVTK():
    # This is where the data is for testing purposes.
    print "Current working directory:", os.getcwd()
    
    if os.path.isdir("vtk") == False:
        os.makedirs("vtk")
        print "Cretated vtk output directory..."
    
    if os.path.isdir("files") == False:
        os.makedirs("files")
        print "Created files ouptut directory..."
        

    # Working with the task mesh.
    taskMeshReader = vtk.vtkXMLPolyDataReader()
    taskMeshReader.SetFileName(meshSet[0])
    taskMeshReader.Update()

    taskMesh = taskMeshReader.GetOutput()

    # Get the range of branch labels.
    labelRange = [0, 0]
    taskMesh.GetCellData().GetScalars().GetRange(labelRange, 0)

    # Convert label range to a list of labels.
    labelRange = range(int(labelRange[0]), int(labelRange[1]) + 1)
    print "Labels found in task mesh:", labelRange


    # Store the number of rings for each label. 
    numRingsPerLabel = {}

    # For every label in the range of labels we want to extract all cells/quads.
    for label in labelRange:
        # Use this filter to extract the cells for a given label value.
        branchSelector = vtk.vtkThreshold()
        branchSelector.SetInputData(taskMesh)
        branchSelector.ThresholdBetween(label,label);
        branchSelector.Update()

        taskMeshBranch = branchSelector.GetOutput()

        # New vtkPoints for storing reordered points.
        reorderedPoints = vtk.vtkPoints()

        # New vtkCellArray for storing reordeced cells.
        reorderedCellArray = vtk.vtkCellArray()
        numQuadRowsPerBranch = taskMeshBranch.GetNumberOfCells() / numQuadsPerRing;
        numRingsPerLabel[label] = numQuadRowsPerBranch
        ringIds = range(0, numQuadRowsPerBranch);

        # Working with rows in reverse order: UPSTREAM.
        ringIds.reverse()


        rowBase = 0
        # Iterate over the rings in reverse order.
        for ringNum in ringIds:
            # Iterate over the cells in normal order.
            for cellNum in range(0, numQuadsPerRing):
                # Calculate the 'real' cell id and get the corresponding cell.
                cellId = ringNum * numQuadsPerRing + cellNum
                cell = taskMeshBranch.GetCell(cellId)

                # The ids to be written to the TXT file.
                pointIdList = [cell.GetNumberOfPoints()]

                # Write the appropriate points to TXT file.
                for pPos in range(0, cell.GetNumberOfPoints()):
                    newPoint = False
                    if ringNum == ringIds[0]:
                        if cellNum == 0:
                            newPoint = True
                        elif pPos == 1 or pPos == 2:
                            newPoint = True
                    else:
                        if cellNum == 0:
                            if pPos == 0 or pPos == 1:
                                newPoint = True
                        else:
                            if pPos == 1:
                                newPoint = True

                    if newPoint == True:

                        # Inserting a new point...
                        point = taskMeshBranch.GetPoint(cell.GetPointId(pPos))
                        # ... with a new id.
                        newId = reorderedPoints.InsertNextPoint(point)
                        pointIdList.append(newId)

                        # To make it easier for remembering the number of points instered in a row.
                        if cellNum == 0 and pPos == 0:
                            rowBasePrev = newId
                    else:
                        # Perhaps this can be done in a nicer way.
                        # Calculate the id of a previously inserted point.
                        if ringNum == ringIds[0]:
                            if cellNum == 1:
                                if pPos == 0:
                                    pointIdList.append(1L)
                                elif pPos == 3:
                                    pointIdList.append(2L)
                            else:
                                if pPos == 0:
                                    pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 2))
                                elif pPos == 3:
                                    pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3))
                        elif ringNum == ringIds[1]:
                            if cellNum == 0:
                                if pPos == 2:
                                    pointIdList.append(1L)
                                elif pPos == 3:
                                    pointIdList.append(0L)
                            else:
                                if pPos == 0:
                                    pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                elif pPos == 2:
                                    pointIdList.append(long(cellNum * 2 + 2))
                                elif pPos == 3:
                                    if cellNum == 1:
                                        pointIdList.append(1L)
                                    else:
                                        pointIdList.append(long(cellNum * 2))
                        else:
                            if cellNum == 0:
                                if pPos == 2:
                                    pointIdList.append(long(rowBase + 1))
                                elif pPos == 3:
                                    pointIdList.append(long(rowBase))
                            else:
                                if pPos == 0:
                                    pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                elif pPos == 2:
                                    pointIdList.append(long(rowBase + cellNum + 1))
                                elif pPos == 3:
                                    pointIdList.append(long(rowBase + cellNum))

                # print pointIdList, rowBase

                # Insert the ids into the cell array.
                newCell = vtk.vtkQuad()
                newCell.GetPointIds().Reset()
                for id in pointIdList[1:]:
                    newCell.GetPointIds().InsertNextId(id)
                reorderedCellArray.InsertNextCell(newCell)

            rowBase = rowBasePrev

        # print '\n'
        print "Inserted", reorderedPoints.GetNumberOfPoints(), "task mesh points for label", label, "..."
        print "Inserted", reorderedCellArray.GetNumberOfCells(), "task mesh cells for label", label, "..."

        # Create new vtkPolyData object for the new reordered mesh.
        reorderedTaskMeshBranch = vtk.vtkPolyData()

        # Put the reordered points and cells into the reordered mesh.
        reorderedTaskMeshBranch.SetPoints(reorderedPoints)
        reorderedTaskMeshBranch.SetPolys(reorderedCellArray)

        # Write the VTK file.
        reorderedMeshWriter = vtk.vtkXMLPolyDataWriter()
        reorderedMeshWriter.SetInputData(reorderedTaskMeshBranch)
        reorderedMeshWriter.SetFileName(taskVTKFiles[label])
        reorderedMeshWriter.Update()

    print "Rings per label:", numRingsPerLabel, "..."
    ringsPerLabelVals = numRingsPerLabel.values()

    # Check all rings per label values are the same.
    assert ringsPerLabelVals[1:] == ringsPerLabelVals[:-1], "All values of rings per label must be identical. Generated output is invalid ..."

    # Working with EC mesh.

    ecMeshReader = vtk.vtkXMLPolyDataReader()
    ecMeshReader.SetFileName(meshSet[1])
    ecMeshReader.Update()

    # Original ECs mesh to work with.
    ecMesh = ecMeshReader.GetOutput()
    print "There are", ecMesh.GetNumberOfCells(), "ECs in total ..."

    # For every label in the range of labels we want to extract all ECs.
    for label in labelRange:

        # Keep track of how many branches we need to skip.
        numECsPerLabel = numQuadsPerRing * numRingsPerLabel[label] * numECsPerQuad
        ecCellOffset = label * numECsPerLabel

        print "ecCellOffset", ecCellOffset

        # Collect cell ids to select.
        selectionIds = vtk.vtkIdTypeArray()
        for sId in range(0, numECsPerLabel):
            selectionIds.InsertNextValue(ecCellOffset + sId)

        # Create selecion node.
        selectionNode = vtk.vtkSelectionNode()
        selectionNode.SetFieldType(selectionNode.CELL)
        selectionNode.SetContentType(selectionNode.INDICES)
        selectionNode.SetSelectionList(selectionIds)

        # Create selection.
        selection = vtk.vtkSelection()
        selection.AddNode(selectionNode)

        # Use vtkSelection filter.
        selectionExtractor = vtk.vtkExtractSelection()
        selectionExtractor.SetInputData(0, ecMesh)
        selectionExtractor.SetInputData(1, selection)
        selectionExtractor.Update()

        extractedECs = selectionExtractor.GetOutput()

        # Ring ids list for traversal.
        ringIds = range(0, numRingsPerLabel[label])
        ringIds.reverse()

        # Number of ECs rows is the number of ECs per quad.
        rowIds = range(0, numECsPerCol)
        rowIds.reverse()

        # The ECs are organised in rings of blocks of cells.
        # New vtkCellArray for storing reordeced cells.
        reorderedCellArray = vtk.vtkCellArray()

        # Iterate over the rings in reverse order.
        for ringNum in ringIds:
            # Iterate over the 'imaginary' quads of cells in normal order.
            for quadNum in range(0, numQuadsPerRing):
                # Iterate over the rows of cells in reverse order.
                # Calculate the 'real' id for the 'imaginary' quad.
                quadId = ringNum * numQuadsPerRing + quadNum
                # Iterate over rows of cells in reverse order.
                for rowNum in rowIds:
                    # Iterate over the rows of cells in normal order.
                    for ecNum in range(0, numECsPerRow):
                        # Calculate the 'real' ec cell id and get the corresponding cell.
                        ecId = quadId * numECsPerQuad + rowNum * numECsPerRow + ecNum
                        ecCell = extractedECs.GetCell(ecId)
                        reorderedCellArray.InsertNextCell(ecCell)

        # Create new vtkPolyData object for the new reordered mesh.
        reorderedECMeshBranch = vtk.vtkPolyData()

        # Insert our new points.
        reorderedECMeshBranch.SetPoints(extractedECs.GetPoints())

        # Set the reordered cells to the reordered ECs mesh.
        reorderedECMeshBranch.SetPolys(reorderedCellArray)

        # New vtkPoints for storing reordered points.
        reorderedPoints = vtk.vtkPoints()

        # New vtkCellArray for storing reordeced cells.
        reorderedCellArray = vtk.vtkCellArray()

        rowBase = 0
        # Iterate over quads in normal order because they have been reordered.
        for quadNum in range(0, numRingsPerLabel[label] * numQuadsPerRing):
            # Iterate over rows in normal order because they have been reordered.
            for rowNum in range(0, numECsPerCol):
                # Iterate over the ECs in the row in normal order.
                for ecNum in range(0, numECsPerRow):
                    # Calculate the 'real' ec cell id and get the corresponding cell.
                    ecId = quadNum * numECsPerQuad + rowNum * numECsPerRow + ecNum
                    ecCell = reorderedECMeshBranch.GetCell(ecId)

                    # The ids to be written to the TXT file.
                    pointIdList = [ecCell.GetNumberOfPoints()]

                    # Write the appropriate points to the TXT file.
                    for pPos in range(0, ecCell.GetNumberOfPoints()):
                        newPoint = False
                        if rowNum == 0:
                            if ecNum == 0:
                                newPoint = True
                            elif pPos == 1 or pPos == 2:
                                newPoint = True
                        else:
                            if ecNum == 0:
                                if pPos == 0 or pPos == 1:
                                    newPoint = True
                            else:
                                if pPos == 1:
                                    newPoint = True

                        if newPoint == True:

                            # Inserting a new point...
                            point = reorderedECMeshBranch.GetPoint(ecCell.GetPointId(pPos))
                            # ... with a new id.
                            newId = reorderedPoints.InsertNextPoint(point)
                            pointIdList.append(newId)


                            if ecNum == 0 and pPos == 0:
                                rowBasePrev = newId
                        else:
                            # Perhaps this can be done in a nicer way.
                            # Calculate the ide of a previously inserted point.
                            if rowNum == 0:
                                if ecNum == 1:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3))
                                    elif pPos == 3:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 4))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 2))
                                    elif pPos == 3:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3))
                            elif rowNum == 1:
                                if ecNum == 0:
                                    if pPos == 2:
                                        pointIdList.append(long(rowBase + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                    elif pPos == 2:
                                        pointIdList.append(long(rowBase + ecNum * 2 + 2))
                                    elif pPos == 3:
                                        if ecNum == 1:
                                            pointIdList.append(long(rowBase + 1))
                                        else:
                                            pointIdList.append(long(rowBase + ecNum * 2))
                            else:
                                if ecNum == 0:
                                    if pPos == 2:
                                        pointIdList.append(long(rowBase + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                    elif pPos == 2:
                                        pointIdList.append(long(rowBase + ecNum + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase + ecNum))

                    # print pointIdList, rowBase

                    # Insert the ids into the cell array.
                    newCell = vtk.vtkQuad()
                    newCell.GetPointIds().Reset()
                    for id in pointIdList[1:]:
                        newCell.GetPointIds().InsertNextId(id)
                    reorderedCellArray.InsertNextCell(newCell)

                rowBase = rowBasePrev

        # print '\n'
        print "There are", reorderedPoints.GetNumberOfPoints(), "ECs points for label", label, "..."
        print "There are", reorderedCellArray.GetNumberOfCells(), "ECs cells for label", label, "..."

        # Create new vtkPolyData object for the new reordered mesh.
        reorderedECs = vtk.vtkPolyData()

        # Put the reordered points and cells into the mesh.
        reorderedECs.SetPoints(reorderedPoints)
        reorderedECs.SetPolys(reorderedCellArray)

        # Write the VTK EC mesh file.
        reorderedMeshWriter = vtk.vtkXMLPolyDataWriter()
        reorderedMeshWriter.SetInputData(reorderedECs)
        reorderedMeshWriter.SetFileName(ecVTKFiles[label])
        reorderedMeshWriter.Update()

        # Use VTK centroid filter to get the centroids in the right order
        # from the reorderedECMeshBranch.
        centroidFilter = vtk.vtkCellCenters()
        centroidFilter.SetInputData(reorderedECs)
        centroidFilter.Update()

        # Create a vertex cell for each point.
        pointsToVerticesFilter = vtk.vtkVertexGlyphFilter()
        pointsToVerticesFilter.SetInputData(centroidFilter.GetOutput())
        pointsToVerticesFilter.Update()

        reorderedCentroidBranch = pointsToVerticesFilter.GetOutput()

        # Write the VTK EC centrouid file.
        centroidWriter = vtk.vtkXMLPolyDataWriter()
        centroidWriter.SetInputData(reorderedCentroidBranch)
        centroidWriter.SetFileName(ecCentroidVTKFiles[label])
        centroidWriter.Update()

        # Write the centroids to the TXT points and cells files.
        for cId in range(0, reorderedCentroidBranch.GetNumberOfCells()):
            centCell = reorderedCentroidBranch.GetCell(cId)
            centIds = [centCell.GetNumberOfPoints()]

            # Write centroid ids.
            ptId = centCell.GetPointId(0)
            centIds.append(ptId)

            # Write centroid points.
            point = reorderedCentroidBranch.GetPoint(ptId)




    # Working with SMC mesh.
    # Working with SMC mesh.
    # Working with SMC mesh.
    smcMeshReader = vtk.vtkXMLPolyDataReader()
    smcMeshReader.SetFileName(meshSet[2])
    smcMeshReader.Update()

    # Original SMCs mesh to work with.
    smcMesh = smcMeshReader.GetOutput()
    print "There are", smcMesh.GetNumberOfCells(), "SMCs in total ..."

    # For every label in the range of labels we want to extract all SMCs.
    for label in labelRange:

        # Keep track of how many branches we need to skip.
        numSMCsPerLabel = numQuadsPerRing * numRingsPerLabel[label] * numSMCsPerQuad
        smcCellOffset = label * numSMCsPerLabel

        print "smcCellOffset", smcCellOffset

        # Collect cell ids to select.
        selectionIds = vtk.vtkIdTypeArray()
        for sId in range(0, numSMCsPerLabel):
            selectionIds.InsertNextValue(smcCellOffset + sId)

        # Create selecion node.
        selectionNode = vtk.vtkSelectionNode()
        selectionNode.SetFieldType(selectionNode.CELL)
        selectionNode.SetContentType(selectionNode.INDICES)
        selectionNode.SetSelectionList(selectionIds)

        # Create selection.
        selection = vtk.vtkSelection()
        selection.AddNode(selectionNode)

        # Use vtkSelection filter.
        selectionExtractor = vtk.vtkExtractSelection()
        selectionExtractor.SetInputData(0, smcMesh)
        selectionExtractor.SetInputData(1, selection)
        selectionExtractor.Update()

        extractedSMCs = selectionExtractor.GetOutput()

        # Ring ids list for traversal.
        ringIds = range(0, numRingsPerLabel[label])
        ringIds.reverse()

        # Number of SMCs rows is the number of ECs per quad times 13.
        rowIds = range(0, numSMCsPerCol)
        rowIds.reverse()

        # The SMCs are organised in rings of blocks of cells.
        # New vtkCellArray for storing reordeced cells.
        reorderedCellArray = vtk.vtkCellArray()

        # Iterate over the rings in reverse order.
        for ringNum in ringIds:
            # Iterate over the 'imaginary' quads of cells in normal order.
            for quadNum in range(0, numQuadsPerRing):
                # Iterate over the rows of cells in reverse order.
                # Calculate the 'real' id for the 'imaginary' quad.
                quadId = ringNum * numQuadsPerRing + quadNum
                # Iterate over rows of cells in reverse order.
                for rowNum in rowIds:
                    # Iterate over the rows of cells in normal order.
                    for smcNum in range(0, numSMCsPerRow):
                        # Calculate the 'real' smc cell id and get the corresponding cell.
                        smcId = quadId * numSMCsPerQuad + rowNum * numSMCsPerRow + smcNum
                        smcCell = extractedSMCs.GetCell(smcId)
                        reorderedCellArray.InsertNextCell(smcCell)

        # Create new vtkPolyData object for the new reordered mesh.
        reorderedSMCMeshBranch = vtk.vtkPolyData()

        # Insert our new points.
        reorderedSMCMeshBranch.SetPoints(extractedSMCs.GetPoints())

        # Set the reordered cells to the reordered SMCs mesh.
        reorderedSMCMeshBranch.SetPolys(reorderedCellArray)

        # New vtkPoints for storing reordered points.
        reorderedPoints = vtk.vtkPoints()

        # New vtkCellArray for storing reordeced cells.
        reorderedCellArray = vtk.vtkCellArray()

        rowBase = 0
        # Iterate over quads in normal order because they have been reordered.
        for quadNum in range(0, numRingsPerLabel[label] * numQuadsPerRing):
            # Iterate over rows in normal order because they have been reordered.
            for rowNum in range(0, numSMCsPerCol):
                # Iterate over the SMCs in the row in normal order.
                for smcNum in range(0, numSMCsPerRow):
                    # Calculate the 'real' smc cell id and get the corresponding cell.
                    smcId = quadNum * numSMCsPerQuad + rowNum * numSMCsPerRow + smcNum
                    smcCell = reorderedSMCMeshBranch.GetCell(smcId)

                    # The ids to be written to the TXT file.
                    pointIdList = [smcCell.GetNumberOfPoints()]

                    # Write the appropriate points to the TXT file.
                    for pPos in range(0, smcCell.GetNumberOfPoints()):
                        newPoint = False
                        if rowNum == 0:
                            if smcNum == 0:
                                newPoint = True
                            elif pPos == 1 or pPos == 2:
                                newPoint = True
                        else:
                            if smcNum == 0:
                                if pPos == 0 or pPos == 1:
                                    newPoint = True
                            else:
                                if pPos == 1:
                                    newPoint = True
                        if newPoint == True:

                            # Inserting a new point...
                            point = reorderedSMCMeshBranch.GetPoint(smcCell.GetPointId(pPos))
                            # with a new id.
                            newId = reorderedPoints.InsertNextPoint(point)
                            pointIdList.append(newId)

                            if smcNum == 0 and pPos == 0:
                                rowBasePrev = newId
                        else:
                            # Perhaps this can be done in a nicer way.
                            # Calculate the ide of a previously inserted point.
                            if rowNum == 0:
                                if smcNum == 1:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3))
                                    elif pPos == 3:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 4))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 2))
                                    elif pPos == 3:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 3))
                            elif rowNum == 1:
                                if smcNum == 0:
                                    if pPos == 2:
                                        pointIdList.append(long(rowBase + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                    elif pPos == 2:
                                        pointIdList.append(long(rowBase + smcNum * 2 + 2))
                                    elif pPos == 3:
                                        if smcNum == 1:
                                            pointIdList.append(long(rowBase + 1))
                                        else:
                                            pointIdList.append(long(rowBase + smcNum * 2))
                            else:
                                if smcNum == 0:
                                    if pPos == 2:
                                        pointIdList.append(long(rowBase + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase))
                                else:
                                    if pPos == 0:
                                        pointIdList.append(long(reorderedPoints.GetNumberOfPoints() - 1))
                                    elif pPos == 2:
                                        pointIdList.append(long(rowBase + smcNum + 1))
                                    elif pPos == 3:
                                        pointIdList.append(long(rowBase + smcNum))

                    # print pointIdList, rowBase

                    # Insert the ids into the cell array.
                    newCell = vtk.vtkQuad()
                    newCell.GetPointIds().Reset()
                    for id in pointIdList[1:]:
                        newCell.GetPointIds().InsertNextId(id)
                    reorderedCellArray.InsertNextCell(newCell)

                rowBase = rowBasePrev

        # print '\n'
        print "There are", reorderedPoints.GetNumberOfPoints(), "SMCs points for label", label, "..."
        print "There are", reorderedCellArray.GetNumberOfCells(), "SMCs cells for label", label, "..."

        # Create new vtkPolyData object for the new reordered mesh.
        reorderedSMCs = vtk.vtkPolyData()

        # Put the reordered points and cells in to the mesh.
        reorderedSMCs.SetPoints(reorderedPoints)
        reorderedSMCs.SetPolys(reorderedCellArray)

        # Write the VTK SMC mesh file.
        reorderedMeshWriter = vtk.vtkXMLPolyDataWriter()
        reorderedMeshWriter.SetInputData(reorderedSMCs)
        reorderedMeshWriter.SetFileName(smcVTKFiles[label])
        reorderedMeshWriter.Update()

    print "All done ..."
    print "... Except the last configuration_info.txt file ..."

    configFile = open("files/configuration_info.txt", 'w')
    configFile.write("Processors information\n")
    configFile.write("Total number of points per branch (vtk points) = %d\t\tm = %d n = %d\n" \
    % ((numQuadsPerRing + 1) * (numRingsPerLabel[0] + 1), (numQuadsPerRing + 1), (numRingsPerLabel[0] + 1)))
    configFile.write("Total number of cells per branch (vtk cells) = %d\t\tm = %d n = %d\n" \
    % (numQuadsPerRing * numRingsPerLabel[0], numQuadsPerRing, numRingsPerLabel[0]))
    configFile.write("Total number of SMC mesh points per processor mesh (vtk points) = %d\t\tm = %d n = %d\n" \
    % ((numSMCsPerCol + 1) * (numSMCsPerRow + 1), (numSMCsPerCol + 1), (numSMCsPerRow + 1)))
    configFile.write("Total number of SMC mesh cells per processor mesh (vtk cells) = %d\t\tm = %d n = %d\n" \
    % (numSMCsPerCol * numSMCsPerRow, numSMCsPerCol, numSMCsPerRow))
    configFile.write("Total number of EC mesh points per processor mesh (vtk points) = %d\t\tm = %d n = %d\n" \
    % ((numECsPerCol + 1) * (numECsPerRow + 1), (numECsPerCol + 1), (numECsPerRow + 1)))
    configFile.write("Total number of EC mesh cells per processor mesh (vtk cells) = %d\t\tm = %d n = %d\n" \
    % (numECsPerCol *numECsPerRow, numECsPerCol, numECsPerRow))
    configFile.write("Total number of EC mesh centeroid points per processor mesh (vtk points) = %d\t\tm = %d n = %d\n" \
    % (numECsPerCol *numECsPerRow, numECsPerCol, numECsPerRow))
    configFile.write("Total number of EC mesh centeroid cells per processor mesh (vtk cells) = %d\t\tm = %d n = %d\n" \
    % (numECsPerCol *numECsPerRow, numECsPerCol, numECsPerRow))

    configFile.close()

    print "Now it is all done for real ..."
Esempio n. 44
0
def buildATPMesh():
    # Report our CWD just for testing purposes.
    print "CWD:", os.getcwd()

    # Read in the mesh.
    meshReader = vtk.vtkXMLPolyDataReader()
    meshReader.SetFileName(meshFile)
    meshReader.Update()

    mesh = meshReader.GetOutput()
    print mesh.GetNumberOfCells()
    
    # Put it through centroids filter.
    # Use VTK centroid filter to get the centroids in the right order
    # from the reorderedECMeshBranch.
    centroidFilter = vtk.vtkCellCenters()
    centroidFilter.SetInput(mesh)

    # Create a vertex cell for each point.
    pointsToVerticesFilter = vtk.vtkVertexGlyphFilter()
    pointsToVerticesFilter.SetInputConnection(centroidFilter.GetOutputPort())
    pointsToVerticesFilter.Update()
    
    atpDataset = pointsToVerticesFilter.GetOutput()
    
    # Here we are assuming that cell ordering has been preserved.
    gridCoords = mesh.GetCellData().GetArray("gridCoords")

    # Create a new cell data array "parametricDistance" in the centroids
    # dataset with the values from the previous step. This array is really not
    # needed for any computations but is good to have for verification. Also,
    # it is useful to know the max value for each branch.
    axialDist = vtk.vtkIntArray()
    axialDist.SetName("parametriDistance")
    
    # Iterate over all quad cells in the mesh and pull out the first component
    # of the "gridCoords" cell data array. Here we assuming the mesh contains
    # only quad cells.
    # If the branches were labelled properly here, it would be much simpler
    # to set the neganive axial distance values by examining the range first.
    for cellId in range(0, mesh.GetNumberOfCells()):
        axialDist.InsertNextValue(gridCoords.GetTuple(cellId)[0])

    atpArray = vtk.vtkDoubleArray()
    atpArray.SetName("initialATP")
    
    axialDistRange = [0, 0]
    axialDist.GetRange(axialDistRange, 0)
    
    # Iterate over the "axialDist" cell array and for each value call
    # the agonistValue function and store the computed values in the new
    # "initialATP" cell data array.
    for cellId in range(0, axialDist.GetNumberOfTuples()):
        # Figure out the current branch id.
        branchId = cellId / (axialDist.GetNumberOfTuples() / 3)
        
        # For the first branch the parametric distance value must be in the
        # range [maxDist - 1, 0). Range values are required for this.
        
        # TODO: The ATP calculations here are repeated many times for the same value
        # of the parametric distnace. It would make sense to have a lookup table (dictionary)
        # for previously calculated values.
        if branchId == 0:
            distVal = axialDist.GetValue(cellId) - axialDistRange[1] - 1
            atpVal = sigmoidATP(distVal)
        else:
            # This is for the 'normal' atp map.
            distVal = axialDist.GetValue(cellId)
            atpVal = sigmoidATP(distVal)

        atpArray.InsertNextValue(atpVal)

    # Assert the number of cells is equal to the number of items in the cell arrays.
    assert axialDist.GetNumberOfTuples() == atpDataset.GetNumberOfCells(), "Number of cells (%d) and cell data values (%d) mismatch." % (axialDist.GetNumberOfTuples(), atpDataset.GetNumberOfCells)
    assert atpArray.GetNumberOfTuples() == atpDataset.GetNumberOfCells(), "Number of cells (%d) and cell data values (%d) mismatch." % (atpArray.GetNumberOfTuples(), atpDataset.GetNumberOfCells())
    
    atpDataset.GetCellData().AddArray(axialDist)
    atpDataset.GetCellData().AddArray(atpArray)
    
    atpMapWriter = vtk.vtkXMLPolyDataWriter()
    atpMapWriter.SetFileName(atpFile)
    atpMapWriter.SetInput(atpDataset)
    atpMapWriter.Update()
    
    # Provide a quick visualisation of the ATP profile for validation.
    pointsX = range(-int(axialDistRange[1] - 1), int(axialDistRange[1]))
    pointsY = []
    for pt in pointsX:
        pointsY.append(sigmoidATP(pt))
    
    pyplot.plot(pointsX, pointsY, 'b')
    pyplot.show()