Masthead

The Blob Class

The example below shows how to create a very simple "Spatiall Explicit Individually Based Model" in Python. This is a model that contains objects that are spatially referenced where each object represents an individual. The individeuals in this case are "blobs" but could be any type of animal.

The example relies on the tkinter library to display the objects as they move from left to right. This also maes it an example of how to use modeless windows to display animated data in Python.

1. Blob Class

Below is a class that represents a "blob" within a tkinter window. The class contains a number of functions that are explained below. Copy the class into the Wing IDE and then review the contents of the class based on the descriptions below. Save the code as BlobModule.py.

#################################################################
# A blob that can be moved in a canvas
# Heavliy modified from: http://effbot.org/tkinterbook/canvas.htm
# Author: Jim Graham
# Date: 2/27/2013
#################################################################

""" Class to create blob objects and have them move around the screen.
 This is a template class that can be used to create agent-based models.
"""
class BlobClass:
	""" Initialize the new object
	 Inputs:
	  canvas - the canvas widget that the blob will appear in
	  Position - a list of the x and y pixel coordinate for the starting location of the blob
	  FillColor - the color of the Blob
	  MovementAmount - The Amount to move the Blob for each time Move() is called
	"""
	def __init__(self, TheCanvas, Coordinate, FillColor, MovementAmount):

		self.TheCanvas = TheCanvas # save the canvas the blob is in

		# save the amount to move for later
		self.MovementAmount = MovementAmount

		# create the oval at an x and y location based on movement
		self.id = self.TheCanvas.create_oval(Coordinate[0], Coordinate[1],
		      Coordinate[0]+20, Coordinate[1]+20,fill=FillColor)

	""" Move the blob objct
	"""
	def move(self):
		# get the existing coordinate of the blob
		Coordinate = self.TheCanvas.coords(self.id)

		# if the blob has moved off the frame, reverse the direction of movement
		if Coordinate[2] >= self.TheCanvas.winfo_width():
			self.MovementAmount = -self.MovementAmount
		if Coordinate[0] < 0:
			self.MovementAmount = -self.MovementAmount
			
		# update the blob in the canvas
		self.TheCanvas.move(self.id, self.MovementAmount, 0)

The __init__ function first saves the Canvas and Coordinate parameters into itself for access later on. The function then creates an oval object and adds it to the Canvas.

You can add varaibles to the object with code like self.MovementAmount=MovementAmount. This will take the value passed in as MovementAmount and save it in the object with the label MovementAmount.

The function move(self) moves the objects based on the MovementAmount. The concept is that this function should be called for a single time step so the animal can move a given distance.

2. Calling The Blob

The code below shows you how to use the Blob class to make a number of blobs move across the screen. Note that we import the BlobClass from the BlobModule.

Below is an overview of the code:

  1. Imports the required libraries
  2. Sets up the tkinter interface
  3. Creates the canvas that the blobs will move around on
  4. Initializes the Blobs into a list
  5. Runs "forever" while updating the blobs positions and then allowing tkinter to redraw the window. This step includes:
    1. Move each blob in the list
    2. Call "MasterWindow.update_idletasks()" to allow the window to redraw
    3. Call "time.sleep()" to slow down the speed of the animation
#################################################################
# A script to create and move Blobs in a tKinter frame
# Heavliy modified from: http://effbot.org/tkinterbook/canvas.htm
# Author: Jim Graham
# Date: 2/27/2013
#################################################################
from tkinter import *
from BlobModule import BlobClass
import time # bring in the time library so we can "wait" between drawing

# Setup the GUI with a modeless window labeled "Blobs"
MasterWindow = Tk()
MasterWindow.title("Blobs")
MasterWindow.resizable(0, 0)

# Create the Canvas widget for the blobs to move in
canvas = Canvas(MasterWindow, width=500, height=500, bd=0, highlightthickness=0)
canvas.pack()


# Create four blobs objects
TheItems = [
    BlobClass(canvas, (100, 50), "red", 2),
    BlobClass(canvas, (100, 80), "blue", -1),
    BlobClass(canvas, (100, 120), "green", 1),
    BlobClass(canvas, (100, 150), "gold", -2)
]

MasterWindow.update() # fix geometry

# Move the blobs forever
try:
	while True:
		for TheItem in TheItems:
			TheItem.move()
		MasterWindow.update_idletasks() # redraw
		MasterWindow.update() # process events
		time.sleep(.01)

except TclError:
	pass # to avoid errors when the window is closed

Copy and paste this code into Wing and then try running it. You should see four circles moving in a window. Now try changing the color and size of the blobs. Try changing the sleep parameter speed up and slow down the action. Try adding more blobs.

You can now add additional movement in the vertical direction, add interactions between blobs, make the blobs grow, breed, and die - the options are limitless!

Additional Resources:

Python Documentation: Classes

An Introduction to tkinter

© Copyright 2018 HSU - All rights reserved.