{
 "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": [
    "# Generating a simulation mesh from scanned data\n",
    "\n",
    "Computed tomography and magnetic resonance imaging deliver stacks of images; segmentation turns\n",
    "them into a three-dimensional array of labels, one integer per voxel and material. Medical\n",
    "devices, geological cores, foams and castings with pores are modelled from such data.\n",
    "\n",
    "`LabelImage(labels, spacing, names=...)` (`onesim.meshing`) reads the array. `OctreeMesher`\n",
    "fills it with tetrahedra from a grid of cubes that is cut where the label changes: the faces lie\n",
    "where the labels change, smoothed instead of following the steps of the voxels, and every label\n",
    "becomes a region of one conforming mesh. `CartesianMesher` fills it with cut cubes instead.\n",
    "\n",
    "The image `mesh_from_scanned_data.npy` is written by `mesh_from_scanned_data_geometry.py`: 64 x 48\n",
    "x 48 voxels of 0.5 mm, label 1 for an ellipsoidal bone with half axes 14, 10 and 10 mm and label 2\n",
    "for an implant of 3 mm radius and 20 mm length inside it.\n",
    "\n",
    "**Reference.** The volumes of the scanned shapes,\n",
    "$V_\\text{implant} = \\pi r^2 \\ell$, $V_\\text{bone} = \\tfrac43\\pi abc - \\pi r^2\\ell$, and the\n",
    "voxel counts times the voxel volume $s^3$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.meshing import CartesianMesher, LabelImage, OctreeMesher\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 image\n",
    "\n",
    "Each label gets a name; the names become the regions of the mesh and the faces between them."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "labels = np.load(\"mesh_from_scanned_data.npy\")\n",
    "spacing = 0.5e-3\n",
    "image = LabelImage(labels, spacing, names={1: \"bone\", 2: \"implant\"})\n",
    "counts = {\n",
    "    name: int((labels == value).sum()) for value, name in ((1, \"bone\"), (2, \"implant\"))\n",
    "}\n",
    "print(\n",
    "    f\"image {labels.shape} voxels of {spacing * 1e3} mm; bone {counts['bone']} voxels, implant {counts['implant']} voxels\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Meshes\n",
    "\n",
    "Tetrahedra of 1 mm at the faces, growing to 2 mm inside; and cut cubes of 1 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mesh = OctreeMesher(target_size=1e-3, coarsening=1).generate(image)\n",
    "cubes = CartesianMesher(target_size=1e-3, coarsening=1).generate(image)\n",
    "print(\n",
    "    f\"tetrahedra: {mesh.cell_count} cells, regions {', '.join(mesh.regions)}, outer boundary {', '.join(sorted(mesh.geometry.boundaries.all.members))}\"\n",
    ")\n",
    "print(f\"cut cubes:  {cubes.cell_count} cells, regions {', '.join(cubes.region_names)}\")\n",
    "\n",
    "view = plots.Camera(elevation=25, azimuth=-55)\n",
    "fig = plots.figure(1, 2, size=(16, 7))\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"outside\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"Outer face of the scan: {mesh.cell_count} tetrahedra\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    cell_values=quality(mesh)[\"shape\"],\n",
    "    limits=(0, 1),\n",
    "    plane=((0.016, 0.012, 0.012), (0.0, 1.0, 0.0)),\n",
    "    label=\"shape measure\",\n",
    "    camera=plots.Camera(elevation=10, azimuth=90),\n",
    "    title=\"Cut through bone and implant\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Volumes of the two regions in both meshes against the voxel counts and the scanned shapes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "exact = {\n",
    "    \"implant\": np.pi * 0.003**2 * 0.020,\n",
    "    \"bone\": 4 / 3 * np.pi * 0.014 * 0.010 * 0.010 - np.pi * 0.003**2 * 0.020,\n",
    "}\n",
    "cells = quality(mesh)[\"size\"]\n",
    "regions = {name: cells[list(mesh.regions[name])].sum() for name in exact}\n",
    "in_cubes = {name: cubes.cell_volumes[cubes.regions == name].sum() for name in exact}\n",
    "print(\n",
    "    \"region     tetrahedra [cm3]   cut cubes [cm3]   voxels [cm3]   scanned shape [cm3]\"\n",
    ")\n",
    "for name in exact:\n",
    "    print(\n",
    "        f\"{name:9s} {regions[name] * 1e6:15.4f} {in_cubes[name] * 1e6:17.4f} {counts[name] * spacing**3 * 1e6:14.4f} {exact[name] * 1e6:18.4f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"cells: bone {len(mesh.regions['bone'])}, implant {len(mesh.regions['implant'])} tetrahedra in one conforming mesh\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The tetrahedra cut open and coloured by their material, and the volumes of both materials in the\n",
    "two meshes, the voxels and the scanned shapes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "material = np.zeros(mesh.cell_count)\n",
    "material[list(mesh.regions[\"implant\"])] = 1.0\n",
    "fig = plots.figure(1, 2, size=(16, 7))\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    cell_values=material,\n",
    "    limits=(0, 1),\n",
    "    plane=((0.016, 0.012, 0.012), (0.0, 1.0, 0.0)),\n",
    "    label=\"material (0 bone, 1 implant)\",\n",
    "    camera=plots.Camera(elevation=10, azimuth=90),\n",
    "    title=\"Bone and implant regions\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.bars(\n",
    "    [\n",
    "        f\"{name}, {kind}\"\n",
    "        for name in exact\n",
    "        for kind in (\"tetrahedra\", \"cut cubes\", \"voxels\", \"shape\")\n",
    "    ],\n",
    "    [\n",
    "        1e6 * value\n",
    "        for name in exact\n",
    "        for value in (\n",
    "            regions[name],\n",
    "            in_cubes[name],\n",
    "            counts[name] * spacing**3,\n",
    "            exact[name],\n",
    "        )\n",
    "    ],\n",
    "    horizontal=True,\n",
    "    ylabel=\"volume [cm3]\",\n",
    "    title=\"Volumes of the two materials\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Give bone and implant their stiffness with `regionwise` and load the implant, read a stack of\n",
    "images with `numpy` from your own segmentation, or smooth noisy labels with\n",
    "`LabelImage(..., smoothing=...)`."
   ]
  }
 ]
}
