Setup cell that imports numpy.
#| exercise: himmelblau_function
#| setup: true
import numpy as npThe Quarto Live authoring guide shows how to embed interactive computation directly in a web page. This example uses Python exercises to demonstrate progressively richer forms of scaffolding and automated feedback.
Unlike a full notebook or REPL, the code cells sit alongside the explanation and can be tailored to one specific learning task.
It can often be illustrative to have students implement some equation as a function and then exploring that function in some ways. Consider for example the function,
\[ f(x) = (x^2 + y - 11)^2 + (x + y^2 - 7)^2. \] This is Himmelblau’s function1. A lot can go wrong in the implementation of this function and subsequent exercises may become difficult if it’s not done correctly - we can use interactive Python cells that give learners immediate feedback to alleviate that.
This example uses the following code:
#| exercise: himmelblau_function
#| setup: true
import numpy as np#| exercise: himmelblau_function
def himmelblau(x, y) -> float:
"""
Implements Himmelblau's function.
"""
result = ______
return result#| exercise: himmelblau_function
def correct_himmelblau(x, y):
return (x**2 + y - 11)**2 + (x + y**2 - 7)**2
test_points = [(3.0, 2.0), (-2.805118, 3.131312), (0, 0)]
correct = True
failures = []
for test_point in test_points:
student_eval = himmelblau(*test_point)
correct_eval = correct_himmelblau(*test_point)
if not np.isclose(student_eval, correct_eval):
correct = False
failures.append((test_point, correct_eval, student_eval))
if correct:
feedback = {
"correct": True,
"message": "That is correct!"
}
else:
lines = ["That is not correct. Please try again."]
for point, expected, student in failures:
lines.append(
f"At ({point[0]}, {point[1]}), the function should return "
f"{expected:.3f}; yours returns {student:.3f}."
)
feedback = {
"correct": False,
"message": "<br>".join(lines)
}
feedbackNote that all three cells have the same #| exercise: himmelblau_function metadata line, with the #| setup and #| check cells been additional identifiers for the setup and feedback cells.
We could build further on the previous exercise by asking students to use scipy.optimize.minimize to find a local minimum of Himmelblau’s function.
The cell below expects local_minimum to be set to one of the four minima of the function.
Use the minimize-function to find a minimum, the syntax is
result = minimize(f, [0, 0])Where the first argument f is the function to be minimized and second are the initial starting coordinates.
The function returns a OptimizeResult-object that stores information about the found solution and about the optimization process. The coordinates can be extracted like so
local_minimum = result.xThe exercise can be solved with
local_minimum = minimize(himmelblau, [0, 0]).xTry varying the initial coordinates.
This again uses a setup, exercise and check cell. These are shown below
#| exercise: himmelblau_opt
#| setup: true
import numpy as np
from scipy.optimize import minimize
def himmelblau(x):
return (x[0]**2 + x[1] - 11)**2 + (x[0] + x[1]**2 - 7)**2minimize.
#| exercise: himmelblau_opt
# Use the minimize-function to find a local minimum of the Himmelblau function
local_minimum = _______#| exercise: himmelblau_opt
#| check: true
local_minima = [
(3.0, 2.0),
(-2.805118, 3.131312),
(-3.779310, -3.283186),
(3.584428, -1.848126)
]
match_found = False
for (lx, ly) in local_minima:
if np.isclose(lx, local_minimum[0]) and np.isclose(ly, local_minimum[1]):
match_found = True
break
if match_found:
feedback = {"correct": True, "message": f"That's correct! ({lx}, {ly}) is a minimum of Himmelblau's function"}
else:
feedback = {"correct": False, "message": "That's not quite right."}
feedbackAddittionally the hints and solutions for this exercise are defined by blocks like so
::: {.hint exercise="himmelblau_opt"}
::: {.callout-tip collapse="false"}
## Hint 1
Use the `minimize`-function to find a minimum, the syntax is
```python
result = minimize(f, [0, 0])
```
Where the first argument `f` is the function to be minimized and second are
the initial starting coordinates.
The function returns a `OptimizeResult`-object that stores information about the found solution and about the optimization process. The coordinates can be extracted like so
```python
local_minimum = result.x
```
:::
:::::: { .solution exercise="himmelblau_opt" }
::: {.callout-tip collapse="false"}
## Solution
The exercise can be solved with
```python
local_minimum = minimize(himmelblau, [0, 0]).x
```
Try varying the initial coordinates.
:::
:::The previous exercises evaluated Himmelblau’s function and located one of its minima. A plot can make the shape of the function, and the presence of several minima, easier to understand. In this exercise, students create a filled contour plot over the interval \(-5 \leq x \leq 5\) and \(-5 \leq y \leq 5\).
Complete the code to evaluate the function on a grid and create the plot. The finished figure should include a colour bar, the title Himmelblau's function, and axes labelled x and y.
The setup, exercise, and check cells used for this example are shown below.
#| exercise: himmelblau_plot
#| setup: true
import numpy as np
import matplotlib.pyplot as plt
def himmelblau(x, y):
return (x**2 + y - 11)**2 + (x + y**2 - 7)**2#| exercise: himmelblau_plot
x = np.linspace(-5, 5, 200)
y = np.linspace(-5, 5, 200)
X, Y = np.meshgrid(______, ______)
Z = himmelblau(______, ______)
fig, ax = plt.subplots()
contours = ax.contourf(______, ______, ______, levels=30)
fig.colorbar(contours, ax=ax, label="f(x, y)")
ax.set_xlabel(______)
ax.set_ylabel(______)
ax.set_title(______)
plt.show()#| exercise: himmelblau_plot
#| check: true
checks = []
try:
grid_is_correct = (
isinstance(X, np.ndarray)
and isinstance(Y, np.ndarray)
and X.shape == Y.shape == (200, 200)
and np.isclose(X.min(), -5)
and np.isclose(X.max(), 5)
and np.isclose(Y.min(), -5)
and np.isclose(Y.max(), 5)
)
except (NameError, AttributeError, TypeError):
grid_is_correct = False
checks.append((grid_is_correct, "Create the required X and Y mesh grid."))
try:
expected_Z = himmelblau(X, Y)
values_are_correct = (
isinstance(Z, np.ndarray)
and Z.shape == expected_Z.shape
and np.allclose(Z, expected_Z)
)
except (NameError, AttributeError, TypeError, ValueError):
values_are_correct = False
checks.append((values_are_correct, "Evaluate the function on the grid."))
try:
contour_is_present = contours.axes is ax and len(ax.collections) > 0
except (NameError, AttributeError, TypeError):
contour_is_present = False
checks.append((contour_is_present, "Create a filled contour plot on ax."))
try:
colour_bar_is_present = len(fig.axes) >= 2
except (NameError, AttributeError, TypeError):
colour_bar_is_present = False
checks.append((colour_bar_is_present, "Add a colour bar to the figure."))
try:
x_label_is_correct = ax.get_xlabel().strip().lower() == "x"
except (NameError, AttributeError):
x_label_is_correct = False
checks.append((x_label_is_correct, "Label the horizontal axis x."))
try:
y_label_is_correct = ax.get_ylabel().strip().lower() == "y"
except (NameError, AttributeError):
y_label_is_correct = False
checks.append((y_label_is_correct, "Label the vertical axis y."))
try:
title_is_correct = ax.get_title().strip() == "Himmelblau's function"
except (NameError, AttributeError):
title_is_correct = False
checks.append((title_is_correct, "Set the requested title."))
failed_checks = [message for passed, message in checks if not passed]
if not failed_checks:
feedback = {
"correct": True,
"message": "That is correct! The plot contains the requested data and labels."
}
else:
feedback = {
"correct": False,
"message": "Please revise the following:<br>" + "<br>".join(
f"- {message}" for message in failed_checks
)
}
feedbackThe checker tests the numerical grid and function values as well as the visible parts of the figure. In particular, it verifies that the learner created a filled contour plot, added a colour bar, labelled both axes, and supplied the requested title. Reporting each failed check separately makes the feedback specific without revealing the completed exercise code.
This is a function used for testing optimization algortihms.↩︎