Пример #1
0
  def testThreshold(self):
    global args
    writefiles = "SaveData" in args

    renderer = vtk.vtkRenderer()
    renwin = vtk.vtkRenderWindow()
    renwin.AddRenderer(renderer)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renwin)
    renwin.Render()

    if "GPURender" in args:
        vtk.vtkPistonMapper.InitCUDAGL(renwin)

    src = vtk.vtkImageMandelbrotSource()
    src.SetWholeExtent(0,10,0,10,0,10)

    #scale and bias until piston's threshold understands origin and spacing
    src.Update()
    inputdata = src.GetOutput()
    if "Normalize" in args:
         testdata1 = inputdata.NewInstance()
         testdata1.ShallowCopy(inputdata)
         testdata1.SetSpacing(1,1,1)
         testdata1.SetOrigin(0,0,0)
         inputdata = testdata1

    d2p = vtk.vtkDataSetToPiston()
    d2p.SetInputData(inputdata)
    #d2p.SetInputConnection(src.GetOutputPort())

    threshF = vtk.vtkPistonThreshold()
    threshF.SetInputConnection(d2p.GetOutputPort())
    threshF.SetMinValue(0)
    threshF.SetMaxValue(80)

    p2d = vtk.vtkPistonToDataSet()
    p2d.SetInputConnection(threshF.GetOutputPort())
    p2d.SetOutputDataSetType(vtk.VTK_POLY_DATA)

    if writefiles:
        writeFile(p2d, "piston_threshold.vtk")

    mapper = vtk.vtkPistonMapper()
    mapper.SetInputConnection(threshF.GetOutputPort())
    mapper.Update()

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

    renderer.AddActor(actor)

    renderer.ResetCamera()
    renwin.Render()

    img_file = "TestThreshold.png"
    Testing.compareImage(renwin, Testing.getAbsImagePath(img_file))

    if Testing.isInteractive():
        iren.Start()
    def testBoundaryExtraction(self):
        ugg = vtkUnstructuredGridGeometryFilter()
        ugg.SetInputConnection(self.rdr.GetOutputPort())
        ugg.Update()

        a1, m1 = self.addToScene(ugg)
        clr = vtkColorSeries()
        lkup = vtkLookupTable()
        # Color the contours with a qualitative color scheme:
        clr.SetColorScheme(vtkColorSeries.BREWER_QUALITATIVE_DARK2)
        clr.BuildLookupTable(lkup, vtkColorSeries.CATEGORICAL);
        lkup.SetAnnotation(vtkVariant(0), 'Cell Low')
        lkup.SetAnnotation(vtkVariant(1), 'Somewhat Low')
        lkup.SetAnnotation(vtkVariant(2), 'Medium')
        lkup.SetAnnotation(vtkVariant(3), 'High')
        m1.SetScalarModeToUseCellFieldData()
        m1.SelectColorArray('SrcCellNum')
        m1.SetLookupTable(lkup)

        self.ri.Initialize()
        cam = self.rr.GetActiveCamera()
        cam.SetPosition(16.429826228, -5.64575247779, 12.7186363446)
        cam.SetFocalPoint(4.12105459591, 1.95201869763, 1.69574200166)
        cam.SetViewUp(-0.503606926552, 0.337767269532, 0.795168746344)

        # wri = vtkXMLUnstructuredGridWriter()
        # wri.SetInputConnection(ugg.GetOutputPort())
        # wri.SetDataModeToAscii()
        # wri.SetFileName('/tmp/surface.vtu')
        # wri.Write()

        self.rw.Render()
        image = 'LagrangeGeometricOperations-Boundary.png'
        #events = self.prepareTestImage(self.ri, filename=os.path.join('/tmp', image))
        Testing.compareImage(self.rw, self.pathToValidatedOutput(image))
Пример #3
0
 def testvtkTkRenderWidget(self):
     "Test if vtkTkRenderWidget works."
     self.rw.Render()
     self.root.update()
     img_file = "TestTkRenderWidget.png"
     Testing.compareImage(self.rw, Testing.getAbsImagePath(img_file))
     Testing.interact()
 def testvtkTkRenderWindowInteractor(self):
     "Test if vtkTkRenderWindowInteractor works."
     self.tkrw.Start()
     self.tkrw.Render()
     self.root.update()
     img_file = "TestTkRenderWindowInteractor.png"
     Testing.compareImage(self.rw, Testing.getAbsImagePath(img_file))
     Testing.interact()
Пример #5
0
    def testGlyphs(self):
        '''Test if the glyphs are created nicely.'''
        reader = vtk.vtkDataSetReader()

        data_file = os.path.join(Testing.VTK_DATA_ROOT, "Data", "tensors.vtk")

        reader.SetFileName(data_file)

        g1 = SimpleGlyph(reader)
        g1.glyph.ColorGlyphsOff()
        g1.Update()

        g2 = SimpleGlyph(reader)
        g2.glyph.ExtractEigenvaluesOff()
        g2.Update()
        g2.SetPosition((2.0, 0.0, 0.0))

        g3 = SimpleGlyph(reader)
        g3.glyph.SetColorModeToEigenvalues()
        g3.glyph.ThreeGlyphsOn()
        g3.Update()
        g3.SetPosition((0.0, 2.0, 0.0))

        g4 = SimpleGlyph(reader)
        g4.glyph.SetColorModeToEigenvalues()
        g4.glyph.ThreeGlyphsOn()
        g4.glyph.SymmetricOn()
        g4.Update()
        g4.SetPosition((2.0, 2.0, 0.0))

        # 6Components symetric tensor
        g5 = SimpleGlyph(reader)
        g5.glyph.SetInputArrayToProcess(0, 0, 0, 0, "symTensors1")
        g5.SetPosition((4.0, 2.0, 0.0))
        g5.Update()

        ren = vtk.vtkRenderer()
        for i in (g1, g2, g3, g4, g5):
            for j in i.GetActors():
                ren.AddActor(j)

        ren.ResetCamera();

        cam = ren.GetActiveCamera()
        cam.Azimuth(-20)
        cam.Elevation(20)
        cam.Zoom(1.1)

        ren.SetBackground(0.5, 0.5, 0.5)

        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        renWin.Render()

        img_file = "TestTensorGlyph.png"
        Testing.compareImage(renWin, Testing.getAbsImagePath(img_file))
        Testing.interact()
Пример #6
0
 def DoIt(self):
     self.SetUp()
     self.viewer.Render()
     self.tkrw.Render()
     self.root.update()
     # If you want to interact and use the sliders etc,
     # uncomment the following line.
     # self.root.mainloop()
     img_file = "cursor3D.png"
     Testing.compareImage(self.viewer.GetRenderWindow(), Testing.getAbsImagePath(img_file))
Пример #7
0
 def DoIt(self):
     self.SetUp()
     self.renWin.Render()
     self.tkrw.Render()
     self.root.update()
     # If you want to interact and use the sliders etc,
     # uncomment the following line.
     #self.root.mainloop()
     img_file = "squadViewer.png"
     Testing.compareImage(self.renWin, Testing.getAbsImagePath(img_file))
     Testing.interact()
    def testContour(self):
        ## Contour actor
        con = vtkContourFilter()
        con.SetInputConnection(self.rdr.GetOutputPort())
        con.SetInputArrayToProcess(0,0,0, vtkDataSet.FIELD_ASSOCIATION_POINTS_THEN_CELLS, 'Ellipsoid')
        con.SetComputeNormals(1)
        con.SetComputeScalars(1)
        con.SetComputeGradients(1)
        con.SetNumberOfContours(4)
        con.SetValue(0, 2.5)
        con.SetValue(1, 1.5)
        con.SetValue(2, 0.5)
        con.SetValue(3, 1.05)
        con.Update()

        # Add the contour to the scene:
        a1, m1 = self.addToScene(con)
        clr = vtkColorSeries()
        lkup = vtkLookupTable()
        # Color the contours with a qualitative color scheme:
        clr.SetColorScheme(vtkColorSeries.BREWER_QUALITATIVE_DARK2)
        clr.BuildLookupTable(lkup, vtkColorSeries.CATEGORICAL);
        lkup.SetAnnotation(vtkVariant(0.5), 'Really Low')
        lkup.SetAnnotation(vtkVariant(1.05), 'Somewhat Low')
        lkup.SetAnnotation(vtkVariant(1.5), 'Medium')
        lkup.SetAnnotation(vtkVariant(2.5), 'High')
        m1.SelectColorArray('Ellipsoid')
        m1.SetLookupTable(lkup)

        a2, m2 = self.addSurfaceToScene()

        self.ri.Initialize()
        cam = self.rr.GetActiveCamera()
        cam.SetPosition(12.9377265875, 6.5914481094, 7.54647854482)
        cam.SetFocalPoint(4.38052401617, 0.925973308028, 1.91021697659)
        cam.SetViewUp(-0.491867406412, -0.115590747077, 0.862963054655)

        ## Other nice viewpoints:
        # cam.SetPosition(-1.53194314907, -6.07277748432, 19.283152654)
        # cam.SetFocalPoint(4.0, 2.25, 2.25)
        # cam.SetViewUp(0.605781341771, 0.619386648223, 0.499388772365)
        #
        # cam.SetPosition(10.5925480421, -3.08988382244, 9.2072891403)
        # cam.SetFocalPoint(4.0, 2.25, 2.25)
        # cam.SetViewUp(-0.384040517561, 0.519961374525, 0.762989547683)

        self.rw.Render()
        image = 'LagrangeGeometricOperations-Contour.png'
        # events = self.prepareTestImage(self.ri, filename=os.path.join('/tmp', image))
        Testing.compareImage(self.rw, self.pathToValidatedOutput(image))
    def testClip(self):

        # Color the cells with a qualitative color scheme:
        clr = vtkColorSeries()
        lkup = vtkLookupTable()
        clr.SetColorScheme(vtkColorSeries.BREWER_QUALITATIVE_DARK2)
        clr.BuildLookupTable(lkup, vtkColorSeries.CATEGORICAL);
        lkup.SetAnnotation(vtkVariant(0), 'First cell')
        lkup.SetAnnotation(vtkVariant(1), 'Second cell')

        ## Clip
        pln = vtkPlane()
        pln.SetOrigin(4, 2, 2)
        pln.SetNormal(-0.28735, -0.67728, 0.67728)
        clp = vtkClipDataSet()
        clp.SetInputConnection(self.rdr.GetOutputPort())
        clp.SetClipFunction(pln)
        # clp.InsideOutOn()
        # clp.GenerateClipScalarsOn()
        clp.Update()

        # wri = vtkXMLUnstructuredGridWriter()
        # wri.SetFileName('/tmp/clip.vtu')
        # wri.SetInputDataObject(0, clp.GetOutputDataObject(0))
        # wri.SetDataModeToAscii()
        # wri.Write()

        # Add the clipped data to the scene:
        a1, m1 = self.addToScene(clp)
        m1.SetScalarModeToUseCellFieldData()
        m1.SelectColorArray('SrcCellNum')
        m1.SetLookupTable(lkup)

        ## Surface actor
        a2, m2 = self.addSurfaceToScene()
        m2.SetScalarModeToUseCellFieldData()
        m2.SelectColorArray('SrcCellNum')
        m2.SetLookupTable(lkup)

        self.ri.Initialize()
        cam = self.rr.GetActiveCamera()
        cam.SetPosition(16.0784261776, 11.8079343039, -6.69074553411)
        cam.SetFocalPoint(4.54685488135, 1.74152986486, 2.38091647662)
        cam.SetViewUp(-0.523934540522, 0.81705750638, 0.240644194852)
        self.rw.Render()
        image = 'LagrangeGeometricOperations-Clip.png'
        # events = self.prepareTestImage(self.ri, filename=os.path.join('/tmp', image))
        Testing.compareImage(self.rw, self.pathToValidatedOutput(image))
    def testImportExport(self):
        "Testing if images can be imported to and from numeric arrays."
        imp = vtkImageImportFromArray()
        exp = vtkImageExportToArray()
        idiff = vtk.vtkImageDifference()        

        img_dir = Testing.getAbsImagePath("")
        for i in glob.glob(os.path.join(img_dir, "*.png")):
            # Putting the reader outside the loop causes bad problems.
            reader = vtk.vtkPNGReader()            
            reader.SetFileName(i)
            reader.Update()

            # convert the image to a Numeric Array and convert it back
            # to an image data.            
            exp.SetInputConnection(reader.GetOutputPort())
            imp.SetArray(exp.GetArray())

            # ensure there is no difference between orig image and the
            # one we converted and un-converted.            
            idiff.SetInputConnection(imp.GetOutputPort())
            idiff.SetImage(reader.GetOutput())
            idiff.Update()
            err = idiff.GetThresholdedError()

            msg = "Test failed on image %s, with threshold "\
                  "error: %d"%(i, err)
            self.assertEqual(err, 0.0, msg)
Пример #11
0
  def testQVTKWidget(self):

    w2 = vtk.QVTKWidget()
    w2.resize(500,500)

    ren = vtk.vtkRenderer()
    ren.SetBackground(0,0,0)
    ren.SetBackground2(1,1,1)
    ren.SetGradientBackground(1)
    win2 = vtk.vtkRenderWindow()
    win2.AddRenderer(ren)
    w2.SetRenderWindow(win2)

    renwin = w2.GetRenderWindow()
    cone = vtk.vtkConeSource()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInput(cone.GetOutput())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    ren.AddViewProp(actor)
    ren.ResetCamera()

    w2.show()
    if Testing.isInteractive():
      PyQt4.QtGui.qApp.exec_()
Пример #12
0
  def testRendering(self):
    global args

    renderer = vtk.vtkRenderer()
    renwin = vtk.vtkRenderWindow()
    renwin.AddRenderer(renderer)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renwin)
    renwin.Render()

    if "GPURender" in args:
        print "Testing GPU direct render path"
        vtk.vtkPistonMapper.InitCUDAGL(renwin)
    else:
        print "Testing CPU indirect render path"

    src = vtk.vtkSphereSource()

    d2p = vtk.vtkDataSetToPiston()
    d2p.SetInputConnection(src.GetOutputPort())

    mapper = vtk.vtkPistonMapper()
    mapper.SetInputConnection(d2p.GetOutputPort())
    mapper.Update() #TODO: shouldn't need this

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

    renderer.AddActor(actor)

    renderer.ResetCamera()
    renwin.Render()

    img_file = "TestRendering.png"
    Testing.compareImage(renwin, Testing.getAbsImagePath(img_file))

    if Testing.isInteractive():
        iren.Start()
Пример #13
0
    def testRasterEPS(self):
        """Test EPS output when Write3DPropsAsRasterImage is on."""
        # Get a temporary file name.  Set the extension to empty since
        # the exporter appends a suitable extension.
        tmp_eps = tempfile.mktemp('')
        # Write an EPS file.
        exp = vtk.vtkGL2PSExporter()
        exp.SetRenderWindow(self.renWin)
        exp.SetFilePrefix(tmp_eps)
        # Turn off compression so PIL can read file.
        exp.CompressOff() 
        exp.SetSortToOff()
        exp.DrawBackgroundOn()
        exp.Write3DPropsAsRasterImageOn()
        exp.Write()
        # Now read the EPS file using PIL.
        tmp_eps += '.eps'
        im = Image.open(tmp_eps)
        # Get a temporary name for the PNG file.
        tmp_png = tempfile.mktemp('.png')
        im.save(tmp_png)

        # Now read the saved image and compare it for the test.
        png_r = vtk.vtkPNGReader()
        png_r.SetFileName(tmp_png)
        png_r.Update()
        img = png_r.GetOutput()

        # Cleanup.  Do this first because if the test fails, an
        # exception is raised and the temporary files won't be
        # removed.
        self._cleanup([tmp_eps, tmp_png])
        
        img_file = "TestGL2PSExporter.png"
        Testing.compareImageWithSavedImage(img,
                                           Testing.getAbsImagePath(img_file))
        # Interact if necessary.
        Testing.interact()
Пример #14
0
    def testvtkQtTableView(self):

        sphereSource = vtk.vtkSphereSource()
        tableConverter = vtk.vtkDataObjectToTable()
        tableConverter.SetInput(sphereSource.GetOutput())
        tableConverter.SetFieldType(1)
        tableConverter.Update()
        pointTable = tableConverter.GetOutput()

        tableView = vtk.vtkQtTableView()
        tableView.SetSplitMultiComponentColumns(1)
        tableView.AddRepresentationFromInput(pointTable)
        tableView.Update()
        w = tableView.GetWidget()
        w.show()

        if Testing.isInteractive():
            PyQt4.QtGui.qApp.exec_()
Пример #15
0
    def testQVTKRenderWindowInteractor(self):
        w2 = QVTKRenderWindowInteractor()
        w2.Initialize()

        ren = vtk.vtkRenderer()
        ren.SetBackground(0,0,0)
        ren.SetBackground2(1,1,1)
        ren.SetGradientBackground(1)

        renwin = w2.GetRenderWindow()
        renwin.AddRenderer(ren)
        cone = vtk.vtkConeSource()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(cone.GetOutputPort())
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        ren.AddViewProp(actor)
        ren.ResetCamera()

        w2.show()
        if Testing.isInteractive():
            QtGui.qApp.exec_()
Пример #16
0
        iact = vtk.vtkRenderWindowInteractor()
        iact.SetRenderWindow(renWin)
        planeWidgetX.SetInteractor(iact)
        planeWidgetX.On()
        planeWidgetY.SetInteractor(iact)
        planeWidgetY.On()
        planeWidgetZ.SetInteractor(iact)
        planeWidgetZ.On()

        # Create an initial interesting view
        ren.ResetCamera();
        cam1 = ren.GetActiveCamera()
        cam1.Elevation(110)
        cam1.SetViewUp(0, 0, -1)
        cam1.Azimuth(45)
        ren.ResetCameraClippingRange()

        iact.Initialize()
        renWin.Render()

        # Compare the images and test.
        img_file = "TestImagePlaneWidget.png"
        Testing.compareImage(renWin, Testing.getAbsImagePath(img_file))
        # Interact if necessary.
        if Testing.isInteractive():
            iact.Start()

if __name__ == "__main__":
    Testing.main([(TestMapperLUT, 'test')])

Пример #17
0
        encoder = vtk.vtkDataEncoder()
        base64String = encoder.EncodeAsBase64Png(imgData).encode('ascii')

        # Now Base64 decode the string back to PNG image data bytes
        outputBuffer = bytearray(120000)
        inputArray = array.array('B', base64String)
        utils = vtk.vtkIOCore.vtkBase64Utilities()
        actualLength = utils.Decode(inputArray, 120000, outputBuffer)
        outputArray = bytearray(actualLength)
        outputArray[:] = outputBuffer[0:actualLength]

        # And write those bytes to the disk as an actual PNG image file
        with open('TestDataEncoder.png', 'wb') as fd:
            fd.write(outputArray)

        # Create a vtkTesting object and specify a baseline image
        rtTester = vtk.vtkTesting()
        for arg in sys.argv[1:]:
            rtTester.AddArgument(arg)
        rtTester.AddArgument("-V")
        rtTester.AddArgument("TestDataEncoder.png")

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

        if result == 0:
            raise Exception("TestDataEncoder failed.")

if __name__ == "__main__":
    Testing.main([(TestDataEncoder, 'test')])
Пример #18
0
                value = vtk.vtkVariant("world")
                a.SetValue(i, value)
                result = a.GetValue(i)
                self.assertEqual(value, result)
            else:
                value = 12
                a.SetValue(i, value)
                result = a.GetValue(i)
                self.assertEqual(value, result)

    def testArray(self):
        """Test array CreateArray"""
        o = vtk.vtkArray.CreateArray(vtk.vtkArray.DENSE, vtk.VTK_DOUBLE)
        self.assertEqual(o.__class__, vtk.vtkDenseArray[float])

    def testVector(self):
        """Test vector templates"""
        # make sure Rect inherits operators
        r = vtk.vtkRectf(0, 0, 2, 2)
        self.assertEqual(r[2], 2.0)
        c = vtk.vtkColor4ub(0, 0, 0)
        self.assertEqual(list(c), [0, 0, 0, 255])
        e = vtk.vtkVector['float32', 3]([0.0, 1.0, 2.0])
        self.assertEqual(list(e), [0.0, 1.0, 2.0])
        i = vtk.vtkVector3['i'](0)
        self.assertEqual(list(i), [0, 0, 0])


if __name__ == "__main__":
    Testing.main([(TestTemplates, 'test')])
Пример #19
0
    def testBitArrayArguments(self):
        a = vtk.vtkBitArray()
        a.SetNumberOfComponents(2)
        a.SetNumberOfTuples(1)
        ti = [0,1]
        to = [0,0]
        a.SetTuple(0, ti)
        a.GetTuple(0, to);
        self.assertEqual(ti, [int(x) for x in to])

    def testNDimArrayArguments(self):
        a = [[0,0,0],[0,0,0],[0,0,0]]
        vtk.vtkMath.Identity3x3(a)
        x = [0.5, 0.2, 0.1]
        y = [0.0, 0.0, 0.0]
        vtk.vtkMath.Multiply3x3(a, x, y)
        self.assertEqual(x, y)

    def testInformationVectorKeys(self):
        a = vtk.vtkImageGridSource()
        spacing = (3.0, 2.0, 1.0)
        a.SetDataSpacing(spacing)
        a.UpdateInformation()
        info = a.GetOutputInformation(0)
        t = info.Get(vtk.vtkDataObject.SPACING())
        self.assertEqual(t, spacing)

if __name__ == "__main__":
    Testing.main([(TestArrayArguments, 'test')])
Пример #20
0
    def setUp(self):
        self.vtkObj = vtk.vtkObject()

        self.vtkObjForCallData = vtk.vtkObject()

    def test_int(self):
        self.vtkObj.AddObserver(vtk.vtkCommand.AnyEvent, self.callbackInt)
        self.vtkObj.InvokeEvent(vtk.vtkCommand.ModifiedEvent, testInt)
        self.assertEqual(self.calldata, testInt)

    def test_string(self):
        self.vtkObj.AddObserver(vtk.vtkCommand.AnyEvent, self.callbackString)
        self.vtkObj.InvokeEvent(vtk.vtkCommand.ModifiedEvent, testString)
        self.assertEqual(self.calldata, testString)

    def test_float(self):
        self.vtkObj.AddObserver(vtk.vtkCommand.AnyEvent, self.callbackFloat)
        self.vtkObj.InvokeEvent(vtk.vtkCommand.ModifiedEvent, testFloat)
        self.assertAlmostEqual(self.calldata, testFloat)

    def test_obj(self):
        self.vtkObj.AddObserver(vtk.vtkCommand.AnyEvent, self.callbackObj)
        self.vtkObj.InvokeEvent(vtk.vtkCommand.ModifiedEvent,
                                self.vtkObjForCallData)
        self.assertEqual(self.calldata, self.vtkObjForCallData)


if __name__ == '__main__':
    Testing.main([(VTKPythonObjectCalldataInvokeEventTest, 'test')])

class TestQVTKRenderWindowInteractor(Testing.vtkTest):
    def testQVTKRenderWindowInteractor(self):
        w2 = QVTKRenderWindowInteractor()
        w2.Initialize()

        ren = vtk.vtkRenderer()
        ren.SetBackground(0, 0, 0)
        ren.SetBackground2(1, 1, 1)
        ren.SetGradientBackground(1)

        renwin = w2.GetRenderWindow()
        renwin.AddRenderer(ren)
        cone = vtk.vtkConeSource()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(cone.GetOutputPort())
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        ren.AddViewProp(actor)
        ren.ResetCamera()

        w2.show()
        if Testing.isInteractive():
            QtGui.qApp.exec_()


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    Testing.main([(TestQVTKRenderWindowInteractor, 'test')])
Пример #22
0
            self.assertEqual(output.GetNumberOfBlocks(), 2)

            b0 = output.GetBlock(0)
            self.assertEqual(
                int(b0.GetFieldData().GetArray("Properties").GetValue(0)), 2)
            pd = b0.GetPointData()
            self.assertEqual(int(pd.GetArray("Momentum").GetComponent(10, 2)),
                             0)
            self.assertEqual(int(pd.GetArray("StagnationEnergy").GetValue(3)),
                             9)

            b1 = output.GetBlock(1)
            self.assertEqual(
                int(b1.GetFieldData().GetArray("Properties").GetValue(0)), 2)
            pd = b1.GetPointData()
            self.assertEqual(int(pd.GetArray("Momentum").GetComponent(10, 2)),
                             0)
            self.assertEqual(int(pd.GetArray("StagnationEnergy").GetValue(3)),
                             1)

    def testMetaReader(self):
        r = vtk.vtkPlot3DMetaReader()
        r.SetFileName(str(VTK_DATA_ROOT) + "/Data/multi.p3d")
        r.Update()
        self.assertTrue(
            r.GetOutput().GetBlock(0).GetPointData().GetArray("Function0"))


if __name__ == "__main__":
    Testing.main([(TestPlot3D, 'test')])
Пример #23
0
        reader = vtk.vtkAMREnzoReader()
        reader.SetFileName(filename)
        reader.SetMaxLevel(10)
        reader.SetCellArrayStatus("TotalEnergy", 1)

        filter = vtk.vtkAMRResampleFilter()
        filter.SetMin([0.2, 0.2, 0])
        filter.SetMax([0.8, 0.8, 1])
        filter.SetNumberOfSamples([30, 30, 30])
        filter.SetDemandDrivenMode(1)

        filter.SetInputConnection(reader.GetOutputPort())
        filter.Update()

        out = filter.GetOutputDataObject(0).GetBlock(0)
        self.assertEqual(out.GetNumberOfPoints(), 27000)
        data = out.GetPointData().GetArray("TotalEnergy")
        minV = data.GetTuple(0)[0]
        maxV = data.GetTuple(0)[0]
        for i in range(out.GetNumberOfPoints()):
            v = data.GetTuple(i)[0]
            minV = min(v, minV)
            maxV = max(v, maxV)

        noError = abs(maxV * 100000 - 201) < 1
        self.assertEqual(noError, True)


if __name__ == "__main__":
    Testing.main([(TestAMRResampleFilter, 'test')])
        imp = vtkImageImportFromArray()
        exp = vtkImageExportToArray()
        idiff = vtk.vtkImageDifference()

        img_dir = Testing.getAbsImagePath("")
        for i in glob.glob(os.path.join(img_dir, "*.png")):
            # Putting the reader outside the loop causes bad problems.
            reader = vtk.vtkPNGReader()
            reader.SetFileName(i)
            reader.Update()

            # convert the image to a Numeric Array and convert it back
            # to an image data.
            exp.SetInputConnection(reader.GetOutputPort())
            imp.SetArray(exp.GetArray())

            # ensure there is no difference between orig image and the
            # one we converted and un-converted.
            idiff.SetInputConnection(imp.GetOutputPort())
            idiff.SetImage(reader.GetOutput())
            idiff.Update()
            err = idiff.GetThresholdedError()

            msg = "Test failed on image %s, with threshold "\
                  "error: %d"%(i, err)
            self.assertEqual(err, 0.0, msg)


if __name__ == "__main__":
    Testing.main([(TestNumericArrayImageData, 'test')])
Пример #25
0
        cf.Update()
        self.assertEqual(cf.GetOutput().GetNumberOfPoints(), 1047)
        self.assertEqual(cf.GetOutput().GetNumberOfCells(), 2056)

        # Check that expected arrays are in the output

        # The active scalars in the input shouldn't effect the
        # scalars in the output
        availableScalars = ["Temp", "Pres"]
        for scalar in availableScalars:

            input.GetPointData().SetActiveScalars(scalar)

            cf.ComputeScalarsOn()
            cf.Update()

            pd = cf.GetOutput().GetPointData()
            self.assertNotEqual(pd.GetArray("Temp"), None)
            self.assertNotEqual(pd.GetArray("Pres"), None)

            cf.ComputeScalarsOff()  # "Temp" array should not be in output
            cf.Update()

            pd = cf.GetOutput().GetPointData()
            self.assertEqual(pd.GetArray("Temp"), None)
            self.assertNotEqual(pd.GetArray("Pres"), None)


if __name__ == "__main__":
    Testing.main([(TestContourGrid, 'test')])
Пример #26
0
        g5 = SimpleGlyph(reader)
        g5.glyph.SetInputArrayToProcess(0, 0, 0, 0, "symTensors1")
        g5.SetPosition((4.0, 2.0, 0.0))
        g5.Update()

        ren = vtk.vtkRenderer()
        for i in (g1, g2, g3, g4, g5):
            for j in i.GetActors():
                ren.AddActor(j)

        ren.ResetCamera()

        cam = ren.GetActiveCamera()
        cam.Azimuth(-20)
        cam.Elevation(20)
        cam.Zoom(1.1)

        ren.SetBackground(0.5, 0.5, 0.5)

        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        renWin.Render()

        img_file = "TestTensorGlyph.png"
        Testing.compareImage(renWin, Testing.getAbsImagePath(img_file))
        Testing.interact()


if __name__ == "__main__":
    Testing.main([(TestTensorGlyph, 'test')])
Пример #27
0
        self.assertEqual((v[0], v[1], v[2]), (3, 4, 5))
        v = vtk.vtkVector3d(6)
        self.assertEqual((v[0], v[1], v[2]), (6, 6, 6))
        # resolve by argument type
        v = vtk.vtkVariant(3.0)
        self.assertEqual(v.GetType(), vtk.VTK_DOUBLE)
        v = vtk.vtkVariant(1)
        self.assertEqual(v.GetType(), vtk.VTK_INT)
        v = vtk.vtkVariant("hello")
        self.assertEqual(v.GetType(), vtk.VTK_STRING)
        v = vtk.vtkVariant(vtk.vtkObject())
        self.assertEqual(v.GetType(), vtk.VTK_OBJECT)

    def testArgumentConversion(self):
        """Test argument conversion via implicit constructors"""
        # automatic conversion to vtkVariant
        a = vtk.vtkVariantArray()
        a.InsertNextValue(2.5)
        a.InsertNextValue(vtk.vtkObject())
        self.assertEqual(a.GetValue(0), vtk.vtkVariant(2.5))
        self.assertEqual(a.GetValue(1).GetType(), vtk.VTK_OBJECT)
        # same, but this one is via "const vtkVariant&" argument
        a = vtk.vtkDenseArray[float]()
        a.Resize(1)
        a.SetVariantValue(0, 2.5)
        self.assertEqual(a.GetVariantValue(0).ToDouble(), 2.5)


if __name__ == "__main__":
    Testing.main([(TestOverloads, 'test')])
Пример #28
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)])


class TestWedge(Testing.vtkTest, CellTestBase):
    def setUp(self):
        self.Cell = GenerateCell(vtk.VTK_WEDGE, [(-1.0, -1.0, -1.0),
                                                 (1.0, -1.0, -1.0),
                                                 (0.0, -1.0, 1.0),
                                                 (-1.0, 1.0, -1.0),
                                                 (1.0, 1.0, -1.0),
                                                 (0.0, 1.0, 0.0)])


class TestPyramid(Testing.vtkTest, CellTestBase):
    def setUp(self):
        self.Cell = GenerateCell(vtk.VTK_PYRAMID, [(-1.0, -1.0, -1.0),
                                                   (1.0, -1.0, -1.0),
                                                   (1.0, 1.0, -1.0),
                                                   (-1.0, 1.0, -1.0),
                                                   (0.0, 0.0, 1.0)])


if __name__ == '__main__':
    Testing.main([(TestPyramid, 'test'), (TestWedge, 'test'),
                  (TestTetra, 'test'), (TestHexahedron, 'test')])
        imp = vtkImageImportFromArray()
        exp = vtkImageExportToArray()
        idiff = vtk.vtkImageDifference()        

        img_dir = Testing.getAbsImagePath("")
        for i in glob.glob(os.path.join(img_dir, "*.png")):
            # Putting the reader outside the loop causes bad problems.
            reader = vtk.vtkPNGReader()            
            reader.SetFileName(i)
            reader.Update()

            # convert the image to a Numeric Array and convert it back
            # to an image data.            
            exp.SetInputConnection(reader.GetOutputPort())
            imp.SetArray(exp.GetArray())

            # ensure there is no difference between orig image and the
            # one we converted and un-converted.            
            idiff.SetInputConnection(imp.GetOutputPort())
            idiff.SetImage(reader.GetOutput())
            idiff.Update()
            err = idiff.GetThresholdedError()

            msg = "Test failed on image %s, with threshold "\
                  "error: %d"%(i, err)
            self.assertEqual(err, 0.0, msg)


if __name__ == "__main__":
    Testing.main([(TestNumericArrayImageData, 'test')])
Пример #30
0
        b = vtk.vtkIntArray()
        b.SetNumberOfTuples(1)
        b.SetValue(0, 2)
        ptr = a.GetVoidPointer(0)
        # check the format _0123456789abcdef_p_void
        self.assertEqual(ptr[0:1], "_")
        self.assertEqual(ptr[-7:], "_p_void")
        address = int(ptr[1:-7], 16)
        # check that we can use the pointer
        b.SetVoidArray(ptr, 1, 1)
        self.assertEqual(b.GetValue(0), 1)
        a.SetValue(0, 10)
        self.assertEqual(b.GetValue(0), 10)

    def testObjectPointer(self):
        a = vtk.vtkInformation()
        ptr = a.__this__
        # check the format _0123456789abcdef_p_vtkInformation
        self.assertEqual(ptr[0:1], "_")
        self.assertEqual(ptr[-17:], "_p_vtkInformation")
        address = int(ptr[1:-17], 16)
        # create a VTK object from the swig pointer
        b = vtk.vtkObject(ptr)
        self.assertEqual(b.GetClassName(), a.GetClassName())
        self.assertEqual(a.__this__, b.__this__)
        self.assertEqual(a, b)


if __name__ == "__main__":
    Testing.main([(TestSwigPointer, 'test')])
        ghosts.SetName("vtkGhostLevels")
        ghosts.SetNumberOfTuples(10)
        ghosts.SetValue(0, 1)
        ghosts.SetValue(1, 1)
        ghosts.SetValue(2, 1)
        ghosts.SetValue(3, 0)
        ghosts.SetValue(4, 1)
        ghosts.SetValue(5, 1)
        ghosts.SetValue(6, 1)
        ghosts.SetValue(7, 0)
        ghosts.SetValue(8, 0)

        grid = vtk.vtkUnstructuredGrid()
        grid.Allocate(1, 1)
        grid.InsertNextCell(te.GetCellType(), te.GetPointIds())
        grid.SetPoints(pts)
        grid.GetPointData().AddArray(ghosts)

        ugg = vtk.vtkUnstructuredGridGeometryFilter()
        ugg.SetInputData(grid)

        dss = vtk.vtkDataSetSurfaceFilter()
        dss.SetNonlinearSubdivisionLevel(2)
        dss.SetInputConnection(ugg.GetOutputPort())
        dss.Update()
        self.assertEqual(dss.GetOutput().GetNumberOfCells(), 48)


if __name__ == "__main__":
    Testing.main([(TestGhostPoints, 'test')])
Пример #32
0
        # Now read the EPS file using PIL.
        tmp_eps += '.eps'
        im = Image.open(tmp_eps)
        # Get a temporary name for the PNG file.
        tmp_png = tempfile.mktemp('.png')
        im.save(tmp_png)

        # Now read the saved image and compare it for the test.
        png_r = vtk.vtkPNGReader()
        png_r.SetFileName(tmp_png)
        png_r.Update()
        img = png_r.GetOutput()

        # Cleanup.  Do this first because if the test fails, an
        # exception is raised and the temporary files won't be
        # removed.
        self._cleanup([tmp_eps, tmp_png])

        img_file = "TestGL2PSExporter.png"
        Testing.compareImageWithSavedImage(img,
                                           Testing.getAbsImagePath(img_file))
        # Interact if necessary.
        Testing.interact()


if __name__ == "__main__":
    cases = [(TestGL2PSExporter, 'test')]
    # This should prevent debug leaks messages.
    del TestGL2PSExporter
    Testing.main(cases)
Пример #33
0
        a = vtk.vtkStringArray()
        a.InsertNextValue(eightbit)
        s = a.GetValue(0)
        self.assertEqual(s, 'Francois')

    def testPassEncodedString(self):
        """Pass encoded 8-bit strings."""
        a = vtk.vtkStringArray()
        # latin1 encoded string will be returned as "bytes", which is
        # just a normal str object in Python 2
        encoded = cedilla.encode('latin1')
        a.InsertNextValue(encoded)
        result = a.GetValue(0)
        self.assertEqual(type(result), bytes)
        self.assertEqual(result, encoded)
        # utf-8 encoded string will be returned as "str", which is
        # actually unicode in Python 3
        a = vtk.vtkStringArray()
        encoded = cedilla.encode('utf-8')
        a.InsertNextValue(encoded)
        result = a.GetValue(0)
        self.assertEqual(type(result), str)
        if sys.hexversion >= 0x03000000:
            self.assertEqual(result.encode('utf-8'), encoded)
        else:
            self.assertEqual(result, encoded)


if __name__ == "__main__":
    Testing.main([(TestString, 'test')])
Пример #34
0
        # invalid variants all hash the same
        d[vtk.vtkVariant()] = 'invalid'
        self.assertEqual(d[vtk.vtkVariant()], 'invalid')

    def testPassByValueReturnByReference(self):
        """Pass vtkVariant by value, return by reference"""
        a = vtk.vtkVariantArray()
        a.SetNumberOfValues(1)
        v = vtk.vtkVariant(1)
        a.SetValue(0, v)
        u = a.GetValue(0)
        self.assertEqual(u.ToInt(), v.ToInt())
        self.assertEqual(u.GetType(), v.GetType())
        self.assertEqual(u.IsValid(), v.IsValid())

    def testPassByReferenceReturnByValue(self):
        """Pass vtkVariant by reference, return by value."""
        a = vtk.vtkArray.CreateArray(1, vtk.VTK_INT)
        a.Resize(1, 1)
        v = vtk.vtkVariant(1)
        a.SetVariantValue(0, 0, v)
        u = a.GetVariantValue(0, 0)
        self.assertEqual(u.ToInt(), v.ToInt())
        self.assertEqual(u.GetType(), v.GetType())
        self.assertEqual(u.IsValid(), v.IsValid())


if __name__ == "__main__":
    Testing.main([(TestVariant, 'test')])
Пример #35
0
class TestXYZMolReader(Testing.vtkTest):
    timerange = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0)

    def createMolecule(self):
        reader = vtk.vtkXYZMolReader2()
        reader.SetFileName(VTK_DATA_ROOT + "/Data/nanowireTB23K298.xyz")
        reader.Update()
        return reader

    def test1(self):
        reader = self.createMolecule()
        mol = reader.GetOutput()
        bonder = vtk.vtkSimpleBondPerceiver()
        bonder.SetInputData(mol)
        bonder.SetTolerance(.3)
        bonder.Update()
        mol = bonder.GetOutput()
        self.assertEqual(mol.GetNumberOfAtoms(), 3254)
        self.assertEqual(mol.GetNumberOfBonds(), 16948)
        if (reader.GetOutputInformation(0).Has(
                vtk.vtkCompositeDataPipeline.TIME_STEPS())):
            self.assertEqual(
                self.timerange,
                reader.GetOutputInformation(0).Get(
                    reader.GetExecutive().TIME_STEPS()))


if __name__ == "__main__":
    Testing.main([(TestXYZMolReader, 'test')])
Пример #36
0
        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 testParse(self):
        "Test if vtkKMeansDistanceFunctorCalculator is parseable"
        tg = vtk.vtkKMeansDistanceFunctorCalculator()
        self._testParse(tg)

    def testGetSet(self):
        "Testing Get/Set methods of vtkKMeansDistanceFunctorCalculator"
        tg = vtk.vtkKMeansDistanceFunctorCalculator()
        self._testGetSet(tg)

    def testParse(self):
        "Testing Boolean methods of vtkKMeansDistanceFunctorCalculator"
        tg = vtk.vtkKMeansDistanceFunctorCalculator()
        self._testBoolean(tg)


if __name__ == "__main__":
    Testing.main([(kMeansDistanceCalculator, 'test')])
Пример #37
0
#!/usr/bin/env python

import sys
import os
import PyQt4

import vtk
from vtk.test import Testing


class TestTimeUtility(Testing.vtkTest):
    def testConvertBack(self):
        t = 0
        d = vtk.vtkQtTimePointUtility.TimePointToQDateTime(t)
        print d
        t2 = vtk.vtkQtTimePointUtility.QDateTimeToTimePoint(d)
        print t2
        self.assertEqual(t, t2)

    def testConvertBack2(self):
        t = 0
        t2 = vtk.vtkQtTimePointUtility.QDateTimeToTimePoint(
            vtk.vtkQtTimePointUtility.TimePointToQDateTime(t))
        self.assertEqual(t, t2)


if __name__ == "__main__":
    Testing.main([(TestTimeUtility, 'test')])
Пример #38
0
# This tests vtkAMRExtractLevel

import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot

VTK_DATA_ROOT = vtkGetDataRoot()

class TestAMRExtractLevel(Testing.vtkTest):
  def testAMR(self):
    filename= VTK_DATA_ROOT +"/Data/AMR/Enzo/DD0010/moving7_0010.hierarchy"
    level = 1

    reader = vtk.vtkAMREnzoReader()
    reader.SetFileName(filename)
    reader.SetMaxLevel(10)
    reader.SetCellArrayStatus("TotalEnergy",1)

    filter = vtk.vtkExtractLevel()
    filter.AddLevel(level)

    filter.SetInputConnection(reader.GetOutputPort())
    filter.Update()

    amr  = reader.GetOutputDataObject(0)
    out = filter.GetOutputDataObject(0)
    self.assertEqual(out.GetNumberOfBlocks(), amr.GetNumberOfDataSets(level))

if __name__ == "__main__":
    Testing.main([(TestAMRExtractLevel, 'test')])
Пример #39
0
        renWin.SetSize(600, 600)
        ren.SetBackground(0.1, 0.1, 0.2)

        current_widget = planeWidgetZ
        mode_widget = planeWidgetZ

        # Set the interactor for the widgets
        iact = vtk.vtkRenderWindowInteractor()
        iact.SetRenderWindow(renWin)
        planeWidgetX.SetInteractor(iact)
        planeWidgetX.On()
        planeWidgetY.SetInteractor(iact)
        planeWidgetY.On()
        planeWidgetZ.SetInteractor(iact)
        planeWidgetZ.On()

        # Create an initial interesting view
        ren.ResetCamera()
        cam1 = ren.GetActiveCamera()
        cam1.Elevation(110)
        cam1.SetViewUp(0, 0, -1)
        cam1.Azimuth(45)
        ren.ResetCameraClippingRange()

        iact.Initialize()
        renWin.Render()


if __name__ == "__main__":
    Testing.main([(TestMapperLUT, 'test')])
Пример #40
0
                self.assertEqual(len(z1.shape), 1)
            self.assertEqual(sum(numpy.ravel(z) - numpy.ravel(z1)), 0)

    def testNumpyView(self):
        "Test if the numpy and VTK array share the same data."
        # ----------------------------------------
        # Test if the array is copied or not.
        a = numpy.array([[1, 2, 3],[4, 5, 6]], 'd')
        vtk_arr = numpy_to_vtk(a)
        # Change the numpy array and see if the changes are
        # reflected in the VTK array.
        a[0] = [10.0, 20.0, 30.0]
        self.assertEqual(vtk_arr.GetTuple3(0), (10., 20., 30.))

    def testExceptions(self):
        "Test if the right assertion errors are raised."
        # Test if bit arrays raise an exception.
        vtk_arr = vtk.vtkBitArray()
        vtk_arr.InsertNextValue(0)
        vtk_arr.InsertNextValue(1)
        self.assertRaises(AssertionError, vtk_to_numpy, vtk_arr)
        # Test if non-contiguous arrays are not supported.
        a = numpy.linspace(0, 1, 100)
        a.shape = (10, 10)
        x = a[::2,::2]
        self.assertRaises(AssertionError, numpy_to_vtk, x)

if __name__ == "__main__":
    Testing.main([(TestNumpySupport, 'test')])

    if a - i <= 0.5:
        return i
    else:
        return i + 1


class TestTemporalSnapToTimeStep(Testing.vtkTest):
    def test(self):
        source = vtk.vtkTemporalFractal()
        source.DiscreteTimeStepsOn()

        shift = vtk.vtkTemporalSnapToTimeStep()
        shift.SetInputConnection(source.GetOutputPort())

        shift.UpdateInformation()
        executive = shift.GetExecutive()
        for i in range(4):
            inTime = i * 0.5 + 0.1
            executive.SetUpdateTimeStep(0, inTime)
            executive.Update()
            self.assertEqual(
                shift.GetOutputDataObject(0).GetInformation().Has(
                    vtk.vtkDataObject.DATA_TIME_STEP()), True)
            outTime = shift.GetOutputDataObject(0).GetInformation().Get(
                vtk.vtkDataObject.DATA_TIME_STEP())
            self.assertEqual(outTime == Nearest(inTime), True)


if __name__ == "__main__":
    Testing.main([(TestTemporalSnapToTimeStep, 'test')])
Пример #42
0
import sys

try:
    import numpy
except ImportError:
    print("Numpy (http://numpy.scipy.org) not found.")
    print("This test requires numpy!")
    from vtk.test import Testing
    Testing.skip()

import vtk
from vtk.numpy_interface import dataset_adapter as dsa
from vtk.numpy_interface import algorithms as algs

def test_dataset(ds):
  p2c = vtk.vtkPointDataToCellData()
  p2c.SetInputData(ds)
  p2c.Update()

  c2p = vtk.vtkCellDataToPointData()
  c2p.SetInputConnection(p2c.GetOutputPort())
  c2p.Update()

  d1 = dsa.WrapDataObject(c2p.GetOutput())

  c2p = vtk.vtkmAverageToPoints()
  c2p.SetInputData(p2c.GetOutput())
  c2p.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, "RTData")
  c2p.Update()

  d2 = dsa.WrapDataObject(c2p.GetOutput())
Пример #43
0
        cam.Elevation(20)
        cam.Zoom(1.5)

        ren.SetBackground(0.5, 0.5, 0.5)
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        renWin.Render()
        
        img_file = "TestTensorGlyph.png"
        Testing.compareImage(renWin, Testing.getAbsImagePath(img_file))
        Testing.interact()

    def testParse(self):
        "Test if vtkTensorGlyph is parseable"
        tg = vtk.vtkTensorGlyph()
        self._testParse(tg)

    def testGetSet(self):
        "Testing Get/Set methods of vtkTensorGlyph"
        tg = vtk.vtkTensorGlyph()
        self._testGetSet(tg)

    def testParse(self):
        "Testing Boolean methods of vtkTensorGlyph"
        tg = vtk.vtkTensorGlyph()
        self._testBoolean(tg)


if __name__ == "__main__":
    Testing.main([(TestTensorGlyph, 'test')])
Пример #44
0
        grad.Update()

        vals = (10, 0, 0)

        for i in range(3):
            r = grad.GetOutput().GetPointData().GetArray("Gradients").GetRange(i)

            self.assertTrue(abs(r[0] - vals[i]) < 1E-4)
            self.assertTrue(abs(r[1] - vals[i]) < 1E-4)

        elev.SetLowPoint(0.05, -0.05, 0)
        elev.SetHighPoint(0.05, 0.05, 0)
        grad.Update()

        vals = (0, 10, 0)

        for i in range(3):
            r = grad.GetOutput().GetPointData().GetArray("Gradients").GetRange(i)

            self.assertTrue(abs(r[0] - vals[i]) < 1E-4)
            self.assertTrue(abs(r[1] - vals[i]) < 1E-4)

    def testQuadraticQuad(self):
        self._test("/Data/Disc_QuadraticQuads_0_0.vtu")

    def testBiQuadraticQuad(self):
        self._test("/Data/Disc_BiQuadraticQuads_0_0.vtu")

if __name__ == "__main__":
    Testing.main([(TestCommand, 'test')])
Пример #45
0
        p1 = (0.0, 0.0, 0.0)
        p2 = (1.0, 1.0, 1.0)
        x = [0.0, 0.0, 0.0]
        vtk.vtkPlane.IntersectWithLine(p1, p2, n, p0, t, x)
        self.assertEqual(round(t,6), 0.5)
        self.assertEqual(round(x[0],6), 0.5)
        self.assertEqual(round(x[1],6), 0.5)
        self.assertEqual(round(x[2],6), 0.5)
        vtk.vtkPlane().IntersectWithLine(p1, p2, n, p0, t, x)
        self.assertEqual(round(t,6), 0.5)
        self.assertEqual(round(x[0],6), 0.5)
        self.assertEqual(round(x[1],6), 0.5)
        self.assertEqual(round(x[2],6), 0.5)
        t.set(0)
        p = vtk.vtkPlane()
        p.SetOrigin(0.5, 0.0, 0.0)
        p.SetNormal(1.0, 0.0, 0.0)
        p.IntersectWithLine(p1, p2, t, x)
        self.assertEqual(round(t,6), 0.5)
        self.assertEqual(round(x[0],6), 0.5)
        self.assertEqual(round(x[1],6), 0.5)
        self.assertEqual(round(x[2],6), 0.5)
        vtk.vtkPlane.IntersectWithLine(p, p1, p2, t, x)
        self.assertEqual(round(t,6), 0.5)
        self.assertEqual(round(x[0],6), 0.5)
        self.assertEqual(round(x[1],6), 0.5)
        self.assertEqual(round(x[2],6), 0.5)

if __name__ == "__main__":
    Testing.main([(TestMutable, 'test')])
Пример #46
0
    mapper.ScalarVisibilityOff()
    head = vtk.vtkActor()
    head.SetMapper(mapper)
    head.GetProperty().SetColor(1,0.7,0.6)
    # Create the RenderWindow, Renderer and Interactor
    #
    ren1 = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    # Add the actors to the renderer, set the background and size
    #
    ren1.AddActor(head)
    ren1.SetBackground(1,1,1)
    renWin.SetSize(400,400)
    ren1.SetBackground(0.5,0.5,0.6)
    ren1.GetActiveCamera().SetPosition(99.8847,537.926,15)
    ren1.GetActiveCamera().SetFocalPoint(99.8847,109.81,15)
    ren1.GetActiveCamera().SetViewAngle(20)
    ren1.GetActiveCamera().SetViewUp(0,0,-1)
    ren1.ResetCameraClippingRange()
    # render the image
    #
    renWin.Render()
    # prevent the tk window from showing up then start the event loop
    # --- end of script --

if __name__ == "__main__":
  Testing.main([(TestSynchronizedTemplates3D, 'test')])
Пример #47
0
    def testImagePlaneWidget(self):
        "A more rigorous test using the image plane widget."
        # This test is largely copied from
        # Widgets/Python/TestImagePlaneWidget.py

        # Load some data.
        v16 = vtk.vtkVolume16Reader()
        v16.SetDataDimensions(64, 64)
        v16.SetDataByteOrderToLittleEndian()
        v16.SetFilePrefix(os.path.join(Testing.VTK_DATA_ROOT,
                                       "Data", "headsq", "quarter"))
        v16.SetImageRange(1, 93)
        v16.SetDataSpacing(3.2, 3.2, 1.5)
        v16.Update()

        xMin, xMax, yMin, yMax, zMin, zMax = v16.GetExecutive().GetWholeExtent(v16.GetOutputInformation(0))
        img_data = v16.GetOutput()
        spacing = img_data.GetSpacing()
        sx, sy, sz = spacing

        origin = img_data.GetOrigin()
        ox, oy, oz = origin

        # An outline is shown for context.
        outline = vtk.vtkOutlineFilter()
        outline.SetInputData(img_data)

        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())

        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)

        # The shared picker enables us to use 3 planes at one time
        # and gets the picking order right
        picker = vtk.vtkCellPicker()
        picker.SetTolerance(0.005)

        # The 3 image plane widgets are used to probe the dataset.
        planeWidgetX = vtk.vtkImagePlaneWidget()
        planeWidgetX.DisplayTextOn()
        planeWidgetX.SetInputData(img_data)
        planeWidgetX.SetPlaneOrientationToXAxes()
        planeWidgetX.SetSliceIndex(32)
        planeWidgetX.SetPicker(picker)
        planeWidgetX.SetKeyPressActivationValue("x")
        prop1 = planeWidgetX.GetPlaneProperty()
        prop1.SetColor(1, 0, 0)

        planeWidgetY = vtk.vtkImagePlaneWidget()
        planeWidgetY.DisplayTextOn()
        planeWidgetY.SetInputData(img_data)
        planeWidgetY.SetPlaneOrientationToYAxes()
        planeWidgetY.SetSliceIndex(32)
        planeWidgetY.SetPicker(picker)
        planeWidgetY.SetKeyPressActivationValue("y")
        prop2 = planeWidgetY.GetPlaneProperty()
        prop2.SetColor(1, 1, 0)
        planeWidgetY.SetLookupTable(planeWidgetX.GetLookupTable())

        # for the z-slice, turn off texture interpolation:
        # interpolation is now nearest neighbour, to demonstrate
        # cross-hair cursor snapping to pixel centers
        planeWidgetZ = vtk.vtkImagePlaneWidget()
        planeWidgetZ.DisplayTextOn()
        planeWidgetZ.SetInputData(img_data)
        planeWidgetZ.SetPlaneOrientationToZAxes()
        planeWidgetZ.SetSliceIndex(46)
        planeWidgetZ.SetPicker(picker)
        planeWidgetZ.SetKeyPressActivationValue("z")
        prop3 = planeWidgetZ.GetPlaneProperty()
        prop3.SetColor(0, 0, 1)
        planeWidgetZ.SetLookupTable(planeWidgetX.GetLookupTable())

        # Now create another actor with an opacity < 1 and with some
        # scalars.
        p = vtk.vtkPolyData()
        pts = vtk.vtkPoints()
        pts.InsertNextPoint((0,0,0))
        sc = vtk.vtkFloatArray()
        sc.InsertNextValue(1.0)
        p.SetPoints(pts)
        p.GetPointData().SetScalars(sc)
        m = vtk.vtkPolyDataMapper()
        m.SetInputData(p)
        # Share the lookup table of the widgets.
        m.SetLookupTable(planeWidgetX.GetLookupTable())
        m.UseLookupTableScalarRangeOn()
        dummyActor = vtk.vtkActor()
        dummyActor.SetMapper(m)
        dummyActor.GetProperty().SetOpacity(0.0)

        # Create the RenderWindow and Renderer
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.SetMultiSamples(0)
        renWin.AddRenderer(ren)

        # Add the dummy actor.
        ren.AddActor(dummyActor)
        # Add the outline actor to the renderer, set the background
        # color and size
        ren.AddActor(outlineActor)
        renWin.SetSize(600, 600)
        ren.SetBackground(0.1, 0.1, 0.2)

        current_widget = planeWidgetZ
        mode_widget = planeWidgetZ

        # Set the interactor for the widgets
        iact = vtk.vtkRenderWindowInteractor()
        iact.SetRenderWindow(renWin)
        planeWidgetX.SetInteractor(iact)
        planeWidgetX.On()
        planeWidgetY.SetInteractor(iact)
        planeWidgetY.On()
        planeWidgetZ.SetInteractor(iact)
        planeWidgetZ.On()

        # Create an initial interesting view
        ren.ResetCamera();
        cam1 = ren.GetActiveCamera()
        cam1.Elevation(110)
        cam1.SetViewUp(0, 0, -1)
        cam1.Azimuth(45)
        ren.ResetCameraClippingRange()

        iact.Initialize()
        renWin.Render()

        # Compare the images and test.
        img_file = "TestImagePlaneWidget.png"
        Testing.compareImage(renWin, Testing.getAbsImagePath(img_file))
        # Interact if necessary.
        if Testing.isInteractive():
            iact.Start()
    def testBug(self):
        # Uncomment the next line if you want to run this via
        # `gdb python`.
        #raw_input('Hit Ctrl-C')

        # Load some data.
        v16 = vtk.vtkVolume16Reader()
        v16.SetDataDimensions(64, 64)
        v16.SetDataByteOrderToLittleEndian()
        v16.SetFilePrefix(os.path.join(Testing.VTK_DATA_ROOT,
                                       "Data", "headsq", "quarter"))
        v16.SetImageRange(1, 93)
        v16.SetDataSpacing(3.2, 3.2, 1.5)
        v16.Update()

        xMin, xMax, yMin, yMax, zMin, zMax = v16.GetOutput().GetWholeExtent()
        img_data = v16.GetOutput()

        # **************************************************
        # Look here for wierdness.

        # Lets create this data using the data from the reader.
        my_img_data = vtk.vtkImageData()
        my_img_data.SetDimensions(img_data.GetDimensions())
        my_img_data.SetWholeExtent(img_data.GetWholeExtent())
        my_img_data.SetExtent(img_data.GetExtent())
        my_img_data.SetUpdateExtent(img_data.GetUpdateExtent())
        my_img_data.SetSpacing(img_data.GetSpacing())
        my_img_data.SetOrigin(img_data.GetOrigin())
        my_img_data.SetScalarType(img_data.GetScalarType())
        my_img_data.GetPointData().SetScalars(img_data.GetPointData().GetScalars())
        my_img_data.Update()
        # hang on to original image data.
        orig_img_data = img_data

        # hijack img_data with our own.  If you comment this out everything is
        # fine.
        img_data = my_img_data
        # **************************************************

        spacing = img_data.GetSpacing()
        sx, sy, sz = spacing

        origin = img_data.GetOrigin()
        ox, oy, oz = origin

        # An outline is shown for context.
        outline = vtk.vtkOutlineFilter()
        outline.SetInput(img_data)

        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())

        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)

        # The shared picker enables us to use 3 planes at one time
        # and gets the picking order right
        picker = vtk.vtkCellPicker()
        picker.SetTolerance(0.005)

        # The 3 image plane widgets are used to probe the dataset.
        planeWidgetX = vtk.vtkImagePlaneWidget()
        planeWidgetX.DisplayTextOn()
        planeWidgetX.SetInput(img_data)
        planeWidgetX.SetPlaneOrientationToXAxes()
        planeWidgetX.SetSliceIndex(32)
        planeWidgetX.SetPicker(picker)
        planeWidgetX.SetKeyPressActivationValue("x")
        prop1 = planeWidgetX.GetPlaneProperty()
        prop1.SetColor(1, 0, 0)

        planeWidgetY = vtk.vtkImagePlaneWidget()
        planeWidgetY.DisplayTextOn()
        planeWidgetY.SetInput(img_data)
        planeWidgetY.SetPlaneOrientationToYAxes()
        planeWidgetY.SetSliceIndex(32)
        planeWidgetY.SetPicker(picker)
        planeWidgetY.SetKeyPressActivationValue("y")
        prop2 = planeWidgetY.GetPlaneProperty()
        prop2.SetColor(1, 1, 0)
        planeWidgetY.SetLookupTable(planeWidgetX.GetLookupTable())

        # for the z-slice, turn off texture interpolation:
        # interpolation is now nearest neighbour, to demonstrate
        # cross-hair cursor snapping to pixel centers
        planeWidgetZ = vtk.vtkImagePlaneWidget()
        planeWidgetZ.DisplayTextOn()
        planeWidgetZ.SetInput(img_data)
        planeWidgetZ.SetPlaneOrientationToZAxes()
        planeWidgetZ.SetSliceIndex(46)
        planeWidgetZ.SetPicker(picker)
        planeWidgetZ.SetKeyPressActivationValue("z")
        prop3 = planeWidgetZ.GetPlaneProperty()
        prop3.SetColor(0, 0, 1)
        planeWidgetZ.SetLookupTable(planeWidgetX.GetLookupTable())

        # Create the RenderWindow and Renderer
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)

        # Add the outline actor to the renderer, set the background
        # color and size
        ren.AddActor(outlineActor)
        renWin.SetSize(600, 600)
        ren.SetBackground(0.1, 0.1, 0.2)

        current_widget = planeWidgetZ
        mode_widget = planeWidgetZ

        # Set the interactor for the widgets
        iact = vtk.vtkRenderWindowInteractor()
        iact.SetRenderWindow(renWin)
        planeWidgetX.SetInteractor(iact)
        planeWidgetX.On()
        planeWidgetY.SetInteractor(iact)
        planeWidgetY.On()
        planeWidgetZ.SetInteractor(iact)
        planeWidgetZ.On()

        # Create an initial interesting view
        ren.ResetCamera();
        cam1 = ren.GetActiveCamera()
        cam1.Elevation(110)
        cam1.SetViewUp(0, 0, -1)
        cam1.Azimuth(45)
        ren.ResetCameraClippingRange()

        iact.Initialize()
        renWin.Render()

        # Compare the images and test.
        img_file = "TestImagePlaneWidget.png"
        Testing.compareImage(renWin, Testing.getAbsImagePath(img_file))
        # Interact if necessary.
        if Testing.isInteractive():
            iact.Start()
Пример #49
0
        renWin.SetSize(600, 600)
        ren.SetBackground(0.1, 0.1, 0.2)

        current_widget = planeWidgetZ
        mode_widget = planeWidgetZ

        # Set the interactor for the widgets
        iact = vtk.vtkRenderWindowInteractor()
        iact.SetRenderWindow(renWin)
        planeWidgetX.SetInteractor(iact)
        planeWidgetX.On()
        planeWidgetY.SetInteractor(iact)
        planeWidgetY.On()
        planeWidgetZ.SetInteractor(iact)
        planeWidgetZ.On()

        # Create an initial interesting view
        ren.ResetCamera()
        cam1 = ren.GetActiveCamera()
        cam1.Elevation(110)
        cam1.SetViewUp(0, 0, -1)
        cam1.Azimuth(45)
        ren.ResetCameraClippingRange()

        iact.Initialize()
        renWin.Render()


if __name__ == "__main__":
    Testing.main([(TestMapperLUT, "test")])
Пример #50
0
    # assign our actor to the renderer
    ren.AddActor(act)

    def testvtkTkRenderWidget(self):
        "Test if vtkTkRenderWidget works."
        self.rw.Render()
        self.root.update()
        img_file = "TestTkRenderWidget.png"
        Testing.compareImage(self.rw, Testing.getAbsImagePath(img_file))
        Testing.interact()

    # Dummy tests to demonstrate how the blackbox tests can be done.
    def testParse(self):
        "Test if vtkActor is parseable"
        self._testParse(self.act)

    def testGetSet(self):
        "Testing Get/Set methods"
        self._testGetSet(self.act, excluded_methods="AllocatedRenderTime")

    def testBoolean(self):
        "Testing Boolean methods"
        self._testBoolean(self.act)


if __name__ == "__main__":
    cases = [(TestTkRenderWidget, 'test')]
    del TestTkRenderWidget
    Testing.main(cases)
Пример #51
0
        be set to the string 'string0'.
        """
        self.onErrorCalldata = ''

        @vtk.calldata_type('string0')
        def onError(caller, event, calldata):
            self.onErrorCalldata = calldata

        lt = vtk.vtkLookupTable()
        lt.AddObserver(vtk.vtkCommand.ErrorEvent, onError)
        lt.SetTableRange(2, 1)
        self.assertTrue(self.onErrorCalldata.startswith("ERROR: In"))

    def testUseCallDataTypeWithDecorator(self):
        """Test adding an observer associated with a callback expecting a CallData
        """
        self.onErrorCalldata = ''

        @vtk.calldata_type(vtk.VTK_STRING)
        def onError(caller, event, calldata):
            self.onErrorCalldata = calldata

        lt = vtk.vtkLookupTable()
        lt.AddObserver(vtk.vtkCommand.ErrorEvent, onError)
        lt.SetTableRange(2, 1)
        self.assertTrue(self.onErrorCalldata.startswith("ERROR: In"))


if __name__ == "__main__":
    Testing.main([(TestCommand, 'test')])
Пример #52
0
            counter += 1
        self.assertEqual(counter, 30)

        counter = 0
        for _ in self.emptyCollection:
           counter += 1
        self.assertEqual(counter, 0)

    def testCollectionChild(self):
        #check that iteration is being inherited correctly
        dataArray = vtk.vtkIntArray()

        dataArrayCollection = vtk.vtkDataArrayCollection()
        dataArrayCollection.AddItem(dataArray)

        self.assertEqual([obj for obj in dataArrayCollection],
                         [dataArray])

    def testOperators(self):
        self.assertTrue(self.vtkObjs[0] in self.collection)
        self.assertEqual(list(self.collection), self.vtkObjs)

    def testReferenceCounting(self):
        initialReferenceCount = self.collection.GetReferenceCount()
        list(self.collection)
        self.assertEqual(self.collection.GetReferenceCount(), initialReferenceCount)


if __name__ == "__main__":
    Testing.main([(TestIterateCollection, 'test')])
Пример #53
0
    p2d = vtk.vtkPistonToDataSet()
    p2d.SetInputConnection(contourF.GetOutputPort())
    p2d.SetOutputDataSetType(vtk.VTK_POLY_DATA)
    p2d.Update()

    if writefiles:
        writeFile(p2d, "piston_sortcontour.vtk")

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(p2d.GetOutputPort())
    mapper.Update()

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

    renderer.AddActor(actor)

    renderer.ResetCamera()
    renwin.Render()

    img_file = "TestSort.png"
    Testing.compareImage(renwin, Testing.getAbsImagePath(img_file))

    if Testing.isInteractive():
        iren.Start()

if __name__ == "__main__":
    global args
    args = parseArgs()
    Testing.main([(TestSort, 'test')])
    mapper.ScalarVisibilityOff()
    head = vtk.vtkActor()
    head.SetMapper(mapper)
    head.GetProperty().SetColor(1,0.7,0.6)
    # Create the RenderWindow, Renderer and Interactor
    #
    ren1 = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    # Add the actors to the renderer, set the background and size
    #
    ren1.AddActor(head)
    ren1.SetBackground(1,1,1)
    renWin.SetSize(400,400)
    ren1.SetBackground(0.5,0.5,0.6)
    ren1.GetActiveCamera().SetPosition(99.8847,537.926,15)
    ren1.GetActiveCamera().SetFocalPoint(99.8847,109.81,15)
    ren1.GetActiveCamera().SetViewAngle(20)
    ren1.GetActiveCamera().SetViewUp(0,0,-1)
    ren1.ResetCameraClippingRange()
    # render the image
    #
    renWin.Render()
    # prevent the tk window from showing up then start the event loop
    # --- end of script --

if __name__ == "__main__":
  Testing.main([(TestSynchronizedTemplates3D, 'test')])
        # Set the interactor for the widgets
        iact = vtk.vtkRenderWindowInteractor()
        iact.SetRenderWindow(renWin)
        planeWidgetX.SetInteractor(iact)
        planeWidgetX.On()
        planeWidgetY.SetInteractor(iact)
        planeWidgetY.On()
        planeWidgetZ.SetInteractor(iact)
        planeWidgetZ.On()

        # Create an initial interesting view
        ren.ResetCamera();
        cam1 = ren.GetActiveCamera()
        cam1.Elevation(110)
        cam1.SetViewUp(0, 0, -1)
        cam1.Azimuth(45)
        ren.ResetCameraClippingRange()

        iact.Initialize()
        renWin.Render()

        # Compare the images and test.
        img_file = "TestImagePlaneWidget.png"
        Testing.compareImage(renWin, Testing.getAbsImagePath(img_file))
        # Interact if necessary.
        if Testing.isInteractive():
            iact.Start()

if __name__ == "__main__":
    Testing.main([(TestImagePlaneWidget, 'test')])
Пример #56
0
        p2d = vtk.vtkPistonToDataSet()
        p2d.SetInputConnection(threshF.GetOutputPort())
        p2d.SetOutputDataSetType(vtk.VTK_POLY_DATA)

        if writefiles:
            writeFile(p2d, "piston_threshold.vtk")

        mapper = vtk.vtkPistonMapper()
        mapper.SetInputConnection(threshF.GetOutputPort())
        mapper.Update()

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

        renderer.AddActor(actor)

        renderer.ResetCamera()
        renwin.Render()

        img_file = "TestThreshold.png"
        Testing.compareImage(renwin, Testing.getAbsImagePath(img_file))

        if Testing.isInteractive():
            iren.Start()


if __name__ == "__main__":
    global args
    args = parseArgs()
    Testing.main([(TestThreshold, 'test')])
Пример #57
0
        self.assertEqual((v[0], v[1], v[2]), (3, 4, 5))
        v = vtk.vtkVector3d(6)
        self.assertEqual((v[0], v[1], v[2]), (6, 6, 6))
        # resolve by argument type
        v = vtk.vtkVariant(3.0)
        self.assertEqual(v.GetType(), vtk.VTK_DOUBLE)
        v = vtk.vtkVariant(1)
        self.assertEqual(v.GetType(), vtk.VTK_INT)
        v = vtk.vtkVariant("hello")
        self.assertEqual(v.GetType(), vtk.VTK_STRING)
        v = vtk.vtkVariant(vtk.vtkObject())
        self.assertEqual(v.GetType(), vtk.VTK_OBJECT)

    def testArgumentConversion(self):
        """Test argument conversion via implicit constructors"""
        # automatic conversion to vtkVariant
        a = vtk.vtkVariantArray()
        a.InsertNextValue(2.5)
        a.InsertNextValue(vtk.vtkObject())
        self.assertEqual(a.GetValue(0), vtk.vtkVariant(2.5))
        self.assertEqual(a.GetValue(1).GetType(), vtk.VTK_OBJECT)
        # same, but this one is via "const vtkVariant&" argument
        a = vtk.vtkDenseArray[float]()
        a.Resize(1)
        a.SetVariantValue(0, 2.5)
        self.assertEqual(a.GetVariantValue(0).ToDouble(), 2.5)


if __name__ == "__main__":
    Testing.main([(TestOverloads, 'test')])
Пример #58
0
  def testQVTKWidget(self):

    w2 = vtk.QVTKWidget()
    w2.resize(500,500)

    ren = vtk.vtkRenderer()
    ren.SetBackground(0,0,0)
    ren.SetBackground2(1,1,1)
    ren.SetGradientBackground(1)
    win2 = vtk.vtkRenderWindow()
    win2.AddRenderer(ren)
    w2.SetRenderWindow(win2)

    renwin = w2.GetRenderWindow()
    cone = vtk.vtkConeSource()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInput(cone.GetOutput())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    ren.AddViewProp(actor)
    ren.ResetCamera()

    w2.show()
    if Testing.isInteractive():
      PyQt4.QtGui.qApp.exec_()


if __name__ == "__main__":
  app = PyQt4.QtGui.QApplication(sys.argv)
  Testing.main([(TestQVTKWidget, 'test')])
Пример #59
0
        spacing = (3.0, 2.0, 1.0)
        a.SetDataSpacing(spacing)
        a.UpdateInformation()
        info = a.GetOutputInformation(0)
        t = info.Get(vtk.vtkDataObject.SPACING())
        self.assertEqual(t, spacing)

    def testArrayIterator(self):
        # try a string array
        a = vtk.vtkStringArray()
        a.InsertNextValue("hello")
        i = a.NewIterator()
        self.assertEqual(a.GetValue(0), i.GetValue(0))
        # try the various data array subclasses
        for arrayClass in arrays:
            a = arrayClass()
            a.SetNumberOfComponents(2)
            a.SetNumberOfTuples(1)
            tupleIn = (a.GetDataTypeValueMin(), a.GetDataTypeValueMax())
            a.SetTypedTuple(0, tupleIn)
            i = a.NewIterator()
            # make sure iterator's GetTuple method is wrapped
            tupleOut = i.GetTuple(0)
            self.assertEqual(tupleIn, tupleOut)
            # make sure the GetValue method returns expected result
            self.assertEqual(tupleIn[0], i.GetValue(0))
            self.assertEqual(tupleIn[1], i.GetValue(1))

if __name__ == "__main__":
    Testing.main([(TestArrayArguments, 'test')])
Пример #60
0
        self.assertEqual(round(t,6), 0.5)
        self.assertEqual(round(x[0],6), 0.5)
        self.assertEqual(round(x[1],6), 0.5)
        self.assertEqual(round(x[2],6), 0.5)
        t.set(0)
        p = vtk.vtkPlane()
        p.SetOrigin(0.5, 0.0, 0.0)
        p.SetNormal(1.0, 0.0, 0.0)
        p.IntersectWithLine(p1, p2, t, x)
        self.assertEqual(round(t,6), 0.5)
        self.assertEqual(round(x[0],6), 0.5)
        self.assertEqual(round(x[1],6), 0.5)
        self.assertEqual(round(x[2],6), 0.5)
        vtk.vtkPlane.IntersectWithLine(p, p1, p2, t, x)
        self.assertEqual(round(t,6), 0.5)
        self.assertEqual(round(x[0],6), 0.5)
        self.assertEqual(round(x[1],6), 0.5)
        self.assertEqual(round(x[2],6), 0.5)

    def testPassTupleByReference(self):
        n = vtk.reference(0)
        t = vtk.reference((0,))
        ca = vtk.vtkCellArray()
        ca.InsertNextCell(3, (1, 3, 0))
        ca.GetCell(0, n, t)
        self.assertEqual(n, 3)
        self.assertEqual(tuple(t), (1, 3, 0))

if __name__ == "__main__":
    Testing.main([(TestPassByReference, 'test')])