Python vtk.vtkStructuredGrid() Examples

The following are 10 code examples of vtk.vtkStructuredGrid(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module vtk , or try the search function .
Example #1
Source File: vtkModule.py    From discretize with MIT License 7 votes vote down vote up
def __create_structured_grid(ptsMat, dims, models=None):
        """An internal helper to build out structured grids"""
        # Adjust if result was 2D:
        if ptsMat.shape[1] == 2:
            # Figure out which dim is null
            nullDim = dims.index(None)
            ptsMat = np.insert(ptsMat, nullDim, np.zeros(ptsMat.shape[0]), axis=1)
        if ptsMat.shape[1] != 3:
            raise RuntimeError('Points of the mesh are improperly defined.')
        # Convert the points
        vtkPts = _vtk.vtkPoints()
        vtkPts.SetData(_nps.numpy_to_vtk(ptsMat, deep=True))
        # Uncover hidden dimension
        for i, d in enumerate(dims):
            if d is None:
                dims[i] = 0
            dims[i] = dims[i] + 1
        output = _vtk.vtkStructuredGrid()
        output.SetDimensions(dims[0], dims[1], dims[2]) # note this subtracts 1
        output.SetPoints(vtkPts)
        # Assign the model('s) to the object
        return assign_cell_data(output, models=models) 
Example #2
Source File: pointset.py    From pyvista with MIT License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        """Initialize the structured grid."""
        super().__init__()

        if len(args) == 1:
            if isinstance(args[0], vtk.vtkStructuredGrid):
                self.deep_copy(args[0])
            elif isinstance(args[0], str):
                self._load_file(args[0])

        elif len(args) == 3:
            arg0_is_arr = isinstance(args[0], np.ndarray)
            arg1_is_arr = isinstance(args[1], np.ndarray)
            arg2_is_arr = isinstance(args[2], np.ndarray)

            if all([arg0_is_arr, arg1_is_arr, arg2_is_arr]):
                self._from_arrays(args[0], args[1], args[2]) 
Example #3
Source File: test_composite.py    From pyvista with MIT License 5 votes vote down vote up
def test_multi_block_init_vtk():
    multi = vtk.vtkMultiBlockDataSet()
    multi.SetBlock(0, vtk.vtkRectilinearGrid())
    multi.SetBlock(1, vtk.vtkStructuredGrid())
    multi = MultiBlock(multi)
    assert isinstance(multi, MultiBlock)
    assert multi.n_blocks == 2
    assert isinstance(multi.GetBlock(0), RectilinearGrid)
    assert isinstance(multi.GetBlock(1), StructuredGrid)
    multi = vtk.vtkMultiBlockDataSet()
    multi.SetBlock(0, vtk.vtkRectilinearGrid())
    multi.SetBlock(1, vtk.vtkStructuredGrid())
    multi = MultiBlock(multi, deep=True)
    assert isinstance(multi, MultiBlock)
    assert multi.n_blocks == 2
    assert isinstance(multi.GetBlock(0), RectilinearGrid)
    assert isinstance(multi.GetBlock(1), StructuredGrid)
    # Test nested structure
    multi = vtk.vtkMultiBlockDataSet()
    multi.SetBlock(0, vtk.vtkRectilinearGrid())
    multi.SetBlock(1, vtk.vtkImageData())
    nested = vtk.vtkMultiBlockDataSet()
    nested.SetBlock(0, vtk.vtkUnstructuredGrid())
    nested.SetBlock(1, vtk.vtkStructuredGrid())
    multi.SetBlock(2, nested)
    # Wrap the nested structure
    multi = MultiBlock(multi)
    assert isinstance(multi, MultiBlock)
    assert multi.n_blocks == 3
    assert isinstance(multi.GetBlock(0), RectilinearGrid)
    assert isinstance(multi.GetBlock(1), UniformGrid)
    assert isinstance(multi.GetBlock(2), MultiBlock) 
Example #4
Source File: wvtk.py    From pyCGNS with GNU Lesser General Public License v2.1 5 votes vote down vote up
def setCutPlane(self):
        if self._currentactor is None:
            return
        if not vtk.vtkStructuredGrid().SafeDownCast(self._currentactor[1].GetMapper().GetInput()):
            return
        bounds = self._currentactor[1].GetBounds()
        bds = [0, 0, 0]
        bds[0] = (bounds[0] + bounds[1]) / 2.0
        bds[1] = (bounds[3] + bounds[2]) / 2.0
        bds[2] = (bounds[5] + bounds[4]) / 2.0
        grid = self._currentactor[1].GetMapper().GetInput()
        filter = vtk.vtkStructuredGridGeometryFilter()
        if VTK_VERSION_MAJOR < 8:
            raise RuntimeError("VTK version is too old, please upgrade")
        filter.SetInputData(grid)
        self.planeWidget.SetPlaceFactor(1.0)
        self.planeWidget.GetOutlineProperty().SetColor(0, 1, 1)
        self.planeWidget.OutlineTranslationOff()
        if VTK_VERSION_MAJOR < 8:
            raise RuntimeError("VTK version is too old, please upgrade")
        self.planeWidget.SetInputConnection(filter.GetOutputPort())
        self.planeWidget.PlaceWidget()
        self.planeWidget.SetOrigin(bds[0], bds[1], bds[2])
        self.planeWidget.SetNormal(1, 0, 0)
        self.planeWidget.On()
        self.planeWidget.AddObserver("InteractionEvent", self.myCallback)
        self._iren.Render() 
Example #5
Source File: wvtk.py    From pyCGNS with GNU Lesser General Public License v2.1 5 votes vote down vote up
def showValues(self, *args):
        if self._currentactor is not None:
            if not vtk.vtkStructuredGrid().SafeDownCast(self._currentactor[1].GetMapper().GetInput()):
                self.cShowValue.setChecked(0)
                return
        if (self.cVariables.currentIndex() == 0) or self.OutlineActor is None:
            self.cShowValue.setChecked(0)
            return
        if self.cShowValue.isChecked():
            self.observer = self._iren.AddObserver("MouseMoveEvent", self.displayScalars)
        elif self.observer is not None:
            self._iren.RemoveObserver(self.observer) 
Example #6
Source File: vtkModule.py    From discretize with MIT License 5 votes vote down vote up
def _save_structured_grid(filename, vtkStructGrid, directory=''):
        """Saves a VTK structured grid file (vtk) for an already generated
        :class:`pyvista.StructuredGrid` object.

        Parameters
        ----------

        filename : str
            path to the output vtk file or just its name if directory is specified

        directory : str
            directory where the UBC GIF file lives

        """
        if not isinstance(vtkStructGrid, _vtk.vtkStructuredGrid):
            raise RuntimeError('`_save_structured_grid` can only handle `vtkStructuredGrid` objects. `{}` is not supported.'.format(vtkStructGrid.__class__))
        # Check the extension of the filename
        fname = os.path.join(directory, filename)
        ext = os.path.splitext(fname)[1]
        if ext is '':
            fname = fname + '.vts'
        elif ext not in '.vts':
            raise IOError('{:s} is an incorrect extension, has to be .vts'.format(ext))
        # Make the writer
        writer = _vtkStrucWriter()
        if float(_vtk_version.split('.')[0]) >= 6:
            writer.SetInputDataObject(vtkStructGrid)
        else:
            writer.SetInput(vtkStructGrid)
        writer.SetFileName(fname)
        # Write the file
        writer.Update() 
Example #7
Source File: vtkModule.py    From discretize with MIT License 5 votes vote down vote up
def writeVTK(mesh, filename, models=None, directory=''):
        """Makes and saves a VTK object from this mesh and given models

        Parameters
        ----------

        filename : str
            path to the output vtk file or just its name if directory is specified

        models : dict
            dictionary of numpy.array - Name('s) and array('s). Match number of cells

        directory : str
            directory where the UBC GIF file lives


        """
        vtkObj = InterfaceVTK.to_vtk(mesh, models=models)
        writers = {
            'vtkUnstructuredGrid' : InterfaceVTK._save_unstructured_grid,
            'vtkRectilinearGrid' : InterfaceVTK._save_rectilinear_grid,
            'vtkStructuredGrid' : InterfaceVTK._save_structured_grid,
            }
        key = vtkObj.GetClassName()
        try:
            write = writers[key]
        except:
            raise RuntimeError('VTK data type `%s` is not currently supported.' % key)
        return write(filename, vtkObj, directory=directory) 
Example #8
Source File: pointset.py    From pyvista with MIT License 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        """Initialize the unstructured grid."""
        super().__init__()
        deep = kwargs.pop('deep', False)

        if not len(args):
            return
        if len(args) == 1:
            if isinstance(args[0], vtk.vtkUnstructuredGrid):
                if deep:
                    self.deep_copy(args[0])
                else:
                    self.shallow_copy(args[0])

            elif isinstance(args[0], str):
                self._load_file(args[0])

            elif isinstance(args[0], vtk.vtkStructuredGrid):
                vtkappend = vtk.vtkAppendFilter()
                vtkappend.AddInputData(args[0])
                vtkappend.Update()
                self.shallow_copy(vtkappend.GetOutput())

            else:
                itype = type(args[0])
                raise TypeError('Cannot work with input type %s' % itype)

        elif len(args) == 3 and VTK9:
            arg0_is_arr = isinstance(args[0], np.ndarray)
            arg1_is_arr = isinstance(args[1], np.ndarray)
            arg2_is_arr = isinstance(args[2], np.ndarray)

            if all([arg0_is_arr, arg1_is_arr, arg2_is_arr]):
                self._from_arrays(None, args[0], args[1], args[2], deep)
            else:
                raise TypeError('All input types must be np.ndarray')

        elif len(args) == 4:
            arg0_is_arr = isinstance(args[0], np.ndarray)
            arg1_is_arr = isinstance(args[1], np.ndarray)
            arg2_is_arr = isinstance(args[2], np.ndarray)
            arg3_is_arr = isinstance(args[3], np.ndarray)

            if all([arg0_is_arr, arg1_is_arr, arg2_is_arr, arg3_is_arr]):
                self._from_arrays(args[0], args[1], args[2], args[3], deep)
            else:
                raise TypeError('All input types must be np.ndarray')

        else:
            err_msg = 'Invalid parameters.  Initialization with arrays ' +\
                      'requires the following arrays:\n'
            if VTK9:
                raise TypeError(err_msg + '`cells`, `cell_type`, `points`')
            else:
                raise TypeError(err_msg + '`offset`, `cells`, `cell_type`, `points`') 
Example #9
Source File: surface.py    From omfvista with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def surface_grid_geom_to_vtk(surfgridgeom):
    """Convert the 2D grid to a :class:`pyvista.StructuredGrid` object.

    Args:
        surfgridgeom (:class:`omf.surface.SurfaceGridGeometry`): the surface
            grid geometry to convert

    """
    surfgridgeom._validate_mesh()

    output = vtk.vtkStructuredGrid()

    axis_u = np.array(surfgridgeom.axis_u)
    axis_v = np.array(surfgridgeom.axis_v)
    axis_w = np.cross(axis_u, axis_v)
    if not check_orthogonal(axis_u, axis_v, axis_w):
        raise ValueError('axis_u, axis_v, and axis_w must be orthogonal')
    rotation_mtx = np.array([axis_u, axis_v, axis_w])
    ox, oy, oz = surfgridgeom.origin

    # Make coordinates along each axis
    x = ox + np.cumsum(surfgridgeom.tensor_u)
    x = np.insert(x, 0, ox)
    y = oy + np.cumsum(surfgridgeom.tensor_v)
    y = np.insert(y, 0, oy)

    z = np.array([oz])

    output.SetDimensions(len(x), len(y), len(z))

    # Build out all nodes in the mesh
    xx, yy, zz = np.meshgrid(x, y, z, indexing='ij')
    xx, yy, zz, = xx.ravel('F'), yy.ravel('F'), zz.ravel('F')
    zz += surfgridgeom.offset_w
    points = np.c_[xx, yy, zz]

    # Rotate the points based on the axis orientations
    points = points.dot(rotation_mtx)

    # Convert points to vtk object
    pts = vtk.vtkPoints()
    pts.SetNumberOfPoints(len(points))
    pts.SetData(nps.numpy_to_vtk(points))
    # Now build the output
    output.SetPoints(pts)

    return pyvista.wrap(output) 
Example #10
Source File: volume.py    From omfvista with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def volume_grid_geom_to_vtk(volgridgeom):
    """Convert the 3D gridded volume to a :class:`pyvista.StructuredGrid`
    (or a :class:`pyvista.RectilinearGrid` when apprropriate) object contatining
    the 2D surface.

    Args:
        volgridgeom (:class:`omf.volume.VolumeGridGeometry`): the grid geometry
            to convert
    """
    volgridgeom._validate_mesh()

    ox, oy, oz = volgridgeom.origin

    # Make coordinates along each axis
    x = ox + np.cumsum(volgridgeom.tensor_u)
    x = np.insert(x, 0, ox)
    y = oy + np.cumsum(volgridgeom.tensor_v)
    y = np.insert(y, 0, oy)
    z = oz + np.cumsum(volgridgeom.tensor_w)
    z = np.insert(z, 0, oz)

    # If axis orientations are standard then use a vtkRectilinearGrid
    if check_orientation(volgridgeom.axis_u, volgridgeom.axis_v, volgridgeom.axis_w):
        output = vtk.vtkRectilinearGrid()
        output.SetDimensions(len(x), len(y), len(z)) # note this subtracts 1
        output.SetXCoordinates(nps.numpy_to_vtk(num_array=x))
        output.SetYCoordinates(nps.numpy_to_vtk(num_array=y))
        output.SetZCoordinates(nps.numpy_to_vtk(num_array=z))
        return pyvista.wrap(output)

    # Otherwise use a vtkStructuredGrid
    output = vtk.vtkStructuredGrid()
    output.SetDimensions(len(x), len(y), len(z)) # note this subtracts 1

    # Build out all nodes in the mesh
    xx, yy, zz = np.meshgrid(x, y, z, indexing='ij')
    points = np.c_[xx.ravel('F'), yy.ravel('F'), zz.ravel('F')]

    # Rotate the points based on the axis orientations
    rotation_mtx = np.array([volgridgeom.axis_u, volgridgeom.axis_v, volgridgeom.axis_w])
    points = points.dot(rotation_mtx)

    # Convert points to vtk object
    pts = vtk.vtkPoints()
    pts.SetNumberOfPoints(len(points))
    pts.SetData(nps.numpy_to_vtk(points))
    # Now build the output
    output.SetPoints(pts)

    return pyvista.wrap(output)