{
 "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": [
    "# Homogenized thermal properties of a fibre composite\n",
    "\n",
    "A unidirectional composite looks homogeneous at the scale of a part, but conducts heat\n",
    "differently along and across its fibres. Its effective properties follow from one unit cell of\n",
    "the fibre arrangement. Glass fibres ($k_f=1.05$ W/(m K), $\\rho_f=2550$ kg/m³,\n",
    "$c_f=840$ J/(kg K)) fill $\\varphi=50$ % of an epoxy matrix ($k_m=0.19$ W/(m K), $\\rho_m=1200$ kg/m³,\n",
    "$c_m=1100$ J/(kg K)) in a square array with a spacing of 10 µm.\n",
    "\n",
    "The effective conductivity $k_\\text{eff}$ relates the mean heat flux to the mean temperature\n",
    "gradient. A cell with mirror symmetry about its mid-planes has the same solution for a temperature\n",
    "jump across it with insulated sides as for the periodic cell problem, so\n",
    "\n",
    "$$k_{xx}=\\frac{Q_x\\,L_x}{A_x\\,\\Delta T},\\qquad k_{zz}=\\frac{Q_z\\,L_z}{A_z\\,\\Delta T},$$\n",
    "\n",
    "with $Q$ the heat flow through the cell for a temperature difference $\\Delta T$ between opposite\n",
    "faces. Density and heat capacity per volume are exact volume averages:\n",
    "$\\rho_\\text{eff}=\\varphi\\rho_f+(1-\\varphi)\\rho_m$ and\n",
    "$c_\\text{eff}=(\\varphi\\rho_f c_f+(1-\\varphi)\\rho_m c_m)/\\rho_\\text{eff}$.\n",
    "\n",
    "| cell problem | faces with $T=1$ K and $T=0$ | insulated |\n",
    "|---|---|---|\n",
    "| across the fibres | `left`, `right` (x) | `sides` (y), `bottom`, `top` (z) |\n",
    "| along the fibres | `bottom`, `top` (z) | `left`, `right`, `sides` |\n",
    "\n",
    "The cell and its fibre come from the CAD files `fiber_composite_thermal_homogenization.step` and\n",
    "`fiber_composite_thermal_homogenization_fibre.step`; the script `fiber_composite_thermal_homogenization_geometry.py` builds\n",
    "it with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** Along the fibres the parallel rule $k_{zz}=\\varphi k_f+(1-\\varphi)k_m$ is exact.\n",
    "Across them, Rayleigh's multipole series for a square array of cylinders, in the form of Perrins,\n",
    "McKenzie and McPhedran (*Proc. R. Soc. Lond. A* 369, 1979, 207–225), with\n",
    "$\\beta=(k_f-k_m)/(k_f+k_m)$:\n",
    "\n",
    "$$\\frac{k_{xx}}{k_m}=1+\\frac{2\\beta\\varphi}{1-\\beta\\varphi-0.305827\\,\\beta^2\\varphi^4\\big/\\big(1-1.402958\\,\\beta^2\\varphi^8\\big)-0.013362\\,\\beta^2\\varphi^8}.$$\n",
    "\n",
    "It must lie between the Reuss (series) and Voigt (parallel) values and between the two-dimensional\n",
    "Hashin-Shtrikman bounds."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid, regionwise\n",
    "from onesim.meshing import TetrahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.heat_transfer import FixedTemperature, HeatConduction, HeatFlux\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the cell with its named faces and the fibre, which the mesher embeds as a material\n",
    "region. Three meshes of quadratic tetrahedra, 1.4, 1 and 0.8 µm, check the convergence."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cell, fibre_body = load(\"fiber_composite_thermal_homogenization.step\"), load(\n",
    "    \"fiber_composite_thermal_homogenization_fibre.step\"\n",
    ").named(\"fibre\")\n",
    "faces = cell.boundaries\n",
    "side, depth = cell.size[0], cell.size[2]\n",
    "meshes = [\n",
    "    TetrahedralMesher(target_size=size, embedded_regions=(fibre_body,)).generate(cell)\n",
    "    for size in (1.4e-6, 1.0e-6, 0.8e-6)\n",
    "]\n",
    "\n",
    "fig = plots.figure(1, 2, size=(14, 6))\n",
    "plots.geometry(\n",
    "    [cell.named(\"matrix\"), fibre_body],\n",
    "    labels=False,\n",
    "    camera=plots.Camera(elevation=35, azimuth=-55),\n",
    "    length_unit=\"um\",\n",
    "    title=\"Unit cell: fibre in matrix\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    meshes[1],\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    length_unit=\"um\",\n",
    "    title=f\"Middle mesh: {meshes[1].cell_count} tetrahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cell problems\n",
    "\n",
    "`regionwise` gives each part its conductivity. Each cell problem holds two opposite faces at 1 K\n",
    "and 0 K and insulates the others; the heat flow through the cold face, `reaction`, gives the\n",
    "effective conductivity."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fibre, matrix, fraction = (\n",
    "    {\"k\": 1.05, \"rho\": 2550.0, \"c\": 840.0},\n",
    "    {\"k\": 0.19, \"rho\": 1200.0, \"c\": 1100.0},\n",
    "    0.5,\n",
    ")\n",
    "material = IsotropicSolid(\n",
    "    density=1.0,\n",
    "    specific_heat_capacity=1.0,\n",
    "    youngs_modulus=1.0,\n",
    "    poisson_ratio=0.3,\n",
    "    thermal_expansion_coefficient=0.0,\n",
    "    thermal_conductivity=regionwise(\n",
    "        {\"fibre\": fibre[\"k\"]}, default=matrix[\"k\"], unit=\"W/m/K\"\n",
    "    ),\n",
    ")\n",
    "directions = {\n",
    "    \"across\": (faces.left, faces.right, side),\n",
    "    \"along\": (faces.bottom, faces.top, depth),\n",
    "}\n",
    "numerics = Numerics(\n",
    "    spatial=FiniteElement(element=Lagrange(order=2)), linear_solver=SparseDirect()\n",
    ")\n",
    "conductivity, meshed = {}, []\n",
    "for direction, (hot, cold, length) in directions.items():\n",
    "    model = HeatConduction(domain=cell.domain(), material=material, heating=0.0)\n",
    "    problem = Problem(\n",
    "        name=f\"Cell problem {direction} the fibres\",\n",
    "        geometry=cell,\n",
    "        physics=(model,),\n",
    "        boundary_conditions=(\n",
    "            FixedTemperature(boundary=hot, physics=model, value=1.0),\n",
    "            FixedTemperature(boundary=cold, physics=model, value=0.0),\n",
    "            HeatFlux(boundary=faces.all - hot - cold, physics=model, value=0.0),\n",
    "        ),\n",
    "    )\n",
    "    area = side * side * depth / length\n",
    "    temperatures = [\n",
    "        Simulation(problem=problem, mesh=mesh, numerics=numerics)\n",
    "        .solve_stationary()\n",
    "        .field(model.temperature)\n",
    "        for mesh in meshes\n",
    "    ]\n",
    "    conductivity[direction] = [\n",
    "        temperature.reaction(hot) * length / area for temperature in temperatures\n",
    "    ]\n",
    "    meshed = [\n",
    "        temperature.integrate(\n",
    "            region=fibre_body, component=lambda T, position: np.ones_like(T)\n",
    "        ).value\n",
    "        / (side * side * depth)\n",
    "        for temperature in temperatures\n",
    "    ]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The effective conductivities on the three meshes against the references, then density and heat\n",
    "capacity. The faceted fibre of a mesh holds slightly less than half of the cell; the references\n",
    "are evaluated at the fibre fraction each mesh holds (the volume of its fibre cells)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "kf, km = fibre[\"k\"], matrix[\"k\"]\n",
    "beta = (kf - km) / (kf + km)\n",
    "rayleigh = km * (\n",
    "    1\n",
    "    + 2\n",
    "    * beta\n",
    "    * fraction\n",
    "    / (\n",
    "        1\n",
    "        - beta * fraction\n",
    "        - 0.305827 * beta**2 * fraction**4 / (1 - 1.402958 * beta**2 * fraction**8)\n",
    "        - 0.013362 * beta**2 * fraction**8\n",
    "    )\n",
    ")\n",
    "voigt, reuss = fraction * kf + (1 - fraction) * km, 1 / (\n",
    "    fraction / kf + (1 - fraction) / km\n",
    ")\n",
    "lower = km + fraction / (1 / (kf - km) + (1 - fraction) / (2 * km))\n",
    "upper = kf + (1 - fraction) / (1 / (km - kf) + fraction / (2 * kf))\n",
    "print(\n",
    "    f\"bounds across the fibres: Reuss {reuss:.4f} < Hashin-Shtrikman {lower:.4f} ... {upper:.4f} < Voigt {voigt:.4f} W/(m K)\"\n",
    ")\n",
    "series = lambda f: km * (\n",
    "    1\n",
    "    + 2\n",
    "    * beta\n",
    "    * f\n",
    "    / (\n",
    "        1\n",
    "        - beta * f\n",
    "        - 0.305827 * beta**2 * f**4 / (1 - 1.402958 * beta**2 * f**8)\n",
    "        - 0.013362 * beta**2 * f**8\n",
    "    )\n",
    ")\n",
    "print(\n",
    "    \"tetrahedra   fibre fraction of the mesh   k_xx [W/(m K)]   Rayleigh at that fraction   deviation   k_zz [W/(m K)]   parallel rule   deviation\"\n",
    ")\n",
    "for mesh, f, across, along in zip(\n",
    "    meshes, meshed, conductivity[\"across\"], conductivity[\"along\"]\n",
    "):\n",
    "    parallel = f * kf + (1 - f) * km\n",
    "    print(\n",
    "        f\"{mesh.cell_count:10d} {100 * f:27.3f} % {across:15.5f} {series(f):26.5f} {100 * (across / series(f) - 1):+10.3f} % \"\n",
    "        f\"{along:15.5f} {parallel:15.5f} {100 * (along / parallel - 1):+10.4f} %\"\n",
    "    )\n",
    "density = fraction * fibre[\"rho\"] + (1 - fraction) * matrix[\"rho\"]\n",
    "capacity = (\n",
    "    fraction * fibre[\"rho\"] * fibre[\"c\"] + (1 - fraction) * matrix[\"rho\"] * matrix[\"c\"]\n",
    ") / density\n",
    "print(\n",
    "    f\"effective density {density:.1f} kg/m³, effective specific heat capacity {capacity:.1f} J/(kg K)\"\n",
    ")\n",
    "print(\n",
    "    f\"anisotropy k_zz / k_xx = {conductivity['along'][-1] / conductivity['across'][-1]:.3f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The transverse conductivity of the three meshes at the fibre fraction each holds, on the curve of\n",
    "the Rayleigh series."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fractions = np.linspace(0.488, 0.5, 61)\n",
    "plots.line(\n",
    "    x=100 * fractions,\n",
    "    y={\"Rayleigh series\": series(fractions)},\n",
    "    points={\n",
    "        \"simulation on three meshes\": (\n",
    "            [100 * f for f in meshed],\n",
    "            conductivity[\"across\"],\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"fibre volume fraction [%]\",\n",
    "    ylabel=\"k_xx [W/(m K)]\",\n",
    "    title=\"Effective conductivity across the fibres\",\n",
    "    legend=\"lower right\",\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the fibre fraction in `fiber_composite_thermal_homogenization_geometry.py` (up to the\n",
    "touching limit of 78.5 %) and follow the Rayleigh curve, or replace the fibre by an anisotropic\n",
    "carbon fibre with a conductivity tensor."
   ]
  }
 ]
}
