{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "fundamentals": {
   "title": "Read twist and mismatch from the moiré of two lattices",
   "lead": "Stack two square grids that differ slightly in orientation or pitch. The slowly varying registry map is visible over many unit cells. Derive its scale and direction in reciprocal space, and find which combinations of layer parameters a single period measurement can resolve.",
   "unit_slug": "lattice-mismatch-and-moire-registry"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "id": "98f0f42a688f",
   "metadata": {},
   "source": [
    "# Read twist and mismatch from the moiré of two lattices\n",
    "\n",
    "Stack two square grids that differ slightly in orientation or pitch. The slowly varying registry map is visible over many unit cells. Derive its scale and direction in reciprocal space, and find which combinations of layer parameters a single period measurement can resolve."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "efcaa280102c",
   "metadata": {
    "fundamentals": {
     "section": "derive-the-model"
    }
   },
   "source": [
    "## Subtract two spatial phases\n",
    "\n",
    "One family of planes in layer one carries a density modulation proportional to $\\cos(\\mathbf G_1\\cdot\\mathbf r)$, with $|\\mathbf G_1|=2\\pi/a$. Layer two has spacing $a(1+\\delta)$ and is rotated by $\\theta$. Multiplying their modulations, as in a local registry correlation, produces half the sum of two cosines. The rapidly varying term contains $\\mathbf G_1+\\mathbf G_2$; averaging over several original cells leaves the term with $\\Delta\\mathbf G=\\mathbf G_1-\\mathbf G_2$. A distance parallel to $\\Delta\\mathbf G$ that advances the resulting phase by $2\\pi$ spans one full registry period.\n",
    "\n",
    "Taking the dot product of the rotated reciprocal vectors gives the exact geometric scale\n",
    "\n",
    "$$\\frac{\\Lambda}{a}=\\left[1+\\frac{1}{(1+\\delta)^2}-\\frac{2\\cos\\theta}{1+\\delta}\\right]^{-1/2}. $$\n",
    "\n",
    "The second perpendicular family of a square lattice rotates and rescales the same way. Its difference vector is perpendicular to the first and has the same magnitude. Their two slow cosines generate a square registry pattern. For small mismatch and small twist measured in radians the period is approximately $a/\\sqrt{\\delta^2+\\theta^2}$. The interference construction specifies a local continuum period. An exact common atomistic supercell would require additional commensurability conditions."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e474c154c61a",
   "metadata": {
    "fundamentals": {
     "section": "worked-prediction"
    }
   },
   "source": [
    "## Interpret a long measured period\n",
    "\n",
    "Take $a=0.246$ nm, mismatch 1.3 percent and twist two degrees. In units of $2\\pi/a$ the horizontal family's difference vector is $(1-\\cos\\theta/(1+\\delta),-\\sin\\theta/(1+\\delta))$, approximately $(0.0134,-0.0345)$. Its length is about 0.0370, so the registry period reaches about 6.65 nm. Each layer still has a spacing near a quarter nanometre. The larger scale is the distance over which small phase differences accumulate.\n",
    "\n",
    "If an image measures only this period and the first layer spacing, it supplies a single scalar for the two unknowns $\\delta$ and $\\theta$. A reciprocal-space measurement referenced to the first lattice supplies direction as well. In the simple isotropic model this resolves the rotated and rescaled vector by $\\mathbf G_2=\\mathbf G_1-\\Delta\\mathbf G$. Additional distortions or strain require more directions before an inversion is possible."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c0e2b4e58cb3",
   "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": "e08be5ecbc83",
   "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": "4a8d972c8f1d",
   "metadata": {},
   "source": [
    "spacing_nm = .246\n",
    "mismatch = .013\n",
    "twist_deg = 2."
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "5c91040d2fe4",
   "metadata": {},
   "source": [
    "assert spacing_nm>0 and mismatch>-1\n",
    "angle = np.deg2rad(twist_deg)\n",
    "g = 2*np.pi/spacing_nm\n",
    "g1 = np.array([g,0.])\n",
    "g2 = g*np.array([np.cos(angle),np.sin(angle)])/(1+mismatch)\n",
    "difference = g1-g2\n",
    "norm = np.linalg.norm(difference)\n",
    "period = 2*np.pi/norm if norm>1e-12*g else np.inf\n",
    "orthogonal = np.array([-difference[1],difference[0]])\n",
    "assert np.isclose(np.dot(difference,orthogonal),0,atol=1e-10)\n",
    "print(f\"Registry period {period:.5g} nm; difference vector {difference} per nm\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "f6908837f7cb",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "condensed-matter-condensed-matter-methods-1.png",
      "alt": "Two orthogonal families of reciprocal vectors appear for both square lattices, with an enlargement of the displacement between the nearly coincident horizontal tips.",
      "caption": "The right panel enlarges the displacement between reciprocal-vector tips. Its direction is the normal to one family of registry fringes."
     }
    }
   },
   "source": [
    "fig,(ax,zoom) = plt.subplots(1,2,figsize=(7,4),constrained_layout=True)\n",
    "def arrow(axis,start,vector,colour):\n",
    "    axis.annotate(\"\",xy=start+vector,xytext=start,arrowprops=dict(arrowstyle=\"->\",color=colour,lw=2))\n",
    "for vec,colour,label in [(g1,teal,\"Layer 1\"),(g2,orange,\"Layer 2\")]:\n",
    "    arrow(ax,np.zeros(2),vec,colour)\n",
    "    second = np.array([-vec[1],vec[0]])\n",
    "    arrow(ax,np.zeros(2),second,colour)\n",
    "    ax.plot(vec[0],vec[1],\"o\",color=colour,label=label)\n",
    "    ax.plot(second[0],second[1],\"o\",color=colour)\n",
    "full_vectors=np.array([g1,g2,[0,g],[-g2[1],g2[0]],[0,0]])\n",
    "low=full_vectors.min();high=full_vectors.max();pad_full=.12*(high-low)\n",
    "ax.set(xlim=(low-pad_full,high+pad_full),ylim=(low-pad_full,high+pad_full))\n",
    "arrow(zoom,g2,difference,blue);zoom.scatter([g1[0],g2[0]],[g1[1],g2[1]],c=[teal,orange])\n",
    "pad=max(norm*.7,g*.02);centre=(g1+g2)/2\n",
    "zoom.set(xlim=(centre[0]-pad,centre[0]+pad),ylim=(centre[1]-pad,centre[1]+pad))\n",
    "for axis,heading in [(ax,\"Reciprocal vectors\"),(zoom,\"Difference at the tips\")]:\n",
    "    axis.set(xlabel=\"Gx (nm⁻¹)\",ylabel=\"Gy (nm⁻¹)\",title=heading);axis.set_aspect(\"equal\",adjustable=\"box\");axis.grid(alpha=.2)\n",
    "ax.legend(loc=\"best\",fontsize=8)\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "e8246d71f6e1",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "The right panel enlarges the displacement between reciprocal-vector tips. Its direction is the normal to one family of registry fringes."
   ]
  },
  {
   "cell_type": "code",
   "id": "876ffa22e972",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "condensed-matter-condensed-matter-methods-2.png",
      "alt": "A two-dimensional grayscale registry field has a spatial period much larger than either single-layer spacing for small mismatch and twist.",
      "caption": "The map sums the two perpendicular slow modulations; the colour bar measures their dimensionless average. At perfect alignment with equal spacing the registry is constant everywhere."
     }
    }
   },
   "source": [
    "extent = 1.5*period if np.isfinite(period) else 10*spacing_nm\n",
    "x = np.linspace(-extent,extent,251)\n",
    "X,Y = np.meshgrid(x,x)\n",
    "registry = (np.cos(difference[0]*X+difference[1]*Y)+np.cos(orthogonal[0]*X+orthogonal[1]*Y))/2\n",
    "fig,ax=axes(\"Horizontal distance (nm)\",\"Vertical distance (nm)\")\n",
    "image=ax.imshow(registry,origin=\"lower\",extent=(-extent,extent,-extent,extent),vmin=-1,vmax=1,cmap=\"Greys\")\n",
    "ax.grid(False);fig.colorbar(image,ax=ax,label=\"Registry correlation\")\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "dc651a6a72f4",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "The map sums the two perpendicular slow modulations; the colour bar measures their dimensionless average. At perfect alignment with equal spacing the registry is constant everywhere."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e40e03313b74",
   "metadata": {
    "fundamentals": {
     "section": "problem-1"
    }
   },
   "source": [
    "## Exercise · determine a twist from pure rotation\n",
    "\n",
    "The lattice spacings have been verified equal at 0.246 nm. What is the magnitude of the twist if the registry spacing is 10.0 nm?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "529e8ff66c30",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "With $\\delta=0$, the reciprocal vectors form an isosceles triangle and $\\Lambda=a/[2|\\sin(\\theta/2)|]$. The small positive solution is $2\\arcsin(0.246/20.0)=0.02460$ rad or 1.41 degrees. Changing the twist sign reflects the pattern without changing its period."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47f3848a108d",
   "metadata": {
    "fundamentals": {
     "section": "problem-2"
    }
   },
   "source": [
    "## Exercise · make the same spacing with no twist\n",
    "\n",
    "Use the same first-layer spacing and measured 10.0 nm period. What positive mismatch would explain the observation for aligned layers?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a2d7adfb03fb",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "At $\\theta=0$ and positive mismatch,\n",
    "\n",
    "$$\n",
    "\\Lambda=a(1+\\delta)/\\delta.\n",
    "$$\n",
    "\n",
    "Solving gives $\\delta=a/(\\Lambda-a)=0.02522$, about 2.52 percent. Comparing this result with the previous exercise shows explicitly why period alone cannot identify a twist."
   ]
  }
 ]
}
