{ "cells": [ { "cell_type": "markdown", "id": "lab2", "metadata": { "editable": true, "slideshow": { "slide_type": "slide" }, "tags": [] }, "source": [ "## Lab 02: NumPy, SciPy, and Matplotlib\n", "\n", "- **Import before using a package**\n", "- **Point out the short names**\n", "\n", "We'll use a short set of temperature readings to work with arrays, make plots, and fit\n", "a line. The readings are provided below; there's no data file to download.\n", "\n", "First, import the packages. `import numpy as np` lets us use the short name `np`.\n", "`matplotlib.pyplot` is the plotting module; we'll call it `plt`." ] }, { "cell_type": "code", "execution_count": null, "id": "imports", "metadata": { "editable": true, "slideshow": { "slide_type": "slide" }, "tags": [] }, "outputs": [], "source": [ "import numpy as np\n", "import scipy\n", "import matplotlib.pyplot as plt" ] }, { "cell_type": "markdown", "id": "package-versions-cue", "metadata": { "editable": true, "slideshow": { "slide_type": "slide" }, "tags": [] }, "source": [ "- **Which versions did we import?**" ] }, { "cell_type": "code", "execution_count": null, "id": "package-versions", "metadata": {}, "outputs": [], "source": [ "print(\"NumPy:\", np.__version__)\n", "print(\"SciPy:\", scipy.__version__)" ] }, { "cell_type": "markdown", "id": "installing", "metadata": { "editable": true, "slideshow": { "slide_type": "" }, "tags": [] }, "source": [ "### If a package is missing\n", "\n", "- **Install into this notebook’s environment**\n", "- **After restarting, import again**\n", "\n", "If the import cell gives `ModuleNotFoundError`, the package isn't available in that\n", "kernel. In Colab or your own local notebook, remove the `#` from the line below and run it.\n", "`%pip` installs into the environment used by this notebook.\n", "\n", "If installation asks for a restart, restart the kernel. After any successful installation,\n", "rerun the import cell above. Then put the `#` back so Run All doesn't keep running\n", "the installation command. For a different\n", "package, replace the names with the package you need.\n", "\n", "On DataHub, these packages should be in the course environment. If they aren't, check\n", "which environment you selected and ask me before installing over the existing setup.\n", "For a separate custom environment, use the [DataHub instructions](https://support.ucsd.edu/services?id=kb_article_view&sysparm_article=KB0033812).\n", "\n", "**Install** adds the package to an environment. **Import** makes it available to the\n", "current Python session. You'll import again after a restart. A new Colab runtime may\n", "also need packages installed again." ] }, { "cell_type": "code", "execution_count": null, "id": "91eef648-fd31-4a99-8413-8c0790f6c3b0", "metadata": {}, "outputs": [], "source": [ "import art" ] }, { "cell_type": "code", "execution_count": null, "id": "install-command", "metadata": {}, "outputs": [], "source": [ "%pip install art" ] }, { "cell_type": "markdown", "id": "arrays", "metadata": {}, "source": [ "### NumPy arrays\n", "\n", "- **Same values, different containers**\n", "- **Predict before you run**\n", "\n", "With an array, we can apply the same calculation to every number at once. A list behaves\n", "differently: multiplying a list repeats it, while multiplying an array multiplies its values." ] }, { "cell_type": "code", "execution_count": null, "id": "list-array", "metadata": {}, "outputs": [], "source": [ "values_list = [1, 2, 3]\n", "values_array = np.array(values_list)" ] }, { "cell_type": "markdown", "id": "list-times-two-cue", "metadata": {}, "source": [ "- **Predict: a list times two.**" ] }, { "cell_type": "code", "execution_count": null, "id": "list-times-two", "metadata": {}, "outputs": [], "source": [ "values_list * 2" ] }, { "cell_type": "markdown", "id": "array-times-two-cue", "metadata": {}, "source": [ "- **Same operator. Now an array.**" ] }, { "cell_type": "code", "execution_count": null, "id": "array-times-two", "metadata": {}, "outputs": [], "source": [ "values_array * 2" ] }, { "cell_type": "markdown", "id": "array-squared-cue", "metadata": {}, "source": [ "- **Square every entry.**" ] }, { "cell_type": "code", "execution_count": null, "id": "array-squared", "metadata": {}, "outputs": [], "source": [ "values_array**2" ] }, { "cell_type": "markdown", "id": "array-data", "metadata": {}, "source": [ "- **One time, one temperature**\n", "- **Inspect before calculating**\n", "\n", "Here's our example data. Each temperature goes with the time at the same index.\n", "`shape` gives the size of each dimension, and `dtype` gives the type of the entries.\n", "These are one-dimensional arrays with six entries each." ] }, { "cell_type": "code", "execution_count": null, "id": "data", "metadata": {}, "outputs": [], "source": [ "time_min = np.array([0, 1, 2, 3, 4, 5], dtype=float)\n", "temperature_c = np.array([20.0, 21.1, 21.8, 23.2, 23.9, 25.1])" ] }, { "cell_type": "markdown", "id": "data-shape-cue", "metadata": {}, "source": [ "- **How many dimensions? How many entries?**" ] }, { "cell_type": "code", "execution_count": null, "id": "data-shape", "metadata": {}, "outputs": [], "source": [ "temperature_c.shape" ] }, { "cell_type": "markdown", "id": "data-dtype-cue", "metadata": {}, "source": [ "- **What kind of numbers are stored?**" ] }, { "cell_type": "code", "execution_count": null, "id": "data-dtype", "metadata": {}, "outputs": [], "source": [ "temperature_c.dtype" ] }, { "cell_type": "markdown", "id": "data-fahrenheit-cue", "metadata": {}, "source": [ "- **Convert the whole array at once.**" ] }, { "cell_type": "code", "execution_count": null, "id": "data-fahrenheit", "metadata": {}, "outputs": [], "source": [ "temperature_c * 9 / 5 + 32" ] }, { "cell_type": "code", "execution_count": null, "id": "b3f5cec4-543e-4b14-9be1-477a5e024452", "metadata": {}, "outputs": [], "source": [ "def convert2f(ctemp):\n", " return ctemp * 9 / 5 + 32" ] }, { "cell_type": "code", "execution_count": null, "id": "b8e604b8-06a7-4a1c-bc7e-857c1a83af77", "metadata": {}, "outputs": [], "source": [ "convert2f(temperature_c)" ] }, { "cell_type": "markdown", "id": "data-mean-cue", "metadata": {}, "source": [ "### Convenience functions\n", "- **Reduce six readings to one mean.**" ] }, { "cell_type": "code", "execution_count": null, "id": "data-mean", "metadata": {}, "outputs": [], "source": [ "np.mean(temperature_c)" ] }, { "cell_type": "markdown", "id": "data-extremes-cue", "metadata": {}, "source": [ "- **Find the smallest and largest readings.**" ] }, { "cell_type": "code", "execution_count": null, "id": "data-extremes", "metadata": {}, "outputs": [], "source": [ "print(\"Minimum:\", np.min(temperature_c))\n", "print(\"Maximum:\", np.max(temperature_c))" ] }, { "cell_type": "markdown", "id": "data-isclose-cue", "metadata": {}, "source": [ "- **Remember `0.1 + 0.2`? Compare with tolerance.**" ] }, { "cell_type": "code", "execution_count": null, "id": "data-isclose", "metadata": {}, "outputs": [], "source": [ "np.isclose(0.1 + 0.2, 0.3)" ] }, { "cell_type": "markdown", "id": "0adfead2-ea64-41a6-bcf9-3a3193e1e715", "metadata": {}, "source": [ "Be careful with `np.isclose` in particular: https://numpy.org/devdocs/reference/generated/numpy.isclose.html" ] }, { "cell_type": "markdown", "id": "grids", "metadata": {}, "source": [ "#### Making arrays without typing every value\n", "\n", "- **Choose a step or point count**\n", "- **Check whether the endpoint appears**\n", "\n", "`np.arange(start, stop, step)` steps through values and excludes the stop value.\n", "`np.linspace(start, stop, num)` makes `num` evenly spaced points, including both endpoints.\n", "Use `linspace` when you want control over the number of points." ] }, { "cell_type": "code", "execution_count": null, "id": "grids-code", "metadata": {}, "outputs": [], "source": [ "np.arange(0, 6, 1)" ] }, { "cell_type": "markdown", "id": "grid-count-cue", "metadata": {}, "source": [ "- **Choose the number of points.**" ] }, { "cell_type": "code", "execution_count": null, "id": "grid-count", "metadata": {}, "outputs": [], "source": [ "np.linspace(0, 5, 6)" ] }, { "cell_type": "markdown", "id": "grid-denser-cue", "metadata": {}, "source": [ "- **More points. Same endpoints.**" ] }, { "cell_type": "code", "execution_count": null, "id": "grid-denser", "metadata": {}, "outputs": [], "source": [ "np.linspace(0, 5, 11)" ] }, { "cell_type": "markdown", "id": "grids-try", "metadata": {}, "source": [ "- **Count the gaps between points**\n", "- **Check the first and last values**\n", "\n", "Make an array of 21 evenly spaced points from 0 to 10. What will the spacing be?\n", "Then make the same array using `arange`. Remember that its stop value is excluded." ] }, { "cell_type": "markdown", "id": "indexing", "metadata": {}, "source": [ "#### Slices and masks\n", "\n", "- **Show the mask before selecting**\n", "- **Keep times and temperatures paired**\n", "\n", "Array slices work like list slices. You can also select values with a condition.\n", "`temperature_c > 23` creates an array of `True` and `False` values, called a mask.\n", "Use the same mask on both arrays to keep the times paired with their temperatures." ] }, { "cell_type": "code", "execution_count": null, "id": "masks-code", "metadata": {}, "outputs": [], "source": [ "temperature_c[:3]" ] }, { "cell_type": "markdown", "id": "mask-create-cue", "metadata": {}, "source": [ "- **One `True` or `False` per reading.**" ] }, { "cell_type": "code", "execution_count": null, "id": "mask-create", "metadata": {}, "outputs": [], "source": [ "above_23 = temperature_c > 23\n", "above_23" ] }, { "cell_type": "markdown", "id": "mask-apply-cue", "metadata": {}, "source": [ "- **Use the same mask on both arrays.**" ] }, { "cell_type": "code", "execution_count": null, "id": "mask-apply", "metadata": {}, "outputs": [], "source": [ "print(\"Selected times:\", time_min[above_23])\n", "print(\"Selected temperatures:\", temperature_c[above_23])" ] }, { "cell_type": "markdown", "id": "masks-try", "metadata": {}, "source": [ "- **One condition, then two**\n", "- **Parentheses around each comparison**\n", "\n", "Change the condition to select readings at or below 23 °C. If you want two conditions,\n", "use `&` with parentheses around each one, for example `(temperature_c > 21) & (temperature_c < 24)`.\n", "Python's `and` doesn't combine array conditions element by element." ] }, { "cell_type": "markdown", "id": "copies", "metadata": {}, "source": [ "#### Make a copy before changing an array\n", "\n", "- **Two names. One array.**\n", "- **Change one; check the other**\n", "\n", "`new = old` gives the same array a second name. It doesn't copy the data.\n", "A basic slice such as `old[:3]` also shares data with the original array.\n", "Use `.copy()` if you want to change one without changing the other." ] }, { "cell_type": "code", "execution_count": null, "id": "copy-code", "metadata": {}, "outputs": [], "source": [ "original = np.array([10.0, 20.0, 30.0])\n", "same_array = original\n", "same_array[0] = -1\n", "print(\"Original after changing its other name:\", original)" ] }, { "cell_type": "markdown", "id": "copy-independent-cue", "metadata": {}, "source": [ "- **Now copy it. Does the original change?**" ] }, { "cell_type": "code", "execution_count": null, "id": "copy-independent", "metadata": {}, "outputs": [], "source": [ "separate_array = original.copy()\n", "separate_array[0] = 99\n", "print(\"Original:\", original)\n", "print(\"Copy:\", separate_array)" ] }, { "cell_type": "markdown", "id": "two-dimensions", "metadata": {}, "source": [ "#### Two-dimensional arrays\n", "\n", "- **Point to one row and column**\n", "- **Which dimension are we averaging over?**\n", "\n", "Suppose we have three runs with four readings each. We'll store one run per row.\n", "An array with shape `(3, 4)` has three rows and four columns. `runs[1, 2]` selects\n", "row 1, column 2.\n", "\n", "For this layout, `axis=0` averages across runs, giving one result per time.\n", "`axis=1` averages across times, giving one result per run. Without an axis, `mean`\n", "averages every entry together." ] }, { "cell_type": "code", "execution_count": null, "id": "axis-code", "metadata": {}, "outputs": [], "source": [ "runs = np.array([\n", " [20.0, 21.0, 22.0, 23.0],\n", " [20.2, 21.1, 21.9, 23.2],\n", " [19.8, 20.9, 22.1, 22.8],\n", "])\n", "runs" ] }, { "cell_type": "markdown", "id": "axis-shape-cue", "metadata": {}, "source": [ "- **Rows first. Columns second.**" ] }, { "cell_type": "code", "execution_count": null, "id": "axis-shape", "metadata": {}, "outputs": [], "source": [ "runs.shape" ] }, { "cell_type": "markdown", "id": "axis-entry-cue", "metadata": {}, "source": [ "- **Find row 1, column 2.**" ] }, { "cell_type": "code", "execution_count": null, "id": "axis-entry", "metadata": {}, "outputs": [], "source": [ "runs[1, 2]" ] }, { "cell_type": "markdown", "id": "axis-zero-cue", "metadata": {}, "source": [ "- **Average down the rows. Four results.**" ] }, { "cell_type": "code", "execution_count": null, "id": "axis-zero", "metadata": {}, "outputs": [], "source": [ "np.mean(runs, axis=0)" ] }, { "cell_type": "markdown", "id": "axis-one-cue", "metadata": {}, "source": [ "- **Average across columns. Three results.**" ] }, { "cell_type": "code", "execution_count": null, "id": "axis-one", "metadata": {}, "outputs": [], "source": [ "np.mean(runs, axis=1)" ] }, { "cell_type": "markdown", "id": "axis-try", "metadata": {}, "source": [ "- **Predict each result’s length**\n", "- **A colon selects every entry**\n", "\n", "Print the first row with `runs[0, :]`, then the first column with `runs[:, 0]`.\n", "The colon selects everything along that dimension. Check their lengths against the shape." ] }, { "cell_type": "markdown", "id": "plotting", "metadata": {}, "source": [ "### Matplotlib\n", "\n", "- **One marker per pair of values**\n", "- **Label both axes with units**\n", "\n", "Let's plot the temperature data. `plt.subplots` returns a figure and an axes object.\n", "The figure is the whole image; the axes is the plot we're drawing on.\n", "\n", "`ax.plot(x, y, \"o\")` draws a marker for each pair of values. Both arrays need the same\n", "length. The labels tell us what the numbers mean and which units we're using." ] }, { "cell_type": "code", "execution_count": null, "id": "first-plot", "metadata": {}, "outputs": [], "source": [ "fig_data, ax_data = plt.subplots(figsize=(6, 4), constrained_layout=True)\n", "ax_data.plot(time_min, temperature_c, \"o\", label=\"Readings\")\n", "ax_data.set_xlabel(\"Time (min)\")\n", "ax_data.set_ylabel(\"Temperature (°C)\")\n", "ax_data.set_title(\"Temperature readings\")\n", "ax_data.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "plot-try", "metadata": {}, "source": [ "- **Connecting points does not fit them**\n", "- **Two series, same axes**\n", "\n", "Change `\"o\"` to `\"o-\"` and run the cell again. What changed? The line connects the\n", "points; it doesn't calculate a fit.\n", "\n", "Try `color=\"tab:orange\"` in `ax_data.plot(...)`, or change the figure size.\n", "To put two series on the same plot, call `plot` twice on the same axes before `plt.show()`." ] }, { "cell_type": "markdown", "id": "functions-arrays", "metadata": {}, "source": [ "#### Plotting a function\n", "\n", "- **Pass an array into our function**\n", "- **More x values, more plotted points**\n", "\n", "Our functions can accept arrays too, as long as the operations inside work on arrays.\n", "Here's a line, $y=mx+b$. `slope` and `intercept` are inputs, so we can change them when\n", "we call it. A denser grid gives us more points to draw the line with." ] }, { "cell_type": "code", "execution_count": null, "id": "line-function", "metadata": {}, "outputs": [], "source": [ "def line(x, slope, intercept):\n", " return slope * x + intercept" ] }, { "cell_type": "markdown", "id": "line-grid-cue", "metadata": {}, "source": [ "- **Choose where to evaluate the function.**" ] }, { "cell_type": "code", "execution_count": null, "id": "line-grid", "metadata": {}, "outputs": [], "source": [ "time_dense = np.linspace(0, 5, 101)" ] }, { "cell_type": "markdown", "id": "line-plot-cue", "metadata": {}, "source": [ "- **Draw our guess over the data.**" ] }, { "cell_type": "code", "execution_count": null, "id": "line-plot", "metadata": {}, "outputs": [], "source": [ "fig_guess, ax_guess = plt.subplots(figsize=(6, 4), constrained_layout=True)\n", "ax_guess.plot(time_min, temperature_c, \"o\", label=\"Readings\")\n", "ax_guess.plot(time_dense, line(time_dense, 0.8, 20.0), label=\"Line we chose\")\n", "ax_guess.set_xlabel(\"Time (min)\")\n", "ax_guess.set_ylabel(\"Temperature (°C)\")\n", "ax_guess.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "line-try", "metadata": {}, "source": [ "- **Change slope, then intercept**\n", "- **Watch what each parameter changes**\n", "\n", "In the plotting cell above, change the slope and intercept to get the line closer to the points. Changing the slope\n", "tilts the line; changing the intercept shifts it up or down.\n", "\n", "Next we'll have SciPy choose the parameters from the data." ] }, { "cell_type": "markdown", "id": "scipy-fit", "metadata": {}, "source": [ "### SciPy\n", "\n", "- **Give SciPy the function itself**\n", "- **It chooses the slope and intercept**\n", "\n", "SciPy provides routines for tasks such as fitting, integration, and solving equations.\n", "We'll try two of them. `from scipy.optimize import curve_fit` imports one function,\n", "so we can call it as `curve_fit(...)`.\n", "\n", "`curve_fit` takes a function, x data, and y data. Here it chooses the slope and intercept\n", "that minimize the sum of squared differences between the line and the readings.\n", "Pass `line`, not `line(...)`: SciPy will call the function with different parameters." ] }, { "cell_type": "code", "execution_count": null, "id": "fit-code", "metadata": {}, "outputs": [], "source": [ "from scipy.optimize import curve_fit\n", "\n", "parameters, covariance = curve_fit(line, time_min, temperature_c)" ] }, { "cell_type": "markdown", "id": "fit-parameters-cue", "metadata": {}, "source": [ "- **Read the slope and intercept.**" ] }, { "cell_type": "code", "execution_count": null, "id": "fit-parameters", "metadata": {}, "outputs": [], "source": [ "fitted_slope, fitted_intercept = parameters\n", "print(f\"Slope: {fitted_slope:.3f} °C/min\")\n", "print(f\"Intercept: {fitted_intercept:.3f} °C\")" ] }, { "cell_type": "markdown", "id": "fit-predictions-cue", "metadata": {}, "source": [ "- **Evaluate the fitted line at our times.**" ] }, { "cell_type": "code", "execution_count": null, "id": "fit-predictions", "metadata": {}, "outputs": [], "source": [ "line(time_min, fitted_slope, fitted_intercept)" ] }, { "cell_type": "markdown", "id": "fit-explain", "metadata": {}, "source": [ "- **Unpack parameters in the function’s order**\n", "- **Residual means data minus fitted value**\n", "\n", "`parameters` contains the fitted values in the order they appear after `x` in our function:\n", "slope, then intercept. The assignment to two names unpacks those two values.\n", "`covariance` is a separate estimate of the fitted parameters' covariance; we don't need\n", "it to draw the line.\n", "\n", "Plot the result and check the differences. Those differences are called **residuals**.\n", "An axes array lets us put two plots in the same figure." ] }, { "cell_type": "code", "execution_count": null, "id": "fit-residuals", "metadata": {}, "outputs": [], "source": [ "fitted_values = line(time_min, fitted_slope, fitted_intercept)\n", "residuals = temperature_c - fitted_values\n", "residuals" ] }, { "cell_type": "markdown", "id": "fit-plot-cue", "metadata": {}, "source": [ "- **Plot the fit. Look at the residuals.**" ] }, { "cell_type": "code", "execution_count": null, "id": "fit-plot", "metadata": {}, "outputs": [], "source": [ "fig_fit, axes = plt.subplots(2, 1, figsize=(6, 6), sharex=True, constrained_layout=True)\n", "axes[0].plot(time_min, temperature_c, \"o\", label=\"Readings\")\n", "axes[0].plot(time_dense, line(time_dense, fitted_slope, fitted_intercept), label=\"Fitted line\")\n", "axes[0].set_ylabel(\"Temperature (°C)\")\n", "axes[0].legend()\n", "\n", "axes[1].plot(time_min, residuals, \"o\")\n", "axes[1].axhline(0, color=\"0.5\", linestyle=\"--\")\n", "axes[1].set_xlabel(\"Time (min)\")\n", "axes[1].set_ylabel(\"Data − line (°C)\")\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "fit-try", "metadata": {}, "source": [ "- **Move one point; predict the fit**\n", "- **Restore the data and rerun**\n", "\n", "Increase the last temperature reading by 2 °C in the data cell. Rerun that cell,\n", "the fit, parameter unpacking, residual calculation, and this plot. Does the line move through the changed point, or does it\n", "compromise between all the points? Restore the data when you're done, then rerun the\n", "data, fit, parameter, residual, and plot cells so the figure agrees with the values you'll save.\n", "\n", "`sharex=True` makes the two panels use the same x axis limits. `axes[0]` is the top\n", "plot and `axes[1]` is the bottom one." ] }, { "cell_type": "markdown", "id": "integration", "metadata": {}, "source": [ "#### Integrating a function\n", "\n", "- **Check against an integral we know**\n", "- **Read both returned values**\n", "\n", "`scipy.integrate.quad` calculates a definite integral. For example, the area under\n", "$x^2$ from 0 to 1 is $1/3$. Let's check that numerically.\n", "\n", "Give `quad` the function and the two limits. It returns the integral and an estimate\n", "of its numerical error. That estimate doesn't check whether you supplied the right function." ] }, { "cell_type": "code", "execution_count": null, "id": "integral-function", "metadata": {}, "outputs": [], "source": [ "from scipy.integrate import quad\n", "\n", "def square(x):\n", " return x**2" ] }, { "cell_type": "markdown", "id": "integral-code-cue", "metadata": {}, "source": [ "- **Give it the function and two limits.**" ] }, { "cell_type": "code", "execution_count": null, "id": "integral-code", "metadata": {}, "outputs": [], "source": [ "area, error_estimate = quad(square, 0, 1)\n", "print(\"Integral:\", area)" ] }, { "cell_type": "markdown", "id": "integral-error-cue", "metadata": {}, "source": [ "- **Read the numerical error estimate.**" ] }, { "cell_type": "code", "execution_count": null, "id": "integral-error", "metadata": {}, "outputs": [], "source": [ "error_estimate" ] }, { "cell_type": "markdown", "id": "integral-check-cue", "metadata": {}, "source": [ "- **Check against a result we know.**" ] }, { "cell_type": "code", "execution_count": null, "id": "integral-check", "metadata": {}, "outputs": [], "source": [ "print(\"Expected:\", 1 / 3)\n", "print(\"Agreement:\", np.isclose(area, 1 / 3))" ] }, { "cell_type": "markdown", "id": "integral-try", "metadata": {}, "source": [ "- **Change the limit and expected answer**\n", "- **Use help to check arguments**\n", "\n", "Change the upper limit to 2 in the integration cell. Rerun it, then replace both\n", "`1 / 3` values in the check cell with `8 / 3` and run that cell.\n", "Then try another function whose\n", "integral you know. You can look up the arguments with `help(quad)` in a new cell." ] }, { "cell_type": "markdown", "id": "files", "metadata": {}, "source": [ "### Save a plot and a data file\n", "\n", "- **Save the figure and the numbers**\n", "- **Same filename replaces the old file**\n", "\n", "`savefig` writes a figure to disk. `np.savetxt` writes numbers, and `np.loadtxt` reads\n", "them back. Here `column_stack` puts the time and temperature arrays into two columns.\n", "\n", "These files go into the notebook's current working directory. Running the cell again\n", "replaces the files with these names." ] }, { "cell_type": "code", "execution_count": null, "id": "save-code", "metadata": {}, "outputs": [], "source": [ "fig_fit.savefig(\"temperature_fit.png\", dpi=150, bbox_inches=\"tight\")" ] }, { "cell_type": "markdown", "id": "save-table-cue", "metadata": {}, "source": [ "- **One column per variable. Write the CSV.**" ] }, { "cell_type": "code", "execution_count": null, "id": "save-table", "metadata": {}, "outputs": [], "source": [ "table = np.column_stack((time_min, temperature_c))\n", "np.savetxt(\"temperature.csv\", table, delimiter=\",\",\n", " header=\"time_min,temperature_c\", comments=\"\")" ] }, { "cell_type": "markdown", "id": "load-table-cue", "metadata": {}, "source": [ "- **Read the file back.**" ] }, { "cell_type": "code", "execution_count": null, "id": "load-table", "metadata": {}, "outputs": [], "source": [ "loaded = np.loadtxt(\"temperature.csv\", delimiter=\",\", skiprows=1)\n", "loaded" ] }, { "cell_type": "markdown", "id": "check-table-cue", "metadata": {}, "source": [ "- **Did the numbers survive the round trip?**" ] }, { "cell_type": "code", "execution_count": null, "id": "check-table", "metadata": {}, "outputs": [], "source": [ "np.allclose(loaded, table)" ] }, { "cell_type": "markdown", "id": "files-explain", "metadata": {}, "source": [ "- **Load it back; check the columns**\n", "- **Download files before leaving Colab**\n", "\n", "`delimiter=\",\"` separates the columns with commas. `skiprows=1` skips the header when\n", "reading the file. `loaded[:, 0]` gives the time column and `loaded[:, 1]` gives temperature.\n", "\n", "On DataHub, the files appear in the file browser on the left. Right-click a file to\n", "download it. In Colab, open the Files panel and download them there. Files created in\n", "the Colab runtime aren't automatically saved to Drive and disappear when that runtime is deleted." ] }, { "cell_type": "markdown", "id": "practice", "metadata": {}, "source": [ "### Try it with another dataset\n", "\n", "- **Build it from the earlier pieces**\n", "- **Use new names for this dataset**\n", "\n", "Use the arrays below to fit and plot a line. Write the code yourself; the earlier cells\n", "have the pieces you need.\n", "\n", "1. Print the array shapes and the mean temperature.\n", "2. Plot the readings with axis labels and units.\n", "3. Fit `line` with `curve_fit`, then add the fitted line to your plot.\n", "4. Print the fitted slope and intercept. Save the plot with a new filename.\n", "\n", "Keep separate names for this dataset so the earlier plots still use their original data." ] }, { "cell_type": "code", "execution_count": null, "id": "practice-data", "metadata": {}, "outputs": [], "source": [ "new_time_min = np.array([0, 2, 4, 6, 8], dtype=float)\n", "new_temperature_c = np.array([18.1, 18.9, 20.2, 20.8, 22.1])" ] }, { "cell_type": "code", "execution_count": null, "id": "practice-code", "metadata": {}, "outputs": [], "source": [ "# Add your analysis here." ] }, { "cell_type": "markdown", "id": "finish", "metadata": {}, "source": [ "- **Restart and run everything**\n", "- **Save and download the notebook**\n", "\n", "Save your edits, restart the kernel, and run the whole notebook from the top.\n", "In JupyterLab, use **Kernel → Restart Kernel and Run All Cells**. In Colab, restart\n", "the session from **Runtime**, then run all cells.\n", "\n", "Fix any missing definitions, save again, and download the `.ipynb`. In Colab, use the\n", "File menu; in JupyterLab, right-click the notebook in the file browser and choose Download.\n", "This gives you a copy with the code, notes, and latest outputs together.\n", "\n", "For syntax you don't remember: [NumPy](https://numpy.org/doc/stable/user/absolute_beginners.html),\n", "[Matplotlib](https://matplotlib.org/stable/tutorials/pyplot.html),\n", "[curve_fit](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html),\n", "[quad](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html),\n", "and [notebook package installation](https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-pip)." ] } ], "metadata": { "colab": { "name": "lab02.ipynb", "provenance": [] }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.11.9" }, "title": "Lab 02: NumPy, SciPy, and Matplotlib" }, "nbformat": 4, "nbformat_minor": 5 }