AnyLogic And Java - University Of Saskatchewan

1y ago
6 Views
2 Downloads
1.78 MB
38 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Ronan Orellana
Transcription

AnyLogic and JavaNathaniel Osgood

Advantages of AnyLogic(as compared to other Agent-Based Modeling Software) Primarily declarative specificationLess codeGreat flexibilityAccess to Java librariesSupport for multiple modeling typesSupport for mixture of modeling types

Painful Sides of AnyLogic Education/Advanced Export of model results: Lack of trajectory filesLack of a built-in debuggerNeed for bits of Java codeMany pieces of system

Internals of AnyLogic files: XML

Java Code: When & How Much? “Java” is a popular cross-platform “object oriented”programming language introduced by SunMicrosystems Anylogic is written in Java and turns models into Java AnyLogic offers lots of ways to insert snippets (“hooks”)of Java code You will need these if you want to e.g.– Push AnyLogic outside the envelop of its typical support e.g. Enabling a network with diverse Agent types– Exchange messages between Agents– Put into place particular initialization mechanisms– Collect custom statistics over the population

Stages of the Anylogic BuildModificationPossibleModification Not PossibleJava CodeJVMByteCodePerson.class

Inspecting the Java code As a step towards creating an executablerepresentation of the code, AnyLogic creates a Javarepresentation– If you want to see the Java code for a model, you willneed to do a “build” Sometimes it can be helpful to look at this Java code– To find errors about which AnyLogic may be complaining– Advanced: To see how things are being accomplished or“work”

Requesting Viewing of Java Code

Examples of Where to Insert CodeObject Properties “Advanced”

Examples of Where to Insert CodeObject Properties “General”

Example of Where to Insert CodePresentations Properties “Dynamic”properties ofpresentationelements(especiallyof Agents)

Tips to Bear in Mind While Writing Code Click on the “light bulb” next to fields to getcontextual advice (e.g. on the variables that areavailable from context While typing code, can hold down the Control keyand press the “Space” key to requestautocompletion– This can help know what parameters are required for amethod, etc. Java is case sensitive! Can press “Control-J” to go to the point in Javacode associated with the current code snippet Can press “build” button after writing snippet toincrease confidence that code is understood

Example of Contextual Information

Autocompletion Info (via Control-Space)

Finding the Enclosing “Main” classfrom an Embedded Agent From within an embedded Agent, one can findthe enclosing “Main” class by calling get Main()– This will give a reference to the single instance(object) of the Main class in which the agent isembedded– An alternative approach is to call ((Main) getOwner)

Presentation Properties Both key customizable classes (“Main”, variousAgent classes) can be associated with“Presentation” elements These elements are assembled during executioninto animations & presentations of the agents Many of these presentation elements haveproperties that can be set to Java expressions

Enabling Programmatic Control

Getting to the AnyLogic Help Choose “Help”/”Help Contents” AnyLogic help includes many components– Tutorials– User references– AnyLogic “library” information

Getting Information on the Anylogic (Java)Libraries

The Notion of a Code “Library” A “library” lets third parties (e.g. xjtek) sharecompiled code they have developed with others The classes built into our AnyLogic projects (e.g.Agent, ActiveObject, NetworkResourcePool, etc.)are contained in the library The available libraries that come with AnyLogic &Java have many additional components that canoffer tremendous additional functionality– By tapping into this functionality, we can avoid having towrite code ourselves To use a library, you need to know what is in it!

Finding out InformationInterfaces for Library Elements 1

Finding out InformationInterfaces for Library Elements 2

Using Libraries There are two major libraries that are “builtin” and can be used without additionalreference: Java libraries & AnyLogic libraries To use an object in the Java libraries, you willuse an “import” statement

Using External Libraries There are tremendous numbers of 3rd partylibraries available for Java The functionality associated with these librariesis incredibly diverse Many of these libraries are available for free;others are sold It is very easy to make use of the functionality of3rd party libraries from AnyLogic– In order to do this, AnyLogic needs to “know about”the external library.

Adding External Libraries 1

Adding External Libraries 2

Common Contextual Variables that areUsed by Code Snippets In statistics: “item” indicates current agent In “On Message Received” handler for agent:“msg” indicates received message In Dynamic properties of an Agent’s replicatedline property: “index” indicates currentperson’s index In “Parameters” properties of Agentpopulations (used to set properties of agentswithin population): “index” indicates theindex of the current agent in the population

Example code to Export DatasetFileOutputStream fos newFileOutputStream(“Filename”);PrintStream p new ; // outputscomma delimited values

Useful Bits of Java Code get Main() gets reference to Main objectActiveObject.trace(str) outputs string to logEngine.getTime() gets the current timeagents.size() gets number of objects in collectionagents agents.item(i) gets item i from agent collection uniform() generates a random number from 0.1

Useful Bits of Java Code : GeneralExpressions ActiveObject.traceln(Stringstr) outputs string to log time() gets the current internal model time (differentfrom the time in the external world) Members of com.xj.anylogic.engine.Utilities– uniform() generates a random number from 0.1– uniform(x) gen. a random number in range 0 to x– lognormal(double meanNormal, double sigmaStdDevNormal,double minNormal) draws from a lognormal distribution– normal(double meanNormal, double sigmaStdDevNormal)draws from a normal distribution– Many other probability distributions

Methods on Populations of Agents (inMain class) population.size() gets number of objects incollection population population.statName() retrieves the current value ofthe population statistic statName, as computed forpopulation population. population.item(int i) gets item i from populationcollection add populationname() Adds agent to thatpopulation remove populationname() Removes agent from thatpopulation

Useful Java Code: Methods to Call on(or from within, using “this”) an Agent a.getConnectionsNumber() returns number ofconnections between this agent and others get Main() gets reference to Main object toString() gets string rendition of agent a.getConnections() gets a collection (linked) list of agentsto which this agent is connected (& over which we caniterate) a.connectTo(Agent b) connects a to b a.disconnectFrom(Agent b) disconnects b from a a.disconnectFromAll() disconnects all agents from a a.getConnectedAgent(int i) gets the ith agent connectedto a a.isConnectedTo(Agent b) indicates if a is connected to b

Methods on Statecharts(Called from within Agent code) isStateActive(intstatename) indicates whetheragent is in a given state (composite or simple) getActiveSimpleState() Get number of simplestate. Can then compare to different statenames, e.g. in switch statement.

Methods on Process Flow Diagrams source.inject(int count) injects a count ofentities into the source object (i.e. into anobject of type Source)

Gotchas Changing rates for leaving a state do not getupdated until leave & reenter state (includingby a self-transition)

Example Use of getActiveSimpleStateswitch ase LTBI:return Color.YELLOW;case UnDiagnosedActiveTB:return Color.RED;case DiagnosedActiveTB:return Color.ORANGE;case TBSusceptible:default:return Color.BLACK;}

Useful Snippets: Handling Messages Sending– sender.deliver(msg, receiver) immediately deliver amessage from sender to receiver– sender.send(msg, receiver) deliver a message from senderto receiver– environment.deliverToRandom(msg) [within Main]immediately deliver a message to a random agent in theenvironment– send( "Infection", RANDOM CONNECTED) [within an agent]send a message to a randomly selected agent connected tothis one (where those agents are selected w/uniform prob) Receive message– TBProgressionStatechart.receiveMessage( msg) to forwardmessage received by agent to statechart

Useful Snippets Fields of dynamic properties of line object forAgent Presentation (Under “Dynamic” tab of line’sproperties)––––Replication: getConnectionsNumber()dX: getConnectedAgent(index).getX() - getX()dY: getConnectedAgent(index).getY() - getY()These basically allow for appropriate initiation of visualproperties of the inter-agent connections In Agent’s “On Message Received” Handler (Under “Agent”tab of Person) statechartname.receiveMessage( msg ) This forwards a message received by this agent to statechart; notethat if there are different messages, destined for differentstatecharts, they can be dispatched here to different targets

Java Code: When & How Much? "Java" is a popular cross-platform "object oriented" programming language introduced by Sun Microsystems Anylogic is written in Java and turns models into Java AnyLogic offers lots of ways to insert snippets ("hooks") of Java code You will need these if you want to e.g.

Related Documents:

java.io Input and output java.lang Language support java.math Arbitrary-precision numbers java.net Networking java.nio "New" (memory-mapped) I/O java.rmi Remote method invocations java.security Security support java.sql Database support java.text Internationalized formatting of text and numbers java.time Dates, time, duration, time zones, etc.

Java Version Java FAQs 2. Java Version 2.1 Used Java Version This is how you find your Java version: Start the Control Panel Java General About. 2.2 Checking Java Version Check Java version on https://www.java.com/de/download/installed.jsp. 2.3 Switching on Java Console Start Control Panel Java Advanced. The following window appears:

3. _ is a software that interprets Java bytecode. a. Java virtual machine b. Java compiler c. Java debugger d. Java API 4. Which of the following is true? a. Java uses only interpreter b. Java uses only compiler. c. Java uses both interpreter and compiler. d. None of the above. 5. A Java file with

JAR Javadoc Java Language jar Security Others Toolkits: FX Java 2D Sound . Java Programming -Week 1. 6/25. Outline Java is. Let’s get started! The JDK The Java Sandbox . into your namespace. java.lang contains the most basic classes in the Java language. It is imported automatically, so

Java IO to download a file. The Java IO provides APIs to read bytes from InputStream and writing them to a File on disk. While, Java NET package provides APIs to interact with a resource residing over internet with the help of URL. In order to use Java IO and Java NET we need to use java.io.* and java.net.* packages into our class. Using

–‘java’ command launches Java runtime with Java bytecode An interpreter executes a program by processing each Java bytecode A just-in-time compiler generates native instructions for a target machine from Java bytecode of a hotspot method 9 Easy and High Performance GPU Programming for Java Programmers Java program (.

2 Java Applications on Oracle Database 2.1 Database Sessions Imposed on Java Applications 2-1 2.2 Execution Control of Java Applications 2-3 2.3 Java Code, Binaries, and Resources Storage 2-3 2.4 About Java Classes Loaded in the Database 2-4 2.5 Preparing Java Class Methods for Execution 2-5 2.5.1 Compiling Java Classes 2-6

of its Animal Nutrition Series. The Food and Drug Administration relies on information in the report to regulate and ensure the safety of pet foods. Other reports in the series address the nutritional needs of horses, dairy cattle, beef cattle, nonhuman primates, swine, poultry, fish, and small ruminants. Scientists who study the nutritional needs of animals use the Animal Nutrition Series to .