{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Koch snowflake: a recursively defined planar region\n",
    "\n",
    "The Koch snowflake starts from an equilateral triangle of side $s$. One step of the recursion\n",
    "replaces every side by four sides of a third of its length: the middle third is removed and an\n",
    "equilateral spike is erected outwards on it. After $n$ steps the outline has $3\\cdot 4^n$ sides\n",
    "of length $s/3^n$, so the perimeter grows without bound while the area converges.\n",
    "\n",
    "Step $k$ adds $3\\cdot 4^{k-1}$ triangles of area $A_0/9^k$, one on every side. With $A_0=\\sqrt3 s^2/4$ the area after $n$\n",
    "steps is the geometric series\n",
    "\n",
    "$$A_n = A_0\\left(1+\\frac{3}{4}\\sum_{k=1}^{n}\\Big(\\frac{4}{9}\\Big)^{k}\\right)\n",
    "      = A_0\\left(\\frac{8}{5}-\\frac{3}{5}\\Big(\\frac{4}{9}\\Big)^{n}\\right),\n",
    "\\qquad P_n = 3s\\Big(\\frac{4}{3}\\Big)^{n},$$\n",
    "\n",
    "and the limit is $8A_0/5$. The centroid stays in the centre of the triangle,\n",
    "$(s/2,\\ s/(2\\sqrt3))$, at every level.\n",
    "\n",
    "**Reference.** H. von Koch, *Sur une courbe continue sans tangente, obtenue par une construction\n",
    "géométrique élémentaire*, Arkiv för Matematik, Astronomi och Fysik 1 (1904) 681-702; the area\n",
    "and perimeter series as in B. Mandelbrot, *The Fractal Geometry of Nature*, Freeman 1982, ch. 6."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import PlanarRegion, Profile\n",
    "from onesim.meshing import TriangularMesher\n",
    "from onesim.meshing.quality import quality\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The recursion\n",
    "\n",
    "The corners of a level are an array of points in counter-clockwise order. One step takes every\n",
    "side from $p$ to $q$ with $d=q-p$ and inserts three new corners: $p+d/3$, the apex\n",
    "$p+d/3+R_{-60^\\circ}\\,d/3$ (the middle third turned outwards by 60 degrees) and $p+2d/3$. Five\n",
    "steps give 3072 corners. Each level becomes a profile and a planar region of OneSimulation."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "side = 1.0\n",
    "corners = [side * np.array([(0.0, 0.0), (1.0, 0.0), (0.5, np.sqrt(3) / 2)])]\n",
    "turn = np.array([[0.5, np.sqrt(3) / 2], [-np.sqrt(3) / 2, 0.5]])\n",
    "for step in range(5):\n",
    "    p = corners[-1]\n",
    "    d = np.roll(p, -1, axis=0) - p\n",
    "    corners.append(\n",
    "        np.stack(\n",
    "            [p, p + d / 3, p + d / 3 + (d / 3) @ turn.T, p + 2 * d / 3], axis=1\n",
    "        ).reshape(-1, 2)\n",
    "    )\n",
    "regions = [PlanarRegion(profile=Profile.polygon(points)) for points in corners]\n",
    "print(\n",
    "    \", \".join(\n",
    "        f\"level {level}: {len(points)} corners\" for level, points in enumerate(corners)\n",
    "    )\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Meshes\n",
    "\n",
    "Every level is meshed with triangles of at most 50 mm. The mesher follows each of the 3072 short\n",
    "sides of the last level, so the triangles become as small as the sides near the outline and grow\n",
    "towards the middle."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "meshes = [TriangularMesher(target_size=0.05).generate(region) for region in regions]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(15, 7))\n",
    "plots.geometry(\n",
    "    regions[-1], title=\"Level 5: one planar region, outline 'side'\", ax=fig[0]\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[-1],\n",
    "    legend=False,\n",
    "    title=f\"Level 5: {meshes[-1].cell_count} triangles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()\n",
    "\n",
    "fig = plots.figure(2, 3, size=(16, 10))\n",
    "for level, region in enumerate(regions):\n",
    "    plots.geometry(\n",
    "        region,\n",
    "        selection={\"outline\": region.boundaries.all},\n",
    "        labels=False,\n",
    "        title=f\"level {level}: {len(corners[level])} sides\",\n",
    "        ax=fig[level],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The area of the region and of its mesh, the perimeter (the length of the one boundary line of\n",
    "the region) and the centroid against the closed form at every level."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "area0 = np.sqrt(3) / 4 * side**2\n",
    "area = lambda n: area0 * (8 / 5 - 3 / 5 * (4 / 9) ** n)\n",
    "centre = (side / 2, side / (2 * np.sqrt(3)))\n",
    "print(\n",
    "    \"level  sides   triangles   area CAD   area mesh   closed form   deviation   perimeter   closed form\"\n",
    ")\n",
    "for level, (region, mesh) in enumerate(zip(regions, meshes)):\n",
    "    print(\n",
    "        f\"{level:5d} {len(corners[level]):6d} {mesh.cell_count:10d} {region.measure:10.6f} {quality(mesh)['size'].sum():11.6f}\"\n",
    "        f\" {area(level):12.6f} {region.measure / area(level) - 1:+11.1e} {region.edges[0].length:10.5f} {3 * side * (4 / 3) ** level:12.5f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"limit of the area 8/5 A0 = {8 / 5 * area0:.6f}; level 5 reaches {regions[-1].measure / (8 / 5 * area0):.4%} of it\"\n",
    ")\n",
    "centroid = Profile.polygon(corners[-1]).section_values().centroid\n",
    "print(\n",
    "    f\"centroid of level 5: ({centroid[0]:.9f}, {centroid[1]:.9f}), centre of the triangle ({centre[0]:.9f}, {centre[1]:.9f})\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The smallest angle of each triangle of the mesh of level 4, the meshed area against the\n",
    "closed-form series and the perimeter against the level."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "levels = np.arange(len(regions))\n",
    "fig = plots.figure(1, 3, size=(19, 6))\n",
    "plots.mesh(\n",
    "    meshes[4],\n",
    "    cell_values=np.degrees(quality(meshes[4])[\"minimum_angle\"]),\n",
    "    limits=(0, 60),\n",
    "    label=\"smallest angle [deg]\",\n",
    "    title=\"Level 4: smallest angle of the triangles\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    levels,\n",
    "    {\"meshed area\": np.array([quality(mesh)[\"size\"].sum() for mesh in meshes])},\n",
    "    reference={\"A_n, closed form\": (levels, area(levels))},\n",
    "    hlines={\"limit 8/5 A0\": 8 / 5 * area0},\n",
    "    markers=True,\n",
    "    xlabel=\"level n\",\n",
    "    ylabel=\"area [m2]\",\n",
    "    title=\"Area converges\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    levels,\n",
    "    {\"CAD region\": np.array([region.edges[0].length for region in regions])},\n",
    "    reference={\"P_n, closed form\": (levels, 3 * side * (4 / 3) ** levels)},\n",
    "    markers=True,\n",
    "    xlabel=\"level n\",\n",
    "    ylabel=\"perimeter [m]\",\n",
    "    title=\"Perimeter grows without bound\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Extrude a level with `Prism(profile=Profile.polygon(corners[3]), height=0.1)` for a fractal\n",
    "column, compute the lowest membrane eigenvalues of the levels with `onesim.physics.acoustics`\n",
    "to see how the boundary shifts the spectrum, or replace the 60 degree spike by another angle for\n",
    "the Cesàro variants of the curve."
   ]
  }
 ]
}
