• No results found

A Template-Based Java Code Generator for OpenModelica and MetaModelica

N/A
N/A
Protected

Academic year: 2021

Share "A Template-Based Java Code Generator for OpenModelica and MetaModelica"

Copied!
108
0
0

Loading.... (view fulltext now)

Full text

(1)

Institutionen för datavetenskap

Department of Computer and Information Science

Master Thesis

A Template-Based Java Code Generator

for OpenModelica and MetaModelica

By

Manokar Munisamy

LIU-IDA/LITH-EX-A--14/022—SE

(2)

Linköping University

Department of Computer and Information Science

Master Thesis

A Template-Based Java Code Generator for

OpenModelica and MetaModelica

By

Manokar Munisamy

LIU-IDA/LITH-EX-A--14/022—SE

2014-09-01

Supervisor: Lena Buffoni (fd Olena Rogovchenko)

Department of Computer and Information Science

Examiner: Peter Fritzson

(3)

Abstract

The current OpenModelica Complier (OMC) translates Modelica models into executable C-code through several stages. The Code Generator is the final stage of the compiler which generates target C-code from the optimized sorted equations. Recently, the Code Generator in OMC has been rewritten using the OpenModelica text template language. This gives a more concise and easier to understand code generator. Modeling and simulation is becoming increasingly used in several application areas. There is demand for the OpenModelica Complier (OMC) to generate code in languages like C#, CSharp, XML, JAVA and so on. In this thesis work, we implement a Java code generator to translate the internal equation-based models in OpenModelica and its extension MetaModelica into a Java code representation. To create the Java code generator we used the OpenModelica text template language, also called Susan. This work is an important step on the way to finalize a full version of a Java Code Generator for the OpenModelica Complier (OMC).

(4)

4

Acknowledgments

I take this opportunity to thank my examiner Prof. Peter Fritzson and my supervisor Dr. Olena Rogovchenko for this thesis opportunity, and for guidance. I also thank my technical supervisor Martin Sjölund and give special thanks to Prof. Hans Georg Schaathun from høgskolen i Ålesund (Aalesund University College) for his continuous support through skype meetings. Finally I thank my friends and family for their support.

(5)

5

Contents

Contents ... 5 Chapter 1 ... 7 Introduction ... 7 1.1 Motivation ... 7 1.2 Problem Statement ... 7 1.3 Goals ... 8 1.4 Methodology ... 8 1.5 Intended Readers ... 8 1.6 Thesis Outline ... 9 Chapter 2 ... 11 Background ... 11

2.1 Modelica and OpenModelica ... 11

2.2 OpenModelica Compiler Phases and Modules ... 12

2.2.1. The OpenModelica Compiler Phases ... 12

2.1.2 The OpenModelica Compiler Modules ... 14

2.3 MetaModelica ... 15

2.4 Numerical Integration ... 16

2.4.1 Introduction to Numerical Integration ... 16

2.4.2 Euler Integration ... 17

2.5 Event Handling ... 18

2.5.1 Events ... 18

2.5.2 Run-time Algorithm ... 19

2.6 The Susan Template Language ... 21

Chapter 3 ... 23

Design and Implementation ... 23

3.1 Java Code Generation ... 23

3.1.1 Root Template ... 24

3.1.2 Java Specific File Template ... 24

3.1.3 simulationFileHeader Template ... 25

3.1.4 modelClassName Template ... 25

(6)

6 3.1.6 modelClassConstructorTemplate ... 26 3.1.7 functionBoundParameters Template ... 27 3.1.8 functionODE Template ... 28 3.1.9 functionDAE Template ... 29 3.1.10 functions Template ... 30 3.1.11 mainFunction Template ... 31 3.1.12 daeExp Template ... 32

3.2 Java runtime system ... 33

3.2.1 SimModel ... 34

3.2.2 SimData ... 34

3.2.3 EulerSolver ... 35

Chapter 4 ... 37

Testing ... 37

4.1 Modelica Test Models ... 37

4.1.1 Verification Test ... 38

4.1.2 Performance Test ... 38

4.2 Improvements from previous version ... 42

Chapter 5 ... 45

Conclusion and Future Work ... 45

5.1 Conclusion ... 45 5.2 Future Work ... 45 User Guide ... 47 References ... 49 Appendix ... 51 A Sample Results ... 51 B Simulation Time ... 55 C Implementation code ... 59

(7)

7

Chapter 1

Introduction

In this chapter, we provide an overview and motivation for this thesis work. We also explain the methodology which we use to achieve our goals. In the next section, we have stated the goals and problem statement in this chapter. Finally, we present the outline of this thesis work.

1.1 Motivation

In modern technology, modeling and simulation plays a vital role in many industries. Industries need a multi domain modeling and simulation language and tool for their application development such as: mechanical, robotics, automotive, aerospace, electrical, hydraulic, control subsystems, process oriented applications and many more. Modelica is a non-proprietary, object oriented, mathematical and equation based language. The Modelica language is used for modeling and simulating the above mentioned applications/models.

OpenModelica is an open-source Modelica-based modeling and simulation environment intended for industrial and academic usage. OpenModelica is growing fast and contains different subsystems such as OMC, OMShell, OMNotebook, OMEdit, OMWeb, OMOptim, MDT, ModelicaML, and OMPython.

The idea of creating this thesis work came from some users of OpenModelica, including University of Ålesund, who are using the Java platform for software development and simulation. They have a need for a simulator which is running as a Java application. Therefore there is a need for OpenModelica to be able to generate Java code as an alternative to C code.

1.2 Problem Statement

The OpenModelica Compiler, code generator has recently (two years ago) been rewritten using the OpenModelica text template based language, Susan [2.6]. A previous master thesis project developed a subset text template based code generator. This work extends that to cover a larger part of the language, to create a Java Run-time that supports event handling, and to also support code generation for MetaModelica to Java. Thus the first problem is that,

(8)

8

Problem 1: How to implement a template based Java code generator for

OpenModelica and MetaModelica?

After Java code is generated, we need a runtime system to simulate the model. Currently there exists a C runtime system but now we also need a Java runtime system to simulate. Thus the second problem is that,

Problem 2: How to implement a Java runtime system to simulate Java coded

models?

1.3 Goals

The main goals of this thesis work are the following:

 To further develop a template based Java code generator for OpenModelica Complier OMC. 

 o further develop a Java Runtime System to simulate the models.

 To perform the example test cases that demonstrate the possibility of OMC to generate Java code for Modelica models, and track the performance with other the programming language.

1.4 Methodology

The methodology used for the development of theTemplate Based Java code generator and Java runtime system for OpenModelica is based upon:

Literature Study – A literature study is the basic for the initiation of this thesis work. The

OpenModelica project was studied as along with already existing code generation thesis works made for different languages such as C, C++, C# and XML code generation, as well as previous master thesis with limited code generation from Modelica to Java in OpenModelica. Also, some publications and documentations on OpenModelica were studied which are related to this thesis work. Taking part in Intense Modelica Course and OpenModelica workshop helped to a large extent to learn more about the Modelica language.

Implementation – The implementation leads to obtain a deeper understanding about the

problems and its proposed solutions. The Java code generator and Java runtime system were developed using Susan template language and Java respectively.

1.5 Intended Readers

The intended readers of this thesis work are people with general idea in Modelica language, Susan template language, OpenModelica modeling and simulation environment. However, interested readers with basic knowledge of compiler construction and programming can understand as well.

(9)

9

1.6 Thesis Outline

The rest of this thesis is organized as follows.

Chapter 2: Background studies on the Modelica, OpenModelica, MetaModelica, complier

phases and modules, numerical integration for solver and Susan template language.

Chapter 3: Explains the design and implementation of Template Based Java Code

Generator and Java Runtime System for OpenModelica/MetaModelica.

Chapter 4: Demonstrates the different test case and simulation to show the performance of

the implementation.

(10)
(11)

11

Chapter 2

Background

In this chapter, some theoretical background and technology needed for the implementation is described. Initially, an overview of Modelica and OpenModelica for modeling and simulation environment is given. In the section 2.2, an introduction to compiler construction and its phases is described along with the modules of OMC. In the next section, the Run-time algorithms for numerical integration and event handling are discussed. Finally, the Susan template language is described which is used for the implementation of this thesis work.

2.1 Modelica and OpenModelica

Modeling and simulation plays a vital role in many industries, because modeling and simulation gives an overview of the actual system before it is implemented in the real world. There are many modeling and simulation tools are available. In this thesis work, we focus in OpenModelica and its extension MetaModelica.

Modelica is an object oriented and equation based language for modeling and simulation of multi domain such as mechanical, electrical, hydraulic, control subsystems etc. The Modelica Association is a non-profit organization which supports the development of the open standard Modelica and the open source Modelica Standard Library.

The OpenModelica is an open source project for Modelica based modeling, compilation and simulation environment. The major development of OpenModelica is done in Linköping University, PELAB. OpenModelica is supported by non-profit organization, Open Source Modelica Consortium (OSMC). There are many development is in under construction, recently new version of OpenModelica1.9.0 beta 4 has been released including the different tools as shown below in the figure 2.1.

(12)

12

Figure 2.1: The overall architecture of the OpenModelica environment

 An OpenModelica Compiler (OMC) –The OMC translates Modelica source code to an executable C code for simulation.

 An interactive session handler (OMShell) – An OMShell provides a command interface to OMC. 

 The OpenModelica Notebook (OMNotebook) – OMNotebook gives a tutorial for Modelica. In addition, Modelica models can be written and simulated on it. 

 The OpenModelica Development Environment (OMDev) – The OMDev is a tool for building OMC. 

 A Modelica eclipse plugin (MDT-Modelica Development Tooling) – MDT is used for Modelica development, code browsing, and simulation. 

 Modelica Debugger – The Modelica debugger used for debugging an extended algorithm subset of Modelica by using eclipse for displaying and positioning. 

 Graphical model editor – The OpenModelica Connection Editor (OMEdit) is used for graphical model editing, plotting and browsing of the Modelica standard library. 

2.2 OpenModelica Compiler Phases and Modules 2.2.1. The OpenModelica Compiler Phases

A Modelica Compiler - The OMC translates Modelica source code to executable C code for simulation by several phases. In this section, we give a short description for every phase with the help of OpenModelica compiler phases shown in figure 2.2.1 below.

(13)

13

Figure 2.2.1: The OpenModelica compiler translation phases Phases of compiler are as follows:

1. The first phase of the compiler is Scanner (input: symbols, output: tokens), which produce tokens from the Modelica model symbols.

2. The second phase of the compiler is Parser (input: tokens, output: abstract syntax tree), which translates the tokens to flattened model with list of variables, equation, function. 3. The Analyzer (input: abstract syntax tree, output: error messages, abstract syntax tree), which is used for type checking, import statements, handling of inheritance, modifications and all other object oriented operations are also performed in this phase.

4. Optimization (input: abstract syntax tree, output: (optimized) abstract syntax tree), which gives the Optimized sorted equation.

5. Code Generator is an important phase of the compiler (input: abstract syntax tree, output: executable code). Code generation generates the final code (this is typically architecture specific, one has to consider memory issues, etc.)

6. In the last phase of OMC, the code generator generates C code which is then pass to a C compiler to produce executable code for simulation.

(14)

14

Interested readers to know the detailed compiler phases are encouraged to go through the “Compliers Principles, Techniques, & Tools” book[3].

2.1.2 The OpenModelica Compiler Modules

The OMC has around 40 modules. The brief descriptions of each module can be found in the OpenModelica system documentation and figure2.2.2a shown below for a quick reference.

Figure 2.2.2a: Module connections and data flows in the OMC

In this section, we will describe only the most important modules of OMC and its short description, see also figure 2.2.2b below.

1. The parser generates Abstract Syntax (Absyn) which is then converted into a simplified intermediate form (SCode).

2. The code instantiation module (Inst) calls Lookup to find a name in an environment. It also generates the Differential Algebraic Equation (DAE) representation which is simplified by DAELow.

3. The Ceval module performs compile time or interactive expression evaluation and returns values.

4. The static module performs static semantic and type checking.

5. SimCode is the data structure for representing solved equation code which then can be used to generate different target code in code generation phase.

(15)

15

Figure 2.2.2b: The OpenModelica compiler most important modules

2.3 MetaModelica

MetaModelica is a unified equation-based modeling language specifically designed for OMC development. MetaModelica is an extended subset of Modelica used for the development of OMC. There are some extended features such as local equations, pattern equations, match expressions and high level data structures are matchcontinue, uniontype, list and the option type.

The MetaModelica uniontype construct used to specify the type of each node in the AST. It declares one or more record members. The structure of uniontype may be recursive (i.e., the records are allowed to contain uniontype members). See the listing 2.3 for an example on how to declare an expression uniontype of six record types.

uniontype Exp

record INT Integer value; end INT; record ADD Exp lhs; Exp rhs; end ADD; record SUB Exp lhs; Exp rhs; end SUB; record MUL Exp lhs; Exp rhs; end MUL; record DIV Exp lhs; Exp rhs; end DIV; record NEG Exp exp1; end NEG; end Exp;

Listing 2.3: Exp Abstract syntax definition using MetaModelica Uniontype constructs The AST representation of the expression 10+3*8 by using the Exp abstract syntax definition is shown below in the Figure 2.3.

(16)

16 ADD INT MUL 10 INT INT 3 8

Figure 2.3: AST of 10+8*3 in the language Exp

See the listing 2.3.b for an example on how to declare a match constructs in MetaModelica.

function eval input Exp in_exp; output Real out_real; algorithm

out_real := match in_exp

local Real v1,v2,v3; Exp e1,e2; case RCONST(v1) then v1; case ADD(e1,e2) equation

v1 = eval(e1); v2 = eval(e2); v3 = v1 + v2; then v3;

case SUB(e1,e2) equation

v1 = eval(e1); v2 = eval(e2); v3 = v1 - v2; then v3;

case MUL(e1,e2) equation

v1 = eval(e1); v2 = eval(e2); v3 = v1 * v2;then v3;

case DIV(e1,e2) equation

v1 = eval(e1); v2 = eval(e2); v3 = v1 / v2; then v3;

case NEG(e1) equation

v1 = eval(e1); v2 = -v1; then v2;

end match; end eval;

Listing 2.3.b: MetaModelica match constructs

2.4Numerical Integration

In this section, we explain the numerical integration procedure and methods used in this thesis work to solve the ODE equations in solver.

2.4.1 Introduction to Numerical Integration

One of the inputs to the final code generation step, with the limited set of models used in this thesis, is a set of explicit ODEs on the form:

x ' ( t )= f ( x( t ) , u( t ) ,t ) …. (2.1) with initial conditions:

(17)

17

In equation (2.1) x is the state vector, u is the input vector, and t represents time. We are not considering any input to our Modelica model while simulation so we may skip the u(t) part from equation (2.2) and thus form a new equation (2.3). The new equation can be written as:

x ' ( t )= f ( x( t ) , t ) ….. (2.3) Our task is to calculate the state vector x and derivative x' of these states of the specified time t. We can get the value of state vector x by analytically calculating them one by one but is not possible in all cases specially if there are many time stamps and multiple state variables. The alternative is to use the numerical integration methods. By using the numerical integration methods, we can get the approximated values. Although it is not always possible to get the accurate results but approximated values very close to the accurate ones. The approximated values can be calculated at any given point using Taylor-Series expansion for every element of xi: xi( t∗ +h )= xi( t∗ )+dxi( t∗ ) dt .h+ d2xi( t∗ ) dt2 . h2 2 !+. .. …. (2.4)

By plugging in equation (2.3) we get:

xi( t∗ +h )= xi( t∗ )+fi( t∗ ). h+dfi( t∗ )

dt . h2

2 !+.. . …. (2.5)

2.4.2 Euler Integration

Euler integration is the first-order numerical procedure for solving ODEs. The Euler integration algorithm is formed by taking only the linear part from the Taylor Series equation (2.5), such as:

xi(t*+ h)¿ xi(t*) + x'i(t*) . h ….(2.6)

We use the approximation sign here instead of the equal sign, this is because we are just taking the linear part and ignoring the rest of the Taylor equation of (2.5). Now the above equation (2.6) scheme is very simple comparatively to Taylor series equation (2.5) because it doesn't hold any higher-order derivatives. We call this integration scheme Forward Euler algorithm since this numerical integration algorithm depends only on the past values of states and state derivatives unlike Backward Euler 3 [3].

Recall equation (2.2), with initial conditions, x(t = t0) = x0, we can write the rest of steps as

follows:

step 1a: x'(t0) = f(x(t0); t0)

step 1b: x(t0 + h) = x(t0) + h . x'(t0)

step 2a: x' (t0 + h) = f(x(t0 + h); t0 + h)

(18)

18 step 3a: x' (t0+ 2h) = f(x(t0 + 2h); t0 + 2h) step 3b: x(t0 + 3h) = x(t0 + 2h) + h . x'(t0 + 2h) x(t) x' time t t+h

Figure 2.4: Numerical integration using the Forward Euler method.

Backward Euler integration scheme depends on past as well as current values of variables. *Note this integration is not discussed in this thesis.

2.5 Event Handling

In this section, we address about events and how we handle events in run-time system.

2.5.1 Events

An event (or discrete changes) is simply something that happens. Events are associated with a point in time, state and conditional equation. The An Event in Modelica is something that happens and has the following four properties: taken from [2 ]

 A point in time that is instantaneous, i.e., has zero duration.

 An event condition that switches from false to true for the event to happen.

 A set of variables that are associated with the event, i.e., are referenced or explicitly changed by equations associated with the event.

 Some behavior associated with the event, expressed as conditional equations that become active or are deactivated at the event. Instantaneous equations are special case of conditional equations that are active only at events.

The short definitions of different events are given below:

Timed event: An event is triggered by time and the corresponding event-action takes place.

An example is shown below, when time >=10.0 then event-action1; end when;

State event: An event takes place in a particular state that triggers an action.

Conditional Event: An event takes place after satisfying a condition which triggers an action.

An example is shown below, when event-conditions then

Actual Value

(19)

19 event-action1; event-action2; … end when; 2.5.2 Run-time Algorithm

The following flowchart is shown in the figure 2.5 gives an overview of how an event is handled in the run time system. The each and every step of the flowchart is described below. First of all the simulation must be initialized consistently. By use of the initial conditions the initial values for the entire system can be determined. This will also execute all initial events at time .

After the initialization the main simulation loop starts with the continuous integration step that calculates the states and state derivatives with its size value. With the new values of states and state derivatives, the functions “Solver and CSVBuilder” can be evaluated. Thus, the entire continuous system is determined.

The continuous integration step is accepted if no event has occurred then the values can be saved and the next step can be performed. If an event has occurred then the value of condition changes, an event occurred within the interval and . Then the exact time has to be detected.

The continuous part is evaluated at the time just before the event and all values are saved to provide them to the pre() operator. Then the entire system is evaluated by the functions again. At this point the event is handled and the further events are handling by loop.

The main simulation loop will repeat until it reaches the end time. This helps us to get the simulation time for Run-time system.

(20)

20

(21)

21

2.6 The Susan Template Language

In this section, we explain the Susan template language which is used in implementation of Java code generator. Susan is a functional, strongly typed, expression oriented template language which is specifically designed for OMC with the following main advantages are:

 Increases readability  

 Compiled to reach maximum performance  

 Provides a full vehicle for different target code generation such as C++, Java, C# etc...  

Susan template expressions can consists of conditional expressions, match-expressions, function calls, iterator expressions, and etc. For more expressions and its complete description refer the Susan template guide. The match expression in the template language is used for distinction of AST structure nodes declared in MetaModelica union types. See the listing 2.6 for an example of how pattern matching against a tree structure of figure 2.6.

ADD

INT MUL

10

INT INT

3 8

Figure 2.6: AST of 10+8*3 in the language Exp

template exp(Exp inExp) ::= match inExp

case INT(__) then value

case ADD(__) then '<%exp(lhs)%> + <%exp(rhs)%>' case SUB(__) then '<%exp(lhs)%> - <%exp(rhs)%>' case MULT(__) then '<%exp(lhs)%> * <%exp(rhs)%>' case DIV(__) then '<%exp(lhs)%> / <%exp(rhs)%>' case NEG(__) then '- <%exp(exp1)%> '

end exp;

Listing 2.6: Template “exp” - Pattern matching example

The template function exp is recursive. The scope of the INT constructor is automatically opened by using INT(__) pattern to make its field (i.e., value) available, and the ADD, SUB, MUL, DIV and NEG constructors are opened automatically by using the ADD(__), SUB(__),

(22)

22 MUL(__), DIV(__) and NEG(__) pattern respectively.

(23)

23

Chapter 3

Design and Implementation

This chapter describes the design and implementation of this thesis work. Initially, we present the process of Java code generator design and implementation in OMC. Secondly, we present the process of Java runtime system design and implementation for simulation.

3.1 Java Code Generation

To design a Java code generator with the basic block diagram as shown in Figure 3.1a. Java code generator takes the input as Modelica model and process in the generator to produce an output as Java code corresponding to the Modelica model.

Input Output

Figure 3.1a: Block diagram for Java code generator

Code generator generates the Java code from the modelica model though OMC. The block diagram for OpenModelica Compiler for Java Code Generation is shown in the figure 3.1b. below. Code generator is depends directly on the SimCode’s solved equations (SimCodeTV). So, the SimCodeTV module is important to understand, SimCodeTV is data structure for solved equations. SimCodeTV contains many data structure representation, but in this section we describe only some data structure.

DAELow

Solved Equations

Java Code

Figure 3.1b: Block diagram for OpenModelica Compiler for Java Code Generation

Modelica Model

OMC Front End

SimCodeTV Code Generator Simulation Modelica Model (testmodel.mo) Java Code Generator

Java Coded Model (testmodel.Java)

(24)

24

Java code generation is implemented by passing the correct data structure into SimCodeTV data structure as function template in Susan template language. The main functions of Java code generation templates are described in the following sections.

3.1.1 Root Template

Root template is top level of code generation, it generates java file which is also a target file can be used for simulation in Java Runtime System. It also consists of main function which is “simulationFile(simCode)” as shown below in the listing 3.1.1.

Listing 3.1.1: Root template for Java Code generation

3.1.2 Java Specific File Template

In this section, we are going to elaborate more on the main funtion “simulationFile(simCode)”. This main template function consists of set of templates which is used to generate a Java file as complete Java executable file. The file consists of necessary packages, class declaration, variable declarations, constructor, functions, external functions and main class declaration. The main template “simulationFile(simCode)” is defined as shown below in the listing 3.1.2.

template translateModel(SimCode simCode)

"Generates Java code and Makefile for compiling and running a simulation of a Modelica model."

::=

match simCode

case SIMCODE(modelInfo=modelInfo as MODELINFO(__)) then let()= textFile(simulationFile(simCode),

'<%fileNamePrefix%>.java')

"" //empty result for true case

//this top-level template always returns an empty result //since generated texts are written to files directly

end translateModel;

template simulationFile(SimCode simCode)

"Generates code for main Java file for simulation target." ::=

match simCode

case SIMCODE(modelInfo = MODELINFO(__)) then << <%simulationFileHeader(simCode)%> <%modelClassName(simCode)%> <%addGlobalInitialization(modelInfo, simCode)%> <%modelClassConstructor(simCode)%> <%functionInput(modelInfo, simCode)%> <%functionOutput(modelInfo, simCode)%> <%functionBoundParameters(parameterEquations, simCode)%> <%functionODE(odeEquations, simCode)%>

<%functionDAE(allEquations, whenClauses, relations, simCode)%> <%functions(modelInfo.functions, recordDecls, simCode)%>

<%mainFunction(simCode)%> >>

(25)

25

Listing 3.1.2: Main temaple for Java specific file in Java Code generation

3.1.3 simulationFileHeader Template

This Java code generation template is responsible for importing the necessary packages, which are used in the Java file, as header for the Java file. The header template is shown below in the listing 3.1.3., and an example is shown in the Listing 3.1.4a.

Listing 3.1.3: simulationFileHeader template for Java Code generation

3.1.4 modelClassName Template

This Java code generation template corresponds to the model class declaration and initializing Data object with necessary parameters. In this model class declaration template, declares class name as model name, number of states, output file name and initializing a new SimData as data object. As shown below in the listing 3.1.4.

Listing 3.1.4: modelClassName template for Java Code generation

Example 1: Representation of simulationFileHeader and modelClassName declaration are

shown in the listing 3.1.4b., for the below model is shown in the listing 3.1.4a.

In the below model “AddReal.mo”, consists of two algebraic parameters and an algebraic template simulationFileHeader(SimCode simCode)

"Generates header part of simulation file." ::=

match simCode

case SIMCODE(modelInfo=MODELINFO(__), extObjInfo=EXTOBJINFO(__)) then <<

package CodegenJava; // solver package name import java.io.IOException; import java.math.*; import java.lang.Thread.State; import java.util.Vector; >> end simulationFileHeader;

template modelClassName(SimCode simCode)

"Generates model class name of simulation file." ::=

match simCode

case SIMCODE(modelInfo=MODELINFO(varInfo = vi as VARINFO(__)), extObjInfo=EXTOBJINFO(__)) then

let noOfstates = if vi.numAlgVars then vi.numAlgVars else vi.numStateVars <<

/* Simulation code for <%dotPath(modelInfo.name)%> generated by the OpenModelica Compiler <%getVersionNr()%>.*/

@SuppressWarnings("unused")

public class <%dotPath(modelInfo.name)%> extends SuperModel // name of the given model

{

static int n= <%noOfstates%>; // n --> number of states

static String filename = "<%dotPath(modelInfo.name)%>_result.txt"; /* Simulation output file */

public static SimData localData = new SimData(n, 0, 0); /*

Initializing a Data Object*/ >>

(26)

26

variables. It also consists of an ODEs equation with an external function called addReal1_.

Listing 3.1.4a. Model AddReal1.mo

Listing 3.1.4b:Example of simulationFileHeader and modelClassName declaration

3.1.5 addGlobalInitialization Template

This Java code generation template corresponds to the initialization of global variables and parameters. In this template, we declare algebraic variable parameter lists such as variables, parameters, integer variables, integer parameters, string variables, string parameters and external objects under separate subsections in order to easy understand for the users. The example is shown in the listing 3.1.6a.

3.1.6 modelClassConstructorTemplate

This Java code generation template corresponds to the declaration of a constructor. In this template, the generation of class constructor with the state initialization as in model or set as default for the equations. The example is shown in the listing 3.1.6a.

Example 2: Representation of global initialization and constructor as shown in the listing

3.1.6a. for the model “AddReal.mo” mentioned in listing 3.1.4a. package CodegenJava; // solver package name

import java.io.IOException; import java.math.*;

import java.lang.Thread.State; import java.util.Vector;

/* Simulation code for AddReal1 generated by the OpenModelica Compiler 1.9.0 beta4+dev (r16707).*/

@SuppressWarnings("unused")

public class AddReal1 extends SuperModel /* name of the given model */ {

static int n= 1; // n --> number of states

static String filename = "AddReal1_result.txt"; /* Simulation output file */

public static SimData localData = new SimData(n, 0, 0); /* Initializing a Data Object */

model AddReal1 parameter Real a=2.3; parameter Real b=4.5; Real c; equation c = addReal1_(a, b); end AddReal1; /* Algebraic Vars */

double c[] = new double [1]; /* c */ /* Algebraic Parameter */

double a = 2.3; /* a */ double b = 4.5; /* b */ public AddReal1() // constructor {

/* States Initialization Ordinary equations */ localData.x/*state*/.add(0,0.0); /* $dummy */ /* States Initialization algebraic equations */ localData.x/*state*/.add(0,0.0); /* c */ }

simulationFileHeader

(27)

27

Listing 3.1.6a:Example of global initialization and constructor for AddReal1.mo

3.1.7 functionBoundParameters Template

In this function BoundParameters, the parameters for state algebraic equations are bounded with corresponding state derivatives. This function is being called in functionODE, functionDAE to update the algebraic equations. The parameter equations are either “SES_SIMPLE_ASSIGN” or “SES_ALGORITHM” defined as shown below in the listing 3.1.7.

Listing 3.1.7: functionBoundParameters Template for Java code generation

Example 3: Representation of bound parameter is shown in the listing 3.1.7b. for the below

model “EquationFor6.mo”. In this model, there are three algebraic variables with three simple algebraic equations respectively and shown in the listing 3.1.7a.

Listing 3.1.7a: EquationFor6.mo

template functionBoundParameters(list<SimEqSystem> parameterEquations, SimCode simCode)

::=

let &tmp = buffer "" <<

public void BoundParameters() {

<% parameterEquations

|> saeq as SES_SIMPLE_ASSIGN(__) => equation_(saeq, contextOther, simCode, &tmp) ;separator="\n"%>

<% parameterEquations

|> eq as SES_ALGORITHM(__) => equation_(eq, contextOther, simCode, &tmp) ;separator="\n"%> } >> end functionBoundParameters; class EquationFor6 Real a[3]; equation for i loop a[i] = i; end for; end EquationFor6; // Result: // class EquationFor6 // Real a[1]; // Real a[2]; // Real a[3]; // equation // a[1] = 1.0; // a[2] = 2.0; // a[3] = 3.0; // end EquationFor6; // endResult Flattened Model

(28)

28

Listing 3.1.7b:Example of bound parameter function for EquationFor6.mo

3.1.8 functionODE Template

This Java code generation template is an important function for the simulation. In this template, only the “statecontEquations” implemented. If the model consists of ordinary differential equation then the corresponding “equation_” will be executed. The “equation_” template is the root template for the entire equations such as SES_SIMPLE_ASSIGN, SES_ARRAY_CALL_ASSIGN, SES_ALGORITHM, SES_WHEN. StatesAssign template is useful for declaring the variables locally. Finally “BoundParameters” function will be called to update the changes in stateDerivative if any. The functionODE template is defined as shown in the listing 3.1.8 and its representation of functionODE is shown in the listing 3.1.9a. for “BouncingBall.mo” model.

Listing 3.1.8: functionODE Template for Java code generation public void BoundParameters()

{

localData.xdot/*stateDerivative*/.add(0,1.0); //a[1] = 1.0; localData.xdot/*stateDerivative*/.add(1,2.0); //a[2] = 2.0; localData.xdot/*stateDerivative*/.add(2,3.0); //a[3] = 3.0; }

template functionODE(list<list<SimEqSystem>> stateContEquations, SimCode simCode) ::= match simCode case SIMCODE(modelInfo = MODELINFO(varInfo=VARINFO(numStateVars=numStateVars), vars=SIMVARS(__))) then match modelInfo case MODELINFO(varInfo=VARINFO(numStateVars=numStateVars), vars=SIMVARS(__)) then

let &tmp = buffer "" <<

public void functionODE() {

<%StatesAssign("states", vars.stateVars, simCode) ;separator="\n"%>

<%StatesAssign("states", vars.algVars, simCode) ;separator="\n"%>

<%stateContEquations |> eqs =>

(eqs |> it => equation_(it, contextOther, simCode, &tmp) ;separator="\n") ;separator="\n"%> BoundParameters(); } >> end functionODE;

(29)

29

3.1.9 functionDAE Template

In this template, all type of equations with when-clauses is implemented. For every equation, the corresponding “equation_” will be executed. StatesAssign template is useful for declaration of variables locally. The functionDAE template is defined as shown in the listing 3.1.9 and its representation of functionDAE is shown in the listing 3.1.9a. for “BouncingBall.mo” model.

Listing 3.1.9: functionDAE Template for Java code generation

Example 4: Representation of functionODE and functionDAE are shown in the listing 3.1.9b.

for the “BouncingBall.mo” as shown in listing 3.1.9a. This model contains two basic equations and when equation as discrete issues suitable for functionODE and functionDAE.

Listing 3.1.9a: BouncingBall.mo

model BouncingBall "The bouncing ball model"

constant Real g = 9.81; // Gravitational acceleration parameter Real c = 0.9; // Elasticity constant of ball parameter Real radius = 0.1; // Radius of the ball

Real height(start = 1); // height above ground of the ball center Real velocity(start = 0); // Velocity of the ball

equation

der(height) = velocity; der(velocity) = -g;

when height <= radius then

reinit(velocity, -c*pre(velocity)); end when;

end BouncingBall;

template functionDAE(list<SimEqSystem> allEquationsPlusWhen, list<SimWhenClause> whenClauses, list<ZeroCrossing> relations, SimCode simCode)

"Generates function in simulation file." ::= match simCode case SIMCODE(modelInfo = MODELINFO(varInfo=VARINFO(numStateVars=numStateVars), vars=SIMVARS(__))) then match modelInfo case MODELINFO(varInfo=VARINFO(numStateVars=numStateVars), vars=SIMVARS(__)) then

let &varDecls = buffer "" /*BUFD*/ let &tmp = buffer ""

<<

public void functionDAE() {

<%StatesAssign("states", vars.stateVars, simCode) ;separator="\n"%>

<%StatesAssign("states", vars.algVars, simCode) ;separator="\n"%> <%allEquationsPlusWhen |> eq => equation_(eq,

contextSimulationDiscrete, simCode, &tmp) ;separator="\n"%>

<%whenClauses |> when hasindex i0 => genreinits(when, relations, contextOther, &varDecls, simCode)

;separator="\n" %>

} >>

(30)

30

Listing 3.1.9b:Example of functionODE and functionDAE for BouncingBall.mo

3.1.10 functions Template

In this template, Java code generation for user defined functions and external functions. The root template for this “functionJava” is “functions” template which contains the list of functions “list<Function>”. This template is the root for the following templates such as user defined functions, external functions and the record constructor. The “functionJava” template is defined as shown in the listing 3.1.10.

Listing 3.1.10: Functions and external functions Template for Java code generation

Example 5: Representation of external function is shown in the listing 3.1.10a. for the

“AddReal.mo” model, which consists of a ODEs equation with an external function called “addReal1_” in C language.

public void functionODE() {

double velocity = localData.getState().elementAt(0); double height = localData.getState().elementAt(1); localData.xdot.add(0,-9.81);

localData.xdot.add(1,velocity); BoundParameters();

}

public void functionDAE() {

double velocity = localData.getState().elementAt(0); double height = localData.getState().elementAt(1); localData.xdot.add(0,-9.81);

localData.xdot.add(1,velocity);

//(height <= radius) "Condition Relation" if (height <= radius)

{

velocity = ((-c) * velocity);

} }

template functionJava(Function fn, list<RecordDeclaration> recordDecls, SimCode simCode)

"Generates the body for a function." ::=

match fn

case fn as FUNCTION(__) then regularFunction(fn, simCode) case fn as EXTERNAL_FUNCTION(__) then externalFunction(fn, simCode) case fn as RECORD_CONSTRUCTOR(__) then recordsJava(recordDecls) end functionJava;

(31)

31 AddReal1.mo

Listing 3.1.10a:Example of external functions for AddReal1.mo

3.1.11 mainFunction Template

This Java code generation template corresponds to the main class declaration and invokes the EulerSolver with correct parameters. It is shown below in the listing 3.1.11.

Listing 3.1.11: mainfunction Template for Java code generation

Example 9: Representation of main function for the class model is shown in the listing

3.1.11a. for the AddReal1.mo.

template mainFunction(SimCode simCode) ::=

match simCode

case SIMCODE(modelInfo = MODELINFO(__)) then <<

public static void main(String[] args) throws IOException {

<%dotPath(modelInfo.name)%> temp = new <%dotPath(modelInfo.name)%>();

temp.functionODE();

/* Invoke the Solver with correct parameters */

EulerSolver.main(localData.stepsize, localData, temp, filename); } } >> end mainFunction; function addReal1_ input Real x; input Real y; output Real res; external "C"; end addReal1_; model AddReal1 parameter Real a=2.3; parameter Real b=4.5; Real c; equation c = addReal1_(a, b); end AddReal1;

public void BoundParameters() {

/*Function Call*/

localData.xdot/*stateDerivative*/.add(0, addReal1__(a,b)); }

public double addReal1__(double arg_x , double arg_y) /*Function*/ {

double res;

double x = arg_x; double y = arg_y;

return res = addReal1_(x,y); /*externalFunction*/ }

(32)

32

Listing 3.1.11a:Example of global initialization and constructor for AddReal1.mo

3.1.12 daeExp Template

This Java code generation template is the root template for all the expressions. The expressions which are used in models are flattened, and those expressions “exp” match the corresponding case in this template in order to translate into a Java code. This template is defined below in the listing 3.1.12.

Listing 3.1.12:daeExp template for Java code generation public static void main(String[] args) throws IOException {

AddReal1 temp = new AddReal1(); temp.functionODE();

/* Invoke the Solver with correct parameters */

EulerSolver.main(localData.stepsize, localData, temp, filename); }

template daeExp(Exp exp, Context context, Text &preExp /*BUFP*/, SimCode simCode)

"Generates code for an expression." ::=

match exp

case e as ICONST(__) then integer case e as RCONST(__) then real

case e as SCONST(__) then daeExpSconst(string, context, &preExp /*BUFC*/, simCode)

case e as BCONST(__) then if bool then "true" else "false" case e as ENUM_LITERAL(__) then index

case e as CREF(__) then daeExpCrefRhs(e, context, &preExp, simCode)

case e as BINARY(__) then daeExpBinary(e, context, &preExp /*BUFC*/, simCode)

case e as UNARY(__) then daeExpUnary(e, context, &preExp /*BUFC*/, simCode)

/**************************** Some code removed here *************** *******************************************************************/ case e as CAST(__) then daeExpCast(e, context, &preExp /*BUFC*/, simCode)

case e as ASUB(__) then daeExpAsub(e, context, &preExp /*BUFC*/, simCode)

case e as TSUB(__) then '<%daeExp(exp, context, &preExp, simCode)%>'

case e as SIZE(__) then daeExpSize(e, context, &preExp /*BUFC*/, simCode)

case e as BOX(__) then daeExpBox(e, context, &preExp /*BUFC*/, simCode)

case e as UNBOX(__) then daeExpUnbox(e, context, &preExp /*BUFC*/, simCode)

case e as SHARED_LITERAL(__) then '_OMC_LIT<%index%>' // META_TUPLE

// META_OPTION // METARECORDCALL

else error(sourceInfo(), 'Unknown expression: <%ExpressionDump.printExpStr(exp)%>')

(33)

33

The interested readers who wants to know more about Java code generator implemention are welcome to go though the full implemention code in the section “Appendix B Implementation code”.

3.2 Java runtime system

Java Runtime System takes the java files as input and returns the simulation results to verify the model. Runtime system is needed for every specific programming language. The block diagram for Java Runtime System is shown below in the Figure 3.2a.

Input Output

Figure 3.2a: Block diagram for Java Runtime System

The class diagram for Java Runtime System is shown below in the Figure 3.2b, and consists of

 SimModel – Java coded model which is generated from Java code generator.

 SimData – The dynamic data for a simulation at a given time.

 Solver: Euler's method for numerical integration.

 Super Model – This is the superclass for any model class generated from Modelica.

 Static Model – A ModelicaModel with its static information.

 Modelica Variable –Static information about a single variable in the model.

 Modelica Equation: A single equation in the Modelica model.

Figure 3.2b: Class Diagram for Java Runtime System

Java coded model (testmodel.Java) Java Runtime System Simulation test results Super Model SimModel (testmodel.Java) EulerSolver Modelica Variable SimData Static Model Modelica Equation testmodel_result.txt Output

(34)

34

The description of the class diagram and its implementation is discussed in the following sections.

3.2.1 SimModel

The SimModel is a Java coded model which is generated by using Java code generator for the corresponding modelica model. The Java code model contains the packages, class declaration, variable declaration, class constructor, functions, external functions and the main class declaration.

The sample Java code for modelica models are given in the section “Appendix A” for some test models.

3.2.2 SimData

SimData class is being initialized by the model class declaration object in SimModel. After the initialization, this class is ready for simulation at a given time. This class contains the values of state and state derivative in appropriate format for the solver. The state and state derivatives are initialize as Vector type as Double for better efficiency for runtime system. This class also contains default simulation settings. This SimData implementation is shown in the listing 3.2.1. package jrt; import java.util.*; import org.jscience.physics.amount.* ; import javax.measure.quantity.* ; /*** @author georg@schaathun.net***/

public class SimData {

double time ; int size;

double start;

double stepsize;

double stop;

/* Initialize as Vector type as Double*/ Vector<Double> x = new Vector<Double>(); Vector<Double> xdot = new Vector<Double>() ;

public SimData( int xdim, int mdim, int zdim ) {

// simulation default settings size = xdim;

start = 0.0; stepsize = 0.002; stop = 1.0;

}

/*** Advance to next time step, advancing time by dt.***/

public void advance( double dt )

{

time = time+dt; }

/*** Get the continuous state vector ***/

public Vector<Double> getState()

{

return x ; }

(35)

35

Listing 3.2.1:SimData for Java Runtime System

3.2.3 EulerSolver

Java runtime system uses Euler's numerical integration method. The EulerSolver main class is invoked by SimModel’s main-function with necessary parameters. By using those parameters, the solver main class initializes the output result file (testmodel_result.txt). And the values of state and state derivative values by using SimData object.

In the main simulation loop, the solver function and CSVBuilder function is being called for simulate the model. The function Solver() takes the appropriate parameters in order to do the numerical integration. There are two main operations in the Solver function, one is the setting of state values in the size loop. And the other is the function-call of functionODE ().

The state vectors are compute by using below equation:

states[i] = states[i] + statesDerivatives[i] * (step);

This method is implemented and shown in the listing 3.2.2. This function helps to get the state and statesDerivatives values which is set for the operations and generates the output result file by using CSVBuilder function.

Finally there is an small calculation for simulation time for the model. The outline of the code for time stamp is given below.

// for time measurement

long startSimulationTime = System.currentTimeMillis();

// simulation loop

// end simulation time measurements

long endSimulationTime = System.currentTimeMillis(); // simulation time calculation

System.out.println("Simulation took: " + (endSimulationTime - startSimulationTime)+ " milliseconds.\n");

/*** Get the continuous state derivative vector.***/

public Vector<Double> getDer()

{

return xdot ; }

/*** Get current time.***/

public double getTime()

{

return time ; }

/*** Set the continuous state vector and update time.***/

public void updateState( Vector<Double> x )

{

this.x = x ; }

(36)

36

Listing 3.2.2: Solver Function of EulerSolver.Java for Java Runtime System

For EulerSolver, SuperModel, StaticModel and it’s ModelicaEquation, Modelica Variable. The interested readers who wants to know more about Java Runtime System implemention are welcome to go though the full implemention code in section “Appendix C Java Runtime System”.

public static void Solver( SimData data ,SuperModel model, double dt )

throws IOException

{

Vector<Double> x = data.getState() ; Vector<Double> xdot = data.getDer() ; for(int i=0;i<x.size();i++)

{

x.set(i, x.get(i)+ xdot.get(i)*dt);

}

data.advance( dt ) ; model.functionODE(); }

(37)

37

Chapter 4

Testing

In this chapter, we provide different test cases conducted to test the implementation of the thesis work.

4.1 Modelica Test Models

We have tested around 250 test case models and all the models were successfully generated. We have taken almost all the types of Modelica language constructs from the OpenModelica test suite. The listing.4 shown below is the general description of subset from the OpenModelica test suite. The detailed listing is shown in “Appendix B” with the model name and its simulation time for both Java Runtime System and C Runtime System.

Test Cases Section Description 38

algorithms-functions

In this section, we have tested all type of Algorithms and functions such as inline function, function call, function evaluations.

56 array In this section, we have tested for Arrays, array declarations, array operations such as array addition, division, multiplication, subtraction, xpowers, and etc,. 37 built-in-functions In this section, we have generated Java code for the

built-in-functions which are Acos, Asin, Atan, Cos, Cosh, Log, Log10, Sqrt, Sin, Sinh, Sign, Tan, Tanh, Transpose, Ceil and etc,.

9 declarations In this section, we perform to test the Constant declarations, DeclarationEquations.

32 Equations In this section, we have tested all type of equations with When, for, if condition equations and some hybrid models which is taken from book [2].

23 extends In this section, Some extends models like Colors, Moonlanding, Multiplex, StepAdvanced and some more models are tested.

(38)

38

7 external-functions In this section, we have tested the different external functions for instance AddReal1, ExternalFunctionArray, ExternalFunctionBuiltin, etc.

13 records In this section, we have tested record construct of Modelica language such as RecordAssignment, RecordConstants, and RecordVariability.

30 MetaModelica

models

In this section, we have tested all type MetaModelica such as List, match, partialfunction and uniontype.

Listing 4: Modelica Test Models

In this section, we have chosen one model from OpenModelica and another model from MetaModelica to showcase the implementation of Java code generator and its Java Runtime system works fine. The verification and performance test methods are used for testing the generated models.

4.1.1 Verification Test

The following method is used to verify the test results:

 Generate the simulation output for both C Runtime System (testmodel_res.csv) and Java Runtime System (testmodel_resJava.csv).

 By executing the file Script.mos, a graph is generated. We can verify the model using this graph.

Script.mos

4.1.2 Performance Test

The following method is used for testing the performance of models:

 By executing the file Script_table.mos, a table is generated. The table consists of model name and its simulation time.

 The flag “+s +simCodeTarget=Java” is used for Java Runtime System. The flag “+s +simCodeTarget=C” is used for C Runtime System.

 By using these tables, we can compare the simulation time of models for both C Runtime System and Java Runtime System.

html := diffSimulationResultsHtml("/*any one attribute*/ ", "testmodel_res.csv", "testmodel_resJava.csv");

writeFile("b.html",html);getErrorString(); system("cp " + getInstallationDirectoryPath() + "/share/doc/omc/testmodels/dygraph-combined.js ."); system("chromium-browser b.html &");

(39)

39

Script_table.mos

Model 1: BouncingBall.mo:

The BouncingBall model contains the two basic equations of motion relating height and velocity as well as the acceleration caused by the gravitational force. At the bounce instant the velocity is suddenly reversed and slightly decreased, i.e.,veclocity(after bounce) = -c*veclocity(before bounce), which is accomplished by the special reinit synatactic form.. This model suitable for functionODE and functionDAE. This model is a good example of a hybrid system for which the when-equation is appropriate when modeled. And this discrete model handles the event handling. The full Java code generation of this model is given in section “Appendix A”.

Verification Test:

Figure 4.1.1a: Graph for BouncingBall.mo

mofiles := {"testmodel1.mo", "testmodel2.mo"}; system("rm -f log.csv"); {writeFile(file + ".mos", " loadFile(\""+file+"\"); names:=getClassNames(); name:=names[1]; res:=simulate(name); t:=res.timeSimulation; writeFile(\"log.txt\",typeNameString(name) + \",\" + String(t) + \"\\n\",append=true);

") for file in mofiles};

(40)

40

From this graph, we can conclude that the projection of BouncingBall for both JCG and CCG are almost same. Thus the model is successfully generated using JCG and simulated using JRS.

Performance Test:

Simulation Time For: C Runtime System Java Runtime System

BouncingBall.mo 0.0156448 seconds 0.0209959 seconds The following model is an example of MetaModelica.

Model 2: PartialFn12.mo

This model consists of an equation section with the function call of TestFn(x). This function section has another function call. The full Java code generation of this model is given in the section “Appendix A”.

partial function PartFn input Real x;

output Real y;

end PartFn;

function FullFn extends PartFn;

input Real extraReal1; input Real extraReal2;

algorithm

y := x * ((extraReal1 + extraReal2) / 2.0);

end FullFn;

function CallerFn input Real inReal; input PartFn inPartFn; output Real outReal;

algorithm

outReal := inPartFn(inReal) * 2.0;

end CallerFn;

function TestFn input Real inReal; output Real outReal;

algorithm

outReal := 0; for i in 1:10 loop

outReal := outReal + CallerFn(inReal, function FullFn(1.5,7.5)); end for; end TestFn; model PartialFn12 Real x; Real y; equation x = 2.0; y = TestFn(x); end PartialFn12;

(41)

41

Verification Test:

Figure 4.1.1b: Graph for PartialFn12.mo

From this graph, we can conclude that the projection of PartialFn for both JCG and CCG are almost same. Thus the model is successfully generated using JCG and simulated using JRS.

Performance Test:

Simulation Time For: C Runtime System Java Runtime System

PartialFn12.mo 0.0099915 seconds 0.00943867 seconds

The following bar chart shows the performance of models in JRS and CRS. The performance of Java Runtime System varies from C Runtime System, because C code executes more directly on the hardware platform whereas Java runs on a JVM. Thus the C compiler compiles the code directly into the machine code while the Java compiler compiles into the byte code which is understandable by JVM. Due to this, Java Runtime System takes more time to execute than C Runtime System. In contrast for some models, Java Runtime System executes in lesser time than C Run time System.

(42)

42

Figure 4.1: Bar Chart Graph for Equations Subset 4.2 Improvements from previous version

When we started this thesis work, we used the thesis report of “Template-Based Java Code Generator and Java Runtime System for OpenModelica” by Inam Ul Haq. A. As the development of “Template-Based Java Code Generator” began from his thesis work and listed below the improvements made in this thesis work.

Design:

We started the design of Java Code Generator and Java Runtime System in order to get better efficiency, and to handle hybrid models such as event handling, external functions, records and MetaModelica constructs. With the help of Prof. Hans Georg Schaathun, the new design of Java Runtime System is created and the detailed class diagram is given in the chapter 3.

Implementation: Java Code Generator

We have implemented the Java Code Generator for the whole Openmodelica and Metamodelica constructs. The previous version of the Java Code Generator did not cover the following features:

 Algebraic loops

 Hybrid Models (Event Handling)

 Algebraic Arrays

 External functions

 Records

(43)

43

But, we have implemented the complete Java Code Generator for the entire Modelica constructs, which are not supported in the previous version.

Java Runtime System:

The OpenModelica has changed a lot during the period of two years and this leads to some changes in simCodeTv. As we mentioned before, simCodeTv contains all the data structures which are required for the code generation. So the previous version of Java Code Generator and Java Runtime System does not support the latest version of Openmodelica. Therefore we couldn’t use the previous version of Java Runtime System anymore. This leads to the new design of Java Runtime System based on the previous version. We have implemented the complete Java Runtime System which supports the latest version of Java Code Generator.

Testing:

We have used the script files for verification testing and performance testing, which were not used in the previous version. It is used to test the group of models which makes the testing process easier and efficient. The produced results are very accurate and clear, which is used to compare the simulation time of Java Runtime System with C Runtime System. We have used a total of 250 test cases which are passed successfully, from which we can conclude that the entire Modelica constructs are covered. The previous version does not cover the entire Modelica constructs.

(44)
(45)

45

Chapter 5

Conclusion and Future Work

This chapter concludes the work conducted in this thesis work and discussion the possible directions for future work.

5.1 Conclusion

In this thesis work, we have implemented an extended version of the previous subset Java Code Generator by using Susan template based language. We have tested around 250 test cases which cover almost all types of Modelica language constructs. This code generation will be helpful to open the OpenModelica Java code generator to a wide range of users both academic and commercial.

5.2 Future Work

The current version of SimCodeTv is unstable and the Java Code Generation is fully dependent on the SimCodeTv. If the SimCodeTv is modified in future then the Java Code Generation will be interrupted. Thus in order to support the Java Code Generation, a stable SimCodeTv can be implemented.

Another task for future work is to implement a Click-on button in OMEdit which makes exporting models to an Java format from OpenModelica straightforward for users. To implement a click-on button in OMEdit.

(46)
(47)

47

User Guide

1. Install OpenModelica Compiler. Follow the instructions found in https://www.openmodelica.org/index.php/developer/source-code 2. Compiling a model and generate Java code

The following step compiles a model to a Java code generation.

- Open the mingw terminal if you are a windows user and normal terminal for linux user - In the terminal window go to the path where your model file found(C:/<%path to .mo file%>).

- Go to omc path (<%path to omc%>/omc) and write the flag +s +simCodeTarget=Java <%your.mo file%>.mo>

This is demonstrated in the following example, where +s +simCodeTarget=Java is the flag specific for Java code generation and Circle.mo is the model name.

Once compilation has completed successfully a Java file will have been generated and can be found in the same directory as your model found.

(48)
(49)

49

References

[1] OpenModelica project. https://www.openmodelica.org/

[2] TDDB44 Compiler Construction course http://www.ida.liu.se/~TDDB44/index.en.shtml. [3] The OpenModelica source code. Available from

https://openmodelica.org/svn/OpenModelica/trunk/Compiler/Template/ User name: anonymous, Password: none

Books:

[4] Peter Fritzson. Principles of Object-Oriented Modeling and Simulation with Modelica, Wiley-IEEE Press, 2003.

[5] Alfred V.Aho, Monica S.Lam, Ravi Sethi, Jeffrey D.Ullman. Compilers Principles, Techniques, & Tools, Second Edition, Addison Wesley, 2006.

[6] David J. Barnes, Michael Kölling. Objects First with Java, third edition, Pearson Education Limited, 2006.

Technical reports:

[7] Peter Fritzson, Pavol Privitzer Adrian Pop, and Martin Sjölund. Towards a Text Generation Template Language for Modelica. Technical report in Computer and Information Science, Linköping University Electronic Press, September 2009.

[8] Peter Fritzson, Adrian Pop, and Martin Sjölund. Towards Modelica 4 Meta-Programming and Language Modeling with MetaModelica 2.0, Technical report in Computer and Information Science, Linköping University Electronic Press, May 2011. [9] Peter Fritzson, Adrian Pop, and Martin Sjölund. Meta-Programming and Language

Modeling with MetaModelica 1.0, Technical report in Computer and Information Science, Linköping University Electronic Press, March 2011.

[10] Peter Fritzson. Modelica Text Template Language Susan Users Guide v0.2, Technical report in Linköping University, PELAB - Programming Environment Laboratory, April 2010.

Thesis:

[11] Inam Ul Haq. A Template-Based Java Code Generator and Java Runtime System for OpenModelica. Master's thesis, PELAB, Linköping University, Department of Computer and Information Science, August 2011.

[12] Rickard Lindberg. A Template-Based Code Generator for the OpenModelica Compiler. Master's thesis, PELAB, Linköping University, Department of Computer and Information Science, March 2010.

[13] Martin Sjölund. Bidirectional external function interface between Modelica/MetaModelica and Java. Master's thesis, PELAB, Linköping University, Department of Computer and Information Science, August 2009.

(50)

References

Related documents

As an analyzing tool, Carol Bacchi’s theoretical approach ”What’s the problem represented to be?” (WPR) will be used. The framework discusses what the problem is instead

Looking only at longer work periods like in Case 1a, the resulting schedule without any constraint on the collaboration distribution is seen in Figure 5.7.. Figure 5.8 shows the

Many  patients  are  diagnosed  as  having  chronic  heart  failure  (CHF)  and  apart  from  the  fact  that  daily  activities  are  impaired,  they  are 

The reason why Python is considered to be one of, if not the best machine learning language is because of the flexibility and support it holds, where it uses parts of both

Krantz kartlägger dessa försvar och menar på att dessa ”stödben” måste kapas för att bilisterna ska förändra sitt beteende (Krantz 2001: 179). Två olika typer av försvar

Den naturliga beständigheten och fukttrögheten hos furukäma och gran kan vara ett bra komplement till andra åtgärder (konstruktion, fuktawisade behandling) när man söker ett

Undersökningen syftat till att synliggöra vad 1940- talets lokalmedia och riksmedia skriver fram till sina läsare om Anna Larsson, vad fokuserar media på att skriva fram om

As such this use case is particularly applicable for Managed Security Service Providers and for Cloud user organisations who want to control the protection of data at