{ "nbformat": 4, "nbformat_minor": 5, "metadata": { "colab": { "provenance": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Chapter 5 - Modeling the Speed-Duration Curve" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import plotly.graph_objects as go\n", "from scipy.optimize import curve_fit\n", "\n", "distances = np.array([100, 200, 400, 800, 1500, 3000, 5000, 10000, 21100, 42200], dtype=float)\n", "speeds = np.array([37.6, 37.5, 33.5, 28.5, 26.2, 24.5, 23.8, 22.9, 22.0, 20.9], dtype=float)\n", "\n", "def speed_curve(x, a, b):\n", " return a * np.power(x, b)\n", "\n", "params, covariance = curve_fit(speed_curve, distances, speeds, p0=(50, -0.1), maxfev=10000)\n", "print(f\"Fit: speed = {params[0]:.2f} * distance^{params[1]:.3f}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig = go.Figure()\n", "fig.add_trace(go.Scatter(x=distances, y=speeds, mode=\"markers\", name=\"Observed\"))\n", "fig.add_trace(go.Scatter(x=distances, y=speed_curve(distances, *params), mode=\"lines\", name=\"Fitted curve\"))\n", "fig.update_layout(title=\"Speed-Distance Curve\", xaxis_title=\"Distance (m)\", yaxis_title=\"Speed (km/h)\")\n", "fig.show()\n", "print(\"Notebook completed.\")" ] } ] }