{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "fundamentals": {
   "title": "Can a stable finite-element heat step turn a cold node negative?",
   "lead": "Start a conducting rod with one positive temperature pulse. Assemble the heat capacity from first principles and determine when an explicit step respects both decay and the sign of every temperature.",
   "unit_slug": "can-a-stable-heat-step-turn-negative"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "id": "36ecf04463fc",
   "metadata": {},
   "source": [
    "# Can a stable finite-element heat step turn a cold node negative?\n",
    "\n",
    "Start a conducting rod with one positive temperature pulse. Assemble the heat capacity from first principles and determine when an explicit step respects both decay and the sign of every temperature."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9cb6b5a69a3d",
   "metadata": {
    "fundamentals": {
     "section": "derive-the-model"
    }
   },
   "source": [
    "## Integrate the heat equation against a hat function\n",
    "\n",
    "Take a uniform rod of length one with the two endpoint temperatures held at zero. With constant diffusivity $\\kappa>0$ the evolution is $u_t=\\kappa u_{xx}$. Approximate $u(x,t)$ as a linear combination of continuous piecewise-linear hat functions. Multiply by an interior hat and integrate. Integration by parts transfers one spatial derivative onto each hat. The boundary term vanishes. The nodal temperature vector satisfies\n",
    "\n",
    "$$\n",
    "M\\dot u=-Ku.\n",
    "$$\n",
    "\n",
    "On an element of length $h$ the two hats are $1-x/h$ and $x/h$ in local coordinates. Integrating their products gives diagonal entries $h/3$ and off-diagonal entries $h/6$ in the element mass matrix. Their constant derivatives give diagonal stiffness $\\kappa/h$ and off-diagonal stiffness $-\\kappa/h$. After assembly and imposing Dirichlet values, the interior mass has diagonal $4h/6$ and neighbouring entries $h/6$. The stiffness has diagonal $2\\kappa/h$ and neighbours $-\\kappa/h$.\n",
    "\n",
    "Forward Euler advances with $G=I-\\Delta t M^{-1}K$. On an eigenvector of $K\\phi=\\lambda M\\phi$ it multiplies the amplitude by $1-\\Delta t\\lambda$. A bound $\\Delta t\\lambda_{\\max}\\leq2$ therefore ensures no growth in the mass norm. Preserving nonnegative temperatures for every nonnegative initial vector requires every entry of $G$ to be nonnegative. Each column is the response to a single positive nodal impulse, so the latter condition can be tested directly.\n",
    "\n",
    "One alternative assigns half of each element's total heat capacity to each endpoint, before removing boundary degrees of freedom. Each interior mass then equals $h$ and the explicit stencil has weights $r,1-2r,r$, with $r=\\kappa\\Delta t/h^2$. These coefficients are all nonnegative for $0\\leq r\\leq 1/2$. The first and last interior equations also couple to the fixed zero boundary temperatures."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7160a2dd35f",
   "metadata": {
    "fundamentals": {
     "section": "worked-prediction"
    }
   },
   "source": [
    "## Compute the remote temperature after one update\n",
    "\n",
    "With three interior nodes, $h=1/4$, initially set the left interior node to 1 K above the boundary reference and both others to zero. Inverting the consistent mass in this three-by-three system gives the first column of $(h^2/\\kappa)M^{-1}K$ as $(51,-36,9)/14$. At $r=0.1$ the interior temperatures after one step become $(0.63571,0.25714,-0.06429)$ K. The cold node two edges away immediately drops below the lower reference.\n",
    "\n",
    "The largest dimensionless eigenvalue is about 7.9223. The chosen step gives $r\\lambda_{\\max}h^2/\\kappa\\approx0.7922$, comfortably inside the linear stability interval. Lumping instead gives $(0.8,0.1,0)$ K. The negative consistent-mass entry shrinks linearly when the step shrinks. For this impulse its sign persists for every positive first step. With OneSimulation installed locally, the notebook also constructs a physical line mesh and obtains the mass and stiffness by integrating its hat functions at mapped quadrature points. Compare the assembled result against the explicit tridiagonal entries. The experiment shows why reducing the time step can satisfy a stability test without restoring a discrete maximum principle."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d197fc17274",
   "metadata": {
    "fundamentals": {
     "section": "choose-inputs",
     "notebook_only": true
    }
   },
   "source": [
    "## Set the experimental inputs\n",
    "\n",
    "Edit these values, then run the calculation and both figures again."
   ]
  },
  {
   "cell_type": "code",
   "id": "1f8e87e52711",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "teal, orange, blue = \"#19596a\", \"#aa462a\", \"#3868a0\"\n",
    "def axes(xlabel, ylabel):\n",
    "    fig, ax = plt.subplots(figsize=(7, 4), constrained_layout=True)\n",
    "    ax.set(xlabel=xlabel, ylabel=ylabel)\n",
    "    ax.grid(alpha=0.2)\n",
    "    return fig, ax"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "897146321247",
   "metadata": {},
   "source": [
    "interior_nodes = 3\n",
    "diffusivity = 1.0\n",
    "r = 0.10"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "ac0e6c9f6ded",
   "metadata": {},
   "source": [
    "assert 3 <= interior_nodes <= 60 and diffusivity > 0 and 0 < r <= 1\n",
    "n = interior_nodes\n",
    "h = 1/(n+1)\n",
    "near = np.diag(np.ones(n-1),1)+np.diag(np.ones(n-1),-1)\n",
    "mass = h*(4*np.eye(n)+near)/6\n",
    "stiffness = diffusivity*(2*np.eye(n)-near)/h\n",
    "dimensionless = h*h*np.linalg.solve(mass,stiffness)/diffusivity\n",
    "lumped = 2*np.eye(n)-near\n",
    "u0 = np.zeros(n); u0[0]=1\n",
    "consistent_u = u0-r*dimensionless@u0\n",
    "lumped_u = u0-r*lumped@u0\n",
    "theta = np.pi*np.arange(1,n+1)/(n+1)\n",
    "eigen = 6*(1-np.cos(theta))/(2+np.cos(theta))\n",
    "assert np.allclose(np.sort(np.linalg.eigvals(dimensionless)),eigen)\n",
    "assert np.isclose(consistent_u[2],-r*dimensionless[2,0]) and consistent_u[2]<0\n",
    "if r<=0.5: assert lumped_u.min() >= -1.e-12\n",
    "print(f\"Time step {r*h*h/diffusivity:.6f}, largest stable r {2/eigen.max():.6f}\")\n",
    "print(\"First three nodal temperatures:\",consistent_u[:3],lumped_u[:3])\n",
    "try:\n",
    "    from onesim.cad.d1 import Line\n",
    "    from onesim.meshing import StructuredLineMesher\n",
    "    from onesim.numerics.fem.backends.spaces.line_lagrange import LineLagrangeSpace\n",
    "except ImportError:\n",
    "    print(\"The independent OneSimulation element check is available in a local installation.\")\n",
    "else:\n",
    "    rod = Line(start=(0,0,0),end=(1,0,0))\n",
    "    grid = StructuredLineMesher(cells=n+1).generate(rod)\n",
    "    space = LineLagrangeSpace(grid,order=1)\n",
    "    assembled_mass = np.zeros((n+2,n+2))\n",
    "    assembled_stiffness = np.zeros_like(assembled_mass)\n",
    "    for cell,dofs in enumerate(space.cells):\n",
    "        _,w,(phi,dx,_) = space.element_data(cell)\n",
    "        local = np.ix_(dofs,dofs)\n",
    "        assembled_mass[local] += (phi.T*w) @ phi\n",
    "        assembled_stiffness[local] += diffusivity*(dx.T*w) @ dx\n",
    "    assert np.allclose(assembled_mass[1:-1,1:-1],mass)\n",
    "    assert np.allclose(assembled_stiffness[1:-1,1:-1],stiffness)\n",
    "    print(\"OneSimulation line-element assembly agrees for both matrices.\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "1727e277b2c9",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "partial-differential-equations-partial-differential-equations-methods-1.png",
      "alt": "After a local initial pulse the consistent mass gives a negative distant node, while lumping keeps this node at zero.",
      "caption": "Line segments are the linear finite-element interpolants. Both ends have a fixed zero temperature and participate in the heat balance."
     }
    }
   },
   "source": [
    "x = h*np.arange(n+2)\n",
    "fig, ax = axes(\"Coordinate along rod\", \"Temperature above boundary reference (K)\")\n",
    "for values,col,style,label in [(u0,\"#747474\",\":\",\"Initial\"),(consistent_u,orange,\"-\",\"Consistent mass\"),\n",
    "                                (lumped_u,teal,\"--\",\"Lumped mass\")]:\n",
    "    ax.plot(x,np.r_[0.,values,0.],ls=style,marker=\"o\",ms=3,color=col,label=label)\n",
    "ax.axhline(0,color=\"#555\",lw=.7)\n",
    "ax.legend()\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "b943e7db1f0a",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "Line segments are the linear finite-element interpolants. Both ends have a fixed zero temperature and participate in the heat balance."
   ]
  },
  {
   "cell_type": "code",
   "id": "49e55c080b83",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "partial-differential-equations-partial-differential-equations-methods-2.png",
      "alt": "The remote temperature is negative throughout a range where the consistent system still passes the spectral stability test.",
      "caption": "The orange trace is the one-step temperature at the third interior node. The vertical line is the exact stability threshold for this mesh. Crossing it eventually produces amplification greater than one."
     }
    }
   },
   "source": [
    "fig, ax = axes(\"Dimensionless time step r\", \"Remote nodal temperature (K)\")\n",
    "sweep = np.linspace(0,max(.55,1.12*r),201)\n",
    "ax.plot(sweep,-sweep*dimensionless[2,0],color=orange,label=\"Third node after one step\")\n",
    "ax.axvline(2/eigen.max(),color=\"#444\",ls=\":\",label=\"Stability limit\")\n",
    "ax.scatter(r,consistent_u[2],color=orange)\n",
    "right = ax.twinx(); right.set_ylabel(\"Largest mode amplification\")\n",
    "right.plot(sweep,np.max(np.abs(1-sweep[:,None]*eigen),axis=1),color=teal,label=\"Spectral radius\")\n",
    "right.axhline(1,color=teal,ls=\"--\",lw=.9)\n",
    "ax.legend(loc=\"center left\",fontsize=8);right.legend(loc=\"upper center\",fontsize=8)\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "809c12f8f996",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "The orange trace is the one-step temperature at the third interior node. The vertical line is the exact stability threshold for this mesh. Crossing it eventually produces amplification greater than one."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "715121e85a68",
   "metadata": {
    "fundamentals": {
     "section": "problem-1"
    }
   },
   "source": [
    "## Exercise · keep the lumped temperatures nonnegative\n",
    "\n",
    "Suppose $h=0.02$ m and $\\kappa=8\\times10^{-5}$ m²/s. Find the greatest time step allowed by nonnegative weights. What stencil results at that step?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee8b63872172",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "The condition gives $\\Delta t=h^2/(2\\kappa)=2.5$ s. The central coefficient vanishes and each adjacent value receives weight one half. At the first interior node the fixed boundary value supplies one of these two terms. A step slightly above this threshold gives a negative central coefficient and can drive an isolated positive impulse below zero."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c82e86a4e52",
   "metadata": {
    "fundamentals": {
     "section": "problem-2"
    }
   },
   "source": [
    "## Exercise · derive the largest mode on successively finer meshes\n",
    "\n",
    "An interior sine wave has neighbouring sum $2\\cos(\\theta)$ times its own nodal value. Use this fact to find the limiting stability condition for forward Euler with consistent mass as the number of uniform elements grows."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6893a76404f6",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "The mass eigenvalue is $h(2+\\cos\\theta)/3$ and the stiffness eigenvalue is $2\\kappa(1-\\cos\\theta)/h$. Their ratio, multiplied by $h^2/\\kappa$, is $6(1-\\cos\\theta)/(2+\\cos\\theta)$. The largest allowed angle tends to $\\pi$, giving 12. The limiting stable step therefore has $r\\leq1/6$. A positivity test still inspects the entries of the update matrix separately."
   ]
  }
 ]
}
