multi-agent simulations of social phenomena

47
West University Timisoara Faculty of Mathematics and Informatics Computer Science – English Language GRADUATION PAPER MULTI-AGENT SIMULATIONS OF SOCIAL PHENOMENA Scientific Coordinator Student Gabriel Istrate Victor-Emanuel Blaga Timisoara 2008

Upload: georgel-preput

Post on 10-Apr-2015

333 views

Category:

Documents


2 download

DESCRIPTION

Simulating social interaction in humans is a quite daunting task, should one take into account its almost infinite complexity and dynamic nature. Evidently, models built on paper are as static as they are limited in detail. Therefore, modelling a social system requires computer-based simulations that have the benefit of animation.While most models deal strictly with one side or other of society, and do it at a very abstract, mathematical level, agent-based models such as Sugarscape take a bottom-up approach, allowing the user to include as many behaviours as necessary, from virtually any field, and apply them at the individual level. Consequently, this particular model becomes much more approachable, requiring only casual observation of real-life activities on the part of the analyst in order to output aggregate, top-level answers to a particular question.Shaped along the lines of the Sugarscape model, the current framework attempts to give the potential user an unprecedented level of flexibility in tackling and deciphering the inner workings of social systems, through a modular approach and an open, script-based system. The application presents itself on a two-pronged basis: written in Lua script, the heart of the simulation is open to ad-hoc modifications, while the user interface takes advantage of the graphical features of Java and a set of third-party libraries to bring life to the data outputs of the model.Expanding on these highlights, the paper provides an in-depth view of the framework itself, as well as of its context, reasons and methods of usage.

TRANSCRIPT

Page 1: Multi-Agent Simulations of Social Phenomena

West University Timisoara

Faculty of Mathematics and Informatics

Computer Science – English Language

GRADUATION PAPER MULTI-AGENT SIMULATIONS OF SOCIAL PHENOMENA

Scientific Coordinator Student

Gabriel Istrate Victor-Emanuel Blaga

Timisoara

2008

Page 2: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

2

Table of Contents

1. INTRODUCTION ............................................................................................................................ 4

2. A USER’S PERSPECTIVE .............................................................................................................. 7

2.1 The Need for Artificial Societies .......................................................................................................... 7 2.1.1 An Uphill Puzzle .................................................................................................................................... 7 2.1.2 Doing Away with the Haystack ............................................................................................................. 8 2.1.3 The Agent-Based Model ....................................................................................................................... 9

2.2 On the Practical Side ......................................................................................................................... 11 2.2.1 The Big Picture outside the Box .......................................................................................................... 12 2.2.2 The “Why” ........................................................................................................................................... 13 2.2.3 The “How” ........................................................................................................................................... 14 2.2.4 Falling in Line ...................................................................................................................................... 15

3. THE SUGARSCAPE ..................................................................................................................... 16

3.1 Components ...................................................................................................................................... 16 3.1.1 The Environment ................................................................................................................................ 16 3.1.2 The Agents .......................................................................................................................................... 18 3.1.3 The Clock ............................................................................................................................................. 20

3.2 Adding Slices to the Pie ..................................................................................................................... 21 3.2.1 Sex ....................................................................................................................................................... 21 3.2.2 Disease ................................................................................................................................................ 22 3.2.3 Trade ................................................................................................................................................... 23 3.2.4 Credit .................................................................................................................................................. 24 3.2.5 Culture ................................................................................................................................................ 25 3.2.6 Combat ............................................................................................................................................... 26 3.2.7 The Pie ................................................................................................................................................ 27

3.3 Off the Beaten Path ........................................................................................................................... 28 3.3.1 Custom Scenery .................................................................................................................................. 28 3.3.2 Change of Conduct .............................................................................................................................. 29

4. DESIGN AND IMPLEMENTATION ......................................................................................... 30

4.1 Design Process .................................................................................................................................. 30 4.1.1 Factory Design Pattern ....................................................................................................................... 30 4.1.2 Observer ............................................................................................................................................. 31

Page 3: Multi-Agent Simulations of Social Phenomena

3 Blaga Victor-Emanuel

4.2 The Foundation ................................................................................................................................. 32 4.2.1 Front-End: Java and Swing .................................................................................................................. 33 4.2.2 Scripting Support: Lua 5.1 ................................................................................................................... 34 4.2.3 Input Data: Java Advanced Imaging API .............................................................................................. 35

4.3 Upwards and Onwards ...................................................................................................................... 37 4.3.1 Living off the Land ............................................................................................................................... 38 4.3.2 Part of a Community ........................................................................................................................... 39 4.3.3 I Spy ..................................................................................................................................................... 41 4.3.4 Full Circle ............................................................................................................................................. 42

5. CONCLUSIONS ............................................................................................................................. 43

5.1 Lessons Learned ................................................................................................................................ 43 5.1.1 What Went Right ................................................................................................................................ 43 5.1.2 What Went Wrong .............................................................................................................................. 45

5.2 Like, Finally ....................................................................................................................................... 46

6. BIBLIOGRAPHY .......................................................................................................................... 47

Page 4: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

4

1 Introduction

Society works, at times, in mysterious ways – trying to understand it, man has developed a

number of sciences studying its various facets, in what is a more manageable, “divide and

conquer” approach. Nevertheless, studying and developing the methods of human

interaction through the lens of just one particular field of activity will inherently ignore

most, or at times, all factors described by the other social sciences, factors which may have

a noticeable impact on the field of study.

Moreover, decision makers in all lines of work must take into account many seemingly

unconnected aspects of a problem in order to figure out the dynamic of a situation, and plan

accordingly. At this point, one has to turn to interdisciplinary study to attain his goals in an

efficient manner, and social simulation proves to be an indispensable aid to this process.

Sugarscape1 is, in itself, one such social simulation model. Developed by Joshua M. Epstein

and Robert Axtell, it builds a bottom-up social model that is easy to comprehend and

modify. The basis of this model is the concept of individuals (called agents) who live in a

certain environment, and interact with one another and with the land according to a

defined set of rules. Recording the results of these complex interactions as statistical and

map data, we have a reasonable basis to predict the outcomes of a “what-if” scenario.

Dealing with a bottom-up model, the user holds control over the heterogeneity of the agent

population, in terms of traits, and, most importantly, of behavioural rules. This freedom

brings Sugarscape one huge leap forward towards the real world, as opposed to other

aggregate models in use, which tend to oversimplify the matters at hand, by assuming that

each individual acts the same way, or even by completely ignoring the passing of time.

Capitalizing on the need of powerful mechanics and ease of use, this project implements the

Sugarscape model in such a way as to be both intuitive, modifiable, and to require only basic

programming knowledge, akin to the skills a sixteen-year-old gamer learns, in order to

1 Epstein, J. M., & Axtell, R. (1996). Growing Artificial Societies. Cambridge: MIT Press.

Page 5: Multi-Agent Simulations of Social Phenomena

5 Blaga Victor-Emanuel

modify his favourite game. To this end, this project makes use of interpreted simple,

pictographic maps (in other words, images) to define the environment, and of the LUA

scripting system, widely used in computer games, to define the behaviour of the agents, and

even the flow of the simulation.

The whole point of this project is to allow the researcher to build and analyze observable

patterns in social structures, whether those are the inter-human relationships in an office

building, or the annual migration of the Gnu wildebeests in Africa.

This paper will try to expand on these topics, at first by presenting a user’s perspective of

the issue, and making a point in detail as of why exactly there is a need for a comprehensive

interdisciplinary method of social pattern prediction. We will speak at length about the

current uses of such modelling, as well as the various pitfalls in which separate discipline-

centric analysis of social phenomena tends to fall in.

Moving on to presenting the software’s capabilities from a user’s point of view, as opposed

to a developer’s, we go on to enumerate its various use instances in a range of fields of

work.

Furthermore, we will try to define the artificial world we are building with this software, at

first by determining its structural components: the environment, the agents, and the rules,

each with its own distinctive framework. Secondly, we have to look upon a basic set of rule-

independent interactions that take place between the agents and the environment, in order

to set the stage for more advanced behavioural patterns.

Building on this basis, we will then try to expand the scope of our artificial world, by adding

rules and traits to both agents and environment, in such a way as to develop recognizable

social phenomena among the agent population, akin to what drives society in the real

world. In addition to the standard Sugarscape model, an analysis of the additions and

modifications to its paradigm shall emerge, following the consequences that introducing

real-world landscapes and modifiable agent behaviour have on its reliability and versatility.

Practice follows theory – therefore, with the next section we shall go on to explore the

actual design process and implementation of the software package. Starting with a

systematic walkthrough of the roads taken and not taken during the development process,

Page 6: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

6

we continue by going over the technologies embedded in the project and their features, as

pertaining to the advancement of our goals. Finally, we describe in detail the way we built

the Sugarscape, in terms of classes for agents, the environment, the overall society and its

various sub-groupings.

In order to prove our point, we will also provide a series of run scenarios and other

examples, to give a feeling for what output data the user can expect to receive, from a given

model that goes beyond testing, and attempts to mimic a real situation.

To wrap it all up, the project, along with this paper attempt to expand and explain what we

believe to be crucial issues with Sugarscape implementations, namely ease of use and

versatility, while employing off-the-shelf technologies and standardized formats to bring the

application into the mainstream category of software projects.

Page 7: Multi-Agent Simulations of Social Phenomena

7 Blaga Victor-Emanuel 2 A User’s Perspective

2.1 The Need for Artificial Societies

As our world grows increasingly complex, businesses, sociologists, armies, policy makers,

and a host of other categories of people find themselves confronted with ever more

complex systems to analyze reliably, and most importantly, with accurate results.

The previous generations of equation-based mathematical modelling tools generally fail at

producing dependable results from their analysis of intricate phenomena due to their

consistent approach of over-simplification and data abstraction. As they say, more often

than not, the devil is in the details – therefore, models of idealized systems tend to break

down in practice and lead to erroneous decisions at higher levels.

Because agent-based modelling does not require the scientist to implement the functioning

system as a whole, does not rely on over-simplification, and literally “grows” out of the sum

of its parts, it manages to capture a realistic picture of the structure it represents, and can

add or remove components more-or-less on the fly.

2.1.1 An Uphill Puzzle

Structurally, most organizations have gradually become more elaborate, mostly because of

the multifaceted environment of their operations. Coupled with diminishing business

resources, the situation can turn into quite a predicament for managers and decision or

policy makers. These people have to continually battle to keep their organizations afloat and

predict emerging trends and opportunities in order to attain specific long-term goals in an

often volatile and ever-evolving environment.

The rate of situational change is in many circumstances dictated by technological progress

and the new mechanics evolved thereof. Cheap storage space means beefier databases and

Page 8: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

8

more detail from which to draw conclusions through analysis. Globalized travel and

communications have led to outsourced manufacturing, mostly offshore, in sweatshop-

friendly countries. Former such manufacturing heavens progressively get more expensive to

use, so one has to be able to predict when and where it is profitable to move factories.

Consequently, supply chains will also expand and interweave, meaning that it gets harder by

the minute to perform a centralized analysis on their efficiency.

Globalization also implies that unrest in some remote corner of the third world may have

great impact in the countries that matter to people who use computers to analyze things, as

verified by the on-going terrorism and Islamic liberation trends, or by rising oil prices due to

Nigerian tribal attacks on oil pipelines. Planning for counterinsurgency in a foreign country

has to take a great deal of variables into consideration, and has to be people, or agent-

centric, as it aims to win the hearts and minds of an alien culture.

Transportation networks grow progressively more interconnected, markets become ever

more sophisticated and fragmented; companies grow, escalating the number and variety of

interactions within and with the outside world; infrastructures holding our modern lives

together are interdependent: electricity, petroleum, water and telecommunications – all of

this amounts to a world so complex that mathematical simulations just cannot cope with

the information load.

2.1.2 Doing Away with the Haystack

The approach that non-agent based simulations take to modelling systems or phenomena is

to radically idealize their inner workings. People will throw all detail to the bin in order to be

able to feed the simulation a concept small enough for it to handle. Expectedly, results are

either highly skewed, work only in highly improbable circumstances, or are simply out of this

world, leading to flawed decisions and unwanted consequences.

Over-simplification ranges from assuming you can buy only one product off the market, and

choose from an infinite number of vendors, to the presumption that all factions in a theatre

of operations have the same goal and abide by the same rules. While any corporate CEO will

Page 9: Multi-Agent Simulations of Social Phenomena

9 Blaga Victor-Emanuel

sneer at the first example, lives and homes may be lost due to decisions made on top of a

faulty and generalized analysis adopting the second as a rule.

Moreover, mathematical simulations will only provide results for long-term outcomes that

imply steady progress over extended periods of time, case that rarely applies to the real

world. The simulation will provide no data for the time in-between the present and the far-

away goal, nor will it be able to compensate for, or even consider disturbances along the

way. Bearing in mind the rapid pace at which our world changes, one may even consider the

phrase “long-term” just short of obsolete.

Simplified models have yet another drawback: by replacing details with assumptions of an

idealized situation, they will not signal that any data is missing, again leaving the person

running the simulation at a loss to explain just why prediction analysis differs so wildly from

the facts of reality.

In all, the previous generations of analysis and planning tools have a workflow analogous to

planning for a needle-in-the-haystack search operation, without taking into account that

there actually is a haystack to search. Unfortunately, more misses than hits in analysis and

pattern prediction leads, in non-technical circles, rather to a change of operating procedures

than to a drive to better analysis tools or shift their working paradigms.

2.1.3 The Agent-Based Model

The “new” way of organizational and situational modelling, the agent-based approach

captures the essence of a system’s behaviour through a ground-up approach. The conduct

of the whole develops as the result of the conduct of each of its parts – of each modelled

agent, in other words. This method enables organizations to convert specific individual

functions, which are tangible, so to say, and well documented, into aggregate group

behaviours and their system-wide implications. Furthermore, the level of detail and the

number of cross-agent interactions are only limited by development time and processing

horsepower, as there are no set limits to how complex a behaviour each individual agent

has.

Page 10: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

10

An important point to make about the Sugarscape model is that time flows naturally,

similarly to the real world. Therefore, the observer can follow the results from start to finish,

through all the intermediary steps, having a clear analysis of both the road to his goals, and

of the context of attaining them.

The main drive in agent-based simulations is to mimic the real world as closely as possible,

and then adopt a laissez-faire attitude, to see the results. Once a behaviour pattern is set,

and if it differs from the target goal, the user will tinker with each agent’s individual

behaviour, in order to see what down-to-earth, clear-cut modifications are required for the

entire system to function properly.

Page 11: Multi-Agent Simulations of Social Phenomena

11 Blaga Victor-Emanuel

2.2 On the Practical Side

Before delving into the structure of the Sugarscape, we first need to fill in two blanks,

namely the reasons to engage in simulations at all, and the methods of solving a practical

problem through an artificial model. There are a number of approaches to simulation, all

geared towards different uses and contexts2, Sugarscape extracting concepts and

functionality from most of them.

• The System Dynamics approach structurally models a high-level dynamic process

over time, without taking an in-depth, detailed view of its inner-workings.

• Discrete-event simulations, although modelling similar types of processes tend to

focus heavily on detail, simulating events that forward the process each time unit.

• Participatory simulations use the concept of people in order to replicate dynamic

decision-making processes, as well as social interactions and the way these affect the

system as a whole.

• Optimization is a process that, as the name implies, tries to find an optimum solution

to a mathematically expressed problem.

• Statistical modelling, however, does not address the system at all, but rather only its

output and inputs, correlating the two with no regard whatsoever to internal

structure or causality.

• Risk analysis focuses on the factors that put an entity at risk, reason for which it is

widely used in businesses that want to survive.

These traditional models will take either what can be called a “strategic” perspective, with a

top-down approach, or a more “tactical” view, in order to be applicable at a more

operational level as well. The Sugarscape itself draws from both worlds, allowing itself to

become most of the above and more.

Nevertheless, suspicion leads us to believe there is a reason behind all this, and somebody

may actually have some gain off using these systems.

2 North, M. J., & M, M. C. (2007). Managing Business Complexity. New York: Oxford University Press.

Page 12: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

12

2.2.1 The Big Picture outside the Box

Ever since decision makers in business and government decided they should turn into

control freaks, they needed tools and an underlying organizational framework to analyze

and predict the outcomes of goals, activities, tasks, resource and other constraints on their

companies. People generally employ system analysis to the end of bettering an

organization, by spotting bad or sub-par processes, developing enhanced versions of the

said processes, and predicting the outcomes of their subsequent integration.

A good way of approaching system analysis is through the perspective of the information

flow in an organization: who needs what information, where? Do we generate that data in-

house, or through a third party? Does anyone actually use it, and how much does it cost?

Simulation and modelling serve to monitor and answer these questions, in order to optimize

whatever process they replicate, and provide the big suits with a rationale for writing pay

checks.

The people involved with dissecting the inner workings of an already running process will

start by summing up the details, identifying causes for the visible effects, and will then try to

gain a better understanding of the system as a whole. Though doable with only a pen and

paper, in an eco-friendly world, the analyst does not always have direct access to the

Page 13: Multi-Agent Simulations of Social Phenomena

13 Blaga Victor-Emanuel

process, or needs confirmation that his theory works, point in time when resorting to the

miracles of computing seems to be the best course of action. Creating computer simulations

of business or more generally, organizational processes and systems will imbue the analyst

with the power to explore the nooks and crannies of the model in his own time, and allow

him to create comprehensive conclusions based on patterns or limit situations otherwise

not observable in everyday life.

Moreover, analysts tend to get lost in the details, and burrow themselves so deep in one

corner or other of the process, that they simply miss the big picture. Computer simulations

force them to consider the greater issues, sometimes for no other reason than simply

because their output relates to the organization as a whole. The analyst can therefore

regain perspective by never having to plunge so deep into the investigation itself that it

becomes a purpose, rather than a means to make more money.

Not all people in a company will get bogged down in the details, however, reason for which

there’s always a conflict over how much detail should be included in a simulation, in order

for it to be valid and true to real life, as well as cost effective and timely. The Sugarscape

somewhat settles the issue, by introducing a minimal standard to the level of detail, due to

its bottom-up methodology.

2.2.2 The “Why”

Since most analysis translates to computer simulation, non-luddites have built up a whole

set of rationalizations for trusting these models and taking decisions based on their output:

• People’s brains are too small, so they cannot hope to comprehend and work an

entire system from scratch, the poor weaklings. Therefore, managers will opt to

model a system before they deploy it and risk having to pick up the pieces.

• Computers are more imaginative, or at least they can explore a much greater range

of possibilities through sheer brute force. Even workaholic managers that have a

good grasp of their target process, and who have all the time in the world to cook up

a wide range of possible outcomes, due to them living at work, become dwarfed by

Page 14: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

14

the capabilities of a machine, which can spew out potential outcomes that no man

has thought before.

• Humans think on rails, limiting mental models to their experience and restraining

possible extrapolations to the boundaries of what seems normal. We had better left

it to computers to think up cascading chains of improbable events, before they

actually happen.

• Real visionaries among humans are the minority, and oracles are overrated. While

people will generally not have the ability to predict something completely novel, the

complex interactions of a multi-agent model may amount to a scientifically provable

result that no one had expected.

• We value real-world consequences more than in-game ones, hence the Save and

Load functions. A business owner will likely care less if half his virtual employees

starve to death in a computer simulation, than if one valued employee threatens to

leave the boat for real. Experimentation in real life is discouraged, to put it mildly, so

the masses expect decision makers to get their first resolution right.

We regard agent-based models as the best choice due to each of these incentives, with high

chances of new, insightful results, otherwise impossible to attain through traditional

methods.

2.2.3 The “How”

Building a simulation of something can go on one of two paths:

• Modelling the problem – assuming there is a problem, will focus on getting specific

answers to clear-cut issues.

• Modelling the system – will end up in a simulation that reproduces certain

behaviours and sort of lets the user to take on from there.

Most used in business and for immediate practical use is the first modelling technique,

considered most efficient due to its power of concentrating development on specific areas

with the highest probability of return. Avoiding unnecessary features seems to be the trend

among businesses that hire developers for money.

Page 15: Multi-Agent Simulations of Social Phenomena

15 Blaga Victor-Emanuel

Other areas of research, though, such as academic study, benefit most from the other

approach, since they need a comprehensive, complete model of the system in order to draw

their conclusions.

2.2.4 Falling in Line

All simulations, no matter the area of research, or the model employed face the same two

defining challenges: data collection and model validation. Sometimes, the latter depends

greatly on the first, since where and how the data was collected influences the viability and

trustworthiness of the simulated output.

These two issues being most important in any model, analysts tend to address them in the

same manner, independent of the modelling technique. Exceptions exist, such as having to

collect data beforehand when building a statistical simulation, as opposed to being able to

do it in parallel with constructing a system model.

Finally, the greatest pitfall simulation developers can fall in is sidetracking. Most models are

there to bring about never before seen processes or procedures, and special challenges may

arise in development. Even the intended focus of the model may at first present itself as

imprecise, therefore each step of model-building has to be refined to a cutting edge, to

ensure that problems do not pop up afterwards and prove to be unsolvable.

Page 16: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

16

3 The Sugarscape

3.1 Components

The Sugarscape model rests on three main pillars: the environment, the agents, complete

with the rules to which both abide, and last, but not least, the clock, which apart from

driving time forward, also acts as an invisible hand managing agent actions. Just like in real

life, the model makes a clear-cut distinction between the terrain and its inhabitants, who

roam the landscape pursuing their own goals, interacting with each other and with their

surroundings, as time irreversibly passes. This means that agent spatial distribution will

influence, depending on what we simulate, the dynamics of epidemics, trade, cultural drift,

or even warfare.

Most notably, the agent population is heterogeneous, each agent sporting different traits,

maybe even abiding to different rules, maybe to the extent that no two agents are alike. We

can afford to be just as flexible in building the landscape: no two spots have the same

resources, in the exact same amounts. Moreover, environmental rules may differ from one

spot to another, for example, differentiating the expected mortality rate between

harvesting crops, say, on a field, as opposed to in an active volcano.

Let us, then, take a closer look at each of the three basic components that make up our

simulation.

3.1.1 The Environment

The universe in which our agents live looks pretty much as your average paper map,

meaning that we have done away with the third dimension, limiting the field of vision to 2D,

or at most, 2.5D.

Page 17: Multi-Agent Simulations of Social Phenomena

17 Blaga Victor-Emanuel

There are two types of environments: one closely mimicking real life, in the form of an

open-world grid, with terrain features and free roaming agents, and another, more abstract

environment, that best resembles the concept of settlements connected by roads. This

second type of environment will remove any other terrain from the equation, resulting in

what looks more-or-less like a graph.

Both environments can handle a virtually limitless number of resources for the agents to

harvest and live on. Being a finite landscape in both resolution and dimension, each grid cell,

by default, represents just enough space for an agent to occupy. Each of these cells

(locations) has resource stocks of varying quantities, each resource type belonging to its

own layer. Therefore, the environment is comprised of a set of concurrently accessible

resource layers, every one of them a landscape in itself, sharing the very same coordinates.

For example, we might have a cornfield on top of uranium-rich soil. Doing away with the

third dimension, an agent standing in the middle of this landscape, will, at the same time,

find himself knee-deep in uranium, and harvesting the dubiously oversized corn for the

day’s meal.

This brings us to the rules governing our artificial universe, most of which relate to resource

grow-back and allocation. We may assign a different set of rules for every resource layer

mapped on our grid locations, or even to every unique grid point. Once harvested, the corn

may grow back incrementally, pop up at full capacity after a certain period of time, or even

instantaneously. This may vary according to location, or even to the amount of uranium held

by that particular spot. An entire ecosystem can thus arise – development time and machine

power the only limits to its complexity.

Not all resources held by the landscape are necessarily harvestable, or even desirable. The

developer may simulate ground altitude, or even pollution, through the very same process.

Should we consider dirt a resource, we get to the logical conclusion that the more dirt on

one spot, the higher its elevation. Conversely, pollution as a resource can have dispersion

rules comparable to the way an ink drop spreads on blotting paper.

Page 18: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

18

3.1.2 The Agents

Any given Sugarscape model simulation will usually have a fractured agent population,

forming two or more splinter groups, possibly going as far as to forego grouping in favour of

unique individuals, defined by traits and rules. While homogeneity is certainly possible when

building up the population, the real life social structures that Sugarscape typically simulates

are much more complex and subtle. Not only will agents have different characteristics and

abide to different rules, but some may not have some traits altogether, while others may do

without one rule or another.

The most basic agent model describes individuals that do not have any particular traits,

apart from their name, or ID, and age that roam the landscape in search for food. The rate

at which they collect resources from the environment differs from their in-born metabolism;

therefore, the agent may have a stockpile of resources in his virtual backpack, which he

Movement Rule M: function Agent:look() local locations = List:new() local look = 1 n = self.location.neighbours["N"] s = self.location.neighbours["S"] e = self.location.neighbours["E"] w = self.location.neighbours["W"] while look <= self.vision do if n ~= nil then locations:add(n) n = n.neighbours["N"] end if s ~= nil then locations:add(s) s = s.neighbours["S"] end if e ~= nil then locations:add(e) e = e.neighbours["E"] end if w ~= nil then locations:add(w) w = w.neighbours["W"] end look = look + 1 end return locations end function Agent:chooseNextLocation() local locations = self:look() locations:sort("resources.last.value.current_resources", locations.gt) for location in locations:iterator() do if location.value.occupant == nil then return location.value end end return nil end

Page 19: Multi-Agent Simulations of Social Phenomena

19 Blaga Victor-Emanuel

slowly eats away. Upon running out of resources to consume, agents die of starvation.

Failing that, they will still die, eventually, of old age.

Typical agent traits concern vision distance, genetic attributes, cultural heritage, group

membership, resource carrying capacity, metabolism, sex, and diseases. The developer may

insert any type of attributes, relating to the object of each particular simulation. These traits

connect closely to the agents’ rules of conduct, that define each individual’s response in

varying circumstances to meeting another agent with, or without, certain traits.

Rules, however, go beyond agent-to-agent interaction. They describe the entire behaviour

of each agent, from movement, to resource consumption, to trade, reproduction, warfare,

death, and any other imaginable action, or set of actions that he undertakes. The most basic

rule of all, movement, does not even concern other agents past acknowledging their

existence in a certain spot. As is the case with the environment, rules can be applied globally

(to the entire population), only to a certain group, or individually, to each agent.

Whereas we thought out built-in rules to be as simple as possible, in no small measure due

to processing and development constraints, custom simulations can use an intricate set of

laws to govern agent and environment behaviour, taking into account multiple variables and

affecting more than one agent.

Agent Action A: function Agent:action() for resource in self.resource_list:iterator() do resource.value:calculateMetabolism() end if self.age == 100 then self:die() else next_location = self:chooseNextLocation() if next_location ~= nil then self.location.occupant = nil self.location = next_location self.location.occupant = self self:consumeAllResources() end self.age = self.age + 1 end end

Page 20: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

20

3.1.3 The Clock

A real underdog of the Sugarscape model, the clock drives the entire simulation. Even

though the simulation divides time into finite units, be they years or seconds, agents take

turns in performing their actions within each timeframe. No two agents work at the same

time, lest conflicts appear – therefore the clock is required to choose which agent has

priority.

This means that different choices may skew the results of the simulation one way or

another. Normally, the choice is random, but in some cases, we might want a certain type of

agent to have priority over another, in order for the simulation to be accurate.

Apart from this mechanic, time is a deciding factor in almost any simulation, a vast number

of variables depending on it, such as agent age limits, or crop growth.

Page 21: Multi-Agent Simulations of Social Phenomena

21 Blaga Victor-Emanuel

3.2 Adding Slices to the Pie

Sugarscape goes way beyond what we have described in the previous chapter. Adding stuff

on top of this basis varies wildly according to the object or objects of study, but assuming

we are studying humans, not ants on a table, and wanting to include and / or examine the

motivators of human society, there are preset rules that Epstein has left for the picking.

3.2.1 Sex

The commonly accepted view of the world is that making babies keeps a species going, in

the interest of which, our special breed of agents need to learn how to produce offspring.

Unfortunately, this does not entail fathers having manly talks with their sons, or mothers

giving out pictures of flowers to their daughters, but rather lines of algorithm code.

Emulating the real world, such an algorithm could base itself for the most part, on age.

Humans are thought to be fertile from around the age of 14, 15, up to somewhere in their

50s or 60s. Since we are not automatically accounting for in-vitro fertilization, we suppose

the two agents first have to be near one another – in other words, within each other’s field

of vision. Then we check if they are both of fertile age, and then, maybe for some other

arbitrary attribute, like money. If the neighbourhood is not currently overcrowded, in the

sense that there is one empty space for the new kid within both parents’ fields of vision, the

two get together and produce another agent sharing similar characteristics with their own,

and lugging a part of their hoarded resources.

Assuming there is no God, and Darwin actually got evolution right, our function will weed

bad “genes” from good ones, be they high metabolism, low vision, or anything else, really.

Neighbour Finding Algorithm N: function Agent:neighbours() local locations = self:look() local neighbours = List:new() for location in locations:iterator() do if location.value.occupant ~= nil then neighbours:add(location.value.occupant) end end return neighbours end

Page 22: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

22

This algorithm can even check for similarities in a partner, or can differ from one agent to

the other, depending on how discerning we want the agents to become. If we plan on high

discrimination, and general soberness, we can expect the birth rate to drop dramatically,

but if we do the right choice of engineering agents with a drinking problem, we could even

simulate the population of Bangladesh.

3.2.2 Disease

Speaking of which, (Bangladesh, disease is just coming up) we can simulate an entire range

of illnesses and pandemics through the same process as building a computer virus. First, we

have to differentiate between healthy and unhealthy individuals by setting a variable that

asserts the agent’s state. This is akin to having an executable include the bad code in it.

Reproduction Rule R: function Agent:procreate() if self.age > 15 and self.age < 50 then local neighbours = self:neighbours() local locations = self:look() local baby_loc = nil for neighbour in neighbours:iterator() do if neighbour.value.age <= 15 or neighbour.value.age >= 50 then neighbour:rem() end end neighbours:sort("vision", neighbours.gt) spouse = neighbours.first.next.value for location in locations:iterator() do if location.value.occupant == nil then baby_loc = location.value break end end if baby_loc ~= nil then local agent = Agent:new() agent.location = baby_loc baby_loc.occupant = agent agent.vision = math.floor((self.vision + parent.vision) / 2) for resource in self.resource_list:iterator() do if spouse.resource_list:get("id", resource.id) ~= nil then father = resource mother = spouse.resource_list:get("id", resource.id) new_resource = Resource:new() new_resource.metabolism = (father.metabolism + mother.metabolism) / 2 new_resource.current_value = ((father.current_value / 3) + (mother.current_value / 3)) father.current_value = (father.current_value / 3) * 2 mother.current_value = (mother.current_value / 3) * 2 agent:addResource(new_resource, resource.id) end end population:addAgent(agent) end end end

Page 23: Multi-Agent Simulations of Social Phenomena

23 Blaga Victor-Emanuel

Furthermore, we attach a function that serves to spread the illness to the other

unsuspecting victims, which amounts to running the said executable. Finally, we can have a

payload, meaning that the disease is more than just a trait, like blue eyes, but it also affects

the agent’s life and behaviour.

On the other hand, we could concomitantly have another illness, called “caring for your

fellow agent”, that has struck a particular group, called “medics”, just so that not all disease

goes untreated.

3.2.3 Trade

Having already familiarized you with our rather dystopian view of how agents grow crops on

top of fertile, uranium-rich soil, let us assume that only some spots grow uranium, but

agents need to grow crops on arid soil as well in order to survive. Consequently, radioactives

become a commodity, and our population will start trading fissionable material in order to

get the day’s meal. Since uranium itself tends to be harder on your teeth and kidneys than

corn, agents will still eat corn, so the mineworkers will not get off easy.

Trade follows a decentralized pattern, presenting agents that are located one near the other

with the opportunity of bartering and bargaining. Each agent can do this with all his

neighbours within vision range, and will naturally choose the best deal, if not influenced by

other, as of yet unmentioned, factors. Agents with what they believe is excess corn will give

away the corn for uranium, and hungry, yet wealthy agents, will give shell out uranium to

grab a snack.

Resource Status Algorithm S: function Agent:resourceStatus() local best = self.resource_list.first.next.value local worst = self.resource_list.first.next.value for resource in self.resource_list:iterator() do if resource:timeLeft() > best:timeLeft() then best = resource elseif resource:timeLeft() < worst:timeLeft() then worst = resource end end return best, worst end

Page 24: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

24

3.2.4 Credit

Some agents, due to starting out on a bad patch of land, having a small initial resource

endowment, or simply because they are weak, cannot afford to make a living, produce

offspring, or buy that shiny Lamborghini. One final effort to save their lives or reach their

other goals could be to borrow some resources, be they uranium or corn, from a fellow

agent within range. The simplest form of credit would be one without an interest, payable

at a set later date, but a whole range of credits can be implemented, as well as a whole set

of consequences for not paying on time.

When considering a credit, the lender will first see if he has anything to give away, analyze

how many resources the borrower has been able to gather up to now, in order to assess the

latter’s ability to repay, then think up a payment plan according to the type of credit made.

Trading Rule T: function Agent:tradeResources() if self.resource_list.total_items > 1 then local best, worst = self:resourceStatus() if worst < 3 or best > 10 then local neighbours = self:neighbours() local sell_quantity = (best:timeLeft() - 5) * best.metabolism local traders = List:new() for neighbour in neighbours:iterator() do response = neighbour:acceptBarter(best, worst) if response ~= nil then trader = { id = neighbour.id, val = response } traders:add(trader) end end traders:sort("val", traders.gt) partner = neighbours:get("id", traders.first.next.value.id) if sell_quantity > traders.first.next.value.val then sell_quantity = traders.first.next.value.val partner.resource_list:get("id", best.id):add(sell_quantity) self.resource_list:get("id", best.id):rem(sell_quantity) partner.resource_list:get("id", worst.id):rem(sell_quantity) self.resource_list:get("id", worst.id):add(sell_quantity) end end end function Agent:acceptBarter(buy, sell) if self.resource_list.total_items > 1 then local best, worst = self:resourceStatus() if buy.id == worst.id and sell.id == best.id and best:timeLeft() > 10 then return (best:timeLeft() - 5) * best.metabolism end end return nil end

Page 25: Multi-Agent Simulations of Social Phenomena

25 Blaga Victor-Emanuel

Visualizing credit networks through a graph will show the very dynamic nature of these

agent-to-agent relationships.

3.2.5 Culture

Since there is a small part of life that is not entirely dependent on either sex, or money, we

have introduced the very fuzzy concept of culture in Sugarscape. In practice, this is just a list

of variables that agents can recognize in others and compare to their own, in the interest of

sex, giving and receiving money, or the odd case of jihad.

Moreover, just like disease, agents can pass on cultural traits from one to another according

to random, user-selected criteria, and can have different spreading patterns. Two African

friends may share a passion for blonde Europeans, but in order to pass on their rationale to

a mutual Pakistani friend, they will have to pass on knowledge of their language first.

Furthermore, those two Africans are likely to pass on their cultural traits, should they adopt

and raise a still innocent blonde European as their child, through a process called education.

The latter form of cultural transmission takes place at birth, similarly to the way parents

pass on their genes to their children. In order to impart cultural traits peer-to-peer, an agent

will have to go through all of his neighbours, select one of its traits, and then look for the

same one in the first neighbour. Three cases can occur: one, the neighbour already has the

same value for that trait, case in which nothing happens; two, the neighbour has a different

value, so the current agent changes it to its own value; and three, the neighbour does not

have that trait at all, so the current agent adds it to his neighbour’s list of traits.

Based on this list of cultural preferences, just as in the case of genetic characteristics, we

can divide the population according to how close their lists match. Two shotgun-approach

comparisons come up: one checking for the same preference in the entire population, the

other checking for global differences in the cultural list.

Since the first amounts to string comparison, there is only a point in explaining the latter.

One way of doing it would involve reducing the culture list to an array of one and zero,

therefore dividing the population by how close to zero the sum of each agent’s list is. This

method, however, only allows for two possible values per cultural preference.

Page 26: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

26

The second method is more comprehensive, yet much more time consuming, as it requires

comparing each list with the lists of every other agent, and establishing the percentage of

identical preference values.

3.2.6 Combat

Since we have already included most of the other entertaining activities people partake in,

warfare seemed the next logical step on the road to simulating a civilized world.

We therefore made agents able to cane one another to death over crops and uranium, in

the absence of lambs. Someone may occupy the best resource spots within one agent’s

vision, reason enough to murder them and harvest the crops they had been standing on,

plus some or all of the victim’s resource stash.

Many rules can be thought up to control if and how combat takes place, but the basic, common

sense ones would dictate that the big fish will not get eaten by the little one, and that even a big fish

will not risk eating another one if it leaves him vulnerable to an even bigger fish. In programmer talk,

this means that an agent with an overall resource stash smaller than that of its targeted victim will

not attack, and neither will an agent that has within his vision a third agent that will be bigger than

himself after he will have robbed his mark.

If the attacker can rob the victim of all its wealth, the attacker’s ascent will be close to exponential,

since he will have a better chance at robbing ever more wealthy opponents, its attack deterrent ever

greater. Infinite agent lifetimes would take this to an extreme where after a number of generations

nobody could challenge the Methuselah agents that would grow fatter at the expense of the

youngsters.

However, if there is only a fixed reward for breaking the sixth commandment, and lives are finite,

like on Earth, combat becomes relatively reasonable, in terms of monopoly. If we couple this rule to

agent grouping, group regeneration, possibly through reproduction, and no group infighting, we can

observe an ensuing war of attrition.

Page 27: Multi-Agent Simulations of Social Phenomena

27 Blaga Victor-Emanuel

3.2.7 The Pie

Adding these components together in one simulation reveals a complex proto-society that

progresses and interacts in patterns remarkably similar to what we observe in real life. Agents evolve

from a rather uniform population into more genetically fit individuals that trade with one another;

divide into spatially segregated groups, according to resource geographic distribution; form

networks of friends and peers, and fight over resources and cultural beliefs.

A potential user can customize this generic artificial society to account for virtually any thinkable

situation that involves individuals, be they human or bacteria.

Combat Rule C: function Agent:isSuperiorTo(rival) local self_points = 0 local rival_points = 0 for resource in self.resource_list:iterator() do if rival.resource_list:get("id", resource.id) ~= nil then self_time = resource:timeLeft() rival_time = rival.resource_list:get("id", resource.id):timeLeft() self_points = self_points + self_time rival_points = rival_points + rival_time end end self_points = self_points * self.vision rival_points = rival_points * rival.vision if self_points > rival_points then return true else return false end end function Agent:fightForNextLocation() local locations = self:look() locations:sort("resources.last.value.current_resources", locations.gt) for location in locations:iterator() do if location.value.occupant == nil or self:isSuperiorTo(location.value.occupant) then location.value.occupant:die() self.location.occupant = nil self.location = location.value self.location.occupant = self end end end

Page 28: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

28

3.3 Off the Beaten Path

Since the vanilla version of the Sugarscape has never really served for anything else except

demonstration purposes, we brought a set of modifications to it, both by not sticking strictly

to the book when implementing the predefined agent rule set, and by introducing a couple

of innovative concepts to the mix, so as to prepare this framework for real use. In this

process, we were careful not to degrade the simulation results’ level of accuracy, but rather

prepare the model to deal with real-life data and processes.

3.3.1 Custom Scenery

Worth mentioning are the addition of customizable landscapes and behavioural modification. The

Sugarscape environment is traditionally an unravelled torus, with two hills of sugar, one in the

northeast corner, and another in the southwest corner of the map. This map wraps around both

along the X-axis, and along the Y-axis, forming the said torus, and allowing agents to pop out on one

end and appear at the other.

Since such behaviour is not very consistent with how people move on a map, and because a

landscape usually encompasses other features, apart from two perfectly round hills, we reasoned

that importing custom scenery should be a high priority on our list. The landscape retains the

possibility of wrapping around vertically and horizontally, but this has become an optional feature,

and no one really expects to see this feature in heavy use anytime soon, since we all know the Earth

is flat.

Further modification to the environment is possible, given that we can link locations from off the

map to any point on the grid, or create shortcuts between two places, to simulate fast travel

options. These shortcuts need not even be bidirectional, one location’s north neighbour pointing to

a place far, far away, and the south neighbour of that faraway place being just below on the map.

We opted for this approach after weighing in that versatility is more important than error

prevention, if the latter rules out the first. This means that forging a two-way link between two

places needs linking both to one another, similarly to building a second train track connecting two

stations.

Page 29: Multi-Agent Simulations of Social Phenomena

29 Blaga Victor-Emanuel

3.3.2 Change of Conduct

The other notable addition to the standard Sugarscape model comes in the form of agent

behavioural modification. Though more an added bonus made possible by our choice of used

technologies, this feature brings the Sugarscape to a completely new level of realism, impossible to

attain otherwise without going through much unnecessary complication.

Even though the practical aspect of this process is unremarkable, i.e. referencing one function

instead of the other, the conceptual implications open up the gateway to real agent change. The

original Sugarscape model fails in providing truly heterogeneous populations of agents – they do not

have the same genetic traits, the same cultural attributes, the same wealth, or the same age; what

they do share in common, is the rules by which they abide.

It would be almost foolish to think that all people adhere to the same code of conduct, which, in

turn, is immutable. Fortunately, we are now able to not only change agent behaviour internally,

based on arbitrary values, but also transmit rules, actions, algorithms from one agent to the other,

allowing for much more complex interactions within a dynamic artificial society.

Our agents now can act differently as a baby, a young adult, or an old person; they can even

“convince” other agents to copy their behaviour, through processes similar to genetic or cultural

attribute transmission. For example, we need not represent disease only as a tag on an agent, but

can attach a manner of conduct specific to that disease, be it in the form of erratic behaviour,

reduced resource-processing rate, or lifespan reduction.

The meaningful difference in our approach is that an agent should not automatically have a latent

ability to act in a certain way since birth – even though the agent does not have that function, it can

reference it from another’s pool of functions, and practically adopt it as its own.

By more closely mimicking real life, these two additions enhance the model’s reliability, going

further along the road of ever-increasing complexity, as opposed to the mathematical models we

have already brought to attention.

Page 30: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

30

4 Design and Implementation

4.1 Design Process

Although we wrote and designed a great deal of the application code somewhat

haphazardly, the first step taken was to settle upon a number of design decisions, which

greatly simplified our work. Due to the dual nature of the application, we had to use the

factory design pattern to build a solid and viable framework, as well as try making it as

modular as possible.

4.1.1 Factory Design Pattern

The whole idea behind this design pattern is to provide encapsulation to classes prone to

frequent changes, to avoid the myriad of modifications brought about in virtually all code

segments that use these classes as programmers revise them. Moreover, if we are to adhere

to the Dependency-Inversion Principle3, we ought to try to depend as much as possible on

abstract classes, rather than concrete ones.

Achievement of this objective is possible by introducing a factory class and an interface in

addition to the class or classes that are being included in this pattern, so that we call a

factory method to create the volatile classes, which are all accessible through the same

interface. The factory method may even be able to call a set of different class constructors,

based on the provided parameters, and return a generic object, cast to the appropriate

class, as necessity dictates.

Not all projects benefit from using factories, but they can be of great help as the application

grows ever larger and complex, since they allow higher-up classes to create and manage

instances of volatile classes without depending on how the latter are implemented.

3 Martin, R. C. (2002). Agile Software Development. New Jersey: Prentice Hall.

Page 31: Multi-Agent Simulations of Social Phenomena

31 Blaga Victor-Emanuel

More to the point of our project, factories were a necessity, instead of just a convenience,

since controlling Java classes directly through Lua script is a real hassle if not done through

helper methods. The incentives to use factory were even greater, since the user interface

classes mapped to the factory are practically tabs containing plot canvases for graphic

representation of the simulation’s output data. Most of these plot canvases are thoroughly

similar, so mapping them to a common interface was mostly a breeze.

Therefore, the user interface, mapped by default in the Lua memory space, and thus fully

accessible through the script, also serves as factory for creating data output tabs of various

kinds, from pie and scatter plots, to fully interactive consoles and other advanced charts.

Even the simulation proper has to use some form of factory to build itself from the provided

input data, even though the inner workings of Lua are very dissimilar to the object-oriented

concepts and restrictions of C++ and Java.

4.1.2 Observer

Another early discovery was the conceptual difference between actually running a Sugarscape simulation, and printing the output data to screen. Since these two do not necessarily go hand in hand, we opted for a completely separate approach.

This clear-cut distinction gives us easy access to perform modifications to the way we output data, without having to access vital functions of a running simulation, or even pause it at all. Equally, when performing modifications to the simulation behaviour, we do not have to worry about matching the new functions to the already defined output charts.

We materialized this decision on two layers: within the Lua script, and in the entirety of the Java user interface.

Inside the script, we decided to have a set of event listeners, or observers, which simply pluck out required data from the running simulation, then pass it on. The only thing the Java executable ever does, apart from starting the simulation, is management of the user interface. Nothing in Java even remotely relates to the Sugarscape itself, the executable thus having the potential to plot completely unrelated data.

Page 32: Multi-Agent Simulations of Social Phenomena

4.2

We can

executa

and the

will talk

be on th

Develop

Java. W

correct

In orde

have in

firm be

support

This int

at othe

The Foun

n conceiva

able, which

e Sugarscap

k about it in

he Java imp

ped in Eclip

We carefully

functioning

er to stream

tegrated a

elief that t

t groups an

tegration co

r key points

ndation

bly divide

acts as ge

e model, w

n detail in th

plementatio

pse, the ap

y selected

g on all plat

mline the d

number of

this will fa

d readily av

omes at diff

s throughou

our softw

neral-purpo

which reside

he next cha

on of the ex

pplication is

all attache

tforms supp

evelopmen

open-sourc

cilitate its

vailable thir

ferent level

ut the applic

M

ware applica

ose user int

s wholly in

apter, the fo

ecutable pe

s not OS-sp

d packages

ported by th

t process o

ce, mostly o

use throug

rd-party doc

ls, most not

cation as a

Multi-Agent S

ation into

terface and

scripts. Igno

ocus of this

er-se.

pecific, since

s with the

he JDK.

of the Suga

off-the-shel

gh standar

cumentatio

tably at the

whole.

Simulations o

two main

d input / ou

oring the la

chapter wi

e we devel

intention o

arscape soft

f technolog

rdization, a

n.

e user inter

West Uof Social Phe

parts: the

utput data h

tter for now

ll for the m

loped it en

of facilitati

tware pack

gies with it.

already esta

rface level,

Universityenomena

3

e actual

handler,

w, as we

most part

tirely in

ng their

kage, we

It is our

ablished

but also

32

Page 33: Multi-Agent Simulations of Social Phenomena

333 Blaga Vi

4.2.1

Given t

operati

implem

all mod

platform

Moreov

feature

Rich Te

place in

the full

crunchi

are exte

also inc

ctor-Emanue

Front-End

that one o

ng systems

ment the use

dern distri

ms, at virtua

ver, Java p

s, among w

xt read / w

n our softw

y self-conta

ng in the ba

endable, wi

cluded into t

el

d: Java an

of the main

s, such as

er interface

butions of

ally no code

provides cr

which netwo

write capabi

are project

ained threa

ackground,

ith a good n

the Sugarsc

d Swing

n design g

Linux flavo

e in Swing. B

f Java, it

e refactorin

oss-platform

ork and data

lities. Most

t – nonethe

ad access in

without loc

number of e

cape applica

oals of thi

ours or eve

Because the

provides c

g cost what

m, uniform

abase acces

t of these, a

eless, one cr

nterface, wh

cking up th

existing thir

ation.

s software

n Mac OS,

e Swing pac

consistent

tsoever.

m access to

ss, OpenGL

admittedly,

ritical and h

hich enable

e applicatio

rd-party add

is easy p

, the natur

ckages are

results acr

o a numbe

rendering,

do not hav

heavily used

es us to do

on. On top o

d-ons, some

ortability t

ral solution

present in

ross all su

er of othe

as well as X

ve, as of no

d feature o

the heavy

of this, the

e of which w

o other

was to

virtually

pported

r useful

XML and

ow, their

of Java is

number

libraries

we have

Page 34: Multi-Agent Simulations of Social Phenomena

One of

Althoug

easy to

surface

integrat

output

from w

update

4.2.2

Closely

primari

industry

well in

corpora

4 The Pro

these libra

gh it somew

o use plotti

plotting w

ted method

data. The

within the s

automatica

Scripting

integrated

ly provides

y profession

excess of 30

ate applicat

ogramming La

ries is JFree

what lacks

ing package

widgets an

d of present

user simply

simulation,

ally.

Support:

d with and

s the basis

nals, who g

0 computer

ions.

nguage Lua, h

eChart, whi

in redraw s

es available

nd associat

ting the use

y has to re

as each tim

Lua 5.1

even driv

for the Su

generally us

r games, to

http://www.lu

M

ich we have

speed, JFre

e for the Ja

ed classes,

er with an in

eport the d

me unit pa

ving the us

ugarscape

e it for artif

date, as we

ua.org/

Multi-Agent S

e used for d

eeChart is o

ava langua

, the Plot

ntuitive inte

esired valu

asses, and t

ser interfac

simulation.

ficial intellig

ell as a sign

Simulations o

data outpu

one of the

ge. Contain

library off

erpretation

ues through

the desired

ce, the Lua

In wide u

gence, Lua

ificant num

West Uof Social Phe

t and visua

most comp

ning 2D gra

fers a con

of the simu

h specific fu

d plot wind

a scripting

use among

script has p

mber of indu

Universityenomena

3

alization.

plex, yet

aph and

venient,

ulation’s

unctions

dow will

system4

gaming

powered

ustrial or

34

Page 35: Multi-Agent Simulations of Social Phenomena

35 Blaga Victor-Emanuel

The actual library is fast, lightweight, portable and easily embeddable with both C / C++, and

with Java applications. Even though the actual source code is ANSI C in its entirety, there are

a number of third-party Java bindings, allowing the user to handle classes and call functions

of the main application from within Lua.

Dynamically typed, the language itself offers a simple to use procedural syntax, a data

description based on two-dimensional associative arrays, automatic garbage collection, as

well as the option of extending or modifying the language through function re-assignment.

We implement objects and classes, for example, simply by creating an array of functions and

variables, and then having other objects inherit their values.

Our integration of Lua script with the user interface has enabled us to dictate what is shown

on screen from within the simulation itself, or from an additional script, therefore

controlling on the fly both the options available to the user in the given context, as well as

the methods of output data representation.

Lua script already has a well-entrenched user base, which extends over not only the

dedicated Lua forums and newsgroups, but rather over the entire game modding

community, because so many games have implemented their AI using this scripting

language. Additionally, you can find manuals, reference books and a host of tutorials online,

all of which make it easy for even the most inexperienced programmer to take up learning

Lua.

4.2.3 Input Data: Java Advanced Imaging API

To smooth the user’s workflow in relation to setting the stage for the simulation, we have

decided to import the Sugarscape’s environment from TIFF images, and translate it into

hard data, and use it further in the simulation’s mechanics. Taking into account that most of

the times, the user will want to make a map of resources on which the agents can roam, the

most natural way to do it would be from an image editing software package. Our choice for

the specific TIFF image format derived from a number of considerations, among which the

fact that TIFF is not a proprietary format, its high data capacity (4 GB of pixel data), its

support for layers, as well as for arbitrary embedded data, unrelated to the picture itself.

Page 36: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

36

Since our data model called for an environment that held multiple resources, which could

each fluctuate at all locations according to minimum and maximum values, we chose to

interpret the TIFF image as follows:

• the image as a whole stands for the entire environment

• each pixel represents a location in the environment

• each layer represents a resource held by the environment

• each layer’s red channel represents the minimum possible resource value, on a per-

pixel basis

• each layer’s green channel represents the maximum possible resource value, on a

per-pixel basis

• each layer’s blue channel represents the current resource value at the outset of the

simulation, on a per-pixel basis

To this end, we have chosen the Java Advanced Imaging API5, linked against the Java Image

I/O library6, both of them being open-source solutions and having a wide user base,

community and even corporate support. While other third party libraries would have

permitted stand-alone reading of TIFF images, this combination adds certain flexibility to the

whole process, and most importantly, allows for 16-bit red, green and blue channel values,

feature critical to approximating real-life data with this software.

5 Java Advanced Imaging, http://java.sun.com/javase/technologies/desktop/media/jai 6 Java Image I/O, http://java.sun.com/javase/6/docs/technotes/guides/imageio/index.html

Page 37: Multi-Agent Simulations of Social Phenomena

37 Blaga Victor-Emanuel

4.3 Upwards and Onwards

Of real interest, nonetheless, is the actual simulation, residing in the Lua script files. More of

a framework than an actual simulation, our implementation of Sugarscape makes wide use

of the loose rules of Lua to achieve a level of flexibility impossible to attain through any

other programming paradigm. Convey this thought better requires a short description of the

inner workings of Lua script.

To begin with, every single variable and function in Lua is stored as an entry in a table. The

global table _G contains the name and value of all functions and variables available in Lua

memory space, the latter of which can very well be tables themselves. This allows the user

to think about and use Lua similarly to a database, and means that the user treats functions

as variables, in the sense that any function can take the place of another by simply placing

the two on opposite ends of an “equals” sign. All of this is possible since tables in Lua hold

names, type and references to memory addresses, therefore allowing for swift changes in

any of these fields.

Secondly, there is no such thing as classes in Lua, in spite of our object-oriented approach to

building the Sugarscape. What we have are tables with variables and functions, that stand

for objects – these, in turn, can stand as prototypes for other objects. Consequently, when

we define the Agent table, for example, we could have it function both as a class, and as an

instance of itself. Moreover, we can add numerous distinct functions and variables to all

objects that inherit Agent, to the point that all derived agents are unique not only by value,

but also by behaviour and elements contained.

Having absorbed all this knowledge, we set out to lay the groundwork for our model.

Apparently, the Sugarscape needed a whole set of independent data structures to hold itself

and its occupants together: a three dimensional array for the environment, a cross-

referenced hierarchical structure for the population and its groups, sets of formatted data

for agent properties, and specialized containers for holding and passing on the various types

of gathered output data. Building and having these disparate structures work together was

an unwelcome complication, so unifying them seemed in high order.

Page 38: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

38

The solution came in the form of a linked list

versatile enough to accommodate all these

requirements at the same time, in conjunction

with a set of descriptive classes derived rather

from real world concepts than from programming

abstractions. What sets this list apart is its

inherent capability of searching for and removing

objects based on their contained fields

and values, as well as the included

modular sorting mechanism that can

order the list according to user defined

criteria.

4.3.1 Living off the Land

The Sugarscape environment is composed

of individual locations (pixels), and layers

corresponding to the different types of

resources present. Mapping this two

dimensional lattice on a linked list

required having each location object store

references to its neighbours, and defining

a function of the environment to calculate

the position on the list of each location,

Page 39: Multi-Agent Simulations of Social Phenomena

39 Blaga Victor-Emanuel

based on its position on the X and Y axes.

Each location has a set of layer points, or resources – looking at this set is akin to taking out

a vertical section of the local soil sample. Each layer point corresponds to the amount of one

specific resource held by the current location.

Layers are more of a convenience class, since they are to layer points what the entire

environment is to locations. They provide easy access to neighbouring resources of the

same type, should the current simulation require any sort of dispersion, or area calculation.

By structuring the environment in this particular way, we add some sort of third dimension

to it, without having to go through the hassle of actually mapping it, or through the other

pain of having agents search and move along the Z-axis.

4.3.2 Part of a Community

We can view the agent population as a multitude

of sets that share elements, each element being

an individual agent. Since we are not fond of

mathematics, we shall go on to call those sets

groups, and not look back.

The population class has both a list of groups,

and one of individuals, very much in the same

way that the environment handles layers and

locations. The plot twist, however, comes when

we do not make a vertical section of each agent

to partition its internals, but instead opt to allow

the poor sod to belong to one, more, or no

groups whatsoever.

Fitting into a group is just a matter of facade, a

uniform to dress the otherwise unique agent.

We never meant groups to accommodate a

Page 40: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

40

homogeneous collection of agents, but rather to imbue these individuals with a sense of

belonging and a way to recognize one from another.

Furthermore, in order to have the user care about his minions, we allowed him to each

agent names, such as “Daisy”, or “Mr. Hyde”. This paves the way to pointing the odd man

out in a simulation of, say, the London bombings of July 2005.

The way our agents act bears both similarities and differences from the way real-world

people go about their business. The difference is that we cannot have everybody act at the

same time, since building a thread of execution for each agent, and then setting

semaphores for each possible resource is both computer-wise, and programmer-wise, hard

work, which should unmistakably be avoided. Thus, we implemented a queue, every agent

standing in line to put his virtual punch cards through the obviously virtual IBM mainframe.

What we brought about in our simulation, however, is the general unfairness of life. Since

resources on our landscape are limited, agents at the front of the queue will have the

chance of getting much better return on their movement and associated actions than the

ones at the end. The ones discriminated against will therefore have a much more significant

chance of dying of starvation, for example, and sadly, we have not implemented the

afterlife... yet.

Given this inherent favouritism, we reasoned that instead of leaving it to pure chance, we

should account for this variable by letting the user decide who his loved agents are. The

population therefore uses the sorting mechanism of the agent list to re-arrange them in the

line, so the user can get his desired action order each time unit.

Another fortuitous similarity to real life is that the agents are greedy, be that an appetite for

food, money, or even other people. Apart from their modifiable decision-making and

movement algorithms, the agents all have a backpack, which they like to fill with goodies.

However, as living also means turning useful stuff into nothing, at best, and into bad stuff, at

worst, each time unit these agents will eat something from that backpack, as well as hoard

some more while reaping the land’s product.

In programming terms, this means that each agent has a resources object that contains a list

of possessions. The agent also has a metabolism function that eats away at those

Page 41: Multi-Agent Simulations of Social Phenomena

41 Blaga Victor-Emanuel

possessions, or even adds to some of them, as time passes. Should the agent reach a lower

or upper limit of one of those resources, he will die of starvation, inability to pay the rent, or

toxin build-up in his body, as convenient examples.

4.3.3 I Spy

Privacy is of no concern to agents in Lua space,

because, simply put, private variables do not exist.

Algorithmically speaking, a programmer would have

to go through a lot more than the devil had to, in

order to get agent Adam and agent Eve to realize

how exposed they are to the world.

The upside of this problem is that we can build true

event listeners in Lua, which do not have to rely on

the actual agents to report their status, but rather

strap themselves, lock and load, then go in foraging

for the needed information. The simulation goes on

undisturbed, blissfully ignorant of the myriad of eyes

checking in on its status every time unit.

We called these listeners Events, and their overlord, Event Viewer, for maybe no other

reason than lack of a good idea of what they will be supposed to do, finally. Each such event

stores a list of values that it looks for, then waits for the viewer to come in, harvest that

data, and output it on screen, through the Java user interface.

Evidently, we leave the user to build the data harvesting algorithms and to decide upon the

form in which to represent this data, since the framework is supposed to help in building

any kind of custom simulation. What is fixed is the fact that each time unit, after the agents

have accomplished their temporary goals, the Events drop in and record progress from the

comfort of their flying saucers.

Page 42: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

42

4.3.4 Full Circle

Completing these structures are the functions and constructs pertaining strictly to the

current simulation, which we meant to leave room for in the “Test” class, defined solely by

the user.

Here one can add and override existing model functionality, insert agent and environment

properties, and define the event listeners. Therefore, we leave both data and its particular

on screen presentation completely to user preference.

The simulation will not work without user intervention, because we did not define any

proper actions in the framework. The framework leaves all environment regeneration rules,

all individual and aggregate agent behaviour, and any other miscellaneous events at the

user’s discretion. Moreover, interpretation of input data is highly customizable, to allow for

changes in environment layer number, initial agent group creation and simulation time

span. Even so, the framework does ship with an example test class and a working factory.

Page 43: Multi-Agent Simulations of Social Phenomena

43 Blaga Victor-Emanuel 5 Conclusions

5.1 Lessons Learned

At the end of the day, a retrospective analysis of the development process seems in order,

highlighting what went right and not so right throughout the duration of this project.

5.1.1 What Went Right

The best decision relevant to this project was starting early. It took almost a year to

complete, with an on and off development program, and the pre-production stages have

been critical to understanding and planning for the challenge.

At this stage, we took decisions regarding the outsourced components of the project, and

the technologies involved – we drew up a basic initial plan of the simulation, and started the

documentation process for the various libraries. The two initial choices that proved to be

right were Lua script and TIFF image import.

While studying the former, we discovered the potential for variable agent behaviour,

although admittedly, we initially based our choice for it on the fact that a huge number of

computer games were already using Lua as an AI scripting language. The choice for using

TIFF files, however, came about when we comprehended that the structure of the

environment called for multiple resource strata on the same landscape. Connecting this

requirement to the concept of multi-layered image formats was simple, and the two

available options were Adobe PSD files and TIFFs. Since the former is a proprietary format,

we went for the second, and it proved to be a breeze to work with.

As opposed to other projects, we did not dive into programming from the very beginning.

Instead, we have gone through the stage of UML modelling, feature rationalization and user

Page 44: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

44

interface sampling. Skipping this phase would have led to a much more complex and hard to

understand design, and would have probably impeded further development.

Prototyping most aspects of the Sugarscape model, and each user interface component has

also helped in skipping annoying and convoluted debugging further off along the line. The

first two incarnations of the model served as working projects for other classes, requiring

early functionality and hence a modular approach to content additions. In the end, this

proved to be the stepping-stone from a functional application to a usable and adjustable

framework.

The first version of the model would have gone for a mixed hard-coded and scripted

approach, which would not only have gratuitously complicated programming, but also

limited the versatility of the framework. Recognizing the problem, we never even started

the hard-coded version, but went straight for the clear-cut division between scripted model

and static user interface executable.

Developing the second version of the model in tandem with the first user interface

prototype called for a number of modifications in the way we looked at the Event Viewer

and its bridge to the hard-coded application. We rethought a number of functions and

moved them to the actual executable, in order to allow the conversion from raw data to

user-friendly diagrams and plots.

Finally, we held back on putting the documentation on paper from the start, decision that at

first seems bad, as one would think that with time we would have forgotten the details and

inner-workings of the written code. What we did with time was to modify and rewrite the

framework multiple times over, so we avoided recording the documentation repeatedly

with each incremental alteration.

By foregoing documentation, we do not imply sacrificing code comments, as virtually each

line of Lua code has comments to provide an easy to read description of every function of

the Sugarscape model.

Page 45: Multi-Agent Simulations of Social Phenomena

45 Blaga Victor-Emanuel

5.1.2 What Went Wrong

Initially, we went for C++ with Lua integration for the standalone executable, attempting to

write the code in Eclipse CDT7 with MinGW8 compiler. Since cross-platform usage was a

requirement, the proposed goal was to stick as much as possible to the ANSI C++ standards,

and attach packages of cross-platform static or dynamic libraries for any added

functionality.

We therefore chose Trolltech’s Qt9 library, and added its Qwt add-on, Qt Widgets for

Technical Applications10, which was supposed to deal with chart and graph plotting.

Unfortunately, integrating Qt and Qwt with Lua proved to be somewhat of a pain, and the

real showstopper was the lack of any meaningful documentation or user support for Qwt.

Performance was also horrible, to the extent that simple scatter plots had slow redraw

rates, and creating other types of graphs was undocumented.

In addition, picking Adobe GIL11 linked against LibTIFF12 for image import, though both

seeing widespread use, was an unfortunate one, for the reason that the former will only

compile in Microsoft Visual Studio.

The answer was to switch to Java at the end of the development process, and redo the

entire user interface, image import routines and Lua script handling. Fortunately, we

promptly managed to find alternative libraries for the outsourced code, but the user

interface now looks a bit rushed, mostly because it is.

The bottom line, however, is that we needed to learn to adapt and port important sections

of code from one programming language to another in record time, skill learned on the

front line, so to speak, rather than out of curiosity.

7 Eclipse C/C++ Development Tooling – CDT, http://www.eclipse.org/cdt/ 8 Minimalist GNU for Windows, http://www.mingw.org/ 9 Qt: Cross-Platform Rich Client Development Framework, http://trolltech.com/products/qt 10 Qt Widgets for Technical Applications, http://qwt.sourceforge.net/ 11 Adobe Generic Image Library, http://opensource.adobe.com/wiki/display/gil/Generic+Image+Library 12 LibTIFF – TIFF Library and Utilities, http://www.libtiff.org/

Page 46: Multi-Agent Simulations of Social Phenomena

West UniversityMulti-Agent Simulations of Social Phenomena

46

5.2 Like, Finally

An agent-based model for social simulations, Sugarscape brings a bottom-up approach to

pattern prediction and analysis in a volatile environment. This specific implementation aims

at taking the model one step further, by adding the flexibility and trial-and-error approach

that Lua script allows for, to the otherwise complex and time-consuming process of building

an entire application.

Overall, this project attempts to bring a fresh approach to agent-based model simulation, in

a flexible and reusable manner, to grow into more than just a static, one-use assignment.

Attaining this goal was possible in part through the introduction of what we see as an

innovative paradigm for creating agent-based simulations, and in part by a good initial

selection of embedded technologies. The versatility of the Sugarscape itself lent most of the

usefulness of our framework, owing more to its initial authors than to the developer of this

particular incarnation.

The source code resides online, at: https://sourceforge.net/projects/artificial-soc

Page 47: Multi-Agent Simulations of Social Phenomena

47 Blaga Victor-Emanuel 6 Bibliography

Works Cited

Brantingham, P. L., Glasser, U., Kinney, B., Singh, K., & Vajihollahi, M. (2005). A Computational Model for Simulating Spatial and Temporal Aspects of Crime in Urban Environments. Burnaby: Simon Fraser University.

Epstein, J. M., & Axtell, R. (1996). Growing Artificial Societies. Cambridge: MIT Press.

Ierusalimschy, R. (2003, December 1). Programming in Lua. Retrieved July 1, 2007, from The Programming Language Lua: http://www.lua.org/pil

L, G., & S, B. (2005). FABLES: Functional Agent-Based Language for Simulations. Proceedings of the 2005 Conference on Generative Social Processes, Models, and Mechanisms (pp. 139-150). Chicago: Argonne National Laboratory and The University of Chicago.

Martin, R. C. (2002). Agile Software Development. New Jersey: Prentice Hall.

North, M. J., & M, M. C. (2007). Managing Business Complexity. New York: Oxford University Press.

Singh, K. (2005). An Abstract Mathematical Framework for Semantic Modelling and Simulation of Urban Crime Patterns. Burnaby: Simon Fraser University.

Zaft, G. C. (2001). Social Science Applications of Discrete Event Simulation: A Devs Artificial Society. Arizona: University of Arizona.