-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathvtk.py
453 lines (417 loc) · 12.9 KB
/
vtk.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
import dash_vtk
import base64
import numpy as np
try:
# v9 and above
from vtkmodules.util.numpy_support import vtk_to_numpy
from vtkmodules.vtkFiltersGeometry import vtkGeometryFilter
except:
# v8.1.2 and below
print("Can't import vtkmodules. Falling back to importing vtk.")
from vtk.util.numpy_support import vtk_to_numpy
from vtk.vtkFiltersGeometry import vtkGeometryFilter
# Numpy to JS TypedArray
to_js_type = {
"int8": "Int8Array",
"uint8": "Uint8Array",
"int16": "Int16Array",
"uint16": "Uint16Array",
"int32": "Int32Array",
"uint32": "Uint32Array",
"int64": "Int32Array",
"uint64": "Uint32Array",
"float32": "Float32Array",
"float64": "Float64Array",
}
def b64_encode_numpy(obj):
# Convert 1D numpy arrays with numeric types to memoryviews with
# datatype and shape metadata.
if len(obj) == 0:
return obj.tolist()
dtype = obj.dtype
if (
dtype.kind in ["u", "i", "f"]
and str(dtype) != "int64"
and str(dtype) != "uint64"
):
# We have a numpy array that is compatible with JavaScript typed
# arrays
buffer = base64.b64encode(memoryview(obj.ravel(order="C"))).decode("utf-8")
return {"bvals": buffer, "dtype": str(dtype), "shape": obj.shape}
else:
buffer = None
dtype_str = None
# Try to see if we can downsize the array
max_value = np.amax(obj)
min_value = np.amin(obj)
signed = min_value < 0
test_value = max(max_value, -min_value)
if test_value < np.iinfo(np.int16).max and signed:
dtype_str = 'int16'
buffer = base64.b64encode(memoryview(obj.astype(np.int16).ravel(order="C"))).decode("utf-8")
elif test_value < np.iinfo(np.int32).max and signed:
dtype_str = 'int32'
buffer = base64.b64encode(memoryview(obj.astype(np.int32).ravel(order="C"))).decode("utf-8")
elif test_value < np.iinfo(np.uint16).max and not signed:
dtype_str = 'uint16'
buffer = base64.b64encode(memoryview(obj.astype(np.uint16).ravel(order="C"))).decode("utf-8")
elif test_value < np.iinfo(np.uint32).max and not signed:
dtype_str = 'uint32'
buffer = base64.b64encode(memoryview(obj.astype(np.uint32).ravel(order="C"))).decode("utf-8")
if dtype:
return {"bvals": buffer, "dtype": dtype_str, "shape": obj.shape}
# Convert all other numpy arrays to lists
return obj.tolist()
def to_mesh_state(dataset, field_to_keep=None, point_arrays=None, cell_arrays=None):
"""Expect any dataset and extract its surface into a dash_vtk.Mesh state property"""
if dataset is None:
return None
if point_arrays is None:
point_arrays = []
if cell_arrays is None:
cell_arrays = []
# Make sure we have a polydata to export
polydata = None
if dataset.IsA("vtkPolyData"):
polydata = dataset
else:
extractSkinFilter = vtkGeometryFilter()
extractSkinFilter.SetInputData(dataset)
extractSkinFilter.Update()
polydata = extractSkinFilter.GetOutput()
if polydata.GetPoints() is None:
return None
# Extract mesh
points = b64_encode_numpy(vtk_to_numpy(polydata.GetPoints().GetData()))
verts = (
b64_encode_numpy(vtk_to_numpy(polydata.GetVerts().GetData()))
if polydata.GetVerts()
else []
)
lines = (
b64_encode_numpy(vtk_to_numpy(polydata.GetLines().GetData()))
if polydata.GetLines()
else []
)
polys = (
b64_encode_numpy(vtk_to_numpy(polydata.GetPolys().GetData()))
if polydata.GetPolys()
else []
)
strips = (
b64_encode_numpy(vtk_to_numpy(polydata.GetStrips().GetData()))
if polydata.GetStrips()
else []
)
# Extract field
values = None
js_types = "Float32Array"
nb_comp = 1
dataRange = [0, 1]
location = None
if field_to_keep is not None:
p_array = polydata.GetPointData().GetArray(field_to_keep)
c_array = polydata.GetCellData().GetArray(field_to_keep)
if c_array:
dataRange = c_array.GetRange(-1)
nb_comp = c_array.GetNumberOfComponents()
values = vtk_to_numpy(c_array)
js_types = to_js_type[str(values.dtype)]
location = "CellData"
if p_array:
dataRange = p_array.GetRange(-1)
nb_comp = p_array.GetNumberOfComponents()
values = vtk_to_numpy(p_array)
js_types = to_js_type[str(values.dtype)]
location = "PointData"
state = {
"mesh": {"points": points,},
}
if len(verts):
state["mesh"]["verts"] = verts
if len(lines):
state["mesh"]["lines"] = lines
if len(polys):
state["mesh"]["polys"] = polys
if len(strips):
state["mesh"]["strips"] = strips
if values is not None:
state.update(
{
"field": {
"name": field_to_keep,
"values": b64_encode_numpy(values),
"numberOfComponents": nb_comp,
"type": js_types,
"location": location,
"dataRange": dataRange,
},
}
)
# other arrays (points)
point_data = []
for name in point_arrays:
array = polydata.GetPointData().GetArray(name)
if array:
dataRange = array.GetRange(-1)
nb_comp = array.GetNumberOfComponents()
values = vtk_to_numpy(array)
js_types = to_js_type[str(values.dtype)]
point_data.append(
{
"name": name,
"values": b64_encode_numpy(values),
"numberOfComponents": nb_comp,
"type": js_types,
"location": "PointData",
"dataRange": dataRange,
}
)
# other arrays (cells)
cell_data = []
for name in cell_arrays:
array = polydata.GetCellData().GetArray(name)
if array:
dataRange = array.GetRange(-1)
nb_comp = array.GetNumberOfComponents()
values = vtk_to_numpy(array)
js_types = to_js_type[str(values.dtype)]
cell_data.append(
{
"name": name,
"values": b64_encode_numpy(values),
"numberOfComponents": nb_comp,
"type": js_types,
"location": "CellData",
"dataRange": dataRange,
}
)
if len(point_data):
state.update({"pointArrays": point_data})
if len(cell_data):
state.update({"cellArrays": cell_data})
return state
def to_volume_state(dataset):
"""Expect a vtkImageData and extract its setting for the dash_vtk.Volume state"""
if dataset is None or not dataset.IsA("vtkImageData"):
return None
state = {
"image": {
"dimensions": dataset.GetDimensions(),
"spacing": dataset.GetSpacing(),
"origin": dataset.GetOrigin(),
},
}
# Capture image orientation if any
if hasattr(dataset, "GetDirectionMatrix"):
matrix = dataset.GetDirectionMatrix()
js_mat = []
for j in range(3):
for i in range(3):
js_mat.append(matrix.GetElement(i, j))
state["image"]["direction"] = js_mat
scalars = dataset.GetPointData().GetScalars()
if scalars is not None:
values = vtk_to_numpy(scalars)
js_types = to_js_type[str(values.dtype)]
state["field"] = {
"name": scalars.GetName(),
"numberOfComponents": scalars.GetNumberOfComponents(),
"dataRange": scalars.GetRange(-1),
"type": js_types,
"values": b64_encode_numpy(values),
}
return state
presets = [
"KAAMS",
"Cool to Warm",
"Cool to Warm (Extended)",
"Warm to Cool",
"Warm to Cool (Extended)",
"Rainbow Desaturated",
"Cold and Hot",
"Black-Body Radiation",
"X Ray",
"Grayscale",
"BkRd",
"BkGn",
"BkBu",
"BkMa",
"BkCy",
"Black, Blue and White",
"Black, Orange and White",
"Linear YGB 1211g",
"Linear Green (Gr4L)",
"Linear Blue (8_31f)",
"Blue to Red Rainbow",
"Red to Blue Rainbow",
"Rainbow Blended White",
"Rainbow Blended Grey",
"Rainbow Blended Black",
"Blue to Yellow",
"blot",
"CIELab Blue to Red",
"jet",
"rainbow",
"erdc_rainbow_bright",
"erdc_rainbow_dark",
"nic_CubicL",
"nic_CubicYF",
"gist_earth",
"2hot",
"erdc_red2yellow_BW",
"erdc_marine2gold_BW",
"erdc_blue2gold_BW",
"erdc_sapphire2gold_BW",
"erdc_red2purple_BW",
"erdc_purple2pink_BW",
"erdc_pbj_lin",
"erdc_blue2green_muted",
"erdc_blue2green_BW",
"GREEN-WHITE_LINEAR",
"erdc_green2yellow_BW",
"blue2cyan",
"erdc_blue2cyan_BW",
"erdc_blue_BW",
"BLUE-WHITE",
"erdc_purple_BW",
"erdc_magenta_BW",
"magenta",
"RED-PURPLE",
"erdc_red_BW",
"RED_TEMPERATURE",
"erdc_orange_BW",
"heated_object",
"erdc_gold_BW",
"erdc_brown_BW",
"copper_Matlab",
"pink_Matlab",
"bone_Matlab",
"gray_Matlab",
"Purples",
"Blues",
"Greens",
"PuBu",
"BuPu",
"BuGn",
"GnBu",
"GnBuPu",
"BuGnYl",
"PuRd",
"RdPu",
"Oranges",
"Reds",
"RdOr",
"BrOrYl",
"RdOrYl",
"CIELab_blue2red",
"blue2yellow",
"erdc_blue2gold",
"erdc_blue2yellow",
"erdc_cyan2orange",
"erdc_purple2green",
"erdc_purple2green_dark",
"coolwarm",
"BuRd",
"Spectral_lowBlue",
"GnRP",
"GYPi",
"GnYlRd",
"GBBr",
"PuOr",
"PRGn",
"PiYG",
"OrPu",
"BrBG",
"GyRd",
"erdc_divHi_purpleGreen",
"erdc_divHi_purpleGreen_dim",
"erdc_divLow_icePeach",
"erdc_divLow_purpleGreen",
"Haze_green",
"Haze_lime",
"Haze",
"Haze_cyan",
"nic_Edge",
"erdc_iceFire_H",
"erdc_iceFire_L",
"hsv",
"hue_L60",
"Spectrum",
"Warm",
"Cool",
"Blues",
"Wild Flower",
"Citrus",
"Brewer Diverging Purple-Orange (11)",
"Brewer Diverging Purple-Orange (10)",
"Brewer Diverging Purple-Orange (9)",
"Brewer Diverging Purple-Orange (8)",
"Brewer Diverging Purple-Orange (7)",
"Brewer Diverging Purple-Orange (6)",
"Brewer Diverging Purple-Orange (5)",
"Brewer Diverging Purple-Orange (4)",
"Brewer Diverging Purple-Orange (3)",
"Brewer Diverging Spectral (11)",
"Brewer Diverging Spectral (10)",
"Brewer Diverging Spectral (9)",
"Brewer Diverging Spectral (8)",
"Brewer Diverging Spectral (7)",
"Brewer Diverging Spectral (6)",
"Brewer Diverging Spectral (5)",
"Brewer Diverging Spectral (4)",
"Brewer Diverging Spectral (3)",
"Brewer Diverging Brown-Blue-Green (11)",
"Brewer Diverging Brown-Blue-Green (10)",
"Brewer Diverging Brown-Blue-Green (9)",
"Brewer Diverging Brown-Blue-Green (8)",
"Brewer Diverging Brown-Blue-Green (7)",
"Brewer Diverging Brown-Blue-Green (6)",
"Brewer Diverging Brown-Blue-Green (5)",
"Brewer Diverging Brown-Blue-Green (4)",
"Brewer Diverging Brown-Blue-Green (3)",
"Brewer Sequential Blue-Green (9)",
"Brewer Sequential Blue-Green (8)",
"Brewer Sequential Blue-Green (7)",
"Brewer Sequential Blue-Green (6)",
"Brewer Sequential Blue-Green (5)",
"Brewer Sequential Blue-Green (4)",
"Brewer Sequential Blue-Green (3)",
"Brewer Sequential Yellow-Orange-Brown (9)",
"Brewer Sequential Yellow-Orange-Brown (8)",
"Brewer Sequential Yellow-Orange-Brown (7)",
"Brewer Sequential Yellow-Orange-Brown (6)",
"Brewer Sequential Yellow-Orange-Brown (5)",
"Brewer Sequential Yellow-Orange-Brown (4)",
"Brewer Sequential Yellow-Orange-Brown (3)",
"Brewer Sequential Blue-Purple (9)",
"Brewer Sequential Blue-Purple (8)",
"Brewer Sequential Blue-Purple (7)",
"Brewer Sequential Blue-Purple (6)",
"Brewer Sequential Blue-Purple (5)",
"Brewer Sequential Blue-Purple (4)",
"Brewer Sequential Blue-Purple (3)",
"Brewer Qualitative Accent",
"Brewer Qualitative Dark2",
"Brewer Qualitative Set2",
"Brewer Qualitative Pastel2",
"Brewer Qualitative Pastel1",
"Brewer Qualitative Set1",
"Brewer Qualitative Paired",
"Brewer Qualitative Set3",
"Traffic Lights",
"Traffic Lights For Deuteranopes",
"Traffic Lights For Deuteranopes 2",
"Muted Blue-Green",
"Green-Blue Asymmetric Divergent (62Blbc)",
"Asymmtrical Earth Tones (6_21b)",
"Yellow 15",
"Magma (matplotlib)",
"Inferno (matplotlib)",
"Plasma (matplotlib)",
"Viridis (matplotlib)",
"BlueObeliskElements",
]
def toDropOption(name):
return {"label": name, "value": name}
preset_as_options = list(map(toDropOption, presets))