# Post-processing and visualization (no ParaView)

Stage outputs are Exodus II (`*.e`) + CSV. ParaView is not installed on this box and
chigger drags in MOOSE's whole python layer; `netCDF4` + `matplotlib` + `ffmpeg`
cover everything, and the working script is
`the-compound/reactor/post/stage1_plot.py` (modes `png` and `video`).

## Reading a MOOSE Exodus file with netCDF4

- Nodal fields: `vals_nod_var<i>` indexed `[time_step, num_nodes]`.
- **Elemental fields are written PER BLOCK: `vals_elem_var<i>eb<b>`, not a flat
  `vals_elem_var<i>`.** Concatenate over `num_el_blk` in block order to line up
  with `connect<b>`. (`elem_var_tab` says which var is on which block.)
- Connectivity: `connect<b>` holds 1-based GLOBAL node ids; map through
  `node_num_map` (`local = node_num_map[global-1]`) before indexing `coordx`.
- **`name_*` char arrays are fixed-width and MOOSE leaves the tail
  uninitialised.** `netCDF4.chartostring` raises `UnicodeDecodeError` on the
  garbage; decode with `row.tobytes().split(b"\x00")[0]`.
- Eigen solves write TWO time rows; the converged one is the LAST (`time = 1`).
- k_eff: console prints lambda; the `Eigenvalues` VPP with
  `inverse_eigenvalue = true` writes 1/lambda to `<file_base>_eigen_NNNN.csv`.
  They are reciprocals of each other - do not average them.

## Static figure

`tripcolor`/`tricontourf` on the node cloud with quads split into two triangles
(`q[:, [0,1,2]]`, `q[:, [0,2,3]]`) is mesh-agnostic and exact at nodes. Gotchas:

- `tripcolor(..., facecolors=<float array>)` is interpreted as MAPPABLE DATA
  through the current colormap, not as grey levels - a "grey background" comes
  out dark purple. Use a `plt.Rectangle`/`PolyCollection` with a colour string.
- `edgecolors="face"` on a fine mesh is moire noise; use `edgecolors="none"`.
- Cell-centred fields (MONOMIAL/CONSTANT aux) live at element centroids:
  `tricontourf(xc, yc, values)` lets matplotlib Delaunay the centroids.
- Profiles: on a structured mesh select the exact node row
  (`np.flatnonzero(abs(y - z0) < 1e-9)`), never "the 60 nearest nodes" - that
  mixes rows and jags the curve at material interfaces.

## Flux diagnostics on a closed cavity: advect (T - T_ref), never absolute T

Summing an advective energy flux `rho*u*T` over a CLOSED surface is garbage:
`sum(rho*u_r)` over the surface is zero only to solver tolerance, and that
residual mass flux times `rho*cp*T ~ 4e5 J/m3` injects +-80 W onto a 96 W
signal. Advect the deviation, `rho*u*(T - T_ref)`, and cross-check against the
pure conductive flux at each wall (they must agree to the printed digits) and
across interior face columns (a few % spread is conservation).

## Video

A steady k-eigenvalue solve has NO time axis. An honest "video" is a turntable:
revolve the axisymmetric field (r, z) -> (r cos t, r sin t, z) and orbit the
camera (`ax.view_init(azim=...)`). Say so on the frame; do not dress a still up
as a transient. A real transient video needs the decay-heat stage.

- **A real transient video must resample the time axis.** `IterationAdaptiveDT`
  packs most exodus frames into the first minutes of a days-long march, so
  playing the saved frames in order shows a frozen picture and then a jump.
  Pick frames log-uniformly in time (`np.logspace` over the saved
  `time_whole`, nearest-index), and hold ONE colour scale across every frame or
  the eye cannot read change. A live T(t) strip with a moving marker under the
  field panel makes each frame self-locating.
- Colourbars: size them to the axes AS DRAWN (`fig.canvas.draw()`, then
  `fig.add_axes` at the drawn position) - a plain `fig.colorbar(ax=ax)` overtops
  the title on fixed-aspect panels. And leave enough `wspace` for the colourbar
  PLUS its tick labels before the next panel's y-label starts, or they collide
  in the gutter.
- `imageio.mimwrite(..., fps=24, macro_block_size=1)` encodes mp4 through the
  `imageio-ffmpeg` bundled binary - no system ffmpeg needed to WRITE.
- ~0.8 s/frame for a 38k-point 3D scatter at 990x726; 72 frames < 1 min. Run it
  through `proc("start", ...)` and `proc("wait", pid=...)`, not in-cell.
- **`MPLBACKEND` is exported by the crow kernel** as
  `module://matplotlib_inline.backend_inline`, which matplotlib REJECTS outside
  a notebook (`ValueError: Key backend ... is not a valid value`). Pass
  `env={"MPLBACKEND": "Agg"}` to proc, or `matplotlib.use("Agg")` before pyplot.

## Judging the video: one vision call, not nine

Slice the ENCODED mp4 back into frames and tile them into one contact sheet, so
a single `vision()` call judges the whole animation and the encode at once:

```bash
ffmpeg -y -v error -i stage1_turntable.mp4 \
       -vf "select='not(mod(n,8))',scale=460:-1,tile=3x3" -frames:v 1 contact.png
```

72 frames / every 8th = 9 tiles. Same trick verifies any render: if the sheet
shows the orbit advancing and the colourbar stable, the encode is good.
(`imageio.get_reader(mp4).get_data(i)` + PIL tiling is the no-ffmpeg fallback.)
