files: #!/usr/bin/env python
  
  # ==============================================================================
  # MODULE DOCSTRING
  # ==============================================================================
  
  """Utilities to run on MPI.
  
  Provide functions and decorators that simplify running the same code on
  multiple nodes. One benefit is that serial and parallel code is exactly
  the same.
  
  Global variables
  ----------------
  disable_mpi : bool
      Set this to True to force running serially.
  
  Routines
  --------
  get_mpicomm
      Automatically detect and configure MPI execution and return an
      MPI communicator.
  run_single_node
      Run a task on a single node.
  on_single_node
      Decorator version of run_single_node.
  distribute
      Map a task on a sequence of arguments on all the nodes.
  delay_termination
      A context manager to delay the response to termination signals.
  delayed_termination
      A decorator version of delay_termination.
  
  """
  
  
  # ==============================================================================
  # GLOBAL IMPORTS
  # ==============================================================================
  
  import os
  import sys
  import signal
  import logging
  from contextlib import contextmanager
  
  import numpy as np
  # TODO drop this when we drop Python 2 support
  from openmoltools.utils import wraps_py2
  
  logger = logging.getLogger(__name__)
  
  # ==============================================================================
  # GLOBAL VARIABLES
  # ==============================================================================
  
  disable_mpi = False
  
  
  # ==============================================================================
  # MAIN FUNCTIONS
  # ==============================================================================
  
  def get_mpicomm():
      """Retrieve the MPI communicator for this execution.
  
      The function automatically detects if the program runs on MPI by checking
      specific environment variables set by various MPI implementations. On
      first execution, it modifies sys.excepthook and register a handler for
      SIGINT, SIGTERM, SIGABRT to call Abort() to correctly terminate all
      processes.
  
      Returns
      -------
      mpicomm : mpi4py communicator or None
          The communicator for this node, None if the program doesn't run
          with MPI.
  
      """
      # If MPI execution is forcefully disabled, return None.
      if disable_mpi:
          return None
  
      # If we have already initialized MPI, return the cached MPI communicator.
      if get_mpicomm._is_initialized:
          return get_mpicomm._mpicomm
  
      # Check for environment variables set by mpirun. Variables are from
      # http://docs.roguewave.com/threadspotter/2012.1/linux/manual_html/apas03.html
      variables = ['PMI_RANK', 'OMPI_COMM_WORLD_RANK', 'OMPI_MCA_ns_nds_vpid',
                   'PMI_ID', 'SLURM_PROCID', 'LAMRANK', 'MPI_RANKID',
                   'MP_CHILD', 'MP_RANK', 'MPIRUN_RANK']
      use_mpi = False
      for var in variables:
          if var in os.environ:
              use_mpi = True
              break
  
      # Return None if we are not running on MPI.
      if not use_mpi:
          logger.debug('Cannot find MPI environment. MPI disabled.')
          get_mpicomm._mpicomm = None
          get_mpicomm._is_initialized = True
          return get_mpicomm._mpicomm
  
      # Initialize MPI
      from mpi4py import MPI
      mpicomm = MPI.COMM_WORLD
  
      # Override sys.excepthook to abort MPI on exception
      def mpi_excepthook(type, value, traceback):
          sys.__excepthook__(type, value, traceback)
          sys.stdout.flush()
          sys.stderr.flush()
          if mpicomm.size > 1:
              mpicomm.Abort(1)
      # Use our eception handler
      sys.excepthook = mpi_excepthook
  
      # Catch sigterm signals
      def handle_signal(signal, frame):
          if mpicomm.size > 1:
              mpicomm.Abort(1)
      for sig in [signal.SIGINT, signal.SIGTERM, signal.SIGABRT]:
          signal.signal(sig, handle_signal)
  
      # Cache and return the MPI communicator.
      get_mpicomm._is_initialized = True
      get_mpicomm._mpicomm = mpicomm
  
      # Report initialization
      logger.debug("MPI initialized on node {}/{}".format(mpicomm.rank+1, mpicomm.size))
  
      return mpicomm
  
  get_mpicomm._is_initialized = False  # Static variable
  
  
  def run_single_node(rank, task, *args, **kwargs):
      """Run task on a single node.
  
      If MPI is not activated, this simply runs locally.
  
      Parameters
      ----------
      task : callable
          The task to run on node rank.
      rank : int
          The rank of the MPI communicator that must execute the task.
      broadcast_result : bool, optional
          If True, the result is broadcasted to all nodes. If False,
          only the node executing the task will receive the return
          value of the task, and all other nodes will receive None
          (default is False).
      sync_nodes : bool, optional
          If True, the nodes will be synchronized at the end of the
          execution (i.e. the task will be blocking) even if the
          result is not broadcasted  (default is False).
  
      Other Parameters
      ----------------
      *args
          The ordered arguments to pass to task.
      **kwargs
          The keyword arguments to pass to task.
  
      Returns
      -------
      result
          The return value of the task. This will be None on all nodes
          that is not the rank unless broadcast_result is set to True.
  
      Examples
      --------
      >>> def add(a, b):
      ...     return a + b
      >>> # Run 3+4 on node 0.
      >>> run_single_node(0, task=add, a=3, b=4, broadcast_result=True)
      7
  
      """
      broadcast_result = kwargs.pop('broadcast_result', False)
      sync_nodes = kwargs.pop('sync_nodes', False)
      result = None
      mpicomm = get_mpicomm()
  
      if mpicomm is not None:
          node_name = 'Node {}/{}'.format(mpicomm.rank+1, mpicomm.size)
      else:
          node_name = 'Single node'
  
      # Execute the task only on the specified node.
      if mpicomm is None or mpicomm.rank == rank:
          logger.debug('{}: executing {}'.format(node_name, task))
          result = task(*args, **kwargs)
  
      # Broadcast the result if required.
      if mpicomm is not None:
          if broadcast_result is True:
              logger.debug('{}: waiting for broadcast of {}'.format(node_name, task))
              result = mpicomm.bcast(result, root=rank)
          elif sync_nodes is True:
              logger.debug('{}: waiting for barrier after {}'.format(node_name, task))
              mpicomm.barrier()
  
      # Return result.
      return result
  
  
  def on_single_node(rank, broadcast_result=False, sync_nodes=False):
      """A decorator version of run_single_node.
  
      Decorates a function to be always executed with run_single_node.
  
      Parameters
      ----------
      rank : int
          The rank of the MPI communicator that must execute the task.
      broadcast_result : bool, optional
          If True the result is broadcasted to all nodes. If False,
          only the node executing the function will receive its return
          value, and all other nodes will receive None (default is False).
      sync_nodes : bool, optional
          If True, the nodes will be synchronized at the end of the
          execution (i.e. the task will be blocking) even if the
          result is not broadcasted (default is False).
  
      See Also
      --------
      run_single_node
  
      Examples
      --------
      >>> @on_single_node(rank=0, broadcast_result=True)
      ... def add(a, b):
      ...     return a + b
      >>> add(3, 4)
      7
  
      """
      def _on_single_node(task):
          @wraps_py2(task)
          def _wrapper(*args, **kwargs):
              kwargs['broadcast_result'] = broadcast_result
              kwargs['sync_nodes'] = sync_nodes
              return run_single_node(rank, task, *args, **kwargs)
          return _wrapper
      return _on_single_node
  
  
  def distribute(task, distributed_args, *other_args, **kwargs):
      """Map the task on a sequence of arguments to be executed on different nodes.
  
      If MPI is not activated, this simply runs serially on this node. The
      algorithm guarantees that each node will be assigned to the same job_id
      (i.e. the index of the argument in distributed_args) every time.
  
      Parameters
      ----------
      task : callable
          The task to be distributed among nodes. The task will be called as
          task(distributed_args[job_id], *
  
  [... the rest is omitted ...]
files: Yank/mpi.py
files: #!/usr/bin/env python
  
  # ==============================================================================
  # MODULE DOCSTRING
  # ==============================================================================
  
  """Utilities to run on MPI.
  
  Provide functions and decorators that simplify running the same code on
  multiple nodes. One benefit is that serial and parallel code is exactly
  the same.
  
  Global variables
  ----------------
  disable_mpi : bool
      Set this to True to force running serially.
  
  Routines
  --------
  get_mpicomm
      Automatically detect and configure MPI execution and return an
      MPI communicator.
  run_single_node
      Run a task on a single node.
  on_single_node
      Decorator version of run_single_node.
  distribute
      Map a task on a sequence of arguments on all the nodes.
  delay_termination
      A context manager to delay the response to termination signals.
  delayed_termination
      A decorator version of delay_termination.
  
  """
  
  
  # ==============================================================================
  # GLOBAL IMPORTS
  # ==============================================================================
  
  import os
  import sys
  import signal
  import logging
  from contextlib import contextmanager
  
  # TODO drop this when we drop Python 2 support
  from openmoltools.utils import wraps_py2
  
  logger = logging.getLogger(__name__)
  
  # ==============================================================================
  # GLOBAL VARIABLES
  # ==============================================================================
  
  disable_mpi = False
  
  
  # ==============================================================================
  # MAIN FUNCTIONS
  # ==============================================================================
  
  def get_mpicomm():
      """Retrieve the MPI communicator for this execution.
  
      The function automatically detects if the program runs on MPI by checking
      specific environment variables set by various MPI implementations. On
      first execution, it modifies sys.excepthook and register a handler for
      SIGINT, SIGTERM, SIGABRT to call Abort() to correctly terminate all
      processes.
  
      Returns
      -------
      mpicomm : mpi4py communicator or None
          The communicator for this node, None if the program doesn't run
          with MPI.
  
      """
      # If MPI execution is forcefully disabled, return None.
      if disable_mpi:
          return None
  
      # If we have already initialized MPI, return the cached MPI communicator.
      if get_mpicomm._is_initialized:
          return get_mpicomm._mpicomm
  
      # Check for environment variables set by mpirun. Variables are from
      # http://docs.roguewave.com/threadspotter/2012.1/linux/manual_html/apas03.html
      variables = ['PMI_RANK', 'OMPI_COMM_WORLD_RANK', 'OMPI_MCA_ns_nds_vpid',
                   'PMI_ID', 'SLURM_PROCID', 'LAMRANK', 'MPI_RANKID',
                   'MP_CHILD', 'MP_RANK', 'MPIRUN_RANK']
      use_mpi = False
      for var in variables:
          if var in os.environ:
              use_mpi = True
              break
  
      # Return None if we are not running on MPI.
      if not use_mpi:
          logger.debug('Cannot find MPI environment. MPI disabled.')
          get_mpicomm._mpicomm = None
          get_mpicomm._is_initialized = True
          return get_mpicomm._mpicomm
  
      # Initialize MPI
      from mpi4py import MPI
      mpicomm = MPI.COMM_WORLD
  
      # Override sys.excepthook to abort MPI on exception
      def mpi_excepthook(type, value, traceback):
          sys.__excepthook__(type, value, traceback)
          sys.stdout.flush()
          sys.stderr.flush()
          if mpicomm.size > 1:
              mpicomm.Abort(1)
      # Use our eception handler
      sys.excepthook = mpi_excepthook
  
      # Catch sigterm signals
      def handle_signal(signal, frame):
          if mpicomm.size > 1:
              mpicomm.Abort(1)
      for sig in [signal.SIGINT, signal.SIGTERM, signal.SIGABRT]:
          signal.signal(sig, handle_signal)
  
      # Cache and return the MPI communicator.
      get_mpicomm._is_initialized = True
      get_mpicomm._mpicomm = mpicomm
  
      # Report initialization
      logger.debug("MPI initialized on node {}/{}".format(mpicomm.rank+1, mpicomm.size))
  
      return mpicomm
  
  get_mpicomm._is_initialized = False  # Static variable
  
  
  def run_single_node(rank, task, *args, **kwargs):
      """Run task on a single node.
  
      If MPI is not activated, this simply runs locally.
  
      Parameters
      ----------
      task : callable
          The task to run on node rank.
      rank : int
          The rank of the MPI communicator that must execute the task.
      broadcast_result : bool, optional
          If True, the result is broadcasted to all nodes. If False,
          only the node executing the task will receive the return
          value of the task, and all other nodes will receive None
          (default is False).
      sync_nodes : bool, optional
          If True, the nodes will be synchronized at the end of the
          execution (i.e. the task will be blocking) even if the
          result is not broadcasted  (default is False).
  
      Other Parameters
      ----------------
      *args
          The ordered arguments to pass to task.
      **kwargs
          The keyword arguments to pass to task.
  
      Returns
      -------
      result
          The return value of the task. This will be None on all nodes
          that is not the rank unless broadcast_result is set to True.
  
      Examples
      --------
      >>> def add(a, b):
      ...     return a + b
      >>> # Run 3+4 on node 0.
      >>> run_single_node(0, task=add, a=3, b=4, broadcast_result=True)
      7
  
      """
      broadcast_result = kwargs.pop('broadcast_result', False)
      sync_nodes = kwargs.pop('sync_nodes', False)
      result = None
      mpicomm = get_mpicomm()
  
      if mpicomm is not None:
          node_name = 'Node {}/{}'.format(mpicomm.rank+1, mpicomm.size)
      else:
          node_name = 'Single node'
  
      # Execute the task only on the specified node.
      if mpicomm is None or mpicomm.rank == rank:
          logger.debug('{}: executing {}'.format(node_name, task))
          result = task(*args, **kwargs)
  
      # Broadcast the result if required.
      if mpicomm is not None:
          if broadcast_result is True:
              logger.debug('{}: waiting for broadcast of {}'.format(node_name, task))
              result = mpicomm.bcast(result, root=rank)
          elif sync_nodes is True:
              logger.debug('{}: waiting for barrier after {}'.format(node_name, task))
              mpicomm.barrier()
  
      # Return result.
      return result
  
  
  def on_single_node(rank, broadcast_result=False, sync_nodes=False):
      """A decorator version of run_single_node.
  
      Decorates a function to be always executed with run_single_node.
  
      Parameters
      ----------
      rank : int
          The rank of the MPI communicator that must execute the task.
      broadcast_result : bool, optional
          If True the result is broadcasted to all nodes. If False,
          only the node executing the function will receive its return
          value, and all other nodes will receive None (default is False).
      sync_nodes : bool, optional
          If True, the nodes will be synchronized at the end of the
          execution (i.e. the task will be blocking) even if the
          result is not broadcasted (default is False).
  
      See Also
      --------
      run_single_node
  
      Examples
      --------
      >>> @on_single_node(rank=0, broadcast_result=True)
      ... def add(a, b):
      ...     return a + b
      >>> add(3, 4)
      7
  
      """
      def _on_single_node(task):
          @wraps_py2(task)
          def _wrapper(*args, **kwargs):
              kwargs['broadcast_result'] = broadcast_result
              kwargs['sync_nodes'] = sync_nodes
              return run_single_node(rank, task, *args, **kwargs)
          return _wrapper
      return _on_single_node
  
  
  def distribute(task, distributed_args, *other_args, **kwargs):
      """Map the task on a sequence of arguments to be executed on different nodes.
  
      If MPI is not activated, this simply runs serially on this node. The
      algorithm guarantees that each node will be assigned to the same job_id
      (i.e. the index of the argument in distributed_args) every time.
  
      Parameters
      ----------
      task : callable
          The task to be distributed among nodes. The task will be called as
          task(distributed_args[job_id], *other_args, **kwargs
  
  [... the rest is omitted ...]
files: Yank/mpi.py
files: #!/usr/bin/env python
  
  # =============================================================================
  # MODULE DOCSTRING
  # =============================================================================
  
  """
  Test MPI utility functions in mpi.py.
  
  """
  
  # =============================================================================
  # GLOBAL IMPORTS
  # =============================================================================
  
  import json
  import shutil
  import contextlib
  
  from simtk import unit
  from openmoltools.utils import temporary_cd
  
  from yank.mpi import *
  
  
  # =============================================================================
  # GLOBAL VARIABLES
  # =============================================================================
  
  NODE_RANK = 1  # The node rank passed to rank or send_results_to.
  
  
  # =============================================================================
  # UTILITY FUNCTION
  # =============================================================================
  
  def assert_is_equal(a, b):
      err_msg = '{} != {}'.format(a, b)
      try:
          assert a == b, err_msg
      except ValueError:
          # This is a list or tuple of numpy arrays.
          try:
              for element_a, element_b in zip(a, b):
                  assert_is_equal(element_a, element_b)
          except AssertionError:
              raise AssertionError(err_msg)
  
  
  # =============================================================================
  # TEST CASES
  # =============================================================================
  
  def square(x):
      return x**2
  
  
  def multiply(a, b):
      return a * b
  
  
  @on_single_node(rank=NODE_RANK, broadcast_result=True)
  def multiply_decorated_broadcast(a, b):
      return multiply(a, b)
  
  
  @on_single_node(rank=NODE_RANK, broadcast_result=False)
  def multiply_decorated_nobroadcast(a, b):
      return multiply(a, b)
  
  
  class MyClass(object):
  
      def __init__(self, par):
          self.par = par
  
      @staticmethod
      def square_static(x):
          return x**2
  
      @staticmethod
      def multiply_static(a, b):
          return a * b
  
      @staticmethod
      @on_single_node(rank=NODE_RANK, broadcast_result=True)
      def multiply_decorated_broadcast_static(a, b):
          return a * b
  
      @classmethod
      @on_single_node(rank=NODE_RANK, broadcast_result=False)
      def multiply_decorated_nobroadcast_static(cls, a, b):
          return cls.multiply_static(a, b)
  
      def multiply_by_par(self, a):
          return self.par * a
  
      @on_single_node(rank=NODE_RANK, broadcast_result=True)
      def multiply_by_par_decorated_broadcast(self, a):
          return self.multiply_by_par(a)
  
      @on_single_node(rank=NODE_RANK, broadcast_result=False)
      def multiply_by_par_decorated_nobroadcast(self, a):
          return self.multiply_by_par(a)
  
  
  # =============================================================================
  # TEST FUNCTIONS
  # =============================================================================
  
  def test_run_single_node():
      """Test run_single_node function."""
      mpicomm = get_mpicomm()
      my_instance = MyClass(3.0)
  
      # Test_case: (function, args, kwargs)
      test_cases = [
          (multiply, (3, 4), {}),
          (multiply, (), {'a': 5, 'b': 4}),
          (multiply, (2, 'teststring',), {}),
          (multiply, (5, [3, 4],), {}),
          (multiply, (4, np.array([3, 4, 5.0]),), {}),
          (multiply, (3.0, unit.Quantity(np.array([3, 4, 5.0]), unit=unit.angstrom),), {}),
          (square, (5,), {}),
          (square, (), {'x': 2}),
          (MyClass.multiply_static, (3, 4), {}),
          (MyClass.multiply_static, (), {'a': 5, 'b': 4}),
          (MyClass.square_static, (5,), {}),
          (MyClass.square_static, (), {'x': 2}),
          (my_instance.multiply_by_par, (4,), {}),
          (my_instance.multiply_by_par, (), {'a': 2}),
      ]
  
      for task, args, kwargs in test_cases:
          expected_result = task(*args, **kwargs)
          for broadcast_result in [True, False]:
              result = run_single_node(NODE_RANK, task, *args,
                                       broadcast_result=broadcast_result, **kwargs)
              if not broadcast_result and mpicomm is not None and mpicomm.rank != NODE_RANK:
                  assert result is None
              else:
                  assert_is_equal(result, expected_result)
  
  
  def test_on_single_node():
      """Test on_single_node decorator."""
      mpicomm = get_mpicomm()
      my_instance = MyClass(3.0)
  
      # Test case: (function, args, kwargs, broadcast_result, expected_result)
      test_cases = [
          (multiply_decorated_broadcast, (3, 4), {}, True, 12),
          (multiply_decorated_nobroadcast, (), {'a': 5, 'b': 5}, False, 25),
          (MyClass.multiply_decorated_broadcast_static, (3, 4), {}, True, 12),
          (MyClass.multiply_decorated_nobroadcast_static, (), {'a': 5, 'b': 5}, False, 25),
          (my_instance.multiply_by_par_decorated_broadcast, (4,), {}, True, 4 * my_instance.par),
          (my_instance.multiply_by_par_decorated_broadcast, (), {'a': 5}, True, 5 * my_instance.par),
      ]
  
      for task, args, kwargs, broadcast_result, expected_result in test_cases:
          result = task(*args, **kwargs)
          if not broadcast_result and mpicomm is not None and mpicomm.rank != NODE_RANK:
              assert result is None
          else:
              assert_is_equal(result, expected_result)
  
  
  def test_distribute():
      """Test distribute function."""
      mpicomm = get_mpicomm()
      my_instance = MyClass(4)
  
      # Testcase: (function, distributed_args)
      test_cases = [
          (square, [1, 2, 3]),
          (MyClass.square_static, [1, 2, 3, 4]),
          (my_instance.multiply_by_par, [1, 2, 3, 4, 5]),
          (my_instance.multiply_by_par, ['a', 'b', 'c', 'd', 'e', 'f']),
          (my_instance.multiply_by_par, [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]),
          (my_instance.multiply_by_par, [np.array([1, 2]), np.array([3, 4]), np.array([5, 6]), np.array([7, 8])]),
          (my_instance.multiply_by_par, [unit.Quantity(np.array([1, 2]), unit=unit.angstrom),
                                         unit.Quantity(np.array([3, 4]), unit=unit.angstrom),
                                         unit.Quantity(np.array([5, 6]), unit=unit.angstrom)]),
      ]
  
      for task, distributed_args in test_cases:
          all_indices = list(range(len(distributed_args)))
          all_expected_results = [task(x) for x in distributed_args]
  
          # Determining full and partial results.
          if mpicomm is not None:
              partial_job_indices = list(range(mpicomm.rank, len(distributed_args), mpicomm.size))
          else:
              partial_job_indices = all_indices
          partial_expected_results = [all_expected_results[i] for i in partial_job_indices]
  
          result = distribute(task, distributed_args, send_results_to='all')
          assert_is_equal(result, all_expected_results)
  
          result = distribute(task, distributed_args, send_results_to=NODE_RANK)
          if mpicomm is not None and mpicomm.rank != NODE_RANK:
              assert_is_equal(result, (partial_expected_results, partial_job_indices))
          else:
              assert_is_equal(result, (all_expected_results, all_indices))
  
          result = distribute(task, distributed_args, send_results_to=None)
          assert_is_equal(result, (partial_expected_results, partial_job_indices))
  
  
  def test_distribute_groups():
      """Test distribute jobs among groups of nodes."""
      # Configuration.
      group_nodes = 2
      temp_folder = 'temp_test_mpi_test_distribute_groups'
  
      @contextlib.contextmanager
      def enter_temp_directory():
          run_single_node(0, os.makedirs, temp_folder, sync_nodes=True)
          try:
              with temporary_cd(temp_folder):
                  yield
          finally:
              run_single_node(0, shutil.rmtree, temp_folder)
  
  
      def store_data(file_name, data):
          with open(file_name, 'w
  
  [... the rest is omitted ...]
files: Yank/tests/test_mpi.py
files: #!/usr/bin/env python
  
  # =============================================================================
  # MODULE DOCSTRING
  # =============================================================================
  
  """
  Test MPI utility functions in mpi.py.
  
  """
  
  # =============================================================================
  # GLOBAL IMPORTS
  # =============================================================================
  
  import numpy as np
  from simtk import unit
  
  from yank.mpi import *
  
  
  # =============================================================================
  # GLOBAL VARIABLES
  # =============================================================================
  
  NODE_RANK = 1  # The node rank passed to rank or send_results_to.
  
  
  # =============================================================================
  # UTILITY FUNCTION
  # =============================================================================
  
  def assert_is_equal(a, b):
      err_msg = '{} != {}'.format(a, b)
      try:
          assert a == b, err_msg
      except ValueError:
          # This is a list or tuple of numpy arrays.
          try:
              for element_a, element_b in zip(a, b):
                  assert_is_equal(element_a, element_b)
          except AssertionError:
              raise AssertionError(err_msg)
  
  
  # =============================================================================
  # TEST CASES
  # =============================================================================
  
  def square(x):
      return x**2
  
  
  def multiply(a, b):
      return a * b
  
  
  @on_single_node(rank=NODE_RANK, broadcast_result=True)
  def multiply_decorated_broadcast(a, b):
      return multiply(a, b)
  
  
  @on_single_node(rank=NODE_RANK, broadcast_result=False)
  def multiply_decorated_nobroadcast(a, b):
      return multiply(a, b)
  
  
  class MyClass(object):
  
      def __init__(self, par):
          self.par = par
  
      @staticmethod
      def square_static(x):
          return x**2
  
      @staticmethod
      def multiply_static(a, b):
          return a * b
  
      @staticmethod
      @on_single_node(rank=NODE_RANK, broadcast_result=True)
      def multiply_decorated_broadcast_static(a, b):
          return a * b
  
      @classmethod
      @on_single_node(rank=NODE_RANK, broadcast_result=False)
      def multiply_decorated_nobroadcast_static(cls, a, b):
          return cls.multiply_static(a, b)
  
      def multiply_by_par(self, a):
          return self.par * a
  
      @on_single_node(rank=NODE_RANK, broadcast_result=True)
      def multiply_by_par_decorated_broadcast(self, a):
          return self.multiply_by_par(a)
  
      @on_single_node(rank=NODE_RANK, broadcast_result=False)
      def multiply_by_par_decorated_nobroadcast(self, a):
          return self.multiply_by_par(a)
  
  
  # =============================================================================
  # TEST FUNCTIONS
  # =============================================================================
  
  def test_run_single_node():
      """Test run_single_node function."""
      mpicomm = get_mpicomm()
      my_instance = MyClass(3.0)
  
      # Test_case: (function, args, kwargs)
      test_cases = [
          (multiply, (3, 4), {}),
          (multiply, (), {'a': 5, 'b': 4}),
          (multiply, (2, 'teststring',), {}),
          (multiply, (5, [3, 4],), {}),
          (multiply, (4, np.array([3, 4, 5.0]),), {}),
          (multiply, (3.0, unit.Quantity(np.array([3, 4, 5.0]), unit=unit.angstrom),), {}),
          (square, (5,), {}),
          (square, (), {'x': 2}),
          (MyClass.multiply_static, (3, 4), {}),
          (MyClass.multiply_static, (), {'a': 5, 'b': 4}),
          (MyClass.square_static, (5,), {}),
          (MyClass.square_static, (), {'x': 2}),
          (my_instance.multiply_by_par, (4,), {}),
          (my_instance.multiply_by_par, (), {'a': 2}),
      ]
  
      for task, args, kwargs in test_cases:
          expected_result = task(*args, **kwargs)
          for broadcast_result in [True, False]:
              result = run_single_node(NODE_RANK, task, *args,
                                       broadcast_result=broadcast_result, **kwargs)
              if not broadcast_result and mpicomm is not None and mpicomm.rank != NODE_RANK:
                  assert result is None
              else:
                  assert_is_equal(result, expected_result)
  
  
  def test_on_single_node():
      """Test on_single_node decorator."""
      mpicomm = get_mpicomm()
      my_instance = MyClass(3.0)
  
      # Test case: (function, args, kwargs, broadcast_result, expected_result)
      test_cases = [
          (multiply_decorated_broadcast, (3, 4), {}, True, 12),
          (multiply_decorated_nobroadcast, (), {'a': 5, 'b': 5}, False, 25),
          (MyClass.multiply_decorated_broadcast_static, (3, 4), {}, True, 12),
          (MyClass.multiply_decorated_nobroadcast_static, (), {'a': 5, 'b': 5}, False, 25),
          (my_instance.multiply_by_par_decorated_broadcast, (4,), {}, True, 4 * my_instance.par),
          (my_instance.multiply_by_par_decorated_broadcast, (), {'a': 5}, True, 5 * my_instance.par),
      ]
  
      for task, args, kwargs, broadcast_result, expected_result in test_cases:
          result = task(*args, **kwargs)
          if not broadcast_result and mpicomm is not None and mpicomm.rank != NODE_RANK:
              assert result is None
          else:
              assert_is_equal(result, expected_result)
  
  
  def test_distribute():
      """Test distribute function."""
      mpicomm = get_mpicomm()
      my_instance = MyClass(4)
  
      # Testcase: (function, distributed_args)
      test_cases = [
          (square, [1, 2, 3]),
          (MyClass.square_static, [1, 2, 3, 4]),
          (my_instance.multiply_by_par, [1, 2, 3, 4, 5]),
          (my_instance.multiply_by_par, ['a', 'b', 'c', 'd', 'e', 'f']),
          (my_instance.multiply_by_par, [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]),
          (my_instance.multiply_by_par, [np.array([1, 2]), np.array([3, 4]), np.array([5, 6]), np.array([7, 8])]),
          (my_instance.multiply_by_par, [unit.Quantity(np.array([1, 2]), unit=unit.angstrom),
                                         unit.Quantity(np.array([3, 4]), unit=unit.angstrom),
                                         unit.Quantity(np.array([5, 6]), unit=unit.angstrom)]),
      ]
  
      for task, distributed_args in test_cases:
          all_indices = list(range(len(distributed_args)))
          all_expected_results = [task(x) for x in distributed_args]
  
          # Determining full and partial results.
          if mpicomm is not None:
              partial_job_indices = list(range(mpicomm.rank, len(distributed_args), mpicomm.size))
          else:
              partial_job_indices = all_indices
          partial_expected_results = [all_expected_results[i] for i in partial_job_indices]
  
          result = distribute(task, distributed_args, send_results_to='all')
          assert_is_equal(result, all_expected_results)
  
          result = distribute(task, distributed_args, send_results_to=NODE_RANK)
          if mpicomm is not None and mpicomm.rank != NODE_RANK:
              assert_is_equal(result, (partial_expected_results, partial_job_indices))
          else:
              assert_is_equal(result, (all_expected_results, all_indices))
  
          result = distribute(task, distributed_args, send_results_to=None)
          assert_is_equal(result, (partial_expected_results, partial_job_indices))
  
  
  [... the rest is omitted ...]
files: Yank/tests/test_mpi.py