The aim of re-writing the library code upon which Indra models relied was to reduce the complexity of the system, and achieve greater expressiveness with fewer lines of code.
So far, the results look promising. Let's take a look at the beginnings of the first model being written based on the indra2
library. This is a classic predator-prey model, often called "wolf-sheep" in the ABM world. The central idea is to model how populations of predators and their prey will cycle in a circumscribed environment.
The first thing to do is import the (few!) items we need to get going:
In [1]:
from indra.agent import Agent, AgentEncoder
from indra.composite import Composite
from indra.env import Env
Next define a few constants -- these will be params in the fully developed system:
In [2]:
NUM_WOLVES = 3
NUM_SHEEP = 12
WOLF_LIFESPAN = 5
WOLF_REPRO_PERIOD = 6
SHEEP_LIFESPAN = 8
SHEEP_REPRO_PERIOD = 6
Now we will define what wolves and sheep do when called upon to act -- the model is far from done at this point, and these actions are trivial, but they illustrate the use of the system:
In [ ]:
def sheep_action(agent):
print("I'm " + agent.name + " and I eat grass.")
def wolf_action(agent):
print("I'm " + agent.name + " and my remaining life is: "
+ str(agent.duration))
Next let's create to helper functions to create wolves and sheep, just to make the code following this a little simpler:
In [6]:
def create_wolf(i):
return Agent("wolf" + str(i), duration=WOLF_LIFESPAN,
action=wolf_action,
attrs={"time_to_repr": WOLF_REPRO_PERIOD})
def create_sheep(i):
return Agent("sheep" + str(i), duration=SHEEP_LIFESPAN,
action=sheep_action,
attrs={"time_to_repr": SHEEP_REPRO_PERIOD})
Now we have everything we need to create our populations and put them in a meadow to interact:
In [7]:
wolves = Composite("wolves")
for i in range(NUM_WOLVES):
wolves += create_wolf(i)
sheep = Composite("sheep")
for i in range(NUM_SHEEP):
sheep += create_sheep(i)
Now we will create a "meadow" in which these critters will interact -- the meadow is an instance of Env
:
In [4]:
meadow = Env("meadow")
meadow += wolves
meadow += sheep
Lastly, we set things going in the meadow:
In [3]:
meadow()
In [ ]:
3 + 7
In [ ]:
3 + + 7
In [ ]:
3 + * + 7
In [ ]: