Files
jupyter-collection/scientific-computing-2/auto_examples_jupyter_3/solutions/plot_periodicity_finder.ipynb
2025-10-21 11:20:44 +08:00

93 lines
2.5 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Crude periodicity finding\n\nDiscover the periods in evolution of animal populations\n(:download:`../../../../data/populations.txt`)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Load the data\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n\ndata = np.loadtxt(\"../../../../data/populations.txt\")\nyears = data[:, 0]\npopulations = data[:, 1:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Plot the data\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n\nplt.figure()\nplt.plot(years, populations * 1e-3)\nplt.xlabel(\"Year\")\nplt.ylabel(r\"Population number ($\\cdot10^3$)\")\nplt.legend([\"hare\", \"lynx\", \"carrot\"], loc=1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Plot its periods\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import scipy as sp\n\nft_populations = sp.fft.fft(populations, axis=0)\nfrequencies = sp.fft.fftfreq(populations.shape[0], years[1] - years[0])\nperiods = 1 / frequencies\n\nplt.figure()\nplt.plot(periods, abs(ft_populations) * 1e-3, \"o\")\nplt.xlim(0, 22)\nplt.xlabel(\"Period\")\nplt.ylabel(r\"Power ($\\cdot10^3$)\")\n\nplt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There's probably a period of around 10 years (obvious from the\nplot), but for this crude a method, there's not enough data to say\nmuch more.\n\n"
]
}
],
"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
}