diff --git a/CMakeLists.txt b/CMakeLists.txt index 42ac7e8723..fc28fba18d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -195,7 +195,56 @@ if(NOT DEFINED BUILD_EXAMPLES) endif() option(openPMD_BUILD_CLI_TOOLS "Build the command line tools" ${BUILD_CLI_TOOLS}) option(openPMD_BUILD_EXAMPLES "Build the examples" ${BUILD_EXAMPLES}) -openpmd_option(CUDA_EXAMPLES "Use CUDA in examples" OFF) +# Remember whether the options were set explicitly (e.g. on the command line) +# before creating the cache entries. CMake marks command-line cache entries as +# UNINITIALIZED until the option() call assigns them a type. +if(DEFINED openPMD_USE_CUDA) + set(openPMD_USE_CUDA_explicit TRUE) + get_property(_openPMD_USE_CUDA_type CACHE openPMD_USE_CUDA PROPERTY TYPE) + if(_openPMD_USE_CUDA_type STREQUAL "UNINITIALIZED") + set(openPMD_USE_CUDA_user_specified TRUE) + else() + set(openPMD_USE_CUDA_user_specified FALSE) + endif() +else() + set(openPMD_USE_CUDA_explicit FALSE) + set(openPMD_USE_CUDA_user_specified FALSE) +endif() +if(DEFINED openPMD_USE_CUDA_EXAMPLES) + get_property(_openPMD_USE_CUDA_EXAMPLES_type CACHE + openPMD_USE_CUDA_EXAMPLES PROPERTY TYPE) + if(_openPMD_USE_CUDA_EXAMPLES_type STREQUAL "UNINITIALIZED") + set(openPMD_USE_CUDA_EXAMPLES_user_specified TRUE) + else() + set(openPMD_USE_CUDA_EXAMPLES_user_specified FALSE) + endif() +else() + set(openPMD_USE_CUDA_EXAMPLES_user_specified FALSE) +endif() +openpmd_option(CUDA "Use CUDA in tests and examples" OFF) + +# deprecated: backwards compatibility to the CUDA_EXAMPLES option +openpmd_option(CUDA_EXAMPLES "Deprecated: use openPMD_USE_CUDA" OFF) +mark_as_advanced(openPMD_USE_CUDA_EXAMPLES) +if(openPMD_USE_CUDA_user_specified + AND openPMD_USE_CUDA_EXAMPLES_user_specified) + message(WARNING + "Both openPMD_USE_CUDA and the deprecated openPMD_USE_CUDA_EXAMPLES " + "were specified; openPMD_USE_CUDA takes precedence.") +endif() +if(NOT openPMD_USE_CUDA_EXAMPLES STREQUAL "OFF") + message(DEPRECATION + "openPMD_USE_CUDA_EXAMPLES is deprecated; use openPMD_USE_CUDA") + if(NOT openPMD_USE_CUDA_explicit) + set(openPMD_USE_CUDA "${openPMD_USE_CUDA_EXAMPLES}" CACHE STRING + "Use CUDA in tests and examples" FORCE) + endif() +endif() +unset(openPMD_USE_CUDA_explicit) +unset(openPMD_USE_CUDA_user_specified) +unset(openPMD_USE_CUDA_EXAMPLES_user_specified) +unset(_openPMD_USE_CUDA_type) +unset(_openPMD_USE_CUDA_EXAMPLES_type) # Helper Functions ############################################################ @@ -272,14 +321,19 @@ target_link_libraries(openPMD::thirdparty::toml11 INTERFACE toml11::toml11) # external: CUDA (optional) -if(openPMD_BUILD_EXAMPLES) # currently only used in examples - if(openPMD_USE_CUDA_EXAMPLES STREQUAL AUTO) - find_package(CUDAToolkit) - elseif(openPMD_USE_CUDA_EXAMPLES) - find_package(CUDAToolkit REQUIRED) - endif() +if(openPMD_USE_CUDA STREQUAL AUTO) + find_package(CUDAToolkit QUIET) + set(openPMD_HAVE_CUDA ${CUDAToolkit_FOUND}) +elseif(openPMD_USE_CUDA) + find_package(CUDAToolkit REQUIRED) + set(openPMD_HAVE_CUDA TRUE) +else() + set(openPMD_HAVE_CUDA FALSE) endif() -if(CUDAToolkit_FOUND) + +# The CUDA language is only needed to compile the examples. Tests only use the +# CUDA runtime, which is linked via the CUDA::cudart imported target. +if(openPMD_HAVE_CUDA AND openPMD_BUILD_EXAMPLES) enable_language(CUDA) set(openPMD_HAVE_CUDA_EXAMPLES TRUE) else() @@ -858,6 +912,7 @@ if(openPMD_BUILD_TESTING) test/Files_SerialIO/components_without_extent.cpp test/Files_SerialIO/read_while_writing.cpp test/Files_SerialIO/file_state_lifetime.cpp + test/Files_SerialIO/adios2_array_ordering.cpp ) elseif(${test_name} STREQUAL "ParallelIO" AND openPMD_HAVE_MPI) list(APPEND ${out_list} @@ -910,6 +965,10 @@ if(openPMD_BUILD_TESTING) target_compile_definitions(${testname}Tests PRIVATE openPMD_USE_INVASIVE_TESTS=1) endif() target_link_libraries(${testname}Tests PRIVATE openPMD) + if(${testname} STREQUAL SerialIO AND openPMD_HAVE_CUDA) + target_link_libraries(${testname}Tests PRIVATE CUDA::cudart) + target_compile_definitions(${testname}Tests PRIVATE openPMD_TEST_CUDA=1) + endif() if(${testname} MATCHES "Parallel.+$") # Parallel tests use CatchRunner (custom main with MPI) target_link_libraries(${testname}Tests PRIVATE CatchRunner) diff --git a/README.md b/README.md index 2348eebbc1..4287318344 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ Optional language bindings: * mpi4py 2.1+ (optional, for MPI) * pandas 1.0+ (optional, for dataframes) * dask 2021+ (optional, for dask dataframes) -* CUDA C++ (optional, currently used only in tests) +* CUDA C++ (optional, used in tests and examples) ## Installation @@ -284,7 +284,11 @@ In order to skip building those, pass ``OFF`` to these ``cmake`` options: | `openPMD_BUILD_TESTING` | **ON**/OFF | Build tests | | `openPMD_BUILD_EXAMPLES` | **ON**/OFF | Build examples | | `openPMD_BUILD_CLI_TOOLS` | **ON**/OFF | Build command-line tools | -| `openPMD_USE_CUDA_EXAMPLES` | ON/**OFF** | Use CUDA in examples | +| `openPMD_USE_CUDA` | ON/AUTO/**OFF** | Use CUDA in tests and examples | + +CUDA is never used unless requested. The deprecated +`openPMD_USE_CUDA_EXAMPLES` option is kept as an advanced alias for +`openPMD_USE_CUDA`. ## Linking to your project diff --git a/docs/source/backends/adios2.rst b/docs/source/backends/adios2.rst index 3a03cc725b..50e7f40067 100644 --- a/docs/source/backends/adios2.rst +++ b/docs/source/backends/adios2.rst @@ -83,6 +83,7 @@ environment variable default description ``OPENPMD_ADIOS2_NUM_SUBSTREAMS`` ``0`` Number of files to be created, 0 indicates maximum number possible. ``OPENPMD_ADIOS2_ENGINE`` ``File`` `ADIOS2 engine `_ ``OPENPMD_ADIOS2_PRETEND_ENGINE`` *empty* Pretend that an (unknown) ADIOS2 engine is in fact another one (also see the ``adios2.pretend_engine`` :ref:`parameter `). +``OPENPMD_ADIOS2_ARRAY_ORDERING`` see below Array ordering passed to ADIOS2 (``adios2_default``, ``row_major`` or ``column_major``, see the ``adios2.dataset.array_ordering`` :ref:`parameter `). Defaults to ``adios2_default``. ``OPENPMD2_ADIOS2_USE_GROUP_TABLE`` ``0`` Use group table (see below) ``OPENPMD_ADIOS2_STATS_LEVEL`` see below Whether to generate statistics for variables in ADIOS2. (``1``: yes, ``0``: no) ``OPENPMD_ADIOS2_ASYNC_WRITE`` ``0`` ADIOS2 BP5 engine: 1 means setting "AsyncWrite" in ADIOS2 to "on". Flushes will go to the buffer by default (see ``preferred_flush_target``). diff --git a/docs/source/details/adios2.json b/docs/source/details/adios2.json index c817eb0d7a..17c9d26897 100644 --- a/docs/source/details/adios2.json +++ b/docs/source/details/adios2.json @@ -9,6 +9,7 @@ } }, "dataset": { + "array_ordering": "adios2_default", "operators": [ { "type": "blosc", diff --git a/docs/source/details/adios2.toml b/docs/source/details/adios2.toml index 20ef9e827f..c81cb52202 100644 --- a/docs/source/details/adios2.toml +++ b/docs/source/details/adios2.toml @@ -4,6 +4,10 @@ # however rank 0 should be the most common option here attribute_writing_ranks = 0 +[adios2.dataset] +# one of "adios2_default", "row_major" or "column_major" +array_ordering = "adios2_default" + [adios2.engine] type = "sst" preferred_flush_target = "disk" diff --git a/docs/source/details/backendconfig.rst b/docs/source/details/backendconfig.rst index 2f64366326..116579996e 100644 --- a/docs/source/details/backendconfig.rst +++ b/docs/source/details/backendconfig.rst @@ -218,6 +218,13 @@ Explanation of the single keys: Additionally, specifying ``"disk_override"``, ``"buffer_override"`` or ``"new_step_override"`` will take precedence over options specified without the ``_override`` suffix, allowing to invert the normal precedence order. This way, a data producing code can hardcode the preferred flush target per ``flush()`` call, but users can e.g. still entirely deactivate flushing to disk in the ``Series`` constructor by specifying ``preferred_flush_target = buffer_override``. This is useful when applying the asynchronous IO capabilities of the BP5 engine. +* ``adios2.dataset.array_ordering``: Forwards the array ordering to ``adios2::Variable::SetArrayLayout``. + Possible values are ``"adios2_default"`` (default, let ADIOS2 decide), ``"row_major"`` and ``"column_major"``. + This option is only effective with ADIOS2 2.10 or newer built with GPU support (CUDA or Kokkos), where it controls how ADIOS2 interprets buffers. + It does not change the row-major semantics of datasets in the openPMD-api itself. + In GPU-enabled ADIOS2 builds, specifying ``"row_major"`` prevents ADIOS2 from automatically switching GPU buffers to column-major ordering. + In other builds, configuring anything other than ``"adios2_default"`` emits a warning since it cannot take effect. + Can also be set via the environment variable ``OPENPMD_ADIOS2_ARRAY_ORDERING``; a JSON/TOML option takes precedence. * ``adios2.dataset.operators``: This key contains either a single ADIOS2 `operator `_ or a list of operators, used to enable compression or dataset transformations. Each operator is an object with two keys: diff --git a/docs/source/dev/buildoptions.rst b/docs/source/dev/buildoptions.rst index b2c483f34e..52ca9ddef2 100644 --- a/docs/source/dev/buildoptions.rst +++ b/docs/source/dev/buildoptions.rst @@ -124,5 +124,14 @@ CMake Option Values Description ``openPMD_BUILD_TESTING`` **ON**/OFF Build tests ``openPMD_BUILD_EXAMPLES`` **ON**/OFF Build examples ``openPMD_BUILD_CLI_TOOLS`` **ON**/OFF Build command-line tools -``openPMD_USE_CUDA_EXAMPLES`` ON/**OFF** Use CUDA in examples +``openPMD_USE_CUDA`` ON/AUTO/**OFF** Use CUDA in tests and examples =============================== =============== ================================================== + +CUDA is never used unless requested. The deprecated +``openPMD_USE_CUDA_EXAMPLES`` option is kept as an advanced alias for +``openPMD_USE_CUDA``. + +To run the GPU-aware tests, configure with ``-DopenPMD_USE_CUDA=ON`` and an +ADIOS2 build with GPU support (ADIOS2 2.10 or newer). The CUDA-specific tests +are tagged with ``[cuda]`` and can be run with +``./build/bin/SerialIOTests "[cuda]"``. diff --git a/include/openPMD/IO/ADIOS/ADIOS2IOHandler.hpp b/include/openPMD/IO/ADIOS/ADIOS2IOHandler.hpp index f3f4fe6b09..fb9f0aecc9 100644 --- a/include/openPMD/IO/ADIOS/ADIOS2IOHandler.hpp +++ b/include/openPMD/IO/ADIOS/ADIOS2IOHandler.hpp @@ -288,6 +288,15 @@ class ADIOS2IOHandlerImpl UseSpan m_useSpanBasedPutByDefault = UseSpan::Auto; + enum class ArrayOrdering : char + { + Adios2Default, + RowMajor, + ColumnMajor + }; + + ArrayOrdering m_arrayOrdering = ArrayOrdering::Adios2Default; + enum class ModifiableAttributes : char { Yes, @@ -356,8 +365,19 @@ class ADIOS2IOHandlerImpl // use m_config std::optional> getOperators(); + static ArrayOrdering parseArrayOrdering( + std::string const &value, std::vector const &configPath); + + std::optional getArrayOrdering(json::TracingJSON config); + + struct DatasetConfiguration + { + std::vector operators; + ArrayOrdering arrayOrdering; + }; + template - std::vector getDatasetOperators( + DatasetConfiguration getDatasetConfiguration( Parameter const &, Writable *, std::string const &varName); std::string fileSuffix(bool verbose = true) const; @@ -491,6 +511,40 @@ class ADIOS2IOHandlerImpl var.SetStepSelection({step_selection, 1}); } + template + void + applyArrayOrdering(adios2::Variable &var, ArrayOrdering arrayOrdering) + { +#if openPMD_HAS_ADIOS_2_10 && \ + (defined(ADIOS2_HAVE_GPU_SUPPORT) || defined(ADIOS2_HAVE_KOKKOS)) + switch (arrayOrdering) + { + case ArrayOrdering::Adios2Default: + // leave the layout up to ADIOS2 + break; + case ArrayOrdering::RowMajor: + var.SetArrayLayout(adios2::ArrayOrdering::RowMajor); + break; + case ArrayOrdering::ColumnMajor: + var.SetArrayLayout(adios2::ArrayOrdering::ColumnMajor); + break; + } +#else + (void)var; + if (arrayOrdering != ArrayOrdering::Adios2Default && + !printedWarningsAlready.arrayOrderingUnsupported) + { + std::cerr + << "[ADIOS2] Warning: The configured array ordering will be " + "ignored because this ADIOS2 build does not support it. " + "The 'adios2.dataset.array_ordering' option requires " + "ADIOS2 >= 2.10 built with GPU support." + << std::endl; + printedWarningsAlready.arrayOrderingUnsupported = true; + } +#endif + } + /* * Prepare a variable that already exists for an IO * operation, including: @@ -623,6 +677,7 @@ class ADIOS2IOHandlerImpl { bool noGroupBased = false; bool blosc2bp5 = false; + bool arrayOrderingUnsupported = false; } printedWarningsAlready; }; // ADIOS2IOHandlerImpl @@ -685,6 +740,7 @@ namespace detail std::optional stepSelection, std::vector const &operators, + ADIOS2IOHandlerImpl::ArrayOrdering arrayOrdering, detail::AdiosVariables const &); static constexpr char const *errorMsg = "ADIOS2: openDataset()"; @@ -695,6 +751,7 @@ namespace detail /** * @brief Define a Variable of type T within the passed IO. * + * @param impl The ADIOS2 backend implementation. * @param IO The adios2::IO object within which to define the * variable. The variable can later be retrieved from * the IO using the passed name. @@ -706,9 +763,11 @@ namespace detail * @param start As in adios2::IO::DefineVariable * @param count As in adios2::IO::DefineVariable * @param constantDims As in adios2::IO::DefineVariable + * @param arrayOrdering The array ordering to apply to the variable. */ template static void call( + ADIOS2IOHandlerImpl *impl, adios2::IO &IO, std::string const &name, std::vector const @@ -716,7 +775,9 @@ namespace detail adios2::Dims const &shape = adios2::Dims(), adios2::Dims const &start = adios2::Dims(), adios2::Dims const &count = adios2::Dims(), - bool const constantDims = false); + bool const constantDims = false, + ADIOS2IOHandlerImpl::ArrayOrdering arrayOrdering = + ADIOS2IOHandlerImpl::ArrayOrdering::Adios2Default); static constexpr char const *errorMsg = "ADIOS2: defineVariable()"; }; diff --git a/src/IO/ADIOS/ADIOS2IOHandler.cpp b/src/IO/ADIOS/ADIOS2IOHandler.cpp index f50b0d1a21..dfd5d98ebb 100644 --- a/src/IO/ADIOS/ADIOS2IOHandler.cpp +++ b/src/IO/ADIOS/ADIOS2IOHandler.cpp @@ -254,10 +254,24 @@ void ADIOS2IOHandlerImpl::init( groupTableViaEnv == 0 ? UseGroupTable::No : UseGroupTable::Yes; } + if (auto arrayOrderingViaEnv = + auxiliary::getEnvString("OPENPMD_ADIOS2_ARRAY_ORDERING", ""); + !arrayOrderingViaEnv.empty()) + { + m_arrayOrdering = parseArrayOrdering( + arrayOrderingViaEnv, {"adios2", "dataset", "array_ordering"}); + } + if (cfg.json().contains("adios2")) { m_config = cfg["adios2"]; + if (auto arrayOrdering = getArrayOrdering(m_config); + arrayOrdering.has_value()) + { + m_arrayOrdering = *arrayOrdering; + } + if (m_config.json().contains("use_group_table")) { m_useGroupTable = m_config["use_group_table"].json().get() @@ -428,12 +442,64 @@ ADIOS2IOHandlerImpl::getOperators() return getOperators(m_config); } +ADIOS2IOHandlerImpl::ArrayOrdering ADIOS2IOHandlerImpl::parseArrayOrdering( + std::string const &value, std::vector const &configPath) +{ + std::string ordering = value; + auxiliary::lowerCase(ordering); + if (ordering == "adios2_default") + { + return ArrayOrdering::Adios2Default; + } + else if (ordering == "row_major") + { + return ArrayOrdering::RowMajor; + } + else if (ordering == "column_major") + { + return ArrayOrdering::ColumnMajor; + } + else + { + throw error::BackendConfigSchema( + configPath, + "Must be one of 'adios2_default', 'row_major' or " + "'column_major', but was '" + + ordering + "'."); + } +} + +std::optional +ADIOS2IOHandlerImpl::getArrayOrdering(json::TracingJSON cfg) +{ + if (!cfg.json().contains("dataset")) + { + return std::nullopt; + } + auto datasetConfig = cfg["dataset"]; + if (!datasetConfig.json().contains("array_ordering")) + { + return std::nullopt; + } + auto arrayOrdering = datasetConfig["array_ordering"]; + auto maybeOrdering = json::asStringDynamic(arrayOrdering.json()); + if (!maybeOrdering.has_value()) + { + throw error::BackendConfigSchema( + {"adios2", "dataset", "array_ordering"}, + "Must be convertible to string type."); + } + return parseArrayOrdering( + *maybeOrdering, {"adios2", "dataset", "array_ordering"}); +} + template -auto ADIOS2IOHandlerImpl::getDatasetOperators( +auto ADIOS2IOHandlerImpl::getDatasetConfiguration( Parameter const ¶meters, Writable *writable, std::string const &varName) - -> std::vector + -> DatasetConfiguration { std::vector operators; + ArrayOrdering arrayOrdering = m_arrayOrdering; json::TracingJSON options = parameters.template compileJSONConfig( writable, *m_handler->jsonMatcher, "adios2"); @@ -441,9 +507,14 @@ auto ADIOS2IOHandlerImpl::getDatasetOperators( { json::TracingJSON datasetConfig(options["adios2"]); auto datasetOperators = getOperators(datasetConfig); - operators = datasetOperators ? std::move(datasetOperators.value()) : defaultOperators; + + if (auto datasetArrayOrdering = getArrayOrdering(datasetConfig); + datasetArrayOrdering.has_value()) + { + arrayOrdering = *datasetArrayOrdering; + } } else { @@ -454,7 +525,7 @@ auto ADIOS2IOHandlerImpl::getDatasetOperators( "adios2", "Warning: parts of the backend configuration for ADIOS2 dataset '" + varName + "' remain unused:\n"); - return operators; + return {std::move(operators), arrayOrdering}; } using AcceptedEndingsForEngine = std::map; @@ -918,8 +989,8 @@ void ADIOS2IOHandlerImpl::createDataset( filePos->gd = GroupOrDataset::DATASET; auto const varName = nameOfVariable(writable); - std::vector operators = - getDatasetOperators(parameters, writable, varName); + auto [operators, arrayOrdering] = + getDatasetConfiguration(parameters, writable, varName); // cast from openPMD::Extent to adios2::Dims adios2::Dims shape(parameters.extent.begin(), parameters.extent.end()); @@ -966,7 +1037,16 @@ For further details see #undef HAS_BP5_BLOSC2_BUG switchAdios2VariableType( - parameters.dtype, fileData.m_IO, varName, operators, shape); + parameters.dtype, + this, + fileData.m_IO, + varName, + operators, + shape, + adios2::Dims(), + adios2::Dims(), + false, + arrayOrdering); writable->written = true; m_dirty.emplace(writable->fileState); } @@ -1228,8 +1308,8 @@ void ADIOS2IOHandlerImpl::openDataset( * reading, so the dataset-specific configuration should still be explored * here. */ - std::vector operators = - getDatasetOperators(parameters, writable, varName); + auto [operators, arrayOrdering] = + getDatasetConfiguration(parameters, writable, varName); switchAdios2VariableType( *parameters.dtype, this, @@ -1238,6 +1318,7 @@ void ADIOS2IOHandlerImpl::openDataset( parameters, fileData.stepSelection(), operators, + arrayOrdering, fileData.variables()); writable->written = true; } @@ -2556,6 +2637,7 @@ namespace detail std::optional stepSelection, std::vector const &operators, + ADIOS2IOHandlerImpl::ArrayOrdering arrayOrdering, detail::AdiosVariables const &av) { auto &fileData = impl->getFileData( @@ -2576,6 +2658,8 @@ namespace detail var, varName, *stepSelection, file_steps, av); } + impl->applyArrayOrdering(var, arrayOrdering); + // Operators in reading needed e.g. for setting decompression threads for (auto const &operation : operators) { @@ -2597,6 +2681,7 @@ namespace detail template void VariableDefiner::call( + ADIOS2IOHandlerImpl *impl, adios2::IO &IO, std::string const &name, std::vector const @@ -2604,7 +2689,8 @@ namespace detail adios2::Dims const &shape, adios2::Dims const &start, adios2::Dims const &count, - bool const constantDims) + bool const constantDims, + ADIOS2IOHandlerImpl::ArrayOrdering arrayOrdering) { /* * Step/Variable-based iteration layout: @@ -2633,6 +2719,9 @@ namespace detail "[ADIOS2] Internal error: Could not create Variable '" + name + "'."); } + + impl->applyArrayOrdering(var, arrayOrdering); + for (auto const &compression : compressions) { if (compression.op) diff --git a/test/Files_SerialIO/adios2_array_ordering.cpp b/test/Files_SerialIO/adios2_array_ordering.cpp new file mode 100644 index 0000000000..b74356e253 --- /dev/null +++ b/test/Files_SerialIO/adios2_array_ordering.cpp @@ -0,0 +1,204 @@ +/* Copyright 2026 Franz Poeschel + * + * This file is part of openPMD-api. + * + * openPMD-api is free software: you can redistribute it and/or modify + * it under the terms of of either the GNU General Public License or + * the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * openPMD-api is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License and the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License + * and the GNU Lesser General Public License along with openPMD-api. + * If not, see . + */ +#include "openPMD/Error.hpp" +#include "openPMD/config.hpp" +#include "openPMD/openPMD.hpp" + +#include + +#include +#include +#include + +#if openPMD_HAVE_ADIOS2 + +#include + +#if defined(openPMD_TEST_CUDA) && defined(ADIOS2_HAVE_GPU_SUPPORT) && \ + ADIOS2_VERSION >= 21000 +#define openPMD_TEST_CUDA_ARRAY_ORDERING 1 +#include +#else +#define openPMD_TEST_CUDA_ARRAY_ORDERING 0 +#endif + +using namespace openPMD; + +namespace +{ +std::vector testData{0, 1, 2, 3, 4, 5}; +Extent const testExtent{2, 3}; +} // namespace + +TEST_CASE("serial_adios2_array_ordering", "[serial][adios2]") +{ + auto writeAndRead = [](std::string const &filename, + std::string const &config, + bool twoDimensional, + std::string const &datasetOptions = "") { + Extent extent = + twoDimensional ? testExtent : Extent{static_cast(6)}; + Offset offset = + twoDimensional ? Offset{0, 0} : Offset{static_cast(0)}; + + { + Series series(filename, Access::CREATE, config); + auto E_x = series.iterations[0].meshes["E"]["x"]; + Dataset dataset(Datatype::INT, extent); + dataset.options = datasetOptions; + E_x.resetDataset(dataset); + if (twoDimensional) + { + std::vector firstRow( + testData.begin(), testData.begin() + 3); + std::vector secondRow( + testData.begin() + 3, testData.end()); + E_x.storeChunk(firstRow, {0, 0}, {1, 3}); + series.flush(); + E_x.storeChunk(secondRow, {1, 0}, {1, 3}); + series.flush(); + } + else + { + E_x.storeChunk(testData, offset, extent); + series.flush(); + } + } + { + Series series(filename, Access::READ_ONLY, config); + auto E_x = series.iterations[0].meshes["E"]["x"]; + REQUIRE(E_x.getExtent() == extent); + auto chunk = E_x.loadChunk(offset, extent); + series.flush(); + for (size_t i = 0; i < testData.size(); ++i) + { + REQUIRE(chunk.get()[i] == testData[i]); + } + } + }; + + writeAndRead( + "../samples/array_ordering.json_row_major.bp", + R"({"adios2":{"dataset":{"array_ordering":"row_major"}}})", + true); + writeAndRead( + "../samples/array_ordering.json_adios2_default.bp", + R"({"adios2":{"dataset":{"array_ordering":"adios2_default"}}})", + true); + writeAndRead( + "../samples/array_ordering.json_column_major.bp", + R"({"adios2":{"dataset":{"array_ordering":"column_major"}}})", + false); + + writeAndRead( + "../samples/array_ordering.dataset_override.bp", + R"({"adios2":{"dataset":{"array_ordering":"row_major"}}})", + false, + R"({"adios2":{"dataset":{"array_ordering":"column_major"}}})"); + + REQUIRE_THROWS_AS( + Series( + "../samples/array_ordering.invalid.bp", + Access::CREATE, + R"({"adios2":{"dataset":{"array_ordering":"invalid"}}})"), + error::BackendConfigSchema); + +#ifdef __unix__ + setenv("OPENPMD_ADIOS2_ARRAY_ORDERING", "row_major", 1); + writeAndRead("../samples/array_ordering.env.bp", "{}", true); + unsetenv("OPENPMD_ADIOS2_ARRAY_ORDERING"); +#endif +} + +#if openPMD_TEST_CUDA_ARRAY_ORDERING +namespace +{ +void readAndCheck(std::string const &filename) +{ + Series series(filename, Access::READ_ONLY); + auto E_x = series.iterations[0].meshes["E"]["x"]; + REQUIRE(E_x.getExtent() == testExtent); + auto chunk = E_x.loadChunk({0, 0}, testExtent); + series.flush(); + for (size_t i = 0; i < testData.size(); ++i) + { + REQUIRE(chunk.get()[i] == testData[i]); + } +} +} // namespace + +TEST_CASE("serial_adios2_array_ordering_gpu", "[serial][adios2][cuda]") +{ + int deviceCount = 0; + cudaError_t error = cudaGetDeviceCount(&deviceCount); + if (error != cudaSuccess || deviceCount == 0) + { + SKIP( + "No usable CUDA device: " + std::string(cudaGetErrorString(error))); + } + + auto write = [](std::string const &filename, + std::string const &config, + std::string const &datasetOptions) { + int *deviceBuffer = nullptr; + REQUIRE( + cudaMalloc(&deviceBuffer, testData.size() * sizeof(int)) == + cudaSuccess); + REQUIRE( + cudaMemcpy( + deviceBuffer, + testData.data(), + testData.size() * sizeof(int), + cudaMemcpyHostToDevice) == cudaSuccess); + { + Series series(filename, Access::CREATE, config); + auto E_x = series.iterations[0].meshes["E"]["x"]; + Dataset dataset(Datatype::INT, testExtent); + dataset.options = datasetOptions; + E_x.resetDataset(dataset); + E_x.storeChunkRaw(deviceBuffer, {0, 0}, testExtent); + series.flush(); + } + REQUIRE(cudaFree(deviceBuffer) == cudaSuccess); + }; + + write( + "../samples/array_ordering.gpu_row_major.bp", + R"({"adios2":{"dataset":{"array_ordering":"row_major"}}})", + ""); + readAndCheck("../samples/array_ordering.gpu_row_major.bp"); + + write( + "../samples/array_ordering.gpu_dataset_override.bp", + R"({"adios2":{"dataset":{"array_ordering":"adios2_default"}}})", + R"({"adios2":{"dataset":{"array_ordering":"row_major"}}})"); + readAndCheck("../samples/array_ordering.gpu_dataset_override.bp"); + +#ifdef __unix__ + setenv("OPENPMD_ADIOS2_ARRAY_ORDERING", "row_major", 1); + write("../samples/array_ordering.gpu_env.bp", "{}", ""); + unsetenv("OPENPMD_ADIOS2_ARRAY_ORDERING"); + readAndCheck("../samples/array_ordering.gpu_env.bp"); +#endif +} +#endif // openPMD_TEST_CUDA_ARRAY_ORDERING + +#endif // openPMD_HAVE_ADIOS2