forked from pyvista/pyvista
/
container.py
405 lines (331 loc) · 12.3 KB
/
container.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
"""
Container to mimic ``vtkMultiBlockDataSet`` objects. These classes hold many
VTK datasets in one object that can be passed to VTK algorithms and ``vtki``
filtering/plotting routines.
"""
import collections
import logging
import os
import numpy as np
import vtk
from vtk import vtkMultiBlockDataSet
import vtki
from vtki import plot
from vtki.utilities import get_scalar, is_vtki_obj, wrap
log = logging.getLogger(__name__)
log.setLevel('CRITICAL')
class MultiBlock(vtkMultiBlockDataSet):
"""
A container class to hold many data sets which can be iterated over.
This wraps/extends the ``vtkMultiBlockDataSet`` class in VTK so that we can
easily plot these data sets and use the container in a Pythonic manner.
"""
# Bind vtki.plotting.plot to the object
plot = plot
def __init__(self, *args, **kwargs):
super(MultiBlock, self).__init__()
deep = kwargs.pop('deep', False)
if len(args) == 1:
if isinstance(args[0], vtk.vtkMultiBlockDataSet):
if deep:
self.DeepCopy(args[0])
else:
self.ShallowCopy(args[0])
elif isinstance(args[0], (list, tuple)):
for block in args[0]:
self.append(block)
elif isinstance(args[0], str):
self._load_file(args[0])
elif isinstance(args[0], dict):
idx = 0
for key, block in args[0].items():
self[idx, key] = block
idx += 1
def extract_geometry(self):
"""Combines the geomertry of all blocks into a single ``PolyData``
object. Place this filter at the end of a pipeline before a polydata
consumer such as a polydata mapper to extract geometry from all blocks
and append them to one polydata object.
"""
gf = vtk.vtkCompositeDataGeometryFilter()
gf.SetInputData(self)
gf.Update()
return wrap(gf.GetOutputDataObject(0))
def combine(self, merge_points=False):
"""Appends all blocks into a single unstructured grid.
Parameters
----------
merge_points : bool, optional
Merge coincidental points.
"""
alg = vtk.vtkAppendFilter()
for block in self:
alg.AddInputData(block)
alg.SetMergePoints(merge_points)
alg.Update()
return wrap(alg.GetOutputDataObject(0))
def _load_file(self, filename):
"""Load a vtkMultiBlockDataSet from a file (extension ``.vtm`` or
``.vtmb``)
"""
filename = os.path.abspath(os.path.expanduser(filename))
# test if file exists
if not os.path.isfile(filename):
raise Exception('File %s does not exist' % filename)
# Get extension
ext = vtki.get_ext(filename)
# Extensions: .vtm and .vtmb
# Select reader
if ext in ['.vtm', '.vtmb']:
reader = vtk.vtkXMLMultiBlockDataReader()
else:
raise IOError('File extension must be either "vtm" or "vtmb"')
# Load file
reader.SetFileName(filename)
reader.Update()
self.ShallowCopy(reader.GetOutput())
def save(self, filename, binary=True):
"""
Writes a ``MultiBlock`` dataset to disk.
Written file may be an ASCII or binary vtm file.
Parameters
----------
filename : str
Filename of mesh to be written. File type is inferred from
the extension of the filename unless overridden with
ftype. Can be one of the following types (.vtm or .vtmb)
binary : bool, optional
Writes the file as binary when True and ASCII when False.
Notes
-----
Binary files write much faster than ASCII and have a smaller
file size.
"""
filename = os.path.abspath(os.path.expanduser(filename))
ext = vtki.get_ext(filename)
if ext in ['.vtm', '.vtmb']:
writer = vtk.vtkXMLMultiBlockDataWriter()
else:
raise Exception('File extension must be either "vtm" or "vtmb"')
writer.SetFileName(filename)
writer.SetInputDataObject(self)
if binary:
writer.SetDataModeToBinary()
else:
writer.SetDataModeToAscii()
writer.Write()
return
@property
def bounds(self):
"""Finds min/max for bounds across blocks
Returns:
tuple(float):
length 6 tuple of floats containing min/max along each axis
"""
bounds = [np.inf,-np.inf, np.inf,-np.inf, np.inf,-np.inf]
def update_bounds(ax, nb, bounds):
"""internal helper to update bounds while keeping track"""
if nb[2*ax] < bounds[2*ax]:
bounds[2*ax] = nb[2*ax]
if nb[2*ax+1] > bounds[2*ax+1]:
bounds[2*ax+1] = nb[2*ax+1]
return bounds
# get bounds for each block and update
for i in range(self.n_blocks):
try:
bnds = self[i].GetBounds()
for a in range(3):
bounds = update_bounds(a, bnds, bounds)
except AttributeError:
# Data object doesn't have bounds or is None
pass
return bounds
@property
def n_blocks(self):
"""The total number of blocks set"""
return self.GetNumberOfBlocks()
@n_blocks.setter
def n_blocks(self, n):
"""The total number of blocks set"""
self.SetNumberOfBlocks(n)
self.Modified()
def get_data_range(self, name):
"""Gets the min/max of a scalar given its name across all blocks"""
mini, maxi = np.inf, -np.inf
for i in range(self.n_blocks):
data = self[i]
if data is None:
continue
# get the scalar if availble
arr = get_scalar(data, name)
if arr is None:
continue
tmi, tma = np.nanmin(arr), np.nanmax(arr)
if tmi < mini:
mini = tmi
if tma > maxi:
maxi = tma
return mini, maxi
def get_index_by_name(self, name):
"""Find the index number by block name"""
for i in range(self.n_blocks):
if self.get_block_name(i) == name:
return i
raise KeyError('Block name ({}) not found'.format(name))
def __getitem__(self, index):
"""Get a block by its index or name (if the name is non-unique then
returns the first occurence)"""
if isinstance(index, str):
index = self.get_index_by_name(index)
data = self.GetBlock(index)
if data is None:
return data
if data is not None and not is_vtki_obj(data):
data = wrap(data)
return data
def append(self, data):
"""Add a data set to the next block index"""
index = self.n_blocks # note off by one so ues as index
self[index] = data
def get(self, index):
"""Get a block by its index or name (if the name is non-unique then
returns the first occurence)"""
return self[index]
def set_block_name(self, index, name):
"""Set a block's string name at the specified index"""
if name is None:
return
self.GetMetaData(index).Set(vtk.vtkCompositeDataSet.NAME(), name)
self.Modified()
def get_block_name(self, index):
"""Returns the string name of the block at the given index"""
meta = self.GetMetaData(index)
if meta is not None:
return meta.Get(vtk.vtkCompositeDataSet.NAME())
return None
def keys(self):
"""Get all the block names in the dataset"""
names = []
for i in range(self.n_blocks):
names.append(self.get_block_name(i))
return names
def __setitem__(self, index, data):
"""Sets a block with a VTK data object. To set the name simultaneously,
pass a string name as the 2nd index.
Example
-------
>>> import vtki
>>> multi = vtki.MultiBlock()
>>> multi[0] = vtki.PolyData()
>>> multi[1, 'foo'] = vtki.UnstructuredGrid()
>>> multi['bar'] = vtki.PolyData()
>>> multi.n_blocks
3
"""
if isinstance(index, collections.Iterable) and not isinstance(index, str):
i, name = index[0], index[1]
elif isinstance(index, str):
try:
i = self.get_index_by_name(index)
except KeyError:
i = -1
name = index
else:
i, name = index, None
if data is not None and not is_vtki_obj(data):
data = wrap(data)
if i == -1:
self.append(data)
i = self.n_blocks - 1
else:
self.SetBlock(i, data)
if name is None:
name = 'Block-{0:02}'.format(i)
self.set_block_name(i, name) # Note that this calls self.Modified()
def __delitem__(self, index):
"""Removes a block at the specified index"""
if isinstance(index, str):
index = self.get_index_by_name(index)
self.RemoveBlock(index)
def __iter__(self):
"""The iterator across all blocks"""
self._iter_n = 0
return self
def next(self):
"""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
else:
raise StopIteration
__next__ = next
def pop(self, index):
"""Pops off a block at the specified index"""
data = self[index]
del self[index]
return data
## TODO: I can't get this to work as expected
# def clean(self):
# """This will remove any null blocks"""
# nvalid = 0
# for i in range(self.n_blocks):
# print(i, type(self[i]), self[i], self.get_block_name(i))
# if self[i] is None:
# print('removing', i)
# del self[i]
# else:
# nvalid += 1
# #self.n_blocks = nvalid
# print('nvalid', nvalid)
# return
def _get_attrs(self):
"""An internal helper for the representation methods"""
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):
"""A pretty representation for Jupyter notebooks"""
fmt = ""
fmt += "<table>"
fmt += "<tr><th>Information</th><th>Blocks</th></tr>"
fmt += "<tr><td>"
fmt += "\n"
fmt += "<table>\n"
fmt += "<tr><th>{}</th><th>Values</th></tr>\n".format(type(self).__name__)
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):
# return a string that is Python console friendly
fmt = "{} ({})\n".format(type(self).__name__, hex(id(self)))
# now make a call on the object to get its attributes as a list of len 2 tuples
row = " {}:\t{}\n"
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