Exemple #1
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkStreamTracer(), 'Processing.',
         ('vtkDataObject', 'vtkDataSet'), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Exemple #2
0
    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)
        InputArrayChoiceMixin.__init__(self)

        # 0 = RK2
        # 1 = RK4
        # 2 = RK45
        self._config.integrator = INTEG_TYPE.index('RK2')
        self._config.max_prop = 5.0
        self._config.integration_direction = INTEG_DIR.index('FORWARD')

        configList = [
            ('Vectors selection:', 'vectorsSelection', 'base:str', 'choice',
             'The attribute that will be used as vectors for the warping.',
             (input_array_choice_mixin.DEFAULT_SELECTION_STRING, )),
            ('Max propagation:', 'max_prop', 'base:float', 'text',
             'The streamline will propagate up to this lenth.'),
            ('Integration direction:', 'integration_direction', 'base:int',
             'choice', 'Select an integration direction.', INTEG_DIR_TEXTS),
            ('Integrator type:', 'integrator', 'base:int', 'choice',
             'Select an integrator for the streamlines.', INTEG_TYPE_TEXTS)
        ]

        self._streamTracer = vtk.vtkStreamTracer()

        ScriptedConfigModuleMixin.__init__(
            self, configList, {
                'Module (self)': self,
                'vtkStreamTracer': self._streamTracer
            })

        module_utils.setup_vtk_object_progress(self, self._streamTracer,
                                               'Tracing stream lines.')

        self.sync_module_logic_with_config()
Exemple #3
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkStreamTracer(),
                                       'Processing.',
                                       ('vtkDataObject', 'vtkDataSet'),
                                       ('vtkPolyData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
def _generate_vtk_err():
    """Simple operation which generates a VTK error."""
    x, y, z = np.meshgrid(np.arange(-10, 10, 0.5), np.arange(-10, 10, 0.5),
                          np.arange(-10, 10, 0.5))
    mesh = pyvista.StructuredGrid(x, y, z)
    x2, y2, z2 = np.meshgrid(np.arange(-1, 1, 0.5), np.arange(-1, 1, 0.5),
                             np.arange(-1, 1, 0.5))
    mesh2 = pyvista.StructuredGrid(x2, y2, z2)

    alg = vtk.vtkStreamTracer()
    obs = pyvista.Observer()
    obs.observe(alg)
    alg.SetInputDataObject(mesh)
    alg.SetSourceData(mesh2)
    alg.Update()
Exemple #5
0
    def __init__(self, data_directory):
        self.color_range = [0, 1]
        bike_filename = os.path.join(data_directory, "bike.vtp")
        tunnel_filename = os.path.join(data_directory, "tunnel.vtu")

        # Seeds settings
        self.resolution = 10
        self.point1 = [-0.4, 0, 0.05]
        self.point2 = [-0.4, 0, 1.5]

        # VTK Pipeline setup
        bikeReader = vtk.vtkXMLPolyDataReader()
        bikeReader.SetFileName(bike_filename)
        bikeReader.Update()
        self.bike_mesh = to_mesh_state(bikeReader.GetOutput())

        tunnelReader = vtk.vtkXMLUnstructuredGridReader()
        tunnelReader.SetFileName(tunnel_filename)
        tunnelReader.Update()

        self.lineSeed = vtk.vtkLineSource()
        self.lineSeed.SetPoint1(*self.point1)
        self.lineSeed.SetPoint2(*self.point2)
        self.lineSeed.SetResolution(self.resolution)

        streamTracer = vtk.vtkStreamTracer()
        streamTracer.SetInputConnection(tunnelReader.GetOutputPort())
        streamTracer.SetSourceConnection(self.lineSeed.GetOutputPort())
        streamTracer.SetIntegrationDirectionToForward()
        streamTracer.SetIntegratorTypeToRungeKutta45()
        streamTracer.SetMaximumPropagation(3)
        streamTracer.SetIntegrationStepUnit(2)
        streamTracer.SetInitialIntegrationStep(0.2)
        streamTracer.SetMinimumIntegrationStep(0.01)
        streamTracer.SetMaximumIntegrationStep(0.5)
        streamTracer.SetMaximumError(0.000001)
        streamTracer.SetMaximumNumberOfSteps(2000)
        streamTracer.SetTerminalSpeed(0.00000000001)

        self.tubeFilter = vtk.vtkTubeFilter()
        self.tubeFilter.SetInputConnection(streamTracer.GetOutputPort())
        self.tubeFilter.SetRadius(0.01)
        self.tubeFilter.SetNumberOfSides(6)
        self.tubeFilter.CappingOn()
        self.tubeFilter.Update()
Exemple #6
0
    def getStreamer(vtkReader,
                    array='B',
                    x0=None,
                    maxSteps=50000,
                    error_tol=1e-8,
                    direct='f'):

        if direct == 'f':
            direction = 0
        elif direct == 'b':
            direction = 1
        else:
            print(
                "Unknown Direction Specified. Please use 'f' for forward (norther hemisphere) "
                "and 'b' for backward (southern hemisphere)")
            assert False
        # print ("X0: {}".format(x0))
        # There seems to be a problem with the interpolator getting some point exactly on the x axis.
        #   This small oscillation seems to fix the issue.

        x0 += [0, 1e-12, -1e-12]

        output = vtkReader.GetOutput()
        b_field = output.GetPointData().GetArray(array)
        output.GetPointData().SetVectors(b_field)
        rk45 = vtk.vtkRungeKutta45()
        streamer = vtk.vtkStreamTracer()
        streamer.SetInputConnection(vtkReader.GetOutputPort())
        streamer.SetInputData(output)
        streamer.SetStartPosition(x0)
        streamer.SetMaximumPropagation(maxSteps)
        streamer.SetIntegrationStepUnit(2)
        streamer.SetMinimumIntegrationStep(0.01)
        streamer.SetMaximumIntegrationStep(2.0)
        streamer.SetInitialIntegrationStep(0.5)
        streamer.SetIntegrationDirection(direction)
        streamer.SetIntegrator(rk45)
        streamer.SetMaximumError(error_tol / 10)
        streamer.Update()
        # print("Streamer Complete")
        return streamer
Exemple #7
0
def make_stream_actors(position, color):
    """Create a stream and use two mappers. One to represent velocity with
    the default colour, and the other to change the colour.
    """
    seed = vtk.vtkPointSource()
    seed.SetRadius(15)
    seed.SetNumberOfPoints(100)
    seed.SetCenter(*position)

    stream_tracer = vtk.vtkStreamTracer()
    stream_tracer.SetInputConnection(mixer.GetOutputPort())
    stream_tracer.SetMaximumPropagation(500)
    stream_tracer.SetIntegrator(vtk.vtkRungeKutta45())
    stream_tracer.SetIntegrationDirectionToBoth()
    stream_tracer.SetTerminalSpeed(0.0001)
    stream_tracer.SetSource(seed.GetOutput())

    stream_tube = vtk.vtkTubeFilter()
    stream_tube.SetInputConnection(stream_tracer.GetOutputPort())
    stream_tube.SetRadius(.2)
    stream_tube.SetNumberOfSides(12)

    # Solid transparent colour
    stream_mapper1 = vtk.vtkPolyDataMapper()
    stream_mapper1.SetInputConnection(stream_tube.GetOutputPort())
    stream_mapper1.ScalarVisibilityOff()

    stream_actor1 = vtk.vtkActor()
    stream_actor1.GetProperty().SetColor(*color)
    stream_actor1.SetMapper(stream_mapper1)
    stream_actor1.GetProperty().SetOpacity(0.4)

    # opaque velocity colour
    stream_mapper2 = vtk.vtkPolyDataMapper()
    stream_mapper2.SetInputConnection(stream_tube.GetOutputPort())

    stream_actor2 = vtk.vtkActor()
    stream_actor2.SetMapper(stream_mapper2)
    stream_actor2.GetProperty().SetOpacity(1.)
    return [stream_actor1, stream_actor2]
Exemple #8
0
def __vtkStreamTracer__(GetOutputPort):
    sphereSource = vtk.vtkSphereSource()
    sphereSource.SetCenter(0.0, 0.0, 0.0)
    sphereSource.SetRadius(0.1)
    sphereSource.SetThetaResolution(10)
    sphereSource.SetPhiResolution(10)
    sphereSource.Update()

    LineSourceWidget0 = vtk.vtkLineSource()
    LineSourceWidget0.SetPoint1(0.0, 0.0, 1e-3)
    LineSourceWidget0.SetPoint2(0.0, 0.0, -1e-3)
    LineSourceWidget0.SetResolution(100)

    Stream = vtk.vtkStreamTracer()
    Stream.SetInput(LineSourceWidget0.GetOutput())
    Stream.SetInputConnection(GetOutputPort)
    Stream.SetStartPosition(0.0, 0.0, 0.0)
    #Stream.SetMaximumPropagation 500
    Stream.SetIntegrationDirectionToBoth()
    Stream.SetIntegratorTypeToRungeKutta4()
    Stream.SetComputeVorticity(False)

    return Stream
Exemple #9
0
    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)
        InputArrayChoiceMixin.__init__(self)

        # 0 = RK2
        # 1 = RK4
        # 2 = RK45
        self._config.integrator = INTEG_TYPE.index('RK2')
        self._config.max_prop = 5.0
        self._config.integration_direction = INTEG_DIR.index(
                'FORWARD')

        configList = [
            ('Vectors selection:', 'vectorsSelection', 'base:str', 'choice',
             'The attribute that will be used as vectors for the warping.',
             (input_array_choice_mixin.DEFAULT_SELECTION_STRING,)),
            ('Max propagation:', 'max_prop', 'base:float', 'text',
                'The streamline will propagate up to this lenth.'),
            ('Integration direction:', 'integration_direction', 'base:int', 'choice',
             'Select an integration direction.',
             INTEG_DIR_TEXTS),
            ('Integrator type:', 'integrator', 'base:int', 'choice',
             'Select an integrator for the streamlines.',
             INTEG_TYPE_TEXTS)]

        self._streamTracer = vtk.vtkStreamTracer() 

        ScriptedConfigModuleMixin.__init__(
            self, configList,
            {'Module (self)' : self,
             'vtkStreamTracer' : self._streamTracer})

        module_utils.setup_vtk_object_progress(self, self._streamTracer,
                                           'Tracing stream lines.')
        
        self.sync_module_logic_with_config()
def main():
    xyzFilename, qFilename = get_program_parameters()

    colors = vtk.vtkNamedColors()

    aren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(aren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    scalarRange = [0.0] * 2
    c = [0.0] * 3
    maxTime = 0.0

    reader = vtk.vtkMultiBlockPLOT3DReader()
    reader.SetXYZFileName(xyzFilename)
    reader.SetQFileName(qFilename)
    reader.Update()  # Force a read to occur.

    pd = reader.GetOutput().GetBlock(0)
    pd.GetCenter(c)
    if pd.GetPointData().GetScalars():
        pd.GetPointData().GetScalars().GetRange(scalarRange)
    if pd.GetPointData().GetVectors():
        maxVelocity = pd.GetPointData().GetVectors().GetMaxNorm()
        maxTime = 20.0 * pd.GetLength() / maxVelocity

    outlineF = vtk.vtkStructuredGridOutlineFilter()
    outlineF.SetInputData(pd)

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

    outline = vtk.vtkActor()
    outline.SetMapper(outlineMapper)
    outline.GetProperty().SetColor(colors.GetColor3d('Moccasin'))
    outline.GetProperty().SetLineWidth(2.0)

    #
    # Some geometry for context
    #
    wall = vtk.vtkStructuredGridGeometryFilter()
    wall.SetInputData(pd)
    wall.SetExtent(0, 100, 0, 100, 0, 0)

    wallMap = vtk.vtkPolyDataMapper()
    wallMap.SetInputConnection(wall.GetOutputPort())
    wallMap.ScalarVisibilityOff()

    wallActor = vtk.vtkActor()
    wallActor.SetMapper(wallMap)
    wallActor.GetProperty().SetColor(colors.GetColor3d('Silver'))

    fin = vtk.vtkStructuredGridGeometryFilter()
    fin.SetInputData(pd)
    fin.SetExtent(0, 100, 0, 0, 0, 100)

    finMap = vtk.vtkPolyDataMapper()
    finMap.SetInputConnection(fin.GetOutputPort())
    finMap.ScalarVisibilityOff()

    finActor = vtk.vtkActor()
    finActor.SetMapper(finMap)
    finActor.GetProperty().SetColor(colors.GetColor3d('Silver'))
    #
    # regular streamlines
    #
    line1 = vtk.vtkLineSource()
    line1.SetResolution(25)
    line1.SetPoint1(-6.36, 0.25, 0.06)
    line1.SetPoint2(-6.36, 0.25, 5.37)

    rakeMapper = vtk.vtkPolyDataMapper()
    rakeMapper.SetInputConnection(line1.GetOutputPort())

    rake1 = vtk.vtkActor()
    rake1.SetMapper(rakeMapper)
    rake1.GetProperty().SetColor(colors.GetColor3d('Black'))
    rake1.GetProperty().SetLineWidth(5)

    streamers = vtk.vtkStreamTracer()
    # streamers.DebugOn()
    streamers.SetInputConnection(reader.GetOutputPort())
    streamers.SetSourceConnection(line1.GetOutputPort())
    streamers.SetMaximumPropagation(maxTime)
    streamers.SetInitialIntegrationStep(0.2)
    streamers.SetMinimumIntegrationStep(0.01)
    streamers.SetIntegratorType(2)
    streamers.Update()

    streamersMapper = vtk.vtkPolyDataMapper()
    streamersMapper.SetInputConnection(streamers.GetOutputPort())
    streamersMapper.SetScalarRange(scalarRange)

    lines = vtk.vtkActor()
    lines.SetMapper(streamersMapper)

    aren.AddActor(outline)
    aren.AddActor(wallActor)
    aren.AddActor(finActor)
    aren.AddActor(rake1)
    aren.AddActor(lines)
    aren.SetBackground(colors.GetColor3d('Gray'))

    aren.ResetCamera()
    aren.GetActiveCamera().Elevation(30.0)
    aren.GetActiveCamera().Azimuth(30.0)
    aren.GetActiveCamera().Dolly(1.2)
    aren.ResetCameraClippingRange()

    renWin.SetSize(640, 480)
    renWin.SetWindowName('BluntStreamlines')
    renWin.Render()

    # Interact with the data.
    iren.Start()
Exemple #11
0
def main():
    colors = vtk.vtkNamedColors()

    # colors.SetColor('bkg', [0.1, 0.2, 0.4, 1.0])

    xyz_file, q_file = get_program_parameters()

    # Read the data.
    #
    pl3d = vtk.vtkMultiBlockPLOT3DReader()
    pl3d.SetXYZFileName(xyz_file)
    pl3d.SetQFileName(q_file)
    pl3d.SetScalarFunctionNumber(100)
    pl3d.SetVectorFunctionNumber(202)
    pl3d.Update()

    seeds = vtk.vtkPlaneSource()
    seeds.SetXResolution(4)
    seeds.SetYResolution(4)
    seeds.SetOrigin(2, -2, 26)
    seeds.SetPoint1(2, 2, 26)
    seeds.SetPoint2(2, -2, 32)

    streamline = vtk.vtkStreamTracer()
    streamline.SetInputData(pl3d.GetOutput().GetBlock(0))
    streamline.SetSourceConnection(seeds.GetOutputPort())
    streamline.SetMaximumPropagation(200)
    streamline.SetInitialIntegrationStep(.2)
    streamline.SetIntegrationDirectionToForward()

    streamline_mapper = vtk.vtkPolyDataMapper()
    streamline_mapper.SetInputConnection(streamline.GetOutputPort())
    streamline_actor = vtk.vtkActor()
    streamline_actor.SetMapper(streamline_mapper)
    streamline_actor.VisibilityOn()

    outline = vtk.vtkStructuredGridOutlineFilter()
    outline.SetInputData(pl3d.GetOutput().GetBlock(0))
    outline_mapper = vtk.vtkPolyDataMapper()
    outline_mapper.SetInputConnection(outline.GetOutputPort())
    outline_actor = vtk.vtkActor()
    outline_actor.SetMapper(outline_mapper)
    outline_actor.GetProperty().SetColor(colors.GetColor3d('White'))

    renderer = vtk.vtkRenderer()
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)
    render_window.SetWindowName('StreamLines')

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
    render_window.SetInteractor(interactor)

    renderer.AddActor(streamline_actor)
    renderer.AddActor(outline_actor)

    renderer.SetBackground(colors.GetColor3d('MidnightBlue'))
    interactor.Initialize()
    render_window.Render()
    renderer.GetActiveCamera().SetPosition(-32.8, -12.3, 46.3)
    renderer.GetActiveCamera().SetFocalPoint(8.3, 0.03, 29.8)
    renderer.GetActiveCamera().SetViewUp(0.2, 0.5, 0.9)
    render_window.Render()
    interactor.Start()
Exemple #12
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()
Exemple #13
0
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.vtkStreamTracer()
sl.SetIntegrator(integ)
sl.SetInputData(pl3d_output)
sl.SetSourceConnection(seeds.GetOutputPort())
sl.SetMaximumPropagation(100)
sl.SetInitialIntegrationStep(0.1)
sl.SetIntegrationDirectionToBackward()

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

mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(tube.GetOutputPort())

actor = vtk.vtkActor()
Exemple #14
0
C = N.array(density.GetOutput().GetPoint(0))
H = N.array(density.GetOutput().GetPoint(1))

seedsC = vtk.vtkPointSource()
seedsC.SetRadius(0.05)
seedsC.SetCenter(0.9 * C + 0.1 * H)
seedsC.SetNumberOfPoints(30)

seedsH = vtk.vtkPointSource()
seedsH.SetRadius(0.05)
seedsH.SetCenter(0.9 * H + 0.1 * C)
seedsH.SetNumberOfPoints(30)

integ = vtk.vtkRungeKutta4()
streamC = vtk.vtkStreamTracer()
streamC.SetInputConnection(attrib.GetOutputPort())
streamC.SetSourceConnection(seedsC.GetOutputPort())
streamC.SetMaximumPropagation(500)
streamC.SetInitialIntegrationStep(0.05)
streamC.SetIntegrationDirectionToBackward()
streamC.SetIntegrator(integ)

streamCMapper = vtk.vtkPolyDataMapper()
streamCMapper.SetInputConnection(streamC.GetOutputPort())

streamCActor = vtk.vtkActor()
streamCActor.SetMapper(streamCMapper)

streamH = vtk.vtkStreamTracer()
streamH.SetInputConnection(attrib.GetOutputPort())
Exemple #15
0
def main():
    colors = vtk.vtkNamedColors()

    xyxFile, qFile = get_program_parameters()

    # Read the data.
    #
    pl3d = vtk.vtkMultiBlockPLOT3DReader()
    pl3d.AutoDetectFormatOn()
    pl3d.SetXYZFileName(xyxFile)
    pl3d.SetQFileName(qFile)
    pl3d.SetScalarFunctionNumber(153)
    pl3d.SetVectorFunctionNumber(200)
    pl3d.Update()

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

    # blue to red lut
    #
    lut = vtk.vtkLookupTable()
    lut.SetHueRange(0.667, 0.0)

    # Computational planes.
    floorComp = vtk.vtkStructuredGridGeometryFilter()
    floorComp.SetExtent(0, 37, 0, 75, 0, 0)
    floorComp.SetInputData(sg)
    floorComp.Update()

    floorMapper = vtk.vtkPolyDataMapper()
    floorMapper.SetInputConnection(floorComp.GetOutputPort())
    floorMapper.ScalarVisibilityOff()
    floorMapper.SetLookupTable(lut)

    floorActor = vtk.vtkActor()
    floorActor.SetMapper(floorMapper)
    floorActor.GetProperty().SetRepresentationToWireframe()
    floorActor.GetProperty().SetColor(colors.GetColor3d("Beige"))
    floorActor.GetProperty().SetLineWidth(2)

    subFloorComp = vtk.vtkStructuredGridGeometryFilter()

    subFloorComp.SetExtent(0, 37, 0, 15, 22, 22)
    subFloorComp.SetInputData(sg)

    subFloorMapper = vtk.vtkPolyDataMapper()
    subFloorMapper.SetInputConnection(subFloorComp.GetOutputPort())
    subFloorMapper.SetLookupTable(lut)
    subFloorMapper.SetScalarRange(sg.GetScalarRange())

    subFloorActor = vtk.vtkActor()

    subFloorActor.SetMapper(subFloorMapper)

    subFloor2Comp = vtk.vtkStructuredGridGeometryFilter()
    subFloor2Comp.SetExtent(0, 37, 60, 75, 22, 22)
    subFloor2Comp.SetInputData(sg)

    subFloor2Mapper = vtk.vtkPolyDataMapper()
    subFloor2Mapper.SetInputConnection(subFloor2Comp.GetOutputPort())
    subFloor2Mapper.SetLookupTable(lut)
    subFloor2Mapper.SetScalarRange(sg.GetScalarRange())

    subFloor2Actor = vtk.vtkActor()

    subFloor2Actor.SetMapper(subFloor2Mapper)

    postComp = vtk.vtkStructuredGridGeometryFilter()

    postComp.SetExtent(10, 10, 0, 75, 0, 37)
    postComp.SetInputData(sg)

    postMapper = vtk.vtkPolyDataMapper()
    postMapper.SetInputConnection(postComp.GetOutputPort())
    postMapper.SetLookupTable(lut)
    postMapper.SetScalarRange(sg.GetScalarRange())

    postActor = vtk.vtkActor()
    postActor.SetMapper(postMapper)
    postActor.GetProperty().SetColor(colors.GetColor3d("Beige"))

    fanComp = vtk.vtkStructuredGridGeometryFilter()
    fanComp.SetExtent(0, 37, 38, 38, 0, 37)
    fanComp.SetInputData(sg)

    fanMapper = vtk.vtkPolyDataMapper()
    fanMapper.SetInputConnection(fanComp.GetOutputPort())
    fanMapper.SetLookupTable(lut)
    fanMapper.SetScalarRange(sg.GetScalarRange())

    fanActor = vtk.vtkActor()

    fanActor.SetMapper(fanMapper)
    fanActor.GetProperty().SetColor(colors.GetColor3d("Beige"))

    # streamers
    #
    # spherical seed points
    rake = vtk.vtkPointSource()
    rake.SetCenter(-0.74, 0, 0.3)
    rake.SetNumberOfPoints(10)

    # a line of seed points
    seedsComp = vtk.vtkStructuredGridGeometryFilter()
    seedsComp.SetExtent(10, 10, 37, 39, 1, 35)
    seedsComp.SetInputData(sg)

    streamers = vtk.vtkStreamTracer()
    streamers.SetInputConnection(pl3d.GetOutputPort())

    # streamers SetSource [rake GetOutput]
    streamers.SetSourceConnection(seedsComp.GetOutputPort())
    streamers.SetMaximumPropagation(250)
    streamers.SetInitialIntegrationStep(.2)
    streamers.SetMinimumIntegrationStep(.01)
    streamers.SetIntegratorType(2)
    streamers.Update()

    tubes = vtk.vtkTubeFilter()
    tubes.SetInputConnection(streamers.GetOutputPort())
    tubes.SetNumberOfSides(8)
    tubes.SetRadius(.08)
    tubes.SetVaryRadius(0)

    mapTubes = vtk.vtkPolyDataMapper()

    mapTubes.SetInputConnection(tubes.GetOutputPort())
    mapTubes.SetScalarRange(sg.GetScalarRange())

    tubesActor = vtk.vtkActor()
    tubesActor.SetMapper(mapTubes)

    # outline
    outline = vtk.vtkStructuredGridOutlineFilter()
    outline.SetInputData(sg)

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

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(colors.GetColor3d("Beige"))

    # Create graphics stuff.
    ren1 = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Add the actors to the renderer, set the background and size.
    #
    ren1.AddActor(outlineActor)
    ren1.AddActor(floorActor)
    ren1.AddActor(subFloorActor)
    ren1.AddActor(subFloor2Actor)
    ren1.AddActor(postActor)
    ren1.AddActor(fanActor)
    ren1.AddActor(tubesActor)

    aCam = vtk.vtkCamera()
    aCam.SetFocalPoint(0.00657892, 0, 2.41026)
    aCam.SetPosition(-1.94838, -47.1275, 39.4607)
    aCam.SetViewUp(0.00653193, 0.617865, 0.786257)
    ren1.ResetCamera()
    aCam.Dolly(1.)
    aCam.SetClippingRange(1, 100)

    ren1.SetBackground(colors.GetColor3d("SlateGray"))
    ren1.SetActiveCamera(aCam)
    renWin.SetSize(640, 480)

    renWin.Render()
    iren.Start()
Exemple #16
0
def main():
    fileName = get_program_parameters()

    colors = vtk.vtkNamedColors()

    # Set the furniture colors.
    colors.SetColor("Furniture", [204, 204, 153, 255])

    scalarRange = [0.0, 0.0]
    maxTime = 0

    aren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(aren)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    #
    # Read the data.
    #
    reader = vtk.vtkStructuredGridReader()
    reader.SetFileName(fileName)
    reader.Update()  # Force a read to occur.
    reader.GetOutput().GetLength()

    if reader.GetOutput().GetPointData().GetScalars():
        reader.GetOutput().GetPointData().GetScalars().GetRange(scalarRange)

    if reader.GetOutput().GetPointData().GetVectors():
        maxVelocity = reader.GetOutput().GetPointData().GetVectors(
        ).GetMaxNorm()
        maxTime = 4.0 * reader.GetOutput().GetLength() / maxVelocity

    #
    # Outline around the data.
    #
    outlineF = vtk.vtkStructuredGridOutlineFilter()
    outlineF.SetInputConnection(reader.GetOutputPort())
    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outlineF.GetOutputPort())
    outline = vtk.vtkActor()
    outline.SetMapper(outlineMapper)
    outline.GetProperty().SetColor(colors.GetColor3d("LampBlack"))

    #
    # Set up shaded surfaces (i.e., supporting geometry).
    #
    doorGeom = vtk.vtkStructuredGridGeometryFilter()
    doorGeom.SetInputConnection(reader.GetOutputPort())
    doorGeom.SetExtent(27, 27, 14, 18, 0, 11)
    mapDoor = vtk.vtkPolyDataMapper()
    mapDoor.SetInputConnection(doorGeom.GetOutputPort())
    mapDoor.ScalarVisibilityOff()
    door = vtk.vtkActor()
    door.SetMapper(mapDoor)
    door.GetProperty().SetColor(colors.GetColor3d("Burlywood"))

    window1Geom = vtk.vtkStructuredGridGeometryFilter()
    window1Geom.SetInputConnection(reader.GetOutputPort())
    window1Geom.SetExtent(0, 0, 9, 18, 6, 12)
    mapWindow1 = vtk.vtkPolyDataMapper()
    mapWindow1.SetInputConnection(window1Geom.GetOutputPort())
    mapWindow1.ScalarVisibilityOff()
    window1 = vtk.vtkActor()
    window1.SetMapper(mapWindow1)
    window1.GetProperty().SetColor(colors.GetColor3d("SkyBlue"))
    window1.GetProperty().SetOpacity(.6)

    window2Geom = vtk.vtkStructuredGridGeometryFilter()
    window2Geom.SetInputConnection(reader.GetOutputPort())
    window2Geom.SetExtent(5, 12, 23, 23, 6, 12)
    mapWindow2 = vtk.vtkPolyDataMapper()
    mapWindow2.SetInputConnection(window2Geom.GetOutputPort())
    mapWindow2.ScalarVisibilityOff()
    window2 = vtk.vtkActor()
    window2.SetMapper(mapWindow2)
    window2.GetProperty().SetColor(colors.GetColor3d("SkyBlue"))
    window2.GetProperty().SetOpacity(.6)

    klower1Geom = vtk.vtkStructuredGridGeometryFilter()
    klower1Geom.SetInputConnection(reader.GetOutputPort())
    klower1Geom.SetExtent(17, 17, 0, 11, 0, 6)
    mapKlower1 = vtk.vtkPolyDataMapper()
    mapKlower1.SetInputConnection(klower1Geom.GetOutputPort())
    mapKlower1.ScalarVisibilityOff()
    klower1 = vtk.vtkActor()
    klower1.SetMapper(mapKlower1)
    klower1.GetProperty().SetColor(colors.GetColor3d("EggShell"))

    klower2Geom = vtk.vtkStructuredGridGeometryFilter()
    klower2Geom.SetInputConnection(reader.GetOutputPort())
    klower2Geom.SetExtent(19, 19, 0, 11, 0, 6)
    mapKlower2 = vtk.vtkPolyDataMapper()
    mapKlower2.SetInputConnection(klower2Geom.GetOutputPort())
    mapKlower2.ScalarVisibilityOff()
    klower2 = vtk.vtkActor()
    klower2.SetMapper(mapKlower2)
    klower2.GetProperty().SetColor(colors.GetColor3d("EggShell"))

    klower3Geom = vtk.vtkStructuredGridGeometryFilter()
    klower3Geom.SetInputConnection(reader.GetOutputPort())
    klower3Geom.SetExtent(17, 19, 0, 0, 0, 6)
    mapKlower3 = vtk.vtkPolyDataMapper()
    mapKlower3.SetInputConnection(klower3Geom.GetOutputPort())
    mapKlower3.ScalarVisibilityOff()
    klower3 = vtk.vtkActor()
    klower3.SetMapper(mapKlower3)
    klower3.GetProperty().SetColor(colors.GetColor3d("EggShell"))

    klower4Geom = vtk.vtkStructuredGridGeometryFilter()
    klower4Geom.SetInputConnection(reader.GetOutputPort())
    klower4Geom.SetExtent(17, 19, 11, 11, 0, 6)
    mapKlower4 = vtk.vtkPolyDataMapper()
    mapKlower4.SetInputConnection(klower4Geom.GetOutputPort())
    mapKlower4.ScalarVisibilityOff()
    klower4 = vtk.vtkActor()
    klower4.SetMapper(mapKlower4)
    klower4.GetProperty().SetColor(colors.GetColor3d("EggShell"))

    klower5Geom = vtk.vtkStructuredGridGeometryFilter()
    klower5Geom.SetInputConnection(reader.GetOutputPort())
    klower5Geom.SetExtent(17, 19, 0, 11, 0, 0)
    mapKlower5 = vtk.vtkPolyDataMapper()
    mapKlower5.SetInputConnection(klower5Geom.GetOutputPort())
    mapKlower5.ScalarVisibilityOff()
    klower5 = vtk.vtkActor()
    klower5.SetMapper(mapKlower5)
    klower5.GetProperty().SetColor(colors.GetColor3d("EggShell"))

    klower6Geom = vtk.vtkStructuredGridGeometryFilter()
    klower6Geom.SetInputConnection(reader.GetOutputPort())
    klower6Geom.SetExtent(17, 19, 0, 7, 6, 6)
    mapKlower6 = vtk.vtkPolyDataMapper()
    mapKlower6.SetInputConnection(klower6Geom.GetOutputPort())
    mapKlower6.ScalarVisibilityOff()
    klower6 = vtk.vtkActor()
    klower6.SetMapper(mapKlower6)
    klower6.GetProperty().SetColor(colors.GetColor3d("EggShell"))

    klower7Geom = vtk.vtkStructuredGridGeometryFilter()
    klower7Geom.SetInputConnection(reader.GetOutputPort())
    klower7Geom.SetExtent(17, 19, 9, 11, 6, 6)
    mapKlower7 = vtk.vtkPolyDataMapper()
    mapKlower7.SetInputConnection(klower7Geom.GetOutputPort())
    mapKlower7.ScalarVisibilityOff()
    klower7 = vtk.vtkActor()
    klower7.SetMapper(mapKlower7)
    klower7.GetProperty().SetColor(colors.GetColor3d("EggShell"))

    hood1Geom = vtk.vtkStructuredGridGeometryFilter()
    hood1Geom.SetInputConnection(reader.GetOutputPort())
    hood1Geom.SetExtent(17, 17, 0, 11, 11, 16)
    mapHood1 = vtk.vtkPolyDataMapper()
    mapHood1.SetInputConnection(hood1Geom.GetOutputPort())
    mapHood1.ScalarVisibilityOff()
    hood1 = vtk.vtkActor()
    hood1.SetMapper(mapHood1)
    hood1.GetProperty().SetColor(colors.GetColor3d("Silver"))

    hood2Geom = vtk.vtkStructuredGridGeometryFilter()
    hood2Geom.SetInputConnection(reader.GetOutputPort())
    hood2Geom.SetExtent(19, 19, 0, 11, 11, 16)
    mapHood2 = vtk.vtkPolyDataMapper()
    mapHood2.SetInputConnection(hood2Geom.GetOutputPort())
    mapHood2.ScalarVisibilityOff()
    hood2 = vtk.vtkActor()
    hood2.SetMapper(mapHood2)
    hood2.GetProperty().SetColor(colors.GetColor3d("Furniture"))

    hood3Geom = vtk.vtkStructuredGridGeometryFilter()
    hood3Geom.SetInputConnection(reader.GetOutputPort())
    hood3Geom.SetExtent(17, 19, 0, 0, 11, 16)
    mapHood3 = vtk.vtkPolyDataMapper()
    mapHood3.SetInputConnection(hood3Geom.GetOutputPort())
    mapHood3.ScalarVisibilityOff()
    hood3 = vtk.vtkActor()
    hood3.SetMapper(mapHood3)
    hood3.GetProperty().SetColor(colors.GetColor3d("Furniture"))

    hood4Geom = vtk.vtkStructuredGridGeometryFilter()
    hood4Geom.SetInputConnection(reader.GetOutputPort())
    hood4Geom.SetExtent(17, 19, 11, 11, 11, 16)
    mapHood4 = vtk.vtkPolyDataMapper()
    mapHood4.SetInputConnection(hood4Geom.GetOutputPort())
    mapHood4.ScalarVisibilityOff()
    hood4 = vtk.vtkActor()
    hood4.SetMapper(mapHood4)
    hood4.GetProperty().SetColor(colors.GetColor3d("Furniture"))

    hood6Geom = vtk.vtkStructuredGridGeometryFilter()
    hood6Geom.SetInputConnection(reader.GetOutputPort())
    hood6Geom.SetExtent(17, 19, 0, 11, 16, 16)
    mapHood6 = vtk.vtkPolyDataMapper()
    mapHood6.SetInputConnection(hood6Geom.GetOutputPort())
    mapHood6.ScalarVisibilityOff()
    hood6 = vtk.vtkActor()
    hood6.SetMapper(mapHood6)
    hood6.GetProperty().SetColor(colors.GetColor3d("Furniture"))

    cookingPlateGeom = vtk.vtkStructuredGridGeometryFilter()
    cookingPlateGeom.SetInputConnection(reader.GetOutputPort())
    cookingPlateGeom.SetExtent(17, 19, 7, 9, 6, 6)
    mapCookingPlate = vtk.vtkPolyDataMapper()
    mapCookingPlate.SetInputConnection(cookingPlateGeom.GetOutputPort())
    mapCookingPlate.ScalarVisibilityOff()
    cookingPlate = vtk.vtkActor()
    cookingPlate.SetMapper(mapCookingPlate)
    cookingPlate.GetProperty().SetColor(colors.GetColor3d("Tomato"))

    filterGeom = vtk.vtkStructuredGridGeometryFilter()
    filterGeom.SetInputConnection(reader.GetOutputPort())
    filterGeom.SetExtent(17, 19, 7, 9, 11, 11)
    mapFilter = vtk.vtkPolyDataMapper()
    mapFilter.SetInputConnection(filterGeom.GetOutputPort())
    mapFilter.ScalarVisibilityOff()
    sgfilter = vtk.vtkActor()
    sgfilter.SetMapper(mapFilter)
    sgfilter.GetProperty().SetColor(colors.GetColor3d("Furniture"))
    #
    # regular streamlines
    #
    line = vtk.vtkLineSource()
    line.SetResolution(39)
    line.SetPoint1(0.08, 2.50, 0.71)
    line.SetPoint2(0.08, 4.50, 0.71)
    rakeMapper = vtk.vtkPolyDataMapper()
    rakeMapper.SetInputConnection(line.GetOutputPort())
    rake = vtk.vtkActor()
    rake.SetMapper(rakeMapper)

    streamers = vtk.vtkStreamTracer()
    # streamers.DebugOn()
    streamers.SetInputConnection(reader.GetOutputPort())
    streamers.SetSourceConnection(line.GetOutputPort())
    streamers.SetMaximumPropagation(maxTime)
    streamers.SetInitialIntegrationStep(.5)
    streamers.SetMinimumIntegrationStep(.1)
    streamers.SetIntegratorType(2)
    streamers.Update()

    streamersMapper = vtk.vtkPolyDataMapper()
    streamersMapper.SetInputConnection(streamers.GetOutputPort())
    streamersMapper.SetScalarRange(scalarRange)

    lines = vtk.vtkActor()
    lines.SetMapper(streamersMapper)
    lines.GetProperty().SetColor(colors.GetColor3d("Black"))

    aren.TwoSidedLightingOn()

    aren.AddActor(outline)
    aren.AddActor(door)
    aren.AddActor(window1)
    aren.AddActor(window2)
    aren.AddActor(klower1)
    aren.AddActor(klower2)
    aren.AddActor(klower3)
    aren.AddActor(klower4)
    aren.AddActor(klower5)
    aren.AddActor(klower6)
    aren.AddActor(klower7)
    aren.AddActor(hood1)
    aren.AddActor(hood2)
    aren.AddActor(hood3)
    aren.AddActor(hood4)
    aren.AddActor(hood6)
    aren.AddActor(cookingPlate)
    aren.AddActor(sgfilter)
    aren.AddActor(lines)
    aren.AddActor(rake)

    aren.SetBackground(colors.GetColor3d("SlateGray"))

    aCamera = vtk.vtkCamera()
    aren.SetActiveCamera(aCamera)
    aren.ResetCamera()

    aCamera.SetFocalPoint(3.505, 2.505, 1.255)
    aCamera.SetPosition(3.505, 24.6196, 1.255)
    aCamera.SetViewUp(0, 0, 1)
    aCamera.Azimuth(60)
    aCamera.Elevation(30)
    aCamera.Dolly(1.5)
    aren.ResetCameraClippingRange()

    renWin.SetSize(640, 512)
    renWin.Render()

    # interact with data
    iren.Start()
Exemple #17
0
rakes[0].SetPoint1(160, 100, 160)
rakes[0].SetPoint2(160, 200, 160)
rakes[0].SetResolution(50)

rakes[1].SetPoint1(100, 160, 160)
rakes[1].SetPoint2(200, 160, 160)
rakes[1].SetResolution(50)

rakes[2].SetPoint1(160, 160, 100)
rakes[2].SetPoint2(160, 160, 200)
rakes[2].SetResolution(50)

streamLineArr = []

for i in range(0, len(rakes)):
    streamLine = vtk.vtkStreamTracer()
    streamLine.SetInputConnection(reader.GetOutputPort())
    streamLine.SetSourceConnection(rakes[i].GetOutputPort())
    streamLine.SetMaximumPropagation(3000)
    streamLine.SetIntegrationDirectionToForward()
    streamLine.SetIntegratorTypeToRungeKutta4()
    streamLineArr.append(streamLine)

# Create the standard renderer, render window and interactor
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
n = len(rakes)
stream_actorArr = []
Exemple #18
0
LineSourceWidget0.SetPoint1(3.05638, -3.00497, 28.2211)
LineSourceWidget0.SetPoint2(3.05638, 3.95916, 28.2211)
LineSourceWidget0.SetResolution(20)

mbds = vtk.vtkMultiBlockDataSet()
mbds.SetNumberOfBlocks(3)

i = 0
while i < 3:
    eval("ExtractGrid" + str(i)).Update()
    exec("sg" + str(i) + " = vtk.vtkStructuredGrid()")
    eval("sg" + str(i)).ShallowCopy(eval("ExtractGrid" + str(i)).GetOutput())
    mbds.SetBlock(i, eval("sg" + str(i)))
    i += 1

Stream0 = vtk.vtkStreamTracer()
Stream0.SetInputData(mbds)
Stream0.SetSourceConnection(LineSourceWidget0.GetOutputPort())
Stream0.SetIntegrationStepUnit(2)
Stream0.SetMaximumPropagation(20)
Stream0.SetInitialIntegrationStep(0.5)
Stream0.SetIntegrationDirection(0)
Stream0.SetIntegratorType(0)
Stream0.SetMaximumNumberOfSteps(2000)
Stream0.SetTerminalSpeed(1e-12)

#del mbds

aa = vtk.vtkAssignAttribute()
aa.SetInputConnection(Stream0.GetOutputPort())
aa.Assign("Normals", "NORMALS", "POINT_DATA")
Exemple #19
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()
Exemple #20
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
Exemple #21
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
Exemple #22
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]]
Exemple #23
0
def office(fileName, center):
    # These are the centers for the streamline seed.
    seedCenters = [[0.0, 2.1, 0.5], [0.1, 2.1, 0.5], [0.1, 2.7, 0.5],
                   [0.08, 2.7, 0.5]]
    center = abs(center)
    if center >= len(seedCenters):
        center = len(seedCenters) - 1

    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).
    reader = vtk.vtkDataSetReader()
    reader.SetFileName(fileName)

    # 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 source for the streamtubes.
    seeds = vtk.vtkPointSource()
    seeds.SetRadius(0.075)
    seeds.SetCenter(seedCenters[center])
    seeds.SetNumberOfPoints(25)
    streamers = vtk.vtkStreamTracer()
    streamers.SetInputConnection(reader.GetOutputPort())
    streamers.SetSourceConnection(seeds.GetOutputPort())
    streamers.SetMaximumPropagation(500)
    streamers.SetMinimumIntegrationStep(0.1)
    streamers.SetMaximumIntegrationStep(1.0)
    streamers.SetInitialIntegrationStep(0.2)
    streamers.Update()
    mapStreamers = vtk.vtkPolyDataMapper()
    mapStreamers.SetInputConnection(streamers.GetOutputPort())
    mapStreamers.SetScalarRange(
        reader.GetOutput().GetPointData().GetScalars().GetRange())
    streamersActor = vtk.vtkActor()
    streamersActor.SetMapper(mapStreamers)

    # 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(streamersActor)

    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)
    iren.Initialize()
    iren.Start()
Exemple #24
0
def points2():
    output = pointSource2.GetPolyDataOutput()
    points2 = vtk.vtkPoints()
    output.SetPoints(points2)

    for i in range(nPoints):
        x, y, z = 1.5, (.5 + random.randint(y2[0],y2[1])), (.5 + random.randint(z2[0],z2[1]))
        points2.InsertNextPoint(x, y, z)

pointSource1.SetExecuteMethod(points1)
pointSource2.SetExecuteMethod(points2)

#Streamlines for point source 1
integ = vtk.vtkRungeKutta45()
streamer1 = vtk.vtkStreamTracer()
streamer1.SetInputConnection(reader.GetOutputPort())
streamer1.SetSourceConnection(pointSource1.GetOutputPort())
streamer1.SetMaximumPropagation(2000) 
streamer1.SetIntegrationStepUnit(2) #Cell length unit
streamer1.SetMinimumIntegrationStep(0.01)
streamer1.SetMaximumIntegrationStep(10)
streamer1.SetInitialIntegrationStep(0.2)
streamer1.SetIntegrationDirection(0)
streamer1.SetIntegrator(integ)
streamer1.SetRotationScale(0.5)

#Streamlines for point source 2
streamer2 = vtk.vtkStreamTracer()
streamer2.SetInputConnection(reader.GetOutputPort())
streamer2.SetSourceConnection(pointSource2.GetOutputPort())
Exemple #25
0
    def requestData():
        self = container.Filter

        inpt = self.GetInputDataObject(0, 0)

        pt = vtk.vtkPointSource()
        pt.SetNumberOfPoints(1)
        pt.SetCenter(29.,29.,0.)
        pt.SetRadius(0.)

        st = vtk.vtkStreamTracer()
        st.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, 'velocity')
        st.SetSourceConnection(pt.GetOutputPort())
        st.SetInputData(inpt)
        
        #Specify the maximum length of a streamline expressed in LENGTH_UNIT. 
        st.SetMaximumPropagation(5000)
        
        st.SetMaximumNumberOfSteps(100) #bifurcation @ 100 steps
        st.SetInitialIntegrationStep(0.5)
        st.SetMinimumIntegrationStep(0.5)
        st.SetMaximumIntegrationStep(1.0)
        st.SetIntegratorTypeToRungeKutta45()
        st.SetIntegrationDirectionToBackward()#Forward()
        st.Update()

        sline = st.GetOutput().NewInstance()
        sline.ShallowCopy(st.GetOutput())

        container.Streamlines.append(sline)

        req = self.GetCurrentRequest()
        if container.Count == 0:
            req.Set(vtk.vtkStreamingDemandDrivenPipeline.CONTINUE_EXECUTING(), 1)
        elif container.Count == container.MaxIterations - 1:
            container.Count = 0
            req.Remove(vtk.vtkStreamingDemandDrivenPipeline.CONTINUE_EXECUTING())
            append = vtk.vtkAppendPolyData()
            
            comp1_array = vtk.vtkDoubleArray()
            comp1_array.SetNumberOfComponents(1)
            comp2_array = vtk.vtkDoubleArray()
            comp2_array.SetNumberOfComponents(1)
            
            for line in container.Streamlines:
                append.AddInputData(line)
                
                tpt = line.GetPoint(line.GetNumberOfPoints()-1)
                
                comp1_array.SetName( 'x' )
                comp1_array.InsertNextValue(tpt[0])
                
                comp2_array.SetName( 'y' )
                comp2_array.InsertNextValue(tpt[1])
               
            append.Update()
            
            calcPCA(comp1_array, comp2_array)
            
            print 'writing'
            w = vtk.vtkPolyDataWriter()
            w.SetInputConnection(append.GetOutputPort())
            w.SetFileName("spaghetti.vtk")
            w.Write()

            return
        container.Count += 1
Exemple #26
0
attrib = vtk.vtkAssignAttribute()
attrib.SetInputConnection(grad.GetOutputPort())
attrib.Assign(vtk.vtkDataSetAttributes.SCALARS,
              vtk.vtkDataSetAttributes.VECTORS,
              vtk.vtkAssignAttribute.POINT_DATA)

center = potential_cation.GetOutput().GetPoint(0)

seeds = vtk.vtkPointSource()
seeds.SetRadius(3.0)
seeds.SetCenter(center)
seeds.SetNumberOfPoints(150)

integ = vtk.vtkRungeKutta4()
stream = vtk.vtkStreamTracer()
stream.SetInputConnection(attrib.GetOutputPort())
stream.SetSourceConnection(seeds.GetOutputPort())
stream.SetMaximumPropagation(500)
#stream.SetStepLength(0.5)
stream.SetInitialIntegrationStep(0.05)
stream.SetIntegrationDirectionToBackward()
stream.SetIntegrator(integ)

streamMapper = vtk.vtkPolyDataMapper()
streamMapper.SetInputConnection(stream.GetOutputPort())

streamActor = vtk.vtkActor()
streamActor.SetMapper(streamMapper)

renderer = vtk.vtkRenderer()
Exemple #27
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]]
Exemple #28
0
plane.SetPoint1(xma, 0, 0)
plane.SetPoint2(0, 0, zma)
plane.SetXResolution(20)
plane.SetYResolution(20)

# Add the outline of the plane
outline = vtk.vtkOutlineFilter()
outline.SetInputData(reader.GetOutput())
outlineMapper = vtk.vtkPolyDataMapper()
outlineMapper.SetInputConnection(outline.GetOutputPort())
outlineActor = vtk.vtkActor()
outlineActor.SetMapper(outlineMapper)
outlineActor.GetProperty().SetColor(1, 1, 1)

# Compute streamlines
streamline = vtk.vtkStreamTracer()
streamline.SetSourceConnection(plane.GetOutputPort())
streamline.SetInputConnection(reader.GetOutputPort())
# Try different integration alternatives! See the documentation of vtkStreamTracer
streamline.SetIntegrationDirectionToForward()
streamline.SetMaximumPropagation(5)  # reader.GetDimensions(y)
streamline.SetComputeVorticity(True)

# Pass the streamlines to the mapper
streamlineMapper = vtk.vtkPolyDataMapper()
streamlineMapper.SetLookupTable(lut)
streamlineMapper.SetInputConnection(streamline.GetOutputPort())
streamlineMapper.SetScalarVisibility(True)
streamlineMapper.SetScalarModeToUsePointFieldData()
streamlineMapper.SelectColorArray('vectors')
# See documentation for the parameter in GetRange()
Exemple #29
0
def main():
    colors = vtk.vtkNamedColors()

    xyxFile, qFile = get_program_parameters()

    # Read the data.
    #
    pl3d = vtk.vtkMultiBlockPLOT3DReader()
    pl3d.AutoDetectFormatOn()
    pl3d.SetXYZFileName(xyxFile)
    pl3d.SetQFileName(qFile)
    pl3d.SetScalarFunctionNumber(153)
    pl3d.SetVectorFunctionNumber(200)
    pl3d.Update()

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

    # blue to red lut
    #
    lut = vtk.vtkLookupTable()
    lut.SetHueRange(0.667, 0.0)

    seeds = [[-0.74, 0.0, 0.3], [-0.74, 0.0, 1.0], [-0.74, 0.0, 2.0],
             [-0.74, 0.0, 3.0]]

    renderers = list()

    for s in range(0, len(seeds)):
        # computational planes
        floorComp = vtk.vtkStructuredGridGeometryFilter()
        floorComp.SetExtent(0, 37, 0, 75, 0, 0)
        floorComp.SetInputData(sg)
        floorComp.Update()

        floorMapper = vtk.vtkPolyDataMapper()
        floorMapper.SetInputConnection(floorComp.GetOutputPort())
        floorMapper.ScalarVisibilityOff()
        floorMapper.SetLookupTable(lut)

        floorActor = vtk.vtkActor()
        floorActor.SetMapper(floorMapper)
        floorActor.GetProperty().SetRepresentationToWireframe()
        floorActor.GetProperty().SetColor(colors.GetColor3d("Black"))
        floorActor.GetProperty().SetLineWidth(2)

        postComp = vtk.vtkStructuredGridGeometryFilter()
        postComp.SetExtent(10, 10, 0, 75, 0, 37)
        postComp.SetInputData(sg)

        postMapper = vtk.vtkPolyDataMapper()
        postMapper.SetInputConnection(postComp.GetOutputPort())
        postMapper.SetLookupTable(lut)
        postMapper.SetScalarRange(sg.GetScalarRange())

        postActor = vtk.vtkActor()
        postActor.SetMapper(postMapper)
        postActor.GetProperty().SetColor(colors.GetColor3d("Black"))

        # streamers
        #
        # spherical seed points
        rake = vtk.vtkPointSource()
        rake.SetCenter(seeds[s])
        rake.SetNumberOfPoints(10)

        streamers = vtk.vtkStreamTracer()
        streamers.SetInputConnection(pl3d.GetOutputPort())

        # streamers SetSource [rake GetOutput]
        streamers.SetSourceConnection(rake.GetOutputPort())
        streamers.SetMaximumPropagation(250)
        streamers.SetInitialIntegrationStep(.2)
        streamers.SetMinimumIntegrationStep(.01)
        streamers.SetIntegratorType(2)
        streamers.Update()

        tubes = vtk.vtkTubeFilter()
        tubes.SetInputConnection(streamers.GetOutputPort())
        tubes.SetNumberOfSides(8)
        tubes.SetRadius(.08)
        tubes.SetVaryRadius(0)

        mapTubes = vtk.vtkPolyDataMapper()

        mapTubes.SetInputConnection(tubes.GetOutputPort())
        mapTubes.SetScalarRange(sg.GetScalarRange())

        tubesActor = vtk.vtkActor()
        tubesActor.SetMapper(mapTubes)

        renderer = vtk.vtkRenderer()

        renderer.AddActor(floorActor)
        renderer.AddActor(postActor)
        renderer.AddActor(tubesActor)
        renderer.SetBackground(colors.GetColor3d("SlateGray"))
        renderers.append(renderer)

    renderWindow = vtk.vtkRenderWindow()

    # Setup viewports for the renderers
    rendererSize = 256
    xGridDimensions = 2
    yGridDimensions = 2
    renderWindow.SetSize(rendererSize * xGridDimensions,
                         rendererSize * yGridDimensions)
    for row in range(0, yGridDimensions):
        for col in range(xGridDimensions):
            index = row * xGridDimensions + col
            # (xmin, ymin, xmax, ymax)
            viewport = [
                float(col) / xGridDimensions,
                float(yGridDimensions - (row + 1)) / yGridDimensions,
                float(col + 1) / xGridDimensions,
                float(yGridDimensions - row) / yGridDimensions
            ]
            renderers[index].SetViewport(viewport)

    camera = vtk.vtkCamera()
    camera.SetFocalPoint(0.918037, -0.0779233, 2.69513)
    camera.SetPosition(0.840735, -23.6176, 8.50211)
    camera.SetViewUp(0.00227904, 0.239501, 0.970893)
    camera.SetClippingRange(1, 100)

    renderers[0].SetActiveCamera(camera)
    for r in range(0, len(renderers)):
        renderWindow.AddRenderer(renderers[r])
        if r > 0:
            renderers[r].SetActiveCamera(camera)

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

    renderWindow.SetSize(512, 512)

    renderWindow.Render()
    interactor.Start()
Exemple #30
0
mapInlet.SetInputConnection(inlet.GetOutputPort())
mapInlet.ScalarVisibilityOff()
inletActor = vtk.vtkActor()
inletActor.SetMapper(mapInlet)
inletActor.GetProperty().SetColor(0, 0, 0)

outline = vtk.vtkStructuredGridOutlineFilter()
outline.SetInputConnection(reader.GetOutputPort())
mapOutline = vtk.vtkPolyDataMapper()
mapOutline.SetInputConnection(outline.GetOutputPort())
outlineActor = vtk.vtkActor()
outlineActor.SetMapper(mapOutline)
outlineActor.GetProperty().SetColor(0, 0, 0)

# Create source for streamtubes
streamer = vtk.vtkStreamTracer()
streamer.SetInputConnection(reader.GetOutputPort())
streamer.SetStartPosition(0.1, 2.1, 0.5)
streamer.SetMaximumPropagation(500)
streamer.SetInitialIntegrationStep(0.2)
streamer.SetIntegrationDirectionToForward()

cone = vtk.vtkConeSource()
cone.SetResolution(8)
cones = vtk.vtkGlyph3D()
cones.SetInputConnection(streamer.GetOutputPort())
cones.SetSourceConnection(cone.GetOutputPort())
cones.SetScaleFactor(0.5)
cones.SetInputArrayToProcess(1, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "vectors")
cones.SetScaleModeToScaleByVector()
Exemple #31
0
def main():
    fileName = r"carotid.vtk"

    colors = vtk.vtkNamedColors()

    ren1 = vtk.vtkRenderer()

    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Create the pipeline.
    reader = vtk.vtkStructuredPointsReader()
    reader.SetFileName(fileName)

    psource = vtk.vtkPointSource()
    psource.SetNumberOfPoints(25)
    psource.SetCenter(133.1, 116.3, 5.0)
    psource.SetRadius(2.0)

    threshold = vtk.vtkThresholdPoints()
    threshold.SetInputConnection(reader.GetOutputPort())
    threshold.ThresholdByUpper(275)

    streamers = vtk.vtkStreamTracer()
    streamers.SetInputConnection(reader.GetOutputPort())
    streamers.SetSourceConnection(psource.GetOutputPort())
    streamers.SetMaximumPropagation(100.0)
    streamers.SetInitialIntegrationStep(0.2)
    streamers.SetTerminalSpeed(.01)
    streamers.Update()
    scalarRange = [0] * 2
    scalarRange[0] = streamers.GetOutput().GetPointData().GetScalars(
    ).GetRange()[0]
    scalarRange[1] = streamers.GetOutput().GetPointData().GetScalars(
    ).GetRange()[1]

    tubes = vtk.vtkTubeFilter()
    tubes.SetInputConnection(streamers.GetOutputPort())
    tubes.SetRadius(0.3)
    tubes.SetNumberOfSides(6)
    tubes.SetVaryRadius(0)

    lut = vtk.vtkLookupTable()
    lut.SetHueRange(.667, 0.0)
    lut.Build()

    streamerMapper = vtk.vtkPolyDataMapper()
    streamerMapper.SetInputConnection(tubes.GetOutputPort())
    streamerMapper.SetScalarRange(scalarRange[0], scalarRange[1])
    streamerMapper.SetLookupTable(lut)

    streamerActor = vtk.vtkActor()
    streamerActor.SetMapper(streamerMapper)

    # Speed contours.
    iso = vtk.vtkContourFilter()
    iso.SetInputConnection(reader.GetOutputPort())
    iso.SetValue(0, 175)

    isoMapper = vtk.vtkPolyDataMapper()
    isoMapper.SetInputConnection(iso.GetOutputPort())
    isoMapper.ScalarVisibilityOff()

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

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

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

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

    # Add the actors to the renderer, set the background and size.
    ren1.AddActor(outlineActor)
    ren1.AddActor(streamerActor)
    ren1.AddActor(isoActor)
    ren1.SetBackground(1., 1., 1.)
    renWin.SetSize(640, 480)

    ren1.ResetCamera()
    ren1.ResetCameraClippingRange()

    # Render the image.
    renWin.Render()
    iren.Start()
Exemple #32
0
# 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)
streamer.SetIntegrator(rk4)
streamer.SetInterpolatorPrototype(ivp)
streamer.Update()
reasons = streamer.GetOutput().GetCellData().GetArray("ReasonForTermination")
print(reasons.GetValue(0))
Exemple #33
0
    def render_velocity(self):
        self.ren.RemoveActor(self.velocity_actor)
        if not self.config["velocity"][0]:
            return
        data_path = compose_file_name(self.base_dir, "/velocity",
                                      self.data_folders["velocity"],
                                      self.time_step)
        reader = vtk.vtkXMLImageDataReader()
        reader.SetFileName(data_path)
        reader.Update()

        rake = vtk.vtkLineSource()
        cur_seeds = seeds[self.time_step - 1]
        rake.SetPoint1(cur_seeds[0][0], cur_seeds[0][1], cur_seeds[0][2])
        rake.SetPoint2(cur_seeds[1][0], cur_seeds[1][1], cur_seeds[1][2])
        rake.SetResolution(1000)

        integ = vtk.vtkRungeKutta45()
        sl = vtk.vtkStreamTracer()
        sl.SetInputData(reader.GetOutput())
        sl.SetSourceConnection(rake.GetOutputPort())
        sl.SetIntegrator(integ)
        sl.SetMaximumPropagation(10000)
        sl.SetInitialIntegrationStep(10)
        sl.SetIntegrationDirectionToBoth()

        transform = vtk.vtkTransform()
        transform.Scale(1, 1, 30)
        transform.Update()

        transform_filter = vtk.vtkTransformFilter()
        transform_filter.SetInputConnection(sl.GetOutputPort())
        transform_filter.SetTransform(transform)
        transform_filter.Update()

        # the filter generates (only when multiple lines are input).
        streamTube = vtk.vtkTubeFilter()
        streamTube.SetInputConnection(transform_filter.GetOutputPort())
        streamTube.SetInputArrayToProcess(
            1, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "vectors")
        streamTube.SetRadius(2)
        streamTube.SetNumberOfSides(12)
        streamTube.SetVaryRadiusToVaryRadiusByVector()

        # streamTube.GetOutput().GetPointData().SetActiveScalars("Vorticity")
        # myrange = reader.GetOutput().GetPointData().GetScalars().GetRange()
        #
        # color = vtk.vtkColorTransferFunction()
        # color.AddRGBPoint(myrange[0], 0., 0., 1)
        # color.AddRGBPoint(myrange[1], 1., 0., 0)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(streamTube.GetOutputPort())
        # mapper.SetScalarRange(reader.GetOutput().GetPointData().GetScalars().GetRange())
        # mapper.SetLookupTable(color)

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetOpacity(0.3)
        self.velocity_actor = actor
        self.ren.AddActor(actor)
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.vtkStreamTracer()
sl.SetIntegrator(integ)
sl.SetInputData(pl3d_output)
sl.SetSourceConnection(seeds.GetOutputPort())
sl.SetMaximumPropagation(100)
sl.SetInitialIntegrationStep(0.1)
sl.SetIntegrationDirectionToBackward()

scalarSurface = vtk.vtkRuledSurfaceFilter ()
scalarSurface.SetInputConnection(sl.GetOutputPort())
scalarSurface.SetOffset(0)
scalarSurface.SetOnRatio(2)
scalarSurface.PassLinesOn()
scalarSurface.SetRuledModeToPointWalk()
scalarSurface.SetDistanceFactor(30)
Exemple #35
0
def main():
    fileName = get_program_parameters()

    colors = vtk.vtkNamedColors()

    ren1 = vtk.vtkRenderer()

    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Create the pipeline.
    #
    reader = vtk.vtkStructuredPointsReader()
    reader.SetFileName(fileName)

    psource = vtk.vtkPointSource()
    psource.SetNumberOfPoints(25)
    psource.SetCenter(133.1, 116.3, 5.0)
    psource.SetRadius(2.0)

    threshold = vtk.vtkThresholdPoints()
    threshold.SetInputConnection(reader.GetOutputPort())
    threshold.ThresholdByUpper(275)

    streamers = vtk.vtkStreamTracer()
    streamers.SetInputConnection(reader.GetOutputPort())
    streamers.SetSourceConnection(psource.GetOutputPort())
    # streamers.SetMaximumPropagationUnitToTimeUnit()
    streamers.SetMaximumPropagation(100.0)
    # streamers.SetInitialIntegrationStepUnitToCellLengthUnit()
    streamers.SetInitialIntegrationStep(0.2)
    streamers.SetTerminalSpeed(.01)
    streamers.Update()
    scalarRange = [0] * 2
    scalarRange[0] = streamers.GetOutput().GetPointData().GetScalars(
    ).GetRange()[0]
    scalarRange[1] = streamers.GetOutput().GetPointData().GetScalars(
    ).GetRange()[1]
    print("range: ", scalarRange[0], ", ", scalarRange[1])

    tubes = vtk.vtkTubeFilter()
    tubes.SetInputConnection(streamers.GetOutputPort())
    tubes.SetRadius(0.3)
    tubes.SetNumberOfSides(6)
    tubes.SetVaryRadius(0)

    lut = vtk.vtkLookupTable()
    lut.SetHueRange(.667, 0.0)
    lut.Build()

    streamerMapper = vtk.vtkPolyDataMapper()
    streamerMapper.SetInputConnection(tubes.GetOutputPort())
    streamerMapper.SetScalarRange(scalarRange[0], scalarRange[1])
    streamerMapper.SetLookupTable(lut)

    streamerActor = vtk.vtkActor()
    streamerActor.SetMapper(streamerMapper)

    # Speed contours.
    iso = vtk.vtkContourFilter()
    iso.SetInputConnection(reader.GetOutputPort())
    iso.SetValue(0, 175)

    isoMapper = vtk.vtkPolyDataMapper()
    isoMapper.SetInputConnection(iso.GetOutputPort())
    isoMapper.ScalarVisibilityOff()

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

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

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

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(colors.GetColor3d("Black"))

    # Add the actors to the renderer, set the background and size.
    #
    ren1.AddActor(outlineActor)
    ren1.AddActor(streamerActor)
    ren1.AddActor(isoActor)
    ren1.SetBackground(colors.GetColor3d("Wheat"))
    renWin.SetSize(640, 480)

    cam1 = vtk.vtkCamera()
    cam1.SetClippingRange(17.4043, 870.216)
    cam1.SetFocalPoint(136.71, 104.025, 23)
    cam1.SetPosition(204.747, 258.939, 63.7925)
    cam1.SetViewUp(-0.102647, -0.210897, 0.972104)
    cam1.Zoom(1.6)
    ren1.SetActiveCamera(cam1)

    # Render the image.
    #
    renWin.Render()
    iren.Start()