/
vtk.py
667 lines (574 loc) · 19.7 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
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
# ***********************************************************************************
# * Copyright 2010 - 2016 Paulo A. Herrera. All rights reserved. *
# * *
# * Redistribution and use in source and binary forms, with or without *
# * modification, are permitted provided that the following conditions are met: *
# * *
# * 1. Redistributions of source code must retain the above copyright notice, *
# * this list of conditions and the following disclaimer. *
# * *
# * 2. Redistributions in binary form must reproduce the above copyright notice, *
# * this list of conditions and the following disclaimer in the documentation *
# * and/or other materials provided with the distribution. *
# * *
# * THIS SOFTWARE IS PROVIDED BY PAULO A. HERRERA ``AS IS'' AND ANY EXPRESS OR *
# * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF *
# * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO *
# * EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, *
# * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, *
# * BUT NOT LIMITED TO, PROCUREMEN OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, *
# * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY *
# * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING *
# * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *
# * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
# ***********************************************************************************
"""Low level Python library to export data to binary VTK file."""
import sys
import os
import numpy as np
from .evtk import writeBlockSize, writeArrayToFile, writeArraysToFile
from .xml import XmlWriter
# ================================
# VTK Types
# ================================
# FILE TYPES
class VtkFileType:
"""
Wrapper class for VTK file types.
Parameters
----------
name : str
Data name.
ext : str
File extension.
"""
def __init__(self, name, ext):
self.name = name
self.ext = ext
def __str__(self):
return "Name: %s Ext: %s \n" % (self.name, self.ext)
VtkImageData = VtkFileType("ImageData", ".vti")
VtkPolyData = VtkFileType("PolyData", ".vtp")
VtkRectilinearGrid = VtkFileType("RectilinearGrid", ".vtr")
VtkStructuredGrid = VtkFileType("StructuredGrid", ".vts")
VtkUnstructuredGrid = VtkFileType("UnstructuredGrid", ".vtu")
# DATA TYPES
class VtkDataType:
"""
Wrapper class for VTK data types.
Parameters
----------
size : int
Size in byte.
name : str
Type name.
"""
def __init__(self, size, name):
self.size = size
self.name = name
def __str__(self):
return "Type: %s Size: %d \n" % (self.name, self.size)
VtkInt8 = VtkDataType(1, "Int8")
VtkUInt8 = VtkDataType(1, "UInt8")
VtkInt16 = VtkDataType(2, "Int16")
VtkUInt16 = VtkDataType(2, "UInt16")
VtkInt32 = VtkDataType(4, "Int32")
VtkUInt32 = VtkDataType(4, "UInt32")
VtkInt64 = VtkDataType(8, "Int64")
VtkUInt64 = VtkDataType(8, "UInt64")
VtkFloat32 = VtkDataType(4, "Float32")
VtkFloat64 = VtkDataType(8, "Float64")
# Map numpy to VTK data types
np_to_vtk = {
"int8": VtkInt8,
"uint8": VtkUInt8,
"int16": VtkInt16,
"uint16": VtkUInt16,
"int32": VtkInt32,
"uint32": VtkUInt32,
"int64": VtkInt64,
"uint64": VtkUInt64,
"float32": VtkFloat32,
"float64": VtkFloat64,
}
# CELL TYPES
class VtkCellType:
"""
Wrapper class for VTK cell types.
Parameters
----------
tid : int
Type ID.
name : str
Cell type name.
"""
def __init__(self, tid, name):
self.tid = tid
self.name = name
def __str__(self):
return "VtkCellType( %s ) \n" % (self.name)
VtkVertex = VtkCellType(1, "Vertex")
VtkPolyVertex = VtkCellType(2, "PolyVertex")
VtkLine = VtkCellType(3, "Line")
VtkPolyLine = VtkCellType(4, "PolyLine")
VtkTriangle = VtkCellType(5, "Triangle")
VtkTriangleStrip = VtkCellType(6, "TriangleStrip")
VtkPolygon = VtkCellType(7, "Polygon")
VtkPixel = VtkCellType(8, "Pixel")
VtkQuad = VtkCellType(9, "Quad")
VtkTetra = VtkCellType(10, "Tetra")
VtkVoxel = VtkCellType(11, "Voxel")
VtkHexahedron = VtkCellType(12, "Hexahedron")
VtkWedge = VtkCellType(13, "Wedge")
VtkPyramid = VtkCellType(14, "Pyramid")
VtkQuadraticEdge = VtkCellType(21, "Quadratic_Edge")
VtkQuadraticTriangle = VtkCellType(22, "Quadratic_Triangle")
VtkQuadraticQuad = VtkCellType(23, "Quadratic_Quad")
VtkQuadraticTetra = VtkCellType(24, "Quadratic_Tetra")
VtkQuadraticHexahedron = VtkCellType(25, "Quadratic_Hexahedron")
# ==============================
# Helper functions
# ==============================
def _mix_extents(start, end):
assert len(start) == len(end) == 3
string = "%d %d %d %d %d %d" % (
start[0],
end[0],
start[1],
end[1],
start[2],
end[2],
)
return string
def _array_to_string(a):
s = "".join([repr(num) + " " for num in a])
return s
def _get_byte_order():
if sys.byteorder == "little":
return "LittleEndian"
return "BigEndian"
# ================================
# VtkGroup class
# ================================
class VtkGroup:
"""
Creates a VtkGroup file that is stored in filepath.
Parameters
----------
filepath : str
filename without extension.
"""
def __init__(self, filepath):
self.xml = XmlWriter(filepath + ".pvd")
self.xml.openElement("VTKFile")
self.xml.addAttributes(
type="Collection", version="0.1", byte_order=_get_byte_order()
)
self.xml.openElement("Collection")
self.root = os.path.dirname(filepath)
def save(self):
"""Close this VtkGroup."""
self.xml.closeElement("Collection")
self.xml.closeElement("VTKFile")
self.xml.close()
def addFile(self, filepath, sim_time, group="", part="0"):
"""
Add a file to this VTK group.
Parameters
----------
filepath : str
full path to VTK file.
sim_time : float
simulated time.
group : str, optional
This attribute is not required;
it is only for informational purposes.
The default is "".
part : int, optional
It is an integer value greater than or equal to 0.
The default is "0".
Notes
-----
See: http://www.paraview.org/Wiki/ParaView/Data_formats#PVD_File_Format for details.
"""
# TODO: Check what the other attributes are for.
filename = os.path.relpath(filepath, start=self.root)
self.xml.openElement("DataSet")
self.xml.addAttributes(
timestep=sim_time, group=group, part=part, file=filename
)
self.xml.closeElement()
# ================================
# VtkFile class
# ================================
class VtkFile:
"""
Class for a VTK file.
Parameters
----------
filepath : str
filename without extension.
ftype : str
file type, e.g. VtkImageData, etc.
largeFile : bool, optional
If size of the stored data cannot be represented by a UInt32.
The default is False.
"""
def __init__(self, filepath, ftype):
self.ftype = ftype
self.filename = filepath + ftype.ext
self.xml = XmlWriter(self.filename)
self.offset = 0 # offset in bytes after beginning of binary section
self.appendedDataIsOpen = False
self.xml.openElement("VTKFile").addAttributes(
type=ftype.name,
version="1.0",
byte_order=_get_byte_order(),
header_type="UInt64",
)
def getFileName(self):
"""Return absolute path to this file."""
return os.path.abspath(self.filename)
def openPiece(
self,
start=None,
end=None,
npoints=None,
ncells=None,
nverts=None,
nlines=None,
nstrips=None,
npolys=None,
):
"""
Open piece section.
Parameters
----------
start : array-like, optional
array or list with start indexes in each direction.
Must be given with end.
end : array-like, optional
array or list with end indexes in each direction.
Must be given with start.
npoints : int, optional
number of points in piece
ncells : int, optional
number of cells in piece.
If present, npoints must also be given.
nverts : int, optional
number of vertices.
nlines : int, optional
number of lines.
nstrips : int, optional
number of stripes.
npolys : int, optional
number of poly.
Returns
-------
VtkFile
This VtkFile to allow chained calls.
"""
# TODO: Check what are the requirements for each type of grid.
self.xml.openElement("Piece")
if start and end:
ext = _mix_extents(start, end)
self.xml.addAttributes(Extent=ext)
elif ncells and npoints:
self.xml.addAttributes(
NumberOfPoints=npoints, NumberOfCells=ncells
)
elif npoints or nverts or nlines or nstrips or npolys:
if npoints is None:
npoints = str(0)
if nverts is None:
nverts = str(0)
if nlines is None:
nlines = str(0)
if nstrips is None:
nstrips = str(0)
if npolys is None:
npolys = str(0)
self.xml.addAttributes(
NumberOfPoints=npoints,
NumberOfVerts=nverts,
NumberOfLines=nlines,
NumberOfStrips=nstrips,
NumberOfPolys=npolys,
)
else:
assert False
return self
def closePiece(self):
"""Close Piece."""
self.xml.closeElement("Piece")
def openData(
self,
nodeType,
scalars=None,
vectors=None,
normals=None,
tensors=None,
tcoords=None,
):
"""
Open data section.
Parameters
----------
nodeType : str
Either "Point", "Cell" or "Field".
scalars : str, optional
default data array name for scalar data.
vectors : str, optional
default data array name for vector data.
normals : str, optional
default data array name for normals data.
tensors : str, optional
default data array name for tensors data.
tcoords : str, optional
default data array name for tcoords data.
Returns
-------
VtkFile
This VtkFile to allow chained calls.
"""
self.xml.openElement(nodeType + "Data")
if scalars:
self.xml.addAttributes(Scalars=scalars)
if vectors:
self.xml.addAttributes(Vectors=vectors)
if normals:
self.xml.addAttributes(Normals=normals)
if tensors:
self.xml.addAttributes(Tensors=tensors)
if tcoords:
self.xml.addAttributes(TCoords=tcoords)
return self
def closeData(self, nodeType):
"""
Close data section.
Parameters
----------
nodeType : str
"Point", "Cell" or "Field".
Returns
-------
VtkFile
This VtkFile to allow chained calls.
"""
self.xml.closeElement(nodeType + "Data")
def openGrid(self, start=None, end=None, origin=None, spacing=None):
"""
Open grid section.
Parameters
----------
start : array-like, optional
array or list of start indexes.
Required for Structured, Rectilinear and ImageData grids.
The default is None.
end : array-like, optional
array or list of end indexes.
Required for Structured, Rectilinear and ImageData grids.
The default is None.
origin : array-like, optional
3D array or list with grid origin.
Only required for ImageData grids.
The default is None.
spacing : array-like, optional
3D array or list with grid spacing.
Only required for ImageData grids.
The default is None.
Returns
-------
VtkFile
This VtkFile to allow chained calls.
"""
gType = self.ftype.name
self.xml.openElement(gType)
if gType == VtkImageData.name:
if not start or not end or not origin or not spacing:
assert False
ext = _mix_extents(start, end)
self.xml.addAttributes(
WholeExtent=ext,
Origin=_array_to_string(origin),
Spacing=_array_to_string(spacing),
)
elif gType in [VtkStructuredGrid.name, VtkRectilinearGrid.name]:
if not start or not end:
assert False
ext = _mix_extents(start, end)
self.xml.addAttributes(WholeExtent=ext)
return self
def closeGrid(self):
"""
Close grid element.
Returns
-------
VtkFile
This VtkFile to allow chained calls.
"""
self.xml.closeElement(self.ftype.name)
def addHeader(self, name, dtype, nelem, ncomp):
"""
Add data array description to xml header section.
Parameters
----------
name : str
data array name.
dtype : str
data type.
nelem : int
number of elements in array.
ncomp : int
number of components, 1 (=scalar) and 3 (=vector).
Returns
-------
VtkFile
This VtkFile to allow chained calls.
Notes
-----
This is a low level function.
Use addData if you want to add a numpy array.
"""
dtype = np_to_vtk[dtype]
self.xml.openElement("DataArray")
self.xml.addAttributes(
Name=name,
NumberOfComponents=ncomp,
type=dtype.name,
format="appended",
offset=self.offset,
)
self.xml.closeElement()
self.offset += (
nelem * ncomp * dtype.size + 8
) # add 8 to indicate array size
return self
def addData(self, name, data):
"""
Add array description to xml header section.
Parameters
----------
name : str
data array name.
data : array-like
one numpy array or a tuple with 3 numpy arrays.
If a tuple, the individual arrays must represent the components
of a vector field.
All arrays must be one dimensional or three-dimensional.
"""
if isinstance(data, tuple): # vector data
assert len(data) == 3
x = data[0]
self.addHeader(name, x.dtype.name, x.size, 3)
elif isinstance(data, np.ndarray):
if data.ndim == 1 or data.ndim == 3:
self.addHeader(name, data.dtype.name, data.size, 1)
else:
assert False, "Bad array shape: " + str(data.shape)
else:
assert False, "Argument must be a Numpy array"
def appendHeader(self, dtype, nelem, ncomp):
"""
Append size of data block to header.
This function only writes the size of the data block
that will be appended.
The data itself must be written immediately after
calling this function.
Parameters
----------
dtype : str
string with data type representation (same as numpy).
For example, 'float64'.
nelem : int
number of elements.
ncomp : int
number of components, 1 (=scalar) or 3 (=vector)..
"""
self.openAppendedData()
dsize = np_to_vtk[dtype].size
block_size = dsize * ncomp * nelem
writeBlockSize(self.xml.stream, block_size)
# else: # this routine does not exist!
# writeBlockSize64Bit(self.xml.stream, block_size)
def appendData(self, data):
"""
Append data to binary section.
This function writes the header section
and the data to the binary file.
Parameters
----------
data : array-like
one numpy array or a tuple with 3 numpy arrays.
If a tuple, the individual
arrays must represent the components of a vector field.
All arrays must be one dimensional or three-dimensional.
The order of the arrays must coincide with
the numbering scheme of the grid.
Returns
-------
VtkFile
This VtkFile to allow chained calls.
"""
# TODO: Extend this function to accept contiguous C order arrays.
self.openAppendedData()
if isinstance(data, tuple): # 3 numpy arrays
ncomp = len(data)
assert ncomp == 3
dsize = data[0].dtype.itemsize
nelem = data[0].size
block_size = ncomp * nelem * dsize
# if self.largeFile == False:
writeBlockSize(self.xml.stream, block_size)
# else:
# writeBlockSize64Bit(self.xml.stream, block_size)
x, y, z = data[0], data[1], data[2]
writeArraysToFile(self.xml.stream, x, y, z)
elif isinstance(data, np.ndarray) and (
data.ndim == 1 or data.ndim == 3
): # single numpy array
ncomp = 1
dsize = data.dtype.itemsize
nelem = data.size
block_size = ncomp * nelem * dsize
# if self.largeFile == False:
writeBlockSize(self.xml.stream, block_size)
# else:
# writeBlockSize64Bit(self.xml.stream, block_size)
writeArrayToFile(self.xml.stream, data)
else:
assert False
return self
def openAppendedData(self):
"""
Open binary section.
It is not necessary to explicitly call this function
from an external library.
"""
if not self.appendedDataIsOpen:
self.xml.openElement("AppendedData").addAttributes(
encoding="raw"
).addText("_")
self.appendedDataIsOpen = True
def closeAppendedData(self):
"""
Close binary section.
It is not necessary to explicitly call this function
from an external library.
"""
self.xml.closeElement("AppendedData")
def openElement(self, tagName):
"""
Open an element.
Useful to add elements such as: Coordinates, Points, Verts, etc.
"""
self.xml.openElement(tagName)
def closeElement(self, tagName):
"""Close an element."""
self.xml.closeElement(tagName)
def save(self):
"""Close file."""
if self.appendedDataIsOpen:
self.xml.closeElement("AppendedData")
self.xml.closeElement("VTKFile")
self.xml.close()