Week 12: Numpy and Matplotlib

Week 12: In-Class#

Demo#

Demo 12.1: Smooth Curve#

A closed curve is represented using a sequence of 2D points \(\mathbf{p}_i\), \(i = 1, . . . , n\) connected by line segments, where the last point is connected to the first point. The curve is smoothed by moving every curve point \(\mathbf{p}_i\) in the direction of the average of its two neighbors. The coordinates for the smoothed curve are computed as

\[ \mathbf{s}_i = (1-\alpha)\mathbf{p}_i + \alpha \frac{\mathbf{p}_{i-1} + \mathbf{p}_{i+1}}{2} \]

for \(i = 2, . . . , n−1\). For the first and last points in the curve, the smoothing is done similarly, taking into account that the curve is closed (i.e., \(\mathbf{p}_n\) is a neighbor of \(\mathbf{p}_1\), and \(\mathbf{p}_1\) is a neighbor of \(\mathbf{p}_n\)).

The parameter \(\alpha\) controls the strength of the smoothing and is usually between \(0.1\) and \(0.5\).

An example of the original and smoothed curves is shown below for \(\alpha = 0.5\).

Original Smoothed

Problem Analysis

Consider a curve with the points

\[\begin{split} \mathbf{P} = \begin{bmatrix} \mathbf{p}_1 & \mathbf{p}_2 & \dots & \mathbf{p}_{10} \end{bmatrix} = \begin{bmatrix} 24 & 40 & 36 & 44 & 28 & 18 & 12 & 0 & 8 & 4 \\ 12 & 16 & 8 & 4 & 0 & 4 & 0 & 4 & 12 & 16 \end{bmatrix}, \end{split}\]

and the smoothing parameter \(\alpha = 0.5\).

What are the coordinates of \(\mathbf{s}_1\) and \(\mathbf{s}_2\)?

\(\mathbf{s}_1\)

\(\mathbf{s}_2\)

Coding Practice#

Code 12.2: Powers of 2#

In Code 6.4: Powers of 2 you wrote code which created a list with the first n powers of 2. Let’s write code to do the same, but in a single line, using NumPy.

You should write code that, given an integer n, computes a NumPy array of the first n powers of 2. For example, for n = 4 the array should contain the values \(2^1\), \(2^2\), \(2^3\), \(2^4\), so the array should be [2, 4, 8, 16]. Test your code with n = 1, n = 4 and n = 10.

Code 12.3: Months with More than d Days#

You are given the following NumPy arrays.

months = np.array(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])
days = np.array([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31])

You should write code that, given a number d, creates a new NumPy array, months_with_more_than_d_days, containing the names of all months that have more than d days. For example, for d = 30, the array should contain:

['Jan' 'Mar' 'May' 'Jul' 'Aug' 'Oct' 'Dec']

Also try it for d = 31 and confirm that the array is empty.

Code 12.4: Math Functions#

We want to plot the function:

\[ f(x) = |1/2-x^3|-\sqrt{\sin(x)+e^x} \]

on n equally spaced points in the interval \([0,1]\).

To solve the problem, you should:

  • Define an integer n, for example n = 100.

  • Create a NumPy array x containing linearly spaced points between \(0\) and \(1\) (including both \(0\) and \(1\)).

  • Write an expression for the function \(f(x)\), and call it y.

  • Use Matplotlib to plot the line consisting of the points \((x, y)\). Your plot should look like the one shown below.

../_images/2fcb27f51f721040efcde9674bafb40e30ba79c926fcab2ab105b6ebc76d0085.png

Code 12.5: Counting Integers#

In the previous weeks, you have been counting how often different letters and numbers appear in lists. In this exercise, you will combine functions and NumPy to calculate the frequency of a specific integer in a NumPy array.

Start by making a function count_number(array, integer) with two inputs. The first input array should be a NumPy array of integers and the second input integer should be an integer. Your function count_number should count the number of times integer appears in array.

Test the function by defining array = np.array([3, 5, 2, 3, 3, 5, 6, 9]), and checking that count_number(array, integer) gives the correct output for different integers.

Make another function, array_frequencies, that counts the number of times all integers between 0 and 9 occur in the array. The function should take as input a NumPy array of integers between 0 and 9, and output a NumPy array of integers of length 10 with the frequencies of each number between 0 and 9 in the input.

Check your function by printing array_frequencies(array). You should get

[0 0 1 3 0 2 1 0 0 1]

To see how to solve this problem using a specific NumPy function, take a look at Advanced 12.4: Counting Integers.

Problem Solving#

Problem 12.6: Is the CPR Number Valid?#

Have you ever wondered how websites know if the CPR number (the Danish civil registration number) is valid or not? In this exercise, you will find out how to do this yourself!

The last digit of the CPR number is a check digit. It is chosen such that the CPR number passes the test described below, which can be used to check the validity of a CPR number.

Let’s say you are given the CPR number \(1111111111\) and you want to know whether it is valid. Here is how you can check it:

  • Multiply each digit of the CPR number by the corresponding digit of the control number \(4327654321\), and add the results together. This is the dot product of the CPR digits and the control digits. In our example, this gives

\[ \begin{bmatrix} 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \end{bmatrix} \cdot \begin{bmatrix} 4 & 3 & 2 & 7 & 6 & 5 & 4 & 3 & 2 & 1 \end{bmatrix} = 37 \]
  • Check whether the dot product is divisible by \(11\). If it is, the CPR number is valid. In our example, \(37\) is not divisible by \(11\), so \(1111111111\) is not a valid CPR number.

If the last digit had been \(8\) instead of \(1\), the dot product would have been \(44 = 4\cdot 11\), so \(1111111118\) is a valid CPR number. That’s it!

Write a function that takes a NumPy array of CPR digits as input and returns a boolean value indicating whether the CPR number is valid or not.

cpr_check.py

cpr_check(array)

Checks if a CPR number is valid or not

Parameters:

  • array

numpy.ndarray

A numpy array of shape (10,) containing the digits of a CPR number

Returns:

  • bool

A boolean variable which is True if the CPR is valid

You can test your function by verifying the following (randomly chosen) cases:

Problem 12.7: Growth Curve of Bacteria#

Download the file bacteria.npy. The file contains the results of 160 experiments, where the bacterial growth was measured every 10 minutes for a total of 120 minutes.

Place the file in your current working directory. If you are unsure what your current working directory is, you can go back to Prep 9.1: Current Working Directory (CWD).

Load the data in the file using data = np.load('bacteria.npy').

Each row, data[i, :], records the bacterial growth for one experiment. Each column, data[:, j], shows the bacterial growth for all 160 experiments at the \(j\)’th measurement time.

Calculate the mean \(\mu\) and standard deviation \(\sigma\) of the bacterial growth at each time step. You can find the mean and standard deviation of a NumPy array with np.mean() and np.std().

Calculate the lower and upper range at each time step as \(\text{r}_\mathrm{lower} = \mu - 2\sigma\) and \(\text{r}_\mathrm{upper} = \mu + 2\sigma\).

Plot the bacterial growth from all the experiments in the same plot using a for-loop. The horizontal axis should have the label Time in minutes.

In the same plot, plot the mean bacterial growth, and the lower and upper range, using different colors and line styles.

Change the plot options so that the plot looks like the one shown below.

../_images/85bbc067ea5c9a27778acc312b6c001d242da5d03639d5b082fc70773879210a.png

Problem 12.8: Flowering Plants#

The information about the flowering season for the plants in a tropical greenhouse is stored in an \(n \times 2\) matrix of integer numbers between 0 and 12. Each row in this matrix is a pair of numbers representing one plant. The first number is the month of the year when the plant starts flowering, and the second number is the month when the plant stops flowering. For example, a pair \((11, 2)\) represents a plant with flowering season starting in November (month 11) and ending in February (month 2). If a plant flowers all year round, it is represented with \((0, 0)\). A plant represented with \((7, 7)\) has a short flowering season which both starts and ends in July.

Create a function which takes as input a 2D NumPy array (a matrix) of greenhouse plants \(G\), and a month \(m\) given by a number between \(1\) and \(12\). The function should return the total number of plants which flower in month \(m\). Plants which start or stop flowering in month \(m\) should be counted as flowering in month \(m\).

flowering_plants.py

flowering_plants(G, m)

Compute the number of plants flowering in month m.

Parameters:

  • G

numpy.ndarray

A NumPy array of shape (n, 2) of numbers between 0 and 12 representing a flowering season of plants.

  • m

int

Integer between 1 and 12 representing a month.

Returns:

  • int

Number of plants flowering in the given month.

As an example, consider the input

\[\begin{split} G = \begin{bmatrix} 5 & 9 \\ 9 & 11 \\ 12 & 6 \\ 0 & 0 \end{bmatrix} \quad \text{and} \quad m = 6. \end{split}\]

The first plant has a flowering season represented by \((5, 9)\), which corresponds to months 5, 6, 7, 8, and 9, so this plant flowers in June. The second plant is represented by \((9, 11)\), which corresponds to months 9, 10, and 11, so it does not flower in June. The third plant is \((12, 6)\), corresponding to months 12, 1, 2, 3, 4, 5, and 6, so it flowers in June. The last plant is \((0, 0)\), and it flowers all year round, also in June.

In total, there are 3 plants flowering in June. The function should return \(\mathbf{3}\).

Solutions to Demo Tasks