{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# LU Factorization"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {},
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "import numpy.linalg as la"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Part 1: One Column of LU"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[-2.,  2., -1.],\n",
              "       [-3.,  1., -9.],\n",
              "       [-5., -5., -2.]])"
            ]
          },
          "execution_count": 3,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "n = 3\n",
        "\n",
        "np.random.seed(15)\n",
        "A = np.round(5*np.random.randn(n, n))\n",
        "\n",
        "A"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Initialize `L` and `U` with zeros:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {},
      "outputs": [],
      "source": [
        "L = np.zeros((n,n))\n",
        "U = np.zeros((n,n))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Set `U` to be the first row of `A`:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[-2.,  2., -1.],\n",
              "       [ 0.,  0.,  0.],\n",
              "       [ 0.,  0.,  0.]])"
            ]
          },
          "execution_count": 5,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "U[0,:] = A[0,:]\n",
        "U"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Compute the first column of `L`:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[1. , 0. , 0. ],\n",
              "       [1.5, 0. , 0. ],\n",
              "       [2.5, 0. , 0. ]])"
            ]
          },
          "execution_count": 6,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "L[:,0] = A[:,0]/U[0,0]\n",
        "L"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Compare what we have to `A`:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[[-2.  2. -1.]\n",
            " [-3.  1. -9.]\n",
            " [-5. -5. -2.]]\n",
            "[[-2.   2.  -1. ]\n",
            " [-3.   3.  -1.5]\n",
            " [-5.   5.  -2.5]]\n"
          ]
        }
      ],
      "source": [
        "print(A)\n",
        "print(L@U)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Perform the Schur complement update and store the result in `A1`:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[  0. ,   0. ,   0. ],\n",
              "       [  0. ,  -2. ,  -7.5],\n",
              "       [  0. , -10. ,   0.5]])"
            ]
          },
          "execution_count": 8,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "A1 = A - L @ U\n",
        "A1"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Take the second row of `U` to be the second row of `A1`:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[-2. ,  2. , -1. ],\n",
              "       [ 0. , -2. , -7.5],\n",
              "       [ 0. ,  0. ,  0. ]])"
            ]
          },
          "execution_count": 9,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "U[1,1:] = A1[1,1:]\n",
        "U"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can now compute the next column of `L`:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[1. , 0. , 0. ],\n",
              "       [1.5, 1. , 0. ],\n",
              "       [2.5, 5. , 0. ]])"
            ]
          },
          "execution_count": 10,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "L[1:,1] = A1[1:,1]/U[1,1]\n",
        "L"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "And finally, compute the bottom right elements of `L` and `U`"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {},
      "outputs": [],
      "source": [
        "U[2,2] = A1[2,2] - L[2,1]*U[1,2]\n",
        "L[2,2] = 1.0"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[[1.  0.  0. ]\n",
            " [1.5 1.  0. ]\n",
            " [2.5 5.  1. ]]\n",
            "[[-2.   2.  -1. ]\n",
            " [ 0.  -2.  -7.5]\n",
            " [ 0.   0.  38. ]]\n"
          ]
        }
      ],
      "source": [
        "print(L)\n",
        "print(U)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[[-2.  2. -1.]\n",
            " [-3.  1. -9.]\n",
            " [-5. -5. -2.]]\n",
            "[[-2.  2. -1.]\n",
            " [-3.  1. -9.]\n",
            " [-5. -5. -2.]]\n"
          ]
        }
      ],
      "source": [
        "print(A)\n",
        "print(L@U)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Part 2: The Full Algorithm\n",
        "\n",
        "Implement the general LU factorization algorithm"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "metadata": {},
      "outputs": [],
      "source": [
        "n = 4\n",
        "A = np.random.random((n,n)) \n",
        "L = np.zeros((n,n)) \n",
        "U = np.zeros((n,n)) \n",
        "M = A.copy()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "metadata": {},
      "outputs": [],
      "source": [
        "for i in range(n):\n",
        "    U[i,i:] = M[i,i:]\n",
        "    L[i:,i] = M[i:,i]/U[i,i]\n",
        "    M[i+1:,i+1:] -= np.outer(L[i+1:,i:i+1],U[i:i+1,i+1:])   "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[[  1.           0.           0.           0.        ]\n",
            " [  0.87952614   1.           0.           0.        ]\n",
            " [  0.04296101  -8.67490157   1.           0.        ]\n",
            " [  0.82877669 -11.69108892   1.80202512   1.        ]]\n",
            "[[ 0.9176299   0.26414685  0.71777369  0.86571503]\n",
            " [ 0.         -0.02177348 -0.46405769 -0.71471261]\n",
            " [ 0.          0.         -3.05794766 -5.86446657]\n",
            " [ 0.          0.          0.          2.43970137]]\n",
            "[[ 0.00000000e+00  0.00000000e+00  0.00000000e+00  0.00000000e+00]\n",
            " [ 0.00000000e+00  0.00000000e+00  0.00000000e+00  0.00000000e+00]\n",
            " [ 0.00000000e+00  0.00000000e+00 -2.22044605e-16 -3.33066907e-16]\n",
            " [ 0.00000000e+00  0.00000000e+00  0.00000000e+00  2.22044605e-16]]\n"
          ]
        }
      ],
      "source": [
        "print(L)\n",
        "print(U)\n",
        "print(A-L@U)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "collapsed": true
      },
      "source": [
        "## Part 3: LU with Partial Pivoting\n",
        "\n",
        "When a divisor (U_ii) becomes zero, while nonzeros remain in the trailing matrix, the LU factorization does not exist. Further, if U_ii is small, the magnitude of elements in L and U can blow up, increasing round-off error. Partial pivoting circumvents both problems."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 31,
      "metadata": {},
      "outputs": [],
      "source": [
        "n = 4\n",
        "A = np.random.random((n,n)) \n",
        "L = np.zeros((n,n)) \n",
        "U = np.zeros((n,n)) \n",
        "P = np.eye(n,n)\n",
        "M = A.copy()\n",
        "\n",
        "def perm(i,j):\n",
        "    P = np.eye(n,n)\n",
        "    P[i,i] = 0\n",
        "    P[j,j] = 0\n",
        "    P[i,j] = 1\n",
        "    P[j,i] = 1\n",
        "    return P\n",
        "\n",
        "for i in range(n):\n",
        "    imax = np.argmax(np.abs(M[i:,i]))\n",
        "    Pi = perm(i,i+imax)\n",
        "    P = Pi @ P\n",
        "    L = Pi @ L\n",
        "    M = Pi @ M\n",
        "    U[i,i:] = M[i,i:]\n",
        "    L[i:,i] = M[i:,i]/U[i,i]\n",
        "    M[i+1:,i+1:] -= np.outer(L[i+1:,i:i+1],U[i:i+1,i+1:])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Check residual error for the permuted A, i.e., PA-LU. What property do off-diagonal entries in L satisfy?"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 32,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[[ 0.00000000e+00  0.00000000e+00  0.00000000e+00  0.00000000e+00]\n",
            " [ 0.00000000e+00  1.11022302e-16  0.00000000e+00  0.00000000e+00]\n",
            " [ 0.00000000e+00  0.00000000e+00 -1.11022302e-16  0.00000000e+00]\n",
            " [ 0.00000000e+00  0.00000000e+00  0.00000000e+00  0.00000000e+00]]\n"
          ]
        }
      ],
      "source": [
        "print(P@A - L @ U)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 33,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[ 1.        ,  0.        ,  0.        ,  0.        ],\n",
              "       [ 0.93673604,  1.        ,  0.        ,  0.        ],\n",
              "       [ 0.91055425, -0.35441189,  1.        ,  0.        ],\n",
              "       [ 0.26450396, -0.02409714, -0.02133641,  1.        ]])"
            ]
          },
          "execution_count": 33,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "L"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 34,
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "array([[0., 1., 0., 0.],\n",
              "       [0., 0., 1., 0.],\n",
              "       [0., 0., 0., 1.],\n",
              "       [1., 0., 0., 0.]])"
            ]
          },
          "execution_count": 34,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "P"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": []
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3 (ipykernel)",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.6"
    },
    "widgets": {
      "state": {},
      "version": "1.1.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 1
}