{ "cells": [ { "cell_type": "markdown", "id": "lab09-title", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Lab 09: Assignment 2 Tutorial\n", "\n", "In Assignment 1, we followed a wave packet in a harmonic well. Now put it in the right-hand well of a double-well potential." ] }, { "cell_type": "code", "execution_count": null, "id": "lab09-imports", "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from numba import njit\n", "\n", "# if you're curious, this is to change default formatting \n", "# make plots look good in the slideshow format.\n", "plt.rcParams.update({\"font.size\": 13,\n", " \"figure.figsize\": (6.2, 3.3), \"figure.dpi\": 100,\n", " \"figure.constrained_layout.use\": True})" ] }, { "cell_type": "markdown", "id": "lab09-opening-caption", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "We'll follow the probability density as the packet moves between the wells." ] }, { "cell_type": "markdown", "id": "lab09-grid", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Put the wavefunction on a grid\n", "\n", "We will store one complex amplitude at each position. Use $m=\\hbar=1$ and 600 intervals on $[-4,4]$." ] }, { "cell_type": "code", "execution_count": null, "id": "lab09-grid-code", "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "# coding culture: we tend to use capital letters when want to define \n", "# immutable constants that will be used throughout a whole script.\n", "ALPHA = 0.4\n", "HBAR = 1\n", "BOXSIZE = 8\n", "ND = 600\n", "DELTAX = BOXSIZE / ND\n", "XMIN = 1 / np.sqrt(ALPHA)\n", "x = np.linspace(-BOXSIZE / 2, BOXSIZE / 2, ND + 1)\n", "print(\"Positions:\", x.size, \"Spacing:\", DELTAX)" ] }, { "cell_type": "markdown", "id": "lab09-grid-discussion", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "There are 601 positions and 600 intervals. The spacing $\\Delta x$ will weight our spatial sums." ] }, { "cell_type": "markdown", "id": "lab09-potential", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Two wells and a barrier\n", "\n", "$$\n", "V(x)=\\alpha x^4-2x^2+\\frac{1}{\\alpha}.\n", "$$\n", "\n", "We'll use $\\alpha=0.4$ here. Use your assigned value in the homework." ] }, { "cell_type": "code", "execution_count": null, "id": "lab09-potential-plot", "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "# and then we use lowercase for more generic variables.\n", "@njit\n", "def V(x, alpha):\n", " return alpha * x**4 - 2 * x**2 + 1 / alpha\n", "\n", "alpha_view = ALPHA\n", "fig, ax = plt.subplots()\n", "ax.plot(x, V(x, alpha_view), color=\"black\")\n", "ax.set(xlabel=\"x\", ylabel=\"V(x)\",\n", " xlim=(-4, 4), ylim=(0, 6),\n", " title=f\"alpha = {alpha_view}\")\n", "ax.grid(True) \n", "plt.show()" ] }, { "cell_type": "markdown", "id": "lab09-potential-discussion", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "What happens when we set alpha to .6?" ] }, { "cell_type": "markdown", "id": "lab09-potential-comparison", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## After changing alpha" ] }, { "cell_type": "code", "execution_count": null, "id": "afcd4d38-e3a4-46da-a1f3-6791ae292ef1", "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "alpha_view = .6 # <==========================================\n", "fig, ax = plt.subplots()\n", "ax.plot(x, V(x, alpha_view), color=\"black\")\n", "ax.set(xlabel=\"x\", ylabel=\"V(x)\",\n", " xlim=(-4, 4), ylim=(0, 6),\n", " title=f\"alpha = {alpha_view}\")\n", "ax.grid(True) \n", "plt.show()" ] }, { "cell_type": "markdown", "id": "lab09-potential-comparison-note", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "This preview uses $\\alpha=0.6$. `ALPHA` is still 0.4." ] }, { "cell_type": "markdown", "id": "lab09-harmonic", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Near each minimum\n", "\n", "Expand around either minimum through second order. Since $V=V^{\\prime}=0$ and $V^{\\prime\\prime}=8$ there, the potential is locally quadratic:\n", "\n", "$$\n", "V_\\pm(x)=4(x\\mp x_{\\min})^2,\n", "$$\n", "\n", "with $x_{\\min}=1/\\sqrt{\\alpha}$" ] }, { "cell_type": "code", "execution_count": null, "id": "lab09-harmonic-plot", "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "alpha_view = ALPHA # let's not forget to turn this back to our universal CONSTANT\n", "@njit\n", "def V_plus(x, alpha): \n", " return 4 * (x - 1 / np.sqrt(alpha))**2\n", "@njit\n", "def V_minus(x, alpha):\n", " return 4 * (x + 1 / np.sqrt(alpha))**2\n", "\n", "def plot_potentials(ax, v_color, posv_color, negv_color):\n", " ax.plot(x, V(x, ALPHA), color=v_color)\n", " ax.plot(x, V_plus(x, ALPHA), \"--\", color=posv_color)\n", " ax.plot(x, V_minus(x, ALPHA), \":\", color=negv_color)\n", " ax.set(ylabel=\"Potential\", ylim=(0, 6),\n", " zorder=0)\n", " ax.legend([\"V\", \"V+\", \"V-\"],\n", " loc=\"upper right\", fontsize=10)\n", " \n", "x_window = (-4, 4)\n", "fig, ax = plt.subplots()\n", "\n", "plot_potentials(ax, v_color = ('black', 0.15), posv_color='red', negv_color='blue') # can you guess how to colors work here?\n", "ax.set(xlabel=\"x\", xlim=x_window)\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "lab09-harmonic-discussion", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "We'll use these local harmonic wells to choose the initial state." ] }, { "cell_type": "markdown", "id": "lab09-gaussian", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## The initial wavefunction\n", "\n", "We're approximating both wells locally as harmonic, so we might as well approximate the state as a ground state oscillator, with $\\omega=2\\sqrt{2}$ from $\\tfrac12\\omega^2=4$:\n", "\n", "$$\n", "\\psi(x)=\\left(\\frac{\\omega}{\\pi}\\right)^{1/4}\n", "\\exp\\left[-\\frac{\\omega}{2}(x-x_c)^2\\right],\n", "$$\n", "\n", "which remember is just a gaussian." ] }, { "cell_type": "code", "execution_count": null, "id": "lab09-gaussian-plot", "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "OMEGA = np.sqrt(8)\n", "@njit\n", "def func_psi_0(x, x_start):\n", " return (OMEGA / np.pi)**0.25 * np.exp(\n", " -OMEGA * (x - x_start)**2 / (2 * HBAR))\n", "\n", "psi_0 = func_psi_0(x, XMIN)\n", "center = XMIN\n", "\n", "fig, ax = plt.subplots()\n", "ax.plot(x, func_psi_0(x, center), color='red')\n", "ax.set(xlabel=\"x\", ylabel=\"Wavefunction\",\n", " zorder=1, xlim=(-4, 4), ylim=(0, 1.1),\n", " title=f\"Center = {center:.2f}\")\n", "\n", "ax.patch.set_visible(False)\n", "plot_potentials(ax.twinx(), v_color = ('black', .05), posv_color=('red', .15), negv_color=('blue', .1))\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "lab09-gaussian-answer", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "The Gaussian starts in the right well, centered at $x_c=x_{\\min}$." ] }, { "cell_type": "markdown", "id": "lab09-combinations", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Even and odd combinations\n", "\n", "The full potential has even and odd energy eigenstates (state functions).\n", "We can write our right-well Gaussian as a sum of even and odd combinations.\n", "This gives us a useful way to understand its motion between the wells.\n", "\n", "$$\n", "\\psi_{\\mathrm S}=\\frac{\\psi_++\\psi_-}{\\sqrt{2}},\\qquad\n", "\\psi_{\\mathrm A}=\\frac{\\psi_+-\\psi_-}{\\sqrt{2}}.\n", "$$\n", "\n", "### Even/odd function refresher\n", "
\n", "\n", "\n", "Reflecting $x$ swaps the two local Gaussians: $\\psi_+(-x)=\\psi_-(x)$ and $\\psi_-(-x)=\\psi_+(x)$. Therefore\n", "\n", "$$\n", "\\begin{aligned}\n", "\\psi_{\\mathrm S}(-x)&=\\frac{\\psi_-(x)+\\psi_+(x)}{\\sqrt2}=\\psi_{\\mathrm S}(x),\\\\\n", "\\psi_{\\mathrm A}(-x)&=\\frac{\\psi_-(x)-\\psi_+(x)}{\\sqrt2}=-\\psi_{\\mathrm A}(x).\n", "\\end{aligned}\n", "$$\n", "\n", "The even combination stays the same; the odd combination changes sign.\n", "\n", "
" ] }, { "cell_type": "code", "execution_count": null, "id": "lab09-combination-plot", "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "psi_plus = func_psi_0(x, XMIN)\n", "psi_minus = func_psi_0(x, -XMIN)\n", "psi_S = (psi_plus + psi_minus) / np.sqrt(2)\n", "psi_A = (psi_plus - psi_minus) / np.sqrt(2)\n", "\n", "fig, ax = plt.subplots()\n", "ax.plot(x, psi_S, label=\"Symmetric\", color='lightgreen')\n", "ax.plot(x, psi_A, label=\"Antisymmetric\", color='magenta')\n", "ax.axhline(0, color=\"gray\", linewidth=0.7)\n", "ax.set(xlabel=\"x\", ylabel=\"Wavefunction\",\n", " zorder=1, xlim=(-4, 4), ylim=(-1, 1.5))\n", "ax.legend(loc=\"upper left\", fontsize=10)\n", "ax.patch.set_visible(False)\n", "plot_potentials(ax.twinx(), v_color = ('black', .05), posv_color=('red', .15), negv_color=('blue', .1))\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "lab09-combinations-caption", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "So we've split the right-well Gaussian into pieces whose phases evolve at different rates. Our combinations approximate the lowest even and odd energy eigenstates, $\\phi_{\\mathrm S}$ and $\\phi_{\\mathrm A}$. Keeping these two states gives\n", "\n", "$$\n", "\\Psi(x,t)\\approx c_{\\mathrm S}\\phi_{\\mathrm S}(x)e^{-iE_{\\mathrm S}t/\\hbar}\n", "+c_{\\mathrm A}\\phi_{\\mathrm A}(x)e^{-iE_{\\mathrm A}t/\\hbar}.\n", "$$\n", "\n", "The coefficients come from the initial Gaussian. Both spatial functions can be real; the time factors supply the complex phase. As their relative phase changes, interference moves probability between the wells." ] }, { "cell_type": "markdown", "id": "lab09-kernel", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Advance the amplitudes\n", "\n", "Now evolve the Gaussian using the full double-well potential. As in Assignment 1, the short-time propagator carries amplitude from $x_a$ to $x_b$:\n", "\n", "$$\n", "\\tilde{\\mathcal K}(x_b,\\Delta t;x_a,0)=\n", "\\exp\\left[i\\left(\\frac{(x_b-x_a)^2}{2\\Delta t}\n", "-V\\left(\\frac{x_a+x_b}{2}\\right)\\Delta t\\right)\\right].\n", "$$" ] }, { "cell_type": "code", "execution_count": null, "id": "lab09-kernel-plot", "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "@njit\n", "def func_K(x_a, x_b, dt, alpha):\n", " kinetic = 0.5 * (x_b - x_a)**2 / dt\n", " potential = V((x_a + x_b) / 2, alpha) * dt\n", " return np.exp(1j * (kinetic - potential))" ] }, { "cell_type": "markdown", "id": "lab09-kernel-caption", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "Next, apply this propagator to every pair of positions on our grid." ] }, { "cell_type": "markdown", "id": "lab09-grid-propagation", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## From the propagator to the next state\n", "\n", "Add the complex amplitudes from every starting position. On the grid, the integral becomes a weighted sum:\n", "\n", "$$\n", "\\begin{aligned}\n", "\\psi(x_b,t+\\Delta t)&\\approx\\int \\mathcal K(x_b,x_a;\\Delta t)\\psi(x_a,t)\\,dx_a,\\\\\n", "\\psi_i(t+\\Delta t)&\\approx\\Delta x\\sum_j K_{ij}\\psi_j(t).\n", "\\end{aligned}\n", "$$" ] }, { "cell_type": "markdown", "id": "lab09-kernel-matrix", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Build the matrix\n", "\n", "Each column starts at one position; each row arrives at one position. Use the assignment's $\\Delta t=\\pi/128$ for the evolution.\n", "\n", "Compile the loops with `@njit`, as in Lab 08. The first call includes compilation." ] }, { "cell_type": "code", "execution_count": null, "id": "lab09-kernel-matrix-code", "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "@njit\n", "def build_kernel(x, dt, alpha):\n", " kernel = np.zeros((x.size, x.size),\n", " dtype=np.complex64)\n", " for i in range(x.size):\n", " for j in range(x.size):\n", " kernel[i, j] = func_K(\n", " x[j], x[i], dt, alpha)\n", " return kernel.astype(np.complex128)\n", "\n", "DELTAT = np.pi / 128\n", "K_dt = build_kernel(x, DELTAT, ALPHA)\n", "print(\"Kernel shape:\", K_dt.shape)" ] }, { "cell_type": "markdown", "id": "lab09-kernel-matrix-discussion", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "The matrix and state use `complex128` for Numba's matrix multiplication." ] }, { "cell_type": "markdown", "id": "lab09-step", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Take a step and inspect it\n", "\n", "The grid sum is a matrix–vector product. Normalize because our kernel omits the scalar prefactor." ] }, { "cell_type": "code", "execution_count": null, "id": "lab09-step-plot", "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "@njit\n", "def step(state, kernel, dx):\n", " updated = dx * (kernel @ state)\n", " norm = dx * np.sum(np.abs(updated)**2)\n", " return updated / np.sqrt(norm)\n", " \n", "@njit\n", "def evolve(state, kernel, dx, nt):\n", " psi = np.empty((nt + 1, state.size),\n", " dtype=np.complex128)\n", " psi[0] = state\n", " for n in range(nt):\n", " psi[n + 1] = step(psi[n], kernel, dx)\n", " return psi\n", "\n", "steps_view = 20\n", "psi_view = evolve(psi_0.astype(np.complex128),\n", " K_dt, DELTAX, steps_view)[-1]\n", " \n", "fig, ax = plt.subplots()\n", "ax.plot(x, np.abs(psi_0)**2, \"--\", label=\"t = 0\")\n", "ax.plot(x, np.abs(psi_view)**2, label=\"Later\")\n", "ax.set(xlabel=\"x\", ylabel=\"Probability density\",\n", " zorder=1, xlim=(-4, 4), ylim=(0, 1.3))\n", "ax.legend(loc=\"upper left\", fontsize=10)\n", "ax.patch.set_visible(False)\n", "\n", "plot_potentials(ax.twinx(), v_color = ('black', .5), posv_color=('red', 0), negv_color=('blue', 0))\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "lab09-step-discussion", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "Try `steps_view = 100` to follow the packet for a little longer.\n", "\n", "Numba compiles the whole loop in `evolve`. Each step uses the state from the previous step." ] }, { "cell_type": "markdown", "id": "lab09-evolve", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Follow the motion\n", "\n", "Run to $T=20\\pi$. The mean is the probability-weighted average of position:\n", "\n", "$$\n", "\\langle x\\rangle(t)\\approx\\Delta x\\sum_i x_i|\\psi(x_i,t)|^2.\n", "$$" ] }, { "cell_type": "code", "execution_count": null, "id": "lab09-mean-plot", "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "T0 = 20 * np.pi\n", "NT = int(T0 / DELTAT)\n", "t = np.arange(NT + 1) * DELTAT\n", "psi = evolve(psi_0.astype(np.complex128),\n", " K_dt, DELTAX, NT)\n", "prob = np.abs(psi)**2\n", "x_bar = DELTAX * (prob @ x)\n", "\n", "fig, ax = plt.subplots()\n", "ax.plot(t, x_bar)\n", "ax.axhline(0, color=\"gray\", linewidth=0.7)\n", "ax.set(xlabel=\"Time\", ylabel=\"Mean position\",\n", " xlim=(0, t[-1]))\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "lab09-evolve-discussion", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "Choose a time near the first broad minimum. We'll inspect the density at that time." ] }, { "cell_type": "markdown", "id": "lab09-density", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Check what the mean is telling us" ] }, { "cell_type": "code", "execution_count": null, "id": "lab09-density-plot", "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "time_view = 0\n", "n = np.argmin(np.abs(t - time_view))\n", "fig, ax = plt.subplots()\n", "ax.plot(x, prob[n])\n", "ax.set(xlabel=\"x\", ylabel=\"Probability density\",\n", " zorder=1, xlim=(-4, 4),\n", " ylim=(0, 1.1 * prob.max()),\n", " title=f\"t = {t[n]:.3f}\")\n", "ax.patch.set_visible(False)\n", "plot_potentials(ax.twinx(), v_color = ('black', .5), posv_color=('red', 0), negv_color=('blue', 0))\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "lab09-density-discussion", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "Set `time_view` to the time you chose from the mean-position plot." ] }, { "cell_type": "code", "execution_count": null, "id": "7e2a8307-f538-4211-b7ab-8a67c12883da", "metadata": {}, "outputs": [], "source": [ "from matplotlib.animation import FuncAnimation, PillowWriter\n", "from IPython.display import Image, display\n", "\n", "fps = 25\n", "frames = np.unique(np.linspace(0, len(t) - 1, 240, dtype=int))\n", "\n", "fig, ax = plt.subplots()\n", "line, = ax.plot(x, prob[0])\n", "ax.set(xlabel=\"x\", ylabel=\"Probability density\",\n", " zorder=1, xlim=(-4, 4),\n", " ylim=(0, 1.1 * prob.max()))\n", "title = ax.set_title(f\"t = {t[0]:.3f}\")\n", "\n", "ax.patch.set_visible(False)\n", "plot_potentials(\n", " ax.twinx(),\n", " v_color=('black', .5),\n", " posv_color=('red', 0),\n", " negv_color=('blue', 0)\n", ")\n", "\n", "def update(n):\n", " line.set_ydata(prob[n])\n", " title.set_text(f\"t = {t[n]:.3f}\")\n", " return line, title\n", "\n", "ani = FuncAnimation(\n", " fig, update, frames=frames,\n", " interval=1000 / fps, blit=False, repeat=True\n", ")\n", "\n", "gif_path = \"density_evolution.gif\"\n", "ani.save(gif_path, writer=PillowWriter(fps=fps), dpi=100)\n", "plt.close(fig)\n", "display(Image(filename=gif_path))" ] }, { "cell_type": "markdown", "id": "lab09-closing", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Back to Assignment 2\n", "\n", "Give the time and mean position at the first major minimum. Use the density at that time to explain whether most of the probability has reached the left well.\n", "\n", "For your assigned $\\alpha$, check that the run is long enough to see the transfer and return.\n", "\n", "Assignment 2 is due Monday, November 2." ] }, { "cell_type": "markdown", "id": "lab09-rise-note", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "Run cells in order. Shift+Enter selects the next cell on the same slide, leaving the result visible. Click the code cell to edit and run it again; Ctrl+Enter runs without changing the selected cell. After changing `ALPHA`, rerun from the setup onward. The preview controls redraw their own plots; use `ALPHA` in the setup to change the evolution." ] } ], "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.11.9" }, "rise": { "auto_select": "code", "center": false, "footer": "PHYS 142/242 · Lab 09", "header": "", "height": 720, "margin": 0.04, "minScale": 0.2, "scroll": true, "slideNumber": "c/t", "start_slideshow_at": "beginning", "theme": "simple", "transition": "none", "width": 1280 }, "title": "Lab 09: Assignment 2 Tutorial" }, "nbformat": 4, "nbformat_minor": 5 }