diff --git a/src/atlas4py/CMakeLists.txt b/src/atlas4py/CMakeLists.txt index c0fa4ac..456ac35 100644 --- a/src/atlas4py/CMakeLists.txt +++ b/src/atlas4py/CMakeLists.txt @@ -84,9 +84,12 @@ endif() nanobind_add_module(_atlas4py _atlas4py.cpp _atlas4py_Config.cpp + mpi/_mpi.cpp ) target_link_libraries(_atlas4py PUBLIC atlas) +target_include_directories(_atlas4py PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) target_compile_definitions(_atlas4py PRIVATE ATLAS4PY_VERSION_STRING=${PROJECT_VERSION_FULL}) +target_compile_definitions(_atlas4py PRIVATE ATLAS4PY_ATLAS_VERSION_INT=${ATLAS4PY_ATLAS_VERSION_INT}) ### Installation diff --git a/src/atlas4py/_atlas4py.cpp b/src/atlas4py/_atlas4py.cpp index 8f5670b..126fe30 100644 --- a/src/atlas4py/_atlas4py.cpp +++ b/src/atlas4py/_atlas4py.cpp @@ -41,6 +41,7 @@ namespace pluto { #include "eckit/config/Configuration.h" #include "_atlas4py_Config.hpp" +#include "mpi/_mpi.hpp" namespace nb = ::nanobind; @@ -224,6 +225,7 @@ NB_MODULE( _atlas4py, m ) { .def("_finalise", atlas::finalise); m.attr("__version__") = STRINGIFY(ATLAS4PY_VERSION_STRING); + atlas4py::bind_submodule_mpi( m ); atlas4py::bind_Config( m ); nb::class_( m, "PointLonLat" ) diff --git a/src/atlas4py/_atlas4py_common.hpp b/src/atlas4py/_atlas4py_common.hpp new file mode 100644 index 0000000..8511446 --- /dev/null +++ b/src/atlas4py/_atlas4py_common.hpp @@ -0,0 +1,4 @@ +#pragma once + +#define ATLAS4PY_ATLAS_VERSION_AT_LEAST(x, y, z) (ATLAS4PY_ATLAS_VERSION_INT >= x * 10000 + y * 100 + z) + diff --git a/src/atlas4py/cmake/atlas4py_add_atlas.cmake b/src/atlas4py/cmake/atlas4py_add_atlas.cmake index 0fd2bf8..c8f4030 100644 --- a/src/atlas4py/cmake/atlas4py_add_atlas.cmake +++ b/src/atlas4py/cmake/atlas4py_add_atlas.cmake @@ -67,5 +67,9 @@ macro(atlas4py_add_atlas) set(ATLAS_ENABLE_ECKIT_CMD OFF) FetchContent_MakeAvailable(eckit atlas) + find_package(atlas CONFIG REQUIRED) endif() + + include(cmake/atlas4py_parse_version.cmake) + atlas4py_parse_version(${atlas_VERSION_STR} PREFIX ATLAS4PY_ATLAS) endmacro() diff --git a/src/atlas4py/cmake/atlas4py_parse_version.cmake b/src/atlas4py/cmake/atlas4py_parse_version.cmake new file mode 100644 index 0000000..695444b --- /dev/null +++ b/src/atlas4py/cmake/atlas4py_parse_version.cmake @@ -0,0 +1,99 @@ +# This file defines a function to parse version strings and export version components as CMake variables. + +############################################################################## +#.rst: +# +# atlas4py_parse_version +# ===================== +# +# Parse version string of the form "[.[.[.]]][]" :: +# +# atlas4py_parse_version( [ PREFIX ] ) +# +# Options +# ------- +# +# PREFIX : optional +# string to be prefixed to all defined variables. If not given, +# the value "_" will be used. +# +# Notes +# ----- +# +# Following variables if possible: +# +# _VERSION_STR = [.[.[.]]][] +# _VERSION = [.[.[.]]] +# _VERSION_MAJOR = +# _VERSION_MINOR = +# _VERSION_PATCH = +# _VERSION_TWEAK = +# _VERSION_SUFFIX = +# _VERSION_INT = * 10000 + * 100 + +# +# Note, this is taken from ecbuild_parse_version.cmake, with addition of _VERSION_INT + +function( atlas4py_parse_version version_str ) + set( options ) + set( single_value_args PREFIX ) + set( multi_value_args ) + + cmake_parse_arguments( _PAR "${options}" "${single_value_args}" "${multi_value_args}" ${ARGN} ) + + if( NOT _PAR_PREFIX ) + set( prefix "_" ) + else() + set( prefix ${_PAR_PREFIX} ) + endif() + + ## Parse version_str + set( ${prefix}_VERSION_STR "${version_str}" ) + string( REGEX REPLACE "^((([0-9]+)\\.)+([0-9]+)).*" "\\1" ${prefix}_VERSION "${version_str}" ) + string( LENGTH "${${prefix}_VERSION}" ver_len ) + string( SUBSTRING "${version_str}" ${ver_len} -1 ${prefix}_VERSION_SUFFIX ) + string( REPLACE "." " " _version_list ${${prefix}_VERSION} ) # dots to spaces + separate_arguments( _version_list ) + list (LENGTH _version_list _len) + if( ${_len} GREATER 0 ) + list( GET _version_list 0 ${prefix}_VERSION_MAJOR ) + endif() + if( ${_len} GREATER 1 ) + list( GET _version_list 1 ${prefix}_VERSION_MINOR ) + endif() + if( ${_len} GREATER 2 ) + list( GET _version_list 2 ${prefix}_VERSION_PATCH ) + endif() + if( ${_len} GREATER 3 ) + list( GET _version_list 3 ${prefix}_VERSION_TWEAK ) + endif() + + if( NOT DEFINED ${prefix}_VERSION_MINOR ) + set( ${prefix}_VERSION_MINOR 0 ) + endif() + if( NOT DEFINED ${prefix}_VERSION_PATCH ) + set( ${prefix}_VERSION_PATCH 0 ) + endif() + if( NOT DEFINED ${prefix}_VERSION_TWEAK ) + set( ${prefix}_VERSION_TWEAK 0 ) + endif() + + math(EXPR ${prefix}_VERSION_INT "${${prefix}_VERSION_MAJOR} * 10000 + ${${prefix}_VERSION_MINOR} * 100 + ${${prefix}_VERSION_PATCH}") + + ## Export variables to parent scope + list( APPEND export_variables_parent_scope + ${prefix}_VERSION_STR + ${prefix}_VERSION + ${prefix}_VERSION_MAJOR + ${prefix}_VERSION_MINOR + ${prefix}_VERSION_PATCH + ${prefix}_VERSION_TWEAK + ${prefix}_VERSION_SUFFIX + ${prefix}_VERSION_INT + ) + foreach( _var ${export_variables_parent_scope} ) + if( DEFINED ${_var} ) + set( ${_var} ${${_var}} PARENT_SCOPE ) + endif() + endforeach() + +endfunction() diff --git a/src/atlas4py/mpi/_mpi.cpp b/src/atlas4py/mpi/_mpi.cpp new file mode 100644 index 0000000..fe102d1 --- /dev/null +++ b/src/atlas4py/mpi/_mpi.cpp @@ -0,0 +1,274 @@ + +#include "_mpi.hpp" + +#include +#include +#include +#include + +#include "atlas/library/config.h" +#include "atlas/parallel/mpi/mpi.h" +#include "eckit/mpi/Comm.h" +#include "_atlas4py_common.hpp" + +namespace atlas4py { +namespace mpi { +namespace { + +const eckit::mpi::Comm& comm_world() { + static const eckit::mpi::Comm& world = atlas::mpi::comm("world"); + return world; +} +const eckit::mpi::Comm& comm_self() { + static const eckit::mpi::Comm& self = atlas::mpi::comm("self"); + return self; +} +int comm_world_int() { + static int world = comm_world().communicator(); + return world; +} +int comm_self_int() { + static int self = comm_self().communicator(); + return self; +} + +std::string comm_name_from_int( int comm_as_int ) { + if ( comm_as_int == comm_world_int() ) { + return "world"; + } + if ( comm_as_int == comm_self_int() ) { + return "self"; + } + std::ostringstream s; + s << "int." << comm_as_int; + return s.str(); +} + +enum class RegisterIfNotFound { + yes, + no +}; +const eckit::mpi::Comm& lookup_comm_in_eckit( int comm_as_int, RegisterIfNotFound register_if_not_found ) { + if ( comm_as_int == comm_world_int() ) { + return comm_world(); + } + else if ( comm_as_int == comm_self_int() ) { + return comm_self(); + } + else { + for( std::string name : eckit::mpi::listComms() ) { + const auto& comm = atlas::mpi::comm(name); + if ( comm.communicator() == comm_as_int ) { + return comm; + } + } + } + if ( register_if_not_found == RegisterIfNotFound::yes ) { + std::string name = comm_name_from_int(comm_as_int); + eckit::mpi::addComm( name.c_str(), comm_as_int ); + return atlas::mpi::comm( name ); + } + throw std::out_of_range( "comm with int value " + std::to_string(comm_as_int) + " not found in eckit and register_if_not_found is false" ); +} + +int comm_to_int( const nb::object& comm ) { + if ( nb::isinstance( comm ) ) { + return nb::cast(comm); + } + else if (nb::hasattr(comm, "toint")) { // This is supporting mpi4py.MPI.Comm + return nb::cast(comm.attr("toint")()); + } + else if (nb::hasattr(comm, "to_int")) { // This is supporting atlas4py.mpi.Comm + return nb::cast(comm.attr("to_int")()); + } + throw std::out_of_range( "unsupported type for comm" ); +} + +} + +// -------------------------------------------------------------------------------------------------- +// Standalone functions +// -------------------------------------------------------------------------------------------------- + +bool has_comm( const std::string& name ) { + return eckit::mpi::hasComm( name.c_str() ); +} + +Comm register_comm( const std::string& name, int comm ) { + eckit::mpi::addComm( name.c_str(), comm ); + return Comm(name); +} + +#if ATLAS_ECKIT_VERSION_AT_LEAST(2,0,0) +void unregister_comm( const std::string& name ) { + eckit::mpi::unregisterComm( name.c_str() ); +} +#endif + +void delete_comm( const std::string& name ) { + eckit::mpi::deleteComm( name.c_str() ); // Note, this calls MPI_Comm_free! +} + +void set_default_comm( const std::string& name) { + eckit::mpi::setCommDefault( name.c_str() ); +} + +// -------------------------------------------------------------------------------------------------- +// Class Comm +// -------------------------------------------------------------------------------------------------- + +Comm::Comm() : comm_( atlas::mpi::comm() ) {} +Comm::Comm( const std::string& name ) : comm_( atlas::mpi::comm(name) ) {} +Comm::Comm( const eckit::mpi::Comm& comm ) : comm_( comm ) {} +Comm::Comm( int comm ) : comm_( lookup_comm_in_eckit(comm, RegisterIfNotFound::yes) ) {} +Comm::Comm( const nb::object& comm ) : Comm( comm_to_int(comm) ) {} + +int Comm::size() const { + if (size_ < 0) { + size_ = comm_.size(); + } + return size_; +} +int Comm::rank() const { + if (rank_ < 0) { + rank_ = comm_.rank(); + } + return rank_; +} +void Comm::barrier() const { comm_.barrier(); } +void Comm::abort(int errorcode) const { comm_.abort(errorcode); } +const std::string& Comm::name() const { + if (name_.empty()) { + name_ = comm_.name(); + } + return name_; +} +int Comm::to_int() const { + if (comm_int_ == std::numeric_limits::min()) { + comm_int_ = comm_.communicator(); + } + return comm_int_; +} + +const Comm& Comm::WORLD() { + static const Comm world = mpi::Comm( "world" ); + return world; +} +const Comm& Comm::SELF() { + static const Comm self = mpi::Comm( "self" ); + return self; +} + +Comm Comm::split(int color, const std::string& name) const { + return Comm( comm_.split(color, name.c_str()) ); +} + +// -------------------------------------------------------------------------------------------------- +// Class Scope +// -------------------------------------------------------------------------------------------------- + +class Scope { + public: + Scope( const std::string& name ) { + push(name); + } + Scope( const mpi::Comm& comm ) : Scope(comm.name()) {} + Scope( const int comm ) : Scope(mpi::Comm(comm).name()) {} + Scope( const nb::object& comm ) : Scope(mpi::Comm(comm).name()) {} + ~Scope() { deactivate(); } + + void deactivate() { + if (is_active_) { + pop(); + is_active_ = false; + } + } + + static void push(const std::string& name) { + #if ATLAS4PY_ATLAS_VERSION_AT_LEAST(0,46,0) + atlas::mpi::scope::push(name); + #else + atlas::mpi::push(name); + #endif + } + static void pop() { + #if ATLAS4PY_ATLAS_VERSION_AT_LEAST(0,46,0) + atlas::mpi::scope::pop(); + #else + atlas::mpi::pop(); + #endif + } + bool is_active_ = true; +}; + +} // namespace mpi + +// -------------------------------------------------------------------------------------------------- +// Python module +// -------------------------------------------------------------------------------------------------- + +namespace nb = ::nanobind; +void bind_submodule_mpi(nb::module_ &m) { + using namespace nb::literals; + nb::module_ m_mpi = m.def_submodule("mpi", "mpi python binding."); + + + m_mpi.def("set_default_comm", [](const std::string& name) { mpi::set_default_comm(name); }, "Set the default MPI communicator by name.", "name"_a); + m_mpi.def("has_comm", &mpi::has_comm, "Check if an MPI communicator with the given name exists.", "name"_a ); + m_mpi.def("list_comms", &eckit::mpi::listComms, "List all registered MPI communicators."); + m_mpi.def("register_comm", [](const std::string& name, int comm) { return mpi::register_comm(name, comm); }, "Register an MPI communicator by name and integer handle.", "name"_a, "comm"_a ); + m_mpi.def("register_comm", [](const std::string& name, nb::object comm) { return mpi::register_comm(name, mpi::comm_to_int(comm)); }, "Register an MPI communicator by name and object.", "name"_a, "comm"_a ); +#if ATLAS_ECKIT_VERSION_AT_LEAST(2,0,0) + m_mpi.def("unregister_comm", [](const std::string& name) { mpi::unregister_comm(name); }, "Unregister an MPI communicator by name.", "name"_a ); + m_mpi.def("unregister_comm", [](mpi::Comm& comm) { mpi::unregister_comm(comm.name()); }, "Unregister an MPI communicator by Comm object.", "comm"_a ); +#endif + m_mpi.def("delete_comm", &mpi::delete_comm, "Delete the MPI communicator with the given name.", "name"_a ); + m_mpi.def("size", []() { return atlas::mpi::size(); }, "Get the size of the default MPI communicator." ); + m_mpi.def("rank", []() { return atlas::mpi::rank(); }, "Get the rank of the default MPI communicator." ); + m_mpi.def("barrier", []() { atlas::mpi::comm().barrier(); }, "Synchronize all processes in the default MPI communicator." ); + m_mpi.def("abort", [](int errorcode = -1) { atlas::mpi::comm().abort(errorcode); }, "Abort all processes in the default MPI communicator with the given error code.", "errorcode"_a = -1 ); + m_mpi.def("finalize", []() { atlas::mpi::finalize(); }, "Finalize the MPI environment." ); + m_mpi.def("push", [](const std::string& name) { mpi::Scope::push(name); }, "Push a new MPI scope by name.", "name"_a ); + m_mpi.def("pop", []() { mpi::Scope::pop(); }, "Pop the current MPI scope." ); + + nb::class_( m_mpi, "Comm", "Class representing an MPI communicator." ) + .def( nb::init<>(), "Create a new default MPI communicator." ) + .def( nb::init(), "Create a new MPI communicator from an integer.", "comm"_a ) + .def( nb::init(), "Create a new MPI communicator from a name.", "name"_a ) + .def( nb::init(), "Create a new MPI communicator from a Python object representing a communicator.", "comm"_a ) + .def_prop_ro("size", &mpi::Comm::size, "The size of the MPI communicator." ) + .def_prop_ro("rank", &mpi::Comm::rank, "The rank of the MPI communicator." ) + .def_prop_ro("name", &mpi::Comm::name, "The name of the MPI communicator." ) + .def("barrier", &mpi::Comm::barrier, "Synchronize all processes in the communicator." ) + .def("abort", &mpi::Comm::abort, "Abort all processes in the communicator with the given error code.", "errorcode"_a = -1 ) + .def("split", &mpi::Comm::split, "Split the communicator into multiple sub-communicators based on the color.", "color"_a, "name"_a ) + .def("to_int", &mpi::Comm::to_int, "Return the integer representation of the MPI communicator." ) + .def("__int__", &mpi::Comm::to_int, "Automatic conversion to the integer representation of the MPI communicator." ) + .def("__eq__", [](const mpi::Comm &self, const mpi::Comm &other) { + return self.to_int() == other.to_int(); + }, "Check if two MPI communicators are equal based on their integer representation." ) + .def("__repr__", []( const mpi::Comm& comm ) { + return "atlas4py.mpi.Comm(" + std::to_string( comm.to_int() ) + ")"; + }, "Return a string representation of the MPI communicator." ) + .def("__str__", []( const mpi::Comm& comm ) { + return "atlas4py.mpi.Comm(name=" + comm.name() + ", size=" + std::to_string( comm.size() ) + + ", rank=" + std::to_string( comm.rank() ) + ", int=" + std::to_string( comm.to_int() ) + ")"; + }, "Return a human-readable string representation of the MPI communicator." ) + .def_prop_ro_static("WORLD", [](nb::object cls) { return mpi::Comm::WORLD(); }, "Return the MPI_COMM_WORLD communicator." ) + .def_prop_ro_static("SELF", [](nb::object cls) { return mpi::Comm::SELF(); }, "Return the MPI_COMM_SELF communicator." ); + + nb::class_( m_mpi, "Scope", "Class representing an MPI scope." ) + .def( nb::init(), "Create a new MPI scope from a name.", "name"_a ) + .def( nb::init(), "Create a new MPI scope from an existing MPI communicator.", "comm"_a ) + .def( nb::init(), "Create a new MPI scope from an integer representing a communicator.", "comm"_a ) + .def( nb::init(), "Create a new MPI scope from a Python object representing a communicator.", "comm"_a ) + .def( "__enter__", []( mpi::Scope& self ) { return &self; }, "Enter the MPI scope." ) + .def( "__exit__", []( mpi::Scope& self, nb::object exc_type, nb::object exc_value, nb::object traceback ) { self.deactivate(); }, "Exit the MPI scope.", "exc_type"_a = nb::none(), "exc_value"_a = nb::none(), "traceback"_a = nb::none() ) + .def( "__repr__", []( const mpi::Scope& scope ) { + return "atlas4py.mpi.Scope(name=" + atlas::mpi::comm().name() + ")"; + }, "Return a string representation of the MPI scope." ); + +} + + +} // namespace atlas4py diff --git a/src/atlas4py/mpi/_mpi.hpp b/src/atlas4py/mpi/_mpi.hpp new file mode 100644 index 0000000..78fc8f5 --- /dev/null +++ b/src/atlas4py/mpi/_mpi.hpp @@ -0,0 +1,61 @@ +#pragma once + +/* +Module atlas4py.mpi + +Interoperability with mpi4py or other MPI libraries is possible via the underlying MPI integer handle +```python +import atlas4py +from mpi4py import MPI + +mpi4py_comm = MPI.Comm.fromint( int(atlas4py.mpi.comm()) ) +atlas4py_comm = atlas4py.mpi.comm( mpi4py_comm.toint() ) + +# You can also register the communicator by name +atlas4py.mpi.register_comm( "my_comm", mpi4py_comm.toint() ) + +# and retrieve it later +atlas4py_my_comm = atlas4py.mpi.comm( "my_comm" ) +``` +*/ + +#include + +#include + +namespace eckit::mpi { +class Comm; +} +namespace atlas4py { +namespace nb = ::nanobind; +void bind_submodule_mpi(nb::module_ &m); + +namespace mpi { +class Comm { +public: + Comm(); + Comm( const std::string& name ); + Comm( const eckit::mpi::Comm& comm ); + Comm( const nb::object& comm ); + explicit Comm( int comm ); + int size() const; + int rank() const; + void barrier() const; + void abort(int errorcode = -1) const; + Comm split(int color, const std::string& name) const; + const std::string& name() const; + int to_int() const; + static const Comm& WORLD(); + static const Comm& SELF(); + +private: + const eckit::mpi::Comm& comm_; + mutable int size_ = -1; + mutable int rank_ = -1; + mutable int comm_int_ = std::numeric_limits::min(); + mutable std::string name_; +}; + +} // namespace mpi + +} // namespace atlas4py diff --git a/tests/test_bindings.py b/tests/test_bindings.py index 1d818bb..ae6f487 100644 --- a/tests/test_bindings.py +++ b/tests/test_bindings.py @@ -1,6 +1,7 @@ import atlas4py import numpy as np import pytest +import importlib.util @@ -412,3 +413,146 @@ def test_config_from_file_format_is_guard(tmp_path): atlas4py.Config.from_file(test_config_yaml, format="toml") assert "does not select a parser or validate the file contents" in atlas4py.Config.from_file.__doc__ + +class Mock_mpi4py_MPI_Comm: + def __init__(self, handle=0): + self.handle = handle + def toint(self): + return self.handle + + +def test_mpi_comm(): + assert atlas4py.mpi.Comm().name == "world" # the default comm is 'world' + assert atlas4py.mpi.Comm("world").name == "world" + assert atlas4py.mpi.Comm("self").name == "self" + atlas4py.mpi.push("self") # the new default comm is now 'self' + assert atlas4py.mpi.Comm().name == "self" + assert atlas4py.mpi.size() == 1 + assert atlas4py.mpi.rank() == 0 + atlas4py.mpi.pop() # the default comm is back to 'world' + assert atlas4py.mpi.Comm().name == "world" + assert atlas4py.mpi.Comm("self").size == 1 + assert atlas4py.mpi.Comm("self").rank == 0 + assert atlas4py.mpi.Comm("world") == atlas4py.mpi.Comm.WORLD + assert atlas4py.mpi.Comm("self") == atlas4py.mpi.Comm.SELF + +def test_mpi_comm_to_from_int(): + world_int = int(atlas4py.mpi.Comm("world")) + comm_from_int = atlas4py.mpi.Comm(world_int) + assert isinstance(comm_from_int, atlas4py.mpi.Comm) + assert comm_from_int.name == "world" + assert comm_from_int == atlas4py.mpi.Comm("world") + assert atlas4py.mpi.has_comm("world") + + # This can be used to create a mpi4py.MPI.Comm from an + # atlas4py.mpi.Comm and vice versa + if importlib.util.find_spec("mpi4py") is not None: + import mpi4py.MPI + mpi4py_comm = mpi4py.MPI.Comm.fromint(int(comm_from_int)) + atlas4py_comm = atlas4py.mpi.Comm(mpi4py_comm.toint()) + assert atlas4py_comm.name == "world" + # Also works directly with the mpi4py comm object, + # as long as it has a toint() method that returns the correct int value for the comm + atlas4py_comm = atlas4py.mpi.Comm(mpi4py_comm) + assert atlas4py_comm.name == "world" + +def test_mpi_repr_and_str(): + WORLD = atlas4py.mpi.Comm.WORLD + assert repr(atlas4py.mpi.Comm("world")) == "atlas4py.mpi.Comm(" + str(int(WORLD)) + ")" + assert eval(repr(atlas4py.mpi.Comm("world"))) == WORLD + assert str(atlas4py.mpi.Comm("world")) == "atlas4py.mpi.Comm(name=world, size=" + str(WORLD.size) + ", rank=" + str(WORLD.rank) + ", int=" + str(int(WORLD)) + ")" + + +def test_mpi_comm_registration(): + my_comm = atlas4py.mpi.Comm("self") # or from another source, e.g. mpi4py + atlas4py.mpi.register_comm("my_comm", my_comm) + assert atlas4py.mpi.has_comm("my_comm") == True + + # to register comm coming from mpi4py + atlas4py.mpi.register_comm("my_comm_from_int", int(my_comm)) + assert atlas4py.mpi.has_comm("my_comm_from_int") == True + + # using comms, e.g. by mpi4py.MPI.Comm + mock_mpi4py_comm_6 = Mock_mpi4py_MPI_Comm(6) + atlas4py.mpi.register_comm("my_comm_from_mpi4py", mock_mpi4py_comm_6) + assert atlas4py.mpi.has_comm("my_comm_from_mpi4py") == True + + # change the default comm to the newly registered one + atlas4py.mpi.set_default_comm("my_comm") + assert atlas4py.mpi.Comm().name == "my_comm" + + atlas4py.mpi.set_default_comm("world") + assert atlas4py.mpi.Comm().name == "world" + + # When eckit::mpi::unregisterComm is available (from eckit 2.0.0) + if hasattr(atlas4py.mpi, "unregister_comm"): + atlas4py.mpi.unregister_comm("my_comm") + assert atlas4py.mpi.has_comm("my_comm") == False + +def test_mpi_scope(): + mpi = atlas4py.mpi + comm_scope_1 = mpi.register_comm("scope 1", atlas4py.mpi.Comm.WORLD) + comm_scope_2 = mpi.register_comm("scope 2", atlas4py.mpi.Comm.SELF) + + assert mpi.Comm().name == "world" + + # using named comms + with mpi.Scope("scope 1"): + assert mpi.Comm().name == "scope 1" + with mpi.Scope("scope 2"): + assert mpi.Comm().name == "scope 2" + assert mpi.Comm().name == "scope 1" + assert mpi.Comm().name == "world" + + # using comms returned by register_comm + with mpi.Scope(comm_scope_1): + assert mpi.Comm().name == "scope 1" + with mpi.Scope(comm_scope_2): + assert mpi.Comm().name == "scope 2" + assert mpi.Comm().name == "scope 1" + assert mpi.Comm().name == "world" + + # using comms, e.g. by mpi4py.MPI.Comm + mock_mpi4py_comm_9999 = Mock_mpi4py_MPI_Comm(9999) + + with mpi.Scope(mock_mpi4py_comm_9999): + assert "int.9999" in mpi.list_comms() + + assert mpi.Comm().name == "world" + + # When eckit::mpi::unregisterComm is available (from eckit 2.0.0) + if hasattr(atlas4py.mpi, "unregister_comm"): + atlas4py.mpi.unregister_comm("scope 1") + atlas4py.mpi.unregister_comm("scope 2") + assert atlas4py.mpi.has_comm("scope 1") == False + assert atlas4py.mpi.has_comm("scope 2") == False + +def test_scope_repr_and_str(): + scope = atlas4py.mpi.Scope("world") + assert repr(scope) == "atlas4py.mpi.Scope(name=world)" + assert str(scope) == "atlas4py.mpi.Scope(name=world)" + +def test_mpi_barrier(): + atlas4py.mpi.barrier() # uses default comm + atlas4py.mpi.Comm("world").barrier() + + +def test_mpi_comm_split(): + """Test splitting the world communicator and using the split comm.""" + mpi = atlas4py.mpi + world = mpi.Comm("world") + color = world.rank % 2 + split_comm = world.split(color, "split_comm") + mpi.set_default_comm("split_comm") + # The split_comm should have a subset of ranks + assert split_comm.name == "split_comm" + assert split_comm.size <= world.size + # Each rank in split_comm should have a unique rank + assert 0 <= split_comm.rank < split_comm.size + # The split_comm should be accessible by name + split_comm_by_name = mpi.Comm("split_comm") + assert split_comm_by_name.name == "split_comm" + # Clean up: set default comm back to world if needed + mpi.set_default_comm("world") + mpi.delete_comm("split_comm") + assert not mpi.has_comm("split_comm")