advanced guide gproms

236
gPROMS Advanced User Guide Process Systems Enterprise Ltd. Bridge Studios 107a Hammersmith Bridge Road London W6 9DA United Kingdom Tel : +44 (0)20 8563 0888 Fax : +44 (0)20 8563 0999 Release 2.3—February 2004 c 1997–2004 Process Systems Enterprise Limited. ModelEnterprise and gPROMS are trademarks of Process Systems Enter- prise Limited. All other registered and pending trademarks mentioned in this material are considered the sole property of their respective owners. All rights reserved. No part of this material may be copied, distributed, published, retransmit- ted or modified in any way without the prior written consent of Process Systems Enterprise Limited. This document is the property of Process Sys- tems Enterprise Ltd., and must not be reproduced in any manner without prior written permission.

Upload: mruet04

Post on 12-Nov-2014

1.155 views

Category:

Documents


173 download

DESCRIPTION

gPROMS

TRANSCRIPT

Page 1: Advanced Guide Gproms

gPROMS Advanced User Guide

Process Systems Enterprise Ltd.

Bridge Studios107a Hammersmith Bridge Road

London W6 9DAUnited Kingdom

Tel : +44 (0)20 8563 0888Fax : +44 (0)20 8563 0999

Release 2.3—February 2004

c© 1997–2004 Process Systems Enterprise Limited.

ModelEnterprise and gPROMS are trademarks of Process Systems Enter-prise Limited. All other registered and pending trademarks mentioned inthis material are considered the sole property of their respective owners. Allrights reserved.No part of this material may be copied, distributed, published, retransmit-ted or modified in any way without the prior written consent of ProcessSystems Enterprise Limited. This document is the property of Process Sys-tems Enterprise Ltd., and must not be reproduced in any manner withoutprior written permission.

Page 2: Advanced Guide Gproms

Disclaimer

gPROMS provides an environment for modelling the behaviour of complex sys-tems. While gPROMS provides valuable insights into the behaviour of the systembeing modelled, this is not a substitute for understanding the real system andany dangers that it may present. Except as otherwise provided, all warranties,representations, terms and conditions express and implied (including implied war-ranties of satisfactory quality and fitness for a particular purpose) are expresslyexcluded to the fullest extent permitted by law. gPROMS provides a frameworkfor applications which may be used for supervising a process control system andinitiating operations automatically. gPROMS is not intended for environmentswhich require fail-safe characteristics from the supervisor system. Process Sys-tems Enterprise Limited (”PSE”) specifically disclaims any express or impliedwarranty of fitness for environments requiring a fail-safe supervisor. Nothing inthis disclaimer shall limit PSE’s liability for death or personal injury caused byits negligence.

Page 3: Advanced Guide Gproms

The license management portion of this product is based on:SentinelLM c©1996–1997 Rainbow Technologies, Inc.

All rights reserved.

FLEXlm c©2001 GLOBEtrotter Software, Inc. A Macrovision Company.All rights reserved.

SentinelLM is a trademark of Rainbow Technologies, Inc.

FLEXlm is a trademark of GLOBEtrotter Software, Inc.

Code from LAPACK and BLAS is used in gPROMS.We would like to thank the authors

E. Anderson, Z. Bai, C. Bischof, S. Blackford, J. Demmel,J. Dongarra, J. Du Croz, A. Greenbaum, S. Hammarling,

A. McKenney, and D. Sorensenfor making the code publicly available.

The gPROMS Model Builder interface uses the following packages:ANTLR (http://www.antlr.org).

Xerces and Xalan (http://xml.apache.org/) from the Apache XML Project.

Components from NetBeans (http://www.netbeans.org).

To support the multiple shooting implementation fordynamic optimisation, gPROMS makes use of HQP, a solver

for non-linearly constrained, large-scale optimization problems.

HQP is free software. The programs and libraries in HQP aredistributed under the GNU Lesser General Public License (LGPL)as published by the Free Software Foundation. The source code

for HQP is available at http://www.sourceforge.net/projects/hqp.

We would like to thank HQP’s author, Ruediger Franke of ABB, forhis help in developing the interface from gPROMS to HQP.

Page 4: Advanced Guide Gproms

To support Mixed Integer Optimisation, gPROMS makes use of a serverwhich uses GLPK (http://www.gnu.org/software/glpk/glpk.html),

the GNU Linear Programming Kit. The source code for the server,including the GLPK, is included in the gPROMS distribution,under the terms of the GNU General Public License (GPL).

To support the Distributed Computing facility,gPROMS makes use of omniORB2, an Object Request Broker (ORB)which implements specification 2.3 of the Common Object Request

Broker Architecture (CORBA).

omniORB2 is copyright AT&T Laboratories, Cambridge.It is free software. The programs in omniORB2 are distributed

under the GNU General Public Licence as published bythe Free Software Foundation. The libraries in omniORB2 aredistributed under the GNU Library General Public Licence.

Page 5: Advanced Guide Gproms

gPROMS Advanced User Guide

Contents

1 Introduction 10

1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

1.2 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2 Dynamic Optimisation in gPROMS 12

2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2.2 What is dynamic optimisation? . . . . . . . . . . . . . . . . . . . . . . . 14

2.3 What is the mathematical problem? . . . . . . . . . . . . . . . . . . . . 16

2.3.1 The process model . . . . . . . . . . . . . . . . . . . . . . . . . . 16

2.3.2 The initial conditions . . . . . . . . . . . . . . . . . . . . . . . . 16

2.3.3 The objective function . . . . . . . . . . . . . . . . . . . . . . . . 17

2.3.4 Bounds on the optimisation decision variables . . . . . . . . . . . 18

2.3.5 Other constraint types . . . . . . . . . . . . . . . . . . . . . . . . 18

2.4 What is a “solution” of a dynamic optimisation problem? . . . . . . . . 20

2.4.1 Classes of control variable profile . . . . . . . . . . . . . . . . . . 21

2.4.2 Control variable profiles in gPROMS . . . . . . . . . . . . . . . . 22

2.5 Specifying dynamic optimisation problems in gPROMS . . . . . . . . . 24

2.5.1 PROCESS entities for optimisation . . . . . . . . . . . . . . . . . . 24

2.5.2 The OPTIMISATION entity . . . . . . . . . . . . . . . . . . . . . . 25

2.6 Point Optimisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

2.6.1 Specification of point OPTIMISATION Entities . . . . . . . . . . 30

2.6.2 Specification of steady-state optimisation problems . . . . . . . . 30

4

Page 6: Advanced Guide Gproms

gPROMS Advanced User Guide

2.7 Running optimisation problems in gPROMS . . . . . . . . . . . . . . . . 31

2.8 Results of the optimisation run . . . . . . . . . . . . . . . . . . . . . . . 33

2.8.1 The comprehensive optimisation report file . . . . . . . . . . . . 33

2.8.2 The optimisation report file . . . . . . . . . . . . . . . . . . . . . 34

2.8.3 The SCHEDULE file . . . . . . . . . . . . . . . . . . . . . . . . . . 35

2.8.4 The point file . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

2.9 Other features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

3 Parameter Estimation in gPROMS 37

3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

3.2 What is parameter estimation? . . . . . . . . . . . . . . . . . . . . . . . 39

3.3 What is the mathematical problem? . . . . . . . . . . . . . . . . . . . . 44

3.3.1 The process model . . . . . . . . . . . . . . . . . . . . . . . . . . 44

3.3.2 The experimental data . . . . . . . . . . . . . . . . . . . . . . . . 45

3.3.3 The objective function . . . . . . . . . . . . . . . . . . . . . . . . 46

3.3.4 Statistical variance models . . . . . . . . . . . . . . . . . . . . . 46

3.4 Specifying parameter estimation problems . . . . . . . . . . . . . . . . . 49

3.4.1 PROCESS entities for parameter estimation . . . . . . . . . . . . . 49

3.4.2 The ESTIMATION entity . . . . . . . . . . . . . . . . . . . . . . . 50

3.4.3 The EXPERIMENT entities . . . . . . . . . . . . . . . . . . . . . . . 53

3.5 Running parameter estimation problems . . . . . . . . . . . . . . . . . . 56

3.6 Results of the parameter estimation run . . . . . . . . . . . . . . . . . . 58

3.6.1 Output files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

3.6.2 The advanced statistical analysis tool . . . . . . . . . . . . . . . 61

4 Using Foreign Objects 66

4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

4.1.1 What is a Foreign Object? . . . . . . . . . . . . . . . . . . . . . . 67

4.1.2 Why use a Foreign Object? . . . . . . . . . . . . . . . . . . . . . 67

4.1.3 What’s in a name? . . . . . . . . . . . . . . . . . . . . . . . . . . 68

Contents 5

Page 7: Advanced Guide Gproms

gPROMS Advanced User Guide

4.1.4 Some rules and terminology . . . . . . . . . . . . . . . . . . . . . 68

4.1.5 Classes and instances . . . . . . . . . . . . . . . . . . . . . . . . 69

4.1.6 What do I need to read next? . . . . . . . . . . . . . . . . . . . . 69

4.2 Using Foreign Objects in gPROMS entities . . . . . . . . . . . . . . . . 71

4.2.1 Using Foreign Objects in gPROMS MODELs . . . . . . . . . . . . 71

4.2.2 Foreign Object values and their specification . . . . . . . . . . . 74

4.2.3 Consistency checking and validation . . . . . . . . . . . . . . . . 78

5 Using Foreign Processes 82

5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

5.1.1 Applications of the FPI . . . . . . . . . . . . . . . . . . . . . . . 83

5.1.2 What is the FPI? . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

5.1.3 Chapter outline . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

5.2 The elementary communication tasks . . . . . . . . . . . . . . . . . . . . 85

5.2.1 The PAUSE elementary communication task . . . . . . . . . . . . 86

5.2.2 The GET elementary communication task . . . . . . . . . . . . . . 88

5.2.3 The SEND elementary communication task . . . . . . . . . . . . . 93

5.2.4 The SENDMATHINFO elementary communication task . . . . . . . 95

5.2.5 The LINEARISE elementary task . . . . . . . . . . . . . . . . . . 97

5.3 Using the FPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

5.3.1 The standard FPI implementation . . . . . . . . . . . . . . . . . 107

5.3.2 Using non-standard FPI implementations . . . . . . . . . . . . . 107

5.4 FPI performance issues . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

5.4.1 Effects of model size . . . . . . . . . . . . . . . . . . . . . . . . . 111

5.4.2 Effects of model re-initialisation . . . . . . . . . . . . . . . . . . 111

5.4.3 Effects of results logging . . . . . . . . . . . . . . . . . . . . . . . 112

5.4.4 Effects of FPI communication overheads . . . . . . . . . . . . . . 113

6 Using Physical Properties for Simple Materials 114

6.1 The set of physical properties supported by gPROMS . . . . . . . . . . 116

Contents 6

Page 8: Advanced Guide Gproms

gPROMS Advanced User Guide

6.2 Incorporating physical properties in MODELs . . . . . . . . . . . . . . . . 120

6.3 Using MODELs incorporating physical property calculations . . . . . . . . 123

6.3.1 Example 1: Explicit specification within a primitive MODEL . . . 123

6.3.2 Example 2: Explicit specification within a higher-level MODEL . . 124

6.3.3 Example 3: Explicit specification within a PROCESS . . . . . . . . 124

6.3.4 Example 4: Implicit specification via parameter propagation . . 124

6.4 The Multiflash physical property interface . . . . . . . . . . . . . . . . . 128

6.4.1 Error handling in the gPROMS/Multiflash interface . . . . . . . 128

6.4.2 Units of measurement . . . . . . . . . . . . . . . . . . . . . . . . 130

6.4.3 Equilibrium flash methods in Multiflash . . . . . . . . . . . . . . 130

6.4.4 Constructing a Multiflash input file . . . . . . . . . . . . . . . . . 130

6.4.5 Using Multiflash stream types . . . . . . . . . . . . . . . . . . . . 134

6.5 The IK-CAPE physical property interface . . . . . . . . . . . . . . . . . 140

6.6 The CAPE-OPEN thermodynamics interface . . . . . . . . . . . . . . . 141

6.6.1 CAPE-OPEN Property Packages and Property Systems . . . . . 141

6.6.2 Using CAPE-OPEN Property Packages and Property Systems . 141

6.6.3 CAPE-OPEN Property Package report . . . . . . . . . . . . . . 143

6.6.4 CAPE-OPEN properties . . . . . . . . . . . . . . . . . . . . . . . 143

7 Using Physical Properties for Complex Materials 148

7.1 General concepts for electrolyte system modelling . . . . . . . . . . . . . 150

7.1.1 Species and phases . . . . . . . . . . . . . . . . . . . . . . . . . . 150

7.1.2 Vapour-liquid equilibrium . . . . . . . . . . . . . . . . . . . . . . 151

7.1.3 Liquid-phase reactions . . . . . . . . . . . . . . . . . . . . . . . . 151

7.1.4 Liquid-solid equilibrium . . . . . . . . . . . . . . . . . . . . . . . 152

7.1.5 Fugacity and activity coefficients . . . . . . . . . . . . . . . . . . 152

7.2 Electrolytic physical property methods . . . . . . . . . . . . . . . . . . . 153

7.3 The OLI physical property interface . . . . . . . . . . . . . . . . . . . . 159

7.3.1 Electrolyte system report file . . . . . . . . . . . . . . . . . . . . 160

7.3.2 Error handling in the OLI interface . . . . . . . . . . . . . . . . . 160

Contents 7

Page 9: Advanced Guide Gproms

gPROMS Advanced User Guide

A Dynamic Optimisation Example 162

A.1 Project tree (ReactorOpt.gPJ) . . . . . . . . . . . . . . . . . . . . . . . 163

A.2 VARIABLE TYPE entities in ReactorOpt.gPJ . . . . . . . . . . . . . . . . 164

A.3 Text contained within the Reactor MODEL entity . . . . . . . . . . . . . 165

A.4 BatchReaction MODEL entity . . . . . . . . . . . . . . . . . . . . . . . . 167

A.5 Text contained within the Optimise Reactor PROCESS entity . . . . . . 168

A.6 OPTIMISATION entity (OPTIMISE REACTOR) . . . . . . . . . . . . . . . . . 169

A.7 Sample optimisation report file (OPTIMISE REACTOR.out) . . . . . . . . 170

A.8 Sample gPROMS schedule file (OPTIMISE REACTOR.SCHEDULE) . . . . . 171

A.9 Sample point file (OPTIMISE REACTOR.point) . . . . . . . . . . . . . . . 172

A.10 Simulating the optimal solution within a PROCESS . . . . . . . . . . . . . 173

A.11 Interpretation of screen output . . . . . . . . . . . . . . . . . . . . . . . 175

B Backward Compatibility of Dynamic Optimisation Features 178

B.1 Importing of gPROMS v1.x .gOPT files . . . . . . . . . . . . . . . . . . . 179

B.2 Exporting of projects containing optimisation entities . . . . . . . . . . 179

B.3 Use of gOPT.param files . . . . . . . . . . . . . . . . . . . . . . . . . . . 179

C Parameter Estimation Example 182

C.1 Project tree (ReactorEst.gPJ) . . . . . . . . . . . . . . . . . . . . . . . 183

C.2 Variable Type entities in ReactorEst.gPJ . . . . . . . . . . . . . . . . 184

C.3 Text contained within the BatchReactor MODEL entity . . . . . . . . . . 185

C.4 Text contained within the Estimate Reactor PROCESS entity . . . . . . 187

C.5 PARAMETER ESTIMATION entity (ESTIMATE REACTOR) . . . . . . . . . . . 189

C.6 Text contained within the C13T1 EXPERIMENT entity . . . . . . . . . . . 190

C.7 Sample Optimisation Report File (ESTIMATE REACTOR.out) . . . . . . . 191

C.8 Sample Estimation Statistics File (ESTIMATE REACTOR.stat) . . . . . . 192

C.9 Sample summary sheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196

C.10 Sample parameter estimates sheet . . . . . . . . . . . . . . . . . . . . . 197

C.11 Sample variance matrix sheet . . . . . . . . . . . . . . . . . . . . . . . . 198

Contents 8

Page 10: Advanced Guide Gproms

gPROMS Advanced User Guide

C.12 Sample correlation matrix sheet . . . . . . . . . . . . . . . . . . . . . . . 199

C.13 Sample information matrix sheet . . . . . . . . . . . . . . . . . . . . . . 200

C.14 Part of a sample statistical significance sheet . . . . . . . . . . . . . . . 201

C.15 Sample measured variable sheet . . . . . . . . . . . . . . . . . . . . . . . 202

C.16 Overlay plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203

C.17 Residual plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204

C.18 Confidence ellipsoid plots . . . . . . . . . . . . . . . . . . . . . . . . . . 205

D Backward Compatibility of Parameter Estimation Features 206

D.1 Importing of gPROMS v1.x .gEST and .RUN files . . . . . . . . . . . . . 207

D.2 Exporting of projects containing parameter estimation entities . . . . . 207

D.3 Use of gEST.param files . . . . . . . . . . . . . . . . . . . . . . . . . . . 207

E Microsoft Excel Foreign Object and Foreign Process Interfaces 211

E.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212

E.2 Using Microsoft Excel Foreign Objects . . . . . . . . . . . . . . . . . . . 213

E.3 Creating Microsoft Excel Foreign Objects . . . . . . . . . . . . . . . . . 214

E.3.1 Specifying cell cross-references . . . . . . . . . . . . . . . . . . . 216

E.3.2 Using the method definition macro . . . . . . . . . . . . . . . . . 217

E.3.3 A simple example . . . . . . . . . . . . . . . . . . . . . . . . . . 218

E.3.4 Cell ranges for arrays with more than two dimensions . . . . . . 218

E.4 Using the Microsoft Excel Foreign Process Interface . . . . . . . . . . . 223

E.5 Creating Microsoft Excel Foreign Processes . . . . . . . . . . . . . . . . 225

E.5.1 Using the FPI definition macro . . . . . . . . . . . . . . . . . . . 226

E.6 Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227

E.7 An example problem with Microsoft Excel FOI and FPI . . . . . . . . . 228

Contents 9

Page 11: Advanced Guide Gproms

gPROMS Advanced User Guide

Chapter 1

Introduction

1.1 Overview

This manual describes several advanced features of the gPROMS package. These in-clude:

• Dynamic Optimisation in gPROMS (see chapter 2).

gPROMS can be used to optimise the steady-state and/or the dynamic behaviourof a continuous or batch process. Both plant design and operational optimisationcan be carried out. The form of the objective function and the constraints canbe quite general. Moreover, the optimisation decision variables can be eitherfunctions of time (“controls”) or time-invariant quantities.

• Parameter Estimation in gPROMS (see chapter 3).

gPROMS can be used to estimate the values of model parameters from the resultsof one or more experiments. Both steady-state and dynamic experiments can beused for this purpose. The experiments can employ different initial conditionsand/or operating sequences; the sets of variables measured by each experiment,as well as the times at which these measurements are taken, may also differ fromexperiment to experiment.

• The gPROMS Foreign Object Interface (see chapter 4).

Foreign Objects are external software components that provide certain compu-tational services to gPROMS MODELs. These include physical property packages,external unit operation modules, or even complete computational fluid dynam-ics (CFD) software packages. This chapter explains how to make use of ForeignObjects that are already interfaced to gPROMS.

• The gPROMS Foreign Process Interface (see chapter 5).

10

Page 12: Advanced Guide Gproms

gPROMS Advanced User Guide

The Foreign Process Interface (FPI) allows gPROMS simulations to interact withexternal software such as distributed control systems and operator training pack-ages, exchanging data and other information. The interaction takes the formof a special set of elementary actions within the gPROMS TASK language. FPIis particularly useful for embedding gPROMS simulations within larger softwaresystems.

• Physical Properties interfaces to gPROMS (see chapters 6 and 7).

Physical property packages form a special class of Foreign Objects (see above)that are encountered very frequently in practice. A number of widely-used phys-ical property packages are already interfaced to gPROMS. Chapter 6 describeshow to incorporate physical property calculations for ‘conventional’ materials ingPROMS models using the interfaces to Multiflash and IK-Cape or a CAPE-OPEN compliant physical properties package, while chapter 7 looks at more com-plex, electrolytic systems using the OLI package.

1.2 Prerequisites

A good understanding of gPROMS at an introductory level is essential for making themost of the facilities described in this manual. The “gPROMS Introductory User Guide”and/or the gPROMS Introductory Training Course provide the necessary background.

With the exception of Chapters 6 and 7, the chapters in this manual can be read inde-pendently of each other. For these chapters, understanding of the concepts presentedin Chapter 4 is a necessary prerequisite.

1.2. Prerequisites 11

Page 13: Advanced Guide Gproms

gPROMS Advanced User Guide

Chapter 2

Dynamic Optimisation ingPROMS

Contents

2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2.2 What is dynamic optimisation? . . . . . . . . . . . . . . . . . 14

2.3 What is the mathematical problem? . . . . . . . . . . . . . . 16

2.3.1 The process model . . . . . . . . . . . . . . . . . . . . . . . . . 16

2.3.2 The initial conditions . . . . . . . . . . . . . . . . . . . . . . . 16

2.3.3 The objective function . . . . . . . . . . . . . . . . . . . . . . . 17

2.3.4 Bounds on the optimisation decision variables . . . . . . . . . . 18

2.3.5 Other constraint types . . . . . . . . . . . . . . . . . . . . . . . 18

2.4 What is a “solution” of a dynamic optimisation problem? . 20

2.4.1 Classes of control variable profile . . . . . . . . . . . . . . . . . 21

2.4.2 Control variable profiles in gPROMS . . . . . . . . . . . . . . . 22

2.5 Specifying dynamic optimisation problems in gPROMS . . 24

2.5.1 PROCESS entities for optimisation . . . . . . . . . . . . . . . . . 24

2.5.2 The OPTIMISATION entity . . . . . . . . . . . . . . . . . . . . . 25

2.6 Point Optimisation . . . . . . . . . . . . . . . . . . . . . . . . 30

2.6.1 Specification of point OPTIMISATION Entities . . . . . . . . . 30

2.6.2 Specification of steady-state optimisation problems . . . . . . . 30

2.7 Running optimisation problems in gPROMS . . . . . . . . . 31

2.8 Results of the optimisation run . . . . . . . . . . . . . . . . . 33

2.8.1 The comprehensive optimisation report file . . . . . . . . . . . 33

2.8.2 The optimisation report file . . . . . . . . . . . . . . . . . . . . 34

2.8.3 The SCHEDULE file . . . . . . . . . . . . . . . . . . . . . . . . . 35

2.8.4 The point file . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

2.9 Other features . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

12

Page 14: Advanced Guide Gproms

gPROMS Advanced User Guide

2.1 Introduction

This chapter describes how gPROMS can be used to perform (dynamic) optimisationcalculations.

• In section 2.2, we describe the dynamic optimisation problem by using a smallexample. We use this example throughout this document to illustrate the dynamicoptimisation facilities provided by gPROMS.

• In section 2.3, we define the dynamic optimisation problem mathematically.

• In section 2.4, we define what constitutes a solution to the dynamic optimisationproblem.

• In section 2.5, we describe how to specify dynamic optimisation problems ingPROMS.

• In section 2.6, we describe how to specify point (including steady-state) optimi-sation problems in gPROMS.

• In section 2.7, we describe how optimisation problems are executed in gPROMS.

• In section 2.8, we explain the contents of the various output files that are gener-ated.

• In section 2.9, we discuss various other features of the optimisation capabilities ofgPROMS.

The optimisation capabilities in gPROMS have evolved significantly in recent versionsof the software. Appendix B considers some issues of backward compatibility withcorresponding features in earlier versions of gPROMS.

Some basic familiarity with the gPROMS language and concepts is assumed.

2.1. Introduction 13

Page 15: Advanced Guide Gproms

gPROMS Advanced User Guide

2.2 What is dynamic optimisation?

In order to introduce the various elements of the definition of the problem of dynamicoptimisation, we consider the semi-batch reactor shown in Figure 2.1. Two exothermicreactions are taking place:

A + B → C

B + C → D

where A and B are the raw materials, C the desirable product, and D the unwantedby-product.

CoolingWater

B + C DA + B C

Feed A Feed B

Figure 2.1: Batch Reactor

The reactor receives two independent inputs of pure A and B, and is cooled with coolingwater circulating through a coil. Starting with an empty reactor, we are free to varythe in-flows of A and B, as well as the cooling water flowrate.

For a given reactor design, our operational objective may be to determine the durationof the operation, and the time variation of the various material and energy flowratesover this duration, so as to maximise the final concentration of C. Of course, equipmentdesign and resource availability usually impose certain limits within which our controlmanipulations must be maintained—for instance, there is an upper limit on the availableflowrate of cooling water.

In general, the design of processes operating in the transient domain also leads toproblems that are similar to operational optimisation problems, but may have additionaldegrees of freedom. For instance, we may wish to determine the optimal geometry ofthe reactor in addition to the optimal way of operating it over time.

Because of the transient nature of the underlying process, both the operational and

2.2. What is dynamic optimisation? 14

Page 16: Advanced Guide Gproms

gPROMS Advanced User Guide

design problems considered above are applications of dynamic optimisation 1, and serveto introduce some of the important features of this problem in its most basic form.Some other complications that often arise in practical applications will be introducedlater.

1Often, the term “optimal control” is also used, especially for problems that involve control variablesbut no time-invariant parameters (see next section).

2.2. What is dynamic optimisation? 15

Page 17: Advanced Guide Gproms

gPROMS Advanced User Guide

2.3 What is the mathematical problem?

Here we provide a mathematical statement of the class of dynamic optimisation problemssolved by gPROMS:

2.3.1 The process model

We consider processes described by mixed differential and algebraic equations of theform:

f(x(t), x(t), y(t), u(t), v) = 0. (2.1)

Here x(t) and y(t) are the differential and algebraic variables in the model while x(t)are the time derivatives of the x(t) (i.e., x ≡ dx/dt). u(t) are the control variables andv the time invariant parameters to be determined by the optimisation. In the contextof the batch reactor example considered earlier, the differential variables will typicallycorrespond to fundamental conserved quantities (such as molar component holdups andinternal energy), while y will include various quantities related to them (e.g. componentmolar concentrations and temperature). The input flowrates of A, B and cooling waterare the control variables u while, in the design case, the volume of the reactor acts as atime invariant parameter v.

Note:

For simplicity, the mathematical description in this document assumes thatthe system behaviour is defined in terms of ordinary (with respect to time)differential and algebraic equations. However, the optimisation capabilitiesof gPROMS are equally applicable to mixed lumped and distributed systemsdescribed by general integral, partial differential and algebraic equations intime and one or more space dimensions.

2.3.2 The initial conditions

In general, gPROMS assumes that the initial (t = 0) condition of the system is describedin terms of a set of general non-linear relations of the form:

I(x(0), x(0), y(0), u(0), v) = 0. (2.2)

It is important to note that, once we fix the time variation of the controls, u(t) andthe values of any time invariant parameters, v, the modelling equations (2.1) together

2.3. What is the mathematical problem? 16

Page 18: Advanced Guide Gproms

gPROMS Advanced User Guide

with the initial conditions (2.2) completely determine the transient response of the sys-tem. In practice, we could determine this response by performing a gPROMS dynamicsimulation.

2.3.3 The objective function

Dynamic optimisation in gPROMS seeks to determine

• the time horizon, tf ,

• the values of the time invariant parameters, v, and

• the time variation of the control variables, u(t), over the entire time horizon t ∈[0, tf ],

so as to minimise (or maximise) the final value of a single variable z. This can bewritten mathematically as:

mintf ,v,u(t), t∈[0,tf ]

z(tf ) (2.3)

Here the objective function variable, z is one of either the differential variables x orthe algebraic variables y. In the context of the batch reactor example, tf would bethe duration of the batch reaction while z would be the concentration of component C(either a differential or an algebraic variable, depending on the model used).

The above form of the objective function is not as restrictive as might appear at first.In particular, it is worth noting that:

• Maximisation can be carried out as well as minimisation.

• If we wish to optimise a function φ(x(tf ), x(tf ), y(tf ), u(tf ), v) of several variablesinstead of a single variable, we can simply add an extra algebraic equation to themodel:

z = φ(x, x, y, u, v) (2.4)

The additional computational cost incurred because of this model extension isusually negligible.

• If we wish to minimise or maximise the integral of a function ψ(x, x, y, u, v) overthe entire time horizon, we can simply add the differential equation:

z = ψ(x, x, y, u, v) (2.5)

together with the initial condition:

z(0) = 0 (2.6)

2.3. What is the mathematical problem? 17

Page 19: Advanced Guide Gproms

gPROMS Advanced User Guide

We can easily verify that this is equivalent to:

z(tf ) =

∫ tf

0ψ(x(t), x(t), y(t), u(t), v) dt (2.7)

Again, very little additional computational cost is incurred in doing this.

• Minimising the time horizon itself can be achieved by adding the equation:

z = 1 (2.8)

together with the initial condition (2.6).

2.3.4 Bounds on the optimisation decision variables

In practice, the time horizon tf will often be subject to certain lower and upper bounds:

tminf ≤ tf ≤ tmax

f (2.9)

In some cases, tf will, in fact, be fixed at a given value, t∗f . This can be achieved simply

by setting tminf = tmax

f = t∗f .

As we have already seen in the batch reactor example, it is likely that the controlvariables and time invariant parameters will also be subject to lower and upper bounds:

umin ≤ u(t) ≤ umax, ∀t ∈ [0, tf ] (2.10)

vmin ≤ v ≤ vmax (2.11)

2.3.5 Other constraint types

2.3.5.1 End-point constraints

In some applications, it is necessary to impose certain conditions that the system mustsatisfy at the end of the operation. These are called end-point constraints. For instance,in the batch reactor example, we may require:

• the final amount of material in the reactor to be at certain prescribed value;

and also

• the final temperature to lie within given limits.

In the first case, we have an equality end-point constraint of the type:

w(tf ) = w∗ (2.12)

where w is one of the system variables (x or y). In the second case, we have an inequalityend-point constraint :

wmin ≤ w(tf ) ≤ wmax (2.13)

2.3. What is the mathematical problem? 18

Page 20: Advanced Guide Gproms

gPROMS Advanced User Guide

2.3.5.2 Interior point constraints

We can also have constraints that hold at one or more distinct times tI during the timehorizon (e.g. at the middle of the horizon). These are called interior-point constraints.These may be represented mathematically as:

wminI ≤ w(tI) ≤ wmax

I (2.14)

where w is a system variable, and tI is a given time.

We note that both interior and end-point constraints are special cases of point con-straints. However, for convenience, gPROMS treats them separately. It also treats anyconstraints that have to be satisfied at the initial time t = 0 as interior-point constraints.

2.3.5.3 Path constraints

We may also have certain constraints that must be satisfied at all times during thesystem operation. If these path constraints are equalities, then often they can simplybe added to the system model (2.1) effectively converting one of the control variablesu(t) into an algebraic variable y. More often, they are inequalities of the form:

wmin ≤ w(t) ≤ wmax, ∀t ∈ [0, tf ] (2.15)

For instance, in our batch reactor example, we may require that the temperature neverexceed a certain value so as to avoid some unwanted side-reactions that are not explicitlyconsidered by our model.

Although we have assumed in equations (2.12) to (2.15) that the various constraints areimposed on a single variable w, this is not really restrictive. If we wanted to constraina function φ of several variables, we could simply define a new variable w through anadditional equation:

w = φ(x, x, y, u, v) (2.16)

and then impose the required constraints on w.

2.3. What is the mathematical problem? 19

Page 21: Advanced Guide Gproms

gPROMS Advanced User Guide

2.4 What is a “solution” of a dynamic optimisation prob-lem?

Let us start by summarising the mathematical statement of the dynamic optimisationproblem as defined in the previous section:

Objective function: mintf ,v,u(t), t∈[0,tf ]

z(tf )

subject to

Process model : f(x(t), x(t), y(t), u(t), v) = 0 t ∈ [0, tf ]Initial conditions: I(x(0), x(0), y(0), u(0), v) = 0

Time horizon bounds: tminf ≤ tf ≤ tmax

f

Control variable bounds: umin ≤ u(t) ≤ umax t ∈ [0, tf ]Time invariant parameter bounds: vmin ≤ v ≤ vmax

End-point constraints: w(tf ) = w∗

wmin ≤ w(tf ) ≤ wmax

Interior point constraints: wminI ≤ w(tI) ≤ wmax

I

Path constraints: wmin ≤ w(t) ≤ wmax t ∈ [0, tf ]

Clearly, a “solution” to this problem comprises three key elements:

• The value of the time horizon, tf .

• The values of the time invariant parameters, v.

• The variation of the control variables u(t) over the time horizon from t = 0 tot = tf .

As has already been mentioned, if these are specified, we can solve the model equations(2.1) to determine how the system behaves over the time horizon of interest, obtainingvalues of x(t) and y(t) for all t ∈ [0, tf ]. We can then evaluate the objective function(2.3), and also check whether the various end-point and path constraints (2.12–2.15)are satisfied.

Normally, there will be more than one combination of tf , v and u(t) that satisfies thebounds (2.9–2.10) and the constraints (2.12–2.15)—and this, of course, is what givesrise to the optimisation problem. The latter aims to find the combination that producesthe best value of the objective function while satisfying all the constraints.

2.4. What is a “solution” of a dynamic optimisation problem? 20

Page 22: Advanced Guide Gproms

gPROMS Advanced User Guide

2.4.1 Classes of control variable profile

For the above dynamic optimisation problem to be well defined, we need to be rathermore specific regarding the type of the variation of the control variables over time thatwe are willing to consider. For instance, we could have:

Time, t

Con

trol

Var

iabl

e

Time, t

Con

trol

Var

iabl

e

Time, t

Con

trol

Var

iabl

e

(b) Piecewise linear controls

(c) Piecewise linear continuous controls (d) Polynomial controls

Time, t

Con

trol

Var

iabl

e

(a) Piecewise constant controls

Figure 2.2: Different types of control variable profile

• Piecewise-constant controls—these remain constant at a certain value over a cer-tain part of the time horizon before jumping discretely to a different value overthe next interval (see Figure 2.2(a)).

• Piecewise-linear controls—these take a certain linear time variation over a certainpart of the time horizon before jumping discretely to a different linear variationover the next interval (see Figure 2.2(b)).

• Piecewise-linear continuous controls—these are similar to the piecewise-linear con-trols described above, with the additional requirement that their values be con-tinuous at the interval boundaries (see Figure 2.2(c)).

2.4. What is a “solution” of a dynamic optimisation problem? 21

Page 23: Advanced Guide Gproms

gPROMS Advanced User Guide

• Controls that vary smoothly over time—perhaps as polynomials of a given degree(see Figure 2.2(d)).

It is important to appreciate that, in most cases, the choice of the form of the controlvariables is an engineering rather than a mathematical issue: it very much dependson the capabilities of the actual control system (automatic or manual!) that we willeventually use to implement these controls on the real plant. For instance, piecewise-constant controls may often be preferable to other types as they are much easier toimplement.

2.4.2 Control variable profiles in gPROMS

The dynamic optimisation facilities in gPROMS support piecewise-constant and piecewise-linear controls of the types shown in Figures 2(a) and 2(b) respectively. These are byfar the most commonly encountered in practical applications. However, if necessary, itis relatively straightforward to introduce several other types of control. For instance, apiecewise-linear continuous control of the type shown in Figure 2.2(c) can be defined byadding the equations:

z = U (2.17)

u = z + α (2.18)

where:

• z is a new differential variable with initial condition z(0) = 0;

• U is a new piecewise-constant control variable (cf. Figure 2.2(a)) to be determinedby the optimisation;

• α is a new time invariant parameter representing the initial value of u (i.e. u(0) =α), to be determined by the optimisation.

We note that this is equivalent to:

u(t) = α+

∫ t

0U(τ) dτ (2.19)

which expresses the fact that the time gradient of a piecewise-linear continuous controlis a piecewise-constant function of time.

Also a cubic polynomial control variation of the form:

u(t) = α+ βt+ γt2 + δt3 (2.20)

2.4. What is a “solution” of a dynamic optimisation problem? 22

Page 24: Advanced Guide Gproms

gPROMS Advanced User Guide

can be introduced by adding the following to the model equations (2.1):

z = 1 (2.21)

u = α+ βz + γz2 + δz3 (2.22)

Together with the initial condition z(0) = 0, equation (2.21) effectively defines z as time.By virtue of equation (2.22), the variable u becomes one of the algebraic variables y to bedetermined by solving the model equations. The actual control variation is determinedby the values of α, β, γ and δ which should now be treated as time invariant parametersv.

2.4. What is a “solution” of a dynamic optimisation problem? 23

Page 25: Advanced Guide Gproms

gPROMS Advanced User Guide

2.5 Specifying dynamic optimisation problems in gPROMS

Most of the information needed for specifying dynamic optimisation problems in gPROMSwill be present in the various entities used for dynamic simulation of the process. Someadditional information will have to be specified in separate entities.

Below, we consider each of these sources of information in turn.

2.5.1 PROCESS entities for optimisation

Just like a dynamic simulation experiment, a dynamic optimisation problem in gPROMSis defined in a PROCESS entity. In fact, there is no difference in syntax between a simu-lation and an optimisation PROCESS. Thus, the latter specifies most of the informationrequired for defining mathematically the optimisation problem to be solved:

• The UNIT specification, together with parameter SETting, effectively determine theset of model equations f(.) = 0 (equation (2.1)).

• The ASSIGN specifications mark certain system variables as fixed for the purposesof dynamic simulation. As far as optimisation is concerned, some of these variableswill be either controls or time invariant parameters (see Section 2.5.2).

• The INITIAL specifications provide the initial conditions I(.) = 0 (equation (2)).

• An optional PRESET specification may be used to override the default initial guessesand bounds for any system variable. In particular, the bounds on the controls andtime invariant parameters to be used for the purposes of the dynamic optimisationare either those specified here or the default values specified in the VARIABLE TYPE

entities.

• There are two standard mathematical solvers available in gPROMS for solvingdynamic optimisation problems. The first (default) implements a control vectorparameterisation algorithm based via single-shooting. This can be specified in theSOLUTIONPARAMETERS section of a PROCESS entity through the syntax:

SOLUTIONPARAMETERS

DOSolver := "CVP_SS" ;

The second solver is an implementation of control vector parameterisation viamultiple-shooting. This is specified in the SOLUTIONPARAMETERS using:

SOLUTIONPARAMETERS

DOSolver := "CVP_MS" ;

In general, CVP MS is more suited than CVP SS for solving dynamic optimisationproblems with relatively few differential variables but a large number of control

2.5. Specifying dynamic optimisation problems in gPROMS 24

Page 26: Advanced Guide Gproms

gPROMS Advanced User Guide

variables and/or control intervals. A detailed description of the two solvers andthe various parameters that can be used for configuring their precise behaviour isgiven in section 10.6 of the “gPROMS Introductory User Guide”.

• Any SCHEDULE specification in the PROCESS is ignored for the purposes of dynamicoptimisation.

Experience indicates that most of the effort in defining a dynamic optimisation prob-lem is, in fact, incurred in the construction of a robust model of your process. Thiswill probably be exactly the same model as that used for dynamic simulations withingPROMS. However, it is worth investing some effort in ensuring that it behaves prop-erly for the entire range of possible values of the control variables and time invariantparameters. In particular, you should check that the differential and algebraic variablesx and y remain within any specified bounds even for extreme values of u and v.

The various VARIABLE TYPE, MODEL and PROCESS entities for the batch reactor examplein this chapter are shown within a project called ‘‘ReactorOpt.gPJ’’ in appendices A.1to A.5.

2.5.2 The OPTIMISATION entity

The complete specification of a dynamic optimisation problem requires some additionalinformation which is not provided in the gPROMS PROCESS entity. This includes infor-mation on the time horizon and the objective function, the form of the control variableprofiles, and any end-point and path constraints that have to be imposed on the process.

All of the above information has to be specified in a separate entity which appearsunder the Optimisations entry in the gPROMS project tree. In order to create suchan entity:

1. Pull-down the Entity menu from the top pane in gPROMS ModelBuilder.

2. Click on New Entity. A dialog box will appear.

3. Choose OPTIMISATION for the Entity type and fill in the Name field. The nameof the OPTIMISATION entity must be the name of the relevant PROCESS entity inthe gPROMS project.

The structure of the OPTIMISATION entity is shown in table 2.1, with keywords high-lighted in typewriter style CAPITALS. Most of the information presented is adequatelyexplained by the comments in the second column. However, it is worth clarifying somepoints regarding the selection of control variables and time invariant parameters (sec-tion 2.5.2.1), and also the specification of interior point constraints (section 2.5.2.2) andpath constraints (section 2.5.2.3).

An example of such an entity is shown in appendix A.6 for the batch reactor consideredin this chapter.

2.5. Specifying dynamic optimisation problems in gPROMS 25

Page 27: Advanced Guide Gproms

gPROMS Advanced User Guide

Note:

• To omit any lower bound from the optimisation, specify it as -1E30.

• To omit any upper bound from the optimisation, specify it as 1E30.

2.5.2.1 Specifications of control variables and time–invariant parameters

All of the variables specified as PIECEWISE CONSTANT, PIECEWISE LINEAR and TIME INVARIANT

must be ASSIGNed in the gPROMS PROCESS entity. Any variables that are ASSIGNedin the PROCESS entity but are not included here will be kept constant at the value towhich they are assigned. Effectively, these variables are removed from the optimisationproblem.

By default, the initial control-variable profiles are taken to be constant (at the ASSIGNedvalue) throughout the time horizon. Similarly, the initial guesses for time-invariantparameters is also taken to be the corresponding ASSIGNed values. Also the upper andlower bounds are taken, by default, to be the values specified in VARIABLE TYPE entitiesor in the PRESET section of the PROCESS entity (see section 2.5.1).

The defaults for initial control-variable profiles may be overridden by an INITIAL PROFILE

specification of the following type:

INITIAL PROFILE

{InitialValue} : {LowerBound} : {UpperBound}...{InitialValue} : {LowerBound} : {UpperBound}

where InitialValue, LowerBound and UpperBound are real constants. For piecewise-constant controls, one such line must be included for each of the time intervals specifiedin INTERVALS earlier in the file, with each specification referring to the value of thecontrol over the corresponding interval. For piecewise-linear controls, there must be twosuch lines for each interval, corresponding to the value of the control at the beginningand at the end of the interval respectively.

The default initial guesses for time-invariant parameters may be overridden by anINITIAL VALUE specification of the type:

INITIAL VALUE

{InitialValue} : {LowerBound} : {UpperBound}

where {InitialValue}, {LowerBound} and {UpperBound} are real constants.

2.5. Specifying dynamic optimisation problems in gPROMS 26

Page 28: Advanced Guide Gproms

gPROMS Advanced User Guide

Specification Comments# Lines starting with hash (#) symbols are treated as comments.

HORIZON Time horizon specification{IV} : {LB} : {UB} Initial guess for tf followed by tmin

f and tmax

f (cf. constraint (2.9)).

INTERVALS Intervals in control variable profiles.{number of intervals}{IV} : {LB} : {UB} Initial guess, lower bound and upper bound for the length of each

interval....{IV} : {LB} : {UB}

PIECEWISE CONSTANT Specification of a piecewise-constant control variable.{variable name} Its full gPROMS path name.{initial profile specification} Optional—see Section 2.5.2.1.

PIECEWISE LINEAR Specification of a piecewise-linear control variable.{variable name} Its full gPROMS path name.{initial profile specification} Optional—see Section 2.5.2.1.

TIME INVARIANT Specification of a time-invariant parameter.{variable name} Its full gPROMS path name.{initial value specification} Optional—see Section 2.5.2.1.

ENDPOINT EQUALITY Specification of a variable on which an equality end-point con-straint is to be imposed.

{variable name} Its full gPROMS path name.{value} The value w∗ in constraint (2.12).

ENDPOINT INEQUALITY Specification of a variable on which an inequality end-point con-straint is to be imposed.

{variable name} Its full gPROMS path name.{LB} : {UB} The values wmin and wmax in constraint (2.13).

INTERIORPOINT Specification of a variable on which an interior-point constraintis to be imposed.

{variable name} Its full gPROMS path name.{LB} : {UB} The values wmin and wmax in constraint (2.14).

Note: an alternate syntax for specifying varying interior-pointconstraints will be presented later.

MAXIMISE or MINIMISE{variable name} The objective function variable z (see equation (2.3)).

Table 2.1: Syntax of a gPROMS OPTIMISATION entity

2.5. Specifying dynamic optimisation problems in gPROMS 27

Page 29: Advanced Guide Gproms

gPROMS Advanced User Guide

2.5.2.2 Interior point constraints

The INTERIORPOINT specifications force the named variable to lie within the specifiedlower and upper bounds at a set of discrete times, namely the time-interval boundaries2.The most frequent use of such specifications is as an approximate way of enforcing pathconstraints (cf. equation (2.15))—the latter are not handled directly by gPROMS.

In some applications, it can be useful to specify different bounds at each of the time-interval boundaries—for example, a batch reaction procedure might require the tem-perature to lie in a narrower range in the final stages of reaction than in the earlierstages. This can be achieved in gPROMS through the use of an alternative syntax forthe INTERIORPOINT segment of the input file as shown in Figure 2.3.

Specification Comments

INTERIORPOINT Specification of a variable on which an interior-pointconstraint is to be imposed.

{variable name} Its full gPROMS path name.VARYING Keyword to indicate distinct bounds at each interval

boundary.{lower bound} : {upper bound} Bounds at start of first interval....{lower bound} : {upper bound} Bounds at start of last interval.

Figure 2.3: Alternative syntax for INTERIORPOINT constraints

2.5.2.3 Inequality path constraints

It is worth noting that enforcing a path constraint at the interval boundaries does notautomatically guarantee that the constraints are not violated within the intervals. Formany applications, this is not a major problem as path constraints tend to be “soft”and minor violations can be tolerated. However, if this is not the case, a more stringentway of enforcing the constraint is to define a violation variable z within the relevantMODEL entity in the gPROMS project through the equation:

z =(

max(0, wmin − w,w − wmax))2

(2.23)

with initial condition (2.6), and then impose the additional end-point equality con-straint:

z(tf ) = 0 (2.24)

2This includes the initial point but not the final one. An ENDPOINT INEQUALITY specification shouldbe used to enforce a final-time constraint, if necessary.

2.5. Specifying dynamic optimisation problems in gPROMS 28

Page 30: Advanced Guide Gproms

gPROMS Advanced User Guide

It can be verified that constraint (2.24) can be satisfied if and only if the original pathconstraint is satisfied. In many cases, it is still worthwhile retaining the INTERIORPOINTconstraints on w as this often leads to improved numerical performance. It may also bebetter to relax constraint (2.24) to an inequality constraint:

z(tf ) ≤ ε (2.25)

where ε is a small positive tolerance.

An implementation of path constraints is shown for the batch reactor example in theREACTOR MODEL entity in appendix A.3, the INITIAL section of the OPTIMISE REACTOR

PROCESS entity in appendix A.5, and the OPTIMISE REACTOR OPTIMISATION entity inappendix A.6.

2.5. Specifying dynamic optimisation problems in gPROMS 29

Page 31: Advanced Guide Gproms

gPROMS Advanced User Guide

2.6 Point Optimisation

By default, gPROMS treats optimisation problems as dynamic ones, optimising the be-haviour of a system over a finite non-negative time horizon. However, in some cases, itis desired to optimise a system at a single time point—performing a so-called “point”optimisation. From the mathematical point of view, this is equivalent to solving a purelyalgebraic problem in which a generally nonlinear objective function is maximised or min-imised subject to generally nonlinear constraints by manipulating a set of optimisationdecision variables that may be either continuous or discrete.

2.6.1 Specification of point OPTIMISATION Entities

The specification of a point optimisation problem in gPROMS is achieved simply byomitting the HORIZON part of the corresponding OPTIMISATION Entity. It is worthnoting that point OPTIMISATION Entities:

• may contain TIME INVARIANT controls as well as ENDPOINT INEQUALITY and ENDPOINT EQUALITY

constraints; such constraints are interpreted as simple algebraic constraints to besatisfied by the optimal solution;

• must not contain time-varying controls (PIECEWISE CONSTANT or PIECEWISE LINEAR

ones) or INTERIORPOINT constraints, or specifications of control INTERVALS, all ofwhich are meaningless in this context.

Moreover,

• the value of the global TIME variable used in any ASSIGNments in the corre-sponding PROCESS Entity is taken to be zero;

• any INITIAL conditions specified in corresponding PROCESS Entity are taken asadditional equality constraints to be satisfied by the optimisation.

Note that, for the purposes of point optimisation, any time derivative terms of the form$x, that may occur in gPROMS MODEL Entities, are treated as distinct to the variablesx.

2.6.2 Specification of steady-state optimisation problems

A steady-state optimisation problem is a special case of a point optimisation one. Assuch, its specification must obey all the rules outlined in section 2.6.1

If the underlying model is a dynamic one (i.e. its MODEL Entities contain one or moretime derivative terms of the form $x) , then the initial-condition of the system must bespecified as STEADY STATE in the INITIAL section of the PROCESS Entity.

2.6. Point Optimisation 30

Page 32: Advanced Guide Gproms

gPROMS Advanced User Guide

2.7 Running optimisation problems in gPROMS

As explained in section 2.5, before an optimisation problem can be executed, it mustbe specified completely in a gPROMS project that contains:

• one or more MODEL entities;

• a PROCESS entity named, for example, ppp; and

• an OPTIMISATION entity named ppp.

In order to run the optimisation problem:

1. Select either the PROCESS entity or its associated OPTIMISATION entity in thegPROMS project tree.

2. Pull down the Activitiesmenu from the top toolbar. If you selected the PROCESSentity in step 1, then both the Simulate... and Optimise... Activities willbe available (see figure 2.4). If you selected the OPTIMISATION entity in step 1then only Optimise... will be available (see figure 2.5).

3. Select Optimise.... If there are any syntactical, cross-referencing mistakes etc.these will be detected. Otherwise, the gRMS and execution windows are openedby gPROMS, the optimisation run starts and output is directed to the screen ofthe execution window.

Figure 2.4: Executing an optimisation run via a PROCESS entity.

2.7. Running optimisation problems in gPROMS 31

Page 33: Advanced Guide Gproms

gPROMS Advanced User Guide

Figure 2.5: Executing an optimisation run via an OPTIMISATION entity.

2.7. Running optimisation problems in gPROMS 32

Page 34: Advanced Guide Gproms

gPROMS Advanced User Guide

2.8 Results of the optimisation run

The execution of an optimisation run will generate four files in the Results folder of theCase:

• PPP

• PPP.out

• PPP.SCHEDULE

• PPP.point

where PPP is the name (in capitals) of the optimisation entity that has been executedto produce these results (cf. section 2.7 above).

2.8.1 The comprehensive optimisation report file

Double-clicking on the report entry, PPP, in the Case tree causes a report window toappear in the main window, see Figure 2.6. The report, presented in HTML format,includes:

• a table of contents that allows quick access to the information listed below via“hyperlinks”;

• general information such as the date and time of the execution of the activity, itsfinal status and the value of the objective function;

• information on the various optimisation decision variables (time horizon, controlinterval durations, and time-invariant and time-varying controls), including thevalues of:

– the initial guess used,

– the final value obtained,

– the lower and upper bounds,

– the Lagrange multipliers corresponding to the above bounds.

All active bounds are automatically highlighted.

2.8. Results of the optimisation run 33

Page 35: Advanced Guide Gproms

gPROMS Advanced User Guide

Optimisation report in case

Optimisation entity

executed

Optimisation entity

executed

Optimisation report in Case

Figure 2.6: Comprhensive optimisation report.

2.8.2 The optimisation report file

The PPP.out file contains a summary report on the optimisation run in a simple textformat, including:

• the outcome of the optimisation run;

• the final value of the objective function;

• the final value of the time horizon and the lengths of the time intervals;

• the final values of the time-invariant parameters, and the control-variable profiles;the latter are specified in terms of a single value per interval for piecewise-constantcontrols, and a pair of values for piecewise-linear controls (as usual, correspondingto the value of the control at the start and end of each interval); and

• the values of variables on which end-point and/or interior-point constraints wherespecified, at the corresponding final and/or interior points.

The file also contains computational statistics on the performance of the numericalmethod.

A sample PPP.out file is listed in appendix A.7.

2.8. Results of the optimisation run 34

Page 36: Advanced Guide Gproms

gPROMS Advanced User Guide

2.8.3 The SCHEDULE file

The PPP.SCHEDULE presents the most recent optimisation solution point in the formof a gPROMS SCHEDULE, as shown for the batch reactor example in appendix A.8.

The SCHEDULE file can be used to reproduce the detailed results of the optimisation bycarrying out a simulation activity within gPROMS. This provides you access to the fullfacilities of the gPROMS Results Management System (gRMS). In order to do this:

1. Paste the contents of the SCHEDULE file except for the final END statement into therelevant PROCESS entity of your gPROMS project.

2. Also, paste the lines that appear inside the first RESET statement in the SCHEDULEinto the ASSIGN section of the PROCESS entity.

A PROCESS entity that contains these changes is shown for the batch reactor examplein appendix A.10. It is useful for you to compare it with the original PROCESS entity inappendix A.5 and the SCHEDULE results file in appendix A.8.

Note: the contents of the SCHEDULE file do not necessarily represent an optimal or evena feasible solution to the problem: if the optimisation run is interrupted by the user,or ends without finding a satisfactory solution, the file will simply show the point lastconsidered by gPROMS. Only if a comment at the top of the file states the following:

# Final Optimisation Status : Optimal Solution Found

should the results be relied upon as a (locally) optimal solution.

2.8.4 The point file

The PPP.point file is generated at every iteration of the optimisation calculation. Itcontains the same information as the SCHEDULE file, but in the format of an OPTIMISATION

entity (except that constraints are not reproduced). This is useful if there is a need torestart an optimisation after a system crash or other catastrophic event, or, following asuccessful solution, to provide a good ‘initial guess’ for a slightly altered optimisationproblem.

A sample PPP.point file is listed in appendix A.9.

2.8. Results of the optimisation run 35

Page 37: Advanced Guide Gproms

gPROMS Advanced User Guide

2.9 Other features

The following apply to the current version of gPROMS:

• The initial conditions specified in the PROCESS entity must be:

– equations of the form:

VariableName = Value ;

where VariableName is the full gPROMS pathname of a differential or alge-braic variable, and Value is a numerical value;

– or equations of the form:

$VariableName = Value ;

– or the steady-state specification:

INITIAL

STEADY_STATE

• Many applications involve the optimisation of the initial values of some of thesystem variables. For instance, it may be that you want to determine the op-timal initial amount of catalyst to be charged to a batch reactor. This kind ofrequirement can easily be accommodated as follows:

– In the MODEL entity containing the variable, z, whose initial value is to beoptimised, introduce:

∗ an additional variable, z0, of the same type as z;

∗ an additional variable, δz, of type NoType;

∗ the additional equation:δz = z − z0

– In the PROCESS entity,

∗ assign z0 to a default value:

ASSIGN

Z0 := 1.0 ;

∗ set the initial value of δz to zero:

INITIAL

DeltaZ = 0.0 ;

– In the OPTIMISATION entity, declare z0 as a time-invariant parameter, speci-fying an initial guess and lower and upper bounds for it.

2.9. Other features 36

Page 38: Advanced Guide Gproms

gPROMS Advanced User Guide

Chapter 3

Parameter Estimation ingPROMS

Contents

3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

3.2 What is parameter estimation? . . . . . . . . . . . . . . . . . 39

3.3 What is the mathematical problem? . . . . . . . . . . . . . . 44

3.3.1 The process model . . . . . . . . . . . . . . . . . . . . . . . . . 44

3.3.2 The experimental data . . . . . . . . . . . . . . . . . . . . . . . 45

3.3.3 The objective function . . . . . . . . . . . . . . . . . . . . . . . 46

3.3.4 Statistical variance models . . . . . . . . . . . . . . . . . . . . 46

3.4 Specifying parameter estimation problems . . . . . . . . . . 49

3.4.1 PROCESS entities for parameter estimation . . . . . . . . . . . . 49

3.4.2 The ESTIMATION entity . . . . . . . . . . . . . . . . . . . . . . 50

3.4.3 The EXPERIMENT entities . . . . . . . . . . . . . . . . . . . . . . 53

3.5 Running parameter estimation problems . . . . . . . . . . . 56

3.6 Results of the parameter estimation run . . . . . . . . . . . 58

3.6.1 Output files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

3.6.2 The advanced statistical analysis tool . . . . . . . . . . . . . . 61

37

Page 39: Advanced Guide Gproms

gPROMS Advanced User Guide

3.1 Introduction

This chapter describes how gPROMS can be used to perform parameter estimation forcomplex models using both dynamic and steady-state experimental data.

• In section 3.2, we describe the parameter estimation problem via a small example.We use this example throughout the chapter to illustrate the parameter estimationfacilities provided by gPROMS.

• In section 3.3, we define the mathematical problem that is solved by gPROMS.

• In section 3.4, we describe the entities that are necessary for specifying parameterestimation problems.

• In section 3.5, we describe how parameter estimation problems are executed, ex-plain the contents of the various output files that are generated, and give detailsof the gPROMS advanced statistical analysis tool.

• Appendix C shows the project entities for the batch reactor described in section 3.2and the output of the graphical front-end.

The parameter estimation capabilities in gPROMS have evolved significantly in recentversions of the software. Appendix D considers some issues of backward compatibilitywith corresponding features in earlier versions of gPROMS.

Some basic familiarity with the gPROMS language and concepts is assumed.

3.1. Introduction 38

Page 40: Advanced Guide Gproms

gPROMS Advanced User Guide

3.2 What is parameter estimation?

In order to introduce the various elements of the parameter estimation problem, weconsider the batch reactor shown in figure 3.1. The reactor is used to carry out thefollowing liquid-phase endothermic reaction:

A + B → C + D.

An electrical heating element is used to provide the necessary heat to the reactor.

A + B C + D

ElectricalHeatingElement

Figure 3.1: Batch reactor

Experimental and theoretical evidence indicates that the order of the reaction withrespect to both A and B is one. We also know that the kinetic constant of the reactionfollows an Arrhenius-type temperature dependence relationship.

Based on this information, and assuming perfect mixing and ideal liquid mixture be-haviour, we can construct the following mathematical model for the process:

Component mass balance

dMi

dt= νirV , i = A, B, C, D.

Energy balancedH

dt= rV (−∆HR) +Q.

Reaction rater = kCACB.

3.2. What is parameter estimation? 39

Page 41: Advanced Guide Gproms

gPROMS Advanced User Guide

Arrhenius temperature dependence

k = k0e−E/RT .

Component concentrations

Ci =Mi

V, i = A, B, C, D,

V =∑

i=A,B,C,D

Mi

ρi.

Energy content

H =∑

i=A,B,C,D

MiHi,

Hi = αi(T − Tref ) +βi

2(T 2 − T 2

ref ) , i = A, B, C, D.

Table 3.1 summarises the parameters and variables that appear in this model. Thecorresponding gPROMS MODEL entity is given in appendix C.3.

Model Parameters

E Reaction activation energyk0 Arrhenius constantTref Reference temperatureαi, βi Specific molar enthalpy coefficients of component i∆HR Heat of reactionνi Stoichiometric coefficient of component iρi Molar density of component i

Model Variables

Ci Molar concentration of component iH Total enthalpy content of the reactor

Hi Specific molar enthalpy of component ik Reaction constantMi Molar holdup of component iQ Heating loadr Rate of the reactionT Reactor temperatureV Total volume of liquid in the reactor

Table 3.1: Parameters and variables in batch reactor model

Before this model can be used to simulate or optimise the operation of the reactor,all parameters that appear in it must be assigned fixed values. Imagine, however, asituation where the kinetic characteristics of the reaction are unknown, i.e. we do not

3.2. What is parameter estimation? 40

Page 42: Advanced Guide Gproms

gPROMS Advanced User Guide

know the values of k0, E and ∆HR. In order to determine these, we can perform anumber of experiments and measure the values of some or all process variables.

The data from four typical experiments are shown in table 3.3. In this particularexample, the same conditions are used for all the experiments, as given in table 3.2.The duration of each experiment is 400 s, the reactor is initially loaded with 100 molof A, 100 mol of B, 1 mol of C and 1 mol of D, and the initial temperature is 293 K.The heating element power supply is set to 505 kW for the first 100 s of operation andto zero thereafter. The reactor temperature and the concentrations of reactant A andproduct C are automatically measured every 10 seconds.

We note that, for any given set of values of the unknown parameters, the model equationscan be solved to predict the reactor behaviour at the experimental conditions. Forinstance, figure 3.2 compares the predicted variation of CA(t) and T (t) for k0 = 6.5 ×10−4 m3 mol−1 s, E = 20000 J mol−1 and ∆HR = 55000 J mol−1, against the dataobtained from the first experiment. It can be seen that the model predictions are ratherpoor.

In practice, we obviously need to determine the values of the unknown parameters,k0, E and ∆HR, in order to maximise the probability that the model will predict thevalues obtained from the experiments. This is the objective of the parameter estimationproblem.

Initial Conditions Heating Policy

MA = 100 molMB = 100 mol Q = 505 kW , 0 ≤ t(s) ≤ 100MC = 1 mol Q = 0, 100 < t(s) ≤ 400MD = 1 molT = 293 K

Table 3.2: Conditions for batch reactor experiments #1 to #4

3.2. What is parameter estimation? 41

Page 43: Advanced Guide Gproms

gPROMS Advanced User Guide

Experiment Time (s) Temperature (K) Concentrations (mol m−3)# t T CA CC

10 412.549 3746.911 898.55220 504.179 2518.600 2358.859

1 30 603.486 1504.120 3634.89540 715.300 883.783 4407.92250 837.841 548.051 4849.769· · · · · · · · · · · ·10 411.804 3700.752 898.21620 504.530 2520.929 2380.372

2 30 604.027 1502.396 3626.62540 714.709 894.412 4388.87450 837.154 545.142 4828.031· · · · · · · · · · · ·10 412.823 3705.683 896.79920 503.740 2513.977 2386.384

3 30 604.359 1516.819 3633.75940 715.539 895.847 4419.04450 836.518 551.290 4796.965· · · · · · · · · · · ·10 411.235 3711.353 902.85820 503.830 2526.062 2409.363

4 30 603.157 1527.653 3653.77940 716.325 895.004 4400.96450 837.703 543.662 4824.272· · · · · · · · · · · ·

Table 3.3: Data from the batch reactor experiments

3.2. What is parameter estimation? 42

Page 44: Advanced Guide Gproms

gPROMS Advanced User Guide

Figure 3.2: Experimental data vs. model predictions for batch reactor (experiment #1)

3.2. What is parameter estimation? 43

Page 45: Advanced Guide Gproms

gPROMS Advanced User Guide

3.3 What is the mathematical problem?

3.3.1 The process model

For the purposes of illustrating the mathematical nature of the parameter estimationproblem, we consider processes described by mixed differential and algebraic equationsof the form:

f(x(t), x(t), y(t), u(t), p, θ) = 0, (3.1)

where:

• x(t) and y(t) are the differential and algebraic variables in the model; x(t) are thetime derivatives of x(t) (i.e. x ≡ dx/dt);

• u(t) and p are the time-varying control variables and time-invariant control pa-rameters, respectively (these define the form of the experiment(s) being carriedout); and

• θ is the set of unknown model parameters to be estimated.

Note:

For simplicity, the mathematical description in this document assumes thatthe system behaviour is defined in terms of ordinary (with respect to time)differential and algebraic equations. However, the parameter estimationcapabilities of gPROMS are equally applicable to mixed lumped and dis-tributed systems described by general integral, partial differential and alge-braic equations in time and one or more space dimensions.

For the purposes of parameter estimation, we assume that the initial condition of thesystem (3.1) is defined in terms of the initial values of a subset of the variables x(0),y(0) and/or x(0)1, i.e.

subset { x(0), x(0), y(0) } = v,

where v are given values. We note that v also play an important role in defining theprecise nature of the experiment(s) being carried out.

For instance, in the batch reactor example considered earlier,

1Normally (i.e. for DAE systems of index 0 or 1), the number of such initial conditions will equalthe number of differential variables x in the system.

3.3. What is the mathematical problem? 44

Page 46: Advanced Guide Gproms

gPROMS Advanced User Guide

• MA, MB , MC , MD and H are differential variables, while CA, CB , CC , CD, HA,HB, HC , HD, r, k, V and T are algebraic variables;

• the heating load, Q, is a time-varying control variable; and

• k0, E and ∆HR are the unknown parameters to be estimated.

The initial condition of the system is specified in terms of the following initial values:

MA(0), MB(0), MC(0), MD(0) and T (0).

We note that the number of initial condition specifications is equal to the number ofdifferential variables in the system (5). However, it is not necessary that the initialcondition be specified in terms of the initial values of these variables; for instance, it ismuch more convenient to specify T (0) rather than H(0).

3.3.2 The experimental data

A parameter estimation problem makes use of data gathered from a set of experiments.Each experiment is characterised by a set of conditions under which it is performed,namely:

• the overall duration;

• the initial conditions, v;

• the variation of the control variables, u(t); and

• the values of the time-invariant parameters, p.

For the batch reactor example, table 3.2 contains the above information for the fourbatch reactor experiments. The first column describes the initial conditions (i.e. theinitial amounts of the different components and the initial reactor temperature), whilethe second column specifies the overall duration and the variation of the control variableQ (i.e. the heating policy). Note that although in this example all the experiments arecharacterised by the same set of conditions, this is not a requirement of any of themethods presented later in this chapter.

During each experiment data are collected. These are of the form:

(tijk , zijk)

where zijk is the kth value measured for variable zj during experiment i, and tijk is thetime at which this measurement was taken. Here, zj can be one of the differential oralgebraic variables, x and y.

For the batch reactor example, table 3.3 contains the temperature and concentrationmeasurements taken during four experiments. Note that the measurement times do notneed to be equi-spaced, nor is it necessary for all measured variables to be recorded atthe same times.

3.3. What is the mathematical problem? 45

Page 47: Advanced Guide Gproms

gPROMS Advanced User Guide

3.3.3 The objective function

As mentioned earlier, parameter estimation attempts to determine values for the un-known parameters, θ, in order to maximise the probability that the mathematical modelwill predict the values obtained from the experiments. Assuming independent, normallydistributed measurement errors, εijk, with zero means and standard deviations, σijk, thismaximum likelihood goal can be captured through the following objective function:

Φ =N

2ln (2π) +

1

2min

θ

NE∑

i=1

NVi∑

j=1

NMij∑

k=1

[

ln(

σ2ijk

)

+(zijk − zijk)

2

σ2ijk

]

, (3.2)

where the symbols in (3.2) have the following definitions:

N : Total number of measurements taken during all the experiments.θ: Set of model parameters to be estimated.

The acceptable values may be subject to given lower and upper bounds,i.e. θL ≤ θ ≤ θU .

NE: Number of experiments performed.NVi: Number of variables measured in the ith experiment.NMij : Number of measurements of the jth variable in the ith experiment.σ2

ijk: Variance of the kth measurement of variable j in experiment i.

zijk: kth measured value of variable j in experiment i.zijk: kth (model-)predicted value of variable j in experiment i.

3.3.4 Statistical variance models

The maximum likelihood objective function (3.2) gives the flexibility for several typesof variance models to be specified by the user. These take the general form:

σ2 = σ2 (β, z, z) , (3.3)

where β is a set of parameters. Table 3.4 shows the variance models provided bygPROMS. The following points should be noted:

• The set of parameters, β, in the general statistical variance model (3.3), comprisethe parameters ω and γ, as appropriate, and can either be given fixed values ordetermined as part of the optimisation.

• In a CONSTANT VARIANCE model, the measurement error has a constant standarddeviation ω. In a CONSTANT RELATIVE VARIANCE model, the measurement errordepends on the magnitude of the predicted or measured values. In case of aHETEROSCEDASTIC variance model, the measurement error also depends on themeasured or predicted values, but is proportional to zγ/2 or zγ/2, respectively.

3.3. What is the mathematical problem? 46

Page 48: Advanced Guide Gproms

gPROMS Advanced User Guide

gPROMS Keyword Mathematical Description

CONSTANT VARIANCE σ2 = ω2

CONSTANT RELATIVE VARIANCE PREDICTED VALUES σ2 = ω2 ·(

z2 + ε)

CONSTANT RELATIVE VARIANCE MEASURED VALUES σ2 = ω2 ·(

z2 + ε)

HETEROSCEDASTIC PREDICTED VALUES σ2 = ω2 ·(

z2 + ε)γ

HETEROSCEDASTIC MEASURED VALUES σ2 = ω2 ·(

z2 + ε)γ

Table 3.4: Statistical variance models

• ε is a very small but non-zero number calculated by gPROMS. This ensures thatthe variance has a meaningful definition for measured or predicted values that areequal to zero or very small. The value of ε is AbsoluteTolerance2, taken fromthe solver specification in the SOLUTIONPARAMETERS of the corresponding PROCESS

(see section 3.4).

• If ω is fixed in the CONSTANT VARIANCE model, this reduces to a LEAST SQUARES

model.

• If γ = 0 in the HETEROSCEDASTIC variance models, these both reduce to theirrespective CONSTANT VARIANCE models.

• If γ = 1 in the HETEROSCEDASTIC variance models, these reduce to their respectiveCONSTANT RELATIVE VARIANCE models. Thus, any of the variance models in table3.4 can be described generally by one of the HETEROSCEDASTIC formulations.

In principle, each measured variable in each experiment may be described by a differentstatistical variance model characterised by its own set of values for the parameters β.Thus:

(i) a measured variable (e.g. R101.T) may be characterised by different variance mod-els in two (or more) different experiments (e.g. CONSTANT VARIANCE in the firstexperiment and HETEROSCEDASTIC in the second); or

(ii) a measured variable may be characterised by the same variance model in two ormore different experiments but the values of the parameters, β, may be differentin the two cases (e.g. CONSTANT VARIANCE with different values of ω); or

(iii) a measured variable may have the same statistical variance model with the sameparameters over all experiments.

All of the above options are supported by gPROMS. As will be described in sections 3.4.2and 3.4.3, (i) and (ii) are effected through information inserted by the user in theEXPERIMENT) entities, while (iii) is effected through information in the ESTIMATION en-tity.

3.3. What is the mathematical problem? 47

Page 49: Advanced Guide Gproms

gPROMS Advanced User Guide

Note:

As the estimation of the parameters and the statistical analysis of the resultsdepend strongly on the given or estimated standard deviations of the mea-surement errors, attention should be paid to the formulation of the variancemodel and the values of the respective variance model parameters. You areencouraged to specify the variance model and the values of the accordingparameters as precisely as possible. gPROMS will determine optimal esti-mates for the values of the variance model parameters within the boundsthat you specify.Note that, if the available data are insufficient for the estimation, the statis-tical analysis may show large confidence intervals for the associated param-eters, even though the fit may be very good.

3.3. What is the mathematical problem? 48

Page 50: Advanced Guide Gproms

gPROMS Advanced User Guide

3.4 Specifying parameter estimation problems

Most of the information needed for specifying parameter estimation problems in gPROMSwill already be present in the various entities used for dynamic simulation of the process.Some additional information will have to be specified in separate entities.

Below, we consider each of these sources of information in turn.

3.4.1 PROCESS entities for parameter estimation

Just like a dynamic simulation experiment, a parameter estimation problem in gPROMSis defined in a PROCESS entity. In fact, there is no difference in syntax between a simula-tion and a parameter estimation PROCESS. The latter specifies most of the informationrequired for defining mathematically the parameter estimation problem to be solved:

• The UNIT specification, together with parameter SETting, effectively determinesthe set of model equations (3.1).

• The ASSIGN specifications mark certain system variables as fixed for the purposesof dynamic simulation. As far as parameter estimation is concerned, some of thesevariables will belong to one of the following categories:

– time-varying control variables;

– time-invariant control parameters; or

– unknown parameters to be estimated.

It is very important to note that, for the purposes of parameter estimation, un-known parameters must be declared as VARIABLEs in gPROMS MODEL entities, andnot as PARAMETERs2. Of course, once the parameter estimation problem has beensolved successfully and their values have been found, they can either be declaredas PARAMETERs (SET to the estimated value) or be left as VARIABLEs (ASSIGNed tothe estimated value).

• The INITIAL specifications are used to specify the default initial conditions forthe experiments. These have to be equations of the form

VariableName = Value ;

where VariableName is the full gPROMS pathname of a differential or algebraicvariable, and Value is a numerical value or expression.

Note that the initial values specified here are only defaults and can be overwrittenfor individual experiments (see section 3.4.2 below).

2This is consistent with the general gPROMS rule that PARAMETERs can never be the result of anygPROMS calculation.

3.4. Specifying parameter estimation problems 49

Page 51: Advanced Guide Gproms

gPROMS Advanced User Guide

• gPROMS provides a mathematical solver that is specifically designed for solvingmaximum likelihood optimisation problems of the type described in section 3.3.3.The solver can be specified in the SOLUTIONPARAMETERS section of a PROCESS entitythrough the syntax:

SOLUTIONPARAMETERS

PESolver := "MXLKHD" ;

Obviously, a specification in the simple form shown above is redundant sinceMXLKHD is already the default solver. However, the solver has a number of pa-rameters that can be used for configuring its precise behaviour for any particularproblem being solved. A detailed description of these is given in section 10.7.1 ofthe “gPROMS Introductory User Guide”3.

• Any SCHEDULE specification in the PROCESS is ignored for the purposes of param-eter estimation.

Experience indicates that most of the effort in defining a parameter estimation prob-lem is, in fact, incurred in the construction of a robust model of your process. Thiswill probably be exactly the same model as that used for dynamic simulations withingPROMS. However, it is worth investing some effort in ensuring that it behaves prop-erly over the entire range of possible parameter values. In particular, you should checkthat the differential and algebraic variables x and y remain within any specified boundseven for extreme values of u, p and θ.

The various VARIABLE TYPE, MODEL and PROCESS entities for the batch reactor examplein this chapter are shown within a project called “ReactorEst.gPJ” in appendices C.1to C.4.

3.4.2 The ESTIMATION entity

The complete specification of a parameter estimation problem requires some additionalinformation which is not provided in the gPROMS PROCESS entity. This includes in-formation on the unknown parameters to be estimated, the number of experimentsthat were performed and the statistical variance models to be used for the measuredvariables.

All of the above information has to be specified in a separate entity which appears underthe Estimations entry in the gPROMS project tree. In order to create such an entity:

1. Pull-down the Entity menu from the top pane in gPROMS ModelBuilder.

2. Click on New Entity. A dialog box will appear.

3It is particularly important to consider whether you need to request the solver to employ automaticscaling of your problem; see the description of parameter Scaling in section 10.7.1 of the “gPROMSIntroductory User Guide”.

3.4. Specifying parameter estimation problems 50

Page 52: Advanced Guide Gproms

gPROMS Advanced User Guide

3. Choose ESTIMATION for the Entity type and fill in the Name field. The name ofthe Estimation entity must be the name of the relevant PROCESS entity in thegPROMS project.

The structure of the ESTIMATION entity is shown in table 3.5, with keywords highlightedin typewriter style CAPITALS. The information presented is explained by the commentsin the second column. The following additional points should be noted:

• The MEASURE section indicates that the particular measured variable is describedby the specified statistical variance model with one set of values for its parametersfor all the experiments listed in the RUNS section. If a measured variable is to havedifferent variance models and/or different sets of values for the parameters of thevariance models, then the variance models should be specified in the MEASURE

sections of the EXPERIMENTS entities described in section 3.4.3, and not in theESTIMATION entity.

• The syntax shown in table 3.5 for the variance models is the most general form.Variations are allowed; for example:

MEASURE

R101.T

HETEROSCEDASTIC MEASURED_VALUES

(2.5 : 0 : 5; 0.8)

indicates that the measured variable R101.T is described by a heteroscedasticvariance model where ω is to be determined by the optimisation but γ is fixed ata value of 0.8.

• If the qualifier MEASURED VALUES or PREDICTED VALUES is omitted from theCONSTANT RELATIVE VARIANCE or HETEROSCEDASTIC variance model names, it isassumed that the model is on the MEASURED VALUES, i.e.

MEASURE

R101.T

CONSTANT_RELATIVE_VARIANCE

(2.5 : 0 : 5)

is treated as

MEASURE

R101.T

CONSTANT_RELATIVE_VARIANCE MEASURED_VALUES

(2.5 : 0 : 5)

3.4. Specifying parameter estimation problems 51

Page 53: Advanced Guide Gproms

gPROMS Advanced User Guide

Specification Comments

# Lines starting with hash (#) symbols are treated as comments.

ESTIMATE Specify parameter to be estimated.{variable name} Full gPROMS pathname.{IV}:{LB}:{UB} Initial guess, followed by lower and upper bounds on its value

MEASURE (optional) Specify variance model over all experiments for a particular vari-able.

{variable name} Full gPROMS pathname.{variance model} Keyword from table 3.4.({IV}:{LB}:{UB}; Initial guess, followed by lower and upper bounds for ω;{IV}:{LB}:{UB}) Initial guess, followed by lower and upper bounds for γ (if

HETEROSCEDASTIC model is used).The minimum lower bound and maximum upper bound on γ are0 and 1, respectively.

RUNS Specify experimental runs.{run name} Run name.{run name}... For each run name, name1, used in this entity, there should exist

an EXPERIMENT entity called name1 in the gPROMS project.

Table 3.5: Format of an ESTIMATION entity

3.4. Specifying parameter estimation problems 52

Page 54: Advanced Guide Gproms

gPROMS Advanced User Guide

The ESTIMATION entity for the batch reactor example presented in section 3.2 is givenin appendix C.5. The unknown parameters to be estimated are:

• The Arrhenius coefficient, k0 (gPROMS pathname R101.ARRHENIUSCONSTANT).The initial guess for this parameter is 5E-4 and the lower and upper bounds onits value are 1E-4 and 1E-3 respectively.

• The reaction activation energy, E (gPROMS pathname R101.ACTIVATIONENERGY).The initial guess for this parameter is 15000 and the lower and upper bounds onits value are 10000 and 20000 respectively.

• The heat of reaction, ∆HR (gPROMS pathname R101.REACTIONENTHALPY). Theinitial guess for this parameter is 55000 and the lower and upper bounds on itsvalue are 35000 and 75000 respectively.

In this example, each measured variable is to be described by the same variance modelfor all the four experiments that were performed. Hence:

• The concentration of reactant A, CA (gPROMS pathname R101.C(1)), and theconcentation of product C, CC (gPROMS pathname R101.C(3)), are both de-scribed by HETEROSCEDASTIC models on the PREDICTED VALUES. The initial guessfor ω is 0.1, with lower and upper bounds of 0.01 and 3 respectively, while theinitial guess for γ is 0.5 with bounds of 0 and 1.

• The reactor temperature, T (gPROMS pathname R101.T), is also described by aHETEROSCEDASTIC model. The initial guess for ω is 0.1, with bounds of 0.01 and3. However, γ is fixed at zero (the measurement error for the temperature is aconstant value and does not depend on the size of T ). As explained in section 3.3.4,this is equivalent to:

MEASURE

R101.T

CONSTANT_VARIANCE

(0.1 : 0.01 : 3)

The final part of the ESTIMATION entity shown in appendix C.5 indicates that four ex-periments were performed with the batch reactor (see table 3.3). These have been giventhe names C13T1, C13T2, C13T3 and C13T4.

3.4.3 The EXPERIMENT entities

As specified in table 3.5, for each experimental run name, name1, provided under theRUNS section of a ESTIMATION entity, there should be a corresponding EXPERIMENT entityentitled name1. In order to create such an entity:

3.4. Specifying parameter estimation problems 53

Page 55: Advanced Guide Gproms

gPROMS Advanced User Guide

Specification Comments

# Lines starting with hash (#) symbols are treated as com-ments.

INITIAL CONDITION Specify initial conditions for experiment.{variable name} {value} Full gPROMS pathname, followed by initial variable value.{variable name} {value}...

MEASURE Specify measurement data.{variable name} Full gPROMS pathname.{variance model} (optional) Keyword from table 3.4.({IV}:{LB}:{UB}; Initial guess, followed by lower and upper bounds for ω;{IV}:{LB}:{UB}) Initial guess, followed by lower and upper bounds for γ (if

HETEROSCEDASTIC model is used).{time} {value} Data pairs.{time} {value}...

INTERVALS Specify intervals for time-varying control variable profiles.{number of intervals} There follows one line per interval. . .{duration} Interval duration.{duration}...

PIECEWISE CONSTANT Specify a piecewise constant time-varying control variable,u.

{variable name} Full gPROMS pathname.{value (interval 1)} Variable value in each interval.{value (interval 2)}...

TIME INVARIANT Specify the value of a time-invariant parameter, p.{variable name} Full gPROMS pathname.{value} Variable value.

Table 3.6: Format of an EXPERIMENT entity

3.4. Specifying parameter estimation problems 54

Page 56: Advanced Guide Gproms

gPROMS Advanced User Guide

1. Pull-down the Entity menu from the top pane in gPROMS ModelBuilder.

2. Click on New Entity. A dialog box will appear.

3. Choose EXPERIMENT for the Entity type and fill in the Name field.

This EXPERIMENT entity is used to specify:

1. The conditions under which the experiment was performed. These include:

(a) the initial conditions for the experiment (these can only be specified in termsof initial values for a subset of the process variables);

(b) the values of the time-invariant control parameters; and

(c) the profiles of the time-varying control variables.

Currently, only piecewise constant control variables are supported. Theseremain constant at a certain value over a certain part of the time horizonbefore jumping discontinuously to a different value over the next interval.They are by far the most common kind of time-varying control variablesencountered in practice.

2. The measured variables and their measured values that were obtained during theexperiment.

3. (Optional). The types of statistical variance models and the initial guesses andbounds on the associated parameters. This is only required for measured variableswith different variance models and/or different sets of values for the parametersof the variance models in different experiments.

The structure of such a file is shown in table 3.6, with keywords highlighted in typewriterstyle CAPITALS. The information presented is explained by the comments in the secondcolumn.

The EXPERIMENT entity for the first batch reactor experiment shown in table 3.3 is givenin appendix C.6.

3.4. Specifying parameter estimation problems 55

Page 57: Advanced Guide Gproms

gPROMS Advanced User Guide

3.5 Running parameter estimation problems

As explained in the previous section, in order to execute a parameter estimation prob-lem, it must be first specified completely in a gPROMS project that contains:

• one or more MODEL entities;

• a PROCESS entity named, for example, PPP ;

• an ESTIMATION entity also named PPP which contains a RUNS section with one ormore experiment names name1, name2 etc.; and

• EXPERIMENT entities called name1, name2 etc.

In order to run the parameter estimation problem:

1. Select either the PROCESS entity or its associated ESTIMATION entity in the gPROMSproject tree.

2. Pull down the Activitiesmenu from the top toolbar. If you selected the PROCESSentity in step 1 then both the Simulate... and Estimate... Activities willbe available (see figure 3.3). If you selected the ESTIMATION entity in step 1 thenonly Estimate... will be available (see figure 3.4).

3. Select Estimate.... If there are any syntactical, cross-referencing mistakes etc.,these will be detected. Otherwise, the gRMS and execution windows are openedby gPROMS, the parameter estimation run starts and output is directed to thescreen of the exectution window.

3.5. Running parameter estimation problems 56

Page 58: Advanced Guide Gproms

gPROMS Advanced User Guide

Figure 3.3: Executing a parameter estimation run via a PROCESS entity.

Figure 3.4: Executing a parameter estimation run via a ESTIMATION entity.

3.5. Running parameter estimation problems 57

Page 59: Advanced Guide Gproms

gPROMS Advanced User Guide

3.6 Results of the parameter estimation run

3.6.1 Output files

The execution of a parameter estimation run will generate four files in the Results

sub-directory of the CASE:

• PPP

• PPP.out

• PPP.stat

• PPP.stat-mr

where PPP is the name (in capitals) of the parameter estimation entity that has beenexecuted to produce these results (cf. section 3.5 above).

3.6.1.1 The comprehensive estimation report file

Double-clicking on the comprehensive report entry in the Case tree, PPP, causes a reportwindow to appear. The comprehensive report, presented in HTML format, includes:

• a table of contents that allows quick access to the information listed below via“hyperlinks”;

• general information such as the date and time of the execution of the activity, andits final status;

• a detailed breakdown of the value of the likelihood function in terms of the con-stant, variance and residual terms of each measured variable in each experiment;

• the initial guesses and final (optimal) values of all model parameters being esti-mated, together with the corresponding lower and upper bounds, the 90%, 95%and 99% confidence intervals, the 95% t-value and the standard deviation;

• the same information as above for any parameters describing the variance be-haviour of the various sensors used for the measurements; these parameters willalso have been estimated;

• a detailed analysis of each experiment, including the experimental controls andinitial conditions, and the measured and estimated values of each measured point,as well as the corresponding difference (“residual”);

• the variance/covariance matrix;

• the correlation matrix;

3.6. Results of the parameter estimation run 58

Page 60: Advanced Guide Gproms

gPROMS Advanced User Guide

• a goodness-of-fit analysis based on the 95% χ2 criterion.

Figure 3.5 shows an example of a comprehensive report.

Optimisation report in case

Optimisation entity

executed

Parameter estimation entity

executed

Parameter estimation report

in Case

Figure 3.5: Parameter estimation comprehensive report.

3.6.1.2 The estimation report file

The PPP.out file contains a summary report on the optimisation run, including:

• the outcome of the estimation run;

• the final value of the objective function; and

• the final values of the estimated parameters.

The file also contains computational statistics on the performance of the numericalmethod.

The estimation report file for the batch reactor example is listed in appendix C.7.

3.6.1.3 The estimation statistics file

The PPP.stat file contains a report on the statistical validity of, and other indicatorson the final results of the parameter estimation. Specifically, it contains the followinginformation:

3.6. Results of the parameter estimation run 59

Page 61: Advanced Guide Gproms

gPROMS Advanced User Guide

• The variance model used for each estimated parameter (measured variable) in eachexperiment, and information on the parameters of the variance model. If thesevariance model parameters were determined by the optimisation, PPP.stat liststhe final values, initial guess, lower and upper bounds. Otherwise, the fixed valuesspecified by the user are listed.

• Tables comparing each measurement from each experiment with the predictedvalues from the process model, together with:

– the absolute deviation, (zijk − zijk);

– the relative deviation, 100% ·(

1 − zijk

zijk

)

;

– the standard deviation,√

σ2ijk; and

– the scaled residual,(zijk−zijk)

σ2

ijk

.

• The total contribution of each measured variable in each experiment to the objec-tive function. This can help the user to identify experiments and/or measurementsthat give large contributions to the objective function and so are potentially in-accurate.

• A breakdown of the contributions to the objective function of:

– the variance terms,

1

NE∑

i=1

NVi∑

j=1

NMij∑

k=1

ln(

σ2ijk

)

; and

– the residual terms,

1

NE∑

i=1

NVi∑

j=1

NMij∑

k=1

(zijk − zijk)2

σ2ijk

.

The estimation statistics file for the batch reactor example is listed in appendix C.8.

3.6.1.4 The machine-readable estimation statistics file

The PPP.stat-mr file contains all the information that appears in the PPP.stat filebut in machine-readable form.

Depending on the value of the Statistics parameter4 of the MXLKHD solver (cf. section10.7.1 of the “gPROMS Introductory User Guide”), the file may contain additional data

4Values of Statistics of 0 or 1.

3.6. Results of the parameter estimation run 60

Page 62: Advanced Guide Gproms

gPROMS Advanced User Guide

that are necessary for advanced statistical analysis via the graphical results managementservice described in the next section.

This is designed to be used with the advanced statistical analysis tool. To use the file youshould export it from ModelBuilder, see the chapter entitled “gPROMS ModelBuilder”in the “gPROMS Introductory User Guide”.

3.6.2 The advanced statistical analysis tool

gPROMS provides an advanced statistical analysis tool that allows the user to furtheranalyse the results and create several statistical plots. The data that are necessary forthe operation of this facility are stored in file PPP.stat-mr (cf. section 3.6.1.4 above).

The statistical analysis tool involves graphical output and is implemented in MS ExcelTM .It is, therefore, available only on the MS Windows platform. However, it can be usedwith PPP.stat-mr files created on other platforms (e.g. UNIX) provided these aretransferred to a MS Windows-based system.

In order to use this tool, the following steps should be followed:

1. From the Start menu in Windows, click on Process Systems Enterprise andthen Parameter Estimation Results (in Excel). This will open a workbookin Excel called “Parameter Estimation Results”. Note that a window may ap-pear with the message, “The workbook you are opening contains macros...

If you are sure this workbook is from a trusted source, click ‘Enable

Macros’...”. Click on the Enable Macros button.

2. Click on Parameter Estimation on the Excel toolbar. A pull-down menu willappear with the options Import File and Plot. Click on Import File, navigateto the required PPP.stat-mr file and open it.

This creates a number of spreadsheets within the workbook using the data from thePPP.stat-mr file:

Summary. This sheet summarises the contributions to the objective function of theconstant, variance and residual terms (see section 3.6.1.3), as well as the typesof variance models used for each measured variable in each experiment and theirrespective contributions to the objective function. It also shows the estimatedparameters. Parameters in red colour indicate either that the estimated value isat one of its bounds or that the confidence intervals are very large (see also the“Statistical significance” sheet). Appendix C.9 shows a sample summary sheet forthe batch reactor example.

Parameter estimates. This sheet summarises the estimated values of the model pa-rameters and the parameters of the different statistical variance models used,

3.6. Results of the parameter estimation run 61

Page 63: Advanced Guide Gproms

gPROMS Advanced User Guide

together with their initial guesses, and lower and upper bounds (see appendixC.10).

Variance matrix. This sheet prints the variance-covariance matrix, V. This matrixcontains the variances and covariances of the estimated process model and vari-ance model parameters. The square root of each diagonal element,

√Vii, is the

approximated standard deviation of the respective estimated parameter.

The following approximation to the variance-covariance matrix is used:

V = H∗−1

ΓVz ΓT H∗−1

,

where

H ∗ =

∂2

∂θ2 Φ ∂2

∂βi, j ∂θ Φ

∂2

∂βi, j ∂θ Φ ∂2

∂βi, j2 Φ

, Γ =

∂2

∂zi, j, k ∂θ Φ

∂2

∂zi, j, k ∂βi, jΦ

,

and Vz = diag(σ2ijk) denotes the variance-covariance matrix of the measurement

errors. The variance-covariance matrix of the estimated parameters, V, is of sizeIRNp×Np , where Np is the number of all estimated parameters (process modelparameters θ and variance model parameters β) whose values do not lie at one oftheir respective lower or upper bounds.

Correlation matrix. This sheet (see appendix C.12) prints the correlation matrix, R,which is calculated from the variance-covariance matrix, where

Rij =Vij

ViiVjj

, i 6= j,

Rij = 1, i = j.

Values with absolute value close to one in the off-diagonals indicate a high corre-lation of the corresponding parameters i and j, and vice versa.

The high correlation of these parameters can also be seen in the correspondingconfidence ellipsoid plots (see below).

Information matrix. This sheet prints the Fischer information matrix, M (see ap-pendix C.13), which is equal to the inverse of the variance-covariance matrix V.It also prints the 90%, 95% and 99% F-values for this matrix (calculated usinginternal statistical functions).

An approximate (1 − α) highest posterior density region for the parameters pT =(θT , βT ) is given by

(p− p)T ·M · (p− p) ≤ Np s2 F (α,Np, N −Np), (3.4)

with

s2 =1

N −NP

NE∑

i=1

NVi∑

j=1

NMij∑

k=1

(zijk − zijk)2

σ2ijk

(3.5)

3.6. Results of the parameter estimation run 62

Page 64: Advanced Guide Gproms

gPROMS Advanced User Guide

which forms an ellipsoid in the Np-dimensional parameter space.5 An α% confi-dence region means that if we repeat the experiments (which produces nearly thesame measurements, but with slightly different observation values and thereforea different distribution of the measurement errors), and estimate the parametersout of the repeated experimental data, the values of the estimated parameters willlie in this confidence region with α% probability.6

Confidence ellipsoids for any chosen pair of parameters can be plotted by selectingthe Plot option (see below).

Statistical significance. This sheet prints:

• the estimated values of the process model and variance model parameters;

• the 90%, 95% and 99% confidence intervals for the estimated model andvariance model parameters. The confidence ellipsoid in (3.4) is bounded bythe box

⊗Np

i=1 [pi −Xi(α); pi +Xi(α)]. (3.6)

The sides of the box (3.6), [pi −Xi(α); pi +Xi(α)], are called the two-sidedjoint α% confidence intervals.

These are calculated from

Xi(α) = t

(

1 + α

2, N −Np

)

·√

Vii.

• 95% t-values for the estimated parameters. These are calculated from:

ti =pi

Xi(0.95).

The t-values show the percentage accuracy of the estimated parameters withrespect to the 95% confidence intervals.

The associated t-values, ti, are compared with the reference 95% t-value,t(0.95, N −Np), which is again calculated using internal statistical functions.A t-value larger than the reference t-value indicates that the correspond-ing parameter has been accurately estimated (the standard deviation andthe confidence interval are small compared to the value of the estimatedparameter); a smaller value indicates a poor estimate of the correspondingparameter.

• the standard deviations√Vii of the estimated parameters.

Appendix C.14 shows part of a sample statistical significance sheet for the batchreactor example.

5Again only those parameters whose values are not at one of their bounds are considered.6Note that the confidence ellipsoid (3.4) is only a linear approximation of the non-linear confidence

region and may not be very accurate for models which are highly non-linear in the parameters.

3.6. Results of the parameter estimation run 63

Page 65: Advanced Guide Gproms

gPROMS Advanced User Guide

Note that estimating the parameters of the variance models (in addition to theprocess model parameters) results in a higher number of degrees of freedom forthe parameter estimation problem and therefore in an additional uncertainty forthe estimation of the process model parameters. This may cause larger confidenceintervals for both the process model and variance model parameters.

Measured variable information. For each measured variable in each experiment, asheet is produced with the measured and predicted values, the standard deviationsand the absolute, relative and weighted deviations. One such sheet for the variableR101.C(1) in the batch reactor experiment C13T1 is shown in appendix C.15.

In addition to the spreadsheets described above, the user can also create three types ofstatistical plots by choosing the Plot option from the Parameter Estimation menu onthe top toolbar. These are described below:

Overlay chart. This overlays the measured and predicted values for whichever variableis chosen from a specified experiment. The user has the option of showing errorbars by checking the Show standard deviations dialog box (see figure C.1 inappendix C.16). These error bars correspond to zijk ± σijk.

The user selects one or more variables (choose Flat list, if you want to selectmore than one variable). The charts can be plotted on the respective variabledata worksheets, on a new sheet for each chart or all charts on one new sheet.

Figure C.2 in appendix C.16 shows a plot of the batch reactor variable R101.C(1)in experiment C13T1. It can be seen that the agreement between the predictedvalues using the estimated parameters and the measured values is very close.

Residual chart. This allows the user to plot the absolute deviation, relative deviationand/or weighted (scaled) residual (see section 3.6.1.3) for each measured variablein each experiment.

As for the “Overlay chart”, the user may select one or more variables and plot thecharts on the respective data worksheets, on a new sheet for each chart or all thecharts on one new sheet.

Figures C.3 and C.4 in appendix C.17 show the dialog window and weightedresidual plot, respectively, for the batch reactor variable R101.C(1) in experimentC13T1.

Confidence ellipsoids. This option gives the confidence ellipsoids in two-dimensionalspace for any pair of parameters (pi, pj) according to the joint confidence region(3.4):

(

pi − pi

pj − pj

)T (

Vii Vij

Vij Vjj

)−1 (

pi − pi

pj − pj

)

≤ Np s2 F (α,Np, N −Np). (3.7)

The parameters can be plotted against each other using different confidence levels(90%, 95% or 99%). The user may select any pair of parameters or plot theconfidence ellipsoids for all pairs (see figure C.5 in appendix C.18).

3.6. Results of the parameter estimation run 64

Page 66: Advanced Guide Gproms

gPROMS Advanced User Guide

An example of a confidence ellipsoid is shown in figure C.6 in appendix C.18.

Note:

Although the variance model parameters have uncertainties, the user maywish to exclude these uncertainties from the calculations. In this case thevector pT does not contain the parameters βT and is defined as pT = θT .

This is achieved by setting the parameter STATISTICS in the PARAMETERS

entity to 1.

3.6. Results of the parameter estimation run 65

Page 67: Advanced Guide Gproms

gPROMS Advanced User Guide

Chapter 4

Using Foreign Objects

Contents

4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

4.1.1 What is a Foreign Object? . . . . . . . . . . . . . . . . . . . . . 67

4.1.2 Why use a Foreign Object? . . . . . . . . . . . . . . . . . . . . 67

4.1.3 What’s in a name? . . . . . . . . . . . . . . . . . . . . . . . . . 68

4.1.4 Some rules and terminology . . . . . . . . . . . . . . . . . . . . 68

4.1.5 Classes and instances . . . . . . . . . . . . . . . . . . . . . . . 69

4.1.6 What do I need to read next? . . . . . . . . . . . . . . . . . . . 69

4.2 Using Foreign Objects in gPROMS entities . . . . . . . . . . 71

4.2.1 Using Foreign Objects in gPROMS MODELs . . . . . . . . . . . 71

4.2.2 Foreign Object values and their specification . . . . . . . . . . 74

4.2.3 Consistency checking and validation . . . . . . . . . . . . . . . 78

66

Page 68: Advanced Guide Gproms

gPROMS Advanced User Guide

4.1 Introduction

4.1.1 What is a Foreign Object?

A Foreign Object is an external piece of software which provides a gPROMS simulationor optimisation run with computational services during run time. Typical examplesinclude:

• A package that provides various routines for calculating the values of one or morethermophysical properties for given values of intensive and/or extensive variablesin the gPROMS model.

• A spreadsheet that calculates the capital and operating cost for given values ofequipment size and operating parameters in the gPROMS model.

• A set of routines for calculating mass transfer coefficients and other fluid transportproperties for given values of intensive variables in the gPROMS model.

4.1.2 Why use a Foreign Object?

In principle, most types of mathematical relations can be expressed directly as EQUATIONsin gPROMS MODELs. However, there may still be good reasons why one would want touse an external (“foreign”) software package to express relationships between some ofthe variables in a MODEL:

• The relationship cannot be expressed conveniently in closed algebraic form withoutthe introduction of many intermediate quantities.

• The relationship involves many data parameters that would have to be extractedfirst and then inserted manually in the gPROMS MODEL.

• The software that carries out the required calculation already exists and is tested;it would be wasteful to have to reproduce its functionality in gPROMS.

A good example for all of the above reasons is provided by physical property calcula-tions. Consider, for instance, the relationship between the specific enthalpy of a mixtureand its temperature, pressure and composition implied by a cubic equation of state (e.g.the well-known Soave-Redlich-Kwong (SRK) equation). Expressing this relationship di-rectly in the gPROMS language would involve the introduction of a number of auxiliaryvariables; this not only increases the size of the problem being solved but also sometimesmakes its convergence more difficult: since many of these new variables have no directphysical meaning, it is difficult to obtain good initial guesses for them. Moreover, theequation of state involves critical point parameters for the various components in themixture as well as binary interaction coefficients; these will have to be extracted fromappropriate databanks and inserted in the gPROMS input file.

4.1. Introduction 67

Page 69: Advanced Guide Gproms

gPROMS Advanced User Guide

And yet all this effort is rather unnecessary if a well-documented and tested physicalproperty package is already available. A better solution in this case would be to linkthe physical property package as a Foreign Object with gPROMS and make use of itsservices during the simulation.

4.1.3 What’s in a name?

By this stage, you may well be wondering about the meaning and origins of the term“Foreign Object”.

Here the term “Foreign” simply indicates that this software is external to the gPROMSsystem and its input.

The term “Object” is a software engineering one: it refers to the fact that this softwareis an independent block (a “component”), perhaps with its own private storage andinternal workings; but the only way one can access any information relating to it is bymaking use of a well-defined interface that it provides to the outside world.

4.1.4 Some rules and terminology

Before going any further, let’s introduce some of the rules that govern the use andoperation of Foreign Objects in gPROMS and also some of the terminology that we willbe using throughout this chapter.

• Each gPROMS simulation or optimisation run may interact with any number ofForeign Objects.

• Each Foreign Object provides a set of methods. These are simply the calculationroutines that are accessible to the outside world. So, for instance, a typical physicalproperty Foreign Object would provide methods for calculating vapour and liquidphase densities, enthalpies, fugacities and so on. And a Foreign Object for capitalcosting estimation could provide methods for calculating capital costs of pressurevessels, packed and tray distillation columns etc.

• A Foreign Object method in gPROMS calculates one quantity (the “output”)for given values of one or more other quantities (the “inputs”). Consider, forinstance, a typical method for calculating the specific enthalpy of a liquid-phasemixture provided by a physical property Foreign Object. This method wouldhave the specific enthalpy as its unique output and the temperature, pressure andcomponent mole fractions in the mixture as its three inputs.

• The output of a method can be either a scalar or a vector—and so can each oneof its inputs. Going back to our physical property example, a method providingliquid-phase fugacities has a vector-valued output. And of course, the componentmole fractions are a vector-valued input.

4.1. Introduction 68

Page 70: Advanced Guide Gproms

gPROMS Advanced User Guide

• The method may also provide partial derivatives of its output with respect to all orsome of its inputs. Having access to such derivative information usually enhancesboth the efficiency and the robustness of the numerical computations carried outby gPROMS.

4.1.5 Classes and instances

As we mentioned at the start of section 4.1.4, each gPROMS run may make use of anynumber of Foreign Objects. So, by way of an example, consider a simulation run makinguse of:

• a Foreign Object calculating physical properties in the high-pressure, low-temp-erature (cryogenic) region;

• a Foreign Object calculating physical properties in the low-pressure, ambient-temperature region;

• a spreadsheet object that calculates capital and operating costs; and

• another spreadsheet that does accounting calculations of tax liabilities and assetdepreciation.

Now, the two physical property Foreign Objects mentioned above may, in fact, involvethe same physical property software, say a new package called SUPERPRO ; thus, theymake available exactly the same types of physical property calculations (density, en-thalpy, fugacities—all of the “methods”). However, they do differ in the data andcorrelations that they use internally for each one of these calculations—perhaps, evenin the set of components that appear in the mixtures that they are supposed to handle.

In such a situation, we would say that these two Foreign Objects are different instances(one of which is, say, called “HPCryoProps” and the other “LPAmbientProps”) of thesame class, namely SUPERPRO.

Similarly, the two spreadsheet Foreign Objects mentioned above may actually employthe same spreadsheet software (e.g. Microsoft ExcelTM); but, of course, they use dif-ferent spreadsheet files (e.g. one called Costing.xls and another one called Tax.xls

respectively). Again, in this case, we would have two instances, say called Costing andTax, both belonging to the same class (ExcelFO).

4.1.6 What do I need to read next?

If you intend to use Foreign Objects that are already interfaced to gPROMS, all youneed to read is section 4.2. This tells you how to reference Foreign Objects inside yourgPROMS input files.

4.1. Introduction 69

Page 71: Advanced Guide Gproms

gPROMS Advanced User Guide

If, on the other hand, you intend to interface your own Foreign Objects to gPROMSfor use by yourself and/or other people, you will first need to read section 4.2 and thenread the chapter entitled “Developing New Foreign Objects” in the “gPROMS SystemProgrammer Guide”.

As you may have already concluded from the examples we used above, one of the mostcommon uses of Foreign Objects is as a means of interfacing physical property packagesto gPROMS. Indeed, this is so common that gPROMS provides a simplified mechanismfor using and implementing such interfaces. If all you want to do is learn how to use thephysical property interface, then you should read chapters 6 and 7. The implementationof new physical properties interfaces is discussed in the chapter entitled “DevelopingNew Physical Properties Interfaces” in the “gPROMS System Programmer Guide”.

4.1. Introduction 70

Page 72: Advanced Guide Gproms

gPROMS Advanced User Guide

4.2 Using Foreign Objects in gPROMS entities

This section describes how to make use of Foreign Objects in different gPROMS entities.It is assumed that these objects are already fully implemented, tested and interfaced togPROMS.

4.2.1 Using Foreign Objects in gPROMS MODELs

As we have already explained, a Foreign Object basically provides a means of calculatingone or more quantities as function(s) of the gPROMS variables. As such, the naturalplace for these objects to appear is in the gPROMS MODELs.

The usage of Foreign Objects in MODELs is governed by a set of simple rules:

A. Each distinct Foreign Object used by a MODEL is declared as a PARAMETER oftype FOREIGN OBJECT1. The latter keyword is normally followed by the class ofthe Foreign Object (see section 4.1.5). This class simply identifies the externalsoftware (e.g. physical software package, CFD code, capital costing tool) that willbe used to implement this instance of the Foreign Object. For example, a typicaldeclaration would be:

# MODEL Flash

PARAMETER

PPP AS FOREIGN_OBJECT "ThermoPack"

...

This simply states that:

– MODEL Flash will make use of a Foreign Object.

– Whenever necessary within this MODEL (see below), the Foreign Object willbe referred to as PPP.

– PPP is implemented by a piece of external software (in this case, a phys-ical property package) called ThermoPack. Thus, PPP is an “instance” ofThermoPack.

One important thing to note is that the class of the Foreign Object must beenclosed in quotes ("ThermoPack"). This is because it is neither a gPROMSkeyword nor an identifier that has previously been defined in the gPROMS inputfile.

B. The methods of a Foreign Object are referred to as:

1This is a new type of PARAMETER complementing the existing types INTEGER, REAL and LOGICAL.

4.2. Using Foreign Objects in gPROMS entities 71

Page 73: Advanced Guide Gproms

gPROMS Advanced User Guide

ForeignObjectName.MethodName (InputList)

where the InputList is a list of method inputs. For a method without any inputs,the correct syntax is:

ForeignObjectName.MethodName

C. Each input of a method is a scalar or vector-valued variable or expression.

D. Each method returns a single scalar or vector-valued quantity. The latter may beof type integer, logical or real. A method may be used anywhere in the MODEL

where an expression of the corresponding dimensionality and type is allowed. Forinstance:

– A real-valued method may be used in an equation or in an expression SETtingthe value of a real PARAMETER.

– An integer-valued method may be used to SET the value of an integer PARA-METER.

– A logical-valued method may be used within the logical condition in an IF

equation.

An example of a gPROMS MODEL making use of a Foreign Object is shown in figure 4.12.

There are several features of this MODEL that are worth noting:

• As we have already seen, line 3 specifies that the MODEL Flash makes use of aForeign Object of type ThermoPack, corresponding to a software package that isexternal to gPROMS. For the purposes of defining this MODEL, this Foreign Objectwill be called PPP.

• This Foreign Object provides several methods. These return quantities of varioustypes that can be used anywhere in the MODEL. For example:

– At line 13, we make use of a method called NumberOfComponents whichsimply returns an integer corresponding to the number of components in themixture being considered. We use this to SET the number of components, aPARAMETER NoComp, in this MODEL. Note that method NumberOfComponents

does not have any inputs.

– At line 16, we make use of two other methods provided by this Foreign Ob-ject, namely LiquidEnthalpy and VapourEnthalpy, which compute liquidand vapour phase specific enthalpies respectively. Each of these returns areal quantity computed by the Foreign Object from the inputs (T,P,x) and(T,P,y) respectively. We note that, in each case, the first two inputs arescalar quantities but the third one is a vector.

2This and later figures in this chapter make use of the standard convention that identifiers shown inCAPITALS are gPROMS keywords; all others are user-selected names.

4.2. Using Foreign Objects in gPROMS entities 72

Page 74: Advanced Guide Gproms

gPROMS Advanced User Guide

1 # MODEL Flash

2 PARAMETER

3 PPP AS FOREIGN_OBJECT "ThermoPack"

4 NoComp AS INTEGER

5 VARIABLE

6 F, L, V AS MolarRate

7 Hf AS MolarEnergy

8 Q AS EnergyRate

9 T AS Temperature

10 P AS Pressure

11 x, y, z AS ARRAY(NoComp) OF MoleFraction

12 SET

13 NoComp := PPP.NumberOfComponents ;

14 EQUATION

15 F*z = L*x + V*y ;

16 F*Hf = L*PPP.LiquidEnthalpy(T,P,x) +

V*PPP.VapourEnthalpy(T,P,y) + Q ;

17 x*PPP.LiquidFugacityCoeff(T,P,x) =

y*PPP.VapourFugacityCoeff(T,P,y) ;

18 SIGMA(x) = SIGMA(y) = 1 ;

19 IF PPP.StableLiquid(T,P,x) THEN

20 ...

21 ELSE

22 ...

23 END

Figure 4.1: An example of a gPROMS MODEL entity using a Foreign Object.

– At line 17, we make use of two more methods, namely LiquidFugacityCoeff

and VapourFugacityCoeff respectively. These compute and return vectorsof real quantities, i.e. liquid and vapour phase fugacity coefficients.

– At line 19, we make use of a method called StableLiquid that returns alogical quantity indicating whether or not the liquid phase is stable underthe prevailing temperature, pressure and composition.

There are two further points that are worth making:

• Method inputs can be expressions rather than simple variables. For instance,if we wanted to evaluate a liquid-phase viscosity at the mean of the inlet and

4.2. Using Foreign Objects in gPROMS entities 73

Page 75: Advanced Guide Gproms

gPROMS Advanced User Guide

exit conditions of the above flash, we could achieve this via the following methodinvocation:

PPP.LiquidViscosity((Tin+T)/2, (Pin+P)/2, (z+x)/2)

• No direct reference can be made to an individual element (or slice) of a vector-valued method. For instance, it is not possible to directly access the ith element ofthe vector of liquid fugacity coefficients returned by method LiquidFugacityCoeff

(see line 17 of Figure 4.1). If such access is desired, an equation defining a vector-valued variable as being equal to the method result must first be introduced, e.g.:

LFC = PPP.LiquidFugacityCoeff(T.P,x) ;

Other equations can then refer to individual elements of the variable LFC asdesired.

4.2.2 Foreign Object values and their specification

As we have seen, each Foreign Object is an instance of a class which determines theactual external software that will be used to compute the methods that the ForeignObject is supposed to provide. However, in most cases, just specifying the class of theForeign Object is not sufficient to determine completely its behaviour.

Consider, for instance, the Foreign Object PPP used in the example of Figure 4.1. Wealready know that the methods (e.g. LiquidFugacityCoeff) of this Foreign Object willbe provided by an external physical property package called ThermoPack. However,for these methods to be fully defined, we also need to know the set of componentsthat are involved in the mixture under consideration and also the particular type ofthermophysical model (e.g. the equation of state or activity coefficient model) thatwill be used to compute these properties. All of this information is associated with thespecific Foreign Object instance PPP. Indeed, two different instances of the same ForeignObject class within the same gPROMS simulation may involve different component setsor use different thermophysical property calculation options.

As described in the previous section, the Foreign Objects used in a MODEL are declared asPARAMETERs. Therefore, just like any other PARAMETER, each Foreign Object must even-tually be given a “value” before any instance of the MODEL can be used in a simulationor optimisation run.

More specifically, the value of the Foreign Object is a string of characters (enclosedin double quotes) that identifies this particular instance of a Foreign Object. In theexample described above, this string could be a pathname for a data file that containsthe information on the component set and thermophysical property calculation options.The ThermoPack software would read this file to determine precisely what mixture it issupposed to handle and how. Different instances of ThermoPack would be described bydifferent such files.

4.2. Using Foreign Objects in gPROMS entities 74

Page 76: Advanced Guide Gproms

gPROMS Advanced User Guide

4.2.2.1 Explicit specification of a Foreign Object value

Like any other gPROMS PARAMETER, the value of a Foreign Object can be SET in oneof three ways:

A. Within the MODEL in which the Foreign Object is declared.

For example, we could insert the following line after line 12 of the Flash MODEL

shown in Figure 4.1:

PPP := "Aromatics.tpk" ;

This states that the behaviour of Foreign Object PPP is defined by a ThermoPack in-put file (.tpk) called Aromatics.tpk. The input file must be imported into Mod-elBuilder as a Miscellaneous File (or linked), see the chapter entitled “gPROMSModelBuilder” in the “gPROMS Introductory User Guide”. Alternatively the fullname for any file located outside ModelBuilder can be used (e.g. C:\Temp\Aromatics.tpk).

The obvious disadvantage of the above way of specifying the Foreign Object valueis that all instances of MODEL Flash will be restricted to using the same set ofcomponents and thermophysical property calculation options. Thus, the general-ity and re-usability of this MODEL is severely limited!

B. Within a higher-level MODEL containing instances of the MODEL within which theForeign Object was declared.

Consider, for instance, the MODEL TwoTankSystem illustrated in Figure 4.2. It con-tains two instances, HighPTank and LowPTank respectively, of the MODEL Flash

shown in Figure 4.1. These two flashes operate at significantly different pres-sures, and consequently make use of different thermophysical property calculationoptions. At line 10, the Foreign Object PPP of the first of these two flashes is iden-tified with a ThermoPack input file HPThermo.tpk. On the other hand, line 11 setsthe corresponding Foreign Object of the second flash to be equal to a PARAMETER

LPPP declared within TwoTankSystem (see line 3). Obviously, LPPP will have to begiven a value at an even higher-level MODEL or in a PROCESS (see below).

As is standard in gPROMS, a composite MODEL can access any entity declaredwithin instances of lower-level MODELs that it contains. This rule also holds forForeign Object entities. For example, in lines 13-15 of Figure 4.2, the PPP ForeignObjects within HighPTank and LowPTank are used in order to compute the averagemolecular weight of the liquid streams leaving the two units.

C. Within the PROCESS section defining the simulation or optimisation run.

This is illustrated in Figure 4.3. Lines 2–3 declare an instance (called Plant) ofthe composite MODEL defined in Figure 4.2. The value of LPPP occurring in thatMODEL is then SET in lines 4–5.

4.2. Using Foreign Objects in gPROMS entities 75

Page 77: Advanced Guide Gproms

gPROMS Advanced User Guide

1 # MODELTwoTankSystem

2 PARAMETER

3 LPPP AS FOREIGN_OBJECT "ThermoPack"

4 VARIABLE

5 AverageMolWt AS MolecularWeight

6 UNIT

7 HighPTank AS Flash

8 LowPTank AS Flash

9 SET

10 HighPTank.PPP := "HPThermo.tpk" ;

11 LowPTank.PPP := LPPP ;

12 EQUATION

13 AverageMolWt * (HighPTank.L + LowPTank.L) =

14 (HighPTank.L*HighPTank.PPP.MeanMW(HighPTank.x) +

15 LowPTank.L*LowPTank.PPP.MeanMW(LowPTank.x))/2 ;

Figure 4.2: SETting of Foreign Object values within composite MODELs.

4.2.2.2 Implicit specification of a Foreign Object value

Like other gPROMS PARAMETERs, the values of Foreign Objects may be specified im-plicitly via the gPROMS parameter propagation mechanism.

Parameter propagation is invoked automatically by gPROMS at the start of the execu-tion of a PROCESS entity if the value of any Foreign Object instance within the entireproblem has not been specified explicitly. In such cases, gPROMS will try to determinethe missing value by searching for a Foreign Object that:

• is declared within a higher-level MODEL containing the instance of the MODEL whichhas the unspecified Foreign Object, and

• has exactly the same name as the unspecified Foreign Object, and

• belongs to the same class as the unspecified Foreign Object, and

• has already been given a value either explicitly or implicitly.

If a Foreign Object fulfilling all of the above criteria is found, its value is also given to theunspecified Foreign Object. If no such Foreign Object is found, the algorithm is appliedrecursively, searching increasingly higher-level MODELs and ultimately the PROCESS itself.

4.2. Using Foreign Objects in gPROMS entities 76

Page 78: Advanced Guide Gproms

gPROMS Advanced User Guide

1 # PROCESS PlantSimulation

2 UNIT

3 Plant AS TwoTankSystem

4 SET

5 Plant.LPPP := "LPThermo.tpk" ;

6 ...

Figure 4.3: SETting of a Foreign Object value within a PROCESS entity.

If, by the end of this procedure, the value of the unspecified Foreign Object remainsundetermined, an error occurs and the execution of the PROCESS is aborted.

The main practical implication of the parameter propagation mechanism is that, pro-vided the model developer adopts a standard name (say PPP) for all Foreign Objectinstances of a certain class (e.g. ThermoPack) in all MODELs that he or she develops,then it is sufficient to specify the value of this Foreign Object once only (usually in thePROCESS entity) for it to be adopted automatically by the entire problem.

Alternatively, if a plant has two distinct sections (e.g. a high temperature and a lowtemperature one) which require the use of two different Foreign Objects, this can againbe specified conveniently at the highest appropriate level, as illustrated in figure 4.4.Here, it is assumed that the MODELs HighTemperatureSection and LowTemperature

Section referred to in lines 3–4 each contain a Foreign Object called PPP and so doall of their sub-models. In this case, simply SETting appropriate values for the twohighest-level Foreign Objects in the PROCESS entity (see lines 5–7) achieves the desiredspecification for the entire problem.

1 # MODEL Plant

2 UNIT

3 HTS AS HighTemperatureSection

4 LTS AS LowTemperatureSection

5 SET

6 HTS.PPP := "HighTThermo.tpk" ;

7 LTS.PPP := "LowTThermo.tpk" ;

8 EQUATION

9 ...

Figure 4.4: Foreign Object specification via parameter propagation.

4.2. Using Foreign Objects in gPROMS entities 77

Page 79: Advanced Guide Gproms

gPROMS Advanced User Guide

4.2.3 Consistency checking and validation

4.2.3.1 Ensuring correct usage of Foreign Objects

To make correct use of a Foreign Object in your MODELs, you need the following infor-mation:

A) The name of the Foreign Object class.

B) The names of the methods provided by this Foreign Object.

C) The following information for each method:

i) The type, length, physical dimensions and units of measurement of themethod output.

ii) The number of the method inputs.

iii) The length, physical dimensions and units of measurement of each of themethod inputs.

It is worth noting the following in conjunction with points (C-i) and (C-iii) above:

• The type of a quantity is real, integer or logical.

• The length of a quantity is 1 for a scalar, and n for a vector (array) of length n.

• The physical dimensions are defined only for real quantities. They determine thephysical type of the quantity in terms of the nine fundamental physical dimensionsas well as a tenth dimension, “money” (see Table 4.1). For instance, a molardensity has dimensions:

[Amount of Substance]1[Length]−3

A unit material cost might be expressed in terms of:

[Money]1[Mass]−1

• The units of measurement are expressed in relation to the SI set of units (see lastcolumn of Table 4.1 in the following manner:

Value ofQuantity in

SI Units

= Offset + Multiplier ×

Value ofQuantity WithinForeign Object

where the Offset and the Multiplier are two real-valued quantities. For in-stance, if the Foreign Object measures temperatures in degrees Fahrenheit, thenthe Offset is 255.37 and the Multiplier is 0.55556.

You should be able to obtain all of the above information from the documentationaccompanying the particular Foreign Object that you wish to use.

4.2. Using Foreign Objects in gPROMS entities 78

Page 80: Advanced Guide Gproms

gPROMS Advanced User Guide

4.2.3.2 Consistency checking

gPROMS checks the consistency of your Foreign Object usage at the start of the exe-cution of a PROCESS. To achieve this, it goes though a number of steps:

1. It attempts to locate the external software identified by the Foreign Object classname(s) by searching first in a sub-directory called fo in the export directory3;if it does not find it there, it searches in a directory specified by the operatingsystem “environment variable” GPROMSFODIR if the latter has been given a value.Finally, it searches in a sub-directory called fo of the gPROMS system installationdirectory.

If the external software cannot be located or if it can be located but communica-tion with gPROMS cannot be established for whatever reason, execution of thePROCESS will abort with a message of the form:

Cannot open the Foreign Object dynamic shared library: <FOClass.so>

Foreign Object initialisation failed: <FOClass>

where <FOClass> is the name of the Foreign Object class whose software imple-mentation cannot be found.

2. It establishes a link with the external software, passing to it the value (see section4.2.2) of each Foreign Object instance of this class and asking it to create such aninstance.

If the instance value is illegal (e.g. because it contains illegal characters or it refersto a file that cannot be located by the external software), then execution of thePROCESS will abort with the message:

Cannot create Foreign Object instance: <FOClass>::<FOInstance>

Foreign Object initialisation failed: <FOClass>::<FOInstance>

where <FOInstance> is the name of the Foreign Object instance of class <FOClass>that is causing the problem.

3. It compares the usage of each Foreign Object instance in the problem against in-formation that it obtains by issuing direct requests to that instance. For example,it will seek to verify that any methods of this Foreign Object that are referred toin MODELs are really supported by the external software, and that the actual typeand length of their outputs are consistent with the manner in which they are usedin these MODELs. It also checks the number and length of the inputs of each suchmethod.

3The foreign object must be imported into Modelbuilder or linked, with the export directory set tofo. See the chapter entitled “gPROMS ModelBuilder” in the “gPROMS Introductory User Guide”

4.2. Using Foreign Objects in gPROMS entities 79

Page 81: Advanced Guide Gproms

gPROMS Advanced User Guide

WARNING!

gPROMS does not currently check the consistency of the fundamentalphysical dimensions or the units of measurement, nor does it carry outautomatic conversion of units of measurement.

It is your responsibility to ensure the correct usage of Foreign Objects inthis respect.

4.2. Using Foreign Objects in gPROMS entities 80

Page 82: Advanced Guide Gproms

gPROMS Advanced User Guide

Fundamental Description SI UnitsDimension

1 Length metre2 Mass kilogram3 Time second4 Electric Current Ampere5 Temperature Kelvin6 Amount of Substance mole7 Luminous Intensity candela8 Plane Angle radian9 Solid Angle steradian10 Money US dollar

Table 4.1: Physical dimensions for the inputs and output of a method.

4.2. Using Foreign Objects in gPROMS entities 81

Page 83: Advanced Guide Gproms

gPROMS Advanced User Guide

Chapter 5

Using Foreign Processes

Contents

5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

5.1.1 Applications of the FPI . . . . . . . . . . . . . . . . . . . . . . 83

5.1.2 What is the FPI? . . . . . . . . . . . . . . . . . . . . . . . . . . 83

5.1.3 Chapter outline . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

5.2 The elementary communication tasks . . . . . . . . . . . . . 85

5.2.1 The PAUSE elementary communication task . . . . . . . . . . . 86

5.2.2 The GET elementary communication task . . . . . . . . . . . . . 88

5.2.3 The SEND elementary communication task . . . . . . . . . . . . 93

5.2.4 The SENDMATHINFO elementary communication task . . . . . . 95

5.2.5 The LINEARISE elementary task . . . . . . . . . . . . . . . . . 97

5.3 Using the FPI . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

5.3.1 The standard FPI implementation . . . . . . . . . . . . . . . . 107

5.3.2 Using non-standard FPI implementations . . . . . . . . . . . . 107

5.4 FPI performance issues . . . . . . . . . . . . . . . . . . . . . . 111

5.4.1 Effects of model size . . . . . . . . . . . . . . . . . . . . . . . . 111

5.4.2 Effects of model re-initialisation . . . . . . . . . . . . . . . . . 111

5.4.3 Effects of results logging . . . . . . . . . . . . . . . . . . . . . . 112

5.4.4 Effects of FPI communication overheads . . . . . . . . . . . . . 113

82

Page 84: Advanced Guide Gproms

gPROMS Advanced User Guide

5.1 Introduction

The Foreign Process Interface (FPI) provides a general mechanism for the exchange ofinformation between executing gPROMS simulations and external software.

This communication takes place at discrete time points throughout the duration of thesimulation. The user is entirely free to determine the frequency and content of theexchanges, which may include:

• time synchronisation signals;

• values of variables and flags;

• information on the mathematical model used for the simulation and its currentstate.

5.1.1 Applications of the FPI

Typical applications of the FPI include:

• the use of gPROMS simulations to study and validate control algorithms imple-mented in an external real-time control system;

• the construction of bespoke user-interfaces to gPROMS simulations offering awell-defined and limited scope for modifications on behalf of the end-user;

• the incorporation of gPROMS within operator training systems;

• the interfacing of gPROMS with model-based control system design packages.

5.1.2 What is the FPI?

The FPI comprises two main components:

• A set of elementary communication tasks.

By inserting instances of these tasks in SCHEDULES within TASK and PROCESS

entities, the user determines the timing and content of any communication thatwill occur when the SCHEDULE is executed.

• A communication protocol between gPROMS and the external software.

The execution of an elementary communication task in a SCHEDULE automaticallycauses gPROMS to invoke one of a set of procedures provided by the user.

The FPI communication protocol specifies

– what procedures must be provided;

5.1. Introduction 83

Page 85: Advanced Guide Gproms

gPROMS Advanced User Guide

– their names;

– the precise form of their argument lists.

The FPI communication protocol does not specify the content or detailed be-haviour of these procedures. They can be as complex or as simple as desired—infact, some of them may be completely empty!

Typically, the communication procedures will be developed once for a given hard-ware/software setup.

5.1.3 Chapter outline

The rest of this chapter is structured as follows:

• Section 5.2 describes the elementary communications tasks that comprise an FPIand the effects they have on the simulation.

• Section 5.3 explains how to ensure that the correct FPI implementation is usedby your simulation.

• Finally, section 5.4 discusses some important issues pertaining to the performanceof simulations that make use of the FPI.

This chapter does not discuss how to develop new FPI implementations. This topic iscovered in detail in the chapter entitled “Developing New FPI Implementations” in the“gPROMS System Programmer Guide”.

5.1. Introduction 84

Page 86: Advanced Guide Gproms

gPROMS Advanced User Guide

5.2 The elementary communication tasks

Dynamic simulations in gPROMS are defined in PROCESS entities which can be executedto carry out the simulation. In general, each PROCESS involves a SCHEDULE of actions(defined by TASK entities) organised in SEQUENCE or in PARALLEL. There is also thepossibility of conditional (IF) and iterative (WHILE) task execution.

A TASK entity may be defined in terms of lower level TASKs which, in turn, may involveeven lower level TASKs, and so on. We therefore have a hierarchy of TASKs of arbitrarydepth. At the bottom level of this hierarchy, we have a number of elementary tasks,such as RESET, REPLACE and CONTINUE (see the chapters entitled “Simple OperatingProcedures” and “Complex Operating Procedures” in the “gPROMS Introductory UserGuide”).

The FPI introduces five new elementary tasks. Just like the other elementary tasks,these can be inserted anywhere in a SCHEDULE. Their function is to exchange informationbetween the executing gPROMS PROCESS and some external software. The latter, asfar as gPROMS is concerned, is just a “foreign” PROCESS (i.e. one that is not writtenin the gPROMS language). From now on, we will use this term to refer to the externalsoftware.

The five elementary communication tasks are summarised below:

PAUSE : Hold the gPROMS simulation until receiving a signal fromthe Foreign Process.

GET : Receive the values of a subset of the gPROMS variables fromthe Foreign Process.

SEND : Transmit the values of a subset of the gPROMS variables tothe Foreign Process.

SENDMATHINFO : Transmit information on the mathematical model used forthe simulation, and its current state, to the Foreign Process.

LINEARISE : Create the minimal state-space representation of a non-linear,dynamic model

All elementary communication tasks are executed in a synchronous fashion. That is, thesimulation is suspended completely (i.e. the simulation clock is stopped) while gPROMSis waiting for the response of the foreign process.

In the rest of this section, we consider each of these elementary tasks in more detail.

5.2. The elementary communication tasks 85

Page 87: Advanced Guide Gproms

gPROMS Advanced User Guide

5.2.1 The PAUSE elementary communication task

5.2.1.1 General syntax

The PAUSE elementary task simply holds the gPROMS simulation until a signal is re-ceived from the Foreign Process. Its syntax is:

PAUSE SIGNALID "SigName" STATUS StatVar

where

SigName is a string of characters that will be passed to the ForeignProcess by gPROMS on executing the PAUSE task.This may be used by the Foreign Process for identifying theactual PAUSE request being executed, which may be usefulif there are several PAUSE tasks at different places in theSCHEDULE.The SIGNALID "SigName" specification is optional. Anempty string will be passed to the Foreign Process by de-fault.

StatVar is a logical gPROMS variable1 that will receive the outcomeof the PAUSE request from the Foreign Process.Generally, a value of TRUE will indicate success (or permissionto proceed with the simulation), while a value of FALSE maysignal failure (or a request to abort the simulation).The STATUS StatVar specification is also optional.

A typical use of a PAUSE task is right at the beginning of a TASK SCHEDULE:

1Logical variables are normally defined within the VARIABLE section of TASK entities.

5.2. The elementary communication tasks 86

Page 88: Advanced Guide Gproms

gPROMS Advanced User Guide

# TASK Example

VARIABLE

OKtoContinue AS LOGICAL

SCHEDULE

SEQUENCE

PAUSE SIGNALID "ExampleStartRequest" STATUS OKtoContinue

IF OKtoContinue THEN

SEQUENCE

{ Do rest of task }

END

ELSE

SEQUENCE

MESSAGE "TASK Example aborted !"

STOP

END

END

END

In this case, the first action of TASK Example is to PAUSE, sending the string of characters“ExampleStartRequest” to the Foreign Process. The simulation clock stops at thispoint waiting for the Foreign Process to respond. The execution of the rest of the TASK

depends on the value of the STATUS variable returned by the Foreign Process.

5.2.1.2 Side effects of PAUSE

PAUSE tasks have no side effects on the simulation results.

5.2. The elementary communication tasks 87

Page 89: Advanced Guide Gproms

gPROMS Advanced User Guide

5.2.2 The GET elementary communication task

5.2.2.1 General syntax

The GET elementary task receives values of one or more variables from the ForeignProcess. Its syntax is of the form:

GET

SIGNALID "SigName"STATUS StatVar

gPROMSVariable ;gPROMSVariable ;gPROMSVariable ;...gPROMSVariable := "ForeignVariableID" ;gPROMSVariable := "ForeignVariableID" ;gPROMSVariable := "ForeignVariableID" ;...

END

where

SigName is a string of characters that will be passed to the ForeignProcess by gPROMS on executing the GET task.This may be used by the Foreign Process for identifying theactual GET request being executed, which may be useful ifthere are several GET tasks at different places in the SCHEDULE.In some applications in which the gPROMS PROCESS is ex-pected to receive information from more than one foreignsource, the SigName may also be used to identify the partic-ular source of the data requested. It is the responsibility ofthe FPI implementation to request the data from the correctsource (e.g., in an operator training context, from a trainee’sconsole rather than from the trainer’s console) and returnthem to gPROMS.The SIGNALID "SigName" specification is optional. Anempty string will be passed to the Foreign Process by de-fault.

5.2. The elementary communication tasks 88

Page 90: Advanced Guide Gproms

gPROMS Advanced User Guide

StatVar is a logical gPROMS variable that will receive the outcomeof the GET request from the Foreign Process.Generally, a value of TRUE will indicate success (or permissionto proceed with the simulation), while a value of FALSE maysignal failure (or a request to abort the simulation).The STATUS StatVar specification is optional.

gPROMSVariable is either a variable occurring in a gPROMS MODEL entity usedfor the simulation (specified through its complete pathname),or a local variable in a TASK entity (of type REAL, INTEGER,or LOGICAL).

ForeignVariableID is the name by which this quantity is known to the ForeignProcess (e.g. a “tag name” in a real-time database). Thiswill be used by the Foreign Process to identify the requestedinformation so that it can return it to gPROMS.If the ForeignVariableID is omitted, the complete path nameof gPROMSVariable will be used instead.

5.2.2.2 GETting array and distribution slices

In most applications, GET is applied to individual variables or array elements. However,in some cases, it may be desirable to GET values of an entire array or a slice of an array.The syntax for achieving this is of the form:

GET

SIGNALID "SigName"STATUS StatVargPROMSArrayVariable := "ForeignVariableID"(1:N) ;gPROMSArrayVariable(N1:N2) := "ForeignVariableID"(1:N2-N1+1) ;gPROMSArrayVariable ;gPROMSArrayVariable(N1:N2) ;...

END

The main point to note is that if a foreign variable ID is specified to receive an arrayof gPROMS variable values, then we must declare this ForeignVariableID as an arrayof the same length. Thus, in the first case above, to get an entire array of length N ,we treat the ForeignVariableID also as an array of length N and show this explicitly byadding the (1:N) “slice” notation to it.

Similarly, in the second case, to get the values of a slice of the array between indices N1and N2 inclusive (assuming N1 ≤ N2 ), we treat the ForeignVariableID as an array ofthe same length (i.e. comprising N2 − N1 + 1 elements).

If entire multi-dimensional arrays or slices thereof are to be received, the ForeignVari-

5.2. The elementary communication tasks 89

Page 91: Advanced Guide Gproms

gPROMS Advanced User Guide

ableID must be treated as arrays of the same number of dimensions and this must beshown explicitly. For instance:

GET

SIGNALID "SigName"STATUS StatVargPROMSArrayVariable(N1:N2, N3:N4) :=

"ForeignVariableID" (1:N2-N1+1, 1:N4-N3+1) ;gPROMSArrayVariable(N1:N2, N3:N4) ;...

END

Similar syntax and rules apply for GETting variables that are distributed over one ormore continuous domains. However, in such cases, it must be borne in mind that GET

can only obtain a discrete representation of the variable:

GET

SIGNALID "SigName"STATUS StatVargPROMSDistributedVariable := "ForeignVariableID" (1:N) ;gPROMSDistributedVariable ;...

END

where N is the number of elements in the discretisation of the distributed variable. Thiswill depend on the discretisation method specified for the corresponding distributiondomain, which is normally of the form:

SET DistributionDomain := [ Method, Order, NumberOfElements ] ;

In particular,

• for finite-difference based methods (i.e., for Method being BFDM, CFDM, or FFDM),use

N = NumberOfElements + 1.

Here the values to be received correspond to the values of the distributed variableat N uniformly distributed points (including the domain boundaries).

• for orthogonal-collocation based methods (i.e., for Method being OCFEM), use

N = NumberOfElements × Order + 1.

Here the values to be received correspond to the values of the distributed variableat the (NumberOfElements +1) finite element boundaries, and at the (Order − 1)collocation points within each finite element.

5.2. The elementary communication tasks 90

Page 92: Advanced Guide Gproms

gPROMS Advanced User Guide

GETting slices of distributed variables is not recommended as it requires a detailedunderstanding of the internal representation and handling of variable distributions bygPROMS.

5.2.2.3 Side effects of GET

A successful return (i.e. StatVar = TRUE) from the foreign process following a GET requestprovides the gPROMS simulation with a set of new values for the specified subset of itsvariables. These values overwrite the values that the variables had before the GET task.The actual effect of this overwriting on the subsequent simulation depends on the typeof each such variable:

• If gPROMSVariable is a local TASK variable, then the new value simply overwritesthe old value without any other side effect. In effect, this is equivalent to:

gPROMSVariable := new value ;

• If gPROMSVariable is an input variable2 in the mathematical model, being cur-rently ASSIGNed to a numerical value or an explicit function of time, then itbecomes ASSIGNed to the new value obtained via GET. In effect, this is equivalentto:

RESET

gPROMSVariable := new value ;END

• If gPROMSVariable is a differential variable in the mathematical model, then itscurrent value is changed instantaneously to the new value obtained via GET. Ineffect, this is equivalent to:

REINITIAL

gPROMSVariableWITH

gPROMSVariable = new value ;END

• If gPROMSVariable is an algebraic variable in the mathematical model, then itscurrent value is momentarily overwritten by the new value.

If the GET task changes the values of any input or differential variables in the model, thenthese new values may be inconsistent with the values of all other model variables (i.e.they no longer satisfy the model equations). In such cases, gPROMS automatically

2The classification of gPROMS variables into input, differential and algebraic variables is discussedin detail in section 5.2.4.2.

5.2. The elementary communication tasks 91

Page 93: Advanced Guide Gproms

gPROMS Advanced User Guide

undertakes a re-initialisation calculation which aims to restore this consistency whilekeeping all input and differential variables at their new values.

An interesting consequence of the way this re-initialisation is done is that GETting an al-gebraic variable has absolutely no effect on the subsequent trajectory that the simulationfollows: irrespective of what the value obtained by GET is, the variable will be restoredto a value that is consistent with the values of the input and differential variables.

However, there are circumstances under which GETting one or more algebraic variablesmay be useful. In particular, it should be borne in mind that re-initialisation involvesthe solution of a non-linear set of equations which is carried out iteratively startingfrom the current point as the initial guess. A good initial guess for a critical algebraicvariable (e.g. a temperature in a chemical reactor) received from the Foreign Process(e.g. a control system having access to real plant measurements) may facilitate theconvergence of this iteration—even if it does not affect the converged solution foundeventually.

5.2. The elementary communication tasks 92

Page 94: Advanced Guide Gproms

gPROMS Advanced User Guide

5.2.3 The SEND elementary communication task

5.2.3.1 General syntax

The SEND elementary task sends values of one or more variables to the Foreign Process.Its syntax is of the form:

SEND

SIGNALID "SigName"STATUS StatVargPROMSVariable ;"ForeignVariableID" := gPROMSVariable ;gPROMSVariable ;"ForeignVariableID" := gPROMSVariable ;gPROMSVariable ;"ForeignVariableID" := gPROMSVariable ;...

END

where

SigName is a string of characters that will be passed to the ForeignProcess by gPROMS on executing the SEND task.This may be used by the Foreign Process for identifyingthe actual SEND request being executed, which may be use-ful if there are several SEND tasks at different places in theSCHEDULE.In some applications in which the gPROMS PROCESS is ex-pected to transmit information to more than one foreign des-tination, the SigName may also be used to identify the finaldestination of the data being sent. It is the responsibility ofthe FPI implementation to direct the data to the correct des-tination (e.g., in an operator training context, to a trainee’sconsole rather than to the trainer’s console).The SIGNALID "SigName" specification is optional and maybe omitted. An empty string will be passed to the foreignprocess by default.

5.2. The elementary communication tasks 93

Page 95: Advanced Guide Gproms

gPROMS Advanced User Guide

StatVar is a logical gPROMS variable that will receive the outcomeof the SEND request from the Foreign Process.Generally, a value of TRUE will indicate success (or permissionto proceed with the simulation), while a value of FALSE maysignal failure (or a request to abort the simulation).The STATUS StatVar specification is optional.

ForeignVariableID is the name by which this quantity is known to the ForeignProcess (e.g. a “tag name” in a real-time database). Thiswill be used by the Foreign Process to identify the requestedinformation so that it can return it to gPROMS.If the ForeignVariableID is omitted, the complete path nameof gPROMSVariable will be used instead.

gPROMSVariable is either a variable occurring in a gPROMS MODEL entity usedfor the simulation (specified through its complete pathname),or a local variable in a TASK entity (of type REAL, INTEGER,or LOGICAL).

5.2.3.2 SENDing array and distribution slices

SENDing entire arrays and distributions, or slices thereof to a foreign process is handledin an entirely analogous fashion to GETting them from the Foreign Process.

See section 5.2.2.2 for details on the relevant syntax and rules.

5.2.3.3 Side effects of SEND

SEND tasks have no side effects on the simulation results.

5.2. The elementary communication tasks 94

Page 96: Advanced Guide Gproms

gPROMS Advanced User Guide

5.2.4 The SENDMATHINFO elementary communication task

5.2.4.1 General syntax

The SENDMATHINFO elementary task transmits to the Foreign Process information onthe mathematical model being used by the simulation, and its current state. Its syntaxis:

SENDMATHINFO SIGNALID "SigName" STATUS StatVar

where

SigName is a string of characters that will be passed to the ForeignProcess by gPROMS on executing the SENDMATHINFO task.This may be used by the Foreign Process for identifying theactual SENDMATHINFO request being executed, which may beuseful if there are several SENDMATHINFO tasks at differentplaces in the SCHEDULE.The SIGNALID "SigName" specification is optional. Anempty string will be passed to the foreign process by default.

StatVar is a logical gPROMS variable that will receive the outcomeof the SENDMATHINFO request from the Foreign Process.Generally, a value of TRUE will indicate success (or permissionto proceed with the simulation), while a value of FALSE maysignal failure (or a request to abort the simulation).The STATUS StatVar specification is also optional.

5.2.4.2 Information transmitted by SENDMATHINFO

The mathematical problem that gPROMS is solving over time can be written in theform:

f(x, x, y, u) = 0 (5.1)

where

• x is a set of nx differential variables;

• x is a set of nx time derivatives of the differential variables x (i.e., x ≡ dx/dt);

• y is a set of ny algebraic variables;

• u is a set of nu input variables;

5.2. The elementary communication tasks 95

Page 97: Advanced Guide Gproms

gPROMS Advanced User Guide

• f(·) is a set of nx + ny ordinary differential (with respect to time) or algebraicequations.

It is worth noting that some of the variables x, y, u and the equations f may havearisen from the discretisation of variable and equation distributions over one or moreDISTRIBUTION DOMAINs. This is performed by gPROMS automatically before the startof the simulation.

At the start of the simulation, the input variables u are those which are ASSIGNed inthe PROCESS entity. Of the rest of the variables, the ones that occur prefixed with a $

sign at least once in the model are considered to be differential variables x, while allothers are algebraic variables y. However, the classification of a certain variable maychange during the simulation. For instance:

• Using a REPLACE task in a SCHEDULE, we may drop a specification imposed onone variable z1 replacing it by a specification on a different variable z2. In such acase, z2 will become an input variable, while z1 will become (most probably) analgebraic variable.

• A discontinuity resulting in a change in the active clause in a conditional (i.e.IF/THEN/ELSE or CASE) equation in a MODEL entity may alter the status of one ormore variables from differential to algebraic or vice versa.

In any case, the SENDMATHINFO task always reports on the state of the model at thetime of its execution.

One important characteristic of the mathematical model (Equation 5.1) is that it isusually very sparse. This means that each of the equations f(·) = 0 involves only asmall subset of the variables x, x, y, u. Since a model may involve tens of thousands ofequations and variables, this fact may be of particular significance to a Foreign Processthat seeks to carry out some mathematical manipulation of the gPROMS model.

The sparsity of a system of equations is related to the structure of its Jacobian matrixJ . This is the matrix of the partial derivatives of the equations with respect to thevariables, i.e.:

J ij ≡∂fi

∂wj(5.2)

where w is the vector of all variables in the system, i.e.:

w ≡

xxyu

(5.3)

5.2. The elementary communication tasks 96

Page 98: Advanced Guide Gproms

gPROMS Advanced User Guide

Of course, J ij will be zero if variable wj does not actually occur in equation fi = 0.In practice, the number of nonzero elements of J , nz, will normally be a very smallproportion of the (nx +ny)× (2nx +ny +nu) elements of this matrix. The total numberof nonzero elements, as well as the row and column in which each such element occurs,define the sparsity pattern of the model. This pattern may change during the simulationas a result of changes in the structure of individual equations (e.g. due to implicitmodel discontinuities described by IF and/or CASE constructs in MODELs). Once again,SENDMATHINFO will always report the state of the model at the time of its execution.

In addition to the SigName (see section 5.2.4.1), the execution of a SENDMATHINFO tasktransmits to the Foreign Process the information summarised below:

Timing information

The current simulation time t

Overall mathematical model statistics

The total number of variables in the model nx + ny + nu

The total number of equations in the model nx + ny

The number of differential variables in the model nx

The number of nonzero elements in the equation Jacobian nz

Information on each model variable x, y, u

Its current valueThe current value of its time derivative (x variables only)Its current classification as “input”, “differential” or “algebraic”Its name (in terms of its full gPROMS pathname)

Information on the model Jacobian J

The row number of each non-zero Jacobian elementThe column number of each non-zero Jacobian elementThe current numerical value of each non-zero Jacobian element

5.2.4.3 Side effects of SENDMATHINFO

SENDMATHINFO tasks have no side effect on the simulation results.

5.2.5 The LINEARISE elementary task

5.2.5.1 Background

gPROMSincludes a comprehensive model linearisation facility. This provides a meansof using non-linear models that are coded in gPROMSand are of arbitrary complexity(e.g. described by mixed, integro-partial differential and algebraic equations) for control-

5.2. The elementary communication tasks 97

Page 99: Advanced Guide Gproms

gPROMS Advanced User Guide

system design using linear-analysis techniques coded, for instance, in standard tools suchas MATLAB. This section provides a description of this facility.

5.2.5.2 The basics of linearisation

gPROMS models typically comprise mixed sets of non-linear differential and algebraicequations. These can be written in the form3:

f(x, x, y, u) = 0. (5.4)

Here x(t) and y(t) are the sets of differential and algebraic variables respectively (bothof which are unknowns to be determined by the gPROMS simulation) while x(t) are thederivatives of x(t) with respect to time, t. On the other hand, u is the set of input vari-ables that are given functions of time4. Now consider a point (x∗(t), x∗(t), y∗(t), u∗(t))on the simulation trajectory that satisfies equation 5.4. By linearising the above equa-tions at this point, we can obtain a linear model of the form:

∂f

∂xδx+

∂f

∂xδx+

∂f

∂yδy +

∂f

∂uδu = 0, (5.5)

where δz denotes the deviation of the variable z from the reference trajectory z∗(t) andall the partial derivatives are evaluated on the reference trajectory.

For most DAE systems of index 1, the matrix[

∂f∂x

∂f∂y

]

is non-singular, and consequently

the above system can be re-arranged to the form:

(

δxδy

)

= −[

∂f

∂x

∂f

∂y

]

−1 [

∂f

∂x

∂f

∂u

] (

δxδu

)

, (5.6)

which is a linearised form of the original non-linear system (5.4).

5.2.5.3 The linearised model generated by gPROMS

gPROMS generates a linearised model from three specified items of information:

• the non-linear model described by equation (5.4);

3Models of distributed processes described by mixed, integro-partial differential and algebraic equa-tions (IPDAEs) are automatically converted to the above form by the gPROMS discretisation techniques.

4It should be noted that, in gPROMS, the membership of the sets x(t), y(t), u(t) may change duringthe course of the simulation (e.g. via REPLACE tasks). The analysis presented in this document applies ata particular point during the simulation at which the linearised model is constructed from the nonlinearone.

5.2. The elementary communication tasks 98

Page 100: Advanced Guide Gproms

gPROMS Advanced User Guide

• a set of input variables U ; and

• a set of output variables Y .

The linearised model is of the general form:

δX = AδX +BδUδY = CδX +DδU

(5.7)

where X is a set of state variables and A, B, C and D are matrices of appropriatedimensions.

Although equation (5.7) seems to be very similar to equation (5.6), the variable sets X,Y and U are not generally identical to x, y and u, respectively. More specifically:

• the input variables U specified by the user are generally a subset of x, y, u;

• the output variables Y specified by the user are generally a subset of x, y, u;

• the state variables X are determined automatically by gPROMS as the minimalsubset of x that is necessary to express the effects of the specified inputs U on thespecified outputs Y via relationships of the form (5.7).

To understand the above points, consider a process of the form shown in figure 5.1 . Itcomprises four inter-connected sub-processes (“blocks”).

Now consider the following cases:

Case 1: specify U ≡ {u1, u2, u3, u4} and Y ≡ {y1, y2, y3, y4, y5}.This is the “classic” case in which the linearised model (5.7) corresponds exactlyto the non-linear model (5.4). The set of states X in (5.7) is identical to x,i.e. X ≡ {x1, x2, x3, x4, x5, x6} and the linearised model will be derived from theequations in all four blocks, i.e. the entire non-linear model (5.4).

Case 2: specify U ≡ {u1, u2} and Y ≡ {y4, y5}.This is still a “classic” case in the sense that U and Y are subsets of the trueprocess inputs u and outputs y respectively. The set of states X that is requiredin (5.4) to describe the effects of U on Y still comprises the entire set of differentialvariables x, i.e. X ≡ {x1, x2, x3, x4, x5, x6} and the linearised model will still bederived from the entire non-linear model (5.7).

5.2. The elementary communication tasks 99

Page 101: Advanced Guide Gproms

gPROMS Advanced User Guide

x3

x1, x2

u2

u1

y2

y1

y3 x5, x6

x4 y4

y5

u4

u3

Block 2

Block 1

Block 4

Block 3

Figure 5.1: Diagram of process considered.

Case 3: specify U ≡ {u1, u3} and Y ≡ {y4}.This is similar to Case 2. However, the set of states X that is required in (5.7)to describe the effects of U on Y needs to include only a subset of the differentialvariables x, i.e. X ≡ {x1, x2, x4}. The linearised model (5.7) will be derived fromthe non-linear equations in blocks 1 and 3 only.

Case 4: specify U ≡ {y1} and Y ≡ {x4, y4}.This is a “non-classic” case in which the specified set of inputs U includes a variablethat is actually an output of the non-linear model (5.4). The set of states X thatis required to describe the effects of U on Y is simply X ≡ {x4}. Moreover, onlythe non-linear equations in block 3 are needed to form the linearised model (5.7).

Case 5: specify U ≡ {u2, x2, u3} and Y ≡ {y1, y4, x6}.This is also a “non-classic” case in which the specified set of inputs U includesa differential variable the non-linear model (5.4). The set of states X that isrequired to describe the effects of U on Y is now X ≡ {x3, x4, x5, x6} and thelinearised model (5.7) is derived from the equations in blocks 2, 3 and 4 of thenon-linear model. Note that the variable x2 appears in the linearised model as aninput variable, U , and not as a state, X. Moreover, since it is a specified input,the equations that determine it (i.e. those in block 1) are not used for generatingthe linearised model.

5.2. The elementary communication tasks 100

Page 102: Advanced Guide Gproms

gPROMS Advanced User Guide

Case 6: specify U ≡ {u1, y2, u3} and Y ≡ {y4, y5}.Here, the specified set of inputs, U , includes a variable, y2, that is actually af-fected by another element of U , namely variable u1—consequently, y2 cannot beconsidered as an independent input variable. In this case, the linearisation proce-dure automatically removes y2 from the list of inputs. The corresponding columnsof matrices B and D (which are zeroes) are removed. Therefore, the number ofcolumns of matrices B and D is reduced accordingly.

5.2.5.4 Formal statement of the linearisation problem

The six cases presented above illustrate the complexity of what is, at first sight, a rathersimple problem. The required analysis is performed automatically by gPROMS and iscompletely transparent to the user. The overall specification of the new facility is asfollows:

Given:

• the non-linear model described by equation 5.4;

• a vector of variable values x(t), x(t), y(t), u(t) on the solution trajectory (i.e. sat-isfying equation 5.4);

• a set of input variables U ; and

• a set of output variables Y ,

Determine:

• the minimal set of states X ⊆ {x}; and

• the matrices A, B, C and D.

5.2.5.5 The LINEARISE elementary task

The linearisation facility is implemented as an elementary task that can be insertedanywhere in a gPROMS SCHEDULE.

The form of the task is illustrated in the example below5:

SCHEDULE

SEQUENCE

. . . . . . .

5 Note that “tag names” are allowed as aliases for the gPROMS variable path names, and thatsemicolons are used as separators between different variables in the lists of inputs and outputs. This isconsistent with the syntax of other FPI tasks such as GET and SEND.

5.2. The elementary communication tasks 101

Page 103: Advanced Guide Gproms

gPROMS Advanced User Guide

. . . . . . .

LINEARISE

SIGNALID "SignalName"

STATUS StatVar

INPUT_VARIABLE

Plant.Reactor.Fin ;

"InputConcentration" := Plant.Reactor.Xin ;

Plant.Reactor.Tout ;

OUTPUT_VARIABLE

Plant.Column(1).DistillateFlow ;

Plant.Column(1).DistillatePurity ;

"BottomFlowrate" := Plant.Column(2).BottomsFlow ;

Plant.Column(2).BottomsPurity ;

END

. . . . . . .

. . . . . . .

END

Notes:

• The alternative spelling LINEARIZE is also allowed.

• The input variable specification begins with the keyword INPUT VARIABLE. Thesimpler alternative INPUT is also allowed.

• The output variable specification starts with the keyword OUTPUT VARIABLE. Thesimpler alternative OUTPUT is also allowed.

• There must be exactly one input section and one output section. However, theycan be specified in any order.

• The SIGNALID and STATUS specifications are optional as in other Foreign Processtasks.

• The LINEARISE task has no side effects on the simulation results.

5.2.5.6 The gFPLINEARISE procedure

The LINEARISE task ultimately results in a call to a new Foreign Process Interface (FPI)routine, gFPLINEARISE.

This complements the existing FPI routines, gFPI, gFPPAUSE, gFPGET, gFPSEND, gFPSENDMand gFPT.

gFPLINEARISE receives the following list of arguments from gPROMS:

5.2. The elementary communication tasks 102

Page 104: Advanced Guide Gproms

gPROMS Advanced User Guide

FPID Full name of Foreign Process.FPHANDLE Identifier value assigned by gFPI.PRNAME Name of executing gPROMS Process.SIGNAL SignalName string specified for current instance of the task in the SCHEDULE.TIME Current simulation time.NU Number of input variables specified in the LINEARISE task. Any input vari-

ables that are not independent (cf. Case 6) will be removed, so in this case,this argument will give the number of independent input variables.

UINDICES Indices of input variables in the global variable array. Any input variablesthat are not independent (cf. Case 6) will be removed, so in this case, thisargument will give the indices of independent input variables.

UNAMES Names (tag names) of input variables. Any input variables that are notindependent (cf. Case 6) will be removed, so in this case, this argument willgive the names of independent input variables.

NY Number of output variables specified in the LINEARISE task.YINDICES Indices of output variables in the global variable array.YNAMES Names (tag names) of output variables.NX Number of the minimal subset of state variables.XINDICES Indices of state variables in the global variable array.XNAMES Names of state variables.A Matrix A in equation (5.7) (NX × NX elements, sorted by rows).B Matrix B in equation (5.7) (NX × NU elements, sorted by rows).C Matrix C in equation (5.7) (NY × NX elements, sorted by rows).D Matrix D in equation (5.7) (NY × NU elements, sorted by rows).STATUS Flag indicating success/failure of the LINEARISE task:

1: successful execution;0: non-existent Jacobian element;

-1: structurally singular DAE system;-2: failure of linear system solver.

All of the above arguments are already initialised with the corresponding informationby gPROMS on entry to gFPLINEARISE. They must be left unchanged on exit.

If implemented in FORTRAN, gFPLINEARISE will be a subroutine with the followingdeclaration:

SUBROUTINE gFPLINEARISE(FPID, FPHANDLE, PRNAME, SIGNAL, TIME,

+ NU, UINDICES, UNAMES,

+ NY, YINDICES, YNAMES,

+ NX, XINDICES, XNAMES,

+ A, B, C, D,

+ STATUS)

INTEGER FPHANDLE, NU, NY, NX, STATUS

INTEGER UINDICES(NU), YINDICES(NY), XINDICES(NX)

CHARACTER * 256 FPID, PRNAME, SIGNAL

5.2. The elementary communication tasks 103

Page 105: Advanced Guide Gproms

gPROMS Advanced User Guide

CHARACTER * 256 UNAMES(NU), YNAMES(NY), XNAMES(NX)

DOUBLE PRECISION TIME

DOUBLE PRECISION A(NX * NX), B(NX * NU), C(NY * NX), D(NY * NU)

If implemented in C/C++, the gFPLINEARISE function will have the following declara-tion:

extern "C" void gfplinearise_(

const char *foreignProcessId,

const long *foreignProcessHandle,

const char *processName,

const char *taskSignalName,

const double *currentTime,

const unsigned long *numberOfInputVariables,

const long *indicesOfInputVariables,

const char (*namesOfInputVariables)[256],

const unsigned long *numberOfOutputVariables,

const long *indicesOfOutputVariables,

const (*namesOfOutputVariables)[256],

Const unsigned long *numberOfMinimalStateVariables,

Const long *indicesOfMinimalStateVariables,

const (*namesOfMinimalStateVariables)[256],

Const double *aMatrix,

Const double *bMatrix,

Const double *cMatrix,

Const double *dMatrix,

long *Status);

5.2.5.7 The default gFPLINEARISE procedure

gPROMS is provided with a default FPI implementation.

Each execution of the default implementation of the gFPLINEARISE routine creates afile called PrName n.gLINEAR, where:

• PrName is the name of the process that is currently executed (as passed togFPLINEARISE by gPROMS).

• n is the number of instances of the LINEARISE task that have been executed sofar in the current simulation (e.g. 1, 2, 3, etc.).

The above files are placed in the Results folder of the corresponding Case. A samplefile is shown below.

5.2. The elementary communication tasks 104

Page 106: Advanced Guide Gproms

gPROMS Advanced User Guide

gPROMS Linearisation Utility

============================

Output generated at 11:06 on 2001-01-25

Process : TEST_LINEARMODEL

Signal ID : LinearisationTest

Linearised model generated at simulation time 0 in the form:

dX/dt = A X + B U

Y = C X + D U

Number of input variables, U : 2

Number of output variables, Y : 2

Number of state variables, X : 5

Input variables, U

------------------

Index Name

~~~~~ ~~~~

4 UNIT_1.U1

8 UNIT_1.U3

Output variables, Y

-------------------

Index Name

~~~~~ ~~~~

14 UNIT_1.Y(4)

15 UNIT_1.Y(5)

State variables, X

------------------

Index Name

~~~~~ ~~~~

1 UNIT_1.X_1

2 UNIT_1.X_2

5 UNIT_1.X_4

7 UNIT_1.X_5

9 UNIT_1.X_6

Matrix A

~~~~~~~~

A = [

-1.6711 0.057895 0.0000 0.0000 0.0000

5.2. The elementary communication tasks 105

Page 107: Advanced Guide Gproms

gPROMS Advanced User Guide

-0.073810 -0.39246 0.0000 0.0000 0.0000

-0.24211 -0.30080 0.0023256 0.0000 0.0000

-3.8452 -2.2786 0.0000 -41.131 -19.635

-1.0658 -0.63158 0.0000 -18.403 -8.3281

]

Matrix B

~~~~~~~~

B = [

1.5605 0.0000

-0.70119 0.0000

-0.68231 -0.033915

-2.1362 0.0000

-0.59211 0.0000

]

Matrix C

~~~~~~~~

C = [

-0.61517 -0.76430 -0.39535 0.0000 0.0000

0.0000 0.0000 0.0000 -42.254 -20.028

]

Matrix D

~~~~~~~~

D = [

-1.7337 -0.15116

0.0000 0.0000

]

5.2. The elementary communication tasks 106

Page 108: Advanced Guide Gproms

gPROMS Advanced User Guide

5.3 Using the FPI

Once you introduce one or more elementary communication tasks in your simulationSCHEDULE, gPROMS will seek to communicate with an external software package duringthe simulation. However, some additional information is required to specify exactlywhich external piece of software is to be involved in this communication. This issue isdiscussed in this section.

5.3.1 The standard FPI implementation

The standard gPROMS executable installed on your system already provides a basicFPI implementation. In this implementation, the elementary communication tasks otherthan LINEARISE operate in the following manner:

• The PAUSE task prints a message to the screen and pauses the simulation until theuser presses the ENTER (or carriage return) key (see section 5.2.1).

• The GET task prints a message to the screen; then the current value of each of thevariables being communicated is printed to the screen and the user is requestedto enter a new value (see section 5.2.2).

• The SEND task prints a message to the screen followed by the current values of thevariables being communicated (see section 5.2.3).

• The SENDMATHINFO task prints a message to the screen followed by all the infor-mation normally transmitted by this task (see section 5.2.4).

Albeit quite basic, the standard FPI implementation is often useful for initial testingof input files involving communication tasks, and, in particular, for ensuring that thecorrect communication actions are initiated by a given simulation.

5.3.2 Using non-standard FPI implementations

In most practical applications of the FPI, you will eventually want to use an FPI im-plementation that is more powerful than the standard one provided by gPROMS (seesection 5.3.1). This implementation will typically have been developed either by you orby another person (e.g. a gPROMS system programmer) and will be written as code ina conventional programming language (e.g. FORTRAN or C). The precise form of thiscode is discussed in detail in the chapter entitled “Developing New FPI Implementa-tions” in the “gPROMS System Programmer Guide”.

Here, we will assume that the FPI implementation that we wish to use is alreadyembodied in:

5.3. Using the FPI 107

Page 109: Advanced Guide Gproms

gPROMS Advanced User Guide

• a shared object library (.so) file under the UNIX operating system, or,

• a dynamic link library (.dll) file under the MS Windows NT operating system.

For the purposes of illustration in this section, let us suppose that this FPI implemen-tation file is called MyFPI.so or MyFPI.dll.

For gPROMS to be able to use the above FPI implementation to execute any commu-nication tasks that you may have in your simulation SCHEDULE, you need to ensure twothings: first, that gPROMS knows which FPI implementation you intend to use; andsecondly, that it is able to find the corresponding .so or .dll for this implementation.We deal with each of these issues separately below.

5.3.2.1 Specifying the FPI implementation to be used

The FPI implementation to be used by a given simulation must be specified in theSOLUTIONPARAMETERS section of the corresponding PROCESS entity. The parameter thatneeds to be specified is called FPI, and the name of the FPI implementation is enclosedin quotes. For instance, the specification:

SOLUTIONPARAMETERS

FPI := "MyFPI" ;

indicates that an FPI implementation called MyFPI6 should be used for the currentsimulation.

Some FPI implementations may require additional data that determine their precisebehaviour. Typically, such data will be held in an input file but this is not necessarily so.In any case, the additional data define a specific “instance” of an FPI implementation.The name of this instance must be appended to that of the FPI implementation7 andthe two must be separated with a double colon (::) separator.

For instance, suppose that the FPI implementation MyFPI needs to operate at someconstant factor to real-time, and that this factor (together with, perhaps, other param-eters) must be specified in a text file that you need to provide. Now, suppose that youhave prepared such a file and you have called it /home/user01/MyFPI.dat. In this case,the FPI specification will take the form:

SOLUTIONPARAMETERS

FPI := "MyFPI::/home/user01/MyFPI.dat" ;

6This would be implemented as either MyFPI.so under UNIX or MyFPI.dll under MS Windows NT.7In object-oriented programming terminology, the FPI implementation is called the “class” of all its

instances.

5.3. Using the FPI 108

Page 110: Advanced Guide Gproms

gPROMS Advanced User Guide

We note that gPROMS always passes the complete FPI specification string to the FPIimplementation. It is up to the FPI implementation to break down this string into itsclass and instance names (if appropriate), and to decide what to do with them.

A typical application of this facility is in the case of the ExcelFP FPI implementationthat provides a link between gPROMS simulations and user interfaces implemented inMicrosoft Excel spreadsheets (see section E.4). In such cases, the above instance nameis simply the name of the Excel spreadsheet to be used for this purpose.

5.3.2.2 Locating the FPI implementation file

Once you have specified the FPI implementation that you wish to use in a given simula-tion (see section 5.3.2.1), you must ensure that gPROMS is able to locate the correspond-ing FPI implementation file. This can be done by locating this file at an appropriateplace in your file system.

If an absolute path name is specified for the FPI implementation in the SOLUTIONPARAMETERSsection of the PROCESS (see section 5.3.2.1 above), then gPROMS will look for this spe-cific file. For instance, the specification:

SOLUTIONPARAMETERS

FPI := "/home/user01/MyFiles/MyFPI" ;

on a UNIX system will cause gPROMS to look for a file called /home/user01/MyFiles/MyFPI.so.If this file is not found, the simulation will be aborted.

If an absolute path name is not specified for the FPI implementation in SOLUTIONPARAMETERS,then gPROMS will search for the FPI implementation file at three different locations:

1. In a subdirectory called fpi of the export directory, see the chapter entitled“gPROMS ModelBuilder” in the “gPROMS Introductory User Guide”. For this tobe done the FPI implementation file must be imported or linked to ModelBuilder.

2. In a directory specified by the operating system “environment variable” GPROMSFPIDIRif the latter has been given a value8.

8The manner in which UNIX environment variables can be given a value depends on the com-mand line interpreter (“shell”) being used. For instance, to set GPROMSFPIDIR to a directory called/home/ps/library/FPI on a UNIX system operating under the C shell, type the command:

setenv GPROMSFPIDIR /home/library/FPI

The equivalent command under the Korn and Bourne shells is:

GPROMSFPIDIR=/home/library/FPI; export GPROMSFPIDIR

Please note that there are no blank spaces on either side of the equals sign in the above command.

5.3. Using the FPI 109

Page 111: Advanced Guide Gproms

gPROMS Advanced User Guide

3. In sub-directory fpi of the gPROMS installation directory9.

The three directories are searched in the order listed above. If the FPI implementa-tion file is found at one of these locations, then the search terminates successfully andgPROMS proceeds to use this file. Otherwise, the simulation is aborted.

9On UNIX systems, the gPROMS installation directory is normally specified by the GPROMSHOME

environment variable.

5.3. Using the FPI 110

Page 112: Advanced Guide Gproms

gPROMS Advanced User Guide

5.4 FPI performance issues

The issue of FPI performance is particularly important in view of the fact that manyof its applications will operate in real-time under stringent timing constraints.

Some of the factors that may affect this performance are considered below.

5.4.1 Effects of model size

In general, the larger the model, the longer its solution will take! In many cases, ofcourse, the size of the model will be determined by the application, and there may belittle scope for reducing it. However, for models that are going to be used time and timeagain in critical on-line applications, it is worth investing some effort in this direction.

In particular, large models arising from the discretisation of distributed systems maybe reduced by selecting a smaller number of discretisation elements while taking careto maintain sufficient accuracy for the purposes of the application—this accuracy canbe relatively low for many operator training applications.

You may also try to eliminate unnecessary intermediate variables and the equationsdefining them from such models. For instance, the original model for a tubular reactorunit may include variables for the reaction constants and the reaction rates, all of whichare distributed over one or more spatial dimensions. Although this may be advantageousfrom the point of view of clarity at the model development stage, it may be causingunnecessary overheads during the solution. In such cases, it may be better to eliminatethese variables and equations by substituting the kinetic and reaction rate expressionsdirectly within the material and energy conservation equations.

5.4.2 Effects of model re-initialisation

As explained in section 5.2.2.3, the interaction of a gPROMS PROCESS with the ForeignProcess through a GET task may cause changes to the underlying model. This then leadsto the need for re-initialisation, i.e. a calculation aiming at re-establishing consistentvalues for all variables in the model.

In general, this re-initialisation calculation involves the solution of the model equations,and can, therefore, be very time consuming. Fortunately, it takes place after GET tasksif and only if the value of at least one of the input or differential variables involved ischanged by the Foreign Process. In some cases, it may be possible to exploit this factby the FPI implementation not passing back to gPROMS insignificantly small changes.

5.4. FPI performance issues 111

Page 113: Advanced Guide Gproms

gPROMS Advanced User Guide

5.4.3 Effects of results logging

By default, gPROMS records the values of all the variables in the model at each report-ing interval, as specified either in the SOLUTIONPARAMETERS part of the PROCESS in theinput file (see section 9.2 of the “gPROMS Introductory User Guide”):

# PROCESS Example

UNIT Plant AS BigModel

SET

...

ASSIGN

...

PRESET

...

INITIAL

...

SOLUTIONPARAMETERS

REPORTINGINTERVAL := 10 ;

SCHEDULE

...

or manually at the start of the PROCESS execution:

Executing process Example...

gPROMS simulation initialisation took 0.010 seconds.

All 54 variables will be monitored during this simulation!

gPROMS problem construction took 0.020 seconds.

What reporting interval do you require?

Specify time interval as a positive number

Enter Value :

....

In both cases, the above specifications will result in values for all variables that arecurrently being MONITORed (cf. section 7.3.2) to be transmitted to all Output Channelsthat are currently active (cf. section 9.2) for archiving and display every 10 time units.For simulations involving large models, the effect of the associated overhead on real-time performance may well be unacceptable. It may also be unnecessary as the ForeignProcess may itself wish to assume responsibility for the archiving and display of theimportant variables transmitted to it from gPROMS via SEND tasks.

There are two easy ways to solve this problem. The first is to turn off all output channelsin the SOLUTIONPARAMETERS section of the PROCESS (see section 9.2):

5.4. FPI performance issues 112

Page 114: Advanced Guide Gproms

gPROMS Advanced User Guide

SOLUTIONPARAMETERS

gRMS := OFF ;

gPLOT := OFF ;

gExcelOutput := OFF ;

gUserOutput := OFF ;

The second is to switch off variable monitoring and/or to restrict the number of variablessent to the output channel. Monitoring can be turned off either before the simulationstarts by setting:

MONITOR := OFF ;

in the SOLUTIONPARAMETERS section or during the simulation by using the MONITOR task:

SCHEDULE

SEQUENCE...MONITOR OFF...

END

If there are many intermediate variables that do not need to be monitored, they canbe excluded from the set of variables that is sent to the output channel. This is doneby specifying only the variables of interest in the MONITOR section of the PROCESS (seesection 7.3.2).

5.4.4 Effects of FPI communication overheads

The communication between gPROMS and the FPI procedures is done using standardprocedure calls, and usually incurs negligible costs. However, this may not be the caseif the FPI routines then proceed to communicate with some other software througha different mechanism involving data transmission across networks (e.g. using UNIX“sockets” or some other message-passing protocol).

There is also some overhead incurred by gPROMS just before and just after calling theFPI procedures. This is mainly due to the need for copying data between the arrays tobe passed to FPI and the internal gPROMS data structures. This type of cost is likelyto be significant only for SENDMATHINFO tasks applied to large models.

5.4. FPI performance issues 113

Page 115: Advanced Guide Gproms

gPROMS Advanced User Guide

Chapter 6

Using Physical Properties forSimple Materials

Contents

6.1 The set of physical properties supported by gPROMS . . . 116

6.2 Incorporating physical properties in MODELs . . . . . . . . . . 120

6.3 Using MODELs incorporating physical property calculations . 123

6.3.1 Example 1: Explicit specification within a primitive MODEL . . 123

6.3.2 Example 2: Explicit specification within a higher-level MODEL . 124

6.3.3 Example 3: Explicit specification within a PROCESS . . . . . . . 124

6.3.4 Example 4: Implicit specification via parameter propagation . 124

6.4 The Multiflash physical property interface . . . . . . . . . . 128

6.4.1 Error handling in the gPROMS/Multiflash interface . . . . . . 128

6.4.2 Units of measurement . . . . . . . . . . . . . . . . . . . . . . . 130

6.4.3 Equilibrium flash methods in Multiflash . . . . . . . . . . . . . 130

6.4.4 Constructing a Multiflash input file . . . . . . . . . . . . . . . . 130

6.4.5 Using Multiflash stream types . . . . . . . . . . . . . . . . . . . 134

6.5 The IK-CAPE physical property interface . . . . . . . . . . 140

6.6 The CAPE-OPEN thermodynamics interface . . . . . . . . 141

6.6.1 CAPE-OPEN Property Packages and Property Systems . . . . 141

6.6.2 Using CAPE-OPEN Property Packages and Property Systems 141

6.6.3 CAPE-OPEN Property Package report . . . . . . . . . . . . . 143

6.6.4 CAPE-OPEN properties . . . . . . . . . . . . . . . . . . . . . . 143

114

Page 116: Advanced Guide Gproms

gPROMS Advanced User Guide

Most non-trivial process models make use of physical properties, such as density, en-thalpy and fugacity, all of which are typically functions of temperature, pressure andcomposition. The accuracy of estimation of these physical properties is one of the mostcritical factors in determining the accuracy of the model predictions.

In principle, physical property calculations may be coded as EQUATIONs within gPROMSMODELs. However, this is not practical for all but the simplest methods of computingphysical properties. It may also be unnecessary in view of the wide range of generaland reliable physical property calculation packages that are currently available.

This chapter describes how you can incorporate physical properties within your MODELs.The actual computation of these physical properties is performed by external physicalproperty software that is interfaced to gPROMS.

gPROMS defines a minimal set of physical properties that any external package inter-faced to it should provide, as well as the precise form of these properties. These arelisted in section 6.1. We strongly recommend that you use these and, if possible, onlythese physical properties in any MODELs that you write. In this way, you will be ableto use your MODELs with any physical property package that adheres to the standardgPROMS protocol.

Section 6.2 describes how precisely you can refer to the above physical properties in anyMODELs that you write. This is done by treating the external physical property softwareas a Foreign Object interfaced to gPROMS and providing services to it. You will findthat a basic understanding of Foreign Object concepts (described in chapter 4) is veryhelpful in making the most out of this section.

Section 6.3 describes how you can use MODELs (written by yourself or by others) thatinvolve physical property calculations.

In addition to defining a standard protocol for interacting with physical property pack-ages, interfaces to two such packages are already available to be licensed and used withgPROMS. The special characteristics of these interfaces are described in sections 6.4and 6.5 respectively.

gPROMS supports the CAPE-OPEN thermodynamics standard. This allows the useof external physical properties software complying to this standard within gPROMSMODEL entities. Section 6.6 describes the details of how this is done.

This chapter is concerned with physical property calculations of simple mixtures ofmolecular species existing in liquid and vapour phases. Physical properties for morecomplex materials (such as electrolytic systems) are considered in chapter 7. However,we recommend that you read and understand the present chapter before proceeding tochapter 7.

If you are interested in interfacing a different physical property package to gPROMS,then you need to read the chapter entitled “Interfacing Physical Property Packagesto gPROMS” in the “gPROMS System Programmer Guide” after you have read andthoroughly understood this chapter.

115

Page 117: Advanced Guide Gproms

gPROMS Advanced User Guide

6.1 The set of physical properties supported by gPROMS

External physical property packages are interfaced to gPROMS via the latter’s PhysicalProperty Interface (PPI). The PPI recommends that a minimal set of physical propertycalculations are supported by any such external package. These are listed in tables 6.1and 6.2 and include most of the common thermophysical and transport property calcu-lations used in the chemical industry.

CAUTION!

Always consult the documentation provided with the physicalproperty interface that you intend to use.

The physical properties listed in tables 6.1 and 6.2 represent a mini-mal set of properties that physical property packages interfaced to gPROMSare recommended to support.

There is no guarantee that all (or any!) of these properties are actu-ally supported by any particular interface. Also, some interfaces mayprovide access to properties other than those listed in tables 6.1 and 6.2.

The units of measurement of the physical properties and the variousquantities needed for their calculation may also vary from package topackage.

There a few points that you need to note about table 6.1:

• Scalar methods (like LiquidEnthalpy) return a single value, typically correspond-ing to a property of the mixture.

• Vector methods (like MolecularWeight) return an array of results, each elementof which corresponds to a different component in the mixture.

• Most methods receive three arguments, namely T, P and n.

– T is a scalar quantity that corresponds to the temperature and should be inKelvin.

– P is a scalar quantity that corresponds to the pressure and should be inPascal.

– n is an array-valued expression that corresponds to the number of moles ofthe components in the mixture.

6.1. The set of physical properties supported by gPROMS 116

Page 118: Advanced Guide Gproms

gPROMS Advanced User Guide

• The enthalpy, entropy, internal energy and volume calculations return total quan-tities. However, the corresponding specific quantities can be obtained by normal-ising the mole numbers n, i.e. passing molar fractions as arguments to the variousmethods.

• SurfaceTension is a special case: nL and nV are the number of moles of, respec-tively, the liquid and vapour phases in contact with each other.

• For the vapour phase properties, the spelling VaporXXXX is also recognised asan alternative to VapourXXXX.

The methods presented in table 6.2 require an equilibrium flash calculation to be per-formed. The following points need to be noted:

• The number of moles n in the inputs list refers to the overall composition of themixture.

• Property methods like Enthalpy and Density return the values for the whole sys-tem (and not for a specific phase as is the case for the methods listed in table 6.1).

• The content and size of the results array returned by the vector methods willdepend on the particular physical property package that is being used. You willneed to refer to the appropriate documentation (see, for instance, section 6.4 forone particular example).

• The method IsLiquidStable returns a Boolean result which is true if the phaseis liquid and stable, otherwise the result is false.

• The method IsVapourStable returns a Boolean result which is true if the phaseis vapour and stable, otherwise the result is false.

6.1. The set of physical properties supported by gPROMS 117

Page 119: Advanced Guide Gproms

gPROMS Advanced User Guide

Property Name Inputs Description Type

NormalBoilingPoint Normal boiling point VectorCriticalTemperature Critical temperature VectorCriticalPressure Critical pressure VectorCriticalVolume Critical volume VectorNormalFreezingPoint Melting point VectorMolecularWeight Molecular weight VectorIdealGasEnthalpyOfFormationAt25C Enthalpy of formation VectorNumberOfComponents Number of components ScalarVapourPressure T Pure component vapour pressures VectorLiquidCpCv T, P, n Ratio of CP to CV in the liquid phase ScalarVapourCpCv T, P, n Ratio of CP to CV in the vapour phase ScalarLiquidCompressibilityFactor T, P, n Compressibility factor for the liquid phase ScalarVapourCompressibilityFactor T, P, n Compressibility factor for the vapour phase ScalarLiquidEnthalpy T, P, n Total enthalpy of the liquid phase ScalarVapourEnthalpy T, P, n Total enthalpy of the vapour phase ScalarLiquidExcessEnthalpy T, P, n Excess enthalpy of the mixture ScalarLiquidEntropy T, P, n Total entropy of the liquid phase ScalarVapourEntropy T, P, n Total entropy of the vapour phase ScalarLiquidFugacityCoefficient T, P, n Liquid fugacity coefficients VectorVapourFugacityCoefficient T, P, n Vapour fugacity coefficients VectorLiquidActivityCoefficient T, P, n Liquid fugacity coefficients VectorLiquidGibbsFreeEnergy T, P, n Total Gibbs energy of the liquid phase ScalarVapourGibbsFreeEnergy T, P, n Total Gibbs energy of the vapour phase ScalarLiquidExcessGibbsFreeEnergy T, P, n Excess Gibbs energy of the mixture ScalarLiquidHeatCapacity T, P, n Liquid heat capacity at constant pressure ScalarVapourHeatCapacity T, P, n Vapour heat capacity at constant pressure ScalarLiquidEnergy T, P, n Total internal energy of the liquid phase ScalarVapourEnergy T, P, n Total internal energy of the vapour phase ScalarLiquidVolume T, P, n Total liquid volume ScalarVapourVolume T, P, n Total vapour volume ScalarLiquidDensity T, P, n Density of the liquid phase ScalarVapourDensity T, P, n Density of the vapour phase ScalarLiquidThermalConductivity T, P, n Thermal conductivity of the liquid phase ScalarVapourThermalConductivity T, P, n Thermal conductivity of the vapour phase ScalarLiquidViscosity T, P, n Viscosity of the liquid phase ScalarVapourViscosity T, P, n Viscosity of the vapour phase ScalarSurfaceTension T, P, nL, nV Surface tension of the mixture Scalar

Table 6.1: Physical property functions and their arguments

6.1. The set of physical properties supported by gPROMS 118

Page 120: Advanced Guide Gproms

gPROMS Advanced User Guide

Property Name Inputs Description Type

TPFlash T, P, n Equilibrium temperature and pressure flash VectorTVFlash T, P, n Equilibrium temperature and volume flash VectorPHFlash P,H, n Equilibrium pressure and enthalpy flash VectorUVFlash U, V, n Equilibrium internal energy and volume flash VectorEnthalpy T, P, n Total enthalpy of the mixture ScalarEntropy T, P, n Total entropy of the mixture ScalarVolume T, P, n Total volume of the mixture ScalarDensity T, P, n Total density of the mixture ScalarCompressibilityFactor T, P, n Total compressibility factor of the mixture ScalarEnergy T, P, n Total internal energy of the mixture ScalarHeatCapacity T, P, n Total heat capacity of the mixture ScalarGibbsFreeEnergy T, P, n Total Gibbs energy of the mixture ScalarBubbleTemperature P, n Bubble point temperature of the mixture ScalarBubblePressure T, n Bubble point pressure of the mixture ScalarDewTemperature P, n Dew point temperature of the mixture ScalarDewPressure T, n Dew point pressure of the mixture ScalarIsLiquidStable T, P, n Stability indicator for the liquid phase ScalarIsVapourStable T, P, n Stability indicator for the vapour phase ScalarVapourPhaseFraction T, P, n Vapour phase fraction of the mixture Scalar

Table 6.2: Equilibrium flash physical property functions and their arguments

6.1. The set of physical properties supported by gPROMS 119

Page 121: Advanced Guide Gproms

gPROMS Advanced User Guide

6.2 Incorporating physical properties in MODELs

External physical property packages are interfaced to gPROMS as Foreign Objects (cf.chapter 4). The usage of physical property Foreign Objects in MODELs is governed by aset of simple rules:

A. Each distinct Physical Property Foreign Object used by a MODEL is declared as aPARAMETER of type FOREIGN OBJECT. The latter keyword is normally followed bythe class of the Foreign Object (see section 4.1.5) which identifies the externalphysical properties software that will be used to implement this instance of theForeign Object. For example, a typical declaration would be:

PARAMETER PPP AS FOREIGN_OBJECT "Multiflash"

This simply states that:

– MODEL Flash will make use of a Physical Property Foreign Object.

– Whenever necessary within this MODEL (see below), the Foreign Object willbe referred to as PPP.

– PPP is implemented by a piece of external software (in this case, a physicalproperty package) called Multiflash. Thus, PPP is an “instance” of Multiflash.

One important thing to note is that the class of the Foreign Object must beenclosed in quotes (“Multiflash”). This is because it is neither a gPROMSkeyword nor an identifier that has previously been defined in the gPROMS inputfile.

B. The standard way of referring to physical property calculations within the MODEL

is as follows:

– for constant properties (mainly those relating to pure components propertiessuch as molecular weights):

ForeignObjectName.PhysicalProperty

– for variable physical properties:

ForeignObjectName.PhysicalProperty(InputList)

PhysicalProperty is one of those listed in the first column of tables 6.1 and 6.2while the InputList list is as given in the second column.

C. Each input of a physical property is a scalar or vector-valued variable or expression.

D. Each property returns a single scalar or vector-valued quantity. The latter maybe of type integer, logical or real. A method may be used anywhere in the MODEL

where an expression of the corresponding dimensionality and type is allowed.

6.2. Incorporating physical properties in MODELs 120

Page 122: Advanced Guide Gproms

gPROMS Advanced User Guide

An example of a MODEL making use of a physical properties package is shown in figure6.11.

1 # model entity "Flash"

2 PARAMETER

3 PPP AS FOREIGN_OBJECT "Multiflash"

4 NoComp AS INTEGER

5 Mw AS ARRAY(NoComp) OF REAL

6 VARIABLE

7 F, L, V AS MolarRate

8 Hf AS MolarEnergy

9 Q AS EnergyRate

10 T AS Temperature

11 P AS Pressure

12 x, y, z AS ARRAY(NoComp) OF MoleFraction

13 SET

14 NoComp := PPP.NumberOfComponents ;

15 Mw := PPP.MolecularWeight ;

16 EQUATION

17 F*z = L*x + V*y ;

18 F*Hf = PPP.LiquidEnthalpy(T,P,L*x) + PPP.VapourEnthalpy(T,P,V*y) + Q ;

19 x*PPP.LiquidFugacityCoefficient(T,P,x) =

20 y*PPP.VapourFugacityCoefficient(T,P,y) ;

21 SIGMA(x) = SIGMA(y) = 1 ;

22 ...

Figure 6.1: An example of a MODEL using physical properties

As we have already seen, line 3 specifies that the MODEL Flash makes use of a ForeignObject of type Multiflash, corresponding to a software package that is external togPROMS. For the purposes of defining this MODEL, this Foreign Object will be calledPPP.

Physical property methods are used in several places within the MODEL. For example:

• At line 14, we make use of the scalar integer method NumberOfComponents to SET

the value of the integer parameter NoComp.

• At line 15, we make use of the vector real method MolecularWeight to SET thevalue of the real array parameter Mw.

• At line 18, we invoke the methods LiquidEnthalpy and VapourEnthalpy to com-pute the (total) enthalpies of the liquid and vapour product streams respectively.

1Note that the line numbers shown in the figures have been included for ease of reference in thisdocument and are not part of the gPROMS language.

6.2. Incorporating physical properties in MODELs 121

Page 123: Advanced Guide Gproms

gPROMS Advanced User Guide

• At line 19 and 20, we invoke two more methods, namely LiquidFugacityCo-efficient and VapourFugacityCoefficient respectively to compute arrays ofliquid and vapour phase fugacity coefficients.

It is worth emphasising that method inputs can be expressions rather than simplevariables. One example has already been seen at line 18 of the above flash model. Asecond example is shown below where a liquid phase viscosity is evaluated at the meanof the inlet and exit conditions of a particular unit:

PPP.LiquidViscosity((Tin+T)/2, (Pin+P)/2, (xin+x)/2)

Finally, no direct reference can be made to an element of a vector-valued method. Forinstance, it is not possible to access directly the ith element of the vector of liquidfugacity coefficients returned by method LiquidFugacityCoefficient (see line 17 offigure 6.1 above). If such access is desired, an equation defining a vector-valued variableas being equal to the method result must first be introduced, e.g.:

LFC = PPP.LiquidFugacityCoefficient(T,P,x) ;

Other equations can then refer to individual elements of the variable LFC as desired.

CAUTION!

It is the model developer’s responsibility to check the type (including thecorrect units of the inputs) and the order of the arguments for each physicalproperty invocation. The current version of gPROMS will perform only aminimal check on these.

6.2. Incorporating physical properties in MODELs 122

Page 124: Advanced Guide Gproms

gPROMS Advanced User Guide

6.3 Using MODELs incorporating physical property calcula-tions

We have seen how physical property calculations can be incorporated within MODELs,being provided by external physical property packages. However, before these MODELscan be used to perform, say, a simulation of a given process, some additional informationrelating to physical properties needs to be specified.

Consider, for example, the Foreign Object PPP used in the example of figure 6.1. Wealready know that the methods (e.g. LiquidFugacityCoeffient) of this Foreign Objectwill be provided by an external physical property package called “Multiflash”. However,for these methods to be fully defined, we also need to know the set of componentsthat are involved in the mixture under consideration and also the particular type ofthermophysical model (e.g. the equation of state or activity coefficient model) thatwill be used to compute these properties. All of this information is associated with thespecific Foreign Object instance PPP. Indeed, two different instances of the same ForeignObject class within the same gPROMS simulation may involve different component setsand/or use different thermophysical property calculation options.

We note that the above information is not actually directly used by gPROMS as it reliesentirely on computations provided to it by the external physical property package. Infact, most modern physical property packages provide their own mechanism for thespecification of the above information. Typically, this takes the form of a text fileconforming to a proprietary format. The file can be constructed and edited using eithera text editor or a graphical user interface provided by the package.

As we have seen in section 4.2.2, the value of an instance of a Foreign Object is astring of characters that gPROMS passes to the external software to allow it to createthis instance. In the case of physical property Foreign Objects, this string typicallycorresponds to the name of the proprietary file that contains the information mentionedabove.

The value of an instance Foreign Object is specified in the SET section of either a MODEL

or a PROCESS entity. Here, we provide some examples of such specifications.

6.3.1 Example 1: Explicit specification within a primitive MODEL

Consider the flash model shown in figure 6.1. In this case, the value of the Foreign Objectparameter PPP could be specified by inserting the following line in its SET section (say,after line 13): of the Flash MODEL :

PPP := "Aromatics.mfl" ;

This states that the behaviour of Foreign Object PPP is defined by a Multiflash inputfile (.mfl) called Aromatics.mfl. For this to occur, the file must either be imported

6.3. Using MODELs incorporating physical property calculations 123

Page 125: Advanced Guide Gproms

gPROMS Advanced User Guide

into the project file or linked, see the chapter Entitled “gPROMS ModelBuilder” in the“gPROMS Introductory User Guide”. Alternatively, hte absolute path to the file canbe given.

The obvious disadvantage of the above way of specifying the Foreign Object value isthat all instances of MODEL Flash will be restricted to using the same set of componentsand thermophysical property calculation options. Thus, the generality and reusabilityof this MODEL is severely compromised!

6.3.2 Example 2: Explicit specification within a higher-level MODEL

Consider, for example, the MODEL TwoTankSystem illustrated in figure 6.2. It containstwo instances, HighPTank and LowPTank respectively, of the MODEL Flash shown in fig-ure 6.1. These two flashes operate at significantly different pressures, and consequentlymake use of different thermophysical property calculation options. On line 10, the For-eign Object PPP of the first of these two flashes is identified with a Multiflash inputfile HPThermo.mfl in the gPROMS export directory. On the other hand, line 11 SETsthe corresponding Foreign Object of the second flash to be equal to a PARAMETER LPPP

declared within TwoTankSystem (see line 3). Obviously, LPPP will have to be SET in aneven higher-level MODEL or in a PROCESS (see below).

As is standard in gPROMS, a composite MODEL entity can access any PARAMETER orVARIABLE declared within instances of lower-level MODEL entities that it refers to. Thisrule also holds for physical properties Foreign Object entities. For example, lines 13-17of figure 6.2 compute the combined volumetric flowrate of the liquid streams leaving thetwo tanks by making use of their individual physical property calculations.

6.3.3 Example 3: Explicit specification within a PROCESS

This is illustrated in figure 6.3. Lines 2 and 3 declare an instance called Plant of thecomposite MODEL defined in figure 6.2. The value of the Foreign Object parameter LPPPoccurring in that MODEL is then SET in lines 4 and 5.

6.3.4 Example 4: Implicit specification via parameter propagation

Like other gPROMS PARAMETERs, the values of Physical Properties Foreign Objects maybe specified implicitly via the gPROMS parameter propagation mechanism.

Parameter propagation is invoked automatically by gPROMS at the start of the execu-tion of a PROCESS if the value of any Foreign Object instance within the entire problemhas not been specified explicitly. In such cases, gPROMS will try to determine themissing value by searching for a Foreign Object that:

• is declared within a higher-level MODEL containing the instance of the MODEL which

6.3. Using MODELs incorporating physical property calculations 124

Page 126: Advanced Guide Gproms

gPROMS Advanced User Guide

has the unspecified Foreign Object, and

• has exactly the same name as the unspecified Foreign Object, and

• belongs to the same class as the unspecified Foreign Object, and

• has already been given a value either explicitly or implicitly.

If a Foreign Object fulfilling all of the above criteria is found, its value is also given to theunspecified Foreign Object. If no such Foreign Object is found, the algorithm is appliedrecursively, searching increasingly higher-level MODELs and ultimately the PROCESS itself.If, by the end of this procedure, the value of the unspecified Foreign Object remainsundetermined, an error occurs and the execution of the PROCESS is aborted.

The main practical implication of the parameter propagation mechanism is that, pro-vided the model developer adopts a standard name (say PPP) for all Physical PropertiesForeign Object instances of a certain class (e.g. Multiflash) in all MODELs that heor she develops, then it is sufficient to specify the value of this Foreign Object onceonly (usually in the PROCESS section) for it to be adopted automatically by the entireproblem.

Alternatively, if a plant has two distinct sections (e.g. a high temperature and a lowtemperature one) which require the use of two different Foreign Objects, again this canbe specified conveniently at the highest appropriate level, as illustrated in figure 6.4.Here, it is assumed that the MODELs HighTemperatureSection and LowTemperature-Section referred to in lines 3-4 each contain a Foreign Object called PPP and so doall of their sub-models. In this case, simply SETting appropriate values for the twohighest-level Foreign Objects in the PROCESS section (see lines 5-7) achieves the desiredspecification for the entire problem.

6.3. Using MODELs incorporating physical property calculations 125

Page 127: Advanced Guide Gproms

gPROMS Advanced User Guide

1 # model entity "TwoTankSystem"

2 PARAMETER

3 LPPP AS FOREIGN_OBJECT "Multiflash"

4 VARIABLE

5 TotalVolFlow AS VolumeRate

6 UNIT

7 HighPTank AS Flash

8 LowPTank AS Flash

9 SET

10 HighPTank.PPP := "HPThermo.mfl" ;

11 LowPTank.PPP := LPPP ;

12 EQUATION

13 TotalVol =

14 HighPTank.PPP.LiquidVolume

15 (HighPTank.T, HighPTank.P, HighPTank.L*HighPTank.x) +

16 LowPTank.PPP.LiquidVolume

17 (LowPTank.T, LowPTank.P, LowPTank.L*LowPTank.x) ;

Figure 6.2: SETting of Foreign Object values within composite MODELs

1 # process entity "PlantSimulation"

2 UNIT

3 Plant AS TwoTankSystem

4 SET

5 Plant.LPPP := "LPThermo.mfl" ;

6 ...

Figure 6.3: SETting of a Physical Properties Foreign Object value within a PROCESS

entity

6.3. Using MODELs incorporating physical property calculations 126

Page 128: Advanced Guide Gproms

gPROMS Advanced User Guide

1 # model entity "Plant"

2 UNIT

3 HTS AS HighTemperatureSection

4 LTS AS LowTemperatureSection

5 SET

6 HTS.PPP := "HighTThermo.mfl" ;

7 LTS.PPP := "LowTThermo.mfl" ;

8 EQUATION

9 ...

Figure 6.4: Foreign Object specification via parameter propagation

6.3. Using MODELs incorporating physical property calculations 127

Page 129: Advanced Guide Gproms

gPROMS Advanced User Guide

6.4 The Multiflash physical property interface

Multiflash is a physical property package developed and marketed by Infochem Com-puter Services Ltd2. A gPROMS interface for Multiflash providing the functionalitydescribed in section 6.1 is available and can be licensed together with gPROMS.

To use Multiflash, you need to go through the following steps:

1. Check whether your installation is licensed to use Multiflash. You can do thisby checking for the existence of file Multiflash.so in the fo/Multiflash sub-directory of the gPROMS installation directory on your computer system.

2. In your gPROMS project, ensure that you state the class of your Foreign Objectsto be Multiflash (see lines 2 and 3 of figure 6.1).

3. Create a Multiflash input file (.mfl) defining all the components, physical propertymodels, databanks etc. that are to be used by your problem (see section 6.4.4 formore details).

4. In your gPROMS project, SET the value of your Foreign Object to the name ofthis command file. For example, if the name of the command file is AlkaneMix-ture.mfl and the Foreign Object is called PhysProp, then the corresponding SET

statement in the MODEL or PROCESS will be:

SET

PhysProp := "AlkaneMixture.mfl" ;

5. Import the Multiflash command file (e.g. AlkaneMixture.mfl) into the gPROMSProject.

6. Any of the methods listed in tables 6.1 and 6.2 can now be used in your gPROMSproject3 .

6.4.1 Error handling in the gPROMS/Multiflash interface

Errors may occur at two different two stages when using Multiflash in gPROMS:

• During the creation of the Multiflash instance at the start of the simulation

This type of failure will almost always be caused by a mistake (e.g. syntax error)in the Multiflash input file. Any error at this stage will lead to an immediatetermination of the simulation. Specific attention should be given to the syntax

2See http://www.infochemuk.com3with the exception of the LiquidExcessEnthalpy which is not currently supported

6.4. The Multiflash physical property interface 128

Page 130: Advanced Guide Gproms

gPROMS Advanced User Guide

of component names according to the specifications described in the Multiflashmanual.

At least one message and an error number will be reported on the screen and a line-by-line analysis of the input file(s) will be dumped in the file MultiflashCommand-FileErrors.txt residing in the Results sub-directory of the Case. Please viewthis file to detect the source of the errors. In some cases, you may need to con-sult the Multiflash manual (using the number of the error reported) for moreinformation. Note that the error message:

No information available under this error number

very often indicates that the configfile (i.e. the file which tells Multiflash whereto locate its databanks and error files) could not be found. In such cases, youshould check the path specification for the configfile as described in the Multi-flash manual.

If the creation of the Multiflash instance is successful, a message will appear on thescreen to confirm this. gPROMS will then proceed with the numerical solution.

• During the numerical solution

Errors reported by Multiflash as a result of calls issued to it by gPROMS duringthe numerical solution phase are captured by the interface. If a fatal error occurs:

– A message will be printed on the screen pointing out:

∗ the particular method that was being called (e.g. the enthalpy calculationroutine);

∗ the values of the inputs (e.g. temperature, pressure, composition) of thismethod;

∗ the number used by Multiflash to identify this type of error; use this toconsult the Multiflash manual for more details.

– An error file will automatically be generated. The name of the error file willbe xxx-multiflash.error, where xxx is the name of the .mfl file, and itwill be located in the Results directory of the Case. For instance, if thename of the error file is AlkaneMixture.mfl, then the name of the errorfile will be AlkaneMixture-multiflash.error. The error file will containdetails of the input and output values of the Multiflash routine called aswell as the full listing of the command file. A screen message also appearsconfirming the creation of the error file. The error file should be included inall correspondence with [email protected].

Any non-fatal errors reported by Multiflash are ignored. For example, during aparticular iteration in gPROMS, the values of inputs may temporary go outsidethe recommended bounds of a correlation or the simulation may enter supercriticalregions. The numerical solution continues and, when appropriate, screen messagesare printed.

6.4. The Multiflash physical property interface 129

Page 131: Advanced Guide Gproms

gPROMS Advanced User Guide

6.4.2 Units of measurement

This section refers to the quantities listed in tables 6.1 and 6.2. The units for the inputquantities are:

• temperature T : Kelvin

• pressure P : Pa

• amount of substance, n: mol. This is the default unit. The amount of substancecan alternatively be expressed on a mass basis, in kg. To indicate this, the key-word, MASS, should be used when SETting the value of the Foreign Object, asfollows:

SET

PhysProp1 := "AlkaneMixture.mfl" ; #molar basis

PhysProp2 := "MASS:AlkaneMixture.mfl" ; #mass basis

Note that it is permissible to have both types of specifications in the same gPROMSMODEL or PROCESS. These will correspond to two different Foreign Objects.

• total enthalpy of mixture, H: Joule

• total volume of the mixture, V : m3

• total internal energy, U : Joule

The units of the returned quantities are given in table 6.3.

6.4.3 Equilibrium flash methods in Multiflash

All the flash methods listed in table 6.2 are made available by the Multiflash interface.

The results vector for the first four methods listed in 6.2 is of length 11 + 3 * NoComp.The information contained in it is organised as detailed in table 6.4.

An important point to note is that up to two liquid phases are assumed to be present atequilibrium. Consequently, the flash methods and results can handle a VLLE system.If a particular phase does not exist under the specified conditions, then its amount andall its intensive properties are returned as zero.

6.4.4 Constructing a Multiflash input file

The Multiflash input file is a text file containing the specification of the thermody-namic models, data sources for pure components, binary interaction parameters and

6.4. The Multiflash physical property interface 130

Page 132: Advanced Guide Gproms

gPROMS Advanced User Guide

components that occur in the mixture of interest4.

By convention, Multiflash input files have the extension .mfl.

There are two ways of constructing Multiflash input files:

• Create a Miscellaneous file in ModelBuilder and use the text editor to type in allthe necessary information. (Alternatively any text editor can be used, with thefile imported into ModelBuilder).

• Define the information using the graphical interface of Multiflash for Windows5,and then “export” this information to create the input file automatically, whichcan then be imported into ModelBuilder.

Full information on the use of the Multiflash for Windows package is provided with theMultiflash user manual. Here we are concerned primarily with the first approach6.

As an illustration, suppose we are interested in a mixture consisting of four components:methyl-acetate, methanol, water and toluene. We will use a text editor to construct thecorresponding Multiflash input file, specifying the information listed below in sequence.Note that each command line is terminated with a semicolon, and that comment linescan be inserted anywhere using the # symbol.

6.4.4.1 Source of Pure Component Data

The data source (databank) for pure components is set using the command PUREDATA

followed by the databank name:

PUREDATA databank name ;

where the databank name can be either DIPPR (from AIChE) or the standard Infochemfluids databank INFODATA.

6.4.4.2 Components In a Mixture

Components are added to the mixture using the command COMPONENTS followed by alist of components’ names. If a particular component’s name includes punctuation orspaces, then it should be enclosed in double quotation marks. Each name must be avalid component name for the databank considered. A list of components supported by

4Although Multiflash input files may also contain the mixture conditions (e.g. temperature, pressureand composition), this is not necessary (or meaningful) for the use of these files within the context ofgPROMS.

5This is a MS Windows-based program, the availability and use of which is covered by your MultiflashInterface licence.

6It may be helpful to note that a number of sample problem input files covering typical problemtypes are supplied with the Multiflash manual. It may be best to use one of these as the starting pointfor creating your own files.

6.4. The Multiflash physical property interface 131

Page 133: Advanced Guide Gproms

gPROMS Advanced User Guide

Multiflash is given in the Multiflash manual. For the specific mixture considered here,the command takes the following form:

COMPONENTS methylacetate methanol water toluene ;

6.4.4.3 Source of Binary Interaction Parameters Data

Binary Interaction Parameters (BIPs) are required by most of the mixture models inMultiflash for use by the thermodynamic and/or transport properties models for mix-tures. BIP data may be taken from a databank or entered directly on the commandline. The command has the following form:

BIPDATA databank name ;

The oilandgas databank is the most frequently used one; it provides BIP values fortypical compounds in oil and gas mixtures.

6.4.4.4 Model Definition

The thermodynamic and transport property models to be used are specified throughthe MODEL command which has the following general syntax:

MODEL model id MF model name Model options ;

where:

• model id is a user-defined name that will be used to refer to the particular com-bination of the property model and options specified;

• MF model name is the Multiflash name for the basic model—the list of recognisedmodels is given in the Multiflash manual;

• Model options are additional keywords that describe model variants, references toother previously described models or references to the source of binary interactionparameters.

For example, to define a model called model1 which involves the use of the Redlich-Kwong equation of state with a Soave modification, the command has the followingform:

MODEL model1 RKS ;

Any number of models may be defined in the same input file. For example, the com-mand:

MODEL model2 UNIFAC VLE model1 ;

6.4. The Multiflash physical property interface 132

Page 134: Advanced Guide Gproms

gPROMS Advanced User Guide

defines a second model, called model2, that makes use of the UNIFAC liquid-phaseactivity model7. Note that model2 specifies that the previously defined model1 is to beused for the calculation of gas phase properties.

Transport property models are optional and need only be defined if the computationof a transport property is required by the model. For example, in the common casewhere the Lohrenz-Bray-Clark (LBC) viscosity model is to be used, taking into accountthe model identified by model1 for the calculation of densities, the following commandis added:

MODEL model3 LBC * model1 ;

where model3 is the user defined model name and the asterisk indicates that the LBC

method should use the default option for matching the reference viscosities.

Similarly, if the Chung-Lee-Starling model (CLS) for the calculation of thermal conduc-tivity is to be used based on the user defined model1 model (for the calculation of therequired thermodynamic properties) the syntax has the format:

MODEL model4 CLS model1 ;

Other models based on simple mixing rules are also available.

The models that have been mentioned above are the ones that are most often used forseparations involving oil and gas mixtures. A complete list of all available models canbe found in the Multiflash manual.

6.4.4.5 Phase Descriptors

A phase descriptor is a user defined name that it is used to refer to a phase. It isnecessary to define a phase descriptor for every phase that Multiflash is to considerwhen performing a calculation.

The general format of the PD command used for defining a phase descriptor is as follows:

PD PD ID PHASE TYPE MODEL IDENTIFIERS ;

where PD ID is a user defined name that will be used to refer to the particular instanceof phase type and associated models. PHASE TYPE is a keyword that defines thephase type. Valid settings are GAS, LIQUID, SOLIDSOLUTION and CONDENSED (pure solidphase).

MODEL IDENTIFIERS is a list of up to six models. These must have already beendefined as described in section 6.4.4.4. The same model may appear more than once inthe list. The models specified determine the approach to be used for the computationof the thermodynamic and transport properties of the phase in the following order:

1. model to be used for fugacity (K-values)

7This is used in many applications since it is completely predictive and does not require any BIPs.

6.4. The Multiflash physical property interface 133

Page 135: Advanced Guide Gproms

gPROMS Advanced User Guide

2. model to be used for volume/density (optional)

3. model to be used for enthalpy/entropy (optional)

4. model to be used for viscosity (optional)

5. model to be used for thermal conductivity (optional)

6. model to be used for surface tension (optional)

For example, the command:

PD PDLiquid LIQUID model2 model1 model1 ;

defines a phase descriptor PDLiquid that corresponds to a liquid phase. Model model2will be used for the calculation of fugacities in this phase, while model model1 will beemployed for the computation of both volume/densities and enthalpies.

On the other hand, the command:

PD PDVapour VAPOUR model1 model1 model1 ;

defines a phase descriptor PDVapour corresponding to a vapour phase and using modelmodel1 model for the calculation of all thermodynamic properties (fugacity, volume,enthalpy).

Note that transport properties are not needed for the example, considered here. There-fore, only the first three (of the six) models are specified against each phase descriptor.

6.4.4.6 The complete Multiflash input file

The complete Multiflash input file for the example considered here will have the followingform:

PUREDATA DIPPR

COMPONENTS methylacetate methanol water toluene ;

BIPDATA oilandgas ;

MODEL model1 RKS ;

MODEL model2 UNIFAC VLE model1 ;

PD PDLiquid LIQUID model2 model1 model1 ;

PD PDVapour VAPOUR model1 model1 model1 ;

6.4.5 Using Multiflash stream types

A Multiflash input file, of the kind described in section 6.4.4, specifies the informationthat is necessary for the computation of the thermophysical and transport properties ofa particular type of material.

6.4. The Multiflash physical property interface 134

Page 136: Advanced Guide Gproms

gPROMS Advanced User Guide

However, many processes involve more than one type of material. For instance, inaddition to the main material being processed (which, say, is generally a mixture ofseveral components), the process may also involve other materials used in auxiliaryfunctions (e.g. cooling water).

Even when the set of components appears everywhere in the process, large variations inoperating conditions may mean that it is expedient to use different thermodynamic andtransport models in different sections of the plant – thereby, at least from the modellingpoint of view, treating the matter in each of those sections as a different material.

For all these reasons, we need to be able to handle more than one type of material in ourmodel. One way of doing this is by using separate Multiflash input files, one for eachmaterial, and creating a different instance for each one of them using the mechanismsdescribed in section 6.3.

A different, and computationally more efficient way, is by making use of a single Mul-tiflash input file containing multiple “stream types”8.

A stream type is a collection of components and phase descriptors, typically corre-sponding to the chemical species and the phases that may be present in a particularpart of the plant being studied. Thus, these are generally subsets of, respectively, allthe components and all the phase descriptors that are defined in a Multiflash input file.

6.4.5.1 Defining stream types in the Multiflash input file

A stream may be introduced to a Multiflash input file using the STREAMTYPE command(often abbreviated to ST). An extended version of the input file presented in section6.4.4.6 is shown below:

PUREDATA DIPPR

COMPONENTS methylacetate methanol water toluene ;

BIPDATA oilandgas ;

MODEL model1 RKS ;

MODEL model2 UNIFAC VLE model1 ;

PD PDLiquid LIQUID model2 model1 model1 ;

PD PDVapour VAPOUR model1 model1 model1 ;

ST Liq1 COMPONENTS methylacetate methanol; PDS PDLiquid PDVapour ;;

ST Wat COMPONENTS water; PDS PDLiquid ;;

The last two lines of the extended file define two separate stream types called Liq1 andWat respectively. The first one involves two of the four components declared in the inputfile while the second one contains only one of these components. Moreover, stream typeLiq1 involves both vapour and liquid phases while Wat is just liquid.

8These have no direct relationship with the concept of gPROMS stream types described in section6.4 of the gPROMS Introductory User Guide.

6.4. The Multiflash physical property interface 135

Page 137: Advanced Guide Gproms

gPROMS Advanced User Guide

Note that a semi-colon (;) is used to terminate each field of the stream type, as well asthe stream type command itself – hence the double semi-colons at the end of each of theabove commands. If the COMPONENTS keyword is omitted, all the components defined inthe input file are included in the stream type. Similarly, omitting the PDS keyword willinclude all the defined phase descriptors.

6.4.5.2 Referring to stream types in gPROMS entities

Consider, for example, a gPROMS model of a plant which includes a water-cooledcondenser .The latter makes use of two physical property Foreign Objects—one (calledProcessPPP) to compute the properties of the process stream being condensed and asecond one (called CoolantPPP) to provide the properties of the coolant.

The condenser is situated in a part of the plant where no toluene exists. However,the reaction section of the plant needs to handle all four components declared in theMultiflash input file in both the vapour and the liquid phases. It does this by usinganother physical property Foreign Object, called GenericPPP.

Assuming that the Multiflash input file is called Organics.mfl, we can then specify thefollowing values for the physical property Foreign Objects in the condenser:

SET

Condenser.ProcessPPP := "Organics.mfl<Liq1>" ;

Condenser.CoolantPPP := "Organics.mfl<Wat>" ;

RxnSection.GenericPPP := "Organics.mfl" ;

We note that the first two specified values comprise the name of the Multiflash inputfile followed by the name of the stream type enclosed in angled brackets. As usual,each value is enclosed within double quotes. On the other hand, the last specificationcomprises simply the name of the Multiflash input file.

In this case, an invocation of the method ProcessPPP.LiquidEnthalpy within the con-denser model would return the liquid enthalpy for the methyl-acetate/methanol mixturewhile CoolantPPP.LiquidEnthalpy will return the liquid phase enthalpy for the watercoolant. Also, GenericPPP.LiquidDensity will return the liquid-phase density for thefour-component system. On the other hand, any attempt to invoke CoolantPPP.Vapour-Enthalpy will result in a failure because no vapour phase descriptor has been definedfor the Wat stream.

As the above example shows, as far as gPROMS is concerned, using multiple streamtypes within the same Multiflash input file is little different to using multiple Multiflashinstances, each being described by a separate Multiflash input file. However, the useof streams within a single input file may result in significant benefits in computationalefficiency during the actual computation.

It is also possible to combine mass basis (see section 6.4.2) and stream type specificationsas follows:

6.4. The Multiflash physical property interface 136

Page 138: Advanced Guide Gproms

gPROMS Advanced User Guide

SET

Condenser.CoolantPPP1 := "Organics.mfl<Wat>" ; #molar basis

Condenser.CoolantPPP2 := "MASS:Organics.mfl<Wat>" ; #mass basis

6.4. The Multiflash physical property interface 137

Page 139: Advanced Guide Gproms

gPROMS Advanced User Guide

Property Units of measurement

NumberOfComponents -MolecularWeight g/molCriticalTemperature KCriticalPressure PaCriticalVolume m3/molBoilingPoint KMeltingPoint KVapourPressure PaCpCv -CompressibilityFactor -Enthalpy JEntropy J/KFugacityCoefficients -ActivityCoefficients -GibbsEnergy JExcessGibbsEnergy JHeatCapacity J/KInternalEnergy JVolume m3

Density kg/m3

Conductivity W/(m.K)Viscosity Pa.sSurfaceTension N/mBubbleTemperature KBubblePressure PaDewTemperature KDewPressure PaVapourPhaseFraction -

Table 6.3: Units of the properties returned by the Multiflash interface

6.4. The Multiflash physical property interface 138

Page 140: Advanced Guide Gproms

gPROMS Advanced User Guide

Variable Length Position in Results vectorFrom To

Temperature 1 1 1Pressure 1 2 2

Vapour molar fractions NoComp 3 2+NoCompVapour enthalpy 1 3+NoComp 3+NoCompVapour molar amount 1 4+NoComp 4+NoCompVapour volume 1 5+NoComp 5+NoComp

1st liquid molar fractions NoComp 6+NoComp 5+2*NoComp1st liquid enthalpy 1 6+2*NoComp 6+2*NoComp1st liquid molar amount 1 7+2*NoComp 7+2*NoComp1st liquid volume 1 8+2*NoComp 8+2*NoComp

2nd Liquid molar fractions NoComp 9+2*NoComp 8+3*NoComp2nd Liquid enthalpy 1 9+3*NoComp 9+3*NoComp2nd Liquid molar amount 1 10+3*NoComp 10+3*NoComp2nd Liquid volume 1 11+3*NoComp 11+3*NoComp

Table 6.4: Results vector organisation for the Multiflash equilibrium flash methods

6.4. The Multiflash physical property interface 139

Page 141: Advanced Guide Gproms

gPROMS Advanced User Guide

6.5 The IK-CAPE physical property interface

The IK-CAPE physical property package has been developed by the IK-CAPE consor-tium of German chemical companies9 with the aim of standardising the usage of physicalproperties across these companies.

If you wish to use the IK-CAPE package, you need to go through the following steps:

1. Check whether your installation is licensed to use IK-CAPE. You can do this bychecking for the existence of file IKCAPE.so in the fo/IKCAPE sub-directory of thegPROMS installation directory on your computer system.

2. In your gPROMS project, ensure that you state the class of your Foreign Objectsto be IKCAPE (see lines 2 and 3 of figure 6.1).

3. Create the IK-CAPE neutral file you would like to use. The form of this fileis described in detail in the document “Thermodynamik-Schnittstelle fur CAPE-Anwendungen: User’s Guide”. Your neutral file should contain at least one ma-terial system10.

4. In your gPROMS project, SET the value of your Foreign Object to the name of thisneutral file. For example, if the name of the neutral file is BenzeneToluene.dat

located in the Miscellaneous Files folder of the gPROMS project and the ForeignObject is called PhysProp, then the corresponding SET statement in the MODEL orPROCESS will be:

SET

PhysProp := "BenzeneToluene.dat" ;

5. Any of the methods listed in table 6.1 can now be used in your gPROMS inputfile with the exception of the BoilingPoint, LiquidEntropy, VapourEntropy,LiquidGibbsEnergy and VapourGibbsEnergy properties that are not currentlysupported by the IK-CAPE package.

9Current membership (June 1998): BASF, BAYER, Degussa, DOW Chemical, Hoechst and Huls.10The current implementation of the IK-CAPE physical property interface allows only one material

system in each neutral file; if your file contains more than one such system, all but the first one will beignored. If you wish to use multiple material systems with the IK-CAPE package, simply insert themin separate neutral files and treat the latter as different instances of class IKCAPE in your project.

6.5. The IK-CAPE physical property interface 140

Page 142: Advanced Guide Gproms

gPROMS Advanced User Guide

6.6 The CAPE-OPEN thermodynamics interface

gPROMS is equipped with a CAPE-OPEN compliant “socket” which allows gPROMSmodels to make use of external physical properties software complying to the CAPE-OPEN Thermo specification11.

6.6.1 CAPE-OPEN Property Packages and Property Systems

The CAPE-OPEN standard for thermophysical properties12 is based on the concept ofa Property Package (PP). This is a software component that represents a particularmixture of interest; it involves a combination of:

• a specification of the species appearing in the mixture;

• a specification of the set of thermodynamic models that will be used for the com-putation of the physical properties of this mixture;

• a set of calculation routines for performing the above computations;

• all fundamental data required for the above computations (e.g. critical constantsfor pure components, binary interaction coefficients for pairs of components, andso on).

A collection of PPs is called a Property System (PS).

A user can construct a PP using the external CAPE-OPEN compliant physical proper-ties software tool. Depending on the tool used, these PPs may exist independently, orform part of a PS.

Before a CAPE-OPEN PP (or PS) can be used in gPROMS, it has to be installed in theMS Windows registry of the computer on which it will be executing. If this is the samecomputer as the one on which the PP (or PS) was created, this installation is likely tohave been performed automatically at the end of the installation process and no furtheraction is required. Otherwise, the user will need to follow instructions provided withthe PP (or PS).

6.6.2 Using CAPE-OPEN Property Packages and Property Systems

Once a CAPE-OPEN PP or PS has been installed, it can be used via standard gPROMSmechanisms for physical properties packages. Thus, the user will typically:

11This is currently defined only for Microsoft COM components. Hence, the whole of this section onCAPE-OPEN is only applicable to the Microsoft Windows operating system.

12Full details are given in the CAPE-OPEN document on “Open In-terface Specification: Thermodynamic and Physical Properties” available athttp://www.colan.org/archive/specs/v09x/doc/04 CO Thermodynamics and PhysProps.pdf.

6.6. The CAPE-OPEN thermodynamics interface 141

Page 143: Advanced Guide Gproms

gPROMS Advanced User Guide

• Introduce a Foreign Object for thermophysical property calculations in each MODELentity that needs such calculations, (cf. section 6.2).

PARAMETER

PhysProps AS FOREIGN_OBJECT "Thermo"

VARIABLE

...

EQUATION

F * h_in = L * PhysProps.LiquidEnthalpy (T, P, x) +

V * PhysProps.VapourEnthalpy (T, P, y) ;

...

• Use standard gPROMS physical property calculation methods in the MODEL en-tity’s equations (cf. section 6.1). CAPE-OPEN property packages in gPROMSsupport all the properties listed in table 6.1. Consequently, CAPE-OPEN compli-ant packages and other packages are completely interchangeable without the needfor any modification to gPROMS MODEL entities that make use of them.

In addition to the properties listed in table 6.1, CAPE-OPEN PPs and PSs canalso support many more properties. The full list and a more detailed discussionis given in section 6.6.4.

• In the PROCESS entity, declare the Foreign Object to belong to class CapeOpen-Thermo. The “value” of the particular instance of this Foreign Object is set tothe ProgId under which the CAPE-OPEN PP or PS has been installed in the MSWindows registry (cf. section 6.6.1), preceded by the qualifier “(PP)” or “(PS)”respectively. For example, the following specification:

UNIT

F AS Flash

SET

F.PhysProps := "CapeOpenThermo::(PP)ThermoCo.AroPack.1" ;

...

specifies that the Foreign Object PhysProps appearing in instance F of MODEL

Flash is a CAPE-OPEN compliant PP that has been installed in the MS Win-dows registry under the ProgId ThermoCo.AroPack.1. On the other hand, thespecification:

SET

F.PhysProps := "CapeOpenThermo::(PS)ThermoCo.PropSys.1<AroPack>" ;

sets the Foreign Object instance to PP called AroPack contained within a PSinstalled in the registry as ThermoCo.PropSys.1.

If, for whatever reason, the ProgIds of the available PPs and PSs are not known,then they can be determined by executing the above PROCESS entity withoutspecifying a ProgId, i.e.

6.6. The CAPE-OPEN thermodynamics interface 142

Page 144: Advanced Guide Gproms

gPROMS Advanced User Guide

UNIT

F AS Flash

SET

F.PhysProps := "CapeOpenThermo::" ;

...

This incomplete specification will cause gPROMS to produce a list of the ProgIdsof all CAPE-OPEN PPs and PSs that are currently installed in the registry, aswell as a list of the PPs in each PS.

6.6.3 CAPE-OPEN Property Package report

Each time a CAPE-OPEN PP (or PS) is used by gPROMS, it will create a report filein the Results folder of the Case containing the following:

• date and time of usage;

• identification in the form of the name and description as supplied by the PP itself;

• the list of chemical components the PP supports; the list of CAPE-OPEN phasesit supports;

• the list of the CAPE-OPEN properties supported by the PP.

Note that as explained in section 6.6.4, in some cases, the names of CAPE-OPENphases and CAPE-OPEN properties will need to be combined to form the ForeignObject method to be used in gPROMS MODEL entities.

All property package report files will be placed in the output directory relative to wheregPROMS is running from. The name of each file will be in the form pppp.txt, wherepppp is:

• the ProgId in the case of a PP, for example, ThermoCo.AroPack.1.txt

• the ProgId.PropertyPackageName in the case of a PS, for example:ThermoCo.PropSys.1.AroPack.txt

6.6.4 CAPE-OPEN properties

In addition to the properties listed in table 6.1, CAPE-OPEN property packages canalso support a wider list of properties. The full list of properties is given in tables 6.5and 6.6, while the list of CAPE-OPEN phases is given in table 6.7. Table 6.5 is a listof the pure component properties and universal constants, while table 6.6 contains allthe model-dependent and/or mixture properties.

6.6. The CAPE-OPEN thermodynamics interface 143

Page 145: Advanced Guide Gproms

gPROMS Advanced User Guide

To construct the name of the physical property to use as a Foreign Object method ingPROMS, it may be necessary, for some methods, to prefix the CAPE-OPEN name intable 6.6 with a CAPE-OPEN phase name from table 6.7. For example, to calculate thedensity of solid at given conditions the gPROMS method name will be SolidDensity,which is obtained by prefixing the CAPE-OPEN property Density with the CAPE-OPEN phase Solid. In contrast, the pure component vapour pressures are obtainedfrom gPROMS by calling the CAPE-OPEN property VaporPresuure which does notneed any prefix.

It is important to note that any particular CAPE-OPEN property package will notnecessarily support all the methods and phases given in tables 6.5 to 6.7, nor all themethods in table 6.1. The details of what a particular property package supports aregiven in the property package report (cf. section 6.6.3).

Some CAPE-OPEN property packages will provide derivatives with respect to temper-ature(T), pressure(P), and/or number of moles(n). The CAPE-OPEN names of prop-erty derivatives are formed by appending one of “.DTEMPERATURE”, “.DPRESSURE”, or“.DMOLES” to the CAPE-OPEN property names given in table 6.6. For example, theCAPE-OPEN property name “ENTHALPY.DMOLES” indicates that the property packageprovides the derivatives of the Enthalpy (for all phases) with respect to number ofMoles. These derivatives are used internally by gPROMS — do not use these methodswithin your own gPROMS models.

The default units for temperature, pressure, and amount of material in tables 6.5 and 6.6are Kelvin (K), Pascal (Pa), and moles (mol) respectively. The amount of materialcan alternatively be expressed on a mass basis, in kilograms (kg). To indicate this, thekeyword, MASS, should be used when SETting the value of the Foreign Object, as follows:

SET

F.PhysProp1 := "CapeOpenThermo::(PP)ThermoCo.AroPack.1" ; #molar basis

F.PhysProp2 := "CapeOpenThermo::MASS:(PP)ThermoCo.AroPack.1" ; #mass basis

The same syntax is used for PSs. When mass basis is specified, all the results returnedby the PP or PS are converted accordingly. The values of the universal constants intable 6.5 are not converted.

6.6. The CAPE-OPEN thermodynamics interface 144

Page 146: Advanced Guide Gproms

gPROMS Advanced User Guide

CAPE-OPEN Property Units Inputs ResultType

MolecularWeight kg/mol none VectorCriticalTemperature K none VectorCriticalPressure Pa none VectorCriticalVolume m3/mol none VectorCriticalCompressibilityFactor – none VectorCriticalDensity mol/m3 none VectorAcentricFactor – none VectorDipoleMoment C.m none VectorParachor m3kg0.25/s0.5mol none VectorGyrationRadius m none VectorAssociationParameter – none VectorDiffusionVolume m3/mol none VectorDiffusionCoefficient m2/s none VectorVanderwaalsVolume m3/mol none VectorVanderwaalsArea m2/mol none VectorEnergyLennardJones J none VectorLengthLennardJones m none VectorNormalBoilingPoint K none VectorHeatOfVaporizationAtNormalBoilingPoint J/mol none VectorNormalFreezingPoint K none VectorHeatOfFusionAtNormalFreezingPoint J/mol none VectorLiquidDensityAt25C mol/m3 none VectorLiquidVolumeAt25C m3/mol none VectorIdealGasGibbsFreeEnergyOfFormationAt25C J/mol none VectorIdealGasEnthalpyOfFormationAt25C J/mol none VectorStandardFormationEnthalpySolid J/mol none VectorStandardFormationEnthalpyLiquid J/mol none VectorStandardFormationEnthalpyGas J/mol none VectorStandardFreeFormationEnthalpySolid J/mol none VectorStandardFreeFormationEnthalpyLiquid J/mol none VectorStandardFreeFormationEnthalpyGas J/mol none VectorStandardEntropySolid J/(mol.K) none VectorStandardEntropyLiquid J/(mol.K) none VectorStandardEntropyGas J/(mol.K) none Vector

CAPE-OPEN universal constants

StandardAccelerationOfGravity 9.80665m/s2

AvogadroConstant 6.02214199(47)×1023/molBoltzmannConstant 1.3806503(24)×1023J/KMolarGasConstant 8.314472(15)J/(mol.K)

Table 6.5: CAPE-OPEN pure component constant properties and universal constants

6.6. The CAPE-OPEN thermodynamics interface 145

Page 147: Advanced Guide Gproms

gPROMS Advanced User Guide

CAPE-OPEN Property Units Inputs ResultType

Properties that do not need a phase prefixVaporPressure Pa T VectorSublimationPressure Pa T VectorMeltingPressure Pa T VectorGlassTransitionTemperature K P VectorSolidSolidPhaseTransitionTemperature K P VectorSolidSolidPhaseTransitionPressure Pa T VectorVirialCoefficient m3/mol T VectorExpansivity 1/K T VectorHeatOfVaporization J/mol T VectorHeatOfSublimation J/mol T VectorHeatOfFusion J/mol T VectorHeatOfSolidSolidPhaseTransition J/mol T VectorVolumeChangeUponVaporization m3/mol T VectorVolumeChangeUponSublimation m3/mol T VectorVolumeChangeUponMelting m3/mol T VectorVolumeChangeUponSolidSolidPhaseTransition m3/mol T VectorIdealGasHeatCapacity J/(mol.K) T VectorIdealGasEnthalpy J/mol T Vector

Table continued on next page . . .

6.6. The CAPE-OPEN thermodynamics interface 146

Page 148: Advanced Guide Gproms

gPROMS Advanced User Guide

. . . continued from previous page

Properties that may need a prefix with one of the phase namesin table 6.7 (depends on the physical property package)

SurfaceTension† N/m T,P,n1,n2 ScalarCompressibilityFactor – T,P,n ScalarJouleThomsonCoefficient K/Pa T,P,n ScalarHeatCapacity J/(mol.K) T,P,n ScalarExcessEnthalpy‡ J/mol T,P,n ScalarExcessEnergy J/mol T,P,n ScalarExcessGibbsFreeEnergy J/mol T,P,n ScalarExcessHelmholtzFreeEnergy J/mol T,P,n ScalarExcessEntropy J/(mol.K) T,P,n ScalarExcessVolume m3/mol T,P,n ScalarCompressibility 1/Pa T,P,n ScalarViscosity Pa.s T,P,n ScalarThermalConductivity W/(m.K) T,P,n ScalarSelfDiffusionCoefficient m2/s T,P,n ScalarFugacity Pa T,P,n VectorFugacityCoefficient – T,P,n VectorLogFugacityCoefficient – T,P,n VectorActivity‡ – T,P,n VectorActivityCoefficient‡ – T,P,n VectorKvalues† – T,P,n1,n2 VectorLogKvalues – T,P,n1,n2 VectorDensity mol/m3 T,P,n ScalarEnthalpy J T,P,n ScalarEntropy J/K T,P,n ScalarVolume m3 T,P,n ScalarEnergy J T,P,n ScalarFreeEnergy J T,P,n ScalarGibbsFreeEnergy J T,P,n ScalarHelmholtzFreeEnergy J T,P,n Scalar† These methods do not take a prefix.

‡ These methods must always be prefixed with Liquid.

Table 6.6: CAPE-OPEN non-constant properties

CAPE-OPEN phase nameVaporLiquidSolid

Table 6.7: CAPE-OPEN thermodynamic phases

6.6. The CAPE-OPEN thermodynamics interface 147

Page 149: Advanced Guide Gproms

gPROMS Advanced User Guide

Chapter 7

Using Physical Properties forComplex Materials

Contents

7.1 General concepts for electrolyte system modelling . . . . . 150

7.1.1 Species and phases . . . . . . . . . . . . . . . . . . . . . . . . . 150

7.1.2 Vapour-liquid equilibrium . . . . . . . . . . . . . . . . . . . . . 151

7.1.3 Liquid-phase reactions . . . . . . . . . . . . . . . . . . . . . . . 151

7.1.4 Liquid-solid equilibrium . . . . . . . . . . . . . . . . . . . . . . 152

7.1.5 Fugacity and activity coefficients . . . . . . . . . . . . . . . . . 152

7.2 Electrolytic physical property methods . . . . . . . . . . . . 153

7.3 The OLI physical property interface . . . . . . . . . . . . . . 159

7.3.1 Electrolyte system report file . . . . . . . . . . . . . . . . . . . 160

7.3.2 Error handling in the OLI interface . . . . . . . . . . . . . . . . 160

148

Page 150: Advanced Guide Gproms

gPROMS Advanced User Guide

The state of the simple materials considered in chapter 6 can be described in terms oftheir thermodynamic phase and their temperature, pressure, and molecular composition(e.g. a vector of molar fractions). This chapter is concerned with more complex materialsthat need to be characterised by additional properties or attributes. The latter mayinclude size, shape, electrical charge, porosity and surface roughness. Examples ofcomplex materials include electrolytes, polymers, petroleum fractions and particulatesolids.

gPROMS provides a generalised interface to physical properties packages for electrolyticsystems. To make the most of this chapter, you should already be familiar with theconcepts introduced in chapter 6 for simple materials. You should then read:

• Section 7.1.This describes the general concepts that underpin all electrolytic physical propertypackages interfaced to gPROMS. It is important to understand these concepts tobe able to make effective use of the facilities provided by these packages in yourmodels.

• Section 7.2.This describes the methods provided by all physical property packages interfacedto gPROMS via the standard electrolytic physical properties interface.

• Section 7.3.This describes how to use one particular interface, namely that to the OLI1 packagefor aqueous electrolytic systems.

1OLI Systems Inc. (http://www.olisystems.com)

149

Page 151: Advanced Guide Gproms

gPROMS Advanced User Guide

7.1 General concepts for electrolyte system modelling

This section describes the general concepts that underpin the gPROMS electrolyticphysical properties interface.

7.1.1 Species and phases

An electrolytic material may involve several different classes of species, including:

– molecular species (e.g. H2O, HCl, CO2)

– ionic species (e.g. Cl−, OH−, H+, Na+)

– solid components (e.g. NaCl, Na2SO4)

– hydrates (e.g. NaOH.1H2O)

In general, the above species may occur in a number of thermodynamic phases. Theelectrolytic physical property interface assumes that the following phases may appearin a system:

– a single vapour phase comprising a mixture of molecular species;

– a single liquid phase comprising a mixture of molecular species and ions;

– one or more solid phases, each comprising a single solid component or hydrate.

The interface makes the following additional assumptions:

– All species that exist in the vapour phase will also exist in the liquid phase.

– Species in the solid phase(s) do not exist in either the vapour or liquid phases.

– If the same chemical component exists in both solid and liquid phases, it will bemodelled as two different species.

– The species are ordered as follows:

– species that occur in both vapour and liquid phases, followed by,

– species that occur in the liquid phase only, followed by,

– species that occur in the solid phase only.

As an example, the following species may be present in a system comprising sodiumchloride and water:

7.1. General concepts for electrolyte system modelling 150

Page 152: Advanced Guide Gproms

gPROMS Advanced User Guide

Vapour:H2O(vap),HCl(vap)Liquid: H2O(liq),HCl(aq), OH−,H+, Na+, Cl−

Solid : NaCl(sol), NaOH(sol), NaOH.1H2O(sol)

Note that the solid species include hydrates and precipitates.

7.1.2 Vapour-liquid equilibrium

The vapour-liquid equilibrium (VLE) relationships pertain to species that exist in bothliquid and vapour phases. For the sodium chloride example considered earlier, thefollowing VLE equilibria may be established:

H2O(vap) ⇐⇒ H2O(liq)HCl(vap) ⇐⇒ HCl(aq)

The VLE equations are given by:

Kvli (T, P ) f v

i (T, P, y) = f li (T, P, x) i = 1, . . . , N v (7.1)

where Kvli is the vapour-liquid equilibrium constant for species i, f v

i and f li are, re-

spectively, vapour and liquid-phase fugacities of component i, and N v is the numberof species present in the vapour phase2. Here, T and P are the system temperatureand pressure while x and y denote molar fractions in the liquid and vapour phasesrespectively.

7.1.3 Liquid-phase reactions

Liquid-phase reactions may take place among the molecular and ionic species in theliquid phase. For example, the following reactions may be considered for the sodiumchloride system introduced earlier:

H2O ⇐⇒ H+ +OH−

HCl(aq) ⇐⇒ H+ + Cl−

The equilibria corresponding to the above reactions are generally described by equationsof the form:

K lrj (T, P ) =

N l∏

i=1

(f li )

νlji j = 1, . . . ,M l (7.2)

whereK lrj is the equilibrium constant for reaction j, ν l

ji are the stoichiometric coefficients

for the liquid phase reactions, M l is the number of liquid-phase reactions, and N l is thenumber of species in the liquid phase.

2As has already been mentioned, all of these are assumed also to exist in the liquid phase.

7.1. General concepts for electrolyte system modelling 151

Page 153: Advanced Guide Gproms

gPROMS Advanced User Guide

7.1.4 Liquid-solid equilibrium

Each solid species in the system is assumed to undergo dissociation to form species inthe liquid phase. For the sodium chloride example, the solid dissociation reactions are:

NaCl(sol) ⇐⇒ Na+ + Cl−

NaOH.1H2O ⇐⇒ Na+ +OH− +H2O(liq)NaOH(sol) ⇐⇒ Na+ +OH−

The equilibria of solid dissociation reactions are generally described by equations of theform:

Ksrj (T, P ) =

N l∏

i=1

(f li )

νsji j = 1, . . . , N s (7.3)

where Ksrj is the equilibrium constant (the “solubility product”) for species j, ν s

ji is the

stoichiometric matrix for the solid dissociation reactions3 and N s is the number of solidspecies.

7.1.5 Fugacity and activity coefficients

The equations presented in sections 7.1.2 to 7.1.4 have been expressed in terms of thevapour and liquid-phase fugacities, f v

i and f li respectively.

Alternative quantities, such as the vapour-phase fugacity coefficients φvi and the (liquid-

phase) activity coefficients γi, are often used in electrolytic system modelling. Therelation between vapour-phase fugacity and fugacity coefficient is given by:

fvi = φv

i (T, P, y) yi P i = 1, . . . , N v (7.4)

As far as the liquid phase is concerned, the gPROMS electrolytic physical propertyinterface treats the first species in the system as the (main) solvent (e.g. water). Theliquid-phase fugacities for the other species are related to the corresponding activitycoefficients via:

f li = γi(T, P, x)mi i = 2, . . . , N l (7.5)

Here mi is the molality of species i in the liquid phase defined as:

mi =xi

x1 MW1i = 2, . . . , N l (7.6)

where MW1 is the molecular weight of species 1 (in kg/mol).

3Note that dissociation reactions are always written with the solid species appearing on the left handside of the reaction. Hence, all coefficients νs

ji used in the above equation are non-negative.

7.1. General concepts for electrolyte system modelling 152

Page 154: Advanced Guide Gproms

gPROMS Advanced User Guide

7.2 Electrolytic physical property methods

The gPROMS Electrolytic Physical Properties interface specifies that all electrolyticphysical property packages interfaced to gPROMS need to provide the methods listedin table 7.1.

The form of the methods described here has been chosen so as to maximise the re-liability and accuracy of any gPROMS within which they are incorporated. This isparticularly important in view of the extremely low concentrations of some species inmany electrolytic applications. We recommend that you make use of these methods inany models that you develop4. In this manner, you will also ensure that your modelswill be usable with any electrolytic physical property package interfaced to gPROMS.

The following points should be noted about tables 7.1 to 7.3:

1. The inputs of the methods in table 7.1 are as follows:

• T: temperature (K)

• P: pressure (Pa)

• nx: natural logarithm of the amounts of each species in the liquid phase(in mol)

• ny: natural logarithm of the amounts of each species in the vapour phase(in mol)

• ns: natural logarithm of the amounts of each species in the solid phase (inmol)

• nz: natural logarithm of the amounts of each molecular species (in mol)

2. The following methods return the natural logarithms of the corresponding quan-tities:

• VapourFugacity: ln(f vi )

• LiquidFugacity: ln(f li )

• VapourFugacityCoefficients: ln(φvi )

• LiquidActivityCoefficients: ln(γi)

• VapourLiquidEquilibriumConstants: ln(K vlj )

• LiquidReactionEquilibriumConstants: ln(K lrj )

• SolidDissociationEquilibriumConstants: ln(K srj )

3. The datum for all enthalpy calculations is the elemental species at standard condi-tions. One implication of this is that “heat generation” terms must not be includedin energy conservation equations to account for chemical reactions.

4The details of how precisely to refer to Foreign Object methods in your MODELs are described insections 4.2.1 and 6.2.

7.2. Electrolytic physical property methods 153

Page 155: Advanced Guide Gproms

gPROMS Advanced User Guide

4. The results of the two equilibrium flash methods (MolecularTPEquilibrium andTrueSpeciesTPEquilibrium) are organised as detailed in table 7.3. The quanti-ties returned in the results vector of the methods in table 7.3 include the naturallogarithms of molar fractions and amounts.

5. For convenience in the construction of some complex models, three additionalquantities are defined:

• Vapour Liquid Sum (VLS)

V LSi = ln(f li ) − ln(f v

i ) − ln(Kvli ) j = 1, . . . , N v (7.7)

Thus, the VLS is the logarithm of the ratio of the right hand side of equation7.1 to its left hand side. Under conditions of vapour/liquid equilibrium, itsvalue should be zero.

• Liquid Reaction Sum (LRS)

LRSj =

N l∑

i=1

νlji ln(f l

i ) − ln(K lrj ) j = 1, . . . , N l (7.8)

Thus, the LRS is the logarithm of the ratio of the right hand side of equation7.2 to its left hand side. Under conditions of reaction equilibrium, its valueshould be zero.

• Solid Dissociation Sum (SDS)

SDSj =N l∑

i=1

νsji ln(f l

i ) − ln(Ksrj ) j = 1, . . . , N s (7.9)

Thus, the SDS is the logarithm of the ratio of the right hand side of equation7.3 to its left hand side. If the solid species j is in equilibrium with the liquidphase, its value should be zero.

The three above quantities are returned by methods VapourLiquidSum, LiquidReactionSumand SolidDissociationSum respectively.

7.2. Electrolytic physical property methods 154

Page 156: Advanced Guide Gproms

gPROMS Advanced User Guide

Property Name Inputs Description Type Units

NumberOfSpecies - Total number of species in the system. Scalar -NumberOfVapourSpecies - Number of vapour species. Scalar -NumberOfLiquidSpecies - Number of liquid species. Scalar -NumberOfSolidSpecies - Number of solid species. Scalar -NumberOfMolecularSpecies - Number of whole molecular species. Scalar -MolecularWeight - Molecular weights of the species. Vector g/molSpeciesCharge - Electric charges of the species. Vector -NumberOfLiquidReactions - Number of liquid phase reactions. Scalar -LiquidReactionMatrix - Stoichiometric coefficient matrix for

the liquid-phase reactions.Vector -

SolidDissociationMatrix - Stoichiometric coefficient matrix forthe solid dissociation reactions.

Vector -

LiquidSolidReactionMatrix - Stoichiometric coefficient matrix forthe liquid-phase and solid dissociationreactions.

Vector -

VapourLiquidEquilibriumConstants T,P Equilibrium constants for the vapour-liquid equilibria.

Vector -

LiquidReactionEquilibriumConstants T,P Equilibrium constants for the liquidphase reactions.

Vector -

SolidDissociationEquilibriumConstants T,P Equilibrium constants for the solid dis-sociation reactions.

Vector -

VapourLiquidSum T,P,ny,nx Vapour-liquid equilibrium sums forvapour species.

Vector -

LiquidReactionSum T,P,nx Liquid reaction equilibrium sums forliquid-phase reactions.

Vector -

SolidDissociationSum T,P,nx Solid dissociation sums for solidspecies.

Vector -

VapourEnthalpy T,P,ny Total enthalpy of the vapour phase. Scalar JVapourVolume T,P,ny Total volume of the vapour phase. Scalar m3

VapourDensity T,P,ny Density of the vapour phase. Scalar kg/m3

VapourFugacity T,P,ny Vapour fugacity of all species in thevapour phase.

Vector -

VapourFugacityCoefficients T,P,ny Vapour fugacity coefficients of allspecies in the vapour phase.

Vector -

LiquidEnthalpy T,P,nx Total enthalpy of the liquid phase. Scalar JLiquidVolume T,P,nx Total volume of the liquid phase. Scalar m3

LiquidDensity T,P,nx Density of the liquid phase. Scalar kg/m3

LiquidFugacity T,P,nx Liquid fugacity of all species in the liq-uid phase.

Vector -

LiquidActivityCoefficients T,P,nx Activity coefficients of all the speciesin the liquid phase.

Vector -

Table continued on next page . . .

7.2. Electrolytic physical property methods 155

Page 157: Advanced Guide Gproms

gPROMS Advanced User Guide

. . . continued from previous page

SolidEnthalpy T,P,ns Total enthalpy of the solid phase. Scalar JSolidVolume T,P,ns Total volume of the solid phase. Scalar m3

SolidDensity T,P,ns Density of the solid phase. Scalar kg/m3

pH T,P,nx pH of the liquid phase. Scalar -MolecularTPEquilibrium T,P,nz Equilibrium flash calculation (at given T,

P, and molecular species amounts, nz).Vector -

TrueSpeciesTPEqulibrium T,P,ny,nx,ns Equilibrium flash calculation (at given T,P, and true species amounts).

Vector -

BubbleTemperature P,nx Bubble point temperature. Scalar KBubblePressure T,nx Bubble point pressure. Scalar PaDewTemperature P,ny Dew point temperature. Scalar KDewPressure T,ny Dew point pressure. Scalar Pa

Table 7.1: Thermophysical property methods and their arguments

7.2. Electrolytic physical property methods 156

Page 158: Advanced Guide Gproms

gPROMS Advanced User Guide

T Temperature, K.P Pressure, Pa.Nvap Number of vapour species.Nliq Number of liquid species.Nsol Number of solid species.NoS Number of species = Nliq+Nsol.Ninp Number of molecular species in feed.NliqR Number of liquid equilibrium constants (reactions).nx molar amounts of all true species in liquid phase(size=NoS).ny molar amounts of all true species in vapour phase(size=NoS).ns molar amounts of all true species in solid phase(size=NoS).nz molar amounts of the molecular species in feed(size=Ninp).

Name of vector property Size

MolecularWeight NoSSpeciesCharge NoSReactionType Nvap+NliqR+NsolReactionNumberToSolidSpecies NliqRVapourLiquidEquilibriumConstants NvapVapourFugacity NvapVapourFugacityCoefficients NvapLiquidReactionEquilibriumConstants NliqRSolidDissociationEquilibriumConstants NsolLiquidActivityCoefficients NliqLiquidFugacity NliqMolecularTPEquilibrium 14+Nvap+Nliq+NsolTrueSpeciesTPEquilibrium 14+Nvap+Nliq+NsolLiquidReactionMatrix NliqR*NliqSolidDissociationMatrix Nsol*NliqLiquidSolidReactionMatrix (NliqR+Nsol)*NoSVapourLiquidSum NvapLiquidReactionSum NliqRSolidDissociationSum Nsol

Table 7.2: Details of the vector methods in the interface

7.2. Electrolytic physical property methods 157

Page 159: Advanced Guide Gproms

gPROMS Advanced User Guide

Variable Length Position in results vector UnitsFrom To

Temperature 1 1 1 KPressure 1 2 2 Pa

Vapour molar fractions Nvap 3 2+Nvap -Vapour enthalpy 1 3+Nvap 3+Nvap JVapour molar amount 1 4+Nvap 4+Nvap molVapour volume 1 5+Nvap 5+Nvap m3

Vapour density 1 6+Nvap 6+Nvap kg/m3

Liquid molar fractions Nliq 7+Nvap 6+Nvap+Nliq -Liquid enthalpy 1 7+Nvap+Nliq 7+Nvap+Nliq JLiquid molar amount 1 8+Nvap+Nliq 8+Nvap+Nliq molLiquid volume 1 9+Nvap+Nliq 9+Nvap+Nliq m3

Liquid density 1 10+Nvap+Nliq 10+Nvap+Nliq kg/m3

Solid molar fractions Nsol 11+Nvap+Nliq 10+Nvap+Nliq+Nsol -Solid enthalpy 1 11+Nvap+Nliq+Nsol 11+Nvap+Nliq+Nsol JSolid molar amount 1 12+Nvap+Nliq+Nsol 12+Nvap+Nliq+Nsol molSolid volume 1 13+Nvap+Nliq+Nsol 13+Nvap+Nliq+Nsol m3

Solid density 1 14+Nvap+Nliq+Nsol 14+Nvap+Nliq+Nsol kg/m3

Table 7.3: Organisation of results vector for methods MolecularTPEquilibrium andTrueSpeciesTPEquilibrium

7.2. Electrolytic physical property methods 158

Page 160: Advanced Guide Gproms

gPROMS Advanced User Guide

7.3 The OLI physical property interface

OLI is a physical property package for aqueous electrolytic systems developed and mar-keted by OLI Systems, Inc.5.

To use OLI with gPROMS, you need to go through the following steps:

1. Check whether your installation is licensed to use OLI. You can do this by checkingfor the existence of either the file OLI.so or OLI.dll in the fo/OLI subdirectoryof the gPROMS installation directory on your computer system.

2. In your gPROMS project, ensure that you state the class of your Foreign Objectsto be OLI (see lines 2 and 3 of figure 6.1).

3. Specify the system chemistry by creating the chemistry model or data file. Thisfile encapsulates all the thermodynamic details of the system to be studied andwill be used internally by the interface to perform all the calculations. The chem-istry model will contain information on speciation, all the equilibrium equations,species charges and stoichiometry, pure component constants, various correlationcoefficients, etc.

The best way to create the chemistry model file is via the OLI Toolkit. In choosingthe phases present, it is advisable to specify the vapour and aqueous (liquid)phases; include the solid phase only if there is a possibility of solid formation (e.g.as a result of salt precipitation or hydrate formation).

At the end of the chemistry model definition, a text file with extension .dbs willbe created. This is the only file that the gPROMS-OLI interface will need fromthe OLI package.

4. In your gPROMS project, SET the value of your Foreign Object to the name ofthe chemistry model file including the .dbs extension. For example, if the nameof the chemistry model file is SodiumChloride.dbs located in the MiscellaneousFiles of the gPROMS project treeand the Foreign Object is called PhysProp,then the corresponding SET statement in the MODEL or PROCESS will be:

SET

PhysProp := "SodiumChloride.dbs" ;

5. Any of the methods listed in table 7.1 can now be used in your gPROMS project.Two points are worth noting in this context:

• The first component in the list of species will always be water.

• The first element of the vector returned by the method LiquidActivityCoefficients

will contain the activity of water rather than its activity coefficient. Subse-quent elements will contain the activity coefficients of the remaining species.

5http://www.olisystems.com

7.3. The OLI physical property interface 159

Page 161: Advanced Guide Gproms

gPROMS Advanced User Guide

7.3.1 Electrolyte system report file

At the start of the gPROMS simulation run, the interface will automatically initialise thechemistry model that you have specified (see above). If this initialisation is successful,an Electrolytic System Report (ESR) file will be produced in the Results folder of theCase.

The ESR file will be placed in the output sub-directory of your gPROMS workingdirectory. It will have the extension .esr and the same base name as the .dbs file. Forexample, if the chemistry model file is SodiumChloride.dbs, then the ESR file will becalled SodiumChloride.esr.

An example of an ESR file is given in figure 7.1. As can be seen, it contains the detailsof the species present (names and phases) and the vapour-liquid equilibria, liquid phasereactions and solid dissociation reactions that take place in the system.

CAUTION!

Always study the information in the ESR file carefully to ensurethat gPROMS’ interpretation of your chemistry file is indeedwhat you intended to specify!

7.3.2 Error handling in the OLI interface

In general, errors occur in two phases of the simulation in gPROMS: initialisation andcalculations.

The initialisation of an OLI Foreign Object consists of loading the chemistry model file(.dbs file) and checking all the Foreign Object methods used in your gPROMS MODELs.At the end of a successful loading of the chemistry model file, an electrolyte systemreport file (see section 7.3.1) will be generated. Any error messages that arise from thisstep will be printed on the screen. A common error will be the inability to locate thechemistry model file specified. Please check that either the full pathname of the file orthe pathname relative to the gPROMS export directory is given.

The initialisation step will also involve checking all the methods used in the gPROMSMODELs. Any errors detected here will also be printed to the screen. Please use the ESRfile generated to help in locating errors. Also, check that the names of the methods areexactly as given in table 7.1.

The second type of errors arise during the gPROMS PROCESS initialisation and integra-tion. All error messages will be printed on the screen.

7.3. The OLI physical property interface 160

Page 162: Advanced Guide Gproms

gPROMS Advanced User Guide

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

+ +

+ +

+ +

+ gPROMS ELECTROLYTE SYSTEM REPORT +

+ +

+ +

+ Created from OLI chemistry model file: nacl.dbs +

+ +

+ +

+ +

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

SPECIES PHASES IN WHICH PRESENT

======= =======================

Vapour Liquid Solid

------ ------ -----

1 H2O * *

2 HCL * *

3 OH(-) *

4 H(+) *

5 NA(+) *

6 CL(-) *

7 NACL(ppt) *

8 NAOH(ppt) *

9 NAOH.1H2O *

Number of vapour species = 2

Number of liquid species = 6

Number of solid species = 3

Total number of species = 9

VAPOUR-LIQUID EQUILIBRIA

========================

[VL 1] H2O(vap) <=> H2O(aq)

[VL 2] HCL(vap) <=> HCL(aq)

IONIC EQUILIBRIA

================

[IE 1] HCL(aq) <=> H(+) + CL(-)

[IE 2] H2O <=> OH(-) + H(+)

SOLID-LIQUID (DISSOCIATION) EQUILIBRIA

======================================

[SD 1] NACL(ppt) <=> NA(+) + CL(-)

[SD 2] NAOH.1H2O <=> H2O + OH(-) + NA(+)

[SD 3] NAOH(ppt) <=> OH(-) + NA(+)

Figure 7.1: Example of an Electrolyte System Report File

7.3. The OLI physical property interface 161

Page 163: Advanced Guide Gproms

gPROMS Advanced User Guide

Appendix A

Dynamic Optimisation Example

Contents

A.1 Project tree (ReactorOpt.gPJ) . . . . . . . . . . . . . . . . . . 163

A.2 VARIABLE TYPE entities in ReactorOpt.gPJ . . . . . . . . . . . . 164

A.3 Text contained within the Reactor MODEL entity . . . . . . . . 165

A.4 BatchReaction MODEL entity . . . . . . . . . . . . . . . . . . . . 167

A.5 Text contained within the Optimise Reactor PROCESS entity . 168

A.6 OPTIMISATION entity (OPTIMISE REACTOR) . . . . . . . . . . . . . 169

A.7 Sample optimisation report file (OPTIMISE REACTOR.out) . . . 170

A.8 Sample gPROMS schedule file (OPTIMISE REACTOR.SCHEDULE) 171

A.9 Sample point file (OPTIMISE REACTOR.point) . . . . . . . . . . 172

A.10 Simulating the optimal solution within a PROCESS . . . . . . 173

A.11 Interpretation of screen output . . . . . . . . . . . . . . . . . 175

162

Page 164: Advanced Guide Gproms

gPROMS Advanced User Guide

A.1 Project tree (ReactorOpt.gPJ)

A.1. Project tree (ReactorOpt.gPJ) 163

Page 165: Advanced Guide Gproms

gPROMS Advanced User Guide

A.2 VARIABLE TYPE entities in ReactorOpt.gPJ

A.2. VARIABLE TYPE entities in ReactorOpt.gPJ 164

Page 166: Advanced Guide Gproms

gPROMS Advanced User Guide

A.3 Text contained within the Reactor MODEL entity

#---------------------------------------------------------------

# Model of an externally cooled batch reactor: A + B -> C + D

#

# The reactor model takes into account mass and energy balances.

#---------------------------------------------------------------

PARAMETER

NoComp AS INTEGER

a,b,rho AS ARRAY (NoComp) OF REAL

nu AS ARRAY (NoComp) OF REAL

Ai,E,R,DH AS REAL

Tref AS REAL

VARIABLE

N,C,h AS ARRAY (NoComp) OF NoType

HR,Rate,V AS NoType

QcR,TR,K,Fcw AS NoType

Uacc,Tviol AS NoType

Obj AS NoType

EQUATION

# Component material balance

$N = V * Rate * nu ;

# Definition of reaction rate

Rate = K * C(1)* C(2) ;

# Rate constant

K = Ai * exp( - E / (R *TR) ) ;

# Energy balance

$HR = ( V * Rate * ( -DH ) ) - QcR ;

# Cooling load as a function of cooling water flowrate

QcR = 4200* 40 *Fcw ;

# Cumulative cooling water consumption

$Uacc= Fcw ;

# Definition of total enthalpy content of reactor

HR = sigma(N * h ) ;

# Pure component specific enthalpies

h = ( a * (TR - Tref ) + ( b * ( TR^2 - Tref^2 ) / 2 ) ) ;

# Relate molar concentrations C to component holdups N

V * C = N ;

A.3. Text contained within the Reactor MODEL entity 165

Page 167: Advanced Guide Gproms

gPROMS Advanced User Guide

# Volumetric holdup in reactor

V = sigma( N / rho ) ;

# Path constraint

$Tviol = MAX(TR - 450,0)^2 ;

# Objective to be maximised: value of product (3) - cooling water

Obj = 2*N(3) - Uacc ;

A.3. Text contained within the Reactor MODEL entity 166

Page 168: Advanced Guide Gproms

gPROMS Advanced User Guide

A.4 BatchReaction MODEL entity

A.4. BatchReaction MODEL entity 167

Page 169: Advanced Guide Gproms

gPROMS Advanced User Guide

A.5 Text contained within the Optimise Reactor PROCESS

entity

UNIT

React AS BatchReaction

ASSIGN

# This will be overridden in the Optimisation entity

WITHIN React.Batch_Reactor DO

FcW := 0.0 ;

END

PRESET

REACT.BATCH_REACTOR.RATE := 7.28422E+00 ;

REACT.BATCH_REACTOR.HR := 6.50000E+06 ;

REACT.BATCH_REACTOR.C(1) := 4.44444E+03 ;

REACT.BATCH_REACTOR.C(2) := 4.44444E+03 ;

REACT.BATCH_REACTOR.C(3) := 0.00000E+00 ;

REACT.BATCH_REACTOR.C(4) := 0.00000E+00 ;

REACT.BATCH_REACTOR.OBJ := 0.00000E+00 ;

REACT.BATCH_REACTOR.H(1) := 6.00000E+02 ;

REACT.BATCH_REACTOR.H(2) := 7.00000E+02 ;

REACT.BATCH_REACTOR.H(3) := 8.00000E+02 ;

REACT.BATCH_REACTOR.H(4) := 7.00000E+02 ;

REACT.BATCH_REACTOR.FCW := 0.00000E+00 ;

REACT.BATCH_REACTOR.K := 3.68763E-07 ;

REACT.BATCH_REACTOR.QCR := 0.00000E+00 ;

REACT.BATCH_REACTOR.V := 1.12500E+00 ;

INITIAL

WITHIN React.Batch_Reactor DO

N(1) = 5000.0 ;

N(2) = 5000.0 ;

N(3) = 0.0 ;

N(4) = 0.0 ;

TR = 300.0 ;

Uacc = 0.0 ;

Tviol = 0.0 ;

END

SOLUTIONPARAMETERS

ABSOLUTEACCURACY := 1.0E-6 ;

REPORTINGINTERVAL := 100 ;

SCHEDULE

# This will be ignored by the dynamic optimisation

SEQUENCE

CONTINUE FOR 2000

END

A.5. Text contained within the Optimise Reactor PROCESS entity 168

Page 170: Advanced Guide Gproms

gPROMS Advanced User Guide

A.6 OPTIMISATION entity (OPTIMISE REACTOR)

A.6. OPTIMISATION entity (OPTIMISE REACTOR) 169

Page 171: Advanced Guide Gproms

gPROMS Advanced User Guide

A.7 Sample optimisation report file (OPTIMISE REACTOR.out)

---------------------------

gPROMS Dynamic Optimisation

---------------------------

gPROMS Process : OPTIMISE_REACTOR

Final Optimisation Status : Optimal Solution Found

(SRQPD flag = 1)

Objective Function being Maximised: 7.64277E+03

Time Horizon : 1.00000E+03

Current Control Profiles

Duration Control 1

Interval 1 2.50065E+02 1.00000E-01

Interval 2 1.58764E+02 1.85192E+00

Interval 3 2.88801E+02 5.55992E-01

Interval 4 3.02370E+02 3.00000E+00

Control 1 = REACT.BATCH_REACTOR.FCW

Constraint Residuals: ([*] denotes violation)

Variable Type Lower Bound Upper Bound Current Value Time

-------- -------- ----------- ----------- ----------- -----------

REACT.BATCH_REACTOR.TR Endpoint 3.10000E+02 3.20000E+02 3.20000E+02 1.00000E+03

REACT.BATCH_REACTOR.TVIOL Endpoint N/A 1.00000E-01 9.93060E-02 1.00000E+03

Computational Statistics

------------------------

Total CPU Time: 6.0 seconds.

SRQPD Optimiser Statistics:

CPU Time : 1.2 seconds ( 20.55 % of total time)

Number of Optimisation Iterations: 41

Number of Linesearch Steps : 47

Infeasible Linesearch Steps : 0

DASOLV Integrator Statistics:

CPU Time : 3.8 seconds ( 62.84 % of total time)

CPU Time Spent on State Integration Only : 1.1 seconds ( 29.04 % of DASOLV time)

( 10076 steps, 18885 residuals( 0.25 seconds), 2488 Jacobians( 0.03 seconds) )

CPU Time Spent on Sensitivity Integration Only: 2.7 seconds ( 70.96 % of DASOLV time)

( 8686 steps, 24117 residuals( 0.35 seconds), 11102 Jacobians( 0.22 seconds) )

Mean (Sensitivity+State)/(State) CPU Ratio : 3.9

A.7. Sample optimisation report file (OPTIMISE REACTOR.out) 170

Page 172: Advanced Guide Gproms

gPROMS Advanced User Guide

A.8 Sample gPROMS schedule file (OPTIMISE REACTOR.SCHEDULE)

#

# Schedule generated for process OPTIMISE_REACTOR

#

# Final Optimisation Status : Optimal Solution Found

# Objective Function being Maximised: 7.64277E+03

#

SCHEDULE

SEQUENCE

RESET

REACT.BATCH_REACTOR.FCW:= 1.00000E-01;

END

CONTINUE FOR 2.50065E+02

RESET

REACT.BATCH_REACTOR.FCW:= 1.85192E+00;

END

CONTINUE FOR 1.58764E+02

RESET

REACT.BATCH_REACTOR.FCW:= 5.55992E-01;

END

CONTINUE FOR 2.88801E+02

RESET

REACT.BATCH_REACTOR.FCW:= 3.00000E+00;

END

CONTINUE FOR 3.02370E+02

END

END

A.8. Sample gPROMS schedule file (OPTIMISE REACTOR.SCHEDULE) 171

Page 173: Advanced Guide Gproms

gPROMS Advanced User Guide

A.9 Sample point file (OPTIMISE REACTOR.point)

#

# .gOPT segment generated by gOPT for process OPTIMISE_REACTOR

# at most recent point.

#

HORIZON

1.00000E+03 : 1.00000E+03 : 1.00000E+03

INTERVALS

4

2.50065E+02 : 5.00000E+01 : 3.50000E+02

1.58764E+02 : 5.00000E+01 : 3.50000E+02

2.88801E+02 : 5.00000E+01 : 3.50000E+02

3.02370E+02 : 5.00000E+01 : 3.50000E+02

PIECEWISE-CONSTANT

REACT.BATCH_REACTOR.FCW

INITIAL-PROFILE

1.00000E-01 : 1.00000E-01 : 3.00000E+00

1.85192E+00 : 1.00000E-01 : 3.00000E+00

5.55992E-01 : 1.00000E-01 : 3.00000E+00

3.00000E+00 : 1.00000E-01 : 3.00000E+00

A.9. Sample point file (OPTIMISE REACTOR.point) 172

Page 174: Advanced Guide Gproms

gPROMS Advanced User Guide

A.10 Simulating the optimal solution within a PROCESS

UNIT

React AS BatchReaction

ASSIGN

{ This was the previous ASSIGN section

# This will be overridden in the Optimisation entity

WITHIN React.Batch_Reactor DO

FcW := 0.0 ;

END

}

# This is the new one using the first RESET statement

# from the SCHEDULE file

REACT.BATCH_REACTOR.FCW:= 1.00000E-01;

PRESET

REACT.BATCH_REACTOR.RATE := 7.28422E+00 ;

REACT.BATCH_REACTOR.HR := 6.50000E+06 ;

REACT.BATCH_REACTOR.C(1) := 4.44444E+03 ;

REACT.BATCH_REACTOR.C(2) := 4.44444E+03 ;

REACT.BATCH_REACTOR.C(3) := 0.00000E+00 ;

REACT.BATCH_REACTOR.C(4) := 0.00000E+00 ;

REACT.BATCH_REACTOR.OBJ := 0.00000E+00 ;

REACT.BATCH_REACTOR.H(1) := 6.00000E+02 ;

REACT.BATCH_REACTOR.H(2) := 7.00000E+02 ;

REACT.BATCH_REACTOR.H(3) := 8.00000E+02 ;

REACT.BATCH_REACTOR.H(4) := 7.00000E+02 ;

REACT.BATCH_REACTOR.FCW := 0.00000E+00 ;

REACT.BATCH_REACTOR.K := 3.68763E-07 ;

REACT.BATCH_REACTOR.QCR := 0.00000E+00 ;

REACT.BATCH_REACTOR.V := 1.12500E+00 ;

INITIAL

WITHIN React.Batch_Reactor DO

N(1) = 5000.0 ;

N(2) = 5000.0 ;

N(3) = 0.0 ;

N(4) = 0.0 ;

TR = 300.0 ;

Uacc = 0.0 ;

Tviol = 0.0 ;

END

SOLUTIONPARAMETERS

ABSOLUTEACCURACY := 1.0E-6 ;

REPORTINGINTERVAL := 100 ;

A.10. Simulating the optimal solution within a PROCESS 173

Page 175: Advanced Guide Gproms

gPROMS Advanced User Guide

{ This is the previous SCHEDULE

SCHEDULE

# This will be ignored by the dynamic optimisation

SEQUENCE

CONTINUE FOR 2000

END

}

# This is the new one taken from the SCHEDULE results file

# minus the final END statement

SCHEDULE

SEQUENCE

RESET

REACT.BATCH_REACTOR.FCW:= 1.00000E-01;

END

CONTINUE FOR 2.50065E+02

RESET

REACT.BATCH_REACTOR.FCW:= 1.85192E+00;

END

CONTINUE FOR 1.58764E+02

RESET

REACT.BATCH_REACTOR.FCW:= 5.55992E-01;

END

CONTINUE FOR 2.88801E+02

RESET

REACT.BATCH_REACTOR.FCW:= 3.00000E+00;

END

CONTINUE FOR 3.02370E+02

END

A.10. Simulating the optimal solution within a PROCESS 174

Page 176: Advanced Guide Gproms

gPROMS Advanced User Guide

A.11 Interpretation of screen output

The purpose of this section is to explain the detailed meaning of the screen output pro-duced by gPROMS during optimisation, which can be of value in determining whetherthe problem is unsatisfactorily posed, for example.

This output is essentially of four kinds. We will review these together with a brief expla-nation of each. The examples below refer to when the single-shooting algorithm CVP SS

is chosen. This output is very similar to that when the multiple-shooting algorithmCVP MS is invoked.

1. Display of the solution point

This is indicated by a line of the type:

After 73 cycles, the solution point is:

A report is then given of values of:

• the time invariant parameters,

• the time interval lengths and control values,

for the current solution point.

Note that the SCHEDULE and point files are updated at the same time that thesevalues are written to the screen.

2. Output from the integration

During optimisation, gPROMS repeatedly carries out integrations for a differentchoices of time invariant parameters and controls. This computation, similar tothe execution of a conventional gPROMS simulation, will produce some output ifthe method parameter IPRINT is not set to zero. This may be of use if there areproblems with these integrations.

3. Report on constraint residuals

Following a successful simulation, gPROMS outputs both the objective functionvalue and a report on the status of the constraints. The latter are marked with [*]

if they are violated (for equality constraints, a violation is indicated if the actualvalue differs from the desired one by more than one millionth of its magnitude).

4. Optimiser reports

Following a gradient evaluation, the optimiser will produce a report of this type:

No. of No. of Step Objective Current Constraint

Iterations Functions Length Function Accuracy Violations

18 63 1.587E-03 -7.473E+03 8.493E-02 5.684E-14

A.11. Interpretation of screen output 175

Page 177: Advanced Guide Gproms

gPROMS Advanced User Guide

These values have the following meanings:

• No. of Iterations: this refers to the number of full optimiser iterations,i.e. the number of gradient evaluations used to determine new search direc-tions.

• No. of Functions: the total number of simulations carried out so far.Since the optimiser works by selecting a search direction and then carryingout a line search along that direction, it generally evaluates the objectivefunction considerably more often than it evaluates its gradient.

• Step Length: this provides a measure of how much the optimiser is alteringthe optimisation decision variables between simulations.

• Objective Function: the present objective function value, negated if a max-imisation is in progress.

• Current Accuracy: this shows how close the optimiser considers the currentpoint is to optimality. When this value falls below 10−4 (or the value suppliedwith the ACC keyword in the PARAMETERS entity), the optimisation will reportthat the solution has been found, and terminate (after its output integration).

• Constraint Violations a measure of the total constraint violation of thecurrent point — zero (or very small) if the point is feasible.

Finally, here is an example of one iteration’s output for the problem OPTIMISE REACTOR.Again, a wide screen format is needed.

Optimisation Iteration 10

---------------------------

Values and gradients of objective function and constraints to be evaluated

at the following point:

Time Horizon: 1.00000E+03

Current Control Profiles

Duration Control 1

Interval 1 3.50000E+02 3.83448E-01

Interval 2 3.26555E+02 1.48681E+00

Interval 3 1.23949E+02 1.99611E+00

Interval 4 1.99496E+02 3.00000E+00

Control 1 = REACT.BATCH_REACTOR.FCW

Objective function and constraint residuals:

Objective Function to be Maximised: 7.48409E+03

Constraint Residuals: ([*] denotes violation)

Variable Type Lower Bound Upper Bound Current Value Time

-------- -------- ----------- ----------- ----------- -----------

REACT.BATCH_REACTOR.TR Endpoint 3.10000E+02 3.20000E+02 3.11559E+02 1.00000E+03

REACT.BATCH_REACTOR.TVIOL Endpoint N/A 1.00000E-01 0.00000E+00 1.00000E+03

No. of No. of Step Objective Current Constraint

Iterations Functions Length Function Accuracy Violations

9 27 3.490E-03 -7.484E+03 8.236E-02 5.684E-14

Searching Along Optimisation Step..... ( 28)

After 37 cycles, the solution point is:

Time Horizon: 1.00000E+03

Current Control Profiles

A.11. Interpretation of screen output 176

Page 178: Advanced Guide Gproms

gPROMS Advanced User Guide

Duration Control 1

Interval 1 3.50000E+02 1.00000E-01

Interval 2 5.00000E+01 1.35623E+00

Interval 3 2.50000E+02 3.00000E+00

Interval 4 3.50000E+02 3.00000E+00

Control 1 = REACT.BATCH_REACTOR.FCW

About to perform a function evaluation.

A.11. Interpretation of screen output 177

Page 179: Advanced Guide Gproms

gPROMS Advanced User Guide

Appendix B

Backward Compatibility ofDynamic Optimisation Features

Contents

B.1 Importing of gPROMS v1.x .gOPT files . . . . . . . . . . . . 179

B.2 Exporting of projects containing optimisation entities . . . 179

B.3 Use of gOPT.param files . . . . . . . . . . . . . . . . . . . . . . 179

178

Page 180: Advanced Guide Gproms

gPROMS Advanced User Guide

In the interests of backward compatibility, the current version of gPROMS still allowsaccess to certain deprecated features that were supported by earlier versions. These aredetailed in this appendix.

B.1 Importing of gPROMS v1.x .gOPT files

gPROMS v1.x .gOPT files can be imported into a project in the gPROMS ModelBuilder.

In order to do this, follow the same procedure as that outlined in the chapter entitled“gPROMS ModelBuilder” of the “gPROMS Introductory User Guide”. Any .gOPT fileimported into a project is automatically placed under the Optimisations category inthe project tree.

Note that the corresponding .gPROMS file would normally also need to be importedseparately into the project.

B.2 Exporting of projects containing optimisation entities

The contents of a project in ModelBuilder can be exported into a gPROMS v1.x inputfile and a separate .gOPT file.

In order to do this, follow the procedure described in the chapter entitled “gPROMSModelBuilder” of the “gPROMS Introductory User Guide”. The optimisation entitieswill be exported as name.gOPT files into the input sub-directory where name is thename of the optimisation entity (in capitals).

B.3 Use of gOPT.param files

In earlier versions of gPROMS, solver parameters for dynamic optimisation were speci-fied using a gOPT.param file. This is a text file that resides in your gPROMS workingdirectory. Its format is shown in table B.1. The parameters can be specified in any or-der, and can be included or omitted selectively. Keywords are highlighted in CAPITALS.The value next to the “{value}” entry is the default.

Note that gPROMS will make use of the contents of the gOPT.param file only if noexplicit specification of the DOSolver parameter (see section 10.6 of the “gPROMSIntroductory User Guide”) appears in the corresponding PROCESS entity. If an explicitDOSolver specification appears (with or without any solver parameters actually beingspecified), then gOPT.param is ignored.

The values shown in table B.1 correspond to the following SOLUTIONPARAMETERS speci-fication in the current version of gPROMS1:

1Note that the parameter ISTEPS is no longer necessary or supported.

B.1. Importing of gPROMS v1.x .gOPT files 179

Page 181: Advanced Guide Gproms

gPROMS Advanced User Guide

Specification Description/default value

RTOL Relative DAE integration tolerance{value} 10−5

ATOL Absolute DAE integration tolerance{value} 10−5

EVTOL Event location tolerance for DAE integration{value} 10−5

SSTOL (Re-)initialisation tolerance{value} 10−5

ISTEPS Number of points used for results reportingin gPLOT file.

{value} 20ACC Optimisation tolerance{value} 10−4

IPRINT Output print level{value} 0 (values of 1, 2 and 3 also allowed)MAXFUN Maximum number of function evaluations{value} 10000ISCAL Scaling of optimisation decision variables{value} 0NOSENERR Suppress additional error test for sensitivities (default)SENERR Perform additional error test for sensitivities.

Note that no ‘value’ line is needed – the presenceof the flag alters the default behaviour.

Table B.1: Form of deprecated gOPT.param files

B.3. Use of gOPT.param files 180

Page 182: Advanced Guide Gproms

gPROMS Advanced User Guide

DOSolver := "CVP_SS" ["OutputLevel" := 0;

"MaxFun" := 10000;

"Scaling" := 0;

"OptTol" := 1E-4;

"SenErr" := FALSE;

"DASolver" := "DASOLV"

[

"AbsoluteTolerance" := 1E-5;

"RelativeTolerance" := 1E-5;

"OutputLevel" := 0;

"InitialisationNLSolver" := "BDNLSOL"

[

"OutputLevel" := 0;

"BlockSolver" := "SPARSE"

[

"OutputLevel" := 0;

"ConvergenceTolerance" := 1E-5]

]

]

]

] ;

Note:

As gOPT.param files may not be supported by future versions of gPROMS,you are strongly advised:

• not to use such files;

• to convert any existing ones to the new form of solver parameter spec-ification, as described in section 10.6 of the “gPROMS IntroductoryUser Guide”, as soon as possible.

B.3. Use of gOPT.param files 181

Page 183: Advanced Guide Gproms

gPROMS Advanced User Guide

Appendix C

Parameter Estimation Example

Contents

C.1 Project tree (ReactorEst.gPJ) . . . . . . . . . . . . . . . . . . 183

C.2 Variable Type entities in ReactorEst.gPJ . . . . . . . . . . . . 184

C.3 Text contained within the BatchReactor MODEL entity . . . . 185

C.4 Text contained within the Estimate Reactor PROCESS entity . 187

C.5 PARAMETER ESTIMATION entity (ESTIMATE REACTOR) . . . . . . . . 189

C.6 Text contained within the C13T1 EXPERIMENT entity . . . . . 190

C.7 Sample Optimisation Report File (ESTIMATE REACTOR.out) . 191

C.8 Sample Estimation Statistics File (ESTIMATE REACTOR.stat) . 192

C.9 Sample summary sheet . . . . . . . . . . . . . . . . . . . . . . 196

C.10 Sample parameter estimates sheet . . . . . . . . . . . . . . . 197

C.11 Sample variance matrix sheet . . . . . . . . . . . . . . . . . . 198

C.12 Sample correlation matrix sheet . . . . . . . . . . . . . . . . 199

C.13 Sample information matrix sheet . . . . . . . . . . . . . . . . 200

C.14 Part of a sample statistical significance sheet . . . . . . . . . 201

C.15 Sample measured variable sheet . . . . . . . . . . . . . . . . . 202

C.16 Overlay plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203

C.17 Residual plots . . . . . . . . . . . . . . . . . . . . . . . . . . . 204

C.18 Confidence ellipsoid plots . . . . . . . . . . . . . . . . . . . . 205

182

Page 184: Advanced Guide Gproms

gPROMS Advanced User Guide

C.1 Project tree (ReactorEst.gPJ)

C.1. Project tree (ReactorEst.gPJ) 183

Page 185: Advanced Guide Gproms

gPROMS Advanced User Guide

C.2 Variable Type entities in ReactorEst.gPJ

C.2. Variable Type entities in ReactorEst.gPJ 184

Page 186: Advanced Guide Gproms

gPROMS Advanced User Guide

C.3 Text contained within the BatchReactor MODEL entity

PARAMETER

# Component densities

Density AS ARRAY(4) OF REAL

# Specific enthalpy coefficients

Ac, Bc AS ARRAY(4) OF REAL

# Reaction data

# These may be parameters for simulation purposes but ...

# ArrheniusConstant AS REAL

# ActivationEnergy AS REAL

# ReactionEnthalpy AS REAL

# Component stoichiometric coefficients

Nu AS ARRAY(4) OF INTEGER

# Ideal gas constant

R AS REAL

# Reference temperature

Tref AS REAL

VARIABLE

HoldUp AS ARRAY(4) OF Moles

C AS ARRAY(4) OF MolarConcentration

TotalVolume AS Volume

ReactionRate AS NoType

ReactionConstant AS NoType

TotalH AS Energy

H AS ARRAY(4) OF Energy

T AS Temperature

Q AS Energy

# Reaction data

# ... variables for parameter estimation purposes

ArrheniusConstant AS NoType

ActivationEnergy AS NoType

ReactionEnthalpy AS NoType

EQUATION

# Mass balance

FOR i := 1 TO 4 DO

$HoldUp(i) = Nu(i)*ReactionRate*TotalVolume ;

END # For

# Energy balance

C.3. Text contained within the BatchReactor MODEL entity 185

Page 187: Advanced Guide Gproms

gPROMS Advanced User Guide

$TotalH = ReactionRate*TotalVolume*(-ReactionEnthalpy) + Q ;

# Reaction rate

ReactionRate = ReactionConstant*C(1)*C(2) ;

# Reaction constant

ReactionConstant = ArrheniusConstant * EXP(-ActivationEnergy/(R*T)) ;

# Concentrations

Holdup = C * TotalVolume ;

TotalVolume = SIGMA(Holdup/Density) ;

# Reactor energy content

TotalH = SIGMA(HoldUp*H) ;

H = Ac * ( T - Tref ) + Bc * ( T^2 - Tref^2 ) / 2 ;

C.3. Text contained within the BatchReactor MODEL entity 186

Page 188: Advanced Guide Gproms

gPROMS Advanced User Guide

C.4 Text contained within the Estimate Reactor PROCESS

entity

UNIT # Equipment items

R101 AS BatchReactor

SET # Parameter values

WITHIN R101 DO

Density := [ 10.0E3, 8.0E3, 11.0E3, 11.0E3 ] ;

Ac := [ 150.0, 175.0, 200.0, 175.0 ] ;

Bc := [ 0.0, 0.0, 0.0, 0.0 ] ;

Nu := [ -1, -1, +1, +1 ] ;

R := 8.314 ;

Tref := 298 ;

END # Within

ASSIGN # Degrees of freedom - these may be overridden by parameter estimation

WITHIN R101 DO

Q := 0.0 ;

ArrheniusConstant := 5E-4 ;

ActivationEnergy := 15000.0 ;

ReactionEnthalpy := 55000.0 ;

END # For

INITIAL # Initial conditions - these may be overridden by EXPERIMENTs

WITHIN R101 DO

Holdup(1) = 100.0 ;

Holdup(2) = 100.0 ;

Holdup(3) = 1.0 ;

Holdup(4) = 1.0 ;

T = 293.0 ;

END # Within

SCHEDULE # Operating procedure - this is ignored by parameter estimation

SEQUENCE

RESET R101.Q := 505E3 ; END

C.4. Text contained within the Estimate Reactor PROCESS entity 187

Page 189: Advanced Guide Gproms

gPROMS Advanced User Guide

CONTINUE FOR 100

RESET R101.Q := 0 ; END

CONTINUE FOR 600

STOP

END # Sequence

END # Process Estimate_Reactor

C.4. Text contained within the Estimate Reactor PROCESS entity 188

Page 190: Advanced Guide Gproms

gPROMS Advanced User Guide

C.5 PARAMETER ESTIMATION entity (ESTIMATE REACTOR)

C.5. PARAMETER ESTIMATION entity (ESTIMATE REACTOR) 189

Page 191: Advanced Guide Gproms

gPROMS Advanced User Guide

C.6 Text contained within the C13T1 EXPERIMENT entity

INITIAL-CONDITION

R101.HOLDUP(1) 100.000

R101.HOLDUP(2) 100.000

R101.HOLDUP(3) 1.0

R101.HOLDUP(4) 1.0

R101.T 293

MEASURE

R101.C(1)

10 3746.911

20 2518.600

30 1504.120

...

380 14.573

390 11.848

400 14.051

MEASURE

R101.C(3)

10 898.552

20 2358.859

30 3634.895

...

380 5490.156

390 5498.067

400 5488.697

MEASURE

R101.T

10 412.549

20 504.179

30 603.486

...

380 1481.593

390 1482.212

400 1482.140

INTERVALS

2

100

300

PIECEWISE-CONSTANT

R101.Q

505000

0

C.6. Text contained within the C13T1 EXPERIMENT entity 190

Page 192: Advanced Guide Gproms

gPROMS Advanced User Guide

C.7 Sample Optimisation Report File (ESTIMATE REACTOR.out)

---------------------------

gPROMS Parameter Estimation

---------------------------

gPROMS Process : ESTIMATE_REACTOR

Final Optimisation Status : Optimal Solution Found

(SRQPD flag = 1)

Objective Function being Minimised: 1.12408E+03

Time Invariant Parameters:

R101.ARRHENIUSCONSTANT : 7.54552E-04

R101.ACTIVATIONENERGY : 1.50293E+04

R101.REACTIONENTHALPY : 5.50211E+04

Computational Statistics

------------------------

Total CPU Time: 41.8 seconds.

SRQPD Optimiser Statistics:

CPU Time : 5.1 seconds ( 12.08 % of total time)

Number of Optimisation Iterations: 34

Number of Linesearch Steps : 37

Infeasible Linesearch Steps : 0

DASOLV Integrator Statistics:

CPU Time : 32.0 seconds ( 76.43 % of total time)

CPU Time Spent on State Integration Only : 6.1 seconds ( 19.18 % of DASOLV time)

CPU Time Spent on Sensitivity Integration Only: 25.8 seconds ( 80.82 % of DASOLV time)

Mean (Sensitivity+State)/(State) CPU Ratio : 5.7

C.7. Sample Optimisation Report File (ESTIMATE REACTOR.out) 191

Page 193: Advanced Guide Gproms

gPROMS Advanced User Guide

C.8 Sample Estimation Statistics File (ESTIMATE REACTOR.stat)

Final estimate of parameters:

R101.ARRHENIUSCONSTANT

: 0.0007545524 ( 0.0005 : 0.0001 : 0.001 )

R101.ACTIVATIONENERGY

: 15029.286 ( 15000 : 10000 : 20000 )

R101.REACTIONENTHALPY

: 55021.121 ( 55000 : 35000 : 75000 )

HETEROSCEDASTICITY

Referenced by the variable(s)

RUN: C13T1 Name: R101.C(1)

RUN: C13T2 Name: R101.C(1)

RUN: C13T3 Name: R101.C(1)

RUN: C13T4 Name: R101.C(1)

Omega : 0.15092 ( 0.1 : 0.01 : 3 )

Gamma : 0.58222 ( 0.5 : 0 : 1 )

HETEROSCEDASTICITY

Referenced by the variable(s)

RUN: C13T1 Name: R101.C(3)

RUN: C13T2 Name: R101.C(3)

RUN: C13T3 Name: R101.C(3)

RUN: C13T4 Name: R101.C(3)

Omega : 0.13138 ( 0.1 : 0.01 : 3 )

Gamma : 0.58071 ( 0.5 : 0 : 1 )

HETEROSCEDASTICITY

Referenced by the variable(s)

RUN: C13T1 Name: R101.T

RUN: C13T2 Name: R101.T

RUN: C13T3 Name: R101.T

RUN: C13T4 Name: R101.T

Omega : 0.48595 ( 0.1 : 0.01 : 3 )

Gamma : 0 ( 0 : 0 : 0 )

RUN: C13T1

Variable R101.C(1)

Time exp. value pred. value deviation %deviation Sigma deviation/sigma

-----------------------------------------------------------------------------------------------------

10 3746.911 3721.3929 25.518 0.681 18.100265 1.4098193

20 2518.6 2514.3608 4.2392 0.168 14.40606 0.29426182

30 1504.12 1510.605 -6.485 -0.431 10.708111 -0.60561327

...

380 14.57341 13.886515 0.68689 4.71 0.69820401 0.98380215

390 11.8482 13.469821 -1.6216 -13.7 0.68592824 -2.3641262

400 14.05076 13.077406 0.97335 6.93 0.67422183 1.4436707

Variable R101.C(3)

Time exp. value pred. value deviation %deviation Sigma deviation/sigma

-----------------------------------------------------------------------------------------------------

10 898.5522 894.77629 3.7759 0.42 6.8020912 0.55511032

20 2358.859 2388.4785 -29.619 -1.26 12.029908 -2.4621511

30 3634.895 3630.6263 4.2687 0.117 15.341607 0.27824043

...

380 5490.156 5482.8154 7.3406 0.134 19.490871 0.37661543

390 5498.067 5483.3311 14.736 0.268 19.491935 0.75600001

400 5488.697 5483.8167 4.8803 0.0889 19.492938 0.25036193

Variable R101.T

Time exp. value pred. value deviation %deviation Sigma deviation/sigma

-----------------------------------------------------------------------------------------------------

10 412.5493 412.291 0.2583 0.0626 0.48595066 0.53153798

C.8. Sample Estimation Statistics File (ESTIMATE REACTOR.stat) 192

Page 194: Advanced Guide Gproms

gPROMS Advanced User Guide

20 504.1786 504.41591 -0.23731 -0.0471 0.48595066 -0.48833834

30 603.4858 603.46722 0.018582 0.00308 0.48595066 0.038239291

...

380 1481.593 1482.4928 -0.89977 -0.0607 0.48595066 -1.8515755

390 1482.212 1482.4697 -0.25766 -0.0174 0.48595066 -0.53021431

400 1482.14 1482.4479 -0.30789 -0.0208 0.48595066 -0.63358233

RUN: C13T2

Variable R101.C(1)

Time exp. value pred. value deviation %deviation Sigma deviation/sigma

-----------------------------------------------------------------------------------------------------

10 3700.752 3721.3929 -20.641 -0.558 18.100265 -1.1403644

20 2520.929 2514.3608 6.5682 0.261 14.40606 0.45592989

30 1502.396 1510.605 -8.209 -0.546 10.708111 -0.76661272

...

380 14.47842 13.886515 0.5919 4.09 0.69820401 0.84775309

390 12.73918 13.469821 -0.73064 -5.74 0.68592824 -1.0651856

400 13.40005 13.077406 0.32264 2.41 0.67422183 0.47854323

Variable R101.C(3)

Time exp. value pred. value deviation %deviation Sigma deviation/sigma

-----------------------------------------------------------------------------------------------------

10 898.2157 894.77629 3.4394 0.383 6.8020912 0.50564024

20 2380.372 2388.4785 -8.1065 -0.341 12.029908 -0.6738582

30 3626.625 3630.6263 -4.0013 -0.11 15.341607 -0.26081652

...

380 5477.987 5482.8154 -4.8284 -0.0881 19.490871 -0.24772814

390 5509.101 5483.3311 25.77 0.468 19.491935 1.3220803

400 5475.758 5483.8167 -8.0587 -0.147 19.492938 -0.41341692

Variable R101.T

Time exp. value pred. value deviation %deviation Sigma deviation/sigma

-----------------------------------------------------------------------------------------------------

10 411.8036 412.291 -0.4874 -0.118 0.48595066 -1.00298

20 504.5298 504.41591 0.11389 0.0226 0.48595066 0.23436879

30 604.0272 603.46722 0.55998 0.0927 0.48595066 1.1523442

...

380 1483.454 1482.4928 0.96123 0.0648 0.48595066 1.9780314

390 1482.851 1482.4697 0.38134 0.0257 0.48595066 0.78473402

400 1482.095 1482.4479 -0.35289 -0.0238 0.48595066 -0.72618432

RUN: C13T3

Variable R101.C(1)

Time exp. value pred. value deviation %deviation Sigma deviation/sigma

-----------------------------------------------------------------------------------------------------

10 3705.683 3721.3929 -15.71 -0.424 18.100265 -0.86793746

20 2513.977 2514.3608 -0.38385 -0.0153 14.40606 -0.026644797

30 1516.819 1510.605 6.214 0.41 10.708111 0.5803102

...

380 14.58668 13.886515 0.70016 4.8 0.69820401 1.0028081

390 14.10359 13.469821 0.63377 4.49 0.68592824 0.92395831

400 13.72198 13.077406 0.64457 4.7 0.67422183 0.95602702

Variable R101.C(3)

Time exp. value pred. value deviation %deviation Sigma deviation/sigma

-----------------------------------------------------------------------------------------------------

10 896.7986 894.77629 2.0223 0.226 6.8020912 0.29730725

20 2386.384 2388.4785 -2.0945 -0.0878 12.029908 -0.17410377

30 3633.759 3630.6263 3.1327 0.0862 15.341607 0.20419343

...

380 5476.954 5482.8154 -5.8614 -0.107 19.490871 -0.30072731

C.8. Sample Estimation Statistics File (ESTIMATE REACTOR.stat) 193

Page 195: Advanced Guide Gproms

gPROMS Advanced User Guide

390 5465.794 5483.3311 -17.537 -0.321 19.491935 -0.89971038

400 5476.927 5483.8167 -6.8897 -0.126 19.492938 -0.35344649

Variable R101.T

Time exp. value pred. value deviation %deviation Sigma deviation/sigma

-----------------------------------------------------------------------------------------------------

10 412.8228 412.291 0.5318 0.129 0.48595066 1.0943523

20 503.7398 504.41591 -0.67611 -0.134 0.48595066 -1.3913107

30 604.3594 603.46722 0.89218 0.148 0.48595066 1.8359527

...

380 1482.818 1482.4928 0.32523 0.0219 0.48595066 0.66925658

390 1482.833 1482.4697 0.36334 0.0245 0.48595066 0.74769322

400 1482.361 1482.4479 -0.08689 -0.00586 0.48595066 -0.17880365

RUN: C13T4

Variable R101.C(1)

Time exp. value pred. value deviation %deviation Sigma deviation/sigma

-----------------------------------------------------------------------------------------------------

10 3711.353 3721.3929 -10.04 -0.271 18.100265 -0.55468237

20 2526.062 2514.3608 11.701 0.463 14.40606 0.81223828

30 1527.653 1510.605 17.048 1.12 10.708111 1.5920666

...

380 12.56785 13.886515 -1.3187 -10.5 0.69820401 -1.8886534

390 12.61461 13.469821 -0.85521 -6.78 0.68592824 -1.2467935

400 11.32563 13.077406 -1.7518 -15.5 0.67422183 -2.5982186

Variable R101.C(3)

Time exp. value pred. value deviation %deviation Sigma deviation/sigma

-----------------------------------------------------------------------------------------------------

10 902.8577 894.77629 8.0814 0.895 6.8020912 1.1880774

20 2409.363 2388.4785 20.885 0.867 12.029908 1.7360521

30 3653.779 3630.6263 23.153 0.634 15.341607 1.5091414

...

380 5439.398 5482.8154 -43.417 -0.798 19.490871 -2.2275781

390 5512.179 5483.3311 28.848 0.523 19.491935 1.4799917

400 5461.194 5483.8167 -22.623 -0.414 19.492938 -1.1605593

Variable R101.T

Time exp. value pred. value deviation %deviation Sigma deviation/sigma

-----------------------------------------------------------------------------------------------------

10 411.2345 412.291 -1.0565 -0.257 0.48595066 -2.1740865

20 503.8299 504.41591 -0.58601 -0.116 0.48595066 -1.2059009

30 603.1569 603.46722 -0.31032 -0.0514 0.48595066 -0.6385784

...

380 1482.294 1482.4928 -0.19877 -0.0134 0.48595066 -0.4090422

390 1482.465 1482.4697 -0.004658 -0.000314 0.48595066 -0.0095853147

400 1482.628 1482.4479 0.18011 0.0121 0.48595066 0.37063485

Analysis of the objective function: 1124.0778

RUN Variable Contribution

--------------------------------------

C13T1 R101.C(1) 34.545873

C13T1 R101.C(3) 139.77498

C13T1 R101.T -14.339464

C13T2 R101.C(1) 35.847343

C13T2 R101.C(3) 128.28478

C13T2 R101.T -0.27762525

C13T3 R101.C(1) 32.643752

C13T3 R101.C(3) 129.38619

C13T3 R101.T -4.846182

C13T4 R101.C(1) 63.511197

C.8. Sample Estimation Statistics File (ESTIMATE REACTOR.stat) 194

Page 196: Advanced Guide Gproms

gPROMS Advanced User Guide

C13T4 R101.C(3) 150.39624

C13T4 R101.T -11.939767

N/2*ln(2*PI) 441.0905

Sum of variance terms 420.36518

Sum of residual terms 262.62214

C.8. Sample Estimation Statistics File (ESTIMATE REACTOR.stat) 195

Page 197: Advanced Guide Gproms

gPROMS Advanced User Guide

C.9 Sample summary sheet

C.9. Sample summary sheet 196

Page 198: Advanced Guide Gproms

gPROMS Advanced User Guide

C.10 Sample parameter estimates sheet

C.10. Sample parameter estimates sheet 197

Page 199: Advanced Guide Gproms

gPROMS Advanced User Guide

C.11 Sample variance matrix sheet

C.11. Sample variance matrix sheet 198

Page 200: Advanced Guide Gproms

gPROMS Advanced User Guide

C.12 Sample correlation matrix sheet

C.12. Sample correlation matrix sheet 199

Page 201: Advanced Guide Gproms

gPROMS Advanced User Guide

C.13 Sample information matrix sheet

C.13. Sample information matrix sheet 200

Page 202: Advanced Guide Gproms

gPROMS Advanced User Guide

C.14 Part of a sample statistical significance sheet

C.14. Part of a sample statistical significance sheet 201

Page 203: Advanced Guide Gproms

gPROMS Advanced User Guide

C.15 Sample measured variable sheet

C.15. Sample measured variable sheet 202

Page 204: Advanced Guide Gproms

gPROMS Advanced User Guide

C.16 Overlay plots

Figure C.1: Overlay Plot Dialog Window

Figure C.2: Sample Overlay Plot

C.16. Overlay plots 203

Page 205: Advanced Guide Gproms

gPROMS Advanced User Guide

C.17 Residual plots

Figure C.3: Residual Plot Dialog Window

Figure C.4: Sample Weighted Residual Plot

C.17. Residual plots 204

Page 206: Advanced Guide Gproms

gPROMS Advanced User Guide

C.18 Confidence ellipsoid plots

Figure C.5: Residual Plot Dialog Window

Figure C.6: Sample Confidence Ellipsoid

C.18. Confidence ellipsoid plots 205

Page 207: Advanced Guide Gproms

gPROMS Advanced User Guide

Appendix D

Backward Compatibility ofParameter Estimation Features

Contents

D.1 Importing of gPROMS v1.x .gEST and .RUN files . . . . . . . 207

D.2 Exporting of projects containing parameter estimation entities207

D.3 Use of gEST.param files . . . . . . . . . . . . . . . . . . . . . . 207

206

Page 208: Advanced Guide Gproms

gPROMS Advanced User Guide

In the interests of backward compatibility, the current version of gPROMS still allowsaccess to certain deprecated features that were supported by earlier versions. These aredetailed in this appendix.

D.1 Importing of gPROMS v1.x .gEST and .RUN files

gPROMS v1.x .gEST and .RUN files can be imported into a project in the gPROMSModelBuilder.

In order to do this, follow the same procedure as that outlined in the chapter entitled“gPROMS ModelBuilder” of the “gPROMS Introductory User Guide”. Any .gEST fileimported into a project is automatically placed under the Parameter Estimations cate-gory in the project tree. Similarly, imported .RUN files are placed under the Experimentscategory

Note that the corresponding .gPROMS file would normally also need to be importedseparately into the project.

D.2 Exporting of projects containing parameter estima-tion entities

The contents of a project in ModelBuilder can be exported into a gPROMS v1.x inputfile and separate .gEST and .RUN files.

In order to do this, follow the procedure described in the chapter entitled “gPROMSModelBuilder” of the “gPROMS Introductory User Guide”. All files generated in thismanner will be placed in the input sub-directory. The file names are of the formname.gEST and name.RUN where name is the name of the corresponding entity (incapitals).

D.3 Use of gEST.param files

In earlier versions of gPROMS, solver parameters for parameter estimation were speci-fied using a gEST.param file. This is a text file that resides in your gPROMS workingdirectory. Its format is shown in table D.1. The parameters can be specified in any or-der, and can be included or omitted selectively. Keywords are highlighted in CAPITALS.The value next to the “{value}” entry is the default.

Note that gPROMS will make use of the contents of the gEST.param file only if noexplicit specification of the PESolver parameter (see section 10.7 of the “gPROMSIntroductory User Guide”) appears in the corresponding PROCESS entity. If an explicitPESolver specification appears (with or without any solver parameters actually being

D.1. Importing of gPROMS v1.x .gEST and .RUN files 207

Page 209: Advanced Guide Gproms

gPROMS Advanced User Guide

Specification Description/default value

RTOL Relative DAE integration tolerance{value} 10−5

ATOL Absolute DAE integration tolerance{value} 10−5

EVTOL Event location tolerance for DAE integration{value} 10−5

SSTOL (Re-)initialisation tolerance{value} 10−5

ACC Optimisation tolerance{value} 10−4

IPRINT Output printlevel{value} 0 (values of 1, 2 and 3 also allowed)MAXFUN Maximum number of function evaluations{value} 10000ISCAL Scaling of parameters1

{value} 0NOSENERR Suppress additional error test for sensitivities (default)SENERR Perform additional error test for sensitivities.

Note that no ‘value’ line is needed – the presenceof the flag alters the default behaviour.

STATISTICS Controls the level of advanced statistical calculation, cf. section 3.6.1.4{value} 0

Table D.1: Form of deprecated gEST.param files

D.3. Use of gEST.param files 208

Page 210: Advanced Guide Gproms

gPROMS Advanced User Guide

specified), then gEST.param is ignored.

The values shown in table B.1 correspond to the following SOLUTIONPARAMETERS speci-fication in the current version of gPROMS:

D.3. Use of gEST.param files 209

Page 211: Advanced Guide Gproms

gPROMS Advanced User Guide

PESolver := "MXLKHD" ["OutputLevel" := 0;

"MaxFun" := 10000;

"Scaling" := 0;

"OptTol" := 1E-4;

"SenErr" := FALSE;

"Statistics" := 0;

"DASolver" := "DASOLV"

[

"AbsoluteTolerance" := 1E-5;

"RelativeTolerance" := 1E-5;

"OutputLevel" := 0;

"InitialisationNLSolver" := "BDNLSOL"

[

"OutputLevel" := 0;

"BlockSolver" := "SPARSE"

[

"OutputLevel" := 0;

"ConvergenceTolerance" := 1E-5]

]

]

]

] ;

Note:

As gEST.param files may not be supported by future versions of gPROMS,you are strongly advised:

• not to use such files;

• to convert any existing ones to the new form of solver parameter spec-ification, as described in section 10.6 of the “gPROMS IntroductoryUser Guide”, as soon as possible.

D.3. Use of gEST.param files 210

Page 212: Advanced Guide Gproms

gPROMS Advanced User Guide

Appendix E

Microsoft Excel Foreign Objectand Foreign Process Interfaces

Contents

E.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212

E.2 Using Microsoft Excel Foreign Objects . . . . . . . . . . . . 213

E.3 Creating Microsoft Excel Foreign Objects . . . . . . . . . . . 214

E.3.1 Specifying cell cross-references . . . . . . . . . . . . . . . . . . 216

E.3.2 Using the method definition macro . . . . . . . . . . . . . . . . 217

E.3.3 A simple example . . . . . . . . . . . . . . . . . . . . . . . . . 218

E.3.4 Cell ranges for arrays with more than two dimensions . . . . . 218

E.4 Using the Microsoft Excel Foreign Process Interface . . . . 223

E.5 Creating Microsoft Excel Foreign Processes . . . . . . . . . 225

E.5.1 Using the FPI definition macro . . . . . . . . . . . . . . . . . . 226

E.6 Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . 227

E.7 An example problem with Microsoft Excel FOI and FPI . . 228

211

Page 213: Advanced Guide Gproms

gPROMS Advanced User Guide

E.1 Introduction

The Microsoft Excel1 Foreign Object and Foreign Process interfaces are designed toallow gPROMS to interact dynamically with calculations performed in Microsoft Ex-cel. The Microsoft Excel Foreign Object interface can be used to provide values forPARAMETERs and external calculations for VARIABLEs in a gPROMS simulation (e.g. tolink a gPROMS model with an accounting spreadsheet). The Microsoft Excel ForeignProcess interface can be used for a number of purposes:

• An Excel “front-end” to a gPROMS simulation can be created where the usercan interactively provide input to the simulation and have the results update thespreadsheet automatically.

• The results of a gPROMS simulation can be tabulated in an Excel spreadsheet,or tabulated data in a spreadsheet can be used, over time, to update variables ina simulation.

• The Microsoft Excel FPI can be used to synchronise a gPROMS simulation withexternal software.

In this chapter, we describe how to use Microsoft Excel Foreign Objects and the ForeignProcess interface from gPROMS and how to create and use foreign objects and theForeign Process interface in Microsoft Excel.

1The facilities described in this Appendix are supported by Microsoft Excel 97 and later versions.

E.1. Introduction 212

Page 214: Advanced Guide Gproms

gPROMS Advanced User Guide

E.2 Using Microsoft Excel Foreign Objects

Microsoft Excel Foreign Objects are specified in the gPROMS input file in the sameway that other Foreign Objects are.

In the gPROMS MODEL, a parameter must be defined as FOREIGN OBJECT with the class"ExcelFO":

PARAMETER

ParameterPath AS FOREIGN_OBJECT "ExcelFO"

The file that will be used by ExcelFO must then be specified in a SET statement:

SET

ParameterPath := "ForeignObjectValue" ;

In this case, ForeignObjectValue must be the full path name of the file (recommended)or the file must be present in the gPROMS export directory.

This Foreign Object can be used in equations to provide external calculations. Forexample, imagine that a workbook with the filename Capital Costs.xls calculatesthe approximate capital cost of various units. These calculations can be defined asmethods of this workbook, with inputs such as the volume of the unit. We might thenhave:

PARAMETER

CapCosts AS FOREIGN_OBJECT "ExcelFO"

...

SET

CapCosts := "Capital_Costs.xls"

...

EQUATION

Tank_Cost = CapCosts.Tank(Tank_Volume) ;

...

In the example above, we calculate the capital cost of a tank, based on its volumeusing the Tank method in the Capital Costs.xls workbook (resident in the gPROMSworking directory).

In the next section, we describe in detail how to create Foreign Object methods inMicrosoft Excel workbooks.

E.2. Using Microsoft Excel Foreign Objects 213

Page 215: Advanced Guide Gproms

gPROMS Advanced User Guide

E.3 Creating Microsoft Excel Foreign Objects

Microsoft Excel Foreign Objects are created from Excel workbooks by including methoddefinition worksheets. The method definition worksheets specify, for each method:

• the method name;

• which cells are to provide the output values of the method;

• the names of any inputs;

• which cells correspond to the inputs;

• the parameter type (REAL, INTEGER, or LOGICAL);

• information for consistency checking of dimensions2;

• cells that provide values for the derivative of the output with respect to the input(if available).

Worksheets that contain method definitions must have names that begin with gFO- (e.g.gFO-Scalars and gFO-Vectors), and there may be any number of method definitionworksheets. The format of the worksheet is shown in figure E.1.

Multiple method definitions can exist side-by-side on a worksheet. ExcelFO determineswhere a method definition starts by searching for the word “Output” in the first row.The first method definition must start in column B; column A is ignored so that theentries above can be used for guidance. Any subsequent column in row 1 that containsanything other than “Output” is treated as an input for the current method. If ExcelFOfinds an empty cell while scanning the first row (other than A1), it stops searching forany more method definitions on the current worksheet and moves on to the next method-definition worksheet (method-definition worksheets are processed in order from left toright). Therefore the method definitions must not be separated by blank columns; anydefinitions to the right of a blank column will be ignored.

Below each entry in row 1, ExcelFO searches for information in the following order:

row 2 The method name (if the column begins with the keyword “Output”) or theinput name must be specified in row 2. Note that since gPROMS is not casesensitive, the methods method1 and METHOD1 are considered identical. If thereare multiple definitions of the same method in your workbook, the first definitionthat gPROMS finds will be used; all subsequent definitions will be ignored and awarning message will be displayed when the gPROMS input file is executed.

row 3 The third row contains cell cross-references for the inputs and output of themethod. This is described in more detail below.

2These are for future compatibility with new versions of gPROMS.

E.3. Creating Microsoft Excel Foreign Objects 214

Page 216: Advanced Guide Gproms

gPROMS Advanced User Guide

Figure E.1: Format of the method definition worksheet.

E.3. Creating Microsoft Excel Foreign Objects 215

Page 217: Advanced Guide Gproms

gPROMS Advanced User Guide

row 4 The variable or parameter type must be specified here. The entries in this rowmust correspond with the type of the gPROMS PARAMETER that is being transmit-ted (i.e. REAL, INTEGER or LOGICAL) or be set to “Real” for gPROMS VARIABLEs.ExcelFO only recognises the first letter of the entry and is case insensitive.

rows 5–16 The information for checking the consistency of dimensions is specified here.Rows 5 to 14 contain the indices of the dimensions in rational form. For example,for a parameter with dimensions of [Length]2 the string “2/1” would be enteredin row 5; if the units of a parameter were kg/m3, the strings “-3/1” and “1/1”would be entered in rows 5 and 6 respectively. The indices of the dimensions mustbe entered in the order [Length], [Mass], [Time], [Electric current], [Temperature],[Amount of substance], [Luminous intensity], [Plane angle], [Solid angle], [Money].Rows 15 and 16 contain the offset and multiplier required to convert the units ofthe parameter (or output) to SI using the equation: SIunits = offset+multiplier×nonSIunits . For example, if the units of a parameter were Celsius, the offset andmultiplier would be specified as 273.15 and 1 respectively.

row 17 Contains optional cell references for the derivative of the method output withrespect to its inputs. This is ignored for columns that specify outputs. Blank cellsindicate that the derivative is unavailable.

E.3.1 Specifying cell cross-references

Cell cross-references are specified as is normal in Excel: i.e. by typing “=<sheet name>!<range>” to specify a range from a particular worksheet. This can be done automati-cally in Excel by pressing “=” then selecting the worksheet with the mouse, highlightingthe range and pressing the RETURN or TAB key.

It is important to make sure that the number of cells specified in the range is equalto the number of elements of the variable or parameter in gPROMS. For variables andparameters that are scalars or vectors, the specification of the ranges is trivial; vectorsmay be specified in columns or rows. For variables and parameters of higher dimension,the range must be specified in a specific manner. For two-dimensional arrays, the rangeof cells must be a rectangle with the number of rows equal to the number of elementsin the first index and the number of columns equal to the number of elements in thesecond index. The example below illustrates this more clearly.

Consider a parameter defined by the following:

PARAMETER

A1 AS ARRAY(2,3) OF REAL

The array of cells in the Excel worksheet that correspond to this should be a rectanglethree columns wide and two rows deep. It is important to check that this is specifiedcorrectly because gPROMS only checks that the number of elements is correct. Fig-ure E.2(a) shows how the elements of the parameter are related to the array of cells in

E.3. Creating Microsoft Excel Foreign Objects 216

Page 218: Advanced Guide Gproms

gPROMS Advanced User Guide

A1(1,1) A1(1,2) A1(1,3)

A1(2,1) A1(2,2) A1(2,3)

(a) Cell range specified correctly

A1(1,1) A1(1,2)

A1(1,3) A1(2,1)

A1(2,2) A1(2,3)

(b) Cell range speci-fied incorrectly

Figure E.2: Correspondence of elements in a 2 × 3 array with correctly and incorrectlyspecified cell blocks in Excel.

Excel; figure E.2(b) illustrates how the elements will be assigned incorrectly if the cellsare specified incorrectly.

Although it is not envisaged that arrays with more than two dimensions will be neces-sary, support for higher dimensions is possible and is outlined in section E.3.4.

E.3.2 Using the method definition macro

Your ExcelFO installation comes with a template workbook that contains macros forgenerating method definition worksheets and foreign process worksheets. To make useof the macros, you must have the file gXLmacros.xls open while working on your Excelworkbook. To run the method definition macro select Tools menu, then select Macro,then Macros. . . (or just press ALT+F8), select the makeFOsheet macro and left-clickon the “Run” button.

You will now be presented with a dialogue box that contains a list of current macrodefinition worksheets and four buttons:

“New. . . ” Left-click on this button to create a new method definition worksheet.

“Delete” Select a method definition worksheet from the list and left-click this buttonto delete it.

“Methods. . . ” Select a method definition worksheet from the list and left-click thisbutton to edit, add or delete methods from the worksheet.

“Exit” Left-click to return to the workbook. Any modifications you made during thesession were saved automatically.

When you click on the “New. . . ” button, you will be prompted to enter the name ofthe new worksheet. Enter the name without the gFO- prefix; this is added automati-cally. Once there is a method definition worksheet, you can select it and click on the“Methods. . . ” button. This takes you to the method dialogue, where new methods canbe added and existing methods can be edited or deleted.

E.3. Creating Microsoft Excel Foreign Objects 217

Page 219: Advanced Guide Gproms

gPROMS Advanced User Guide

To create a new method, type the name in the space provided and press the “Add”button. You may also specify the type (which must be Real) and the cell cross-reference.Note that you must include the “=” when typing in the cross-reference and that theworksheet must be specified along with the cell range. If you do not specify the typeand cell cross-reference, then they can be edited in the workbook later.

Once a method is defined, you may add, remove or edit its inputs by clicking on the“Inputs >>” button, below the list of methods. The input dialogue behaves exactly asthe methods dialogue. To return to the methods dialogue, click on the “<< Methods”button, below the list of inputs.

Once you have finished adding methods and inputs to the worksheet, click on the “OK”button. If you wish to discard any edits, press the “Cancel” button.

Note that you can edit most properties by using the macro, but it is not possible to editthe names of worksheets, methods or inputs. However, these are easily modified in theworkbook.

To complete the method definition worksheet, you need to edit the workbook directlyto include cross-references for derivatives, to specify the information on dimensions (ifnecessary) and to complete the specification of input and output cross-referencing.

E.3.3 A simple example

To illustrate many of the features described above, we consider the trivial example ofcalculating the Reynold’s Number for fluid flow in a pipe. Figure E.3 shows excerptsfrom a MODEL where the Reynolds number is calculated using the ExcelFO Foreign Ob-ject interface. The physical properties of the fluid are also obtained from the MicrosoftExcel Foreign Object.

To make the Foreign Object, we need to open a new file called FlowCalc.xls in Mi-crosoft Excel and enter the Reynold’s Number calculation and the method definitions.The worksheet, named Sheet1, containing the Reynold’s Number calculation is shownin figure E.4. The method-definition sheet shown in figure E.5 is easily created us-ing the method definition macro. Simply run the macro (press ALT-F8), add a newmethod-definition worksheet (call it “methods”), add the three methods and add twoinputs to the ReNumber method, selecting variable type “Real” for each. Return to theworksheet by pressing “OK” then “Exit” and complete the “gFO-methods” worksheetby adding the cross references and filling out the dimensions of the inputs and outputs(this last part is not necessary with the current version of gPROMS).

E.3.4 Cell ranges for arrays with more than two dimensions

Earlier, we looked at the specification of cell ranges for arrays of one or two dimensions.One-dimensional arrays can have cell ranges specified as either columns or rows. Vari-ables and parameters defined as ARRAY(x,y) correspond to cell ranges which are y cells

E.3. Creating Microsoft Excel Foreign Objects 218

Page 220: Advanced Guide Gproms

gPROMS Advanced User Guide

PARAMETER

FO AS FOREIGN_OBJECT "ExcelFO"

Diameter AS REAL

Viscosity AS REAL

Density AS REAL

...

VARIABLE

Velocity AS Flow

Re AS Dimensionless

...

SET

FO := "FlowCalc.xls" ;

Diameter := 0.1 ;

Viscosity := FO.Viscosity ;

Density := FO.Density ;

EQUATION

...

Re = FO.ReNumber(Velocity,Diameter) ;

...

Figure E.3: Example MODEL using the ExcelFO Foreign Object.

wide and x cells deep. This is shown in figure E.6.

Cell ranges must be specified as prescribed above because of the format in whichgPROMS stores arrays and the way that the elements are sent to and read from Excel.Internally, gPROMS converts all n-dimensional arrays into arrays of one dimension. Theelements of the n-dimensional array are mapped to the 1-d array by cycling through theindices; the right-most index is cycled fastest and the left-most index cycles throughslowest. This is illustrated using a small 3-d array: A1 AS ARRAY(2,3,4). Internally,the elements of A1 would be stored in the order:

E.3. Creating Microsoft Excel Foreign Objects 219

Page 221: Advanced Guide Gproms

gPROMS Advanced User Guide

Figure E.4: Worksheet containing the calculation of the Reynold’s Number.

Figure E.5: Macro-definition worksheet for the Reynold’s Number example.

E.3. Creating Microsoft Excel Foreign Objects 220

Page 222: Advanced Guide Gproms

gPROMS Advanced User Guide

(1,1) (1,2) (1,3) · · · (1,y)(2,1) (2,2) (2,3) · · · (2,y)

......

......

(x,1) (x,2) (x,3) · · · (x,y)

Figure E.6: Cell range for an x by y array.

[ (1,1,1,), (1,1,2,), (1,1,3,), (1,1,4,), (1,2,1,), (1,2,2,),

(1,2,3,), (1,2,4,), (1,3,1,), (1,3,2,), (1,3,3,), (1,3,4,),

(2,1,1,), (2,1,2,), (2,1,3,), (2,1,4,), (2,2,1,), (2,2,2,),

(2,2,3,), (2,2,4,), (2,3,1,), (2,3,2,), (2,3,3,), (2,3,4,) ]

When data is exchanged between gPROMS and Excel, the elements of arrays are reador sent in this order. In Excel, the elements are then read from or written to the cellsstarting with the top left cell of the cell range and moving left-to-right. If, for example,we were to specify the cell range A1:C8 for the above 3-dimensional array (obviouslynot a sensible choice), the first few rows would correspond to the following elements:

Clearly, the above cell-range specification is not much use, but since we now know howthe elements are exchanged between Excel and gPROMS, we can specify a more usefulcell range. For 3-dimensional arrays, there are two possibilities that would seem to beof most use: z cells wide and x× y cells deep or y× z cells wide and x cells deep, wherethe array is defined as ARRAY(x,y,z). The former consists of x blocks of cells, stackedvertically, that are z cells wide and y cells deep; the latter consists of y blocks of cells,positioned horizontally, that are z cells wide and x cells deep. These two specificationsare illustrated in figures E.7 and E.8 respectively.

It is also possible to specify cell ranges for arrays of more dimensions. 4-dimensionalarrays can be specified by repeating cell blocks for 3-dimensional arrays, and so on.However, in the majority of cases, it will not be necessary to specify cell ranges for morethan 2-dimensional arrays.

E.3. Creating Microsoft Excel Foreign Objects 221

Page 223: Advanced Guide Gproms

gPROMS Advanced User Guide

(1,1,1) (1,1,2) (1,1,3) · · · (1,1,z)(1,2,1) (1,2,2) (1,2,3) · · · (1,2,z)

......

......

(1,y,1) (1,y,2) (1,y,3) · · · (1,y,z)

(2,1,1) (2,1,2) (2,1,3) · · · (2,1,z)(2,2,1) (2,2,2) (2,2,3) · · · (2,2,z)

......

......

(2,y,1) (2,y,2) (2,y,3) · · · (2,y,z)...

(x,1,1) (x,1,2) (x,1,3) · · · (x,1,z)(x,2,1) (x,2,2) (x,2,3) · · · (x,2,z)

......

......

(x,y,1) (x,y,2) (x,y,3) · · · (x,y,z)

Figure E.7: z by x× y cell range for an x by y by z array.

Block 1 Block 2 · · · Block y

(a) Block view

(1,j,1) (1,j,2) (1,j,3) · · · (1,j,z)(2,j,1) (2,j,2) (2,j,3) · · · (2,j,z)

......

......

(x,j,1) (x,j,2) (x,j,3) · · · (x,j,z)

(b) Close-up view of block j

Figure E.8: y × z by x cell range for an x by y by z array.

E.3. Creating Microsoft Excel Foreign Objects 222

Page 224: Advanced Guide Gproms

gPROMS Advanced User Guide

E.4 Using the Microsoft Excel Foreign Process Interface

Setting up the gPROMS input file to use the Microsoft Excel FPI is very simple. All thatis needed to enable the FPI is the following line in the SOLUTIONPARAMETERS section:

FPI := "ExcelFP::filename"

where filename is the name of the Excel workbook to be used. Again, if the full path ofthe workbook is not specified, the file is assumed to be in the gPROMS export directory.

Once the FPI has been enabled using the above syntax, the following FPI tasks may beused in the SCHEDULE section of a PROCESS entity.

PAUSE gPROMS suspends execution of a process until the workbook is recalculated.Excel must be configured to recalculate only when the user requests it, which canbe set in the “Tools/Options. . . /Calculation” menu.

GET gPROMS retrieves data from the Excel workbook and assigns them to a VARIABLE

(or VARIABLES). This task behaves differently depending on the calculation modeset in the PFI worksheet (see later).

Normal mode In normal mode, the workbook is recalculated automatically andthe data is retrieved.

Manual mode In manual mode, the execution of the process is suspended untilthe workbook is recalculated manually (as with the PAUSE task), at whichpoint the required values are retrieved.

Real-time mode Real-time mode is used to synchronise the gPROMS simula-tion with real time. Every time a GET or SEND task is called, gPROMS willpause until the real elapsed time is equal to the simulation time and thentransmit or recieve the data. Naturally, if the simulation is unable to keepup with real time (i.e. the model is too complex to solve in real time), thismode will behave similarly to Normal mode.

SEND gPROMS sends the value(s) of one or more VARIABLEs to the Excel worksheet. Ifthe “gTIME” tag has been defined, its value is automatically updated every timeSEND is called. SEND is unaffected by the calculation mode.

SENDMATHINFO Each time this task is called, a new worksheet is created and filled inwith the details (current values of the variables, Jacobian elements, etc.) of thecurrent simulation problem.

The syntax for the above tasks is shown below.

PAUSE

GET

E.4. Using the Microsoft Excel Foreign Process Interface 223

Page 225: Advanced Guide Gproms

gPROMS Advanced User Guide

VariablePath := "ForeignVariableID" ;

END

SEND

<SIGNALID "NoTime">"ForeignVariableID" := VariablePath ;

END

SENDMATHINFO

PAUSE and SENDMATHINFO require no arguments. GET and SEND specify the gPROMSvariable pathname and the name of the Excel variable that are to be equated to eachother. For the GET task, the gPROMS variable specified in VariablePath is assigned tothe value of the Excel variable ForeignVariableID (this is defined in the FPI worksheet);for the SEND task, the assignment works the other way around. Multiple assignmentsmay be included in any one instance of the task. The SEND task may also contain theoptional argument: SIGNALID "NoTime", which suppresses the updating of “gTIME”.

For array variables, the "ForeignVariableID" entry must also include the element rangebeing sent (there is no shortcut for sending all elements, as there is in gPROMS). Thesyntax for this is:

"ForeignVariableID"(LowerCellLimit:UpperCellLimit < , . . .> )

For example, if we wanted to send all elements of the variable A defined as an ARRAY(2,4),the following syntax would be used:

"A"(1:2,1:4) := A ;

For a general description of the FPI communication tasks, see section 5.2.

The next section describes how the FPI is defined in the Excel workbook.

E.4. Using the Microsoft Excel Foreign Process Interface 224

Page 226: Advanced Guide Gproms

gPROMS Advanced User Guide

Figure E.9: Format of the Foreign Process definition worksheet.

E.5 Creating Microsoft Excel Foreign Processes

As with the FOI, the Excel FPI is defined using a worksheet with a special name. Ex-celFP only uses one FPI definition sheet, called “gFPI”. This worksheet defines eachtag (the name that will be used in the gPROMS input file corresponding to Foreign-VariableID), its cell cross-reference, the type variable (Real, Integer or Logical) andwhether the data should be sent or received in tabular form. Finally, the “gFPI” work-sheet contains a cell that defines the calculation mode (Normal, Real-time, or Manual).The format of the worksheet is shown in figure E.9.

As with the Foreign Object definition worksheets, the first column is ignored by ExcelFP.Each subsequent column defines a single tag. The name, type and cross-reference needno explanation (see section E.3 for details on specifying types and cross-references). Thetable mode is used to specify how data sent to Excel may be tabulated or how tabulateddata in Excel may be sent to gPROMS. If a table mode is specified, ExcelFO uses a cellrange offset from the one specified in the FOI definition worksheet. Each time GET orSEND is called on the tag, this offset increases so that either a table is created (SEND) orread (GET). Specifying the table mode as R(owise) results in the cross-reference beingincreased by one row every time the tag is referenced in a GET or SEND task (naturally,the original cell range must be either a scalar or a column vector and you cannot useboth SEND and GET tasks on the same table). The C(olumnwise) specification workssimilarly.

Finally, the execution mode is specified in cell B6. The execution mode affects howthe GET task is handled, and may be set to Normal, Automatic or Manual. This wasdescribed in detail in section E.4.

If a tag is defined with the name “gTIME”, ExcelFP uses this to synchronise the execu-tion of the gPROMS process with an external process. Whenever a SEND task is called,ExcelFP automatically updates the gTIME tag with the current simulation time. IfgTIME is being used in table mode, to generate a table of a variable with time as theabscissa, there are occasions when two SEND tasks will be called in sequence without thesimulation time increasing (e.g. at the beginning and end of a WHILE loop). In thesecircumstances, two entries with the same time will be generated in the table. To avoid

E.5. Creating Microsoft Excel Foreign Processes 225

Page 227: Advanced Guide Gproms

gPROMS Advanced User Guide

this, the SIGNALID "NoTime" option can be used to suppress one of the entries.

E.5.1 Using the FPI definition macro

As with ExcelFO, there is a macro available which greatly reduces the effort in creatingthe FPI definition worksheet. The macro is available in the gXLmacros.xls file and isaccessed through the Tools/Macro/Macros. . . menu (or press ALT+F8). Selecting themakeFPsheet and pressing “Run” will start the macro.

Using the FPI definition macro is very easy. Simply enter the details of the new tagin the appropriate boxes, then press the “Add” button to add a new tag. Existingtags may be removed by selecting its name and pressing the “Delete” button. Changesmade in the session are updated on the worksheet by pressing “OK”, whereas pressing“Cancel” discards all changes.

E.5. Creating Microsoft Excel Foreign Processes 226

Page 228: Advanced Guide Gproms

gPROMS Advanced User Guide

E.6 Troubleshooting

If gPROMS appears to have stopped working while using ExcelFO or ExcelFP then trythe following:

• Make sure there are no dialog boxes open in Excel, and no cells are being edited.Then just select another cell in the worksheet. If ExcelFO or ExcelFP have troubletalking to Excel at any point, they often wait for either a selection change or acell to be changed before continuing execution.

• Select all the cells in the worksheet, select the “format/cell. . . ” menu, select the“protection” tab and make sure the “locked” property is unchecked. ExcelFO andExcelFP use the locked property of cells to determine whether another instanceis accessing those cells. This problem often occurs if a gPROMS run is stoppedprematurely.

E.6. Troubleshooting 227

Page 229: Advanced Guide Gproms

gPROMS Advanced User Guide

E.7 An example problem with Microsoft Excel FOI andFPI

In this section, we will describe a more detailed example problem involving both theMicrosoft Excel FOI and FPI. The process is a liquid-phase CSTR reactorinvolving thefollowing reaction: A+B C+D. A general-purpose gPROMS model for an isothermalCSTR is shown in figure E.10.

The reaction schemes and the rates of the reactions are specified through the parame-ters Nu, Order and ReactionConstant. The number of components and reactions arespecified through the NoComp and NoReac parameters. A typical specification for theabove reversible reaction is shown in figure E.11. However, as this is quite cumbersome(and will be even more so with a large number of components and reactions), it wouldbe more convenient to specify these using an Excel spreadsheet. The Foreign ObjectRxnData is instead used for this purpose. Figure E.12 shows the equivalent parameterspecification using the Foreign Object defined in the file cstr.xls.

The two worksheets that are used to generate the Foreign Object are shown in figuresE.13 and E.14. The first worksheet shows how the data for the parameters is entered.The second worksheet contains the method definitions for the Foreign Object (note theworksheet name begins with the prefix gFO-).

Finally, the problem can be run in the gPROMS environment without an FPI usingthe typical PROCESS entity shown in figure E.15. However, an alternative approach isto write a Microsoft Excel FPI to specify the inlet flowrate and composition and toretrieve the tank composition and outlet flowrate over time. This can be implementedby creating the worksheets shown in figures E.17 and E.18. The first worksheet simplycontains a schematic of the process, along with the inlet conditions to be specified, thetank composition, the simulation time and the outlet flowrate. The second worksheet,called gFPI, contains the definitions of the tags that are used to link gPROMS variableswith the cells in the Excel worksheet.

E.7. An example problem with Microsoft Excel FOI and FPI 228

Page 230: Advanced Guide Gproms

gPROMS Advanced User Guide

# MODEL LiquidPhaseCSTR

PARAMETER

NoComp AS INTEGER

NoReac AS INTEGER

ValveConstant AS REAL

CrossSectionalArea AS REAL

Hp AS REAL

Density AS ARRAY(NoComp) OF REAL

ReactionConstant AS ARRAY(NoReac) OF REAL

Order AS ARRAY(NoComp,NoReac) OF INTEGER

Nu AS ARRAY(NoComp,NoReac) OF INTEGER

RxnData AS FOREIGN_OBJECT "ExcelFO"

VARIABLE

Fin AS MolarFlowrate

Xin AS ARRAY(NoComp) OF MolarFraction

Fout AS MolarFlowrate

X AS ARRAY(NoComp) OF MolarFraction

HoldUp AS ARRAY(NoComp) OF Moles

C AS ARRAY(NoComp) OF MolarConcentration

TotalHoldup AS Moles

TotalVolume AS Volume

Height AS Length

Rate AS ARRAY(NoReac) OF NoType

EQUATION

FOR i := 1 TO NoComp DO

$HoldUp(i) = Fin*Xin(i) - Fout*X(i) + TotalVolume*SIGMA(Nu(i,)*Rate) ;

END

FOR j := 1 TO NoReac DO

Rate(j) = ReactionConstant(j) * PRODUCT(C^Order(,j)) ;

END

TotalVolume = SIGMA(Holdup/Density) ;

TotalHoldup = SIGMA(HoldUp) ;

Holdup = X * TotalHoldup ;

Holdup = C * TotalVolume ;

TotalVolume = CrossSectionalArea * Height ;

IF Height > Hp THEN

Fout = ValveConstant * (Height - Hp) ;

ELSE

Fout = 0 ;

END

Figure E.10: gPROMS model of the CSTR.

E.7. An example problem with Microsoft Excel FOI and FPI 229

Page 231: Advanced Guide Gproms

gPROMS Advanced User Guide

SET

WITHIN R101 DO

RxnData := "cstr.xls" ;

NoComp := 4 ;

NoReac := 2 ;

Nu := [ -1, +1,

-1, +1,

+1, -1,

+1, -1 ] ;

Order := [ 1, 0,

1, 0,

0, 1,

0, 1 ] ;

ReactionConstant := [ 8E-5, 1E-5 ] ; # m3/kmol s

Density := [ 17.48, 17.15, 10.24, 55.56 ] ; # kmol/m3

CrossSectionalArea := 5 ; # m2

Hp := 5 ; # m

ValveConstant := 0.3 ;

END

Figure E.11: A typical specification for the CSTR parameters.

SET

WITHIN R101 DO

RxnData := "cstr.xls" ;

NoComp := RxnData.NumberOfComponents ;

NoReac := RxnData.NumberOfReactions ;

Nu := RxnData.StoichiometricCoefficients ;

Order := RxnData.ReactionOrder ;

ReactionConstant := RxnData.RateConstant ;

Density := RxnData.Density ;

CrossSectionalArea := RxnData.CrossSectionalArea ;

ValveConstant := RxnData.ValveCoefficient ;

Hp := RxnData.PipeHeight ;

END

Figure E.12: Specification of the CSTR parameters using the Foreign Object.

E.7. An example problem with Microsoft Excel FOI and FPI 230

Page 232: Advanced Guide Gproms

gPROMS Advanced User Guide

Figure E.13: Parameter worksheet for the CSTR example.

E.7. An example problem with Microsoft Excel FOI and FPI 231

Page 233: Advanced Guide Gproms

gPROMS Advanced User Guide

(a) Columns A to E.

(b) Columns F to J

Figure E.14: Method definition worksheet for the CSTR example.

E.7. An example problem with Microsoft Excel FOI and FPI 232

Page 234: Advanced Guide Gproms

gPROMS Advanced User Guide

# PROCESS Sim2 # using EXCEL Foreign Object for data

UNIT

R101 AS LiquidPhaseCSTR

SET

...

ASSIGN

WITHIN R101 DO

Fin := 1 ;

Xin := [ 0.5, 0.5, 0, 0 ] ;

END

INITIAL

WITHIN R101 DO

X(2) = 2 * X(1) ;

X(3) = 0 ;

X(4) = 0 ;

TotalVolume = 10 ;

END

SCHEDULE

CONTINUE FOR 7200

Figure E.15: PROCESS entity for the CSTR example without a Foreign Object.

E.7. An example problem with Microsoft Excel FOI and FPI 233

Page 235: Advanced Guide Gproms

gPROMS Advanced User Guide

# PROCESS Sim3 # using EXCEL Foreign Object for data

# using EXCEL Foreign Process for real-time interaction

UNIT

R101 AS LiquidPhaseCSTR

SET

...

ASSIGN

WITHIN R101 DO

Fin := 1 ;

Xin := [ 0.5, 0.5, 0, 0 ] ;

END

INITIAL

WITHIN R101 DO

X(2) = 2 * X(1) ;

X(3) = 0 ;

X(4) = 0 ;

TotalVolume = 10 ;

END

SOLUTIONPARAMETERS

FPI := "ExcelFP::cstr.xls" ;

SCHEDULE

WHILE TIME < 7200 DO

SEQUENCE

CONTINUE FOR 1

PARALLEL

GET

R101.Fin := "FeedFlowrate" ;

R101.Xin := "FeedMoleFractions"(1:4) ;

END

SEND

"TankMoleFractions"(1:4) := R101.X ;

"LiquidHeight" := R101.Height ;

"ExitFlowrate" := R101.Fout ;

END

END

END

END

Figure E.16: PROCESS entity for the CSTR example with a Foreign Object.

E.7. An example problem with Microsoft Excel FOI and FPI 234

Page 236: Advanced Guide Gproms

gPROMS Advanced User Guide

Figure E.17: User-interface worksheet for the CSTR example.

Figure E.18: FPI definition worksheet for the CSTR example.

E.7. An example problem with Microsoft Excel FOI and FPI 235