From dd4e6cff421afb43110a489254948854305bf5d3 Mon Sep 17 00:00:00 2001 From: Willem Deconinck Date: Tue, 3 Feb 2026 18:35:03 +0100 Subject: [PATCH 1/5] Add submodule mpi --- src/atlas4py/CMakeLists.txt | 3 + src/atlas4py/_atlas4py.cpp | 2 + src/atlas4py/_atlas4py_common.hpp | 4 + src/atlas4py/cmake/atlas4py_add_atlas.cmake | 59 ++++ .../cmake/atlas4py_parse_version.cmake | 89 ++++++ src/atlas4py/mpi/_mpi.cpp | 283 ++++++++++++++++++ src/atlas4py/mpi/_mpi.hpp | 60 ++++ tests/test_bindings.py | 134 +++++++++ 8 files changed, 634 insertions(+) create mode 100644 src/atlas4py/_atlas4py_common.hpp create mode 100644 src/atlas4py/cmake/atlas4py_parse_version.cmake create mode 100644 src/atlas4py/mpi/_mpi.cpp create mode 100644 src/atlas4py/mpi/_mpi.hpp 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..d7330b2 100644 --- a/src/atlas4py/cmake/atlas4py_add_atlas.cmake +++ b/src/atlas4py/cmake/atlas4py_add_atlas.cmake @@ -4,6 +4,61 @@ # If it cannot find it, it uses FetchContent to download and build atlas and its dependencies (eckit and ecbuild) from source. # The macro is called in the main CMakeLists.txt file of the project. +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() + + 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() + macro(atlas4py_add_atlas) if (NOT build_atlas) if (DEFINED ENV{ATLAS_INSTALL_DIR}) @@ -67,5 +122,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..b18adc5 --- /dev/null +++ b/src/atlas4py/cmake/atlas4py_parse_version.cmake @@ -0,0 +1,89 @@ +# 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() + + 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..5a86c35 --- /dev/null +++ b/src/atlas4py/mpi/_mpi.cpp @@ -0,0 +1,283 @@ + +#include "_mpi.hpp" + +#include +#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" ); +} + +} + +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() ); +} + +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) ) {} + +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 { + 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(mpi::comm_to_int(comm)).name()) {} + ~Scope() { + if (not ended_) { + pop(); + } + ended_ = true; + } + + void reset( const std::string& name ) { + pop(); + push(name); + } + void reset( const mpi::Comm& comm ) { + pop(); + push(comm.name()); + } + void reset( std::nullptr_t ) { + pop(); + ended_ = true; + } + 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 ended_ = false; +}; + +} // namespace mpi + +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); }, "name"_a); + m_mpi.def("has_comm", &mpi::has_comm, "name"_a ); + m_mpi.def("list_comms", &eckit::mpi::listComms); + m_mpi.def("register_comm", [](const std::string& name, int comm) { return mpi::register_comm(name, comm); }, "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)); }, "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); }, "name"_a ); + m_mpi.def("unregister_comm", [](mpi::Comm& comm) { mpi::unregister_comm(comm.name()); }, "comm"_a ); +#endif + m_mpi.def("delete_comm", &mpi::delete_comm, "name"_a ); + m_mpi.def("comm", []() { return mpi::Comm(); } ); + m_mpi.def("comm", [](const std::string& name) { return mpi::Comm(name); } ); + m_mpi.def("comm", [](int comm) { return mpi::Comm(comm); } ); + m_mpi.def("comm", [](nb::object comm) { return mpi::Comm(mpi::comm_to_int(comm)); } ); + m_mpi.def("size", []() { return atlas::mpi::size(); } ); + m_mpi.def("rank", []() { return atlas::mpi::rank(); } ); + m_mpi.def("barrier", []() { atlas::mpi::comm().barrier(); } ); + m_mpi.def("abort", [](int errorcode = -1) { atlas::mpi::comm().abort(errorcode); }, "errorcode"_a = -1 ); + m_mpi.def("finalize", []() { atlas::mpi::finalize(); } ); + m_mpi.def("push", [](const std::string& name) { mpi::Scope::push(name); }, "name"_a ); + m_mpi.def("pop", []() { mpi::Scope::pop(); } ); + + nb::class_( m_mpi, "Comm" ) + .def( nb::init<>() ) + .def_prop_ro("size", &mpi::Comm::size ) + .def_prop_ro("rank", &mpi::Comm::rank ) + .def_prop_ro("name", &mpi::Comm::name ) + .def("barrier", &mpi::Comm::barrier ) + .def("abort", &mpi::Comm::abort, "errorcode"_a = -1 ) + .def("split", &mpi::Comm::split, "color"_a, "name"_a ) + .def("to_int", &mpi::Comm::to_int ) + .def("__int__", &mpi::Comm::to_int ) + .def("__eq__", [](const mpi::Comm &self, const mpi::Comm &other) { + return self.to_int() == other.to_int(); + } ) + .def("__repr__", []( 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() ) + ")"; + } ); + + nb::class_( m_mpi, "Scope" ) + .def( nb::init(), "name"_a ) + .def( nb::init(), "comm"_a ) + .def( nb::init(), "comm"_a ) + .def( nb::init(), "comm"_a ) + .def( "__enter__", []( mpi::Scope& self ) { return &self; } ) + .def( "__exit__", []( mpi::Scope& self, nb::object exc_type, nb::object exc_value, nb::object traceback ) { self.reset(nullptr); }, "exc_type"_a = nb::none(), "exc_value"_a = nb::none(), "traceback"_a = nb::none() ); + + m_mpi.def("__getattr__", [m_mpi](nb::handle name) -> nb::object { + // Check if the requested attribute is the one we want to lazily initialize + std::string name_str = nb::cast(name); + if (name_str == "COMM_WORLD" || name_str == "COMM_SELF") { + const mpi::Comm& comm = [name_str]() -> const mpi::Comm& { + if (name_str == "COMM_WORLD") { + return mpi::Comm::WORLD(); + } + else { // name_str == "COMM_SELF" + return mpi::Comm::SELF(); + } + }(); + nb::object value = nb::cast(comm, nb::rv_policy::reference); // policy::reference tells nanobind NOT to manage the memory. + + // 2. Cache it in the module's __dict__ for fast subsequent access + // This makes it act like a read-only property after the first call + nb::getattr(nb::handle(m_mpi), "__dict__")[name] = value; + return value; + } + // Raise AttributeError for other missing attributes + throw nb::attribute_error(); + }); +} + + +} // namespace atlas4py diff --git a/src/atlas4py/mpi/_mpi.hpp b/src/atlas4py/mpi/_mpi.hpp new file mode 100644 index 0000000..9a1ace4 --- /dev/null +++ b/src/atlas4py/mpi/_mpi.hpp @@ -0,0 +1,60 @@ +#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.add_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 ); + 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..19c275d 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,136 @@ 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(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_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") + + # 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_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") From d0cb7e58ab64e40c9dfbc9a27ffab9b9bf76ce86 Mon Sep 17 00:00:00 2001 From: Willem Deconinck Date: Mon, 31 Aug 2026 10:08:38 +0200 Subject: [PATCH 2/5] Fix atlas4py_parse_version duplication and possible undefined variables --- src/atlas4py/cmake/atlas4py_add_atlas.cmake | 55 ------------------- .../cmake/atlas4py_parse_version.cmake | 10 ++++ 2 files changed, 10 insertions(+), 55 deletions(-) diff --git a/src/atlas4py/cmake/atlas4py_add_atlas.cmake b/src/atlas4py/cmake/atlas4py_add_atlas.cmake index d7330b2..c8f4030 100644 --- a/src/atlas4py/cmake/atlas4py_add_atlas.cmake +++ b/src/atlas4py/cmake/atlas4py_add_atlas.cmake @@ -4,61 +4,6 @@ # If it cannot find it, it uses FetchContent to download and build atlas and its dependencies (eckit and ecbuild) from source. # The macro is called in the main CMakeLists.txt file of the project. -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() - - 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() - macro(atlas4py_add_atlas) if (NOT build_atlas) if (DEFINED ENV{ATLAS_INSTALL_DIR}) diff --git a/src/atlas4py/cmake/atlas4py_parse_version.cmake b/src/atlas4py/cmake/atlas4py_parse_version.cmake index b18adc5..695444b 100644 --- a/src/atlas4py/cmake/atlas4py_parse_version.cmake +++ b/src/atlas4py/cmake/atlas4py_parse_version.cmake @@ -67,6 +67,16 @@ function( atlas4py_parse_version version_str ) 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 From 2ed68d3b552839951a94c74b200792fa88136de4 Mon Sep 17 00:00:00 2001 From: Willem Deconinck Date: Mon, 31 Aug 2026 11:56:39 +0200 Subject: [PATCH 3/5] Fix commented example --- src/atlas4py/mpi/_mpi.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/atlas4py/mpi/_mpi.hpp b/src/atlas4py/mpi/_mpi.hpp index 9a1ace4..4750798 100644 --- a/src/atlas4py/mpi/_mpi.hpp +++ b/src/atlas4py/mpi/_mpi.hpp @@ -12,7 +12,7 @@ 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.add_comm( "my_comm", mpi4py_comm.toint() ) +atlas4py.mpi.register_comm( "my_comm", mpi4py_comm.toint() ) # and retrieve it later atlas4py_my_comm = atlas4py.mpi.comm( "my_comm" ) From fd337a6ced99ce7b2331fdc4723bd4e64cc713ee Mon Sep 17 00:00:00 2001 From: Willem Deconinck Date: Mon, 31 Aug 2026 11:56:57 +0200 Subject: [PATCH 4/5] Be more explicit that the mpi comm is converted to int --- tests/test_bindings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_bindings.py b/tests/test_bindings.py index 19c275d..fffdcb8 100644 --- a/tests/test_bindings.py +++ b/tests/test_bindings.py @@ -449,7 +449,7 @@ def test_mpi_comm_to_from_int(): # atlas4py.mpi.Comm and vice versa if importlib.util.find_spec("mpi4py") is not None: import mpi4py.MPI - mpi4py_comm = mpi4py.MPI.Comm.fromint(comm_from_int) + 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, From d0badb52cf30ea1e9babfea607ee309570984679 Mon Sep 17 00:00:00 2001 From: Willem Deconinck Date: Mon, 31 Aug 2026 15:34:36 +0200 Subject: [PATCH 5/5] Cleanup --- src/atlas4py/mpi/_mpi.cpp | 155 ++++++++++++++++++-------------------- src/atlas4py/mpi/_mpi.hpp | 1 + tests/test_bindings.py | 74 ++++++++++-------- 3 files changed, 116 insertions(+), 114 deletions(-) diff --git a/src/atlas4py/mpi/_mpi.cpp b/src/atlas4py/mpi/_mpi.cpp index 5a86c35..fe102d1 100644 --- a/src/atlas4py/mpi/_mpi.cpp +++ b/src/atlas4py/mpi/_mpi.cpp @@ -2,7 +2,6 @@ #include "_mpi.hpp" #include -#include #include #include #include @@ -87,6 +86,10 @@ int comm_to_int( const nb::object& comm ) { } +// -------------------------------------------------------------------------------------------------- +// Standalone functions +// -------------------------------------------------------------------------------------------------- + bool has_comm( const std::string& name ) { return eckit::mpi::hasComm( name.c_str() ); } @@ -110,10 +113,15 @@ 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) { @@ -155,6 +163,10 @@ 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 ) { @@ -162,26 +174,16 @@ class Scope { } 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(mpi::comm_to_int(comm)).name()) {} - ~Scope() { - if (not ended_) { + Scope( const nb::object& comm ) : Scope(mpi::Comm(comm).name()) {} + ~Scope() { deactivate(); } + + void deactivate() { + if (is_active_) { pop(); + is_active_ = false; } - ended_ = true; } - void reset( const std::string& name ) { - pop(); - push(name); - } - void reset( const mpi::Comm& comm ) { - pop(); - push(comm.name()); - } - void reset( std::nullptr_t ) { - pop(); - ended_ = true; - } static void push(const std::string& name) { #if ATLAS4PY_ATLAS_VERSION_AT_LEAST(0,46,0) atlas::mpi::scope::push(name); @@ -196,87 +198,76 @@ class Scope { atlas::mpi::pop(); #endif } - bool ended_ = false; + 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); }, "name"_a); - m_mpi.def("has_comm", &mpi::has_comm, "name"_a ); - m_mpi.def("list_comms", &eckit::mpi::listComms); - m_mpi.def("register_comm", [](const std::string& name, int comm) { return mpi::register_comm(name, comm); }, "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)); }, "name"_a, "comm"_a ); + 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); }, "name"_a ); - m_mpi.def("unregister_comm", [](mpi::Comm& comm) { mpi::unregister_comm(comm.name()); }, "comm"_a ); + 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, "name"_a ); - m_mpi.def("comm", []() { return mpi::Comm(); } ); - m_mpi.def("comm", [](const std::string& name) { return mpi::Comm(name); } ); - m_mpi.def("comm", [](int comm) { return mpi::Comm(comm); } ); - m_mpi.def("comm", [](nb::object comm) { return mpi::Comm(mpi::comm_to_int(comm)); } ); - m_mpi.def("size", []() { return atlas::mpi::size(); } ); - m_mpi.def("rank", []() { return atlas::mpi::rank(); } ); - m_mpi.def("barrier", []() { atlas::mpi::comm().barrier(); } ); - m_mpi.def("abort", [](int errorcode = -1) { atlas::mpi::comm().abort(errorcode); }, "errorcode"_a = -1 ); - m_mpi.def("finalize", []() { atlas::mpi::finalize(); } ); - m_mpi.def("push", [](const std::string& name) { mpi::Scope::push(name); }, "name"_a ); - m_mpi.def("pop", []() { mpi::Scope::pop(); } ); - - nb::class_( m_mpi, "Comm" ) - .def( nb::init<>() ) - .def_prop_ro("size", &mpi::Comm::size ) - .def_prop_ro("rank", &mpi::Comm::rank ) - .def_prop_ro("name", &mpi::Comm::name ) - .def("barrier", &mpi::Comm::barrier ) - .def("abort", &mpi::Comm::abort, "errorcode"_a = -1 ) - .def("split", &mpi::Comm::split, "color"_a, "name"_a ) - .def("to_int", &mpi::Comm::to_int ) - .def("__int__", &mpi::Comm::to_int ) + 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(name=" + comm.name() + ", size=" + std::to_string( comm.size() ) + + 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() ) + ")"; - } ); - - nb::class_( m_mpi, "Scope" ) - .def( nb::init(), "name"_a ) - .def( nb::init(), "comm"_a ) - .def( nb::init(), "comm"_a ) - .def( nb::init(), "comm"_a ) - .def( "__enter__", []( mpi::Scope& self ) { return &self; } ) - .def( "__exit__", []( mpi::Scope& self, nb::object exc_type, nb::object exc_value, nb::object traceback ) { self.reset(nullptr); }, "exc_type"_a = nb::none(), "exc_value"_a = nb::none(), "traceback"_a = nb::none() ); - - m_mpi.def("__getattr__", [m_mpi](nb::handle name) -> nb::object { - // Check if the requested attribute is the one we want to lazily initialize - std::string name_str = nb::cast(name); - if (name_str == "COMM_WORLD" || name_str == "COMM_SELF") { - const mpi::Comm& comm = [name_str]() -> const mpi::Comm& { - if (name_str == "COMM_WORLD") { - return mpi::Comm::WORLD(); - } - else { // name_str == "COMM_SELF" - return mpi::Comm::SELF(); - } - }(); - nb::object value = nb::cast(comm, nb::rv_policy::reference); // policy::reference tells nanobind NOT to manage the memory. - - // 2. Cache it in the module's __dict__ for fast subsequent access - // This makes it act like a read-only property after the first call - nb::getattr(nb::handle(m_mpi), "__dict__")[name] = value; - return value; - } - // Raise AttributeError for other missing attributes - throw nb::attribute_error(); - }); + }, "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." ); + } diff --git a/src/atlas4py/mpi/_mpi.hpp b/src/atlas4py/mpi/_mpi.hpp index 4750798..78fc8f5 100644 --- a/src/atlas4py/mpi/_mpi.hpp +++ b/src/atlas4py/mpi/_mpi.hpp @@ -36,6 +36,7 @@ class Comm { 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; diff --git a/tests/test_bindings.py b/tests/test_bindings.py index fffdcb8..ae6f487 100644 --- a/tests/test_bindings.py +++ b/tests/test_bindings.py @@ -422,27 +422,26 @@ def toint(self): 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" + 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.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 - + 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) + 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 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 @@ -450,16 +449,22 @@ def test_mpi_comm_to_from_int(): 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()) + 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) + 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 + 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 @@ -474,9 +479,10 @@ def test_mpi_comm_registration(): # change the default comm to the newly registered one atlas4py.mpi.set_default_comm("my_comm") - assert atlas4py.mpi.comm().name == "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"): @@ -485,26 +491,26 @@ def test_mpi_comm_registration(): 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) + 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" + assert mpi.Comm().name == "world" # using named comms with mpi.Scope("scope 1"): - assert mpi.comm().name == "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" + 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" + 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" + 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) @@ -512,7 +518,7 @@ def test_mpi_scope(): with mpi.Scope(mock_mpi4py_comm_9999): assert "int.9999" in mpi.list_comms() - assert mpi.comm().name == "world" + assert mpi.Comm().name == "world" # When eckit::mpi::unregisterComm is available (from eckit 2.0.0) if hasattr(atlas4py.mpi, "unregister_comm"): @@ -521,16 +527,20 @@ def test_mpi_scope(): 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() + 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") + world = mpi.Comm("world") color = world.rank % 2 split_comm = world.split(color, "split_comm") mpi.set_default_comm("split_comm") @@ -540,7 +550,7 @@ def test_mpi_comm_split(): # 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") + 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")