openimpala 4.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. openimpala-4.1.0/CMakeLists.txt +148 -0
  2. openimpala-4.1.0/PKG-INFO +11 -0
  3. openimpala-4.1.0/bindings/VoxelImage.H +35 -0
  4. openimpala-4.1.0/bindings/config.cpp +112 -0
  5. openimpala-4.1.0/bindings/enums.cpp +82 -0
  6. openimpala-4.1.0/bindings/io.cpp +284 -0
  7. openimpala-4.1.0/bindings/module.cpp +165 -0
  8. openimpala-4.1.0/bindings/props.cpp +77 -0
  9. openimpala-4.1.0/bindings/solvers.cpp +199 -0
  10. openimpala-4.1.0/openimpala/__init__.py +111 -0
  11. openimpala-4.1.0/openimpala/_solver.py +465 -0
  12. openimpala-4.1.0/openimpala/cli.py +172 -0
  13. openimpala-4.1.0/openimpala/exceptions.py +13 -0
  14. openimpala-4.1.0/openimpala/facade.py +571 -0
  15. openimpala-4.1.0/openimpala/session.py +102 -0
  16. openimpala-4.1.0/openimpala.egg-info/PKG-INFO +11 -0
  17. openimpala-4.1.0/openimpala.egg-info/SOURCES.txt +30 -0
  18. openimpala-4.1.0/openimpala.egg-info/dependency_links.txt +1 -0
  19. openimpala-4.1.0/openimpala.egg-info/entry_points.txt +2 -0
  20. openimpala-4.1.0/openimpala.egg-info/requires.txt +2 -0
  21. openimpala-4.1.0/openimpala.egg-info/top_level.txt +1 -0
  22. openimpala-4.1.0/pyproject.toml +36 -0
  23. openimpala-4.1.0/setup.cfg +4 -0
  24. openimpala-4.1.0/tests/__init__.py +0 -0
  25. openimpala-4.1.0/tests/conftest.py +54 -0
  26. openimpala-4.1.0/tests/test_cli.py +32 -0
  27. openimpala-4.1.0/tests/test_config.py +77 -0
  28. openimpala-4.1.0/tests/test_enums.py +31 -0
  29. openimpala-4.1.0/tests/test_facade_helpers.py +39 -0
  30. openimpala-4.1.0/tests/test_percolation.py +49 -0
  31. openimpala-4.1.0/tests/test_tortuosity.py +83 -0
  32. openimpala-4.1.0/tests/test_volume_fraction.py +60 -0
@@ -0,0 +1,148 @@
1
+ # ==============================================================================
2
+ # OpenImpala Python Bindings — CMakeLists.txt
3
+ # ==============================================================================
4
+ #
5
+ # Builds the _core pybind11 extension module, linking against the existing
6
+ # openimpala_io and openimpala_props OBJECT libraries. AMReX types are
7
+ # managed natively — no pyamrex dependency.
8
+ #
9
+ # Usage (from the top-level build directory):
10
+ # cmake .. -DOPENIMPALA_PYTHON=ON
11
+ # make -j$(nproc)
12
+ #
13
+ # Or via pip / scikit-build-core:
14
+ # pip install .
15
+ # ==============================================================================
16
+
17
+ cmake_minimum_required(VERSION 3.18)
18
+
19
+ # --- Find Python and pybind11 ---
20
+ find_package(Python 3.8 COMPONENTS Interpreter Development.Module REQUIRED)
21
+ find_package(pybind11 2.11 CONFIG REQUIRED)
22
+
23
+ # --- Build the extension module ---
24
+ set(BINDING_SOURCES
25
+ bindings/module.cpp
26
+ bindings/enums.cpp
27
+ bindings/io.cpp
28
+ bindings/props.cpp
29
+ bindings/solvers.cpp
30
+ bindings/config.cpp
31
+ )
32
+ pybind11_add_module(_core ${BINDING_SOURCES})
33
+
34
+ # When CUDA is enabled, AMReX headers contain __host__/__device__ attributes
35
+ # that require compilation by nvcc.
36
+ if(GPU_BACKEND STREQUAL "CUDA")
37
+ set_source_files_properties(${BINDING_SOURCES} PROPERTIES LANGUAGE CUDA)
38
+ # AMReX's static library contains relocatable device code (RDC). The _core
39
+ # shared library must run CUDA's device linker to resolve __cudaRegister*
40
+ # symbols from AMReX and HYPRE device objects.
41
+ set_target_properties(_core PROPERTIES
42
+ CUDA_SEPARABLE_COMPILATION ON
43
+ CUDA_RESOLVE_DEVICE_SYMBOLS ON
44
+ )
45
+ endif()
46
+
47
+ target_link_libraries(_core PRIVATE
48
+ openimpala_io
49
+ openimpala_props
50
+ AMReX::amrex
51
+ HYPRE::HYPRE
52
+ ${HDF5_CXX_LIBRARIES}
53
+ ${HDF5_C_LIBRARIES}
54
+ TIFF::TIFF
55
+ MPI::MPI_CXX
56
+ nlohmann_json::nlohmann_json
57
+ )
58
+
59
+ target_include_directories(_core PRIVATE
60
+ ${CMAKE_CURRENT_SOURCE_DIR}/bindings
61
+ ${CMAKE_SOURCE_DIR}/src/io
62
+ ${CMAKE_SOURCE_DIR}/src/props
63
+ ${HDF5_INCLUDE_DIRS}
64
+ )
65
+
66
+ # Compile with C++17 to match the rest of the project
67
+ target_compile_features(_core PRIVATE cxx_std_17)
68
+
69
+ # --- Place the compiled extension directly into the Python package ---
70
+ # This ensures Python's relative imports (from . import _core) work
71
+ # natively during local testing. We skip this during wheel builds
72
+ # (when SKBUILD is defined) so scikit-build-core can track the artifact.
73
+ if(NOT SKBUILD)
74
+ set_target_properties(_core PROPERTIES
75
+ LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/openimpala"
76
+ )
77
+ endif()
78
+
79
+ # --- Install into the Python package layout ---
80
+ install(TARGETS _core LIBRARY DESTINATION openimpala COMPONENT python)
81
+ install(FILES
82
+ openimpala/__init__.py
83
+ openimpala/session.py
84
+ openimpala/exceptions.py
85
+ openimpala/facade.py
86
+ openimpala/cli.py
87
+ openimpala/_solver.py
88
+ DESTINATION openimpala
89
+ COMPONENT python
90
+ )
91
+
92
+ # ==============================================================================
93
+ # Python Tests (pytest via CTest)
94
+ # ==============================================================================
95
+ # Register pytest as a CTest target. The PYTHONPATH must include both the
96
+ # build directory (for _core.so) and the source directory (for the pure-Python
97
+ # package). Tests are only registered when BUILD_TESTING is ON.
98
+ if(BUILD_TESTING)
99
+ # Discover pytest executable
100
+ execute_process(
101
+ COMMAND ${Python_EXECUTABLE} -m pytest --version
102
+ RESULT_VARIABLE PYTEST_FOUND
103
+ OUTPUT_QUIET ERROR_QUIET
104
+ )
105
+
106
+ if(PYTEST_FOUND EQUAL 0)
107
+ set(PYTHON_TEST_DIR "${CMAKE_CURRENT_SOURCE_DIR}/tests")
108
+ set(PYTHON_PKG_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
109
+
110
+ # Helper: register one pytest file as a CTest test
111
+ function(openimpala_add_pytest TEST_NAME TEST_FILE)
112
+ add_test(
113
+ NAME ${TEST_NAME}
114
+ COMMAND ${Python_EXECUTABLE} -m pytest
115
+ ${TEST_FILE}
116
+ -v --tb=short
117
+ WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
118
+ )
119
+ set_tests_properties(${TEST_NAME} PROPERTIES
120
+ ENVIRONMENT "PYTHONPATH=${PYTHON_PKG_DIR}:$ENV{PYTHONPATH}"
121
+ TIMEOUT 120
122
+ LABELS "python"
123
+ )
124
+ endfunction()
125
+
126
+ # --- Pure-Python tests (no compiled module needed) ---
127
+ openimpala_add_pytest(pytest_cli
128
+ "${PYTHON_TEST_DIR}/test_cli.py")
129
+
130
+ # --- Tests requiring _core module ---
131
+ openimpala_add_pytest(pytest_enums
132
+ "${PYTHON_TEST_DIR}/test_enums.py")
133
+ openimpala_add_pytest(pytest_facade_helpers
134
+ "${PYTHON_TEST_DIR}/test_facade_helpers.py")
135
+ openimpala_add_pytest(pytest_config
136
+ "${PYTHON_TEST_DIR}/test_config.py")
137
+ openimpala_add_pytest(pytest_volume_fraction
138
+ "${PYTHON_TEST_DIR}/test_volume_fraction.py")
139
+ openimpala_add_pytest(pytest_percolation
140
+ "${PYTHON_TEST_DIR}/test_percolation.py")
141
+ openimpala_add_pytest(pytest_tortuosity
142
+ "${PYTHON_TEST_DIR}/test_tortuosity.py")
143
+
144
+ message(STATUS "Python tests registered with CTest (label: python)")
145
+ else()
146
+ message(STATUS "pytest not found — Python tests will not be registered with CTest")
147
+ endif()
148
+ endif()
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.4
2
+ Name: openimpala
3
+ Version: 4.1.0
4
+ Summary: Transport-property computation on 3-D voxel images — tortuosity, diffusivity, and more
5
+ License-Expression: BSD-3-Clause
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/plain
8
+ Requires-Dist: numpy
9
+ Requires-Dist: scipy>=1.7
10
+
11
+ Transport-property computation on 3-D voxel images — tortuosity, diffusivity, and more.
@@ -0,0 +1,35 @@
1
+ /** @file VoxelImage.H
2
+ * @brief Opaque container for AMReX grid objects, exposed to Python via pybind11.
3
+ *
4
+ * Encapsulates the Geometry, BoxArray, DistributionMapping, and iMultiFab
5
+ * so that Python users never need to interact with AMReX types directly.
6
+ * This eliminates the pyamrex dependency entirely.
7
+ */
8
+ #ifndef OPENIMPALA_VOXEL_IMAGE_H
9
+ #define OPENIMPALA_VOXEL_IMAGE_H
10
+
11
+ #include <memory>
12
+
13
+ #include <AMReX.H>
14
+ #include <AMReX_BoxArray.H>
15
+ #include <AMReX_DistributionMapping.H>
16
+ #include <AMReX_Geometry.H>
17
+ #include <AMReX_iMultiFab.H>
18
+
19
+ namespace OpenImpala {
20
+
21
+ /** @brief Opaque handle that bundles AMReX grid infrastructure for a 3-D voxel image.
22
+ *
23
+ * Created from a NumPy array (via pybind11) or from a native C++ reader.
24
+ * Passed by shared_ptr so pybind11 can safely prevent premature destruction.
25
+ */
26
+ struct VoxelImage {
27
+ amrex::Geometry geom;
28
+ amrex::BoxArray ba;
29
+ amrex::DistributionMapping dm;
30
+ std::shared_ptr<amrex::iMultiFab> mf;
31
+ };
32
+
33
+ } // namespace OpenImpala
34
+
35
+ #endif // OPENIMPALA_VOXEL_IMAGE_H
@@ -0,0 +1,112 @@
1
+ /** @file config.cpp
2
+ * @brief pybind11 bindings for PhysicsConfig, ResultsJSON, and CathodeWrite.
3
+ */
4
+
5
+ #include <stdexcept>
6
+ #include <sstream>
7
+
8
+ #include <pybind11/pybind11.h>
9
+ #include <pybind11/stl.h>
10
+
11
+ #include "PhysicsConfig.H"
12
+ #include "ResultsJSON.H"
13
+ #include "CathodeWrite.H"
14
+
15
+ namespace py = pybind11;
16
+ using namespace OpenImpala;
17
+
18
+ void init_config(py::module_& m) {
19
+ // =========================================================================
20
+ // PhysicsConfig
21
+ // =========================================================================
22
+ py::class_<PhysicsConfig>(
23
+ m, "PhysicsConfig",
24
+ "Maps solver output to physical quantities (diffusion, conductivity, etc.).")
25
+
26
+ .def(py::init<>())
27
+
28
+ .def_readwrite("type", &PhysicsConfig::type)
29
+ .def_readwrite("name", &PhysicsConfig::name)
30
+ .def_readwrite("coeff_label", &PhysicsConfig::coeff_label)
31
+ .def_readwrite("field_label", &PhysicsConfig::field_label)
32
+ .def_readwrite("eff_property_label", &PhysicsConfig::eff_property_label)
33
+ .def_readwrite("ratio_label", &PhysicsConfig::ratio_label)
34
+ .def_readwrite("bulk_property", &PhysicsConfig::bulk_property)
35
+
36
+ .def("effective_property", &PhysicsConfig::effectiveProperty, py::arg("D_eff_ratio"))
37
+
38
+ .def("tortuosity_factor", &PhysicsConfig::tortuosityFactor, py::arg("D_eff_ratio"),
39
+ py::arg("vf"))
40
+
41
+ .def("formation_factor", &PhysicsConfig::formationFactor, py::arg("D_eff_ratio"))
42
+
43
+ .def_static(
44
+ "from_type_string",
45
+ [](const std::string& type_str) {
46
+ PhysicsConfig cfg;
47
+ if (!PhysicsConfig::fromTypeString(type_str, cfg)) {
48
+ throw py::value_error("Unknown physics type: '" + type_str + "'");
49
+ }
50
+ return cfg;
51
+ },
52
+ py::arg("type_str"), "Create a PhysicsConfig from a type string (e.g. 'diffusion').")
53
+
54
+ .def("__repr__",
55
+ [](const PhysicsConfig& c) { return "<PhysicsConfig type='" + c.name + "'>"; });
56
+
57
+ // =========================================================================
58
+ // ResultsJSON
59
+ // =========================================================================
60
+ py::class_<ResultsJSON>(m, "ResultsJSON",
61
+ "Builder for structured JSON output (BPX / BattINFO compatible).")
62
+
63
+ .def(py::init<>())
64
+
65
+ .def("set_physics_config", &ResultsJSON::setPhysicsConfig, py::arg("config"))
66
+ .def("set_input_file", &ResultsJSON::setInputFile, py::arg("filename"))
67
+ .def("set_phase_id", &ResultsJSON::setPhaseId, py::arg("phase_id"))
68
+ .def("set_grid_info", &ResultsJSON::setGridInfo, py::arg("nx"), py::arg("ny"),
69
+ py::arg("nz"), py::arg("box_size"))
70
+ .def("set_solver_info", &ResultsJSON::setSolverInfo, py::arg("solver"),
71
+ py::arg("converged"))
72
+ .def("set_provenance", &ResultsJSON::setProvenance, py::arg("sample_id"),
73
+ py::arg("provenance_uri"))
74
+ .def("set_volume_fraction", &ResultsJSON::setVolumeFraction, py::arg("vf"))
75
+ .def("add_direction_result", &ResultsJSON::addDirectionResult, py::arg("dir"),
76
+ py::arg("D_eff_ratio"))
77
+ .def("set_bpx_electrode", &ResultsJSON::setBPXElectrode, py::arg("electrode"))
78
+
79
+ // Return JSON as a Python string (user can json.loads() it)
80
+ .def(
81
+ "build_json_string", [](const ResultsJSON& self) { return self.buildJSON().dump(2); },
82
+ "Build the JSON output and return it as a formatted string.")
83
+
84
+ .def("write", &ResultsJSON::write, py::arg("filepath"),
85
+ "Write the JSON output to a file. Returns True on success.");
86
+
87
+ // =========================================================================
88
+ // CathodeParams
89
+ // =========================================================================
90
+ py::class_<CathodeParams>(m, "CathodeParams", "Parameter set for cathode electrode output.")
91
+
92
+ .def(py::init<>())
93
+
94
+ .def_readwrite("volume_fraction_solid", &CathodeParams::volume_fraction_solid)
95
+ .def_readwrite("particle_radius", &CathodeParams::particle_radius)
96
+ .def_readwrite("active_material_conductivity", &CathodeParams::active_material_conductivity)
97
+ .def_readwrite("max_concentration", &CathodeParams::max_concentration);
98
+
99
+ // =========================================================================
100
+ // CathodeWrite
101
+ // =========================================================================
102
+ py::class_<CathodeWrite>(m, "CathodeWrite",
103
+ "Writes cathode parameter files for battery-model integration.")
104
+
105
+ .def(py::init<const CathodeParams&>(), py::arg("params"))
106
+
107
+ .def("write_dandeliion_parameters", &CathodeWrite::writeDandeLiionParameters,
108
+ py::arg("filename"), "Write DandeLiion-compatible parameter file.")
109
+
110
+ .def("write_pybamm_parameters", &CathodeWrite::writePyBammParameters, py::arg("filename"),
111
+ "Write PyBaMM-compatible parameter file.");
112
+ }
@@ -0,0 +1,82 @@
1
+ /** @file enums.cpp
2
+ * @brief pybind11 bindings for OpenImpala enums.
3
+ */
4
+
5
+ #include <pybind11/pybind11.h>
6
+
7
+ #include "BoundaryCondition.H"
8
+ #include "Tortuosity.H"
9
+ #include "RawReader.H"
10
+ #include "PhysicsConfig.H"
11
+
12
+ namespace py = pybind11;
13
+
14
+ void init_enums(py::module_& m) {
15
+ // --- Direction (X / Y / Z) ---
16
+ py::enum_<OpenImpala::Direction>(m, "Direction",
17
+ "Cardinal direction for transport calculations.")
18
+ .value("X", OpenImpala::Direction::X)
19
+ .value("Y", OpenImpala::Direction::Y)
20
+ .value("Z", OpenImpala::Direction::Z);
21
+
22
+ // --- CellType ---
23
+ py::enum_<OpenImpala::CellType>(m, "CellType", "Cell role within the computational domain.")
24
+ .value("BLOCKED", OpenImpala::CellType::BLOCKED)
25
+ .value("FREE", OpenImpala::CellType::FREE)
26
+ .value("BOUNDARY_X_LO", OpenImpala::CellType::BOUNDARY_X_LO)
27
+ .value("BOUNDARY_X_HI", OpenImpala::CellType::BOUNDARY_X_HI)
28
+ .value("BOUNDARY_Y_LO", OpenImpala::CellType::BOUNDARY_Y_LO)
29
+ .value("BOUNDARY_Y_HI", OpenImpala::CellType::BOUNDARY_Y_HI)
30
+ .value("BOUNDARY_Z_LO", OpenImpala::CellType::BOUNDARY_Z_LO)
31
+ .value("BOUNDARY_Z_HI", OpenImpala::CellType::BOUNDARY_Z_HI);
32
+
33
+ // --- RawDataType ---
34
+ py::enum_<OpenImpala::RawDataType>(
35
+ m, "RawDataType", "Primitive data type and endianness for raw binary voxel files.")
36
+ .value("UNKNOWN", OpenImpala::RawDataType::UNKNOWN)
37
+ .value("UINT8", OpenImpala::RawDataType::UINT8)
38
+ .value("INT8", OpenImpala::RawDataType::INT8)
39
+ .value("INT16_LE", OpenImpala::RawDataType::INT16_LE)
40
+ .value("INT16_BE", OpenImpala::RawDataType::INT16_BE)
41
+ .value("UINT16_LE", OpenImpala::RawDataType::UINT16_LE)
42
+ .value("UINT16_BE", OpenImpala::RawDataType::UINT16_BE)
43
+ .value("INT32_LE", OpenImpala::RawDataType::INT32_LE)
44
+ .value("INT32_BE", OpenImpala::RawDataType::INT32_BE)
45
+ .value("UINT32_LE", OpenImpala::RawDataType::UINT32_LE)
46
+ .value("UINT32_BE", OpenImpala::RawDataType::UINT32_BE)
47
+ .value("FLOAT32_LE", OpenImpala::RawDataType::FLOAT32_LE)
48
+ .value("FLOAT32_BE", OpenImpala::RawDataType::FLOAT32_BE)
49
+ .value("FLOAT64_LE", OpenImpala::RawDataType::FLOAT64_LE)
50
+ .value("FLOAT64_BE", OpenImpala::RawDataType::FLOAT64_BE);
51
+
52
+ // --- SolverType (HYPRE structured solvers — shared by Tortuosity and EffDiff) ---
53
+ py::enum_<OpenImpala::SolverType>(m, "SolverType", "HYPRE structured-grid solver algorithm.")
54
+ .value("Jacobi", OpenImpala::SolverType::Jacobi)
55
+ .value("GMRES", OpenImpala::SolverType::GMRES)
56
+ .value("FlexGMRES", OpenImpala::SolverType::FlexGMRES)
57
+ .value("PCG", OpenImpala::SolverType::PCG)
58
+ .value("BiCGSTAB", OpenImpala::SolverType::BiCGSTAB)
59
+ .value("SMG", OpenImpala::SolverType::SMG)
60
+ .value("PFMG", OpenImpala::SolverType::PFMG);
61
+
62
+ // --- EffDiffSolverType: backward-compatible alias for SolverType ---
63
+ m.attr("EffDiffSolverType") = m.attr("SolverType");
64
+
65
+ // --- BCType (boundary condition strategy for transport solvers) ---
66
+ py::enum_<OpenImpala::BCType>(m, "BCType", "Boundary condition type for transport solvers.")
67
+ .value("DirichletExternal", OpenImpala::BCType::DirichletExternal,
68
+ "Dirichlet at domain faces (standard default)")
69
+ .value("DirichletPhaseBoundary", OpenImpala::BCType::DirichletPhaseBoundary,
70
+ "Dirichlet at active cells adjacent to inactive cells near boundary")
71
+ .value("Neumann", OpenImpala::BCType::Neumann, "Zero-flux Neumann (implicit)")
72
+ .value("Periodic", OpenImpala::BCType::Periodic,
73
+ "Periodic wrapping (requires periodic grid)");
74
+
75
+ // --- PhysicsType ---
76
+ py::enum_<OpenImpala::PhysicsType>(m, "PhysicsType", "Physical quantity being computed.")
77
+ .value("Diffusion", OpenImpala::PhysicsType::Diffusion)
78
+ .value("ElectricalConductivity", OpenImpala::PhysicsType::ElectricalConductivity)
79
+ .value("ThermalConductivity", OpenImpala::PhysicsType::ThermalConductivity)
80
+ .value("DielectricPermittivity", OpenImpala::PhysicsType::DielectricPermittivity)
81
+ .value("MagneticPermeability", OpenImpala::PhysicsType::MagneticPermeability);
82
+ }
@@ -0,0 +1,284 @@
1
+ /** @file io.cpp
2
+ * @brief pybind11 bindings for OpenImpala I/O readers.
3
+ *
4
+ * Readers produce VoxelImage handles natively — no pyamrex dependency.
5
+ */
6
+
7
+ #include <memory>
8
+ #include <string>
9
+
10
+ #include <pybind11/pybind11.h>
11
+ #include <pybind11/stl.h>
12
+
13
+ #include <AMReX_BoxArray.H>
14
+ #include <AMReX_CoordSys.H>
15
+ #include <AMReX_DistributionMapping.H>
16
+ #include <AMReX_Geometry.H>
17
+ #include <AMReX_RealBox.H>
18
+ #include <AMReX_iMultiFab.H>
19
+
20
+ #include "TiffReader.H"
21
+ #include "HDF5Reader.H"
22
+ #include "RawReader.H"
23
+ #include "DatReader.H"
24
+ #include "VoxelImage.H"
25
+
26
+ namespace py = pybind11;
27
+ using namespace OpenImpala;
28
+
29
+ /** @brief Build a VoxelImage from a reader's Box, then run threshold to fill it. */
30
+ template <typename ReaderT, typename ThreshT>
31
+ static std::shared_ptr<VoxelImage>
32
+ reader_to_voxelimage(const ReaderT& reader, ThreshT threshold_value, int max_grid_size) {
33
+ auto img = std::make_shared<VoxelImage>();
34
+
35
+ const amrex::Box& box = reader.box();
36
+ img->ba.define(box);
37
+ img->ba.maxSize(max_grid_size);
38
+ img->dm.define(img->ba);
39
+ img->mf = std::make_shared<amrex::iMultiFab>(img->ba, img->dm, 1, 1);
40
+
41
+ int nx = box.length(0);
42
+ int ny = box.length(1);
43
+ int nz = box.length(2);
44
+ amrex::RealBox rb({0.0, 0.0, 0.0},
45
+ {static_cast<double>(nx), static_cast<double>(ny), static_cast<double>(nz)});
46
+ amrex::Array<int, AMREX_SPACEDIM> is_periodic{0, 0, 0};
47
+ img->geom.define(box, &rb, amrex::CoordSys::cartesian, is_periodic.data());
48
+
49
+ reader.threshold(threshold_value, *(img->mf));
50
+ return img;
51
+ }
52
+
53
+ /** @brief Build a VoxelImage with custom threshold output values. */
54
+ template <typename ReaderT, typename ThreshT>
55
+ static std::shared_ptr<VoxelImage>
56
+ reader_to_voxelimage_custom(const ReaderT& reader, ThreshT threshold_value, int value_if_true,
57
+ int value_if_false, int max_grid_size) {
58
+ auto img = std::make_shared<VoxelImage>();
59
+
60
+ const amrex::Box& box = reader.box();
61
+ img->ba.define(box);
62
+ img->ba.maxSize(max_grid_size);
63
+ img->dm.define(img->ba);
64
+ img->mf = std::make_shared<amrex::iMultiFab>(img->ba, img->dm, 1, 1);
65
+
66
+ int nx = box.length(0);
67
+ int ny = box.length(1);
68
+ int nz = box.length(2);
69
+ amrex::RealBox rb({0.0, 0.0, 0.0},
70
+ {static_cast<double>(nx), static_cast<double>(ny), static_cast<double>(nz)});
71
+ amrex::Array<int, AMREX_SPACEDIM> is_periodic{0, 0, 0};
72
+ img->geom.define(box, &rb, amrex::CoordSys::cartesian, is_periodic.data());
73
+
74
+ reader.threshold(threshold_value, value_if_true, value_if_false, *(img->mf));
75
+ return img;
76
+ }
77
+
78
+ void init_io(py::module_& m) {
79
+ // =========================================================================
80
+ // TiffReader
81
+ // =========================================================================
82
+ py::class_<TiffReader>(
83
+ m, "TiffReader",
84
+ "Reads 3-D image data from single/multi-directory TIFFs or file sequences.")
85
+
86
+ .def(py::init<>(),
87
+ "Create an empty reader. Call read_file() or read_file_sequence() next.")
88
+
89
+ .def(py::init<const std::string&>(), py::arg("filename"),
90
+ "Open a single TIFF file and read its metadata (no pixel data yet).")
91
+
92
+ .def(py::init<const std::string&, int, int, int, const std::string&>(),
93
+ py::arg("base_pattern"), py::arg("num_files"), py::arg("start_index") = 0,
94
+ py::arg("digits") = 1, py::arg("suffix") = ".tif",
95
+ "Open a numbered TIFF sequence and read metadata from the first file.")
96
+
97
+ .def("read_file", &TiffReader::readFile, py::arg("filename"),
98
+ "Read metadata from a single TIFF (clears previous state).")
99
+
100
+ .def("read_file_sequence", &TiffReader::readFileSequence, py::arg("base_pattern"),
101
+ py::arg("num_files"), py::arg("start_index") = 0, py::arg("digits") = 1,
102
+ py::arg("suffix") = ".tif",
103
+ "Read metadata from a TIFF sequence (clears previous state).")
104
+
105
+ // Two-arg threshold → VoxelImage
106
+ .def(
107
+ "threshold",
108
+ [](const TiffReader& self, double raw_threshold, int max_grid_size) {
109
+ return reader_to_voxelimage(self, raw_threshold, max_grid_size);
110
+ },
111
+ py::arg("raw_threshold"), py::arg("max_grid_size") = 32,
112
+ "Threshold the image and return a VoxelImage (1 where pixel > threshold, else 0).")
113
+
114
+ // Four-arg threshold → VoxelImage
115
+ .def(
116
+ "threshold",
117
+ [](const TiffReader& self, double raw_threshold, int value_if_true, int value_if_false,
118
+ int max_grid_size) {
119
+ return reader_to_voxelimage_custom(self, raw_threshold, value_if_true,
120
+ value_if_false, max_grid_size);
121
+ },
122
+ py::arg("raw_threshold"), py::arg("value_if_true"), py::arg("value_if_false"),
123
+ py::arg("max_grid_size") = 32,
124
+ "Threshold the image with custom output values and return a VoxelImage.")
125
+
126
+ // Metadata properties
127
+ .def_property_readonly("box", &TiffReader::box)
128
+ .def_property_readonly("width", &TiffReader::width)
129
+ .def_property_readonly("height", &TiffReader::height)
130
+ .def_property_readonly("depth", &TiffReader::depth)
131
+ .def_property_readonly("is_read", &TiffReader::isRead)
132
+ .def_property_readonly("bits_per_sample", &TiffReader::bitsPerSample)
133
+ .def_property_readonly("sample_format", &TiffReader::sampleFormat)
134
+ .def_property_readonly("samples_per_pixel", &TiffReader::samplesPerPixel)
135
+ .def_property_readonly("fill_order", &TiffReader::getFillOrder)
136
+
137
+ .def("__repr__", [](const TiffReader& r) {
138
+ if (!r.isRead())
139
+ return std::string("<TiffReader (no file loaded)>");
140
+ return "<TiffReader " + std::to_string(r.width()) + "x" + std::to_string(r.height()) +
141
+ "x" + std::to_string(r.depth()) + ">";
142
+ });
143
+
144
+ // =========================================================================
145
+ // HDF5Reader
146
+ // =========================================================================
147
+ py::class_<HDF5Reader>(m, "HDF5Reader", "Reads 3-D datasets from HDF5 files.")
148
+
149
+ .def(py::init<>())
150
+
151
+ .def(py::init<const std::string&, const std::string&>(), py::arg("filename"),
152
+ py::arg("hdf5dataset"),
153
+ "Open an HDF5 file and read metadata for the specified dataset.")
154
+
155
+ .def("read_file", &HDF5Reader::readFile, py::arg("filename"), py::arg("hdf5dataset"),
156
+ "Read metadata from an HDF5 file + dataset (clears previous state).")
157
+
158
+ .def(
159
+ "threshold",
160
+ [](const HDF5Reader& self, double raw_threshold, int max_grid_size) {
161
+ return reader_to_voxelimage(self, raw_threshold, max_grid_size);
162
+ },
163
+ py::arg("raw_threshold"), py::arg("max_grid_size") = 32)
164
+
165
+ .def(
166
+ "threshold",
167
+ [](const HDF5Reader& self, double raw_threshold, int value_if_true, int value_if_false,
168
+ int max_grid_size) {
169
+ return reader_to_voxelimage_custom(self, raw_threshold, value_if_true,
170
+ value_if_false, max_grid_size);
171
+ },
172
+ py::arg("raw_threshold"), py::arg("value_if_true"), py::arg("value_if_false"),
173
+ py::arg("max_grid_size") = 32)
174
+
175
+ .def_property_readonly("box", &HDF5Reader::box)
176
+ .def_property_readonly("width", &HDF5Reader::width)
177
+ .def_property_readonly("height", &HDF5Reader::height)
178
+ .def_property_readonly("depth", &HDF5Reader::depth)
179
+ .def_property_readonly("is_read", &HDF5Reader::isRead)
180
+
181
+ .def("get_attribute", &HDF5Reader::getAttribute, py::arg("attr_name"),
182
+ "Read a string attribute from the HDF5 dataset.")
183
+
184
+ .def("get_all_attributes", &HDF5Reader::getAllAttributes,
185
+ "Read all attributes from the HDF5 dataset as a dict.")
186
+
187
+ .def("__repr__", [](const HDF5Reader& r) {
188
+ if (!r.isRead())
189
+ return std::string("<HDF5Reader (no file loaded)>");
190
+ return "<HDF5Reader " + std::to_string(r.width()) + "x" + std::to_string(r.height()) +
191
+ "x" + std::to_string(r.depth()) + ">";
192
+ });
193
+
194
+ // =========================================================================
195
+ // RawReader
196
+ // =========================================================================
197
+ py::class_<RawReader>(m, "RawReader", "Reads 3-D voxel data from flat binary (RAW) files.")
198
+
199
+ .def(py::init<>())
200
+
201
+ .def(py::init<const std::string&, int, int, int, RawDataType>(), py::arg("filename"),
202
+ py::arg("width"), py::arg("height"), py::arg("depth"), py::arg("data_type"),
203
+ "Open a raw binary file with externally supplied dimensions and data type.")
204
+
205
+ .def("read_file", &RawReader::readFile, py::arg("filename"), py::arg("width"),
206
+ py::arg("height"), py::arg("depth"), py::arg("data_type"))
207
+
208
+ .def(
209
+ "threshold",
210
+ [](const RawReader& self, double threshold_value, int max_grid_size) {
211
+ return reader_to_voxelimage(self, threshold_value, max_grid_size);
212
+ },
213
+ py::arg("threshold_value"), py::arg("max_grid_size") = 32)
214
+
215
+ .def(
216
+ "threshold",
217
+ [](const RawReader& self, double threshold_value, int value_if_true, int value_if_false,
218
+ int max_grid_size) {
219
+ return reader_to_voxelimage_custom(self, threshold_value, value_if_true,
220
+ value_if_false, max_grid_size);
221
+ },
222
+ py::arg("threshold_value"), py::arg("value_if_true"), py::arg("value_if_false"),
223
+ py::arg("max_grid_size") = 32)
224
+
225
+ .def_property_readonly("box", &RawReader::box)
226
+ .def_property_readonly("width", &RawReader::width)
227
+ .def_property_readonly("height", &RawReader::height)
228
+ .def_property_readonly("depth", &RawReader::depth)
229
+ .def_property_readonly("is_read", &RawReader::isRead)
230
+ .def_property_readonly("data_type", &RawReader::getDataType)
231
+
232
+ .def("get_value", &RawReader::getValue, py::arg("i"), py::arg("j"), py::arg("k"),
233
+ "Retrieve a single voxel value (converted to float).")
234
+
235
+ .def("__repr__", [](const RawReader& r) {
236
+ if (!r.isRead())
237
+ return std::string("<RawReader (no file loaded)>");
238
+ return "<RawReader " + std::to_string(r.width()) + "x" + std::to_string(r.height()) +
239
+ "x" + std::to_string(r.depth()) + ">";
240
+ });
241
+
242
+ // =========================================================================
243
+ // DatReader
244
+ // =========================================================================
245
+ py::class_<DatReader>(m, "DatReader", "Reads 3-D image data from legacy DAT binary files.")
246
+
247
+ .def(py::init<>())
248
+
249
+ .def(py::init<const std::string&>(), py::arg("filename"))
250
+
251
+ .def("read_file", &DatReader::readFile, py::arg("filename"))
252
+
253
+ .def(
254
+ "threshold",
255
+ [](const DatReader& self, DatReader::DataType raw_threshold, int max_grid_size) {
256
+ return reader_to_voxelimage(self, raw_threshold, max_grid_size);
257
+ },
258
+ py::arg("raw_threshold"), py::arg("max_grid_size") = 32)
259
+
260
+ .def(
261
+ "threshold",
262
+ [](const DatReader& self, DatReader::DataType raw_threshold, int value_if_true,
263
+ int value_if_false, int max_grid_size) {
264
+ return reader_to_voxelimage_custom(self, raw_threshold, value_if_true,
265
+ value_if_false, max_grid_size);
266
+ },
267
+ py::arg("raw_threshold"), py::arg("value_if_true"), py::arg("value_if_false"),
268
+ py::arg("max_grid_size") = 32)
269
+
270
+ .def_property_readonly("box", &DatReader::box)
271
+ .def_property_readonly("width", &DatReader::width)
272
+ .def_property_readonly("height", &DatReader::height)
273
+ .def_property_readonly("depth", &DatReader::depth)
274
+ .def_property_readonly("is_read", &DatReader::isRead)
275
+
276
+ .def("get_raw_value", &DatReader::getRawValue, py::arg("i"), py::arg("j"), py::arg("k"))
277
+
278
+ .def("__repr__", [](const DatReader& r) {
279
+ if (!r.isRead())
280
+ return std::string("<DatReader (no file loaded)>");
281
+ return "<DatReader " + std::to_string(r.width()) + "x" + std::to_string(r.height()) +
282
+ "x" + std::to_string(r.depth()) + ">";
283
+ });
284
+ }