---
title: "Output, plotting and comparison"
---

Docstrings from `src/output.jl`, `src/plotting.jl`, `src/metrics.jl`, `src/compare.jl`.

## Exported

### `write_vtk` {#write_vtk}

Source: [`src/output.jl:81`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/output.jl#L81)

```julia
write_vtk(sim, path) -> String
```

Write the interior state as a VTK image-data file (cell data). `path` may be
given with or without the `.vti` extension; the file name actually written is
returned.

A numbered series such as `data_00000.vti`, `data_00001.vti`, ... is recognised
by ParaView as a time series.

### `write_line` {#write_line}

Source: [`src/output.jl:139`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/output.jl#L139)

```julia
write_line(sim, path; dir = 1, at = nothing)
```

Write a one-dimensional cut through the domain as a whitespace-separated text
table with a header line: coordinate, then every field of
[`output_fields`](#output_fields) component by component.

`dir` selects the axis of the cut and `at` the transverse cell indices (a
2-tuple of interior indices, default the middle of the domain). Intended for
quick plotting of shock tubes and Marshak waves.

### `save_checkpoint` {#save_checkpoint}

Source: [`src/output.jl:204`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/output.jl#L204)

```julia
save_checkpoint(sim, path) -> String
```

Write a raw binary checkpoint (grid metadata plus the full conserved state,
ghost cells included) that [`load_checkpoint!`](#load_checkpoint-bang) can restore. With MHD
the state is the cell-centred `U` and the face-centred field `sim.B`, ghost
faces included. The file extension `.honghu` is added unless the path already
ends in `.honghu`, or in `.h3d`, the extension from the package's old name: a
script that saves to and loads from a fixed `.h3d` path keeps working. The file
is written in the current format either way, format 3:

| bytes | content |
|:---|:---|
| 8 | the magic `HONGHU ` |
| 8 | `sizeof(T)`, the precision |
| 24, 24 | the interior cell counts and the ghost widths, three `Int64` each |
| 24 | `t`, `dt` (`Float64`) and `step` (`Int64`) |
| 8, 16, 8 | flags and counts (`Int64`): radiation, the rows of `U` and `R`, MHD |
| ... | `U`, then `R` with radiation, then `B[1]`, `B[2]`, `B[3]` with MHD, each in native byte order |

### `load_checkpoint!` {#load_checkpoint-bang}

Source: [`src/output.jl:251`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/output.jl#L251)

```julia
load_checkpoint!(sim, path) -> sim
```

Restore a simulation from a checkpoint written by [`save_checkpoint`](#save_checkpoint).
The grid, floating-point precision, presence of radiation and of a magnetic
field, and the number of gas and radiation variables (hence of mass scalars) must
match those of `sim`, or it throws before touching `sim.t`, `sim.dt`, `sim.step`
or the state. A checkpoint of format 2 holds no magnetic field, so it loads only
into a simulation without MHD; one of format 1 and a `.h3d` checkpoint, written
when the package was called Hydro3D, carry no variable counts either, so they
load only into a simulation without MHD and with `nscalars == 0`.

### `coordinates` {#coordinates}

Source: [`src/plotting.jl:9`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/plotting.jl#L9)

```julia
coordinates(grid, d) -> Vector
```

Cell-centre coordinates of the interior cells along direction `d`.

### `available_fields` {#available_fields}

Source: [`src/plotting.jl:26`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/plotting.jl#L26)

```julia
available_fields(sim) -> Tuple{Vararg{Symbol}}
```

The field names [`field`](#field) accepts for this simulation. Radiation fields
are only present when the radiation module is enabled.

A multigroup run also lists `:Erad_1`, `:Fx_1`, ... one set per group. A grey
run does not: with one group those names are accepted but they name the same
array as `:Erad`, `:Fx`, ..., and advertising both would suggest a distinction
that is not there.

A run with mass scalars also lists `:X_1`, ..., `:X_ns`, the mass fraction of
each scalar, and a run with MHD lists `:bx`, `:by`, `:bz`, the cell-centred field
(the average of each cell's two faces), and `:magnetic_pressure`, `|b|^2 / 2`.

### `field` {#field}

Source: [`src/plotting.jl:67`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/plotting.jl#L67)

```julia
field(sim, name) -> (data, label)
```

Extract one named field over the interior as a fresh `(nx, ny, nz)` array,
together with a label suitable for an axis or colour bar.

See [`available_fields`](#available_fields) for the accepted names. `:Erad`, `:Fx`, `:Fy`,
`:Fz` and `:reduced_flux` are summed over the frequency groups, so they mean the
same thing in a grey run and a multigroup one; a trailing group number picks one
group out, as in `field(sim, :Erad_2)`. `:X_s` is the mass fraction
`rho X_s / rho` of mass scalar `s`, not the conserved density.

```julia
rho, lbl = field(sim, :density)
```

### `plotstate` {#plotstate}

Source: [`src/plotting.jl:178`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/plotting.jl#L178)

```julia
plotstate(sim; var = :density, slice = nothing, kwargs...)
```

Plot one field of the simulation, choosing the representation from the
dimensionality: a line plot in 1D, a heat map in 2D, and a heat map of the
mid-plane slice in 3D.

`var` is any name from [`available_fields`](#available_fields). `slice` overrides the slice
index in 3D. Remaining keyword arguments pass through to Plots.

**Requires `using Plots`.**

```julia
using Plots, Honghu
sim, tmax = Honghu.Problems.kelvin_helmholtz(n = 256)
run!(sim; tmax)
plotstate(sim, var = :density)
```

### `plotpanels` {#plotpanels}

Source: [`src/plotting.jl:199`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/plotting.jl#L199)

```julia
plotpanels(sim; vars = nothing, kwargs...)
```

A multi-panel overview of the state: density, velocity, pressure and gas
temperature, plus radiation energy and temperature when radiation is enabled.
Pass `vars` to choose the panels yourself.

**Requires `using Plots`.**

### `animate_run` {#animate_run}

Source: [`src/plotting.jl:210`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/plotting.jl#L210)

```julia
animate_run(sim; tmax, nframes = 100, var = :density, fps = 20,
            filename = "honghu.gif", kwargs...)
```

Integrate `sim` to `tmax` while capturing `nframes` evenly spaced frames of
`var`, and write an animated GIF. Returns the file name.

Named `animate_run` rather than `animate` so that it does not collide with
`Plots.animate` when both packages are in scope.

**Requires `using Plots`.**

```julia
using Plots, Honghu
sim, tmax = Honghu.Problems.kelvin_helmholtz(n = 256)
animate_run(sim; tmax, var = :density, filename = "kh.gif")
```

### `plotcompare` {#plotcompare}

Source: [`src/plotting.jl:230`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/plotting.jl#L230)

```julia
plotcompare(table_or_path...; metric = nothing, kwargs...)
```

Plot one or more [`ComparisonTable`](#ComparisonTable)s: each metric against resolution, one
line per variant, on log-log axes with the measured convergence rate in the
legend.

Accepts tables or the paths to tables written by [`compare`](#compare), so a figure
can be redrawn from stored numbers without re-running any simulation:

```julia
using Plots, Honghu
plotcompare("radhydro_shock_compare.txt")
```

Give it several tables to put the same schemes on different problems side by
side, each panel labelled with its problem. That comparison is the point --
one problem gives a ranking, two tell you whether the ranking means anything:

```julia
plotcompare("sod_shock_tube_riemann_compare.txt",
            "smooth_advection_riemann_compare.txt")
```

Pass `metric` to draw one panel per table instead of all of them.

A table with only one resolution -- one built by comparing prebuilt
[`Simulation`](simulation.md#Simulation)s -- is drawn as a bar chart instead. There is no trend to
put on a log-log axis, and an axis that implies one would be a claim the run
never measured.

**Requires `using Plots`.**

### `relative_l1` {#relative_l1}

Source: [`src/metrics.jl:10`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/metrics.jl#L10)

```julia
relative_l1(num, ref) -> Real
```

Relative `L1` error `Σ|num - ref| / Σ|ref|` between a numerical result and a
reference of the same length.

This is the norm Quokka reports for its radiation tests, so a number produced
here is directly comparable with one produced there.

### `relative_l2` {#relative_l2}

Source: [`src/metrics.jl:27`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/metrics.jl#L27)

```julia
relative_l2(num, ref) -> Real
```

Relative `L2` error `√(Σ(num - ref)²/Σ ref²)`. Use when you care about a
localised feature that an `L1` norm would average away.

### `default_metrics` {#default_metrics}

Source: [`src/metrics.jl:41`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/metrics.jl#L41)

```julia
default_metrics(problem) -> NamedTuple
```

The metrics a built-in problem scores itself with, as a `NamedTuple` of
callables `metric(sim) -> Real` evaluated on the finished simulation.
[`compare`](#compare) uses these when you do not pass `metrics` yourself, so

```julia
compare(Honghu.Problems.radhydro_shock, variants; nx = (64, 128, 256))
```

needs no configuration at all.

Defined for the problems that have a reference solution to be scored against.
Problems without one (Kelvin-Helmholtz, the Marshak wave) have no default, and
`compare` then requires explicit `metrics`.

Adding a problem with an exact solution? Give it a method here, in one line, and
the test suite, the verification figures and the comparison harness all pick up
the same definition of "the error".

### `ComparisonTable` {#ComparisonTable}

Source: [`src/compare.jl:15`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L15)

```julia
ComparisonTable
```

The result of [`compare`](#compare): one row per (variant, resolution), a string
`variant` column and a numeric matrix.

Index it like a table -- `t[:l1_Trad]` gives a column, `t.variant` the labels --
or write it with [`write_comparison`](#write_comparison) and read it back with
[`read_comparison`](#read_comparison).

### `compare` {#compare}

Source: [`src/compare.jl:234`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L234)

```julia
compare(variants; sizes, metrics, tmax, name, path, outdir, verbose) -> ComparisonTable
```

Run each variant once per size, score every run, and return the results as a
[`ComparisonTable`](#ComparisonTable) which is also written to disk.

`variants` is a vector of `label => builder`, where a **builder** is a function
of resolution returning `(sim, tmax)` -- the contract the problem factories
already satisfy:

```julia
compare(["HLLC" => nx -> P.sod_shock_tube(; nx, riemann = HLLC()),
         "warm" => nx -> my_own_setup(nx)];
        sizes = (64, 128, 256), metrics = default_metrics(P.sod_shock_tube))
```

Because the builder is arbitrary code, a variant may differ in anything at all
-- a different initial condition, a different geometry, a global flag -- not
only in keywords the harness knows how to pass. A builder may also be a
prebuilt [`Simulation`](simulation.md#Simulation), which fixes its own resolution and so needs an
explicit `tmax`.

  - `sizes`   : resolutions to sweep, default `(64, 128)`; each is handed to the
    builder. The stored `size` is read back off the grid that was built.
  - `metrics` : `NamedTuple` of `metric(sim) -> Real`. Required here; the forms
    taking a `problem` default it to [`default_metrics`](#default_metrics)`(problem)`.
  - `tmax`    : override the builder's suggested stopping time.
  - `name`    : what the table calls itself, and the stem of the default file.
  - `path`    : where to write the table; defaults to `<name>_compare.txt`
    inside `outdir` (default the working directory). Pass `path = nothing` to
    skip writing.

Every run also records `cells`, `steps`, `wall_s`, `floors` and the Newton
statistics, so a variant that is more accurate *because* it took ten times as
long, or that only converged with help from the positivity floors, is visible
rather than flattering.

Then `plotcompare(t)` (with Plots loaded), or `plotcompare("..._compare.txt")`
in a later session, redraws it without re-running anything.

See also the two sugars: [`compare(problem, variants)`](#compare) and
[`compare(problem, key, values)`](#compare).

Source: [`src/compare.jl:357`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L357)

```julia
compare(problem, variants; kwargs...) -> ComparisonTable
```

Variants as keywords to a problem: `variants` is a `NamedTuple` of keyword
`NamedTuple`s, which labels itself, or an iterable of `label => kwargs`. Each is
splatted into `problem` alongside the resolution.

```julia
compare(P.radhydro_shock,
        (P1 = (closure = EddingtonClosure(),),
         M1 = (closure = LevermoreClosure(),));
        sizes = (64, 128, 256))
```

`metrics` defaults to [`default_metrics`](#default_metrics)`(problem)` and the table names
itself after the problem. A variant's value may also be a builder or a prebuilt
[`Simulation`](simulation.md#Simulation), so one call can mix "same problem, different keywords"
with "something else entirely". All other keywords are as for [`compare`](#compare).

Source: [`src/compare.jl:384`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L384)

```julia
compare(sims::Simulation...; tmax, metrics, kwargs...) -> ComparisonTable
compare((label => sim)...; tmax, metrics, kwargs...)
```

Compare simulations you have already built, however they differ. There is no
resolution sweep -- every configuration field of `Simulation` is `const`, so an
instance pins its own grid -- which means no convergence rate. For that, give
[`compare`](#compare) builders instead.

```julia
a, _ = P.sod_shock_tube(nx = 256, riemann = HLLC())
b, _ = P.sod_shock_tube(nx = 256, riemann = LLF())
compare("HLLC" => a, "LLF" => b; tmax = 0.2,
        metrics = default_metrics(P.sod_shock_tube))
```

`tmax` is required, because a simulation carries no suggested stopping time.
Unlabelled simulations are called `sim1`, `sim2`, ...; the harness will not
guess a name by inspecting what differs between them. The simulations are run
in place, so they are left finished and ready to plot.

Source: [`src/compare.jl:415`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L415)

```julia
compare(problem, key::Symbol, values; kwargs...) -> ComparisonTable
```

Sweep a single keyword: run `problem` once per entry of `values`, passing it as
`key`, and label each run with the value.

```julia
compare(P.sod_shock_tube, :riemann, (HLLC(), LLF()); sizes = (64, 128, 256))
```

This is the common case -- one knob, several settings -- and it writes the
scheme's name once instead of three times. `HLLC()` labels its rows `HLLC`;
numbers label themselves. Use the general form when a variant needs more than
one keyword, or when you want the labels to say something else.

The default table is `<problem>_<key>_compare.txt`, so sweeping two different
knobs on the same problem gives two files. All other keywords are as for
[`compare`](#compare).

### `write_comparison` {#write_comparison}

Source: [`src/compare.jl:502`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L502)

```julia
write_comparison(table, path) -> path
```

Write a [`ComparisonTable`](#ComparisonTable) as a tab-separated text table with a `#`
comment header carrying the provenance. Readable by hand, by
[`read_comparison`](#read_comparison), and by anything that skips comment lines.

### `read_comparison` {#read_comparison}

Source: [`src/compare.jl:533`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L533)

```julia
read_comparison(path) -> ComparisonTable
```

Read back a table written by [`write_comparison`](#write_comparison). Needs nothing beyond
the package, so a stored comparison can be re-plotted or re-analysed in a
session that never loads a solver.

### `convergence_rate` {#convergence_rate}

Source: [`src/compare.jl:574`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L574)

```julia
convergence_rate(table, metric; variant = nothing) -> Real
```

Least-squares slope of `log(metric)` against `log(size)` for one variant,
negated, so that a second-order scheme returns about `2`.

With one variant in the table `variant` may be omitted.

## Internals

### `_rad_group_sum` {#_rad_group_sum}

Source: [`src/output.jl:13`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/output.jl#L13)

```julia
_rad_group_sum(sim, comps) -> Array{T,4}
```

Sum of the radiation components `comps` -- given as their offsets *within* a
group, so `IERAD:IERAD` or `IFRX:IFRZ` -- over every frequency group, on the
interior, with the component axis kept.

The unsuffixed radiation outputs are group sums so that a grey file and a
multigroup file of the same problem carry the same quantity. With one group the
sum is the group, and the array is the plain slice it always was.

### `output_fields` {#output_fields}

Source: [`src/output.jl:35`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/output.jl#L35)

```julia
output_fields(sim) -> Vector{Tuple{String,Int,Array}}
```

The named fields written by [`write_vtk`](#write_vtk): `(name, ncomponents, data)`
where `data` is laid out with the component index first and then `x, y, z`.

A run with mass scalars adds `mass_fraction_1`, ... after `gas_temperature`: the
mass fraction `X_s`, not the conserved density `rho X_s`. A run with MHD adds
`magnetic_field`, the cell-centred field, after them.

`radiation_energy` and `radiation_flux` are summed over the frequency groups.
A multigroup run adds `radiation_energy_1`, `radiation_flux_1`, ... per group
after them; a grey run does not, since those would be exact duplicates of the
totals, and a grey file is byte for byte what it has always been.

### `has_default_metrics` {#has_default_metrics}

Source: [`src/metrics.jl:72`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/metrics.jl#L72)

```julia
has_default_metrics(problem) -> Bool
```

Whether [`default_metrics`](#default_metrics) has a method for `problem`, as opposed to
falling through to the error.

### `line` {#line}

Source: [`src/metrics.jl:80`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/metrics.jl#L80)

```julia
line(sim, name) -> Vector
```

The named field along the single active direction of a one-dimensional problem,
as a plain vector. A convenience for writing metrics.

### `Base.getindex` {#Base-getindex}

Source: [`src/compare.jl:36`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L36)

```julia
t[name] -> Vector{Float64}
```

The named numeric column of a [`ComparisonTable`](#ComparisonTable).

Source: [`src/compare.jl:48`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L48)

```julia
t[name, variant] -> Vector{Float64}
```

The named column restricted to one variant and ordered by size, which is the
slice most analysis wants:

```julia
t[:l1_density, "HLLC"] ./ t[:l1_density, "LLF"]   # how much the solver bought
```

### `rows` {#rows}

Source: [`src/compare.jl:66`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L66)

```julia
rows(t) -> Vector{NamedTuple}
```

The table as one `NamedTuple` per row, `variant` first. Convenient for filtering
and for feeding a plot.

### `variants` {#variants}

Source: [`src/compare.jl:77`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L77)

```julia
variants(t) -> Vector{String}
```

The distinct variant labels, in the order they were run.

### `BOOKKEEPING` {#BOOKKEEPING}

Source: [`src/compare.jl:86`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L86)

```julia
BOOKKEEPING
```

Column names that record how a run went rather than how good it was. They are
worth storing beside the metrics -- a variant that wins only because it took ten
times as long should be visible -- but they are not scores, so they get no
convergence rate and no panel on a plot.

### `metric_columns` {#metric_columns}

Source: [`src/compare.jl:97`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L97)

```julia
metric_columns(t) -> Vector{String}
```

The columns of a [`ComparisonTable`](#ComparisonTable) that are scores, i.e. everything not
in [`BOOKKEEPING`](#BOOKKEEPING).

### `is_error_metric` {#is_error_metric}

Source: [`src/compare.jl:117`](https://github.com/chongchonghe/Honghu.jl/blob/e6bd095ecb38a1e27e4481cb8bbbcb062ea0ae9a/src/compare.jl#L117)

```julia
is_error_metric(t, metric) -> Bool
```

Whether `metric` behaves like an error: positive everywhere, and falling under
refinement for at least one variant.

Not every metric is one. `radhydro_shock`'s `spike` converges *to* 4.26 rather
than to zero, so a log-log slope through it is a number with no meaning and a
log axis is the wrong axis. Printing a table and plotting one both ask this,
rather than each deciding for itself.

