Parallelisation and Python
The algorithm we'll work to is:
- Make an local list containing the densities in the landscape on a particular node
- Send the local list to node zero
- Receive all the local lists on node zero
- Add them up on node zero to make a global density list
- Send the global list to all the other nodes from node zero
- Receive the global density list back from node zero
- Move the agents if necessary based on the density
Let's start with making the local list in "task" – remember, each node gets its own copy of task, agent.py, and landscape.py. This local list variable is going to contain the densities for the local node. It will then be sent to node zero to be added to the total for all nodes:
# Run
for time in range(iterations):
# Send out the local densities to node zero
if (node != 0):
landscape.calc_densities()
densities = landscape.getdensities()
pipe_to_zero.send(densities)
The second to last line requires we add a getdensities
method in
landscape.py
to return the array made by landscape.calc_densities
. While we're at it, we might as
well also add a setdensities
method, as we'll need it later (here's the code: landscape.py).
Next we need to write the receiving code for node zero, so we replace the end of the "if not node zero" statement with...
else : # if node is node zero
# Get the local densities in to node zero
densities = []
for x in range(width):
for y in range(height):
densities.append(0)
for i in range (len(pipes)):
# Get the local density from each node i.
local_densities = pipes[i].recv()
# Add node i's density surface to the global surface.
for x in range(width):
for y in range(height):
densities[(y*width) + x] =
densities[(y*width) + x] +
local_densities[(y*width) + x]
Now that's done, let's have a look at our model.py class with the alterations in.
So the final thing is to pass the global density array back again. We'll do that Next.