Esempio n. 1
0
    def __init__(self):
        self._rendererScene = vtk.vtkRenderer()
        self._rendererScene.SetBackground(self.COLOR_BG)

        self._renderWindowScene = vtk.vtkRenderWindow()
        self._renderWindowScene.AddRenderer(self._rendererScene)
        self._renderWindowInteractor = vtk.vtkRenderWindowInteractor()
        self._renderWindowInteractor.SetRenderWindow(self._renderWindowScene)
        #self._interactorStyle = vtk.vtkInteractorStyleUnicam()
        self._interactorStyle = self.KeyPressInteractorStyle()
        self._interactorStyle.SetCamera(self._rendererScene.GetActiveCamera())
        self._interactorStyle.SetRenderer(self._rendererScene)
        self._interactorStyle.SetRenderWindow(self._renderWindowScene)

        self._contextViewPlotCurv = vtk.vtkContextView()
        self._contextViewPlotCurv.GetRenderer().SetBackground(
            self.COLOR_BG_PLOT)

        self._contextInteractorStyleCurv = self.KeyPressContextInteractorStyle(
        )
        self._contextInteractorStyleCurv.SetRenderWindow(
            self._contextViewPlotCurv.GetRenderWindow())

        self._chartXYCurv = vtk.vtkChartXY()
        self._contextViewPlotCurv.GetScene().AddItem(self._chartXYCurv)
        self._chartXYCurv.SetShowLegend(True)
        self._chartXYCurv.GetAxis(vtk.vtkAxis.LEFT).SetTitle("")
        self._chartXYCurv.GetAxis(vtk.vtkAxis.BOTTOM).SetTitle("")

        self._contextViewPlotTors = vtk.vtkContextView()
        self._contextViewPlotTors.GetRenderer().SetBackground(
            self.COLOR_BG_PLOT)

        self._contextInteractorStyleTors = self.KeyPressContextInteractorStyle(
        )
        self._contextInteractorStyleTors.SetRenderWindow(
            self._contextViewPlotTors.GetRenderWindow())

        self._chartXYTors = vtk.vtkChartXY()
        self._contextViewPlotTors.GetScene().AddItem(self._chartXYTors)
        self._chartXYTors.SetShowLegend(True)
        self._chartXYTors.GetAxis(vtk.vtkAxis.LEFT).SetTitle("")
        self._chartXYTors.GetAxis(vtk.vtkAxis.BOTTOM).SetTitle("")

        self._textActor = vtk.vtkTextActor()
        self._textActor.GetTextProperty().SetColor(self.COLOR_LENGTH)

        self._addedBSpline = False
Esempio n. 2
0
def main():
    colors = vtk.vtkNamedColors()

    chart = vtk.vtkChartXYZ()
    chart.SetGeometry(vtk.vtkRectf(10.0, 10.0, 630, 470))

    plot = vtk.vtkPlotSurface()

    view = vtk.vtkContextView()
    view.GetRenderer().SetBackground(colors.GetColor3d("Silver"))
    view.GetRenderWindow().SetSize(640, 480)
    view.GetScene().AddItem(chart)

    # Create a surface
    table = vtk.vtkTable()
    numPoints = 70
    inc = 9.424778 / (numPoints - 1)
    for i in range(numPoints):
        arr = vtk.vtkFloatArray()
        table.AddColumn(arr)

    table.SetNumberOfRows(numPoints)
    for i in range(numPoints):
        x = i * inc
        for j in range(numPoints):
            y = j * inc
            table.SetValue(i, j, sin(sqrt(x * x + y * y)))

    # Set up the surface plot we wish to visualize and add it to the chart
    plot.SetXRange(0, 10.0)
    plot.SetYRange(0, 10.0)
    plot.SetInputData(table)
    plot.GetPen().SetColorF(colors.GetColor3d("Tomato"))
    chart.AddPlot(plot)

    view.GetRenderWindow().SetMultiSamples(0)
    view.GetInteractor().Initialize()
    view.GetRenderWindow().Render()

    # Rotate
    mouseEvent = vtk.vtkContextMouseEvent()
    mouseEvent.SetInteractor(view.GetInteractor())

    pos = vtk.vtkVector2i()

    lastPos = vtk.vtkVector2i()
    mouseEvent.SetButton(vtk.vtkContextMouseEvent.LEFT_BUTTON)
    lastPos.Set(100, 50)
    mouseEvent.SetLastScreenPos(lastPos)
    pos.Set(150, 100)
    mouseEvent.SetScreenPos(pos)

    sP = [float(x) for x in pos]
    lSP = [float(x) for x in lastPos]
    screenPos = [float(x) for x in mouseEvent.GetScreenPos()]
    lastScreenPos = [float(x) for x in mouseEvent.GetLastScreenPos()]

    chart.MouseMoveEvent(mouseEvent)

    view.GetInteractor().Start()
Esempio n. 3
0
    def testBarGraph(self):
        "Test if bar graphs can be built with python"

        # Set up a 2D scene, add an XY chart to it
        view = vtk.vtkContextView()
        view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
        view.GetRenderWindow().SetSize(400, 300)
        chart = vtk.vtkChartXY()
        view.GetScene().AddItem(chart)

        # Create a table with some points in it
        table = vtk.vtkTable()

        arrMonth = vtk.vtkIntArray()
        arrMonth.SetName("Month")

        arr2008 = vtk.vtkIntArray()
        arr2008.SetName("2008")

        arr2009 = vtk.vtkIntArray()
        arr2009.SetName("2009")

        arr2010 = vtk.vtkIntArray()
        arr2010.SetName("2010")

        numMonths = 12

        for i in range(0, numMonths):
            arrMonth.InsertNextValue(i + 1)
            arr2008.InsertNextValue(data_2008[i])
            arr2009.InsertNextValue(data_2009[i])
            arr2010.InsertNextValue(data_2010[i])

        table.AddColumn(arrMonth)
        table.AddColumn(arr2008)
        table.AddColumn(arr2009)
        table.AddColumn(arr2010)

        # Now add the line plots with appropriate colors
        line = chart.AddPlot(2)
        line.SetInputData(table, 0, 1)
        line.SetColor(0, 255, 0, 255)

        line = chart.AddPlot(2)
        line.SetInputData(table, 0, 2)
        line.SetColor(255, 0, 0, 255)

        line = chart.AddPlot(2)
        line.SetInputData(table, 0, 3)
        line.SetColor(0, 0, 255, 255)

        view.GetRenderWindow().SetMultiSamples(0)
        view.GetRenderWindow().Render()

        img_file = "TestBarGraph.png"
        vtk.test.Testing.compareImage(
            view.GetRenderWindow(),
            vtk.test.Testing.getAbsImagePath(img_file),
            threshold=25)
        vtk.test.Testing.interact()
def TestColorTransferFunction(int ,  char):
    # Set up a 2D scene, add an XY chart to it
    view = vtk.vtkContextView()
    view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
    view.GetRenderWindow().SetSize(400, 300)
    
    chart = vtk.vtkChartXY()
    chart.SetTitle('Chart')
    view.GetScene().AddItem(chart)
    
    colorTransferFunction = vtk.vtkColorTransferFunction()
    colorTransferFunction.AddHSVSegment(50.,0.,1.,1.,85.,0.3333,1.,1.)
    colorTransferFunction.AddHSVSegment(85.,0.3333,1.,1.,170.,0.6666,1.,1.)
    colorTransferFunction.AddHSVSegment(170.,0.6666,1.,1.,200.,0.,1.,1.)
    
    colorTransferFunction.Build()
    
    colorTransferItem = vtk.vtkColorTransferFunctionItem()
    colorTransferItem.SetColorTransferFunction(colorTransferFunction)
    chart.AddPlot(colorTransferItem)
    
    controlPointsItem = vtk.vtkColorTransferControlPointsItem()
    controlPointsItem.SetColorTransferFunction(colorTransferFunction)
    controlPointsItem.SetUserBounds(0., 255., 0., 1.)
    chart.AddPlot(controlPointsItem)
    
    # Finally render the scene and compare the image to a reference image
    view.GetRenderWindow().SetMultiSamples(1)
    if view.GetContext().GetDevice().IsA( "vtkOpenGLContextDevice2D") :
      view.GetInteractor().Initialize()
      view.GetInteractor().Start()
    else:
        print 'GL version 2 or higher is required.'
    
    return EXIT_SUCCESS
Esempio n. 5
0
    def __init__(self, parent=None):
        QCellWidget.__init__(self, parent)
        
        centralLayout = QtGui.QVBoxLayout()
        self.setLayout(centralLayout)
        centralLayout.setMargin(0)
        centralLayout.setSpacing(0)
                
        self.view = vtk.vtkContextView()
        self.widget = QVTKRenderWindowInteractor(self, 
                                                 rw=self.view.GetRenderWindow(),
                                                 iren=self.view.GetInteractor()
                                                )

        self.chart = vtk.vtkChartParallelCoordinates()
        self.view.GetScene().AddItem(self.chart)

        self.layout().addWidget(self.widget)

        # Create a annotation link to access selection in parallel coordinates view
        self.annotationLink = vtk.vtkAnnotationLink()
        # If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010)
        # See vtkSelectionNode doc for field and content type enum values
        self.annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(1)     # Point
        self.annotationLink.GetCurrentSelection().GetNode(0).SetContentType(4)   # Indices
        # Connect the annotation link to the parallel coordinates representation
        self.chart.SetAnnotationLink(self.annotationLink)
        self.annotationLink.AddObserver("AnnotationChangedEvent", self.selectionCallback)
    def generateParallelCoordinatesPlot(self):
        input = self.inputModule().getOutput()
        ptData = input.GetPointData()
        narrays = ptData.GetNumberOfArrays()
        arrays = []
        # Create a table with some points in it...
        table = vtk.vtkTable()
        for iArray in range(narrays):
            table.AddColumn(ptData.GetArray(iArray))

        # Set up a 2D scene, add an XY chart to it
        view = vtk.vtkContextView()
        #        view.SetRenderer( self.renderer )
        #        view.SetRenderWindow( self.renderer.GetRenderWindow() )
        view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
        view.GetRenderWindow().SetSize(600, 300)

        plot = vtk.vtkPlotParallelCoordinates()
        plot.SetInput(table)

        view.GetScene().AddItem(plot)

        view.ResetCamera()
        view.Render()
        # Start interaction event loop
        view.GetInteractor().Start()
Esempio n. 7
0
    def __init__(self, parent=None):
        QCellWidget.__init__(self, parent)

        centralLayout = QtGui.QVBoxLayout()
        self.setLayout(centralLayout)
        centralLayout.setMargin(0)
        centralLayout.setSpacing(0)

        self.view = vtk.vtkContextView()
        self.widget = QVTKRenderWindowInteractor(
            self,
            rw=self.view.GetRenderWindow(),
            iren=self.view.GetInteractor())

        self.chart = vtk.vtkChartParallelCoordinates()
        self.view.GetScene().AddItem(self.chart)

        self.layout().addWidget(self.widget)

        # Create a annotation link to access selection in parallel coordinates view
        self.annotationLink = vtk.vtkAnnotationLink()
        # If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010)
        # See vtkSelectionNode doc for field and content type enum values
        self.annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(
            1)  # Point
        self.annotationLink.GetCurrentSelection().GetNode(0).SetContentType(
            4)  # Indices
        # Connect the annotation link to the parallel coordinates representation
        self.chart.SetAnnotationLink(self.annotationLink)
        self.annotationLink.AddObserver("AnnotationChangedEvent",
                                        self.selectionCallback)
Esempio n. 8
0
    def __init__(self, x, y, xrange_=10.):
        super(VTKPlot, self).__init__()
        self.setGeometry(50, 50, 700, 350)

        self.setWindowOpacity(1.)

        self.view = vtk.vtkContextView()
        chartMatrix = vtk.vtkChartMatrix()
        chartMatrix.SetSize(vtk.vtkVector2i(1, 1))
        chartMatrix.SetGutter(vtk.vtkVector2f(50, 50))

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        self.view.SetRenderWindow(self.vtkWidget.GetRenderWindow())
        self.view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
        self.view.GetScene().AddItem(chartMatrix)

        self.chart = chartMatrix.GetChart(vtk.vtkVector2i(0, 0))
        self.arrY = vtk.vtkFloatArray()
        self.arrX = vtk.vtkFloatArray()

        self.table = vtk.vtkTable()
        self.add_plot(x, y, xrange_=xrange_)

        self.chart.GetAxis(vtk.vtkAxis.BOTTOM).SetTitle("Time")
        self.chart.GetAxis(vtk.vtkAxis.LEFT).SetTitle("Signal")

        self.view.GetRenderWindow().SetMultiSamples(0)
        self.view.GetRenderWindow().Render()

        layout = QGridLayout()
        layout.addWidget(self.vtkWidget, 0, 0)

        self.setLayout(layout)
Esempio n. 9
0
    def testLinePlot(self):
        "Test if line plots can be built with python"

        # Set up a 2D scene, add an XY chart to it
        view = vtk.vtkContextView()
        view.GetRenderer().SetBackground(1.0,1.0,1.0)
        view.GetRenderWindow().SetSize(400,300)
        chart = vtk.vtkChartXY()
        view.GetScene().AddItem(chart)

        # Create a table with some points in it
        table = vtk.vtkTable()

        arrX = vtk.vtkFloatArray()
        arrX.SetName("X Axis")

        arrC = vtk.vtkFloatArray()
        arrC.SetName("Cosine")

        arrS = vtk.vtkFloatArray()
        arrS.SetName("Sine")

        arrS2 = vtk.vtkFloatArray()
        arrS2.SetName("Sine2")

        numPoints = 69
        inc = 7.5 / (numPoints - 1)

        for i in range(0,numPoints):
            arrX.InsertNextValue(i*inc)
            arrC.InsertNextValue(math.cos(i * inc) + 0.0)
            arrS.InsertNextValue(math.sin(i * inc) + 0.0)
            arrS2.InsertNextValue(math.sin(i * inc) + 0.5)

        table.AddColumn(arrX)
        table.AddColumn(arrC)
        table.AddColumn(arrS)
        table.AddColumn(arrS2)

        # Now add the line plots with appropriate colors
        line = chart.AddPlot(0)
        line.SetInput(table,0,1)
        line.SetColor(0,255,0,255)
        line.SetWidth(1.0)

        line = chart.AddPlot(0)
        line.SetInput(table,0,2)
        line.SetColor(255,0,0,255);
        line.SetWidth(5.0)

        line = chart.AddPlot(0)
        line.SetInput(table,0,3)
        line.SetColor(0,0,255,255);
        line.SetWidth(4.0)

        view.GetRenderWindow().SetMultiSamples(0)

        img_file = "TestLinePlot.png"
        vtk.test.Testing.compareImage(view.GetRenderWindow(),vtk.test.Testing.getAbsImagePath(img_file),threshold=25)
        vtk.test.Testing.interact()
    def generateParallelCoordinatesPlot( self ):
        input = self.inputModule().getOutput() 
        ptData = input.GetPointData()
        narrays = ptData.GetNumberOfArrays()
        arrays = []
        # Create a table with some points in it...
        table = vtk.vtkTable()
        for iArray in range( narrays ):
            table.AddColumn(  ptData.GetArray( iArray ) )                  
        
        # Set up a 2D scene, add an XY chart to it
        view = vtk.vtkContextView()
#        view.SetRenderer( self.renderer )    
#        view.SetRenderWindow( self.renderer.GetRenderWindow() )
        view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
        view.GetRenderWindow().SetSize(600,300)
        
        plot = vtk.vtkPlotParallelCoordinates()
        plot.SetInput(table)
                
        view.GetScene().AddItem(plot)
                                
        view.ResetCamera()
        view.Render()       
        # Start interaction event loop
        view.GetInteractor().Start()
Esempio n. 11
0
    def addPlot(self,_plotName,_style="Lines"):   # called directly from Steppable; add a (possibly more than one) plot to a plot window

        self.plotWindowInterfaceMutex.lock()
#        self.plotWindowMutex.lock()

#        return
#        print MODULENAME,'   addPlot():  _plotName= ',_plotName
#        import pdb; pdb.set_trace()
        
#        self.plotData[_plotName] = [array([],dtype=double),array([],dtype=double),False]  # 'array': from PyQt4.Qwt5.anynumpy import *
        
        self.chart = vtk.vtkChartXY()
#        self.chart.GetAxis(vtk.vtkAxis.LEFT).SetLogScale(True)
#        self.chart.GetAxis(vtk.vtkAxis.BOTTOM).SetLogScale(True)
#        self.numCharts += 1
        self.plotData[_plotName] = [self.chart]

        self.view = vtk.vtkContextView()
        self.ren = self.view.GetRenderer()
#        self.renWin = self.qvtkWidget.GetRenderWindow()
        self.renWin = self.pW.GetRenderWindow()
        self.renWin.AddRenderer(self.ren)

        # Create a table with some points in it
        self.table = vtk.vtkTable()

        self.arrX = vtk.vtkFloatArray()
        self.arrX.SetName("xarray")

        self.arrC = vtk.vtkFloatArray()
        self.arrC.SetName("yarray")

        numPoints = 5
        numPoints = 15
        inc = 7.5 / (numPoints - 1)

#        for i in range(0,numPoints):
#            self.arrX.InsertNextValue(i*inc)
#            self.arrC.InsertNextValue(math.cos(i * inc) + 0.0)

#        self.arrX.InsertNextValue(0.0)
#        self.arrC.InsertNextValue(0.0)
#        self.arrX.InsertNextValue(0.1)
#        self.arrC.InsertNextValue(0.1)

        self.table.AddColumn(self.arrX)
        self.table.AddColumn(self.arrC)

        # Now add the line plots with appropriate colors
        self.line = self.chart.AddPlot(0)
        self.line.SetInput(self.table,0,1)
        self.line.SetColor(0,0,255,255)
        self.line.SetWidth(1.0)


        self.view.GetRenderer().SetBackground([0.6,0.6,0.1])
        self.view.GetRenderer().SetBackground([1.0,1.0,1.0])
        self.view.GetScene().AddItem(self.chart)

        self.plotWindowInterfaceMutex.unlock()
Esempio n. 12
0
def initialize(self, VTKWebApp, args):
    dataid = args.id
    treedata = getDBdata(dataid)
    VTKWebApp.tree1 = treedata["tree1"]
    VTKWebApp.tree2 = treedata["tree2"]
    VTKWebApp.table = dataid+ ".csv"

    # Create default pipeline (Only once for all the session)
    if not VTKWebApp.view:
        # read the trees
        treeReader1 = vtk.vtkNewickTreeReader()
        treeReader1.SetReadFromInputString(1)
        treeReader1.SetInputString(VTKWebApp.tree1)
        treeReader1.Update()
        tree1 = treeReader1.GetOutput()

        treeReader2 = vtk.vtkNewickTreeReader()
        treeReader2.SetReadFromInputString(1)
        treeReader2.SetInputString(VTKWebApp.tree2)
        treeReader2.Update()
        tree2 = treeReader2.GetOutput()

        # read the table
        tableReader = vtk.vtkDelimitedTextReader()
        tableReader.SetFileName(VTKWebApp.table)
        tableReader.SetHaveHeaders(True)
        tableReader.DetectNumericColumnsOn()
        tableReader.ForceDoubleOn()
        tableReader.Update()
        table = tableReader.GetOutput()

        # setup the tanglegram
        tanglegram = vtk.vtkTanglegramItem()
        tanglegram.SetTree1(tree1);
        tanglegram.SetTree2(tree2);
        tanglegram.SetTable(table);
        tanglegram.SetTree1Label("tree1");
        tanglegram.SetTree2Label("tree2");

        # setup the window
        view = vtk.vtkContextView()
        view.GetRenderer().SetBackground(1,1,1)
        view.GetRenderWindow().SetSize(800,600)

        iren = view.GetInteractor()
        iren.SetRenderWindow(view.GetRenderWindow())

        transformItem = vtk.vtkContextTransform()
        transformItem.AddItem(tanglegram)
        transformItem.SetInteractive(1)

        view.GetScene().AddItem(transformItem)
        view.GetRenderWindow().SetMultiSamples(0)

        iren.Initialize()
        view.GetRenderWindow().Render()

        # VTK Web application specific
        VTKWebApp.view = view.GetRenderWindow()
        self.Application.GetObjectIdMap().SetActiveObject("VIEW", view.GetRenderWindow())
Esempio n. 13
0
def main():
    view = vtk.vtkContextView()
    view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
    view.GetRenderWindow().SetSize(400, 300)

    chart = vtk.vtkChartXY()
    view.GetScene().AddItem(chart)
    chart.SetShowLegend(True)

    table = vtk.vtkTable()

    arrX = vtk.vtkFloatArray()
    arrX.SetName('X Axis')

    arrC = vtk.vtkFloatArray()
    arrC.SetName('Cosine')

    arrS = vtk.vtkFloatArray()
    arrS.SetName('Sine')

    arrT = vtk.vtkFloatArray()
    arrT.SetName('Sine-Cosine')

    table.AddColumn(arrC)
    table.AddColumn(arrS)
    table.AddColumn(arrX)
    table.AddColumn(arrT)

    numPoints = 40

    inc = 7.5 / (numPoints - 1)
    table.SetNumberOfRows(numPoints)
    for i in range(numPoints):
        table.SetValue(i, 0, i * inc)
        table.SetValue(i, 1, math.cos(i * inc))
        table.SetValue(i, 2, math.sin(i * inc))
        table.SetValue(i, 3, math.sin(i * inc) - math.cos(i * inc))

    points = chart.AddPlot(vtk.vtkChart.POINTS)
    points.SetInputData(table, 0, 1)
    points.SetColor(0, 0, 0, 255)
    points.SetWidth(1.0)
    points.SetMarkerStyle(vtk.vtkPlotPoints.CROSS)

    points = chart.AddPlot(vtk.vtkChart.POINTS)
    points.SetInputData(table, 0, 2)
    points.SetColor(0, 0, 0, 255)
    points.SetWidth(1.0)
    points.SetMarkerStyle(vtk.vtkPlotPoints.PLUS)

    points = chart.AddPlot(vtk.vtkChart.POINTS)
    points.SetInputData(table, 0, 3)
    points.SetColor(0, 0, 255, 255)
    points.SetWidth(1.0)
    points.SetMarkerStyle(vtk.vtkPlotPoints.CIRCLE)

    view.GetRenderWindow().SetMultiSamples(0)
    view.GetInteractor().Initialize()
    view.GetInteractor().Start()
Esempio n. 14
0
    def create_widgets(self):
        # transfer function control

        self.qtVtkWidget = DBSTransferFunctionWindowInteractor(self, \
            app=self.parent() ) 
        
        self._contextView = vtk.vtkContextView()
        self._contextView.SetRenderWindow(self.qtVtkWidget.GetRenderWindow())
Esempio n. 15
0
	def __init__(self, data_source, input_link=None, highlight_link=None):
		"""Parallel coordinates view constructor needs a valid DataSource plus
		and external annotation link (from the icicle view).
		"""

		self.ds = data_source

		self.input_link = None
		if input_link is not None:
			self.SetInputAnnotationLink(input_link)

		# Set up a 2D scene, add an XY chart to it
		self.view = vtk.vtkContextView()
		self.view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
		self.view.GetRenderWindow().SetSize(600,300)

		self.chart = vtkvtg.vtkMyChartParallelCoordinates()

		self.highlight_link = None
		if highlight_link is not None:
			self.SetHighlightAnnotationLink(highlight_link)

		# Create a annotation link to access selection in parallel coordinates view
		self.link = vtk.vtkAnnotationLink()
		# If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010)
		# See vtkSelectionNode doc for field and content type enum values
		self.link.GetCurrentSelection().GetNode(0).SetFieldType(1)     # Point
		# The chart seems to force INDEX selection, so I'm using vtkConvertSelection below to get
		# out PedigreeIds...
		self.link.GetCurrentSelection().GetNode(0).SetContentType(4)   # 2 = PedigreeIds, 4 = Indices
		# Connect the annotation link to the parallel coordinates representation
		self.chart.SetAnnotationLink(self.link)

		# Set up callback for ID -> Pedigree ID conversion & copy to output link
		self.link.AddObserver("AnnotationChangedEvent", self.PCoordsSelectionCallback)

		# Set up output annotation link which will carry pedigree ids to image flow view
		# Type and field will be set during conversion to pedigree ids in PCoordsSelectionCallback
		self.output_link = vtk.vtkAnnotationLink()

		self.view.GetScene().AddItem(self.chart)
		# self.view.ResetCamera()
		# self.view.Render()

		# Set default scale range to show: 'all', 'coarse', 'fine'
		# TODO: Should check the menu to see which is checked so default is
		#   set by GUI
		self.scale_range = 'coarse'

		# Want to keep track of whether the node coming in on the input_link
		# is new or not
		self.input_link_idx = 0

		# Flag for whether to color by 'category_ids'
		# TODO: Should check the menu to see which is checked so default is
		#   set by GUI
		self.SetColorByArray("None")
Esempio n. 16
0
    def testBarGraph(self):
        "Test if bar graphs can be built with python"

        # Set up a 2D scene, add an XY chart to it
        view = vtk.vtkContextView()
        view.GetRenderer().SetBackground(1.0,1.0,1.0)
        view.GetRenderWindow().SetSize(400,300)
        chart = vtk.vtkChartXY()
        view.GetScene().AddItem(chart)

        # Create a table with some points in it
        table = vtk.vtkTable()

        arrMonth = vtk.vtkIntArray()
        arrMonth.SetName("Month")

        arr2008 = vtk.vtkIntArray()
        arr2008.SetName("2008")

        arr2009 = vtk.vtkIntArray()
        arr2009.SetName("2009")

        arr2010 = vtk.vtkIntArray()
        arr2010.SetName("2010")

        numMonths = 12

        for i in range(0,numMonths):
            arrMonth.InsertNextValue(i + 1)
            arr2008.InsertNextValue(data_2008[i])
            arr2009.InsertNextValue(data_2009[i])
            arr2010.InsertNextValue(data_2010[i])

        table.AddColumn(arrMonth)
        table.AddColumn(arr2008)
        table.AddColumn(arr2009)
        table.AddColumn(arr2010)

        # Now add the line plots with appropriate colors
        line = chart.AddPlot(2)
        line.SetInput(table,0,1)
        line.SetColor(0,255,0,255)

        line = chart.AddPlot(2)
        line.SetInput(table,0,2)
        line.SetColor(255,0,0,255);

        line = chart.AddPlot(2)
        line.SetInput(table,0,3)
        line.SetColor(0,0,255,255);

        view.GetRenderWindow().SetMultiSamples(0)
	view.GetRenderWindow().Render()

        img_file = "TestBarGraph.png"
        vtk.test.Testing.compareImage(view.GetRenderWindow(),vtk.test.Testing.getAbsImagePath(img_file),threshold=25)
        vtk.test.Testing.interact()
Esempio n. 17
0
  def __init__(self):
    self.i = 0 
    self.props_name = {} 

    self.table = vtk.vtkTable() 
    self.view  = vtk.vtkContextView() 
    self.view.GetRenderer().SetBackground(1.0, 1.0, 1.0);

    print "+Vtk_plot"
Esempio n. 18
0
    def testPythonItem(self):
        width = 400
        height = 400

        view = vtk.vtkContextView()
        renWin = view.GetRenderWindow()
        renWin.SetSize(width, height)

        area = vtk.vtkInteractiveArea()
        view.GetScene().AddItem(area)

        drawAreaBounds = vtk.vtkRectd(0.0, 0.0, 1.0, 1.0)

        vp = [0.05, 0.95, 0.05, 0.95]
        screenGeometry = vtk.vtkRecti(int(vp[0] * width),
                                      int(vp[2] * height),
                                      int((vp[1] - vp[0]) * width),
                                      int((vp[3] - vp[2]) * height))

        item = vtk.vtkPythonItem()
        item.SetPythonObject(CustomPythonItem(buildPolyData()))
        item.SetVisible(True)
        area.GetDrawAreaItem().AddItem(item)

        area.SetDrawAreaBounds(drawAreaBounds)
        area.SetGeometry(screenGeometry)
        area.SetFillViewport(False)
        area.SetShowGrid(False)

        axisLeft = area.GetAxis(vtk.vtkAxis.LEFT)
        axisRight = area.GetAxis(vtk.vtkAxis.RIGHT)
        axisBottom = area.GetAxis(vtk.vtkAxis.BOTTOM)
        axisTop = area.GetAxis(vtk.vtkAxis.TOP)
        axisTop.SetVisible(False)
        axisRight.SetVisible(False)
        axisLeft.SetVisible(False)
        axisBottom.SetVisible(False)
        axisTop.SetMargins(0, 0)
        axisRight.SetMargins(0, 0)
        axisLeft.SetMargins(0, 0)
        axisBottom.SetMargins(0, 0)

        renWin.Render()

        # Create a vtkTesting object
        rtTester = vtk.vtkTesting()
        rtTester.SetRenderWindow(renWin)

        for arg in sys.argv[1:]:
            rtTester.AddArgument(arg)

        # Perform the image comparison test and print out the result.
        result = rtTester.RegressionTest(0.0)

        if result == 0:
            raise Exception("TestPythonItem failed.")
Esempio n. 19
0
    def __init__(self):
        self.i = 0
        self.props_name = {}

        self.table = vtk.vtkTable()
        self.view = vtk.vtkContextView()
        self.view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
        self.view.GetRenderWindow().SetSize(600, 600)

        print "+Vtk_plot \'%s\'" % vtk.vtkVersion().GetVTKVersion()
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Update authentication key to use
        self.updateSecret(_PhylogeneticTree.authKey)

        # Create default pipeline (Only once for all the session)
        if not _PhylogeneticTree.view:
            # read in  a tree
            treeReader = vtk.vtkNewickTreeReader()
            treeReader.SetFileName(_PhylogeneticTree.treeFilePath)
            treeReader.Update()
            reader = treeReader.GetOutput()

            # read in  a table
            tableReader = vtk.vtkDelimitedTextReader()
            tableReader.SetFileName(_PhylogeneticTree.csvFilePath)
            tableReader.SetHaveHeaders(True)
            tableReader.DetectNumericColumnsOn()
            tableReader.Update()
            table = tableReader.GetOutput()

            # play with the heatmap vis
            treeHeatmapItem = vtk.vtkTreeHeatmapItem()
            treeHeatmapItem.SetTree(reader)
            treeHeatmapItem.SetTable(table)

            # setup the window
            view = vtk.vtkContextView()
            view.GetRenderer().SetBackground(1, 1, 1)
            view.GetRenderWindow().SetSize(800, 600)

            iren = view.GetInteractor()
            iren.SetRenderWindow(view.GetRenderWindow())

            transformItem = vtk.vtkContextTransform()
            transformItem.AddItem(treeHeatmapItem)
            transformItem.SetInteractive(1)

            view.GetScene().AddItem(transformItem)
            view.GetRenderWindow().SetMultiSamples(0)

            iren.Initialize()
            view.GetRenderWindow().Render()

            # VTK Web application specific
            _PhylogeneticTree.view = view.GetRenderWindow()
            self.Application.GetObjectIdMap().SetActiveObject(
                "VIEW", view.GetRenderWindow())
Esempio n. 21
0
    def __init__(self):
        self._rendererScene = vtk.vtkRenderer()
        self._rendererScene.SetBackground(self.COLOR_BG)

        self._renderWindowScene = vtk.vtkRenderWindow()
        self._renderWindowScene.AddRenderer(self._rendererScene)
        self._renderWindowInteractor = vtk.vtkRenderWindowInteractor()
        self._renderWindowInteractor.SetRenderWindow(self._renderWindowScene)
        #self._interactorStyle = vtk.vtkInteractorStyleUnicam()
        self._interactorStyle = self.KeyPressInteractorStyle()
        self._interactorStyle.SetCamera(self._rendererScene.GetActiveCamera())
        self._interactorStyle.SetRenderer(self._rendererScene)
        self._interactorStyle.SetRenderWindow(self._renderWindowScene)

        self._contextViewPlotCurv = vtk.vtkContextView()
        self._contextViewPlotCurv.GetRenderer().SetBackground(self.COLOR_BG_PLOT)

        self._contextInteractorStyleCurv = self.KeyPressContextInteractorStyle()
        self._contextInteractorStyleCurv.SetRenderWindow(self._contextViewPlotCurv.GetRenderWindow())
        
        self._chartXYCurv = vtk.vtkChartXY()
        self._contextViewPlotCurv.GetScene().AddItem(self._chartXYCurv)
        self._chartXYCurv.SetShowLegend(True)
        self._chartXYCurv.GetAxis(vtk.vtkAxis.LEFT).SetTitle("")
        self._chartXYCurv.GetAxis(vtk.vtkAxis.BOTTOM).SetTitle("")

        self._contextViewPlotTors = vtk.vtkContextView()
        self._contextViewPlotTors.GetRenderer().SetBackground(self.COLOR_BG_PLOT)

        self._contextInteractorStyleTors = self.KeyPressContextInteractorStyle()
        self._contextInteractorStyleTors.SetRenderWindow(self._contextViewPlotTors.GetRenderWindow())
        
        self._chartXYTors = vtk.vtkChartXY()
        self._contextViewPlotTors.GetScene().AddItem(self._chartXYTors)
        self._chartXYTors.SetShowLegend(True)
        self._chartXYTors.GetAxis(vtk.vtkAxis.LEFT).SetTitle("")
        self._chartXYTors.GetAxis(vtk.vtkAxis.BOTTOM).SetTitle("")

        self._textActor = vtk.vtkTextActor()
        self._textActor.GetTextProperty().SetColor(self.COLOR_LENGTH)

        self._addedBSpline = False
Esempio n. 22
0
    def __init__(self, measure_obj=None, parent=None):
        """
        Constructor
        """
        super(GraphWidget, self).__init__(parent=parent)

        #   parent
        self._parent = parent

        # self.frame = QtGui.QFrame()
        #
        # self.vl = QtGui.QVBoxLayout()
        self.view = vtk.vtkContextView()
        self.view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
        # self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
        #
        # self.vl.addWidget(self.vtkWidget)

        self.view.SetInteractor(self.GetRenderWindow().GetInteractor())
        self.SetRenderWindow(self.view.GetRenderWindow())

        # self.ren = vtk.vtkRenderer()
        # self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        # self.interactor = self.vtkWidget.GetRenderWindow().GetInteractor()

        # self.frame.setLayout(self.vl)
        # self.setCentralWidget(self.frame)

        self.xy_data = vtk.vtkTable()
        self.arrX = vtk.vtkFloatArray()
        self.arrX.SetName("X Axis")
        self.xy_data.AddColumn(self.arrX)

        self.arrY = vtk.vtkFloatArray()
        self.arrY.SetName("Y value")
        self.xy_data.AddColumn(self.arrY)

        numPoints = 20
        inc = 7.5 / (numPoints - 1)
        self.xy_data.SetNumberOfRows(numPoints)
        for i in range(numPoints):
            self.xy_data.SetValue(i, 0, i * inc)
            self.xy_data.SetValue(i, 1, i * inc)

        # self.view = vtk.vtkContextView()
        # self.view.GetRenderer().SetBackground(1.0, 0.0, 1.0)
        #
        self.chart = vtk.vtkChartXY()
        self.chart.GetAxis(0).SetGridVisible(False)
        self.chart.GetAxis(1).SetGridVisible(False)

        self.view.GetScene().AddItem(self.chart)
        self.line = self.chart.AddPlot(vtk.vtkChart.LINE)
        self.line.SetInputData(self.xy_data, 0, 1)
Esempio n. 23
0
    def initialize(self):
        global renderer, renderWindow, renderWindowInteractor, cone, mapper, actor

        # Bring used components
        self.registerVtkWebProtocol(protocols.vtkWebMouseHandler())
        self.registerVtkWebProtocol(protocols.vtkWebViewPort())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortImageDelivery())
        self.registerVtkWebProtocol(protocols.vtkWebViewPortGeometryDelivery())

        # Update authentication key to use
        self.updateSecret(_PhylogeneticTree.authKey)

        # Create default pipeline (Only once for all the session)
        if not _PhylogeneticTree.view:
            # read in  a tree
            treeReader = vtk.vtkNewickTreeReader()
            treeReader.SetFileName(_PhylogeneticTree.treeFilePath)
            treeReader.Update()
            reader = treeReader.GetOutput()

            # read in  a table
            tableReader = vtk.vtkDelimitedTextReader()
            tableReader.SetFileName(_PhylogeneticTree.csvFilePath)
            tableReader.SetHaveHeaders(True)
            tableReader.DetectNumericColumnsOn()
            tableReader.Update()
            table = tableReader.GetOutput()

            # play with the heatmap vis
            treeHeatmapItem = vtk.vtkTreeHeatmapItem()
            treeHeatmapItem.SetTree(reader);
            treeHeatmapItem.SetTable(table);

            # setup the window
            view = vtk.vtkContextView()
            view.GetRenderer().SetBackground(1,1,1)
            view.GetRenderWindow().SetSize(800,600)

            iren = view.GetInteractor()
            iren.SetRenderWindow(view.GetRenderWindow())

            transformItem = vtk.vtkContextTransform()
            transformItem.AddItem(treeHeatmapItem)
            transformItem.SetInteractive(1)

            view.GetScene().AddItem(transformItem)
            view.GetRenderWindow().SetMultiSamples(0)

            iren.Initialize()
            view.GetRenderWindow().Render()

            # VTK Web application specific
            _PhylogeneticTree.view = view.GetRenderWindow()
            self.Application.GetObjectIdMap().SetActiveObject("VIEW", view.GetRenderWindow())
    def generateParallelCoordinatesChart(self):
        input = self.inputModule().getOutput()
        ptData = input.GetPointData()
        narrays = ptData.GetNumberOfArrays()
        arrays = []
        # Create a table with some points in it...
        table = vtk.vtkTable()
        for iArray in range(narrays):
            table.AddColumn(ptData.GetArray(iArray))

        # Set up a 2D scene, add an XY chart to it
        view = vtk.vtkContextView()
        #        view.SetRenderer( self.renderer )
        #        view.SetRenderWindow( self.renderer.GetRenderWindow() )
        view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
        view.GetRenderWindow().SetSize(600, 300)

        chart = vtk.vtkChartParallelCoordinates()

        brush = vtk.vtkBrush()
        brush.SetColorF(0.1, 0.1, 0.1)
        chart.SetBackgroundBrush(brush)

        # Create a annotation link to access selection in parallel coordinates view
        annotationLink = vtk.vtkAnnotationLink()
        # If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010)
        # See vtkSelectionNode doc for field and content type enum values
        annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(
            1)  # Point
        annotationLink.GetCurrentSelection().GetNode(0).SetContentType(
            4)  # Indices
        # Connect the annotation link to the parallel coordinates representation
        chart.SetAnnotationLink(annotationLink)

        view.GetScene().AddItem(chart)

        chart.GetPlot(0).SetInput(table)

        def selectionCallback(caller, event):
            annSel = annotationLink.GetCurrentSelection()
            if annSel.GetNumberOfNodes() > 0:
                idxArr = annSel.GetNode(0).GetSelectionList()
                if idxArr.GetNumberOfTuples() > 0:
                    print VN.vtk_to_numpy(idxArr)

        # Set up callback to update 3d render window when selections are changed in
        #       parallel coordinates view
        annotationLink.AddObserver("AnnotationChangedEvent", selectionCallback)

        #        view.ResetCamera()
        #        view.Render()
        #        view.GetInteractor().Start()
        return view
Esempio n. 25
0
 def __init__(self, parent):
     super(VTK2d, self).__init__(parent)
     self.iren = QVTKRenderWindowInteractor()
     self.vl = QtWidgets.QHBoxLayout()
     self.vl.addWidget(self.iren)
     self.setLayout(self.vl)
     self.iren.Initialize()
     self.view = vtk.vtkContextView()
     self.chart_matrix = vtk.vtkChartMatrix()
     self.view.GetScene().AddItem(self.chart_matrix)
     self.ren = self.view.GetRenderer()
     self.iren.GetRenderWindow().AddRenderer(self.ren)
    def generateParallelCoordinatesChart( self ):
        input = self.inputModule().getOutput() 
        ptData = input.GetPointData()
        narrays = ptData.GetNumberOfArrays()
        arrays = []
        # Create a table with some points in it...
        table = vtk.vtkTable()
        for iArray in range( narrays ):
            table.AddColumn(  ptData.GetArray( iArray ) )                  
        
        # Set up a 2D scene, add an XY chart to it
        view = vtk.vtkContextView()
#        view.SetRenderer( self.renderer )    
#        view.SetRenderWindow( self.renderer.GetRenderWindow() )
        view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
        view.GetRenderWindow().SetSize(600,300)
        
        chart = vtk.vtkChartParallelCoordinates()
        
        brush = vtk.vtkBrush()
        brush.SetColorF (0.1,0.1,0.1)
        chart.SetBackgroundBrush(brush)
        
        # Create a annotation link to access selection in parallel coordinates view
        annotationLink = vtk.vtkAnnotationLink()
        # If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010)
        # See vtkSelectionNode doc for field and content type enum values
        annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(1)     # Point
        annotationLink.GetCurrentSelection().GetNode(0).SetContentType(4)   # Indices
        # Connect the annotation link to the parallel coordinates representation
        chart.SetAnnotationLink(annotationLink)
        
        view.GetScene().AddItem(chart)
                
        
        chart.GetPlot(0).SetInput(table)
        
        def selectionCallback(caller, event):
                annSel = annotationLink.GetCurrentSelection()
                if annSel.GetNumberOfNodes() > 0:
                        idxArr = annSel.GetNode(0).GetSelectionList()
                        if idxArr.GetNumberOfTuples() > 0:
                                print VN.vtk_to_numpy(idxArr)
        
        # Set up callback to update 3d render window when selections are changed in 
        #       parallel coordinates view
        annotationLink.AddObserver("AnnotationChangedEvent", selectionCallback)
                
#        view.ResetCamera()
#        view.Render()       
#        view.GetInteractor().Start()
        return view 
Esempio n. 27
0
def main():
    view = vtk.vtkContextView()
    table = vtk.vtkTable()
    arrMonth = vtk.vtkIntArray()
    arrMonth.SetName("Month")
    arr2008 = vtk.vtkIntArray()
    arr2008.SetName("2008")
    arr2009 = vtk.vtkIntArray()
    arr2009.SetName("2009")
    arr2010 = vtk.vtkIntArray()
    arr2010.SetName("2010")

    table.AddColumn(arrMonth)
    table.AddColumn(arr2008)
    table.AddColumn(arr2009)
    table.AddColumn(arr2010)

    table.SetNumberOfRows(12)
    for i in range(12):
        table.SetValue(i, 0, i + 1)
        table.SetValue(i, 1, data_2008[i])
        table.SetValue(i, 2, data_2009[i])
        table.SetValue(i, 3, data_2010[i])

    chart = vtk.vtkChartXY()

    line = chart.AddPlot(vtk.vtkChart.BAR)
    line.SetInputData(table, 0, 1)
    line.SetColor(0.0, 1.0, 0.0)

    line = chart.AddPlot(vtk.vtkChart.BAR)
    line.SetInputData(table, 0, 2)
    line.SetColor(1.0, 0.0, 0.0)

    line = chart.AddPlot(vtk.vtkChart.BAR)
    line.SetInputData(table, 0, 3)
    line.SetColor(0.0, 0.0, 1.0)

    view.GetScene().AddItem(chart)
    view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
    view.GetRenderWindow().SetSize(1200, 1000)
    view.GetRenderWindow().Render()

    winToImageFilter = vtk.vtkWindowToImageFilter()
    winToImageFilter.SetInput(view.GetRenderWindow())
    winToImageFilter.Update()

    writer = vtk.vtkPNGWriter()
    writer.SetFileName("./test.png")
    writer.SetInputData(winToImageFilter.GetOutput())
    writer.Write()
Esempio n. 28
0
def initialize(self, VTKWebApp, args):
    VTKWebApp.treeFilePath = args.tree
    VTKWebApp.csvFilePath = args.table

    # Create default pipeline (Only once for all the session)
    if not VTKWebApp.view:
        # read in  a tree
        treeReader = vtk.vtkNewickTreeReader()
        treeReader.SetFileName(VTKWebApp.treeFilePath)
        treeReader.Update()
        reader = treeReader.GetOutput()

        # read in  a table
        tableReader = vtk.vtkDelimitedTextReader()
        tableReader.SetFileName(VTKWebApp.csvFilePath)
        tableReader.SetHaveHeaders(1)
        tableReader.DetectNumericColumnsOn()
        tableReader.Update()
        table = tableReader.GetOutput()

        # play with the heatmap vis
        treeHeatmapItem = vtk.vtkTreeHeatmapItem()
        treeHeatmapItem.SetTree(reader)
        treeHeatmapItem.SetTable(table)

        # setup the window
        view = vtk.vtkContextView()
        view.GetRenderer().SetBackground(1, 1, 1)
        view.GetRenderWindow().SetSize(800, 600)

        iren = view.GetInteractor()
        iren.SetRenderWindow(view.GetRenderWindow())

        transformItem = vtk.vtkContextTransform()
        transformItem.AddItem(treeHeatmapItem)
        transformItem.SetInteractive(1)

        view.GetScene().AddItem(transformItem)
        view.GetRenderWindow().SetMultiSamples(0)

        iren.Initialize()
        view.GetRenderWindow().Render()

        # VTK Web application specific
        VTKWebApp.view = view.GetRenderWindow()
        self.Application.GetObjectIdMap().SetActiveObject("VIEW", view.GetRenderWindow())
Esempio n. 29
0
    def __init__(self, parent = None):
        super(E_VolumeRenderingWidget, self).__init__(parent)
        self.setMaximumWidth(300)

        self.mainLayout = QVBoxLayout()
        self.mainLayout.setSpacing(0)        
        self.setLayout(self.mainLayout)

        self.m_widget = QVTKRenderWindowInteractor();
        self.m_widget.setMaximumHeight(100)
        self.m_widget.AddObserver('MouseMoveEvent', self.onMouseMove)
        self.m_widget.AddObserver('LeftButtonPressEvent', self.onLeftDown, 1.0)
        self.m_widget.AddObserver('LeftButtonReleaseEvent', self.onLeftUp, -1.0)
        self.m_widget.hide()
        self.m_bClicked = False

        self.m_view = vtk.vtkContextView()
        self.m_histogramChart  = vtk.vtkChartXY()

        self.Initialize()
    def __init__(self, chart_frame):
        super(VTKChartWidget, self).__init__()
        vtk.vtkObject.GlobalWarningDisplayOff()

        self.line_colors = default_line_colors
        self.line_width = default_line_width
        self.line_types = default_line_types

        self._gui_callbacks = []

        self.chart_frame = chart_frame

        self.renderer = vtk.vtkRenderer()
        self.renderer.SetBackground(1.0, 1.0, 1.0)

        self.table = vtk.vtkTable()
        self.chart = vtk.vtkChartXY()
        self.chart_scene = vtk.vtkContextScene()
        self.chart_actor = vtk.vtkContextActor()
        self.chart_view = vtk.vtkContextView()

        self.chart_scene.AddItem(self.chart)
        self.chart_actor.SetScene(self.chart_scene)
        self.chart_view.SetScene(self.chart_scene)

        self.renderer.AddActor(self.chart_actor)
        self.chart_scene.SetRenderer(self.renderer)

        self.chart.SetShowLegend(True)
        legend = self.chart.GetLegend()
        legend.SetInline(False)
        legend.SetHorizontalAlignment(vtk.vtkChartLegend.RIGHT)
        legend.SetVerticalAlignment(vtk.vtkChartLegend.TOP)
        legend.SetLabelSize(20)
        title_prop = self.chart.GetTitleProperties()
        title_prop.SetFontSize(20)

        self.init_xy_data()
        self.set_up_view()
    def addPlot(
        self,
        _plotName,
        _style="Lines"
    ):  # called directly from Steppable; add a (possibly more than one) plot to a plot window

        self.plotWindowInterfaceMutex.lock()
        #        self.plotWindowMutex.lock()

        #        return
        #        print MODULENAME,'   addPlot():  _plotName= ',_plotName
        #        import pdb; pdb.set_trace()

        #        self.plotData[_plotName] = [array([],dtype=double),array([],dtype=double),False]  # 'array': from PyQt4.Qwt5.anynumpy import *

        self.chart = vtk.vtkChartXY()
        #        self.chart.GetAxis(vtk.vtkAxis.LEFT).SetLogScale(True)
        #        self.chart.GetAxis(vtk.vtkAxis.BOTTOM).SetLogScale(True)
        #        self.numCharts += 1
        self.plotData[_plotName] = [self.chart]

        self.view = vtk.vtkContextView()
        self.ren = self.view.GetRenderer()
        #        self.renWin = self.qvtkWidget.GetRenderWindow()
        self.renWin = self.pW.GetRenderWindow()
        self.renWin.AddRenderer(self.ren)

        # Create a table with some points in it
        self.table = vtk.vtkTable()

        self.arrX = vtk.vtkFloatArray()
        self.arrX.SetName("xarray")

        self.arrC = vtk.vtkFloatArray()
        self.arrC.SetName("yarray")

        numPoints = 5
        numPoints = 15
        inc = 7.5 / (numPoints - 1)

        #        for i in range(0,numPoints):
        #            self.arrX.InsertNextValue(i*inc)
        #            self.arrC.InsertNextValue(math.cos(i * inc) + 0.0)

        #        self.arrX.InsertNextValue(0.0)
        #        self.arrC.InsertNextValue(0.0)
        #        self.arrX.InsertNextValue(0.1)
        #        self.arrC.InsertNextValue(0.1)

        self.table.AddColumn(self.arrX)
        self.table.AddColumn(self.arrC)

        # Now add the line plots with appropriate colors
        self.line = self.chart.AddPlot(0)
        self.line.SetInput(self.table, 0, 1)
        self.line.SetColor(0, 0, 255, 255)
        self.line.SetWidth(1.0)

        self.view.GetRenderer().SetBackground([0.6, 0.6, 0.1])
        self.view.GetRenderer().SetBackground([1.0, 1.0, 1.0])
        self.view.GetScene().AddItem(self.chart)

        self.plotWindowInterfaceMutex.unlock()
Esempio n. 32
0
    def __init__(self, parent=None):
#        QtGui.QFrame.__init__(self, parent)
#
##        self.plotWidget = CartesianPlot()
#        self.plotWidget = PlotWidget()
#        
#        self.parentWidget = parent
#        layout = QtGui.QBoxLayout(QtGui.QBoxLayout.TopToBottom)
#        layout.addWidget(self.plotWidget)
#        self.setLayout(layout)
#        self.resize(400, 400)
#        self.setMinimumSize(200, 200) #needs to be defined to resize smaller than 400x400


        QtGui.QFrame.__init__(self, parent)
        self.qvtkWidget = QVTKRenderWindowInteractor(self)   # a QWidget
        self.parentWidget = parent
        
#        self.lineEdit = QtGui.QLineEdit()
        
#        self.__initCrossSectionActions()
#        self.cstb = self.initCrossSectionToolbar()        
        
        layout = QtGui.QBoxLayout(QtGui.QBoxLayout.TopToBottom)
#        layout.addWidget(self.cstb)
        layout.addWidget(self.qvtkWidget)
        self.setLayout(layout)
        
        self.qvtkWidget.Initialize()
        self.qvtkWidget.Start()
        
#        self.ren = vtk.vtkRenderer()
#        self.renWin = self.qvtkWidget.GetRenderWindow()
#        self.renWin.AddRenderer(self.ren)
#        self.resize(300, 300)


        self.chart = vtk.vtkChartXY()
        self.view = vtk.vtkContextView()
        self.ren = self.view.GetRenderer()
        self.renWin = self.qvtkWidget.GetRenderWindow()
        self.renWin.AddRenderer(self.ren)

        # Create a table with some points in it
        table = vtk.vtkTable()

        arrX = vtk.vtkFloatArray()
        arrX.SetName("X Axis")

        arrC = vtk.vtkFloatArray()
        arrC.SetName("Cosine")

        numPoints = 20
        inc = 7.5 / (numPoints - 1)

        for i in range(0,numPoints):
            arrX.InsertNextValue(i*inc)
            arrC.InsertNextValue(math.cos(i * inc) + 0.0)

        table.AddColumn(arrX)
        table.AddColumn(arrC)

        # Now add the line plots with appropriate colors
        line = self.chart.AddPlot(0)
        line.SetInput(table,0,1)
        line.SetColor(0,0,255,255)
        line.SetWidth(2.0)
Esempio n. 33
0
def initialize(self, VTKWebApp, args):
    # Create default pipeline (Only once for all the session)
    if not VTKWebApp.view:

        baseURL = args.baseURL
        # support for overriding the base URL
        scriptDir = os.path.dirname(os.path.realpath(__file__))
        configPath = scriptDir + "/baseURL.txt"
        if os.path.isfile(configPath):
            f = file(configPath, "r")
            baseURL = f.read().rstrip()
            f.close()

        # get our input data from romanesco
        r = requests.get(baseURL + args.tree1URI, verify=False)
        tree1JSON = r.json()
        tree1Str = tree1JSON["data"]
        r = requests.get(baseURL + args.tree2URI, verify=False)
        tree2JSON = r.json()
        tree2Str = tree2JSON["data"]
        r = requests.get(baseURL + args.tableURI, verify=False)
        tableJSON = r.json()
        tableStr = tableJSON["data"]

        # get the tree names (TODO: consider better ways to get this info)
        tree1LabelURI = args.tree1URI[0:args.tree1URI.find("romanesco")]
        r = requests.get(baseURL + tree1LabelURI, verify=False)
        tree1LabelJSON = r.json()
        tree1Label = tree1LabelJSON["name"]
        tree1Label = tree1Label[0:tree1Label.find(".")]

        tree2LabelURI = args.tree2URI[0:args.tree2URI.find("romanesco")]
        r = requests.get(baseURL + tree2LabelURI, verify=False)
        tree2LabelJSON = r.json()
        tree2Label = tree2LabelJSON["name"]
        tree2Label = tree2Label[0:tree2Label.find(".")]

        # convert our input data into deserialized VTK objects
        tree1Reader = vtk.vtkTreeReader()
        tree1Reader.ReadFromInputStringOn()
        tree1Reader.SetInputString(tree1Str, len(tree1Str))
        tree1Reader.Update()
        tree1 = tree1Reader.GetOutput()

        tree2Reader = vtk.vtkTreeReader()
        tree2Reader.ReadFromInputStringOn()
        tree2Reader.SetInputString(tree2Str, len(tree2Str))
        tree2Reader.Update()
        tree2 = tree2Reader.GetOutput()

        tableReader = vtk.vtkDelimitedTextReader()
        tableReader.ReadFromInputStringOn()
        tableReader.SetInputString(tableStr, len(tableStr))
        tableReader.SetHaveHeaders(True)
        tableReader.DetectNumericColumnsOn()
        tableReader.ForceDoubleOn()
        table = tableReader.GetOutput()
        tableReader.Update()

        # create our visualization item and load the data into it.
        tanglegram = vtk.vtkTanglegramItem()
        tanglegram.SetTree1(tree1)
        tanglegram.SetTree2(tree2)
        tanglegram.SetTable(table)
        tanglegram.SetTree1Label(tree1Label)
        tanglegram.SetTree2Label(tree2Label)
        tanglegram.SetCorrespondenceLineWidth(4.0)
        tanglegram.SetTreeLineWidth(2.0)

        # setup the window
        view = vtk.vtkContextView()
        view.GetRenderWindow().SetSize(int(args.width), int(args.height))
        view.GetRenderer().SetBackground(1, 1, 1)

        iren = view.GetInteractor()
        iren.SetRenderWindow(view.GetRenderWindow())

        transformItem = vtk.vtkContextTransform()
        transformItem.AddItem(tanglegram)
        transformItem.SetInteractive(1)

        view.GetScene().AddItem(transformItem)
        view.GetRenderWindow().SetMultiSamples(0)

        iren.Initialize()
        view.GetRenderWindow().Render()

        # VTK Web application specific
        VTKWebApp.view = view.GetRenderWindow()
        self.Application.GetObjectIdMap().SetActiveObject(
            "VIEW", view.GetRenderWindow())
Esempio n. 34
0
    def testLinePlot(self):
        "Test if colored scatter plots can be built with python"

        # Set up a 2D scene, add an XY chart to it
        view = vtk.vtkContextView()
        view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
        view.GetRenderWindow().SetSize(400, 300)

        chart = vtk.vtkChartXY()
        chart.SetShowLegend(True)
        view.GetScene().AddItem(chart)

        # Create a table with some points in it
        arrX = vtk.vtkFloatArray()
        arrX.SetName("XAxis")

        arrC = vtk.vtkFloatArray()
        arrC.SetName("Cosine")

        arrS = vtk.vtkFloatArray()
        arrS.SetName("Sine")

        arrS2 = vtk.vtkFloatArray()
        arrS2.SetName("Tan")

        numPoints = 40
        inc = 7.5 / (numPoints-1)

        for i in range(numPoints):
            arrX.InsertNextValue(i * inc)
            arrC.InsertNextValue(math.cos(i * inc) + 0.0)
            arrS.InsertNextValue(math.sin(i * inc) + 0.0)
            arrS2.InsertNextValue(math.tan(i * inc) + 0.5)

        table = vtk.vtkTable()
        table.AddColumn(arrX)
        table.AddColumn(arrC)
        table.AddColumn(arrS)
        table.AddColumn(arrS2)

        # Generate a black-to-red lookup table with fixed alpha
        lut = vtk.vtkLookupTable()
        lut.SetValueRange(0.2, 1.0)
        lut.SetSaturationRange(1, 1)
        lut.SetHueRange(0,0)
        lut.SetRampToLinear()
        lut.SetRange(-1,1)
        lut.SetAlpha(0.75)
        lut.Build()

        # Generate a black-to-blue lookup table with alpha range
        lut2 = vtk.vtkLookupTable()
        lut2.SetValueRange(0.2, 1.0)
        lut2.SetSaturationRange(1, 1)
        lut2.SetHueRange(0.6667, 0.6667)
        lut2.SetAlphaRange(0.4, 0.8)
        lut2.SetRampToLinear()
        lut2.SetRange(-1,1)
        lut2.Build()

        # Add multiple line plots, setting the colors etc
        points0 = chart.AddPlot(vtk.vtkChart.POINTS)
        points0.SetInputData(table, 0, 1)
        points0.SetColor(0, 0, 0, 255)
        points0.SetWidth(1.0)
        points0.SetMarkerStyle(vtk.vtkPlotPoints.CROSS)

        points1 = chart.AddPlot(vtk.vtkChart.POINTS)
        points1.SetInputData(table, 0, 2)
        points1.SetColor(0, 0, 0, 255)
        points1.SetMarkerStyle(vtk.vtkPlotPoints.DIAMOND)
        points1.SetScalarVisibility(1)
        points1.SetLookupTable(lut)
        points1.SelectColorArray(1)

        points2 = chart.AddPlot(vtk.vtkChart.POINTS)
        points2.SetInputData(table, 0, 3)
        points2.SetColor(0, 0, 0, 255)
        points2.ScalarVisibilityOn()
        points2.SetLookupTable(lut2)
        points2.SelectColorArray("Cosine")
        points2.SetWidth(4.0)

        view.GetRenderWindow().SetMultiSamples(0)
        view.GetRenderWindow().Render()

        img_file = "TestScatterPlotColors.png"
        vtk.test.Testing.compareImage(view.GetRenderWindow(),vtk.test.Testing.getAbsImagePath(img_file),threshold=25)
        vtk.test.Testing.interact()
Esempio n. 35
0
	def __init__(self, data_source, input_link=None, highlight_link=None):
		"""Parallel coordinates view constructor needs a valid DataSource plus
		and external annotation link (from the icicle view).
		"""

		self.ds = data_source

		self.input_link = None
		if input_link is not None:
			self.SetInputAnnotationLink(input_link)

		# Set up a 2D scene, add an XY chart to it
		# Relies on changes to VTK (drawimage branch) that allow DrawImage() scaling factor
		self.chartView = vtk.vtkContextView()
		self.chartView.GetRenderer().SetBackground(1.0, 1.0, 1.0)

		# vtkChart::
			# PAN 	
			# ZOOM 	
			# SELECT 	
		# vtkContextMouseEvent:
		# enum  	
		#  { NO_BUTTON = 0, LEFT_BUTTON = 1, MIDDLE_BUTTON = 2, RIGHT_BUTTON = 4 }
		
		self.chart = vtkvtg.vtkMyChartXY()
		# self.chart.SetMouseMoveSelectZoomButtons(2,1,4)
		self.chart.SetActionToButton(vtk.vtkChart.PAN, 2)
		self.chart.SetActionToButton(vtk.vtkChart.ZOOM, 4)
		self.chart.SetActionToButton(vtk.vtkChart.SELECT, 1)
		self.chartView.GetScene().AddItem(self.chart)

		self.axisView = vtk.vtkContextView()
		self.axisView.GetRenderer().SetBackground(1.0, 1.0, 1.0)

		self.ai = vtkvtg.vtkAxisImageItem()
		self.axisView.GetScene().AddItem(self.ai)
		# Create a BrBg7 lookup table
		self.lut = self.ds.GetDivergingLUT('BrBg')
		self.ai.SetAxisImagesLookupTable(self.lut)
		# Create a greyscale lookup table
		self.lutBW = self.ds.GetGrayscaleLUT('gray')
		self.ai.SetCenterImageLookupTable(self.lutBW)

		self.highlight_link = None
		if highlight_link is not None:
			self.SetHighlightAnnotationLink(highlight_link)
			# Set up callback to listen for changes in IcicleView selections
			self.highlight_link.AddObserver("AnnotationChangedEvent", self.HighlightSelectionCallback)

			# Set up annotation link which will carry indices to parallel coordinates chart
			# for highlighting outside selections (e.g. back from image_flow)
			# This needs to carry indices, while image_flow link outputs pedigree ids
			# so conversion happens in HighlightSelectionCallback
			self.highlight_link_idxs = vtk.vtkAnnotationLink()
			self.highlight_link_idxs.GetCurrentSelection().GetNode(0).SetFieldType(1)     # Point
			self.highlight_link_idxs.GetCurrentSelection().GetNode(0).SetContentType(4)   # 2 = PedigreeIds, 4 = Indices
			self.chart.SetHighlightLink(self.highlight_link_idxs)

		# Create a annotation link to access selection in parallel coordinates view
		self.link = vtk.vtkAnnotationLink()
		# If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010)
		# See vtkSelectionNode doc for field and content type enum values
		self.link.GetCurrentSelection().GetNode(0).SetFieldType(1)     # Point
		# The chart seems to force INDEX selection, so I'm using vtkConvertSelection below to get
		# out PedigreeIds...
		self.link.GetCurrentSelection().GetNode(0).SetContentType(4)   # 2 = PedigreeIds, 4 = Indices
		# Connect the annotation link to the parallel coordinates representation
		self.chart.SetAnnotationLink(self.link)

		# Set up callback for ID -> Pedigree ID conversion & copy to output link
		# self.link.AddObserver("AnnotationChangedEvent", self.PCoordsSelectionCallback)

		# Set up output annotation link which will carry pedigree ids to image flow view
		# Type and field will be set during conversion to pedigree ids in PCoordsSelectionCallback
		# self.output_link = vtk.vtkAnnotationLink()

		# self.chartView.ResetCamera()
		# self.chartView.Render()

		# Want to keep track of whether the node coming in on the input_link
		# is new or not
		self.input_link_idx = 0

		# TODO: Should check the menu to see which is checked so default is
		#   set by GUI
		self.SetColorByArray("None")
Esempio n. 36
0
def om_display_vtk(f,d = 0,n = 0):
    """
    This function displays a VTK::vtk file generated with OpenMEEG.
    Such a file defines a polydata, containing points and triangles of a single
    mesh. Most often a EEG helmet mesh and associated leadfield.
    """
    welcome = """Welcome\n\n
    Move the slider to see all sources (columns of the input matrix)\n
    Press 'r': To select points/cells.\n"""

    # This callback function does updates the mappers for where n is the slider value
    def CleanPickData(object, event):
        ren.RemoveActor(selactor)
        PickData(object, event, selactor, 0, view, text_init)

    def SelectSource(object, event): # object will be the slider2D
        slidervalue = int(round(object.GetRepresentation().GetValue()))
        mapper.GetInput().GetPointData().SetActiveScalars("Potentials-"+str(slidervalue))
        renWin.SetWindowName(renWin.GetWindowName()[0:(renWin.GetWindowName().find('-')+1)]+str(slidervalue))
        UpdateColorBar(colorBar, mapper)

    # A window with an interactor
    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(600, 600)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    iren.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick())
    # A picker (to pick points/cells)
    picker = vtk.vtkRenderedAreaPicker()
    iren.SetPicker(picker)
    # Read the input file
    reader = vtk.vtkPolyDataReader()
    reader.SetFileName(f); reader.Update()
    poly = reader.GetOutput()
    renWin.SetWindowName(f+' Potentials-'+str(n))
    # determine the number of sources
    nb_sources = 0
    for i in range(poly.GetPointData().GetNumberOfArrays()):
        if poly.GetPointData().GetGlobalIds('Potentials-'+str(i)):
            nb_sources += 1
    if nb_sources == 0: #the file doesn't provide potentials
        if not d.__class__ == int:
            assert(d.shape[0] == poly.GetNumberOfPoints())
            nb_sources = d.shape[1]
            pot = [vtk.vtkDoubleArray() for j in range(d.shape[1])]
            for j in range(d.shape[1]):
                pot[j].SetName('Potentials-'+str(j))
                for i in range(d.shape[0]):
                    pot[j].InsertNextValue(d[i,j])
                poly.GetPointData().AddArray(pot[j])
            poly.Update()
        if not poly.GetPointData().GetGlobalIds('Indices'):
            ind = vtk.vtkUnsignedIntArray()
            ind.SetName('Indices')
            for i in range(poly.GetNumberOfPoints()):
                ind.InsertNextValue(i)
            poly.GetPointData().AddArray(ind)

    poly.GetPointData().SetActiveScalars('Potentials-'+str(n))

    mapper   = vtk.vtkPolyDataMapper()
    colorBar = vtk.vtkScalarBarActor()
    actor    = vtk.vtkActor()
    ren      = vtk.vtkRenderer()
    mapper.SetInput(poly)
    mapper.SetScalarModeToUsePointData(); mapper.Update()
    actor.SetMapper(mapper)
    ren.AddActor(actor)
    if nb_sources:
        ren.AddActor2D(colorBar)
        UpdateColorBar(colorBar, mapper)
    renWin.AddRenderer(ren)
    renWin.Render()

    if nb_sources > 1:
        # Slider
        sliderWidget = vtk.vtkSliderWidget()
        slider = vtk.vtkSliderRepresentation2D(); slider.SetMaximumValue(nb_sources-1)
        slider.SetValue(n); slider.SetEndCapLength(0.01); slider.SetLabelFormat('%1.0f')
        slider.SetSliderWidth(0.05); slider.SetSliderLength(1./nb_sources)
        slider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedViewport()
        slider.GetPoint1Coordinate().SetValue(.0, 0.02)
        slider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedViewport()
        slider.GetPoint2Coordinate().SetValue(1., 0.02);
        sliderWidget.SetInteractor(iren); sliderWidget.SetRepresentation(slider);
        sliderWidget.SetAnimationModeToAnimate(); sliderWidget.EnabledOn();
        sliderWidget.AddObserver("InteractionEvent", SelectSource);
        # Selection
        selactor = vtk.vtkActor()
        view = vtk.vtkContextView(); view.GetRenderWindow().SetWindowName('Plot')
        view.GetRenderWindow().SetPosition(600, 0); view.GetRenderWindow().SetSize(600, 600)
        # Welcome text
        text_init = vtk.vtkTextActor()
        text_init.SetPosition(10, 300)
        text_init.SetInput(welcome)
        text_init.GetTextProperty().SetColor(1.0, 0.0, 0.0)
        view.GetRenderer().AddActor2D(text_init)
        view.GetInteractor().Initialize()
        iren.AddObserver(vtk.vtkCommand.EndPickEvent,CleanPickData)
    iren.Initialize()
    iren.Start()
Esempio n. 37
0
def initialize(self, VTKWebApp, args):
    # Create default pipeline (Only once for all the session)
    if not VTKWebApp.view:
        # create our visualization item
        treeHeatmapItem = vtk.vtkTreeHeatmapItem()

        # get our input data, read it into VTK format,
        # and load it into our visualization item.
        if args.treeName:
            r = requests.get(
                "%s/arborapi/projmgr/project/%s/PhyloTree/%s/phyloxml" % (args.baseURL, args.projectName, args.treeName))
            phyloxmlTree = r.text
            tree = vtk_arbor_utils.PhyloXMLToVTKTree(phyloxmlTree)
            treeHeatmapItem.SetTree(tree)
            if tree.GetVertexData().GetArray("property.differences"):
              treeHeatmapItem.GetDendrogram().SetColorArray("property.differences")
              treeHeatmapItem.GetDendrogram().SetLineWidth(2.0)

        if args.tableName:
            r = requests.get(
                "%s/arborapi/projmgr/project/%s/CharacterMatrix/%s/csv" % (args.baseURL, args.projectName, args.tableName))
            csvTable = r.text
            table = vtk_arbor_utils.CSVToVTKTable(csvTable)
            treeHeatmapItem.SetTable(table)

        # setup the window
        view = vtk.vtkContextView()
        view.GetRenderWindow().SetSize(int(args.width), int(args.height))
        view.GetRenderer().SetBackground(1,1,1)

        iren = view.GetInteractor()
        iren.SetRenderWindow(view.GetRenderWindow())

        transformItem = vtk.vtkContextTransform()
        transformItem.AddItem(treeHeatmapItem)
        transformItem.SetInteractive(1)

        view.GetScene().AddItem(transformItem)
        view.GetRenderWindow().SetMultiSamples(0)

        iren.Initialize()
        view.GetRenderWindow().Render()

        # adjust zoom so the item nicely fills the screen
        itemSize = [0, 0]
        treeHeatmapItem.GetSize(itemSize)

        itemSize.append(0)
        transformItem.GetTransform().MultiplyPoint(itemSize, itemSize)

        newWidth = view.GetScene().GetSceneWidth()
        newHeight = view.GetScene().GetSceneHeight()

        pageWidth = newWidth
        pageHeight = newHeight
        sx = pageWidth  / itemSize[0]
        sy = pageHeight / itemSize[1]
        if sy < sx:
           scale = sy;
        else:
           scale = sx;

        if scale > 1:
           scale = scale * 0.5
        else:
           scale = scale * 0.9

        transformItem.Scale(scale, scale)

        # center the item within the screen
        itemCenter = [0, 0]
        treeHeatmapItem.GetCenter(itemCenter)
        itemCenter.append(0)

        centerPt = vtk.vtkPoints2D()
        centerPt.InsertNextPoint(newWidth / 2.0, newHeight / 2.0)
        transformItem.GetTransform().InverseTransformPoints(centerPt, centerPt)
        sceneCenter = [0, 0]
        centerPt.GetPoint(0, sceneCenter)

        dx = -1 * (itemCenter[0] - sceneCenter[0])
        dy = -1 * (itemCenter[1] - sceneCenter[1])

        transformItem.Translate(dx, dy)

        # VTK Web application specific
        VTKWebApp.view = view.GetRenderWindow()
        self.Application.GetObjectIdMap().SetActiveObject("VIEW", view.GetRenderWindow())
Esempio n. 38
0
	def __init__(self, parent = None):
	
		# Number of slider divisions per integer value
		self.divs = 10

		# self.rot_method = 'alt_axis'
		self.rot_method = '111'
		# self.rot_method = 'simple'
		
		self.axis_rescale = False

		QtGui.QMainWindow.__init__(self, parent)
		self.ui = Ui_MainWindow()
		   
		# Set up a 2D scene, add an XY chart to it
		self.view = vtk.vtkContextView()
		self.view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
		
		self.ui.setupUi(self, self.view.GetRenderWindow())

		if self.rot_method == 'alt_axis':
			self.ui.comboBox.setCurrentIndex(0)
		elif self.rot_method == '111':
			self.ui.comboBox.setCurrentIndex(1)
		else:
			self.ui.comboBox.setCurrentIndex(2)
			
		style = vtk.vtkInteractorStyleRubberBand2D()
		self.view.GetInteractor().SetInteractorStyle(style)
		self.view.GetScene().SetInteractorStyle(style)
		# Need this additional command (plus above set style) for this class
		# self.view.SetInteractionModeTo2D()
		
		self.chart = vtk.vtkChartXY()
		self.chart.SetShowLegend(False)

		# Create a annotation link to access selection in parallel coordinates view
		annotationLink = vtk.vtkAnnotationLink()
		# If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010)
		# See vtkSelectionNode doc for field and content type enum values
		annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(1)     # Point
		annotationLink.GetCurrentSelection().GetNode(0).SetContentType(4)   # Indices
		# Connect the annotation link to the parallel coordinates representation
		self.chart.SetAnnotationLink(annotationLink)
		
		self.view.GetScene().AddItem(self.chart)		
		
		# Set up callback to update 3d render window when selections are changed in 
		#	parallel coordinates view
		annotationLink.AddObserver("AnnotationChangedEvent", self.selectionCallback)
						
		QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL("triggered()"), self.fileExit)
		QtCore.QObject.connect(self.ui.actionOpen, QtCore.SIGNAL("triggered()"), self.LoadData)
		QtCore.QObject.connect(self.ui.horizontalSlider, QtCore.SIGNAL("valueChanged(int)"), self.columnUpdate)
		QtCore.QObject.connect(self.ui.comboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.rotMethodChanged)
		
		self.LoadData()
		
		self.view.ResetCamera()
		self.ui.vtkWidget.GetRenderWindow().Render()
		self.view.GetInteractor().Start()
Esempio n. 39
0
    def testStackedPlot(self):
        "Test if stacked plots can be built with python"

        # Set up a 2D scene, add an XY chart to it
        view = vtk.vtkContextView()
        view.GetRenderer().SetBackground(1.0,1.0,1.0)
        view.GetRenderWindow().SetSize(400,300)
        chart = vtk.vtkChartXY()
        view.GetScene().AddItem(chart)

        # Create a table with some points in it
        table = vtk.vtkTable()

        arrMonthLabels = vtk.vtkStringArray()
        arrMonthPositions = vtk.vtkDoubleArray()

        arrMonth = vtk.vtkIntArray()
        arrMonth.SetName("Month")

        arrBooks = vtk.vtkIntArray()
        arrBooks.SetName("Books")

        arrNew = vtk.vtkIntArray()
        arrNew.SetName("New / Popular")

        arrPeriodical = vtk.vtkIntArray()
        arrPeriodical.SetName("Periodical")

        arrAudiobook = vtk.vtkIntArray()
        arrAudiobook.SetName("Audiobook")

        arrVideo = vtk.vtkIntArray()
        arrVideo.SetName("Video")

        numMonths = 12

        for i in range(0,numMonths):
            arrMonthLabels.InsertNextValue(month_labels[i])
            arrMonthPositions.InsertNextValue(float(i));

            arrMonth.InsertNextValue(i)
            arrBooks.InsertNextValue(book[i])
            arrNew.InsertNextValue(new_popular[i])
            arrPeriodical.InsertNextValue(periodical[i])
            arrAudiobook.InsertNextValue(audiobook[i])
            arrVideo.InsertNextValue(video[i])

        table.AddColumn(arrMonth)
        table.AddColumn(arrBooks)
        table.AddColumn(arrNew)
        table.AddColumn(arrPeriodical)
        table.AddColumn(arrAudiobook)
        table.AddColumn(arrVideo)

        # Now add the line plots with appropriate colors

        chart.GetAxis(1).SetTickLabels(arrMonthLabels)
        chart.GetAxis(1).SetTickPositions(arrMonthPositions)
        chart.GetAxis(1).SetMaximum(11)

        # Books
        line = chart.AddPlot(3)
        line.SetInput(table,0,1)
        line.SetColor(120,120,254,255)

        # New / Popular
        line = chart.AddPlot(3)
        line.SetInput(table,0,2)
        line.SetColor(254,118,118,255)

        # Periodical
        line = chart.AddPlot(3)
        line.SetInput(table,0,3)
        line.SetColor(170,170,254,255)

        # Audiobook
        line = chart.AddPlot(3)
        line.SetInput(table,0,4)
        line.SetColor(91,91,254,255)

        # Video
        line = chart.AddPlot(3)
        line.SetInput(table,0,5)
        line.SetColor(253,158,158,255)

        view.GetRenderWindow().SetMultiSamples(0)
        #view.GetRenderWindow().GetInteractor().Start()

        img_file = "TestStackedPlot.png"
        img_file2 = "TestStackedPlot0Hidden.png"
        vtk.test.Testing.compareImage(view.GetRenderWindow(),vtk.test.Testing.getAbsImagePath(img_file),threshold=25)
        vtk.test.Testing.interact()
        chart.GetPlot(0).SetVisible(False)
        vtk.test.Testing.compareImage(view.GetRenderWindow(),vtk.test.Testing.getAbsImagePath(img_file2),threshold=25)
        vtk.test.Testing.interact()
Esempio n. 40
0
def om_display_vtp(f, n = 0):
    """
    This function displays a VTK::vtp file generated with OpenMEEG.
    Such a file defines a polydata, containing points and triangles of several
    meshes which are labelled through a vtkAbstractArray (Strings) associated to
    the cells (mesh names).
    Results of the forward problem (or a cortical mapping) can be seen thanks to
    arrays associated to points and cells (respectively potentials and normals
    currents).
    """
    welcome = """Welcome\n\n
    Switch the button: To either see Potentials (on points) or Currents (on triangles)\n
    Move the slider to see all sources (columns of the input matrix)\n
    Press 'r': To select points/cells.\n"""

    # This callback function does updates the mappers for where n is the slider value
    def CleanPickData(object, event):
        for i in range(4):
            rens[i].RemoveActor(selactor)
        if buttonWidget.GetRepresentation().GetState():
            PickData(object, event, selactor, 1, view, text_init)
        else:
            PickData(object, event, selactor, 0, view, text_init)
    def SelectSource(object, event): # object will be the slider2D
        slidervalue = int(round(object.GetRepresentation().GetValue()))
        for i in range(4):
            mappers[i].GetInput().GetPointData().SetActiveScalars("Potentials-"+str(slidervalue))
            mappers[i].GetInput().GetCellData().SetActiveScalars("Currents-"+str(slidervalue))
            renWin.SetWindowName(renWin.GetWindowName()[0:(renWin.GetWindowName().find('-')+1)]+str(slidervalue))
            UpdateColorBar(colorBars[i], mappers[i])

    # This callback function does updates the Scalar Mode To Use
    def SelectMode(object, event):
        # object will be the buttonWidget
        for i in range(4):
            if (object.GetRepresentation().GetState()):
                mappers[i].SetScalarModeToUseCellData()
                renWin.SetWindowName(renWin.GetWindowName().replace('Potentials','Currents'))
            else:
                mappers[i].SetScalarModeToUsePointData()
                renWin.SetWindowName(renWin.GetWindowName().replace('Currents','Potentials'))
            UpdateColorBar(colorBars[i], mappers[i])

    # A window with an interactor
    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(600, 600)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    iren.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick())
    # A picker (to pick points/cells)
    picker = vtk.vtkRenderedAreaPicker()
    iren.SetPicker(picker)
    # Read the input file
    reader = vtk.vtkXMLPolyDataReader()
    reader.SetFileName(f); reader.Update()
    poly = reader.GetOutput()
    renWin.SetWindowName(f+' Potentials-'+str(n))
    # determine the number of sources
    nb_sources = 0
    for i in range(poly.GetPointData().GetNumberOfArrays()):
        if poly.GetPointData().GetGlobalIds('Potentials-'+str(i)):
            nb_sources += 1
    if n < nb_sources:
        poly.GetPointData().SetActiveScalars('Potentials-'+str(n))
        poly.GetCellData().SetActiveScalars('Currents-'+str(n))
    # Get the mesh names
    cell_labels = poly.GetCellData().GetAbstractArray(0)
    assert(cell_labels.GetName()=='Names')
    s = set(); nb_meshes = 0; cell_ids = list()
    for i in range(cell_labels.GetNumberOfValues()):
        s.add(cell_labels.GetValue(i))
        if len(s)>nb_meshes:
            # if a label is added, store the ID for the connectivity filter
            cell_ids.append(i)
            nb_meshes += 1
    # Number of meshes
    assert(nb_meshes<=4)
    # Multiple viewports: 4
    xmins = [0,.5,0,.5]; xmaxs = [0.5,1,0.5,1]; ymins = [0,0,.5,.5]; ymaxs = [0.5,0.5,1,1]

    mappers   = [vtk.vtkPolyDataMapper() for i in range(4)]
    colorBars = [vtk.vtkScalarBarActor() for i in range(4)]
    actors    = [vtk.vtkActor() for i in range(4)]
    rens      = [vtk.vtkRenderer() for i in range(4)]

    for i in range(4):
        rens[i].SetViewport(xmins[i],ymins[i],xmaxs[i],ymaxs[i]);
        # Display the meshes
        if (i < nb_meshes):
            # Create a connectivity filter based on cell seeded region (to display
            # only one mesh per viewport)
            conn = vtk.vtkPolyDataConnectivityFilter()
            conn.SetInput(poly)
            conn.SetExtractionModeToCellSeededRegions()
            conn.AddSeed(cell_ids[i]); conn.Update()
            actor_meshname = vtk.vtkTextActor();
            actor_meshname.SetInput(cell_labels.GetValue(cell_ids[i]));
            actor_meshname.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport();
            actor_meshname.SetPosition(0.5, 0.85); tprop = actor_meshname.GetTextProperty(); tprop.SetFontSize(30)
            tprop.SetFontFamilyToArial(); tprop.SetColor(1, 1, 1); tprop.SetJustificationToCentered()
            mappers[i].SetInputConnection(conn.GetOutputPort())
            mappers[i].SetScalarModeToUsePointData(); mappers[i].Update()
            if nb_sources:
                rens[i].AddActor2D(colorBars[i])
            actors[i].SetMapper(mappers[i])
            rens[i].AddActor2D(actor_meshname)
            rens[i].AddActor(actors[i])
            if (i == 0):
                cam = rens[i].GetActiveCamera()
                rens[i].ResetCamera()
        else:
            # Create a plane to cut
            plane = vtk.vtkPlane(); plane.SetOrigin(0,0,0); plane.SetNormal(1,0,0);
            # Create cutter
            extract = vtk.vtkExtractPolyDataGeometry(); extract.SetInput(poly)
            extract.SetImplicitFunction(plane); extract.ExtractBoundaryCellsOff()
            mappers[i].SetInputConnection(extract.GetOutputPort())
            mappers[i].SetScalarModeToUsePointData(); mappers[i].Update()
            # Create plane actor
            actors[i].SetMapper(mappers[i])
            rens[i].AddActor(actors[i])
        rens[i].SetActiveCamera(cam)
        if nb_sources:
            UpdateColorBar(colorBars[i], mappers[i])
        renWin.AddRenderer(rens[i])
        renWin.Render();

    if nb_sources > 1:
        # Slider
        sliderWidget = vtk.vtkSliderWidget()
        slider = vtk.vtkSliderRepresentation2D(); slider.SetMaximumValue(nb_sources-1)
        slider.SetValue(n); slider.SetEndCapLength(0.01); slider.SetLabelFormat('%1.0f')
        slider.SetSliderWidth(0.05); slider.SetSliderLength(1./nb_sources)
        slider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedViewport()
        slider.GetPoint1Coordinate().SetValue(.0 ,0.02)
        slider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedViewport()
        slider.GetPoint2Coordinate().SetValue(1. ,0.02);
        sliderWidget.SetInteractor(iren); sliderWidget.SetRepresentation(slider);
        sliderWidget.SetAnimationModeToAnimate(); sliderWidget.EnabledOn();
        sliderWidget.AddObserver("InteractionEvent", SelectSource);
    if not nb_sources == 0:
        # The button for choosing Potentials/Currents
        buttonWidget = vtk.vtkButtonWidget()
        button = vtk.vtkTexturedButtonRepresentation2D(); button.SetNumberOfStates(2)
        tex1r = vtk.vtkImageData(); tex2r = vtk.vtkImageData();
        prop  = vtk.vtkTextProperty(); prop.SetFontSize(24);
        prop.SetColor(1,0,0); prop.SetBold(2); prop.SetShadow(2); 
        str2im = vtk.vtkFreeTypeStringToImage()
        str2im.RenderString(prop,'Potentials',tex1r)
        str2im.RenderString(prop,'Currents',tex2r)
        button.SetButtonTexture(0, tex1r)
        button.SetButtonTexture(1, tex2r)
        buttonWidget.SetInteractor(iren);
        buttonWidget.SetRepresentation(button);
        button.SetPlaceFactor(1);
        button.PlaceWidget([0., 100, 50, 500, 0, 0]);
        buttonWidget.On()
        buttonWidget.AddObserver(vtk.vtkCommand.StateChangedEvent,SelectMode);
        # Selection
        selactor = vtk.vtkActor()
        view = vtk.vtkContextView(); view.GetRenderWindow().SetWindowName('Plot')
        view.GetRenderWindow().SetPosition(600, 0); view.GetRenderWindow().SetSize(600, 600)
        # Welcome text
        text_init = vtk.vtkTextActor()
        text_init.SetPosition(10, 300)
        text_init.SetInput(welcome)
        text_init.GetTextProperty().SetColor(1.0, 0.0, 0.0)
        view.GetRenderer().AddActor2D(text_init)
        view.GetInteractor().Initialize()
        iren.AddObserver(vtk.vtkCommand.EndPickEvent,CleanPickData)
    iren.Initialize()
    iren.Start()
def main():
    colors = vtk.vtkNamedColors()

    filename = get_program_parameters()

    # Create the reader for the data.
    print('Loading ', filename)
    reader = vtk.vtkUnstructuredGridReader()
    reader.SetFileName(filename)
    reader.Update()

    extractEdges = vtk.vtkExtractEdges()
    extractEdges.SetInputConnection(reader.GetOutputPort())

    legendValues = vtk.vtkVariantArray()
    it = reader.GetOutput().NewCellIterator()
    it.InitTraversal()
    while not it.IsDoneWithTraversal():
        cell = vtk.vtkGenericCell()
        it.GetCell(cell)
        cellName = vtk.vtkCellTypes.GetClassNameFromTypeId(cell.GetCellType())
        print(cellName, 'NumberOfPoints:', cell.GetNumberOfPoints(),
              'CellDimension:', cell.GetCellDimension())
        legendValues.InsertNextValue(cellName)
        it.GoToNextCell()

    # Tube the edges
    tubes = vtk.vtkTubeFilter()
    tubes.SetInputConnection(extractEdges.GetOutputPort())
    tubes.SetRadius(.05)
    tubes.SetNumberOfSides(21)

    edgeMapper = vtk.vtkPolyDataMapper()
    edgeMapper.SetInputConnection(tubes.GetOutputPort())
    edgeMapper.SetScalarRange(0, 26)

    edgeActor = vtk.vtkActor()
    edgeActor.SetMapper(edgeMapper)
    edgeActor.GetProperty().SetSpecular(0.6)
    edgeActor.GetProperty().SetSpecularPower(30)

    # Glyph the points
    sphere = vtk.vtkSphereSource()
    sphere.SetPhiResolution(21)
    sphere.SetThetaResolution(21)
    sphere.SetRadius(0.08)

    pointMapper = vtk.vtkGlyph3DMapper()
    pointMapper.SetInputConnection(reader.GetOutputPort())
    pointMapper.SetSourceConnection(sphere.GetOutputPort())
    pointMapper.ScalingOff()
    pointMapper.ScalarVisibilityOff()

    pointActor = vtk.vtkActor()
    pointActor.SetMapper(pointMapper)
    pointActor.GetProperty().SetDiffuseColor(colors.GetColor3d('Banana'))
    pointActor.GetProperty().SetSpecular(0.6)
    pointActor.GetProperty().SetSpecularColor(1.0, 1.0, 1.0)
    pointActor.GetProperty().SetSpecularPower(100)

    # Label the points
    labelMapper = vtk.vtkLabeledDataMapper()
    labelMapper.SetInputConnection(reader.GetOutputPort())
    labelActor = vtk.vtkActor2D()
    labelActor.SetMapper(labelMapper)

    # The geometry
    geometryShrink = vtk.vtkShrinkFilter()
    geometryShrink.SetInputConnection(reader.GetOutputPort())
    geometryShrink.SetShrinkFactor(0.8)

    # NOTE: We must copy the originalLut because the CategoricalLegend
    # needs an indexed lookup table, but the geometryMapper uses a
    # non-index lookup table
    categoricalLut = vtk.vtkLookupTable()
    originalLut = reader.GetOutput().GetCellData().GetScalars().GetLookupTable(
    )

    categoricalLut.DeepCopy(originalLut)
    categoricalLut.IndexedLookupOn()

    geometryMapper = vtk.vtkDataSetMapper()
    geometryMapper.SetInputConnection(geometryShrink.GetOutputPort())
    geometryMapper.SetScalarModeToUseCellData()
    geometryMapper.SetScalarRange(0, 11)

    geometryActor = vtk.vtkActor()
    geometryActor.SetMapper(geometryMapper)
    geometryActor.GetProperty().SetLineWidth(3)
    geometryActor.GetProperty().EdgeVisibilityOn()
    geometryActor.GetProperty().SetEdgeColor(0, 0, 0)

    # Legend
    for v in range(0, legendValues.GetNumberOfTuples()):
        categoricalLut.SetAnnotation(legendValues.GetValue(v),
                                     legendValues.GetValue(v).ToString())
    legend = vtk.vtkCategoryLegend()
    legend.SetScalarsToColors(categoricalLut)
    legend.SetValues(legendValues)
    legend.SetTitle('Cell Type')
    legend.GetBrush().SetColor(colors.GetColor4ub('Silver'))

    placeLegend = vtk.vtkContextTransform()
    placeLegend.AddItem(legend)
    placeLegend.Translate(640 - 20, 480 - 12 * 16)

    contextView = vtk.vtkContextView()
    contextView.GetScene().AddItem(placeLegend)

    renderer = contextView.GetRenderer()

    renderWindow = contextView.GetRenderWindow()

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(geometryActor)
    renderer.AddActor(labelActor)
    renderer.AddActor(edgeActor)
    renderer.AddActor(pointActor)
    renderer.SetBackground(colors.GetColor3d('SlateGray'))

    aCamera = vtk.vtkCamera()
    aCamera.Azimuth(-40.0)
    aCamera.Elevation(50.0)

    renderer.SetActiveCamera(aCamera)
    renderer.ResetCamera()

    renderWindow.SetSize(640, 480)
    renderWindow.SetWindowName('ReadLegacyUnstructuredGrid')
    renderWindow.Render()

    renderWindowInteractor.Start()
Esempio n. 42
0
	def __init__(self, parent = None):
	
		QtGui.QMainWindow.__init__(self, parent)
		self.ui = Ui_MainWindow()
		
		self.renWinList = []
		   
		# data_file = askopenfilename()
		data_file = '/Users/emonson/Data/Fodava/EMoGWDataSets/mnist1_5c_20100324.mat'
# 		self.openFilesDefaultPath = QtCore.QDir.homePath()
# 		data_file = QtGui.QFileDialog.getOpenFileName(self,
# 				"Load Saved Matlab File", 
# 				self.openFilesDefaultPath,
# 				"All Files (*);;Matlab Files (*.mat)")
		
		# DataSource loads .mat file and can generate data from it for other views
		self.ds = DataSource(str(data_file))
		
		# All view classes have access to an instance of that data source for internal queries
		# Note that the only view which will pull and display data right away is the icicle view
		#  the other views need to be able to initialize without any data and only pull and show
		#  upon the first AnnotationChanged event...
		
		# View #0 -- Icicle View
		# Set up a 2D scene, add an XY chart to it
		self.chartView = vtk.vtkContextView()
		self.chartView.GetRenderer().SetBackground(1.0, 1.0, 1.0)
		self.renWinList.append(self.chartView.GetRenderWindow())

		self.chart = vtkvtg.vtkMyChartXY()
		self.chartView.GetScene().AddItem(self.chart)

		# View #1 -- AxisImageView
		self.axisView = vtk.vtkContextView()
		self.axisView.GetRenderer().SetBackground(1.0, 1.0, 1.0)
		self.renWinList.append(self.axisView.GetRenderWindow())

		self.ai = vtkvtg.vtkAxisImageItem()
		self.axisView.GetScene().AddItem(self.ai)
		
		# Set up all the render windows in the GUI
		self.ui.setupUi(self, self.renWinList)
		
		# Now need to get all the interactors working properly
		# XY
		style0 = vtk.vtkInteractorStyleRubberBand2D()
		self.chartView.GetInteractor().SetInteractorStyle(style0)
		self.chartView.GetScene().SetInteractorStyle(style0)

		# Axis images
		style1 = vtk.vtkInteractorStyleRubberBand2D()
		self.axisView.GetInteractor().SetInteractorStyle(style1)
		self.axisView.GetScene().SetInteractorStyle(style1)

		# Set sizes for veritcal splitters
		self.ui.splitter.setSizes([200,400])		
		
		# Connect signals and slots
		QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL("triggered()"), self.fileExit)

		
		# CORE setting up chart and axis images
		test_id = 68
		self.table = self.ds.GetNodeOneScaleCoeffTable(test_id)
		
		line1 = vtkvtg.vtkMyPlotPoints()
		# line1.DebugOn()
		self.chart.AddPlot(line1)		# POINTS
		line1.SetInput(self.table, 0, 1)
		line1.SetMarkerStyle(2)
		line1.SetColor(0, 0, 0, 255)
		
		# Tooltip image stack will now be owned by the tooltip, so need to do that differently... 
		id_list = self.ds.PIN[test_id]
		image_stack = self.ds.GetProjectedImages(id_list)
		self.chart.SetTooltipImageStack(image_stack)
		self.chart.SetTooltipShowImage(True)
		# self.chart.SetTooltipImageScalingFactor(2.0)
		self.chart.SetTooltipImageTargetSize(40)
		
		axis_images = self.ds.GetNodeBasisImages(test_id)
		center_image = self.ds.GetNodeCenterImage(test_id)
		self.ai.SetAxisImagesHorizontal()
		self.ai.SetChartXY(self.chart)
		self.ai.SetChartXYView(self.chartView)
		self.ai.SetAxisImageStack(axis_images)
		self.ai.SetCenterImage(center_image)
		
		# Set up annotation link which will carry indices to parallel coordinates chart
		# for highlighting outside selections (e.g. back from image_flow)
		# This needs to carry indices, while image_flow link outputs pedigree ids
		# so conversion happens in HighlightSelectionCallback
# 		data_col_idxs = vtk.vtkAnnotationLink()
# 		data_col_idxs.GetCurrentSelection().GetNode(0).SetFieldType(1)     # Point
# 		data_col_idxs.GetCurrentSelection().GetNode(0).SetContentType(4)   # 2 = PedigreeIds, 4 = Indices
# 		self.chart.SetDataColumnsLink(data_col_idxs)
# 		self.ai.SetDataColumnsLink(data_col_idxs)

		# Create a annotation link to access selection in XY chart
		annotationLink = vtk.vtkAnnotationLink()
		annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(1)     # Point
		annotationLink.GetCurrentSelection().GetNode(0).SetContentType(4)   # Indices
		# Connect the annotation link to the parallel coordinates representation
		self.chart.SetAnnotationLink(annotationLink)
		self.chart.GetAnnotationLink().AddObserver("AnnotationChangedEvent", self.IcicleSelectionCallback)

		# Set up annotation link which will carry indices to parallel coordinates chart
		# for highlighting outside selections (e.g. back from image_flow)
		# This needs to carry indices, while image_flow link outputs pedigree ids
		# so conversion happens in HighlightSelectionCallback
		highlight_link_idxs = vtk.vtkAnnotationLink()
		highlight_link_idxs.GetCurrentSelection().GetNode(0).SetFieldType(1)     # Point
		highlight_link_idxs.GetCurrentSelection().GetNode(0).SetContentType(4)   # 2 = PedigreeIds, 4 = Indices
		self.chart.SetHighlightLink(highlight_link_idxs)
		
		# Fill selection link with dummy IDs
		id_array = N.array([0],dtype='int64')
		id_list = VN.numpy_to_vtkIdTypeArray(id_array, deep=True)
		highlight_link_idxs.GetCurrentSelection().GetNode(0).SetSelectionList(id_list)
		highlight_link_idxs.InvokeEvent("AnnotationChangedEvent")

# 		self.updater = vtk.vtkViewUpdater()
# 		self.updater.AddAnnotationLink(data_col_idxs)
# 		self.updater.AddView(self.axisView)
# 		self.updater.AddView(self.chartView)
		
# 		col_array = N.array([0,1],dtype='int64')
# 		col_vtk = VN.numpy_to_vtkIdTypeArray(col_array, deep=True)
# 		data_col_idxs.GetCurrentSelection().GetNode(0).SetSelectionList(col_vtk)
# 		data_col_idxs.InvokeEvent("AnnotationChangedEvent")
		
		self.chart.RecalculateBounds()

		# Only need to Start() interactor for one view
		# self.pc_class.GetView().GetInteractor().Start()
		# Shouldn't have to do this render...
		for rw in self.renWinList:
			rw.Render()
Esempio n. 43
0
        nprecs = solv_data[:, 2].copy()
        xtime = numpy_support.numpy_to_vtk(nxtime)
        xiters = numpy_support.numpy_to_vtk(nxiters)
        xprecs = numpy_support.numpy_to_vtk(nprecs)

        xtime.SetName('time')
        xiters.SetName('iterations')
        xprecs.SetName('precisions')

        table = vtk.vtkTable()
        table.AddColumn(xtime)
        table.AddColumn(xiters)
        table.AddColumn(xprecs)
        # table.Dump()

        tview_iter = vtk.vtkContextView()
        tview_prec = vtk.vtkContextView()

        chart_iter = vtk.vtkChartXY()
        chart_prec = vtk.vtkChartXY()
        tview_iter.GetScene().AddItem(chart_iter)
        tview_prec.GetScene().AddItem(chart_prec)
        iter_plot = chart_iter.AddPlot(vtk.vtkChart.LINE)
        iter_plot.SetLabel('Solver iterations')
        iter_plot.GetXAxis().SetTitle('time')
        iter_plot.GetYAxis().SetTitle('iterations')

        prec_plot = chart_prec.AddPlot(vtk.vtkChart.LINE)
        prec_plot.SetLabel('Solver precisions')
        prec_plot.GetXAxis().SetTitle('time')
        prec_plot.GetYAxis().SetTitle('precisions')
Esempio n. 44
0
    def testLinePlot(self):
        "Test if colored parallel coordinates plots can be built with python"

        # Set up a 2D scene, add a PC chart to it
        view = vtk.vtkContextView()
        view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
        view.GetRenderWindow().SetSize(600,300)

        chart = vtk.vtkChartParallelCoordinates()
        view.GetScene().AddItem(chart)

        # Create a table with some points in it
        arrX = vtk.vtkFloatArray()
        arrX.SetName("XAxis")

        arrC = vtk.vtkFloatArray()
        arrC.SetName("Cosine")

        arrS = vtk.vtkFloatArray()
        arrS.SetName("Sine")

        arrS2 = vtk.vtkFloatArray()
        arrS2.SetName("Tan")

        numPoints = 200
        inc = 7.5 / (numPoints-1)

        for i in range(numPoints):
            arrX.InsertNextValue(i * inc)
            arrC.InsertNextValue(math.cos(i * inc) + 0.0)
            arrS.InsertNextValue(math.sin(i * inc) + 0.0)
            arrS2.InsertNextValue(math.tan(i * inc) + 0.5)

        table = vtk.vtkTable()
        table.AddColumn(arrX)
        table.AddColumn(arrC)
        table.AddColumn(arrS)
        table.AddColumn(arrS2)

        # Create blue to gray to red lookup table
        lut = vtk.vtkLookupTable()
        lutNum = 256
        lut.SetNumberOfTableValues(lutNum)
        lut.Build()

        ctf = vtk.vtkColorTransferFunction()
        ctf.SetColorSpaceToDiverging()
        cl = []
        # Variant of Colorbrewer RdBu 5
        cl.append([float(cc)/255.0 for cc in [202, 0, 32]])
        cl.append([float(cc)/255.0 for cc in [244, 165, 130]])
        cl.append([float(cc)/255.0 for cc in [140, 140, 140]])
        cl.append([float(cc)/255.0 for cc in [146, 197, 222]])
        cl.append([float(cc)/255.0 for cc in [5, 113, 176]])
        vv = [float(xx)/float(len(cl)-1) for xx in range(len(cl))]
        vv.reverse()
        for pt,color in zip(vv,cl):
            ctf.AddRGBPoint(pt, color[0], color[1], color[2])

        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)

        lut.SetAlpha(0.25)
        lut.SetRange(-1, 1)

        chart.GetPlot(0).SetInputData(table)
        chart.GetPlot(0).SetScalarVisibility(1)
        chart.GetPlot(0).SetLookupTable(lut)
        chart.GetPlot(0).SelectColorArray("Cosine")

        view.GetRenderWindow().SetMultiSamples(0)
        view.GetRenderWindow().Render()

        img_file = "TestParallelCoordinatesColors.png"
        vtk.test.Testing.compareImage(view.GetRenderWindow(),vtk.test.Testing.getAbsImagePath(img_file),threshold=25)
        vtk.test.Testing.interact()
def generate_distance_plot():
    def add_spline(outline):
        outline['spline_params'] = sa.get_spline_params(outline['points'])[0]
        return outline

    bones = map(add_spline, lh.load_files('data/2D/registered-outline/2015-06-08'))
    class1bones = [ bone for bone in bones if bone['class'] == 2 ]
    class2bones = [ bone for bone in bones if bone['class'] == 3 ]
    class1outline = np.mean([sa.evaluate_spline(np.linspace(0, 1, 180, endpoint=False), s['spline_params']) for s in class1bones], axis=0)
    class2outline = np.mean([sa.evaluate_spline(np.linspace(0, 1, 180, endpoint=False), s['spline_params']) for s in class2bones], axis=0)
    total_mean = np.mean([sa.evaluate_spline(np.linspace(0, 1, 180, endpoint=False), s['spline_params']) for s in bones], axis=0)

    distances = np.linalg.norm(class1outline - class2outline, axis=1)
    angles = np.array([degrees(gh.cart2pol(ev[0], ev[1])[1]) for ev in total_mean])
    angles[angles[:] < 0] += 360

    limit_min, limit_max = get_axis_limits(distances)

    chart = vtk.vtkChartXY()
    chart.GetAxis(1).SetBehavior(vtk.vtkAxis.FIXED)
    chart.GetAxis(0).SetBehavior(vtk.vtkAxis.FIXED)
    chart.GetAxis(0).SetTitle('')
    chart.GetAxis(1).SetTitle('')
    chart.GetAxis(0).GetLabelProperties().SetFontSize(30)
    chart.GetAxis(1).GetLabelProperties().SetFontSize(30)
    chart.GetAxis(1).SetRange(0, 359)
    chart.GetAxis(0).SetRange(0, 1)
    chart_table = vtk.vtkTable()
    chart_angle_axis_array = vtk.vtkFloatArray()
    chart_angle_axis_array.SetName('Angle (degrees)')
    chart_metric_array = vtk.vtkFloatArray()
    chart_metric_array.SetName('Distance')
    chart_table.AddColumn(chart_angle_axis_array)
    chart_table.AddColumn(chart_metric_array)

    chart_line = chart.AddPlot(vtk.vtkChart.LINE)
    chart_line.SetColor(0, 0, 0, 255)
    chart_line.SetWidth(2)

    chart.GetAxis(0).SetGridVisible(False)
    chart.GetAxis(1).SetGridVisible(False)
    chart_line.SetWidth(5)

    chart_table.SetNumberOfRows(distances.shape[0])
    for i in range(distances.shape[0]):
        chart_table.SetValue(i, 0, angles[i])
        chart_table.SetValue(i, 1, distances[i])
    chart_line.SetInputData(chart_table, 0, 1)

    render_window = vtk.vtkRenderWindow()
    render_window.SetOffScreenRendering(1)
    render_window.SetSize(640, 360)

    tick_positions_x = vtk.vtkDoubleArray()
    tick_positions_y = vtk.vtkDoubleArray()
    for angle in [0, 90, 180, 270, 360]:
        tick_positions_x.InsertNextValue(angle)
    for height in [limit_min, floor(limit_max*100) / 100]:
        tick_positions_y.InsertNextValue(height)
    chart.GetAxis(0).SetRange(limit_min, limit_max)
    chart.GetAxis(0).SetCustomTickPositions(tick_positions_y)
    chart.GetAxis(1).SetRange(0, 360)
    chart.GetAxis(1).SetCustomTickPositions(tick_positions_x)
    chart.Update()

    graph_context = vtk.vtkContextView()
    graph_context.SetRenderWindow(render_window)

    graph_context.GetScene().AddItem(chart)

    exporter = vtk.vtkGL2PSExporter()
    exporter.SetRenderWindow(render_window)
    exporter.SetFileFormatToSVG()
    exporter.CompressOff()
    exporter.DrawBackgroundOff()
    exporter.SetFilePrefix(os.path.abspath('thesis/img/results/real/distances'))
    exporter.Write()

    render_window.Finalize()
Esempio n. 46
0
    },
    {
        # A blue triangle in [0, 0] - [0.5, 0.5]
        'poly':
        buildPolyDataLineStrips([[[0.1, 0.1, 0.0], [0.1, 0.4, 0.0],
                                  [0.4, 0.4, 0.0], [0.4, 0.2, 0.0],
                                  [0.2, 0.2, 0.0], [0.2, 0.3, 0.0],
                                  [0.3, 0.3, 0.0]]]),
        'color': [0, 0, 255, 255]
    }
]

width = 400
height = 400

view = vtk.vtkContextView()
renWin = view.GetRenderWindow()
renWin.SetSize(width, height)

area = vtk.vtkInteractiveArea()
view.GetScene().AddItem(area)

drawAreaBounds = vtk.vtkRectd(0.0, 0.0, 1.0, 1.0)

vp = [0.0500000007451, 0.949999988079, 0.259999990463, 0.860000014305]
screenGeometry = vtk.vtkRecti(int(vp[0] * width), int(vp[2] * height),
                              int((vp[1] - vp[0]) * width),
                              int((vp[3] - vp[2]) * height))

for obj in polyDataList:
    pd = obj['poly']
Esempio n. 47
0
    def testLinePlot(self):
        "Test if line plots can be built with python"

        # Set up a 2D scene, add an XY chart to it
        view = vtk.vtkContextView()
        view.GetRenderer().SetBackground(1.0,1.0,1.0)
        view.GetRenderWindow().SetSize(400,300)
        chart = vtk.vtkChartXY()
        view.GetScene().AddItem(chart)

        # Create a table with some points in it
        table = vtk.vtkTable()

        arrX = vtk.vtkFloatArray()
        arrX.SetName("X Axis")

        arrC = vtk.vtkFloatArray()
        arrC.SetName("Cosine")

        arrS = vtk.vtkFloatArray()
        arrS.SetName("Sine")

        arrS2 = vtk.vtkFloatArray()
        arrS2.SetName("Sine2")

        numPoints = 69
        inc = 7.5 / (numPoints - 1)

        for i in range(0,numPoints):
            arrX.InsertNextValue(i*inc)
            arrC.InsertNextValue(math.cos(i * inc) + 0.0)
            arrS.InsertNextValue(math.sin(i * inc) + 0.0)
            arrS2.InsertNextValue(math.sin(i * inc) + 0.5)

        table.AddColumn(arrX)
        table.AddColumn(arrC)
        table.AddColumn(arrS)
        table.AddColumn(arrS2)

        # Now add the line plots with appropriate colors
        line = chart.AddPlot(0)
        line.SetInput(table,0,1)
        line.SetColor(0,255,0,255)
        line.SetWidth(1.0)

        line = chart.AddPlot(0)
        line.SetInput(table,0,2)
        line.SetColor(255,0,0,255);
        line.SetWidth(5.0)

        line = chart.AddPlot(0)
        line.SetInput(table,0,3)
        line.SetColor(0,0,255,255);
        line.SetWidth(4.0)

        view.GetRenderWindow().SetMultiSamples(0)
	view.GetRenderWindow().Render()

        img_file = "TestLinePlot.png"
        vtk.test.Testing.compareImage(view.GetRenderWindow(),vtk.test.Testing.getAbsImagePath(img_file),threshold=25)
        vtk.test.Testing.interact()
Esempio n. 48
0
    def testStackedPlot(self):
        "Test if stacked plots can be built with python"

        # Set up a 2D scene, add an XY chart to it
        view = vtk.vtkContextView()
        view.GetRenderer().SetBackground(1.0,1.0,1.0)
        view.GetRenderWindow().SetSize(400,300)
        chart = vtk.vtkChartXY()
        view.GetScene().AddItem(chart)

        # Create a table with some data in it
        table = vtk.vtkTable()

        arrMonthLabels = vtk.vtkStringArray()
        arrMonthPositions = vtk.vtkDoubleArray()

        arrMonth = vtk.vtkIntArray()
        arrMonth.SetName("Month")

        arrBooks = vtk.vtkIntArray()
        arrBooks.SetName("Books")

        arrNew = vtk.vtkIntArray()
        arrNew.SetName("New / Popular")

        arrPeriodical = vtk.vtkIntArray()
        arrPeriodical.SetName("Periodical")

        arrAudiobook = vtk.vtkIntArray()
        arrAudiobook.SetName("Audiobook")

        arrVideo = vtk.vtkIntArray()
        arrVideo.SetName("Video")

        numMonths = 12

        for i in range(0,numMonths):
            arrMonthLabels.InsertNextValue(month_labels[i])
            arrMonthPositions.InsertNextValue(float(i))

            arrMonth.InsertNextValue(i)
            arrBooks.InsertNextValue(book[i])
            arrNew.InsertNextValue(new_popular[i])
            arrPeriodical.InsertNextValue(periodical[i])
            arrAudiobook.InsertNextValue(audiobook[i])
            arrVideo.InsertNextValue(video[i])

        table.AddColumn(arrMonth)
        table.AddColumn(arrBooks)
        table.AddColumn(arrNew)
        table.AddColumn(arrPeriodical)
        table.AddColumn(arrAudiobook)
        table.AddColumn(arrVideo)

        # Set up the X Labels
        chart.GetAxis(1).SetCustomTickPositions(arrMonthPositions, arrMonthLabels)
        chart.GetAxis(1).SetMaximum(11)
        chart.GetAxis(1).SetBehavior(vtk.vtkAxis.FIXED)

        chart.SetShowLegend(True)

        # Create the stacked plot
        stack = chart.AddPlot(3)
        stack.SetUseIndexForXSeries(True)
        stack.SetInputData(table)
        stack.SetInputArray(1,"Books")
        stack.SetInputArray(2,"New / Popular")
        stack.SetInputArray(3,"Periodical")
        stack.SetInputArray(4,"Audiobook")
        stack.SetInputArray(5,"Video")

        # Set up a nice color series
        colorSeries = vtk.vtkColorSeries()
        colorSeries.SetColorScheme(2)
        stack.SetColorSeries(colorSeries)

        view.GetRenderWindow().SetMultiSamples(0)
        view.GetRenderWindow().Render()

        img_file = "TestStackedPlot.png"
        vtk.test.Testing.compareImage(view.GetRenderWindow(),
                                      vtk.test.Testing.getAbsImagePath(img_file),
                                      threshold=25)
        vtk.test.Testing.interact()
        'color': [0, 0, 255],
        'lineWidth': 1.5,
        'stippleType': vtk.vtkPen.DASH_DOT_LINE
    }),
    buildSpiralPolyDataItem({
        'vp': [0.5, 1.0, 0.0, 0.5],
        'color': [255, 0, 255],
        'lineWidth': 0.5,
        'stippleType': vtk.vtkPen.SOLID_LINE
    })
]

width = 400
height = 400

view = vtk.vtkContextView()
renWin = view.GetRenderWindow()
renWin.SetSize(width, height)

area = vtk.vtkInteractiveArea()
view.GetScene().AddItem(area)

drawAreaBounds = vtk.vtkRectd(0.0, 0.0, 1.0, 1.0)

vp = [0.0, 1.0, 0.0, 1.0]
screenGeometry = vtk.vtkRecti(int(vp[0] * width),
                              int(vp[2] * height),
                              int((vp[1] - vp[0]) * width),
                              int((vp[3] - vp[2]) * height))

for item in polyDataItemList:
Esempio n. 50
0
def initialize(self, VTKWebApp, args):
    dataid = args.id
    treedata = getDBdata(dataid)
    VTKWebApp.tree = treedata["tree"]
    VTKWebApp.table = dataid+ ".csv"

    # Create default pipeline (Only once for all the session)
    if not VTKWebApp.view:
        treeHeatmapItem = vtk.vtkTreeHeatmapItem()

        # read in  a tree
        treeReader = vtk.vtkNewickTreeReader()
        treeReader.SetReadFromInputString(1)
        treeReader.SetInputString(VTKWebApp.tree)
        treeReader.Update()
        tree = treeReader.GetOutput()
        treeHeatmapItem.SetTree(tree)

        if (VTKWebApp.table != "none" and os.path.isfile(VTKWebApp.table)):
          # read in  a table
          print("read table"+ VTKWebApp.table)
          tableReader = vtk.vtkDelimitedTextReader()
          tableReader.SetFileName(VTKWebApp.table)
          tableReader.SetHaveHeaders(1)
          tableReader.DetectNumericColumnsOn()
          tableReader.Update()
          table = tableReader.GetOutput()
          if (table):
              treeHeatmapItem.SetTable(table)


        # setup the window
        view = vtk.vtkContextView()
        view.GetRenderer().SetBackground(1,1,1)
        view.GetRenderWindow().SetSize(800,600)

        iren = view.GetInteractor()
        iren.SetRenderWindow(view.GetRenderWindow())

        transformItem = vtk.vtkContextTransform()
        transformItem.AddItem(treeHeatmapItem)
        transformItem.SetInteractive(1)

        view.GetScene().AddItem(transformItem)
        view.GetRenderWindow().SetMultiSamples(0)

        iren.Initialize()
        view.GetRenderWindow().Render()

        # adjust zoom so the item nicely fills the screen
        itemSize = [0, 0]
        treeHeatmapItem.GetSize(itemSize)

        itemSize.append(0)
        transformItem.GetTransform().MultiplyPoint(itemSize, itemSize)

        newWidth = view.GetScene().GetSceneWidth()
        newHeight = view.GetScene().GetSceneHeight()

        pageWidth = newWidth
        pageHeight = newHeight
        sx = pageWidth  / itemSize[0]
        sy = pageHeight / itemSize[1]
        if sy < sx:
           scale = sy;
        else:
           scale = sx;

        if scale > 1:
           scale = scale * 0.5
        else:
           scale = scale * 0.9

        transformItem.Scale(scale, scale)

        # center the item within the screen
        itemCenter = [0, 0]
        treeHeatmapItem.GetCenter(itemCenter)
        itemCenter.append(0)

        centerPt = vtk.vtkPoints2D()
        centerPt.InsertNextPoint(newWidth / 2.0, newHeight / 2.0)
        transformItem.GetTransform().InverseTransformPoints(centerPt, centerPt)
        sceneCenter = [0, 0]
        centerPt.GetPoint(0, sceneCenter)

        dx = -1 * (itemCenter[0] - sceneCenter[0])
        dy = -1 * (itemCenter[1] - sceneCenter[1])

        transformItem.Translate(dx, dy)

        # VTK Web application specific
        VTKWebApp.view = view.GetRenderWindow()
        self.Application.GetObjectIdMap().SetActiveObject("VIEW", view.GetRenderWindow())
Esempio n. 51
0
	def __init__(self, parent = None):
	
		QtGui.QMainWindow.__init__(self, parent)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		   
		# Set up a 2D scene (later we'll add a pcoords chart to it)
		self.view = vtk.vtkContextView()
		# self.view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
		
		# // QVTKWidget *widget = new QVTKWidget;
		# // vtkContextView *view = vtkContextView::New();
		# // view->SetInteractor(widget->GetInteractor());
		# // widget->SetRenderWindow(view->GetRenderWindow());

		# Necessary for RenderView types
		self.view.SetInteractor(self.ui.vtkWidget.GetInteractor())
		self.ui.vtkWidget.SetRenderWindow(self.view.GetRenderWindow())

		data_file = '/Users/emonson/Data/Fodava/EMoGWDataSets/mnist12_1k_20101119.mat'
		
		# DataSource loads .mat file and can generate data from it for other views
		ds = DataSource(data_file)

		# Testing my custom chart class which has image hover tooltips
		chart = vtkvtg.vtkMyChartXY()
		chart.SetActionToButton(vtk.vtkChart.PAN, 2)
		chart.SetActionToButton(vtk.vtkChart.ZOOM, 4)
		chart.SetActionToButton(vtk.vtkChart.SELECT, 1)
		self.view.GetScene().AddItem(chart)
		
		# Create a annotation link to access selection in parallel coordinates view
		annotationLink = vtk.vtkAnnotationLink()
		# If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010)
		# See vtkSelectionNode doc for field and content type enum values
		annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(1)     # Point
		annotationLink.GetCurrentSelection().GetNode(0).SetContentType(4)   # Indices
		# Connect the annotation link to the parallel coordinates representation
		chart.SetAnnotationLink(annotationLink)
		
		test_id = 3
		table = ds.GetNodeOneScaleCoeffTable(test_id)
		
		chart.ClearPlots()
		
		line1 = vtkvtg.vtkMyPlotPoints()
		chart.AddPlot(line1)		# POINTS
		line1.SetInput(table, 0, 1)
		line1.SetMarkerStyle(2)
		line1.SetColor(0, 0, 0, 255)
		
		# Tooltip image stack will now be owned by the tooltip, so need to do that differently... 
		id_list = ds.PointsInNet[test_id]
		image_stack = ds.GetProjectedImages(id_list)
		chart.SetTooltipImageStack(image_stack)
		chart.SetTooltipShowImage(True)
		# chart.SetTooltipImageScalingFactor(2.0)
		chart.SetTooltipImageTargetSize(40)
		
		# Set up annotation link which will carry indices to parallel coordinates chart
		# for highlighting outside selections (e.g. back from image_flow)
		# This needs to carry indices, while image_flow link outputs pedigree ids
		# so conversion happens in HighlightSelectionCallback
		highlight_link_idxs = vtk.vtkAnnotationLink()
		highlight_link_idxs.GetCurrentSelection().GetNode(0).SetFieldType(1)     # Point
		highlight_link_idxs.GetCurrentSelection().GetNode(0).SetContentType(4)   # 2 = PedigreeIds, 4 = Indices
		chart.SetHighlightLink(highlight_link_idxs)
		
		# Finally render the scene and compare the image to a reference image
		# view.GetRenderWindow().SetMultiSamples(0)
		
		annotationLink.AddObserver("AnnotationChangedEvent", self.selectionCallback)
		
		# view.ResetCamera()
		# view.Render()
		
		# Fill selection link with dummy IDs
		id_array = N.array([0],dtype='int64')
		id_list = VN.numpy_to_vtkIdTypeArray(id_array)
		highlight_link_idxs.GetCurrentSelection().GetNode(0).SetSelectionList(id_list)
		highlight_link_idxs.InvokeEvent("AnnotationChangedEvent")
		
		# Set up annotation link which will carry indices to parallel coordinates chart
		# for highlighting outside selections (e.g. back from image_flow)
		# This needs to carry indices, while image_flow link outputs pedigree ids
		# so conversion happens in HighlightSelectionCallback
		data_col_idxs = vtk.vtkAnnotationLink()
		data_col_idxs.GetCurrentSelection().GetNode(0).SetFieldType(1)     # Point
		data_col_idxs.GetCurrentSelection().GetNode(0).SetContentType(4)   # 2 = PedigreeIds, 4 = Indices
		chart.SetDataColumnsLink(data_col_idxs)
		# Fill selection link with dummy IDs
		col_array = N.array([1,2],dtype='int64')
		col_list = VN.numpy_to_vtkIdTypeArray(col_array)
		data_col_idxs.GetCurrentSelection().GetNode(0).SetSelectionList(col_list)
		data_col_idxs.InvokeEvent("AnnotationChangedEvent")
		
		# Start interaction event loop
		self.ui.vtkWidget.show()
Esempio n. 52
0
    def testStackedPlot(self):
        "Test if stacked plots can be built with python"

        # Set up a 2D scene, add an XY chart to it
        view = vtk.vtkContextView()
        view.GetRenderer().SetBackground(1.0,1.0,1.0)
        view.GetRenderWindow().SetSize(400,300)
        chart = vtk.vtkChartXY()
        view.GetScene().AddItem(chart)

        # Create a table with some data in it
        table = vtk.vtkTable()

        arrMonthLabels = vtk.vtkStringArray()
        arrMonthPositions = vtk.vtkDoubleArray()

        arrMonth = vtk.vtkIntArray()
        arrMonth.SetName("Month")

        arrBooks = vtk.vtkIntArray()
        arrBooks.SetName("Books")

        arrNew = vtk.vtkIntArray()
        arrNew.SetName("New / Popular")

        arrPeriodical = vtk.vtkIntArray()
        arrPeriodical.SetName("Periodical")

        arrAudiobook = vtk.vtkIntArray()
        arrAudiobook.SetName("Audiobook")

        arrVideo = vtk.vtkIntArray()
        arrVideo.SetName("Video")

        numMonths = 12

        for i in range(0,numMonths):
            arrMonthLabels.InsertNextValue(month_labels[i])
            arrMonthPositions.InsertNextValue(float(i))

            arrMonth.InsertNextValue(i)
            arrBooks.InsertNextValue(book[i])
            arrNew.InsertNextValue(new_popular[i])
            arrPeriodical.InsertNextValue(periodical[i])
            arrAudiobook.InsertNextValue(audiobook[i])
            arrVideo.InsertNextValue(video[i])

        table.AddColumn(arrMonth)
        table.AddColumn(arrBooks)
        table.AddColumn(arrNew)
        table.AddColumn(arrPeriodical)
        table.AddColumn(arrAudiobook)
        table.AddColumn(arrVideo)

        # Set up the X Labels
        chart.GetAxis(1).SetCustomTickPositions(arrMonthPositions, arrMonthLabels)
        chart.GetAxis(1).SetMaximum(11)
        chart.GetAxis(1).SetBehavior(vtk.vtkAxis.FIXED)

        # Create the stacked plot
        stack = chart.AddPlot(3)
        stack.SetUseIndexForXSeries(True)
        stack.SetInputData(table)
        stack.SetInputArray(1,"Books")
        stack.SetInputArray(2,"New / Popular")
        stack.SetInputArray(3,"Periodical")
        stack.SetInputArray(4,"Audiobook")
        stack.SetInputArray(5,"Video")

        # Set up a nice color series
        colorSeries = vtk.vtkColorSeries()
        colorSeries.SetColorScheme(2)
        stack.SetColorSeries(colorSeries)

        view.GetRenderWindow().SetMultiSamples(0)
        view.GetRenderWindow().Render()

        img_file = "TestStackedPlot.png"
        vtk.test.Testing.compareImage(view.GetRenderWindow(),
                                      vtk.test.Testing.getAbsImagePath(img_file),
                                      threshold=25)
        vtk.test.Testing.interact()
Esempio n. 53
0
    nprecs = solv_data[:, 2].copy()
    xtime = numpy_support.numpy_to_vtk(nxtime)
    xiters = numpy_support.numpy_to_vtk(nxiters)
    xprecs = numpy_support.numpy_to_vtk(nprecs)

    xtime.SetName('time')
    xiters.SetName('iterations')
    xprecs.SetName('precisions')

    table = vtk.vtkTable()
    table.AddColumn(xtime)
    table.AddColumn(xiters)
    table.AddColumn(xprecs)
    #table.Dump()

    tview_iter = vtk.vtkContextView()
    tview_prec = vtk.vtkContextView()

    chart_iter = vtk.vtkChartXY()
    chart_prec = vtk.vtkChartXY()
    tview_iter.GetScene().AddItem(chart_iter)
    tview_prec.GetScene().AddItem(chart_prec)
    iter_plot = chart_iter.AddPlot(vtk.vtkChart.LINE)
    iter_plot.SetLabel('Solver iterations')
    iter_plot.GetXAxis().SetTitle('time')
    iter_plot.GetYAxis().SetTitle('iterations')

    prec_plot = chart_prec.AddPlot(vtk.vtkChart.LINE)
    prec_plot.SetLabel('Solver precisions')
    prec_plot.GetXAxis().SetTitle('time')
    prec_plot.GetYAxis().SetTitle('precisions')
    def testLinePlot(self):
        "Test if colored scatter plots can be built with python"

        # Set up a 2D scene, add an XY chart to it
        view = vtk.vtkContextView()
        view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
        view.GetRenderWindow().SetSize(400, 300)

        chart = vtk.vtkChartXY()
        chart.SetShowLegend(True)
        view.GetScene().AddItem(chart)

        # Create a table with some points in it
        arrX = vtk.vtkFloatArray()
        arrX.SetName("XAxis")

        arrC = vtk.vtkFloatArray()
        arrC.SetName("Cosine")

        arrS = vtk.vtkFloatArray()
        arrS.SetName("Sine")

        arrS2 = vtk.vtkFloatArray()
        arrS2.SetName("Tan")

        numPoints = 40
        inc = 7.5 / (numPoints-1)

        for i in range(numPoints):
            arrX.InsertNextValue(i * inc)
            arrC.InsertNextValue(math.cos(i * inc) + 0.0)
            arrS.InsertNextValue(math.sin(i * inc) + 0.0)
            arrS2.InsertNextValue(math.tan(i * inc) + 0.5)

        table = vtk.vtkTable()
        table.AddColumn(arrX)
        table.AddColumn(arrC)
        table.AddColumn(arrS)
        table.AddColumn(arrS2)

        # Generate a black-to-red lookup table with fixed alpha
        lut = vtk.vtkLookupTable()
        lut.SetValueRange(0.2, 1.0)
        lut.SetSaturationRange(1, 1)
        lut.SetHueRange(0,0)
        lut.SetRampToLinear()
        lut.SetRange(-1,1)
        lut.SetAlpha(0.75)
        lut.Build()

        # Generate a black-to-blue lookup table with alpha range
        lut2 = vtk.vtkLookupTable()
        lut2.SetValueRange(0.2, 1.0)
        lut2.SetSaturationRange(1, 1)
        lut2.SetHueRange(0.6667, 0.6667)
        lut2.SetAlphaRange(0.4, 0.8)
        lut2.SetRampToLinear()
        lut2.SetRange(-1,1)
        lut2.Build()

        # Add multiple line plots, setting the colors etc
        points0 = chart.AddPlot(vtk.vtkChart.POINTS)
        points0.SetInputData(table, 0, 1)
        points0.SetColor(0, 0, 0, 255)
        points0.SetWidth(1.0)
        points0.SetMarkerStyle(vtk.vtkPlotPoints.CROSS)

        points1 = chart.AddPlot(vtk.vtkChart.POINTS)
        points1.SetInputData(table, 0, 2)
        points1.SetColor(0, 0, 0, 255)
        points1.SetMarkerStyle(vtk.vtkPlotPoints.DIAMOND)
        points1.SetScalarVisibility(1)
        points1.SetLookupTable(lut)
        points1.SelectColorArray(1)

        points2 = chart.AddPlot(vtk.vtkChart.POINTS)
        points2.SetInputData(table, 0, 3)
        points2.SetColor(0, 0, 0, 255)
        points2.ScalarVisibilityOn()
        points2.SetLookupTable(lut2)
        points2.SelectColorArray("Cosine")
        points2.SetWidth(4.0)

        view.GetRenderWindow().SetMultiSamples(0)
        view.GetRenderWindow().Render()

        img_file = "TestScatterPlotColors.png"
        vtk.test.Testing.compareImage(view.GetRenderWindow(),vtk.test.Testing.getAbsImagePath(img_file),threshold=25)
        vtk.test.Testing.interact()
Esempio n. 55
0
  def setup(self):
    ScriptedLoadableModuleWidget.setup(self)

    self.imageData = None

    # Add a Qt timer, that fires every X ms (16.7ms = 60 FPS, 33ms = 30FPS)
    # Connect the timeout() signal of the qt timer to a function in this class that you will write
    self.timer = qt.QTimer()
    self.timer.connect('timeout()', self.OnTimerTimeout)
    self.timer.start(16.7)

    self.table = vtk.vtkTable()
    self.chart = vtk.vtkChartXY()
    self.line = self.chart.AddPlot(0)
    #self.chart.RecalculateBounds() 
    self.view = vtk.vtkContextView()

    # Instantiate and connect widgets ...
    #
    # Parameters Area
    #
    parametersCollapsibleButton = ctk.ctkCollapsibleButton()
    parametersCollapsibleButton.text = "Parameters"
    self.layout.addWidget(parametersCollapsibleButton)

    # Layout within the dummy collapsible button
    parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton)

    #
    # transform first peak selector
    #
    self.firstPeakTransformSelector = slicer.qMRMLNodeComboBox()
    self.firstPeakTransformSelector.nodeTypes = ["vtkMRMLLinearTransformNode"]
    self.firstPeakTransformSelector.selectNodeUponCreation = True
    self.firstPeakTransformSelector.addEnabled = False
    self.firstPeakTransformSelector.removeEnabled = False
    self.firstPeakTransformSelector.noneEnabled = True
    self.firstPeakTransformSelector.showHidden = False
    self.firstPeakTransformSelector.showChildNodeTypes = False
    self.firstPeakTransformSelector.setMRMLScene( slicer.mrmlScene )
    self.firstPeakTransformSelector.setToolTip( "Pick the transform for the first peak." )
    parametersFormLayout.addRow("First Peak Transform: ", self.firstPeakTransformSelector)
    
    #
    # transform second peak selector
    #
    self.secondPeakTransformSelector = slicer.qMRMLNodeComboBox()
    self.secondPeakTransformSelector.nodeTypes = ["vtkMRMLLinearTransformNode"]
    self.secondPeakTransformSelector.selectNodeUponCreation = True
    self.secondPeakTransformSelector.addEnabled = False
    self.secondPeakTransformSelector.removeEnabled = False
    self.secondPeakTransformSelector.noneEnabled = True
    self.secondPeakTransformSelector.showHidden = False
    self.secondPeakTransformSelector.showChildNodeTypes = False
    self.secondPeakTransformSelector.setMRMLScene( slicer.mrmlScene )
    self.secondPeakTransformSelector.setToolTip( "Pick the transform for the second peak." )
    parametersFormLayout.addRow("Second Peak Transform: ", self.secondPeakTransformSelector)
    
    #
    # transform third peak selector
    #
    self.thirdPeakTransformSelector = slicer.qMRMLNodeComboBox()
    self.thirdPeakTransformSelector.nodeTypes = ["vtkMRMLLinearTransformNode"]
    self.thirdPeakTransformSelector.selectNodeUponCreation = True
    self.thirdPeakTransformSelector.addEnabled = False
    self.thirdPeakTransformSelector.removeEnabled = False
    self.thirdPeakTransformSelector.noneEnabled = True
    self.thirdPeakTransformSelector.showHidden = False
    self.thirdPeakTransformSelector.showChildNodeTypes = False
    self.thirdPeakTransformSelector.setMRMLScene( slicer.mrmlScene )
    self.thirdPeakTransformSelector.setToolTip( "Pick the transform for the third peak." )
    parametersFormLayout.addRow("Third Peak Transform: ", self.thirdPeakTransformSelector)

    #
    # volume selector
    #
    self.imageSelector = slicer.qMRMLNodeComboBox()
    self.imageSelector.nodeTypes = ["vtkMRMLScalarVolumeNode"]
    self.imageSelector.selectNodeUponCreation = True
    self.imageSelector.addEnabled = False
    self.imageSelector.removeEnabled = False
    self.imageSelector.noneEnabled = True
    self.imageSelector.showHidden = False
    self.imageSelector.showChildNodeTypes = False
    self.imageSelector.setMRMLScene( slicer.mrmlScene )
    self.imageSelector.setToolTip( "Pick the image that is the oscilloscope signal." )
    parametersFormLayout.addRow("Signal Volume: ", self.imageSelector)

    #
    # threshold value
    #
    #self.imageThresholdSliderWidget = ctk.ctkSliderWidget()
    #self.imageThresholdSliderWidget.singleStep = 0.1
    #self.imageThresholdSliderWidget.minimum = -100
    #self.imageThresholdSliderWidget.maximum = 100
    #self.imageThresholdSliderWidget.value = 0.5
    #self.imageThresholdSliderWidget.setToolTip("Set threshold value for computing the output image. Voxels that have intensities lower than this value will set to zero.")
    #parametersFormLayout.addRow("Image threshold", self.imageThresholdSliderWidget)

    #
    # check box to trigger taking screen shots for later use in tutorials
    #
    #self.enableScreenshotsFlagCheckBox = qt.QCheckBox()
    #self.enableScreenshotsFlagCheckBox.checked = 0
    #self.enableScreenshotsFlagCheckBox.setToolTip("If checked, take screen shots for tutorials. Use Save Data to write them to disk.")
    #parametersFormLayout.addRow("Enable Screenshots", self.enableScreenshotsFlagCheckBox)

    #
    # Apply Button
    #
    self.runButton = qt.QPushButton("Run")
    self.runButton.toolTip = "Start visualization."
    self.runButton.enabled = True
    parametersFormLayout.addRow(self.runButton)

    # connections
    self.runButton.connect('clicked(bool)', self.onRunButton)
    self.imageSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.OnInputVolumeSelect)
    self.firstPeakTransformSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onFirstPeakSelect)
    self.secondPeakTransformSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSecondPeakSelect)
    self.thirdPeakTransformSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onThirdPeakSelect)
    #self.outputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)

    # Add vertical spacer
    self.layout.addStretch(1)