{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Curve fitting: temperature as a function of month of the year\n\nWe have the min and max temperatures in Alaska for each months of the\nyear. We would like to find a function to describe this yearly evolution.\n\nFor this, we will fit a periodic function.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## The data\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\n\ntemp_max = np.array([17, 19, 21, 28, 33, 38, 37, 37, 31, 23, 19, 18])\ntemp_min = np.array([-62, -59, -56, -46, -32, -18, -9, -13, -25, -46, -52, -58])\n\nimport matplotlib.pyplot as plt\n\nmonths = np.arange(12)\nplt.plot(months, temp_max, \"ro\")\nplt.plot(months, temp_min, \"bo\")\nplt.xlabel(\"Month\")\nplt.ylabel(\"Min and max temperature\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Fitting it to a periodic function\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import scipy as sp\n\n\ndef yearly_temps(times, avg, ampl, time_offset):\n    return avg + ampl * np.cos((times + time_offset) * 2 * np.pi / times.max())\n\n\nres_max, cov_max = sp.optimize.curve_fit(yearly_temps, months, temp_max, [20, 10, 0])\nres_min, cov_min = sp.optimize.curve_fit(yearly_temps, months, temp_min, [-40, 20, 0])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Plotting the fit\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "days = np.linspace(0, 12, num=365)\n\nplt.figure()\nplt.plot(months, temp_max, \"ro\")\nplt.plot(days, yearly_temps(days, *res_max), \"r-\")\nplt.plot(months, temp_min, \"bo\")\nplt.plot(days, yearly_temps(days, *res_min), \"b-\")\nplt.xlabel(\"Month\")\nplt.ylabel(r\"Temperature ($^\\circ$C)\")\n\nplt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.12.11"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}