{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c10541d6",
   "metadata": {},
   "source": [
    "# What a passenger and a tyre feel on the same road\n",
    "\n",
    "A repeating surface profile produces a temporal excitation whose frequency depends on travel speed. Before running, predict whether doubling the road speed must increase the passenger acceleration. Change the first cell, rerun, and compare the two observables in the plot."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "63fc91f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "ms, mu = 250.0, 35.0   # sprung and unsprung masses, kg\n",
    "ks, kt = 15000., 160000.  # suspension and tyre stiffnesses, N/m\n",
    "c = 1200.               # suspension damping, N s/m\n",
    "road_amplitude = .003   # m, sinusoidal height amplitude\n",
    "wavelength = 4.0        # m per cycle\n",
    "speed = 12.0            # m/s\n",
    "assert min(ms, mu, ks, kt, c, road_amplitude, wavelength, speed) > 0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "afbad147",
   "metadata": {},
   "source": [
    "## Find the two undamped modes\n",
    "Mass-normalising the stiffness produces a symmetric eigenproblem. The eigenvectors in these normalised coordinates must be mapped back to physical displacements. In an environment with OneSimulation this cell uses its symmetric eigensystem solver."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "372e0bfe",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    from onesim.numerics.linear.matrices.dense_linear_algebra import symmetric_eigensystem\n",
    "except ImportError:\n",
    "    symmetric_eigensystem = np.linalg.eigh\n",
    "K = np.array([[ks,-ks],[-ks,ks+kt]])\n",
    "Minvhalf = np.diag([ms**-.5,mu**-.5])\n",
    "omega2, modes = symmetric_eigensystem(Minvhalf @ K @ Minvhalf)\n",
    "natural = np.sqrt(omega2)/(2*np.pi)\n",
    "physical = Minvhalf @ modes\n",
    "print(\"Undamped frequencies (Hz):\", np.round(natural,3))\n",
    "print(\"Body displacement / wheel displacement in each mode:\", np.round(physical[0]/physical[1],3))\n",
    "assert np.all(omega2 > 0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e384b98a",
   "metadata": {},
   "source": [
    "## Turn a road height into body acceleration and tyre force\n",
    "Complex displacements below are per unit road amplitude. The tyre force is determined by the difference between wheel and road positions, so its phase matters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4509d9f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "def response(freq, damping):\n",
    "    w = 2*np.pi*np.asarray(freq)\n",
    "    s = ks + 1j*w*damping\n",
    "    a, b = s - ms*w*w, s + kt - mu*w*w\n",
    "    det = a*b - s*s\n",
    "    return s*kt/det, a*kt/det\n",
    "\n",
    "def observables(freq, damping):\n",
    "    body, wheel = response(freq,damping)\n",
    "    acc = (2*np.pi*freq)**2*np.abs(body)*road_amplitude\n",
    "    force = kt*np.abs(wheel-1)*road_amplitude\n",
    "    return acc,force\n",
    "\n",
    "physical_frequency = speed/wavelength\n",
    "a0, f0 = observables(physical_frequency,c)\n",
    "print(f\"At {physical_frequency:.3f} Hz: body acceleration amplitude {a0:.3f} m/s², dynamic tyre force amplitude {f0:.1f} N\")\n",
    "assert np.allclose(response(0., c), [1,1])\n",
    "assert np.allclose(response(physical_frequency,c), np.linalg.solve(\n",
    "    K-(2*np.pi*physical_frequency)**2*np.diag([ms,mu])+1j*2*np.pi*physical_frequency*c*np.array([[1,-1],[-1,1]]),[0,kt]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7005fc3b",
   "metadata": {},
   "source": [
    "## Compare damping for the same input\n",
    "Follow the two dashed vertical markers from the low- to the high-frequency mode. The solid and dashed responses differ only in the suspension damping."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d139047",
   "metadata": {},
   "outputs": [],
   "source": [
    "f = np.geomspace(.25,35.,550)\n",
    "fig, ax = plt.subplots(1,2,figsize=(9.2,3.6),layout=\"constrained\")\n",
    "for factor,style in [(1,\"-\"),(2,\"--\")]:\n",
    "    a,force = observables(f,c*factor)\n",
    "    ax[0].loglog(f,a,style,label=f\"c = {c*factor:.0f} N s/m\")\n",
    "    ax[1].loglog(f,force,style,label=f\"c = {c*factor:.0f} N s/m\")\n",
    "for p in ax:\n",
    "    for mode in natural: p.axvline(mode,color=\"0.65\",lw=.8,ls=\":\")\n",
    "    p.set_xlabel(\"Road excitation (Hz)\"); p.grid(which=\"major\",alpha=.24); p.legend(fontsize=8)\n",
    "ax[0].set(ylabel=\"Acceleration amplitude (m/s²)\",title=\"Sprung mass\")\n",
    "ax[1].set(ylabel=\"Dynamic contact force amplitude (N)\",title=\"Tyre against the road\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3fc1918",
   "metadata": {},
   "source": [
    "## Investigate\n",
    "Find a frequency band where greater damping increases passenger acceleration. Translate each natural frequency to a road speed at the chosen wavelength. Check the maximum dynamic tyre force against the static corner load $(m_s+m_u)g$. If their ratio exceeds one, the linear model predicts tensile contact during part of a cycle and its contact assumption has failed."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
