{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Running Mean Script\n", "### Ewan Miles - 06/05/2020\n", "\n", "**This code is entirely open-source and thus editable by any user.**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This script is designed to be used contemporaneously with data-taking, and does not save any data to files or require the user to be complete with units or variables. It is simply designed such that the user re-runs a cell for each new datapoint, and the graph updates with a display of the mean value (plus error) vs. number of trials.\n", "\n", "This makes it useful for learning how many trials should be taken to collect data without being inefficient by taking too many datapoints; for example, if a mean can be found in 30 points when taking 100 reduces the uncertainty by only 0.1%, ideally you should take 30 points instead of 100. \n", "\n", "The function **runningmean()** is defined, with its only argument being the value of the new datapoint. It appends the empty data sets in the first cell, calculates a new mean with error, and appends that also. A very simple process! The third cell is run repeatedly, each time with **runningmean()** being given a new data value (e.g. `runningmean(14)` (run) -> `runningmean(12)` (run) -> etc.). The third cell also plots the new graph each time, using the arrays defined earlier, which are appended with new values each time the cell is run.\n", "\n", "The following equations are used:\n", "* The mean average, $\\bar{x}$:\n", "$$\\normalsize{\\bar{x}=\\frac{\\sum x_i}{n}}$$\n", "where $x_i$ is each datapoint and $n$ is the total number of datapoints.\n", "\n", "\n", "\n", "* The standard deviation, $\\sigma$:\n", "$$\\normalsize{\\sigma=E(x_i^2) - [E(x_i)]^2} \\equiv \\bar{(x^2)} - (\\bar{x})^2$$\n", "where $E(x) \\equiv \\bar{x}$, that is, the relation above is **the mean of the square subtract the square of the mean**.\n", "\n", "\n", "\n", "* The error on the mean, $\\Delta \\bar{x}$:\n", "$$\\normalsize{\\Delta \\bar{x}=\\frac{\\sigma}{\\sqrt{n}}}$$\n", "\n", "A save cell is included at the end of the script, which will ask the user to input a file name for the figure, and save it to the local directory. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "### IMPORTING MODULES, CREATING EMPTY DATASETS\n", "\n", "# Interactive figures\n", "%matplotlib notebook\n", "\n", "import numpy as np # Maths module\n", "import matplotlib.pyplot as plt # Plots graphs\n", "\n", "# Empty arrays to be appended for plotting\n", "dataset = []\n", "trials = []\n", "x = []\n", "y = []\n", "yerr = []" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def runningmean(i):\n", " trials.append(1)\n", " dataset.append(float(i))\n", " n = np.sum(trials) # Current number of trials\n", " square = np.square(dataset)\n", " mean = np.mean(dataset)\n", " stdev = np.sqrt(np.mean(square) - np.square(mean)) # Standard deviation of datapoints\n", " error = stdev/np.sqrt(n) # Error on mean of datapoints\n", " x.append(n) # Append x with trial number\n", " y.append(mean) # Append y with current mean\n", " yerr.append(error) # Append yerr with current error on mean" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "### RE-RUN THIS CELL FOR EACH NEW DATAPOINT, INPUT IN runningmean() FUNCTION ###\n", "\n", "runningmean(1.72)\n", "\n", "#Plot data\n", "plt.figure()\n", "plt.grid(True)\n", "plt.errorbar(x, y, yerr=yerr, fmt=\"b.\")\n", "plt.xlabel(\"Number of Trials\")\n", "plt.ylabel(\"Mean \")\n", "plt.title(\"Verifying the Number of Trials Used\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### SAVE CELL: The code below saves the figure with any name you give it.\n", "\n", "**Do not run the cell if you do not wish to save the figure - the only escape to the input field is to kill the kernel.**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Save figure to local directory with name chosen by user\n", "name = str(input(\"Name the graph. End it with .pdf for a PDF, .png for a PNG, etc. The default is a PNG:\"))\n", "plt.savefig(name)\n", "print(\"It has been saved to the file location (local directory) of this python program.\") " ] } ], "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.6.8" } }, "nbformat": 4, "nbformat_minor": 2 }