-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvtk_functions.py
executable file
·463 lines (377 loc) · 12.4 KB
/
vtk_functions.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
#!/usr/bin/env python
import os
import vtk
import pdb
import numpy as np
from collections import defaultdict
from tqdm import tqdm
from vtk.util.numpy_support import numpy_to_vtk as n2v
from vtk.util.numpy_support import vtk_to_numpy as v2n
class Integration:
"""
Class to perform integration on slices
"""
def __init__(self, inp):
try:
self.integrator = vtk.vtkIntegrateAttributes()
except AttributeError:
raise Exception('vtkIntegrateAttributes is currently only supported by pvpython')
if not inp.GetOutput().GetNumberOfPoints():
raise Exception('Empty slice')
self.integrator.SetInputData(inp.GetOutput())
self.integrator.Update()
def evaluate(self, res_name):
"""
Evaluate integral.
Distinguishes between scalar integration (e.g. pressure) and normal projection (velocity)
Optionally divides integral by integrated area
Args:
field: pressure, velocity, ...
res_name: name of array
Returns:
Scalar integral
"""
# type of result
field = res_name.split('_')[0]
if field == 'velocity':
int_name = 'normal_' + res_name
else:
int_name = res_name
# evaluate integral
integral = v2n(self.integrator.GetOutput().GetPointData().GetArray(int_name))[0]
# choose if integral should be divided by area
if field == 'velocity':
return integral
else:
return integral / self.area()
def area(self):
"""
Evaluate integrated surface area
Returns:
Area
"""
return v2n(self.integrator.GetOutput().GetCellData().GetArray('Area'))[0]
class ClosestPoints:
"""
Find closest points within a geometry
"""
def __init__(self, inp):
if isinstance(inp, str):
geo = read_geo(inp)
inp = geo.GetOutput()
dataset = vtk.vtkPolyData()
dataset.SetPoints(inp.GetPoints())
locator = vtk.vtkPointLocator()
locator.Initialize()
locator.SetDataSet(dataset)
locator.BuildLocator()
self.locator = locator
def search(self, points, radius=None):
"""
Get ids of points in geometry closest to input points
Args:
points: list of points to be searched
radius: optional, search radius
Returns:
Id list
"""
ids = []
for p in points:
if radius is not None:
result = vtk.vtkIdList()
self.locator.FindPointsWithinRadius(radius, p, result)
ids += [result.GetId(k) for k in range(result.GetNumberOfIds())]
else:
ids += [self.locator.FindClosestPoint(p)]
return ids
def collect_arrays(output):
res = {}
for i in range(output.GetNumberOfArrays()):
name = output.GetArrayName(i)
data = output.GetArray(i)
res[name] = v2n(data)
return res
def get_all_arrays(geo):
# collect all arrays
cell_data = collect_arrays(geo.GetCellData())
point_data = collect_arrays(geo.GetPointData())
return point_data, cell_data
def read_geo(fname):
"""
Read geometry from file, chose corresponding vtk reader
Args:
fname: vtp surface or vtu volume mesh
Returns:
vtk reader, point data, cell data
"""
_, ext = os.path.splitext(fname)
if ext == '.vtp':
reader = vtk.vtkXMLPolyDataReader()
elif ext == '.vtu':
reader = vtk.vtkXMLUnstructuredGridReader()
else:
raise ValueError('File extension ' + ext + ' unknown.')
reader.SetFileName(fname)
reader.Update()
return reader
def write_geo(fname, input):
"""
Write geometry to file
Args:
fname: file name
"""
_, ext = os.path.splitext(fname)
if ext == '.vtp':
writer = vtk.vtkXMLPolyDataWriter()
elif ext == '.vtu':
writer = vtk.vtkXMLUnstructuredGridWriter()
else:
raise ValueError('File extension ' + ext + ' unknown.')
writer.SetFileName(fname)
writer.SetInputData(input)
writer.Update()
writer.Write()
def threshold(inp, t, name):
"""
Threshold according to cell array
Args:
inp: InputConnection
t: BC_FaceID
name: name in cell data used for thresholding
Returns:
reader, point data
"""
thresh = vtk.vtkThreshold()
thresh.SetInputData(inp)
thresh.SetInputArrayToProcess(0, 0, 0, 1, name)
thresh.ThresholdBetween(t, t)
thresh.Update()
return thresh
def calculator(inp, function, inp_arrays, out_array):
"""
Function to add vtk calculator
Args:
inp: InputConnection
function: string with function expression
inp_arrays: list of input point data arrays
out_array: name of output array
Returns:
calc: calculator object
"""
calc = vtk.vtkArrayCalculator()
for a in inp_arrays:
calc.AddVectorArrayName(a)
calc.SetInputData(inp.GetOutput())
if hasattr(calc, 'SetAttributeModeToUsePointData'):
calc.SetAttributeModeToUsePointData()
else:
calc.SetAttributeTypeToPointData()
calc.SetFunction(function)
calc.SetResultArrayName(out_array)
calc.Update()
return calc
def cut_plane(inp, origin, normal):
"""
Cuts geometry at a plane
Args:
inp: InputConnection
origin: cutting plane origin
normal: cutting plane normal
Returns:
cut: cutter object
"""
# define cutting plane
plane = vtk.vtkPlane()
plane.SetOrigin(origin[0], origin[1], origin[2])
plane.SetNormal(normal[0], normal[1], normal[2])
# define cutter
cut = vtk.vtkCutter()
cut.SetInputData(inp)
cut.SetCutFunction(plane)
cut.Update()
return cut
def get_points_cells(inp):
cells = []
for i in range(inp.GetNumberOfCells()):
cell_points = []
for j in range(inp.GetCell(i).GetNumberOfPoints()):
cell_points += [inp.GetCell(i).GetPointId(j)]
cells += [cell_points]
return v2n(inp.GetPoints().GetData()), np.array(cells)
def connectivity(inp, origin):
"""
If there are more than one unconnected geometries, extract the closest one
Args:
inp: InputConnection
origin: region closest to this point will be extracted
Returns:
con: connectivity object
"""
con = vtk.vtkConnectivityFilter()
con.SetInputData(inp.GetOutput())
con.SetExtractionModeToClosestPointRegion()
con.SetClosestPoint(origin[0], origin[1], origin[2])
con.Update()
return con
def connectivity_all(inp):
"""
Color regions according to connectivity
Args:
inp: InputConnection
Returns:
con: connectivity object
"""
con = vtk.vtkConnectivityFilter()
con.SetInputData(inp)
con.SetExtractionModeToAllRegions()
con.ColorRegionsOn()
con.Update()
assert con.GetNumberOfExtractedRegions() > 0, 'empty geometry'
return con
def extract_surface(inp):
"""
Extract surface from 3D geometry
Args:
inp: InputConnection
Returns:
extr: vtkExtractSurface object
"""
extr = vtk.vtkDataSetSurfaceFilter()
extr.SetInputData(inp)
extr.Update()
return extr.GetOutput()
def clean(inp):
"""
Merge duplicate Points
"""
cleaner = vtk.vtkCleanPolyData()
cleaner.SetInputData(inp)
# cleaner.SetTolerance(1.0e-3)
cleaner.PointMergingOn()
cleaner.Update()
return cleaner.GetOutput()
def scalar_array(length, name, fill):
"""
Create vtkIdTypeArray array with given name and constant value
"""
ids = vtk.vtkIdTypeArray()
ids.SetNumberOfValues(length)
ids.SetName(name)
ids.Fill(fill)
return ids
def add_scalars(inp, name, fill):
"""
Add constant value array to point and cell data
"""
inp.GetOutput().GetCellData().AddArray(scalar_array(inp.GetOutput().GetNumberOfCells(), name, fill))
inp.GetOutput().GetPointData().AddArray(scalar_array(inp.GetOutput().GetNumberOfPoints(), name, fill))
def rename(inp, old, new):
if inp.GetOutput().GetCellData().HasArray(new):
inp.GetOutput().GetCellData().RemoveArray(new)
if inp.GetOutput().GetPointData().HasArray(new):
inp.GetOutput().GetPointData().RemoveArray(new)
inp.GetOutput().GetCellData().GetArray(old).SetName(new)
inp.GetOutput().GetPointData().GetArray(old).SetName(new)
def replace(inp, name, array):
arr = n2v(array)
arr.SetName(name)
inp.GetOutput().GetCellData().RemoveArray(name)
inp.GetOutput().GetCellData().AddArray(arr)
def geo(inp):
poly = vtk.vtkGeometryFilter()
poly.SetInputData(inp)
poly.Update()
return poly.GetOutput()
def region_grow(geo, seed_points, seed_ids, n_max=99):
# initialize output arrays
array_ids = -1 * np.ones(geo.GetNumberOfPoints(), dtype=int)
array_rad = np.zeros(geo.GetNumberOfPoints())
array_dist = -1 * np.ones(geo.GetNumberOfPoints(), dtype=int)
array_ids[seed_points] = seed_ids
# initialize ids
cids_all = set()
pids_all = set(seed_points.tolist())
pids_new = set(seed_points.tolist())
# get points
pts = v2n(geo.GetPoints().GetData())
# loop until region stops growing or reaches maximum number of iterations
i = 0
while len(pids_new) > 0 and i < n_max:
# update
pids_old = pids_new
# print progress
print_str = 'Iteration ' + str(i)
print_str += '\tNew points ' + str(len(pids_old)) + ' '
print_str += '\tTotal points ' + str(len(pids_all))
print(print_str)
# grow region one step
pids_new = grow(geo, array_ids, pids_old, pids_all, cids_all)
# convert to array
pids_old_arr = list(pids_old)
# create point locator with old wave front
points = vtk.vtkPoints()
points.Initialize()
for i_old in pids_old:
points.InsertNextPoint(geo.GetPoint(i_old))
dataset = vtk.vtkPolyData()
dataset.SetPoints(points)
locator = vtk.vtkPointLocator()
locator.Initialize()
locator.SetDataSet(dataset)
locator.BuildLocator()
# find closest point in new wave front
for i_new in pids_new:
i_old = pids_old_arr[locator.FindClosestPoint(geo.GetPoint(i_new))]
array_ids[i_new] = array_ids[i_old]
array_rad[i_new] = array_rad[i_old] + np.linalg.norm(pts[i_new] - pts[i_old])
array_dist[i_new] = i
# count grow iterations
i += 1
return array_ids, array_dist + 1, array_rad
def grow(geo, array, pids_in, pids_all, cids_all):
# ids of propagating wave-front
pids_out = set()
# loop all points in wave-front
for pi_old in pids_in:
cids = vtk.vtkIdList()
geo.GetPointCells(pi_old, cids)
# get all connected cells in wave-front
for j in range(cids.GetNumberOfIds()):
# get cell id
ci = cids.GetId(j)
# skip cells that are already in region
if ci in cids_all:
continue
else:
cids_all.add(ci)
pids = vtk.vtkIdList()
geo.GetCellPoints(ci, pids)
# loop all points in cell
for k in range(pids.GetNumberOfIds()):
# get point id
pi_new = pids.GetId(k)
# add point only if it's new and doesn't fullfill stopping criterion
if array[pi_new] == -1 and pi_new not in pids_in:
pids_out.add(pi_new)
pids_all.add(pi_new)
return pids_out
def cell_connectivity(geo):
"""
Extract the point connectivity from vtk and return a dictionary that can be used in meshio
"""
vtk_to_meshio = {3: 'line', 5: 'triangle', 10: 'tetra'}
cells = defaultdict(list)
for i in range(geo.GetNumberOfCells()):
cell_type_vtk = geo.GetCellType(i)
if cell_type_vtk in vtk_to_meshio:
cell_type = vtk_to_meshio[cell_type_vtk]
else:
raise ValueError('vtkCellType ' + str(cell_type_vtk) + ' not supported')
points = geo.GetCell(i).GetPointIds()
point_ids = []
for j in range(points.GetNumberOfIds()):
point_ids += [points.GetId(j)]
cells[cell_type] += [point_ids]
for t, c in cells.items():
cells[t] = np.array(c)
return cells