{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "point_source_unit_disk-1",
   "source": [
    "# A point source in a disk\n",
    "\n",
    "A unit point source drives the two-dimensional Poisson equation $-\\nabla^2u=\\delta_0$ on a disk of radius one. The rim is held at zero. Every circle around the origin carries a unit outward flux, giving the exact potential $u(r)=-\\log(r)/(2\\pi)$ for $0<r\\leq1$ (Evans, *Partial Differential Equations*, Chapter 2). The value at the origin diverges. We compare profiles at finite distances."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "point_source_unit_disk-2",
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange, PlanarDirichletFiniteElement\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "point_source_unit_disk-3",
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "Cut the disk halfway through the STEP cylinder. The three meshes use progressively smaller triangles toward the point source, where the potential changes fastest."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "point_source_unit_disk-4",
   "source": [
    "part = load(\"point_source_unit_disk.step\")\n",
    "disk = part.section((0, 0, 1), origin=(0, 0, part.size[2] / 2))\n",
    "meshes = [TriangularMesher(\n",
    "    target_size=h, size_field=lambda p, h=h: h * (0.1 + 0.9 * np.linalg.norm(p[:, :2], axis=1)),\n",
    ").generate(disk) for h in (0.22, 0.11, 0.04)]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(11, 4.5))\n",
    "plots.geometry(part, selection={\"zero potential\": part.boundaries.rim}, labels=False,\n",
    "               camera=plots.Camera(elevation=35, azimuth=-65), title=\"Disk and grounded rim\", ax=fig[0])\n",
    "plots.mesh(meshes[-1], groups=(\"all\",), legend=False, title=\"Fine mesh on the mid-plane\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "point_source_unit_disk-5",
   "source": [
    "## Apply the point load\n",
    "\n",
    "The load on each linear basis function $N_i$ is exactly $N_i(0)$. OneSim locates the origin, evaluates the three basis functions of its triangle and assembles the stiffness matrix with a zero value on the rim. The three weights must add to one. The same finite-element basis samples the computed potential along twelve rays."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "point_source_unit_disk-6",
   "source": [
    "element = FiniteElement(element=Lagrange(order=1))\n",
    "form = PlanarDirichletFiniteElement(finite_element=element, boundary=disk.boundaries.rim)\n",
    "radii = np.geomspace(0.08, 0.95, 48)\n",
    "angles = np.arange(12) * (2 * np.pi / 12)\n",
    "probes = (np.column_stack((np.cos(angles), np.sin(angles)))[:, None, :] * radii[None, :, None]).reshape(-1, 2)\n",
    "exact = -np.log(radii) / (2 * np.pi)\n",
    "profiles = []\n",
    "for mesh in meshes:\n",
    "    space, op = element.bind_space(mesh), form.bind(mesh)\n",
    "    cell, local = space.locate([[0.0, 0.0]])\n",
    "    load = np.zeros(space.dof_count)\n",
    "    load[space.cell_dofs[cell[0]]] = space.basis(local)[0]\n",
    "    solution = SparseDirect().bind().solve(op.stiffness, load[op.interior])\n",
    "    potential = op.embed(solution.solution)\n",
    "    rays = space.evaluate(potential, probes).reshape(len(angles), len(radii))\n",
    "    profiles.append(rays[0])\n",
    "    error = np.max(np.abs(rays - exact))\n",
    "    print(f\"{len(mesh.coordinates):5d} nodes, {mesh.cell_count:5d} triangles   total load {load.sum():.8f}   max absolute error {error:.5f}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "point_source_unit_disk-7",
   "source": [
    "## Read the potential\n",
    "\n",
    "The field map includes the finite peak on the fine mesh. The radial profile compares all three meshes with the logarithm over the annulus used for the error check, $0.08\\le r\\le0.95$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "id": "point_source_unit_disk-8",
   "source": [
    "fig = plots.figure(1, 2, size=(11, 4.5))\n",
    "plots.heatmap(*space.dof_coordinates.T, potential, triangles=space.cell_dofs, contours=8,\n",
    "              label=\"Potential u\", title=\"Potential on the unit disk\", ax=fig[0])\n",
    "plots.line(radii, {f\"{mesh.cell_count} triangles\": profile for mesh, profile in zip(meshes, profiles)}, reference={\"Exact\": exact},\n",
    "           xlabel=\"Radius [m]\", ylabel=\"Potential u\", title=\"Profile along the positive x-axis\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
