{
 "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": [
    "# Recursively defined geometry: the Menger sponge\n",
    "\n",
    "A geometry that repeats itself at smaller and smaller scales is easiest to describe by a rule and\n",
    "a loop. The Menger sponge of level $n$ is a cube of side $a$ from which, at every level\n",
    "$k=1,\\dots,n$, all points are removed whose $k$-th ternary digit is 1 in at least two of the three\n",
    "coordinates. Removing exactly those points is the same as cutting square bars of width\n",
    "$a/3^k$ through the whole cube along each axis, at the positions where both cross coordinates\n",
    "have the digit 1 at that level: $3\\cdot 9^{k-1}$ bars at level $k$.\n",
    "\n",
    "Each level keeps 20 of the 27 sub-cubes, so volume and surface follow geometric series:\n",
    "\n",
    "$$V_n = a^3\\Big(\\frac{20}{27}\\Big)^n,\\qquad S_n = 2a^2\\Big(\\frac{20}{9}\\Big)^n + 4a^2\\Big(\\frac{8}{9}\\Big)^n ,$$\n",
    "\n",
    "and the centre of mass stays in the centre of the cube. The volume tends to zero and the surface\n",
    "to infinity: the limit has the fractal dimension $\\ln 20/\\ln 3 \\approx 2.73$.\n",
    "\n",
    "**Reference.** K. Menger, *Allgemeine Räume und Cartesische Räume*, Proc. Royal Academy\n",
    "Amsterdam 29 (1926) 476-482; volume and surface series as in B. Mandelbrot, *The Fractal Geometry\n",
    "of Nature*, Freeman 1982, ch. 14."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from functools import reduce\n",
    "\n",
    "import numpy as np\n",
    "from onesim.cad.d3 import Box\n",
    "from onesim.meshing import TetrahedralMesher\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",
    "For every level the bars are a list comprehension over the grid of $3^k\\times3^k$ positions; the\n",
    "sponge of a level is the cube with all bars of all levels up to it subtracted one after another\n",
    "(`reduce` over the list with `body - bar`)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "side = 0.09\n",
    "cube = Box(length=side, width=side, height=side)\n",
    "bars = {\n",
    "    level: [\n",
    "        bar\n",
    "        for i in range(3**level)\n",
    "        for j in range(3**level)\n",
    "        if i % 3 == 1 and j % 3 == 1\n",
    "        for w in [side / 3**level]\n",
    "        for bar in (\n",
    "            Box(length=w, width=w, height=side, origin=(i * w, j * w, 0.0)),\n",
    "            Box(length=side, width=w, height=w, origin=(0.0, i * w, j * w)),\n",
    "            Box(length=w, width=side, height=w, origin=(i * w, 0.0, j * w)),\n",
    "        )\n",
    "    ]\n",
    "    for level in (1, 2)\n",
    "}\n",
    "sponges = [cube]\n",
    "for level in (1, 2):\n",
    "    sponges.append(reduce(lambda body, bar: body - bar, bars[level], sponges[-1]))\n",
    "print(\", \".join(f\"level {level}: {len(items)} bars\" for level, items in bars.items()))\n",
    "\n",
    "meshes = [\n",
    "    TetrahedralMesher(target_size=side / 9).generate(sponges[0]),\n",
    "    TetrahedralMesher(target_size=side / 15).generate(sponges[1]),\n",
    "    TetrahedralMesher(target_size=side / 27).generate(sponges[2]),\n",
    "]\n",
    "\n",
    "view = plots.Camera(elevation=28, azimuth=-52)\n",
    "fig = plots.figure(1, 2, size=(16, 7))\n",
    "plots.render(\n",
    "    sponges[2],\n",
    "    camera=view,\n",
    "    material=\"ceramic\",\n",
    "    title=\"Menger sponge of level 2\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[2],\n",
    "    cell_values=quality(meshes[2])[\"shape\"],\n",
    "    limits=(0, 1),\n",
    "    plane=((side / 2, side / 2, side / 2), (0.0, 1.0, 0.0)),\n",
    "    label=\"shape measure\",\n",
    "    camera=view,\n",
    "    title=f\"Level 2: {meshes[2].cell_count} tetrahedra, cut at the mid-plane\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Volume and surface area of the CAD body and of the mesh, and the centre of mass, against the\n",
    "closed-form series."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "volume = lambda n: side**3 * (20 / 27) ** n\n",
    "surface = lambda n: 2 * side**2 * (20 / 9) ** n + 4 * side**2 * (8 / 9) ** n\n",
    "print(\n",
    "    \"level  faces   volume CAD [cm3]  mesh     closed form   surface CAD [cm2]  closed form   cells\"\n",
    ")\n",
    "for level, (sponge, mesh) in enumerate(zip(sponges, meshes)):\n",
    "    print(\n",
    "        f\"{level:5d} {len(sponge.faces):6d} {sponge.measure * 1e6:14.4f} {quality(mesh)['size'].sum() * 1e6:10.4f} {volume(level) * 1e6:12.4f}\"\n",
    "        f\" {sponge.surface_area * 1e4:17.4f} {surface(level) * 1e4:12.4f} {mesh.cell_count:9d}\"\n",
    "    )\n",
    "centre = sponges[2].center_of_mass\n",
    "print(\n",
    "    f\"centre of mass of level 2: ({1e3 * centre[0]:.6f}, {1e3 * centre[1]:.6f}, {1e3 * centre[2]:.6f}) mm, \"\n",
    "    f\"centre of the cube ({1e3 * side / 2:.6f}, {1e3 * side / 2:.6f}, {1e3 * side / 2:.6f}) mm\"\n",
    ")\n",
    "print(\n",
    "    f\"volume fraction left at level 2: {sponges[2].measure / side**3:.6f} (20/27)^2 = {(20 / 27)**2:.6f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The three levels side by side, rendered as shaded solids, with their volume and surface."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(19, 6.5))\n",
    "for level in range(3):\n",
    "    plots.render(\n",
    "        sponges[level],\n",
    "        camera=view,\n",
    "        material=\"ceramic\",\n",
    "        title=f\"level {level}: volume {sponges[level].measure / side**3:.3f} a^3, surface {sponges[level].surface_area / side**2:.3f} a^2\",\n",
    "        ax=fig[level],\n",
    "    )\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Extend the dictionary of bars to level 3 (273 bars; the CAD body takes a few minutes), build the\n",
    "Sierpinski tetrahedron from `Cone(..., top_radius=0)` pyramids the same way, or solve a heat\n",
    "conduction problem on the sponge to see how the effective conductivity falls with the level."
   ]
  }
 ]
}
