Sie sind auf Seite 1von 135

EMSO

Manual

Rafael de Pelegrini Soares


www.rps.eng.br

LastChangedDate: 2007-08-30 11:22:15 -0300 (qui, 30 ago 2007)

Contents

Users Guide

1 Introduction

1
2

1.1

What is EMSO and EML? . . . . . . . . . . . . .

1.2

Why use EMSO? . . . . . . . . . . . . . . . . . .

1.2.1

Easy FlowSheet building . . . . . . . . . .

1.2.2

Integrated Graphical Interface . . . . . . .

1.2.3

Open-Source Model Library . . . . . . . .

1.2.4

Object-Oriented Modeling Language . . .

1.2.5

Multi-Platform system . . . . . . . . . . .

1.2.6

Fast and Transparent Setup . . . . . . . .

1.2.7

Solution Power . . . . . . . . . . . . . . .

1.2.8

Modeling of discontinuous process . . . . .

1.2.9

Operational procedures scripts . . . . . . .

1.2.10 Optimization . . . . . . . . . . . . . . . .

1.2.11 Parameter Estimation . . . . . . . . . . .

1.2.12 Data Reconciliation . . . . . . . . . . . .

1.2.13 Case Study . . . . . . . . . . . . . . . . .

1.2.14 Sensitivity Analysis . . . . . . . . . . . . .

1.2.15 Open Interfaces . . . . . . . . . . . . . .

1.2.16 Open Engine API . . . . . . . . . . . . .

Installation . . . . . . . . . . . . . . . . . . . . .

1.3.1

Installing EMSO in win32 platforms . . . .

1.3.2

Installing EMSO in POSIX platforms . . .

1.3

2 Overview

2.1

EMSO Basics

. . . . . . . . . . . . . . . . . . .

2.2

Running EMSO . . . . . . . . . . . . . . . . . .

2.2.1

Starting EMSO in win32 platforms . . . .

2.2.2

Starting EMSO in POSIX platforms . . . .

2.3

EMSO graphical interface . . . . . . . . . . . . .

2.4

Tutorials . . . . . . . . . . . . . . . . . . . . . . 11
2.4.1

Three Tank FlowSheet . . . . . . . . . 12

3 EMSO Modeling Language


3.1

3.2

3.3

3.4

18

Modeling basics . . . . . . . . . . . . . . . . . . 19
3.1.1

Object Oriented Modeling . . . . . . . . . 19

3.1.2

Writing EMSO Entities . . . . . . . . . . 20

3.1.3

Documenting with Comments . . . . . . . 20

3.1.4

Types . . . . . . . . . . . . . . . . . . . . 21

3.1.5

Using files . . . . . . . . . . . . . . . . . 22

Model . . . . . . . . . . . . . . . . . . . . . . . 23
3.2.1

Parameters . . . . . . . . . . . . . . . . . 24

3.2.2

Variables . . . . . . . . . . . . . . . . . . 25

3.2.3

Composition in Models . . . . . . . . . . 26

3.2.4

Equations . . . . . . . . . . . . . . . . . 27

3.2.5

Initial Conditions . . . . . . . . . . . . . . 28

3.2.6

Abstract Models . . . . . . . . . . . . . 28

FlowSheet . . . . . . . . . . . . . . . . . . . . 28
3.3.1

Devices

. . . . . . . . . . . . . . . . . 29

3.3.2

Connections . . . . . . . . . . . . . . . . 29

3.3.3

Specifications . . . . . . . . . . . . . . . 30

3.3.4

Options . . . . . . . . . . . . . . . . . . . 30

Optimization . . . . . . . . . . . . . . . . . . . . 30
3.4.1

Simple Optimizations . . . . . . . . . . . 32

3.4.2

Large-Scale Optimization . . . . . . . . . 33

3.5

3.6

3.7

3.8

3.9

3.4.3

Mixed Integer Optimization . . . . . . . . 33

3.4.4

Options . . . . . . . . . . . . . . . . . . . 34

3.4.5

Dynamic Optimization . . . . . . . . . . . 34

Parameter Estimation . . . . . . . . . . . . . . . 35
3.5.1

Experiments . . . . . . . . . . . . . . . . 36

3.5.2

Estimate . . . . . . . . . . . . . . . . . . 37

3.5.3

Options . . . . . . . . . . . . . . . . . . . 37

Data Reconciliation . . . . . . . . . . . . . . . . 39
3.6.1

Experiments . . . . . . . . . . . . . . . . 40

3.6.2

Reconcile . . . . . . . . . . . . . . . . . . 41

3.6.3

Free . . . . . . . . . . . . . . . . . . . . 42

3.6.4

Options . . . . . . . . . . . . . . . . . . . 42

Case Study . . . . . . . . . . . . . . . . . . . . . 45
3.7.1

Vary . . . . . . . . . . . . . . . . . . . . 46

3.7.2

Response . . . . . . . . . . . . . . . . . . 46

3.7.3

Results . . . . . . . . . . . . . . . . . . . 46

Sensitivity Analysis . . . . . . . . . . . . . . . . . 48
3.8.1

Vary . . . . . . . . . . . . . . . . . . . . 50

3.8.2

Response . . . . . . . . . . . . . . . . . . 50

3.8.3

Results . . . . . . . . . . . . . . . . . . . 51

Built-in Functions . . . . . . . . . . . . . . . . . 53

3.10 Units Of Measurement (UOM) . . . . . . . . . . 54


3.10.1 Fundamental Units . . . . . . . . . . . . . 54
3.10.2 Derived Units . . . . . . . . . . . . . . . 54
3.11 Solver Options . . . . . . . . . . . . . . . . . . . 58
4 Advanced Modeling
4.1

66

Arrays . . . . . . . . . . . . . . . . . . . . . . . 67
4.1.1

Vectors . . . . . . . . . . . . . . . . . . . 67

4.1.2

Multidimensional Arrays . . . . . . . . . . 68

4.1.3

Equation Expansion . . . . . . . . . . . . 68

4.2

4.1.4

Array Functions . . . . . . . . . . . . . . 69

4.1.5

Loop For . . . . . . . . . . . . . . . . . . 70

Conditional Modeling . . . . . . . . . . . . . . . 70

5 Calculation Object Interface


5.1

5.2

71

Introduction . . . . . . . . . . . . . . . . . . . . 72
5.1.1

What is Plugin? . . . . . . . . . . . . . 72

5.1.2

Why use a Plugin? . . . . . . . . . . . 72

5.1.3

The Plugin Basics . . . . . . . . . . . . 72

Using Plugins . . . . . . . . . . . . . . . . . . 73
5.2.1

Using Plugins in Models . . . . . . . . 73

6 EMSO Matlab Scilab Interface

76

6.1

EMSO Basics

. . . . . . . . . . . . . . . . . . . 77

6.2

Installation . . . . . . . . . . . . . . . . . . . . . 77
6.2.1

Requisites . . . . . . . . . . . . . . . . . 77

6.2.2

Matlab Install . . . . . . . . . . . . . . . 77

6.2.3

Scilab Installation . . . . . . . . . . . . . 79

6.2.4

Scilab Uninstall . . . . . . . . . . . . . . 82

6.3

The Configuration Graphic User Interface . . . . . 82

6.4

c communication . . . . . . . . 87
Matlab/Simulink

6.5

c communication . . . . . . . . . . 90
Scilab/Scicos

7 EMSO CAPE-OPEN Interfaces

97

7.1

About the CAPE-OPEN standards . . . . . . . . 98

7.2

Using external thermodynamics sources . . . . . . 99

7.3

7.2.1

Setting an external Property Package to


be used on EMSO . . . . . . . . . . . . . 100

7.2.2

Using CAPE-OPEN thermodynamics on EMSO101

Using EMSO as an unit-operation block . . . . . . 102

II

Programming Guide

8 Developing new Plugin Services


8.1

8.2

8.3

9.2

9.3

9.4

105

Interface Specification . . . . . . . . . . . . . . . 106


8.1.1

Create Function . . . . . . . . . . . . . . 106

8.1.2

Destroy Function . . . . . . . . . . . . . . 108

8.1.3

Verification Functions . . . . . . . . . . . 108

8.1.4

Calculation Function . . . . . . . . . . . . 110

Writing new Plugin Services . . . . . . . . . . . 113


8.2.1

Writing Plugin Services in Fortran . . . 113

8.2.2

Writing Plugin Services in C . . . . . . 113

8.2.3

Writing Plugin Services in C++ . . . . 114

Documenting Plugin Services . . . . . . . . . . 114

9 Developing new Solvers


9.1

104

115

NLA Solvers . . . . . . . . . . . . . . . . . . . . 116


9.1.1

Residuals Function . . . . . . . . . . . . . 116

9.1.2

Jacobian . . . . . . . . . . . . . . . . . . 117

9.1.3

Matrix Multiplication . . . . . . . . . . . 118

9.1.4

Create and Destroy Functions . . . . . . . 119

9.1.5

Solve Function . . . . . . . . . . . . . . . 121

DAE Solvers . . . . . . . . . . . . . . . . . . . . 122


9.2.1

Create and Destroy Functions . . . . . . . 123

9.2.2

Step Function . . . . . . . . . . . . . . . 124

Writing new Solver Services . . . . . . . . . . . . 125


9.3.1

Writing External Solver Services in Fortran 125

9.3.2

Writing External Solver Services in C . . . 126

9.3.3

Writing External Solver Services in C++ . 126

Documenting Solver Services . . . . . . . . . . . 126

License

EMSO alpha version License


(C) 2004-2007 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 GIMSCOPa 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)

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 differential-algebraic equation systems
www.enq.ufrgs.br/enqlib/numeric/;
FOX-Toolkit : a C++ based Toolkit for developing Graphical User Interfaces easily and effectively
www.fox-toolkit.org;
FXScintilla : an implementation of Scintilla1 for the FOX-Toolkit
www.nongnu.org/fxscintilla;
RCOMPLEX : a solver for constrained nonlinear optimization.
www.enq.ufrgs.br/enqlib/numeric/;
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 improvements and bug-fixes 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.

Scintilla is a free source code editing component, see www.scintilla.


org.

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
2
3

Model tank
# body of the model
end

Code Identifier: emphasize identifiers that are commands,


file names and related entities.
Note: a note, for instance: EMSO is an equation based description system, therefore the order of the equations does not matter.

Warning: a warning advertise, for instance: a .mso file 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 specific for POSIX systems (Linux and Unix),
for instance: EMSO can be available for any POSIX compliant
system upon request.

Windows note: note specific for win32 systems (Windows 95


and above and Windows NT 4 and above), for instance: the
windows file system is not case sensitive.

Under construction: marks a section as not yet implemented


or documented.

I. Users Guide

Introduction

Go any further in reading this manual or using EMSO without read, understand and accept
the EMSO license, found on page vii.
In this chapter we will learn what is EMSO and why use it.

Contents
1.1

What is EMSO and EML? . . . . . . . . . . . . . . . . . . . . . .

1.2

Why use EMSO? . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1.3

Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1.1 What is EMSO and EML?

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 simply selecting and connecting model blocks. In addition, the user
can develop new models using the EMSO modeling language or
using 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 objectoriented 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 advantages.

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 files. Multiple files can be opened simultaneously and each file 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 .mso files coming with EMSO


are distributed under the terms of
the EMSO model license.

1.2.4

The EMSO distribution comes with a set of ready to use models


written in the EMSO modeling language the EMSO Model Library (EML). Therefore, complex FlowSheets can be built by
simply selecting EML models as Devices and connecting them.
EML is an open-source library and can be extended or modified
by the user.

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

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 specific models by deriving standard ones.
All EML models are written in the EMSO modeling language and
are stored in plain text .mso files 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 between 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 description to some solvable form. This translation step is called setup
phase.
In EMSO, the setup phase does not relies in the creation of intermediary files, compilation, linkage or translation to another
language, the models are directly converted (in memory) to systems 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 efficient 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 differentiation
algorithms are built-in in EMSO. Furthermore, it has proved to
be one of the most time efficient 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.2 Why use EMSO?


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
find 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
(manipulated variables) in the Optimization environment and
let the system to find the best solution. See examples in the
ammonia opt.mso and flash opt.mso in the folder
<EMSO>/mso/sample/optimization.

1.2.11

Parameter Estimation
EMSO can perform parameter estimation of dynamic and steadystate models using the Estimation environment. See examples
in the BatchReactor.mso and sample est.mso files in
the <EMSO>/mso/sample/estimation folder.

1.2.12

Data Reconciliation
EMSO can perform data reconciliation of steady-state models using the Reconciliation environment. See examples in the
heatEx.mso in the <EMSO>/mso/sample/reconciliation
folder.

1.2.13

Case Study
EMSO can perform case studies of variables of dynamic and
steady-state models using the CaseStudy environment. See examples in the CaseStudy ss.mso and CaseStudy dyn.mso
files in the <EMSO>/mso/sample/casestudy folder.

1.2.14

Sensitivity Analysis
EMSO can perform sensitivity analysis of dynamic and steadystate models using the Sensitivity environment. See examples in the Sensitivity ss.mso and Sensitivity dyn.mso
files in the <EMSO>/mso/sample/sensitivity folder.

1 Introduction

1.2.15

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 libraries. (See Part II).
In addition, there are standard interfaces for implementing new
differential-algebraic equations (DAE), nonlinear algebraic equations (NLA), and nonlinear optimization problem (NLP) solvers.

1.2.16

Open Engine API

AUTO2000 DAE can be


donwloaded at www.enq.ufrgs.
br/enqlib/numeric. See www.
peq.coppe.ufrj.br/auto_dae
for details.

1.3

EMSO is composed by two major softwares: the graphical interface and the engine. The EMSO power in solving complex
large-scale dynamic problems is available to be embedded in third
party software through the EMSO engine open Application Program Interface (API). Using this technology, EMSO installation
already provides an engine to build bifurcation diagrams using
AUTO2000 adapted to work with differential-algebraic equations
(DAE), and also SFunctions for simulating dynamic models
R
built with EMSO modeling language inside Matlab/Simulink
with continuous and discrete-time simulation. See the installation
procedure.

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.

1.3.1

Installing EMSO in win32 platforms


EMSO is compatible with a variety of win32 operational systems (Windows 95, Windows NT 4, Windows XP and above).
In order to install EMSO in such systems one can just run the
installation package emso-win32-<VERSION>.exe available
at www.enq.ufrgs.br/alsoc and follow the on screen instructions.

MINGW may be download at


www.mingw.org and CYGWIN at
www.cygwin.com.

In order to use the EMSO-AUTO interface it is also necessary to


install the AUTO2000 DAE package, that can be downloaded at
www.enq.ufrgs.br/enqlib/numeric, using a Linux-like
environment for Windows, such as MINGW or CYGWIN in the location /usr/local/auto/2000 dae. After the installation, just run
the script auto2000 dae provided in the root directory of the
AUTO2000 DAE, using the command source auto2000 dae.

1.3 Installation

7
There are some examples to test the installation in the directory /usr/local/auto/2000 dae/demos/DAE. Copy the
file auto emso.exe from <EMSO>/bin in the same location
of the examples and execute the command @r-emso ab dae,
where ab dae is the name of the example to run, or put the
directory <EMSO>/bin in the PATH environment variable.
In order to use the EMSO-Matlab/Simulink interface, just copy
the files emso sf.dll and emsod sf.dll from the location
<EMSO>/interface/matlab to the working directory. In
the original location there are some MDL files to run some examples in the Simulink.

1.3.2

Installing EMSO in POSIX platforms

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.

EMSO is compatible with a variety of POSIX platforms (Linux,


Unix).
In order to install EMSO in such systems you have to download the
archive emso-<PLATFORM>-<ARCH>-<VERSION>.tar.gz
available at www.enq.ufrgs.br/alsoc.
For instance, emso-linux2-i386-0.9.53.tar.gz is the
installation archive for Linux version 2 or above platforms running
in an i386 compatible machine.
The installation procedure for the EMSO-AUTO interface is the
same as for win32 platform, described above, just skip the part
for the Linux-like environment for Windows.
In order to use the EMSO-Matlab/Simulink interface, just copy
the files emso sf.mexlx and emsod sf.mexlx from the location <EMSO>/interface/matlab to the working directory. In the original location there are some MDL files to run
some examples in the Simulink, if you can make Simulink work in
Linux.
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>-<ARCH>-<VERSION>.tar.gz
# sudo mv emso /usr/local
# sudo ln -sf /usr/local/emso/bin/emso /usr/bin/emso

Note: The EMSO executable is found at the bin directory, the


installation at /usr/local is not mandatory.

Overview

This chapter provides an overview about EMSO. First some basics are presented followed by
some tutorials. These tutorials teaches how to:
build a FlowSheet composed by a set of predefine Models;
check the consistency of a FlowSheet
run a dynamic simulations and plot results;
customize FlowSheet options.
Further, the EMSO modeling language for development of new models is introduced.

Contents
2.1

EMSO Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.2

Running EMSO

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.3

EMSO graphical interface . . . . . . . . . . . . . . . . . . . . . . .

2.4

Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

11

2.1 EMSO Basics

2.1

EMSO Basics
EMSO is a software tool for modeling, simulation and optimization 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 files which are usually stored in .mso
files. Each .mso file can have any number of any of these entities and the EMSO graphical user interface can open an unlimited
number of .mso files simultaneously.

2.2

Running EMSO
EMSO is available in a variety of platforms:
Windows 95 or above and
Windows NT 4 or above.

Distribution for any POSIX


compliant platform can be built
upon request.

2.2.1

win32 platforms;
POSIX platforms: Linux and Unix.

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 with the command emso. Another option is to
double-click in file <EMSO>/bin/emso, where <EMSO> is the
directory where EMSO was installed, for instance /usr/local.

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 identical 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.

10

2 Overview

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 files and its contents (Models and FlowSheets).
The Figure 2.2 (a) shows a typical view of the file 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 interchanged, 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 files can have
problems. Each time that a file is opened the Problems window
automaticaly list all errors and warnings found, as exemplified by
the Figure 2.3.

2.4 Tutorials

11

(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 files 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. The directory

12

2 Overview

Figure 2.4: EMSO Console Window.


<EMSO>/mso/tutorial/ contains all code samples found in
this section, where <EMSO> is the directory where EMSO was
installed.
2.4.1

Three Tank FlowSheet


In this section we describe how to create and simulate the dynamic 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 file


In order to simulate this example, the first step is to create a new
.mso file containing a FlowSheet. This is achieved by left
clicking in the new file button . This will bring up the new file
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 fields Name and Location should be filled with the
desired file name and directory location, respectively. The user
can fill this dialog as exemplified in Figure 2.5 then left click in
the Accept button in order to create the new file. After this
EMSO will create and open a file with the given properties. At
this point the interface will look like Figure 2.6.

2.4 Tutorials

13

Figure 2.5: New file dialog wizard.

Figure 2.6: EMSO new file window.


Writing the FlowSheet
Before continue reading this tutorial is advisable to read the comments on the file new file created (which comes from the selected
template).
The first comments are about the using command. This command makes available all entities contained in a given filename or
directory (all files belonging to it).
In our example we will make use of one of the EML models, the
TankSimplified model. This model is found in file tanks.mso
in the library directory. Therefore, in order to use this model instead of copy and paste we will use this file with the using
command as follows:
using "stage_separators/tanks";

14

2 Overview

The file tank.mso (as most of the


EML files) uses the file
types.mso which contains the
declaration of several variable types
as length, area, etc.

This command turns available all entities contained in file tank.mso


which is part of EML. For more details about using see subsection 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 file
should look like Code 2.1.
Code 2.1: File ThreeTank1.mso.

using "stage_separators/tank";

FlowSheet ThreeTank
VARIABLES
Feed
as flow_vol;

4
5

DEVICES
Tank1 as tank_simplified;
Tank2 as tank_simplified;
Tank3 as tank_simplified;

7
8
9
10

CONNECTIONS
Feed
to
Tank1.Fout to
Tank2.Fout to

12
13
14
15
16

Tank1.Fin;
Tank2.Fin;
Tank3.Fin;

end

The Code 2.1 contains no problems, once there is no item on the


Problems window.
Warning: Even if a .mso file has no problems the FlowSheets
of such file 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 file 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
ThreeTank1.mso...
Number of variables: 7
Number of equations: 6
Degrees of freedom: 1

2.4 Tutorials

15
The number of variables and equations does not match
!
System is not consistent!

At this point the Problems window will also show the consistency problems. This error was expected, once we have neither
specified the input flow of the first 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
INITIAL
Tank1.h =
Tank2.h =
Tank3.h =

* m3/h;
1 * m;
2 * m;
1 * m;

The user can choose between to add this code into its FlowSheet
or use the already made file 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 flow of the first 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
file explorer and then left click in the
button.
Simulation of ThreeTank started ...
Simulation of ThreeTank finished succesifuly in
0.02 seconds.

16

2 Overview

Tip: In order to get more detailed output when running a simulation 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)).
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 profile by double clicking in it.
If not specified the integration
interval is the interval ranging from
0 to 100 seconds.

We have not configured the simulation time vector for our simulation and the default integration interval is not suitable for the
dynamics of our system. We can modify the integration interval
by adding, for instance, the following commands:
OPTIONS
TimeStep = 0.1;
TimeEnd = 2;
TimeUnit = 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 parameter values. Hence the default values for all parameters were
considered, these defaults come from the types on which the parameters 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.

2.4 Tutorials

17
At this point our code should look like Code 2.2 found in the
tutorial directory.
Code 2.2: File ThreeTank3.mso.
1

using "stage_separators/tank";

FlowSheet ThreeTank
VARIABLES
Feed
as flow_vol;

4
5

DEVICES
Tank1 as tank_simplified;
Tank2 as tank_simplified;
Tank3 as tank_simplified;

7
8
9
10

CONNECTIONS
Feed
to
Tank1.Fout to
Tank2.Fout to

12
13
14
15

SPECIFY
Feed = 10 * m3/h;

17
18

INITIAL
Tank1.Level = 1 * m;
Tank2.Level = 2 * m;
Tank3.Level = 1 * m;

20
21
22
23

SET
Tank2.k = 8 * m2.5/h;
Tank2.A = 4 * m2;

25
26
27

OPTIONS
TimeStep = 0.1;
TimeEnd = 2;
TimeUnit = h;

29
30
31
32
33

Tank1.Fin;
Tank2.Fin;
Tank3.Fin;

end

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 files stored, by default, in .mso files.

Contents
3.1

Modeling basics . . . . . . . . . . . . . . . . . . . . . . . . . . . .

19

3.2

Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

23

3.3

FlowSheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

28

3.4

Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

30

3.5

Parameter Estimation . . . . . . . . . . . . . . . . . . . . . . . . .

35

3.6

Data Reconciliation . . . . . . . . . . . . . . . . . . . . . . . . . .

39

3.7

Case Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

45

3.8

Sensitivity Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . .

48

3.9

Built-in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . .

53

3.10 Units Of Measurement (UOM) . . . . . . . . . . . . . . . . . . . .

54

3.11 Solver Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

58

3.1 Modeling basics

3.1

19

Modeling basics
As mentioned before, in EMSO a FlowSheet is the problem
in study. But, a FlowSheet is composed by a set of connected Devices, each one having a mathematical description
called Model.
In chapter 2 the Model and FlowSheet entities were introduced. The description of these entities share several basic concepts 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 behind the object oriented (OO) paradigm. The EMSO language
can be used to create high reusable models by means of composition 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 specific models reusing
already developed models.
In OO modeling this is achieved by inheritance, the ability to create 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.

See the EML file stream.mso, for


instance.

The EMSO modeling language provides unlimited levels of inheritance or multiple inheritance for Models and FlowSheets.
The following sections and EML are a good sources of examples
of inheritances.

20
3.1.2

3 EMSO Modeling Language


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 keyword, as follows.
FlowSheet FlowSheetName
# FlowSheet body
end
Model ModelName
# Model body
end

A .mso file 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 Model. 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 understanding 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 exemplifies 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

3.1 Modeling basics

21
$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.

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 can be one
of the built-in types or types derived 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
Real

Description
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

Switcher Type for textual parameters, with attributes:


Brief textual brief description
Valid the valid values for the switcher
Default default value for the switcher

Boolean

Type for logical parameters or variables, with attributes:


Brief textual brief description
Default default value for parameters and initial guess for variables

Plugin

Object for loading third party pieces of software providing special calculation
services, see chapter 5.

22

3 EMSO Modeling Language


As Table 3.1 shows, each built-in type has a set of attributes.
These attributes can be modified when a new type is created
deriving a preexistent one. For instance, consider the Code 3.1
making part of EML, in this file a set of convenient types are
declared, and are used in all EML models.
Code 3.1: EML file types.mso.
2
3

# Pressure
pressure as Real (Brief = "Pressure", Default=1,
Lower=1e-30, Upper=5e7, final Unit = atm);
press_delta as pressure (Brief = "Pressure
Difference", Default=0.01, Lower=-5e6);
head_mass as Real (Brief = "Head", Default=50, Lower
=-1e6, Upper=1e6, final Unit = kJ/kg);

Note that type declarations can be stated only outside of any


Model or FlowSheet context.
Variables can be only declared based on types deriving from
Real. Note that the Plugin type cannot be derived to a new
type, read more in chapter 5.
3.1.5

Using files
Code reuse is one of the key concepts behind EMSO. To achieve
this the user can be able to use code written in another files
without have to touch such files. A .mso file can make use of
all entities declared in another files with the using command.
This command has the following form:
using "file name";

where "file name" is a textual file name. Therefore, commands matching this pattern could be:
1
2
3

using "types";
using "streams";
using "tanks";

When EMSO find a using command it searches the given file


name in the following order:
1. the current directory (directory of the file where the using
was found);
2. the libraries configured on the system;

3.2 Model

23

Note: As shown in the sample code, if the user suppress the file
extension when using files 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 file system is not. Therefore, when using files in windows, the language became case insensitive to the file 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
2
3

Model name [as base]


PARAMETERS
[outer] name [as base[( (attribute = value)+ )]
];
VARIABLES
[in | out] name [as base[( (attribute = value)+ )
] ];

5
6

EQUATIONS
["equation name"] expression = expression;

8
9

INITIAL
["equation name"] expression = expression;

11
12

SET
name = expression;

14
15
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 ( );

24

3 EMSO Modeling Language


the code a|b means a or b;
name is a valid identifier chosen by the user;
base is a valid EMSO type or already declared Model;
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

When running an optimization or


parameter estimation the value of a
parameter could be the result of
the calculation.

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
starts.
In Code 3.2, each identifier in capitals starts a new section. In
line 2 the identifier PARAMETERS starts the section where the
parameters are declared. A parameter declaration follows the pattern 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 identified with
different names, can be declared. Examples of parameter declarations follows:
PARAMETERS
NumberOfComponents as Integer(Lower=0);
outer OuterPar as Real;

3.2 Model

25

Outer Parameters
As can be seen in line 3 of Code 3.2 a parameter declaration
can use the outer prefix. When a parameter is declared with
this prefix, the parameter is only a reference to a parameter with
same name but declared in an outer context, for instance in a
FlowSheet. Because of this, parameters declared with the
outer prefix are known as outer parameters, while parameters
without the prefix are known as concrete parameters.
The purpose of outer parameters is to share the value of a parameter between several Devices of a FlowSheet. Note that the
value of an outer parameter comes from a parameter with same
name but declared in some outer context. When the source of an
outer parameter is a FlowSheet its value is specified only in
the FlowSheet and then all models can use that value directly.
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 manner very close to parameters. The VARIABLES identifier 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 should already note that the declaration of types, variables 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 deriving from the built-in ones or predeclared Models.
Inputs and Outputs
When declaring variables, the prefixes in and out can be used,
see line 6 of Code 3.2.

26

3 EMSO Modeling Language


Variables declared with the out prefix are called output variables,
while that declared with the in prefix 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 variables.
An output variable works exactly as an usual variable, but is available 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
connection, with the intent of reduce the size of the resulting system 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, parameters 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 exemplified in line 4
of the code below:
1
2
3
4

VARIABLES
controller as PID;
SET
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 Model
3.2.4

27

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 between 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 useless, 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
preciously declared variables, parameters, operators, built-in functions 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.9.
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 comments,
such texts are recognized as units of measurement (UOM) constants and effectively are part of the expression. In such example
the UOMs are required to assure units dimension correctness, because the ln function expects a UOM dimensionless argument.
The UOM of a variable or parameter comes from its type or
declaration, for example:
temperature as Real(final Unit=K, Lower = 100,
Upper = 5000);
pressure as Real(final Unit=atm, Lower = 1e-6,
Upper = 1000);
VARIABLES
T1 as temperature;
T2 as Real(Unit = K);
P1 as pressure;
P2 as pressure(Unit = kPa); # error because
Unit was declared as final in pressure
P2 as pressure(DisplayUnit = kPa);

28

3 EMSO Modeling Language


An attribute of a type can be fixed with the final prefix. A final
attribute cannot be changed when deriving from it. In the above
code, the declaration of variable P2 contains an error because the
Unit attribute of pressure is final and cannot be changed.
Declaring Unit attributes as final is important because the
limits (Lower and Upper) are considered to be in the same
UOM as Unit. But making a Unit to be final still leaves
to the user the option to change the UOM to be displayed in results. This can be achieved setting the DisplayUnit attribute
accordingly.

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 identifier, 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 rectangular or abstract Model, because specifications, 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
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.

3.3 FlowSheet

29
Code 3.3: Syntax for writing FlowSheets.
1
2
3

FlowSheet name [as base]


DEVICES
name [as base[( (attribute = value)+ )] ];
CONNECTIONS
name to name;

5
6

SPECIFY
name = expression;

8
9

OPTIONS
name = value;

11
12
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 prefix is allowed.
Note: There is no sense in using the in or out prefix 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;

3.3.2

Connections
In subsection 3.2.2 was described how to declare an input or output variable. However, was not specified how to connect an output 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 connected to an input.

30

3 EMSO Modeling Language


It is stressed that the values of an input variable are only references 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

Specifications
In subsection 3.2.6 the term abstract model was defined, basically
it means models with missing equations. Most useful models
are abstract, because of their flexibility. This flexibility comes
from the possibility of specify or connect the models in several
different fashions.
In order to simulate a FlowSheet it must have the number of
variables equal number of equations. FlowSheets using abstract Models requires specifications for variables in the form
presented in line 9 of Code 3.3. In a specification expression
can be any expression valid for an equation (see subsection 3.2.4)
and name is the name or path name of the specified 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
TimeStart = 1;
TimeStep = 0.1;
TimeEnd = 10;
TimeUnit = h;
DAESolver( File = "dasslc");

In Table 3.2 all available options are listed.

3.4

Optimization
Optimization differ from simulation in several aspects. In simulation problems the solvers will try to find the solution. In optimization problems the solvers try to find the best solution with

3.4 Optimization

31

Table 3.2: FlowSheet options, default value in bold.


Option name
TimeStart
TimeStep
TimeEnd
Dynamic
Integration
RelativeAccuracy
AbsoluteAccuracy
EventVarAccuracy
SparseAlgebra
InitialFile
GuessFile
NLASolver

DAESolver

Type
real
real
real
boolean
text
real
real
real
boolean
text
text
text

text

Description
The reporting integration time start: 0;
The reporting integration time step: 10;
The reporting integration time end: 100;
Execute dynamic or static simulation: true or false;
The system to be used in integration: "original",
"index1" or "index0";
The relative accuracy: 1e-3;
The absolute accuracy: 1e-6;
The independent variable accuracy when detecting state
events: 1e-2;
To use sparse linear algebra or dense: true or false;
Load the initial condition from result file
Load the an initial guess from result file
The NLA solver library file name to be used:
"sundials", "nlasolver", or the name the file
of some solver developed by the user as described in
chapter 9;
The DAE solver library file name to be used:
"dasslc", "sundials", "dassl", "mebdf", or
the name the file of some solver developed by the user
as described in chapter 9;

32

3 EMSO Modeling Language


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 Optimization.
1
2
3
4

Optimization name [as base]


MINIMIZE
expression1;
expression2;
MAXIMIZE
expression3;
expression4;

6
7
8

EQUATIONS
expression5 < expression6;
expression7 > expression8;

10
11
12

FREE
variable1;
variable2;

14
15
16
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
Dynamic = false;
end

3.4 Optimization

33
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 optimization problem. The same approach can be used to describe largescale problems but this form is barely convenient.
As a convenience for the user, EMSO supports the directly optimization 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 want to find the recycle fraction
which yields to the minimun lost of product on the purge. For
this case the following code could be used:
Optimization AmmoniaOptimization as Ammonia
MINIMIZE
productLoose;
FREE
Splitter102.fraction;
OPTIONS
Dynamic = false;
end

Warning: In order to optimize FlowSheets make sure that the


FlowSheet can run (it should be consistent and the simulation
should succeed).
3.4.3

Mixed Integer Optimization


EMSO can handle mixed-integer non-linear optimization. In the
case where integer variables are present, and a minlp otimization
solver are choosed, EMSO will start automatically a minlp optimization. Integer variables has no units and the problem will fail
if a unit is set. The algorithm used, Bonmin, can handle continuous, integer and binary variables. If an integer variable has it

34

3 EMSO Modeling Language


lower bound equal to 0 and upper bound equal to 1, it will be
treated internally by the algorithm as a binary variable. In the case
where integer variables are present and a mixed-integer solver is
not choosed, or, in the case where the optimization problem has
only continuos variables and a minlp solver was choosed, EMSO
will report an error.
Below follows a simple minlp problem included in the library.
Optimization minlp1
VARIABLES
x0 as Integer(Default=0, Lower=0, Upper=1);
x1 as Real(Default=0, Lower=0, Upper=1.0e10);
x2 as Real(Default=0, Lower=0, Upper=1.0e10);
x3 as Integer(Default=0, Lower=0, Upper=5);
MINIMIZE
-1*(x0 + x1 + x2);
EQUATIONS
#-1 *((x1 - 0.5)2 + (x2 - 0.5)2 - 0.25) <=
0;
#-1*(x0 - x1) <= 0;
#-1*(x0 + x2 + x3 -2) <= 0;
(x1 - 0.5)2 + (x2 - 0.5)2 <= 0.25;
x0 - x1 <= 0;
x0 + x2 + x3 <= 2;
OPTIONS
Dynamic = false;
NLPSolver(File = "minlp_emso",
print_level = 5);
end

3.4.4

Options
In subsection 3.3.4 all options supported by FlowSheets were
presented. Optimization problems support additional options as
listed in Table 3.3.

3.4.5

Dynamic Optimization
Under construction: As of this time, EMSO only supports static
optimization, dynamic optimization will be available soon.

3.5 Parameter Estimation

35

Table 3.3: Optimization options, default value in bold.


Option name
Type
NLPSolveNLA boolean
NLPSolver

3.5

Description
Flag if the simulation solution should be used as start
value for the optimization problem: true or false;
The file name of the NLP solver library:
"ipopt emso", or the name the file of some
solver developed by the user as described in chapter 9;

text

Parameter Estimation
EMSO can be used to solve steady state and dynamic parameter
estimation problems using already running FlowSheets.1 In order to create a new environment for parameter estimation problem
writing, the user should inform the name of the new environment
and the name of the base FlowSheet. This should be done
by using the keyword Estimation, as presented in Code 3.5,
which uses the same code conventions explained in section 3.2.
Code 3.5: Syntax for writing Estimation.
1
2
3
4

Estimation name as base


ESTIMATE
# PARAMETER START LOWER UPPER UNIT
parameter
1.0
0.001 0.100 Unit;
EXPERIMENTS
# DATA FILE
WEIGTH
"data file one" [weight]
"data file two" [weight]

6
7
8
9

OPTIONS

11
12

TYPE
"fit";
"test";

end

Warning: Before running a estimation problem, it must be assured that the base FlowSheet can run (it should be consistent
and the simulation should succeed).
Into the Estimation environment, the parameter estimation
problem can be written using the commands presented in Code 3.5.
It is important to remark that only this specific commands showed
in Code 3.5 can be used for writing a parameter problem. The
other way round Optimization, the user can not use other
1

The parameter estimation section of this manual was written by Eng. Msc.
Tiago Fiorenzano Finkler.

36

3 EMSO Modeling Language


commands of FlowSheet and Model bodies. It follows below
the details of the sections of this code and its specific commands.

It is not necessary to provide


measures of all variables of the
base FlowSheet.

As for specification variables the


deviations will always be zero, the
deviations are presented only for
variables that are not specified in
the FlowSheet.

3.5.1

The user will have to provide a set of measurements for the variables of the base FlowSheet and inform what parameters of the
base FlowSheet should be estimated. After properly written, a
parameter estimation problem is solved exactly as FlowSheets,
with the run button. So, by using the weighted least squares
criterion, EMSO will seek a set of new values for the measured
variables which minimizes the differences between the model predictions and the measurements of the variables.
When the problem is being solved, relevant information is reported in the Console window. The final results are reported
in the Results window. In addition to the results that are
reported when solving FlowSheets, the following informations
regarding the parameter estimation problem are provided: the
measurements of the variables, the absolute deviation between
the model predictions and the measurements, the relative deviation between the model predictions and the measurements, and
the standardized deviation between the model predictions and the
measurements.

Experiments
In the experiment section, the names of the data files containing
measures of base FlowSheet variables must be informed as
showed in Code 3.5. The name of the data file should informed
as a string and the file should be in the same folder of the .mso
file of the parameter estimation problem that is being solved. The
data files are expected to be text files with the following structure:
MEASURE
VARIANCE
DATA

variable1
value
value
value
value
value

variable2
value
value
value
value
value

After the keyword MEASURE, the name of the measured variables


should be informed. Any variable of the base FlowSheet can
be entered and the name of the variable is exactly the same as
it is in the base FlowSheet. In dynamic problems, the first
variable must always be time. After the keyword VARIANCE,
the value of the variance of the measurements of each one of
the previously informed measured variables should be informed.
Finally, after the keyword DATA, the values of the measurements
of the measured variables must be informed.

3.5 Parameter Estimation

37
As it can be seen in Code 3.5, the user may use multiple data files
containing measures of base FlowSheet variables. If it is the
case, two optional informations can be provided. The first is a
weight which should be a real number between 0 and 1 that can
be freely used to value or to devalue the particular experiments.
The second is the type of the experiment which can be equal
to fit or test. Experiments marked with the fit flag are
took into account for estimate the parameters while experiments
marked with the test flag are reserved for model validation.
More details about using experiments marked with the test
flag are provided in subsection 3.5.3.
Warning: When more than one experiment is informed at the
experiment section, it must be assured that all experiments have
exactly the same set of measured variables.

3.5.2

Estimate
In the estimate section, the parameters to be estimated must be
informed as showed in Code 3.5. EMSO will vary this parameters
until it finds a solution which minimizes the differences between
the model predictions and the fit data.

3.5.3

Options

The user is referred to


subsection 3.3.4 in order to get
more details about the options
supported by Optimization.

Internally, EMSO treats a parameter estimation problem as a


optimization problem with a predefined objective function. So,
the options supported into the Optimization environment are
also supported into the Estimation environment. Additionally,
the options RunTests, Statistics, Significance, and
BiLateral are also supported. Details about how to use each
one of this options are given in the following.
Note: Inside the Estimation environment, the Dynamic option must always be equal to the Dynamic option of the base
FlowSheet.

RunTests

More details about marking


experiments with the test flag
can be found in subsection 3.5.1.

The RunTests option allows the user to choose if EMSO should


run simulations using the experiments marked with the test flag.
The syntax for using this option is showed in Code 3.6, in which
RunTests must be set as true or false. When RunTests
is set as true, the measurements of the variables, the absolute deviation between the model predictions and the measurements, the relative deviation between the model predictions and

38

3 EMSO Modeling Language


the measurements, and the standardized deviation between the
model predictions and the measurements which are reported in
the Results window will refer to the test data. Otherwise they
will refer to the fit data.
Code 3.6: Syntax for using RunTests
RunTests = false;

Warning: By default the RunTests option is set as false.


So, in order to obtain the reports regarding the test data, the user
must certify that this option is set as true.
Statistics
EMSO can compute the following statistics which may help the
user to evaluate the quality of the achieved results: explained variability of each fit variables, significance of fit for each fit variable,
significance of each estimated parameter, confidence interval of
each estimated parameter, parameter correlation matrix, parameter covariance matrix, and predictions errors covariances matrix.
The user can decide which of those tests will be performed by
using the Statistics option. The syntax for using this option
is showed in Code 3.7. When using this code, the user can decide
which of the tests will be performed by setting the respective
boolean values as true or false. The results of all tests
are reported at the Console window.
Code 3.7: Syntax for using Statistics
Statistics([Fit=true], [Parameter=true], [
Prediction=true]);

Significance
The statistical tests presented before are performed considering a
specific significance level. By default, the significance level is set
as 0.95, but the user can change it using the Significance
option. The syntax for using this option is showed in Code 3.8.
When using this code, the user can change the significance level
by setting it as any real number between 0 and 1.
Code 3.8: Syntax for using Significance
Significance = value;

3.6 Data Reconciliation

39

BiLateral
This is an specific option for the significance of the estimated
parameter computation. By default, this statistic is computed
using a unilateral test, which is a conservative one. But this
statistic can also be computed using a bilateral test. This can
be done by changing thee BiLateral option. The syntax for
using this option is showed in Code 3.9. When using this code,
the user can set the BiLateral as true or false.
Code 3.9: Syntax for using BiLateral
BiLateral = true;

3.6

Data Reconciliation
Data reconciliation is a technique that was developed to improve
the accuracy of process measurements by reducing the effect of
random errors in the data. Basically, data reconciliation consists on adjusting variables measurements in such a way that the
obtained adjusted values obey some known process constrains,
which are described by the process model.
EMSO can be used to solve steady state data reconciliation problems using already running FlowSheets.2 In order to create a
new environment for data reconciliation problem writing, the user
should inform the name of the new environment and the name of
the base FlowSheet. This should be done by using the keyword
Reconciliation, as presented in Code 3.10, which uses the
same code conventions explained in section 3.2.
Code 3.10: Syntax for writing Reconciliation.
1
2
3

Reconciliation name as base


RECONCILE
variable1; variable2;
FREE
variable1; variable2;

5
6

EXPERIMENTS
"data file one" [weight];
"data file two" [weight];

8
9
10

OPTIONS

12
13

end
2

The data reconciliation section of this manual was written by Eng. Msc.
Tiago Fiorenzano Finkler.

40

3 EMSO Modeling Language


Into the Reconciliation environment, the data reconciliation problem can be written using the commands presented in
Code 3.10. It is important to remark that only this specific commands showed in Code 3.10 can be used for writing a data reconciliation problem. The other way round Optimization, the
user can not use other commands of FlowSheet and Model
bodies. It follows below the details of the sections of this code
and its specific commands.
The user will have to provide a set of steady state measurements
for the variables of the base FlowSheet that should be reconciled and inform what variables of the base FlowSheet should
be set free to solve the problem. After properly written, a data
reconciliation problem is solved exactly as FlowSheets, with
the run button. So, by using an appropriate objective function,
EMSO will seek a set of adjusted values for the measured variables provided that this adjusted values respect the process model
constrains.

when replicates of the


measurements are available, a
filtered value is considered. More
details about it are showed in
subsection 3.6.1

When the problem is being solved, relevant information is reported


in the Console window. The final results are reported in the
Results window. In addition to the results that are reported
when solving FlowSheets, the following informations regarding
the reconciled variables are provided: final reconciled values; original measurements which were reconciled; absolute, relative and
standardized deviations of the reconciled values with respect to
the original measurements; and the result of a gross error detection test.
Warning: Before running a reconciliation problem, it must be assured that the base FlowSheet can run (it should be consistent
and the simulation should succeed).

3.6.1

Experiments
In the experiment section, the names of the data files containing the measures to reconciled must be informed as showed in
Code 3.10. The name of the data file should informed as a string
and the file should be in the same folder of the .mso file of the
data reconciliation problem that is being solved. The data files
are expected to be text files with the following structure:
MEASURE
VARIANCE
DATA

variable1
value
value

variable2
value
value

After the keyword MEASURE, the name of the measured variables


should be informed. Any variable of the base FlowSheet can

3.6 Data Reconciliation

41
be entered and the name of the variable is exactly the same as
it is in the base FlowSheet. After the keyword VARIANCE,
the value of the variance of the measurements of each one of
the previously informed measured variables should be informed.
Finally, after the keyword DATA, the values of the steady state
measurements of the measured variables must be informed.
Measurements replicates can be informed as additional entries after the keyword DATA. When replications are informed, the reconciliation problem take into account some representative value
of the informed measures for each variable. By default, this representative value is the arithmetic mean. But it can be set as the
median by using the Filter option, as it will be showed further in
subsection 3.6.4.
Another way of taking replicates of the measurements into account is informing them as additional experiments. Using the
format showed in Code 3.10, it can be informed as many experiments the user wants. When multiple experiments are informed,
a weight which should be a real number between 0 and 1 that
can be freely used to value or to devalue the particular data files.
Note: The weight of a experiment is took into account in the
computation of the filtered value for each measure. Actually it is
only considered when the chosen filtered measure is the weighted
arithmetic mean. When the filtered measure is chosen as the
median it is not considered. See subsection 3.6.4 for details about
choosing the Filter option.)

Warning: When more than one experiment is informed at the


experiment section, it must be assured that all experiments have
exactly the same set of measured variables.

3.6.2

Reconcile
In the reconcile section, the variables to be reconciled must be
informed as showed in Code 3.10. Any of the variables informed
at the experiment section can be reconciled.
EMSO will use the variables entered in the reconcile section to
compute the objective function of the data reconciliation problem.
By default, the weighted least squares criterion is used. Another
objective functions can be used by changing the ObjectiveFunction option, as it will be explained further in subsection 3.6.4.

42

3 EMSO Modeling Language

3.6.3

Free
In this section, the degrees of freedom of the data reconciliation
problem, which are also variables of the base FlowSheet, should
be informed. The variables chosen as degrees of freedom must
be specifications in the base FlowSheet that can be measured
or not.

Considering the set of


measurements and the model
which are available, a variable is
said to be redundant if its value
can be computed even if it was not
measured.

3.6.4

An important restriction about the variables chosen as degrees of


freedom is that they must be redundant ones. In order to provide this information to the user, EMSO performs a redundancy
analysis of the system variables just before start running a data
reconciliation problem. If any of the variables informed at the
free section is not redundant, an error message is sent to the
Console window to indicate the problem.

Options

The user is referred to


subsection 3.3.4 in order to get
more details about the options
supported by Optimization.

Internally, EMSO treats a data reconciliation problem as a optimization problem with a predefined objective function. So, the
options supported into the Optimization environment are also
supported into the Reconciliation environment. Additionally, the options Filter, GrossErrorTests, Significance,
and ObjectiveFunction are also supported. Details about
how to use each one of this options are given in the following.
Note: The Dynamic option must always be set as false in order
to run data reconciliation problems.

Filter

More details about informing


measurements replicates can be
found at subsection 3.6.1

The Filter option allows the user to choose how EMSO will
deal with measurements replicates. The user can decide if the
representative values of the measurements of each variable will
be computed as the weighted arithmetic mean or as the median
of the individual measurements. The syntax for using this option
is showed in Code 3.11, in which Filter must be set as mean
or median.
Code 3.11: Syntax for using Filter
Filter = "mean";

GrossErrorTest
In order for data reconciliation to be effective, it is important to
assure that only random errors are present in the measurements.

3.6 Data Reconciliation

43
The presence of gross errors caused by nonrandom events such
as instrument malfunctioning, miscalibration, wear corrosion of
sensors, or solid deposits, can highly damage the adjustments
evaluation. For this reason, it is important to check reconciliation results using statistical tests for gross error detection. When
a gross error is detected, the necessary actions to eliminate it
must be taken, e.g. instrument recalibration, and measurements
free from gross errors should be provided in order to the data
reconciliation problem be properly solved.
EMSO provides three statistical tests for gross error detection:
the global test, the nodal test and the measurement test. The
global test is applied over the objective function value and only
indicates if the probability of a gross error exists between the considered measurements can be neglected or not. The nodal test
is applied over each one of the model equations and indicates if
the probability of a gross error exists between the measured variables of the respective equations can be neglected or not. Finally,
the measurements test is applied over each one of the reconciled
variables and indicates directly if the probability of a gross error
exists in every particular measurement can be neglected or not.
The user can decide which of those tests will be performed by
using the GrossErrorTests option. The syntax for using
this option is showed in Code 3.12. When using this code, the
user can decide which of the tests will be performed by setting the
respective boolean values as true or false. The results of
all tests are reported at the Console window. Additionally, the
results of the measurement test are also reported at the Results
window.
Code 3.12: Syntax for using GrossErrorTests
GrossErrorTests([Global=true], [Nodal=true], [
Measurements=true]);

Significance
The statistical tests presented before are performed considering a
specific significance level. By default, the significance level is set
as 0.95, but the user can change it using the Significance
option. The syntax for using this option is showed in Code 3.13.
When using this code, the user can change the significance level
by setting it as any real number between 0 and 1.
Code 3.13: Syntax for using Significance
Significance = value;

44

3 EMSO Modeling Language

ObjectiveFunction
As it was mentioned in subsection 3.6.2, by default, EMSO uses
the weighted least squares criterion to build the objective function
of the data reconciliation problem. The weight least squares criterion results from the assumption that the random measurement
errors follow a normal distribution around the true measurement
value to be estimated. This is generally a good hypothesis which
can be assumed in most of cases.
However, as this criterion states a quadratic dependence between
the measurements adjustments and its individual contributions to
the objective function, measurements with gross errors will tend
to have a high influence on the overall least squares value. In the
final solution it will inevitably be compensated by changing the
adjustments of other measured variables. This means that the
least squares criterion is highly prone to gross error propagation.
In order to minimize this ill effect, EMSO provides a set of alternative objective functions to solve data reconciliation problems
which are based on different assumptions about the way the errors are distributed around the true measurement value to be
estimated. All those different objective functions exhibit almost
the same behavior that the least squares function in a certain
range around the central point but, outside this range, they stop
growing quadratically as error increases, which results in much
smaller contributions when the error is large. This feature may
help to reduce the gross error propagation effect.
The user can choose the between the different objective functions
provided by EMSO by changing the ObjetctiveFunction
option. The syntax for using this option is showed in Code 3.14, in
which ObjectiveFunction must be set as: Normal, ContaminatedNormal, Cauchy, Logistic, Lorenzian, Fair,
or Hampel.
Code 3.14: Syntax for using ObjectiveFunction
ObjectiveFunction = "Normal";

Note: Although using the available alternative objective functions may considerably reduce the gross error propagation effect,
it can not eliminate it. In fact, as the objective functions grows
monotonically as the error modulus increases, measurements with
higher errors will still show important contributions to the final
objective function value. So, gross errors must be properly identified and eliminated, no matter what objective function is being
used.

3.7 Case Study

3.7

45

Case Study
Case study is a research technique aimed to study the response
variables, disturbing some decision or manipulated variables.
EMSO can be used to solve case study problems in steady state
and dynamic models using already running FlowSheets.3 In
order to create a new environment for case study problem writing,
the user should inform the name of the new environment and the
name of the base FlowSheet. This should be done by using
the keyword CaseStudy, as presented in Code 3.15, which uses
the same code conventions explained in section 3.2.
Code 3.15: Syntax for writing CaseStudy.
1
2
3
4

CaseStudy name as base


VARY
variable1 = [value1 : var : value2] * unit;
variable2 = [value1, value2, value3] * unit;
RESPONSE
variable3 unit;
variable4 unit;

6
7
8
9

end

Inside the CaseStudy environment, the problem can be written


using the commands presented in Code 3.15. It is important to
remark that only this specific commands showed in Code 3.15
can be used for writing a case study problem. The user can
not use other commands of FlowSheet and Model bodies.
It follows below the details of the sections of this code and its
specific commands.
The user will have to provide a set, or a range, of measurements for the specifications, or parameters, (in CaseStudy they
are called VARY variables) of the base FlowSheet that should
be varied, or disturbed, and inform what variables of the base
FlowSheet will be the response of the problem. After properly
written, a case study problem is solved exactly as FlowSheets,
with the run button. So, EMSO will obtain a set of response
values for each possible combination of all of vary variables provided.
Warning: Before running a case study problem, it must be assured that the base FlowSheet can run (it should be consistent
and the simulation should succeed).
3

The case study section of this manual was written by Eng. Marcos Vincius
Almeida Narciso.

46

3 EMSO Modeling Language


Case the FlowSheet is dynamic type, all points in the time
interval will be computed and exhibited in Results tab.
Tip: In dynamic flowsheets, small step size or large intervals of
time can result in a lot of results to be exhibited. If it is possible,
adjust the time interval in FlowSheet to reduce number of
results.

3.7.1

Vary
In the VARY section, the variables to be varied must be informed
as showed in Code 3.15. All of the variables informed at this section will be combined in grid format. In a dynamic FlowSheet,
all points in time range are computed.
The VARY variable can have its unit of measure declared or not,
if it is not informed, the SI standard unit of measure is used.
EMSO will use the variables entered in the VARY section to compute the response variables of the case study problem. By default,
EMSO will make a combination with all elements of each variable,
simulating each one.

3.7.2

Response
In the response section, the response variables must be informed
as showed in Code 3.15. All of the variables informed at this section will be calculated by EMSO and they are showed in Results
tab.
As explained in 3.7.1, the VARY variable can have its unit of
measure declared or not, if it is not informed, the SI standard
unit of measure is used.
Warning: In RESPONSE section, the * symbol can not be
informed in unit declaration.

3.7.3

Results
If the flowsheet converged, an OK symbol will be displayed in
the cell corresponding to the response, in the case that the flowsheet did not converged, the result will not be displayed. In the
case of success, in the Results tab, the CaseStudy results
will be exhibited in a table. As showed in Figure 3.1, variables,
with its unit, will be disposed in lines, and the time will be disposed in columns.

3.7 Case Study

47

Figure 3.1: Case Study Results Window.


As showed in Figure 3.2, yellow lines represent RESPONSE variables and white lines represent VARY variables. If a steady-state
FlowSheet is the base of CaseStudy structure, the time
value exhibited in table is 0*s (default value of time variable in
EMSO). In a dynamic FlowSheet all time value is exhibited in
table, respecting the order of values in grid combination.
It is possible save the case study results in a file, it can be saved
in EMSO by left clicking in save button in Results tab. The
user can save in EMSO result file format (.rlt) or Microsoft
c 2003 XML format (.xml). In this file, only chooses
Office
variables present in CaseStudy will be written.

Figure 3.2: Case Study Results Table.

48

3.8

3 EMSO Modeling Language

Sensitivity Analysis
Sensitivity analysis, is similar as CaseStudy, it reports how the
variation of a disturb affects a response variable. The main difference is that this response is a derivative of a response variable
in respect to a input or disturb variable:
y
x

Sensitivity analysis can evaluate how the effect of uncertainty in


the output of a model can be observed, qualitatively or quantitatively, in different sources of variation in the input of a model. In
other words, the sensitivity analysis investigates the robustness of
a process model, analysing what variable have a bigger weight in
uncertainty of models results.
EMSO can be used to do sensitivity analysis in steady state and
dynamic models using already running FlowSheets.4 In order
to create a new environment for sensitivity analysis writing, the
user should inform the name of the new environment and the
name of the base FlowSheet. This should be done by using
the keyword Sensitivity, as presented in Code 3.16, which
uses the same code conventions explained in section 3.2.
Code 3.16: Syntax for writing Sensitivity.
1
2
3
4

Sensitivity name as base


VARY
variable1 unit;
variable2 unit;
RESPONSE
variable3 unit;
variable4 unit;

6
7
8
9

end

Into the Sensitivity environment, the sensitivity analysis can


be written using the commands presented in Code 3.16. It is
important to remark that only this specific commands showed
in Code 3.16 can be used for writing a sensitivity analysis. The
user can not use other commands of FlowSheet and Model
bodies. It follows below the details of the sections of this code
and its specific commands.
The user will have to provide a list of specifications, or parameters,
(in Sensitivity they are called VARY variables) of the base
FlowSheet that should be analysed and inform what variables
of the base FlowSheet will be the response of the problem.
These response variables can not be specifications or parameters.
4

The sensitivity analysis section of this manual was written by Eng. Marcos
Vincius Almeida Narciso.

3.8 Sensitivity Analysis

49
After properly written, a sensitivity analysis is solved exactly as
FlowSheets, with the run button. So, EMSO will transform
the Jacobian matrix of model (matrix with all derivatives equations related with all variables present in model) to obtain a Sensitivity matrix of Model between VARY and RESPONSE variables.

50

3 EMSO Modeling Language

Warning: Before running a sensitivity analysis, it must be assured


that the base FlowSheet can run (it should be consistent and
the simulation should succeed).
EMSO calculates the steady-state sensitivity according to the formula referenced by Shengtai and Petzold (2000) 5 , while the dynamic sensitivity was implemented based in the journal article by
Cao, Shengtai and Petzold 6
in the dynamic FlowSheet, only the last time point of each variable will be used to calculate the Sensitivity matrix and exhibited
in Results tab.
3.8.1

Vary
In the VARY section, the input variables must be informed as
showed in Code 3.16. All of the variables informed at this section
will be combined with the variables of RESPONSE section. These
variables can be specifications or parameters.
The VARY variable can have its unit of measure declared or not,
if it is not informed, the SI standard unit of measure is used.
EMSO will use the variables entered in the RESPONSE section
to compute the Jacobian matrix related with VARY variables of
the sensitivity analysis.

3.8.2

Response
In the response section, the response variables must be informed
as showed in Code 3.16. All of the variables informed at this section will be calculated by EMSO and they are showed in Results
tab. These variables can not be specifications or parameters.
As explained in 3.8.1, the RESPONSE variable can have its unit
of measure declared or not, if it is not informed, the SI standard
unit of measure is used.
Warning: In RESPONSE section, the * symbol can not be
informed in unit declaration.
5

Shengtai Li, Linda Petzold - Software and algorithms for sensitivity analysis of large-scale differential algebraic systems, Journal of Computational
and Applied Mathematics, 125 (2000) 131145
6
Yang Cao, Shengtai Li, Linda Petzold, Adjoint sensitivity analysis for
differential-algebraic equations: algorithms and software, Journal of Computational and Applied Mathematics 149 (2002) 171 191

3.8 Sensitivity Analysis


3.8.3

51

Results
If the flowsheet converged, an OK symbol will be displayed
in the cell corresponding to the response, in the case that the
flowsheet did not converged, the result will not be displayed. In
the case of success, in the Results tab, the CaseStudy results will be exhibited in a table. As showed in Figure 3.3, the
VARY variables, with your unit, will be disposed in lines, and the
RESPONSE variables, with your unit, will be disposed in columns.

Figure 3.3: Sensitivity Analysis Results Window.

52

3 EMSO Modeling Language


It is possible save the sensitivity analysis results in a file, it can
be saved in EMSO by left clicking in save button in Results
tab. The user can save in EMSO result file format (.rlt) or
c 2003 XML format (.xml). In this file, only
Microsoft Office
variables present in FlowSheet will be written.

Figure 3.4: Sensitivity Analysis Results Table.

3.9 Built-in Functions

3.9

53

Built-in Functions
In this section the built-in functions supported by the EMSO are
listed. There are two categories of functions:
Element-by-element: if the argument of the function is a
vector or matrix, the function is applied in the same way to
all elements of the argument. The returned value of these
functions always have the same dimensions of its argument;
Matrix transformation: The functions in this category
make sense only for vector and matrix arguments. The
return value can be a scalar, vector, or matrix depending
on the function and the argument.
Examples of use of the functions are available in the folder
<EMSO>/mso/sample/miscellaneous.

Table 3.4: Element-by-Element functions.


Function
diff(Z)
exp(Z)
log(Z)
ln(Z)
sqrt(Z)
Trigonometric
sin(Z)
cos(Z)
tan(Z)
asin(Z)
acos(Z)
atan(Z)
Hyperbolic
sinh(Z)
cosh(Z)
tanh(Z)
coth(Z)
Discontinuous
abs(Z)
max(Z)
min(Z)
sign(Z)
round(Z)

Meaning
Returns the
Returns the
Returns the
Returns the
Returns the

derivative of Z with respect to time


exponential function, e raised to the power Z
base 10 logarithm of Z
natural logarithm (base e) of Z
square root of Z

Returns
Returns
Returns
Returns
Returns
Returns

the
the
the
the
the
the

sine of Z
cosine of Z
tangent of Z
angle whose sine is Z
angle whose cosine is Z
angle whose tangent is Z

Returns
Returns
Returns
Returns

the
the
the
the

hyperbolic
hyperbolic
hyperbolic
hyperbolic

Returns
Returns
Returns
Returns
Returns

the
the
the
the
the

magnitude or absolute value of Z


maximum value of Z
minimum value of Z
signal of Z (-1 if Z < 0 e 1 if Z> 0
small integer value of Z

sine of Z
cosine of Z
tangent of Z
cotangent of Z

54

3 EMSO Modeling Language

Table 3.5: Matrix Transformation Functions.


Function
Sum
sum(VEC)
sum(MAT)
sumt(MAT)
Product
prod(VEC)
prod(MAT)
prodt(MAT)
Transpose
transp(MAT)

3.10

Meaning
Returns a scalar with the sum of all elements of the vector VEC
Returns a vector with the sum of each column of the matrix MAT
Returns a vector with the sum of each row of the matrix MAT
Returns a scalar with the product of all elements of the vector
VEC
Returns a vector with the product of each column of the matrix
MAT
Returns a vector with the product of each row of the matrix MAT
Returns the transpose of a matrix MAT

Units Of Measurement (UOM)


The units of measurement recognized by the EMSO modeling
language are listed below.

3.10.1

Fundamental Units
m
kg
s
K
A
mol
cd
rad
US$

3.10.2

length in meters
mass in kilogram
time in seconds
temperature in Kelvin
eletric current in Ampere
the amount of substance in mole
the luminous intensity in Candela
angle measure in radian
money in dollar (USA)

Derived Units
Acceleration of Gravity
ga
9.80665*m/s2
Angle
arcs
4.8481368111e-6*rad
arcmin 2.90888208666e-4*rad
grad
1.57079632679e-2*rad
deg
1.74532925199e-2*rad

std acceleration of gravity


arcsecond
arcminute
grad
degree

3.10 Units Of Measurement (UOM)


Area
acre
a
ha
b
Eletric
Wb
T
S
mho
Fdy
F
ohm
C
V
Energy
J
kJ
MJ
GJ
eV
MeV
therm
Btu
cal
kcal
erg
Force
N
pdl
lbf
kip
gf
kgf
dyn
Length
cm
mm
fermi

55

4046.87260987*m2
100*m2
10000*m2
1e-28*m2

acre
are
hectare
barn

kg*m2 /A/s2
kg/A/s2
A2 *s3 /kg/m2
A2 *s3 /kg/m2
96487*A*s
A2 *s4 /kg/m2
kg*m2 /A2 /s3
A*s
kg*m2 /A/s3

weber
tesla
siemens
mho
faraday
farad
ohm
relative current for batteries
volt

kg*m2 /s2
1e3*J
1e6*J
1e9*J
1.60217733e-19*J
1e6*eV
105506000*J
1055.05585262*J
4.1868*J
1e3*cal
1e-7*J

joule
kilojoule
megajoule
gigajoule
electronvolt
megaelectronvolt
therm
British thermal unit
calorie
kilo calorie
erg

kg*m/s2
0.138254954376*N
4.44822161526*N
4448.22161526*N
0.00980665*N
1e3*gf
0.00001*N

newton
poundal
pounds of force
kip
gram force
kilogram force
dyne

1e-2*m
0.1*cm
1e-15*m
1e-10*m
1e-6*m

centimeter
millimeter
fermi
angstrom
micro

56

3 EMSO Modeling Language


mil
ftUS
fath
rd
chain
miUS
nmi
mi
km
au
lyr
pc
Mpc
in
ft
yd
Mass
u
grain
ct
ozt
t
tonUK
ton
lbt
slug
oz
lb
g
kmol
lbmol
Money
R$
Power
W
kW
MW
hp
Pressure
Pa
kPa

2.54e-5*m
0.304800609601*m
1.82880365761*m
5.02921005842*m
20.1168402337*m
1609.34721869*m
1852*m
1609.344*m
1000*m
1.495979e11*m
9.46052840488e15*m
3.08567818585e16*m
3.08567818585e22*m
0.0254*m
0.3048*m
0.9144*m

mil
international foot
fathom
rod
chain
US statute miles
nautical mile
International Mile
Kilometer
Astronomical Unit
light year
parsec
megaparsec
inch
foot
yard

1.6605402e-27*kg
0.00006479891*kg
0.0002*kg
0.0311034768*kg
1000*kg
1016.0469088*kg
907.18474*kg
0.3732417216*kg
14.5939029372*kg
0.028349523125*kg
0.45359237*kg
kg/1000
1e3*mol
453.59237*mol

atomic mass unit


grain
carat
troy ounce
tonne
ton (UK)
ton
troy pound
slug
ounce
pound
gram
kilomole
pound mole

US$/3.05

Brazilian money (Real)

kg m2 /s3
1e3*W
1e6*W
745.699871582*W

watt
Kilowatt
megawatt
horsepower

kg/m/s2 pascal
1e3*Pa

Kilopascal

3.10 Units Of Measurement (UOM)


MPa
inH2O
inHg
mmHg
torr
psi
bar
atm
Radiation
R
Ci
Bq
Sv
rem
Gy
Temperature
degR
Time
Hz
min
rpm
h
d
yr
Velocity
c
knot
mph
kph
Viscosity
St
P
cP
Volume
st
fbm
pk
bu
bbl
trp
tbsp

57
1e3*kPa
248.84*Pa
3386.38815789*Pa
133.322368421*Pa
133.322368421*Pa
6894.75729317*Pa
1e5*Pa
101325*Pa

megapascal
inch of water column
inch of mercury
millimeter of mercury
torr
pound per square inch
bar
atmosphere

0.000258*A*s/kg
3.7e10/s
1/s
m2 /s2
0.01*m2 /s2
m2 /s2

R
curie
becquerel
sievert
rem
gray

K/1.8

degree Rankine

1/s
60*s
1/min
60*min
24*h
31556925.9744*s

hertz
minute
revolution per minute
hour
day
year

299792458*m/s
0.514444444444*m/s
0.44704*m/s
0.277777777778*m/s

light speed
knot
mile per hour
kilometer per hour

0.0001*m2 /s
0.1*kg/m/s
0.001*kg/m/s

stoke
poise
centipoise

m3
0.002359737216*m3
0.0088097675*m3
0.03523907*m3
0.158987291928*m3
4.92892159375e-6*m3
1.47867647813e-5*m3

Stere
board foot
peck
bushel
barrel
teaspoon
tablespoon

58

3 EMSO Modeling Language


ozUK
ozfl
cu
l
ml
pt
qt
gal
galC
galUK

3.11

2.8413075e-5*m3
2.95735295625e-5*m3
2.365882365e-4*m3
1e-3*m3
1e-3*l
0.000473176473*m3
0.000946352946*m3
0.00378541178*m3
0.00454609*m3
0.004546092*m3

fluid ounce (UK)


fluid ounce
US Cup
liter
milliliter
pint
quart
gallon
imperial gallon
gallon (UK)

Solver Options
Solver specific options can be declared in the following way, they
are not case sensitive:
OPTIONS
Dynamic = false;
NLPSolveNLA = false;
NLPSolver(File = "ipopt_emso",
RelativeAccuracy = 1e-6,
limited_memory_max_history = 20);

3.11 Solver Options

59

Table 3.6: IPOPT optimization solver specific options, default value in bold.
Option name
MaxIter
Print level
Limited memory max history

Derivative test
Derivative test print all
Output file
Mu strategy
Print user options
Linear solver

Hessian approximation
Fixed variable treatment

RelativeAccuracy
Acceptable tol
Constr viol tol
Acceptable constr viol tol
Dual inf tol
Acceptable dual inf tol
Barrier tol factor
Compl inf tol
Bound mult init val
Bound push
Bound relax factor
Finite difference perturbation

Type Description
integer Maximum number of iterations: textbf3000
integer Output verbosity level. The valid range for this integer
option is 0 printlevel 11
integer Maximum size of the history for the limited quasiNewton Hessian approximation. The valid range for this
integer option is 0 6 < +
string Enable
derivative
checker:
first-order,
second-order, none
string Indicates whether information for all estimated derivatives should be printed: yes, no
string File name of desired output file. ipopt.out
string Update strategy for barrier parameter: "adaptive",
monotone
string Print all options set by the user: "yes", no
string Linear solver used for step computations: "ma27",
"ma57", "mumps", Default depends on compilation
options.
string Indicates what Hessian information is to be used:
"exact", "limited-memory"
string Determines how fixed variables should be handled "relax bounds", "make constraint",
"make parameter"
real
Desired convergence tolerance (relative): 1 1008
real
Acceptable convergence tolerance (relative): 1 1006
real
Desired threshold for the constraint violation(Absolute):
1 1004
real
Acceptance threshold for the constraint violation(Absolute): 1 1002
real
Desired threshold for the dual infeasibility(absolute): 1
1004
real
Acceptance threshold for the dual infeasibility(absolute): 1 1002
real
Factor for mu in barrier stop test.(absolute): 1 10+01
real
Desired threshold for the complementarity conditions:
1 1004
real
Initial value for the bound multipliers 0 1 < +
real
Desired minimum absolute distance from the initial point
to bound 0 1002 < +
real
Factor for initial relaxation of the bounds. Used together
with fixed variable treatment option. 0 1008 < +
real
Perturbation size for finite-diff Hessian Evaluation 0
1006 < +

60

3 EMSO Modeling Language


The minlp solver used by EMSO, Bonmin, is a MINLP solver
which uses Ipopt to solve the internal NLP. To pass the options to
Ipopt, simply write the option as an NLP using Ipopt for example:
OPTIONS
NLPSolver(File = "minlp_emso",
RelativeAccuracy = 1e-6,
limited_memory_max_history = 20);

In the case where the option belongs to the mixed-integer algorithm itself, it is necessary write the option preceded by the word
bonmin (pay attention to the underscore ), for example:
OPTIONS
NLPSolver(File = "minlp_emso", derivative_test = "
second-order",
bonmin_algorithm = "B-BB", print_level = 5);

Below follows the Bonmin options, more details about the options
can be found at Bonmin manual:

3.11 Solver Options

61

Table 3.7: MINLP ( Bonmin )optimization solver specific options, default value in bold.
Option name
algorithm

Type
string

Print user options


nodeselect stra

string
string

warm start

string

sos constraints

string

nlp failure behavior

string

milp subsolver

string

bb log level

integer

bb log interval

integer

bb log level

integer

bb log level

integer

oa log level

integer

oa log frequency

integer

nlp log level

integer

number strong branch

integer

number before trust

integer

node limit

integer

max consecutive failures

integer

num retry unsolved random point

integer

Description
Bonmin algorithm: "B-BB", "B-OA", "B-QG",
B-Hyb
Print all options set by the user: "yes", no
Choose the node selection strategy. "best-bound",
"dept-first", "breadth-first", dynamic
Select the warm start method.
"optimum",
"interior point", "none"
Whether or not to activate SOS constraints branching.
"stop", "fathom"
Set the behavior when an NLP or a series of NLP are
unsolved by Ipopt "enable", "disable"
Choose the subsolver to solve MILPs sub-problems in
OAdecompositions. "Cbc D", "Cbc Par"
Specify branch-and-bounds log level: The valid range for
this integer option is 0 1 0
Interval at which node level output is printed: The valid
range for this integer option is 0 100
Set the level of output of the linear programming subsolver in B-Hyb or B-QG: The valid range for this integer
option is 0 0 4
specify MILP subsolver log level. Set the level of output
of the MILP subsolver in OA. The valid range for this
integer option is: 0 0 3
Set the level of output of OA decomposition solver. The
valid range for this integer option is: 0 1 2
Specify OA log frequency. The valid range for this integer option is: 0 100
Set the level of output of nlp solver (independent from
Ipopt print level). The valid range for this integer option
is: 0 1 2
Choose the maximum number of variables considered for
strong branching. The valid range for this integer option
is: 0 20
Set the number of branches on a variable before its
pseudo costs are to be believed in dynamic strong
branching.The valid range for this integer option is:
08
Set the maximum number of nodes explored in the
branch-andbound search.The valid range for this integer option is: 0 INT MAX
Number n of consecutive unsolved problems before
aborting a branch of the tree. The valid range for this
integer option is: 0 10
Number k of times that the algorithm tries to resolve an
unsolved NLP with a random starting point. The valid
range for this integer option is: 0 0

62

3 EMSO Modeling Language

Table 3.8: MINLP ( Bonmin )optimization solver specific options, default value in bold,
continued.
Option name
max consecutive unfeasible

num resolve at root

nlp solve frequency

nlp solve frequency

num resolve at node

mir cuts

num iteractions suspect

allowable gap
allowable fraction gap
cutoff
cutoff decr
time limit
integer tolerance
max random point radius
max consecutive failures
oa dec time limit
tiny element
very tiny element

Type Description
integer Number k of consecutive infeasible subproblems before
aborting a branch. The valid range for this integer option
is: 0 0
integer Number k of trials to solve the root node with different
starting points. The valid range for this integer option
is: 0 0
integer Specify the frequency (in terms of nodes) at which NLP
relaxations are solved in B-Hyb method.The valid range
for this integer option is: 0 10
integer Specify the frequency (in terms of nodes) at which NLP
relaxations are solved in B-Hyb method.The valid range
for this integer option is: 0 10
integer Number k of trials to solve a node of the tree with different starting points. The valid range for this integer
option is: 0 0
integer Sets the frequency (in terms of nodes) for generating
cuts of the given type in the branch-and-cut .The valid
range for this integer option is: 100 -5
integer (for debugging purposes only) number of iterations to
consider a problem suspect.The valid range for this integer option is: 1 -1
real
Specify the value of absolute gap under which the algorithm stops: 0
real
Specify the value of relative gap under which the algorithm stops: 0
real
Specify a cutoff value: 1 10100
real
Specify cutoff decrement: 1 105
real
Set the global maximum computation time (in seconds)
for the algorithm.: 1 1010
real
Any number within that value of an integer is considered
integer: 1 106
real
Set max value r for coordinate of a random point: 1105
real
Set max value r for coordinate of a random point: 1105
real
Specify the maximum number of seconds spent overall
in OA decomposition iterations: 120
real
Value for tiny element in OA cut: 1 108
real
Value for very tiny element in OA cut. Algorithm will
take the risk of neglecting an element lower than this:
1 1017

3.11 Solver Options

63

Warning: One must pay attentions that the above options are
compatible with just some algorithms,the compatibility table is
presented below:

Table 3.9: List of options and compatibility with the different algorithms.
Option
bb log level
bb log interval
lp log level
milp log level
oa log level
oa log frequency
nlp log level
print user options
time limit
allowable gap
allowable fraction gap
cutoff
cutoff decr
integer tolerance
node limit
nodeselect stra
number before trust
number strong branch
sos constraints
max random point radius
max consecutive failures
nlp failure behavior
num iterations suspect
num retry unsolved random point

type
default B-BB B-OA B-QG B-Hyb
output options
I
1
+

+
+
I
100
+

+
+
I
0

+
+
I
0

+
I
1

+
I
100

+
I
1
+
+
+
+
S
no
+
+
+
+
branch-and-bound options
F
1010
+
+
+
+
F
0
+
+
+
+
F
0
+
+
+
+
100
F
10
+
+
+
+
F
105
+
+
+
+
6
F
10
+
+
+
+
I INT MAX
+
+
+
+
S best-bound
+
+
+
+
I
8

+
+
+
I
20

+
+
+
S
enable
+
options for robustness
F
105
+
+
+
+
I
10
+

S
stop
+
+
+
+
I
1
+
+
+
+
I
0
+
+
+
+

64

3 EMSO Modeling Language

Table 3.10: List of options and compatibility with the different algorithms continued.
Option
max consecutive infeasible
num resolve at node
num resolve at root
nlp solve frequency
oa dec time limit
tiny element
very tiny element
cover cuts
Gomory cuts
milp subsolver
mir cuts
probing cuts1

type default B-BB B-OA B-QG B-Hyb


options for nonconvex problems
I
0
+

I
0
+
+
+
+
I
0
+
+
+
+
B-Hyb specific options
I
10

+
F
120

+
F
108

+
+
+
17
F
10

+
+
+
MILP options
I
5

+
I
5

+
S Cbc D

+
I
5

+
I
-5

Table 3.11: OPT++ optimization solver specific options, default value in bold.
Option name
MaxIterations
MaxFeval

Type Description
integer Maximum number of iterations: 100
integer Maximum number of function evaluations allowed:
1000
MaxBTIter
integer Maximum number of Back Track iterations allowed: 5
PrintDebug
integer Print debug information: 1, 0
SearchStrategy
string Search Strategy: BTLineSearch, TrustRegion,
LineSearch
MeritFun
string Search Strategy:
ArgaezTapia, NormFmu,
VanShanno ;
OutputFile
string Output file name: opt.out
RelativeAccuracy
real
set the Function tolerance: 1.49 1008
GradTol
real
set the Function tolerance: 6 1006

ConstrTol
real
set the Function tolerance: eps
StepTol
real
set the Function tolerance: 1.49 1008
MaxStep
real
set the Function tolerance: 1 10+03
MinStep
real
set the Function tolerance: 1.49 1008
LineSearchTol
real
set the Function tolerance: 1 1004
TRSize
real
set the Function tolerance: 0.1 kf (x)k

3.11 Solver Options

65

Table 3.12: NLASolver and Sundials specific options, default value in bold.
Option name
MaxIterations
Maxatbound
MaxDumpIter
MaxLSetupReuse
RelativeAccuracy
AbsoluteAccuracy

Type
integer
integer
integer
integer
real
real

Description
Maximum number of iterations: 100
Maximum number of iterations at bound: 20
Maximum dump iteration: 6
Maximum Jacobian reuse in the linear solving phase: 0
set the Function tolerance: 1 1003
set the Function tolerance: 1 1006

Table 3.13: IDASolver specific options, default value in bold.


Option name
MaxIterations

Type Description
integer Maximum number of internal steps to be taken by the
solver in its attempt to reach tout. 500
MaxOrder
integer Maximum LMM mathod order: 5
SuppressAlg
integer Suppress alg. vars. from error test 0
RelativeAccuracy
real
Set the function tolerance: 1 1003
AbsoluteAccuracy
real
Set the function tolerance: 1 1006
Hinit
real
Initial step size 0
Hmax
real
Maximum absolute value of step size allowed 1 1010
Nconfac
real
Factor in nonlinear convergence test for use during integration 1.0

Table 3.14: DASSLC specific options, default value in bold.


Option name
MaxIterations

Type Description
integer Maximum number of internal steps to be taken by the
solver in its attempt to reach tout. 10
MaxOrder
integer Maximum LMM mathod order: 5
Maxl
integer max. number of iterations before restart: 5
Kmp
integer number of orthogonalized vectors: 5
Istall
integer intermediate time steps : 5
RelativeAccuracy
real
Set the function tolerance: 1 1003
AbsoluteAccuracy
real
Set the function tolerance: 1 1006

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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

67

4.2

Conditional Modeling . . . . . . . . . . . . . . . . . . . . . . . . .

70

4.1 Arrays

4.1

67

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


fixed 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 parameter 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;

68

4 Advanced Modeling

CONNECTIONS
s1 to mix.Inlet(1);
s2 to mix.Inlet(2);
s3 to mix.Inlet(3);
SET
mix.Ninputs = 3;
end

Warning: Differently 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

A vector is an array with only one


dimension, see subsection 4.1.1

Arrays with more than one dimension are declared in an analogous


way to vectors :
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

The loop for is treated in


subsection 4.1.5

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
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.zi = Inlet.zi , i = 1 : N comps

4.1 Arrays

69

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)
EQUATIONS
ones = 1;

as Real;

Note: The above equation ones=1; actually accounts as M


times N equations.
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 flow rate we could use:
Outlet.F =

Inleti .F

The above equation can be obtained by the last line of the following 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:

70

4 Advanced Modeling

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:
var2dx,y =

var3dx,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.
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 fashion:
EQUATIONS
Outlet.z([1:Ncomps]) = Inlet.z([1:Ncomps]);

4.2

Conditional Modeling
Under construction: needs to be documented

Calculation Object Interface

In this chapter, we describe how the Plugin paradigm can be used to load, at run time,
third party software within EMSO entities. In chapter 8 is explained how to implement a new
Plugin service.

Contents
5.1

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

72

5.2

Using Plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

73

72

5 Calculation Object Interface

5.1

Introduction
In this section we describe what is a Plugin and what it is good
for.

5.1.1

What is Plugin?
Plugin is an interfacing mechanism which enables the user to
load calculation services provided by third party software within
EMSO. Typical cases where using Plugins 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 Plugin?


EMSO is an equation-based tool, therefore most type of mathematical 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 difficult to converge the problem without decoupling
the system.

5.1.3

The Plugin Basics


Before showing how to use a Plugin, lets introduce its basics:
Any number of Plugins can be declared within an EMSO
entity (Model, FlowSheet, etc.). The declaration of a
Plugin is very near to a parameter declaration;
Each Plugin provides a set of methods which are the
calculation routines available to be used in EMSO;
Each method calculates one quantity (the output) for given
zero or more other quantities (the inputs).

5.2 Using Plugins

73
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 Plugin service is provided by one library file which
must be compatible with the Plugin interface specification presented in section 8.1.

5.2

Using Plugins
In this section we show how to use Plugins within some EMSO
entities.

5.2.1

Using Plugins in Models

Plugin is one of the EMSO


built-in types, as Real, Integer,
etc.

As already mentioned, the declaration of a Plugin is very near


to a parameter declaration but using as base the EMSO builtin type Plugin. In Code 5.1 a typical usage of the Plugin
paradigm can be seen.
Code 5.1: EML file streams.mso.

1
2
3
4
5
6
7

Model liquid_stream as stream


ATTRIBUTES
Pallete = false;
Brief = "Liquid Material Stream";
Info =
"Model for liquid material streams.
This model should be used only when the phase
of the stream
is known a priori.";
PARAMETERS
outer PP as Plugin(Brief = "External Physical
Properties", Type="PP");

10
11

EQUATIONS
"Liquid Enthalpy"
h = PP.LiquidEnthalpy(T, P, z);
"Liquid stream"
v = 0;

13
14
15
16
17
18

Outer parameters were treated in


subsection 3.2.1.

end

The Code 5.1 makes part of EML, in line 55 of it a Plugin is


declared. As can be seen, it is declared with the outer prefix,
therefore it is only an reference to a entity with same name but
declared in the top level model, the FlowSheet.

74

A calculation library must be a


valid DLL (dynamic link library) or
a SO (shared library) file in win32
and posix platforms respectively.

5 Calculation Object Interface


In the case of a concrete Plugin (declared without the outer
prefix) the user must supply the corresponding calculation library
type and optionally supply arguments to create the object. A
sample declaration of a concrete Plugin follows:
PARAMETERS
PP as Plugin(Brief="Physical Properties Object",
Type="PP");

In this code, the object PP will be created using the type PP. The
available Plugin types are configured with help of the Plugins
Configuration dialog, as shown in Figure 5.1. This dialog is can
be reached by the menu ConfigPlugins.

Figure 5.1: Plugins Configuration dialog.


Using the dialog shown in Figure 5.1, the user can register any
number of Plugin types, but each type needs a unique type
name. Each type is dynamic linked by EMSO with the given file.
In line 59 of Code 5.1 a Plugin method is called, as can be
seen, this methods requires three inputs:
T temperature;
P pressure;
z molar composition vector.
The cited method returns the molar enthalpy of the liquid phase
of the mixture represented by PP.

5.2 Using Plugins

75

Note: EMSO will check the units of measurement of all Plugin


arguments, it also checks the units of the returned value.

EMSO Matlab Scilab Interface

c and Scilab
c communication
This chapter describes how to run the EMSO Matlab
c
c


interface inside Simulink or Scicos . This communication interface was developed by
VRTech Tecnologias Industriais Ltda (www.vrtech.com.br) for the ALSOC project. Special
thanks to Ramine Nikoukhah who helped the developers with the Scicos communication
interface.

Contents
6.1

EMSO Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

77

6.2

Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

77

6.3

The Configuration Graphic User Interface . . . . . . . . . . . . . .


c communication . . . . . . . . . . . . . . . . .
Matlab/Simulink
c communication . . . . . . . . . . . . . . . . . . .
Scilab/Scicos

82

6.4
6.5

87
90

6.1 EMSO Basics

6.1

77

EMSO Basics
EMSO has a vast library of chemical process equipments and the
main objective of this integration is to use these models integrated
c and Scilab
c in order to use their control libraries
with Matlab
such as robust, multivariate, model predictive and non-linear control that have been developed for these software. Basically, EMSO
c by a S-function in Simulink
c block.
is integrated with Matlab
c , the integration with EMSO is made by a Scicos
c
In Scilab
block. These blocks are configured by a graphical user interface,
which set-up a text file (with the .ems extension) that will be
loaded by the Simulink/Scicos block and set-up the simulation.
c and Scilab
c interface has three components:
EMSO Matlab
The configuration graphical user interface (GUI), which reads
an EMSO file and lists flowsheets and variables and also setup a projet file to be loaded by the dynamic libraries.
c
Two dynamic library for Matlab/Simulink
c
Two dynamic library for Scilab/Scicos

6.2
6.2.1

Installation
Requisites
c is availThe communication version between EMSO and Matlab
c

able only for Windows, while the version for Scilab is available
for both Windows and Linux.
c , the user must
To use the communication interface for Matlab
have installed the Microsoft Visual C++ 2008 Redistributable
Package (can be found searching at google), that can be freely
c was tested with Matdownload from Microsoft. The Matlab
lab 7.4 using Windows XP 32 bits version with Service Pack 3
installed.
Scilab communication version was tested with Scilab GTK 4.2,
which includes the lastest stable version of Scicos. This version
is available for Windows and Linux and the communication interface was tested in these platforms. Although the latest version
of Scilab is 5.0.3, the developers of Scicos does not support new
features in this new version, so the version selected for the communication interface selected was Scilab GTK 4.2.

6.2.2

Matlab Install
There are two manners of installing the EMSO Matlab interface:
Permanent install (require administrations privileges )

78

6 EMSO Matlab Scilab Interface


Temporary install (available only for the current Matlab section)
The permanent install can be performed when the installation is
executed with administration privileges on the system. Otherwise
the installation is only valid for the current section and must be
loaded again every time Matlab is opened. To execute the EMSO
Matlab communication, run the following command in Matlabs
prompt:
cd EMSODIR\interface\matlab
emsomatinstall

where EMSODIR is the complete path to the folder where EMSO


was installed.
If a successfull installation was performed, the following message
will be displayed:
EMSO<->Matlab/Simulink communication successfully
added to Matlab permanent path

Otherwise, the temporary installation will be automatically performed and the following message will be displayed:
Warning you have no rights to permanently change
Matlab path
You will need to run EMSOMATINSTALL again next time
Matlab is started

Uninstalling from Matlab


The uninstalling of EMSO Matlab communication interface is
necessary only when the permanent installation was performed.
To uninstall, run the following commands in Matlabs command
prompt:
cd EMSODIR\interface\matlab
emsomatuninstall

where EMSODIR is the complete path to the folder where EMSO


was installed.
If the installation was successfully done, the following message
will appear:
EMSO<->Matlab/Simulink communication interface
successfully removed from Matlab permanent path

otherwise the following message will be presented

6.2 Installation

79
Warning you have no rights to change Matlab
permanent path

6.2.3

Scilab Installation
Warning: Remember that this version of the communication
interface is only available to Scilab Gtk 4.2

Windows Installation
Open Scilab and type in prompt:
SCIHOME
This will tell where the Scilab user files were installed. Open the
following file with your favorite text editor which is located in
SCIHOME folder:
SCIHOME\scilab.ini
If the file does not exist, create a new one with the same name
on the SCIHOME folder.
Add the following line to the end of the file:
1

exec (SCIHOME + \ +emso_init.sce);

Save and close the file


Copy the file emso init.sce located at EMSODIR\interface\scilab
to the folder SCIHOME\Scilab\ScilabGtk-4.2\.
where EMSODIR is the complete path where EMSO was installed.
Edit the emso init.sce that has just been copied and add
the following line as the FIRST line of the file.
1

emdir

= EMSODIR;

where EMSODIR is the complete path where EMSO was installed,


pay attention that the EMSODIR MUST be between .
After the successfull installation the following message will be
displayed in Scilab console and every time Scilab is loaded:
link done
ans =
0.
link done
ans =
1.

80

6 EMSO Matlab Scilab Interface


This installation will make the communication interface available
only to the user, to install the interface for all users, it is necessary
to have administrator privileges and follow these steps:
Open the following file with your favorite text editor:
SCILAB GTK PATH\scilab.star
where SCILAB GTK PATH is the path where Scilab was installed.
Add the following line at the end of the file:
1

exec (SCIHOME + \ +emso_init.sce);

where EMSODIR is the complete path where EMSO was installed.


Save and close the file
Copy the file emso init.sce located at EMSODIR\interface\scilab
to the folder SCILAB GTK PATH.
where EMSODIR is the complete path where EMSO was installed.
Edit the emso init.sce that has just been copied and add
the following line as the FIRST line of the file.
1

emdir

= EMSODIR;

where EMSODIR is the complete path where EMSO was installed.Pay attention that the EMSODIR MUST be between
.
After the successfull installation the following message will be
displayed in Scilab console and every time Scilab is loaded:
link done
ans =
0.
link done
ans =
1.

Linux Installation
Copy the file emso init.sce located at EMSODIR/interface/scilab
to the folder /home/USER/.Scilab/ScilabGtk-4.2/.
where EMSODIR is the complete path where EMSO was installed
and USER is the user name.
Edit the emso init.sce that has just been copied and add
the following line as the FIRST line of the file.

6.2 Installation

81

emdir

= EMSODIR;

Where EMSODIR is the complete path where EMSO was installed


and USER is the user name. Pay attention that the EMSODIR
MUST be between .
Open the following file with your favorite text editor:
/home/USER/.Scilab/ScilabGtk-4.2/.scilab
Add the following line to the end of the file:
1

exec (SCIHOME + / +emso_init.sce);

Save and close the file


After the successfull installation the following message will be
displayed in Scilab console and every time Scilab is loaded:
link done
ans =
0.
link done
ans =
1.

This installation will make the communication interface available


only to the user, to install the interface for all users, it is necessary
to have administrator privileges and follow these steps:
Copy the file emso init.sce located at EMSODIR/interface/scilab
to the folder /usr/lib/scilab-gtk-4.2/
Open the following file with your favorite text editor:
/usr/lib/scilab-gtk-4.2/scilab.star
Add the following line at the end of the file:
1

exec (SCIHOME + / +emso_init.sce);

Save and close the file.


Edit the emso init.sce that has just been copied and add
the following line as the FIRST line of the file.
1

emdir

= EMSODIR;

where EMSODIR is the complete path where EMSO was installed,


pay attention that the EMSODIR MUST be between .
After the successfull installation the following message will be
displayed in Scilab console and every time Scilab is loaded:

82

6 EMSO Matlab Scilab Interface


link done
ans =
0.
link done
ans =
1.

6.2.4

Scilab Uninstall
To remove the EMSO Scilab communication interface, remove
the lines added previously to the files edited:
For Linux:
/home/user/.Scilab/ScilabGtk-4.2/.scilab
or /usr/lib/scilab-gtk-4.2/scilab.star
for Windows:
SCIHOME\Scilab.ini
or SCILAB GTK PATH\scilab.star

6.3

The Configuration Graphic User Interface


The configuration graphical user interface (GUI) is responsible
for open the EMSO file, the flowsheet and list the flowsheets
variables. Based in the variables list, it is possible to set the
c or Scicos
c block. This
inputs, outputs of the Simulink
GUI can be called by running the emso matlab scilab file in
the bin folder of the EMSO installation folder. After click two
times in the executable, the user open the configuration GUI as
presented in Figure 6.1.
Warning: Before start a new communication project make sure
your dynamic simulation in the flowsheet is running, with the
libraries and plug-ins properly installed.
With this GUI the user can create a new project or open an existing
one. After the creation of a new project, a new screen is presented
as shown by Figure 6.2.
This screen has four regions:
The toolbars: Where some basic buttons are presented.
The inputs: Where the block inputs (specifications or parameters) are selected.
The outputs: Where the block outputs (all variables) are
selected.

6.3 The Configuration Graphic User Interface

83

Figure 6.1: Initial screen of the GUI.

Figure 6.2: Graphical user interface of a new project.


The message window: Where the user can check consistency of the flowsheet and the number or states of the
DAE system.
In the toolbar, the flowsheet selection button calls the select the
.mso file dialog as presented in Figure 6.3

84

6 EMSO Matlab Scilab Interface

Figure 6.3: Select .mso file dialog.

Warning: Only .mso files with dynamic simulations must be


selected, since Simulink/Scicos will perform only dynamic simulations.
After the file selection, the flowsheets inside this file are scanned
and listed to the user, as presented in Figure 6.4

Figure 6.4: Select flowsheet dialog.


Inside the inputs region, on the left side of the screen, is presented
three listboxes. The first two lists on the left are the specifications(top) and parameters(botton). These variables are in the
EMSO diagram selected. They should be added to the Matlab
block by selection the right arrow () and removed with the left
arrow ().
In the right region of the screen are presented the outputs of the
block, inside this region there are two lists, one in the left where
all EMSO variables are listed; and the right, where the outputs
of the Matlab block are listed. The variables can be added from

6.3 The Configuration Graphic User Interface

85

EMSO to Matlab by selection the right arrow () and removed


with the left arrow (). The regions of the screen are explained
in Figure 6.5.

Figure 6.5: GUI regions explanation.


After the flowsheet loading, it is presented to the user in the
message box some information about the flowsheet, as showed in
Figure 6.6.

Figure 6.6: Flowsheet loaded and configured.


It is important to notice that in some flowsheets, some specifica-

86

6 EMSO Matlab Scilab Interface


tions or parameters are not available, in this case, the user will
receive a warning message and the respective list will be empty,
as presented in Figure 6.7.

Figure 6.7: Flowsheet without specifications.


In the case where the variables are vectors, e.g. compositions, a
new dialog box is showed to the user in order to select the array
index, as presented in Figure 6.8.

Figure 6.8: Variable with index.


The user can also add a new location where its libraries with personal .mso files are located. This can be done in the options
menu and the dialog is presented in Figure 6.9.
After the configuration, the project can be saved. The file format
is a text file, as presented in Figure 6.10.
This textfile organized in the following way:
1 The .mso file.
2 The fowsheet.

c communication
6.4 Matlab/Simulink

87

Figure 6.9: New libraries add dialog.

Figure 6.10: Text file generated.


3 The number of inputs.
4 The name of the inputs.
5 The number of outputs
6 The name of the outputs.
7 The number if the extra folders to look for user files (libraries).
8 The name of the folders to look for user files.
The generated file can be used either with Matlab/Simulink or
Scilab/Scicos.

6.4

c communication
Matlab/Simulink
There are two versions of the communication library between
EMSO and Matlab/Simulink: In the first one, named continuous EMSO receives the inputs and calculates the states deriva-

88

6 EMSO Matlab Scilab Interface


tives and returns to Simulink, which performs the integration; In
the second one, named discrete, EMSO receives the inputs and
the integration interval from Simulink, integrates the system and
calculates the output and send to Simulink. For both implementations there are a template diagram which the user can start its
own work. It is important to point-out that, depending on the
block diagram configuration in Simulink, one of the simulation
may not converge, in this case, it is suggested to test other integrators or change from discrete to continuous implementation
and vice-versa.
In order to start with the new template, the user can open a
Simulink diagram and choose one of the template available as
shown in Figure 6.11. The template diagram is presented in Figure 6.12

Figure 6.11: Simulink open diagram.


The block in the center of the diagram is a S-function block that
will call and configure the communication, clicking two times in
the block will display the window presented in Figure 6.13.
The first text box is the name of the librarys (.dll) communication interface, in this case the continuous version. In the text
box below, three parameters must be given, separated by comma:
The project file previously configured with the GUI, delimited with .
The number of inputs.

c communication
6.4 Matlab/Simulink

89

Figure 6.12: Simulink template diagram.

Figure 6.13: Simulink S-function configuration for the continuous


version of the communication interface.
The number of outputs.
The last textbox is left empty.
If the discrete version of the library is used, the user must change
2 parameters, the first text box, with the name of the .dll and
the last parameter of the second textbox, which is the integration
time interval passed to EMSO, as presented in Figure 6.14.
Warning: The templates are not fixed, they can have their type
changed from continuous to discrete (and vice-versa) but but

90

6 EMSO Matlab Scilab Interface

Figure 6.14: Simulink S-function configuration for the discrete


version of the communication interface.
name of the .dll should be changed and also the number of the
parameters in the second text box.
The discrete and continuous version of the communication interface can be used together in the same diagram, as presented in
Figure 6.15. The user can also make more complex block diagrams as presented in Figure 6.16 or in the diagrams folder.

6.5

c communication
Scilab/Scicos
In this section, the communication between Scicos and EMSO
will be presented. The communication interface is very similar of
Matlab/Simulink.
There are two versions of the communication library between
EMSO and Scilab/Scicos: In the first one, named continuous
EMSO receives the inputs and calculates the states derivatives
and returns to Scicos, which performs the integration; In the second one, named discrete, EMSO receives the inputs and the
integration interval from Scicos, integrates the system and calculates the output and send to Scicos. For both implementations
there are a template diagram which the user can start its own
work. It is important to point-out that, depending on the block diagram configuration in Scicos, the simulation may not converge,

c communication
6.5 Scilab/Scicos

91

Figure 6.15: Simulink example diagram.

Figure 6.16: Simulink example diagram.


in this case, it is suggested to test other integrators or change
from discrete to continuous implementation and vice-versa. The
main difference between the Scicos and Simulink communication
interface is that the blocks in the EMSO blocks (continuous and
discrete) in Scicos is masked and not a S-function, so the user
need to start from the template or add the continuous or discrete
EMSO block, which are different. The other difference, is that
the user should previously know the number of states of the DAE
system in EMSO to configure the continuous block. This information can be inspected at the configuration GUI, in the message
outputs, listed as dynamic degrees of freedom, as presented in
Figure 6.17

92

6 EMSO Matlab Scilab Interface

Warning: In order to run the simulation, the Scilab folder must


be the same folder where the .ems file and the .mso file are located.

Figure 6.17: Checking the number of states for the continuous


version of the communication interface.
The other difference e between the Scicos and Simulink communication interface is that the configuration GUI in Scilab must be
called by the command line by the Scilab running the command:
host(EMSODIR BIN\EMSO MAT SCI.exe) for windows
or
unix(EMSODIR BIN/EMSO MAT SCI) for Linux/Unix
where EMSODIR BIN is the folder where the EMSO binary is
located.
The configurations GUI can also be called outside Scilab.
In order to start with the new template, the user can open a
Scicos diagram and choose one of the templates available.
The block in the center of the diagram is a block that will call
and configure the communication, clicking two times in the block
will display the window presented in Figure 6.19.
In this block, three parameters must be given:

c communication
6.5 Scilab/Scicos

93

Figure 6.18: Scicos template diagram.

Figure 6.19: Scicos block for the continuous version of the communication interface.
The project file previously configured with the GUI, delimited with .
The number of inputs.
The number of outputs.
The number of states.
If the discrete version of the library is used, only the first three
parameters will be asked. The user can also start from an empty
diagram, in this case the block can be inserted by clicking with
the mouse right button and choose the Add new block option.
A dialog will be displayed, as presented if , where the user must
fill with emso scid, for the discrete version, or emso sci c, for the
continuous version.
Warning: The user must be sure that the blocks function and
the dll were properly loaded into Scilab otherwise the adding
of the blocks and the simulation will return an error.

94

6 EMSO Matlab Scilab Interface

Figure 6.20: Inserting the EMSO block into a new Scicos diagram
Instead of adding a EMSO block, the user can also add a GENERIC
block, from Others block palette, and than configure it properly.
The configuration dialog of the GENERIC block is presented in
Figure 6.21, and its done as follows:

Figure 6.21: Generic block in Scicos


First text box: The communication interface function (emso scid,
for the discrete version, or emso sci c, for the continuous
version)
Third text box: The number of inputs in the following way:
[nInputs, 1].
Fifth text box: The number of outputs in the following way:
[nOutputs, 1].

c communication
6.5 Scilab/Scicos

95

Ninth text box: The vector of initial continuous states of


the DAE system (only for the continuous version!) in
the following way (example for three states): [1 1 1] (for
each state a one).
After the generic block configuration it is necessary to update
the label of the block, this label will be used as the configuration
file name. To access this block property, right click on the block
and select PropertiesLabel, where Label is the file name, as
presented in Figure 6.22.

Figure 6.22: Editing the block label.


Examples diagrams can be checked at the sciclab\ diagrams folder,
one of them is presented in Figure 6.23

Figure 6.23: Scicos example diagram.


Warning: In the case where the integration is slow, increase the
activation signal at the clock configuration.
Warning: In the case where the output is constant or empty,
the simulation may not be converging, try to change the Scicos

96

6 EMSO Matlab Scilab Interface


solver (IDA or CVODE), the communication version (continuous
or discrete or the EMSO solver

EMSO CAPE-OPEN Interfaces

In this chapter, we describe how to use EMSO together with other simulation software through
CAPE-OPEN communication. EMSO implements interfaces to access third party properties
calculations and to be accessed by other simulators, as an unit-operation block.

Contents
7.1

About the CAPE-OPEN standards . . . . . . . . . . . . . . . . . .

98

7.2

Using external thermodynamics sources . . . . . . . . . . . . . . .

99

7.3

Using EMSO as an unit-operation block . . . . . . . . . . . . . . . 102

98

7.1

7 EMSO CAPE-OPEN Interfaces

About the CAPE-OPEN standards


CAPE-OPEN is a set of programming standards on which process
simulation software must be developed in order that they could
communicate and exchange functionalities. These standards are
mantained by CO-LaN (http://www.colan.org/). The motivation
is the interoperability between different CAPE (Computer-Aided
Process Engineering) applications, seeking for the generality and
flexibility on their communication. It also eases the development
of new applications for instance, an unit operation model developed under CAPE-OPEN standards will depend only on a CAPEOPEN compliant physical property systems, without concerning
about every possible system.
Each software component could act as a database of compounds
and thermodynamic data, properties and/or equilibrium calculator, an individual unit-operation block and, assembling them, the
main simulation environment. Also, these software components
must implement classes of objects and packages that will be used
by the other components and how those objects are handled is also
defined on the CAPE-OPEN standards. The associations among
those entities can be seen schematically on Figure 7.1, where software components are represented in boxes and objects/packages
in ellipses.
These entities must relate with each other through the interfaces
defined by the CAPE-OPEN standards. The interfaces are implemented in COM (Component Object Model) compatibility, which
is the most common interface standard on Microsoft Windows.
Each CAPE-OPEN compliant software component installed on
the system has respective entries in the system registry. This way,
any of them can be aware of which other compatible software is
available on the system.
Windows note: CAPE-OPEN communication is only available
for Windows systems.
EMSO is ready to communicate through CAPE-OPEN standards,
according to its version 1.1, implementing interfaces needed to:
access an ICapePropertyPackage, which means that it can
use any thermodynamics source that is CAPE-OPEN compliant;
be used as an individual unit-operation block in a CAPEOPEN Simulation Environment (COSE).

7.2 Using external thermodynamics sources

99

Figure 7.1: Schematical diagram of CAPE-OPEN entities.

7.2

Using external thermodynamics sources


On this context, EMSO responds as the simulation environment,
with its own equipment models and a socket of communication to
CAPE-OPEN compliant thermodynamics systems. EMSO keeps
the ICapeThermoMaterialObject, which is where all the properties of the material streams are stored, but retrieves the data and
the calculations from an external CAPE-OPEN compliant thermodynamics system.
At the other side, a CAPE-OPEN compliant thermodynamics system has to provide a Physical Property Package, which will be
reached by the CAPE-OPEN client (i. e. EMSO), through the
respective interfaces. In order to identify the Physical Property
Package to be used on EMSO, there must be informed a ClsId,
the unique identification code of the Physical Property Package
Manager and a package name, which is usually defined on the

100

7 EMSO CAPE-OPEN Interfaces


external thermodynamics system.
The Physical Property Package contains the information about
the compounds to be considered on the simulation. It is responsible to retrieve the compounds constant properties, to describe
the phases on the Material Object (hold by EMSO) to the software components of the thermodynamic system and to pass and
receive data to the properties and equilibrium calculators.

7.2.1

Setting an external Property Package to be used on EMSO


To get the ClsId of a Physical Property Package Manager, it is
recommended to use OLE View, a tool to browse the COM classes
installed on the computer. It is freely distributed by Microsoft.
From its interface, there can be found the group CAPE-OPEN
Physical Property Package Managers, which contains all available
Package Managers. Clicking on one of them with the right mouse
button, there is the option Copy CLSID to Clipboard, as seen on
Figure 7.2.

Figure 7.2: Browsing the available property package managers.


Besides the ClsId of the Property Package Manager, there is
also needed to specify the name of the package name, pckgName,
which is usually defined on the interface of the software component responsible for the Property Package Manager.
The thermodynamics CAPE-OPEN communication socket is in
the form of a Plugin. The file copp.dll must be registered
as a Plugin on EMSO Config menu. More details on plugin
configuration are found on section 5.2.

7.2 Using external thermodynamics sources


7.2.2

101

Using CAPE-OPEN thermodynamics on EMSO


The CAPE-OPEN thermodynamics plugin must be properly registered and then it can be used on EMSO flowsheets. Following
there is an example of the configuration of the connection to a
CAPE-OPEN thermodynamic system:
PARAMETERS
PP as Plugin(Brief="CAPE-OPEN Physical
Properties",
Type="COPP"
,clsId = "{B6AC41D3-7755-4ED5-B307B58841E05C74}"
,pckgName = "C1_C2"
);

VRTherm is a software for physical


properties prediction from VRTech
www.vrtech.com.br.

Here, our thermodynamics CAPE-OPEN communication socket


was registered as a Plugin of type COPP. It must be declared
as a parameter, as seen on section 5.2. This plugin has two attributes that must be informed as options of the Plugin: the
ClsId of the Property Package Manager and the pckgName,
the name of a package provided by this Property Package Manager. EMSO will check if the ClsId is valid and if there exists
the given package.
The CAPE-OPEN thermodynamics socket was built in such way
that it has the same syntax as the VRTherm Plugin into the
flowsheet environment. We find an example following:
Pvap = PP.VapourPressure(T);

On this example, the thermodynamics system will return a vector,


of length equal to the number of components present on the
CAPE-OPEN property package, with the values of the vapour
pressure for each component at the temperature T. PP is the
name which the Plugin was declared on the flowsheet, as in
the example from the beginning of the section. The funcition call
is entered right after a point and the arguments are informed in
parenthesis.
Table 7.1 presents the pure compounds properties functions calls.
They return a vector, of length equal to the number of components, with the values of the respective property for each one.
Table 7.2 presents the calls for the mixture properties calculations. They all return a single value, which stands for the phase
composed by the mixture. The Table 7.3 contains the calls for
the phase equilibrium calculations. They return just a single value
for the respective property, that stands for the phase equilibrium
state, except the Flash calculations that returns 3 results: the

102

7 EMSO CAPE-OPEN Interfaces


vapour fraction and 2 vectors, for the equilibrium composition of
both phases.

Table 7.1: Pure compounds properties.


Property
Call
Boiling temperature
NormalBoilingPoint
Critical temperature
CriticalTemperature
CriticalPressure
Critical pressure
Critical volume
CriticalVolume
Freezing temperature
NormalFreezingPoint
Molecular weight
MolecularWeight
Enthalpy of formation at 25
IdealGasEnthalpyOfFormatioAt25C
IdealGasGibbsOfFormationAt25C
Gibbs Free Energy of formation at 25
Vapour pressure
VapourPressure(T)

7.3

Using EMSO as an unit-operation block


under construction.

7.3 Using EMSO as an unit-operation block

Table 7.2: Properties of mixtures.


Property
Number of components
Liquid enthalpy
Vapour enthalpy
Fugacity Coefficient of liquid
Fugacity Coefficient of vapour
Liquid cp
Vapour cp
Liquid cv
Vapour cv
Cp /Cv ratio for liquid
Cp /Cv ratio for vapor
Liquid entropy
Vapour entropy
Liquid molar volume
Vapour molar volume
Compressibility factor for lquido
Compressibility factor for vapour
Liquid Gibbs free energy
Vapour Gibbs free energy
Liquid thermal conductivity
Vapour thermal conductivity
Liquid viscosity
Vapour viscosity
Liquid internal energy
Vapoir internal energy
Liquid density
Vapour density

Call
NumberOfComponents
LiquidEnthalpy(T,P,z)
VapourEnthalpy(T,P,z)
LiquidFugacityCoefficient(T,P,z)
VapourFugacityCoefficient(T,P,z)
LiquidCp(T,P,z)
VapourCp(T,P,z)
LiquidCv(T,P,z)
VapourCv(T,P,z)
LiquidCpCv(T,P,z)
VapourCpCv(T,P,z)
LiquidEntropy(T,P,z)
VapourEntropy(T,P,z)
LiquidVolume(T,P,z)
VapourVolume(T,P,z)
LiquidCompressibilityFactor(T,P,z)
VapourCompressibilityFactor(T,P,z)
LiquidGibbsFreeEnergy(T,P,z)
VapourGibbsFreeEnergy(T,P,z)
LiquidThermalConductivity(T,P,z)
VapourThermalConductivity(T,P,z)
LiquidViscosity(T,P,z)
VapourViscosity(T,P,z)
LiquidInternalEnergy(T,P,z)
VapourInternalEnergy(T,P,z)
LiquidDensity(T,P,z)
VapourDensity(T,P,z)

Table 7.3: Equilibrium calculations.


Property
Call
Vapour fraction
VapourFraction(T,P,z)
Flash TP calculation
Flash(T,P,z)
Flash PH calculation
FlashPH(P,h,z)
Bubble point temperature
BubbleT(P,z)
Bubble point pressure
BubbleP(T,z)

103

II. Programming Guide

Developing new Plugin Services

In this chapter, we describe how to develop a new Plugin service enabling to load external
software within EMSO entities. In section 5.2 the usage of the Plugin interface was described. Note that the information presented here is not a required to use Plugins but to
develop new services.

Contents
8.1

Interface Specification . . . . . . . . . . . . . . . . . . . . . . . . . 106

8.2

Writing new Plugin Services . . . . . . . . . . . . . . . . . . . . 113

8.3

Documenting Plugin Services . . . . . . . . . . . . . . . . . . . . 114

106

8.1

8 Developing new Plugin Services

Interface Specification
In order to implement a Plugin service one can use any of
the most common scientific programming languages. There are
template implementations available for C, C++ and Fortran, presented in sections 8.2.1, 8.2.2 and 8.2.3 respectively. It follows
bellow the concepts behind the Plugin interface.
Note: The information presented here is not required to use
already made Plugins but to develop new services.
A Plugin 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 Plugin service
check method: checks if a specific method exists and
returns the number of inputs and outputs
method details: provides detailed information about a
specific 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
In the following subsections these functions are detailed described.
Note that, depending on the programming langued used to actually implement the service, a prefix in the function names can
be required. For instance, when implemented in C, the create
function should be eo create. In Frotran, depending the compiler it should be eo create. For more details check subsection 8.2.1, subsection 8.2.2, or subsection 8.2.3.

8.1.1

Create Function
When a new EMSO task is started, like a dynamic simulation, for
each concrete Plugin declared, EMSO creates a new instance
of such object. In this creation procedure the create function
is called in order to load the instance specific data.
The create function has the following form:
create(objectHandler, retVal, msg)

8.1 Interface Specification

107
where the arguments are as described in Table 8.1.

Table 8.1: Arguments of the Plugin create function.


Argument name
Type
objectHandler [out] integer

retVal
msg

[out] integer
[out] text

Description
Unique identifier of the object instance created (will be used to identify the instance in subsequent calls).
Return flag, see ??.
A text space where error messages
should be copied.

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;
if some error or warning has occurred set retVal accordingly and copy a message to the msg
return the memory address of the data structure (or an
integer which unique identifies it) in the objectHandler
As EMSO Models, a Plugin can have parameters. An example
could be the required precision to be used when calculating a
method. These parameters can be set as usuall in the Model,
for instance:
PARAMETERS
PP as Plugin(Brief="Physical Properties Object",
Type = "PP", VapourModel = "PR",
LiquidModel = "PR");

For each attribute given 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 8.2.


The expected behavior of the set parameter function is:

108

8 Developing new Plugin Services

Table 8.2: Arguments of the Plugin set parameter function.


Argument name
objectHandler

Type
[in] integer

parameterName
valueType

[in] text
[in] integer

valueLength

[in] integer

values

[in] real vector

valuesText

[in] text vector

retVal
msg

[out] integer
[out] text

Description
Identifier of the object instance coming from the create function.
The name of the parameter to be set.
The type of the parameter (1 for
Real, 2 for Integer, 3 for
Boolean and 4 for text)
The length of the value (1 if is a
scalar)
The vector of values (empty if the
type is text)
The vector of values (empty if the
type is not text)
Return flag, see ??.
A text space where error messages
should be copied.

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
8.1.2

Destroy Function
When a Plugin instance is created the create function is
called. Then, when the object is no longer used by EMSO 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 8.3.


The expected behavior of the destroy function is to release any
memory, close data banks, etc. regarding the given objectHandler.
8.1.3

Verification Functions
A priori, EMSO does not known what are the methods supplied
by a particular Plugin nor the number or kind of its inputs

8.1 Interface Specification

109

Table 8.3: Arguments of destroy function.


Argument name
objectHandler

Type
[in] integer
[out] integer
[out] text

retVal
msg

Description
Identifier of the object instance coming from the create function.
Return flag, see ??.
A text space where error messages
should be copied.

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 8.4.


Table 8.4: Arguments of check method function.
Argument name
objectHandler

Type
[in] integer

methodName
methodID

[in] text
[out] integer

numOfInputs

[out] integer

numOfOutputs

[out] integer

retVal
msg

[out] integer
[out] text

Description
Identifier of the object instance coming from the create function.
Name of the method being checked.
Unique identifier for the given method
name (will be used to identify the
method in subsequent calls).
The number of expected inputs of the
method.
The number of outputs of the
method.
Return flag, see ??.
A text space where error messages
should be copied.

From the check method function the following behavior is expected:


Check the existence of a given methodName, if the method
does not exist this should be reported copying some message into error.

110

8 Developing new Plugin Services


If the required method exists, return the number of inputs
and the number of outputs. Optionally, an unique identifier
for the method can be returned in methodID. Then EMSO
will use this identifier 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 detailed information about the method. This function has the following form:
method_details(objectHandler, methodName, methodID,
numOfInputs, inputLengths, inputTypes
, inputUnits,
numOfOutputs, outputLengths,
outputTypes, outputUnits,
hasDerivatives,
retVal, msg)

where the arguments are as described in Table 8.5.


The purpose of the method details function is to provide
detailed information about the inputs and outputs of a specific
method. The expected behaviour is:
Given the methodName (or the methodID previouslly returned), set inputLengths, inputTypes and inputUnits.
Given the methodName (or the methodID previouslly returned), set outputLengths, outputTypes and outputUnits.
If the method will provide calculation for the derivatives set
hasDerivatives to 1.
8.1.4

Calculation Function
Given the inputs, each Plugin 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 8.6.


The expected behaviour for the calc function is:

8.1 Interface Specification

111

Table 8.5: Arguments of check inputs function.


Argument name
objectHandler

Type
[in] integer

methodName
methodID

[in] text
[in] integer

numOfInputs
inputLengths
inputTypes
inputUnits

[in] integer
[out] integer vector
[out] integer vector
[out] text vector

numOfOutputs

[in] integer

outputLengths
outputTypes

[out] integer vector


[out] integer vector

outputUnits

[out] text vector

hasDerivatives

[out] integer

retVal
msg

[out] integer
[out] text

Description
Identifier of the object instance coming from the create function.
Name of the method being checked.
Identifier of the method coming from
the check method function.
The number of inputs of the method.
The length of each input.
The type of each input (1 for Real, 2
for Integer and 3 for Boolean).
The unit of measurement of each input.
The number of outputs of the
method.
The length of each output.
The type of each output (1 for Real,
2 for Integer and 3 for Boolean).
The unit of measurement of each output.
If the method provides analytical
derivatives calculation
Return flag, see ??.
A text space where error messages
should be copied.

112

8 Developing new Plugin Services

Table 8.6: Arguments of calc function.


Argument name
objectHandler

Type
[in] integer

methodName
methodID

[in] text
[in] integer

numOfInputs
inputLengths
totalInputLength
inputValues
numOfOutputs
outputLengths
totalOutputLength
outputValues
calculeDerivatives
outputDerivatives

[in] integer
[in] integer vector
[in] integer
[in] real vector
[in] integer
[in] integer vector
[in] integer
[out] real vector
[in] integer
[out] real vector

error

[out] text

warning

[out] text

Description
Identifier of the object instance coming from the create function.
Name of the method being checked.
Unique
identifier
of
the
method name,
coming from
check method.
The number of inputs.
The length of each input.
Total input length.
Vector containing the input values.
The number of outputs.
The length of each input.
Total output length.
Vector to put the calculated output
values.
Flag if the method should calculate
the derivatives or not.
Vector to put the calculated output
derivative values.
A text space where error messages
should be copied.
A text space where warning messages
should be copied.

8.2 Writing new Plugin Services

113

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 derivatives and calculeDerivatives is not false, return the
value of the derivatives on outputDerivatives.

8.2

Writing new Plugin Services


In this section we describe how to implement a new Plugin
service using the most common scientific programming languages.
As a base concept of the Plugin interface was stated that an
EMSO entity can have any number of Plugins (see ??). Therefore, multiple instances of a Plugin service can be active simultaneously. If this is the case and the service being implemented
has instance dependent data, each Plugin instance should allocate its own data. Unfortunately, dynamic memory allocation is
not a trivial task in Fortran then if the service 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.

8.2.1

Writing Plugin Services in Fortran


As mentioned in section 8.1, in order to implement a new Plugin
service some functions must be implemented. In file external object.f
found at interfaces directory a template implementation for
a Plugin service in Fortran is given.
The template file 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.

8.2.2

Writing Plugin Services in C


As mentioned in section 8.1, in order to implement a new Plugin
service some functions must be implemented. In file external object.c
found at interfaces directory a template implementation for
a Plugin service in C is given. This file makes use of the interface definitions declared at external object.h. Note that
the header file should not be modified by the user.
The template file 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.

114
8.2.3

8 Developing new Plugin Services


Writing Plugin Services in C++
As mentioned in section 8.1, in order to implement a new Plugin
service some functions must be implemented. When using C++,
this functions actually are member functions of a class. In file
external object.cpp, found at interfaces directory, a
template implementation for a Plugin service in C++ is given.
This file makes use of the interface definitions declared in file
external object.h. Note that the header file should not be
modified by the user.
The C++ template file has a skeleton implementation that should
be filled 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 Plugin services in C++
the user can choose between implement the interfaces exactly as
described in the C template file or to implement it as class. The
C++ template file uses the class approach.

8.3

Documenting Plugin Services

VRTherm is a software for physical


properties prediction from VRTech
www.vrtech.com.br.

The software VRTherm is a typical example of Plugin. Its


documentation can be used as a base for developing the manual
for a new service.
Basicaly, a good Plugin 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.

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 Plugins described in chapter 8.

Contents
9.1

NLA Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

9.2

DAE Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

9.3

Writing new Solver Services . . . . . . . . . . . . . . . . . . . . . 125

9.4

Documenting Solver Services . . . . . . . . . . . . . . . . . . . . . 126

116

9.1

9 Developing new Solvers

NLA Solvers
Nonlinear-algebraic (NLA) systems arise naturally from steadystate 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, yl < y < yu

(9.1)

where y is the vector of variables to solve, F (y) is the vector


of functions (the equations), yl and yu are the lower and upper
bounds, respectivelly.
In this section we describe how to implement a new solver for
systems as Equation 9.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
the Jacobian matrix, and are scalars, x and y are given
vectors.

This operation is also known as the


GEMV BLAS operation

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;
9.1.1

Residuals Function
For any point yc which is not the solution of Equation 9.1 we will
have a residual:
F (yc ) = res

(9.2)

9.1 NLA Solvers

117
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 9.1.

Table 9.1: Arguments of the ResFn function.


Argument name
y
res
EMSOdata
retVal

9.1.2

Type
[in] real
[out] real
[out] integer

Description
Vector with the current point for y
Residuals vector, will be calculated as a function of y.
EMSO problem specific data (should not be
used by the solver).
Return flag, see ??.

Jacobian
Newtons like methods can solve Equation 9.1 iteratively with
some modification of the following equation:
F n
(y y n+1 ) = F (y n )
y

(9.3)

where F/y is the Jacobian and F (y n ) is the residuals vector


(subsection 9.1.1).
Using Equation 9.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 9.2.


Note: The LSolve function solves for x given a vector b, depending 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 efficient storage structures (dense
or sparse) and specific algorithms for solving the linear system
which are independent from the solver implementation.

118

9 Developing new Solvers

Table 9.2: Arguments of the LSolve function.


Argument name
x
b
EMSOdata

Type
[out] real
[in] real
[out] integer

retVal

Description
Vector with the solution of the linear system
The independent vector b
EMSO problem specific data (should not be
used by the solver)
Return flag, see ??.

The LSolve function solves the linear system using the Jacobian
of the system. But aiming at efficiency 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 9.3.

Table 9.3: Arguments of the LSetup function.


Argument name
EMSOdata
retVal

Type
[out] integer

Description
EMSO problem specific data (should not be
used by the solver)
Return flag, see ??.

As can be seen in Table 9.3 the LSetup function does not require an input argument for y. EMSO uses the y values given at
the last call to ResFn (subsection 9.1.1), this method improve
the efficiency when calculating the Jacobian using automatic differentiation.
9.1.3

Matrix Multiplication
Some modifications 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.

9.1 NLA Solvers

119
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 simplified 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 9.4.

Table 9.4: Arguments of the LProd function.


Argument name
alpha
x
beta
y
EMSOdata
retVal

9.1.4

Type
[in] real
[in] real
[in] real
[inout] real
[out] integer

Description
Given scalar
Given vector
Given scalar
Given vector, will hold the result of the operation
EMSO problem specific data (should not be
used by the solver).
Return flag, see ??.

Create and Destroy Functions


EMSO can run concurrent simulations, and so, in order to support 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 instance of the solver should have its own memory space to avoid
conflicts 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 9.5.

120

9 Developing new Solvers

Table 9.5: Arguments of the NLA solver create function.


Argument name
solverID

Type
[out] integer

numOfEqs
resFn

[in] integer
[in] function

y0
ylb
yub
EMSOdata

[in] real vector


[in] real vector
[in] real vector
[in] integer

iopt
ropt
retVal
msg

[in] integer vector


[in] real vector
[out] integer
[out] text

Description
Unique identifier of the solver instance created
(will be used to identify the instance in subsequent calls).
The number of equations of the system.
Function that calculates the residuals of the
system.
Initial values of the variables.
Lower bound for the variables.
Upper bound for the variables.
EMSO problem specific data (only to pass back
to resFn, lsetup and lsolve)
The vector of integer options, see ??.
The vector of real options, see ??.
Return flag, see ??.
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 9.6.


Table 9.6: Arguments of the NLA solver destroy function.
Argument name
solverID
retVal
msg

Type
[in] integer
[out] integer
[out] text

Description
Unique identifier of the solver instance (returned by create).
Return flag, see ??.
A text space where error messages should be
copied.

Using the given solverID the solver should release any memory
associated with that solver instance.

9.1 NLA Solvers

121
Note: When using C or C++, an easy way to implement an
unique identifier for the solver is to create an structure or class
for the solver and return its address as the identifier. Then the
solver just needs to cast back the SolverId to get the address
of the structure.

9.1.5

Solve Function
Once the solver instace has been created (as described in subsection 9.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 9.10.


Table 9.7: Arguments of the NLA solver solve function.
Argument name
solverID

Type
[out] integer

numOfEqs
resFn

[in] integer
[in] function

y
ylb
yub
EMSOdata
rtol
atol
iopt
ropt
retVal
msg

[inout] real vector


[in] real vector
[in] real vector
[in] integer
[in] real
[in] real
[in] integer vector
[in] real vector
[out] integer
[out] text

Description
Unique identifier of the solver instance (returned by create).
The number of equations of the system.
Function that calculates the residuals of the
system.
Initial values of the variables and the solution
at the end.
Lower bound for the variables.
Upper bound for the variables.
EMSO problem specific data (only to pass back
to resFn, lsetup and lsolve)
The relative accuracy
The absolute accuracy (optionally a vector)
The vector of integer options, see ??.
The vector of real options, see ??.
Return flag, see ??.
A text space where error messages should be
copied.

EMSO can call multiple times the solve function before destoying 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.

122

9 Developing new Solvers

Warning: The parameter rtol is always a real scalar but atol


can be a vector depending on the options at iopt.

9.2

DAE Solvers
Differential-algebraic equations (DAE) arise naturally from dynamic modeling in several engineering areas.
Prior to a dynamic simulation, EMSO internally converts in memory the given FlowSheet description to a general DAE system
in the following form:
F (t, y, y 0 ) = 0, yl < y < yu

(9.4)

where t is the independent variable (usually the time), y is the


vector of variables, y 0 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
tn , yn , yn0 the DAE solver should only to advance one step to a
0
.
next solution tn+1 , yn+1 , yn+1
Note: The first solution t0 , y0 , y00 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 9.1) EMSO provides
a set of services which give informations about the problem being
solved:
ResFn: returns the residuals of Equation 9.4 for a given
t, y, y 0
LSetup: tells EMSO to update the Jacobian matrices
F/y and F/y 0
LFactor: builds the iteration matrix cF/y + dF/y 0
LSolve: solves for x the linear system Ax = b for a given
b, where A is the iteration matrix cF/y + dF/y 0
Using the functions provided by EMSO, a new DAE solver needs
to implement the following routines:

9.2 DAE Solvers

123
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;

9.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 9.8.

Table 9.8: Arguments of the DAE solver create function.


Argument name
solverID

Type
[out] integer

numOfEqs
resFn

[in] integer
[in] function

y0
[in] real vector
y0
[in] real vector
variableIndexes [in] integer vector
EMSOdata
rtol
atol
iopt
ropt
retVal
msg

[in] integer
[in] real
[in] real
[in] integer vector
[in] real vector
[out] integer
[out] text

Description
Unique identifier of the solver instance created
(will be used to identify the instance in subsequent calls).
The number of equations of the system.
Function that calculates the residuals of the
system.
Initial values of the variables y.
Initial values of the variable derivatives y 0 .
The index of each variable (only for high index
problems).
EMSO problem specific data (only to pass back
to resFn, lsetup and lsolve)
The relative accuracy
The absolute accuracy (optionally a vector)
The vector of integer options, see ??.
The vector of real options, see ??.
Return flag, see ??.
A text space where error messages should be
copied.

124

9 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 9.9.

Table 9.9: Arguments of the DAE solver destroy function.


Argument name
solverID
retVal
error

Type
[in] integer
[out] integer
[out] text

Description
Unique identifier of the solver instance (returned by create).
Return flag, see ??.
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 identifier for the solver is to create an structure or class
for the solver and return its address as the identifier. Then the
solver just needs to cast back the SolverId to get the address
of the structure.
9.2.2

Step Function
After created as described in subsection 9.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 9.10.


EMSO can call multiple times the solve function before destoying it. Each time EMSO asks the solver to solve the problem a

9.3 Writing new Solver Services

125

Table 9.10: Arguments of the NLA solver solve function.


Argument name
solverID

Type
[out] integer

numOfEqs
resFn

[in] integer
[in] function
[inout] real vector

y
ylb
yub
EMSOdata
rtol
atol
iopt
ropt
retVal
msg

[in] real vector


[in] real vector
[in] integer
[in] real
[in] real
[in] integer vector
[in] real vector
[out] integer
[out] text

Description
Unique identifier of the solver instance (returned by create).
The number of equations of the system.
Function that calculates the residuals of the
system.
Initial values of the variables and the solution
at the end.
Lower bound for the variables.
Upper bound for the variables.
EMSO problem specific data (only to pass back
to resFn, lsetup and lsolve)
The relative accuracy
The absolute accuracy (optionally a vector)
The vector of integer options, see ??.
The vector of real options, see ??.
Return flag, see ??.
A text space where error messages should be
copied.

initial guess y is given and the solution should be returned on the


same vector.
Warning: The parameter rtol is always a real scalar but atol
can be a vector depending on the options at iopt.

9.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 scientific
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.

9.3.1

Writing External Solver Services in Fortran


As mentioned in sections ?? and 9.2, in order to implement a new
external solver service a set of functions must be implemented. In

126

9 Developing new Solvers


files NLASolverTemplate.f and DAESolverTemplate.f
found at interfaces directory are given template implementations for an external NLA and DAE solvers services in Fortran.
The template files 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.

9.3.2

Writing External Solver Services in C


As mentioned in section 9.2, in order to implement a new external solver service a set of functions must be implemented.
In file ExterSolverTpl.c found at interfaces directory
a template implementation for a external solver service in C is
given. This file makes use of the interface definitions declared at
ExternalSolver.h. Note that the header file should not be
modified by the user.
The template file 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.

9.3.3

Writing External Solver Services in C++


As mentioned in section 9.2, in order to implement a new external
solver service a set of functions must be implemented. When using C++ this functions actually are member functions of a class.
In file ExternalSolverTlp.cpp found at interfaces directory a template implementation for an external solver service
in C++ is given. This file makes use of the interface definitions
declared in file ExternlaSolver.h. Note that the header
file should not be modified by the user. When included in a
C++ file the ExternlaSolver.h, besides the C interfaces,
declares two C++ pure abstract class called NLASolverBase
and DAESolverBase.
The C++ template file has a skeleton implementation that should
be filled 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 files or to implement a class deriving from the
given pure virtual classes as made in the C++ template file.

9.4

Documenting Solver Services


Under construction: To be documented.

Das könnte Ihnen auch gefallen