{
 "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": [
    "# Creating a random geometry: inclusions in a matrix\n",
    "\n",
    "Particle-filled composites, porous media and foams are modelled as random arrangements of\n",
    "simple bodies. A common way to build one is random sequential addition: draw a centre and a\n",
    "radius, keep the sphere if it does not come too close to anything placed before, repeat. With a\n",
    "seed for the random numbers the geometry is random but reproducible.\n",
    "\n",
    "Here up to 300 attempts place spheres with radii between 3 and 6 mm in a cube of 50 mm. Every\n",
    "sphere keeps at least $g$ = 1 mm from the walls and from every other sphere, so the matrix\n",
    "between them never becomes thinner than that and the mesh stays well formed. The matrix is the\n",
    "cube minus the spheres; matrix and spheres are the parts of an `Assembly`, which the mesher\n",
    "fills as one mesh with a volume per part that meet node by node at every sphere surface.\n",
    "\n",
    "**Reference.** The inclusion volume is the sum of the sphere volumes,\n",
    "$V_i=\\sum_k \\tfrac43\\pi r_k^3$, and the volume fraction $\\varphi = V_i/a^3$; the matrix must have\n",
    "$a^3 - V_i$. The placement rule requires $|c_j-c_k| \\ge r_j+r_k+g$ for every pair."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from functools import reduce\n",
    "\n",
    "import numpy as np\n",
    "from onesim.cad.d3 import Assembly, Box, Sphere\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": [
    "## Random sequential addition\n",
    "\n",
    "The candidates are drawn at once from a seeded generator; the loop keeps those that respect the\n",
    "gap."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "side, smallest, largest, gap = 0.05, 0.003, 0.006, 0.001\n",
    "random = np.random.default_rng(2026)\n",
    "radii = random.uniform(smallest, largest, 300)\n",
    "candidates = [(random.uniform(r + gap, side - r - gap, 3), r) for r in radii]\n",
    "placed = []\n",
    "for centre, r in candidates:\n",
    "    if all(np.linalg.norm(centre - other) >= r + rk + gap for other, rk in placed):\n",
    "        placed.append((centre, r))\n",
    "print(f\"{len(placed)} of {len(candidates)} candidate spheres placed\")\n",
    "\n",
    "spheres = [\n",
    "    Sphere(radius=r, origin=tuple(centre)).named(f\"inclusion_{k + 1}\")\n",
    "    for k, (centre, r) in enumerate(placed)\n",
    "]\n",
    "matrix = reduce(\n",
    "    lambda body, ball: body - ball, spheres, Box(length=side, width=side, height=side)\n",
    ").named(\"matrix\")\n",
    "composite = Assembly(parts=[matrix, *spheres])\n",
    "mesh = TetrahedralMesher(target_size=0.004, curvature_angle=0.35).generate(composite)\n",
    "\n",
    "view = plots.Camera(elevation=25, azimuth=-55)\n",
    "fig = plots.figure(1, 2, size=(16, 7))\n",
    "plots.geometry(\n",
    "    matrix,\n",
    "    selection={\"inclusions\": matrix.select(faces=lambda face: face.kind == \"sphere\")},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=f\"{len(spheres)} random inclusions placed in the cube\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    cell_values=quality(mesh)[\"shape\"],\n",
    "    limits=(0, 1),\n",
    "    plane=((side / 2, side / 2, side / 2), (0.0, 0.0, 1.0)),\n",
    "    label=\"shape measure\",\n",
    "    camera=plots.Camera(elevation=60, azimuth=-60),\n",
    "    title=f\"One mesh of both, cut at mid-height: {mesh.cell_count} cells\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Volume of the inclusions and of the matrix in the CAD model and in the mesh against the sum of\n",
    "the sphere volumes, and the smallest clearance between two spheres and between a sphere and a\n",
    "wall. The flat faces of linear tetrahedra lie inside the round spheres, so the meshed inclusions\n",
    "come out smaller and the matrix larger by the same amount; with spheres of 3 to 6 mm radius the\n",
    "difference is a few per cent."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "exact = sum(4 / 3 * np.pi * r**3 for _, r in placed)\n",
    "cells = quality(mesh)[\"size\"]\n",
    "meshed = {\n",
    "    part.id: cells[list(mesh.region_cells(composite.volume_of(part.id)))].sum()\n",
    "    for part in composite.volumes\n",
    "}\n",
    "in_mesh = sum(value for name, value in meshed.items() if name != \"matrix\")\n",
    "print(\n",
    "    f\"inclusions: CAD {sum(ball.measure for ball in spheres) * 1e6:.4f} cm3, mesh {in_mesh * 1e6:.4f} cm3, \"\n",
    "    f\"sum of 4/3 pi r^3 {exact * 1e6:.4f} cm3\"\n",
    ")\n",
    "print(\n",
    "    f\"matrix: CAD {matrix.measure * 1e6:.4f} cm3, mesh {meshed['matrix'] * 1e6:.4f} cm3, a^3 - V_i {(side**3 - exact) * 1e6:.4f} cm3\"\n",
    ")\n",
    "print(\n",
    "    f\"volume fraction: CAD {1 - matrix.measure / side**3:.4f}, mesh {in_mesh / side**3:.4f}, closed form {exact / side**3:.4f}\"\n",
    ")\n",
    "clearance = min(\n",
    "    np.linalg.norm(cj - ck) - rj - rk\n",
    "    for j, (cj, rj) in enumerate(placed)\n",
    "    for ck, rk in placed[j + 1 :]\n",
    ")\n",
    "walls = min(min(c.min() - r, side - c.max() - r) for c, r in placed)\n",
    "print(\n",
    "    f\"smallest clearance between spheres {1e3 * clearance:.3f} mm, to the walls {1e3 * walls:.3f} mm (required {1e3 * gap:.1f} mm)\"\n",
    ")\n",
    "print(f\"contact faces between parts: {len(composite.interfaces)} (one per inclusion)\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The cross-section of the matrix at mid-height with the circles cut out by the inclusions, and the\n",
    "radii of the placed spheres."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(16, 7))\n",
    "cut = matrix.section((0, 0, 1), (side / 2, side / 2, side / 2))\n",
    "plots.geometry(\n",
    "    cut,\n",
    "    selection={\"matrix section\": cut.boundaries.all},\n",
    "    labels=False,\n",
    "    title=\"Matrix cut at mid-height\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "counts, edges = np.histogram(\n",
    "    [1e3 * r for _, r in placed], bins=6, range=(1e3 * smallest, 1e3 * largest)\n",
    ")\n",
    "plots.bars(\n",
    "    [f\"{a:.1f}-{b:.1f}\" for a, b in zip(edges[:-1], edges[1:])],\n",
    "    counts,\n",
    "    ylabel=\"number of spheres\",\n",
    "    title=\"Radii of the placed spheres [mm]\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the seed for another realisation, replace the spheres by randomly turned cylinders\n",
    "(`Cylinder(...).rotated(axis, angle)`) for a fibre composite, or give matrix and inclusions their\n",
    "own conductivity with `regionwise` and compute the effective conductivity of the composite."
   ]
  }
 ]
}
