Debian Codegraph @

pyvista/core/utilities/features.py

raw
1 """Module containing geometry helper functions."""
2
3 from __future__ import annotations
4
5 from collections.abc import Sequence
6 import os
7 import sys
8 import warnings
9
10 import numpy as np
11
12 import pyvista as pv
13 from pyvista import _vtk
14 from pyvista._deprecate_positional_args import _deprecate_positional_args
15 from pyvista.core.errors import DeprecationError
16 from pyvista.core.utilities.helpers import wrap
17
18
19 def _padded_bins(mesh, density):
20 """Construct bin edges for voxelization.
21
22 Parameters
23 ----------
24 mesh : pyvista.DataSet
25 Mesh to voxelize.
26
27 density : array_like[float]
28 A list of densities along x,y,z directions.
29
30 Returns
31 -------
32 list[np.ndarray]
33 List of bin edges for each axis.
34
35 Notes
36 -----
37 Ensures limits of voxelization are padded to ensure the mesh is fully enclosed.
38
39 """
40 bounds = np.array(mesh.bounds).reshape(3, 2)
41 bin_count = np.ceil(1e-10 + (bounds[:, 1] - bounds[:, 0]) / density)
42 pad = (bin_count * density - (bounds[:, 1] - bounds[:, 0])) / 2
43
44 return [
45 np.arange(bounds[i, 0] - pad[i], bounds[i, 1] + pad[i] + density[i] / 2, density[i])
46 for i in range(3)
47 ]
48
49
50 @_deprecate_positional_args(allowed=['mesh'])
51 def voxelize( # noqa: PLR0917
52 mesh, # noqa: ARG001
53 density=None, # noqa: ARG001
54 check_surface: bool = True, # noqa: ARG001, FBT001, FBT002
55 enclosed: bool = False, # noqa: ARG001, FBT001, FBT002
56 fit_bounds: bool = False, # noqa: ARG001, FBT001, FBT002
57 ):
58 """Voxelize mesh to UnstructuredGrid.
59
60 .. deprecated:: 0.46
61
62 This function is deprecated. Use :meth:`pyvista.DataSetFilters.voxelize` instead.
63
64 Parameters
65 ----------
66 mesh : pyvista.DataSet
67 Mesh to voxelize.
68
69 density : float | array_like[float]
70 The uniform size of the voxels when single float passed.
71 A list of densities along x,y,z directions.
72 Defaults to 1/100th of the mesh length.
73
74 check_surface : bool, default: True
75 Specify whether to check the surface for closure. If on, then the
76 algorithm first checks to see if the surface is closed and
77 manifold. If the surface is not closed and manifold, a runtime
78 error is raised.
79
80 enclosed : bool, default: False
81 If True, the voxel bounds will be outside the mesh.
82 If False, the voxel bounds will be at or inside the mesh bounds.
83
84 fit_bounds : bool, default: False
85 If enabled, the end bound of the input mesh is used as the end bound of the
86 voxel grid and the density is updated to the closest compatible one. Otherwise,
87 the end bound is excluded. Has no effect if `enclosed` is enabled.
88
89 Returns
90 -------
91 pyvista.UnstructuredGrid
92 Voxelized unstructured grid of the original mesh.
93
94 Notes
95 -----
96 Prior to version 0.39.0, this method improperly handled the order of
97 structured coordinates.
98
99 See Also
100 --------
101 pyvista.DataSetFilters.voxelize_rectilinear
102 Similar function that returns a :class:`pyvista.RectilinearGrid` with cell data.
103
104 pyvista.DataSetFilters.voxelize_binary_mask
105 Similar function that returns a :class:`pyvista.ImageData` with point data.
106
107 Examples
108 --------
109 Create an equal density voxelized mesh.
110
111 >>> import pyvista as pv
112 >>> from pyvista import examples
113 >>> mesh = examples.download_bunny_coarse().clean() # doctest:+SKIP
114 >>> vox = pv.voxelize(mesh, density=0.01) # doctest:+SKIP
115 >>> vox.plot(show_edges=True) # doctest:+SKIP
116
117 Create a voxelized mesh using unequal density dimensions.
118
119 >>> vox = pv.voxelize(mesh, density=[0.01, 0.005, 0.002]) # doctest:+SKIP
120 >>> vox.plot(show_edges=True) # doctest:+SKIP
121
122 Create an equal density voxel volume without enclosing input mesh.
123
124 >>> vox = pv.voxelize(mesh, density=0.01) # doctest:+SKIP
125 >>> vox = vox.select_enclosed_points(mesh, tolerance=0.0) # doctest:+SKIP
126 >>> vox.plot(scalars='SelectedPoints', show_edges=True) # doctest:+SKIP
127
128 Create an equal density voxel volume enclosing input mesh.
129
130 >>> vox = pv.voxelize(mesh, density=0.01, enclosed=True) # doctest:+SKIP
131 >>> vox = vox.select_enclosed_points(mesh, tolerance=0.0) # doctest:+SKIP
132 >>> vox.plot(scalars='SelectedPoints', show_edges=True) # doctest:+SKIP
133
134 Create a voxelized mesh that does not fit the input mesh's bounds. Notice the
135 cropped rectangular box.
136
137 >>> mesh = pv.Cube(x_length=0.25) # doctest:+SKIP
138 >>> vox = pv.voxelize(mesh=mesh, density=0.2) # doctest:+SKIP
139 >>> pl = pv.Plotter() # doctest:+SKIP
140 >>> _ = pl.add_mesh(mesh=vox, show_edges=True, color='yellow') # doctest:+SKIP
141 >>> _ = pl.add_mesh(
142 ... mesh=mesh, show_edges=True, line_width=5, opacity=0.4
143 ... ) # doctest:+SKIP
144 >>> pl.show() # doctest:+SKIP
145
146 Create a voxelized mesh that fits the input mesh's bounds. The rectangular mesh is
147 now complete. Notice that the voxel size was updated to fit the bounds in the first
148 direction.
149
150 >>> vox = pv.voxelize(mesh=mesh, density=0.2, fit_bounds=True) # doctest:+SKIP
151 >>> pl = pv.Plotter() # doctest:+SKIP
152 >>> _ = pl.add_mesh(mesh=vox, show_edges=True, color='yellow') # doctest:+SKIP
153 >>> _ = pl.add_mesh(
154 ... mesh=mesh, show_edges=True, line_width=5, opacity=0.4
155 ... ) # doctest:+SKIP
156 >>> pl.show() # doctest:+SKIP
157
158 """
159 # Deprecated on v0.46.0, error in v0.49.0
160 msg = '`pyvista.voxelize` is deprecated. Use `pyvista.DataSetFilters.voxelize` instead.'
161 raise DeprecationError(msg)
162
163
164 def _voxelize_legacy(
165 mesh,
166 *,
167 density=None,
168 check_surface: bool = True,
169 enclosed: bool = False,
170 fit_bounds: bool = False,
171 ):
172 """Voxelize mesh to UnstructuredGrid.
173
174 The public `voxelize` function is deprecated but we need to keep it for
175 generating the PyVista logo.
176
177 """
178 if not pv.is_pyvista_dataset(mesh):
179 mesh = wrap(mesh)
180 if density is None:
181 density = mesh.length / 100
182 if isinstance(density, (int, float, np.number)):
183 density_x, density_y, density_z = [density] * 3
184 elif isinstance(density, (Sequence, np.ndarray)):
185 density_x, density_y, density_z = density
186 else:
187 msg = f'Invalid density {density!r}, expected number or array-like.'
188 raise TypeError(msg)
189
190 # check and pre-process input mesh
191 surface = mesh.extract_surface(
192 algorithm=None, pass_cellid=False, pass_pointid=False
193 ) # filter preserves topology
194 if not surface.faces.size:
195 # we have a point cloud or an empty mesh
196 msg = 'Input mesh must have faces for voxelization.'
197 raise ValueError(msg)
198 if not surface.is_all_triangles:
199 # reduce chance for artifacts, see gh-1743
200 surface.triangulate(inplace=True)
201
202 if enclosed:
203 # Get x, y, z bin edges
204 x, y, z = _padded_bins(mesh, [density_x, density_y, density_z])
205 else:
206 x_min, x_max, y_min, y_max, z_min, z_max = mesh.bounds
207 if fit_bounds:
208 # Calculate an integer number of voxels, floor to ensure that the voxels
209 # don't exceed the input mesh
210 nof_voxels_x = int(np.round((x_max - x_min) / density_x))
211 nof_voxels_y = int(np.round((y_max - y_min) / density_y))
212 nof_voxels_z = int(np.round((z_max - z_min) / density_z))
213
214 # One additional point is required to ensure the proper number of voxels
215 x = np.linspace(x_min, x_max, nof_voxels_x + 1)
216 y = np.linspace(y_min, y_max, nof_voxels_y + 1)
217 z = np.linspace(z_min, z_max, nof_voxels_z + 1)
218 else:
219 x = np.arange(x_min, x_max, density_x)
220 y = np.arange(y_min, y_max, density_y)
221 z = np.arange(z_min, z_max, density_z)
222
223 x, y, z = np.meshgrid(x, y, z, indexing='ij')
224 # indexing='ij' is used here in order to make grid and ugrid with x-y-z ordering,
225 # not y-x-z ordering, see https://github.com/pyvista/pyvista/pull/4365
226
227 # Create unstructured grid from the structured grid
228 grid = pv.StructuredGrid(x, y, z)
229 ugrid = pv.UnstructuredGrid(grid)
230
231 if enclosed:
232 # Normalise cells to unit size
233 ugrid_norm = ugrid.copy()
234 surface_norm = surface.copy()
235 ugrid_norm.points /= np.array(density)
236 surface_norm.points /= np.array(density)
237 # Select cells if they're within one unit of the surface
238 ugrid_norm = ugrid_norm.compute_implicit_distance(surface_norm)
239 mask = ugrid_norm['implicit_distance'] < 1
240 del ugrid_norm, surface_norm
241 else:
242 # get part of the mesh within the mesh's bounding surface.
243 with warnings.catch_warnings():
244 warnings.simplefilter('ignore', category=pv.PyVistaDeprecationWarning)
245 selection = ugrid.select_enclosed_points(
246 surface, tolerance=0.0, check_surface=check_surface
247 )
248 mask = selection.point_data['SelectedPoints'].view(np.bool_)
249 del selection
250
251 # extract cells from point indices
252 return ugrid.extract_points(mask)
253
254
255 @_deprecate_positional_args(allowed=['mesh'])
256 def voxelize_volume( # noqa: PLR0917
257 mesh, # noqa: ARG001
258 density=None, # noqa: ARG001
259 check_surface: bool = True, # noqa: ARG001, FBT001, FBT002
260 enclosed: bool = False, # noqa: ARG001, FBT001, FBT002
261 fit_bounds: bool = False, # noqa: ARG001, FBT001, FBT002
262 ):
263 """Voxelize mesh to create a RectilinearGrid voxel volume.
264
265 Creates a voxel volume that encloses the input mesh and discretizes the cells
266 within the volume that intersect or are contained within the input mesh.
267 ``InsideMesh``, an array in ``cell_data``, is ``1`` for cells inside and ``0`` outside.
268
269 .. deprecated:: 0.46
270
271 This function is deprecated. Use :meth:`pyvista.DataSetFilters.voxelize_rectilinear`
272 instead.
273
274 Parameters
275 ----------
276 mesh : pyvista.DataSet
277 Mesh to voxelize.
278
279 density : float | array_like[float]
280 The uniform size of the voxels when single float passed.
281 Nonuniform voxel size if a list of values are passed along x,y,z directions.
282 Defaults to 1/100th of the mesh length.
283
284 check_surface : bool, default: True
285 Specify whether to check the surface for closure. If on, then the
286 algorithm first checks to see if the surface is closed and
287 manifold. If the surface is not closed and manifold, a runtime
288 error is raised.
289
290 enclosed : bool, default: False
291 If True, the voxel bounds will be outside the mesh.
292 If False, the voxel bounds will be at or inside the mesh bounds.
293
294 fit_bounds : bool, default: False
295 If enabled, the end bound of the input mesh is used as the end bound of the
296 voxel grid and the density is updated to the closest compatible one. Otherwise,
297 the end bound is excluded. Has no effect if `enclosed` is enabled.
298
299 Returns
300 -------
301 pyvista.RectilinearGrid
302 RectilinearGrid as voxelized volume with discretized cells.
303
304 See Also
305 --------
306 pyvista.DataSetFilters.voxelize
307 Similar function that returns a :class:`pyvista.UnstructuredGrid` of
308 :attr:`~pyvista.CellType.VOXEL` cells.
309
310 pyvista.DataSetFilters.voxelize_binary_mask
311 Similar function that returns a :class:`pyvista.ImageData` with point data.
312
313 pyvista.DataSetFilters.select_enclosed_points
314
315 Examples
316 --------
317 Create an equal density voxel volume from input mesh.
318
319 >>> import pyvista as pv
320 >>> import numpy as np
321
322 Load file from PyVista examples.
323
324 >>> from pyvista import examples
325 >>> mesh = examples.download_cow() # doctest:+SKIP
326
327 Create an equal density voxel volume and plot the result.
328
329 >>> vox = pv.voxelize_volume(mesh, density=0.15) # doctest:+SKIP
330 >>> cpos = [(15, 3, 15), (0, 0, 0), (0, 0, 0)] # doctest:+SKIP
331 >>> vox.plot(scalars='InsideMesh', show_edges=True, cpos=cpos) # doctest:+SKIP
332
333 Slice the voxel volume to view ``InsideMesh``.
334
335 >>> slices = vox.slice_orthogonal() # doctest:+SKIP
336 >>> slices.plot(scalars='InsideMesh', show_edges=True) # doctest:+SKIP
337
338 Create a voxel volume from unequal density dimensions and plot result.
339
340 >>> vox = pv.voxelize_volume(mesh, density=[0.15, 0.15, 0.5]) # doctest:+SKIP
341 >>> vox.plot(scalars='InsideMesh', show_edges=True, cpos=cpos) # doctest:+SKIP
342
343 Slice the unequal density voxel volume to view ``InsideMesh``.
344
345 >>> slices = vox.slice_orthogonal() # doctest:+SKIP
346 >>> slices.plot(
347 ... scalars='InsideMesh', show_edges=True, cpos=cpos
348 ... ) # doctest:+SKIP
349
350 Create an equal density voxel volume without enclosing input mesh.
351
352 >>> vox = pv.voxelize_volume(mesh, density=0.15) # doctest:+SKIP
353 >>> vox = vox.select_enclosed_points(mesh, tolerance=0.0) # doctest:+SKIP
354 >>> vox.plot(
355 ... scalars='SelectedPoints', show_edges=True, cpos=cpos
356 ... ) # doctest:+SKIP
357
358 Create an equal density voxel volume enclosing input mesh.
359
360 >>> vox = pv.voxelize_volume(
361 ... mesh, density=0.15, enclosed=True
362 ... ) # doctest:+SKIP
363 >>> vox = vox.select_enclosed_points(mesh, tolerance=0.0) # doctest:+SKIP
364 >>> vox.plot(
365 ... scalars='SelectedPoints', show_edges=True, cpos=cpos
366 ... ) # doctest:+SKIP
367
368 Create an equal density voxel volume that does not fit the input mesh's bounds.
369
370 >>> mesh = pv.examples.load_nut() # doctest:+SKIP
371 >>> vox = pv.voxelize_volume(mesh=mesh, density=2.5) # doctest:+SKIP
372 >>> pl = pv.Plotter() # doctest:+SKIP
373 >>> _ = pl.add_mesh(mesh=vox, show_edges=True) # doctest:+SKIP
374 >>> _ = pl.add_mesh(mesh=mesh, show_edges=True, opacity=1) # doctest:+SKIP
375 >>> pl.show() # doctest:+SKIP
376
377 Create an equal density voxel volume that fits the input mesh's bounds.
378
379 >>> vox = pv.voxelize_volume(
380 ... mesh=mesh, density=2.5, fit_bounds=True
381 ... ) # doctest:+SKIP
382 >>> pl = pv.Plotter() # doctest:+SKIP
383 >>> _ = pl.add_mesh(mesh=vox, show_edges=True) # doctest:+SKIP
384 >>> _ = pl.add_mesh(mesh=mesh, show_edges=True, opacity=1) # doctest:+SKIP
385 >>> pl.show() # doctest:+SKIP
386
387 """
388 # Deprecated on v0.46.0, error in v0.49.0
389 msg = (
390 '`pyvista.voxelize_volume` is deprecated. Use '
391 '`pyvista.DataSetFilters.voxelize_rectilinear` instead.'
392 )
393 raise DeprecationError(msg)
394
395
396 def create_grid(dataset, dimensions=(101, 101, 101)):
397 """Create a uniform grid surrounding the given dataset.
398
399 The output grid will have the specified dimensions and is commonly used
400 for interpolating the input dataset.
401
402 Parameters
403 ----------
404 dataset : DataSet
405 Input dataset used as a reference for the grid creation.
406 dimensions : tuple[int, int, int], default: (101, 101, 101)
407 The dimensions of the grid to be created. Each value in the tuple
408 represents the number of grid points along the corresponding axis.
409
410 Raises
411 ------
412 NotImplementedError
413 If the dimensions parameter is set to None. Currently, the function
414 does not support automatically determining the "optimal" grid size
415 based on the sparsity of the points in the input dataset.
416
417 Returns
418 -------
419 ImageData
420 A uniform grid with the specified dimensions that surrounds the input
421 dataset.
422
423 """
424 bounds = np.array(dataset.bounds)
425 if dimensions is None:
426 # TODO: we should implement an algorithm to automatically determine an
427 # "optimal" grid size by looking at the sparsity of the points in the
428 # input dataset - I actually think VTK might have this implemented
429 # somewhere
430 msg = 'Please specify dimensions.'
431 raise NotImplementedError(msg)
432 dimensions = np.array(dimensions, dtype=int)
433 image = pv.ImageData()
434 image.dimensions = dimensions
435 dims = dimensions - 1
436 dims[dims == 0] = 1
437 image.spacing = (bounds[1::2] - bounds[:-1:2]) / dims
438 image.origin = bounds[::2]
439 return image
440
441
442 def grid_from_sph_coords(theta, phi, r):
443 """Create a structured grid from arrays of spherical coordinates.
444
445 Parameters
446 ----------
447 theta : array_like[float]
448 Azimuthal angle in degrees ``[0, 360]``.
449 phi : array_like[float]
450 Polar (zenith) angle in degrees ``[0, 180]``.
451 r : array_like[float]
452 Distance (radius) from the point of origin.
453
454 Returns
455 -------
456 pyvista.StructuredGrid
457 Structured grid.
458
459 See Also
460 --------
461 :ref:`spherical_example`
462
463 """
464 x, y, z = np.meshgrid(np.radians(theta), np.radians(phi), r)
465 # Transform grid to cartesian coordinates
466 x_cart = z * np.sin(y) * np.cos(x)
467 y_cart = z * np.sin(y) * np.sin(x)
468 z_cart = z * np.cos(y)
469 # Make a grid object
470 return pv.StructuredGrid(x_cart, y_cart, z_cart)
471
472
473 @_deprecate_positional_args
474 def transform_vectors_sph_to_cart(theta, phi, r, u, v, w): # noqa: PLR0917 # numpydoc ignore=RT02
475 """Transform vectors from spherical (r, phi, theta) to cartesian coordinates (z, y, x).
476
477 Note the "reverse" order of arrays's axes, commonly used in geosciences.
478
479 Parameters
480 ----------
481 theta : array_like[float]
482 Azimuthal angle in degrees ``[0, 360]`` of shape ``(M,)``.
483 phi : array_like[float]
484 Polar (zenith) angle in degrees ``[0, 180]`` of shape ``(N,)``.
485 r : array_like[float]
486 Distance (radius) from the point of origin of shape ``(P,)``.
487 u : array_like[float]
488 X-component of the vector of shape ``(P, N, M)``.
489 v : array_like[float]
490 Y-component of the vector of shape ``(P, N, M)``.
491 w : array_like[float]
492 Z-component of the vector of shape ``(P, N, M)``.
493
494 Returns
495 -------
496 u_t, v_t, w_t : :class:`numpy.ndarray`
497 Arrays of transformed x-, y-, z-components, respectively.
498
499 """
500 xx, yy, _ = np.meshgrid(np.radians(theta), np.radians(phi), r, indexing='ij')
501 th, ph = xx.squeeze(), yy.squeeze()
502
503 # Transform wind components from spherical to cartesian coordinates
504 # https://en.wikipedia.org/wiki/Vector_fields_in_cylindrical_and_spherical_coordinates
505 u_t = np.sin(ph) * np.cos(th) * w + np.cos(ph) * np.cos(th) * v - np.sin(th) * u
506 v_t = np.sin(ph) * np.sin(th) * w + np.cos(ph) * np.sin(th) * v + np.cos(th) * u
507 w_t = np.cos(ph) * w - np.sin(ph) * v
508
509 return u_t, v_t, w_t
510
511
512 def cartesian_to_spherical(x, y, z):
513 """Convert 3D Cartesian coordinates to spherical coordinates.
514
515 Parameters
516 ----------
517 x, y, z : numpy.ndarray
518 Cartesian coordinates.
519
520 Returns
521 -------
522 r : numpy.ndarray
523 Radial distance.
524
525 phi : numpy.ndarray
526 Angle (radians) with respect to the polar axis. Also known
527 as polar angle.
528
529 theta : numpy.ndarray
530 Angle (radians) of rotation from the initial meridian plane.
531 Also known as azimuthal angle.
532
533 Examples
534 --------
535 >>> import numpy as np
536 >>> import pyvista as pv
537 >>> grid = pv.ImageData(dimensions=(3, 3, 3))
538 >>> x, y, z = grid.points.T
539 >>> r, phi, theta = pv.cartesian_to_spherical(x, y, z)
540
541 """
542 xy2 = x**2 + y**2
543 r = np.sqrt(xy2 + z**2)
544 phi = np.arctan2(np.sqrt(xy2), z) # the polar angle in radian angles
545 theta = np.arctan2(y, x) # the azimuth angle in radian angles
546
547 return r, phi, theta
548
549
550 def spherical_to_cartesian(r, phi, theta):
551 """Convert Spherical coordinates to 3D Cartesian coordinates.
552
553 Parameters
554 ----------
555 r : numpy.ndarray
556 Radial distance.
557
558 phi : numpy.ndarray
559 Angle (radians) with respect to the polar axis. Also known
560 as polar angle.
561
562 theta : numpy.ndarray
563 Angle (radians) of rotation from the initial meridian plane.
564 Also known as azimuthal angle.
565
566 Returns
567 -------
568 output : numpy.ndarray, numpy.ndarray, numpy.ndarray
569 Cartesian coordinates.
570
571 """
572 s = np.sin(phi)
573 x = r * s * np.cos(theta)
574 y = r * s * np.sin(theta)
575 z = r * np.cos(phi)
576 return x, y, z
577
578
579 @_deprecate_positional_args(allowed=['datasets'])
580 def merge( # noqa: PLR0917
581 datasets,
582 merge_points: bool = True, # noqa: FBT001, FBT002
583 main_has_priority: bool | None = None, # noqa: FBT001
584 progress_bar: bool = False, # noqa: FBT001, FBT002
585 ):
586 """Merge several datasets.
587
588 .. note::
589 The behavior of this filter varies from the
590 :func:`PolyDataFilters.boolean_union` filter. This filter
591 does not attempt to create a manifold mesh and will include
592 internal surfaces when two meshes overlap.
593
594 .. warning::
595
596 The merge order of this filter depends on the installed version
597 of VTK. For example, if merging meshes ``a``, ``b``, and ``c``,
598 the merged order is ``bca`` for VTK<9.5 and ``abc`` for VTK>=9.5.
599 This may be a breaking change for some applications. If only
600 merging two meshes, it may be possible to maintain `some` backwards
601 compatibility by swapping the input order of the two meshes,
602 though this may also affect the merged arrays and is therefore
603 not fully backwards-compatible.
604
605 Parameters
606 ----------
607 datasets : sequence[:class:`pyvista.DataSet`]
608 Sequence of datasets. Can be of any :class:`pyvista.DataSet`.
609
610 merge_points : bool, default: True
611 Merge equivalent points when ``True``.
612
613 main_has_priority : bool, default: True
614 When this parameter is ``True`` and ``merge_points=True``, the arrays
615 of the merging grids will be overwritten by the original main mesh.
616
617 .. deprecated:: 0.46
618
619 This keyword will be removed in a future version. The main mesh
620 always has priority with VTK 9.5.0 or later.
621
622 progress_bar : bool, default: False
623 Display a progress bar to indicate progress.
624
625 Returns
626 -------
627 pyvista.DataSet
628 :class:`pyvista.PolyData` if all items in datasets are
629 :class:`pyvista.PolyData`, otherwise returns a
630 :class:`pyvista.UnstructuredGrid`.
631
632 Examples
633 --------
634 Merge two polydata datasets.
635
636 >>> import pyvista as pv
637 >>> sphere = pv.Sphere(center=(0, 0, 1))
638 >>> cube = pv.Cube()
639 >>> mesh = pv.merge([cube, sphere])
640 >>> mesh.plot()
641
642 """
643 if not isinstance(datasets, Sequence):
644 msg = f'Expected a sequence, got {type(datasets).__name__}'
645 raise TypeError(msg)
646
647 if len(datasets) < 1:
648 msg = 'Expected at least one dataset.'
649 raise ValueError(msg)
650
651 first = datasets[0]
652 if not isinstance(first, pv.DataSet):
653 msg = f'Expected pyvista.DataSet, not {type(first).__name__}'
654 raise TypeError(msg)
655
656 return datasets[0].merge(
657 datasets[1:],
658 merge_points=merge_points,
659 main_has_priority=main_has_priority,
660 progress_bar=progress_bar,
661 )
662
663
664 def perlin_noise(amplitude, freq: Sequence[float], phase: Sequence[float]):
665 """Return the implicit function that implements Perlin noise.
666
667 Uses :vtk:`vtkPerlinNoise` and computes a Perlin noise field as
668 an implicit function. :vtk:`vtkPerlinNoise` is a concrete
669 implementation of :vtk:`vtkImplicitFunction`. Perlin noise,
670 originally described by Ken Perlin, is a non-periodic and
671 continuous noise function useful for modeling real-world objects.
672
673 The amplitude and frequency of the noise pattern are
674 adjustable. This implementation of Perlin noise is derived closely
675 from Greg Ward's version in Graphics Gems II.
676
677 Parameters
678 ----------
679 amplitude : float
680 Amplitude of the noise function.
681
682 ``amplitude`` can be negative. The noise function varies
683 randomly between ``-|Amplitude|`` and
684 ``|Amplitude|``. Therefore the range of values is
685 ``2*|Amplitude|`` large. The initial amplitude is 1.
686
687 freq : sequence[float]
688 The frequency, or physical scale, of the noise function
689 (higher is finer scale).
690
691 The frequency can be adjusted per axis, or the same for all axes.
692
693 phase : sequence[float]
694 Set/get the phase of the noise function.
695
696 This parameter can be used to shift the noise function within
697 space (perhaps to avoid a beat with a noise pattern at another
698 scale). Phase tends to repeat about every unit, so a phase of
699 0.5 is a half-cycle shift.
700
701 Returns
702 -------
703 :vtk:`vtkPerlinNoise`
704 Instance of :vtk:`vtkPerlinNoise` to a Perlin noise field as an
705 implicit function. Use with :func:`~pyvista.sample_function`.
706
707 See Also
708 --------
709 :ref:`perlin_noise_2d_example`
710 :ref:`perlin_noise_3d_example`
711
712 Examples
713 --------
714 Create a Perlin noise function with an amplitude of 0.1, frequency
715 for all axes of 1, and a phase of 0 for all axes.
716
717 >>> import pyvista as pv
718 >>> noise = pv.perlin_noise(0.1, (1, 1, 1), (0, 0, 0))
719
720 Sample Perlin noise over a structured grid and plot it.
721
722 >>> grid = pv.sample_function(noise, bounds=[0, 5, 0, 5, 0, 5])
723 >>> grid.plot()
724
725 """
726 noise = _vtk.vtkPerlinNoise()
727 noise.SetAmplitude(amplitude)
728 noise.SetFrequency(freq)
729 noise.SetPhase(phase)
730 return noise
731
732
733 @_deprecate_positional_args(allowed=['function'])
734 def sample_function( # noqa: PLR0917
735 function: _vtk.vtkImplicitFunction,
736 bounds: Sequence[float] = (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0),
737 dim: Sequence[int] = (50, 50, 50),
738 compute_normals: bool = False, # noqa: FBT001, FBT002
739 output_type: np.dtype = np.double, # type: ignore[assignment]
740 capping: bool = False, # noqa: FBT001, FBT002
741 cap_value: float = sys.float_info.max,
742 scalar_arr_name: str = 'scalars',
743 normal_arr_name: str = 'normals',
744 progress_bar: bool = False, # noqa: FBT001, FBT002
745 ):
746 """Sample an implicit function over a structured point set.
747
748 Uses :vtk:`vtkSampleFunction`
749
750 This method evaluates an implicit function and normals at each
751 point in a :vtk:`vtkStructuredPoints`. The user can specify the
752 sample dimensions and location in space to perform the sampling.
753
754 To create closed surfaces (in conjunction with the
755 :vtk:`vtkContourFilter`), capping can be turned on to set a particular
756 value on the boundaries of the sample space.
757
758 Parameters
759 ----------
760 function : :vtk:`vtkImplicitFunction`
761 Implicit function to evaluate. For example, the function
762 generated from :func:`perlin_noise() <pyvista.core.utilities.features.perlin_noise>`.
763
764 bounds : sequence[float], default: (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)
765 Specify the bounds in the format of:
766
767 - ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
768
769 dim : sequence[float], default: (50, 50, 50)
770 Dimensions of the data on which to sample in the format of
771 ``(xdim, ydim, zdim)``.
772
773 compute_normals : bool, default: False
774 Enable or disable the computation of normals.
775
776 output_type : numpy.dtype, default: numpy.double
777 Set the output scalar type. One of the following:
778
779 - ``np.float64``
780 - ``np.float32``
781 - ``np.int64``
782 - ``np.uint64``
783 - ``np.int32``
784 - ``np.uint32``
785 - ``np.int16``
786 - ``np.uint16``
787 - ``np.int8``
788 - ``np.uint8``
789
790 capping : bool, default: False
791 Enable or disable capping. If capping is enabled, then the outer
792 boundaries of the structured point set are set to cap value. This can
793 be used to ensure surfaces are closed.
794
795 cap_value : float, default: sys.float_info.max
796 Capping value used with the ``capping`` parameter.
797
798 scalar_arr_name : str, default: "scalars"
799 Set the scalar array name for this data set.
800
801 normal_arr_name : str, default: "normals"
802 Set the normal array name for this data set.
803
804 progress_bar : bool, default: False
805 Display a progress bar to indicate progress.
806
807 Returns
808 -------
809 pyvista.ImageData
810 Uniform grid with sampled data.
811
812 Examples
813 --------
814 Sample Perlin noise over a structured grid in 3D.
815
816 >>> import pyvista as pv
817 >>> noise = pv.perlin_noise(0.1, (1, 1, 1), (0, 0, 0))
818 >>> grid = pv.sample_function(
819 ... noise, bounds=[0, 3.0, -0, 1.0, 0, 1.0], dim=(60, 20, 20)
820 ... )
821 >>> grid.plot(cmap='gist_earth_r', show_scalar_bar=False, show_edges=True)
822
823 Sample Perlin noise in 2D and plot it.
824
825 >>> noise = pv.perlin_noise(0.1, (5, 5, 5), (0, 0, 0))
826 >>> surf = pv.sample_function(noise, dim=(200, 200, 1))
827 >>> surf.plot()
828
829 See :ref:`perlin_noise_2d_example` and :ref:`perlin_noise_3d_example`
830 for a full example using this function.
831
832 """
833 # internal import to avoid circular dependency
834 from pyvista.core.filters import _update_alg # noqa: PLC0415
835
836 samp = _vtk.vtkSampleFunction()
837 samp.SetImplicitFunction(function)
838 samp.SetSampleDimensions(dim) # type: ignore[call-overload]
839 samp.SetModelBounds(bounds)
840 samp.SetComputeNormals(compute_normals)
841 samp.SetCapping(capping)
842 samp.SetCapValue(cap_value)
843 samp.SetNormalArrayName(normal_arr_name)
844 samp.SetScalarArrayName(scalar_arr_name)
845
846 if output_type == np.float64:
847 samp.SetOutputScalarTypeToDouble()
848 elif output_type == np.float32:
849 samp.SetOutputScalarTypeToFloat()
850 elif output_type == np.int64:
851 if os.name == 'nt':
852 msg = 'This function on Windows only supports int32 or smaller'
853 raise ValueError(msg)
854 samp.SetOutputScalarTypeToLong()
855 elif output_type == np.uint64:
856 if os.name == 'nt':
857 msg = 'This function on Windows only supports int32 or smaller'
858 raise ValueError(msg)
859 samp.SetOutputScalarTypeToUnsignedLong()
860 elif output_type == np.int32:
861 samp.SetOutputScalarTypeToInt()
862 elif output_type == np.uint32:
863 samp.SetOutputScalarTypeToUnsignedInt()
864 elif output_type == np.int16:
865 samp.SetOutputScalarTypeToShort()
866 elif output_type == np.uint16:
867 samp.SetOutputScalarTypeToUnsignedShort()
868 elif output_type == np.int8:
869 samp.SetOutputScalarTypeToChar()
870 elif output_type == np.uint8:
871 samp.SetOutputScalarTypeToUnsignedChar()
872 else:
873 msg = f'Invalid output_type {output_type}'
874 raise ValueError(msg)
875
876 _update_alg(samp, progress_bar=progress_bar, message='Sampling')
877 return wrap(samp.GetOutput())