Peano
Loading...
Searching...
No Matches
repartition_vtu.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""Repartition a single-piece .vtu into a K-piece .pvtu for low-memory streaming.
3
4The CCZ4 sample snapshots are written as one big `<Piece>`, which VTK's XML
5reader can only load all-at-once. This one-time, offline tool splits such a file
6into K disjoint pieces referenced by a `.pvtu` summary. The apparent-horizon
7finder can then stream that `.pvtu` piece by piece, so its peak memory is bounded
8by one piece rather than the whole grid.
9
10The split itself must load the whole grid once (that is the cost this tool pays
11so the finder never has to). It is deliberately separate from the reader: it runs
12occasionally, has the opposite memory profile, and is unnecessary for genuinely
13multi-piece / domain-decomposed output that Peano already produces.
14
15Usage:
16 python3 repartition_vtu.py input.vtu output.pvtu [-k 8] [--no-compress]
17
18The K piece files are written next to output.pvtu as <output-stem>_<p>.vtu.
19"""
20
21import argparse
22import os
23import sys
24from xml.sax.saxutils import quoteattr
25
26import vtk
27
28# VTK scalar type name -> VTK XML DataArray type name.
29_VTK_TO_XML_TYPE = {
30 "double": "Float64",
31 "float": "Float32",
32 "int": "Int32",
33 "long": "Int64",
34 "long long": "Int64",
35 "idtype": "Int64",
36 "short": "Int16",
37 "unsigned char": "UInt8",
38 "unsigned short": "UInt16",
39 "unsigned int": "UInt32",
40 "unsigned long": "UInt64",
41}
42
43
44def _xml_type(data_array):
45 return _VTK_TO_XML_TYPE.get(data_array.GetDataTypeAsString(), "Float64")
46
47
49 """ComponentName attributes, as VTK's writer emits them, for the named components."""
50 names = ""
51 for component in range(array.GetNumberOfComponents()):
52 name = array.GetComponentName(component)
53 if name:
54 names += f' ComponentName{component}={quoteattr(name)}'
55 return names
56
57
58def _parallel_arrays(field_data, indent=" "):
59 # The parallel reader builds its arrays from these declarations, so the
60 # component names have to be here as well as in the pieces: the finder
61 # selects its fields by them.
62 lines = []
63 for i in range(field_data.GetNumberOfArrays()):
64 array = field_data.GetArray(i)
65 if array is None:
66 continue
67 lines.append(
68 f'{indent}<PDataArray type="{_xml_type(array)}" '
69 f'Name="{array.GetName()}" '
70 f'NumberOfComponents="{array.GetNumberOfComponents()}"'
71 f'{_component_names(array)}/>'
72 )
73 return "\n".join(lines)
74
75
76def _write_summary(pvtu_path, grid, piece_sources):
77 """Write the .pvtu summary that ties the piece files together."""
78 points = grid.GetPoints().GetData()
79 scalars = grid.GetCellData().GetScalars()
80 scalars_attr = f' Scalars="{scalars.GetName()}"' if scalars is not None else ""
81 piece_lines = "\n".join(
82 f' <Piece Source="{source}"/>' for source in piece_sources
83 )
84
85 xml = f"""<?xml version="1.0"?>
86<VTKFile type="PUnstructuredGrid" version="1.0" byte_order="LittleEndian" header_type="UInt64">
87 <PUnstructuredGrid GhostLevel="0">
88 <PPoints>
89 <PDataArray type="{_xml_type(points)}" Name="Points" NumberOfComponents="3"/>
90 </PPoints>
91 <PPointData>
92{_parallel_arrays(grid.GetPointData())}
93 </PPointData>
94 <PCellData{scalars_attr}>
95{_parallel_arrays(grid.GetCellData())}
96 </PCellData>
97{piece_lines}
98 </PUnstructuredGrid>
99</VTKFile>
100"""
101 with open(pvtu_path, "w") as summary:
102 summary.write(xml)
103
104
105def repartition(input_path, output_path, pieces, compress=True):
106 if pieces < 1:
107 raise ValueError("number of pieces must be >= 1")
108
109 reader = vtk.vtkXMLUnstructuredGridReader()
110 reader.SetFileName(input_path)
111 if not reader.CanReadFile(input_path):
112 raise RuntimeError(f"cannot read {input_path}")
113 reader.Update()
114 grid = reader.GetOutput()
115
116 number_of_cells = grid.GetNumberOfCells()
117 if number_of_cells == 0:
118 raise RuntimeError(f"{input_path} has no cells")
119 pieces = min(pieces, number_of_cells)
120
121 output_dir = os.path.dirname(os.path.abspath(output_path))
122 os.makedirs(output_dir, exist_ok=True)
123 stem = os.path.splitext(os.path.basename(output_path))[0]
124
125 sources = []
126 for p in range(pieces):
127 lo = number_of_cells * p // pieces
128 hi = number_of_cells * (p + 1) // pieces
129
130 extract = vtk.vtkExtractCells()
131 extract.SetInputData(grid)
132 extract.AddCellRange(lo, hi - 1) # AddCellRange is inclusive on both ends
133 extract.Update()
134
135 piece = extract.GetOutput()
136 # vtkExtractCells injects bookkeeping arrays that are not in the summary
137 # and that we do not want streamed into GridData; drop them.
138 for name in ("vtkOriginalCellIds",):
139 if piece.GetCellData().HasArray(name):
140 piece.GetCellData().RemoveArray(name)
141 for name in ("vtkOriginalPointIds",):
142 if piece.GetPointData().HasArray(name):
143 piece.GetPointData().RemoveArray(name)
144
145 source = f"{stem}_{p}.vtu"
146 sources.append(source)
147 writer = vtk.vtkXMLUnstructuredGridWriter()
148 writer.SetInputData(piece)
149 writer.SetFileName(os.path.join(output_dir, source))
150 # Inline base64 binary (the source snapshot's format): pure-ASCII XML that
151 # is portable across VTK versions, unlike raw-appended binary.
152 writer.SetDataModeToBinary()
153 if compress:
154 writer.SetCompressorTypeToZLib()
155 else:
156 writer.SetCompressorTypeToNone()
157 writer.Write()
158 print(f"piece {p}: cells [{lo}, {hi}) -> {source}", flush=True)
159
160 _write_summary(output_path, grid, sources)
161 print(f"wrote {output_path} with {pieces} pieces ({number_of_cells} cells total)")
162
163
164def main(argv=None):
165 parser = argparse.ArgumentParser(description=__doc__,
166 formatter_class=argparse.RawDescriptionHelpFormatter)
167 parser.add_argument("input", help="single-piece .vtu snapshot")
168 parser.add_argument("output", help="output .pvtu summary path")
169 parser.add_argument("-k", "--pieces", type=int, default=8,
170 help="number of pieces to split into (default: 8)")
171 parser.add_argument("--no-compress", action="store_true",
172 help="write uncompressed piece files")
173 args = parser.parse_args(argv)
174
175 repartition(args.input, args.output, args.pieces, compress=not args.no_compress)
176 return 0
177
178
179if __name__ == "__main__":
180 sys.exit(main())
repartition(input_path, output_path, pieces, compress=True)
_parallel_arrays(field_data, indent=" ")
_component_names(array)
ComponentName attributes, as VTK's writer emits them, for the named components.
_xml_type(data_array)
_write_summary(pvtu_path, grid, piece_sources)
Write the .pvtu summary that ties the piece files together.