#!/bin/sh

#-------------------------------------------------------------------------------

# This file is part of code_saturne, a general-purpose CFD tool.
#
# Copyright (C) 1998-2023 EDF S.A.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# Street, Fifth Floor, Boston, MA 02110-1301, USA.

#-------------------------------------------------------------------------------

#===============================================================================
# A priori detection of the rank of a MPI process
#===============================================================================
#
# In order to get the MPI rank from a script launched
# by mpirun (or prun, mpijob, or equivalent):
#
# MPI_RANK=`runcase_mpi_rank $@`
#
# Mainly useful to launch MPMD applications
# like coupling within MPI environments
# which do not have a command like mpiexec.

# Current systems
# ---------------

# For PMIx (shared by most MPI libraries)
if [ "$PMIX_RANK" != "" ] ; then
  MPI_RANK="$PMIX_RANK"

# For MPICH
elif [ "$PMI_RANK" != "" ] ; then
  MPI_RANK="$PMI_RANK"

# For Open MPI (prefer PMIx when available)
elif [ "$OMPI_COMM_WORLD_RANK" != "" ] ; then # Since Open MPI 1.3
  MPI_RANK="$OMPI_COMM_WORLD_RANK"

# Otherwise, with SLURM
elif [ "$PMI_ID" != "" ] ; then
  MPI_RANK="$PMI_ID"
elif [ "$SLURM_PROCID" != "" ] ; then
  MPI_RANK="$SLURM_PROCID"

# For IBM Platform MPI
elif [ "$MPI_RANKID" != "" ] ; then
  MPI_RANK="$MPI_RANKID"

# Current systems for which we have no access (so trust docs)
# -------------------------------------------

# For IBM PE
elif [ "$MP_CHILD" != "" ] ; then
  MPI_RANK="$MP_CHILD"

# Obsolete systems (are any of those still used somewhere ?)
# ----------------

# For MVAPICH 1.1
elif [ "$SMPIRUN_RANK" != "" ] ; then
  MPI_RANK="$MPIRUN_RANK"

# On cluster with HP-MPI (has become Platform MPI since)
elif [ "$MPI_PROC" != "" ] ; then
  MPI_RANK=`echo $MPI_PROC | cut -f 2 -d,`

elif [ "$OMPI_MCA_ns_nds_vpid" != "" ] ; then # Open MPI 1.2
  MPI_RANK="$OMPI_MCA_ns_nds_vpid"

# End of known cases
fi

# Output of the obtained rank

echo "$MPI_RANK"

