Example #1
0
    def _from_arrays(self, vertices, faces, deep=True, verts=False):
        """Set polygons and points from numpy arrays.

        Parameters
        ----------
        vertices : np.ndarray of dtype=np.float32 or np.float64
            Vertex array.  3D points.

        faces : np.ndarray of dtype=np.int64
            Face index array.  Faces can contain any number of points.

        verts : bool, optional
            Faces array is a vertex array.

        Examples
        --------
        >>> import numpy as np
        >>> import pyvista
        >>> vertices = np.array([[0, 0, 0],
        ...                      [1, 0, 0],
        ...                      [1, 1, 0],
        ...                      [0, 1, 0],
        ...                      [0.5, 0.5, 1]])
        >>> faces = np.hstack([[4, 0, 1, 2, 3],
        ...                    [3, 0, 1, 4],
        ...                    [3, 1, 2, 4]])  # one square and two triangles
        >>> surf = pyvista.PolyData(vertices, faces)

        """
        self.SetPoints(pyvista.vtk_points(vertices, deep=deep))
        if verts:
            self.SetVerts(CellArray(faces))
        else:
            self.SetPolys(CellArray(faces))
Example #2
0
    def _from_arrays(self, x, y, z):
        """Create VTK structured grid directly from numpy arrays.

        Parameters
        ----------
        x : np.ndarray
            Position of the points in x direction.

        y : np.ndarray
            Position of the points in y direction.

        z : np.ndarray
            Position of the points in z direction.

        """
        if not (x.shape == y.shape == z.shape):
            raise ValueError('Input point array shapes must match exactly')

        # make the output points the same precision as the input arrays
        points = np.empty((x.size, 3), x.dtype)
        points[:, 0] = x.ravel('F')
        points[:, 1] = y.ravel('F')
        points[:, 2] = z.ravel('F')

        # ensure that the inputs are 3D
        dim = list(x.shape)
        while len(dim) < 3:
            dim.append(1)

        # Create structured grid
        self.SetDimensions(dim)
        self.SetPoints(pyvista.vtk_points(points))
Example #3
0
 def points(self, points):
     """ set points without copying """
     if not isinstance(points, np.ndarray):
         raise TypeError('Points must be a numpy array')
     vtk_points = pyvista.vtk_points(points, False)
     self.SetPoints(vtk_points)
     self.GetPoints().Modified()
     self.Modified()
Example #4
0
 def points(self) -> pyvista_ndarray:
     """Return a pointer to the points as a numpy object."""
     _points = self.GetPoints()
     try:
         _points = _points.GetData()
     except AttributeError:
         # create an empty array
         vtk_points = pyvista.vtk_points(np.empty((0, 3)), False)
         self.SetPoints(vtk_points)
         _points = self.GetPoints().GetData()
     return pyvista_ndarray(_points, dataset=self)
Example #5
0
 def points(self, points):
     """Set points without copying."""
     if not isinstance(points, np.ndarray):
         raise TypeError('Points must be a numpy array')
     vtk_points = pyvista.vtk_points(points, False)
     pdata = self.GetPoints()
     if not pdata:
         self.SetPoints(vtk_points)
     else:
         pdata.SetData(vtk_points.GetData())
     self.GetPoints().Modified()
     self.Modified()
def Pyramid(points=None):
    """Create a pyramid defined by 5 points.

    Parameters
    ----------
    points : sequence, optional
        Points of the pyramid.  Points are ordered such that the first
        four points are the four counterclockwise points on the
        quadrilateral face, and the last point is the apex.

        Defaults to pyramid in example.

    Returns
    -------
    pyvista.UnstructuredGrid
        Unstructured grid containing a single pyramid cell.

    Examples
    --------
    >>> import pyvista
    >>> pointa = [1.0, 1.0, 0.0]
    >>> pointb = [-1.0, 1.0, 0.0]
    >>> pointc = [-1.0, -1.0, 0.0]
    >>> pointd = [1.0, -1.0, 0.0]
    >>> pointe = [0.0, 0.0, 1.608]
    >>> pyramid = pyvista.Pyramid([pointa, pointb, pointc, pointd, pointe])
    >>> pyramid.plot(show_edges=True, line_width=5)
    """
    if points is None:
        points = [[1.0, 1.0, 0.0], [-1.0, 1.0, 0.0], [-1.0, -1.0, 0.0],
                  [1.0, -1.0, 0.0], [0.0, 0.0, (4 - 2**0.5)**0.5]]

    if len(points) != 5:
        raise TypeError('Points must be given as length 5 np.ndarray or list')

    check_valid_vector(points[0], 'points[0]')
    check_valid_vector(points[1], 'points[1]')
    check_valid_vector(points[2], 'points[2]')
    check_valid_vector(points[3], 'points[3]')
    check_valid_vector(points[4], 'points[4]')

    pyramid = _vtk.vtkPyramid()
    pyramid.GetPointIds().SetId(0, 0)
    pyramid.GetPointIds().SetId(1, 1)
    pyramid.GetPointIds().SetId(2, 2)
    pyramid.GetPointIds().SetId(3, 3)
    pyramid.GetPointIds().SetId(4, 4)

    ug = _vtk.vtkUnstructuredGrid()
    ug.SetPoints(pyvista.vtk_points(np.array(points), False))
    ug.InsertNextCell(pyramid.GetCellType(), pyramid.GetPointIds())

    return pyvista.wrap(ug)
Example #7
0
def Pyramid(points):
    """Create a pyramid defined by 5 points.

    Parameters
    ----------
    points : np.ndarray or list
        Points of the pyramid.  Points are ordered such that the first
        four points are the four counterclockwise points on the
        quadrilateral face, and the last point is the apex.

    Returns
    -------
    pyramid : pyvista.UnstructuredGrid

    Examples
    --------
    >>> import pyvista
    >>> pointa = [1.0, 1.0, 1.0]
    >>> pointb = [-1.0, 1.0, 1.0]
    >>> pointc = [-1.0, -1.0, 1.0]
    >>> pointd = [1.0, -1.0, 1.0]
    >>> pointe = [0.0, 0.0, 0.0]
    >>> pyramid = pyvista.Pyramid([pointa, pointb, pointc, pointd, pointe])
    >>> pyramid.plot() # doctest:+SKIP
    """
    if len(points) != 5:
        raise TypeError('Points must be given as length 5 np.ndarray or list')

    check_valid_vector(points[0], 'points[0]')
    check_valid_vector(points[1], 'points[1]')
    check_valid_vector(points[2], 'points[2]')
    check_valid_vector(points[3], 'points[3]')
    check_valid_vector(points[4], 'points[4]')

    pyramid = _vtk.vtkPyramid()
    pyramid.GetPointIds().SetId(0, 0)
    pyramid.GetPointIds().SetId(1, 1)
    pyramid.GetPointIds().SetId(2, 2)
    pyramid.GetPointIds().SetId(3, 3)
    pyramid.GetPointIds().SetId(4, 4)

    ug = _vtk.vtkUnstructuredGrid()
    ug.SetPoints(pyvista.vtk_points(np.array(points), False))
    ug.InsertNextCell(pyramid.GetCellType(), pyramid.GetPointIds())

    return pyvista.wrap(ug)
Example #8
0
def Spline(points, n_points=None):
    """Create a spline from points.

    Parameters
    ----------
    points : np.ndarray
        Array of points to build a spline out of.  Array must be 3D
        and directionally ordered.

    n_points : int, optional
        Number of points to interpolate along the points array.

    Returns
    -------
    pyvista.PolyData
        Line mesh of spline.

    Examples
    --------
    Construct a spline.

    >>> import numpy as np
    >>> import pyvista as pv
    >>> theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
    >>> z = np.linspace(-2, 2, 100)
    >>> r = z**2 + 1
    >>> x = r * np.sin(theta)
    >>> y = r * np.cos(theta)
    >>> points = np.column_stack((x, y, z))
    >>> spline = pv.Spline(points, 1000)
    >>> spline.plot(render_lines_as_tubes=True, line_width=10, show_scalar_bar=False)

    """
    spline_function = _vtk.vtkParametricSpline()
    spline_function.SetPoints(pyvista.vtk_points(points, False))

    # get interpolation density
    u_res = n_points
    if u_res is None:
        u_res = points.shape[0]

    u_res -= 1
    spline = surface_from_para(spline_function, u_res)
    return spline.compute_arc_length()
def polygon_to_vtk(polygon, topo_points):
    """Converts a polygon shape to a pyvista.PolyData object.
    This assumes the points are ordered.
    """
    pts = np.array(polygon.points)
    pts = np.c_[pts, np.zeros(pts.shape[0])]
    pts = _fix_to_topography(topo_points, pts)
    cells = vtk.vtkCellArray()
    for i in range(pts.shape[0]-1):
        cell = _makeLineCell(i, i+1)
        cells.InsertNextCell(cell)
    # Add in last connection to make complete polygon
    cell = _makeLineCell(i, 0)
    cells.InsertNextCell(cell)
    # Build the output
    pdo = vtk.vtkPolyData()
    pdo.SetPoints(pyvista.vtk_points(pts))
    pdo.SetLines(cells)
    return pyvista.wrap(pdo)
Example #10
0
    def points(self, points: np.ndarray):
        """Set points without copying."""
        if isinstance(points, pyvista_ndarray):
            # simply set the underlying data
            if points.VTKObject is not None:
                self.GetPoints().SetData(points.VTKObject)
                self.GetPoints().Modified()
                self.Modified()
                return

        # otherwise, wrap and use the array
        if not isinstance(points, np.ndarray):
            raise TypeError('Points must be a numpy array')
        vtk_points = pyvista.vtk_points(points, False)
        pdata = self.GetPoints()
        if not pdata:
            self.SetPoints(vtk_points)
        else:
            pdata.SetData(vtk_points.GetData())
        self.GetPoints().Modified()
        self.Modified()
Example #11
0
def create_polyhedron(polyhedron_data):
    """
    create the vtk grid containing all points and faces
    """
    points = pv.vtk_points(np.array(polyhedron_data.vertex_list))

    polyhedron_faces = polyhedron_data.polyhedron_faces

    polyhedron_faces_id_list = vtk.vtkIdList()
    # Number faces that make up the cell.
    polyhedron_faces_id_list.InsertNextId(len(polyhedron_faces))
    for face in polyhedron_faces:
        # Number of points in the face == numberOfFaceVertices
        polyhedron_faces_id_list.InsertNextId(len(face))
        # Insert the pointIds for that face.
        [polyhedron_faces_id_list.InsertNextId(i) for i in face]

    polyhedron_grid = vtk.vtkUnstructuredGrid()
    polyhedron_grid.InsertNextCell(
        vtk.VTK_POLYHEDRON, polyhedron_faces_id_list)
    polyhedron_grid.SetPoints(points)

    return polyhedron_grid
Example #12
0
    def _from_arrays(self, offset, cells, cell_type, points, deep=True):
        """Create VTK unstructured grid from numpy arrays.

        Parameters
        ----------
        offset : np.ndarray dtype=np.int64
            Array indicating the start location of each cell in the cells
            array.  Set to ``None`` when using VTK 9+.

        cells : np.ndarray dtype=np.int64
            Array of cells.  Each cell contains the number of points in the
            cell and the node numbers of the cell.

        cell_type : np.uint8
            Cell types of each cell.  Each cell type numbers can be found from
            vtk documentation.  See example below.

        points : np.ndarray
            Numpy array containing point locations.

        Examples
        --------
        >>> import numpy
        >>> import vtk
        >>> import pyvista
        >>> offset = np.array([0, 9])
        >>> cells = np.array([8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15])
        >>> cell_type = np.array([vtk.VTK_HEXAHEDRON, vtk.VTK_HEXAHEDRON], np.int8)

        >>> cell1 = np.array([[0, 0, 0],
        ...                   [1, 0, 0],
        ...                   [1, 1, 0],
        ...                   [0, 1, 0],
        ...                   [0, 0, 1],
        ...                   [1, 0, 1],
        ...                   [1, 1, 1],
        ...                   [0, 1, 1]])

        >>> cell2 = np.array([[0, 0, 2],
        ...                   [1, 0, 2],
        ...                   [1, 1, 2],
        ...                   [0, 1, 2],
        ...                   [0, 0, 3],
        ...                   [1, 0, 3],
        ...                   [1, 1, 3],
        ...                   [0, 1, 3]])

        >>> points = np.vstack((cell1, cell2))

        >>> grid = pyvista.UnstructuredGrid(offset, cells, cell_type, points)

        """
        # Convert to vtk arrays
        vtkcells = CellArray(cells, cell_type.size, deep)
        if cell_type.dtype != np.uint8:
            cell_type = cell_type.astype(np.uint8)
        cell_type = numpy_to_vtk(cell_type, deep=deep)

        # Convert points to vtkPoints object
        points = pyvista.vtk_points(points, deep=deep)
        self.SetPoints(points)

        # vtk9 does not require an offset array
        if VTK9:
            if offset is not None:
                warnings.warn('VTK 9 no longer accepts an offset array',
                              stacklevel=3)
            self.SetCells(cell_type, vtkcells)
        else:
            self.SetCells(cell_type, numpy_to_idarr(offset), vtkcells)
Example #13
0
    def _from_arrays(self, offset, cells, cell_type, points, deep=True):
        """Create VTK unstructured grid from numpy arrays.

        Parameters
        ----------
        offset : np.ndarray dtype=np.int64
            Array indicating the start location of each cell in the cells
            array.

        cells : np.ndarray dtype=np.int64
            Array of cells.  Each cell contains the number of points in the
            cell and the node numbers of the cell.

        cell_type : np.uint8
            Cell types of each cell.  Each cell type numbers can be found from
            vtk documentation.  See example below.

        points : np.ndarray
            Numpy array containing point locations.

        Examples
        --------
        >>> import numpy
        >>> import vtk
        >>> import pyvista
        >>> offset = np.array([0, 9])
        >>> cells = np.array([8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15])
        >>> cell_type = np.array([vtk.VTK_HEXAHEDRON, vtk.VTK_HEXAHEDRON], np.int8)

        >>> cell1 = np.array([[0, 0, 0],
        ...                   [1, 0, 0],
        ...                   [1, 1, 0],
        ...                   [0, 1, 0],
        ...                   [0, 0, 1],
        ...                   [1, 0, 1],
        ...                   [1, 1, 1],
        ...                   [0, 1, 1]])

        >>> cell2 = np.array([[0, 0, 2],
        ...                   [1, 0, 2],
        ...                   [1, 1, 2],
        ...                   [0, 1, 2],
        ...                   [0, 0, 3],
        ...                   [1, 0, 3],
        ...                   [1, 1, 3],
        ...                   [0, 1, 3]])

        >>> points = np.vstack((cell1, cell2))

        >>> grid = pyvista.UnstructuredGrid(offset, cells, cell_type, points)

        """
        if offset.dtype != pyvista.ID_TYPE:
            offset = offset.astype(pyvista.ID_TYPE)

        if cells.dtype != pyvista.ID_TYPE:
            cells = cells.astype(pyvista.ID_TYPE)

        if not cells.flags['C_CONTIGUOUS']:
            cells = np.ascontiguousarray(cells)

        # if cells.ndim != 1:
            # cells = cells.ravel()

        if cell_type.dtype != np.uint8:
            cell_type = cell_type.astype(np.uint8)

        # Get number of cells
        ncells = cell_type.size

        # Convert to vtk arrays
        cell_type = numpy_to_vtk(cell_type, deep=deep)
        offset = numpy_to_vtkIdTypeArray(offset, deep=deep)

        vtkcells = vtk.vtkCellArray()
        vtkcells.SetCells(ncells, numpy_to_vtkIdTypeArray(cells.ravel(), deep=deep))

        # Convert points to vtkPoints object
        points = pyvista.vtk_points(points, deep=deep)

        # Create unstructured grid
        self.SetPoints(points)
        self.SetCells(cell_type, offset, vtkcells)
Example #14
0
    def __init__(self,
                 var_inp=None,
                 faces=None,
                 n_faces=None,
                 lines=None,
                 n_lines=None,
                 deep=False) -> None:
        """Initialize the polydata."""
        local_parms = locals()
        super().__init__()

        # allow empty input
        if var_inp is None:
            return

        # filename
        opt_kwarg = ['faces', 'n_faces', 'lines', 'n_lines']
        if isinstance(var_inp, (str, pathlib.Path)):
            for kwarg in opt_kwarg:
                if local_parms[kwarg]:
                    raise ValueError(
                        'No other arguments should be set when first '
                        'parameter is a string')
            self._from_file(var_inp)  # is filename

            # When loading files with just point arrays, create and
            # set the polydata vertices
            if self.n_points > 0 and self.n_cells == 0:
                verts = self._make_vertex_cells(self.n_points)
                self.verts = CellArray(verts, self.n_points, deep)

            return

        # PolyData-like
        if isinstance(var_inp, _vtk.vtkPolyData):
            for kwarg in opt_kwarg:
                if local_parms[kwarg]:
                    raise ValueError(
                        'No other arguments should be set when first '
                        'parameter is a PolyData')
            if deep:
                self.deep_copy(var_inp)
            else:
                self.shallow_copy(var_inp)
            return

        # First parameter is points
        if isinstance(var_inp, (np.ndarray, list)):
            self.SetPoints(pyvista.vtk_points(var_inp, deep=deep))
        else:
            msg = f"""
                Invalid Input type:

                Expected first argument to be either a:
                - vtk.PolyData
                - pyvista.PolyData
                - numeric numpy.ndarray (1 or 2 dimensions)
                - List (flat or nested with 3 points per vertex)

                Instead got: {type(var_inp)}"""
            raise TypeError(dedent(msg.strip('\n')))

        # At this point, points have been setup, add faces and/or lines
        if faces is None and lines is None:
            # one cell per point (point cloud case)
            verts = self._make_vertex_cells(self.n_points)
            self.verts = CellArray(verts, self.n_points, deep)

        elif faces is not None:
            # here we use CellArray since we must specify deep and n_faces
            self.faces = CellArray(faces, n_faces, deep)

        # can always set lines
        if lines is not None:
            # here we use CellArray since we must specify deep and n_lines
            self.lines = CellArray(lines, n_lines, deep)
Example #15
0
def KochanekSpline(points,
                   tension=None,
                   bias=None,
                   continuity=None,
                   n_points=None):
    """Create a Kochanek spline from points.

    Parameters
    ----------
    points : sequence
        Array of points to build a Kochanek spline out of.  Array must
        be 3D and directionally ordered.

    tension : sequence, optional
        Changes the length of the tangent vector.  Defaults to ``[0.0,
        0.0, 0.0]``.

    bias : sequence, optional
        Primarily changes the direction of the tangent vector.
        Defaults to ``[0.0, 0.0, 0.0]``.

    continuity : sequence, optional
        Changes the sharpness in change between tangents.  Defaults to
        ``[0.0, 0.0, 0.0]``.

    n_points : int, optional
        Number of points on the spline.  Defaults to the number of
        points in ``points``.

    Returns
    -------
    pyvista.PolyData
        Kochanek spline.

    Examples
    --------
    Construct a Kochanek spline.

    >>> import numpy as np
    >>> import pyvista as pv
    >>> theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
    >>> z = np.linspace(-2, 2, 100)
    >>> r = z ** 2 + 1
    >>> x = r * np.sin(theta)
    >>> y = r * np.cos(theta)
    >>> points = np.column_stack((x, y, z))
    >>> kochanek_spline = pv.KochanekSpline(points, n_points=6)
    >>> kochanek_spline.plot(line_width=4, color="k")

    See :ref:`create_kochanek_spline_example` for an additional example.

    """
    if tension is None:
        tension = np.array([0.0, 0.0, 0.0])
    check_valid_vector(tension, "tension")
    if not np.all(np.abs(tension) <= 1.0):
        raise ValueError(
            "The absolute value of all values of the tension array elements must be <= 1.0 "
        )

    if bias is None:
        bias = np.array([0.0, 0.0, 0.0])
    check_valid_vector(bias, "bias")
    if not np.all(np.abs(bias) <= 1.0):
        raise ValueError(
            "The absolute value of all values of the bias array elements must be <= 1.0 "
        )

    if continuity is None:
        continuity = np.array([0.0, 0.0, 0.0])
    check_valid_vector(continuity, "continuity")
    if not np.all(np.abs(continuity) <= 1.0):
        raise ValueError(
            "The absolute value of all values continuity array elements must be <= 1.0 "
        )

    spline_function = _vtk.vtkParametricSpline()
    spline_function.SetPoints(pyvista.vtk_points(points, False))

    # set Kochanek spline for each direction
    xspline = _vtk.vtkKochanekSpline()
    yspline = _vtk.vtkKochanekSpline()
    zspline = _vtk.vtkKochanekSpline()
    xspline.SetDefaultBias(bias[0])
    yspline.SetDefaultBias(bias[1])
    zspline.SetDefaultBias(bias[2])
    xspline.SetDefaultTension(tension[0])
    yspline.SetDefaultTension(tension[1])
    zspline.SetDefaultTension(tension[2])
    xspline.SetDefaultContinuity(continuity[0])
    yspline.SetDefaultContinuity(continuity[1])
    zspline.SetDefaultContinuity(continuity[2])
    spline_function.SetXSpline(xspline)
    spline_function.SetYSpline(yspline)
    spline_function.SetZSpline(zspline)

    # get interpolation density
    u_res = n_points
    if u_res is None:
        u_res = points.shape[0]

    u_res -= 1
    spline = surface_from_para(spline_function, u_res)
    return spline.compute_arc_length()