{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"# NumPy Broadcasting\n",
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Overview\n",
"Before we begin, broadcasting is a valuable part of the power that NumPy provides. However, there's no looking past the fact that broadcasting can be conceptually difficult to digest. This information can be helpful and very powerful, but we also suggest moving on to take a look at some of the label-based corners of the Python ecosystem, namely [Pandas](../pandas) and [Xarray](../xarray) for the ways that they make some of these concepts simpler or easier to use for real-world data.\n",
"\n",
"1. An introduction to broadcasting\n",
"1. Avoiding loops with vectorization"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prerequisites\n",
"\n",
"| Concepts | Importance | Notes |\n",
"| --- | --- | --- |\n",
"| [NumPy Basics](numpy-basics) | Necessary | |\n",
"| [Intermediate NumPy](intermediate-numpy) | Helpful | |\n",
"| [Conceptual guide to broadcasting](https://numpy.org/doc/stable/user/theory.broadcasting.html#array-broadcasting-in-numpy) | Helpful | |\n",
"\n",
"* **Time to learn**: 30 minutes\n",
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Imports"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Using broadcasting to implicitly loop over data"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### What is broadcasting?\n",
"Broadcasting is a useful NumPy tool that allows us to perform operations between arrays with different shapes, provided that they are compatible with each other in certain ways. To start, we can create an array below and add 5 to it:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"a = np.array([10, 20, 30, 40])\n",
"a + 5"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This works even though 5 is not an array; it works like we would expect, adding 5 to each of the elements in `a`. This also works if 5 is an array:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"b = np.array([5])\n",
"a + b"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This takes the single element in `b` and adds it to each of the elements in `a`. This won't work for just any `b`, though; for instance, the following:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"raises-exception"
]
},
"outputs": [],
"source": [
"b = np.array([5, 6, 7])\n",
"a + b"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"won't work. It does work if `a` and `b` are the same shape:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"b = np.array([5, 5, 10, 10])\n",
"a + b"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What if what we really want is pairwise addition of a, b? Without broadcasting, we could accomplish this by looping:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"b = np.array([1, 2, 3, 4, 5])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"result = np.empty((5, 4), dtype=np.int32)\n",
"for row, valb in enumerate(b):\n",
" for col, vala in enumerate(a):\n",
" result[row, col] = vala + valb\n",
"result"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also do this by manually repeating the arrays to the proper shape for the result, using `np.tile`. This avoids the need to manually loop:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"aa = np.tile(a, (5, 1))\n",
"aa"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Turn b into a column array, then tile it\n",
"bb = np.tile(b.reshape(5, 1), (1, 4))\n",
"bb"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"aa + bb"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Giving NumPy room for broadcasting\n",
"We can also do this using broadcasting, which is where NumPy implicitly repeats the array without using additional memory. With broadcasting, NumPy takes care of repeating for you, provided dimensions are \"compatible\". This works as:\n",
"1. Check the number of dimensions of the arrays. If they are different, *prepend* size one dimensions\n",
"2. Check if each of the dimensions are compatible: either the same size, or one of them is 1."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a.shape"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"b.shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Right now, they have the same number of dimensions, 1, but that dimension is incompatible. We can solve this by appending a dimension using `np.newaxis` when indexing:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"bb = b[:, np.newaxis]\n",
"bb.shape"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a + bb"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"(a + bb).shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This can be written more directly in one line:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a + b[:, np.newaxis]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Extending to higher dimensions\n",
"This also works for higher dimensions. `x`, `y`, and `z` are here different dimensions, and we can broadcast to perform $x^2 + y^2 + z^2$,"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = np.array([1, 2])\n",
"y = np.array([3, 4, 5])\n",
"z = np.array([6, 7, 8, 9])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First, let's extend `x` (and square it) by one dimension, onto which we can broadcast the vector `y ** 2`,"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d_2d = x[:, np.newaxis] ** 2 + y**2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d_2d.shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and then further extend this new 2-D array by one more dimension before using broadcasting to add `z ** 2` across all other dimensions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d_3d = d_2d[..., np.newaxis] + z**2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d_3d.shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Or in one line:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"h = x[:, np.newaxis, np.newaxis] ** 2 + y[np.newaxis, :, np.newaxis] ** 2 + z**2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can see this one-line result has the same shape and same values as the other multi-step calculation."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"h.shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and we can confirm that the results here are identical,"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.all(h == d_3d)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Broadcasting is often useful when you want to do calculations with coordinate values, which are often given as 1-D arrays corresponding to positions along a particular array dimension. For example, taking range and azimuth values for radar data (1-D separable polar coordinates) and converting to x,y pairs relative to the radar location."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Given the 3-D temperature field and 1-D pressure coordinates below, let's calculate $T * exp(P / 1000)$. We will need to use broadcasting to make the arrays compatible!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pressure = np.array([1000, 850, 500, 300])\n",
"temps = np.linspace(20, 30, 24).reshape(4, 3, 2)\n",
"pressure.shape, temps.shape"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pressure[:, np.newaxis, np.newaxis].shape"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"temps * np.exp(pressure[:, np.newaxis, np.newaxis] / 1000)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Vectorize calculations to avoid explicit loops"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When working with arrays of data, loops over the individual array elements is a fact of life. However, for improved runtime performance, it is important to avoid performing these loops in Python as much as possible, and let NumPy handle the looping for you. Avoiding these loops frequently, but not always, results in shorter and clearer code as well."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Look ahead/behind\n",
"\n",
"One common pattern for vectorizing is in converting loops that work over the current point as well as the previous and/or next point. This comes up when doing finite-difference calculations, e.g. approximating derivatives,\n",
"\n",
"\\begin{equation*}\n",
"f'(x) = f_{i+1} - f_{i}\n",
"\\end{equation*}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = np.linspace(0, 20, 6)\n",
"a"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can calculate the forward difference for this array with a manual loop as:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d = np.zeros(a.size - 1)\n",
"for i in range(len(a) - 1):\n",
" d[i] = a[i + 1] - a[i]\n",
"d"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It would be nice to express this calculation without a loop, if possible. To see how to go about this, let's consider the values that are involved in calculating `d[i]`, `a[i+1]` and `a[i]`. The values over the loop iterations are:\n",
"\n",
"| i | a[i+1] | a[i] |\n",
"| --- | ---- | ---- |\n",
"| 0 | 4 | 0 |\n",
"| 1 | 8 | 4 |\n",
"| 2 | 12 | 8 |\n",
"| 3 | 16 | 12 |\n",
"| 4 | 20 | 16 |\n",
"\n",
"We can express the series of values for `a[i+1]` then as:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a[1:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and `a[i]` as:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a[:-1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This means that we can express the forward difference as:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a[1:] - a[:-1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It should be noted that using slices in this way returns only a **view** on the original array. This means not only can you use the slices to modify the original data (even accidentally), but that this is also a quick operation that does not involve a copy and does not bloat memory usage."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 2nd Derivative\n",
" \n",
"A finite difference estimate of the 2nd derivative is given by:\n",
"\n",
"\\begin{equation*}\n",
"f''(x) = 2\n",
"f_i - f_{i+1} - f_{i-1}\n",
"\\end{equation*}\n",
"\n",
"(we're ignoring $\\Delta x$ here)\n",
"\n",
"Let's write some vectorized code to calculate this finite difference for `a` (using slices.) What values should we be expecting to get for the 2nd derivative?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"2 * a[1:-1] - a[:-2] - a[2:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Blocking\n",
"\n",
"Another application where vectorization comes into play to make operations more efficient is when operating on blocks of data. Let's start by creating some temperature data (rounding to make it easier to see/recognize the values)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"temps = np.round(20 + np.random.randn(10) * 5, 1)\n",
"temps"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's start by writing a loop to take a 3-point running mean of the data. We'll do this by iterating over all points in the array and average the 3 points centered on that point. We'll simplify the problem by avoiding dealing with the cases at the edges of the array."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"avg = np.zeros_like(temps)\n",
"for i in range(1, len(temps) - 1):\n",
" sub = temps[i - 1 : i + 2]\n",
" avg[i] = sub.mean()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"avg"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As with the case of doing finite differences, we can express this using slices of the original array:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# i - 1 i i + 1\n",
"(temps[:-2] + temps[1:-1] + temps[2:]) / 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another option to solve this is not using slicing but by using a powerful NumPy tool: `as_strided`. This tool can result in some odd behavior, so take care when using--the trade-off is that this can be used to do some powerful operations. What we're doing here is altering how NumPy is interpreting the values in the memory that underpins the array. So for this array:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"temps"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"we can create a view of the array with a new, bigger shape, with rows made up of overlapping values. We do this by specifying a new shape of 8x3, one row for each of the length 3 blocks we can fit in the original 1-D array of data. We then use the `strides` argument to control how NumPy walks between items in each dimension. The last item in the strides tuple is just as normal--it says that the number of bytes to walk between items is just the size of an item. (Increasing this would skip items.) The first item says that when we go to a new, in this case row, only advance the size of a single item. This is what gives us overlapping rows."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"block_size = 3\n",
"new_shape = (len(temps) - block_size + 1, block_size)\n",
"bytes_per_item = temps.dtype.itemsize\n",
"temps_strided = np.lib.stride_tricks.as_strided(\n",
" temps, shape=new_shape, strides=(bytes_per_item, bytes_per_item)\n",
")\n",
"temps_strided"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that we have this view of the array with the rows representing overlapping blocks, we can operate across the rows with `mean` and the `axis=-1` argument to get our running average:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"temps_strided.mean(axis=-1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It should be noted that there are no copies going on here, so if we change a value at a single indexed location, the change actually shows up in multiple locations:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"temps_strided[0, 2] = 2000\n",
"temps_strided"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Finding the difference between min and max\n",
"\n",
"Another operation that crops up when slicing and dicing data is trying to identify a set of indexes, along a particular axis, within a larger multidimensional array. For instance, say we have a 3-D array of temperatures, and want to identify the location of the $-10^oC$ isotherm within each column:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pressure = np.linspace(1000, 100, 25)\n",
"temps = np.random.randn(25, 30, 40) * 3 + np.linspace(25, -100, 25).reshape(-1, 1, 1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"NumPy has the function `argmin()` which returns the index of the minimum value. We can use this to find the minimum absolute difference between the value and -10:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Using axis=0 to tell it to operate along the pressure dimension\n",
"inds = np.argmin(np.abs(temps - -10), axis=0)\n",
"inds"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"inds.shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Great! We have an array representing the index of the point closest to $-10^oC$ in each column of data. We could use this to look up into our pressure coordinates to find the pressure level for each column:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pressure[inds]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"How about using that to find the actual temperature value that was closest?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"temps[inds, :, :].shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Unfortunately, this replaced the pressure dimension (size 25) with the shape of our index array (30 x 40), giving us a 30 x 40 x 30 x 40 array (imagine what would have happened with real data!). One solution here would be to loop:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"output = np.empty(inds.shape, dtype=temps.dtype)\n",
"for (i, j), val in np.ndenumerate(inds):\n",
" output[i, j] = temps[val, i, j]\n",
"output"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Of course, what we really want to do is avoid the explicit loop. Let's temporarily simplify the problem to a single dimension. If we have a 1-D array, we can pass a 1-D array of indices (a full) range, and get back the same as the original data array:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pressure[np.arange(pressure.size)]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.all(pressure[np.arange(pressure.size)] == pressure)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can use this to select all the indices on the other dimensions of our temperature array. We will also need to use the magic of broadcasting to combine arrays of indices across dimensions."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now let's consider a vectorized solution:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"y_inds = np.arange(temps.shape[1])[:, np.newaxis]\n",
"x_inds = np.arange(temps.shape[2])\n",
"temps[inds, y_inds, x_inds]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's say we want to find the relative humidity at the $-10^oC$ isotherm"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"np.all(output == temps[inds, y_inds, x_inds])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Summary\n",
"We've previewed some advanced NumPy capabilities with a focus on _vectorization_, or using clever broadcasting and windows of our data to enhance the speed and readability of our calculations. Doing so can reduce explicit construction of loops in your code and keep calculations running quickly!\n",
"\n",
"### What's next\n",
"This is an advanced NumPy topic, and important to designing your own calculations in a way for them to be as scalable and quick as possible. Please check out some of the following links to explore this topic further. We also suggest diving into label-based indexing and subsetting with [Pandas](../pandas) and [Xarray](../xarray), where some of this broadcasting can be simplified or have added context."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Resources and references\n",
"* [NumPy Broadcasting Documentation](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)"
]
}
],
"metadata": {
"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.10.4"
}
},
"nbformat": 4,
"nbformat_minor": 4
}