Agent-Based Modelling. Part 1
Tags: abm, tutorial
Published: 2019-08-07 23:42:49

---
title: Agent-Based Modelling. Part 1
published: true
description: Agent-based modeling tutorial
tags: abm, tutorial
---


Agent-Based Modelling: An Introduction
====================

Agent-Based Modeling (I will refer to it as ABM from now on) is a simulating
paradigm in which the programmer creates an entity that has specific
properties and can perform a set of actions. Sounds simple, and they are
more intuitive than mathematical or statistical models as they represent
objects as we see them: individual elements in an environment. You might
have already had a glimpse of what some ABM looks like if you have
played The Sims or SimCity videogames.
It’s possible to model almost anything: financial markets,
transportation grids, social interactions, natural environments, etc. A
simple example would be to model traffic. We can create three different
templates: for a car, for a road, and for a pedestrian, and then we can
simulate several vehicles, in a few streets interacting with some
pedestrians. I told you it *sounded* simple!

The benefits from the agent-based models are:[^1]

> 1. Capture the understanding of systems.
> 2. Test that systems’ understanding of coherence and comprehensiveness.
> 3. See if the individual-level behavior creates global patterns.
> 4. Validate the theory against real data.
> 5. Make predictions about the system.

But how do we do this? In this series of posts, I am going to describe
how to do this with Python and Ruby. I want to tell you that you don’t
have to use those programming languages, there exist other options, such
as any programming language with an Object-Oriented “mentality” (e.g.,
C++, MATLAB or Java, among **many** others) or specific tools like
NetLogo or Dramatis.[^2]
(*Disclaimer*: I’ve been using Python for a few years now, but I became
interested in Ruby a few months ago. Hence, this is more a way to
finally force me to learn Ruby, and the way I use Ruby might not be the
best you have ever seen.)

Let’s get down to work!

First things first: you need a functional version of Python and/or Ruby.
It is possible to install both languages in your system, there are
plenty of good tutorials on the Internet, and I highly recommend it to
not depend on an Internet connection to run some scripts. In case you
can’t do it, don’t want it, or think you’d fail miserably, there exists
an excellent website—called [*Repl.it*](https://repl.it/)—that allows
you to run scripts without any effort. This is convenient for learning
but not scalable for more significant projects.

Now, the *concepts:* we are going to use **objects**, the idea I will
describe in this first post.

An object, in a programming environment, is something that contains data
(known as *attributes* or *properties*) and procedures (known as
*methods*). We can create an object, and then we create as many
instances of that object as we want, all of them following the same
pattern. Let’s see how this translates into Python and Ruby.
Suppose we want to model the previous example of traffic modeling. We
need cars, roads, and pedestrians. For simplicity, here the cars will
only have the model and the color (attributes), and they will be able to
move (method); the roads, a name and a defined number of lanes, and they
can be congested or not; and the pedestrians, a speed, and they can be
moving or still.

The cars, in Python, will be like the following:
```python
class Car:
    def __init__(self, model, color):
        self.model = model
        self.color = color
        self.moving = False
    def change_state(self):
        self.moving = not self.moving
        if self.moving:
            print("The car is moving now")
        else:
            print("The car stopped")
```

We use the reserved word “class” to define the car class. The
\_\_init\_\_ method is particular to Python and is executed every time
one instance of a car is created, i.e., initializes a vehicle with its
properties. We also need a method that changes the state of the car:
“change\_state.”
The roads, in Ruby, can be coded like this:
```ruby
class Road
    def initialize(name, lanes, state)
        @name = name
        @lanes = lanes
        @state=state
    end
    def get_state 
        puts "Is the road congested? #@state"
    end
end
```

The syntax is similar to the one in Python but with a few more mandatory
words and letters. We have an initializer, as before, and a method that
gives us the state of the road. (Don’t worry now for the trifles of a
real road and if it’s not very realistic. I want you to get the idea of
how to model in Ruby.)
The pedestrians, in Python and Ruby, can be modeled as follows:

```python
class Pedestrian:
    def __init__(self, speed):
        self.speed = speed
        self.moving = False
    def moving(self):
        self.moving = not self.moving
        if self.moving print("The car is moving now") else print("The car
stopped")
```

```ruby
class Pedestrian
    def initialize(speed, state)
        @speed=speed
        @state=state
    end
    def change_state
        puts "State was #@state"
        @state = !@state
        puts "State is #@state now"
        puts "\n"
    end
end
```

Cool. We know how to create the templates—classes—for our objects, and
to create the copies—instances—of the objects, we proceed as follows (in
Ruby and Python, respectively):
```ruby
ped = Pedestrian.new(0, false)
ped.change_state
```
```python
car1 = Car('Buik', 'red')
car.change_state()
```

In the next post, I will go step by step on a dummy model to show what
is my strategy to approach this kind of systems. It is worth noting that
the critical bits come when you must associate the individuals’ behavior
with the environment, with certain conditions, or with a set of observed
actions.
For this matter, there exist a few tools which help in the process. My
background is in engineering, so I usually like diagrams, such as UML
diagrams. UML stands for Unified Modeling Language and helps to
visualize the architecture, design, and implementation of complex
software systems. Among the benefits, UML is a standardized modeling
language and, therefore, can be used across different programming
languages. Software developers will understand it and might want to
apply it to their work. There are many good tutorials on the Internet
about UML,[^3] and specialized tools to use with the languages you use
to create the diagrams from your code.


See you in the next post! :D

[^1]: Reference [*here*](http://www.geog.leeds.ac.uk/courses/other/crime/abm/general-modelling/index.html)

[^2]: See [*this Wikipedia page*](https://es.wikipedia.org/wiki/Comparación_de_software_de_modelaje_basado_en_agentes) for more information, and this article review of the state-of-the-art for more accurate information: Abar, S., Theodoropoulos, G. K., Lemarinier, P., & O’Hare, G. M. (2017). Agent Based Modelling and Simulation tools: A review of the state-of-art software. Computer Science Review, 24, 13-33.

[^3]: [*lucidchar website*](https://www.lucidchart.com/blog/types-of-UML-diagrams), and [*tallyfy website*](https://tallyfy.com/uml-diagram/)