{
 "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": [
    "# Friction stir welding of an aluminium plate\n",
    "\n",
    "In friction stir welding a rotating tool with a shoulder and a pin plunges into the joint between\n",
    "two plates and travels along it. Friction and plastic work heat the metal to a doughy state, the\n",
    "pin stirs both sides together, and the plates are joined without melting. The temperature field\n",
    "decides the quality of the weld.\n",
    "\n",
    "Seen from the tool, the plate moves past it with the welding speed $u=3$ mm/s and the field is\n",
    "steady. Heat is carried by the moving metal and conducted:\n",
    "\n",
    "$$\\rho c\\,\\mathbf v\\cdot\\nabla T=\\nabla\\cdot(k\\nabla T)+\\dot q,\\qquad \\mathbf v=(-u,0,0),$$\n",
    "\n",
    "with an aluminium alloy ($k=167$ W/(m K), $\\rho=2700$ kg/m³, $c=896$ J/(kg K)). The tool puts\n",
    "$Q=1$ kW into the 6 mm plate, spread through the thickness with a Gaussian profile of radius\n",
    "$a=6$ mm about the tool axis, $\\dot q=Q/(\\pi a^2d)\\,e^{-r^2/a^2}$.\n",
    "\n",
    "| face | condition |\n",
    "|---|---|\n",
    "| `edges`, the four cut edges of the modelled plate | temperature of the infinite plate (Rosenthal) |\n",
    "| `faces`, top and bottom | insulated (losses to the backing plate and the air neglected) |\n",
    "\n",
    "The plate comes from the CAD file `friction_stir_welding_plate.step`; the script\n",
    "`friction_stir_welding_plate_geometry.py` builds it with the CAD objects of OneSimulation.\n",
    "\n",
    "**Reference.** D. Rosenthal, \"The theory of moving sources of heat and its application to metal\n",
    "treatments\", *Trans. ASME* 68 (1946) 849: for a line source in an infinite thin plate,\n",
    "\n",
    "$$T-T_0=\\frac{Q}{2\\pi k d}\\,\\exp\\!\\Big(-\\frac{u\\,x}{2\\alpha}\\Big)\\,K_0\\!\\Big(\\frac{u\\,r}{2\\alpha}\\Big),\n",
    "  \\qquad \\alpha=\\frac{k}{\\rho c},$$\n",
    "\n",
    "with $x$ measured ahead of the tool and $r$ the distance from its axis. A few tool radii away the\n",
    "Gaussian source acts like this line source; the cut edges of the model carry its values."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d2 import Plane\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.materials import IsotropicSolid\n",
    "from onesim.meshing import Geometric, Piecewise, StructuredHexahedralMesher\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.fem import FiniteElement, GalerkinAdvection, Lagrange\n",
    "from onesim.numerics.linear import SparseDirect\n",
    "from onesim.physics.heat_transfer import (\n",
    "    ConvectiveHeatTransfer,\n",
    "    FixedTemperature,\n",
    "    HeatFlux,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.special import k0\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and mesh\n",
    "\n",
    "`load` returns the plate with its named faces. The hexahedral mesh is 2.5 mm fine in a 40 mm\n",
    "square around the tool and grows towards the edges."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plate = load(\"friction_stir_welding_plate.step\")\n",
    "faces = plate.boundaries\n",
    "(x0, y0, _), (x1, y1, thickness) = plate.bounding_box\n",
    "grading = (\n",
    "    Piecewise(\n",
    "        (\n",
    "            (-0.02 - x0, Geometric(10, first=0.0025, toward=\"end\")),\n",
    "            (0.04, Geometric(16, ratio=1.0)),\n",
    "            (x1 - 0.02, Geometric(16, first=0.0025)),\n",
    "        )\n",
    "    ),\n",
    "    Piecewise(\n",
    "        (\n",
    "            (-0.02 - y0, Geometric(8, first=0.0025, toward=\"end\")),\n",
    "            (0.04, Geometric(16, ratio=1.0)),\n",
    "            (y1 - 0.02, Geometric(8, first=0.0025)),\n",
    "        )\n",
    "    ),\n",
    "    Piecewise(((thickness, Geometric(2, ratio=1.0)),)),\n",
    ")\n",
    "mesh = StructuredHexahedralMesher(\n",
    "    cells=tuple(g.cells for g in grading), grading=grading\n",
    ").generate(plate)\n",
    "\n",
    "view = plots.Camera(elevation=35, azimuth=-60)\n",
    "fig = plots.figure(1, 2, size=(15, 5.5))\n",
    "plots.geometry(\n",
    "    plate,\n",
    "    selection={\"cut edges\": faces.edges, \"top and bottom\": faces.faces},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"Plate with its named faces (tool axis at the origin)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.mesh(\n",
    "    mesh,\n",
    "    groups=(\"all\",),\n",
    "    legend=False,\n",
    "    camera=view,\n",
    "    title=f\"{mesh.cell_count} quadratic hexahedra\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`ConvectiveHeatTransfer` adds the transport by the prescribed velocity of the plate to the heat\n",
    "equation; quadratic elements with Galerkin advection solve it (the cell Péclet number is about\n",
    "0.1, no stabilisation is needed)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "power, speed, spot, ambient = 1000.0, 0.003, 0.006, 293.15\n",
    "alloy = IsotropicSolid(\n",
    "    density=2700.0,\n",
    "    specific_heat_capacity=896.0,\n",
    "    thermal_conductivity=167.0,\n",
    "    youngs_modulus=6.9e10,\n",
    "    poisson_ratio=0.33,\n",
    "    thermal_expansion_coefficient=2.3e-5,\n",
    ")\n",
    "alpha = alloy.thermal_conductivity / (alloy.density * alloy.specific_heat_capacity)\n",
    "rosenthal = lambda x, y, z: ambient + power / (\n",
    "    2 * np.pi * alloy.thermal_conductivity * thickness\n",
    ") * np.exp(-speed * x / (2 * alpha)) * k0(\n",
    "    speed * np.maximum(np.hypot(x, y), 1e-6) / (2 * alpha)\n",
    ")\n",
    "model = ConvectiveHeatTransfer(\n",
    "    domain=plate.volume,\n",
    "    material=alloy,\n",
    "    velocity=lambda x, y, z: np.column_stack(\n",
    "        (np.full_like(x, -speed), np.zeros_like(x), np.zeros_like(x))\n",
    "    ),\n",
    "    heating=lambda x, y, z: power\n",
    "    / (np.pi * spot**2 * thickness)\n",
    "    * np.exp(-(x**2 + y**2) / spot**2),\n",
    ")\n",
    "problem = Problem(\n",
    "    name=\"Friction stir welding\",\n",
    "    geometry=plate,\n",
    "    physics=(model,),\n",
    "    boundary_conditions=(\n",
    "        FixedTemperature(boundary=faces.edges, physics=model, value=rosenthal),\n",
    "        HeatFlux(boundary=faces.faces, physics=model, value=0.0),\n",
    "    ),\n",
    ")\n",
    "temperature = (\n",
    "    Simulation(\n",
    "        problem=problem,\n",
    "        mesh=mesh,\n",
    "        numerics=Numerics(\n",
    "            spatial=FiniteElement(\n",
    "                element=Lagrange(order=2), convection=GalerkinAdvection()\n",
    "            ),\n",
    "            linear_solver=SparseDirect(),\n",
    "        ),\n",
    "    )\n",
    "    .solve_stationary()\n",
    "    .field(model.temperature)\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The temperature along the weld line and along a parallel line 20 mm beside it, against\n",
    "Rosenthal's solution at distances of more than three tool radii from the axis."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x = np.linspace(x0 + 0.002, x1 - 0.002, 600)\n",
    "line = lambda y: np.column_stack(\n",
    "    (x, np.full_like(x, y), np.full_like(x, thickness / 2))\n",
    ")\n",
    "lines = {f\"y = {1e3 * y:.0f} mm\": y for y in (0.0, 0.02, 0.05)}\n",
    "simulated = {name: temperature.evaluate(line(y)).ravel() for name, y in lines.items()}\n",
    "exact = {name: rosenthal(x, np.full_like(x, y), 0) for name, y in lines.items()}\n",
    "far = {name: np.hypot(x, y) > 3 * spot for name, y in lines.items()}\n",
    "print(f\"Péclet number of the tool u a / (2 alpha) = {speed * spot / (2 * alpha):.3f}\")\n",
    "for name in lines:\n",
    "    print(\n",
    "        f\"{name:10s}: largest deviation from Rosenthal beyond 3 a: {np.abs(simulated[name] - exact[name])[far[name]].max():.2f} K, \"\n",
    "        f\"peak {simulated[name].max() - 273.15:.1f} °C at x = {1e3 * x[simulated[name].argmax()]:+.1f} mm\"\n",
    "    )\n",
    "print(\n",
    "    f\"peak temperature under the tool {np.ravel(temperature.evaluate([[0.0, 0.0, thickness / 2]]))[0] - 273.15:.1f} °C\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The temperature on the top face with the isotherms pushed back into a wake behind the tool, and\n",
    "the temperature along the three lines with Rosenthal's solution."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "celsius = lambda T, position: T - 273.15\n",
    "fig = plots.figure(1, 2, size=(17, 6))\n",
    "plots.section(\n",
    "    temperature,\n",
    "    plane=Plane(origin=(0, 0, thickness / 2), normal=(0, 0, 1)),\n",
    "    component=celsius,\n",
    "    limits=(20, 400),\n",
    "    contours=19,\n",
    "    subdivisions=2,\n",
    "    label=\"T [°C]\",\n",
    "    title=\"Mid-plane temperature (tool at the origin, moving to +x)\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={name: (1e3 * x, simulated[name] - 273.15) for name in lines},\n",
    "    reference={\n",
    "        name: (1e3 * x, np.where(far[name], exact[name] - 273.15, np.nan))\n",
    "        for name in lines\n",
    "    },\n",
    "    xlabel=\"distance ahead of the tool x [mm]\",\n",
    "    ylabel=\"T [°C]\",\n",
    "    title=\"Simulation (lines), Rosenthal (dashed)\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the welding speed: the isotherms are compressed ahead of the tool and stretched behind it,\n",
    "and the peak temperature falls. Add the losses to the backing plate (`ConvectiveHeatFlux` on the\n",
    "bottom face), or split the heat input into a shoulder flux on the top face and a pin source."
   ]
  }
 ]
}
