{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1c701dd3f78d",
   "metadata": {},
   "source": [
    "# Can a pulse reverse dephasing?\n",
    "Compare indistinguishable static frequency offsets and a fluctuating environment. The detuning is an angular frequency. A perfect midpoint π pulse reverses its sign in the accumulated phase. Predict which noise timescales the pulse will reject before drawing the curves."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0c04f94ff414",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "sigma_per_ms = 1.2     # rms angular detuning in rad/ms\n",
    "tau_ms = 1.5           # correlation time in ms\n",
    "evolution_ms = 2.0\n",
    "assert sigma_per_ms > 0 and tau_ms>0 and evolution_ms>0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45a4d1be205e",
   "metadata": {},
   "source": [
    "## Integrate the noise covariance\n",
    "Use a Gaussian stationary process with covariance σ² exp(−|t−s|/τ). The ensemble coherence is exp(−variance of accumulated phase/2). A series near zero avoids subtracting almost equal floating-point numbers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "922753995ee3",
   "metadata": {},
   "outputs": [],
   "source": [
    "def exponents(t,tau,sigma):\n",
    "    x=np.asarray(t,dtype=float)/tau\n",
    "    small=x<1e-3\n",
    "    free=np.where(small,x**2/2-x**3/6+x**4/24,x+np.expm1(-x))\n",
    "    echo=np.where(small,x**3/12-x**4/32+7*x**5/960,x+4*np.expm1(-x/2)-np.expm1(-x))\n",
    "    return sigma**2*tau**2*free,sigma**2*tau**2*echo\n",
    "\n",
    "free,echo=exponents(evolution_ms,tau_ms,sigma_per_ms)\n",
    "print(f\"Contrast at T={evolution_ms:g} ms: free {np.exp(-free):.6f}; echo {np.exp(-echo):.6f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "56a6b9cd729f",
   "metadata": {},
   "source": [
    "## Locate the frequencies that the echo transmits\n",
    "For harmonic noise the squared Fourier integral of the switching function measures sensitivity. At zero frequency these two filters make opposite predictions. The vertical scale of the right panel is normalised by the square of the observation time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7682e478d875",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,ax=plt.subplots(1,2,figsize=(9,3.9),layout=\"constrained\")\n",
    "ts=np.linspace(0,3*evolution_ms,240)\n",
    "cf,ce=exponents(ts,tau_ms,sigma_per_ms)\n",
    "ax[0].plot(ts,np.exp(-cf),label=\"Free evolution\",color=\"#a23d21\")\n",
    "ax[0].plot(ts,np.exp(-ce),label=\"Midpoint echo\",color=\"#175868\")\n",
    "ax[0].plot(ts,np.exp(-.5*(sigma_per_ms*ts)**2),\"--\",label=\"Static offsets, free\",color=\"#777777\")\n",
    "ax[0].set(xlabel=\"Total evolution time (ms)\",ylabel=\"Normalised coherence\",title=\"Same noise, two pulse sequences\",ylim=(-.03,1.05)); ax[0].legend(fontsize=8)\n",
    "cycles=np.linspace(0,3,401); wT=2*np.pi*cycles\n",
    "ff=np.sinc(cycles)**2\n",
    "fe=np.zeros_like(wT); fe[1:]=16*np.sin(wT[1:]/4)**4/wT[1:]**2\n",
    "ax[1].plot(cycles,ff,label=\"Free evolution\",color=\"#a23d21\")\n",
    "ax[1].plot(cycles,fe,label=\"Midpoint echo\",color=\"#175868\")\n",
    "ax[1].set(xlabel=\"Noise cycles during T\",ylabel=\"Squared filter / T²\",title=\"Static and time-dependent fields\");ax[1].legend(fontsize=8)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e7d8e824479",
   "metadata": {},
   "source": [
    "## Test the analytic result without using its closed form\n",
    "Represent the sign function at midpoints of an even time grid. Use the matrix of pair covariances to evaluate the phase variance. Halve the time step and check the convergence. The pulse sign convention may be reversed globally without changing the contrast."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e09f6ff99092",
   "metadata": {},
   "outputs": [],
   "source": [
    "def numerical_chi(n,flip):\n",
    "    dt=evolution_ms/n\n",
    "    t=(np.arange(n)+.5)*dt\n",
    "    sign=np.where((t>=evolution_ms/2)&flip,-1.,1.)\n",
    "    cov=sigma_per_ms**2*np.exp(-abs(t[:,None]-t[None,:])/tau_ms)\n",
    "    return .5*dt**2*(sign@cov@sign)\n",
    "for n in (80,160,320):\n",
    "    print(n,numerical_chi(n,False),numerical_chi(n,True))\n",
    "assert abs(numerical_chi(320,True)-echo) < 2e-4*(1+sigma_per_ms**2*evolution_ms**2)*(1+evolution_ms/tau_ms)\n",
    "assert 0<=echo<=free+1e-12"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e1701bbbe83",
   "metadata": {},
   "source": [
    "## An optional single-spin check with OneSimulation\n",
    "Use exact matrix exponentiation through a Hermitian eigensystem. This checks the reversal for a constant detuning on one spin; the stochastic variance above describes an ensemble of many spins."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5edabbd57d6f",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    from onesim.numerics.linear.matrices.dense_linear_algebra import symmetric_eigensystem\n",
    "except ImportError:\n",
    "    print(\"The independent spin propagator is available in a local OneSimulation environment.\")\n",
    "else:\n",
    "    E,U=symmetric_eigensystem(np.diag([sigma_per_ms/2,-sigma_per_ms/2]))\n",
    "    half=(U*np.exp(-1j*E*evolution_ms/2))@U.T\n",
    "    pulse=np.array([[0,-1j],[-1j,0]])\n",
    "    initial=np.array([1,1])/np.sqrt(2)\n",
    "    final=half@pulse@half@initial\n",
    "    print(\"Echo return probability for a static detuning:\",abs(np.vdot(initial,final))**2)\n",
    "    assert np.isclose(abs(np.vdot(initial,final))**2,1.)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
