Output, plotting and comparison
Markdown: this page · all pages in one file
Docstrings from src/output.jl, src/plotting.jl, src/metrics.jl, src/compare.jl.
Exported
write_vtk
Source: src/output.jl:81
write_vtk(sim, path) -> StringWrite 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
Source: src/output.jl:139
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 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
Source: src/output.jl:204
save_checkpoint(sim, path) -> StringWrite a raw binary checkpoint (grid metadata plus the full conserved state, ghost cells included) that load_checkpoint! 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!
Source: src/output.jl:251
load_checkpoint!(sim, path) -> simRestore a simulation from a checkpoint written by 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
Source: src/plotting.jl:9
coordinates(grid, d) -> VectorCell-centre coordinates of the interior cells along direction d.
available_fields
Source: src/plotting.jl:26
available_fields(sim) -> Tuple{Vararg{Symbol}}The field names 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
Source: src/plotting.jl:67
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 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.
rho, lbl = field(sim, :density)plotstate
Source: src/plotting.jl:178
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. slice overrides the slice index in 3D. Remaining keyword arguments pass through to Plots.
Requires using Plots.
using Plots, Honghu
sim, tmax = Honghu.Problems.kelvin_helmholtz(n = 256)
run!(sim; tmax)
plotstate(sim, var = :density)plotpanels
Source: src/plotting.jl:199
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
Source: src/plotting.jl:210
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.
using Plots, Honghu
sim, tmax = Honghu.Problems.kelvin_helmholtz(n = 256)
animate_run(sim; tmax, var = :density, filename = "kh.gif")plotcompare
Source: src/plotting.jl:230
plotcompare(table_or_path...; metric = nothing, kwargs...)Plot one or more ComparisonTables: 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, so a figure can be redrawn from stored numbers without re-running any simulation:
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:
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 Simulations – 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
Source: src/metrics.jl:10
relative_l1(num, ref) -> RealRelative 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
Source: src/metrics.jl:27
relative_l2(num, ref) -> RealRelative L2 error √(Σ(num - ref)²/Σ ref²). Use when you care about a localised feature that an L1 norm would average away.
default_metrics
Source: src/metrics.jl:41
default_metrics(problem) -> NamedTupleThe metrics a built-in problem scores itself with, as a NamedTuple of callables metric(sim) -> Real evaluated on the finished simulation. compare uses these when you do not pass metrics yourself, so
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
Source: src/compare.jl:15
ComparisonTableThe result of 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 and read it back with read_comparison.
compare
Source: src/compare.jl:234
compare(variants; sizes, metrics, tmax, name, path, outdir, verbose) -> ComparisonTableRun each variant once per size, score every run, and return the results as a 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:
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, 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 storedsizeis read back off the grid that was built.metrics:NamedTupleofmetric(sim) -> Real. Required here; the forms taking aproblemdefault it todefault_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.txtinsideoutdir(default the working directory). Passpath = nothingto 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) and compare(problem, key, values).
Source: src/compare.jl:357
compare(problem, variants; kwargs...) -> ComparisonTableVariants as keywords to a problem: variants is a NamedTuple of keyword NamedTuples, which labels itself, or an iterable of label => kwargs. Each is splatted into problem alongside the resolution.
compare(P.radhydro_shock,
(P1 = (closure = EddingtonClosure(),),
M1 = (closure = LevermoreClosure(),));
sizes = (64, 128, 256))metrics defaults to default_metrics(problem) and the table names itself after the problem. A variant’s value may also be a builder or a prebuilt Simulation, so one call can mix “same problem, different keywords” with “something else entirely”. All other keywords are as for compare.
Source: src/compare.jl:384
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 builders instead.
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
compare(problem, key::Symbol, values; kwargs...) -> ComparisonTableSweep a single keyword: run problem once per entry of values, passing it as key, and label each run with the value.
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.
write_comparison
Source: src/compare.jl:502
write_comparison(table, path) -> pathWrite a ComparisonTable as a tab-separated text table with a # comment header carrying the provenance. Readable by hand, by read_comparison, and by anything that skips comment lines.
read_comparison
Source: src/compare.jl:533
read_comparison(path) -> ComparisonTableRead back a table written by 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
Source: src/compare.jl:574
convergence_rate(table, metric; variant = nothing) -> RealLeast-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
Source: src/output.jl:13
_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
Source: src/output.jl:35
output_fields(sim) -> Vector{Tuple{String,Int,Array}}The named fields written by 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
Source: src/metrics.jl:72
has_default_metrics(problem) -> BoolWhether default_metrics has a method for problem, as opposed to falling through to the error.
line
Source: src/metrics.jl:80
line(sim, name) -> VectorThe named field along the single active direction of a one-dimensional problem, as a plain vector. A convenience for writing metrics.
Base.getindex
Source: src/compare.jl:36
t[name] -> Vector{Float64}The named numeric column of a ComparisonTable.
Source: src/compare.jl:48
t[name, variant] -> Vector{Float64}The named column restricted to one variant and ordered by size, which is the slice most analysis wants:
t[:l1_density, "HLLC"] ./ t[:l1_density, "LLF"] # how much the solver boughtrows
Source: src/compare.jl:66
rows(t) -> Vector{NamedTuple}The table as one NamedTuple per row, variant first. Convenient for filtering and for feeding a plot.
variants
Source: src/compare.jl:77
variants(t) -> Vector{String}The distinct variant labels, in the order they were run.
BOOKKEEPING
Source: src/compare.jl:86
BOOKKEEPINGColumn 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
Source: src/compare.jl:97
metric_columns(t) -> Vector{String}The columns of a ComparisonTable that are scores, i.e. everything not in BOOKKEEPING.
is_error_metric
Source: src/compare.jl:117
is_error_metric(t, metric) -> BoolWhether 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.