{
 "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": [
    "# Lumped model of a seated human body\n",
    "\n",
    "How a seated person responds to vertical vibration of the seat, in a vehicle, a helicopter or on\n",
    "a construction machine, is described by biodynamic models: the body segments are masses, the\n",
    "tissues between them springs and dampers. Two measures characterise such a model. The\n",
    "*seat-to-head transmissibility* $T(f)=a_\\text{head}/a_\\text{seat}$ tells how much of the seat\n",
    "motion arrives at the head; the *apparent mass* $M(f)=F_\\text{seat}/a_\\text{seat}$ is the dynamic\n",
    "mass the seat feels. Both show the well-known whole-body resonance near 4-6 Hz (Griffin,\n",
    "*Handbook of Human Vibration*, Academic Press 1990).\n",
    "\n",
    "**Setup.** A chain from the seat upwards (masses in kg, stiffness in kN/m, damping in N s/m):\n",
    "\n",
    "| segment | mass | connection below | stiffness | damping |\n",
    "|---|---|---|---|---|\n",
    "| pelvis | 36.0 | seat | 75 | 3500 |\n",
    "| abdomen | 5.5 | pelvis | 100 | 330 |\n",
    "| thorax | 15.0 | abdomen | 120 | 800 |\n",
    "| upper torso | 15.0 | thorax | 150 | 900 |\n",
    "| head and neck | 5.3 | upper torso | 120 | 400 |\n",
    "\n",
    "The seat moves vertically, harmonically or as a half-sine shock of 2 g and 20 ms.\n",
    "\n",
    "**Reference.** (1) For $f\\to0$ the body moves rigidly with the seat: $T\\to1$ and $M\\to\\sum m_i$\n",
    "(Newton's second law for the whole body). (2) In every harmonic state the mean power the seat puts\n",
    "into the body equals the power dissipated in the dampers. (3) A shock of velocity change\n",
    "$\\Delta v$ leaves every segment, once the vibration has decayed, moving with the seat."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.physics.solid_mechanics import Damper, LumpedMechanicalNetwork, Spring\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Five coordinates and one input, the seat height; each element connects a segment to the one below."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "segments = {\n",
    "    \"pelvis\": 36.0,\n",
    "    \"abdomen\": 5.5,\n",
    "    \"thorax\": 15.0,\n",
    "    \"upper torso\": 15.0,\n",
    "    \"head\": 5.3,\n",
    "}\n",
    "below = {\n",
    "    \"pelvis\": \"seat\",\n",
    "    \"abdomen\": \"pelvis\",\n",
    "    \"thorax\": \"abdomen\",\n",
    "    \"upper torso\": \"thorax\",\n",
    "    \"head\": \"upper torso\",\n",
    "}\n",
    "stiffness = {\n",
    "    \"pelvis\": 75e3,\n",
    "    \"abdomen\": 100e3,\n",
    "    \"thorax\": 120e3,\n",
    "    \"upper torso\": 150e3,\n",
    "    \"head\": 120e3,\n",
    "}\n",
    "damping = {\n",
    "    \"pelvis\": 3500.0,\n",
    "    \"abdomen\": 330.0,\n",
    "    \"thorax\": 800.0,\n",
    "    \"upper torso\": 900.0,\n",
    "    \"head\": 400.0,\n",
    "}\n",
    "body = LumpedMechanicalNetwork(\n",
    "    inertias=segments,\n",
    "    springs=tuple(Spring(stiffness[name], name, below[name]) for name in segments),\n",
    "    dampers=tuple(Damper(damping[name], name, below[name]) for name in segments),\n",
    "    inputs=(\"seat\",),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Natural modes, transmissibility and apparent mass\n",
    "\n",
    "The response to a unit seat displacement gives both measures: $T=X_\\text{head}$, and the seat\n",
    "force is the sum of the segment inertia forces, $F=-\\omega^2\\sum m_iX_i$, so\n",
    "$M=\\sum m_iX_i$ for a unit seat acceleration $-\\omega^2$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "modes = body.modes()\n",
    "for k, frequency in enumerate(modes.frequencies):\n",
    "    shape = modes.shape(k)\n",
    "    print(\n",
    "        f\"mode {k + 1}: {frequency:6.2f} Hz, largest motion in the {max(shape, key=lambda name: abs(shape[name]))}\"\n",
    "    )\n",
    "frequencies = np.geomspace(0.05, 30.0, 500)\n",
    "response = body.frequency_response(frequencies, inputs={\"seat\": 1.0})\n",
    "transmissibility = np.abs(response[\"head\"])\n",
    "apparent = np.abs(sum(mass * response[name] for name, mass in segments.items()))\n",
    "peak = int(np.argmax(apparent))\n",
    "print(\n",
    "    f\"at 0.05 Hz: transmissibility {transmissibility[0]:.5f} (rigid: 1), apparent mass {apparent[0]:.3f} kg (total mass {sum(segments.values()):.1f} kg)\"\n",
    ")\n",
    "print(\n",
    "    f\"apparent mass peaks at {frequencies[peak]:.2f} Hz with {apparent[peak] / sum(segments.values()):.2f} times the static mass; \"\n",
    "    f\"transmissibility peaks at {frequencies[np.argmax(transmissibility)]:.2f} Hz with {transmissibility.max():.2f}\"\n",
    ")\n",
    "for f in (2.0, 5.0, 12.0):\n",
    "    state = body.frequency_response([f], inputs={\"seat\": 1e-3})\n",
    "    omega = 2 * np.pi * f\n",
    "    force = stiffness[\"pelvis\"] * (1e-3 - state[\"pelvis\"][0]) + damping[\n",
    "        \"pelvis\"\n",
    "    ] * 1j * omega * (1e-3 - state[\"pelvis\"][0])\n",
    "    supplied = 0.5 * np.real(np.conj(1j * omega * 1e-3) * force)\n",
    "    print(\n",
    "        f\"{f:4.1f} Hz, 1 mm seat amplitude: power from the seat {supplied:.6f} W, dissipated {body.dissipated_power(f, {n: v[0] for n, v in state.items()}, inputs={'seat': 1e-3}):.6f} W\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Seat shock\n",
    "\n",
    "A half-sine acceleration pulse of 2 g and 20 ms; its velocity change is $\\Delta v=2\\cdot 2g\\cdot0.02/\\pi$.\n",
    "The seat height is the twice-integrated pulse."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "amplitude, duration = 2 * 9.81, 0.020\n",
    "seat = lambda t: (\n",
    "    amplitude\n",
    "    * duration\n",
    "    / np.pi\n",
    "    * (\n",
    "        np.clip(t, 0.0, duration)\n",
    "        - duration / np.pi * np.sin(np.pi * np.clip(t, 0.0, duration) / duration)\n",
    "    )\n",
    "    + amplitude * duration * 2 / np.pi * max(t - duration, 0.0)\n",
    ")\n",
    "times = np.linspace(0.0, 1.5, 1501)\n",
    "positions, velocities = body.transient(times, inputs={\"seat\": seat})\n",
    "head_acceleration = np.gradient(velocities[\"head\"], times)\n",
    "jump = amplitude * duration * 2 / np.pi\n",
    "print(\n",
    "    f\"seat shock: velocity change {jump:.4f} m/s; after 1.5 s the segments move at \"\n",
    "    + \", \".join(f\"{name} {velocities[name][-1]:.4f}\" for name in segments)\n",
    "    + \" m/s\"\n",
    ")\n",
    "print(\n",
    "    f\"largest head acceleration {np.abs(head_acceleration).max() / 9.81:.2f} g against 2 g at the seat\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left the seat-to-head transmissibility and the normalised apparent mass with the natural\n",
    "frequencies; right the head acceleration after the seat shock."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.line(\n",
    "    y={\n",
    "        \"seat-to-head transmissibility\": (frequencies, transmissibility),\n",
    "        \"apparent mass / static mass\": (frequencies, apparent / sum(segments.values())),\n",
    "    },\n",
    "    vlines={f\"mode {k + 1}\": f for k, f in enumerate(modes.frequencies)},\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"frequency [Hz]\",\n",
    "    ylabel=\"ratio\",\n",
    "    title=\"Biodynamic response to vertical seat vibration\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        \"head\": (1e3 * times, head_acceleration / 9.81),\n",
    "        \"seat\": (\n",
    "            1e3 * times,\n",
    "            np.where(times <= duration, 2 * np.sin(np.pi * times / duration), 0.0),\n",
    "        ),\n",
    "    },\n",
    "    xlimits=(0, 600),\n",
    "    xlabel=\"time [ms]\",\n",
    "    ylabel=\"vertical acceleration [g]\",\n",
    "    title=\"Half-sine seat shock, 2 g, 20 ms\",\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",
    "Add a seat cushion between the seat pan and the pelvis and tune it to lower the transmissibility\n",
    "at 5 Hz, couple the model to the vehicle model of the companion example, or fit the stiffness and\n",
    "damping values to measured apparent-mass curves with a least-squares study."
   ]
  }
 ]
}
