Ejemplo n.º 1
0
 def __init__(self, params, element_id, dimensions, color,
              opacity, origin=None, spacing=None):
     """Initialize the Element."""
     self.actor = None
     self.params = params
     self.element_id = element_id
     self.unit = self.params["unit"]
     self.edge_color_offset = self.params["element"]["edge_color_offset"]
     if origin is None:
         origin = self.params["origin"]
     if spacing is None:
         spacing = [self.unit, self.unit, self.unit]
     self.dimensions = np.asarray(dimensions)
     self.origin = np.asarray(origin)
     self.spacing = np.asarray(spacing)
     self.center = self.origin + np.multiply(self.dimensions / 2.,
                                             self.spacing)
     self.color = np.asarray(color)
     self.edge_color = np.asarray(self.color) + self.edge_color_offset
     self.opacity = float(opacity)
     self.mesh = vtk.vtkUniformGrid()
     self.mesh.Initialize()
     self.mesh.SetDimensions(self.dimensions)
     self.mesh.SetSpacing(self.spacing)
     self.mesh.SetOrigin(self.origin)
     self.plotting = {
         "mesh": self.mesh,
         "color": self.color,
         "edge_color": self.edge_color,
         "opacity": self.opacity,
     }
Ejemplo n.º 2
0
def get_uniform_grid(dimensions=(2, 2, 2),
                     origin=(0., 0., 0.),
                     spacing=(1., 1., 1.)):
    """Create a vtkUniformGrid."""
    mesh = vtk.vtkUniformGrid()
    mesh.Initialize()
    mesh.SetDimensions(*dimensions)
    mesh.SetOrigin(*origin)
    mesh.SetSpacing(*spacing)
    return mesh
Ejemplo n.º 3
0
def uniform_grid(min_, max_, res):
    """ Creates an uniform grid
    @param min_    minimum of bounding rectangle
    @param max_    maximum of bounding rectangle
    @param res_    cell resolution
    @return The vtkUniformGrid
    """
    grid = vtk.vtkUniformGrid()
    grid.SetDimensions(int(res[0]) + 1,
                       int(res[1]) + 1,
                       int(res[2]) + 1)  # cell to point resolution
    grid.SetOrigin(min_[0], min_[1], min_[2])
    s = (max_ - min_) / res
    grid.SetSpacing(s[0], s[1], s[2])
    return grid
Ejemplo n.º 4
0
    def getVTKGrid(self):
        """
        Return a vtkUniformGrid object for given patch specification
        """

        # Create VTK grid patch
        grid = vtk.vtkUniformGrid()
        grid.SetSpacing(self.dx, self.dy, 0)
        grid.SetExtent(0, self.nx, 0, self.ny, 0, 0)
        grid.SetOrigin([self.origin[0], self.origin[1], 0])

        # Attach data array - note that this can be easily replaced with a pointer
        # into a large data array
        vtkData = nps.numpy_to_vtk(self.data.flat,
                                   deep=False,
                                   array_type=vtk.VTK_DOUBLE)
        vtkData.SetName('data')
        grid.GetCellData().AddArray(vtkData)

        return grid
Ejemplo n.º 5
0
def main():
    colors = vtk.vtkNamedColors()

    # Create and populate the AMR dataset
    # The dataset should look like
    # Level 0
    #   uniform grid, dimensions 11, 11, 11, AMR box (0, 0, 0) - (9, 9, 9)
    # Level 1 - refinement ratio : 2
    #   uniform grid, dimensions 11, 11, 11, AMR box (0, 0, 0) - (9, 9, 9)
    #   uniform grid, dimensions 11, 11, 11, AMR box (10, 10, 10) - (19, 19, 19)
    # Use MakeScalars() above to fill the scalar arrays

    amr = vtk.vtkOverlappingAMR()
    blocksPerLevel = [1, 2]
    amr.Initialize(2, blocksPerLevel)

    origin = [0.0, 0.0, 0.0]
    spacing = [1.0, 1.0, 1.0]
    dims = [11, 11, 11]

    ug1 = vtk.vtkUniformGrid()
    # Geometry
    ug1.SetOrigin(origin)
    ug1.SetSpacing(spacing)
    ug1.SetDimensions(dims)

    # Data
    scalars = vtk.vtkFloatArray()
    ug1.GetPointData().SetScalars(scalars)
    MakeScalars(dims, origin, spacing, scalars)

    lo = [0, 0, 0]
    hi = [9, 9, 9]
    box1 = vtk.vtkAMRBox()
    amr.SetAMRBox(0, 0, box1)
    amr.SetDataSet(0, 0, ug1)

    spacing2 = [0.5, 0.5, 0.5]
    ug2 = vtk.vtkUniformGrid()
    # Geometry
    ug2.SetOrigin(origin)
    ug2.SetSpacing(spacing2)
    ug2.SetDimensions(dims)

    # Data
    scalars = vtk.vtkFloatArray()
    ug2.GetPointData().SetScalars(scalars)
    MakeScalars(dims, origin, spacing2, scalars)

    lo2 = [0, 0, 0]
    hi2 = [9, 9, 9]
    box2 = vtk.vtkAMRBox()
    amr.SetAMRBox(1, 0, box2)
    amr.SetDataSet(1, 0, ug2)

    origin3 = [5, 5, 5]
    ug3 = vtk.vtkUniformGrid()

    # Geometry
    ug3.SetOrigin(origin3)
    ug3.SetSpacing(spacing2)
    ug3.SetDimensions(dims)

    # Data
    scalars = vtk.vtkFloatArray()
    ug3.GetPointData().SetScalars(scalars)
    MakeScalars(dims, origin3, spacing2, scalars)

    lo3 = [10, 10, 10]
    hi3 = [19, 19, 19]
    box3 = vtk.vtkAMRBox()
    amr.SetAMRBox(1, 1, box3)
    amr.SetDataSet(1, 1, ug3)
    amr.SetRefinementRatio(0, 2)

    # Render the amr data here.
    of = vtk.vtkOutlineFilter()
    of.SetInputData(amr)

    geomFilter = vtk.vtkCompositeDataGeometryFilter()
    geomFilter.SetInputConnection(of.GetOutputPort())

    # Create an iso-surface - at 10.
    cf = vtk.vtkContourFilter()
    cf.SetInputData(amr)
    cf.SetNumberOfContours(1)
    cf.SetValue(0, 10.0)

    geomFilter2 = vtk.vtkCompositeDataGeometryFilter()
    geomFilter2.SetInputConnection(cf.GetOutputPort())

    # Create the render window, renderer, and interactor.
    aren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(aren)

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

    # Associate the geometry with a mapper and the mapper to an actor.
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(geomFilter.GetOutputPort())
    actor1 = vtk.vtkActor()
    actor1.GetProperty().SetColor(colors.GetColor3d("Yellow"))
    actor1.SetMapper(mapper)

    # Associate the geometry with a mapper and the mapper to an actor.
    mapper2 = vtk.vtkPolyDataMapper()
    mapper2.SetInputConnection(geomFilter2.GetOutputPort())
    actor2 = vtk.vtkActor()
    actor2.SetMapper(mapper2)

    # Add the actor to the renderer and start handling events.
    aren.AddActor(actor1)
    aren.AddActor(actor2)
    aren.SetBackground(colors.GetColor3d("CornflowerBlue"))
    renWin.Render()
    iren.Start()
Ejemplo n.º 6
0
def write(
    solution,
    frame,
    path="_output",
    file_prefix='claw',
    write_aux=None,
    options=None,
    write_p=None,
):
    """Write out a VTK representation of solution

    This capability requires installation of the vtk module that is created by
    Kitware. Binary distributions are available through
    `PyPI <https://pypi.org/project/vtk/>`_
    or `conda-forge <https://anaconda.org/conda-forge/vtk>`_.

    .. code-block:: bash

       $ conda install -c conda-forge vtk

    or

    .. code-block:: bash

       $ pip install vtk

    For each input frame the following files and directories are created in
    the directory specified by *path*:

      - input_prefixXXXX.vthb. This file provides the metadata to
        describe how AMR patches are represented in the .vti files
        (including a relative
        path to the .vti files).
      - directory: input_prefixXXXX containing files called
        input_prefixXXXX_<index>.vti. <index> represents the file
        index. There is a file for each patch at each AMR level.

    Writing this function took advantage of the following VTK resources:
      - `the VTK users guide <https://www.kitware.com/products/books/VTKUsersGuide.pdf>`_
      - `this blog post on numpy integration <https://blog.kitware.com/improved-vtk-numpy-integration-part-5/>`_
      - `the vtkOverlappingAMR example <https://lorensen.github.io/VTKExamples/site/Python/CompositeData/OverlappingAMR/>`_
      - `the XML writing example <https://lorensen.github.io/VTKExamples/site/Python/IO/WriteXMLLinearCells/>`_

    This function uses the following VTK classes:

      - `vtkUniformGrid <https://vtk.org/doc/nightly/html/classvtkUniformGrid.html>`_
      - `vtkOverlappingAMR <https://vtk.org/doc/nightly/html/classvtkOverlappingAMR.html>`_
      - `vtkAMRBox <https://vtk.org/doc/nightly/html/classvtkAMRBox.html>`_
      - `vtkXMLUniformGridAMRWriter <https://vtk.org/doc/nightly/html/classvtkXMLUniformGridAMRWriter.html>`_

    To open in paraview, choose the group of .vthb files, not the group of
    folders. This will be read in as cell data. In order to use filters like
    WarpByScalar you must use the CellDataToPointData filter first.

    :Input:
     - *solution* - (:class:`~pyclaw.solution.Solution`) Pyclaw object to be
       output
     - *frame* - (int) Frame number
     - *path* - (string) Root path
     - *file_prefix* - (string) Prefix for the file name. ``default = 'claw'``
     - *write_aux* - (bool) Not implemented.
     - *options* - (dict) if contains the key value pair ``binary = True`` then
       output will be in binary rather than ascii. Default is ascii. Not implemented.
     - *write_p* - (bool) Not implemented.

    Note that some keyword arguments are not used. This is to maintain
    compatibility with the function signature expected by
    :py:class:`~pyclaw.Solution`

    Notes on what is not yet implemented
        - Add options for writing aux files.
        - Consider making an equivalent vtk.read function.
    """
    # get options from the options dictionary.
    binary = options.get("binary", False)

    # check types.
    assert (isinstance(frame, int))
    assert (isinstance(solution, Solution))

    # calculate overlapped status, used to identify some cells as ghosts.
    _set_overlapped_status(solution)

    global_origin = solution.state.patch.lower_global + [0.]  # base patch
    levels = [state.patch.level - 1 for state in solution.states]

    # shift base level to 0, since the base level in clawpack
    # is 1 while the base level in VTK is 0
    level_count = {}
    level_spacing = {}  # spacing of each level
    for i, level in enumerate(levels):
        if level in level_count.keys():
            level_count[level] = level_count[level] + 1
        else:
            level_count[level] = 1
            spacing = solution.states[i].patch.delta
            spacing.append(spacing[0])  # dz = dx
            spacing = np.array(spacing)
            level_spacing[level] = spacing
    numLevels = len(level_count.keys())

    # a list of num of patches at each level
    blocksPerLevel = [
        item[1] for item in sorted(level_count.items(), key=lambda a: a[0])
    ]

    # Initialize the vtkOverlappingAMR object. Provide it the number of levels,
    # number of blocks per level, and the global origin.
    amr = vtkOverlappingAMR()
    amr.Initialize(numLevels, blocksPerLevel)
    amr.SetOrigin(global_origin)

    # get states and initialize the global index (used below)
    states_sorted = sorted(solution.states, key=lambda a: a.patch.level)
    global_index = 0

    # for each AMR level create the vtkAMRBox and vtkUniformGrid and add to
    # the vtkOverlappingAMR object.
    for level in level_count.keys():
        # get number of blocks per level.
        nblocks = blocksPerLevel[level]

        # and the spacing at that level
        spacing = level_spacing[level]
        amr.SetSpacing(level, spacing)

        # for each block at this AMR level.
        for index in range(nblocks):
            # get the index used on the states_sorted file.
            local_index = global_index + index

            # get the origin and number of dimensions.
            origin = states_sorted[local_index].patch.lower_global + [0.]
            node_dims = [
                x + 1
                for x in states_sorted[local_index].patch.num_cells_global +
                [0]
            ]

            # create a vtkUniformGrid using the vtkAMRBox
            grid = vtkUniformGrid()
            grid.Initialize()
            grid.SetOrigin(origin)
            grid.SetSpacing(spacing)
            grid.SetDimensions(node_dims)

            # Construct an vtkAMRbox
            # Note that the dimensions specify the node dimensions, rather than the cell dimensions.
            # Nodes are one more than the cells.
            box = vtkAMRBox(origin, node_dims, spacing, global_origin)

            # Set the data of the vtkUniformGrid

            # get the cell data, and add each to the uniform grid.
            # ignore the last element of q, which provides info about overlapping.
            # it is set next.
            q = states_sorted[local_index].q

            for i in range(q.shape[0] - 1):
                array_name = "q_" + str(i)
                q_i = q[i, ...]
                q_i = q_i.transpose()

                #https://pyscience.wordpress.com/2014/09/06/numpy-to-vtk-converting-your-numpy-arrays-to-vtk-arrays-and-files/
                # transform into an array.
                array = numpy_support.numpy_to_vtk(num_array=q_i.ravel(),
                                                   deep=True,
                                                   array_type=vtk.VTK_FLOAT)

                # set the name.
                array.SetName(array_name)

                # verify the sizes are correct.
                assert q_i.size == grid.GetNumberOfCells()

                # add the array to the uniform grid.
                grid.GetCellData().AddArray(array)

            # mark overlapping cells using the vtkGhostType array name.
            q_ol = q[-1, ...]  # last piece is used to mark overlapped cells
            q_ol = q_ol.transpose()
            array = numpy_support.numpy_to_vtk(
                q_ol.ravel(), deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
            array.SetName("vtkGhostType")
            # add the array to the uniform grid.
            grid.GetCellData().AddArray(array)

            # add AMR box and uniform grid to the overlapping AMR object.
            amr.SetAMRBox(level, index, box)
            amr.SetDataSet(level, index, grid)

            # verify that the box is not invalid.
            assert not box.IsInvalid()

        # after each level is done increment global_index used with states_sorted
        global_index += nblocks

    # write out the vtkOverlappingAMR object.
    out = os.path.join(path, file_prefix + str(frame).zfill(4) + '.vthb')
    writer = vtkXMLUniformGridAMRWriter()
    if not binary:
        writer.SetDataModeToAscii()
    writer.SetFileName(out)
    writer.SetInputData(amr)
    success = writer.Write()

    # assert writing returned 1, indicating success.
    assert success == 1