Debian Codegraph @

pyvista/core/utilities/points.py

raw
1 """Points related utilities."""
2
3 from __future__ import annotations
4
5 from typing import TYPE_CHECKING
6 from typing import Literal
7 from typing import overload
8
9 import numpy as np
10
11 import pyvista as pv
12 from pyvista import _vtk
13 from pyvista._deprecate_positional_args import _deprecate_positional_args
14 from pyvista._warn_external import warn_external
15 from pyvista.core import _validation
16
17 if TYPE_CHECKING:
18 from pyvista import PolyData
19 from pyvista.core._typing_core import MatrixLike
20 from pyvista.core._typing_core import NumpyArray
21 from pyvista.core._typing_core import VectorLike
22
23
24 @_deprecate_positional_args(allowed=['points'])
25 def vtk_points( # noqa: PLR0917
26 points: VectorLike[float] | MatrixLike[float],
27 deep: bool = True, # noqa: FBT001, FBT002
28 force_float: bool = False, # noqa: FBT001, FBT002
29 allow_empty: bool = True, # noqa: FBT001, FBT002
30 ) -> _vtk.vtkPoints:
31 """Convert numpy array or array-like to a :vtk:`vtkPoints` object.
32
33 Parameters
34 ----------
35 points : numpy.ndarray or sequence
36 Points to convert. Should be 1 or 2 dimensional. Accepts a
37 single point or several points.
38
39 deep : bool, default: True
40 Perform a deep copy of the array. Only applicable if
41 ``points`` is a :class:`numpy.ndarray`.
42
43 force_float : bool, default: False
44 Casts the datatype to ``float32`` if points datatype is
45 non-float. Set this to ``False`` to allow non-float types,
46 though this may lead to truncation of intermediate floats
47 when transforming datasets.
48
49 allow_empty : bool, default: True
50 Allow ``points`` to be an empty array. If ``False``, points
51 must be strictly one- or two-dimensional.
52
53 .. versionadded:: 0.45
54
55 Returns
56 -------
57 :vtk:`vtkPoints`
58 The :vtk:`vtkPoints` object.
59
60 Examples
61 --------
62 >>> import pyvista as pv
63 >>> import numpy as np
64 >>> points = np.random.default_rng().random((10, 3))
65 >>> vpoints = pv.vtk_points(points)
66 >>> vpoints # doctest:+SKIP
67 (vtkmodules.vtkCommonCore.vtkPoints)0x7f0c2e26af40
68
69 """
70 try:
71 points_ = _validation.validate_arrayNx3(points, name='points')
72 except ValueError as e:
73 if 'points has shape (0,)' in repr(e) and allow_empty:
74 points_ = np.empty(shape=(0, 3), dtype=np.array(points).dtype)
75 else:
76 raise
77
78 if force_float and not np.issubdtype(points_.dtype, np.floating):
79 warn_external(
80 'Points is not a float type. This can cause issues when '
81 'transforming or applying filters. Casting to '
82 '``np.float32``. Disable this by passing '
83 '``force_float=False``.',
84 )
85 points_ = points_.astype(np.float32)
86
87 # use the underlying vtk data if present to avoid memory leaks
88 if not deep and isinstance(points_, pv.pyvista_ndarray) and points_.VTKObject is not None:
89 vtk_object = points_.VTKObject
90
91 # we can only use the underlying data if `points` is not a slice of
92 # the VTK data object
93 size = (
94 vtk_object.GetSize()
95 if pv.vtk_version_info < (9, 6, 99) # < (9, 7, 0)
96 else vtk_object.GetCapacity()
97 )
98 if size == points_.size:
99 vtkpts = _vtk.vtkPoints()
100 vtkpts.SetData(points_.VTKObject)
101 return vtkpts
102 else:
103 deep = True
104
105 # points must be contiguous
106 points_ = np.require(points_, requirements=['C'])
107 vtkpts = _vtk.vtkPoints()
108 vtk_arr = _vtk.numpy_to_vtk(points_, deep=deep)
109 vtkpts.SetData(vtk_arr)
110
111 return vtkpts
112
113
114 def line_segments_from_points(points: VectorLike[float] | MatrixLike[float]) -> PolyData:
115 """Generate non-connected line segments from points.
116
117 Assumes points are ordered as line segments and an even number of
118 points.
119
120 Parameters
121 ----------
122 points : array_like[float]
123 Points representing line segments. An even number must be
124 given as every two vertices represent a single line
125 segment. For example, two line segments would be represented
126 as ``np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]])``.
127
128 Returns
129 -------
130 pyvista.PolyData
131 PolyData with lines and cells.
132
133 Examples
134 --------
135 This example plots two line segments at right angles to each other.
136
137 >>> import pyvista as pv
138 >>> import numpy as np
139 >>> points = np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]])
140 >>> lines = pv.line_segments_from_points(points)
141 >>> lines.plot()
142
143 See :ref:`graph_network_example` for more examples using this function.
144
145 """
146 if len(points) % 2 != 0:
147 msg = 'An even number of points must be given to define each segment.'
148 raise ValueError(msg)
149 # Assuming ordered points, create array defining line order
150 n_points = len(points)
151 n_lines = n_points // 2
152 lines = np.c_[
153 2 * np.ones(n_lines, np.int_),
154 np.arange(0, n_points - 1, step=2),
155 np.arange(1, n_points + 1, step=2),
156 ]
157 poly = pv.PolyData()
158 poly.points = points
159 poly.lines = lines
160 return poly
161
162
163 @_deprecate_positional_args(allowed=['points'])
164 def lines_from_points(
165 points: VectorLike[float] | MatrixLike[float],
166 close: bool = False, # noqa: FBT001, FBT002
167 ) -> PolyData:
168 """Make a connected line set given an array of points.
169
170 Parameters
171 ----------
172 points : array_like[float]
173 Points representing the vertices of the connected
174 segments. For example, two line segments would be represented
175 as ``np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0]])``.
176
177 close : bool, default: False
178 If ``True``, close the line segments into a loop.
179
180 Returns
181 -------
182 pyvista.PolyData
183 PolyData with lines and cells.
184
185 Examples
186 --------
187 >>> import numpy as np
188 >>> import pyvista as pv
189 >>> points = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0]])
190 >>> poly = pv.lines_from_points(points)
191 >>> poly.plot(line_width=5)
192
193 See :ref:`lorenz_attractor_example` for more examples using this function.
194
195 """
196 poly = pv.PolyData()
197 poly.points = points
198 cells = np.full((len(points) - 1, 3), 2, dtype=np.int_)
199 cells[:, 1] = np.arange(0, len(points) - 1, dtype=np.int_)
200 cells[:, 2] = np.arange(1, len(points), dtype=np.int_)
201 if close:
202 cells = np.append(cells, [[2, len(points) - 1, 0]], axis=0)
203 poly.lines = cells
204 return poly
205
206
207 @_deprecate_positional_args(allowed=['points'])
208 def fit_plane_to_points( # noqa: PLR0917
209 points: MatrixLike[float],
210 return_meta: bool = False, # noqa: FBT001, FBT002
211 resolution: int = 10,
212 init_normal: VectorLike[float] | None = None,
213 ) -> PolyData | tuple[PolyData, float, NumpyArray[float]]:
214 """Fit a plane to points using its :func:`principal_axes`.
215
216 The plane is automatically sized and oriented to fit the extents of
217 the points.
218
219 .. versionchanged:: 0.42.0
220 The generated plane is now sized and oriented to match the points.
221
222 .. versionchanged:: 0.42.0
223 The center of the plane (returned if ``return_meta=True``) is now
224 computed as the center of the generated plane mesh. In previous
225 versions, the center of the input points was returned.
226
227 .. versionchanged:: 0.45.0
228 The internal method used for fitting the plane has changed. Previously, singular
229 value decomposition (SVD) was used, but eigenvectors are now used instead.
230 See warning below.
231
232 .. warning::
233 The sign of the plane's normal vector prior to version 0.45 may differ
234 from the latest version. This may impact methods which rely on the plane's
235 direction. Use ``init_normal`` to control the sign explicitly.
236
237 Parameters
238 ----------
239 points : array_like[float]
240 Size ``[N x 3]`` sequence of points to fit a plane through.
241
242 return_meta : bool, default: False
243 If ``True``, also returns the center and normal of the
244 generated plane.
245
246 resolution : int, default: 10
247 Number of points on the plane mesh along its edges. Specify two numbers to
248 set the resolution along the plane's long and short edge (respectively) or
249 a single number to set both edges to have the same resolution.
250
251 .. versionadded:: 0.45.0
252
253 init_normal : VectorLike[float] | str, optional
254 Flip the normal of the plane such that it best aligns with this vector. Can be
255 a vector or string specifying the axis by name (e.g. ``'x'`` or ``'-x'``, etc.).
256
257 .. versionadded:: 0.45.0
258
259 Returns
260 -------
261 pyvista.PolyData
262 Plane mesh.
263
264 pyvista.pyvista_ndarray
265 Plane center if ``return_meta=True``.
266
267 pyvista.pyvista_ndarray
268 Plane normal if ``return_meta=True``.
269
270 See Also
271 --------
272 fit_line_to_points
273 Fit a line using the first principal axis of the points.
274
275 principal_axes
276 Compute axes vectors which best fit a set of points.
277
278 Examples
279 --------
280 Fit a plane to a random point cloud.
281
282 >>> import pyvista as pv
283 >>> import numpy as np
284 >>> from pyvista import examples
285 >>>
286 >>> rng = np.random.default_rng(seed=0)
287 >>> cloud = rng.random((10, 3))
288 >>> cloud[:, 2] *= 0.1
289 >>>
290 >>> plane = pv.fit_plane_to_points(cloud)
291
292 Plot the point cloud and fitted plane.
293
294 >>> pl = pv.Plotter()
295 >>> _ = pl.add_mesh(plane, style='wireframe', line_width=4)
296 >>> _ = pl.add_points(
297 ... cloud,
298 ... render_points_as_spheres=True,
299 ... color='r',
300 ... point_size=30,
301 ... )
302 >>> pl.show()
303
304 Fit a plane to a mesh and return its metadata. Set the plane resolution to 1
305 so that the plane has no internal points or edges.
306
307 >>> mesh = examples.download_shark()
308 >>> plane, center, normal = pv.fit_plane_to_points(
309 ... mesh.points, return_meta=True, resolution=1
310 ... )
311
312 Plot the mesh and fitted plane.
313
314 >>> pl = pv.Plotter()
315 >>> _ = pl.add_mesh(plane, show_edges=True, opacity=0.25)
316 >>> _ = pl.add_mesh(mesh, color='gray')
317 >>> pl.camera_position = pv.CameraPosition(
318 ... position=(-117, 76, 235),
319 ... focal_point=(1.69, -1.38, 0),
320 ... viewup=(0.189, 0.957, -0.22),
321 ... )
322 >>> pl.show()
323
324 Use the metadata with :meth:`pyvista.DataObjectFilters.clip` to split the mesh into
325 two.
326
327 >>> first_half, second_half = mesh.clip(
328 ... origin=center, normal=normal, return_clipped=True
329 ... )
330
331 Plot the two halves of the clipped mesh.
332
333 >>> pl = pv.Plotter()
334 >>> _ = pl.add_mesh(first_half, color='red')
335 >>> _ = pl.add_mesh(second_half, color='blue')
336 >>> pl.camera_position = pv.CameraPosition(
337 ... position=(-143, 43, 40),
338 ... focal_point=(-8.7, -11, -14),
339 ... viewup=(0.25, 0.92, -0.29),
340 ... )
341 >>> pl.show()
342
343 Note that it is pointing in the positive z-direction.
344
345 >>> normal # doctest:+SKIP
346 pyvista_ndarray([0.0, 0.0, 1.0], dtype=float32)
347
348 Use ``init_normal`` to flip the sign and make it negative instead.
349
350 >>> _, _, normal = pv.fit_plane_to_points(
351 ... mesh.points, return_meta=True, init_normal='-z'
352 ... )
353 >>> normal # doctest:+SKIP
354 pyvista_ndarray([0.0, 0.0, -1.0], dtype=float32)
355
356 """
357 valid_resolution = _validation.validate_array(
358 resolution,
359 must_have_shape=[(), (2,)],
360 must_be_integer=True,
361 broadcast_to=(2,),
362 dtype_out=int,
363 )
364 i_resolution, j_resolution = valid_resolution
365
366 # Align points to the xyz-axes
367 aligned, matrix = pv.PolyData(points).align_xyz(
368 return_matrix=True, axis_2_direction=init_normal
369 )
370
371 # Fit plane to xyz-aligned mesh
372 i_size, j_size, _ = aligned.bounds_size
373 plane = pv.Plane(
374 i_size=i_size,
375 j_size=j_size,
376 i_resolution=i_resolution,
377 j_resolution=j_resolution,
378 )
379
380 # Transform plane back to input points positioning
381 inverse_matrix = pv.Transform(matrix).inverse_matrix
382 plane.transform(inverse_matrix, inplace=True)
383
384 if return_meta:
385 # Compute center and normal from the plane's points and normals
386 center = np.mean(plane.points, axis=0)
387 normal = np.mean(plane.point_normals, axis=0)
388 return plane, center, normal
389 return plane
390
391
392 def fit_line_to_points(
393 points: MatrixLike[float],
394 *,
395 resolution: int = 1,
396 init_direction: VectorLike[float] | None = None,
397 return_meta: bool = False,
398 ) -> PolyData | tuple[PolyData, float, NumpyArray[float]]:
399 """Fit a line to points using its :func:`principal_axes`.
400
401 The line is automatically sized and oriented to fit the extents of
402 the points.
403
404 .. versionadded:: 0.45.0
405
406 Parameters
407 ----------
408 points : MatrixLike[float]
409 Size ``[N x 3]`` array of points to fit a line through.
410
411 resolution : int, default: 1
412 Number of pieces to divide the line into.
413
414 init_direction : VectorLike[float], optional
415 Flip the direction of the line's points such that it best aligns with this
416 vector. Can be a vector or string specifying the axis by name (e.g. ``'x'``
417 or ``'-x'``, etc.).
418
419 return_meta : bool, default: False
420 If ``True``, also returns the length (magnitude) and direction of the line.
421
422 See Also
423 --------
424 fit_plane_to_points
425 Fit a plane using the first two principal axes of the points.
426
427 principal_axes
428 Compute axes vectors which best fit a set of points.
429
430 Returns
431 -------
432 pyvista.PolyData
433 Line mesh.
434
435 float
436 Line length if ``return_meta=True``.
437
438 numpy.ndarray
439 Line direction (unit vector) if ``return_meta=True``.
440
441 Examples
442 --------
443 Download a point cloud. The points trace a path along topographical surface.
444
445 >>> import pyvista as pv
446 >>> from pyvista import examples
447 >>> mesh = examples.download_gpr_path()
448
449 Fit a line to the points and plot the result. The line of best fit is colored red.
450
451 >>> line = pv.fit_line_to_points(mesh.points)
452
453 >>> pl = pv.Plotter()
454 >>> _ = pl.add_mesh(mesh, color='black', line_width=10)
455 >>> _ = pl.add_mesh(line, color='red', line_width=5)
456 >>> pl.show()
457
458 Fit a line to a mesh and return the metadata.
459
460 >>> mesh = examples.download_human()
461 >>> line, length, direction = pv.fit_line_to_points(
462 ... mesh.points, return_meta=True
463 ... )
464
465 Show the length of the line.
466
467 >>> length
468 167.6145
469
470 Plot the line as an arrow to show its direction.
471
472 >>> arrow = pv.Arrow(
473 ... start=line.points[0],
474 ... direction=direction,
475 ... scale=length,
476 ... tip_length=0.2,
477 ... tip_radius=0.04,
478 ... shaft_radius=0.01,
479 ... )
480
481 >>> pl = pv.Plotter()
482 >>> _ = pl.add_mesh(mesh, opacity=0.5)
483 >>> _ = pl.add_mesh(arrow, color='red')
484 >>> pl.show()
485
486 Set ``init_direction`` to the positive z-axis to flip the line's direction.
487
488 >>> mesh = examples.download_human()
489 >>> line, length, direction = pv.fit_line_to_points(
490 ... mesh.points, init_direction='z', return_meta=True
491 ... )
492
493 Plot the results again with an arrow.
494
495 >>> arrow = pv.Arrow(
496 ... start=line.points[0],
497 ... direction=direction,
498 ... scale=length,
499 ... tip_length=0.2,
500 ... tip_radius=0.04,
501 ... shaft_radius=0.01,
502 ... )
503
504 >>> pl = pv.Plotter()
505 >>> _ = pl.add_mesh(mesh, opacity=0.5)
506 >>> _ = pl.add_mesh(arrow, color='red')
507 >>> pl.show()
508
509 """
510 # Align points to the xyz-axes
511 aligned, matrix = pv.PolyData(points).align_xyz(
512 axis_0_direction=init_direction, return_matrix=True
513 )
514
515 # Fit line to xyz-aligned mesh
516 point_a = (aligned.bounds.x_min, 0, 0)
517 point_b = (aligned.bounds.x_max, 0, 0)
518 line_mesh = pv.LineSource(point_a, point_b, resolution=resolution).output
519
520 # Transform line back to input points positioning
521 inverse_matrix = pv.Transform(matrix).inverse_matrix
522 line_mesh.transform(inverse_matrix, inplace=True)
523
524 if return_meta:
525 return line_mesh, line_mesh.length, matrix[0, :3]
526 return line_mesh
527
528
529 def make_tri_mesh(points: NumpyArray[float], faces: NumpyArray[int]) -> PolyData:
530 """Construct a ``pyvista.PolyData`` mesh using points and faces arrays.
531
532 Construct a mesh from an Nx3 array of points and an Mx3 array of
533 triangle indices, resulting in a mesh with N vertices and M
534 triangles. This function does not require the standard VTK
535 "padding" column and simplifies mesh creation.
536
537 Parameters
538 ----------
539 points : np.ndarray
540 Array of points with shape ``(N, 3)`` storing the vertices of the
541 triangle mesh.
542
543 faces : np.ndarray
544 Array of indices with shape ``(M, 3)`` containing the triangle
545 indices.
546
547 Returns
548 -------
549 pyvista.PolyData
550 PolyData instance containing the triangle mesh.
551
552 Examples
553 --------
554 This example discretizes the unit square into a triangle mesh with
555 nine vertices and eight faces.
556
557 >>> import numpy as np
558 >>> import pyvista as pv
559 >>> points = np.array(
560 ... [
561 ... [0, 0, 0],
562 ... [0.5, 0, 0],
563 ... [1, 0, 0],
564 ... [0, 0.5, 0],
565 ... [0.5, 0.5, 0],
566 ... [1, 0.5, 0],
567 ... [0, 1, 0],
568 ... [0.5, 1, 0],
569 ... [1, 1, 0],
570 ... ]
571 ... )
572 >>> faces = np.array(
573 ... [
574 ... [0, 1, 4],
575 ... [4, 7, 6],
576 ... [2, 5, 4],
577 ... [4, 5, 8],
578 ... [0, 4, 3],
579 ... [3, 4, 6],
580 ... [1, 2, 4],
581 ... [4, 8, 7],
582 ... ]
583 ... )
584 >>> tri_mesh = pv.make_tri_mesh(points, faces)
585 >>> tri_mesh.plot(show_edges=True, line_width=5)
586
587 """
588 if points.shape[1] != 3:
589 msg = 'Points array should have shape (N, 3).'
590 raise ValueError(msg)
591 if faces.ndim != 2 or faces.shape[1] != 3:
592 msg = 'Face array should have shape (M, 3).'
593 raise ValueError(msg)
594 cells = np.empty((faces.shape[0], 4), dtype=faces.dtype)
595 cells[:, 0] = 3
596 cells[:, 1:] = faces
597 return pv.PolyData(points, cells)
598
599
600 def vector_poly_data(
601 orig: VectorLike[float] | MatrixLike[float], vec: VectorLike[float] | MatrixLike[float]
602 ) -> PolyData:
603 """Create a pyvista.PolyData object composed of vectors.
604
605 Parameters
606 ----------
607 orig : array_like[float]
608 Array of vector origins.
609
610 vec : array_like[float]
611 Array of vectors.
612
613 Returns
614 -------
615 pyvista.PolyData
616 Mesh containing the ``orig`` points along with the
617 ``'vectors'`` and ``'mag'`` point arrays representing the
618 vectors and magnitude of the vectors at each point.
619
620 Examples
621 --------
622 Create basic vector field. This is a point cloud where each point
623 has a vector and magnitude attached to it.
624
625 >>> import pyvista as pv
626 >>> import numpy as np
627 >>> x, y = np.meshgrid(np.linspace(-5, 5, 10), np.linspace(-5, 5, 10))
628 >>> points = np.vstack((x.ravel(), y.ravel(), np.zeros(x.size))).T
629 >>> u = x / np.sqrt(x**2 + y**2)
630 >>> v = y / np.sqrt(x**2 + y**2)
631 >>> vectors = np.vstack((u.ravel() ** 3, v.ravel() ** 3, np.zeros(u.size))).T
632 >>> pdata = pv.vector_poly_data(points, vectors)
633 >>> pdata.point_data.keys()
634 ['vectors', 'mag']
635
636 Convert these to arrows and plot it.
637
638 >>> pdata.glyph(orient='vectors', scale='mag').plot()
639
640 """
641 # shape, dimension checking
642 if not isinstance(orig, np.ndarray):
643 orig = np.asarray(orig)
644
645 if not isinstance(vec, np.ndarray):
646 vec = np.asarray(vec)
647
648 if orig.ndim != 2:
649 orig = orig.reshape((-1, 3))
650 elif orig.shape[1] != 3:
651 msg = 'orig array must be 3D'
652 raise ValueError(msg)
653
654 if vec.ndim != 2:
655 vec = vec.reshape((-1, 3))
656 elif vec.shape[1] != 3:
657 msg = 'vec array must be 3D'
658 raise ValueError(msg)
659
660 # Create vtk points and cells objects
661 vpts = _vtk.vtkPoints()
662 vpts.SetData(_vtk.numpy_to_vtk(np.ascontiguousarray(orig), deep=True))
663
664 npts = orig.shape[0]
665 vcells = pv.core.cell.CellArray.from_regular_cells(
666 np.arange(npts, dtype=pv.ID_TYPE).reshape((npts, 1)), # type: ignore[arg-type]
667 )
668
669 # Create vtkPolyData object
670 pdata = _vtk.vtkPolyData()
671 pdata.SetPoints(vpts)
672 pdata.SetVerts(vcells)
673
674 # Add vectors to polydata
675 name = 'vectors'
676 vtkfloat = _vtk.numpy_to_vtk(np.ascontiguousarray(vec), deep=True)
677 vtkfloat.SetName(name)
678 pdata.GetPointData().AddArray(vtkfloat)
679 pdata.GetPointData().SetActiveVectors(name)
680
681 # Add magnitude of vectors to polydata
682 name = 'mag'
683 scalars = (vec * vec).sum(1) ** 0.5
684 vtkfloat = _vtk.numpy_to_vtk(np.ascontiguousarray(scalars), deep=True)
685 vtkfloat.SetName(name)
686 pdata.GetPointData().AddArray(vtkfloat)
687 pdata.GetPointData().SetActiveScalars(name)
688
689 return pv.PolyData(pdata)
690
691
692 @overload
693 def principal_axes(points: MatrixLike[float]) -> NumpyArray[float]: ...
694 @overload
695 def principal_axes(
696 points: MatrixLike[float],
697 *,
698 return_std: Literal[True] = True,
699 ) -> tuple[NumpyArray[float], NumpyArray[float]]: ...
700 @overload
701 def principal_axes(
702 points: MatrixLike[float],
703 *,
704 return_std: Literal[False] = False,
705 ) -> NumpyArray[float]: ...
706 @overload
707 def principal_axes(
708 points: MatrixLike[float], *, return_std: bool = ...
709 ) -> NumpyArray[float] | tuple[NumpyArray[float], NumpyArray[float]]: ...
710 def principal_axes(
711 points: MatrixLike[float], *, return_std: bool = False
712 ) -> NumpyArray[float] | tuple[NumpyArray[float], NumpyArray[float]]:
713 """Compute the principal axes of a set of points.
714
715 Principal axes are orthonormal vectors that best fit a set of points. The axes
716 are also known as the principal components in Principal Component Analysis (PCA),
717 or the right singular vectors from the Singular Value Decomposition (SVD).
718
719 The axes are computed as the eigenvectors of the covariance matrix from the
720 mean-centered points, and are processed to ensure that they form a right-handed
721 coordinate frame.
722
723 The axes explain the total variance of the points. The first axis explains the
724 largest percentage of variance, followed by the second axis, followed again by
725 the third axis which explains the smallest percentage of variance.
726
727 The axes may be used to build an oriented bounding box or to align the points to
728 another set of axes (e.g. the world XYZ axes).
729
730 .. note::
731 The computed axes are not unique, and the sign of each axis direction can be
732 arbitrarily changed.
733
734 .. note::
735 This implementation creates a temporary array of the same size as the input
736 array, and is therefore not optimal in terms of its memory requirements.
737 A more memory-efficient computation may be supported in a future release.
738
739 .. versionadded:: 0.45.0
740
741 See Also
742 --------
743 fit_plane_to_points
744 Fit a plane to points using the first two principal axes.
745
746 pyvista.DataSetFilters.align_xyz
747 Filter which aligns principal axes to the x-y-z axes.
748
749 :ref:`point_cloud_orientation_example`
750 Example using this function with point clouds.
751
752 Parameters
753 ----------
754 points : MatrixLike[float]
755 Nx3 array of points.
756
757 return_std : bool, default: False
758 If ``True``, also returns the standard deviation of the points along each axis.
759 Standard deviation is computed as the square root of the eigenvalues of the
760 mean-centered covariance matrix.
761
762 Returns
763 -------
764 numpy.ndarray
765 3x3 orthonormal array with the principal axes as row vectors.
766
767 numpy.ndarray
768 Three-item array of the standard deviations along each axis.
769
770 Examples
771 --------
772 >>> import pyvista as pv
773 >>> import numpy as np
774 >>> rng = np.random.default_rng(seed=0) # only seeding for the example
775
776 Create a mesh with points that have the largest variation in ``X``,
777 followed by ``Y``, then ``Z``.
778
779 >>> radii = np.array((6, 3, 1)) # x-y-z radii
780 >>> mesh = pv.ParametricEllipsoid(
781 ... xradius=radii[0], yradius=radii[1], zradius=radii[2]
782 ... )
783
784 Plot the mesh and highlight its points in black.
785
786 >>> pl = pv.Plotter()
787 >>> _ = pl.add_mesh(mesh)
788 >>> _ = pl.add_points(mesh, color='black')
789 >>> _ = pl.show_grid()
790 >>> pl.show()
791
792 Compute its principal axes and return the standard deviations.
793
794 >>> axes, std = pv.principal_axes(mesh.points, return_std=True)
795 >>> axes # doctest:+SKIP
796 pyvista_ndarray([[-1., 0., 0.],
797 [ 0., 1., 0.],
798 [ 0., 0., -1.]], dtype=float32)
799
800 Note that the principal axes have ones along the diagonal and zeros
801 in the off-diagonal. This indicates that the first principal axis is
802 aligned with the x-axis, the second with the y-axis, and third with
803 the z-axis. This is expected, since the mesh is already axis-aligned.
804
805 However, since the signs of the principal axes are arbitrary, the
806 first and third axes in this case have a negative direction.
807
808 Show the standard deviation along each axis.
809
810 >>> std # doctest:+SKIP
811 array([3.0149 , 1.5074 , 0.7035], dtype=float32)
812
813 Compare this to using :meth:`numpy.std` for the computation.
814
815 >>> np.std(mesh.points, axis=0)
816 pyvista_ndarray([3.0149572, 1.5074761, 0.7035699], dtype=float32)
817
818 Since the points are axis-aligned, the two results agree in this case. In general,
819 however, these two methods differ in that :meth:`numpy.std` with `axis=0` computes
820 the standard deviation along the `x-y-z` axes, whereas the standard deviation
821 returned by :meth:`principal_axes` is computed along the principal axes.
822
823 Convert the values to proportions for analysis.
824
825 >>> std / sum(std) # doctest:+SKIP
826 array([0.5769149 , 0.28845742, 0.1346276 ], dtype=float32)
827
828 From this result, we can determine that the axes explain approximately
829 58%, 29%, and 13% of the total variance in the points, respectively.
830
831 Let's compare this to the proportions of the known radii of the ellipsoid.
832
833 >>> radii / sum(radii)
834 array([0.6, 0.3, 0.1])
835
836 Note how the two ratios are similar, but do not match exactly. This is
837 because the points of the ellipsoid are prolate and are denser near the
838 poles. If the points were normally distributed, however, the proportions
839 would match exactly.
840
841 Create an array of normally distributed points scaled along the x-y-z axes.
842 Use the same scaling as the radii of the ellipsoid from the previous example.
843
844 >>> normal_points = rng.normal(size=(1000, 3))
845 >>> scaled_points = normal_points * radii
846 >>> axes, std = pv.principal_axes(scaled_points, return_std=True)
847 >>> axes
848 array([[-0.99997578, 0.00682346, 0.00136972],
849 [ 0.00681368, 0.99995213, -0.00702282],
850 [-0.00141757, -0.00701331, -0.9999744 ]])
851
852 Once again, the axes have ones along the diagonal as expected since the
853 points are already axis-aligned. Now let's examine the standard deviation
854 and compare the relative proportions.
855
856 >>> std
857 array([5.94466738, 2.89590334, 1.02103169])
858
859 >>> std / sum(std)
860 array([0.60280948, 0.29365444, 0.10353608])
861
862 >>> radii / sum(radii)
863 array([0.6, 0.3, 0.1])
864
865 Since the points are normally distributed, the relative proportion of
866 the standard deviation matches the scaling of the axes almost perfectly.
867
868 """
869 points = _validation.validate_arrayNx3(points)
870
871 points_centered = points - np.mean(points, axis=0)
872 eig_vals, eig_vectors = np.linalg.eigh(points_centered.T @ points_centered)
873 axes = eig_vectors.T[::-1] # columns, ascending order -> rows, descending order
874
875 # Ensure axes form a right-handed coordinate frame
876 if np.linalg.det(axes) < 0:
877 axes[2] *= -1
878
879 if return_std:
880 # Compute standard deviation and swap order from ascending -> descending
881 std = np.sqrt(np.abs(eig_vals) / len(points))[::-1]
882 return axes, std
883 return axes