Você está na página 1de 410

Aspen Custom

Modeler 2004.1
Aspen Modeler Reference Guide
Who Should Read this Guide

This guide contains information on using automation, solver options, physical


properties, the Control Design Interface (CDI), Simulation Access eXtensions,
online links, and using external nonlinear algebraic solvers.

Who Should Read this Guide 2


Contents
INTRODUCING ASPEN CUSTOM MODELER ..................................................... 14

1 USING AUTOMATION AND VISUAL BASIC ................................................. 15


Automatically Run Script Events ............................................................................... 15
Handling Errors...................................................................................................... 16
Working with Sets .................................................................................................. 17

2 CONTROLLING SIMULATIONS WITH SCRIPTS ........................................... 20


Syntax for Scripts .................................................................................................. 21
Examples of Scripts ................................................................................................ 22
Example of Setting Up Initial Conditions for a Flash System .................................... 22
Example of Initializing an Array Variable, Changing the Upper Bound of a Variable, and
Setting the Run Mode to Dynamic........................................................................ 23
Calling External Applications .................................................................................... 23
Improving the Speed of Visual Basic Scripts............................................................... 24
DisableIncrementalUpdate Command................................................................... 24
EnableIncrementalUpdate Command.................................................................... 25
Passing Inputs to Scripts and Getting Outputs from Scripts .......................................... 26
Automatically Run Event Scripts ............................................................................... 27

3 CONTROLLING SIMULATIONS WITH EXTERNAL VISUAL BASIC ................. 29


Creating an Instance of an Application Object ............................................................ 30
Example of Creating an Instance of an Application Object ....................................... 30
Creating an Instance of an Application Object for a Specified Product Version ............ 30
Accessing Simulation and Document Objects.............................................................. 31
Example of Accessing Objects ............................................................................. 32
Using a Simulation Variable to Run a Simulation ......................................................... 32
Example of Using a Simulation Variable to Run a Simulation.................................... 33
Checking the Simulation ......................................................................................... 33
Saving Changes and Closing the Application............................................................... 33
Example of Using External Visual Basic...................................................................... 33
Running Multiple Simulations ................................................................................... 34
Example of Running Multiple Simulations .............................................................. 34

Contents 3
Using the GetObject Method .................................................................................... 35
Example of Using GetObject ............................................................................... 36

4 AUTOMATION METHODS AND PROPERTIES ............................................... 37


List of Properties that Return Objects ................................................................... 38
Accessing Items Within the Flowsheet .................................................................. 40
Table of Key Automation Objects ......................................................................... 41
Application Object .................................................................................................. 42
Application Properties ........................................................................................ 42
Application Methods .......................................................................................... 46
Application Events............................................................................................. 50
ActiveDocument Object........................................................................................... 51
ActiveDocument Properties ................................................................................. 51
ActiveDocument Methods ................................................................................... 53
Form Object .......................................................................................................... 56
VariablesPaths .................................................................................................. 57
Simulation Object .................................................................................................. 57
Simulation Properties......................................................................................... 57
Simulation Methods ........................................................................................... 72
Properties Object ................................................................................................... 79
Properties of the Properties Object....................................................................... 79
Properties Methods............................................................................................ 80
ComponentList Object............................................................................................. 81
ComponentList Properties................................................................................... 81
OutputLogger Object .............................................................................................. 84
OutputLogger Properties .................................................................................... 84
OutputLogger Methods....................................................................................... 87
Results Object ....................................................................................................... 88
Results Properties ............................................................................................. 88
Results Methods..................................................................................................... 89
UOM Object........................................................................................................... 95
Block, Stream, Structure and Flowsheet Objects ......................................................... 95
Methods Common to Block, Stream, Structure and Flowsheet Objects ...................... 96
Flowsheet-Specific Methods ...............................................................................110
Stream-Specific Methods...................................................................................113
Port Object ..........................................................................................................116
Name and GetPath Methods for Ports ..................................................................116
Testing Whether a Port is Connected...................................................................117
Testing Whether a Port is Connected to Hierarchy Connector or Is Linked.................117
Variable Object .....................................................................................................118

Contents 4
Units of Measurement .......................................................................................118
Working with Set Attributes ...............................................................................119
About the History Method ..................................................................................120
History Properties and Methods ..........................................................................121
Exploring Variable Time History..........................................................................124
Other Custom Methods .....................................................................................127
RealVariables Methods ......................................................................................133
Task Object..........................................................................................................134
Active Property ................................................................................................134
LanguageText Property .....................................................................................135
Homotopy Object ..................................................................................................135
Homotopy Properties ........................................................................................135
Homotopy Methods ..........................................................................................136
Optimization Object...............................................................................................137
Optimization Properties .....................................................................................137
Optimization Methods .......................................................................................139
OnLineLinks Object ...............................................................................................143
OnlineLinks Properties ......................................................................................143
OnLineLinks Methods ........................................................................................146
OLL Variable Object...............................................................................................148
OLL Variable Object Properties ...........................................................................148
OLL Variable Object Methods .............................................................................150
CDI Object ...........................................................................................................150
CDI Properties .................................................................................................150
CDI Methods ...................................................................................................153
StructureContainer Object ......................................................................................157
StructureContainer Methods ..............................................................................157
Defining an Estimation Simulation ...........................................................................158
Defining Estimated Variables .............................................................................158
Defining Steady-State Estimation Experiments .....................................................159
Defining Dynamic Estimation Experiments ...........................................................161
Resetting Estimation Experiments.......................................................................163
Accessing Results of Estimation Simulations..............................................................164
Accessing Estimated Variables' Values.................................................................164
Accessing Standard Errors .................................................................................165
Testing for Standard Error Results ......................................................................165
Accessing Individual Correlation Results ..............................................................166
Accessing the Correlation Matrix.........................................................................166
Testing for the Correlation Matrix .......................................................................167

5 SYNCHRONOUS AND ASYNCHRONOUS SIMULATION RUNS ......................169

Contents 5
Using Synchronous Runs ........................................................................................169
Synchronous Run Example ................................................................................169
Using Asynchronous Runs ......................................................................................170
Asynchronous Run Example ...............................................................................171

6 USING THE ASPEN MODELER TYPE LIBRARIES.........................................173


Referencing a Type Library from a Microsoft Visual Basic Project ..................................173
Using the Object Type Names in Your Code...............................................................173

7 SOLVER PROPERTIES DIALOG BOX............................................................175


Diagnostics Tab ....................................................................................................175
Tearing Tab..........................................................................................................178
Tolerances Tab .....................................................................................................182
Integrator Tab ......................................................................................................187
Migrating from 11.1 Integrators to 12.1 Integrators ..............................................188
Integrator Tab: Explicit Euler .............................................................................190
Integrator Tab:Runge Kutta 4 ............................................................................191
Integrator Tab: ImpEuler (11.1).........................................................................191
Integrator Tab: Implicit Euler.............................................................................192
Integrator Tab: VSIE (11.1)...............................................................................193
Integrator Tab: Gear(11.1)................................................................................196
Integrator Tab: Gear ........................................................................................200
Integrator Solver Options ..................................................................................200
Event Handling ................................................................................................203
Diagnostics .....................................................................................................204
Linear Solver Tab ..................................................................................................205
Linear Solver Tab: MA48 ...................................................................................205
Linear Solve Tab: MA38 ....................................................................................207
Linear Solver Tab: MA28 ...................................................................................212
Non-Linear Solver Tab ...........................................................................................212
Non-Linear Solver Tab: General .........................................................................213
Non-Linear Solver Tab: Diagnostics ....................................................................215
Non-Linear Solver Tab: Tolerances .....................................................................216
Non-Linear Solver Tab: Open NLA Solver .............................................................218
Optimizer Tab.......................................................................................................219
Optimizer Tab Reporting Level ...........................................................................219
Homotopy Tab ......................................................................................................219
Homotopy Options ...........................................................................................220
Estimator Tab.......................................................................................................221
Estimator Tab: Least Squares ............................................................................221

Contents 6
Estimator Tab: Maximum Log Likelihood..............................................................224
Solvers for Optimization and Estimation ...................................................................224
FEASOPT ........................................................................................................225
Nelder-Mead....................................................................................................227
SRQP .............................................................................................................228
NL2SOL ..........................................................................................................230
Open NLP - reduced space.................................................................................230
Open NLP - full space .......................................................................................230
DMO ..............................................................................................................230

8 USING CALCULATION OPTIONS FOR PROPERTIES PLUS ..........................253


OPSET Option .......................................................................................................254
FREE-WATER Option ..............................................................................................254
CHEMISTRY Option................................................................................................254
TRUE-COMP Option ...............................................................................................255
HENRY-COMPS Option ...........................................................................................255
SOLU-WATER Option .............................................................................................256
KBASE Option.......................................................................................................257
MAXIT Option .......................................................................................................257
TOLERANCE Option ...............................................................................................257
RETENTION Option................................................................................................258

9 INTERFACING YOUR OWN PHYSICAL PROPERTIES ..................................259


How the Interface Communicates with Properties Plus ................................................259
Phase specific Variable Types and Property Procedures ...............................................260
Generalized Physical Properties Interface Routines.....................................................261
GPP_SETUP .....................................................................................................262
GPP_INI..........................................................................................................262
GPP_QUERY ....................................................................................................263
GPP_LOAD ......................................................................................................264
GPP_UNLOAD ..................................................................................................265
GPP_END ........................................................................................................265
GPP_OPTIONS .................................................................................................265
Entry Point Routines ..............................................................................................266
Example of Procedure Declaration with Analytic Derivatives....................................269
Example of Entry Point Routine that returns Analytic Derivatives.............................269
Example of Procedure Declaration without Analytic Derivatives ...............................272
Example of Entry Point Routine that Does Not Return Analytic Derivatives ................272
Linking Property Procedure Types to Subroutines.......................................................274

Contents 7
Property Procedures with Analytic Derivatives ......................................................274
Property Procedures Without Analytic Derivatives .................................................275
Definition of GPPI Entry Points ................................................................................276
pAct_Coeff_Liq ................................................................................................276
pBubt .............................................................................................................277
pCond_Liq.......................................................................................................277
pCond_Vap .....................................................................................................278
pCp_Mol_Liq....................................................................................................278
pCp_Mol_Vap ..................................................................................................279
pCv_Mol_Liq....................................................................................................280
pCv_Mol_Vap ..................................................................................................281
pDens_Mass_Liq ..............................................................................................281
pDens_Mass_Sol ..............................................................................................282
pDens_Mass_Vap .............................................................................................282
pDens_Mol_Liq ................................................................................................283
pDens_Mol_Sol ................................................................................................284
pDens_Mol_Vap ...............................................................................................284
pDewt ............................................................................................................285
pDiffus_Liq......................................................................................................286
pDiffus_Vap ....................................................................................................286
pEnth_Mol.......................................................................................................287
pEnth_Mol_Liq .................................................................................................287
pEnth_Mol_Sol.................................................................................................288
pEnth_Mol_Vap................................................................................................289
pEntr_Mol .......................................................................................................289
pEntr_Mol_Liq .................................................................................................290
pEntr_Mol_Sol .................................................................................................291
pEntr_Mol_Vap ................................................................................................291
pFlash ............................................................................................................292
pFlashPH ........................................................................................................293
pFlashPV.........................................................................................................293
pFlashTH ........................................................................................................294
pFlashTV.........................................................................................................295
pFlash3 ..........................................................................................................296
pFlash3PH.......................................................................................................297
pFlash3PV .......................................................................................................298
pFlash3TH.......................................................................................................299
pFlash3TV .......................................................................................................300
pFuga_Liq .......................................................................................................301
pFuga_Sol.......................................................................................................302
pFuga_Vap......................................................................................................302
pGibbs_Mol_IDLGAS.........................................................................................303

Contents 8
pGibbs_Mol_Liq ...............................................................................................303
pGibbs_Mol_Sol ...............................................................................................304
pGibbs_Mol_Vap ..............................................................................................305
pKllValues .......................................................................................................305
pKValues ........................................................................................................306
pMolweight .....................................................................................................307
pMolweights ....................................................................................................307
pSurf_Tens .....................................................................................................308
pSurf_TensY....................................................................................................308
pTrueComp .....................................................................................................309
pTrueCmp2 .....................................................................................................310
pTrueCmpVLS..................................................................................................310
pVap_Pressures ...............................................................................................311
pVisc_Liq ........................................................................................................311
pVisc_Vap .......................................................................................................312
Fortran Programmer's Checklist ..............................................................................312
Installing the Physical Properties Interface................................................................313

10 USING THE CONTROL DESIGN INTERFACE (CDI)....................................314


How CDI Works ....................................................................................................314
About DAE Models ............................................................................................315
About Linear Models .........................................................................................315
How CDI Produces Linearized Models ..................................................................316
Relative Gain Array (RGA) .................................................................................316
Niederlinski Index (NI)......................................................................................317
Morari Resiliency Index (MRI) ............................................................................317
State Transition Matrix (STM) ............................................................................317
Creating CDI Automation Scripts .............................................................................318
Syntax for CDI Automation Scripts .....................................................................319
Example of Creating a CDI Script .......................................................................319
CDI Output Files ...................................................................................................320
ASCII DAT Format............................................................................................320
About the CDI .lis File .......................................................................................321

11 ESTIMATION ..........................................................................................328
Mathematical Statement of Flowsheet Equations........................................................328
About Experimental Data .......................................................................................329
About Parameter Estimation Methods.......................................................................329
About Least Squares Parameter Estimation ...............................................................330
About Log Likelihood Estimation .........................................................................330

Contents 9
12 USING THE SIMULATION ACCESS EXTENSIONS .....................................332
Writing a DLL Function for the Simulation Access eXtension ........................................333
Using Variable Accessing Functions .....................................................................333
Using Return Codes ..........................................................................................334
Events in Simulation Access eXtensions...............................................................335
Controlling the Simulation Access eXtensions ............................................................337
Specifying the Simulation Access eXtensions Input and Output Variables..................337
Specifying the DLL and Function Name for the Simulation Access eXtensions ............338
Additional Simulation Access eXtensions Functions.....................................................338
Simulation Access eXtensions Attribute Tokens.....................................................341

13 USING ONLINE LINKS (OLL) ..................................................................343


Installing the Data Server for OLL ...........................................................................343
Specifying the Data Server Configuration for OLL.......................................................344
Specifying the Links between the Simulator and the OLL Data Server ...........................346
Adding New Links for OLL..................................................................................348
Removing OLL Links .........................................................................................349
Changing the Simulation Variable in an OLL Link...................................................349
Browsing for OLL Tags ......................................................................................349

14 USING EXTERNAL SOLVERS....................................................................351

15 EXPORTING FLOWSHEETS TO ASPEN PLUS ............................................352


Software and Hardware Requirements .....................................................................352

16 PREPARING AN ASPEN MODELER FLOWSHEET FOR EXPORT .................353


Preparing a Flowsheet for Export .............................................................................353
Making the Flowsheet Square.............................................................................354
Ensuring the Flowsheet has a Rating Specification.................................................354
Defining Ports for Connecting to Aspen Plus Material Streams .................................355
Ensuring the Flowsheet Solves in Steady-State Mode ............................................357
Preparing a Flowsheet That Uses Custom Models .......................................................358
Adding Custom Feed and Product Blocks..............................................................358
Adapting the Example Models ............................................................................358
Preparing an Aspen Dynamics Flowsheet for Export....................................................359
Exporting an Aspen Modeler Flowsheet.....................................................................361

17 USING AN EXPORTED FLOWSHEET IN ASPEN PLUS ................................364


Using an Aspen Modeler Flowsheet in Aspen Plus .......................................................364

Contents 10
Modifying an Exported Flowsheet.............................................................................364
Licensing of Exported Flowsheets ............................................................................365
Distributing the Exported Flowsheet to Aspen Plus Users.............................................365

18 USING MODELS IN OTHER APPLICATIONS .............................................367


Building Custom Unit Operation Models for Aspen Plus and HYSYS ...............................367
Software and Hardware Requirements.................................................................368
Creating a Unit Operation Model for Aspen Plus and HYSYS .........................................368
Creating the Model ...........................................................................................369
Exporting the Model .........................................................................................375
Installing the Model using Windows Explorer ........................................................376
Using an Aspen Modeler Unit Operation Model in Aspen Plus or HYSYS..........................377
Using an Aspen Modeler Model in Aspen Plus........................................................377
Using an Aspen Modeler Model in HYSYS .............................................................377
Configuring an Aspen Modeler Unit Operation Block In Aspen Plus ...........................378
Configuring an Aspen Modeler Unit Operation Block In HYSYS.................................379
Licensing Exported Models Running in Aspen Plus .................................................380
Licensing Exported Models Running in HYSYS .......................................................380
Distributing an Exported Model To Aspen Plus Users..............................................380
Distributing an Exported Model To HYSYS Users ...................................................380
Using the MyPipe Model in HYSYS .......................................................................381

19 ASPEN CUSTOM MODELER LANGUAGE FILE ............................................382


Version ...........................................................................................................383
Libraries .........................................................................................................383
<Global Definitions> ........................................................................................383
<Type Definitions> ..........................................................................................383
<Plot and History Table Definitions>...................................................................384
Flowsheet ............................................................................................................384
StructureContainer ...........................................................................................384
<Blocks, Stream and Connection Statements>.....................................................385
CONSTRAINTS .................................................................................................385
Task <name>..................................................................................................385
ActiveTasks .....................................................................................................386
<Flowsheet Assignments> ................................................................................386
Graphics .........................................................................................................386
HIERARCHY <name>........................................................................................386
Properties .......................................................................................................387
Options...........................................................................................................388
Optimization....................................................................................................393
Estimation.......................................................................................................394

Contents 11
Homotopy .......................................................................................................394
SimulationAccessExtensions ..............................................................................395
Snapshot <name> ...........................................................................................395

GENERAL INFORMATION..............................................................................397
Copyright.............................................................................................................397
Related Documentation..........................................................................................399

TECHNICAL SUPPORT...................................................................................400
Online Technical Support Center .............................................................................400
Phone and E-mail..................................................................................................401

INDEX ..........................................................................................................402

Contents 12
Contents 13
Introducing Aspen Custom
Modeler

Aspen Custom Modeler (ACM) is an easy-to-use tool for creating, editing and
re-using models of process units. You build simulation applications by
combining these models on a graphical flowsheet. Models can use inheritance
and hierarchy and can be re-used directly or built into libraries for distribution
and use. Dynamic, steady-state, parameter estimation and optimization
simulations are solved in an equation-based manner which provides flexibility
and power.
ACM uses an object-oriented modeling language, editors for icons and tasks,
and Microsoft Visual Basic for scripts. ACM is customizable and has extensive
automation features, making it simple to combine with other products such as
Microsoft Excel and Visual Basic. This allows you to build complete
applications for non-experts to use.

Introducing Aspen Custom Modeler 14


1 Using Automation and
Visual Basic

You can use Microsoft Visual Basic (VB) and automation to control and
define a simulation either from:
• Scripts that use Microsoft® Visual Basic® scripting
• External Microsoft® Visual Basic® applications, such as Microsoft® Visual
Basic® 5.0 Control Creation Edition (CCE), Microsoft® Visual Basic® 5.0
or 6.0 Professional or Enterprise editions, or Microsoft® Visual Basic® for
Applications (VBA) as supplied with Microsoft® Office applications, such as
Microsoft® Excel and Microsoft® Word.
In both cases, you use automation methods and properties to control the
simulation.
You can also choose whether control returns to Microsoft® Visual Basic® only
when the simulation run finishes, or immediately.

Note: Microsoft and Visual Basic are registered trademarks of


Microsoft Corporation.

Automatically Run Script


Events
When certain events occur in the application an automation script will be run.
These scripts should be contained in files located in the installation directory
for the application.
By default this is in:
C:\ProgramFiles\AspenTech\Aspen Custom Modeler 12.1\bin
The scripts should be placed in files will specific names so the application can
find them.
These are:
• OnNewDocumentScript.vb
• OnPreOpenDocumentScript.vb
• OnPostOpenDocumentScript.vb

1 Using Automation and Visual Basic 15


• OnSaveDocumentScript.vb
• OnCloseDocumentScript.vb
The scripts in these files will be called when opening closing and saving
documents.
New
When you start up the application or select to create a New document in the
GUI the script files OnNewDocumentScript.vb and
OnPostOpenDocumentScript.vb are called.
Open
When you open up the application by double clicking on an .acmf file or select
to open a document in the GUI the script files OnNewDocumentScript.vb,
OnPreOpenDocumentScript.vb and OnPostOpenDocumentScript.vb are called.
Save As
The script OnSaveDocumentScript.vb is called when you select Save As in the
GUI.
Close
The script OnCloseDocumentScript.vb is called when a document is closed
either by leaving the application or by opening or creating a different
document.

Handling Errors
When an ACM method or property fails a Visual Basic error is raised. This can
be handled using the Visual Basic “On Error” command. If no On Error
command is given the Visual Basic program will terminate. When an error is
raised the Visual Basic Err object can be used to obtain information about the
error. Note that for scripts in ACM the statement On Error Resume Next must
be used, On Error Goto cannot be used.
Example in Visual Basic

Sub RunTestSimulation()
Dim ACMobj As AspenModelerSimulation ' Available in the
ACM type library
Set ACMobj = GetObject("d:\test.acmf")
ACMobj.Application.Visible = True

On Error Resume Next


ACMobj.Run (True)
If Err.Number <> 0 Then
' got an error
MsgBox "Error " & Err.Number & " : " & Err.Description

1 Using Automation and Visual Basic 16


Err.Clear
End If
On Error GoTo errorhandler
If ACMobj.Successful Then
MsgBox "last run was successful."
Else
MsgBox "last run was not successful."
End If
Exit Sub

errorhandler:
MsgBox "default error handler."

End Sub
In this example if an error is raised by the Run command On Error Resume
Next will cause the next statement to be executed. An Err.Number value
other than 0 indicates an error has occurred. Note that an On Error GoTo
statement could have been used to handle the error in the Run command.
Refer to the Visual Basic help for more information.

Working with Sets


ACM gives access to some data via sets of objects.
Examples of these are:
• Components in a component list are accessed as a set of strings
• Sets of variables can be accessed
• The value of some variables can be sets of strings, reals or integers
Sets can be retrieved via methods on their owning objects:
e.g.:
Set MyVars = B1.FindMatchingVariables(“~”)
will retrieve all variable objects from the block B1.

Set MyComponentList =
Application.Simulation.Properties.
ComponentList("CompList").Components
retrieves the components in a component set.
Alternatively new sets can be created in a script using the following methods:
• NewVariableSet

1 Using Automation and Visual Basic 17


• NewStringSet
• NewIntegerSet
e.g.:

Set MyVarSet = B1.NewVariableSet


This creates an empty variable set.
Once a set has been obtained the following methods can be used to
manipulate the contents:

AddValues item1, item2,…


This can be used to add values to the set. The arguments can be single values
or sets of the correct type:
e.g.:

MyVarSet.AddValues Varset1, Varset2, B1.Temp


This adds the contents of the set Varset1 and Varset2 as well as the variable
B1.Temp to the set MyVarSet.

RemoveValues item1, item2,…


This can be used to remove values from the set. Not available for variable
sets:
e.g.:

MyComponentList.RemoveValues “H2O”
Note that manipulating the set will have no affect until the set is used:
e.g.:

Set Application.Simulation.Properties.
ComponentList("CompList").Components =
MyComponentList
This replaces the existing component list with the contents of the set
MyComponentList:

e.g. UpdateVariables MyVarSet


This updates values in the ACM client for all variable in the set. It improves
performance when values are accessed for these variables.
Elements of a set can be accessed using the For Each Syntax
e.g.:

For Each Var in MyVarSet


Application.msg Var.Name

1 Using Automation and Visual Basic 18


Next
This prints out the names of each variable in the set.
Refer also to Working with Set Attributes and ComponentList.Components.

1 Using Automation and Visual Basic 19


2 Controlling Simulations
with Scripts

A script is a set of instructions written in Microsoft® Visual Basic® Scripting


Edition (VBScript) that automates the setup and control of a simulation. You
can write your own scripts or generate them from the Status window or from
Variable Find.
You can use scripts to:
• Automate and record actions on models and flowsheets, which enables
you to automate specification and initialization.
• Control sequences of simulation runs using automation methods and
properties. For example, you can use scripts to run scripts from within
scripts, apply snapshots to a simulation, set the run mode, launch forms,
and set solver options for a simulation.
• Define estimation simulations.
• Define units of measurement sets and conversions.
• Obtain inputs and outputs.
• Call external applications.
Microsoft® Visual Basic® Scripting Edition (VBScript) is supplied
automatically with your installation.

Important Note: Do not confuse scripts with tasks. Scripts are


used to set up a simulation. In contrast, tasks are used to define
a sequence of actions that take place during a dynamic
simulation. For more information on tasks, see the Modeling
Language Reference, Defining Tasks.

From scripts, the top level of the object path can be one of:
• Application
• Flowsheet
• ActiveDocument
Note the following Microsoft® Visual Basic® conventions:

Convention Meaning
' Comment marker
_ Continuation marker

2 Controlling Simulations with Scripts 20


This chapter includes:
• Syntax for variable assignments in scripts.
• Examples of variable assignments in scripts.
• Tips on making faster scripts.
• Information on passing inputs to scripts and getting outputs from scripts.

Note: If you receive an unhandled exception message while a


script is running, you may need to quit your Aspen Modeler
product and start it again. This is because the Microsoft® Visual
Basic® engine can become unusable after an unhandled
exception. The only way to resolve this situation is to restart the
Visual Basic engine by restarting the Aspen Technology user
interface.

Examples of Object Paths


Application for run time settings:
Application.Simulation.RunMode = "Dynamic"
Flowsheet for the variable assignment:
Flowsheet.Tank1.Flowin.Flow.Spec = "Fixed"
In the following example, Application.Simulation is used to set the run mode:
Application.Simulation.RunMode = "Initialization"
The preceding example is equivalent to:
ActiveDocument.RunMode = "Initialization"
The path ActiveDocument is equivalent to the path Application.Simulation.

About Microsoft Visual Basic Scripting Edition


For basic applications such as automating specification for defining parameter
and variable properties, that is, spec, value, upper and lower limits, you do
not need to learn VBScript. However, learning VBScript gives you access to
powerful features such as calling scripts within scripts and launching an
external Windows application such as a Microsoft® Excel spreadsheet or
Microsoft® Visual Basic® application.
You can obtain documentation on the more powerful features of VBScript
from the Microsoft® web site.

Note: Microsoft®, and Visual Basic® are registered trademarks of


Microsoft Corporation.

Syntax for Scripts


The syntax for variable assignments in a flowsheet is:

2 Controlling Simulations with Scripts 21


BlockName.VariableName.Property = value
The syntax for variable assignments in a model is:
VariableName.Property = value
For properties whose values are strings, place the strings within quote marks.

Examples of Scripts
The following two example scripts show how to:
• Set up initial conditions for a flash system.
• Initialize an array variable, change the upper bound of a variable, and set
run mode to dynamic.

Example of Setting Up Initial


Conditions for a Flash System
The following script shows how to set up the initial conditions for a flash
system:
'Initial conditions - state variables initialized
FLASH1.E.Spec="Initial"
FLASH1.E.Value=0.964186
FLASH1.Mc("BENZENE").Spec="Initial"
FLASH1.Mc("BENZENE").Value=8.41653
FLASH1.Mc("OXYLENE").Spec="Initial"
FLASH1.Mc("OXYLENE").Value=12.2439
FLASH2.E.Spec="Initial"
FLASH2.E.Value=0.231459
FLASH2.Mc("BENZENE").Spec="Initial"
FLASH2.Mc("BENZENE").Value=1.31776
FLASH2.Mc("OXYLENE").Spec="Initial"
FLASH2.Mc("OXYLENE").Value=6.06461
'Variables fixed and free to provide consistent
specifications
FLASH1.M.Spec="Free"
FLASH1.M.Value=30.
FLASH1.P_drop.Spec="Free"
FLASH1.P_drop.Value=0.1
FLASH2.M.Spec="Free"
FLASH2.M.Value=10.

2 Controlling Simulations with Scripts 22


FLASH2.P_drop.Spec="Free"
FLASH2.P_drop.Value=0.1

Example of Initializing an Array


Variable, Changing the Upper Bound of
a Variable, and Setting the Run Mode
to Dynamic
The following example shows how to initialize an array variable, change the
upper bound of a variable, and set run mode to dynamic:
Application.Simulation.RunMode = "Dynamic"
Bed.TempIn.Upper = 800
dim i
for i = 1 to 20
Bed.Tg(I).spec = "initial"
Bed.Tg(I).value = 600
Bed.Ts(I).spec = "initial"
Bed.Ts(I).value = 600
next

Note: To define the run mode, you could use ActiveDocument


instead of Application.Simulation.

Calling External Applications


You can call external applications from scripts.

Examples of Calling an External Application


The following example shows opening a Microsoft® Excel spreadsheet from a
script:
Dim xlObj
Set xlObj = GetObject("\directory\sheet.xls",
"Excel.Sheet")
xlObj.Application.Visible = True
' Makes windows visible
xlObj.Application.Windows("sheet.xls").Activate
' Makes the new worksheet visible

2 Controlling Simulations with Scripts 23


Improving the Speed of Visual
Basic Scripts
When you run a Microsoft® Visual Basic® script within the user interface,
each statement is acted upon on a line-by-line basis. This means that any
structural changes you make in a script that alters a flowsheet block
parameter causes the simulation to be re-evaluated each time a statement is
made.
Quite often for a large flowsheet, you need to alter block parameters for
several independent blocks. Each time you make a change to one block, the
whole simulation is re-evaluated.
To make scripts in which you change several parameters run faster, you need
to change the way script statements are interpreted. You can force the script
to batch process structural changes so that all the changes to the simulation
equations are made at one time.
The following commands enable you to affect the way scripts are interpreted:
• DisableIncrementalUpdate
• EnableIncrementalUpdate
DisableIncrementalUpdate and EnableIncrementalUpdate operate on a lock
counter which is incremented by DisableIncrementalUpdate and decremented
by EnableIncrementalUpdate. This allows scripts called within scripts to use
Disable or EnableIncrementalUpdate without overriding the lock on
incremental updating that may have been established in the calling script.

For scripts that run The lock count is controlled by


Within an Aspen Modeler Automatically checking that the lock
product count is restored to its initial condition,
when the script completes.
From external Visual Basic Ensuring that the number of calls to
DisableIncrementalUpdate are matched
by an equal number of calls to
EnableIncrementalUpdate.

DisableIncrementalUpdate Command
The incremental update command is enabled by default, which means that
each line of a script in acted upon as it is interpreted. By entering the
automation method command DisableIncrementalUpdate, you change the
way script commands are acted upon.
After you enter the command DisableIncrementalUpdate, all parameter
changes are stored and applied either when the script finishes, or when the
command EnableIncrementalUpdate is encountered. In general, it is better to
pair DisableIncrementalUpdate and EnableIncrementalUpdate commands,
rather than relying on the end of a script to re-enable the default setting.

2 Controlling Simulations with Scripts 24


Example of DisableIncrementalUpdate
The following script uses DisableIncrementalUpdate to store all the changes
made to all the blocks on the flowsheet until the EnableIncrementalUpdate
command:
'Change the specifications of a series of columns
DisableIncrementalUpdate
C1.Ntrays = 21
C2.Ntrays = 48
C3.Ntrays = 16
C4.Ntrays = 17
EnableIncrementalUpdate
'End of script
If you do not disable incremental updates, the simulation equations are re-
evaluated four times. When you use DisableIncrementalUpdate, the equations
are re-evaluated once.

EnableIncrementalUpdate Command
The EnableIncrementalUpdate command is used to re-enable the default
action of the scripts, where each line is acted upon as it is interpreted. Usually
the EnableIncrementalUpdate command is made after the
DisableIncrementalUpdate command and several structural statements.
You can use EnableIncrementalUpdate to force the changes to be made since
the previous DisableIncrementalUpdate command during a script.

Example of EnableIncrementalUpdate
The following example script uses EnableIncrementalUpdate to force the
changes made in the previous line to be acted upon at that point. Thereafter,
all lines are acted on as they are interpreted:
'Change the specifications of a series of columns
'Then initialize the simulation
DisableIncrementalUpdate
C1.Ntrays = 21
C2.Ntrays = 48
C3.Ntrays = 16
C4.Ntrays = 17
EnableIncrementalUpdate
FeedStream.F = 10.0
Application.Simulation.RunMode = "Steady State"
Application.Simulation.Run(True)

2 Controlling Simulations with Scripts 25


Application.Simulation.RunMode = "Dynamic"
Application.Simulation.Run(False)
' End of script
If you do not enable incremental updates, both runs do not use the updated
values of the number of trays in the column. This is because, if you do not
use the EnableIncrementalUpdate command, the changes to the structure of
the simulation are made when the script finishes, which is after the two
simulation runs made by the script. In this example, if you do not use
EnableIncrementalUpdate, you do not converge the simulation with the
specification you have defined.

Passing Inputs to Scripts and


Getting Outputs from Scripts
If a script is invoked with arguments, these will be exposed in the called script
as a collection of variants called Inputs. This is a conventional collection
supporting a Count & item and iteration using the For Each syntax.
For example, a script called "CallableScript" is written, with the following text:
application.msg " Input count = " & Inputs.count
for each arg in inputs
application.msg " " & arg
next
It can then be passed arguments like a conventional method, for example:
call CallableScript("arg1", 10.5)
This would print the following in the Simulation Messages window:
Input count = 2
arg1
10.5
A script can also return outputs, using a second variant collection called
Outputs. This is the same type of object as the inputs collection. When a
script is invoked, the Outputs collection is initially empty. To size it, you
assign a value to the Count property.
The following script, called SumInputs, sums its inputs and returns the result
in the output collection:
outputs.count=1
outputs(1) = 0

for each arg in Inputs


outputs(1) = outputs(1) + arg

2 Controlling Simulations with Scripts 26


next
The outputs collection will be returned as the result of the script, so an
invocation of the script looks like this:
set results = SumInputs(1,2,3.5)
application.msg "Sum of inputs = " & results(1)

Automatically Run Event


Scripts
When certain events occur in the application an automation script will be run.
These scripts should be contained in files located in the installation folder for
the application.
By default this is in:
C:\ProgramFiles\AspenTech\AMSystem 12.1\bin
The scripts should be placed in files will specific names so the application can
find them.
These are:
• OnNewDocumentScript.vb
• OnPreOpenDocumentScript.vb
• OnPostOpenDocumentScript.vb
• OnSaveDocumentScript.vb
• OnCloseDocumentScript.vb
The scripts in these files will be called when opening closing and saving
documents.
New
When you start up the application or select to create a New document in the
GUI the script files OnNewDocumentScript.vb and
OnPostOpenDocumentScript.vb are called.
Open
When you open up the application by double clicking on an .acmf file or select
to open a document in the GUI the script files OnNewDocumentScript.vb,
OnPreOpenDocumentScript.vb and OnPostOpenDocumentScript.vb are called.
In addition the Open Document event will run a script called
OnLoadSimulation located under the Flowsheet in the simulation being
loaded. This allows you to make changes that are specific to the simulation
being loaded e.g. simulation specific units of measurements and screen
layouts. This script is run after the OnPostOpenDocumentScript.vb script.
Save As
The script OnSaveDocumentScript.vb is called when you select Save As in the
GUI.
Close

2 Controlling Simulations with Scripts 27


The script OnCloseDocumentScript.vb is called when a document is closed
either by leaving the application or by opening or creating a different
document.

2 Controlling Simulations with Scripts 28


3 Controlling Simulations
with External Visual Basic

You need to define a variable to refer to the simulation document, that is, the
file created by your Aspen Modeler product, (for example, Aspen Custom
Modeler® or Aspen Dynamics™), so that you can access the automation
methods from your external Microsoft® Visual Basic®.
Aspen Modeler type libraries are available for use in external Microsoft®
Visual Basic® applications. Using these type libraries will improve the
efficiency of your code and provide helpful prompts, giving available method
and property names. For more information see Chapter 6.
This chapter describes how to:
• Create an instance of the application.
• Obtain access to objects.
• Use a simulation variable to run a simulation.
• Check whether the simulation completed successfully.
• Save and exit the application.
• Run multiple simulations.
• Use the GetObject method.

Note: Previous versions of the Automation documentation


advocated the use of the GetObject() routine to obtain access to
simulation documents. Although GetObject() is still supported,
the use of the Application methods described in this section is
now the preferred approach, in that the methods provide
additional functionality and are more compliant with recent
developments in.

Automation architecture. Consequently you should use GetObject only for


accessing a simulation that is already running, as described in the GetObject
section.

3 Controlling Simulations with External Visual Basic 29


Creating an Instance of an
Application Object
To create an instance of an application object, use the following syntax:
Dim AppName as Object
Set AppName = CreateObject("Application")
AppName.Visible=Value

AppName Name you give to the object variable, for example,


ACMApp, ADApp, ADSApp, ChmApp.
Application Can be one of:
ACM Application Aspen Custom Modeler
AD Application Aspen Dynamics
ADS Application Aspen Adsim
Chm Application Aspen Chromatography
AppName.Visible Determines whether or not the application is visible

Value Can be one of:


FALSE Object is invisible (default)
TRUE Object is visible

Example of Creating an Instance of an


Application Object
The following example defines the necessary Aspen Custom Modeler®
objects, and makes it visible:
Dim ACMApp As Object
Dim ACMDocument As Object
Dim ACMSimulation As Object
Set ACMApp = CreateObject("ACM Application")
ACMApp.Visible = True

Creating an Instance of an Application


Object for a Specified Product Version
When more than one version of the product is installed on your machine
simultaneously, you may want to specify which version is invoked under
automation.
The general syntax for this is:
Dim AppName as Object
Set AppName = CreateObject("Application")
AppName.Visible=Value

"Application" The product name and a version number. The version

3 Controlling Simulations with External Visual Basic 30


number consists of the major version and minor
version numbers run together to make a four digit
number.

Example of Creating an Instance of an Application Object for a


Specified Product Version
The following is an example of creating an instance of an application object
for a specified product version:
' launch version 12.1 of ACM
Set AppName = CreateObject("ACM Application 1210")

Note: Product versions 10.0 and earlier cannot be started using


this syntax.

Accessing Simulation and


Document Objects
To handle simulation documents, the application object can use the following
methods:
• NewDocument
• OpenDocument
• CloseDocument
• SaveDocument
• SaveDocumentAs
An application can have zero or one documents open at any given time
(initially zero) and each document corresponds to one simulation flowsheet.
After you obtain an application variable, you would typically open an existing
simulation document using the OpenDocument method:
Dim ATDocument as Object
Set ATDocument=AppName.OpenDocument("path")

path Full path name and file name of the existing simulation
document you want to open, for example:
d:\acm_simulations\tower.acmf

After a simulation document has been opened, you can ask the application for
access to the simulation it represents:
Dim ATSimulation as Object
Set ATSimulation=AppName.Simulation

Important Note: You ask the application, not the document, for
the simulation. Because there is never more than a single
simulation open at once within a single executable session, the

3 Controlling Simulations with External Visual Basic 31


application knows which document contains the simulation.

The simulation object has properties and methods pertaining to the


simulation, including:
• RunMode
• Time
• Run
• Step
• Reset
• Restart

Example of Accessing Objects


The following example shows how to obtain access to objects by opening an
Aspen Custom Modeler® simulation document, specifying the path to the
document, and getting a variable which points to the simulation:
Set ACMDocument = ACMApp.OpenDocument("d:\acm
simulations\tower.acmf")
Set ACMSimulation = ACMApp.Simulation

Using a Simulation Variable to


Run a Simulation
You can use the simulation variable to run the simulation:
ATSimulation.RunMode="Mode"
ATSimulation.Run(value)

value Can be one of:


True Control returns to Visual Basic after the
simulation has completed
False Control returns to Visual Basic immediately
For more information, see Chapter 5.
Mode Can be one of:
Steady State
Optimization
Estimation
Dynamic
Initialization

As is normal in Visual Basic, you do not need to explicitly create a variable for
the simulation, and could instead have written:
AppName.Simulation.RunMode="Mode"
AppName.Simulation.Run(value)

3 Controlling Simulations with External Visual Basic 32


Example of Using a Simulation
Variable to Run a Simulation
The following Aspen Custom Modeler® example sets the run mode to steady
state, runs the simulation and waits for it to complete:
ACMSimulation.RunMode = "Steady State"
ACMSimulation.Run (True)

Checking the Simulation


After the simulation has completed, you can check whether it completed
successfully and take action accordingly:
if ATSimulation.Successful then
msgBox "Simulation Complete"
else
msgBox "Simulation Failed"
endif

Saving Changes and Closing the


Application
After a simulation has completed and you have checked whether it was
successful, you can save any changes to disk and close down the application:
AppName.SaveDocument()
AppName.quit()

AppName.SaveDocument() Save the changes to disk


AppName.quit() Exit the application

Example of Using External


Visual Basic
The following example shows the complete code for using external Visual
Basic® to load and run an Aspen Custom Modeler® simulation:
Dim ACMApp As Object
Dim ACMDocument As Object
Dim ACMSimulation As Object
Set ACMApp = CreateObject("ACM Application")
' Use "ACM Application" for aspen custom modeler,

3 Controlling Simulations with External Visual Basic 33


' Use "AD Application" for Aspen Dynamics
ACMApp.Visible = True
' Now that we have access to the app we can obtain
' other useful objects. First open a simulation document
Set ACMDocument = ACMApp.OpenDocument("d:\acm
simulations\tower.acmf")
' Substitute the path with one that exists on your machine.
' Get a variable which points to the simulation
Set ACMSimulation = ACMApp.Simulation
' Set the run mode to steady state
ACMSimulation.RunMode = "Steady State"
' Run the simulation and wait for it to complete
ACMSimulation.Run (True)
' Check whether it worked
If ACMSimulation.Successful Then
MsgBox "Simulation Complete"
Else
MsgBox "Simulation Failed"
End If
' Save the changes
' and shut down the ACM application
ACMApp.SaveDocument()
ACMApp.quit

Running Multiple Simulations


You can use a single invocation of the Aspen Modeler server to run many
different simulations.

Example of Running Multiple


Simulations
The following code could be used to run six Aspen Custom Modeler®
simulations, assuming the folder "d:\acm simulations" contains six simulation
files: test1.acmf, test2.acmf, to test6.acmf :
Option Explicit
Public Sub RunSimuls()

3 Controlling Simulations with External Visual Basic 34


Dim ACMApp As Object
Dim ACMSimulation As Object
Dim nFileNumber As Integer
Dim sFileName As String
nFileNumber = 0
On Error GoTo ErrorHandler
Set ACMApp = CreateObject("ACM Application")
ACMApp.Visible = True
For nFileNumber = 1 To 6
sFileName = "d:\acm simulations\test" & CStr(nFileNumber)
& ".acmf"
ACMApp.OpenDocument (sFileName)
Set ACMSimulation = ACMApp.Simulation
' set the run mode to Initialization
ACMSimulation.RunMode = "Initialization"
' and run the simulation, waiting for it to complete
ACMSimulation.Run (True)
ACMApp.CloseDocument (True) ' save changes
Next nFileNumber
' and shut down the ACM application
ACMApp.quit
Exit Sub
'
'
ErrorHandler:
' Error handling might normally be more sophisticated than
this
MsgBox "Error at simulation " & nFileNumber & " " &
Err.Description
Exit Sub
End Sub

Using the GetObject Method


Normally, you use the OpenDocument method of the Application automation
object to gain access to a simulation in stored file form (for example, an
.acmf,.acmd,.dynf or .dynd file).

3 Controlling Simulations with External Visual Basic 35


However, sometimes it is more convenient to use the Visual Basic®
GetObject method, for example, when you want to connect to a simulation
that is already running. The syntax for defining an object name for an Aspen
Modeler product is:
Set MyObject = GetObject("Filename.extension" , "Class")

MyObject An object variable name that you define using a DIM


statement
Filename.extension Either the name of an existing Aspen Modeler product
file or an empty string, in which case the class is
Compulsory.
Class Name describing the type of object. Optional if you
have included an existing file name, compulsory if you
have not included an existing file name

The following classes are available to GetObject:

File extension Class name


.acmf Aspen Custom Modeler Language
.acmd Aspen Custom Modeler Document
.dynf Aspen Dynamics Language
.dynd Aspen Dynamics Document
.ada Aspen Adsim Language
.adb Aspen Adsim Document
.cra Aspen Chromatography Language
.crb Aspen Chromatography Document
.bspf Aspen BatchSep Language
.bspd Aspen BatchSep Document
.auf Aspen Utilities Language
.aud Aspen Utilities Document
.awf Aspen Water Language
.awd Aspen Water Document

Example of Using GetObject


The following line of VBA shows an example of running GetObject as a
Microsoft® Excel macro:
Set Mysim = GetObject("C:\Program Files\AspenTech\Aspen Cus
tom Modeler 12.1\Examples\5Tank\fivetank.acmf")
Mysim.Application.Visible = True
Mysim.Run True
If Aspen Custom Modeler® is already running the simulation, a link to the
running instance will be returned. If it is not already running, Aspen Custom
Modeler will be started and the simulation loaded. In either case, the
simulation is then run.

3 Controlling Simulations with External Visual Basic 36


4 Automation Methods and
Properties

Methods are commands that you can use to control the simulation. Properties
contain values that you can read and/or write.
This chapter contains information on automation methods and properties.
The following diagram shows the relationship between the objects and
collections within Aspen Modeler products:

4 Automation Methods and Properties 37


List of Properties that Return Objects
The following properties all return references to objects:

Property Returns
Application The one and only Application object
Application.Simulation The one and only Simulation object
Application.ActiveDocument The one and only ActiveDocument object
Application.Simulation. The one and only Flowsheet object

4 Automation Methods and Properties 38


Flowsheet
Application.Simulation. Collection of blocks within the flowsheet
Flowsheet.Blocks
Application.Simulation. Collection of streams within the flowsheet
Flowsheet.Streams
Application.Simulation. Returns a specified object
Flowsheet.Resolve
Application.Simulation. Collection of global variables
Flowsheet.Global
Application.Simulation.CDI The one and only CDI object
Application.Simulation. Provides access to the Homotopy facility for
Homotopy automation
Application.Simulation. Provides access to the OnLine Links facility for
OnLineLinks automation
Application.Simulation. Provides access to the various run options of
Options the simulation
Application.Simulation. Provides access to the optimization facility for
Optimization automation
Application.Simulation. Provides access to methods & properties which
OutputLogger determine how run-time output is handled
Application.Simulation. Contains physical properties information
Properties
Application.Simulation. Manages snapshots and results
Results
Application.Simulation.UOM Provides the ability to manipulate Unit of
Measurement sets
Application.Simulation. An event-driven task
Flowsheet
<Taskname>

For a given block, for example, b1, the following are returned:

Property Returns
b1.Blocks Collection of blocks within block b1; equivalent to
Application.Simulation.Flowsheet.Blocks("b1").blocks
b1.Streams Collection of streams connected to block b1; equivalent to
Application.Simulation.Flowsheet.Streams("b1").streams
b1.Ports Collection of Ports within this block
b1.ControlPorts Collection of ControlPorts within this block
b1.Resolve A specified object

For a given stream, for example, s1, the following are returned:

Property Returns
s1.Blocks Collection of blocks connected to stream s1; equivalent to
Application.Simulation.Flowsheet.Blocks
s1.Streams Collection of streams within stream
s1.Ports Collection of Ports within this stream
s1.ControlPorts Collection of ControlPorts within this stream
s1.Resolve A specified object
s1.InputPort A specified object
s1.InputBlockPort A specified object
s1.OutputPort A specified object

4 Automation Methods and Properties 39


s1.OutputBlockPort A specified object

For a given port, for example, p1, the following is returned::

Property Returns
p1.Resolve A specified object

Accessing Items Within the Flowsheet


The Resolve method converts a string to a reference to an object.
If the string is constant, you do not need to use it explicitly. For example, in a
flowsheet flow containing a block b1, the following all return the same object:
From a script within Aspen Custom Modeler®:
Simulation.Flowsheet.Resolve("b1")
Simulation.Flowsheet.b1

Furthermore, the Flowsheet.blocks collection can be used to return a


reference to this object, too:
Simulation.Flowsheet.Blocks.Item("b1")

Lastly, note that the Item keyword is optional in Visual Basic® so this
expression is equivalent to:
Simulation.Flowsheet.Blocks("b1")

Using Scope in Scripts


Scripts have scope, so for example, for a script within a block b1, there is no
need to specify the full path in a script at the flowsheet level:
ports
is equivalent to:
b1.ports
To refer to this b1.ports collection from a script in another block b2, use the
following syntax:
Application.Simulation.Flowsheet.b1.ports

Accessing Variables Using the Resolve Method


The Resolve method takes a string argument and returns a reference to an
object. It can be used to access variables in any given block, stream, or the
flowsheet itself from a script anywhere in the simulation.
For example, given a simulation with two blocks, b1 and b2, from a script in
b1, you can access the variable b2.x like this:
resolve("Application.Simulation.Flowsheet.b2.x")

4 Automation Methods and Properties 40


Note: Global variables are not accessed with the Resolve
method. Instead, the syntax is, for example:

Simulation.Global.vrbname
where vrbname is the name of the required variables.
For more information on Resolve, see Resolve Method.

Table of Key Automation Objects


The following table lists the key automation objects, and their relationship
(path) from the Application object.

Name Path Relative to Description


Application
Application Application The application object.
For example, for Aspen Custom Modeler®:
In external Microsoft® Visual Basic®, obtained by:
Dim ACMApp as objectSet ACMApp =createobject("ACM
Application")
In a script, available as:
"Application":Set ACMApp=Application
Active Application. Represents the currently open simulation document (,
Document ActiveDocument that is, the file created by your Aspen Modeler product)
and supports methods such as Save, Save As, and
others, found on the File menu.
Is the object returned when a GetObject("file.acmf")
call is made from external Microsoft® Visual Basic®. Is
the same object as the simulation object
Simulation Application.Simulation The current simulation, contains the flowsheet object
and has methods to perform runs.
Flowsheet Application.Simulation. Contains the blocks, streams, variables, etc., of the
Flowsheet currently open simulation, and gives access to them to
allow variables to be set or retrieved.
Block Application.Simulation. A block in the flowsheet
Flowsheet.BlockName
Stream Application.Simulation. A stream in the flowsheet
Flowsheet.StreamName
Port Application.Simulation. A port in a block
Flowsheet.BlockName.
PortName
Variable Application.Simulation. A variable in a block
Flowsheet.BlockName.
VarName
Properties Application.Simulation. Contains physical properties information
Properties
Component Application.Simulation. Contains information about a particular named list of
List Properties. components
ComponentList(name)
OutputLogger Application.Simulation. Controls the behavior of the Simulation Messages
OutputLogger window and the logging file. Provides access to the
same functionality as the right mouse button does in
the Simulation Messages window.
Results Application.Simulation. Provides the ability to use results from a snapshot file to
Results initialize a run, that is, the same functionality provided

4 Automation Methods and Properties 41


by the menu item Use on the Tools menu.
UOM Application.Simulation. Provides the ability to manipulate the Unit of
Uom Measurement sets in use by your Aspen Modeler
product. See the Modeling Language Reference, Chapter
2.
Task Application.Simulation. An event-driven task
Flowsheet.TaskName
Homotopy Application.Simulation. Controls Homotopy behavior
Homotopy
Optimization Application.Simulation. Accesses optimization functions for the current
Optimization simulation
OnlineLinks Application.Simulation. Provides access to the Online Links facility, which
OnlineLinks controls the exchange of data between the simulation
and an on-line data server.
CDI Application.Simulation.CDI Returns a reference to the CDI object.

Note: If a method or property is used incorrectly, it generates an


error. In Microsoft Visual Basic, you can inspect the Err object
(particularly Err.Description, which is a string describing the
error) to find the nature of the error.

Application Object
Properties, methods and events are available for the Application object.

Application Properties
The following properties are available for the Application object.
• Application.ActiveDocument
• Application.Caption
• Application.DefaultFilePath
• Application.FullName
• Application.Height
• Application.Interactive
• Application.Left
• Application.Name
• Application.Path
• Application.ProcessID
• Application.Simulation
• Application.StatusBar
• Application.Top
• Application.Version
• Application.Visible
• Application.Width
• WorkingFolder

4 Automation Methods and Properties 42


Application.ActiveDocument
Returns the currently open document (if any).
Example
Running external Microsoft® Visual Basic®:
Dim doc as object
Set doc=ACMApp.ActiveDocument

Application.Caption
Returns or sets the caption on the main GUI window.
Example
Running a script from Flowsheet or Model:
Application.Caption = "My own GUI title"
Running external Microsoft® Visual Basic®:
label1.caption = ACMApp.Caption

Application.DefaultFilePath
Returns the file path name that is initially available on a File / Open...
operation.
Example
Running a script from Flowsheet or Model:
Dim OpenPath
OpenPath = Application.DefaultFilePath
'sets the path
Application.DefaultFilePath="c:\project\"

Application.FullName
Returns the full path and file name of the current executable.
Example
Running a script from Flowsheet or Model:
Dim CurrentExec
CurrentExec = Application.FullName

Application.Height
Returns or sets the height in points (there are approximately 72 points in an
inch) of the GUI window.
Example
Running a script from Flowsheet or Model:
Application.Height = 400
Running external Microsoft® Visual Basic®:

4 Automation Methods and Properties 43


Label1.Caption = ACMApp.Height

Application.Interactive
Sets whether the user can interact with the GUI. Takes a logical value of True
and False.
Example
Running a script from Flowsheet or Model:
Application.Interactive = False

Application.Left
Returns or sets the position in points (there are approximately 72 points in an
inch) of the left edge of the GUI window.
Example
Running a script from Flowsheet or Model:
Application.Left = 30
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Left

Application.Name
Returns the current name of the application.
Example
Running a script from Flowsheet or Model:
Dim CurrentName
CurrentName = Application.Name

Application.Path
Returns the path to the current application.
Example
Running a script from Flowsheet or Model:
Dim CurrentPath
CurrentPath = Application.Path

Application.ProcessID
Returns the process ID of the ACM client process.
Example
From external Microsoft Visual Basic:
Dim ProcID
ProcID = ACMApp. ProcessID

4 Automation Methods and Properties 44


Application.StatusBar
You can read the value of the text in the status bar of the GUI.
Example
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.StatusBar
Running a script from Flowsheet or Model:
Application.StatusBar = "Definitions in progress"

Application.Top
Returns or sets the position in points (there are approximately 72 points in an
inch) of the top edge of the GUI window.
Example
Running a script from Flowsheet or Model:
Application.Top = 10
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Top

Application.Version
Returns the version of the application. Read-only string.
Example
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Version

Application.Visible
You can make the GUI visible or invisible. Can be either True or False.
Example
Running external Microsoft® Visual Basic®:
If Check1.Value = 0 Then ACMApp.Visible = True

Application.Width
Returns or sets the width in points (there are approximately 72 points in an
inch) of the GUI window.
Example
Running a script from Flowsheet or Model:
Application.Width = 600
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Width

4 Automation Methods and Properties 45


WorkingFolder
Returns or sets the working folder for the simulation server. Note that the
working folder can not be changed if a simulation is already opened.
Example:
in a script:

display the current working folder


Application.Msg "Current working folder is " &
Application.WorkingFolder
Example:
with external visual basic
(This example shows how to set the working folder before opening the
simulation.)

Private Sub CommandButton1_Click()


Dim acm As Object
Dim acmsim As Object

Set acm = CreateObject("ACM Application")


acm.Application.Visible = True
acm.Application.WorkingFolder = "d:\tmp1"
Set acmsim =
acm.Application.OpenDocument("d:\tmp\test1.acmf")

End Sub

Application Methods
The following methods are available for the Application object.
• Application.Activate()
• Application.CloseDocument()
• Application.Maximize()
• Application.Minimize()
• Application.Msg()
• Application.NewDocument()
• Application.OpenDocument()
• Application.ProcessIDs
• Application.Quit()
• Application.Restore()
• Application.SaveDocument()

4 Automation Methods and Properties 46


• Application.SaveDocumentAs()

Application.Activate()
Brings the application's main window to the front and gives it keyboard focus.
Example
Running external Microsoft® Visual Basic®:
ACMApp.Activate

Application.CloseDocument()
Closes the currently open document. The Boolean parameter is true if any
changes to the document should be saved back to disk.

Caution: Do not execute this command from a script because


the script will be abruptly terminated. This is because the running
script is owned by the document being closed.

Example
Running external Microsoft® Visual Basic®:
ACMApp.CloseDocument(True)

Application.Maximize()
Makes the application's main window occupy the full screen.
Example
Running external Microsoft® Visual Basic®:
ACMApp.Maximize

Application.Minimize()
Iconizes the application's window.
Example
Running external Microsoft® Visual Basic®:
ACMApp.Minimize

Application.Msg()
You can print text to the Simulation Messages window.
The & character enables you to concatenate strings of text.
If you find that you cannot print some values to the message window, try
using the CStr() function, which converts parameters to strings of text.

Caution: When running from external Microsoft® Visual Basic®,


the Simulation Messages window only exists when a simulation
document is open. If there is no open document, the text sent
through this method will be lost.

4 Automation Methods and Properties 47


Examples
Running a script from Flowsheet or Model:
Application.Msg "Hello World"

Application.Msg Application.Simulation.RunMode

Application.Msg "Run Mode is " &


Application.Simulation.RunMode

Application.Msg "Run complete at time" & Time

Application.NewDocument()
Closes any currently open document, and creates a new document.
If a document is already open at the time the call is made then it will be
automatically closed if it is not modified.
If it is modified then the system will prompt you to save changes.
Consequently it is usually best to close any existing document explicitly using
the CloseDocument method before using this method. For details, see
Application.CloseDocument().

Caution: Do not execute this command from a script because


the script will be abruptly terminated. This is because the running
script is owned by the document being closed.

Example
Running external Microsoft® Visual Basic®:
Dim ACMDocument as object
Set ACMDocument=ACMApp.NewDocument

Application.OpenDocument()
Opens an existing document. Takes a string argument which is the path to
the file, and returns a document.
If a document is already open at the time the call is made then it will be
automatically closed if it is not modified.
If it is modified then the system will prompt you to save changes.
Consequently it is usually best to close any existing document explicitly using
the CloseDocument method before using this method. For details, see
Application.CloseDocument().

Caution: If you execute the command from within a script, it will


be abruptly terminated. This is because the running script is
owned by the document being closed.

4 Automation Methods and Properties 48


Example
Running external Microsoft® Visual Basic®:
Dim ACMDocument as object
Set
ACMDocument=ACMApp.OpenDocument("d:\simulations\towersim.ac
mf")

Application.ProcessIDs
Returns an array of 3 integers. These are the process IDs of the 3 ACM
processes, ACM client, server and task server in that order.
Example
From external Microsoft Visual Basic:
Dim ProcIDs

ProcIDs = ACMApp. ProcessIDs

Application.Quit()
Quits the current session.
Example
Running external Microsoft® Visual Basic®:
MsgBox("Do you want to close the application?",
vbYesNoCancel, "Quit Application")
If Response = "yes" Then ACMApp.Quit

Application.Restore()
Restores the application's main window to its normal size. Normally called
after the window has been minimized or maximized.
Example
Running external Microsoft® Visual Basic®:
ACMApp.Restore

Application.SaveDocument()
Saves the currently open simulation document under its existing name.

Example
Running external Microsoft® Visual Basic®:
Dim ACMApp as Object
Set ACMApp= CreateObject("ACM Application")
ACMApp.visible=true
ACMApp.OpenDocument("d:\test\simulation01.acmf")
' other work occurs here…

4 Automation Methods and Properties 49


' save results
ACMApp.SaveDocument
ACMApp.Quit

Application.SaveDocumentAs()
Saves the currently open simulation document under a new name.
Takes the new path as the first argument, and a Boolean variable as the
second. If the second argument is true then any existing file with the name
will be overwritten.

Note: After the document has been saved using this function,
the new path becomes the default path for future calls to the
SaveDocument method.

Example
Running external Microsoft® Visual Basic®:
Dim ACMApp as Object
Set ACMApp= CreateObject("ACM Application")
ACMApp.visible=true
ACMApp.OpenDocument("d:\test\simulation01.acmf")
' other work occurs here…
' save results, overwriting file if it exists
ACMApp.SaveDocumentAs "d:\test\simulation02.acmf",True
ACMApp.Quit

Application Events
Aspen Modeler products expose a number of automation events which can be
handled in a Visual Basic form. These events are:

Event Occurs whenever


void OnRunStarted(); A run is started in ACM
void OnRunPaused(); A run is paused in ACM
void OnHasQuit(); The ACM application terminates
void OnHasSaved(); The current simulation is saved
void OnSavedAs(VARIANT sPath); The current simulation is saved
to a new filename. sPath gives
the new path and filename.
void OnOpened(VARIANT sPath); A simulation is opened. sPath
gives the path and filename of
that simulation.
void OnNew(); A new, blank simulation is
created
void OnRunModeChanged(VARIANT sRunMode); The run mode is changed, for

4 Automation Methods and Properties 50


example, from steady-state to
dynamic. sRunMode gives the
new run mode.
void OnNewBlock(VARIANT sBlockName); A new block is added to the
flowsheet. sBlockName gives the
name of that block.
void OnNewStream(VARIANT sStreamName); A new stream is added to the
flowsheet. sStreamName gives
the name of that stream.
void OnDeletedBlock(VARIANT sBlockName); A block is deleted from the
flowsheet. sBlockName gives the
name of that block.
void OnDeletedStream(VARIANT sStreamName); A stream is deleted from the
flowsheet. sStreamName gives
the name of that stream.
void OnUomSetChanged(VARIANT sUomSetName); The units of measurement set
changes.
void OnStreamConnected(VARIANT sStreamName); A stream is connected.
sStreamName gives the name of
that stream.
void OnUserChangedVariable The value or other properties of a
(VARIANT sVariableName); variable are changed by the user.
void OnStreamDisconnected(VARIANT sStreamName); A stream is disconnected.
sStreamName gives the name of
that stream.
void OnStepComplete(); A solution step is completed.

For an example of using Visual Basic 6 to handle events, see Aspen Custom
Modeler Examples, Handling Events in a Visual Basic Form.

ActiveDocument Object
Properties and methods are available for the ActiveDocument object.

ActiveDocument Properties
The following properties are available for the ActiveDocument object.
• ActiveDocument.Application
• ActiveDocument.FullName
• ActiveDocument.Name
• ActiveDocument.Parent
• ActiveDocument.Saved
• ActiveDocument.FlowsheetWallpaperMode

ActiveDocument.Application
This read-only string property returns the application.
Example
Running a script from Flowsheet or Model:
Dim ACMApp
Set ACMApp= ActiveDocument.Application

4 Automation Methods and Properties 51


ACMapp.msg "using the application"

ActiveDocument.FullName
This read-only string property returns the full path of the document. If the
document has not yet been loaded from or saved to disk then the string may
be empty.
Example
Running a script from Flowsheet or Model:
Dim ACMName
' Get full path to document
ACMName = ActiveDocument.FullName
' write path to Simulation Message Window
ACMapp.msg ACMName

ActiveDocument.Name
This read-only string property returns the name of the document. For a
document which not been associated with a disk file this is normally
"Untitled". If the document was opened from the file
"d:\simulations\sim01.acmf" then the Name would be "sim01.acmf".
Example
Running a script from Flowsheet or Model:
Dim ACMName
' Get name of the document
ACMName = ActiveDocument.Name
'write name to Simulation Message Window
ACMapp.msg ACMName

ActiveDocument.Parent
This read-only property returns the parent automation object of the
document, that is, the application.
Example
Running a script from Flowsheet or Model:
Dim ACMApp
' Get parent of the document
Set ACMApp = ActiveDocument.parent
' Use one of the application’s methods to show
' we really have hold of the application
ACMApp.msg "using the msg method of the application"

4 Automation Methods and Properties 52


ActiveDocument.Saved
This read-only Boolean property returns True if any modifications made to the
document have been saved to disk. If the document has been changed in
memory since it was last written to disk, it returns False.
Example
Running a script from Flowsheet or Model:
Dim bSaved
' Get document modification state
bSaved = ActiveDocument.Saved
' write status to Simulation Message Window
if bSaved Then
activedocument.application.msg "Document secure on disk"
else
activedocument.application.msg "Document modified in
memory"
end if

ActiveDocument.FlowsheetWallpaperMode
This Boolean property controls if the flowsheet will be set as the wallpaper
background of the application or as a floating window.
Example
Running a script from Flowsheet or Model:
Application.ActiveDocument.FlowsheetWallpaperMode = true

ActiveDocument Methods
The following methods are available for the ActiveDocument object.
• ActiveDocument.CloseAllForms()
• ActiveDocument.CreateLibrary()
• ActiveDocument.SaveDocument()
• ActiveDocument.SaveDocumentAs()
• ActiveDocument.CloseExplorerWindows
• ActiveDocument.CloseEditorWindows
• ActiveDocument.LaunchExplorer
• ActiveDocument.ShowFlowsheetWindow
• ActiveDocument.ShowEditorWindow
• ActiveDocument.ShowMessagesWindow

ActiveDocument.CloseAllForms()
Closes all of the currently open forms (plots and tables).
Example

4 Automation Methods and Properties 53


Running from a script within Aspen Custom Modeler®:
ActiveDocument.CloseAllForms

ActiveDocument.CreateLibrary()
Creates a library with the path supplied by its one string argument. The file
name must end with the extension .acml.
Example
Running external Microsoft® Visual Basic®:
Dim ACMApp as Object
Dim ACMDoc as Object
Set ACMApp= CreateObject("ACM Application")
ACMApp.visible=true
ACMDoc=ACMApp.OpenDocument("d:\test\simulation01.acmf")
' save as a library
ACMDoc.CreateLibrary("d:\test\simulation01.acml")
' save results
ACMApp.Quit

ActiveDocument.SaveDocument()
Saves the currently open simulation document under its current name.
Example
Running external Microsoft® Visual Basic®:
Dim ACMApp as Object
Dim ACMDoc as Object
Set ACMApp= CreateObject("ACM Application")
ACMApp.visible=true
Set ACMDoc=ACMApp.OpenDocument("d:\test\simulation01.acmf")
' other work occurs here…
' save results
ACMDoc.SaveDocument
ACMApp.Quit

ActiveDocument.SaveDocumentAs()
Saves the currently open simulation document under a new name.
Takes the new path as the first argument, and a Boolean variable as the
second. If the second argument is True then any existing file with the name
will be overwritten.

4 Automation Methods and Properties 54


Notes:

• After the document has been saved using this function the
new path becomes the default path for future calls to the
SaveDocument method.

• The path must specify a directory that already exists.

Example
Running external Microsoft® Visual Basic®:
Dim ACMApp as Object
Dim ACMDoc as Object
Set ACMApp= CreateObject("ACM Application")
ACMApp.visible=true
Set ACMDoc=ACMApp.OpenDocument("d:\test\simulation01.acmf")
' other work occurs here…
' save results
ACMDoc.SaveDocumentAs "d:\test\simulation02.acmf",TRUE
ACMApp.Quit

ActiveDocument.CloseExplorerWindows
Closes all of the currently open explorer windows.
Example
Running from a script within Aspen Custom Modeler:
Application.ActiveDocument.CloseExplorerWindows

ActiveDocument.CloseEditorWindows
Closes all of the currently open editor windows.
Example
Running from a script within Aspen Custom Modeler:
Application.ActiveDocument.CloseEditorWindows

ActiveDocument.LaunchExplorer
Launches an explorer window. Optional arguments can be used to give the
window position and size.
LaunchExplorer x position, y position, width, depth
Example
Running a script from Flowsheet or Model:
Application.ActiveDocument.LaunchExplorer 100,0,180,600

4 Automation Methods and Properties 55


ActiveDocument.ShowFlowsheetWindow
Show the flowsheet window. Optional arguments can be used to give the
window position and size.
ShowFlowsheetWindow x position, y position, width, depth
Example
Running a script from Flowsheet or Model:
Application.ActiveDocument.ShowFlowsheetWindow
100,0,180,600

ActiveDocument.ShowEditorWindow
Shows an editor window. There can be up to 8 arguments. Arguments 1 and 2
are mandatory and are the location and name of the item to be edited.
The location can be "Flowsheet", “Custom” or a library name which must be a
full path to an attached library.
The name is the name of the type in the case of a library or Custom modeling
or the path to the item in the case of the Flowsheet.
Argument 3 is a read only flag, 0 for read only, 1 for write. All libraries must
be accessed read only.
Argument 4 to 7 are the x position, y position, width and depth of the editor
window.
Argument 8 is the line number to be made current.
Example
Running a script from Flowsheet or Model:
ActiveDocument.ShowEditorWindow
"Custom","Tank",0,581,387,351,160,1
ActiveDocument.ShowEditorWindow
"E:\Program Files\AspenTech\AMSystem
2004\lib\Modeler.acml","APlusProduct", 0,182,184,603,218

ActiveDocument.ShowMessagesWindow
Shows the simulation messages window. Optional arguments can be used to
give the window position and size.
ShowMessagesWindow x position, y position, width, depth
Example
Running a script from Flowsheet or Model:
Application.ActiveDocument.ShowMessagesWindow 180,497,840,124

Form Object
The following properties are available for the Form object:

4 Automation Methods and Properties 56


Name
The name of the object relative to its parent model (read only).
VariablesPaths
Collection of variable paths the form displays (read only).

VariablesPaths
VariablesPaths is the collection of strings which contains the names of the
variables selected on a form.

Example:
The following script prints the variables selected on table "Results" from block
B1.

for each s in B1.Forms("Results").VariablesPaths


set v = B1.Resolve(s)
application.msg s & " = " & v.value
next

Simulation Object
Properties and methods are available for the Simulation object.

Simulation Properties
The following properties are available for the Simulation object.
• Simulation.CDI
• Simulation.CommunicationInterval
• Simulation.Correlation
• Simulation.CorrelationMatrix
• Simulation.CorrelationMatrixPresent
• Simulation.Covariance
• Simulation.CovarianceMatrix
• Simulation.CovarianceMatrixPresent
• Simulation.Degrees
• Simulation.Deviation
• Simulation.DeviationArrayPresent
• Simulation.DisplayTime
• Simulation.EndStepCount
• Simulation.EndTime
• Simulation.Equations
• Simulation.EstimatedValue

4 Automation Methods and Properties 57


• Simulation.EstimationRunState
• Simulation.Flowsheet
• Simulation.FullName
• Simulation.LeastSquaresObjective
• Simulation.Name
• Simulation.Options...
• Simulation.Properties
• Simulation.Results
• Simulation.RunMode
• Simulation.RunNumber
• Simulation.Saved
• Simulation.ScriptIsRunning
• Simulation.SpecState
• Simulation.State
• Simulation.Successful
• Simulation.Termination
• Simulation.Time
• Simulation.Variables

Simulation.CDI
Returns a reference to the CDI object. For more information, see CDI Object.

Simulation.CommunicationInterval
This Read/Write property gives access to the Communication Interval. This is
the interval in simulation time at which results are returned from the
simulation engine to the GUI.
Example
Running a script from Flowsheet:
Simulation.CommunicationInterval=0.02
Application.msg "Com Time: " &
Simulation.CommunicationInterval

Simulation.Correlation
This read-only property accepts the names of two of the estimated variables
and returns the correlation of the variables (that is, one element of the
correlation matrix).
For an example, see the Modeling Language Reference, Chapter 2, Accessing
Individual Correlation Results.

Simulation.CorrelationMatrix
This read-only property returns the 2D correlation matrix of floating point
numbers. The array subscripts both range from
0..number_estimated_variables-1, where 0 corresponds to the first variable
added by AddEsstimateVariable(), 1 to the second, and so on. The array is

4 Automation Methods and Properties 58


symmetric about the lead diagonal. For an example, see the Modeling
Language Reference, Chapter 2, Testing for the Correlation Matrix.

Note: Use after an Estimation run only.

Simulation.CorrelationMatrixPresent
This read-only property returns true if the correlation matrix is present. For
an example, see the Modeling Language Reference, Chapter 2, Testing for the
Correlation Matrix.

Simulation.Covariance
This read-only property is used as follows:
Covariance("estimated var1", "estimated var2")
It returns the covariance of the variables (that is, one element of the
covariance matrix).

Note: Use after an Estimation run only.

Simulation.CovarianceMatrix
This read-only property returns the 2D covariance matrix of floating point
numbers. The array subscripts both range from
0..number_estimated_variable-1, where 0 corresponds to the first variable
added by AddEstimateVariable(), 1 to the second, and so on. The array is
symmetric about the lead diagonal.

Simulation.CovarianceMatrixPresent
This read-only property returns true if the covariance matrix is present, and
false if it is not.

Simulation.Degrees
Returns the number of degrees of freedom of the simulation. Returns 0 for a
complete simulation, a positive value for an under-specified simulation, and a
negative number for an over-specified simulation.
Example
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Simulation.Degrees
Running a script from Flowsheet or Model:
IF Application.Simulation.Degrees < 0 THEN
B1.Input1.Flow.Spec = "Fixed"
ENDIF

4 Automation Methods and Properties 59


Simulation.Deviation
See the Modeling Language Reference, Chapter 2, Defining an Estimation
Simulation..

Simulation.DeviationArrayPresent
See the Modeling Language Reference, Chapter 2, Defining an Estimation
Simulation..

Simulation.DisplayTime
This read-write property allows you to access and modify the current
simulation time in the current display units. See also Simulation.Time.
Example
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Simulation.DisplayTime

Simulation.EndStepCount
Returns or sets the number of steps before a dynamic run pauses.

Notes
• This option has no effect if the Application.Simulation.Termination
property is subsequently set to Never.
• Depending on the previous value of Termination, setting
Simulation.EndStepCount changes that value:

If Termination was Setting EndStepCount changes the value of


previously set to Termination to
"Never" "OnIterations"
"AtTime" "TimeOrIterations"

Example
Running a script from Flowsheet or Model:
Application.Simulation.EndStepCount = 50
Application.Simulation.Termination = "AtTime"
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Simulation.EndStepCount

Simulation.EndTime
Returns or sets the end time of a dynamic run.

Notes
• This option has no effect if the Application.Simulation.Termination
property is set to Never.
• Depending on the previous value of Termination, setting
Simulation.EndStepCount changes that value:

4 Automation Methods and Properties 60


If Termination was Setting EndTime changes the value of
previously set to Termination to
"Never" "AtTime"
"OnIterations" "TimeOrIterations"

Example
Running a script from Flowsheet or Model:
Application.Simulation.EndTime = 100.0
Application.Simulation.Termination = "AtTime"
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Simulation.EndTime

Simulation.Equations
Returns the total number of equations in the simulation.
Example
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Simulation.Equations

Simulation.EstimatedValue
See the Modeling Language Reference, Chapter 2, Defining an Estimation
Simulation.

Simulation.EstimationRunState
A read-only property that may be inspected after an Estimation run to
determine if it succeeded. Possible values are:

Value Meaning
0 Still running
1 Solution Convergence
2 Relative Function Convergence
3 Solution and Relative Function Convergence
4 Absolute Function Convergence
5 Singular Convergence
6 False Convergence
7 Exceeded maximum number of iterations
8 Non specific error condition (see Simulation Messages window)
255 Not run

Simulation.Flowsheet
Returns the Flowsheet object. The Flowsheet object is used to access blocks
and stream on the flowsheet. For more information, see Block, Stream, and
Flowsheet Objects.
Example
Running external Microsoft® Visual Basic®:

4 Automation Methods and Properties 61


Dim ACMFlowsheet as Object
Set ACMFlowsheet = ACMApp.Simulation.Flowsheet

Simulation.FullName
Returns the full path name of the current simulation, for example:
D:\simulations\simulation01.acmf.

Note: If the simulation document has not yet been loaded from,
or saved to disk, then the string may be empty.

Example
Running external Microsoft Visual Basic:
Label1.Caption = ACMApp.Simulation.FullName

Simulation. LeastSquaresObjective
This read only property allows you to access the result of an estimation run
giving the final value of the least squares objective function.

Example
Running external Microsoft Visual Basic:
Labell.Caption = ACMApp.Simulation. LeastSquaresObjective

Simulation.Name
This read-only property returns the name of the current simulation as a
string. For example, if the open simulation document is
D:\simulations\simulation01.acmf, the value returned is simulation01.acmf.
Example
Running external Microsoft Visual Basic:
Label1.Caption = ACMApp.Simulation.Name

Simulation.Options...
The Options properties correspond to the options available on the Solver
Options dialog. Each solver property is defined by
Application.Simulation.Options, followed by the solver option property name
OptionProperty. Running a script from Flowsheet or Model, the syntax is:
Application.Simulation.Options.OptionProperty
For the valid values of numerical solver options, see Solver Properties Dialog
Box Chapter 6.

General Properties
The available General properties are:

Property Explanation

4 Automation Methods and Properties 62


AbsPerturb Numerical derivative absolute perturbation
AbsTearTol Absolute tear tolerance
AbsTol Absolute variable tolerance
ChangeTol SAX tolerance
CheckProcDerivs Check procedure derivatives. Argument is an integer
or string.
Valid values are: 0 = "Off", 1 = "Active derivatives".
Returns as a string.
Compression Eliminates equivalence equations: Boolean
DerivAbsTol Absolute checking tolerance
DerivRelTol Relative checking tolerance
EqnTol Absolute equation tolerance
MaxTearIter Maximum tear iteration
PrintLevel Print level. Argument is an integer from 0 to 5
0 – None 1 - Low
2 – Medium 3 - High
4 - Very High 5 - Maximum
PropInfo Properties print level. Argument is an integer from -1
to 3
-1 – None 0 - Minimal
1 – Low 2 - High
3 - Maximum
RelPerturb Numerical derivative relative perturbation
RelTearTol Relative tear tolerance
RelTol Relative variable tolerance
Scaling Solver scaling. Argument is a Boolean: True or False
SyncSteps Takes an integer or string argument:
0 = "Full", 1 = "Low", 2 = "Medium", 3 = "High"
Tearing Argument is an integer or string. Valid values are:
0 = "none", 1 = "update", 2 = "start", 3 =
"complete". Returns as a string.
TearUpdate Takes an integer or string argument:
0 = "Wegstein", 1 = "Direct". Returns as a string.
WatchGroup Watch group. Argument is an integer from 1 to the
number of equation groups in the simulation
WatchSubgroup Watch Subgroup of torn group
Wegstein.MaxAcceleratio Wegstein maximum Acceleration
n
Wegstein.MinAcceleration Wegstein minimum Acceleration

Integrator Properties
To display the relevant Solver Options Reference information, refer to the
property name in the left column of the table.
Integrator:
Explicit Euler, Runge Kutta 4, Implicit Euler, ImpEuler (11.1), Gear, VSIE
(11.1), Gear (11.1).
Example:
Application.Simulation.Options.Integrator = "Gear"
Label1.Caption = Application.Simulation.Options.Integrator.

4 Automation Methods and Properties 63


Returns a string.

Property Explanation
Unified integrator options
Where appropriate these options will be applied when any of the following
integration methods is selected: Explicit Euler, Runge Kutta 4, Implicit
Euler, Gear.
Integration..AbsErrorTol Absolute integration error tolerance
Integration..AbsTearTol Absolute integration tear error tolerance
Integration..RelErrorTol Relative integration error tolerance
Integration..RelTearTol Relative integration tear error tolerance
Integration..IncSensErrors Include sensitivity errors
Integration..RcvTornVars Reconverge torn variables
Integration.TestSAndAVars Integration error test includes State and
Algebraic variables
Integration.StepSizeType Step size type - Fixed or Variable
Integration.StepSize Step size
Integration.InitStepSize Initial step size
Integration.MinStepSize Minimum step size
Integration.MaxStepSize Maximum step size
Integration.StepRedFact Step reduction factor
Integration.EnforceMinStep Always enforce minimum step
Integration.ItplToComTime Interpolate communication time
Integration.LocateIEvents Locate model discontinuities
Integration.ReInitAfterIE Re-initialize after model discontinuities
Integration.DiscontinuityEvent Discontinuity event tolerance [was
Tol ImplicitEventTolerance]
Integration.ReInitAfterEE Re-initialize after Variable Step Change
Integration.UsePrevAfterEE Step size after Variable Step Change
Integration.ShowHIErrors Highest integration errors
Integration.ShowHTIErrors Highest tear integration errors
Integration.MaxOrder Maximum order for Gear method
ImpEuler(11.1) options
ImpEuler.Step Integration step
VSIE (11.1) options
VSIE.InitialStep Initial integration step
VSIE.MinimumStep Minimum integration step
VSIE.MaximumStep Maximum integration step
VSIE.StepRedFact Step reduction factor
VSIE.MaxIncFact Maximum step increment factor
VSIE.HighestErrors Highest errors
VSIE.MaxCorIter Maximum corrector iterations
VSIE.AbsErrTol Absolute error tolerance
VSIE.TearErrTol Tear error tolerance
VSIE.Interpolation VSIE interpolation Takes a Boolean
argument
VSIE.ReconvergeTorn VSIE reconverge torn variables Takes a
Boolean argument
Gear (11.1) options
Gear.HighestErrors Gear highest integration errors

4 Automation Methods and Properties 64


Gear.InitialStep Gear initial integration step
Gear.MinimumStep Gear minimum integration step
Gear.MaximumStep Gear maximum integration step
Gear.Reinit Gear re-initialization method Takes an
integer or string argument, returns as a
string Valid Values are 0 = "Normal", 1 =
"Fast", 2 = "Save"
Gear.BoundCheck Gear keep solution within bounds Takes
an integer or string argument, returns as
a string 0 = "Off", 1 = "Track", 2 = "Clip"
Gear.EventTol Gear event tolerance
Gear.JacUpdate Gear Jacobian update policy
Gear.MaxCorSteps Show Gear maximum corrector step sizes
Gear.MaxCorIter Gear Maximum corrector iterations

Linear Solver Properties


The available Linear Solver properties are:

Property Explanation
LinearSolver Linear solver. Takes an integer or string
argument. Valid values are:
1 = "MA28"
4 = "MA48"
MA28.DropTol MA28 drop tolerance
MA48.DropTol MA48 drop tolerance
MA48.PivotTol MA48 pivot tolerance
MA48.ReanalyzeThreshold MA48 reanalyze threshold
MA48.ReanalyzeWindow MA48 reanalyze FLOPS window size
MA48.Repivot MA48 repivot every n factorizations
MA48.PivotSearch MA48 solver searches n columns for pivots

Non-Linear Solver Properties


The available Non-Linear Solver properties are:

Property Explanation
Nonlinear.Method Non-linear solver method. Takes an
integer or string argument:
0 = "Hybrid"
1 = "Newton"
2 = "Fast Newton"
OpenNLASolver The name of the DLL for the Open
Nonlinear Algebraic solver
OpenNLASolverParameters.Item("Param") Set or get this property to read/write to
the OpenNlaSolver parameter "param",
for example:
OpenNLASolverParameters.Item("PrintLe
vel") = 1 'Set printlevel parameter to
one
OpenNLASolverParameters.Count Returns the number of OpenNLASolver
parameters
OpenNLASolverParameters.ParamName(i) Returns the name of parameter i in the
OpenNLASolverParameters collection

4 Automation Methods and Properties 65


Nonlinear.MaxIter Non-linear solver maximum iterations
Nonlinear.MaxDivSteps Non-linear solver maximum divergent
steps
Nonlinear.MaxStepRed Non-linear solver maximum step
reductions
Nonlinear.MaxFastNewtonSteps Non-linear solver maximum Fast Newton
steps
Nonlinear.ConvCrit Non-linear solver convergence criterion.
Takes an integer or string argument:
0 = "Residual"
1 = "Variable"
2 = "Residual and Variable"
3 = "Residual or Variable"
Nonlinear.Dogleg Non-linear solver dogleg method. Takes
a Boolean argument, True or False
Nonlinear.HiVarSteps Non-linear solver highest variable steps
Nonlinear.HiResidual Non-linear solver highest residuals
Nonlinear.MathsPrint Non-linear solver print linear algebra for
groups of size greater than or equal to
n.
Nonlinear.Boundfrac Non-linear solver maximum approach to
bound
Nonlinear.RangeFrac Non-linear solver maximum range
fraction
Nonlinear.BoundClip Non-linear solver approach to bound
Nonlinear.AbsPert Non-linear solver absolute perturbation
Nonlinear.SingPert Non-linear solver singularity
perturbation
Nonlinear.MaxVarStep Non-linear solver maximum variable
step

Estimation Solver Properties


Estimation solver property options are listed below. To display the relevant
Solver Options Reference information, click the name in the property column.

Property Explanation
NL2Sol.AbsFuncTol Estimation Absolute Function Tolerance
NL2Sol.FalseConvTol Estimation False Convergence Tolerance
NL2Sol.MaxIter Estimation Maximum Iterations
NL2Sol.RelFuncTol Estimation Relative Function Tolerance
NL2Sol.SolTol Estimation Solution Tolerance
Estimator Estimation method. Valid values are: 1 = Least squares; 2 =
Maximum log likelihood
EstimationSolver Estimation solver to be used. Takes an integer argument. Valid
values are: 1 = FEASOPT (Maximum log likelihood estimator
only); 2 = NL2SOL; 3 = Nelder-Mead; 6 = Open NLP (reduced
space)
EstimationPrintLevel Reporting level for estimator diagnostic output. Takes an integer
or string argument but returns a string. Valid values are: 0 =
"None"; 1 = "Low"; 2 = "Medium"; 3 = "High"; 4 = "Very High"
OpenESTSolver The name of the DLL for the Open estimator Algebraic solver
OpenNLPEstSolverPar Set or get this property to read/write to the OpenNLPEstSolver
ameters.Item("Param parameter "param".For
") example:OpenNLPEstSolverParameters.Item("PrintLevel") = 1 'Set

4 Automation Methods and Properties 66


printlevel parameter to oneOpenNLPEstSolverParameters.Count –
Returns the number of OpenNLPEstSolver
parametersOpenNLPSolverParameters ParamName(i) – Returns
the name of parameter i in the OpenNLPEstSolverParameters
collection

Timesettings Properties

Property Explanation
TimeSettings. Specifies the communication interval at which data is
CommunicationInterval available for plotting and snapshots
TimeSettings.DisplayUpdateInterva Specifies the interval at which data is updated on
l screen in real time
TimeSettings.EnablePauseAt Boolean; pauses the simulation at the time specified
in TimeSettings.PauseAt
TimeSettings.PauseAt Pauses the simulation at the specified time in
conjunction with TimeSettings.EnablePauseAt =
TRUE
TimeSettings.EnableStepFor: False Boolean; pauses the simulation after the number of
steps specified in TimeSettings.StepFor
TimeSettings.StepFor Pauses the simulation after the specified number of
steps in conjunction with
TimeSettings.EnableStepFor = TRUE
TimeSettings.RealTimeSyncFactor Determines the relationship between real time and
simulation time. Set to 0 for the simulation to run as
fast as possible; set to 1 to run the simulation in real
time, if possible. Any other positive real number acts
as a multiplier of real time
TimeSettings.RecordHistory Boolean; set to TRUE to record a time history for all
variables in the simulation regardless of each
variable's Record attribute
TimeSettings.CommunicationUnits Specifies the simulation time units. Valid units are:
"seconds", "minutes", "hours", "days", "weeks",
"months", "years"
TimeSettings.TimeDisplayUnits Sets or retrieves the unit in which time is displayed
in the GUI. Valid units are: "seconds", "minutes",
"hours", "days", "weeks", "months", "years"

Examples of Using Estimation Solver Properties


Running a script from Flowsheet or Model:
Application.Simulation.Options.NL2Sol.AbsFuncTol = 1e-20 '
absolute function tolerance
Application.Simulation.Options.NL2Sol.RelFuncTol = 1e-4 '
relative function tolerance
Application.Simulation.Options.NL2Sol.SolTol = 1e-4 '
solution tolerance
Application.Simulation.Options.NL2Sol.PrintLevel = 2 '
print level
Application.Simulation.Options.NL2Sol.FalseConvTol = 0 '
false convergence tolerance
Application.Simulation.Options.NL2Sol.MaxIter = 50 '
maximum iterations

4 Automation Methods and Properties 67


Running external Microsoft Visual Basic:
Dim objApplication as Object
Set objApplication = GetObject(filename)
objApplication.Application.Simulation.Options.NL2Sol.AbsFun
cTol = 1e-20 ' absolute function tolerance
objApplication.Application.Simulation.Options.NL2Sol.RelFun
cTol = 1e-4 ' relative function tolerance
objApplication.Application.Simulation.Options.NL2Sol.SolTol
= 1e-4 ' solution tolerance
objApplication.Application.Simulation.Options.NL2Sol.PrintL
evel = 2 ' print level
objApplication.Application.Simulation.Options.NL2Sol.FalseC
onvTol = 0 ' false convergence tolerance
objApplication.Application.Simulation.Options.NL2Sol.MaxIte
r = 50 ' maximum iterations

Simulation.Properties
This read-only property contains the physical properties object. For
information on its uses, see Properties Object.
Example
The following is an example of retrieval at the Flowsheet level:
Set physprops=properties

Simulation.Results
Returns a reference to the Results object.
For more information, see Results Object.

Simulation.RunMode
This Read/write property gives access to the run mode for the next simulation
run.
Valid options are "Steady State", "Initialization", "Dynamic", "Estimation",
"Optimization".
Example
Running a script from Flowsheet or Model:
Application.Simulation.RunMode = "Dynamic"
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Simulation.RunMode

Simulation.RunNumber
This read-only property returns the run number of the current simulation.
Example

4 Automation Methods and Properties 68


Running a script from Flowsheet or Model:
Dim iRun
iRun = Application.Simulation.RunNumber
Application.Msg "The run number is " & Cstr(iRun)

Simulation.Saved
This read-only Boolean property returns True if any modifications made to the
simulation document have been saved to disk. If the document has been
changed in memory since it was last written to disk, it returns False.
Example
Running a script from Flowsheet or Model:
Dim bSaved
' Get document modification state
bSaved = Application.Simulation.Saved
' write status to Simulation Message Window
if bSaved Then
application.msg "Document secure on disk"
else
application.msg "Document modified in memory"
end if

Simulation.ScriptIsRunning
Read only property which returns true if a script is currently being run.
Example
From external Microsoft Visual Basic:
If ACMApp.Simulation ScriptIsRunning then

Simulation.SpecState
This read-only property returns the specification status of the current
simulation. Can return the string values "Complete", "UnderFixed",
"OverFixed", "UnderInitial", "OverInitial".
Example
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Simulation.SpecState

Simulation.State
This read-only object returns the current run state. Valid run states are
"Paused", "Running", "Stepping" and "Ready".
Example
Running external Microsoft® Visual Basic®:

4 Automation Methods and Properties 69


Label1.Caption = ACMApp.Simulation.State

Simulation.Successful
Returns whether the previous simulation run or step is successfully
converged. Returns a logical value, True or False.

Note: The value of the property is undefined if no run has taken


place.

Example
Running a script from Flowsheet or Model:
Sub RunTestSimulation()
Dim ACMobj As Object
Set ACMobj = GetObject("d:\test.acmf")
ACMobj.Application.Visible = True

On Error Resume Next


ACMobj.Application.simulation.Run (True)
If Err.Number <> 0 Then
' got an error
MsgBox "Error " & Err.Number & " : " & Err.Description
Err.Clear
End If
On Error GoTo errorhandler
If ACMobj.Application.simulation.successful Then
MsgBox "last run was successful."
Else
MsgBox "last run was not successful."
End If
Exit Sub

errorhandler:
MsgBox "default error handler."

End Sub

4 Automation Methods and Properties 70


Simulation.Termination
This read-write property determines how a dynamic run terminates in the
current simulation. It can return the string values "AtTime", "OnIterations",
"TimeOrIterations", or "Never". See also Simulation.EndTime and
Simulation.EndStepCount.
• AtTime is equivalent to checking the checkbox in the Run, Run Options,
"Pause At" time. This means the simulation pauses automatically at the
Simulation.EndTime.
• OnIterations is equivalent to the Run, Run Options, "Pause After"
checkbox. This means the simulation pauses after the specified number of
communication intervals, which is specified via Simulation.EndStepCount.
• TimeOrIterations means that it pauses whenever one of the criteria is
satisfied, ie both checkboxes enabled.
• Never means that it ignores the settings, ie clears both checkboxes.
Examples
Stop at a time 0.3:-
application.simulation.endtime = 0.3
application.simulation.termination = "AtTime"

Step for 10 time intervals from current time then stop:-


application.simulation.endstepcount = 10
application.simulation.termination = "OnIterations"

Stop at a time 0.5 or after 4 time intervals whichever is sooner:-


application.simulation.endstepcount = 4
application.simulation.endtime = 0.5
application.simulation.termination = "TimeOrIterations"

Simulation.Time
This read-only property returns the current simulation time in communication
units. See also Simulation.DisplayTime.
Example
Running external Microsoft® Visual Basic®:
label1.caption = ACMApp.Simulation.Time

Simulation.Variables
This read-only property returns the total number of active variables in the
simulation.

Note: An active variable is a variable that occurs in an equation


in the current simulation.

4 Automation Methods and Properties 71


Example
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Simulation.Variables

Simulation Methods
The following methods are available for the Simulation object.
• Simulation.AddEstimateVariable()
• Simulation.AddExperiment()
• Simulation.AddSensitivityParameter()
• Simulation.AddSensitivityVariable()
• Simulation.ClearSensitivities()
• Simulation.CloseAllForms
• Simulation.CloseFormView(“FormName”)
• Simulation.CompileType
• Simulation.CreateFolder
• Simulation.CreateLibrary()
• Simulation.CreateStructure
• Simulation.CreateType
• Simulation.DisableSensitivities()
• Simulation.EnableSensitivities()
• Simulation.GetEstimationPredictedValues
• Simulation.GetSensitivityValue ( "Variable","Parameter" )
• Simulation.GetTypeText
• Simulation.Interrupt()
• Simulation.LaunchFormView("FormName")
• Simulation.NewExperiment()
• Simulation.Pause()
• Simulation.RemoveFolder
• Simulation.RemoveType
• Simulation.Reset()
• Simulation.ResetEstimation()
• Simulation.Restart()
• Simulation.Run()
• Simulation.SetTypeText
• Simulation.Step()

Simulation.AddEstimateVariable()
See the Modeling Language Reference, Chapter 2, Defining an Estimation
Simulation.

4 Automation Methods and Properties 72


Simulation.AddExperiment()
See the Modeling Language Reference, Chapter 2, Defining an Estimation
Simulation.

Simulation.AddSensitivityParameter()
You need to add the names of the known variables you use to get sensitivity
data. Known or Fixed variables are applied with the AddSensitivityParameter
method.

Note: You cannot apply parameters for use in calculating


sensitivities. If you call AddSensitivityParameter or
AddSensitivityVariable you must perform either an initialization
or steady simulation or dynamic step and ensure the sensitivities
are enabled BEFORE making a GetSensitivityValue call.

Example
From external Microsoft® Visual Basic®:
ACMApp.Simulation.AddSensitivityParameter "B1.In1.Flow"

Simulation.AddSensitivityVariable()
You need to add the names of the calculated variables you use to get
sensitivity data. Calculated or Free variables are applied with the
AddSensitivityVariable method.

Note: If you call AddSensitivityParameter or


AddSensitivityVariable you must perform either an initialization
or steady simulation or dynamic step and ensure the sensitivities
are enabled BEFORE making a GetSensitivityValue call.

Example
From external Microsoft® Visual Basic®:
ACMApp.Simulation.AddSensitivityVariable "B1.Out1.Temp"

Simulation.ClearSensitivities()
You can delete all the calculated variables and known variables that have
been previously applied to the current simulation.
Example
From external Microsoft® Visual Basic®:
ACMApp.Simulation.ClearSensitivities

Simulation.CloseFormView(“FormName”)
You can close a named form, such as a plot or a table. The argument is the
name of the form, including the block name if required. If the form is opened
more than once all instances will be closed.

4 Automation Methods and Properties 73


Example
Running a script from Flowsheet or Model:
Application.Simulation.CloseFormView("Plot1")
Application.Simulation.CloseFormView("B1.FeederTable")

Simulation.CloseAllForms
You can close all forms open in the application

Example
Running a script from Flowsheet or Model:
Application.Simulation.CloseAllForms

Simulation.CompileType (alternative CompileModel)


CompileType "TypeName"
This automation method will compile the given type. The method fails if the
type fails to compile.

Simulation.CreateFolder
CreateFolder "Folder path"
This automation method create a hierarchy of folders given by the folder path
argument. The folder names should be separated by ‘.’ characters. E.g.
Reactions.Methanol will create a new folder Methanol in the folder Reactions.
The folder Reactions will be created if necessary.

Simulation.CreateLibrary()
Creates a library from the current simulation, with the specified name.
Example
Running a script from Flowsheet or Model:
Application.Simulation.CreateLibrary("C:\project2\heaters.a
cml")

Simulation.CreateStructure
CreateStructure "Structure Type", "Structure Name"
This automation method creates an instance of the given structure type. The
type can be in any folder but the instance will be created in a folder under the
flowsheet Explore node with the same name as the folder containing the type.

Simulation.CreateType
CreateType "TypeName","Language Text","Folder" - "Folder"
is optional (alternative CreateModel)
This automation method will create a new type with the given name in the
Custom Modeling folder. The language text given should start with the
keyword for the type required e.g. Model followed by the given name and the

4 Automation Methods and Properties 74


language statements. It should terminate with End. You can provide the name
of a folder.

Simulation.DisableSensitivities()
You can temporarily hide the variables you have applied to the current
simulation. Later, you can re-activate the variables you previously applied to
the simulation.
Example
From external Microsoft® Visual Basic®:
ACMApp.Simulation.DisableSensitivities

Simulation.EnableSensitivities()
You can re-activate the variables you previously de-activated in the current
simulation.
Example
From external Microsoft® Visual Basic®:
ACMApp.Simulation.EnableSensitivities

Simulation.GetEstimationPredictedValues
This method returns the predicted values for the measured variables in the
given estimation experiment. If the experiment is steady state a single value
is returned. For dynamic experiments an array of values is returned, one
value for each time point in the experiment
GetEstimationPredictedValues(“Experiment 1”, “Variable 1”)

Note. Use after an Estimation run only.

Simulation.GetSensitivityValue ("Variable","Parameter")
Returns the sensitivity of an unknown variable with respect to a known
variable in a simulation.
Sensitivities are the values of partial derivatives of calculated variables with
respect to known variables.
Sensitivity information is available in the following run modes:
• Steady state
• Initialization
• Dynamic

Note: To get sensitivity information, you must not have


activated the ImpEuler (11.1) Integrator. VSIE

You must perform either an initialization or steady simulation or dynamic step


between defining your sensitivity parameters and variables and enabling them
and BEFORE making a GetSensitivityValue call.

4 Automation Methods and Properties 75


Example
From external Microsoft® Visual Basic®:
Dim Sens1
Sens1 = ACMApp.Simulation.GetSensitivityValue (
"B1.Out1.Temp","B1.In1.Flow" )

Simulation.GetTypeText (alternative GetModelText)


"Language Text" = GetTypeText "TypeName"
This automation method will get the defining text for a given type.

Simulation.Interrupt()
You can use the Simulation.Interrupt method to interrupt a running or
stepping simulation. If the simulation is not running or stepping then the call
is ignored. The parameter determines whether method should wait for the
simulation to stop (bWait is True) or return immediately (bWait is False). It
can take some seconds for a simulation to be interrupted. When using the
parameter as False, you can check when the interrupt has completed by
looking for a Simulation.State of “paused”.
Example
From external Microsoft® Visual Basic®:
AcmApp.Simulation.Run False
'other code here
ACMApp.Simulation.Interrupt true

Simulation.LaunchFormView("FormName")
You can open a named form, such as a plot or a table. The argument is the
name of the form, including the block name if required.
Example
Running a script from Flowsheet or Model:
Application.Simulation.LaunchFormView("Plot1")
Application.Simulation.LaunchFormView("B1.FeederTable")

Simulation.NewExperiment()
See the Modeling Language Reference, Chapter 2, Defining an Estimation
Simulation.

Simulation.Pause()
You can pause a simulation.
Example
Running a script from Flowsheet or Model:
Application.Simulation.Pause

4 Automation Methods and Properties 76


Simulation.RemoveFolder
RemoveFolder "Folder path"
This automation method removes a hierarchy of folders given by the folder
path argument. The folder names should be separated by ‘.’ characters. E.g.
Reactions.Methanol will delete the folder Methanol in the folder Reactions. The
method will fail if the folder is not empty except when it contains empty
folders itself.

Simulation.RemoveType (alternative RemoveModel)


RemoveType "TypeName"
This automation method will remove the given type from the simulation. The
method will fail if the type is in use on the flowsheet or in any other types.

Simulation.Reset()
You can return the current simulation to the default values of all the
variables. Optional logical argument specifies what will be reset.

Reset(True) resets everything


Reset(False) resets only free variables.

If the argument is omitted, it resets only free variables.


Example
Running a script from Flowsheet or Model:
Application.Simulation.Reset

Simulation.ResetEstimation()
Clears all estimated results, variables, and parameters.

Simulation.Restart()
You can return the current dynamic simulation to the state of the simulation
at time zero of the current simulation.
Example
Running a script from Flowsheet or Model:
Application.Simulation.Restart

Simulation.Run()
You can start a simulation run. An argument is required. Valid values are True
and False.
Use False to start the simulation and pass control on to the next line of
Microsoft Visual Basic.
Use True to start the simulation and only pass control on to the next line of
Microsoft Visual Basic when the run is complete. Note that in this case if the
run is unsuccessful an error will be raised which must be handled with Visual
Basic error statements or the Visual Basic program will terminate. When an

4 Automation Methods and Properties 77


error is raised the Visual Basic Err object can be used to obtain information
about the error. Note that for scripts in ACM the statement On Error Resume
Next must be used, On Error Goto cannot be used.

Example in Visual Basic


Sub RunTestSimulation()
Dim ACMobj As AspenModelerSimulation ' Available in the
ACM type library
Set ACMobj = GetObject("d:\test.acmf")
ACMobj.Application.Visible = True
ACMobj. RunMode = "Steady State"
On Error Resume Next
ACMobj.Run (True)
If Err.Number <> 0 Then
' got an error
MsgBox "Error " & Err.Number & " : " & Err.Description
Err.Clear
End If
On Error GoTo errorhandler
If ACMobj.Successful Then
MsgBox "last run was successful."
Else
MsgBox "last run was not successful."
End If
Exit Sub

errorhandler:
MsgBox "default error handler."

End Sub

Simulation.SetTypeText (alternative SetModelText)


SetTypeText "TypeName","Language Text" (alternative
SetModelText)
This automation method sets the defining text for a given type. The language
text given should start with the keyword for the type required e.g. Model
followed by the given name and the language statements. It should terminate
with End. This method does not compile the type.

4 Automation Methods and Properties 78


Simulation.Step()
You can step a dynamic simulation by one communication interval. An
argument is required. Valid values are True and False.
Use False to step the simulation and pass control on to the next line of
Microsoft® Visual Basic®.
Use True to step the simulation and only pass control on to the next line of
Microsoft Visual Basic when the step is complete.
Example
Running a script from Flowsheet or Model:
Application.Simulation.Step(False)

Properties Object
Properties and methods are available for the Properties object.

Properties of the Properties Object


The following properties are available for the Properties object:
• Properties.ComponentList
• Properties.ComponentListNames

Properties.ComponentList
This property returns a componentlist object specified by name.
Example
Running external Microsoft® Visual Basic®:
Set objPhysProps=ACMApp.Simulation.Properties
'get component list whose name is in text box
txtCompListname
Set objCompList=
objPhysProps.ComponentList(txtCompListName.Text)

Properties.ComponentListNames
This read-only property returns a collection containing the names of all the
component lists in the simulation.
Example
Running external Microsoft® Visual Basic®:
Dim objPhysProps
Set objPhysProps= ACMApp.simulation.Properties
' populate list box with names of componentlists
Dim Components

4 Automation Methods and Properties 79


lstNames.Clear
Set Components = objPhysProps.ComponentListNames
Dim sCurrentComp
For Each sCurrentComp In Components
lstNames.AddItem sCurrentComp
Next

Properties Methods
The following methods are available for the Properties object:
• Properties.AddComponentList()
• Properties.LoadPropertiesFile()
• Properties.RemoveComponentList()

Properties.AddComponentList()
This method creates a new component list with the specified name. It takes
one mandatory string argument, which is the name of the component set,
and one optional Boolean parameter, which, if true, causes the list to be
created as a component set. If the second argument is false or omitted, the
component list is created with the reference to the physical properties (which
do not have to be initialized beforehand).
Example
Running external Microsoft® Visual Basic®:
Private Sub btnAddComponentList_Click()
Dim sCompname As String
sCompname = txtComponentListName.Text 'get name from text
box
If 1 = chkIsSet Then 'look at check box' Component set
ACMApp.Simulation.Properties.addcomponentlist sCompname,
True
Else
ACMApp.Simulation.Properties.addcomponentlist sCompname
End If
End Sub

Properties.LoadPropertiesFile()
This method loads a physical properties file (.appdf or .aprpdf file) with the
specified name. It takes one mandatory string argument, which is the name
of file.
Example
Running external Microsoft® Visual Basic®:

4 Automation Methods and Properties 80


ACMApp.simulation.Properties.LoadPropertiesFile
"props1.appdf"

Properties.RemoveComponentList()
This method destroys the component list with the specified name. It takes
one string argument, which is the name of the component list to be deleted.
Example
Running external Microsoft® Visual Basic®:
ACMApp.Simulation.Properties.removecomponentlist "List1"

ComponentList Object
Properties only are currently available for the ComponentList object.

ComponentList Properties
The following properties are available for the ComponentList object.
• ComponentList.Components
• ComponentList.IsComponentSet
• ComponentList.Name
• ComponentList.Option
• ComponentList.OptionNames

ComponentList.Components
This read/write property is a string collection of the names of the components
in the component list.
Example
Running external Microsoft® Visual Basic®:
Private Sub btnGetComponentNames_Click()
' populate list box lstNames with list of components in
component
' list "complist"
Dim objPhysProps
Set objPhysProps=ACMApp.simulation.Flowsheet.Properties
Set objComponentList =
objPhysProps.ComponentList("CompList")
Dim comps
lstNames.Clear
Set comps = objComponentList.Components
Dim sCurrentComp

4 Automation Methods and Properties 81


For Each sCurrentComp In Components
lstNames.AddItem sCurrentComp
Next
End Sub

Note: You cannot edit the components object in situ—you must


first copy them to another collection, for example:

Set comps=objComponentList.Components
comps.RemoveValues("CH4")
comps.AddValues("CO2")
objComponentList.Components=comps
You cannot use the following:

objComponentList.Components.RemoveValues("CH4")

ComponentList.IsComponentSet
This read/write Boolean property determines whether the component list is a
component set or not.
Example
Running external Microsoft® Visual Basic®:
'Set whether component set based on checkbox
If 1 = chkIsComponentSet.Value Then
objComponentList.IsComponentSet = True
Else
objComponentList.IsComponentSet = False
End If

ComponentList.Name
This read-only string contains the name of the component list.
Example
Running external Microsoft® Visual Basic®:
Dim objPhysProps
Set objPhysProps= ACMApp.simulation.Properties
Set objComponentList =
objPhysProps.ComponentList("CompList")
MsgBox "Name: " & objComponentList.Name

4 Automation Methods and Properties 82


ComponentList.Option
This read/write property is a string collection of the names of the values for
the particular named option.
Example
Running external Microsoft® Visual Basic®:
Private Sub btnGetOption_Click()
' populate a list box with the allowed values for the
option
' whose name is in text box txtOptionName
Dim colOptionValues
Set colOptionValues =
objComponentList.Option(txtOptionName.Text)
Dim sOptionValue
For Each sOptionValue In colOptionValues
lstNames.AddItem sOptionValue
Next
End Sub

Note: You cannot edit the option object in situ, but must first
copy it to another collection, for example:

Set values1=objComponentList.Option("G1")
values1.remove("Full")
objComponentList.Option("G1")= values1
You cannot use the following:

objComponentList.Option.Remove("Full")

ComponentList.OptionNames
This read-only property is a string collection of allowed option names.
Example
Running external Microsoft® Visual Basic®:
Private Sub btnOptionNames_Click()
' load list box lstNames with option names for component
' list "ACompList"
Dim objPhysProps
Set objPhysProps=ACMApp.Simulation.Properties
Set objComponentList =
objPhysProps.ComponentList("ACompList")

4 Automation Methods and Properties 83


Dim colOptions
Set colOptions = objComponentList.optionnames
lstNames.Clear
Dim sCol
For Each sCol In colOptions
lstNames.AddItem sCol
Next
End Sub

OutputLogger Object
Properties and methods are available for the OutputLogger object.

OutputLogger Properties
The following properties are available for the OutputLogger object:
• OutputLogger.FileOutput
• OutputLogger.Height
• OutputLogger.Left
• OutputLogger.MessageCount
• OutputLogger.Messages
• OutputLogger.MessageText
• OutputLogger.Path
• OutputLogger.ScreenOutput
• OutputLogger.Top
• OutputLogger.Width

Note: These methods will fail if the messages window is not


currently being displayed. You can ensure that it is by using the
ActiveDocument.ShowMessagesWindow method.

OutputLogger.FileOutput
Returns or sets whether run-time output is sent to file.
Example
Running a script from Flowsheet or Model:
IF Application.Simulation.OutputLogger.FileOutput = False
THEN
Application.Simulation.OutputLogger.FileOutput = True
ENDIF

4 Automation Methods and Properties 84


OutputLogger.Height
Sets the height in points (there are approximately 72 points in an inch) of the
Simulation Messages window.
Example
Running a script from Flowsheet or Model:
Application.Simulation.OutputLogger.Height = 10

OutputLogger.Left
Sets the horizontal coordinate of the Simulation Messages window.
Example
Running a script from Flowsheet or Model:
Application.Simulation.OutputLogger.Left = 20

OutputLogger.MessageCount
Returns the number of lines of messages currently in the Simulation
Messages window. Note that this number can change rapidly as more output
is generated.
Example
Running a script from Flowsheet or Model:
MsgBox "Messages:" &
Application.Simulation.OutputLogger.MessageCount

OutputLogger.Messages
This read-only property is a collection of all the messages in the Simulation
Messages window.
Example
Running a script from Flowsheet or Model:
dim op
dim mescoll
dim acmapp
dim curmsg
set acmapp=application
set op=acmapp.outputlogger
set mescoll=op.messages
msgbox "number of lines in message window" & mescoll.count
for each curmsg in mescoll
msgbox curmsg
next

4 Automation Methods and Properties 85


OutputLogger.MessageText
This read/only property contains a single string which is all the lines present
in the Simulation Messages window returned as a single string, with each end
of line marked by a carriage return or line feed pair of characters.
OutputLogger.MessageText has two parameters:
• The first line to be returned (0…MessageCount-1)
• The last line to be returned (0..MessageCount-1)
If the second parameter is less than the first, or the first parameters is less
than zero, an error will be raised. If the second parameter is greater than the
upper limit then no error will be raised and as many lines as available will be
returned.
Example
Running a script from Flowsheet or Model:
MsgBox Application.Simulation.OutputLogger.MessageText(0,9)

OutputLogger.Path
Sets the path name for the logging file.
Example
Running a script from Flowsheet or Model:
Application.Simulation.OutputLogger.Path = "C:\My
Simulations\Output.txt"

OutputLogger.ScreenOutput
Sets whether messages are sent to the Simulation Messages window. Takes
the logical arguments True and False.
Example
Running a script from Flowsheet or Model:
Application.Simulation.OutputLogger.ScreenOutput = True

OutputLogger.Top
Sets the vertical coordinate of the Simulation Messages window.
Example
Running a script from Flowsheet or Model:
Application.Simulation.OutputLogger.Top = 45

OutputLogger.Width
Sets the width of the Simulation Messages window.
Example
Running a script from Flowsheet or Model:
Application.Simulation.OutputLogger.Width = 150

4 Automation Methods and Properties 86


OutputLogger Methods
The following methods are available for the OutputLogger object.
• OutputLogger.ClearWindow()
• OutputLogger.Print()
• OutputLogger.WriteFileHeader()

OutputLogger.ClearWindow()
You can clear the text from the Simulation Messages window.
Example
Running a script from Flowsheet or Model:
Application.Simulation.OutputLogger.ClearWindow

OutputLogger.Print()
You can send the contents of the Simulation Messages window to your default
printer.
Example
Running a script from Flowsheet or Model:
Application.Simulation.Run(True)
Application.Simulation.OutputLogger.Print

OutputLogger.WriteFileHeader()
When you set OutputLogger.FileOutput to true, a log file is opened to contain
the output logger messages. At the top of the file, there is normally a line
that specifies the user who opened the log file and when the file was opened.
The OutputLogger.WriteFileHeader method controls whether this header line
is written:

If WriteFileHeader Then
is
True (default) The header line is written
False The header line is not written

If you set the value of the WriteFileHeader method to False, you can compare
logger files generated at different times without the difference in the first line
appearing.
Example
Running a script from Flowsheet or Model which opens a log file without the
header line.
set logger=application.outputlogger
logger.writefileheader=false
logger.path="d:\temp\unittest.txt"
logger.fileoutput=true.

4 Automation Methods and Properties 87


Note: The state of WriteFileHeader is set before the path or
fileoutput properties because the line is written as the file is
opened.

Results Object
Properties and methods are available for the Results object.
Before using the Results object, you must call Results.Refresh() to ensure
access to all currently available snapshots and results.

Results Properties
The following properties are available for the Results object.
• Results.Interval
• Results.Limit
• Results.RegularSnapshot
• Results.ResultCount
• Results.SnapshotCount
• Results AutoSnapshot

Results.Interval
You can retrieve or set the simulation time interval at which snapshots are
taken.
Example
Running a script from Flowsheet or Model:
Application.Simulation.Results.Interval = 2.0
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Simulation.Results.Interval

Results.Limit
Returns or sets the maximum number of snapshots that can exist for the
current simulation. When this number of snapshots is reached, the oldest
automatically taken snapshot is deleted before a new snapshot is taken.
Example
Running a script from Flowsheet or Model:
Application.Simulation.Results.Limit = 20
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Simulation.Results.Limit

4 Automation Methods and Properties 88


Results.RegularSnapshot
Returns or sets whether regular snapshots are taken during a dynamic run.
Read/write Boolean.
Example
Running a script from Flowsheet or Model:
Application.Simulation.Results.RegularSnapshot = True

Results.ResultCount
Returns the number of results that are available for the current simulation.
This includes all kept results and results contained in result files.
Example
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Simulation.Results.ResultCount

Results.SnapshotCount
Returns the number of snapshots that are available for the current simulation.
Example
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Simulation.Results.SnapshotCount

Results.AutoSnapshot
Returns or sets whether snapshots are taken automatically when a simulation
is run in any run mode. Read/write Boolean.
Example
Running a script from Flowsheet or Model:
Application.Simulation.Results.AutoSnapshot = True

Results Methods
The following methods are available for the Results object.
• Results.Compress()
• Results.CopyValues()
• Results.Delete()
• Results.FindResult()
• Results.FindSnapshot()
• Results.GetResult()
• Results.GetSnapshot()
• Results.GetSnapshot().Converged
• Results.GetSnapshot().DateTime
• Results.GetSnapshot().Description
• Results.GetSnapshot().Export

4 Automation Methods and Properties 89


• Results.GetSnapshot().ExportasBinary
• Results.GetSnapshot().RunNumber
• Results.GetSnapshot().SimulationTime
• Results.Import()
• Results.Refresh()
• Results.Rewind()
• Results.TakeSnapshot()

Results.Compress()
You can reduce the size of the snapshot files in the working folder for the
current problem by using this method. If snapshots or results have been
deleted, compress will reclaim the space in the file.
Example
Running a script from Flowsheet or Model:
Application.Simulation.Results.Compress()

Results.CopyValues
You can take a snapshot or result and copy the values to the current
simulation. This has the same function as the CopyValues button on the
Advanced Copy dialog available from the Snapshot Management dialog box.
Application.Simulation.Results.CopyValues has two forms:
CopyValues aResult
This copies the values of all the variables in the same way as the CopyValues
button on the Snapshot Management dialog, and is the same as:
CopyValues aResult, True, True, True, True, True, True, "",
"~", False, False
The second form takes the following arguments:

Argument Type Example


Result Variant Typically, a variant equated to
the value returned by the
GetSnapshot or GetResult
methods
SourceFixed Boolean False
SourceFree Boolean True
SourceInitial Boolean True
DestinationFixed Boolean False
DestinationFree Boolean True
DestinationInitial Boolean True
SourcePath Text String "B1"
DestinationPattern Text String "~.Temp"
SourceStructural Boolean False
DestinationStructural Boolean False

4 Automation Methods and Properties 90


Note: The last two arguments are optional, and only have
meaning for results containing structural parameters that cause
structural changes. If both arguments are TRUE, then structural
changes will be applied.

To copy the values of all the variables in the same way as the
CopyValues button on the Snapshot Management dialog, use:

CopyValues aResult, True, True, True, True, True,


True, " ", "~"
Example
Running a script from Flowsheet or Model:
Dim aResult
Set aResult = Application.Simulation.Results.GetResult(1)
Application.Simulation.Results.CopyValues aResult, False,
True, True, False, True, True, "Reactor", "~.*Tray.Temp"
Dim aSnapshot
Set aSnapshot =
Application.Simulation.Results.GetSnapshot(2)
Application.Simulation.Results.CopyValues aSnapshot

Results.Delete()
You can delete an existing snapshot or result. The single argument is a
snapshot or result object returned by either GetSnapshot or GetResult.
Example
Running a script from Flowsheet or Model, this example deletes all snapshots
with the description "example":
Dim aSnapshot
Dim iCount
Application.Simulation.Results.Refresh
For iCount = 0 To
Application.Simulation.Results.SnapshotCount-1
Set aSnapshot =
Application.Simulation.Results.GetSnapshot(iCount)
If (aSnapshot.Description = "example") Then
Application.Simulation.Results.Delete (aSnapshot)
End If
Next

4 Automation Methods and Properties 91


Results.FindResult()
You can find a result from the description. As result descriptions are not
necessarily unique, this will find the first result with the given description. A
result object is returned.
Example
Running a script from Flowsheet or Model:
Set aResult =
Application.Simulation.Results.FindResult("Steady State")

Results.FindSnapshot()
You can find a snapshot from the description. As snapshot descriptions are
not necessarily unique, this will find the first snapshot or result with the given
description. A snapshot object is returned.
Example
Running a script from Flowsheet or Model:
Set aSnapshot =
Application.Simulation.Results.FindSnapshot("Steady State")

Results.GetResult()
You can select a result from a numbered list. The first result in the list is
numbered 0.The last item is numbered Results.ResultCount ( ) –1. Note that
all the properties available for GetSnapshot are also available for GetResult.
Example
Running a script from Flowsheet or Model:
Dim aResult
Set aResult = Application.Simulation.Results.GetResult(4)

Results.GetSnapshot()
You can select a snapshot from a numbered list. The first snapshot in the list
is numbered 0. The last item is numbered Results.SnapshotCount ( ) –1. Note
that all the properties available for GetResult are also available for
GetSnapshot.
Example
Running a script from Flowsheet or Model:
Dim aSnapshot
Set aSnapshot =
Application.Simulation.Results.GetSnapshot(4)

Results.GetSnapshot().Converged
Returns whether a selected snapshot (or result, if GetResult is used) was
converged (1 = converged, 0 = not converged). Integer, read-only.
Example

4 Automation Methods and Properties 92


Running a script from Flowsheet or Model:
Dim aSnapshot
Dim iCount
Application.Simulation.Results.Refresh
For iCount = 0 To
Application.Simulation.Results.SnapshotCount-1
Set aSnapshot =
Application.Simulation.Results.GetSnapshot(iCount)
If (aSnapshot.converged = 1) Then
application.msg asnapshot.description & "is converged"
End If
Next

Results.GetSnapshot().DateTime
Returns at what date and time a selected snapshot (or result, if GetResult is
used) was taken.
Example
Running external Microsoft® Visual Basic®:
Label1.Caption =
ACMApp.Simulation.Results.GetSnapshot(4).DateTime

Results.GetSnapshot().Description
Sets or returns the description name of a selected snapshot (or result, if
GetResult is used). String, read-write.
Example
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Simulation.Results.GetSnapshot(4).
Description

Results.GetSnapshot().Export
Exports a snapshot to an ASCII result file with an extension of .asnp. You can
then import the file into any simulation using the Results.Import method.
This command also works for GetResults.
Example
The following example will export the contents of snapshot number 4 to the
given file:
Application.Simulation.Results.GetSnapshot(4).
Export "\aspen\result1.asnp"

4 Automation Methods and Properties 93


Results.GetSnapshot().ExportasBinary
Exports a snapshot (but not results) to a binary file with extension .snp. You
can export a snapshot directly to the working directory of another simulation,
where it is picked up automatically by that simulation as a result.
Example
The following example exports the contents of snapshot number 4 to the
given binary file:
Application.Simulation.Results.GetSnapshot(4).
ExportasBinary "..\mysimulation\result1.snp"

Results.GetSnapshot().RunNumber
Returns the run number for the selected snapshot (or result, if GetResult is
used).
Example
Running external Microsoft® Visual Basic®:
Label1.Caption =
Application.Simulation.Results.GetSnapshot(4).
RunNumber

Results.GetSnapshot().SimulationTime
Returns at what simulation time a selected snapshot (or result, if GetResult is
used) was taken.
Example
Running external Microsoft® Visual Basic®:
Label1.Caption = ACMApp.Simulation.Results.GetSnapshot(4).
SimulationTime

Results.Import()
You can import a result from an ASCII result file into the current simulation.
It will be added as a kept result and will be included on saving changes to
your input file. The default file extension for ASCII result files is .asnp.
Example
Running a script from Flowsheet or Model:
Application.Simulation.Results.Import "\aspen\result1.asnp"

Results.Refresh()
Before using any of the Automation methods and properties, you need to
issue a Refresh command. This command ensures that automation has access
to all the currently available snapshots and results in the simulation.
If you do not issue a Refresh command, you may find that the snapshots and
results to which you have access do not match the snapshots and results in
the current simulation.
Example

4 Automation Methods and Properties 94


Running a script from Flowsheet or Model:
Application.Simulation.Results.Refresh
Running external Microsoft® Visual Basic®:
ACMApp.Simulation.Results.Refresh

Results.Rewind()
You can rewind to a snapshot. This causes the values of all variables in the
simulation to be set to the values stored in the snapshot. This has the same
effect as Rewind from the Snapshot Management dialog box.

Note: You cannot rewind a result.

Example
Running a script from Flowsheet or Model:
Application.Simulation.Results.Rewind aSnapshot

Results.TakeSnapshot()
You can take a snapshot of the current simulation results. Takes a string of
text as an argument for the snapshot name.
Example
Running a script from Flowsheet or Model:
Application.Simulation.Results.TakeSnapshot("test1")

UOM Object
The following methods are available for the UOM object. For more
information, see the Modeling Language Reference, Chapter 2, Using Units of
Measurement.
• Uom.AddUOMSet
• Uom.AddPhysicalQuantity
• Uom.DefineConversion
• Uom.SelectUOMSet
• Uom.ConvertToBaseUOM
• Uom.ConvertFromBaseUOM

Block, Stream, Structure and


Flowsheet Objects
All the properties of blocks and streams in the modeling language are
exposed as properties of the corresponding Microsoft Visual Basic objects.

4 Automation Methods and Properties 95


For example, to access the feed port object of a mixer M1 in the flowsheet,
you write the following:
Mixer = Simulation.Flowsheet.M1.feed
To access stem position variable in a valve block called V1:
Set VarInput = V1.ValveStemPosition
You can also use a number of additional properties and methods, which are
common to block, stream, and flowsheet objects. This section describes these
methods.
Each of these object types also has certain special methods that are unique to
each object type.

Methods Common to Block, Stream,


Structure and Flowsheet Objects
The following methods are common to block, stream, and flowsheet objects:

Method Description
Name() The name of the object relative to its parent model
GetPath() The full path to an object from the flowsheet
TypeName() The name of an objects type
BaseTypeName The BaseTypeName method returns the name of
the base type of an object that is the base of the
derivation tree if any. If the model is not derived it
will return the same as the TypeName method.
Resolve() Convert a string path to an object
Blocks() Collection of block objects
Block.IsKindOf Collection of block objects
Streams() Collection of stream objects
Ports() Collection of port objects
ControlPorts() Collection of control port objects
Forms() Collection of Form Objects
FindMatchingVariables() Collection of variables matching a given pattern
GetVariableValues() Collection of many values in one call (fast method)
UpdateVariables() Update the object variables with the values from
the server
Global() Property through which to access global variables
DisableIncrementalUpdate() Suspend incremental updates
EnableIncrementalUpdate() Resume incremental updates
BeginLongOperation() Disable server busy dialog boxes
EndLongOperation() Enable server busy dialog boxes
Invoke() Runs a named script
InvokeLibraryScript Runs a named library script
LaunchFormView() Display a model form
LaunchCustomFormView() Displays a form based upon a specified cusom ocx
control

4 Automation Methods and Properties 96


Name and GetPath Methods
All blocks and streams have a Name method and a GetPath method:

This method Returns a string which is


Name() The path to the object relative to its parent model
GetPath() The full path to an object

Example
The following examples show the use of GetPath and Name:
Str = B1.stage(1).GetPath 'result is "B1.stage(1)"
Str = B1.stage(1).Name 'result is "stage(1)"
In the case of a flowsheet block or stream that has a quoted name in the
language input file (for example, Streams("1") as MaterialStream;), the
Name method will also remove the Streams("") part of the path, as
illustrated in the next example:
Str = Streams("1").GetPath 'result is "Streams(1)"
Str = Streams("1").Name 'result is "1"

TypeName Method
The TypeName method returns the name of the type of an object.
Example
The following example shows the use of the TypeName method:
Str = Streams("1").TypeName 'result is "MaterialStream"

Resolve Method
In some situations, you may need to be able to convert a string that
represents the path to an object, to the object itself. To do this for block,
stream, and flowsheet objects, you can use the Resolve method, which takes
a string argument and returns an object.
Example
At the Flowsheet level:
' Resolve the block "Flash1"
dim b1
set b1 = resolve("Flash1")
application.msg "Resolve Flash1 gave us " & b1.getpath

'Resolve the stream "Stream1"


dim s1
set s1 = resolve("Stream1")
application.msg "Resolve Stream1 gave us " & s1.getpath

4 Automation Methods and Properties 97


' Get variable "MassHoldUp" from b1
dim var1
set var1 = b1.resolve("MassHoldUp")
application.msg "b1.Resolve MassHoldUp gave us " &
var1.getpath

' Get variable "TotalVolume" directly


dim var2
set var2 = resolve("Flash1.TotalVolume")
application.msg "Resolve Flash1.TotalVolume gave us " &
var2.getpath

4 Automation Methods and Properties 98


Example

The following automation example shows how to read the name of a variable
from an Excel sheet and write the value in the next cell.

Private Sub CommandButton1_Click()

Dim var As Object

Set acmObj = GetObject("d:\FiveTanks.acmf")

acmObj.Application.Visible = True

Set oFlowsheet = acmObj.Application.Simulation.Flowsheet

On Error Resume Next

For i = 1 To 10

Set var = oFlowsheet.Resolve(Sheet1.Cells(i + 1,


1).Value)

If Err.Number <> 0 Then

Err.Clear clear error

Sheet1.Cells(i + 1, 2).Value = "N/A"

Else

Sheet1.Cells(i + 1, 2).Value = var.Value

End If

Next

End Sub

ShowFlowsheetWindow
Show the flowsheet window associated with the hierarchy block. This method
will fail is the current items is not a hierarchy.
Optional arguments can be used to give the window position and size.
ShowFlowsheetWindow x position, y position, width, depth
Running a script in a hierarchy block:
ShowFlowsheetWindow 100,0,180,600

Blocks Collection Properties and Methods


You can access information about all the blocks on your flowsheet or in other
blocks or streams. Note that structures cannot contain blocks or streams. The
information about the blocks is returned as a collection. You can use the
standard collection properties and methods:

4 Automation Methods and Properties 99


Method or Description
Property
Count Integer, the number of block objects in the
collection
Item([integer] Index) Gets the block object at position Index in the
collection. The first item is at position 1, and the
last at position Count.
Item([string] Name) Returns the block object whose name matched
Name

You can use the information to read the names of the blocks on your
flowsheet and determine the models used by the blocks, and you can also use
the information in For loops.
Example
Using external Microsoft® Visual Basic®:
Dim BlockCollctn
Set BlockCollctn = ACMApp.ActiveDocument.Flowsheet.Blocks
ACMApp.Msg "Number of blocks on Flowsheet is " &
BlockCollctn.Count
FOR EACH i IN BlockCollctn
ACMApp.Msg "Block " & i.Name & " uses Model " &
i.TypeName & "."
NEXT
From a script at Flowsheet level:
Dim BlockCollctn
Set BlockCollctn = Blocks
Application.Msg "Number of blocks on Flowsheet is " &
BlockCollctn.Count
FOR EACH i IN BlockCollctn
Application.Msg "Block " & i.Name & " uses Model " &
i.TypeName & "."
NEXT

Block.IsKindOf
Returns true if the object accessed is of the type given, false if not. 1
argument is required which can be:
“Flowsheet“
“Hierarchy”
“Block”
“MaterialStream”
“ControlStream”

4 Automation Methods and Properties 100


“ConnectionStream”
“Stream”
Note that these are not exclusive so a material stream will return true with
the arguments “Stream” or “MaterialStream”.
Example
From external Microsoft Visual Basic:
for each blk in Blocks
if blk.IsKindOf("Hierarchy") then
application.msg "Hierarchy " & blk.name
for each sblk in Blocks
application.msg " " & sblk.name
next
else
application.msg blk.name
end if
next
In this example the blocks in a hierarchy are processed.

Streams Collection Properties and Methods


You can access information about all the streams on your flowsheet or in
other blocks or streams. Note that structures cannot contain blocks or
streams. The information about the streams is returned as a collection. You
can use the standard collection properties and methods:

Method or Description
Property
Count Integer, the number of stream objects in the
collection
Item([integer] Index) Gets the stream object at position Index in the
collection, the first item is at position 1, and the last
at position Count
Item([string] Name) Returns the stream object whose name matched
Name

You can use the information to read the names of the streams on your
flowsheet and determine the models used by the streams, and you can also
use the information in For loops.
Example
Using external Microsoft® Visual Basic®:
Dim Using external Microsoft Visual Basic:
Dim StreamCollctn
StreamCollctn = ActiveDocument.Flowsheet.Streams

4 Automation Methods and Properties 101


ACMApp.App.Msg "Number of Streams on Flowsheet is " &
StreamCollctn.Count
FOR EACH i IN StreamCollctn
ACMApp.Msg "Stream " & i.Name & " uses Stream Model " &
i.TypeName
NEXT
From a script at Flowsheet level:
Dim StreamCollctn
Set StreamCollctn = Streams
Application.Msg "Number of Streams on Flowsheet is " &
StreamCollctn.Count
FOR EACH i IN StreamCollctn
Application.Msg "Stream " & i.Name & " uses Stream Model
" & i.TypeName
NEXT

Structures Collection Properties and Methods


You can access information about all the structures contained in a block,
stream or structure. Note the flowsheet itself cannot contain structures. The
information about the structures is returned as a collection. You can use the
standard collection properties and methods:

Method or Description
Property
Count Integer, the number of structure objects in the
collection
Item([integer] Index) Gets the structure object at position Index in the
collection, the first item is at position 1, and the last
at position Count
Item([string] Name) Returns the structure object whose name matched
Name

You can use the information to read the names of the structures and
determine the models used by the structures, and you can also use the
information in For loops.
Example
Using external Microsoft Visual Basic:
Dim StructureCollctn
StructureCollctn = ActiveDocument.Flowsheet.B1.Structures
ACMApp.App.Msg "Number of Structures in B1 is " &
StructureCollctn.Count
FOR EACH i IN StructureCollctn

4 Automation Methods and Properties 102


ACMApp.Msg "Structure " & i.Name & " uses Structure Model
" & i.TypeName
NEXT

From a script at Flowsheet level:


Dim StructureCollctn
Set StructureCollctn = B1.Structures
Application.Msg "Number of Structures on Flowsheet is " &
StructureCollctn.Count
FOR EACH i IN StructureCollctn
Application.Msg "Structure " & i.Name & " uses Structure
Model " & i.TypeName
NEXT

Port and Control Ports Collection Methods and Properties


The Ports and ControlPorts methods return collections of port objects. The
Ports collection contains all the conventional ports and multiports, and the
ControlPorts collection contains all the control ports in the object. Note that
structures cannot contain ports. You can use the standard collection
properties and methods:

Method or Description
Property
Count Integer, the number of port objects in the
collection
Item([integer] Index) Gets the port object at position Index in the
collection, the first item is at position 1, and the
last at position Count
Item([string] Name) Returns the port object whose name matched
Name

Example
This script will print the names of all the ports in block "b1":
set b = Blocks("b1")
application.msg "Ports of " & b.name
for each p in b.Ports
application.msg " " & p.name
next
application.msg "Control ports of " & b.name
for each p in b.ControlPorts
application.msg " " & p.name
next

4 Automation Methods and Properties 103


FindMatchingVariables Method
The method FindMatchingVariables takes from 1 to 7 arguments. It returns a
collection of variable objects which match the specifications in the arguments
when they are applied to the current object. All the arguments are optional, if
no arguments are given all variables and parameters will be returned
including inactive ones.
Argument 1 is a string argument which is used as a pattern to match against
all the variables contained within the object. The pattern syntax is the same
as that used for snapshots and Variable Find.
Argument 2 is a string to match the spec attribute of the required variables.
This should be a delimited list of any combination of “Fixed”, “Free”,
“Rateinitial” or “Initial”. E.g. “fixed free initial” will return all but rateinitial
variables. It is case insensitive.
Argument3 is a string giving the variable type to be used. Only variables of
that type will be returned. It is case insensitive.
Argument 4 is Boolean and specifies if parameters should be included. The
default is true.
Argument 5 is Boolean and specifies if algebraic variables should be included.
The default is true.
Argument 6 is Boolean and specifies if state variables should be included. The
default is true.
Argument 7 is Boolean and specifies if inactive variables should be included.
The default is true.
Example
At the Flowsheet level:
'Get a collection of all fixed variables in block B1
set vars = blocks("B1").FindMatchingVariables("~",
“fixed”,””,false,true,true,false)
application.msg "Listing fixed variables for flowsheet..."
for each v in vars
application.msg " " & v.name & ".spec = " & v.spec
next
This will list out all variables in B1 with a spec of fixed excluding parameters
and inactive variables.

GetVariableValues Method
When values are required for many variables there is a considerable overhead
in performance getting values one at a time when they are required in an
external application such as Excel or in a Visual Basic application. This method
allows you to get many values in one call, which is much faster. It can be
used to get values for a list of variable paths, variable objects, or variable
collections in the same way as the UpdateVariables Method except that
GetVariableValues always requires an argument.

4 Automation Methods and Properties 104


Note that the method returns an array of variants that can hold values other
than numerical data. Care must be taken if a real array is used to receive
values as a failure will occur for non-numeric values e.g. from string
parameters.
Example
Set vars1 = ACMFlowsheet.FindMatchingVariables("B1~")
Set vars2 = ACMFlowsheet.FindMatchingVariables("B2~")
Set vars = ACMFlowsheet.NewVariableSet
vars.AddValues vars2, vars1
ACMFlowsheet.UpdateVariables vars
novars = 0
varvalues = ACMFlowsheet.GetVariableValues(vars)
For Each varvalue In varvalues
novars = novars + 1
Sheet1.Cells(novars + 1, 3) = varvalue
Next
In this example a collection of variable objects is assembled into vars and
then used in UpdateVariables to make sure the values are up to date and
then in GetVariableValues to get an array of values. The For Each statement
goes through each value in vars and places it in a cell in an Excel sheet.

UpdateVariables Method
When it is necessary to have up-to-date data for a variable, it is retrieved on
demand from the server. If you know in advance that you are going to access
a number of variables, it is more efficient to update all the relevant variables
in a single operation. The UpdateVariables method enables you to do this.
When it is used with no arguments, UpdateVariables updates all the variables
in the scope of the object on which it is invoked. It can also update a list of
variable paths, variable objects, or variable collections.
Example
Running a script at Flowsheet level:
B1.UpdateVariables 'Updates all the variables in the block
B1
Set var = B2.Height
UpdateVariables("B2.Vol",var) 'Updates the values of B2.Vol
and B2.Height
From external Microsoft® Visual Basic®:
ACMApp.Simulation.Flowsheet.B1.UpdateVariables 'Updates all
the variables in the block B1
Set var = ACMApp.Simulation.Flowsheet.B2.Height
ACMApp.Simulation.Flowsheet.UpdateVariables("B2.vol", var)

4 Automation Methods and Properties 105


'Updates the values of B2.Vol and B2.Height

Global Method
You can access most variables directly, using their property path from the
flowsheet. However, because global variables are not in the scope of the
flowsheet, the Global method is provided to enable you to access global
variables.
Example
The following example shows how to access the global variable "P_Max" in a
Flowsheet script:
Set var = Global.P_Max

Invoking Scripts
To invoke a script contained in a block, stream or in a flowsheet, use the path
to that script.
You can pass arguments to and receive arguments back from a library script.
Arguments added after the library name and script name will be passed into
the library script:
e.g. Flowsheet.B1.InvokeLibraryScript("Custom Modeling",
"LibraryScript","B1")
The script LibraryScript will receive the string B1 in the variable input(1).
Examples
Running a script at Flowsheet level from external Microsoft Visual Basic:
ACMApp.ActiveDocument.Flowsheet.SetUpScript
Running script at Block level from external Microsoft® Visual Basic®:
ACMApp.ActiveDocument.Flowsheet.B1.BlockScript
Running script at Flowsheet level:
SetUpScript
Running script at Block level from Flowsheet level:
B1.BlockScript

Note: You can also invoke scripts given a string path using the
Invoke method, for example:

Flowsheet.Invoke"B1.BlockScript"
is equivalent to:

Flowsheet.B1.BlockScript
To invoke a script that is in a library script's folder, use InvokeLibraryScript.
This takes the name of the library as the first argument and the name of the
script as the second argument, for example:

4 Automation Methods and Properties 106


Flowsheet.B1.InvokeLibraryScript"Custom Modeling",
"LibraryScript"
If the library is given as an empty string (that is, ""), all libraries are searched
to find the named script.

DisableIncrementalUpdate and EnableIncrementalUpdate


Methods
By default, whenever a change is made to the simulation that will require the
update of assignments, connections, or equations, the update happens
immediately. For example, the following script will perform two incremental
updates, one after each assignment:
'Incremental update happens after this assignment
B1.PropMode = "Local"

'and again after this assignment


B2.Nstages = 10
To batch together a number of simulation changes, the following methods are
provided on the Flowsheet object:

Method Description
DisableIncrementalUpdate Call this to stop incremental updates
EnableIncrementalUpdate Call this to enable incremental updates

The methods DisableIncrementalUpdate and EnableIncrementalUpdate


operate on a lock counter which is incremented by DisableIncrementalUpdate
and decremented by EnableIncrementalUpdate. This allows scripts called
within scripts to use Disable and EnableIncrementalUpdate without overriding
the lock on incremental updating that may have been established in the
calling script.
When a script is invoked via the GUI, the lock count is automatically restored
to its original state when the script completes. If these methods are used
from external automation, ensure that there are matching calls to
DisableIncrementalUpdate and EnableIncrementalUpdate.
Example
To batch the operations of the above script:
'do not update until we have completed edit
DisableIncrementalUpdate

B1.PropMode = "Local"
B2.NStages = 10

'incremental update happens after this command

4 Automation Methods and Properties 107


EnableIncrementalUpdate

BeginLongOperation and EndLongOperation Methods


Sometimes in a script, a lengthy operation may need to be performed. While
the script is executing, it is unable to process normal windows messages. If
the condition lasts a long time, a Server Busy dialog box is automatically
displayed. You can use the following methods to disable the display of this
dialog box:

Method Description
BeginLongOperation() Call this before starting the long operation
EndLongOperation() Call this after the operation is complete

Example
The following example shows the use of BeginLongOperation and
EndLongOperation:
BeginLongOperation 'Disable server busy dialogs
ExcelObject.Calculate
EndLongOperation 'Re-enable the server busy dialogs

Invoke Method
This method runs a script, given the path to that script.
Example
The following example shows the use of Invoke:
Invoke"B1.Initialize"

LaunchFormView, LaunchCustomFormView and


LaunchLibraryFormView Methods
These methods enable you to display a named form on a model.
LaunchFormView is used for a form that is defined within the model.
LaunchLibraryFormView was used for a form that is defined in a library.
Changes to the way form configuration data is saved in Aspen Custom
Modeler 2004.1 mean that LaunchLibraryFormView is becoming redundant.
To launch a form based on a custom ocx, use the new automation method:
LaunchCustomFormView.

LaunchCustomFormView Parameters
The LaunchCustomFormView parameters are:
LaunchCustomFormView(Progld As String, FormName = NULL As
String, x=0 As Integer, y=0 As Integer, cx=0 As Integer,
cy=0 As Integer).
This takes 1, 2 or 6 parameters:
• Progld is the progid of the custom form to be loaded.
• FormName is the caption to appear in the frame of this form.

4 Automation Methods and Properties 108


• The remaining parameters are the x, y co-ordinates and size of the form.
Example
The following example shows the use of LaunchFormView:
B1.LaunchFormView("AllVariables")

Forms Collection Methods and Properties


The Forms method returns collections of form objects. You can use the
standard collection properties and methods:

Method or Property Description


Count Integer, the number of port objects in the
collection
Item([integer] Index) Gets the port object at position Index in the
collection, the first item is at position 1, and the
last at position Count
Item([string] Name) Returns the port object whose name matched
Name

Example:
The following script prints the variables selected on table "Results" from block
B1.

for each s in B1.Forms("Results").VariablesPaths


set v = B1.Resolve(s)
application.msg s & " = " & v.value
next

VariablesPaths Property
VariablesPaths is the collection of strings which contains the names of the
variables selected on a form.

Example:
The following script prints the variables selected on table "Results" from block
B1.

for each s in B1.Forms("Results").VariablesPaths


set v = B1.Resolve(s)
application.msg s & " = " & v.value
next

Forms Property
Forms property is the collection of forms of the parent object.

4 Automation Methods and Properties 109


Example:
The following script prints the variables selected on table "Results" from block
B1.

for each s in B1.Forms("Results").VariablesPaths


set v = B1.Resolve(s)
application.msg s & " = " & v.value
next

Tasks Property
Tasks property is the collection of tasks of the owning object.
Example:
The following script prints the name of each task in the current object and
whether it is active or not.
for each task in tasks if task.active then
MsgBox task.name & " Task Active"
else
MsgBox task.name & " Task Inactive"
end if
next

Flowsheet-Specific Methods
The Flowsheet object supports all the methods common to flowsheets, blocks,
and streams. For more information on common methods, see Methods
Common to Block, Stream, and Flowsheet Objects:
• AddBlock()
• AddStream()
• RemoveBlock()
• RemoveStream()
• IsValidBlockName()
• IsValidStreamName()
• CreateTask()
• DeleteTask()
• EditTask()
• GetTaskText()
• CreateScript()
• EditScript()
• DeleteScript()
• GetScriptText()

4 Automation Methods and Properties 110


• StructureContainers
• AddStructureContainer
• RemoveStructureContainer

Editing the Flowsheet


You can use the following methods to edit a flowsheet:

Method Description
AddBlock([string] BlockType, Add a block of type BlockType to the
[optional, string] BlockName) flowsheet with name BlockName. If
BlockName is not given, an auto-
generated name is used. Returns the
block object that has been added.
AddStream([string] StreamType, Add a stream of type StreamType to the
[optional, string] StreamName) flowsheet with name StreamName. If
StreamName is not given, an auto-
generated name will be used. Returns the
stream object that has been added.
RemoveBlock([string] Removes the block BlockName from the
BlockName) flowsheet.
RemoveStream([string] Remove the stream StreamName from
StreamName) the flowsheet.
IsValidBlockName([string] Returns true if BlockName can be used as
BlockName) a valid name for a new block.
IsValidStreamName([string] Returns true if StreamName can be used
StreamName) as a valid name for a new stream.

Example
This flowsheet script example adds a block to the flowsheet, first checking
that the name is valid:
BlockType = "PID"
BlockName = "cntrl"
if (Not IsValidBlockName(BlockName) ) then
MsgBox "Block name """ & BlockName _
& """ is invalid or already exists"
else
AddBlock BlockType, BlockName

CreateTask (TaskName, TaskText)


CreateTask creates a new task at the flowsheet level. It takes two
parameters. The first is a string, which is the name of the task. The second is
a string, which contains the full text of the task (each line terminated by a
carriage return or a line feed).
Example
From a script at Flowsheet level:
tasktext="task Task1 runs when time == .1" & vbcrlf _
& "print ""task running"" ;" & + vbcrlf _

4 Automation Methods and Properties 111


& "end"
CreateTask "Task1" , tasktext

DeleteTask(TaskName)
DeleteTask deletes an existing task at the flowsheet level. It takes one string
parameter, which is the name of the task to be deleted.
Example
From a script at Flowsheet level:
DeleteTask "Task1"

EditTask(Taskname, TaskText)
Replaces the language text of TaskName with TaskText and recompiles.

GetTaskText(Taskname): result string


Returns the language text for the named task.

CreateScript(Scriptname, ScriptText)
Creates a new script called ScriptName and text ScriptText.

EditScript(Scriptname, ScriptText)
Replaces the language text of ScriptName with ScriptText.

DeleteScript(Scriptname)
Deletes script the script called scriptname.

GetScriptText(Scriptname): result string


Returns the language text for the named script.

StructureContainers
StructureContainers “Structure Container Name”
This automation method returns the structure container object with the given
name. Alternatively if the argument is omitted it returns a collection of
structure container objects
AddStructureContainer
AddStructureContainer "StructureContainer Name"
Creates a structure container object under the flowsheet with the given name.
RemoveStructureContainer
RemoveStructureContainer "StructureContainer Name"
Removes a structure container object with the given name from the
flowsheet.

4 Automation Methods and Properties 112


Stream-Specific Methods
You can use all the methods common to flowsheets, blocks, and streams on
the Stream object. For more information on common methods, see Methods
Common to Block, Stream, and Flowsheet Objects:
• IsControlSignal()
• InputPort()
• InputConnected()
• InputBlockPort()
• OutputPort()
• OutputConnected()
• OutputBlockPort()
• CanConnectInput()
• ConnectInput()
• CanConnectOutput()
• ConnectOutput()
For control signal streams, the following methods are also available:
• InputVariable()
• OutputVariable()

IsControlSignal Method
The Streams collection includes both conventional streams and control
signals. To distinguish a control signal from a conventional stream, the
IsControlSignal method returns True for control signals.
Example
This script will print the names of all control signals:
set coll = streams
for each s in coll
if s.IsControlSignal then
application.msg " " & s.Name & " is a control signal"
end if
next

Querying the Connectivity of a Stream


The following methods enable you to determine the topology of a flowsheet
by enumeration of its streams:

Method Description
InputPort() The stream's input port object
InputConnected() True if the streams input is connected
InputBlockPort() The block port to which the stream input is connected
OutputPort() The streams output port object

4 Automation Methods and Properties 113


OutputConnected() True if the streams output is connected
OutputBlockPort() The block port to which the stream input is connected

For control signals, the following methods are also provided:

Method Description
InputVariable() The variable the control signals input is connected to.
OutputVariable() The variable the control signal output is connected to.

Examples
The following flowsheet script prints the names of all the stream input and
output ports:
set coll = streams
for each s in coll
application.msg "The name of the Input Port of " & s.name
_
& " is " & s.InputPort.Name
application.msg "The name of the Output Port of " &
s.name _
& " is " & s.OutputPort.Name
next
This script prints the topology of the flowsheet:
set app = application
set coll = streams
app.msg "Now iterating through the streams"
for each s in coll
app.msg "Stream " & s.name
if s.InputConnected then
set p = s.InputBlockPort
set b = p.Parent
app.msg " Input is connected to " & p.GetPath _
& " of block " & b.name
if s.IsControlSignal then
app.msg " Input variable is " & s.InputVariable.Name
end if
else
app.msg " Is a Feed Stream"
end if
if s.OutputConnected then

4 Automation Methods and Properties 114


set p = s.OutputBlockPort
set b = p.Parent
app.msg " Output is connected to " & p.GetPath _
& " of block " & b.name
else
app.msg " Is a Product Stream"
end if
next

Changing the Connectivity of a Stream


To change the connectivity of the flowsheet, you can use the following
methods for flowsheet level streams:

Method Description
CanConnectInput ([string] True if the streams input can be connected
BlockPortName) to the named block port
ConnectInput ([string] Connects the stream input to the named
BlockPortName) block port
DisconnectInput() Disconnects the stream input
CanConnectOutput ([string] True if the streams output can be connected
BlockPortName) to the named block port
ConnectOutput ([string] Connects streams output can be connected
BlockPortName) to the name block port
DisconnectOutput() Disconnects the stream output

Control signals support an equivalent set of methods but the arguments


differ:

Method Description
CanConnectInput ([string] Returns true if the control signals input can be
VariablePath, [optional, connected to the named variable via the
string] ControlPort) specified control port. If the control port is not
specified then the default control port will be
used.
ConnectInput ([string] Connects the control signal input to the named
VariablePath, [optional, variable via the specified control port. If the
string] ControlPort) control port is not specified the default control
port will be used.
DisconnectInput() Disconnects the control signals input.
CanConnectOutput([string Returns true if the control signals output can be
] VariablePath, [optional, connected to the named variable via the
string] ControlPort) specified control port. If the control port is not
specified then the default control port will be
used.
ConnectOutput ([string] Connects the control signal output to the
VariablePath, [optional, named variable via the specified control port. If
string] ControlPort) the control port is not specified the default
control port will be used.
DisconnectOutput() Disconnects the control signals output.

4 Automation Methods and Properties 115


Examples
This flowsheet script will add a new block called Mixer and then connect
existing streams to the Mixer block:
AddBlock "Makeup", "Mixer"
Streams("IS0").ConnectOutput "Mixer.FeedInlet"
Streams("IS6").ConnectOutput "Mixer.RecycleInlet"
Streams("IS1").ConnectInput "Mixer.MixerOutlet"
This flowsheet script will add a control signal and a PID block, then connect
the input of the PID block to the variable Mixer.Ratio:
AddStream "ControlSignal", "c1"
AddBlock "PID", "Cntrl"
Streams("c1").ConnectInput "Mixer.Ratio"
Streams("c1").ConnectOutput "cntrl.pv"

Port Object
All the properties of ports in the modeling language are exposed as properties
of the port object. For example, to access the flow variable of the feed port
property of a mixer M1 in the flowsheet you can write:
FlowVar = Simulation.Flowsheet.M1.feed.flow
You can also use the following additional methods for port objects:

Method Description
Name() The name of the object relative to its parent model
GetPath() The full path to an object from the flowsheet
TypeName() The name of the type of an object
Resolve() Convert a string path to an object

Name and GetPath Methods for Ports


The Name method returns a string which is the path to the port relative to its
parent model. In contrast, the GetPath method will return the full path to the
port.
Example
The following examples show the use of Name and GetPath:
Str = B1.Feed.GetPath 'result is "B1.feed"
Str = B1.Feed.Name 'result is "feed"

4 Automation Methods and Properties 116


Testing Whether a Port is Connected
To determine whether a conventional port is connected, you can check the
value of the IsConnected parameter. If the port is a multiport, you must test
whether the Connection array is non-empty.
Examples
The following example tests whether a conventional port is connected.
In a script:
If( B1.Feed.IsConnected.Value ) then
application.msg "B1.Feed is connected"
End if

The next example tests whether a multiport feed is connected:


If( B1.Feed.Connection.Count > 0 ) then
application.msg "B1.Feed is connected"
End if
The next example iterates over the connection ports of a multiport:
For each p in B1.Feed.Connection
application.msg " connection " & p.Name
Next
In ACM modelling language:

If( Feed.IsConnected) then ...

Testing Whether a Port is Connected


to Hierarchy Connector or Is Linked
The IsLinked parameter can be used to test if a stream is connected to an off
sheet connector in a hierarchy block. It can also be used to test if a port in a
sub-model has been linked to a port in a containing model.
Examples
The following example tests whether a conventional port is linked.
From a script:

If( S1.Source.IsLinked.Value ) then


application.msg "S1.Feed is connected"
End If
In ACM modelling language:

If( Source.IsLinked) then ...

4 Automation Methods and Properties 117


Variable Object
All the language attributes of variables and parameters are exposed as
properties of the Variable object in Microsoft® Visual Basic®.
Example
From a script at Flowsheet level:
'Get the current value of temperature
realValue = B1.Temperature.value
'Change the current value of temperature
B1.Temperature.Value = 100.0
From external Microsoft® Visual Basic®:
Set var = ACMApp.ActiveDocument.Flowsheet.B1.Temperature
'Get the current value of temperature
realValue = var.value
'Change the current value of temperature
var.value = 100.0

Note: The following will not return the value of B1.Temperature:

realValue = B1.Temperature 'This is an error

Units of Measurement
For attributes that support UOM scaling (for example, value and derivative of
RealVariable types) the example calls under Variable Object.
To obtain the value of a variable in a specific set of units use the following
syntax:
'obtain the value in units of C
centigrade = B1.T.Value("C")

'set the value in units of F


B2.T.Value("F") = 1.8*centigrade + 32
There are three special unit strings:

"CurrentUnits" Scales the attribute to the current display units.


"BaseUnits" Forces the attribute to be returned in base units.
"GlobalUnits" Scales the attribute according to the current selected
global units set (for example, in US will be scaled to
Farenheight irrespective of whether the variables units
attribute has been set).

The current display units for a variable can be accessed via the units string
property, for example:

4 Automation Methods and Properties 118


UOMstring = B1.x.units
The correct global units for a variable can be looked up, even if the current
display units are different. For example, if the global UOM is set to SI but a
mass variable stemmass is set to be displayed in lbs then the following string
will return Kg:
B1.stemmass.defaultunit

Working with Set Attributes


When a variable attribute is a set, the object returned is a StringSet collection
object or IntegerSet collection object, as appropriate. This collection is a copy
of the attribute's value: it can be enumerated as per conventional collections,
and also supports AddValues and RemoveValues methods for modifying the
contents of the set collection.
Use StringSet and IntegerSet collection objects to overwrite the existing
contents of a set attribute. Note that changing the contents of the set
collections does not change the value of the attribute.
To create a new StringSet or IntegerSet collection object:
• Use either the NewStringSet method or NewIntegerSet method, as
appropriate. Both methods are available with any object that can contain
variables (for example, blocks, streams or ports).
To change the value of the set attribute:
• Assign the collection to the attribute.
Examples
The first example obtains the value of an attribute, modifies a collection, and
assigns the collection to the attribute:
set index1set = B1.index1.value 'Gets the value of the
stringset
index1set.RemoveValues "ABC","XYZ" 'Remove "ABC" and
"XYZ" from collection
index1set.AddValues "FGH" 'Add string "FGH"
B1.index1.value = index1set 'Assigns the set collection
to the modified stringset
The next example creates a new set object and assigns it to the attribute:
set myset = B1.NewStringSet 'Create a new string set
myset.AddValues "A1","A2" 'Add some strings
myset.AddValues("A3")
B1.index1.value = myset 'Assigns the set collection to
the new stringset
The final example shows the other methods available with StringSet and
IntegerSet collection objects:
set myset = B1.index1.value

4 Automation Methods and Properties 119


Application.msg myset.Name ' This is the full string set
as text
for I = 1 to myset.Count ' Can loop through the set
getting individual strings
Application.msg myset.Item(I)
next

About the History Method


The values of variables are saved for a simulation when:
• The Record property of the variables have been set to True before running
the simulation.
• In Run settings, Record History for All Variables was selected before
running the simulation.
The History method gives you access to the recorded history of a variable for
the current simulation run. The recorded history is a collection of values for a
variable, recorded over a period of time, at regular intervals.
This collection of values is built from the information stored in the server
when the history method is invoked. You can build the set of values in two
ways:
• Invoke the method with arguments. The order for the arguments is the
start time, the end time, and the interval.
• Invoke the method without arguments. The start time is 0, the end time is
the current time, and the interval is set to the current value of the
communication interval. When the specified end time is greater than the
current time, the current time is used.
The syntax for the History method is:
method history([in: real, optional] StartTime,
[in: real, optional] EndTime,
[in: real, optional] Interval)

result: history collection


The parameters are all optional and are as follows:

StartTime Time of the earliest point to be included in the history,


default=0.0
EndTime Time of the latest point to be included in the history,
default=current simulation time
Interval Time interval between points in the history.

To get the full history of a variable use the following syntax:


set hist = b1.x.history
When the history collection is returned, the actual StartTime, EndTime, and
Interval are available as read-only properties of the collection.

4 Automation Methods and Properties 120


Note. You should access the methods and properties on the
object returned by the history method rather than using the
history method again as this will get the history again.

e.g. b1.x.history.interval

If you have previously used the history method with arguments


to specify time range or interval the above statement will
overwrite that history with the default range and interval. Using
the history method repeatedly will also be slower.

Example
The following example shows the history starting from time 1 and ending at
time 2, with an interval of 0.1:
set hist = Blocks("B1").stage(1).T.history (1, 2, 0.1)
app.msg "History, number of data points: " &
cstr(hist.count)
app.msg " start time = " & cstr(hist.starttime)
app.msg " end time = " & cstr(hist.endtime)
app.msg " interval = " & cstr(hist.interval)

History Properties and Methods


Properties and methods are available for History.

History Properties
The parent property of the history collection will return the variable to which
the history applies.
The following properties are available for History:
• History.Count
• History EndTime
• History.Interval
• History.StartTime
• History.Units

History.Count
Returns the number of data points in this history. It is a read-only property.
Example
set hist = Blocks("B1").stage(3).T.history
npoints = hist.count

History.EndTime
Returns the end time of the history. It is read-only property.

4 Automation Methods and Properties 121


If invoked before any simulation has taken place or after the simulation has
been restarted, it returns -1. If invoked after an initialization or steady state
run, it returns 0.
Example
set hx = B1.x.history
Application.Msg "End time " & Cstr(hx.endtime)

History.Interval
Returns the value of the time interval which was set when the variable history
was created. It is read-only property.
Example
set hx = B1.x.history
Application.Msg "Interval " & Cstr(hx.interval)

History.StartTime
Returns the start time of the history (double). It is a read-only property.
If invoked before any simulation has taken place or the simulation has been
restarted, it returns -1.
If invoked after an initialization or steady-state run, it returns 0.
Example
set hx = B1.x.history
Application.Msg "Start time " & Cstr(hx.starttime)

History.Units
By default, the values returned by the collection are in the base units of the
variable. You can change the units by setting the unit's property:
property Units: type string
The interpretation of this string is the same as that described in Units of
Measurement. For example, to return the history in the current display units,
write:
hist.Units = "CurrentUnits"

Notes:

• The values stored in the history data are in the base units
of the variable

• No error is detected if the unit string is not compatible


with the base units of the variable. The value returned is still
in the base units.

Example

4 Automation Methods and Properties 122


The following example shows a history scaled in the current units, and
selected units:
' history scaled in the current units
set hist = B1.x.history
hist.units = "CurrentUnits"
uom = hist.units
val = hist.AtTime(2.0)
' history scaled in the selected units
hist.units = "C"
' for example in centigrade -- which has to be compatible
with the base
' units of the variable
valc = hist.AtTime(2.0)

History Methods
You can refresh the history by calling the GetHistory method, which takes the
same parameters as the variable's history method.
The following methods are available for History:
• History.AtTime(t)
• History.Item
• GetAtTime
• ForEach loops

History.AtTime(t)
This method interpolates in the available data points to return the value of
the variable at the specified time t, which is counted from the start time. If no
history data for the specified time is available, an error is detected and the
following message is printed in the Simulation messages window:
Error in script scriptname: "No History available"
Example
set hx = B1.x.history
t = 2.34
Application.Msg "Value at time " & Cstr(t) & " = " & Cstr
(hx.AtTime(t))

History.Item
A specific point may be indexed directly using the item method, for example:
set hist = B1.x.history
val = hist(1)

Note: The valid range for the item index is 1 to hist.Count.

4 Automation Methods and Properties 123


For Each Loops
The history collection can be enumerated in the conventional way using, a for
each loop, for example:
set hist = B1.x.history
for each v in hist
application.msg " " & v
next

Exploring Variable Time History


You can access the data points for each loop sequentially.
set hist = B1.x.history
for each p in B1.x.hist
Application.Msg " value " & Cstr(p)
next
An alternative way uses the item method:
set hist = B1.x.history
for i=1 to hist.count
Application.Msg "value " & Cstr(hist.item(i))
next
The time of the item(i) is StartTime + (i-1)*Interval. Note it starts with i=1,
not i=0, to return the first point (at the start time).

Examples of Exploring Variable Time History


The first example shows how to use variable time history for Aspen
Dynamics™, whereas the second example shows how to use variable time
history for Aspen Custom Modeler®.
Example 1: Aspen Dynamics
The following example shows how to retrieve the value of a variable from the
start of the simulation and export it into a spreadsheet, for a column created
for Aspen Dynamics:

' loop on the stages to get t, p, compositions


'
' this script writes the data in a spreadsheet
dim excel
set excel = getobject ("c:\My Documents\Book1.xls")
' name of the block
blockname = "B1"
' because this flowsheet is created with Aspen Dynamics,
the name of block
' has to be enclosed in the Blocks("xxxx") function.

4 Automation Methods and Properties 124


' list of the component names
' we assume that all the blocks within the column are using
the same
' componentlist (otherwise, you need to include this in the
loop)
set comps = Blocks(blockname).componentlist.components
icol = 1
' do a loop over history to set the time in the first
column in spreadsheet
set hist = Blocks(blockname).stage(1).T.history
dt = hist.interval
t = hist.starttime
excel.worksheets("Sheet1").Cells(1,icol).Value = "Time"
excel.worksheets("Sheet1").Cells(2,icol).Value = " "
for irow = 1 to hist.count
excel.worksheets("Sheet1").Cells(irow+2,icol).Value = t
t = t + dt
next
' do a loop over all the stages temperature
for istage = 1 to Blocks(blockname).nstage.value
icol = icol + 1
excel.worksheets("Sheet1").Cells(1,icol).Value = "T"
excel.worksheets("Sheet1").Cells(2,icol).Value = istage
irow = 0
for each point in
Blocks(blockname).stage(istage).T.history
irow = irow + 1
excel.worksheets("Sheet1").Cells(irow+2,icol).Value =
point
next
next
' do a loop over all the stages pressure
for istage = 1 to Blocks(blockname).nstage.value
icol = icol + 1
excel.worksheets("Sheet1").Cells(1,icol).Value = "P"
excel.worksheets("Sheet1").Cells(2,icol).Value = istage
irow = 0

4 Automation Methods and Properties 125


for each point in
Blocks(blockname).stage(istage).P.history
irow = irow + 1
excel.worksheets("Sheet1").Cells(irow+2,icol).Value =
point
next
next

' composition
for istage = 1 to Blocks(blockname).nstage.value
for each c in comps
' liquid mole fractions
icol = icol + 1
excel.worksheets("Sheet1").Cells(1,icol).Value = "x " &
Cstr(c)
excel.worksheets("Sheet1").Cells(2,icol).Value = istage
irow = 0
for each point in
Blocks(blockname).stage(istage).x(c).history
irow = irow + 1
excel.worksheets("Sheet1").Cells(irow+2,icol).Value =
point
next
' vapor mole fractions
icol = icol + 1
excel.worksheets("Sheet1").Cells(1,icol).Value = "y " &
Cstr(c)
excel.worksheets("Sheet1").Cells(2,icol).Value = istage
irow = 0
for each point in
Blocks(blockname).stage(istage).y(c).history
irow = irow + 1
excel.worksheets("Sheet1").Cells(irow+2,icol).Value =
point
next
next
next
Example 2: Aspen Custom Modeler

4 Automation Methods and Properties 126


The following example shows how to extract the simulation history from
Aspen Custom Modeler®, using a Microsoft® Excel macro:
The only difference is that you need to prefix all the variable with the name of
the object created to access Aspen Custom Modeler®.
Sub history()
Set ACM = GetObject("tank.acmf")

Set hist = ACM.flowsheet.B1.s.history


Sheet1.Cells(1, 1).Value = hist.starttime
Sheet1.Cells(2, 1).Value = hist.endtime
Sheet1.Cells(3, 1).Value = hist.Count
For i = 1 To hist.Count
Sheet1.Cells(i + 4, 1).Value = hist.starttime + (i - 1)
*
hist.interval
Sheet1.Cells(i + 4, 2).Value = hist.Item(i)
Next
End Sub

Other Custom Methods


This section describes other custom methods.

BaseTypeName
The BaseTypeName method returns the name of the base type of the
variable.
Example:
The following example shows the use of the TypeName method:
Str = Blocks("Reactor").T.BaseTypeName 'result is
"RealVariable"

Change TypeName Method


The TypeName method returns the name of the type of the variable.
Example:
The following example shows the use of the TypeName method:
Str = Blocks("Reactor").T.TypeName 'result is
"Temperature"

ConvertToBaseUOM and ConvertFromBaseUOM Methods


These methods take a real number and a unit string. ConvertToBaseUOM
converts the value of a real number to the variable's base units.

4 Automation Methods and Properties 127


ConvertFromBaseUOM converts the real number from base units to those of
the unit string.
Example
cent = temp.convertToBaseUOM(32, "F");
far = temp.convertFromBaseUOM(cent, "F");

DefaultValue Method
This method returns the default value of the variable

' set T_def to default value of T in block B1


T_def = blocks("B1").T.DefaultValue

FixedValue Method
This method sets the value of the variable to the value given and also sets
the value of the specification attribute to “Fixed”.
e.g. var.FixedValue = 12.3

FreeValue Method
This method sets the value of the variable to the value given and also sets
the value of the specification attribute to “Free”.

e.g. var.FreeValue = 12.3

GetPath Method
The following method returns the full path for the variable, for example,
"b1.in_p.F("CO")":
GetPath: result string

Note: The GetPath method always returns the full path of an


object.

InitialValue Method
This method sets the value of the variable to the value given and also sets
the value of the specification attribute to “Initial”. Using this method allows
you to change both the value and the specification of the variable with a
single statement, which improves performance and makes the script more
compact.
e.g. var.InitialValue = 12.3

IsAlgebraicVariable Method
The following method returns true if the variable is currently active as an
algebraic variable in the simulation:
IsAlgebraicVariable: result boolean

4 Automation Methods and Properties 128


IsHidden Method
The following method returns true for variables declared as hidden:
IsHidden: result boolean

IsInput Method
The following method returns true if the variable allows input control
connections:
IsInput: result boolean

IsOutput Method
The following method returns true if the variable allows output control
connections:
IsOutput: result boolean

IsParameter Method
The following method returns true if the variable is a parameter:
IsParameter: result boolean

IsStateVariable Method
The following method returns true if the variable is currently active as a state
variable in the simulation:
IsStateVariable: result boolean

Name Method
The following method returns the full path for the variable, for example,
"b1.in_p.F("CO")":
Name: result string

Note: Unlike GetPath, the Name method returns the full path for
variables, but the path relative to the parent for models.

Parent Method
The following method returns the port or model that contains the variable:
Parent: result object

Property Method
The Property method provides access to the properties of a variable by string.
Examples
' The value of derivative
val = var.Property("derivative")
' Set the variable value

4 Automation Methods and Properties 129


var.Property("value") = 10.0;
'set the value in Fahrenheit
var.Property("value", "F") = 10.0;

Reset Method
This will reset the named property to its default value.
Example
var.Reset("value");

TypeName Method
The following method returns the name of the type of the variable:
TypeName: result string

ValidValues Method
The following method returns the valid values that can be assigned to
Attribute:
ValidValues([in: optional, string, default="value"]
Attribute): result String collection

ValidValues: result String collection


This form is used to determine all the possible values for a variable defined as
a string parameter, for example:
Model fragment:
PARAMETER HXType USES stringparameter
Valid as stringset(["Shortcut","Hot Tube","Hot Shell"]);
value:"Shortcut";
END
CalcType as HXType (Description:"Calculation type for heat
exchanger");
External Microsoft® Visual Basic® fragment:
Dim coll As Object
Dim s As Variant

cbo.Clear

Set coll = MyBlock.CalcType.ValidValues


For Each s In coll
cbo.AddItem s
Next

4 Automation Methods and Properties 130


cbo.Text = Var.value
This fragment initializes a combobox (cbo) list with the range of values
available to CalcType. In this case "ShortCut", "Hot Tube", and "Hot Shell".

ValidValues(OptionalString) Method
ValidValues can optionally take a string to determine which attribute to
examine. This form is often used to determine the valid units available to a
variable.

Note: An error is raised if the variable attribute is undefined (for


example, no units).

Example
External Microsoft® Visual Basic® fragment:
Dim coll As Object
Dim s As Variant

cbo.Clear

On Error Resume Next


Set coll = Var.ValidValues("units")
If Err.Number = 0 Then
For Each s In coll
cbo.AddItem s
Next
cbo.Text = Var.units("CurrentUnits")
cbo.Visible = True
Else
cbo.Visible = False
End If
This fragment initializes a combobox (cbo) list with the range of units
available to Var. If no units are defined then the control is hidden.

Variable.IsKindOf
Returns true if the object accessed is of the type given, false if not. 1
argument is required which can be:
“IntegerParameter”
“LogicalParameter”
“IntegerSet”

4 Automation Methods and Properties 131


“Parameter”
“RealVariable”
“RealParameter”
“SlackVariable”
“StringParameter“
“StringSet”
“Variable”
Note that these are not exclusive so a string parameter type will return true
with the arguments “StringParameter” or “Parameter”.
Example
From external Microsoft Visual Basic:

set vars = FindMatchingVariables("~")


for each var in vars
if(var.IsKindof("IntegerParameter")) then
application.msg var.Name & " is a IntegerParameter"
elseif(var.IsKindof("RealParameter")) then
application.msg var.Name & " is a RealParameter"
elseif(var.IsKindof("LogicalParameter")) then
application.msg var.Name & " is a LogicalParameter"
elseif(var.IsKindof("IntegerSet")) then
application.msg var.Name & " is a IntegerSet"
elseif(var.IsKindof("StringParameter")) then
application.msg var.Name & " is a StringParameter"
elseif(var.IsKindof("StringSet" )) then
application.msg var.Name & " is a StringSet"
elseif(var.IsKindof("Parameter")) then
application.msg var.Name & " is a Parameter"
elseif(var.IsKindof("RealVariable")) then
application.msg var.Name & " is a RealVariable"
elseif(var.IsKindof("SlackVariable")) then
application.msg var.Name & " is a SlackVariable"
elseif(var.IsKindof("Variable")) then
application.msg var.Name & " is a Variable"
end if
next

4 Automation Methods and Properties 132


This example obtains all the variables in the current flowsheet and prints out
their name and type to the message window.

RealVariables Methods
These methods are specific to RealVariables.

InputVariable Method
Returns the name of the variable that is connected to an input variable by a
ControlSignal stream using this method:
InputVariable(): result variable object
Example
From external Microsoft® Visual Basic®:
Dim VarInput
Set VarInput = V1.ValveStemPosition.InputVariable
ACMApp.Msg VarInput & " is connected to the Valve V1 Stem
Position variable."

OutputVariables Method
Returns which variables are connected to an output variable by a
ControlSignal stream using this method.
OutputVariables: result variable object collection
The information about the variables attached to an output variable is returned
as a collection of variable objects. You can access the following properties
from the collection:

Property Meaning
Count Number of variables connected to the output
variable
Item(Index) The variable object at position Index in the
variable collections

Example
From external Microsoft® Visual Basic®:
Set VarOutput = B1.Out1.Temp.OutputVariables
ACMApp.Msg VarOutput.Count & " variable(s) is/are connected
to the output temperature of block B1."
for I = 1 to VarOutput.Count
ACMApp.Msg "Variable " & I & " is the variable " &
VarOutput.Item(I).Name
next

4 Automation Methods and Properties 133


Task Object
Event-driven tasks can be accessed as properties of their containing block,
stream, or flowsheet.
Example
From a script at Flowsheet level:
Task1.Active = True

From external Microsoft Visual Basic:

ACMApp.ActiveDocument.Flowsheet.Task1.Active = True

Note: Use the Resolve method if you need to give the name of
the task as a string variable:

taskname = "Task1"
on error resume next
set task =
Application.Simulation.Flowsheet.Resolve(taskname)
if Err.Number <> 0 then
Err.Clear ' task does not exist
else
task.Active = True
end if
The Task object has the following properties:
• Active
• LanguageText

Active Property
You can use this Boolean property to determine whether a particular task at
flowsheet level is active, and to set whether it is active.

Note: To be activated, a task must be event-driven (that is, it is


declared with the "RUNS [ONCE] WHEN condition" syntax). For
more information see the Modeling Language Reference.

Example
From a script at Flowsheet level:
if Task1.active then
MsgBox "Task Active"
else
MsgBox "Task Inactive"

4 Automation Methods and Properties 134


end if
Task1.Active=True

LanguageText Property
This is a read-only property that will return the language task for the task
object.
Example
From a script at the Flowsheet level
Text = Task1.LanguageText

Homotopy Object
The Homotopy object has properties and methods.

Homotopy Properties
The following properties are available for the Homotopy object.
• Homotopy.Count
• Homotopy.HomotopyEnabled
• Homotopy.Theta
• Homotopy.Variable

Homotopy.Count
Returns a count of the number of Homotopy variables currently in the
simulation.
Example
count = Homotopy.Count
"Number of Homotopy variables = " &CSTR(count)

Homotopy.HomotopyEnabled
Can be True or False. Controls whether the next run will use homotopy.
Example
Homotopy.HomotopyEnabled = True

Homotopy.Theta
Returns the current value of the Homotopy parameter. Value will be 0 before
a homotopy run has been performed. A value of 1 indicates that the last
homotopy run was successful.
Example
Theta = Homotopy.Theta
application.msg "value of theta is " &CSTR(theta)

4 Automation Methods and Properties 135


Homotopy.Variable
Variable(index) returns a string containing the name of the variable at
position index. Index is zero-based: 0 is the first element in the list.
Example
dim name
name = Homotopy.Variable(1)

Homotopy Methods
application.msg "Variable 1 is " &name

The following methods are available for the Homotopy object.


• Homotopy.AddTarget
• Homotopy.GetTarget
• Homotopy.RemoveAll
• Homotopy.SetTarget

Homotopy.AddTarget
The AddTarget method adds a homotopy variable, and optionally enables you
to set a target and the UOM of the target. The Target Value and UOM specifier
are optional. If you omit the Target Value, it is taken to be the current value,
and if you omit the UOM specifier, the UOM is taken to be the base UOM for
that variable.
Example
The following example adds the homotopy variable "FEEDEMB.TOTAL" and
specifies the target as 12000, and the UOM of the target as kmol/hr:
Homotopy.AddTarget "FEEDERMB.TOTAL", 12000, "kmol/hr"

Homotopy.GetTarget(VarName)
GetTarget gets the target value of the variable. It returns an error if you have
not added the variable name to the homotopy specification.

Homotopy.RemoveAll
The RemoveAll method clears the existing homotopy specification.
Example
Homotopy.RemoveAll

Homotopy.SetTarget
The SetTarget method changes a target value for a variable already added
using the AddTarget method and optionally enables you to set the UOM. You
must supply the target. If you omit the UOM, the units are assumed to be
base UOM for that variable.
Example

4 Automation Methods and Properties 136


The following example adds a variable using AddTarget, and then sets a
target value and UOM using SetTarget:
Homotopy.AddTarget "MEREACTOR.TEMP"
Homotopy.SetTarget "MEREACTOR.TEMP", 480, "F"

Optimization Object
The Optimization object has properties and methods.

Optimization Properties
The following properties are available for the Optimization object.
• Optimization.ControlElementTime
• Optimization.EndTime
• Optimization.EndTimeFixed
• Optimization.IsDynamic
• Optimization.LowerTimeBound
• Optimization.MaxMove
• Optimization.MaxMoveEnabled
• Optimization.MovingElementSizes
• Optimization.NumberOfElements
• Optimization.OptimizeFinalTime
• Optimization.PiecewiseLinear
• Optimization.UpperTimeBound

Optimization.ControlElementTime
Used for dynamic optimization only. Sets the time corresponding to a
particular control element. The number of control elements must previously
have been set to at least that number. The time cannot be set for the first
control element (because it is always at time zero).
Example
Optimization.NumberOfElements = 4
Optimization.EqualElementSizes = False
Optimization.EndTime = 20.0
‘ needn’t set element 1
Optimization.ControlElementTime(2) = 5.0
Optimization.ControlElementTime(3) = 10.0
Optimization.ControlElementTime(4) = 15.0

Optimization.EndTimeFixed
Used for dynamic optimization only. If this Read/Write Boolean property is
True then the EndTime for the simulation will not be changed in the course of
the optimization run.

4 Automation Methods and Properties 137


Example
Optimization.EndTimeFixed = False

Optimization.IsDynamic
Can be True or False. Set this to True for a dynamic optimization, or False for
steady-state optimization.

Optimization.LowerTimeBound
Used for dynamic optimization only. This Read/Write floating property is the
minimum value to which time may vary during the simulation run. It is only
relevant if the end time of the run is not fixed (see
Optimization.EndTimeFixed).
Example
Optimization.LowerTimeBound = 0.5

Optimization.MaxMove
Used for dynamic optimization only. This Read/Write floating property
determines the maximum amount that a control variable may change from
one element to the next. It is only enforced if the MaxMoveEnabled property
of the Control Variable is True.
Example
Optimization.MaxMoveEnabled ("UNIT1.Theta") = True
Optimization.PieceWiseLinear = True
Optimization.MaxMove ("UNIT1.Theta") = 21.4

Optimization.MaxMoveEnabled
Used for dynamic optimization only. This Read/Write Boolean property of a
control variable is True if there is a limit on the amount a control variable may
change in value from one control element to the next. It is used in
conjunction with the MaxMove property.
Example
Optimization.MaxMoveEnabled ("UNIT1.Theta") = True
Optimization.PieceWiseLinear = True
Optimization.MaxMove ("UNIT1.Theta") = 21.4

Optimization.MovingElementSizes
Used for dynamic optimization only. This Read/Write Boolean property is True
if the control element sizes are allowed to be varied during a simulation run.
Example
Optimization.MovingElementSizes = True

4 Automation Methods and Properties 138


Optimization.NumberOfElements
Used for dynamic optimization only. This Read/Write integer property sets the
number of control elements that span the time between time zero and the
simulation end time. Each control variable may have one value specified for
each control element, resulting in a set of values across time.
Example
Optimization.NumberOfElements = 10

Optimization.OptimizeFinalTime
Used for dynamic optimization only. This Read/Write Boolean property is True
if final time is to be optimized. The EndTimeFixed property should also be set
False if time is being optimized.
Example
Optimization.EndTimeFixed = False
Optimization.OptimizeFinalTime = True

Optimization.PiecewiseLinear
Used for dynamic optimization only. This Read/Write Boolean property is True
if piecewise linear control discretization is to be used, and False if piecewise
constant control discretization is to be used.
Example
Optimization.PiecewiseLinear = False

Optimization.UpperTimeBound
Used for dynamic optimization only. This Read/Write property is the
maximum value to which time may vary during the simulation run. It is only
of relevance if the end time of the run is not fixed (see
Optimization.EndTimeFixed).
Example
Optimization.UpperTimeBound = 20.0

Optimization Methods
The following methods are available for the Optimization object.
• Optimization.AddDynVariable
• Optimization.AddInteriorPoint
• Optimization.AddSSVariable
• Optimization.AddVariable
• Optimization.ClearVariables
• Optimization.SetControlElementValue
• Optimization.SetControlElementValueBounds
• Optimization.SetDynVariableParams
• Optimization.SetInitialParams

4 Automation Methods and Properties 139


Optimization.AddDynVariable
AddDynVariable: Is used to add a dynamic constraint to an optimization
simulation, using the following syntax:
Optimization.AddDynVariable "VariableName", Active, Handle

VariableName Must be the name of a variable in your flowsheet


Active True or False, Switches the constraint on or off.
Handle An output parameter. This will be set to a unique
value used to refer to this constraint when calling
other methods, i.e. SetDynVariableParams and
AddInteriorPoint

Example
dim Handle1
Optimization.AddDynVariable "UNI1.temp", TRUE, Handle1

Optimization.AddInteriorPoint
AddInteriorPoint: Is used to add an interior point to a dynamic constraint in
an optimization simulation, using the following syntax:
Optimization.AddInteriorPoint "VariableName",
InteriorPoint, Active, ElementSize, LowerBound, UpperBound,
Handle

VariableName Must be the name of a variable in your flowsheet


InteriorPoint The zero bases index number of the interior point
Active True or False, Switches the interior point constraint on
or off
ElementSize The size of the interior point expressed as a fraction of
the element
LowerBound The lower bound to be used for this interior point
during a dynamic optimization run
UpperBound The upper bound to be used for this interior point
during a dynamic optimization run
Handle This is the unique value returned by the
AddDynVariable method

Example
dim Handle1
Optimization.AddDynVariable "UNI1.temp", TRUE, Handle1
Optimization.SetDynVariableParams "UNI1.temp", TRUE, 2,
TRUE, 0.5, 2.0, Handle1
Optimization.AddInteriorPoint "UNI1.temp", 0, TRUE, 0.5,
0.25, 2.0, Handle1
Optimization.AddInteriorPoint "UNI1.temp", 1,
TRUE, 0.5, 0.75, 2.0, Handle1

4 Automation Methods and Properties 140


Optimization.AddSSVariable
AddSSVariable: Is used to add a steady state constraint to an optimization
simulation, using the following syntax:
Optimization.AddSSVariable "VariableName", LowerBound,
UpperBound, Active

VariableName Must be the name of a variable in your flowsheet


LowerBound The optimizer will attempt to solve the optimization
problem such that the value of the variable will not be
below this value during the simulation
UpperBound The optimizer will attempt to solve the optimization
problem such that the value of the variable will not be
above this value during the simulation
Active True or False, Switches the constraint on or off

Example
Optimization.AddSSVariable "UNI1.u", 0.5, 1.5, TRUE

Optimization.AddVariable
AddVariable is used to add variables to an optimization simulation, using the
following syntax:
Optimization.AddVariable "VariableName", "type"

VariableName Must be the name of a variable in your flowsheet


Type Can be Objective, Design, Initial, or Control. For
steady-state optimization, you must specify an
objective variable and a design variable. For dynamic
optimization, you must specify an objective variable
and at least one other type. Objective variables must
be Free or Initial or RateInitial variables. Design and
Control variables must be Fixed and the Initial variable
type must have an Initial or RateInitial specification.

Example
Optimization.AddVariable "UNI1.obj", "Objective"

Optimization.ClearVariables
This clears any existing optimization definitions.
Example
Optimization.ClearVariables

Optimization.SetControlElementValue
The number of the control element for which a value is being set. If using
Piecewise Constant Discretization then the number should be between 1 and
the number of elements(inclusive). If using Piecewise Linear Discretization
then the number should be between 1 and the number of elements+1
(inclusive). The extra final value corresponds to the value of the control
variable at the simulation final time.
Example

4 Automation Methods and Properties 141


Optimization.SetControlElementValue "UNI1.u", 3, 0.5

Optimization.SetControlElementValueBounds
SetControlElementValueBounds: Is used to set the upper and lower bounds of
a control variable for a particular control element, using the following syntax:
Optimization.SetControlElementValueBounds "VariableName",
Element, LowerBound, UpperBound

VariableName Must be the name of a variable in your flowsheet


Element The number of the control element for which a value is
being set. If using Piecewise Constant Discretization
then the number should be between 1 and the number
of elements(inclusive). If using Piecewise Linear
Discretization then the number should be between 1
and the number of elements+1 (inclusive). The extra
final value corresponds to the value of the control
variable at the simulation final time
LowerBound The value of the variable will not be allowed to drop
below this value within the specified element
UpperBound The value of the variable will not be allowed to exceed
this value within the specified element

Example
Optimization.SetControlElementValueBounds "UNI1.u", 3, 0.5,
1.5

Optimization.SetDynVariableParams
SetDynVariableParams: Is used to set the parameters for a dynamic
constraint in an optimization simulation, using the following syntax:
Optimization.SetDynVariableParams "VariableName",
FinalTimeOnly, InteriorPointsPerElement, Active,
FinalTimeLowerBound, FinalTimeUpperBound, Handle

VariableName Must be the name of a variable in your flowsheet


FinalTimeOnly True, if the constraint applies to the final time only.
False, if the constraint is a path constraint
InteriorPointsPerElemen The number of interior points per element
t
Active True or False, Switches the constraint on or off
FinalTimeLowerBound The lower bound to be used when the constraint
applies to the final time only
FinalTimeUpperBound The upper bound to be used when the constraint
applies to the final time only
Handle This is the unique value returned by the
AddDynVariable method

Example
dim Handle1
Optimization.AddDynVariable "UNI1.temp", TRUE, Handle1
Optimization.SetDynVariableParams "UNI1.temp", TRUE, 5,
TRUE, 0.5, 2.0, Handle1

4 Automation Methods and Properties 142


Optimization.SetInitialParams
SetInitialParams: Is used to set the initial value and the upper and lower
bounds of an initial variable, using the following syntax:
Optimization.SetInitialParams "VariableName", InitialValue,
LowerBound, UpperBound

VariableName Must be the name of a variable in your flowsheet


InitialValue The Initial value of the variable
LowerBound The minimum initial value
UpperBound The maximum initial value

Example
Optimization.SetInitialParams "UNI1.h", 3, 2.5, 3.5

OnLineLinks Object
This object provides access to the OnLine Links facility for automation. It has
methods and properties.
To access the object, the syntax is:
Set OLL = Simulation.OnLineLinks

OnlineLinks Properties
The following properties are available for the OnlineLinks object:
• ServerName
• IOTiming
• ReadingMode
• QualityHandling
• BoundsHandling
• BeforeSteadyStateRun
• AfterSteadyStateRun
• BeforeInitializationRun
• AfterInitializationRun
• BeforeDynamicStep
• AfterDynamicStep
• BeforeInitializationStep
• AfterInitializationStep
• Enable

ServerName
This property contains the name of the data server to be used by
OnLineLinks.
Example

4 Automation Methods and Properties 143


OLL.ServerName = "SST.SimulationOpcSvr.1"

IOTiming
This property contains the current setting of the IOTiming mechanism. It can
have either of the two values "Synchronous" or "Asynchronous".
Example
OLL.IOTiming = "Asynchronous"

ReadingMode
This property specifies the current mode to be used for reading variables. It
can have one of the two values "Cached" or "Device".
Example
OLL.ReadingMode = "Device"

QualityHandling
This property specifies how data with a quality that is not GOOD should be
handled. It can have one of the values "UseLast", "Override", or "Pause".
Example
OLL.QualityHandling = "Pause"

BoundsHandling
This property specifies how to handle values read from the data server that
are out of the simulation variable’s bounds. It can have one of the values
"Clip", "UseLast" or "Pause".
Example
OLL.BoundsHandling = "UseLast"

BeforeSteadyStateRun
This property indicates whether or not OLL data should be exchanged before a
steady-state run. This property takes a boolean argument which is TRUE for
the input variables and FALSE for the output variables. The property itself is
also boolean.
Example
' Disable reading before a steady state run
OLL.BeforeSteadyStateRun(TRUE) = FALSE
' Enable writing before a steady state run
OLL.BeforeSteadyStateRun(FALSE) = TRUE

AfterSteadyStateRun
This property indicates whether or not OLL data should be exchanged after a
steady-state run. This property takes a boolean argument which is TRUE for
the input variables and FALSE for the output variables. The property itself is
also boolean.

4 Automation Methods and Properties 144


Example
' Disable reading after a steady state run
OLL.AfterSteadyStateRun(TRUE) = FALSE
' Enable writing after a steady state run
OLL.AfterSteadyStateRun(FALSE) = TRUE

BeforeInitializationRun
This property indicates whether or not OLL data should be exchanged before
an initialization run. This property takes a boolean argument which is TRUE
for the input variables and FALSE for the output variables. The property itself
is also boolean.
Example
' Disable reading before an initialization run
OLL.BeforeInitializationRun(TRUE) = FALSE
' Enable writing before an initialization run
OLL.BeforeInitializationRun(FALSE) = TRUE

AfterInitializationRun
This property indicates whether or not OLL data should be exchanged after an
initialization run. This property takes a boolean argument which is TRUE for
the input variables and FALSE for the output variables. The property itself is
also boolean.
Example
' Disable reading after an initialization run
OLL.AfterInitializationRun(TRUE) = FALSE
' Enable writing after an initialization run
OLL.AfterInitializationRun(FALSE) = TRUE

BeforeDynamicStep
This property indicates whether or not OLL data should be exchanged before a
dynamic step. This property takes a boolean argument which is TRUE for the
input variables and FALSE for the output variables. The property itself is also
boolean.
Example
' Disable reading before a dynamic step
OLL.BeforeDynamicStep(TRUE) = FALSE
' Enable writing before a dynamic step
OLL.BeforeDynamicStep(FALSE) = TRUE

4 Automation Methods and Properties 145


AfterDynamicStep
This property indicates whether or not OLL data should be exchanged after a
dynamic step. This property takes a boolean argument which is TRUE for the
input variables and FALSE for the output variables. The property itself is also
boolean.
Example
' Disable reading after a dynamic step
OLL.AfterDynamicStep(TRUE) = FALSE
' Enable writing after a dynamic step
OLL.AfterDynamicStep(FALSE) = TRUE

BeforeInitializationStep
This property indicates whether or not OLL data should be exchanged before a
dynamic initialization step. This property takes a boolean argument which is
TRUE for the input variables and FALSE for the output variables. The property
itself is also boolean.
Example
' Disable reading before a dynamic initialization step
OLL.BeforeInitializationStep(TRUE) = FALSE
' Enable writing before a dynamic initialization step
OLL.BeforeInitializationStep(FALSE) = TRUE

AfterInitializationStep
This property indicates whether or not OLL data should be exchanged after a
dynamic initialization step. This property takes a boolean argument which is
TRUE for the input variables and FALSE for the output variables. The property
itself is also boolean.
Example
' Disable reading after a dynamic initialization step
OLL.AfterInitializationStep(TRUE) = FALSE
' Enable writing after a dynamic initialization step
OLL. AfterInitializationStep(FALSE) = TRUE

Enable
This property specifies whether OnLineLinks are enabled or not. It can have
one of the values "On", "ReadOnly" or "Off".
Example
OLL.Enable = "ON"

OnLineLinks Methods
The following methods are available for the OnlineLinks object.

4 Automation Methods and Properties 146


• AddInputVariable
• AddOutputVariable
• FindInputVariable
• FindOutputVariable
• RemoveInputVariable
• RemoveOutputVariable

AddInputVariable
This method adds a simulation variable to the OLL input variable list. The
method takes two arguments, the name of the simulation variable and the
OLL data server’s tag-name to which that variable is to be linked.
Example
OLL.AddInputVariable "b1.theta", "Simulated Card.Simulated
Node.COS"

AddOutputVariable
This method adds a simulation variable to the OLL output variable list. The
method takes two arguments, the name of the simulation variable and the
OLL data server’s tag-name to which that variable is to be linked.
Example
OLL.AddOutputVariable "b1.alpha", "Simulated
Card.Simulated Node.FLOAT"

FindInputVariable
This method returns an OLL Variable Object that is the OLL link in the OLL
input list, specified by its simulation variable’s name, and, optionally by the
corresponding OLL tag-name. Once the object is obtained, the properties of
the OLL Variable Object can be accessed.
Example
Set var1 = OLL.FindInputVariable("b1.theta")
Set var2 = OLL.FindInputVariable("b1.beta"," Simulated
Card.Simulated Node.FLOAT")

FindOutputVariable
This method returns an OLL Variable Object that is the OLL link in the OLL
output list, specified by its simulation variable’s name, and, optionally by the
corresponding OLL tag-name. Once the object is obtained, the properties of
the OLL Variable Object can be accessed.
Example
Set var1 = OLL.FindOutputVariable("b1.theta")
Set var2 = OLL.FindOutputVariable("b1.beta"," Simulated
Card.Simulated Node.FLOAT")

4 Automation Methods and Properties 147


RemoveInputVariable
This function removes a variable from the OLL Input variable list, specified by
the simulation variable’s name.
Example
OLL.RemoveInputVariable "b1.theta"

RemoveOutputVariable
This function removes a variable from the OLL Output variable list, specified
by the simulation variable’s name.
Example
OLL.RemoveOutputVariable "b1.alpha"

OLL Variable Object


This object provides access to the various properties of individual links in the
OLL input and output variable lists. In order to query or modify these
properties, the object must first be located using FindInputVariable or
FindOutputVariable, as appropriate.

OLL Variable Object Properties


The following properties are provided:
• VariableName
• TagName
• Mode
• Bias
• Gain
• OverrideValue
• ConversionUnits
• ChangeTolerance
• NoiseStandardDeviation

VariableName
This property contains the name of the simulation variable in the OLL link.
Example
Set var = OLL.FindInputVariable("b1.theta")
'Change the simulation variable in the link
Var.VariableName = "b1.alpha"

TagName
This property contains the OLL tag name for the variable in the link.
Example

4 Automation Methods and Properties 148


Set var = OLL.FindOutputVariable("b1.alpha")
Application.PrintToMessageWindow "b1.alpha is connected to"
& var.TagName

Mode
This property contains the mode of the variable in the link. It can be one of
the values "Manual" or "Auto".
Example
Set var = OLL.FindInputVariable("b1.gamma")
'Switch to manual mode
var.Mode = "Manual"

Bias
This property contains the bias applied to values read from or written to the
variable in the link.
Example
Set var = OLL.FindInputVariable("b1.theta")
'set the bias for this link to 0.1
Var.Bias = 0.1

Gain
This property contains the gain applied to values read from or written to the
variable in the link.
Example
Set var = OLL.FindOutputVariable("b1.alpha")
'set the gain for this link to 2.0
Var.Gain = 2.0

OverrideValue
This property contains the override value for the link.
Example
Set var = OLL.FindINputVariable("b1.gamma")
'Set override value to 0.25 (Simulation units)
Var.OverrideValue = 0.25

ConversionUnits
This property contains the conversion units for the link.
Example
Set var = OLL.FindInputVariable("b1.theta")
'Set conversion units to millimeters

4 Automation Methods and Properties 149


Var.ConversionUnits = "mm"

ChangeTolerance
This property contains the change tolerance for the link.
Example
Set var = OLL.FindInputVariable("b1.alpha")
Var.ChangeTolerance = 1e-3

NoiseStandardDeviation
This property is only meaningful for a variable in the output list, and specifies
the standard deviation of the random noise to be applied to the simulation
value before it is written to the OLL data server.
Example
Set var = OLL.FindOutputVariable("b1.alpha")
Var.NoiseStandardDeviation = 0.03

OLL Variable Object Methods


The OLL Variable object specifies the following methods:
• ReverseWrite
• ReverseRead

ReverseWrite
This method allows the current value for an input variable, which would
normally be read from the OLL data server, to be written to the server.

ReverseRead
This method allows the current value for an output variable, which would
normally be written to the OLL data server, to be read from the server.

CDI Object
Properties and methods are available for the CDI object.
For an example, see Using DMCplus.

CDI Properties
The following properties are available for the CDI object.
• StepResponseAbsoluteTolerance
• StepResponseAbsoluteRampTolerance
• StepResponseIntegrationsPerInterval
• StepResponseMaxIntervals
• StepResponseMinIntervals

4 Automation Methods and Properties 150


• StepResponseRelativeTolerance
• StepResponseRelativeRampTolerance
• StepResponseTimeInterval
• STMIntegrationStep
• STMTime
• STMZeroTolerance
• ZeroTolerance

StepResponseAbsoluteTolerance
Defines the absolute tolerance used to compute the responses of the
measured variables.
It has a default of 1.e-5 and the range is 0 to 1. You may need to decrease
this tolerance if your measured variables have very small values.
Example
StepResponseAbsoluteTolerance = stepabstol

StepResponseAbsoluteRampTolerance
Defines the absolute tolerance used to detect if any of the measured variables
are "ramping", that is, not at steady state. Ramping variables can exist even
though all the state variables in your flowsheet have settled down to steady
state after the step changes in the manipulated variables. You may need to
change this tolerance depending on the scaling and range of your measured
variables to avoid falsely detecting ramping variable.
It has a default of 1.e-2 and a range 0 to 1. Make sure the value is greater
than StepResponseAbsoluteTolerance.
Example
StepResponseAbsoluteRampTolerance = steprampabstol

StepResponseIntegrationsPerInterval
Specifies a positive integer defining the number of integration steps taken per
time interval used to generate the step response. The default is 10.
Example
StepResponseIntegrationsPerInterval Interval =
stepsperinterval

StepResponseMaxIntervals
Defines the maximum number of sample time intervals of the measured
variables to be calculated, with a default of 1000.

Note: The number of intervals produced will be a multiple of 30,


45, 60, 75, 90, 105 or 120, for compatibility with DMCPlus.

Example
StepResponseMaxIntervals = maxint

4 Automation Methods and Properties 151


StepResponseMinIntervals
Defines the minimum number of sample time intervals to be computed before
the step response is defined to be at steady state, with a default of 12. This
can be used to terminate the step response too early in the case of controllers
with "dead time" or in special cases where the response settles down before
moving to the true steady state later.
Example
StepResponseMinIntervals = minint

StepResponseRelativeTolerance
Defines the relative tolerance used to compute the responses of the measured
variables.
It has default 1.e-5 and range 0 to 1.
Example
StepResponseRelativeTolerance = stepreltol

StepResponseRelativeRampTolerance
Defines the relative tolerance used to detect if any of the measured variables
are "ramping", that is not at steady state. You may need to change this
tolerance depending on the scaling and range of your measured variables.
It has default 1.e-2 and range 0 to 1. Make sure the value is greater than
StepResponseRelativeTolerance.
Example
StepResponseRelativeRampTolerance = steprampreltol

StepResponseTimeInterval
Specifies a positive value interval time defining the sample times of the
response of the measured variables to steps in the manipulated variables.
Default is equal to the current value of the Communication time.
Example
StepResponseTimeInterval = intervaltime

STMIntegrationStep
Defines the step size used by the implicit fixed step Implicit Euler method
used to compute the approximation to the SEM. Default is 0.01 * STMTime.
Range is 0 to STMTime.
Example
STMIntegrationStep = h

STMTime
Defines the double precision time at which the State Transition Matrix (STM)
is required. There is no default. Range is 0 to 10E9.
Example

4 Automation Methods and Properties 152


STMTime = time

STMZeroTolerance
Rounds to zero any elements in the State Transition Matrix (STM) that are
below the value zerotol. Default is 1.e-16. Range is 0 to 1.
Example
STMZeroTolerance = zerotol

ZeroTolerance
Specifies what the CDI will return as a non-zero value in the state-space
matrices. Any value smaller than value is treated as zero. The default is 1.0e-
16.
Example
ZeroTolerance = value

CDI Methods
The following methods are available for the CDI object
• AddInputVariable()
• AddOutputVariable()
• Calculate()
• FilesRequired()
• GenerateStepResponse()
• GetMRIStatus()
• GetMRIValue ()
• GetNIStatus()
• GetNIValue()
• Inputs()
• MatricesRequired()
• MatrixCols("Matrix")
• MatrixNonZeros("Matrix")
• MatrixRows("Matrix")
• MatrixStatus("Matrix")
• MatrixValues("Matrix")
• NumberofInputs()
• NumberofOutputs()
• NumberofStates()
• Outputs()
• Reset()
• States()
• STMAddIgnoredState("var path")
• STMStates()

4 Automation Methods and Properties 153


AddInputVariable()
Used to add input variables to the interface.
Examples
AddInputVariable "var path"

Note: If the variable name includes double quotes, you must


insert two of these in the variable path for input and output
variables, for example:

CDI.AddInputVariable "Feed1.F(""CH4"")"

AddOutputVariable()
Used to add output variables to the interface.
Example
AddOutputVariable "var path"

Calculate()
Calculates and specifies the name of the MDL file. The filename argument
provides a file name prefix. If you provide a prefix, the file is named
prefix.dat. If you do not supply a file name prefix, the file is named cdi_.mdl.
Example
Calculate "filename argument"

GenerateStepResponse()
Requests computation of the response of the measured variables with respect
to perturbations in the manipulated variables. The results of the step
response calculation are output in the form of a DMCplus .mdl file.
Example
The following is an example of generating a DMCplus .mdl file:
Set Doc = ActiveDocument
Set MDL = Doc.CDI
MDL.Reset
MDL.AddInputVariable "b1.valueposition"
MDL.AddOutputVariable "b1.level"
MDL.GenerateStepResponse
MDL.StepResponseTimeInterval = 1
MDL.StepResponseIntegrationsPerInterval = 10
MDL.StepResponseMinIntervals = 30
MDL.StepResponseMaxIntervals = 800
MDL.Calculate "myresponse"

4 Automation Methods and Properties 154


FilesRequired()
Default is True (.dat files of matrices are created). If it is set to False, no .dat
files are created and all matrices can be accessed by automation only. This is
particularly useful if only automation access is required, or when the State
Transition Matrix (STM) is calculated, as the resulting file could be very large.

GetMRIStatus()
This command returns TRUE if the value is available and FALSE if not. It can
be used to stop a script failing if the value is unavailable.

GetMRIValue ()
This command returns the values of the MRI. If you have not requested this
value before the calculation, an error occurs in the script.

GetNIStatus()
This command returns TRUE if the value is available and FALSE if not. It can
be used to stop a script failing if the value is unavailable.

GetNIValue()
This command returns the values of the NI. If you have not requested this
value before the calculation, an error occurs in the script.

Inputs()
Returns an array of strings containing the variable names of each input, that
is the columns of the B and D matrices.
Example
Inputs()

MatricesRequired("Matrix")
Tells the interface which matrices to calculate. "Matrix" can be one or more of
A, B, C, D, G, RGA, NI, MRI, STM, or ALL. The default is "ALL".

Note: "STM" requests that the State Transition Matrix (STM) will
be generated at the next CDI Calculate call. "ALL" does not
include the STM matrix: it must be requested explicitly. For more
information on STM, see State Transition Matrix.

Example
MatricesRequired "matrix","matrix", ...

MatrixCols("Matrix")
Returns an integer array of size GetMatrixNonZeros("Matrix") of the rows of
the non-zero elements of Matrix.

4 Automation Methods and Properties 155


MatrixNonZeros("Matrix")
Returns an integer equal to the number of non-zeros in the sparsity pattern
for the given Matrix.
Example
MatrixNonZeros("Matrix")

MatrixRows("Matrix")
Returns an integer array of size GetMatrixNonZeros("Matrix") of the rows of
the non-zero elements of Matrix.
Example
MatrixRows("Matrix")

MatrixStatus("Matrix")
Returns a logical value. If the Matrix is available, True is returned; if it is not
available, False is returned.
Example
MatrixStatus("Matrix")

MatrixValues("Matrix")
Returns a double array of size GetMatrixNonZeros("Matrix") of the non-zero
values of Matrix.
Example
MatrixValues("Matrix")

NumberofInputs()
Returns an integer equal to the number of input variables in the state-space
model.
Example
NumberofInputs()

NumberofOutputs()
Returns an integer equal to the number of output variables in the state-space
model.
Example
NumberofOutputs()

NumberofStates()
Returns an integer equal to the number of state variables in the state-space
model.
Example
NumberofStates()

4 Automation Methods and Properties 156


Outputs()
Returns an array of strings containing the variable names of each output, that
is, the rows of the B and C matrices.
Example
Outputs()

Reset()
Clears the list of variables and resets the other parameters to their default
values.
Example
Reset

States()
Returns an array of strings containing the variable names of each state, that
is the columns of the A and C matrices
Example
States

STMAddIgnoredState("var path")
Used to define states which are ignored in the State Transition Matrix (STM)
calculation. This produces a "reduced" STM. By default, the STM is based on
ALL state variables.

STMStates()
Similar to the CDI States command, but this method returns a list of the
variable names in the columns of the (reduced) STM.

StructureContainer Object
The following methods are available for the StructureContainer object.
• AddStructure
• RemoveStructure
• Structures
• IsValidStructureName Method

StructureContainer Methods
AddStructure
AddStructure "Structure Type", "Structure Name"
This automation method adds an instance of the structure type given, with
the name given to the structure container.

4 Automation Methods and Properties 157


RemoveStructure
RemoveStructure "Structure Name"
This automation method removes the structure instance with the name given
from the structure container.

Structures
Structures “Structure Name”
This automation method returns the structure instance object with the given
name. Alternatively if the argument is omitted it returns a collection of
structure instances.

IsValidStructureName
IsValidStructureName "Structure Name"
This automation method returns true if the given name is a valid name for a
structure instance.

Defining an Estimation
Simulation
You can define and run steady-state and dynamic parameter estimation
simulations, as well as steady-state data reconciliation simulations.
For information on how to use the Estimation dialog box to interactively
define Estimation simulations, see the online Help on running Estimation
simulations.
You can also use automation methods and properties to define and run your
estimation simulation, and to view the results. One use of this is for reading
data or writing results to a spreadsheet package such as Microsoft® Excel.
For information on the solver options available for Estimation simulations, see
the Aspen Modeler Reference.

Defining Estimated Variables


You can define an estimated variable using the following automation method
APPLICATION.SIMULATION.ADDESTIMATEVARIABLE
“BlockName.VariableName”

BlockName The name of the block containing the variable you


are estimating
VariableName The name of the variable you are estimating

Repeat this statement once for each variable to be estimated.

Note: To make a variable an Estimated variable, it must have a


Spec of either Fixed or Initial.

4 Automation Methods and Properties 158


Spec of either Fixed or Initial.

Defining Estimated Variables Example


The following example shows two variables being defined as estimate
variables for an estimation simulation:

Application.Simulation.AddEstimateVariable "Reactor1.RK1"
Application.Simulation.AddEstimateVariable "Reactor1.RK2"

Defining Steady-State Estimation


Experiments
For each steady state experiment you must give an experiment name and
define the experiment as steady-state. You must also add measurement
points for the experiment. You can also specify changes that were made to
the values of fixed variables for each experiment.

Syntax for Defining Steady State Estimation Experiments


DIM ThisExp
SET ThisExp = APPLICATION.SIMULATION.NEWEXPERIMENT (
"ExperimentName", "STEADY STATE" )

ThisExp.ADDSSMEASUREPOINT "BlockName.VariableName",
MeasuredValue, MeasurementWeight
:

ThisExp.ADDFIXEDPOINT "BlockName.VariableName", FixedValue


:

ThisExp.SETWEIGHT ExperimentWeight
APPLICATION.SIMULATION.ADDEXPERIMENT(ThisExp)

ThisExp A reference to the new experiment object


ExperimentName A name you give for this experiment. This name is
used when reporting the results of the experiment
Steady State Keyword that identifies this experiment as a
steady-state experiment
BlockName Name of the block containing the variable for this
data point
VariableName Name of the variable for this data point
FixedValue Value of a fixed variable for this data point
MeasuredValue Value of a measured variable for this data point
MeasurementWeight Value of a weighting applied to this data point
ExperimentWeight Value of a weighting applied to this experiment

4 Automation Methods and Properties 159


Remarks on Defining Steady-State Estimation Experiments
You can define any number of experiments. The experiment is only used once
it has been added with the AddExperiment method. This means you can
define a number of experiments but use a subset of these for a given run.
This enables you to quickly test the effect of using different combinations of
experiments on the estimation results.
For each experiment you can define any number of measurement points and
fixed points.
When the heteroscedasticity parameter for a measured variable is not fixed,
the Automation Method AddSSMeasurepoint resets the estimated
heteroscedasticity parameter to 1.
If a variable name includes quotation marks, you must use double quotation
marks as shown in the following example.
For a detailed example of a steady-state estimation simulation, follow the
instructions in the online Help, under Examples, Steady-State Estimation of a
Methanol Reactor Example.

Example of Defining Steady-State Estimation Experiments


The following example shows two experiments being defined for a simulation.
The first measurement is given ten times the waiting of the second, and the
second experiment is given double the weighting of the first:

SET SSExpt1 = _
Application.Simulation.NewExperiment("Experiment1","Steady
State")
SSExpt1.AddFixedPoint "Rctr1.In1.Flow(""ReagentA"")", 1.0
SSExpt1.AddFixedPoint "Rctr1.In1.Flow(""ReagentB"")", 9.0
SSExpt1.AddSSMeasurePoint "Rctr1.Out1.x(""ReagentA"")",
0.092, 10.0
SSExpt1.AddSSMeasurePoint "Rctr1.Out1.x(""ReagentB"")",
0.904, 1.0
SSExpt1.SetWeight 1.0

SET SSExpt2 = _
Application.Simulation.NewExperiment("Experiment2","Steady
State")
SSExpt2.AddFixedPoint "Rctr1.In1.Flow(""ReagentA"")", 2.0
SSExpt2.AddFixedPoint "Rctr1.In1.Flow(""ReagentB"")", 8.0
SSExpt2.AddSSMeasurePoint "Rctr1.Out1.x(""ReagentA"")",
0.179, 10.0
SSExpt2.AddSSMeasurePoint "Rctr1.Out1.x(""ReagentB"")",
0.808, 1.0

4 Automation Methods and Properties 160


SSExpt2.SetWeight 2.0

Application.Simulation.AddExperiment(SSExpt1)
Application.Simulation.AddExperiment(SSExpt2)

Defining Dynamic Estimation


Experiments
For each experiment, you must give an experiment name and define the
experiment as dynamic. You must also add measurement values for the
experiment at time points during the experiment. You can add initial
conditions for the derivatives or state variables, and change the value of fixed
variables for each experiment.

Syntax for Defining Dynamic Estimation Experiments


DIM ThisExp
SET ThisExp = APPLICATION.SIMULATION.NEWEXPERIMENT (
"ExperimentName", "Dynamic" )

ThisExp.ADDDYNMEASUREPOINT "BlockName.VariableName",
MeasurementTime, MeasuredValue, MeasurementWeight
:

ThisExp.ADDFIXEDPOINT "BlockName.VariableName", FixedValue


:

ThisExp.AddFixedRampPoint "BlockName.VariableName",
FixedTimeValue, FixedValue
:

ThisExp.ADDINITIALPOINT "BlockName.VariableName",
InitialValue
:

ThisExp.ADDRATEINITIALPOINT "BlockName.VariableName",
RateInitialValue
:

ThisExp.SetWeight ExperimentWeight
APPLICATION.SIMULATION.ADDEXPERIMENT(ThisExp)

ThisExp A reference to the new experiment object


ExperimentName A name you give for this experiment. This name is
used when reporting the results of the experiment
Dynamic Keyword that identifies this experiment as a

4 Automation Methods and Properties 161


dynamic experiment
BlockName The name of the block containing the variable for
this data point
VariableName The name of the variable for this data point
FixedValue Value of a fixed variable for this data point
FixedTimeValue Time at which the associated fixed value should be
applied
InitialValue Value of an initial variable at time zero of the
experiment. The variable must have Spec = Initial
RateInitialValue Value of a derivative of a state variable at time
zero of the experiment. The variable must have
Spec = Initial
MeasurementTime Time at which the MeasuredValue is taken during
the experiment
MeasuredValue Value of a measured variable for this data point
MeasurementWeight Value of the weighting applied to this data point
ExperimentWeight Value of the weighting applied to this experiment

Remarks on Defining Dynamic Estimation Experiments


You can define any number of experiments. The experiment is only used once
it has been added with the AddExperiment method. This means you can
define a number of experiments but use a subset of these for a given run.
This enables you to quickly test the effect of using different combinations of
experiments on the estimation results.
If a variable name includes quotation marks, you must use double quotation
marks as shown in the following example.
For a detailed example of a dynamic estimation simulation, follow the
instructions in the online Help, under Examples, Reactor Dynamic Estimation
Example.

Example of Defining Dynamic Estimation Experiments


This example shows two dynamic experiment defined. The initial value of
methanol in a reactor is supplied for time zero. Measurements are taken at 10
minutes, 20 minutes, and 30 minutes into the experiment. The initial amount
of methanol in the reactor is different for the two experiments.

SET DynExpt1 = _

Application.Simulation.NewExperiment("DynamicExperiment1","
Dynamic")
DynExpt1.AddInitialPoint "Rctr1.x(""CH3OH"")", 0.012
DynExpt1.AddFixedPoint "Rctr1.Temp", 200.0
DynExpt1.AddFixedPoint "Rctr1.Press", 12.5
DynExpt1.AddDynMeasurePoint "Rctr1.x(""CH3OH"")", 0.1667,
0.019, 1.0
DynExpt1.AddDynMeasurePoint "Rctr1.x(""CH3OH"")", 0.3333,
0.038, 1.0

4 Automation Methods and Properties 162


DynExpt1.AddDynMeasurePoint "Rctr1.x(""CH3OH"")", 0.5000,
0.044, 1.0

SET DynExpt2 = _

Application.Simulation.NewExperiment("DynamicExperiment1","
Dynamic")
DynExpt2.AddInitialPoint "Rctr1.x(""CH3OH"")", 0.009
DynExpt2.AddFixedPoint "Rctr1.Temp", 200.0
DynExpt2.AddFixedPoint "Rctr1.Press", 12.5
DynExpt2.AddDynMeasurePoint "Rctr1.x(""CH3OH"")", 0.1667,
0.008, 1.0
DynExpt2.AddDynMeasurePoint "Rctr1.x(""CH3OH"")", 0.3333,
0.015, 1.0
DynExpt2.AddDynMeasurePoint "Rctr1.x(""CH3OH"")", 0.5000,
0.029, 1.0

Application.Simulation.AddExperiment(DynExpt1)
Application.Simulation.AddExperiment(DynExpt2)

Resetting Estimation Experiments


If you wish to change or remove some experiments before performing a new
estimation run you must first use the ResetEstimation method to remove all
existing experiments, and then add all of the experiments to be used for the
new run.

Syntax for Resetting Estimation Experiments


APPLICATION.SIMULATION.RESETESTIMATION
This automation method clears all of the experiments defined previously.

Example of Resetting an Estimation Experiment


The following example shows the use of ResetEstimation to clear any existing
experiments before adding the experiment SSExpt1. Without ResetEstimation,
if you ran the script twice it would fail the second time because it would be
trying to add an experiment with the same name as one that already exists.

SET SSExpt1 = _
Application.Simulation.NewExperiment("Experiment1","Steady
State")
SSExpt1.AddFixedPoint "Rctr1.In1.Flow(""ReagentA"")", 1.0
SSExpt1.AddFixedPoint "Rctr1.In1.Flow(""ReagentB"")", 9.0

4 Automation Methods and Properties 163


SSExpt1.AddSSMeasurePoint "Rctr1.Out1.x(""ReagentA"")",
0.092, 1.0
SSExpt1.AddSSMeasurePoint "Rctr1.Out1.x(""ReagentB"")",
0.904, 1.0
SSExpt1.SetWeight 1.0

Application.Simulation.ResetEstimation
Application.Simulation.AddExperiment(SSExpt1)

Accessing Results of Estimation


Simulations
You can access the results of an estimation simulation through the
automation interface. One use of this is for writing results to a spreadsheet
package such as Microsoft® Excel.
You can access:
• Individual estimated variable values.
• Individual correlation values.
• The complete correlation matrix.
• Individual standard errors (also known as standard deviations).

Accessing Estimated Variables' Values


You can access the values of the estimated variables using the following
syntax.

Estimated Variable Syntax


The syntax for accessing estimated variables' values is:
APPLICATION.SIMULATION.ESTIMATEDVALUE("EstVariable")

EstVariable The name of the estimated variable for which you


want the estimated value

Example of Accessing the Value of an Estimated Variable


This example shows how to access the value of an estimated variable
following a successful estimation simulation:

Dim EstVal1
EstVal1 = Application.Simulation.EstimatedValue("Rctr.K1")
Application.Msg "Estimated value for K1 is " +
Cstr(EstVal1)

4 Automation Methods and Properties 164


Accessing Standard Errors
After an estimation simulation is complete, you can access the standard
errors (also known as standard deviations) for the estimated variables.

Syntax for Accessing Standard Error


To obtain the standard error for a single estimated variable, use the following
syntax
APPLICATION.SIMULATION.DEVIATION ("EstVariable ")

EstVariable The name of the estimated variable for which you


want the standard error

Example of Accessing Standard Errors


In this example, the standard error of a variable is printed out after a
successful estimation run.

Dim StdDev
StdDev = Application.Simulation.Deviation("Reactor.K1")
Application.Msg "The standard error for K1 is " +
Cstr(StdDev)

Testing for Standard Error Results


You can test to see if the standard error results are available to download and
view.

Syntax for Testing for Standard Error Results


APPLICATION.SIMULATION .DEVIATIONARRAYPRESENT
The property DeviationArrayPresent returns a logical value.

Example of Testing for Standard Error Results


The following example verifies that the standard error (also known as
standard deviation) results are present. and if results are available, prints the
error values to the Simulation Messages window.
IF Application.Simulation.DeviationArrayPresent = True THEN
Application.Msg "Standard Error K1 = " + _
Cstr(Application.Simulation.Deviation("Reactor.K2"))
Application.Msg "Standard Error K2 = " + _
Cstr(Application.Simulation.Deviation("Reactor.K1"))
Application.Msg "Standard Error K3 = " + _
Cstr(Application.Simulation.Deviation("Reactor.K3"))
ELSE

4 Automation Methods and Properties 165


Application.Msg "Standard Error results not available"
END IF

Accessing Individual Correlation


Results
After an estimation run has completed, you can access correlation coefficients
between two estimated variables.

Syntax for Accessing Individual Correlation Results


To get the correlation between two of the estimated variables, use this
syntax:
APPLICATION.SIMULATION.CORRELATION("EstVar1", "EstVar2")

EstVar1, EstVar2 Names of the two estimated variables for the


correlation coefficient

Example of Accessing Individual Correlation Results


This example represents a script at flowsheet level that is invoked following
an estimation run. K1 and K2 are reaction rate constants. The correlation
between them is printed to the Simulation Messages window.

Dim Corr
SET Corr = Application.Simulation.Correlation
("Reactor.K1", _
"Reactor.K2")
Application.Msg "Correlation between K1 and K2 is " +
Cstr(Corr)

Accessing the Correlation Matrix


After an estimation simulation you can access the complete correlation matrix
for all of the estimated variables in your simulation.
The correlation matrix is returned as a two-dimensional array, representing a
square matrix. The size of the matrix is equal to the number of estimated
variables. The order of the estimated variables is the order in which the
estimated variables were added by the AddEstimateVariable method.

Syntax for Accessing the Correlation Matrix


Use the following syntax for accessing the correlation matrix:
APPLICATION.SIMULATION.CORRELATIONMATRIX
Note that the Correlation matrix is indexed from 0 to the number of estimated
variables minus one.

4 Automation Methods and Properties 166


Example of Accessing the Correlation Matrix
The following example shows the estimated variables being defined, a
previously defined experiment being applied, and the estimation simulation
running. In this example, the correlation matrix is 3 by 3. The column / row
order is in the order the estimated variables are added. The nine elements of
the correlation matrix are printed out to the simulation messages window.

Dim Sim, Corr


SET Sim =Application.Simulation
:
Sim.AddEstVar("Reactor.K1")
Sim.AddEstVar("Reactor.K2")
Sim.AddEstVar("Reactor.K3")
Sim.AddExperiment (DynExpt)
Sim.Runmode = "Estimation"
Sim.Run (True)
Corr = Sim.CorrelationMatrix
FOR i = 1 TO 3
FOR j = 1 TO 3
Application.Msg "Correlation " + CStr(i) + ", " + Cstr(j)
+ " = " _
+ CStr(Corr(i-1 ,j-1))
NEXT
NEXT

Testing for the Correlation Matrix


You can test to see if the correlation matrix is present before attempting to
access the matrix.

Syntax for Testing for the Correlation Matrix


APPLICATION.SIMULATION.CORRELATIONMATRIXPRESENT
The property CorrelationMatrixPresent returns a logical value.

Example of Testing for the Correlation Matrix


This example checks to see if the correlation matrix is present before loading
the matrix into an array:

Dim Corr
IF Application.Simulation.CorrelationMatrix Present = True
THEN

4 Automation Methods and Properties 167


Corr = Application.Simulation.Correlation Matrix
ELSE
Application.Msg "WARNING : Correlation Matrix Not Present"
END IF

4 Automation Methods and Properties 168


5 Synchronous and
Asynchronous Simulation
Runs

When running a simulation, you can choose whether control returns to


Microsoft® Visual Basic® only when the run finishes (synchronous run), or
immediately (asynchronous run).
This chapter describes:
• Synchronous runs
• Asynchronous runs

Using Synchronous Runs


In many cases, synchronous running behavior is appropriate. For an example
of code that results in synchronous running, see Synchronous Run Example.
However, the time that the following line takes to execute is indeterminate:
ATSimulation.Run (True)

Depending on the simulation, this step may take a few milliseconds or it may
last for days. This has the following disadvantages:
• For the duration of the run, the application driving your Aspen Modeler
product through Visual Basic® will stop processing events and be
unresponsive to users.
• In the case of a dynamic simulation, the driving program is unable to
retrieve and use values from the simulation while it is still running.
To resolve these issues, Aspen Modeler products support running simulations
asynchronously.

Synchronous Run Example


In the following code fragment of external Visual Basic® that runs Aspen
Custom Modeler®, because True is passed as the parameter to the run
method, control will not return to Visual Basic® until the run finishes or
terminates:

5 Synchronous and Asynchronous Simulation Runs 169


' Example of loading and running a simulation
Dim ACMApp As Object
Dim ACMDocument As Object
Dim ACMSimulation As Object
Set ACMApp = CreateObject("ACM Application")
' Use "ACM Application" for aspen custom modeler,
' Use "AD Application" for Aspen Dynamics
ACMApp.Visible = True
' Now that we have access to the app we can obtain
' other useful objects. First open a simulation document
Set ACMDocument = ACMApp.OpenDocument("d:\acm
simulations\tower.acmf")
' Note that the path is fictitious; you should substitute
' one that exists on your machine.
' Get a variable which points to the simulation
Set ACMSimulation = ACMApp.Simulation
' set the run mode to dynamic
ACMSimulation.RunMode = "Dynamic"
ACMSimulation.EndTime = 10.0
' and run the simulation, waiting for it to complete
ACMSimulation.Run (True)
' will get to this line when run completes
MsgBox "Run complete"
' save the changes
' and shut down the ACM application ACMApp.quit

Using Asynchronous Runs


To resolve the issues arising from synchronous running, Aspen Modeler
products support asynchronous simulation runs.
e.g. ATSimulation.Run (False)
will start the attached simulation run and will return immediately allowing the
calling program to proceed.
However care must be taken when running like this. For example:
• Because the driving program and the Aspen Modeler application are no
longer locked in step, commands sent from the driving program to the
Aspen Modeler application may occur at a different stage of the run each

5 Synchronous and Asynchronous Simulation Runs 170


time the programs are used, depending on how the operating system
allocates resources to each process. If for example you set the value of a
variable during a run it cannot be predicted when the value will be used. It
is best to pause the run before making such changes.
• Some OLE automation commands which worked previously when the run
was paused will give errors when the simulation is running e.g. editing the
flowsheet or trying to start a run again.
You can use automation events to let your driving program know when the
run has finished or has taken a step. This could be used for example to re-
enable facilities that needed to be disabled while the simulation was running.
You could also use them to get simulation results after each time step in a
dynamic run using the OnStepComplete event.

Asynchronous Run Example


The following code fragment is a rewritten version of the Synchronous Run
Example:
Dim ACMApp As Object
Dim ACMDocument As Object
Dim ACMSimulation As Object
Set ACMApp = CreateObject("ACM Application")
' Use "ACM Application" for aspen custom modeler,
' Use "AD Application" for Aspen Dynamics
ACMApp.Visible = True
' Now that we have access to the app we can obtain
' other useful objects. First open a simulation document
Set ACMDocument = ACMApp.OpenDocument("d:\acm
simulations\tower.acmf")
' Note that the path is fictitious; you should substitute
' one that exists on your machine.
' Get a variable which points to the simulation
Set ACMSimulation = ACMApp.Simulation
' set the run mode to dynamic
ACMSimulation.RunMode = "Dynamic"
ACMSimulation.EndTime = 10.0
' and run the simulation, not waiting
' for it to complete
ACMSimulation.Run (False)
Do
' Stay responsive to the user

5 Synchronous and Asynchronous Simulation Runs 171


DoEvents
' write out the simulation time to a label on
' the form of the driving program
lblTime.Caption=ACMSimulation.Time
Loop While (ACMSimulation.State = "Running")
' will get to this following line when run
' completes or fails
if ACMSimulation.Successful then
msgBox "Simulation Complete"
else
msgBox "Simulation Failed"
endif
' save the changes
' and shut down the ACM application
ACMApp.quit
Now the program driving Aspen Custom Modeler® through Visual Basic® can
remain responsive while waiting for the run to complete. It can also display
the current simulation time in a label on its own form.

Note: The value of ACMSimulation.Successful is indeterminate


until ACMSimulation.State ceases to be "running".

5 Synchronous and Asynchronous Simulation Runs 172


6 Using the Aspen Modeler
Type Libraries

Aspen Modeler type libraries are available for the following products:
• Aspen Custom Modeler
• Aspen Dynamics
• Aspen Water
• Aspen Adsim
• Aspen Chromatography
You can access the type libraries for the AspenTech products you have
installed.

Referencing a Type Library


from a Microsoft Visual Basic
Project
A type library is registered as part of the Aspen Modeler installation. To
reference it from a Microsoft Visual Basic project:
1 From the Project menu, click References.
2 Fom the Available References list, select the type library for your installed
AspenTech product, and then click OK.

The name also includes the current version number.

Using the Object Type Names in


Your Code
After you have referenced the type library in your Visual Basic project, you
can use object type names for your Aspen Modeler product in your Visual
Basic code. For example, if you are using Aspen Custom Modeler:

Dim ACM As AspenCustomModeler

6 Using the Aspen Modeler Type Libraries 173


Dim ACMSimulation As AspenModelerSimulation
Set ACM = New AspenCustomModeler
ACM.Visible = True
Set ACMSimulation =
ACM.OpenDocument("C:\aspen\fivetank.acmf")
ACMSimulation.Run False
This code fragment will launch Aspen Custom Modeler, make the application
visible, load up an input file, and start it running.

6 Using the Aspen Modeler Type Libraries 174


7 Solver Properties Dialog
Box

The Solver Properties dialog box enables you to change the default settings
for the numerical algorithms used in your simulation. For example, you may
need to change some algorithm properties to:
• Solve a difficult simulation or to improve the speed of a dynamic run.
• Get comprehensive diagnostic output from your simulation to determine
why a simulation does not converge or runs more slowly than expected.
Take care when changing solver properties and follow these guidelines:
• Never make a change without first thinking about why you are making the
change.
• Consider the side effects of changing a tolerance; you could lose accuracy
or cause problems elsewhere in your simulation.
• Do not change more than one property between runs; you need to
understand the effect of each change. Some combinations of solver
property changes can cause new problems.
If you find a combination of solver property changes makes your simulation
converge, consider which changes gave the improvement. As far as possible,
keep the maximum number of solver properties set to their default values.
This chapter describes the following:
• Diagnostics tab
• Tearing tab
• Tolerances tab
• Integrator tab
• Linear Solver tab
• Non-Linear Solver tab
• Optimizer tab
• Homotopy tab
• Estimator tab

Diagnostics Tab
The Diagnostics tab enables you to change the way diagnostic information is
displayed.

7 Solver Properties Dialog Box 175


Solver Reporting Level
You can change Solver Reporting Level to control the amount of detail sent to
the Simulation Messages window and the external simulation log file. The
higher the reporting level, the more detailed the resulting output.
The recommended print level depends on the type of work you are doing:

Type of Work Solver Reporting Level


General model and flowsheet design High or Medium
Running a tried and tested simulation Medium or Low
Diagnosing run time errors Very High or Maximum
Operator Training. Running a robust None
simulation

Properties Reporting Level


You can set the value of Properties Reporting Level to change the amount of
detail provided by the physical properties database you are using. The higher
the properties reporting level, the more detail you get about the information
that is passed between Aspen Modeler products and the properties database.
The recommended properties reporting level depends on your type of work:

Type of Work Properties Print Level


Running simulations and general design None
work
Simulation design for a properties Low
intensive flowsheet
Diagnosing properties run time errors High or Maximum

Watch Group
Use this option when you want to understand why a particular equation group
fails to converge. The most useful equation group to watch is typically the
first group that fails to converge.
You can define the number of an equation group for which you want to see
detailed convergence information in situations where:
• Convergence information for groups is normally suppressed.
• You do not wish to increase the Solver Reporting Level to High or above
and get information on ALL groups.
For example, during dynamic runs with the Explicit Euler, Implicit Euler, VSIE
or Runge Kutta 4 integrators, no information on convergence of groups is
displayed in the Simulation Messages window unless the Solver Reporting
Level is High or above. If you define an equation group number, you can see
the convergence of that group alone for each integration step during the
dynamic run.
This diagnostic is also helpful for estimation and optimization simulations.

7 Solver Properties Dialog Box 176


Note: You can obtain the equation group number from the
decomposition information in the Simulation Explorer.
Unconverged equation groups are shown with a red cross mark
on the equation group icon.

Watch Torn Sub-Group


You can use this option to specify a sub-group of a torn group for which you
want to see detailed convergence information in situations where:
• Convergence information for groups is normally suppressed.
• You do not wish to increase the Solver Reporting Level to High or above
and get information on ALL groups.
For example, during dynamic runs with the Explicit Euler, Implicit Explicit
Euler, VSIE or Runge Kutta 4 integrators, no information on convergence of
groups is displayed in the Simulation Messages window unless the Solver
Reporting Level is High or above. If you define an equation group number,
you can see the convergence of that group alone for each integration step
during the dynamic run.
This diagnostic is also helpful for estimation and optimization simulations.
To use this option, you must have entered the number of the torn group in
the Watch Group option.

Check Procedure Derivatives


You can specify that the analytical derivatives you return from your
procedures are checked against the numerical derivatives derived by Aspen
Modeler. This option can be used as a diagnostic tool to determine that your
procedures calculate derivatives correctly.
Available options are:

Option Meaning
Off (default) No derivative checking
Active Derivatives All active derivatives for the current run mode are
checked

Active Derivatives are derivatives of variables that are neither fixed nor
calculated from a previously solved equation (this may change between run
modes).

Note: After you have verified your procedure derivative


calculations, turn this option off, otherwise you do not gain the
speed benefits by returning derivatives from procedures.

Relative and Absolute Checking Tolerance


The Relative and Absolute Checking Tolerances determine the tolerance that
decides whether the analytical derivative returned from a procedure call is
acceptably close to the numerical derivative calculated by Aspen Modeler.

7 Solver Properties Dialog Box 177


The expression that determines whether the derivative returned from a
procedure is acceptable is:
(YK − X K ) < DerivRelTol ∗ X K +1 + DerivAbsTo l

Where
XK = Procedure derivative value calculated
numerically by Aspen Modeler
YK = Procedure derivative value calculated
analytically within the procedure
DerivRelTol = Relative Checking Tolerance
DerivAbsTol = Absolute Checking Tolerance
This means that if the procedure derivative calculated analytically within the
procedures is close enough to the numerically derived derivative, the
procedure calculated derivative is considered to be correct.

List variables in equivalences for highest variable steps and


residuals
When using the Diagnostics: Highest Variable Steps or Diagnostics: Highest
Residuals options, if the diagnostics involve an equivalened variable, the
entire list of variables in that equivalence are also output for clarity. If the
equivalence involves many variables this can cause a large amount of output.
Switching the option off stops the equivalence list being output and therefore
reduce the amount of output.

Tearing Tab
The Tearing tab enables you to control the options for procedure tearing.
Aspen Modeler is an equation-based simulator. For steady-state or
initialization simulations, and for re-initializations with Gear (11.) integrators,
or when the Re-initialize After Variable Step Change option is checked, all the
simulation equations are solved simultaneously. To make this task easier,
Aspen Modeler applies decomposition to break down the sets of equations into
groups. Each equation group is then solved in sequence.
The degree to which the equations can be broken down into groups depends
on the nature of the simulation. Typically, simulations of processes with
recycles require that more of the equations be solved together in one large
group. This is more difficult than solving many smaller groups.
Procedure tearing enables you to influence the way a simulation is solved and
to improve the decomposition by de-coupling the procedure inputs and
outputs.
Use procedure tearing to break the simulation down into smaller groups of
equations. Breaking down the simulation into smaller groups of equations
enables the simulation to solve more robustly and quickly for solution
methods that use decomposed equation groups.

7 Solver Properties Dialog Box 178


Note: Torn output variables are clipped to their bounds.

Procedure Tearing
You can set Procedure Tearing to the following options:

Procedure Tearing Action


None No procedure tearing
Update (default) Torn procedures are calculated throughout solution
of decomposed runs
Start Torn procedures are calculated once at the start of
the simulation
Complete Torn procedures are never calculated

None
All tears are ignored and the simulation treats all torn procedures as normal
procedures.

Update
Aspen Modeler calls each torn procedure once at the start of the simulation
with the initial values of the input variables. Aspen Modeler then fixes the
procedure outputs to those calculated during that call. They become, in effect,
fixed variables.
The remainder of the simulation is then solved as normal. After this, Aspen
Modeler compares the original Procedure outputs with those from the latest
solution. If these are the same to within a tolerance, the simulation is
converged. Otherwise Aspen Modeler updates the new procedure output
values, and the process is repeated until successive Procedure outputs are the
same.
A steady-state or initialization simulation solved with tearing gives the same
results as a simulation solved without tearing. Tearing only affects the ability
to find the solution and the time taken.
For a dynamic run , torn procedures are converged at initialization and re-
initialization.
For a dynamic run using Implicit Euler, Explicit Euler Runge Kutta 4 or Gear,
torn procedures are not re-converged after initialization.

Start
Each torn procedure is called once at the start of the simulation. The values of
the procedure input variables are the start values for the simulation. The
outputs remain fixed to the values calculated from this first procedure call for
the whole simulation.
Use Start mainly in dynamic simulations. This option is not normally
recommended for steady-state or initialization runs. Because the outputs from
the torn procedure are not updated, using them can result in solutions that do
not satisfy the torn procedures.

7 Solver Properties Dialog Box 179


Complete
The torn procedures are not called at all. The output variables are fixed to
their start values for the whole simulation.
Use Complete mainly in dynamic simulations. This option is not normally
recommended for steady-state or initialization runs. Because the outputs from
the torn procedure are not updated, using them can result in solutions that do
not satisfy the torn procedures.

Tear Update Strategy


You can define the algorithm used to converge torn procedures. The options
are:

Strategy Action
Direct Uses direct substitution
Wegstein Uses Wegstein acceleration

Direct substitution is a reliable method for converging torn procedures. If you


want a faster convergence, you can select the Wegstein convergence method.
In some cases you need to tune the Minimum and Maximum Acceleration
Parameters for Wegstein convergence.
If oscillatory convergence occurs in direct substitution, switch to Wegstein.
Then give values for the minimum and maximum acceleration parameters of
between 0 and 1. This may help to damp down any oscillations.
The Wegstein acceleration parameter is calculated for each torn variable with
these equations:
S
Q=
(S − 1)
G( X K ) − G ( X K −1 )
S=
X K − X K −1
Where:
X = Estimate of variable value
G(X) = Resulting Calculated variable value
K = Iteration number
The new estimate calculated by the Wegstein method is:
X K +1 = Q ∗ X K + (1 − Q ) ∗ G( X K )
The following table shows the effect of the value of Q on convergence:

If Then the effect is


Q<0 Accelerated convergence
Q=0 Direct substitution convergence
0<Q<1 Damped convergence

7 Solver Properties Dialog Box 180


The value of Q causes oscillatory behavior, and perhaps divergence, when
greater than 1, and monotonic divergence when too negative. For this reason,
the value of Q calculated by the Wegstein method is bounded by a Minimum
and Maximum Acceleration Parameter.
The Direct substitution method can be derived from the Wegstein equation as
a limiting case when Q = 0. With Q = 0 the Wegstein equation becomes:
X K +1 = G( X K )
This means that the estimate of the value of the variable at the next
convergence iteration is simply the calculated value for the current iteration.

Relative and Absolute Tear Tolerance


For runs using the Update option, you can control the accuracy within which a
tear is converged, using relative and absolute tolerances.
Aspen Modeler uses these tolerances to determine if a tear is converged. The
simulation is converged when the change in each output variable from the
torn Procedure satisfies the following inequality:
abs ( X K +1 − X K ) < Tearreltol ∗ abs ( X K +1 ) + Tearabstol
Where:
Error! = Value of Procedure output variable after k
Objects iterations
cannot
be
created
from
editing
field
codes.
Error! = Value of Procedure output variable after k+1
Objects iterations
cannot
be
created
from
editing
field
codes.
Tearabstol = Value of Absolute Tear Tolerance
Tearreltol = Value of Relative Tear Tolerance

Minimum and Maximum Acceleration


The minimum and maximum acceleration are used to determine the stability
and speed of the Wegstein convergence option for Tear Update Strategy.
The Wegstein acceleration parameter needs limits to avoid oscillations and/or
divergence. The default values of the minimum and maximum acceleration of
-5 and 0 are sufficient for most simulations.

7 Solver Properties Dialog Box 181


Normally, you should use the maximum acceleration of 0. If the tear
convergence is slow, you can use smaller values of the minimum acceleration,
such as -25 or -50.
For non-divergent oscillatory behavior, use values for maximum and
minimum acceleration between 0 and 1.

Maximum Number of Tear Iterations


The maximum number of tear iterations defines the tear iterations limit for
steady state and initialization simulations using procedure tearing. The value
can be any positive integer. If you define the maximum number of tear
iterations to 0, there is no limit to the number of tear iterations.

Tolerances Tab
The Tolerances tab enables you to change the options for controlling
tolerances, and to control solver scaling and the elimination of equivalence
equations.
You can change the value of the tolerances to affect the speed and accuracy
of the solution under most solution methods available.

Relative and Absolute Variable Tolerance


The relative and absolute variable tolerances are used to:
• Converge non-linear equation groups when the convergence criterion
includes a test on variable convergence.
• Determine whether the estimated local integration error for a variable is
acceptable with the Gear (11.1) or VSIE integrators.
The test used for the two cases above is as follows:
Local error ⇐ (Relative Tolerance ∗ X + Absolute Tolerance )

Where:
X = Tested variable
The default values for the Relative and Absolute Variable Tolerances of 1E-5
are suitable for most simulations.

Absolute Equation Tolerance


The absolute equation tolerance defines the solution accuracy for the non-linear
equation solver where the convergence criterion depends upon residual
convergence. Iteration stops when the absolute value of the residual of each of
the equations in the simulation is reduced below this tolerance.
The Absolute Equation Tolerance is used in the following types of simulation:
• Steady-state and initialization simulations.
• Re-initialization of dynamic simulations using the Gear integrator.
• Dynamic simulations using Explicit Euler, Implicit Euler, or Runge Kutta 4
integrators.

7 Solver Properties Dialog Box 182


• Each iteration of a steady-state estimation or data reconciliation
simulation.
The Absolute Equation Tolerance can take a real number greater than 1E-10.
The default value of 1E-5 is accurate enough for most simulations.

Variable Change Tolerance


While Aspen Modeler is integrating a dynamic simulation, any change in any
variable is compared to the variable change tolerance.
Under the following conditions, the integrator takes action depending on the
integrator chosen:
X new − X old > ChangeTol ∗ X new IF X new ≥ ChangeTol

or
X new − X old > ChangeTol IF X new < ChangeTol

Where:
Error! = Latest value of a fixed variable
Objects
cannot be
created
from
editing
field
codes.
Error! = Value of a fixed variable at the previous
Objects integration step
cannot be
created
from
editing
field
codes.
ChangeTol = Variable Change Tolerance
With the Gear (11.1) integrator, if the integrator takes action due to the
magnitude of change in a variable, the integrator re-initializes the simulation.
Variable change tolerance has no effect on the ImpEuler (11.1) integrator.
With the remaining integrators, the action taken depends on whether the Re-
initialize after variable step change’ box on the Integrator Solver Options Tab
is ticked or not.

Numerical Derivative Absolute and Relative Perturbation


The perturbation for evaluating elements of the Jacobian matrix that are not
available analytically is defined by:

If Deriv Re lTol × X > DerivAbsTol then ε = Deriv Re lTol × X


Otherwise ε = DerivAbsTol

7 Solver Properties Dialog Box 183


Where:
Error! = Perturbation on Jacobian matrix element
Objects
cannot be
created
from
editing
field codes.
X = Value of Jacobian matrix element to be
perturbed
DerivAbsTol = Derivative Absolute Perturbation
DerivRelTol = Derivative Relative Perturbation
You can alter the values of the numerical derivative perturbation parameters
to improve the evaluation of procedures that do not return analytical
derivatives.
If the partial derivative of the procedure output variables with respect to the
input variables is close to zero, the perturbations to the procedure inputs
used to calculate the numerical derivatives may not produce any change in
the output variables.
You can increase the perturbation to the input variables so that there is a
detectable change to the output variables.

Tip: To get more accurate numerical derivatives for procedures,


you can change the values of the perturbations. If your
simulation is failing to converge and you suspect your procedures
are highly non-linear, try reducing the values of the
perturbations.

Solver Scaling
Aspen Modeler products enable you to scale variables for your simulations.
Careful scaling can improve the robustness of the convergence and in some
cases the performance of your simulations.

How Scaling Works


You supply scale values for the variables and Aspen Modeler computes
appropriate equation scales to make the derivatives well-scaled to improve
numerical stability.
The scaled variables’ values are the values of the unscaled variables, divided
by their scale value. The scaled results are then converted back to unscaled
values for the reporting of results.
Scaling of variables is always applied, but the default scaling factor is 1 (this
is inherited from the RealVariable type). When you supply a scale value to a
variable, this scale factor is automatically applied to the solution algorithms
for that variable, even if you do not request solver scaling.

7 Solver Properties Dialog Box 184


If you switch on scaling, additional equation scaling is applied. This means
that the solvers use the scaled equations, but the convergence tests use the
original un-scaled equations.
Make sure that the equations you write in your models are well scaled, so that
you produce a robust and easily-solved simulation. Use Solver Scaling to
further improve your simulation performance. Do not rely on Solver Scaling to
improve the performance of poorly scaled equations.

Supplying Values for Each Variable Type


To supply scaling values for each variable type, supply a value for the
property called scale when you define the variable type, for example:
Variable FlowRate
Upper: 1000;
Lower: 0.0;
Value: 25;
Scale: 100;
End
In general, choose a scale factor such that the scaled variable is of magnitude
1 during the simulation.
If you do not want to scale a particular variable type, enter a scale value of 1.

Supplying Values for Individual Variables


To provide scaling values for individual variables, define a scale value for the
variable’s scale property, for example:
Model Test
Temp as Temperature(Value:25, Scale:20) ;
Vol as Volume(Value: 1275, Scale: 1.0e3);
.
.
End
When you use scaling, the run-time output during solution from all non-linear
blocks is in terms of the scaled variables and the corresponding scaled
bounds.

Eliminate Equivalence Equations


An equivalence equation is an equation equating two variables.
An equivalence equation is stated mathematically as:
VariableX = VariableY ;
You can eliminate many equations of this form by enabling this option. When
two variables are equivalenced, they will be replaced in the simulation by a
"variable" with a name of the form AM_Equivalence<nnnn>, where <nnnn> is
an integer which uniquely identifies the equivalence. These equivalences can

7 Solver Properties Dialog Box 185


be seen in the Explorer Diagnostics views and you can examine the variables
they contain.
An Equivalence behaves as if it were a variable in the simulation, with a
value, bounds, scale factor, and specification.
Equivalence equations are generated from:
• Model equations.
• Connection of blocks in the flowsheet.
• Port matching.
• Equations in sub-block declarations.
An equivalence equation will NOT be eliminated if:
• The equation is within a run-time IF, or a SWITCH.
• Either variable is a parameter.
• Either variable is the time-derivative of another variable.
• Either variable has a specification of FIXED or INITIAL.
• Both variables are state variables.
• Both variables are algebraic variables with assigned values which differ by
more than the Absolute Equation Tolerance.

Notes:

• Equivalencing happens before any snapshot is applied.


Saving the simulation and re-loading can increase the
compression ratio (which is the percentage of the equations in
the simulation that have been eliminated).

• Equivalencing reduces the size of the solved problem,


improving server performance by reducing memory use and
CPU time, but can sometimes lead to groups in the problem
being more difficult to solve. On rare occasions, a simulation
will solve when equivalence equations are not eliminated, but
not when they are: this usually indicates a modeling problem.

• If the ranges of the two variables do not overlap (that is,


if the lower bound of one variable is greater than the upper
bound of the other) then the problem is indeterminate
because there is no value that can simultaneously satisfy both
sets of bounds.

Elimination Precedence
The elimination precedence rules are used to determine the initial value and
scale factor of the equivalence.
The bounds of the equivalence are such that the lower bound is the maximum
of the lower bounds of all the variables in the equivalence, and the upper
bound of the equivalence is the minimum of the upper bounds of all the
variables in the equivalence.

7 Solver Properties Dialog Box 186


The initial value of the equivalence is the average of the values of all the
variables in the equivalence with the highest precedence from the following
list:
Lowest
• Variables of type RealVariable.
• Variables of type ControlVariable.
• Variables of any other type.
Highest
• Variables (of any type) that have been assigned a value.
The scale factor of an equivalence is the largest scale factor of the variables in
the list with the highest precedence

Example of Exception to Arbitrary Rule


In the following example, an equation of the form c=x; is shown:
C(IndexSet) as Large_pos_number (50);
X(IndexSet) as Molefraction (1.0/SIZE(IndexSet));
The equation will not be removed by the arbitrary rule if the Standard
elimination method has been selected, provided no user-assigned values have
been applied to either variable.

Use Group Decomposition


Group Decomposition is the process of breaking the problem to be solved into
a number of much smaller sub-problems. Solving a series of sub-problems is
usually more efficient than solving the whole problem simultaneously, and
Aspen Custom Modeler uses group decomposition by default.
The 'Use Group Decomposition' check box controls the decomposition. When
checked, a normal decomposition with potentially many sub-groups, is used.
When unchecked, the entire problem is solved simultaneously. In either case,
the 'decomposition' is visible in the Simulation Explorer under Diagnostics.

Integrator Tab
The Integrator tab in the Solver Properties dialog box enables you to choose
the integrator you use for your simulation. The integrator you choose depends
on the type of models you have in the flowsheet and the objective of the run.
Consider whether you are looking for speed, or accuracy and robustness.

Integrator Characteristics and use


Explicit Euler Explicit first order method. Fastest integration method
with consistent speed but can become unstable. Often
requires a very small step size to maintain stability.
Runga Kutta 4 Fourth order explicit method. Suitable for some stiff
systems. Variable step size used to maintain error.
Can be good for problems with a large number of
disturbances.
ImpEuler (11.1) First order Implicit Euler method from ACM 11.1. Fixed

7 Solver Properties Dialog Box 187


step size.
Used for simple flowsheets where a reliable,
predictable integration is needed.
Implicit Euler First order Implicit Euler method. Step size can be
variable (to control integration error) or fixed
(integration error ignored). Fixed step method can be
used for simple flowsheets where a reliable,
predictable integration is needed. Variable step
method (the default) should be used error must be
controlled.
VSIE (11.1) Old method from ACM 11.1. Used for general
simulations for speed, accuracy and stiff systems.
Handles discontinuities well.
Gear (11.1) Old Gear method from ACM 11.1 Used for general
simulations when good event detection is required.
Good for stiff systems. Decomposition is not used and
tearing is ignored. Model discontinuities are located.
Variable order, variable step backward difference
Gear implicit method. Uses decomposition and obeys
procedure tearing. You can define the behavior of the
method for model discontinuities and variable step
changes. Use when high accuracy is required.

When you have decided on the appropriate integrator, click the Name box to
select the integrator.

Note: All integrators use decomposition except Gear(11.1) when


solving your problem dynamically.

Except for Gear (11.1), during integration non-linear groups in


the decomposition are solved using the solver and options
specified in the Solver Options Non-linear tab.

Migrating from 11.1 Integrators to


12.1 Integrators
Migrating from ImpEuler (11.1) to Implicit Euler 12.1
When migrating from ImpEuler (11.1) to the new version in 12.1, it is
important to select the correct solver options if you wish to ensure the
performance and accuracy of your simulation is as close as possible to the old
version.
The following table lists the new integrator solver options and how you
should set them to make the new Implicit Euler behave as close as possible to
ImpEuler (11.1).

Integrator Solver Option Value or Source Solver Option


to be Set
Step size type Fixed
Step size ImpEuler (11.1) integration step

7 Solver Properties Dialog Box 188


Migrating from VSIE (11.1) to Implicit Euler 12.1
When migrating from VSIE (11.1) to the new version in 12.1, it is important
to select the correct solver options if you wish to ensure the performance and
accuracy of your simulation is as close as possible to the old version.
The following table lists the new integrator solver options and how you
should set them to make the new Implicit Euler behave as close as possible to
VSIE (11.1).

Integrator Solver Option to be Value or Source Solver Option


Set
Step size type Variable
Absolute integration error tolerance 5*VSIE(11.1) Absolute integration error tolerance
Relative integration error tolerance 5*VSIE(11.1) Absolute integration error tolerance
Absolute tear integration error tolerance 5*VSIE(11.1) Tear integration error tolerance
Relative tear integration error tolerance 5*VSIE(11.1) Tear integration error tolerance
Include sensitivity errors Checked
Re-converge torn variables As VSIE(11.1) Re-converge torn variables
Integration test error test includes States
Initial step size VSIE(11.1) Initial integration step
Minimum step size VSIE(11.1) Minimum integration step
Maximum step size VSIE(11.1) Maximum integration step
Always enforce minimum step size Unchecked
Interpolate communication time As VSIE(11.1) Use interpolation
Locate model discontinuities Unchecked
Re-initialize after Variable Step Change Unchecked
Non-Linear Tab Maximum iterations VSIE(11.1) Maximum corrector iterations

Migrating from Gear (11.1) to Gear 12.1


When migrating from Gear (11.1) to the new version in 12.1, it is important
to select the correct solver options if you wish to ensure the performance and
accuracy of your simulation is as close as possible to the old version.
The following table lists the new integrator solver options and how you should
set them to make the new Gear behave as close as possible to Gear (11.1).

Integrator Solver Option to be Set Value or Source Solver Option


Step size type Variable
Absolute integration error tolerance Tolerances Tab Absolute variable tolerance
Relative integration error tolerance Tolerances Tab Relative variable tolerance
Maximum order 5
Include sensitivity errors Checked
Re-converge torn variables Unchecked
Integration test error test includes States and Algebraics
Initial step size Gear (11.1) Initial integration step*
Minimum step size Gear (11.1) Minimum integration step*
Maximum step size +Gear (11.1) Maximum integration* step
Always enforce minimum step size Checked

7 Solver Properties Dialog Box 189


Interpolate communication time Checked
Locate model discontinuities Checked
Re-initialize after model discontinuities Checked
Discontinuity tolerance Gear(11.1) Event tolerance
Re-initialize after Variable Step Change Checked
Step size after Variable Step Change Gear(12.1) Initial step size
Non-Linear Tab Maximum iterations Gear(11.1) Maximum corrector iterations
Tearing Tab Procedure Tearing None
Non-Linear Solver Tab Method Fast Newton
Non-Linear Solver Tab Convergence Variable
criterion

Integrator Tab: Explicit Euler


Explicit Euler is the simplest form of integrator. You can use Explicit Euler to
run simulations where a faster and more regular simulation speed is more
important than greater accuracy.
For Explicit Euler, the equation used to integrate state variables is:
y (t + h ) = y (t ) + h • y& (t )
Where:
h = Integration time step
y(t) = Value of state variable at time t
y(t+h) = Value of state variable at time t+h
y& (t ) = Time derivative of state variable at time t
Explicit Euler is a fixed step explicit integrator that uses Euler's method. It has
the following advantages and disadvantages:
• Normally less accurate than other integrators.
• Because the step length is fixed, it is less accurate than Gear and Implicit
Euler in tracking fast transients. In these cases, Gear and Implicit Euler
cut their step length to follow the transients more closely. However, this
slows down the speed at which the integration progresses.
• Ideal for use in operator training simulators, where real time performance
is important because Explicit Euler continues at a near constant speed.

Note: Because Explicit Euler is an explicit method, the


integration may become unstable, causing the run to terminate.
This is not an error, but is a feature of this relatively simple
integration method. If instability occurs, try reducing the size of
the Step Size, or changing the formulation of your model.

You can specify the following options for Explicit Euler:


• Step size
• Interpolate step size

7 Solver Properties Dialog Box 190


Caution: A larger integration step may make the simulation
unstable. Unlike other integrators, Explicit Euler does not stop
integrating if the accuracy of the solution starts going out of
tolerance. Always validate the data produced from Explicit Euler
with a more accurate integrator.

Integrator Tab:Runge Kutta 4


You can use Runge Kutta to integrate using an explicit fourth order method. It
is a variable step, fourth order, explicit Runge-Kutta integrator. Because it
has a high order and a variable step, it is normally more accurate than
Explicit Euler. For given values of the Integration and Tear error tolerances,
the accuracy is comparable to that of the Gear and VSIE (variable step)
integrators.
Runge Kutta 4 is suitable for a wide range of applications, although Gear is
more suitable for very stiff systems. It can be very effective on some
problems which have a large number of disturbances.

Caution: Avoid using a large value of the Relative Tolerances


(greater than 1e-3), as this may result in excessively large
integration steps, causing instability or failure of the integration.

You can specify the following integrator options for Runge


Kutta 4:
Absolute and Relative integration
Absolute and Relative tear
Re-convergence torn variables
Initial step size
Minimum step size
Maximum step size
Interpolate to communication time

Integrator Tab: ImpEuler (11.1)


The Implicit Euler integrator is the default and is very fast for basic
simulations.
Implicit Euler is a first-order, fixed-step implicit integrator that uses a
backward Euler's method.
For Implicit Euler the equation used is:
y (t + h ) = y (t ) + h • y& (t + h )
Where:
h = Integration time step
y(t) = Value of state variable at time t

7 Solver Properties Dialog Box 191


y(t+h) = Value of state variable at time t+h
y& (t + h ) = Time derivative of state variable at time t+h
Fixed-step Implicit Euler has the following advantages and disadvantages:
• Remains more stable than Explicit Euler whatever the value of the
integration step size.
• Becomes increasingly inaccurate as you increase the step size.
• Steps over discontinuities without locating the event or re-initializing.
• For a given simulation and step size, is normally slower than Explicit Euler,
because it has to perform iterative calculations to solve the integration
equations.

Implicit Euler: Integration Step


You can specify the Integration Step to control the speed of the simulation. In
general, the larger the integration step, the faster a simulation runs. Try to
obtain an optimum integration step for your simulation because too large an
integration step causes your run to fail to converge.

Integrator Tab: Implicit Euler


The Implicit Euler integrator is the default and, when the step is variable,
very fast for basic simulations.
Implicit Euler is a first-order, implicit integrator that uses a backward Euler's
method.
For Implicit Euler the equation used is:
y (t + h ) = y (t ) + h • y& (t + h )
Where:
h = Integration time step
y(t) = Value of state variable at time t
y(t+h) = Value of state variable at time t+h
y& (t + h ) = Time derivative of state variable at time t+h
You can choose between a fixed or variable step size using the Fixed and
Variable radio buttons. Integration error is ignored when the step is fixed: use
this when you want consistent and predicable dynamic simulation
performance over time. To obtain greater accuracy and efficiency, the step
size should be variable.
Implicit Euler has the following advantages and disadvantages:
• Remains more stable than Explicit Euler whatever the value of the
integration step size.
• Becomes increasingly inaccurate as you increase the step size.
• For a given simulation and step size, is normally slower than Explicit Euler,
because it has to perform iterative calculations to solve the integration
equations.
You can specify the following integrator options for Implicit Euler.

7 Solver Properties Dialog Box 192


Error tolerances:
Absolute and Relative integration
Absolute and Relative tear
Include sensitivity errors
Re-convergence torn variables
Integration error test includes
Step size: fixed or variable
Initial step size
Minimum step size
Maximum step size
Always enforce minimum step size
Interpolate to communication time
Locate model discontinuities
Discontinuity tolerance
Re-initialize after variable step change
Step size after variable step change
Show highest integration errors
Show highest tear integration errors

Integrator Tab: VSIE (11.1)


VSIE combines the speed advantages of Implicit Euler and the robustness
around fast transients of variable step integrators like Gear. You can use VSIE
for simulations that are fairly stiff where you want an improvement in speed
over the Gear integrator.
VSIE has the following advantages:
• Can take large step sizes.
• Maintains accuracy according to an error control strategy.
• For many dynamic simulations, consumes less overall computational time
than the fixed-step option.
• For many dynamic simulations, provides more accurate results during
highly transient conditions than the fixed-step option.

VSIE: Initial Integration Step


You can specify the size of the first integration step after initialization or re-
initialization by changing the value of Initial Integration Step.
You can use this option to improve the speed and robustness of a simulation,
for example, if a run fails or goes slowly just after initialization or re-
initialization. If error messages report that the step is too large after an
initialization or re-initialization, decrease the initial integration step to a value
of about the same size as the step reported in the message window when
converging. The default value is 0.005.

7 Solver Properties Dialog Box 193


VSIE: Maximum and Minimum Integration Step
You can limit the maximum and minimum size of an integration step by
setting Maximum Integration Step and Minimum Integration Step.
You can set the maximum and minimum integration steps to avoid situations
where the integrator may miss a discontinuity, or where you want the
integrator to step over a unrealistic discontinuity, such as a step change in
property data where phase changes are taking place. The minimum and
maximum step sizes are 0.001 and 0.05 respectively.

Tip: Setting too large a value for the minimum integration step
may result in inaccurate results. If you see the integrator
rejecting steps of this size, you may wish to decrease the
minimum to allow a greater degree of accuracy.

Note: If you set these two properties to the same value, then
the VSIE acts in the same way as Implicit Euler.

VSIE: Step Reduction Factor


When an integration step is rejected as being out of tolerance, the integration
step is reduced by a factor. The default factor of 0.5 means that the step is
halved when the integration step fails. You can change the step reduction
factor to a more aggressive value (greater than 0.5) or a more conservative
value (less than 0.5).
To determine your change to the step reduction factor, note how often the
integrator is cutting back the integration step. If a simulation repeatedly cuts
back the step, reduce the value of the step reduction factor. If you want to
improve the speed of integration during a simulation with mild transients, try
increasing the step reduction factor.

VSIE: Maximum Step Increment Factor


When the VSIE integrator detects that there are no significant transients in
the simulation, the integrator gradually increases the step size to speed up
the integration. You can limit how aggressive the increase in step size is by
decreasing the maximum step increment factor. A smaller value causes the
integrator to be more cautious in increasing the step size.
If you know that there are repeated step changes in the simulation, try
reducing the maximum step increment factor. This ensures that the step does
not get too large and time is wasted repeatedly cutting the integration step at
each discontinuity.

VSIE: Absolute and Tear Integration Error Tolerance


The absolute integration error tolerance is used by the integrator to
determine any increase in integration step based on the values of state
variables in the simulation.

7 Solver Properties Dialog Box 194


When you enable torn procedure calls, the tear integration error tolerance
determines any increase in integration step based in the values of torn
variables.
At each integration step, the following calculations are made to determine the
value of the next integration step.
0.4
 RMS_State 
Temp1 =  IntErrTol 
 2 
0.4
 RMS_Tear 
Temp2 = TearErrTol 
 2 
Temp3 = MIN (MaxStepInc Fac, Temp1, Temp2 )
StepIncFac = MAX (0.5, Temp3 )
Where:
RMS_State = Root-mean-square of the relative
differences between the predicted
and corrected values of the state
variables
RMS_Tear = Root-mean-square of the relative
differences between the current
and the previous integration
step’s values of torn variables
IntErrTol = Integration Error Tolerance
TearIntErrTol = Tear Integration Error Tolerance,
default 0.01
Temp1, Temp2, = Intermediate variables
Temp3
MaxStepIncFac = Maximum Step Increment Factor,
default 1.5
StepIncFac = Step Increment Factor for the
next integration step

VSIE: Maximum Corrector Iterations


Maximum Corrector Iterations is the maximum number of iterations the
corrector can take to converge a step. The default of 150 is suitable for most
simulations. However, for some difficult simulations you may need to supply a
larger number.

VSIE: Show Highest Integration Errors


When set to a value x greater than zero, the integrator will display the x
variables with the largest contribution to the integration error and the x
variables with the largest contribution to the tear error. This is useful when
attempting to diagnose why a simulation is failing to converge. There is a
slight performance penalty for using this option, so set it until zero unless you
need to use it.

7 Solver Properties Dialog Box 195


VSIE: Use Interpolation
You can use interpolation to improve the speed of your simulation. When Use
Interpolation is cleared, the simulation will cut an integration step to coincide
with a reporting interval, giving the most accurate results possible with the
current simulation settings. When Use Interpolation is selected, values of
reporting intervals are calculated using a linear interpolation between the two
adjacent integration points. This allows the integrator to maintain its current
step size and avoids slowing the simulation, but reduces the accuracy of the
results.

VSIE: Reconverge Torn Variables


You can choose to converge all the output variables for torn procedures if the
procedure tearing option is set to update. If the procedure tearing option is
set to start or complete, torn variables are not updated at all during
integration.
By default, output variables for torn procedures are not converged at each
integration step. Instead, the values of the output variables are simply
updated if the procedure tearing option is set to update.
If you select Reconverge Torn Variables, this forces the torn variables to be
converged iteratively at the end of each integration step. Reconverging the
torn variables gives a more accurate and possibly more stable solution.
However, it requires more processing which can cause a simulation to run
more slowly.

Integrator Tab: Gear(11.1)


The Gear integrator uses a modified Gear’s method algorithm. Gear
automatically varies the integration step and integration algorithm order so
that the estimated integration errors are within a tolerance determined from
the Relative and Absolute Variable tolerances.
Gear can cope with partially indeterminate systems. (An indeterminate
variable is one that has no unique value, that is, any value will satisfy your
equations.) This situation can occur when, for example, there is no holdup in
a vessel in a simulation where there are several components. The composition
of components in an empty vessel cannot be determined. This type of system
is singular. To handle this situation, Gear maintains the values of the
composition at the time the values were last able to be determined, such as
at the point the vessel became empty. When the vessel starts to fill again, the
composition becomes determinate again.
Use the Gear integrator where you want to use a fast robust integrator that
can handle difficult discontinuities, indeterminate simulations, and stiff
systems.

Note: Gear(11.1) is the ACM 11 version of Gear and included in


ACM 12 for backwards compatibility. It does not use
decomposition, and tearing is ignored.

7 Solver Properties Dialog Box 196


Gear: Show Highest Integration Errors
You can specify the number of variables shown that are giving the greatest
integration errors in the simulation. To do this, you need to specify a number
for the highest integration errors shown.
Use this feature to determine which variables are causing the integrator to
take smaller integration steps than necessary, and are causing the run to
slow down. You may want to change the scale of a variable if the variable
consistently creates the highest integration error.

Gear: Initial Integration Step


You can specify the size of the first integration step after initialization or a re-
initialization by changing the value of initial integration step.
You can improve the speed and robustness of a simulation if you find that a
run fails or goes slowly just after initialization or re-initialization by changing
the initial integration step.
If there are error messages that the step is too large after an initialization or
re-initialization, decrease the initial integration step to a value of about the
same size as the step reported in the message window when converging.

Gear: Maximum and Minimum Integration Step


You can limit the maximum and minimum size of an integration step by
setting Maximum Integration Step and Minimum Integration Step
You can set the maximum and minimum integration steps to avoid situations
where the integrator may miss a discontinuity, or where you want the
integrator to step over a unrealistic discontinuity, such as a step change in
property data where phase changes are taking place.

Gear: Event Tolerance


You can define the accuracy to which discontinuities are located by specifying
a value of Event Tolerance.
You can reduce the value of event tolerance to get a more accurate location
of an error. If you have a simulation that repeatedly locates a discontinuity at
the same time point but cannot integrate past this discontinuity, you can
decrease the event tolerance to locate the discontinuity better and resolve it
before continuing to integrate.

Gear: Jacobian Update Policy


You can change the value of the Jacobian update policy to change the
maximum number of corrector steps before the Jacobian matrix is updated.
Jacobian Update Policy controls the Jacobian matrix update strategy for the
integrators shown in the following table.
Jacobian Update Policy can take an integer greater than 0.
The default is shown in the table:

Integrator Default
Explicit Euler, RUNGE KUTTA 4, 5

7 Solver Properties Dialog Box 197


Implicit Euler, and VSIE only when
Fast Newton is used
Gear 0
This means Gear uses its own
internal policy to decide when to
update the Jacobian, based on rates
of convergence.

If the Hybrid or Newton non-linear solver methods are used with Explicit
Euler, Runge Kutta 4, Implicit Euler or VSIE, the Jacobian is updated every
iteration. The Jacobian update policy has no effect.
These default values for Jacobian Update Policy are of general applicability. In
some simulations, you can improve solution speed or robustness by adjusting
this parameter. However, adjusting this parameter to improve one simulation
may not produce an improvement in another simulation.
If you are having convergence difficulties, you can try reducing the value of
Jacobian Update Policy. However, before spending time adjusting this
parameter, first check that the cause of the convergence failure is not within
your own simulation definition.

Gear: Re-initialization Method


During integration with Gear, the integrator needs to re-initialize whenever it
encounters a discontinuity.
A discontinuity may be caused by:
• A step change in an input variable.
• A conditional equation switching from one branch to another.
• A sudden change in an output from a procedure.
You can use re-initialization method to control re-initialization during dynamic
runs. Valid settings are:

Setting Result
Normal Use standard re-initialization
Fast Use fast re-initialization
Save Use re-initialization that saves additional numerical
information, resulting in faster re-initialization
(default)

If you specify fast re-initialization, an alternative re-initialization method is


used for dealing with discontinuities. With fast re-initialization, rather than
locating and solving all the equations at the discontinuity point, then
integrator attempts to step over the discontinuity by making a number of
small, first order integration steps. This alternative method can result in
faster handling of the discontinuity but can give slightly less accurate results.
If you specify Save, additional information about the linear solver is saved.
This reduces the calculations needed at re-initialization, which uses additional
memory but reduces the time taken to re-initialize. If your computer has
plenty of memory, we recommend that you use the Save option for all your
dynamic simulations.

7 Solver Properties Dialog Box 198


The Re-initialization Method switch is most useful in increasing the speed of
simulations with a large number of discontinuities, when very high accuracy is
not required. The default value is Save.

Gear: Show Highest Corrector Steps


Show Highest Corrector Steps enables Gear to show the variables that are
producing the greatest corrector errors. If your simulation is failing due to
corrector errors, you can use this option to determine which variables are
contributing most to the integration failure.

Gear: Maximum Corrector Iterations


Maximum Corrector Iterations is the maximum number of corrector iterations
the Gear integrator can take to converge a step. Set Maximum Corrector
Iterations to be an integer greater than 0. The default is 5. However, for
some difficult simulations you may need to supply a larger number.

Gear: Keep Solution within Bounds


If you enforce bound checking (Track or Clip), Gear enforces bounds at all
times. If you do not have bound checking set (Off), bounds are only enforced
at re-initialization.
The options are:

Select For Gear to


Track Track the variables as they lie on their bounds by cutting the
integration step size
Clip Enforce bounds by clipping individual variable steps as they
cross the bound
Off The solver allows variables to move outside their bounds
during integration

Notes:

• In some cases, you may need to use Clip rather than


Track to avoid the integrator taking very small step sizes.

• Although bound checking can improve the robustness of


simulations, it sometimes causes an integration to proceed
slowly. If the solution for a variable lies along its bound, Gear
spends time checking that it does not cross the bound. If the
variable bounds are causing Gear to slow down, you can set
bound checking to Off or Clip.

• Values displayed in variable tables are always clipped


within their bounds, regardless of the bound checking option.
It is recommended that you change the bounds rather than
rely on the bound checking Off option.

It is dangerous to use the Off option and allow variables to go outside their
bounds during simulation. This should be done for debugging purposes only.

7 Solver Properties Dialog Box 199


If you need to use this option to get a simulation to converge, it is better to
enlarge the variable bounds, or work out why variables go outside their
bounds.

Integrator Tab: Gear


The Gear integrator uses an integration method based on Gear’s algorithm. It
automatically varies the integration step (if the step size is Variable <link>)
and integration algorithm order so that the estimated integration errors are
within a tolerance determined by the Relative and Absolute Variable
tolerances.
Use the Gear integrator where you want to use fast and accurate integration
that can handle and stiff systems.
See Integrator solver options for the options can be used to control the
behavior of the Gear integrator.

Integrator Solver Options


Maximum Order
Defines the maximum order allowed when using the Gear integrator method.
Default is 5 with range 1 to 5.

Error tolerances
• Absolute and Relative integration.
• Absolute and Relative tear.
These tolerances only have an effect if the step size is Variable.
The absolute integration error tolerance is used by the integrator to
determine any change to the size of the integration step based on the values
of variables in the simulation.
When you enable torn procedure calls, the tear integration error tolerance
determines any increase in integration step based in the values of torn
variables.
The integration variable step size at time t is accepted if:
2
1 N  x(i ) − x p (i ) 
 ≤1

N i =1  RTOL x0 (i ) + ATOL 
(1)
 
and, when there are torn procedures in the ACM flowsheet and procedure
tearing is set to update [2], if
2
1 N  θ (i ) − θ 0 (i ) 
N
∑ 

 ≤1

i =1  RtearTOL θ 0 (i ) + AtearTOL 
(2)

where:

7 Solver Properties Dialog Box 200


x: corrected state (and algebraic if Integration Error test includes is set to
states and algebraics) variables at time t

x p : predicted state (and algebraic if Integration Error test includes is set to


states and algebraics) variables at time t
x0 : state and (and algebraic if Integration Error test includes is set to states
and algebraics) variables at time t-h
θ : torn output variables at time t
θ 0 : torn output variables at time t-h
n: number of equations
h: current integration step size
RTOL: relative integration error tolerance
ATOL: absolute integration error tolerance
RtearTOL: relative tear error tolerance
AtearTOL: absolute tear error tolerance

Include sensitivity errors


When checked (the default), and the integrator is computing sensitivities with
a variable step size, the error in the sensitivity variables is taken into account
when computing the step size. When unchecked, errors in the sensitivities are
ignored.
In simulations where dynamic sensitivities are computed (dynamic parameter
estimation, dynamic optimization and dynamic runs with sensitivities) and a
variable step integration step method is used, it is recommended (and it is
the default) to include a sensitivity error check at each integration point to
make sure the sensitivities are accurate to within the integration error
tolerances. When the sensitivity integration errors are greater than the
integration errors in your usual flowsheet variables, then the current
integration step size will be cut and a new integration step taken.
In some extreme cases, the integrator step can become very small due to
repeatedly sensitivity integration error failures (set the Solver Reporting Level
to High and look for "Step rejected due to sensitivity" messages in the
Simulation Messages Window to see if this is occurring in your simulation),
often resulting in your simulation running slowly. In these cases, it may be
appropriate to un-check the Include Sensitivity Errors box to improve
performance, at the expense of having less accurate sensitivities. In some
cases, this may result in the dynamic estimation or optimization simulation
failing; if it does, try tightening the integrator error tolerances, reducing the
maximum integration step size, reducing the variable or equation tolerances
or relaxing the estimator or optimizer tolerances.

Re-converge torn variables


You can choose to converge all the output variables for torn procedures.

7 Solver Properties Dialog Box 201


By default, output variables for torn procedures are not converged at each
integration step. Instead, the values of the output variables are simply
updated if the procedure tearing option is set to update.
If you select Reconverge Torn Variables, this forces the torn variables to be
converged iteratively at the end of each integration step. Reconverging the
torn variables gives a more accurate and possibly more stable solution.
However, it requires more processing which can cause a simulation to run
more slowly.

Integration error test includes


You can switch between the state variables only and states and algebraic
variables (the default) radio button to control which variables in your
simulation are included in the integration error control. For maximum
accuracy you should include both the states and algebraics.

Step Size
To fix the integrator step size (and ignore integration error), select the Fixed
radio button and specify the step size to be used in the Step size box (default
0.01, range >0 and <1).
To use a variable step size, select the Variable radio button. The step size will
be changed, subject to the initial, minimum and maximum step sizes , so that
the integrator satisfies the error norm <link to error norms above> at every
integration step size. The step will be variable to obtain best accuracy.

Initial Step Size


You can specify the size of the first integration step after initialization or a re-
initialization by changing the value of initial integration step.
You can use this option to improve the speed and robustness of a simulation,
for example, if a run fails or goes slowly just after initialization or re-
initialization. If error messages report that the step is too large after an
initialization or re-initialization, decrease the initial integration step to a value
of about the same size as the step reported in the message window when
converging. The default value is 0.005 and range is >0 to <1.

Minimum and Minimum step size


You can limit the maximum and minimum size of an integration step by
setting Maximum Integration Step and Minimum Integration Step.
You can set the maximum and minimum integration steps to avoid situations
where the integrator may miss a discontinuity, or where you want the
integrator to step over a unrealistic discontinuity, such as a step change in
property data where phase changes are taking place. The minimum and
maximum step sizes are 0.001 and 0.05 respectively.

Tip: Setting too large a value for the minimum integration step
may result in inaccurate results because the integrator will not go
below the minimum even if the integration error is above
tolerance. If you see the integrator stuck on the minimum step
size, you may wish to decrease it to allow a greater degree of

7 Solver Properties Dialog Box 202


accuracy.

Always enforce minimum step size


When checked, the minimum step size is enforced – the integrator will never
choose a step size smaller than the minimum. When unchecked (the default),
the integrator can go below the minimum to attempt to recover and continue
integrating when there are repeated convergence failures when integrating.

Step Reduction Factor


This option controls how much the current integration step size is reduced by
following a convergence failure during a dynamic run. The default is 0.5 and
range between 0 and 1. For example, if the step reduction factor is set to 0.1
and a convergence failure occurs, the next step chosen is a tenth of the
previous one.
Increasing or decreasing this value may improve the performance of your
simulation if there are repeated corrector failures.

Interpolate to communication time


You can use interpolation to improve the speed of your simulation.
When Interpolate to Communication Time is unchecked, the simulation will
cut an integration step to coincide with a communication time, giving the
most accurate results possible with the current simulation settings.
When Interpolate to Communication Time is checked, variable values at
communication times are calculated using interpolation. This allows the
integrator to maintain its current step size for best performance, but can
slightly reduce the accuracy.

Event Handling
Locate model discontinuities
When checked, the integrator will detect when model discontinuities (IF and
switch statements changing branch) occur, locate where they occur within the
Discontinuity tolerance, step to that point and restart the integrator. When
unchecked (default) , model discontinuities are not located and the integrator
simply steps over them.

Discontinuity tolerance
This is the tolerance to which model discontinuities are located. Default if 1.e-
5 and range >0 and <1.

Re-initialize after model discontinuity


Determinates the behavior after a model discontinuity is located. When
checked, an algebraic re-initialization is performed. When unchecked
(default), the integrator restarts by resuming integration at the located point
and, when the step size is variable, uses the initial integration step.

7 Solver Properties Dialog Box 203


Re-initialize after Variable Step Change and Step Size after
Variable Step Change
Determines the behavior of the integrator following a step change in a
variable value (when a fixed variable changes by more than the Variable
Change Tolerance). When checked, an algebraic re-initialization is performed.
When unchecked (the default), the integrator resumes using the fixed step
size or, if the step size is variable, the initial step size if the Use Initial step
size radio button is active (default) or continues using the previous step size if
the Use previous step size radio button is active:

Note: A ramped variable has a step change at the start and end
of the ramp.

Diagnostics
Show highest integration errors
You can specify the number of variables shown that are giving the largest
contribution to the integration errors in the simulation.
This diagnostic shows the largest values of the relative error term:

x(i ) − x 0 (i )
RTOL θ 0 (i ) + ATOL
used in the integration error norm over all variables contributing to the error
test,
where:
x : corrected state and algebraic variables at time t
x0 : predicted state and algebraic variables at time t
RTOL : relative integration error tolerance
ATOL : absolute integration error tolerance
To do this, you need to specify a number for the highest integration errors
shown.
Use this feature to determine which variables are causing the integrator to
take smaller integration steps than necessary, and are causing the run to
slow down. You may want to change the scale of a variable if the variable
consistently creates the highest integration error.

Show highest tear integration errors


You can specify the number of tear output variables shown that are giving the
largest contribution to the integration errors in the simulation.
You can specify the number of tear output variables shown that are giving the
largest contribution to the integration errors in the simulation.

7 Solver Properties Dialog Box 204


This diagnostic shows the largest values of the relative error term:
θ (i) − θ 0 (i )
RtearTOL θ 0 (i) + AtearTOL
used in the integration tear error norm over all torn variables contributing to
the tear error test,
where:
θ : torn output variables at time t
θ 0 : torn output variables at time t-h
RtearTOL: relative tear error tolerance
AtearTOL: absolute tear error tolerance
To do this, you need to specify a number for the highest integration errors
shown.
To do this, you need to specify a number for the highest integration errors
shown.
Use this feature to determine which tear output variables are causing the
integrator to take smaller integration steps than necessary, and are causing
the run to slow down. You may want to change the scale of a variable if the
variable consistently creates the highest integration error.

Linear Solver Tab


The Linear Solver tab in the Solver Properties dialog box enables you to
choose the linear solver you use for your simulation.
To change the linear solver, click the Name box on the Linear Solver tab.

Linear Solver Tab: MA48


The linear solver is used to solve simple equalities. It is the fundamental
routine that lies at the heart of all modes of simulation. Changes to the linear
solver options affect all solution methods.
MA48 is an updated version of MA28, with the advantages of faster execution
times. The default solver properties for MA48 are applicable for most
situations. Any changes to the MA48 properties should be made with caution
and good reason.

MA48: Drop Tolerance


You can alter the drop tolerance to force Aspen Modeler to calculate whether
an element in the Jacobian matrix is small enough to be considered zero.
If you increase the value of drop tolerance, more elements are dropped from
the Jacobian matrix, and the solution can be faster. However, more
information is lost and the solution may not converge.

7 Solver Properties Dialog Box 205


MA48: Pivot Tolerance
The pivot tolerance controls partial pivoting of the Jacobian matrix in the
MA48 solver. Any pivot value below the pivot tolerance is considered
numerically to be zero by the MA48 solver.
This feature is useful for cases where the Jacobian matrix is singular. The
default value of zero is suitable for most simulations. If you have some very
small values in the Jacobian matrix, setting the pivot tolerance to a small
non-zero value, such as 1e-25, prevents pivoting on very small matrix
element values.

MA48: Re-Analyze Threshold


The re-analyze threshold value determines when a Jacobian re-ordering step
is required. Aspen Modeler keeps a moving average of the number of floating
point operations (FLOPS) over a period defined by the Re-analyze FLOPS
Window Size parameter. This average is compared to the number of FLOPS
immediately after the previous Jacobian matrix re-ordering.
A new re-ordering operation is called when:
FLOPS_ave rage >= Re - analyze Threshold ∗ FLOPS_initial
Where:
FLOPS_average = Average number of FLOPS over the
previous number of factorizations
defined by Re-analyze FLOPS
Window Size
FLOPS_initial = Number of FLOPS immediately after
previous re-order operation
The re-analyze threshold is the factor by which the initial number of FLOPS
after the last Jacobian matrix re-order is allowed to increase before the next
Jacobian matrix re-order is called.

MA48: Re-Analyze FLOPS Window Size


For each equation group the number of floating point operations (FLOPS)
required to perform an MA48 factorization is stored over the number
factorizations defined by the FLOPS window size. This enables Aspen Modeler
to determine by how much the number of FLOPS is increasing and how to act
on this change. Aspen Modeler keeps a moving average of the number of
FLOPS. If this exceeds the Re-analyze Threshold, re-ordering of the Jacobian
matrix is requested.
If you define a large FLOPS window size, Aspen Modeler evaluates a moving
average of the number of FLOPS over a large number of factorizations. This
means any sharp increase in the number of FLOPS may not be acted upon, as
the sample taken for the average number of FLOPS is large.
If you define a smaller FLOPS window size, then a sharp increase in FLOPS
quickly affects the moving average and Aspen Modeler responds to this
change.
This option enables you to make Aspen Modeler sensitive to increases in the
number of FLOPS taking place by decreasing the FLOPS window size, or to

7 Solver Properties Dialog Box 206


make Aspen Modeler indifferent to FLOPS growth, by increasing the FLOPS
window size.

MA48: Re-pivot every n Factorizations


You can define how often a re-pivot operation on the Jacobian matrix is
performed. The default value is re-pivot every 0 factorizations. This means
that MA48 re-pivots the Jacobian matrix whenever a zero pivot is found
during factorization.
You can change this option if you suspect that convergence is being hindered
because the MA48 solver needs a new pivot sequence. A typical value in this
case is to re-pivot every 5 factorizations.

MA48: Solver Searches n Columns for Pivots


The number of columns searched for pivots determines how many columns
the MA48 solver searches the Jacobian matrix for a suitable pivot point. The
default value of 3 is suitable for most simulations. A value of 0 means that all
columns in the Jacobian matrix are searched.
If you increase the number of columns searched, this can reduce the
performance but can produce a more accurate solution. Only change the
number of columns searched for a very sensitive simulation that is close to
singularity.

MA48: Use Transpose


When checked, MA48 uses a transpose of the matrix instead of the original
matrix when solving linear systems. This has the effect of changing the
direction in which MA48 searches for pivots. For some models, using the
transpose will be faster than using the original matrix. You may wish to use
this option if your simulation is very slow (particularly if each non-linear
iteration is taking a long time) to improve performance.

Linear Solve Tab: MA38


AOS_MA38 uses the MA38 package from the Harwell Subroutine Library,
written by T.A. Davis and I.S Duff. It solves the system of linear equations Ax
= b by factorizing the matrix A into LU factors and then performing a
back/forward solve to compute x for a given b. We refer the reader to the
references for full details of the algorithm and implementation. The package
uses an unsymmetric multifrontal method of solution. It makes extensive use
of Level 3 BLAS routines, attempting to exploit dense blocks within the
matrix, potentially giving better performance because direct rather than
indirect addressing can be used for such blocks.

All memory allocation is handled by the AOS MA38 wrapper code, making the
AOS solver DLL very easy to use. The implementation is as efficient as
possible and the minimum amount of work is performed when solving linear
equations (for example, by avoiding re-pivot and re-analyze operations unless
absolutely necessary).
The solver options exposed for the AOS DLL allow direct access to the options
in the MA48 code itself (for example, PivotTolerance), some extra options

7 Solver Properties Dialog Box 207


(RePivot, UseTranspose) that control the way the AOS DLL manipulates the
MA38 code, including influencing the way memory requirements are
estimated (GrowthFactor, InitialFactor) and using the Harwell Subroutine
MC29 to scale the linear equations (ScaleVariables).

For most applications it is not necessary to change any of these options from
their defaults. However, if it is taking a long time or a large amount of
memory in the SetMatrixVals method, then changing the following options
may help improve the performance:
• InitialFactor
• GrowthFactor
• PivotSearch
• UseTranspose

If it is unexpectedly reported that the problem is singular, then changing


PivotSearch; ScaleMatrix; PivotTolerance may help avoid the singularity. See
the help on each option for further details.
References
[1] Arioli, M., Demmel, J.W. and Duff, I.S. "Solving sparse linear systems with
sparse backward error", SIAM J. Matrix Anal. Appl. 10, p165-190, 1989.
[2] Curtis and Reid, "On the automatic scaling of matrices for Gaussian
Elimination", J. Inst. Maths. Applics. 10, p118-124, 1972.

MA38: Solver Parameters

Name Description
Print Level Level of detail to print
Scale Matrix Scale matrix using MC29
UseTranspose Use matrix transpose for factorization
BlockTriangularizati Pre-order matrix to block triangular form
on
PivotSearch Maximum number of columns to search for
pivots.
PreferDiagonalPivots Prefer on-diagonal pivots for roughly
symmetric matrices
DenseBlockSize Block size for numerical factorization of dense
blocks
MaxIterRefinements Maximum number of steps for iterative
refinement.
PivotTolerance Tolerance for partial pivoting test
FrontalAmalgamatio Control how much frontal matrix can grow
n due to amalgamation.
InitialFactor Amount of workspace at start as a multiple of
nnz
GrowthFactor Amount to resize workspace as a multiple of
nnz
RePivot MA38 Re-pivoting frequency

7 Solver Properties Dialog Box 208


PrintLevel: Level of detail to print
Type: integer; default 0;

Range: 0 No messages output


1 Only error messages printed.
2 Errors and warnings printed.
3 Errors and warnings and terse diagnostics
(only first ten entries of arrays printed, a;
thennl duplicate and invalid entries).
4 Errors and warnings and most information
on input and output parameters printed.
5 Errors and warnings and all information on
input and output parameters printed.

The above are all controls on the output printed by the HSL routines. In
addition, a small amount of diagnostic information (relating to resizing the
arrays if not enough workspace was specified initially), is printed if the print
level is greater than zero.

Warning: Selecting values 4 or 5 for this parameter can give


rise to excessively large amounts of output, as it causes MA38 to
dump out the entire sparse matrix, and all other arrays. This
should only be used for diagnostic purposes if a solve runs into
problems.

ScaleMatrix: Scale matrix using MC29


Type: String

Range: No Do not scale matrix (default)


Yes Scale matrix

When "Yes" is selected, the MC29 routine from the Harwell Subroutine Library
(see [2]) is used to rescale the rows and columns of the matrix prior to
factorization (and to un-scale the resulting solution from the Solve method so
that the solution is in the original scale). The scales are re-computed every
time MA38 re-factorises. Using scaling can improve the numerical solution of
the linear equations and is particularly useful for ill-conditioned or badly-
scaled problems.

UseTranspose: Use matrix transpose for factorization


Type: String

Range: No Do not use the transpose of the matrix for


factorization (default)
Yes Use the transpose of the matrix for
factorization

The default is "No", but when "Yes" is selected, MA38 uses a transpose of the
matrix instead of the original matrix when solving the linear system. This has
the effect of changing the direction in which MA38 searches for pivots. For

7 Solver Properties Dialog Box 209


some models, using the transpose will be faster than using the original
matrix. You may wish to use this option if MA38 to improve performance if
calls to the SetMatrixVals method are taking a long time.

BlockTriangularization: Pre-order matrix to block triangular


form
Type: string;

Range: No do not block triangularise


Yes attempt to block triangularise (default)

Controls whether MA38 attempts to block triangularise the matrix. Re-


ordering the matrix into lower block triangular form (whether this is possible
depends on the structure of the matrix) and solving each block in term can be
more efficient than handling the matrix as a whole (but may introduce small
numerical errors into the solution).

PivotSearch: Maximum number of columns to search for pivots.


Type: integer; default 4; range [1, 10000000]
PivotSearch controls how many columns MA38 searches for suitable pivots in
the matrix. The default value of 4 is suitable for most simulations. Increasing
the number of columns searched may mean MA38 takes more time in the
factorization stage, but can produce a more accurate solution. It may be
worthwhile to change the number of columns searched for a very sensitive
simulation that is close to singularity.

PreferDiagonalPivots: Prefer on-diagonal pivots for roughly


symmetric matrices
Type: string;

Range: Yes Prefer on-diagonal pivot elements


No Don’t restrict pivoting to diagonal
elements (default)

If "Yes" is selected, then pivots on the diagonal of the matrix are preferred
over off-diagonal pivots. If the matrix has been preordered into Block Upper
Triangular form, then the diagonal of the permuted matrix is preferred. If
"No" then no preference is made. Selecting "Yes" for this option is useful for
matrices that are symmetric in structure and diagonally dominant, since fill-in
is often less if symmetry is preserved. This is only a preference in the sense
that, when searching a column for a pivot, the diagonal entry is accepted if it
passes the threshold test (see PivotTolerance), otherwise an off-diagonal in
that column can still be chosen.

FullFactor: Block size for numerical factorization of dense


blocks
Type: integer; default 32; range [1, 10000000]

7 Solver Properties Dialog Box 210


This is the block size for the numerical factorization of the dense frontal
matrices. It controls the trade-off between Level 2 and Level 3 BLAS. The
best value of this parameter depends on the computer being used. The
typical range is 16-64. The default value of 32 should generally not be
changed.

MaxIterRefinements: Maximum number of steps for iterative


refinement.
Type: integer; default 0; range 0-20.
If this is set to a non-zero value, then this is the maximum number of steps
of iterative refinement performed. Normally this should be set to zero, as
linear solves are normally used as intermediate steps in a non-linear problem
and an exact solution is not normally required. Clearly the more steps used,
the longer a solution takes.

PivotTolerance: Tolerance for partial pivoting test


Type: real; default 0.1; range 0-1.
This parameter is used to control the relative numerical pivot tolerance. If
zero, then no relative numerical test is made. If greater than zero, a pivot
aij(k) musts satisfy the threshold partial pivoting test: | aij(k)| =
PivotTolerance * maxi| aij(k)|, where the notation aij(k) refers to the entry
in the partially factorized matrix just prior to step k of Gaussian elimination.

FrontalAmalgamation: Control how much frontal matrix can


grow due to amalgamation.
Type: real; default 2.0; range 1.0-3.0
Controls how much a frontal matrix can grow due to amalgamation. A value
of 1.0 means that no fill-in due to amalgamation will occur. Some
amalgamation is necessary for efficient use of the Level 3 BLAS.

InitialFactor: Amount of workspace at start as a multiple of


nnz.
Type: real; default 5; range [ 2,100]
This parameter determines the initial amount of real and integer workspace
allocated prior to calling MA38. It is expressed as a multiple of the number of
non-zeros in the initial matrix. The LU factorization typically generates fill-in,
so the decomposition is less sparse than the original. A good default value is
4, but some matrices may generate a lot more fill-in than this. If insufficient
workspace has been allocated, then MA38 sets a flag and causes the AOS
solver to resize one or both arrays, controlled by the parameter
GrowthFactor. However, resizing the matrix every time is inefficient, and if a
resize has taken place, then the user should increase the size of this
parameter.

GrowthFactor: Amount to resize workspace as a multiple of nnz


Type: real; default 1; range [0.0,5.0]

7 Solver Properties Dialog Box 211


This option controls the amount of workspace memory allocated with the
current amount of memory (see InitialFactor) is insufficient to analyse or
factorize the matrix. When the memory is insufficient, MA38 computes an
estimate of the likely amount of memory required (this is only an estimate
because it is not possible to determine the precise memory requirement in
advance or when the numerical values change.)
This option allows an extra GrowthFactor*NNZ of memory to be allocated on
top of the MA38 estimate, where NNZ is the number of non-zero entries in the
matrix, and thus increasingly the likelihood that the subsequent factorizaton
will have enough memory to succeed. The default is 0, which means no extra
memory is allocated. This option can be set above zero (e.g. to 0.5) if it is
taking a long time to factorize the matrix (the SetMatrixVals method is taking
a long time) and it is clear that the memory being used by the DLL is
incrementing in a number of steps during the SetMatrixVals call.

RePivot: MA38 Re-pivoting frequency


Type: integer; default 0; range [0, 10000]
You can use this option to control how often a re-pivot operation on the
matrix is performed by MA38. The default value of 0 means that MA38 re-
pivots the matrix only when a zero pivot is found during factorization (this is
the most efficient, but not necessarily the most robust).
You can change this option if you find that the convergence is being hindered
or is stalled. A typical value in this case is to re-pivot every 5 factorizations.

Linear Solver Tab: MA28


The linear solver is used to solve simple equalities. It is the fundamental
routine that lies at the heart of all modes of simulation. Changes to the linear
solver options affect all solution methods.

MA28: Drop Tolerance


You can alter the drop tolerance to force Aspen Modeler to calculate whether
an element in the occurrence matrix is small enough to be considered zero. If
you increase the value of drop tolerance, more elements are dropped from
the occurrence matrix, and the solution is faster. However, more information
is lost and the linear solvers may not converge.

Non-Linear Solver Tab


From the Non-Linear Solver tab in the Solver Properties dialog box, choose
Diagnostics, or General, or Tolerances when the selection in the Mode field is
‘Standard’, or select an Open non-linear algebraic (NLA) solver when the
selection in the Mode field is ‘Open NLA Solver’.

7 Solver Properties Dialog Box 212


Non-Linear Solver Tab: General
The General option is on the Non-Linear Solver tab in the Solver Properties
dialog box. The non-linear solver is used to converge sets of simultaneous
equations or equations where there is no direct solution.

General: Method
You have a choice of four options for the non-linear solver method.

Option Comments
Newton Most robust, slowest method
Fast Newton Fastest, may not be the best method in some cases
Hybrid Fast, may not converge as well as other methods
Mixed Newton Uses Newton for initialization and steady state steps and
Fast Newton for dynamic steps and is the default method.
This is the best combination of speed and robustness for
most dynamic simulations

General: Newton
Newton calculates a new Jacobian matrix at every iteration. The Newton non-
linear solver method is slower than the other available methods, especially if
there are a lot of procedure calls that do not return derivative information,
because the Jacobian elements for variables output from procedures have to
be calculated numerically. However, Newton can be more robust and may
solve some simulations that fail to converge using Hybrid.
Newton is most useful for steady-state and initialization runs, where solution
speed is not the most important factor.

General: Fast Newton


Fast Newton updates the Jacobian matrix only when convergence progress is
poor. By recalculating the derivatives less frequently, it is usually the fastest
method, but it may take a different path to solution, so its effectiveness
varies.
In general, Fast Newton is the best method when moving a simulation from
one solution to a close neighboring solution. It is recommended that you use
Fast Newton if you are:
• Using the Explicit Euler, Implicit Euler, VSIE or Runge Kutta 4 integrator
options, where the solution of each equation group of the decomposed
simulation advances incrementally with time.
• Running steady-state simulations with good initial estimates.

General: Hybrid
To try to improve performance, Hybrid uses an approximate update method,
where possible, to estimate values of numerical derivatives in the Jacobian
matrix instead of calculating new values every time.

7 Solver Properties Dialog Box 213


Note: Although the Hybrid method can give an increase in
speed, the robustness of the solution may be reduced.

General: Convergence Criterion


You can define the parameters on which a simulation is considered
converged:

Convergence Description
Criterion
Residual Convergence determined by the difference
between the left and right hand side of an
equation
Variable Convergence determined by the largest change in
a variable value during the non-linear solution
Residual and Variable Both Residual and Variable convergence must
happen
Residual or Variable Either Residual or Variable convergence can
happen

General: Maximum Divergent Steps


You can use Maximum Divergent Steps to specify the number of divergent
steps the non-linear solver takes before the solver returns to the previous
best point and tries again.
You can increase this number if you think that the solver is getting close to
converging but proceeding slowly and giving up before reaching the solution.

General: Maximum Step Reductions


You can use Maximum Step Reductions to specify the number of returns to
the previous best point allowed before the solver decides it cannot converge.
You can increase this number if you think that the solver is getting close to
solution but terminates the attempt before it gets to solution.
Increasing the maximum step reductions can help to converge a solution that
fails to converge with the default number of maximum step reductions but
does not appear to be divergent close to the solution point.

General: Maximum Iterations


You can specify the maximum number of iterations taken by the non-linear
solver before the solver stops looking for a solution.
You can increase this value if you think that the solver is not diverging near
the solution point but needs more time to get to a converged solution.

General: Maximum Fast Newton Steps


The number of Fast Newton steps taken before a new Jacobian matrix is
calculated is limited by the value of the Maximum Fast Newton Steps
parameter.
You can increase this number for stable dynamic simulations to try to improve
the speed of integration. If the simulation has fast transients then increasing

7 Solver Properties Dialog Box 214


the maximum number of fast Newton steps before a new Jacobian matrix is
calculated can slow the performance.

General: Dogleg Method


The Dogleg Method option is used to select the method for calculating a
variable step.
The default is not to use the Dogleg method, but to use a Newton-based
method to determine the search direction.
The Dogleg method uses a combination of the direction calculated by a
Newton method and that calculated by a steepest descent method. This may
prove more robust for simulations that are difficult to converge, or when it is
not possible to provide a good initial guess for the solution.
Dogleg has an effect during steady-state runs; the initialization and
re-initialization of dynamic runs; dynamic runs using the Explicit Euler,
Implicit Euler, and VSIE integrators; and estimation runs.

Non-Linear Solver Tab: Diagnostics


The non-linear solver is used to converge sets of simultaneous equations or
equations where there is no direct solution.
You can use the non-linear solver diagnostics to try and understand why a
non-linear equation or group of equations containing more than one equation
is failing to converge. The Diagnostics option is displayed on the Non-Linear
Solver tab in the Solver Properties dialog box.

Diagnostics: Highest Variable Steps


You can define the number of variables shown that take the largest steps
between successive non-linear solver iterations. You can see which variables
are causing the solver to work hardest to get to solution.
With this information, you can change the equation containing these variables
to improve linearity, scale the variables or perhaps give the variable a
different starting value.

Diagnostics: Highest Residuals


Highest Residuals defines the number of equations displayed in the simulation
output that are furthest from residual solution. These equations are those that
have the largest difference between the left and the right hand side. Only the
residuals which are above the absolute equation tolerance are displayed.
You can rearrange or re-scale equations that are consistently holding up
solution, and so improve the speed of convergence.

Diagnostics: Print Linear Algebra for Groups of Size >= n


You can use this option to specify which equation groups send detailed
solution information to the simulation messages window. All equation groups
larger than the size you state display the detailed solution information.

7 Solver Properties Dialog Box 215


Typically you can use this option to determine how hard the linear and non-
linear solvers are working to solve the largest equation groups in your
simulation.

Non-Linear Solver Tab: Tolerances


You can change the default tolerances for the non-linear solvers to try to
improve the speed and robustness of convergence.
The Tolerances option is displayed on the Non-Linear Solver tab in the Solver
Properties dialog box.

Tolerances: Maximum Range Fraction


Use the Maximum Range Fraction option to constrain a variable step to a
fraction of the variable range. The range is the difference between the upper
and lower bound for the variable. The variable step may not exceed the
product of Maximum Range Fraction and this range, that is:
VARIABLE STEP < Maximum Range Fraction ∗ (UPPER BOUND - Lower BOUND )

A value of less than 1 is useful if large variable steps are making convergence
difficult.
Maximum Range Fraction affects steady-state runs; the initialization and
re-initialization of dynamic runs; dynamic runs using the Explicit Euler,
Implicit Euler, and VSIE integrators; and estimation runs.
The default value of 0 means that no restraints are imposed. The valid range
is any positive real number.

Tolerances: Maximum Approach to Bound


The Maximum Approach to Bound option is used to constrain a variable step
that would cross a bound. When solving simultaneous equations, a calculated
step for a variable may violate the bound on that variable. By default, Aspen
Modeler cuts the step so that the updated value is at the point where the step
crosses the bound. It is sometimes better for the step to be cut to some
fraction of the distance to the bound, so that it does not end up on the bound.
This fraction is the Maximum Approach to Bound.
If a simulation converges very slowly as one or more variables move along a
bound, or if the equations become ill-conditioned or singular at the bound,
you can try a value of, for example, 0.9.
Maximum Approach to Bound affects steady-state runs; the initialization and
re-initialization of dynamic runs; dynamic runs using the Explicit Euler,
Implicit Euler, and VSIE integrators; and estimation runs. The default value is
1.0, and the valid range is:
0 < Maximum Approach to Bounds ≤ 1 (real)

7 Solver Properties Dialog Box 216


Tolerances: Absolute and Singularity Perturbation
For steady-state and initialization runs, when the non-linear solver reaches a
point where there is a singularity, the singular variables are moved by an
amount determined by:
SingPerturb IF X ≤ AbsPerturb

– or –
SingPerturb ∗ X IF X 〉 AbsPerturb

Where:
X = Current singular variable value
AbsPerturb = Absolute perturbation
SingPerturb = Singularity perturbation
You can change the values of Absolute Perturbation and Singularity
Perturbation if the default values are not able to move the solution away from
a singularity.
For dynamic runs, no perturbation is used for singularities, and the Absolute
and Singular Perturbation parameters have no effect.

Tolerances: Maximum Variable Step


You can use the Maximum Variable Step to specify the maximum step taken
in a variable by the non-linear solver per iteration. The range is 0.1 to 100
and default is 50.
Reducing this value can improve the robustness of convergence by limiting
(damping) how much the Newton solver can move variables from one
iteration to the next. Reducing this value can also help when a variable is
stepping repeatedly about a solution point but cannot converge to the
solution.
The whole Newton step is scaled by a damping factor α such that for the
Newton step δX in each variable X:
α * ∆X <= ( Maximum Variable Step * |X_c| if |X_c| >
Absolute Perturbation)
( Maximum Variable Step otherwise)
where X_c is the value of X at the current iteration. The Maximum Variable
Step is relative provided the absolute current value of the variable is > the
value of the Absolute Perturbation option; otherwise it is absolute.

Tolerances: Clip Factor


If a Newton step in the non-linear equation solver results in the value of a
variable going outside a bound, then the direction of the Newton step is
truncated. The clip factor determines the method of truncation of the step.
The non-linear solver first determines an internal clip factor value between 0
and 1 to ensure the Newton step does not exceed the bounds for the variable.
If the calculated clip factor is less than or equal to Clip Factor, then the
Newton step is clipped rather than scaled. Each element of the Newton step

7 Solver Properties Dialog Box 217


direction that causes the variable bound violation is clipped so that the step in
that variable results in the variable value being equal to the bound value.
If the calculated clip factor is greater than Clip Factor, the Newton step is
scaled rather than clipped.
If you have defined a value for the Maximum Approach to Bound less than 1,
the value of the variable after the Newton step is not equal to the bound
value but is determined by the Maximum Approach to Bound factor.
If you set the value of Clip Factor to 1, you ensure that the Newton step is
always clipped to the bound. If you set the value of Clip Factor to 0, you
ensure that the Newton step is always scaled to the bound. The default value
of 1e-6 ensures that the scaling approach is used unless the resulting step is
very small, when the clipping approach applies. This means that time is not
wasted making very small steps close to the bound.
When you are considering changing the value of Clip Factor, consider how far
the current solution point is from the final solution. If the current point is far
from the solution, set a small Clip Factor, as this allows a scaled step that
gets towards solution faster. If there are many bound violations, a small Clip
Factor results in fewer variables with values on the bounds. However, a small
Clip Factor may result in slow convergence, as the Newton steps are too
conservative. To arrive at the final solution point within a specified number of
iterations, a larger Clip Factor may be better, as long as this does not mean
that the solution is impeded by bound violations.
You may find that some convergence situations are not affected by Clip
Factor, such as when you have small mole fractions and concentrations in the
solution. In these cases, the benefits of increasing Clip Factor to give a faster
approach to solution are outweighed by the possible closeness of the mole
fraction and concentration values to their bounds.

Non-Linear Solver Tab: Open NLA


Solver
The Open NLA Solver option is displayed from the Mode box on the Non-
Linear Solver tab in the Solver Properties dialog box. The non-linear solver is
used to converge sets of simultaneous equations or equations where there is
no direct solution.
Aspen Custom Modeler® allows external, non-linear algebraic equation
solvers to be plugged in and used in the solution of simulations. To Aspen
Custom Modeler, an external solver is a software component that implements
a number of defined interfaces. These interfaces allow Aspen Custom Modeler
to load the solver, set options and to drive the solution.
For more information on using external nonlinear algebraic solvers, see
Chapter 12.

Note: You can specify an open solver and change the parameters
through automation. For examples of using automation, see the
Aspen Modeler Reference, Chapter 4. If the open solver or
parameters change through automation then those changes will

7 Solver Properties Dialog Box 218


be automatically reflected in this dialog box.

Optimizer Tab
The Optimizer tab in the Solver Properties dialog box enables you to choose
optimization options for your simulation.
You can choose the Optimizer used to solve your optimization problem from
the following list:
• FEASOPT
• Nelder-Mead
• SRQP
• Open NLP - reduced space
• Open NLP - full space
• DMO

Optimizer Tab Reporting Level


The Reporting Level controls the amount of diagnostics information in the
simulation messages window that appears during an optimization simulation.

Value Description
None No diagnostics
Low Information on the solution only
Normal As low plus values of the objective at each iteration and
Lagrange multipliers at the solution (default)
High As normal plus values of the decision, initial and control
variables at each iteration
Very High As high plus constraint and derivative information at
each iteration

Homotopy Tab
The Homotopy tab enables you to specify the options for homotopy steps. You
can perform both steady-state and initialization homotopy runs:
• Steady-state homotopy enables you to step a steady-state solution to
another steady-state solution by defining fixed variables.
• Initialization homotopy enables you to vary the initial conditions of an
initialization run.
On the Homotopy tab, you can change the size of the first homotopy step, the
maximum and minimum step size, and the size by which a step increases and
decreases (depending on the success of the last step).

Important Note:

7 Solver Properties Dialog Box 219


• To use the options you specify on the Homotopy tab, you
must enable homotopy, and specify which fixed variables to
use.

• Messages in the Simulation Messages window from the


homotopy control that refer to values of homotopy variables
are in the base units for the variable, not the selected Units of
Measurement.

Homotopy Options
This section describes the options on the Homotopy tab of the Solver
Properties dialog box.

Initial Homotopy Step


In the Initial Homotopy Step box, you can specify the size of the first
homotopy step following initialization or re-initialization. This size must be
within the range of Maximum Homotopy Step and Minimum Homotopy Step.
The range is any non-zero number to 1, and the default is 0.1.

Maximum Homotopy Step


In the Maximum Homotopy Step box, you can specify the maximum size of
homotopy step. This size must be greater than the Initial Homotopy Step and
Minimum Homotopy Step. The range is any non-zero number to 1, and the
default is 1.

Minimum Homotopy Step


In the Minimum Homotopy Step box, you can specify the minimum size of
homotopy step. This size must be less than the Initial Homotopy Step and
Maximum Homotopy Step. The range is any non-zero number to 1, and the
default is 0.05.

Step Size Increment Factor


In the Step Size Increment Factor box, you can specify the factor by which a
homotopy step increases or decreases following a successful step. The range
is any positive number greater than or equal to 1, and the default is 10. If the
maximum number of iterations over all non-linear groups in the
decomposition is > Step Size Increment Factor, then the homotopy step is
increased by an amount inversely proportional to the number of steps;
otherwise the step size is reduced by a factor of Step_Size / (maximum
number of iterations).

Step Size Decrement Factor


In the Step Size Decrement Factor box, you can specify the factor by which a
homotopy step is cut when the previous homotopy step fails to converge. The
range is any non-zero number less than 1, and the default is 0.5.

7 Solver Properties Dialog Box 220


Estimator Tab
The Estimator tab in the Solver Properties dialog box allows you to choose
one of the following methods to solve your estimation problem:
• Weighted least squares
• Maximum log likelihood
These options are available from the Estimator tab in the Solver Options
dialog box.

Estimator Tab: Least Squares


The Least Squares method minimizes the weighted absolute squared error
between the observed and predicted values of the measurements. You should
set the weights of the measured variables to be the reciprocal of the standard
error (if they are known) of the observations.
To change the Estimation solver options, you can use Automation or the
Solver Options dialog box. From the Estimator tab in the Solver Options
dialog box, you can select least squares estimation. The sum of the
differences between the measured data and the predicted values for the data
points are minimized. The predicted data always conforms to a feasible
solution for the simulation equations.
The following solvers can be used for Least Squares Estimation:
• NL2SOL
• Nelder-Mead
• Open NLP – reduced space

Note: NL2SOL uses the bounds on estimated and reconciled


variables when choosing step size.

NL2SOL: Absolute Function Tolerance


If the absolute value of the sum of the squares of the weighted errors is less
than the absolute function tolerance, the estimation run is considered
converged. The estimation run successfully solves with absolute convergence.
If you use the default value of absolute function tolerance, in most cases the
simulation will not solve by absolute convergence. This is because the default
value of absolute function tolerance is deliberately very small, which means
the measured data must have a very good fit with the simulation equations.
The default value of the absolute function tolerance is 1.0e-20. The valid
range is any real number between 0.0 and 1.0.

NL2SOL: Relative Function Tolerance


If the predicted change in the sum of the squares of the weighted errors for
the next NL2SOL iteration is less than the product of the relative function
convergence and the current value of the sum of the squares of the weighted
errors, and the last NL2SOL iteration achieved less than twice the predicted
decrease in the sum of the squares of the weighted errors, the estimation run

7 Solver Properties Dialog Box 221


is considered converged. The estimation run successfully solves with relative
convergence.
The default value of relative function convergence is good for most
simulations. If you reduce the value of relative function convergence below its
default value, you need to increase the accuracy of the computation of the
estimation experiments by reducing the value of the equation and/or variable
tolerances (Solver Options Tolerances tab). In addition, for dynamic
estimation runs you need to reduce the integrator tolerances. These
additional tolerance changes ensure that the sum of the squares of the
weighted errors are calculated to a sufficient accuracy.
The default value of the relative function tolerance is 1.0e-4. The valid range
is any real number between 0.0 and 0.1.

NL2SOL: Solution Tolerance


If the relative change in the estimated parameters at the end of an NL2SOL
iteration is less than the solution tolerance, and the last NL2SOL iteration
achieved less than twice the predicted decrease in the sum of the squares of
the weighted errors, the estimation run is considered converged. The
estimation run successfully solves with solution convergence.
The default value of relative function convergence is good for most
simulations. If you reduce the value of relative function convergence below its
default value, you need to reduce the value of the residual tolerance. In
addition, for dynamic estimation runs you need to reduce the values of the
absolute and relative equation tolerances. These additional tolerance changes
ensure that the changes in the estimated parameter values are calculated to
a sufficient accuracy.
The default value of the solution tolerance is 1.0e-4. The valid range is any
real number between 0.0 and 1.0.

NL2SOL: False Convergence Tolerance


If an attempted NL2SOL iteration produces less than 10% of the predicted
reduction in the sum of the least squares of the weighted errors, and the
relative change in the sum of the least squares of the weighted errors is less
than the false convergence tolerance, and no other convergence test is met,
then the run is considered to be at a false convergence point and stops.
The default value of false convergence tolerance is 0, which means that the
tolerance is calculated from the machine accuracy. The default value should
be used in most simulations. If you get a false convergence solution,
investigate the following possible causes:

Cause Action
The experiments are Do one of the following:
not being calculated • Increase the Relative Function Tolerance
accurately enough to and the Solution Convergence Tolerance. To
satisfy solution change these tolerances, in the Simulation
tolerances. Explorer make sure Simulation is selected and
then in the Contents pane double-click Solver
Options and then click the Estimator tab.
– or –

7 Solver Properties Dialog Box 222


• Decrease the Absolute Equation
Tolerance, Absolute variable Tolerance, and
Relative Variable Tolerance. To change these
tolerances, in the Simulation Explorer make
sure Simulation is selected and then, in the
Contents pane click Solver Options and then
click the General tab.
The measured Review your model equations to make the
variables is simulation continuous about the estimation
discontinuous around solution point.
the solution point.

If you think you are getting a false convergence due to the reasons given
above, and you want the simulation to stop before reaching such a false
convergence point, increase the value of the false convergence tolerance.
The default value for the false convergence tolerance is 0. The valid range is
any real value between 0.0 and 1.0.

NL2SOL: Maximum Iterations


You can change the number of iterations NL2SOL attempts to solve the
estimation simulation. Increase the number of iterations if you think the
estimation run is converging slowly on a solution point and needs some extra
iterations to get there. Reduce the number of iterations if you want to restrict
the number of attempts to converge the estimation run for a large simulation.
Normally the default value should be used.
The default value for the maximum NL2SOL iterations is 50.
The valid range is any positive integer. Setting the value to zero will perform
a simulation of each of your experiments at the current values of your
estimated variables. This is useful to perform manual testing of how your
measured variables depend on the estimated variables or how good the fit is
for certain values of the estimated variables.

NL2SOL: Reporting Level


The Estimation Reporting Level controls the amount of diagnostics information
in the simulation messages window that appears during an estimation
simulation.
The values are:

Value Description
None No diagnostics
Low Information on the solution only
Normal As low plus values of the objective (least squares or
maximum likelihood) at each iteration and covariance,
correlation and standard error statistics at the solution
(default)
High As normal plus values of the estimated variables at each
iteration
Very High As high plus residual and derivative information at each
iteration

7 Solver Properties Dialog Box 223


Estimator Tab: Maximum Log
Likelihood
The Maximum Log Likelihood method maximizes the log of the likelihood
function of the predicted and observed values. When the log of the likelihood
function (and hence the likelihood function itself since log is a monotonically
increasing function) is maximized, the probability of obtaining the given set of
measurements from the estimated variables is maximized. This corresponds
to getting the best fit of your measurements.
The following solvers can be used Maximum Log Likelihood Estimation:
• FEASOPT
• Nelder-Mead
• Open NLP - reduced space

Solvers for Optimization and


Estimation
The following table details the solvers available for Optimization and
Estimation. Nelder-Mead and Open NLP - reduced space are common solver
options. The other solvers are specific to the tab they are selected from
(including the FEASOPT solver).
Optimization solvers:

Solver Type of Optimization Method


FEASOPT Steady state or dynamic Reduced space
Nelder-Mead Steady state or dynamic Reduced space
SRQP Steady state Full space
Open NLP - reduced Steady state or dynamic Reduced space
space
Open NLP - full space Steady state Full space
DMO Steady state or dynamic Reduced space

Reduced space optimization is where only the additional constraint


equations (inequalities and equalities) in the flowsheet constraints section are
handled by the optimization solver. The remaining flowsheet equations are
solved at each value of the optimization variables (decision, initial and
control) separately by steady state or dynamic simulations
Full space optimization is where both the additional constraint equations and
all flowsheet equations are simultaneously handled by the optimization solver.
It can only be used for steady state optimization.
Estimation solvers:

Solver Type of Estimation


NL2SOL Least squares only

7 Solver Properties Dialog Box 224


FEASOPT Maximum likelihood only
Nelder-Mead Least squares or maximum likelihood
Open NLP - reduced space Least squares or maximum likelihood

NL2SOL, FEASOPT and Nelder-Mead are built in solvers supplied with ACM.
The Open NLP interface allows you to interface your own solver.

FEASOPT
FEASOPT is a feasible path successive quadratic programming optimizer. It
can be used for optimization or maximum log likelihood estimation.

Note: To get a good starting point for FEASOPT, you should first
successfully solve a steady-state or dynamic simulation before
starting an optimization run.

FEASOPT evaluates the objective variable (the maximum likelihood function in


the case of estimation) at the current point and moves the design variables,
initial and control variables (in the case of optimization) or estimated
variables (in the case of estimation) to take the objective variable towards its
optimum value. After solving with the new values of the design, initial, and
control variables or estimated variables, FEASOPT re-evaluates the objective
variable. In this way, FEASOPT steps towards the optimum solution.
FEASOPT solves the simulation at each step subject to:
• Simulation equations
• Variable bounds
• Any constraints applied to the optimization

Note: Any changes you make to solver tolerances or Linear and


Non-Linear options affect an optimization or estimation run using
FEASOPT.

At each step, FEASOPT uses the solvers, equation group decomposition, and
tearing to obtain a steady-state or dynamic solution, depending on the type of
optimization chosen or type of estimation experiments. If after a step a
solution cannot be obtained, FEASOPT goes back to the previously solved
position and tries different values of the design, initial, and control variables
or estimated variables.

FEASOPT: Solution Tolerance


The Solution Tolerance determines whether the improvement in the objective
variable is small enough to consider the optimum point reached. If the
absolute value of the improvement in the objective function is less than the
Optimization Tolerance, the optimization or estimation run completes
successfully.
You may increase the value of the Optimization Tolerance if your simulation
contains discontinuities, or if you suspect that the simulation is poorly scaled.
Increasing the value of Solution Tolerance makes the optimum easier to find,
but the optimum point may not be as accurately located. You may have a

7 Solver Properties Dialog Box 225


simulation that has local optimum values. Making the Solution Tolerance
smaller may help to locate the true optimum point. The tolerance must be
any positive real number. The default is 1.e-4.

Note: You must ensure that this tolerance is greater than the
solver tolerances used to perform the optimization simulations or
estimation experiments. It is recommended that you set this
tolerance to at least an order of magnitude greater than the
solver tolerances.

FEASOPT: Maximum Iterations


The Maximum Iterations determines how many steps towards an optimum
point are attempted before the simulation stops looking for an optimum. The
default value for the Maximum Iterations is 100. The valid range is any
positive integer.
Setting the value to zero will perform a simulation of each of your
experiments at the current values of your estimated variables. This is useful
to perform manual testing of how your measured variables depend on the
estimated variables or how good the fit is for certain values of the estimated
variables.
You may need to increase the Maximum Iterations from the default of 100 in
very rare circumstances. You can increase the Maximum Iterations if you
believe the optimizer is approaching a true optimum, but slowly. If there is a
small improvement in the objective variable at each step, you may be
working in a flat region. Also consider increasing the value of the Solution
Convergence Tolerance.
You may want to reduce this value to avoid excessive computations if the
optimizer has problems in trying to find an optimum solution.

FEASOPT: Maximum Absolute Step


This determines the maximum absolute amount FEASOPT can move the
optimization variables (decision, initial or control variables) from one iteration
to the next. The default value is 0.01 and range 0.001 to 1. FEASOPT will not
move each variable by more than:

{Maximum Absolute Step if Maximum Relative Step*abs(current


value) <=Maximum Absolute Step
{Maximum Relative Step * abs(current value) otherwise
You can use this option to restrict how much FEASOPT moves the optimization
variables which may improve the robustness of some optimization
simulations.

FEASOPT: Maximum Relative Step


This determines the maximum relative amount FEASOPT can move the
optimization variables (decision, initial or control variables) from one iteration
to the next. The default value is 10 and range 0.01 to 10000. FEASOPT will

7 Solver Properties Dialog Box 226


not move each variable by more than:

{Maximum Relative Step * abs(current value) if Maximum


Relative Step*abs(current value) >Maximum Absolute Step
{Maximum Absolute Step otherwise
You can use this option to restrict how much FEASOPT moves the optimization
variables which may improve the robustness of some optimization
simulations.

Nelder-Mead
Nelder-Mead is a direct search solver based on the simplex algorithm (see
reference [1] for details). It:
• Can require many more iterations to converge than gradient based
methods such as NL2SOL or FEASOPT. However, it may be able to solve
estimation problems which fail to converge using NL2SOL or FEASOPT.
• Does not use gradient information. Therefore sensitivities of the measured
variables with respect to the estimated variables are not computed during
the iterations (with the exception of the last one because sensitivities are
required to compute covariance and standard error). This can make each
steady state or dynamic simulation performed during an estimation or
optimization simulation faster.
• Nelder-mead is an unconstrained optimization method but this
implementation has a penalty function to ensure that the solution lies
within the variable upper and lower bounds. It is best suited for estimation
simulations or optimization simulations that do not have additional
equality or inequality constraints. It is sometimes suitable for
optimization simulations with additional constraints provided an
appropriate value penalty parameter is chosen.
• Nelder mead is not guaranteed to always converge to the optimal
solution. On some problems it can converge to a sub-optimal solution. To
check that a converged solution is not sub-optimal, it is recommended to
change the number of restarts and/or initial simplex and perform a
second optimization starting from the previously converged point. The
second optimization may give a better solution than the first.
Reference
[1] W. H. Press, S. A. Teukolsky, W. T. Vetterling, B. P. Flannery, "Numerical
Recipes in FORTRAN. The Art of Scientific Computing", Second edition,
Cambridge University Press 1992.
The Nelder Mead solver has the following options:
• Number of restarts
• Initial simplex
• Maximum iterations
• Optimization tolerance
• Penalty parameter

7 Solver Properties Dialog Box 227


Number of restarts
An integer >=0 with default 1.
This controls the number of times the Nelder Mead solver is automatically
restarted from a converged solution. It is advisable to perform at least one
restart to ensure the optimum has been found because the algorithm can
occasionally terminate at sub-optimal points.

Initial simplex
A double >0.0 with default 0.2.
This controls the initial size of the simplex generated about the initial point.
Each vertex of the simplex is generated by a relative peturbation, that is
perturbing each estimated variable by the value of perturbation option
multiplied by the current absolute value of the initial value. This option can be
used to generate a larger initial simplex if smaller a smaller simplex
converges to a sub optimal solution. It can also be used to restrict the size of
the initial simplex if your flowsheet has robustness problems converging too
far away from the initial point. If the current absolute value of the variable is
less than 1.e-6, then an absolute perturbation is used rather than relative.
Increasing the initial simplex increases the initial search space and can reduce
the number of iterations.

Maximum iterations
An integer >0 with default 500
Controls the maximum number of iterations. Typically Nelder-Mead requires a
large number of iterations to converge so you may need to increase this value
for some problems.

Optimization Tolerance
A double >0 and <=1.
Controls the accuracy to which the Nelder-Mead algorithm computes the
optimum. The algorithm terminates when the relative difference between the
smallest and largest value of the objective over all vertices of the simplex is
less than this tolerance.

Penalty parameter
A double >=1.e-16 <=1.e+30
Controls the amount of penalty applied to the constraint violations when they
are infeasible. The default is 1. Nead-Mead is best suited to unconstrained
optimization, but can be useful for some constrained problems for which you
may need to increase this value so that Nelder Mead obtains that a solution
that satisfies your constraints.

SRQP
SRQP is a successive reduced quadratic programming method to maximize or
minimize the objective function subject to upper and lower bounds on the
variables and general equality and inequality constraints. SRQP handles both

7 Solver Properties Dialog Box 228


the flowsheet equations and additional equality and inequality constraints in
the constraints section of your flowsheet section simultaneously. It can only
be used for steady state optimization and sometimes can be more robust than
the "reduced space" methods such as FEASOPT.
If during the optimization simulation some constraints are found to be
incompatible (no feasible region), SRQP attempts to get around the problem
by allowing some violation of the constraints. This may result in some
variables exceeding their bounds. However, the final solution should lie within
the bounds.
The SRQP solver has the following options:
• Feasibility improvement
• Hessian Scaling
• Maximum Iterations
• Optimization Tolerance
• Print Level
• Variable initialization policy

Feasibility improvement
Integer - 0 (default) or 1
Selecting 1 will keep the residuals of the constraints and flowsheet equations
small as the optimizer searches for the optimum. In order to stay close to the
constraints, extra iterations per optimization step are preformed.

Hessian Scaling
Controls the Hessian scaling policy. 0=no scaling (default), 1=scale. It is
recommended that the default is used unless the variables have initial values
close to the expected solution and are realistically bounded. Scaling affects
the relative weight of the decision variables and their initial values are used to
calculate the scaling factors.

Maximum Iterations
Integer >0
Defines the maximum number of iterations allowed during the optimization
simulation. The default is 100.

Optimization tolerance
Double >0 and <1
Controls the accuracy of the optimization, that is how accurately the optimum
is found and how accurately the solution satisfies the equalities and
inequalities in the constraint section and how small the residuals of your
flowsheet equations are. Default is 0.001.

Print Level
Controls the amount of diagnostic information from SRQP. 1=no information,
2=medium, 3=high, 4=very high. Default is 1.

7 Solver Properties Dialog Box 229


Variable initialization policy
Controls the dependent (free) variable initialization policy. 0=no initialization,
1=initialization (default). If set to 1, then a steady state step is performed
initially before the optimization begins.

NL2SOL
NL2SOL is a least squares nonlinear solver. The algorithm is a variation on
Newton's method in which part of the Hessian matrix is computed exactly and
part is approximated by a secant (quasi-Newton) updating method. To
promote convergence from a poor initial point, a trust-region is used along
with a choice of model Hessian.

Open NLP - reduced space


This allows you to use your own reduced space optimization solver interfaced
using the AspenTech Open Solver (AOS) interfaces.

Open NLP - full space


This allows you to use your own full space optimization solver interfaced using
the AspenTech Open Solver (AOS) interfaces.

DMO
Summary
Solves non-linear optimization problems using an implementation of a variant
of the successive quadratic programming (SQP) algorithm. It performs the
optimization by solving a sequence of quadratic programming sub-problems.
Used extensively for on-line optimization.
Attributes:
Solver type: NLP
DLL Name: aos_dmo.dll
Author: Dimitrios Varvarezos
Dependencies: aos_services.dll (AOS); aos_zedmo.dll, aosutils.dll, blas.dll,
rtanalysis.dll, rtharwell.dll (OOMF)
AOS extended interfaces used: AOSNumericLASystemExtended,
AOSNumericESOExtension, AOSNumericSolverExtension,
AOSNumericESOExtension2
Restrictions:
• Code is not thread or instance safe.
• DLL is built and delivered as part of OOMF, which must be installed.
• Solver parameters have very wide bounds in the AOS wrapper and the
AOS client must therefore ensure that the values are within the bounds as
documented here.

7 Solver Properties Dialog Box 230


• DMO uses a modified version of MA48 for linear equation solving. It is not
possible to switch to a different linear solver.
Use in AspenTech products: ACM; OOMF; Aspen Optimizer.

How to use
The DMO solver implements a variant of the successive quadratic
programming (SQP) algorithm to solve small or large-scale optimization
problems. It performs the optimization by solving a sequence of quadratic
programming sub-problems.
DMO offers various options for controlling the line search and trust region
methods to improve efficiency and robustness, particularly for large problems.
DMO is also useful for solving cases with no degrees of freedom, such as
equation-oriented simulation and parameter estimation.
The general optimization problem that DMO solves can be expressed as
follows:
• Minimize f(x)
• Subject to c(x) = 0
• xmin ≤ x ≤ xmax
Where:
X Vector of unknown variables
F(x) Objective function
C(x) Vector of constraint equations
xmin Vector of lower bounds on x
xmax Vector of upper bounds on x

A simplified description of the DMO algorithm is outlined as follows:


1 Given an initial estimate of the solution vector, x0
2 Set iteration counter, k = 0
3 Evaluate derivative of the objective function, gradient, and the derivative
of the constraints, Jacobian.
4 Initialize or update an approximation of the second derivative matrix, or
Hessian, of the Lagrange function.
The Lagrange function, f(x) + ∑ λici, accounts for constraints through weighting factors λi
, often called Lagrange multipliers or shadow prices.
5 Solve a quadratic programming subproblem to determine a search
direction, dk. In the quadratic programming subproblem, the objective
function is replaced by a quadratic approximation, constraints are
linearized, and bounds are included.
6 Check for convergence or failure. If the optimization convergence criteria
are satisfied or if the maximum number of allowed iterations is reached,
then end.

Convergence is achieved when:


• Objective function gradient <= objective function convergence
tolerance

7 Solver Properties Dialog Box 231


• Scaled or unscaled constraint residuals <= residual convergence
tolerance
7 Perform a one-dimensional search to determine a search step αk so that
xk+αkdk is a better approximation of the solution as measured by a line
search or merit function. The reduction of merit function requirement is
sometimes relaxed to achieve a full correction step.
8 Update iteration counter, k = k + 1, and loop back to step 3.

You can change the following DMO solver parameters referred to in step 6:
• Maximum number of allowed iterations to reach convergence
• Objective and residual convergence tolerance
The DMO solver parameters are grouped into Basic or Advanced type. The
table lists all the DMO solver parameters (the prefix of Basic or Adv in the
description refers to the type of parameter) with links for detailed help on
each parameter. The detailed help is grouped into specific topics relating to
the DMO solver.

Note: We recommend that you start your equation-oriented


solution with the default parameter settings for the Advanced
parameters..

Viewing DMO Solver Report Information


DMO outputs information to two report files:
• EO Solver Report File (*.atslv)
• DMO Active Bounds Report (*.atact)
The DMO Active Bounds Report (*.atact) and EO Solver Report (*.atslv)
report files are similar. However, the Active Bounds report lists all of the
problem variables and independent variables; whereas the Solver Report does
not.
The following sections describe contents of the EO Solver report for the DMO
solver:
• Problem information
• Basic iteration information
• Largest unscaled residuals
• Constrained variables and shadow price
• General iteration information
• Nonlinearity ratios

Problem Information
The EO Solver report begins with a summary of the problem. This shows the
size of the problem and the values of some important parameters.
Model or plant name C2S
Solution case OPTIMIZE
Number of variables 1024
Number of equality constraints 1004
Number of fixed variables 18
Actual degrees of freedom 2

7 Solver Properties Dialog Box 232


Number of lower bounded variables 1024
Number of upper bounded variables 1024
Total number of constraints 3052
Maximum number of iterations 50
Printing frequency -1
Objective function tolerance 1.0D-06
Residual convergence tolerance 1.0D-06
Derivative perturbation size 1.0D-06
Solution mode NORMAL
Maximum number of models 4000
Maximum number of soft bounds 1500
Time of run 15:46:44
Date of run 13-AUG-00

Basic Iteration Information


At each iteration, the following header is printed, showing the iteration
number and the value of the objective function:
+----------------+
| Iteration 0 |
+----------------+

Objective Function => -2.779

Largest Unscaled Residuals


This section of the EO Solver report shows the largest unscaled residuals. A
similar section shows the largest scaled residuals. This section is particularly
helpful when the solver has trouble closing all the residuals, because it points
to the largest residual.
Shadow
Index Most Violated UNSCALED Residuals Residual Price
====== ======================================= ============ =============
975 MSMT.T2.BLKEQN_OFFSET -5.06330D-03 3.17244D-03
974 MSMT.T1.BLKEQN_OFFSET -8.05215D-04 5.21167D-04
575 C2S.BLKEQN_PHSEQBL_81_C2H4 1.72885D-05 8.55130D-03
568 C2S.BLKEQN_PHSEQBL_80_C2H4 1.72406D-05 7.37848D-03
561 C2S.BLKEQN_PHSEQBL_79_C2H4 1.63227D-05 6.39407D-03
582 C2S.BLKEQN_PHSEQBL_82_C2H4 1.61711D-05 9.91235D-03
554 C2S.BLKEQN_PHSEQBL_78_C2H4 1.49203D-05 5.59494D-03
589 C2S.BLKEQN_PHSEQBL_83_C2H4 1.38826D-05 1.14612D-02
547 C2S.BLKEQN_PHSEQBL_77_C2H4 1.33611D-05 4.97392D-03
540 C2S.BLKEQN_PHSEQBL_76_C2H4 1.18602D-05 4.52121D-03

Constrained Variables and Shadow Price


This section of the EO Solver report shows the variables that lie on their
bounds and reports the variable number, which bound is active, the variable
name, the current value and the shadow price. The shadow price is also
known as the Lagrange multiplier. This is the derivative of the objective
function with respect to the value of the constraint and represents the cost for
the constraint.
Projected Active Constraints Shadow
Index for the Next Iteration Bound Price
====== ======================================= ============ =============
949 Upper Bnd C2SDDEF.SPC.MOLEFR.C2H6 2.00000D-04 -4.32924D+02

The shadow price is based on the value of the objective function that is seen
by DMO. That means the shadow price is in SI units, such as $/sec, and is
affected by any scaling. This is true even if you declare the units to be
something other than SI (such as $/HR).

7 Solver Properties Dialog Box 233


Consider this example. We have a tower with a composition constraint,
expressed as a mole fraction of a component. The following table shows the
results of two optimization runs at two different values of the composition
constraint:
Value Objective Shadow Price
0.0002 2.853 432.924
0.0003 2.893 258.664

The large change in the shadow price indicates that the effect of the
composition on the objective function is very nonlinear. We can manually
estimate the average shadow price in this region by a finite difference
method:
Price = ∆Obj/∆x = ( 2.893-2.853 ) / ( 0.0003 - 0.0002 ) = 400.00 $/sec/mole
fraction
This value lies between the two prices.
If the objective function had a scale factor of 100., we would get the
following:
Value Objective Shadow Price
0.0002 285.4 43290.7
0.0003 289.3 25860.2

We would have to remember to unscale the shadow price by dividing by 100.

General Iteration Information


This section of the EO Solver report appears after the residual output:

Iteration status => Normal


Degrees of freedom => 2
Constrained variables => 0
Current degrees of freedom => 2
Number of function evaluations => 0
Number of Jacobian evaluations => 1
Objective function convergence function => 4.78209D-03
Residual function convergence function => 5.78057D-06
LU decomposition time (seconds) => 2.77D-01
Search direction time (seconds) => 3.91D-01

Reported Item Description


Iteration status The exit condition of that iteration, where:
Normal indicates a normal successful iteration.
Warning indicates a successful iteration despite some solver difficulties.
Error indicates a failure.
Solved indicates the final iteration of a successfully solved problem.
Degrees of freedom The number of declared independent variables in the problem
Constrained variables Those variables at bounds in the QP subproblem
Current degrees of The degrees of freedom less the constrained variables. This is the true
freedom degrees of freedom for the problem. A highly constrained solution is
one that has very few current degrees of freedom.
Number of function An accumulative count of function evaluations, which generally
evaluations matches the number of iterations
Number of Jacobian An accumulative count of Jacobian evaluations, which generally
evaluations matches the number of iterations
Objective function The norm of the Jacobian for the objective function. At the solution,

7 Solver Properties Dialog Box 234


convergence function this value should be near zero.
Residual function The sum of the scaled residuals. At the solution, this value should be
convergence function near zero.

Nonlinearity Ratios
This section of the EO Solver report shows the nonlinearity ratio of the worst
block, the objective function, and the worst equations. The criterion is the
accuracy of the predicted change in the equation. If the function is linear,
then the new value would match the predicted value and the nonlinearity
ratio would be one. A value of the ratio other than one indicates some degree
of nonlinearity. A negative value indicates that the function value moved in
the opposite of the expected direction. Large negative values could indicate a
discontinuity or bad derivative.
This section also shows the step size for the iteration.
Model nonlinearity ratios =>
----------------------------

C2S = 0.69071

Model nonlinearity ratios of 6 model(s) between 0.99 and 1.01

Objective function nonlinearity ratio => 1.0000

Non-Linearity Report for Iteration 11 : Step Fraction = 1.00000D+00

Index Worst Equation Non-Linearity Ratios Ratio Deviation


===== ======================================== ============ ============
484 C2S.BLKEQN_PHSEQBL_68_C2H4 1.53058D+00 5.30578D-01
491 C2S.BLKEQN_PHSEQBL_69_C2H4 1.48206D+00 4.82055D-01
498 C2S.BLKEQN_PHSEQBL_70_C2H4 1.43615D+00 4.36148D-01
499 C2S.BLKEQN_PHSEQBL_70_C2H6 1.43222D+00 4.32219D-01
505 C2S.BLKEQN_PHSEQBL_71_C2H4 1.39245D+00 3.92447D-01

Guidelines for Using the DMO Solver


In this section, we describe some ideas to improve the performance of the
DMO solver and to help diagnose common problems, including:
• Scaling
• Handling infeasible solutions
• Handling singularities
• Variable bounding
• Run-time intervention

Scaling
Generally, it is not necessary to scale your equations or variables beyond
what is done by default in the models. However, it may be more efficient to
scale your objective function.
The scaling of the objective function plays an important role, since it affects
the overall convergence behavior. This is particularly important in cases
where there is a large change between the original value of the objective and
the expected optimum.
A good rule of thumb is to scale the objective function so that its value is on
the order of 10 to 1000.

7 Solver Properties Dialog Box 235


Handling Infeasible Solutions
Infeasible solutions often occur during optimization cases where it is not
possible to simultaneously solve all the equations while respecting all the
variable bounds. This does not happen in simulation cases, because DMO
ignores bounds in simulation cases.
If you solve a simulation case that violates a bound, then the optimization
case will start at an infeasible point. In this case, the following is reported in
the EO Solver report:
Information => QP step for variable 1157: C2SDDEF.SPC.MOLEFR.C2H6
was adjusted to satisfy its UPPER bound = 2.0000000E-04
The size of QP step violation was = 2.5673465E-04

Here, the value of the variable had to be adjusted to respect the bound. When
the optimization proceeds and there is no feasible solution for the equality
constraints, the screen output might look like this:
Residual Objective Objective Overall Model
Convergence Convergence Function Nonlinearity Nonlinearity Worst
Iteration Function Function Value Ratio Ratio Model
--------- ----------- ----------- ----------- ------------- ------------- ------
Warning ... QP slack variable = 2.29070D-01
0 9.312D-04 4.809D-03 -2.779D+00 9.968D-01 -2.834D-01 C2S
Warning ... QP slack variable = 1.80624D-01
1 5.244D-04 4.667D-02 -2.792D+00 2.900D-01 -1.846D+02 C2S
Warning ... QP slack variable = 1.44771D-01
2 1.552D-02 5.479D-02 -2.922D+00 -7.475D-01 -1.540D+01 C2S
Warning ... QP slack variable = 6.09502D-01
3 3.853D-02 2.379D-03 -3.083D+00 9.908D-01 9.914D-01 C2S
Warning ... QP slack variable = 1.87163D-01
4 1.496D-02 1.040D-02 -3.075D+00 8.346D-01 6.012D-01 C2S
Warning ... QP slack variable = 3.18508D-01
+---------------------- ERROR ----------------------+
Error return from [DMO] system subroutine DMOQPS
because the problem has NO FEASIBLE SOLUTION.
Action : Check the bounds that are set on variables
to insure consistency. Check the .atact file
for information on initial
infeasibilities.
+---------------------------------------------------+
Error return, [DMO] System Status Information = 5
Optimization Timing Statistics Time Percent
================================ ======== =======
MODEL computations 1.32 secs 31.10 %
DMO computations 0.91 secs 21.28 %
Miscellaneous 2.03 secs 47.61 %
-------------------------------- --------- -------
Total Optimization Time 4.26 secs 100.00 %
Updating Plex
Problem failed to converge

Note the messages from the QP indicating an invalid value for a slack
variable.
To solve this problem, you need to be aware of the initial message, indicating
that the initial value of a variable violated its bound. In this case,

7 Solver Properties Dialog Box 236


C2S.SPC.REFL_RATIO_MASS is causing the problems. Unfortunately, the EO Solver
report does not list this variable as constrained, since it could never solve the
QP successfully.

Handling Singularities
Singularities often occur when a library model is moved into a region where
the equations are not well defined. The most common example of this is when
a stream flow becomes too small. If singularities exist, they are usually
detected at the start of the problem. In this case, some information is written
to the EO Solver report file (*.atslv), which can help locate the cause of the
problem. In general, you should prevent stream flows from going near zero
by placing nonzero lower bounds on the flow (e.g., 10 kg/hr). This is
especially important on streams from flow splitters or feed streams whose
total flow is being manipulated. In the case of a singularity the following
message is displayed:
+-------------------- WARNING ----------------------+
A NUMERICALLY SINGULAR matrix is detected during
the ANALYSIS phase of LU decomposition.
The number of dependent equation set(s) detected = 1
Check the output file for more information.
+---------------------------------------------------+

The EO Solver report includes information on the possible cause of the


singularity similar to the following:
+-------------------- WARNING ----------------------+
A NUMERICALLY SINGULAR matrix is detected during
ANALYZE phase of LU decomposition.
WARNING: The dependent equation set is NOT unique.
It depends on the options for performing
LU decomposition.
==> Dependent equation set: 1
The partial derivatives of the following
equations with respect to variable
1: Strm 1 moles lbmol/h
in the reduced matrix are zero.
Equation -> 10: Enthalpy balance M Btu/lbmol
is a function of the following variables:
1: Strm 1 moles lbmol/h = 0.00000D+00 -> Calc
4: Strm 1 enth M Btu/lbmol = -7.45977D+01 -> Const
12: Strm 2 moles lbmol/h = 0.00000D+00 -> Const
15: Strm 2 enth M Btu/lbmol = -7.45977D+01 -> Const
23: Heat loss MM Btu/h = 0.00000D+00 -> Const
25: Prod moles lbmol/h = 8.93760D-07 -> Calc
28: Prod enth M Btu/lbmol = -7.45977D+01 -> Calc
Equation -> 9: Prod C9H20_1 mf
is a function of the following variables:
1: Strm 1 moles lbmol/h = 0.00000D+00 -> Calc
10: Strm 1 C9H20_1 mf = 4.52017D-01 -> Const
12: Strm 2 moles lbmol/h = 0.00000D+00 -> Const
21: Strm 2 C9H20_1 mf = 4.52017D-01 -> Const
25: Prod moles lbmol/h = 8.93760D-07 -> Calc
34: Prod C9H20_1 mf = 4.52017D-01 -> Calc

Sometimes, singularities are simply caused by the optimization being too


aggressive. This moves the models into a region where the equations are not
well defined. To make the optimization more robust, DMO has a creep mode.
This mode simply causes smaller steps to be taken for a specified number of
iterations.

7 Solver Properties Dialog Box 237


When the creep mode is enabled, the following message is displayed at each
iteration:
<Line Search Creep Mode ACTIVE> ==> Step taken 1.00D-01

By default, this will operate for 10 iterations with a step size of 0.1. You can
use the creep mode Iterations and Step size parameters to change these
values.

Variable Bounding
By default DMO does not respect bounds during the solution of an EO
Simulation or Parameter-Estimation case. However, you can impose bounds in
a square case by using a different line search parameter. This is
recommended only in cases where there are truly multiple solutions to a
model (e.g. the cubic equation) and you want to use a bound to eliminate an
unwanted solution.
To use this mode, change the LINESEARCH parameter to square.
In general, it is not recommended to heavily bound an optimization problem
for reasons that are both practical and algorithmic. Bounds on independent
variables are recommended in order to avoid unbounded problems. All other
bounds should be used only if they are absolutely necessary. Finally,
redundant bounds should be avoided.

References
None.

Solver parameters
The solver parameters are grouped in different types: Basic and Advanced.
Within Basic, there are two sub-groups – Search and Report. Within
Advanced, there are six sub-groups – Search, QP1, QP2, Linear algebra 1,
Linear Algebra 2 and Workspace. These grouping are useful for guiding the
user to the scope, effect and complexity of each group of parameters.

Name Description
ACTIVEINIT Adv.QP2: Restore active set? (0=no;1=yes)
ACTIVERPT Adv.QP1: Print initial active set? (0=no;1=yes)
ACTIVESAVE Adv.QP2: Save active set? (0=no;1=yes)
ACTIVESPACE Adv.Workspace: Active set workspace factor
ADCVITER Adv.Search: Iterations start
ADCVMETH Adv.Search: Trust region flag (0=off;1=on)
ADCVOBJCVG Adv.Search: Starting objective convergence tolerance
ADCVRESCVG Adv.Search: Starting residual convergence tolerance
ANALYSISTHRES Adv.LinAlg1: Fill-in monitoring factor
BOUNDRPT Adv.QP1: QP report bounds (0=off;1=on)
BTF Adv.LinAlg2: Block lower triangularization? (0=no;1=yes)
CREEPFLAG Basic: Enable(1)/disable(0) creep mode
CREEPITER Basic: Number of creep steps
CREEPSIZE Basic: Creep step size fraction
CWORKF Adv.LinAlg2: Density ratio

7 Solver Properties Dialog Box 238


DENSITYRATIO Adv.LinAlg2: Density ratio
DROPTOL Adv.LinAlg1: Drop tolerance
FACTORSPACE Adv.Workspace: Linear algebra factorisation workspace factor
FACTORSPEED Adv.LinAlg2: Factorisation speed (1=normal;2=fast)
FREEONLY Adv.LinAlg2: Free variables only? (0=no;1=yes)
HESSIANSCL Basic.Search: Hessian scale
HESSIANUPDATES Basic.Search: Hessian updates stored
IPSIRPT Adv.QP1: Infeasibility report level (0=off;1=brief;2=full)
IWORKF Adv.Workspace: Integer workspace factor
LINESEARCH Basic.Search: Line search algorithm
(0=Exact,1=Square,2=Residual,3=Normal
LINESRCMODE Basic.Search: Line search control
(0=Normal,1=Aggressive,2=Conservative)
LSMODEITER Basic.Search: Line search iterations
LUSTATS Adv.LinAlg2: Report statistics (0=no;1=yes)
MAXITER Basic: Maximum number of iterations
MINBTFSIZE Adv.LinAlg2: Minimum block size
MINITER Basic: Minimum number of iterations
OBJCVG Basic: Objective convergence tolerance
PIVOTANAL Adv.LinAlg1: Pivot Analysis frequency (0=Medium;1=;2=
PIVOTSEARCH Adv.LinAlg1: Number of columns to search for pivots
PIVOTTHRESH Adv.LinAlg1: Stability threshold
PIVOTZERO Adv.LinAlg1: Zero pivot threshold
PRINTFREQ Basic.Report: Iteration print frequency (-ve sign:normal;+ve
sign:full)
QPCONVTOL Adv.QP2: QP convergence tolerance
QPDEPDIAG Adv.QP1: QP dependencies output
target(0=Neither;1=File;2=FileandScreen
QPHESSIANUPD Adv.QP2: Hessian updates stored
QPITER Adv.QP2: Incomplete QP parameter
QPMICROINF Adv.QP1: QP micro infeasibility handling switch (0=off;1=on
QPMICROMAX Adv.QP1: QP micro infeasibility maximum corrections
QPMICROTOL Adv.QP1: Micro infeasibility bound relaxation tolerance
QPSTATS Adv.QP1: QP statistic reporting (0=off;1=on)
RESCVG Basic: Residual convergence tolerance
RIGORUPDATES Adv.QP2: QP rigorous constraint updates
RWORKF Adv.Workspace: Real workspace factor
SAVEJDFFILE Expert: 1=Creates a total derivative of Jacobian
SCREENFORM Basic.Report: Target for solver output (0=File;1=MessagesHandler)
SEARCHMODE Basic.Search: Hessian initialisation
(0=aggressive;1=normal;2=advanced;3=scaled)
SINGULARHAND Adv.LinAlg2: Singularity
handling(0=normal;1=active;2=structual;3=none)
TRUSTITER Adv.Search: Trust region fixed iterations
TRUSTMODE Adv.Search: Trust region method
(0=Normal;1=Any;2=Iterations;3=Objective;4=Resid;5=All
TRUSTRAMPIT Adv.Search: Trust region ramp iterations
TRUSTSIZE Adv.Search: Trust region initial size
USEDROPTOL Adv.LinAlg1: Drop small Jacobian entries? (0=no;1=yes)
VARSCALE Basic.Search: Variable scaling factor (0=off;1=on)

7 Solver Properties Dialog Box 239


VMS_P1 Expert: VMS workspace offset (do not use)

DMO Basic Solver Parameters


Use these parameters to specify the commonly used parameters that control:
• The accuracy, performance, and robustness of the DMO solver
• Diagnostic reporting for variables and residuals
There are the most commonly used parameters for controlling the accuracy,
performance, and robustness of the DMO solver.
Convergence is achieved if the residual and objective function tolerances are
satisfied, or if the maximum number of allowed iterations is reached. Tighter
convergence tolerances usually increase the accuracy of the solution at the
expense of additional running time.

MAXITER: Basic: Maximum number of iterations


Type: integer; Default 50; Range [0,2147483647]
Lets you specify the maximum number of SQP iterations allowed.

MINITER: Basic: Basic: Minimum number of iterations


Type: integer; Default 0; Range [0, 2147483647]
Lets you specify the minimum number of SQP iterations allowed.

OBJCVG: Basic: Objective convergence tolerance


Type: real; Default 1.e-6; Range [0,1e+35]
Lets you specify the residual convergence tolerance.

RESCVG: Basic: Residual convergence tolerance


Type: real; Default 1.e-6; Range [0,1e+35]
Lets you specify the residual convergence tolerance.

Viewing Iteration Summary Information


By default DMO displays iteration summary information via
AOSMessagesHandler and to the DMO .atact and .atslv files. Use the
following options to determine the amount of information displayed.

PRINTFREQ: Basic.Report: Iteration print frequency (-ve


sign:normal;+ve sign:full)
Type: integer;
Range: n<0 print normal/brief information every nth
iteration
0 no information is printed
n>0 print full information every nth iteration

The diagnostic printing frequency for variables and residuals, where variables
are residuals are printed at every nth iteration. The default is -1.

7 Solver Properties Dialog Box 240


Brief prints the ten worst residuals (default); Full prints all variables and
residuals

Note: Full print can result in a very large amount of output..

This is a sample of the Control Panel output:


Residual Objective Objective Overall Model
Convergence Convergence Function Nonlinearity Nonlinearity Worst
Iteration Function Function Value Ratio Ratio Model
--------- ----------- ----------- ---------- ------------ ------------ -------
0 5.781D-06 4.782D-03 -2.779D+00 9.950D-01 -4.485D+00 C2S
1 1.640D-04 2.774D-02 -2.792D+00 5.528D-01 -2.011D+01 C2S
2 5.560D-03 4.533D-03 -2.870D+00 9.020D-01 9.269D-01 C2S
3 1.247D-04 1.109D-03 -2.857D+00 7.547D-01 9.498D-01 C2S
4 9.993D-06 2.506D-05 -2.853D+00 9.233D-01 9.510D-01 C2S
5 2.751D-07 7.327D-06 -2.853D+00 9.504D-01 8.874D-01 C2S
6 4.162D-08 1.637D-05 -2.853D+00 5.642D-01 -3.939D+00 C2S
7 6.724D-07 7.624D-05 -2.853D+00 5.956D-01 -1.281D+00 C2S
8 9.962D-07 4.329D-05 -2.854D+00 9.176D-01 8.254D-01 C2S
9 2.691D-07 3.344D-06 -2.854D+00 7.505D-01 6.581D-01 C2S
10 1.324D-07 4.748D-06 -2.854D+00 8.463D-01 6.907D-01 C2S
11 4.804D-08 1.700D-06 -2.854D+00 9.487D-01 8.925D-01 C2S
12 1.395D-08 4.722D-07 -2.854D+00
*******************************************************************************
Successful solution.
Optimization Timing Statistics Time Percent
================================ ======== =======
MODEL computations 2.38 secs 40.88 %
DMO computations 0.72 secs 12.40 %
Miscellaneous 2.72 secs 46.72 %
-------------------------------- --------- -------
Total Optimization Time 5.83 secs 100.00 %

Here, the Objective Convergence Function refers to the Jacobian of the


objective function. The Nonlinear Ratio is a measure of the nonlinearity of the
problem. The closer the value is to one, the more linear the problem. A
negative value indicates that the problem behaved in the opposite of what
was expected. Near the solution, as the step sizes become small, this value
becomes close to one.
The last section of the output shows the execution times for the various parts
of the problem.
In this example, we can see that convergence was achieved when the residual
and objective convergence functions were less than their respective
tolerances at iteration 12.
From this output, we also see that there have been no line searches. Thus the
step size for each iteration is one. When a line search is performed for an
iteration, a message similar to this appears:
<Line Search ACTIVE> ==> Step taken 3.26D-01

7 Solver Properties Dialog Box 241


SCREENFORM: Basic.Report: Target for solver output
(0=File;1=MessagesHandler)
Type: integer;
Range: 0 iteration information sent to file and
AOSMessagesHandler
1 iteration information sent to
AOSMessagesHandler only

Note: file (.atslv) output shows more significant figures.

Basic Search options


The parameters line search options, including parameters for initializing or
updating the second derivative matrix, or Hessian. You can use these
parameters to set the convergence behavior of the DMO solver between
conservative and aggressive.

SEARCHMODE: Basic.Search: Hessian initialisation


(0=aggressive;1=normal;2=advanced;3=scaled)
Type: integer;
Range: 0 Aggressive
1 Normal (default)
2 Advanced
3 Scaled

Lets you select the Hessian initialization mode:


Aggressive - Uses small values. This mode moves the problem to its bounds
faster than the normal mode and is the preferred mode for highly constrained
optimization problems with few degrees of freedom at the solution.
Normal – Uses identity matrix.
Advanced – Uses second order information. This mode is recommended for
problems with many degrees of freedom at the solution. It is ideal for
reconciliation problems.
Scaled – Combines small values (aggressive) and second order information
(advanced). This mode is recommended for highly constrained optimization
problems with few degrees of freedom at the solution and a nonlinear
objective function.

VARSCALE: Basic.Search: Variable scaling factor (0=off;1=on)


Type: integer
Range: 0 off
1 on (default)

Lets you specify whether to enable variable scaling.

HESSIANSCL: Basic.Search: Hessian scale


Type real; Default 1.0; Range [1.e-9,2]

7 Solver Properties Dialog Box 242


Lets you specify the scaling factor for scaling the identity matrix when using
the scaled Hessian initialization mode.

HESSIANUPDATES: Basic.Search: Hessian updates stored


Type integer; Default 0; Range [0, 2147483647]
Lets you specify the number of Hessian updates kept before reinitializing.

LINESEARCH: Basic.Search: Line search algorithm


(0=Exact,1=Square,2=Residual,3=Normal
Type integer;
Range: 0 Exact
1 Square
2 Residual
3 Normal (default)

Lets you select the line search algorithm:


Exact: Exact penalty. This is too conservative for most practical problems.
Residual: A proprietary line search designed to initially favor convergence of
residuals over the objective function improvement.
Normal: A proprietary line search designed to balance robustness with
efficiency.
Square: A line search designed to attempt enforcing bounds on cases with no
degrees of freedom. It should be used only in cases where there are multiple
solutions to a problem and the desired one lies within the bounds.

LINESRCMODE: Basic.Search: Line search control


(0=Normal,1=Aggressive,2=Conservative)
Type: integer;
Range: 0 Normal (default)
1 Aggressive
2 Conservative

Lets you select the line search step control.

LSMODEITER: Basic.Search: Line search iterations


Type: integer; Default 0 or 5; Range [0,2147483647]
Lets you specify the number of step control iterations. If the step control
(LINESRCMODE) is Normal, the default is 0; otherwise the default is 5.

Using the Creep Mode


DMO has a creep mode to make the optimization more conservative and
robust. This mode simply makes the optimizer take smaller steps for a
specified number of iterations.
Creep mode is very helpful when the problem diverges. It can also prevent
the DMO optimizer from making aggressive moves that cause singularities
when models are taken into regions where the equations are not well defined.
• The following options control the use of the Creep mode:

7 Solver Properties Dialog Box 243


CREEPFLAG: Basic: Enable(1)/disable creep mode
Type: integer;
Range: 0 off (default): disables creep mode
1 on: enables creep mode

CREEPITER: Basic: Number of creep iterations


Type: integer; default 10; range [0,2147483647]
The number of iterations to perform creep steps.

CREEPSIZE: Basic: Creep step size fraction


Type: real; default 0.1; range [1.e-10, 1]
The step size, as a fraction of the full step size when in creep mode.

Advanced Solver Parameters


Use these parameters to specify:
• Advanced search and convergence parameters for the DMO solver
• DMO solver parameters related to the quadratic programming (QP)
subproblem
• Parameters for controlling the solution of the sparse linear equation
systems that arise during the DMO solution process
• More memory workspace
In most cases, the recommended default values are sufficient.
Use the trust region parameters to enable and control a trust region for the
optimization variables. Use the advanced convergence parameters to control
the method for terminating optimization moves while closing any remaining
open residuals.

Advanced Search options


These include parameters for optimization variables and advanced
convergence parameters to control the method for terminating optimization
moves while closing any remaining open residuals.

TRUSTMODE: Adv.Search: Trust region method


(0=Normal;1=Any;2=Iterations;3=Objective;4=Resid;5=All
Type: integer
Range: 0 None (default)
1 Any
2 Iterations
3 Objective
4 Residual
5 All

Lets you select the method for terminating the optimization moves while
closing any remaining residuals.

7 Solver Properties Dialog Box 244


ADCVITER: Adv.Search: Iterations start
Type integer; Default 100; Range [0,2147483647];
Lets you specify the number of iterations before activating the advanced
convergence method.

ADCVOBJCVG: Adv.Search: Starting objective convergence


tolerance
Type real; Default 1,e-6; Range [0,1+e35];
Lets you specify the convergence tolerance threshold for the objective
function, before activating the advanced convergence method.

ADCVRESCVG: Adv.Search: Starting residual convergence


tolerance
Type real; Default 1,e-6; Range [0,1+e35];
Lets you specify the residual convergence tolerance threshold before
activating the advanced convergence method.

Applying a Trust Region


The application of a trust region limits the optimization moves for the
optimized variables only. The optimized variables are allowed to move within
an initial range for a fixed number of iterations. The size of the trust region is
specified as a fraction of the original variable bound range. Following the fixed
iterations, the size of the trust region is gradually increased until it reaches
the original variable bound range.
These options provide better reliability and execution efficiency to a number
of problem classes such as parameter reconciliation (typically found in
refinery optimization) and design optimization. In some cases, up to 80%
improvement of execution time has been reported.

TRUSTSIZE: Adv.Search: Trust region initial size


Type real; Default 0.1; Range [1e-6,1]
The range that the optimized variables are initially allowed to move for all of
the fixed iterations, expressed as a fraction of the original variable bound
range. The default is 0.1.

ADCVMETH: Adv.Search: Trust region flag (0=off; 1=on)


Type integer;
Range: 0 Disables the application of a trust region
(default)
1 the application of a trust region that limits the
optimization

TRUSTITER: Adv.Search: Trust region fixed iterations


Type integer; Default 2; Range [0,2147483647];
The number of iterations that the trust region will be applied with a fixed size.

7 Solver Properties Dialog Box 245


TRUSRAMPIT: Adv.Search: Trust region ramp iterations
Type integer; Default 2; Range [0,2147483647];
The number of iterations, following the fixed iterations, over which the size of
the trust region is gradually increased until it reaches the original variable
bound range.

QP options 1
These advanced DMO solver parameters are related to the quadratic
programming (QP) subproblem. Usually, the default values should be used
with these advanced parameters.
You can use the micro infeasibility handling option when a problem may be
incorrectly declared as infeasible due to round-off error.
You can also enable diagnostic reporting of the QP subproblem.
Use the micro infeasibility handling option when a problem may be incorrectly
declared as infeasible due to roundoff error and turn on diagnostic reporting
for the QP subproblem.

IPSIRPT: Adv.QP1: Infeasibility report level


(0=off;1=brief;2=full)
Type integer;
Range: 0 Off - suppresses all infeasibility information,
except slack value (default)
1 Brief - reports only the top three contributors
of each category.
2 Full - reports all the relevant information on
the likely causes (equations, fixed variables,
bounds) of the infeasibility

Flag controlling the amount of information printed in the OUT file as a result
of an infeasible QP problem.

BOUNDRPT: Adv.QP1: QP report bounds (0=off;1=on)


Type integer;
Range: 0 Do not report bounds
1 Report bounds (default)

Lets you specify whether to report all bounds in the active file.

QPDEPDIAG: Adv.QP1: QP dependencies output


target(0=Neither;1=File;2=FileandScreen
Type: integer;
Range: 0 Neither
1 File
2 FileandScreen–(default)

Lets you select the output device for reporting warning messages on linear
dependencies when an active set change causes a singularity:
FileandScreen – messages are written to the output report file and displayed
on the “terminal” or “window” on the GUI (via the AOSMessagesHandler);

7 Solver Properties Dialog Box 246


File – messages are written to the output report file only.
Neither – messages are not reported.

QPSTATS: Adv.QP1: QP statistic reporting (0=off;1=on)


Type: integer
Range: 0 off (default)
1 on

Lets you specify whether to enable diagnostic reporting for the QP


subproblem. If the report print option is Full, the report can be very large,
including the Jacobian.

Using Micro-Infeasibility Handling


This option pertains to the situation where a problem may become infeasible
due to very small errors in one or more constraints. This often happens in
optimization cases as a result of round-off or machine precision errors, or
loose convergence tolerance.
Employing this option leads to far fewer cases of solver failure due to
infeasible problems, thus improving robustness and enhancing usability.
Use the micro infeasibility handling option when a problem may be incorrectly
declared as infeasible due to roundoff error and turn on diagnostic reporting
for the QP subproblem.

QPMICROINF: Adv.QP1: QP micro infeasibility handling switch


(0=off;1=on)
Type integer;
Range: 0 Disable (default)
1 Enables the Micro Infeasibility handling in the
QP

QPMICROTOL: Adv.QP1: Micro infeasibility bound relaxation


tolerance
Type real; Default 1.e-12 ; Range [0,1e+35]
The absolute relaxation of an infeasible bound in the QP while micro-
infeasibility handling is enabled.

QPMICROMAX: Adv.QP1: QP micro infeasibility maximum


corrections
Type integer; Default 5; Range [0, 2147483647]
Lets you specify the maximum number of micro-infeasibility handling
attempts that can be handled in one DMO iteration.

QP options 2
These advanced DMO solver parameters are related to the quadratic
programming (QP) subproblem. Usually, the default values should be used
with these advanced parameters.

7 Solver Properties Dialog Box 247


You can use active set initialization to improve convergence of planning
problems that have a large number of degrees of freedom and often involve
the solution of a solved problem that has been slightly modified. The reuse of
active set information from previous solutions is expected to decrease
solution times and potentially increase success rates.
Specify active set initialization parameters for improving convergence of
planning problems that have a large number of degrees of freedom and often
involve the solution of a solved problem that has been slightly modified.

QPCONVTOL: Adv.QP2: QP convergence tolerance


Type: real; Default 1e-10; Range [0,1e+35]
Lets you specify an internal QP convergence tolerance.

Warning: Changing the default value may degrade solution


performance and robustness.

QPHESSIANUPD: Adv.QP2: Hessian updates stored


Type: integer; Default 20; Range [0,2147483647]
Lets you specify the number of QP Hessian updates stored.

QPITER: Adv.QP2: Incomplete QP parameter


Type: integer; Default 10; Range [1,10]
Lets you specify the degree of completeness in finding the optimal active set
at each QP iteration, for the first 10 iterations. The values are between 1 and
10, where 1 is the most incomplete and 10 is the most complete.

RIGORUPDATES: Adv.QP2: QP rigorous constraint updates


Type: integer; Default 25; Range [1,2147483647]
Lets you specify the number of constraint updates before a rigorous analysis
phase.

Specifying Active Set Initialization Parameters


The active set is the set of variable bounds that hold with equality at any
feasible point. The active set initialization procedure in DMO provides both
efficiency and robustness. It produces a "warm" start, based on the existing
information of a successful execution. This is very important for applications
with a large number of degrees of freedom (above 100). For such
applications, up to 50% improvement in execution speed has been reported in
addition to improved robustness.

ACTIVESAVE: Adv.QP2: Save active set? (0=no;1=yes)


Type: integer;
Range: 0 No – do not save active set (default)
1 Yes - writes to the .set file every time a QP
subproblem successfully converges in
Optimization and Reconciliation run modes.

7 Solver Properties Dialog Box 248


The file contains information on which
variables were active at bounds. When the
"restore active set" parameter is set to Yes,
the information in the file can be used to
initialize the active set of another run.

ACTIVEINIT: Adv.QP2: Restore active set? (0=no;1=yes)


Type integer;
Range: 0 Do not restore the active set (default)
1 The information in the .set file is used to
initialize the active set as an initial guess of the
active set.

ACTIVERPT: Adv.QP1: Print initial active set? (0=no;1=yes)


Type integer;
Range: 0 Do not print the initial active set (default)
1 Print the initial active set

Flag that controls the reporting of the active set at the end of iteration zero.
It is written to the <prob>.out file.

Linear Algebra options 1


Use these parameters for controlling the solution of the sparse linear equation
systems that arise during the DMO solution process. Usually, the default
values should be used with these advanced parameters.
You can use the parameters to drop small non-zeros from the matrix of first
derivatives (Jacobian). The linear solution will then require less storage but
will be inaccurate.
You can also control the pivoting strategy to compromise between
maintaining sparsity and controlling loss of accuracy through roundoff.

ANALYSISTHRES: Adv.LinAlg1: Fill-in monitoring factor


Type integer; Default 2; Range [1.00001,10]
Lets you specify a fill-in monitoring factor (default=2) to control the
automatic reanalysis of the Jacobian by monitoring fill-in. The automatic
reanalysis is invoked once the number of non-zeros has grown by a factor
equal to this parameter.

DROPTOL: Adv.LinAlg1: Drop tolerance


Type real; default 1.e-20; range [0,1e+35]
Lets you specify the non-zero drop tolerance used to remove small Jacobian
values (default=1.e-20). A larger tolerances reduces the number of non-zeros
and decreases factorization time. Too large a value reduces the accuracy of
the Jacobian.

PIVOTANAL: Adv.LinAlg1: Pivot Analysis frequency


Type: integer;
Range: 0 Medium
1 Low (default)

7 Solver Properties Dialog Box 249


2 High

Lets you select a re-analysis frequency, which determines the Jacobian pivot
reanalysis strategy.

PIVOTSEARCH: Adv.LinAlg1: Number of columns to search for


pivots
Type: integer; Default 10; range [1,2147483647]
Lets you specify the maximum number of columns used in a pivot search.

PIVOTTHRESH: Adv.LinAlg1: Stability threshold


Type: real; Default 0.1; range [0,1]
Lets you specify a pivot strategy threshold. Values near zero emphasize
sparsity and values near one emphasize stability.

PIVOTZERO: Adv.LinAlg1: Zero pivot threshold


Type: real; Default 0; range [0,1]
Lets you specify a pivot strategy zero threshold. This is the minimum pivot
element for near singular problems. If this parameter is set to a positive
value, any pivot whose modulus is less than this value is treated as zero.

USEDROPTOL: Adv.LinAlg1: Drop small Jacobian entries?


(0=no;1=yes)
Type: integer
Range: 0 no (default)
1 yes

Lets you specify whether to enable the dropping of small Jacobian non-zeros.

Linear Algebra options 2


Use these parameters for controlling the solution of the sparse linear algebra
equation systems that arise during the DMO solution process. Usually, the
default values should be used with these advanced parameters.
You can use these advanced parameters to try to improve the performance
and robustness of the numerical factorization phase of the linear solver used
in DMO.
You can enable and disable several reporting options related to linear algebra.

BTF: Adv.LinAlg2: Block lower triangularization? (0=no;1=yes)


Type integer;
Range: 0 Do not use block triangularisation
1 Use block triangularisation (default)

DENSITYRATIO: Adv.LinAlg2: Density ratio


Type real; default 0.7; range [0,1]
Lets you specify a density ratio. When the ratio of the number of non-zeros in
the reduced matrix to the number that it would have as a full matrix is

7 Solver Properties Dialog Box 250


greater than the specified density ratio, the solver switches from sparse to full
matrix processing.

FACTORSPEED: Adv.LinAlg2: Factorisation speed


(1=normal;2=fast)
Type integer
Range: 1 normal (default)
2 fast

Lets you select the linear matrix factorization method:


Normal – optimizes pivot at every iteration

FREEONLY: Adv.LinAlg2: Free variables only? (0=no;1=yes)


Type integer
Range: 0 no (default)
1 yes

Lets you specify whether to include free variables (i.e. those not fixed or a
constant) when solving the problem.

LUSTATS: Adv.LinAlg2: Report statistics (0=no;1=yes)


Type: integer
Range: 0 Off (default)
1 On

Lets you specify whether to enable diagnostic printing for linear algebra.

MINBTFSIZE: Adv.LinAlg2: Minimum block size


Type: integer; Default 1; Range [1,2147483647]
Lets you specify the minimum size of a block creating during block
triangularisation.

SINGULARHAND: Adv.LinAlg2: Singularity


handling(0=normal;1=active;2=structual;3=none)
Type: integer
Range: 0 normal (default)
1 active
2 structural
3 none

Lets you specify a strategy handling singular problems.

Workspace options
Use this sheet to increase the amount of memory workspace used by the
DMO solver. Usually, the default values should be used with these
parameters.

ACTIVESPACE: Adv.Workspace: Active set workspace factor


Type integer; Default 2; Range [2, 2147483647]

7 Solver Properties Dialog Box 251


Lets you specify the workspace allocated for part of the active set strategy.
The default should suffice for most cases.

CWORKF: Adv.Workspace: Character workspace factor


Type integer; Default 1; Range [1,10]
Lets you specify a character workspace size multiplier.

FACTORSPACE: Adv.Workspace: Linear algebra factorisation


workspace factor
Type integer; Default 6; Range [2,2147483647]
Lets you specify the workspace allocated for the solution of the linear system
of equations. Problems with excessive fill-in may require a higher number.

IWORKF: Adv.Workspace: Integer workspace factor


Type integer; Default 1; Range [1,10]
Lets you specify a integer workspace size multiplier.

RWORKF: Adv.Workspace: Real workspace factor


Type integer; Default 1; Range [1,10]
Lets you specify a real workspace size multiplier

Expert Solver Parameters


These options should not be changed. They are documented for completeness
only.

SAVEJDFFILE: Expert: 1=Creates a total derivative of Jacobian


Type: integer;
Range: 0 Do not create a total derivative
1 Create a total derivative

For internal debugging purposes only.

VMS_P1: Expert: VMS workspace offset (do not use)


Type: integer; Range [?];
Do not use this option.

7 Solver Properties Dialog Box 252


8 Using Calculation Options
for Properties Plus

To use Properties Plus you need to:


1 Use Aspen Plus® to specify the components, property methods, and any
additional information needed, for example your own physical properties
information and calculation options.
2 Decide whether to specify values for various calculation options. If you do
not specify values for the calculation options, default values are used. You
should make sure that the default settings are appropriate.
3 Generate a file, runid.appdf which will be used in the simulator
environment.

The calculation options can be used in the component list you create. The
calculation options that you can change within a component list are:
• OPSET
• FREE-WATER
• CHEMISTRY
• TRUE-COMP
• HENRY-COMPS
• SOLU-WATER
• KBASE
• MAXIT
• TOLERANCE
• RETENTION
For more detailed information on the possible values for each of these
options, see the Aspen Plus User Guide, Volume 1, Chapter 8.

About Properties Plus


Properties Plus® enables you to use the features of the Aspen Plus® 10
physical properties system. For more information on physical properties
methods, see the Aspen Plus User Guide, Volume 1, chapters 7 and 8; and
the Aspen Plus® reference volumes, Physical Property Methods and Models,
and Physical Property Data.
Properties Plus also provides all of the physical properties calculations
supported by the Aspen Custom Modeler® library. Other products have
libraries which reference modeler.acml to access Properties Plus where they

8 Using Calculation Options for Properties Plus 253


use the same core Aspen Custom Modeler simulation environment. Aspen
Dynamics™ is one of these products. For further information on the library
property procedures, see the Aspen Custom Modeler Library Reference.

OPSET Option
Use OPSET to specify the primary property method for calculating all
properties for the component list.

Valid Values
Valid values include any property method listed in the Properties Plus® input
file, using Aspen Plus®.

Default Value
The default value is the global property method specified in the Properties
Specifications Global sheet (in Aspen Plus).
If no property method is specified, IDEAL (Ideal property method) is used.

FREE-WATER Option
Use the FREE-WATER calculation option for petroleum processes only.
When you use the FREE-WATER approximation, you must specify the property
method to be used for the free water phase. This property method calculates
all thermodynamic and transport properties for the free-water phase.
For further information, see the Aspen Plus User Guide, Volume 1 for further
details.

Valid Values
Valid values include any property method listed in the Properties Plus® file.

Default Value
The default value is the Free-Water property method specified in the
Properties Specifications Global sheet (in Aspen Plus).
If no property method is specified, STEAM-TA, the ASME steam table
correlation, is used.

CHEMISTRY Option
Use the CHEMISTRY option for electrolyte systems only.
The CHEMISTRY option specifies which Chemistry ID (defined in Aspen Plus®)
is used for property calculations.
Electrolyte systems involve ionic components and reactions that must be
defined to complete the components specification. Therefore, you need to

8 Using Calculation Options for Properties Plus 254


select which ionic reactions set you want to use. CHEMISTRY is required when
you wish to model dissociation, equilibrium reaction, or salt precipitation in
the liquid phase. For more details see the Aspen Plus User Guide, Volume 1,
Chapter 6, and Volume 2, Chapter 27.

Valid Values
Valid values are any Chemistry ID specified in the Properties Plus® file, using
Aspen Plus®.

Default Value
The default value is <none>.

TRUE-COMP Option
Use the TRUE-COMP option for electrolyte systems only.
TRUE-COMP specifies whether property calculations for the component list are
to be performed in terms of true or apparent components.
If you choose apparent components (TRUE-COMP=No) the input to all
thermodynamic and transport property procedure calls should be in terms of
apparent components. The procedure will internally automatically calculate
the true composition where needed as part of it's property calculations.
If you choose true components (TRUE-COMP=Yes) the input to all
thermodynamic and transport property procedure calls must be in terms of
the true equilibrium composition. Your model must calculate this before
calling these property procedures. You can do this using the pTrueCmp2 or
pTrueCmpVLS procedures. pTrueCmp2 is suitable for liquid-solid systems, and
pTrueCmpVLS is suitable for vapor-liquid-solid systems.
If no Chemistry ID is specified, then the true and apparent approaches are
equivalent, so you do not need to specify a value for TRUE-COMP.
For a description of the differences between the apparent and true component
approaches, see Aspen Plus Physical Property Methods and Models, Chapter 5.

Valid Values
Valid values for TRUE-COMP are YES (true component approach) or NO
(apparent component approach).

Default Value
The default value is NO.

HENRY-COMPS Option
Use the HENRY-COMPS calculation option with property methods based on
activity coefficient models only.
In the activity coefficient approach for computing vapor-liquid equilibrium,
Henry's Law is used to represent the behavior of dissolved gases or other

8 Using Calculation Options for Properties Plus 255


supercritical components. HENRY-COMPS is used to specify the components
(if any) for which Henry's Law is to be used.
For information on how to specify the set of Henry Components in Aspen
Plus®, see the Aspen Plus User Guide, Volume 1, Chapter 6.

Valid Values
Valid values include any Henry's component list ID specified in the Properties
Plus® file.

Default Value
If a Henry's Law component list is referenced in the Properties Plus file for the
property method you have selected, this list will be used.
If no Henry's Law component list is referenced, the default is <none> and no
Henry's components are used.

SOLU-WATER Option
Use the SOLU-WATER option with petroleum processes only.
SOLU-WATER is used to specify the method for calculating the K-value of
water.
For properties procedures, the FREE-WATER calculation option is always used,
except for three-phase flash procedures with the FULL option.
For further information, see the Aspen Plus User Guide, Volume 1, Chapter 7.

Valid Values
Valid values for SOLU-WATER are:

Value Method Used


0 Water solubility correlation. Vapor phase fugacity for water
calculated by free water phase option set.
1 Water solubility correlation. Vapor phase fugacity for water is
calculated by primary option set.
2 Water solubility correlation with a correction for unsaturated
systems. Vapor phase fugacity for water is calculated by
primary option set.
3 Primary option set. Not recommended for water-hydrocarbon
systems unless water-hydrocarbon interaction parameters are
available.

Default Value
The default value is 3.

Important Note: Change the default value only if you want to


use free water approximations.

8 Using Calculation Options for Properties Plus 256


KBASE Option
KBASE is used to define the thermodynamic reference state to be used for
property calculations. For further information, see the Aspen Plus® reference
manual, User Models.

Valid Values
Valid values for KBASE are:

Value Option Used


0 Pure compounds in ideal gas state at 298.15K. If you model
reactions, you must explicitly include the heat of reaction term
in the energy balances.
1 Elements in their standard states at 298.15K. The heat of
reaction term is built into the enthalpy calculations.

Default Value
The default value is 1.

MAXIT Option
Use MAXIT to define the maximum number of iterations to be used for flash
calculations before a failure code is returned.
If a failure code is returned, the run will stop automatically. The default value
of 100 is nearly always adequate. However, if a run fails because the
maximum number of iterations has been reached, it is worth trying a larger
value.

Note: Flash calculations are used in determining mixed phase


properties such as mixed phase enthalpy, or mixed phase
entropy, as well as by the flash procedure itself.

Valid Values
Valid values for MAXIT are 30, 100, and 500.

Default Value
The default value is 100. This default is larger than the Aspen Plus® default.

TOLERANCE Option
Use TOLERANCE to define the tolerance within which flash calculations must
be converged.
The default value of 1E-6 is good for most applications. A smaller value gives
more precise values from flash calculations, and enables numerical

8 Using Calculation Options for Properties Plus 257


derivatives to be calculated more precisely. However, this can also slow down
the simulation.

Valid Values
Valid values for TOLERANCE are:
1E-3
1E-4
1E-5
1E-7
1E-6
1E-8
1E-9
1E-10
1E-11
1E-12

Default Value
The default value is 1E-6. This default is smaller than the Aspen Plus®
default.

RETENTION Option
Use RETENTION to retain intermediate results for flash calculations between
calls. Using RETENTION may substantially reduce the time taken for flash
calculations where many flash calculations are performed.

Valid Values
Valid values are ON and OFF.

Default Value
The default value is OFF.

8 Using Calculation Options for Properties Plus 258


9 Interfacing Your Own
Physical Properties

You can link in your own physical property package if it can be:
• Written in Fortran or C
• Organized to permit calls to subroutines that return physical properties as
they are required in models

Note for C Programmers: Make sure all calls obey Fortran


calling conventions

The following sections describe:


• How the interface communicates with Properties Plus.
• The two sets of routines that comprise the Generalized Physical Properties
Interface (GPPI):
− Generalized Physical Properties Interface routines.
− Entry point routines.
• Linking property procedure types to property routines.
• Fortran programmer's checklist.
• Installing the physical properties interface.
For information on property procedure types, see the Aspen Custom Modeler
Library Reference Chapter 2.

How the Interface


Communicates with Properties
Plus
The interface is implemented as two DLLs, described in this table:

This DLL Is Used To


gpp_setup.dll Correctly set up the environment that gpp.dll needs by
modifying the PATH environment variable so that it
includes the A+ xeq directory.

9 Interfacing Your Own Physical Properties 259


This means when gpp.dll is loaded, references to Aspen
Plus DLLs can be resolved. Doing it this way avoids the
need for the A+ directories to be added to the PATH at
installation time.
gpp.dll Implement these GPP_ functions:
o GPP_SETUP
o GPP_INI
o GPP_QUERY
o GPP_LOAD
o GPP_UNLOAD
o GPP_END
o GPP_OPTIONS

In addition to the GPP functions above, you also need to define a set of Aspen
Modeler procedures through which properties calculations can be called from
models. These functions are normally be implemented in a separate DLL.

Installing your Interface


To install your interface you must put gpp_setup.dll and gpp.dll in one of the
directories listed in the PATH environment variable, so that they get loaded in
preference to the two DLLs that were provided for the Properties Plus
interface.
The search path that Windows uses for loading a DLL is current working
directory first, then directories on the PATH, and finally the Windows system
directories.

Phase specific Variable Types


and Property Procedures
The argument lists for phase specific property procedures have been updated
to include non-phase specific variable types.
Where phase specific variable types are defined they now inherit from non
phase variable specific type.
For example:
• The output variable type for procedure pCond_liq has been changed from
cond_liq to conductivity and the variable type cond_liq now inherits from
variable type conductivity i.e.:
− Variable cond_liq uses conductivity.
This change means that a variable for a mixture property can be an output
from a phase specific property procedure, and you do not need to have
another intermediate variable of the correct type.
If you have definitions of phase specific variable types in your input file, which
are used in the argument list of property procedures, you may get errors on
loading the file of the form:
1000: CALL (K) = pCond_liq (T,P,Z);

9 Interfacing Your Own Physical Properties 260


Error at position 32: Procedure output argument 1 must be (or inherit)
variable type conductivity
To fix these errors you must modify the definitions of the phase specific
variables in your input file so that they inherit from the non-phase specific
type e.g.
Change:
Variable cond_liq
to
Variable cond_liq Uses conductivity

Generalized Physical Properties


Interface Routines
The Generalized Physical Properties Interface (GPPI) routines are used to:
• Initialize the physical properties system.
• Query the names of the components and the thermodynamic options
available.
• Load data from the physical properties system and initialize constants and
parameters that will apply to future physical property calls.
• Reset the physical properties system if the data changes.
• Provide access to the physical properties output level.
• Terminate the physical properties system.
This section describes each of the GPPI routines. For each routine, the
following information is provided:

Under this heading Find this information


Requirement Whether or not you must provide the routine
Purpose Purpose of the routine
Definition The first few lines of the routine. This defines the
argument list, and the meaning of the variables.

Important
Note the following points when you are writing GPPI routines:
• All code linked in via shared or dynamically linked libraries (DLLs) must be
thread safe.
• If your routine can fail under certain circumstances, use the parameter
IFAIL to return the failure status. Always assign IFAIL a value of 1 if the
call is successful or 4 if the call is unsuccessful. The following error flags
are defined:
1 Normal. Continue execution.
2 Warning. Continue execution.
3 Error. Continue execution.

9 Interfacing Your Own Physical Properties 261


4 Fatal error. Stop execution immediately and return to executive.
• Use the routine ACM_PRINT for printing diagnostic output.

GPP_SETUP
Requirement
Optional

Purpose
This routine is loaded from an optional DLL called GPP_SETUP, which is loaded
before the main GPP_DLL, so it can set up the runtime environment for
GPP.DLL.

Definition
The argument list of GPP_SETUP is:
SUBROUTINE GPP_SETUP (IFAIL)

Name Type Description


IFAIL I Failure flag

GPP_INI
GPP_INI passes the name and path of the simulation physical properties
definition file. Even if there is no such file provided by your interface, you
should include dummy arguments for PATH & FILEID in the argument list.

Requirement
Compulsory.

Purpose
The routine is called with the user defined path and full filename of the
simulation physical properties definition file. Use this routine to initialize your
interface as required.

Definition
The argument list of GPP_INI is:
SUBROUTINE GPP_INI (PATH, FILEID, IFAIL)

Name Type Description


PATH C*(*) Location of the physical properties
definition file
FILEID C*(*) Name of the physical properties
definition file in the form:
<filename>.<filetype>, e.g.
gasplant.appdf

9 Interfacing Your Own Physical Properties 262


IFAIL I Failure flag

GPP_QUERY
GPP_QUERY reads component and options data from the .appdf file.
If your interface does not have an equivalent of the .appdf file, GPP_QUERY
returns the list of components and options that your package supports.
This data is then displayed in the GUI dialog boxes where component lists are
defined. If the properties being used in a simulation are defined in a Modeling
Language file, then the data returned from GPP_QUERY is used to validate the
description given in the Properties definition. In fact, when a file containing a
Properties definition is loaded, Editing Properties appears in the status bar,
then gpp.dll is loaded, and gpp_ini and then gpp_query are called.

Requirement
Compulsory

Purpose
Used to query the physical properties system for a complete list of component
names and valid keywords or thermodynamic options such as PENG and
IDEAL.

Definition
The argument list of GPP_QUERY is:
SUBROUTINE GPP_QUERY (IACTION, NUM, KEYW, VAL1, VAL2,
IFAIL)
The data to be returned depends on the value of IACTION as follows:

IACTION Subroutine GPP_QUERY Response


1 Called once. Returns total number of components known to the
property package in the second argument NUM and the string
values COMPONENT NAME and FORMULA in the arguments KEYW
and VAL1 respectively.
2 Called once for each known component. Returns the name of the
NUMth component in the argument KEYW, and its formula in the
argument VAL1.
3 Called once. Returns the total number of valid property options and
their values known to the property package in the second argument
NUM.
4 Called once for each valid property option. Returns the name of the
NUMth property option in the argument KEYW, and its value in the
argument VAL1. Note, if a property option has more than one value,
then GPP_QUERY should return the same name in KEYW for each
value. If KEYW is a vector then VAL2 has the word "VECTOR" —that
is it accepts a list of options at once. If VAL2 is not set, it is
assumed to be scalar.

9 Interfacing Your Own Physical Properties 263


GPP_LOAD
GPP_LOAD describes the component list to the package and is called when
you exit the Build Component List dialog box. Aspen Modeler products
associate a number with each component list used in a simulation. When a
procedure call equation which has the PROPERTIES option associated with it is
called, this number is passed in to the call as the extra ICLST argument. From
this number, the package knows which components and options were chosen
for the component list associated with the procedure call.

Requirement
Compulsory

Purpose
Used to:
• Perform any loading of pure component and interaction data that is
required.
• Establish which calculation options have been specified for each
component list.
• Process data supplied through the Graphical User Interface (GUI) client
into a suitable form for efficient use by the physical properties package.
This also includes assigning and copying files for use by the physical
properties package.

Definition
The argument list of GPP_LOAD is:
SUBROUTINE GPP_LOAD (NOCLIS, NCOMP, COMPNA, NOVAL, OPTKWD,
OPTVAL, MAXCSU, MAXVAL, IFAIL)

Name Type Dimensions Description


NOCLIS I – Total number of components lists
NCOMP I NOCLIS Number of components in each component list
COMPNA C*(*) MAXCSU, Names of components in each component list
NOCLIS
NOVAL I NOCLIS Number of option values in each component list
OPTKWD C*(*) MAXVAL, OPTion KeyWorD for the options in each
NOCLIS component list

OPTVAL C*(*) MAXVAL, OPTion VALues for the options in each component
NOCLIS list

MAXCSU I – Maximum number of components for any


component list
MAXVAL I – Maximum number of option values for any
component list
IFAIL I – Failure flag

9 Interfacing Your Own Physical Properties 264


GPP_UNLOAD
GPP_UNLOAD is called when the data passed to GPP_LOAD is not required
anymore. Use GPP_UNLOAD to clean up anything done in GPP_LOAD.

Requirement
Compulsory

Purpose
When a run terminates or the component lists are redefined, this routine is
called to reset the package so that it is ready to accept a new set of
component lists. This routine is also used for unassigning and deleting files.

Definition
The argument list of GPP_UNLOAD is:
SUBROUTINE GPP_UNLOAD (IFAIL)

Name Type Description


IFAIL I Failure flag

GPP_END
GPP_END is called when simulator shuts down; it implements anything
necessary to clean up what was done in GPP_INI.

Requirement
Compulsory

Purpose
Called when the simulator shuts down or a different physical properties
package is selected.

Definition
The argument list of GPP_END is:
SUBROUTINE GPP_END (IFAIL)

Name Type Description


IFAIL I Failure flag

GPP_OPTIONS
Requirement
Compulsory

9 Interfacing Your Own Physical Properties 265


Purpose
Provides access to the diagnostic print level for the physical properties
interface and/or package.

Definition
The argument list of GPP_OPTIONS is:
SUBROUTINE GPP_OPTIONS (PROP_LEVEL, IFAIL)

Name Type Description


PROP_LEVEL I The property output level
IFAIL I Failure flag

Entry Point Routines


The entry point routines are a set of routines that intercept internal procedure
calls and call the necessary routines within the physical property package with
an appropriate argument list.

ACM Library Procedure Declaration


Each entry point routine is defined by an internal procedure declaration in the
ACM Library.
For information about Procedure Declaration, see Modeling Language
Reference, Chapter 3-9.

Procedures with Analytic Derivatives


For procedures that return analytic derivatives, a typical procedure
declaration is:
PROCEDURE <procedure_name>
CALL : <subroutine_name>;
LIBRARY : "<dllname>”;
IMPLEMENTATION : SUBROUTINE;
LANGUAGE : FORTRAN;
OPTIONS : PROPERTIES, DERIVATIVES;
INPUTS : <input_var_type> [,<input_var1_type>];
OUTPUTS : <output_var_type> [,<output_var1_type>];
END;

Note: The appearance of the keyword DERIVATIVES under


the OPTIONS statement.
<procedure_name> Name of the declared procedure

9 Interfacing Your Own Physical Properties 266


<subroutine_name> Name of the fortran subroutine
<dllname> Name of the Dynamics Link Library
<input_var_type> List of input variable types. For array
[,<input_var1_type>] variables with a single dimension, a
wildcard size, given by (*), is used.
<output_var> List of output variable types. For array
[,<output_var1_type>] variables with a single dimension, a
wildcard size, given by (*), is used.

The corresponding fortran entry point subroutine headings are in the form:
SUBROUTINE <subroutine_name> (<input_var1> [, <input_var],
<output_var> [, <output_var1>, IFLAG, ICLST, DERIV, NDOUT,
NDIN, ICALL)

<subroutine_name> Name of the fortran subroutine


<input_var> [,<input_var1>] List of real input variables. For array variables with
a single dimension, the dimension of the array is
inserted automatically as an integer value
immediately after the variable. Values of input
variables should never be changed by entry point
routines.
<output_var> List of real output variables. For array variables
[,<output_var1>] with a single dimension, the dimension of the array
is inserted automatically as an integer value
immediately after the variable.
IFLAG An integer flag, initially set to 1. You can use this
parameter to return error codes from your routine.
See Status Codes Returned from Procedures.
The following error flags are defined:
1 Normal. Continue execution
2 Warning. Continue execution
3 Error. Continue execution
4 Fatal error. Stop execution immediately and
return to executive.

Note: Thus if an iterative routine fails to converge, it can set


IFLAG to 3 if the result is close to tolerance. If the error is too
large, it can set IFLAG to 4. In the first case, execution
continues, but a warning message is issued. In the second case,
execution is terminated immediately on return from the routine.
You should use the error return code wherever appropriate.
ICLST An integer value representing the component list
for which the physical property calculation is
requested.
DERIV A 2-D real array of size (NDOUT, NDIN) containing
analytic derivatives of the output variables WRT the
input variables.
NDOUT Number of output variables
NDIN Number of input variables
ICALL An integer flag from the calling code which declares
the type of the procedure call. See ICALL codes
passed to Procedures.
The following calling status are relevant:
0 Requires Property calculation only

9 Interfacing Your Own Physical Properties 267


3 Requires Derivatives only
4 Requires both Property calculation and
Derivatives

Note: Your subroutine coding must respond correctly to the


above 3 different instances of ICALL from ACM Executive. For
example, when ICALL=0, that is, when Derivatives are not
required, NDOUT and NDIN are zeros and DERIV is of zero size.

To use with Aspen Modeler products, you need to generate a (standard)


fortran wrapper routine for the Procedure.

Status Codes Returned from Procedures


All procedures must return a status code, normally an argument called IFLAG.
The calling code will initialize this to 1
The following values for the status code are defined:
1 Normal. Continue execution
2 Warning. Issue message and continue execution
3 Severe Error. Issue message and continue execution
4 Fatal error. Issue dialog and stop execution.

Note: You should return a FATAL error if there is no possibility of


recovery from the error: for example, if a necessary data file
cannot be found, or if data is unitilialized. If the error is caused
by values going out of range, you should return a SEVERE error,
which will allow the solver to perturb the solution point and try
again.

If you generate a template for your procedure code, suitable symbolic values
are defined for you to use in your code.

ICALL codes passed to Procedures


Procedures are normally passed a flag, usually called ICALL, to indicate the
kind of call that is being made to the procedure. If the procedure does not
need PRECALL, POSTCALL, or DERIVATIVES, then ICALL is not passed to the
procedure, as it will always be zero.
The following codes may occur:
0 Requires calculation of outputs only
1 PRECALL – use to open files, initialize workspace, COMMON data.
2 POSTCALL – use to close files.
3 Requires calculation of derivative values only.
4 Requires both calculation outputs and derivatives.

9 Interfacing Your Own Physical Properties 268


Note: Your subroutine coding must respond correctly to the
above different values of ICALL from ACM Executive. For
example, when ICALL=0, that is, when Derivatives are not
required, NDOUT and NDIN are zeros and DERIV is of zero size,
and may not have been allocated by the calling code (hence an
attempt to read from it or write to it would result in an access
violation).

Example of Procedure Declaration with


Analytic Derivatives
The following example shows a typical Procedure Declaration for a Fortran
entry point routine that returns Analytic Derivatives:

PROCEDURE pEnth_Mol_Liq
// Specific Liquid Molar Enthalpy with Analytic Derivatives
CALL : gpidlhx;
LIBRARY : "gpp.dll";
IMPLEMENTATION : SUBROUTINE;
LANGUAGE : FORTRAN;
OPTIONS : PROPERTIES, DERIVATIVES;
INPUTS : Temperature, Pressure, Molefraction(*);
OUTPUTS : enth_mol;
END;

Example of Entry Point Routine that


returns Analytic Derivatives
The following fortran subroutine reflects the above declared Procedure
pEnth_Mol_Liq defining the entry point routine GPIDLHX:

SUBROUTINE GPIDLHX ( T, P, X, NX, IFAIL, ICLST,


& DERIV, DOUT, DIN, ICALL )
C Return Stream Specific Molar Enthalpy
IMPLICIT DOUBLE PRECISION (A-H, O-Z)
COMMON /LOADED/ ILOAD
DIMENSION X(NX)
C
C Array for the returning composition derivatives
DIMENSION dHHdX(NX)

9 Interfacing Your Own Physical Properties 269


C Parameterize the required UOM conversion factors
PARAMETER ( UCFProp = 1.0D-3, UCFTemp = 273.15,
& UCFPres = 1.0D-4, UCFComp = 1.0D-3 )
C
C Check whether correct Component List data loaded
IF (ICLST.NE.ILOAD) CALL LOAD(ICLST)
C Convert T from Celsius to Kelvin
TK = T + 273.15D0
C
C CALL Physical Property Package Routine
CALL PPPACK ( TK, P, X, .. <argument list>..., HH,
& dHHdT, dHHdP, dHHdX, ISTATUS )
C
C Check the status of the call to Subroutine PPPACK
IF (ISTATUS.LE.0) THEN
IFAIL = 4
GOTO 999
ENDIF
C Respond to the incoming ICALL flag
IF (ICALL.EQ.0 .OR. ICALL.EQ.4) THEN
C Both cases require the return of the Property
H = HH * UCFProp
ENDIF
IF (ICALL.EQ.3 .OR. ICALL.EQ.4) THEN
C Both cases require the return of all property
derivatives
C Get Temperature derivative with UOM conversion
DERIV(1,1) = dHHdT * UCFT%emp
C Get Pressure derivative with UOM conversion
DERIV(1,2) = dHHdP * UCFPress
C Get Compositon derivatives with UOM conversion
DO I = 1, NX
DERIV(1,I) = dHHdX(I) * UCFComp
ENDDO
ENDIF

9 Interfacing Your Own Physical Properties 270


999 CONTINUE
RETURN
END

Procedures without Analytic Derivatives


For procedures that do not return analytic derivatives, a typical procedure
declaration is:
PROCEDURE <procedure_name>
CALL : <subroutine_name>;
LIBRARY : "<dllname>”;
IMPLEMENTATION : SUBROUTINE;
LANGUAGE : FORTRAN;
OPTIONS : PROPERTIES;
INPUTS : <input_var_type> [,<input_var1_type>];
OUTPUTS : <output_var_type> [,<output_var1_type>];
END;

Note: the absence of the keyword DERIVATIVES under the


OPTIONS statement.

<procedure_name> Name of the declared procedure


<subroutine_name> Name of the fortran subroutine
<dllname> Name of the Dynamics Link Library
<input_var_type> List of input variable types. For array variables with a
[,<input_var1_type>] single dimension, a wildcard size, given by (*), is used.

<output_var> List of output variable types. For array variables with a


[,<output_var1_type>] single dimension, a wildcard size, given by (*), is used.

The corresponding fortran entry point subroutine headings are in the form:
SUBROUTINE <subroutine_name> (<input_var1> [, <input_var],
<output_var> [, <output_var1>, IFLAG, ICLST)

<subroutine_name> Name of the fortran subroutine


<input_var> List of real input variables. For array variables
[,<input_var1>] with a single dimension, the dimension of the
array is inserted automatically as an integer
value immediately after the variable. Values of
input variables should never be changed by
entry point routines.
<output_var> List of real output variables. For array variables
[,<output_var1>] with a single dimension, the dimension of the
array is inserted automatically as an integer
value immediately after the variable.
IFLAG An integer flag, initially set to 1. You can use
this parameter to return error conditions from

9 Interfacing Your Own Physical Properties 271


your routine.
The following error flags are defined:
1 Normal. Continue execution
2 Warning. Continue execution
3 Error. Continue execution
4 Fatal error. Stop execution immediately
and return to executive.

Note: Thus if an iterative routine fails to converge, it can set


IFLAG to 3 if the result is close to tolerance. If the error is too
large, it can set IFLAG to 4. In the first case, execution
continues, but a warning message is issued. In the second case,
execution is terminated immediately on return from the routine.
You should use the error return code wherever appropriate.

To use with Aspen Modeler products, you need to generate a standard fortran
wrapper routines for a C calling program from ACM Executive.

Example of Procedure Declaration


without Analytic Derivatives
The following example shows a typical Procedure Declaration for a Fortran
entry point routine that does not return Analytic Derivatives:

PROCEDURE pEnth_Mol_Liq
// Specific Liquid Molar Enthalpy
CALL : gpilhx;
LIBRARY : "gpp.dll";
IMPLEMENTATION : SUBROUTINE;
LANGUAGE : FORTRAN;
OPTIONS : PROPERTIES;
INPUTS : Temperature, Pressure, Molefraction(*);
OUTPUTS : enth_mol;
END;

Example of Entry Point Routine that


Does Not Return Analytic Derivatives
The following fortran subroutine reflects the above declared entry point
Procedure pEnth_Mol_Liq defining the entry point routine GPILHX:

SUBROUTINE GPILHX ( T, P, X, NX, IFAIL, ICLST )


C Return Stream Specific Molar Enthalpy

9 Interfacing Your Own Physical Properties 272


IMPLICIT DOUBLE PRECISION (A-H, O-Z)
COMMON /LOADED/ ILOAD
DIMENSION X(NX)
C
C Parameterize the property UOM Conversion Factor
PARAMETER ( UCFProp = 1.0D-3)
C
C Check whether correct Component List data loaded
IF (ICLST.NE.ILOAD) CALL LOAD(ICLST)
C
C Convert T from Celsius to Kelvin
TK = T + 273.15D0
C
C CALL Physical Property Package Routine
CALL PPPACK ( TK, P, X, .. <argument list>...,
& HH, ISTATUS )
C
C Check the status of the call to Subroutine PPPACK
IF (ISTATUS.LE.0) THEN
IFAIL = 4
GOTO 999
ENDIF
C
C UOM conversion
H = HH * UCFProp
C
CONTINUE
C
RETURN
END

9 Interfacing Your Own Physical Properties 273


Linking Property Procedure
Types to Subroutines
When implementing a physical property interface, you can link to any
property routines you choose. However, you must link to all physical
properties that are used by your models. If you are using the Aspen
Technology property procedure types, you are advised to link to all the
procedures in the Library.

Property Procedures with Analytic


Derivatives
The following table is a list of all the physical property procedures that returns
analytic derivatives used by the Library, and their subroutines. Subroutine
names of this category begin with GPID, as shown in the table. For detailed
information on linking each routine, see Generalized Physical Properties
Interface Routine.

Procedure Subroutine Description


Name Name
pCond_Liq GPIDLKX Liquid thermal conductivity
pCond_Vap GPIDVKX Vapor thermal conductivity
pCp_Mol_Liq GPIDLCP Liquid molar heat capacity at constant pressure
pCp_Mol_Vap GPIDVCP Vapor molar heat capacity at constant pressure
pCv_Mol_Liq GPIDLCV Liquid molar heat capacity at constant volume
pCv_Mol_Vap GPIDVCV Vapor molar heat capacity at constant volume
pDens_Mass_Liq GPIDLDX Liquid mass density
pDens_Mass_Vap GPIDVDX Vapor mass density
pDens_Mol_Liq GPIDLMX Liquid molar density
pDens_Mol_Vap GPIDVMX Vapor molar density
pDiffus_Liq GPIDLDC Liquid diffusion coefficients of components in a mixture
pDiffus_Vap GPIDVDC Vapor diffusion coefficients of components in a mixture
pEnth_Mol_Liq GPIDLHX Liquid molar enthalpy
pEnth_Mol_Vap GPIDVHX Vapor molar enthalpy
pEntr_Mol_Liq GPIDLSX Liquid molar enthalpy
pEntr_Mol_Vap GPIDVSX Vapor molar enthalpy
pFuga_Liq GPIDLFU Component liquid fugacity coefficients
pFuga_Vap GPIDVFU Component vapor fugacity coefficients
pGibbs_Mol_Liq GPIDLGX Liquid molar Gibbs free energy
pGibbs_Mol_Vap GPIDVGX Vapor molar Gibbs free energy
pKllValues GPIDKLL Component liquid/liquid equilibrium K values
pKValues GPID0KX Vapor liquid equilibrium K values
pSurf_Tens GPIDLTX Liquid surface tension
pVisc_Liq GPIDLVX Liquid viscosity
pVisc_Vap GPIDVVX Vapor viscosity

9 Interfacing Your Own Physical Properties 274


Property Procedures Without Analytic
Derivatives
The following table is a list of all the physical property procedures that do not
return analytic derivatives used by the Library, and their subroutines.
Subroutine names of this category begin with GPI, as shown in the table. For
detailed information on linking each routine, see Generalized Physical
Properties Interface Routine.

Procedure Subroutine Description


Name Name
pAct_Coeff_Liq GPILAX Liquid activity coefficients
pBubt GPIBTX Bubble point temperature at fixed pressure
pDens_Mass_Sol GPISDX Solid mass density
pDens_Mol_Sol GPISMX Solid molar density
pDewt GPIDTX Dew point temperature at fixed pressure
pEnth_Mol GPI2EX Mixed phase molar enthalpy
pEnth_Mol_Sol GPISEX Solid molar enthalpy
pEntr_Mol GPI2SX Mixed phase molar enthalpy
pEntr_Mol_Sol GPISSX Solid molar enthalpy
pFlash GPI2FE Two-phase flash at given temperature and pressure
pFlash3 GPI3FH Three-phase flash at given temperature and pressure
pFlash3PH GPI3PH Three-phase flash at given pressure and enthalpy
pFlash3PV GPI3PV Three-phase flash at given pressure and vapor fraction
pFlash3TH GPI3TH Three-phase flash at given temperature and enthalpy
pFlash3TV GPI3TV Three-phase flash at given temperature and vapor
fraction
pFlashPH GPI2PH Two-phase flash at given pressure and molar enthalpy
pFlashPV GPI2PV Two-phase flash at given pressure and vapor fraction
pFlashTH GPI2TH Two-phase flash at given temperature and molar
enthalpy
pFlashTV GPI2TV Two-phase flash at given temperature and vapor fraction
pFuga_Sol GPISFU Component solid fugacity coefficients
pGibbs_Mol_IDLG GPIZGX_IDL Component Ideal Gas Molar Gibbs Free Energies
AS GAS
pGibbs_Mol_Sol GPISGX Solid molar Gibbs free energy
pMolWeight GPI0WX Mean molar weight
pMolWeights GPIZW0 Component molar weights
pSurfTensY GPILTXY Vapor and liquid surface tension
pTrueCmp2 GPITR2 Liquid & Solid species comp. of an electrolyte mixture
pTrueCmpVLS GPITRVLS V, L & S species composition of an electrolyte mixture
pTrueComp GPITRU True species composition of an electrolyte mixture
pVap_Pressures GPIZP0 Component vapor pressure

9 Interfacing Your Own Physical Properties 275


Definition of GPPI Entry Points
This section lists all of the physical property procedures used by the Library,
except those for calculating properties of polymer solutions. (Polymer
procedures are specific to Properties Plus® and are therefore not relevant if
you are interfacing your own property package.)
For each procedure, the following information is provided:

Under this heading Find this information


Purpose Purpose of the procedure
Subroutine Name of the corresponding subroutine
Definition Subroutine definition for the routine. This
defines the argument list, and the types and
meaning of the variables. The letter I or O
after a variable name denotes whether it is an
input or output to the subroutine.

pAct_Coeff_Liq
Purpose
Liquid phase activity coefficient

Subroutine
GPILAX

Definition
The argument list for GPILAX is:
SUBROUTINE GPILAX (T, P, X, NX, ACTL, NACTL, IFLAG, ICLST)
INTEGER NX, IFLAG, ICLST, NACTL,
DOUBLE PRECISION T, P, X(NX), ACTL(NACTL)

Name Type Description


T I Temperature (C )
P I Pressure (bar)
X I Component mole fractions
NX I Number of components
ACTL O Liquid phase activity coefficient
NACTL I Number of components
IFLAG M Error flag
ICLST I Integer value for component list

9 Interfacing Your Own Physical Properties 276


pBubt
Purpose
Bubble temperature at given pressure

Subroutine
GPIBTX

Definition
The argument list for GPIBTX is:
SUBROUTINE GPIBTX ( P, ZF, NZ, TBUB, IFLAG, ICLST )
INTEGER NZ, IFLAG, ICLST
DOUBLE PRECISION P, ZF(NZ), TBUB

Name Type Description


P I Pressure (bar)
ZF I Component mole fractions
NZ I Number of components
TBUB O Bubble temperature (C)
IFLAG M Error flag
ICLST I Integer value for component list

pCond_Liq
Purpose
Liquid phase thermal conductivity with analytic derivatives

Subroutine
GPIDLKX

Definition
The argument list for GPIDLKX is:
SUBROUTINE GPIDLKX ( T, P, X, NX, CONDL, IFLAG, ICLST,
DERIV, NOUT, NIN, ICALL )
INTEGER NX, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, X(NX), CONDL, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Component mole fractions
NX I Number of components
CONDL O Liquid phase thermal conductivity
(W/m/K)

9 Interfacing Your Own Physical Properties 277


IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pCond_Vap
Purpose
Vapor phase thermal conductivity with analytic derivatives

Subroutine
GPIDVKX

Definition
The argument list for GPIDVKX is:
SUBROUTINE GPIDVKX ( T, P, Y, NY, CONDV, IFLAG, ICLST,
DERIV, NOUT, NIN, ICALL )
INTEGER NY, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, Y(NY), CONDV, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
Y I Component mole fractions
NY I Number of components
CONDV O Vapor phase thermal conductivity
(W/m/K)
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pCp_Mol_Liq
Purpose
Liquid specific heat capacity at constant pressure with analytic derivatives

Subroutine
GPIDLCP

9 Interfacing Your Own Physical Properties 278


Definition
The argument list for GPIDLCP is:
SUBROUTINE GPIDLCP ( T, P, X, NX, CPL, IFLAG, ICLST, DERIV,
NOUT, NIN, ICALL )
INTEGER NX, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, X(NX), CPL, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Component mole
fractions
NX I Number of
components
CPL O Liquid phase spec.
heat capacity at
constant pressure
(kJ/kmol/K)
IFLAG M Error flag
ICLST I Integer value for
component list
DERIV O Analytic derivatives
NOUT I Number of output
variables
NIN I Number of input
variables
ICALL I Calling status

pCp_Mol_Vap
Purpose
Vapor phase specific heat capacity at constant pressure with analytic
derivatives

Subroutine
GPIDVCP

Definition
The argument list for GPIDVCP is:
SUBROUTINE GPIDVCP ( T, P, Y, NY, CPV, IFLAG, ICLST, DERIV,
NOUT, NIN, ICALL )
INTEGER NY, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, Y(NY), CPV, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)

9 Interfacing Your Own Physical Properties 279


P I Pressure (bar)
Y I Component mole fractions
NY I Number of components
CPV O Vapor phase spec. heat capacity at constant
pressure (kJ/kmol/K)
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pCv_Mol_Liq
Purpose
Liquid specific heat capacity at constant volume with analytic derivatives

Subroutine
GPIDLCV

Definition
The argument list for GPIDLCV is:
SUBROUTINE GPIDLCV ( T, P, X, NX, CVL, IFLAG, ICLST, DERIV,
NOUT, NIN, ICALL )
INTEGER NX, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, X(NX), CVL, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Component mole fractions
NX I Number of components
CVL O Liquid phase spec. heat capacity at constant
volume (kJ/kmol/K)
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

9 Interfacing Your Own Physical Properties 280


pCv_Mol_Vap
Purpose
Vapor phase specific heat capacity at constant volume with analytic
derivatives.

Subroutine
GPIDVCV

Definition
The argument list for GPIDVCV is:
SUBROUTINE GPIDVCV ( T, P, Y, NY, CVV, IFLAG, ICLST, DERIV,
NOUT, NIN, ICALL )
INTEGER NY, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, Y(NY), CVV, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
Y I Component mole fractions
NY I Number of components
CVV O Vapor phase spec. heat capacity at
constant volume (kJ/kmol/K)
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pDens_Mass_Liq
Purpose
Stream liquid density with analytic derivatives

Subroutine
GPIDLDX

Definition
The argument list for GPIDLDX is:
SUBROUTINE GPIDLDX (T, P, X, NC, D, IFLAG, ICLST, DERIV,
NOUT, NIN, ICALL)
INTEGER NC, IFLAG, ICLST, ICALL
DOUBLE PRECISION P, X(NC), T, D, DERIV(NOUT,NIN)

9 Interfacing Your Own Physical Properties 281


Name Type Description
T I Temperature (C)
P I Pressure (bar)
X I Vector of component mole fractions of size
NC
NC I Number of components
D O Liquid density (kg/m3)
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pDens_Mass_Sol
Purpose
Solid mass density

Subroutine
GPISDX

Definition
The argument list for GPISDX is:
SUBROUTINE GPISDX (T, P, X, NX, DS, IFLAG, ICLST)
INTEGER NX, IFLAG, ICLST
DOUBLE PRECISION T, P, X(NX), DS

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Component mole fractions
NX I Number of components
DS O Solid mass density (kg/m3)
IFLAG M Error flag
ICLST I Integer value for component list

pDens_Mass_Vap
Purpose
Stream vapor mass density with analytic derivatives.

9 Interfacing Your Own Physical Properties 282


Subroutine
GPIDVDX

Definition
The argument list for GPIDVDX is:
SUBROUTINE GPIDVDX (T, P, X, NC, DV, IFLAG, ICLST, DERIV,
NOUT, NIN, ICALL)
INTEGER NC, IFLAG, ICLST, ICALL
DOUBLE PRECISION P, T, X(NX), DV, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Vector of component mole fractions of size NC
NC I Number of components
DV O Vapor density (kg/m3)
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pDens_Mol_Liq
Purpose
Liquid molar density with analytic derivatives

Subroutine
GPIDLMX

Definition
The argument list for GPIDLMX is:
SUBROUTINE GPIDLMX ( T, P, X, NX, RHOL, IFLAG, ICLST,
DERIV, NOUT, NIN, ICALL )
INTEGER NX, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, X(NX), RHOL DERIV(NOUT,NIN)

Name Type Description

T I Temperature (C)

P I Pressure (bar)

X I Component mole fractions

9 Interfacing Your Own Physical Properties 283


NX I Number of components

RHOL O Liquid density (kmol/m3)

IFLAG M Error flag

ICLST I Integer value for component list

DERIV O Analytic derivatives

NOUT I Number of output variables

NIN I Number of input variables

ICALL I Calling status

pDens_Mol_Sol
Purpose
Solid molar density

Subroutine
GPISMX

Definition
The argument list for GPISMX is:
SUBROUTINE GPISMX (T, P, X, NX, RHOS, IFLAG, ICLST)
INTEGER NX, IFLAG, ICLST
DOUBLE PRECISION T, P, X(NX), RHOS

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Component mole fractions
NX I Number of components
RHOS O Solid molar density (kmol/m3)

pDens_Mol_Vap
IFLAG M Error flag
ICLST I Integer value for component list

Purpose
Vapor molar density with analytic derivatives

Subroutine
GPIDVMX

9 Interfacing Your Own Physical Properties 284


Definition
The argument list for GPIDVMX is:
SUBROUTINE GPIDVMX ( T, P, YF, NY, RHOV, IFLAG, ICLST,
DERIV, NOUT, NIN, ICALL )
INTEGER NY, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, YF(NY), RHOV, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
YF I Component mole fractions
NY I Number of components
RHOV O Vapor density (kmol/m3)
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pDewt
Purpose
Dew temperature at given pressure

Subroutine
GPIDTX

Definition
The argument list for GPIDTX is:
SUBROUTINE GPIDTX ( P, Z, NZ, TDEW, IFLAG, ICLST )
INTEGER NZ, IFLAG, ICLST
DOUBLE PRECISION P, ZF(NZ), TDEW

Name Type Description


P I Pressure (bar)
Z I Component mole fractions
NZ I Number of components
TDEW O Dew temperature (C)
IFLAG M Error flag
ICLST I Integer value for component list

9 Interfacing Your Own Physical Properties 285


pDiffus_Liq
Purpose
Liquid diffusion coefficients with analytic derivatives

Subroutine
GPIDLDC

Definition
The argument list for GPIDLDC is:
SUBROUTINE GPIDLDC ( T, P, X, NX, DCL, NDCL, IFLAG, ICLST,
DERIV, NOUT, NIN, ICALL )
INTEGER NX, NDCL, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, X(NX), DCL(NDCL), DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Component mole fractions
NX I Number of components
DCL O Diffusion coefficients (cm2/s)
NDCL I Number of components
IFLAG M Error flag
ICLST Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pDiffus_Vap
Purpose
Vapor diffusion coefficients with analytic derivatives

Subroutine
GPIDVDC

Definition
The argument list for GPIDVDC is:
SUBROUTINE GPIDVDC ( T, P, Y, NY, DCV, NDCV, IFLAG, ICLST,
DERIV, NOUT, NIN, ICALL )
INTEGER NY, NDCV, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, Y(NY), DCV(NDCV), DERIV(NOUT,NIN)

9 Interfacing Your Own Physical Properties 286


Name Type Description
T I Temperature (C)
P I Pressure (bar)
Y I Component mole fractions
NY I Number of components
DCV O Diffusion coefficients (cm2/s)
NDCV I Number of components
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables

pEnth_Mol
ICALL I Calling status

Purpose
Mixed phase specific enthalpy

Subroutine
GPI2EX

Definition
The argument list for GPI2EX is:
SUBROUTINE GPI2EX ( T, P, Z, NZ, ENTHM, IFLAG, ICLST )
INTEGER NZ, IFLAG, ICLST
DOUBLE PRECISION T, P, Z(NZ), ENTHM

Name Type Description


T I Temperature (C)
P I Pressure (bar)
Z I Component mole fractions
NZ I Number of components
ENTHM O Mixed phase specific enthalpy (GJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list

pEnth_Mol_Liq
Purpose
Liquid specific enthalpy with analytic derivatives

9 Interfacing Your Own Physical Properties 287


Subroutine
GPIDLHX

Definition
The argument list for GPIDLHX is:
SUBROUTINE GPIDLHX ( T, P, X, NX, SPHL, IFLAG, ICLST,
DERIV, NOUT, NIN, ICALL )
INTEGER NX, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, X(NX), SPHL, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Component mole fractions
NX I Number of components
SPHL O Liquid specific enthalpy (GJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pEnth_Mol_Sol
Purpose
Solid molar enthalpy

Subroutine
GPISEX

Definition
The argument list for GPISEX is:
SUBROUTINE GPISEX (T, P, X, NX, SPHS, IFLAG, ICLST)
INTEGER NX, IFLAG, ICLST
DOUBLE PRECISION T, P, X(NX), SPHS

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Component mole fractions
NX I Number of components
SPHS O Solid specific enthalpy (GJ/kmol)

9 Interfacing Your Own Physical Properties 288


IFLAG M Error flag
ICLST I Integer value for component list

pEnth_Mol_Vap
Purpose
Vapor specific enthalpy with analytic derivatives

Subroutine
GPIDVHX

Definition
The argument list for GPIDVHX is:
SUBROUTINE GPIDVHX ( T, P, Y, NY, SPHV, IFLAG, ICLST,
DERIV, NOUT, NIN, ICALL )
INTEGER NY, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, Y(NY), SPHV, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
Y I Component mole fractions
NY I Number of components
SPHV O Vapor specific enthalpy (GJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pEntr_Mol
Purpose
Mixed phase specific molar entropy

Subroutine
GPI2SX

Definition
The argument list for GPI2SX is:

9 Interfacing Your Own Physical Properties 289


SUBROUTINE GPI2SX ( T, P, FZ, NZ, SPSM, IFLAG, ICLST )
INTEGER NZ, IFLAG, ICLST
DOUBLE PRECISION T, P, FZ(NZ), SPSM

Name Type Description


T I Temperature (C)
P I Pressure (bar)
FZ I Component mole fractions
NZ I Number of components
ENTRM O Mixed phase molar entropy (kJ/kmol/K)
IFLAG M Error flag
ICLST I Integer value for component list

pEntr_Mol_Liq
Purpose
Liquid specific molar entropy with analytic derivatives

Subroutine
GPIDLSX

Definition
The argument list for GPIDLSX is:
SUBROUTINE GPIDLSX ( T, P, X, NX, SPSL, IFLAG, ICLST,
DERIV, NOUT, NIN, ICALL )
INTEGER NX, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, X(NX), SPSL, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Component mole fractions
NX I Number of components
SPSL O Liquid molar entropy (kJ/kmol/K)
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

9 Interfacing Your Own Physical Properties 290


pEntr_Mol_Sol
Purpose
Solid molar entropy

Subroutine
GPISSX

Definition
The argument list for GPISSX is:
SUBROUTINE GPISSX (T, P, X, NX, SPSS, IFLAG, ICLST)
INTEGER NX, IFLAG, ICLST
DOUBLE PRECISION T, P, X(NX), SPSS

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Component mole fractions
NX I Number of components
SPSS O Solid molar entropy (kJ/kmol/K)
IFLAG M Error flag
ICLST I Integer value for component list

pEntr_Mol_Vap
Purpose
Vapor specific molar entropy with analytic derivatives

Subroutine
GPIDVSX

Definition
The argument list for GPIDVSX is:
SUBROUTINE GPIDVSX ( T, P, Y, NY, SPSV, IFLAG, ICLST,
DERIV, NOUT, NIN, ICALL )
INTEGER NY, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, Y(NY), SPSV, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
Y I Component mole fractions

9 Interfacing Your Own Physical Properties 291


NY I Number of components
SPSV O Vapor molar entropy (kJ/kmol/K)
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pFlash
Purpose
Two phase flash at fixed temperature and pressure

Subroutine
GPI2FE

Definition
The argument list for GPI2FE is:
SUBROUTINE GPI2FE (
T,P,Z,NZ,Y,NY,X,NX,VF,HV,HL,IFLAG,ICLST,WS,NWS )
INTEGER NZ, NY, NX, IFLAG, ICLST, NWS
DOUBLE PRECISION T, P, Z(NZ), Y(NY), X(NX), VF, HV, HL,
WS(NWS)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
Z I Stream component mole fractions
NZ I Number of components
Y O Vapor component mole fractions
NY I Number of components
X O Liquid component mole fractions
NX I Number of components
VF O Vapor fraction
HV O Vapor specific enthalpy (GJ/kmol)
HL O Liquid specific enthalpy (GJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list
WS I/O Workspace array for saving values between
calls
NWS I Size of WS array

9 Interfacing Your Own Physical Properties 292


pFlashPH
Purpose
Two phase flash at fixed pressure and enthalpy

Subroutine
GPI2PH

Definition
The argument list for GPI2PH is:
SUBROUTINE GPI2PH (
P,H,Z,NZ,T,VF,Y,NY,X,NX,HV,HL,IFLAG,ICLST,WS,NWS )
INTEGER NZ, NX, NY, IFLAG, ICLST, NWS
DOUBLE PRECISION P, H, Z(NZ), T, VF, X(NX), Y(NY), HV,
HL, WS(NWS)

Name Type Description


P I Pressure (bar)
H I Overall specific enthalphy (GJ/kmol)
Z I Overall mole fractions
NZ I Number of components
T O Temperature (C)
VF O Vapor fraction
Y O Vapor component mole fractions
NY I Number of components
X O Liquid component mole fractions
NX I Number of components
HV O Vapor specific enthalpy (GJ/kmol)
HL O Liquid specific enthalpy (GJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list
WS I/O Workspace array for saving values
between calls
NWS I Size of WS array

pFlashPV
Purpose
Two phase flash at fixed pressure and vapor fraction

Subroutine
GPI2PV

9 Interfacing Your Own Physical Properties 293


Definition
The argument list for GPI2PV is:
SUBROUTINE GPI2PV (
P,VF,Z,NZ,T,Y,NY,X,NX,HV,HL,IFLAG,ICLST,WS,NWS )
INTEGER NZ, NX, NY, IFLAG, ICLST, NWS
DOUBLE PRECISION P, Z(NZ), T, VF, X(NX), Y(NY), HV, HL,
WS(NWS)

Name Type Description


P I Pressure (bar)
VF I Vapor fraction
Z I Overall mole fractions
NZ I Number of components
T O Temperature (C)
Y O Vapor component mole fractions
NY I Number of components
X O Liquid component mole fractions
NX I Number of components
HV O Vapor specific enthalpy (GJ/kmol)
HL O Liquid specific enthalpy (GJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list
WS I/O Workspace array for saving values
between calls
NWS I Size of WS array

pFlashTH
Purpose
Two phase flash at fixed temperature and enthalpy

Subroutine
GPI2TH

Definition
The argument list for GPI2TH is:
SUBROUTINE GPI2TH (
T,H,Z,NZ,P,VF,Y,NY,X,NX,HV,HL,IFLAG,ICLST,WS,NWS )
INTEGER NZ, NX, NY, IFLAG, ICLST, NWS
DOUBLE PRECISION P, Z(NZ), T, VF, X(NX), Y(NY), HV, HL,
WS(NWS)

Name Type Description

9 Interfacing Your Own Physical Properties 294


T I Temperature (C)
H I Overall specific enthalphy (GJ/kmol)
Z I Overall mole fractions
NZ I Number of components
P O Pressure (bar)
VF O Vapor fraction
Y O Vapor component mole fractions
NY I Number of components
X O Liquid component mole fractions
NX I Number of components
HV O Vapor specific enthalpy (GJ/kmol)
HL O Liquid specific enthalpy (GJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list
WS I/O Workspace array for saving values
between calls
NWS I Size of WS array

pFlashTV
Purpose
Two phase flash at fixed temperature and vapor fraction

Subroutine
GPI2TV

Definition
The argument list for GPI2TV is:
SUBROUTINE GPI2TV (
T,VF,Z,NZ,P,Y,NY,X,NX,HV,HL,IFLAG,ICLST,WS,NWS )
INTEGER NZ, NX, NY, IFLAG, ICLST, NWS
DOUBLE PRECISION P, Z(NZ), T, VF, X(NX), Y(NY), HV, HL,
WS(NWS)

Name Type Description


T I Temperature (C)
VF I Vapor fraction
Z I Overall mole fractions
NZ I Number of components
P O Pressure (bar)
Y O Vapor component mole fractions
NY I Number of components
X O Liquid component mole fractions

9 Interfacing Your Own Physical Properties 295


NX I Number of components
HV O Vapor specific enthalpy (GJ/kmol)
HL O Liquid specific enthalpy (GJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list
WS I/O Workspace array for saving values
between calls
NWS I Size of WS array

pFlash3
Purpose
Three phase flash at fixed temperature and pressure

Subroutine
GPI3FH

Definition
The argument list for GPI3FH is:
SUBROUTINE GPI3FH ( T, P, Z, NZ, RIGOR,
1 Y, NY, X1, NX1, X2, NX2,
2 VF, L2F, HV, HL1, HL2, IFAIL, ISTR )
INTEGER NZ, NY, NX1, NX2, IFLAG, ICLST
DOUBLE PRECISION T, P, Z(NZ), RIGOR, Y(NY), X(NX1),
X2(NX2),
1 VF, L2F, HV, HL1, HL2
CHARACTER*(*) RIGOR

Name Type Description


T I Temperature (C)
P I Pressure (bar)
Z I Stream component mole fraction
NZ I Number of components
RIGOR I 3-phase flash model type
“full”– perform full 3-phase calculation
“decant”– perform 2-phase plus free-
water calculation
Y O Vapor component mole fraction
NY O Number of components
X1 O Liquid 1 component mole fraction
NX1 O Number of components
X2 O Liquid 2 component mole fraction
NX2 O Number of components
VF O Vapor mole fraction
L2F O Mole fraction of liquid phase 2, that is,

9 Interfacing Your Own Physical Properties 296


L2/(L1 + L2 + V)
HV O Vapor specific enthalpy (GJ/kmol)
HL1 O Liquid 1 specific enthalpy (GJ/kmol)
HL2 O Liquid 2 specific enthalpy (GJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list

pFlash3PH
Purpose
Three phase flash at fixed pressure and enthalpy

Subroutine
GPI3PH

Definition
The argument list for GPI3PH is:
SUBROUTINE GPI3PH (P, H, Z, NZ, RIGOR, T, VF, Y, NY, X1,
NX1,
1 X2, NX2, L2F, HV, HL1, HL2, IFLAG,
ICLST, WS, NWS)
INTEGER NZ, NY, NX1, NX2, IFLAG, ICLST, NWS
DOUBLE PRECISION P, H, Z(NZ), T, VF, Y(NY), X1(NX1),
X2(NX2),
1 L2F, HV, HL1, HL2, WS(NWS)
CHARACTER*(*) RIGOR

Name Type Description


P I Pressure (bar)
H I Mixture specific enthalpy (GJ/kmol)
Z I Mixture mole fractions
NZ I Number of components
RIGOR I 3-phase flash model type
“full” – perform full 3-phase calculation
“decant”– perform 2-phase plus free-water
calculation
T O Temperature (C)
VF O Vapor fraction
Y O Vapor mole fractions
NY I Number of components
X1 O Liquid 1 mole fractions
NX1 I Number of components
X2 O Liquid 2 mole fractions
NX2 I Number of components
L2F O Mole fraction of liquid phase 2, that is,
L2/(L1+L2+V)

9 Interfacing Your Own Physical Properties 297


HV O Vapor specific enthalpy (GJ/kmol)
HL1 O Liquid 1 specific enthalpy (GJ/kmol)
HL2 O Liquid 2 specific enthalpy (GJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list
WS I/O Workspace array for saving values between calls
NWS I Size of WS array

pFlash3PV
Purpose
Three phase flash at fixed pressure and vapor fraction

Subroutine
GPI3PV

Definition
The argument list for GPI3PV is:
SUBROUTINE GPI3PV (P, VF, Z, NZ, RIGOR, T, Y, NY, X1,
NX1,
1 X2, NX2, L2F, HV, HL1, HL2, IFLAG,
ICLST, WS, NWS)
INTEGER NZ, NY, NX1, NX2, IFLAG, ICLST, NWS
DOUBLE PRECISION P, Z(NZ), T, VF, Y(NY), X1(NX1),
X2(NX2), L2F,
1 HV, HL1, HL2, WS(NWS)
CHARACTER*(*) RIGOR

Name Type Description


P I Pressure (bar)
VF I Vapor fraction
Z I Mixture mole fractions
NZ I Number of components
RIGOR I 3-phase flash model type
“full” – perform full 3-phase calculation
“decant”– perform 2-phase plus free-
water calculation
T O Temperature (C)
Y O Vapor mole fractions
NY I Number of components
X1 O Liquid 1 mole fractions
NX1 I Number of components
X2 O Liquid 2 mole fractions
NX2 I Number of components
L2F O Mole fraction of liquid phase 2, that is,

9 Interfacing Your Own Physical Properties 298


L2/(L1+L2+V)
HV O Vapor specific enthalpy (GJ/kmol)
HL1 O Liquid 1 specific enthalpy (GJ/kmol)
HL2 O Liquid 2 specific enthalpy (GJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list
WS I/O Workspace array for saving values
between calls
NWS I Size of WS array

pFlash3TH
Purpose
Three phase flash at fixed temperature and enthalpy

Subroutine
GPI3TH

Definition
The argument list for GPI3TH is:
SUBROUTINE GPI3TH (T, H, Z, NZ, RIGOR, P, VF, Y, NY, X1,
NX1,
1 X2, NX2, L2F, HV, HL1, HL2, IFLAG,
ICLST, WS, NWS)
INTEGER NZ, NY, NX1, NX2, IFLAG, ICLST, NWS
DOUBLE PRECISION P, H, Z(NZ), T, VF, Y(NY), X1(NX1),
X2(NX2),
1 HV, HL1, HL2, WS(NWS), L2F
CHARACTER*(*) RIGOR

Name Type Description


T I Temperature (C)
H I Mixture specific enthalpy (GJ/kmol)
Z I Mixture mole fractions
NZ I Number of components
RIGOR I 3-phase flash model type
“full” – perform full 3-phase calculation
decant”– perform 2-phase plus free-water
calculation
P O Pressure (bar)
VF O Vapor fraction
Y O Vapor mole fractions
NY I Number of components
X1 O Liquid 1 mole fractions
NX1 I Number of components

9 Interfacing Your Own Physical Properties 299


X2 O Liquid 2 mole fractions
NX2 I Number of components
L2F O Mole fraction of liquid phase 2, that is,
L2/(L1+L2+V)
HV O Vapor specific enthalpy (GJ/kmol)
HL1 O Liquid 1 specific enthalpy (GJ/kmol)
HL2 O Liquid 2 specific enthalpy (GJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list
WS I/O Workspace array for saving values between
calls
NWS I Size of WS array

pFlash3TV
Purpose
Three phase flash at fixed temperature and vapor fraction

Subroutine
GPI3TV

Definition
The argument list for GPI3TV is:
SUBROUTINE GPI3TV (T, VF, Z, NZ, RIGOR, P, Y, NY, X1,
NX1,
1 X2, NX2, L2F, HV, HL1, HL2, IFLAG,
ICLST, WS, NWS)
INTEGER NZ, NY, NX1, NX2, IFLAG, ICLST, NWS
DOUBLE PRECISION P, Z(NZ), T, VF, Y(NY), X1(NX1),
X2(NX2),
1 HV, HL1, HL2, WS(NWS), L2F
CHARACTER*(*) RIGOR

Name Type Description


T I Temperature (C)
VF I Vapor fraction
Z I Mixture mole fractions
NZ I Number of components
RIGOR I 3-phase flash model type
“full” – perform full 3-phase calculation
“decant”– perform 2-phase plus free-
water calculation
P O Pressure (bar)
Y O Vapor mole fractions
NY I Number of components

9 Interfacing Your Own Physical Properties 300


X1 O Liquid 1 mole fractions
NX1 I Number of components
X2 O Liquid 2 mole fractions
NX2 I Number of components
L2F O Mole fraction of liquid phase 2, that is,
L2/(L1+L2+V)
HV O Vapor specific enthalpy (GJ/kmol)
HL1 O Liquid 1 specific enthalpy (GJ/kmol)
HL2 O Liquid 2 specific enthalpy (GJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list
WS I/O Workspace array for saving values
between calls
NWS I Size of WS array

pFuga_Liq
Purpose
Component liquid fugacity coefficients with analytic derivatives

Subroutine
GPIDLFU

Definition
The argument list for GPIDLFU is:
SUBROUTINE GPIDLFU (T, P, X, NX, FUGL, NFUGL, IFLAG, ICLST,
DERIV, NOUT, NIN, ICALL)
INTEGER NX, IFLAG, ICLST, NFUGL, ICALL
DOUBLE PRECISION T, P, X(NX), FUGL(NFUGL), DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Component mole fractions
NX I Number of components
FUGL O Liquid phase fugacity coefficients
NFUGL I Number of components
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

9 Interfacing Your Own Physical Properties 301


pFuga_Sol
Purpose
Component solid fugacity coefficients

Subroutine
GPISFU

Definition
The argument list for GPISFU is:
SUBROUTINE GPISFU (T, P, Z, NZ, FUGS, NFUGS, IFLAG, ICLST)
INTEGER NZ, NFUGS, IFLAG, ICLST
DOUBLE PRECISION T, P, Z(NZ), FUGS(NFUGS)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
Z I Component mole fractions
NZ I Number of components
FUGS O Solid phase fugacity coefficients
NFUGS I Number of components
IFLAG M Error flag
ICLST I Integer value for component list

pFuga_Vap
Purpose
Component vapor fugacity coefficients with analytic derivatives

Subroutine
GPIDVFU

Definition
The argument list for GPIDVFU is:
SUBROUTINE GPIDVFU (T, P, Y, NY, FUGV, NFUGV, IFLAG, ICLST,
DERIV, NOUT, NIN, ICALL)
INTEGER NY, IFLAG, ICLST, NFUGV, ICALL
DOUBLE PRECISION T, P, Y(NY), FUGV(NFUGV), DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
Y I Component mole fractions

9 Interfacing Your Own Physical Properties 302


NY I Number of components
FUGV O Vapor phase fugacity coefficients
NFUGV I Number of components
IFLAG O Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pGibbs_Mol_IDLGAS
Purpose
Component ideal gas molar Gibbs free energies

Subroutine
GPIZGX_IDLGAS

Definition
The argument list for GPIZGX_IDLGAS is:
SUBROUTINE GPIZGX_IDLGAS (T, Y, NY, ZGi, NG, IFLAG, ICLST)
INTEGER NY, IFLAG, ICLST
DOUBLE PRECISION T, Y(NY), ZGi(NG)

Name Type Description


T I Temperature (C)
Y I Component mole fractions
NY I Number of components
ZGi O Component ideal gas molar Gibbs
free energies (kJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list

pGibbs_Mol_Liq
Purpose
Liquid molar Gibbs free energy with analytic derivatives

Subroutine
GPIDLGX

Definition
The argument list for GPIDLGX is:

9 Interfacing Your Own Physical Properties 303


SUBROUTINE GPIDLGX (T, P, X, NX, SPGL, IFLAG, ICLST, DERIV,
NOUT,NIN, ICALL)
INTEGER NX, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, X(NX), SPGL, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Component mole fractions
NX I Number of components
SPGL O Liquid molar Gibbs free energy
(kJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pGibbs_Mol_Sol
Purpose
Solid molar Gibbs free energy

Subroutine
GPISGX

Definition
The argument list for GPISGX is:
SUBROUTINE GPISGX (T, P, W, NW, SPGS, IFLAG, ICLST)
INTEGER NW, IFLAG, ICLST
DOUBLE PRECISION T, P, W(NW), SPGS

Name Type Description


T I Temperature (C)
P I Pressure (bar)
W I Component mole fractions
NW I Number of components
SPGS O Solid molar Gibb’s free energy
(kJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list

9 Interfacing Your Own Physical Properties 304


pGibbs_Mol_Vap
Purpose
Vapor molar Gibbs free energy with analytic derivatives

Subroutine
GPIDVGX

Definition
The argument list for GPIDVGX is:
SUBROUTINE GPIDVGX (T, P, Y, NY, SPGV, IFLAG, ICLST, DERIV, NOUT,
NIN, ICALL)
INTEGER NY, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, Y(NY), SPGV, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
Y I Component mole fractions
NY I Number of components
SPGV O Vapor molar Gibbs free energy
(kJ/kmol)
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pKllValues
Purpose
Liquid-liquid equilibrium K-values with analytic derivatives

Subroutine
GPIDKLL

Definition
The argument list for GPIDKLL is:
SUBROUTINE GPIDKLL (T, P, X1, NX1, X2, NX2, KLL, NKLL,
IFLAG, ICLST, DERIV, NOUT, NIN, ICALL)
INTEGER NX1, NX2, NKLL, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, X1(NX1), X2(NX2), KLL(NKLL)
DOUBLE PRECISION DERIV(NOUT, NIN)

9 Interfacing Your Own Physical Properties 305


Name Type Description
T I Temperature (C)
P I Pressure (bar)
X1 I Component mole fractions in first liquid phase
NX1 I Number of components
X2 I Component mole fractions in second liquid phase
NX2 I Number of components
KLL O Liquid-liquid equilibrium K values
NKLL I Number of components
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pKValues
Purpose
Vapor-liquid equilibrium K-values with analytic derivatives

Subroutine
GPID0KX

Definition
The argument list for GPID0KX is:
SUBROUTINE GPID0KX (T, P, X, NX, Y, NY, K, NK, IFLAG,
ICLST, DERIV, NOUT, NIN, ICALL)
INTEGER IFLAG, ICLST, NX, NY, NK, ICALL
DOUBLE PRECISION T, P, X(NX), Y(NY), K(NK),DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
Y I Vector of vapor component mole
fractions
NY I Number of components
FX I Vector of liquid component mole
fractions
NX I Number of components
K O Vector of K values
NK I Number of components
IFLAG M Error flag

9 Interfacing Your Own Physical Properties 306


ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pMolweight
Purpose
Stream molar weight

Subroutine
GPI0WX

Definition
The argument list for GPI0WX is:
SUBROUTINE GPI0WX (X, NC, MW, IFLAG, ICLST)
INTEGER NC, IFLAG, ICLST
DOUBLE PRECISION X(NC), MW

Name Type Description


X I Vector of component mole
fractions of size NC
NC I Number of components
MW O Stream mean molar weight
(kg/kmol)
IFLAG M Error flag
ICLST I Integer value for component list

pMolweights
Purpose
Component molar weights

Subroutine
GPIZW0

Definition
The argument list for GPIZW0 is:
SUBROUTINE GPIZW0 (MW, NMW, IFLAG, ICLST)
INTEGER NMW, IFLAG, ICLST
DOUBLE PRECISION MW

9 Interfacing Your Own Physical Properties 307


Name Type Description
MW O Array of component molar weights
(kg/kmol)
NMW I Number of components
IFLAG M Error flag
ICLST I Integer value for component list

pSurf_Tens
Purpose
Liquid surface tension with analytic derivatives

Subroutine
GPIDLTX

Definition
The argument list for GPIDLTX is:
SUBROUTINE GPIDLTX (T, P, X, NX, ST, IFLAG, ICLST, DERIV,
NOUT, NIN, ICALL)
INTEGER NX, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, X(NX), ST, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Component mole fractions
NX I Number of components
ST O Liquid surface tension (N/m)
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pSurf_TensY
Purpose
Surface tension using vapor and liquid mole fractions

Subroutine
GPILTXY

9 Interfacing Your Own Physical Properties 308


Definition
The argument list for GPILTXY is:
SUBROUTINE GPILTXY ( T, P, X, NX, Y, NY, ST, IFLAG,
ICLST )
INTEGER NX, NY, IFLAG, ICLST
DOUBLE PRECISION T, P, X(NX), Y(NY), ST

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Component liquid mole fractions
NX I Number of components
Y I Component vapor mole fractions
NY I Number of components
ST O Surface tension (N/m)
IFLAG M Error flag
ICLST I Integer value for component list

pTrueComp
Purpose
True species composition of an electrolyte mixture

Subroutine
GPITRU

Definition
SUBROUTINE GPITRU (T, P, AZ, NAZ, TZ, NTZ, SF, LF, IFLAG,
ICLST)
INTEGER NAZ, NTZ, IFLAG, ICLST
DOUBLE PRECISION T, P, AZ(NAZ), TZ(NTZ), SF, LF

Name Type Description


T I Temperature (C)
P I Pressure (bar)
AZ I Apparent component mole fractions
NAZ I Number of components
TZ O True component mole fractions
NTZ I Number of components
SF O Molar ratio of true solid to true liquid
LF O Molar ratio of true liquid to apparent liquid
IFLAG M Error flag
ICLST I Integer value for component list

9 Interfacing Your Own Physical Properties 309


pTrueCmp2
Purpose
PTrueCmp2 calculates the composition of true species composition in the
slurry phase.
(An alternative version to Procedure pTrueComp for electrolytes)

Subroutine
GPITR2

Definition
SUBROUTINE GPITR2 ( T, P, XA, NXA, XT, NXT, XTL, NXTL, XTS,
NXTS,SFRAC,T2A,IFLAG,ICLST)
INTEGER NXA, NXT, NXTL, NXTS, IFLAG, ICLST
DOUBLE PRECISION T, P, XA(NXA), XT(NXT), XTL(NXTL), XTS(NXTS), SFRAC,
T2A

Name Type Description


T I Temperature (C)
P I Pressure (bar)
XA I Apparent component mole fractions
NXA I Number of apparent components
XT O Overall true component mole fractions
NXT I Number of overall true components
XTL O Liquid true component mole fractions
NXTL I Number of liquid true components
XTS O Solid true component mole fractions
NXTS O Number of solid true components
SFRAC O True solid mole fraction
T2A O True to apparent mole ratio
IFLAG M Error flag
ICLST I Integer value for component list

pTrueCmpVLS
Purpose
V, L & S species composition of an electrolyte mixture

Subroutine
GPITRVLS

Definition
The argument list for GPITRVLS is:

9 Interfacing Your Own Physical Properties 310


SUBROUTINE GPITRVLS

pVap_Pressures
Purpose
Component vapor pressures

Subroutine
GPIZP0

Definition
The argument list for GPIZP0 is:
SUBROUTINE GPIZP0 (T, PV, NPV, IFLAG, ICLST)
INTEGER NPV, IFLAG, ICLST
DOUBLE PRECISION T, PV(NPV)

Name Type Description


T I Temperature (C)
PV O Component vapor pressures (bar)
NPV I Number of components
IFLAG M Error flag
ICLST I Integer value for component list

pVisc_Liq
Purpose
Liquid phase viscosity with analytic derivatives

Subroutine
GPIDLVX

Definition
The argument list for GPIDLVX is:
SUBROUTINE GPIDLVX (T, P, X, NX, VL, IFLAG, ICLST, DERIV,
NOUT, NIN, ICALL)
INTEGER NX, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, X(NX), VL, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
X I Component mole fractions
NX I Number of components

9 Interfacing Your Own Physical Properties 311


VL O Liquid phase viscosity (cP)
IFLAG M Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

pVisc_Vap
Purpose
Vapor phase viscosity

Subroutine
GPIDVVX

Definition
The argument list for GPIDVVX is:
SUBROUTINE GPIDVVX (T, P, Y, NY, VV, IFLAG, ICLST, DERIV,
NOUT, NIN, ICALL)
INTEGER NY, IFLAG, ICLST, ICALL
DOUBLE PRECISION T, P, Y(NY), VV, DERIV(NOUT,NIN)

Name Type Description


T I Temperature (C)
P I Pressure (bar)
Y I Component mole fractions
NY I Number of components
VV O Vapor phase viscosity (cP)
IFL O Error flag
ICLST I Integer value for component list
DERIV O Analytic derivatives
NOUT I Number of output variables
NIN I Number of input variables
ICALL I Calling status

Fortran Programmer's Checklist


Ensure that your routines conform to the following rules:
• All calls must obey Fortran calling conventions.
• All routines that employ an iterative equation-solving procedure (for
example, flash calculations), must ensure that the precision of their
results is at least 1.0E-7.

9 Interfacing Your Own Physical Properties 312


• All real variables must be double precision. To do this, use IMPLICIT
NONE, and declare them as double precision variables.

Installing the Physical


Properties Interface
After you have prepared the Generalized Physical Properties Interface
routines and the entry point routines, you must install them.
All your Generalized Physical Properties and entry point routines must be built
into a dynamic linked library called gpp.dll. The optional gpp_setup function
must be built into its own dynamic linked library, called gpp_setup.dll.
To ensure that your Aspen Modeler product uses your version of gpp.dll, you
can either:
• Rename the existing gpp.dll and gpp_setup.dll files (which are valid for
Properties Plus) in the bin directory and place your own gpp.dll and
gpp_setup.dll files in this directory.

Note: The default installation path for the bin directory


containing the DLLs is \Program Files\AspenTech\AMSystem
12.1.

– or –
• Place your gpp.dll and gpp_setup.dll files in the working directory for the
simulation.
Make sure you test your interface thoroughly before releasing it for general
use.

9 Interfacing Your Own Physical Properties 313


10 Using the Control Design
Interface (CDI)

An Aspen Modeler model contains full information on the process being


studied. A number of Computer Aided Control System Design (CACSD)
software packages take simplified, linear process representations and analyze
this data to recommend a control strategy for the process. The Control Design
Interface (CDI) enables you to produce linear models from an Aspen Modeler
simulation for transfer between Aspen Modeler and a CACSD package, for
example MATLAB®.
This chapter explains:
• How CDI works.
• How to create CDI automation scripts to generate the information required
for CACSD packages.
• CDI output file format.

Note: Some CDI calculations use LAPACK 2.0.

CDI also produces the following, which can be used in designing control
systems:
• Relative Gain Array (RGA).
• Niederlinski Index (NI).
• Morari Resiliency Index (MRI).
• State Transition Matrix (STM).
LAPACK 2.0 is written by E. Anderson, Z. Bai, C. Bischof, J Demmel, J.
Dongarra, J. du Croz, A. Greenbaum, S. Hammarling, A. McKenney, S.
Ostrouchov, and D. Sorensen.

How CDI Works


To understand how the Control Design Interface (CDI) works, you need to
understand the differences between the Aspen Modeler DAE models involving
differential and algebraic equations, and the linear models that are required
by CACSD packages.

10 Using the Control Design Interface (CDI) 314


About DAE Models
Aspen Modeler products provide an equation-based simulation environment and
enable you to perform dynamic simulations. A dynamic model of a lumped
parameter process is described in terms of differential and algebraic equations
(a DAE system). The general form for such a model is:

 dX 
f t, , X , Z, U  = 0
 dt 
Where:
t = Time, the independent variable
X = A vector of the variables whose time derivatives
appear in the model:
dX
dt
These are known as state variables.
Z = A vector of unknowns whose time derivatives
do not appear. These are known as algebraic
variables.
U = The set of inputs or forcing functions whose
time behavior is given.

About Linear Models


Dynamic simulators have been used extensively to evaluate process control
schemes. These control systems can be designed using Computer Aided Control
System Design (CACSD) packages such as MATLAB®. These tools require a
linear model of the process. The Control Design Interface (CDI) enables you to
produce this model in the state-space form:

x& (t ) = Ax (t ) + Bu (t )
y (t ) = Cx (t ) + Du (t )
Where:
t = Time
x(t) = The vector of n perturbations in the state
variables in the problem.
u(t) = A vector of r perturbations about the
chosen inputs, which refer to a subset of
the set variables. These include any
potential manipulated variables for the
purpose of control system design.
Manipulated variables are those varied by
a controller.
y(t) = A vector of m resultant perturbations in
the chosen outputs, which are a subset of

10 Using the Control Design Interface (CDI) 315


the state and unknown algebraic
variables. These include measured
variables for the purposes of control
system design.
A, B, C, D = Coefficient matrices of appropriate
dimensions:
A –nxn (square)
B –nxr
C –mxn
D –mxr
These are known as the state-space
matrices.
The state space may be produced at any
plant state, but is usually produced at the
normal operating steady state.

How CDI Produces Linearized Models


The Control Design Interface ( CDI ) enables data to be transferred between
Aspen Modeler products and CACSD packages. It does this by producing a
linearized version of an Aspen Modeler simulation in the form of state-space
matrices. For information on how to use CDI to do this, see Creating CDI
Automation Scripts.
The state-space matrices A, B, C, and D are the products of CDI. To produce
these matrices, CDI eliminates all the algebraic variables from the original
dynamic simulation which do not appear in the linear model. For example, by
selecting five algebraic output variables in a problem of 100 algebraic
unknowns, CDI eliminates 95 variables.
CDI also produces the steady-state transfer function defined as follows:

y (t ) = G u (t )
Where all derivatives and algebraic variables have been eliminated.
G has the dimensions:
G –mxr

Relative Gain Array (RGA)


The Relative Gain Array (RGA), is a matrix of ratios of steady-state gains.
Element (i,j) of the matrix is the ratio between the ith controlled (output)
variable and the jth manipulated (input) variable when all other manipulated
variables are constant, divided by the steady-state gain between the same
two variables when all other controlled variables are constant.
The RGA matrix is useful for avoiding poor pairings of manipulated and
controlled variables. If the diagonal element in the RGA is negative, the
control system might be unstable and large values of the RGA indicate that

10 Using the Control Design Interface (CDI) 316


the system can be sensitive to changes in values of parameters in the control
system.

Niederlinski Index (NI)


The Niederlinski Index (NI), can be used to help determine the stability of
your control system based on the input and output variables chosen:

If the Then
index is
Negative The control system is unstable (known as "integral instability").
Positive The control system may or may not be stable.

Morari Resiliency Index (MRI)


The Morari Resiliency Index (MRI) is used to give an idea of the controllability
of your process flowsheet, using the input and output variables you have
chosen. The MRI is computed at zero frequency, that is, based on the steady-
state gain array only. The larger the value of the MRI, the more controllable
(or "resilient") the process.

Note: When comparing different control schemes, note that MRI


depends on the units of measurement used.

State Transition Matrix (STM)


The State Transition Matrix (STM) at time T relates the values of the state
variables at time T in the linearized state-space model to the initial condition
via the following expression:
x(T) = STM(T) . x(0)
Where:
x = A vector of the n state variables in your non-
linear model
x(0) = The corresponding initial conditions
T = The time you specify for which the STM is
required.
You can choose a subset of the state variables to be ignored and these are
dropped from the STM, analogous to model reduction. The choice of variables
ignored must be based on engineering knowledge so that a valid STM exists.
The STM is computed using fixed step Implicit Euler integration of the state-
space model. You can specify the size of integration step used to compute the
STM, which affects both the accuracy of the STM and speed of computation.

10 Using the Control Design Interface (CDI) 317


Creating CDI Automation
Scripts
Before you use the CDI on a simulation, make sure:

• The simulation contains at least one CDI input variable and one output
variable.
• The simulation does not have an index > 1 for the A, B, C, and D matrices
to be computed.
• The current solution is converged.

Note: You can have several CDI automation scripts in a


flowsheet.

To create a CDI script:


1 Create a script in the usual way.
2 In the Text Editor window, type the appropriate CDI syntax.
3 Run or save the script as required.

Notes:

• You can perform a CDI calculation at any time during the


simulation, provided the simulation is paused. For example,
you might want to calculate the A, B, C, D matrices at a
number of different time points during a dynamic simulation.
To do this, you would pause the simulation and run the CDI
script at the times required. (You could also write a task
which runs the CDI script at each time point required.)

• You should make sure that your model is not of index>1


before performing a CDI calculation.

• Tearing is ignored during a CDI calculation (that is CDI


linearises your model as if tearing is off).

• Delay is ignored during a CDI calculation (that is, the


delay is set to zero for your delayed variables).

• You should not perform a CDI calculation at a time when


your model contains indeterminate variables.

For general background information on scripts, see the Automation Reference.

10 Using the Control Design Interface (CDI) 318


Syntax for CDI Automation Scripts
For details of the syntax for creating CDI automation scripts, see the
Automation Reference.

Example of Creating a CDI Script


The following syntax runs the Control Design Interface on the currently open
simulation document:
Set Doc = Simulation
set CDI = Doc.CDI
CDI.Reset
'CDI.ZeroTolerance=value
CDI.AddInputVariable "B1.u(1)"
CDI.AddInputVariable "B1.u(2)"
CDI.AddOutputVariable "B1.y(1)"
CDI.AddOutputVariable "B1.y(2)"

' "Matrix" can be one or more of A, B, C, D, G, RGA, NI, MRI,


STM, or ALL.
' The default is "ALL".
CDI.MatricesRequired "G","A","B","C","D","RGA"
CDI.Calculate

application.msg "input variables U"


dim inputs
inputs = cdi.inputs()
for i=1 to CDI.numberofinputs
application.msg "U " & i & " is " & inputs(i-1)
next

application.msg "output variables X"


dim outputs
outputs = cdi.outputs()
for i=1 to CDI.numberofoutputs
application.msg "Y " & i & " is " & outputs(i-1)
next

10 Using the Control Design Interface (CDI) 319


application.msg "state variables X"
dim states
states = cdi.states()
for i=1 to CDI.numberofstates
application.msg "X " & i & " is " & states(i-1)
next

' example to list the elements of a matrix


dim rows, cols, vals
if CDI.MatrixStatus("A") then
application.msg "Matrix A"
rows = CDI.matrixrows("A")
cols = CDI.matrixcols("A")
vals = CDI.matrixValues("A")
for i=0 to CDI.MatrixNonZeros("A")-1
' application.msg rows(i) & " "& cols(i) & " "& vals(i)
application.msg states(rows(i)-1) & " "& states(cols(i)-1) & "
"& vals(i)
next
application.msg ""
end if

CDI Output Files


The matrix data generated by CDI is in ASCII .dat file format.
The .dat format enables you to import your state-space model into a
Computer Aided Control System Design (CACSD) package, for example,
MATLAB®.
In addition to the .dat file, the CDI Calculate function also creates a .lis file of
the same name. You can use the values in the .lis file to scale the matrices
produced.

ASCII DAT Format


The .dat ASCII text file contains three columns delimited by spaces: the first
column is a list of row indices, the second a list of column indices and the
third column a list of values. For example, the .dat file:
1 1 2.0
2 1 -1.0

10 Using the Control Design Interface (CDI) 320


2 2 3.0
represents the matrix:
[2 0]
[-1 3]
This file can be easily read by other applications or programs. It can be
imported into Matlab(R) using the following commands
load A.dat
A = spconvert(A)
where A.dat is the name of the .dat file and A will be the matrix in sparse
format.

Note: Because the .dat file is in sparse format (that is, it


contains only the non-zero values of the matrix above the
threshold), the .dat file is not generated if the matrix has no non-
zero values.

About the CDI .lis File


The .lis file created by CDI contains the following information:
• A description, including the simulation file name.
• Time of linearization.
• Lists of state, input, and output variables, and for each variable, the index
number into the relevant matrix, and the value of the variable at the point
of linearization.
You can use the values in the .lis file to scale the matrices produced.

Example CDI .lis File


The following is an example of a CDI .lis file:
CDI information for btxcdi.acmf
Linearized at time 0
CDI summary of matrices computed:
A matrix computed, number of non-zero elements = 2027
B matrix computed, number of non-zero elements = 10
C matrix computed, number of non-zero elements = 9
G matrix computed, number of non-zero elements = 9
RGA matrix computed, number of non-zero elements = 9
MRI = 0.000045
NI = -45.639983

10 Using the Control Design Interface (CDI) 321


Number of state variables: 152
Number of input variables: 3
Number of output variables: 3

Statevariables:
Row number value, variable name
1 56630.91392788936 BOIL1.H
2 29.34365911855432 BOIL1.HOLD
3 0.001600381056687257 BOIL1.X(1)
4 0.04839961894331289 BOIL1.X(2)
5 0.9500000000000003 BOIL1.X(3)
6 40027.78575458659 BOIL2.H
7 3.374829890424375 BOIL2.HOLD
8 0.09756317794410598 BOIL2.X(1)
9 0.8599999999999991 BOIL2.X(2)
10 0.04243682205589397 BOIL2.X(3)
11 1.26090782888274E-005 COL1CC1.INT_ERROR
12 0.0006108000000000003 COL1LC1.INT_ERROR
13 34124.00295229167 COL1LSD.H
14 1.469734318272604 COL1LSD.HOLD
15 0.489623436584582 COL1LSD.X(1)
16 0.4942614216602229 COL1LSD.X(2)
17 0.01611514175519472 COL1LSD.X(3)
18 55303.67884006869 COL1S1.DTRAY_(1).H
19 1.578342265854297 COL1S1.DTRAY_(1).HOLD
20 0.005000157710917587 COL1S1.DTRAY_(1).X(1)
21 0.08336499426852256 COL1S1.DTRAY_(1).X(2)
22 0.9116348480205604 COL1S1.DTRAY_(1).X(3)
23 53937.18572594383 COL1S1.DTRAY_(2).H
24 1.591115757132761 COL1S1.DTRAY_(2).HOLD
25 0.01407130148293106 COL1S1.DTRAY_(2).X(1)
26 0.1275970773766303 COL1S1.DTRAY_(2).X(2)
27 0.8583316211404389 COL1S1.DTRAY_(2).X(3)
28 51986.67561748526 COL1S1.DTRAY_(3).H
29 1.606739705233883 COL1S1.DTRAY_(3).HOLD

10 Using the Control Design Interface (CDI) 322


30 0.03630380807061213 COL1S1.DTRAY_(3).X(1)
31 0.1753161450635736 COL1S1.DTRAY_(3).X(2)
32 0.7883800468658145 COL1S1.DTRAY_(3).X(3)
33 49306.68313959331 COL1S1.DTRAY_(4).H
34 1.630876457027793 COL1S1.DTRAY_(4).HOLD
35 0.08443663380975423 COL1S1.DTRAY_(4).X(1)
36 0.2129733680481336 COL1S1.DTRAY_(4).X(2)
37 0.7025899981421124 COL1S1.DTRAY_(4).X(3)
38 45994.13285292211 COL1S1.DTRAY_(5).H
39 1.666987865560976 COL1S1.DTRAY_(5).HOLD
40 0.1708049644348191 COL1S1.DTRAY_(5).X(1)
41 0.2215726719669167 COL1S1.DTRAY_(5).X(2)
42 0.6076223635982644 COL1S1.DTRAY_(5).X(3)
43 41418.83202631665 COL1S1.DTRAY_(7).H
44 1.319435851211945 COL1S1.DTRAY_(7).HOLD
45 0.3122235872826195 COL1S1.DTRAY_(7).X(1)
46 0.2344717468241706 COL1S1.DTRAY_(7).X(2)
47 0.4533046658932101 COL1S1.DTRAY_(7).X(3)
48 39856.29686982051 COL1S1.DTRAY_(8).H
49 1.346612120389595 COL1S1.DTRAY_(8).HOLD
50 0.3427912484734354 COL1S1.DTRAY_(8).X(1)
51 0.2936260349648588 COL1S1.DTRAY_(8).X(2)
52 0.3635827165617058 COL1S1.DTRAY_(8).X(3)
53 38145.34215893035 COL1S1.DTRAY_(9).H
54 1.379424477712419 COL1S1.DTRAY_(9).HOLD
55 0.378355139274437 COL1S1.DTRAY_(9).X(1)
56 0.3621779792418554 COL1S1.DTRAY_(9).X(2)
57 0.2594668814837076 COL1S1.DTRAY_(9).X(3)
58 36616.46598584802 COL1S1.DTRAY_(10).H
59 1.411728819023971 COL1S1.DTRAY_(10).HOLD
60 0.4125512694761682 COL1S1.DTRAY_(10).X(1)
61 0.4252928967717221 COL1S1.DTRAY_(10).X(2)
62 0.1621558337521095 COL1S1.DTRAY_(10).X(3)
63 35473.94728342046 COL1S1.DTRAY_(11).H
64 1.437817415678034 COL1S1.DTRAY_(11).HOLD

10 Using the Control Design Interface (CDI) 323


65 0.4409875674513755 COL1S1.DTRAY_(11).X(1)
66 0.4702477599755525 COL1S1.DTRAY_(11).X(2)
67 0.08876467257307183 COL1S1.DTRAY_(11).X(3)
68 34694.99810045036 COL1S1.DTRAY_(12).H
69 1.456327384917594 COL1S1.DTRAY_(12).HOLD
70 0.4647758470399063 COL1S1.DTRAY_(12).X(1)
71 0.4929654751627123 COL1S1.DTRAY_(12).X(2)
72 0.04225867779738084 COL1S1.DTRAY_(12).X(3)
73 42610.38072431905 COL1S1.DFTRAY_.H
74 1.713763806847634 COL1S1.DFTRAY_.HOLD
75 0.2900384130099258 COL1S1.DFTRAY_.X(1)
76 0.1920373694422355 COL1S1.DFTRAY_.X(2)
77 0.5179242175478388 COL1S1.DFTRAY_.X(3)
78 33258.77588427347 COL1S2.DTRAY_(15).H
79 1.585593472664548 COL1S2.DTRAY_(15).HOLD
80 0.550675663666079 COL1S2.DTRAY_(15).X(1)
81 0.4468777798630484 COL1S2.DTRAY_(15).X(2)
82 0.002446556470872464 COL1S2.DTRAY_(15).X(3)
83 32687.21777623817 COL1S2.DTRAY_(16).H
84 1.59870339232037 COL1S2.DTRAY_(16).HOLD
85 0.5998167262708132 COL1S2.DTRAY_(16).X(1)
86 0.3992834173940175 COL1S2.DTRAY_(16).X(2)
87 0.0008998563351691505 COL1S2.DTRAY_(16).X(3)
88 31995.1376181745 COL1S2.DTRAY_(17).H
89 1.615340075748922 COL1S2.DTRAY_(17).HOLD
90 0.6628494052313106 COL1S2.DTRAY_(17).X(1)
91 0.3368363178704358 COL1S2.DTRAY_(17).X(2)
92 0.0003142768982534644 COL1S2.DTRAY_(17).X(3)
93 31216.92243668794 COL1S2.DTRAY_(18).H
94 1.6351804701215 COL1S2.DTRAY_(18).HOLD
95 0.7370471341578386 COL1S2.DTRAY_(18).X(1)
96 0.2628502253015669 COL1S2.DTRAY_(18).X(2)
97 0.0001026405405945184 COL1S2.DTRAY_(18).X(3)
99 1.656583671115566 COL1S2.DTRAY_(19).HOLD
100 0.8153884653177895 COL1S2.DTRAY_(19).X(1)

10 Using the Control Design Interface (CDI) 324


101 0.1845808532812316 COL1S2.DTRAY_(19).X(2)
102 3.068140097857487E-005 COL1S2.DTRAY_(19).X(3)
103 29713.47334158488 COL1S2.DTRAY_(20).H
104 1.677118566833914 COL1S2.DTRAY_(20).HOLD
105 0.8887844439714674 COL1S2.DTRAY_(20).X(1)
106 0.1112076093614257 COL1S2.DTRAY_(20).X(2)
107 7.946667106603748E-006 COL1S2.DTRAY_(20).X(3)
108 33725.94758562 COL1VF.H
109 1.575084246590023 COL1VF.HOLD
110 0.5142481364033974 COL1VF.X(1)
111 0.4793611206033546 COL1VF.X(2)
112 0.006390742993247772 COL1VF.X(3)
113 38495.65648181258 COL2.DTRAY_(1).H
114 0.1101611331477206 COL2.DTRAY_(1).HOLD
115 0.16410365816141 COL2.DTRAY_(1).X(1)
116 0.8114974344797556 COL2.DTRAY_(1).X(2)
117 0.02439890735883355 COL2.DTRAY_(1).X(3)
118 37356.54270046446 COL2.DTRAY_(2).H
119 0.1115288131841191 COL2.DTRAY_(2).HOLD
120 0.2399027544464658 COL2.DTRAY_(2).X(1)
121 0.7409111436863956 COL2.DTRAY_(2).X(2)
122 0.0191861018671378 COL2.DTRAY_(2).X(3)
123 36323.07008250972 COL2.DTRAY_(3).H
124 0.1127401705364569 COL2.DTRAY_(3).HOLD
125 0.3152434180958412 COL2.DTRAY_(3).X(1)
126 0.6671765631006116 COL2.DTRAY_(3).X(2)
127 0.01758001880354662 COL2.DTRAY_(3).X(3)
128 35471.19703044987 COL2.DTRAY_(4).H
129 0.1138176570093002 COL2.DTRAY_(4).HOLD
130 0.3807482795858485 COL2.DTRAY_(4).X(1)
131 0.6023396803845782 COL2.DTRAY_(4).X(2)
132 0.01691204002957304 COL2.DTRAY_(4).X(3)
133 34835.49621452565 COL2.DTRAY_(5).H
134 0.1146683449867835 COL2.DTRAY_(5).HOLD
135 0.4312132095856979 COL2.DTRAY_(5).X(1)

10 Using the Control Design Interface (CDI) 325


136 0.5522579713440989 COL2.DTRAY_(5).X(2)
137 0.0165288190702029 COL2.DTRAY_(5).X(3)
138 34396.53012457469 COL2.DTRAY_(6).H
139 0.1152730396070888 COL2.DTRAY_(6).HOLD
140 0.4665080600391092 COL2.DTRAY_(6).X(1)
141 0.5172110097593484 COL2.DTRAY_(6).X(2)
142 0.0162809302015423 COL2.DTRAY_(6).X(3)
143 -1.041701473697337E-005 COL2CC1.INT_ERROR
144 1.726221818181818 COL2LC1.INT_ERROR
145 29135.11893854067 COND1.DDRUM_.H
146 28.57538395971298 COND1.DDRUM_.HOLD
147 0.95 COND1.DDRUM_.X(1)
148 0.04999869034720324 COND1.DDRUM_.X(2)
149 1.30965279643544E-006 COND1.DDRUM_.X(3)
150 0.07044514285714286 COND1.P_I_CONTROLLER_
(1).INT_ERROR
151 1.181997073571317E-005 COND1.P_I_CONTROLLER_
(2).INT_ERROR
152 -3.55284602705969E-005 DTC.INT_ERROR
Input variables:
1 0.95 COL1CC1.SET_POINT
2 272.7 MF.TOT_FLOW
3 0.45 MF.X(1)
Output variables:
1 173.6485382570043 BOIL1.TEMP
2 0.3122235872826195 COL1S1.DTRAY_(7).X(1)
3 134.0401535317992 COL1S1.DTRAY_(7).TEMP

Relating Indices to Matrices


The indices are numbered from 1 to the number of states/inputs/outputs (n),
and can be mapped to the indices of the matrices produced by the CDI
calculation.
For example, matrix A is nStates x nStates in size, so variable 1 represents
row 1/column 1 of A.
Similarly, matrix D is nOutputs x nInputs, with the indices of the input
variables mapping to the columns of D, and the outputs map to the rows.
Matrix G is nOutputs x nInputs

10 Using the Control Design Interface (CDI) 326


The following diagram shows the complete mapping:
States Inputs

States A B

Outputs C D

10 Using the Control Design Interface (CDI) 327


11 Estimation

Estimation is used when you need to fit a model to a set of experimental or


actual process data. You can use estimation for both steady-state and
dynamic simulations. The model is fitted by finding the appropriate values for
the estimated parameters. A special run class is provided with the Aspen
Modeler product to allow the estimation of adjustable parameters.
The elements of an estimation simulation are:
• Blocks and streams, as in other run types.
• Experimental data, which you define using the Estimation tool or scripting.
• Regressed parameters (variables), which are selected using the Estimation
tool or scripting.
Two different estimation methods are available:
• Weighted least squares minimization.
• Maximum log likelihood.

Mathematical Statement of
Flowsheet Equations
The mathematical statement of the flowsheet equations in Aspen Modeler
products is:
f ( x, x& , y , u, θ ) = 0
(1)
g ( x, y , u , θ ) = 0
(2)
consisting of n differential equations f and m algebraic
equations g.
The variables are partitioned as:

x (t ) ∈ R n Differential variables

x& (t ) ∈ R n Time derivatives of differential variables

y (t ) ∈ R m
Algebraic variables

u (t ) ∈ R λ Input variables

11 Estimation 328
θ ∈R ρ Input variables to be estimated
It should be noted that, for purely steady-state problems, n=0.

About Experimental Data


A dynamic experiment is defined by specifying the time variation of the
input variables u (t) and a consistent initial condition for the given
mathematical model. At various times t>0 during the experiment,
measurements (or observed values) are taken of a subset z of x and/or y.
Note that the variables being measured are not necessarily the same for
different times t.
Let the total number of dynamic experiments be Ndyn; the dimension of z,
that is, the number of unique variables z(j), of x or y which have been
measured over all the experiments be Nmeas; and the number of
measurements of z(j) in experiment i be Mij.
Mij may be zero if variable j is not measured at all in experiment i.
z$ijk th
denotes the k measurement of variable z(j) in experiment i. It is a
zj t ijk
measurement of at time .
A steady-state experiment is simply a special case of the a dynamic
&
experiment, with inputs u = constant, for all t ≥ 0 and the initial conditions x =
0. They involve a single measurement only of a subset z of variables x and/or
y. Let NSS be the total number of steady-state experiments.
z$ ij
denotes the measurement of variable z(j) in steady-state experiment i.

About Parameter Estimation


Methods
You can use two methods to solve estimation simulations:
• Weighted least squares minimization.
• Maximum log likelihood.
The choice of which method is appropriate to solve a particular estimation
problem depends on the errors in the measurements. The two methods are
equivalent in a situation when:
• The estimated variables are normally distributed.
• The errors in the observed values of the measured variables are
independent from observation to observation.
• The errors are independent from one measured variable to the next
measured variable.
This situation is not common and it is usually not possible even to know if or
when the above criteria are satisfied. Hence, an appropriate choice of method

11 Estimation 329
must be made. If you have some idea of the error in the measurements, then
the Weighted Least Squares method is appropriate, otherwise the Maximum
Log Likelihood method is preferred.
For more information on the two methods available for solving a parameter
estimation problem, see the Solver Options Reference.

About Least Squares Parameter


Estimation
The Least Squares method minimizes the weighted absolute squared error
between the observed and predicted values of the measurements. You should
set the weights of the measured variables to be the reciprocal of the standard
error (if they are known) of the observations.
Given the process model and the experimental measurements, using the least
squares method to solve your parameter estimation problem determines the
values of the parameters θ which solve the following minimization problem:
2
NDyn NMeas Mij NSS NMeas

∑ ∑∑ (
W ijk2 z j (t ijk ) − z ikj ) ∑∑ ( )
2
Min  + w ij2 z ij − z$ ij 
 i =1 j =1 k =1 i =1 j =1 
θ
subject to:

θ L ≤ θ ≤ θU

z t( )
where j ijk are calculated (or predicted) by solving the model equations (1)
and (2) with the inputs u and initial conditions corresponding to dynamic
experiment i.

ijk W ij W
The weights and (the product of experiment and measurement
weights) are user-specified and reflect the importance of, or confidence in,
the corresponding experimental measurement.

The lower and upper bounds θ and θ serve to keep the parameters within
L U

physically realistic and/or mathematically acceptable limits.

About Log Likelihood Estimation


The Maximum Log Likelihood method maximizes the log of the likelihood
function of the predicted and observed values. When the log of the likelihood
function (and hence the likelihood function itself since log is a monotonically
increasing function) is maximized, the probability of obtaining the given set of
measurements from the estimated variables is maximized. This corresponds
to getting the best fit of your measurements.

11 Estimation 330
The likelihood function used takes into account the standard error of the
observations by using a heteroscedasticity parameter for each unique
measured variable.
The heteroscedasticity parameter has range 0 to 2:
• 0 corresponds to the error in the measurements being independent of the
values of the measurements (constant absolute error).
• 2 corresponds to the error in the measurements being proportional to the
values of the measurements (constant relative error).
You can fix the value of the heteroscedasticity parameters (if you know
suitable values for them) or ask the method to compute them automatically
during maximization of the log likelihood function. This method is particularly
useful if you have no idea of the errors in the measurements.
Given the process model and the experimental measurements, using the
maximum log likelihood method to solve your parameter estimation problem
seeks to determine the values of the parameters θ (and optionally the
γ
heteroscedasticity parameters of your measurements) to solve the
following minimization problem:

  NDyn Mij  z$ ijk − z(t ijk )  


2
max  1 NMeas 
 n i (log 2π + 1) + n i logn i
∑ wj 
2
∑∑  +
θ , γ  2 i =1    z γi  
  j =1 k =1  ijk  

   NSS
( ) 
2
NDyn Mij
 1 NMeas  z$ ij − z ij
γi ∑∑ log w j z$(t ijk )  + ∑ n
 i (log 2π + 1) + n i logn
i ∑
w 2j 
j =1 k =1  2 i =1   j =1 z$ ij
γi 
   


NSS
 
+γi
j =1
∑ $
log w j z ij  
 

subject to θ L ≤ θ ≤ θ U , and where:


γ i = The heteroscedasticity parameter for measured variable z(i)
wj
= The weight of experiment j

Note: When the heteroscedasticity is not fixed, the Automation


Method AddSSMeasurepoint resets the heteroscedasticity
parameter to 1.

11 Estimation 331
12 Using the Simulation
Access eXtensions

The Simulation Access eXtensions (SAX) enable you to control a simulation


while it is running, and to access solution data using a programmatic
interface. You can use Simulation Access eXtensions in all run modes for a
variety of applications, for example, for operator training or online
optimization.
To use SAX, you must create a DLL containing a function written in C or C++
with a defined prototype. You register the DLL and function names in the
Simulation Access eXtensions dialog box. The function will then be called
when specified events occur during a run, for example, at the start of a run,
or after a step in a dynamic run. The Simulation Access eXtensions dialog box
also enables you to control which events are used, as well as list the variables
which are passed as arguments to your function.
Utility functions are also supplied, to enable you to manipulate or retrieve
data for these variables within your function.
To use Simulation Access eXtensions, you need to:
1 Write a function for a DLL that will be loaded at run time.
2 Open a simulation.
3 Optionally add variables to the list of input and output variables that are
operated on by the function. Pointers to these variables will be passed to
your function.
4 Specify the name of the DLL and the function to be called when a specified
event occurs during simulation.
5 Make sure that Simulation Access eXtensions are switched on.
6 Run the simulation.

While the simulation is running, your function will be called when the specified
events take place. This enables you to modify or get variable values, or add
control to the simulation. A number of access functions are available for use
within your function.

Caution: Make sure you do not change key variables with SAX
while you are performing an estimation, homotopy, or
optimization run.

12 Using the Simulation Access eXtensions 332


Writing a DLL Function for the
Simulation Access eXtension
Your Simulation Access eXtensions DLL should contain a function of the
following form:
DLL_C_AS_C(int) SAXFunctionName (SAX_EventToken Event,
const double Time, const int NoInputs, const
SAX_ExternalId *InVariableList, const int NoOutputs,
const SAX_ExternalId *OutVariableList, void
*pSimulationManager)

SAXFunctionName The name you give to the function


const Token giving the type of event which caused
SAX_EventToken this function to be called
Event
const double Time The current simulation time
const int NoInputs The number of variables set up as input
variables
const Array of SAX_ExternalID variable identifiers,
SAX_ExternalID one for each variable set up as an input. The
*InVariableList array length is NoInputs. You can use variables
from the list in variable accessing functions.
const int NoOutputs The number of variables set up as output
variables
const Array of SAX_ExternalID variable identifiers,
SAX_ExternalID one for each variable set up as an output. The
*OutVariableList array length is NoOutputs. You can use
variables from the list in variable accessing
functions.
void *pSimulationMa Pointer to the Simulation Manager object to be
nager used in setting up events

DLL_C_AS_C(int) The return value type is int. The macro


DLL_C_AS_C ensures the function is exported
from the DLL and has the correct calling
convention.

Tips:
• Ensure that the file sax_support.h is included in your function to give you
access to the enumeration values. Include this file in your code as follows:
#include "sax_support.h"
• Aspen Custom Modeler users can use an example makefile called
MakePhconSax as a template for linking DLLs. If you have installed in the
default location, this file can be found in:
C:\Program Files\AspenTech\Aspen Custom Modeler 12.1\Examples\Sax\

Using Variable Accessing Functions


Variable accessing functions can be used to assign or inquire an attribute
value for the variable, for example:

12 Using the Simulation Access eXtensions 333


SAX_InquireRealAttribute(OutVariableList[i], SAX_VAR_VALUE,
&doublevalue);
This call will get the value of the ith variable in the output variable list. This
assumes that the variable is of type double precision. You can inquire the
type using the following call:
SAX_InquireIntAttribute(OutVariableList[i], SAX_VAR_TYPE,
&intvalue);
The intvalue is an enumeration of the variable type (SAX_INT, SAX_DBL or
SAX_STR). You can then use this to select the correct function to assign or
inquire the variable value.
If you want to get at a variable which is not in either list, you can get the
variable identifier from the variable path, for example:
SAX_GetVariable("B1.TEMPERATURE",id);

Using Return Codes


You can use the return code from your function to control the simulation. Set
the return code to one of the values listed in this section. This value will
normally be SAX_CONTINUE. The effect of these codes depends on the run
mode.

Using Return Codes on Steady-State and Initialization Runs


The return codes have the following effects:

Return Code Result


SAX_CONTINUE A single run takes place

SAX_RUN_AGAIN† Another steady-state or initialization run will


be carried out
SAX_RUN_COMPLETE No more events are generated
SAX_ABORT_RUN The current solution is aborted and the run is
terminated.

Returned from the SAX_AFTER_SS_RUN or
SAX_AFTER_INI_RUN events.

Notes:
• When the SAX_ERROR_EVENT is triggered you can return
either of the following:
− SAX_CONTINUE, which causes the run to terminate.
− SAX_RUN_AGAIN, which repeats the run.
• Use the SAX_WAITING return code when your function is
waiting for interactions with external programs or user input.
Ensure your function returns this code rather than waiting for
the interaction or input operation to complete. Your function
will be called again with the same event code when you can
check for completion.

12 Using the Simulation Access eXtensions 334


Using Return Codes for Dynamic Runs
The return codes have the following effects:

Return Code Result


SAX_CONTINUE The dynamic run keeps going
SAX_RUN_COMPLETE Causes the run to pause
SAX_REINITIALIZE Forces a reinitialization before the next
dynamic step. (for the Gear solver only)
SAX_ABORT_RUN The current run is terminated

Notes:
• When the SAX_ERROR_EVENT is triggered you can return
either of the following:
− SAX_CONTINUE, which causes the run to terminate.
− SAX_RUN_AGAIN, which repeats the step.
• Use the SAX_WAITING return code when your function is
waiting for interactions with external programs or user input.
Ensure your function returns this code rather than waiting for
the interaction or input operation to complete. Your function
will be called again with the same event code when you can
check for completion.

Events in Simulation Access


eXtensions
When a particular event occurs in the simulation, your SAX function will be
called if you have requested this. The type of event that occurs depends on
the run mode.

Events in All Run Modes


The following events occur in all run modes. Note that these events cannot be
controlled from the Simulation Access eXtensions dialog box.

Event Occurs
SAX_START_OF_SIMULATION When you open an existing simulation
or start a new one
SAX_END_OF_SIMULATION When you exit the application or
unload a loaded simulation
SAX_ERROR_EVENT On any solution failure. This event
cannot be switched off.

Events in Steady-State Runs


The following events occur in steady-state runs.

Event Occurs

12 Using the Simulation Access eXtensions 335


SAX_NEW_RUN At the start of a new run, that is, each
time the Run button is clicked. Note
that this event cannot be controlled
from the Simulation Access eXtensions
dialog box.
SAX_BEFORE_SS_RUN Before the run and when the Before
Run check box is selected in the
Simulation Access eXtensions dialog
box
SAX_AFTER_SS_RUN On successful completion of the run
and when the After Run check box is
selected in the Simulation Access
eXtensions dialog box

Events in Initialization Runs


The following events occur in initialization runs.
Event Occurs
SAX_NEW_RUN At the start of a new run, that is, each time
the Run button is clicked. Note that this event
cannot be controlled from the Simulation
Access eXtensions dialog box.
SAX_BEFORE_INI_RUN Before the run and when the Before Run check
box is selected in the Simulation Access
eXtensions dialog box
SAX_AFTER_INI_RUN On successful completion of the run and when
the After Run check box is selected in the
Simulation Access eXtensions dialog box

Events in Dynamic Runs


The following events occur in dynamic runs:

Event Occurs
SAX_NEW_RUN At the start of a new run, that is, when
the Run button is clicked, having either
just changed run mode to dynamic or just
loaded a simulation with dynamic run
mode as the default. Note that this event
cannot be controlled from the Simulation
Access eXtensions dialog box.
Note: Rewind, Restart and Reset do NOT
cause this event. Having started a
dynamic run, you can only cause this
event again by triggering it for a different
run mode or by editing the simulation.
Simply changing the run mode and back
again is not sufficient.
SAX_BEFORE_DYN_STEP Before or after an integration step and
SAX_AFTER_DYN_STEP when the Before Step or After Step check
box is selected in the Simulation Access
eXtensions dialog box. This step is
controlled by the communication interval
set in the Run Options dialog box. You can
also request these events using the
SAX_ScheduleTimeEvent function.
SAX_BEFORE_INI_STEP Before and after the initialization at time
and SAX_AFTER_INI_STEP 0, and when the Before Initialization or
After Initialization check box is selected in

12 Using the Simulation Access eXtensions 336


the Simulation Access eXtensions dialog
box. For dynamic solvers that do a
reinitialization (currently Gear only) these
events will also happen on reinitialization.
You can also request these events using
the SAX_ScheduleTimeEvent function.

The full sequence of events for a dynamic run is:


1 SAX_NEW_RUN
2 SAX_BEFORE_INI_STEP
3 Dynamic initialization carried out.
4 SAX_AFTER_INI_STEP
5 SAX_BEFORE_DYN_STEP
6 Integrate first step.
7 SAX_AFTER_DYN_STEP

If you require events to occur at times other than the step controlled by the
communication interval, you can request a timed event, for example:
SAX_ScheduleTimeEvent(pSimulationManager, 0, 5.67)
This causes the SAX_AFTER_DYN_STEP and SAX_BEFORE_DYN_STEP events
to occur at the time requested if the given time is after the current time. If
not, the request is ignored.

Controlling the Simulation


Access eXtensions
To open the Simulation Access eXtensions dialog box:
• From the Tools menu, click Simulation Access eXtensions.
This dialog box enables you to specify the following information:
• Input and output variables that will be provided to your interface function.
• The name of the DLL and function in the DLL to be called.
• The simulation events on which the function will be called.

Specifying the Simulation Access


eXtensions Input and Output Variables
To specify the input and output variables that are to be operated on by the
Simulation Access eXtensions function:
1 From the Tools menu, click Simulation Access eXtensions.
2 To add variable names to the Input Variables and Output Variables list
boxes, click the relevant tab and then do one of the following:
− Type a variable name in the text box at the bottom of the dialog box
and then click the Add button.
− Drag and drop variable names from forms.

12 Using the Simulation Access eXtensions 337


− Drag and drop variable names from Variable Find.

Notes:

• You can also use pattern matching to add variables to the


list.

• You can rename variables by double-clicking the variable


name in the Tag column.

• Tag names do not have to be unique within the


simulation.

Specifying the DLL and Function Name


for the Simulation Access eXtensions
After the DLL has been generated, and you have specified the variables, you
can specify the DLL and the name of the function to be called. To do this:
1 In the Simulation Access eXtensions dialog box, click the Procedure tab.
2 In the Function name box, type the name of the function that is to be
called.
3 In the Library name box, type the stub name of the DLL which contains
your function.
4 In the Events area, select the event(s) which will trigger the function.
5 Make sure the Enable Access eXtensions check box is selected.
6 When you have finished setting up the Simulation Access eXtensions, click
Close.

Additional Simulation Access


eXtensions Functions
This section lists the functions you can use to add functionality to the
Simulation Access eXtensions. Most of these functions return an ACMStatus
value to show success or failure of the function. Use the code
SAX_ERR_Success, or SAX_ERR_Failure when testing the returned value.

Displaying Diagnostic Messages


The following function displays diagnostic messages. For more information,
see the Library Reference, Chapter 3.
ACM_Print (....)

12 Using the Simulation Access eXtensions 338


Accessing Options Parameters
The following function enables your routines to access the values of Options
parameters. For more information, see the Library Reference.
ACM_Rqst(....)

Setting the Value of an Attribute


The following function sets the value of a real attribute of a variable:
ACMStatus SAX_AssignRealAttribute (const SAX_ExternalId
id, const SAX_Attribute_Token token, const double
Attrib_Value)

const SAX_ExternalId id Variable identifier


const SAX_Attribute_Token Integer token identifying the attribute
token to which the value will be assigned. For
information on attribute tokens, see
Simulation Access eXtensions Attribute
Tokens.
const double Attrib_Value Double value to be assigned

Note: If you change a variable bound such that the current value
is outside the new bound, the current value will be reset to the
bound. Also any attempt to invert the bounds (that is, if the
upper bound is lower than the lower bound), will be rejected.

The following function sets the value of an attribute from an integer value:
ACMStatus SAX_AssignIntAttribute (const SAX_ExternalId id,
const SAX_Attribute_Token token, const int Attrib_Value)

const SAX_ExternalId id Variable identifier


const Integer token identifying the attribute to
SAX_Attribute_Token which the value will be assigned. For
token information on attribute tokens, see
Simulation Access eXtensions Attribute
Tokens.
const int Attrib_Value Integer value to be assigned

The following function sets the value of an attribute from a character string:
ACMStatus SAX_AssignStringAttribute (const SAX_ExternalId
id, const SAX_Attribute_Token token, const char
*Attrib_Value)

const SAX_ExternalId id Variable identifier


const Integer token identifying the attribute
SAX_Attribute_Token to which the value will be assigned.
token For information on attribute tokens,
see Simulation Access eXtensions
Attribute Tokens.
const char* attrib_value Character value to be assigned

12 Using the Simulation Access eXtensions 339


Querying the Value of an Attribute
The following function queries the value of a variable's attribute and returns
its value as a real.
ACMStatus SAX_InquireRealAttribute(const SAX_ExternalId
id,const SAX_Attribute_Token token , double *Attrib_Value)

const SAX_ExternalId Variable identifier


id
const Integer token identifying the attribute to
Attribute_Token which the value will be assigned. For
token information on attribute tokens, see
Simulation Access eXtensions Attribute
Tokens.
double *Attrib_Value Double value returned

The following function queries the value of a variable's attribute and returns
its value as an integer:
ACMStatus SAX_InquireIntAttribute(const SAX_ExternalId
id,const SAX_Attribute_Token token , int*Attrib_Value)

const SAX_ExternalId id Variable identifier


const SAX_Attribute_Token token Integer token identifying the
attribute to which the value
will be assigned. For
information on attribute
tokens, see Simulation
Access eXtensions Attribute
Tokens.
int * Attrib_Value Integer value returned

The following function queries the value of a variable's attribute and returns
its value as a string:
ACMStatus SAX_InquireStringAttribute(const SAX_ExternalId
id,const SAX_Attribute_Token token , char **Attrib_Value)

const SAX_ExternalId id Variable identifier


const Atribute_Token token Integer token identifying the
attribute to which the value will be
assigned. For information on
attribute tokens, see Simulation
Access eXtensions Attribute
Tokens.
char ** Attrib_Value Character value returned

Converting a Path Name


The following function converts a full path name to a variable identifier:
ACMStatus SAX_GetVariable(char*const Variable_Name,
SAX_ExternalId *VarId)

char*const Variable_Name Name of the variable to be


located

12 Using the Simulation Access eXtensions 340


SAX_ExternalId *Var_Id Returned variable identifier for
named variable

Note: This function can find only variables or parameters that


are active in the simulation, that is, variables or parameters that
appear in equations, procedure calls, or run-time conditional
expressions.

Scheduling an Event
The following function schedules an event which will cause this function to be
called:
ACMStatus SAX_ScheduleTimeEvent(void *pSimulationManager,
const int EventType, const double Time)

void * p Handle to Simulation Manager


SimulationManager
const int Event Type Type of event to be scheduled. Default is 0,
meaning reporting time is 0.
const double time Time at which event will occur

Simulation Access eXtensions


Attribute Tokens
Use these tokens in functions where variable attribute information is to be set
or received. These tokens are available as symbols from the header file
sax_support.h:

Token Symbol Attribute Type Returned


Description
SAX_VAR_NAME (Read Variable Name string
only)
SAX_VAR_VALUE Variable Value double, int or string
(Use SAX_VAR_TYPE
to find out which)
SAX_VAR_LOWER Variable Lower bound double or int
SAX_VAR_UPPER Variable Upper bound double or int
SAX_VAR_TYPE (Read only) Variable type Integer (one of
SAX_INT, SAX_DBL or
SAX_STR)
SAX_VAR_TAG (Read only) Variable tag String
SAX_VAR_SPEC (Read only) Variable specification Integer (One of
SAX_SPEC_FREE,
SAX_ SPEC_FIXED,
SAX_ SPEC_INITIAL,
SAX_
SPEC_RATEINITIAL) *
SAX_VAR_LLAGR (Read Variable Lagrange Double
only) Lower Bound (not
defined for all
variables)

12 Using the Simulation Access eXtensions 341


SAX_VAR_ULAGR (Read Variable Lagrange Double
only) Upper Bound (not
defined for all
variables)

12 Using the Simulation Access eXtensions 342


13 Using Online Links (OLL)

The Online Links (OLL) facility allows the simulator to access the data
provided by an online data server, using one of the published standard
interfaces. An interface DLL is loaded by the simulator and communicates
with the data server when required.
OLL uses many of the facilities of the Simulation Access eXtensions (SAX), but
is independent of SAX. OLL and SAX can be used simultaneously.
Aspen Engineering Suite™ supports communication with data servers that
conform to the OLE for Process Control (OPC) standard 1.0A, published by the
OPC Foundation, dated September 11, 1997. Detailed information about this
standard can be obtained from the OPC Foundation web site at:
http://www.opcfoundation.org
The Online Links dialog box enables you to specify:
• The OPC data server you wish to connect to.
• How you want to communicate with the OPC data server.
• At what points to communicate with the OPC data server during the
simulation.
• Which data you wish to read from, or write to, the OPC data server.
To use OLL, you need to:
1 Install the data server on a machine accessible to the simulator.
2 Specify the server and its configuration data.
3 Specify the links between the simulator and the data server.
4 Run the simulation.

The OLL interface is affected by the Solver Reporting Level. Messages from
the interface appear in the Simulation Messages window, and changing the
Solver Reporting Level will increase or decrease the number of messages.

Installing the Data Server for


OLL
For the simulator to access the data server, the data server must be
registered on the same machine as the simulator. Usually, this means that
the data server is installed on the same machine as well, but it is possible to

13 Using Online Links (OLL) 343


install a data server on one machine and run it from another. For information
on how to do this, see the documentation on the data server.
If you have more than one data server and you wish to be able to browse for
them from the OLL dialog, or if your data server(s) support an interface that
allows for browsing of its data tags, you will need to ensure that your data
server(s) are correctly registered on the same machine as the simulation
client. If the simulation client and simulation server are running on different
machines, this means that the data server(s) will be registered on more than
one machine.

Specifying the Data Server


Configuration for OLL
To specify the data server configuration:
1 From the Tools menu, click Online Links.
The Online Links dialog box is displayed, showing the Configuration tab.
All the fields on this tab are set to their defaults, and the Server Name
field is blank.
2 In the Server Name box, type or click Browse to select the name of the
data server you want to use.
Note that if one or more data servers are registered on your computer,
the browser presents a list of available data servers that support the
requested protocol. To select a server, click the ID field of the required
server and then click OK.
3 For IO Timing, select one of the options:

Option Description
Synchronous The OLL interface will wait for IO operations to
complete
Asynchronous A call-back is specified

Note: Data servers must support either Synchronous or


Asynchronous operation, but need not support both. You cannot
use both options simultaneously.

4 Select whether the Reading Mode should be CACHED or DEVICE. Your


choice depends upon your data server.

Note: The OPC standard expects that synchronous reads should


be CACHED, while asynchronous reads should be DEVICE. Some
data servers may not support all four possible combinations. If
you specify a Timing method and Reading Mode combination that
is not supported by your server, OLL will fail to exchange data. If
you use Asynchronous operation, you may need to perform reads
before a dynamic step rather than after, particularly if the time

13 Using Online Links (OLL) 344


taken by the step is of the same order as the time taken for the
data server to respond to the request. Make sure you select the
combination of IO timing and Reading mode that works best with
your simulation.

5 In the Bounds Handling box, you can change the action the OLL interface
must take when the value supplied by the data server lies outside the
bounds of the simulation variable specified for the link. The values are:

Value Description
CLIP Default value. The value is clipped to the nearest
variable bound. A warning message is written to
the Simulation Messages window.
USELAST The value is replaced by the last valid value for the
link supplied by the interface. A warning message
is written to the Simulation Messages window.
PAUSE The run is paused and a message appears
informing you of this.

6 In the Quality Handling box, you can change the action the OLL interface
must take when the QUALITY of a data item is anything other than GOOD.
The values are:

Value Description
USELAST Default value. The value is replaced by the last
valid value for the link supplied by the interface. A
warning message is written to the Simulation
Messages window.
OVERRIDE The value is replaced by the OVERRIDE value
specified for the link. A warning message is written
to the Simulation Messages window.
PAUSE The run is paused and a dialog is issued to that
effect.

Note: The OLL value field of a data item that does not have
GOOD quality is displayed in red. GOOD data is displayed in
black.

7 In the Update Period box, you can specify a period in milliseconds


between updates of the values read from the data server. The default
period of 1000ms (1 per second) is suitable for most small to medium
sized problems; for larger simulations, you may need to increase the
value.
The data server may adjust the value you specify to the nearest available
value. For example, if you specify an update period of 100ms for an item
connected to a sensor that has a response time of 110 ms, the data
server may change the specified value to 110 ms (this change will not be
reflected on the configuration pane). The update period is not meaningful
to some servers when reading synchronously. When reading
asynchronously, the data will continue to be sent from the data server
even when the simulation run is paused. This will be reflected in the OLL
value fields of inputs being continuously updated.

13 Using Online Links (OLL) 345


Note: Do not to specify an update period that is too short,
otherwise the simulator may spend more time handling the
updates than in solving your simulation. The default period of
1000ms (1 per second) is suitable for most small to medium
sized problems; for larger simulations, you may need to increase
the value.

8 In the Events list, you can change when to interact with the data server.
To enable interaction at a given point, select the appropriate box: the
boxes headed In are for the interaction points for input variables, and the
boxes headed Out are for interaction points for the output variables. To
disable an interaction, clear the box.
The events specified by default are:

To At these events And these events


Read inputs Before steady-state After dynamic initialization
and initialization runs steps and dynamic steps
Write outputs After steady-state After dynamic initialization
or initialization runs steps or dynamic steps

Note: OLL does not distinguish between the first initialization


step of a dynamic run, and any subsequent re-initializations
triggered by discontinuities. Re-initializations only occur when
using a locating integrator, such as GEAR.

9 In the Enable box, you can change OLL interactions globally:

Option Description
OFF Default value. No interactions will take place (and no
attempt will be made to load the OLL interface or to
communicate with the data server when a new run
starts).
READONLY Values will be read from the data server to the input
variables. Values will not be sent to the OLL data
server from the output variables.
ON Reading and writing are both enabled.

Specifying the Links between


the Simulator and the OLL Data
Server
In the Online Links dialog box, you can specify the Input links for which the
OLL data server will send values to the simulator, and the Output links for
which the data from the simulator will be written to the OLL data server:

13 Using Online Links (OLL) 346


When specifying these variables, remember the following rules:
• The variables specified on the Input tab must all be Fixed variables, and
should not normally be manipulated by any other means (tasks, scripts,
SAX, etc). It is not necessary for Output variables to be Fixed.
• Each Simulation Variable/OLL tag combination must appear only once on a
tab. The combination may be repeated on the other tab.
• Each destination (that is, the Simulation Variable on the input tab, or the
OLL tag on the output tab) must appear only once on a tab.

Notes:

• These rules are not enforced by the interface, as there are


situations when they may safely be ignored.

• The table can be sorted by clicking on one of the column


headings.

• The scroll bar at the foot of the tabs does not affect the
first two columns (the Simulation Variable name and
Simulation Value).

To specify the links on the Input and Output Variables tabs:


1 From the Tools menu, click Online Links and then click the Input Variables
tab or the Output Variables tab.
2 Make sure that the Simulation Variable field contains the name of the
simulation variable involved in the link, and that it is valid. If it is valid, a
green check mark is displayed to the right of the row, but if it is not valid
(for example, if it is in a block that has been deleted, a red cross is
displayed.
For more information, see Adding New Links for OLL and Changing the
Simulation Variable in an OLL Link.
3 In the OLL Tag box, type or select the name of the data item in the OLL
data server.

Note: The name must conform to the syntax expected by the


data server: remember that some data servers are case-
sensitive. The tag is not validated until the data server is
connected to the simulation server, at the start of the first run.

4 In the Mode box, select whether links are enabled or disabled:

Value Description
Auto The link operates normally.
Manual The simulation value is replaced by the Override
value.

5 In the Override Value box, specify the value to be used for the simulation
value when the link’s mode is Manual, or when the Quality Handling is set

13 Using Online Links (OLL) 347


to OVERRIDE and the quality of an input item is not GOOD. The value is
displayed in simulation units.
6 In the Bias box, you can specify an offset to be added to a written value
(input), or subtracted from a read value (input) during the exchange of
data. Gain is applied before bias on a write, and after on a read, so that:
OLL value = (Simulation value) * Gain + Bias
7 In the Gain box, you can specify a factor that is used to multiply a written
value or divide a read value during the exchange of data. Gain is applied
before Bias on a write, and after on a read, so that:
OLL value = (Simulation value) * Gain + Bias
8 For output variables only, you can use the Noise Std Dev box to simulate
the effect of measurement noise. When non-zero, it is the standard
deviation of a random number with a Gaussian distribution about zero,
which is added to the value before being written to the data server. Noise
is applied during dynamic runs only, after any bias and gain.
9 In the Change Tolerance box, you can change the absolute tolerance used
to minimize traffic between the simulator and the data server. If the
simulation value differs from the previous simulation value by less than
the tolerance, the data is not exchanged. The change tolerance test is
only applied during dynamic runs. The default Change Tolerance value is
1E-5.
10 In the Conversion Units box, specify the units of measurement of the
values in the data server.
For example, the data server may return the value from a temperature
sensor in degrees Celsius, and this value will need conversion after
reading or before writing. The list of units of measurement provided is the
same as the list for the simulation variable in the link, and thus this field is
only useful if the simulation variable is of the appropriate type. If the
simulation variable does not have units of measurement, you cannot set
the Conversion Units field.
If the units of the data server are arbitrary, or are not available in the list,
the you can use the Bias and Gain fields to do the necessary conversions.

Adding New Links for OLL


To add Input links (for which the OLL data server will send values to the
simulator), and the Output links (for which the data from the simulator will be
written to the OLL data server):
1 From the Tools menu, click Online Links and then click the Input Variables
tab or the Output Variables tab.
2 In the Variable box at the bottom of the tab, type the full name of a
simulation variable, and the click Add.
A new row is created in the table, with a blank tag name. It is marked by
a red cross to the left of the row until a tag name has been entered and
validated.
– or –

13 Using Online Links (OLL) 348


Add links by selecting a simulation variable from a form or from Variable
Find, and drag them to the appropriate tab.
3 In the OLL Tag field, either type the full tag name, or click the Browse for
Tags button to locate the tag.
When the row has a valid simulation variable and a valid OLL tag, it will be
marked by a green check mark on the far left of the row.

Note: The tags are not validated until the data server is
connected to the simulation server, at the start of the first run.

Removing OLL Links


To remove an OLL link:
1 From the Tools menu, click Online Links and then click the Input Variables
tab or the Output Variables tab.
2 In the Variable box at the bottom of the tab, click the link and then click
Remove.
The table row is deleted.

Changing the Simulation Variable in an


OLL Link
To change the simulation variable in an OLL link:
1 From the Tools menu, click Online Links and then click the Input Variables
tab or the Output Variables tab.
2 In the Variable box at the bottom of the tab, select the appropriate table
row, and then click the Edit Variable button.
You can then edit the name of the variable. This name is validated when
press ENTER.

Browsing for OLL Tags


If your data server supports browsing for tags, and is accessible from your
simulation client machine, you can browse the data server for tags. To do
this:
1 From the Tools menu, click Online Links and then click the Input Variables
tab or the Output Variables tab.
2 Next to the OLL Tag box, click the Browse for Tags button.
The Tag Browser is displayed.
The tag browser has two panes: the left one is the OLL data for the
currently visible tag, and the right one is the list of tags available in the
data server.
3 To connect a data server tag to a given simulation variable, click the
simulation variable in the left pane, then click the required tag in the right
pane, and then click the central arrow button.

13 Using Online Links (OLL) 349


When the browser is closed, the links you have specified will be
established.

13 Using Online Links (OLL) 350


14 Using External Solvers

Aspen Custom Modeler® allows external, non-linear algebraic equation


solvers to be plugged in and used in the solution of simulations. There are
two types:
• Non-linear algebraic (NLA) equation solvers.
• Non-linear programming (NLP) optimization solvers.
To Aspen Custom Modeler, an external solver is a software component that
implements a number of defined interfaces. These interfaces allow Aspen
Custom Modeler to load the solver, set options and to drive the solution. To
the external solver, Aspen Custom Modeler presents an interface that allows
access to the system of equations and/or optimization problem to be solved.
The set of interfaces that allow Aspen Custom Modeler to use a solver
component are called the AspenTech Open Solver (AOS) interfaces.
For further details of these interfaces, refer to the Aspen Open Solvers User’s
Guide, or the Aspen Open Solvers on-line help.

14 Using External Solvers 351


15 Exporting Flowsheets to
Aspen Plus

Flowsheets written in Aspen Modeler products using the Modeling Language


can be used as custom blocks in Aspen Plus® simulations. This means you
can:
• Describe proprietary reactors or units for which there is no Aspen Plus
model.
• Customize Aspen Dynamics™ models to provide variations on existing
Aspen Plus models.
Export a flowsheet and use it in Aspen Plus by:
1 Checking you have the necessary software.
2 In your Aspen Modeler product, preparing a flowsheet for export.
3 Generating a dynamic link library (DLL) and an Aspen Plus User Model
Library (.apm) file by exporting the flowsheet.
4 In Aspen Plus, reference the new library and select the new unit operation
from the Aspen Plus Model Library. You can now use the unit like any
other Aspen Plus unit operation.

Software and Hardware


Requirements
To export a flowsheet from an Aspen Modeler product:
• You must have a C++ compiler—Microsoft® Visual C++ Studio Net is
recommended for exporting flowsheets on machines running Microsoft
Windows. Your C++ compiler must be configured so that it can be used
from the command line.

Note: The C++ compiler is only needed to create the DLL from
the Aspen Modeler flowsheet. A DLL can be used in Aspen Plus
without having a C++ compiler.

An Aspen Modeler flowsheet running within Aspen Plus requires an Aspen


Custom Modeler licence.

15 Exporting Flowsheets to Aspen Plus 352


16 Preparing an Aspen
Modeler Flowsheet for
Export

Any Aspen Modeler flowsheet can be exported but a flowsheet must meet
some basic requirements if it is to be used successfully in Aspen Plus®. This
is because Aspen Plus blocks use certain conventions, for example, they
always calculate outputs from inputs, and they must have ports which are
compatible with Aspen Plus streams.

Note: It is currently only possible to connect exported Aspen


Modeler flowsheets to Aspen Plus streams which have a single
mixed sub-stream. You cannot connect exported Aspen Modeler
flowsheets to polymer streams, streams containing solids or
streams with multiple sub-streams.

This chapter contains information on the following topics:


• Preparing an Aspen Modeler flowsheet for export.
• Exporting the flowsheet.

Preparing a Flowsheet for


Export
In order to use an Aspen Modeler flowsheet as a custom block in Aspen
Plus®, you should ensure that:
• The flowsheet is square.
• The flowsheet has a rating specification.
• The flowsheet contains ports for connecting to Aspen Plus material
streams.
• The flowsheet solves in steady-state mode.

Notes:
Note the following restrictions when preparing flowsheets for export:

16 Preparing an Aspen Modeler Flowsheet for Export 353


• If your Aspen Modeler flowsheet uses tearing to influence the order of
equations in a decomposition, it may not solve in Aspen Plus. Aspen Plus
solvers do not use decomposition to divide the equations into smaller
groups of related equations. This means that Aspen Plus solves the
equations in the order presented, not in the order produced by the Aspen
Modeler decomposition algorithm.
• Do not use the ChangesInputs procedure qualifier in a flowsheet that you
want to export. This qualifier allows a procedure equation to change the
value of an input variable during solution. The Aspen Plus solvers do not
support this functionality.

Making the Flowsheet Square


Any Aspen Modeler flowsheet that you want to export to Aspen Plus® must
be square.
This is because the solvers used within Aspen Plus can only work with a
system of equations that is square. If an Aspen Modeler flowsheet that is not
square is exported, then Aspen Plus will not be able to load it during a
simulation.
It is possible to change the specification of variables in the exported flowsheet
from Aspen Plus. For more information on this, see Exporting Flowsheets to
Aspen Plus.

Ensuring the Flowsheet has a Rating


Specification
Any Aspen Modeler flowsheet that you want to export to Aspen Plus® must
have a rating specification.
This means that input (or feed) variables are all fixed and output (or product)
variables are all free. This is necessary because an Aspen Plus block uses
input stream values to calculate output stream values.
It is possible to export a flowsheet which does not have a rating specification
and it is possible to use it in Aspen Plus but this is not recommended as
Aspen Plus will not give you a reliable solution.

Using Aspen Dynamics Pressure-Driven Flowsheets


Aspen Dynamics™ pressure-driven flowsheets do not have a rating
specification. This means that before you can export and use them as Aspen
Plus blocks, you must first modify their specification to ensure that all inlet
stream variables are fixed.
Aspen Dynamics™ flow-driven simulations do have a rating specification so
they can be exported without modifying their specification.

16 Preparing an Aspen Modeler Flowsheet for Export 354


Defining Ports for Connecting to Aspen
Plus Material Streams
To connect an exported flowsheet to Aspen Plus® streams, the flowsheet
must define input and output ports. These ports must contain particular
variables so that, when the flowsheet has been exported and is running in
Aspen Plus:
• Aspen Plus input stream data in SI units can be copied to the input port
variables.
• Aspen Plus output stream data can be copied from the output port
variables in SI units.
Aspen Modeler identifies the ports to export by searching the flowsheet for
unconnected ports containing a parameter called ExportAs. The ExportAs
parameter has two purposes:
• To identify ports for export.
• To describe how the port should be exported.
The value of the ExportAs parameter tells Aspen Modeler how to represent
the port in the code generated during export. Currently, only one value is
supported: “MoleFractionPort”. This value means that the port has the
properties needed to connect to an Aspen Plus material stream. The direction
of the port determines whether Aspen Plus treats the port as an inlet or an
outlet.

MoleFractionPort_SI Definition
The Modeler library contains the definition of a port type called
MoleFractionPort_SI, which Aspen Modeler will export as a port suitable for
connection to Aspen Plus streams:
Port MoleFractionPort_SI
Description: "A port that conforms to the requirements of
a mole fraction port in AspenPlus";
ExportAs as ExportParam("MoleFractionPort");
F as notype (Description:"Molar flow rate");
T as notype (Description:"Temperature");
P as notype (Description:"Pressure");
h as notype (Description:"Molar enthalpy");
V as notype (Description:"Molar volume");
z(componentlist) as notype (Description:"Mole
fractions");
End

Note: All the variables are of type notype. This is because the
values of these variables are in SI units rather than Aspen
Modeler units. Using notype means that Aspen Modeler will not

16 Preparing an Aspen Modeler Flowsheet for Export 355


attempt to convert the values of the variables.

Typically an Aspen Modeler flowsheet will not contain any ports of type
MoleFractionPort_SI; if you export such a flowsheet you will not be able to
use it in Aspen Plus. Exportable ports are added to a flowsheet by adding
blocks that contain ports of type MoleFractionPort_SI.
Every port that is exported can be connected to an Aspen Plus material
stream when the simulation is used as a unit operation in Aspen Plus. The
name of the block that owns the exported port is used as the port name in
Aspen Plus. So a port called WaterFeed.Export in an Aspen Modeler simulation
will be called WaterFeed in Aspen Plus. Similarly, a port called DrawOff.Export
in Aspen Modeler will be called DrawOff in Aspen Plus.

APlusFeed and APlusProduct Definitions


The Modeler.acml library includes models, called APlusFeed and APlusProduct,
that contain ports of type MoleFractionPort_SI. These are the definitions used
for the APlusFeed model type:
Model APlusFeed

Description: "Maps a MoleFractionPort_SI to a


MoleFractionPort";
Export as input MoleFractionPort_SI;
Feed as output MoleFractionPort;
dummy as hidden notype;
// Fix the Export conditions
Export.F: fixed;
Export.T: fixed;
Export.P: fixed;
Export.h: fixed;
Export.V: fixed;
Export.z: fixed;
// Convert inlet values from SI to Metric...
Export.F * 3600.0 = Feed.F;
Export.T - 273.15 = Feed.T;
Export.P * 1e-5 = Feed.P;
Export.h * 1e-9 = Feed.h;
Export.V = Feed.V;
Export.z = Feed.z;
END

16 Preparing an Aspen Modeler Flowsheet for Export 356


Port MoleFractionPort
Description: "Metric equivalent of an AspenPlus mole
fraction port";
F as flow_mol (Description:"Molar flow rate");
z(componentlist) as molefraction (Description:"Mole
fractions", 1.0/size(componentlist));
T as temperature (Description:"Temperature");
P as pressure (Description:"Pressure");
V as vol_mol (Description:"Molar Volume");
h as enth_mol (Description:"Molar enthalpy");
End
An APlusFeed block represents an Aspen Plus stream in a simulation. When a
simulation containing an APlusFeed block runs in Aspen Modeler, the variables
in the port called Export are fixed and should be given values close to those
expected when the simulation runs in Aspen Plus. When the flowsheet is
exported and runs in Aspen Plus, these variables are initialized with values
from the Aspen Plus stream connected to the port.
An APlusProduct block also represents an Aspen Plus stream but it performs
the reverse function. When a simulation containing an APlusProduct block
runs in Aspen Plus, the values of the variables of the port called Export are
copied to the Aspen Plus stream connected to the port.
The variables whose values are copied from Aspen Plus streams or copied to
them have to be in SI units. Variables in an Aspen Modeler simulation must
be in the Aspen Modeler base unit set. The APlusFeed and APlusProduct
models ensure that variable values are appropriately converted; from SI for
inputs, and to SI for outputs.
The rating specification ensures that the equations in the simulation calculate
the stream outputs from the input variables that were initialized from the
Aspen streams connected to the exported input ports.

Ensuring the Flowsheet Solves in


Steady-State Mode
Aspen Modeler flowsheets must solve using the Steady-State run mode.
This is because Aspen Plus® uses steady-state solvers, not the Aspen
Modeler dynamic solvers. The steady-state solvers do not take account of the
relationship between derivative and state variables as the Aspen Modeler
solvers do.
If you have the Steady-State run mode selected when you export the
flowsheet, Aspen Modeler ensures that derivative variables are fixed with a
value of 0.0 and variables with a specification of Initial will be made Free. If
you have any other run mode selected, Aspen Modeler does not modify the
specification of the exported flowsheet. This means that Aspen Plus will solve
the flowsheet as specified in Aspen Modeler, treating variables with a
specification of Initial as Fixed.

16 Preparing an Aspen Modeler Flowsheet for Export 357


Preparing a Flowsheet That
Uses Custom Models
If you want to prepare a flowsheet that uses your own custom models for
export you need to add custom feed and product blocks containing ports that
can be exported.
The process of adding feed and product blocks can be automated using a
script. The Aspen Dynamics library, Dynamics.acml contains a script called
AddExportBlocks that adds feed and product blocks to an Aspen Dynamics
flowsheet automatically. The script also modifies the specification of variables
in material streams and it initializes the values of variables in the added
blocks.

Adding Custom Feed and Product


Blocks
Your flowsheet uses particular port definitions and possibly stream models. To
export such a flowsheet for use in Aspen Plus the flowsheet must contain feed
and product blocks containing ports of type MoleFractionPort_SI. The purpose
of the feed blocks is to translate Aspen Plus stream data, which is in SI units,
in to the stream representation used in your flowsheet and to convert variable
values into Aspen Modeler base units. The purpose of the product blocks is to
translate data from the streams used in your flowsheet to the variables whose
values, in SI units, will be copied back to an Aspen Plus stream.
Blocks (or streams) representing a flow of feed material are connected to
blocks representing unit operations using the built-in Connection stream type
or a custom stream model. To run a flowsheet like this in Aspen Plus, the
Material Feed Model has to be replaced with a model that can be connected to
an Aspen Plus stream. The following is a diagram of the flowsheet.

Aspen Plus Feed Custom Product


Stream block Unit block
exported Operation exported
as a port as a port

Adapting the Example Models


The modeler library contains an example feed block called APlusFeed and an
example product block called APlusProduct. To adapt these models for use
with your flowsheet:
1 Copy the model to the Custom Modeling folder in the Simulation Explorer
window
2 Edit the model and change the type of the Feed port from APlusFeed and
the Product port in APlusProduct to the port type used in your flowsheet.

16 Preparing an Aspen Modeler Flowsheet for Export 358


3 Modify the equations in the model to map variable values to from the port
called Export to the variables in your port type.

After you have developed feed and product models that map variables
between exportable ports of type MoleFractionPort_SI and the variables in
your port type, you can replace the material feed models used in your
flowsheet and add product blocks as required. If you use a stream model to
represent a material feed you can connect the inlet end to your new feed
block.

Preparing an Aspen Dynamics


Flowsheet for Export
If you want to prepare an Aspen Dynamics™ pressure-driven flowsheet, you
must first modify its specification, because it will not have a rating
specification. You do not have to modify the specification of Aspen Dynamics
flow-driven simulations.
Prepare an Aspen Dynamics™ flowsheet for export by:
1 Ensuring that the flowsheet solves in steady-state.
2 Deleting the controllers and control streams added when the flowsheet
was created in Aspen Plus®.
3 Switching the flowsheet to use rigorous Physical Properties calculations.
4 Adding blocks.

Solving an Aspen Dynamics Flowsheet in Steady-State Mode


Most Aspen Dynamics™ flowsheets will solve in steady-state mode. If you
have one that will not converge then the reason is probably that the initial
solution generated from Aspen Plus® is not at steady-state.
In this case, to get a solution in steady-state you should:
1 Perform an Initialization run.
2 Take a few dynamic steps.
3 Switch to steady-state mode.
This will help to make sure that all the derivative variables in the problem
have a value close to 0.

Tip: You can check the values of the derivatives by creating a


table showing all the state variables in the simulation.

Creating a Table Showing All the State Variables


To create a table showing all the state variables:
1 From the Tools menu, click Variable Find.

16 Preparing an Aspen Modeler Flowsheet for Export 359


2 Ensure that the Include Algebraic Variables checkbox is not selected.
3 Click Find.
The resulting list of variables contains all the state variables in the
simulation.
4 Select all the variables in the list, by selecting one entry then pressing
CTRL+A.
5 Click the Table button to create a table in the flowsheet showing the
selected variables.
6 Type a name for the table, for example AllStateVariables, and then click
OK.
The newly generated table appears and a new icon appears in the
Contents pane for Flowsheet, showing the new table.
7 If your table does not have a column showing the derivative values:
− Click with the right mouse button on the table and from the menu that
appears, click Properties.
− Add derivative to the list of columns being displayed.
The table now shows which derivatives are close to 0 and which are
not.

Deleting Controllers and Control Streams


To prepare an Aspen Dynamics™ flowsheet for export, you can delete the
controllers and control streams added when the flowsheet was created in
Aspen Plus®. You do not have to do this, but you may want to do so, either
because the controllers and control streams are not meaningful in a steady-
state run or because you want the exported flowsheet to match an Aspen Plus
block closely. By deleting the controllers you will remove the equations
associated with them and the control streams from the flowsheet.
To delete controllers and control streams easily you can use the
RemoveControl script supplied with the Dynamics.acml library. To do this:
1 In the All Items pane of the Simulation Explorer, expand the Dynamics
library and then select the Scripts folder.
2 In the Contents pane, double-click the RemoveControl script.
The script removes all controllers and control streams from your
flowsheet.

Switching to Rigorous Physical Properties


To prepare your Aspen Dynamics™ flowsheet for export, you should switch
from local physical properties to rigorous physical properties. The reason for
doing this is that the local physical properties are optimized for use with
Aspen Modeler’s dynamic solvers. When a flowsheet is exported and solved
using Aspen Plus® steady-state solvers, local properties calculations may not
work properly. There is no disadvantage in changing to rigorous properties
since local properties calculations only improve the performance of dynamic
runs.
To switch to rigorous properties:
1 In the Simulation Explorer, select Simulation.

16 Preparing an Aspen Modeler Flowsheet for Export 360


2 In the Contents pane, double-click Globals.
3 Change the value of the global parameter Propmode from local to
rigorous.
4 Solve the simulation in steady-state mode.

Adding Feed and Product Blocks


To prepare your Aspen Dynamics™ flowsheet for export, you need to add
blocks to represent the ports to which Aspen Plus® streams can be
connected. Use the script AddExportBlocks to do this automatically. This
script:
• Connects an APlusFeed block to each feed stream in the flowsheet.
• Connects an APlusProduct block to every product stream.
• Copies variable values to the newly-added blocks so that the new
variables have sensible values.

Note: Running the AddExportBlocks script affects the layout of


your flowsheet. After the script has run, you may want to move
the added blocks to restore the layout.

To run the script:


1 In the All Items pane of the Simulation Explorer, expand the Dynamics
library and then select the Scripts folder.
2 In the Contents pane, double-click the AddExportBlocks script.

Tip: After running the script, you may want to tidy your
flowsheet and zoom in.

3 Solve the simulation in steady-state mode to ensure that the new problem
is converged.

Exporting an Aspen Modeler


Flowsheet
When you have prepared a flowsheet for export, follow these steps to export
it:
1 From the Tools menu, click Export Compiled Flowsheet.
The Export Compiled Flowsheet dialog box appears.

16 Preparing an Aspen Modeler Flowsheet for Export 361


2 In the Flowsheet Export Name box, enter the name of the DLL that you
are going to build from the flowsheet or accept the default name (the
name of the simulation). If you have an existing DLL with the same name,
it will be overwritten.
3 If you want to generate code, select the Generate Flowsheet Code
checkbox. You may want to uncheck this box if have already generated a
DLL but want to regenerate the corresponding Aspen Plus User Model
Library.
4 In the Export Directory box, specify the folder where the DLL should be
generated. By default the box shows the working folder. Typically you will
want the DLL to be in the same folder as your Aspen Plus input files.

Note: To be sure that Aspen Plus can load the DLL, you must put
it :

− In the folder where the Aspen Plus engine is running, that


is, the folder where your Aspen Plus .bkp or .inp files are
located.
– or –
− In a folder which is listed in the PATH environment
variable.

16 Preparing an Aspen Modeler Flowsheet for Export 362


5 If you want the compiler to optimize the generated code, select the
Optimize Code checkbox. If this box is selected, the resulting code will run
more quickly and the DLL will be smaller. However, it also means that it
will take longer to compile the file. It is recommended that you only select
Generate Optimized Code when you are satisfied that the exported
flowsheet works properly in Aspen Plus®.
6 If you don’t want the generated code to be compiled and linked during the
export, select the Create Code Files Only checkbox. This option allows the
DLL to be built outside ACM. The advantage of this option is that the
compilation and link process is slightly faster and you can use ACM while it
is happening. If you compile and link during export you will not be able to
use ACM until the link is complete.

Note: If you check this option ACM will generate the necessary
files and the Simulation Messages window will contain
information on command you need to use to build the DLL
outside ACM.

7 Select the Add to Aspen Plus User Model Library checkbox if you want to
create a new library file or add the flowsheet to an existing one. The
library files is used to add the exported flowsheet to the Aspen Plus Model
Library.
8 In the Library File box enter the name of the library in which you want to
put the flowsheet.
9 If you want to export a list of input variables which can be updated in
Aspen Plus, you should first create a table showing the variables. To
export the list, select your table from the drop-down list in the Inputs
Table box.

Note: Do not include variables from the export port of a block of


type APlusFeed on an input form. If you do, the values of these
variables will take precedence over values from the Aspen Plus
inlet stream connected to the port. This may lead to Aspen Plus
reporting a mass imbalance for an upstream block.

10 You can export a list of result variables for display in Aspen Plus by
creating a table showing the variables and then selecting it from the drop-
down list in the Results Table box.

When you have selected the options you want, select OK to proceed with the
export. Now you are ready to use your flowsheet in Aspen Plus.

16 Preparing an Aspen Modeler Flowsheet for Export 363


17 Using an Exported
Flowsheet in Aspen Plus

When you have prepared an Aspen Modeler flowsheet for export, and
exported it, you are ready to use it in Aspen Plus.
This chapter contains information on the following topics:
• Using an exported flowsheet in Aspen Plus®
• Modifying an exported flowsheet
• Licensing of Exported Flowsheets
• Distributing flowsheets to other Aspen Plus users

Using an Aspen Modeler


Flowsheet in Aspen Plus
To use an exported Aspen Modeler flowsheet in Aspen Plus your Aspen Plus
simulation needs to refer to the User Model Library containing the ACM
flowsheet. In Aspen Plus follow these steps:
1 From the Library menu, click References.
2 In the list of available libraries, select Browse and navigate to the
directory where your User Model Library is located, select the file and use
Open to load it into Aspen Plus.
3 Select the ACM Flowsheets tab in the Model Library and select the
flowsheet that you want to use.

You can edit the User Model Library in Aspen Plus by selecting the library
name on the Library menu and then selecting Edit from the pop-up menu.
Use the Aspen Plus help for more information on editing library files.

Modifying an Exported
Flowsheet
You may need to make changes to a flowsheet after you have exported it. For
example, you might want to use a different set of components or you may

17 Using an Exported Flowsheet in Aspen Plus 364


need to change the specification of the variables. Some changes to the
flowsheet can be made within Aspen Plus®, others can only be made in your
Aspen Modeler product.
Within Aspen Plus you can use Aspen Plus input forms for an exported
flowsheet to:
• Change the values of variables.
• Change the bounds on variables.
• Change the specification of variables.
• Change flash calculation options.
You must use your Aspen Modeler product if you want to:
• Change the value of a parameter.
• Change the components used in the exported flowsheet.
• Change the Physical Property options used in the flowsheet.
If you make any of these changes in your Aspen Modeler product you will
need to export the flowsheet again for your changes to affect Aspen Plus
runs.

Licensing of Exported
Flowsheets
Exported flowsheets running in Aspen Plus® may use an Aspen Modeler
license, depending upon your license agreement.

Important Note: If an Aspen Modeler license is required, it is


acquired using the Aspen Plus License Manager settings, not the
settings for your Aspen Modeler product. This means that if
Aspen Plus connects to a particular server to access an Aspen
Plus license, the same server must be able to provide an Aspen
Modeler license when an exported flowsheet is used in an Aspen
Plus simulation.

Distributing the Exported


Flowsheet to Aspen Plus Users
You can distribute an exported flowsheet to other Aspen Plus® users who do
not have an Aspen Modeler product installed by copying to the users'
machines:
• The flowsheet DLL.
• The Aspen Plus User Model Library generated by Aspen Custom Modeler®.
• Any other DLLs on which the flowsheet DLL is dependent.

17 Using an Exported Flowsheet in Aspen Plus 365


Notes:
• If your flowsheet uses procedure equations, the exported DLL
will depend on the DLLs containing their implementation. The
flowsheet DLL will not load correctly in Aspen Plus® if these
DLLs are not available, so you must copy them in addition to
the flowsheet DLL.
• If you export an Aspen Dynamics™ simulation, the exported
DLL will rely on the following DLLs:
− Dynamics.DLL
− Modeler.DLL
− Gpp.DLL

Tip: Dynamics.DLL, Modeler.DLL, and Gpp.DLL can be found in


%SystemDrive%\Program Files\Aspentech\AmSystem 12.1\bin

• If you export an Aspen Custom Modeler simulation that uses


procedure calls defined in the modeler.acml library, the
exported DLL will rely on the following DLLs:
− Modeler.DLL
− Gpp.DLL

Tip: Modeler.DLL, and Gpp.DLL can be found in


%SystemDrive%\Program Files\Aspentech\AmSystem 12.1\bin

• When you generate a DLL in an Aspen Modeler application,


the list of DLLs that it depends on is shown in the Simulation
Messages window. If you want to use the exported DLL on a
machine which does not have an Aspen Modeler application
installed, check the list in the Simulation Messages window to
make sure that the correct DLLs are available.
• If you put the extra DLLs in a directory which is always
searched when the exported DLL is loaded into Aspen Plus,
you will need to copy them to the target machine once only.
Any directory on the path will be searched, as will the
engine\xeq directory of the Aspen Plus installation.

17 Using an Exported Flowsheet in Aspen Plus 366


18 Using Models in Other
Applications

Building Custom Unit Operation


Models for Aspen Plus and
HYSYS
Models written in Aspen Modeler products using the Modeling Language can
be used as Unit Operation Models in Aspen Plus 12.1 and HYSYS 3.2
simulations.
This means you can:
• Describe proprietary reactors or units for which there is no Aspen
Plus/HYSYS model and use the model in either simulator.
• Customize Aspen Dynamics models to provide variations on existing Aspen
Plus models that can be used in either simulator.
• Models exported from Aspen Modeler can be configured in Aspen Plus or
HYSYS; for example, you can change the values of model parameters in
the same way that you can in your Aspen Modeler product. In Aspen Plus
the model will automatically use the component specifications made in the
Aspen Plus simulation. In HYSYS the components used by the model are
defined in a .appdf or a .aprpdf file which is selected as part of the model
configuration.
To export a model and use it in Aspen Plus or HYSYS:
1 Check you have the necessary software.
2 In your Aspen Modeler product, create a model that is compatible with
Aspen Plus streams and specify model properties, for example, tables,
scripts, ports and custom forms, to be included when it is exported. A
model that is compatible with Aspen Plus streams will also be compatible
with HYSYS streams.
3 Export the model to create a Model Package.
4 Install the Model Package on the machine you want to use the model on.
5 In Aspen Plus, reference the catalog of installed Aspen Modeler models
and select the new unit operation from the Aspen Plus Model Library. You

18 Using Models in Other Applications 367


can now use the unit like any other Aspen Plus unit operation. Refer to the
“Exporting Models for use in Aspen Plus” tutorial for detailed instructions.
6 In HYSYS, select the User Ops button from the Object Palette and then
double-click “ACM Op” or drag it to the PFD and drop it to create an
instance. On the Acm Configs page for the block select the installed
model that you want to use. Refer to the “Exporting Models for use in
HYSYS. tutorial for detailed instructions.

Software and Hardware Requirements


To export a model from an Aspen Modeler product:
• You must have a C++ compiler—Microsoft® Visual C++ 6.0 or Microsoft
Visual Studio Net is recommended for exporting models on machines
running Microsoft Windows. Your C++ compiler must be configured so
that it can be used from the command line.

Note: The C++ compiler is only needed to create the DLL when
the model is exported from your Aspen Modeler product. A DLL
can be used in Aspen Plus or HYSYS without having a C++
compiler.

• An Aspen Modeler model running within Aspen Plus or HYSYS will use
either an ACM_MODEL_EXPORT license or a license corresponding to the
Aspen Modeler product used to create the model, if an
ACM_MODEL_EXPORT license is not available.
• The Aspen Modeler client and server must be installed on the same
machine. If the server is installed on a remote machine it will not be
possible to export a model.

Creating a Unit Operation


Model for Aspen Plus and
HYSYS
Any Aspen Modeler Model can be exported but a model must meet some basic
requirements if it is to be used successfully. This is because Unit Operations in
Aspen Plus and HYSYS use certain common conventions., for example an
exported model must use port types that allow the model to be connected to
Aspen Plus and HYSYS streams.

Note: Currently it is only possible to connect exported Aspen


Modeler Unit Operation models to Aspen Plus streams that have
a single mixed sub-stream, either with or without polymer
stream attributes. You cannot connect exported models to
streams containing solids or streams with multiple sub-streams.
Polymer stream types are not supported in HYSYS.

18 Using Models in Other Applications 368


This section contains information on the following topics:
• Creating a model compatible with Aspen Plus streams.
• Exporting the model.
• Installing the model for use with Aspen Plus and HYSYS.

Creating the Model


• To be used in Aspen Plus or HYSYS a model must:
• Use port types that are compatible with the MOLE_FRAC port specification
used in Aspen Plus Equation-Oriented Models.
• For Aspen Plus use, the model must calculate its output streams based on
inlet stream data, parameter values and initial values for other internal
variables.
• Not depend on procedure tearing or decomposition to solve successfully.

Using Port Types Compatible with Aspen Plus


Aspen Plus and HYSYS streams can only be connected to ports on exported
models if the port types used in the model contain particular variables. For
connections to non-polymer streams in either Aspen Plus or HYSYS it is
recommended that you use the one of the following port types:
• MoleFractionPort – which can be found in the Modeler library.
• MaterialPort (or any of the port types derived from it) - which can be
found in the Dynamics library if you have Aspen Dynamics installed.
For connections to polymer streams in Aspen Plus it is recommended that you
use the MaterialPortRP port type or any of its derivatives. MaterialPortRP can
be found in the Aspen Dynamics library.
For a port to be connected to a material stream in Aspen Plus or HYSYS it
must contain at least the following variable definitions:

F as flow_mol(Description:"Molar flow rate");


T as temperature(Description:"Temperature");
P as pressure(Description:"Pressure");
V as vol_mol(Description:"Molar Volume");
h as enth_mol(Description:"Molar enthalpy");
z(componentlist)
as molefraction(Description:"Mole fractions");
A compatible port type can contain extra variables but these must be fixed on
the inlet side and free on the outlet side and no data will be transferred
between the extra variables and connected streams.

Tables
Your model may own tables that you have defined to display particular sets of
variables and parameters. These tables can be included in the exported model
and displayed in both Aspen Plus and HYSYS. By default Aspen Modeler will

18 Using Models in Other Applications 369


include all tables belonging to a model in the exported package. Use the
Model Package Properties dialogs to exclude tables if necessary.
Aspen Plus distinguishes between input forms and results forms whereas
Aspen Modeler does not. Use the Model Package Properties dialogs to specify
whether a form should be considered as an input form or a results form or
both in Aspen Plus.
For models that are going to be exported it is advisable to define tables that
display either variables or parameters but not both together. Both Aspen Plus
and HYSYS distinguish tables that show parameters and tables that show
variables.

Custom Forms
Your model may contain custom forms implemented using .ocx controls. By
default Aspen Modeler will include all the custom forms belonging to a model
in the exported package. Use the Model Package Properties dialogs to exclude
Custom Forms if necessary.
Exported custom forms will be displayed in the Aspen Plus Data Browser for
an instance of an exported Model.

Note: At release 3.2 HYSYS does not support the use of Custom
Forms in exported models.

Not all the automation methods that Aspen Modeler supports are available
once a model is exported. Custom Forms and Visual Basic scripts associated
with a model that is to be exported should only use the automation methods
that are supported by exported models. The relevant methods are listed in
the table below:

Object Methods supported Methods that are not


when using an exported supported for exported
model models
An Instance of Application TypeName
any object ActiveDocument
GetPath
IsKindOf
Name
Parent
Application AppName OutputLogger
FullName
Name
Version
Path
Simulation
processID
ActiveDocument
WorkingFolder
PrintToMessageWindow
Msg

18 Using Models in Other Applications 370


Document Flowsheet Problem
Application OutputLogger
Equations Options
RunMode FullName
Name
Parent
Degrees
SpecState
State
Variables
Results
UOM
Successful
ScriptIsRunning
Run
Reset
Properties
Variable Value IsStateVariable
Units IsHidden
Description Reset
ValidValues TypeName
Name FixedValue
IsAlgebraicVariable FreeValue
IsParameter InitialValue
IsInput
IsOutput
Parent
getPath
IsKindOf
Property
ConvertFromBaseUOM
ConvertToBaseUOM
DefaultUnit
DefaultValue
derivative
spec
ULangrange
LLagrange
ComponentList Components
(supports the OptionsNames
Variable methods)
Option
Structure Resolve Invoke
DisableIncrementalUpdate
EnableIncrementalUpdate
RunIncrementalUpdate
Global
NewStringSet
NewIntegerSet
NewVariableSet
FindMatchingVariables

18 Using Models in Other Applications 371


GetScriptText
GetVariableValues
Port IsInput
(Supports the IsOutput
Structure GetPath
methods)
Name
Parent

If your OCX Custom Forms calls an unsupported method the function being
executed will fail. This will typically result in the form failing to initialize
properly.
We recommend the following techniques should be followed when writing OCX
Custom Forms for use in Aspen Plus and Aspen Modeler applications:
• Use case sensitive comparisons on variable names because variable
names will be uppercase when running n Aspen Plus. For example, in
Visual Basic use Option Compare Text and the “Like” operator when
comparing variable names.
• Do not rely on the double quote (“) character being part of variable names
involving string indices to arrays. The double quotes in variable names
are stripped out in Aspen Plus.
It is possible to debug OCX forms running in Aspen Plus by building a debug
version of the OCX and then attaching a debugging tool (for example
Microsoft Visual Studio 6) to the apwn process when the OCX is running so
that you can trace through the source code.
If your Custom Form uses any of the unsupported methods and you want the
form to run in Aspen Plus you should either create a new ocx that does not
use these methods, or modify the code for the OCX so that it detects when it
is running in Aspen Plus so that it can avoid making calls to unsupported
methods.
You can detect whether your Custom Form is running in Aspen Plus using the
Application.AppName property: For example:

If application.AppName = “Aspen Plus” then


‘ running in Aspen Plus
else
if application.AppName = “Aspen Custom Modeler” then
‘ running in ACM
else
‘ running in an unknown application
end if
end if

18 Using Models in Other Applications 372


Visual Basic Scripts
Your model’s Visual Basic scripts will be exported with a model and can be run
in Aspen Plus and HYSYS. Visual Basic scripts are primarily intended to help
with model initialization.
Visual Basic scripts can be run in two ways:
• Scripts with one of these standard names will be run at specific times
during the process of creating, configuring and solving an instance of a
model.

Script Executes
Name: when:
PreSolve Immediately before solution following all other updates.
The presolve script may be setup to run under specific
circumstances depending on the status of certain read
only block attributes. For example,
If the presolve script must be run only in the Sequential
Modular mode in Aspen Plus then check to see if the
SolutionMode block attribute is set to “Sequential
Modular”.
If the presolve script should be run only if the block has
never been solved then check to see if the SMStatus block
attribute is set to “Not solved”. This is especially
significant if the exported model is used within a recycle
loop in a flowsheet.
The relevant syntax may be found in the presolve script
for the MyPipe model in the tutorial example titled
“Exporting Models for Use in Aspen Plus”. The various
possible values for these parameters in Aspen Plus are:
SolutionMode – “Sequential Modular” or “Equation
Oriented”
SMStatus and EOStatus - "Incomplete", "Not solved",
"Not converged", "Converged" or "Built in"
In Hysys, SolutionMode will be set to “Sequential
Modular” , EOStatus will be set to “Incomplete” and
SMStatus will be set to one of - "Incomplete", "Not
solved", "Not converged", "Converged" depending on the
state of the solution.
In ACM itself the SolutionMode, SMStatus and EOStatus
block parameters will always return an empty string.
PostSolve Immediately after solution and before any other action is
taken.
Init When the block is placed in the flowsheet and whenever a
parameter that changes the number of equations and
variables in the block is updated.

• Visual Basic scripts can be invoked manually from the Equation-Oriented


(EO) command line in Aspen Plus. The EO command is available in the
advanced mode of the Aspen Plus Control Panel when a simulation is
running in EO mode. In HYSYS enter the commands needed to invoke a
script on the Simulation Engine page.
• The syntax for executing a Visual Basic script is:

Invoke <blockname>,<script name>

Where <blockname> is the fully qualified name of the instance of the

18 Using Models in Other Applications 373


model that you want to run the script for, and <script name> is the
name of the script to be run.

Units of Measure
Instances of Aspen Modeler Models will solve in Aspen Modeler’s base units of
measure so that any scaling built-in to the model equations will still be
appropriate when an instance of the model runs in another simulator.
Unit of Measurement conversions between simulator base Units of Measure
and Aspen Modeler base Units are applied automatically as long as:
• Aspen Modeler variables are of a type which has a physical quantity
defined.
• The mapping between the Aspen Modeler physical quantity and the Aspen
Plus Units table is known. This mapping is defined in calls to the
AddPhysicalQuantity method of the UOM Converter object in the Visual
Basic script used to build Aspen Modeler’s UOM tables – typically
AMSystem 12.1\bin\OnNewDocumentScript.vb.
• HYSYS will display model variables and parameters in the Aspen Modeler
base units of measure. This means values can be directly used with the
model equations without any conversions.
If a variable has a physical quantity that cannot be mapped to Aspen Plus
units it will be treated as being dimensionless.

Solver Options
In Aspen Plus an exported Aspen Modeler Model uses the Aspen Modeler
SPARSE non-linear solver by default when running in Sequential Modular
mode (SM), and whichever solver has been selected when running in
Equation-oriented (EO) mode. Alternative solvers can be selected in SM
mode using the Block Options form.
In HYSYS an exported Aspen Modeler Model uses the same Aspen Modeler
SPARSE non-linear solver by default when running in Steady-State mode. In
dynamic mode the model uses the Aspen Modeler Implicit Euler integrator.

Note: Decomposition is not used in either Aspen Plus or HYSYS


so it is recommended that you test the model in your Aspen
Modeler application with decomposition switched off. To switch
decomposition off: select Solver Options from the Aspen Modeler
Run menu, then select the Tolerances tab where you can
uncheck the “Use Group Decomposition” switch.

Setting Model Package Properties.


You can modify the default Model Package properties before exporting a
model by:
• Selecting the model you want to export in the Explorer Window using the
right mouse button.
• Selecting the Model Package Properties menu item on the context menu
and then:

18 Using Models in Other Applications 374


• Following the dialogs shown to specify Package properties.

Note: The Model Package Properties dialogs are not available for
models loaded from Aspen Modeler Library files (*.acml). Models
exported from libraries will use built-in settings for Model
Package Properties. If you want to change the defaults, copy the
model from the Library to the Custom Modeling Folder, and then
follow the steps described above.
The Model Package Properties dialogs are in the form of a Wizard
– you must complete each dialog and end with the Finish button
for your changes to take effect.

Your Model Package Properties settings will be saved along with your Aspen
Modeler simulation.
The Model Package Properties dialogs let you control how the model is
exported:

Model Package Properties – General


1 In the Model Library Category field enter the name of the tab where you
want the Model to appear in the Aspen Plus Model Library .
2 Change the Display Name to be the name you want to use for the model
in the application where you will use the model. Note, for use in Aspen
Plus you must change the display name if your model has the same name
as an existing Aspen Plus model.

Model Package Properties – Ports


1 This dialog shows the settings for your model’s ports. You can control
whether a port is accessible in the exported model, what its prompt
should be and whether a connection is mandatory or optional.
2 Aspen Modeler will determine a type for each of the ports automatically
but you can change it if necessary.

Model Package Properties – Forms


1 This dialog shows your model’s Custom Forms and Tables. You can control
whether a form is included in the Model Package, whether it is an input,
results or input and results form. For tables you can also specify whether
it displays variables or parameters or a mixture of both variables and
parameters.
2 Once exported, a table can only display variables or parameters. If your
table displays both there will be two versions of it in Aspen Plus and
HYSYS: one will display variables, the other will display parameters.
3 Press Finish to apply your changes.

Exporting the Model


Export a model by selecting it with the right mouse button in the Explorer
View and then choosing the Export menu item from pop-up menu.

18 Using Models in Other Applications 375


On the Export dialog change the file type to be Model Package (*.msi) in the
Save As Type box.
Check export options as required:
• Optimize Code – This option will switch on compiler optimization, which
will produce faster code.
• Include Debugging Information – Use this option if you need to be able to
debug the generated code.
• Delete Intermediate Files – Check this if you want ACM to delete the
intermediate files it creates during the export process.
Navigate to the directory where you want ACM to create Unit Operation
Model, use Save to export the model.
When you press Save, Aspen Modeler generates C++ code corresponding to
the Aspen Modeler Language statements that define your model. It also
exports any Tables, Icons, VB Scripts, Procedure code DLLs and Custom Form
OCX files belonging to your model. is complete a DLL is built from the
generated code. A Windows Installer Package, a file with the extension .msi,
is then created containing all the files that need to be installed to use the
model.
When the Windows Installer Package for your model is complete Aspen
Modeler will ask whether you want to install the model. If you say “Yes”,
follow the install instructions to install the model. If you say “No” you can
install the model manually later. Installing the Model Using Windows Explorer
describes the steps required to install the model manually. These are the
steps that should be followed if you want to install the model on a different
machine.

Installing the Model using Windows


Explorer
To install your Unit Operation model manually:
• Use the Windows Explorer to navigate to the directory containing the
Model Package you have exported.
• Select the .msi file created by Aspen Modeler with the right mouse button.
• Select Install from the context menu.
• Follow the installation instructions provided by the Windows Installer.

Note: If you save your Model Package Properties and


subsequently recreate the Model Package after it has been
installed, the Windows Installer will offer Repair and Remove
options rather than an Install option. If the Package has not
already been installed, Windows Installer offers the Install
option. Once the installation process is complete the model is
ready for use in other applications. Note, the Repair option only
re-installs currently existing features in the model. For example,
if you have added a table or a custom form to your model and
re-exported it from ACM, you must use the Remove option and
then install the model.

18 Using Models in Other Applications 376


To install this model on another machine copy the .msi file to that machine
and follow the same steps.

Using an Aspen Modeler Unit


Operation Model in Aspen Plus
or HYSYS
When you have exported and installed an Aspen Modeler Model you are ready
to use it in Aspen Plus or HYSYS.
This section contains information on the following topics:
• Using an Aspen Modeler Model in Aspen Plus or HYSYS.
• Configuring an Exported Model.
• Licensing of Exported Models.
• Distributing Models to other Aspen Plus or HYSYS users.

Using an Aspen Modeler Model in


Aspen Plus
To use an exported Aspen Modeler Model in Aspen Plus your Aspen Plus
simulation must refer to the library of installed Aspen Modeler Models.
In Aspen Plus follow these steps:
1 From the Library menu, click References.
2 In the list of available libraries, check the “ACM Models” entry.
3 Select the “ACM Models” tab in the Model Library and select the Model that
you want to use.

Using an Aspen Modeler Model in


HYSYS
To use an exported Aspen Modeler Model in HYSYS you will need the
following:
1 You must have either Aspen Plus (and Aspen Custom Modeler 12.1)
installed, or the required Aspen core components installed. The core
components can be optionally installed as part of the HYSYS installation
procedure. The core components allow you to use Aspen Modeler models
in HYSYS, but you can not create new Models.
2 You must have a Properties file. If Aspen Plus is installed on the machine
where HYSYS is used, you can use a .appdf file that is generated by Aspen
Plus (see “Generate a Properties Plus .appdf File”). If Aspen Plus is not
installed on the machine, you must generate a .aprpdf file using Aspen
Properties. (Do not use a .appdf file if Aspen Plus is not installed.)

18 Using Models in Other Applications 377


Note: In general, if a model works in Aspen Plus, it should also
work in HYSYS.

Configuring an Aspen Modeler Unit


Operation Block In Aspen Plus
You configure an Aspen Modeler Unit Operation block in the same way as a
built-in Aspen Plus Unit Operation block.
Either:
1 Double-click the block in the flowsheet Window to open the Data Browser
Input forms for the block
or,
2 Open the Data Browser and navigate to the block to open the input forms.

An Aspen Modeler Unit Operation Block has a standard Block Options form,
sheets showing Variables, Ports, Parameters and equations and an entry for
each OCX form.
The variables sheet has a tab for each Aspen Modeler Variable Table exported
with the model. Similarly the Parameter sheet has a tab for each Parameter
Table exported with the model. If your model has an “All Parameters” table it
will display a parameter called “DOF” which can be used to ensure that the
model is square. If your model does not have an “All Parameters” table you
can create one in Aspen Plus by:
• Clicking on the tab for any other table using the right mouse button.
• Selecting Insert from the context menu.
• Entering the name you want to use for the new table.
• Accept all the defaults on the query dialog that is displayed.
The new table will display all the parameters in the model.
Use the Variable sheet tabs to specify initial values for variables, use the
Parameter sheet tabs to configure model parameters. As in Aspen Modeler
products, the set of variables, parameters, equations and ports shown on the
sheets change as you configure the model.
Your Aspen Modeler Unit Operation Block is automatically configured with the
components entered on the global Components form. As you change the
components the block reconfigures itself.
If your unit operation block makes use of more than one component list you
can define component lists in the Component Lists sheet of the Block Options
form. This sheet allows you to define component lists with their own subset of
components and their own Property Options.
Once you have created a component list it appears as an available option for
all the Component List parameters shown on the Parameters sheet.
You can connect streams to Unit Operation blocks in the flowsheet window in
the normal way. If your Unit Operation Block uses multiports connecting a

18 Using Models in Other Applications 378


stream will extend the multiport creating new variables and equations when
the connection is made.

Configuring an Aspen Modeler Unit


Operation Block In HYSYS
Aspen Modeler Unit Operation in HYSYS can be created via the object palette
(press F4) or UnitOps view (press F12).
1 On the object palette, click on the User Ops button then double click on
ACM Op or drag the ACM Op icon onto a PFD window.
2 When you have created a new instance, double click on it in the PFD to
bring up its property view. On the ACM Configs page, click the Select
Property File… button. It allows you to select an .appdf or .aprpdf file.
This file defines the available components and property options. (Note
that all ACM Op instances share the same property file.)
3 The drop-down selection box on the same page shows a list of installed
models. Select the one that you want to use.
4 When you have selected the property file and model, go to the Design,
Connections page. This page shows the ports associated with the model
and it lets you connect one HYSYS material stream to each port.
Connections can also be made via the PFD.

The Design, Properties page allows you to change property options and also
select a subset of components to be used, should you wish to do so.
Because HYSYS and the property file use different components, you need to
match components on the Design, Component Map page. For each component
used by the model, you can select one HYSYS component. The simplest
option is to use the Map Components Based on Molecular Weights button
to map components automatically. If HYSYS is in steady state, your model
now has enough information to solve.

Note: You do not have to map all components (they default to


zero). You can also map multiple model components to the same
HYSYS component in which case they will be added up or equally
divided.

You can change model parameters and variables on the Parameters and
Variable tabs which also show you any defined forms or style sheets. You can
drag and drop values from these pages to a HYSYS spread sheet, and values
can also be imported and exported via the variable navigator.
The Dynamics page allows you to change settings if you wish to use the
model in HYSYS Dynamics. You can use a steady state solution of your model
if your model does not have dynamic behavior or if you desired a steady state
solution. For dynamics mode you need to set ACM Specs as well as PF Specs.
On the ACM Specs page, specify which variables should be fixed when the
ACM model is being solved. For a typical model you can fix all the inlet port
variables and free all the outlet port variables. On the PF Specs page you
typically want to select one variable for each HYSYS stream. Do not select a

18 Using Models in Other Applications 379


variable if it corresponds to a stream variable that is also specified in the
stream.
The Simulation Engine page allows you to enter OOMF script commands. This
can be used for troubleshooting or changing advanced options.

Licensing Exported Models Running in


Aspen Plus
Exported Models running in Aspen Plus may use an Aspen Modeler license,
depending upon your license agreement.

Important Note: If an Aspen Modeler license is required, it is


acquired using the Aspen Plus License Manager settings, not the
settings for your Aspen Modeler product. This means that if
Aspen Plus connects to a particular server to access an Aspen
Plus license, the same server must be able to provide an Aspen
Modeler license when an exported Model is used in an Aspen Plus
simulation.

Licensing Exported Models Running in


HYSYS
Exported Models running in HYSYS require one license on the HYSYS side
(named “HYSYS_ACMOp”). If you use Aspen Plus and Aspen Custom Modeler,
those applications also require separate licenses. You do not need a license
for the Aspen core components.

Distributing an Exported Model To


Aspen Plus Users
You can distribute an exported model to other Aspen Plus users who do not
have an Aspen Modeler product installed by installing the Model Package
created by Aspen Modeler on to the users' machines.

Distributing an Exported Model To


HYSYS Users
You can distribute an exported model to other HYSYS users who do not have
the Aspen Plus or Aspen Modeler products installed by installing the Model
Package created by Aspen Modeler on to the users' machines. If these
products are not installed, then you will need to install the Aspen core
components as part of the HYSYS installation. In this case also be sure to use
a .aprpdf properties file and not a .appdf file created by Aspen Plus.

18 Using Models in Other Applications 380


Using the MyPipe Model in HYSYS
To use this model in HYSYS:
1 Start HYSYS. Click the New Case button. In the basis environment, click
the View button to view the component list, then enter ‘Water’ to add it
to the list.
Switch back to the Simulation Basis Manager window and on the Fluid
Pkgs tab, click Add. Next select a property package from the list (e.g.
ASME Steam). Click the Enter Simulation Environment button.
2 Create a new stream (by double clicking the Material Stream icon on the
object palette; this can be opened by pressing F4; and name it S1. In the
stream view, specify 50 C, 1 bar and a volume flow of 1 m3 per hour. Set
the stream composition to be 100% water. (These conditions should be
the same as in the MyPipe case in Aspen Plus, although that is not
required.)
You can alternatively open almost any case that has water as a
component.
3 On the object palette, click the User Ops icon, then double-click on
ACMOp icon.
A new instance is created and its view comes up.
4 On the ‘ACM Configs’ page (which should be open), click the Select
Property File button. Navigate to the MyPipe.appdf file that was created
when the MyPipe case was saved in Aspen Plus. (The file should be located
under the Aspen Custom Modeler 2004.1\Examples\ModelExport
directory.)
5 Now, from the list of models, select MyPipe.
6 On the Connections page: Next to IN_F, select S1 from the drop down
list. Next to OUT_P, enter S2.
7 Now go to the component map page and click the Map Components
Based on Molecular Weights button. The pipe will now solve.

Explore the other tabs which will show you variable and parameters values.
For example, you can navigate to the Parameters, Input_Par page and change
the pipe roughness.

Note: Further information about this model can be found in the


HYSYS documentation.

18 Using Models in Other Applications 381


19 Aspen Custom Modeler
Language File

Aspen Custom Modeler input files with the extension .acmf are ASCII text files
which are written out by Aspen Custom Modeler when you save a simulation.
.acmf files are intended to be accessed only by the Aspen Custom Modeler
program, and are not intended for direct editing by users of Aspen Custom
Modeler. In general we recommend that you do not edit these files directly.
Because the file is not intended for direct editing , if you do make direct
changes to a .acmf file this may result in the file no longer loading in to Aspen
Custom Modeler, and if it does not load there may be no explanatory error
messages to say why it does not load. It is also possible that your changes
may cause Aspen Custom Modeler to fail when you attempt to load the file.
Having said this, some users have found it useful to edit the file directly, and
this is possible if you are careful with the changes that you make. One
example where it is convenient to edit the file directly is in a global rename of
a block or stream. If many scripts, tasks and forms refer to a given block then
it can be tedious to change all of these references from within Aspen Custom
Modeler.
Another example is to remove a custom model that is being used with in the
flowsheet, to force Aspen Custom Modeler to use a version of this same
model that is included in a model library.
This chapter provides an overview of the contents of the Aspen Custom
Modeler Language file, looking at each of the main sections in turn. Where the
section name is shown in angle brackets (<>) this means the name is not
uses in the input file, it is just the name we are using to refer to the section in
this documentation.

19 Aspen Custom Modeler Language File 382


Version
Defines the version of Aspen Custom Modeler that was used to create the file.
Example:
Version "2004-0";

Libraries
Lists the ACM libraries to attach to this simulation. Libraries given without a
specified path will be searched for in the default library folder for the current
application, for example Program Files\AspenTech\AMSystem 2004.1\lib.
Example:
Libraries "Modeler.acml", "SystemLibrary.acml";

<Global Definitions>
This section contains definitions of assignments to global variables. Once a
global variable has been created by a Block or Stream in your simulation,
direct editing in the input file is the only way it can be removed or modified.
Example:
Pi AS RealVariable;
Pi.Spec : Fixed;
Pi : 3.142;

<Type Definitions>
Definitions of types which will appear in the custom modeling folder. These
can include Variables, Parameters, Ports, Stream types, Procedures, Models
and Structures. The syntax is documented in the ACM modelling language
documentation. Note that the order in which the types appear is important,
types must already have been defined before they can be used in other types.
For types which can own icons, forms or scripts a system section is included
giving the definition of these. These sections are marked with:-
//SYSTEM SECTION - WARNING: DO NOT EDIT

//SYSTEM SECTION END
As the text says, do not try to edit these sections. The END statement which
finishes the type appears after the //SYSTEM SECTION END line.
If you delete a type definition from this section ensure you delete everything
from the start of the type definition (for example “MODEL Reactor”) to and
including the line “end;”. Take care not to delete any types that are used in
the flowsheet or by other types, and which are not present elsewhere in a
library used by the simulation.

19 Aspen Custom Modeler Language File 383


<Plot and History Table Definitions>
These appear within the //SYSTEM SECTION markers. Although in general
you should not edit this section it can be useful to add form definitions
particularly when large numbers of variables are to be added such as on a
history table. To add a plot or history table add a form section starting with
<FORM NAME= and ending with </FORM>. This should be placed after the
<FORMLIST > statement but before the </FORMLIST> statement for the
model you want to edit. Take care that this is not in the context of an existing
form.
Example:
<FORMLIST DEFAULTFORM="TankResults">
<FORM NAME="TankResults" CLSID="{F6AD2450-A109-11D0-8B2F-
0A024E1AC0C}">
{ Version : 2
VariablesPaths : [ 1 h 11 FlowIn.flow 1 k 12
FlowOut.flow ]
}
</FORM>
</FORMLIST>
The list of variables for the plot or history table appears between the […] after
the VariablesPaths keyword. The number before each variable is the number of
characters in name. If your list of variables goes over more than 1 line ensure that each
new line starts with the length number. The order in this list is the order in which they will
appear on the form.

Flowsheet
This section defines the flowsheet content including what blocks, streams and
hierarchies are present and how they are connected; the flowsheet graphics;
any structure instances, and any user assignments to variables and
parameters.
The Flowsheet section can include any of the following:-

StructureContainer
This defines a structure container and its contents. There can be several
structure containers in a flowsheet. They contain instances of 1 or more
structure types.
Example:
StructureContainer Structures
StrInst1 as Struct1;
End

19 Aspen Custom Modeler Language File 384


<Blocks, Stream and Connection
Statements>
Defines what blocks and streams appears on the flowsheet and how they are
connected up. The syntax and rules of usage are the same as when these
statements are used within a model.
Example 1
Tank1 as Tank;
Tank2 as Tank;
FeedStream as Connection;
IS1 as Connection;
Connect Tank1.FlowIn with FeedStream;
Connect Tank1.FlowOut and Tank2.FlowIn with IS1;
Example 2 - Hierarchy connections
FLOWSHEET
Tank5 as Tank;
HIERARCHY Hier1
B1 as Tank;
S1 as input Connection;
Connect B1.FlowIn with S1;
END
IS5 as Connection;
Connect Tank5.FlowOut and input of Hier1.S1 with IS5;
END

CONSTRAINTS
This contains the flowsheet text which appears under the flowsheet folder in
the explorer. See Defining Flowsheet Constraints. for more information. The
section is terminated with an END statement.
Example:
CONSTRAINTS
// Flowsheet variables and equations...
END

Task <name>
Definition of flowsheet level tasks. See Using Task Statements for more
information. The section must be terminated with an END statement.
Example:

19 Aspen Custom Modeler Language File 385


Task SubTask1
Ramp(Tank1.flowin.flow, 3.0, 5.0);
End
As in models, the Flowsheet section contains a System section which contains
the definition of flowsheet level scripts, tasks and forms. You should not edit
the contents of this section.
//SYSTEM SECTION - WARNING: DO NOT EDIT

//SYSTEM SECTION END

ActiveTasks
This is a list of the Tasks that were active in your simulation when you saved
the file
Example:
ActiveTasks : ["FillTank", “StartPump”];

<Flowsheet Assignments>
Any assignments that you have made to the properties of variables or
parameters in any part of the flowsheet, including hierarchy blocks, are saved
in the flowsheet assignments list.
Example:
B1.Tank1.ComponentList : "Default";
B1.Tank1.D : 1.954283353193783;
B1.Tank1.FlowIn.Flow.Spec : Fixed;

Graphics
The graphics section contains information about the graphical layout of the
flowsheet or hierarchy block. This should not be edited. If you change the
flowsheet connectivity by deleting blocks or streams or by changing the way
existing connections are made in the ACM input file you should delete the
graphics section from the Graphics keyword to ENDTEXT as the graphics will
no longer be applicable to the flowsheet. Adding items is OK as the extra
items will be laid out automatically. If the graphics section is deleted
altogether all items in the simulation will be laid out automatically.

HIERARCHY <name>
Hierarchy definitions are contained in the Flowsheet definition section. A
hierarchy definition can contain anything a flowsheet definition contains
including hierarchies but excepting flowsheet assignments and structure
containers.
Flowsheet and Hierarchy definitions must end with an END statement.

19 Aspen Custom Modeler Language File 386


Properties
This section defines the physical properties package to be used for the
simulation. It is omitted if no physical properties package is used.
Example 1 - Define Aspen Properties file
Properties
Package : "Aprpdf";
WorkingDirectory : "E:\ACM13\Examples\";
RunID : "absorber.appdf";
Default as ComponentList;
Within Default
Components: ["BUTANE","ETHANE","METHANE"];
Option("OPSET") : "RK-SOAVE";
Option("FREE-WATER") : "STEAM-TA";
Option("TRUE-COMP") : "NO";
EndWithin
End
Examples 2 - Use Aspen Properties directly
Properties
Package : "PropertiesPlus";
DefinitionText : TEXT

ENDTEXT;
Default as ComponentList;
Within Default
Components :["C2H6","C3H8","CH4"];
EndWithin
End
The definition text between TEXT and ENDTEXT is the Properties Plus aprbkp
file text and should not be edited.
If WorkingDirectory is defined, and you move a properties package file to a
different location, you will need to edit the value of WorkingDirectory.
Alternatively you can delete this line and place the properties package in the
same folder as your .acmf file. The later is recommended because if you
move the two files together to another location you will not need to edit the
.acmf file again.

19 Aspen Custom Modeler Language File 387


Options
Contains values for all of the simulation options, as define on the Solver
Options, Run Options and Snapshots dialogs. Most of these are self
explanatory.
Example:
Options
AbsPerturb: 1.e-005;
AbsTearTol: 1.e-005;
AbsTol: 1.e-005;
ChangeTol: 1.e-005;
CheckProcDerivs: "Off";
Compression: False;
CurrentUOMSet: "Metric";
Decomposer.ProgID: "AspenTech.Decomposer";
Decomposition.MultipleGroup: True;
DerivAbsTol: 1.e-005;
DerivRelTol: 1.e-005;
EqnTol: 1.e-005;
EstimationPrintLevel: "Medium";
EstimationSolver: 2;
Estimator: 1;
ExplicitEventTolerance: 1.e-005;
Feasopt.MaxAbsStep: 10.;
Feasopt.MaxEval: 100;
Feasopt.MaxRelStep: 10.;
Feasopt.ObjFun: "Minimize";
Feasopt.OptTol: 1.e-004;
Gear.BoundCheck: "Track";
Gear.EventTol: 1.e-005;
Gear.HighestErrors: 0;
Gear.InitialStep: 0.;
Gear.JacUpdate: 0;
Gear.MaxCorIter: 5;
Gear.MaxCorSteps: 0;
Gear.MaximumStep: 0.;

19 Aspen Custom Modeler Language File 388


Gear.MinimumStep: 0.;
Gear.Reinit: "Save";
Homotopy.Bounded: True;
Homotopy.Delta: 0.1;
Homotopy.HomotopyEnabled: False;
Homotopy.HomotopyType: "Newton";
Homotopy.InitialStep: 0.1;
Homotopy.MaximumStep: 1.;
Homotopy.MaxIters: 5000;
Homotopy.MaxRelStep: 1.;
Homotopy.MinimumStep: 1.e-002;
Homotopy.OnlyOnFail: True;
Homotopy.RelErr: 1.e-004;
Homotopy.StepDecrement: 0.5;
Homotopy.StepIncrement: 10;
Homotopy.WeightJac: False;
Homotopy.Write: False;
ImpEuler.Step: 1.e-002;
Integration.AbsErrorTol: 1.e-005;
Integration.AbsTearTol: 1.e-005;
Integration.DiscontinuityEventTol: 1.e-005;
Integration.EnforceMinStep: False;
Integration.IncSensErrors: False;
Integration.InitStepSize: 5.e-003;
Integration.ItplToComTime: True;
Integration.LocateIEvents: False;
Integration.MaxOrder: 5;
Integration.MaxStepSize: 1.;
Integration.MinStepSize: 1.e-003;
Integration.ProgID: "AspenTech.UnifiedIntegrator";
Integration.RcvTornVars: False;
Integration.ReInitAfterEE: False;
Integration.ReInitAfterIE: False;
Integration.RelErrorTol: 1.e-005;
Integration.RelTearTol: 1.e-005;

19 Aspen Custom Modeler Language File 389


Integration.ShowHIErrors: 0;
Integration.ShowHTIErrors: 0;
Integration.StepRedFact: 0.5;
Integration.StepSize: 1.e-002;
Integration.StepSizeType: "Variable";
Integration.TestSAndAVars: False;
Integration.UsePrevAfterEE: False;
Integrator: "ImplicitEuler";
KeepCompiledEvaluationFiles: False;
LinearSolver: "MA48";
LogLikelihood.MaxIter: 100;
LogLikelihood.SolTol: 1.e-004;
MA48.DropTol: 0.;
MA48.PivotSearch: 3;
MA48.PivotTol: 0.;
MA48.ReanalyzeThreshold: 2.;
MA48.ReanalyzeWindow: 0;
MA48.Repivot: 0;
MA48.UseTranspose: 0;
MaxTearIter: 100;
Nl2sol.AbsFuncTol: 1.e-020;
Nl2sol.FalseConvTol: 0.;
Nl2sol.MaxIter: 50;
Nl2sol.RelFuncTol: 1.e-004;
Nl2sol.SolTol: 1.e-004;
NLASolver: "Standard";
Nonlinear.AbsPert: 1.e-005;
Nonlinear.BoundClip: 1.e-006;
Nonlinear.BoundFrac: 1.;
Nonlinear.ConvCrit: "Residual";
Nonlinear.Dogleg: False;
Nonlinear.HiResidual: 0;
Nonlinear.HiVarSteps: 0;
Nonlinear.MathsPrint: 0;
Nonlinear.MaxDivSteps: 10;

19 Aspen Custom Modeler Language File 390


Nonlinear.MaxFastNewtonSteps: 5;
Nonlinear.MaxIter: 100;
Nonlinear.MaxStepRed: 10;
Nonlinear.MaxVarStep: 50.;
Nonlinear.Method: "Newton";
Nonlinear.RangeFrac: 0.;
Nonlinear.SingPert: 1.e-002;
OptimizationPrintLevel: "Medium";
Optimizer: 1;
PrintLevel: 2;
PropInfo: -1;
RelPerturb: 1.e-005;
RelTearTol: 1.e-005;
RelTol: 1.e-005;
RunMode: "Dynamic";
SaveFreeVariableValues: True;
Scaling: False;
SensErrorCheck: True;
SnapshotSettings.EnableMaximum: False;
SnapshotSettings.EnableonReinitialization: False;
SnapshotSettings.EnableRegularSnapshot: False;
SnapshotSettings.Interval: 2.;
SnapshotSettings.Maximum: -1;
SnapshotSettings.SaveConvergedOnly: True;
SnapshotSettings.TakeAutoSnapshots: True;
SyncSteps: "Full";
Tearing: "none";
TearUpdate: "Direct";
TimeSettings.CommunicationInterval: 0.1;
TimeSettings.CommunicationUnits: "Hours";
TimeSettings.DisplayUpdateInterval: 2000;
TimeSettings.EnablePauseAt: False;
TimeSettings.EnableStepFor: False;
TimeSettings.PauseAt: 0.;
TimeSettings.RealTimeSyncFactor: 0.;

19 Aspen Custom Modeler Language File 391


TimeSettings.RecordHistory: True;
TimeSettings.StepFor: 0;
TimeSettings.TimeDisplayUnits: "Hours";
UseCompiledEvaluation: False;
UseSavedSnapshotOnLoad: True;
VSIE.AbsErrTol: 1.e-004;
VSIE.HighestErrors: 0;
VSIE.InitialStep: 0.1;
VSIE.Interpolation: True;
VSIE.MaxCorIter: 100;
VSIE.MaximumStep: 1.;
VSIE.MaxIncFact: 1.5;
VSIE.MinimumStep: 5.e-002;
VSIE.ReconvergeTorns: False;
VSIE.StepRedFact: 0.5;
VSIE.TearErrTol: 1.;
WatchGroup: 0;
WatchSubGroup: 0;
Wegstein.MaxAcceleration: 1000.;
Wegstein.MinAcceleration: -1000.;
OpenNLASolver: "";
OpenOPTSolver: "";
OpenESTSolver: "";
End

19 Aspen Custom Modeler Language File 392


Optimization
Contains values for all data entered on the Optimization dialog.
Example:
Optimization
IsDynamic : TRUE;
ElementSizeBoundsAutomatic : TRUE;
EndTime : 30;
Control.FinalTime_Initial : 30;
Control.FinalTime_IsFixed : TRUE;
Control.FinalTime_IsObjective : FALSE;
Control.Elements : 2;
Control.FixedInterval : TRUE;
Control.PiecewiseLinear : FALSE;
Control(0) : 2, 0.02, 4 ;
Control(1) : 2, 0.02, 4 ;
B1.CoolingRate : control;
Control(0).B1.CoolingRate : 0, 0, 1000;
Control(1).B1.CoolingRate : 0, 0, 1000;
Control.MaxMove.B1.CoolingRate : 1, FALSE;
B1.FeedRate : control;
Control(0).B1.FeedRate : 4, 0, 100;
Control(1).B1.FeedRate : 4, 0, 100;
Control.MaxMove.B1.FeedRate : 1, FALSE;
B1.Holdup_C : objective;
b1.temp : Dynamic, TRUE, TRUE, 1, 295, 300;
b1.temp@InteriorPoint(0) : TRUE, 1, 27, 5273;
End

19 Aspen Custom Modeler Language File 393


Estimation
Contains values for all data entered on the Estimation dialog.
Example:
Estimation
CalcHeteroParams : TRUE;
Reactor.RK1: 5;
Reactor.RK2: 1;
EXPERIMENT
Description: "experiment1";
Weight: 1;
IsDynamic: FALSE;
IsActive: TRUE;
Reactor.FLOW_IN("A"): 1,FIXED;
Reactor.FLOW_IN("B"): 9,FIXED;
Reactor.Output1.M("A"): 0.091887,1,-1,0;
Reactor.Output1.M("B"): 0.904,1,-1,0;
END
END

Homotopy
Contains values for all data entered on the Homotopy dialog.
Example:
Homotopy
Enabled: TRUE;
Reactor.FLOW_IN("A"): 6;
Reactor.FLOW_IN("A2B"): 1;
Reactor.FLOW_IN("B"): 0.5;
End

19 Aspen Custom Modeler Language File 394


SimulationAccessExtensions
Contains values for all data entered on the Simulation Access Extensions
dialog.
Example:
SimulationAccessExtension
CALL: SAXFunction;
LIBRARY: "C:\My Simulations\Modeler\SAX\phconsax";
EVENTS: After Step;
ENABLED: false;
OUTPUTS: {CST.Acid.flow};
End

Snapshot <name>
There is 1 snapshot section per kept snapshot. The name is internal and
should be unique in the input file. The Description is the name that you see in
the Snapshots dialog. The section is terminated with END.
Example:
snapshot snap1
// Start of Snapshot Header Information. Please don't
modify or move.
description : "Steady State";
solution_date : "27-04-2004 16:02:59";
Solution_Time :0.3 ;
Solution_Convergence :1 ;
Run_Number :1 ;
// End of Snapshot Header Information.
WITHIN global
Pi: 3.14200, FIXED;
ENDWITHIN;
WITHIN B1
WITHIN Tank1
Vol: 6.75000, FREE;

ENDWITHIN;
END

19 Aspen Custom Modeler Language File 395


19 Aspen Custom Modeler Language File 396
General Information

Copyright
Version Number: 2004.1
April 2005
Copyright © 1982-2005 Aspen Technology, Inc, and its applicable
subsidiaries, affiliates, and suppliers. All rights reserved. This Software is a
proprietary product of Aspen Technology, Inc., its applicable subsidiaries,
affiliates and suppliers and may be used only under agreement with
AspenTech.
Aspen ACOL™, Aspen Adsim®, Aspen Advisor™, Aspen Aerotran®, Aspen
Alarm & Event™, Aspen APLE™, Aspen Apollo Desktop™, Aspen Apollo
Online™, Aspen AssetBuilder™, Aspen ATOMS™, Aspen Automated Stock
Replenishment™, Aspen Batch Plus®, Aspen Batch.21™, Aspen BatchCAD™,
Aspen BatchSep™, Aspen Calc™, Aspen Capable-to-Promise®, Aspen
CatRef®, Aspen Chromatography®, Aspen Cim-IO for ACS™, Aspen Cim-IO
for Csi VXL™, Aspen Cim-IO for Dow MIF™, Aspen Cim-IO for G2™, Aspen
Cim-IO for GSE D/3™, Aspen Cim-IO for Hewlett-Packard RTAP™, Aspen Cim-
IO for Hitachi PLC (H04E)™, Aspen Cim-IO for Intellution Fix™, Aspen Cim-IO
for Melsec™, Aspen Cim-IO for WonderWare InTouch™, Aspen Cim-IO for
Yokogawa Centum CS™, Aspen Cim-IO for Yokogawa Centum XL™, Aspen
Cim-IO for Yokogawa EW3™, Aspen Cim-IO Interfaces™, Aspen Cim-IO
Monitor™, Aspen Cim-IO™, Aspen Collaborative Demand Management™,
Aspen Collaborative Forecasting™, Aspen Compliance.21™, Aspen
COMThermo TRC Database™, Aspen COMThermo®, Aspen Cost Factor
Manual™, Aspen Crude Manager™, Aspen Crude Margin Evaluation™, Aspen
Custom Modeler®, Aspen Data Source Architecture™, Aspen Decision
Analyzer™, Aspen Demand Manager™, Aspen DISTIL™, Aspen Distribution
Scheduler™, Aspen DMCplus® Composite, Aspen DMCplus® Desktop, Aspen
DMCplus® Online, Aspen DPO™, Aspen Dynamics®, Aspen eBRS™, Aspen
Enterprise Model™, Aspen ERP Connect™, Aspen FCC®, Aspen FIHR™, Aspen
FLARENET™, Aspen Fleet Operations Management™, Aspen Framework™,
Aspen FRAN™, Aspen Fuel Gas Optimizer Desktop™, Aspen Fuel Gas
Optimizer Online™, Aspen General Construction Standards™, Aspen Hetran®,
Aspen HX-Net®, Aspen Hydrocracker®, Aspen Hydrotreater™, Aspen HYSYS
Amines™, Aspen HYSYS Crude™, Aspen HYSYS Dynamics™, Aspen HYSYS
OLGAS 3-Phase™, Aspen HYSYS OLGAS™, Aspen HYSYS OLI Interface™,
Aspen HYSYS Tacite™, Aspen HYSYS Upstream Dynamics™, Aspen HYSYS
Upstream™, Aspen HYSYS®, Aspen Icarus Process Evaluator®, Aspen Icarus

General Information 397


Project Manager®, Aspen InfoPlus.21®, Aspen Inventory Balancing™, Aspen
IQ Desktop™, Aspen IQ Online™, Aspen IQmodel Powertools™, Aspen
Kbase®, Aspen LIMS Interface™, Aspen Local Security™, Aspen LPIMS™,
Aspen MBO™, Aspen MIMI®, Aspen MPIMS™, Aspen Multivariate Server™,
Aspen MUSE™, Aspen NPIMS™, Aspen OnLine®, Aspen Operations Manager -
Event Management™, Aspen Operations Manager - Integration
Infrastructure™, Aspen Operations Manager - Peformance Scorecarding™,
Aspen Operations Manager - Role Based Visualization™, Aspen Order Credit
Management™, Aspen Orion Planning™, Aspen Orion™, Aspen PEP Process
Library™, Aspen PIMS Blend Model Library™, Aspen PIMS Distributed
Processing™, Aspen PIMS Enterprise Edition™, Aspen PIMS Mixed Integer
Programming™, Aspen PIMS Simulator Interface™, Aspen PIMS Solution
Ranging™, Aspen PIMS Submodel Calculator™, Aspen PIMS XNLP
Optimizer™, Aspen PIMS™, Aspen PIPESYS™, Aspen PIPE™, Aspen Planning
Accuracy™, Aspen Plant Planner & Scheduler™, Aspen Plant Scheduler Lite™,
Aspen Plant Scheduler™, Aspen Plus OLI Interface™, Aspen Plus®, Aspen
Polymers Plus®, Aspen PPIMS™, Aspen Process Data™, Aspen Process
Explorer™, Aspen Process Manual™, Aspen Process Order™, Aspen Process
Plant Construction Standards™, Aspen Process Recipe®, Aspen Process
Tools™, Aspen Product Margin & Blending Evaluation™, Aspen Production
Control Web Server™, Aspen ProFES® 2P Tran, Aspen ProFES® 2P Wax,
Aspen ProFES® 3P Tran, Aspen ProFES® Tranflo, Aspen Properties®, Aspen
Pumper Log™, Aspen Q Server™, Aspen RateSep™, Aspen RefSYS
CatCracker™, Aspen RefSYS Spiral™, Aspen RefSYS™, Aspen Report Writer™,
Aspen Resource Scheduling Optimization™, Aspen RTO Watch Cim-IO
Server™, Aspen RTO Watch Server™, Aspen Scheduling & Inventory
Management™, Aspen SmartStep Desktop™, Aspen SmartStep Online™,
Aspen SQLplus™, Aspen Supply Chain Analytics™, Aspen Supply Chain
Connect™, Aspen Supply Planner™, Aspen Tank Management™, Aspen TASC-
Mechanical™, Aspen TASC™, Aspen Teams®, Aspen Terminals
Management™, Aspen TICP™, Aspen Transition Manager™, Aspen Turbo
PIMS™, Aspen Utilities™, Aspen Voice Fulfillment Management™, Aspen
Watch Desktop™, Aspen Watch Server™, Aspen Water™, Aspen Web
Fulfillment Management™, Aspen WinRace Database™, Aspen XPIMS™,
Aspen Zyqad Development Version™, Aspen Zyqad™, SLM™, SLM
Commute™, SLM Config Wizard™, the aspen leaf logo, and Plantelligence are
trademarks or registered trademarks of Aspen Technology, Inc., Cambridge,
MA.
All other brand and product names are trademarks or registered trademarks
of their respective companies.
This document is intended as a guide to using AspenTech's software. This
documentation contains AspenTech proprietary and confidential information
and may not be disclosed, used, or copied without the prior consent of
AspenTech or as set forth in the applicable license.

Corporate
Aspen Technology, Inc. Phone: (1) (617) 949-1000
Ten Canal Park Toll Free: (1) (888) 996-7001
Cambridge, MA 02141-2201 Fax: (1) (617) 949-1030
USA URL: http://www.aspentech.com

General Information 398


Related Documentation
Title Content
Aspen Custom Modeler 2004.1 Getting Started Contains basic hands-on tutorials to
Guide help you become familiar with Aspen
Custom Modeler.
Aspen Custom Modeler 2004.1 Examples Guide Contains a general overview of ACM
functionality and more complex and
extensive examples of using Aspen
Custom Modeler.

Aspen Custom Modeler 2004.1 Library Contains reference information on


Reference control models, property procedure
types, utility routines, port types, and
variable types.

Aspen Custom Modeler 2004.1 DMCplus® Contains information on using


Controllers Interface DMCplus with Aspen Custom Modeler
or Aspen Dynamics™.

Aspen Custom Modeler 2004.1 Polymer Polymers Plus is a layered product of


Simulations with Polymers Plus Aspen Custom Modeler. It provides
additional functionality to the
properties package, Properties Plus,
enabling polymers to be fully
characterized in Aspen Custom
Modeler models.

General Information 399


Technical Support

Online Technical Support


Center
AspenTech customers with a valid license and software maintenance
agreement can register to access the Online Technical Support Center at:
http://support.aspentech.com
You use the Online Technical Support Center to:
• Access current product documentation.
• Search for technical tips, solutions, and frequently asked questions
(FAQs).
• Search for and download application examples.
• Search for and download service packs and product updates.
• Submit and track technical issues.
• Search for and review known limitations.
• Send suggestions.
Registered users can also subscribe to our Technical Support
e-Bulletins. These e-Bulletins proactively alert you to important technical
support information such as:
• Technical advisories.
• Product updates.
• Service Pack announcements.
• Product release announcements.

Technical Support 400


Phone and E-mail
Customer support is also available by phone, fax, and e-mail for customers
who have a current support contract for their product(s). Toll-free charges are
listed where available; otherwise local and international rates apply.
For the most up-to-date phone listings, please see the Online Technical
Support Center at:
http://support.aspentech.com

Support Centers Operating Hours


North America 8:00 – 20:00 Eastern time
South America 9:00 – 17:00 Local time
Europe 8:30 – 18:00 Central European time
Asia and Pacific Region 9:00 – 17:30 Local time

Technical Support 401


Index

Application.Msg() 47
A Application.Name 44
Absolute Checking Tolerance 177 Application.NewDocument() 48
Absolute Equation Tolerance 182 Application.OpenDocument() 48
Absolute Integration Error Tolerance 194 Application.Path 44
Absolute Perturbation 216 Application.Quit() 49
Absolute tear tolerance 181 Application.Restore() 49
Absolute variable tolerance 182 Application.SaveDocument() 49
Active set initialization parameters (DMO) Application.SaveDocumentAs() 50
specifying 248 Application.Simulation 57
Active set initialization parameters (DMO): 248 Application.StatusBar 45
ActiveDocument.Application 51 Application.Top 45
ActiveDocument.CloseAllForms 53 Application.Version 45
ActiveDocument.CreateLibrary 54 Application.Visible 45
ActiveDocument.FullName 52 Application.Width 45
ActiveDocument.Name 52 Applications
ActiveDocument.Parent 52 automation for 42
ActiveDocument.Saved 53 Asynchronous runs 169
ActiveDocument.SaveDocument 54 available 401
ActiveDocument.SaveDocumentAs 54
B
Application.Activate() 47
Application.ActiveDocument 43 BeginLongOperation method 108
Application.Caption 43 Blocks
Application.CloseDocument() 47 automation for 61, 95, 99
Application.DefaultFilePath 43
Application.FullName 43
C

Application.Height 43 CACSD packages 314


Application.Interactive 44 CDI
Application.Left 44 automation for 150
Application.Maximize() 47 overview 314
Application.Minimize() 47 Check Procedure Derivatives 177

Index 402
CHEMISTRY physical properties calculation locating 197
option 254
Disturbances
Clip Factor 217
locating 197
Component lists
DMO Adv form
automation for 81
QP2 sheet 248
ComponentList.Components 81
Search sheet 244
ComponentList.IsComponentSet 82
DMO Adv form: 244, 248
ComponentList.Name 82
DMO Basic form
ComponentList.Option 83
Basic sheet 231
ComponentList.OptionNames 83
Report sheet 240
Control Design Interface, overview 314
DMO Basic form: 231, 240
Control Panel output: 240
DMO maximum number of allowed iterations
Controllers
changing 231
deleting 360
DMO maximum number of allowed iterations:
Convergence Criterion 213 231
ConvertToBaseUOM and ConvertFromBaseUOM DMO objective function convergence tolerance
methods 127
changing 231
CreateObject Visual Basic command 30
DMO objective function convergence tolerance:
CreateScript method 112 231
CreateTask method 111 DMO residual convergence tolerance
Creep mode (DMO) changing 231
using 243 DMO residual convergence tolerance: 231
Creep mode (DMO): 243 DMO solver 235
applying a trust region 244
D changing parameters 231
Data servers 343 creep mode 243
DeleteScript method 112 handling infeasible solutions 235
DeleteTask method 112 handling singularities 236
Deleting scaling 235
controllers 360 troubleshooting 234
Derivative calculations variable bounding 237
Check Procedure Derivatives option 177 DMO solver parameters
Diagnostic information active set initialization 248
Non-Linear Solver tab 214 control panel report 240
Solver Reporting Level 176 creep mode 243
Direct convergence method 180 micro-infeasibility handling 247
DisableIncrementalUpdate command 24 trust region 244, 245
DisableIncrementalUpdate method 107 DMO solver parameters: 231, 240, 243, 244,
246, 248
Discontinuities

Index 403
DMO solver: 230, 231, 234, 235, 236, 237, modifying 364
243, 244
Exporting
Dogleg Method 214
flowsheets to Aspen Plus 359
Drop Tolerance
to Aspen Plus 352, 367
MA28 212
External data, accessing 343
MA48 205
External programs
calling from scripts 23
E

EditScript method 112 F


EditTask method 112
Fast Newton 212, 214
Eliminate Equivalence Equations 185
Files 231
EnableIncrementalUpdate command 25
DMO active bounds report (*.atact) 231
EnableIncrementalUpdate method 107
EO solver report (*.atslv) 231
EndLongOperation method 108
FindMatchingVariables method 104
Entry point routines 266
Flowsheets
EO convergence 235
automation for 110
DMO solver 230, 231
exporting Aspen Dynamics to Aspen Plus
DMO solver problems 234 359
scaling objective function 235 Forms
EO convergence: 230, 234 displaying using automation 108
EO solver report FREE-WATER physical properties calculation
option 254
DMO 231
DMO basic iteration information 232
G
DMO constrained variables 233
Gear 196, 199
DMO general iteration information 233
General option, Non-Linear Solver tab 212
DMO largest unscaled residuals 232
General tab, Solver Properties dialog box 175
DMO problem information 232
Generalized Physical Properties Interface
DMO shadow price 233
routines 261
nonlinearity ratios (DMO): 234
GetObject Visual Basic method 35
EO solver report: 231, 232, 233, 234
Getpath method 97
Equation group
GetPath method 128
defining for diagnostics 176
GetScriptText method 112
Equivalence equations 185
GetTaskText method 112
Estimation simulations
GetVariableValues method 104
accessing results 164
Global method 106
modeling language for 158
GPPI routines 261
solver options 220
Event Tolerance 197
Exported flowsheets

Index 404
H IsStateVariable method 129

HENRY-COMPS physical properties calculation J


option 255
Highest errors 196 Jacobian Update Policy 197, 200

Highest Residuals 215


K
Highest Variable Steps 215
History KBASE physical properties calculation option
257
automation method 120, 121
Keep Solution within Bounds 198
Homotopy
automation for 135
L
Homotopy simulations 219
LaunchCustomFormView method 108
Hybrid 212
LaunchFormView method 108
I LaunchLibraryFormView method 108
Least squares option 220
Implicit Euler 191, 192
Linear Solver tab, overview 205
Indeterminate variables 196, 199
Linear solvers
Initial Integration Step
MA28 212
Gear 196, 200
MA48 205
Integerset collection object 119
Log file 176
Integration step
Gear 197
M
Integration Step
MA28 212
Euler 191
MA48 205
Implicit Euler 191
MATLAB 314
VSIE 193
Maximum Approach to Bound 216
Integrator tab, overview 187
Maximum Corrector Iterations
Integrators
Gear 198
differences between 187
VSIE 195
Gear 196, 199
Maximum Divergent Steps 213
Implicit Euler 191, 192
Maximum Eigenvalue 181
VSIE 193
Maximum Fast Newton Steps 214
Invoke method 108
Maximum Integration Step
IsAlgebraicVariable method 128
Gear 197
IsControlSignal method 113
VSIE 193
IsHidden method 129
Maximum Iterations 214
IsInput method 129
Maximum log likelihood option 223
IsOutput method 129
Maximum Number of Tear Iterations 182
IsParameter method 129
Maximum Range Fraction 215

Index 405
Maximum Step Increment Factor 194 overview 343
Maximum Step Reductions 214 Online links variable object
Maximum Variable Step 216 automation 148
MAXIT physical properties calculation option Open NLP - full space 229
257
Open NLP - reduced 229
Method, non-linear solver 212
Open non-linear algebraic equation solvers
Micro-infeasibility handling (DMO) 218, 351
using 246 OPSET physical properties calculation option
254
Micro-infeasibility handling (DMO): 246
Optimization simulations
Minimum Eigenvalue 181
automation for 137
Minimum Integration Step
OutputLogger.ClearWindow() 87
Gear 197
OutputLogger.FileOutput 84
VSIE 193
OutputLogger.Height 85
Morari Resiliency Index 317
OutputLogger.Left 85
MRI 317
OutputLogger.MessageCount 85
N OutputLogger.Messages 85
OutputLogger.MessageText 86
Name method 97, 129
OutputLogger.Path 86
Nelder-Mead Direct Search Solver 226
OutputLogger.Print() 87
Initial simplex 227
OutputLogger.ScreenOutput 86
Maximum iterations 227
OutputLogger.Top 86
Number of restarts 227
OutputLogger.Width 86
Optimization tolerance 227
OutputLogger.WriteFileHeader() 87
Newton 212
NI 317 P
Niederlinski Index 317
Parent method 129
NL2SOL 229
pGibbs_Mol_Liq 303
Non-linear solvers
pGibbs_Mol_Vap 305
Non-Linear Solver tab 212
Physical properties
Numerical Derivative Absolute and Relative
Perturbation 183 entry point routines 266
GPPI routines 261
O installing the physical properties interface
313
objective function 235
subroutines for property procedure types
changing the scale 235 274
OLL Pivot Tolerance 205
overview 343 Ports
Online links automation for 103, 116
automation 143

Index 406
Print Linear Algebra for Groups of Size Greater Results.FindSnapshot() 92
than or Equal to 215
Results.GetResult() 92
Procedures
Results.GetSnapshot() 92
tearing 178
Results.GetSnapshot().Converged 92
Properties
Results.GetSnapshot().DateTime 93
automation for 68, 79
Results.GetSnapshot().Description 93
Properties Plus
Results.GetSnapshot().Export 93
calculation options for 253
Results.GetSnapshot().ExportasBinary 94
Properties Reporting Level 176
Results.GetSnapshot().RunNumber 94
Properties.AddComponentList() 80
Results.GetSnapshot().SimulationTime 94
Properties.ComponentList 79
Results.Import() 94
Properties.ComponentListNames 79
Results.Interval 88
Properties.LoadPropertiesFile() 80
Results.Limit 88
Properties.RemoveComponentList() 81
Results.Refresh() 94
Property method 129
Results.RegularSnapshot 89
Results.ResultCount 89
R
Results.Rewind() 95
RealVariables methods 133
Results.SnapshotCount 89
Re-analyze FLOPS Window Size 206
Results.TakeSnapshot() 95
Re-Analyze Threshold 205
RETENTION physical properties calculation
Reconverge Torn Variables 195 option 258
Recorded history of variables 120, 121 RGA 316
Re-initialization Method 198
S
Relative Checking Tolerance 177
Relative Gain Array 316 SAX, overview 332
Relative tear tolerance 181 Scaling 184
Relative variable tolerance 182 Scripts
RemoveControllers script 360 basic examples 22
Re-pivot every n Factorizations 206 calling external applications 23
Reports 231 improving the speed of 24
DMO active bound 231 invoking 106
EO solver report syntax for 21
DMO 231 Sensitivities 73, 75
Reset method 130 Server Busy dialog box 108
Resolve method 97 Set attributes 119
Results.AutoSnapshot 89 Show Highest Corrector Steps 198
Results.CopyValues() 90 Show Highest Integration Errors 195, 196
Results.Delete() 91 Simulation Access eXtensions, overview 332
Results.FindResult() 92 Simulation Messages window

Index 407
automation for 84 Simulation.State 69
controlling level of detail in 176 Simulation.Step() 79
Simulation.AddSensitivityParameter() 73 Simulation.Successful 70
Simulation.AddSensitivityVariable() 73 Simulation.Termination 71
Simulation.ClearSensitivities() 73 Simulation.Time 71
Simulation.Correlation 58 Simulation.Variables 71
Simulation.CorrelationMatrix 58 Simulations
Simulation.CorrelationMatrixPresent 59 accessing estimation results 164
Simulation.Covariance 59 automation for 57
Simulation.CovarianceMatrix 59 estimation modeling language 158
Simulation.CovarianceMatrixPresent 59 Singularity Perturbation 216
Simulation.CreateLibrary() 74 Snapshots
Simulation.Degrees 59 automation for 88
Simulation.DeviationArrayPresent 60 SOLU-WATER physical properties calculation
option 256
Simulation.DisableSensitivities() 75
Solver properties
Simulation.DisplayTime 60
for Estimation runs 220
Simulation.EnableSensitivities() 75
Solver Reporting Level
Simulation.EndStepCount 60
described 176
Simulation.EndTime 60
Solver Scaling 184
Simulation.Equations 61
Solver Searches n Columns for Pivots 206, 207
Simulation.EstimationRunState 61
Speed of simulation
Simulation.Flowsheet 61
Euler 191
Simulation.FullName 62
Implicit Euler 191
Simulation.GetSensitivityValue 75
SRQP solver 228
Simulation.Interrupt() 76
Feasibility improvements 228
Simulation.LaunchFormView 76
Hessian scaling 228
Simulation.Name 62
Maximum iterations 229
Simulation.Options... 62
Optimization tolerance 229
Simulation.Pause() 76
Print level 229
Simulation.Properties 68
Variable initialisation policy 229
Simulation.Reset() 77
State Transition Matrix 317
Simulation.ResetEstimation() 77
STM 317
Simulation.Restart() 77
Streams
Simulation.Results 68
automation for 101, 113
Simulation.Run() 77
Stringset collection object 119
Simulation.RunMode 68
Synchronous runs 169
Simulation.RunNumber 68
Simulation.Saved 69
Simulation.SpecState 69

Index 408
T W

Tasks Watch Group 176


automation for 134 Watch Torn Sub-Group 177
Tear Integration Error Tolerance 194 Wegstein convergence method 180
Tear Update Strategy 180 WorkingFolder 46
Tearing
Solver Options dialog box 178
Time history of variables 120, 121
TOLERANCE physical properties calculation
option 257
Tolerances
absolute and singularity perturbation 216
absolute equation tolerance 182
General tab in Solver Properties dialog box
182
Maximum Variable Step 216
Non-Linear Solver tab 215
tear 181
variable 182
variable change 183
TRUE-COMP physical properties calculation
option 255
Trust region (DMO)
applying 244
Trust region (DMO): 244
TypeName method 97, 130

UpdateVariables method 105


Use Interpolation 195

ValidValues method 130


Variable Change Tolerance 183
Variable object 118
Variable.Units 118
Variables
automation for 118
VSIE integrator 193

Index 409
Index 410

Você também pode gostar