Example #1
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkBoxClipDataSet(), 'Processing.',
         ('vtkDataSet',), ('vtkUnstructuredGrid', 'vtkUnstructuredGrid'),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Example #2
0
    def cutWithBox(self, box):
        """
        Cut the mesh with the plane defined by a point and a normal.

        Parameter box has format [xmin, xmax, ymin, ymax, zmin, zmax].
        If a Mesh is passed, its bounding box is used.

        Example:

            .. code-block:: python

                from vtkplotter import *
                tetmesh = TetMesh(datadir+'limb_ugrid.vtk')
                tetmesh.color('rainbow')
                cu = Cube(side=500).x(500) # any Mesh works
                tetmesh.cutWithBox(cu).show(axes=1)
        """
        bc = vtk.vtkBoxClipDataSet()
        bc.SetInputData(self._ugrid)
        if isinstance(box, (Mesh, TetMesh)):
            box = box.GetBounds()
        bc.SetBoxClip(*box)
        bc.Update()
        cout = bc.GetOutput()
        return self._update(cout)
Example #3
0
def clip(data, extent):
#   print "CLIP CLIP CLIP CLIP CLIP CLIP CLIP CLIP ", extent
    boxclip = vtk.vtkBoxClipDataSet()
    boxclip.GenerateClipScalarsOn()
    #boxclip.GenerateClippedOutputOn()
    boxclip.SetBoxClip(*extent)
    boxclip.SetInputData(data)
    boxclip.Update()
    return boxclip.GetOutput()
Example #4
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self,
         module_manager,
         vtk.vtkBoxClipDataSet(),
         'Processing.', ('vtkDataSet', ),
         ('vtkUnstructuredGrid', 'vtkUnstructuredGrid'),
         replaceDoc=True,
         inputFunctions=None,
         outputFunctions=None)
Example #5
0
def _calculateVolumeByBoxClip(vtkDataSet1,vtkDataSet2,iV):
    """
    Function to calculate the volumes of a cell intersecting a mesh.

    Uses a BoxClip filter to calculate the intersection, assumes the cell to
    be a voxel (=11) and aligned to the grid. This should work well for rectilinear
    and unstructured grids with all cells as voxels

    """
    import numpy as np, SimPEG as simpeg, vtk
    import vtk.util.numpy_support as npsup

    from telluricpy import vtkTools

    # Triangulate polygon and calc normals
    baseC = vtkTools.dataset.getCell2vtp(vtkDataSet2,iV)
    # Extrct the cell by the bounds first, significant speed up...
    if vtkDataSet1.IsA('vtkRectilinearGrid'):
        # Use a faster implementation of the rectgrid extraction
        extCells = _extractRectGridByBounds(vtkDataSet1,baseC)
    else:
        extCells = vtkTools.extraction.extractDataSetByBounds(vtkDataSet1,baseC)
    # Define the box clip and clip the first mesh with the cell
    cb = baseC.GetBounds()
    boxClip = vtk.vtkBoxClipDataSet()
    boxClip.SetInputConnection(extCells.GetOutputPort())
    boxClip.SetBoxClip(cb[0],cb[1],cb[2],cb[3],cb[4],cb[5])
    boxClip.Update()
    # Get the intersect grid
    intCells = boxClip.GetOutput()
    idList = npsup.vtk_to_numpy(intCells.GetCellData().GetArray('id'))
    uniIDs = np.unique(idList)
    # Extract cells from the first mesh that intersect the base cell
    # Calculate the volumes of the clipped cells and insert to the matrix
    volList =[]
    for i in range(intCells.GetNumberOfCells()):
        c = intCells.GetCell(i)
        cPts = c.GetPoints()
        volList.append(c.ComputeVolume(cPts.GetPoint(0),cPts.GetPoint(1),cPts.GetPoint(2),cPts.GetPoint(3)))
    volArr =  np.array(volList)
    # Calculate the volumes
    volCal = np.array([np.sum(volArr[idList == curId]) for curId in uniIDs])

    return uniIDs, volCal/np.sum(volCal)
Example #6
0
    def clip_box(dataset, bounds=None, invert=True, factor=0.35):
        """Clips a dataset by a bounding box defined by the bounds. If no bounds
        are given, a corner of the dataset bounds will be removed.

        Parameters
        ----------
        bounds : tuple(float)
            Length 6 iterable of floats: (xmin, xmax, ymin, ymax, zmin, zmax)

        invert : bool
            Flag on whether to flip/invert the clip

        factor : float, optional
            If bounds are not given this is the factor along each axis to
            extract the default box.

        """
        if bounds is None:
            def _get_quarter(dmin, dmax):
                """internal helper to get a section of the given range"""
                return dmax - ((dmax - dmin) * factor)
            xmin, xmax, ymin, ymax, zmin, zmax = dataset.bounds
            xmin = _get_quarter(xmin, xmax)
            ymin = _get_quarter(ymin, ymax)
            zmin = _get_quarter(zmin, zmax)
            bounds = [xmin, xmax, ymin, ymax, zmin, zmax]
        if isinstance(bounds, (float, int)):
            bounds = [bounds, bounds, bounds]
        if len(bounds) == 3:
            xmin, xmax, ymin, ymax, zmin, zmax = dataset.bounds
            bounds = (xmin,xmin+bounds[0], ymin,ymin+bounds[1], zmin,zmin+bounds[2])
        if not isinstance(bounds, collections.Iterable) or len(bounds) != 6:
            raise AssertionError('Bounds must be a length 6 iterable of floats')
        xmin, xmax, ymin, ymax, zmin, zmax = bounds
        alg = vtk.vtkBoxClipDataSet()
        alg.SetInputDataObject(dataset)
        alg.SetBoxClip(xmin, xmax, ymin, ymax, zmin, zmax)
        port = 0
        if invert:
            # invert the clip if needed
            port = 1
            alg.GenerateClippedOutputOn()
        alg.Update()
        return _get_output(alg, oport=port)
Example #7
0
def _calculateVolumeByBoxClip(vtkDataSet1,vtkDataSet2,iV):
    """
    Function to calculate the volumes of a cell intersecting a mesh.

    Uses a BoxClip filter to calculate the intersection, assumes the cell to
    be a voxel (=11) and aligned to the grid. This should work well for rectilinear
    and unstructured grids with all cells as voxels

    """

    # Triangulate polygon and calc normals
    baseC = vtkTools.dataset.getCell2vtp(vtkDataSet2,iV)
    # Extrct the cell by the bounds first, significant speed up...
    if vtkDataSet1.IsA('vtkRectilinearGrid'):
        # Use a faster implementation of the rectgrid extraction
        extCells = _extractRectGridByBounds(vtkDataSet1,baseC)
    else:
        extCells = vtkTools.extraction.extractDataSetByBounds(vtkDataSet1,baseC)
    # Define the box clip and clip the first mesh with the cell
    cb = baseC.GetBounds()
    boxClip = vtk.vtkBoxClipDataSet()
    boxClip.SetInputConnection(extCells.GetOutputPort())
    boxClip.SetBoxClip(cb[0],cb[1],cb[2],cb[3],cb[4],cb[5])
    boxClip.Update()
    # Get the intersect grid
    intCells = boxClip.GetOutput()
    idList = npsup.vtk_to_numpy(intCells.GetCellData().GetArray('id'))
    uniIDs = np.unique(idList)
    # Extract cells from the first mesh that intersect the base cell
    # Calculate the volumes of the clipped cells and insert to the matrix
    volList =[]
    for i in range(intCells.GetNumberOfCells()):
        c = intCells.GetCell(i)
        cPts = c.GetPoints()
        volList.append(c.ComputeVolume(cPts.GetPoint(0),cPts.GetPoint(1),cPts.GetPoint(2),cPts.GetPoint(3)))
    volArr =  np.array(volList)
    # Calculate the volumes
    volCal = np.array([np.sum(volArr[idList == curId]) for curId in uniIDs])

    return uniIDs, volCal/np.sum(volCal)
Example #8
0
    def add_mesh_clip_box(self,
                          mesh,
                          invert=False,
                          rotation_enabled=True,
                          widget_color=None,
                          outline_translation=True,
                          **kwargs):
        """Clip a mesh using a box widget.

        Add a mesh to the scene with a box widget that is used to clip
        the mesh interactively.

        The clipped mesh is saved to the ``.box_clipped_meshes`` attribute on
        the plotter.

        Parameters
        ----------
        mesh : pyvista.Common
            The input dataset to add to the scene and clip

        invert : bool
            Flag on whether to flip/invert the clip

        rotation_enabled : bool
            If ``False``, the box widget cannot be rotated and is strictly
            orthogonal to the cartesian axes.

        kwargs : dict
            All additional keyword arguments are passed to ``add_mesh`` to
            control how the mesh is displayed.

        """
        name = kwargs.get('name', str(hex(id(mesh))))
        rng = mesh.get_data_range(kwargs.get('scalars', None))
        kwargs.setdefault('clim', kwargs.pop('rng', rng))

        self.add_mesh(mesh.outline(), name=name + "outline", opacity=0.0)

        port = 1 if invert else 0

        alg = vtk.vtkBoxClipDataSet()
        alg.SetInputDataObject(mesh)
        alg.GenerateClippedOutputOn()

        if not hasattr(self, "box_clipped_meshes"):
            self.box_clipped_meshes = []
        box_clipped_mesh = pyvista.wrap(alg.GetOutput(port))
        self.box_clipped_meshes.append(box_clipped_mesh)

        def callback(planes):
            bounds = []
            for i in range(planes.GetNumberOfPlanes()):
                plane = planes.GetPlane(i)
                bounds.append(plane.GetNormal())
                bounds.append(plane.GetOrigin())

            alg.SetBoxClip(*bounds)
            alg.Update()
            box_clipped_mesh.shallow_copy(alg.GetOutput(port))

        self.add_box_widget(callback=callback,
                            bounds=mesh.bounds,
                            factor=1.25,
                            rotation_enabled=rotation_enabled,
                            use_planes=True,
                            color=widget_color,
                            outline_translation=outline_translation)

        actor = self.add_mesh(box_clipped_mesh, reset_camera=False, **kwargs)

        return actor