5@file check_statistics_nodal_consistency.py
6@brief Cross-check derived statistics VTK output against the convergence-history CSV.
8The two are produced by paths that share no code: the CSV mean comes from
9`PicurvWindowSpatialMean`, which reduces the cell-centred accumulators over the
10resolved spatial target, while the VTK field comes from `ComputeNodalAverage`
11interpolating the derived staging buffer onto grid nodes. Agreement between them
12is therefore a real check rather than a restatement.
14It catches the specific failure this check was written for: an interior-only
15producer leaving structural zeros on the layout boundary, which halves every
16boundary node and biases a whole-domain mean without any other symptom.
19check_statistics_nodal_consistency.py RUN_DIR WINDOW_NAME
24USAGE =
"usage: check_statistics_nodal_consistency.py RUN_DIR WINDOW_NAME"
34 @brief Resolve the one per-recipe subdirectory beneath a canonical output home.
35 @param[in] run_dir Run directory being inspected.
36 @param[in] canonical_relative Run-relative canonical home, such as output/visualization.
37 @return Absolute path to the single recipe subdirectory.
38 @throws ValueError when the home is absent or holds anything but one recipe.
40 root = os.path.join(run_dir, canonical_relative)
41 if not os.path.isdir(root):
42 raise ValueError(f
"{canonical_relative} does not exist under {run_dir}.")
43 entries = sorted(name
for name
in os.listdir(root)
44 if os.path.isdir(os.path.join(root, name)))
47 f
"expected exactly one recipe directory under {root}, found {entries}."
49 return os.path.join(root, entries[0])
54 @brief Import NumPy, which this checker needs to read the binary VTK payload.
55 @return Imported NumPy module.
63 @brief Read appended raw Float64 point arrays from a PICurv `.vts`.
64 @param[in] path VTK structured-grid file path.
65 @return Tuple of the node extent per direction and a name-to-array mapping.
68 raw = open(path,
"rb").read()
69 head = raw[:8192].decode(
"utf-8",
"replace")
70 extent = re.search(
r'WholeExtent="0 (\d+) 0 (\d+) 0 (\d+)"', head)
72 raise ValueError(f
"{path}: no WholeExtent in header.")
73 nodes = tuple(int(extent.group(i)) + 1
for i
in (1, 2, 3))
74 marker = raw.find(b
"<AppendedData")
76 raise ValueError(f
"{path}: no appended data section.")
77 start = raw.find(b
"_", marker) + 1
79 for match
in re.finditer(
80 r'Name="([^"]+)" NumberOfComponents="(\d+)" format="appended" offset="(\d+)"', head
82 name, ncomp, offset = match.group(1), int(match.group(2)), int(match.group(3))
84 nbytes = int(numpy.frombuffer(raw, dtype=
"<u4", count=1, offset=base)[0])
85 values = numpy.frombuffer(raw, dtype=
"<f8", count=nbytes // 8, offset=base + 4)
86 arrays[name] = values.reshape(-1, ncomp)
if ncomp > 1
else values
92 @brief Read the periodicity the solver recorded in any committed checkpoint.
93 @param[in] run_dir Run directory to search.
94 @return Tuple of three booleans for i, j, k, or None when no checkpoint is present.
96 for root, _dirs, files
in os.walk(os.path.join(run_dir,
"output")):
97 if "checkpoint.meta" not in files:
99 with open(os.path.join(root,
"checkpoint.meta"),
"r", encoding=
"utf-8")
as stream:
101 if line.startswith(
"-checkpoint_periodic "):
102 flags = line.split(
None, 1)[1].strip().split(
",")
103 return tuple(token.strip() ==
"1" for token
in flags)
109 @brief Locate the highest-step derived statistics file for one window.
110 @param[in] viz_dir Directory holding the post-processing output.
111 @param[in] window Window name.
112 @return Path to the selected file.
114 pattern = re.compile(rf
"_statistics_{re.escape(window)}_(\d+)\.vts$")
115 best, best_step =
None, -1
116 for name
in sorted(os.listdir(viz_dir)):
117 match = pattern.search(name)
118 if match
and int(match.group(1)) > best_step:
119 best, best_step = os.path.join(viz_dir, name), int(match.group(1))
121 raise ValueError(f
"no derived statistics VTK output for window '{window}' in {viz_dir}.")
127 @brief Verify every derived array wraps across each periodic layout boundary.
129 @details Independent of whether the flow is turbulent, so a steady case still guards
130 the layout boundary. An interior-only producer leaves the two boundary
131 planes holding different partial averages, which this detects directly.
133 @param[in] arrays Name-to-array mapping from `read_vts_point_arrays()`.
134 @param[in] nodes Node extent per direction, in i, j, k order.
135 @param[in] periodic Per-direction periodicity in i, j, k order.
136 @return Zero when every array wraps, or one on the first disagreement.
140 for name, values
in sorted(arrays.items()):
141 if name ==
"Position":
143 ncomp = values.shape[1]
if values.ndim > 1
else 1
144 field = values.reshape(nodes[2], nodes[1], nodes[0], ncomp)
146 for flag, axis, label
in zip(periodic, (2, 1, 0), (
"i",
"j",
"k")):
149 low = numpy.take(field, 0, axis=axis)
150 high = numpy.take(field, field.shape[axis] - 1, axis=axis)
151 if not numpy.allclose(low, high):
152 print(f
"[FAIL] '{name}': the two layout boundary planes in the periodic "
153 f
"{label} direction differ, so the wrap was not applied. See "
154 f
"SynchronizePeriodicCellFields().", file=sys.stderr)
157 print(f
"[INFO] periodic layout boundary wraps verified on {checked} array/direction pair(s).")
163 @brief Run the consistency check.
164 @param[in] argv Optional argument override for tests.
165 @return Process exit code.
168 args =
list(sys.argv[1:]
if argv
is None else argv)
170 print(USAGE, file=sys.stderr)
172 run_dir, window = args
176 viz_dir =
sole_recipe_dir(run_dir, os.path.join(
"output",
"visualization"))
177 stats_dir =
sole_recipe_dir(run_dir, os.path.join(
"output",
"analysis",
"statistics"))
184 if periodic
and any(periodic):
188 tke_name = next((n
for n
in arrays
if n.endswith(
"_tke")),
None)
190 print(f
"[SKIP] {os.path.basename(vts_path)} carries no turbulent kinetic energy field.")
192 field = arrays[tke_name].reshape(nodes[2], nodes[1], nodes[0])
195 (os.path.join(stats_dir, n)
for n
in sorted(os.listdir(stats_dir))
196 if n.endswith(f
"_statistics_{window}.csv")),
None
199 raise ValueError(f
"no convergence-history CSV for window '{window}' in {stats_dir}.")
200 rows =
list(csv.DictReader(open(csv_path,
"r", encoding=
"utf-8")))
201 if not rows
or "mean_tke" not in rows[0]:
202 print(f
"[SKIP] {os.path.basename(csv_path)} records no mean_tke column.")
204 reference = float(rows[-1][
"mean_tke"])
206 print(f
"[SKIP] window '{window}' has no accumulated energy to compare.")
211 interior = field[1:-1, 1:-1, 1:-1].mean()
212 deviation = abs(interior / reference - 1.0)
214 print(f
"[INFO] {window}: nodal interior mean {interior:.6e} vs CSV mean_tke "
215 f
"{reference:.6e} ({100*deviation:+.2f}%)")
216 if deviation > tolerance:
218 f
"[FAIL] derived statistics VTK and convergence CSV disagree by "
219 f
"{100*deviation:.2f}%, above the {100*tolerance:.0f}% interpolation "
220 f
"allowance. A layout boundary left unwritten by an interior-only "
221 f
"producer is the usual cause; see SynchronizePeriodicCellFields().",
226 if periodic
and all(periodic):
232 whole_deviation = abs(whole / reference - 1.0)
233 print(f
"[INFO] {window}: whole-domain nodal mean {whole:.6e} "
234 f
"({100*whole_deviation:+.2f}%)")
235 if whole_deviation > tolerance:
237 f
"[FAIL] every boundary node is defined on a fully periodic layout, "
238 f
"but the whole-domain nodal mean is off by {100*whole_deviation:.2f}%. "
239 f
"The layout boundary was left unwritten; see SynchronizePeriodicCellFields().",
244 print(
"[PASS] derived statistics VTK is consistent with the convergence CSV.")
246 except Exception
as exc:
247 print(f
"[ERROR] statistics nodal consistency check failed: {exc}", file=sys.stderr)
251if __name__ ==
"__main__":
check_periodic_wrap(arrays, nodes, periodic)
Verify every derived array wraps across each periodic layout boundary.
read_vts_point_arrays(path)
Read appended raw Float64 point arrays from a PICurv .vts.
require_numpy()
Import NumPy, which this checker needs to read the binary VTK payload.
main(argv=None)
Run the consistency check.
newest_window_vts(viz_dir, window)
Locate the highest-step derived statistics file for one window.
str sole_recipe_dir(str run_dir, str canonical_relative)
Resolve the one per-recipe subdirectory beneath a canonical output home.
read_checkpoint_periodicity(run_dir)
Read the periodicity the solver recorded in any committed checkpoint.
Head of a generic C-style linked list.