实例介绍
一个非常实用的文档,方便开发ANYLOGIC,快速上手
Simulation Modeling with AnyLogic: Agent Based, Discrete Event and System Dynamics Methods 3 If you wish to include the quote character in a string, you need to write \" For example the string constant"String with \"in the middle"will print as To include a backslash in a string, use a double backlash For example, " This is a backslash: "will print as Classes Structures more complex than primitive types are defined with the help of classes and in object-oriented manner. The mission of explaining the concepts of object-oriented design is impossible within the scope of this chapter: the subject deserves a separate book, and there are a lot of them already written. all we can do here is give you a feeling of what object-orientedness is about by introducing such fundamental terms as class, method, object, instance, subclass, and inheritance, and show how Java supports object-oriented design You should not try to learn or fully understand the code fragments in this section It will be sufficient if, having read this section, you will know that, for example,a statechart in your model is an instance of Any Logic class Statechart and you can find or its current state by calling its method: statechart. getActive Simple StateO), or if the class Agent is a subclass of ActiveObject, it supports the methods of both of them Class as grouping of data and methods. objects as instances of class Consider an example. Suppose you are working a with local map and use coordinates of locations and calculate distances. of course you can remem ber two double values x and y for each location and write a function distance( x1, y1, x2, y2 )that would calculate distances between two pairs of coordinates but it is a lot more elegant to introduce a new entity that would group together the coordinates and the method of calculating distance to another location In object-oriented programming such an entity is called a class. Java class definition for the location on a local map can look like this class Location I //constructor: creates a Location object with given coordinates Location( double xcoord, double ycoord )i x= xcoord y ycoord; ox]Technologieswww.anylogic.com Simulation Modeling with AnyLogic: Agent Based, Discrete Event and System Dynamics Methods 4 //two fields of type double double X;//x coordinate of the location double y; //y coordinate of the location //method (function ): calculates distance from this location to another one double distanceTo( Location other ) double dx= otherx-x double dy=othery-y; return sqrt( dx*dx+ dy*dy ) As you can see, a class combines data and methods that work with the data Having defined such a class, we can write very simple and readable code when working with the map. Consider the following code Location origin new Location (0, 0;//create first location Location destination new Location( 250, 470);//create second location double distance= origin. distance To( destination );//calculate distance The locations origin and destination are objects and are instances of the class Location The expression new Location( 250, 470 )is a constructor call; it creates and returns a new instance of the class Location with the given coordinates. The expression origin. distance To( destination ) is a method call; it asks the object origin to calculate the distance to another object destination If you declare a variable of a non-primitive type (of a class) and do not initialize it, its value will be set to null (null is a special Java literal that denotes"nothing"). Sometimes you explicitly assign null to a variable to "forget" the object it referred to and to indicate that the object is missing or unavailable Location target; //a variable is declared without initialization target equals null target warehouse; //assign the object(pointed to by the variable) warehouse to target //now target and warehouse point to the same object target null; / target forgets about the warehouse and equals null again Inheritance. Subclass and super class Now suppose some locations in your 2D space correspond to cities. A city has a nam and population size To efficiently manipulate cities we can extend the class location by adding two more fields: name and population. We will call the new entity City. In java this will look like ox]Technologieswww.anylogic.com Simulation Modeling with AnyLogic: Agent Based, Discrete Event and System Dynamics Methods 5 class City extends Location(//declaration of the class clty that extends the class location /constructor of class City City( String n, double x, double y)[ super(x, y ) //call of constructor of the super class with parameters x and y name n; //the population field is not initialized in the constructor- to be set later //fields of class Cit String name; It population; class location Classes-"type ● double x● double distanceto0 definitions" or templates for double y objects Objects real things ▲ subclass of inherits from class City instance of ● String name nt population x:300.07 y:364.18 obJect sompo instance of instance of instance of x:229.73 x:260.21 x:269.98 y:363.08 y:39718 y:405.03 name: Los angeles name:"La jolla name: San Diego population: 3, 831, 868 population: 42, 808 population: 1, 359, 132 object losAngeles object laJolla bject sanDiego Classes and inheritance City is called a subclass of Location, and Location is correspondingly a super class (or base class) of City City inherits all properties of Location and adds new ones. See how elegant the code is for finding the biggest city in the range of 100 kilometers from a given point of class Location(we assume that there is a collection cities where all cities are luded) ox]Technologieswww.anylogic.com Simulation Modeling with AnyLogic: Agent Based, Discrete Event and System Dynamics Methods 6 int pop=0; // here we will remember the largest population found so far City biggestcity null; //here we will store the best city found so far for( City city: cities )(//for each city in the collection cities if( point distanceTo( city ) 100 & city population pop )(//if best so far biggestcity= city; //remember it pop city population; //and remember its population size traceIn("the biggest city within 100km is"+ city name );//print the search result Notice that although city is an object of class City, which is "bigger" than Location, it can still be treated as Location when needed, in particular when calling the method distanceToo of class Location This is a general rule: an object of a subclass can always be considered as an object of its base class How about vice versa? You can declare a variable of class Location and assign it an object of class City (a subclass of Location) Location place laJolla This will work. However, if you then try to access the population of place, Java will signal an error int p= place. population; //error: population cannot be resolved or is not a field This happens because Java does not know that place is in fact an object of class City. To handle such situations you can test whether an object of a certain class is actually an object of its particular subclass by using the operator instanceof: <object> instanceof <class> ."cast" the object from a super class to a subclass by writing the name of the subclass in parentheses before the object: (<class>)<object> a typical code pattern is If( place instanceof City )I City city =(City)place; int p= city. population: ox]Technologieswww.anylogic.com Simulation Modeling with AnyLogic: Agent Based, Discrete Event and System Dynamics Methods 7 Classes and objects in any Logic models Virtually all objects of which you create your models are instances of Any Logic Java classes. In the Table you will find the Java class names for most model elements you work with Whenever you need to find out what can you do with a particular object using Java, you should find the corresponding Java class in Any Logic Class Reference and look through its methods and fields Model object Java class name Active object(such as Main) Base class: ActiveObject Agent(such as Person Base class: Agent (subclass of ActiveObject) Classes: AgentContinuous 2D, AgentContinuouS3D AgentDiscrete2D, AgentContinuousGIs Event Base class: Event Classes: Eventcondition Event Rate. EventTimeout Dynamic event Dynamic Event Statechart Statechart Transition of a statechart Base class: Transition Classes: Transition Condition, Transition Message Transition Rate, Transition Timeout Table function Table Function Schedule Schedule Port Base class: port Classes of the Enterprise Library: In Port, OutPort, OutPortPush Statistic collectors: data DataSet, HistogramData set, Histogram Data, Charts: Bar chart Plot BarChart, Plot, Histogram Histogram chart,… Shapes: Rectangle, Polyline, Base class: Shape Group,… Classes: ShapeRectangle, Shape PolyLine, Shape Group Controls: button slider Base class: Shape Control(subclass of Shape) List box Classes: Shape Button, Shape Slider, ShapeListBox Connectivity objects: Text Text File, ExcelFile, Database, file, Excel file, database ox]Technologieswww.anylogic.com Simulation Modeling with AnyLogic: Agent Based, Discrete Event and System Dynamics Methods 8 Enterprise Library Base class: Active Object objects: Source, Delay, Classes of the Enterprise Library: Source, Queue, Queue, Select Output, Delay, SelectOutput Entities and resource units Classes of the Enterprise Library: Entity,ResourceUnit in process models Experimen Base class: Experiment Parameter variation, Classes: ExperimentSimulation Optimization ExperimentParamVariation, Experimentoptimization Any Logic model gUI Presentation Panel Variables(local variables and class fields) In this section we are considering plain Java variables. Special kinds of variables with additional functionality specific to simulation modeling, such as parameters or dynamic variables are described in other chapters of the book Depending on where a variable is declared it can be either a Local variable- an auxiliary temporary variable that exists only while a particular function or a block of statements is executed,or Class variable for class field -more correct term in Java-a variable that is present in any object of a class, and whose lifetime is the same as the object lifetime Local (temporary) variables Local variables are declared in sections of java code such as a block, a loop statement or a function body. They are created and initialized when the code section execution starts and disappear when it finishes. The declaration consists of the variable type, name, and optional initialization. The declaration is a statement, so it should end with a semicolon. For example double sum =0; //double variable sum initially O int k;//integer variable k, not initialized String msg=ok?OK": Not OK"//string variable msg initialized with expression Local variables can be declared and used in Any Logic fields where you enter actions sequences of statements), such as of the active object class field of events or transitions an d of state and fields of flowchart objects. In the Figure the variables sum and p are declared in the action code of the event endofYear and exist only while this portion of code is being executed ox]Technologieswww.anylogic.com Simulation Modeling with AnyLogic: Agent Based, Discrete Event and System Dynamics Methods endofYear ocal variable sum can Local variable p, exists be used throughout the only while the" loop Action code is executed Action: donble gum =0 for( Person p: people )t sum+=P.2nco4ei traceln("Total income of all people: # sum ); Local variables declared in the action code of an event Class variables(fields) Java variables (fields) of the active object class are part of the memory "or stateof active objects. They can be declared graphically or in code 8. General a83 PArameter Drag and drop Event 29 Dy income v Plain variable so Collection F Function 唱 Table Fi 9 income. Plain Variable General Name: income Show name回 Ignore Description v Show at runtime Access:public- 0 Static Constant Save in snapshot Type O boolean o int double O String O Other: int nitialvalue:10000 A variable of an active object declared in the graphical editor To declare a variable of active object (or experiment)class 1. Open the palette and drag the object to the canvas 2. Type the variable name in the in-place editor or in the variable properties 3. Choose the variable type in the page of the variable properties. In most cases you can leave default, which means the variable will ox]Technologieswww.anylogic.com Simulation Modeling with AnyLogic: Agent Based, Discrete Event and System Dynamics Methods 10 other models, an d private limits access to this active object on e riable from be visible within the current model. public opens access to the v 4. Choose the variable type. If the type is not one of the primitive types, you should choose and enter the type name in the field nearby 5. Optionally you can enter the variable Initial value If you do not specify the initial value, it will be false for boolean type, o for numeric variables, and null C"nothing )for all other classes including String In the Figure, a variable income of type int is declared in an active object or experiment class. Its access type is public, therefore it will be accessible from anywhere. The initial value of the variable is 10000. The graphical declaration above is equivalent to a line of code of the class, which you can write in the field of the property page of the class, as shown in the Figure G Main Active Object Class General Advanced Additional class code Agent public int income=10000: Access type Type Name Initial value The same variable declared in the additional class code field Graphical declaration of a variable allows you to visually group it together with related functions or objects, and to view or change the variable value at runtime with one click Functions(methods) In Java, to call a function (or method, which is more correct in object-oriented anguages like Java, as any function is a method of a class you write the function name followed by the argument values in parentheses. For example, this is a call of a triangular probability distribution function with three numeric arguments triangular 2, 5, 14 The next function call prints the coordinates of an agent to the model log with a timestamp traceIn( time(+x=+ getXo+Y=+ getO); The argument of this function call is a string expression with five components; three of them are also function calls: timeO, getXO, and getTo ox]Technologieswww.anylogic.com 【实例截图】
【核心代码】
标签:
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论