/
composite.py
1310 lines (1095 loc) · 41.8 KB
/
composite.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Container to mimic ``vtkMultiBlockDataSet`` objects.
These classes hold many VTK datasets in one object that can be passed
to VTK algorithms and PyVista filtering/plotting routines.
"""
from __future__ import annotations
import collections.abc
from itertools import zip_longest
import pathlib
from typing import Any, Iterable, List, Optional, Set, Tuple, Union, cast, overload
import numpy as np
import pyvista
from . import _vtk_core as _vtk
from ._typing_core import BoundsLike, NumpyArray
from .dataset import DataObject, DataSet
from .filters import CompositeFilters
from .pyvista_ndarray import pyvista_ndarray
from .utilities.arrays import FieldAssociation
from .utilities.geometric_objects import Box
from .utilities.helpers import is_pyvista_dataset, wrap
_TypeMultiBlockLeaf = Union['MultiBlock', DataSet]
class MultiBlock(
_vtk.vtkMultiBlockDataSet,
CompositeFilters,
DataObject,
collections.abc.MutableSequence, # type: ignore[type-arg]
):
"""A composite class to hold many data sets which can be iterated over.
This wraps/extends the `vtkMultiBlockDataSet
<https://vtk.org/doc/nightly/html/classvtkMultiBlockDataSet.html>`_ class
so that we can easily plot these data sets and use the composite in a
Pythonic manner.
You can think of ``MultiBlock`` like a list as we
can iterate over this data structure by index. It has some dictionary
features as we can also access blocks by their string name.
.. versionchanged:: 0.36.0
``MultiBlock`` adheres more closely to being list like, and inherits
from :class:`collections.abc.MutableSequence`. Multiple nonconforming
behaviors were removed or modified.
Parameters
----------
*args : dict, optional
Data object dictionary.
**kwargs : dict, optional
See :func:`pyvista.read` for additional options.
Examples
--------
>>> import pyvista as pv
Create an empty composite dataset.
>>> blocks = pv.MultiBlock()
Add a dataset to the collection.
>>> sphere = pv.Sphere()
>>> blocks.append(sphere)
Add a named block.
>>> blocks["cube"] = pv.Cube()
Instantiate from a list of objects.
>>> data = [
... pv.Sphere(center=(2, 0, 0)),
... pv.Cube(center=(0, 2, 0)),
... pv.Cone(),
... ]
>>> blocks = pv.MultiBlock(data)
>>> blocks.plot()
Instantiate from a dictionary.
>>> data = {
... "cube": pv.Cube(),
... "sphere": pv.Sphere(center=(2, 2, 0)),
... }
>>> blocks = pv.MultiBlock(data)
>>> blocks.plot()
Iterate over the collection.
>>> for name in blocks.keys():
... block = blocks[name]
...
>>> for block in blocks:
... # Do something with each dataset
... surf = block.extract_surface()
...
"""
plot = pyvista._plot.plot
_WRITERS = dict.fromkeys(['.vtm', '.vtmb'], _vtk.vtkXMLMultiBlockDataWriter)
def __init__(self, *args, **kwargs) -> None:
"""Initialize multi block."""
super().__init__()
deep = kwargs.pop('deep', False)
# keep a python reference to the dataset to avoid
# unintentional garbage collections since python does not
# add a reference to the dataset when it's added here in
# MultiBlock. See https://github.com/pyvista/pyvista/pull/1805
self._refs: Any = {}
if len(args) == 1:
if isinstance(args[0], _vtk.vtkMultiBlockDataSet):
if deep:
self.deep_copy(args[0])
else:
self.shallow_copy(args[0])
elif isinstance(args[0], (list, tuple)):
for block in args[0]:
self.append(block)
elif isinstance(args[0], (str, pathlib.Path)):
self._from_file(args[0], **kwargs)
elif isinstance(args[0], dict):
for key, block in args[0].items():
self.append(block, key)
else:
raise TypeError(f'Type {type(args[0])} is not supported by pyvista.MultiBlock')
elif len(args) > 1:
raise ValueError(
'Invalid number of arguments:\n``pyvista.MultiBlock``supports 0 or 1 arguments.',
)
# Upon creation make sure all nested structures are wrapped
self.wrap_nested()
def wrap_nested(self):
"""Ensure that all nested data structures are wrapped as PyVista datasets.
This is performed in place.
"""
for i in range(self.n_blocks):
block = self.GetBlock(i)
if not is_pyvista_dataset(block):
self.SetBlock(i, wrap(block))
@property
def bounds(self) -> BoundsLike: # numpydoc ignore=RT01
"""Find min/max for bounds across blocks.
Returns
-------
tuple[float, float, float, float, float, float]
Length 6 tuple of floats containing min/max along each axis.
Examples
--------
Return the bounds across blocks.
>>> import pyvista as pv
>>> data = [
... pv.Sphere(center=(2, 0, 0)),
... pv.Cube(center=(0, 2, 0)),
... pv.Cone(),
... ]
>>> blocks = pv.MultiBlock(data)
>>> blocks.bounds
(-0.5, 2.5, -0.5, 2.5, -0.5, 0.5)
"""
# apply reduction of min and max over each block
# (typing.cast necessary to make mypy happy with ufunc.reduce() later)
all_bounds = [cast(List[float], block.bounds) for block in self if block]
# edge case where block has no bounds
if not all_bounds: # pragma: no cover
minima = np.array([0.0, 0.0, 0.0])
maxima = np.array([0.0, 0.0, 0.0])
else:
minima = np.minimum.reduce(all_bounds)[::2]
maxima = np.maximum.reduce(all_bounds)[1::2]
# interleave minima and maxima for bounds
the_bounds = np.stack([minima, maxima]).ravel('F')
return cast(BoundsLike, tuple(the_bounds))
@property
def center(self) -> NumpyArray[float]: # numpydoc ignore=RT01
"""Return the center of the bounding box.
Returns
-------
np.ndarray
Center of the bounding box.
Examples
--------
>>> import pyvista as pv
>>> data = [
... pv.Sphere(center=(2, 0, 0)),
... pv.Cube(center=(0, 2, 0)),
... pv.Cone(),
... ]
>>> blocks = pv.MultiBlock(data)
>>> blocks.center # doctest:+SKIP
array([1., 1., 0.])
"""
# (typing.cast necessary to make mypy happy with np.reshape())
return np.reshape(cast(List[float], self.bounds), (3, 2)).mean(axis=1)
@property
def length(self) -> float: # numpydoc ignore=RT01
"""Return the length of the diagonal of the bounding box.
Returns
-------
float
Length of the diagonal of the bounding box.
Examples
--------
>>> import pyvista as pv
>>> data = [
... pv.Sphere(center=(2, 0, 0)),
... pv.Cube(center=(0, 2, 0)),
... pv.Cone(),
... ]
>>> blocks = pv.MultiBlock(data)
>>> blocks.length
4.3584
"""
return Box(self.bounds).length
@property
def n_blocks(self) -> int: # numpydoc ignore=RT01
"""Return the total number of blocks set.
Returns
-------
int
Total number of blocks set.
Examples
--------
>>> import pyvista as pv
>>> data = [
... pv.Sphere(center=(2, 0, 0)),
... pv.Cube(center=(0, 2, 0)),
... pv.Cone(),
... ]
>>> blocks = pv.MultiBlock(data)
>>> blocks.n_blocks
3
"""
return self.GetNumberOfBlocks()
@n_blocks.setter
def n_blocks(self, n): # numpydoc ignore=GL08
"""Change the total number of blocks set.
Parameters
----------
n : int
The total number of blocks set.
"""
self.SetNumberOfBlocks(n)
self.Modified()
@property
def volume(self) -> float: # numpydoc ignore=RT01
"""Return the total volume of all meshes in this dataset.
Returns
-------
float
Total volume of the mesh.
Examples
--------
>>> import pyvista as pv
>>> data = [
... pv.Sphere(center=(2, 0, 0)),
... pv.Cube(center=(0, 2, 0)),
... pv.Cone(),
... ]
>>> blocks = pv.MultiBlock(data)
>>> blocks.volume
1.7348
"""
return sum(block.volume for block in self if block)
def get_data_range(self, name: str, allow_missing: bool = False) -> Tuple[float, float]: # type: ignore[explicit-override, override]
"""Get the min/max of an array given its name across all blocks.
Parameters
----------
name : str
Name of the array.
allow_missing : bool, default: False
Allow a block to be missing the named array.
Returns
-------
tuple
``(min, max)`` of the named array.
"""
mini, maxi = np.inf, -np.inf
for i in range(self.n_blocks):
data = self[i]
if data is None:
continue
# get the scalars if available - recursive
try:
tmi, tma = data.get_data_range(name)
except KeyError:
if allow_missing:
continue
else:
raise
if not np.isnan(tmi) and tmi < mini:
mini = tmi
if not np.isnan(tma) and tma > maxi:
maxi = tma
return mini, maxi
def get_index_by_name(self, name: str) -> int:
"""Find the index number by block name.
Parameters
----------
name : str
Name of the block.
Returns
-------
int
Index of the block.
Examples
--------
>>> import pyvista as pv
>>> data = {
... "cube": pv.Cube(),
... "sphere": pv.Sphere(center=(2, 2, 0)),
... }
>>> blocks = pv.MultiBlock(data)
>>> blocks.get_index_by_name('sphere')
1
"""
for i in range(self.n_blocks):
if self.get_block_name(i) == name:
return i
raise KeyError(f'Block name ({name}) not found')
@overload
def __getitem__(
self,
index: Union[int, str],
) -> Optional[_TypeMultiBlockLeaf]: # noqa: D105 # numpydoc ignore=GL08
... # pragma: no cover
@overload
def __getitem__(self, index: slice) -> MultiBlock: # noqa: D105
... # pragma: no cover
def __getitem__(self, index):
"""Get a block by its index or name.
If the name is non-unique then returns the first occurrence.
"""
if isinstance(index, slice):
multi = MultiBlock()
for i in range(self.n_blocks)[index]:
multi.append(self[i], self.get_block_name(i))
return multi
elif isinstance(index, str):
index = self.get_index_by_name(index)
############################
if index < -self.n_blocks or index >= self.n_blocks:
raise IndexError(f'index ({index}) out of range for this dataset.')
if index < 0:
index = self.n_blocks + index
return wrap(self.GetBlock(index))
def append(self, dataset: Optional[_TypeMultiBlockLeaf], name: Optional[str] = None):
"""Add a data set to the next block index.
Parameters
----------
dataset : pyvista.DataSet or pyvista.MultiBlock
Dataset to append to this multi-block.
name : str, optional
Block name to give to dataset. A default name is given
depending on the block index as ``'Block-{i:02}'``.
Examples
--------
>>> import pyvista as pv
>>> from pyvista import examples
>>> data = {
... "cube": pv.Cube(),
... "sphere": pv.Sphere(center=(2, 2, 0)),
... }
>>> blocks = pv.MultiBlock(data)
>>> blocks.append(pv.Cone())
>>> len(blocks)
3
>>> blocks.append(examples.load_uniform(), "uniform")
>>> blocks.keys()
['cube', 'sphere', 'Block-02', 'uniform']
"""
# do not allow to add self
if dataset is self:
raise ValueError("Cannot nest a composite dataset in itself.")
index = self.n_blocks # note off by one so use as index
# always wrap since we may need to reference the VTK memory address
wrapped = wrap(dataset)
if isinstance(wrapped, pyvista_ndarray):
raise TypeError('dataset should not be or contain an array')
dataset = wrapped
self.n_blocks += 1
self[index] = dataset
# No overwrite if name is None
self.set_block_name(index, name)
def extend(self, datasets: Iterable[_TypeMultiBlockLeaf]) -> None:
"""Extend MultiBlock with an Iterable.
If another MultiBlock object is supplied, the key names will
be preserved.
Parameters
----------
datasets : Iterable[pyvista.DataSet or pyvista.MultiBlock]
Datasets to extend.
Examples
--------
>>> import pyvista as pv
>>> from pyvista import examples
>>> data = {
... "cube": pv.Cube(),
... "sphere": pv.Sphere(center=(2, 2, 0)),
... }
>>> blocks = pv.MultiBlock(data)
>>> blocks_uniform = pv.MultiBlock(
... {"uniform": examples.load_uniform()}
... )
>>> blocks.extend(blocks_uniform)
>>> len(blocks)
3
>>> blocks.keys()
['cube', 'sphere', 'uniform']
"""
# Code based on collections.abc
if isinstance(datasets, MultiBlock):
for key, data in zip(datasets.keys(), datasets):
self.append(data, key)
else:
for v in datasets:
self.append(v)
def get(
self,
index: str,
default: Optional[_TypeMultiBlockLeaf] = None,
) -> Optional[_TypeMultiBlockLeaf]:
"""Get a block by its name.
If the name is non-unique then returns the first occurrence.
Returns ``default`` if name isn't in the dataset.
Parameters
----------
index : str
Index or name of the dataset within the multiblock.
default : pyvista.DataSet or pyvista.MultiBlock, optional
Default to return if index is not in the multiblock.
Returns
-------
pyvista.DataSet or pyvista.MultiBlock or None
Dataset from the given index if it exists.
Examples
--------
>>> import pyvista as pv
>>> from pyvista import examples
>>> data = {"poly": pv.PolyData(), "img": pv.ImageData()}
>>> blocks = pv.MultiBlock(data)
>>> blocks.get("poly")
PolyData ...
>>> blocks.get("cone")
"""
try:
return self[index]
except KeyError:
return default
def set_block_name(self, index: int, name: Optional[str]):
"""Set a block's string name at the specified index.
Parameters
----------
index : int
Index or the dataset within the multiblock.
name : str, optional
Name to assign to the block at ``index``. If ``None``, no name is
assigned to the block.
Examples
--------
>>> import pyvista as pv
>>> data = {
... "cube": pv.Cube(),
... "sphere": pv.Sphere(center=(2, 2, 0)),
... }
>>> blocks = pv.MultiBlock(data)
>>> blocks.append(pv.Cone())
>>> blocks.set_block_name(2, 'cone')
>>> blocks.keys()
['cube', 'sphere', 'cone']
"""
if name is None:
return
index = range(self.n_blocks)[index]
self.GetMetaData(index).Set(_vtk.vtkCompositeDataSet.NAME(), name)
self.Modified()
def get_block_name(self, index: int) -> Optional[str]:
"""Return the string name of the block at the given index.
Parameters
----------
index : int
Index of the block to get the name of.
Returns
-------
str
Name of the block at the given index.
Examples
--------
>>> import pyvista as pv
>>> data = {
... "cube": pv.Cube(),
... "sphere": pv.Sphere(center=(2, 2, 0)),
... }
>>> blocks = pv.MultiBlock(data)
>>> blocks.get_block_name(0)
'cube'
"""
index = range(self.n_blocks)[index]
meta = self.GetMetaData(index)
if meta is not None:
return meta.Get(_vtk.vtkCompositeDataSet.NAME())
return None
def keys(self) -> List[Optional[str]]:
"""Get all the block names in the dataset.
Returns
-------
list
List of block names.
Examples
--------
>>> import pyvista as pv
>>> data = {
... "cube": pv.Cube(),
... "sphere": pv.Sphere(center=(2, 2, 0)),
... }
>>> blocks = pv.MultiBlock(data)
>>> blocks.keys()
['cube', 'sphere']
"""
return [self.get_block_name(i) for i in range(self.n_blocks)]
def _ipython_key_completions_(self) -> List[Optional[str]]:
return self.keys()
def replace(self, index: int, dataset: Optional[_TypeMultiBlockLeaf]) -> None:
"""Replace dataset at index while preserving key name.
Parameters
----------
index : int
Index of the block to replace.
dataset : pyvista.DataSet or pyvista.MultiBlock
Dataset for replacing the one at index.
Examples
--------
>>> import pyvista as pv
>>> import numpy as np
>>> data = {
... "cube": pv.Cube(),
... "sphere": pv.Sphere(center=(2, 2, 0)),
... }
>>> blocks = pv.MultiBlock(data)
>>> blocks.replace(1, pv.Sphere(center=(10, 10, 10)))
>>> blocks.keys()
['cube', 'sphere']
>>> np.allclose(blocks[1].center, [10.0, 10.0, 10.0])
True
"""
name = self.get_block_name(index)
self[index] = dataset
self.set_block_name(index, name)
@overload
def __setitem__(
self,
index: Union[int, str],
data: Optional[_TypeMultiBlockLeaf],
): # noqa: D105 # numpydoc ignore=GL08
... # pragma: no cover
@overload
def __setitem__(
self,
index: slice,
data: Iterable[Optional[_TypeMultiBlockLeaf]],
): # noqa: D105 # numpydoc ignore=GL08
... # pragma: no cover
def __setitem__(
self,
index: Union[int, str, slice],
data,
):
"""Set a block with a VTK data object.
To set the name simultaneously, pass a string name as the 2nd index.
Examples
--------
>>> import pyvista as pv
>>> multi = pv.MultiBlock()
>>> multi.append(pv.PolyData())
>>> multi[0] = pv.UnstructuredGrid()
>>> multi.append(pv.PolyData(), 'poly')
>>> multi.keys()
['Block-00', 'poly']
>>> multi['bar'] = pv.PolyData()
>>> multi.n_blocks
3
"""
i: int = 0
name: Optional[str] = None
if isinstance(index, str):
try:
i = self.get_index_by_name(index)
except KeyError:
self.append(data, index)
return
name = index
elif isinstance(index, slice):
index_iter = range(self.n_blocks)[index]
for i, (idx, d) in enumerate(zip_longest(index_iter, data)):
if idx is None:
self.insert(
index_iter[-1] + 1 + (i - len(index_iter)),
d,
) # insert after last entry, increasing
elif d is None:
del self[index_iter[-1] + 1] # delete next entry
else:
self[idx] = d #
return
else:
i = index
# data, i, and name are a single value now
data = cast(pyvista.DataSet, wrap(data))
i = range(self.n_blocks)[i]
# this is the only spot in the class where we actually add
# data to the MultiBlock
# check if we are overwriting a block
existing_dataset = self.GetBlock(i)
if existing_dataset is not None:
self._remove_ref(i)
self.SetBlock(i, data)
if data is not None:
self._refs[data.memory_address] = data
if name is None:
name = f'Block-{i:02}'
self.set_block_name(i, name) # Note that this calls self.Modified()
def __delitem__(self, index: Union[int, str, slice]) -> None:
"""Remove a block at the specified index."""
if isinstance(index, slice):
if index.indices(self.n_blocks)[2] > 0:
for i in reversed(range(*index.indices(self.n_blocks))):
self.__delitem__(i)
else:
for i in range(*index.indices(self.n_blocks)):
self.__delitem__(i)
return
if isinstance(index, str):
index = self.get_index_by_name(index)
self._remove_ref(index)
self.RemoveBlock(index)
def _remove_ref(self, index: int):
"""Remove python reference to the dataset."""
dataset = self[index]
if hasattr(dataset, 'memory_address'):
self._refs.pop(dataset.memory_address, None) # type: ignore[union-attr]
def __iter__(self) -> MultiBlock:
"""Return the iterator across all blocks."""
self._iter_n = 0
return self
def __eq__(self, other):
"""Equality comparison."""
if not isinstance(other, MultiBlock):
return False
if self is other:
return True
if len(self) != len(other):
return False
if not self.keys() == other.keys():
return False
if any(self_mesh != other_mesh for self_mesh, other_mesh in zip(self, other)):
return False
return True
def __next__(self) -> Optional[_TypeMultiBlockLeaf]:
"""Get the next block from the iterator."""
if self._iter_n < self.n_blocks:
result = self[self._iter_n]
self._iter_n += 1
return result
raise StopIteration
def insert(self, index: int, dataset: _TypeMultiBlockLeaf, name: Optional[str] = None) -> None:
"""Insert data before index.
Parameters
----------
index : int
Index before which to insert data.
dataset : pyvista.DataSet or pyvista.MultiBlock
Data to insert.
name : str, optional
Name for key to give dataset. A default name is given
depending on the block index as ``'Block-{i:02}'``.
Examples
--------
Insert a new :class:`pyvista.PolyData` at the start of the multiblock.
>>> import pyvista as pv
>>> data = {
... "cube": pv.Cube(),
... "sphere": pv.Sphere(center=(2, 2, 0)),
... }
>>> blocks = pv.MultiBlock(data)
>>> blocks.keys()
['cube', 'sphere']
>>> blocks.insert(0, pv.Plane(), "plane")
>>> blocks.keys()
['plane', 'cube', 'sphere']
"""
index = range(self.n_blocks)[index]
self.n_blocks += 1
for i in reversed(range(index, self.n_blocks - 1)):
self[i + 1] = self[i]
self.set_block_name(i + 1, self.get_block_name(i))
self[index] = dataset
self.set_block_name(index, name)
def pop(self, index: Union[int, str] = -1) -> Optional[_TypeMultiBlockLeaf]:
"""Pop off a block at the specified index.
Parameters
----------
index : int or str, default: -1
Index or name of the dataset within the multiblock. Defaults to
last dataset.
Returns
-------
pyvista.DataSet or pyvista.MultiBlock
Dataset from the given index that was removed.
Examples
--------
Pop the ``"cube"`` multiblock.
>>> import pyvista as pv
>>> data = {
... "cube": pv.Cube(),
... "sphere": pv.Sphere(center=(2, 2, 0)),
... }
>>> blocks = pv.MultiBlock(data)
>>> blocks.keys()
['cube', 'sphere']
>>> cube = blocks.pop("cube")
>>> blocks.keys()
['sphere']
"""
if isinstance(index, int):
index = range(self.n_blocks)[index]
data = self[index]
del self[index]
return data
def reverse(self):
"""Reverse MultiBlock in-place.
Examples
--------
Reverse a multiblock.
>>> import pyvista as pv
>>> data = {
... "cube": pv.Cube(),
... "sphere": pv.Sphere(center=(2, 2, 0)),
... }
>>> blocks = pv.MultiBlock(data)
>>> blocks.keys()
['cube', 'sphere']
>>> blocks.reverse()
>>> blocks.keys()
['sphere', 'cube']
"""
# Taken from implementation in collections.abc.MutableSequence
names = self.keys()
n = len(self)
for i in range(n // 2):
self[i], self[n - i - 1] = self[n - i - 1], self[i]
for i, name in enumerate(reversed(names)):
self.set_block_name(i, name)
def clean(self, empty=True):
"""Remove any null blocks in place.
Parameters
----------
empty : bool, default: True
Remove any meshes that are empty as well (have zero points).
Examples
--------
>>> import pyvista as pv
>>> data = {"cube": pv.Cube(), "empty": pv.PolyData()}
>>> blocks = pv.MultiBlock(data)
>>> blocks.clean(empty=True)
>>> blocks.keys()
['cube']
"""
null_blocks = []
for i in range(self.n_blocks):
if isinstance(self[i], MultiBlock):
# Recursively move through nested structures
self[i].clean()
if self[i].n_blocks < 1:
null_blocks.append(i)
elif self[i] is None or empty and self[i].n_points < 1:
null_blocks.append(i)
# Now remove the null/empty meshes
null_blocks = np.array(null_blocks, dtype=int)
for i in range(len(null_blocks)):
# Cast as int because windows is super annoying
del self[int(null_blocks[i])]
null_blocks -= 1
def _get_attrs(self):
"""Return the representation methods (internal helper)."""
attrs = []
attrs.append(("N Blocks", self.n_blocks, "{}"))
bds = self.bounds
attrs.append(("X Bounds", (bds[0], bds[1]), "{:.3f}, {:.3f}"))
attrs.append(("Y Bounds", (bds[2], bds[3]), "{:.3f}, {:.3f}"))
attrs.append(("Z Bounds", (bds[4], bds[5]), "{:.3f}, {:.3f}"))
return attrs
def _repr_html_(self) -> str:
"""Define a pretty representation for Jupyter notebooks."""
fmt = ""
fmt += "<table style='width: 100%;'>"
fmt += "<tr><th>Information</th><th>Blocks</th></tr>"
fmt += "<tr><td>"
fmt += "\n"
fmt += "<table>\n"
fmt += f"<tr><th>{type(self).__name__}</th><th>Values</th></tr>\n"
row = "<tr><td>{}</td><td>{}</td></tr>\n"
# now make a call on the object to get its attributes as a list of len 2 tuples
for attr in self._get_attrs():
try:
fmt += row.format(attr[0], attr[2].format(*attr[1]))
except:
fmt += row.format(attr[0], attr[2].format(attr[1]))
fmt += "</table>\n"
fmt += "\n"
fmt += "</td><td>"
fmt += "\n"
fmt += "<table>\n"
row = "<tr><th>{}</th><th>{}</th><th>{}</th></tr>\n"
fmt += row.format("Index", "Name", "Type")
for i in range(self.n_blocks):
data = self[i]
fmt += row.format(i, self.get_block_name(i), type(data).__name__)
fmt += "</table>\n"
fmt += "\n"
fmt += "</td></tr> </table>"
return fmt
def __repr__(self) -> str:
"""Define an adequate representation."""
# return a string that is Python console friendly
fmt = f"{type(self).__name__} ({hex(id(self))})\n"
# now make a call on the object to get its attributes as a list of len 2 tuples
max_len = max(len(attr[0]) for attr in self._get_attrs()) + 4
row = " {:%ds}{}\n" % max_len
for attr in self._get_attrs():
try:
fmt += row.format(attr[0], attr[2].format(*attr[1]))
except:
fmt += row.format(attr[0], attr[2].format(attr[1]))
return fmt.strip()
def __str__(self) -> str:
"""Return the str representation of the multi block."""
return MultiBlock.__repr__(self)
def __len__(self) -> int:
"""Return the number of blocks."""
return self.n_blocks
def copy_meta_from(self, ido, deep): # numpydoc ignore=PR01
"""Copy pyvista meta data onto this object from another object."""
# Note that `pyvista.MultiBlock` datasets currently don't have any meta.
# This method is here for consistency with the rest of the API and
# in case we add meta data to this pbject down the road.
def copy(self, deep=True):
"""Return a copy of the multiblock.
Parameters
----------