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)
def set_multiple_xy_data(self, x_array, y_arrays_list, title): if not title: title = 'N/A' self.chart.SetTitle(title) self.chart.ClearPlots() self.chart.GetAxis(0).SetTitle('') self.chart.GetAxis(1).SetTitle(x_array.GetName()) self.table = vtk.vtkTable() self.table.AddColumn(x_array) for var_index, y_array in enumerate(y_arrays_list): self.table.AddColumn(y_array) line = self.chart.AddPlot(vtk.vtkChart.LINE) line.SetInputData(self.table, 0, var_index + 1) _index = var_index % len(self.line_colors) color_rgb = self.line_colors[_index] line.SetColor(*color_rgb) line.GetPen().SetLineType(self.line_types[_index]) line.SetWidth(self.line_width[_index]) self.set_active() self.render()
def testMultiTreeOutputs(self): outputs = vtk.vtkStringArray() outputs.SetNumberOfComponents(1) outputs.SetNumberOfTuples(2) outputs.SetValue(0, "tree1") outputs.SetValue(1, "tree2") rcal = vtk.vtkRCalculatorFilter() rcal.SetRscript("library(ape)\n\ tree1 = read.tree(text=\"" + tree_data + "\")\n\ tree2 = read.tree(text=\"" + tree_data + "\")\n") rcal.GetTrees(outputs) input = vtk.vtkTable() rcal.SetInputData(input) rcal.Update() compo = rcal.GetOutput() tree1 = compo.GetPieceAsDataObject(0) self.assertTrue(tree1.IsA('vtkTree')) tree2 = compo.GetPieceAsDataObject(1) self.assertTrue(tree2.IsA('vtkTree'))
def set_xy_data(self, x_array, y_array, title): if not title: title = 'N/A' self.chart.SetTitle(title) self.chart.ClearPlots() self.table = vtk.vtkTable() self.table.AddColumn(x_array) self.table.AddColumn(y_array) line = self.chart.AddPlot(vtk.vtkChart.LINE) self.chart.GetAxis(1).SetTitle(x_array.GetName()) self.chart.GetAxis(0).SetTitle(y_array.GetName()) line.SetInputData(self.table, 0, 1) line.SetColor(*self.line_colors[0]) line.SetWidth(self.line_width[0]) line.GetPen().SetLineType(self.line_types[0]) self.set_active() self.render()
def testTableInputOutput(self): rcal = vtk.vtkRCalculatorFilter() rcal.SetRscript("output = input\n") rcal.PutTable('input') rcal.GetTable('output') value = 1 array = vtk.vtkDoubleArray() array.SetNumberOfComponents(1) array.SetNumberOfTuples(4) array.SetName('test') for i in range(0, 4): array.SetValue(i, value) value += 1 input = vtk.vtkTable() input.AddColumn(array) rcal.SetInputData(input) rcal.Update() t1 = rcal.GetOutput().GetColumnByName('test') value = 1 for i in range(0, t1.GetNumberOfTuples()): self.assertEqual(value, t1.GetValue(i)) value += 1
def addPlot(chart, reader, name): data1 = reader.GetOutput() coords = vtk.vtkFloatArray() coords.SetName("Coords") for i in range(data1.GetNumberOfPoints()): x, y, z = data1.GetPoint(i) coords.InsertNextValue(y) table = vtk.vtkTable() table.AddColumn(coords) table.AddColumn(data1.GetPointData().GetArray("S_g")) table.AddColumn(data1.GetPointData().GetArray("S_n")) table.AddColumn(data1.GetPointData().GetArray("S_w")) line1 = chart.AddPlot(vtk.vtkChart.LINE) line1.SetInput(table, 0, 1) line1.SetMarkerStyle(vtk.vtkPlotPoints.CROSS) line2 = chart.AddPlot(vtk.vtkChart.LINE) line2.SetInput(table, 0, 2) line2.SetMarkerStyle(vtk.vtkPlotPoints.PLUS) line3 = chart.AddPlot(vtk.vtkChart.LINE) line3.SetInput(table, 0, 3) line3.SetMarkerStyle(vtk.vtkPlotPoints.CIRCLE)
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()
def testTableInputOutput(self): rcal = vtk.vtkRCalculatorFilter() rcal.SetRscript("output = input\n"); rcal.PutTable('input') rcal.GetTable('output') value = 1 array = vtk.vtkDoubleArray() array.SetNumberOfComponents(1) array.SetNumberOfTuples(4) array.SetName('test') for i in range(0, 4): array.SetValue(i, value) value += 1 input = vtk.vtkTable() input.AddColumn(array) rcal.SetInputData(input) rcal.Update() t1 = rcal.GetOutput().GetColumnByName('test') value = 1 for i in range(0, t1.GetNumberOfTuples()): self.assertEqual(value, t1.GetValue(i)) value += 1
def make_spreadsheet(column_names, table): # column_names is a list of strings # table is a 2D numpy.ndarray # returns a vtkTable object that stores the table content # Create a vtkTable to store the output. rows = table.shape[0] if (table.shape[1] != len(column_names)): print('Warning: table number of columns differs from number of ' 'column names') return from vtk import vtkTable, vtkFloatArray vtk_table = vtkTable() for (column, name) in enumerate(column_names): array = vtkFloatArray() array.SetName(name) array.SetNumberOfComponents(1) array.SetNumberOfTuples(rows) vtk_table.AddColumn(array) for row in range(0, rows): array.InsertValue(row, table[row, column]) return vtk_table
def RequestData(self, request, inInfo, outInfo): """Used by pipeline to get output data object for given time step. Constructs the ``vtkImageData`` """ # Get output: output = vtk.vtkImageData.GetData(outInfo) # Get requested time index i = _helpers.getRequestedTime(self, outInfo) if self.NeedToRead(): self._ReadUpFront() # Generate the data object n1, n2, n3 = self.__extent dx, dy, dz = self.__spacing ox, oy, oz = self.__origin output.SetDimensions(n1 + 1, n2 + 1, n3 + 1) output.SetSpacing(dx, dy, dz) output.SetOrigin(ox, oy, oz) # Use table generater and convert because its easy: table = vtk.vtkTable() interface.dataFrameToTable(self._GetRawData(idx=i), table) # now get arrays from table and add to point data of pdo for i in range(table.GetNumberOfColumns()): output.GetCellData().AddArray(table.GetColumn(i)) del (table) return 1
def RequestData(self, request, inInfo, outInfo): """Used by pipeline to get data for current timestep and populate the output data object. This assumes that ``self._get_raw_data()`` will return a dataset ready for PVGeo's ``interface.points_to_poly_data()``. """ # Get output: output = self.GetOutputData(outInfo, 0) # Get requested time index i = _helpers.get_requested_time(self, outInfo) if self.need_to_read(): self._read_up_front() # Get the data which has already been loaded data = self._get_raw_data(idx=i) # Generate the data object nx, ny, nz = self.get_extent(dim=True) dx, dy, dz = self.__spacing ox, oy, oz = self.__origin output.SetDimensions(nx+1, ny+1, nz+1) output.SetSpacing(dx, dy, dz) output.SetOrigin(ox, oy, oz) # Use table generater and convert because its easy: table = vtk.vtkTable() interface.data_frame_to_table(data, table) # now get arrays from table and add to cell data of output for i in range(table.GetNumberOfColumns()): output.GetCellData().AddArray(table.GetColumn(i)) del(table) return 1 # NOTE: ALWAYS return 1 on pipeline methods
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()
def addPlot(chart, reader, name): data1 = reader.GetOutput() coords = vtk.vtkFloatArray() coords.SetName("Coords") for i in range(data1.GetNumberOfPoints()): x,y,z = data1.GetPoint(i) coords.InsertNextValue(y) table = vtk.vtkTable() table.AddColumn(coords) table.AddColumn(data1.GetPointData().GetArray("S_g")) table.AddColumn(data1.GetPointData().GetArray("S_n")) table.AddColumn(data1.GetPointData().GetArray("S_w")) line1 = chart.AddPlot(vtk.vtkChart.LINE) line1.SetInput(table, 0, 1) line1.SetMarkerStyle(vtk.vtkPlotPoints.CROSS) line2 = chart.AddPlot(vtk.vtkChart.LINE) line2.SetInput(table, 0, 2) line2.SetMarkerStyle(vtk.vtkPlotPoints.PLUS) line3 = chart.AddPlot(vtk.vtkChart.LINE) line3.SetInput(table, 0, 3) line3.SetMarkerStyle(vtk.vtkPlotPoints.CIRCLE)
def make_spreadsheet(column_names, table): # column_names is a list of strings # table is a 2D numpy.ndarray # returns a vtkTable object that stores the table content require_internal_mode() # Create a vtkTable to store the output. rows = table.shape[0] if (table.shape[1] != len(column_names)): print('Warning: table number of columns differs from number of ' 'column names') return from vtk import vtkTable, vtkFloatArray vtk_table = vtkTable() for (column, name) in enumerate(column_names): array = vtkFloatArray() array.SetName(name) array.SetNumberOfComponents(1) array.SetNumberOfTuples(rows) vtk_table.AddColumn(array) for row in range(0, rows): array.InsertValue(row, table[row, column]) return vtk_table
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 main(): # Use the specified filename output_filename = get_program_parameters() # Construct an empty table table = vtk.vtkTable() for i in range(0, 3): col = vtk.vtkVariantArray() col_name = "column-" + str(i) col.SetName(col_name) col.InsertNextValue(vtk.vtkVariant(0.0)) col.InsertNextValue(vtk.vtkVariant(0.0)) col.InsertNextValue(vtk.vtkVariant(0.0)) table.AddColumn(col) # Fill the table with values counter = 0 for r in range(0, table.GetNumberOfRows()): for c in range(table.GetNumberOfColumns()): table.SetValue(r, c, vtk.vtkVariant(counter)) counter += 1 writer = vtk.vtkDelimitedTextWriter() writer.SetFileName(output_filename) writer.SetInputData(table) writer.Write()
def RequestData(self, request, inInfo, outInfo): """Used by pipeline to get output data object for given time step. Constructs the ``vtkImageData`` """ # Get output: output = vtk.vtkImageData.GetData(outInfo) # Get requested time index i = _helpers.get_requested_time(self, outInfo) if self.need_to_read(): self._read_up_front() # Generate the data object n1, n2, n3 = self.__extent dx, dy, dz = self.__spacing ox, oy, oz = self.__origin output.SetDimensions(n1 + 1, n2 + 1, n3 + 1) output.SetSpacing(dx, dy, dz) output.SetOrigin(ox, oy, oz) # Use table generator and convert because its easy: table = vtk.vtkTable() df = self._get_raw_data(idx=i) # Replace all masked values with NaN df.replace(self.__mask, np.nan, inplace=True) interface.data_frame_to_table(df, table) # now get arrays from table and add to point data of pdo for i in range(table.GetNumberOfColumns()): output.GetCellData().AddArray(table.GetColumn(i)) del (table) return 1
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()
def testMultiTableOutputs(self): outputs = vtk.vtkStringArray() outputs.SetNumberOfComponents(1) outputs.SetNumberOfTuples(3) outputs.SetValue(0, "output1") outputs.SetValue(1, "output2") outputs.SetValue(2, "output3") rcal = vtk.vtkRCalculatorFilter() rcal.SetRscript("output1 = list(test=c(1,2,3,4))\n\ output2 = list(test=c(5,6,7,8))\n\ output3 = list(test=c(9,10,11,12))\n") rcal.GetTables(outputs) input = vtk.vtkTable() rcal.SetInputData(input) rcal.Update() t1 = rcal.GetOutput().GetPieceAsDataObject(0).GetColumnByName('test') value = 1 for i in range(0, t1.GetNumberOfTuples()): self.assertEqual(value, t1.GetValue(i)) value += 1 t2 = rcal.GetOutput().GetPieceAsDataObject(1).GetColumnByName('test') for i in range(0, t2.GetNumberOfTuples()): self.assertEqual(value, t2.GetValue(i)) value += 1 t3 = rcal.GetOutput().GetPieceAsDataObject(2).GetColumnByName('test') for i in range(0, t3.GetNumberOfTuples()): self.assertEqual(value, t3.GetValue(i)) value += 1
def calcPCA(xarray, yarray): ''' Computes the eigenvalues/eigenvectors of the covariance matrix for the terminal particle positions. ''' #See: http://www.vtk.org/Wiki/VTK/Examples/Cxx/Utilities/PCAStatistics datasetTable = vtk.vtkTable() datasetTable.AddColumn(xarray) datasetTable.AddColumn(yarray) pcaStatistics = vtk.vtkPCAStatistics() pcaStatistics.SetInputData( vtk.vtkStatisticsAlgorithm.INPUT_DATA, datasetTable ) pcaStatistics.SetColumnStatus('x', 1 ) pcaStatistics.SetColumnStatus('y', 1 ) pcaStatistics.RequestSelectedColumns() pcaStatistics.SetDeriveOption(True) pcaStatistics.Update() # Eigenvalues eigenvalues = vtk.vtkDoubleArray() pcaStatistics.GetEigenvalues(eigenvalues) for idx in range(0,eigenvalues.GetNumberOfTuples()): #for eigenvalue in eigenvalues: print 'Eigenvalue ' + str(idx) + ' = ' + str(eigenvalues.GetValue(idx)) # Eigenvectors eigenvectors = vtk.vtkDoubleArray() pcaStatistics.GetEigenvectors(eigenvectors) for idx in range(0,eigenvectors.GetNumberOfTuples()): print 'Eigenvector ' + str(idx) + ' : ' evec = [0]*eigenvectors.GetNumberOfComponents() eigenvectors.GetTuple(idx, evec) print evec
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()
def getFields(self): if not self.dataTable: # read a data file if '.csv' in self.inputFile: r = vtk.vtkDelimitedTextReader() r.DetectNumericColumnsOn() r.SetFileName(self.inputFile) r.SetHaveHeaders(True) r.Update() self.dataTable = r.GetOutput() else: reader = simple.OpenDataFile(self.inputFile) reader.UpdatePipeline() ds = reader.GetClientSideObject().GetOutputDataObject(0) if ds.IsA('vtkTable'): self.dataTable = ds else: self.dataTable = vtk.vtkTable() fillTableWithDataSet(self.dataTable, ds) self.fields = {} self.columnNames = [] self.numRows = self.dataTable.GetNumberOfRows() for i in range(self.dataTable.GetNumberOfColumns()): # Add a range for any numeric fields self.columnNames.append(self.dataTable.GetColumnName(i)) arr = self.dataTable.GetColumn(i) if arr.GetDataTypeAsString() in NUMERIC_TYPES: self.fields[self.columnNames[i]] = { 'range': list(arr.GetRange()) } return self.fields
def RequestData(self, request, inInfo, outInfo): """Used by pipeline to get output data object for given time step. Constructs the ``vtkImageData`` """ # Get output: output = vtk.vtkImageData.GetData(outInfo) # Get requested time index i = _helpers.GetRequestedTime(self, outInfo) if self.NeedToRead(): self._ReadUpFront() # Generate the data object n1, n2, n3 = self.__extent dx, dy, dz = self.__spacing ox, oy, oz = self.__origin output.SetDimensions(n1, n2, n3) output.SetExtent(0, n1 - 1, 0, n2 - 1, 0, n3 - 1) output.SetSpacing(dx, dy, dz) output.SetOrigin(ox, oy, oz) # Use table generater and convert because its easy: table = vtk.vtkTable() _helpers.placeArrInTable(self._GetRawData(idx=i), self.GetTitles(), table) # now get arrays from table and add to point data of pdo for i in range(table.GetNumberOfColumns()): output.GetPointData().AddArray(table.GetColumn(i)) #TODO: maybe we ought to add the data as cell data del (table) return 1
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 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()
def test_multi_block_init_vtk(): multi = vtk.vtkMultiBlockDataSet() multi.SetBlock(0, vtk.vtkRectilinearGrid()) multi.SetBlock(1, vtk.vtkTable()) multi = pyvista.MultiBlock(multi) assert isinstance(multi, pyvista.MultiBlock) assert multi.n_blocks == 2 assert isinstance(multi[0], pyvista.RectilinearGrid) assert isinstance(multi[1], vtk.vtkTable) multi = vtk.vtkMultiBlockDataSet() multi.SetBlock(0, vtk.vtkRectilinearGrid()) multi.SetBlock(1, vtk.vtkTable()) multi = pyvista.MultiBlock(multi, deep=True) assert isinstance(multi, pyvista.MultiBlock) assert multi.n_blocks == 2 assert isinstance(multi[0], pyvista.RectilinearGrid) assert isinstance(multi[1], vtk.vtkTable)
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()
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"
def gslib(FileName, deli=' ', useTab=False, numIgLns=0, pdo=None): """ Description ----------- Reads a GSLIB file format to a vtkTable. The GSLIB file format has headers lines followed by the data as a space delimited ASCI file (this filter is set up to allow you to choose any single character delimiter). The first header line is the title and will be printed to the console. This line may have the dimensions for a grid to be made of the data. The second line is the number (n) of columns of data. The next n lines are the variable names for the data in each column. You are allowed up to ten characters for the variable name. The data follow with a space between each field (column). Parameters ---------- `FileName` : str - The absolute file name with path to read. `deli` : str - The input files delimiter. To use a tab delimiter please set the `useTab`. `useTab` : boolean - A boolean that describes whether to use a tab delimiter. `numIgLns` : int - The integer number of lines to ignore. `pdo` : vtk.vtkTable, optional - A pointer to the output data object. Returns ------- Returns a vtkTable of the input data file. """ if pdo is None: pdo = vtk.vtkTable() # vtkTable if (useTab): deli = '\t' titles = [] data = [] with open(FileName) as f: reader = csv.reader(f, delimiter=deli) # Skip defined lines for i in range(numIgLns): next(f) # Get file header (part of format) header = next(f) # TODO: do something with the header #print(os.path.basename(FileName) + ': ' + header) # Get titles numCols = int(next(f)) for i in range(numCols): titles.append(next(f).rstrip('\r\n')) # Read data for row in reader: data.append(row) _rows2table(data, titles, pdo) return pdo, header
def initializeSelection(self): if not self.dataTableSelection: self.dataTableSelection = vtk.vtkTable() self.dataTableSelection.ShallowCopy(self.dataTable) self._userSelection = vtk.vtkUnsignedCharArray() self._userSelection.SetNumberOfTuples(self.numRows) self._userSelection.SetName(USER_SELECTION) self._userSelection.FillComponent(0, UNSELECTED_INDEX) self.dataTableSelection.AddColumn(self._userSelection)
def setUp(self): # Create some input tables self.t0 = vtk.vtkTable() # Populate the tables self.n = 400 self.title = 'Array 0' self.arr = np.random.random(self.n) # Table 0 self.t0.AddColumn(_helpers.numToVTK(self.arr, self.title)) return
def setUp(self): TestBase.setUp(self) # Create some input tables self.t0 = vtk.vtkTable() # Populate the tables self.n = 400 self.title = 'Array 0' self.arr = np.random.random(self.n) # Table 0 self.t0.AddColumn(interface.convertArray(self.arr, self.title)) return
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 data_frame_to_table(df, pdo=None): """Converts a pandas DataFrame to a vtkTable""" if not isinstance(df, pd.DataFrame): raise PVGeoError('Input is not a pandas DataFrame') if pdo is None: pdo = vtk.vtkTable() for key in df.keys(): VTK_data = convert_array(df[key].values, name=key) pdo.AddColumn(VTK_data) return wrap_vista(pdo)
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)
def setUp(self): # Create some input tables self.t0 = vtk.vtkTable() self.t1 = vtk.vtkTable() # Populate the tables self.n = 100 self.titles = ('Array 0', 'Array 1', 'Array 2') self.arrs = [None, None, None] self.arrs[0] = np.random.random(self.n) # Table 0 self.arrs[1] = np.random.random(self.n) # Table 0 self.arrs[2] = np.random.random(self.n) # Table 1 self.t0.AddColumn(_helpers.numToVTK(self.arrs[0], self.titles[0])) self.t0.AddColumn(_helpers.numToVTK(self.arrs[1], self.titles[1])) self.t1.AddColumn(_helpers.numToVTK(self.arrs[2], self.titles[2])) # Now use the `CombineTables` filter: f = CombineTables() f.SetInputDataObject(0, self.t0) f.SetInputDataObject(1, self.t1) f.Update() self.TABLE = f.GetOutputDataObject(0)
def setUp(self): # Create some input tables self.t0 = vtk.vtkTable() # Populate the tables self.arrs = [None, None] self.n = 400 self.titles = ('Array 0', 'Array 1') self.arrs[0] = np.random.random(self.n) # Table 0 self.arrs[1] = np.random.random(self.n) # Table 0 self.t0.AddColumn(_helpers.numToVTK(self.arrs[0], self.titles[0])) self.t0.AddColumn(_helpers.numToVTK(self.arrs[1], self.titles[1])) return
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
def GetNodeOneScaleCoeffTable(self, node_id): """Returns a table of the wavelet coefficients at a single node at a single scale for plotting on a scatter plot. Relying on icicle_view already having called GetWaveletCoeffImages() with correct positions of leaf nodes in view, otherwise just using original Matlab-saved LeafNodes ordering. This version supports category labels.""" if self.data_loaded: # For a given node_id, concatenate wavelet coeffs in proper order # (according to leaf node positions in icicle view if it was set already) # Columns of table will be rows of the wavelet coeffs image scale = self.Scales[node_id] leaf_offspring = N.array(list(self.get_leaf_children(self.cp, node_id))) offspring_idxs = self.LeafNodesImap[leaf_offspring] offspring_pos = self.mapped_leaf_pos[offspring_idxs] sorted_offspring_pos_idxs = N.argsort(offspring_pos) sorted_offspring_idxs = offspring_idxs[sorted_offspring_pos_idxs] img_tuple = tuple(pp for pp in self.CelCoeffs[sorted_offspring_idxs, scale]) # The image comes out with shape (npts, ndims) # May need to reorder (reverse) this...? img = N.concatenate(img_tuple, axis=0) table = vtk.vtkTable() for ii in range(img.shape[1]): column = VN.numpy_to_vtk(img[:,ii].copy(), deep=True) column.SetName(str(scale) + '.' + str(ii)) table.AddColumn(column) IDtuple = tuple(self.PointsInNet[xx] for xx in self.LeafNodes[sorted_offspring_idxs]) IDarray = N.concatenate(IDtuple) # Trying to set PedigreeIds to that parallel coords selections have correct IDs IDvtk = VN.numpy_to_vtk(IDarray, deep=True) IDvtk.SetName('pedigree_ids') table.AddColumn(IDvtk) table.GetRowData().SetActivePedigreeIds('pedigree_ids') # Adding in category labels # Name needs to end in _ids so plots will ignore it if self.hasLabels: for ii in range(self.cat_labels.shape[0]): CATvtk = VN.numpy_to_vtk(self.cat_labels[ii,IDarray], deep=True) CATvtk.SetName(self.label_names[ii]) table.AddColumn(CATvtk) return table else: raise IOError, "Can't get image until data is loaded successfully"
def createTable(self, matrix): table = vtk.vtkTable() for col, attr in zip(matrix.values.T, matrix.attributes): column = VN.numpy_to_vtk(col.copy(), deep=True) column.SetName(attr) table.AddColumn(column) self.chart.GetPlot(0).SetInput(table) min_ = matrix.values.min()-0.01 max_ = matrix.values.max()+0.01 for i in range(self.chart.GetNumberOfAxes()): self.chart.GetAxis(i).SetRange(min_, max_) self.chart.GetAxis(i).SetBehavior(vtk.vtkAxis.FIXED);
def testTableOutput(self): rcal = vtk.vtkRCalculatorFilter() rcal.SetRscript("output = list(test=c(1,2,3,4))\n"); rcal.GetTable('output') input = vtk.vtkTable() rcal.SetInputData(input) rcal.Update() t1 = rcal.GetOutput().GetColumnByName('test') value = 1 for i in range(0, t1.GetNumberOfTuples()): self.assertEqual(value, t1.GetValue(i)) value += 1
def createSource(self): r = vtk.vtkEnsembleSource() aColumn = vtk.vtkIntArray() aColumn.SetName("Resolution") nrows = len(TestEnsemble.resolutions) for res in TestEnsemble.resolutions: aColumn.InsertNextValue(res) table = vtk.vtkTable() table.SetNumberOfRows(nrows) table.GetRowData().AddArray(aColumn) r.SetMetaData(table) for res in TestEnsemble.resolutions: c = vtk.vtkConeSource() c.SetResolution(res) r.AddMember(c) return r
def addPlot(chart, reader, name): data1 = reader.GetOutput() coords = vtk.vtkFloatArray() coords.SetName("Coords") for i in range(data1.GetNumberOfPoints()): x,y,z = data1.GetPoint(i) coords.InsertNextValue(y) scalars = data1.GetPointData().GetArray("P_w") scalars.SetName(name) table = vtk.vtkTable() table.AddColumn(coords) table.AddColumn(scalars) line1 = chart.AddPlot(vtk.vtkChart.LINE) line1.SetInput(table, 0, 1)
def PlotSelectedData(data, state, view, text_init): nb_sources = 0 for i in range(data.GetPointData().GetNumberOfArrays()): if data.GetPointData().GetGlobalIds('Potentials-'+str(i)): nb_sources += 1 view.GetRenderer().RemoveActor2D(text_init) chart = vtk.vtkChartXY() view.GetScene().RemoveItem(0) view.GetScene().AddItem(chart) chart.SetShowLegend(True) table = vtk.vtkTable() X = vtk.vtkDoubleArray(); X.SetName("X") if state: numPoints = data.GetNumberOfCells() chart.GetAxis(0).SetTitle('Current'); else: numPoints = data.GetNumberOfPoints() chart.GetAxis(0).SetTitle('Potential'); chart.GetAxis(0).SetRange(0,nb_sources) for j in range(nb_sources): X.InsertNextValue(j) table.AddColumn(X) for i in range(numPoints): Y = vtk.vtkDoubleArray() if state: Y.SetName("id"+str(data.GetCellData().GetGlobalIds('Indices').GetValue(i))) else: Y.SetName("id"+str(data.GetPointData().GetGlobalIds('Indices').GetValue(i))) for j in range(nb_sources): if state: Y.InsertNextValue(data.GetCellData().GetGlobalIds('Currents-'+str(j)).GetValue(i)) else: Y.InsertNextValue(data.GetPointData().GetGlobalIds('Potentials-'+str(j)).GetValue(i)) table.AddColumn(Y) # Now add the line plots line = chart.AddPlot(0) line.SetInput(table,0,i+1) line.SetColor(0,1,0) line.SetWidth(1.0) view.GetRenderWindow().Render()
def testDistanceCalculator(self): "See whether the distance calculator evaluates functions properly." xv = vtk.vtkDoubleArray() yv = vtk.vtkDoubleArray() xv.SetName( 'x' ) yv.SetName( 'y' ) tab = vtk.vtkTable() xv.InsertNextValue( 0.0 ) xv.InsertNextValue( 1.0 ) xv.InsertNextValue( 0.0 ) xv.InsertNextValue( 1.0 ) xv.InsertNextValue( 5.0 ) yv.InsertNextValue( 0.0 ) yv.InsertNextValue( 0.0 ) yv.InsertNextValue( 1.0 ) yv.InsertNextValue( 1.0 ) yv.InsertNextValue( 12.0 ) tab.AddColumn( xv ) tab.AddColumn( yv ) km = vtk.vtkKMeansStatistics() km.SetDefaultNumberOfClusters( 1 ) df = vtk.vtkKMeansDistanceFunctorCalculator() km.SetDistanceFunctor( df ) df.SetDistanceExpression( 'sqrt( (x0-y0)*(x0-y0) + (x1-y1)*(x1-y1) )' ) km.SetInput( tab ) km.SetColumnStatus( 'x', 1 ) km.SetColumnStatus( 'y', 1 ) km.RequestSelectedColumns() km.SetLearnOption( 1 ) km.SetDeriveOption( 1 ) km.SetAssessOption( 1 ) km.Update() av = km.GetOutput( 0 ) # We should always converge to a cluster center at [ 1.4, 2.8 ] # These distances are the distances of each input observation to that cluster center: dists = [ 3.1304951684997055, 2.8284271247461898, 2.2803508501982757, 1.8439088914585773, 9.879271228182775 ] for i in range(5): self.failUnlessAlmostEqual( dists[i], av.GetColumn( 2 ).GetValue( i ) )
def calcPCA(xarray, yarray): ''' Returns the eigenvalue the covariance matrix for the terminal particle positions. ''' datasetTable = vtk.vtkTable() datasetTable.AddColumn(xarray) datasetTable.AddColumn(yarray) pcaStatistics = vtk.vtkPCAStatistics() pcaStatistics.SetInputData( vtk.vtkStatisticsAlgorithm.INPUT_DATA, datasetTable ) pcaStatistics.SetColumnStatus('x', 1 ) pcaStatistics.SetColumnStatus('y', 1 ) pcaStatistics.RequestSelectedColumns() pcaStatistics.SetDeriveOption(True) pcaStatistics.Update() eigenvalues = vtk.vtkDoubleArray() pcaStatistics.GetEigenvalues(eigenvalues) return eigenvalues.GetValue(0)
def __init__(self, x_data=None, y_data=None, **kwargs): super(Line, self).__init__(**kwargs) # Storage for vtk line/point object self._vtkplot = None # Build the vtkTable that stores the data x = vtk.vtkFloatArray() x.SetName('x-data') y = vtk.vtkFloatArray() y.SetName('y-data') self._vtktable = vtk.vtkTable() self._vtktable.AddColumn(x) self._vtktable.AddColumn(y) # Storage for tracing lines self._xtracer = None self._ytracer = None # Set x,y data if x_data: self.setOption('x', x_data) if y_data: self.setOption('y', y_data)
def testMultiTableOutputs(self): outputs = vtk.vtkStringArray() outputs.SetNumberOfComponents(1) outputs.SetNumberOfTuples(3) outputs.SetValue(0, "output1") outputs.SetValue(1, "output2") outputs.SetValue(2, "output3") rcal = vtk.vtkRCalculatorFilter() rcal.SetRscript("output1 = list(test=c(1,2,3,4))\n\ output2 = list(test=c(5,6,7,8))\n\ output3 = list(test=c(9,10,11,12))\n"); rcal.GetTables(outputs) input = vtk.vtkTable() rcal.SetInputData(input) rcal.Update() t1 = rcal.GetOutput().GetPieceAsDataObject(0).GetColumnByName('test') value = 1 for i in range(0, t1.GetNumberOfTuples()): self.assertEqual(value, t1.GetValue(i)) value += 1 t2 = rcal.GetOutput().GetPieceAsDataObject(1).GetColumnByName('test') for i in range(0, t2.GetNumberOfTuples()): self.assertEqual(value, t2.GetValue(i)) value += 1 t3 = rcal.GetOutput().GetPieceAsDataObject(2).GetColumnByName('test') for i in range(0, t3.GetNumberOfTuples()): self.assertEqual(value, t3.GetValue(i)) value += 1
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()
def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.WordleView = vtkvtg.vtkQtWordleDebugView() # Set widget for the wordle view self.ui.centralWidget.layout().addWidget(self.WordleView.GetWidget()) data_dir = '/Users/emonson/Data/Fodava/EMoGWDataSets/' data_file = data_dir + 'sciNews_20110216.mat' print 'Trying to load data set from .mat file...' try: MatInput = scipy.io.loadmat(data_file, struct_as_record=True, chars_as_strings=True) except: raise IOError, "Can't load supplied matlab file" self.mat_terms = MatInput['terms'].T[0] self.WavBases = [] # Wavelet bases self.Centers = [] # Center of each node # NodeWavCoeffs = [] # NodeScalCoeffs = [] for ii in range(MatInput['PointsInNet'].shape[1]): self.WavBases.append(N.mat(MatInput['WavBases'][0,ii])) # matrix self.Centers.append(N.mat(MatInput['Centers'][0,ii][0])) # matrix terms = vtk.vtkStringArray() terms.SetName('dictionary') terms.SetNumberOfComponents(1) for term in self.mat_terms: terms.InsertNextValue(term[0]) self.basis_idx = 0 coeffs = VN.numpy_to_vtk(self.WavBases[self.basis_idx][::-1,0]*100, deep=True) coeffs.SetName('coefficient') c_sign = VN.numpy_to_vtk(N.sign(self.WavBases[self.basis_idx][::-1,0]), deep=True) c_sign.SetName('sign') # Create a table with some points in it... self.table = vtk.vtkTable() self.table.AddColumn(terms) self.table.AddColumn(coeffs) self.table.AddColumn(c_sign) vt = vtk.vtkViewTheme() lut = vtk.vtkLookupTable() lut.SetHueRange(0, 0.66) lut.SetValueRange(0.7, 0.7) lut.SetSaturationRange(1, 1) lut.Build() # Set value for no color by array vt.SetPointColor(0,0,0) # Set LUT for color by array vt.SetPointLookupTable(lut) # ViewTheme Background color is black by default vt.SetBackgroundColor(1,1,1) self.WordleView.AddRepresentationFromInput(self.table) self.WordleView.SetFieldType(vtkvtg.vtkQtWordleView.ROW_DATA) self.WordleView.SetColorByArray(True) self.WordleView.SetColorArrayName('sign') self.WordleView.SetTermsArrayName('dictionary') self.WordleView.SetSizeArrayName('coefficient') self.WordleView.ApplyViewTheme(vt) self.WordleView.SetMaxNumberOfWords(150); self.WordleView.SetFontFamily("Rockwell") self.WordleView.SetFontStyle(vtkvtg.vtkQtWordleView.StyleNormal) self.WordleView.SetFontWeight(99) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.HORIZONTAL) self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.MOSTLY_HORIZONTAL) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.HALF_AND_HALF) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.MOSTLY_VERTICAL) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.VERTICAL) self.WordleView.SetLayoutPathShape(vtkvtg.vtkQtWordleView.CIRCULAR_PATH) # self.WordleView.SetLayoutPathShape(vtkvtg.vtkQtWordleView.SQUARE_PATH) QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL("triggered()"), self.fileExit) # Do first update before changing to debug mode... self.WordleView.Update() self.WordleView.ZoomToBounds() # while(True): # self.table.Modified() # self.WordleView.Update() # DEBUG self.WordleView.SetWatchLayout(True) self.WordleView.SetWatchCollision(True) self.WordleView.SetWatchQuadTree(True) self.WordleView.SetWatchDelay(50000)
def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.WordleView = vtkvtg.vtkQtWordleView() # Set widget for the wordle view self.ui.centralWidget.layout().addWidget(self.WordleView.GetWidget()) term_list = [ "straw", "gold", "name", "miller", "manikin", "daughter", "little", "queen", "man", "came", "girl", "give", "spin", "full", "whirr", "spun", "night", "one", "child", "king", "room", "answered", "morning", "names", "took", "began", "thought", "time", "find", "world", "day", "leg", "whole", "another", "three", "rumpelstiltskin", "knew", "left", "help", "still", "crying", "gave", "good", "round", "wheel", "second", "opened", "messenger", "ever", "told", "quite", "alone", "mistress", "larger", "became", "first", "brought", "put", "ring", "devil", "next", "house", "taken", "life", "door", "fire", "reel", "glad", "must", "beautiful", "heard", "promised", "saw", "perhaps", "also", "poor", "shall", "third", "wife", "necklace", "bring", "daybreak", "earth", "hopped", "inquiries", "cried", "dearer", "front", "far", "bid", "early", "every", "hands", "foot", "course", "always", "cry", "become", "conrad", "art", "hare", "hard", "back", "alive", "die", "curious", "bake", "even", "appear", "fox", "enough", "finger", "harry", "caspar", "greedy", "found", "country", "days", "asked", "already", "afterwards", "burning", "imagine", "delighted", "frightened", "appeared", "idea", "clever", "else", "alas", "astonished", "grew", "happened", "heart", "deep", "high", "evening", "anger", "commanded", "happen", "beyond", "end", "able", "forest", "jumping", "brew", "important", "balthazar", "inquire", "glittering" ] size_list = [ 12.0, 10.0, 10.0, 9.0, 9.0, 9.0, 9.0, 8.0, 8.0, 8.0, 7.0, 7.0, 6.0, 6.0, 6.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ] terms = vtk.vtkStringArray() terms.SetName('dictionary') terms.SetNumberOfComponents(1) for term in term_list: terms.InsertNextValue(term) coeffs = vtk.vtkDoubleArray() coeffs.SetName('coefficient') coeffs.SetNumberOfComponents(1) for size in size_list: coeffs.InsertNextValue(size) # Create a table with some points in it... self.table = vtk.vtkTable() self.table.AddColumn(terms) self.table.AddColumn(coeffs) self.vt = vtk.vtkViewTheme() lut = vtk.vtkLookupTable() lut.SetHueRange(0,0) lut.SetValueRange(0,1) lut.SetSaturationRange(1,1) lut.Build() # Set value for no color by array self.vt.SetPointColor(0,0,0) # Set LUT for color by array self.vt.SetPointLookupTable(lut) # ViewTheme Background color is black by default self.vt.SetBackgroundColor(1,1,1) self.vt2 = vtk.vtkViewTheme() lut2 = vtk.vtkLookupTable() lut2.SetHueRange(0, 0.66) lut2.SetValueRange(0.7, 0.7) lut2.SetSaturationRange(1, 1) lut2.Build() # Set value for no color by array self.vt2.SetPointColor(0,0,0) # Set LUT for color by array self.vt2.SetPointLookupTable(lut2) # ViewTheme Background color is black by default self.vt2.SetBackgroundColor(1,1,1) self.WordleView.AddRepresentationFromInput(self.table) self.WordleView.SetFieldType(vtkvtg.vtkQtWordleView.ROW_DATA) self.WordleView.SetColorByArray(True) self.WordleView.SetColorArrayName('coefficient') self.WordleView.SetTermsArrayName('dictionary') self.WordleView.SetSizeArrayName('coefficient') self.WordleView.SetOutputImageDataDimensions(200, 200) self.WordleView.ApplyViewTheme(self.vt) self.WordleView.SetMaxNumberOfWords(150); self.WordleView.SetFontFamily("Rockwell") self.WordleView.SetFontStyle(vtkvtg.vtkQtWordleView.StyleNormal) self.WordleView.SetFontWeight(99) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.HORIZONTAL) self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.MOSTLY_HORIZONTAL) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.HALF_AND_HALF) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.MOSTLY_VERTICAL) # self.WordleView.SetOrientation(vtkvtg.vtkQtWordleView.VERTICAL) self.WordleView.SetLayoutPathShape(vtkvtg.vtkQtWordleView.CIRCULAR_PATH) # self.WordleView.SetLayoutPathShape(vtkvtg.vtkQtWordleView.SQUARE_PATH) self.WordleView.Update() self.WordleView.ZoomToBounds() self.color_by_array = True self.font_flag = True QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL("triggered()"), self.fileExit)
def Execute(self): if (self.Mesh == None): self.PrintError('Error: no Mesh.') if (self.Source == None): self.PrintError('Error: no Source surface.') if (self.FirstTimeStep == None or self.LastTimeStep == None or self.IntervalTimeStep == None): timesteps = self.Mesh.GetFieldData().GetArray("timesteps") if (timesteps == None): self.PrintError('Error: no Timesteps.') indexList = [] i = 0 while i < self.Mesh.GetFieldData().GetArray("timesteps").GetNumberOfTuples(): indexList.append(int(timesteps.GetTuple(i)[0])) i+=1 firstTimeStep = indexList[0] else: indexList = range(self.FirstTimeStep,self.LastTimeStep+1,self.IntervalTimeStep) firstTimeStep = self.FirstTimeStep indexColumn = vtk.vtkIntArray() indexColumn.SetName("index") timeColumn = vtk.vtkDoubleArray() timeColumn.SetName("time") time = 0 timeStepsTable = vtk.vtkTable() timeStepsTable.AddColumn(indexColumn) timeStepsTable.AddColumn(timeColumn) for index in indexList: time+=(1./(len(indexList)-1)) indexColumn.InsertNextValue(index) timeColumn.InsertNextValue(time) u = self.Source.GetPointData().GetArray("u") if u: v = self.Source.GetPointData().GetArray("v") w = self.Source.GetPointData().GetArray("w") else: u = self.Source.GetPointData().GetArray("u_"+str(firstTimeStep)) v = self.Source.GetPointData().GetArray("v_"+str(firstTimeStep)) w = self.Source.GetPointData().GetArray("w_"+str(firstTimeStep)) speed = vtk.vtkFloatArray() speed.SetNumberOfComponents(u.GetNumberOfComponents()) speed.SetNumberOfTuples(u.GetNumberOfTuples()) speed.SetName('speed') i=0 while i<u.GetNumberOfTuples(): speed.InsertTuple1(i, vtk.vtkMath.Norm((u.GetTuple(i)[0],v.GetTuple(i)[0],w.GetTuple(i)[0]))) i+=1 self.Source.GetPointData().AddArray(speed) if self.Subdivide: sd = vtk.vtkLinearSubdivisionFilter() sd.SetInputData(self.Source) sd.SetNumberOfSubdivisions(1) sd.Update() self.Source = sd.GetOutput() self.Source.GetPointData().SetActiveScalars('speed') cp = vtk.vtkClipPolyData() cp.SetInputData(self.Source) cp.GenerateClipScalarsOff() cp.SetValue(self.MinSpeed) cp.Update() self.Source = cp.GetOutput() tracer = vtkvmtk.vtkvmtkStaticTemporalStreamTracer() tracer.SetInputData(self.Mesh) tracer.SetIntegratorTypeToRungeKutta45() tracer.SetTimeStepsTable(timeStepsTable) tracer.SetSeedTime(self.SeedTime) tracer.SetMaximumPropagation(self.MaximumPropagation) tracer.SetInitialIntegrationStep(self.InitialIntegrationStep) tracer.SetMinimumIntegrationStep(self.MinimumIntegrationStep) tracer.SetMaximumIntegrationStep(self.MaximumIntegrationStep) tracer.SetMaximumNumberOfSteps(self.MaximumNumberOfSteps) if self.Vorticity: tracer.SetComputeVorticity(1) if self.IntegrationDirectionBoth: tracer.SetIntegrationDirectionToBoth() tracer.SetSourceData(self.Source) tracer.SetVelocityScale(self.VelocityScale) if self.VectorComponents: tracer.UseVectorComponentsOn() tracer.SetComponent0Prefix(self.Component0Prefix) tracer.SetComponent1Prefix(self.Component1Prefix) tracer.SetComponent2Prefix(self.Component2Prefix) if self.Periodic: tracer.PeriodicOn() tracer.Update() self.Traces = tracer.GetOutput()
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()
for yr in range(1820,2010,10): print 'Year: ' + str(yr) # Break pipeline while set up new graph if yr != years_list[0]: layout.RemoveAllInputs() # del table, col0, col1, val, rawGraph, tgraph, currCoords, constraintArray, constraintData, yearData, vertexData # Build table of edges for correct year range start_n = start_node[cite_year < yr] end_n = end_node[cite_year < yr] all_n = N.unique(N.concatenate((start_n,end_n))) table = vtk.vtkTable() col0 = VN.numpy_to_vtk(start_n, deep=True) col0.SetName('start_node') col1 = VN.numpy_to_vtk(end_n, deep=True) col1.SetName('end_node') val = VN.numpy_to_vtk( N.ones(cite_year[cite_year < yr].shape) ) val.SetName('weight') table.AddColumn(col0) table.AddColumn(col1) table.AddColumn(val) # Only use cases as nodes if they've cited others node_table = vtk.vtkTable() col2 = VN.numpy_to_vtk(all_n, deep=True) col2.SetName('case_id')
def LoadData(self): # data_file = '/Users/emonson/Data/Fodava/EMoGWDataSets/yaleB_diffMap.mat' if os.path.exists('/Users/emonson/Data/Fodava/EMoGWDataSets'): self.openFilesDefaultPath = '/Users/emonson/Data/Fodava/EMoGWDataSets' else: self.openFilesDefaultPath = QtCore.QDir.homePath() picked_file = QtGui.QFileDialog.getOpenFileName(self, "Load Saved Matlab File", self.openFilesDefaultPath, "All Files (*);;Matlab Files (*.mat)") data_file = str(picked_file) # DataSource loads .mat file and can generate data from it for other views print "Loading data from ", str(data_file) self.last_data_dir = os.path.dirname(str(data_file)) # Hack for labels if 'yaleB' in data_file: l_idx = 2 else: l_idx = 0 print 'Trying to really load now...' try: MatInput = scipy.io.loadmat(data_file, struct_as_record=True, chars_as_strings=True) except: print 'loadmat crapping out for some reason...' raise IOError, "Can't load supplied matlab file" # return # Create original multi-dimensional data matrix e_vecs = MatInput['EigenVecs'] e_vals = MatInput['EigenVals'] self.data = N.mat(e_vecs*e_vals.T[0]) d = self.data.shape[1] # Try out fixed axis bounds for less distracting axis label switching # Still a problem that some points in in-between projections go out of these bounds... d_max = N.abs(self.data.max()) d_min = N.abs(self.data.min()) if d_max > d_min: w_max = d_max else: w_max = d_min # Rescale data so that max is 1.0 self.data = self.data/w_max self.ui.horizontalSlider.setMaximum((d-2)*self.divs+1) self.ui.horizontalSlider.setPageStep(self.divs) self.ui.horizontalSlider.setValue(0) # Start by plotting the first two columns of the data # These column matrices will hold results of all later calculations # and share memory with the table columns plotted self.r0 = self.data[:,0].copy() self.r1 = self.data[:,1].copy() # Create a table with some points in it... self.table = vtk.vtkTable() self.rv0 = VN.numpy_to_vtk(self.r0) self.rv0.SetName('column0') self.rv1 = VN.numpy_to_vtk(self.r1) self.rv1.SetName('column1') self.table.AddColumn(self.rv0) self.table.AddColumn(self.rv1) # Color-by array labels_array = MatInput['Labels'] self.cat_labels = N.zeros_like(labels_array) for ii in range(labels_array.shape[0]): cl_unique = set(labels_array[ii,:]) cl_map = {} for jj,vv in enumerate(cl_unique): cl_map[vv] = jj self.cat_labels[ii,:] = N.array([cl_map[vv] for vv in labels_array[ii,:]]) # Specifying a single label array here rvC = VN.numpy_to_vtk(self.cat_labels[l_idx,:].copy(),deep=True) rvC.SetName('color') self.table.AddColumn(rvC) self.chart.ClearPlots() points1 = self.chart.AddPlot(vtk.vtkChart.POINTS) points1.SetInput(self.table, 0, 1) points1.SetColor(0, 0, 0, 255) points1.SetMarkerStyle(vtk.vtkPlotPoints.CIRCLE) points1.SetScalarVisibility(1) points1.SetLookupTable(self.GetCategoryLUT(l_idx)) points1.SelectColorArray('color') sc = 1.01 x_axis = self.chart.GetAxis(1) y_axis = self.chart.GetAxis(0) if not self.axis_rescale: y_axis.SetBehavior(1) y_axis.SetNotation(2) y_axis.SetRange(-sc, sc) y_axis.RecalculateTickSpacing() y_axis.SetPrecision(1) if not self.axis_rescale: x_axis.SetBehavior(1) x_axis.SetNotation(2) x_axis.SetRange(-sc, sc) x_axis.RecalculateTickSpacing() x_axis.SetPrecision(1) x_axis.GetTitleProperties().BoldOff() y_axis.GetTitleProperties().BoldOff() x_axis.GetTitleProperties().SetFontSize(10) y_axis.GetTitleProperties().SetFontSize(10) self.columnUpdate()
# Warning! numpy support offer a view on numpy array # the numpy array must not be garbage collected! nxtime = solv_data[:, 0].copy() nxiters = solv_data[:, 1].copy() 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')
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()
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()
def GetSource(dataType): s = vtk.vtkRTAnalyticSource() if dataType == 'ImageData': return s elif dataType == 'UnstructuredGrid': dst = vtk.vtkDataSetTriangleFilter() dst.SetInputConnection(s.GetOutputPort()) return dst elif dataType == 'RectilinearGrid': s.Update() input = s.GetOutput() rg = vtk.vtkRectilinearGrid() rg.SetExtent(input.GetExtent()) dims = input.GetDimensions() spacing = input.GetSpacing() x = vtk.vtkFloatArray() x.SetNumberOfTuples(dims[0]) for i in range(dims[0]): x.SetValue(i, spacing[0]*i) y = vtk.vtkFloatArray() y.SetNumberOfTuples(dims[1]) for i in range(dims[1]): y.SetValue(i, spacing[1]*i) z = vtk.vtkFloatArray() z.SetNumberOfTuples(dims[2]) for i in range(dims[2]): z.SetValue(i, spacing[2]*i) rg.SetXCoordinates(x) rg.SetYCoordinates(y) rg.SetZCoordinates(z) rg.GetPointData().ShallowCopy(input.GetPointData()) pf.SetInputData(rg) return pf elif dataType == 'StructuredGrid': s.Update() input = s.GetOutput() sg = vtk.vtkStructuredGrid() sg.SetExtent(input.GetExtent()) pts = vtk.vtkPoints() sg.SetPoints(pts) npts = input.GetNumberOfPoints() for i in range(npts): pts.InsertNextPoint(input.GetPoint(i)) sg.GetPointData().ShallowCopy(input.GetPointData()) pf.SetInputData(sg) return pf elif dataType == 'Table': s.Update() input = s.GetOutput() table = vtk.vtkTable() RTData = input.GetPointData().GetArray(0) nbTuples = RTData.GetNumberOfTuples() array = vtk.vtkFloatArray() array.SetName("RTData") array.SetNumberOfTuples(nbTuples) for i in range(0, nbTuples): array.SetTuple1(i, float(RTData.GetTuple1(i))) table.AddColumn(array) pf.SetInputData(table) return pf