SlideShare a Scribd company logo
Emilio Serrano, Ph.d.
Polytechnic University of Madrid
Madrid, Spain
eserrano@gsi.dit.upm.es
1
Developing social simulations with
UbikSim
Introduction
2
 UbikSim is a framework to develop social simulation which emphasizes:
 The construction of realistic indoor environments
 The modeling of realistic person behaviors
 The evaluation of Ubiquitous Computing and Ambient Intelligence systems
 UbikSim is written in Java
 and employs a number of third-party libraries such us SweetHome3D and MASON.
 UbikSim has a GPL license
 So its code is not only free (“libre”), but yours has to be it likewise.
 Website: http://ants.dif.um.es/staff/emilioserra/ubiksim/
 GitHub reposository: https://github.com/emilioserra/UbikSim
 Authors:
 Juan A. Botía , juanbot@um.es, Pablo Campillo, pablocampillo@um.es, Francisco
Campuzano, fjcampuzano@um.es, Emilio Serrano, emilioserra@um.es
 Software necessary for UbikSim:
 Java and Java3D
 Make sure you install Java3D correctly!
 NetBeans
 (recommended IDE, but not mandatory)
 The project: claseABSS
 (it uses UbikSimIDE.jar, available in GitHub)
Creating an environment
3
 Open NetBeans and the project UbikSimIDEclass.
 Execute the class StartUbikEditor
 Create a new environment model as follows:
Creating an environment 2
4
 Some clues:
 Add the walls for a big square
room
 Split it with another wall
 Add the floor with “create room”
 Add an open door
 Add aTestPerson
 Add a couple of NodeGraphs
 Why?
 Double click in the rooms and in
the agent to put them a name
 Why?
 Can you do something a little more
complicated?
Creating an environment 3
5
 The environment can be saved and used
 The “config.pros” file tells UbikSim the environment to use
 Now, it says “./environments/hotel.ubiksim”
 Open this environment that will be used in this class
 Explore the environment
 Clue: use the virtual visit in the 3D view menu which introduces an “observer
agent”
Running a simulation with GUI
6
 Run the class EscapeSimWithGUI
 It is the main class of the NetBeans project
 Run the simulation just like any other
simulation in MASON
 Explore the console menu
 “Pause” generates the scenario and displays
 Check the displays UbikSim3D and UbikSim
2D
 Execute just one step with play
 What happened?
 Keep executing pressing pause again
 Repeat step by step (stop, pause, button play
repeatedly)
 What problems do you see in this evacuation?
Running a simulation with GUI 2
7
 Simulations with GUI have to extend UbikSimWithUI
 The method start is called after pressing pause when the
environment and its variables are instantiated
 It can be used, among others, to register new displays
 (any Jframe that you could find useful to monitor/change the simulation
behavior)
 It should have a main method to start it
public static void main(String []args) {
escapesim = new EscapeSim(System.currentTimeMillis());
EscapeSimWithGUI vid = new EscapeSimWithGUI(escapesim);
Console c = new Console(vid);
c.setIncrementSeedOnStop(false);
c.setVisible(true);
}
Running a simulation without GUI
8
 Run the class EscapeSim
 What is the difference?
 Displays are very important to debug
 But they disappear in experimentation
 Simulations without GUI extends Ubik
 And are called by simulations with GUI (see previous slide).
 They have several methods to create the simulation
 The random seed is very important
 It ensures replicability
 It can be loaded from file, fixed, or depending on the current time.
public EscapeSim(long seed) {
super(seed);
}
public EscapeSim() {
super();
setSeed(getSeedFromFile());
}
Running a simulation without GUI 2
9
 The final condition must be defined
 In the main method, maxTimeForExecution steps are performed
 If EscapeSim(long seed,int timeForSim) is used, an agent finishes the simulation
public EscapeSim(long seed, int timeForSim) {
super(seed);
EscapeMonitorAgent.setStepToStop(timeForSim);
}
public static void main(String []args) {
EscapeSim state = new EscapeSim(System.currentTimeMillis());
state.start();
do{
if (!state.schedule.step(state)) break;
}while(state.schedule.getSteps() < maxTimeForExecution);//
state.finish();
}
Running a simulation without GUI 3
10
 Usually, some treatment is needed after setting up the environment
and before executing the simulation
 Again, method start is used
 Some examples are: adding a logger/analyzer/monitor agent, creating
more agents in the environment, changing agents’ name, etcetera
 Since simulations with GUI call the ones without GUI, this method is
executed in all of them.
public void start() {
super.start();
ema= new EscapeMonitorAgent(this);
Automaton.setEcho(false);
//add more people
PersonHandler ph= getBuilding().getFloor(0).getPersonHandler();
//ph.addPersons(20, true, ph.getPersons().get(0));
//change their name
ph.changeNameOfAgents("a");
}
Running batch experiments
11
 Run the class EscapeSimBatch
 Explore the files which have been created in the project folder
 What conclusions can you reach?
 An isolated simulation cannot determine anything
 Explore the class
 How many experiments are conducted?
 How long does it take each?
 What object is filling the generic logger?
 Next section treats the log of events
Running batch experiments 2
12
 A batch class must
 Iterate over the different parameters of the simulation experimentsForDifferentParameters()
 Execute a batch of experiments for those parameters batchOfExperiments()
 Execute one experiment for each element of the batch oneExperiment(int seed)
 The series of seeds must be repeated for each different combination of parameters
 Perform statistical operations on results and print them in files
 The example assumes 2 operations (in 2 files): mean and standard deviation
 It can be extended easily extended for more operations
 Can you add a third file with an interesting operation?
private static ArrayList<GenericLogger> batchOfExperiments() {
…
r.add(GenericLogger.getMean(listOfResults));
r.add(GenericLogger.getStandardDeviation(listOfResults));
}
private static void printInFile(ArrayList<GenericLogger> r) throws IOException {
PrintWriter w1 = new PrintWriter(new BufferedWriter(new FileWriter(fileName
+ " mean.txt", false)));
PrintWriter w2 = new PrintWriter(new BufferedWriter(new FileWriter(fileName
+ " sd.txt", false)));
…
if (i % 2 == 0) {//mean in pair positions
…
}
Logging interesting data
13
 As seen, batch experiments deals with genericLogger objects which are filled by an
EscapeMonitorAgent
 As seen, this agent is created in the start method of the simulation without GUI
 So it is also present in batches and experiments with GUIs
 It is a very simple MASON agent which extends from MonitorService, requiring to
define
 register():To be included in the schedule
 step(SimState ss):To perform actions which basically are:
 Fill a generic logger (or your favorite data structure)
 Check if the simulation has to finish to kill it
 Can you find another interesting metric and log it?
public void register() {ubik.schedule.scheduleRepeating(this, 1);}
…
public void step(SimState ss) {
…
double[] toLogInStep ={ people.size(), peopleCloseToFire};
genericLogger.addStep(toLogInStep);
…
if(ubik.schedule.getSteps()>=maxStepToStop){
ubik.kill();
}
…
Another simple agent, the fire
14
 The fire, as the EscapeMonitorAgent, has a method step and is registered in the
schedule when created
 It has a simple method to know if people is close to fire
 But here, we are interested in the method insertInDisplay()
 It paints a fire in the displays
 It is called by the simulation with GUI, why?
 It allow developers to insert any object
 It is important to have the 3D files in the same folder of the class that uses them
 Explore the folder UbikSimClaseABSSsrcsimappubikbehaviorsescape
 It has a .obj or .dae with the 3D object and .jpg or .png with the “texture”
o The files position matters!
 Can you make the flame spread?
public boolean tauchingFire(Person p) {
return PositionTools.isNeighboring(p.getPosition().x, p.getPosition().y,
initialPosition.x, initialPosition.y, steps);
}
Where can an agent be?
15
 In the display
 It is shown in the 3D and 2D display of the building
 It uses “3D coordinates” (see PositionTools)
 In the schedule
 Its method step is called each step
 In the “space” (SparseGrid2 of the class ElementHandler).
 It uses “MASON coordinates” (see PositionTools)
 It can be considered “an obstacle” (method isObstacle in OfficeFloor)
 Can you think a case where something is in the schedule but not in the
display?
 Methods PositionTools.getOutOfSpace,PositionTools.putInSpace
public void add(Person p) {
persons.add(p);
grid.setObjectLocation(p, p.getPosition().getX(), p.getPosition()
.getY());
}
public void register() {
ubik.schedule.scheduleRepeating(this, 1);
}
Modeling people
16
 We have seen a couple of simple agents
 MASON only gives you the step()
method
 UbikSim proposes a top-down
approach for complex agents
 This involves the breaking down of a
human behavior to gain insight into its
compositional sub-behaviors
 The class Automaton implements it
 Automaton is a hierarchical automaton of
behaviors (HAB)
 Each state is another automaton (with sub
states which also are automata).
 There is a main automaton, father
automata and subordinate automata
 Maybe you see it better as a tree of behaviors
 Where is the transition function?
Modeling people 2
17
 The transitions in the automaton are made automatically by an interpreter
 You can check the nextState method of the Automaton class
Modeling people 3
18
 So,TestPerson delegates in anAutomaton calledTestAutomaton
 AutomatonTestPerson extendsAutomaton, so 4 methods have
to be implemented
 (1)The constructor
 If the person delegates directly in this automaton, only the person is passed
 Otherwise, more information is needed (priority, duration, name of state, etc)
public void step(SimState state) {
…
if(automaton==null) {
automaton = new sim.app.ubik.behaviors.escape.AutomatonTestPerson(this);
}
automaton.nextState(state);
}
public AutomatonTestPerson(Person personImplementingAutomaton) {
super(personImplementingAutomaton);
}
public Move(Person personImplementingAutomaton, int priority, int duration, String
name, Room room) {
super(personImplementingAutomaton,priority,duration,name);
…
}
Modeling people 4
19
 (2) createNewTransitions
 It is called in each step
 Besides generating transitions, any extra action/instruction can be included and it will be executed while the
Automaton has the control
 It generates and returns a list with the states that Automaton can take from the current state
 Look out!, they are not taken, just planned; the interpreter will do it.
 isTransitionPlanned can be used to make sure that some transition are already planned
public class AutomatonTestPerson extends Automaton {
…
public ArrayList<Automaton> createNewTransitions(SimState simState) {
ArrayList<Automaton> r=null;
if(!this.isTransitionPlanned("goToExit")){
r=new ArrayList<Automaton>();
Room exit= PositionTools.closestRoom(p, STAIRS);
r.add(new Move(p,10,-1,"goToExit",exit));
r.add(new Disappear(p, " escaped ", p.getName() + " escaped using " +
exit.getName()));
}
if(!p.hasBeenCloseToFire()){
if (sim.getFire().tauchingFire(personImplementingAutomaton)){
p.setCloseToFire(true);
sim.getMonitorAgent().peopleCloseToFire++;
}
}
return r;
}
Modeling people 5
20
 (3) getDefaultState
 The main automaton (level 0), the highest in the hierarchy, never ends if a cyclic behavior
wants to be modeled (and therefore a default state must be given)
 Otherwise, it usually returns null to return control to the “automaton father” if no more
transitions are planned
public boolean isFinished(SimState state){
return destinyAchieved(state);
return super.isFinished(state);
}
 (4) isFinished
 As said, the main automaton usually does not have to finish
 Besides, If there are no transitions planned and no default state is given the automaton
ends and the control is given to the father automatically
 It also ends automatically if the time given in the constructor ends
 But, this method may be necessary for extra finalization , like in Move Automaton
public Automaton getDefaultState(SimState simState) {
return new DoNothing(p,0,1,"doNothing");
}
Modeling people 6
21
 MoveToClosestExit is an example of subordinate automaton
 What is the difference between using Move or MoveToClosestExist in
this code?
 The moment of calculating the closest exit!
 With move it is calculated before going to the hall
 With MoveToClosestExit it is calculated when the agent has already visited the hall
public class AutomatonTestPerson extends Automaton {
…
public ArrayList<Automaton> createNewTransitions(SimState simState) {
…
Room exit= PositionTools.closestRoom(p, STAIRS);
r.add(new Move(p,10,-1,”checkHall",hall));
r.add(new Move(p,10,-1,"goToExit",exit));
//r.add(new MoveToClosestExit(p,10,-1,"goToExit"));
…
}
Modeling people 7
22
 This seems complicated, but in the end, there are very simple
states that Automaton delegates to.
 Automaton allows developers to divide the complexity of human
behaviors
 The simple states extends SimpleState and only has to define
nextState
public class Disappear extends SimpleState {
…
public void nextState(SimState state) {
if(!personImplementingAutomaton.isStopped()) {
if(message!=null) System.out.println(message);
personImplementingAutomaton.stop();
}
}
…
The final question
23
 Can you improve AutomatonTestPerson to implement a
better evacuation?
 Examples:
 if Fire is too close to an exit, it should not be used
 if there are too many people using an exit and others are free, they could
be used
 Clue: study the PositionTools class
Testing and debugging in UbikSim
24
 Debugging any multi-agent system is challenging, here some advice
 MASON tools can be used: inspectors an charts
 Make it as automatic as possible
 If the display is not needed, do not use it
 2D displays are way faster and clearer than 3D display
 Try to generate the conflictive situation at the beginning of the simulation
 Use the same random seed to reproduce always the same situation while testing
 Deal with just one agent or a few before trying the final environment
 An extra .ubiksim file can be generated for tests
 System.out in an agent will be executed withALLAGENTS
 The monitor agent is called once per step, so it is a good place to put messages
 To study an agent you can change its name and color from the code
 WithAutomaton.setEcho(true), the output of the interpreter is shown
Testing and debugging in UbikSim 2
25
 Output with Automaton.setEcho(true),
a1, MAINAUTOMATON pending transitions extended [goToExit, escaped ]
a1, MAINAUTOMATON automaton changes to state goToExit
a1, goToExit pending transitions extended [SimpleMove, simple move to (698,157) [editor
format: 3490,785], SimpleMove, simple move to (727,102) [editor format: 3635,510],
SimpleMove, simple move to (731,99) [editor format: 3655,495], SimpleMove, simple move to
(744,63) [editor format: 3720,315], SimpleMove, simple move to (744,63) [editor format:
3720,315]]
a1, goToExit automaton changes to state SimpleMove, simple move to (698,157) [editor format:
3490,785]
a1, goToExit automaton finished SimpleMove, simple move to (698,157) [editor format:
3490,785]
a1, goToExit automaton changes to state SimpleMove, simple move to (727,102) [editor format:
3635,510]
. . .
a1, MAINAUTOMATON automaton finished goToExit
a1, MAINAUTOMATON automaton changes to state escaped
26
Thank you very much for your attention

More Related Content

Viewers also liked (13)

PDF
Introducción a la simulación social basada en agentes (only in Spanish)
Emilio Serrano
 
PDF
Infrastructure for forensic analysis of multi-agent systems
Emilio Serrano
 
PDF
Casos de sistemas inteligentes (only in Spanish)
Emilio Serrano
 
PDF
An Explanation-Based Alert Management Tool for Basic AAL Systems
Emilio Serrano
 
PDF
A qualitative reputation system for multiagent systems with protocol-based co...
Emilio Serrano
 
PDF
Articial societies immersed in an Ambient Intelligence Environment
Emilio Serrano
 
PDF
Un prototipo para el modelado de un sistema de metaheurísticas cooperativa...
Emilio Serrano
 
PDF
TOWARDS SOCIO-CHRONOBIOLOGICAL COMPUTATIONAL HUMAN MODELS
Emilio Serrano
 
PDF
An Approach for the Qualitative Analysis of Open Agent Conversations
Emilio Serrano
 
PDF
Creating and validating emergency management services by social simulation a...
Emilio Serrano
 
PDF
Desarrollo y evaluación de sistemas de inteligencia ambiental con UbikSim
Emilio Serrano
 
PDF
Study and development of methods and tools for testing, validation and verif...
Emilio Serrano
 
PDF
Investigaciones y análisis de redes sociales (only in Spanish)
Emilio Serrano
 
Introducción a la simulación social basada en agentes (only in Spanish)
Emilio Serrano
 
Infrastructure for forensic analysis of multi-agent systems
Emilio Serrano
 
Casos de sistemas inteligentes (only in Spanish)
Emilio Serrano
 
An Explanation-Based Alert Management Tool for Basic AAL Systems
Emilio Serrano
 
A qualitative reputation system for multiagent systems with protocol-based co...
Emilio Serrano
 
Articial societies immersed in an Ambient Intelligence Environment
Emilio Serrano
 
Un prototipo para el modelado de un sistema de metaheurísticas cooperativa...
Emilio Serrano
 
TOWARDS SOCIO-CHRONOBIOLOGICAL COMPUTATIONAL HUMAN MODELS
Emilio Serrano
 
An Approach for the Qualitative Analysis of Open Agent Conversations
Emilio Serrano
 
Creating and validating emergency management services by social simulation a...
Emilio Serrano
 
Desarrollo y evaluación de sistemas de inteligencia ambiental con UbikSim
Emilio Serrano
 
Study and development of methods and tools for testing, validation and verif...
Emilio Serrano
 
Investigaciones y análisis de redes sociales (only in Spanish)
Emilio Serrano
 

Recently uploaded (20)

PPTX
Fake Science: Where it comes from and how to avoid beign part of it
Leonid Schneider
 
PPTX
FACTORS PREDISPOSING TO MICROBIAL PATHOGENICITY.pptx
Remya M S
 
PPTX
Comparative Testing of 2D Stroke Gesture Recognizers in Multiple Contexts of Use
Jean Vanderdonckt
 
PDF
Investigatory_project Topic:-effect of electrolysis in solar desalination .pdf
shubham997ku
 
PPTX
General properties of connective tissue.pptx
shrishtiv82
 
PDF
Impact of Network Topologies on Blockchain Performance
vschiavoni
 
PDF
We are Living in a Dangerous Multilingual World!
Editions La Dondaine
 
PDF
Sujay Rao Mandavilli public profile June 2025.pdf
Sujay Rao Mandavilli
 
PPTX
MEDICINAL CHEMISTRY PROSPECTIVES IN DESIGN OF EGFR INHIBITORS.pptx
40RevathiP
 
PPTX
1-SEAFLOOR-SPREADINGGGGGGGGGGGGGGGGGGGG.pptx
JohnCristoffMendoza
 
PDF
Relazione di laboratorio Idrolisi dell'amido (in inglese)
paolofvesco
 
PDF
SCH 4103_Fibre Technology & Dyeing_07012020.pdf
samwelngigi37
 
PPTX
Indian Podophyllum [Autosaved].pptx done
TahirChowdhary1
 
PPSX
Overview of Stem Cells and Immune Modulation.ppsx
AhmedAtwa29
 
PPTX
Chromosomal Aberration (Mutation) and Classification.
Dr-Haseeb Zubair Tagar
 
PPTX
History of Nursing and Nursing As A Profession UNIT-3.pptx
madhusrinivas68
 
PPTX
Single-Cell Multi-Omics in Neurodegeneration p1.pptx
KanakChaudhary10
 
PPTX
arun battery Li-ion presentation physics.pptx
lakshyanss2122
 
PDF
An Analysis of The Pearl by John Steinbeck
BillyDarmawan3
 
PDF
Enzyme Kinetics_Lecture 8.5.2025 Enzymology.pdf
ayeshaalibukhari125
 
Fake Science: Where it comes from and how to avoid beign part of it
Leonid Schneider
 
FACTORS PREDISPOSING TO MICROBIAL PATHOGENICITY.pptx
Remya M S
 
Comparative Testing of 2D Stroke Gesture Recognizers in Multiple Contexts of Use
Jean Vanderdonckt
 
Investigatory_project Topic:-effect of electrolysis in solar desalination .pdf
shubham997ku
 
General properties of connective tissue.pptx
shrishtiv82
 
Impact of Network Topologies on Blockchain Performance
vschiavoni
 
We are Living in a Dangerous Multilingual World!
Editions La Dondaine
 
Sujay Rao Mandavilli public profile June 2025.pdf
Sujay Rao Mandavilli
 
MEDICINAL CHEMISTRY PROSPECTIVES IN DESIGN OF EGFR INHIBITORS.pptx
40RevathiP
 
1-SEAFLOOR-SPREADINGGGGGGGGGGGGGGGGGGGG.pptx
JohnCristoffMendoza
 
Relazione di laboratorio Idrolisi dell'amido (in inglese)
paolofvesco
 
SCH 4103_Fibre Technology & Dyeing_07012020.pdf
samwelngigi37
 
Indian Podophyllum [Autosaved].pptx done
TahirChowdhary1
 
Overview of Stem Cells and Immune Modulation.ppsx
AhmedAtwa29
 
Chromosomal Aberration (Mutation) and Classification.
Dr-Haseeb Zubair Tagar
 
History of Nursing and Nursing As A Profession UNIT-3.pptx
madhusrinivas68
 
Single-Cell Multi-Omics in Neurodegeneration p1.pptx
KanakChaudhary10
 
arun battery Li-ion presentation physics.pptx
lakshyanss2122
 
An Analysis of The Pearl by John Steinbeck
BillyDarmawan3
 
Enzyme Kinetics_Lecture 8.5.2025 Enzymology.pdf
ayeshaalibukhari125
 
Ad

Developing social simulations with UbikSim

  • 1. Emilio Serrano, Ph.d. Polytechnic University of Madrid Madrid, Spain [email protected] 1 Developing social simulations with UbikSim
  • 2. Introduction 2  UbikSim is a framework to develop social simulation which emphasizes:  The construction of realistic indoor environments  The modeling of realistic person behaviors  The evaluation of Ubiquitous Computing and Ambient Intelligence systems  UbikSim is written in Java  and employs a number of third-party libraries such us SweetHome3D and MASON.  UbikSim has a GPL license  So its code is not only free (“libre”), but yours has to be it likewise.  Website: http://ants.dif.um.es/staff/emilioserra/ubiksim/  GitHub reposository: https://github.com/emilioserra/UbikSim  Authors:  Juan A. Botía , [email protected], Pablo Campillo, [email protected], Francisco Campuzano, [email protected], Emilio Serrano, [email protected]  Software necessary for UbikSim:  Java and Java3D  Make sure you install Java3D correctly!  NetBeans  (recommended IDE, but not mandatory)  The project: claseABSS  (it uses UbikSimIDE.jar, available in GitHub)
  • 3. Creating an environment 3  Open NetBeans and the project UbikSimIDEclass.  Execute the class StartUbikEditor  Create a new environment model as follows:
  • 4. Creating an environment 2 4  Some clues:  Add the walls for a big square room  Split it with another wall  Add the floor with “create room”  Add an open door  Add aTestPerson  Add a couple of NodeGraphs  Why?  Double click in the rooms and in the agent to put them a name  Why?  Can you do something a little more complicated?
  • 5. Creating an environment 3 5  The environment can be saved and used  The “config.pros” file tells UbikSim the environment to use  Now, it says “./environments/hotel.ubiksim”  Open this environment that will be used in this class  Explore the environment  Clue: use the virtual visit in the 3D view menu which introduces an “observer agent”
  • 6. Running a simulation with GUI 6  Run the class EscapeSimWithGUI  It is the main class of the NetBeans project  Run the simulation just like any other simulation in MASON  Explore the console menu  “Pause” generates the scenario and displays  Check the displays UbikSim3D and UbikSim 2D  Execute just one step with play  What happened?  Keep executing pressing pause again  Repeat step by step (stop, pause, button play repeatedly)  What problems do you see in this evacuation?
  • 7. Running a simulation with GUI 2 7  Simulations with GUI have to extend UbikSimWithUI  The method start is called after pressing pause when the environment and its variables are instantiated  It can be used, among others, to register new displays  (any Jframe that you could find useful to monitor/change the simulation behavior)  It should have a main method to start it public static void main(String []args) { escapesim = new EscapeSim(System.currentTimeMillis()); EscapeSimWithGUI vid = new EscapeSimWithGUI(escapesim); Console c = new Console(vid); c.setIncrementSeedOnStop(false); c.setVisible(true); }
  • 8. Running a simulation without GUI 8  Run the class EscapeSim  What is the difference?  Displays are very important to debug  But they disappear in experimentation  Simulations without GUI extends Ubik  And are called by simulations with GUI (see previous slide).  They have several methods to create the simulation  The random seed is very important  It ensures replicability  It can be loaded from file, fixed, or depending on the current time. public EscapeSim(long seed) { super(seed); } public EscapeSim() { super(); setSeed(getSeedFromFile()); }
  • 9. Running a simulation without GUI 2 9  The final condition must be defined  In the main method, maxTimeForExecution steps are performed  If EscapeSim(long seed,int timeForSim) is used, an agent finishes the simulation public EscapeSim(long seed, int timeForSim) { super(seed); EscapeMonitorAgent.setStepToStop(timeForSim); } public static void main(String []args) { EscapeSim state = new EscapeSim(System.currentTimeMillis()); state.start(); do{ if (!state.schedule.step(state)) break; }while(state.schedule.getSteps() < maxTimeForExecution);// state.finish(); }
  • 10. Running a simulation without GUI 3 10  Usually, some treatment is needed after setting up the environment and before executing the simulation  Again, method start is used  Some examples are: adding a logger/analyzer/monitor agent, creating more agents in the environment, changing agents’ name, etcetera  Since simulations with GUI call the ones without GUI, this method is executed in all of them. public void start() { super.start(); ema= new EscapeMonitorAgent(this); Automaton.setEcho(false); //add more people PersonHandler ph= getBuilding().getFloor(0).getPersonHandler(); //ph.addPersons(20, true, ph.getPersons().get(0)); //change their name ph.changeNameOfAgents("a"); }
  • 11. Running batch experiments 11  Run the class EscapeSimBatch  Explore the files which have been created in the project folder  What conclusions can you reach?  An isolated simulation cannot determine anything  Explore the class  How many experiments are conducted?  How long does it take each?  What object is filling the generic logger?  Next section treats the log of events
  • 12. Running batch experiments 2 12  A batch class must  Iterate over the different parameters of the simulation experimentsForDifferentParameters()  Execute a batch of experiments for those parameters batchOfExperiments()  Execute one experiment for each element of the batch oneExperiment(int seed)  The series of seeds must be repeated for each different combination of parameters  Perform statistical operations on results and print them in files  The example assumes 2 operations (in 2 files): mean and standard deviation  It can be extended easily extended for more operations  Can you add a third file with an interesting operation? private static ArrayList<GenericLogger> batchOfExperiments() { … r.add(GenericLogger.getMean(listOfResults)); r.add(GenericLogger.getStandardDeviation(listOfResults)); } private static void printInFile(ArrayList<GenericLogger> r) throws IOException { PrintWriter w1 = new PrintWriter(new BufferedWriter(new FileWriter(fileName + " mean.txt", false))); PrintWriter w2 = new PrintWriter(new BufferedWriter(new FileWriter(fileName + " sd.txt", false))); … if (i % 2 == 0) {//mean in pair positions … }
  • 13. Logging interesting data 13  As seen, batch experiments deals with genericLogger objects which are filled by an EscapeMonitorAgent  As seen, this agent is created in the start method of the simulation without GUI  So it is also present in batches and experiments with GUIs  It is a very simple MASON agent which extends from MonitorService, requiring to define  register():To be included in the schedule  step(SimState ss):To perform actions which basically are:  Fill a generic logger (or your favorite data structure)  Check if the simulation has to finish to kill it  Can you find another interesting metric and log it? public void register() {ubik.schedule.scheduleRepeating(this, 1);} … public void step(SimState ss) { … double[] toLogInStep ={ people.size(), peopleCloseToFire}; genericLogger.addStep(toLogInStep); … if(ubik.schedule.getSteps()>=maxStepToStop){ ubik.kill(); } …
  • 14. Another simple agent, the fire 14  The fire, as the EscapeMonitorAgent, has a method step and is registered in the schedule when created  It has a simple method to know if people is close to fire  But here, we are interested in the method insertInDisplay()  It paints a fire in the displays  It is called by the simulation with GUI, why?  It allow developers to insert any object  It is important to have the 3D files in the same folder of the class that uses them  Explore the folder UbikSimClaseABSSsrcsimappubikbehaviorsescape  It has a .obj or .dae with the 3D object and .jpg or .png with the “texture” o The files position matters!  Can you make the flame spread? public boolean tauchingFire(Person p) { return PositionTools.isNeighboring(p.getPosition().x, p.getPosition().y, initialPosition.x, initialPosition.y, steps); }
  • 15. Where can an agent be? 15  In the display  It is shown in the 3D and 2D display of the building  It uses “3D coordinates” (see PositionTools)  In the schedule  Its method step is called each step  In the “space” (SparseGrid2 of the class ElementHandler).  It uses “MASON coordinates” (see PositionTools)  It can be considered “an obstacle” (method isObstacle in OfficeFloor)  Can you think a case where something is in the schedule but not in the display?  Methods PositionTools.getOutOfSpace,PositionTools.putInSpace public void add(Person p) { persons.add(p); grid.setObjectLocation(p, p.getPosition().getX(), p.getPosition() .getY()); } public void register() { ubik.schedule.scheduleRepeating(this, 1); }
  • 16. Modeling people 16  We have seen a couple of simple agents  MASON only gives you the step() method  UbikSim proposes a top-down approach for complex agents  This involves the breaking down of a human behavior to gain insight into its compositional sub-behaviors  The class Automaton implements it  Automaton is a hierarchical automaton of behaviors (HAB)  Each state is another automaton (with sub states which also are automata).  There is a main automaton, father automata and subordinate automata  Maybe you see it better as a tree of behaviors  Where is the transition function?
  • 17. Modeling people 2 17  The transitions in the automaton are made automatically by an interpreter  You can check the nextState method of the Automaton class
  • 18. Modeling people 3 18  So,TestPerson delegates in anAutomaton calledTestAutomaton  AutomatonTestPerson extendsAutomaton, so 4 methods have to be implemented  (1)The constructor  If the person delegates directly in this automaton, only the person is passed  Otherwise, more information is needed (priority, duration, name of state, etc) public void step(SimState state) { … if(automaton==null) { automaton = new sim.app.ubik.behaviors.escape.AutomatonTestPerson(this); } automaton.nextState(state); } public AutomatonTestPerson(Person personImplementingAutomaton) { super(personImplementingAutomaton); } public Move(Person personImplementingAutomaton, int priority, int duration, String name, Room room) { super(personImplementingAutomaton,priority,duration,name); … }
  • 19. Modeling people 4 19  (2) createNewTransitions  It is called in each step  Besides generating transitions, any extra action/instruction can be included and it will be executed while the Automaton has the control  It generates and returns a list with the states that Automaton can take from the current state  Look out!, they are not taken, just planned; the interpreter will do it.  isTransitionPlanned can be used to make sure that some transition are already planned public class AutomatonTestPerson extends Automaton { … public ArrayList<Automaton> createNewTransitions(SimState simState) { ArrayList<Automaton> r=null; if(!this.isTransitionPlanned("goToExit")){ r=new ArrayList<Automaton>(); Room exit= PositionTools.closestRoom(p, STAIRS); r.add(new Move(p,10,-1,"goToExit",exit)); r.add(new Disappear(p, " escaped ", p.getName() + " escaped using " + exit.getName())); } if(!p.hasBeenCloseToFire()){ if (sim.getFire().tauchingFire(personImplementingAutomaton)){ p.setCloseToFire(true); sim.getMonitorAgent().peopleCloseToFire++; } } return r; }
  • 20. Modeling people 5 20  (3) getDefaultState  The main automaton (level 0), the highest in the hierarchy, never ends if a cyclic behavior wants to be modeled (and therefore a default state must be given)  Otherwise, it usually returns null to return control to the “automaton father” if no more transitions are planned public boolean isFinished(SimState state){ return destinyAchieved(state); return super.isFinished(state); }  (4) isFinished  As said, the main automaton usually does not have to finish  Besides, If there are no transitions planned and no default state is given the automaton ends and the control is given to the father automatically  It also ends automatically if the time given in the constructor ends  But, this method may be necessary for extra finalization , like in Move Automaton public Automaton getDefaultState(SimState simState) { return new DoNothing(p,0,1,"doNothing"); }
  • 21. Modeling people 6 21  MoveToClosestExit is an example of subordinate automaton  What is the difference between using Move or MoveToClosestExist in this code?  The moment of calculating the closest exit!  With move it is calculated before going to the hall  With MoveToClosestExit it is calculated when the agent has already visited the hall public class AutomatonTestPerson extends Automaton { … public ArrayList<Automaton> createNewTransitions(SimState simState) { … Room exit= PositionTools.closestRoom(p, STAIRS); r.add(new Move(p,10,-1,”checkHall",hall)); r.add(new Move(p,10,-1,"goToExit",exit)); //r.add(new MoveToClosestExit(p,10,-1,"goToExit")); … }
  • 22. Modeling people 7 22  This seems complicated, but in the end, there are very simple states that Automaton delegates to.  Automaton allows developers to divide the complexity of human behaviors  The simple states extends SimpleState and only has to define nextState public class Disappear extends SimpleState { … public void nextState(SimState state) { if(!personImplementingAutomaton.isStopped()) { if(message!=null) System.out.println(message); personImplementingAutomaton.stop(); } } …
  • 23. The final question 23  Can you improve AutomatonTestPerson to implement a better evacuation?  Examples:  if Fire is too close to an exit, it should not be used  if there are too many people using an exit and others are free, they could be used  Clue: study the PositionTools class
  • 24. Testing and debugging in UbikSim 24  Debugging any multi-agent system is challenging, here some advice  MASON tools can be used: inspectors an charts  Make it as automatic as possible  If the display is not needed, do not use it  2D displays are way faster and clearer than 3D display  Try to generate the conflictive situation at the beginning of the simulation  Use the same random seed to reproduce always the same situation while testing  Deal with just one agent or a few before trying the final environment  An extra .ubiksim file can be generated for tests  System.out in an agent will be executed withALLAGENTS  The monitor agent is called once per step, so it is a good place to put messages  To study an agent you can change its name and color from the code  WithAutomaton.setEcho(true), the output of the interpreter is shown
  • 25. Testing and debugging in UbikSim 2 25  Output with Automaton.setEcho(true), a1, MAINAUTOMATON pending transitions extended [goToExit, escaped ] a1, MAINAUTOMATON automaton changes to state goToExit a1, goToExit pending transitions extended [SimpleMove, simple move to (698,157) [editor format: 3490,785], SimpleMove, simple move to (727,102) [editor format: 3635,510], SimpleMove, simple move to (731,99) [editor format: 3655,495], SimpleMove, simple move to (744,63) [editor format: 3720,315], SimpleMove, simple move to (744,63) [editor format: 3720,315]] a1, goToExit automaton changes to state SimpleMove, simple move to (698,157) [editor format: 3490,785] a1, goToExit automaton finished SimpleMove, simple move to (698,157) [editor format: 3490,785] a1, goToExit automaton changes to state SimpleMove, simple move to (727,102) [editor format: 3635,510] . . . a1, MAINAUTOMATON automaton finished goToExit a1, MAINAUTOMATON automaton changes to state escaped
  • 26. 26 Thank you very much for your attention