{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "914c7250",
   "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\n",
    "\n",
    "# Partial Differential Equations (PDEs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "afbe96e7",
   "metadata": {},
   "source": [
    "## Contents\n",
    "\n",
    "In this notebook, we will learn\n",
    "\n",
    "- Key concepts for the solution of PDEs on large-scale computers\n",
    "- What is a preconditioner\n",
    "- What is a multi-grid solver\n",
    "- Parallelization of conjugate gradient method\n",
    "- Distributed sparse matrix-vector product"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a343cca6",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-info\">\n",
    "<b>Note:</b> Do not forget to execute the cell below before starting this notebook! \n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "821ac5e2",
   "metadata": {},
   "outputs": [],
   "source": [
    "using Printf\n",
    "function answer_checker(answer,solution)\n",
    "    if answer == solution\n",
    "        \"🥳 Well done! \"\n",
    "    else\n",
    "        \"It's not correct. Keep trying! 💪\"\n",
    "    end |> println\n",
    "end\n",
    "pdes_check_0(answer)=answer_checker(answer,\"f\")\n",
    "pdes_check_1(answer)=answer_checker(answer, \"b\")\n",
    "pdes_check_2(answer)=answer_checker(answer, \"c\")\n",
    "pdes_check_3(answer)=answer_checker(answer, \"d\")\n",
    "pdes_check_4(answer)=answer_checker(answer, \"a\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da4d45cd",
   "metadata": {},
   "source": [
    "## Mini project\n",
    "\n",
    "For the demonstration of different numberical methods we will use the example project of simulating the temperature distribution in a closed room. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "924de06a",
   "metadata": {},
   "source": [
    "### Problem statement\n",
    "\n",
    "Given the temperature at the boundary of a room, predict the temperature at any point in the room. The illustration below shows the temperature at different intervals of the room boundary (including a window and a heater). \n",
    "\n",
    "We will discuss the serial implementation first and learn how to compute it in parallel afterwards."
   ]
  },
  {
   "attachments": {
    "g927.png": {
     "image/png": "[encoded data, 24280 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "570d7e1f",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 24280 characters]\" align=\"left\" width=\"200\"/>\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3168a06c",
   "metadata": {},
   "source": [
    "### Laplace equation\n",
    "\n",
    "Assuming that the room is isolated, it can be shown that the temperature in the room can be described using the [Laplace equation](https://en.wikipedia.org/wiki/Laplace%27s_equation)\n",
    "\n",
    "\n",
    "$$\\dfrac{\\partial^2 u(x,y)}{\\partial x^2} + \\dfrac{\\partial^2 u(x,y)}{\\partial y^2} = 0.$$\n"
   ]
  },
  {
   "attachments": {
    "laplace.jpg": {
     "image/jpeg": "[encoded data, 108592 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "1b32658b",
   "metadata": {},
   "source": [
    " Pierre-Simon, marquis de Laplace (1749-1827)\n",
    " \n",
    " *Picture from wikipedia*\n",
    "\n",
    "<div>\n",
    "<img src=\"attachment:laplace.jpg\" align=\"left\" width=\"200\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3602f79",
   "metadata": {},
   "source": [
    "### Boundary value problem (BVP)\n",
    "\n",
    "$\\dfrac{\\partial^2 u}{\\partial x^2} + \\dfrac{\\partial^2 u}{\\partial y^2} = 0 \\text{ in the room}$\n",
    "\n",
    "$u = 5 \\text{ on the window}$\n",
    "\n",
    "$u = 40 \\text{ on the heater}$\n",
    "\n",
    "$u = 20 \\text{ on the walls}$\n"
   ]
  },
  {
   "attachments": {
    "g1775.png": {
     "image/png": "[encoded data, 50400 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "b3e74d18",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 50400 characters]\" align=\"left\" width=\"200\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "60e01813",
   "metadata": {},
   "source": [
    "### Numerical methods for PDEs\n",
    "\n",
    "There are several methods for solving PDEs: \n",
    "\n",
    "- Finite difference method (FDM)\n",
    "- Finite element method (FEM)\n",
    "- Finite volume method (FVM)\n",
    "- Boundary element method (BEM)\n",
    "- Meshfree methods\n",
    "\n",
    "All of them follow the same main idea: to transform a PDE into a system of linear equations. The problem is first discretized into a computational mesh. The solution to the PDE at any point of the mesh is then given by the solution for vector x. \n"
   ]
  },
  {
   "attachments": {
    "g3373.png": {
     "image/png": "[encoded data, 518848 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "b3ba6f5b",
   "metadata": {},
   "source": [
    "\n",
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 518848 characters]\" align=\"left\" width=\"400\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e17d1c5f",
   "metadata": {},
   "source": [
    "### Finite Difference method\n",
    "\n",
    "To solve the temperature distribution in the room, we choose the Finite Difference method. The advantage of this method is that it is easy to implement and computationally efficient. On the other hand, it is not suitable for more complex geometries. "
   ]
  },
  {
   "attachments": {
    "g2421.png": {
     "image/png": "[encoded data, 107880 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "bb9b5d52",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 107880 characters]\" align=\"left\" width=\"200\"/>\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54a8f290",
   "metadata": {},
   "source": [
    "With the finite difference method, we first model the room as a grid, which can be stored using an array. Each entry of the matrix `u[i,j]` represents the temperature in the room at point $(i,j)$. The goal is now to compute the temperature at each grid point. \n",
    "\n",
    "Let's set up the grid matrix for our problem."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "344420b3",
   "metadata": {},
   "outputs": [],
   "source": [
    "] add Plots IterativeSolvers Preconditioners Printf SparseArrays LinearAlgebra"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3b69c74",
   "metadata": {},
   "outputs": [],
   "source": [
    "N = 8\n",
    "u = zeros(N,N)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c7af2b38",
   "metadata": {},
   "outputs": [],
   "source": [
    "function fill_boundary!(u)\n",
    "    u_window = 5.0\n",
    "    u_heater = 40.0\n",
    "    u_wall = 20.0\n",
    "    window_span = (0.6,0.9)\n",
    "    heater_span = (0.2,0.4)\n",
    "    nx,ny = size(u)\n",
    "    hx,hy = 1 ./ (nx-1,ny-1)\n",
    "    for j in 1:ny\n",
    "        y = hy*(j-1)\n",
    "        for i in 1:nx\n",
    "            x = hx*(i-1)\n",
    "            if j==ny && (window_span[1]<=x && x<=window_span[2])\n",
    "                u[i,j] = u_window\n",
    "            elseif i==1 && (heater_span[1]<=y && y<=heater_span[2])\n",
    "                u[i,j] = u_heater\n",
    "            elseif (j==1||j==ny) || (i==1||i==ny)\n",
    "                u[i,j] = u_wall\n",
    "            end\n",
    "        end\n",
    "    end\n",
    "    u\n",
    "end"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76888875",
   "metadata": {},
   "outputs": [],
   "source": [
    "fill_boundary!(u)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "53231e30",
   "metadata": {},
   "source": [
    "### Data Visualization\n",
    "\n",
    "To illustrate the solution, we also write a visualization function that plots the temperature of the room as a heatmap. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e29f8eaf",
   "metadata": {},
   "outputs": [],
   "source": [
    "using Plots"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b75d45cf",
   "metadata": {},
   "outputs": [],
   "source": [
    "function visualize(u;title=\"Temperature distribution\")\n",
    "    xlabel=\"x-coordinate\"\n",
    "    ylabel=\"y-coordinate\"\n",
    "    aspectratio = :equal\n",
    "    plt = plot(;size= 1.5 .*(350,300),title,xlabel,ylabel,aspectratio,fontsize=100)\n",
    "    nx,ny = size(u)\n",
    "    hx,hy = (1,1) ./ (nx-1,ny-1)\n",
    "    x = hx .* ((1:nx) .- 1)\n",
    "    y = hy .* ((1:ny) .- 1)\n",
    "    heatmap!(x,y,transpose(u),color=:thermal)\n",
    "    plt\n",
    "end"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b5a0362c",
   "metadata": {},
   "outputs": [],
   "source": [
    "visualize(u)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f7a0f7f",
   "metadata": {},
   "source": [
    "### How to find the temperature at the interior points?\n",
    "\n",
    "To set up a system of linear equations, we have to find one equation for each unknown value in the grid. The Laplace equation can be approximated by the following linear equation:\n",
    "\n",
    "$$\\dfrac{\\partial^2 u}{\\partial x^2} + \\dfrac{\\partial^2 u}{\\partial y^2} = 0 $$\n",
    "\n",
    "$$\\downarrow$$\n",
    "\n",
    "$$u_{i-1,j} + u_{i+1,j} + u_{i,j-1} + u_{i,j+1} - 4u_{i,j} = 0.$$\n",
    "\n",
    "This approximation computes the value at point $(i,j)$ by combining the values of its neighbors. \n"
   ]
  },
  {
   "attachments": {
    "g2632.png": {
     "image/png": "[encoded data, 84388 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "6fa66416",
   "metadata": {},
   "source": [
    "\n",
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 84388 characters]\" align=\"left\" width=\"200\"/>\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "406f9436",
   "metadata": {},
   "source": [
    "### System of linear equations\n",
    " \n",
    "We can now obtain this kind of equation for every unknown point in the grid (= all the interior points). All these equations can be arranged in array form\n",
    " \n",
    "$$Ax=b.$$\n",
    "\n",
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>Question:</b> For a grid of size NxN, how many rows does matrix A have? \n",
    "</div>\n",
    "\n",
    "    a) N\n",
    "    b) N²\n",
    "    c) N-1\n",
    "    d) (N-1)x(N-1)\n",
    "    e) N-2\n",
    "    f) (N-2)x(N-2)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b52c8b2f",
   "metadata": {},
   "outputs": [],
   "source": [
    "answer=\"x\" # Replace x with a,b,c,d,e, or f\n",
    "pdes_check_0(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a380c04",
   "metadata": {},
   "source": [
    "Next we create the matrix $A$: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ec0622d6",
   "metadata": {},
   "outputs": [],
   "source": [
    "using SparseArrays\n",
    "function generate_system_sparse(u)\n",
    "    nx,ny = size(u)\n",
    "    stencil = [(-1,0),(1,0),(0,-1),(0,1)]\n",
    "    nnz_bound = 5*nx*ny\n",
    "    nrows = (nx-2)*(ny-2)\n",
    "    ncols = nrows\n",
    "    b = zeros(nrows)\n",
    "    I = zeros(Int,nnz_bound)\n",
    "    J = zeros(Int,nnz_bound)\n",
    "    V = zeros(nnz_bound)\n",
    "    inz = 0\n",
    "    for j in 2:(ny-1)\n",
    "        for i in 2:(nx-1)\n",
    "            row = i-1 + (ny-2)*(j-2)\n",
    "            inz += 1\n",
    "            I[inz] = row\n",
    "            J[inz] = row\n",
    "            V[inz] = 4.0\n",
    "            for (di,dj) in stencil\n",
    "                on_boundary = i+di in (1,nx) || j+dj in (1,ny)\n",
    "                if on_boundary\n",
    "                    b[row] += u[i+di,j+dj]\n",
    "                    continue\n",
    "                end\n",
    "                col = i+di-1 + (ny-2)*(j+dj-2)\n",
    "                inz += 1\n",
    "                I[inz] = row\n",
    "                J[inz] = col\n",
    "                V[inz] = -1.0\n",
    "            end\n",
    "        end\n",
    "    end\n",
    "    A = sparse(view(I,1:inz),view(J,1:inz),view(V,1:inz),nrows,ncols)\n",
    "    A,b\n",
    "end"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a5cc7201",
   "metadata": {},
   "outputs": [],
   "source": [
    "N = 5\n",
    "u = zeros(N,N)\n",
    "A, b = generate_system_sparse(u)\n",
    "A"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f4c98fd",
   "metadata": {},
   "source": [
    "We created the matrix $A$ of the system of linear equations $Ax=b$ for a grid size $N=5$. For a grid of this size, we need 9 linear equations since there are 9 interior points. Note that we are using two types of numeration: one that defines the coordinates in the grid, e.g. $(2,3)$. The other numeration simply enumerates the interior values row-wise (1,2,...,9). The latter numeration is used to construct the matrix $A$. \n",
    "\n",
    "For any grid size, the equations matrix will only contain up to 5 nonzero values per row. Therefore, it is useful to store it as a sparse array which only stores the nonzero values under the hood. This is essential for the implementation because a lot of memory can be saved in this way. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e521df4",
   "metadata": {},
   "source": [
    "$u_{i-1,j} + u_{i+1,j} + u_{i,j-1} + u_{i,j+1} - 4u_{i,j} = 0$"
   ]
  },
  {
   "attachments": {
    "Screenshot%20from%202023-10-12%2010-18-37.png": {
     "image/png": "[encoded data, 52380 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "756ae8fd",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 52380 characters]\" align=\"left\" width=\"200\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8a3b45b",
   "metadata": {},
   "source": [
    "### Solution methods\n",
    "\n",
    "Two possible solution methods have already been discussed in the course:\n",
    "\n",
    "- Jacobi method\n",
    "- Gaussian elimination\n",
    "\n",
    "To determine wether any of these methods are useful solvers for our problem, we analyze if they are _algorithmically scalable_. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f29c756a",
   "metadata": {},
   "source": [
    "### Algorithmically scalable solver\n",
    "\n",
    "A computation method is an _algorithmically scalable_ solver if the total cost scales at most linearly with respect to the total problem size.\n",
    "\n",
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>Question:</b>  Let $R$ be our problem size, the number of rows in our matrix $A$. Because we have $N$ points in each dimension of the grid, $R=O(N^2)$. What is the complexity of the Jacobi method and Gaussian elimination with respect to the problem size $R$?\n",
    "</div>\n",
    "\n",
    "    a) Jacobi: O(N^2) = O(R) per iteration, GE: O(N^3) = O(R*sqrt(R))\n",
    "    b) Jacobi: O(N^2) = O(R) per iteration, GE: O(R^3)\n",
    "    c) Jacobi: O(R^2) per iteration, GE: O(R^3)\n",
    "    d) Jacobi: O(N^2) = O(R) per iteration, GE: O(R) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0244f525",
   "metadata": {},
   "outputs": [],
   "source": [
    "answer=\"x\" # Replace x with a,b,c or d\n",
    "pdes_check_1(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "638b0ecc",
   "metadata": {},
   "source": [
    "To conclude, we find that none of the two solvers are algorithmically scalable. The Jacobi method scales linearly with respect to the problem size per iteration. However, the number of iterations might increase with the problem size, as we will demonstrate in the next section."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ca3d718",
   "metadata": {},
   "source": [
    "### Complexity of Jacobi method\n",
    "\n",
    "Next we implement the Jacobi method to solve the PDE. In addition to using a fixed maximum number of iterations, we introduce a relative tolerance threshold. The iterations stop when the relative error in an iteration subceeds this threshold."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f70617a",
   "metadata": {},
   "outputs": [],
   "source": [
    "using LinearAlgebra\n",
    "function jacobi!(u,f=zeros(size(u));reltol=0.0,maxiters=0)\n",
    "    u_new = copy(u)\n",
    "    e = similar(u)\n",
    "    ni,nj = size(u)\n",
    "    for iter in 1:maxiters\n",
    "        for j in 2:(nj-1)\n",
    "            for i in 2:(ni-1)\n",
    "                u_new[i,j] =\n",
    "                  0.25*(u[i-1,j] + u[i+1,j] + u[i,j-1] + u[i,j+1] + f[i,j])\n",
    "            end\n",
    "        end\n",
    "        e .= u_new .- u\n",
    "        relerror = norm(e)/norm(u_new)\n",
    "        if relerror < reltol\n",
    "            return u_new, iter\n",
    "        end\n",
    "        u, u_new = u_new, u\n",
    "    end\n",
    "    u, maxiters\n",
    "end"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3b1b69d",
   "metadata": {},
   "source": [
    "Run the following code cell several times with different values for $N$. For instance, $N=10$, $N=20$, $N=40$. Compare the number of iterations that are needed to converge for each problem size."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7a8ff556",
   "metadata": {},
   "outputs": [],
   "source": [
    "N = 10\n",
    "u = zeros(N,N)\n",
    "fill_boundary!(u)\n",
    "u, iter = jacobi!(u,reltol=1.0e-5,maxiters=1000000)\n",
    "println(\"Jacobi converged in $iter iterations\")\n",
    "visualize(u)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "791691b8",
   "metadata": {},
   "source": [
    "### Convergence analysis\n",
    "We can observe that the number of iterations scales with the problem size. In the next step, we plot the number of iterations needed for convergence against the problem size. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67e79b9c",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt = plot(xlabel=\"N^2\",ylabel=\"Iterations\");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "86c8fbb7",
   "metadata": {},
   "outputs": [],
   "source": [
    "Ns = [20,40,80,160]\n",
    "reltol = 1.0e-6\n",
    "iters = zeros(size(Ns))\n",
    "for (i,N) in enumerate(Ns)\n",
    "    u = zeros(N,N)\n",
    "    fill_boundary!(u)\n",
    "    u, iter = jacobi!(u;reltol=reltol,maxiters=1000000)\n",
    "    iters[i] = iter\n",
    "end\n",
    "plot!(plt,Ns.^2,iters,xaxis=:log10,yaxis=:log10,label=\"reltol=$reltol (Jacobi)\",marker=:auto)\n",
    "plt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4886157c",
   "metadata": {},
   "source": [
    "It can be analytically proven that the number of iterations to achieve a relative error of $10^{-s}$ increases as $O(s N^2)$. Recall: The cost per iteration of the Jacobi method is $O(N^2) = O(R)$. Treating $s$ as a constant, the total cost of the Jacobi method will be $O((N^2)^2) = O(R^2) = O(N^4)$.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55c529a1",
   "metadata": {},
   "source": [
    "### Complexity of some solvers\n",
    "\n",
    "There exist several methods to solve a Laplace equation on a regular mesh of $S$ points ($S=N^d$). The following table compares the scalability of these solvers for different numbers of mesh dimensions."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9a87f765",
   "metadata": {},
   "source": [
    "| Solver | 1D | 2D | 3D |\n",
    "|--|--|--|--|\n",
    "| Dense Cholesky | O(S^3) | O(S^3) | O(S^3) |\n",
    "| Sparse Cholesky | O(S) | O(S^1.5) | O(S^2) |\n",
    "| Conjugate gradient + Multi grid | O(S) | O(S) | O(S) |\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d24408b4",
   "metadata": {},
   "source": [
    "## Conjugate gradient method\n",
    "\n",
    "In this section, we will discuss the [Conjugate Gradient Method](https://en.wikipedia.org/wiki/Conjugate_gradient_method). Combined with the multi grid method, it achieves the best scalability for solving Laplace equations.\n",
    "\n",
    "\n",
    "The idea of the conjugate gradient method is to transform the problem into an optimization problem of the form\n",
    "\n",
    "$$ x = \\text{arg }\\min_{y} f(y)$$ \n",
    "\n",
    "<p style=\"text-align:center\">with</p> \n",
    "\n",
    "$$ f(y)= \\frac{1}{2}( y^\\mathrm{T}Ay - y^\\mathrm{T} b ).$$\n",
    "\n",
    "Thus, the goal is to find vector $x$, the minimum of function $f(y)$. This vector is equivalent to the solution of the system of linear equations, $A x = b$.  \n",
    "\n",
    "The conjugate gradient method is a gradient descent algorithm optimized for symmetic ($A^\\mathrm{T}=A$) positive-definite ($y^\\mathrm{T}Ay > 0$) matrices. The algorithm is applicable to our problem since the matrix $A$ is both symmetric and positive-definite.\n",
    "\n",
    "\n",
    "### Top 10 algorithms of the 20th century\n",
    "\n",
    "The conjugate gradient method is a type of Krylov subspace method, which is listed by the IEEE Computer Society as one of the top 10 algorithms of the past century:\n",
    "\n",
    "- Metropolis Algorithm for Monte Carlo\n",
    "- Simplex Method for Linear Programming\n",
    "- **Krylov Subspace Iteration Methods**\n",
    "- The Decompositional Approach to Matrix Computations\n",
    "- The Fortran Optimizing Compiler\n",
    "- QR Algorithm for Computing Eigenvalues\n",
    "- Quicksort Algorithm for Sorting\n",
    "- Fast Fourier Transform\n",
    "- Integer Relation Detection\n",
    "- Fast Multipole Method\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a9f516e6",
   "metadata": {},
   "source": [
    "### Convergence analysis\n",
    "\n",
    "For the following convergence analysis, we will use the implementation of the conjugate gradient method from the `IterativeSolvers` package."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f8dbf39",
   "metadata": {},
   "outputs": [],
   "source": [
    "using IterativeSolvers: cg!\n",
    "N = 80\n",
    "u = zeros(N,N)\n",
    "fill_boundary!(u)\n",
    "A,b = generate_system_sparse(u)\n",
    "x = zeros(length(b))\n",
    "_,ch = cg!(x, A, b, reltol=1e-5,log=true)\n",
    "display(ch)\n",
    "u[2:end-1,2:end-1] = x\n",
    "visualize(u)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30c6e04e",
   "metadata": {},
   "outputs": [],
   "source": [
    "Ns = [20,40,80,160]\n",
    "reltol = 1.0e-5\n",
    "iters = zeros(size(Ns))\n",
    "for (i,N) in enumerate(Ns)\n",
    "    u = zeros(N,N)\n",
    "    fill_boundary!(u)\n",
    "    A,b = generate_system_sparse(u)\n",
    "    x = zeros(length(b))\n",
    "    _,ch = cg!(x, A, b, reltol=reltol,log=true)\n",
    "    iters[i] = ch.iters\n",
    "end\n",
    "plot!(plt,Ns.^2,iters,xaxis=:log10,yaxis=:log10,label=\"reltol=$reltol (CG)\",marker=:auto)\n",
    "plt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5396554c",
   "metadata": {},
   "source": [
    "The number of iterations needed to converge is much lower with the conjugate gradient method than with the Jacobi method. However, the number of iterations still increases with the problem size, so there is still room for improvement. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "92bfd7d7",
   "metadata": {},
   "source": [
    "### Number of iterations\n",
    "\n",
    "It can be shown that the number of iterations to achieve a relative error of $10^{-s}$ increases as $O(s \\sqrt{\\kappa(A)})$. As a reminder, the condition number of A $\\kappa(A)$ is ratio between the largest and smallest eigenvalues of A: \n",
    "$$\\kappa(A)=\\dfrac{\\lambda_{max}(A)}{\\lambda_{min}(A)}$$\n",
    "\n",
    "It can also be shown that in our example $\\kappa(A) = O(N^2)$. Thus, the number of iterations scales as $O(s N)$ for the conjugate gradient method. Remember that the number of iterations scales as $O(sN^2)$ for the Jacobi method.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1bb8ffe6",
   "metadata": {},
   "source": [
    "### Goal\n",
    "\n",
    "The conjugate gradient method provides some improvement to the Jacobi method, since the number of iterations increases more slowly with the problem size. However, the ultimate goal is to find an iterative method whose number of iterations is _independent_ of the problem size."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "956564d5",
   "metadata": {},
   "source": [
    "### Preconditioner\n",
    "\n",
    "To achieve this goal, we will apply a [preconditioner](https://en.wikipedia.org/wiki/Preconditioner) to transform the original problem into a format that is easier to solve. \n",
    "\n",
    "A preconditioner is simply a linear function $M$ such that \n",
    "$$M(b) \\approx x, \\text{ with } Ax=b \\text{ for any }  b.$$ \n",
    "\n",
    "Once we have found such a function $M(b)$, we can solve the _preconditioned problem_ $(MA)x = Mb$, which is equivalent to $Ax=b$.\n",
    "\n",
    "The way that preconditioning affects the number of iterations is that it reduces the condition number of $A$: \n",
    "\n",
    "$$ \\begin{align}\n",
    "&M(b) \\approx x, \\text{ with } Ax=b \\text{ for any }  b \\\\\n",
    "&\\rightarrow M(b) \\approx A^{-1}b \\\\\n",
    "&\\rightarrow M \\approx A^{-1} \\\\\n",
    "&\\rightarrow M A \\approx I \\text{ (Identity matrix)} \\\\\n",
    "&\\rightarrow \\kappa (MA) \\approx 1 \\\\\n",
    "\\end{align}$$\n",
    "\n",
    "Recall that the number of iterations to achieve a relative error of $10^{-s}$ is $O(s\\sqrt{\\kappa (A)})$. With $\\kappa (MA) \\approx 1$, the number of iterations will scale as $O(s)$. Thus, the number of iterations will be independent of the problem size for the preconditioned problem. \n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89563cc4",
   "metadata": {},
   "source": [
    "### How to build a preconditioner  ?\n",
    "\n",
    "Many ways of building a preconditioner can be found in the literature. The solutions range between two extremes: \n",
    "\n",
    "1. $M=A^{-1}$. This is the exact preconditioner. The CG method will converge in just one iteration. However, it is exactly as costly to compute the matrix $M$ as it is to find the solution to the original problem. \n",
    "2. $M=I$. This is the other extreme where we do no extra work to find the matrix $M$. The preconditioned problem is identical to the original problem.\n",
    "\n",
    "The solution is to find a good trade-off such that we get a matrix $M$ that is accurate enough to approximate the original problem but also cheap enough to be computed quickly. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4338ee30",
   "metadata": {},
   "source": [
    "### Jacobi Preconditioner\n",
    "\n",
    "Next we use the Jacobi method to construct a preconditioner for the CG method. The matrix $M$ is simply computed as the grid values after a certain number of iterations with the Jacobi method. In order for $M$ to be linear, we set a fixed maximum number of iterations in the `jacobi!` function and disable the relative error stopping criterion."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd608f2f",
   "metadata": {},
   "outputs": [],
   "source": [
    "struct JacobiPrec{T}\n",
    "    u::Matrix{T}\n",
    "    f::Matrix{T}\n",
    "    niters::Int\n",
    "end\n",
    "function jacobi_prec(N;niters)\n",
    "    u = zeros(N,N)\n",
    "    f = zeros(N,N)\n",
    "    JacobiPrec(u,f,niters)\n",
    "end\n",
    "function LinearAlgebra.ldiv!(x,M::JacobiPrec,b)\n",
    "    M.u[2:end-1,2:end-1] .= 0 \n",
    "    M.f[2:end-1,2:end-1] = b\n",
    "    u,_ = jacobi!(M.u,M.f,reltol=0,maxiters=M.niters)\n",
    "    x[:] = @view u[2:end-1,2:end-1]\n",
    "    x\n",
    "end"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "46b3883d",
   "metadata": {},
   "source": [
    "Run the following cell for different values of `niters`. The larger the value of `niters`, the more matrix $M$ resembles the exact solution. The fewer iterations we use, the less accurate the approximation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "858ac6ba",
   "metadata": {},
   "outputs": [],
   "source": [
    "N = 80\n",
    "u = zeros(N,N)\n",
    "fill_boundary!(u)\n",
    "A,b = generate_system_sparse(u)\n",
    "# Generate preconditioner\n",
    "M = jacobi_prec(N,niters=1000)\n",
    "x = zeros(size(b))\n",
    "# Compute solution as x=b/M\n",
    "ldiv!(x,M,b)\n",
    "u[2:end-1,2:end-1] = x\n",
    "visualize(u)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1750ecb1",
   "metadata": {},
   "outputs": [],
   "source": [
    "Ns = [20,40,80,160]\n",
    "reltol = 1.0e-5\n",
    "iters = zeros(size(Ns))\n",
    "for (i,N) in enumerate(Ns)\n",
    "    u = zeros(N,N)\n",
    "    fill_boundary!(u)\n",
    "    A,b = generate_system_sparse(u)\n",
    "    M = jacobi_prec(N,niters=100)\n",
    "    x = zeros(length(b))\n",
    "    # Provide preconditioner to conjugate gradient method\n",
    "    _,ch = cg!(x, A, b, Pl=M, reltol=reltol,log=true)\n",
    "    iters[i] = ch.iters\n",
    "end\n",
    "plot!(plt,Ns.^2,iters,xaxis=:log10,yaxis=:log10,label=\"reltol=$reltol (CG+Jacobi($(M.niters)))\",marker=:auto)\n",
    "plt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "26f7e342",
   "metadata": {},
   "source": [
    "Observe that the Jacobi preconditioner achieves that the CG method needs fewer iterations. However, the number of iterations still increases with the problem size. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43fb5082",
   "metadata": {},
   "source": [
    "### How can we improve the Jacobi method?\n",
    "\n",
    "We can optimize the Jacobi method to obtain a better preconditioner for the CG method. Run the following code cell again with a grid size of $N=10$ and $N=100$. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "db9397dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "N = 100\n",
    "u = zeros(N,N)\n",
    "fill_boundary!(u)\n",
    "A,b = generate_system_sparse(u)\n",
    "M = jacobi_prec(N,niters=80)\n",
    "x = zeros(size(b))\n",
    "ldiv!(x,M,b)\n",
    "u[2:end-1,2:end-1] = x\n",
    "visualize(u)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf76a64b",
   "metadata": {},
   "source": [
    "The main reason that the preconditioner performs badly for larger problem sizes is that it takes more time to update the interior values of the grid. The larger the grid, the longer the Jacobi method needs to propagate the values from the outer boundary to the interior of the grid. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c04df158",
   "metadata": {},
   "source": [
    "### Multi-grid method\n",
    "\n",
    "The [multi-grid method](https://en.wikipedia.org/wiki/Multigrid_method) is the second building block of the fast solver for our Laplace equation. \n",
    "\n",
    "The multi-grid method achieves a faster convergence of the Jacobi method by starting to solve the coarse problem first and then stepwise increasing the grid resolution. On each resolution level, a few steps of the Jacobi method are performed (only 2 steps per level in this example). Next, the resolution of the grid is increased and the Jacobi method is run again. This process is repeated until we reach the desired grid size. Since the Jacobi method converges after a few iterations on very small grids, the values are propagated to the center much more quickly than without using the multi-grid method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee7679f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "function prolongate!(u_fine,u_coarse)\n",
    "    ni_coarse, nj_coarse = size(u_coarse)\n",
    "    ni_fine, nj_fine = size(u_fine)\n",
    "    @assert 2*(ni_coarse-1) == (ni_fine-1)\n",
    "    for j_fine in 1:nj_fine\n",
    "        j_coarse = div(j_fine-1,2)+1\n",
    "        j_rem = mod(j_fine-1,2)\n",
    "        for i_fine in 1:ni_fine\n",
    "            i_coarse = div(i_fine-1,2)+1\n",
    "            i_rem = mod(i_fine-1,2)\n",
    "            u_fine[i_fine,j_fine] = 0.25*(\n",
    "                u_coarse[i_coarse,j_coarse] +\n",
    "                u_coarse[i_coarse+i_rem,j_coarse] +\n",
    "                u_coarse[i_coarse,j_coarse+j_rem] +\n",
    "                u_coarse[i_coarse+i_rem,j_coarse+j_rem] )\n",
    "        end\n",
    "    end\n",
    "end"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "260bbcb0",
   "metadata": {},
   "outputs": [],
   "source": [
    "iters_in_level = [2,2,2,2,2,2,2,2]\n",
    "u_coarse = zeros(2,2)\n",
    "anim = @animate  for (level,iters) in enumerate(iters_in_level)\n",
    "    N = 2^level\n",
    "    u = zeros(1+N,1+N)\n",
    "    prolongate!(u,u_coarse)\n",
    "    fill_boundary!(u)\n",
    "    global u_coarse\n",
    "    u_coarse,_ = jacobi!(u,reltol=0,maxiters=iters)\n",
    "    visualize(u,title=\"Level $level\")\n",
    "end\n",
    "gif(anim,\"a2.gif\",fps=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6122ac8b",
   "metadata": {},
   "source": [
    "### Multi-grid preconditioner\n",
    "\n",
    "Let's see what happens when we use the CG method in combination with a multi-grid preconditioner. In the following code cell, we use a multi-grid preconditioner from the package `Preconditioners`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8a5e1031",
   "metadata": {},
   "outputs": [],
   "source": [
    "using Preconditioners\n",
    "Ns = [20,40,80,160]\n",
    "reltol = 1.0e-5\n",
    "iters = zeros(size(Ns))\n",
    "for (i,N) in enumerate(Ns)\n",
    "    u = zeros(N,N)\n",
    "    fill_boundary!(u)\n",
    "    A,b = generate_system_sparse(u)\n",
    "    M = AMGPreconditioner{SmoothedAggregation}(A)\n",
    "    x = zeros(length(b))\n",
    "    _,ch = cg!(x, A, b, Pl=M, reltol=reltol,log=true)\n",
    "    iters[i] = ch.iters\n",
    "end\n",
    "plot!(plt,Ns.^2,iters,xaxis=:log10,yaxis=:log10,label=\"reltol=$reltol (CG+MG)\",marker=:auto)\n",
    "plt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63c406e0",
   "metadata": {},
   "source": [
    "The number of iterations is now constant for different problem sizes. Thus, we have finally achieved an algorithmically scalable solver by combining the conjugate gradient method and the multi-grid method!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3c02536",
   "metadata": {},
   "source": [
    "### High-performance conjugate gradient (HPCG) benchmark\n",
    "\n",
    "The HPCG benchmark is an alternative to the HPL benchmark to rank the [top 500](https://www.top500.org/) computers. It is based on the CG + multigrid method, whereas the HPL benchmark is a Gaussian elimination type of algorithm. The HPCG was introduced because the CG + multigrid method is more commonly run on supercomputers than Gaussian elimination. While HPL gives a good indication of the peak performance, the HPCG benchmark is orders of magnitude below the peak performance. \n"
   ]
  },
  {
   "attachments": {
    "Screenshot%20from%202023-10-12%2014-39-49.png": {
     "image/png": "[encoded data, 64644 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "e240db31",
   "metadata": {},
   "source": [
    "Fig. from DOI: [10.1177/1094342015593158](https://journals.sagepub.com/doi/10.1177/1094342015593158)\n",
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 64644 characters]\" align=\"left\" width=\"350\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b30f96ad",
   "metadata": {},
   "source": [
    "## Parallel implementation\n",
    "In this section, we will discuss the parallel implementation of the CG method. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b5eadafc",
   "metadata": {},
   "source": [
    "### Implementation of conjugate gradient method\n",
    "First, let's analyze how to parallelize the individual parts of the serial implementation of the CG method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b37f6be4",
   "metadata": {},
   "outputs": [],
   "source": [
    "function conjugate_gradient!(x,A,b;M,reltol,maxiters=size(A,1))\n",
    "    c = similar(x)\n",
    "    u = similar(x)\n",
    "    r = similar(x)\n",
    "    mul!(c,A,x)\n",
    "    r .= b .- c\n",
    "    norm_r0 = sqrt(dot(r,r))\n",
    "    for iter in 1:maxiters\n",
    "        ldiv!(c,M,r)\n",
    "        ρ_prev = ρ\n",
    "        ρ = dot(c,r)\n",
    "        β = ρ / ρ_prev\n",
    "        u .= c .+ β .* u\n",
    "        mul!(c, A, u)\n",
    "        α = ρ / dot(u,c)\n",
    "        x .= x .+ α .* u\n",
    "        r .= r .- α .* c\n",
    "        if sqrt(dot(r,r)) < reltol*norm_r0\n",
    "            break\n",
    "        end\n",
    "    end\n",
    "    x\n",
    "end"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e0bb3512",
   "metadata": {},
   "source": [
    "The algorithm performs matrix multiplications and additions which are trivially parallelizable. The phases that are not trivially parallelizable are\n",
    "\n",
    "   - Dot products\n",
    "   - Sparse matrix-vector products\n",
    "   - Preconditioners\n",
    "   \n",
    "If we find parallel implementations for these parts, we get a complete parallel implementation for the CG method. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c88fb01",
   "metadata": {},
   "source": [
    "### Dot product\n",
    "\n",
    "The dot product is defined as \n",
    "$$\\text{dot}(a,b)=  \\sum_i a_i b_i$$. \n",
    "\n",
    "Imagine we have our data distributed on two CPUs as in the picture below. How can we implement the dot product computation in parallel? "
   ]
  },
  {
   "attachments": {
    "d1.png": {
     "image/png": "[encoded data, 20248 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "8392e688",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 20248 characters]\" align=\"left\" width=\"300\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93ec2564",
   "metadata": {},
   "source": [
    "### MPI implementation\n",
    "For the parallel implementation, the processes can compute the dot product of their respective sub-vectors independently. But they have to send the result to the other processes so they can be combined for the final dot product. Each process needs the _global_ dot product, because further computations in the algorithm depend on it. For instance, the stopping criterion depends on the result of the global dot product, such that all processes stop at the same time. "
   ]
  },
  {
   "attachments": {
    "fig-pdes-dot-product.png": {
     "image/png": "[encoded data, 42304 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "a8aa2ebd",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 42304 characters]\" align=\"left\" width=\"550\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "42776d84",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>Question:</b>  Which MPI directive best incorporates the communication of the local dot product among processes?\n",
    "</div>\n",
    "\n",
    "    a) MPI_Gather\n",
    "    b) MPI_Reduce\n",
    "    c) MPI_Allreduce\n",
    "    d) MPI_Bcast"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e0907af2",
   "metadata": {},
   "outputs": [],
   "source": [
    "answer=\"x\" # Replace x with a, b, c, or d\n",
    "pdes_check_2(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "759aefd1",
   "metadata": {},
   "source": [
    "### Sparse matrix-vector product\n",
    "Next we will discuss how to parallelize the product of a sparse matrix $A$ with a vector $x$. "
   ]
  },
  {
   "attachments": {
    "data-partition.png": {
     "image/png": "[encoded data, 34860 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "1961a0c6",
   "metadata": {},
   "source": [
    "\n",
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 34860 characters]\" align=\"left\" width=\"350\"/>\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d00ca4c1",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>Question:</b>  Which parts of $A$ and $x$ are needed to compute the local values of $b$ in a worker? \n",
    "</div>\n",
    "\n",
    "    a) The local entries of A and all entries of x.\n",
    "    b) The local entries of A and the local entries of x. \n",
    "    c) All entries of A and the entries of x associated with local non-zero columns of A. \n",
    "    d) The local entries of A and the entries of x associated with the local non-zero columns of A. \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "53672399",
   "metadata": {},
   "outputs": [],
   "source": [
    "answer=\"x\" # Replace x with a, b, c, or d\n",
    "pdes_check_3(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4afca5ab",
   "metadata": {},
   "source": [
    "### Ghost (halo) columns\n",
    "In our example, each CPU needs all local entries of $x$ plus two additional entries from another machine. If all entries in $A$ were non-zero, the whole vector $x$ would be required. Thus, the sparsity of $A$ allows to reduce the amount of communication. This pays off especially in larger problems. "
   ]
  },
  {
   "attachments": {
    "spmvp.png": {
     "image/png": "[encoded data, 31252 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "ce7c6c20",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 31252 characters]\" align=\"left\" width=\"350\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb1fc034",
   "metadata": {},
   "source": [
    "### Latency hiding\n",
    "\n",
    "We can also use latency hiding for this problem. The computations are split into two parts: \n",
    "1. Multiplication with only local values of $x$  \n",
    "2. Multiplication with the remaining communicated values of $x$\n",
    "\n",
    "The first part of the computations has no data dependencies, so it can be started immediately. During its computation, the communication of the values of $x$ can be started. "
   ]
  },
  {
   "attachments": {
    "g4581.png": {
     "image/png": "[encoded data, 41016 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "9c0f0ddf",
   "metadata": {},
   "source": [
    "\n",
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 41016 characters]\" align=\"left\" width=\"500\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "541cd29a",
   "metadata": {},
   "source": [
    "### Mesh partition"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "149111fa",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-block alert-success\">\n",
    "<b>Question:</b>  Which mesh partition does lead to less communication in the sparse matrix-vector product?\n",
    "</div>"
   ]
  },
  {
   "attachments": {
    "fig-pdes-2d-partition.png": {
     "image/png": "[encoded data, 21800 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "b2883efb",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 21800 characters]\" align=\"left\" width=\"400\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e2926d0",
   "metadata": {},
   "source": [
    "    a) The 2D block partitioning\n",
    "    b) The 2D cyclic partitioning\n",
    "    c) Both are equally good"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7f67a66a",
   "metadata": {},
   "outputs": [],
   "source": [
    "answer=\"x\" # Replace x with a, b, or c \n",
    "pdes_check_4(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a91edb5d",
   "metadata": {},
   "source": [
    "Remember:  The equation associated with point (i,j) is:\n",
    "\n",
    "$u_{i-1,j} + u_{i+1,j} + u_{i,j-1} + u_{i,j+1} - 4u_{i,j} = 0$\n",
    "\n",
    "Each equation for a point corresponds with a row in the matrix $A$. Each row will have only 5 non-zero values, and it reduces communication if they are on the same CPU. Therefore, the 2D block partitioning is more suitable, since only the boundary values need to be communicated."
   ]
  },
  {
   "attachments": {
    "g2632.png": {
     "image/png": "[encoded data, 84388 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "f28cf7b2",
   "metadata": {},
   "source": [
    "\n",
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 84388 characters]\" align=\"left\" width=\"200\"/>\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d401713b",
   "metadata": {},
   "source": [
    "## How to partition unstructured meshes?\n",
    "\n",
    "Finite element methods also work on unstructured meshes. The grid of points can be modeled as a graph. Again, there will be one equation per node in the graph. The partition can be computed as the result of a k-way graph partitioning problem.\n"
   ]
  },
  {
   "attachments": {
    "g1133.png": {
     "image/png": "[encoded data, 1458576 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "a1275f90",
   "metadata": {},
   "source": [
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 1458576 characters]\" align=\"left\" width=\"500\"/>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b4385e0",
   "metadata": {},
   "source": [
    "### k-way graph partitioning problem\n",
    "\n",
    "\n",
    "Given a graph $G$ (i.e. the mesh),\n",
    "\n",
    "- Partition the vertices of $G$ into $k$ disjoint parts of equal size (to achieve load balance)\n",
    "- Minimize the number of edges with end vertices belonging to different parts (to reduce communication)\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "attachments": {
    "sc3.png": {
     "image/png": "[encoded data, 79208 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "ea55c3dc",
   "metadata": {},
   "source": [
    "### Example\n",
    "\n",
    "The picture shows a partition of a mesh into 8 parts (computed with [METIS](https://github.com/KarypisLab/METIS)).\n",
    "\n",
    "<div>\n",
    "<img src=\"data:image/png;base64,[encoded data, 79208 characters]\" align=\"left\" width=\"350\"/>\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b706b055",
   "metadata": {},
   "source": [
    "# License\n",
    "\n",
    "\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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "87beee72",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Julia 1.9.1",
   "language": "julia",
   "name": "julia-1.9"
  },
  "language_info": {
   "file_extension": ".jl",
   "mimetype": "application/julia",
   "name": "julia",
   "version": "1.9.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
