{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "approximatio-00",
   "metadata": {},
   "source": [
    "# Endpoint singularities with tanh–sinh quadrature\n",
    "Estimate the integral of x raised to minus alpha on [0,1]. The integrand is unbounded, yet its integral exists for alpha below one. Compare the physical midpoint grid with a double-exponential change of variable. All controls and calculations run with NumPy and Matplotlib."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "approximatio-01",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "alpha = 0.65\n",
    "cutoff = 3.0                  # half-width in transformed coordinates\n",
    "step = 0.25\n",
    "assert 0.05 <= alpha <= 0.95 and 1 <= cutoff <= 6 and .04 <= step <= .5\n",
    "\n",
    "def transformed(t, exponent):\n",
    "    s = np.pi*np.sinh(t)\n",
    "    log_x = -np.logaddexp(0., -s)\n",
    "    log_1mx = -np.logaddexp(0., s)\n",
    "    log_values = np.log(np.pi) + np.log(np.cosh(t)) + (1-exponent)*log_x + log_1mx\n",
    "    return np.exp(log_values)\n",
    "\n",
    "def tanh_sinh(T, h, exponent):\n",
    "    n = int(np.ceil(T/h))\n",
    "    t = np.linspace(-T, T, 2*n+1)\n",
    "    g = transformed(t, exponent)\n",
    "    # Composite trapezoid on the truncated interval.\n",
    "    value = (T/n)*(g.sum()-(g[0]+g[-1])/2)\n",
    "    return value, len(t)\n",
    "\n",
    "def midpoint(n, exponent):\n",
    "    return np.mean(((np.arange(n)+.5)/n)**(-exponent))\n",
    "\n",
    "def exact_truncation(T, exponent):\n",
    "    # Left and right tails calculated without subtracting nearly equal numbers.\n",
    "    s = np.pi*np.sinh(T)\n",
    "    log_left = -np.logaddexp(0., s)\n",
    "    log_right = -np.logaddexp(0., -s)\n",
    "    return (np.exp((1-exponent)*log_left)-np.expm1((1-exponent)*log_right))/(1-exponent)\n",
    "\n",
    "exact = 1/(1-alpha)\n",
    "value, nodes = tanh_sinh(cutoff,step,alpha)\n",
    "print(f\"Exact {exact:.10f}; tanh–sinh {value:.10f} with {nodes} nodes\")\n",
    "print(\"Omitted tail alone:\", exact_truncation(cutoff,alpha))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "approximatio-02",
   "metadata": {},
   "source": [
    "## Plot the transformed integrand and separate both errors\n",
    "The midpoint rule in the original coordinate never evaluates zero. The transformed quadrature additionally concentrates nodes where the original slope diverges. Reducing the transformed step at fixed cutoff eventually leaves the omitted tail exposed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "approximatio-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, (shape, errors) = plt.subplots(1, 2, figsize=(10, 4), layout=\"constrained\")\n",
    "tt = np.linspace(-5, 4, 450)\n",
    "for exponent, color in [(alpha, \"#145c71\"),(.85,\"#b94626\")]:\n",
    "    shape.plot(tt, transformed(tt,exponent), color=color, label=f\"α = {exponent:g}\")\n",
    "shape.axvspan(-cutoff,cutoff,color=\"grey\",alpha=.08)\n",
    "shape.set(xlabel=\"Transformed coordinate t\",ylabel=\"Weight times integrand\",title=\"Where does the integral live?\")\n",
    "shape.legend()\n",
    "counts = 2*np.array([4,6,8,12,16,24,32,48,64])+1\n",
    "de = [abs(tanh_sinh(cutoff,cutoff/(n//2),alpha)[0]-exact) for n in counts]\n",
    "errors.loglog(counts,np.maximum(de,1e-16),\"o-\",color=\"#145c71\",label=\"tanh–sinh\")\n",
    "errors.loglog(counts,[abs(midpoint(n,alpha)-exact) for n in counts],\"s--\",color=\"#b94626\",label=\"midpoint in x\")\n",
    "errors.axhline(max(1e-16,exact_truncation(cutoff,alpha)),ls=\":\",color=\"black\",label=\"truncation alone\")\n",
    "errors.set(xlabel=\"Function evaluations\",ylabel=\"Absolute error\",title=\"Refinement at a fixed cutoff\")\n",
    "errors.legend(fontsize=9)\n",
    "for ax in (shape,errors): ax.grid(alpha=.2)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "approximatio-04",
   "metadata": {},
   "source": [
    "## Check a finite integral independently\n",
    "A second substitution x = u raised to the power 1/(1−alpha) makes the integrand exactly constant. Try alpha 0.95 before increasing the cutoff. More nodes at fixed cutoff cannot replace the missing area beyond the window."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "approximatio-05",
   "metadata": {},
   "outputs": [],
   "source": [
    "exponent = 1/(1-alpha)\n",
    "u = np.linspace(.1,.99,10)\n",
    "flat = exponent*u**(exponent-1-alpha*exponent)\n",
    "assert np.allclose(flat,exact)\n",
    "test, _ = tanh_sinh(5.5,.075,.65)\n",
    "assert abs(test-1/.35) < 5e-13\n",
    "print(\"Analytical substitution and converged reference checks passed.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "approximatio-06",
   "metadata": {},
   "source": [
    "## Check the retained window with an element quadrature\n",
    "The exact finite-window target equals the full integral minus the two omitted tails. A local OneSimulation installation can measure this finite part by building a physical line mesh in the transformed variable and integrating at mapped Gaussian quadrature points of each element. This is a different sampling grid from the trapezoid. The analytical finite-window check runs in every environment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "approximatio-07",
   "metadata": {},
   "outputs": [],
   "source": [
    "finite_target = exact - exact_truncation(cutoff,alpha)\n",
    "print(f\"Window loss {exact-finite_target:.8g}; signed panel error {finite_target-value:.8g}\")\n",
    "try:\n",
    "    from onesim.cad.d1 import Line\n",
    "    from onesim.meshing import StructuredLineMesher\n",
    "    from onesim.numerics.fem.backends.spaces.line_lagrange import LineLagrangeSpace\n",
    "except ImportError:\n",
    "    print(\"The mapped Gaussian element comparison is available with OneSimulation installed locally.\")\n",
    "else:\n",
    "    line = Line(start=(-cutoff,0,0),end=(cutoff,0,0))\n",
    "    mesh = StructuredLineMesher(cells=24).generate(line)\n",
    "    space = LineLagrangeSpace(mesh,order=1,quadrature_order=8)\n",
    "    finite_gauss = 0.\n",
    "    for i in range(len(space.cells)):\n",
    "        points,weights = space.quadrature(i)\n",
    "        finite_gauss += weights @ transformed(points[:,0],alpha)\n",
    "    assert np.isclose(finite_gauss,finite_target,atol=2e-10,rtol=1e-11)\n",
    "    print(f\"OneSimulation finite-window integral {finite_gauss:.10f}.\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
