Dark theme

I/O


In this practical, we're going to import some data to use as our agents' environment, and get them to interact with it.

First off, here's a text file with some comma separated variable data in it: in.txt; download it to the directory where your model is. This is raster data, with each value being the equivalent to a pixel in an image, arranged in a grid.

Secondly, find the CSV reading code in the lecture notes. Import the csv module, and get the code reading in.txt. Next we need to add this data, as we read it in, to a 2D list. Let's think about how to do this...

In general, the pattern for dealing with looping 2D data is this:

# Lines here happen before any data is processed
for row in dataset
    # Lines here happen before each row is processed
    for values in row
        # do something with values.
    # Lines here happen before after row is processed
# Lines here happen after all the data is processed

With raster data like this, each row is an increase in the y-direction, and each subsequent values in a row increases the x-direction. The matplotlib method we'll use to display the data should understand this. This is why we've been talking about y,x throughout the practicals, not the more traditional x,y.

If "dataset" above is our csv reader, we basically have the csv reader code. If we want to shift the data into a 2D list, we need to make an empty list, (let's call it "environment" here, as it'll hold our environmental data) before any processing is done, make a new list (let's call it "rowlist") before each row is processed, append the values to the rowlist, and then, when a row is finished, append the rowlist to the environment list. In the end, we'll end up with each row being a new list in our environment, and each row filled with values.

Here are the lines you need, but we've ordered them randomly. Can you put them together with your csv reader code, with the right indents, to read the csv into the environment list?

environment.append(rowlist)
rowlist.append(value)
rowlist = []
environment = []

To check you you've read the data in correctly, you can show it using:

matplotlib.pyplot.imshow(environment)
matplotlib.pyplot.show()

When you've got it working, go on to see how we get our agents to interact with it. We're going to make sure each agent has access to the environment.


  1. This page
  2. Nibbling the environment <-- next