{
 "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 vehicle suspension with seated occupants\n",
    "\n",
    "Ride comfort is decided at low frequencies, below about 20 Hz, where a car moves as a few rigid\n",
    "bodies on springs: the body heaves, pitches and rolls on the suspension, the wheels hop on the\n",
    "tyres, and seats and occupants add their own small spring-mass systems. A lumped model with\n",
    "masses, springs and dampers captures this. With $\\mathbf q$ the free coordinates and $\\mathbf u$\n",
    "the road heights under the four tyres,\n",
    "\n",
    "$$\\mathbf M\\ddot{\\mathbf q}+\\mathbf C\\dot{\\mathbf q}+\\mathbf K\\mathbf q=-\\mathbf C_u\\dot{\\mathbf u}-\\mathbf K_u\\mathbf u .$$\n",
    "\n",
    "Springs and dampers act between points: the corners and seat mounts of the body move with\n",
    "$z\\mp a\\,\\theta\\pm w\\,\\varphi$ for small pitch $\\theta$ and roll $\\varphi$.\n",
    "\n",
    "**Setup.** Body: 1200 kg, pitch inertia 2100 kg m², roll inertia 460 kg m²; front axle 1.2 m and\n",
    "rear axle 1.4 m from the centre of mass, half track 0.75 m. Wheels: 40 kg each, tyre stiffness\n",
    "200 kN/m. Suspension: 28 kN/m and 2000 N s/m at the front, 24 kN/m and 1800 N s/m at the rear.\n",
    "Seats 0.3 m ahead of the centre of mass and 0.35 m left and right: cushion frame 15 kg on 60 kN/m\n",
    "and 500 N s/m; occupant 75 kg on the cushion with 50 kN/m and 1500 N s/m. Eleven coordinates:\n",
    "body heave, pitch and roll, four wheel heights, two seat frames and two occupants.\n",
    "\n",
    "| element | between |\n",
    "|---|---|\n",
    "| tyre | wheel and road under it |\n",
    "| suspension spring and damper | wheel and body corner |\n",
    "| seat mount | body at the seat and seat frame |\n",
    "| cushion | seat frame and occupant |\n",
    "\n",
    "**Reference.** (1) Statics: under gravity the axle loads follow from the moment balance about the\n",
    "centre of mass, $F_\\text{front}=W_s\\,b_s/L$ with the sprung weight $W_s$ and its lever $b_s$ to the\n",
    "rear axle, and each spring compresses by its load over its stiffness. (2) At very low frequency\n",
    "every coordinate follows the road rigidly (transmissibility 1). (3) In a harmonic state the power\n",
    "the road puts into the car equals the power dissipated in the dampers."
   ]
  },
  {
   "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",
    "Each corner $c$ of the body is a point $\\{z: 1, \\theta: -x_c, \\varphi: y_c\\}$ with its distance\n",
    "$x_c$ ahead of the centre of mass and $y_c$ to the left; the road heights under the tyres are the\n",
    "inputs of the network."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "front, rear, track, seat_x, seat_y = 1.2, 1.4, 0.75, 0.3, 0.35\n",
    "corners = {\n",
    "    \"fl\": (front, track),\n",
    "    \"fr\": (front, -track),\n",
    "    \"rl\": (-rear, track),\n",
    "    \"rr\": (-rear, -track),\n",
    "}\n",
    "body_point = lambda x, y: {\"heave\": 1.0, \"pitch\": -x, \"roll\": y}\n",
    "suspension = {\n",
    "    \"fl\": (28e3, 2000.0),\n",
    "    \"fr\": (28e3, 2000.0),\n",
    "    \"rl\": (24e3, 1800.0),\n",
    "    \"rr\": (24e3, 1800.0),\n",
    "}\n",
    "seats = {\"driver\": seat_y, \"passenger\": -seat_y}\n",
    "car = LumpedMechanicalNetwork(\n",
    "    inertias={\n",
    "        \"heave\": 1200.0,\n",
    "        \"pitch\": 2100.0,\n",
    "        \"roll\": 460.0,\n",
    "        **{f\"wheel_{c}\": 40.0 for c in corners},\n",
    "        **{f\"seat_{s}\": 15.0 for s in seats},\n",
    "        **{f\"occupant_{s}\": 75.0 for s in seats},\n",
    "    },\n",
    "    springs=(\n",
    "        *(Spring(200e3, f\"wheel_{c}\", f\"road_{c}\") for c in corners),\n",
    "        *(\n",
    "            Spring(suspension[c][0], body_point(*corners[c]), f\"wheel_{c}\")\n",
    "            for c in corners\n",
    "        ),\n",
    "        *(Spring(60e3, f\"seat_{s}\", body_point(seat_x, y)) for s, y in seats.items()),\n",
    "        *(Spring(50e3, f\"occupant_{s}\", f\"seat_{s}\") for s in seats),\n",
    "    ),\n",
    "    dampers=(\n",
    "        *(\n",
    "            Damper(suspension[c][1], body_point(*corners[c]), f\"wheel_{c}\")\n",
    "            for c in corners\n",
    "        ),\n",
    "        *(Damper(500.0, f\"seat_{s}\", body_point(seat_x, y)) for s, y in seats.items()),\n",
    "        *(Damper(1500.0, f\"occupant_{s}\", f\"seat_{s}\") for s in seats),\n",
    "    ),\n",
    "    inputs=tuple(f\"road_{c}\" for c in corners),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Natural modes\n",
    "\n",
    "The undamped modes, each named after the coordinate that moves most."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "modes = car.modes()\n",
    "for k, frequency in enumerate(modes.frequencies):\n",
    "    shape = modes.shape(k)\n",
    "    print(\n",
    "        f\"mode {k + 1:2d}: {frequency:6.2f} Hz, dominated by {max(shape, key=lambda name: abs(shape[name]))}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Static sag under gravity\n",
    "\n",
    "Gravity acts on all masses; the seat mounts pass the weight of seats and occupants to the body\n",
    "ahead of its centre of mass. The axle loads from the moment balance give the spring compressions."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "gravity = 9.81\n",
    "sag = car.static(\n",
    "    {\n",
    "        name: -mass * gravity\n",
    "        for name, mass in car.inertias.items()\n",
    "        if name not in (\"pitch\", \"roll\")\n",
    "    }\n",
    ")\n",
    "sprung = 1200.0 + 2 * (15.0 + 75.0)\n",
    "lever = (1200.0 * rear + 2 * (15.0 + 75.0) * (rear + seat_x)) / sprung\n",
    "front_axle = sprung * gravity * lever / (front + rear)\n",
    "expected = {\n",
    "    \"front tyre\": -(front_axle / 2 + 40.0 * gravity) / 200e3,\n",
    "    \"rear tyre\": -((sprung * gravity - front_axle) / 2 + 40.0 * gravity) / 200e3,\n",
    "    \"front spring\": -front_axle / 2 / 28e3,\n",
    "    \"rear spring\": -(sprung * gravity - front_axle) / 2 / 24e3,\n",
    "}\n",
    "computed = {\n",
    "    \"front tyre\": sag[\"wheel_fl\"],\n",
    "    \"rear tyre\": sag[\"wheel_rl\"],\n",
    "    \"front spring\": sag[\"heave\"] - front * sag[\"pitch\"] - sag[\"wheel_fl\"],\n",
    "    \"rear spring\": sag[\"heave\"] + rear * sag[\"pitch\"] - sag[\"wheel_rl\"],\n",
    "}\n",
    "for name in expected:\n",
    "    print(\n",
    "        f\"static compression of the {name:13s}: {1e3 * computed[name]:8.3f} mm (statics {1e3 * expected[name]:8.3f} mm)\"\n",
    "    )\n",
    "print(\n",
    "    f\"occupant sinks {1e3 * (sag['occupant_driver'] - sag['seat_driver']):.2f} mm into the cushion (statics {-1e3 * 75.0 * gravity / 50e3:.2f} mm); \"\n",
    "    f\"body pitch {1e3 * sag['pitch']:.3f} mrad\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Ride comfort over a road wave\n",
    "\n",
    "A road with a sinusoidal height reaches the rear wheels a wheelbase later than the front wheels.\n",
    "At 72 km/h the delay is $L/v$; the driver's vertical acceleration per metre of road amplitude\n",
    "follows over 0.1–20 Hz."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "speed = 20.0\n",
    "delay = (front + rear) / speed\n",
    "frequencies = np.geomspace(0.1, 20.0, 400)\n",
    "response = {\n",
    "    c: (\n",
    "        np.exp(-2j * np.pi * frequencies * delay)\n",
    "        if c.startswith(\"r\")\n",
    "        else np.ones_like(frequencies, dtype=complex)\n",
    "    )\n",
    "    for c in corners\n",
    "}\n",
    "harmonic = {\n",
    "    name: np.array(\n",
    "        [\n",
    "            car.frequency_response(\n",
    "                [f], inputs={f\"road_{c}\": response[c][k] for c in corners}\n",
    "            )[name][0]\n",
    "            for k, f in enumerate(frequencies)\n",
    "        ]\n",
    "    )\n",
    "    for name in (\"occupant_driver\", \"heave\", \"pitch\")\n",
    "}\n",
    "acceleration = np.abs((2 * np.pi * frequencies) ** 2 * harmonic[\"occupant_driver\"])\n",
    "check = car.frequency_response([1.5], inputs={f\"road_{c}\": 0.01 for c in corners})\n",
    "road_force = sum(200e3 * (0.01 - check[f\"wheel_{c}\"][0]) for c in corners)\n",
    "supplied = 0.5 * np.real(np.conj(1j * 2 * np.pi * 1.5 * 0.01) * road_force)\n",
    "print(\n",
    "    f\"at 0.1 Hz the driver follows the road with transmissibility {abs(harmonic['occupant_driver'][0]):.4f} (rigid motion: 1)\"\n",
    ")\n",
    "print(\n",
    "    f\"harmonic state at 1.5 Hz, 10 mm road: power from the road {supplied:.4f} W, dissipated in the dampers \"\n",
    "    f\"{car.dissipated_power(1.5, {name: values[0] for name, values in check.items()}, inputs={f'road_{c}': 0.01 for c in corners}):.4f} W\"\n",
    ")\n",
    "print(\n",
    "    f\"largest driver acceleration per metre of road: {acceleration.max():.0f} m/s² per m at {frequencies[np.argmax(acceleration)]:.2f} Hz\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Crossing a speed bump\n",
    "\n",
    "A bump 80 mm high and 0.5 m long, a half sine in space, crossed at 18 km/h; the rear wheels meet it\n",
    "a wheelbase later."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "bump_speed, height, length = 5.0, 0.08, 0.5\n",
    "bump = (\n",
    "    lambda t: height\n",
    "    * np.sin(np.pi * np.clip(bump_speed * t / length, 0.0, 1.0))\n",
    "    * (0.0 <= bump_speed * t <= length)\n",
    ")\n",
    "times = np.linspace(0.0, 3.0, 1501)\n",
    "positions, velocities = car.transient(\n",
    "    times,\n",
    "    inputs={\n",
    "        f\"road_{c}\": (\n",
    "            lambda t, d=(\n",
    "                delay * speed / bump_speed if c.startswith(\"r\") else 0.0\n",
    "            ): bump(t - d)\n",
    "        )\n",
    "        for c in corners\n",
    "    },\n",
    ")\n",
    "driver_acceleration = np.gradient(velocities[\"occupant_driver\"], times)\n",
    "print(\n",
    "    f\"speed bump at 18 km/h: largest driver acceleration {np.abs(driver_acceleration).max():.2f} m/s², largest body pitch \"\n",
    "    f\"{1e3 * np.abs(positions['pitch']).max():.1f} mrad; after 3 s the body is back within {1e3 * abs(positions['heave'][-1]):.2f} mm\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Left the driver's acceleration per metre of road amplitude over frequency at 72 km/h; right the\n",
    "heights of road, body centre and driver while crossing the bump."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(16, 6))\n",
    "plots.line(\n",
    "    y={\"driver acceleration\": (frequencies, acceleration)},\n",
    "    vlines={f\"mode {k + 1}\": f for k, f in enumerate(modes.frequencies[:3])},\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"frequency [Hz]\",\n",
    "    ylabel=\"|a| per road amplitude [m/s² per m]\",\n",
    "    title=\"Ride comfort at 72 km/h\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        \"road under the front wheels\": (\n",
    "            times,\n",
    "            1e3 * np.array([bump(t) for t in times]),\n",
    "        ),\n",
    "        \"body centre\": (times, 1e3 * positions[\"heave\"]),\n",
    "        \"driver\": (times, 1e3 * positions[\"occupant_driver\"]),\n",
    "        \"front-left wheel\": (times, 1e3 * positions[\"wheel_fl\"]),\n",
    "    },\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"height [mm]\",\n",
    "    title=\"Crossing an 80 mm speed bump at 18 km/h\",\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",
    "Tune the seat damping for the lowest peak acceleration, let only one side of the car hit the bump\n",
    "to excite roll, or replace the half-sine bump by a measured road profile."
   ]
  }
 ]
}
