{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7606d30a",
   "metadata": {},
   "source": [
    "<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/39/VU_logo.png/800px-VU_logo.png?20161029201021\" width=\"350\">\n",
    "\n",
    "### Programming large-scale parallel systems"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ac1e5d9",
   "metadata": {},
   "source": [
    "#  Intro to MPI (point-to-point)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a341be2e",
   "metadata": {},
   "source": [
    "## Contents\n",
    "\n",
    "\n",
    "In this notebook, we will learn the basics of parallel computing using the Message Passing Interface (MPI) from Julia. In particular, we will learn:\n",
    "\n",
    "- How to use point-to-point communication directives\n",
    "- Which are the pros and cons of several types of send and receive functions\n",
    "- Which are the common pitfalls when using point-to-point directives\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8862079b",
   "metadata": {},
   "source": [
    "## What is MPI ?\n",
    "\n",
    "- MPI stands for the \"Message Passing Interface\"\n",
    "- It is a standardized library specification for communication between parallel processes in distributed-memory systems.\n",
    "- It is the gold-standard for distributed computing in HPC systems since the 90s\n",
    "- It is huge: the MPI standard has more than 1k pages (see https://www.mpi-forum.org/docs/mpi-4.0/mpi40-report.pdf)\n",
    "- There are several implementations of this standard (OpenMPI, MPICH, IntelMPI)\n",
    "- The interface is in C and FORTRAN (C++ was deprecated)\n",
    "- There are Julia bindings via the package MPI.jl https://github.com/JuliaParallel/MPI.jl"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c31907f",
   "metadata": {},
   "source": [
    "### Before starting this notebook\n",
    "\n",
    "Read this paper to get an overview of the history and rationale behind MPI:\n",
    "\n",
    "J.J. Dongarra, S.W. Otto, M. Snir, and D. Walker, David. A message passing standard for MPP and workstations, *Commun. ACM*, 39(7), 84–90, 1996. DOI: [10.1145/233977.234000](https://doi.org/10.1145/233977.234000).\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99c6febb",
   "metadata": {},
   "source": [
    "### What is MPI.jl ?\n",
    "\n",
    "We will access MPI via the Julia bindings provided by the [`MPI.jl`]( https://github.com/JuliaParallel/MPI.jl) package. It is worth noting that:\n",
    "\n",
    "- MPI is not a Julia implementation of the MPI standard\n",
    "- It is just a wrapper to the C interface of MPI.\n",
    "- You need a C MPI installation in your system (MPI.jl downloads one for you when needed).\n",
    "- On a cluster (e.g. DAS-5), you want you use the MPI installation already available in the system.\n",
    "\n",
    "\n",
    "### Why MPI.jl?\n",
    "\n",
    "MPI.jl provides a convenient Julia API to access MPI. For instance, this is how you get the id (rank) of the current process.\n",
    "\n",
    "```julia\n",
    "comm = MPI.COMM_WORLD\n",
    "rank = MPI.Comm_rank(comm)\n",
    "```\n",
    "\n",
    "Internally, MPI.jl uses `ccall` which is a mechanism that allows you to call C functions from Julia. In this, example we are calling the C function `MPI_Comm_rank` from the underlying MPI installation.\n",
    "\n",
    "```julia\n",
    "comm = MPI.COMM_WORLD    \n",
    "rank_ref = Ref{Cint}()\n",
    "ccall((:MPI_Comm_rank, MPI.API.libmpi), Cint, (MPI.API.MPI_Comm, Ptr{Cint}), comm, rank_ref)\n",
    "rank = Int(rank_ref[])\n",
    "```\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c6c44e2d",
   "metadata": {},
   "source": [
    "If you are curious, run next cell to get more information about how `ccall` works."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f1f4c046",
   "metadata": {},
   "outputs": [],
   "source": [
    "? ccall"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e99c7676-989e-4e91-b65e-ebca2d5626a4",
   "metadata": {},
   "source": [
    "### Installing MPI in Julia\n",
    "\n",
    "MPI can be installed as any other Julia package using the package manager."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b44409e",
   "metadata": {},
   "outputs": [],
   "source": [
    "] add MPI"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "abc6f017",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Note:</b> Julia will download and install a MPI library for you, but it is also possible to use a MPI library already available in your system. This is useful, e.g., when running on HPC clusters. See the documentation of MPI.jl for further details. See more information in <a href=\"https://github.com/JuliaParallel/MPI.jl\">https://github.com/JuliaParallel/MPI.jl</a>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9db130db",
   "metadata": {},
   "source": [
    "## Minimal MPI program\n",
    "\n",
    "An MPI program must, at least, initialize and then finalize MPI. Finalizing MPI in the user code is optional in Julia as there is an internal mechanism that will finalize MPI for your. You can deactivate this mechanism by initializing MPI with `MPI.Init(finalize_atexit=false)`. Once finalized, MPI procedures cannot be used anymore except very few exceptions."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f15cfda",
   "metadata": {},
   "source": [
    "\n",
    "In Julia (option 1, recommended):\n",
    "\n",
    "```julia\n",
    "using MPI\n",
    "MPI.Init()\n",
    "# Your MPI programm here\n",
    "MPI.Finalize() # Optional\n",
    "```\n",
    "\n",
    "In Julia (option 2, advanced):\n",
    "\n",
    "```julia\n",
    "using MPI\n",
    "MPI.Init(finalize_atexit=false)\n",
    "# Your MPI programm here\n",
    "MPI.Finalize() # Mandatory\n",
    "```\n",
    "\n",
    "In C:\n",
    "\n",
    "```C\n",
    "#include <mpi.h>\n",
    "int main(int argc, char** argv) {\n",
    "    MPI_Init(NULL, NULL);\n",
    "    /* Your MPI Programm here */\n",
    "    MPI_Finalize();\n",
    "}\n",
    "```\n",
    "\n",
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Note:</b> Note that the Julia syntax is almost 1-to-1 to the C one. The key difference is that in Julia MPI routines are written as `MPI.X` where in C are written `MPI_X`.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87dfb768",
   "metadata": {},
   "source": [
    "### An incorrect MPI program\n",
    "\n",
    "It is very easy to end up with incorrect programs when using MPI if you are not careful following the rules. In this notebook, we will see many examples. For instance:\n",
    "\n",
    "```julia\n",
    "using MPI\n",
    "MPI.Init(;finalize_atexit=false)\n",
    "@assert rand(1:10) != 2\n",
    "MPI.Finalize()\n",
    "```\n",
    "\n",
    "This is incorrect. In some process `rand(1:10)` might be 2 and the program will stop without reaching `MPI.Finalize()` leading to an incorrect program."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65de4419",
   "metadata": {},
   "source": [
    "### Solving the issue"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a8ebeff",
   "metadata": {},
   "source": [
    "Premature finalization of a program is done with `MPI_Abort`.\n",
    "\n",
    "```julia\n",
    "using MPI\n",
    "MPI.Init()\n",
    "if rand(1:10) != 2\n",
    "    errorcode = -1\n",
    "    MPI.Abort(MPI.COMM_WORLD,errorcode)\n",
    "end\n",
    "MPI.Finalize()\n",
    "```\n",
    "\n",
    "There is no need to call `MPI_Abort` in all ranks. The MPI library will do its best to stop all MPI ranks even if `MPI_Abort` was called just on a single rank.\n",
    "\n",
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Note:</b> Processes are often called ranks, when working with MPI.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa7145bc",
   "metadata": {},
   "source": [
    "### Read the docs\n",
    "\n",
    "Not sure if an MPI routine needs to be called by all ranks? Read the documentation, specially the external links. Run the next cell, open an external link and read the documentation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7511de1b",
   "metadata": {},
   "outputs": [],
   "source": [
    "using MPI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a74c7c72",
   "metadata": {},
   "outputs": [],
   "source": [
    "? MPI.Finalize"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a534e3a2",
   "metadata": {},
   "source": [
    "## Basic information about MPI processes\n",
    "\n",
    "The following cells give information about MPI processes, such as the rank id, the total number of processes and the name of the host running the code. Before calling this functions one needs to initialize MPI."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96f7c14e",
   "metadata": {},
   "outputs": [],
   "source": [
    "MPI.Init()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48f89e38",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Note:</b> If you get some error or warning when initializing MPI, make sure that you started the notebook using `IJulia`. Go back to the first notebook for specific details.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe202985",
   "metadata": {},
   "source": [
    " Current rank (process) id"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bd8232f5",
   "metadata": {},
   "outputs": [],
   "source": [
    "comm = MPI.COMM_WORLD\n",
    "rank = MPI.Comm_rank(comm)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb480322",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Note:</b> Note that the rank ids start with 0.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dd40d1dc",
   "metadata": {},
   "source": [
    "Number of available processes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0befa408",
   "metadata": {},
   "outputs": [],
   "source": [
    "nranks = MPI.Comm_size(comm)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1eeaf81",
   "metadata": {},
   "source": [
    "Name of the current host"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ff01adcf",
   "metadata": {},
   "outputs": [],
   "source": [
    "MPI.Get_processor_name()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f1a502a3",
   "metadata": {},
   "source": [
    "Note that this note notebook is running on a single process. So using MPI will only make actual sense later when we add more processes."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "133327e2",
   "metadata": {},
   "source": [
    "### Hello-world example\n",
    "\n",
    "Using these functions we can create the a classic MPI hello world example. This example (or variations thereof) are used in practice to check how MPI ranks are mapped to available processing units in a given computing system.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a154b55e",
   "metadata": {},
   "outputs": [],
   "source": [
    "using MPI\n",
    "MPI.Init()\n",
    "comm = MPI.COMM_WORLD\n",
    "nranks = MPI.Comm_size(comm)\n",
    "rank = MPI.Comm_rank(comm)\n",
    "host = MPI.Get_processor_name()\n",
    "println(\"Hello from $host, I am process $rank of $nranks processes!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "baddbba1",
   "metadata": {},
   "source": [
    "### Hello world in C\n",
    "\n",
    "This is the equivalent code in C.\n",
    "\n",
    "```C\n",
    "#include <mpi.h>\n",
    "#include <stdio.h>\n",
    "int main(int argc, char** argv) {\n",
    "    MPI_Init(NULL, NULL);\n",
    "    int world_size;\n",
    "    MPI_Comm_size(MPI_COMM_WORLD, &world_size);\n",
    "    int world_rank;\n",
    "    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);\n",
    "    char processor_name[MPI_MAX_PROCESSOR_NAME];\n",
    "    int name_len;\n",
    "    MPI_Get_processor_name(processor_name, &name_len);\n",
    "    printf(\"Hello from %s, I am rank %d of %d ranks!\\n\",\n",
    "           processor_name, world_rank, world_size);\n",
    "    MPI_Finalize();\n",
    "}\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3901c57",
   "metadata": {},
   "source": [
    "## Running MPI code"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8376135d",
   "metadata": {},
   "source": [
    "### Creating MPI processes (aka ranks)\n",
    "\n",
    "MPI processes are created with the driver program `mpiexec`, which comes as part of an MPI installation:\n",
    "\n",
    "- `mpiexec` takes an application as argument, it creates different processes, and runs the application on these processes.\n",
    "- The application will typically call MPI directives to communicate between these ranks\n",
    "- In particular, the application can be `julia code.jl`, i.e., Julia running a given script `code.jl`.\n"
   ]
  },
  {
   "attachments": {
    "fig23.png": {
     "image/png": "[encoded data, 162228 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "a458c714",
   "metadata": {},
   "source": [
    " <div>\n",
    "<img src=\"attachment:fig23.png\"  align=\"left\" width=\"450\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "044aaeec",
   "metadata": {},
   "source": [
    "### Execution model\n",
    "\n",
    "- MPI programs are typically run with a Single Program Multiple Data (SPMD) model, which is a particular case of the SIMD model.\n",
    "- But the standard supports Multiple Program Multiple Data (MPMD), which is a particular case of the MIMD model."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f76fb65",
   "metadata": {},
   "source": [
    "### Hello world example\n",
    "\n",
    "Julia code typically needs to be in a file to run it in with MPI. Let's us write our hello world in a file. The next cell will create a file, and write some code in it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e03f35c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "code = raw\"\"\"\n",
    "using MPI\n",
    "MPI.Init()\n",
    "comm = MPI.COMM_WORLD\n",
    "nranks = MPI.Comm_size(comm)\n",
    "rank = MPI.Comm_rank(comm)\n",
    "host = MPI.Get_processor_name()\n",
    "println(\"Hello from $host, I am process $rank of $nranks processes!\")\n",
    "MPI.Finalize()\n",
    "\"\"\"\n",
    "filename = tempname()*\".jl\"\n",
    "write(filename,code)\n",
    "filename"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f13946dd",
   "metadata": {},
   "source": [
    "Now, we can run it"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dbe654dc",
   "metadata": {},
   "outputs": [],
   "source": [
    "using MPI\n",
    "run(`$(mpiexec()) -np 4 julia --project=. $filename`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "651f26ae",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Note:</b> Function `mpiexec` provided by `MPI.jl` is a convenient way of accessing the `mpiexec` program that matches the MPI installation used by Julia.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a958c015",
   "metadata": {},
   "source": [
    "### Another way to launch MPI code\n",
    "\n",
    "In the hello world example above we have created an auxiliary file to run the code with MPI. This can be annoying specially if you are working in a jupyter notebook. With this other syntax you can skip creating the auxiliary file. We use `quote` which is part of the [meta-programming capabilities of Julia](https://docs.julialang.org/en/v1/manual/metaprogramming/). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "359e569b",
   "metadata": {},
   "outputs": [],
   "source": [
    "code = quote\n",
    "    using MPI\n",
    "    MPI.Init()\n",
    "    comm = MPI.COMM_WORLD\n",
    "    nranks = MPI.Comm_size(comm)\n",
    "    rank = MPI.Comm_rank(comm)\n",
    "    host = MPI.Get_processor_name()\n",
    "    println(\"Hello from $host, I am process $rank of $nranks processes!\")\n",
    "    MPI.Finalize()\n",
    "end\n",
    "run(`$(mpiexec()) -np 4 julia --project=. -e $code`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ec1c52a",
   "metadata": {},
   "source": [
    "## Data availability"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c8a5e099",
   "metadata": {},
   "source": [
    "Note that mpiexec creates new processes which are different from the process running this notebook. In particular, these new processes will not see any variables or function definitions in the current notebook. So, the full MPI program needs to be in the source file passed to Julia or the quote block.\n",
    "\n",
    "The following cell will fail. Note that the same error message is displayed by all ranks, which makes difficult to read them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "16bb608a",
   "metadata": {},
   "outputs": [],
   "source": [
    "foo() = print(\"Hi there!\")\n",
    "code = quote\n",
    "    using MPI\n",
    "    MPI.Init()\n",
    "    foo()\n",
    "end\n",
    "run(`$(mpiexec()) -np 3 julia --project=. -e $code`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b455f98",
   "metadata": {},
   "source": [
    "So, the full MPI program needs to be in the source file passed to Julia or the quote block. In practice, long MPI programms are written as Julia packages using several files, which are then loaded by each MPI process. For our simple example, we just need to include the definition of `foo` inside the quote block."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b816659a",
   "metadata": {},
   "outputs": [],
   "source": [
    "code = quote\n",
    "    foo() = print(\"Hi there!\")\n",
    "    using MPI\n",
    "    MPI.Init()\n",
    "    foo()\n",
    "end\n",
    "run(`$(mpiexec()) -np 3 julia --project=. -e $code`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a37daef2",
   "metadata": {},
   "source": [
    "## Point-to-point communication\n",
    "\n",
    "Now we are up and running, and ready to start learning MPI communication primitives. In this notebook we will cover so-called point-to-point communication. In a later notebook we will also learn about collective primitives.\n",
    "\n",
    "MPI  provides point-to-point communication directives for arbitrary communication between processes. Point-to-point communications are two-sided: there is a sender and a receiver. Here, we will discuss different types of directives:\n",
    "\n",
    "- `MPI_Send`, and `MPI_Recv`: *complete (blocking) directives*\n",
    "- `MPI_Isend`, and `MPI_Irecv`: *incomplete (non-blocking) directives*\n",
    "- `MPI_Bsend`, `MPI_Ssend`, and `MPI_Rsend`: *advanced communication modes*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e515109",
   "metadata": {},
   "source": [
    "In all cases, these functions are used to send a message from a rank and receive it in another rank. See next picture."
   ]
  },
  {
   "attachments": {
    "fig_p2p.png": {
     "image/png": "[encoded data, 91880 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "14674ca9",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"attachment:fig_p2p.png\"  align=\"left\" width=\"350\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ead20fc0",
   "metadata": {},
   "source": [
    "## Blocking send and receive\n",
    "\n",
    "Let's start with the \"standard\" blocking send and receive.\n",
    "\n",
    "In Julia:\n",
    "\n",
    "```julia\n",
    "MPI.Send(sndbuf, comm; dest, tag)\n",
    "_, status = MPI.Recv!(rcvbuf, comm, MPI.Status; source, tag)\n",
    "```\n",
    "In C:\n",
    "```C\n",
    "int MPI_Send(const void *sndbuf, int count, MPI_Datatype datatype, int dest,\n",
    "    int tag, MPI_Comm comm)\n",
    "int MPI_Recv(void *rcvbuf, int count, MPI_Datatype datatype,\n",
    "    int source, int tag, MPI_Comm comm, MPI_Status *status)\n",
    "```\n",
    "\n",
    "The key arguments are:\n",
    "\n",
    "* `sndbuf` data to send.\n",
    "* `rcvbuf` space to store the incoming data.\n",
    "* `source` rank of the sender.\n",
    "* `dest` rank of the receiver.\n",
    "* `tag`. Might be used to distinguish between different kinds of messages from the same sender to the same receiver (similar to the \"subject\" in an email).\n",
    "\n",
    "\n",
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Note:</b> Note that the C interface provides additional arguments `MPI_Datatype` (type of data to send/receive) and `count` (number of items to send/receive). In Julia, send and receive buffers are usually arrays or references, from which the data type and the count can be inferred. This is true for many other MPI functions.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be4fae1c",
   "metadata": {},
   "source": [
    "### Example"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c2301992",
   "metadata": {},
   "source": [
    "Send 5 integers from rank 2 to rank 3. Note that the same code will be executed in all ranks by `mpiexec`. This is why we need to use if statements to select specific ranks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "61fe5db3",
   "metadata": {},
   "outputs": [],
   "source": [
    "code = quote\n",
    "    using MPI\n",
    "    MPI.Init()\n",
    "    comm = MPI.COMM_WORLD\n",
    "    rank = MPI.Comm_rank(comm)\n",
    "    if rank == 2\n",
    "        sndbuf = [1,2,3,5,8]\n",
    "        MPI.Send(sndbuf, comm; dest=3, tag=0)\n",
    "    end\n",
    "    if rank == 3\n",
    "        rcvbuf = zeros(Int,5) # Allocate space for the incoming message\n",
    "        MPI.Recv!(rcvbuf, comm, MPI.Status; source=2, tag=0)\n",
    "        @show rcvbuf\n",
    "    end\n",
    "end\n",
    "run(`$(mpiexec()) -np 4 julia --project=. -e $code`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee680aa5",
   "metadata": {},
   "source": [
    "## Any source, any tag\n",
    "\n",
    "We can use\n",
    "\n",
    "* `source = MPI.ANY_SOURCE`\n",
    "* `tag = MPI.ANY_TAG`\n",
    "\n",
    "If we want to receive messages from any source and/or with any tag.\n",
    "\n",
    "\n",
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Note:</b> These can only be used by the receiver, not the sender. Moreover there is no option to send to any destination.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f0cb6c8",
   "metadata": {},
   "source": [
    "### Example"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2add5065",
   "metadata": {},
   "source": [
    "Send 5 integers from rank 2 to rank 3. Since there is only one sender and only one message from this sender, we can receive from any source and with any tag."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ccdf660a",
   "metadata": {},
   "outputs": [],
   "source": [
    "code = quote\n",
    "    using MPI\n",
    "    MPI.Init()\n",
    "    comm = MPI.COMM_WORLD\n",
    "    rank = MPI.Comm_rank(comm)\n",
    "    if rank == 2\n",
    "        sndbuf = [1,2,3,5,8]\n",
    "        MPI.Send(sndbuf, comm; dest=3, tag=0)\n",
    "    end\n",
    "    if rank == 3\n",
    "        rcvbuf = zeros(Int,5)\n",
    "        source = MPI.ANY_SOURCE\n",
    "        tag = MPI.ANY_TAG\n",
    "        MPI.Recv!(rcvbuf, comm, MPI.Status; source, tag)\n",
    "        @show rcvbuf\n",
    "    end\n",
    "end\n",
    "run(`$(mpiexec()) -np 4 julia --project=. -e $code`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7833da72",
   "metadata": {},
   "source": [
    "## MPI_Status\n",
    "\n",
    "When using `MPI.ANY_SOURCE` and `MPI.ANY_TAG` it might be still useful to know which was the sender and which tag was used. This information is given by a `MPI.Status` object.\n",
    "\n",
    "\n",
    "```julia\n",
    "_, status = MPI.Recv!(rcvbuf, comm, MPI.Status; source, tag)\n",
    "status.source # Gives the source\n",
    "status.tag # Gives the tag\n",
    "```\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4618ad58",
   "metadata": {},
   "source": [
    "### Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f037032",
   "metadata": {},
   "outputs": [],
   "source": [
    "code = quote\n",
    "    using MPI\n",
    "    MPI.Init()\n",
    "    comm = MPI.COMM_WORLD\n",
    "    rank = MPI.Comm_rank(comm)\n",
    "    if rank == 2\n",
    "        sndbuf = [1,2,3,5,8]\n",
    "        MPI.Send(sndbuf, comm; dest=3, tag=0)\n",
    "    end\n",
    "    if rank == 3\n",
    "        rcvbuf = zeros(Int,5)\n",
    "        source = MPI.ANY_SOURCE\n",
    "        tag = MPI.ANY_TAG\n",
    "        _, status = MPI.Recv!(rcvbuf, comm, MPI.Status; source, tag)\n",
    "        @show rcvbuf\n",
    "        @show status.source\n",
    "        @show status.tag\n",
    "    end\n",
    "end\n",
    "run(`$(mpiexec()) -np 4 julia --project=. -e $code`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "590bc407",
   "metadata": {},
   "source": [
    "## MPI_Probe\n",
    "\n",
    "Note that we need to provide a receive buffer with the right size, but it general we do not know which is the size of the incoming message. This can be solved using an `MPI_Probe`. It works similar to `MPI_Recv`, but instead of receiving the message only receives information about the message (source, tag, and also message size). Like for `MPI_Recv`, `MPI_Probe` will wait (block) until a matching send is posted. More information about the blocking behavior will be given below.\n",
    "\n",
    "\n",
    "`MPI_Probe` provides an `MPI_Status` object. We can get the message size from the status object using function `MPI_Get_count`. We can also get the source and tag from the status object as shown before.\n",
    "\n",
    "In Julia:\n",
    "```julia\n",
    "status = MPI.Probe(comm,MPI.Status; source, tag)\n",
    "count = MPI.Get_count(status, T)\n",
    "```\n",
    "In C:\n",
    "```C\n",
    "int MPI_Probe(int source, int tag, MPI_Comm comm, MPI_Status *status)\n",
    "int MPI_Get_count(const MPI_Status *status, MPI_Datatype datatype, int *count)\n",
    "```\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "517d052e",
   "metadata": {},
   "source": [
    "### Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1b54af36",
   "metadata": {},
   "outputs": [],
   "source": [
    "code = quote\n",
    "    using MPI\n",
    "    MPI.Init()\n",
    "    comm = MPI.COMM_WORLD\n",
    "    rank = MPI.Comm_rank(comm)\n",
    "    if rank == 2\n",
    "        sndbuf = [1,2,3,5,8]\n",
    "        MPI.Send(sndbuf, comm; dest=3, tag=0)\n",
    "    end\n",
    "    if rank == 3\n",
    "        source = MPI.ANY_SOURCE\n",
    "        tag = MPI.ANY_TAG\n",
    "        status = MPI.Probe(comm,MPI.Status; source, tag)\n",
    "        count = MPI.Get_count(status,Int) # Get incomming message length\n",
    "        println(\"I am about to receive $count integers.\")\n",
    "        rcvbuf = zeros(Int,count) # Allocate        \n",
    "        MPI.Recv!(rcvbuf, comm, MPI.Status; source, tag)\n",
    "        @show rcvbuf\n",
    "    end\n",
    "end\n",
    "run(`$(mpiexec()) -np 4 julia --project=. -e $code`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d0add95c",
   "metadata": {},
   "source": [
    "## Complete operations\n",
    "\n",
    "Functions `MPI_Send`, `MPI_Recv`, and `MPI_Probe` are *complete* operations, meaning that their argument can be used once the function returns.\n",
    "\n",
    "In particular:\n",
    "\n",
    "- It is safe to re-write the send buffer with new data once `MPI_Send` returns.\n",
    "- The received message is guaranteed to be fully available in the receive buffer once `MPI_Recv` returns."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed0c4d76",
   "metadata": {},
   "source": [
    "### Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2299bf78",
   "metadata": {},
   "outputs": [],
   "source": [
    "code = quote\n",
    "    using MPI\n",
    "    MPI.Init()\n",
    "    comm = MPI.COMM_WORLD\n",
    "    rank = MPI.Comm_rank(comm)\n",
    "    if rank == 2\n",
    "        sndbuf = [1,2,3,5,8]\n",
    "        MPI.Send(sndbuf, comm; dest=3, tag=0)\n",
    "        sndbuf .= 0 # This is fine. Send has returned.\n",
    "    end\n",
    "    if rank == 3\n",
    "        rcvbuf = zeros(Int,5)\n",
    "        MPI.Recv!(rcvbuf, comm, MPI.Status; source=2, tag=0)\n",
    "        # recvbuf will have the incomming message fore sure. Recv! has returned.\n",
    "        @show rcvbuf\n",
    "    end\n",
    "end\n",
    "run(`$(mpiexec()) -np 4 julia --project=. -e $code`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "04bdb01f",
   "metadata": {},
   "source": [
    "## Blocking operations\n",
    "\n",
    "`MPI_Recv` and `MPI_Probe` are *blocking* operations. This means that they will wait for a matching send.\n",
    "\n",
    "\n",
    "\n",
    "`MPI_Send` is  *informally* called a blocking send, but this is not accurate. `MPI_Send` might or not wait for a matching `MPI_Recv`. Assuming that `MPI_Send` will block waiting for a matching receive is erroneous. I.e., we cannot assume that `MPI_Send` has synchronization side effects with the receiver process. However, assuming that `MPI_Send` will not block is also erroneous. Look into the following example (which in fact is an incorrect MPI program). `MPI_Send` only guarantees that the send buffer can be reused when function returns (complete operation)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "59fcac63",
   "metadata": {},
   "source": [
    "### Incorrect program\n",
    "\n",
    "The following program will or will not work depending on the underlying implementation and other factors (i.e. this program has undefined behavior). On my laptop, it works with `n=1`, but leads to a dead lock when `n=10000`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42fb8089",
   "metadata": {},
   "outputs": [],
   "source": [
    "code = quote\n",
    "    using MPI\n",
    "    MPI.Init()\n",
    "    comm = MPI.COMM_WORLD\n",
    "    rank = MPI.Comm_rank(comm)\n",
    "    n = 1\n",
    "    sndbuf = fill(rank,n)\n",
    "    rcvbuf = zeros(Int,n)\n",
    "    if rank == 2\n",
    "        MPI.Send(sndbuf, comm; dest=3, tag=0)\n",
    "        MPI.Recv!(rcvbuf, comm, MPI.Status; source=3, tag=0)\n",
    "    end\n",
    "    if rank == 3\n",
    "        MPI.Send(sndbuf, comm; dest=2, tag=0)\n",
    "        MPI.Recv!(rcvbuf, comm, MPI.Status; source=2, tag=0)\n",
    "    end\n",
    "    @show (rcvbuf[1],rank)\n",
    "end\n",
    "run(`$(mpiexec()) -np 4 julia --project=. -e $code`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "42402ec1",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Tip:</b> You can stop the cell from runnig with Kernel > Interrupt. You might need to click in Interrupt 2 times.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "94c39af5",
   "metadata": {},
   "source": [
    "## To buffer or not to buffer outbound messages?\n",
    "\n",
    "There are two key competing requirements that face implementations of `MPI_Send`.\n",
    "\n",
    "1. One might want to minimize synchronization time. This is often achieved by copying the outgoing message in an internal buffer and returning from the `MPI_Send` as soon as possible, without waiting for a matching `MPI_Recv`.\n",
    "2. One might want to avoid data copies (e.g. for large messages). In this case, one needs to wait for a matching receive and return from the `MPI_Send` when the data has been sent.\n",
    "\n",
    "Thus, there is a trade-off between memory copied (buffering) and synchronization (wait) time. One cannot minimize both at the same time unfortunately."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b2cb0a43",
   "metadata": {},
   "source": [
    "## Fixing cyclic dependencies\n",
    "\n",
    "Returning to the incorrect program seen before. Remember that on my laptop it worked for `n=1`, but it failed for `n=10000`.  For `n=1` the MPI implementation provably decided that the best trade-off was to buffer the small message and return from the `MPI_Send` as soon as possible. For the large message (`n=10000`) it provably decided to wait for a matching receive in order to avoid copying data. In this case, both ranks were  blocked on the call to `MPI_Send` and the receives were never posted leading to a dead lock.\n",
    "\n",
    "We can fix these cyclic dependences by smartly ordering the sends and the receives:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94c8d5e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "code = quote\n",
    "    using MPI\n",
    "    MPI.Init()\n",
    "    comm = MPI.COMM_WORLD\n",
    "    rank = MPI.Comm_rank(comm)\n",
    "    n = 10000\n",
    "    sndbuf = fill(rank,n)\n",
    "    rcvbuf = zeros(Int,n)\n",
    "    if rank == 2\n",
    "        # We first send and then receive\n",
    "        MPI.Send(sndbuf, comm; dest=3, tag=0)\n",
    "        MPI.Recv!(rcvbuf, comm, MPI.Status; source=3, tag=0)\n",
    "    end\n",
    "    if rank == 3\n",
    "        # We first receive and then send\n",
    "        MPI.Recv!(rcvbuf, comm, MPI.Status; source=2, tag=0)\n",
    "        MPI.Send(sndbuf, comm; dest=2, tag=0)\n",
    "    end\n",
    "    @show (rcvbuf[1],rank)\n",
    "end\n",
    "run(`$(mpiexec()) -np 4 julia --project=. -e $code`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b37ed85",
   "metadata": {},
   "source": [
    "Another solution is to use `MPI_Sendrecv`, which will handle the ordering for us."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c0c84f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "code = quote\n",
    "    using MPI\n",
    "    MPI.Init()\n",
    "    comm = MPI.COMM_WORLD\n",
    "    rank = MPI.Comm_rank(comm)\n",
    "    n = 10000\n",
    "    sndbuf = fill(rank,n)\n",
    "    rcvbuf = zeros(Int,n)\n",
    "    if rank == 2\n",
    "        MPI.Sendrecv!(sndbuf,rcvbuf, comm;dest=3,source=3,sendtag=0,recvtag=0)\n",
    "    end\n",
    "    if rank == 3\n",
    "        MPI.Sendrecv!(sndbuf,rcvbuf, comm;dest=2,source=2,sendtag=0,recvtag=0)\n",
    "    end\n",
    "    @show (rcvbuf[1],rank)\n",
    "end\n",
    "run(`$(mpiexec()) -np 4 julia --project=. -e $code`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "228a2067",
   "metadata": {},
   "source": [
    "## Communication modes\n",
    "\n",
    "What if we as users want to decide when to buffer a message or when to avoid data copies? This is provided by so-called *communication* modes. There are four modes: standard, buffered, synchronous, and ready provided by the respective functions `MPI_Send`, `MPI_Bsend`, `MPI_Ssend`, and `MPI_Rsend`, respectively. \n",
    "\n",
    "\n",
    "All these MPI functions are *complete* MPI operations, and therefore, it is safe to re-write the send buffer once the corresponding send returns. All these send types are matched with an `MPI_Recv`. I.e., there is no `MPI_Brecv`, `MPI_Srecv`, `MPI_Rrecv`. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4fca501c",
   "metadata": {},
   "source": [
    " \n",
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Note:</b>  `MPI_Bsend`, `MPI_Ssend`, and `MPI_Rsend` are not exposed in the Julia bindings via a high-level interface like for `MPI.Send`, but they can be accessed using the low-level bindings in the submodule `MPI.API` (not shown in this notebook).\n",
    "</div>\n",
    " \n",
    " "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "126ce58c",
   "metadata": {},
   "source": [
    "### Standard mode\n",
    "\n",
    "* Function `MPI_Send`.\n",
    "* Programmer cannot make any assumptions whether the message is buffered or not. This is up to the system.\n",
    "* Assuming that `MPI_Send` does not block because it copies the message into a buffer is erroneous (as the example above).\n",
    "* Assuming that `MPI_Send` will block waiting for a matching receive is also incorrect. \n",
    "* Assuming that a matching receive started when `MPI_Send`returns is also incorrect (no synchronization guarantee)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "014ef71f",
   "metadata": {},
   "source": [
    "### Buffered mode\n",
    "\n",
    "* Function `MPI_Bsend`.\n",
    "* Programmer provides additional internal buffer space with function `MPI_Buffer_attach`.\n",
    "* `MPI_Bsend` completes when message is copied into a local buffer.\n",
    "* Erroneous if buffer space is insufficient.\n",
    "* It does not wait for a matching receive."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf456a3e",
   "metadata": {},
   "source": [
    "### Synchronous mode\n",
    "\n",
    "* Function `MPI_Ssend`.\n",
    "* It waits for a matching receive and it is guaranteed that the receive started (synchronization guarantee).\n",
    "* No extra data copy.\n",
    "* Easy to get deadlocks.\n",
    "* It can be started whether or not a matching receive was posted."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a1bd72c3",
   "metadata": {},
   "source": [
    "### Ready mode\n",
    "\n",
    "* Function `MPI_Rsend`.\n",
    "* It may be started only if the matching receive is already posted. This allows the underlying implementation to skip some operations, such as a [handshake](https://en.wikipedia.org/wiki/Handshake_(computing)).\n",
    "* Erroneous if there is no matching receive yet.\n",
    "* Otherwise, the same as the synchronous `MPI_Ssend`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a206008",
   "metadata": {},
   "source": [
    " \n",
    "For further information about the communication modes, refer to [this section](https://www.mpi-forum.org/docs/mpi-2.2/mpi22-report/node53.htm) of the MPI standard.\n",
    " "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e12f3d48",
   "metadata": {},
   "source": [
    "## Non-blocking send and receive\n",
    "\n",
    "\n",
    "In addition to all the send and receive function seen so far, MPI also provide two extra functions: `MPI_Isend` and `MPI_Irecv`.\n",
    "\n",
    "In Julia:\n",
    "\n",
    "```julia\n",
    "request = MPI.Isend(sndbuf, comm; dest, tag)\n",
    "request = MPI.Irecv!(rcvbuf, comm; source, tag)\n",
    "```\n",
    "\n",
    "In C:\n",
    "```C\n",
    "int MPI_Isend(const void *sndbuf, int count, MPI_Datatype datatype, int dest,\n",
    "    int tag, MPI_Comm comm, MPI_Request *request)\n",
    "int MPI_Irecv(void *rcvbuf, int count, MPI_Datatype datatype,\n",
    "    int source, int tag, MPI_Comm comm, MPI_Request *request)\n",
    "\n",
    "```\n",
    "\n",
    "These functions are *non-blocking* as they return immediately without waiting for a matching send or receive."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64938903",
   "metadata": {},
   "source": [
    "## Incomplete operations\n",
    "\n",
    "Functions `MPI_Isend` and `MPI_Irecv` are *incomplete* operations, hence the `I` in `MPI_Isend` and `MPI_Irecv`.  This means that, when these functions return, there is no guarantee that the underlying operation has finished. Function `MPI_Wait` should be used to wait for completion of the send and/or receive.\n",
    "\n",
    "In particular:\n",
    "\n",
    "- One needs to wait for completion before reseting the send buffer\n",
    "- One needs to wait for completion before using the receive buffer\n",
    "\n",
    "Otherwise your program will be erroneous.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c52a5959",
   "metadata": {},
   "source": [
    "## Latency hiding\n",
    "\n",
    "One of the key benefits of using `MPI_Isend` and `MPI_Irecv` is that they allow one to overlap communication and computation, also called as latency-hiding. For instance, one can post an `MPI_Irecv` to start receiving a message, which will return without waiting for a matching send. One can do local work, while waiting for a matching send and while the message is transferred. And finally, one calls `MPI_Wait` to wait for the completion of the receive operation.\n",
    "\n",
    "\n",
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Note:</b>  `MPI_Bsend` also provides a way of doing latency hiding on the send side (at the expense of copying the message). `MPI_Isend` allows you doing latency hiding on the send side without copying data, and `MPI_Irecv` allows you doing latency hiding on the receive side.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85903e61",
   "metadata": {},
   "source": [
    "### Example\n",
    "\n",
    "Send 5 integers from rank 2 to rank 3. Both ranks do some work while messages are being communicated."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42284c69",
   "metadata": {},
   "outputs": [],
   "source": [
    "code = quote\n",
    "    using MPI\n",
    "    MPI.Init()\n",
    "    work() = sum(rand(1000))\n",
    "    comm = MPI.COMM_WORLD\n",
    "    rank = MPI.Comm_rank(comm)\n",
    "    if rank == 2\n",
    "        sndbuf = [1,2,3,5,8]\n",
    "        request = MPI.Isend(sndbuf, comm; dest=3, tag=0)\n",
    "        work() # Overlap local work with communication / synchronization \n",
    "        MPI.Wait(request)\n",
    "    end\n",
    "    if rank == 3\n",
    "        rcvbuf = zeros(Int,5)\n",
    "        request = MPI.Irecv!(rcvbuf, comm; source=2, tag=0)\n",
    "        work()  # Overlap local work with communication / synchronization\n",
    "        MPI.Wait(request)\n",
    "        @show rcvbuf\n",
    "    end\n",
    "end\n",
    "run(`$(mpiexec()) -np 4 julia --project=. -e $code`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0180c576",
   "metadata": {},
   "source": [
    "### Incorrect program\n",
    "\n",
    "This program in incorrect both on the send and the receive side. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52991807",
   "metadata": {},
   "outputs": [],
   "source": [
    "code = quote\n",
    "    using MPI\n",
    "    MPI.Init()\n",
    "    comm = MPI.COMM_WORLD\n",
    "    rank = MPI.Comm_rank(comm)\n",
    "    if rank == 2\n",
    "        sndbuf = [1,2,3,5,8]\n",
    "        request = MPI.Isend(sndbuf, comm; dest=3, tag=0)\n",
    "        sndbuf .= 10 # We cannot set the sndbuf before MPI.Wait.\n",
    "        MPI.Wait(request)\n",
    "    end\n",
    "    if rank == 3\n",
    "        rcvbuf = zeros(Int,5)\n",
    "        request = MPI.Irecv!(rcvbuf, comm; source=2, tag=0)\n",
    "        @show rcvbuf  # Not guaranteed to have the correct value.\n",
    "        MPI.Wait(request)\n",
    "    end\n",
    "end\n",
    "run(`$(mpiexec()) -np 4 julia --project=. -e $code`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4cc264f1",
   "metadata": {},
   "source": [
    "## MPI_Iprobe\n",
    "\n",
    "Remember that we used `MPI_Probe` to query for the size of an incoming message. However, if we use `MPI_Probe` we miss the opportunity to do local work before a matching send started, i.e. we cannot do latency hiding.\n",
    "\n",
    "This can be fixed using an `MPI_Iprobe`, i.e., an incomplete probe (aka a non-blocking probe). It allows us to check for incoming messages without blocking.\n",
    "\n",
    "In Julia:\n",
    "```julia\n",
    "ismsg, status = MPI.Iprobe(comm, MPI.Status; source, tag)\n",
    "```\n",
    "\n",
    "In C:\n",
    "```C\n",
    "int MPI_Iprobe(int source, int tag, MPI_Comm comm, int *ismsg,\n",
    "    MPI_Status *status)\n",
    "```\n",
    "\n",
    "Function `MPI_Iprobe` returns immediately without waiting for a matching send. The value of `ismsg` tells if a send was posted or not. If there was a send, the `status` object can be used to get information about the incoming message as we saw before."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05a72541",
   "metadata": {},
   "source": [
    "### Example\n",
    "\n",
    "Rank 2 sleeps for some time before the send starts. On the receive side, we will block on the call to `MPI_Probe` waiting for the send to start."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03b11966",
   "metadata": {},
   "outputs": [],
   "source": [
    "code = quote\n",
    "    using MPI\n",
    "    MPI.Init()\n",
    "    work() = sum(rand(1000))\n",
    "    comm = MPI.COMM_WORLD\n",
    "    rank = MPI.Comm_rank(comm)\n",
    "    if rank == 2\n",
    "        sleep(5) # Sleep 5 seconds\n",
    "        sndbuf = [1,2,3,5,8]\n",
    "        request = MPI.Isend(sndbuf, comm; dest=3, tag=0)\n",
    "        MPI.Wait(request)\n",
    "    end\n",
    "    if rank == 3\n",
    "        # We are going to wait here for about 5 seconds\n",
    "        # Missing the opportunity to do some useful work\n",
    "        status = MPI.Probe(comm,MPI.Status; source=2, tag=0)\n",
    "        count = MPI.Get_count(status,Int)\n",
    "        rcvbuf = zeros(Int,count)\n",
    "        request = MPI.Irecv!(rcvbuf, comm; source=2, tag=0)\n",
    "        work()\n",
    "        MPI.Wait(request)\n",
    "        @show rcvbuf\n",
    "    end\n",
    "end\n",
    "run(`$(mpiexec()) -np 4 julia --project=. -e $code`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6761b4fa",
   "metadata": {},
   "source": [
    "This other version uses  `MPI_Iprobe` to do some local work wile waiting for the incoming message."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75fdb2b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "code = quote\n",
    "    using MPI\n",
    "    MPI.Init()\n",
    "    work() = sum(rand(1000))\n",
    "    comm = MPI.COMM_WORLD\n",
    "    rank = MPI.Comm_rank(comm)\n",
    "    if rank == 2\n",
    "        sleep(5) # Sleep 5 seconds\n",
    "        sndbuf = [1,2,3,5,8]\n",
    "        request = MPI.Isend(sndbuf, comm; dest=3, tag=0)\n",
    "        MPI.Wait(request)\n",
    "    end\n",
    "    if rank == 3\n",
    "        while true\n",
    "            ismsg, status = MPI.Iprobe(comm, MPI.Status; source=2, tag=0)\n",
    "            if ismsg # If the send started, get message size and start the receive\n",
    "                count = MPI.Get_count(status,Int)\n",
    "                rcvbuf = zeros(Int,count)\n",
    "                reqrcv = MPI.Irecv!(rcvbuf, comm; source=2, tag=0)\n",
    "                work()\n",
    "                MPI.Wait(reqrcv)\n",
    "                @show rcvbuf\n",
    "                break\n",
    "            end\n",
    "            work() # Otherwise do work while waiting for an incoming message.\n",
    "        end\n",
    "    end\n",
    "end\n",
    "run(`$(mpiexec()) -np 4 julia --project=. -e $code`);"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30fc748f",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "We have seen different ways of sending and receiving messages with MPI, each one with its pros and cons. You as user should decide which is the best option for a given problem. We also learned how to get information about an incoming messages with `MPI_Status`, `MPI_Probe`, and `MPI_Iprobe`. In addition, we saw how easy is to write incorrect programs with if you do not follow the semantics of the MPI operations properly.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d02f935d",
   "metadata": {},
   "source": [
    "## Exercises"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd491de3",
   "metadata": {},
   "source": [
    "### Exercise 1\n",
    "\n",
    "Implement the parallel matrix-matrix multiplication (Algorithm 3) in previous notebook using MPI instead of `Distributed`. Use this function signature:\n",
    "\n",
    "```julia\n",
    "function matmul_mpi_3!(C,A,B)\n",
    "```\n",
    "\n",
    "Assume that the input matrices `A` and `B` are given only on rank 0, the other ranks get dummy empty matrices to save memory. You need to communicate the required parts to other ranks. For simplicity you can assume that `A` and `B` are square matrices and that the number of rows is a multiple of the number of processes (on rank 0). The result `C` should be overwritten only on rank 0. You can use the following cell to implement and check your result. Copy the code below to a file called `ex1.jl`. Modify the file (e.g. with vscode).  Run it from the Julia REPL using the `run` function as explained in the [Getting Started tutorial](https://www.francescverdugo.com/XM_40017/dev/getting_started_with_julia/#Running-MPI-code). Don't try to implement complex MPI code in a Jupyter notebook."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4fa53366",
   "metadata": {},
   "source": [
    "```julia\n",
    "# ex1.jl (begin)\n",
    "using MPI\n",
    "MPI.Init()\n",
    "function matmul_mpi_3!(C,A,B)\n",
    "    # Implement here\n",
    "end\n",
    "function testit(load)\n",
    "    comm = MPI.COMM_WORLD\n",
    "    rank = MPI.Comm_rank(comm)\n",
    "    if rank == 0\n",
    "        P = MPI.Comm_size(comm)\n",
    "        N = load*P\n",
    "    else\n",
    "        N = 0\n",
    "    end\n",
    "    A = rand(N,N)\n",
    "    B = rand(N,N)\n",
    "    C = similar(A)\n",
    "    matmul_mpi_3!(C,A,B)\n",
    "    if rank == 0\n",
    "        if !(C ≈ A*B)\n",
    "            println(\"Test failed 😢\")\n",
    "        else\n",
    "            println(\"Test passed 🥳\")\n",
    "        end\n",
    "    end\n",
    "end\n",
    "testit(100)\n",
    "# ex1.jl (end)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8e1c623",
   "metadata": {},
   "source": [
    "### Exercise 2\n",
    "\n",
    "Implement this \"simple\" algorithm (the telephone game):\n",
    "\n",
    "Rank 0 generates a message (an integer). Rank 0 sends the message to rank 1. Rank 1 receives the message, increments the message by 1, and sends the result to rank 2. Rank 2 receives the message, increments the message by 1, and sends the result to rank 3. Etc. The last rank sends back the message to rank 0 closing the ring. See the next figure. Implement the communications using MPI. Do not use `Distributed`. Use a text editor and the Julia REPL. Do not try to implement the code in a notebook.\n"
   ]
  },
  {
   "attachments": {
    "g5148.png": {
     "image/png": "[encoded data, 97648 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "d474d781",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"attachment:g5148.png\"  align=\"left\" width=\"320\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e8f6e6a",
   "metadata": {},
   "source": [
    "# License\n",
    "\n",
    "This notebook is part of the course [Programming Large Scale Parallel Systems](https://www.francescverdugo.com/XM_40017) at Vrije Universiteit Amsterdam and may be used under a [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) license."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Julia 1.10.0",
   "language": "julia",
   "name": "julia-1.10"
  },
  "language_info": {
   "file_extension": ".jl",
   "mimetype": "application/julia",
   "name": "julia",
   "version": "1.10.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
