{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "linear-algeb-00",
   "metadata": {},
   "source": [
    "# Elimination growth with small multipliers\n",
    "This integer family isolates growth during elimination from the sensitivity of a linear system. Change the dimension and compare the largest numbers produced with a direct condition estimate. The displayed elimination keeps the first row when pivot sizes tie."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "linear-algeb-01",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "dimension = 12\n",
    "assert 3 <= dimension <= 40\n",
    "\n",
    "def example(n):\n",
    "    A = np.eye(n)-np.tril(np.ones((n,n)),-1)\n",
    "    A[:,-1] = 1.\n",
    "    return A\n",
    "\n",
    "def eliminate(A):\n",
    "    U=A.copy()\n",
    "    growth=[np.max(abs(U))]\n",
    "    multipliers=[]\n",
    "    for j in range(len(U)-1):\n",
    "        k=j+np.argmax(abs(U[j:,j]))\n",
    "        U[[j,k]]=U[[k,j]]\n",
    "        m=U[j+1:,j]/U[j,j]\n",
    "        multipliers.extend(m)\n",
    "        U[j+1:,j:] -= m[:,None]*U[j,j:]\n",
    "        growth.append(np.max(abs(U)))\n",
    "    return U,np.array(growth),max(abs(np.array(multipliers)))\n",
    "\n",
    "A=example(dimension)\n",
    "U,history,mmax=eliminate(A)\n",
    "assert np.allclose(history,2.**np.arange(dimension))\n",
    "print(\"Growth factor:\",history[-1],\" largest multiplier:\",mmax)\n",
    "print(\"2-norm condition number:\",np.linalg.cond(A))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "linear-algeb-02",
   "metadata": {},
   "source": [
    "## Compare the pivot bound with the growth and conditioning\n",
    "The exponential growth is exact in binary for these small integer inputs. It gives a possible roundoff hazard for perturbed problems; it does not prove large forward error in this exact demonstration."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "linear-algeb-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,(steps,scale)=plt.subplots(1,2,figsize=(10,4),layout=\"constrained\")\n",
    "steps.semilogy(range(dimension),history,\"o-\",color=\"#145c71\")\n",
    "steps.set(xlabel=\"Eliminated columns\",ylabel=\"Largest absolute entry\",title=\"The last column repeatedly doubles\")\n",
    "nn=np.arange(3,dimension+1)\n",
    "scale.semilogy(nn,2.**(nn-1),\"o-\",color=\"#145c71\",label=\"growth factor\")\n",
    "scale.semilogy(nn,[np.linalg.cond(example(i)) for i in nn],\"s--\",color=\"#b94626\",label=\"condition number\")\n",
    "scale.set(xlabel=\"Matrix dimension\",ylabel=\"Dimensionless factor\",title=\"Different questions about a system\")\n",
    "scale.legend()\n",
    "for ax in (steps,scale):ax.grid(alpha=.2)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "linear-algeb-04",
   "metadata": {},
   "source": [
    "## Challenge\n",
    "Reorder the rows before calling eliminate. What changes in the growth history when pivot ties are resolved differently? Which singular values remain unchanged under the row permutation?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "linear-algeb-05",
   "metadata": {},
   "outputs": [],
   "source": [
    "_,reverse,_=eliminate(A[::-1])\n",
    "assert np.isclose(np.linalg.cond(A),np.linalg.cond(A[::-1]))\n",
    "print(\"After reversing the rows, observed growth becomes\",reverse[-1])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
