Debian Codegraph @

pyvista/core/utilities/fileio.py

raw
1 """Contains a dictionary that maps file extensions to VTK readers."""
2
3 from __future__ import annotations
4
5 from abc import ABC
6 from abc import abstractmethod
7 from collections.abc import Sequence
8 import importlib
9 import itertools
10 import json
11 from pathlib import Path
12 import pickle
13 from typing import TYPE_CHECKING
14 from typing import Any
15 from typing import Literal
16 from typing import TextIO
17 from typing import TypeVar
18 from typing import cast
19 from typing import overload
20 from urllib.parse import urlparse
21
22 import numpy as np
23
24 import pyvista as pv
25 from pyvista import _vtk
26 from pyvista._deprecate_positional_args import _deprecate_positional_args
27 from pyvista._warn_external import warn_external
28 from pyvista.core import _validation
29 from pyvista.core.errors import PyVistaDeprecationWarning
30 from pyvista.core.utilities.misc import _classproperty
31 from pyvista.core.utilities.misc import _NoNewAttrMixin
32
33 from .observers import Observer
34
35 if TYPE_CHECKING:
36 from collections.abc import Iterable
37
38 import imageio
39 import meshio
40 import trimesh
41
42 from pyvista import BaseReader
43 from pyvista import DataObject
44 from pyvista import DataSet
45 from pyvista import ExplicitStructuredGrid
46 from pyvista import MultiBlock
47 from pyvista import NumpyArray
48 from pyvista import PolyData
49 from pyvista import Texture
50 from pyvista import UnstructuredGrid
51 from pyvista import VectorLike
52
53 _CompressionOptions = Literal['zlib', 'lz4', 'lzma', None] # noqa: PYI061
54 PathStrSeq = str | Path | Sequence['PathStrSeq']
55 PICKLE_EXT = ('.pkl', '.pickle')
56 _PointCellField = Literal['point', 'cell', 'field']
57 _PassDataOptions = bool | _PointCellField | Sequence[_PointCellField]
58 _ReadReturnT = TypeVar('_ReadReturnT', bound='DataObject')
59
60
61 def _lazy_vtk_import(module_name: str, class_name: str) -> type:
62 """Lazy import of a class from vtkmodules."""
63 module = importlib.import_module(f'vtkmodules.{module_name}')
64 return getattr(module, class_name)
65
66
67 class _FileIOBase(ABC, _NoNewAttrMixin):
68 _vtk_module_name: str = ''
69 _vtk_class_name: str = ''
70
71 def __repr__(self) -> str:
72 """Representation of a FileIO object."""
73 return f'{self.__class__.__name__}({self.path!r})'
74
75 @property
76 @abstractmethod
77 def path(self) -> str:
78 """Get the path."""
79
80 @path.setter
81 @abstractmethod
82 def path(self, path: str | Path) -> None:
83 """Set the path."""
84
85 @_classproperty
86 def _vtk_class(cls) -> _vtk.vtkWriter | None: # noqa: N805
87 if cls._vtk_module_name and cls._vtk_class_name:
88 return _lazy_vtk_import(cls._vtk_module_name, cls._vtk_class_name) # type: ignore[return-value]
89 return None
90
91 @classmethod
92 @abstractmethod
93 def _get_extension_mappings(cls) -> list[dict[str, type]]: ...
94
95 @_classproperty
96 def extensions(cls) -> tuple[str, ...]: # noqa: N805
97 """Return the file extension(s) associated with this class.
98
99 These extensions are used by :func:`~pyvista.read` and :class:`~pyvista.DataObject.save`
100 to determine which reader and/or writer is used for reading and/or saving files.
101
102 """
103 extensions = set()
104 for mapping in cls._get_extension_mappings():
105 for ext, typ in mapping.items():
106 if typ is cls: # type: ignore[comparison-overlap]
107 extensions.add(ext) # type: ignore[unreachable]
108 return tuple(sorted(extensions))
109
110
111 def _warn_multiblock_nested_field_data(mesh: pv.DataObject) -> None:
112 if not isinstance(mesh, pv.MultiBlock):
113 return
114 iterator = mesh.recursive_iterator('all', node_type='parent')
115 for index, name, nested_multiblock in iterator:
116 if len(nested_multiblock.field_data.keys()) > 0:
117 # Avoid circular import
118 from pyvista.core.filters.composite import _format_nested_index # noqa: PLC0415
119
120 index_fmt = _format_nested_index(index)
121 msg = (
122 f"Nested MultiBlock at index {index_fmt} with name '{name}' "
123 f'has field data which will not be saved.\n'
124 'See https://gitlab.kitware.com/vtk/vtk/-/issues/19414 \n'
125 'Use `move_nested_field_data_to_root` to store the field data '
126 'with the root MultiBlock before saving.'
127 )
128 warn_external(msg)
129
130
131 def set_pickle_format(format: Literal['vtk', 'xml', 'legacy']) -> None: # noqa: A002
132 """Set the format used to serialize :class:`pyvista.DataObject` when pickled.
133
134 Parameters
135 ----------
136 format : str
137 The format for serialization. Acceptable values are:
138
139 - ``'vtk'`` (default) : objects are serialized using VTK's official
140 marshalling methods.
141 - ``'xml'``: objects are serialized as an XML-formatted string.
142 - ``'legacy'`` objects are serialized to bytes in VTK's binary format.
143
144 .. note::
145
146 The ``'vtk'`` format requires VTK 9.3 or greater.
147
148 .. warning::
149
150 ``'xml'`` and ``'legacy'`` are not recommended. These formats are not
151 officially supported by VTK and have limitations. For example, these
152 formats cannot be used to pickle :class:`pyvista.MultiBlock`.
153
154 Raises
155 ------
156 ValueError
157 If the provided format is not supported.
158
159 """
160 supported = {'vtk', 'xml', 'legacy'}
161 format_ = cast('Literal["vtk", "xml", "legacy"]', format.lower())
162 if format_ not in supported:
163 msg = (
164 f'Unsupported pickle format `{format_}`. Valid options are `{"`, `".join(supported)}`.'
165 )
166 raise ValueError(msg)
167 if format_ == 'vtk' and pv.vtk_version_info < (9, 3):
168 msg = "'vtk' pickle format requires VTK >= 9.3"
169 raise ValueError(msg)
170
171 pv.PICKLE_FORMAT = format_
172
173
174 def _get_ext_force(filename: str | Path, force_ext: str | None = None) -> str:
175 if force_ext:
176 return str(force_ext).lower()
177 else:
178 return get_ext(filename)
179
180
181 def get_ext(filename: str | Path) -> str:
182 """Extract the extension of the filename.
183
184 For files with the .gz suffix, the previous extension is returned as well.
185 This is needed e.g. for the compressed NIFTI format (.nii.gz).
186
187 Parameters
188 ----------
189 filename : str, Path
190 The filename from which to extract the extension.
191
192 Returns
193 -------
194 str
195 The extracted extension. For files with the .gz suffix, the previous
196 extension is returned as well.
197
198 """
199 path = Path(filename)
200 base = str(path.parent / path.stem)
201 ext = path.suffix
202 ext = ext.lower()
203 if ext == '.gz':
204 path = Path(base)
205 ext_pre = path.suffix.lower()
206 ext = f'{ext_pre}{ext}'
207 return ext
208
209
210 @overload
211 def read(
212 filename: PathStrSeq,
213 force_ext: str | None = ...,
214 file_format: str | None = ...,
215 progress_bar: bool = ..., # noqa: FBT001
216 *,
217 cls: type[_ReadReturnT],
218 validate: bool | None = ...,
219 ) -> _ReadReturnT: ...
220 @overload
221 def read(
222 filename: PathStrSeq,
223 force_ext: str | None = ...,
224 file_format: str | None = ...,
225 progress_bar: bool = ..., # noqa: FBT001
226 *,
227 cls: None = ...,
228 validate: bool | None = ...,
229 ) -> DataSet | MultiBlock: ...
230 @_deprecate_positional_args(allowed=['filename'])
231 def read( # noqa: PLR0917
232 filename: PathStrSeq,
233 force_ext: str | None = None,
234 file_format: str | None = None,
235 progress_bar: bool = False, # noqa: FBT001, FBT002
236 *,
237 cls: type[DataObject] | None = None,
238 validate: bool | None = None,
239 ) -> DataObject:
240 """Read any file type supported by ``vtk`` or ``meshio``.
241
242 Automatically determines the correct reader to use then wraps the
243 corresponding mesh as a pyvista object. Attempts native ``vtk``
244 readers first then tries to use ``meshio``. :py:mod:`Pickled<pickle>`
245 meshes (``'.pkl'`` or ``'.pickle'``) are also supported.
246
247 Remote URIs (``https://``, ``s3://``, etc.) are downloaded to a
248 temporary file automatically. Install ``fsspec`` for full protocol
249 support (``pip install pyvista[io]``); ``pooch`` is used as a
250 fallback for HTTP(S). Third-party reader plugins registered via
251 :func:`pyvista.register_reader` are also checked.
252
253 See :func:`pyvista.get_reader` for list of vtk formats supported.
254
255 .. include:: /api/utilities/mesh_io.rst
256
257 .. note::
258 See https://github.com/nschloe/meshio for formats supported by
259 ``meshio``. Be sure to install ``meshio`` with ``pip install
260 meshio`` if you wish to use it.
261
262 .. versionadded:: 0.45
263
264 Support reading pickled meshes.
265
266 .. warning::
267
268 The pickle module is not secure. Only read pickled mesh files
269 (``'.pkl'`` or ``'.pickle'``) you trust. See :py:mod:`pickle`
270 for details.
271
272 See Also
273 --------
274 pyvista.DataObject.save
275 Save a mesh to file.
276
277 Parameters
278 ----------
279 filename : str, Path, Sequence[str | Path]
280 The string path to the file to read. If a list of files is
281 given, a :class:`pyvista.MultiBlock` dataset is returned with
282 each file being a separate block in the dataset.
283
284 force_ext : str, optional
285 If specified, the reader will be chosen by an extension which
286 is different to its actual extension. For example, ``'.vts'``,
287 ``'.vtu'``.
288
289 file_format : str, optional
290 Format of file to read with meshio.
291
292 progress_bar : bool, default: False
293 Optionally show a progress bar. Ignored when using ``meshio``.
294
295 cls : type, optional
296 Expected concrete type of the returned mesh. When given, the
297 result is checked with :func:`isinstance` and a
298 :class:`TypeError` is raised on mismatch. Static type checkers
299 (``mypy``, ``pyright``) use this to narrow the return type to
300 ``cls`` directly, so callers do not need ``typing.cast`` or a
301 manual ``assert isinstance`` to access subclass-specific
302 attributes, e.g. ``pv.read('file.vtu', cls=pv.UnstructuredGrid)``.
303
304 validate : bool, optional
305 Forwarded to :func:`pyvista.wrap` as the ``validate`` keyword when
306 using a ``vtk`` reader. When ``None`` (the default), honors
307 :attr:`pyvista.core.config.Config.validate_on_wrap`. Pass ``False`` to
308 skip the cheap array-length sanity check on very large trusted
309 files. Has no effect for ``meshio`` or pickle code paths.
310
311 .. versionadded:: 0.48
312
313 Returns
314 -------
315 pyvista.DataSet | pyvista.MultiBlock
316 Wrapped PyVista dataset. When ``cls`` is given, an instance of
317 ``cls`` is returned instead.
318
319 Examples
320 --------
321 Load an example mesh.
322
323 >>> import pyvista as pv
324 >>> from pyvista import examples
325 >>> mesh = pv.read(examples.antfile)
326 >>> mesh.plot(cpos='xz')
327
328 Narrow the return type to a specific class. This avoids the need for
329 a manual ``cast`` when working with type checkers such as ``mypy``
330 or ``pyright``.
331
332 >>> mesh = pv.read('mesh.vtu', cls=pv.UnstructuredGrid) # doctest:+SKIP
333
334 Load a vtk file.
335
336 >>> mesh = pv.read('my_mesh.vtk') # doctest:+SKIP
337
338 Load a meshio file.
339
340 >>> mesh = pv.read('mesh.obj') # doctest:+SKIP
341
342 Load a pickled mesh file.
343
344 >>> mesh = pv.read('mesh.pkl') # doctest:+SKIP
345
346 """
347 result = _read_dispatch(
348 filename,
349 force_ext=force_ext,
350 file_format=file_format,
351 progress_bar=progress_bar,
352 validate=validate,
353 )
354 if cls is not None and not isinstance(result, cls):
355 msg = (
356 f'Expected an instance of {cls.__name__} when reading {filename!r}, '
357 f'but got {type(result).__name__}.'
358 )
359 raise TypeError(msg)
360 return result
361
362
363 def _read_dispatch( # noqa: PLR0911
364 filename: PathStrSeq,
365 *,
366 force_ext: str | None,
367 file_format: str | None,
368 progress_bar: bool,
369 validate: bool | None,
370 ) -> DataObject:
371 """Dispatch a filename to the right reader and return the wrapped mesh."""
372 if file_format is not None and force_ext is not None:
373 msg = 'Only one of `file_format` and `force_ext` may be specified.'
374 raise ValueError(msg)
375
376 if isinstance(filename, Sequence) and not isinstance(filename, str):
377 multi = pv.MultiBlock()
378 for each in filename:
379 name = Path(each).name if isinstance(each, (str, Path)) else None
380 multi.append(
381 _read_dispatch( # type: ignore[arg-type]
382 each,
383 force_ext=None,
384 file_format=file_format,
385 progress_bar=progress_bar,
386 validate=validate,
387 ),
388 name,
389 )
390 return multi
391
392 # Circular import: reader_registry -> reader -> fileio
393 from pyvista.core.utilities.reader_registry import LocalFileRequiredError # noqa: PLC0415
394 from pyvista.core.utilities.reader_registry import _download_uri # noqa: PLC0415
395 from pyvista.core.utilities.reader_registry import _get_ext_handler # noqa: PLC0415
396 from pyvista.core.utilities.reader_registry import has_scheme # noqa: PLC0415
397
398 # Handle remote URIs before Path coercion
399 if isinstance(filename, str) and has_scheme(filename):
400 uri_ext = get_ext(urlparse(filename).path)
401 if uri_ext.lower() in PICKLE_EXT:
402 msg = (
403 f'Refusing to load pickle from remote URI {filename!r}. '
404 f'Loading a pickle from an untrusted source allows arbitrary '
405 f'code execution. Download the file manually after verifying '
406 f'its origin, then pass the local path to `pyvista.read_pickle`.'
407 )
408 raise ValueError(msg)
409 # If a custom reader is registered for this extension, try it
410 # with the raw URI first, the reader may handle cloud paths
411 # natively (e.g. zarr stores on S3). If it fails, fall back to
412 # downloading the file and retrying with a local path.
413 ext_handler = _get_ext_handler(uri_ext)
414 if ext_handler is not None:
415 try:
416 return ext_handler(filename)
417 except LocalFileRequiredError:
418 filename = _download_uri(filename, uri_ext)
419 return ext_handler(filename)
420 filename = _download_uri(filename, uri_ext)
421
422 filename = Path(filename).expanduser().resolve()
423 if not filename.is_file() and not filename.is_dir():
424 msg = f'File ({filename}) not found'
425 raise FileNotFoundError(msg)
426
427 # Read file using meshio.read if file_format is present
428 if file_format:
429 return read_meshio(filename, file_format)
430
431 ext = _get_ext_force(filename, force_ext)
432 if ext in ['.e', '.exo']:
433 return read_exodus(filename)
434 if ext.lower() == '.grdecl':
435 return read_grdecl(filename)
436 if ext in ['.wrl', '.vrml']:
437 msg = (
438 'VRML files must be imported directly into a Plotter. '
439 'See `pyvista.Plotter.import_vrml` for details.'
440 )
441 raise ValueError(msg)
442 if ext in PICKLE_EXT:
443 return read_pickle(filename)
444
445 # Check for registered custom extension readers
446 ext_handler = _get_ext_handler(ext)
447 if ext_handler is not None:
448 return ext_handler(str(filename))
449
450 try:
451 reader = pv.get_reader(filename, force_ext)
452 except ValueError:
453 msg = f'This file was not able to be automatically read by pyvista.\n {str(filename)!r}'
454 # if using force_ext, we are explicitly only using vtk readers
455 if force_ext is not None:
456 raise OSError(msg)
457 try:
458 from meshio._exceptions import ReadError # noqa: PLC0415
459 except ImportError:
460 raise OSError(msg)
461 try:
462 return read_meshio(filename)
463 except ReadError:
464 if ext == '.pv': # pragma: no cover
465 msg += (
466 "\nThe '.pv' extension is supported by the `pyvista-zstd` package. "
467 'It can be installed with `pyvista[io]`.'
468 )
469 raise OSError(msg)
470 else:
471 observer = Observer()
472 observer.observe(reader.reader)
473 if progress_bar:
474 reader.show_progress()
475 mesh = reader.read(validate=validate)
476 if observer.has_event_occurred():
477 warn_external(
478 f'The VTK reader `{reader.reader.GetClassName()}` in pyvista reader `{reader}` '
479 'raised an error while reading the file.\n'
480 f'\t"{observer.get_message()}"',
481 )
482 return mesh
483
484
485 def _apply_attrs_to_reader(
486 reader: BaseReader[Any], attrs: dict[str, object | Sequence[object]]
487 ) -> None:
488 """For a given pyvista reader, call methods according to attrs.
489
490 Parameters
491 ----------
492 reader : pyvista.BaseReader
493 Reader to call methods on.
494
495 attrs : dict
496 Mapping of methods to call on reader.
497
498 """
499 warn_external(
500 'attrs use is deprecated. Use a Reader class for more flexible control',
501 PyVistaDeprecationWarning,
502 )
503 for name, args in attrs.items():
504 attr = getattr(reader.reader, name)
505 if args is not None:
506 if not isinstance(args, (list, tuple)):
507 args = [args] # noqa: PLW2901
508 attr(*args)
509 else:
510 attr()
511
512
513 @_deprecate_positional_args(allowed=['filename'])
514 def read_texture(filename: str | Path, progress_bar: bool = False) -> Texture: # noqa: FBT001, FBT002
515 """Load a texture from an image file.
516
517 Will attempt to read any file type supported by ``vtk``, however
518 if it fails, it will attempt to use ``imageio`` to read the file.
519
520 Parameters
521 ----------
522 filename : str
523 The path of the texture file to read.
524
525 progress_bar : bool, default: False
526 Optionally show a progress bar.
527
528 Returns
529 -------
530 pyvista.Texture
531 PyVista texture object.
532
533 Examples
534 --------
535 Read in an example jpg map file as a texture.
536
537 >>> from pathlib import Path
538 >>> import pyvista as pv
539 >>> from pyvista import examples
540 >>> Path(examples.mapfile).name
541 '2k_earth_daymap.jpg'
542 >>> texture = pv.read_texture(examples.mapfile)
543 >>> type(texture)
544 <class 'pyvista.plotting.texture.Texture'>
545
546 """
547 filename = Path(filename).expanduser().resolve()
548 try:
549 # initialize the reader using the extension to find it
550
551 image = read(filename, progress_bar=progress_bar)
552 if image.n_points < 2:
553 msg = 'Problem reading the image with VTK.'
554 raise ValueError(msg)
555 return pv.Texture(image) # type: ignore[abstract]
556 except (KeyError, ValueError):
557 # Otherwise, use the imageio reader
558 pass
559
560 return pv.Texture(_try_imageio_imread(filename)) # type: ignore[abstract] # pragma: no cover
561
562
563 @_deprecate_positional_args(allowed=['filename'])
564 def read_exodus( # noqa: PLR0917
565 filename: str | Path,
566 animate_mode_shapes: bool = True, # noqa: FBT001, FBT002
567 apply_displacements: bool = True, # noqa: FBT001, FBT002
568 displacement_magnitude: float = 1.0,
569 read_point_data: bool = True, # noqa: FBT001, FBT002
570 read_cell_data: bool = True, # noqa: FBT001, FBT002
571 enabled_sidesets: Iterable[str | int] | None = None,
572 ) -> DataSet | MultiBlock:
573 """Read an ExodusII file (``'.e'`` or ``'.exo'``).
574
575 Parameters
576 ----------
577 filename : str, Path
578 The path to the exodus file to read.
579
580 animate_mode_shapes : bool, default: True
581 When ``True`` then this reader will report a continuous time
582 range [0,1] and animate the displacements in a periodic
583 sinusoid.
584
585 apply_displacements : bool, default: True
586 Geometric locations can include displacements. When ``True``,
587 the nodal positions are 'displaced' by the standard exodus
588 displacement vector. If displacements are turned off, the user
589 can explicitly add them by applying a warp filter.
590
591 displacement_magnitude : float, default: 1.0
592 This is a number between 0 and 1 that is used to scale the
593 ``DisplacementMagnitude`` in a sinusoidal pattern.
594
595 read_point_data : bool, default: True
596 Read in data associated with points.
597
598 read_cell_data : bool, default: True
599 Read in data associated with cells.
600
601 enabled_sidesets : Iterable[str | int], optional
602 The name of the array that store the mapping from side set
603 cells back to the global id of the elements they bound.
604
605 Returns
606 -------
607 pyvista.DataSet
608 Wrapped PyVista dataset.
609
610 Examples
611 --------
612 >>> import pyvista as pv
613 >>> data = pv.read_exodus('mymesh.exo') # doctest:+SKIP
614
615 """
616 from .helpers import wrap # noqa: PLC0415
617
618 reader = _vtk.vtkExodusIIReader()
619 reader.SetFileName(str(filename))
620 reader.UpdateInformation()
621 reader.SetAnimateModeShapes(animate_mode_shapes)
622 reader.SetApplyDisplacements(apply_displacements)
623 reader.SetDisplacementMagnitude(displacement_magnitude)
624
625 if read_point_data: # read in all point data variables
626 reader.SetAllArrayStatus(_vtk.vtkExodusIIReader.NODAL, 1)
627
628 if read_cell_data: # read in all cell data variables
629 reader.SetAllArrayStatus(_vtk.vtkExodusIIReader.ELEM_BLOCK, 1)
630
631 if enabled_sidesets is None:
632 enabled_sidesets = list(range(reader.GetNumberOfSideSetArrays()))
633
634 for sideset in enabled_sidesets:
635 if isinstance(sideset, int):
636 name = reader.GetSideSetArrayName(sideset)
637 elif isinstance(sideset, str):
638 name = sideset
639 else:
640 msg = f'Could not parse sideset ID/name: {sideset} with type {type(sideset)}' # type: ignore[unreachable]
641 raise TypeError(msg)
642
643 reader.SetSideSetArrayStatus(name, 1)
644
645 reader.Update()
646 return cast('pv.DataSet', wrap(reader.GetOutput()))
647
648
649 @_deprecate_positional_args(allowed=['filename'])
650 def read_grdecl(
651 filename: str | Path,
652 elevation: bool = True, # noqa: FBT001, FBT002
653 other_keywords: Sequence[str] | None = None,
654 ) -> ExplicitStructuredGrid:
655 """Read a GRDECL file (``'.GRDECL'``).
656
657 Parameters
658 ----------
659 filename : str | Path
660 The path to the GRDECL file to read.
661
662 elevation : bool, default: True
663 If True, convert depths to elevations and flip grid along Z axis.
664
665 other_keywords : sequence[str], optional
666 Additional keywords to read that are ignored by default.
667
668 Returns
669 -------
670 pyvista.ExplicitStructuredGrid
671 Output explicit structured grid.
672
673 Examples
674 --------
675 Read a ``'.GRDECL'`` file.
676
677 >>> import pyvista as pv
678 >>> grid = pv.read('file.GRDECL') # doctest:+SKIP
679
680 Unused keywords contained in the file are stored in :attr:`pyvista.DataObject.user_dict`:
681
682 >>> grid.user_dict # doctest:+SKIP
683 {"MAPUNITS": ..., "GRIDUNIT": ..., ...}
684
685 """
686 property_keywords = (
687 'ACTNUM',
688 'COORD',
689 'ZCORN',
690 'PERMEABILITY',
691 'PERMX',
692 'PERMY',
693 'PERMZ',
694 'POROSITY',
695 'PORO',
696 'LAYERS',
697 'ZONES',
698 )
699
700 @overload
701 def read_keyword(
702 f: TextIO,
703 split: Literal[True] = True, # noqa: FBT002
704 converter: type = ...,
705 ) -> list[str]: ...
706 @overload
707 def read_keyword(f: TextIO, split: Literal[False] = False, converter: type = ...) -> str: ... # noqa: FBT002
708 @overload
709 def read_keyword(f: TextIO, split: bool = ..., converter: type = ...) -> list[str]: ... # noqa: FBT001
710 @_deprecate_positional_args(allowed=['f'])
711 def read_keyword(
712 f: TextIO,
713 split: bool = True, # noqa: FBT001, FBT002
714 converter: type | None = None,
715 ) -> str | list[str]:
716 """Read a keyword.
717
718 Parameters
719 ----------
720 f : TextIO
721 File buffer.
722
723 split : bool, default: True
724 If True, split strings.
725
726 converter : callable, optional
727 Function to apply to split strings.
728
729 Returns
730 -------
731 output : list | str
732 A list or a string.
733
734 """
735 out: list[str] = []
736
737 while True:
738 line = f.readline().strip()
739
740 if line.endswith('/'):
741 line = line[:-1].strip()
742
743 if line:
744 end = True
745
746 else:
747 break
748
749 elif line.startswith('--') or not line:
750 continue
751
752 else:
753 end = False
754
755 if split:
756 line_ = line.split()
757 out += [converter(x) for x in line_] if converter is not None else line_
758
759 else:
760 out.append(line)
761
762 if end:
763 break
764
765 if not split:
766 return ' '.join(out)
767
768 return out
769
770 def read_buffer(
771 f: TextIO, other_keywords: Sequence[str]
772 ) -> tuple[dict[str, Any], Sequence[str]]:
773 """Read a file buffer.
774
775 Parameters
776 ----------
777 f : TextIO
778 File buffer.
779
780 other_keywords : sequence[str], optional
781 Additional keywords to read that are ignored by default.
782
783 Returns
784 -------
785 dict
786 Dictionary of read keywords.
787
788 sequence[str]
789 Included file names.
790
791 """
792 keys: Sequence[str] = list(property_keywords) + list(other_keywords)
793 keys = tuple(keys)
794
795 keywords: dict[str, str | list[Any]] = {}
796 includes = []
797
798 for line in f:
799 line_ = line.strip()
800
801 if line_.startswith('MAPUNITS'):
802 keywords['MAPUNITS'] = read_keyword(f, split=False).replace("'", '').strip()
803
804 elif line_.startswith('MAPAXES'):
805 keywords['MAPAXES'] = read_keyword(f, converter=float)
806
807 elif line_.startswith('GRIDUNIT'):
808 keywords['GRIDUNIT'] = read_keyword(f, split=False).replace("'", '').strip()
809
810 elif line_.startswith('SPECGRID'):
811 data = read_keyword(f)
812 keywords['SPECGRID'] = [
813 int(data[0]),
814 int(data[1]),
815 int(data[2]),
816 int(data[3]),
817 data[4].strip(),
818 ]
819
820 elif line_.startswith('INCLUDE'):
821 filename = read_keyword(f, split=False)
822 includes.append(filename.replace("'", ''))
823
824 elif line_.startswith(keys):
825 key = line.split()[0]
826 data = read_keyword(f)
827
828 if key in property_keywords:
829 keywords[key] = []
830
831 for x in data:
832 if '*' in x:
833 size, new_x = x.split('*')
834 keywords[key] += int(size) * [float(new_x)] # type: ignore[operator]
835
836 else:
837 keywords[key].append(float(x)) # type: ignore[union-attr]
838
839 else:
840 keywords[key] = data
841
842 return keywords, includes
843
844 def read_keywords(filename: str | Path, other_keywords: Sequence[str]) -> dict[str, Any]:
845 """Read a GRDECL file and return its keywords.
846
847 Parameters
848 ----------
849 filename : str | Path
850 The path to the GRDECL file to read.
851
852 other_keywords : sequence[str], optional
853 Additional keywords to read that are ignored by default.
854
855 Returns
856 -------
857 dict
858 Dictionary of read keywords.
859
860 """
861 with Path.open(Path(filename)) as f:
862 keywords, includes = read_buffer(f, other_keywords)
863
864 if includes:
865 path = Path(filename).parent
866
867 for include in includes:
868 with Path.open(path / include) as f:
869 keywords_, _ = read_buffer(f, other_keywords)
870
871 keywords.update(keywords_)
872
873 return keywords
874
875 # Read keywords
876 other_keywords = other_keywords or []
877 keywords = read_keywords(filename, other_keywords)
878
879 try:
880 ni, nj, nk = keywords['SPECGRID'][:3]
881 cylindric = keywords['SPECGRID'][4] == 'T'
882
883 if cylindric:
884 msg = 'Cylindric grids are not supported.'
885 raise TypeError(msg)
886
887 except KeyError:
888 msg = "Unable to generate grid without keyword 'SPECGRID'."
889 raise ValueError(msg)
890
891 relative = False
892
893 if 'GRIDUNIT' in keywords:
894 grid_unit = keywords['GRIDUNIT'].lower()
895
896 if not grid_unit.endswith('map'):
897 try:
898 cond1 = grid_unit.startswith(keywords['MAPUNITS'].lower())
899
900 if not cond1:
901 warn_external(
902 'Unable to convert relative coordinates with different '
903 'grid and map units. Skipping conversion.',
904 )
905
906 except KeyError:
907 warn_external(
908 "Unable to convert relative coordinates without keyword 'MAPUNITS'. "
909 'Skipping conversion.',
910 )
911 cond1 = False
912
913 try:
914 origin = keywords['MAPAXES'][2:4]
915
916 except KeyError:
917 warn_external(
918 "Unable to convert relative coordinates without keyword 'MAPAXES'. "
919 'Skipping conversion.',
920 )
921 origin = None
922
923 relative = cond1 and origin is not None
924
925 # Pillars and Z corner points
926 pillars = np.reshape(keywords['COORD'], ((ni + 1) * (nj + 1), 6), order='C')
927 zcorners = np.reshape(keywords['ZCORN'], (2 * ni, 2 * nj, 2 * nk), order='F')
928
929 # Convert depth to elevation
930 if elevation:
931 zcorners = -zcorners[..., ::-1]
932 pillars[:, [2, 5]] *= -1.0
933 pillars[:] = pillars[:, [3, 4, 5, 0, 1, 2]]
934
935 # Shift relative to absolute units
936 if relative:
937 pillars[:, [0, 3]] += origin[0]
938 pillars[:, [1, 4]] += origin[1]
939
940 # Interpolate X and Y corner points
941 xcorners = np.empty_like(zcorners)
942 ycorners = np.empty_like(zcorners)
943
944 for i, j in itertools.product(range(2 * ni), range(2 * nj)):
945 ip = np.ravel_multi_index(((i + 1) // 2, (j + 1) // 2), (ni + 1, nj + 1), order='F')
946 z = pillars[ip, [2, 5]]
947 xcorners[i, j] = np.interp(zcorners[i, j], z, pillars[ip, [0, 3]])
948 ycorners[i, j] = np.interp(zcorners[i, j], z, pillars[ip, [1, 4]])
949
950 # Generate explicit structured grid
951 dims = ni + 1, nj + 1, nk + 1
952 corners = np.column_stack(
953 (
954 xcorners.ravel(order='F'),
955 ycorners.ravel(order='F'),
956 zcorners.ravel(order='F'),
957 )
958 )
959 grid = pv.ExplicitStructuredGrid(dims, corners)
960
961 # Add property data
962 for key in property_keywords:
963 if key in {'ACTNUM', 'COORD', 'ZCORN'}:
964 continue
965
966 if key in keywords:
967 v = keywords[key]
968
969 if elevation:
970 v = np.reshape(v, (ni, nj, nk), order='F')
971 v = v[..., ::-1].ravel(order='F')
972
973 grid[key] = v
974
975 # Active cells
976 if 'ACTNUM' in keywords:
977 active = np.array(keywords['ACTNUM']) > 0.0
978 grid.hide_cells(~active, inplace=True) # type: ignore[arg-type]
979
980 # Store unused keywords in user dict
981 grid.user_dict = {k: v for k, v in keywords.items() if k not in property_keywords}
982
983 return grid
984
985
986 def read_pickle(filename: str | Path) -> DataObject:
987 """Load a pickled mesh from file.
988
989 Parameters
990 ----------
991 filename : str
992 The path of the pickled mesh to read.
993
994 Returns
995 -------
996 pyvista.DataObject
997 Unpickled mesh.
998
999 Examples
1000 --------
1001 Save a pickled mesh and read it.
1002
1003 >>> import pyvista as pv
1004 >>> from pyvista import examples
1005 >>> mesh = examples.load_ant()
1006 >>> pv.save_pickle('ant.pkl', mesh)
1007 >>> new_mesh = pv.read_pickle('ant.pkl')
1008 >>> new_mesh
1009 PolyData (...)
1010 N Cells: 912
1011 N Points: 486
1012 N Strips: 0
1013 X Bounds: -1.601e+01, 1.601e+01
1014 Y Bounds: -9.385e+00, 9.385e+00
1015 Z Bounds: -1.678e+01, 1.678e+01
1016 N Arrays: 0
1017
1018 Unlike other file formats, custom attributes are saved with pickled meshes.
1019
1020 >>> pv.set_new_attribute(mesh, 'custom_attribute', 42)
1021 >>> pv.save_pickle('ant.pkl', mesh)
1022 >>> new_mesh = pv.read_pickle('ant.pkl')
1023 >>> new_mesh.custom_attribute
1024 42
1025
1026 """
1027 filename_str = str(filename)
1028 if filename_str.endswith(PICKLE_EXT):
1029 with open(filename_str, 'rb') as f: # noqa: PTH123
1030 mesh = pickle.load(f)
1031
1032 if not isinstance(mesh, pv.DataObject):
1033 msg = (
1034 f'Pickled object must be an instance of {pv.DataObject}. '
1035 f'Got {mesh.__class__} instead.'
1036 )
1037 raise TypeError(msg)
1038 return mesh
1039 msg = f'Filename must be a file path with extension {PICKLE_EXT}. Got {filename} instead.'
1040 raise ValueError(msg)
1041
1042
1043 def save_pickle(filename: str | Path, mesh: DataObject) -> None:
1044 """Pickle a mesh and save it to file.
1045
1046 Parameters
1047 ----------
1048 filename : str
1049 The path of the pickled mesh to save, including the extension ``'.pkl'``
1050 or ``'.pickle'``.
1051
1052 mesh : pyvista.DataObject
1053 Any PyVista mesh.
1054
1055 Examples
1056 --------
1057 Save a pickled mesh and read it.
1058
1059 >>> import pyvista as pv
1060 >>> from pyvista import examples
1061 >>> mesh = examples.load_ant()
1062 >>> pv.save_pickle('ant.pkl', mesh)
1063 >>> new_mesh = pv.read_pickle('ant.pkl')
1064 >>> new_mesh
1065 PolyData (...)
1066 N Cells: 912
1067 N Points: 486
1068 N Strips: 0
1069 X Bounds: -1.601e+01, 1.601e+01
1070 Y Bounds: -9.385e+00, 9.385e+00
1071 Z Bounds: -1.678e+01, 1.678e+01
1072 N Arrays: 0
1073
1074 Unlike other file formats, custom attributes are saved with pickled meshes.
1075
1076 >>> pv.set_new_attribute(mesh, 'custom_attribute', 42)
1077 >>> pv.save_pickle('ant.pkl', mesh)
1078 >>> new_mesh = pv.read_pickle('ant.pkl')
1079 >>> new_mesh.custom_attribute
1080 42
1081
1082 """
1083 filename_str = str(filename)
1084 if not filename_str.endswith(PICKLE_EXT):
1085 filename_str += '.pkl'
1086 if not isinstance(mesh, pv.DataObject):
1087 msg = ( # type: ignore[unreachable]
1088 f'Only {pv.DataObject} are supported for pickling. Got {mesh.__class__} instead.'
1089 )
1090 raise TypeError(msg)
1091 _warn_multiblock_nested_field_data(mesh)
1092 with open(filename_str, 'wb') as f: # noqa: PTH123
1093 pickle.dump(mesh, f)
1094
1095
1096 def is_meshio_mesh(obj: object) -> bool:
1097 """Test if passed object is an instance of :class:`meshio.Mesh`.
1098
1099 Parameters
1100 ----------
1101 obj : object
1102 Any object.
1103
1104 Returns
1105 -------
1106 bool
1107 ``True`` if ``obj`` is a :class:`meshio.Mesh`.
1108
1109 """
1110 try:
1111 import meshio # noqa: PLC0415
1112
1113 return isinstance(obj, meshio.Mesh)
1114 except ImportError:
1115 return False
1116
1117
1118 def is_trimesh_mesh(obj: object) -> bool:
1119 """Test if passed object is an instance of :class:`trimesh.Trimesh`.
1120
1121 .. versionadded:: 0.47
1122
1123 Parameters
1124 ----------
1125 obj : object
1126 Any object.
1127
1128 Returns
1129 -------
1130 bool
1131 ``True`` if ``obj`` is a :class:`trimesh.Trimesh`.
1132
1133 """
1134 try:
1135 import trimesh # noqa: PLC0415
1136
1137 return isinstance(obj, trimesh.Trimesh)
1138 except ImportError:
1139 return False
1140
1141
1142 def from_meshio(mesh: meshio.Mesh) -> UnstructuredGrid:
1143 """Convert a ``meshio`` mesh instance to a PyVista mesh.
1144
1145 Parameters
1146 ----------
1147 mesh : meshio.Mesh
1148 A mesh instance from the ``meshio`` library.
1149
1150 Returns
1151 -------
1152 pyvista.UnstructuredGrid
1153 A PyVista unstructured grid representation of the input ``meshio`` mesh.
1154
1155 Raises
1156 ------
1157 ImportError
1158 If the appropriate version of ``meshio`` library is not found.
1159
1160 """
1161 try: # meshio<5.0 compatibility
1162 from meshio.vtk._vtk import meshio_to_vtk_type # noqa: PLC0415
1163 from meshio.vtk._vtk import vtk_type_to_numnodes # noqa: PLC0415
1164 except ImportError: # pragma: no cover
1165 from meshio._vtk_common import meshio_to_vtk_type # noqa: PLC0415
1166 from meshio.vtk._vtk_42 import vtk_type_to_numnodes # noqa: PLC0415
1167
1168 if len(mesh.cells) == 0:
1169 # Empty mesh
1170 grid = pv.UnstructuredGrid()
1171 if mesh.points.size > 0:
1172 grid.points = mesh.points
1173 return grid
1174
1175 # Extract cells from meshio.Mesh object
1176 cells = []
1177 cell_type = []
1178 for c in mesh.cells:
1179 if c.type.startswith('polyhedron'):
1180 vtk_type = meshio_to_vtk_type['polyhedron']
1181
1182 for cell in c.data:
1183 connectivity = [len(cell)]
1184 for face in cell:
1185 connectivity += [len(face), *face]
1186
1187 connectivity.insert(0, len(connectivity))
1188 cells.append(connectivity)
1189
1190 else:
1191 vtk_type = meshio_to_vtk_type[c.type]
1192 numnodes = vtk_type_to_numnodes[vtk_type]
1193 if numnodes == -1:
1194 # Count nodes in each cell
1195 fill_values = np.array([[len(data)] for data in c.data], dtype=c.data.dtype) # type: ignore[union-attr]
1196 else:
1197 fill_values = np.full((len(c.data), 1), numnodes, dtype=c.data.dtype) # type: ignore[union-attr]
1198 cells.append(np.hstack((fill_values, c.data)).ravel()) # type: ignore[arg-type]
1199
1200 cell_type += [vtk_type] * len(c.data)
1201
1202 # Convert cell sets to cell data
1203 if mesh.cell_sets:
1204 mesh.cell_sets_to_data()
1205
1206 # Extract cell data from meshio.Mesh object
1207 cell_data = {k: np.concatenate(v) for k, v in mesh.cell_data.items()}
1208
1209 # Create pyvista.UnstructuredGrid object
1210 points = mesh.points
1211
1212 # Convert to 3D if points are 2D
1213 if points.shape[1] == 2:
1214 zero_points = np.zeros((len(points), 1), dtype=points.dtype)
1215 points = np.hstack((points, zero_points))
1216
1217 grid = pv.UnstructuredGrid(
1218 np.concatenate(cells).astype(np.int64, copy=False),
1219 np.array(cell_type),
1220 np.array(points, np.float64),
1221 )
1222
1223 # Set point data
1224 grid.point_data.update({k: np.array(v, np.float64) for k, v in mesh.point_data.items()})
1225
1226 # Set cell data
1227 grid.cell_data.update(cell_data)
1228
1229 # Call datatype-specific post-load processing
1230 grid._post_file_load_processing()
1231
1232 return grid
1233
1234
1235 def to_meshio(mesh: DataSet) -> meshio.Mesh:
1236 """Convert a PyVista mesh to a ``meshio`` mesh instance.
1237
1238 .. versionadded:: 0.45
1239
1240 Parameters
1241 ----------
1242 mesh : pyvista.DataSet
1243 Any PyVista mesh/spatial data type.
1244
1245 Returns
1246 -------
1247 meshio.Mesh
1248 A mesh instance from the ``meshio`` library.
1249
1250 Raises
1251 ------
1252 ImportError
1253 If the meshio package is not installed.
1254
1255 See Also
1256 --------
1257 from_meshio, read_meshio, save_meshio, :func:`~pyvista.wrap`
1258
1259 Examples
1260 --------
1261 Convert a pyvista sphere to a ``meshio`` mesh instance.
1262
1263 >>> import pyvista as pv
1264 >>> sphere = pv.Sphere()
1265 >>> mesh = pv.to_meshio(sphere)
1266
1267 """
1268 try:
1269 import meshio # noqa: PLC0415
1270
1271 except ImportError: # pragma: no cover
1272 msg = 'To use this feature install meshio with:\n\npip install meshio'
1273 raise ImportError(msg)
1274
1275 try: # for meshio<5.0 compatibility
1276 from meshio.vtk._vtk import vtk_to_meshio_type # noqa: PLC0415
1277
1278 except (ImportError, AttributeError): # pragma: no cover
1279 from meshio._vtk_common import vtk_to_meshio_type # noqa: PLC0415
1280
1281 # Cast to unstructured grid
1282 mesh = mesh if isinstance(mesh, pv.UnstructuredGrid) else mesh.cast_to_unstructured_grid()
1283 mesh = (
1284 mesh.extract_cells(mesh.cell_data['vtkGhostType'] == 0)
1285 if 'vtkGhostType' in mesh.cell_data
1286 else mesh
1287 )
1288 if mesh.is_empty:
1289 return meshio.Mesh(mesh.points, [])
1290
1291 vtk_celltypes = mesh.celltypes
1292 connectivity = mesh.cell_connectivity
1293
1294 # Generate polyhedral cell faces if any
1295 def split(arr: VectorLike[int]) -> list[VectorLike[int]]:
1296 i = 0
1297 offsets: list[int] = [0]
1298
1299 while i < len(arr):
1300 offsets.append(int(arr[i]) + 1)
1301 i += offsets[-1]
1302
1303 offsets_ = np.cumsum(offsets)
1304
1305 return [arr[i1 + 1 : i2] for i1, i2 in itertools.pairwise(offsets_)]
1306
1307 polyhedron_faces = split(mesh.polyhedron_faces)
1308
1309 if polyhedron_faces:
1310 polyhedron_locations = split(mesh.polyhedron_face_locations)
1311 polyhedral_cell_faces: list[list[VectorLike[int]]] = [
1312 [polyhedron_faces[face] for face in cell] for cell in polyhedron_locations
1313 ]
1314
1315 # Single cell type (except POLYGON and POLYHEDRON)
1316 if vtk_celltypes.min() == vtk_celltypes.max() and vtk_celltypes[0] not in {
1317 pv.CellType.POLYGON,
1318 pv.CellType.POLYHEDRON,
1319 }:
1320 vtk_celltype = vtk_celltypes[0]
1321 cells = connectivity.reshape((mesh.n_cells, connectivity.size // mesh.n_cells))
1322
1323 if vtk_celltype == pv.CellType.PIXEL:
1324 cells = cells[:, [0, 1, 3, 2]]
1325 celltype = 'quad'
1326
1327 elif vtk_celltype == pv.CellType.VOXEL:
1328 cells = cells[:, [0, 1, 3, 2, 4, 5, 7, 6]]
1329 celltype = 'hexahedron'
1330
1331 else:
1332 celltype = vtk_to_meshio_type[vtk_celltype]
1333
1334 cells = [(celltype, cells)]
1335
1336 # Mixed cell types
1337 else:
1338 cells = []
1339 offset = mesh.offset
1340
1341 for i, (i1, i2, vtk_celltype) in enumerate(
1342 zip(offset[:-1], offset[1:], vtk_celltypes, strict=False)
1343 ):
1344 cell = connectivity[i1:i2]
1345
1346 if vtk_celltype == pv.CellType.POLYHEDRON:
1347 celltype = f'polyhedron{len(cell)}'
1348 cell = polyhedral_cell_faces[i]
1349
1350 # Handle the missing voxel key (11) in vtk_to_meshio_type
1351 elif vtk_celltype == pv.CellType.VOXEL:
1352 celltype = 'hexahedron'
1353 cell = cell[[0, 1, 3, 2, 4, 5, 7, 6]]
1354
1355 # Handle the missing "pixel" key in meshio._mesh.topological_dimension
1356 elif vtk_celltype == pv.CellType.PIXEL:
1357 celltype = 'quad'
1358 cell = cell[[0, 1, 3, 2]]
1359
1360 else:
1361 celltype = (
1362 f'polygon{len(cell)}'
1363 if vtk_celltype == pv.CellType.POLYGON
1364 else vtk_to_meshio_type[vtk_celltype]
1365 )
1366
1367 if len(cells) > 0 and cells[-1][0] == celltype:
1368 cells[-1][1].append(cell)
1369
1370 else:
1371 cells.append((celltype, [cell]))
1372
1373 cells = [
1374 (celltype if not celltype.startswith('polygon') else 'polygon', celldata)
1375 for celltype, celldata in cells
1376 ]
1377
1378 # Point data
1379 point_data = {k.replace(' ', '_'): v for k, v in mesh.point_data.items()}
1380
1381 # Cell data
1382 vtk_cell_data = mesh.cell_data
1383 indices = np.insert(np.cumsum([len(c[1]) for c in cells]), 0, 0)
1384 cell_data = {
1385 k.replace(' ', '_'): [v[i1:i2] for i1, i2 in itertools.pairwise(indices)]
1386 for k, v in vtk_cell_data.items()
1387 }
1388
1389 return meshio.Mesh(mesh.points, cells, point_data=point_data, cell_data=cell_data)
1390
1391
1392 def read_meshio(filename: str | Path, file_format: str | None = None) -> UnstructuredGrid:
1393 """Read any mesh file using meshio.
1394
1395 Parameters
1396 ----------
1397 filename : str
1398 The name of the file to read. It should include the file extension.
1399 file_format : str, optional
1400 The format of the file to read. If not provided, the file format will
1401 be inferred from the file extension.
1402
1403 Returns
1404 -------
1405 UnstructuredGrid
1406 The mesh read from the file.
1407
1408 Raises
1409 ------
1410 ImportError
1411 If the meshio package is not installed.
1412
1413 """
1414 try:
1415 import meshio # noqa: PLC0415
1416 except ImportError: # pragma: no cover
1417 msg = 'To use this feature install meshio with:\n\npip install meshio'
1418 raise ImportError(msg)
1419
1420 # Make sure relative paths will work
1421 filename = Path(filename).expanduser().resolve()
1422 # Read mesh file
1423 mesh = meshio.read(filename, file_format)
1424 return from_meshio(mesh)
1425
1426
1427 def save_meshio(
1428 filename: str | Path, mesh: DataSet, file_format: str | None = None, **kwargs
1429 ) -> None:
1430 """Save mesh to file using meshio.
1431
1432 Parameters
1433 ----------
1434 filename : str
1435 Filename to save the mesh to.
1436
1437 mesh : pyvista.DataSet
1438 Any PyVista mesh/spatial data type.
1439
1440 file_format : str, optional
1441 File type for meshio to save. For example ``'.bdf'``. This
1442 is normally inferred from the extension but this can be
1443 overridden.
1444
1445 **kwargs : dict, optional
1446 Additional keyword arguments. See
1447 ``meshio.Mesh.write`` for more details.
1448
1449 Examples
1450 --------
1451 Save a pyvista sphere to a Abaqus data file.
1452
1453 >>> import pyvista as pv
1454 >>> sphere = pv.Sphere()
1455 >>> pv.save_meshio('mymesh.inp', sphere) # doctest:+SKIP
1456
1457 """
1458 # Make sure relative paths will work
1459 filename = Path(filename).expanduser().resolve()
1460
1461 # Save using meshio
1462 to_meshio(mesh).write(filename, file_format=file_format, **kwargs)
1463
1464
1465 def _process_filename(filename: str | Path) -> Path:
1466 return Path(filename).expanduser().resolve()
1467
1468
1469 def _try_imageio_imread(filename: str | Path) -> imageio.core.util.Array:
1470 """Attempt to read a file using ``imageio.imread``.
1471
1472 Parameters
1473 ----------
1474 filename : str, Path
1475 Name of the file to read using ``imageio``.
1476
1477 Returns
1478 -------
1479 imageio.core.util.Array
1480 Image read from ``imageio``.
1481
1482 Raises
1483 ------
1484 ModuleNotFoundError
1485 Raised when ``imageio`` is not installed when attempting to read
1486 ``filename``.
1487
1488 """
1489 try:
1490 from imageio.v2 import imread # noqa: PLC0415
1491 except ModuleNotFoundError: # pragma: no cover
1492 msg = (
1493 'Problem reading the image with VTK. Install imageio to try to read the '
1494 'file using imageio with:\n\n'
1495 ' pip install imageio'
1496 )
1497 raise ModuleNotFoundError(msg) from None
1498
1499 return imread(filename)
1500
1501
1502 def _validate_pass_data(pass_data: _PassDataOptions) -> tuple[bool, bool, bool]:
1503 pass_point_data = pass_cell_data = pass_field_data = False
1504 if pass_data is True:
1505 pass_point_data = pass_cell_data = pass_field_data = True
1506 elif pass_data:
1507 if isinstance(pass_data, str):
1508 if pass_data == 'point':
1509 pass_point_data = True
1510 elif pass_data == 'cell':
1511 pass_cell_data = True
1512 elif pass_data == 'field':
1513 pass_field_data = True
1514 elif isinstance(pass_data, Sequence):
1515 if 'point' in pass_data:
1516 pass_point_data = True
1517 if 'cell' in pass_data:
1518 pass_cell_data = True
1519 if 'field' in pass_data:
1520 pass_field_data = True
1521
1522 if not (pass_point_data or pass_cell_data or pass_field_data) and pass_data is not False:
1523 # Input is not valid
1524 allowed = [True, False, 'point', 'cell', 'field']
1525 _validation.check_contains(allowed, must_contain=pass_data, name='pass_data')
1526
1527 return pass_point_data, pass_cell_data, pass_field_data
1528
1529
1530 def from_trimesh(
1531 mesh: trimesh.Trimesh, *, pass_data: _PassDataOptions = True
1532 ) -> PolyData: # numpydoc ignore=RT01
1533 """Convert a Trimesh mesh to a PyVista mesh.
1534
1535 - ``vertex_attributes`` are stored as point data.
1536 - ``face_attributes`` are stored as cell data.
1537 - ``metadata`` is stored as field data: NumPy arrays are stored directly as field data
1538 arrays, and any other metadata (e.g. strings or lists) is stored in the
1539 :attr:`~pyvista.DataObject.user_dict`.
1540
1541 .. note::
1542
1543 No copies of point, cell, or data arrays are made. Use :meth:`~pyvista.DataObject.copy`
1544 after converting to avoid any side effects.
1545
1546 .. versionadded:: 0.47
1547
1548 Parameters
1549 ----------
1550 mesh : trimesh.Trimesh
1551 Trimesh object to convert.
1552
1553 pass_data : bool | str | sequence[str], default: True
1554 Pass point, cell, and/or field data from the Trimesh object. All data is passed by default.
1555 Set this to ``'point'``, ``'cell'``, ``'field'`` or any combination thereof to only pass
1556 specific fields.
1557
1558 See Also
1559 --------
1560 to_trimesh, from_meshio, :func:`~pyvista.wrap`
1561
1562 Examples
1563 --------
1564 See :ref:`wrap_trimesh_example` for examples.
1565
1566 """
1567 try:
1568 import trimesh # noqa: PLC0415
1569 except ImportError: # pragma: no cover
1570 msg = 'To use this feature install trimesh with:\n\npip install trimesh'
1571 raise ImportError(msg)
1572 else:
1573 _validation.check_instance(mesh, trimesh.Trimesh, name='mesh')
1574
1575 # Handle case with no faces
1576 faces: NumpyArray[int] = mesh.faces
1577 if faces.size == 0:
1578 faces = faces.reshape((0, 3))
1579 # Trimesh doesn't pad faces
1580 polydata = pv.PolyData.from_regular_faces(mesh.vertices, faces=faces, deep=False)
1581
1582 pass_point_data, pass_cell_data, pass_field_data = _validate_pass_data(pass_data)
1583
1584 if pass_point_data:
1585 # Set texture coordinates
1586 if (
1587 hasattr(visual := mesh.visual, 'uv')
1588 and visual is not None
1589 and (uv := visual.uv) is not None
1590 ):
1591 polydata.active_texture_coordinates = uv
1592 polydata.point_data.update(mesh.vertex_attributes, copy=False)
1593
1594 if pass_cell_data:
1595 polydata.cell_data.update(mesh.face_attributes, copy=False)
1596
1597 if pass_field_data:
1598 for key, val in mesh.metadata.items():
1599 if isinstance(val, np.ndarray):
1600 polydata.field_data[key] = val
1601 else:
1602 try:
1603 json.dumps(val)
1604 except TypeError:
1605 msg = (
1606 f'Unable to store metadata key {key!r} with value type {type(val)}.\n'
1607 f'Only NumPy arrays or JSON-serializable values are supported.'
1608 )
1609 warn_external(msg)
1610 else:
1611 polydata.user_dict[key] = val
1612
1613 return polydata
1614
1615
1616 def to_trimesh( # numpydoc ignore=RT01
1617 mesh: DataSet,
1618 *,
1619 triangulate: bool = False,
1620 pass_data: _PassDataOptions = True,
1621 ) -> trimesh.Trimesh:
1622 """Convert a PyVista mesh to a Trimesh mesh.
1623
1624 - Point data is stored as ``vertex_attributes``.
1625 - Cell data is stored as ``face_attributes``.
1626 - Field data is stored as ``metadata``. Any :attr:`~pyvista.DataObject.user_dict` keys
1627 are stored directly as metadata.
1628
1629 .. note::
1630
1631 No copies of point, cell, or data arrays are made. Use :meth:`~pyvista.DataObject.copy`
1632 before converting to avoid any side effects.
1633
1634 .. versionadded:: 0.47
1635
1636 Parameters
1637 ----------
1638 mesh : DataSet
1639 Dataset to convert.
1640
1641 triangulate : bool, default: False
1642 Triangulate the mesh before conversion. If the mesh has 3D cells, the mesh's surface
1643 is extracted. All 2D polygonal cells are triangulated as required, and all 0D and 1D
1644 cells or any unused points are ignored.
1645
1646 pass_data : bool | str | sequence[str], default: True
1647 Pass point, cell, and/or field data to the Trimesh object. All data is passed by default.
1648 Set this to ``'point'``, ``'cell'``, ``'field'`` or any combination thereof to only pass
1649 specific fields.
1650
1651 See Also
1652 --------
1653 from_trimesh, to_meshio, :func:`~pyvista.wrap`
1654
1655 Examples
1656 --------
1657 See :ref:`wrap_trimesh_example` for examples.
1658
1659 """
1660 try:
1661 import trimesh # noqa: PLC0415
1662 from trimesh.visual import TextureVisuals # noqa: PLC0415
1663 except ImportError: # pragma: no cover
1664 msg = 'To use this feature install trimesh with:\n\npip install trimesh'
1665 raise ImportError(msg)
1666
1667 # Avoid circular import
1668 from pyvista.core.dataobject import USER_DICT_KEY # noqa: PLC0415
1669
1670 _validation.check_instance(mesh, pv.DataSet, name='mesh')
1671
1672 if isinstance(mesh, pv.PolyData):
1673 is_all_triangles = mesh.is_all_triangles
1674 elif isinstance(mesh, pv.UnstructuredGrid):
1675 is_all_triangles = mesh.distinct_cell_types == {pv.CellType.TRIANGLE}
1676 elif mesh.is_empty:
1677 is_all_triangles = True
1678 else:
1679 is_all_triangles = False
1680
1681 if not is_all_triangles and not triangulate:
1682 msg = (
1683 'Mesh must be all triangles to convert to Trimesh object.\n'
1684 'Use `triangulate=True` to automatically convert to a triangle surface mesh.'
1685 )
1686 raise pv.NotAllTrianglesError(msg)
1687
1688 surf = (
1689 mesh
1690 if isinstance(mesh, pv.PolyData)
1691 else mesh.extract_surface(algorithm=None, pass_pointid=False, pass_cellid=False)
1692 )
1693 surf = surf if is_all_triangles else surf.triangulate()
1694
1695 pass_point_data, pass_cell_data, pass_field_data = _validate_pass_data(pass_data)
1696
1697 if pass_point_data:
1698 vertex_attributes = dict((point_data := mesh.point_data).items())
1699 vertex_normals = vertex_attributes.pop(point_data.active_normals_name, None) # type: ignore[arg-type]
1700 # Store texture coordinates
1701 texture_coordinates = vertex_attributes.pop(
1702 point_data.active_texture_coordinates_name, # type: ignore[arg-type]
1703 None,
1704 )
1705 visual = (
1706 TextureVisuals(uv=texture_coordinates) if texture_coordinates is not None else None
1707 )
1708 else:
1709 vertex_attributes = None
1710 vertex_normals = None
1711 visual = None
1712
1713 if pass_cell_data:
1714 face_attributes = dict((cell_data := mesh.cell_data).items())
1715 face_normals = face_attributes.pop(cell_data.active_normals_name, None) # type: ignore[arg-type]
1716 else:
1717 face_attributes = None
1718 face_normals = None
1719
1720 if pass_field_data:
1721 metadata = dict(mesh.field_data.items())
1722 if USER_DICT_KEY in metadata.keys():
1723 metadata.pop(USER_DICT_KEY)
1724 metadata.update(mesh.user_dict)
1725 else:
1726 metadata = None
1727
1728 return trimesh.Trimesh(
1729 vertices=surf.points,
1730 faces=surf.regular_faces,
1731 vertex_normals=vertex_normals,
1732 face_normals=face_normals,
1733 face_attributes=face_attributes, # type: ignore[arg-type]
1734 vertex_attributes=vertex_attributes, # type: ignore[arg-type]
1735 metadata=metadata,
1736 visual=visual,
1737 process=False,
1738 )