22
Phd in Transportation / Simulation of Land Use-Transportation Systems 1 Phd Program in Transportation Simulation of Land Use-Transportation Systems Luis Martínez Session 13 Case study presentation in Anylogic

Phd Program in Transportation Simulation of Land Use ... · Phd in Transportation / Simulation of Land Use-Transportation Systems 1 Phd Program in Transportation Simulation of Land

Embed Size (px)

Citation preview

Phd in Transportation / Simulation of Land Use-Transportation Systems 3

Introduction to Java programming language

The purpose of this short presentation about Java language is not to give

you a full manual, but to ease the understanding of the code in the

programmed example, and allow you to introduce refinements to the

original code during your project

This presentation complements some of the general presentation on Java

basics that was sent to you. Some of the examples are overlapped

This presentation will lead you on to the traditional Java code structure

Please complement this notes always with the Anylogic help and the

following libraries and books

AnyLogic Class Reference

API Reference section of AnyLogic Help

Java API Specification

Open http://java.sun.com/

Book

Bruce Eckel. Thinking in Java (http://www.mindview.net/Books/TIJ)

Phd in Transportation / Simulation of Land Use-Transportation Systems 4

Introduction to Java programming language

Main types of variable

Primitive types

double – represent real numbers: 1.43, 3.6E18, -14.0

int – represents integer numbers: 12, 16384, -5000

boolean – represents Boolean (true/false) values (not 0 and 1)

Compound Types –Classes

String – represents textual strings, e.g. “MSFT”, “Hi there!”, etc

Arrays – generates arrays of the previous elements, e.g. double [ 10]

ArrayList, LinkedList, Vector – collections of objects

HashSet, HashMap – collection of references to other collections

HyperArray – represents multi-dimensional array in System Dynamics

models

many others, among graphical objects that you will use (e.g. ShapePolyLine)

Phd in Transportation / Simulation of Land Use-Transportation Systems 5

Introduction to Java programming language

Initializing variables

The definition of the type of variable that you are using is mandatory in

Java, as well as defining the initial value of the variable

This can take several configurations for the different types of variables

int age = 0;

boolean sex=true;

Household household = null;

double fees=0;

int[] trip_rate=new int [24];

ArrayList trip = new ArrayList();

String type="";

Variables, by default are local or private, presenting only effect within the

section of code or function (identified by brackets “{“”}”)

Global variable should be set as public to be used in other contexts

Phd in Transportation / Simulation of Land Use-Transportation Systems 6

Introduction to Java programming language

Some writing code peculiarities

Java code presents two main types of syntax:

Statements, which include assigning values to variables

Expressions, which include workflow special keyworkds as if, do, for, etc.

Special attention to:

Java is case-sensitive: MyVar is different to myVar!

Spaces are not allowed in declarations: “My Var” is an illegal variable’s name!

Each statement has to be finished with “;”: MyVar= 150;

Each function has to have parenthesis: time(), add(a), including the

arguments inside the parenthesis

Mind integer division: 3/2= 1, not 1.5

Boolean values are only true and false, you cannot use 1 and 0

Dot “.” brings you “inside” the object: agent.event.restart()

Array elements have indexes from 0 to N-1

Phd in Transportation / Simulation of Land Use-Transportation Systems 7

Introduction to Java programming language

Expressions

Arithmetic operations

Notation: +, –, *, /, % (remainder)

Multiplication operators have priority over addition operators

The ‘+‘ operator allows operands of type String

Comparison operations

Notation: >, >=, <, <=, ==, !=

Boolean operations

Notation: && (AND), || (OR), ! (NOT)

Conditional operator

Notation: condition ? value-if-true :value-if-false

Assignments and shortcuts

Notation: =, +=, -=, *=, /=, %=, ++, --

Example: a+=b is equivalent to a=a+b

For most of operators, left-

to-right precedence holds

Parentheses may be used

to alter the precedence of

operations

Phd in Transportation / Simulation of Land Use-Transportation Systems 8

Introduction to Java programming language

Main Language Constructs

Assignment

y = f(x1,x2) + 5*z;

Decision statement (if, else if, else)

if ( friendsRatio> attackConstant)

attack();

else

escape();

Alternative outputs

switch (month)

{ case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31;

case 4: case 6: case 9: case 11: numDays = 30;

case 2: if ( ((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0) )

numDays = 29; else numDays = 28; break; default:}

If the statements inside the

conditions are more than one

statement, they should be limited by

brackets

Phd in Transportation / Simulation of Land Use-Transportation Systems 9

Introduction to Java programming language

Main Language Constructs

Loop statement

for ( Person p : people )

total += p.income;

for( int i =0; i<100; i++ )

send( msg, RANDOM );

while (staff.size() > 0)

{

fire( );

amount--;

}

To close a loop for conditions apart from the ones verified in the guard, we

can use a conditional statement within the loop with the following keywords

break, stops the loop after finishing the current iteration

continue, skips the current iteration of an outer loop marked with the given label

do {

fire( );

amount--;

}

while (staff.size() > 0);

Equivalent

Phd in Transportation / Simulation of Land Use-Transportation Systems 10

Introduction to Java programming language

Additional features in Java code

Writing comments

Complete or traditional comments

/* text */

End-of-line comment

//text

Mathematical functions

Numerical: sqrt, sin, cos, tan, exp, log, round, zidz, xidz, etc

Array: get, add, sum, average, min, max, isEmpty(), etc

Statistical distributions (functions)

uniform, normal, exponential, bernoulli, beta, triangular, etc.

Other important keywords and functions:

Execution on the Engine: time(), start(), pause(), finish()

Data workflow and output: System, System.out.println(), getOwner()

Phd in Transportation / Simulation of Land Use-Transportation Systems 11

Introduction to Java programming language

Working with objects and agents

Object or agent are structures in Java, which are generated as a special

class of Arraylist or collection

All the attributes and functions of this class can be used (e.g. size(), get())

Inside this special classes, the user may define different types of

variables and function (and activity flowcharts in the case of agents)

This object should be inserted as replicable objects in a main simulation

platform, where all the objects interact

Inside this platform, these classes present additional features that are

related with their construction or destruction within the environment

add_people(), adds a new object/agent to the collection of the simulation

remove_people(person), removes object/agent from the collection

Phd in Transportation / Simulation of Land Use-Transportation Systems 12

Introduction to Java programming language

Collections workflow

Collection framework is a set of classes representing basic data structures

These classes have different timing characteristics of different operations

Actions ArrayList

Vector LinkedList

HashSet

HashMap

SortedSet

SortedMap

Size Const Const Const Const

Add and item Const Const Const Log

Remove found item Linear Linear Const Log

Remove by index Linear Linear - -

Get by index/random Const Linear - -

Find an item Linear Linear Const Log

Get smallest/largest Linear Linear Linear Const

Phd in Transportation / Simulation of Land Use-Transportation Systems 13

Introduction to Java programming language

Working with SQL connections

The construction of complex agent based model, usually requires the

connection for input and output of large and complex databases.

These connections are performed using sql statements for Java

Reading

Database.getValue(“SELECT X FROM [Zones_Points] WHERE ID1=1”);

We can search for a single value query, multiple, or operations of a field (e.g. MAX,

MIN, AVERAGE)

When storing the obtained queries into variables we should convert the

obtained query (always as a String)

We should use the statement valueOf(), preceded by the type of variable we are

storing (e.g. Integer, Double, etc.)

Writing

Output.modify("INSERT INTO Road_flows VALUES (" + time + "," +

road.get(i).load + ",“ + simulationcode + ") ");

The fields should be ordered following to table structure