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
8 changes: 4 additions & 4 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ turns a `SliceRequest` into a displayable `SliceDisplayResult` — raster image,
contour polylines, vector glyphs, resolved color range — with no Qt dependency.

Beside the display path, `src/analysis` (on `io` and `core`) serves scripts
rather than screens: exact leaf-cell traversal, in native values. `python/`
binds it with nanobind into the `amrexplorer` package (built when
`AMREXPLORER_ENABLE_PYTHON=ON`, or by `pip install .`). See
[python-analysis.md](python-analysis.md).
rather than screens: exact leaf-cell traversal and block statistics, in
native values. `python/` binds it with nanobind into the
`amrexplorer` package (built when `AMREXPLORER_ENABLE_PYTHON=ON`, or by
`pip install .`). See [python-analysis.md](python-analysis.md).

## The GUI layer

Expand Down
14 changes: 13 additions & 1 deletion docs/python-analysis.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
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.
serially or in parallel, and per-block statistics.

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 Expand Up @@ -91,9 +91,21 @@ order, so the result is bit-for-bit the serial one. `executor="processes"`
needs a picklable mapper. For MPI, plan on every rank and pass
`items=plan.partition(rank, size)`. A `CancelToken` stops reads in progress.

## Grids

`ds.blocks()` lists every grid with its box, bounds and covered fraction;
`ds.block_statistics(fields)` gives per-grid minima and maxima from the
decoded data, NaN ignored.

## Batches

`amrexplorer.sequence.find_plotfiles(directory)` lists a run's plotfiles in
step order, `open_each(paths)` opens them one at a time, and `output_path` /
`needs_output` skip outputs already written. Long operations take
`progress=` callbacks and `cancel=` tokens.

## Examples

`python/examples/plotfile_fab_minmax.py` ports Kangaroo's script of the same
name, keeping its arguments and output, and says in its docstring what it
validates.
61 changes: 61 additions & 0 deletions include/amrexplorer/analysis/Blocks.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#pragma once

#include <amrexplorer/core/Geometry.hpp>
#include <amrexplorer/core/StopToken.hpp>

#include <cstdint>
#include <optional>
#include <string>
#include <vector>

// The plotfile's own grid structure, rather than a partition of its leaf
// cells. Blocks are listed by level and then native FAB index, the order the
// level header lists them, and each says its FAB index so output and
// selection match tools that address FABs by plotfile position.

namespace amrvis {

class PlotfileDataset;

struct BlockInfo {
int level = 0;
// The native FAB index on its level.
int grid = 0;
// The valid index box and its physical bounds.
IntBox box;
RealBox bounds;
std::uint64_t cells = 0;
// Valid cells the next finer level covers: not leaves.
std::uint64_t coveredCells = 0;
// Where the payload is: the FAB's data file, relative to the plotfile,
// and its byte offset.
std::string file;
std::uint64_t offset = 0;
};

// Every block, or one level's. Throws AnalysisError for a missing level.
[[nodiscard]] std::vector<BlockInfo> listBlocks(
const PlotfileDataset& dataset, std::optional<int> level = std::nullopt);

struct BlockExtrema {
int level = 0;
int grid = 0;
// The box the extrema cover, per field: a stored field's whole on-disk
// FAB, stored ghost cells included; a derived field's valid box, since
// derived blocks have no stored ghost cells.
std::vector<IntBox> boxes;
std::vector<bool> includesGhostCells;
// NaN is ignored; a block whose values are all NaN reports NaN for both.
std::vector<double> minimum;
std::vector<double> maximum;
};

// Extrema computed from the decoded data, not from the MultiFab header's
// per-FAB minima and maxima: AMReX computes those before converting to the
// stored precision, writes them as text at limited precision, and lets NaN
// propagate. Covered cells count like any other.
[[nodiscard]] std::vector<BlockExtrema> blockStatistics(PlotfileDataset& dataset,
const std::vector<std::string>& fields, std::optional<int> level = std::nullopt,
std::optional<int> grid = std::nullopt, StopToken cancellation = {});

} // namespace amrvis
29 changes: 29 additions & 0 deletions python/amrexplorer/_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,35 @@ def leaf_cells(self, fields: Iterable[str] = (), region: Region = None,
progress(done, len(plan))
yield chunk

# Blocks -------------------------------------------------------------------
def blocks(self, level: Optional[int] = None) -> list:
"""The plotfile's grids (FABs), by level and then native FAB index:
each with its level, FAB index ("grid"), valid index box, physical
bounds, cell count, the cells the next finer level covers
("covered_cells") and "covered_fraction", and its data file and
offset."""
blocks = [dict(block) for block in self._native.blocks(level)]
for block in blocks:
block["box"] = tuple(tuple(side) for side in block["box"])
block["covered_fraction"] = block["covered_cells"] / block["cells"]
return blocks

def block_statistics(self, fields: Iterable[str], level: Optional[int] = None,
grid: Optional[int] = None, *, cancel=None) -> list:
"""Per-block minima and maxima of each field, from the decoded data
with NaN ignored (a block of all NaN reports NaN). A stored field's
extrema cover the whole on-disk FAB, covered cells and stored ghost
cells included; a derived field's cover its valid box. Each entry
says which box ("box", "includes_ghost_cells", per field)."""
if isinstance(fields, str):
fields = [fields]
entries = [dict(entry) for entry in self._native.block_statistics(
list(fields), level, grid, cancel)]
for entry in entries:
entry["box"] = {name: tuple(tuple(side) for side in box)
for name, box in entry["box"].items()}
return entries

def __repr__(self) -> str:
state = "closed" if self.closed else f"{self.dimension}-D"
return f"Dataset({self._native.path if not self.closed else ''!r}, {state})"
Expand Down
48 changes: 48 additions & 0 deletions python/examples/plotfile_fab_minmax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""Print per-component min/max for each FAB in a plotfile.

A port of Kangaroo's ``scripts/plotfile_fab_minmax.py`` to amrexplorer's
block statistics (docs/python-analysis.md), printing the same
report. Extrema are computed from the decoded data over each whole on-disk
FAB -- covered cells and stored ghost cells included -- with NaN ignored; a
FAB whose values are all NaN reports nan.

Validates: raw source values.
"""

from __future__ import annotations

import argparse
import os

import amrexplorer


def main(argv=None) -> int:
parser = argparse.ArgumentParser(description="Print per-component min/max for each FAB.")
parser.add_argument("plotfile", help="Path to the plotfile directory.")
parser.add_argument("--level", type=int, default=None, help="Level to inspect (default: all).")
parser.add_argument("--fab", type=int, default=None, help="FAB index to inspect (default: all).")
args = parser.parse_args(argv)

if not os.path.isdir(args.plotfile):
print(f"Plotfile path does not exist: {args.plotfile}")
return 1

with amrexplorer.open_plotfile(args.plotfile) as ds:
names = ds.stored_fields
levels = [args.level] if args.level is not None else range(ds.finest_level + 1)
for level in levels:
nfabs = ds.levels[level]["num_grids"]
print(f"Level {level}: {nfabs} FABs")
for entry in ds.block_statistics(names, level=level, grid=args.fab):
print(f" FAB {entry['grid']}:")
for c, name in enumerate(names):
lo = entry["minimum"][name]
hi = entry["maximum"][name]
print(f" {c:02d} {name}: min={lo:.6e} max={hi:.6e}")
return 0


if __name__ == "__main__":
raise SystemExit(main())
67 changes: 66 additions & 1 deletion python/src/module.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// The ergonomic surface (open_plotfile, context management, region and dtype
// spellings) lives in the pure-Python package around this module.

#include <amrexplorer/analysis/Blocks.hpp>
#include <amrexplorer/analysis/LeafChunks.hpp>
#include <amrexplorer/cache/ByteLruCache.hpp>
#include <amrexplorer/core/CacheConfig.hpp>
Expand Down Expand Up @@ -346,6 +347,67 @@ class Dataset {
return readLeafChunk(*keep, item, token);
}

nb::list blocks(std::optional<int> level) const
{
const auto& data = dataset();
const auto dimension = data.metadata().dimension;
nb::list result;
for (const auto& block : listBlocks(data, level)) {
nb::dict entry;
entry["level"] = block.level;
entry["grid"] = block.grid;
entry["box"] = boxTuple(block.box, dimension);
entry["lower"] = realVector(block.bounds.lower, dimension);
entry["upper"] = realVector(block.bounds.upper, dimension);
entry["cells"] = block.cells;
entry["covered_cells"] = block.coveredCells;
entry["file"] = block.file;
entry["offset"] = block.offset;
result.append(entry);
}
return result;
}

nb::list blockStatistics(const std::vector<std::string>& fields,
std::optional<int> level, std::optional<int> grid,
const CancelToken* cancel)
{
auto keep = m_dataset;
if (!keep) {
throw DatasetClosed();
}
const auto dimension = keep->metadata().dimension;
std::vector<BlockExtrema> extrema;
{
const auto token = tokenOf(cancel);
nb::gil_scoped_release release;
extrema = amrvis::blockStatistics(*keep, fields, level, grid, token);
}
nb::list result;
for (const auto& block : extrema) {
nb::dict entry;
entry["level"] = block.level;
entry["grid"] = block.grid;
nb::dict minimum;
nb::dict maximum;
nb::dict boxes;
nb::dict ghost;
for (std::size_t field = 0; field < fields.size(); ++field) {
const auto name = nb::str(fields[field].c_str());
minimum[name] = block.minimum[field];
maximum[name] = block.maximum[field];
boxes[name] = boxTuple(block.boxes[field], dimension);
ghost[name] = static_cast<bool>(block.includesGhostCells[field]);
}
entry["minimum"] = minimum;
entry["maximum"] = maximum;
entry["box"] = boxes;
entry["includes_ghost_cells"] = ghost;
result.append(entry);
}
return result;
}

private:
std::shared_ptr<PlotfileDataset> m_dataset;
};
Expand Down Expand Up @@ -437,7 +499,10 @@ NB_MODULE(_amrexplorer, m)
[](Dataset& self, const PlanItem& item, const CancelToken* cancel) {
return self.read(item.item(), cancel);
},
"item"_a, "cancel"_a.none() = nb::none());
"item"_a, "cancel"_a.none() = nb::none())
.def("blocks", &Dataset::blocks, "level"_a.none())
.def("block_statistics", &Dataset::blockStatistics, "fields"_a,
"level"_a.none(), "grid"_a.none(), "cancel"_a.none() = nb::none());

nb::class_<LeafChunkPlan>(m, "_LeafChunkPlan")
.def("__len__",
Expand Down
Loading
Loading