6.1.1一步一步學(xué)Repast代碼解釋_第1頁(yè)
6.1.1一步一步學(xué)Repast代碼解釋_第2頁(yè)
6.1.1一步一步學(xué)Repast代碼解釋_第3頁(yè)
6.1.1一步一步學(xué)Repast代碼解釋_第4頁(yè)
6.1.1一步一步學(xué)Repast代碼解釋_第5頁(yè)
已閱讀5頁(yè),還剩62頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、一步一步學(xué) RePast建模Introduction, (Sim)Model Object, CarryDropThe CarryDrop Model A RePast Tutorial by John Murphyby Junjie SunDepartment of EconomicsIowa State UniversityRePast模型的元素模型對(duì)象:模型對(duì)象:Model Objectacts as the model itself空間對(duì)象:空間對(duì)象:Space Objectcontrols the environment主體對(duì)象:主體對(duì)象:Agent ObjectThe (Sim)M

2、odel Object 模型對(duì)象繼承Repast的SimModelImpl 類 Model object will extend RePasts SimModelImpl object. 負(fù)責(zé)對(duì)Repast控制條的響應(yīng) It will react to the RePast control toolbar.The SimModel ObjectgetName() getName( )中可設(shè)置模型名稱,讓中可設(shè)置模型名稱,讓Repast調(diào)用返回,改名稱會(huì)調(diào)用返回,改名稱會(huì)顯示在控制條左上角顯示在控制條左上角 getName() replaces RePast with the name of t

3、he project on the control toolbar.import uchicago.src.sim.engine.SimModelImpl;public class MyFirstRePastModel extends SimModelImpl public String getName()return “第一個(gè) RePast模型”;The SimModel Objectbegin() begin() 初始化模型的參數(shù).import uchicago.src.sim.engine.SimModelImpl;public class MyFirstRePastModel exte

4、nds SimModelImpl public String getName()return “第一個(gè) RePast 模型”;public void begin()The SimModel Object慣例 RePast模型中的方法一般與模型用到的類匹配,各相關(guān)的類時(shí)用子方法分開. 如初始化Begin()涉及到模型類、規(guī)劃表類和顯示類.,就用三個(gè)子函數(shù)把他們獨(dú)立分開,以便于閱讀和調(diào)試public void begin()buildModel();/模型初始化buildSchedule();/規(guī)劃表初始化buildDisplay();/顯示初始化public void buildModel()p

5、ublic void buildSchedule()public void buildDisplay()The SimModel Objectcurrent 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();pu

6、blic void buildModel()public void buildSchedule()public void buildDisplay()The SimModel Objectsetup() The setup() 讓模型返回到初始狀態(tài)public class MyFirstRePastModel extends SimModelImpl public String getName()return “My First RePast Model”;public void setup()public void begin()The SimModel ObjectSchedule Rep

7、ast模型有一個(gè)基礎(chǔ)時(shí)間單元的概念(單位步長(zhǎng)、節(jié)拍、時(shí)刻),相當(dāng)于模型執(zhí)行一步(控制條上的Tick計(jì)數(shù)加1),模型每一步狀態(tài)會(huì)整體切換到下一個(gè)狀態(tài) 每一步內(nèi)的多個(gè)操作是不可分割的 Schedule 管理基礎(chǔ)時(shí)間單元內(nèi)執(zhí)行哪些基礎(chǔ)操作等 當(dāng)所有基本操作完成后,控制條上的Tick計(jì)數(shù)加1,模型進(jìn)行下一步.執(zhí)行 一個(gè)時(shí)刻內(nèi)多個(gè)基礎(chǔ)操作的執(zhí)行順序是隨機(jī)The SimObject Model-Scheduleimport uchicago.src.sim.engine.SimModelImpl;import uchicago.src.sim.engine.Schedule;public class My

8、FirstRePastModel 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 schedu

9、le;The SimModel Object-getInitParam getInitParam 返回一個(gè)數(shù)組,數(shù)組內(nèi)是字串類型,表示需要初始化設(shè)置參數(shù)名稱列表。 returns an array of String variables (e.g., N agents) 在初始化和設(shè)置中可以修改這些初始化參數(shù)。This will change Ns by using the setup and initialize buttons. 注意兩點(diǎn): 必須提供一個(gè)參數(shù)名列表 參數(shù)表中的每一個(gè)參數(shù)必須創(chuàng)建對(duì)應(yīng)的get與set方法.The SimModel Object-numAgents First,

10、 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”;The SimModel Object-n

11、umAgents 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;The SimModel Object-numAgents Next, RePast structure requires us to provide get and set.public Sched

12、ule getSchedule()return schedule;public String getInitParam()String initParams = “NumAgents”;return initParams;public int getNumAgents()return numAgents;The CarryDrop Model-Introduction模型介紹. 主體在一個(gè)格狀空間內(nèi)移動(dòng) 每個(gè)格子里可能包含一些金子,主體進(jìn)入一個(gè)格子后如果里面沒有其他主體可以拾起里面的金子 主體總是移向相鄰的8個(gè)格子. 當(dāng)一個(gè)主體進(jìn)入另外一個(gè)主體的格子時(shí),進(jìn)入的主體要給已經(jīng)在格子的主體金子. 主

13、體有一個(gè)隨機(jī)的壽命,當(dāng)一個(gè)主體死亡時(shí),他的金子隨機(jī)地?cái)U(kuò)散,發(fā)放到其他格子中去.同時(shí)隨機(jī)誕生一個(gè)新的主體(隨機(jī)不同的位置和隨機(jī)壽命)The CarryDrop model三個(gè)文件 模型對(duì)象實(shí)例 CarryDropModel 主體對(duì)象實(shí)例 CarryDropAgent 空間實(shí)例 CarryDropSpace前面已經(jīng)完成的代碼 CarryDropModel Variables: schedule, numAgents Methods: setup(), begin(), buildModel(), buildSchedule(), buildDisplay(), getName(), getSche

14、dule(), getInitParam(), getNumAgents(), setNumAgents(), main() CarryDropAgent CarryDropSpace增加用戶可以設(shè)置的參數(shù) 主體個(gè)數(shù) (NumAgents) 世界尺寸 橫坐標(biāo) X (WorldXSize) 世界尺寸縱坐標(biāo) Y (WorldYSize)把參數(shù)設(shè)置為類變量 Add worldXSize & worldYSize as class variables private int worldXSize;private int worldYSize; 把參數(shù)設(shè)置到初始化參數(shù)列表中 String ini

15、tParams = NumAgents , WorldXSize, WorldYSize; 為每個(gè)參數(shù)增加Get Set 方法public int getWorldXSize() return worldXSize; 編譯運(yùn)行模型 創(chuàng)建一個(gè)新項(xiàng)目(Eclipse或JBuilder) 增加三個(gè)文件 CarryDropModel.java CarryDropAgent.java CarryDropSpace.java 這個(gè)模型沒做任何事情,但會(huì)影響控制條的顯示Codes to be Added in main Method Creates a new obj. of type SimInit:Si

16、mInit 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);Default Values for User-Settable Parameters (Step 6) private static final int NUMAGENTS = 10

17、0; private static final int WORLDXSIZE = 40; private static final int WORLDYSIZE = 40; private int numAgents = NUMAGENTS; private int worldXSize = WORLDXSIZE; private int worldYSize = WORLDYSIZE;Alerts in Subroutines (Step 7) System.out.println(Running setup); System.out.println(Running BuildModel);

18、 System.out.println(Running BuildSchedule); System.out.println(Running BuildDisplay);The Space Object (Step 8-1) Define the variable for space object using RePasts Object2DGrid: private Object2DGrid moneySpace; Fill moneySpace with Integer objects: public CarryDropSpace(int xSize, int ySize) moneySp

19、ace = 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); 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 specifi

20、ed 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)Need another parameter, the amount of money (Step 8-3) In CarryDropModel.java, add: private static final int TO

21、TALMONEY = 1000; private int money = TOTALMONEY; String initParams = NumAgents , WorldXSize, WorldYSize, Money ; public int getMoney() return money; public void setMoney(int i) money = i; Integrate the Space Object into the Model (Step 9-1) 空間對(duì)象在Setup中刪除 Setup在運(yùn)行前全部清空 每次重新運(yùn)行時(shí)重新創(chuàng)建BuildModel() Allocat

22、e a variable for the space object:private CarryDropSpace cdSpace; Create the space object in buildModel():cdSpace = new CarryDropSpace (worldXSize, worldYSize);/創(chuàng)建 Destroy the space object in setup():cdSpace = null;/刪除Overview : Whats been done in Step 1-9 CarryDropModelVariables: schedule, cdSpace,

23、 numAgents, worldXSize, worldYSize, moneyMethods: setup(), begin(), buildModel(), buildSchedule(), buildDisplay(), getName(), getSchedule(), getInitParam(), getNumAgents(), setNumAgents(), getWorldXSize(), setWorldXSize(), getWorldYSize(), setWorldYSize(), getMoney(), setMoney(), main() CarryDropAge

24、nt CarryDropSpace Variables: moneySpace Constructors: CarryDropSpace()前面已經(jīng)完成以下工作 創(chuàng)建一個(gè)給定尺寸的空間對(duì)象 Start to fill out the CarryDropSpace class Constructor to build a space of a given size 增加空間類的變量 Added CarryDropSpace variable to the model 在模型創(chuàng)建時(shí)增加創(chuàng)建空間對(duì)象 Added creation line in buildModel() 在模型清空時(shí)刪除空間對(duì)象 A

25、dded preparation line in Setup()Step 10 初始化空間類 在格子里初始化金子.在空間類CarryDropSpace定義一個(gè)新方法spreadMoneyCarryDropSpace類的 新方法spreadMoney() 在在 CarryDropModel類里調(diào)用,創(chuàng)建時(shí)調(diào)用Step 11 - Extracting reusuable code getMoneyAt空間里變量是否設(shè)置,如果沒有設(shè)置設(shè)置為0,如果已經(jīng)設(shè)置則返回值. 隨機(jī)查找一個(gè)格子,getMoneyAt,取回當(dāng)前金子數(shù),然后再分配一個(gè)金子。直到金子分完為止 This could be useful

26、 outside of spreadMoney() or CarryDropSpace可視化界面設(shè)計(jì) 查看模型狀態(tài) 初始化可視環(huán)境 查看2維格子空間 白色背景 金子可視化Visible money, which squares have cash 顏色深淺表示金子多寡 RePast 創(chuàng)建顯示的相關(guān)類 DisplaySurface 一個(gè)窗口 ColorMap 顏色圖 Value2DDisplay links value sources from the model to colors according to the color map. Displays colors for each sou

27、rce in window when added to a DisplaySurface.Step 12 Using the DisplaySurface 在頭部導(dǎo)入必要的庫(kù)Import the class Create the variable 如果有舊的,拆毀掉“Tear down” 初始化Instantiate Pass in the model Give it a name Register the objectStep 13 A splash of color Import the needed classes Color is a standard Java class to re

28、present color values Will need access to the 2D grid of values Add access method to CarryDropSpaceStep 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 o

29、f 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. Step 14 Generating the

30、 Display Simply add this line to in the begin() method in CarryDropModel Now run compile everything andrun CarryDropModel in your favorite IDE. When RePast starts, hit the “Initialize” button.Step 15 The Agents Start with 4 attributes Money X position Y position Lifespan (stepsToLive)Step 15 cont. M

31、odifying 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 vriablesStep 16 Adding Agents to the model Make a container to for all the Agents: ArrayList

32、Initialize the agentList in setup()Step 16 cont. Define new method in CarryDropModel for adding Agents to the listStep 17 A Space for Agents Want to add agents to CarryDropSpace. Space containing agents will be an Object2DGrid like moneySpace.Step 17 cont. IsCellOccupied() checks if an Agent is alre

33、ady in a given cell in the agentSpace object. addAgent() attempts to add an Agent in a random cell.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 a

34、dd it to the simulation space.Whats 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

35、variables, constructor, spreadMoney(), getMoneyAt(), getCurrentMoneySpace(), IsCellOccupied(), addAgent()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

36、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.Report function (Step 19-2) In CarryDropModel: public void buildModel() for(int i = 0; i agentList.size(); i+) CarryDropAgent cda = (CarryDropAgent)agentList.get(

37、i); cda.report(); In CarryDropAgent: public String getID() return A- + ID; public int getMoney() return money; public int getStepsToLive() return stepsToLive; public void report() System.out.println(getID() + at + x + , + y + has + getMoney() + dollars + and + getStepsToLive() + steps to live.); Uni

38、que 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; Displaying Agents (Step 20-1) Create an Object2DDisplay object, add the agent list to that Obje

39、ct2DDisplay objects 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

40、that takes a SimGraphics object as an argumentCodes 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(cdSp

41、ace.getCurrentMoneySpace(), map); Object2DDisplay displayAgents = new Object2DDisplay(cdSpace.getCurrentAgentSpace(); displayAgents.setObjectList(agentList); displaySurf.addDisplayable(displayMoney, Money); displaySurf.addDisplayable(displayAgents, Agents);Codes for Displaying Agents (Step 20-3) - M

42、ake 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(SimGr

43、aphics G) G.drawFastRoundRect(Color.blue); In CarryDropSpace:public Object2DGrid getCurrentAgentSpace() return agentSpace; Adding a Schedule and Some Action (Step 21-1) - Motivation At this point the model will load and run, but it wont do anything. We want to add actions to the model, so that it ca

44、n 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

45、 in the simulation.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 objec

46、t to do by creating an inner class CarryDropStep and adding it to the Schedule object using one of RePasts built-in functions. These built in functions allow you to specify when the action defined by the inner class is executed.Codes for creating a step method and a Schedule object (Step 21-3) In Ca

47、rryDropAgent:public class CarryDropAgent implements Drawable public void step() stepsToLive-; In CarryDropModel:public void setup()schedule = new Schedule(1);Codes for creating an inner class CarryDropStep (Step 21-4) In CarryDropModel:import uchicago.src.sim.engine.BasicAction;import uchicago.src.s

48、im.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 CarryDropSte

49、p(); 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 projects build path scheduleActionBeginning routine creates a new instance of inner class, Ca

50、rryDropStep, to add. (0) indicates that we want the action to be taken in the first timestepAnother 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 mo

51、del 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 21Codes for creating coun

52、tLivingAgents in CarryDropModel (Step 22-2)private int countLivingAgents() int livingAgents = 0; for(int i = 0; i 0) livingAgents+; System.out.println(Number of living agents is: + livingAgents); return livingAgents; Codes for CarryDropCountLiving and how to add it to the Schedule object (Step 22-3)

53、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 execute

54、d every timestep, but rather is executed every 10th timestep.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.print

55、ln(Running BuildSchedule); class CarryDropStep extends BasicAction public void execute() displaySurf.updateDisplay(); 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

56、will turn blue In CarryDropAgent,public void draw(SimGraphics G) if(stepsToLive 10) G.drawFastRoundRect(Color.green); else G.drawFastRoundRect(Color.blue); 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 dea

57、d when their stepsToLive goes below zero, but theyre 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

58、are born.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 agents 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 rebornCodes for adding reapDeadAgents() to the model (Step 24-3) In CarryDropModel,private int reapDeadAgen

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論