Unit 3: Simulations

Lesson 26: 2D random walk

Notebook Authors

(fill in your two names here)

Team Roles

Facilitator: (fill in name)
Spokesperson: (fill in name)
Process Analyst: (fill in name)
Quality Control: (fill in name)

If there are only three people in your team, have one person serve as both spokesperson and process analyst for the rest of this activity.

At the end of this Lesson, you will be asked to record how long each Model required for your team. The Facilitator should keep track of time for your team.

Scientific Application: 2D random walk

In this lesson, we will develop a python program to simulate a 2-dimensional random process. The last time we considered a random walk it was in 1 dimension along the number line. Now we will consider 2 dimensions. Later, we will add a velocity component. Our model will end up looking like Brownian motion or diffusion of particles.

Computational Focus: Multi-dimensional arrays

Model 1: Creating Multidimensional Arrays

A multidimensional array is a sequence of 1D arrays.  It can also be thought of as a grid of rows and columns.  The following is an example of a 4x3 array:

$$\left[ \begin{array}{ccc} 0 & 1 & 2\\ 3 & 4 & 4\\ 6 & 7 & 8\\ 9 & 10 & 11\\ \end{array} \right]$$

Arrays are also sometimes referred to as matrices in math classes.

Let's get started!

Type and run the following code:

import numpy as np
array2D = np.array([[0,1,2],[3,4,5]])
print(array2D)

In [ ]:

Type and run the following code - each line in its own cell:

print(array2D[0,1])
print(array2D[1,1])
print(array2D[1,0])
print(array2D[0])
print(array2D[1])
print(array2D[0,2])

In [ ]:

1. How many index numbers are used to represent a single element of a multidimensional array?  

2. When identifying a single element of a multidimensional array, what does the first index number reference? What does the second index number reference?

3. If only a single index number is identified for a 2D array, what is the corresponding output?

Type and run the following code:

array1 = np.array([6,7])
array2 = np.array([8,9])
array3 = np.array([0,1])
multiarray = np.array([array1,array2,array3])
print(multiarray)

In [ ]:

Type and run the following code - each line in its own cell:

print(multiarray[1,1])
print(multiarray[2,1])
print(multiarray[1,0])
print(multiarray[0])
print(multiarray[1])
print(multiarray[0,2])
print(len(array2D))
print(len(multiarray))

In [ ]:

4. Why did the code print(multiarray[0,2]) produce an error?

5. Recall the len function returns the length of a 1D array, such as array1. What happens when you apply the same function to a 2D array?

6. What is the Python code that would return the other dimension of the array? (hint: Consider your answers to questions 3 & 5)

Type and run the following code:

array0 = np.zeros((2,5))
print(array0)

In [ ]:

7. When you use the NumPy zeros function, does the first parameter represent the number of rows or columns?

8a. What is the default data type of the array created by zeros?

8b. You can also specify the data type with a 3rd argument like this:

array0b = np.zeros((2,5), float)

try changing the data type to float and int to see what the default is.

9a. Write and run Python code to create a 3x2 array filled with 2’s in at least two different ways.

9b. Write and run Python code to add $\pi$ to each element in one of the arrays that you created in 9a using array math.

10. Type and run the code below

rand_array=np.random.random((2,3))
rand_array

10a. Write and run code that uses a loop to print $\pi$ times each element in the first row of the rand_array array that you made. (there are times when you want to loop through an array, but not when you want to do math)


In [ ]:

10b. Then write and run code that uses a loop to print $\pi$ times each element of the rand_array array (the entire array).

11. Type and run the following code - each line in its own cell:

print(multiarray[2,1])
print(multiarray[2][1])

In [ ]:

11a. Compare the results.


In [ ]:

12. Type and run the following code:

print(array2D)
new_row = np.array([6,7,8])
print(new_row)
new_array = np.append(array2D,[new_row],0)
print(new_array)
newer_array = np.append(array2D,[new_row])
print(newer_array)

12a. Give the dimensions of each of the arrays:

array rows columns
array2D
new_row
new_array
newer_array

12b. Examine the three above lines of code (besides the print commands). For each line of code, identify whether the code modify the original array or create a new array?

12c. Give the pseudocode for appending to a 2D array.

There are often several ways to accomplish the same thing in Python, in this case, the first notation (multiarray[2,1]) is more "Pythonic" and is what is found in the NumPy documentation (see links below) and the second notation (multiarray[2][1]) is what is used by most other programming languages. This is mostly an FYI so that if you see the second one, you know that it will work, and for when you learn your second programming language.

More info on arrays

There is a lot you can do with arrays, here are a few useful resources:

Team Programming

In this exercise, we will make a series of random 2D walk, graph the results, and calculate the maximum distance from the origin.

Again we will use the idea of a "step" for the walker, but this time we will incorporate the idea of the walker being able to select a direction for its steps.

Algorithm

Use the cartesian X-Y plane with an origin of (0,0) for the start of the walkers. Then we can use a random angle, $\theta$, between $0$ and $2 \pi$ radians, to get a new direction and new values for X ($cos\theta$) and Y ($sin\theta$) to add to the old coordinates, therby taking a "step".

We will keep track of the X and Y coordinates in an array with 2 columns (and as many rows as steps).

For now, the step sizes are all similar, later will add a "velocity" component.

Let's code this thing up!

A. Define a class that:

  • uses a single 2D array to track the (x,y) coordinates of a single random walker
    • the walker should start at (0,0)
  • takes a single parameter in addition to self that sets the number of steps
    • since you know the number of steps, you know the size of the array you need (avoid using append since it is very inefficient!)
  • randomly selects an angle (theta) for the direction of the next step
  • moves the walker one step at a time, keeping track of the (x,y) position in the 2D array
  • prints the resulting array

In [ ]:

test your code several ways with different parameter values to demonstrate that it works


In [ ]:

B. Modify your code to plot the path of the walker and no longer print the array.


In [ ]:

test your code several ways with different parameter values to demonstrate that it works


In [ ]:

C. Now add a parameter that allows the user to enter a velocity that can scale the distance traveled for a single step.


In [ ]:

test your code several ways with different parameter values to demonstrate that it works


In [ ]:

D. Modify your code to calculate and print the maximum distance that the walker wandered from the origin during the simulation. (hints: look at the numpy.max() method and the cdist method from the scipy.spatial.distance module)


In [ ]:

test your code several ways with different parameter values to demonstrate that it works


In [ ]:

Analysis Question: Describe what happens to the maximum distance as you increase the veloicty.

E. Modify your code so that your class can plot multiple 2D random walks on the same axes and the maximum distance reported is the maximum distance of all of the walks (make the default number of random walks = 1).
Be careful asking for too many more than 8 simulations since the colors in matplotlib repeat and at some point you'll bog down your machine.


In [ ]:

test your code several ways with different parameter values to demonstrate that it works


In [ ]:

F. Add code to pretty up your plots by adding grey lines once underneath all of the walker plots, and a red dot at the origin on top of everything else. (see the example output in the Team Programming instructions for an example)


In [ ]:

test your code several ways with different parameter values to demonstrate that it works


In [ ]:

pretty cool, right?!?!?!

Temporal Analysis Report

How much time did it require for your team to complete each part?

Model 1:

Team Programming: