{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2f64e713acd9",
   "metadata": {},
   "source": [
    "# Reconstructing a grating from its own diffracted waves\n",
    "A periodic amplitude mask can reproduce its structure in empty space. Change the period while holding wavelength fixed. Decide whether the recurrence distance grows linearly or quadratically with period."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "123c828fbcb9",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "period_um = 12.\n",
    "wavelength_um = .6\n",
    "phase_rad = .55\n",
    "assert 0<wavelength_um/period_um<.45"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7eb944edc56",
   "metadata": {},
   "source": [
    "## Propagate each Fourier order\n",
    "Choose a smooth mask with two pairs of nonzero diffraction orders, avoiding ambiguous aperture-edge sampling. The longitudinal wave number uses the decaying square-root branch. Removing the common carrier leaves every intensity unchanged."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77cb62066d6a",
   "metadata": {},
   "outputs": [],
   "source": [
    "n=256\n",
    "u=np.arange(n)/n\n",
    "mask=.58+.22*np.cos(2*np.pi*u)+.12*np.cos(4*np.pi*u+phase_rad)\n",
    "m=np.fft.fftfreq(n)*n\n",
    "spectrum=np.fft.fft(mask)\n",
    "k=2*np.pi/wavelength_um; kx=2*np.pi*m/period_um\n",
    "kz=np.sqrt(k*k-kx*kx+0j); ztalbot=2*period_um**2/wavelength_um\n",
    "def field(frac,exact=False):\n",
    "    phase=(kz-k)*ztalbot if exact else -2*np.pi*m*m\n",
    "    return np.fft.ifft(spectrum*np.exp(1j*np.asarray(frac)[...,None]*phase),axis=-1)\n",
    "print(f\"Paraxial field recurrence distance {ztalbot:.4f} μm.\")\n",
    "print(\"RMS intensity discrepancy after one paraxial length:\",\n",
    "      np.sqrt(np.mean((abs(field(1,True))**2-mask**2)**2)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "973cc8d4a894",
   "metadata": {},
   "source": [
    "## Read the carpet before studying the cuts\n",
    "Dark and bright structures need not track geometrical ray paths. The image on the left uses exact angular-spectrum phases; compare the same grating at a quarter, half and full paraxial Talbot distance on the right."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1588928b6b6d",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,ax=plt.subplots(1,2,figsize=(9,3.9),layout=\"constrained\")\n",
    "z=np.linspace(0,1,240);image=abs(field(z,True))**2\n",
    "im=ax[0].pcolormesh(u,z,image,shading=\"auto\",cmap=\"viridis\")\n",
    "fig.colorbar(im,ax=ax[0],label=\"Intensity / incident intensity\")\n",
    "ax[0].set(xlabel=\"Lateral position x/d\",ylabel=\"Propagation distance z/zT\",title=\"Exact propagation of the mask\")\n",
    "for f,c,style in [(0.,\"#222222\",\"-\"),(.25,\"#375b9a\",\":\"),(.50,\"#175868\",\"-.\"),(1.,\"#a23d21\",\"--\")]:\n",
    "    ax[1].plot(u,abs(field(f,True))**2,color=c,ls=style,label=f\"z/zT = {f:g}\")\n",
    "ax[1].set(xlabel=\"Lateral position x/d\",ylabel=\"Relative intensity\",title=\"Planes of the Talbot carpet\");ax[1].legend(fontsize=8)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f7a35a16bb38",
   "metadata": {},
   "source": [
    "## Verify phase, translation and energy\n",
    "A half-recurrence is a translation by half a period for any periodic input within the paraxial model. At a quarter-recurrence the odd Fourier orders are multiplied by minus i. Exact propagation converges towards these predictions at smaller wavelength-to-period ratio. The chosen mask contains only propagating orders."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c96a5812e643",
   "metadata": {},
   "outputs": [],
   "source": [
    "assert np.allclose(field(1.),mask)\n",
    "assert np.allclose(field(.5),np.roll(mask,n//2))\n",
    "quarter=(1-1j)/2*mask+(1+1j)/2*np.roll(mask,n//2)\n",
    "assert np.allclose(field(.25),quarter)\n",
    "assert np.isclose(np.mean(abs(field(1.,True))**2),np.mean(mask**2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11f8c2c699f8",
   "metadata": {},
   "source": [
    "## Optional OneSimulation angular-spectrum solve\n",
    "This comparison exercises the library's forward or decaying longitudinal branch and its propagation operator with the same physical field. The Fourier-order derivation above remains independent."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5710785d6210",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    from onesim.physics.optics.propagation.numerics.angular_spectrum import AngularSpectrumPropagation, longitudinal_wavenumber\n",
    "except ImportError:\n",
    "    print(\"The optional optical propagation check runs locally with OneSimulation.\")\n",
    "else:\n",
    "    longitudinal=longitudinal_wavenumber(kx[:,None],k)\n",
    "    propagator=AngularSpectrumPropagation(longitudinal=longitudinal,forward=np.fft.fft,inverse=np.fft.ifft,reference_wavenumber=k)\n",
    "    result=propagator(mask,ztalbot)\n",
    "    print(\"Maximum complex-field discrepancy:\",np.max(abs(result-field(1.,True))))\n",
    "    assert np.allclose(result,field(1.,True),atol=1e-11)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
