Python vtk.vtkRectilinearGrid() Examples

The following are 17 code examples of vtk.vtkRectilinearGrid(). 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: show_lidar_vtk.py    From Det3D with Apache License 2.0 5 votes vote down vote up
def draw_grid():
    xArray = vtk.vtkDoubleArray()
    yArray = vtk.vtkDoubleArray()
    zArray = vtk.vtkDoubleArray()

    for x in range(-60, 61):
        xArray.InsertNextValue(x)
    # for y in range(-10, 10):
    #     yArray.InsertNextValue(y)
    for y in range(0, 1):
        yArray.InsertNextValue(y)
    for z in range(-80, 80):
        zArray.InsertNextValue(z)

    grid = vtk.vtkRectilinearGrid()
    grid.SetDimensions(121, 1, 161)
    grid.SetXCoordinates(xArray)
    grid.SetYCoordinates(yArray)
    grid.SetZCoordinates(zArray)

    # print(grid.GetPoint(0))

    gridMapper = vtk.vtkDataSetMapper()
    gridMapper.SetInputData(grid)

    gridActor = vtk.vtkActor()
    gridActor.SetMapper(gridMapper)
    gridActor.GetProperty().SetColor(0.75, 0.75, 0)
    gridActor.GetProperty().SetOpacity(0.1)
    # import pdb; pdb.set_trace()
    return gridActor 
Example #2
Source File: grid.py    From pyvista with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        """Initialize the rectilinear grid."""
        super().__init__()

        if len(args) == 1:
            if isinstance(args[0], vtk.vtkRectilinearGrid):
                self.deep_copy(args[0])
            elif isinstance(args[0], str):
                self._load_file(args[0])
            elif isinstance(args[0], np.ndarray):
                self._from_arrays(args[0], None, None)
            else:
                raise TypeError("Type ({}) not understood by `RectilinearGrid`.".format(type(args[0])))

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

            if all([arg0_is_arr, arg1_is_arr, arg2_is_arr]):
                self._from_arrays(args[0], args[1], args[2])
            elif all([arg0_is_arr, arg1_is_arr]):
                self._from_arrays(args[0], args[1], None)
            else:
                raise TypeError("Arguments not understood by `RectilinearGrid`.") 
Example #3
Source File: vtkModule.py    From discretize with MIT License 5 votes vote down vote up
def _save_rectilinear_grid(filename, vtkRectGrid, directory=''):
        """Saves a VTK rectilinear file (vtr) ffor an already generated
        :class:`pyvista.RectilinearGrid` 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(vtkRectGrid, _vtk.vtkRectilinearGrid):
            raise RuntimeError('`_save_rectilinear_grid` can only handle `vtkRectilinearGrid` objects. `{}` is not supported.'.format(vtkRectGrid.__class__))
        # Check the extension of the filename
        fname = os.path.join(directory, filename)
        ext = os.path.splitext(fname)[1]
        if ext is '':
            fname = fname + '.vtr'
        elif ext not in '.vtr':
            raise IOError('{:s} is an incorrect extension, has to be .vtr'.format(ext))
        # Write the file.
        vtrWriteFilter = _vtkRectWriter()
        if float(_vtk_version.split('.')[0]) >= 6:
            vtrWriteFilter.SetInputDataObject(vtkRectGrid)
        else:
            vtuWriteFilter.SetInput(vtuObj)
        vtrWriteFilter.SetFileName(fname)
        vtrWriteFilter.Update() 
Example #4
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 #5
Source File: vtkModule.py    From discretize with MIT License 5 votes vote down vote up
def vtk_to_tensor_mesh(TensorMesh, vtrGrid):
        """Converts a ``vtkRectilinearGrid`` or :class:`pyvista.RectilinearGrid`
        to a :class:`discretize.TensorMesh` object.

        """
        # Sort information
        hx = np.abs(np.diff(_nps.vtk_to_numpy(vtrGrid.GetXCoordinates())))
        xR = _nps.vtk_to_numpy(vtrGrid.GetXCoordinates())[0]
        hy = np.abs(np.diff(_nps.vtk_to_numpy(vtrGrid.GetYCoordinates())))
        yR = _nps.vtk_to_numpy(vtrGrid.GetYCoordinates())[0]
        zD = np.diff(_nps.vtk_to_numpy(vtrGrid.GetZCoordinates()))
        # Check the direction of hz
        if np.all(zD < 0):
            hz = np.abs(zD[::-1])
            zR = _nps.vtk_to_numpy(vtrGrid.GetZCoordinates())[-1]
        else:
            hz = np.abs(zD)
            zR = _nps.vtk_to_numpy(vtrGrid.GetZCoordinates())[0]
        x0 = np.array([xR, yR, zR])

        # Make the object
        tensMsh = TensorMesh([hx, hy, hz], x0=x0)

        # Grap the models
        models = {}
        for i in np.arange(vtrGrid.GetCellData().GetNumberOfArrays()):
            modelName = vtrGrid.GetCellData().GetArrayName(i)
            if np.all(zD < 0):
                modFlip = _nps.vtk_to_numpy(vtrGrid.GetCellData().GetArray(i))
                tM = tensMsh.r(modFlip, 'CC', 'CC', 'M')
                modArr = tensMsh.r(tM[:, :, ::-1], 'CC', 'CC', 'V')
            else:
                modArr = _nps.vtk_to_numpy(vtrGrid.GetCellData().GetArray(i))
            models[modelName] = modArr

        # Return the data
        return tensMsh, models 
Example #6
Source File: tensor.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, nOutputPorts=1, outputType='vtkRectilinearGrid', **kwargs):
        ubcMeshReaderBase.__init__(self,
                                   nOutputPorts=nOutputPorts, outputType=outputType, **kwargs)

        self.__mesh = vtk.vtkRectilinearGrid()
        self.__models = [] 
Example #7
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 #8
Source File: two_file_base.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def RequestInformation(self, request, inInfo, outInfo):
        """Used by pipeline to handle time variance and update output extents
        """
        self._update_time_steps()
        pdi = self.GetInputData(inInfo, 0, 0)
        # Determine if 2D or 3D and read
        if isinstance(pdi, vtk.vtkRectilinearGrid) and pdi.GetExtent()[3] == 1:
            self._is_3D = False
        else:
            self._is_3D = True
        return 1

    #### Setters and Getters #### 
Example #9
Source File: tensor.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __ubc_tensor_mesh(self, filename_mesh, filename_models, output):
        """Wrapper to Read UBC GIF 2D and 3D meshes. UBC Mesh 2D/3D models are
        defined using a 2-file format. The "mesh" file describes how the data is
        descritized. The "model" file lists the physical property values for all
        cells in a mesh. A model file is meaningless without an associated mesh
        file. If the mesh file is 2D, then then model file must also be in the
        2D format (same for 3D).

        Args:
            filename_mesh (str) : The mesh filename as an absolute path for the
                input mesh file in UBC 2D/3D Mesh Format
            filename_models (str or list(str)) : The model filename(s) as an
                absolute path for the input model file in UBC 2D/3D Model Format.
            output (vtkRectilinearGrid) : The output data object

        Return:
            vtkRectilinearGrid :
                a ``vtkRectilinearGrid`` generated from the UBC 2D/3D Mesh grid.
                Mesh is defined by the input mesh file.
                Cell data is defined by the input model file.

        """
        # Check if the mesh is a UBC 2D mesh
        if self.is_2d():
            self.__ubc_mesh_data_2d(filename_mesh, filename_models, output)
        # Check if the mesh is a UBC 3D mesh
        elif self.is_3d():
            self.__ubc_mesh_data_3d(filename_mesh, filename_models, output)
        else:
            raise _helpers.PVGeoError('File format not recognized')
        return output 
Example #10
Source File: tensor.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clear_mesh(self):
        """Use to clean/rebuild the mesh
        """
        self.__mesh = vtk.vtkRectilinearGrid()
        ubcMeshReaderBase.clear_models(self) 
Example #11
Source File: tensor.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, inputType='vtkRectilinearGrid',
                 outputType='vtkRectilinearGrid', **kwargs):
        AlgorithmBase.__init__(self,
                               nInputPorts=1, inputType=inputType,
                               nOutputPorts=1, outputType=outputType)
        self._topoFileName = kwargs.get('filename', None)
        self.__indices = None
        self.__need_to_read = True
        self.__ne, self.__nn = None, None 
Example #12
Source File: two_file_base.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, inputType='vtkRectilinearGrid', outputType='vtkRectilinearGrid', **kwargs):
        base.AlgorithmBase.__init__(self,
                                    nInputPorts=1, inputType=inputType,
                                    nOutputPorts=1, outputType=outputType)
        self._model_filenames = kwargs.get('model_files', [])
        self.__data_name = kwargs.get('dataname', 'Appended Data')
        self.__use_filename = True
        self._models = []
        self.__need_to_read = True
        self._is_3D = None
        # For the VTK/ParaView pipeline
        self.__dt = kwargs.get('dt', 1.0)
        self.__timesteps = None
        self.__last_successfull_index = 0 #This is the index to use if the current timestep is unavailable 
Example #13
Source File: tensor.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def place_model_on_mesh(mesh, model, data_name='Data'):
        """Places model data onto a mesh. This is for the UBC Grid data reaers
        to associate model data with the mesh grid.

        Args:
            mesh (vtkRectilinearGrid): The ``vtkRectilinearGrid`` that is the
                mesh to place the model data upon.
            model (np.array): A NumPy float array that holds all of the data to
                place inside of the mesh's cells.
            data_name (str) : The name of the model data array once placed on the
                ``vtkRectilinearGrid``.

        Return:
            vtkRectilinearGrid :
                Returns the input ``vtkRectilinearGrid`` with model data appended.
        """
        if isinstance(model, dict):
            for key in model.keys():
                TensorMeshReader.place_model_on_mesh(mesh, model[key], data_name=key)
            return mesh

        # model.GetNumberOfValues() if model is vtkDataArray
        # Make sure this model file fits the dimensions of the mesh
        ext = mesh.GetExtent()
        n1,n2,n3 = ext[1],ext[3],ext[5]
        if (n1*n2*n3 < len(model)):
            raise _helpers.PVGeoError('Model `%s` has more data than the given mesh has cells to hold.' % data_name)
        elif (n1*n2*n3 > len(model)):
            raise _helpers.PVGeoError('Model `%s` does not have enough data to fill the given mesh\'s cells.' % data_name)

        # Swap axes because VTK structures the coordinates a bit differently
        #-  This is absolutely crucial!
        #-  Do not play with unless you know what you are doing!
        if model.ndim > 1 and model.ndim < 3:
            ncomp = model.shape[1]
            model = np.reshape(model, (n1, n2, n3, ncomp))
            model = np.swapaxes(model,0,1)
            model = np.swapaxes(model,0,2)
            # Now reverse Z axis
            model = model[::-1,:,:,:] # Note it is in Fortran ordering
            model = np.reshape(model, (n1*n2*n3, ncomp))
        else:
            model = np.reshape(model, (n1,n2,n3))
            model = np.swapaxes(model,0,1)
            model = np.swapaxes(model,0,2)
            # Now reverse Z axis
            model = model[::-1,:,:] # Note it is in Fortran ordering
            model = model.flatten()

        # Convert data to VTK data structure and append to output
        c = interface.convert_array(model, name=data_name, deep=True)
        # THIS IS CELL DATA! Add the model data to CELL data:
        mesh.GetCellData().AddArray(c)
        return mesh

    #------------------------------------------------------------------#
    #----------------------     UBC MESH 2D    ------------------------#
    #------------------------------------------------------------------# 
Example #14
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) 
Example #15
Source File: tensor.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def ubc_mesh_2d(FileName, output):
        """This method reads a UBC 2D Mesh file and builds an empty
        ``vtkRectilinearGrid`` for data to be inserted into. `Format Specs`_.

        .. _Format Specs: http://giftoolscookbook.readthedocs.io/en/latest/content/fileFormats/mesh2Dfile.html

        Args:
            FileName (str) : The mesh filename as an absolute path for the input
                mesh file in UBC 3D Mesh Format.
            output (vtkRectilinearGrid) : The output data object

        Return:
            vtkRectilinearGrid :
                a ``vtkRectilinearGrid`` generated from the UBC 3D Mesh grid.
                Mesh is defined by the input mesh file.
                No data attributes here, simply an empty mesh. Use the
                ``place_model_on_mesh()`` method to associate with model data.
        """
        # Read in data from file
        xpts, xdisc, zpts, zdisc = ubcMeshReaderBase._ubc_mesh_2d_part(FileName)

        nx = np.sum(np.array(xdisc,dtype=int))+1
        nz = np.sum(np.array(zdisc,dtype=int))+1

        # Now generate the vtkRectilinear Grid
        def _genCoords(pts, disc, z=False):
            c = [float(pts[0])]
            for i in range(len(pts)-1):
                start = float(pts[i])
                stop = float(pts[i+1])
                num = int(disc[i])
                w = (stop-start)/num

                for j in range(1,num):
                    c.append(start + (j)*w)
                c.append(stop)
            c = np.array(c,dtype=float)
            if z:
                c = -c[::-1]
            return interface.convert_array(c,deep=True)

        xcoords = _genCoords(xpts, xdisc)
        zcoords = _genCoords(zpts, zdisc, z=True)
        ycoords = interface.convert_array(np.zeros(1),deep=True)

        output.SetDimensions(nx,2,nz) # note this subtracts 1
        output.SetXCoordinates(xcoords)
        output.SetYCoordinates(ycoords)
        output.SetZCoordinates(zcoords)

        return output 
Example #16
Source File: vtkModule.py    From discretize with MIT License 4 votes vote down vote up
def __tensor_mesh_to_vtk(mesh, models=None):
        """
        Constructs a :class:`pyvista.RectilinearGrid`
        (or a :class:`pyvista.StructuredGrid`) object of this tensor mesh and the
        given models as ``cell_arrays`` of that grid.
        If the mesh is defined on a normal cartesian system then a rectilinear
        grid is generated. Otherwise, a structured grid is generated.

        Parameters
        ----------

        mesh : discretize.TensorMesh
            The tensor mesh to convert to a :class:`pyvista.RectilinearGrid`

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

        """
        # Deal with dimensionalities
        if mesh.dim >= 1:
            vX = mesh.vectorNx
            xD = mesh.nNx
            yD, zD = 1, 1
            vY, vZ = np.array([0, 0])
        if mesh.dim >= 2:
            vY = mesh.vectorNy
            yD = mesh.nNy
        if mesh.dim == 3:
            vZ = mesh.vectorNz
            zD = mesh.nNz
        # If axis orientations are standard then use a vtkRectilinearGrid
        if not mesh.reference_is_rotated:
            # Use rectilinear VTK grid.
            # Assign the spatial information.
            output = _vtk.vtkRectilinearGrid()
            output.SetDimensions(xD, yD, zD)
            output.SetXCoordinates(_nps.numpy_to_vtk(vX, deep=1))
            output.SetYCoordinates(_nps.numpy_to_vtk(vY, deep=1))
            output.SetZCoordinates(_nps.numpy_to_vtk(vZ, deep=1))
            return assign_cell_data(output, models=models)
        # Use a structured grid where points are rotated to the cartesian system
        ptsMat = InterfaceVTK.__get_rotated_nodes(mesh)
        dims = [mesh.nCx, mesh.nCy, mesh.nCz]
        # Assign the model('s) to the object
        return InterfaceVTK.__create_structured_grid(ptsMat, dims, models=models) 
Example #17
Source File: filters.py    From pyvista with MIT License 4 votes vote down vote up
def warp_by_scalar(dataset, scalars=None, factor=1.0, normal=None,
                       inplace=False, **kwargs):
        """Warp the dataset's points by a point data scalars array's values.

        This modifies point coordinates by moving points along point normals by
        the scalar amount times the scale factor.

        Parameters
        ----------
        scalars : str, optional
            Name of scalars to warp by. Defaults to currently active scalars.

        factor : float, optional
            A scaling factor to increase the scaling effect. Alias
            ``scale_factor`` also accepted - if present, overrides ``factor``.

        normal : np.array, list, tuple of length 3
            User specified normal. If given, data normals will be ignored and
            the given normal will be used to project the warp.

        inplace : bool
            If True, the points of the give dataset will be updated.

        """
        factor = kwargs.pop('scale_factor', factor)
        assert_empty_kwargs(**kwargs)
        if scalars is None:
            field, scalars = dataset.active_scalars_info
        arr, field = get_array(dataset, scalars, preference='point', info=True)
        if field != FieldAssociation.POINT:
            raise TypeError('Dataset can only by warped by a point data array.')
        # Run the algorithm
        alg = vtk.vtkWarpScalar()
        alg.SetInputDataObject(dataset)
        alg.SetInputArrayToProcess(0, 0, 0, field.value, scalars) # args: (idx, port, connection, field, name)
        alg.SetScaleFactor(factor)
        if normal is not None:
            alg.SetNormal(normal)
            alg.SetUseNormal(True)
        alg.Update()
        output = _get_output(alg)
        if inplace:
            if isinstance(dataset, (vtk.vtkImageData, vtk.vtkRectilinearGrid)):
                raise TypeError("This filter cannot be applied inplace for this mesh type.")
            dataset.overwrite(output)
            return
        return output