6.1.1一步一步学repast代码解释
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

6.1.1一步一步学repast代码解释

on

  • 821 views

 

Statistics

Views

Total Views
821
Views on SlideShare
821
Embed Views
0

Actions

Likes
0
Downloads
11
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Actions scheduled in a specified order should be added to ActionGroup set, which can be added to the Schedule.
  • The word WorldXSize and WorldYSize as well as other parameters such as NumAgents will appear in the Parameters window along with the RePast control toolbar. The string that tells RePast what parameter can be used is ‘NumAgents’ because RePast will look (automatically) for methods named "get" + the string and "set" + the string, hence "getNumAgents" and "setNumAgents."
  • The first line creates a new object of type 'SimInit'- note that this object has been imported as: import uchicago.src.sim.engine.SimInit;
  • Notice when the model is run that the values in the GUI are all zeros. It is good coding practice to have default values defined as constant variables.
  • Note that when the model runs, the 'Setup' routine runs. Press ‘Step' and the Build subroutine runs, calling successively BuildModel, BuildSchedule, and BuildDisplay. Keep this sequence in mind as we move forward. We can leave those lines of code in- they're harmless.
  • (1). import uchicago.src.sim.space.Object2DGrid; (2). Note that an integer (with a small i) is a data type, while an Integer (with a capital I) is a Java object. The value of the Integer object will be the amount of money found 'on the ground' at that point in the grid space. (3).CarryDropSpace(int xSize, int ySize) is the constructor to initialize the space object.
  • We now need to deposit some money on the landscape. To do this we will create a method of the CarryDropSpace object that will deposit an amount of money randomly around the objectSpace. We will then call that method right after the space object is created, in the buildModel method of the CarryDropModel object.
  • Actually, some of the lines of code that we have placed in the 'spreadMoney' method of the CarryDropSpace object will be useful for several reasons; thus we will pull them out into their own method (note also some variable name changes- this is just for style and limited improvements in clarity. As an added technical note, we check for a 'null' condition, but one should never occur because we initialize the whole grid to include values):
  • Makes 10 times the size of the space attempts to add the agent
  • Schedule object is important in RePast. But if we don’t use it, we can switch to extend SimpleModel instead of SimModelImpl.
  • When you run this code and step through it, the model is created, agents are green for a while, then turn blue and the disappear. For each one that disappears, however, another one appears. If you press 'play' you will see that the number of agents living, as reported every 10 timesteps, never changes.

6.1.1一步一步学repast代码解释 Presentation Transcript

  • 1. 一步一步学 RePast 建模 Introduction, (Sim)Model Object, CarryDrop
  • 2. The CarryDrop Model A RePast Tutorial by John Murphy by Junjie Sun Department of Economics Iowa State University
  • 3. RePast 模型的元素
    • 模型对象: Model Object —acts as the model itself
    • 空间对象: Space Object —controls the environment
    • 主体对象: Agent Object
  • 4. The (Sim)Model Object
    • 模型对象继承 Repast 的 SimModelImpl 类
    • Model object will extend RePast’s SimModelImpl object.
    • 负责对 Repast 控制条的响应
    • It will react to the RePast control toolbar.
  • 5. The SimModel Object—getName()
    • getName( ) 中可设置模型名称,让 Repast 调用返回,改名称会显示在控制条左上角
    • getName() replaces ‘RePast’ with the name of the project on the control toolbar.
    import uchicago.src.sim.engine.SimModelImpl; public class MyFirstRePastModel extends SimModelImpl { public String getName(){ return “ 第一个 RePast 模型” ; } }
  • 6. The SimModel Object—begin()
    • begin() 初始化模型的参数 .
    import uchicago.src.sim.engine.SimModelImpl; public class MyFirstRePastModel extends SimModelImpl { public String getName(){ return “ 第一个 RePast 模型” ; } public void begin(){ } }
  • 7. The SimModel Object— 惯例
    • RePast 模型中的方法一般与模型用到的类匹配,各相关的类时用子方法分开 .
    • 如初始化 Begin ()涉及到模型类、规划表类和显示类 . ,就用三个子函数把他们独立分开,以便于阅读和调试
    public void begin(){ buildModel();// 模型初始化 buildSchedule();// 规划表初始化 buildDisplay();// 显示初始化 } public void buildModel(){ } public void buildSchedule(){ } public void buildDisplay(){ }
  • 8. The SimModel Object—current code
    • import uchicago.src.sim.engine.SimModelImpl;
    • public class MyFirstRePastModel extends SimModelImpl {
    • public String getName(){
    • return “My First RePast Model”;
    • }
    • public void begin(){
    • buildModel();
    • buildSchedule();
    • buildDisplay();
    • }
    • public void buildModel(){
    • }
    • public void buildSchedule(){
    • }
    • public void buildDisplay(){
    • }
    • }
  • 9. The SimModel Object—setup()
    • The setup() 让模型返回到初始状态
    public class MyFirstRePastModel extends SimModelImpl { public String getName(){ return “My First RePast Model”; } public void setup(){ } public void begin(){ […]
  • 10. The SimModel Object—Schedule
    • Repast 模型有一个基础时间单元的概念(单位步长、节拍、时刻),相当于模型执行一步(控制条上的 Tick 计数加 1 ),模型每一步状态会整体切换到下一个状态
    • 每一步内的多个操作是不可分割的
    • Schedule 管理基础时间单元内执行哪些基础操作等
    • 当所有基本操作完成后,控制条上的 Tick 计数加 1 ,模型进行下一步 . 执行
    • 一个时刻内多个基础操作的执行顺序是随机
  • 11. The SimObject Model--Schedule import uchicago.src.sim.engine.SimModelImpl; import uchicago.src.sim.engine.Schedule; public class MyFirstRePastModel extends SimModelImpl { private Schedule schedule; public String getName(){ return “My First RePast Model”; } public void begin(){ buildModel(); buildSchedule(); buildDisplay(); } public void buildModel(){ } public void buildSchedule(){ } public void buildDisplay(){ } public Schedule getSchedule(){ return schedule; } }
  • 12. The SimModel Object--getInitParam
    • getInitParam 返回一个数组,数组内是字串类型,表示需要初始化设置参数名称列表。 returns an array of String variables (e.g., N agents)
    • 在初始化和设置中可以修改这些初始化参数。 This will change Ns by using the ‘setup’ and ‘initialize’ buttons.
    • 注意两点 :
        • 必须提供一个参数名列表’
        • 参数表中的每一个参数必须创建对应的 get 与 set 方法 .
  • 13. The SimModel Object--numAgents
    • First, lets insert the variable into our code.
    import uchicago.src.sim.engine.SimModelImpl; import uchicago.src.sim.engine.Schedule; public class MyFirstRePastModel extends SimModelImpl { private Schedule schedule; private int numAgents; public String getName(){ return “My First Repast Model”; } […]
  • 14. The SimModel Object--numAgents
    • Next, RePast structure requires us to provide ‘get’ and ‘set’.
    public Schedule getSchedule(){ return schedule; } public int getNumAgents(){ return numAgents; } public void setNumAgents (int na){ numAgents=na; } }
  • 15. The SimModel Object--numAgents
    • Next, RePast structure requires us to provide ‘get’ and ‘set’.
    public Schedule getSchedule(){ return schedule; } public String[] getInitParam(){ String[] initParams = {“NumAgents”}; return initParams; } public int getNumAgents(){ return numAgents; }
  • 16. The CarryDrop Model--Introduction
    • 模型介绍 .
      • 主体在一个格状空间内移动
      • 每个格子里可能包含一些金子,主体进入一个格子后如果里面没有其他主体可以拾起里面的金子
      • 主体总是移向相邻的 8 个格子 .
      • 当一个主体进入另外一个主体的格子时,进入的主体要给已经在格子的主体金子 .
      • 主体有一个随机的寿命,当一个主体死亡时,他的金子随机地扩散,发放到其他格子中去 . 同时随机诞生一个新的主体(随机不同的位置和随机寿命)
  • 17. The CarryDrop model
    • 三个文件
      • 模型对象实例
        • CarryDropModel
      • 主体对象实例
        • CarryDropAgent
      • 空间实例
        • CarryDropSpace
  • 18. 前面已经完成的代码
    • CarryDropModel
      • Variables: schedule, numAgents
      • Methods: setup(), begin(), buildModel(), buildSchedule(), buildDisplay(), getName(), getSchedule(), getInitParam(), getNumAgents(), setNumAgents(), main()
    • CarryDropAgent
    • CarryDropSpace
  • 19. 增加用户可以设置的参数
    • 主体个数 (NumAgents)
    • 世界尺寸 横坐标 X (WorldXSize)
    • 世界尺寸纵坐标 Y (WorldYSize)
  • 20. 把参数设置为类变量
    • Add worldXSize & worldYSize as class variables
    • private int worldXSize;
    • private int worldYSize;
    • 把参数设置到初始化参数列表中
    • String[ ] initParams = { "NumAgents" , "WorldXSize", "WorldYSize"};
    • 为每个参数增加 Get Set 方法
    • public int getWorldXSize(){
    • return worldXSize; }
  • 21. 编译运行模型
    • 创建一个新项目( Eclipse 或 JBuilder )
    • 增加三个文件
    • CarryDropModel.java CarryDropAgent.java CarryDropSpace.java
    • 这个模型没做任何事情,但会影响控制条的显示
  • 22. Codes to be Added in main Method
    • Creates a new obj. of type SimInit:
    • SimInit init = new SimInit();
    • Creates a new object of type CarryDropModel:
    • CarryDropModel model = new CarryDropModel();
    • Loads the model using the loadModel method of the Init obj.:
    • init.loadModel(model, "", false);
  • 23. Default Values for User-Settable Parameters (Step 6)
    • private static final int NUMAGENTS = 100;
    • private static final int WORLDXSIZE = 40;
    • private static final int WORLDYSIZE = 40;
    • private int numAgents = NUMAGENTS;
    • private int worldXSize = WORLDXSIZE;
    • private int worldYSize = WORLDYSIZE;
  • 24. Alerts in Subroutines (Step 7)
    • System.out.println("Running setup");
    • System.out.println("Running BuildModel");
    • System.out.println("Running BuildSchedule");
    • System.out.println("Running BuildDisplay");
  • 25. The Space Object (Step 8-1)
    • Define the variable for space object using RePast’s Object2DGrid:
    • private Object2DGrid moneySpace;
    • Fill moneySpace with Integer objects:
    • public CarryDropSpace(int xSize, int ySize){
    • moneySpace = new Object2DGrid(xSize, ySize);
    • for(int i = 0; i < xSize; i++){
    • for(int j = 0; j < ySize; j++){
    • moneySpace.putObjectAt(i,j,new Integer(0)); } } } }
  • 26. Q: How can you know the args in the methods / constructors? A: See RePast/Java API (Step 8-2)
    • Object2DGrid(int xSize, int ySize)  
    • Constructs a grid with the specified size.
    • Integer(int value)
    • Constructs a newly allocated Integer object that represents the primitive int argument.
    • putObjectAt(int x, int y, Object object)
    • Puts the specified object at (x,y)
  • 27. Need another parameter, the amount of money (Step 8-3)
    • In CarryDropModel.java, add:
    • private static final int TOTALMONEY = 1000;
    • private int money = TOTALMONEY;
    • String[ ] initParams = { &quot;NumAgents&quot; , &quot;WorldXSize&quot;, &quot;WorldYSize&quot;, &quot;Money&quot; };
    • public int getMoney() { return money; }
    • public void setMoney(int i) { money = i; }
  • 28. I ntegrate the Space Object into the Model (Step 9-1)
    • 空间对象在 Setup 中删除
    • Setup 在运行前全部清空
    • 每次重新运行时重新创建 BuildModel()
    • Allocate a variable for the space object:
    • private CarryDropSpace cdSpace;
    • Create the space object in buildModel():
    • cdSpace = new CarryDropSpace (worldXSize, worldYSize);// 创建
    • Destroy the space object in setup():
    • cdSpace = null;// 删除
  • 29. Overview : What’s been done in Step 1-9
    • CarryDropModel
      • Variables: schedule, cdSpace, numAgents, worldXSize, worldYSize, money
      • Methods: setup(), begin(), buildModel(), buildSchedule(), buildDisplay(), getName(), getSchedule(), getInitParam(), getNumAgents(), setNumAgents(), getWorldXSize(), setWorldXSize(), getWorldYSize(), setWorldYSize(), getMoney(), setMoney(), main()
    • CarryDropAgent
    • CarryDropSpace
    • Variables: moneySpace
    • Constructors: CarryDropSpace()
  • 30. 前面已经完成以下工作
    • 创建一个给定尺寸的空间对象
    • Start to fill out the CarryDropSpace class
      • Constructor to build a space of a given size
    • 增加空间类的变量
    • Added CarryDropSpace variable to the model
    • 在模型创建时增加创建空间对象
    • Added creation line in buildModel()
    • 在模型清空时删除空间对象
    • Added preparation line in Setup()
  • 31. Step 10 – 初始化空间类
    • 在格子里初始化金子 . 在空间类 CarryDropSpace 定义一个新方法 spreadMoney
    • CarryDropSpace 类的 新方法 spreadMoney() 在 CarryDropModel 类里调用 , 创建时调用
  • 32. Step 11 - Extracting reusuable code
    • getMoneyAt 空间里变量是否设置,如果没有设置设置为 0 ,如果已经设置则返回值 .
    • 随机查找一个格子, getMoneyAt ,取回当前金子数,然后再分配一个金子。直到金子分完为止
    • This could be useful outside of spreadMoney() or CarryDropSpace
  • 33. 可视化界面设计
    • 查看模型状态
    • 初始化可视环境
      • 查看 2 维格子空间
      • 白色背景
      • 金子可视化 Visible money, which squares have cash
      • 颜色深浅表示金子多寡
    • RePast 创建显示的相关类
      • DisplaySurface – 一个窗口
      • ColorMap – 颜色图
      • Value2DDisplay – links value sources from the model to colors according to the color map. Displays colors for each source in window when added to a DisplaySurface.
  • 34. Step 12 – Using the DisplaySurface
    • 在头部导入必要的库 Import the class
    • Create the variable
    • 如果有旧的 , 拆毁掉 “ Tear down”
    • 初始化 Instantiate
      • Pass in the model
      • Give it a name
    • Register the object
  • 35. Step 13 – A splash of color
    • Import the needed classes
    • Color is a standard Java class to represent color values
    • Will need access to the 2D grid of values
    • Add access method to CarryDropSpace
  • 36. Step 13 cont.
    • Create and initialize ColorMap in CarryDropModel
    • - Use loop to map values to shades of red
    • - Value of 0 (default) maps to white
    • Create Value2DDisplay object, displayMoney, using in 2D grid of values and our ColorMap
    • Add displayMoney to the window, displaySurf.
    • displayMoney will tell the display window what color (white or a shade of red) to put at each location in a 2D grid. It does this according to what value cdSpace currently has for each location in its grid.
  • 37. Step 14 – Generating the Display
    • Simply add this line to in the begin() method in CarryDropModel
    • Now run compile everything and
    • run CarryDropModel in your favorite IDE.
    • When RePast starts, hit the “Initialize” button.
  • 38. Step 15 – The Agents
    • Start with 4 attributes
      • Money
      • X position
      • Y position
      • Lifespan (stepsToLive)
  • 39. Step 15 cont. – Modifying CarryDropModel for Agents
    • Bounding Agent lifespans
      • Define default values
      • Define parameter variables
    • Add parameter names to allow users to edit values through RePast
    • Add access methods for parameter vriables
  • 40. Step 16 – Adding Agents to the model
    • Make a container to for all the Agents: ArrayList
    • Initialize the agentList in setup()
  • 41. Step 16 cont.
    • Define new method in CarryDropModel for adding Agents to the list
    • In buildModel(), make the desired number of calls to addNewAgent() to add Agents to the list
  • 42. Step 17 – A Space for Agents
    • Want to add agents to CarryDropSpace.
    • Space containing agents will be an Object2DGrid like moneySpace.
    • We need:
      • Agents to track their location
      • Some way to tell if a cell is occupied
      • Some way to add an Agent to the space
  • 43. Step 17 cont.
    • IsCellOccupied() checks if an Agent is already in a given cell in the agentSpace object.
    • addAgent() attempts to add an Agent in a random cell.
  • 44. Step 18 – Adding Agents to the space
    • Add a line in addNewAgent() in the CarryDropModel to add a agent to the CarryDropSpace.
    • Now whenever the model adds a new agent to the list, it will also attempt to add it to the simulation space.
  • 45. What’s been done in Step 1-18
    • In CarryDropModel:
    • imports, private variables, setup(), begin( buildModel(), buildSchedule(), buildDisplay() ), addNewAgent(), get(), set(), main()
    • In CarryDropAgent:
    • private variables, constructor, setXY(),
    • In CarryDropSpace:
    • imports, private variables, constructor, spreadMoney(), getMoneyAt(), getCurrentMoneySpace(), IsCellOccupied(), addAgent()
  • 46. Reporting (Step 19-1)
    • Providing a 'report' function that lists the values of the instance variables for a given object
    • Providing a unique 'ID' variable for each instance of an object
      • create a static variable that can be read by all instances of the class, and have the constructor increment it as a counter each time an agent is created.
  • 47. 'Report' function (Step 19-2)
    • In CarryDropModel:
      • public void buildModel(){ …
      • for(int i = 0; i < agentList.size(); i++){
      • CarryDropAgent cda = (CarryDropAgent)agentList.get(i);
      • cda.report(); } }
    • In CarryDropAgent:
      • public String getID(){ return &quot;A-&quot; + ID; }
      • public int getMoney(){ return money;}
      • public int getStepsToLive(){ return stepsToLive;}
      • public void report(){ System.out.println(getID() +
      • &quot; at &quot; + x + &quot;, &quot; + y + &quot; has &quot; + getMoney() +
      • &quot; dollars&quot; + &quot; and &quot; + getStepsToLive() + &quot;steps to live.&quot;); }
  • 48. Unique 'ID' variable (Step 19-3)
    • In CarryDropAgent:
      • public class CarryDropAgent { …
      • private static int IDNumber = 0;
      • private int ID;
      • public CarryDropAgent(int minLifeSpan, int maxLifeSpan){ …
      • IDNumber++;
      • ID = IDNumber;
      • … }
      • … }
  • 49. Displaying Agents (Step 20-1)
    • Create an Object2DDisplay object , add the agent list to that Object2DDisplay object's list of objects, and add it to the display surface
    • When the objects are added to the display surface, order matters . Money space first and then agent space
    • Make the agents able to be drawn by implementing the 'Drawable' interface
      • 'get' methods for their x and y positions
      • 'draw' method that takes a 'SimGraphics' object as an argument
  • 50. Codes for Displaying Agents (Step 20-2) -- Create an Object2DDisplay object, add it to the display surface, etc.
    • In CarryDropModel:
    • import uchicago.src.sim.gui.Object2DDisplay;
    • public void buildDisplay(){ …
    • Value2DDisplay displayMoney = new Value2DDisplay(cdSpace.getCurrentMoneySpace( ), map);
    • Object2DDisplay displayAgents = new Object2DDisplay(cdSpace.getCurrentAgentSpace());
    • displayAgents.setObjectList(agentList);
    • displaySurf.addDisplayable(displayMoney, &quot;Money&quot;);
    • displaySurf.addDisplayable(displayAgents, &quot;Agents&quot;);
      • … }
  • 51. Codes for Displaying Agents (Step 20-3) -- Make the agents able to be drawn by implementing 'Drawable'
    • In CarryDropAgent:
    • import java.awt.Color;
    • import uchicago.src.sim.gui.Drawable;
    • import uchicago.src.sim.gui.SimGraphics;
    • public class CarryDropAgent implements Drawable{ …
    • public int getX (){ return x; }
    • public int getY (){ return y; }
    • public void draw (SimGraphics G){
    • G.drawFastRoundRect(Color.blue);}…}
    • In CarryDropSpace:
    • public Object2DGrid getCurrentAgentSpace(){
    • return agentSpace; }
  • 52. Adding a Schedule and Some Action (Step 21-1) - Motivation
    • At this point the model will load and run, but it won't do anything. We want to add actions to the model, so that it can be run through time without error reporting
    • Focus on a simple task: getting agents to 'age'. Once per timestep, the agents 'stepsToLive' variable should go down one
    • Ignore the implications of what will happen when 'stepsToLive' hits zero, just focus on how RePast uses a Schedule object to manage actions in the simulation.
  • 53. Adding a Schedule and Some Action (Step 21-2) – Three things to do
    • Create a 'step' method in CarryDropAgent
    • Create the Schedule object in the 'setup' method; in this case we tell the object that we want it to run in timesteps with an interval of '1'
    • Specify what we want the Schedule object to do by creating an inner class ' CarryDropStep ' and adding it to the Schedule object using one of RePast's built-in functions. These built in functions allow you to specify when the action defined by the inner class is executed.
  • 54. Codes for creating a 'step' method and a Schedule object (Step 21-3)
    • In CarryDropAgent:
    • public class CarryDropAgent implements Drawable{ …
      • public void step(){
      • stepsToLive--; } }
    • In CarryDropModel :
    • public void setup(){…
    • schedule = new Schedule(1);
    • … }
  • 55. Codes for creating an inner class 'CarryDropStep' (Step 21-4)
    • In CarryDropModel:
    • import uchicago.src.sim.engine.BasicAction;
    • import uchicago.src.sim.util.SimUtilities;
    • public void buildSchedule(){…
    • class CarryDropStep extends BasicAction {
    • public void execute () {
    • SimUtilities.shuffle (agentList);
    • for(int i =0; i < agentList.size(); i++){
    • CarryDropAgent cda = (CarryDropAgent)agentList.get(i);
    • cda. step (); } } }
    • schedule. scheduleActionBeginning ( 0, new CarryDropStep()) ;
    • }
  • 56. Notes on 'shuffle' and 'scheduleAction Beginning' routine (Step 21-5)
    • 'shuffle' routine makes use of another RePast built-in tool, SimUtilities, to shuffle ArrayLists. It requires you to add colt.jar to your project's build path
    • 'scheduleActionBeginning' routine creates a new instance of inner class, CarryDropStep, to add. (0) indicates that we want the action to be taken in the first timestep
  • 57. Another Schedule Example (Step 22-1)
    • Motivation
      • Add another minor report function, for no other reason than to demonstrate another way to use the schedule object.
    • Two things to be added
      • A new method of the model class ' countLivingAgents ' that counts the agents whose stepsToLive is above zero - that is, they are still 'alive'
      • A new inner class ' CarryDropCountLiving ' that extends BasicAction and calls the new method. Note that this new inner class is paralleled to ' CarryDropStep ' in Step 21
  • 58. Codes for creating 'countLivingAgents' in CarryDropModel (Step 22-2)
    • private int countLivingAgents(){
    • int livingAgents = 0;
    • for(int i = 0; i < agentList.size(); i++){
    • CarryDropAgent cda = (CarryDropAgent)agentList.get(i);
    • if(cda.getStepsToLive() > 0) livingAgents++;
    • }
    • System.out.println(&quot;Number of living agents is: &quot; + livingAgents);
    • return livingAgents;
    • }
  • 59. Codes for 'CarryDropCountLiving' and how to add it to the Schedule object (Step 22-3)
    • public void buildSchedule(){…
    • class CarryDropCountLiving extends BasicAction {
    • public void execute(){
    • countLivingAgents();
    • }
    • }
    • schedule. scheduleActionAtInterval(10, new CarryDropCountLiving()) ;
    • }
    • Note that when adding the new CarryDropCountLiving object to the schedule object, we add it so that it is not executed every timestep, but rather is executed every 10th timestep.
  • 60. Displays and Schedules (Step 23-1)
    • Updates to the display elements must be scheduled. This is done by adding a line to the CarryDropStep schedule item, in the execute() method.
    • In CarryDropModel,
    • public void buildSchedule(){
    • System.out.println(&quot;Running BuildSchedule&quot;);
    • class CarryDropStep extends BasicAction {
    • public void execute() {…
    • displaySurf.updateDisplay(); }
    • }
    • … }
  • 61. Displays and Schedules (Step 23-2)
    • Add one more element to our code: agents who have more than 10 steps left to live will be green, and agents who are nearing the end of their lives will turn blue
    • In CarryDropAgent,
    • public void draw(SimGraphics G){
    • if(stepsToLive > 10)
    • G.drawFastRoundRect(Color.green);
    • else
    • G.drawFastRoundRect(Color.blue);
    • }
  • 62. The Circle of Life: Agents Dying and Being Born (Step 24-1) - Motivation
    • At the moment we have agents who are born and age; we count them as dead when their 'stepsToLive' goes below zero, but they're not really dead, and stepsToLive just keeps dropping. We need a die routine to have agents actually die and be removed from the simulation.
    • On the other hand, to avoid population decreasing, we also need a newborn routine through which new agents are born.
  • 63. The Circle of Life: Agents Dying and Being Born (Step 24-2) – Things to do
    • The die routine must do the following:
      • Remove the agent from the space object
      • Spread the agent's money across the space object
      • Remove the agent from the agent list
    • Add a 'reapDeadAgents()' method to the model
    • Add a 'removeAgentAt()' method to the space object
    • Create the reapDeadAgents() method so that it returns a count of the agents who died. We then create that same number of agents anew to have agents being 'reborn'
  • 64. Codes for adding 'reapDeadAgents()' to the model (Step 24-3)
    • In CarryDropModel,
    • private int reapDeadAgents(){
    • int count = 0;
    • for(int i = (agentList.size() - 1); i >= 0 ; i--){
    • CarryDropAgent cda = (CarryDropAgent)agentList.get(i);
    • if(cda.getStepsToLive() < 1){
    • cdSpace. removeAgentAt (cda.getX(), cda.getY());
    • cdSpace.spreadMoney(cda.getMoney());
    • agentList.remove(i);
    • count++; } }
    • return count;
    • }
  • 65. Codes for adding 'removeAgentAt()' to the space object and agent reborning (Step 24-4)
    • In CarryDropSpace,
    • public void removeAgentAt(int x, int y){
    • agentSpace.putObjectAt(x, y, null);
    • }
    • In CarryDropModel,
    • public void buildSchedule(){…
    • class CarryDropStep extends BasicAction {
    • public void execute() {…
    • int deadAgents = reapDeadAgents();
    • for(int i =0; i < deadAgents; i++){
    • addNewAgent(); } …}
    • }
    • … }
  • 66. What’s been done in Step 1-24
    • In CarryDropModel (extends SimModelImpl):
    • imports (Java & RePast), private variables, setup(), begin( buildModel(), buildSchedule(), buildDisplay() ),
    • private methods: addNewAgent(), reapDeadAgent(), countLivingAgents(),
    • public access methods: get(), set(),
    • public static void method: main()
    • In CarryDropAgent (implements Drawable):
    • imports (Java & RePast), private variables, constructor,
    • public access methods: get(), set()
    • public utility methods: report(), draw(), step()
    • In CarryDropSpace:
    • imports (RePast), private variables, constructor,
    • public access methods: get(), set()
    • public utility methods: spreadMoney(), IsCellOccupied(), addAgent(), removeAgentAt()
  • 67.
    • Step 25: Agents Learn Their Place - Making agents know where they are in
    • space Step 26: Agents Get Money - A 'take money' function that allows agents to pluck money from the landscape
    • Step 27: Agents on the Move - Making it possible for agents to move around the landscape
    • Step 28: Money Changing Hands - When agents collide they exchange money
    • Step 29: Probing the Space and the Agents - RePast allows the model to be interrogated in the GUI
    • Step 30: Adding a Chart - Using RePast for displaying data in a chart
    • Step 31: Adding a Histogram - Using RePast for displaying data in a histogram
    • Step 32: Conclusion - Final comments and JavaDoc