2024-heraklion-scientific-p.../notebooks/walker/Step_1_classes/Step_1_classes_exercise.ipynb
2024-08-27 15:52:41 +03:00

140 KiB

1. Take a look at this (working) code

... and run it.

In [1]:
%matplotlib inline

from walker import create_context_map, plot_trajectory, sample_next_step
In [2]:
i, j = 100, 50  # initial position
sigma_i, sigma_j = 3, 4  # parameters of the next step map
size = 200  # size of the image
context_map = create_context_map(size, 'hills')  # fixed context map

# Sample a next step 1000 times
trajectory = []
for _ in range(1000):
    i, j = sample_next_step(i, j, sigma_i, sigma_j, context_map)
    trajectory.append((i, j))

plot_trajectory(trajectory, context_map)

2. Rewrite the code to look like it would in your wildest dreams!

How could you restructure the interface of the walker library so that the functionality stays the same, but the code is less smelly?

  1. could this code work better/more efficiently as a class?
    • e.g. walker = Walker(...)
  2. how should the setup/initialization work?
    • e.g. which parameters would you pass to instantiate the Walker class? How do you pass them to the class?
  3. which functions should be part of the class?
    • e.g. is sample_next_step a method of Walker? Is create_context_map a method of Walker? How about plot_trajectory? If so, call them with walker.sample_next_step()
  4. what would the import statement look like?

Important: We are not asking you to implement the changes in walker.py! Imagine the new interface, and write the code that would use it in the next cell. Of course it won't run (yet)

Here are some things to keep in mind:

  • Which things will you do a lot? They should be easy to do. The interface for doing those things should be simple.
  • Which things should be modifiable from external code?
  • As a rule of thumb, think about how it sounds when you read it aloud
    • “Giving orders”-style
    • “Telling a story“-style

For inspiration think about how you call code from other libraries. Here is an example of instantiating an object and calling one of its methods:

import scipy as sp

#  Sampling from a gaussian with specific mean and sd:
# Create a Gaussian (normal) distribution object
gaussian_dist = sp.stats.norm(loc=mean, scale=sd)
# Sample 10 values from the Gaussian distribution
samples = gaussian_dist.rvs(size=10)
In [4]:
# Write the code that uses your new `walker` interface here!
# walker = Walker(sigma_i=3, sigma_j=4, ...)
# ...
In [ ]: