130 KiB
Executable file
130 KiB
Executable file
None
<html>
<head>
</head>
Q1 Draw a figure as above with, additionally, a blue line between each point on
Q2 write a function called
Q3 compute the distance between each point on
Q4 make a plot of the bee track parameter
Q5 Using
Q6 What is the position of the bee when it is closest to the flower? Save the result as a numpy array in
</html>
In [1]:
# You must run this cell, but you can ignore its contents.
import hashlib
def ads_hash(ty):
"""Return a unique string for input"""
ty_str = str(ty).encode()
m = hashlib.sha256()
m.update(ty_str)
return m.hexdigest()[:10]
In [2]:
# You must also run this cell.
import numpy as np
import matplotlib.pyplot as plt
Exercise - Optimization first steps¶
We are going to take our first steps towards optimization by returning to a bumblebee example.
We are going to define the positions of a flower and the flight path of a bumblebee.
In [3]:
flower = np.array([7.5, 10.3])
In [4]:
def make_bee_track(t):
pos0 = (-10,3)
velocity = (4.0, 0.2)
pos_x = pos0[0] + t*velocity[0]
pos_y = pos0[1] + t*velocity[1]
return np.array([pos_x,pos_y])
t = np.linspace(0,15,20)
bee_track = make_bee_track(t)
Here we plot these positions.
In [5]:
fig, ax = plt.subplots(nrows=1, ncols=1)
ax.plot( [flower[0]], [flower[1]], 'or', label='flower' )
ax.plot( bee_track[0], bee_track[1], '.-k', label='bee')
ax.axis('equal')
ax.legend();
Q1 Draw a figure as above with, additionally, a blue line between each point on bee_track
and flower
.¶
When complete, your figure should look like this:
Hint, draw the flower first. Then, make a for loop which steps through each position of the bee. Inside the for loop, draw a line segment between the bee and the flower.
In [6]:
# Your code here. Check it is correct by comparing your figure with the above.
fig, ax = plt.subplots(nrows=1, ncols=1)
ax.plot( [flower[0]], [flower[1]], 'or', label='flower' )
ax.plot( bee_track[0], bee_track[1], '.-k', label='bee')
for i in range(bee_track.shape[1]):
bee_pos = bee_track[:,i]
ax.plot( [flower[0], bee_pos[0]], [flower[1], bee_pos[1]], 'b-' )
ax.axis('equal')
ax.legend();
Q2 write a function called my_distance
which takes two arguments, each of which is a length 2 sequence of x
, y
position and returns the Euclidean distance between these points.¶
In [7]:
def my_distance(a,b):
a = np.array(a)
b = np.array(b)
return np.sqrt(np.sum((a-b)**2))
In [8]:
assert my_distance((0,0),(3,4)) == 5
assert my_distance((3,4), (0,0)) == 5
assert my_distance((13,14), (10,10)) == 5
assert my_distance((10,10), (13,14)) == 5
Q3 compute the distance between each point on bee_track
and flower
. Put the results in a 1D numpy array called distance
.¶
Hint: recall the function you wrote in the "numpy basics" exercise called compute_distance
.
In [9]:
distance = np.zeros(bee_track.shape[1])
for i in range(bee_track.shape[1]):
bee_pos = bee_track[:,i]
distance[i] = my_distance(bee_pos, flower)
display(distance)
In [10]:
# If this runs without error, it means the answer in your previous cell was correct.
assert ads_hash(np.round(distance*1000).astype(np.int32))=='54f4f2edcb'
Q4 make a plot of the bee track parameter t
on the X axis and distance
on the Y axis.¶
It should look like this:
In [11]:
# Your code here. Check it is correct by comparing your figure with the above.
fig, ax = plt.subplots(nrows=1, ncols=1)
ax.plot( t, distance )
ax.set_xlabel('t')
ax.set_ylabel('distance')
Out[11]:
Q5 Using calc_distance_func
from the lecture, find the value of t
that minimizes the distance between the bee and the flower. Save the result in best_t
.¶
In [12]:
# Your code here.
def compute_distance(a,b):
a = np.array(a)
b = np.array(b)
return np.sqrt(np.sum((a-b)**2))
def calc_distance_func(t):
x1, y1 = flower
x2, y2 = make_bee_track(t)
dist = compute_distance((x1,y1), (x2,y2))
print(f't: {t} -> dist: {dist}')
return dist
import scipy.optimize
result = scipy.optimize.minimize_scalar(calc_distance_func)
print(result)
best_t = result.x
In [13]:
# If this runs without error, it means the answer in your previous cell was correct.
assert ads_hash(np.round(best_t*1000).astype(np.int32))=='dec1ab2f6d'
In [14]:
make_bee_track(best_t)
Out[14]:
Q6 What is the position of the bee when it is closest to the flower? Save the result as a numpy array in best_pos
.¶
In [15]:
# Your code here.
best_pos = make_bee_track(best_t)
In [16]:
# If this runs without error, it means the answer in your previous cell was correct.
assert type(best_pos)==np.ndarray
assert best_pos.ndim==1
assert best_pos.shape==(2,)
assert ads_hash(np.round(best_pos[0]*1000).astype(np.int32))=='e33b9415bc'
assert ads_hash(np.round(best_pos[1]*1000).astype(np.int32))=='f71cbfce4c'