{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a691e1ea",
   "metadata": {},
   "source": [
    "# A roller chain on a turning polygon\n",
    "\n",
    "Predict what happens to speed ripple when the tooth count doubles while the mean conveying speed is kept fixed. Change the first cell, run all cells, and compare speed, timing and displacement."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d1672918",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "pitch = .0127      # m between adjacent roller centres\n",
    "teeth = 12         # integer sprocket tooth count\n",
    "rpm = 120.0        # constant drive shaft speed\n",
    "sensor_phase = .25 # fraction of one engagement interval, 0 to 1\n",
    "assert int(teeth) == teeth and teeth >= 4 and pitch > 0 and rpm > 0\n",
    "assert 0 <= sensor_phase <= 1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e7b73382",
   "metadata": {},
   "source": [
    "## Advance by one chord\n",
    "A roller centre sweeps an angle of $2\\pi/z$ over one engagement. Integrate the projection of its circular velocity on the straight strand. The difference in projected position between the interval endpoints has to be one pitch."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "620a353c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def chain(z, drive_rpm, phase):\n",
    "    a = np.pi/z\n",
    "    R = pitch/(2*np.sin(a))\n",
    "    omega = 2*np.pi*drive_rpm/60\n",
    "    theta = (2*np.asarray(phase)-1)*a\n",
    "    advance = R*(np.sin(theta)+np.sin(a))\n",
    "    velocity = omega*R*np.cos(theta)\n",
    "    mean = pitch*z*drive_rpm/60\n",
    "    return advance,velocity,mean\n",
    "\n",
    "phase = np.linspace(0,1,501)\n",
    "advance,v,mean = chain(teeth,rpm,phase)\n",
    "assert np.isclose(advance[-1]-advance[0],pitch)\n",
    "assert np.isclose(np.sum(np.diff(phase) * (v[:-1] + v[1:]) / 2)/mean,1,rtol=2e-6)\n",
    "print(f\"Mean strand speed {mean:.5f} m/s; tooth-pass frequency {teeth*rpm/60:.1f} Hz\")\n",
    "print(f\"Full speed variation / mean = {100*(v.max()-v.min())/mean:.4f}%\")\n",
    "x_obs,v_obs,_ = chain(teeth,rpm,sensor_phase)\n",
    "print(f\"At phase {sensor_phase:.3f}: advance = {1e3*x_obs:.4f} mm, speed = {v_obs:.5f} m/s\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "955495e1",
   "metadata": {},
   "source": [
    "## Compare equal mean speeds\n",
    "The doubled-tooth sprocket must rotate half as fast to maintain the same pitch throughput. The phase coordinate stays comparable because the number of engagements per second is also unchanged."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a30e9e8f",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(1,2,figsize=(9,3.5),layout=\"constrained\")\n",
    "for z, r, style in [(teeth,rpm,\"-\"),(2*teeth,rpm/2,\"--\")]:\n",
    "    x,u,m = chain(z,r,phase)\n",
    "    ax[0].plot(phase,100*(u/m-1),style,label=f\"{z} teeth\")\n",
    "    ax[1].plot(phase,(x-phase*pitch)*1e6,style,label=f\"{z} teeth\")\n",
    "ax[0].set(xlabel=\"Fraction of an engagement\",ylabel=\"Speed departure from mean (%)\",title=\"Instantaneous strand speed\")\n",
    "ax[1].set(xlabel=\"Fraction of an engagement\",ylabel=\"Position error (µm)\",title=\"Relative to uniform advance\")\n",
    "for p in ax:\n",
    "    p.axhline(0,color=\"0.55\",lw=.8); p.grid(alpha=.23); p.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2572a53",
   "metadata": {},
   "source": [
    "## Try a tooth-count specification\n",
    "Find the smallest integer tooth count whose peak-to-peak speed variation is below 0.5% of the mean. Does increasing shaft speed change this percentage? Decide whether a sensor that counts only whole pitches would detect the position error drawn on the right."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e5859e92",
   "metadata": {},
   "outputs": [],
   "source": [
    "for z in range(4,200):\n",
    "    a = np.pi/z\n",
    "    ripple = a*np.tan(a/2)\n",
    "    if ripple < .005:\n",
    "        print(f\"First tooth count below 0.5%: {z}; ripple = {100*ripple:.4f}%\")\n",
    "        break"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22de1abf",
   "metadata": {},
   "source": [
    "## Check the mean with four velocity samples\n",
    "Use a four-point Gauss rule in engagement phase. Each node has a different integration weight. OneSimulation supplies the quadrature table in a local installation. The browser computes equivalent Gauss nodes and weights with NumPy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "62aefdf6",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    from onesim.numerics.discretization.geometry.carriers.kernels.quadrature.rules.reference_quadrature import gauss_legendre\n",
    "    nodes, weights = np.asarray(gauss_legendre(4)).T\n",
    "    method = \"OneSimulation Gauss quadrature\"\n",
    "except ImportError:\n",
    "    nodes, weights = np.polynomial.legendre.leggauss(4)\n",
    "    method = \"NumPy Gauss quadrature\"\n",
    "\n",
    "# Map the reference interval [-1, 1] to one complete engagement.\n",
    "gauss_phase = (nodes + 1) / 2\n",
    "sampled_speed = chain(teeth, rpm, gauss_phase)[1]\n",
    "gauss_mean = weights @ sampled_speed / 2\n",
    "print(f\"{method} with four samples: {gauss_mean:.8f} m/s\")\n",
    "assert np.isclose(gauss_mean, mean, rtol=1e-7)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
