Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/python-analysis.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ The `amrexplorer` Python package reads AMReX plotfiles through the same
Qt-free C++ readers the viewer uses, and gives scripts exact, native-unit
access to them: every leaf cell exactly once, in chunks a script can reduce
serially or in parallel, and per-block statistics.
`tools/analysis_validation/run_comparisons.sh` compares it with yt and
Kangaroo.

Values are always the plotfile's own numbers. Nothing reads a unit system or
converts anything: a script that wants solar masses divides by the gram value
Expand Down
135 changes: 135 additions & 0 deletions tools/analysis_validation/compare_with_yt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Compare amrexplorer leaf-cell values and phase totals with yt on a real
plotfile, using the same selection (cell centers in a box) and the same
arithmetic.

Validates: raw source values and analysis totals. yt's region selects cells by
center and excludes covered coarse cells, like plan_leaf_chunks; the two cell
sets are matched by (level, cell center) and their native values compared
exactly. yt converts nothing for an AMReX plotfile whose length unit is the
default (1 cm), so its "code" values are the plotfile's numbers.

python compare_with_yt.py PLOTFILE --half-width 1e17
"""

import argparse
import json
import sys
import time

import numpy as np

import amrexplorer

PHASES = [0.0, 100.0, 8.0e3, 2.0e4, 5.0e5, np.inf]


def amrexplorer_cells(path, fields, lower, upper):
start = time.perf_counter()
columns = {name: [] for name in fields}
level, x, y, z, volume = [], [], [], [], []
with amrexplorer.open_plotfile(path) as ds:
plan = ds.plan_leaf_chunks(fields, region=(lower, upper),
dtype=np.float64)
for chunk in (ds.read_leaf_chunk(item) for item in plan):
for name in fields:
columns[name].append(chunk[name])
level.append(np.full(chunk.size, chunk.level))
x.append(chunk.x)
y.append(chunk.y)
z.append(chunk.z)
volume.append(chunk.cell_volume)
result = {name: np.concatenate(v) for name, v in columns.items()}
result.update(level=np.concatenate(level), x=np.concatenate(x),
y=np.concatenate(y), z=np.concatenate(z),
volume=np.concatenate(volume))
return result, time.perf_counter() - start


def yt_cells(path, fields, lower, upper):
import yt

yt.set_log_level(40)
start = time.perf_counter()
ds = yt.load(path)
region = ds.box(lower, upper)
result = {name: region["boxlib", name].d.astype(np.float64)
for name in fields}
result["level"] = region["index", "grid_level"].d.astype(np.int64)
for axis in "xyz":
result[axis] = region["index", axis].d
result["volume"] = region["index", "cell_volume"].d
return result, time.perf_counter() - start


def phase_masses(cells, density, temperature):
mass = cells[density] * cells["volume"]
out = []
for lo, hi in zip(PHASES[:-1], PHASES[1:]):
selected = (cells[temperature] >= lo) & (cells[temperature] < hi)
out.append(float(np.sum(mass[selected])))
return out


def canonical(cells):
order = np.lexsort((cells["z"], cells["y"], cells["x"], cells["level"]))
return {key: value[order] for key, value in cells.items()}


def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("plotfile")
parser.add_argument("--half-width", type=float, required=True,
help="half width of a box about the origin, native units")
parser.add_argument("--density-field", default="gasDensity")
parser.add_argument("--temperature-field", default="temperature")
parser.add_argument("--output", help="write the comparison as JSON")
args = parser.parse_args()

fields = [args.density_field, args.temperature_field]
lower = [-args.half_width] * 3
upper = [args.half_width] * 3
ours, our_time = amrexplorer_cells(args.plotfile, fields, lower, upper)
theirs, yt_time = yt_cells(args.plotfile, fields, lower, upper)

report = {
"plotfile": args.plotfile,
"region": [lower, upper],
"amrexplorer_cells": int(ours["level"].size),
"yt_cells": int(theirs["level"].size),
"amrexplorer_seconds": our_time,
"yt_seconds": yt_time,
"cells_per_level_amrexplorer": np.bincount(ours["level"]).tolist(),
"cells_per_level_yt": np.bincount(theirs["level"]).tolist(),
}
same_cells = report["amrexplorer_cells"] == report["yt_cells"]
if same_cells:
a, b = canonical(ours), canonical(theirs)
report["levels_match"] = bool(np.array_equal(a["level"], b["level"]))
report["max_center_difference"] = float(max(
np.max(np.abs(a[axis] - b[axis])) for axis in "xyz"))
report["volume_max_rel_difference"] = float(
np.max(np.abs(a["volume"] - b["volume"]) / b["volume"]))
for name in fields:
report[f"{name}_values_identical"] = bool(
np.array_equal(a[name], b[name]))
report[f"{name}_max_rel_difference"] = float(np.max(
np.abs(a[name] - b[name]) / np.maximum(np.abs(b[name]), 1e-300)))
ours_phases = phase_masses(ours, *fields)
yt_phases = phase_masses(theirs, *fields)
report["phase_mass_amrexplorer"] = ours_phases
report["phase_mass_yt"] = yt_phases
report["phase_mass_rel_difference"] = [
abs(a - b) / max(abs(b), 1e-300) for a, b in zip(ours_phases, yt_phases)]
report["total_volume_amrexplorer"] = float(ours["volume"].sum())
report["total_volume_yt"] = float(theirs["volume"].sum())
text = json.dumps(report, indent=2)
print(text)
if args.output:
with open(args.output, "w") as out:
out.write(text + "\n")
return 0 if same_cells else 1


if __name__ == "__main__":
sys.exit(main())
51 changes: 51 additions & 0 deletions tools/analysis_validation/make_amr_fixture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Write a synthetic 3-D plotfile for comparing ports with Kangaroo and yt:
two levels of gas density and temperature over several grids, the fine grids
straddling coarse grid boundaries."""

import argparse
import os
import sys

import numpy as np

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..",
"tests", "python"))
from plotfile_writer import Level, write_plotfile # noqa: E402

KPC = 3.0856775814913673e21
HALF_WIDTH = 8 * KPC


def density(level, i, j, k):
dx = 2 * HALF_WIDTH / (16 * 2**level)
x, y, z = (-HALF_WIDTH + (n + 0.5) * dx for n in (i, j, k))
return 1e-24 * np.exp(-np.hypot(x, y) / (3 * KPC) - np.abs(z) / KPC) * (
1 + 0.2 * np.cos(i - j + 2 * k))


def temperature(level, i, j, k):
dx = 2 * HALF_WIDTH / (16 * 2**level)
x, y, z = (-HALF_WIDTH + (n + 0.5) * dx for n in (i, j, k))
return 10 ** (1.5 + 6 * (np.abs(z) / HALF_WIDTH) + 0.5 * np.sin(x / KPC + y / KPC))


def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("output")
args = parser.parse_args()
boxes = [((0, 0, 0), (7, 7, 15)), ((8, 0, 0), (15, 15, 15)),
((0, 8, 0), (7, 15, 15))]
write_plotfile(
args.output, dim=3, domain_cells=(16, 16, 16),
fields={"gasDensity": density, "temperature": temperature},
levels=[Level(boxes),
# One precision throughout: yt reads a mixed-precision
# hierarchy's float32 level as NaN.
Level([((8, 8, 12), (23, 23, 19)), ((4, 20, 14), (11, 27, 17))])],
prob_lo=(-HALF_WIDTH,) * 3, prob_hi=(HALF_WIDTH,) * 3, time=3.0e15,
quokka_metadata=True)


if __name__ == "__main__":
main()
32 changes: 32 additions & 0 deletions tools/analysis_validation/make_nan_fixture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Write a small two-level single-precision plotfile whose field has NaN
cells, and one FAB of only NaN, for comparing per-FAB extrema."""

import os
import sys

import numpy as np

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..",
"tests", "python"))
from plotfile_writer import Level, write_plotfile # noqa: E402


def field(level, i, j, k):
values = 1.0 + i + 10.0 * j + 100 * k + 0.25 * level
values = np.where((i == 1) & (j == 1), np.nan, values)
return np.where((level == 1) & (k >= 20), np.nan, values)


def main():
write_plotfile(
sys.argv[1], dim=3, domain_cells=(8, 8, 16),
fields={"u": field, "w": lambda l, i, j, k: -1.5 * i + 0 * j},
levels=[Level([((0, 0, 0), (7, 7, 7)), ((0, 0, 8), (7, 7, 15))],
dtype="float32"),
Level([((4, 4, 16), (11, 11, 23)), ((0, 0, 10), (3, 3, 13))],
dtype="float32")])


if __name__ == "__main__":
main()
129 changes: 129 additions & 0 deletions tools/analysis_validation/run_comparisons.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
#!/usr/bin/env bash
# Run the ported per-FAB extrema script (python/examples) against the Kangaroo
# script it replaces on synthetic plotfiles, compare leaf cells with yt on
# real plotfiles, and report whether the outputs agree.
#
# Usage: tools/analysis_validation/run_comparisons.sh BUILD_DIR WORK_DIR
#
# Environment:
# PYTHON interpreter with numpy, yt and matplotlib (default: python3)
# KANGAROO_DIR Kangaroo checkout (default: ../kangaroo); skipped if absent
# KANGAROO_PYTHON its interpreter (default: $KANGAROO_DIR/.pixi/envs/pixi-hpx/bin/python)
# QUOKKA_PLOTFILE a real Quokka plotfile for the yt leaf-cell comparison;
# skipped if unset
# QUOKKA_HALF_WIDTH half width of the comparison box (default: 3e16)
# QUOKKA_GALAXY a real Quokka galaxy plotfile (quokka/tests/plt0000037)
# for a second yt leaf-cell comparison; skipped if unset
set -euo pipefail

if [[ $# -ne 2 ]]; then
echo "usage: $0 BUILD_DIR WORK_DIR" >&2
exit 2
fi
here="$(cd "$(dirname "$0")" && pwd)"
repo="$(cd "$here/../.." && pwd)"
build="$(cd "$1" && pwd)"
mkdir -p "$2"
work="$(cd "$2" && pwd)"
python="${PYTHON:-python3}"
kangaroo="${KANGAROO_DIR:-$repo/../kangaroo}"
kangaroo_python="${KANGAROO_PYTHON:-$kangaroo/.pixi/envs/pixi-hpx/bin/python}"
examples="$repo/python/examples"
export PYTHONPATH="$build/python${PYTHONPATH:+:$PYTHONPATH}"
failures=0

report() {
if [[ "$1" == 0 ]]; then
echo "PASS $2"
else
echo "FAIL $2"
failures=$((failures + 1))
fi
}

same_file() {
cmp -s "$1" "$2"
}

have_kangaroo() {
[[ -x "$kangaroo_python" && -d "$kangaroo/scripts" ]]
}

rm -rf "$work/plt_amr" "$work/plt_nan"
"$python" "$here/make_amr_fixture.py" "$work/plt_amr"
"$python" "$here/make_nan_fixture.py" "$work/plt_nan"

if have_kangaroo; then
# --- Kangaroo: per-FAB extrema -----------------------------------------
for plotfile in plt_amr plt_nan; do
for args in "" "--level 1" "--level 0 --fab 1"; do
read -r -a options <<< "$args"
"$python" "$examples/plotfile_fab_minmax.py" "$work/$plotfile" \
${options[@]+"${options[@]}"} > "$work/minmax_ax.txt"
(cd "$kangaroo" && "$kangaroo_python" scripts/plotfile_fab_minmax.py \
"$work/$plotfile" ${options[@]+"${options[@]}"} \
> "$work/minmax_k.txt" 2> /dev/null)
status=0
same_file "$work/minmax_ax.txt" "$work/minmax_k.txt" || status=1
report $status "per-FAB extrema vs Kangaroo, identical output ($plotfile ${args:-all levels})"
done
done
else
echo "SKIP Kangaroo comparisons ($kangaroo_python not found)"
fi

# --- yt: leaf cells of a real Quokka plotfile --------------------------------
if [[ -n "${QUOKKA_PLOTFILE:-}" ]]; then
status=0
"$python" "$here/compare_with_yt.py" "$QUOKKA_PLOTFILE" \
--half-width "${QUOKKA_HALF_WIDTH:-3e16}" \
--output "$work/quokka_vs_yt.json" > /dev/null || status=$?
if [[ $status == 0 ]]; then
"$python" - "$work/quokka_vs_yt.json" <<'EOF' || status=1
import json, sys
r = json.load(open(sys.argv[1]))
ok = (r["levels_match"] and r["gasDensity_values_identical"]
and r["temperature_values_identical"]
and max(r["phase_mass_rel_difference"]) == 0.0)
sys.exit(0 if ok else 1)
EOF
fi
report $status "Quokka leaf cells and phase masses vs yt ($QUOKKA_PLOTFILE)"
if have_kangaroo; then
# Kangaroo on the real plotfile: the level-0 FAB extrema.
"$python" "$examples/plotfile_fab_minmax.py" "$QUOKKA_PLOTFILE" --level 0 \
> "$work/q_minmax_ax.txt"
(cd "$kangaroo" && "$kangaroo_python" scripts/plotfile_fab_minmax.py \
"$QUOKKA_PLOTFILE" --level 0 > "$work/q_minmax_k.txt" 2> /dev/null)
status=0
same_file "$work/q_minmax_ax.txt" "$work/q_minmax_k.txt" || status=1
report $status "Quokka level-0 FAB extrema vs Kangaroo, identical output"
fi
else
echo "SKIP real-plotfile comparisons (QUOKKA_PLOTFILE unset)"
fi

if [[ -n "${QUOKKA_GALAXY:-}" ]]; then
galaxy="$QUOKKA_GALAXY"
status=0
"$python" "$here/compare_with_yt.py" "$galaxy" --half-width 3e22 \
--temperature-field gasInternalEnergy --output "$work/real_yt.json" \
> /dev/null 2>&1 || status=$?
if [[ $status == 0 ]]; then
"$python" - "$work/real_yt.json" <<'EOF2' || status=1
import json, sys
r = json.load(open(sys.argv[1]))
sys.exit(0 if r["levels_match"] and r["gasDensity_values_identical"]
and r["gasInternalEnergy_values_identical"] else 1)
EOF2
fi
report $status "real galaxy leaf cells vs yt, identical values"
else
echo "SKIP real galaxy comparisons (QUOKKA_GALAXY unset)"
fi

if [[ $failures -ne 0 ]]; then
echo "$failures comparison(s) failed; outputs are in $work"
exit 1
fi
echo "all comparisons passed"
Loading