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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,6 @@ __pycache__/

# ctest run artifacts (ctest from the repo root writes here)
/Testing/

# Python virtual environment
/.venv/
13 changes: 13 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ option(AMREXPLORER_ENABLE_VTK "Build the optional VTK volume module" OFF)
option(AMREXPLORER_ENABLE_REMOTE
"Build production remote client/server support" ${AMREXPLORER_ENABLE_QT})
option(AMREXPLORER_BUILD_TESTS "Build unit and integration tests" ON)
option(AMREXPLORER_ENABLE_PYTHON
"Build the amrexplorer Python analysis module (needs nanobind)" OFF)
option(AMREXPLORER_ENABLE_SERVER_TEST_HOOKS
"Enable internal remote-server synchronization hooks for tests" OFF)
option(AMREXPLORER_BUILD_MACOS_APP_BUNDLE
Expand Down Expand Up @@ -222,6 +224,12 @@ if(NOT AMREXPLORER_HAS_REQUIRED_CXX20_SUPPORT)
"would succeed.")
endif()

# The Python module is a shared library, so every static library it links has
# to be position independent.
if(AMREXPLORER_ENABLE_PYTHON)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
endif()

list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
include(amrexplorer_warnings)

Expand Down Expand Up @@ -249,6 +257,7 @@ add_subdirectory(src/expression)
add_subdirectory(src/core)
add_subdirectory(src/cache)
add_subdirectory(src/io)
add_subdirectory(src/analysis)
add_subdirectory(src/query)
add_subdirectory(src/render3d)
add_subdirectory(src/data)
Expand Down Expand Up @@ -320,6 +329,10 @@ if(AMREXPLORER_ENABLE_VTK)
"is Qt 5-based and must not be linked into this Qt 6 application.")
endif()

if(AMREXPLORER_ENABLE_PYTHON)
add_subdirectory(python)
endif()

add_subdirectory(tools/dataset_inspect)
add_subdirectory(tools/query_benchmark)
add_subdirectory(tools/line_repro)
Expand Down
6 changes: 6 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ file or wire I/O itself. `SlicePipeline` (and the query/render layers under it)
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 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

`MainWindow` is the one window; it owns the plane views (`PlaneViewState`
Expand Down
12 changes: 12 additions & 0 deletions docs/building.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,18 @@ OUTPUT=amrexplorer.AppImage QML_SOURCES_PATHS=. \
--plugin qt
```

## Python analysis module

`-DAMREXPLORER_ENABLE_PYTHON=ON` builds the `amrexplorer` Python package's
nanobind extension into `<build>/python/amrexplorer`, importable with
`PYTHONPATH=<build>/python`. It needs an interpreter with `nanobind` and
`numpy`; point `-DPython_EXECUTABLE` at it if it is not the first on `PATH`.
With `pytest` there too, ctest runs the package's tests as `python_analysis`.
The GUI is not needed (`-DAMREXPLORER_ENABLE_QT=OFF
-DAMREXPLORER_ENABLE_REMOTE=OFF` is the usual pairing), and `pip install .`
builds the module alone through `pyproject.toml`. See
[python-analysis.md](python-analysis.md).

## Optional VTK module

`AMREXPLORER_ENABLE_VTK` is currently deliberately unavailable. It remains off
Expand Down
113 changes: 113 additions & 0 deletions docs/python-analysis.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# Analyzing plotfiles from Python

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
of a solar mass itself.

## Installing

From a checkout, with a C++20 compiler and CMake 3.25 or newer:

```sh
python -m pip install .
```

This builds only the analysis extension (no Qt, no remote protocol). For
development, configure a normal build with the module switched on and point
`PYTHONPATH` at it:

```sh
cmake -S . -B build-python -G Ninja -DAMREXPLORER_ENABLE_QT=OFF \
-DAMREXPLORER_ENABLE_REMOTE=OFF -DAMREXPLORER_ENABLE_PYTHON=ON \
-DPython_EXECUTABLE=$(which python3)
cmake --build build-python
PYTHONPATH=build-python/python python3 -c "import amrexplorer"
```

The interpreter must have `nanobind` and `numpy` (`pip install nanobind
numpy`). With `pytest` installed as well, `ctest` runs the Python suite as
the `python_analysis` test.

## Leaf cells

```python
import numpy as np
import amrexplorer

with amrexplorer.open_plotfile("plt00100") as ds:
print(ds.fields, ds.time, ds.levels)
plan = ds.plan_leaf_chunks(["gasDensity", "temperature"],
region=([-1e21] * 3, [1e21] * 3))
cold = 0.0
for item in plan: # one item per grid (FAB)
chunk = ds.read_leaf_chunk(item)
rho = chunk["gasDensity"]
mask = chunk["temperature"] < 200
cold += np.sum(rho[mask] * chunk.cell_volume[mask])
```

- A plan lists the grids that hold leaf cells -- cells no finer level
covers -- in a fixed order: levels coarsest first, grids in the order the
level header lists them. Within a chunk, cells are in FAB order, x fastest.
Every leaf cell of the region appears in exactly one chunk.
- `region` selects cells by center, `lower <= center < upper` on each axis,
so adjacent regions partition the cells between them.
- Field arrays use the widest precision any level stores, unless `dtype=`
says otherwise. Geometry (`chunk.x`, `.y`, `.z`, `.dx`, `.i`, ...,
`.cell_volume`) is float64 and computed on first use. A 2-D chunk has no
`z`.
- Chunks are copies: they hold no cache memory and outlive the dataset.
Arrays are read-only.
- `ds.leaf_cells(...)` plans and reads in one loop.

Derived fields are defined when the dataset opens, in the viewer's expression
syntax, and fail at open if they do not resolve:

```python
ds = amrexplorer.open_plotfile("plt00100", derived=[("vx", "${x-GasMomentum}/gasDensity")])
```

`cache_bytes=` sets the block cache, otherwise `AMREXPLORER_CACHE_SIZE_MB` or
1 GiB. A plan refuses, with the grid named, any item that might not fit.

## Parallel reductions

```python
from amrexplorer import parallel

total = parallel.map_reduce("plt00100", parallel.LeafCells(["gasDensity"]),
lambda c: float(np.sum(c["gasDensity"] * c.cell_volume)),
lambda a, b: a + b, executor="threads", workers=8)
```

Each worker opens its own handle and plans the same request; at most
`max_in_flight` items are in progress at once; partials are combined in plan
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
Loading
Loading