Read my book

I wrote books about Webpack and React. Check them out!

Tuesday, January 19, 2010

Agent Based Architecture in Python - Solving Marble Problem

I am currently reading Sherry Turkle's renowned The Second Self. It has provided some really nice food for thought. I was inspired by the concept of emergence she mentioned about.

Essentially the idea is that complex behavior may arise based on a set of simple rules. The particular case she described dealt with colored marbles on a table. Let's assume there are only black and white marbles. The question is are there more black marbles or vice versa?

If you can count and are able to compare numbers, it's easy enough to figure this out. It gets more problematic if you don't possess these skills. In this case you could try something simpler. A simple alternative is just to remove a pair of marbles having different colors till only marbles of one color are left on the table. Now it's just a matter of recognizing that color and stating the result.

Modeling Agents

Obviously it would be ridiculously simple to model the first solution. How to proceed with the latter one? I modeled each "skill" using an agent. The book proposed using following agents:
  • GetColor - Returns the color of marbles left. If the color is ambivalent (ie. no marbles left or more than 1 color), it returns None.
  • RemoveMarbles - Removes one marble of each color from the table
  • NoMarblesLeft - Announces that there are no more marbles left on the table
Here's my implementation of those classes:

Just modeling agents is not enough. There needs to be an environment as well.

Modeling Environment

In this case environment is going to be somewhat simple. It should just contain a table that has a bunch of marbles having different colors. I came up with this sort of solution:

Note that I defined marbles using a couple of tuples so it should be easy enough to alter later.

Finally we need an actual class for the application itself.


The application just needs to set up the environment and the agents and poll them when it's run. I added a way to inspect the output of individual steps and provided an adjustable interval to alter the time between prints. Here's my implementation:


This time I didn't come up with any specific tests. Of course there are some asserts here and there but nothing rigorous. Should I want to use the agent framework for something more serious, building a nice test suite would be a nice next step.

In this case using agents doesn't give any tangible benefit compared to a procedural approach. There's a whole group of problems (esp. AI) for which using them is extremely beneficial, however.