Skip to content

Instantly share code, notes, and snippets.

@Sparrow0hawk
Created December 9, 2022 11:42
Show Gist options
  • Select an option

  • Save Sparrow0hawk/a12631e3368381d3da6e5928c7aaf99b to your computer and use it in GitHub Desktop.

Select an option

Save Sparrow0hawk/a12631e3368381d3da6e5928c7aaf99b to your computer and use it in GitHub Desktop.
Playing with ChatGPT
from mpi4py import MPI
import numpy as np
# Define the size of the grid
n = 100
# Initialize MPI and get the rank of the current process
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
# Generate a random starting point for this process
x = np.random.randint(0, n)
y = np.random.randint(0, n)
# Generate a random target point that all processes will search for
if rank == 0:
target_x = np.random.randint(0, n)
target_y = np.random.randint(0, n)
else:
target_x = None
target_y = None
target_x, target_y = comm.bcast((target_x, target_y), root=0)
# Perform the random walk until we find the point
while True:
# Generate a random direction and move in that direction
dx, dy = np.random.choice([(-1, 0), (1, 0), (0, -1), (0, 1)])
x += dx
y += dy
# Check if we have found the point
if x == target_x and y == target_y:
# If so, stop the random walk and exit the loop
break
# Gather all the random walk steps from all processes into a single array
all_steps = comm.gather((x, y), root=0)
# If this is the root process, print the array of steps
if rank == 0:
print(all_steps)
@Sparrow0hawk
Copy link
Author

Generated from the following set of queries:

Here is an example of a MPI-enabled random walk program in Python that searches a 2D grid for a single point and stops as soon as one MPI worker finds the point, gathering all worker random walk values into a single array:

Followed up with:

adapt the code above so the algorithm searches for a randomly generated point and stops when this point is reached.

@Sparrow0hawk
Copy link
Author

This looks great, but doesn't quite work as billed.

The first problem is with line:

dx, dy = np.random.choice([(-1, 0), (1, 0), (0, -1), (0, 1)])

This gives an error:

  File "<stdin>", line 1, in <module>
  File "mtrand.pyx", line 911, in numpy.random.mtrand.RandomState.choice
ValueError: a must be 1-dimensional

You could fix this by using random.choice rather than np.random.choice. I haven't prompted it to use numpy here, but it's interesting that it makes this mistake.

Also more critically, this code doesn't work as intended. As it doesn't halt the search when one MPI worker finds the target. It only breaks the loop on the worker where the target is found. Leading us to a place where this code will only halt once all workers have found the target.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment