pyvista.DataSet.find_closest_cell#

DataSet.find_closest_cell(
point: VectorLike[float] | MatrixLike[float],
return_closest_point: bool = False,
) int | NumpyArray[int] | tuple[int | NumpyArray[int], NumpyArray[int]][source]#

Find index of closest cell in this mesh to the given point.

Parameters:
pointVector | Matrix

Coordinates of point to query (length 3) or a numpy.ndarray of n points with shape (n, 3).

return_closest_pointbool, default: False

If True, the closest point within a mesh cell to that point is returned. This is not necessarily the closest nodal point on the mesh. Default is False.

Returns:
int or numpy.ndarray

Index or indices of the cell in this mesh that is/are closest to the given point(s).

Changed in version 0.35.0: Inputs of shape (1, 3) now return a numpy.ndarray of shape (1,).

numpy.ndarray

Point or points inside a cell of the mesh that is/are closest to the given point(s). Only returned if return_closest_point=True.

Changed in version 0.35.0: Inputs of shape (1, 3) now return a numpy.ndarray of the same shape.

Warning

This method may still return a valid cell index even if the point contains a value like numpy.inf or numpy.nan.

Examples

Find nearest cell on a sphere centered on the origin to the point [0.1, 0.2, 0.3].

>>> import pyvista as pv
>>> mesh = pv.Sphere()
>>> point = [0.1, 0.2, 0.3]
>>> index = mesh.find_closest_cell(point)
>>> index
338

Make sure that this cell indeed is the closest to [0.1, 0.2, 0.3].

>>> import numpy as np
>>> cell_centers = mesh.cell_centers()
>>> relative_position = cell_centers.points - point
>>> distance = np.linalg.norm(relative_position, axis=1)
>>> np.argmin(distance)
np.int64(338)

Find the nearest cells to several random points that are centered on the origin.

>>> points = 2 * np.random.default_rng().random((5000, 3)) - 1
>>> indices = mesh.find_closest_cell(points)
>>> indices.shape
(5000,)

For the closest cell, find the point inside the cell that is closest to the supplied point. The rectangle is a unit square with 1 cell and 4 nodal points at the corners in the plane with z normal and z=0. The closest point inside the cell is not usually at a nodal point.

>>> unit_square = pv.Rectangle()
>>> index, closest_point = unit_square.find_closest_cell(
...     [0.25, 0.25, 0.5], return_closest_point=True
... )
>>> closest_point
array([0.25, 0.25, 0.  ])

But, the closest point can be a nodal point, although the index of that point is not returned. If the closest nodal point by index is desired, see DataSet.find_closest_point().

>>> index, closest_point = unit_square.find_closest_cell(
...     [1.0, 1.0, 0.5], return_closest_point=True
... )
>>> closest_point
array([1., 1., 0.])