{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "36dd2cba0ebb",
   "metadata": {},
   "source": [
    "# Can one isotope trap a lattice vibration?\n",
    "The springs are identical and a single mass differs from the rest. Predict which sign of mass change produces a mode above the propagation band. The chain is periodic so an edge cannot trap the vibration."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b59c0ea81890",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "mass_ratio = .60       # impurity mass / host mass; also try 1 or 1.4\n",
    "sites = 80             # even, to include the host zone boundary on the mesh\n",
    "assert .12<=mass_ratio<=2 and 12<=sites<=180 and sites%2==0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85cc4e9576cf",
   "metadata": {},
   "source": [
    "## Assemble the symmetric eigenproblem\n",
    "Use host mass and spring constant as units. Converting from mass-weighted coordinates back to actual site displacement matters most at the impurity."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "34232cc3a182",
   "metadata": {},
   "outputs": [],
   "source": [
    "def dynamical(n,r):\n",
    "    K=2*np.eye(n)-np.roll(np.eye(n),1,axis=1)-np.roll(np.eye(n),-1,axis=1)\n",
    "    mass=np.ones(n);mass[n//2]=r\n",
    "    return K/np.sqrt(mass[:,None]*mass[None,:]),mass\n",
    "D,mass=dynamical(sites,mass_ratio)\n",
    "values,vec=np.linalg.eigh(D); w=np.sqrt(max(values[-1],0))\n",
    "u=vec[:,-1]/np.sqrt(mass)\n",
    "u/=np.max(abs(u))\n",
    "if u[sites//2]<0:u=-u\n",
    "weight=mass*u*u;weight/=weight.sum()\n",
    "pos=np.arange(sites)-sites//2\n",
    "print(f\"Numerical frequency {w:.6f} in units of sqrt(K/M); impurity kinetic weight {weight[sites//2]:.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f1670b95721d",
   "metadata": {},
   "source": [
    "## Compare the spatial profile and the infinite-chain dispersion\n",
    "The analytic profile alternates sign when the frequency lies above the band. No decaying above-band solution exists for a heavy defect; its uppermost finite-chain mode remains a valid numerical eigenvector."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "530ce2178c65",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,ax=plt.subplots(1,2,figsize=(9,3.9),layout=\"constrained\")\n",
    "ax[0].plot(pos,u,\"o-\",ms=3,color=\"#175868\",label=\"Periodic-chain eigenvector\")\n",
    "if mass_ratio<1:\n",
    "    r=mass_ratio/(2-mass_ratio)\n",
    "    ax[0].plot(pos,(-r)**abs(pos),\"x\",color=\"#a23d21\",label=\"Infinite chain\")\n",
    "ax[0].set(xlabel=\"Site relative to impurity\",ylabel=\"Relative displacement\",title=\"Highest-frequency mode\",\n",
    "          xlim=(-min(12,sites//2),min(12,sites//2)));ax[0].legend(fontsize=8)\n",
    "ratios=np.linspace(.22,1.8,48)\n",
    "finite=[np.sqrt(np.linalg.eigvalsh(dynamical(min(48,sites),q)[0])[-1]) for q in ratios]\n",
    "qs=np.linspace(.22,.999,200)\n",
    "ax[1].plot(ratios,finite,\".\",color=\"#375b9a\",label=\"Finite chain\")\n",
    "ax[1].plot(qs,2/np.sqrt(qs*(2-qs)),color=\"#a23d21\",label=\"Localised solution\")\n",
    "ax[1].axhline(2,ls=\":\",color=\"#175868\",label=\"Host band edge\");ax[1].plot(mass_ratio,w,\"o\",color=\"#175868\")\n",
    "ax[1].set(xlabel=\"Impurity / host mass\",ylabel=\"Frequency / √(K/M)\",title=\"How the local mode detaches\");ax[1].legend(fontsize=8)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "97a61e7fe8c8",
   "metadata": {},
   "source": [
    "## Test translation symmetry and the original force balance\n",
    "Check the acoustic mode and the equation before mass weighting. Increase the ring size at a mass ratio just below one and track the small difference between the numerical eigenfrequency and the infinite-chain limit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "97ee2eef4962",
   "metadata": {},
   "outputs": [],
   "source": [
    "assert abs(values[0])<1e-12\n",
    "res=2*u-np.roll(u,1)-np.roll(u,-1)-w*w*mass*u\n",
    "assert np.max(abs(res))<1e-10\n",
    "if mass_ratio<1:\n",
    "    analytic=2/np.sqrt(mass_ratio*(2-mass_ratio)); length=-1/np.log(mass_ratio/(2-mass_ratio))\n",
    "    print(f\"Infinite-chain frequency {analytic:.6f}, decay length {length:.3f} spacings\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "723d3d335a2e",
   "metadata": {},
   "source": [
    "## Optional independent OneSimulation eigensolve\n",
    "Run the identical mass-weighted operator through the OneSimulation symmetric eigensystem interface, then check its highest eigenvalue and residual in the original coordinates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1a8fd87e9ce1",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    from onesim.numerics.linear.matrices.dense_linear_algebra import symmetric_eigensystem\n",
    "except ImportError:\n",
    "    print(\"The optional eigensolver check runs in a local OneSimulation installation.\")\n",
    "else:\n",
    "    E,Q=symmetric_eigensystem(D)\n",
    "    print(\"OneSimulation eigenvalue residual:\",np.linalg.norm(D@Q[:,-1]-E[-1]*Q[:,-1]))\n",
    "    assert np.isclose(E[-1],w*w)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
