{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "linear-algeb-00",
   "metadata": {},
   "source": [
    "# Finding one vibration mode by counting eigenvalues\n",
    "Change the mass of one bead in a fixed-end chain. Use a three-term inertia recurrence to enclose the chosen eigenvalue without computing an eigenvector. Frequencies are measured in units of the frequency of a single spring and unit mass. The calculation runs with NumPy and Matplotlib."
   ]
  },
  {
   "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",
    "beads = 15\n",
    "middle_mass = 3.0\n",
    "mode = 5                   # one-based, starting at the lowest frequency\n",
    "assert 3 <= beads <= 100 and 0.2 <= middle_mass <= 10 and 1 <= mode <= beads\n",
    "masses = np.ones(beads)\n",
    "masses[beads // 2] = middle_mass\n",
    "diag = 2 / masses\n",
    "off = -1 / np.sqrt(masses[:-1] * masses[1:])\n",
    "A = np.diag(diag) + np.diag(off, 1) + np.diag(off, -1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "linear-algeb-02",
   "metadata": {},
   "source": [
    "## Count signed pivots\n",
    "In exact arithmetic each negative pivot contributes one eigenvalue below the shift as long as no pivot vanishes. For the unit-scale matrices in this notebook a vanishing pivot is replaced by a tiny negative pivot. This assigns an exact tie to the lower spectrum. The common test below also checks the count at an eigenvalue analytically known to be exact."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "linear-algeb-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "def inertia_count(a, b, shift):\n",
    "    floor = np.finfo(float).tiny * max(1.0, np.max(b*b, initial=0.0))\n",
    "    pivot = a[0] - shift\n",
    "    negatives = 0\n",
    "    for i in range(len(a)):\n",
    "        if abs(pivot) < floor:\n",
    "            pivot = -floor\n",
    "        negatives += int(pivot < 0)\n",
    "        if i + 1 < len(a):\n",
    "            pivot = a[i+1] - shift - (b[i]*b[i])/pivot\n",
    "    return negatives\n",
    "\n",
    "assert inertia_count(np.array([2., 2., 2.]), np.array([-1., -1.]), 2.0) == 2\n",
    "\n",
    "def enclosing_interval(a, b, k, rounds=44):\n",
    "    radii = np.r_[0., abs(b)] + np.r_[abs(b), 0.]\n",
    "    lower = float(min(a-radii) - 1)\n",
    "    upper = float(max(a+radii) + 1)\n",
    "    history = []\n",
    "    for _ in range(rounds):\n",
    "        center = (lower+upper)/2\n",
    "        history.append([lower, upper])\n",
    "        if inertia_count(a, b, center) < k:\n",
    "            lower = center\n",
    "        else:\n",
    "            upper = center\n",
    "    return lower, upper, np.array(history)\n",
    "\n",
    "left, right, history = enclosing_interval(diag, off, mode)\n",
    "reference = np.linalg.eigvalsh(A)\n",
    "assert left - 5e-13 <= reference[mode-1] <= right + 5e-13\n",
    "print(f\"Mode {mode}: eigenvalue in [{left:.12f}, {right:.12f}]\")\n",
    "print(f\"Angular frequency = {np.sqrt((left+right)/2):.8f} in spring–mass units.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "linear-algeb-04",
   "metadata": {},
   "source": [
    "## Locate the step; watch its bracket contract\n",
    "The staircase changes height when the trial shift crosses an eigenvalue. The second panel shows the bracket width after each iteration. Try a lighter bead. Does every mode move by the same amount?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "linear-algeb-05",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, (spectrum, convergence) = plt.subplots(1, 2, figsize=(10, 4.0), layout=\"constrained\")\n",
    "shifts = np.linspace(-0.15, reference[-1]+0.2, 500)\n",
    "spectrum.step(shifts, [inertia_count(diag, off, x) for x in shifts], where=\"post\", color=\"#145c71\")\n",
    "spectrum.axvline(reference[mode-1], color=\"#b94626\", ls=\"--\", label=f\"mode {mode}\")\n",
    "spectrum.set(xlabel=\"Shift in squared-frequency units\", ylabel=\"Eigenvalue count\", title=\"Count the negative pivots\")\n",
    "spectrum.legend()\n",
    "convergence.semilogy(range(1, len(history)+1), history[:,1]-history[:,0], color=\"#145c71\")\n",
    "convergence.set(xlabel=\"Bisection iteration\", ylabel=\"Bracket width\", title=\"One reliable binary digit per split\")\n",
    "for ax in (spectrum, convergence): ax.grid(alpha=.2)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "linear-algeb-06",
   "metadata": {},
   "source": [
    "## Independent checks\n",
    "With unit masses the eigenvalues follow from sine modes. An installed OneSimulation environment can cross-check the modified chain through its dense symmetric eigensolver."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "linear-algeb-07",
   "metadata": {},
   "outputs": [],
   "source": [
    "k = np.arange(1, beads+1)\n",
    "uniform = np.diag(np.full(beads,2.0)) + np.diag(-np.ones(beads-1),1) + np.diag(-np.ones(beads-1),-1)\n",
    "assert np.max(np.abs(np.linalg.eigvalsh(uniform) - 4*np.sin(k*np.pi/(2*(beads+1)))**2)) < 1e-12\n",
    "try:\n",
    "    from onesim.numerics.linear.matrices.dense_linear_algebra import symmetric_eigenvalues\n",
    "except ImportError:\n",
    "    print(\"Sine-spectrum and NumPy reference checks passed. OneSimulation comparison is available locally.\")\n",
    "else:\n",
    "    independent = symmetric_eigenvalues(A)\n",
    "    print(\"OneSimulation squared frequency:\", independent[mode-1])\n",
    "    assert np.allclose(independent, reference)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
