Vous êtes sur la page 1sur 72

EMSO

Manual
Rafael de Pelegrini Soares
www.rps.eng.br
September 6, 2006
Contents
I Users Guide 1
1 Introduction 2
1.1 What is EMSO and EML? . . . . . . . . . . . . . 3
1.2 Why use EMSO? . . . . . . . . . . . . . . . . . . 3
1.2.1 Easy FlowSheet building . . . . . . . . . . 3
1.2.2 Integrated Graphical Interface . . . . . . . 3
1.2.3 Open-Source Model Library . . . . . . . . 3
1.2.4 Object-Oriented Modeling Language . . . 3
1.2.5 Multi-Platform system . . . . . . . . . . . 4
1.2.6 Fast and Transparent Setup . . . . . . . . 4
1.2.7 Solution Power . . . . . . . . . . . . . . . 4
1.2.8 Modeling of discontinuous process . . . . . 4
1.2.9 Operational procedures scripts . . . . . . . 5
1.2.10 Optimization . . . . . . . . . . . . . . . . 5
1.2.11 Parameter Estimation . . . . . . . . . . . 5
1.2.12 Open Interfaces . . . . . . . . . . . . . . 5
1.2.13 Open Engine API . . . . . . . . . . . . . 5
1.3 Installation . . . . . . . . . . . . . . . . . . . . . 5
1.3.1 Installing EMSO in win32 platforms . . . . 6
1.3.2 Installing EMSO in POSIX platforms . . . 6
2 Overview 7
2.1 EMSO Basics . . . . . . . . . . . . . . . . . . . 8
2.2 Running EMSO . . . . . . . . . . . . . . . . . . 8
2.2.1 Starting EMSO in win32 platforms . . . . 8
ii
2.2.2 Starting EMSO in POSIX platforms . . . . 8
2.3 EMSO graphical interface . . . . . . . . . . . . . 8
2.4 Tutorials . . . . . . . . . . . . . . . . . . . . . . 10
2.4.1 Three Tank FlowSheet . . . . . . . . . 11
3 EMSO Modeling Language 17
3.1 Modeling basics . . . . . . . . . . . . . . . . . . 18
3.1.1 Object Oriented Modeling . . . . . . . . . 18
3.1.2 Writing EMSO Entities . . . . . . . . . . 19
3.1.3 Documenting with Comments . . . . . . . 19
3.1.4 Types . . . . . . . . . . . . . . . . . . . . 20
3.1.5 Using les . . . . . . . . . . . . . . . . . 21
3.2 Model . . . . . . . . . . . . . . . . . . . . . . . 22
3.2.1 Parameters . . . . . . . . . . . . . . . . . 23
3.2.2 Variables . . . . . . . . . . . . . . . . . . 24
3.2.3 Composition in Models . . . . . . . . . . 25
3.2.4 Equations . . . . . . . . . . . . . . . . . 25
3.2.5 Initial Conditions . . . . . . . . . . . . . . 26
3.2.6 Abstract Models . . . . . . . . . . . . . 26
3.3 FlowSheet . . . . . . . . . . . . . . . . . . . . 27
3.3.1 Devices . . . . . . . . . . . . . . . . . 27
3.3.2 Connections . . . . . . . . . . . . . . . . 28
3.3.3 Specications . . . . . . . . . . . . . . . 28
3.3.4 Options . . . . . . . . . . . . . . . . . . . 28
3.4 Optimization . . . . . . . . . . . . . . . . . . . . 29
3.4.1 Simple Optimizations . . . . . . . . . . . 30
3.4.2 Large-Scale Optimization . . . . . . . . . 30
3.4.3 Options . . . . . . . . . . . . . . . . . . . 31
3.4.4 Dynamic Optimization . . . . . . . . . . . 31
3.5 Built-in Functions . . . . . . . . . . . . . . . . . 31
4 Advanced Modeling 32
4.1 Arrays . . . . . . . . . . . . . . . . . . . . . . . 33
4.1.1 Vectors . . . . . . . . . . . . . . . . . . . 33
4.1.2 Multidimensional Arrays . . . . . . . . . . 34
4.1.3 Equation Expansion . . . . . . . . . . . . 34
4.1.4 Array Functions . . . . . . . . . . . . . . 35
4.1.5 Loop For . . . . . . . . . . . . . . . . . . 36
4.2 Conditional Modeling . . . . . . . . . . . . . . . 36
5 Calculation Object Interface 37
5.1 Introduction . . . . . . . . . . . . . . . . . . . . 38
5.1.1 What is CalcObject? . . . . . . . . . . 38
5.1.2 Why use a CalcObject? . . . . . . . . 38
5.1.3 The CalcObject Basics . . . . . . . . . 38
5.2 Using CalcObjects . . . . . . . . . . . . . . . 39
5.2.1 Using CalcObjects in Models . . . . . 39
II Programming Guide 41
6 Developing new CalcObject Services 42
6.1 Interface Specication . . . . . . . . . . . . . . . 43
6.1.1 Create Function . . . . . . . . . . . . . . 43
6.1.2 Destroy Function . . . . . . . . . . . . . . 44
6.1.3 Verication Functions . . . . . . . . . . . 45
6.1.4 Calculation Function . . . . . . . . . . . . 48
6.2 Writing new CalcObject Services . . . . . . . 49
6.2.1 Writing CalcObject Services in Fortran 49
6.2.2 Writing CalcObject Services in C . . . 49
6.2.3 Writing CalcObject Services in C++ . 50
6.3 Documenting CalcObject Services . . . . . . . 50
7 Developing new Solvers 51
7.1 NLA Solvers . . . . . . . . . . . . . . . . . . . . 52
7.1.1 Residuals Function . . . . . . . . . . . . . 52
7.1.2 Jacobian . . . . . . . . . . . . . . . . . . 53
7.1.3 Matrix Multiplication . . . . . . . . . . . 54
7.1.4 Create and Destroy Functions . . . . . . . 55
7.1.5 Solve Function . . . . . . . . . . . . . . . 57
7.2 DAE Solvers . . . . . . . . . . . . . . . . . . . . 58
7.2.1 Create and Destroy Functions . . . . . . . 59
7.2.2 Step Function . . . . . . . . . . . . . . . 60
7.3 Writing new Solver Services . . . . . . . . . . . . 61
7.3.1 Writing External Solver Services in Fortran 61
7.3.2 Writing External Solver Services in C . . . 62
7.3.3 Writing External Solver Services in C++ . 62
7.4 Documenting Solver Services . . . . . . . . . . . 62
License
EMSO alpha version License
(C) 2004-2006 ALSOC.
(Based on code from Rafael de Pelegrini Soares - www.rps.eng.br, (C)
2002-2004)
All rights reserved.
THIS SOFTWARE IS AT ALPHA STAGE AND CAN BE USED FOR EVALUATION
PURPOSES ONLY. NO USE OR DISTRIBUTION OF THIS SOFTWARE IS
GRANTED WITHOUT WRITTEN AUTHORIZATION OF THE COPYRIGHT HOLDER.
Except where otherwise noted, all of the documentation and
software included in this package is copyrighted by Rafael de
Pelegrini Soares. After the installation check the "license"
directory in order to see all third part software used by EMSO
and their respective licenses.
THIS SOFTWARE IS PROVIDED "AS-IS", WITHOUT ANY EXPRESS OR
IMPLIED WARRANTY. IN NO EVENT SHALL THE AUTHOR BE HELD LIABLE
FOR ANY DAMAGES ARISING FROM THE USE OF THIS SOFTWARE.
Rafael de Pelegrini Soares - www.rps.eng.br
Chemical Engineering M.Sc. at GIMSCOP
a
UFRGS.
EMSO is a trademark of UFRGS (Universidade Federal do Rio
Grande do Sul) All other registered or pending trademarks
mentioned in this manual are considered the sole property of
their respective owners. All rights reserved.
a
Group of Integration, Modeling, Simulation, Control, and Optimization of Processes - Chemical Engineering
Department - Federal University of Rio Grande do Sul (UFRGS)
vi
Acknowledgments
Thank to all the people who sent me corrections and improvement
suggestions to both the manual and software. In special I would
like to thank the main EMSO users Argimiro R. Secchi and Paula
B. Staudt for helping me to disclose many missing aspects.
I would like to thank the authors of the following softwares libraries
for permitting the use of their code in EMSO:
DASSLC : a solver for dierential-algebraic equation systems
www.enq.ufrgs.br/enqlib/numeric/;
FOX-Toolkit : a C++ based Toolkit for developing Graphical User Inter-
faces easily and eectively
www.fox-toolkit.org;
FXScintilla : an implementation of Scintilla
1
for the FOX-Toolkit
www.nongnu.org/fxscintilla;
SUNDIALS : suite of codes consisting of the solvers CVODE, KINSOL,
and IDA, and variants of these
www.llnl.gov/CASC/sundials/;
UMFPACK : a set of routines for solving unsymetric sparse linear systems
www.cise.ufl.edu/research/sparse/umfpack;
Ipopt : a software package for large-scale nonlinear optimization.
https://projects.coin-or.org/Ipopt;
In the development process the author proposed several improve-
ments and bug-xes sent to the original authors to be shared with
the community. The source code of all the above cited softwares
can be obtained in the respective URL. Any further explanation
about how such softwares are used in EMSO can be obtained with
the author - www.rps.eng.br.
1
Scintilla is a free source code editing component, see www.scintilla.
org.
vii
Symbols and Conventions
In this document the following notations are used:
Piece of code: piece of code written in the EMSO modeling
language or console outputs:
1 Model tank
2 # body of the model
3 end
Code Identier: emphasize identiers that are commands,
file names and related entities.
Note: a note, for instance: EMSO is an equation based descrip-
tion system, therefore the order of the equations does not matter.
Warning: a warning advertise, for instance: a .mso le free of
syntax errors still can have consistency errors.
Tip: a tip for the user, for instance: always check EML for a
model before develop a new one.
Linux note: note specic for POSIX systems (Linux and Unix),
for instance: EMSO can be available for any POSIX compliant
system upon request.
Windows note: note specic for win32 systems (Windows 95
and above and Windows NT 4 and above), for instance: the
windows le system is not case sensitive.
Under construction: marks a section as not yet implemented
or documented.
viii
I. Users Guide
1
1 Introduction
Go any further in reading this manual or using EMSO without read, understand and accept
the EMSO license, found on page vi.
In this chapter we will learn what is EMSO and why use it.
Contents
1.1 What is EMSO and EML? . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Why use EMSO? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2
1.1 What is EMSO and EML? 3
1.1 What is EMSO and EML?
EMSO stands for Environment for Modeling, Simulation and
Optimization. It is a complete graphical environment where the
user can model complex dynamic or steady-state processes by sim-
ply selecting and connecting model blocks. In addition, the user
can develop new models using the EMSO modeling language or
use those already made from the EMSO Model Library (EML).
EML is an open source library of models written in the EMSO
modeling language. The EMSO modeling language is an object-
oriented language for modeling general dynamic or steady-state
processes.
1.2 Why use EMSO?
In this section we show the key concepts of EMSO and its advan-
tages.
1.2.1 Easy FlowSheet building
EMSO provides the facility of building complex process models,
called FlowSheets, by simply composing it with preexisting
blocks, called Models, and connecting them.
1.2.2 Integrated Graphical Interface
EMSO provides an integrated graphical interface where the user
can manage their .mso les. Multiple les can be opened si-
multaneously and each le can contain an unlimited number of
Models, FlowSheets or Scripts. In the same interface the
user can run simulations and visualize the results besides a lot of
development facilities.
1.2.3 Open-Source Model Library
The EMSO distribution comes with a set of ready to use models
written in the EMSO modeling language the EMSO Model Li-
brary (EML). Therefore, complex FlowSheets can be built by The .mso les coming with EMSO
are distributed under the terms of
the EMSO model license.
simply selecting EML models as Devices and connecting them.
EML is an open-source library and can be extended or modied
by the user.
1.2.4 Object-Oriented Modeling Language
EMSO provides a modeling language that allows the user to write
mathematical models almost as they would appear on paper. In
4 1 Introduction
addition, the language is fully object-oriented, allowing the user to
develop complex models by composing them with existent small
models or develop specic models by deriving standard ones.
All EML models are written in the EMSO modeling language and
are stored in plain text .mso les which can be edited or extended
by the user.
1.2.5 Multi-Platform system
EMSO is available for win32, POSIX (Linux and Unix) platforms.
Models developed in one platform can be freely interchanged be-
tween others.
1.2.6 Fast and Transparent Setup
Process simulators in which models are not black-boxes pieces of
software obligatory have to translate the human readable descrip-
tion to some solvable form. This translation step is called setup
phase.
In EMSO, the setup phase does not relies in the creation of in-
termediary les, compilation, linkage or translation to another
language, the models are directly converted (in memory) to sys-
tems of equations. This mechanism reduces the setup time by
orders of magnitude.
1.2.7 Solution Power
EMSO provides solvers for dynamic and steady-state systems
which are ecient in solving both small and large scale systems.
The solvers can make use of the dense or sparse linear algebra.
Actually there is no limit regarding problem size other than the
machine memory. In addition, new solvers can be interfaced to
EMSO and used in a seamless manner.
State of art techniques as automatic and symbolic dierentiation
algorithms are built-in in EMSO. Furthermore, it has proved to
be one of the most time ecient tools when solving large scale
dynamic problems.
1.2.8 Modeling of discontinuous process
There are several processes which are in nature discontiuous, with
EMSO it is easy to model continuous-discrete (hybrid) systems
using conditional equations.
1.3 Installation 5
1.2.9 Operational procedures scripts
Under construction: To be implemented and documented.
1.2.10 Optimization
Besides dynamic and steady simulation EMSO can be used to nd
optimal solutions with respect to given criteria. The user just need
to formulate the optimization objective (lower cost, maximum
production, etc) and choose the optimization variables (manipu-
lated variables) and let the system to nd the best solution.
1.2.11 Parameter Estimation
Under construction: To be implemented and documented.
1.2.12 Open Interfaces
EMSO has a set of open interfaces that allow the user to load
at run-time third-party software encapsulated in dynamic link li-
braries. (See Part II).
In addition, there are standard interfaces for implementing new
dierential-algebraic equations (DAE) and nonlinear algebraic equa-
tions (NLA) solvers.
Furthermore, EMSO supports the numerical set of CAPE-OPEN
interfaces, enabling to share system of equations coming from The CAPE-OPEN project aims at
the standardization of interfaces for
Computer Aided Process
Engineering tools, see
www.co-lan.org.
EMSO models and solvers. The thermodynamic and units oper-
ation sets of interfaces are about to be implemented.
1.2.13 Open Engine API
EMSO is composed by two major softwares: the graphical in-
terface and the engine. The EMSO power in solving complex
high-scale dynamic problems is available to be embedded in third
party software through the EMSO engine open Application Pro-
gram Interface (API).
1.3 Installation
EMSO is available for two main platform groups: win32 and
POSIX. Installation instructions for these platforms can be found
in subsection 1.3.1 and subsection 1.3.2 respectively.
6 1 Introduction
1.3.1 Installing EMSO in win32 platforms
EMSO is compatible with a variety of win32 operational systems
(Windows 95 and above, Windows NT 4 and above). In order to
install EMSO in such systems one can just run the installation
package emso-win32.exe available at www.rps.eng.br
and follow the on screen instructions.
1.3.2 Installing EMSO in POSIX platforms
EMSO is compatible with a variety of POSIX platforms (Linux, POSIX is the name for a series of
standards being developed by the
IEEE that specify a Portable
Operating System interface. The
IX denotes the Unix heritage of
these standards.
Unix).
In order to install EMSO in such systems you have to download
the archive emso-<PLATFORM>-<ARCH>.tar.gz available
at www.rps.eng.br.
For instance, emso-linux2-i386.tar.gz is the installation
archive for Linux version 2 or above platforms running in an i386
machine or above.
Note: Installation packages for any POSIX compliant platform
can be produced upon request.
Once an archive compatible with your system was downloaded,
EMSO can be installed with the following commands:
$ tar -xzvf emso-<PLATFORM>.tar.gz
# sudo mv emso /usr/local
# sudo ln -sf /usr/local/emso/bin/emso /usr/bin/emso
Warning: It is strongly recommend that you move the emso
folder to /usr/local/ on your system.
2 Overview
This chapter provides an overview about EMSO. First some basics are presented followed by
some tutorials. These tutorials teaches how to:
built a FlowSheet composed by a set of predene Models;
check the syntax of a .mso le
check the consistency of a FlowSheet
run a dynamic simulations and plot results;
customize FlowSheet options.
Further, the EMSO modeling language for develop mathematical models is introduced.
Contents
2.1 EMSO Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2 Running EMSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.3 EMSO graphical interface . . . . . . . . . . . . . . . . . . . . . . . 8
2.4 Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
7
8 2 Overview
2.1 EMSO Basics
EMSO is a software tool for modeling, simulation and optimiza-
tion of dynamic or steady-state general processes. The referred
processes are called FlowSheets.
A FlowSheet is composed by a set of components, named
Devices. Each Device has a mathematical description, called
Model. These are the three main EMSO entities and all of them
are described in plain text les which are usually stored in .mso
les. Each .mso le can have any number of any of these enti-
ties and the EMSO graphical user interface can open an unlimited
number of .mso les simultaneously.
2.2 Running EMSO
EMSO is available in a variety of platforms:
win32 platforms; Windows 95 or above and
Windows NT 4 or above.
POSIX platforms: Linux and Unix. Distribution for any POSIX
compliant platform can be built
upon request.
2.2.1 Starting EMSO in win32 platforms
If EMSO was successfully installed as described in subsection 1.3.1,
it can be started by left clicking in one of the installed shortcuts:
at the desktop or at the start menu.
2.2.2 Starting EMSO in POSIX platforms
If EMSO was successfully installed as described in subsection 1.3.2,
it can be started by the command emso.
2.3 EMSO graphical interface
After EMSO is started a graphical user interface as showed in
Figure 2.1 raises.
Note: The EMSO graphic interface layout and behavior is iden-
tical in all platforms.
In this section a brief overview about this interface is given.
This interface is inspired on the most successfully interfaces for
software development. It is divided in some panels which are
treated in the following sections.
2.3 EMSO graphical interface 9
Figure 2.1: EMSO graphical user interface.
Explorer and Results Windows
The Explorer and Results windows are in the left most
vertical frame of the interface in Figure 2.1.
Explorer : displays the available libraries of models and the current
loaded les and its contents (Models and FlowSheets).
The Figure 2.2 (a) shows a typical view of the le explorer.
Results : for each task ride (e.g. a dynamic simulation) a new item is
added to this window. A typical view of the results explorer
can be seen in Figure 2.2 (b).
Tip: The position of the frames in Figure 2.1 can be freely inter-
changed, right click on the tab button of the window to change
its position.
Each of these windows can be turned the current one by clicking
in the respective tab. At any time the user can close one or more
tabs. Closed tabs can be shown again with the View menu.
Problems Window
As in any programming or description language les can have
problems. Each time that a le is opened the Problems window
automaticaly list all errors and warnings found, as exemplied by
the Figure 2.3.
10 2 Overview
(a) Explorer (b) Results explorer
Figure 2.2: EMSO Explorer and Results windows.
Figure 2.3: EMSO Problems Window.
Console Window
When running tasks all messages are sent to the Console. As
can be seen in Figure 2.4, the user can select the detailing level
of the messages sent to the console.
The Multiple Document Interface panel
In the center of the interface is implemented a Multiple Document
Interface (MDI) panel. This panel is responsible to show the
opened les and edit it, the result plots, etc.
2.4 Tutorials
In the last section we have presented how to start EMSO and
its graphical interface. Now we give some tutorials introducing
the key concepts of EMSO and its modeling language. All code
2.4 Tutorials 11
Figure 2.4: EMSO Console Window.
samples found in this section can be found at mso/tutorial/
directory.
2.4.1 Three Tank FlowSheet
In this section we describe how to create and simulate the dy-
namic model of a process composed by some tanks. The example
consists of three tanks connected in series. In EMSO this process
can be modeled as a FlowSheet containing three Devices
each one based on a tank Model.
Creating a new le
In order to simulate this example, the rst step is to create a new
.mso le containing a FlowSheet. This is achieved by left
clicking in the new le button . This will bring up the new le
dialog as shown in Figure 2.5. In this window the user can select
one of the available templates:
FlowSheet;
Equation FlowSheet;
Model;
Empty.
In this example we are interested in create a new FlowSheet.
This is the default template item, therefore the user should left it
as is. The elds Name and Location should be lled with the
desired le name and directory location, respectively. The user
can ll this dialog as exemplied in Figure 2.5 then left click in
the Accept button in order to create the new le. After this
EMSO will create and open a le with the given properties. At
this point the interface will look like Figure 2.6.
12 2 Overview
Figure 2.5: New le dialog wizard.
Figure 2.6: EMSO new le window.
Writing the FlowSheet
Before continue reading this tutorial is advisable to read the com-
ments on the le new le created (which comes from the selected
template).
The rst comments are about the using command. This com-
mand makes available all entities contained in a given lename or
directory (all les belonging to it).
In our example we will make use of one of the EML models, the
TankSimplified model. This model is found in le tanks.mso
in the library directory. Therefore, in order to use this model in-
stead of copy and paste we will use this le with the using
command as follows:
using "stage_separators/tanks";
2.4 Tutorials 13
This command turns available all entities contained in le tank.mso
which is part of EML. For more details about using see subsec- The le tank.mso (as most of the
EML les) uses the le
types.mso which contains the
declaration of several variable types
as length, area, etc.
tion 3.1.5.
The next step is to change the default name NewFlowSheet
to a more meaningful name, lets say ThreeTank. Then we can
add the Devices in the DEVICES section and connect them in
the CONNECTIONS section. After this, the contents of the le
should look like Code 2.1.
Code 2.1: File ThreeTank1.mso.
17 using "stage_separators/tank";
19 FlowSheet ThreeTank
20 VARIABLES
21 Feed as flow_vol;
23 DEVICES
24 Tank1 as tank_simplified;
25 Tank2 as tank_simplified;
26 Tank3 as tank_simplified;
28 CONNECTIONS
29 Feed to Tank1.Fin;
30 Tank1.Fout to Tank2.Fin;
31 Tank2.Fout to Tank3.Fin;
32 end
The Code 2.1 contains no problems, once there is no item on the
Problems window.
Warning: Even if a .mso le has no problems the FlowSheets
of such le can be not consistent, as explained in the following
section.
Checking consistency
A FlowSheet is consistent if it has zero degrees of freedom and
zero dynamic degrees of freedom.
In order to check the ThreeTank consistency the user should
select the corresponding FlowSheet item in the le explorer
and then left click in the button. At this time the Console
window will become active and will display a message like:
Checking the consistency for ThreeTank in file /home/rafael/
ThreeTank1.mso...
Number of variables: 7
Number of equations: 6
Degrees of freedom: 1
The number of variables and equations does not match!
System is not consistent!
At this point the Problems window will also show the consis-
tency problems. This error was expected, once we have neither
14 2 Overview
specied the input ow of the rst tank nor the initial level of the
tanks.
Therefore, in order to get a consistent system the user should add
the following commands:
SPECIFY
Feed = 10
*
"m3/h";
INITIAL
Tank1.h = 1
*
"m";
Tank2.h = 2
*
"m";
Tank3.h = 1
*
"m";
The user can choose between to add this code into its FlowSheet
or use the already made le ThreeTank2.mso found in the
tutorial directory.
Note: EMSO is not a sequential tool, therefore the user could
specify a variable other than the input ow of the rst tank.
Now, if the user checks the ThreeTank consistency no errors
will be reported and some interesting messages will be sent to the
Console:
Checking the consistency for ThreeTank in file ThreeTank2.mso
...
Number of variables: 10
Number of equations: 10
Degrees of freedom: 0
Structural differential index: 1
Dynamic degrees of freedom: 3
Number of initial Conditions: 3
System is consistent.
Running a Simulation
Once we have a consistent FlowSheet we can run a simulation.
To do this the user has to select the desired FlowSheet in the
le explorer and then left click in the button.
Simulation of ThreeTank started ...
Simulation of ThreeTank finished succesifuly in 0.02 seconds.
Tip: In order to get more detailed output when running a simu-
lation just change the output level on the Console window and
run again the simulation.
Visualizing Simulation Results
For each task ride by the user a new result is added to the results
explorer. The user can see the available results by left clicking in
the results explorer tab (Figure 2.2 (b)).
2.4 Tutorials 15
If a result is selected on the top list of the results, the bottom
side will show the variables available for plotting. The user can
plot a variable prole by double clicking in it.
We have not congured the simulation time vector for our simu-
lation and the default integration interval is not suitable for the If not specied the integration
interval is the interval ranging from
0 to 100 seconds.
dynamics of our system. We can modify the integration interval
by adding, for instance, the following command:
OPTIONS
time = [0:0.1:2]
*
"h";
Now we have an integration interval compatible with the dynamics
of our system. Then if we run the simulation again, the results
will be much more interesting.
Customizing the FlowSheet
Usually Models are full of parameters to be customized by the
user. In our FlowSheet (Code 2.1) we have not changed pa-
rameter values. Hence the default values for all parameters were
considered, these defaults come from the types on which the pa-
rameters are based.
In order to set values other than the defaults the user can add a
SET section at any point after the parameter declaration. Then
if we want another values for the valve constants or geometry of
our tanks the following code should be added after the DEVICES
section:
SET
Tank2.k = 8
*
"m2.5/h";
Tank2.A = 4
*
"m2";
Now we can run the simulation again and compare the results
with the previous solution.
At this point our code should look like Code 2.2 found in the
tutorial directory.
Code 2.2: File ThreeTank3.mso.
17 using "stage_separators/tank";
19 FlowSheet ThreeTank
20 VARIABLES
21 Feed as flow_vol;
23 DEVICES
24 Tank1 as tank_simplified;
25 Tank2 as tank_simplified;
26 Tank3 as tank_simplified;
28 CONNECTIONS
29 Feed to Tank1.Fin;
16 2 Overview
30 Tank1.Fout to Tank2.Fin;
31 Tank2.Fout to Tank3.Fin;
33 SPECIFY
34 Feed = 10
*
"m3/h";
36 INITIAL
37 Tank1.h = 1
*
"m";
38 Tank2.h = 2
*
"m";
39 Tank3.h = 1
*
"m";
41 SET
42 Tank2.k = 8
*
"m2.5/h";
43 Tank2.A = 4
*
"m2";
45 OPTIONS
46 time = [0:0.1:2]
*
"h";
47 end
3 EMSO Modeling Language
In this chapter, we describe in detail how one can write a Model or FlowSheet using the
EMSO modeling language.
The EMSO modeling language is a case sensitive textual language. In such language the
entities are written in plain text les stored, by default, in .mso les.
Contents
3.1 Modeling basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.2 Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.3 FlowSheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.4 Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.5 Built-in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
17
18 3 EMSO Modeling Language
3.1 Modeling basics
As mentioned before, in EMSO a FlowSheet is the problem
in study. But, a FlowSheet is composed by a set of con-
nected Devices, each one having a mathematical description
called Model.
In chapter 2 the Model and FlowSheet entities were intro-
duced. The description of these entities share several basic con-
cepts particular to the EMSO modeling language, which follows.
3.1.1 Object Oriented Modeling
Reuse is the key to handle complexities, this is the main idea be-
hind the object oriented (OO) paradigm. The EMSO language
can be used to create high reusable models by means of compo-
sition and inheritance OO concepts, described below.
Composition
Every process can be considered as set of sub-processes and so
on, this depends only on the modeling level. Composition is the
ability to create a new model which is composed by a set of
components, its sub-models.
The EMSO modeling language provides unlimited modeling levels,
once one model can have sub-models which can have sub-models
themselves. This section aims at introducing the composition
concept, the application of this concept in the EMSO is shown in
subsection 3.2.3.
Inheritance
When modeling complex systems, set of models with a lot in
common usually arises. If this is the case, an advisable modeling
method is to create a basic model which holds all the common
information and derive it to generate more specif models reusing
already developed models.
In OO modeling this is achieved by inheritance, the ability to cre-
ate a new model based on a preexistent one and add derivations
to it. For this reason, inheriting is also known as deriving. When
a model uses more than one base model it is said to use multiple
inheritance.
The EMSO modeling language provides unlimited levels of in-
heritance or multiple inheritance for Models and FlowSheets.
The following sections and EML are a good sources of examples See the EML le stream.mso, for
instance.
of inheritances.
3.1 Modeling basics 19
3.1.2 Writing EMSO Entities
The basic EMSO entities are Models and FlowSheets. The
formal description of these entities always start with the entity
keyword (Model or FlowSheet) and ends with the end key-
word, as follows.
FlowSheet FlowSheetName
# FlowSheet body
end
Model ModelName
# Model body
end
A .mso le can have an unlimited number of entities declared
on it. Once a entity was declared it is available to be used as
a base for derivation or as a component to another one. The
detailed description of FlowSheets and Model are found in
sections 3.2 and 3.3, respectively.
3.1.3 Documenting with Comments
The EMSO modeling language is a descriptive language, a Model
written on it contains several information about the process being
modeled, as variable and parameter description, equation names,
etc. But extra explanations could be useful for better under-
standing the model or for documenting the history of a model,
the authors, the bibliography, etc. This kind of information can be
inserted in EMSO entities with one of the two types of comments
available:
line comment: starting from # and extending until the end
of line;
block comment: starting from #
*
and extending until
*
#.
It follows below a piece of code which exemplies both kind of
comments:
#
*
This is a block comment, it can be extended in multiple lines.
A block comment can give to the reader useful informations,
for instance the author name or a revision history:
Author: Rafael de Pelegrini Soares
-------------------------------------------------------------
Revision history
$Log: streams.mso,v $
Revision 1.1.1.1 2003/06/26 16:40:37 rafael
-------------------------------------------------------------
*
#
# A line comment extends until the end of line.
20 3 EMSO Modeling Language
3.1.4 Types
As already mentioned in chapter 2, the declaration of variables
and parameters can make use of a base type. A type and can
be a previously declared Model, one of the built-in types or new
types deriving from the built-in ones. The list of built-in types
are shown in Table 3.1.
Table 3.1: List of EMSO built-in types.
Type name Description
Real Type for continuous variables or parameters, with attributes:
Brief: textual brief description
Default: default value for parameters and initial guess for variables
Lower: lower limit
Upper: upper limit
Unit: textual unit of measurement
Integer Type for integer variables or parameters, with attributes:
Brief: textual brief description
Default: default value for parameters and initial guess for variables
Lower: lower limit
Upper: upper limit
Text Type for textual parameters, with attributes:
Brief textual brief description
Default default value for parameters
Boolean Type for logical parameters or variables, with attributes:
Brief textual brief description
Default default value for parameters and initial guess for variables
CalcObject Object for loading third party pieces of software providing special calculation
services, see chapter 5.
As Table 3.1 shows, each built-in type has a set of attributes.
These attributes can be modied when a new type is created
deriving a preexistent one. For instance, consider the Code 3.1
making part of EML, in this le a set of convenient types are
declared, and are used in all EML models.
Code 3.1: EML le types.mso.
3.1 Modeling basics 21
20 coefficient as Real (Brief = "General Coefficient", Default=1,
Lower=-50, Upper=50);
21 constant as Real (Brief = "General Constant", Default=10, Lower
=-5000, Upper=5000);
22 positive as Real (Brief = "Positive General Constant", Default
=1.0, Lower=-1e-6);
23 negative as Real (Brief = "Negative General Constant", Default
=-1.0, Upper=0.0);
24 fraction as positive (Brief = "Fraction" , Default=0.5, Upper=1);
25 percent as Real (Brief = "Percent", Default=50, Lower=0, Upper
=100);
26 control_signal as Real (Brief = "Control Signal", Default=1,
Lower=-1e9, Upper=1e9);
28 # Pressure
29 pressure as Real (Brief = "Pressure", Default=1, Lower=1e-30,
Upper=5e7, Unit = "atm");
30 press_delta as pressure (Brief = "Pressure Difference", Default
=0.01, Lower=-5e6);
Note that type declarations can be stated only outside of any
Model or FlowSheet context.
Variables can be declared based on types deriving from Real,
Integer or Boolean. Variables cannot be of type Text or
CalcObject but parameters can be of any type. Note that the
CalcObject type cannot be derived, more details about this
type can be found in chapter 5.
3.1.5 Using les
Code reuse is one of the key concepts behind EMSO. To achieve
this the user can be able to use code written in another les
without have to touch such les. A .mso le can make use of
all entities declared in another les with the using command.
This command has the following form:
using ("file name")+ ;
where ("file name")+ means a comma separated list of tex-
tual le names. Therefore, commands matching this pattern
could be:
1 using "types";
2 using "streams", "tanks";
When EMSO found a using command it searches the given le
name in the following order:
1. the current directory (directory of the le where the using
was found);
2. the directory list in the search path (see ??);
3. the EML directory.
22 3 EMSO Modeling Language
Note: As shown in the sample code, if the user suppress the le
extension when using les EMSO will automatically add the
mso extension.
Whenever possible the user should prefer the using command
instead of copy and paste code.
Windows note: The EMSO language is case sensitive but the
windows le system is not. Therefore, when using les in win-
dows, the language became case insensitive for the le names.
3.2 Model
The basic form of a Model was introduced in subsection 3.1.2,
here we describe how the Model body is written.
In Code 3.2 the syntax for writing Models in the EMSO modeling
language is presented.
Code 3.2: Syntax for writing Models.
1 Model name [as (base)+]
2 PARAMETERS
3 [ext] name [as base[( (attribute = value)+ )] ];
5 VARIABLES
6 [in | out] name [as base[( (attribute = value)+ )] ];
8 EQUATIONS
9 ["equation name"] expression = expression;
11 INITIAL
12 ["equation name"] expression = expression;
14 SET
15 name = expression;
16 end
where the following conventions are considered:
every command between [ ] is optional, if the command
is used the [ ] must be extracted;
the operator ( )+ means that the code inside of ( )
should be repeated one or more times separated by comma,
but without the ( );
the code a|b means a or b;
name is a valid identier chosen by the user;
base is a valid EMSO type or already declared Model;
3.2 Model 23
expression is an mathematical expression involving any
constant, variable or parameter already declared.
Therefore, using this convention, the the line 1 of Code 3.2 could
be any of the following lines:
Model MyModel
Model MyModel as BaseModel
Model MyModel as Base1, Base2, Base3
As another example, consider the line 5 of Code 3.2, commands
matching that pattern are:
MyVariable;
in MyVariable;
out MyVariable;
MyVariable as Real;
MyVariable as Real(Default=0, Upper = 100);
MyVariable as MyModel;
3.2.1 Parameters
Models of physical systems usually relies in a set of characteristic
constants, called parameters. A parameter will never be the result
of a simulation, its value needs to be known before the simulation When running an optimization or
parameter estimation the value of a
parameter could be the result of
the calculation.
starts.
In Code 3.2, each identier in capitals starts a new section. In
line 2 the identier PARAMETERS starts the section where the
parameters are declared. A parameter declaration follows the pat-
tern shown in line 3, this pattern is very near to that used in type
declarations (see subsection 3.1.4).
In a Model any number of parameters, unique identied with
dierent names, can be declared. Examples of parameter decla-
rations follows:
PARAMETERS
NumberOfComponents as Integer(Lower=0);
ext GlobalPar as Real;
External Parameters
As can be seen in line 3 of Code 3.2 a parameter declaration can
use the ext prex. When a parameter is declared with this prex,
the parameter is only a reference to a parameter with same name
but declared in the FlowSheet. Because of this, parameters
declared with the ext prex are known as external parameters,
while parameters without the prex are known as concrete pa-
rameters.
24 3 EMSO Modeling Language
The purpose of external parameters is to share the value of a
parameter between several Devices of a FlowSheet. Note
that the value of an external parameter comes from a parameter
with same name but declared on the FlowSheet, hence its value
can be specied only in the FlowSheet.
3.2.2 Variables
Every mathematical model has a set of variables once the variable
values describe the behavior of the system being modeled. These
values are the result of a simulation in opposition to parameters,
which need to be known prior to the simulation.
In the EMSO modeling language, variables are declared in a man-
ner very close to parameters. The VARIABLES identier starts
the section where the variables are declared, following the form
presented in line 5 of Code 3.2. Examples of variable declarations
follows:
VARIABLES
T as Real(Brief="Temperature", Lower=200, Upper = 6000);
in Fin as FlowRate;
out Fout as FlowRate;
A Model can contain an unlimited number of variables, but a
Model with no variables has no sense and is considered invalid.
The user already should note that the declaration of types, vari-
ables and parameters are very similar, using a name and optionally
deriving from a base. In the case of variables and parameters the
base can be one of the built-in types (see Table 3.1), types deriv-
ing from the built-in ones or predeclared Models.
Inputs and Outputs
When declaring variables, the prexes in and out can be used,
see line 6 of Code 3.2.
Variables declared with the out prex are called output variables,
while that declared with the in prex are called input variables.
The purpose of these kind of variables is to provide connection
ports, enabling the user to connect output variables to input vari-
ables.
An output variable works exactly as an usual variable, but is avail-
able to be the source of a connection. However, an input variable
is not a concrete variable, once it is only a reference to the values
coming from the output variable connected to it. This connecting
method is used, instead of adding new hidden equations for each
3.2 Model 25
connection, with the intent of reduce the size of the resulting sys-
tem of equations. A description on how to connect variables can
be found in subsection 3.3.2.
3.2.3 Composition in Models
In subsection 3.1.1 the composition concept was introduced. In
the EMSO modeling language, to built composed Models is
nothing more than declare parameters or variables but using Models
as base instead of types.
If a Model is used as base for a variable such variable actually is
a sub-model and the Model where this variable was declared is
called a composed Model.
A variable deriving from a Model contains all the variables, pa-
rameters even equations of the base. In order to access the the
internal entities of a sub-model, for instance in equations or for
setting parameters, a path should be used, as exemplied in line 4
of the code below:
1 VARIABLES
2 controller as PID;
3 SET
4 controller.K = 10;
In the case of parameters deriving from a Model, the inheriting
process has some peculiarities:
Parameters of the base are sub-parameters;
Variables of the base are considered as sub-parameters;
Equations, initial conditions and all the rest of the base are
unconsidered;
3.2.4 Equations
Equations are needed to describe the behavior of the variables of
a Model. A Model can have any number of equations, including
no equations. In EMSO an equation is an equality relation be-
tween two expressions, it is not an attributive relation. Therefore,
the order in which the equations are declared does not matter.
Warning: A Model with more equations than variables is use-
less, once there is no way to remove equations from a model.
An equation is declared using the form presented in line 7 of
Code 3.2, where expression is a expression involving any of
26 3 EMSO Modeling Language
preciously declared variables, parameters, operators, built-in func-
tions and constants. A constant can be a number or the text of
a unit of measurement. Details about the available operators,
functions and their meaning can be found in section 3.5.
Examples of equation follows:
EQUATIONS
"Total mass balance" diff(Mt) = Feed.F - (L.F + V.F);
"Vapor pressure" ln(P/"atm") = A
*
ln(T/"K") + B/T + C + D
*
T2;
Units of measurement
Note that "atm" and "K", in the code above, are not com-
ments, such texts are recognized as units of measurement (UOM)
constants and eectively are part of the expression. In such exam-
ple the UOMs are required to assure units dimension correctness,
because the ln function expects a UOM dimensionless argument.
3.2.5 Initial Conditions
EMSO can execute dynamic and steady state simulations, see
subsection 3.3.4. Most dynamic systems requires a set of initial
conditions in order to obtain its solution. These initial conditions
are stated exactly as equations (subsection 3.2.4 but within the
INITIAL section identier, for instance:
INITIAL
"Initial total mass" Mt = 2000
*
"kg";
Note that the equations given in the INITIAL section are used
only in the initialization procedure of dynamic simulations.
3.2.6 Abstract Models
If a Model has less equations than variables it is known as a rect-
angular or abstract Model, because specications, connections
or extra equations are required in order to obtain its solution. If
a Model has no equation it is known as a pure abstract Model,
once it holds no information about the behavior of its variables.
Most models of a library are abstract or pure abstract where the
pure abstract models are derived to generate a family of abstract
models and so on. Note that is very uncommon to have a pure
abstract model used directly in a FlowSheets as well as to use
a model which is not abstract.
3.3 FlowSheet 27
3.3 FlowSheet
In section 3.2 the Model body was described. When writing
FlowSheets the user can freely make use of all description
commands of a Model body, exactly as stated in section 3.2.
Additionally, in the case of FlowSheets, the sections presented
in in Code 3.3 could be used.
Code 3.3: Syntax for writing FlowSheets.
1 FlowSheet name [as (base)+]
2 DEVICES
3 name [as base[( (attribute = value)+ )] ];
5 CONNECTIONS
6 name to name;
8 SPECIFY
9 name = expression;
11 OPTIONS
12 name = value;
13 end
Code 3.3 uses the same code conventions explained in section 3.2.
It follows below the details of the sections of this code.
3.3.1 Devices
In line 2 of the Code 3.3 the DEVICES section can be seen. In
this section the user can declare any number of Devices of a
FlowSheet, in OO modeling these Devices are known as the
components, see subsection 3.1.1.
The DEVICES section in a FlowSheet is a substitute of the
VARIABLES section of a Model but no prex is allowed.
Note: There is no sense in using the in or out prex in
FlowSheets, because these supposed inputs or outputs could
not be connected once the FlowSheet is the top level model.
Exactly as variables of a Model, the base (line 3 of Code 3.3)
can be any a type, or Model.
Examples of Device declarations follows:
DEVICES
feed as MaterialStream;
pump1 as Pump;
pump2 as Pump;
28 3 EMSO Modeling Language
3.3.2 Connections
In subsection 3.2.2 was described how to declare an input or out-
put variable. However, was not specied how to connect an out-
put variable to an input one. This can be done with the form
presented in line 6 of Code 3.3, where a output variable is con-
nected to an input.
It is stressed that the values of an input variable are only refer-
ences to the values of the output connected to it avoiding extra
equations representing the connections and reducing the size of
the resulting system of equations.
Note that the CONNECTIONS section can be used in Models
in the same way that in FlowSheets. It was omitted when the
Model body was described on purpose because is more intuitive
to connect variables in a FlowSheet. There is no restrictions in
using connections in a Model, but, when possible, composition
and inheritance should be used instead.
3.3.3 Specications
In subsection 3.2.6 the term abstract model was dened, basically
it means models with missing equations. Most useful models
are abstract, because of their exibility. This exibility comes
from the possibility of specify or connect the models in several
dierent fashions.
In order to simulate a FlowSheet it must have the number of
variables equal number of equations. FlowSheets using ab-
stract Models requires specications for variables in the form
presented in line 9 of Code 3.3. In a specication expression
can be any expression valid for an equation (see subsection 3.2.4)
and name is the name or path name of the specied variable.
3.3.4 Options
In order to adjust the simulation parameters of a FlowSheet
the user can make use of the OPTIONS section. The following
piece of code shows how to set simulation options of a FlowSheet:
OPTIONS
time = [1:0.1:10]
*
"h";
DAESolver = "dasslc";
In Table 3.2 all available options are listed.
3.4 Optimization 29
Table 3.2: FlowSheet options, default value in bold.
Option name Type Description
time real vector The reporting integration time: [0:10:100];
mode text The simulation mode: "dynamic" or "steady";
integration text The system to be used in integration: "original",
"index1" or "index0";
relativeAccuracy real The relative accuracy: 1e-3;
absoluteAccuracy real The absolute accuracy: 1e-6;
indVarAccuracy real The independent variable accuracy when detecting state
events: 1e-2;
LASolver text The linear algebra data type and solver to be used:
"sparse" or "dense";
NLASolver text The NLA solver library le name to be used:
"nlasolver", "sundials", or the name the le
of some solver developed by the user as described in
chapter 7;
DAESolver text The DAE solver library le name to be used:
"sundials", "dassl", "mebdf", or the name the
le of some solver developed by the user as described in
chapter 7;
3.4 Optimization
Optimization dier from simulation in several aspects. In simu-
lation problems the solvers will try to nd the solution. In opti-
mization problems the solvers try to nd the best solution with
respect to some objectives and constraints. The objectives can
be to minimize or maximize one or more expressions.
EMSO can be used to execute optimizations ranging from simple
to large-scale. When writing optimization problems the user can
freely make use of all description commands of a FlowSheet
body, exactly as stated in section 3.3. Additionally, in the case
of optimization problems, the sections presented in in Code 3.4
could be used.
Code 3.4: Syntax for writing FlowSheets.
1 Optimization name [as base]
2 MINIMIZE
3 expression1;
4 expression2;
6 MAXIMIZE
7 expression3;
8 expression4;
10 EQUATIONS
30 3 EMSO Modeling Language
11 expression5 < expression6;
12 expression7 > expression8;
14 FREE
15 variable1;
16 variable2;
17 end
Code 3.4 uses the same code conventions explained in section 3.2.
It follows below the details of the sections of this code.
3.4.1 Simple Optimizations
An example of simple optimization problem follows:
Optimization hs71
VARIABLES
x(4) as Real(Default=1, Lower=1, Upper=5);
MINIMIZE
x(1)
*
x(4)
*
(x(1)+x(2)+x(3))+x(3);
EQUATIONS
x(1)
*
x(2)
*
x(3)
*
x(4) > 25;
x(1)
*
x(1) + x(2)
*
x(2) + x(3)
*
x(3) + x(4)
*
x(4) = 40;
OPTIONS
mode = "steady";
end
As can be seen in the code above, optimization problems support
inequality constraints which are not supported in Models or
FlowSheets.
In the example above, the optimization is self-contained. The
variables, optimization objectives and constraints are all declared
in the optimization problem body.
Tip: Optimization problems are solved exactly as FlowSheets,
with the run button.
3.4.2 Large-Scale Optimization
In subsection 3.4.1 we described how to write a simple optimiza-
tion problem. The same approach can be used to describe large-
scale problems but this form is barely convenient.
As a convenience for the user, EMSO supports the directly op-
timization of already running FlowSheets. As an example,
consider that the user has an already developed and running
FlowSheet for a process of ammonia synthesis called Ammonia.
Now lets consider that the user whant to nd the recycle fraction
which yields to the minimun lost of product on the purge. For
this case the following code could be used:
3.5 Built-in Functions 31
Optimization AmmoniaOptimization as Ammonia
MINIMIZE
productLoose;
FREE
Splitter102.fraction;
OPTIONS
mode = "steady";
end
Warning: In order to optimize FlowSheets make sure that
the FlowSheet is running (it is consistent and the simulation
succeds).
3.4.3 Options
In subsection 3.3.4 all options supported by FlowSheets were
presented. Optimization problems support additional options as
listed in Table 3.3.
Table 3.3: Optimization options, default value in bold.
Option name Type Description
NLPSolveNLA integer Flag if the simulation solution should be used as start
value for the optimization problem: 1 or 0;
NLPSolver text The le name of the NLP solver library:
"ipopt emso", or the name the le of some
solver developed by the user as described in chapter 7;
3.4.4 Dynamic Optimization
Under construction: As of this time, EMSO only supports static
optimization, dynamic optimization will be available soon.
3.5 Built-in Functions
Under construction: needs to be documented
4 Advanced Modeling
In chapter 3 the basic concepts of the EMSO modeling language were described. In this
chapter we describe more advanced concepts.
Contents
4.1 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.2 Conditional Modeling . . . . . . . . . . . . . . . . . . . . . . . . . 36
32
4.1 Arrays 33
4.1 Arrays
In EMSO we can make use of multidimensional arrays, i.e., arrays
with any number dimensions.
4.1.1 Vectors
The simplest form of an array is the one dimension array a
vector. In EMSO a vector of variables is declared as follows:
PARAMETERS
N as Integer(Default=10);
VARIABLES
vector1(100) as Real(Brief="A vector with 100 elements");
vector2(N) as Real(Brief="Undefined length vector");
In the code above two vectors were declared, vector1 has a
xed length while vector2 has its length equal to N which can
be set after.
Note: In order to build more general models the user should
declare the dimensions of the arrays as parameters. Remember
that the dimension of an array must be an Integer.
Besides the default types, in EMSO the user can compose new
models using vectors of another models as follows:
using "stream";
Model Mixer
PARAMETERS
Ninputs as Integer(Brief="Number of inputs", Default=2);
VARIABLES
Inlet(Ninputs) as stream;
Outlet as stream;
In the piece of code above the Inlet is a vector of length
Ninputs in which each element is a stream. The parame-
ter Niputs can be set after in any point of a the Model or in
the FlowSheet, for example:
FlowSheet MixProcess
DEVICES
mix as Mixer;
s1 as stream;
s2 as stream;
s3 as stream;
CONNECTIONS
s1 to mix.Inlet(1);
s2 to mix.Inlet(2);
s3 to mix.Inlet(3);
SET
mix.Ninputs = 3;
end
34 4 Advanced Modeling
Warning: Dierently from some popular programming languages
as C or C++ the elements of a vector or array starts from one
and not zero.
4.1.2 Multidimensional Arrays
Arrays with more than one dimension are declared in an analogous
way to vectors : A vector is an array with only one
dimension, see subsection 4.1.1
VARIABLES
var2d(x,y) as Real(Brief="Array with 2 dimensions");
var3d(x,y,z) as Real(Brief="Array with 3 dimensions");
4.1.3 Equation Expansion
In usual programming languages, when dealing with vectors or
arrays the user has to work with loops, like for or while. EMSO
also implements a loop for but it has a convenient mechanism The loop for is treated in
subsection 4.1.5
which automatically expand the equations avoiding the use of
loops in most situations.
Arrays with Identical Shapes
For instance, if we wants an equation telling that the composition
of an outlet stream is equal to the composition of an inlet stream:
EQUATIONS
Outlet.z = Inlet.z;
Then EMSO automatically expands the above equation by:
Outlet.z
i
= Inlet.z
i
, i = 1 : Ncomps
Arrays and Scalars
If an expression involve one array and one scalar, then the scalar
is expanded to match the array dimensions. For example:
VARIABLES
ones(M,N) as Real;
EQUATIONS
ones = 1;
Note: The above equation ones=1; actually accounts as M
times N equations.
4.1 Arrays 35
4.1.4 Array Functions
EMSO implements some functions specially designed for handling
arrays.
Sum
The sum function sums the elements of a vector or array. For
example, if in a mixer model we want to calculate the resulting
outlet ow rate we could use:
Outlet.F =

i
Inlet
i
.F
The above equation can be obtained by the last line of the fol-
lowing model:
Model Mixer
PARAMETERS
Ninputs as Integer(Brief="Number of inputs");
VARIABLES
Inlet(Ninputs) as stream;
Outlet as stream;
EQUATIONS
Outlet.F = sum(Inlet.F);
Note: If the argument of sum is a vector it will return a scalar,
but if the argument is an matrix (array with two dimensions) it
will return a vector with length equal to the number of lines of
the matrix.
In general sum makes the summation of the last dimension of the
argument. For instance, if we have:
VARIABLES
var3d(x,y,z) as Real(Brief="Three dimensional array");
var2d(x,y) as Real(Brief="Two dimensional array");
EQUATIONS
var2d = sum(var3d);
In the equation above, each element of var2d contains the sum
of all elements of var3d over z, which is the last dimension. In
other words:
var2d
x,y
=

z
var3d
x,y,z
Prod
The prod function returns the productory of a vector or array.
The logic of prod is exactly the same presented above for the
sum function.
36 4 Advanced Modeling
4.1.5 Loop For
Most equations involving arrays are more convenient handled by
automatic equation expansion, see subsection 4.1.3. But in some
rare situations the equation expansion cannot yield the desired
result and one or more for loops are needed.
The syntax of a for loop is the following:
EQUATIONS
for i in [1:Ncomps]
Outlet.z(i) = Inlet.z(i);
end
Note: The index i used by the for loop above does not need
to be declared and is valid only in the context of the loop.
The above equation also can be written in a more compact fash-
ion:
EQUATIONS
Outlet.z([1:Ncomps]) = Inlet.z([1:Ncomps]);
4.2 Conditional Modeling
Under construction: needs to be documented
5 Calculation Object Interface
In this chapter, we describe how the CalcObject paradigm can be used to load, at run
time, third party software within EMSO entities. In chapter 6 is explained how to implement
a new CalcObject service.
Contents
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
5.2 Using CalcObjects . . . . . . . . . . . . . . . . . . . . . . . . . . 39
37
38 5 Calculation Object Interface
5.1 Introduction
In this section we describe what is a CalcObject and what it
is good for.
5.1.1 What is CalcObject?
CalcObject is an interfacing mechanism which enables the user
to load calculation services provided by third party software within
EMSO. Typical cases where using CalcObjects is advisable are
when the following calculations are required:
Property based on correlations
Thermo-physical properties
CFD calculations for complex geometries CFD is the acronym for
Computational Fluid Dynamics.
5.1.2 Why use a CalcObject?
EMSO is an equation-based tool, therefore most type of math-
ematical relations can be expressed directly as equations of a
Model using the EMSO modeling language. However, there are
some cases in which using equations is barely convenient. Typical
examples include:
The relationship cannot be expressed in a closed algebraic
form without introducing many intermediate quantities with
no physical sense;
The relationship requires lots of data parameters;
Already exists well established software that provides the
required calculation;
It is dicult to converge the problem without decoupling
the system.
5.1.3 The CalcObject Basics
Before showing how to use a CalcObject, lets introduce its
basics:
Any number of CalcObjects can be declared within an
EMSO entity (Model, FlowSheet, etc.). The declara-
tion of a CalcObject is very near to a parameter decla-
ration;
Each CalcObject provides a set of methods which are
the calculation routines available to be used in EMSO;
5.2 Using CalcObjects 39
Each method calculates one quantity (the output) for given
zero or more other quantities (the inputs).
The output of a method, as each of its inputs, can be a
scalar or a vector of Real, Integer or Boolean and
have an unit of measurement (enabling EMSO to automatic
handle the required unit of measurement conversions).
Additionally, a method can provide partial derivatives of its
output with respect to all or some of its inputs.
Each CalcObject service is provided by one library le
which must be compatible with the CalcObject interface
specication presented in section 6.1.
5.2 Using CalcObjects
In this section we show how to use CalcObjects within some
EMSO entities.
5.2.1 Using CalcObjects in Models
As already mentioned, the declaration of a CalcObject is very
near to a parameter declaration but using as base the EMSO
built-in type CalcObject. In Code 5.1 a typical usage of the CalcObject is one of the EMSO
built-in types, as Real, Integer,
etc.
CalcObject paradigm can be seen.
Code 5.1: EML le streams.mso.
13 Model stream
14 PARAMETERS
15 ext NComp as Integer (Brief = "Number of chemical components",
Lower = 1);
17 VARIABLES
18 F as flow_mol;
19 T as temperature;
20 P as pressure;
21 z(NComp) as fraction (Brief = "Molar Fraction");
22 h as enth_mol;
23 v as fraction (Brief = "Vapourisation fraction");
24 end
26 Model stream_therm as stream
27 PARAMETERS
28 ext PP as CalcObject (Brief = "External Physical Properties
");
30 EQUATIONS
31 h = (1-v)
*
PP.LiquidEnthalpy(T, P, z) + v
*
PP.VapourEnthalpy(T,
P, z);
32 end
34 Model streamTP as stream_therm
35 PARAMETERS
36 ext PP as CalcObject (Brief = "External Physical Properties
");
40 5 Calculation Object Interface
The Code 5.1 makes part of EML, in line 14 of it a CalcObject
is declared. As can be seen it is declared with the ext prex,
therefore it is only an reference to a entity with same name but External parameters were treated
in subsection 3.2.1.
declared in the top level model, the FlowSheet.
In the case of a concrete CalcObject (declared without the
ext prex) the user must supply the corresponding calculation
library le and optionally supply arguments to create the object. A calculation library must be a
valid DLL (dynamic link library) or
a SO (shared library) le in win32
and posix platforms respectively.
A sample declaration of a concrete CalcObject follows:
PARAMETERS
PP as CalcObject(Brief="Physical Properties Object", File="
vrpp");
In this code, the object PP will be created using the DLL le
vrpp.dll . The user should suppress the le
extension and library prex, in such
case EMSO will automatically look
for vrpp.dll under Win32 and
libvrpp.so on Posix platforms.
In line 18 of Code 5.1 the method NumberOfComponents is
used. As can be seen, this method does not require any input and,
as expected, returns a dimensionless scalar integer (the number
of components of the mixture represented by PP). In lines 30 and
35 of Code 5.1 other two methods are found, but these methods
requires three inputs:
T temperature in Kelvin;
P pressure in kPa;
z molar composition vector.
The cited methods return the molar enthalpy of the vapor and
liquid phases of the mixture represented by PP in J/mol respec-
tively.
II. Programming Guide
41
6 Developing new CalcObject Services
In this chapter, we describe how to develop a new CalcObject service enabling to load
external software within EMSO entities. In section 5.2 the usage of the CalcObject
interface was described. Note that the information presented here is not a required to use
CalcObjects but to develop new services.
Contents
6.1 Interface Specication . . . . . . . . . . . . . . . . . . . . . . . . . 43
6.2 Writing new CalcObject Services . . . . . . . . . . . . . . . . . 49
6.3 Documenting CalcObject Services . . . . . . . . . . . . . . . . . 50
42
6.1 Interface Specication 43
6.1 Interface Specication
In order to implement a CalcObject service one can use any
of the most common scientic programming languages. There
are template implementations available for C, C++ and Fortran,
presented in sections 6.2.1, 6.2.2 and 6.2.3 respectively. It follows
bellow the concepts behind the CalcObject interface.
Note: The information presented here is not a required to use
already made CalcObjects but to develop new services.
A CalcObject provides a set of methods, each of which receive
zero or more inputs and returns one output. In order to implement
a library which provides such service one must implement the
following functions:
create: creates a new instance of the CalcObject ser-
vice
check method: checks if a specic method exists and
returns the number of inputs and outputs
method details: provides detailed information about a
specic method
set parameter: function for setting a parameter of the
object
calc: provides the calculation for a given method
destroy: destroys an object instance created with the
create function
6.1.1 Create Function
When a new EMSO task is started, like a dynamic simulation,
for each concrete CalcObject declared, EMSO creates a new
instance of such object. In this creation procedure the create
function is called in order to load the instance specic data.
The create function has the following form:
create(objectHandler, retVal, msg)
where the arguments are as described in Table 6.1.
EMSO does not need to known what really happens in the create
function, but the expected behavior is:
create the memory to some data structure which holds the
instance dependent data;
44 6 Developing new CalcObject Services
Table 6.1: Arguments of the CalcObject create function.
Argument name Type Description
objectHandler [out] integer Unique identier of the object in-
stance created (will be used to iden-
tify the instance in subsequent calls).
retVal [out] integer Return ag, see ??.
msg [out] text A text space where error messages
should be copied.
if some error or warning has occurred set retVal accord-
ingly and copy a message to the msg
return the memory address of the data structure (or an
integer which unique identies it) in the objectHandler
As EMSO Models, a CalcObject can have parameters. An
example could be the required precision to be used when calcu-
lating a method. These parameters can be set as usuall in the
Model, for instance:
PARAMETERS
PP as CalcObject(Brief="Physical Properties Object");
SET
PP.VapourModel = "PR";
PP.Accuracy = 1e-5;
For each set EMSO will make a call to the set parameter
function. The prototype of the set parameter function is as
follows:
set_parameter(objectHandler,
parameterName, valueType, valueLength,
values, valuesText,
retVal, msg)
where the arguments are as described in Table 6.2.
The expected behavior of the set parameter function is:
Check if the given parameterName is a valid parameter,
otherwhise set retVal accordingly and copy a message to
msg
If the parameter is valid, store it to be used later
6.1.2 Destroy Function
When a CalcObject instance is created the create function
is called. Then, when the object is no longer used by EMSO
6.1 Interface Specication 45
Table 6.2: Arguments of the CalcObject set parameter function.
Argument name Type Description
objectHandler [in] integer Identier of the object instance com-
ing from the create function.
parameterName [in] text The name of the parameter to be set.
valueType [in] integer The type of the parameter (1 for
Real, 2 for Integer, 3 for
Boolean and 4 for Text)
valueLength [in] integer The length of the value (1 if is a
scalar)
values [in] real vector The vector of values (empty if the
type is Text)
valuesText [in] text vector The vector of values (empty if the
type is not Text)
retVal [out] integer Return ag, see ??.
msg [out] text A text space where error messages
should be copied.
it is destroyed. In some point of the destruction procedure the
destroy function is called. This function has the following form:
destroy(objectHandler, retVal, msg)
where the arguments are as described in Table 6.3.
The expected behavior of the destroy function is to release any
memory, close data banks, etc. regarding the given objectHandler.
Table 6.3: Arguments of destroy function.
Argument name Type Description
objectHandler [in] integer Identier of the object instance com-
ing from the create function.
retVal [out] integer Return ag, see ??.
msg [out] text A text space where error messages
should be copied.
6.1.3 Verication Functions
A priori, EMSO does not known what are the methods supplied by
a particular CalcObject nor the number or kind of its inputs
46 6 Developing new CalcObject Services
and outputs. This information is obtained with the functions
check method and method details.
Basically, the former function is used to check the existence of a
method and has the following form:
check_method(objectHandler, methodName, methodID,
numOfInputs, numOfOutputs,
retVal, msg)
where the arguments are as described in Table 6.4.
Table 6.4: Arguments of check method function.
Argument name Type Description
objectHandler [in] integer Identier of the object instance com-
ing from the create function.
methodName [in] text Name of the method being checked.
methodID [out] integer Unique identier for the given method
name (will be used to identify the
method in subsequent calls).
numOfInputs [out] integer The number of expected inputs of the
method.
numOfOutputs [out] integer The number of outputs of the
method.
retVal [out] integer Return ag, see ??.
msg [out] text A text space where error messages
should be copied.
From the check method function the following behavior is ex-
pected:
Check the existence of a given methodName, if the method
does not exist this should be reported copying some mes-
sage into error.
If the required method exists, return the number of inputs
and the number of outputs. Optionally, an unique identier
for the method can be returned in methodID. Then EMSO
will use this identier in subsequent calls, this procedure can
speed up the evaluation of the functions.
Upon the ascertain of a method existence with the check method
function, the method details function is used to obtain de-
tailed information about the method. This function has the fol-
lowing form:
6.1 Interface Specication 47
method_details(objectHandler, methodName, methodID,
numOfInputs, inputLengths, inputTypes, inputUnits,
numOfOutputs, outputLengths, outputTypes,
outputUnits,
hasDerivatives,
retVal, msg)
where the arguments are as described in Table 6.5.
Table 6.5: Arguments of check inputs function.
Argument name Type Description
objectHandler [in] integer Identier of the object instance com-
ing from the create function.
methodName [in] text Name of the method being checked.
methodID [in] integer Identier of the method coming from
the check method function.
numOfInputs [in] integer The number of inputs of the method.
inputLengths [out] integer vector The length of each input.
inputTypes [out] integer vector The type of each input (1 for Real, 2
for Integer and 3 for Boolean).
inputUnits [out] text vector The unit of measurement of each in-
put.
numOfOutputs [in] integer The number of outputs of the
method.
outputLengths [out] integer vector The length of each output.
outputTypes [out] integer vector The type of each output (1 for Real,
2 for Integer and 3 for Boolean).
outputUnits [out] text vector The unit of measurement of each out-
put.
hasDerivatives [out] integer If the method provides analytical
derivatives calculation
retVal [out] integer Return ag, see ??.
msg [out] text A text space where error messages
should be copied.
The purpose of the method details function is to provide
detailed information about the inputs and outputs of a specic
method. The expected behaviour is:
Given the methodName (or the methodID previouslly re-
turned), set inputLengths, inputTypes and inputUnits.
Given the methodName (or the methodID previouslly re-
turned), set outputLengths, outputTypes and outputUnits.
48 6 Developing new CalcObject Services
If the method will provide calculation for the derivatives set
hasDerivatives to 1.
6.1.4 Calculation Function
Given the inputs, each CalcObject method calculates one or
more outputs. This calculation is provided by the calc function.
This should be implemented by the service, it has the following
form:
calc(objectHandler, methodName, methodID,
outputLength, numOfInputs, inputLengths, totalInputLenth,
methodInputs, methodOutput,
error, warning)
where the arguments are as described in Table 6.6.
Table 6.6: Arguments of calc function.
Argument name Type Description
objectHandler [in] integer Identier of the object instance com-
ing from the create function.
methodName [in] text Name of the method being checked.
methodID [in] integer Unique identier of the
method name, coming from
check method.
numOfInputs [in] integer The number of inputs.
inputLengths [in] integer vector The length of each input.
totalInputLength [in] integer Total input length.
inputValues [in] real vector Vector containing the input values.
numOfOutputs [in] integer The number of outputs.
outputLengths [in] integer vector The length of each input.
totalOutputLength [in] integer Total output length.
outputValues [out] real vector Vector to put the calculated output
values.
calculeDerivatives [in] integer Flag if the method should calculate
the derivatives or not.
outputDerivatives [out] real vector Vector to put the calculated output
derivative values.
error [out] text A text space where error messages
should be copied.
warning [out] text A text space where warning messages
should be copied.
The expected behaviour for the calc function is:
6.2 Writing new CalcObject Services 49
Given the methodName (or the methodID set previously)
and the inputValues, calculate the method and store
the results on outputValues.
Additionally, if the method has implementation for the deriva-
tives and calculeDerivatives is not false, return the
value of the derivatives on outputDerivatives.
6.2 Writing new CalcObject Services
In this section we describe how to implement a new CalcObject
service using the most common scientic programming languages.
As a base concept of the CalcObject interface was stated that
an EMSO entity can have any number of CalcObjects (see
??). Therefore, multiple instances of a CalcObject service can
be active simultaneously. If this is the case and the service being
implemented has instance dependent data, each CalcObject
instance should allocate its own data. Unfortunately, dynamic
memory allocation is not a trivial task in Fortran then if the ser-
vice being implemented is intended to support multiple instances
the user should consider in using C or C++ or wrap his Fortran
implementation using such languages.
6.2.1 Writing CalcObject Services in Fortran
As mentioned in section 6.1, in order to implement a new CalcObject
service some functions must be implemented. In le external object.f
found at interfaces directory a template implementation for
a CalcObject service in Fortran is given.
The template le has the required function calling conventions,
besides several comments which helps the user in the task of
implementing a new service and creating the library.
6.2.2 Writing CalcObject Services in C
As mentioned in section 6.1, in order to implement a new CalcObject
service some functions must be implemented. In le external object.c
found at interfaces directory a template implementation for
a CalcObject service in C is given. This le makes use of the
interface denitions declared at external object.h. Note
that the header le should not be modied by the user.
The template le has the required function calling conventions,
besides several comments which helps the user in the task of
implementing a new service and creating the library.
50 6 Developing new CalcObject Services
6.2.3 Writing CalcObject Services in C++
As mentioned in section 6.1, in order to implement a new CalcObject
service some functions must be implemented. When using C++,
this functions actually are member functions of a class. In le
external object.cpp, found at interfaces directory, a
template implementation for a CalcObject service in C++ is
given. This le makes use of the interface denitions declared
in le external object.h. Note that the header le should
not be modied by the user.
The C++ template le has a skeleton implementation that should
be lled by the user, besides several comments which helps the
user in the task of implementing a new service and creating the
library. Actually, when implement a new CalcObject services
in C++ the user can choose between implement the interfaces
exactly as described in the C template le or to implement it as
class. The C++ template le uses the class approach.
6.3 Documenting CalcObject Services
The software VRTherm is a typical example of CalcObject.
Its documentation can be used as a base for developing the manual VRTherm is a software for physical
properties prediction from VRTech
www.vrtech.com.br.
for a new service.
Basicaly, a good CalcObject documentation should include at
least:
how to install the service;
how to use the service
what is the File of the library;
specify whether the service supports multiple instances
or not;
valid parameters and its purposes;
document the methods supplied by the service as well
as the inputs and outputs.
7 Developing new Solvers
In this chapter, we describe how to develop new solver services enabling to solve the problems
coming from the FlowSheets with custom solvers. These solvers are called external solvers
because they could be freely implemented by third parties and are implemented in a very
similar way to CalcObjects described in chapter 6.
Contents
7.1 NLA Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
7.2 DAE Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
7.3 Writing new Solver Services . . . . . . . . . . . . . . . . . . . . . 61
7.4 Documenting Solver Services . . . . . . . . . . . . . . . . . . . . . 62
51
52 7 Developing new Solvers
7.1 NLA Solvers
Nonlinear-algebraic (NLA) systems arise naturally from steady-
state mathematical models or in the initialization of dynamic
simulations. In order to obtain the numerical solution, EMSO
automatically converts this kind of problem into the following
formulation:
F(y) = 0, y
l
< y < y
u
(7.1)
where y is the vector of variables to solve, F(y) is the vector
of functions (the equations), y
l
and y
u
are the lower and upper
bounds, respectivelly.
In this section we describe how to implement a new solver for
systems as Equation 7.1.
When communicating to solvers EMSO acts as a server which give
informations about the problem being solved. For NLA problems
EMSO provides four functions to the solver:
ResFn: returns the residuals for a given y
LSetup: tells EMSO to update the Jacobian matrix F/y
LSolve: solves for x the linear system Ax = b for a given
b, where A is the Jacobian matrix F/y
LProd: makes the product y = Ax + y, where A is This operation is also known as the
GEMV BLAS operation
the Jacobian matrix, and are scalars, x and y are given
vectors.
Using the functions provided by EMSO, a new NLA solver needs
to implement the following routines:
create: creates a new instance of the NLA external solver
for a given problem structure;
solve: solves the problem;
destroy: destroy the external solver instance created
with the create function;
7.1.1 Residuals Function
For any point y
c
which is not the solution of Equation 7.1 we will
have a residual:
F(y
c
) = res (7.2)
7.1 NLA Solvers 53
EMSO can calculate the residuals vector res with the ResFn
function which has the following form:
ResFn(y, res, EMSOdata, retVal)
where the arguments are as in Table 7.1.
Table 7.1: Arguments of the ResFn function.
Argument name Type Description
y [in] real Vector with the current point for y
res [out] real Residuals vector, will be calculated as a func-
tion of y.
EMSOdata - EMSO problem specic data (should not be
used by the solver).
retVal [out] integer Return ag, see ??.
7.1.2 Jacobian
Newtons like methods can solve Equation 7.1 iteratively with
some modication of the following equation:
F
y
(y
n
y
n+1
) = F(y
n
) (7.3)
where F/y is the Jacobian and F(y
n
) is the residuals vector
(subsection 7.1.1).
Using Equation 7.3 to solve the problem the solver will need to
solve a linear systems of equations. This can be done directly by
EMSO with the LSolve function:
LSolve(x. b, EMSOdata, retVal)
where the arguments are as in Table 7.2.
Note: The LSolve function solves for x given a vector b, de-
pending on the implementation of the solver, b can be F(y
n
)
or not.
It should be noted that the Jacobian is opaque to the solver. As
a consequence, EMSO can use ecient storage structures (dense
or sparse) and specic algorithms for solving the linear system
which are independent from the solver implementation.
54 7 Developing new Solvers
Table 7.2: Arguments of the LSolve function.
Argument name Type Description
x [out] real Vector with the solution of the linear system
b [in] real The independent vector b
EMSOdata - EMSO problem specic data (should not be
used by the solver)
retVal [out] integer Return ag, see ??.
The LSolve function solves the linear system using the Jacobian
of the system. But aiming at eciency EMSO does not updates
the Jacobian matrix each time it solves the linear system. The
solver needs to explicitly tell EMSO to update the Jacobian with
the function LSetup:
LSetup(EMSOdata, retVal)
where the arguments are as in Table 7.3.
Table 7.3: Arguments of the LSetup function.
Argument name Type Description
EMSOdata - EMSO problem specic data (should not be
used by the solver)
retVal [out] integer Return ag, see ??.
As can be seen in Table 7.3 the LSetup function does not re-
quire an input argument for y. EMSO uses the y values given at
the last call to ResFn (subsection 7.1.1), this method improve
the eciency when calculating the Jacobian using automatic dif-
ferentiation.
7.1.3 Matrix Multiplication
Some modications of the Newton method may require addition
linear algebra operations using the Jacobian matrix. For these
cases, EMSO provides a general product function, as follows:
y = Ax + y
where A is the Jacobian matrix, and are scalars, x and y are
given vectors.
7.1 NLA Solvers 55
Note: The LProd function considers that x and y are given
vectors, therefore x or y can be the current solution point or the
current vector of residuals, it is up to the designed of the solver.
Some codes may need a simplied version of the product, y =
Ax. This is easily achieved passing equal zero to the function
LProd.
The LProd function has the following prototype:
LProd(alpha, x, beta, y, EMSOdata, retVal)
where the arguments are as in Table 7.4.
Table 7.4: Arguments of the LProd function.
Argument name Type Description
alpha [in] real Given scalar
x [in] real Given vector
beta [in] real Given scalar
y [inout] real Given vector, will hold the result of the opera-
tion
EMSOdata - EMSO problem specic data (should not be
used by the solver).
retVal [out] integer Return ag, see ??.
7.1.4 Create and Destroy Functions
EMSO can run concurrent simulations, and so, in order to sup-
port this feature, a new solver instance is created for each new
simulation started. Each time EMSO needs a new solver it calls
the create function of the solver. As a consequence, each in-
stance of the solver should have its own memory space to avoid
conicts when running concurrent simulations.
The create function should allocate any memory needed by the
solver. All allocated memory should be released by the destroy
function.
The create function has the following form:
create(solverID, numOfEqs, resFn, y0, ylb, yub,
EMSOdata, iopt, ropt, retVal, msg)
where the arguments are as described in Table 7.5.
56 7 Developing new Solvers
Table 7.5: Arguments of the NLA solver create function.
Argument name Type Description
solverID [out] integer Unique identier of the solver instance created
(will be used to identify the instance in subse-
quent calls).
numOfEqs [in] integer The number of equations of the system.
resFn [in] function Function that calculates the residuals of the
system.
y0 [in] real vector Initial values of the variables.
ylb [in] real vector Lower bound for the variables.
yub [in] real vector Upper bound for the variables.
EMSOdata [in] integer EMSO problem specic data (only to pass back
to resFn, lsetup and lsolve)
iopt [in] integer vector The vector of integer options, see ??.
ropt [in] real vector The vector of real options, see ??.
retVal [out] integer Return ag, see ??.
msg [out] text A text space where error messages should be
copied.
Warning: The solver should return a unique SolverID for each
call to create because this integer will be used to identify the
solver instance in subsequent calls to solve or destroy.
When EMSO does not need the solver anymore it calls the destroy
function on it:
destroy(solverID, retVal, msg)
where the arguments are as described in Table 7.6.
Table 7.6: Arguments of the NLA solver destroy function.
Argument name Type Description
solverID [in] integer Unique identier of the solver instance (re-
turned by create).
retVal [out] integer Return ag, see ??.
msg [out] text A text space where error messages should be
copied.
Using the given solverID the solver should release any memory
associated with that solver instance.
7.1 NLA Solvers 57
Note: When using C or C++, an easy way to implement an
unique identier for the solver is to create an structure or class
for the solver and return its address as the identier. Then the
solver just needs to cast back the SolverId to get the address
of the structure.
7.1.5 Solve Function
Once the solver instace has been created (as described in sub-
section 7.1.4), EMSO will generate a call to the solve function
each time EMSO needs to solve the problem.
The solve function has the following form:
solve(solverID, numOfEqs, resFn, lsetup, lsolve,
y, ylb, yub, EMSOdata, rtol, atol,
iopt, ropt, retVal, msg)
where the arguments are as described in Table 7.10.
Table 7.7: Arguments of the NLA solver solve function.
Argument name Type Description
solverID [out] integer Unique identier of the solver instance (re-
turned by create).
numOfEqs [in] integer The number of equations of the system.
resFn [in] function Function that calculates the residuals of the
system.
y [inout] real vector Initial values of the variables and the solution
at the end.
ylb [in] real vector Lower bound for the variables.
yub [in] real vector Upper bound for the variables.
EMSOdata [in] integer EMSO problem specic data (only to pass back
to resFn, lsetup and lsolve)
rtol [in] real The relative accuracy
atol [in] real The absolute accuracy (optionally a vector)
iopt [in] integer vector The vector of integer options, see ??.
ropt [in] real vector The vector of real options, see ??.
retVal [out] integer Return ag, see ??.
msg [out] text A text space where error messages should be
copied.
EMSO can call multiple times the solve function before destoy-
ing it. Each time EMSO asks the solver to solve the problem a
initial guess y is given and the solution should be returned on the
same vector.
58 7 Developing new Solvers
Warning: The parameter rtol is always a real scalar but atol
can be a vector depending on the options at iopt.
7.2 DAE Solvers
Dierential-algebraic equations (DAE) arise naturally from dy-
namic modeling in several engineering areas.
Prior to a dynamic simulation, EMSO internally converts in mem-
ory the given FlowSheet description to a general DAE system
in the following form:
F(t, y, y

) = 0, y
l
< y < y
u
(7.4)
where t is the independent variable (usually the time), y is the
vector of variables, y

are the derivatives of y with respect to t


and F are the equations of the problem being solved.
In EMSO a DAE solver is supposed only to advance one step
forward in the solution of a problem. In other words, given a valid
t
n
, y
n
, y

n
the DAE solver should only to advance one step to a
next solution t
n+1
, y
n+1
, y

n+1
.
Note: The rst solution t
0
, y
0
, y

0
is obtained using a NLA solver
in the initialization step.
Between calls to the DAE solver EMSO checks if events have
happened and make proper reinitializations if needed.
In a very similar way to NLA solvers (section 7.1) EMSO provides
a set of services which give informations about the problem being
solved:
ResFn: returns the residuals of Equation 7.4 for a given
t, y, y

LSetup: tells EMSO to update the Jacobian matrices


F/y and F/y

LFactor: builds the iteration matrix cF/y + dF/y

LSolve: solves for x the linear system Ax = b for a given


b, where A is the iteration matrix cF/y + dF/y

Using the functions provided by EMSO, a new DAE solver needs


to implement the following routines:
7.2 DAE Solvers 59
create: creates a new instance of the DAE external solver
for a given problem structure;
step: takes one step forward in the solution or makes an
interpolation for a desired point;
destroy: destroy the solver instance created with the
create function;
7.2.1 Create and Destroy Functions
EMSO can run concurrent simulations, in order to do this a new
solver instance is created for each new simulation started. The
create function is responsible for creating a new instance of the
solver and has the following form:
create(solverID, numOfEqs, resFn,
indVar0, y0, yp0, variableIndexes,
EMSOdata, rtol, atol, iopt, ropt,
retVal, msg)
where the arguments are as described in Table 7.8.
Table 7.8: Arguments of the DAE solver create function.
Argument name Type Description
solverID [out] integer Unique identier of the solver instance created
(will be used to identify the instance in subse-
quent calls).
numOfEqs [in] integer The number of equations of the system.
resFn [in] function Function that calculates the residuals of the
system.
y0 [in] real vector Initial values of the variables y.
y0 [in] real vector Initial values of the variable derivatives y

.
variableIndexes [in] integer vector The index of each variable (only for high index
problems).
EMSOdata [in] integer EMSO problem specic data (only to pass back
to resFn, lsetup and lsolve)
rtol [in] real The relative accuracy
atol [in] real The absolute accuracy (optionally a vector)
iopt [in] integer vector The vector of integer options, see ??.
ropt [in] real vector The vector of real options, see ??.
retVal [out] integer Return ag, see ??.
msg [out] text A text space where error messages should be
copied.
60 7 Developing new Solvers
Warning: The solver should return an unique SolverID for
each call to create because this integer will be used to identify
the solver instance in subsequent calls to step or destroy.
When EMSO does not need the solver anymore it calls the destroy
function on it:
destroy(solverID, retVal, msg)
where the arguments are as described in Table 7.9.
Table 7.9: Arguments of the DAE solver destroy function.
Argument name Type Description
solverID [in] integer Unique identier of the solver instance (re-
turned by create).
retVal [out] integer Return ag, see ??.
error [out] text A text space where error messages should be
copied.
Using the given solverID the destroy function should release
any memory associated with that solver instance.
Note: When using C or C++ an easy way to implement an
unique identier for the solver is to create an structure or class
for the solver and return its address as the identier. Then the
solver just needs to cast back the SolverId to get the address
of the structure.
7.2.2 Step Function
After created as described in subsection 7.1.4, each time EMSO
needs to solve the problem it will call the solve function.
The solve function has the following form:
solve(solverID, numOfEqs, resFn, lsetup, lsolve,
y, ylb, yub, EMSOdata, rtol, atol,
iopt, ropt, retVal, msg)
where the arguments are as described in Table 7.10.
EMSO can call multiple times the solve function before destoy-
ing it. Each time EMSO asks the solver to solve the problem a
initial guess y is given and the solution should be returned on the
same vector.
7.3 Writing new Solver Services 61
Table 7.10: Arguments of the NLA solver solve function.
Argument name Type Description
solverID [out] integer Unique identier of the solver instance (re-
turned by create).
numOfEqs [in] integer The number of equations of the system.
resFn [in] function Function that calculates the residuals of the
system.
y [inout] real vector Initial values of the variables and the solution
at the end.
ylb [in] real vector Lower bound for the variables.
yub [in] real vector Upper bound for the variables.
EMSOdata [in] integer EMSO problem specic data (only to pass back
to resFn, lsetup and lsolve)
rtol [in] real The relative accuracy
atol [in] real The absolute accuracy (optionally a vector)
iopt [in] integer vector The vector of integer options, see ??.
ropt [in] real vector The vector of real options, see ??.
retVal [out] integer Return ag, see ??.
msg [out] text A text space where error messages should be
copied.
Warning: The parameter rtol is always a real scalar but atol
can be a vector depending on the options at iopt.
7.3 Writing new Solver Services
In this section we describe how to implement a new solver services
for both NLA and DAE systems using the most common scientic
programming languages.
As cited before EMSO is able to run concurrent simulations.
Therefore, multiple instances of a external solver service can be
active simultaneously. Unfortunately, dynamic memory allocation
is not a trivial task in Fortran and is left as a challenge to the
user. As an alternative the user should consider in using C or
C++ or wrap his Fortran implementation using such languages.
7.3.1 Writing External Solver Services in Fortran
As mentioned in sections ?? and 7.2, in order to implement a new
external solver service a set of functions must be implemented. In
les NLASolverTemplate.f and DAESolverTemplate.f
62 7 Developing new Solvers
found at interfaces directory are given template implemen-
tations for an external NLA and DAE solvers services in Fortran.
The template les has the required function calling conventions,
besides several comments which helps the user in the task of
implementing a new service and creating the library.
7.3.2 Writing External Solver Services in C
As mentioned in section 7.2, in order to implement a new ex-
ternal solver service a set of functions must be implemented.
In le ExterSolverTpl.c found at interfaces directory
a template implementation for a external solver service in C is
given. This le makes use of the interface denitions declared at
ExternalSolver.h. Note that the header le should not be
modied by the user.
The template le has the required function calling conventions,
besides several comments which helps the user in the task of
implementing a new service and creating the library.
7.3.3 Writing External Solver Services in C++
As mentioned in section 7.2, in order to implement a new external
solver service a set of functions must be implemented. When us-
ing C++ this functions actually are member functions of a class.
In le ExternalSolverTlp.cpp found at interfaces di-
rectory a template implementation for an external solver service
in C++ is given. This le makes use of the interface denitions
declared in le ExternlaSolver.h. Note that the header
le should not be modied by the user. When included in a
C++ le the ExternlaSolver.h, besides the C interfaces,
declares two C++ pure abstract class called NLASolverBase
and DAESolverBase.
The C++ template le has a skeleton implementation that should
be lled by the user, besides several comments which helps the
user in the task of implementing a new service and creating the
library. Actually, when implement solver services in C++ the user
can choose between implement the interfaces exactly as described
in the C template les or to implement a class deriving from the
given pure virtual classes as made in the C++ template le.
7.4 Documenting Solver Services
Under construction: To be documented.
Index
Abstract models, 26
Array
equation expansion, 34
for, 36
function, 35
loops, 36
Multidimensional, 34
prod, 35
sum, 35
Arrays, 33
Calculation Object
developing, 42
documenting, 50
interface specication, 43
the basics, 38
using, 39
what is, 38
why use, 38
writing, 49
Comments, 19
Composition, 18
Conditional Modeling, 36
Connections, 28
Consistency
check, 13
Console Window, 10
DAE Solver
writing, 61
DAE solvers, 58
DASSLC, vii
Devices, 27
connections, 28
Documenting
calculation objects, 50
code, 19
EMSO
graphical interface, 8
license, vi
running, 8
what is, 3
why use, 3
Equation, 25
expansion, 34
Explorer panel, 9
External Solver
documenting, 62
writing, 61
Flowsheet, 27
customizing, 15
denition, 8
running, 14
tutorial, 10
writing, 12
For, 36
FOX-Toolkit, vii
Functions
list of, 31
FXScintilla, vii
IDA, vii
include les, see using les
Inheritance, 18
Initial conditions, 26
Installation, 5
posix, 6
win32, 6
Ipopt, vii
Language, 17
License, vi
Loop, 36
MDI panel, 10
Model, 22
abstract, 26
advanced, 32
composition, 25
denition, 8
language, 17
NLA Solver
63
64 Index
writing, 61
NLA solvers, 52
Object oriented, 18
Optimization, 29
dynamic, 31
large scale, 30
simple problems, 30
Parameter, 23
external, 23
Problems Window, 9
Prod, 35
Results
visualizing, 14
Solver
writing, 61
Solvers
DAE, 58
developing, 51
NLA, 52
Specications, 28
Sum, 35
SUNDIALS, vii
Types, 20
UMFPACK, vii
Units of measurement, 26
UOM, see Units of measurement
using les, 21
Variable, 24
input, 24
output, 24
Variables
connections, 28
specications, 28
Vectors, 33