Debian Codegraph @

pyvista/core/utilities/arrays.py

raw
1 """Internal array utilities."""
2
3 from __future__ import annotations
4
5 from collections import UserDict
6 from collections.abc import Sequence
7 import enum
8 from itertools import product
9 import json
10 from typing import TYPE_CHECKING
11 from typing import Any
12 from typing import Literal
13 from typing import cast
14 from typing import overload
15
16 import numpy as np
17 import numpy.typing as npt
18
19 import pyvista as pv
20 from pyvista import _vtk
21 from pyvista._deprecate_positional_args import _deprecate_positional_args
22 from pyvista.core._vtk_utilities import DisableVtkSnakeCase
23 from pyvista.core.errors import AmbiguousDataError
24 from pyvista.core.errors import MissingDataError
25
26 if TYPE_CHECKING:
27 from pyvista import DataSet
28 from pyvista import Table
29 from pyvista import pyvista_ndarray
30 from pyvista.core._typing_core import MatrixLike
31 from pyvista.core._typing_core import NumpyArray
32 from pyvista.core._typing_core import VectorLike
33 from pyvista.core.dataset import _ActiveArrayExistsInfoTuple
34
35
36 class FieldAssociation(enum.Enum):
37 """Represents which type of vtk field a scalar or vector array is associated with."""
38
39 POINT = int(_vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS)
40 CELL = int(_vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS)
41 NONE = int(_vtk.vtkDataObject.FIELD_ASSOCIATION_NONE)
42 ROW = int(_vtk.vtkDataObject.FIELD_ASSOCIATION_ROWS)
43
44
45 PointLiteral = Literal[
46 FieldAssociation.POINT,
47 'point',
48 ]
49 CellLiteral = Literal[FieldAssociation.CELL, 'cell']
50 FieldLiteral = Literal[FieldAssociation.NONE, 'field']
51 RowLiteral = Literal[FieldAssociation.ROW, 'row']
52
53
54 @overload
55 def parse_field_choice(
56 field: PointLiteral | Literal['p', 'points'],
57 ) -> Literal[FieldAssociation.POINT]: ...
58 @overload
59 def parse_field_choice(
60 field: CellLiteral | Literal['c', 'cells'],
61 ) -> Literal[FieldAssociation.CELL]: ...
62 @overload
63 def parse_field_choice(
64 field: FieldLiteral | Literal['f', 'fields'],
65 ) -> Literal[FieldAssociation.NONE]: ...
66 @overload
67 def parse_field_choice(field: RowLiteral | Literal['r']) -> Literal[FieldAssociation.ROW]: ...
68 @overload
69 def parse_field_choice(field: FieldAssociation) -> FieldAssociation: ...
70 def parse_field_choice(
71 field: FieldAssociation
72 | PointLiteral
73 | CellLiteral
74 | FieldLiteral
75 | RowLiteral
76 | Literal['p', 'c', 'f', 'r', 'points', 'cells', 'fields'],
77 ) -> FieldAssociation:
78 """Return a field association object for a given field type string.
79
80 Parameters
81 ----------
82 field : str, FieldAssociation
83 Name of the field (e.g, ``'cell'``, ``'field'``, ``'point'``,
84 ``'row'``).
85
86 Returns
87 -------
88 pyvista.FieldAssociation
89 Field association.
90
91 """
92 if isinstance(field, str):
93 field_ = field.strip().lower()
94 if field_ in ['cell', 'c', 'cells']:
95 return FieldAssociation.CELL
96 elif field_ in ['point', 'p', 'points']:
97 return FieldAssociation.POINT
98 elif field_ in ['field', 'f', 'fields']:
99 return FieldAssociation.NONE
100 elif field_ in ['row', 'r']:
101 return FieldAssociation.ROW
102 else:
103 msg = f'Data field ({field}) not supported.'
104 raise ValueError(msg)
105 elif isinstance(field, FieldAssociation):
106 return field
107 else:
108 msg = f'Data field ({field}) not supported.' # type: ignore[unreachable]
109 raise TypeError(msg)
110
111
112 def _coerce_pointslike_arg(
113 points: MatrixLike[float] | VectorLike[float],
114 *,
115 copy: bool = False,
116 ) -> tuple[NumpyArray[float], bool]:
117 """Check and coerce arg to (n, 3) np.ndarray.
118
119 Parameters
120 ----------
121 points : MatrixLike[float] | VectorLike[float]
122 Argument to coerce into (n, 3) :class:`numpy.ndarray`.
123
124 copy : bool, default: False
125 Whether to copy the ``points`` array. Copying always occurs if ``points``
126 is not :class:`numpy.ndarray`.
127
128 Returns
129 -------
130 numpy.ndarray
131 Size ``(n, 3)`` array.
132 bool
133 Whether the input was a single point in an array-like with shape ``(3,)``.
134
135 """
136 if isinstance(points, Sequence):
137 points = np.asarray(points)
138
139 if not isinstance(points, np.ndarray):
140 msg = 'Given points must be convertible to a numerical array.' # type: ignore[unreachable]
141 raise TypeError(msg)
142
143 if points.ndim > 2:
144 msg = 'Array of points must be 1D or 2D'
145 raise ValueError(msg)
146
147 if points.ndim == 2:
148 if points.shape[1] != 3:
149 msg = 'Array of points must have three values per point (shape (n, 3))'
150 raise ValueError(msg)
151 singular = False
152
153 else:
154 if points.size != 3:
155 msg = 'Given point must have three values'
156 raise ValueError(msg)
157 singular = True
158 points = np.reshape(points, [1, 3])
159
160 if copy:
161 return points.copy(), singular
162 return points, singular
163
164
165 @_deprecate_positional_args(allowed=['array'])
166 def copy_vtk_array(array: _vtk.vtkAbstractArray, deep: bool = True) -> _vtk.vtkAbstractArray: # noqa: FBT001, FBT002
167 """Create a deep or shallow copy of a VTK array.
168
169 Parameters
170 ----------
171 array : :vtk:`vtkAbstractArray`
172 VTK array.
173
174 deep : bool, optional
175 When ``True``, create a deep copy of the array. When ``False``, returns
176 a shallow copy.
177
178 Returns
179 -------
180 :vtk:`vtkAbstractArray`
181 Copy of the original VTK array.
182
183 Examples
184 --------
185 Perform a deep copy of a vtk array.
186
187 >>> import vtk
188 >>> import pyvista as pv
189 >>> arr = vtk.vtkFloatArray()
190 >>> _ = arr.SetNumberOfValues(10)
191 >>> arr.SetValue(0, 1)
192 >>> arr_copy = pv.core.utilities.arrays.copy_vtk_array(arr)
193 >>> arr_copy.GetValue(0)
194 1.0
195
196 """
197 if not isinstance(array, _vtk.vtkAbstractArray):
198 msg = f'Invalid type {type(array)}.' # type: ignore[unreachable]
199 raise TypeError(msg)
200
201 new_array = _vtk.vtkAbstractArray.CreateArray(array.GetDataType())
202
203 if deep:
204 new_array.DeepCopy(array)
205 else:
206 new_array.ShallowCopy(array) # type: ignore[attr-defined]
207
208 return new_array
209
210
211 def has_duplicates(arr: NumpyArray[Any]) -> bool:
212 """Return if an array has any duplicates.
213
214 Parameters
215 ----------
216 arr : numpy.ndarray
217 Array to be checked for duplicates.
218
219 Returns
220 -------
221 bool
222 ``True`` if the array has any duplicates, otherwise ``False``.
223
224 """
225 s = np.sort(arr, axis=None)
226 return (s[1:] == s[:-1]).any()
227
228
229 def raise_has_duplicates(arr: NumpyArray[Any]) -> None:
230 """Raise a ValueError if an array is not unique.
231
232 Parameters
233 ----------
234 arr : numpy.ndarray
235 Array to be checked for duplicates.
236
237 Raises
238 ------
239 ValueError
240 If the array contains duplicate values.
241
242 """
243 if has_duplicates(arr):
244 msg = 'Array contains duplicate values.'
245 raise ValueError(msg)
246
247
248 @overload
249 def convert_array(
250 arr: _vtk.vtkAbstractArray,
251 name: str | None = ...,
252 deep: bool = ..., # noqa: FBT001
253 array_type: int | None = None,
254 ) -> npt.NDArray[Any]: ...
255 @overload
256 def convert_array(
257 arr: npt.ArrayLike,
258 name: str | None = ...,
259 deep: bool = ..., # noqa: FBT001
260 array_type: int | None = None,
261 ) -> _vtk.vtkAbstractArray: ...
262 @overload
263 def convert_array(
264 arr: None,
265 name: str | None = ...,
266 deep: bool = ..., # noqa: FBT001
267 array_type: int | None = ...,
268 ) -> None: ...
269 @_deprecate_positional_args(allowed=['arr', 'name'])
270 def convert_array( # noqa: PLR0917
271 arr: npt.ArrayLike | _vtk.vtkAbstractArray | None,
272 name: str | None = None,
273 deep: bool = False, # noqa: FBT001, FBT002
274 array_type: int | None = None,
275 ) -> npt.NDArray[Any] | _vtk.vtkAbstractArray | None:
276 """Convert a NumPy array to a :vtk:`vtkDataArray` or vice versa.
277
278 Parameters
279 ----------
280 arr : np.ndarray | :vtk:`vtkDataArray`
281 A numpy array or :vtk:`vtkDataArray` to convert.
282 name : str, optional
283 The name of the data array for VTK.
284 deep : bool, default: False
285 If input is numpy array then deep copy values.
286 array_type : int, optional
287 VTK array type ID as specified in ``vtkType.h``.
288
289 Returns
290 -------
291 output : :vtk:`vtkDataArray` | numpy.ndarray
292 The converted array. If input is a :class:`numpy.ndarray` then
293 returns :vtk:`vtkDataArray` or if input is :vtk:`vtkDataArray` then
294 returns NumPy ``ndarray``.
295
296 """
297 if arr is None:
298 return None
299 if isinstance(arr, (list, tuple, str)):
300 arr = np.array(arr)
301 if isinstance(arr, np.ndarray):
302 if arr.dtype == np.dtype('O'):
303 arr = arr.astype('|S')
304 if arr.dtype.type in (np.str_, np.bytes_):
305 # This handles strings
306 if arr.ndim > 0:
307 # Do not call ascontiguousarray for scalar strings since this will reshape to 1D
308 # and scalars are already contiguous anyway
309 arr = np.ascontiguousarray(arr)
310 vtk_data = convert_string_array(arr)
311 else:
312 # This will handle numerical data
313 arr = np.ascontiguousarray(arr)
314 vtk_data = _vtk.numpy_to_vtk(num_array=arr, deep=deep, array_type=array_type)
315 if isinstance(name, str):
316 vtk_data.SetName(name)
317 return vtk_data
318 # Otherwise input must be a vtkDataArray
319 if not isinstance(arr, (_vtk.vtkDataArray, _vtk.vtkBitArray, _vtk.vtkStringArray)):
320 msg = f'Invalid input array type ({type(arr)}).'
321 raise TypeError(msg)
322 # Handle booleans
323 if isinstance(arr, _vtk.vtkBitArray):
324 arr = vtk_bit_array_to_char(arr)
325 # Handle string arrays
326 if isinstance(arr, _vtk.vtkStringArray):
327 return convert_string_array(arr)
328 # Convert from vtkDataArry to NumPy
329 return _vtk.vtk_to_numpy(arr)
330
331
332 @_deprecate_positional_args(allowed=['mesh', 'name'])
333 def get_array( # noqa: PLR0917
334 mesh: DataSet | _vtk.vtkDataSet | _vtk.vtkTable,
335 name: str,
336 preference: PointLiteral | CellLiteral | FieldLiteral | RowLiteral = 'cell',
337 err: bool = False, # noqa: FBT001, FBT002
338 ) -> pyvista_ndarray | None:
339 """Search point, cell and field data for an array.
340
341 Parameters
342 ----------
343 mesh : pyvista.DataSet
344 Dataset to get the array from.
345
346 name : str
347 The name of the array to get the range.
348
349 preference : str, default: "cell"
350 When scalars is specified, this is the preferred array type to
351 search for in the dataset. Must be either ``'point'``,
352 ``'cell'``, or ``'field'``.
353
354 err : bool, default: False
355 Whether to throw an error if array is not present.
356
357 Returns
358 -------
359 output : pyvista.pyvista_ndarray | None
360 Requested array. Return ``None`` if there is no array
361 matching the ``name`` and ``err=False``.
362
363 """
364 if isinstance(mesh, _vtk.vtkTable):
365 arr = row_array(mesh, name)
366 if arr is None and err:
367 msg = f'Data array ({name}) not present in this dataset.'
368 raise KeyError(msg)
369 return arr
370 else:
371 preference_ = parse_field_choice(preference)
372
373 if preference_ not in [
374 FieldAssociation.CELL,
375 FieldAssociation.POINT,
376 FieldAssociation.NONE,
377 ]:
378 msg = (
379 f'`preference` must be either "cell", "point", "field" for a '
380 f'{type(mesh)}, not "{preference}".'
381 )
382 raise ValueError(msg)
383
384 parr = point_array(mesh, name)
385 carr = cell_array(mesh, name)
386 farr = field_array(mesh, name)
387 if sum(array is not None for array in (parr, carr, farr)) > 1:
388 if preference_ == FieldAssociation.CELL:
389 out = carr
390 elif preference_ == FieldAssociation.POINT:
391 out = parr
392 else: # must be field
393 out = farr
394 elif parr is not None:
395 out = parr
396 elif carr is not None:
397 out = carr
398 elif farr is not None:
399 out = farr
400 elif err:
401 msg = f'Data array ({name}) not present in this dataset.'
402 raise KeyError(msg)
403 else:
404 out = None
405 return out
406
407
408 @_deprecate_positional_args(allowed=['mesh', 'name'])
409 def get_array_association( # noqa: PLR0917
410 mesh: DataSet | _vtk.vtkDataSet | _vtk.vtkTable,
411 name: str,
412 preference: PointLiteral | CellLiteral | FieldLiteral | RowLiteral = 'cell',
413 err: bool = False, # noqa: FBT001, FBT002
414 ) -> FieldAssociation:
415 """Return the array association.
416
417 Parameters
418 ----------
419 mesh : pyvista.DataSet
420 Dataset to get the array association from.
421
422 name : str
423 The name of the array.
424
425 preference : str, default: "cell"
426 When scalars is specified, this is the preferred array type to
427 search for in the dataset. Must be either ``'point'``,
428 ``'cell'``, or ``'field'``.
429
430 err : bool, default: False
431 Boolean to control whether to throw an error if array is not
432 present.
433
434 Returns
435 -------
436 pyvista.core.utilities.arrays.FieldAssociation
437 Association of the array. If array is not present and ``err`` is
438 ``False``, ``FieldAssociation.NONE`` is returned.
439
440 """
441 if isinstance(mesh, _vtk.vtkTable):
442 arr = row_array(mesh, name)
443 if arr is None and err:
444 msg = f'Data array ({name}) not present in this dataset.'
445 raise KeyError(msg)
446 return FieldAssociation.ROW
447
448 # with multiple arrays, return the array preference if possible
449 parr = point_array(mesh, name)
450 carr = cell_array(mesh, name)
451 farr = field_array(mesh, name)
452 arrays = [parr, carr, farr]
453 preferences = [FieldAssociation.POINT, FieldAssociation.CELL, FieldAssociation.NONE]
454 preference_field = parse_field_choice(preference)
455 if preference_field not in preferences:
456 msg = f'Data field ({preference}) not supported.'
457 raise ValueError(msg)
458
459 matches = [pref for pref, array in zip(preferences, arrays, strict=True) if array is not None]
460 # optionally raise if no match
461 if not matches:
462 if err:
463 msg = f'Data array ({name}) not present in this dataset.'
464 raise KeyError(msg)
465 return FieldAssociation.NONE
466 # use preference if it applies
467 if preference_field in matches:
468 return preference_field
469 # otherwise return first in order of point -> cell -> field
470 return matches[0]
471
472
473 def raise_not_matching(scalars: npt.NDArray[Any], dataset: DataSet | Table) -> None:
474 """Raise exception about inconsistencies.
475
476 Parameters
477 ----------
478 scalars : numpy.ndarray
479 Array of scalars.
480
481 dataset : pyvista.DataSet | pyvista.Table
482 Dataset to check against.
483
484 Raises
485 ------
486 ValueError
487 Raises a ValueError if the size of scalars does not the dataset.
488
489 """
490 if isinstance(dataset, _vtk.vtkTable):
491 msg = (
492 f'Number of scalars ({scalars.shape[0]}) must match number of rows ({dataset.n_rows}).'
493 )
494 raise ValueError(msg) # noqa: TRY004
495 msg = (
496 f'Number of scalars ({scalars.shape[0]}) '
497 f'must match either the number of points ({dataset.n_points}) '
498 f'or the number of cells ({dataset.n_cells}).'
499 )
500 raise ValueError(msg)
501
502
503 def _assoc_array(
504 obj: DataSet | _vtk.vtkDataSet, name: str, association: str = 'point'
505 ) -> pyvista_ndarray | None:
506 """Return a point, cell, or field array from a pyvista.DataSet or VTK object.
507
508 If the array or index doesn't exist, return nothing. This matches VTK's
509 behavior when using ``GetAbstractArray`` with an invalid key or index.
510
511 """
512 vtk_attr = f'Get{association.title()}Data'
513 python_attr = f'{association.lower()}_data'
514
515 if isinstance(obj, pv.DataSet):
516 try:
517 return getattr(obj, python_attr).get_array(name)
518 except KeyError: # pragma: no cover
519 return None
520 abstract_array = getattr(obj, vtk_attr)().GetAbstractArray(name)
521 if abstract_array is not None:
522 return pv.pyvista_ndarray(abstract_array)
523 return None
524
525
526 def point_array(obj: DataSet | _vtk.vtkDataSet, name: str) -> pyvista_ndarray | None:
527 """Return point array of a pyvista or vtk object.
528
529 Parameters
530 ----------
531 obj : DataSet | :vtk:`vtkDataSet`
532 PyVista or VTK dataset.
533
534 name : str | int
535 Name or index of the array.
536
537 Returns
538 -------
539 output : pyvista.pyvista_ndarray | None
540 Wrapped array if the index or name is valid. Otherwise, ``None``.
541
542 """
543 return _assoc_array(obj, name, 'point')
544
545
546 def field_array(obj: DataSet | _vtk.vtkDataSet, name: str) -> pyvista_ndarray | None:
547 """Return field data of a pyvista or vtk object.
548
549 Parameters
550 ----------
551 obj : DataSet | :vtk:`vtkDataSet`
552 PyVista or VTK dataset.
553
554 name : str | int
555 Name or index of the array.
556
557 Returns
558 -------
559 output : pyvista.pyvista_ndarray | None
560 Wrapped array if the index or name is valid. Otherwise, ``None``.
561
562 """
563 return _assoc_array(obj, name, 'field')
564
565
566 def cell_array(obj: DataSet | _vtk.vtkDataSet, name: str) -> pyvista_ndarray | None:
567 """Return cell array of a pyvista or vtk object.
568
569 Parameters
570 ----------
571 obj : DataSet | :vtk:`vtkDataSet`
572 PyVista or VTK dataset.
573
574 name : str | int
575 Name or index of the array.
576
577 Returns
578 -------
579 output : pyvista.pyvista_ndarray | None
580 Wrapped array if the index or name is valid. Otherwise, ``None``.
581
582 """
583 return _assoc_array(obj, name, 'cell')
584
585
586 def row_array(obj: _vtk.vtkTable, name: str) -> pyvista_ndarray | None:
587 """Return row array of a vtk object.
588
589 Parameters
590 ----------
591 obj : :vtk:`vtkTable`
592 PyVista or VTK table.
593
594 name : str
595 Name of the array.
596
597 Returns
598 -------
599 numpy.ndarray
600 Wrapped array.
601
602 """
603 vtkarr = obj.GetRowData().GetAbstractArray(name)
604 if vtkarr is not None:
605 return pv.pyvista_ndarray(convert_array(vtkarr))
606 else:
607 return None
608
609
610 def get_vtk_type(typ: npt.DTypeLike) -> int:
611 """Look up the VTK type for a given numpy data type.
612
613 Corrects for string type mapping issues.
614
615 Parameters
616 ----------
617 typ : numpy.dtype
618 Numpy data type.
619
620 Returns
621 -------
622 int
623 Integer type id specified in ``vtkType.h``.
624
625 """
626 typ_ = _vtk.get_vtk_array_type(typ)
627 # This handles a silly string type bug
628 if typ_ == 3:
629 return 13
630 return typ_
631
632
633 def vtk_bit_array_to_char(vtkarr_bint: _vtk.vtkBitArray) -> _vtk.vtkCharArray:
634 """Cast vtk bit array to a char array.
635
636 Parameters
637 ----------
638 vtkarr_bint : :vtk:`vtkBitArray`
639 VTK binary array.
640
641 Returns
642 -------
643 :vtk:`vtkCharArray`
644 VTK char array.
645
646 Notes
647 -----
648 This performs a copy.
649
650 """
651 vtkarr = _vtk.vtkCharArray()
652 vtkarr.DeepCopy(vtkarr_bint)
653 return vtkarr
654
655
656 def vtk_id_list_to_array(vtk_id_list: _vtk.vtkIdList) -> NumpyArray[int]:
657 """Convert a :vtk:`vtkIdList` to a NumPy array.
658
659 Parameters
660 ----------
661 vtk_id_list : :vtk:`vtkIdList`
662 VTK ID list.
663
664 Returns
665 -------
666 numpy.ndarray
667 Array of IDs.
668
669 """
670 return np.array([vtk_id_list.GetId(i) for i in range(vtk_id_list.GetNumberOfIds())])
671
672
673 def _set_string_scalar_object_name(vtkarr: _vtk.vtkStringArray) -> None:
674 """Set object name for scalar string arrays."""
675 # This is used as a flag so that scalar arrays can be reshaped later.
676 try:
677 vtkarr.SetObjectName('scalar')
678 except AttributeError:
679 vtkarr.GetObjectName = lambda: 'scalar' # type: ignore[method-assign]
680
681
682 @overload
683 def convert_string_array(
684 arr: _vtk.vtkStringArray, name: str | None = ...
685 ) -> npt.NDArray[np.str_]: ...
686 @overload
687 def convert_string_array(
688 arr: str | npt.NDArray[np.str_], name: str | None = ...
689 ) -> _vtk.vtkStringArray: ...
690 def convert_string_array(
691 arr: str | npt.NDArray[np.str_] | _vtk.vtkStringArray, name: str | None = None
692 ) -> npt.NDArray[np.str_] | _vtk.vtkStringArray:
693 """Convert a numpy array of strings to a :vtk:`vtkStringArray` or vice versa.
694
695 If a scalar string is provided, it is converted to a :vtk:`vtkCharArray`
696
697 Parameters
698 ----------
699 arr : numpy.ndarray | str
700 Numpy string array to convert.
701
702 name : str, optional
703 Name to set the :vtk:`vtkStringArray` to.
704
705 Returns
706 -------
707 :vtk:`vtkStringArray`
708 VTK string array.
709
710 Notes
711 -----
712 Note that this is terribly inefficient. If you have ideas on how
713 to make this faster, please consider opening a pull request.
714
715 """
716 arr = np.array(arr) if isinstance(arr, str) else arr
717 if isinstance(arr, np.ndarray):
718 # VTK default fonts only support ASCII. See https://gitlab.kitware.com/vtk/vtk/-/issues/16904
719 if (
720 np.issubdtype(arr.dtype, np.str_) and not ''.join(arr.tolist()).isascii()
721 ): # avoids segfault
722 msg = 'String array contains non-ASCII characters that are not supported by VTK.'
723 raise ValueError(msg)
724 vtkarr = _vtk.vtkStringArray()
725 if arr.ndim == 0:
726 arr = arr.reshape((1,))
727 # distinguish scalar inputs from array inputs by
728 # setting the object name
729 _set_string_scalar_object_name(vtkarr)
730
731 # Pre-allocate the underlying storage instead of growing it via
732 # ``InsertNextValue`` per element. Iterating over ``arr.tolist()``
733 # avoids the per-element ``numpy.str_`` scalar boxing cost that
734 # iterating a numpy string array pays.
735 flat_list = arr.reshape(-1).tolist()
736 vtkarr.SetNumberOfValues(len(flat_list))
737 for i, val in enumerate(flat_list):
738 vtkarr.SetValue(i, val)
739 if isinstance(name, str):
740 vtkarr.SetName(name)
741 return vtkarr
742 # Otherwise it is a vtk array and needs to be converted back to numpy.
743 # ``np.array(list, dtype='|U')`` auto-sizes the unicode width to the
744 # longest value; passing dtype='|U' to np.empty defaults to width 1
745 # which truncates strings.
746 nvalues = arr.GetNumberOfValues()
747 arr_out = np.array([arr.GetValue(i) for i in range(nvalues)], dtype='|U')
748 try:
749 if arr.GetObjectName() == 'scalar':
750 return np.array(''.join(arr_out))
751 except AttributeError:
752 pass
753 return arr_out
754
755
756 def array_from_vtkmatrix(matrix: _vtk.vtkMatrix3x3 | _vtk.vtkMatrix4x4) -> NumpyArray[float]:
757 """Convert a vtk matrix to an array.
758
759 Parameters
760 ----------
761 matrix : :vtk:`vtkMatrix3x3` | :vtk:`vtkMatrix4x4`
762 The vtk matrix to be converted to a ``numpy.ndarray``.
763 Returned ndarray has shape (3, 3) or (4, 4) as appropriate.
764
765 Returns
766 -------
767 numpy.ndarray
768 Numpy array containing the data from ``matrix``.
769
770 """
771 if isinstance(matrix, _vtk.vtkMatrix3x3):
772 shape = (3, 3)
773 elif isinstance(matrix, _vtk.vtkMatrix4x4):
774 shape = (4, 4)
775 else:
776 msg = ( # type: ignore[unreachable]
777 'Expected vtk.vtkMatrix3x3 or vtk.vtkMatrix4x4 input,'
778 f' got {type(matrix).__name__} instead.'
779 )
780 raise TypeError(msg)
781 array = np.zeros(shape)
782 for i, j in product(range(shape[0]), range(shape[1])):
783 array[i, j] = matrix.GetElement(i, j)
784 return array
785
786
787 def vtkmatrix_from_array(array: NumpyArray[float]) -> _vtk.vtkMatrix3x3 | _vtk.vtkMatrix4x4:
788 """Convert a ``numpy.ndarray`` or array-like to a vtk matrix.
789
790 Parameters
791 ----------
792 array : array_like[float]
793 The array or array-like to be converted to a vtk matrix.
794 Shape (3, 3) gets converted to a :vtk:`vtkMatrix3x3`, shape (4, 4)
795 gets converted to a :vtk:`vtkMatrix4x4`. No other shapes are valid.
796
797 Returns
798 -------
799 output : :vtk:`vtkMatrix3x3` | :vtk:`vtkMatrix4x4`
800 VTK matrix.
801
802 """
803 array = np.asarray(array)
804 if array.shape == (3, 3):
805 matrix = _vtk.vtkMatrix3x3()
806 elif array.shape == (4, 4):
807 matrix = _vtk.vtkMatrix4x4() # type: ignore[assignment]
808 else:
809 msg = f'Invalid shape {array.shape}, must be (3, 3) or (4, 4).'
810 raise ValueError(msg)
811 m, n = array.shape
812 for i, j in product(range(m), range(n)):
813 matrix.SetElement(i, j, array[i, j])
814 return matrix
815
816
817 def set_default_active_vectors(mesh: DataSet) -> _ActiveArrayExistsInfoTuple:
818 """Set a default vectors array on mesh, if not already set.
819
820 If an active vector already exists, no changes are made.
821
822 If an active vectors does not exist, it checks for possibly cell
823 or point arrays with shape ``(n, 3)``. If only one exists, then
824 it is set as the active vectors. Otherwise, an error is raised.
825
826 .. versionchanged:: 0.45
827 The field and name of the active array is now returned.
828 Previously, ``None`` was returned.
829
830 Parameters
831 ----------
832 mesh : pyvista.DataSet
833 Dataset to set default active vectors.
834
835 Raises
836 ------
837 pyvista.core.errors.MissingDataError
838 If no vector-like arrays exist.
839
840 pyvista.core.errors.AmbiguousDataError
841 If more than one vector-like arrays exist.
842
843 Returns
844 -------
845 tuple[FieldAssociation, str]
846 The field and name of the active array.
847
848 """
849 from pyvista.core.dataset import _ActiveArrayExistsInfoTuple # noqa: PLC0415
850
851 if mesh.active_vectors_name is None:
852 point_data = mesh.point_data
853 cell_data = mesh.cell_data
854
855 possible_vectors_point = [
856 name for name, value in point_data.items() if value.ndim == 2 and value.shape[1] == 3
857 ]
858 possible_vectors_cell = [
859 name for name, value in cell_data.items() if value.ndim == 2 and value.shape[1] == 3
860 ]
861
862 possible_vectors = possible_vectors_point + possible_vectors_cell
863 n_possible_vectors = len(possible_vectors)
864
865 if n_possible_vectors == 1:
866 preference: Literal['point', 'cell'] = (
867 'point' if len(possible_vectors_point) == 1 else 'cell'
868 )
869 mesh.set_active_vectors(possible_vectors[0], preference=preference)
870 elif n_possible_vectors < 1:
871 msg = 'No vector-like data available.'
872 raise MissingDataError(msg)
873 else: # n_possible_vectors > 1:
874 msg = (
875 'Multiple vector-like data available\n'
876 f'cell data: {possible_vectors_cell}.\n'
877 f'point data: {possible_vectors_point}.\n'
878 'Set one as active using DataSet.set_active_vectors(name, preference=type)'
879 )
880 raise AmbiguousDataError(msg)
881 field, name = mesh.active_vectors_info
882 return _ActiveArrayExistsInfoTuple(field, cast('str', name))
883
884
885 def set_default_active_scalars(mesh: DataSet) -> _ActiveArrayExistsInfoTuple:
886 """Set a default scalars array on mesh, if not already set.
887
888 If an active scalars already exists, no changes are made.
889
890 If an active scalars does not exist, it checks for point or cell
891 arrays. If only one exists, then it is set as the active scalars.
892 Otherwise, an error is raised.
893
894 .. versionchanged:: 0.45
895 The field and name of the active array is now returned.
896 Previously, ``None`` was returned.
897
898 Parameters
899 ----------
900 mesh : pyvista.DataSet
901 Dataset to set default active scalars.
902
903 Raises
904 ------
905 pyvista.core.errors.MissingDataError
906 If no arrays exist.
907
908 pyvista.core.errors.AmbiguousDataError
909 If more than one array exists.
910
911 Returns
912 -------
913 tuple[FieldAssociation, str]
914 The field and name of the active array.
915
916 """
917 from pyvista.core.dataset import _ActiveArrayExistsInfoTuple # noqa: PLC0415
918
919 if mesh.active_scalars_name is None:
920 point_data = mesh.point_data
921 cell_data = mesh.cell_data
922
923 possible_scalars_point = point_data.keys()
924 possible_scalars_cell = cell_data.keys()
925
926 possible_scalars = possible_scalars_point + possible_scalars_cell
927 n_possible_scalars = len(possible_scalars)
928
929 if n_possible_scalars == 1:
930 preference: Literal['point', 'cell'] = (
931 'point' if len(possible_scalars_point) == 1 else 'cell'
932 )
933 mesh.set_active_scalars(possible_scalars[0], preference=preference)
934 elif n_possible_scalars < 1:
935 msg = 'No data available.'
936 raise MissingDataError(msg)
937 else: # n_possible_scalars > 1:
938 msg = (
939 'Multiple data available\n'
940 f'cell data: {possible_scalars_cell}.\n'
941 f'point data: {possible_scalars_point}.\n'
942 'Set one as active using DataSet.set_active_scalars(name, preference=type)'
943 )
944 raise AmbiguousDataError(msg)
945 field, name = mesh.active_scalars_info
946 return _ActiveArrayExistsInfoTuple(field, cast('str', name))
947
948
949 _JSONValueType = (
950 dict[str, '_JSONValueType']
951 | list['_JSONValueType']
952 | tuple['_JSONValueType']
953 | str
954 | int
955 | float
956 | bool
957 | None
958 )
959
960
961 class _SerializedDictArray(DisableVtkSnakeCase, UserDict, _vtk.vtkStringArray): # type: ignore[type-arg]
962 """Dict-like object with a JSON-serialized string array representation.
963
964 This class behaves just like a regular dict, except its contents
965 are represented internally as a JSON-formatted :vtk:`vtkStringArray`.
966 The string array is updated dynamically any time the dict is
967 modified, such that modifying the dict will also implicitly modify
968 its JSON string representation.
969
970 Notes
971 -----
972 This class is intended for metadata storage. Values are JSON-serialized
973 on every mutation, so it should not be used in place of a regular field
974 data array when storing bulk array data with many entries.
975
976 """
977
978 @property
979 def _string(self: _SerializedDictArray) -> str:
980 """Get the :vtk:`vtkStringArray` string."""
981 # Joining all values handles both the historical char-per-value
982 # format (read from older saved files) and the current
983 # whole-string-as-one-value format below.
984 n = self.GetNumberOfValues()
985 if n == 1:
986 return self.GetValue(0)
987 return ''.join([self.GetValue(i) for i in range(n)])
988
989 @_string.setter
990 def _string(self: _SerializedDictArray, str_: str) -> None:
991 """Set the :vtk:`vtkStringArray` to a specified string."""
992 # Store the entire string as a single value rather than one
993 # character per value. This avoids O(len(str_)) Python<->C
994 # crossings and matches how every other VTK string field stores
995 # text. Reading still works for the legacy char-per-value format
996 # because the getter joins all values.
997 self.SetNumberOfValues(1)
998 self.SetValue(0, str_)
999
1000 def _update_string(self: _SerializedDictArray) -> None:
1001 """Format dict data as JSON and update the :vtk:`vtkStringArray`."""
1002 data_str = json.dumps(self.data)
1003 if data_str != self._string:
1004 self._string = data_str
1005
1006 def __str__(self: _SerializedDictArray) -> str:
1007 """Return JSON-formatted dict representation."""
1008 return self._string
1009
1010 def __repr__(self: _SerializedDictArray) -> str:
1011 """Return JSON-formatted dict representation."""
1012 return str(self)
1013
1014 def __init__(
1015 self: _SerializedDictArray,
1016 dict_: str | dict[str, _JSONValueType] | UserDict[str, _JSONValueType] | None = None,
1017 /,
1018 **kwargs,
1019 ) -> None:
1020 # Init from JSON string
1021 if isinstance(dict_, str):
1022 dict_ = json.loads(dict_)
1023
1024 # Init UserDict
1025 super().__init__(dict_, **kwargs) # type: ignore[arg-type]
1026 self._update_string()
1027
1028 # Flag self as a scalar string
1029 # This is only needed so that the Field DatasetAttributes repr
1030 # shows this array as `str`
1031 _set_string_scalar_object_name(self)
1032
1033 def __getstate__(self: _SerializedDictArray) -> None:
1034 """Support pickling.
1035
1036 This method does nothing. It only exists to make the pickle library happy.
1037 Classes that store an instance of this class must pickle this array directly.
1038 E.g. DataObjects can support this by storing this array as field data
1039 """
1040
1041 def __setstate__(self: _SerializedDictArray, state: Any) -> None:
1042 """Support pickling.
1043
1044 This method does nothing. It only exists to make the pickle library happy.
1045 Classes that store an instance of this class must pickle this array directly.
1046 E.g. DataObjects can support this by storing this array as field data
1047 """
1048
1049 # Override any/all `UserDict` or `MutableMapping` methods which mutate
1050 # the dictionary. This ensures the serialized string is also updated
1051 # and synced with the dict
1052
1053 def __setitem__(self: _SerializedDictArray, key: Any, item: Any) -> None:
1054 super().__setitem__(key, item)
1055 self._update_string()
1056
1057 def __delitem__(self: _SerializedDictArray, key: Any) -> None:
1058 super().__delitem__(key)
1059 self._update_string()
1060
1061 def __setattr__(self: _SerializedDictArray, key: Any, value: Any) -> None:
1062 object.__setattr__(self, key, value)
1063 self._update_string() if key != '_string' else None
1064
1065 def update(self: _SerializedDictArray, *args, **kwargs) -> None:
1066 super().update(*args, **kwargs)
1067 self._update_string()
1068
1069 def popitem(self: _SerializedDictArray) -> Any:
1070 item = super().popitem()
1071 self._update_string()
1072 return item
1073
1074 def pop(self: _SerializedDictArray, __key: Any) -> Any: # type: ignore[override] # noqa: PYI063
1075 item = super().pop(__key)
1076 self._update_string()
1077 return item
1078
1079 def clear(self: _SerializedDictArray) -> None:
1080 super().clear()
1081 self._update_string()
1082
1083 def setdefault(self: _SerializedDictArray, *args, **kwargs) -> None:
1084 super().setdefault(*args, **kwargs)
1085 self._update_string()