def create_stream_line(self,y1,y2,y3,n,r=10):

        seeds = vtk.vtkPointSource()
        seeds.SetNumberOfPoints(n)
        seeds.SetCenter(y1, y2, y3)
        seeds.SetRadius(r)
        seeds.SetDistributionToShell()



        integ = vtk.vtkRungeKutta4()
        streamline = vtk.vtkStreamLine()
        streamline.SetInputConnection(self.vec_reader.GetOutputPort())
        streamline.SetSourceConnection(seeds.GetOutputPort())
        streamline.SetMaximumPropagationTime(220)
        streamline.SetIntegrationStepLength(0.05)
        streamline.SetStepLength(0.5)
        streamline.SpeedScalarsOn()
        streamline.SetNumberOfThreads(1)
        streamline.SetIntegrationDirectionToIntegrateBothDirections()

        streamline.SetIntegrator(integ)
        streamline.SetSpeedScalars(220);

        streamlineMapper = vtk.vtkPolyDataMapper()
        streamlineMapper.SetInputConnection(streamline.GetOutputPort())
        streamlineMapper.SetLookupTable(self.arrowColor)


        streamline_actor = vtk.vtkActor()
        streamline_actor.SetMapper(streamlineMapper)
        streamline_actor.VisibilityOn()

        return streamline_actor
Ejemplo n.º 2
0
 def mod_integ(self, lastinteg):
     if lastinteg == "2":
         integ = vtk.vtkRungeKutta2()
     elif lastinteg == "4":
         integ = vtk.vtkRungeKutta4()
     elif lastinteg == "4-5":
         integ = vtk.vtkRungeKutta45()
     else:
         integ = None
         self.data_error('Runge-Kutta Method order not selected')
     if integ is not None:
         self.lin.SetIntegrator(integ)
Ejemplo n.º 3
0
 def update_integration_mode (self):
     debug ("In PointStreamer::update_integration_mode ()")
     Common.state.busy ()
     val = self.integration_mode
     try:
         if val == 2:
             self.strmln.SetIntegrator (vtk.vtkRungeKutta2 ())
         elif val == 4:
             self.strmln.SetIntegrator (vtk.vtkRungeKutta4 ())
     except AttributeError, err:            
         msg = "Sorry unable to change the integration type. "\
               "Try upgrading your VTK installation to a more "\
               "recent version."
         Common.print_err (msg)            
    def create_stream_line(self,x,y,z,opa):

        rake = vtk.vtkLineSource()
        rake.SetPoint1(x, -y, z)
        rake.SetPoint2(x, y, z)
        rake.SetResolution(150)

        """
        rake_mapper = vtk.vtkPolyDataMapper()
        rake_mapper.SetInputConnection(rake.GetOutputPort())
        rake_actor = vtk.vtkActor()
        rake_actor.SetMapper(rake_mapper)
        self.ren.AddActor(rake_actor)
        """

        integ = vtk.vtkRungeKutta4()
        streamline = vtk.vtkStreamLine()
        streamline.SetInputConnection(self.vec_reader.GetOutputPort())
        streamline.SetSourceConnection(rake.GetOutputPort())
        streamline.SetIntegrator(integ)
        streamline.SetMaximumPropagationTime(300)
        streamline.SetIntegrationStepLength(0.01)
        streamline.SetIntegrationDirectionToForward()
        streamline.SpeedScalarsOn()
        streamline.SetStepLength(0.05)

        scalarSurface = vtk.vtkRuledSurfaceFilter()
        scalarSurface.SetInputConnection(streamline.GetOutputPort())
        #scalarSurface.SetOffset(0)
        scalarSurface.SetOnRatio(1)
        scalarSurface.PassLinesOn()
        scalarSurface.SetRuledModeToPointWalk()
        scalarSurface.SetDistanceFactor(30)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(scalarSurface.GetOutputPort())
        #mapper.SetScalarRange(self.vec_reader.GetOutput().GetScalarRange())
        mapper.SetLookupTable(self.arrowColor)

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetOpacity(opa)

        return actor
Ejemplo n.º 5
0
    def initStreamlines(self):
        print "initializing Streamlines"
        RK4 = vtk.vtkRungeKutta4()
        self.initSeedPoint()

        self.vtkStreamline = vtk.vtkStreamLine()
        self.vtkStreamline.SetInputData(self.vtkStructuredGrid)
        self.vtkStreamline.SetSourceConnection(self.vtkSeeds.GetOutputPort())
        self.vtkStreamline.SetMaximumPropagationTime(500)
        self.vtkStreamline.SetIntegrationStepLength(.2)
        self.vtkStreamline.SetStepLength(0.001)
        self.vtkStreamline.SetNumberOfThreads(1)
        self.vtkStreamline.SetIntegrationDirectionToIntegrateBothDirections()
        self.vtkStreamline.SetIntegrator(RK4)
        self.vtkStreamline.VorticityOn()

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(self.vtkStreamline.GetOutputPort())
        self.vtkFlowActor.SetMapper(mapper)
        self.vtkFlowActor.VisibilityOn()
    def create_stream_line(self,y1,y2,y3,n,r=10,tr=2):

        seeds = vtk.vtkPointSource()
        seeds.SetNumberOfPoints(n)
        seeds.SetCenter(y1, y2, y3)
        seeds.SetRadius(r)
        seeds.SetDistributionToShell()


        integ = vtk.vtkRungeKutta4()
        streamline = vtk.vtkStreamLine()
        streamline.SetInputConnection(self.vec_reader.GetOutputPort())
        streamline.SetSourceConnection(seeds.GetOutputPort())
        streamline.SetMaximumPropagationTime(220)
        streamline.SetIntegrationStepLength(0.05)
        streamline.SetStepLength(0.5)
        streamline.SpeedScalarsOn()
        streamline.SetNumberOfThreads(1)
        streamline.SetIntegrationDirectionToIntegrateBothDirections()
        streamline.SetIntegrator(integ)
        streamline.SetSpeedScalars(220);


        streamline_mapper = vtk.vtkPolyDataMapper()
        streamline_mapper.SetInputConnection(streamline.GetOutputPort())


        streamTube = vtk.vtkTubeFilter()
        streamTube.SetInputConnection(streamline.GetOutputPort())
        streamTube.SetRadius(tr)
        streamTube.SetNumberOfSides(12)
        streamTube.SetVaryRadiusToVaryRadiusByVector()
        mapStreamTube = vtk.vtkPolyDataMapper()
        mapStreamTube.SetInputConnection(streamTube.GetOutputPort())
        mapStreamTube.SetLookupTable(self.arrowColor)

        streamTubeActor = vtk.vtkActor()
        streamTubeActor.SetMapper(mapStreamTube)
        streamTubeActor.GetProperty().BackfaceCullingOn()

        return streamTubeActor
Ejemplo n.º 7
0
def read_vtk(name):
    import vtk
    import numpy

    gridreader = vtk.vtkXMLStructuredGridReader()
    gridreader.SetFileName(name)
    #gridreader.SetPointArrayStatus("Density",0)
    selection = gridreader.GetPointDataArraySelection()
    selection.DisableArray("Density")
    #selection.DisableArray("Velocity")
    selection.DisableArray("Phase")
    gridreader.Update()

    grid = gridreader.GetOutput()

    data = grid.GetPointData()
    points = grid.GetPoints()
    dims = grid.GetDimensions()
    #data.SetActiveScalars("Phase");
    data.SetActiveVectors("Velocity")
    #Create a contour
    contour = vtk.vtkContourFilter()
    contour.SetInputConnection(gridreader.GetOutputPort())
    contour.SetValue(0, 0.0)

    contourMapper = vtk.vtkPolyDataMapper()
    #contourMapper.SetScalarRange(phase.GetRange())
    contourMapper.SetInputConnection(contour.GetOutputPort())

    contourActor = vtk.vtkActor()
    contourActor.SetMapper(contourMapper)

    rake1 = vtk.vtkLineSource()
    rake1.SetPoint1(0, 0, 0)
    rake1.SetPoint2(0, 50, 0)
    rake1.SetResolution(21)
    rake1Mapper = vtk.vtkPolyDataMapper()
    rake1Mapper.SetInputConnection(rake1.GetOutputPort())
    rake1Actor = vtk.vtkActor()
    rake1Actor.SetMapper(rake1Mapper)

    rake2 = vtk.vtkLineSource()
    rake2.SetPoint1(0, 0, 850)
    rake2.SetPoint2(0, 50, 850)
    rake2.SetResolution(21)
    rake2Mapper = vtk.vtkPolyDataMapper()
    rake2Mapper.SetInputConnection(rake2.GetOutputPort())
    rake2Actor = vtk.vtkActor()
    rake2Actor.SetMapper(rake2Mapper)

    lines = vtk.vtkAppendPolyData()
    lines.AddInput(rake1.GetOutput())
    lines.AddInput(rake2.GetOutput())
    rk4 = vtk.vtkRungeKutta4()
    streamer = vtk.vtkStreamLine()
    streamer.SetInputConnection(gridreader.GetOutputPort())
    streamer.SetSource(lines.GetOutput())
    streamer.SetMaximumPropagationTime(100000)
    #streamer.GetStepLengthMinValue()=0.01
    #streamer.GetStepLengthMaxValue()=0.5
    #streamer.SetTerminalSpeed(1e-13)
    streamer.SetIntegrationStepLength(.2)
    streamer.SetStepLength(.2)
    #streamer.SetNumberOfThreads(1)
    streamer.SetIntegrationDirectionToIntegrateBothDirections()
    #streamer.VorticityOn()
    streamer.SetIntegrator(rk4)

    plane = vtk.vtkPlane()
    #plane.SetInput(grid)
    #plane.SetResolution(50, 50)
    plane.SetOrigin(25.0, 10.0, 0.0)
    plane.SetNormal(1.0, 0.0, 0.0)

    cutter = vtk.vtkCutter()
    cutter.SetCutFunction(plane)
    cutter.SetInput(grid)
    cutter.Update()

    cutterMapper = vtk.vtkPolyDataMapper()
    cutterMapper.SetInputConnection(cutter.GetOutputPort(0))

    # Create plane actor
    planeActor = vtk.vtkActor()
    planeActor.GetProperty().SetColor(1.0, 1, 0)
    planeActor.GetProperty().SetLineWidth(2)
    planeActor.SetMapper(cutterMapper)

    #transP1 = vtk.vtkTransform()
    #transP1.Translate(3.7, 0.0, 28.37)
    #transP1.Scale(5, 5, 5)
    #transP1.RotateY(90)
    #tpd1 = vtk.vtkTransformPolyDataFilter()
    #tpd1.SetInputConnection(plane.GetOutputPort())
    #tpd1.SetTransform(transP1)
    #tpd1Actor.GetProperty().SetColor(0, 0, 0)

    #lineWidget = vtk.vtkLineWidget()
    #seeds = vtk.vtkPolyData()
    #lineWidget.SetInput(grid)
    #lineWidget.SetAlignToYAxis()
    #lineWidget.PlaceWidget()
    #lineWidget.GetPolyData(seeds)
    #lineWidget.ClampToBoundsOn()

    streamMapper = vtk.vtkPolyDataMapper()
    streamMapper.SetInputConnection(streamer.GetOutputPort())
    #streamMapper.SetScalarRange(data.GetOutput().GetScalarRange())
    streamActor = vtk.vtkActor()
    streamActor.SetMapper(streamMapper)
    streamActor.VisibilityOn()

    #Create the outline
    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(gridreader.GetOutputPort())

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

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    #outlineActor.GetProperty().SetColor(0,0,0)

    # Create the Renderer, RenderWindow, and RenderWindowInteractor
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Add the actors to the render; set the background and size
    #ren.AddActor(contourActor)
    #ren.AddActor(outlineActor)
    ren.AddActor(streamActor)
    #ren.AddActor(rake1Actor)
    #ren.AddActor(rake2Actor)
    #ren.AddActor(planeActor)h=streamline(vz,vy,sz,sy,[0.1, 15000])
    #ren.SetBackground(1.0,1.0,1.0)
    ren.SetBackground(0.1, 0.2, 0.4)

    renWin.SetSize(500, 500)

    # Zoom in closer
    #ren.ResetCamera()
    cam1 = ren.GetActiveCamera()
    cam1.SetPosition(1000, 0, 500)
    cam1.SetFocalPoint(0, 0, 500)

    iren.Initialize()
    renWin.Render()
    iren.Start()
Ejemplo n.º 8
0
def main():
    fileName = get_program_parameters()

    colors = vtk.vtkNamedColors()
    # Set the furniture colors, matching those in the VTKTextBook.
    tableTopColor = [0.59, 0.427, 0.392]
    filingCabinetColor = [0.8, 0.8, 0.6]
    bookShelfColor = [0.8, 0.8, 0.6]
    windowColor = [0.3, 0.3, 0.5]
    colors.SetColor('TableTop', *tableTopColor)
    colors.SetColor('FilingCabinet', *filingCabinetColor)
    colors.SetColor('BookShelf', *bookShelfColor)
    colors.SetColor('WindowColor', *windowColor)

    # We read a data file that represents a CFD analysis of airflow in an office
    # (with ventilation and a burning cigarette). We force an update so that we
    # can query the output for its length, i.e., the length of the diagonal
    # of the bounding box. This is useful for normalizing the data.
    reader = vtk.vtkDataSetReader()
    reader.SetFileName(fileName)
    reader.Update()

    # Now we will generate a single streamline in the data. We select the
    # integration order to use (RungeKutta order 4) and associate it with
    # the streamer. The start position is the position in world space where
    # we want to begin streamline integration; and we integrate in both
    # directions. The step length is the length of the line segments that
    # make up the streamline (i.e., related to display). The
    # IntegrationStepLength specifies the integration step length as a
    # fraction of the cell size that the streamline is in.
    integ = vtk.vtkRungeKutta4()

    streamer = vtk.vtkStreamTracer()
    streamer.SetInputConnection(reader.GetOutputPort())
    streamer.SetStartPosition(0.1, 2.1, 0.5)
    streamer.SetMaximumPropagation(500)
    streamer.SetInitialIntegrationStep(0.05)
    streamer.SetIntegrationDirectionToBoth()
    streamer.SetIntegrator(integ)

    # The tube is wrapped around the generated streamline. By varying the radius
    # by the inverse of vector magnitude, we are creating a tube whose radius is
    # proportional to mass flux (in incompressible flow).
    streamTube = vtk.vtkTubeFilter()
    streamTube.SetInputConnection(streamer.GetOutputPort())
    streamTube.SetInputArrayToProcess(1, 0, 0,
                                      vtkDataObject.FIELD_ASSOCIATION_POINTS,
                                      'vectors')
    streamTube.SetRadius(0.02)
    streamTube.SetNumberOfSides(12)
    streamTube.SetVaryRadiusToVaryRadiusByVector()

    mapStreamTube = vtk.vtkPolyDataMapper()
    mapStreamTube.SetInputConnection(streamTube.GetOutputPort())
    mapStreamTube.SetScalarRange(
        reader.GetOutput().GetPointData().GetScalars().GetRange())

    streamTubeActor = vtk.vtkActor()
    streamTubeActor.SetMapper(mapStreamTube)
    streamTubeActor.GetProperty().BackfaceCullingOn()

    # Create the scene.
    # We generate a whole bunch of planes which correspond to
    # the geometry in the analysis; tables, bookshelves and so on.
    table1 = vtk.vtkStructuredGridGeometryFilter()
    table1.SetInputData(reader.GetStructuredGridOutput())
    table1.SetExtent(11, 15, 7, 9, 8, 8)
    mapTable1 = vtk.vtkPolyDataMapper()
    mapTable1.SetInputConnection(table1.GetOutputPort())
    mapTable1.ScalarVisibilityOff()
    table1Actor = vtk.vtkActor()
    table1Actor.SetMapper(mapTable1)
    table1Actor.GetProperty().SetColor(colors.GetColor3d('TableTop'))

    table2 = vtk.vtkStructuredGridGeometryFilter()
    table2.SetInputData(reader.GetStructuredGridOutput())
    table2.SetExtent(11, 15, 10, 12, 8, 8)
    mapTable2 = vtk.vtkPolyDataMapper()
    mapTable2.SetInputConnection(table2.GetOutputPort())
    mapTable2.ScalarVisibilityOff()
    table2Actor = vtk.vtkActor()
    table2Actor.SetMapper(mapTable2)
    table2Actor.GetProperty().SetColor(colors.GetColor3d('TableTop'))

    FilingCabinet1 = vtk.vtkStructuredGridGeometryFilter()
    FilingCabinet1.SetInputData(reader.GetStructuredGridOutput())
    FilingCabinet1.SetExtent(15, 15, 7, 9, 0, 8)
    mapFilingCabinet1 = vtk.vtkPolyDataMapper()
    mapFilingCabinet1.SetInputConnection(FilingCabinet1.GetOutputPort())
    mapFilingCabinet1.ScalarVisibilityOff()
    FilingCabinet1Actor = vtk.vtkActor()
    FilingCabinet1Actor.SetMapper(mapFilingCabinet1)
    FilingCabinet1Actor.GetProperty().SetColor(
        colors.GetColor3d('FilingCabinet'))

    FilingCabinet2 = vtk.vtkStructuredGridGeometryFilter()
    FilingCabinet2.SetInputData(reader.GetStructuredGridOutput())
    FilingCabinet2.SetExtent(15, 15, 10, 12, 0, 8)
    mapFilingCabinet2 = vtk.vtkPolyDataMapper()
    mapFilingCabinet2.SetInputConnection(FilingCabinet2.GetOutputPort())
    mapFilingCabinet2.ScalarVisibilityOff()
    FilingCabinet2Actor = vtk.vtkActor()
    FilingCabinet2Actor.SetMapper(mapFilingCabinet2)
    FilingCabinet2Actor.GetProperty().SetColor(
        colors.GetColor3d('FilingCabinet'))

    bookshelf1Top = vtk.vtkStructuredGridGeometryFilter()
    bookshelf1Top.SetInputData(reader.GetStructuredGridOutput())
    bookshelf1Top.SetExtent(13, 13, 0, 4, 0, 11)
    mapBookshelf1Top = vtk.vtkPolyDataMapper()
    mapBookshelf1Top.SetInputConnection(bookshelf1Top.GetOutputPort())
    mapBookshelf1Top.ScalarVisibilityOff()
    bookshelf1TopActor = vtk.vtkActor()
    bookshelf1TopActor.SetMapper(mapBookshelf1Top)
    bookshelf1TopActor.GetProperty().SetColor(colors.GetColor3d('BookShelf'))

    bookshelf1Bottom = vtk.vtkStructuredGridGeometryFilter()
    bookshelf1Bottom.SetInputData(reader.GetStructuredGridOutput())
    bookshelf1Bottom.SetExtent(20, 20, 0, 4, 0, 11)
    mapBookshelf1Bottom = vtk.vtkPolyDataMapper()
    mapBookshelf1Bottom.SetInputConnection(bookshelf1Bottom.GetOutputPort())
    mapBookshelf1Bottom.ScalarVisibilityOff()
    bookshelf1BottomActor = vtk.vtkActor()
    bookshelf1BottomActor.SetMapper(mapBookshelf1Bottom)
    bookshelf1BottomActor.GetProperty().SetColor(
        colors.GetColor3d('BookShelf'))

    bookshelf1Front = vtk.vtkStructuredGridGeometryFilter()
    bookshelf1Front.SetInputData(reader.GetStructuredGridOutput())
    bookshelf1Front.SetExtent(13, 20, 0, 0, 0, 11)
    mapBookshelf1Front = vtk.vtkPolyDataMapper()
    mapBookshelf1Front.SetInputConnection(bookshelf1Front.GetOutputPort())
    mapBookshelf1Front.ScalarVisibilityOff()
    bookshelf1FrontActor = vtk.vtkActor()
    bookshelf1FrontActor.SetMapper(mapBookshelf1Front)
    bookshelf1FrontActor.GetProperty().SetColor(colors.GetColor3d('BookShelf'))

    bookshelf1Back = vtk.vtkStructuredGridGeometryFilter()
    bookshelf1Back.SetInputData(reader.GetStructuredGridOutput())
    bookshelf1Back.SetExtent(13, 20, 4, 4, 0, 11)
    mapBookshelf1Back = vtk.vtkPolyDataMapper()
    mapBookshelf1Back.SetInputConnection(bookshelf1Back.GetOutputPort())
    mapBookshelf1Back.ScalarVisibilityOff()
    bookshelf1BackActor = vtk.vtkActor()
    bookshelf1BackActor.SetMapper(mapBookshelf1Back)
    bookshelf1BackActor.GetProperty().SetColor(colors.GetColor3d('BookShelf'))

    bookshelf1LHS = vtk.vtkStructuredGridGeometryFilter()
    bookshelf1LHS.SetInputData(reader.GetStructuredGridOutput())
    bookshelf1LHS.SetExtent(13, 20, 0, 4, 0, 0)
    mapBookshelf1LHS = vtk.vtkPolyDataMapper()
    mapBookshelf1LHS.SetInputConnection(bookshelf1LHS.GetOutputPort())
    mapBookshelf1LHS.ScalarVisibilityOff()
    bookshelf1LHSActor = vtk.vtkActor()
    bookshelf1LHSActor.SetMapper(mapBookshelf1LHS)
    bookshelf1LHSActor.GetProperty().SetColor(colors.GetColor3d('BookShelf'))

    bookshelf1RHS = vtk.vtkStructuredGridGeometryFilter()
    bookshelf1RHS.SetInputData(reader.GetStructuredGridOutput())
    bookshelf1RHS.SetExtent(13, 20, 0, 4, 11, 11)
    mapBookshelf1RHS = vtk.vtkPolyDataMapper()
    mapBookshelf1RHS.SetInputConnection(bookshelf1RHS.GetOutputPort())
    mapBookshelf1RHS.ScalarVisibilityOff()
    bookshelf1RHSActor = vtk.vtkActor()
    bookshelf1RHSActor.SetMapper(mapBookshelf1RHS)
    bookshelf1RHSActor.GetProperty().SetColor(colors.GetColor3d('BookShelf'))

    bookshelf2Top = vtk.vtkStructuredGridGeometryFilter()
    bookshelf2Top.SetInputData(reader.GetStructuredGridOutput())
    bookshelf2Top.SetExtent(13, 13, 15, 19, 0, 11)
    mapBookshelf2Top = vtk.vtkPolyDataMapper()
    mapBookshelf2Top.SetInputConnection(bookshelf2Top.GetOutputPort())
    mapBookshelf2Top.ScalarVisibilityOff()
    bookshelf2TopActor = vtk.vtkActor()
    bookshelf2TopActor.SetMapper(mapBookshelf2Top)
    bookshelf2TopActor.GetProperty().SetColor(colors.GetColor3d('BookShelf'))

    bookshelf2Bottom = vtk.vtkStructuredGridGeometryFilter()
    bookshelf2Bottom.SetInputData(reader.GetStructuredGridOutput())
    bookshelf2Bottom.SetExtent(20, 20, 15, 19, 0, 11)
    mapBookshelf2Bottom = vtk.vtkPolyDataMapper()
    mapBookshelf2Bottom.SetInputConnection(bookshelf2Bottom.GetOutputPort())
    mapBookshelf2Bottom.ScalarVisibilityOff()
    bookshelf2BottomActor = vtk.vtkActor()
    bookshelf2BottomActor.SetMapper(mapBookshelf2Bottom)
    bookshelf2BottomActor.GetProperty().SetColor(
        colors.GetColor3d('BookShelf'))

    bookshelf2Front = vtk.vtkStructuredGridGeometryFilter()
    bookshelf2Front.SetInputData(reader.GetStructuredGridOutput())
    bookshelf2Front.SetExtent(13, 20, 15, 15, 0, 11)
    mapBookshelf2Front = vtk.vtkPolyDataMapper()
    mapBookshelf2Front.SetInputConnection(bookshelf2Front.GetOutputPort())
    mapBookshelf2Front.ScalarVisibilityOff()
    bookshelf2FrontActor = vtk.vtkActor()
    bookshelf2FrontActor.SetMapper(mapBookshelf2Front)
    bookshelf2FrontActor.GetProperty().SetColor(colors.GetColor3d('BookShelf'))

    bookshelf2Back = vtk.vtkStructuredGridGeometryFilter()
    bookshelf2Back.SetInputData(reader.GetStructuredGridOutput())
    bookshelf2Back.SetExtent(13, 20, 19, 19, 0, 11)
    mapBookshelf2Back = vtk.vtkPolyDataMapper()
    mapBookshelf2Back.SetInputConnection(bookshelf2Back.GetOutputPort())
    mapBookshelf2Back.ScalarVisibilityOff()
    bookshelf2BackActor = vtk.vtkActor()
    bookshelf2BackActor.SetMapper(mapBookshelf2Back)
    bookshelf2BackActor.GetProperty().SetColor(colors.GetColor3d('BookShelf'))

    bookshelf2LHS = vtk.vtkStructuredGridGeometryFilter()
    bookshelf2LHS.SetInputData(reader.GetStructuredGridOutput())
    bookshelf2LHS.SetExtent(13, 20, 15, 19, 0, 0)
    mapBookshelf2LHS = vtk.vtkPolyDataMapper()
    mapBookshelf2LHS.SetInputConnection(bookshelf2LHS.GetOutputPort())
    mapBookshelf2LHS.ScalarVisibilityOff()
    bookshelf2LHSActor = vtk.vtkActor()
    bookshelf2LHSActor.SetMapper(mapBookshelf2LHS)
    bookshelf2LHSActor.GetProperty().SetColor(colors.GetColor3d('BookShelf'))

    bookshelf2RHS = vtk.vtkStructuredGridGeometryFilter()
    bookshelf2RHS.SetInputData(reader.GetStructuredGridOutput())
    bookshelf2RHS.SetExtent(13, 20, 15, 19, 11, 11)
    mapBookshelf2RHS = vtk.vtkPolyDataMapper()
    mapBookshelf2RHS.SetInputConnection(bookshelf2RHS.GetOutputPort())
    mapBookshelf2RHS.ScalarVisibilityOff()
    bookshelf2RHSActor = vtk.vtkActor()
    bookshelf2RHSActor.SetMapper(mapBookshelf2RHS)
    bookshelf2RHSActor.GetProperty().SetColor(colors.GetColor3d('BookShelf'))

    window = vtk.vtkStructuredGridGeometryFilter()
    window.SetInputData(reader.GetStructuredGridOutput())
    window.SetExtent(20, 20, 6, 13, 10, 13)
    mapWindow = vtk.vtkPolyDataMapper()
    mapWindow.SetInputConnection(window.GetOutputPort())
    mapWindow.ScalarVisibilityOff()
    windowActor = vtk.vtkActor()
    windowActor.SetMapper(mapWindow)
    windowActor.GetProperty().SetColor(colors.GetColor3d('WindowColor'))

    outlet = vtk.vtkStructuredGridGeometryFilter()
    outlet.SetInputData(reader.GetStructuredGridOutput())
    outlet.SetExtent(0, 0, 9, 10, 14, 16)
    mapOutlet = vtk.vtkPolyDataMapper()
    mapOutlet.SetInputConnection(outlet.GetOutputPort())
    mapOutlet.ScalarVisibilityOff()
    outletActor = vtk.vtkActor()
    outletActor.SetMapper(mapOutlet)
    outletActor.GetProperty().SetColor(colors.GetColor3d('lamp_black'))

    inlet = vtk.vtkStructuredGridGeometryFilter()
    inlet.SetInputData(reader.GetStructuredGridOutput())
    inlet.SetExtent(0, 0, 9, 10, 0, 6)
    mapInlet = vtk.vtkPolyDataMapper()
    mapInlet.SetInputConnection(inlet.GetOutputPort())
    mapInlet.ScalarVisibilityOff()
    inletActor = vtk.vtkActor()
    inletActor.SetMapper(mapInlet)
    inletActor.GetProperty().SetColor(colors.GetColor3d('lamp_black'))

    outline = vtk.vtkStructuredGridOutlineFilter()
    outline.SetInputData(reader.GetStructuredGridOutput())
    mapOutline = vtk.vtkPolyDataMapper()
    mapOutline.SetInputConnection(outline.GetOutputPort())
    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(mapOutline)
    outlineActor.GetProperty().SetColor(colors.GetColor3d('Black'))

    # Create the rendering window, renderer, and interactive renderer.
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Add the remaining actors to the renderer, set the background and size.
    ren.AddActor(table1Actor)
    ren.AddActor(table2Actor)
    ren.AddActor(FilingCabinet1Actor)
    ren.AddActor(FilingCabinet2Actor)
    ren.AddActor(bookshelf1TopActor)
    ren.AddActor(bookshelf1BottomActor)
    ren.AddActor(bookshelf1FrontActor)
    ren.AddActor(bookshelf1BackActor)
    ren.AddActor(bookshelf1LHSActor)
    ren.AddActor(bookshelf1RHSActor)
    ren.AddActor(bookshelf2TopActor)
    ren.AddActor(bookshelf2BottomActor)
    ren.AddActor(bookshelf2FrontActor)
    ren.AddActor(bookshelf2BackActor)
    ren.AddActor(bookshelf2LHSActor)
    ren.AddActor(bookshelf2RHSActor)
    ren.AddActor(windowActor)
    ren.AddActor(outletActor)
    ren.AddActor(inletActor)
    ren.AddActor(outlineActor)
    ren.AddActor(streamTubeActor)

    ren.SetBackground(colors.GetColor3d('SlateGray'))

    aCamera = vtk.vtkCamera()
    aCamera.SetClippingRange(0.726079, 36.3039)
    aCamera.SetFocalPoint(2.43584, 2.15046, 1.11104)
    aCamera.SetPosition(-4.76183, -10.4426, 3.17203)
    aCamera.ComputeViewPlaneNormal()
    aCamera.SetViewUp(0.0511273, 0.132773, 0.989827)
    aCamera.SetViewAngle(18.604)
    aCamera.Zoom(1.2)

    ren.SetActiveCamera(aCamera)

    renWin.SetSize(640, 400)
    renWin.SetWindowName('OfficeTube')

    iren.Initialize()
    iren.Start()
Ejemplo n.º 9
0
    def _plotInternal(self):
        """Overrides baseclass implementation."""
        # Preserve time and z axis for plotting these inof in rendertemplate
        projection = vcs.elements["projection"][self._gm.projection]
        taxis = self._originalData1.getTime()

        if self._originalData1.ndim > 2:
            zaxis = self._originalData1.getAxis(-3)
        else:
            zaxis = None

        # Streamline color
        if (not self._gm.coloredbyvector):
            ln_tmp = self._gm.linetype
            if ln_tmp is None:
                ln_tmp = "default"
            try:
                ln_tmp = vcs.getline(ln_tmp)
                lwidth = ln_tmp.width[0]  # noqa
                lcolor = ln_tmp.color[0]
                lstyle = ln_tmp.type[0]  # noqa
            except Exception:
                lstyle = "solid"  # noqa
                lwidth = 1.  # noqa
                lcolor = [0., 0., 0., 100.]
            if self._gm.linewidth is not None:
                lwidth = self._gm.linewidth  # noqa
            if self._gm.linecolor is not None:
                lcolor = self._gm.linecolor

        self._vtkPolyDataFilter.Update()
        polydata = self._vtkPolyDataFilter.GetOutput()

        dataLength = polydata.GetLength()

        if (not self._gm.evenlyspaced):
            # generate random seeds in a circle centered in the center of
            # the bounding box for the data.

            # by default vtkPointSource uses a global random source in vtkMath which is
            # seeded only once. It makes more sense to seed a random sequence each time you draw
            # the streamline plot.
            pointSequence = vtk.vtkMinimalStandardRandomSequence()
            pointSequence.SetSeedOnly(1177)  # replicate the seed from vtkMath

            seed = vtk.vtkPointSource()
            seed.SetNumberOfPoints(self._gm.numberofseeds)
            seed.SetCenter(polydata.GetCenter())
            seed.SetRadius(dataLength / 2.0)
            seed.SetRandomSequence(pointSequence)
            seed.Update()
            seedData = seed.GetOutput()

            # project all points to Z = 0 plane
            points = seedData.GetPoints()
            for i in range(0, points.GetNumberOfPoints()):
                p = list(points.GetPoint(i))
                p[2] = 0
                points.SetPoint(i, p)

        if (self._gm.integratortype == 0):
            integrator = vtk.vtkRungeKutta2()
        elif (self._gm.integratortype == 1):
            integrator = vtk.vtkRungeKutta4()
        else:
            if (self._gm.evenlyspaced):
                warnings.warn(
                    "You cannot use RungeKutta45 for evenly spaced streamlines."
                    "Using RungeKutta4 instead")
                integrator = vtk.vtkRungeKutta4()
            else:
                integrator = vtk.vtkRungeKutta45()

        if (self._gm.evenlyspaced):
            streamer = vtk.vtkEvenlySpacedStreamlines2D()
            streamer.SetStartPosition(self._gm.startseed)
            streamer.SetSeparatingDistance(self._gm.separatingdistance)
            streamer.SetSeparatingDistanceRatio(
                self._gm.separatingdistanceratio)
            streamer.SetClosedLoopMaximumDistance(
                self._gm.closedloopmaximumdistance)
        else:
            # integrate streamlines on normalized vector so that
            # IntegrationTime stores distance
            streamer = vtk.vtkStreamTracer()
            streamer.SetSourceData(seedData)
            streamer.SetIntegrationDirection(self._gm.integrationdirection)
            streamer.SetMinimumIntegrationStep(self._gm.minimumsteplength)
            streamer.SetMaximumIntegrationStep(self._gm.maximumsteplength)
            streamer.SetMaximumError(self._gm.maximumerror)
            streamer.SetMaximumPropagation(dataLength *
                                           self._gm.maximumstreamlinelength)

        streamer.SetInputData(polydata)
        streamer.SetInputArrayToProcess(0, 0, 0, 0, "vector")
        streamer.SetIntegrationStepUnit(self._gm.integrationstepunit)
        streamer.SetInitialIntegrationStep(self._gm.initialsteplength)
        streamer.SetMaximumNumberOfSteps(self._gm.maximumsteps)
        streamer.SetTerminalSpeed(self._gm.terminalspeed)
        streamer.SetIntegrator(integrator)

        # add arc_length to streamlines
        arcLengthFilter = vtk.vtkAppendArcLength()
        arcLengthFilter.SetInputConnection(streamer.GetOutputPort())

        arcLengthFilter.Update()
        streamlines = arcLengthFilter.GetOutput()

        # glyph seed points
        contour = vtk.vtkContourFilter()
        contour.SetInputConnection(arcLengthFilter.GetOutputPort())
        contour.SetValue(0, 0.001)
        if (streamlines.GetNumberOfPoints()):
            r = streamlines.GetPointData().GetArray("arc_length").GetRange()
            numberofglyphsoneside = self._gm.numberofglyphs // 2
            for i in range(1, numberofglyphsoneside):
                contour.SetValue(i, r[1] / numberofglyphsoneside * i)
        else:
            warnings.warn(
                "No streamlines created. "
                "The 'startseed' parameter needs to be inside the domain and "
                "not over masked data.")
        contour.SetInputArrayToProcess(0, 0, 0, 0, "arc_length")

        # arrow glyph source
        glyph2DSource = vtk.vtkGlyphSource2D()
        glyph2DSource.SetGlyphTypeToTriangle()
        glyph2DSource.SetRotationAngle(-90)
        glyph2DSource.SetFilled(self._gm.filledglyph)

        # arrow glyph adjustment
        transform = vtk.vtkTransform()
        transform.Scale(1., self._gm.glyphbasefactor, 1.)
        transformFilter = vtk.vtkTransformFilter()
        transformFilter.SetInputConnection(glyph2DSource.GetOutputPort())
        transformFilter.SetTransform(transform)
        transformFilter.Update()
        glyphLength = transformFilter.GetOutput().GetLength()

        #  drawing the glyphs at the seed points
        glyph = vtk.vtkGlyph2D()
        glyph.SetInputConnection(contour.GetOutputPort())
        glyph.SetInputArrayToProcess(1, 0, 0, 0, "vector")
        glyph.SetSourceData(transformFilter.GetOutput())
        glyph.SetScaleModeToDataScalingOff()
        glyph.SetScaleFactor(dataLength * self._gm.glyphscalefactor /
                             glyphLength)
        glyph.SetColorModeToColorByVector()

        glyphMapper = vtk.vtkPolyDataMapper()
        glyphMapper.SetInputConnection(glyph.GetOutputPort())
        glyphActor = vtk.vtkActor()
        glyphActor.SetMapper(glyphMapper)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(streamer.GetOutputPort())
        act = vtk.vtkActor()
        act.SetMapper(mapper)

        # color the streamlines and glyphs
        cmap = self.getColorMap()
        if (self._gm.coloredbyvector):
            numLevels = len(self._contourLevels) - 1
            while len(self._contourColors) < numLevels:
                self._contourColors.append(self._contourColors[-1])

            lut = vtk.vtkLookupTable()
            lut.SetNumberOfTableValues(numLevels)
            for i in range(numLevels):
                r, g, b, a = self.getColorIndexOrRGBA(cmap,
                                                      self._contourColors[i])
                lut.SetTableValue(i, r / 100., g / 100., b / 100., a / 100.)
            lut.SetVectorModeToMagnitude()
            if numpy.allclose(self._contourLevels[0], -1.e20):
                lmn = self._vectorRange[0]
            else:
                lmn = self._contourLevels[0][0]
            if numpy.allclose(self._contourLevels[-1], 1.e20):
                lmx = self._vectorRange[1]
            else:
                lmx = self._contourLevels[-1][-1]
            lut.SetRange(lmn, lmx)

            mapper.ScalarVisibilityOn()
            mapper.SetLookupTable(lut)
            mapper.UseLookupTableScalarRangeOn()
            mapper.SetScalarModeToUsePointFieldData()
            mapper.SelectColorArray("vector")

            glyphMapper.ScalarVisibilityOn()
            glyphMapper.SetLookupTable(lut)
            glyphMapper.UseLookupTableScalarRangeOn()
            glyphMapper.SetScalarModeToUsePointFieldData()
            glyphMapper.SelectColorArray("VectorMagnitude")
        else:
            mapper.ScalarVisibilityOff()
            glyphMapper.ScalarVisibilityOff()
            if isinstance(lcolor, (list, tuple)):
                r, g, b, a = lcolor
            else:
                r, g, b, a = cmap.index[lcolor]
            act.GetProperty().SetColor(r / 100., g / 100., b / 100.)
            glyphActor.GetProperty().SetColor(r / 100., g / 100., b / 100.)

        plotting_dataset_bounds = self.getPlottingBounds()
        vp = self._resultDict.get('ratio_autot_viewport', [
            self._template.data.x1, self._template.data.x2,
            self._template.data.y1, self._template.data.y2
        ])

        dataset_renderer, xScale, yScale = self._context().fitToViewport(
            act,
            vp,
            wc=plotting_dataset_bounds,
            geoBounds=self._vtkDataSetBoundsNoMask,
            geo=self._vtkGeoTransform,
            priority=self._template.data.priority,
            create_renderer=True)
        glyph_renderer, xScale, yScale = self._context().fitToViewport(
            glyphActor,
            vp,
            wc=plotting_dataset_bounds,
            geoBounds=self._vtkDataSetBoundsNoMask,
            geo=self._vtkGeoTransform,
            priority=self._template.data.priority,
            create_renderer=False)

        kwargs = {
            'vtk_backend_grid': self._vtkDataSet,
            'dataset_bounds': self._vtkDataSetBounds,
            'plotting_dataset_bounds': plotting_dataset_bounds,
            "vtk_dataset_bounds_no_mask": self._vtkDataSetBoundsNoMask,
            'vtk_backend_geo': self._vtkGeoTransform
        }
        if ('ratio_autot_viewport' in self._resultDict):
            kwargs["ratio_autot_viewport"] = vp
        self._resultDict.update(self._context().renderTemplate(
            self._template, self._data1, self._gm, taxis, zaxis, **kwargs))
        if (self._gm.coloredbyvector):
            self._resultDict.update(self._context().renderColorBar(
                self._template, self._contourLevels, self._contourColors, None,
                self.getColorMap()))

        if self._context().canvas._continents is None:
            self._useContinents = False
        if self._useContinents:
            continents_renderer, xScale, yScale = self._context(
            ).plotContinents(plotting_dataset_bounds, projection,
                             self._dataWrapModulo, vp,
                             self._template.data.priority, **kwargs)
        self._resultDict["vtk_backend_actors"] = [[
            act, plotting_dataset_bounds
        ]]
        self._resultDict["vtk_backend_luts"] = [[None, None]]
Ejemplo n.º 10
0
outline = vtk.vtkStructuredGridOutlineFilter()
outline.SetInputData(pl3d_output)

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

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

seeds = vtk.vtkLineSource()
seeds.SetPoint1(15, -5, 32)
seeds.SetPoint2(15, 5, 32)
seeds.SetResolution(10)

integ = vtk.vtkRungeKutta4()

sl = vtk.vtkStreamLine()
sl.SetIntegrator(integ)
sl.SetInputData(pl3d_output)
sl.SetSourceConnection(seeds.GetOutputPort())
sl.SetMaximumPropagationTime(0.1)
sl.SetIntegrationStepLength(0.1)
sl.SetIntegrationDirectionToBackward()
sl.SetStepLength(0.001)

tube = vtk.vtkTubeFilter()
tube.SetInputConnection(sl.GetOutputPort())
tube.SetRadius(0.1)

mapper = vtk.vtkPolyDataMapper()
Ejemplo n.º 11
0
ctf.SetTableRange(a,b)

# A plane for the seeds
plane = vtk.vtkPlaneSource()
plane.SetOrigin(xmi,math.ceil(ymi),zmi)
plane.SetPoint1(xma,math.ceil(ymi),zmi)
plane.SetPoint2(xmi,math.ceil(ymi),zma)
plane.SetXResolution(6)
plane.SetYResolution(6)

# Streamlines
stream = vtk.vtkStreamLine()
stream.SetSource(plane.GetOutput())
stream.SetInput(reader.GetOutput())
stream.SetIntegrationDirectionToForward()
stream.SetIntegrator(vtk.vtkRungeKutta4())
stream.SetStepLength(0.1)

streamMapper = vtk.vtkPolyDataMapper()
streamMapper.SetLookupTable(ctf)
streamMapper.SetInput(stream.GetOutput())
streamMapper.SetScalarRange(a,b)
streamActor = vtk.vtkActor()
streamActor.SetMapper(streamMapper)
streamActor.GetProperty().SetLineWidth(3.0)

#Colour Bar
cbar = vtk.vtkScalarBarActor()
cbar.SetLookupTable(ctf)
cbar.SetOrientationToHorizontal()
cbar.SetPosition(0.1,0.03)
Ejemplo n.º 12
0
def Main():
    global ren
    # Create the RenderWindow, Renderer and both Actors
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.SetMultiSamples(0)
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    iren.RemoveObservers('RightButtonPressEvent')
    iren.AddObserver('RightButtonPressEvent', print_camera_settings, 1.0)
    iren.AddObserver('RightButtonPressEvent', after_print_camera_settings,
                     -1.0)

    print "data: %s %s" % (sys.argv[1], sys.argv[2])

    cfdreader = vtk.vtkStructuredPointsReader()
    cfdreader.SetFileName(sys.argv[1])

    # setup wing data
    wingReader = vtk.vtkUnstructuredGridReader()
    wingReader.SetFileName(sys.argv[2])
    wingReader.Update()
    wingMapper = vtk.vtkDataSetMapper()
    wingMapper.SetInputConnection(wingReader.GetOutputPort())
    wingActor = vtk.vtkActor()
    wingActor.SetMapper(wingMapper)
    wingActor.GetProperty().SetColor(.4, .4, .4)

    bRakesToActor = [True, True, True]
    bWingToActor = True

    datamin = 0
    datamax = 230

    lut = vtk.vtkColorTransferFunction()
    lut.SetColorSpaceToHSV()
    lut.AddHSVPoint(datamin, 0, 1, 1)
    dis = float(datamax - datamin) / 7
    for i in range(0, 8):
        lut.AddHSVPoint(float(datamin + dis * i), 0.1 * i, 1, 1)

    colorBar = vtk.vtkScalarBarActor()
    colorBar.SetLookupTable(lut)
    colorBar.SetTitle("")
    colorBar.SetNumberOfLabels(6)
    colorBar.SetLabelFormat("%4.0f")
    colorBar.SetPosition(0.9, 0.1)
    colorBar.SetWidth(0.05)
    colorBar.SetHeight(0.4)
    ren.AddActor(colorBar)

    rakes = [vtk.vtkLineSource(), vtk.vtkLineSource(), vtk.vtkLineSource()]
    rakes[0].SetPoint1(-230, -230, 0)
    rakes[0].SetPoint2(230, 230, 0)
    rakes[0].SetResolution(50)

    rakes[1].SetPoint1(230, -230, 0)
    rakes[1].SetPoint2(-230, 230, 0)
    rakes[1].SetResolution(50)

    #     rakes[2].SetPoint1(0, -200, 10)
    #     rakes[2].SetPoint2(0, 200, 10)
    #     rakes[2].SetResolution(50)

    for i in range(0, len(rakes)):
        rakeMapper = vtk.vtkPolyDataMapper()
        rakeMapper.SetInputConnection(rakes[i].GetOutputPort())
        rakeActor = vtk.vtkActor()
        rakeActor.SetMapper(rakeMapper)

        integ = vtk.vtkRungeKutta4()
        streamLine = vtk.vtkStreamLine()
        streamLine.SetInputConnection(cfdreader.GetOutputPort())
        streamLine.SetSourceConnection(rakes[i].GetOutputPort())
        streamLine.SetMaximumPropagationTime(50)
        streamLine.SetIntegrationStepLength(.1)
        streamLine.SetStepLength(0.001)
        streamLine.SetIntegrationDirectionToForward()
        streamLine.SetIntegrator(integ)
        streamLine.SpeedScalarsOn()

        scalarSurface = vtk.vtkRuledSurfaceFilter()
        scalarSurface.SetInputConnection(streamLine.GetOutputPort())
        scalarSurface.SetOffset(0)
        scalarSurface.SetOnRatio(0)
        #         scalarSurface.PassLinesOn()
        scalarSurface.SetRuledModeToPointWalk()
        #         scalarSurface.SetDistanceFactor(40)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(scalarSurface.GetOutputPort())
        mapper.SetLookupTable(lut)
        mapper.SetScalarRange(cfdreader.GetOutput().GetScalarRange())
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(0, 1, 0)
        actor.GetProperty().SetOpacity(0.5)

        if bRakesToActor[i]:
            ren.AddActor(actor)

    if bWingToActor:
        ren.AddActor(wingActor)

    ren.SetBackground(0, 0, 0)
    renWin.SetSize(1600, 900)

    ren.ResetCamera()
    ren.GetActiveCamera().SetClippingRange(417.55784439078775,
                                           1491.5763714138557)
    ren.GetActiveCamera().SetFocalPoint(118.72183980792761,
                                        0.00012969970703125,
                                        36.469017028808594)
    ren.GetActiveCamera().SetPosition(680.0192576650034, 16.65944318371372,
                                      790.5781258299678)
    ren.GetActiveCamera().SetViewUp(-0.802117714199773, -0.005112780752923929,
                                    0.5971440630533839)

    # Render
    iren.Initialize()
    renWin.Render()
    iren.Start()
Ejemplo n.º 13
0
Archivo: wind.py Proyecto: borartr/facy
glyphActor = vtk.vtkActor()
glyphActor.SetMapper(glyphMapper)

## define streamlines #############################################################################
# line source for streamline #
LineSource = vtk.vtkLineSource()
LineSource.SetPoint1(17.5, 70.2, 0)
LineSource.SetPoint2(60, 70.2, 0)
LineSource.SetResolution(40)

LineSourceMapper = vtk.vtkPolyDataMapper()
LineSourceMapper.SetInputConnection(LineSource.GetOutputPort())
LineSourceActor = vtk.vtkActor()
LineSourceActor.SetMapper(LineSourceMapper)

integ = vtk.vtkRungeKutta4()  # integrator for generating the streamlines #
streamer = vtk.vtkStreamLine()
streamer.SetInputConnection(reader.GetOutputPort())
streamer.SetSource(LineSource.GetOutput())
streamer.SetMaximumPropagationTime(500)
streamer.SetIntegrationStepLength(.02)
streamer.SetStepLength(.01)
streamer.SetIntegrationDirectionToIntegrateBothDirections()
streamer.SetIntegrator(integ)

streamerMapper = vtk.vtkPolyDataMapper()
streamerMapper.SetInputConnection(streamer.GetOutputPort())
streamerMapper.SetLookupTable(lut)
streamerActor = vtk.vtkActor()
streamerActor.SetMapper(streamerMapper)
streamerActor.VisibilityOn()
Ejemplo n.º 14
0
    def _process_series(self, series):
        self._init_cyclers()
        self._fig.auto_rendering = False
        # clear data
        for o in self._fig.objects:
            self._fig.remove_class(o)

        for ii, s in enumerate(series):
            if s.is_3Dline and s.is_point:
                x, y, z, _ = s.get_data()
                positions = np.vstack([x, y, z]).T.astype(np.float32)
                a = dict(point_size=0.2,
                         color=self._convert_to_int(next(self._cl)))
                line_kw = self._kwargs.get("line_kw", dict())
                plt_points = k3d.points(positions=positions,
                                        **merge({}, a, line_kw))
                plt_points.shader = "mesh"
                self._fig += plt_points

            elif s.is_3Dline:
                x, y, z, param = s.get_data()
                # K3D doesn't like masked arrays, so filled them with NaN
                x, y, z = [
                    np.ma.filled(t)
                    if isinstance(t, np.ma.core.MaskedArray) else t
                    for t in [x, y, z]
                ]
                vertices = np.vstack([x, y, z]).T.astype(np.float32)
                # keyword arguments for the line object
                a = dict(
                    width=0.1,
                    name=s.label
                    if self._kwargs.get("show_label", False) else None,
                    color=self._convert_to_int(next(self._cl)),
                    shader="mesh",
                )
                if self._use_cm:
                    a["attribute"] = (param.astype(np.float32), )
                    a["color_map"] = next(self._cm)
                    a["color_range"] = [s.start, s.end]
                line_kw = self._kwargs.get("line_kw", dict())
                line = k3d.line(vertices, **merge({}, a, line_kw))
                self._fig += line

            elif (s.is_3Dsurface and
                  (not s.is_complex)) or (s.is_3Dsurface and s.is_complex and
                                          (s.real or s.imag or s.abs)):
                x, y, z = s.get_data()
                # K3D doesn't like masked arrays, so filled them with NaN
                x, y, z = [
                    np.ma.filled(t)
                    if isinstance(t, np.ma.core.MaskedArray) else t
                    for t in [x, y, z]
                ]

                # TODO:
                # Can I use get_vertices_indices also for non parametric surfaces?
                if s.is_parametric:
                    vertices, indices = get_vertices_indices(x, y, z)
                    vertices = vertices.astype(np.float32)
                else:
                    x = x.flatten()
                    y = y.flatten()
                    z = z.flatten()
                    vertices = np.vstack([x, y, z]).T.astype(np.float32)
                    indices = Triangulation(x, y).triangles.astype(np.uint32)

                self._high_aspect_ratio(x, y, z)
                a = dict(
                    name=s.label
                    if self._kwargs.get("show_label", False) else None,
                    side="double",
                    flat_shading=False,
                    wireframe=False,
                    color=self._convert_to_int(next(self._cl)),
                )
                if self._use_cm:
                    a["color_map"] = next(self._cm)
                    a["attribute"] = z.astype(np.float32)
                surface_kw = self._kwargs.get("surface_kw", dict())
                surf = k3d.mesh(vertices, indices, **merge({}, a, surface_kw))

                self._fig += surf

            elif s.is_3Dvector and self._kwargs.get("streamlines", False):
                xx, yy, zz, uu, vv, ww = s.get_data()
                # K3D doesn't like masked arrays, so filled them with NaN
                xx, yy, zz, uu, vv, ww = [
                    np.ma.filled(t)
                    if isinstance(t, np.ma.core.MaskedArray) else t
                    for t in [xx, yy, zz, uu, vv, ww]
                ]
                magnitude = np.sqrt(uu**2 + vv**2 + ww**2)
                min_mag = min(magnitude.flatten())
                max_mag = max(magnitude.flatten())

                import vtk
                from vtk.util import numpy_support

                vector_field = np.array(
                    [uu.flatten(), vv.flatten(),
                     ww.flatten()]).T
                vtk_vector_field = numpy_support.numpy_to_vtk(
                    num_array=vector_field,
                    deep=True,
                    array_type=vtk.VTK_FLOAT)
                vtk_vector_field.SetName("vector_field")

                points = vtk.vtkPoints()
                points.SetNumberOfPoints(s.n2 * s.n1 * s.n3)
                for i, (x, y, z) in enumerate(
                        zip(xx.flatten(), yy.flatten(), zz.flatten())):
                    points.SetPoint(i, [x, y, z])

                grid = vtk.vtkStructuredGrid()
                grid.SetDimensions([s.n2, s.n1, s.n3])
                grid.SetPoints(points)
                grid.GetPointData().SetVectors(vtk_vector_field)

                stream_kw = self._kwargs.get("stream_kw", dict())
                starts = stream_kw.pop("starts", None)
                max_prop = stream_kw.pop("max_prop", 500)

                streamer = vtk.vtkStreamTracer()
                streamer.SetInputData(grid)
                streamer.SetMaximumPropagation(max_prop)

                if starts is None:
                    seeds_points = get_seeds_points(xx, yy, zz, uu, vv, ww)
                    seeds = vtk.vtkPolyData()
                    points = vtk.vtkPoints()
                    for p in seeds_points:
                        points.InsertNextPoint(p)
                    seeds.SetPoints(points)
                    streamer.SetSourceData(seeds)
                    streamer.SetIntegrationDirectionToForward()
                elif isinstance(starts, dict):
                    if not all([t in starts.keys() for t in ["x", "y", "z"]]):
                        raise KeyError(
                            "``starts`` must contains the following keys: " +
                            "'x', 'y', 'z', whose values are going to be " +
                            "lists of coordinates.")
                    seeds_points = np.array(
                        [starts["x"], starts["y"], starts["z"]]).T
                    seeds = vtk.vtkPolyData()
                    points = vtk.vtkPoints()
                    for p in seeds_points:
                        points.InsertNextPoint(p)
                    seeds.SetPoints(points)
                    streamer.SetSourceData(seeds)
                    streamer.SetIntegrationDirectionToBoth()
                else:
                    npoints = stream_kw.get("npoints", 200)
                    radius = stream_kw.get("radius", None)
                    center = 0, 0, 0
                    if not radius:
                        xmin, xmax = min(xx[0, :, 0]), max(xx[0, :, 0])
                        ymin, ymax = min(yy[:, 0, 0]), max(yy[:, 0, 0])
                        zmin, zmax = min(zz[0, 0, :]), max(zz[0, 0, :])
                        radius = max([
                            abs(xmax - xmin),
                            abs(ymax - ymin),
                            abs(zmax - zmin)
                        ])
                        center = (xmax - xmin) / 2, (ymax - ymin) / 2, (
                            zmax - zmin) / 2
                    seeds = vtk.vtkPointSource()
                    seeds.SetRadius(radius)
                    seeds.SetCenter(*center)
                    seeds.SetNumberOfPoints(npoints)

                    streamer.SetSourceConnection(seeds.GetOutputPort())
                    streamer.SetIntegrationDirectionToBoth()

                streamer.SetComputeVorticity(0)
                streamer.SetIntegrator(vtk.vtkRungeKutta4())
                streamer.Update()

                streamline = streamer.GetOutput()
                streamlines_points = numpy_support.vtk_to_numpy(
                    streamline.GetPoints().GetData())
                streamlines_velocity = numpy_support.vtk_to_numpy(
                    streamline.GetPointData().GetArray("vector_field"))
                streamlines_speed = np.linalg.norm(streamlines_velocity,
                                                   axis=1)

                vtkLines = streamline.GetLines()
                vtkLines.InitTraversal()
                point_list = vtk.vtkIdList()

                lines = []
                lines_attributes = []

                while vtkLines.GetNextCell(point_list):
                    start_id = point_list.GetId(0)
                    end_id = point_list.GetId(point_list.GetNumberOfIds() - 1)
                    l = []
                    v = []

                    for i in range(start_id, end_id):
                        l.append(streamlines_points[i])
                        v.append(streamlines_speed[i])

                    lines.append(np.array(l))
                    lines_attributes.append(np.array(v))

                count = sum([len(l) for l in lines])
                vertices = np.nan * np.zeros((count + (len(lines) - 1), 3))
                attributes = np.zeros(count + (len(lines) - 1))
                c = 0
                for k, (l, a) in enumerate(zip(lines, lines_attributes)):
                    vertices[c:c + len(l), :] = l
                    attributes[c:c + len(l)] = a
                    if k < len(lines) - 1:
                        c = c + len(l) + 1

                skw = dict(width=0.1, shader="mesh", compression_level=9)
                if self._use_cm and ("color" not in stream_kw.keys()):
                    skw["color_map"] = next(self._cm)
                    skw["color_range"] = [min_mag, max_mag]
                    skw["attribute"] = attributes
                else:
                    col = stream_kw.pop("color", next(self._cl))
                    if not isinstance(col, int):
                        col = self._convert_to_int(col)
                    stream_kw["color"] = col

                self._fig += k3d.line(vertices.astype(np.float32),
                                      **merge({}, skw, stream_kw))
            elif s.is_3Dvector:
                xx, yy, zz, uu, vv, ww = s.get_data()
                # K3D doesn't like masked arrays, so filled them with NaN
                xx, yy, zz, uu, vv, ww = [
                    np.ma.filled(t)
                    if isinstance(t, np.ma.core.MaskedArray) else t
                    for t in [xx, yy, zz, uu, vv, ww]
                ]
                xx, yy, zz, uu, vv, ww = [
                    t.flatten().astype(np.float32)
                    for t in [xx, yy, zz, uu, vv, ww]
                ]
                # default values
                qkw = dict(scale=1)
                # user provided values
                quiver_kw = self._kwargs.get("quiver_kw", dict())
                qkw = merge(qkw, quiver_kw)
                scale = qkw["scale"]
                magnitude = np.sqrt(uu**2 + vv**2 + ww**2)
                vectors = np.array((uu, vv, ww)).T * scale
                origins = np.array((xx, yy, zz)).T
                if self._use_cm and ("color" not in quiver_kw.keys()):
                    colormap = next(self._cm)
                    colors = k3d.helpers.map_colors(magnitude, colormap, [])
                    self._handles[ii] = [qkw, colormap]
                else:
                    col = quiver_kw.get("color", next(self._cl))
                    if not isinstance(col, int):
                        col = self._convert_to_int(col)
                    colors = col * np.ones(len(magnitude))
                    self._handles[ii] = [qkw, None]
                vec_colors = np.zeros(2 * len(colors))
                for i, c in enumerate(colors):
                    vec_colors[2 * i] = c
                    vec_colors[2 * i + 1] = c
                vec_colors = vec_colors.astype(np.uint32)
                vec = k3d.vectors(
                    origins=origins - vectors / 2,
                    vectors=vectors,
                    colors=vec_colors,
                )
                self._fig += vec
            elif s.is_complex and s.is_3Dsurface and (
                    not s.is_domain_coloring):
                x, y, mag_arg, colors, colorscale = s.get_data()
                mag, arg = mag_arg[:, :, 0], mag_arg[:, :, 1]

                x, y, z = [t.flatten() for t in [x, y, mag]]
                vertices = np.vstack([x, y, z]).T.astype(np.float32)
                indices = Triangulation(x, y).triangles.astype(np.uint32)
                self._high_aspect_ratio(x, y, z)

                a = dict(
                    name=s.label
                    if self._kwargs.get("show_label", False) else None,
                    side="double",
                    flat_shading=False,
                    wireframe=False,
                    color=self._convert_to_int(next(self._cl)),
                    color_range=[-np.pi, np.pi],
                )
                if self._use_cm:
                    colors = colors.reshape((-1, 3))
                    a["colors"] = [self._rgb_to_int(c) for c in colors]

                    r = []
                    loc = np.linspace(0, 1, colorscale.shape[0])
                    colorscale = colorscale / 255
                    for l, c in zip(loc, colorscale):
                        r.append(l)
                        r += list(c)

                    a["color_map"] = r
                    a["color_range"] = [-np.pi, np.pi]
                surface_kw = self._kwargs.get("surface_kw", dict())
                surf = k3d.mesh(vertices, indices, **merge({}, a, surface_kw))

                self._fig += surf
            else:
                raise NotImplementedError(
                    "{} is not supported by {}\n".format(
                        type(s),
                        type(self).__name__) +
                    "K3D-Jupyter only supports 3D plots.")

        xl = self.xlabel if self.xlabel else "x"
        yl = self.ylabel if self.ylabel else "y"
        zl = self.zlabel if self.zlabel else "z"
        self._fig.axes = [xl, yl, zl]

        if self.title:
            self._fig += k3d.text2d(self.title,
                                    position=[0.025, 0.015],
                                    color=0,
                                    size=1,
                                    label_box=False)
        self._fig.auto_rendering = True
Ejemplo n.º 15
0
    def _plotInternal(self):
        """Overrides baseclass implementation."""
        # Preserve time and z axis for plotting these inof in rendertemplate
        projection = vcs.elements["projection"][self._gm.projection]

        zaxis, taxis = self.getZandT()

        # Streamline color
        if (not self._gm.coloredbyvector):
            ln_tmp = self._gm.linetype
            if ln_tmp is None:
                ln_tmp = "default"
            try:
                ln_tmp = vcs.getline(ln_tmp)
                lwidth = ln_tmp.width[0]  # noqa
                lcolor = ln_tmp.color[0]
                lstyle = ln_tmp.type[0]  # noqa
            except Exception:
                lstyle = "solid"  # noqa
                lwidth = 1.  # noqa
                lcolor = [0., 0., 0., 100.]
            if self._gm.linewidth is not None:
                lwidth = self._gm.linewidth  # noqa
            if self._gm.linecolor is not None:
                lcolor = self._gm.linecolor

        # The unscaled continent bounds were fine in the presence of axis
        # conversion, so save them here
        continentBounds = vcs2vtk.computeDrawAreaBounds(
            self._vtkDataSetBoundsNoMask, self._context_flipX,
            self._context_flipY)

        # Only scaling the data in the presence of axis conversion changes
        # the seed points in any other cases, and thus results in plots
        # different from the baselines but still fundamentally sound, it
        # seems.  Always scaling the data results in no differences in the
        # plots between Context2D and the old baselines.

        # Transform the input data
        T = vtk.vtkTransform()
        T.Scale(self._context_xScale, self._context_yScale, 1.)

        self._vtkDataSetFittedToViewport = vcs2vtk.applyTransformationToDataset(
            T, self._vtkDataSetFittedToViewport)
        self._vtkDataSetBoundsNoMask = self._vtkDataSetFittedToViewport.GetBounds(
        )

        polydata = self._vtkDataSetFittedToViewport
        plotting_dataset_bounds = self.getPlottingBounds()
        x1, x2, y1, y2 = plotting_dataset_bounds
        vp = self._resultDict.get('ratio_autot_viewport', [
            self._template.data.x1, self._template.data.x2,
            self._template.data.y1, self._template.data.y2
        ])

        # view and interactive area
        view = self._context().contextView
        area = vtk.vtkInteractiveArea()
        view.GetScene().AddItem(area)

        drawAreaBounds = vcs2vtk.computeDrawAreaBounds(
            self._vtkDataSetBoundsNoMask, self._context_flipX,
            self._context_flipY)

        [renWinWidth, renWinHeight] = self._context().renWin.GetSize()
        geom = vtk.vtkRecti(int(round(vp[0] * renWinWidth)),
                            int(round(vp[2] * renWinHeight)),
                            int(round((vp[1] - vp[0]) * renWinWidth)),
                            int(round((vp[3] - vp[2]) * renWinHeight)))

        vcs2vtk.configureContextArea(area, drawAreaBounds, geom)

        dataLength = polydata.GetLength()

        if (not self._gm.evenlyspaced):
            # generate random seeds in a circle centered in the center of
            # the bounding box for the data.

            # by default vtkPointSource uses a global random source in vtkMath which is
            # seeded only once. It makes more sense to seed a random sequence each time you draw
            # the streamline plot.
            pointSequence = vtk.vtkMinimalStandardRandomSequence()
            pointSequence.SetSeedOnly(1177)  # replicate the seed from vtkMath

            seed = vtk.vtkPointSource()
            seed.SetNumberOfPoints(self._gm.numberofseeds)
            seed.SetCenter(polydata.GetCenter())
            seed.SetRadius(dataLength / 2.0)
            seed.SetRandomSequence(pointSequence)
            seed.Update()
            seedData = seed.GetOutput()

            # project all points to Z = 0 plane
            points = seedData.GetPoints()
            for i in range(0, points.GetNumberOfPoints()):
                p = list(points.GetPoint(i))
                p[2] = 0
                points.SetPoint(i, p)

        if (self._gm.integratortype == 0):
            integrator = vtk.vtkRungeKutta2()
        elif (self._gm.integratortype == 1):
            integrator = vtk.vtkRungeKutta4()
        else:
            if (self._gm.evenlyspaced):
                warnings.warn(
                    "You cannot use RungeKutta45 for evenly spaced streamlines."
                    "Using RungeKutta4 instead")
                integrator = vtk.vtkRungeKutta4()
            else:
                integrator = vtk.vtkRungeKutta45()

        if (self._gm.evenlyspaced):
            streamer = vtk.vtkEvenlySpacedStreamlines2D()
            startseed = self._gm.startseed \
                if self._gm.startseed else polydata.GetCenter()
            streamer.SetStartPosition(startseed)
            streamer.SetSeparatingDistance(self._gm.separatingdistance)
            streamer.SetSeparatingDistanceRatio(
                self._gm.separatingdistanceratio)
            streamer.SetClosedLoopMaximumDistance(
                self._gm.closedloopmaximumdistance)
        else:
            # integrate streamlines on normalized vector so that
            # IntegrationTime stores distance
            streamer = vtk.vtkStreamTracer()
            streamer.SetSourceData(seedData)
            streamer.SetIntegrationDirection(self._gm.integrationdirection)
            streamer.SetMinimumIntegrationStep(self._gm.minimumsteplength)
            streamer.SetMaximumIntegrationStep(self._gm.maximumsteplength)
            streamer.SetMaximumError(self._gm.maximumerror)
            streamer.SetMaximumPropagation(dataLength *
                                           self._gm.maximumstreamlinelength)

        streamer.SetInputData(polydata)
        streamer.SetInputArrayToProcess(0, 0, 0, 0, "vector")
        streamer.SetIntegrationStepUnit(self._gm.integrationstepunit)
        streamer.SetInitialIntegrationStep(self._gm.initialsteplength)
        streamer.SetMaximumNumberOfSteps(self._gm.maximumsteps)
        streamer.SetTerminalSpeed(self._gm.terminalspeed)
        streamer.SetIntegrator(integrator)

        # add arc_length to streamlines
        arcLengthFilter = vtk.vtkAppendArcLength()
        arcLengthFilter.SetInputConnection(streamer.GetOutputPort())

        arcLengthFilter.Update()
        streamlines = arcLengthFilter.GetOutput()

        # glyph seed points
        contour = vtk.vtkContourFilter()
        contour.SetInputConnection(arcLengthFilter.GetOutputPort())
        contour.SetValue(0, 0.001)
        if (streamlines.GetNumberOfPoints()):
            r = streamlines.GetPointData().GetArray("arc_length").GetRange()
            numberofglyphsoneside = self._gm.numberofglyphs // 2
            for i in range(1, numberofglyphsoneside):
                contour.SetValue(i, r[1] / numberofglyphsoneside * i)
        else:
            warnings.warn(
                "No streamlines created. "
                "The 'startseed' parameter needs to be inside the domain and "
                "not over masked data.")
        contour.SetInputArrayToProcess(0, 0, 0, 0, "arc_length")

        # arrow glyph source
        glyph2DSource = vtk.vtkGlyphSource2D()
        glyph2DSource.SetGlyphTypeToTriangle()
        glyph2DSource.SetRotationAngle(-90)
        glyph2DSource.SetFilled(self._gm.filledglyph)

        # arrow glyph adjustment
        transform = vtk.vtkTransform()
        transform.Scale(1., self._gm.glyphbasefactor, 1.)
        transformFilter = vtk.vtkTransformFilter()
        transformFilter.SetInputConnection(glyph2DSource.GetOutputPort())
        transformFilter.SetTransform(transform)
        transformFilter.Update()
        glyphLength = transformFilter.GetOutput().GetLength()

        #  drawing the glyphs at the seed points
        glyph = vtk.vtkGlyph2D()
        glyph.SetInputConnection(contour.GetOutputPort())
        glyph.SetInputArrayToProcess(1, 0, 0, 0, "vector")
        glyph.SetSourceData(transformFilter.GetOutput())
        glyph.SetScaleModeToDataScalingOff()
        glyph.SetScaleFactor(dataLength * self._gm.glyphscalefactor /
                             glyphLength)
        glyph.SetColorModeToColorByVector()

        glyphMapper = vtk.vtkPolyDataMapper()
        glyphActor = vtk.vtkActor()

        mapper = vtk.vtkPolyDataMapper()
        act = vtk.vtkActor()

        glyph.Update()
        glyphDataset = glyph.GetOutput()
        streamer.Update()
        lineDataset = streamer.GetOutput()

        deleteLineColors = False
        deleteGlyphColors = False

        # color the streamlines and glyphs
        cmap = self.getColorMap()
        if (self._gm.coloredbyvector):
            numLevels = len(self._contourLevels) - 1
            while len(self._contourColors) < numLevels:
                self._contourColors.append(self._contourColors[-1])

            lut = vtk.vtkLookupTable()
            lut.SetNumberOfTableValues(numLevels)
            for i in range(numLevels):
                r, g, b, a = self.getColorIndexOrRGBA(cmap,
                                                      self._contourColors[i])
                lut.SetTableValue(i, r / 100., g / 100., b / 100., a / 100.)
            lut.SetVectorModeToMagnitude()
            if numpy.allclose(self._contourLevels[0], -1.e20):
                lmn = self._vectorRange[0]
            else:
                lmn = self._contourLevels[0][0]
            if numpy.allclose(self._contourLevels[-1], 1.e20):
                lmx = self._vectorRange[1]
            else:
                lmx = self._contourLevels[-1][-1]
            lut.SetRange(lmn, lmx)

            mapper.ScalarVisibilityOn()
            mapper.SetLookupTable(lut)
            mapper.UseLookupTableScalarRangeOn()
            mapper.SetScalarModeToUsePointFieldData()
            mapper.SelectColorArray("vector")

            lineAttrs = lineDataset.GetPointData()
            lineData = lineAttrs.GetArray("vector")

            if lineData and numLevels:
                lineColors = lut.MapScalars(lineData,
                                            vtk.VTK_COLOR_MODE_DEFAULT, 0)
                deleteLineColors = True
            else:
                print(
                    'WARNING: streamline pipeline cannot map scalars for "lineData", using solid color'
                )
                numTuples = lineDataset.GetNumberOfPoints()
                color = [0, 0, 0, 255]
                lineColors = vcs2vtk.generateSolidColorArray(numTuples, color)

            glyphMapper.ScalarVisibilityOn()
            glyphMapper.SetLookupTable(lut)
            glyphMapper.UseLookupTableScalarRangeOn()
            glyphMapper.SetScalarModeToUsePointFieldData()
            glyphMapper.SelectColorArray("VectorMagnitude")

            glyphAttrs = glyphDataset.GetPointData()
            glyphData = glyphAttrs.GetArray("VectorMagnitude")

            if glyphData and numLevels:
                glyphColors = lut.MapScalars(glyphData,
                                             vtk.VTK_COLOR_MODE_DEFAULT, 0)
                deleteGlyphColors = True
            else:
                print(
                    'WARNING: streamline pipeline cannot map scalars for "glyphData", using solid color'
                )
                numTuples = glyphDataset.GetNumberOfPoints()
                color = [0, 0, 0, 255]
                glyphColors = vcs2vtk.generateSolidColorArray(numTuples, color)
        else:
            mapper.ScalarVisibilityOff()
            glyphMapper.ScalarVisibilityOff()
            if isinstance(lcolor, (list, tuple)):
                r, g, b, a = lcolor
            else:
                r, g, b, a = cmap.index[lcolor]
            act.GetProperty().SetColor(r / 100., g / 100., b / 100.)
            glyphActor.GetProperty().SetColor(r / 100., g / 100., b / 100.)

            fixedColor = [
                int((r / 100.) * 255),
                int((g / 100.) * 255),
                int((b / 100.) * 255), 255
            ]

            numTuples = lineDataset.GetNumberOfPoints()
            lineColors = vcs2vtk.generateSolidColorArray(numTuples, fixedColor)

            numTuples = glyphDataset.GetNumberOfPoints()
            glyphColors = vcs2vtk.generateSolidColorArray(
                numTuples, fixedColor)

        # Add the streamlines
        lineItem = vtk.vtkPolyDataItem()
        lineItem.SetPolyData(lineDataset)
        lineItem.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_POINT_DATA)
        lineItem.SetMappedColors(lineColors)
        if deleteLineColors:
            lineColors.FastDelete()
        area.GetDrawAreaItem().AddItem(lineItem)

        # Add the glyphs
        glyphItem = vtk.vtkPolyDataItem()
        glyphItem.SetPolyData(glyphDataset)
        glyphItem.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_POINT_DATA)
        glyphItem.SetMappedColors(glyphColors)
        if deleteGlyphColors:
            glyphColors.FastDelete()
        area.GetDrawAreaItem().AddItem(glyphItem)

        plotting_dataset_bounds = self.getPlottingBounds()
        vp = self._resultDict.get('ratio_autot_viewport', [
            self._template.data.x1, self._template.data.x2,
            self._template.data.y1, self._template.data.y2
        ])

        kwargs = {
            'vtk_backend_grid':
            self._vtkDataSet,
            'dataset_bounds':
            self._vtkDataSetBounds,
            'plotting_dataset_bounds':
            plotting_dataset_bounds,
            "vtk_dataset_bounds_no_mask":
            self._vtkDataSetBoundsNoMask,
            'vtk_backend_geo':
            self._vtkGeoTransform,
            "vtk_backend_draw_area_bounds":
            continentBounds,
            "vtk_backend_viewport_scale":
            [self._context_xScale, self._context_yScale]
        }
        if ('ratio_autot_viewport' in self._resultDict):
            kwargs["ratio_autot_viewport"] = vp
        self._resultDict.update(self._context().renderTemplate(
            self._template, self._data1, self._gm, taxis, zaxis, **kwargs))
        if (self._gm.coloredbyvector):
            self._resultDict.update(self._context().renderColorBar(
                self._template, self._contourLevels, self._contourColors, None,
                self.getColorMap()))

        kwargs['xaxisconvert'] = self._gm.xaxisconvert
        kwargs['yaxisconvert'] = self._gm.yaxisconvert
        if self._data1.getAxis(-1).isLongitude() and self._data1.getAxis(
                -2).isLatitude():
            self._context().plotContinents(
                self._plot_kargs.get("continents", self._useContinents),
                plotting_dataset_bounds, projection, self._dataWrapModulo, vp,
                self._template.data.priority, **kwargs)
        self._resultDict["vtk_backend_actors"] = [[
            lineItem, plotting_dataset_bounds
        ]]
        self._resultDict["vtk_backend_luts"] = [[None, None]]
Ejemplo n.º 16
0
import vtk

objectPath = r"./assets/density.vtk"

reader = vtk.vtkStructuredGridReader()
reader.SetFileName(objectPath)
reader.Update()

seeds = vtk.vtkPointSource()
seeds.SetRadius(3.0)
seeds.SetCenter(reader.GetOutput().GetCenter())
seeds.SetNumberOfPoints(100)

integrator = vtk.vtkRungeKutta4()

streamer = vtk.vtkStreamTracer()
streamer.SetInputConnection(reader.GetOutputPort())
streamer.SetSourceConnection(seeds.GetOutputPort())
streamer.SetMaximumPropagation(100)
## TIME_UNIT Doesn't exist anymore... see https://vtk.org/doc/nightly/html/classvtkStreamTracer.html#a80f1503728603955364e1618af963ab1
#streamer.SetMaximumPropagationUnit(TIME_UNIT)
## LENGTH_UNIT = 1 CELL_LENGTH_UNIT = 2
streamer.SetInitialIntegrationStep(2)
streamer.SetInitialIntegrationStep(0.1)
streamer.SetIntegrationDirectionToBoth()
streamer.SetIntegrator(integrator)

streamlineMapper = vtk.vtkPolyDataMapper()
streamlineMapper.SetInputConnection(streamer.GetOutputPort())
streamlineMapper.SetScalarRange(reader.GetOutput().GetScalarRange())
Ejemplo n.º 17
0
def main():
    colors = vtk.vtkNamedColors()

    fileName1, fileName2, numOfStreamLines, illustration = get_program_parameters(
    )
    if illustration:
        numOfStreamLines = 25

    # Start by loading some data.
    pl3d = vtk.vtkMultiBlockPLOT3DReader()
    pl3d.SetXYZFileName(fileName1)
    pl3d.SetQFileName(fileName2)
    pl3d.SetScalarFunctionNumber(100)  # Density
    pl3d.SetVectorFunctionNumber(202)  # Momentum
    pl3d.Update()

    pl3d_output = pl3d.GetOutput().GetBlock(0)

    # Create the Renderer, RenderWindow and RenderWindowInteractor.
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Needed by: vtkStreamTracer and vtkLineWidget.
    seeds = vtk.vtkPolyData()
    streamline = vtk.vtkActor()
    seeds2 = vtk.vtkPolyData()
    streamline2 = vtk.vtkActor()

    # The line widget is used seed the streamlines.
    lineWidget = vtk.vtkLineWidget()
    lineWidget.SetResolution(numOfStreamLines)
    lineWidget.SetInputData(pl3d_output)
    lineWidget.GetPolyData(seeds)
    if illustration:
        lineWidget.SetAlignToNone()
        lineWidget.SetPoint1(0.974678, 5.073630, 31.217961)
        lineWidget.SetPoint2(0.457544, -4.995921, 31.080175)
    else:
        lineWidget.SetAlignToYAxis()
    lineWidget.ClampToBoundsOn()
    lineWidget.PlaceWidget()
    # Associate the line widget with the interactor and setup callbacks.
    lineWidget.SetInteractor(iren)
    lineWidget.AddObserver("StartInteractionEvent",
                           EnableActorCallback(streamline))
    lineWidget.AddObserver("InteractionEvent",
                           GenerateStreamlinesCallback(seeds, renWin))

    # The second line widget is used seed more streamlines.
    lineWidget2 = vtk.vtkLineWidget()
    lineWidget2.SetResolution(numOfStreamLines)
    lineWidget2.SetInputData(pl3d_output)
    lineWidget2.GetPolyData(seeds2)
    lineWidget2.SetKeyPressActivationValue('L')
    lineWidget2.SetAlignToZAxis()
    lineWidget.ClampToBoundsOn()
    lineWidget2.PlaceWidget()
    # Associate the line widget with the interactor and setup callbacks.
    lineWidget2.SetInteractor(iren)
    lineWidget2.AddObserver("StartInteractionEvent",
                            EnableActorCallback(streamline2))
    lineWidget2.AddObserver("InteractionEvent",
                            GenerateStreamlinesCallback(seeds2, renWin))

    # Here we set up two streamlines.
    rk4 = vtk.vtkRungeKutta4()
    streamer = vtk.vtkStreamTracer()
    streamer.SetInputData(pl3d_output)
    streamer.SetSourceData(seeds)
    streamer.SetMaximumPropagation(100)
    streamer.SetInitialIntegrationStep(0.2)
    streamer.SetIntegrationDirectionToForward()
    streamer.SetComputeVorticity(1)
    streamer.SetIntegrator(rk4)
    rf = vtk.vtkRibbonFilter()
    rf.SetInputConnection(streamer.GetOutputPort())
    rf.SetWidth(0.1)
    rf.SetWidthFactor(5)
    streamMapper = vtk.vtkPolyDataMapper()
    streamMapper.SetInputConnection(rf.GetOutputPort())
    streamMapper.SetScalarRange(pl3d_output.GetScalarRange())
    streamline.SetMapper(streamMapper)
    streamline.VisibilityOff()

    streamer2 = vtk.vtkStreamTracer()
    streamer2.SetInputData(pl3d_output)
    streamer2.SetSourceData(seeds2)
    streamer2.SetMaximumPropagation(100)
    streamer2.SetInitialIntegrationStep(0.2)
    streamer2.SetIntegrationDirectionToForward()
    streamer2.SetComputeVorticity(1)
    streamer2.SetIntegrator(rk4)
    rf2 = vtk.vtkRibbonFilter()
    rf2.SetInputConnection(streamer2.GetOutputPort())
    rf2.SetWidth(0.1)
    rf2.SetWidthFactor(5)
    streamMapper2 = vtk.vtkPolyDataMapper()
    streamMapper2.SetInputConnection(rf2.GetOutputPort())
    streamMapper2.SetScalarRange(pl3d_output.GetScalarRange())
    streamline2.SetMapper(streamMapper2)
    streamline2.VisibilityOff()

    # Get an outline of the data set for context.
    outline = vtk.vtkStructuredGridOutlineFilter()
    outline.SetInputData(pl3d_output)
    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())
    outlineActor = vtk.vtkActor()
    outlineActor.GetProperty().SetColor(colors.GetColor3d("Black"))
    outlineActor.SetMapper(outlineMapper)

    # Add the actors to the renderer, set the background and size.
    ren.AddActor(outlineActor)
    ren.AddActor(streamline)
    ren.AddActor(streamline2)
    renWin.SetSize(512, 512)
    cam = ren.GetActiveCamera()
    if illustration:
        # We need to directly display the streamlines in this case.
        lineWidget.EnabledOn()
        streamline.VisibilityOn()
        lineWidget.GetPolyData(seeds)
        renWin.Render()

        cam.SetClippingRange(14.216207, 68.382915)
        cam.SetFocalPoint(9.718210, 0.458166, 29.399900)
        cam.SetPosition(-15.827551, -16.997463, 54.003120)
        cam.SetViewUp(0.616076, 0.179428, 0.766979)
        ren.SetBackground(colors.GetColor3d("Silver"))
    else:
        cam.SetClippingRange(3.95297, 50)
        cam.SetFocalPoint(9.71821, 0.458166, 29.3999)
        cam.SetPosition(2.7439, -37.3196, 38.7167)
        cam.SetViewUp(-0.16123, 0.264271, 0.950876)
        ren.SetBackground(colors.GetColor3d("Silver"))

    iren.Initialize()
    renWin.Render()
    iren.Start()
Ejemplo n.º 18
0
def read_vtk_2d(name):
    import vtk
    import numpy

    gridreader = vtk.vtkXMLStructuredGridReader()
    gridreader.SetFileName(name)
    #gridreader.SetPointArrayStatus("Density",0)
    selection = gridreader.GetPointDataArraySelection()
    selection.DisableArray("Density")
    #selection.DisableArray("Velocity")
    #selection.DisableArray("Phase")
    gridreader.Update()

    grid = gridreader.GetOutput()

    data = grid.GetPointData()
    points = grid.GetPoints()
    dims = grid.GetDimensions()
    #data.SetActiveScalars("Phase");
    data.SetActiveVectors("Velocity")
    velocity = data.GetArray("Velocity")
    phase = data.GetArray("Phase")

    vel_image = vtk.vtkImageData()
    vel_image.SetDimensions(dims[1], dims[2], 1)
    vel_image.SetSpacing(1.0, 1.0, 1.0)
    vel_image.SetOrigin(0.0, 0.0, 0.0)

    Array = vtk.vtkDoubleArray()
    Array.SetNumberOfComponents(3)
    Array.SetNumberOfTuples(points.GetNumberOfPoints())
    Array.Initialize()
    Array.SetName("VelocitySlice")

    ArrayPhase = vtk.vtkDoubleArray()
    ArrayPhase.SetNumberOfComponents(1)
    ArrayPhase.SetNumberOfTuples(points.GetNumberOfPoints())
    ArrayPhase.Initialize()
    ArrayPhase.SetName("PhaseSlice")

    for counter in range(0, 10):
        print points.GetPoint(counter)
    raw_input()
    exam = 1
    print dims[0], dims[1], dims[2]
    #raw_input()
    for counter in range(0, vel_image.GetNumberOfPoints()):
        x, y, z = vel_image.GetPoint(counter)
        counter_big = y * dims[0] * dims[1] + x * dims[0] + exam
        #print x,y,z
        #print counter_big

        vz = velocity.GetTuple3(counter_big)[2]
        vy = velocity.GetTuple3(counter_big)[1]
        phase_value = phase.GetTuple1(counter_big)
        Array.InsertNextTuple3(vy, vz, 0.0)
        ArrayPhase.InsertNextTuple1(phase_value)
        #if phase_value<0.0:
        #    print phase_value

    vel_image.GetPointData().SetVectors(Array)
    vel_image.GetPointData().SetScalars(ArrayPhase)
    vel_image.GetPointData().SetActiveScalars("PhaseSlice")
    vel_image.GetPointData().SetActiveVectors("VelocitySlice")
    print vel_image.GetPointData().GetArray("PhaseSlice")
    vel_image.Update()

    contour = vtk.vtkContourFilter()
    contour.SetInput(vel_image)
    #contour.SetValue(0,0.0)

    contourMapper = vtk.vtkPolyDataMapper()
    #contourMapper.SetScalarRange(phase.GetRange())
    contourMapper.SetInputConnection(contour.GetOutputPort())
    #contourMapper.SetColorMode

    contourActor = vtk.vtkActor()
    contourActor.SetMapper(contourMapper)

    #contourActor.SetColor(0.0,0.1,0.2)

    rk4 = vtk.vtkRungeKutta4()
    line = vtk.vtkLineSource()
    line.SetPoint1(50, 0, 0)
    line.SetPoint2(0, 0, 0)
    line.SetResolution(21)
    streamer = vtk.vtkStreamLine()
    streamer.SetInput(vel_image)
    streamer.SetSource(line.GetOutput())
    streamer.SetMaximumPropagationTime(300000)
    #streamer.GetStepLengthMinValue()=0.01
    #streamer.GetStepLengthMaxValue()=0.5
    #streamer.SetTerminalSpeed(1e-13)
    streamer.SetIntegrationStepLength(.2)
    streamer.SetStepLength(.5)
    #streamer.SetNumberOfThreads(1)
    streamer.SetIntegrationDirectionToIntegrateBothDirections()
    #streamer.VorticityOn()
    streamer.SetIntegrator(rk4)

    streamMapper = vtk.vtkPolyDataMapper()
    streamMapper.SetInputConnection(streamer.GetOutputPort())
    #streamMapper.SetScalarRange(data.GetOutput().GetScalarRange())
    streamActor = vtk.vtkActor()
    streamActor.SetMapper(streamMapper)
    streamActor.VisibilityOn()

    # Create the Renderer, RenderWindow, and RenderWindowInteractor
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Add the actors to the render; set the background and size
    ren.AddActor(streamActor)
    ren.AddActor(contourActor)
    #ren.SetBackground(1.0,1.0,1.0)
    ren.SetBackground(0.1, 0.2, 0.4)

    renWin.SetSize(500, 500)

    #ren.ResetCamera()
    #cam1 = ren.GetActiveCamera()
    #cam1.SetPosition(1000,0,500)
    #cam1.SetFocalPoint(0,0,500)

    iren.Initialize()
    renWin.Render()
    iren.Start()
Ejemplo n.º 19
0
    def plot(self, struct):
        # Crea self. data1, legend, filename, fieldname, dim, has_field, tracker, revision
        if not self.call_config(struct):
            return

        # Actualiza campos
        self.update_field_type('vector', True)
        self.update_legend_data()

        # Crea self.src
        if not self.call_src():
            return

        # Obtenemos los vectores
        self.ugrid = self.construct_data(self.src)
        self.src_vc = vtk.vtkAssignAttribute()
        if vtk.vtkVersion.GetVTKMajorVersion() < 6:
            self.src_vc.SetInput(self.ugrid)
        else:
            self.src_vc.SetInputData(self.ugrid)

        # Segunda parte para incluir el visor
        # Pinta los elementos

        # Obtiene los centros de las celdas si se usa dicho tipo de elemento
        if self.data1.get(
                'fielddomain'
        ) == 'cell':  # vtk does not seem to support cell vectors
            self.cellcenters = vtk.vtkCellCenters()
            self.cellcenters.SetInputConnection(self.src_vc.GetOutputPort())
            self.cellcenters_click = vtk.vtkCellCenters()  # ALPHA-vc
            self.cellcenters_click.SetInputConnection(
                self.src.GetOutputPort())  # ALPHA-vc

        self.ini_params()
        #I##############################################################################
        ####### Inicializamos el dibujante #############################################
        # Create source for streamtubes
        self.seeds = vtk.vtkPointSource()
        self.seeds.SetRadius(
            self.lastradio)  # zona que abarca la salida de puntos
        self.seeds.SetCenter(self.lastcenter)
        print '====>plot ->> self.seeds.SetCenter', self.lastcenter[
            0], ',', self.lastcenter[1], ',', self.lastcenter[2]
        self.seeds.SetNumberOfPoints(self.lastnlin)

        self.lin = vtk.vtkStreamTracer()
        self.lin.SetInputConnection(self.src.GetOutputPort())
        if vtk.vtkVersion.GetVTKMajorVersion() < 6:
            self.lin.SetSource(self.seeds.GetOutput())
        else:
            self.lin.SetSourceConnection(self.seeds.GetOutputPort())

####### Configuramos el dibujante ##############################################
        self.lin.SetStartPosition(self.lastcenter)
        print '====>plot ->> self.lin.SetStartPosition', self.lastcenter[
            0], ',', self.lastcenter[1], ',', self.lastcenter[2]
        self.lin.SetMaximumPropagation(500)
        self.lin.SetInitialIntegrationStep(0.5)
        #self.lin.SetIntegrationStepUnit(2) # 2 = CELL_LENGTH_UNIT
        self.lin.SetIntegrationDirectionToBoth()

        integ = vtk.vtkRungeKutta4()
        self.lin.SetIntegrator(integ)

        ####### Configuramos el filtro #################################################
        self.streamTube = vtk.vtkTubeFilter()
        self.streamTube.SetInputConnection(self.lin.GetOutputPort())
        self.streamTube.SetInputArrayToProcess(1, 0, 0, 0, 1)
        self.streamTube.SetRadius(self.lastancho)
        self.streamTube.SetNumberOfSides(12)
        self.streamTube.SetVaryRadiusToVaryRadiusByVector()

        #F###### Configuramos la tabla de colores ######################################
        # Iniicializamos la tabla de asignacion de colores
        self.lut = vtk.vtkLookupTable()
        self.lut.SetRampToLinear()
        self.lut.SetScaleToLinear()
        self.lut.SetVectorModeToMagnitude(
        )  # When using vector magnitude for coloring
        self.lut.Build()

        if self.vectors is not None:
            self.lutrange = self.vectors.GetRange(-1)
            self.lut.SetTableRange(self.lutrange)

####### Configuramos el mapper #################################################
        self.pdM = vtk.vtkPolyDataMapper()
        self.pdM.SetInputConnection(self.streamTube.GetOutputPort())
        #Definicion del campo y el rango para colorear
        if self.vectors is not None:
            self.pdM.SelectColorArray(self.vectors.GetName())
            self.pdM.SetScalarRange(self.lutrange)
            if self.data1.get('fielddomain') == 'cell':
                self.pdM.SetScalarModeToUseCellFieldData()
            else:
                self.pdM.SetScalarModeToUsePointFieldData()
            self.pdM.SetColorModeToMapScalars()
            self.pdM.InterpolateScalarsBeforeMappingOff()
            self.pdM.ScalarVisibilityOn()
        self.pdM.SetLookupTable(self.lut)
        self.pdM.UseLookupTableScalarRangeOn()
        self.pdM.Update()

        ####### Configuramos el actor ##################################################
        self.linA = vtk.vtkActor()
        self.linA.SetMapper(self.pdM)
        self.linA.VisibilityOn()
        self.linA.GetProperty().SetAmbient(1.0)
        self.linA.GetProperty().SetDiffuse(0.0)
        self.linA.GetProperty().SetSpecular(0.0)

        #F##############################################################################

        #para mostrar surface e wireframe ao mesmo tempo
        self.wireM2 = vtk.vtkDataSetMapper()
        self.wireM2.SetInputConnection(self.src_vc.GetOutputPort())
        self.wireM2.ScalarVisibilityOff()
        self.wireA2 = vtk.vtkActor()
        self.wireA2.SetMapper(self.wireM2)
        self.wireA2.GetProperty().SetRepresentationToWireframe()
        self.wireA2.GetProperty().SetColor(Plot.edges_color)
        self.add_opacity_2([self.linA,
                            self.wireA2])  # Opacity: 100%/75%/50%/25%/0%
        # Incluimos los actores en el renderer
        self.rens[0].AddActor(self.wireA2)
        self.rens[0].AddActor(self.linA)

        # Si estamos en modo interactivo configuramos el clicker
        if interactive:
            self.set_iren()  # Configura el interactor
            if self.data1.get('fielddomain') == 'cell':
                self.clicker.set_point_cell('point')  # así ok
                self.clicker.set_objects(self.cellcenters_click, self.rens[0],
                                         self.iren, self.widget)  # ALPHA-vc
            else:
                self.clicker.set_point_cell(self.data1.get('fielddomain'))
                self.clicker.set_objects(self.src, self.rens[0], self.iren,
                                         self.widget)  # ALPHA-vc
            self.clicker.set_props([self.wireA2])
            self.clicker.setup()

        # Obtenemos los datos si los hay en el xml
        newlast = self.read_params(struct)
        changed = self.test_params(newlast)
        if changed:
            self.apply_params()

        # Reseteamos las camaras de todos los renderers
        for ren in self.rens:  # WORKAROUND (aparecia non centrada) // + outline
            ren.ResetCamera()

        # Incluye la barra de escala si tenemos vectores
        if self.vectors is not None:
            self.scalarrange.local_set(self.lutrange)
            self.add_scalarbar_1()
            self.add_scalarbar_2(self.lut)

        self.add_outline_2(self.src_vc)

        self.done = True
Ejemplo n.º 20
0
ctf.SetTableRange(a, b)

# A plane for the seeds
plane = vtk.vtkPlaneSource()
plane.SetOrigin(xmi, math.ceil(ymi), zmi)
plane.SetPoint1(xma, math.ceil(ymi), zmi)
plane.SetPoint2(xmi, math.ceil(ymi), zma)
plane.SetXResolution(6)
plane.SetYResolution(6)

# Streamlines
stream = vtk.vtkStreamLine()
stream.SetSource(plane.GetOutput())
stream.SetInput(reader.GetOutput())
stream.SetIntegrationDirectionToForward()
stream.SetIntegrator(vtk.vtkRungeKutta4())
stream.SetStepLength(0.1)

streamMapper = vtk.vtkPolyDataMapper()
streamMapper.SetLookupTable(ctf)
streamMapper.SetInput(stream.GetOutput())
streamMapper.SetScalarRange(a, b)
streamActor = vtk.vtkActor()
streamActor.SetMapper(streamMapper)
streamActor.GetProperty().SetLineWidth(3.0)

#Colour Bar
cbar = vtk.vtkScalarBarActor()
cbar.SetLookupTable(ctf)
cbar.SetOrientationToHorizontal()
cbar.SetPosition(0.1, 0.03)
Ejemplo n.º 21
0
pl3d.SetQFileName(VTK_DATA_ROOT + "/Data/combq.bin")
pl3d.SetScalarFunctionNumber(100)
pl3d.SetVectorFunctionNumber(202)
pl3d.Update()
pl3d_output = pl3d.GetOutput().GetBlock(0)

# The line widget is used seed the streamlines.
lineWidget = vtk.vtkLineWidget()
seeds = vtk.vtkPolyData()
lineWidget.SetInputData(pl3d_output)
lineWidget.SetAlignToYAxis()
lineWidget.PlaceWidget()
lineWidget.GetPolyData(seeds)
lineWidget.ClampToBoundsOn()

rk4 = vtk.vtkRungeKutta4()
streamer = vtk.vtkStreamLine()
streamer.SetInputData(pl3d_output)
streamer.SetSourceData(seeds)
streamer.SetMaximumPropagationTime(100)
streamer.SetIntegrationStepLength(0.2)
streamer.SetStepLength(0.001)
streamer.SetNumberOfThreads(1)
streamer.SetIntegrationDirectionToForward()
streamer.VorticityOn()
streamer.SetIntegrator(rk4)
rf = vtk.vtkRibbonFilter()
rf.SetInputConnection(streamer.GetOutputPort())
rf.SetWidth(0.1)
rf.SetWidthFactor(5)
streamMapper = vtk.vtkPolyDataMapper()
Ejemplo n.º 22
0
def main(vector_file, magnitude_file):

    ColorRange = vtk.vtkLookupTable()
    ColorRange.SetTableRange(0, 1)
    ColorRange.SetHueRange(0, 1)
    ColorRange.SetSaturationRange(1, 1)
    ColorRange.SetAlphaRange(0.3, 0.5)
    ColorRange.Build()

    reader = vtk.vtkStructuredPointsReader()
    reader.SetFileName(vector_file)
    reader.Update()

    data = reader.GetOutput()

    range1 = data.GetScalarRange()
    v0 = range1[0]
    v1 = range1[1]

    reader_magnitude = vtk.vtkStructuredPointsReader()
    reader_magnitude.SetFileName(magnitude_file)
    reader_magnitude.Update()

    contour = vtk.vtkContourFilter()
    contour.SetInput(reader_magnitude.GetOutput())
    contour.SetValue(0, 1)

    normals = vtk.vtkPolyDataNormals()
    normals.SetInput(contour.GetOutput())
    normals.SetFeatureAngle(60)
    normals.ConsistencyOff()
    normals.SplittingOff()

    mapper_magnitude = vtk.vtkPolyDataMapper()
    mapper_magnitude.SetInput(normals.GetOutput())
    mapper_magnitude.SetLookupTable(ColorRange)
    mapper_magnitude.SetColorModeToMapScalars()
    mapper_magnitude.SetScalarRange(v0, v1)

    actor_magnitude = vtk.vtkActor()
    actor_magnitude.SetMapper(mapper_magnitude)

    sphere = vtk.vtkSphereSource()
    sphere.SetRadius(2)
    sphere.SetCenter(15, 15, 15)  # Critical point for all 3 test datasets
    sphere.SetThetaResolution(10)

    integrator = vtk.vtkRungeKutta4()

    stream = vtk.vtkStreamLine()
    stream.SetInput(reader.GetOutput())
    stream.SetSource(sphere.GetOutput())
    stream.SetIntegrator(integrator)
    stream.SetMaximumPropagationTime(500)
    stream.SetIntegrationStepLength(0.1)
    stream.SetIntegrationDirectionToIntegrateBothDirections()
    stream.SetStepLength(0.1)

    scalarSurface = vtk.vtkRuledSurfaceFilter()
    scalarSurface.SetInput(stream.GetOutput())
    scalarSurface.SetOffset(0)
    scalarSurface.SetOnRatio(2)
    scalarSurface.PassLinesOn()
    scalarSurface.SetRuledModeToPointWalk()
    scalarSurface.SetDistanceFactor(50)

    tube = vtk.vtkTubeFilter()
    tube.SetInput(scalarSurface.GetOutput())
    tube.SetRadius(0.1)
    tube.SetNumberOfSides(6)

    dataMapper = vtk.vtkPolyDataMapper()
    dataMapper.SetInput(tube.GetOutput())
    dataMapper.SetScalarRange(v0, v1)
    dataMapper.SetLookupTable(ColorRange)

    dataActor = vtk.vtkActor()
    dataActor.SetMapper(dataMapper)

    probe = vtk.vtkProbeFilter()
    probe.SetInput(stream.GetOutput())
    probe.SetSource(reader.GetOutput())

    mask = vtk.vtkMaskPoints()
    mask.SetInput(probe.GetOutput())
    mask.SetOnRatio(60)
    mask.RandomModeOn()

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)
    cone.SetHeight(1.0)
    cone.SetRadius(0.2)

    transform = vtk.vtkTransform()
    transform.Translate(0, 0, 0)

    transformFilter = vtk.vtkTransformPolyDataFilter()
    transformFilter.SetInput(cone.GetOutput())
    transformFilter.SetTransform(transform)

    glyph = vtk.vtkGlyph3D()
    glyph.SetInput(mask.GetOutput())
    glyph.SetSource(transformFilter.GetOutput())
    glyph.SetScaleModeToScaleByVector()
    glyph.SetScaleFactor(1.5)
    glyph.SetVectorModeToUseVector()
    glyph.SetColorModeToColorByVector()

    glyphMapper = vtk.vtkPolyDataMapper()
    glyphMapper.SetInput(glyph.GetOutput())
    glyphMapper.SetLookupTable(ColorRange)

    glyphActor = vtk.vtkActor()
    glyphActor.SetMapper(glyphMapper)

    outline = vtk.vtkOutlineFilter()
    outline.SetInput(reader.GetOutput())

    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInput(outline.GetOutput())

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(1, 1, 1)

    criticalMarker = vtk.vtkSphereSource()
    criticalMarker.SetRadius(1.0)
    criticalMarker.SetCenter(15, 15, 15)
    criticalMarker.SetThetaResolution(10)

    criticalMapper = vtk.vtkPolyDataMapper()
    criticalMapper.SetInput(criticalMarker.GetOutput())

    criticalActor = vtk.vtkActor()
    criticalActor.SetMapper(criticalMapper)
    criticalActor.GetProperty().SetColor(1, 1, 0)
    criticalActor.GetProperty().SetOpacity(0.5)

    colorActor = vtk.vtkScalarBarActor()
    colorActor.SetLookupTable(ColorRange)

    renderer = vtk.vtkRenderer()

    renderer_window = vtk.vtkRenderWindow()
    renderer_window.AddRenderer(renderer)
    renderer_window.SetSize(512, 512)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderer_window)
    renderer.AddActor(actor_magnitude)
    renderer.AddActor(outlineActor)
    renderer.AddActor(criticalActor)
    renderer.AddActor(colorActor)
    renderer.AddActor(dataActor)
    renderer.AddActor(glyphActor)

    renderer.ResetCamera()

    style = vtk.vtkInteractorStyleTrackballCamera()
    # style = vtk.vtkInteractorStyleRubberBandZoom()
    # style = vtk.vtkInteractorStyleTerrain()
    interactor.SetInteractorStyle(style)

    renderer_window.Render()
    interactor.Start()
Ejemplo n.º 23
0
# random cloud of points and then use those as integration seeds. We
# select the integration order to use (RungeKutta order 4) and
# associate it with the streamer. The start position is the position
# in world space where we want to begin streamline integration; and we
# integrate in both directions. The step length is the length of the
# line segments that make up the streamline (i.e., related to
# display). The IntegrationStepLength specifies the integration step
# length as a fraction of the cell size that the streamline is in.

# Create source for streamtubes
seeds = vtk.vtkPointSource()
seeds.SetRadius(0.15)
seeds.SetCenter(0.1, 2.1, 0.5)
seeds.SetNumberOfPoints(6)

integ = vtk.vtkRungeKutta4()
streamer = vtk.vtkStreamLine()
streamer.SetInputConnection(reader.GetOutputPort())
streamer.SetSource(seeds.GetOutput())
streamer.SetMaximumPropagationTime(500)
streamer.SetStepLength(0.5)
streamer.SetIntegrationStepLength(0.05)
streamer.SetIntegrationDirectionToIntegrateBothDirections()
streamer.SetIntegrator(integ)

# The tube is wrapped around the generated streamline. By varying the
# radius by the inverse of vector magnitude, we are creating a tube
# whose radius is proportional to mass flux (in incompressible flow).
streamTube = vtk.vtkTubeFilter()
streamTube.SetInputConnection(streamer.GetOutputPort())
streamTube.SetRadius(0.02)
Ejemplo n.º 24
0
def streampoints(filename):
 reader = vtk.vtkStructuredPointsReader()
 reader.SetFileName(filename)
 reader.Update()

 
 outline=vtk.vtkOutlineFilter()
 outline.SetInputConnection(reader.GetOutputPort())

 lineMapper = vtk.vtkDataSetMapper()
 lineMapper.SetInputConnection(outline.GetOutputPort())
 lineActor = vtk.vtkActor()
 lineActor.SetMapper(lineMapper)


 pdata=vtk.vtkPolyData()
 points=vtk.vtkPoints()   
 #Selecting source for Streamtracer 
 ns=200
 r=100
 Z=25
 for i in range(0, ns):
  a=(2*i*pi)/ns
  X=r*cos(a)
  Y=r*sin(a)
 # for Z in range(0,256):
  points.InsertNextPoint(float(X),float(Y),float(Z))

 pdata.SetPoints(points)
 
 integ0 = vtk.vtkRungeKutta4()
 integ1 = vtk.vtkRungeKutta4()
 integ2 = vtk.vtkRungeKutta4()

# Defining controller for vtkDistributedStreamTracer

 controller=vtk.vtkMPIController()
 Stream0 = vtk.vtkDistributedStreamTracer() 
 #Stream0 = vtk.vtkStreamTracer() 
 Stream0.SetInputConnection(reader.GetOutputPort())
 Stream0.SetSource(line0.GetOutput())
 #Stream0.SetSource(pdata)

# Setting the parameters for Integration. Here you can change the integration parameters according to your desire.
  
 Stream0.SetMaximumPropagation(255)
 Stream0.SetController(controller)
 Stream0.SetInitialIntegrationStepUnitToCellLengthUnit()
 Stream0.SetMaximumIntegrationStep(2000)
 Stream0.SetInitialIntegrationStep(0.5)
 Stream0.SetIntegrator(integ0)
 Stream0.SetIntegrationDirectionToBoth()

 Stream0.Update()

# Visualizing streamline as a tube.Here you can change the radius of the streamtube by changing the values of radius.
 
 streamTube0 = vtk.vtkTubeFilter()
 streamTube0.SetInputConnection(Stream0.GetOutputPort())
 streamTube0.SetRadius(0.25)
 streamTube0.SetNumberOfSides(16)
 #streamTube0.SetVaryRadiusToVaryRadiusByVector()
 mapStreamTube0 = vtk.vtkPolyDataMapper()
 mapStreamTube0.SetInputConnection(streamTube0.GetOutputPort())
 #mapStreamTube.SetScalarRange(reader.GetOutput())
 streamTubeActor0 = vtk.vtkActor()
 streamTubeActor0.SetMapper(mapStreamTube0)
 streamTubeActor0.GetProperty().BackfaceCullingOn()
 streamTubeActor0.GetProperty().SetColor(0, 1, 1) 

 Stream1 = vtk.vtkDistributedStreamTracer() 
 #Stream0 = vtk.vtkStreamTracer() 
 Stream1.SetInputConnection(reader.GetOutputPort())
 Stream1.SetSource(line1.GetOutput())
 #Stream0.SetSource(pdata)
 
 Stream1.SetMaximumPropagation(255)
 Stream1.SetController(controller)
 Stream1.SetInitialIntegrationStepUnitToCellLengthUnit()
 Stream1.SetMaximumIntegrationStep(2000)
 Stream1.SetInitialIntegrationStep(0.5)
 Stream1.SetIntegrator(integ1)
 Stream1.SetIntegrationDirectionToBoth()

 Stream1.Update()


 streamTube1= vtk.vtkTubeFilter()
 streamTube1.SetInputConnection(Stream0.GetOutputPort())
 streamTube1.SetRadius(0.25)
 streamTube1.SetNumberOfSides(12)
 #streamTube1.SetVaryRadiusToVaryRadiusByVector()
 mapStreamTube1 = vtk.vtkPolyDataMapper()
 mapStreamTube1.SetInputConnection(streamTube1.GetOutputPort())
 #mapStreamTube.SetScalarRange(reader.GetOutput())
 streamTubeActor1 = vtk.vtkActor()
 streamTubeActor1.SetMapper(mapStreamTube1)
 streamTubeActor1.GetProperty().BackfaceCullingOn()
 streamTubeActor1.GetProperty().SetColor(0.5, 0.25, 1) 
 #ren.AddActor(lineActor)

 Stream2 = vtk.vtkDistributedStreamTracer() 
 #Stream0 = vtk.vtkStreamTracer() 
 Stream2.SetInputConnection(reader.GetOutputPort())
 Stream2.SetSource(line2.GetOutput())
 #Stream2.SetSource(line1.GetOutput())
 #Stream2.SetSource(line0.GetOutput())
 
#Stream0.SetSource(pdata)
 
 Stream2.SetMaximumPropagation(255)
 Stream2.SetController(controller)
 Stream2.SetInitialIntegrationStepUnitToCellLengthUnit()
 Stream2.SetMaximumIntegrationStep(2000)
 Stream2.SetInitialIntegrationStep(0.5)
 Stream2.SetIntegrator(integ2)
 Stream2.SetIntegrationDirectionToBoth()

 Stream2.Update()


 streamTube2= vtk.vtkTubeFilter()
 streamTube2.SetInputConnection(Stream0.GetOutputPort())
 streamTube2.SetRadius(0.25)
 streamTube2.SetNumberOfSides(12)
 #streamTube2.SetVaryRadiusToVaryRadiusByVector()
 mapStreamTube2 = vtk.vtkPolyDataMapper()
 mapStreamTube2.SetInputConnection(streamTube2.GetOutputPort())
 #mapStreamTube.SetScalarRange(reader.GetOutput())
 streamTubeActor2 = vtk.vtkActor()
 streamTubeActor2.SetMapper(mapStreamTube2)
 streamTubeActor2.GetProperty().BackfaceCullingOn()
 streamTubeActor2.GetProperty().SetColor(0, .025, 0.125) 

 # ren.AddActor(lineActor)
# Adding the streanline to the actor for rendering

 ren.AddActor(streamTubeActor0)
 ren.AddActor(streamTubeActor1)
 #ren.AddActor(streamTubeActor2)

 renWin.Render()
 ren.ResetCamera()

# Selecting renderer good position and focal point. Here You can change the camera positin for viewing a good image that you need. 

 ren.GetActiveCamera().SetPosition(0, 1,0)
 ren.GetActiveCamera().SetFocalPoint(0,0,0)
 ren.GetActiveCamera().SetViewUp(0,0 , 1)

 

 ren.GetActiveCamera().Dolly(1.4)
 ren.ResetCameraClippingRange()
	
 largestreamline=vtk.vtkRenderLargeImage()
 largestreamline.SetInput(ren)
 largestreamline.SetMagnification(9)
 
 #cam1 = ren.GetActiveCamera().Zoom(z)
 #cam1 = ren.GetActiveCamera().Elevation(2)
 #cam1 = ren.GetActiveCamera().Azimuth(-5)
 #ren.SetActiveCamera(cam1)
 ren.ResetCamera()
 # Writing .PNG Images of the streamlines with images.
 
 writer = vtk.vtkPNGWriter()
 writer.SetInputConnection(largestreamline.GetOutputPort())
 writer.SetFileName("Streamline.png")
 writer.Modified()
 writer.Write()
Ejemplo n.º 25
0
outlineMapper = vtk.vtkPolyDataMapper()
outlineMapper.SetInputConnection(outline.GetOutputPort())

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

# Now create streamlines from a rake of seed points
pt1 = [0.001,0.1,0.5]
pt2 = [0.001,0.9,0.5]
line = vtk.vtkLineSource()
line.SetResolution(numStreamlines-1)
line.SetPoint1(pt1)
line.SetPoint2(pt2)
line.Update()

rk4 = vtk.vtkRungeKutta4()
strategy = vtk.vtkClosestNPointsStrategy()
ivp = vtk.vtkInterpolatedVelocityField()
ivp.SetFindCellStrategy(strategy)

streamer = vtk.vtkStreamTracer()
streamer.SetInputConnection(append.GetOutputPort())
streamer.SetSourceConnection(line.GetOutputPort())
streamer.SetMaximumPropagation(10)
streamer.SetInitialIntegrationStep(.2)
streamer.SetIntegrationDirectionToForward()
streamer.SetMinimumIntegrationStep(0.01)
streamer.SetMaximumIntegrationStep(0.5)
streamer.SetTerminalSpeed(1.0e-12)
streamer.SetMaximumError(1.0e-06)
streamer.SetComputeVorticity(0)
Ejemplo n.º 26
0
Archivo: wind.py Proyecto: fuesika/facy
glyphActor = vtk.vtkActor()
glyphActor.SetMapper( glyphMapper )

## define streamlines #############################################################################
# line source for streamline #
LineSource = vtk.vtkLineSource()
LineSource.SetPoint1(17.5, 70.2, 0)
LineSource.SetPoint2(60, 70.2, 0)
LineSource.SetResolution(40)

LineSourceMapper = vtk.vtkPolyDataMapper()
LineSourceMapper.SetInputConnection( LineSource.GetOutputPort() )
LineSourceActor = vtk.vtkActor()
LineSourceActor.SetMapper( LineSourceMapper )

integ = vtk.vtkRungeKutta4() # integrator for generating the streamlines #
streamer = vtk.vtkStreamLine()
streamer.SetInputConnection( reader.GetOutputPort() )
streamer.SetSource( LineSource.GetOutput() )
streamer.SetMaximumPropagationTime(500)
streamer.SetIntegrationStepLength(.02)
streamer.SetStepLength(.01)
streamer.SetIntegrationDirectionToIntegrateBothDirections()
streamer.SetIntegrator( integ )

streamerMapper = vtk.vtkPolyDataMapper()
streamerMapper.SetInputConnection( streamer.GetOutputPort() )
streamerMapper.SetLookupTable( lut )
streamerActor = vtk.vtkActor()
streamerActor.SetMapper( streamerMapper )
streamerActor.VisibilityOn()
Ejemplo n.º 27
0
def main(vector_file, magnitude_file):

    num_critical_points = 6
    CriticalPoints = vtk.vtkPoints()

    CriticalPoints.InsertNextPoint(35, 14, 20)
    CriticalPoints.InsertNextPoint(55, 15, 20)
    CriticalPoints.InsertNextPoint(65, 45, 19)
    CriticalPoints.InsertNextPoint(45, 44.8, 20)
    CriticalPoints.InsertNextPoint(20, 29.7, 19.8)
    CriticalPoints.InsertNextPoint(10, 32.2, 16.1)

    ColorRange = vtk.vtkLookupTable()
    ColorRange.SetTableRange(0, 1)
    ColorRange.SetHueRange(0, 1)
    ColorRange.SetSaturationRange(1, 1)
    ColorRange.SetAlphaRange(0.3, 0.5)
    ColorRange.Build()

    reader = vtk.vtkStructuredPointsReader()
    reader.SetFileName(vector_file)
    reader.Update()

    mags = reader.GetOutput()

    range1 = mags.GetScalarRange()
    v0 = range1[0]
    v1 = range1[1]

    reader_magnitude = vtk.vtkStructuredPointsReader()
    reader_magnitude.SetFileName(magnitude_file)
    reader_magnitude.Update()

    # All entities initialized equal to number of critical points
    sphere1, stream1, scalarSurface1, tube1, dataMapper1, dataActor1, criticalMarker1, criticalMapper1, criticalActor1, probe1, mask1, glyph1, glyphMapper1, glyphActor1, plane1 = (
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
    )
    for i in range(0, num_critical_points):
        sphere1.append(vtk.vtkSphereSource())
        stream1.append(vtk.vtkStreamLine())
        scalarSurface1.append(vtk.vtkRuledSurfaceFilter())
        tube1.append(vtk.vtkTubeFilter())
        dataMapper1.append(vtk.vtkPolyDataMapper())
        dataActor1.append(vtk.vtkActor())

        criticalMarker1.append(vtk.vtkSphereSource())
        criticalMapper1.append(vtk.vtkPolyDataMapper())
        criticalActor1.append(vtk.vtkActor())

        probe1.append(vtk.vtkProbeFilter())
        mask1.append(vtk.vtkMaskPoints())
        glyph1.append(vtk.vtkGlyph3D())
        glyphMapper1.append(vtk.vtkPolyDataMapper())
        glyphActor1.append(vtk.vtkActor())

        plane1.append(vtk.vtkPlaneSource())

    integ = vtk.vtkRungeKutta4()

    cone = vtk.vtkConeSource()
    cone.SetResolution(8)
    cone.SetHeight(1.0)
    cone.SetRadius(0.2)

    transform = vtk.vtkTransform()
    transform.Translate(0, 0, 0)

    transformFilter = vtk.vtkTransformPolyDataFilter()
    transformFilter.SetInput(cone.GetOutput())
    transformFilter.SetTransform(transform)

    outline = vtk.vtkOutlineFilter()
    outline.SetInput(reader.GetOutput())

    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInput(outline.GetOutput())

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(1, 1, 1)

    bar = vtk.vtkScalarBarActor()
    bar.SetLookupTable(ColorRange)

    renderer = vtk.vtkRenderer()

    for i in range(0, num_critical_points):
        sphere1[i].SetRadius(2)
        sphere1[i].SetCenter(
            CriticalPoints.GetPoint(i)[0], CriticalPoints.GetPoint(i)[1], CriticalPoints.GetPoint(i)[2]
        )
        sphere1[i].SetThetaResolution(1)
        stream1[i].SetInput(reader.GetOutput())
        stream1[i].SetSource(sphere1[i].GetOutput())
        stream1[i].SetIntegrator(integ)
        stream1[i].SetMaximumPropagationTime(500)
        stream1[i].SetIntegrationStepLength(0.1)
        stream1[i].SetIntegrationDirectionToIntegrateBothDirections()
        stream1[i].SetStepLength(0.1)

        scalarSurface1[i].SetInput(stream1[i].GetOutput())
        scalarSurface1[i].SetOffset(0)
        scalarSurface1[i].SetOnRatio(2)
        scalarSurface1[i].PassLinesOn()
        scalarSurface1[i].SetRuledModeToPointWalk()
        scalarSurface1[i].SetDistanceFactor(50)

        tube1[i].SetInput(scalarSurface1[i].GetOutput())
        tube1[i].SetRadius(0.1)
        tube1[i].SetNumberOfSides(6)

        dataMapper1[i].SetInput(tube1[i].GetOutput())
        dataMapper1[i].SetScalarRange(v0, v1)
        dataMapper1[i].SetLookupTable(ColorRange)

        dataActor1[i].SetMapper(dataMapper1[i])
        # renderer.AddActor(dataActor1[i])

        criticalMarker1[i].SetRadius(1.0)
        criticalMarker1[i].SetCenter(
            CriticalPoints.GetPoint(i)[0], CriticalPoints.GetPoint(i)[1], CriticalPoints.GetPoint(i)[2]
        )
        criticalMarker1[i].SetThetaResolution(10)
        criticalMapper1[i].SetInput(criticalMarker1[i].GetOutput())

        criticalActor1[i].SetMapper(criticalMapper1[i])
        criticalActor1[i].GetProperty().SetColor(1, 1, 0)
        criticalActor1[i].GetProperty().SetOpacity(0.5)
        # renderer.AddActor(criticalActor1[i])

        probe1[i].SetInput(stream1[i].GetOutput())
        probe1[i].SetSource(reader.GetOutput())

        mask1[i].SetInput(probe1[i].GetOutput())
        mask1[i].SetOnRatio(60)
        mask1[i].RandomModeOn()

        glyph1[i].SetInput(mask1[i].GetOutput())
        glyph1[i].SetSource(transformFilter.GetOutput())
        glyph1[i].SetScaleModeToScaleByVector()
        glyph1[i].SetScaleFactor(2)
        glyph1[i].SetVectorModeToUseVector()
        glyph1[i].SetColorModeToColorByVector()

        glyphMapper1[i].SetInput(glyph1[i].GetOutput())
        glyphMapper1[i].SetLookupTable(ColorRange)

        glyphActor1[i].SetMapper(glyphMapper1[i])
        # renderer.AddActor(glyphActor1[i])

    # removeActors1(renderer, dataActor, criticalActor, glyphActor, dataActor1, criticalActor1, glyphActor1)

    mags = reader.GetOutput()
    bounds = mags.GetBounds()
    x0 = bounds[0]
    x1 = bounds[1]
    y0 = bounds[2]
    y1 = bounds[3]
    z0 = bounds[4]
    z1 = bounds[5]

    range1 = mags.GetScalarRange()
    v0 = range1[0]
    v1 = range1[1]

    plane1[0].SetOrigin(x0, y0, z0)
    plane1[0].SetPoint1(x0, y1, z0)
    plane1[0].SetPoint2(x0, y0, z1)

    plane1[1].SetOrigin(x0, y0, z0)
    plane1[1].SetPoint1(x0, y1, z0)
    plane1[1].SetPoint2(x1, y0, z0)

    plane1[2].SetOrigin(x0, y0, z0)
    plane1[2].SetPoint1(x0, y0, z1)
    plane1[2].SetPoint2(x1, y0, z0)

    plane1[3].SetOrigin(x1, y1, z1)
    plane1[3].SetPoint1(x1, y1, z0)
    plane1[3].SetPoint2(x1, y0, z1)

    plane1[4].SetOrigin(x1, y1, z1)
    plane1[4].SetPoint1(x0, y1, z1)
    plane1[4].SetPoint2(x1, y1, z0)

    plane1[5].SetOrigin(x1, y1, z1)
    plane1[5].SetPoint1(x0, y1, z1)
    plane1[5].SetPoint2(x1, y1, z0)

    for i in range(0, num_critical_points):
        plane1[i].SetResolution(5, 5)
        stream1[i].SetSource(plane1[i].GetOutput())
        renderer.AddActor(dataActor1[i])
        renderer.AddActor(glyphActor1[i])
        glyph1[i].SetScaleFactor(4)

    renderer.AddActor(bar)
    renderer.AddActor(outlineActor)

    for i in range(0, num_critical_points):
        renderer.AddActor(criticalActor1[i])

    renderer_window = vtk.vtkRenderWindow()
    renderer_window.AddRenderer(renderer)
    renderer_window.SetSize(512, 512)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderer_window)

    style = vtk.vtkInteractorStyleTrackballCamera()
    interactor.SetInteractorStyle(style)

    renderer.AddActor(bar)

    renderer.AddActor(outlineActor)

    renderer_window.Render()
    interactor.Start()
Ejemplo n.º 28
0
def Main():
    global isovalue, contours, ren
    
    # Create the RenderWindow, Renderer and both Actors
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.SetMultiSamples(0)
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    iren.RemoveObservers('RightButtonPressEvent')
    iren.AddObserver('RightButtonPressEvent', print_camera_settings, 1.0)
    iren.AddObserver('RightButtonPressEvent', after_print_camera_settings, -1.0)

    print "data: %s %s %s" % (sys.argv[1], sys.argv[2], sys.argv[3])
    
    cfdreader = vtk.vtkStructuredPointsReader()
    cfdreader.SetFileName(sys.argv[1])
    
    # setup wing data
    wingReader = vtk.vtkUnstructuredGridReader()
    wingReader.SetFileName(sys.argv[3])
    wingReader.Update()
    wingMapper = vtk.vtkDataSetMapper()
    wingMapper.SetInputConnection(wingReader.GetOutputPort())
    wingActor = vtk.vtkActor()
    wingActor.SetMapper(wingMapper)
    wingActor.GetProperty().SetColor(.4, .4, .4)
    
    bRakesToActor = [True, True, False]
    bWingToActor = True
    
    datamin = 0
    datamax = 230
    
    lut = vtk.vtkColorTransferFunction()
    lut.SetColorSpaceToHSV()
    lut.AddHSVPoint(datamin, 0, 1, 1)
    dis = float(datamax - datamin) / 7
    for i in range(0, 8):
        lut.AddHSVPoint(float(datamin + dis * i), 0.1 * i, 1, 1)
    
    colorBar = vtk.vtkScalarBarActor()
    colorBar.SetLookupTable(lut)
    colorBar.SetTitle("")
    colorBar.SetNumberOfLabels(6)
    colorBar.SetLabelFormat("%4.0f")
    colorBar.SetPosition(0.9, 0.1)
    colorBar.SetWidth(0.05)
    colorBar.SetHeight(0.4)
    ren.AddActor(colorBar)
    
    rakes = [
             vtk.vtkLineSource(),
             vtk.vtkLineSource(),
             vtk.vtkLineSource()
             ]
    rakes[0].SetPoint1(-230, -230, 0)
    rakes[0].SetPoint2(230, 230, 0)
    rakes[0].SetResolution(50)
    
    rakes[1].SetPoint1(230, -230, 0)
    rakes[1].SetPoint2(-230, 230, 0)
    rakes[1].SetResolution(50)
    
    rakes[2].SetPoint1(0, -100, 10)
    rakes[2].SetPoint2(0, 100, 10)
    rakes[2].SetResolution(60)
    
    rakeColors = [
                  [0, 1, 0],
                  [0, 1, 0],
                  [0, 1, 0],
                  ]
    
    for i in range(0, len(rakes)):
        integ = vtk.vtkRungeKutta4()
        streamLine = vtk.vtkStreamLine()
        streamLine.SetInputConnection(cfdreader.GetOutputPort())
        streamLine.SetSourceConnection(rakes[i].GetOutputPort())
        streamLine.SetMaximumPropagationTime(50);
        streamLine.SetIntegrationStepLength(1);
        streamLine.SetStepLength(0.01);
        streamLine.SetIntegrationDirectionToForward();
        streamLine.SetIntegrator(integ)
        streamLine.SpeedScalarsOn()
        
        streamLineMapper = vtk.vtkPolyDataMapper()
        streamLineMapper.SetInputConnection(streamLine.GetOutputPort())
        streamLineMapper.SetLookupTable(lut)
        
        streamLineActor = vtk.vtkActor()
        streamLineActor.SetMapper(streamLineMapper)
        streamLineActor.GetProperty().SetColor(rakeColors[i])
        streamLineActor.GetProperty().SetOpacity(0.9);
        
        if bRakesToActor[i]:
            ren.AddActor(streamLineActor)
 
    if bWingToActor:
        ren.AddActor(wingActor)
    
    isoreader = vtk.vtkStructuredPointsReader()
    isoreader.SetFileName(sys.argv[2])
    isoreader.Update()
    
#     r = isoreader.GetOutput().GetScalarRange()
#     datamin = r[0]
#     datamax = r[1]
#     isovalue = (datamax+datamin)/2.0
    isovalue = 300
    datamin = 0
    datamax = 300
    
    contours = vtk.vtkContourFilter()
    contours.SetInputConnection(isoreader.GetOutputPort());
    contours.ComputeNormalsOn()
    contours.SetValue(0, isovalue)
    
    lut = vtk.vtkColorTransferFunction()
    lut.SetColorSpaceToHSV()
    lut.AddHSVPoint(datamin, 0, 1, 1)
    dis = (datamax - datamin) / 7
    for i in range(0, 8):
        lut.AddHSVPoint(datamin + dis * i, 0.1 * i, 1, 1)
        
    isoMapper = vtk.vtkPolyDataMapper()
    isoMapper.SetLookupTable(lut)
    isoMapper.SetInputConnection(contours.GetOutputPort())

    isoActor = vtk.vtkActor()
    isoActor.GetProperty().SetRepresentationToWireframe()
    isoActor.SetMapper(isoMapper)
    isoActor.GetProperty().SetOpacity(0.08);

    ren.AddActor(wingActor)
    ren.AddActor(isoActor)
    
    ren.SetBackground(0, 0, 0)
    renWin.SetSize(1600, 900)
    
    isovalueSlider = vtk.vtkSliderRepresentation2D()
    isovalueSlider.SetMinimumValue(datamin)
    isovalueSlider.SetMaximumValue(datamax)
    isovalueSlider.SetValue(isovalue)
    isovalueSlider.SetTitleText("isovalue")
    isovalueSlider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
    isovalueSlider.GetPoint1Coordinate().SetValue(0.0, 0.4)
    isovalueSlider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
    isovalueSlider.GetPoint2Coordinate().SetValue(0.2, 0.4)
    isovalueSlider.SetSliderLength(0.02)
    isovalueSlider.SetSliderWidth(0.03)
    isovalueSlider.SetEndCapLength(0.01)
    isovalueSlider.SetEndCapWidth(0.03)
    isovalueSlider.SetTubeWidth(0.005)
    isovalueSlider.SetLabelFormat("%3.0lf")
    isovalueSlider.SetTitleHeight(0.02)
    isovalueSlider.SetLabelHeight(0.02)
    SliderWidget1 = vtk.vtkSliderWidget()
    SliderWidget1.SetInteractor(iren)
    SliderWidget1.SetRepresentation(isovalueSlider)
    SliderWidget1.KeyPressActivationOff()
    SliderWidget1.SetAnimationModeToAnimate()
    SliderWidget1.SetEnabled(False)
    SliderWidget1.AddObserver("InteractionEvent", isovalueSliderHandler)
    
    ren.ResetCamera()
    ren.GetActiveCamera().SetClippingRange(417.55784439078775, 1491.5763714138557)
    ren.GetActiveCamera().SetFocalPoint(118.72183980792761, 0.00012969970703125, 36.469017028808594)
    ren.GetActiveCamera().SetPosition(680.0192576650034, 16.65944318371372, 790.5781258299678)
    ren.GetActiveCamera().SetViewUp(-0.802117714199773, -0.005112780752923929, 0.5971440630533839)

    # Render
    iren.Initialize()
    renWin.Render()
    iren.Start()